diff --git "a/3636.jsonl" "b/3636.jsonl" new file mode 100644--- /dev/null +++ "b/3636.jsonl" @@ -0,0 +1,726 @@ +{"seq_id":"406840240","text":"from flask import Flask, render_template, send_from_directory\n\napp = Flask(__name__)\n\n# DEMO STUFF\n\n@app.route('/')\ndef view_hello():\n return 'Hello World!'\n\n@app.route('/demo-1')\ndef view_demo_1():\n return render_template('demo-1.html', name='Justin')\n\n@app.route('/demo-2/')\ndef view_demo_2(name):\n return render_template('demo-1.html', name=name)\n\n@app.route('/demo-3')\ndef view_demo_3():\n names = ['Alice', 'Bob', 'Charlie']\n return render_template('demo-3.html', salutation='Roll call', names=names)\n\n# STUDENT DIRECTORY APP\n\nclass Student:\n def __init__(self, first_name, last_name, username, majors, advisor):\n self.first_name = first_name\n self.last_name = last_name\n self.username = username\n self.majors = majors\n self.advisor = advisor\n\ndef get_data():\n students = []\n with open('students.csv') as fd:\n for line in fd.read().splitlines():\n name, username, majors, advisor = line.split('\\t')\n last_name, first_name = name.split(', ')\n students.append(Student(first_name, last_name, username, majors, advisor))\n return sorted(students, key=(lambda s: s.username))\n\n@app.route('/directory')\ndef view_directory():\n student_list = get_data()\n return render_template('directory.html', students=student_list)\n\n\n@app.route('/directory/')\ndef view_student(username):\n student_list = get_data()\n current_student = None\n index = 0\n\n for i in range(0, len(student_list)):\n if student_list[i].username == username:\n current_student = student_list[i]\n index = i\n break\n\n if index == 0:\n prev_student = student_list[len(student_list)-1]\n next_student = student_list[1]\n elif index == len(student_list)-1:\n prev_student = student_list[index-1]\n next_student = student_list[0]\n else:\n prev_student = student_list[index-1]\n next_student = student_list[index+1]\n\n return render_template('student.html', student=current_student, prev_student=prev_student, next_student=next_student)\n\n# DON'T TOUCH THE CODE BELOW THIS LINE\n\n@app.route('/css/')\ndef view_css(file):\n return send_from_directory('css', file)\n\nif __name__ == '__main__':\n #print(get_data())\n app.run(debug=True)\n","sub_path":"flask-app.py","file_name":"flask-app.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"501697251","text":"\"\"\"\nfrom datetime import date,timedelta\nfromdate = date(2020,1,1)\ntodate = date(2020,1,1)\ndaygenerator = (fromdate + timedelta(x) for x in range((todate - fromdate).days+1))\ntmp=sum(1 for day in daygenerator if day.weekday() < 5)\nprint(tmp)\n\"\"\"\nfrom datetime import datetime,timedelta\n\nf=open('input.txt')\nf1=open('output.txt','w')\ntry:\n day=f.read().split()\n c=0\n n=day[0]\n n1=day[1]\n start=datetime(int(n[-4:]),int(n[3:5]),int(n[0:2]))\n end=datetime(int(n1[-4:]),int(n1[3:5]),int(n1[0:2]))\n \n if startdatetime(2019,12,30) and end>datetime(2019,12,30):\n daygenerator = (start + timedelta(x) for x in range((end - start).days+1))\n c=sum(1 for day in daygenerator if day.weekday() < 5)\n f1.write(str(c))\n else:\n f1.write('invalid')\nexcept Exception as e:\n f1.write(str(e))\n\nf.close()\nf1.close()\n\n\n#sir solution\n\"\"\"\nfrom datetime import *\nf=open('input.txt')\ny=f.readline()\nl1,m1=map(str,y.split(\" \"))\nf.close()\nl=list(map(int,l1.split(\"/\")))\nm=list(map(int,m1.split(\"/\")))\nvalid = True\ntry :\n datetime(l[2],l[1],l[0])\n datetime(m[2],m[1],m[0])\nexcept ValueError :\n valid = False\nif(valid) :\n time1=datetime(l[2],l[1],l[0])\n time2=datetime(m[2],m[1],m[0])\n time3=datetime(2019,12,30)\n n=(time2-time1).days\n c=0\n if(time2>=time1 and time1>=time3):\n f1=time1.weekday()\n for i in range(1,n+2):\n if(f1!=5 and f1!=6):\n c+=1\n if(f1!=6):\n f1+=1\n else:\n f1=0\n out=str(c)\n else:\n out=\"Invalid\"\nelse:\n out=\"error\"\nff=open(\"output.txt\",\"w\")\nff.write(out)\nff.close()\n\"\"\"\n","sub_path":"csi_round2.py","file_name":"csi_round2.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"573147548","text":"import os\r\nimport random\r\nimport torch\r\nimport numpy as np\r\nfrom torch.utils.data import DataLoader\r\nfrom torchvision import transforms\r\nfrom steer_net.steerNet import SteerNet\r\nfrom steer_net.steerDS import SteerDataSet\r\nfrom steer_net.train_model import train_model\r\nfrom matplotlib import pyplot as plt\r\n\r\n\r\nif __name__ == '__main__':\r\n batch_size = 32\r\n num_epochs = 35\r\n lr = 0.002 # learning rate\r\n seed = 1234 \r\n classes = ['left2', 'left1', 'straight', 'right1', 'right2']\r\n resize_size = 84\r\n out_dir = os.path.join('trained_models', str(random.randint(0, 100000)))\r\n use_cuda = torch.cuda.is_available()\r\n\r\n # Initialize random seed.\r\n torch.manual_seed(seed)\r\n if use_cuda:\r\n torch.cuda.manual_seed(seed)\r\n\r\n # Create output directory.\r\n if not os.path.exists(out_dir):\r\n os.makedirs(out_dir)\r\n else:\r\n exit('Folder already exists')\r\n\r\n device = torch.device('cuda' if use_cuda else 'cpu')\r\n\r\n # Data transformation.\r\n data_transf = transforms.Compose([\r\n transforms.ToTensor(),\r\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\r\n ])\r\n\r\n # Specify training and validation data and prepare it for loading.\r\n data = {x: SteerDataSet('dev_data/{0}_data'.format(x),\r\n img_ext='.jpg',\r\n classes=classes,\r\n transform=data_transf,\r\n resize=resize_size)\r\n for x in ['train', 'val']}\r\n data_loaders = {x: DataLoader(data[x], batch_size=batch_size, num_workers=4)\r\n for x in ['train', 'val']}\r\n\r\n print('output dir = ' + out_dir)\r\n print('use cuda = ' + str(use_cuda))\r\n\r\n # Load model and move it to device (cpu or gpu)\r\n model = SteerNet(len(classes))\r\n model.to(device)\r\n\r\n # Specify optimiser.\r\n optimizer = torch.optim.Adamax(model.parameters(), lr=lr, weight_decay=1e-4)\r\n\r\n # Train model, get best model weights and validation statistics. \r\n best_model, val_loss_history, val_acc_history = train_model(model,\r\n data_loaders,\r\n optimizer,\r\n num_epochs,\r\n device)\r\n\r\n # Move model to cpu, because robot doesn't have gpu, and save it.\r\n best_model.to('cpu')\r\n model_path = os.path.join(out_dir, 'best_model.pt')\r\n torch.save(best_model.state_dict(), model_path)\r\n \r\n # Save validation loss values to text file.\r\n val_loss_path = os.path.join(out_dir, 'val_loss.txt')\r\n with open(val_loss_path, 'w') as f:\r\n f.writelines(['{}\\n'.format(v) for v in val_loss_history])\r\n\r\n # Save validation accuracy values to text file.\r\n val_acc_path = os.path.join(out_dir, 'val_acc.txt')\r\n with open(val_acc_path, 'w') as f:\r\n f.writelines(['{}\\n'.format(v) for v in val_acc_history])\r\n\r\n # Save all parameters to text file.\r\n params_path = os.path.join(out_dir, 'params.txt')\r\n with open(params_path, 'w') as f:\r\n params = []\r\n params.append('seed: {}\\n'.format(seed))\r\n params.append('batch_size: {}\\n'.format(batch_size))\r\n params.append('num_epochs: {}\\n'.format(num_epochs))\r\n params.append('lr: {}\\n'.format(lr))\r\n params.append('classes: {}\\n'.format(classes))\r\n params.append('resize_size: {}\\n'.format(resize_size))\r\n params.append('optimizer: {}\\n'.format(optimizer.__str__()))\r\n f.writelines(params)\r\n\r\n # Plot validation statistics and save plot to file.\r\n plt.plot(val_loss_history, 'r', label='Loss')\r\n plt.plot(val_acc_history, 'b', label='Accuracy')\r\n acc_max = np.argmax(val_acc_history)\r\n plt.plot(acc_max, val_acc_history[acc_max].item(), 'k.',\r\n label=str(val_acc_history[acc_max].item()))\r\n plt.legend()\r\n plt.savefig(os.path.join(out_dir, 'plot.png'))\r\n plt.show()\r\n","sub_path":"on_laptop/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"364515451","text":"import gevent\nimport re\nimport socket\nfrom gevent import monkey\nimport mini_web\nimport sys\nmonkey.patch_all()\n\n\nclass Service(object):\n def __init__(self,port):\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.socket.bind((\"\", port))\n self.socket.listen(128)\n\n def start(self):\n while True:\n client_socket, client_addr = self.socket.accept()\n print(\"连接成功\", client_addr)\n gevent.spawn(self.run, client_socket)\n\n @staticmethod\n def run(client_socket):\n client_socket_recv = client_socket.recv(4096)\n msg = client_socket_recv.decode('utf-8')\n if msg:\n path = re.search('/.+? $', msg).group()\n print('地址为', path)\n open_path, state = mini_web.logic(path)\n try:\n with open(open_path, 'rb') as f:\n response_body = f\n except Exception as e:\n print(\"异常\", e)\n return\n else:\n response_line = \"HTTP/1.1 %s\" % state\n response_head = \"content-type:text/html;charset=utf8\\r\\n\"\n content = response_line.encode('utf-8') + response_head.encode('utf-8') +'\\r\\n'.encode('utf-8') +response_body\n client_socket.send(content)\n finally:\n client_socket.close()\n\n\ndef main():\n if len(sys.argv) != 2:\n print(\"启动命令为\")\n return\n elif not sys.argv[1].isdigit:\n print(\"启动命令为\")\n return\n port = int(sys.argv[1])\n service = Service(port)\n service.start()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"html服务器带命令行指令.py","file_name":"html服务器带命令行指令.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"300491051","text":"list = ['star', 'sky', 'apple', 'lemon', 'sky', 'sky', 'lemon', 'star', 'star', 'star']\r\nf = [None] * len(list)\r\nx = -1\r\n\r\nfor i in range(0, len(list)):\r\n count = 1\r\n for j in range(i + 1, len(list)):\r\n if (list[i] == list[j]):\r\n count += 1\r\n f[j] = x\r\n\r\n if (f[i] != x):\r\n f[i] = count\r\n\r\nprint(\" WORD - Frequency\")\r\nfor i in range(0, len(f)):\r\n if (f[i] != x):\r\n print(\" \" + str(list[i]) + \" - \" + str(f[i]))","sub_path":"Problem1.py","file_name":"Problem1.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"653827972","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport copy\nimport abc\nfrom structure import CrystalStructure\nfrom psp import pseudolist_from\nfrom algo import *\nfrom strategy import *\nfrom task import *\n\n########################################\n# Utility Functions for Handling Task Generator\n########################################\n\ndef copy_taskgen(taskgen, name, workdir):\n c = copy.copy(taskgen)\n c.name = name\n c.workdir = workdir\n return c\n\n########################################\n# Task Generators\n########################################\n\nclass TaskGenerator(object):\n \"\"\" Base class for task generator.\n Task generator can absorb all calculation condition and\n easily generate a task that reflects those.\n \"\"\"\n __metaclass__ = abc.ABCMeta\n\n gentype = \"base\"\n def __init__(self, name, workdir):\n self.name = name\n self.workdir = workdir\n\n @abc.abstractmethod\n def strategy(self):\n pass\n\n def gentask(self, deps=None):\n return gen_task(self.gentype, self.name, self.strategy(), self.workdir, gen_task_manager(), deps)\n\nclass ScfTaskGenerator(TaskGenerator):\n \"\"\" Helper class for creation of a scf task\n \"\"\"\n gentype = \"scf\"\n\n def __init__(self, name, workdir, ciffile, pspfiles, ksampling={},\n elc_alg={}, scf_alg={}, u_alg={}, accuracy=\"normal\", opt_algs={}):\n super(ScfTaskGenerator, self).__init__(name, workdir)\n if ciffile.endswith(\".cif\"):\n self.cs = CrystalStructure.fromcif(ciffile)\n else:\n self.cs = CrystalStructure.fromcif(ciffile, isfile=False)\n self.psplist = pseudolist_from(pspfiles)\n self.ksampling = ksampling_helper(self.cs, **ksampling)\n self.elc_alg = electrons(**elc_alg)\n self.scf_alg = scf_algorithm(**scf_alg)\n self.u_alg = u_algorithm(self.cs, **u_alg)\n self.accuracy = accuracy\n self.opt_algs = opt_algs_helper(**opt_algs)\n\n def strategy(self):\n if self.u_alg not in self.opt_algs:\n self.opt_algs.append(self.u_alg)\n return scf_strategy(self.cs, self.psplist, self.ksampling, self.elc_alg,\n self.scf_alg, self.accuracy, self.opt_algs)\n\nclass RelaxTaskGenerator(ScfTaskGenerator):\n gentype = \"relax\"\n\n def __init__(self, name, workdir, ciffile, pspfiles, ksampling={}, relax_alg={},\n elc_alg={}, scf_alg={}, u_alg={}, accuracy=\"normal\", opt_algs={}):\n super(RelaxTaskGenerator, self).__init__(name, workdir, ciffile, pspfiles,\n ksampling, elc_alg, scf_alg,\n u_alg, accuracy, opt_algs)\n self.relax_alg = relax_algorithm(**relax_alg)\n\n def strategy(self):\n if self.u_alg not in self.opt_algs:\n self.opt_algs.append(self.u_alg)\n return relax_strategy(self.cs, self.psplist, self.ksampling, self.relax_alg,\n self.elc_alg, self.scf_alg, self.accuracy, self.opt_algs)\n\nclass BandStructTaskGenerator(TaskGenerator):\n gentype = \"nscf\"\n\n def __init__(self, scfgen, ndivsm=10, nscf_alg={}):\n super(BandStructTaskGenerator, self).__init__(scfgen.name, scfgen.workdir)\n self.scfgen = scfgen\n self.nscf_ksampling = ksampling_with_path(scfgen.cs, ndivsm)\n self.nscf_alg = scf_algorithm(**nscf_alg)\n\n def strategy(self):\n return bs_strategy(self.scfgen.strategy(), self.nscf_ksampling,\n self.scfgen.elc_alg, self.nscf_alg, self.scfgen.opt_algs)\n","sub_path":"pymatgen_abihelper/taskgen.py","file_name":"taskgen.py","file_ext":"py","file_size_in_byte":3578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"235106155","text":"from json import JSONEncoder\nfrom csv import DictReader, DictWriter\nimport json\nfrom classes import Person\n\nperson = Person(\"Chase\", 33, \"black\")\ndata = JSONEncoder().encode(person.get())\nfield_names = [\"name\", \"age\", \"hair\"]\n\nwith open(\"./person.csv\", \"w\", newline=\"\") as file:\n writer = DictWriter(file, field_names)\n writer.writeheader()\n writer.writerow(person.get())\n\nwith open(\"./person.csv\", \"r\") as file:\n data = DictReader(file)\n for row in data:\n print(row)\n","sub_path":"day7/lesson_csv.py","file_name":"lesson_csv.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"133632122","text":"# -*- coding: utf-8 -*-\nimport sys\n\n__author__ = 'jack'\n\n\nclass Solution:\n def largestRectangleArea(self, heights) -> int:\n # 1. 暴力法\n # max_area = 0\n # for i in range(len(heights)):\n # for j in range(i + 1, len(heights)):\n # min_height = min(heights[i:j + 1])\n # max_area = max(min_height * (j - i + 1), max_area)\n #\n # return max_area\n\n # 2. 暴力法优化\n # max_area = 0\n # for i in range(len(heights)):\n # min_height = heights[0]\n # for j in range(i + 1, len(heights)):\n # min_height = min(min_height, heights[j])\n # max_area = max(min_height * (j - i + 1), max_area)\n # return max_area\n\n # 3. 问题可以抽取为以第i根柱子为最矮柱子所能延伸的最大面积:O(n^2)\n # max_area = 0\n # for i in range(len(heights)):\n # height = heights[i]\n # left = i\n # right = i\n # while (left >= 0) and (heights[left] >= height):\n # left -= 1\n # while (right <= len(heights) - 1) and (heights[right] >= height):\n # right += 1\n # max_area = max(max_area, height * (right - left - 1))\n # return max_area\n\n # 4. 维护一个栈\n max_area = 0\n stack = [-1]\n for i in range(len(heights)):\n while (stack[-1] != -1) & (heights[stack[-1]] > heights[i]):\n # i 为右边界,栈中下一个元素为其左边界\n max_area = max(max_area, heights[stack.pop()] * (i - stack[-1] - 1))\n stack.append(i)\n while stack[-1] != -1:\n max_area = max(max_area, heights[stack.pop()] * (len(heights) - stack[-1] - 1))\n return max_area\n\n\n\n\n\nsolver = Solution()\nprint(solver.largestRectangleArea([2, 1, 5, 6, 2, 3]))\n","sub_path":"Week_01/84.largest_rectangle_in_histogram.py","file_name":"84.largest_rectangle_in_histogram.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"20670321","text":"#!/usr/bin/env python3\n\n#\n# This file is part of LiteX-Boards.\n#\n# Copyright (c) 2023 Gabriel Somlo \n# Copyright (c) 2022 Andrew Gillham \n# Copyright (c) 2014-2015 Sebastien Bourdeauducq \n# Copyright (c) 2014-2020 Florent Kermarrec \n# Copyright (c) 2014-2015 Yann Sionneau \n# SPDX-License-Identifier: BSD-2-Clause\n\nimport os\n\nfrom migen import *\n\nfrom litex.gen import *\n\nfrom litex_boards.platforms import sitlinv_stlv7325_v2\n\nfrom litex.soc.cores.clock import *\nfrom litex.soc.integration.soc_core import *\nfrom litex.soc.integration.builder import *\nfrom litex.soc.cores.led import LedChaser\nfrom litex.soc.cores.bitbang import I2CMaster\nfrom litex.soc.cores.video import VideoS7HDMIPHY\n\nfrom litedram.modules import MT8JTF12864\nfrom litedram.phy import s7ddrphy\n\nfrom liteeth.phy.s7rgmii import LiteEthPHYRGMII\n\nfrom litepcie.phy.s7pciephy import S7PCIEPHY\nfrom litepcie.software import generate_litepcie_software\n\n# CRG ----------------------------------------------------------------------------------------------\n\nclass _CRG(LiteXModule):\n def __init__(self, platform, sys_clk_freq):\n self.rst = Signal()\n self.cd_sys = ClockDomain()\n self.cd_sys4x = ClockDomain()\n self.cd_idelay = ClockDomain()\n self.cd_hdmi = ClockDomain()\n self.cd_hdmi5x = ClockDomain()\n\n # # #\n\n # Clk/Rst.\n clk200 = platform.request(\"clk200\")\n clk50 = platform.request(\"clk50\")\n rst_n = platform.request(\"cpu_reset_n\")\n\n # PLL.\n self.pll = pll = S7PLL(speedgrade=-2)\n self.comb += pll.reset.eq(~rst_n | self.rst)\n pll.register_clkin(clk200, 200e6)\n pll.create_clkout(self.cd_sys, sys_clk_freq)\n pll.create_clkout(self.cd_sys4x, 4*sys_clk_freq)\n pll.create_clkout(self.cd_idelay, 200e6)\n platform.add_false_path_constraints(self.cd_sys.clk, pll.clkin) # Ignore sys_clk to pll.clkin path created by SoC's rst.\n\n self.submodules.pll2 = pll2 = S7PLL(speedgrade=-2)\n self.comb += pll2.reset.eq(~rst_n | self.rst)\n pll2.register_clkin(clk50, 50e6)\n pll2.create_clkout(self.cd_hdmi, 25e6, margin=0)\n pll2.create_clkout(self.cd_hdmi5x, 125e6, margin=0)\n\n self.idelayctrl = S7IDELAYCTRL(self.cd_idelay)\n\n# BaseSoC ------------------------------------------------------------------------------------------\n\nclass BaseSoC(SoCCore):\n def __init__(self, sys_clk_freq=100e6,\n vccio = \"3.3V\",\n with_ethernet = False,\n with_led_chaser = True,\n with_pcie = False,\n with_sata = False, sata_gen=\"gen2\",\n with_jtagbone = False,\n with_video_colorbars = False,\n with_video_framebuffer = False,\n with_video_terminal = False,\n **kwargs):\n platform = sitlinv_stlv7325_v2.Platform(vccio)\n\n # CRG --------------------------------------------------------------------------------------\n self.crg = _CRG(platform, sys_clk_freq)\n\n # SoCCore ----------------------------------------------------------------------------------\n SoCCore.__init__(self, platform, sys_clk_freq, ident=\"LiteX SoC on Sitlinv STLV7325-v2\", **kwargs)\n\n # DDR3 SDRAM -------------------------------------------------------------------------------\n if not self.integrated_main_ram_size:\n self.ddrphy = s7ddrphy.K7DDRPHY(platform.request(\"ddram\"),\n memtype = \"DDR3\",\n nphases = 4,\n sys_clk_freq = sys_clk_freq,\n )\n self.add_sdram(\"sdram\",\n phy = self.ddrphy,\n module = MT8JTF12864(sys_clk_freq, \"1:4\"),\n l2_cache_size = kwargs.get(\"l2_size\", 8192),\n )\n\n # Jtagbone ---------------------------------------------------------------------------------\n if with_jtagbone:\n self.add_jtagbone()\n\n # Ethernet / Etherbone ---------------------------------------------------------------------\n if with_ethernet:\n self.ethphy = LiteEthPHYRGMII(\n clock_pads = self.platform.request(\"eth_clocks\", 0),\n pads = self.platform.request(\"eth\", 0),\n tx_delay = 1.417e-9,\n rx_delay = 1.417e-9,\n )\n self.add_ethernet(phy=self.ethphy)\n\n # PCIe -------------------------------------------------------------------------------------\n if with_pcie:\n self.pcie_phy = S7PCIEPHY(platform, platform.request(\"pcie_x4\"),\n data_width = 128,\n bar0_size = 0x20000)\n self.add_pcie(phy=self.pcie_phy, ndmas=1)\n\n # TODO verify / test\n # SATA -------------------------------------------------------------------------------------\n if with_sata:\n from litex.build.generic_platform import Subsignal, Pins\n from litesata.phy import LiteSATAPHY\n\n # RefClk, Generate 150MHz from PLL.\n self.cd_sata_refclk = ClockDomain()\n self.crg.pll.create_clkout(self.cd_sata_refclk, 150e6)\n sata_refclk = ClockSignal(\"sata_refclk\")\n platform.add_platform_command(\"set_property SEVERITY {{Warning}} [get_drc_checks REQP-52]\")\n\n # PHY\n self.sata_phy = LiteSATAPHY(platform.device,\n refclk = sata_refclk,\n pads = platform.request(\"sata\", 0),\n gen = sata_gen,\n clk_freq = sys_clk_freq,\n data_width = 16)\n\n # Core\n self.add_sata(phy=self.sata_phy, mode=\"read+write\")\n\n # HDMI Options -----------------------------------------------------------------------------\n if (with_video_colorbars or with_video_framebuffer or with_video_terminal):\n self.submodules.videophy = VideoS7HDMIPHY(platform.request(\"hdmi_out\"), clock_domain=\"hdmi\")\n if with_video_colorbars:\n self.add_video_colorbars(phy=self.videophy, timings=\"640x480@60Hz\", clock_domain=\"hdmi\")\n if with_video_terminal:\n self.add_video_terminal(phy=self.videophy, timings=\"640x480@60Hz\", clock_domain=\"hdmi\")\n if with_video_framebuffer:\n self.add_video_framebuffer(phy=self.videophy, timings=\"640x480@60Hz\", clock_domain=\"hdmi\")\n\n # Leds -------------------------------------------------------------------------------------\n if with_led_chaser:\n self.leds = LedChaser(\n pads = platform.request_all(\"user_led_n\"),\n sys_clk_freq = sys_clk_freq)\n\n # I2C --------------------------------------------------------------------------------------\n self.i2c = I2CMaster(platform.request(\"i2c\"))\n\n# Build --------------------------------------------------------------------------------------------\n\ndef main():\n from litex.build.parser import LiteXArgumentParser\n parser = LiteXArgumentParser(platform=sitlinv_stlv7325_v2.Platform, description=\"LiteX SoC on AliExpress STLV7325-v2.\")\n parser.add_target_argument(\"--sys-clk-freq\", default=100e6, type=float, help=\"System clock frequency.\")\n parser.add_target_argument(\"--vccio\", default=\"3.3V\", type=str, help=\"IO Voltage (set by J4), can be 2.5V or 3.3V\")\n parser.add_target_argument(\"--with-pcie\", action=\"store_true\", help=\"Enable PCIe support.\")\n parser.add_target_argument(\"--driver\", action=\"store_true\", help=\"Generate PCIe driver.\")\n parser.add_target_argument(\"--with-ethernet\", action=\"store_true\", help=\"Enable Ethernet support.\")\n parser.add_target_argument(\"--with-sata\", action=\"store_true\", help=\"Enable SATA support.\")\n parser.add_target_argument(\"--sata-gen\", default=\"2\", help=\"SATA Gen..\", choices=[\"1\", \"2\", \"3\"])\n parser.add_target_argument(\"--with-jtagbone\", action=\"store_true\", help=\"Enable Jtagbone support.\")\n sdopts = parser.target_group.add_mutually_exclusive_group()\n sdopts.add_argument(\"--with-spi-sdcard\", action=\"store_true\", help=\"Enable SPI-mode SDCard support.\")\n sdopts.add_argument(\"--with-sdcard\", action=\"store_true\", help=\"Enable SDCard support.\")\n viopts = parser.target_group.add_mutually_exclusive_group()\n viopts.add_argument(\"--with-video-terminal\", action=\"store_true\", help=\"Enable Video Terminal (HDMI).\")\n viopts.add_argument(\"--with-video-framebuffer\", action=\"store_true\", help=\"Enable Video Framebuffer (HDMI).\")\n viopts.add_argument(\"--with-video-colorbars\", action=\"store_true\", help=\"Enable Video Colorbars (HDMI).\")\n args = parser.parse_args()\n\n soc = BaseSoC(\n sys_clk_freq = args.sys_clk_freq,\n vccio = args.vccio,\n with_ethernet = args.with_ethernet,\n with_pcie = args.with_pcie,\n with_sata = args.with_sata,\n sata_gen = \"gen\" + args.sata_gen,\n with_jtagbone = args.with_jtagbone,\n with_video_colorbars = args.with_video_colorbars,\n with_video_framebuffer = args.with_video_framebuffer,\n with_video_terminal = args.with_video_terminal,\n **parser.soc_argdict\n )\n if args.with_spi_sdcard:\n soc.add_spi_sdcard()\n if args.with_sdcard:\n soc.add_sdcard()\n builder = Builder(soc, **parser.builder_argdict)\n if args.build:\n builder.build(**parser.toolchain_argdict)\n\n if args.driver:\n generate_litepcie_software(soc, os.path.join(builder.output_dir, \"driver\"))\n\n if args.load:\n prog = soc.platform.create_programmer()\n prog.load_bitstream(builder.get_bitstream_filename(mode=\"sram\"))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"litex_boards/targets/sitlinv_stlv7325_v2.py","file_name":"sitlinv_stlv7325_v2.py","file_ext":"py","file_size_in_byte":9949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"61648158","text":"from django import forms\nfrom .models import Contato, Grupo, Telefone, Email\n\nclass EditarContatoForm(forms.Form):\n def __init__(self, *args, **kwargs):\n contato = Contato.objects.get(id=kwargs.pop('id'))\n self.contato = contato\n super(EditarContatoForm, self).__init__(*args, **kwargs)\n self.fields['nome_contato'] = forms.CharField(max_length=50, initial=contato.nome)\n grupos = Grupo.objects.all()\n grupos_contato = contato.grupos.all()\n for grupo in grupos:\n self.fields[f\"g_{grupo.nome}\"] = forms.BooleanField(required=False,\n initial=grupo in grupos_contato,\n label=f\"{grupo.nome}\")\n\n for i, tel in enumerate(contato.telefone_set.all()):\n self.fields[f\"tel_{i}\"] = forms.CharField(max_length=14,\n label=f\"Telefone {i+1}\",\n initial=contato.telefone_set.all()[i].numero)\n\n for i, email in enumerate(contato.email_set.all()):\n self.fields[f\"email_{i}\"] = forms.EmailField(max_length=255,\n label=f\"Email {i+1}\",\n initial=contato.email_set.all()[i].endereco)\n\n def clean_nome_contato(self):\n nome_contato = self.cleaned_data.get('nome_contato')\n nomes_contatos = []\n for contact in Contato.objects.all():\n nomes_contatos.append(contact.nome)\n nomes_contatos.remove(self.contato.nome)\n if nome_contato in nomes_contatos:\n raise forms.ValidationError(\"O nome escolhido já está sendo utilizado.\")\n return nome_contato\n\nclass NovoGrupoForm(forms.ModelForm):\n class Meta:\n model = Grupo\n fields = ('nome', 'descricao')\n\nclass NovoTelForm(forms.ModelForm):\n class Meta:\n model = Telefone\n fields = ('numero',)\n\nclass NovoEmailForm(forms.ModelForm):\n class Meta:\n model = Email\n fields = ('endereco',)\n","sub_path":"contatos/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"241516322","text":"#! /usr/bin/env python2\n\nimport tsinsar as ts\nimport argparse\nimport numpy as np\n\ndef parse():\n parser= argparse.ArgumentParser(description='Preparation of XML files for setting up the processing chain. Check tsinsar/tsxml.py for details on the parameters.')\n parser.parse_args()\n\ngeomDir = '/Users/yunjunz/insarlab/Galapagos/GalapagosSenDT128/ISCE/merged/geom_master'\nparse()\ng = ts.TSXML('data')\ng.prepare_data_xml('filt_fine.unw', proc='RPAC',\n xlim=[0,1700], ylim=[400,2400],\n rxlim=[839,841], rylim=[771,773],\n latfile=geomDir+'/lat.rdr',\n lonfile=geomDir+'/lon.rdr',\n hgtfile=geomDir+'/hgt.rdr',\n inc=33.5,\n atmosdir='/Users/yunjunz/insarlab/WEATHER/ECMWF',\n cohth=0.25,\n mask='/Users/yunjunz/insarlab/Galapagos/GalapagosSenDT128/ISCE/merged/geom_master/waterMask.h5',\n chgendian='False',\n masktype='HDF5',\n unwfmt='RMG',\n corfmt='FLT',\n demfmt='float64')\ng.writexml('data.xml')\n\n\ng = ts.TSXML('params')\ng.prepare_sbas_xml(nvalid=300,\n netramp=True,\n atmos='ECMWF',\n demerr=True,\n uwcheck=False,\n regu=True,\n masterdate='20141225',\n filt=0.01)\ng.writexml('sbas.xml')\n\n\ng = ts.TSXML('params')\ng.prepare_mints_xml(netramp=True,\n atmos='ECMWF',\n demerr=True,\n uwcheck=False,\n regu=True,\n masterdate='20141225')\ng.writexml('mints.xml')\n\n","sub_path":"giant/prepxml.py","file_name":"prepxml.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"143110156","text":"#ID8\n\n#This program finds the greatest product of five consecutive digits in\n#a 1000-digit number\n\ndef ID8():\n num = input('What number would you like to check? ')\n maxprod = 0\n for i in range(995):\n a = num[i:i+5]\n b = 1\n for j in a:\n b = b * int(j)\n if b > maxprod:\n maxprod = b\n print(maxprod)\n \nID8()\n","sub_path":"python files/id8.py","file_name":"id8.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"570394963","text":"from django.conf import settings\nfrom django.utils.translation import ugettext as _\nfrom urllib3.exceptions import NewConnectionError, MaxRetryError\nfrom wagtail.admin import messages\nfrom wagtail.core import hooks\n\nfrom xr_newsletter.models import NewsletterFormPage\nfrom xr_newsletter.services import sendy_api\n\n\n@hooks.register(\"after_create_page\")\n@hooks.register(\"after_edit_page\")\ndef newsletter_form_page_check_sendy_api(request, page):\n\n if isinstance(page, NewsletterFormPage):\n if not page.sendy_list_id:\n message = _(\n 'There is no sendy_list_id set for page \"%s\". '\n \"Therefore newsletter subscription will not work.\" % page\n )\n messages.warning(request, message)\n elif not settings.DEBUG:\n\n sendy_response = None\n try:\n sendy_response = sendy_api.subscriber_count(page.sendy_list_id)\n\n # Sendy will return an integer if the given list_id exists\n\n int(sendy_response)\n except (\n ConnectionError,\n NewConnectionError,\n MaxRetryError,\n ValueError,\n ) as e:\n message = (\n _(\n \"There was a problem talking to Sendy API: %s. \"\n \"Please check the sendy_list_id and try again.\"\n )\n % sendy_response\n if sendy_response\n else e\n )\n messages.warning(request, message)\n","sub_path":"src/xr_newsletter/wagtail_hooks.py","file_name":"wagtail_hooks.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"265421340","text":"'''\nIC input shaping sens plots\n'''\n\n\nimport warnings\nwarnings.simplefilter(\"ignore\", UserWarning)\n\n# Import the necessary python library modules\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy.optimize import minimize\nimport os\nimport sys\nimport pdb\n\n# Add my local path to the relevant modules list\nsys.path.append('/Users/Daniel/Github/Crawlab-Student-Code/Daniel Newman/Python Modules')\n\n# Import my python modules\nimport InputShaping as shaping\nimport Boom_Crane as BC\nimport Generate_Plots as genplt\nimport si\n\n# Use lab plot style\nplt.style.use('Crawlab')\n\n# define constants\nDEG_TO_RAD = np.pi / 180\nG = 9.81\n\nBoom=0.81\nCable=0.30\nAmax=174.0\nVmax=17.4\nLuff_vals = np.array([30.,60.])\nTmax=5.0\nTstep=0.01\nnormalized_amp=0.8\nphase=90.\nStartt=np.array([0.])\n\n\np = BC.init_crane(\tBoom,\n\t\t\t\t\tCable,\n\t\t\t\t\tAmax,\n\t\t\t\t\tVmax,\n\t\t\t\t\tLuff_vals,\n\t\t\t\t\tTmax,\n\t\t\t\t\tTstep,\n\t\t\t\t\tnormalized_amp,\n\t\t\t\t\tphase,\n\t\t\t\t\tStartt=Startt\n\t\t\t\t)\n[Amax,Vmax], l, r, StartTime, t_step,t,X0,Distance = p\n\nphase *= DEG_TO_RAD\n\n#phase += Vmax / Amax * np.sqrt(G/l)*0.5\n\ntime_ic = phase / np.sqrt(G/l)\nomega = np.sqrt(G/l) / (2*np.pi)\n\nic = np.array([normalized_amp,time_ic])\n\nres,shaper = si.si(0,1,None,omega - 0.0*omega,omega + 0.0*omega,0.,0.00,0.01,ic_1=ic)\n\nsi_test_response = BC.response([[Amax,Vmax], l, r, StartTime, t_step,t,X0,100.*Distance],shaper)\nsi_test_response[:,0] /= DEG_TO_RAD\n# Get the UM-ZV-IC shaped response\numzvic_response = BC.response(p,['UMZVIC-UMZVIC'])\n\nfrequency, shaped_amps = genplt.ic_sensplot(shaper,0.0 * omega,5*omega,omega,0.0,ic_1=ic,plotflag=1)\nfrequency, shaped_amps = genplt.ic_phase_sensplot(shaper,0.0*time_ic,1/(omega),0.0,omega*2*np.pi,ic_1=ic,plotflag=1)\nfrequency, shaped_amps = genplt.ic_amp_sensplot(shaper,0.0 *normalized_amp,1.0,0.0,omega*2*np.pi,ic_1=ic,plotflag=1)\n\n# Print the residual vibration from the UM-ZV-IC Shaped command\numzvic_amp = BC.response(\n\t\t\t\t\t\tp,['UMZVIC-UMZVIC'],\n\t\t\t\t\t\treturn_response=False,\n\t\t\t\t\t\t)\n\n# Plot all of the relevant response values\n################################################\n################################################\n\n# Determine the folder where the plots will be saved\nfolder = 'Figures/{}/Luff_{}/norm_{}({}_{})_phase_{}'.format(\n\t\t\t\t\t\t\t\t\t\t\t\tsys.argv[0],\n\t\t\t\t\t\t\t\t\t\t\t\tLuff_vals,\n\t\t\t\t\t\t\t\t\t\t\t\tnormalized_amp,\n\t\t\t\t\t\t\t\t\t\t\t\tnp.round(X0[0]/DEG_TO_RAD).astype(int),\n\t\t\t\t\t\t\t\t\t\t\t\tnp.round(X0[1]/DEG_TO_RAD).astype(int),\n\t\t\t\t\t\t\t\t\t\t\t\tphase\n\t\t\t\t\t\t\t\t\t\t\t\t)\n","sub_path":"Code/Paper_Simulations/ACC_RobustIC_2018/Initial Submission/Old/ic_sens.py","file_name":"ic_sens.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"88765882","text":"from brick import *\n\nfrom pgu import gui\n\nimport env\n\nimport math\n\nimport imgs\nfrom robothread import *\nfrom dialog import SettingsDialog\n\nfrom sensors import *\n\nclass Robot(NXTBrick):\n proc = None\n die = False\n inputs = {}\n background = None\n bckg = None\n sensors = {}\n touchPoints = {\n \"topleft\": [\n [29.0, -133.60281897270363],\n [28.319604517012593, -132.13759477388825],\n [27.65863337187866, -130.6012946450045],\n ],\n \"left\": [\n [-29, 42.721999467666336],\n [-28.319604517012593, 41.389942632819086],\n ],\n \"topright\": [\n [27.018512172212592, -51.00900595749453],\n [27.65863337187866, -49.398705354995535],\n [28.319604517012593, -47.862405226111754],\n ],\n \"right\": [\n [29.698484809834994, -43.97583689433345],\n [29, -42.721999467666336],\n [29, -47.278000532333664],\n [28.319604517012593, -41.389942632819086],\n [28.319604517012593, -48.610057367180914],\n ]\n }\n\n def __init__(self, wboot = True):\n __builtins__['robot']= self\n\n self.x = env.w/2\n self.y = env.h/2\n self.angle = 0\n \n \n \n self.mA = 0\n self.mB = 0\n self.mC = 0\n \n self.p = 0\n\n self.rotA = self.rotB = self.rotC = 0\n\n self.radius = 21\n\n self.dragged = False\n self.dragoffset = []\n #self.image = pygame.image.load(\"./robot.jpg\").convert()\n #path = os.path.dirname(os.path.abspath(sys.argv[0]))\n #self.image = pygame.image.load(path + \"/robot.png\").convert_alpha() # imgs.robot.convert()\n self.image = imgs.robot.convert_alpha()\n #self.image = pygame.image.load(\"black_and_blacker.png\").convert_alpha()\n\n self.lock = Lock()\n \n self.root = os.path.abspath(os.path.dirname(sys.argv[0]))\n # directory with programs to the path\n sys.path.append(self.root + os.sep + '__progs__')\n\n\n self.lcd = pygame.Surface((204, 130))\n pygame.draw.rect(self.lcd, pygame.Color(0x43, 0x6c, 0x30),\n ((0, 0), (204, 130)))\n\n if wboot:\n #print \"booting\"\n RoboThread(target=self.boot).start()\n \n self.sensors = {1: BaseSensor(1),\n 2: BaseSensor(2),\n 3: BaseSensor(3),\n 4: BaseSensor(4)}\n\n self.dialog = SettingsDialog()\n\n \n def getDistanceTo(self, point):\n dx = point[0] - self.x\n dy = point[1] - self.y\n return math.sqrt(dx**2 + dy**2)\n\n def mouseOver(self):\n mpos = pygame.mouse.get_pos()\n if self.getDistanceTo(mpos) < self.radius:\n return True\n else:\n return False\n\n def drag(self):\n mpos = pygame.mouse.get_pos()\n self.x = mpos[0]\n self.y = mpos[1]\n \n\n #pygame.image.save(self.image, \"robot_.png\")\n\n self.stayIn()\n \n def rot_center(self, image, angle):\n \"\"\"rotate an image while keeping its center and size\"\"\"\n orig_rect = image.get_rect()\n rot_image = pygame.transform.rotate(image, angle)\n rot_rect = orig_rect.copy()\n rot_rect.center = rot_image.get_rect().center\n rot_image = rot_image.subsurface(rot_rect).copy()\n return rot_image\n\n def draw(self):\n\n env.screen.blit(env.background, (0,0))\n env.screen.blit(self.rot_center(self.image, -self.angle),\n (self.x - 30, self.y - 30))\n\n env.screen.blit(self.lcd, ((640 + (378/2 - 100)-2, 90), (204, 130)))\n\n env.app.paint()\n pygame.display.flip()\n\n def touchesAt(self, positions):\n \n for pos in positions:\n dx = cos(radians(pos[1] + robot.angle)) * pos[0]\n dy = sin(radians(pos[1] + robot.angle)) * pos[0]\n \n #print 30 + round(dx), 30 + round(dy)\n\n x = int(self.x + round(dx))\n y = int(self.y + round(dy))\n\n #env.background.set_at((x, y), (0, 0, 255, 0))\n\n try:\n o = env.background.get_at((x, y))\n except IndexError:\n return True\n\n if o == (190, 190, 190, 255):\n return True\n\n return False\n\n def touches(self):\n out = {}\n for p in self.touchPoints:\n out[p] = self.touchesAt(p)\n\n return out\n\n def stayIn(self):\n if self.x > 623:\n self.x = 623\n\n if self.x < 23:\n self.x = 23\n\n if self.y > 463:\n self.y = 463\n\n if self.y < 23:\n self.y = 23\n\n\n def tick(self):\n # self.stayIn()\n angle = 0\n rotA = rotB = 0\n touchedA = touchedB = False\n\n if not self.touchesAt(self.touchPoints[\"topleft\"]):\n rotA = self.mA / 30.0\n else:\n touchedA = True\n rotA -= self.mA / 40.0 \n\n if not self.touchesAt(self.touchPoints[\"topright\"]):\n rotB = self.mB / 30.0\n else:\n touchedB = True\n rotB -= self.mB / 40.0\n\n rotC = self.mC / 30.0\n \n angle += (rotA - rotB) / 3\n\n self.angle += angle\n p = (rotA + rotB) / 2 / 1.8\n \n # #print self.angle, self.mA, self.mB, self\n \n self.rotA += rotA\n self.rotB += rotB\n self.rotC += rotC\n\n self.x += math.sin(math.radians(self.angle)) * p\n self.y += -math.cos(math.radians(self.angle)) * p\n \n self.angle = round(self.angle)\n\n self.draw()\n \n if touchedA:\n self.rotA += -2*rotA\n if touchedB:\n self.rotB += -2*rotB\n\n # print background.get_at((int(self.x), int(self.y)))\n\n def onCenter(self):\n # Turning off\n if self.screen == -1 and self.btn_x == 0:\n sys.exit(0)\n\n if self.screen < 4:\n self.screen += 1\n\n # taking care of empty __progs__ directory\n if self.screen == 2 and len(self.progs) == 0:\n self.screen -= 1\n\n if self.screen == 4:\n if self.proc == None:\n\n module = __import__('e' + self.progs[self.prog])\n \n self.proc = RoboThread(target=module.main,\n cleaner=self.cleaner)\n self.proc.setName(\"brick\")\n\n ClearScreen()\n self.scr_runner = RoboThread(target=robot.running)\n\n self.scr_runner.start()\n self.proc.start()\n else:\n self.scrout()\n \n \n #print \"center\"\n\n def onBack(self):\n \n # exiting\n #if self.screen == 0:\n # sys.exit(0)\n \n if self.screen == -1:\n self.screen += 2\n\n if self.proc == None:\n self.screen -= 1\n self.scrout()\n else:\n self.die = True\n self.scr_running = False\n\n #print \"back\"\n \n def onLeft(self):\n #print \"left\"\n if self.screen == 2:\n self.prog = (self.prog - 1) % len(self.progs)\n \n if self.screen == -1:\n self.btn_x = 0\n\n self.scrout()\n\n def onRight(self):\n #print \"right\"\n if self.screen == 2:\n self.prog = (self.prog + 1) % len(self.progs)\n\n if self.screen == -1:\n self.btn_x = 1\n\n\n self.scrout()\n\n def cleaner(self):\n ClearScreen()\n\n self.scr_running = False\n\n Off(OUT_ABC)\n ResetTachoCount(OUT_ABC)\n\n self.proc = None\n \n\n self.screen -= 1\n self.scrout()\n #print \"cleaner\"\n\n def onDialog(self):\n self.dialog.connect(gui.CHANGE, self.dialogReturn, self.dialog)\n self.dialog.open()\n self.dialog.rect.x = 120\n \n def imgUpdate(self):\n image = imgs.robot.convert_alpha()\n \n for x in self.inputs:\n inp = self.inputs[x]\n if inp['slot'] != '':\n dx = inp['slot']*7\n if inp['slot'] == 3:\n dx += 1\n \n dw = 1 if inp['slot'] == 2 else 0\n pygame.draw.rect(image, (0xfa, 0x70, 0x0d),\n (13+dx, 9, 5+dw, 5))\n \n\n\n #pygame.draw.rect(image, (0xfa, 0x70, 0x0d), (20, 9, 5, 5))\n #pygame.draw.rect(image, (0xfa, 0x70, 0x0d), (27, 9, 6, 5))\n #pygame.draw.rect(image, (0xfa, 0x70, 0x0d), (35, 9, 5, 5))\n\n self.image = image\n\n def dialogReturn(self, d):\n out = d.out()\n\n robot.inputs = out['inputs']\n \n for i in out['inputs']:\n inp = out['inputs'][i]\n \n self.sensors[i] = sensor_generator(inp['type'], inp['slot'])\n \n if out['others'][0][1] == 'custom' and out['others'][1][1] != '':\n robot.background = out['others'][1][1]\n env.init()\n \n img = pygame.image.load(robot.background)\n if img.get_alpha() != None:\n img = img.convert_alpha()\n else:\n img = img.convert()\n\n\n env.background.blit(img, (3, 3))\n else:\n robot.background = None\n env.init()\n \n self.imgUpdate()\n\n d.close()\n","sub_path":"nxtemu/robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":9470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"446406131","text":"from sys import argv\nimport matplotlib.pyplot as plt\n\ndef readLabels(fileName):\n\tf = open(fileName, 'r')\n\tA = f.readlines()\n\tf.close()\n\n\tX = []\n\tY = []\n\tTHETA = []\n\tLBL = []\n\n\tfor line in A:\n\t\t(x, y, theta, lbl) = line.split(' ')\n\t\tX.append(float(x))\n\t\tY.append(float(y))\n\t\tTHETA.append(float(theta))\n\t\tLBL.append(float(lbl.rstrip('\\n')))\n\n\treturn (X, Y, THETA, LBL)\n\n\ndef readPoses(fileName):\n\tf = open(fileName, 'r')\n\tA = f.readlines()\n\tf.close()\n\n\tX = []\n\tY = []\n\tTHETA = []\n\n\tfor line in A:\n\t\t(x, y, theta) = line.split(' ')\n\t\tX.append(float(x))\n\t\tY.append(float(y))\n\t\tTHETA.append(float(theta.rstrip('\\n')))\n\n\treturn (X, Y, THETA)\n\n\nif __name__ == '__main__':\n\tfileName = str(argv[1])\n\n\t(X, Y, THETA, LBL) = readLabels(fileName)\n\t\n\tX0 = []; Y0 = []; X1 = []; Y1 = []; X2 = []; Y2 =[]; X3 = []; Y3 = [];\n\t\n\tfor i in xrange(len(LBL)):\n\t\tif LBL[i] == 0:\n\t\t\tX0.append(X[i])\n\t\t\tY0.append(Y[i])\n\n\t\telif LBL[i] == 1:\n\t\t\tX1.append(X[i])\n\t\t\tY1.append(Y[i])\n\n\t\telif LBL[i] == 2:\n\t\t\tX2.append(X[i])\n\t\t\tY2.append(Y[i])\n\n\t\telif LBL[i] == 3:\n\t\t\tX3.append(X[i])\n\t\t\tY3.append(Y[i])\n\n\tfig = plt.figure()\n\tax = plt.subplot(2,1,1)\n\n\tax.plot(X0, Y0, 'ro', label='Rackspace')\n\tax.plot(X1, Y1, 'bo', label='Corridor')\n\tax.plot(X2, Y2, 'go', label='Trisection')\n\tax.plot(X3, Y3, 'yo', label='Intersection')\n\t\n\tax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n\n\tax.axis('scaled')\n\t# plt.xlim(-2, 2)\n\t# plt.ylim(-16, 5)\n\t# plt.gca().set_aspect('equal', adjustable='box')\n\t\n\tfileName = str(argv[2])\n\n\t(X, Y, THETA) = readPoses(fileName)\n\n\tax = plt.subplot(2,1,2)\n\tax.plot(X, Y)\n\tax.axis('scaled')\n\n\tplt.show()\n","sub_path":"src/plot_2traj.py","file_name":"plot_2traj.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"325020738","text":"__author__ = 'licheng'\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def binaryTreePaths(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[str]\n \"\"\"\n if root == None:\n return []\n\n result = []\n cur_path = \"\"\n self.dfs(root, cur_path, result)\n return result\n\n def dfs(self, T, cur_path, result):\n cur_path = cur_path + '->' + str(T.val)\n if T.left == None and T.right == None: # leaf node\n result.append(cur_path[2:])\n return\n if T.left != None:\n self.dfs(T.left, cur_path, result)\n if T.right != None:\n self.dfs(T.right, cur_path, result)\n\n","sub_path":"257.binary_tree_paths.py","file_name":"257.binary_tree_paths.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"187195562","text":"import serial\nimport numpy as np\nimport cv2\n\n\ndef send_commends(ser, motors, commands):\n for motor in motors:\n for direction_cmd in commands:\n command_string = bytes(2)\n command_string = bytearray(command_string)\n command_string[0] = motor # 2 motor 1, 4 motor 2, 8 motor 3\n command_string[1] = direction_cmd # 2 forward, 4 backward, 8 release\n print(command_string)\n command_string = bytes(command_string)\n ser.write(command_string) # write a string\n\n\ndef test_dc_motors():\n motors = set()\n commands = []\n # ser = serial.Serial('COM5') # open serial port\n ser = serial.Serial('/dev/ttyUSB1') # open serial port\n print(ser.name) # check which port was really used\n\n while True:\n img = np.zeros((200, 200), np.uint8)\n cv2.imshow('Main', img)\n key = cv2.waitKey(2)\n if key > 0:\n key = chr(key)\n\n if key in [ord('q')]:\n break\n if key in ['2', '4', '8']:\n motor = int(key)\n if motor in motors:\n motors.remove(motor)\n else:\n motors.add(motor)\n if key == 'w':\n commands = [2]\n if key == 's':\n commands = [8]\n if key == 'x':\n commands = [4]\n\n print(key, list(motors), commands)\n send_commends(ser, motors, commands)\n\n ser.close()\n\n\ntest_dc_motors()\n","sub_path":"control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"31962322","text":"import os\nfrom collections import defaultdict\nimport json\nimport argparse\nfrom multiprocessing import cpu_count\n\n#############################################################################\n# arguments\n\ndef argsify():\n\n parser = argparse.ArgumentParser(description='''A generator\n of squares of letters forming words in lines and columns,\n optionally in diagonals as well.''')\n\n parser.add_argument('-f', '--source_file',\n type=str,\n default='data/dicts/google-20000',\n help='''Source dictionary file (one word per line).\n Defaults to data/dicts/google-20000.''')\n\n\n # squares options\n\n parser.add_argument('-z', '--size',\n type=int,\n default=3,\n help='''Square size. Defaults to 3.''')\n\n parser.add_argument('-d', '--diagonals',\n dest='diagonals',\n action='store_true',\n default=True,\n help='''Turns the search for words in diagonals on (the default behaviour).''')\n\n parser.add_argument('-nd', '--no-diagonals',\n dest='diagonals',\n action='store_false',\n help='''Turns the search for words in diagonals off.''')\n\n parser.add_argument('-w', '--words',\n type=str,\n default=None,\n help='''Selects only the squares containing one or more specific words\n (comma separated).''')\n\n parser.add_argument('-e', '--diversity',\n type=int,\n default=None,\n help='''Number of different words required in each\n square.''')\n\n parser.add_argument('-l', '--letter_diversity',\n type=int,\n default=None,\n help='''Number of different letters required in each\n square.''')\n\n # print options\n\n parser.add_argument('-v', '--verbose',\n action='store_true',\n default=False,\n help='''Setting verbose to True will make the script\n print all results to the console. Defaults to false.''')\n\n parser.add_argument('-q', '--quiet',\n action='store_true',\n default=False,\n help='''Limiting the printing to the total found.\n Defaults to false.''')\n\n # compute & time options\n\n parser.add_argument('-p', '--processors',\n type=int,\n default=cpu_count(),\n help='''Number of cores used for parallel processing.\n Default: number of cores detected by the multiprocessing\n module.''')\n\n parser.add_argument('-t', '--time',\n action='store_true',\n default=False,\n help='''Calculate the total time of the program.''')\n\n args = parser.parse_args()\n\n return args\n\n\n#############################################################################\n# dictionary import\n\ndef load_dictionary(args, printer):\n dictionary = defaultdict(list)\n with open(args.source_file, 'r') as file:\n txt = [x for x in file.read().split('\\n') if x]\n for word in txt:\n dictionary[len(word.strip())].append(word)\n for length in dictionary.keys():\n dictionary[length].sort()\n if not args.quiet:\n printer.print_dict(dictionary, args, cols=4)\n return dictionary\n\ndef add_to_dictionary(dictionary, word):\n try:\n words = dictionary[len(word.strip())]\n words.append(word)\n dictionary[len(word.strip())] = words\n except:\n dictionary[len(word.strip())] = [word]\n\n#############################################################################\n# saving & file utils\n\ndef check_dir(result_dir, dict_name):\n # create dir if not already there\n if not os.path.isdir(result_dir):\n os.mkdir(result_dir)\n # extract\n sub_dir = os.path.splitext(os.path.basename(dict_name))[0]\n sub_dir_with_dir = os.path.join(result_dir, sub_dir) + '/'\n if not os.path.isdir(sub_dir_with_dir):\n os.mkdir(sub_dir_with_dir)\n return sub_dir_with_dir\n\ndef to_json(squares, printer, args):\n # prepare our final file\n final_name = 'squares_' + str(args.size)\n if not args.diagonals:\n final_name += '_no_diags'\n if args.diversity:\n final_name += '_div-{}'.format(args.diversity)\n if args.letter_diversity:\n final_name += '_ldiv-{}'.format(args.letter_diversity)\n if args.words:\n final_name += '_{}'.format('-'.join(args.words))\n final_name += '.json'\n\n result_dir = 'data/results'\n result_dir = check_dir(result_dir, args.source_file)\n\n squares_json = []\n for square in squares:\n sq = [square[:args.size], square[args.size:args.size*2]]\n if args.diagonals:\n sq.append(square[args.size*2:])\n squares_json.append(sq)\n\n with open(result_dir + final_name, 'w') as final:\n squares_json = json.dumps(squares_json)\n final.write(squares_json)\n\n printer.print('written results to file: {}'\n .format(result_dir + final_name))\n\n#############################################################################\n# other util: transfer from txt to json\n\ndef txt_to_json(source_file):\n lines = [line.split(',') for line in source_file.readlines() if line]\n squares = []\n for words in lines:\n size = len(words[0])\n square = [words[:size], words[size:size*2]]\n if len(words) > size * 2:\n square.append(words[size*2:])\n squares.append(square)\n outdir = os.path.dirname(os.path.abspath(source_file.name))\n outfile = os.path.splitext(os.path.basename(source_file.name))[0]\n outname = os.path.join(outdir, outfile) + '.json'\n with open(outname, 'w') as f:\n f.write(json.dumps(squares))\n print('written to file:', outname)\n\n#############################################################################\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='''Convert lists of squares\n (one square per line, comma separated, rows, cols, diags, to a json\n file in the same directory.''')\n\n parser.add_argument('-f', '--source_files',\n type=argparse.FileType('r'),\n nargs='+',\n help='''The source file (required).''')\n\n args = parser.parse_args()\n\n if args.source_files is not None:\n for source_file in args.source_files:\n txt_to_json(source_file)\n\n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"473005693","text":"from Utilities.Tools import *\nfrom Utilities.Stack import *\nfrom Utilities.Constant_Values import *\nfrom Utilities.Setting_Values import *\nimport random\n\nclass Computer(object):\n\n # region Constructer\n def __init__(self, model):\n\n # region info\n \"\"\"\n This Class responsible for the computer gameplay.\n It has connection to a smart player (Nega Max) and test player\n\n :param self.model: the connection to the model class.\n :type self.model: Model\n :param self.ai: class which is about the smart moves of the computer (Nega Max)\n :type self.ai: AI\n :param self.test_player: class which is about to test different moves based on the logic I want the computer to follow\n :type self.test_player: TestPlayer\n\n\n\n :return: Nothing\n :rtype: None\n \"\"\"\n # endregion\n\n self.model = model\n self.ai = AI(self.model)\n self.test_player = TestPlayer(self.model, self.ai)\n\n # endregion\n\n # region Methods\n\n def play_ai(self, update_depth_for_turn=False):\n\n # region info\n \"\"\"\n This function responsible for calling the ai to play and return moves.\n\n :param self.update_depth_for_turn: a variable which helps to understand which turn the computer play\n :type self.update_depth_for_turn: bool\n :param self.move_from: list of indexes to where to move from (row, col)\n :type self.move_from: list\n :param self.move_to: list of indexes to where to move to (row, col)\n :type self.move_to: list\n\n\n\n :return: moves (from point a to point b)\n :rtype: list, list\n \"\"\"\n # endregion\n\n move_from, move_to = self.ai.play_ai(update_depth_for_turn)\n return move_from, move_to\n\n def play_test_player(self, turn):\n\n # region info\n \"\"\"\n This function responsible for calling the test player to play and return moves.\n\n :param turn: allows to udnerstand which color to return moves for\n :type turn: bool\n :param self.move_from: list of indexes to where to move from (row, col)\n :type self.move_from: list\n :param self.move_to: list of indexes to where to move to (row, col)\n :type self.move_to: list\n\n\n\n :return: moves (from point a to point b)\n :rtype: list, list\n \"\"\"\n # endregion\n\n move_from, move_to = self.test_player.play_test_player(turn)\n return move_from, move_to\n\n def default_state(self):\n self.ai.default_state()\n # endregion\n\nclass AI(object):\n\n # region Constructer\n def __init__(self, model):\n\n # region info\n \"\"\"\n This Class responsible for the the smart (Nega Max) gameplay of the computer.\n\n :param self.model: the connection to the model class.\n :type self.model: Model\n :param self.board: allow to work with the same board as in the model\n :type self.board: list (of lists)\n :param self.location_nikud_dict: dictionary which helps to give score for each move (based on location on the board)\n :type self.location_nikud_dict: dict\n :param self.piece_nikud_dict: dictionary which helps to give score for each move (based on the soldier on the board)\n :type self.piece_nikud_dict: dict\n :param self.stack: helps to save moves which were made and undo them, so bascially nothing have happened. I use this since the changes are being made on the original board\n :type self.stack: Stack\n :param self.no_repeating_moves: mechanism which allows to prevent infinte loop ove moves, due to the NegaMax. Since the computer wants to do the best move and if play against himself there is a chance he will get stuck in a loop of best moves\n :type self.no_repeating_moves: list\n :param self.no_repeat_list_length: determine the amount of moves to save since the last one\n :type self.no_repeat_list_length: int\n :param self.no_repeat_list_length: a variables which helps to determine which color to use the NegaMax for. Since I dont use turn over here, it helps to make it happen. (switches from 1 to -1, or in another words from min to max)\n :type self.no_repeat_list_length: int\n\n\n :return: Nothing\n :rtype: None\n \"\"\"\n # endregion\n\n self.model = model\n self.board = self.model.get_board()\n self.location_nikud_dict = self.create_location_dictionary()\n self.piece_nikud_dict = self.create_piece_dictionary()\n # for the ai checks inside the negmax tree\n self.stack = Stack()\n\n # against infinite loop and used only only when the pc is against himself\n self.no_repeating_moves = []\n self.default_state()\n self.no_repeat_list_length = 13\n\n self.total_checks = 0\n self.optimiser = self.set_optimiser()\n # endregion\n\n # region Play the computer turn\n def play_ai(self, update_depth_for_turn=False):\n\n # region info\n \"\"\"\n This function is the layer before the NegaMax. This class makes sure everything is correct before we call the NegaMax.\n Since the model makes changs in the board, I have to update the refernce to the same board, therfore, I does it (1).\n Afterwards I sums the amount of checks in roots of the NegaMax (2). Then I use the ai_depth variable for the depth of the ai to\n check. I does it becuase the AI knows which color to check for based on the setting depth % 2. Mathematically it works so I\n use this like that (3). Later, if I have to make changes to for setting depth, I does it from the reason above and undo the change when the check was made (4) (5).\n Between I set the optimizer for the check in the NegaMax (6) and later call the NegaMax and make the checks (7). After, I return the moves (from point A to point B)\n\n :param self.update_depth_for_turn: allows to distinguish if to check for the black or white best option.\n :type self.update_depth_for_turn: bool\n :param self.total_checks: variable which helped to check the amout of times the AI went in the bottom of the NegaMax root\n :type self.total_checks: int\n :param ai_depth: variable which helps with the amount of checks in the ai\n :type ai_depth: int\n\n\n\n :return: Nothing\n :rtype: None\n \"\"\"\n # endregion\n\n\n # (1)\n # update refence each time (if I wont do this the refence to main board is gone)\n self.board = self.model.get_board()\n # (2)\n self.total_checks = 0\n\n # (3)\n ai_depth = S_T.AI_DEPTH\n\n # (4)\n # have to make a change for the optimizer and constant depth for this to work on both sides\n if update_depth_for_turn:\n S_T.AI_DEPTH = S_T.AI_DEPTH + 1\n\n # (6)\n self.optimiser = self.set_optimiser()\n\n # (7)\n move_from, move_to = self.nega_max_root(ai_depth)\n\n # (5)\n if update_depth_for_turn:\n S_T.AI_DEPTH = S_T.AI_DEPTH - 1\n\n return move_from, move_to\n\n\n # Play based on the mini max root logic\n def nega_max_root(self, depth):\n\n # region info\n \"\"\"\n This function is the head of the NegaMax tree. Therefore, in this function we do more things than the normal NegaMax.\n I begin by bringing all the available soldiers and their moves (1). Later, I set few default states for variables which will help me later on (2).\n After that, I use two mechanismes to prevent infinte best moves loops. Both of them work only when it is on AI vs AI mode. The first one is the one which checks for not repeating moves in the\n last amount of moves I chose to remember (3). If the mechanism found the same move again and there is not atleast one new move which is not remembered, then we go in.\n if the amount of players is less than 5, I chose to call it a draw (4). if there are more than 5, then it get a random move (5). Note that I dont return the best or third best moves,\n since they can lead as well to infinte loop quite often, therfore, I chose to use random move. It happens quite rare so it doesn't really effect anything.\n\n later I move to the second mechanism which works only in computer against computer mode. This mechanism make a random move one in 1 / RANDOMNEES_POSSIBILITY. I does it to make more\n complex games and not repeat the same game in every interval. It prevents more determinism and makes new situations we never saw before (6).\n\n If both of this mechanismes didn't work, then we actually move to the NegaMax (7). The NegaMax works as it should. Note, that becuase we work on the same board as the origin one, I save in\n a stack the moves which were made to undo them and make no changes however in the game.\n\n After all the checks if it was computer VS computer mode, I remove the oldest move in the repeating sequence and load the new one (8).\n After all of this I return the best move (point A to point B).\n\n\n :param depth: the depth the ai has to check\n :type depth: int\n :param new_game_places: saves all the available places\n :type new_game_places: list (of lists)\n :param new_game_moves: saves all the available moves\n :type new_game_moves: list (of lists)\n :param best_move: helps to check what is the best move (starts in a high number so new moves can be found easily)\n :type best_move: int\n :param best_move_place: saves the location for the soldier with the best move found (The location to move from)\n :type best_move_place: list\n :param best_move_found: saves the best move which was found (The location where to move to)\n :type best_move_found: list\n\n\n\n :return: from point A to point B\n :rtype: list, list\n \"\"\"\n # endregion\n\n # (1)\n new_game_places, new_game_moves = Tools.all_soldiers_moves(S_T.AI_DEPTH - depth, self.model, self.board)\n new_game_places, new_game_moves = Tools.convert_to_one_dimensional_lists(new_game_places, new_game_moves)\n\n # (2)\n best_move = -9999\n best_move_found = []\n best_move_place = -1\n\n # if there are no new moves which lead to the other situation this will make it a draw (In the case there are only 4 pieces left make it draw and if there are more make random move)\n # (3)\n if S_T.AI_VS_AI and not self.check_draw_state(new_game_moves):\n\n # (4)\n if Tools.find_amount_of_soldiers(self.board) < 5 or new_game_places == []:\n return [], []\n # (5)\n else:\n if len(new_game_moves) > 1:\n random_index = int(random.randint(0, len(new_game_moves) - 1))\n else:\n random_index = 0\n return new_game_places[random_index], new_game_moves[random_index]\n # make a small chance 1 / RANDOMNEES_POSSIBILITY to make random move. I do this to make the game more random and not determinst\n # (6)\n elif S_T.AI_VS_AI and int(random.randint(0, C_V.RANDOMNEES_POSSIBILITY)) == 1:\n random_value = int(random.randint(0, len(new_game_moves) - 1))\n return new_game_places[random_value], new_game_moves[random_value]\n\n # start the nega max (if it is in the case of (the RANDOMNEES_POSSIBILITY - 1) / RANDOMNEES_POSSIBILITY)\n # (7)\n for i in range(len(new_game_moves)):\n\n new_game_move = new_game_moves[i]\n\n if new_game_move != []:\n\n self.ugly_move(new_game_places[i], new_game_move)\n value = -self.nega_max(depth - 1, -10000, 10000)\n self.undo()\n\n if value >= best_move and (not S_T.AI_VS_AI or self.check_it_is_not_exist(value, new_game_move)):\n best_move = value\n best_move_found = new_game_move\n best_move_place = new_game_places[i]\n\n # (8)\n if S_T.AI_VS_AI:\n self.remove_oldest_state_and_update()\n self.save_state(best_move, best_move_found)\n\n return best_move_place, best_move_found\n\n # Play based on the mini max root logic\n def nega_max(self, depth, alpha, beta):\n\n # region info\n \"\"\"\n Basically the same as the NegaMax part in the NegaMax root, only with check if it is in the bottom of the tree.\n If it is, it checks the value and return it.\n\n\n\n :return: the value of the game due to the move after checks in a certin level.\n :rtype: int\n \"\"\"\n # endregion\n\n if depth == 0:\n self.total_checks += 1\n return self.optimiser * self.evaluate_board()\n\n new_game_places, new_game_moves = Tools.all_soldiers_moves((S_T.AI_DEPTH - depth) % 2, self.model, self.board)\n new_game_places, new_game_moves = Tools.convert_to_one_dimensional_lists(new_game_places, new_game_moves)\n\n best_move = -9999\n\n for i in range(len(new_game_moves)):\n\n if new_game_moves[i] != []:\n\n self.ugly_move(new_game_places[i], new_game_moves[i])\n best_move = max(best_move, -self.nega_max(depth - 1, -beta, -alpha))\n\n self.undo()\n\n alpha = max(alpha, best_move)\n\n if beta <= alpha:\n return best_move\n\n return best_move\n\n # endregion\n\n # region Methods\n\n def ugly_move(self, place, move):\n\n # region info\n \"\"\"\n loads the latest move (from where to where and the values in both locations)\n # Creates the ugly move for the minimax A I and saves the changes in a stack object\n\n\n :return: Nothing\n :rtype: None\n \"\"\"\n # endregion\n\n # Saves the move in a stack object so we can undo the move\n place_x = place[0]\n place_y = place[1]\n\n move_x = move[0]\n move_y = move[1]\n\n new_move = [[place_x, place_y, self.board[place_x][place_y]], [move_x, move_y, self.board[move_x][move_y]]]\n self.stack.push(new_move)\n\n # make the move\n\n self.board[move_x][move_y] = self.board[place_x][place_y]\n self.board[place_x][place_y] = 0\n\n def undo(self):\n\n # region info\n \"\"\"\n Unloads the latest move (from where to where and the values in both locations)\n # Undo the last move saved in the stack\n\n\n :return: Nothing\n :rtype: None\n \"\"\"\n # endregion\n\n old_move = self.stack.pop()\n\n move_active = old_move[0]\n move_static = old_move[1]\n\n self.board[move_active[0]][move_active[1]] = move_active[2]\n self.board[move_static[0]][move_static[1]] = move_static[2]\n\n def check_it_is_not_exist(self, value, move):\n\n # region info\n \"\"\"\n # Save move and check it didnt happen twice, for no duplicate moves\n\n\n :return: Nothing\n :rtype: None\n \"\"\"\n # endregion\n\n for i in range(self.no_repeat_list_length):\n\n if self.no_repeating_moves[i][0] == value and self.no_repeating_moves[i][1][0] == move[0] and \\\n self.no_repeating_moves[i][1][1] == move[1]:\n return False\n return True\n\n # region no duplicate moves\n\n def default_state(self):\n\n # region info\n \"\"\"\n # restart the duplicate list\n\n\n :return: Nothing\n :rtype: None\n \"\"\"\n # endregion\n\n self.no_repeating_moves = [[0, [0, 0]], [0, [0, 0]], [0, [0, 0]], [0, [0, 0]], [0, [0, 0]], [0, [0, 0]],\n [0, [0, 0]], [0, [0, 0]], [0, [0, 0]], [0, [0, 0]], [0, [0, 0]], [0, [0, 0]],\n [0, [0, 0]]]\n\n def save_state(self, value, move):\n\n # region info\n \"\"\"\n # function which saves the state of the game (The last move)\n\n\n :return: Nothing\n :rtype: None\n \"\"\"\n # endregion\n\n self.no_repeating_moves[self.no_repeat_list_length - 1] = [value, move]\n\n def remove_oldest_state_and_update(self):\n\n # region info\n \"\"\"\n # removes the oldest move and store the last move in\n\n\n :return: Nothing\n :rtype: None\n \"\"\"\n # endregion\n\n for i in range(self.no_repeat_list_length - 1):\n self.no_repeating_moves[i] = self.no_repeating_moves[i + 1]\n\n def check_draw_state(self, new_game_moves):\n\n # region info\n \"\"\"\n # In the case of a draw these function will find it based on the way i told it to\n\n\n :return: False / True\n :rtype: bool\n \"\"\"\n # endregion\n\n new_move_can_be_made = False\n for i in range(len(new_game_moves)):\n\n new_move_can_be_made = True\n\n for j in range(len(self.no_repeating_moves)):\n\n if new_game_moves[i][0] == self.no_repeating_moves[j][1][0] and new_game_moves[i][1] == \\\n self.no_repeating_moves[j][1][1]:\n new_move_can_be_made = False\n break\n\n if new_move_can_be_made:\n return True\n\n return False\n\n # endregion\n\n def evaluate_board(self):\n\n # region info\n \"\"\"\n # return the value of the entire board\n\n\n :return: value of the state of the board\n :rtype: int\n \"\"\"\n # endregion\n\n total_evaluation = 0\n for i in range(8):\n for j in range(8):\n total_evaluation = total_evaluation + self.get_piece_value(self.board[i][j], i, j)\n\n return total_evaluation\n\n def get_piece_value(self, value, x, y):\n\n # region info\n \"\"\"\n # return the value of each piece\n\n\n :return: value of the piece (by his type + location)\n :rtype: int\n \"\"\"\n # endregion\n\n if value == 0:\n return 0\n\n # black\n if value < 0:\n return -(self.piece_nikud_dict.get(abs(value)) + self.location_nikud_dict.get(value)[y][x])\n\n # white\n else:\n return self.piece_nikud_dict.get(abs(value)) + self.location_nikud_dict.get(value)[y][x]\n\n def create_location_dictionary(self):\n\n # region info\n \"\"\"\n # Logical arrays which help to point the reward of each move (by location on the board)\n\n\n :return: Nothing\n :rtype: None\n \"\"\"\n # endregion\n\n temp = 0\n\n # 1\n pawnEvalWhite = \\\n [\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0],\n [1.0, 1.0, 2.0, 3.0, 3.0, 2.0, 1.0, 1.0],\n [0.5, 0.5, 1.0, 2.5, 2.5, 1.0, 0.5, 0.5],\n [0.0, 0.0, 0.0, 2.0, 2.0, 0.0, 0.0, 0.0],\n [0.5, -0.5, -1.0, 0.0, 0.0, -1.0, -0.5, 0.5],\n [0.5, 1.0, 1.0, -2.0, -2.0, 1.0, 1.0, 0.5],\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n ]\n\n\n # -1\n\n pawnEvalBlack = Tools.reverse_2d_list(pawnEvalWhite)\n\n\n # 2 / -2\n knightEval = \\\n [\n [-5.0, -4.0, -3.0, -3.0, -3.0, -3.0, -4.0, -5.0],\n [-4.0, -2.0, 0.0, 0.0, 0.0, 0.0, -2.0, -4.0],\n [-3.0, 0.0, 1.0, 1.5, 1.5, 1.0, 0.0, -3.0],\n [-3.0, 0.5, 1.5, 2.0, 2.0, 1.5, 0.5, -3.0],\n [-3.0, 0.0, 1.5, 2.0, 2.0, 1.5, 0.0, -3.0],\n [-3.0, 0.5, 1.0, 1.5, 1.5, 1.0, 0.5, -3.0],\n [-4.0, -2.0, 0.0, 0.5, 0.5, 0.0, -2.0, -4.0],\n [-5.0, -4.0, -3.0, -3.0, -3.0, -3.0, -4.0, -5.0]\n ]\n\n # 3\n bishopEvalWhite = \\\n [\n [-2.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -2.0],\n [-1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0],\n [-1.0, 0.0, 0.5, 1.0, 1.0, 0.5, 0.0, -1.0],\n [-1.0, 0.5, 0.5, 1.0, 1.0, 0.5, 0.5, -1.0],\n [-1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, -1.0],\n [-1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0],\n [-1.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, -1.0],\n [-2.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -2.0]\n ]\n\n # -3\n\n\n bishopEvalBlack = Tools.reverse_2d_list(bishopEvalWhite)\n\n # 4\n rookEvalWhite = \\\n [\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [0.5, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.5],\n [-0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.5],\n [-0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.5],\n [-0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.5],\n [-0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.5],\n [-0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.5],\n [0.0, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0]\n ]\n\n # -4\n\n rookEvalBlack = Tools.reverse_2d_list(rookEvalWhite)\n\n # 5 / -5\n evalQueen = \\\n [\n [-2.0, -1.0, -1.0, -0.5, -0.5, -1.0, -1.0, -2.0],\n [-1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0],\n [-1.0, 0.0, 0.5, 0.5, 0.5, 0.5, 0.0, -1.0],\n [-0.5, 0.0, 0.5, 0.5, 0.5, 0.5, 0.0, -0.5],\n [0.0, 0.0, 0.5, 0.5, 0.5, 0.5, 0.0, -0.5],\n [-1.0, 0.5, 0.5, 0.5, 0.5, 0.5, 0.0, -1.0],\n [-1.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, -1.0],\n [-2.0, -1.0, -1.0, -0.5, -0.5, -1.0, -1.0, -2.0]\n ]\n\n # 6\n kingEvalWhite = \\\n [\n [-3.0, -4.0, -4.0, -5.0, -5.0, -4.0, -4.0, -3.0],\n [-3.0, -4.0, -4.0, -5.0, -5.0, -4.0, -4.0, -3.0],\n [-3.0, -4.0, -4.0, -5.0, -5.0, -4.0, -4.0, -3.0],\n [-3.0, -4.0, -4.0, -5.0, -5.0, -4.0, -4.0, -3.0],\n [-2.0, -3.0, -3.0, -4.0, -4.0, -3.0, -3.0, -2.0],\n [-1.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -1.0],\n [2.0, 2.0, 0.0, 0.0, 0.0, 0.0, 2.0, 2.0],\n [2.0, 3.0, 1.0, 0.0, 0.0, 1.0, 3.0, 2.0]\n ]\n\n # -6\n\n kingEvalBlack = Tools.reverse_2d_list(kingEvalWhite)\n\n nikud_dict = \\\n {\n 1: pawnEvalWhite,\n 2: rookEvalWhite,\n 3: knightEval,\n 4: bishopEvalWhite,\n 5: evalQueen,\n 6: kingEvalWhite,\n\n -1: pawnEvalBlack,\n -2: rookEvalBlack,\n -3: knightEval,\n -4: bishopEvalBlack,\n -5: evalQueen,\n -6: kingEvalBlack\n\n }\n\n '''\n 1: pawnEvalWhite,\n 2: knightEval,\n 3: bishopEvalWhite,\n 4: rookEvalWhite,\n 5: evalQueen,\n 6: kingEvalWhite,\n\n -1: pawnEvalBlack,\n -2: knightEval,\n -3: bishopEvalBlack,\n -4: rookEvalBlack,\n -5: evalQueen,\n -6: kingEvalBlack\n '''\n\n return nikud_dict\n\n # endregion\n\n def create_piece_dictionary(self):\n\n # region info\n \"\"\"\n # create a dictionary for the pieces points (base on the soldier type)\n\n\n :return: Nothing\n :rtype: None\n \"\"\"\n # endregion\n\n nikud_dict = \\\n {\n 1: 10,\n 2: 50,\n 3: 30,\n 4: 30,\n 5: 90,\n 6: 900\n\n }\n\n return nikud_dict\n\n def set_optimiser(self):\n\n # region info\n \"\"\"\n # define the value to be 1 or -1 to change from negative and positive values for the evaluted boards in the NegaMax AI becuase when there are even\n # depth returns on even the -value of the board we dont want, so we have to modify the value. if it is not even it returns + value, like I need\n\n\n :return: value of the state of the board\n :rtype: int\n \"\"\"\n # endregion\n\n if S_T.AI_DEPTH % 2 == 0:\n return -1\n else:\n return 1\n # endregion\n\n# class which is responsibles for the test player (can be smart AI with nega max brain or just random move, whatever I choose to test and find)\nclass TestPlayer(object):\n\n # region Constructer\n def __init__(self, model, ai):\n\n # region info\n \"\"\"\n This Class is pretty simple.\n It has connection to a smart player (Nega Max) and the model.\n The purpose of this class is to test different type of computer players.\n Can be smart (NegaMax brain or random one). I chose in this case it will be\n stupid (random).\n\n :param self.model: the connection to the model class.\n :type self.model: Model\n :param self.ai: class which is about the smart moves of the computer (Nega Max)\n :type self.ai: AI\n\n\n\n\n :return: Nothing\n :rtype: None\n \"\"\"\n # endregion\n\n self.model = model\n self.ai = ai\n\n # endregion\n\n # region Methods\n\n # make the test player make his move based on what logic I want it to do (In this case random move)\n def play_test_player(self, turn):\n\n new_game_places, new_game_moves = Tools.all_soldiers_moves(turn, self.model, self.model.get_board())\n new_game_places, new_game_moves = Tools.convert_to_one_dimensional_lists(new_game_places, new_game_moves)\n\n if new_game_places != []:\n\n if len(new_game_moves) > 0:\n random_index = int(random.randint(0, (len(new_game_moves)-1)))\n else:\n random_index = 0\n\n return new_game_places[random_index], new_game_moves[random_index]\n\n return [], []\n\n # endregion","sub_path":"Chess/LogicObjects/Computer.py","file_name":"Computer.py","file_ext":"py","file_size_in_byte":26339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"507341801","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 19 12:03:59 2018\n\n@author: mariarodriguez\n\"\"\"\n\nimport distinct_verbs\n\n\ndef match_verbs(match_i, match_r, match_err, no_i, no_r, v_dist_i, v_dist_r, list_irr, list_reg, child_line):\n \"\"\"\n This fonction checks if a verb is regular or irregular.\n Then it proceeds to the Tolerance principle calculation.\n\n Parameters\n -----------\n match_i, match_r: store regex results for regular and irregular verbs\n match_err: store regex results for errors in the corpus\n no_i, no_r: counters for irregular and regular verbs\n v_dist_i, v_dist_r: store distincts irregular and regular verbs in lists\n list_irr, list_reg: lists of irregulars and regulars verbs created to check\n the quality of verbs annotation.\n child_line: store the child's line\n\n Output\n -----------\n no_i, no_r: counters for irregular and regular verbs\n\n \"\"\"\n irr = False\n if match_i:\n for i in range(len(match_i)):\n if match_i[0][0] in list_irr:\n irr = True\n verb_root = match_i[0][0]\n no_i, no_r = distinct_verbs.dist_verbs(irr, no_i, no_r, match_i, match_r, match_err, v_dist_i, verb_root, child_line)\n if match_i[0][0] in list_reg:\n print(\"ANNOTE COMME IRR MAIS DANS LIST REG --> \", match_i[0][0])\n irr = False #enlever le commentaire pour Eve, Sarah et Abe\n verb_root = match_i[0][0]\n no_i, no_r = distinct_verbs.dist_verbs(irr, no_i, no_r, match_i, match_r, match_err, v_dist_i, verb_root, child_line)\n if match_r:\n for i in range(len(match_r)):\n if match_r[0][0] in list_reg:\n verb_root = match_r[0][0]\n no_i, no_r = distinct_verbs.dist_verbs(irr, no_i, no_r, match_i, match_r, match_err, v_dist_r, verb_root, child_line)\n if match_r[0][0] in list_irr:\n print(\"ANNOTE COMME REG MAIS DANS LIST IRR --> \", match_r[0][0])\n irr = True #enlever le commentaire pour Eve, Sarah et Abe\n verb_root = match_r[0][0]\n no_i, no_r = distinct_verbs.dist_verbs(irr, no_i, no_r, match_i, match_r, match_err, v_dist_r, verb_root, child_line) \n return no_i, no_r\n","sub_path":"code/matching_verbs.py","file_name":"matching_verbs.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"357145700","text":"import smtplib\n\nimport config\n\nlog = open('status.log', 'r')\n\nheaders = f\"\"\"From: Office Notifications <{config.smtp_sendfrom}>\nTo: <{config.smtp_sendto}>\nSubject: Emergency SMS Sent\n\"\"\"\n\ndef send():\n # Istantiate smtplib & log in if needed \n # SMTP_SSL is used here -- allow configuration for insecure SMTP servers later?\n \n msg = f\"\"\"{headers}\nSMS message was sent out saying:\n\n'{config.body}'\n\nLog:\n\n{log.read()}\"\"\"\n \n try: \n notify = smtplib.SMTP(host=config.smtp_host, port=config.smtp_port)\n if config.smtp_auth_req == 1:\n notify.login(config.smtp_username, config.smtp_password)\n notify.sendmail(config.smtp_sendfrom, config.smtp_sendto, msg)\n print('Notification sent.')\n\n except:\n print('Failed to send notification.')\n exit(1)\n\n# send('Test')","sub_path":"smtp.py","file_name":"smtp.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"497237341","text":"alpha = [0]*26\nword = input().upper()\nfor i in range(len(word)):\n alpha[ord(word[i])-ord(\"A\")] += 1\n\nmax = 0\nalphaList = []\nfor i in range(26):\n if alpha[i] > max:\n alphaList.clear()\n max = alpha[i]\n alphaList.append(i)\n elif alpha[i] == max:\n alphaList.append(i)\n\nif not len(alphaList) == 1:\n print(\"?\")\nelse:\n print(chr(alphaList[0]+ord(\"A\")))","sub_path":"Python_workspace/1100/1157.py","file_name":"1157.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"91847905","text":"a=0\nkullanıcıadı=input(\"KULLANICI ADINIZI GİRİNİZ : \")\nif(kullanıcıadı==\"my\"):\n while True:\n pword=input(\"ŞİFRENİZİ GİRİNİZ : \")\n if(pword==\"123456\"):\n print(\"SİSTEME GİRDİNİZ.\")\n break\n else:\n print(\"ŞİFRENİZİ YANLIŞ GİRDİNİZ\")\n a+=1\n if(a==3):\n print(\"3 KERE YANLIŞ GİRİŞ YAPTINIZ.\\nBİR SÜRE SONRA TEKRAR DENEYİNİZ\")\n break\n continue\nelse:\n print(\"SİSTEMDE KAYDINIZ BULUNMAMAKTADIR\")\n print(\"SİSTEME KAYIT YAPTIRABİLİRSİNİZ\")\n","sub_path":"Homeworks/HW3.py","file_name":"HW3.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"84772521","text":"from basics import mean, variance, covariance\n\n\ndef fit_single_linear_regression(x: list, y: list) -> dict:\n \"\"\"\n Fits a single linear regression in the format y = mx + b\n :param x: list of predictor values\n :param y: list of target values\n :return: dict of {'m': float, 'b': float} where m is the slope and b is the y-intercept\n \"\"\"\n m = covariance(data_x=x, data_y=y) / variance(data=x)\n b = mean(y) - m * mean(x)\n coefficients = {\n 'm': m,\n 'b': b\n }\n return coefficients\n\n\ndef predict_single_linear_regression(x: list, model: dict) -> list:\n \"\"\"\n Utilizes model format y = mx + b where we are given predictors\n :param x: list of predictors\n :param model: dict of results of fit_single_linear_regression\n :return: list of predicted outputs\n \"\"\"\n predicted_y = [model['m']*i + model['b'] for i in x]\n return predicted_y\n","sub_path":"single_linear_regression.py","file_name":"single_linear_regression.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"576279253","text":"#Ashena Gorgan Mohammadi, 610394128\n\nimport sys\n\nclass Node:\n def __init__(self, d, l = None):\n self.data = d\n self.link = l\n\n\nclass CircularLinkedList:\n def __init__(self):\n self.head = None\n\n def insert(self, data):\n if(self.head is None):\n self.head = Node(data)\n self.head.link = self.head\n else:\n node = self.head\n while(node.link != self.head):\n node = node.link\n node.link = Node(data, self.head)\n\n\ndef gas_station_traverse(stations):\n node = stations.head\n position = 1\n gas_required = sys.maxsize\n gas_consumption = 0\n current_pos = 1\n while(True):\n gas_consumption += node.data[0] - node.data[1]\n if(gas_consumption < gas_required):\n if(node.data[0] - node.data[1] >= 0):\n gas_required = gas_consumption\n position = current_pos\n node = node.link\n current_pos += 1\n if(node == stations.head):\n break\n if(gas_consumption >= 0):\n return(position)\n else:\n return 0\n\n\nstations = CircularLinkedList()\nn = int(input('Enter number of gas stations: '))\nprint('In next', n, 'rows, enter gas amount and distance from next station in order:')\nfor i in range(n):\n stations.insert(tuple(int(x.strip()) for x in input().split()))\nans = gas_station_traverse(stations)\nif(ans != 0):\n print('You should start from gas station NO.', ans)\nelse:\n print('IMPOSSIBLE!')","sub_path":"gas_station_problem.py","file_name":"gas_station_problem.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"42722832","text":"import time\n\nuser = \"asd\"\nstrlist = []\nstrset = set()\nstrdict = {}\n\nsrno = 1\nfor i in user:\n strlist.append(i)\n strset.add(i)\n strdict[user.index(i)] = i\n\n #time.sleep(0.30)\n print('{}.{} is added into list at position no :{}.'.format(srno,i,user.index(i)))\n srno+1\n\nfor i in range(0,5):\n #time.sleep(1)\n print(\"/\")\nprint('String List:',strlist)\nprint('String Set:',strset)\nprint('String Dictionary:',strdict)\n\n\nname = 'nitin gharge'\nprint(name)","sub_path":"stringsOp.py","file_name":"stringsOp.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"592204959","text":"\nimport sys\n\nsys.path.append('/home/h1/decha/Dropbox/python_workspace/Utility/')\n\nsys.path.append('../')\n\nfrom tool_box.util.utility import Utility\nfrom tool_box.distortion.distortion_utility import Distortion\n\nfrom PoG_Utility.pog_utility import PoGUtility\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom scipy.fftpack import dct, idct\n\ndef gen_mean_and_cov_of_dct(names):\n\n mean = np.array([])\n\n for n in names:\n # print n\n if n in syllable_dct_dict:\n data = syllable_dct_dict[n][0:num_coeff]\n\n else:\n data = np.zeros((num_coeff, 3))\n # data.fill(unvoice)\n data.fill(0)\n # data = np.column_stack(\n # (\n # dct(data[:,0], norm='ortho'), \n # dct(data[:,1], norm='ortho'), \n # dct(data[:,2], norm='ortho')\n # )\n # )\n # print data\n # sys.exit()\n\n if len(mean) == 0:\n mean = data\n else:\n mean = np.concatenate((mean, data))\n\n cov = np.identity(mean.shape[0])\n\n return (mean, cov)\n\n pass\n\ndef gen_W(number_of_frame, dur_list, num_coeff):\n\n w = np.zeros( (num_coeff*len(dur_list), number_of_frame) )\n\n offset_x = 0\n offset_y = 0\n\n for idx, d in enumerate(dur_list):\n\n if idx == (len(dur_list)-1):\n d = number_of_frame-offset_x\n\n local_w = PoGUtility.generate_W_for_DCT(d, num_coeff)\n\n # print offset_x, offset_y, local_w.shape \n\n for i in range(num_coeff):\n w[offset_y+i][offset_x:offset_x+d] = local_w[i]\n\n offset_x = offset_x + d\n offset_y = offset_y + num_coeff\n\n return w\n\n pass\n\ndef gen_dur_and_name_list(label_path, name):\n dur_list = []\n names = []\n for idx, line in enumerate(Utility.read_file_line_by_line(label_path)):\n spl = Utility.trim(line).split(' ')\n\n frame = int(spl[1]) - int(spl[0])\n frame = frame/50000\n\n dur_list.append(frame)\n\n names.append('{}_{}'.format(name, (idx+1) ))\n\n return (dur_list, names)\n\ndef cal_PoG(config):\n\n base_path = config['base_path']\n label_path = config['label_path']\n name = config['name']\n outfilepath = config['outfilepath']\n\n lf0_mean = np.load('{}/mean.npy'.format(base_path))\n\n # print lf0_mean[1000]\n\n lf0_cov = np.load('{}/cov.npy'.format(base_path))\n\n dur_list, names = gen_dur_and_name_list(label_path, name)\n\n w = gen_W(len(lf0_mean), dur_list, num_coeff)\n\n syllable_mean, syllable_cov = gen_mean_and_cov_of_dct(names)\n\n # print w.shape, syllable_mean.shape, syllable_cov.shape, lf0_mean.shape, lf0_cov.shape\n\n mean, cov = PoGUtility.cal_mean_variance_of_product_of_gaussian(w, syllable_mean, syllable_cov, lf0_mean, lf0_cov, alpha=alpha, beta=beta)\n\n # print mean.shape, cov.shape\n # print mean[1000]\n\n np.save('{}/mean.npy'.format(outfilepath), mean)\n np.save('{}/cov.npy'.format(outfilepath), cov)\n\n pass\n\nif __name__ == '__main__':\n\n unvoice = -1.00000000e+10\n\n syllable_dct_dict = Utility.load_obj('/work/w2/decha/Data/GPR_speccom_data/Interspeech2017/syllable_dct_with_delta_dictionary.pkl')\n\n num_coeff = 7\n\n syl_duration_path = '/work/w2/decha/Data/GPR_speccom_data/00_syllable_level_data/mono/tsc/sd/j/'\n\n frame_predicted_lf0_path = '/work/w16/decha/decha_w16/spec_com_work_space/Speech_synthesis/05a_GPR/testrun/out/tsc/a-i/infer/a-i/demo/seed-00/M-1024/B-1024/num_iters-5/lf0/predictive_distribution/'\n\n basename = 'tscsdj'\n\n a_start = 1.6\n a_end = 1.9\n\n b_start = 0.1\n b_end = 2.0\n\n for alpha in np.arange(a_start, a_end, 0.1):\n for beta in np.arange(b_start, b_end, 0.1):\n\n outpath = '/work/w21/decha/Interspeech_2017/Result/03_Given_syllable_dct_with_weigth/num_dct_cov_{}/alpha_{}_beta_{}/'.format(num_coeff, alpha, beta)\n Utility.make_directory(outpath)\n\n for num in range(1, 51):\n\n name = '{}{}'.format(basename, Utility.fill_zero(num, 2)) \n\n outfilepath = '{}/{}/'.format(outpath, name)\n Utility.make_directory(outfilepath)\n\n base_path = '{}/{}/'.format( frame_predicted_lf0_path, name )\n label_path = '{}/{}.lab'.format( syl_duration_path, name )\n\n config = {\n 'base_path' : base_path,\n 'label_path' : label_path,\n 'name' : name,\n 'outfilepath' : outfilepath\n }\n\n cal_PoG(config)\n\n # sys.exit()\n\n pass\n","sub_path":"Products_of_Gaussian/02_Product_of_gaussian/run_separate_alpha_beta/run_alpha_1.6_1.8_beta.py","file_name":"run_alpha_1.6_1.8_beta.py","file_ext":"py","file_size_in_byte":4598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"368456510","text":"from celery.execute import send_task\nfrom django.contrib import admin\nfrom djcelery import admin as djcelery_admin\nfrom djcelery.models import PeriodicTask\n\nclass ExtendedPeriodicTaskAdmin(djcelery_admin.PeriodicTaskAdmin):\n actions = djcelery_admin.PeriodicTaskAdmin.actions + ['run_task']\n\n def run_task(self, request, queryset):\n if request.user.is_superuser:\n for task in queryset.all():\n send_task(task.task)\n self.message = 'Tasks are running'\n else:\n self.message = 'You must be a superuser to perform this action.'\n run_task.short_description = 'Run Task'\n\nadmin.site.unregister(PeriodicTask)\nadmin.site.register(PeriodicTask, ExtendedPeriodicTaskAdmin)\n\n","sub_path":"celery_admin/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"601220355","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2013 IBM Corp.\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 uuid\n\nfrom keystone import notifications\nfrom keystone.openstack.common.fixture import moxstubout\nfrom keystone.openstack.common.notifier import api as notifier_api\nfrom keystone import tests\nfrom keystone.tests import test_v3\n\n\nEXP_RESOURCE_TYPE = uuid.uuid4().hex\n\n\nclass ArbitraryException(Exception):\n pass\n\n\nclass NotificationsWrapperTestCase(tests.TestCase):\n def setUp(self):\n super(NotificationsWrapperTestCase, self).setUp()\n\n self.exp_resource_id = None\n self.exp_operation = None\n self.exp_host = None\n self.send_notification_called = False\n\n def fake_notify(operation, resource_type, resource_id, host=None):\n self.assertEqual(self.exp_operation, operation)\n self.assertEqual(EXP_RESOURCE_TYPE, resource_type)\n self.assertEqual(self.exp_resource_id, resource_id)\n self.assertEqual(self.exp_host, host)\n self.send_notification_called = True\n\n fixture = self.useFixture(moxstubout.MoxStubout())\n self.stubs = fixture.stubs\n\n self.stubs.Set(notifications, '_send_notification', fake_notify)\n\n @notifications.created(EXP_RESOURCE_TYPE)\n def create_resource(self, resource_id, data):\n return data\n\n def test_resource_created_notification(self):\n self.exp_operation = 'created'\n self.exp_resource_id = uuid.uuid4().hex\n exp_resource_data = {\n 'id': self.exp_resource_id,\n 'key': uuid.uuid4().hex}\n self.exp_host = None\n\n self.create_resource(self.exp_resource_id, exp_resource_data)\n self.assertTrue(self.send_notification_called)\n\n @notifications.updated(EXP_RESOURCE_TYPE)\n def update_resource(self, resource_id, data):\n return data\n\n def test_resource_updated_notification(self):\n self.exp_operation = 'updated'\n self.exp_resource_id = uuid.uuid4().hex\n exp_resource_data = {\n 'id': self.exp_resource_id,\n 'key': uuid.uuid4().hex}\n self.exp_host = None\n\n self.update_resource(self.exp_resource_id, exp_resource_data)\n self.assertTrue(self.send_notification_called)\n\n @notifications.deleted(EXP_RESOURCE_TYPE)\n def delete_resource(self, resource_id):\n pass\n\n def test_resource_deleted_notification(self):\n self.exp_operation = 'deleted'\n self.exp_resource_id = uuid.uuid4().hex\n self.exp_host = None\n\n self.delete_resource(self.exp_resource_id)\n self.assertTrue(self.send_notification_called)\n\n @notifications.created(EXP_RESOURCE_TYPE)\n def create_exception(self, resource_id):\n raise ArbitraryException()\n\n def test_create_exception_without_notification(self):\n self.assertRaises(\n ArbitraryException, self.create_exception, uuid.uuid4().hex)\n self.assertFalse(self.send_notification_called)\n\n @notifications.created(EXP_RESOURCE_TYPE)\n def update_exception(self, resource_id):\n raise ArbitraryException()\n\n def test_update_exception_without_notification(self):\n self.assertRaises(\n ArbitraryException, self.update_exception, uuid.uuid4().hex)\n self.assertFalse(self.send_notification_called)\n\n @notifications.deleted(EXP_RESOURCE_TYPE)\n def delete_exception(self, resource_id):\n raise ArbitraryException()\n\n def test_delete_exception_without_notification(self):\n self.assertRaises(\n ArbitraryException, self.delete_exception, uuid.uuid4().hex)\n self.assertFalse(self.send_notification_called)\n\n\nclass NotificationsTestCase(tests.TestCase):\n def setUp(self):\n super(NotificationsTestCase, self).setUp()\n fixture = self.useFixture(moxstubout.MoxStubout())\n self.stubs = fixture.stubs\n\n def test_send_notification(self):\n \"\"\"Test the private method _send_notification to ensure event_type,\n payload, and context are built and passed properly.\n \"\"\"\n\n resource = uuid.uuid4().hex\n resource_type = EXP_RESOURCE_TYPE\n operation = 'created'\n host = None\n\n # NOTE(ldbragst): Even though notifications._send_notification doesn't\n # contain logic that creates cases, this is suppose to test that\n # context is always empty and that we ensure the resource ID of the\n # resource in the notification is contained in the payload. It was\n # agreed that context should be empty in Keystone's case, which is\n # also noted in the /keystone/notifications.py module. This test\n # ensures and maintains these conditions.\n def fake_notify(context, publisher_id, event_type, priority, payload):\n exp_event_type = 'identity.project.created'\n self.assertEqual(exp_event_type, event_type)\n exp_context = {}\n self.assertEqual(exp_context, context)\n exp_payload = {'resource_info': 'some_resource_id'}\n self.assertEqual(exp_payload, payload)\n\n self.stubs.Set(notifier_api, 'notify', fake_notify)\n notifications._send_notification(resource, resource_type, operation,\n host=host)\n\n\nclass NotificationsForEntities(test_v3.RestfulTestCase):\n def setUp(self):\n super(NotificationsForEntities, self).setUp()\n\n self.exp_resource_id = None\n self.exp_operation = None\n self.exp_resource_type = None\n self.send_notification_called = False\n\n def fake_notify(operation, resource_type, resource_id, host=None):\n self.exp_resource_id = resource_id\n self.exp_operation = operation\n self.exp_resource_type = resource_type\n self.send_notification_called = True\n\n fixture = self.useFixture(moxstubout.MoxStubout())\n self.stubs = fixture.stubs\n\n self.stubs.Set(notifications, '_send_notification', fake_notify)\n\n def _assertLastNotify(self, resource_id, operation, resource_type):\n self.assertIs(self.exp_operation, operation)\n self.assertIs(self.exp_resource_id, resource_id)\n self.assertIs(self.exp_resource_type, resource_type)\n self.assertTrue(self.send_notification_called)\n\n def test_create_group(self):\n group_ref = self.new_group_ref(domain_id=self.domain_id)\n self.identity_api.create_group(group_ref['id'], group_ref)\n self._assertLastNotify(group_ref['id'], 'created', 'group')\n\n def test_create_project(self):\n project_ref = self.new_project_ref(domain_id=self.domain_id)\n self.assignment_api.create_project(project_ref['id'], project_ref)\n self._assertLastNotify(project_ref['id'], 'created', 'project')\n\n def test_create_role(self):\n role_ref = self.new_role_ref()\n self.assignment_api.create_role(role_ref['id'], role_ref)\n self._assertLastNotify(role_ref['id'], 'created', 'role')\n\n def test_create_user(self):\n user_ref = self.new_user_ref(domain_id=self.domain_id)\n self.identity_api.create_user(user_ref['id'], user_ref)\n self._assertLastNotify(user_ref['id'], 'created', 'user')\n\n def test_delete_group(self):\n group_ref = self.new_group_ref(domain_id=self.domain_id)\n self.identity_api.create_group(group_ref['id'], group_ref)\n self.identity_api.delete_group(group_ref['id'])\n self._assertLastNotify(group_ref['id'], 'deleted', 'group')\n\n def test_delete_project(self):\n project_ref = self.new_project_ref(domain_id=self.domain_id)\n self.assignment_api.create_project(project_ref['id'], project_ref)\n self.assignment_api.delete_project(project_ref['id'])\n self._assertLastNotify(project_ref['id'], 'deleted', 'project')\n\n def test_delete_role(self):\n role_ref = self.new_role_ref()\n self.assignment_api.create_role(role_ref['id'], role_ref)\n self.assignment_api.delete_role(role_ref['id'])\n self._assertLastNotify(role_ref['id'], 'deleted', 'role')\n\n def test_delete_user(self):\n user_ref = self.new_user_ref(domain_id=self.domain_id)\n self.identity_api.create_user(user_ref['id'], user_ref)\n self.identity_api.delete_user(user_ref['id'])\n self._assertLastNotify(user_ref['id'], 'deleted', 'user')\n\n def test_update_group(self):\n group_ref = self.new_group_ref(domain_id=self.domain_id)\n self.identity_api.create_group(group_ref['id'], group_ref)\n self.identity_api.update_group(group_ref['id'], group_ref)\n self._assertLastNotify(group_ref['id'], 'updated', 'group')\n\n def test_update_project(self):\n project_ref = self.new_project_ref(domain_id=self.domain_id)\n self.assignment_api.create_project(project_ref['id'], project_ref)\n self.assignment_api.update_project(project_ref['id'], project_ref)\n self._assertLastNotify(project_ref['id'], 'updated', 'project')\n\n def test_update_role(self):\n role_ref = self.new_role_ref()\n self.assignment_api.create_role(role_ref['id'], role_ref)\n self.assignment_api.update_role(role_ref['id'], role_ref)\n self._assertLastNotify(role_ref['id'], 'updated', 'role')\n\n def test_update_user(self):\n user_ref = self.new_user_ref(domain_id=self.domain_id)\n self.identity_api.create_user(user_ref['id'], user_ref)\n self.identity_api.update_user(user_ref['id'], user_ref)\n self._assertLastNotify(user_ref['id'], 'updated', 'user')\n","sub_path":"swift/source/keystone/keystone/tests/test_notifications.py","file_name":"test_notifications.py","file_ext":"py","file_size_in_byte":10086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"652845100","text":"# -*- coding: utf-8 -*-\n\"\"\"Exercise 3.\n\nSplit the dataset based on the given ratio.\n\"\"\"\n\n\nimport numpy as np\n\n\ndef split_data(x, y, ratio, seed=1):\n \"\"\"\n split the dataset based on the split ratio. If ratio is 0.8 \n you will have 80% of your data set dedicated to training \n and the rest dedicated to testing\n \"\"\"\n # set seed\n np.random.seed(seed)\n data_size = x.shape[0]\n training_indices = np.random.choice(data_size, int(data_size * ratio), replace=False)\n test_indices = np.delete(np.array(range(data_size)), training_indices) \n return x[training_indices], y[training_indices], x[test_indices], y[test_indices]\n","sub_path":"labs/ex04/template/split_data.py","file_name":"split_data.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"141161577","text":"import numpy as np\nimport pandas as pd\nfrom trendmaster import trend\nimport pickle\nfrom statsmodels.tsa import stattools\n\nvarDict = input(\"Pickle dictionary filename (with .pkl extention):\")\nname = input(\"Variable name:\")\nperiod = input(\"Number of years in period:\")\n\ndef openDict(filename):\n \"\"\"\n Opens dictionary from pickle file in working directory.\n \n Parameters\n ----------\n filename: str\n filename with .pkl ending\n \n Returns\n -------\n dictionary\n \"\"\"\n pickle_in = open(f\"{filename}\",\"rb\")\n loadedDict = pickle.load(pickle_in)\n return loadedDict\n\nfinal = openDict(\"finalSelectionList.pkl\")\n\ndef reshapeToArray(data,MA,fullList):\n \"\"\"\n Reshapes moving average smoothed data from dictionary to array.\n \n Parameters\n ----------\n data: dictionary\n for a certain region, containing 30 year timeseries for different moving averages\n MA: str\n {\"5day\",\"10day\",\"30day\"}\n \n Returns\n -------\n numpy.array\n array of shape (doy,year,catchment) with the catchments ordered by altitude\n \"\"\"\n doy = np.arange(365)\n start = 2013-int(period)\n years = np.arange(start,2013)\n catchments = list(data.keys())\n x = len(fullList)\n # array with shape: doy,year,catchment\n arr = np.full((len(doy),len(years),x),np.nan)\n \n if period == \"30\":\n # filling array\n for c in range(x):\n for y in years:\n for d in doy:\n arr[d,y-start,c] = data[fullList[c]][MA][f\"{y}\"][d]\n \n if period == \"50\":\n # filling array\n for c in range(x):\n if fullList[c] in catchments:\n for y in years:\n for d in doy:\n arr[d,y-start,c] = data[fullList[c]][MA][f\"{y}\"][d]\n else:\n for y in years:\n for d in doy:\n arr[d,y-start,c] = -99\n return(arr)\n\ndef autocorrTest(ts,alpha=0.05):\n \"\"\"\n Ljung-Box test for significant autocorrelation in a time series.\n \"\"\"\n acf, qstat, p = stattools.acf(ts,qstat=True,nlags=1)\n p = p[0]\n sign = p < alpha\n return sign\n\ndef prewhiten(ts):\n \"\"\"\n Pre-whitening procedure of a time series.\n \n After Wang&Swail, 2001:\n https://doi.org/10.1175/1520-0442(2001)014%3C2204:COEWHI%3E2.0.CO;2\n \"\"\"\n r = stattools.acf(ts,nlags=1)[1]\n pw = ts.copy()\n for i in range(ts.shape[0]-1):\n if i > 0:\n pw[i] = (ts[i] - r*ts[i-1])/(1 - r)\n return pw\n\ndef trendMagnitude(array,alpha=0.1):\n \"\"\"\n Calculated the trend magnitude for each doy if a significant trend is detected\n \n Parameters\n ----------\n array: numpy.array\n array of shape: (doy,year,catchment) containing data to be analysed\n \n Returns\n -------\n numpy.array\n array of trend magnitude, shape: (catchments,doy)\n \"\"\"\n output = []\n for c in range(array.shape[2]):\n arr = array[:,:,c] # slicing array by catchment\n if (arr==-99).all():\n out = np.full(arr.shape[0],-99)\n else:\n out = np.full(arr.shape[0],np.nan) # create empty array\n for day in range(arr.shape[0]):\n ts = arr[day,:]\n if autocorrTest(ts):\n ts = prewhiten(ts)\n out[day] = trend.sen_slope(ts)\n output.append(out)\n return np.array(output)\n\ndef trendArrays(varDict,variable=name,averages=[\"5day\",\"10day\",\"30day\"]):\n \"\"\"\n Calculates trend arrays and saves them to .npy file in \"Results\" folder.\n \"\"\"\n for region in varDict.keys():\n print(\"-------------------------\")\n print(f\"Analysing region {region}.\")\n for MA in averages:\n array = reshapeToArray(varDict[region],MA,final[region][30])\n result = trendMagnitude(array)\n np.save(f\"Results/trendMagnitude_{variable}_{region}_{MA}_{period}years\",result)\n print(f\"\\t{MA} completed.\")\n print(f\"Region {region} complete.\")\n print(\"-------------------------\")\n print(\"Trend analysis complete.\")\n print(\"-------------------------\")\n\ndf = openDict(varDict) #open dictionary with data from spesific varaible\ntrendArrays(df) #analyse trends for all regions\n","sub_path":"runTrendMagnitude.py","file_name":"runTrendMagnitude.py","file_ext":"py","file_size_in_byte":4430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"425383848","text":"# -*- coding: utf-8 -*-\nimport sys\n\nif sys.version_info.major < 3:\n reload(sys)\nsys.setdefaultencoding('utf8')\n\nfrom flaskext.mysql import MySQL\nfrom flask import Flask, render_template, request,redirect, session, flash, url_for\n\n\napp = Flask(__name__, template_folder=\"templates/layout_1/LTR/default/full\")\napp.config['MYSQL_DATABASE_USER'] = 'pegue891_develop'\napp.config['MYSQL_DATABASE_PASSWORD'] = 'develop'\napp.config['MYSQL_DATABASE_DB'] = 'pegue891_4worktime'\napp.config['MYSQL_DATABASE_HOST'] = 'www.visiblenet.com.br'\napp.config['MYSQL_DATABASE_PORT'] = 3306\n\n\nmysql = MySQL()\nmysql.init_app(app)\n\n\n\nclass MainMenu:\n 'Classe para exibição do menú lateral esquerdo. A príncipio com dados mockados'\n\n def __init__(self, nome, icone, titulo, rota, submenu, flsub):\n self.nome = nome\n self.icone = icone\n self.titulo = titulo\n self.rota = rota\n self.submenu = submenu\n self.flsub = flsub\n\n class SubMenu():\n def __init__(self, nome, icone, rota):\n self.nome = nome\n self.icone = icone\n self.rota = rota\n\n\n#submenu de configurações\nitemSub1 = MainMenu.SubMenu(\"Cadastro de Empresas\", \"icon-office\", \"cadastro-empresa\")\nitemSub2 = MainMenu.SubMenu(\"Cadastro de Projetos\", \"icon-stack2\", \"cadastro-projeto\")\nitemSub3 = MainMenu.SubMenu(\"Cadastro de Equipes\", \"icon-collaboration\", \"cadastro-equipes\")\nitemSub4 = MainMenu.SubMenu(\"Cadastro de Usuários\", \"icon-users\", \"cadastro-usuarios\")\nitemSub5 = MainMenu.SubMenu(\"Cadastro de Menus\", \"icon-menu2\", \"cadastro-menus\")\n\n#submenu configuracões\nitemSub6 = MainMenu.SubMenu(\"Suas Integrações\", \"\", \"cadastro-menus\")\nitemSub7 = MainMenu.SubMenu(\"Projetos e tarefas permanentes\", \"\", \"cadastro-menus\")\nitemSub8 = MainMenu.SubMenu(\"Configurações dos usuários\", \"\", \"cadastro-menus\")\nitemSub9 = MainMenu.SubMenu(\"Configurações do Payoneer\", \"\", \"cadastro-menus\")\nitemSub10 = MainMenu.SubMenu(\"Cronogramas de trabalho\", \"\", \"cadastro-menus\")\n\n\n\n#subDashboard = None\nsubSupAdm = [itemSub1, itemSub2, itemSub3, itemSub4, itemSub5]\nsubConfiguracoes=[itemSub7, itemSub8, itemSub9, itemSub10, itemSub6]\n\n#menu de super admin\nitemMenu01 = MainMenu(\"Dashboard\", \" icon-graph\", \"Dashboard\", \"dashboard\", \"\", 0)\nitemMenu02 = MainMenu(\"Configurações\", \"icon-cog7\", \"Configurações do Sistema\", \"configuracao\", subConfiguracoes, 1)\nitemMenu03 = MainMenu(\"Super Admin Configurações\", \"icon-magic-wand\", \"Configurações do Sistema\", \"super-configuracao\", subSupAdm, 1)\nmenu = [itemMenu01, itemMenu02, itemMenu03]\n\n@app.route('/dashboard')\ndef dashboard():\n return render_template('main-menu.html', titulo='Dashboard', menu=menu, url='dashboard')\n\n@app.route('/')\ndef index():\n cursor = mysql.connect().cursor()\n cursor.execute(\"SELECT * FROM users\")\n data = cursor.fetchone()\n cursor.close()\n if data is None:\n return \"Username or Password is wrong\"\n else:\n return \"Logged in successfully\"\n #return redirect(url_for('dashboard'))\n\n\napp.run(debug=True, host='127.0.0.1', port=80)\n\n","sub_path":"4worktime/4wtApp.py","file_name":"4wtApp.py","file_ext":"py","file_size_in_byte":3060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"451180901","text":"#!/usr/bin/python3\n\"\"\"This is the databasestorage class for AirBnB\"\"\"\nimport models\nfrom models.base_model import BaseModel, Base\nfrom models.user import User\nfrom models.state import State\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.place import Place\nfrom models.review import Review\nfrom sqlalchemy import create_engine\nimport os\nfrom sqlalchemy.orm import sessionmaker, scoped_session\n\n\nclass DBStorage:\n \"\"\"This class store in databases the objects\"\"\"\n __session = None\n __engine = None\n\n def __init__(self):\n \"\"\"all begins here\"\"\"\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'\n .format(os.getenv('HBNB_MYSQL_USER'),\n os.getenv('HBNB_MYSQL_PWD'),\n os.getenv('HBNB_MYSQL_HOST'),\n os.getenv('HBNB_MYSQL_DB')),\n pool_pre_ping=True)\n if os.getenv('HBNB_ENV') == \"test\":\n Base.metadata.drop_all(self.__engine)\n\n def all(self, cls=None):\n \"\"\"returns a dictionary\n Return:\n returns a dictionary of __object\n \"\"\"\n a = dict()\n clasesitas = [\"State\", \"City\", \"User\", \"Place\", \"Review\", \"Amenity\"]\n # if cls != None:\n # objre = self.__session.query(cls.__name__).all()\n # print(\"Esto esta botando el all del datastorage\", objre)\n # for obj in objre:\n # print(\"en teoria esto es cada objeto\", obj.__dict__)\n # print(\"el id en teoria obj.id\", obj.id)\n # a[obj.id] = obj.to_dict()\n # else:\n for clase in clasesitas:\n objre = self.__session.query(eval(clase)).all()\n for obj in objre:\n # print(\"cada objeto cuando no hay clase\", obj.to_dict())\n # print(\"este es el objeto\", obj)\n a[type(obj).__name__+\".\"+obj.id] = obj\n # key = \"{}.{}\".format(type(obj).__name__, obj.id)\n return a\n\n def new(self, obj):\n \"\"\"sets __object to given obj\n Args:\n obj: given object\n \"\"\"\n if obj:\n self.__session.add(obj)\n\n def save(self):\n \"\"\"Commiting changes\n \"\"\"\n self.__session.commit()\n\n def reload(self):\n \"\"\"Create metadata for all\n \"\"\"\n Base.metadata.create_all(self.__engine)\n Session = sessionmaker(bind=self.__engine, expire_on_commit=False)\n session = scoped_session(Session)\n self.__session = session()\n\n def delete(self, obj=None):\n \"\"\"Delete object\"\"\"\n if obj is not None:\n self.__session.delete(obj)\n\n def close(self):\n \"\"\"remove session\"\"\"\n self.__session.close()\n","sub_path":"models/engine/db_storage.py","file_name":"db_storage.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"293052492","text":"# -*- coding: utf-8 -*-\nimport re\nimport django\nimport codecs\nimport json\nimport unicodecsv\nimport pygtrie\nfrom collections import defaultdict\ndjango.setup()\nfrom sefaria.model import *\n\nmaxrabbilen = 0\nwith open(\"RabbisNames.csv\", 'rb') as fin:\n tonorabbiscsv = unicodecsv.DictReader(fin)\n tonorabbis = pygtrie.Trie()\n for row in tonorabbiscsv:\n rabbiName = \"\"\n for i in range(1,11):\n tempName = row[\"Name{}\".format(i)]\n if not tempName:\n break\n if i > 1:\n rabbiName += \" \"\n rabbiName += tempName\n rabbiName = rabbiName.replace(\"ר'\", \"רבי\")\n if len(rabbiName) > maxrabbilen:\n maxrabbilen = len(rabbiName)\n tonorabbis[rabbiName] = 0\n\n pass\n\ndef get_rabbis_in_category(cat):\n\n\n for ind in library.get_indexes_in_category(cat):\n r = Ref(ind)\n vtitle = None\n if cat == 'Bavli':\n willy = 'William Davidson Edition - Aramaic'\n has_willy = len([v for v in r.version_list() if v['versionTitle'] == willy]) > 0\n if not has_willy:\n print('Skipping {}'.format(ind))\n vtitle = willy\n tc = TextChunk(Ref(ind), 'he', vtitle=vtitle)\n flat = tc.ja().flatten_to_array()\n for segment in flat:\n start = 0\n while start < len(segment):\n end = start + maxrabbilen - 1\n while end >= start:\n temp = segment[start:end + 1]\n has_node = tonorabbis.has_node(temp)\n if has_node == pygtrie.Trie.HAS_VALUE:\n tonorabbis[temp] += 1\n print('found {}'.format(temp))\n start = end\n break\n elif has_node == pygtrie.Trie.HAS_SUBTRIE:\n end -= 1\n else:\n break\n start += 1\n\n\n\nget_rabbis_in_category('Bavli')","sub_path":"research/topics/get_rabbis.py","file_name":"get_rabbis.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"108657188","text":"\n# 图片验证码的 redis 有效期,单位:秒\n\nIMAGE_CODE_REDIS_EXPIRES = 180\n\n# 短信验证码的 redis 有效期, 单位:秒\nSMS_CODE_REDIS_EXPIRES = 300\n\n# 发送短信验证码的redis 有效期,单位:秒\nSEND_SMS_CODE_INTERVAL = 60\n\n# 登录错误尝试次数\nLOGIN_ERROR_MAX_TIMES = 5\n\n# 登录错误限制的时间, 单位:秒\nLOGIN_ERROR_FORBID_TIME = 600\n\n# 设置fdfs存储服务器上nginx的IP和端口号\nFDFS_URL = 'http://192.168.1.103:8888/'\n\n# 设置fdfs使用的client.conf文件路径\n# FDFS_CLIENT_CONF = './utils/client.conf'\nFDFS_CLIENT_CONF = '/etc/fdfs/client.conf'\n\n# 城区信息的缓存时间, 单位:秒\nAREA_INFO_REDIS_CACHE_EXPIRES = 7200\n\n# 首页展示最多的房屋数量\nHOME_PAGE_MAX_HOUSES = 5\n\n# 首页房屋数据的Redis缓存时间,单位:秒\nHOME_PAGE_DATA_REDIS_EXPIRES = 7200\n\n# 房屋详情页展示的评论最大数\nHOUSE_DETAIL_COMMENT_DISPLAY_COUNTS = 30\n\n# 房屋详情页面数据Redis缓存时间,单位:秒\nHOUSE_DETAIL_REDIS_EXPIRE_SECOND = 7200\n\n# 房屋列表页面每页数据容量\nHOUSE_LIST_PAGE_CAPACITY = 2\n\n# 房屋列表页面页数缓存时间,单位秒\nHOUES_LIST_PAGE_REDIS_CACHE_EXPIRES = 7200\n","sub_path":"flask-ihome/ihome/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"480679569","text":"\"\"\"\nGraphing requires Matplotlib. Run the 2 statements below in cmd (Assuming Python has already been installed)\npy -m pip install -U pip setuptools\npy -m pip install matplotlib\n\"\"\"\n\nimport matplotlib.pyplot as plt #import the matplotlib library\nimport numpy as np\t\t\t\t#import the numpy extension\nfrom matplotlib.widgets import Button #import the button widget\nimport warnings\nwarnings.filterwarnings(\"ignore\") \n\ntry:\t\n\tfig, ax = plt.subplots()\t#Create a figure with a set of subplots already made\n\tplt.subplots_adjust(bottom=0.2) #Adjust the distance from the bottom of the graph to the bottom of the window\n\t#ax.set_axis_bgcolor('red')\n\t#plt.set_axis_bgcolor('red')\t\n\tax.patch.set_facecolor('#89CFF0')\n\t\n\tplt.grid(True)\n\tt = list(range(300))\t#x-axis data points\n\t\n\tp = np.sin(t) #represents power array\n\tv = np.array(t)\t#represents voltage array\n\ta = np.array(t)**2 #represents current array\n\t\t\n\tl, = plt.plot(t, p, lw =3)\t#plots a line on the axes with a linewidth of 3\n\t\n\t#The initial graph on startup will be a Power vs Time graph\n\tdisplayingCurrent = False\t#These 3 status variables indicate whether power, voltage or current data is being displayed\n\tdisplayingVoltage = False\t#and are used by the program when updating the graph to ensure that the correct \n\tdisplayingPower = True\t\t#dataset is being drawn\n\t\n\tax.set_xlim(0, 26)\t\t\t#The x and y limits for the Power vs Time graph is set\n\tax.set_ylim(0, 10)\n\ttxt = fig.text(0.4,0.95,' Power vs Time ',bbox=dict(facecolor='none', alpha=10,lw = 0),fontsize = 15)\t#title of graph\n\tyaxistxt = fig.text(0.05,0.6,'Power (Watts)',bbox=dict(facecolor='none', alpha=10,lw = 0),fontsize = 15,rotation = 'vertical')\t#y axis label of graph\t\n\tplt.xlabel('Data Points', fontsize = 15)\t#x-axis label of graph\n\t\n\t\n\n\tclass Index(object):\n\t\t#The 5 below functions are used to adjust the x-axis limits depending on the button that is pressed\n\t\tdef three_hundred(self, event):\t\t\t\n\t\t\tax.set_xlim(0, 301)\n\t\tdef two_hundred(self, event):\t\t\t\n\t\t\tax.set_xlim(0, 201)\n\t\tdef one_hundred(self, event):\t\t\t\n\t\t\tax.set_xlim(0, 101)\n\t\tdef fifty(self, event):\t\t\t\n\t\t\tax.set_xlim(0, 51)\n\t\tdef twenty_five(self, event):\t\t\t\n\t\t\tax.set_xlim(0, 26)\n\t\t\n\t\t#The 3 below functions are used to switch between power, voltage or current graphs depending on which button is pressed\n\t\tdef voltage(self,event):\n\t\t\tl.set_ydata(v)\t#sets the plot to display the voltage dataset\n\t\t\tax.set_ylim(0, 16)\t#sets the y-axis limits to the appropriate size for the voltage dataset\n\t\t\t\n\t\t\tfor txt in fig.texts: #Makes previously drawn text boxes disappear\n\t\t\t\ttxt.set_visible(False)\n\t\t\ttxt = fig.text(0.4,0.95,'Voltage vs Time',bbox=dict(facecolor='none', alpha=10,lw=0),fontsize = 15)\n\t\t\tyaxistxt = fig.text(0.05,0.6,'Voltage (Volts)',bbox=dict(facecolor='none', alpha=10,lw = 0),fontsize = 15,rotation = 'vertical')\n\t\t\t\n\t\t\tglobal displayingCurrent\t#sets the status variables to indicate to the program that it should now be plotting voltage data \n\t\t\tglobal displayingVoltage \n\t\t\tglobal displayingPower \n\t\t\tdisplayingCurrent = False\n\t\t\tdisplayingVoltage = True\n\t\t\tdisplayingPower = False\n\t\tdef current(self,event):\n\t\t\tl.set_ydata(a)\n\t\t\tax.set_ylim(0, 1.5)\n\t\t\tfor txt in fig.texts:\n\t\t\t\ttxt.set_visible(False)\n\t\t\ttxt = fig.text(0.4,0.95,'Current vs Time',bbox=dict(facecolor='none', alpha=10,lw=0),fontsize = 15)\n\t\t\tyaxistxt = fig.text(0.05,0.6,'Current (Amperes)',bbox=dict(facecolor='none', alpha=10,lw = 0),fontsize = 15,rotation = 'vertical')\n\t\t\tglobal displayingCurrent \n\t\t\tglobal displayingVoltage \n\t\t\tglobal displayingPower \n\t\t\tdisplayingCurrent = True\n\t\t\tdisplayingVoltage = False\n\t\t\tdisplayingPower = False\n\t\t\t\n\t\tdef power(self,event):\n\t\t\tl.set_ydata(p)\n\t\t\tax.set_ylim(0, 10)\n\t\t\tfor txt in fig.texts:\n\t\t\t\ttxt.set_visible(False)\n\t\t\tyaxistxt = fig.text(0.05,0.6,'Power (Watts)',bbox=dict(facecolor='none', alpha=10,lw = 0),fontsize = 15,rotation = 'vertical')\t\n\t\t\ttxt = fig.text(0.4,0.95,' Power vs Time ',bbox=dict(facecolor='none', alpha=10,lw = 0),fontsize = 15)\t\n\t\t\t\n\t\t\tglobal displayingCurrent \n\t\t\tglobal displayingVoltage \n\t\t\tglobal displayingPower \n\t\t\tdisplayingCurrent = False\n\t\t\tdisplayingVoltage = False\n\t\t\tdisplayingPower = True\n\t\tdef close(self,event): #Pressing the close button closes the graphing window\n\t\t\tplt.ioff()\n\t\t\tplt.close()\n\t\t\t\t\t\t\n\t\t\t\n\t\t\n\tcallback = Index()\n\t\n\t\n\tax25 = plt.axes([0.01, 0.01, 0.12, 0.05])\n\tax50 = plt.axes([0.14, 0.01, 0.12, 0.05])\n\tax100 = plt.axes([0.27, 0.01, 0.12, 0.05])\n\tax200 = plt.axes([0.4, 0.01, 0.12, 0.05])\n\tax300 = plt.axes([0.53, 0.01, 0.12, 0.05])\n\taxclose = plt.axes([0.8, 0.01, 0.12, 0.05])\n\t\n\taxvoltage = plt.axes([0.01, 0.08, 0.12, 0.05])\n\taxcurrent = plt.axes([0.14, 0.08, 0.12, 0.05])\n\taxpower = plt.axes([0.27, 0.08, 0.12, 0.05])\n\t\n\tbclose = Button(axclose, 'Close',color='#89CFF0',hovercolor='magenta')\n\tbclose.on_clicked(callback.close)\n\tbvoltage = Button(axvoltage, 'Voltage')\n\tbvoltage.on_clicked(callback.voltage)\n\tbcurrent = Button(axcurrent, 'Current')\n\tbcurrent.on_clicked(callback.current)\n\tbpower = Button(axpower, 'Power')\n\tbpower.on_clicked(callback.power)\n\t\n\tb300 = Button(ax300, '300 Points')\n\tb300.on_clicked(callback.three_hundred)\n\tb200 = Button(ax200, '200 Points')\n\tb200.on_clicked(callback.two_hundred)\n\tb100 = Button(ax100, '100 Points')\n\tb100.on_clicked(callback.one_hundred)\n\tb50 = Button(ax50, '50 Points')\n\tb50.on_clicked(callback.fifty)\n\tb25 = Button(ax25, '25 Points')\n\tb25.on_clicked(callback.twenty_five)\n\t\n\tplt.ion() #Call plt.ion() in order to enable interactive plotting\n\t\t\n\twhile True:\n\t\tif displayingCurrent:\t\t\t\t\n\t\t\tl.set_ydata(a)\t\t\t\n\t\telif displayingVoltage:\n\t\t\tl.set_ydata(v)\t\t\t\n\t\telif displayingPower:\n\t\t\tl.set_ydata(p)\n\t\t\t\t\t\n\t\tplt.pause(0.1) #Call plot.pause(0.1) to both draw the new data and it runs the GUI's event loop (allowing for mouse interaction)\n\t\nexcept:\n\tpass\n\t","sub_path":"Python/Graph- Smart Energy Challenge/RealTimeGraph5.py","file_name":"RealTimeGraph5.py","file_ext":"py","file_size_in_byte":5767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"494210641","text":"\n# %%\n# =========================================================================== #\n# UTILITY FUNCTIONS #\n# =========================================================================== #\nimport os\n\nfrom matplotlib import animation, rc\nfrom matplotlib.animation import FuncAnimation\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndef save_fig(fig, directory, filename, transparent=False):\n if os.path.exists(directory):\n path = os.path.join(os.path.abspath(directory), filename)\n fig.savefig(path, facecolor='w', bbox_inches=None, transparent=transparent)\n else:\n os.makedirs(directory)\n path = os.path.join(os.path.abspath(directory),filename)\n fig.savefig(path, facecolor='w', bbox_inches=None)\n\ndef save_gif(ani, directory, filename, fps):\n face_edge_colors = {'facecolor': 'w', 'edgecolor': 'w'}\n path = os.path.join(directory, filename)\n if os.path.exists(directory):\n ani.save(path, writer='imagemagick', fps=fps, savefig_kwargs = face_edge_colors)\n else:\n os.makedirs(directory) \n ani.save(path, writer='imagemagick', fps=fps, savefig_kwargs = face_edge_colors)\n\ndef save_csv(df, directory, filename):\n path = os.path.join(directory, filename)\n if os.path.exists(directory):\n df.to_csv(path)\n else:\n os.makedirs(directory) \n df.to_csv(path)\n\n","sub_path":"content/code/filemanager.py","file_name":"filemanager.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"52703685","text":"\n#No commandline functionality implemented yet- this one only\n#takes the metadata of an image which is dragged onto it (windows)\n\nfrom PIL import ExifTags, Image\nimport sys\n\ndef GetMeta(imagefile):\n try:\n img = Image.open(imagefile)\n exif = {\n ExifTags.TAGS[k]: v\n for k, v in img._getexif().items()\n if k in ExifTags.TAGS\n }\n return exif\n except:\n return None\n\nmeta = GetMeta(sys.argv[1])\n\nfor key in list(meta.keys()):\n print(key, \": \", meta[key], \"\\n\")\n\nprint(\"hit enter to end...\")\n#Wait for user input\ninput()\n","sub_path":"Data analysis and generation/Images/printmeta.py","file_name":"printmeta.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"263695165","text":"def areIdentical(str1,str2):\r\n\tn1=len(str1)\r\n\tn2=len(str2)\r\n\t#checking if the length is same\r\n\tif(n1!=n2):\r\n\t\treturn False\r\n\t#sorting the strings\r\n\tstr1=sorted(str1)\r\n\tstr2=sorted(str1)\r\n\t#comparing sorted strings\r\n\tfor i in range(0,n1):\r\n\t\tif str1[i]!=str2[i]:\r\n\t\t\treturn False\r\n\treturn True\r\n\r\nstr1='Paul'\r\nstr2='Hawee'\r\n\r\n#calling function\r\nif(areIdentical(str1,str2)):\r\n\tprint('Two strings are Identical')\t\r\nelse:\r\n\tprint('Two strings are not Identical')\r\n\r\n\t","sub_path":"IdenticalStrings.py","file_name":"IdenticalStrings.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"419988426","text":"#! /usr/bin/python\n# find the correct box as stated in advent calendar\ndef findCorrectBox(intArray):\n\n noMaxMatches = 0\n correctBox1 = 0\n correctBox2 = 0\n\n # finding which pair has the most matches\n for x in range(0, len(intArray)):\n word1 = list(intArray[x])\n for y in range(x+1, len(intArray)):\n word2 = list(intArray[y])\n matches = 0\n # for lines of unequal length\n if len(word1) < len(word2):\n maxRange = len(word1)\n else:\n maxRange = len(word2)\n for z in range (0, maxRange):\n if word1[z] == word2[z]:\n matches += 1\n if matches > noMaxMatches:\n correctBox1 = x\n correctBox2 = y\n noMaxMatches = matches\n\n # displaying matches in nice fore\n finalWord = []\n\n word1 = list(intArray[correctBox1])\n word2 = list(intArray[correctBox2])\n for z in range (0, len(word1)):\n if word1[z] == word2[z]:\n finalWord.append(word1[z])\n\n finalString = ''.join(finalWord)\n\n return finalString\n\ndef main():\n\n assert(findCorrectBox([\"abcde\", \"fghij\", \"klmno\", \"pqrst\", \"fguij\", \"axcye\", \"wvxyz\"]) == \"fgij\")\n\n fileInput = open('input1.txt','r')\n inputArray = []\n for line in fileInput:\n inputArray.append(line)\n checkSum = findCorrectBox(inputArray)\n print(checkSum)\n \nif __name__== \"__main__\":\n main()","sub_path":"day-2/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"361322346","text":"#! /usr/bin/env python3\n# coding: utf-8\nfrom config import Config\nimport requests\n\nclass GeocodingLocation:\n \"\"\"\n This class will get gps coordinates from Google Geocoding API according\n the location asked by the user in his message.\n \"\"\"\n\n def __init__(self):\n self.api_key = Config.GOOGLE_API_KEY\n\n def get_location_info(self, location):\n \"\"\"\n The methods requests Google Geocoding API, gets only the necessary informations\n and sends back them into a dictionnary\n \"\"\"\n\n location = location.replace(\" \", \"+\")\n\n location_info = {\n \"address\" : \"\",\n \"latitude\" : 0,\n \"longitude\" : 0,\n \"status\" : \"\"\n }\n\n payload = {\n \"address\" : location,\n \"components\" : \"country:FR\",\n \"key\" : self.api_key\n }\n\n try:\n req = requests.get(\"https://maps.googleapis.com/maps/api/geocode/json\", params=payload)\n data = req.json()\n if data[\"results\"][0][\"geometry\"][\"location_type\"] != \"APPROXIMATE\":\n location_info[\"address\"] = data[\"results\"][0][\"formatted_address\"]\n location_info[\"latitude\"] = data[\"results\"][0][\"geometry\"][\"location\"][\"lat\"]\n location_info[\"longitude\"] = data[\"results\"][0][\"geometry\"][\"location\"][\"lng\"]\n location_info[\"status\"] = \"FOUND\"\n else:\n raise KeyError\n except KeyError:\n location_info[\"status\"] = \"NOT_FOUND\"\n except:\n location_info[\"status\"] = \"REQUEST_PROBLEM\"\n\n return location_info\n","sub_path":"botapp/utils/geocoding.py","file_name":"geocoding.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"132297990","text":"################################################################################\n#\n# SublimeBlender.py\n#\n# Version: 1.0\n# Author: Sven Fraeys\n#\n# Description: \n# Blende addon, it will process the incoming url request that is launched by sublime\n# \n# Free for non-commercial use\n#\n################################################################################\n\nimport threading\nimport http.server\nimport socketserver\n\nimport time, traceback\nimport bpy\n\nPORT = 8006 # port number, needs to be identical as the Sublime Plugin\nIP_ADDRESS = \"localhost\" # ip address, needs to be identical as the Sublime Plugin\n\n\n#IP_ADDRESS = \"192.168.254.1\"\n# global running\n# running = 1\n\n\nclass RequestHandler(http.server.BaseHTTPRequestHandler):\n ''' RequestHandler will process the incoming data\n\n '''\n\n def _writeheaders(self):\n self.send_response(200)\n self.send_header('Content-type', 'text/html; charset=UTF-8')\n self.end_headers()\n\n def do_HEAD(self):\n self._writeheaders()\n \n def do_GET(self):\n # global running \n DEBUG = False\n SUBLIME_STDOUT = True\n\n originalStdOut = None\n newStdOut = None\n\n import urllib\n from urllib.parse import urlparse\n import sys, io, traceback\n\n if SUBLIME_STDOUT:\n originalStdOut = sys.stdout\n newStdOut = io.StringIO()\n sys.stdout = newStdOut\n\n parsed_path = urlparse(self.path)\n # print(parsed_path)\n \n try:\n params = dict([p.split('=') for p in parsed_path[4].split('&')])\n except:\n params = {}\n \n for key in params:\n parsedkey = urllib.parse.unquote_plus(params[key])\n if DEBUG: print(parsedkey)\n params[key] = parsedkey\n\n retstr = \"\"\n\n if \"scriptpath\" in params:\n scriptpath = params[\"scriptpath\"]\n \n if DEBUG: print('#' + scriptpath)\n # print(params)\n scriptpath = scriptpath.strip()\n if scriptpath != None:\n try:\n exec(compile(open(scriptpath).read(), scriptpath, 'exec'))\n except:\n print(str(traceback.format_exc()))\n\n if \"eval\" in params:\n try:\n eval(params[\"eval\"])\n except:\n print(traceback.format_exc())\n\n if DEBUG : print(retstr)\n\n if \"print\" in params:\n print(params[\"print\"])\n\n# retstr=\"finished\"\n# retstr = \"\"\"\n# Dummy response\n# dummy response\n# \"\"\"\n if SUBLIME_STDOUT:\n sys.stdout = originalStdOut\n retstr = (newStdOut.getvalue())\n\n self._writeheaders()\n self.wfile.write(str(retstr).encode('latin'))\n\n return\n \n\n\nclass HttpThread(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.httpd = None\n\n def run(self):\n DEBUG = False\n if DEBUG: print(\"HTTP Server THREAD: started\")\n if DEBUG: print(\"serving at port\", PORT)\n self.httpd.serve_forever()\n if DEBUG: print (\"HTTP Server THREAD: finished\")\n \nclass ControlThread(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.httpd = None\n def run(self):\n DEBUG = False\n if DEBUG : print(\"Control THREAD: started\")\n runcontrol = 1 \n while runcontrol >0:\n # if running < 1:\n if False:\n if DEBUG: print(\"try server shutdown\")\n self.httpd.shutdown()\n self.httpd.socket.close() \n if DEBUG: print(\"shutdown finished\")\n runcontrol = 0\n time.sleep(1) \n \n if DEBUG: print (\"Control THREAD: finished\")\n \nimport bpy\nbl_info = {\n \"name\" : \"SublimeBlender\",\n \"description\": \"Develop with Sublime Text 3 as an external script editor\",\n \"category\" : \"Development\",\n \"author\" : \"Sven Fraeys\",\n \"wiki_url\": \"https://docs.google.com/document/d/1-hWEdp1Gz4zjyio7Hdc0ZnFXKNB6eusYITnuMI3n65M\",\n \"version\": (1, 0)\n}\n\nclass SublimeBlenderOpenConnection(bpy.types.Operator):\n bl_idname = \"wm.sublimeblenderopenconnection\"\n bl_label = \"SublimeBlender Open Connection...\"\n http_thread = None\n control_thread = None\n def execute(self, context):\n DEBUG = False\n httpd = None\n\n try:\n httpd = socketserver.TCPServer((IP_ADDRESS, PORT), RequestHandler)\n except:\n pass\n return {'FINISHED'}\n \n if DEBUG: print (\"SCRIPT: started\")\n if DEBUG: print (\"httpd: %s\" % httpd)\n\n self.http_thread = HttpThread()\n self.http_thread.httpd = httpd\n self.http_thread.start()\n \n\n self.control_thread = ControlThread()\n self.control_thread.httpd = httpd\n self.control_thread.start()\n \n if DEBUG: print (\"SCRIPT: finished\") \n\n return {'FINISHED'}\n\ndef register():\n bpy.utils.register_class(SublimeBlenderOpenConnection)\n\ndef unregister():\n self.http_thread.shutdown()\n self.http_thread.socket.close()\n self.control_thread.shutdown()\n self.control_thread.socket.close()\n bpy.utils.unregister_class(SublimeBlenderOpenConnection)\n \nif __name__ == \"__main__\":\n register()\n\n","sub_path":"blender-addon/SublimeBlender.py","file_name":"SublimeBlender.py","file_ext":"py","file_size_in_byte":5030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"521638545","text":"'''-----------------------------------------------------------------------------\nPROJECT : Spark Non ZAR Cashflow Feed\nPURPOSE : Receive responses from TAP for the non zar settlements to MidasPlus\nDEPATMENT AND DESK : PCG/Ops\nREQUESTER : Nick Bance\nDEVELOPER : Anwar Banoo\nCR NUMBER : XXXXXX\n--------------------------------------------------------------------------------\n\nHISTORY\n================================================================================\nDate Change no Developer Description\n--------------------------------------------------------------------------------\n2011-10-25 XXXXXX Initial Implementation\n2015-09-04 Bhavik Mistry Emailing of failures as they occur\n2016-04-05 CHNG0003546459 Paseka Motsoeneng Directing log emails as per source environment. \n2018-07-19 CHG1000679237 Libor Svoboda Fix the Front - Sparks\n'''\nimport sys\nimport time\nimport acm\nfrom collections import OrderedDict\nfrom datetime import datetime\nfrom xml.etree.ElementTree import SubElement, tostring, ElementTree, fromstring\nimport xml.etree.ElementTree as etree\nfrom Spark_Nostro_MQWrapper import MqMessenger \nfrom Sparks_Config import SparksConfig\nimport Spark_Nostro_HTML_Exception_Rep as exRep\nfrom at_logging import getLogger\n\n# Dashboard Settings/imports ---------------------------------------------------------\nmongo_egg_path = 'c:\\\\Python27\\\\lib\\\\site-packages\\\\pymongo-3.3.0-py2.7-win-amd64.egg'\nxml_egg_path = 'c:\\\\Python27\\\\lib\\\\site-packages\\\\xmltodict-0.10.2-py2.7.egg'\nsys.path.append(mongo_egg_path)\nsys.path.append(xml_egg_path)\nimport pymongo\nimport xmltodict\n\n\nconfig = None\nmqMessenger = None\nposts = None\nLOGGER = getLogger(__name__)\n\n \ndef __processMessage(message):\n LOGGER.info('Process the following message\\n%s' % message)\n \n if len(message) > 10:\n \n try:\n tree = ElementTree(fromstring(message))\n element = tree.find('FrontArenaSettlementId')\n LOGGER.info('Check if incoming message has FrontArenaSettlementId')\n if element is not None and element.text is not None:\n object_id = element.text\n LOGGER.info('Incoming message has FrontArenaSettlementId=%s' % object_id)\n \n id_filter = {'_id': object_id}\n diary = posts.find_one(id_filter)\n element = tree.find('Result')\n \n if (diary) and (element is not None):\n LOGGER.info('Prepare to update status to %s' % element.text)\n \n del diary['_id']\n timestamp = datetime.fromtimestamp(float(diary['Timestamp'])).strftime('%d-%m-%Y %H:%M:%S')\n del diary['Timestamp']\n \n root = ElementTree(fromstring(xmltodict.unparse(diary, full_document=False)))\n tracking = root.find('Tracking')\n payday = root.find('Financials/PayDate').text\n curr = root.find('Financials/CurrencyName').text\n amount = root.find('Financials/Amount').text\n trade_num = root.find('Identifiers/TradeNumber').text\n acquirer = root.find('Acquirer/AcquirerName').text\n portfolio = root.find('Acquirer/AcquirerPortfolio').text\n cust_num = root.find('Acquirer/AcquirerMidasCustomerNbr').text\n counterparty = root.find('Counterparty/CounterpartyName').text\n instype = root.find('Identifiers/InstrumentType')\n midas_ref = tree.find('MidasPaymentReference')\n default_nostro = tree.find('DefaultNostroAccount')\n tracking.set('Status', element.text)\n \n identifiers = root.find(\"Identifiers\")\n original_default_nostro = identifiers.find(\"DefaultNostro\") \n \n if original_default_nostro == None:\n LOGGER.info('Creating new \"DefaultNostro\" element with value %s'%default_nostro.text)\n default_nostro_element = etree.Element(\"DefaultNostro\")\n identifiers.append(default_nostro_element)\n default_nostro_element.text = default_nostro.text\n else:\n LOGGER.info('Setting existing \"DefaultNostro\" element with value %s'%default_nostro.text)\n original_default_nostro.text = default_nostro.text\n \n if midas_ref.text is not None:\n tracking.set('MidasPaymentReference', midas_ref.text)\n \n result = element.text\n error = None\n if result == 'Failure':\n element = tree.find('MidasResponse/Errors')\n for node in element: \n error = node.text\n SubElement(tracking, \"Error\").text = node.text\n LOGGER.info('Node contents: %s' % node.text)\n \n LOGGER.info(tostring(root.getroot()))\n \n id_filter = {'_id': object_id}\n posts.delete_one(id_filter)\n \n document = xmltodict.parse(tostring(root.getroot()))\n document['_id'] = object_id\n document['Timestamp'] = time.time()\n\n try:\n posts.insert_one(document)\n except pymongo.errors.DuplicateKeyError:\n LOGGER.error('Receiver: Cannot insert document: %s.' % object_id)\n else:\n LOGGER.info('Receiver: Moneyflow object %s commited to MongoDb.' % object_id)\n\n if result in config.status_to_report:\n if config.intraday_reporting_active.lower() == 'yes':\n classifier = {}\n classifier_backdates = {}\n \n if payday >= acm.Time.DateToday():\n classifier[result] = []\n classifier[result].append([trade_num,\n result, \n acquirer, \n portfolio, \n counterparty, \n cust_num, \n curr, \n amount, \n instype,\n payday, \n midas_ref, \n timestamp,\n error])\n else:\n classifier_backdates[result] = []\n classifier_backdates[result].append([trade_num,\n result, \n acquirer, \n portfolio, \n counterparty, \n cust_num, \n curr, \n amount, \n instype,\n payday, \n midas_ref, \n timestamp,\n error])\n \n body = exRep.__reportOutput(classifier, classifier_backdates)\n exRep.email_report(body, 'Sparks Intraday Report - %s' %config.environment, config.email_group2, 'Sparks Feed', None)\n \n LOGGER.info('Message processed successfully')\n else:\n LOGGER.info('Diary identifier not recognized:%s' % object_id) \n else:\n LOGGER.info('Response message improperly formatted - FrontArenaSettlementId node')\n\n except Exception as exc:\n LOGGER.exception('Error while processing message: %s' % str(exc))\n\n \ndef work():\n if mqMessenger:\n message = mqMessenger.ReadMessage()\n if message:\n __processMessage(message)\n mqMessenger.AcceptMessage()\n \ndef start():\n global config, mqMessenger, posts\n \n LOGGER.info('ATS attempting startup...')\n config = SparksConfig('Receive')\n mqMessenger = MqMessenger(config) \n\n client = pymongo.MongoClient(config.mongo_db_repl_set_conn_str)\n db = client.spark_db\n posts = db.posts\n \n\ndef stop(): \n mqMessenger.DisconnectQueueManager()\n\ndef status():\n pass\n","sub_path":"Python modules/Spark_Nostro_Receiver.py","file_name":"Spark_Nostro_Receiver.py","file_ext":"py","file_size_in_byte":9250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"124160325","text":"from tkinter import*\r\nimport Firms_Result\r\nimport Firms_Add\r\n\r\n\r\ndef ShowRecords_for_firms(root): \r\n root_results = Toplevel(root)\r\n root_results.geometry(\"800x800\")\r\n\r\n#-------------resizing image-----------------------\r\n #icon=Image.open('Serach.png')\r\n #icon=icon.resize((30,30),Image.ANTIALIAS)\r\n #icon.save(\"Search.png\",\"png\")\r\n#--------------------------------------------------\r\n\r\n f=Frame(root_results,width = 1000,height=100,relief=SUNKEN,bd=5)\r\n f.grid_propagate(0)\r\n f.grid(row=0,column=0,rowspan=10,columnspan=100)\r\n\r\n root_results.photo=PhotoImage(file=\"Add.png\", master = root_results)\r\n \r\n b=Button(f,image = root_results.photo,width=\"30\",height=\"30\")\r\n b.grid(row=0,column=0,sticky=W+E)\r\n b.bind('',lambda event,root=root_results:Firms_Add.Add(root))\r\n \r\n r=Button(f,image = root_results.photo,width=\"30\",height=\"30\")\r\n r.grid(row=0,column=1,sticky=W)\r\n r.bind('',lambda event,root=root_results:Firms_Result.Normal_Results(root_results))\r\n\r\n e=Entry(f,width=10)\r\n e.grid(row=0,column=4,pady=2,sticky=W+E+N+S)\r\n \r\n var=StringVar(f)\r\n var.set(\"ЕИК\")\r\n\r\n def get(event):\r\n s.bind('',lambda event,sel=var.get(),root=root_results,ent=e:Firms_Result.Search(sel,root,ent))\r\n \r\n s=Button(f,image = root_results.photo,width=\"30\",height=\"30\")\r\n s.grid(row=0,column=5,padx=2)\r\n s.bind('',lambda event,sel=var.get(),root=root_results,ent=e:Firms_Result.Search(sel,root,ent))\r\n \r\n drop=OptionMenu(f,var,\"ЕИК\", \"Име\", \"Управител\", \"Държава\", \"Град\",command=get)\r\n drop.config(width=\"10\")\r\n drop.grid(row=0,column=3,sticky=E+N+S)\r\n\r\n beautify=Label(f,width=\"5\")\r\n beautify.grid(row=0,column=2)\r\n \r\n Firms_Result.Normal_Results(root_results)\r\n","sub_path":"Firms.py","file_name":"Firms.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"432015771","text":"###########################################\n# Smith and Waterman algorithm #\n###########################################\n\n'''\nDynamic Programming is a method for solving a complex problem by breaking it down into a collection of simpler subproblems, \nsolving each of those subproblems just once, and storing their solutions using a memory-based data structure.\nSmith and Waterman algorithm takes as inputs two DNA sequences , a scoring matrix and a linear gap penalty defintion, \nand returns one among all the local alignmnents with the best score. Step by step an alignment matrix is populated taking into account \na pre-defined scoring matrix and a linear gap penalty, saving the direction corresponding to the best transition:\n \n M[0][0] = 0.0 \n | M[i-1][j-1] + sub[SEQ1[0]][SEQ2[0]]\n M[i][j] = max | M[i-1][j] - GAP\n | M[i][j-1] - GAP \n | 0\nPSEUDO CODE:\n 1. initalise the string DNA_SEQUENCE 1 and DNA_SEQUENCE 2\n 2. define the variable MATCH, MISMATCH and GAP\n \n Function MATRIX_INITIALIZATION with arguments SEQUENCE 1, SEQUENCE 2, GAP:\n - initalise a all 0 matrix MATRIX of dimension M x N where:\n M = lenght of SEQUENCE 1\n N = lenght of SEQUENCE 2\n - iterate for column in range 1, N:\n MATRIX[0][column] = 0\n - iterate for row in range 1, M:\n MATRIX[row][0] = 0\n - return MATRIX, M and N\n \n \n Function FIND_MAX with argument SCORES:\n - initialise MAX_SCORE(-inf)\n - for column in range lenght of SCORES:\n if SCORES[column] is major than MAX_SCORE:\n MAX_SCORE = SCORES[column] \n - return MAX_SCORE\n \n Function SMITH_WATERMAN with arguments SEQUENCE 1, SEQUENCE 2, MATCH, MISMATCH and GAP:\n - call the function MATRIX_INITIALIZATION and save MATRIX, M and N\n - initialise MAX_SCORE(-inf)\n - iterate for row in range 1, M:\n - iterate for column in range 1, N:\n - initalise an empty list SCORES\n - compute DIAGONAL_SCORE as:\n DIAGONAL_SCORE = MATRIX[row-1][column-1] + match if SEQUENCE 1[row-1] = SEQUENCE 2[column-1]\n DIAGONAL_SCORE = MATRIX[row-1][column-1] + mismatch if SEQUENCE 1[row-1] ≠ SEQUENCE 2[column-1]\n - compute UP_SCORE as MATRIX[row-1][column] + GAP\n - compute LEFT_SCORE as MATRIX[row][column-1] + GAP\n \n - append DIAGONAL_SCORE, UP_SCORE and LEFT_SCORE to SCORES \n - call the function FIND_MAX with SCORES as argument for every MATRIX[row][column] \n - update MAX_SCORE if max(SCORES) is bigger: \n MAX_SCORE = FIND_MAX(scores)\n MAX_POSITION = (row, column) \n \n - initialise MAX_ROW as MAX_POSITION[0] and MAX_COLUMN as MAX_POSITION[1]\n - initialise two empty strings ALIGNMENT1 and ALIGNMENT2\n - iterate until MAX_SCORE = 0:\n - define a list DIRECTIONS with DIAGONAL_SCORE, UP_SCORE and LEFT_SCORE where:\n DIAGONAL_SCORE = MATRIX[MAX_ROW-1][MAX_COLUMN-1]\n UP_SCORE = MATRIX[MAX_ROW-1][MAX_COLUMN]\n LEFT_SCORE = MATRIX[MAX_ROW][MAX_COLUMN-1]\n - compute the max score in DIRECTIONS and save it as a string DIRECTION\n \n - if DIRECTION = DIAGONAL_SCORE:\n concatenate SEQUENCE 1[MAX_ROW-1] to ALIGNMENT1 \n concatenate SEQUENCE 2[MAX_COLUMN-1] to ALIGNMENT2 \n decrease -1 MAX_ROW and MAX_COLUMN \n - if DIRECTION = UP_SCORE:\n concatenate SEQUENCE 1[MAX_ROW-1] to ALIGNMENT1 \n concatenate GAP to ALIGNMENT2 \n decrease -1 MAX_ROW\n - if DIRECTION = LEFT_SCORE:\n concatenate GAP to ALIGNMENT1 \n concatenate SEQUENCE 2[MAX_COLUMN-1] to ALIGNMENT2 \n decrease -1 MAX_COLUMN\n - return MATRIX, ALIGNMENT1 and ALIGNMENT2\n'''\n\ndef pretty_matrix(m):\n print()\n for y in range(0, len(m)):\n print(m[y])\n print()\n\ndef brutal_matrix(rows, columns): \n scoring_matrix = []\n for i in range(0, rows):\n scoring_matrix.append([])\n for j in range(0, columns):\n scoring_matrix[i].append(0)\n return(scoring_matrix) \n\ndef matrix_initialization(Seq1, Seq2):\n M = len(Seq1) + 1\n N = len(Seq2) + 1\n matrix = [[0 for col in range(N)] for row in range(M)]\n return(matrix, M, N)\n\ndef find_max(scores):\n max_value = float(\"-inf\")\n for i in range(0, len(scores)):\n if scores[i] > max_value:\n max_value = scores[i]\n return (max_value)\n\n# Population of the scoring_matrix \ndef Needelman_Wunsh(Seq1, Seq2, match, mismatch, gap):\n \n try:\n if set(Seq1) != {'A', 'G', 'T', 'C'} or set(Seq2) != {'A', 'G', 'T', 'C'}:\n variable = float('') #just to have an error\n \n except:\n print('program usage: python text.py ')\n print('where must be composed just by A, C, G and T')\n raise SystemExit\n \n else:\n scoring_matrix, M, N = matrix_initialization(Seq1, Seq2)\n max_score = float(\"-inf\") #syntax that allows \n max_position = None\n for row in range(1, M):\n for column in range(1, N):\n scores = [0]\n \n # Compute diagonal score\n if Seq1[row-1] == Seq2[column-1]:\n DIAG_SCORE = scoring_matrix[row-1][column-1] + match\n else:\n DIAG_SCORE = scoring_matrix[row-1][column-1] + mismatch\n scores.append(DIAG_SCORE)\n \n # Compute up score\n UP_SCORE = scoring_matrix[row-1][column] + gap\n scores.append(UP_SCORE)\n\n # Compute left score\n LEFT_SCORE = scoring_matrix[row][column-1] + gap\n scores.append(LEFT_SCORE)\n \n scoring_matrix[row][column] = find_max(scores)\n if max(scores) > max_score: \n max_score = max(scores)\n max_position = (row, column) \n\n max_row = max_position[0]\n max_column = max_position[1]\n print(max_position)\n align1 = \"\"\n align2 = \"\"\n\n while max_score != 0: \n up_element = scoring_matrix[max_row-1][max_column]\n left_element = scoring_matrix[max_row][max_column-1]\n diagonal_element = scoring_matrix[max_row-1][max_column-1]\n \n direction = [up_element, left_element, diagonal_element]\n DIR = max(direction)\n\n if DIR == diagonal_element:\n align1 += Seq1[max_row-1]\n align2 += Seq2[max_column-1]\n max_row -= 1\n max_column -= 1\n elif DIR == left_element:\n align1 += '-'\n align2 += Seq2[max_column-1]\n max_column -= 1\n else:\n align1 += Seq1[max_row-1]\n align2 += '-'\n max_row -= 1 \n \n max_score = DIR\n\n line_interseq = \"\"\n for i in range(len(align1)):\n if align1[i] == align2[i]:\n line_interseq += \"|\"\n else:\n line_interseq += \" \" \n \n return(scoring_matrix, align1[::-1], line_interseq[::-1], align2[::-1])\n\nif __name__ == '__main__':\n match = +2\n mismatch = -1\n gap = -2\n import sys\n try:\n Seq1 = sys.argv[1] \n Seq2 = sys.argv[2]\n except:\n print('Program usage: text.py ')\n raise SystemExit\n else:\n scoring_matrix, alignment1, line_interseq, alignment2 = Needelman_Wunsh(Seq1, Seq2, match, mismatch, gap)\n \n pretty_matrix(scoring_matrix)\n print(\"This is the score of the global alignment: %d\\n\" %scoring_matrix[len(scoring_matrix)-1][len(scoring_matrix[0])-1])\n print(alignment1)\n print(line_interseq) \n print(alignment2)\nprint()\n","sub_path":"Bioinfo/Esami Fatti-------------------------------/Programmazione Bioinfo/Algorithms (Martelli)/Algorithms/SW.py","file_name":"SW.py","file_ext":"py","file_size_in_byte":8373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"163502543","text":"# -*- coding: utf-8 -*-\nimport codecs\nfrom sefaria.model import *\nfrom parsing_utilities import util\nfrom sources import functions\nfrom sources.Scripts import function\n\nfootnotes = 'Footnotes to '\nfootnotes_hebrew = u'\\u05d4\\u05e2\\u05e8\\u05d5\\u05ea \\u05e2\\u05dc '\n\nfour_dict = function.create_dict('IV', 'Arbah', u'\\u05d3', '4', \"St.Petersburg, 1883\",\"http://primo.nli.org.il/primo_library/libweb/action/dlDisplay.do?vid=NLI&docId=NNL_ALEPH001124682\" )\nfive_dict = function.create_dict('V', 'Chamesh', u'\\u05d4', '5', \"Vilna, 1885\", 'http://primo.nli.org.il/primo_library/libweb/action/dlDisplay.do?vid=NLI&docId=NNL_ALEPH002160720' )\nsix_dict = function.create_dict('VI', 'Shesh', u'\\u05d5', '6', 'Warsaw, 1868', 'http://primo.nli.org.il/primo_library/libweb/action/dlDisplay.do?vid=NLI&docId=NNL_ALEPH001124680')\nseven_dict = function.create_dict('VII', 'Sheva', u'\\u05d6', '7', 'Warsaw, 1868', 'http://primo.nli.org.il/primo_library/libweb/action/dlDisplay.do?vid=NLI&docId=NNL_ALEPH001124680')\n\nthe_dictionaries = {\n '4': four_dict,\n '5': five_dict,\n '6': six_dict,\n '7': seven_dict\n }\n\ndef parse_the_text(file_name_teshuvot, file_name_footnotes, dictionary):\n teshuvot_ja = function.parse(file_name_teshuvot)\n footnotes_ja = function.parse(file_name_footnotes)\n links = function.create_links(teshuvot_ja, dictionary)\n index_teshuvot = function.create_index(dictionary)\n index_footnotes = function.create_index(dictionary,footnotes, footnotes_hebrew)\n teshuvot_ja = util.clean_jagged_array(teshuvot_ja, ['\\d+', '\\+'])\n footnotes_ja = util.clean_jagged_array(footnotes_ja, ['\\d+', '\\+'])\n text_teshuvot = function.create_text(dictionary, teshuvot_ja)\n text_footnotes = function.create_text(dictionary, footnotes_ja)\n functions.post_index(index_teshuvot)\n functions.post_index(index_footnotes)\n functions.post_text_weak_connection('Teshuvot haRashba part {}'.format(dictionary['roman numeral']), text_teshuvot)\n functions.post_text_weak_connection('Footnotes to Teshuvot haRashba part {}'.format(dictionary['roman numeral']), text_footnotes)\n functions.post_link_weak_connection(links)\n\n\nfor number in range(4,8):\n parse_the_text('rashba{}.txt'.format(str(number)), 'rashba{}cmnt.txt'.format(str(number)), the_dictionaries[str(number)])\n\n# hello = codecs.open(\"hello.txt\", 'w', 'utf-8')\n# util.jagged_array_to_file(hello, teshuvot_harashba_4,['Siman', 'Text'])\n# hello.close()\n\n","sub_path":"sources/Scripts/parseTeshuvotHaRashba.py","file_name":"parseTeshuvotHaRashba.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"332349585","text":"import logging\n\nfrom config import log_file\n\ndef getLogger(name=None):\n\n # Create a custom logger\n #logger = logging.getLogger(__name__)\n logger = logging.getLogger(name)\n\n # Create handlers\n c_handler = logging.StreamHandler()\n f_handler = logging.FileHandler(log_file)\n c_handler.setLevel(logging.INFO)\n f_handler.setLevel(logging.INFO)\n\n # Create formatters and add it to handlers\n c_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s')\n f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n c_handler.setFormatter(c_format)\n f_handler.setFormatter(f_format)\n\n # Add handlers to the logger\n logger.addHandler(c_handler)\n logger.addHandler(f_handler)\n logger.setLevel(logging.INFO)\n\n return logger","sub_path":"logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"318409456","text":"import torch\nfrom torch.nn import functional as F\nfrom torch import nn\nimport numpy.ma as ma\nimport numpy as np\nimport copy\nimport datetime\nimport csv\nimport codecs\n\nfrom Experiments_RL.experiment_base import HybridBase\nfrom Utils_RL.models import PASAC_QNetwork_LSTM, PASAC_PolicyNetwork_LSTM\nfrom Utils_RL.utils import copy_param, soft_update, padding_and_convert, gen_mask, PrioritizedReplayBuffer_LSTM, \\\n ReplayBuffer_LSTM, v2id\n\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\n\n\nclass PASAC_Agent_LSTM(HybridBase):\n def __init__(self, debug, weights, gamma, replay_buffer_size, max_steps,\n hidden_size, value_lr, policy_lr, batch_size, state_dim,\n action_discrete_dim, action_continuous_dim, soft_tau,\n use_exp):\n super(PASAC_Agent_LSTM, self).__init__(debug, weights, gamma, replay_buffer_size, max_steps,\n hidden_size, value_lr, policy_lr, batch_size, state_dim,\n action_discrete_dim, action_continuous_dim)\n assert debug['replay_buffer'] in ['r', 'p']\n if debug['replay_buffer'] == 'r':\n self.replay_buffer = ReplayBuffer_LSTM(replay_buffer_size)\n elif debug['replay_buffer'] == 'p':\n self.replay_buffer = PrioritizedReplayBuffer_LSTM(replay_buffer_size)\n\n self.soft_q_net1 = PASAC_QNetwork_LSTM(max_steps, \n state_dim, \n action_discrete_dim, \n action_continuous_dim,\n hidden_size=hidden_size, \n batch_size=batch_size).to(self.device)\n self.soft_q_net2 = PASAC_QNetwork_LSTM(max_steps, \n state_dim, \n action_discrete_dim, \n action_continuous_dim,\n hidden_size=hidden_size, \n batch_size=batch_size).to(self.device)\n self.target_soft_q_net1 = PASAC_QNetwork_LSTM(max_steps, \n state_dim, \n action_discrete_dim, \n action_continuous_dim,\n hidden_size=hidden_size, \n batch_size=batch_size).to(self.device)\n self.target_soft_q_net2 = PASAC_QNetwork_LSTM(max_steps, \n state_dim, \n action_discrete_dim, \n action_continuous_dim,\n hidden_size=hidden_size, \n batch_size=batch_size).to(self.device)\n self.policy_net = PASAC_PolicyNetwork_LSTM(state_dim,\n max_steps,\n action_discrete_dim,\n action_continuous_dim,\n hidden_size=hidden_size,\n batch_size=batch_size).to(self.device)\n \n self.log_alpha_c = torch.zeros(\n 1, dtype=torch.float32, requires_grad=True, device=self.device)\n self.log_alpha_d = torch.tensor(\n [-1.6094], dtype=torch.float32, requires_grad=True, device=self.device)\n\n for target_param, param in zip(self.target_soft_q_net1.parameters(), self.soft_q_net1.parameters()):\n target_param.data.copy_(param.data)\n for target_param, param in zip(self.target_soft_q_net2.parameters(), self.soft_q_net2.parameters()):\n target_param.data.copy_(param.data)\n\n self.models = {'policy': self.policy_net,\n 'value1': self.soft_q_net1, 'target_value1': self.target_soft_q_net1,\n 'value2': self.soft_q_net2, 'target_value2': self.target_soft_q_net2}\n\n self.soft_q_optimizer1 = torch.optim.Adam(\n self.soft_q_net1.parameters(), lr=value_lr, weight_decay=debug['L2_norm'])\n self.soft_q_optimizer2 = torch.optim.Adam(\n self.soft_q_net2.parameters(), lr=value_lr, weight_decay=debug['L2_norm'])\n self.policy_optimizer = torch.optim.Adam(\n self.policy_net.parameters(), lr=policy_lr, weight_decay=debug['L2_norm'])\n self.alpha_optimizer_c = torch.optim.Adam(\n [self.log_alpha_c], lr=debug['alpha_lr'], weight_decay=self.debug['L2_norm'])\n self.alpha_optimizer_d = torch.optim.Adam(\n [self.log_alpha_d], lr=debug['alpha_lr'], weight_decay=self.debug['L2_norm'])\n\n self.soft_q_criterion1 = nn.MSELoss()\n self.soft_q_criterion2 = nn.MSELoss()\n\n self.max_steps = max_steps\n self.DETERMINISTIC = False\n self.soft_tau = soft_tau\n self.use_exp = use_exp\n\n # load models if needed\n if debug['load_model'] and debug['load_filename'] is not None:\n self.load(None)\n\n def act(self, state:np.ndarray, hidden_in, sampling:bool=False):\n \"\"\"\n explore with original action and return one-hot action encoding\n Note - 'sampling' = sample an action tuple with the probability = \n \"\"\"\n param, action_v, (hx, cx) = self.policy_net.get_action(\n state, hidden_in, deterministic=self.DETERMINISTIC)\n action_enc = (action_v, param)\n if sampling:\n a = np.log(action_v) / 1.0\n dist = np.exp(a) / np.sum(np.exp(a))\n choices = range(len(a))\n action = np.random.choice(choices, p=dist), param\n else:\n action = v2id((action_v, param), from_tensor=False)\n return action, action_enc, action_v, param, (hx, cx)\n\n def update(self, batch_size, auto_entropy=True, target_entropy=-2, gamma=0.99, soft_tau=1e-2,\n need_print=False):\n if isinstance(self.replay_buffer, ReplayBuffer_LSTM):\n state, action_v, param, reward, next_state, done = self.replay_buffer.sample(batch_size)\n elif isinstance(self.replay_buffer, PrioritizedReplayBuffer_LSTM):\n batch, indices, weights = self.replay_buffer.sample(batch_size)\n state, action_v, param, reward, next_state, done = batch\n weights = torch.FloatTensor(weights).unsqueeze(-1).unsqueeze(-1).to(self.device)\n else:\n raise NotImplementedError\n\n # -----init-----\n hidden_in = self.policy_net.init_hidden_states(bsize=batch_size)\n hidden_out = self.policy_net.init_hidden_states(bsize=batch_size)\n\n action_v, seq_len = padding_and_convert(action_v, self.max_steps)\n param, _ = padding_and_convert(param, self.max_steps)\n\n for i, r in enumerate(reward): # padding zeros\n ones = [0 for i in range(self.max_steps - len(r))]\n r.extend(ones)\n reward[i] = r\n reward = torch.FloatTensor(reward).unsqueeze(-1).to(self.device)\n\n for i, d in enumerate(done): # padding ones\n d = [int(d_) for d_ in d] # convert True -> 1, False -> 0\n ones = [1 for i in range(self.max_steps - len(d))]\n d.extend(ones)\n done[i] = d\n done = torch.FloatTensor(np.float32(done)).unsqueeze(-1).to(self.device)\n\n # [predict]\n predicted_q_value1, _ = self.soft_q_net1(\n state, action_v, param, hidden_in, seq_dim_len=seq_len)\n predicted_q_value2, _ = self.soft_q_net2(\n state, action_v, param, hidden_in, seq_dim_len=seq_len) # optional: add last_action\n new_action_v, new_param, log_prob, _, _, _, _ = self.policy_net.evaluate(\n state, hidden_in, seq_dim_len=seq_len)\n new_next_action_v, new_next_param, next_log_prob, _, _, _, _ = self.policy_net.evaluate(\n next_state, hidden_out, seq_dim_len=seq_len)\n\n # -----Updating alpha wrt entropy-----\n mask = gen_mask(state, seq_len, self.max_steps)\n mask = torch.BoolTensor(mask).to(self.device)\n\n def get_log_action_prob(action_prob, use_exp):\n if self.use_exp: # expectation\n action_log_prob = torch.log(action_prob)\n action_log_prob = action_log_prob.mul(action_prob) # calculate expectation\n action_log_prob[action_log_prob!=action_log_prob] = 0 # set NaN to zero\n action_log_prob.clamp_(-10, 0)\n action_sum_log_prob = torch.sum(action_log_prob, dim=-1) # A little bit too large, need to be scaled?\n action_sum_log_prob = action_sum_log_prob.view(action_sum_log_prob.size(0),\n self.max_steps, 1) \n else: # sampling\n action_sample_all = []\n for action in action_prob:\n action_sample = []\n for a in action:\n a = a.detach().cpu().numpy()\n choices = range(len(a))\n if a[0] == 0:\n action_sample.append(0)\n continue\n idx = np.random.choice(choices, p=a)\n action_sample.append(a[idx].item())\n action_sample_all.append(action_sample)\n action_sample_all = torch.FloatTensor(action_sample_all)\n action_log_prob = torch.log(action_sample_all)\n action_sum_log_prob = action_log_prob.view(action_log_prob.size(0),\n self.max_steps, 1)\n action_sum_log_prob = action_sum_log_prob.to(self.device)\n\n return action_sum_log_prob\n \n action_sum_log_prob = get_log_action_prob(new_action_v, self.use_exp)\n action_sum_log_prob_next = get_log_action_prob(new_next_action_v, self.use_exp)\n\n # [update temperature alpha]\n if auto_entropy:\n alpha_loss_d = -(self.log_alpha_d * (action_sum_log_prob + target_entropy).detach())\n alpha_loss_d = alpha_loss_d.masked_select(mask)\n alpha_loss_d = alpha_loss_d.mean()\n self.alpha_optimizer_d.zero_grad()\n alpha_loss_d.backward()\n self.alpha_optimizer_d.step()\n self.alpha_d = self.log_alpha_d.exp()\n\n alpha_loss_c = -(self.log_alpha_c * (log_prob + target_entropy).detach())\n alpha_loss_c = alpha_loss_c.masked_select(mask)\n alpha_loss_c = alpha_loss_c.mean()\n self.alpha_optimizer_d.zero_grad()\n alpha_loss_c.backward()\n self.alpha_optimizer_c.step()\n self.alpha_c = self.log_alpha_c.exp()\n else:\n self.alpha_c = 1.\n self.alpha_d = 1.\n alpha_loss_d = 0\n alpha_loss_c = 0\n if need_print:\n print('[debug: alpha_c]', self.alpha_c.data[0].item())\n print('[debug: alpha_d]', self.alpha_d.data[0].item())\n\n # [compute value loss]\n predict_target_q1, _ = self.target_soft_q_net1(\n next_state, new_next_action_v, new_next_param, hidden_out, seq_dim_len=seq_len)\n predict_target_q2, _ = self.target_soft_q_net2(\n next_state, new_next_action_v, new_next_param, hidden_out, seq_dim_len=seq_len)\n target_q_min = torch.min(\n predict_target_q1, predict_target_q2) - self.alpha_c * next_log_prob - self.alpha_d * action_sum_log_prob_next\n target_q_value = reward + (1 - done) * gamma * target_q_min\n\n q_value_loss1_elementwise = (predicted_q_value1 - target_q_value.detach()) * mask.float()\n q_value_loss2_elementwise = (predicted_q_value2 - target_q_value.detach()) * mask.float()\n\n # [compute policy loss]\n predict_q1, _ = self.soft_q_net1(\n state, new_action_v, new_param, hidden_in, seq_dim_len=seq_len)\n predict_q2, _ = self.soft_q_net2(\n state, new_action_v, new_param, hidden_in, seq_dim_len=seq_len)\n predicted_new_q_value = torch.min(predict_q1, predict_q2)\n\n policy_loss_elementwise = self.alpha_c * log_prob + self.alpha_d * action_sum_log_prob - predicted_new_q_value\n policy_loss_elementwise = policy_loss_elementwise * mask.float()\n\n # [compute total loss]\n if isinstance(self.replay_buffer, PrioritizedReplayBuffer_LSTM):\n errors_sum = (q_value_loss1_elementwise.abs() +\n q_value_loss2_elementwise.abs() +\n policy_loss_elementwise.abs()).sum(dim=1)\n q_value_loss1 = (q_value_loss1_elementwise ** 2 * weights).mean()\n q_value_loss2 = (q_value_loss2_elementwise ** 2 * weights).mean()\n policy_loss = (policy_loss_elementwise * weights).mean()\n else:\n q_value_loss1 = self.soft_q_criterion1(q_value_loss1_elementwise, torch.zeros_like(\n q_value_loss1_elementwise))\n q_value_loss2 = self.soft_q_criterion2(q_value_loss2_elementwise, torch.zeros_like(\n q_value_loss2_elementwise))\n policy_loss = policy_loss_elementwise.mean()\n\n # [update networks]\n self.soft_q_optimizer1.zero_grad()\n q_value_loss1.backward()\n self.soft_q_optimizer1.step()\n self.soft_q_optimizer2.zero_grad()\n q_value_loss2.backward()\n self.soft_q_optimizer2.step()\n self.policy_optimizer.zero_grad()\n policy_loss.backward()\n self.policy_optimizer.step()\n\n # [soft update the target value net]\n soft_update(self.target_soft_q_net1, self.soft_q_net1, soft_tau)\n soft_update(self.target_soft_q_net2, self.soft_q_net2, soft_tau)\n\n # [update priorities]\n if isinstance(self.replay_buffer, PrioritizedReplayBuffer_LSTM):\n self.replay_buffer.priority_update(indices, errors_sum.reshape(batch_size).tolist())\n\n return predicted_new_q_value.mean()\n","sub_path":"Experiments_RL/sac_lstm.py","file_name":"sac_lstm.py","file_ext":"py","file_size_in_byte":14475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"401058866","text":"#!/usr/bin/env python3\nfrom math import inf as infinity\nfrom random import choice\nimport platform\nimport time\nfrom os import system\n\n\"\"\"\nAn implementation of Minimax AI Algorithm in Tic Tac Toe,\nusing Python.\nThis software is available under GPL license.\nAuthor: Clederson Cruz\nYear: 2017\nLicense: GNU GENERAL PUBLIC LICENSE (GPL)\n\"\"\"\n\n\nHUMANO = -1\nCOMPUTADOR = +1\nboard = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]\n#print(board)\n\ndef evaluate(estado):\n \"\"\"\n Función de evaluación heurística del estado.\n : parametro: estado, estado actual del tablero\n : devuelve: +1 si COMPUTADOR gana; -1 si el HUMANO gana; 0 en caso de empate\n \"\"\"\n if wins(estado, COMPUTADOR):\n score = +1\n elif wins(estado, HUMANO):\n score = -1\n else:\n score = 0\n\n return score\n\n\ndef wins(estado, player):\n \"\"\"\n Esta funcion verifica si un jugador especifico gana. Posibilidades:\n * Tres filas [X X X] or [O O O]\n * Tres columnas [X X X] or [O O O]\n * Dos diagonales [X X X] or [O O O]\n :parametro estado, el estado del tablero actual\n :parametro player: un HUMANOo o un COMPUTADORutador\n :devuelve: True si un jugador gana\n \"\"\"\n win_state = [\n [estado[0][0], estado[0][1], estado[0][2]],\n [estado[1][0], estado[1][1], estado[1][2]],\n [estado[2][0], estado[2][1], estado[2][2]],\n [estado[3][0], estado[3][1], estado[3][2]],\n [estado[0][1], estado[0][2], estado[0][3]],\n [estado[1][1], estado[1][2], estado[1][3]],\n [estado[2][1], estado[2][2], estado[2][3]],\n [estado[3][1], estado[3][2], estado[3][3]],\n\n [estado[0][0], estado[1][0], estado[2][0]],\n [estado[0][1], estado[1][1], estado[2][1]],\n [estado[0][2], estado[1][2], estado[2][2]],\n [estado[0][3], estado[1][3], estado[2][3]],\n [estado[1][0], estado[2][0], estado[3][0]],\n [estado[1][1], estado[2][1], estado[3][1]],\n [estado[1][2], estado[2][2], estado[3][2]],\n [estado[1][3], estado[2][3], estado[3][3]],\n\n [estado[0][0], estado[1][1], estado[2][2]],\n [estado[2][0], estado[1][1], estado[0][2]],\n\n [estado[0][1], estado[1][2], estado[2][3]],\n [estado[2][1], estado[1][2], estado[0][3]],\n\n [estado[1][1], estado[2][2], estado[3][3]],\n [estado[3][1], estado[2][2], estado[1][3]],\n\n [estado[1][0], estado[2][1], estado[3][2]],\n [estado[3][0], estado[2][1], estado[1][2]],\n ]\n if [player, player, player, player] in win_state:\n return True\n else:\n return False\n\n\ndef game_over(estado):\n \"\"\"\n Esa funcion verifica si el HUMANOo o el COMPUTADORutador gana\n :parametro estado, estado del tablero actual\n :devuelve: True si el HUMANOo o el COMPUTADORutador gana\n \"\"\"\n return wins(estado, HUMANO) or wins(estado, COMPUTADOR)\n\n\ndef empty_cells(estado):\n \"\"\"\n Cada celda vacía se agregará a la lista de celdas\n :parametro estado, estado de tablero actual\n :devuelve, una lista de las celdas vacias\n \"\"\"\n cells = []\n\n for x, fila in enumerate(estado):\n for y, cell in enumerate(fila):\n if cell == 0:\n cells.append([x, y])\n return cells\n\ndef valid_move(x, y):\n \"\"\"\n Un movimiento es válido si la celda elegida está vacía\n :parametro x, coordenada X\n :parametro y, coordenada Y \n :devuelve: True si la posicion del tablero[x][y] esta vacia\n \"\"\"\n if [x, y] in empty_cells(board):\n return True\n else:\n return False\n\ndef set_move(x, y, player):\n \"\"\"\n Establece un movimiento en el tablero, si las coordenadas son validas\n :parametro x, coordenada X\n :parametro y, coordenada Y\n :parametro player, jugador actual\n \"\"\"\n if valid_move(x, y):\n board[x][y] = player\n return True\n else:\n return False\n\n\ndef minimax(estado, depth, player):\n \"\"\"\n Funcion IA que elige la mejor movida\n AI function that choice the best move\n :parametro estado, estado actual en el tablero\n :param depth, indice del nodo en el arbol (0 <= depth <= 9), pero nunca nueve.\n :param player, un HUMANOo o un COMPUTADORutador\n :devuelve, una lista con [la mejor fila, la mejor columna, el mejor score]\n \"\"\"\n if player == COMPUTADOR:\n best = [-1, -1, -infinity]\n else:\n best = [-1, -1, +infinity]\n\n if depth == 0 or game_over(estado):\n score = evaluate(estado)\n return [-1, -1, score]\n\n for cell in empty_cells(estado):\n x, y = cell[0], cell[1]\n estado[x][y] = player\n score = minimax(estado, depth - 1, -player)\n estado[x][y] = 0\n score[0], score[1] = x, y\n\n if player == COMPUTADOR:\n if score[2] > best[2]:\n best = score # max value\n else:\n if score[2] < best[2]:\n best = score # min value\n\n return best\n\n\ndef clean():\n \"\"\"\n Clears the console\n \"\"\"\n os_name = platform.system().lower()\n if 'windows' in os_name:\n system('cls')\n else:\n system('clear')\n\n\ndef render(estado, c_choice, h_choice):\n \"\"\"\n Print the board on console\n :param estado: current estado of the board\n \"\"\"\n\n chars = {\n -1: h_choice,\n +1: c_choice,\n 0: ' '\n }\n str_line = '---------------'\n\n print('\\n' + str_line)\n for fila in estado:\n for cell in fila:\n symbol = chars[cell]\n print(f'| {symbol} |', end = '')\n print('\\n' + str_line)\n\n\ndef ai_turn(c_choice, h_choice):\n \"\"\"\n It calls the minimax function if the depth < 9,\n else it choices a random coordinate.\n :param c_choice: COMPUTADORuter's choice X or O\n :param h_choice: HUMANO's choice X or O\n :return:\n \"\"\"\n depth = len(empty_cells(board))\n if depth == 0 or game_over(board):\n return\n\n clean()\n print(f'Juega COMPUTADO [{c_choice}]')\n render(board, c_choice, h_choice)\n\n if depth == 16:\n x = choice([0, 1, 2, 3])\n y = choice([0, 1, 2, 3])\n else:\n move = minimax(board, depth, COMPUTADOR)\n x, y = move[0], move[1]\n\n set_move(x, y, COMPUTADOR)\n time.sleep(1)\n\ndef HUMANO_turn(c_choice, h_choice):\n \"\"\"\n The HUMANO plays choosing a valid move.\n :param c_choice: COMPUTADORuter's choice X or O\n :param h_choice: HUMANO's choice X or O\n :return:\n \"\"\"\n depth = len(empty_cells(board))\n if depth == 0 or game_over(board):\n return\n\n # Dictionary of valid moves\n move = -1\n moves = {\n 1: [0, 0], 2: [0, 1], 3: [0, 2], 4: [0, 3],\n 5: [1, 0], 6: [1, 1], 7: [1, 2], 8: [1, 3],\n 9: [2, 0], 10: [2, 1], 11: [2, 2], 12: [2, 3],\n 13: [3, 0], 14: [3, 1], 15: [3, 2], 16: [3, 3],\n }\n\n clean()\n print(f'turno HUMANO [{h_choice}]')\n render(board, c_choice, h_choice)\n\n while move < 1 or move > 16:\n try:\n move = int(input('Use numpad (1..16): '))\n coord = moves[move]\n can_move = set_move(coord[0], coord[1], HUMANO)\n\n if not can_move:\n print('Bad move')\n move = -1\n except (EOFError, KeyboardInterrupt):\n print('Bye')\n exit()\n except (KeyError, ValueError):\n print('Bad choice')\n\n\ndef main():\n \"\"\"\n Main function that calls all functions\n \"\"\"\n clean()\n h_choice = '' # X or O\n c_choice = '' # X or O\n first = '' # if HUMANO is the first\n\n # HUMANO chooses X or O to play\n while h_choice != 'O' and h_choice != 'X':\n try:\n print('')\n h_choice = input('Choose X or O\\nChosen: ').upper()\n except (EOFError, KeyboardInterrupt):\n print('Bye')\n exit()\n except (KeyError, ValueError):\n print('Bad choice')\n\n # Setting COMPUTADORuter's choice\n if h_choice == 'X':\n c_choice = 'O'\n else:\n c_choice = 'X'\n\n # HUMANO may starts first\n clean()\n while first != 'Y' and first != 'N':\n try:\n first = input('First to start?[y/n]: ').upper()\n except (EOFError, KeyboardInterrupt):\n print('Bye')\n exit()\n except (KeyError, ValueError):\n print('Bad choice')\n\n # Main loop of this game\n while len(empty_cells(board)) > 0 and not game_over(board):\n if first == 'N':\n ai_turn(c_choice, h_choice)\n first = ''\n\n HUMANO_turn(c_choice, h_choice)\n ai_turn(c_choice, h_choice)\n\n # Game over message\n if wins(board, HUMANO):\n clean()\n print(f'HUMANO turn [{h_choice}]')\n render(board, c_choice, h_choice)\n print('YOU WIN!')\n elif wins(board, COMPUTADOR):\n clean()\n print(f'COMPUTADORuter turn [{c_choice}]')\n render(board, c_choice, h_choice)\n print('YOU LOSE!')\n else:\n clean()\n render(board, c_choice, h_choice)\n print('DRAW!')\n\n exit()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"PrimerParcial/pregunta2/minimax_01.py","file_name":"minimax_01.py","file_ext":"py","file_size_in_byte":9022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"253233251","text":"import logging\r\nimport time\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom tqdm import tqdm\r\nfrom feed_forward_model import *\r\n\r\n\r\nclass DeepBSDESolver(FeedForwardModel):\r\n \"\"\"\r\n Implementation of the Deep BSDE solver and Primal bound using tensorflow.\r\n \"\"\"\r\n\r\n def __init__(self, bsde, run_name):\r\n super().__init__(bsde, run_name + \"_deep\")\r\n\r\n def train(self, sess):\r\n \"\"\"\r\n Train the Deep BSDE solver\r\n\r\n Args:\r\n sess (tf.Session): tensorflow session to use for training.\r\n\r\n Returns:\r\n _loss (float): loss after the last step of training\r\n _y_init (float): value of Y_0 after the last run\r\n \"\"\"\r\n\r\n # validation sets\r\n dw_valid, x_valid = self._bsde.sample(self._deep_config.valid_size)\r\n\r\n # since we still batches during validation, batch norm can stay on\r\n feed_dict_valid = {\r\n self._dw: dw_valid,\r\n self._x: x_valid,\r\n self._is_training: False\r\n }\r\n\r\n sess.run(tf.global_variables_initializer())\r\n\r\n # used to dump training progress\r\n test_writer = tf.summary.FileWriter(self.tb_dir, sess.graph)\r\n\r\n # do sgd\r\n for step in tqdm(range(1, self._deep_config.num_iterations + 1)):\r\n # check learning progress\r\n if step % self._deep_config.logging_frequency == 0:\r\n _, _, summary = sess.run(\r\n [self._loss, self._y_init, self._merged],\r\n feed_dict=feed_dict_valid)\r\n test_writer.add_summary(summary, step)\r\n\r\n # run one training batch\r\n dw_train, x_train = self._bsde.sample(self._deep_config.batch_size)\r\n sess.run(\r\n self._train_ops,\r\n feed_dict={\r\n self._dw: dw_train,\r\n self._x: x_train,\r\n self._is_training: True\r\n })\r\n return (self._loss, self._y_init)\r\n\r\n def build(self, deep_config):\r\n \"\"\"\r\n Build the neural network for the Deep BSDE solver and Primal bound\r\n\r\n Args:\r\n deep_config (DeepConfig): Configuration instructions for the neural network\r\n \"\"\"\r\n\r\n self._deep_config = deep_config\r\n start_time = time.time()\r\n\r\n #Generate the discrete time steps\r\n time_stamp = np.arange(\r\n 0, self._bsde.num_time_interval) * self._bsde.delta_t\r\n\r\n #inputs to the neural network. Will be filled by feed_dicts later on\r\n self._dw = tf.placeholder(\r\n TF_DTYPE, [None, self._bsde.dim, self._bsde.num_time_interval],\r\n name='dW')\r\n self._x = tf.placeholder(\r\n TF_DTYPE, [None, self._bsde.dim, self._bsde.num_time_interval + 1],\r\n name='X')\r\n self._is_training = tf.placeholder(tf.bool)\r\n\r\n #inital guess for Y_0. Might be available due to other approximations\r\n self._y_init = tf.Variable(\r\n tf.random_uniform(\r\n [1],\r\n minval=self._deep_config.y_init_range[0],\r\n maxval=self._deep_config.y_init_range[1],\r\n dtype=TF_DTYPE),\r\n name=\"y_init\")\r\n tf.summary.scalar('Y_0', self._y_init[0])\r\n\r\n # variable for Z_0\r\n z_init = tf.Variable(\r\n tf.random_uniform(\r\n [1, self._bsde.dim], minval=-.1, maxval=.1, dtype=TF_DTYPE))\r\n\r\n # init batch-sized vectors\r\n all_one_vec = tf.ones(\r\n shape=tf.stack([tf.shape(self._dw)[0], 1]), dtype=TF_DTYPE)\r\n y = all_one_vec * self._y_init\r\n z = tf.matmul(all_one_vec, z_init)\r\n\r\n # init integral approximations for Primal bound\r\n i = all_one_vec * 0.0\r\n q = all_one_vec * 0.0\r\n #old_z = all_one_vec * 0.0\r\n\r\n # will hold references to all used matrix weights\r\n self._matrix_weights = []\r\n\r\n with tf.variable_scope('forward'):\r\n\r\n for t in range(0, self._bsde.num_time_interval - 1):\r\n # Primal update\r\n a_star = self._bsde.max_a_tf(y)\r\n q = q + tf.exp(i) * self._bsde.f_star_tf(\r\n a_star) * self._bsde.delta_t\r\n i = i + self._bsde.delta_t * a_star\r\n\r\n # note that all the examples use sigma(t, X) independent of t and X,\r\n # so those calculations are already folded into the generation of dw\r\n\r\n # Deep BSDE update\r\n y = y - self._bsde.delta_t * (self._bsde.f_tf(\r\n time_stamp[t], self._x[:, :, t], y, z)) + tf.reduce_sum(\r\n z * self._dw[:, :, t], 1, keepdims=True)\r\n #+ tf.reduce_sum(\r\n # tf.get_variable(\r\n # 'skip_connection_%u' % t,\r\n # self._bsde.dim,\r\n # TF_DTYPE,\r\n # initializer=tf.random_normal_initializer(0.0, stddev=0.1, dtype=TF_DTYPE)) * old_z *\r\n # self._dw[:, :, t],\r\n # 1,\r\n # keepdims=True)\r\n #generate next gradient z via the nn\r\n #old_z = z\r\n\r\n #generate next subnet\r\n z, weight = self._subnetwork(self._x[:, :, t + 1], t + 1,\r\n self._deep_config.num_hiddens)\r\n z = z / self._bsde.dim\r\n self._matrix_weights.append(weight)\r\n\r\n # Last primal update\r\n a_star = self._bsde.max_a_tf(y)\r\n q = q + tf.exp(i) * self._bsde.f_star_tf(\r\n a_star) * self._bsde.delta_t\r\n i = i + self._bsde.delta_t * a_star\r\n\r\n # Primal bound averaged over batch\r\n self._primal = tf.reduce_mean(\r\n tf.exp(i) * self._bsde.g_tf(self._bsde.total_time, self.\r\n _x[:, :, -1]) - q)\r\n\r\n # Last Deep BSDE Update\r\n y = y - self._bsde.delta_t * self._bsde.f_tf(\r\n time_stamp[-1], self._x[:, :, -2], y, z) + tf.reduce_sum(\r\n z * self._dw[:, :, -1], 1, keepdims=True)\r\n\r\n # Calculate loss\r\n delta = y - self._bsde.g_tf(self._bsde.total_time,\r\n self._x[:, :, -1])\r\n self._loss = tf.reduce_mean(\r\n tf.where(\r\n tf.abs(delta) < DELTA_CLIP, tf.square(delta),\r\n 2 * DELTA_CLIP * tf.abs(delta) - DELTA_CLIP**2))\r\n tf.summary.scalar('primal_loss', self._loss)\r\n\r\n self._merged = tf.summary.merge_all()\r\n\r\n #sgd setup\r\n global_step = tf.get_variable(\r\n 'global_step', [],\r\n initializer=tf.constant_initializer(0),\r\n trainable=False,\r\n dtype=tf.int32)\r\n learning_rate = tf.train.piecewise_constant(\r\n global_step, self._deep_config.lr_boundaries,\r\n self._deep_config.lr_values)\r\n trainable_variables = tf.trainable_variables()\r\n grads = tf.gradients(self._loss, trainable_variables)\r\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\r\n apply_op = optimizer.apply_gradients(\r\n zip(grads, trainable_variables),\r\n global_step=global_step,\r\n name='train_step')\r\n all_ops = [apply_op] + self._extra_train_ops\r\n self._train_ops = tf.group(*all_ops)\r\n self._t_build = time.time() - start_time\r\n\r\n def primal(self, sess, primal_config):\r\n \"\"\"\r\n Calculate the Primal bound\r\n\r\n Args:\r\n sess (tf.Session): tensorflow session to use\r\n primal_config (PrimalConfig): Configuration instructions for the primal bound\r\n\r\n Returns:\r\n float: Primal bound\r\n \"\"\"\r\n start_time = time.time()\r\n num_batches = np.ceil(primal_config.primal_num_total_samples /\r\n primal_config.primal_batch_size).astype(\r\n np.int32)\r\n\r\n # Primal bound of the individual batches\r\n primals = np.zeros(shape=[num_batches])\r\n\r\n for batch in tqdm(range(num_batches)):\r\n dw_train, x_train = self._bsde.sample(\r\n primal_config.primal_batch_size)\r\n primals[batch] = sess.run(\r\n self._primal,\r\n feed_dict={\r\n self._dw: dw_train,\r\n self._x: x_train,\r\n self._is_training: False\r\n })\r\n if (batch % self._deep_config.logging_frequency ==\r\n self._deep_config.logging_frequency - 1):\r\n logging.debug(\"Batch: %5u, primal: %.4e\",\r\n (batch + 1, np.mean(primals[:batch])))\r\n\r\n elapsed_time = time.time() - start_time\r\n return np.mean(primals), (num_batches * primal_config.primal_batch_size\r\n / elapsed_time).astype(np.int64)\r\n\r\n def get_y0(self, sess):\r\n \"\"\"\r\n Return the current Y_0 approximation\r\n\r\n Args:\r\n sess (tf.Session): tensorflow session to use\r\n\r\n Returns:\r\n float: current Y_0 approximation\r\n \"\"\"\r\n return sess.run(self._y_init)[0]\r\n\r\n def get_matrix_weights(self, sess):\r\n \"\"\"\r\n \tGet the matrix weights used in neural network \t\r\n\r\n Args:\r\n sess (tf.Session): tensorflow session to use\r\n\r\n Returns:\r\n np.array(size=[num_timesteps, layer_count]): matrix weights\r\n \"\"\"\r\n return sess.run(self._matrix_weights)\r\n","sub_path":"deep_bsde_solver.py","file_name":"deep_bsde_solver.py","file_ext":"py","file_size_in_byte":9664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"240775933","text":"import os\nimport ws.logger\nimport ws.i_o.writer as writer\nimport shopify\n# import ws.i_o.shopify_api as shopify\nimport ws.i_o.sheet as sheet\nimport vcr\nfrom datetime import date\n\nclass Command(object):\n SHEET_KEY = '1Y1j7Fxu9TxHcr9IJG8k1x27CjQ83gVjI-5klX7o6vgo'\n\n def __init__(self, path, args):\n self.field_names = (\n ['quantity', 'title', 'vendor', 'product_type', 'tags'] +\n ['pid', 'id', 'barcode', 'code_type', 'sku', 'comment', 'cost_price', 'weight', 'weight'] +\n ['length', 'width', 'height', 'supplier', 'supplier_name', 'stock_type', 'stock_depth', 'stock_height', 'stock_width'] +\n ['option1', 'option1_value', 'option2', 'option2_value', 'option3', 'option3_value'] +\n ['price', 'image', 'page']\n )\n self.title = 'import'\n self.processed_product_ids = ['pid', '']\n self.products = {}\n self.variants = {}\n\n def load_products(self):\n with vcr.use_cassette('cache/products.yml', filter_headers=['authorization'], record_mode='once'):\n for p in shopify.items(shopify.Product, 'id,tags,vendor,title,product_type,options,images,variants,template_suffix'):\n self.products[p.id] = p\n for v in p.variants:\n self.variants[v.id] = v\n\n def execute(self):\n from ws.debugger import pry; pry(globals(), locals())\n # self.load_products()\n # worksheet = sheet.open(self.SHEET_KEY, self.title)\n # variants = worksheet.get_all_values()\n # variants.pop(0) # remove header\n # count = 0\n # for variant in variants:\n # # if variant[0] and self.import_variant(variant):\n # if variant[0] and self.add_product(variant):\n # count += 1\n # ws.logger.info('Imported %d lines' % (count))\n\n def import_variant(self, variant):\n variant_id = variant[1]\n sku = variant[4]\n cost_price = variant[6]\n weight = variant[7]\n # ws.logger.info('V %s:' % variant_id)\n if int(variant_id) in self.variants.keys():\n v = self.variants[int(variant_id)]\n save = False\n if not v.sku and sku:\n ws.logger.info('Vs %s: %s->%s' % (v.id, v.sku, sku))\n v.sku = sku\n save = True\n if not v.weight and weight:\n ws.logger.info('Vw %s: %s->%s' % (v.id, v.weight, weight))\n v.weight = weight\n save = True\n if save:\n v.save()\n\n def add_product(self, variant):\n product_id = variant[0]\n if product_id in self.processed_product_ids:\n return True\n self.processed_product_ids.append(product_id)\n if int(product_id) in self.products.keys():\n p = self.products[int(product_id)]\n meta = shopify.metafields(p)\n if meta.get(\"supplier\", '') == '':\n ws.logger.info('Add supplier %s -> %s' % (p.id, variant[12]))\n # p.add_metafield(shopify.Metafield({'namespace': 'playmakers', 'key': 'supplier', 'value': variant[12], 'value_type': 'string'}))\n if meta.get(\"cost_price\", '') == '' and variant[6]:\n ws.logger.info('Add cost_price %s -> %s' % (p.id, variant[6]))\n p.add_metafield(shopify.Metafield({'namespace': 'playmakers', 'key': 'cost_price', 'value': variant[6], 'value_type': 'string'}))\n # meta = shopify.metafields(v, ns='variant')\n return True\n","sub_path":"ws/commands/stockimport.py","file_name":"stockimport.py","file_ext":"py","file_size_in_byte":3537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"526458700","text":"import numpy as np\nimport cv2\nfrom skimage.morphology import skeletonize\n\n\ndef removedot(invertThin):\n temp0 = np.array(invertThin[:])\n temp0 = np.array(temp0)\n temp1 = temp0 / 255\n temp2 = np.array(temp1)\n temp3 = np.array(temp2)\n\n enhanced_img = np.array(temp0)\n filter0 = np.zeros((10, 10))\n W, H = temp0.shape[:2]\n filtersize = 6\n\n for i in range(W - filtersize):\n for j in range(H - filtersize):\n filter0 = temp1[i:i + filtersize, j:j + filtersize]\n\n flag = 0\n if sum(filter0[:, 0]) == 0:\n flag += 1\n if sum(filter0[:, filtersize - 1]) == 0:\n flag += 1\n if sum(filter0[0, :]) == 0:\n flag += 1\n if sum(filter0[filtersize - 1, :]) == 0:\n flag += 1\n if flag > 3:\n temp2[i:i + filtersize, j:j + filtersize] = np.zeros((filtersize, filtersize))\n\n return temp2\n\n\ndef get_descriptors(img):\n clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n img = clahe.apply(img)\n #img = image_enhance.image_enhance(img)\n img = np.array(img, dtype=np.uint8)\n # Threshold\n ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU);\n # Normalize to 0 and 1 range\n img[img == 255] = 1\n\n # Thinning\n skeleton = skeletonize(img)\n skeleton = np.array(skeleton, dtype=np.uint8)\n skeleton = removedot(skeleton)\n # Harris corners\n harris_corners = cv2.cornerHarris(img, 3, 3, 0.04)\n harris_normalized = cv2.normalize(harris_corners, 0, 255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32FC1)\n threshold_harris = 125;\n # Extract keypoints\n keypoints = []\n for x in range(0, harris_normalized.shape[0]):\n for y in range(0, harris_normalized.shape[1]):\n if harris_normalized[x][y] > threshold_harris:\n keypoints.append(cv2.KeyPoint(y, x, 1))\n # Define descriptor\n orb = cv2.ORB_create()\n # Compute descriptors\n _, des = orb.compute(img, keypoints)\n return (keypoints, des);","sub_path":"fpmatching.py","file_name":"fpmatching.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"379299143","text":"from selenium import webdriver\nfrom selenium.webdriver.remote.webdriver import WebDriver as Remote\n\n\n#启动浏览器驱动\ndef browser():\n # host = '127.0.0.1:4444'\n # dc = {\"browserName\": \"firefox\"}\n # driver = Remote(command_executor='http://' + host + '/wd/hub',\n # desired_capabilities=dc)\n driver = webdriver.Firefox()\n return driver\n\n\n\nif __name__ == '__main__':\n driver = browser()\n driver.get('http://www.baidu.com')\n driver.quit()\n\n","sub_path":"mztestpro/bbs/test_case/models/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"90150861","text":"import numpy as np\n\ndef countUpToLengthN(n):\n\n counts = np.ones(10,dtype=np.uint64)\n counts[0] = 0\n total = 0\n for i in range(2,n+1):\n for j in range(0,10):\n counts[j] = sum(counts[j:])\n total += 2*sum(counts[1:]) + counts[0] - 9\n return total + 9\n\nprint(countUpToLengthN(100))","sub_path":"problem113/113.py","file_name":"113.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"273797393","text":"# https://atcoder.jp/contests/abc032/tasks/abc032_d\nimport sys\nsys.setrecursionlimit(2147483647)\nINF=float(\"inf\")\nMOD=10**9+7\ninput=lambda :sys.stdin.readline().rstrip()\nfrom bisect import bisect\ndef resolve():\n n,W=map(int,input().split())\n VW=[tuple(map(int,input().split())) for _ in range(n)]\n\n # n <= 30 -> 半分に分けてmerge\n if(n<=30):\n ans=0\n A=VW[:n//2]; B=VW[n//2:]\n P=[None]*(2**(n//2))\n Q=[None]*(2**(n-n//2))\n # それぞれ全列挙 (O(n2^(n/2)))\n for S in range(2**(n//2)):\n v,w=0,0\n for i in range(n//2):\n if(S&(1<W): continue\n i=bisect(R,(W-w,INF))\n ans=max(ans,v+R[i-1][1])\n print(ans)\n return\n\n # VMAX <= 2*10^5 -> knapsack 2\n VMAX=sum(v for v,w in VW)\n if(VMAX<=2*(10**5)):\n dp=[INF]*(VMAX+1)\n dp[0]=0\n for i in range(n):\n v,w=VW[i]\n ndp=dp[:]\n for v0 in range(VMAX):\n if(v+v0<=VMAX):\n ndp[v+v0]=min(ndp[v+v0],dp[v0]+w)\n dp=ndp\n for i in range(VMAX,-1,-1):\n if(dp[i]<=W):\n print(i)\n return\n\n # WMAX <= 2*10^5 -> knapsack 1\n WMAX=sum(w for v,w in VW)\n if(WMAX<=2*(10**5)):\n dp=[-INF]*(WMAX+1)\n dp[0]=0\n for i in range(n):\n ndp=dp[:]\n v,w=VW[i]\n for w0 in range(WMAX+1):\n if(w+w0<=WMAX):\n ndp[w+w0]=max(ndp[w+w0],dp[w0]+v)\n dp=ndp\n print(max(dp[:W+1]))\n return\nresolve()\n","sub_path":"ABC032/d_ナップサック問題.py","file_name":"d_ナップサック問題.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"24013361","text":"import logging\nimport os\nimport subprocess\nimport threading\n\nimport multiprocessing as mp\n\nfrom logging.handlers import TimedRotatingFileHandler\n\n\ndef log_command(logger, command, **kwargs):\n logger.info(' '.join(command))\n output = subprocess.check_output(' '.join(command), **kwargs)\n logger.debug(output)\n\n\ndef log_command_to_queue(log_queue, command, **kwargs):\n log_queue.put((' '.join(command), logging.INFO))\n try:\n output = subprocess.check_output(' '.join(command), **kwargs)\n failed = False\n except subprocess.CalledProcessError:\n output = \"Command failed!\"\n failed = True\n\n log_queue.put((output, logging.DEBUG))\n return failed\n\n\ndef process_logs(q, logger):\n for msg,level in iter(q.get, 'STOP'):\n if level == logging.INFO:\n logger.info(msg)\n else:\n logger.debug(msg)\n\n\ndef get_logger(name, debug=False, dryrun=False):\n logger = logging.getLogger(name)\n logger.setLevel(logging.DEBUG)\n\n # create a logging format\n if dryrun:\n formatter = logging.Formatter(\n '%(asctime)s - %(name)s - %(levelname)s - (DRYRUN) - %(message)s'\n )\n else:\n formatter = logging.Formatter(\n '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n )\n\n stream_handler = logging.StreamHandler()\n stream_handler.setLevel(logging.DEBUG if debug else logging.INFO)\n stream_handler.setFormatter(formatter)\n\n logger.addHandler(stream_handler)\n\n if os.environ.get('AWS_BATCH_JOB_ID'):\n log_file = os.path.abspath(\n '{}.log'.format(os.environ['AWS_BATCH_JOB_ID'])\n )\n file_handler = logging.FileHandler(log_file)\n file_handler.setLevel(logging.DEBUG)\n file_handler.setFormatter(formatter)\n\n # add the handlers to the logger\n logger.addHandler(file_handler)\n else:\n log_file = None\n file_handler = None\n\n return logger, log_file, file_handler\n\n\ndef get_thread_logger(logger):\n log_queue = mp.Queue()\n log_thread = threading.Thread(target=process_logs,\n args=(log_queue, logger))\n log_thread.start()\n\n return log_queue, log_thread\n\n\ndef get_trfh_logger(name, *args):\n # function to create a rotating-file logger\n # with potentially multiple file handlers\n\n logger = logging.getLogger(name)\n logger.setLevel(logging.DEBUG)\n\n # create a logging format\n formatter = logging.Formatter(\n '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n )\n\n for file_name, log_level, when, backup_count in args:\n log_handler = TimedRotatingFileHandler(file_name, when=when,\n backupCount=backup_count)\n log_handler.setLevel(log_level)\n log_handler.setFormatter(formatter)\n logger.addHandler(log_handler)\n\n return logger\n\n","sub_path":"utilities/log_util.py","file_name":"log_util.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"274985431","text":"import argparse\nimport json\nimport sys\n\n# We're going to explicitly use a local installation of Pyserini (as opposed to a pip-installed one).\n# Comment these lines out to use a pip-installed one instead.\nsys.path.insert(0, './')\n\nfrom pyserini.search import SimpleSearcher\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--qrels', type=str, help='qrels file', required=True)\n parser.add_argument('--index', type=str, help='index location', required=True)\n args = parser.parse_args()\n\n searcher = SimpleSearcher(args.index)\n with open(args.qrels, 'r') as reader:\n for line in reader.readlines():\n arr = line.split('\\t')\n doc = json.loads(searcher.doc(arr[2]).raw())['contents']\n print(f'{arr[2]}\\t{doc}')\n","sub_path":"scripts/msmarco-passage/lookup_docs_from_qrels.py","file_name":"lookup_docs_from_qrels.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"54217098","text":"import os\nimport sys\n\nPROJECT_DIR = os.path.dirname(__file__)\n\nDATABASES = {\n 'default':{\n 'ENGINE': 'django.db.backends.sqlite3',\n }\n}\n\nROOT_URLCONF = 'datetimewidget.tests.urls'\n\nINSTALLED_APPS = [\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'datetimewidget',\n 'datetimewidget.tests',\n]\n\nDEFAULT_FILE_STORAGE = 'datetimewidget.storage.DatabaseStorage'\n\nMEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')\n\n# Disable migrations.\n# http://stackoverflow.com/a/28560805/247542\nclass DisableMigrations(object):\n\n def __contains__(self, item):\n return True\n\n def __getitem__(self, item):\n return \"notmigrations\"\nSOUTH_TESTS_MIGRATE = False # <= Django 1.8\n# if django.VERSION > (1, 7, 0): # > Django 1.8 \n# MIGRATION_MODULES = DisableMigrations()\n\nUSE_TZ = True\n\nSECRET_KEY = 'secret'\n\nAUTH_USER_MODEL = 'auth.User'\n\nSITE_ID = 1\n\nBASE_SECURE_URL = 'https://localhost'\n\nBASE_URL = 'http://localhost'\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n #'django.middleware.transaction.TransactionMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.locale.LocaleMiddleware', \n)\n\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error when DEBUG=False.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n\n# Required for Django>=1.10.\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [\n '%s/templates' % PROJECT_DIR,\n ],\n# 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.contrib.auth.context_processors.auth',\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.template.context_processors.i18n',\n 'django.template.context_processors.media',\n 'django.template.context_processors.static',\n 'django.template.context_processors.tz',\n 'django.contrib.messages.context_processors.messages',\n ],\n 'loaders': [\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n ],\n 'debug': True,\n },\n },\n]\n","sub_path":"datetimewidget/tests/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"11712466","text":"import os\nimport shutil\nimport random\nimport numpy as np\nimport argparse\n\n\nfile_res_mutant_line = \"\"\n\n\ndef parserCommad():\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--min_order_num', action='store',\n dest='min_order_num',\n type=int,\n default=2,\n help=\"The minimum order of a higher-order mutants.\")\n\n parser.add_argument('--max_order_num', action='store',\n dest='max_order_num',\n type=int,\n default=7,\n help=\"The maximum order of a higher-order mutants.\")\n\n parser.add_argument('--version', action='version',\n version='%(prog)s 1.0')\n\n results = parser.parse_args()\n\n return results\n\n\ndef _MutantLine(wait_fault_num, list_nonfault_line, list_fault_line, list_mutant_line):\n if wait_fault_num == 0:\n str_mutant_line = \",\".join(list_mutant_line)\n global file_res_mutant_line\n file_res_mutant_line = file_res_mutant_line + str_mutant_line + '\\n'\n return\n\n if wait_fault_num == 2:\n for fault_line in list_fault_line:\n if str(fault_line) in list_mutant_line:\n return\n list_mutant_line_copy = list_mutant_line.copy()\n list_mutant_line_copy.append(str(fault_line))\n _MutantLine(wait_fault_num-1, list_nonfault_line, list_fault_line, list_mutant_line_copy)\n else:\n for non_fault_line in list_nonfault_line:\n if str(non_fault_line) in list_mutant_line:\n return\n list_mutant_line_copy = list_mutant_line.copy()\n list_mutant_line_copy.append(str(non_fault_line))\n _MutantLine(wait_fault_num - 1, list_nonfault_line, list_fault_line, list_mutant_line_copy)\n\n\ndef recordMutantLine(list_file_res_mutant_line, fault_num, list_fault_line, list_nonfault_line):\n list_file_res_mutant_line.append([])\n _MutantLine(fault_num, list_nonfault_line, list_fault_line, [])\n global file_res_mutant_line\n list_file_res_mutant_line[0] = file_res_mutant_line\n file_res_mutant_line = \"\"\n\n\nif __name__ == \"__main__\":\n\n # 1.read the file of \"./output/Fault_Record.txt\", record all of the fault lines,\n # and record all of the non-fault lines index.\n with open(\"./output/Fault_Record.txt\", 'r') as f:\n str_Fault_Record = f.read()\n f.close()\n list_fault_line = []\n list_fault_line_temp = str_Fault_Record.split(\"Line \")[1:]\n for fault_line_temp in list_fault_line_temp:\n list_fault_line.append(int(fault_line_temp.split(\": \")[0]))\n # print(list_fault_line)\n\n with open(\"./output/suspicious_first_order.txt\", 'r') as f:\n str_suspicious = f.read().split(\"Sus_Ochiai:\")[0]\n f.close()\n list_nonfault_line = []\n list_nonfault_line_temp = str_suspicious.split(\"(\")[1:]\n for nonfault_line_temp in list_nonfault_line_temp:\n line_index = int(nonfault_line_temp.split(\",\")[0])\n if line_index not in list_fault_line and line_index not in list_nonfault_line:\n list_nonfault_line.append(line_index)\n # print(list_nonfault_line)\n\n # 2.generate the record of mutant lines as \"mutant_line.txt\".\n list_file_res_mutant_line = []\n list_line = []\n list_line.extend(list_fault_line)\n list_line.extend(list_nonfault_line)\n\n with open(\"./_entire_randomization_higher_order_mutant_set/res_mutant_line.txt\", 'w') as f:\n f.write(\"\")\n f.close()\n\n with open(\"./output/res_record.txt\", 'r') as f:\n list_res_record = f.readlines()\n f.close()\n # print(len(list_res_record))\n\n min_order_num = parserCommad().min_order_num\n max_order_num = parserCommad().max_order_num\n f = open(\"./_entire_randomization_higher_order_mutant_set/res_mutant_line.txt\", 'a')\n for mutant_line_num in range(min_order_num, max_order_num+1): # Select between the min_order_numnd-order to max_order_numth-order mutants.\n mutant_num_every_order = len(list_res_record) * 50 # len(list_res_record) * 1\n for mutant_index in range(mutant_num_every_order):\n if mutant_line_num > len(list_line):\n mutant_line_num = len(list_line)\n list_choice_line_index = []\n now_choice_index = 0\n while now_choice_index < mutant_line_num:\n choice_line_index = np.random.choice(list_line)\n if choice_line_index in list_choice_line_index:\n continue\n list_choice_line_index.append(choice_line_index)\n now_choice_index += 1\n\n list_choice_line_index.sort()\n for item_index in range(len(list_choice_line_index)):\n list_choice_line_index[item_index] = str(list_choice_line_index[item_index])\n str_choice_line_index = \",\".join(list_choice_line_index)\n f.write(str_choice_line_index)\n if mutant_index != mutant_num_every_order - 1 or mutant_line_num != max_order_num:\n f.write(\"\\n\")\n f.close()\n\n","sub_path":"entire_randomization_higher_order_MBFL/create_res_mutant_line.py","file_name":"create_res_mutant_line.py","file_ext":"py","file_size_in_byte":5087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"647282194","text":"# practica_09/urls.py\n\nfrom django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^test_template/$', views.test_template, name='test_template'),\n url(r'^nuevo_musico/$', views.nuevo_musico, name='nuevo_musico'),\n url(r'^nuevo_instrumento/$', views.nuevo_instrumento, name='nuevo_instrumento'),\n url(r'^nuevo_album/$', views.nuevo_album, name='nuevo_album'),\n url(r'^nuevo_grupo/$', views.nuevo_grupo, name='nuevo_grupo'),\n url(r'^correcto/$', views.correcto, name='correcto'),\n url(r'^incorrecto/(?P\\w{0,50})/$', views.incorrecto, name='incorrecto'),\n url(r'^modificar/(?P\\w{0,50})/(?P\\w{0,50})/$', views.modificar, name='modificar'),\n url(r'^editar/(?P\\w{0,50})/$', views.modificar, name='editar'),\n url(r'^borrar/(?P\\w{0,50})/(?P\\w{0,50})/$', views.borrar, name='borrar'),\n url(r'^login/$', views.login, name='login'),\n url(r'^busqueda/$', views.busqueda, name='busqueda'),\n url(r'^reclama_datos/$', views.reclama_datos, name='reclama_datos'),\n url(r'^ajax/$', views.tablaAjax, name='ajax'),\n url(r'^mapa/(?P\\w{0,50})/$', views.crearMapa, name='mapa'),\n url(r'^grafico/$', views.crearGrafico, name='grafico'),\n url(r'^grafico_ajax/$', views.crearGraficoAjax, name='graficoAjax'),\n url(r'^reclama_datos_grafico/$', views.reclama_datos_grafico, name='reclama_datos_grafico'),\n \n]","sub_path":"practica9/web/practica_09/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"178260464","text":"\"\"\"\n\ncubeset - Defines a CubeSet class that contains code to handle operations\n on several IFU data cubes, e.g., coaddition\n\n\"\"\"\n\nimport os\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom astropy.io import ascii\nfrom astropy.io import fits as pf\nfrom .oscube import OsCube\n\n\nclass CubeSet(list):\n \"\"\"\n\n The Cubeset class is effectively just a list of Spec1d instances that\n includes operations that act on the whole list (e.g., coadds)\n\n \"\"\"\n\n # ------------------------------------------------------------------------\n\n def __init__(self, inlist, informat=None, indir=None, maskfile=None,\n verbose=True):\n \"\"\"\n\n There are three ways to create a Cubeset instance\n\n Option 1: List of filenames\n Option 2: List of already existing OsCubeinstances\n Option 3: A filename, where the file contains within it a list\n of input files\n - Within this option is a specialized format for the coadd, which\n can be chosen by setting informat='coadd'\n For this option, the file must have the following columns:\n File G CRVAL1 CRVAL2 CRPIX1 CRPIX2\n where the column names are fairly self-explanatory except for G,\n which is either 0 or 1 and indicates whether the file is\n good (G=1) or bad (G=0)\n\n \"\"\"\n\n \"\"\" Set default values \"\"\"\n self.info = None\n\n \"\"\"\n First check to see if inlist is a list, of either filenames (strings)\n or OsCube instances (options 1 and 2).\n If it's not a list, check to see if it is a single string, in which\n case it may be a file that contains a list of filenames (option 3)\n \"\"\"\n\n if isinstance(inlist, list):\n \"\"\" Option 1 or 2: list of files or of OsCube instances \"\"\"\n if isinstance(inlist[0], str):\n for f in inlist:\n try:\n cube = OsCube(f)\n except IOError:\n print('')\n print('Could not open requested file: %s' % f)\n return\n self.append(cube)\n\n elif isinstance(inlist[0], OsCube):\n for cube in inlist:\n self.append(cube)\n\n else:\n raise TypeError('input list must be a list of filenames or'\n ' OsCube instances')\n\n elif isinstance(inlist, str):\n \"\"\" Option 3: a file containing a list of filenames \"\"\"\n try:\n if informat == 'coadd' or informat is None:\n intab = ascii.read(inlist)\n else:\n intab = ascii.read(inlist, guess=False, format=informat)\n except IOError:\n print('')\n print('Could not open requested file: %s' % inlist)\n print('')\n return\n\n \"\"\"\n Read in the files.\n If informat is 'coadd', then use the G column to only select\n the good files\n \"\"\"\n if informat == 'coadd':\n goodtab = intab[intab['G'] == 1]\n flist = goodtab['File']\n self.info = goodtab\n else:\n flist = intab.columns[0]\n self.info = intab\n for f in flist:\n if indir is 'fromfile':\n osirisdir = os.getenv('osiris')\n obsdir = (f.split('_')[0]).replace('s', '20')\n infile = os.path.join(osirisdir, obsdir, 'Clean', f)\n elif indir is not None:\n infile = os.path.join(indir, f)\n else:\n infile = f\n try:\n cube = OsCube(infile)\n except IOError:\n print('')\n print('Could not open requested file: %s' % infile)\n return\n self.append(cube)\n\n # ------------------------------------------------------------------------\n\n def clean(self, maskfile='default', maskdir='../Clean',\n outdir='../Clean', debug=False, **kwargs):\n \"\"\"\n\n Runs the clean algorithm for each cube in the CubeSet\n\n \"\"\"\n\n \"\"\"\n Read the mask file into the first cube, and then copy it to the\n subsequent cubes\n \"\"\"\n self[0].read_maskfile(maskfile, maskdir)\n for i in range(1, len(self)):\n self[i].mask = self[0].mask.copy()\n\n \"\"\"\n Loop through the files, cleaning each one and saving to the\n designated directory\n \"\"\"\n print('')\n for f in self:\n basename = os.path.basename(f.infile)\n outfile = os.path.join(outdir, basename)\n varfile = outfile.replace('.fits', '.varspec')\n if debug:\n print('Input file: %s' % f.infile)\n print('Output file: %s' % outfile)\n print('Varspec file: %s' % varfile)\n f.make_varspec(outfile=varfile)\n f.clean(**kwargs)\n f.save_drp('clean', outfile)\n\n # ------------------------------------------------------------------------\n\n def coadd(self, configfile, outfile, wlim=None, testslice='default',\n testonly=False, slroot='slice', verbose=True, **kwargs):\n \"\"\"\n\n Coadd the cubes through calls to swarp\n (NOT YET IMPLEMENTED)\n\n \"\"\"\n\n \"\"\"\n Get the range of wavelength slices to extract from the cube.\n The default is to use the full wavelength range.\n \"\"\"\n if wlim is not None:\n wmin = wlim[0]\n wmax = wlim[1]\n else:\n wmin = 0\n wmax = self[0].wsize\n\n \"\"\"\n Make a test file, with the swarped coadd of a single slice.\n This is used to set the size of the output array\n \"\"\"\n if testslice == 'default':\n testslice = int((wmin + wmax) / 2.)\n\n for i, c in enumerate(self):\n c.set_imslice(testslice, display=False)\n outname = '%s_%02d.fits' % (slroot, i)\n outwht = outname.replace('.fits', '_wht.fits')\n hdr = c['slice'].header\n if 'ELAPTIME' in hdr.keys():\n hdr['exptime'] = hdr['elaptime']\n elif 'ITIME' in hdr.keys():\n hdr['exptime'] = hdr['itime'] / 1000.\n c['slice'].writeto(outname, overwrite=True)\n pf.PrimaryHDU(c.mask.astype(int),\n hdr).writeto(outwht, overwrite=True)\n os.system('swarp %s*fits -c swarp_coseye.config' % slroot)\n\n \"\"\" If the testonly mode has been requested, quit here \"\"\"\n if testonly:\n return\n\n \"\"\"\n Get the relevent information out of the test file, and then delete\n the temporary files.\n The reason for using the WCS call is to get the WCS information in \n the header of the swarped file into a standard format\n \"\"\"\n tmphdu = pf.open('coadd.fits')\n hdr2d = (wcs.WCS(tmphdu[0].header)).to_header()\n dim2d = tmphdu[0].data.shape\n if testonly:\n return\n else:\n os.system('rm %s*fits' % slroot)\n os.system('rm coadd*fits')\n\n \"\"\" Split all the cubes into their slices \"\"\"\n if(verbose):\n print('Splitting the cubes into slices')\n for i, c in enumerate(self):\n outroot = '%s_%i' % (slroot, i)\n c.slice_cube(wlim=wlim, outroot=outroot)\n","sub_path":"keckcode/osiris/cubeset.py","file_name":"cubeset.py","file_ext":"py","file_size_in_byte":7626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"334657847","text":"import re\nimport time\nimport clr\nfrom System import Convert\nfrom System import Text\n\nplayerside = None\nsideflip = None\ncstack = { }\n\nversioncheck = None\n\ndef clearCache(group, x = 0, y = 0):\n if confirm(\"Reset the Autoscript Tag cache?\"):\n global savedtags\n savedtags = { }\n notify(\"{} reset the global tag cache.\".format(me))\n if confirm(\"Reset the Attachment Dictionary?\"):\n setGlobalVariable('cattach', \"{ }\")\n notify(\"{} reset the global attachment dictionary.\".format(me))\n\ndef shuffle(group, x = 0, y = 0):\n global versioncheck\n if versioncheck == None:\n (url, code) = webRead('http://octgn.gamersjudgement.com/OCTGN/game.txt')\n if code == 200:\n if url == gameVersion:\n whisper(\"Your game definition is up-to-date\")\n else:\n notify(\"{}'s game definition is out-of-date!\".format(me))\n if confirm(\"There is a new game definition available! Your version {}. Current version {}.\\nClicking yes will open your browser to the location of the most recent version.\".format(gameVersion, url)):\n openUrl('http://octgn.gamersjudgement.com/viewtopic.php?f=8&t=195')\n else:\n whisper(\"Newest game definition version is unavailable at the moment\")\n versioncheck = True\n for card in group:\n if card.isFaceUp:\n card.isFaceUp = False\n group.shuffle()\n\nautoscripts = True\n\ndef disable(card, x = 0, y = 0):\n mute()\n global autoscripts\n if autoscripts == False:\n autoscripts = True\n notify(\"{} enables autoscripts\".format(me))\n else:\n autoscripts = False\n notify(\"{} disables autoscripts\".format(me))\n\nsavedtags = { }\n\ndef getTags(card, key):\n mute()\n global savedtags\n if re.search(r\"//\", card.name) and card.Type != None and not re.search(r\"Instant\", card.Type) and not re.search(r\"Sorcery\", card.Type):\n if card.isAlternateImage == True:\n cardname = (card.name)[(card.name).find(\"/\")+3:]\n else:\n cardname = (card.name)[:(card.name).find(\"/\")-1]\n else:\n cardname = card.name\n encodedcardname = Convert.ToBase64String(Text.Encoding.UTF8.GetBytes(cardname))\n if not cardname in savedtags:\n (fulltag, code) = webRead('http://octgn.gamersjudgement.com/tags.php?id={}'.format(encodedcardname))\n if code != 200:\n whisper('tag database is currently unavailable.')\n fulltag = tags[cardname]\n tagdict = { }\n classpieces = fulltag.split('; ')\n for classes in classpieces:\n if classes != \"\":\n actionlist = classes.split('.')\n actiondict = { }\n for actionpieces in actionlist[1:]:\n actionname = actionpieces[:actionpieces.find(\"[\")]\n actionparam = actionpieces[actionpieces.find(\"[\")+1:actionpieces.find(\"]\")]\n if actionname == 'token':\n if not 'autotoken' in tagdict:\n tagdict['autotoken'] = [ ]\n tokenname = actionparam[:actionparam.find(\",\")]\n if not tokenname in tagdict['autotoken']:\n tagdict['autotoken'].append(tokenname)\n if actionname == 'marker':\n if not 'automarker' in tagdict:\n tagdict['automarker'] = [ ]\n markername = actionparam[:actionparam.find(\",\")]\n if not markername in tagdict['automarker']:\n tagdict['automarker'].append(markername)\n if not actionname in actiondict:\n actiondict[actionname] = [ ]\n actiondict[actionname].append(actionparam)\n tagdict[actionlist[0]] = actiondict\n savedtags[cardname] = tagdict\n if key == 'allactivate':\n st = savedtags[cardname]\n if 'initactivate1' in st: text11 = st['initactivate1']\n else: text11 = ''\n if 'activate1' in st: text12 = st['activate1']\n else: text12 = ''\n if 'initactivate2' in st: text21 = st['initactivate2']\n else: text21 = ''\n if 'activate2' in st: text22 = st['activate2']\n else: text22 = ''\n if 'initactivate3' in st: text31 = st['initactivate3']\n else: text31 = ''\n if 'activate3' in st: text32 = st['activate3']\n else: text32 = ''\n if 'initactivate4' in st: text41 = st['initactivate4']\n else: text41 = ''\n if 'activate4' in st: text42 = st['activate4']\n else: text42 = ''\n if 'initactivate5' in st: text51 = st['initactivate5']\n else: text51 = ''\n if 'activate5' in st: text52 = st['activate5']\n else: text52 = ''\n return \"1) {}\\n --> {}\\n2) {}\\n --> {}\\n3) {}\\n --> {}\\n4) {}\\n --> {}\\n5) {}\\n --> {}\".format(text11, text12, text21, text22, text31, text32, text41, text42, text51, text52)\n if key in savedtags[cardname]:\n return savedtags[cardname][key]\n else:\n return \"\"\n\ndef submitTags(card, x = 0, y = 0):\n if re.search(r\"//\", card.name) and card.Type != None and not re.search(r\"Instant\", card.Type) and not re.search(r\"Sorcery\", card.Type):\n if card.isAlternateImage == True:\n cardname = (card.name)[(card.name).find(\"/\")+3:]\n else:\n cardname = (card.name)[:(card.name).find(\"/\")-1]\n else:\n cardname = card.name\n encodedcardname = Convert.ToBase64String(Text.Encoding.UTF8.GetBytes(cardname))\n (url, code) = webRead('http://octgn.gamersjudgement.com/tags.php?id={}'.format(encodedcardname))\n if code == 200:\n if url != \"\":\n if not confirm(\"Submit an edit?\\n{}\".format(url)): return()\n openUrl('http://octgn.gamersjudgement.com/submit.php?id={}'.format(encodedcardname))\n else:\n whisper(\"cannot connect to online database.\")\n\ndef transform(card, x = 0, y = 0):\n mute()\n if re.search(r\"//\", card.name) and card.Type != None and not re.search(r\"Instant\", card.Type) and not re.search(r\"Sorcery\", card.Type):\n if re.search(r'DFC', card.Rarity):\n notify(\"{} transforms {}.\".format(me, card))\n else:\n notify(\"{} flips {}.\".format(me, card))\n card.switchImage\n else:\n if card.isFaceUp == True:\n notify(\"{} morphs {} face down.\".format(me, card))\n card.isFaceUp = False\n else:\n card.isFaceUp = True\n notify(\"{} morphs {} face up.\".format(me, card))\n\n##################################\n#Card Functions -- Autoscripted \n##################################\n\ndef trigAbility(card, tagclass, pile):\n mute()\n markerdict = { }\n text = \"\"\n inittag = getTags(card, 'init{}'.format(tagclass))\n####aura attachment####\n if tagclass == 'cast' and card.Subtype != None and re.search(r'Aura', card.Subtype):\n target = (card for card in table if card.targetedBy)\n targetcount = sum(1 for card in table if card.targetedBy)\n if targetcount == 1:\n for targetcard in target:\n while getGlobalVariable('cattach') == 'CHECKOUT':\n whisper(\"Global card attachment dictionary is currently in use, please wait.\")\n return CRASH\n cattach = eval(getGlobalVariable('cattach'))\n setGlobalVariable('cattach', 'CHECKOUT')\n cattach[card._id] = targetcard._id\n targetcard.target(False)\n setGlobalVariable('cattach', str(cattach))\n text += \", targeting {}\".format(targetcard)\n####init tag checking####\n if 'tapped' in inittag and card.orientation == Rot90:\n if not confirm(\"{} is already tapped!\\nContinue?\".format(card.name)): return \"BREAK\"\n if 'untapped' in inittag and card.orientation == Rot0:\n if not confirm(\"{} is already untapped!\\nContinue?\".format(card.name)): return \"BREAK\"\n if 'cost' in inittag:\n for costtag in inittag['cost']:\n (cost, type) = costtag.split(', ')\n if cost in scriptMarkers:\n marker = cost\n else:\n marker = 'cost'\n if type == \"ask\":\n if confirm(\"{}'s {}: Pay additional/alternate cost?\".format(card.name, cost)):\n markerdict[marker] = 1\n text += \", paying {} cost\".format(cost.title())\n elif type == \"num\":\n qty = askInteger(\"{}'s {}: Paying how many times?\".format(card.name, cost), 0)\n if qty == None: qty = 0\n if qty != 0: markerdict[marker] = qty\n text += \", paying {} {} times\".format(cost.title(), qty)\n else:\n qty = cardcount(card, card, type)\n if qty != 0: markerdict[marker] = qty\n if 'marker' in inittag:\n for markertag in inittag['marker']:\n (markername, qty) = markertag.split(', ')\n count = card.markers[counters[markername]]\n if count + cardcount(card, card, qty) < 0:\n if not confirm(\"Not enough {} counters to remove!\\nContinue?\".format(markername)): return \"BREAK\"\n####cast moves card to table####\n if tagclass == 'cast':\n card.moveToTable(0,0)\n card.markers[scriptMarkers['cast']] = 1\n for markers in markerdict:\n card.markers[scriptMarkers[markers]] += markerdict[markers]\n if card.Type != None and re.search(r'Land', card.Type):\n text += stackResolve(card, 'resolve')\n cardalign()\n return text\n####cost modifier####\n if 'cost' in markerdict:\n trigtype = \"cost{}\".format(tagclass)\n else:\n trigtype = tagclass\n####create the triggered copy####\n if trigtype == 'cycle' or getTags(card, trigtype) != '':\n stackcard = table.create(card.model, 0, 0, 1)\n if card.isAlternateImage == True:\n stackcard.switchImage\n if re.search(r'activate', tagclass):\n stackcard.markers[scriptMarkers['activate']] += int(tagclass[-1])\n else:\n stackcard.markers[scriptMarkers[tagclass]] += 1\n cstack[stackcard] = card\n for markers in markerdict:\n stackcard.markers[scriptMarkers[markers]] += markerdict[markers]\n else:\n stackcard = card\n####autoscripts####\n if 'life' in inittag:\n for tag in inittag['life']:\n text += autolife(card, stackcard, tag)\n if 'token' in inittag:\n for tag in inittag['token']:\n text += autotoken(card, stackcard, tag)\n if 'marker' in inittag:\n for tag in inittag['marker']:\n text += automarker(card, stackcard, tag)\n if 'smartmarker' in inittag:\n for tag in inittag['smartmarker']:\n text += autosmartmarker(card, tag)\n if 'highlight' in inittag:\n for tag in inittag['highlight']:\n text += autohighlight(card, tag)\n if 'tapped' in inittag:\n for tag in inittag['tapped']:\n text += autotapped(card, tag)\n if 'untapped' in inittag:\n for tag in inittag['untapped']:\n text += autountapped(card, tag)\n if 'transform' in inittag:\n for tag in inittag['transform']:\n text += autotransform(card, tag)\n if 'moveto' in inittag:\n for tag in inittag['moveto']:\n text += automoveto(card, tag)\n elif pile == \"table\":\n card.moveToTable(0,0)\n elif pile != '':\n cardowner = card.owner\n card.moveTo(cardowner.piles[pile])\n stackcard.sendToFront()\n cardalign()\n return text\n\ndef stackResolve(stackcard, type):\n mute()\n text = ''\n if stackcard in cstack:\n card = cstack[stackcard]\n else:\n card = stackcard\n cost = getTags(stackcard, 'cost{}'.format(type))\n if scriptMarkers['cost'] in stackcard.markers and cost != '':\n resolvetag = cost\n else:\n resolvetag = getTags(stackcard, type)\n if 'persist' in resolvetag:\n for tag in resolvetag['persist']:\n text += autopersist(card, stackcard, tag)\n if 'undying' in resolvetag:\n for tag in resolvetag['undying']:\n text += autoundying(card, stackcard, tag)\n if 'life' in resolvetag:\n for tag in resolvetag['life']:\n text += autolife(card, stackcard, tag)\n if 'token' in resolvetag:\n for tag in resolvetag['token']:\n text += autotoken(card, stackcard, tag)\n if 'marker' in resolvetag:\n for tag in resolvetag['marker']:\n text += automarker(card, stackcard, tag)\n if 'smartmarker' in resolvetag:\n for tag in resolvetag['smartmarker']:\n text += autosmartmarker(card, tag)\n if 'highlight' in resolvetag:\n for tag in resolvetag['highlight']:\n text += autohighlight(card, tag)\n if 'tapped' in resolvetag:\n for tag in resolvetag['tapped']:\n text += autotapped(card, tag)\n if 'untapped' in resolvetag:\n for tag in resolvetag['untapped']:\n text += autountapped(card, tag)\n if 'transform' in resolvetag:\n for tag in resolvetag['transform']:\n text += autotransform(card, tag)\n if 'moveto' in resolvetag:\n for tag in resolvetag['moveto']:\n text += automoveto(card, tag)\n if stackcard in cstack:\n del cstack[stackcard]\n if type == 'miracle':\n if card in me.hand:\n casttext = trigAbility(card, 'cast', 'table')\n text += \", casting{}\".format(casttext)\n else:\n text += \", countered\"\n if type == 'resolve' and stackcard.Type != None and not re.search(r'Instant', stackcard.Type) and not re.search(r'Sorcery', stackcard.Type):\n if scriptMarkers['cost'] in stackcard.markers and getTags(stackcard, 'costetb') != '':\n newcard = table.create(stackcard.model, 0, 0, 1)\n newcard.markers[scriptMarkers['etb']] += 1\n newcard.markers[scriptMarkers['cost']] += stackcard.markers[scriptMarkers['cost']]\n cstack[newcard] = stackcard\n elif not scriptMarkers['cost'] in stackcard.markers and getTags(stackcard, 'etb') != '':\n newcard = table.create(stackcard.model, 0, 0, 1)\n newcard.markers[scriptMarkers['etb']] += 1\n cstack[newcard] = stackcard\n for marker in scriptMarkers:\n stackcard.markers[scriptMarkers[marker]] = 0\n else:\n stackcard.moveTo(me.Graveyard)\n cardalign()\n return text\n\n############################\n#Modifiers\n############################\n\ndef attach(card, x = 0, y = 0):\n if autoscripts == True:\n stackAttach(card)\n else:\n whisper(\"Autoscripts must be enabled to use this feature\")\n\ndef stackAttach(card):\n mute()\n align = True\n while getGlobalVariable('cattach') == 'CHECKOUT':\n whisper(\"Global card attachment dictionary is currently in use, please wait.\")\n return CRASH\n cattach = eval(getGlobalVariable('cattach'))\n setGlobalVariable('cattach', 'CHECKOUT')\n target = (card for card in table if card.targetedBy)\n targetcount = sum(1 for card in table if card.targetedBy)\n if targetcount == 0:\n if card._id in dict([(v, k) for k, v in cattach.iteritems()]):\n card2 = [k for k, v in cattach.iteritems() if v == card._id]\n for card3 in card2:\n del cattach[card3]\n notify(\"{} unattaches {} from {}.\".format(me, Card(card3), card))\n elif card._id in cattach:\n card2 = cattach[card._id]\n del cattach[card._id]\n notify(\"{} unattaches {} from {}.\".format(me, card, Card(card2)))\n else:\n align = False\n elif targetcount == 1:\n for targetcard in target:\n if card == targetcard:\n del cattach[card._id]\n notify(\"{} unattaches {} from {}.\".format(me, card, targetcard))\n else:\n cattach[card._id] = targetcard._id\n targetcard.target(False)\n notify(\"{} attaches {} to {}.\".format(me, card, targetcard))\n else:\n whisper(\"Incorrect targets, select only 1 target.\")\n align = False\n setGlobalVariable('cattach', str(cattach))\n if align == True:\n cardalign()\n\ndef align(group, x = 0, y = 0):\n mute()\n if autoscripts == True:\n if cardalign() != \"BREAK\":\n notify(\"{} re-aligns his cards on the table\".format(me))\n\ndef cardalign():\n mute()\n global playerside\n global sideflip\n if sideflip == 0:\n return \"BREAK\"\n if Table.isTwoSided():\n if playerside == None:\n if me.hasInvertedTable():\n playerside = -1\n else:\n playerside = 1\n if sideflip == None:\n playersort = sorted(players, key=lambda player: player._id)\n playercount = [p for p in playersort if me.hasInvertedTable() == p.hasInvertedTable()]\n if len(playercount) > 2:\n whisper(\"Cannot align: Too many players on your side of the table.\")\n sideflip = 0\n return \"BREAK\"\n if playercount[0] == me:\n sideflip = 1\n else:\n sideflip = -1\n else:\n whisper(\"Cannot align: Two-sided table is required for card alignment.\")\n sideflip = 0\n return \"BREAK\"\n while getGlobalVariable('cattach') == 'CHECKOUT':\n whisper(\"Global card attachment dictionary is currently in use, please wait.\")\n return \"BREAK\"\n cattach = eval(getGlobalVariable('cattach'))\n setGlobalVariable('cattach', 'CHECKOUT') not in table\n group1 = [cardid for cardid in cattach if Card(cattach[cardid]) not in table]\n for cardid in group1:\n if Card(cardid).Subtype != None and re.search(r'Aura', Card(cardid).Subtype) and Card(cardid).controller == me:\n Card(cardid).moveTo(me.Graveyard)\n notify(\"{}'s {} was destroyed\".format(me, Card(cardid)))\n del cattach[cardid]\n group2 = [cardid for cardid in cattach if Card(cardid) not in table]\n for cardid in group2:\n del cattach[cardid]\n setGlobalVariable('cattach', str(cattach))\n stackcount = 0\n stackcards = (card for card in table\n if scriptMarkers['cast'] in card.markers\n or scriptMarkers['activate'] in card.markers\n or scriptMarkers['attack'] in card.markers\n or scriptMarkers['block'] in card.markers\n or scriptMarkers['destroy'] in card.markers\n or scriptMarkers['exile'] in card.markers\n or scriptMarkers['etb'] in card.markers\n or scriptMarkers['cost'] in card.markers\n or scriptMarkers['x'] in card.markers\n or scriptMarkers['cycle'] in card.markers\n or scriptMarkers['miracle'] in card.markers)\n for card in stackcards:\n if card.controller == me:\n card.moveToTable(0, 0 + 10 * stackcount)\n stackcount += 1\n cardorder = [ ]\n carddict = { }\n landorder = [ ]\n landdict = { }\n tablecards = [card for card in table\n if card.controller == me\n and not scriptMarkers['cast'] in card.markers\n and not scriptMarkers['activate'] in card.markers\n and not scriptMarkers['attack'] in card.markers\n and not scriptMarkers['block'] in card.markers\n and not scriptMarkers['destroy'] in card.markers\n and not scriptMarkers['exile'] in card.markers\n and not scriptMarkers['etb'] in card.markers\n and not scriptMarkers['cost'] in card.markers\n and not scriptMarkers['x'] in card.markers\n and not scriptMarkers['cycle'] in card.markers\n and not scriptMarkers['miracle'] in card.markers\n and not counters['general'] in card.markers\n and not card._id in cattach]\n cardsort = sorted(tablecards, key=lambda card:(sortlist(card), card.name))\n for card in cardsort:\n if re.search(r'Land', card.Type) or re.search(r'Planeswalker', card.Type) or re.search(r'Emblem', card.Type):\n vardict = landdict\n varorder = landorder\n yshift = 170\n else:\n vardict = carddict\n varorder = cardorder\n yshift = 45\n if len(card.markers) == 0 and not card._id in dict([(v, k) for k, v in cattach.iteritems()]):\n if not card.name in vardict or vardict[card.name] == 0:\n vardict[card.name] = 1\n varorder.append(card.name)\n xpos = len(varorder)\n ypos = 1\n elif vardict[card.name] >= 3:\n vardict[card.name] = 0\n xpos = varorder.index(card.name) + 1\n varorder[varorder.index(card.name)] = ['BLANK']\n ypos = 4\n else:\n vardict[card.name] += 1\n xpos = varorder.index(card.name) + 1\n ypos = vardict[card.name]\n else:\n varorder.append('BLANK')\n xpos = len(varorder)\n ypos = 4\n card.moveToTable(sideflip * xpos * 80, playerside * yshift - 44 + playerside * 9 * ypos)\n cattachcount = { }\n attachcardsgroup = [card for card in table\n if card.controller == me\n and not scriptMarkers['cast'] in card.markers\n and not scriptMarkers['activate'] in card.markers\n and not scriptMarkers['attack'] in card.markers\n and not scriptMarkers['block'] in card.markers\n and not scriptMarkers['destroy'] in card.markers\n and not scriptMarkers['exile'] in card.markers\n and not scriptMarkers['etb'] in card.markers\n and not scriptMarkers['cost'] in card.markers\n and not scriptMarkers['x'] in card.markers\n and not scriptMarkers['cycle'] in card.markers\n and not scriptMarkers['miracle'] in card.markers\n and not counters['general'] in card.markers\n and card._id in cattach]\n attachcards= sorted(attachcardsgroup, key=lambda card: card.name)\n for card in attachcards:\n origc = cattach[card._id]\n (x, y) = Card(origc).position\n if playerside*y < 0:\n yyy = -1\n else:\n yyy = 1\n if not Card(origc) in cattachcount:\n cattachcount[Card(origc)] = 1\n card.moveToTable(x, y - yyy*playerside*9)\n card.sendToBack()\n else:\n cattachcount[Card(origc)] += 1\n card.moveToTable(x, y - yyy*playerside*cattachcount[Card(origc)]*9)\n card.sendToBack()\n\ndef sortlist(card):\n if re.search(r\"Land\", card.Type): return \"A\"\n elif re.search(r\"Planeswalker\", card.Type): return \"B\"\n elif re.search(r\"Emblem\", card.Type): return \"C\"\n elif re.search(r\"Creature\", card.Type): return \"D\"\n elif re.search(r\"Artifact\", card.Type): return \"E\"\n elif re.search(r\"Enchantment\", card.Type): return \"F\"\n else: return \"G\"\n\ndef cardcount(card, stackcard, search):\n multiplier = 1\n if re.search(r'-', search):\n search = search.replace('-', '')\n multiplier = multiplier * (0 - 1)\n if re.search(r'\\*', search):\n intval = int(search[:search.find(\"*\")])\n search = search[search.find(\"*\")+1:]\n multiplier = multiplier * intval\n if search == \"x\":\n qty = stackcard.markers[scriptMarkers['x']]\n card.markers[scriptMarkers['x']] -= qty \n elif search == \"cost\":\n qty = stackcard.markers[scriptMarkers['cost']]\n card.markers[scriptMarkers['cost']] -= qty \n elif re.search(r'marker', search):\n marker = search[search.find(\"marker\")+7:]\n addmarker = counters[marker]\n qty = card.markers[addmarker]\n elif search == \"ask\":\n qty = askInteger(\"What is X?\", 0)\n if qty == None: qty = 0\n else:\n qty = int(search)\n return qty * multiplier\n\n############################\n#Autoscript\n############################\n\ndef autopersist(card, stackcard, persist):\n if card.group.name == \"Graveyard\":\n card.moveToTable(0,0)\n stackResolve(card, 'resolve')\n card.markers[counters['minusoneminusone']] += 1\n return \", persisting\"\n else:\n return \"\"\n\ndef autoundying(card, stackcard, undying):\n if card.group.name == \"Graveyard\":\n card.moveToTable(0,0)\n stackResolve(card, 'resolve')\n card.markers[counters['plusoneplusone']] += 1\n return \", undying\"\n else:\n return \"\"\n\ndef automoveto(card, pile):\n rnd(100,1000)\n cardowner = card.owner\n cards = card\n position = re.sub(\"[^0-9]\", \"\", pile)\n if position != \"\":\n pos = int(position)\n cards.moveTo(cardowner.Library, pos)\n text = \"{} from top of library\".format(pos)\n if re.search(r'top', pile):\n cards.moveTo(cardowner.Library)\n text = \"top of library\"\n elif re.search(r'bottom', pile):\n cards.moveToBottom(cardowner.Library)\n text = \"bottom of library\"\n elif re.search(r'shuffle', pile):\n librarycount = len(cardowner.Library)\n n = rnd(0, librarycount)\n cards.moveTo(cardowner.Library, n)\n cardowner.Library.shuffle()\n text = \"library and shuffled\"\n elif re.search(r'exile', pile):\n if trigAbility(card, 'exile', 'Exiled Zone') != \"BREAK\":\n text = \"exile\"\n elif re.search(r'hand', pile):\n cards.moveTo(cardowner.hand)\n text = \"hand\"\n elif re.search(r'graveyard', pile):\n if trigAbility(card, 'destroy', 'Graveyard') != \"BREAK\":\n text = \"graveyard\"\n elif re.search(r'stack', pile):\n if trigAbility(card, 'cast', 'table') != \"BREAK\":\n text = \"stack\"\n elif re.search(r'table', pile):\n card.moveToTable(0,0)\n stackResolve(card, 'resolve')\n text = \"table\"\n return \", moving to {}\".format(text)\n\ndef autolife(card, stackcard, tag):\n qty = cardcount(card, stackcard, tag)\n me.Life += qty\n if qty >= 0:\n return \", {} life\".format(qty)\n else:\n return \", {} life\".format(qty)\n\ndef autotransform(card, tag):\n if tag == \"no\": return \"\"\n if tag == \"ask\":\n if not confirm(\"Transform {}?\".format(card.name)): return \"\"\n card.switchImage\n return \", transforming to {}\".format(card)\n\ndef autotoken(card, stackcard, tag):\n tag2 = tag.split(', ')\n name = tag2[0]\n qty = tag2[1]\n if len(tag2) > 2:\n modifiers = tag2[2:]\n else:\n modifiers = \"\"\n quantity = cardcount(card, stackcard, qty)\n if quantity == 1:\n quant = \"\"\n else:\n quant = \"s\"\n if quantity != 0:\n addtoken = tokenTypes[name]\n tokens = table.create(addtoken[1], 0, 0, quantity, persist = False)\n if quantity == 1:\n tokens = [tokens]\n for token in tokens:\n for modtag in modifiers:\n if modtag == 'attack':\n token.highlight = AttackColor\n elif modtag == 'tap':\n token.orientation = Rot90\n elif re.search(r'marker', modtag):\n (marker, type, quant) = modtag.split('_')\n token.markers[counters[type]] += cardcount(token, stackcard, qty)\n tokentext = \"{} {}/{} {} {}\".format(quantity, token.Power, token.Toughness, token.Color, token.name)\n cardalign()\n return \", creating {} token{}\".format(tokentext, quant)\n else:\n return \"\"\n\ndef automarker(card, stackcard, tag):\n (markername, qty) = tag.split(', ')\n quantity = cardcount(card, stackcard, qty)\n originalquantity = quantity\n if quantity == 1:\n quant = \"\"\n else:\n quant = \"s\"\n addmarker = counters[markername]\n while markername == \"plusoneplusone\" and counters[\"minusoneminusone\"] in card.markers and quantity > 0:\n card.markers[counters[\"minusoneminusone\"]] -= 1\n quantity -= 1\n while markername == \"minusoneminusone\" and counters[\"plusoneplusone\"] in card.markers and quantity > 0:\n card.markers[counters[\"plusoneplusone\"]] -= 1\n quantity -= 1\n card.markers[addmarker] += quantity\n if originalquantity > 0:\n sign = \"+\"\n else:\n sign = \"\"\n return \", {}{} {}{}\".format(sign, originalquantity, addmarker[0], quant)\n\ndef autohighlight(card, color):\n if color == \"nountap\":\n if card.highlight == AttackColor:\n card.highlight = AttackDoesntUntapColor\n elif card.highlight == BlockColor:\n card.highlight = BlockDoesntUntapColor\n else:\n card.highlight = DoesntUntapColor\n text = \"does not untap\"\n elif color == \"attack\":\n if card.highlight == DoesntUntapColor:\n card.highlight = AttackDoesntUntapColor\n else:\n card.highlight = AttackColor\n text = \"attacking\"\n elif color == \"block\":\n if card.highlight == DoesntUntapColor:\n card.highlight = BlockDoesntUntapColor\n else:\n card.highlight = BlockColor\n text = \"blocking\"\n else:\n text = \"\"\n return \", {}\".format(text)\n\ndef autotapped(card, tapped):\n card.orientation = Rot90\n return \", tapped\"\n\ndef autountapped(card, untapped):\n card.orientation = Rot0\n return \", untapped\"\n\ndef autosmartmarker(card, marker):\n if marker in counters:\n setGlobalVariable(\"smartmarker\", marker)\n notify(\"{} sets the Smart Counter to {}.\".format(me, counters[marker][0]))\n return \"\"\n\n############################\n#Smart Token/Markers\n############################\n\ndef autoCreateToken(card, x = 0, y = 0):\n mute()\n text = \"\"\n tokens = getTags(card, 'autotoken')\n if tokens != \"\":\n for token in tokens:\n addtoken = tokenTypes[token]\n tokencard = table.create(addtoken[1], x, y, 1, persist = False)\n x, y = table.offset(x, y)\n text += \"{}/{} {} {}, \".format(tokencard.Power, tokencard.Toughness, tokencard.Color, tokencard.name)\n if autoscripts == True: cardalign()\n notify(\"{} creates {}.\".format(me, text[0:-2]))\n\ndef autoAddMarker(card, x = 0, y = 0):\n mute()\n text = \"\"\n markers = getTags(card, 'automarker')\n if markers != \"\":\n for marker in markers:\n addmarker = counters[marker]\n if marker == \"minusoneminusone\" and counters[\"plusoneplusone\"] in card.markers:\n card.markers[counters[\"plusoneplusone\"]] -= 1\n elif marker == \"plusoneplusone\" and counters[\"minusoneminusone\"] in card.markers:\n card.markers[counters[\"minusoneminusone\"]] -= 1\n else:\n card.markers[addmarker] += 1\n text += \"one {}, \".format(addmarker[0])\n notify(\"{} adds {} to {}.\".format(me, text[0:-2], card))\n\ndef smartMarker(card, x = 0, y = 0):\n mute()\n marker = getGlobalVariable(\"smartmarker\")\n if marker == \"\": \n whisper(\"No counters available\")\n return\n if marker == \"minusoneminusone\" and counters[\"plusoneplusone\"] in card.markers:\n card.markers[counters[\"plusoneplusone\"]] -= 1\n notify(\"{} adds one -1/-1 counter to {}.\".format(me, card))\n elif marker == \"plusoneplusone\" and counters[\"minusoneminusone\"] in card.markers:\n card.markers[counters[\"minusoneminusone\"]] -= 1\n notify(\"{} adds one -1/-1 counter to {}.\".format(me, card))\n else:\n addmarker = counters[marker]\n card.markers[addmarker] += 1\n notify(\"{} adds one {} to {}.\".format(me, addmarker[0], card))\n ","sub_path":"magic.o8g/scripts/autoscript.py","file_name":"autoscript.py","file_ext":"py","file_size_in_byte":29168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"256929256","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n\n\n\n# In[22]:\n\n\nimport numpy as np\nimport os\nimport random\nimport matplotlib.pyplot as plt\nimport pickle\nimport cv2\n\n\n# In[23]:\n\n\nDIRECTORY=r'C:\\Users\\Divyansh\\Desktop\\computer-vision'\nCATEGORIES=['freshoranges','rottenoranges']\n\n\n# In[24]:\n\n\nIMG_SIZE=100\n\ndata= []\n\nfor category in CATEGORIES:\n folder=os.path.join(DIRECTORY,category)\n label= CATEGORIES.index(category)\n for img in os.listdir(folder):\n img_path =os.path.join(folder,img)\n img_arr=cv2.imread(img_path)\n img_arr= cv2.resize(img_arr, (100,100)) \n data.append([img_arr,label])\n \n\n\n# In[ ]:\n\n\n\n\n\n# In[25]:\n\n\nrandom.shuffle(data)\n\n\n# In[26]:\n\n\nX=[]\ny=[]\nfor features,labels in data:\n X.append(features)\n y.append(labels)\n\n\n# In[27]:\n\n\nX =np.array(X)\ny=np.array(y)\n\n\n# In[ ]:\n\n\n\n\n\n# In[28]:\n\n\nX=X/255\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[11]:\n\n\nfrom keras.models import Sequential\nfrom keras.layers import *\nfrom tensorflow.keras.callbacks import TensorBoard\nimport time\n\n\n# In[30]:\n\n\nNAME=f'orange-pridiction-{int(time.time())}'\ntensorboard=TensorBoard(log_dir=r'C:\\Users\\Divyansh\\Desktop\\computer-vision')\n\nmodel = Sequential()\n\nmodel.add(Conv2D(64,(3,3),activation='relu'))\nmodel.add(MaxPooling2D(2,2))\n\nmodel.add(Conv2D(64,(3,3),activation='relu'))\nmodel.add(MaxPooling2D(2,2))\n\nmodel.add(Conv2D(64,(3,3),activation='relu'))\nmodel.add(MaxPooling2D(2,2))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(128,input_shape=X.shape[1:],activation='relu'))\n\nmodel.add(Dense(128,activation='relu'))\n\nmodel.add(Dense(2,activation='softmax'))\n\n\n# In[31]:\n\n\nmodel.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])\n\n\n# In[32]:\n\n\nmodel.fit(X,y,epochs=5,validation_split=0.2,callbacks=[tensorboard])\n\n\n# In[33]:\n\n\nmodel.evaluate(X,y)\n\n\n# In[ ]:\n\n\n\n\n\n# In[34]:\n\n\nX.shape\n\n\n# In[39]:\n\n\nDIRECTORY=r'C:\\Users\\Divyansh\\Desktop\\check'\nCATEGORIES=['freshoranges','rottenoranges']\nfolder=os.path.join(DIRECTORY,category)\ntesting=[]\nfor category in CATEGORIES:\n folder=os.path.join(DIRECTORY,category)\n label= CATEGORIES.index(category)\n for img in os.listdir(folder):\n img_path =os.path.join(folder,img)\n img_arr=cv2.imread(img_path)\n img_arr= cv2.resize(img_arr, (100,100)) \n testing.append([img_arr,label])\nX_test=[]\ny_test=[]\nfor features,labels in testing:\n X_test.append(features)\n y_test.append(labels)\n\n \n \n \nrandom.shuffle(testing)\n# In[44]:\n\n\nX_test =np.array(X_test)\ny_test=np.array(y_test)\n\nX_test=X_test/255\n\n# In[45]:\n\n\nX_test.shape\n\n\n# In[46]:\n\n\ny_test.shape\n\n\n# In[47]:\n\n\ny_pred = model.predict(X_test)\ny_pred[:5]\n\n\n# In[48]:\n\n\ny_classes = [np.argmax(element) for element in y_pred]\ny_classes[:5]\n\n\n# In[50]:\n\n\nplt.imshow(X_test[5])\nplt.xlabel([y_test[5]])\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"SERB_CitrusFruit_Classifier.py","file_name":"SERB_CitrusFruit_Classifier.py","file_ext":"py","file_size_in_byte":2806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"513481075","text":"numberLines = int(input())\n\nwhile 0 < numberLines:\n number = int(input())\n sum = 0\n for i in range(number):\n if i%3 == 0 or i%5 == 0:\n sum = sum + i\n print(sum)\n \n numberLines = numberLines - 1","sub_path":"PE1.py","file_name":"PE1.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"507153846","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import division, print_function\n\nimport numpy as np, pandas as pd\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport matplotlib.patheffects as pe\n\nfrom tessmaps.get_time_on_silicon import (\n given_cameras_get_stars_on_silicon as gcgss\n)\nfrom astropy import units as u, constants as const\nfrom astropy.coordinates import SkyCoord\n\nfrom numpy import array as nparr\n\nimport os\nimport json\n\ndef _shift_lon_get_x(lon, origin):\n x = np.array(np.remainder(lon+360-origin,360)) # shift lon values\n ind = x>180\n x[ind] -=360 # scale conversion to [-180, 180]\n x=-x # reverse the scale: East to the left\n return x\n\n\ndef plot_mwd(lon,dec,color_val,origin=0,size=3,title='Mollweide projection',\n projection='mollweide',savdir='../results/',savname='mwd_0.pdf',\n overplot_galactic_plane=True, is_tess=False, is_radec=None,\n cbarbounds=None, for_proposal=False, overplot_k2_fields=False,\n for_GRR=False, plot_tess=True, show_holes=False):\n\n '''\n args, kwargs:\n\n lon, lat are arrays of same length. they can be (RA,dec), or (ecliptic\n long, ecliptic lat). lon takes values in [0,360), lat in [-90,90],\n\n is_radec: mandatory. True if (RA,dec), else elong/elat.\n\n title is the title of the figure.\n\n projection is the kind of projection: 'mollweide', 'aitoff', ...\n\n show_holes: True to get inverse color scheme.\n\n comments: see\n http://balbuceosastropy.blogspot.com/2013/09/the-mollweide-projection.html.\n '''\n if is_radec == None:\n raise AssertionError\n\n # for matplotlib mollweide projection, x and y values (usually RA/dec, or\n # lat/lon) must be in -pi=27 lime green\n # \"#0a3a5c\", # N=14-20 dark blue\n # \"#0a3a5c\",\"#0a3a5c\",\"#0a3a5c\",\n # \"#0a3a5c\",\"#0a3a5c\",\"#0a3a5c\",\n # \"#07273d\", # N=21-26 saturated blue\n # \"#07273d\", \"#07273d\", \"#07273d\",\n # \"#07273d\", \"#07273d\", \"#07273d\",\n \"#000000\" # N>=13 black\n ]\n\n # 14 color\n elif len(cbarbounds) < 15:\n\n colors = [\"#ffffff\", \"#e7d914\", \"#ceb128\", \"#b58a3d\",\n \"#866c50\", \"#515263\", \"#1b3876\", \"#002680\",\n \"#001d80\", \"#001480\", \"#000c80\", \"#000880\",\n \"#000480\", \"#000080\"]\n\n # 28 color (kind of)\n elif len(cbarbounds) < 30:\n\n # first three orbits obsd get different colors. some difference\n # between 1yr and 2yr too.\n # take 1\n colors0 = [\"#ffffff\", \"#e7d914\", \"#ceb128\",\n \"#b58a3d\", \"#b58a3d\", \"#b58a3d\", \"#b58a3d\",\n \"#866c50\", \"#866c50\", \"#866c50\", \"#866c50\",\n \"#515263\", \"#515263\", \"#515263\", \"#515263\",\n \"#1b3876\", \"#1b3876\", \"#1b3876\", \"#1b3876\",\n \"#002680\", \"#002680\", \"#002680\", \"#002680\",\n \"#000c80\", \"#000880\", \"#000880\", \"#000880\",\n \"#000c80\"]\n\n colors1 = [\"#ffffff\", # N=0 white\n \"#e7d914\", # N=1 pale yellow\n \"#e7a013\", # N=2 a little more saturated\n \"#f7781d\", # N=3-5 a little more saturated\n \"#f7781d\", # N=6-11 saturated orange\n \"#f7781d\", \"#e86000\", \"#e86000\",\n \"#e86000\", \"#e86000\", \"#e86000\", \"#e86000\",\n \"#e80000\", \"#e80000\", # N=12,13 saturated red\n \"#12aee7\", # N=14-20 different blue\n \"#12aee7\",\"#12aee7\",\"#12aee7\",\n \"#12aee7\",\"#12aee7\",\"#12aee7\",\n \"#126ae7\", # N=21-26 saturated blue\n \"#126ae7\", \"#126ae7\", \"#126ae7\",\n \"#126ae7\", \"#126ae7\", \"#126ae7\"]\n\n colors2 = [\"#ffffff\", # N=0 white\n \"#84ccff\", # N=1 pale blue\n \"#35aaff\", # N=2 a little more saturated\n \"#279aea\", # N=3-5 a little more saturated\n \"#279aea\", # N=6-11 more saturated blue\n \"#279aea\", \"#1f77b4\", \"#1f77b4\",\n \"#1f77b4\", \"#1f77b4\", \"#1f77b4\", \"#1f77b4\",\n \"#126199\", \"#126199\", # N=12,13 saturated blue\n \"#ffa251\", # N=14-20 light orange\n \"#ffa251\",\"#ffa251\",\"#ffa251\",\n \"#ffa251\",\"#ffa251\",\"#ffa251\",\n \"#ff7f0e\", # N=21-26 saturated orange\n \"#ff7f0e\", \"#ff7f0e\", \"#ff7f0e\",\n \"#ff7f0e\", \"#ff7f0e\", \"#ff7f0e\"]\n\n colors = [\"#ffffff\", # N=0 white\n \"#84ccff\", # N=1 pale blue\n \"#35aaff\", # N=2 a little more saturated\n \"#279aea\", # N=3-5 a little more saturated\n \"#279aea\", # N=6-11 more saturated blue\n \"#279aea\", \"#1f77b4\", \"#1f77b4\",\n \"#1f77b4\", \"#1f77b4\", \"#1f77b4\", \"#1f77b4\",\n \"#126199\", \"#126199\", # N=12,13 saturated blue\n #\"#ffa251\", # N=14-20 light orange\n #\"#ffa251\",\"#ffa251\",\"#ffa251\",\n #\"#ffa251\",\"#ffa251\",\"#ffa251\",\n #\"#ff7f0e\", # N=21-26 saturated orange\n #\"#ff7f0e\", \"#ff7f0e\", \"#ff7f0e\",\n #\"#ff7f0e\", \"#ff7f0e\", \"#ff7f0e\",\n #\"#16E977\" # N>=27 lime green\n \"#0a3a5c\", # N=14-20 dark blue\n \"#0a3a5c\",\"#0a3a5c\",\"#0a3a5c\",\n \"#0a3a5c\",\"#0a3a5c\",\"#0a3a5c\",\n \"#07273d\", # N=21-26 saturated blue\n \"#07273d\", \"#07273d\", \"#07273d\",\n \"#07273d\", \"#07273d\", \"#07273d\",\n \"#000000\" # N>=27 black\n ]\n\n if show_holes:\n colors = [\"#000000\"] # N=0 black\n for i in range(28):\n colors.append(\"#ffffff\") # rest white\n\n from matplotlib.colors import (\n LinearSegmentedColormap, ListedColormap\n )\n\n #METHOD 1: custom cmap\n cmap = LinearSegmentedColormap.from_list(\n 'my_cmap', colors, N=len(colors)\n )\n\n # # METHOD 2 (pre-baked)\n # N = len(colors)\n # colormap = cm.get_cmap('Blues', N)\n # newcolors = colormap(np.linspace(0.15, 1, N))\n # white = np.array([0,0,0,0])\n # newcolors[:1, :] = white\n # cmap = ListedColormap(newcolors)\n\n\n if isinstance(cbarbounds,np.ndarray):\n bounds=cbarbounds\n else:\n bounds = np.arange(-27.32/2, np.max(df['obs_duration'])+1/2*27.32, 27.32)\n\n norm = mpl.colors.BoundaryNorm(bounds, cmap.N)\n\n # plot the stars\n cax = ax.scatter(np.radians(x[::100]),np.radians(dec[::100]),\n c=color_val[::100],\n s=0, lw=0, zorder=2, cmap=cmap, norm=norm,\n rasterized=True)\n\n if plot_tess:\n max_cv = np.max(color_val)\n for ix, cv in enumerate(np.sort(np.unique(color_val))):\n if cv == 0:\n continue\n sel = color_val == cv\n zorder = int(- max_cv - 1 + ix)\n _ = ax.scatter(np.radians(x[sel]),np.radians(dec[sel]),\n c=color_val[sel], s=size,\n lw=0, zorder=zorder, cmap=cmap, norm=norm,\n marker='o',\n rasterized=True)\n\n sel = color_val > 0\n _ = ax.scatter(np.radians(x[~sel]),np.radians(dec[~sel]),\n c=color_val[~sel],\n s=size/4, lw=0, zorder=-999, cmap=cmap, norm=norm,\n marker='s',\n rasterized=True)\n\n # #FIXME WORKS!\n # _ = ax.scatter(np.radians(x[sel]),np.radians(dec[sel]),\n # c=color_val[sel], s=size,\n # lw=0, zorder=-1, cmap=cmap, norm=norm,\n # marker='o',\n # rasterized=True)\n\n # _ = ax.scatter(np.radians(x[~sel]),np.radians(dec[~sel]),\n # c=color_val[~sel],\n # s=size/4, lw=0, zorder=0, cmap=cmap, norm=norm,\n # marker='s',\n # rasterized=True)\n # #FIXME WORKS!\n\n # set up colorbar\n if len(colors) < 8:\n #cbarbounds = [-0.5, 0.5, 1.5, 2.5, 12.5, 39.5 ]\n ticks = [0, 1, 2, (2.5+12.5)/2, (12.5+39.5)/2]\n ylabels = ['0', '1', '2', '3-12', '$\\geq \\! 13$']\n\n elif len(colors) < 15:\n ticks = 27.32*(np.arange(-1,13)+1)\n ylabels = list(map(str,np.round(27.32*(np.arange(0,13)),1)))\n ylabels[-1] = '$\\geq \\! 328$'\n elif len(colors) < 30:\n #ticks = 27.32*(np.arange(-1,26)+1) #FIXME\n #ylabels = list(map(str,np.round(27.32*(np.arange(0,27)),1)))\n #ylabels[-1] = '$\\geq \\! 710$'\n\n # NOTE: default\n ticks = (np.arange(-1,26)+1)\n ylabels = list(map(str,np.round((np.arange(0,27)),1)))\n\n ticks = (np.arange(-1,27)+1)\n ticks[-1] = (26.5 + 39.5) / 2\n ylabels = list(map(str,np.round((np.arange(0,28)),1)))\n ylabels[-1] = '$\\geq \\! 27$'\n\n\n cbar = fig.colorbar(cax, cmap=cmap, norm=norm, boundaries=bounds,\n fraction=0.025, pad=0.03,\n ticks=ticks,\n orientation='vertical')\n\n cbar.ax.set_yticklabels(ylabels, fontsize='xx-small')\n cbar.set_label('Lunar months observed', rotation=270, labelpad=10,\n fontsize='x-small')\n cbar.ax.tick_params(direction='in')\n\n else:\n ax.scatter(np.radians(x),np.radians(dec), c=color_val, s=size,\n zorder=2)\n\n\n if overplot_galactic_plane:\n\n ##########\n # make many points, and also label the galactic center. ideally you\n # will never need to follow these coordinate transformations.\n glons = np.arange(0,360,0.2)\n glats = np.zeros_like(glons)\n coords = SkyCoord(glons*u.degree, glats*u.degree, frame='galactic')\n gplane_ra, gplane_dec = coords.icrs.ra.value, coords.icrs.dec.value\n gplane_elon = coords.barycentrictrueecliptic.lon.value\n gplane_elat = coords.barycentrictrueecliptic.lat.value\n if is_radec:\n gplane_x = _shift_lon_get_x(gplane_ra, origin)\n else:\n gplane_x = _shift_lon_get_x(gplane_elon, origin)\n gplane_dec = gplane_elat\n _x, _y = np.radians(gplane_x),np.radians(gplane_dec)\n s = np.argsort(_x)\n ax.plot(_x[s], _y[s], c='lightgray', lw=0.5, zorder=3, ls='--',\n alpha=0.7, rasterized=True)\n gcenter = SkyCoord('17h45m40.04s', '-29d00m28.1s', frame='icrs')\n gcenter_ra, gcenter_dec = gcenter.icrs.ra.value, gcenter.icrs.dec.value\n gcenter_elon = gcenter.barycentrictrueecliptic.lon.value\n gcenter_elat = gcenter.barycentrictrueecliptic.lat.value\n if is_radec:\n gcenter_x = _shift_lon_get_x(np.array(gcenter_ra), origin)\n else:\n gcenter_x = _shift_lon_get_x(np.array(gcenter_elon), origin)\n gcenter_dec = gcenter_elat\n\n ax.scatter(np.radians(gcenter_x),np.radians(gcenter_dec),\n c='black', s=5, zorder=7, marker='x', linewidth=0.5)\n ax.scatter(np.radians(gcenter_x),np.radians(gcenter_dec),\n c='white', s=7, zorder=6, marker='x', linewidth=0.7)\n\n ax.text(np.radians(gcenter_x), np.radians(gcenter_dec-3), 'GC',\n fontsize='xx-small', ha='left', va='top',\n path_effects=[pe.withStroke(linewidth=0.4, foreground=\"white\")])\n ##########\n\n if overplot_k2_fields:\n\n # do kepler\n kep = pd.read_csv('../data/kepler_field_footprint.csv')\n # we want the corner points, not the mid-points\n is_mipoint = ((kep['row']==535) & (kep['column']==550))\n kep = kep[~is_mipoint]\n\n kep_coord = SkyCoord(np.array(kep['ra'])*u.deg,\n np.array(kep['dec'])*u.deg, frame='icrs')\n kep_elon = kep_coord.barycentrictrueecliptic.lon.value\n kep_elat = kep_coord.barycentrictrueecliptic.lat.value\n kep['elon'] = kep_elon\n kep['elat'] = kep_elat\n\n kep_d = {}\n for module in np.unique(kep['module']):\n kep_d[module] = {}\n for output in np.unique(kep['output']):\n kep_d[module][output] = {}\n sel = (kep['module']==module) & (kep['output']==output)\n\n _ra = list(kep.loc[sel, 'ra'])\n _dec = list(kep.loc[sel, 'dec'])\n _elon = list(kep.loc[sel, 'elon'])\n _elat = list(kep.loc[sel, 'elat'])\n\n _ra = [_ra[0], _ra[1], _ra[3], _ra[2] ]\n _dec = [_dec[0], _dec[1], _dec[3], _dec[2] ]\n _elon = [_elon[0], _elon[1], _elon[3], _elon[2] ]\n _elat = [_elat[0], _elat[1], _elat[3], _elat[2] ]\n\n _ra.append(_ra[0])\n _dec.append(_dec[0])\n _elon.append(_elon[0])\n _elat.append(_elat[0])\n\n kep_d[module][output]['corners_ra'] = _ra\n kep_d[module][output]['corners_dec'] = _dec\n kep_d[module][output]['corners_elon'] = _elon\n kep_d[module][output]['corners_elat'] = _elat\n\n # finally, make the plot!\n for mod in np.sort(list(kep_d.keys())):\n for op in np.sort(list(kep_d[mod].keys())):\n print(mod, op)\n\n this = kep_d[mod][op]\n\n ra = nparr(this['corners_ra'])\n dec = nparr(this['corners_dec'])\n elon = nparr(this['corners_elon'])\n elat = nparr(this['corners_elat'])\n\n if is_radec:\n ch_x = _shift_lon_get_x(np.array(ra), origin)\n ch_y = np.array(dec)\n else:\n ch_x = _shift_lon_get_x(np.array(elon), origin)\n ch_y = np.array(elat)\n\n # draw the outline of the fields -- same as fill.\n #ax.plot(np.radians(ch_x), np.radians(ch_y), c='gray',\n # alpha=0.3, lw=0.15, rasterized=True)\n\n # fill in the fields\n ax.fill(np.radians(ch_x), np.radians(ch_y), c='lightgray',\n alpha=0.95, lw=0, rasterized=True)\n\n # label them (NOTE: skipping)\n # txt_x, txt_y = np.mean(ch_x), np.mean(ch_y)\n # if mod == 13 and output == 2:\n # ax.text(np.radians(txt_x), np.radians(txt_y),\n # 'Kepler', fontsize=4, va='center',\n # ha='center', color='gray', zorder=10)\n\n # done kepler!\n # do k2\n footprint_dictionary = json.load(open(\"../data/k2-footprint.json\"))\n\n for cn in np.sort(list(footprint_dictionary.keys())):\n if cn in ['c1','c10'] and is_radec:\n continue\n if cn in ['c1','c10'] and not is_radec:\n continue\n print(cn)\n\n channel_ids = footprint_dictionary[cn][\"channels\"].keys()\n\n for channel_id in channel_ids:\n channel = footprint_dictionary[cn][\"channels\"][channel_id]\n ra = channel[\"corners_ra\"] + channel[\"corners_ra\"][:1]\n dec = channel[\"corners_dec\"] + channel[\"corners_dec\"][:1]\n\n if is_radec:\n ch_x = _shift_lon_get_x(np.array(ra), origin)\n ch_y = np.array(dec)\n else:\n ch_coord = SkyCoord(ra*u.deg, dec*u.deg, frame='icrs')\n ch_elon = ch_coord.barycentrictrueecliptic.lon.value\n ch_elat = ch_coord.barycentrictrueecliptic.lat.value\n ch_x = _shift_lon_get_x(np.array(ch_elon), origin)\n ch_y = np.array(ch_elat)\n\n # draw the outline of the fields -- same as fill\n # ax.plot(np.radians(ch_x), np.radians(ch_y), c='gray',\n # alpha=0.3, lw=0.15, rasterized=True)\n\n # fill in the fields\n ax.fill(np.radians(ch_x), np.radians(ch_y), c='lightgray',\n alpha=.95, lw=0, rasterized=True)\n\n # label them (NOTE: skipping)\n # txt_x, txt_y = np.mean(ch_x), np.mean(ch_y)\n # if channel_id == '41':\n # ax.text(np.radians(txt_x), np.radians(txt_y),\n # cn.lstrip('c'), fontsize=4, va='center',\n # ha='center', color='gray')\n\n # done k2!\n\n\n\n if is_radec:\n xticks = np.array([120, 60, 0, 300, 240])\n xticks = _shift_lon_get_x(xticks, origin)\n ax.set_xticks(np.radians(xticks))\n xticklabels = [\n '8$^\\mathrm{h}$', '4$^\\mathrm{h}$', '0$^\\mathrm{h}$',\n '20$^\\mathrm{h}$', '16$^\\mathrm{h}$'\n ]\n else:\n xticks = np.array([120, 60, 0, 300, 240])\n xticks = _shift_lon_get_x(xticks, origin)\n ax.set_xticks(np.radians(xticks))\n xticklabels = np.array(\n [str(xtl)+'$\\!$$^\\circ$' for xtl in np.array([120, 60, 0, 300, 240])]\n )\n ax.set_xticklabels(\n xticklabels, fontsize='xx-small', zorder=5,\n path_effects=[pe.withStroke(linewidth=0.4, foreground=\"white\")]\n )\n\n yticks = np.arange(-60,60+30,30)\n ax.set_yticks(np.radians(yticks))\n yticklabels = np.array([str(ytl)+'$\\!$$^\\circ$' for ytl in yticks])\n ax.set_yticklabels(yticklabels, fontsize='xx-small')\n\n if not for_proposal:\n ax.set_title(title, y=1.05, fontsize='small')\n\n if is_radec:\n ax.set_xlabel('Right ascension', fontsize='x-small')\n ax.set_ylabel('Declination', fontsize='x-small')\n else:\n ax.set_xlabel('Ecliptic longitude', fontsize='x-small')\n ax.set_ylabel('Ecliptic latitude', fontsize='x-small')\n\n #ax.set_axisbelow(True)\n ax.grid(color='lightgray', linestyle='--', linewidth=0.5, zorder=-3,\n alpha=0.15)\n\n if not for_proposal and not for_GRR:\n ax.text(0.99,0.01,'github.com/lgbouma/extend_tess',\n fontsize='4',transform=ax.transAxes,\n ha='right',va='bottom')\n\n fig.tight_layout()\n fig.savefig(os.path.join(savdir,savname),dpi=600, bbox_inches='tight')\n print('saved {}'.format(os.path.join(savdir,savname)))\n\n\n\ndef get_n_observations(sector_interval, dirnfile, outpath, n_stars, merged=False,\n withgaps=True, aligncelestial=False):\n\n np.random.seed(42)\n\n # pick points uniformly on celestial sphere. they don't strictly need to be\n # random. takes >~1 minute to draw random numbers after ~2*10^5. faster to\n # just do it on an appropriate grid.\n\n # e.g., http://mathworld.wolfram.com/SpherePointPicking.html\n # uniform0 = np.linspace(0,1,n_stars)\n # uniform1 = np.linspace(0,1,n_stars)\n rand0 = np.random.uniform(low=0,high=1,size=n_stars)\n rand1 = np.random.uniform(low=0,high=1,size=n_stars)\n\n theta = (2*np.pi*rand0 * u.rad).to(u.deg).value\n phi = (np.arccos(2*rand1 - 1) * u.rad).to(u.deg).value - 90\n\n ras = theta*u.deg\n decs = phi*u.deg\n\n coords = SkyCoord(ra=ras, dec=decs, frame='icrs')\n\n rdf = pd.read_csv(dirnfile, sep=',')\n sel = (rdf.S >= sector_interval[0]) & (rdf.S <= sector_interval[1])\n df = rdf[sel]\n\n lats = nparr([\n nparr(df['cam1_elat']),\n nparr(df['cam2_elat']),\n nparr(df['cam3_elat']),\n nparr(df['cam4_elat'])]).T\n lons = nparr([\n nparr(df['cam1_elon']),\n nparr(df['cam2_elon']),\n nparr(df['cam3_elon']),\n nparr(df['cam4_elon'])]).T\n\n cam_directions = []\n for lat, lon in zip(lats, lons):\n\n c1lat,c2lat,c3lat,c4lat = lat[0],lat[1],lat[2],lat[3]\n c1lon,c2lon,c3lon,c4lon = lon[0],lon[1],lon[2],lon[3]\n\n this_cam_dirn = [(c1lat, c1lon),\n (c2lat, c2lon),\n (c3lat, c3lon),\n (c4lat, c4lon)]\n\n cam_directions.append(this_cam_dirn)\n\n df['camdirection'] = cam_directions\n\n n_observations = np.zeros_like(coords)\n\n for ix, row in df.iterrows():\n\n print(row['Start(UTC)'])\n cam_direction = row['camdirection']\n\n onchip = gcgss(coords, cam_direction, verbose=False, withgaps=withgaps,\n aligncelestial=aligncelestial)\n\n n_observations += onchip\n\n outdf = pd.DataFrame({'ra':coords.ra.value,\n 'dec':coords.dec.value,\n 'elat':coords.barycentrictrueecliptic.lat.value,\n 'elon':coords.barycentrictrueecliptic.lon.value,\n 'n_observations': n_observations })\n outdf[['ra','dec','elon','elat','n_observations']].to_csv(\n outpath, index=False, sep=';')\n print('saved {}'.format(outpath))\n\n\ndef make_pointing_map(\n sector_interval, NAME_STRING, for_proposal=False, overplot_k2_fields=False,\n plot_tess=True, show_holes=False\n):\n\n datadir = '../data/'\n savdir = '../results/visualize_survey_designs/EM2_SENIOR_REVIEW'\n orbit_duration_days = 1 #27.32 / 2\n\n filename = f'{NAME_STRING}.csv'\n sectorstr = f'S{sector_interval[0]}_S{sector_interval[1]}'\n eclsavname = f'{NAME_STRING}_{sectorstr}.png'\n icrssavname = f'{NAME_STRING}_{sectorstr}_icrs.png'\n title = ''\n dirnfile = os.path.join(datadir, filename)\n\n size=0.8\n\n if for_proposal:\n eclsavname = eclsavname.replace('.png','.png')\n icrssavname = icrssavname.replace('.png','.png')\n size=0.35 # better than 0.5 with 48e5 points (also better than 0.25)\n\n if overplot_k2_fields:\n eclsavname = eclsavname.replace('.png','_k2.png')\n icrssavname = icrssavname.replace('.png','_k2.png')\n\n if not plot_tess:\n eclsavname = eclsavname.replace('.png','_notess.png')\n icrssavname = icrssavname.replace('.png','_notess.png')\n\n if show_holes:\n eclsavname = eclsavname.replace('.png','_showholes.png')\n icrssavname = icrssavname.replace('.png','_showholes.png')\n\n obsdstr = '' if not for_proposal else '_forproposal'\n obsdpath = dirnfile.replace(\n '.csv', f'_coords_observed{obsdstr}_{sectorstr}.csv'\n )\n\n if not os.path.exists(obsdpath):\n # takes about 1 minute per strategy\n if for_proposal:\n npts = 48e5 # 12e5 default...\n else:\n npts = 1e4\n\n get_n_observations(sector_interval, dirnfile, obsdpath, int(npts))\n\n df = pd.read_csv(obsdpath, sep=';')\n df['obs_duration'] = orbit_duration_days*df['n_observations']\n\n # # NOTE: default\n # cbarbounds = np.arange(-1/2, 27, 1)\n # # NOTE: new\n if show_holes:\n cbarbounds = list(np.arange(-1/2, 27, 1))\n cbarbounds.append(39.5)\n else:\n cbarbounds = [-0.5, 0.5, 1.5, 2.5, 12.5, 39.5 ]\n cbarbounds = np.array(cbarbounds)\n\n sel_durn = (nparr(df['obs_duration']) >= 0)\n\n for lonkey, latkey, savname, is_radec in zip(\n ['elon', 'ra'], ['elat', 'dec'], [eclsavname, icrssavname], [False, True]\n ):\n plot_mwd(nparr(df[lonkey])[sel_durn],\n nparr(df[latkey])[sel_durn],\n nparr(df['obs_duration'])[sel_durn],\n origin=0, size=size, title=title,\n projection='mollweide', savdir=savdir,\n savname=savname,\n overplot_galactic_plane=True, is_tess=True, is_radec=is_radec,\n cbarbounds=cbarbounds,\n for_proposal=for_proposal,\n overplot_k2_fields=overplot_k2_fields,\n plot_tess=plot_tess, show_holes=show_holes)\n\n\nif __name__==\"__main__\":\n\n # BEGIN OPTIONS\n for_proposal=1 # false to debug\n overplot_k2_fields=1 # true to activate k2 field overplot\n plot_tess=1 # true to activate tess field overplot\n for_GRR=0 # if true, make GRR's NCP-pointing idea.\n # intervals of plots you want to make\n sector_intervals = [ # all relevant for EM2+2year\n (1,26), (27,56), (57,97), (1,56), (98, 123), (1,97), (1,123), #(27,47)\n ]\n # sector_intervals = [ # cumulative EM2+2year\n # (1,97), (1,123)\n # ]\n # END OPTIONS\n\n # NOTE: this will be updated. em2_v00.csv for instance, is made by\n # src.convert_vanderspek_to_bouma_format.py\n name_strings = [\n #'em2_v01', 'em2_v02', 'em2_v03', 'em2_v04', 'em2_v05', 'em2_v06'\n #'em2_v07r'\n #'em2_v09'\n #'em2_v09c'\n #'em2_v11a', 'em2_v09l',\n 'em2_v09n'\n ]\n\n for sector_interval in sector_intervals:\n for n in name_strings:\n make_pointing_map(\n sector_interval,\n n,\n for_proposal=for_proposal,\n overplot_k2_fields=overplot_k2_fields,\n plot_tess=plot_tess,\n show_holes=False\n )\n\n for sector_interval in [\n (1,97),\n (1,123)\n ]:\n for n in name_strings:\n make_pointing_map(\n sector_interval,\n n,\n for_proposal=for_proposal,\n overplot_k2_fields=overplot_k2_fields,\n plot_tess=plot_tess,\n show_holes=True\n )\n\n","sub_path":"src/visualize_survey_designs.py","file_name":"visualize_survey_designs.py","file_ext":"py","file_size_in_byte":27790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"211460911","text":"from utils import *\nimport time\nimport json\ndef conversion():\n\tyearly_result = {}\n\n\twith open(\"json_result/output.json\", \"r\") as fp:\n\t\tdic = json.loads(fp.read())\n\t\tfor (name, item) in dic.items():\n\t\t\tcontents = item[\"contents\"]\n\t\t\tyearly_result[name] = {}\n\t\t\tfor (year_str, conf_list) in contents.items():\n\t\t\t\tprint (year_str)\n\t\t\t\tyear = parse_year(year_str)\n\t\t\t\tyearly_result[name][year] = conf_list\n\n\twith open(\"json_result/conference_yearly.json\", \"w\") as fp:\n\t\tfp.write(json.dumps(yearly_result))\n\n\ndef parse_year(year_str):\n\timport re\n\tmatch = re.search(r'[12][0-9]{3}', year_str)\n\tif match is None:\n\t\treturn \"-1000\"\n\n\treturn match.group(0)\n\ndef generate_file_name(conf, year, hash_value):\n\n\treturn year + \"_\" + conf + \"_\" + hash_value\n\ndef scrape_by_conf(conf):\n\tdriver = initial()\n\twith open(\"json_result/conference_yearly.json\", \"r\") as fp:\n\t\tdic = json.loads(fp.read())\n\t\tfor (year, lis) in dic[conf].items():\n\t\t\tfor url in lis:\n\t\t\t\tdownload(driver, url, \"./search_result/\" + generate_file_name(conf, year, str(hash(url))))\n\t\t\t\ttime.sleep(4)\n\t\t\t\tprint (\"sleep......\")\nif __name__ == '__main__':\n\t## conversion()\n\tscrape_by_conf(\"LHD @ IJCAI - Discovering Meaning On the Go in Large Heterogeneous Data\")\n\n\n\n\n\t","sub_path":"pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"13207292","text":"# -*- coding: utf-8 -*-\nimport fuse\nfrom simple import *\nfrom fuse import Fuse\n\n\n# Set fuse.fuse_python_api to make it easy for the fuse module to find out #\n# the which FUSE-Python API revision is appropriate for your code. #\nfuse.fuse_python_api = (0, 2)\n\n# Flags for fuse, for more info; python fusewrapper.py --help\nFLAGS = ['-f', '-o', 'use_ino', '-o', 'attr_timeout=0', '-o', 'allow_other']\n\n# Main\nif __name__ == '__main__':\n # Set flags for fuse.\n sys.argv = sys.argv + FLAGS\n # Instance of the filesystem.\n fs = Simple()\n # Open the log.\n fs.open_log()\n # Parse command line, fill 'fuse_args' attribute.\n fs.parse(errex=1)\n # Start filesystem\n fs.main()\n\n","sub_path":"fusewrapper.py","file_name":"fusewrapper.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"33235782","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 17 07:46:39 2020\n\n@author: cvicentm\n\"\"\"\nfrom sklearn.decomposition import LatentDirichletAllocation\n#import pyLDAvis.sklearn\nimport pickle\nfrom create_corpus import create_corpus\nimport timeit\nimport datetime\n\n\n\nN_TOPICS = 40\nn_documents = 200\nfile_lda_model = 'pickle\\lda_model_'+str(N_TOPICS)+'_'+str(n_documents)+'.sav'\n\ntry:\n \n f=open(file_lda_model, 'rb')\n lda = pickle.load(f)\n print(\"El modelo ya había sido entrenado previamente...\")\n generator_normalize = pickle.load(open(\"pickle\\generator_normalize.txt\", \"rb\"))\n Bow_matrix = pickle.load(open(\"pickle\\Bow_matrix.txt\", \"rb\"))\n vectorizer = pickle.load(open(\"pickle\\Vectorizer.txt\", \"rb\"))\n print(\"Se ha conseguido importar las variables: generator_normalize, Bow_matrix y vectorizer\")\n \nexcept IOError:\n \n try:\n print(\"HA ENTRADO EN EL SEGUNDO TRY\")\n f=open(file_lda_model, 'rb')\n lda = pickle.load(f)\n print(\"Se debe volver a crear el corpus\")\n [generator_normalize, Bow_matrix, vectorizer, vectorizer_first]=create_corpus(n_documents)\n \n except IOError:\n \n print(\"AL FINAL HAY QUE HACERLO TODO\")\n print(\"El modelo se debe entrenar ...\")\n print(\"Creando el corpus\")\n [generator_normalize, Bow_matrix, vectorizer, vectorizer_first]=create_corpus(n_documents)\n print(\"Proceso de creación del corpus finalizado\")\n tic_all_processing=timeit.default_timer()\n lda = LatentDirichletAllocation(n_components=N_TOPICS,max_iter=500,learning_method='batch',batch_size=50)\n print(\"Se comienza a entrenar el corpus\")\n lda.fit(Bow_matrix)\n toc_all_processing=timeit.default_timer()\n time_lda_fit=str(datetime.timedelta(seconds=int(float(toc_all_processing-tic_all_processing))))\n print(\"The process of training lda model with \"+str(N_TOPICS)+\" topics has taken \"+time_lda_fit+\" seconds\") \n print(\"Finalización del entrenamiento del corpus completada\")\n topics_per_document=lda.components_\n \n print(\"se va a proceder a guardar el modelo en un fichero\")\n # if the number of subtitles doest change, we can use the same model than the last time\n pickle.dump(lda, open(file_lda_model, 'wb'))\n \n\n\"\"\"\"\nprint(\"estamos con el tema de imprimir las gráficas\")\npyLDAvis.enable_notebook()\npanel = pyLDAvis.sklearn.prepare(lda, Bow_matrix, vectorizer, mds='tsne')\npyLDAvis.display(panel)\n\"\"\"\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndic_preprocesing_subtitles = pickle.load(open(\"pickle\\dict_preprocesing_subtitles.txt\", \"rb\"))\nnews_list = list(dic_preprocesing_subtitles)\n\nfor i in range(400):\n new_name=news_list[i]\n topic_distribution = lda.transform(Bow_matrix[i])\n numpy_distribution=np.asarray(topic_distribution)\n numpy_distribution=np.resize(numpy_distribution,(n_topics,))\n fig, ax = plt.subplots() # Declares a figure handle\n ax.plot(np.arange(0,n_topics,1),numpy_distribution,'-*',label=new_name)\n ax.legend()\n\"\"\"\n","sub_path":"modules/lda/unsupervised_learning_sklearn.py","file_name":"unsupervised_learning_sklearn.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"543185640","text":"# Exercise : Function and Objects Exercise-2\n# Implement a function that converts the given testList = [1, -4, 8, -9] into [2, -3, 9, -8]\n\n\ndef apply_to_each(L, add):\n list_1 = []\n for x_iter in L:\n list_1.append(add(x_iter))\n print(list_1)\n\n\ndef add(x):\n return x + 1\n\n\ndef main():\n data = input()\n data = data.split()\n list1 = []\n for j in data:\n list1.append(int(j))\n apply_to_each(list1, add)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"cspp1-practice/m9/functions_and_objects_2.py","file_name":"functions_and_objects_2.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"85652261","text":"\"\"\"\nMIT License\n\nCopyright (c) 2019 TUMCREATE \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\nfrom __future__ import division\n\nimport csv\nimport os\n\nimport numpy as np\nimport pandas as pd\nimport xlrd\nfrom geopandas import GeoDataFrame as Gdf\nfrom cea.utilities.dbf import dbf_to_dataframe\n\n__author__ = \"Sebastian Troitzsch\"\n__copyright__ = \"Copyright 2019, Architecture and Building Systems - ETH Zurich\"\n__credits__ = [\"Sebastian Troitzsch\", \"Sreepathi Bhargava Krishna\"]\n__license__ = \"MIT\"\n__version__ = \"0.1\"\n__maintainer__ = \"Daren Thomas\"\n__email__ = \"thomas@arch.ethz.ch\"\n__status__ = \"Production\"\n\n\ndef main(locator, weather_path,\n time_start,\n time_end\n ):\n (\n internal_loads_df,\n indoor_comfort_df,\n construction_envelope_systems_df,\n leakage_envelope_systems_df,\n window_envelope_systems_df,\n roofs_envelope_systems_df,\n wall_envelope_systems_df,\n shading_envelope_systems_df,\n emission_systems_heating_df,\n emission_systems_cooling_df,\n emission_systems_controller_df,\n system_controls_ini_df,\n cooling_generation_df\n ) = extract_cea_databases_files(locator)\n (\n zone_occupancy_df,\n zone_df,\n architecture_df,\n technical_systems_df,\n supply_systems_df\n ) = extract_cea_inputs_files(locator)\n (\n weather_general_info,\n weather_timeseries_initial_df\n ) = process_weather_file(weather_path)\n (\n occupancy_types_full,\n occupancy_types,\n buildings_names\n ) = extract_common_parameters(\n internal_loads_df,\n zone_occupancy_df\n )\n building_geometry_all = extract_cea_building_geometry(locator,\n buildings_names\n )\n\n (\n occupancy_types_full_cardinal,\n buildings_cardinal,\n occupancy_types_cardinal\n ) = calculate_cardinals(\n internal_loads_df,\n zone_occupancy_df,\n occupancy_types\n )\n # restructure all the files into pandas dataframe format\n (\n occupants_probability_dic,\n lighting_appliances_probability_dic,\n processes_probability_dic,\n monthly_use_probability_df,\n occupancy_density_m2_p\n ) = process_occupancy_schedules(locator,\n occupancy_types,\n occupancy_types_cardinal\n )\n footprint = calculate_footprint(\n buildings_names,\n building_geometry_all\n )\n (\n gross_floor_area_m2,\n floors_cardinal_df,\n total_gross_floor_area_m2\n ) = calculate_gross_floor_area(\n footprint,\n zone_df,\n buildings_names\n )\n mean_floor_height_m = calculate_mean_floor_height(\n buildings_names,\n zone_df,\n floors_cardinal_df\n )\n # get cooling/heating seasons\n system_controls_df = process_system_controls_file(system_controls_ini_df)\n # get building cooling systems\n (\n supply_temperature_df,\n emissions_cooling_type_dic,\n emissions_controller_type_dic,\n generation_cooling_code_dic\n ) = synthetize_hvac_properties(\n buildings_names,\n buildings_cardinal,\n technical_systems_df,\n emission_systems_cooling_df,\n supply_systems_df\n )\n (\n occupancy_per_building_cardinal,\n occupancy_per_building_list\n ) = get_occupancy_per_building(\n buildings_names,\n occupancy_types,\n zone_occupancy_df\n )\n\n # get the internal/external temperature within the time-steps\n (\n T_int_cea_dic,\n T_ext_cea_df\n ) = get_temperatures(locator,\n buildings_names,\n time_start,\n time_end\n )\n\n return (\n internal_loads_df,\n indoor_comfort_df,\n construction_envelope_systems_df,\n leakage_envelope_systems_df,\n window_envelope_systems_df,\n roofs_envelope_systems_df,\n wall_envelope_systems_df,\n shading_envelope_systems_df,\n emission_systems_heating_df,\n emission_systems_cooling_df,\n emission_systems_controller_df,\n system_controls_ini_df,\n cooling_generation_df,\n zone_occupancy_df,\n zone_df,\n architecture_df,\n technical_systems_df,\n supply_systems_df,\n weather_general_info,\n weather_timeseries_initial_df,\n occupancy_types_full,\n occupancy_types,\n buildings_names,\n building_geometry_all,\n occupancy_types_full_cardinal,\n buildings_cardinal,\n occupancy_types_cardinal,\n occupants_probability_dic,\n lighting_appliances_probability_dic,\n processes_probability_dic,\n monthly_use_probability_df,\n occupancy_density_m2_p,\n footprint,\n gross_floor_area_m2,\n floors_cardinal_df,\n total_gross_floor_area_m2,\n mean_floor_height_m,\n system_controls_df,\n supply_temperature_df,\n emissions_cooling_type_dic,\n emissions_controller_type_dic,\n generation_cooling_code_dic,\n occupancy_per_building_cardinal,\n occupancy_per_building_list,\n T_int_cea_dic,\n T_ext_cea_df\n )\n\ndef extract_cea_databases_files(locator):\n # Get data\n internal_loads_df = pd.read_excel(locator.get_archetypes_properties(), 'INTERNAL_LOADS')\n indoor_comfort_df = pd.read_excel(locator.get_archetypes_properties(), 'INDOOR_COMFORT')\n construction_envelope_systems_df = pd.read_excel(locator.get_database_envelope_systems(), 'CONSTRUCTION')\n leakage_envelope_systems_df = pd.read_excel(locator.get_database_envelope_systems(), 'LEAKAGE')\n window_envelope_systems_df = pd.read_excel(locator.get_database_envelope_systems(), 'WINDOW')\n roofs_envelope_systems_df = pd.read_excel(locator.get_database_envelope_systems(), 'ROOF')\n wall_envelope_systems_df = pd.read_excel(locator.get_database_envelope_systems(), 'WALL')\n shading_envelope_systems_df = pd.read_excel(locator.get_database_envelope_systems(), 'SHADING')\n emission_systems_heating_df = pd.read_excel(locator.get_database_air_conditioning_systems(), 'HEATING')\n emission_systems_cooling_df = pd.read_excel(locator.get_database_air_conditioning_systems(), 'COOLING')\n emission_systems_controller_df = pd.read_excel(locator.get_database_air_conditioning_systems(), 'CONTROLLER')\n\n # Set index\n internal_loads_df.set_index('Code', inplace=True)\n indoor_comfort_df.set_index('Code', inplace=True)\n construction_envelope_systems_df.set_index('code', inplace=True)\n leakage_envelope_systems_df.set_index('code', inplace=True)\n window_envelope_systems_df.set_index('code', inplace=True)\n roofs_envelope_systems_df.set_index('code', inplace=True)\n wall_envelope_systems_df.set_index('code', inplace=True)\n shading_envelope_systems_df.set_index('code', inplace=True)\n emission_systems_heating_df.set_index('code', inplace=True)\n emission_systems_cooling_df.set_index('code', inplace=True)\n emission_systems_controller_df.set_index('code', inplace=True)\n cooling_generation_df.set_index('code', inplace=True)\n\n return (\n internal_loads_df,\n indoor_comfort_df,\n construction_envelope_systems_df,\n leakage_envelope_systems_df,\n window_envelope_systems_df,\n roofs_envelope_systems_df,\n wall_envelope_systems_df,\n shading_envelope_systems_df,\n emission_systems_heating_df,\n emission_systems_cooling_df,\n emission_systems_controller_df,\n system_controls_ini_df,\n cooling_generation_df\n )\n\n\ndef extract_cea_inputs_files(locator):\n \"\"\"\n extract information from the zones in the case study\n :param locator:\n :return:\n \"\"\"\n # Get dataframes\n zone_occupancy_df = dbf_to_dataframe(locator.get_building_occupancy())\n zone_df = Gdf.from_file(locator.get_zone_geometry())\n architecture_df = dbf_to_dataframe(locator.get_building_architecture())\n technical_systems_df = dbf_to_dataframe(locator.get_building_air_conditioning())\n supply_systems_df = dbf_to_dataframe(locator.get_building_supply())\n\n # Set index\n zone_occupancy_df.set_index('Name', inplace=True)\n zone_df.set_index('Name', inplace=True)\n architecture_df.set_index('Name', inplace=True)\n technical_systems_df.set_index('Name', inplace=True)\n supply_systems_df.set_index('Name', inplace=True)\n\n return zone_occupancy_df, zone_df, architecture_df, technical_systems_df, supply_systems_df\n\n\ndef extract_cea_building_geometry(locator, buildings_names):\n building_geometry_all = {}\n for building in buildings_names:\n building_geometry_all[building] = pd.read_csv(locator.get_radiation_metadata(building))\n return building_geometry_all\n\n\ndef process_weather_file(weather_path):\n \"\"\"\n This function deals with the fact that the weather file has an .epw format that is non-pandas dataframe ready.\n :param weather_path:\n :return:\n \"\"\"\n\n # Get data\n with open(weather_path, 'rb') as f:\n reader = csv.reader(f)\n weather_initial = list(reader)\n\n # Extract the file general information\n weather_general_info = weather_initial[: 8]\n\n # Extract the weather timeseries\n # The labels of this timeseries can be found at\n # https://energyplus.net/sites/all/modules/custom/nrel_custom/pdfs/pdfs_v8.9.0/AuxiliaryPrograms.pdf at 2.9.1\n weather_timeseries_initial = weather_initial[8:]\n weather_timeseries_labels = [\n 'year',\n 'month',\n 'day',\n 'hour',\n 'minute',\n 'data_source',\n 'dry_bulb_temperature_C',\n 'dew_point_temperature_C',\n 'relative_humidity_percent',\n 'atmospheric_pressure_Pa',\n 'extraterrestrial_horizontal_radiation_Wh_m2',\n 'extraterrestrial_direct_normal_radiation_Wh_m2',\n 'horizontal_infrared_radiation_intensity_Wh_m2',\n 'global_horizontal_radiation_Wh_m2',\n 'direct_normal_radiation_Wh_m2',\n 'diffuse_horizontal_radiation_Wh_m2',\n 'global_horizontal_illuminance_lux',\n 'direct_normal_illuminance_lux',\n 'diffuse horizontal_illuminance_lux',\n 'zenith_luminance_Cd_m2',\n 'wind_direction_degrees',\n 'wind_speed_m_s',\n 'total_sky_cover_tenths',\n 'opaque_sky_cover_tenths',\n 'visibility_km',\n 'ceiling_height_m',\n 'present_weather_observation',\n 'present_weather_codes',\n 'precipitable_water_mm',\n 'aerosol_optical_depth_thousands',\n 'snow_depth_cm',\n 'days_since_last_snowfall',\n 'albedo',\n 'liquid_precipitation_depth_mm',\n 'liquid_precipitation_quantity_hour'\n ]\n weather_timeseries_initial_df = pd.DataFrame.from_records(\n weather_timeseries_initial,\n columns=weather_timeseries_labels\n )\n\n return weather_general_info, weather_timeseries_initial_df\n\n\ndef process_occupancy_schedules(\n locator,\n occupancy_types,\n occupancy_types_cardinal\n):\n \"\"\"\n This function makes the data from the occupancy schedule file more readable and pandas dataframe-ready.\n :param locator:\n :param region:\n :param occupancy_types:\n :param occupancy_types_cardinal:\n :return:\n \"\"\"\n # This function makes the data from the occupancy schedule file more readable and pandas dataframe-ready.\n # Get data\n book = xlrd.open_workbook(locator.get_archetypes_schedules())\n\n # Get occupancy types schedules\n occupancy_schedules = {}\n for occupancy in occupancy_types:\n occupancy_data = book.sheet_by_name(occupancy)\n occupancy_cardinal = occupancy_data.nrows\n occupancy_list = []\n for j in range(occupancy_cardinal):\n occupancy_schedules_j = occupancy_data.row_values(j)\n occupancy_list.append(occupancy_schedules_j)\n occupancy_schedules[occupancy] = occupancy_list\n\n # Get indexes\n index_occupancy = {}\n index_lighting_appliances = {}\n index_monthly_use = {}\n index_occupancy_density = {}\n index_process = {}\n for i in range(occupancy_types_cardinal):\n occupancy = occupancy_types[i]\n for j in range(len(occupancy_schedules[occupancy])):\n if str(occupancy_schedules[occupancy][j][1]) == 'Probability of occupancy (daily)':\n index_occupancy[occupancy] = j\n if str(occupancy_schedules[occupancy][j][1]) == 'Probability of use of lighting and appliances (daily)':\n index_lighting_appliances[occupancy] = j\n if str(occupancy_schedules[occupancy][j][1]) == 'Probability of use (monthly)':\n index_monthly_use[occupancy] = j\n if str(occupancy_schedules[occupancy][j][1]) == 'Occupancy density (m2/p)':\n index_occupancy_density[occupancy] = j\n if str(occupancy_schedules[occupancy][j][1]) == 'Probability of processes (daily)':\n index_process[occupancy] = j\n\n # Check that all the indexes have been found\n if len(index_occupancy) != i + 1:\n raise ValueError(\n 'No Probability of occupancy (daily) found for occupancy type '\n + str(i) + ' in occupancy_schedules.xlsx. Please check the spelling'\n )\n if len(index_lighting_appliances) != i + 1:\n raise ValueError(\n 'No Probability of use of lighting and appliances (daily) found for occupancy type '\n + str(i) + ' in occupancy_schedules.xlsx. Please check the spelling.'\n )\n if len(index_monthly_use) != i + 1:\n raise ValueError(\n 'No Probability of use (monthly) found for occupancy type '\n + str(i) + ' in occupancy_schedules.xlsx. Please check the spelling.'\n )\n if len(index_occupancy_density) != i + 1:\n raise ValueError(\n 'No Occupancy density found for occupancy type '\n + str(i) + ' in occupancy_schedules.xlsx. Please check the spelling.'\n )\n\n # Define labels\n label_day = range(1, 25)\n label_day.insert(0, 'day_of_week')\n label_month = range(1, 13)\n label_month.insert(0, 'Code')\n\n # Get probability of occupancy\n occupants_probability_dic = {}\n for occupancy in occupancy_types:\n occupants_probability_occ = (\n occupancy_schedules[occupancy][index_occupancy[occupancy] + 2: index_occupancy[occupancy] + 5]\n )\n occupants_probability_occ_df = pd.DataFrame.from_records(occupants_probability_occ, columns=label_day)\n occupants_probability_occ_df.set_index('day_of_week', inplace=True)\n occupants_probability_dic[occupancy] = occupants_probability_occ_df\n\n # Get probability of use of lighting and appliances\n lighting_appliances_probability_dic = {}\n for occupancy in occupancy_types:\n lighting_appliances_probability_occ = (\n occupancy_schedules[occupancy][\n index_lighting_appliances[occupancy] + 2: index_lighting_appliances[occupancy] + 5\n ]\n )\n lighting_appliances_probability_occ_df = pd.DataFrame.from_records(\n lighting_appliances_probability_occ,\n columns=label_day\n )\n lighting_appliances_probability_occ_df.set_index('day_of_week', inplace=True)\n lighting_appliances_probability_dic[occupancy] = lighting_appliances_probability_occ_df\n\n # Get probability of processes (if existing)\n processes_probability_dic = {}\n for occupancy in occupancy_types:\n if occupancy in index_process:\n processes_probability_occ = (\n occupancy_schedules[occupancy][index_process[occupancy] + 2: index_process[occupancy] + 5]\n )\n processes_probability_occ_df = pd.DataFrame.from_records(processes_probability_occ, columns=label_day)\n processes_probability_occ_df.set_index('day_of_week', inplace=True)\n processes_probability_dic[occupancy] = processes_probability_occ_df\n\n # Get probability of use (monthly)\n monthly_use_probability = []\n for occupancy in occupancy_types:\n monthly_use_probability_occ = occupancy_schedules[occupancy][index_monthly_use[occupancy] + 2][1:13]\n monthly_use_probability_occ.insert(0, occupancy)\n monthly_use_probability.append(monthly_use_probability_occ)\n\n monthly_use_probability_df = pd.DataFrame(monthly_use_probability, columns=label_month)\n monthly_use_probability_df.set_index('Code', inplace=True)\n\n # Get occupancy density (m2/p)\n occupancy_density_m2_p = {}\n for occupancy in occupancy_types:\n occupancy_density_occ = occupancy_schedules[occupancy][index_occupancy_density[occupancy] + 1][1]\n occupancy_density_m2_p[occupancy] = occupancy_density_occ\n\n return (\n occupants_probability_dic,\n lighting_appliances_probability_dic,\n processes_probability_dic,\n monthly_use_probability_df,\n occupancy_density_m2_p\n )\n\n\ndef extract_common_parameters(\n internal_loads_df,\n zone_occupancy_df\n):\n \"\"\"\n get building names and occupancy types\n :param internal_loads_df:\n :param zone_occupancy_df:\n :return:\n \"\"\"\n occupancy_types_full = internal_loads_df.index\n occupancy_types = zone_occupancy_df.columns\n buildings_names = zone_occupancy_df.index\n\n return (\n occupancy_types_full,\n occupancy_types,\n buildings_names\n )\n\n\ndef calculate_cardinals(\n internal_loads_df,\n zone_occupancy_df,\n occupancy_types\n):\n \"\"\"\n get all occupancy types presented each building in a district\n :param internal_loads_df:\n :param zone_occupancy_df:\n :param occupancy_types: occupancy types in each building\n :return:\n \"\"\"\n occupancy_types_full_cardinal = internal_loads_df.shape[0]\n buildings_cardinal = zone_occupancy_df.shape[0]\n occupancy_types_cardinal = len(occupancy_types)\n\n return (\n occupancy_types_full_cardinal,\n buildings_cardinal,\n occupancy_types_cardinal\n )\n\n\ndef calculate_footprint(\n buildings_names,\n building_geometry_all\n):\n footprint = {}\n for building in buildings_names:\n footprint[building] = (\n building_geometry_all[building][building_geometry_all[building]['TYPE'] == 'roofs'].sum()['AREA_m2']\n )\n\n return footprint\n\n\ndef calculate_gross_floor_area(\n footprint,\n zone_df,\n buildings_names\n):\n floors_cardinal_df = zone_df['floors_bg'] + zone_df['floors_ag']\n gross_floor_area_m2 = {}\n for building in buildings_names:\n gross_floor_area_m2[building] = footprint[building] * floors_cardinal_df[building]\n\n total_gross_floor_area_m2 = sum(gross_floor_area_m2.values())\n\n return gross_floor_area_m2, floors_cardinal_df, total_gross_floor_area_m2\n\n\ndef calculate_mean_floor_height(\n buildings_names,\n zone_df,\n floors_cardinal_df\n):\n mean_floor_height_m = {}\n for building in buildings_names:\n mean_floor_height_m[building] = (\n (\n float(zone_df.loc[building]['height_bg'])\n + float(zone_df.loc[building]['height_ag'])\n )\n / float(floors_cardinal_df[building])\n )\n return mean_floor_height_m\n\n\ndef process_system_controls_file(system_controls_ini_df):\n \"\"\"\n This function extracts the data in a format that will be easier to handle afterwards.\n :param system_controls_ini_df:\n :return:\n \"\"\"\n\n heating_season_start_month = (\n int(system_controls_ini_df.loc[0]['heating-season-start'][0])\n * 10\n + int(system_controls_ini_df.loc[0]['heating-season-start'][1])\n )\n heating_season_start_day = (\n int(system_controls_ini_df.loc[0]['heating-season-start'][3])\n * 10\n + int(system_controls_ini_df.loc[0]['heating-season-start'][4])\n )\n heating_season_end_month = (\n int(system_controls_ini_df.loc[0]['heating-season-end'][0])\n * 10\n + int(system_controls_ini_df.loc[0]['heating-season-end'][1])\n )\n heating_season_end_day = (\n int(system_controls_ini_df.loc[0]['heating-season-end'][3])\n * 10\n + int(system_controls_ini_df.loc[0]['heating-season-end'][4])\n )\n cooling_season_start_month = (\n int(system_controls_ini_df.loc[0]['cooling-season-start'][0])\n * 10\n + int(system_controls_ini_df.loc[0]['cooling-season-start'][1])\n )\n cooling_season_start_day = (\n int(system_controls_ini_df.loc[0]['cooling-season-start'][3])\n * 10\n + int(system_controls_ini_df.loc[0]['cooling-season-start'][4])\n )\n cooling_season_end_month = (\n int(system_controls_ini_df.loc[0]['cooling-season-end'][0])\n * 10\n + int(system_controls_ini_df.loc[0]['cooling-season-end'][1])\n )\n cooling_season_end_day = (\n int(system_controls_ini_df.loc[0]['cooling-season-end'][3])\n * 10\n + int(system_controls_ini_df.loc[0]['cooling-season-end'][4])\n )\n\n system_controls_df = pd.DataFrame.from_records(\n [[\n system_controls_ini_df.loc[0]['has-heating-season'],\n heating_season_start_month,\n heating_season_start_day,\n heating_season_end_month,\n heating_season_end_day,\n system_controls_ini_df.loc[0]['has-cooling-season'],\n cooling_season_start_month,\n cooling_season_start_day,\n cooling_season_end_month,\n cooling_season_end_day\n ]],\n columns=[\n 'has_heating_season',\n 'heating_season_start_month',\n 'heating_season_start_day',\n 'heating_season_end_month',\n 'heating_season_end_day',\n 'has_cooling_season',\n 'cooling_season_start_month',\n 'cooling_season_start_day',\n 'cooling_season_end_month',\n 'cooling_season_end_day'\n ]\n )\n\n return system_controls_df\n\n\ndef synthetize_hvac_properties(\n buildings_names,\n buildings_cardinal,\n technical_systems_df,\n emission_systems_cooling_df,\n supply_systems_df\n):\n emissions_cooling_type_dic = {}\n emissions_controller_type_dic = {}\n generation_cooling_code_dic = {}\n supply_temperature_df = pd.DataFrame(\n np.zeros((buildings_cardinal, 3)),\n buildings_names,\n [\n 'ahu',\n 'aru',\n 'scu'\n ]\n )\n for building in buildings_names:\n emissions_cooling_type_dic[building] = technical_systems_df.loc[building]['type_cs']\n emissions_controller_type_dic[building] = technical_systems_df.loc[building]['type_ctrl']\n generation_cooling_code_dic[building] = supply_systems_df.loc[building, 'type_cs']\n for sys in ['ahu', 'aru', 'scu']:\n supply_temperature_df.loc[building][sys] = emission_systems_cooling_df.loc[\n emissions_cooling_type_dic[building], 'Tscs0_' + sys + '_C']\n\n return (\n supply_temperature_df,\n emissions_cooling_type_dic,\n emissions_controller_type_dic,\n generation_cooling_code_dic\n )\n\n\ndef get_occupancy_per_building(\n buildings_names,\n occupancy_types,\n zone_occupancy_df\n):\n occupancy_per_building_cardinal = {}\n occupancy_per_building_list = {}\n for building in buildings_names:\n counter_build = 0\n list_build = []\n for occupancy in occupancy_types:\n if zone_occupancy_df.loc[building][occupancy] > 0:\n counter_build += 1\n list_build.append(occupancy)\n occupancy_per_building_cardinal[building] = counter_build\n occupancy_per_building_list[building] = list_build\n\n return (\n occupancy_per_building_cardinal,\n occupancy_per_building_list\n )\n\n\ndef get_temperatures(\n locator,\n buildings_names,\n time_start,\n time_end\n):\n \"\"\"\n Get interior and exterior temperatures from CEA demand calculations\n\n Previous name: compare_with_cea\n \"\"\"\n T_int_cea_dic = {}\n for building in buildings_names:\n # Get data\n building_demand_cea_build_df = pd.read_csv(locator.get_demand_results_file(building))\n building_demand_cea_build_df.set_index('DATE', inplace=True)\n building_demand_cea_build_df.index = pd.to_datetime(building_demand_cea_build_df.index)\n\n T_int_build_df = building_demand_cea_build_df.loc[time_start:time_end, 'T_int_C']\n if building == buildings_names[0]:\n T_ext_cea_df = building_demand_cea_build_df.loc[time_start:time_end, 'T_ext_C']\n\n T_int_cea_dic[building] = T_int_build_df\n\n return (\n T_int_cea_dic,\n T_ext_cea_df\n )\n","sub_path":"legacy/flexibility_model/model_building/building_extract_cea_data.py","file_name":"building_extract_cea_data.py","file_ext":"py","file_size_in_byte":26171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"182591346","text":"import zlib\nimport base64\nfrom xml.etree import ElementTree as ET\nimport struct\n\nfrom pyglet import resource\n\ndef row_walker(tiles, width):\n row = []\n for tile in tiles:\n row.append(tile)\n if len(row) == width:\n yield tuple(row)\n row = []\n\ndef mapreader(filename):\n f = resource.file(filename)\n xml = ET.XML(f.read())\n f.close()\n layer = xml.find(\"layer\")\n width = int(layer.attrib['width'])\n height = int(layer.attrib['height'])\n tilewidth = int(xml.attrib['tilewidth'])\n tileheight = int(xml.attrib['tileheight'])\n data = zlib.decompress(base64.b64decode(xml.find(\"layer/data\").text))\n unpack_format = 'I' * (width * height)\n data = struct.unpack(unpack_format, data)\n rev_tiles = [row for row in row_walker(data, width)]\n tiles = []\n for row in reversed(rev_tiles):\n tiles.extend(row)\n objectlayer = xml.find(\"objectgroup\")\n objects = {'other':[]}\n for obj in objectlayer:\n obj_type = obj.attrib['type']\n x = int(obj.attrib['x']) / tilewidth\n y = height - int(obj.attrib['y']) / tileheight - 1\n data = (x, y)\n if obj_type == 'other':\n objects[obj_type].append(data)\n data = objects[obj_type]\n elif obj_type == 'seed':\n seed = int(obj.attrib['name'])\n data += (seed,)\n objects[obj_type] = data\n return width, height, tiles, objects\n","sub_path":"mapreader.py","file_name":"mapreader.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"496486989","text":"from absl import flags\nimport tensorflow.compat.v2 as tf\nfrom object_detection import model_lib_v2\n\nflags.DEFINE_string('pipeline_config_path', None, 'Path to pipeline config file.')\nflags.DEFINE_string('model_dir', None, 'Path to output model directory '\n 'where event and checkpoint files will be written.')\nflags.DEFINE_string('checkpoint_dir', None, 'Path to directory holding a checkpoint. If '\n '`checkpoint_dir` is provided, this binary operates in eval-only mode, '\n 'writing resulting metrics to `model_dir`.')\n\nFLAGS = flags.FLAGS\n\n\ndef evaluate(argv):\n flags.mark_flag_as_required('model_dir')\n flags.mark_flag_as_required('pipeline_config_path')\n flags.mark_flag_as_required('checkpoint_dir')\n\n tf.config.set_visible_devices([], 'GPU')\n print(tf.config.get_visible_devices())\n\n model_lib_v2.eval_continuously(\n pipeline_config_path=FLAGS.pipeline_config_path,\n model_dir=FLAGS.model_dir,\n checkpoint_dir=FLAGS.checkpoint_dir,\n postprocess_on_cpu=True,\n wait_interval=1,\n timeout=1000)\n\n\nif __name__ == \"__main__\":\n tf.compat.v1.app.run(evaluate)\n","sub_path":"object_detection/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"229948629","text":"import os\nimport shutil\nimport platform\nimport modules.sharedfunc\n\n\ndef dir_create(*args):\n if args:\n args = ''.join(args)\n if os.path.exists(args):\n return 'директория существует'\n os.mkdir(args)\n return 'директория создана'\n\n dir_name = input('Укажите имя директории: ')\n temp_dir = os.path.join(os.getcwd(), dir_name)\n if os.path.exists(temp_dir):\n while os.path.exists(temp_dir):\n print(\"Директория с таким имененем существует, укажите другое имя\")\n dir_name = input('Укажите имя директории: ')\n temp_dir = os.path.join(os.getcwd(), dir_name)\n\n os.mkdir(temp_dir)\n print(\"Директория создана\")\n\ndef dir_file_remove():\n while True:\n object_name = input('Укажите имя файла или директории: \\n ')\n full_object_name = os.path.join(os.getcwd(), object_name)\n if os.path.exists(full_object_name):\n if os.path.isfile(full_object_name):\n try:\n os.remove(full_object_name)\n print(\"Файл удалён\")\n break\n except FileNotFoundError:\n print('Системе не удается найти указанный файл')\n continue\n try:\n shutil.rmtree(full_object_name)\n print('Директория удалена')\n break\n except FileNotFoundError:\n print('Системе не удается найти указанный путь')\n print('Системе не удается найти указанный путь, введите корректный путь:\\n')\n\ndef dir_file_copy():\n while True:\n full_src_path = input('Укажите полный путь что копировать: \\n')\n full_dst_path = input('Укажите полный путь куда копировать включая новое имя файла или папки: \\n')\n if full_src_path == full_dst_path:\n print('Источник совпадает с назначением, повторите ввод:')\n continue\n\n if not os.path.exists(full_src_path):\n print('Источник для копирования не найден')\n continue\n\n #понадобавлял тут обработок эксепшенов, пока правильно все пути не ввести, будем сидеть в цикле\n #жестко, но в целях тренировки пойдет :)\n if os.path.isfile(full_src_path):\n while True:\n try:\n shutil.copy2(full_src_path, full_dst_path)\n print(\"Файл скопирован\")\n break\n except FileNotFoundError:\n print('Не существует такой путь куда вы пытаетсь скопировать файл')\n full_dst_path = input('Укажите полный путь куда копировать включая новое имя файла: \\n')\n break\n else:\n while True:\n try:\n shutil.copytree(full_src_path, full_dst_path)\n print(\"Директория скопирована\")\n break\n except FileExistsError:\n print('Похоже вы забыли указать имя итоговой папки')\n full_dst_path = input('Повторите ввод полного пути куда копировать включая новое имя папки: \\n')\n except FileNotFoundError:\n print('Системе не удается найти указанный путь')\n break\n\n\n#(переписано как генератор списка)\ndef list_files_and_dirs():\n print('----------------Директории-------------------')\n dirs = [i for i in list_dirs()]\n print(dirs)\n print('------------------Файлы----------------------')\n files = [i for i in list_files()]\n print(files)\n\ndef list_files():\n #(переписано как генератор списка)\n ffiles = [file for file in os.listdir(os.getcwd()) if os.path.isfile(os.path.join(os.getcwd(), file))]\n return ffiles\n\ndef list_dirs(*args):\n # (переписано как генератор списка)\n if args:\n os.chdir(r\"args\")\n dirs = str(os.listdir(os.getcwd()))\n fdirs = [path for path in os.listdir(dirs) if not os.path.isfile(path)]\n return fdirs\n fdirs = [path for path in os.listdir(os.getcwd()) if not os.path.isfile(path)]\n return fdirs\n\ndef save_list_dir_and_files():\n #(переписано как генератор списка)\n fdirs = [path for path in os.listdir(os.getcwd()) if not os.path.isfile(path)]\n ffiles = [file for file in os.listdir(os.getcwd()) if os.path.isfile(os.path.join(os.getcwd(), file))]\n\n with open(\"listdir.txt\", \"w\", encoding='utf-8') as f:\n f.write('Директории\\n')\n for d in fdirs:\n f.write(d + '\\n')\n f.write('----------------------------------\\n')\n f.write('Файлы\\n')\n for file in ffiles:\n f.write(file + '\\n')\n\n\n@modules.sharedfunc.add_separators\ndef watch_os_info():\n print(\"Операционная система: \", platform.system(), platform.release(), platform.machine())\n\ndef about_creator():\n return 'Created by Maxim D.'\n\n","sub_path":"modules/fmfunc.py","file_name":"fmfunc.py","file_ext":"py","file_size_in_byte":5824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"640621845","text":"import numpy as np\r\nimport pyautogui\r\nfrom pyautogui import typewrite\r\nimport imutils\r\nimport cv2\r\nimport pytesseract\r\nWINDOW_POSITION = (0,0)\r\nWINDOW_SIZE = (1280,640)\r\nFULL_SCREEN = (1835,1040)\r\nHEADER_HEIGHT = 30\r\ncharacter = {\r\n\t'frey':(64,290),\r\n\t'lorraine':(120,290),\r\n\t'miruru':(170,290),\r\n\t'clause':(64,350)\r\n}\r\nfilters = {\r\n\t'weapon':\t\t\t(183,172),\r\n\t'armor':\t\t\t(183,190),\r\n\t'secondary':\t\t(183,208),\r\n\t'accessory':\t\t(183,226),\r\n\t'orb':\t\t\t\t(183,242),\r\n\t't8':\t\t\t\t(368,293),\r\n\t'0*':\t\t\t\t(456,172)\r\n}\r\nstat_filters = {\r\n\t'P.Block':\t\t\t(183,172),\r\n\t'CC Resist':\t\t(183,172),\r\n\t'Crit Resist':\t\t(183,172),\r\n\t'M.Crit Resist':\t(183,172),\r\n\t'Max HP':\t\t\t(183,172),\r\n\t'ACC':\t\t\t\t(183,172),\r\n\t'P.Dodge':\t\t\t(183,172),\r\n\t'DEF':\t\t\t\t(183,172),\r\n\t'Debuff ACC':\t\t(183,172),\r\n\t'MP/Sec':\t\t\t(183,172),\r\n\t'P.Def':\t\t\t(183,172),\r\n\t'Penetration':\t\t(183,172),\r\n\t'Block':\t\t\t(183,172),\r\n\t'M.Block':\t\t\t(183,172),\r\n\t'MP/Attack':\t\t(183,172),\r\n\t'M.Def':\t\t\t(183,172),\r\n\t'Lifesteal':\t\t(183,172),\r\n\t'Dodge':\t\t\t(183,172),\r\n\t'M.Dodge':\t\t\t(183,172),\r\n\t'P.Crit Resist':\t(183,172)\r\n\r\n}\r\n\r\n\"\"\"\r\nBefore running, resize window to \r\n1280 by 720+30\r\n640 by 360\r\n\"\"\"\r\ndef help():\r\n\tpass\r\ndef init():\r\n\tpass\r\ndef start_nox():\r\n\tpass\r\ndef position_nox():\r\n\tpass\r\ndef start_kr():\r\n\tpass\r\n\t\r\ndef screenshot(bw=True):\r\n\timage = pyautogui.screenshot()\r\n\tif bw:\r\n\t\treturn cv2.cvtColor(np.array(image),cv2.COLOR_RGB2GRAY)\r\n\treturn cv2.cvtColor(np.array(image),cv2.COLOR_RGB2BGR)\r\n\t\r\ndef click(x, y):\r\n\tx, y = rescale((x,y))\r\n\tpyautogui.moveTo(x,y,.5, pyautogui.easeInQuad)\r\n\tpyautogui.click()\r\ndef rescale(pos):\r\n\tx, y= pos\r\n\tx = int(WINDOW_SIZE[0]/640*x)\r\n\ty = int(WINDOW_SIZE[1]/360*(y-30)+30)\r\n\treturn (x,y)\r\ndef focus_textbox():\r\n\tclick(320, 360)\r\ndef confirm_input():\r\n\tclick(622,360)\r\n\r\ndef chat(message):\r\n\tclick(280,350)\r\n\ttypewrite(message, interval = .05)\r\n\tconfirm_input()\r\n\r\ndef grab_box(topleft, bottomright):\r\n\t#topleft = rescale(topleft)\r\n\t#bottomright = rescale(bottomright)\r\n\timage = screenshot()\r\n\treturn image[topleft[1]:bottomright[1],topleft[0]:bottomright[0]]\r\n\t\r\ndef scan_chat():\r\n\t#image = grab_box((289,320),(410,333))\r\n\timage = grab_box((855,852),(1190,885))\r\n\tcv2.imwrite('output.png',image)\r\n\timage = preprocess(image)\r\n\ttext = pytesseract.image_to_string(image).lower()\r\n\tprint(text)\r\n\tif len(text) > 3 and text[:3] == \"ygg\":\r\n\t\thandle_input(text[4:].strip())\r\n\t\r\ndef sell(input):\r\n\tclick(65,250)\t\t#manage inventory\r\n\tclick(550,340)\t\t#sell\r\n\tclick(370,340)\t\t#sell all\r\n\tclick(385,335)\t\t#sell\r\n\tclick(380,295)\t\t#confirm sell\r\n\tclick(535,80)\t\t#close sell all menu\r\n\tclick(110,40)\r\n\t\r\ndef handle_input(input):\r\n\tif input in commands.keys():\r\n\t\tcommands[input](input)\r\n\telse:\r\n\t\tchat(\"Invalid command: \"+input)\r\n\t\r\ndef invert(image):\r\n\t_, thresh = cv2.threshold(image,127,255,cv2.THRESH_BINARY_INV)\r\n\treturn thresh\r\n\t\r\ndef toggle_char(char):\r\n\tclick(*character[char])\r\ncommands = {\r\n\t'frey': toggle_char,\r\n\t'lorraine': toggle_char,\r\n\t'miruru': toggle_char,\r\n\t'clause': toggle_char,\r\n\t'help': help,\r\n\t'sell': sell\r\n}\r\ndef preprocess(image):\r\n\timage = invert(image)\r\n\treturn cv2.medianBlur(image, 3)\r\ndef stam(image):\r\n\treturn\r\ndef inventory(image, ):\r\n\treturn\r\ndef log_position():\r\n\tprint('Press Ctrl-C to quit.')\r\n\ttry:\r\n\t\twhile True:\r\n\t\t\tx, y = pyautogui.position()\r\n\t\t\tpositionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)\r\n\t\t\tprint(positionStr, end='')\r\n\t\t\tprint('\\b' * len(positionStr), end='', flush=True)\r\n\texcept KeyboardInterrupt:\r\n\t\tprint('\\n')\r\n\r\nWINDOW_SIZE = FULL_SCREEN\r\n#click(100,100)\r\n#focus_textbox()\r\n#chat('Hello world')\r\nscan_chat()\r\nlog_position()","sub_path":"jjyin2/yggdroid.py","file_name":"yggdroid.py","file_ext":"py","file_size_in_byte":3553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"319290222","text":"import frappe\nfrom frappe import _\nfrom .express_checkout import set_express_checkout\n\ndef get_payment_url(doc, method):\n\tif doc.docstatus == 1:\n\t\tif doc.payment_gateway == \"PayPal\":\n\t\t\tset_express_checkout(doc.grand_total, doc.currency, {\"doctype\": doc.doctype, \"docname\": doc.name})\n\telse:\n\t\tfrappe.respond_as_web_page(_(\"Invalid Payment Request\"), \n\t\t\t_(\"Payment Request has been canceled by vendor\"), success=False, \n\t\t\thttp_status_code=frappe.ValidationError.http_status_code)\n\t","sub_path":"paypal_integration/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"341941035","text":"import os, getpass\nclear = lambda: os.system('clear')\nclear()\nplaying = 1\ntries = 0\nmultip = 0\nll = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nwhile playing == 1:\n\tfin = 0\n\tprint(\"Hangman™\\n\")\n\t# word = input(\"Enter a word: \")\n\tword = getpass.getpass(\"Enter a word: \")\n\tword = word.capitalize().strip()\n\tclear()\n\tprint(\"Hangman™\\n\")\n\t\n\tlives = 6\n\ts = \"-\" * len(word)\n\tletters = []\n\ti = 0\n\twhile i < len(word):\n\t\tif word[i].upper() == \" \":\n\t\t\tmultip = 1\n\t\t\ts = s[:i]+\" \"+s[(i+1):]\n\t\ti += 1\n\ta = s\n\tfor x in a:\n\t\tif x == \" \":\n\t\t\ta = a.replace(x,\"\")\t\n\tprint(\"A word consisting of {} letters has been chosen. Good luck!\".format(len(a)))\t\n\t#while lives != 0 and s != word:\n\twhile lives != 0 and \"-\" in s:\n\t\tprint(\"Word: {}\".format(s))\n\t\tletter = input(\"Pick a letter: \")\n\t\twhile letter.upper() in letters or len(letter) != 1 or letter.upper() not in ll:\n\t\t\tletter = input(\"Pick a new letter: \")\n\t\tletters.append(letter.upper())\n\t\tif letter.upper() in word.upper():\n\t\t\ti = 0\n\t\t\tprint(\"You gussed a correct letter!\")\n\t\t\twhile i < len(word):\n\t\t\t\tif word[i].upper() == letter.upper():\n\t\t\t\t\ts = s[:i]+letter.upper()+s[(i+1):]\n\t\t\t\ti += 1\t\n\t\telse:\n\t\t\tlives -= 1\n\t\t\tprint(\"Uh oh, wrong letter...\\nYou have {} lives left.\".format(lives))\n\n\tif lives == 0:\n\t\tclear()\n\t\tprint(\"Hangman™\\n\")\n\t\tprint(\"You suck, pleb.\\nThe word was {}\".format(word))\n\telse:\n\t\tclear()\n\t\tprint(\"Hangman™\\n\")\n\t\tif multip != 1:\n\t\t\tprint(\"Whoever picked that word, congratulations you played yourself. GG.\\nThe word was {}\".format(word))\n\t\telse:\n\t\t\tprint(\"Whoever picked those words, congratulations you played yourself. GG.\\nThe words were {}\".format(word))\t\n\n\twhile fin == 0:\t\n\t\tplaying = input(\"Play again? Yes|No : \")\n\t\tif playing.lower() == \"yes\":\n\t\t\tfin = 1\n\t\t\tplaying = 1\n\t\telif playing.lower() != \"yes\" and playing.lower() != \"no\" :\n\t\t\tprint(\"{} is not a valid option, dummy.\".format(playing.strip()))\n\t\t\ttries += 1\n\t\t\tif tries == 3:\n\t\t\t\tclear()\n\t\t\t\tprint(\"Hangman™\\n\")\n\t\t\t\tprint(\"Think you're being funny, do ya?\")\n\t\t\t\tplaying = 0\n\t\t\t\tfin = 1\n\n\t\telse:\n\t\t\tplaying = 0\n\t\t\tfin = 1\n\t\t\tclear()\n\t\t\tprint(\"Hangman™\\n\")\n\t\t\tprint(\"Whatever, never liked you anyway.\")\n\n\t\t#How do I get rid of whitespace to the left of a string?\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"453021403","text":"from unittest import TestCase\nfrom model_02.class_Building import Building\nfrom model_02.class_Floor import Floor\n\n\nclass TestBuilding(TestCase):\n def test_set_height(self):\n b = Building(\"my building\", 50)\n self.assertEqual(b.height, 50)\n b.set_height(100)\n self.assertEqual(b.height, 100)\n\n\nclass TestBuilding(TestCase):\n def test_generate_floor(self):\n b = Building(\"my building\", 100)\n self.assertEqual(b.floor_height_total(), 0)\n f1 = Floor()\n f1.height = 20\n b.floor_list.append(f1)\n self.assertEqual(b.floor_height_total(), 20)\n b.generate_floor(8)\n self.assertEqual(b.floor_height_total(), 0)\n\n\n","sub_path":"sample/test_building.py","file_name":"test_building.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"379782786","text":"\n# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nimport datetime\nfrom collections import defaultdict\nfrom itertools import groupby\nimport logging\n_logger = logging.getLogger(__name__)\nfrom odoo import api, fields, models, _\nfrom odoo.exceptions import AccessError, UserError\nfrom odoo.tools import date_utils, float_compare, float_round, float_is_zero\n\nclass MrpRouting(models.Model):\n _inherit = 'mrp.routing'\n capacity = fields.Float(\n 'Capacity', default=0.0,\n help=\"Number of pieces that can be produced in parallel. In case the work center has a capacity of 5 and you have to produce 10 units on your work order, the usual operation time will be multiplied by 2.\")\n\nclass MrpRoutingWorkcenter(models.Model):\n _inherit = 'mrp.routing.workcenter'\n @api.depends('time_cycle_manual', 'time_mode', 'workorder_ids')\n def _compute_time_cycle(self):\n manual_ops = self.filtered(lambda operation: operation.time_mode == 'manual')\n for operation in manual_ops:\n operation.time_cycle = operation.time_cycle_manual\n for operation in self - manual_ops:\n\n \n data = self.env['mrp.workorder'].read_group([\n ('operation_id', '=', operation.id),\n ('state', '=', 'done')], ['operation_id', 'duration', 'qty_produced'], ['operation_id'],\n limit=operation.time_mode_batch)\n count_data = dict((item['operation_id'][0], (item['duration'], item['qty_produced'])) for item in data)\n if count_data.get(operation.id) and count_data[operation.id][1]:\n routing_id = operation.routing_id.capacity\n #operation.time_cycle = (count_data[operation.id][0] / count_data[operation.id][1]) * (operation.workcenter_id.capacity or 1.0)\n operation.time_cycle = (count_data[operation.id][0] / count_data[operation.id][1]) * (operation.workcenter_id.capacity or 1.0) if routing_id == 0 else routing_id\n else:\n operation.time_cycle = operation.time_cycle_manual\nclass MrpProduction(models.Model):\n _inherit = 'mrp.production'\n rcount_scrap = fields.Float('Conteo scrap', compute='_on_scrap_ids' ,store=True )\n\n\n\n @api.depends('scrap_ids','scrap_ids.scrap_qty')\n def _on_scrap_ids(self):\n for rec in self:\n \n scraps = rec.scrap_ids\n if scraps:\n \n rec.rcount_scrap = sum(scraps.mapped('scrap_qty'))\n else:\n rec.rcount_scrap = 0\n\n def _plan_workorders(self):\n \"\"\" Plan all the production's workorders depending on the workcenters\n work schedule\"\"\"\n self.ensure_one()\n\n # Schedule all work orders (new ones and those already created)\n qty_to_produce = max(self.product_qty - self.qty_produced, 0)\n qty_to_produce = self.product_uom_id._compute_quantity(qty_to_produce, self.product_id.uom_id)\n start_date = self._get_start_date()\n for workorder in self.workorder_ids:\n workcenters = workorder.workcenter_id | workorder.workcenter_id.alternative_workcenter_ids\n\n best_finished_date = datetime.datetime.max\n vals = {}\n routing_id = workorder.operation_id.routing_id.capacity\n \n for workcenter in workcenters:\n # compute theoretical duration\n\n time_cycle = workorder.operation_id.time_cycle\n \n cycle_number = float_round(qty_to_produce /( workcenter.capacity if routing_id == 0 else routing_id ), precision_digits=0, rounding_method='UP')\n \n duration_expected = workcenter.time_start + workcenter.time_stop + cycle_number * time_cycle * 100.0 / workcenter.time_efficiency\n \n _logger.info(\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\")\n _logger.info( qty_to_produce)\n _logger.info( workcenter.capacity if routing_id == 0 else routing_id)\n _logger.info(cycle_number)\n _logger.info(duration_expected) \n # get first free slot\n # planning 0 hours gives the start of the next attendance\n from_date = workcenter.resource_calendar_id.plan_hours(0, start_date, compute_leaves=True, resource=workcenter.resource_id, domain=[('time_type', 'in', ['leave', 'other'])])\n # If the workcenter is unavailable, try planning on the next one\n if from_date is False:\n continue\n #CHANGE duration_expected / 60.0 -> duration_expected\n to_date = workcenter.resource_calendar_id.plan_hours(duration_expected, from_date, compute_leaves=True, resource=workcenter.resource_id, domain=[('time_type', 'in', ['leave', 'other'])])\n\n # Check if this workcenter is better than the previous ones\n if to_date and to_date < best_finished_date:\n best_start_date = from_date\n best_finished_date = to_date\n best_workcenter = workcenter\n vals = {\n 'workcenter_id': workcenter.id,\n 'capacity': workcenter.capacity if routing_id == 0 else routing_id,\n 'duration_expected': duration_expected,\n }\n\n # If none of the workcenter are available, raise\n if best_finished_date == datetime.datetime.max:\n raise UserError(_('Impossible to plan the workorder. Please check the workcenter availabilities.'))\n\n # Instantiate start_date for the next workorder planning\n if workorder.next_work_order_id:\n if workorder.operation_id.batch == 'no' or workorder.operation_id.batch_size >= qty_to_produce:\n start_date = best_finished_date\n else:\n cycle_number = float_round(workorder.operation_id.batch_size / (best_workcenter.capacity if routing_id == 0 else routing_id ), precision_digits=0, rounding_method='UP')\n duration = best_workcenter.time_start + cycle_number * workorder.operation_id.time_cycle * 100.0 / best_workcenter.time_efficiency\n start_date = best_workcenter.resource_calendar_id.plan_hours(duration / 60.0, best_start_date, compute_leaves=True, resource=best_workcenter.resource_id, domain=[('time_type', 'in', ['leave', 'other'])])\n\n # Create leave on chosen workcenter calendar\n leave = self.env['resource.calendar.leaves'].create({\n 'name': self.name + ' - ' + workorder.name,\n 'calendar_id': best_workcenter.resource_calendar_id.id,\n 'date_from': best_start_date,\n 'date_to': best_finished_date,\n 'resource_id': best_workcenter.resource_id.id,\n 'time_type': 'other'\n })\n vals['leave_id'] = leave.id\n workorder.write(vals)\n self.with_context(force_date=True).write({\n 'date_planned_start': self.workorder_ids[0].date_planned_start,\n 'date_planned_finished': self.workorder_ids[-1].date_planned_finished\n })\n","sub_path":"fleximatic/models/mrp/mrp_routing.py","file_name":"mrp_routing.py","file_ext":"py","file_size_in_byte":7278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"493404468","text":"# Reinforcement Learning with OpenAI Gym\n\n# Example 1\n'''\nimport gym\n\nenv = gym.make('CartPole-v0')\nenv.reset()\n\nfor t in range(1000):\n\n\tenv.render()\n\n\tenv.step(env.action_space.sample()) # this provides a random action\n'''\n\n# Step function is giving us many things like:\n# 1) Observation: Environment specific information representing environment observations. Example: Angles,Velocities,Game States,etc\n# 2) Reward: Amount of reward achieved by the previous action. Scale varies based off environment, but agent should always want to increase the reward level\n# 3) Done: Boolean, indicating whether the environment needs to be reset, example game is lost, pole tipped over, etc\n# 4) Info: Dictionary object with some diagnostic information, useful for debugging\n\n'''\n# Example 2\n\nimport gym\n\nenv = gym.make('CartPole-v0')\n\nprint('Initial Observation')\nobservation = env.reset()\nprint(observation)\n\nfor _ in range(2):\n\n\taction = env.action_space.sample()\n\tobservation, reward, done, info = env.step(action)\n\n\tprint('Observation' +': ')\n\tprint(observation)\n\tprint('Reward' +': '+str(reward))\n\tprint('Done' +': '+str(done))\n\tprint('Info' +': '+str(info))\n'''\n\n# Example 3\n\nimport gym\n\nenv = gym.make('CartPole-v0')\n\nobservation = env.reset()\n\nfor t in range(10000):\n\n\tenv.render()\n\n\tcart_position , cart_velocity, pole_angle, angle_velocity = observation\n\n\tif pole_angle > 0:\n\t\taction = 1\n\telse:\n\t\taction = 0\n\t\t\n\tobservation, reward, done, info = env.step(action)\n","sub_path":"RFL/openai_basic_example.py","file_name":"openai_basic_example.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"611198590","text":"#!/usr/bin/env python\n# Copyright (c) 2020 VMware, Inc. All Rights Reserved.\n# SPDX-License-Identifier: BSD-2 License\n# The full license information can be found in LICENSE.txt\n# in the root directory of this project.\n\nimport json\nimport logging\nimport os\nimport platform\nimport socket\nimport sys\n\nfrom sql30 import db\n\nfrom axon.apps.base import BaseApp\nfrom axon.common import consts, utils\n\nlog = logging.getLogger(__name__)\nconfigs = None\n\n\n# # # # # All Configurable Variables set below # # # # #\n\nLINUX_OS = \"Linux\" in platform.uname()\nLOG_FILE = os.environ.get('LOG_FILE', consts.LOG_FILE)\nLOG_DIR = os.environ.get('LOG_DIR', consts.LOG_DIR)\nutils.setup_logging(log_dir=LOG_DIR, log_file=LOG_FILE)\n\n\n# Traffic Server Configs\nREQUEST_QUEUE_SIZE = 100\nPACKET_SIZE = 1024\nALLOW_REUSE_ADDRESS = True\n\n\n# Env Configs\nTEST_ID = os.environ.get('TEST_ID', None)\nTESTBED_NAME = os.environ.get('TESTBED_NAME', None)\nAXON_PORT = int(os.environ.get('AXON_PORT', 5678))\n\n\n# Wavefront recorder configs\nWAVEFRONT_PROXY_ADDRESS = os.environ.get('WAVEFRONT_PROXY_ADDRESS', None)\nWAVEFRONT_SERVER_ADDRESS = os.environ.get('WAVEFRONT_SERVER_ADDRESS', None)\nWAVEFRONT_SERVER_API_TOKEN = os.environ.get('WAVEFRONT_SERVER_API_TOKEN', None)\nWAVEFRONT_SOURCE_TAG = os.environ.get('WAVEFRONT_SOURCE', socket.gethostname())\nWAVEFRONT_REPORT_PERC = float(os.environ.get('WAVEFRONT_REPORT_PERC', 1.0))\n\n\n# Namespace Configs\nNAMESPACE_MODE = os.environ.get(\"NAMESPACE_MODE\", False)\nNAMESPACE_MODE = True if NAMESPACE_MODE in ['True', True] else False\nNAMESPACE_INTERFACE_NAME_PREFIXES = [\"veth\", \"eth\"]\n\n\n# Recorder Configs\nRECORDER = os.environ.get('RECORDER', None)\nRECORD_COUNT_UPDATER_SLEEP_INTERVAL = 30\nRECORD_UPDATER_THREAD_POOL_SIZE = 50\n\nELASTIC_SEARCH_SERVER_ADDRESS = os.environ.get('ELASTIC_SEARCH_SERVER_ADDRESS', None)\nELASTIC_SEARCH_SERVER_PORT = os.environ.get(\n 'ELASTIC_SEARCH_SERVER_PORT', consts.ELASTIC_SEARCH_PORT)\n\n# # # # # End of Configurable Variables # # # # #\n\n\nclass ConfigDB(db.Model):\n DB_NAME = 'params.db'\n TABLE = 'config'\n\n DB_SCHEMA = {\n 'db_name': DB_NAME,\n 'tables': [\n {\n 'name': TABLE,\n 'fields': {\n 'param': 'text',\n 'value': 'text',\n 'typename': 'text',\n },\n 'primary_key': 'param' # avoid duplicate entries.\n }]\n }\n VALIDATE_BEFORE_WRITE = True\n\nclass Config(ConfigDB, BaseApp):\n NAME = \"CONFIG\"\n\n def __init__(self, db_file=None):\n # Set database name.\n db_name = db_file or self.DB_NAME\n super(Config, self).__init__(db_name=db_name)\n self.table = self.TABLE\n\n # set params\n self._params = {}\n\n # Read configs, load from db file.\n\n self._read_config()\n self.load_from_db()\n self.save_to_db()\n\n def _read_config(self):\n \"\"\"\n Reads config from default config file.\n\n We do not write these configs into the database yet as database\n configs are supposed to overwrite.\n \"\"\"\n\n module_name = sys.modules[__name__]\n VARS = [var for var in dir(module_name) if var.isupper()]\n for var in VARS:\n param, val = var, getattr(module_name, var)\n self._params[param] = val\n\n def _type_handler(self, val, type_name):\n\n types_map = {\n 'int': lambda x: int(x),\n 'float': lambda x: float(x),\n 'tuple': lambda x: tuple(x),\n 'set': lambda x: set(x),\n 'bool': lambda x: True if x == 'True' else False,\n 'NoneType': lambda x: None,\n }\n val = json.loads(val)\n\n return types_map[type_name](val) if type_name in types_map else val\n\n def load_from_db(self):\n \"\"\"\n Load config params from database file to local cache.\n \"\"\"\n configs = []\n with ConfigDB() as db:\n configs = db.read(tbl=self.TABLE)\n for key, val, type_name in configs:\n self._params[key] = self._type_handler(val, type_name)\n\n def save_to_db(self):\n \"\"\"\n Save config params in local cache to database file.\n \"\"\"\n with ConfigDB() as db:\n db.table = self.TABLE\n for param, val in self._params.items():\n self._persist_param(param, val, db)\n\n def get_param(self, param):\n \"\"\"\n Return the value of a config param. Param is always\n returned from local cache as it is simply a reflector of database file.\n \"\"\"\n return self._params.get(param, None)\n\n def set_param(self, param, val, write_to_db=True):\n self._params[param] = val\n\n if write_to_db:\n with ConfigDB() as db:\n db.table = self.TABLE\n self._persist_param(param, val, db)\n\n def _persist_param(self, param, val, db_handle):\n \"\"\"\n Sets a param, val in database file.\n \"\"\"\n type_name = type(val).__name__\n if isinstance(val, set):\n # json.dumps can't serialize sets. We still return the\n # value as set as type is stored as \"set\"\n val = list(val)\n record = db_handle.read(param=param)\n if record:\n db_handle.update(condition={'param': param},\n value=json.dumps(val),\n typename=type_name)\n else:\n db_handle.write(param=param,\n value=json.dumps(val),\n typename=type_name)\n\n exposed_get_param = get_param\n exposed_set_param = set_param\n\n\ndef get_configs():\n global configs\n if not configs:\n configs = Config()\n\n return configs\n\n\ndef get_param(param):\n return get_configs().get_param(param)\n\n\ndef set_param(param, val):\n return get_configs().set_param(param, val)\n","sub_path":"AXON/axon/apps/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":5917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"245417577","text":"from PyQt5.QtWidgets import QCompleter, QPlainTextEdit,QApplication\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QTextCursor\nfrom MyCompleter import *\nimport time\n\nclass AwesomeTextEdit(QPlainTextEdit):\n\tdef __init__(self, parent=None):\n\t\tsuper(AwesomeTextEdit, self).__init__(parent)\n\t\tself.completer = MyCompleter()\n\t\tself.completer.setWidget(self)\n\t\tself.completer.insertText.connect(self.insertCompletion)\n\t\tself.key = None\n\t\tself.block = False\n\t\tself.last = []\n\t\tself.filePath = None\n\t\tself.setStyleSheet(\"background-color: #323232;color:white;\")\n\n\tdef insertCompletion(self, completion):\n\t\ttc = self.textCursor()\n\t\textra = (len(completion) - len(self.completer.completionPrefix()))\n\t\t#print(completion)\n\t\ttc.movePosition(QTextCursor.Left)\n\t\ttc.select(tc.WordUnderCursor)\n\t\ttc.insertText(tc.selectedText().replace(tc.selectedText(),completion))\n\t\tself.setTextCursor(tc)\n\t\tself.completer.popup().hide()\n\n\tdef focusInEvent(self, event):\n\t\tif self.completer:\n\t\t\tself.completer.setWidget(self)\n\t\tQPlainTextEdit.focusInEvent(self, event)\n\n\tdef keyPressEvent(self, event):\n\t\tself.key = event.key()\n\t\tif event.key() == QtCore.Qt.Key_Backtab:\n\t\t\tcur = self.textCursor()\n\t\t\tpos = cur.position()\n\t\t\tanchor = cur.anchor()\n\t\t\tcur.setPosition(pos) \n\t\t\tcur.setPosition(pos-1,QtGui.QTextCursor.KeepAnchor)\n\t\t\t\n\t\t\tif str(cur.selectedText()) == \"\\t\":\n\t\t\t\tcur.removeSelectedText()\n\t\t\t\tcur.setPosition(anchor-1)\n\t\t\t\tcur.setPosition(pos-1,QtGui.QTextCursor.KeepAnchor)\n\t\t\telse:\n\t\t\t\tcur.setPosition(anchor) \n\t\t\t\tcur.setPosition(anchor-1,QtGui.QTextCursor.KeepAnchor)\n\t\t\t\tif str(cur.selectedText()) == \"\\t\":\n\t\t\t\t\tcur.removeSelectedText()\n\t\t\t\t\tcur.setPosition(anchor-1)\n\t\t\t\t\tcur.setPosition(pos-1,QtGui.QTextCursor.KeepAnchor)\n\t\t\t\telse:\n\t\t\t\t\tcur.setPosition(anchor)\n\t\t\t\t\tcur.setPosition(pos,QtGui.QTextCursor.KeepAnchor)\n\t\ttc = self.textCursor()\n\t\tif event.key() == Qt.Key_Return and self.completer.popup().isVisible():\n\t\t\tself.completer.insertText.emit(self.completer.getSelected())\n\t\t\tself.completer.setCompletionMode(QCompleter.PopupCompletion)\n\t\t\treturn\n\n\t\tQPlainTextEdit.keyPressEvent(self, event)\n\t\ttc.select(QTextCursor.WordUnderCursor)\n\t\tcr = self.cursorRect()\n\n\t\tkeylist = [Qt.Key_Down,Qt.Key_Up,Qt.Key_Right,Qt.Key_Left]\n\n\t\tif len(tc.selectedText()) > 0 and tc.selectedText() != self.completer.currentCompletion() and event.key() not in keylist:\n\t\t\tself.completer.setCompletionPrefix(tc.selectedText())\n\t\t\tpopup = self.completer.popup()\n\t\t\tpopup.setCurrentIndex(self.completer.completionModel().index(0,0))\n\t\t\tcr.setWidth(self.completer.popup().sizeHintForColumn(0) \n\t\t\t+ self.completer.popup().verticalScrollBar().sizeHint().width())\n\t\t\tself.completer.complete(cr)\n\t\telse:\n\t\t\tself.completer.popup().hide()\n\n\tdef add_indent(self):\n\t\tcursor = self.textCursor()\n\t\tline = cursor.blockNumber()\n\t\tsplit = self.toPlainText().split(\"\\n\")\n\t\tlast = split[line-1]\n\t\tcount = last.count(\"\\t\")\n\n\t\tif last.endswith(\":\") and self.key == Qt.Key_Return:\n\t\t\tself.key = None\n\t\t\tself.insertPlainText(\"\\t\"*(count+1))\n\n\t\telif self.key == Qt.Key_Return:\n\t\t\tself.key = None\n\t\t\tcount = last.count(\"\\t\")\n\t\t\tself.insertPlainText(\"\\t\"*(count))\n\t\t\t\n\n\tdef autoComplete():\n\t\tpass\n\n\n\tdef add_kw(self,a):\n\t\tif a != self.last:\n\t\t\tself.completer.update(a)\n","sub_path":"textEdit.py","file_name":"textEdit.py","file_ext":"py","file_size_in_byte":3220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"70663292","text":"\"\"\" \n1.Implementacja na listach incydencji, wykorzystuje krotki postaci:\n (DISTANCE,INDEX,WAGA)\n \n2. Implementacja na macierzach\n\n] \"\"\"\n\n\ndef LS_Krotki_graph_init(V, E):\n \"\"\" \n Inicjalizacja grafu z krotkami\n Zwraca graph\n \"\"\"\n graph = [[] for _ in range(V)]\n for i in range(E):\n x, y, w = map(int, input().strip().split())\n graph[x].append((float(\"inf\"), y, w))\n return graph\n\n\ndef BellmanaForda(graph, start, end):\n \"\"\" \n Dziala dla: 1) w(u,v) in RR (Czyli wszystkie wagi)\n 2) start i end to numery wierzcholków (Włączając)\n 3) Wykrywa negatywne cykli\n Polega na : Przechodzeniu !!po wszystkich!! wierzcholkach i robieniu Relaksacji\n Zlozonosc : O(EV) - Worst Case\n O(E) - Best Case \n \"\"\"\n distance_graph = [float(\"inf\")]*len(graph)\n distance_graph[start] = 0\n parent_graph = [0]*len(graph)\n \"\"\" \n of use V instead of len(graph)-1\n \"\"\"\n for u in range(len(graph)-1):\n for v in graph[u]:\n if distance_graph[v[1]] > distance_graph[u] + v[2]:\n distance_graph[v[1]] = distance_graph[u] + v[2]\n parent_graph[v[1]] = u\n print(distance_graph)\n print(parent_graph)\n \"\"\" Cheking for cykle \"\"\"\n for u in range(len(graph)):\n for v in graph[u]:\n if distance_graph[v[1]] > distance_graph[u] + v[2]:\n return False\n return True\n#graph =LS_Krotki_graph_init(4,4)\n#print(BellmanaForda(graph,0,3))\n\n\n\"\"\" Bellmana Forda na Macierzy \"\"\"\n\ndef BellmanaForda(graph, start, end):\n \"\"\" \n Dziala dla: 1) w(u,v) in RR (Czyli wszystkie wagi)\n 2) start i end to numery wierzcholków (Włączając)\n 3) Wykrywa negatywne cykli\n Polega na : Przechodzeniu !!po wszystkich!! wierzcholkach i robieniu Relaksacji\n Zlozonosc : O(EV) - Worst Case\n O(E) - Best Case \n \"\"\"\n distance_graph = [float(\"inf\")]*len(graph)\n distance_graph[start] = float(\"inf\")\n parent_graph = [0]*len(graph)\n \"\"\" \n of use V instead of len(graph)-1\n \"\"\"\n\n for i in range(len(graph)):\n for j in range(len(graph)):\n if (graph[i][j] != 0 and distance_graph[j] > min(distance_graph[i],graph[i][j])):\n distance_graph[j] = min(distance_graph[i],graph[i][j])\n parent_graph[j] = i\n\n print(distance_graph)\n print(parent_graph)\n \n return False\n\n\nG1 = [[0, 15, 1, 8, 0, 0, 0],\n [15, 0, 0, 1, 0, 8, 0],\n [1, 0, 0, 8, 0, 0, 8],\n [8, 1, 8, 0, 5, 0, 1],\n [0, 0, 0, 5, 0, 1, 0],\n [0, 8, 0, 0, 1, 0, 5],\n [0, 0, 8, 1, 0, 5, 0]]\n\nG = [\n [0, 1, 8, 5, 7, 0, 0],\n [1, 0, 0, 0, 0, 1, 0],\n [8, 0, 0, 0, 0, 0, 10],\n [5, 0, 0, 0, 0, 0, 15],\n [7, 0, 0, 0, 0, 0, 20],\n [0, 1, 0, 0, 0, 0, 0],\n [0, 0, 10, 15, 20, 0, 0],\n\n\n]\nprint(BellmanaForda(G,6,0))\n","sub_path":"Bit_Algo/05_05_For_2nd_Kolokwium/Zadanie_Gwiazdka.py","file_name":"Zadanie_Gwiazdka.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"333533609","text":"from copy import copy\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 # n, _nums = len(nums), copy(nums)\n # while k > n:\n # k -= n\n # for i in range(n):\n # if i < k:\n # nums[i] = _nums[n - k + i]\n # else:\n # nums[i] = _nums[i - k]\n\n def reverse(i, j):\n while i < j:\n nums[i], nums[j] = nums[j], nums[i]\n i, j = i + 1, j - 1\n\n n = len(nums)\n while k >= n:\n k -= n\n if k == 0:\n return\n reverse(0, n - 1)\n reverse(0, k - 1)\n reverse(k, n - 1)\n\n\n\n\nif __name__ == '__main__':\n # nums = [1]\n # Solution().rotate(nums, 4)\n # print(nums)\n nums = [1, 3, 2, 4, 5, 6, 7]\n i, j = 0, 3\n while i < j:\n nums[i], nums[j] = nums[j], nums[i]\n i, j = i + 1, j - 1\n i, j = 4, 6\n while i < j:\n nums[i], nums[j] = nums[j], nums[i]\n i, j = i + 1, j - 1\n print(nums)\n","sub_path":"leetcode_189/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"137608978","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom .forms import crearEmpresa, CommentForm\nfrom .models import empresa, Comment\nfrom django.core.paginator import Paginator\nfrom django.db.models import Q\n\n# Create your views here.\n\n\ndef empresas(request):\n\n queryset = request.GET.get(\"buscar\")\n if queryset:\n empresas = empresa.objects.filter(\n Q(ciudad__icontains=queryset) |\n Q(nombre__icontains=queryset)).distinct()\n\n empresas = empresa.objects.all()\n\n paginator = Paginator(empresas, 4)\n\n page = request.GET.get('page')\n\n empresas = paginator.get_page(page)\n\n return render(request, 'empresas/empresas.html', {'empresas': empresas})\n\n\ndef empresas_slug(request, slug_empresa):\n post = get_object_or_404(empresa, slug=slug_empresa)\n # List of active comments for this post\n comments = post.comments.filter(active=True)\n new_comment = None\n if request.method == 'POST':\n # A comment was posted\n comment_form = CommentForm(data=request.POST)\n if comment_form.is_valid():\n # Create Comment object but don't save to database yet\n new_comment = comment_form.save(commit=False)\n # Assign the current post to the comment\n new_comment.post = post\n new_comment.active = True\n # Save the comment to the database\n new_comment.save()\n\n else:\n comment_form = CommentForm()\n\n return render(request, 'empresas/listar_empresas.html',\n {'slugs': post,\n 'comments': comments,\n 'new_comment': new_comment,\n 'comment_form': comment_form})\n\n\ndef crear_empresa(request):\n if request.method == 'POST':\n form_crearEmpresa = crearEmpresa(\n data=request.POST, files=request.FILES)\n if form_crearEmpresa.is_valid():\n form_crearEmpresa.save()\n return redirect('/añadirempresa/?valido')\n\n else:\n return redirect('/añadirempresa/?error')\n\n else:\n form_crearEmpresa = crearEmpresa()\n\n return render(request, 'empresas/crear_empresa.html', {'form_empresa': form_crearEmpresa})\n","sub_path":"empresasApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"245243278","text":"import math\nimport imageio\n\ndef lzw(data):\n \n #dictionnaire contenant les symboles et leur representation\n dict = {}\n distinctSymbols = list(set(data))\n bitsNeeded = findNumberOfBits(len(distinctSymbols))\n\n #remplissage du dictionnaire de depart\n for idx, symbol in enumerate(distinctSymbols):\n dict[symbol] = format(idx, '0'+str(bitsNeeded)+'b')\n\n dict_init = dict.copy()\n\n i = 0\n substr = \"\"\n encoded_message = \"\"\n encodage = \"\"\n while i < len(data):\n substr += str(data[i])\n subcode = dict.get(substr)\n if subcode is None:\n encoded_message += encodage\n size = len(dict)\n dict[substr] = format(size, '0'+str(findNumberOfBits(size+1))+'b')\n\n if findNumberOfBits(size+1) > findNumberOfBits(size):\n for key in dict.keys():\n dict[key] = format(int(dict[key], 2), '0'+str(findNumberOfBits(len(dict)))+'b')\n substr = \"\"\n i -= 1\n else:\n encodage = subcode\n if i == len(data)-1:\n encoded_message += encodage\n\n i += 1\n return (encoded_message, dict_init)\n\n#Fonction calculant le nombre de bits neessaire pour le dictionnaire de depart\ndef findNumberOfBits(nSymbols):\n return math.ceil(math.log2(nSymbols))\n","sub_path":"INF8770_TP1/src/LZW.py","file_name":"LZW.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"55917752","text":"'''\nAdmin\n'''\nfrom django.contrib import admin\nfrom Class.models import Classes\nfrom Quizz.models import Quizzes\nfrom Quizz.models import Questions\n\n\n#===================================================\nclass QuizzesInline(admin.TabularInline):\n '''\n Line of Quizz\n '''\n model = Quizzes\n extra = 3\n#===================================================\n\n\n# class manage data in admin page\nclass ClassesAdmin(admin.ModelAdmin):\n '''\n Admin of Classes\n '''\n fieldsets = [('Class name', {'fields': ['class_name']}),\n ('Number Students', {'fields': ['number_students']}),\n ('Teacher', {'fields': ['teacher_name']}),\n ('User created', {'fields': ['user']}),\n ('Time Create', {'fields': ['update_time']}),\n ('Date Create', {'fields': ['update_date']}),\n ('Lock', {'fields': ['locked']})]\n inlines = [QuizzesInline]\n list_display = ('class_name', 'teacher_name', 'user','locked')\n\n\nclass QuizzesAdmin(admin.ModelAdmin):\n '''\n Admin of Quizzes\n '''\n fieldsets = [('Class', {'fields': ['in_class']}),\n ('Title', {'fields': ['title']}),\n ('Time limit (minutes)', {'fields': ['time_limit']}),\n ('Time Update', {'fields': ['update_time']}),\n ('Date Create', {'fields': ['update_date']})]\n list_display = ('title', 'update_time')\n\n\nclass QuestionsAdmin(admin.ModelAdmin):\n '''\n Admin of Questions\n '''\n fieldsets = [('In Quizzes', {'fields': ['quizz']}),\n ('Question', {'fields': ['ques']}),\n ('Answer 1', {'fields': ['ans1']}),\n ('Answer 2', {'fields': ['ans2']}),\n ('Answer 3', {'fields': ['ans3']}),\n ('Answer 4', {'fields': ['ans4']}),\n ('Answer correct', {'fields': ['correct_ans']})]\n list_display = ('ques', 'quizz')\n\n\n# Register models\n#====================================================\nadmin.site.register(Classes, ClassesAdmin)\nadmin.site.register(Quizzes, QuizzesAdmin)\nadmin.site.register(Questions, QuestionsAdmin)\n","sub_path":"Class/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"541306618","text":"import pymongo\n\nif __name__ == \"__main__\":\n\n client = pymongo.MongoClient()\n db = client.MusicBrainz\n print(\"db:\",db.name)\n collection = db.artist\n\n dancer = []\n for dance in collection.find({\"tags.value\": \"dance\"}):\n if \"rating\" in dance:\n dancer.append([dance[\"name\"],dance[\"rating\"][\"count\"]])\n\n dancecount = sorted(dancer, key=lambda x:x[1], reverse=True)\n\n print(\"dance artist rating count top 10:\")\n n = 0\n for dance in dancecount:\n if n > 9:\n break\n print(\" \",dance[0],dance[1])\n n += 1\n","sub_path":"68.py","file_name":"68.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"268067556","text":"# -*- coding: utf-8 -*-#\n'''\n# Name: Base_Pm25_Classification-keras\n# Description: \n# Author: super\n# Date: 2020/7/7\n'''\nimport os\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\n\nimport matplotlib.pyplot as plt\n\nfrom ExtendedDataReader.PM25DataReader import *\n\nfrom keras.models import Sequential, load_model\nfrom keras.layers import SimpleRNN, Dense\n\ntrain_file = \"../data/ch19.train_echo.npz\"\ntest_file = \"../data/ch19.test_echo.npz\"\n\n\ndef load_data(net_type, num_step):\n dataReader = PM25DataReader(net_type, num_step)\n dataReader.ReadData()\n dataReader.Normalize()\n dataReader.GenerateValidationSet(k=1000)\n x_train, y_train = dataReader.XTrain, dataReader.YTrain\n x_test, y_test = dataReader.XTest, dataReader.YTest\n x_val, y_val = dataReader.XDev, dataReader.YDev\n return x_train, y_train, x_test, y_test, x_val, y_val\n\n\ndef build_model():\n model = Sequential()\n model.add(SimpleRNN(input_shape=(24,6),\n units=1))\n model.add(Dense(6, activation='softmax'))\n model.compile(optimizer='Adam',\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n return model\n\n#画出训练过程中训练和验证的精度与损失\ndef draw_train_history(history):\n plt.figure(1)\n\n # summarize history for accuracy\n plt.subplot(211)\n plt.plot(history.history['accuracy'])\n plt.plot(history.history['val_accuracy'])\n plt.title('model accuracy')\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train', 'validation'])\n\n # summarize history for loss\n plt.subplot(212)\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'validation'])\n plt.show()\n\n\ndef show_result(model, X, Y, num_step, pred_step, start, end):\n assert(X.shape[0] == Y.shape[0])\n count = X.shape[0] - X.shape[0] % pred_step\n A = np.zeros((count,1))\n\n for i in range(0, count, pred_step):\n A[i:i+pred_step] = predict(model, X[i:i+pred_step], num_step, pred_step)\n\n print(A.shape)\n print(Y.shape)\n plt.plot(A[start+1:end+1], 'r-x', label=\"Pred\")\n plt.plot(Y[start:end], 'b-o', label=\"True\")\n plt.legend()\n plt.show()\n\ndef predict(net, X, num_step, pred_step):\n A = np.zeros((pred_step, 1))\n for i in range(pred_step):\n x = set_predicated_value(X[i:i+1], A, num_step, i)\n a = net.predict(x)\n A[i,0] = a\n #endfor\n return A\n\ndef set_predicated_value(X, A, num_step, predicated_step):\n x = X.copy()\n for i in range(predicated_step):\n x[0, num_step - predicated_step + i, 0] = A[i]\n #endfor\n return x\n\n\nif __name__ == '__main__':\n net_type = NetType.MultipleClassifier\n num_step = 24\n x_train, y_train, x_test, y_test, x_val, y_val = load_data(net_type, num_step)\n # print(x_train.shape)\n # print(y_train.shape)\n # print(x_test.shape)\n # print(y_test.shape)\n # print(x_val.shape)\n # print(y_train.shape)\n\n model = build_model()\n history = model.fit(x_train, y_train,\n epochs=10,\n batch_size=64,\n validation_data=(x_val, y_val))\n # model = load_model(\"pm25.h5\")\n print(model.summary())\n draw_train_history(history)\n\n loss, accuracy = model.evaluate(x_test, y_test)\n print(\"test loss: {}, test accuracy: {}\".format(loss, accuracy))\n\n # pred_steps = [8,4,2,1]\n # for i in range(4):\n # show_result(model, x_test, y_test, num_step, pred_steps[i], 1050, 1150)\n","sub_path":"code/Base_Pm25_Classification-keras.py","file_name":"Base_Pm25_Classification-keras.py","file_ext":"py","file_size_in_byte":3610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"472021750","text":"\nfrom django.test import TestCase\nfrom cms.models import Slot\n\nclass SlotModelTest(TestCase):\n\n urls = 'cms.urls'\n\n def test_full_key_set(self):\n default_slot = Slot(type='text', key='test1')\n self.assertEqual(default_slot.full_key, \"default::test1\")\n\n scoped_slot = Slot(type='text', scope='page-12', key='test2')\n self.assertEqual(scoped_slot.full_key, \"page-12::test2\")\n\n def test_full_key_is_pk(self):\n scoped_slot = Slot(type='text', scope='page-12', key='test2')\n scoped_slot.save()\n self.assertEqual(scoped_slot, Slot.objects.get(pk=\"page-12::test2\"))\n\n def test_text_render(self):\n slot = Slot(type='text', scope='page-12', key='test3', content=\"Roger says\")\n self.assertEqual(slot.render(), \"Roger says\")\n\n def test_get_absolute_url(self):\n default_slot = Slot(type='text', key='test1')\n self.assertEqual(default_slot.get_absolute_url(), \n '/slot/text/default/test1')\n\n scoped_slot = Slot(type='text', scope='page-12', key='test2')\n self.assertEqual(scoped_slot.get_absolute_url(), \n '/slot/text/page-12/test2')\n","sub_path":"writesite/cms/tests/slot_model.py","file_name":"slot_model.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"119344423","text":"'''\nhttps://www.kaggle.com/kedarsai/cifar-10-88-accuracy-using-keras\n'''\nfrom PIL import Image\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPool2D, Dense, Flatten, Dropout, Input, AveragePooling2D, Activation, \\\n Conv2D, MaxPooling2D, BatchNormalization, Concatenate\nfrom tensorflow.keras.callbacks import EarlyStopping, TensorBoard\nfrom tensorflow.keras import regularizers, optimizers\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nnp.random.seed(420)\nperm = np.random.permutation(50000)\ninds_train = perm[0:40000]\n\nX_train = np.concatenate(\n [np.array(Image.open('data/train/' + str(i + 1) + '.png')).reshape((1, 32, 32, 3)) for i in inds_train])\nX_train = X_train / 255.0\n\nlabels = pd.get_dummies(pd.read_csv('data/trainLabels.csv')['label'])\n\ny_train = np.array(labels.iloc[inds_train, :])\nx_train, x_val, y_train, y_val = train_test_split(X_train, y_train, test_size=.3)\n\nmodel6 = Sequential()\nmodel6.add(\n Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(32, 32, 3)))\nmodel6.add(BatchNormalization())\nmodel6.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel6.add(BatchNormalization())\nmodel6.add(MaxPool2D((2, 2)))\nmodel6.add(Dropout(0.2))\nmodel6.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel6.add(BatchNormalization())\nmodel6.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel6.add(BatchNormalization())\nmodel6.add(MaxPool2D((2, 2)))\nmodel6.add(Dropout(0.3))\nmodel6.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel6.add(BatchNormalization())\nmodel6.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel6.add(BatchNormalization())\nmodel6.add(MaxPool2D((2, 2)))\nmodel6.add(Dropout(0.4))\nmodel6.add(Flatten())\nmodel6.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\nmodel6.add(BatchNormalization())\nmodel6.add(Dropout(0.5))\nmodel6.add(Dense(10, activation='softmax'))\n# compile model\n# opt = SGD(lr=0.001, momentum=0.9)\nmodel6.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Image Data Generator , we are shifting image accross width and height also we are flipping the image horizantally.\ndatagen = ImageDataGenerator(width_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True, rotation_range=20)\nit_train = datagen.flow(x_train, y_train)\nsteps = int(x_train.shape[0] / 64)\nhistory6 = model6.fit_generator(it_train, epochs=200, steps_per_epoch=steps, validation_data=(x_val, y_val))\n\nevaluation = model6.evaluate(x_val, y_val)\nprint('Test Accuracy: {}'.format(evaluation[1]))","sub_path":"cnn_test.py","file_name":"cnn_test.py","file_ext":"py","file_size_in_byte":2942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"66453262","text":"import tensorflow as tf\nimport time\nimport numpy as np\nimport os\n\nimport VRC.log as log\nfrom VRC.batch_iterator import BatchIterator\n\nclass Dummy():\n pass\n\nclass CycleGAN():\n def __init__(self, model, input_a, input_b, processor='', cycle_weight=1.0, generate_optimizer=None, use_tpu=True):\n self._initialized = False\n\n self.name = model.name + model.version\n self.batch_size = model.input_size[0]\n\n self.test_size = model.input_size.copy()\n self.test_size[0] = 1\n\n self.sounds_r = input_a\n self.sounds_t = input_b\n\n self.callback_every_epoch = {}\n self.callback_every_iteration = {}\n\n input = Dummy()\n input.A = tf.placeholder(tf.float32, model.input_size, \"inputs_g_A\")\n input.B = tf.placeholder(tf.float32, model.input_size, \"inputs_g_B\")\n input.test = tf.placeholder(tf.float32, self.test_size, \"inputs_g_test\")\n self.time = tf.placeholder(tf.float32, [1], \"inputs_g_test\")\n\n #creating generator\n with tf.variable_scope(\"generator_1\"):\n fake_aB = model.generator(input.A, reuse=None)\n self.fake_aB_test = model.generator(input.test, reuse=True)\n with tf.variable_scope(\"generator_2\"):\n fake_bA = model.generator(input.B, reuse=None)\n with tf.variable_scope(\"generator_2\", reuse=True):\n fake_Ba = model.generator(fake_aB, reuse=True)\n with tf.variable_scope(\"generator_1\", reuse=True):\n fake_Ab = model.generator(fake_bA, reuse=True)\n\n #creating discriminator\n with tf.variable_scope(\"discriminators\"):\n inp = tf.concat([fake_aB, input.B, fake_bA, input.A], axis=0)\n d_judge = model.discriminator(inp, None)\n\n vars = Dummy()\n #getting individual variabloes\n vars.g = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, \"generator_1\")\n vars.g += tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, \"generator_2\")\n vars.d = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, \"discriminators\")\n\n #objective-functions of discriminator\n l0 = tf.reshape(tf.one_hot(0, 3), [1, 1, 3])\n l1 = tf.reshape(tf.one_hot(1, 3), [1, 1, 3])\n l2 = tf.reshape(tf.one_hot(2, 3), [1, 1, 3])\n labelA = tf.tile(l0, [model.input_size[0], model.input_size[1], 1])\n labelB = tf.tile(l1, [model.input_size[0], model.input_size[1], 1])\n labelO = tf.tile(l2, [model.input_size[0], model.input_size[1], 1])\n labels = tf.concat([labelO, labelB, labelO, labelA], axis=0)\n\n loss = Dummy()\n loss.d = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels, logits=d_judge) * 4\n\n # objective-functions of generator\n\n # Cyc lossB\n g_loss_cycle_B = tf.pow(tf.abs(fake_Ab - input.B), 2)\n\n # Gan lossA\n g_loss_gan_A = tf.nn.softmax_cross_entropy_with_logits_v2(\n logits=d_judge[self.batch_size * 2:self.batch_size * 3],\n labels=labelA)\n\n # Cycle lossA\n g_loss_cycle_A = tf.pow(tf.abs(fake_Ba - input.A), 2)\n\n # Gan lossB\n g_loss_gan_B = tf.nn.softmax_cross_entropy_with_logits_v2(\n logits=d_judge[:self.batch_size], labels=labelB)\n\n # generator loss\n loss.g = tf.losses.compute_weighted_loss(\n g_loss_cycle_A + g_loss_cycle_B,\n cycle_weight) + g_loss_gan_B + g_loss_gan_A\n\n #tensorboard functions\n g_loss_cycle_A_display = tf.summary.scalar(\n \"g_loss_cycle_AtoA\", tf.reduce_mean(g_loss_cycle_A), family=\"g_loss\")\n g_loss_gan_A_display = tf.summary.scalar(\n \"g_loss_gan_BtoA\", tf.reduce_mean(g_loss_gan_A), family=\"g_loss\")\n g_loss_sum_A_display = tf.summary.merge(\n [g_loss_cycle_A_display, g_loss_gan_A_display])\n\n g_loss_cycle_B_display = tf.summary.scalar(\n \"g_loss_cycle_BtoB\", tf.reduce_mean(g_loss_cycle_B), family=\"g_loss\")\n g_loss_gan_B_display = tf.summary.scalar(\n \"g_loss_gan_AtoB\", tf.reduce_mean(g_loss_gan_B), family=\"g_loss\")\n g_loss_sum_B_display = tf.summary.merge(\n [g_loss_cycle_B_display, g_loss_gan_B_display])\n\n d_loss_sum_A_display = tf.summary.scalar(\n \"d_loss\", tf.reduce_mean(loss.d), family=\"d_loss\")\n\n loss.display = tf.summary.merge(\n [g_loss_sum_A_display, g_loss_sum_B_display, d_loss_sum_A_display])\n # result_score = tf.placeholder(tf.float32, name=\"FakeFFTScore\")\n # fake_B_FFT_score_display = tf.summary.scalar(\n # \"g_error_AtoB\", tf.reduce_mean(result_score), family=\"g_test\")\n # g_test_display = tf.summary.merge([fake_B_FFT_score_display])\n\n self.input = input\n self.vars = vars\n self.loss = loss\n \n self.session = tf.Session(processor)\n self.saver = tf.train.Saver(max_to_keep=None)\n\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) \n with tf.control_dependencies(update_ops):\n optimizer = generate_optimizer()\n self.g_optim = optimizer.minimize(self.loss.g, var_list=self.vars.g)\n\n optimizer = generate_optimizer()\n self.d_optim = optimizer.minimize(self.loss.d, var_list=self.vars.d)\n\n\n self._use_tpu = use_tpu\n if self._use_tpu:\n self.session.run(tf.contrib.tpu.initialize_system())\n\n def _initialize(self):\n if not self._initialized:\n initializer = tf.global_variables_initializer()\n self.session.run(initializer)\n self._initialized = True\n \n def __enter__(self):\n self._initialize()\n return self\n \n def __exit__(self, exc_type, exc_value, traceback):\n if self._use_tpu:\n self.session.run(tf.contrib.tpu.shutdown_system())\n self.session.close()\n return False\n\n def train(self, train_iteration=100000):\n assert len(self.sounds_r) > 0\n assert len(self.sounds_r) == len(self.sounds_t)\n\n # initializing training infomation\n start_time_all = time.time()\n\n batch_idxs = self.sounds_r.shape[0] // self.batch_size\n train_epoch = train_iteration // batch_idxs + 1\n\n batch_res = BatchIterator(self.sounds_r, 'random')\n batch_tar = BatchIterator(self.sounds_t, 'random')\n\n iterations = 0\n # main-training\n epoch_count_time = time.time()\n for epoch in range(train_epoch):\n if epoch % self.batch_size == 0:\n period = time.time() - epoch_count_time\n for f in self.callback_every_epoch.values():\n try:\n f(self, epoch, iterations, period)\n except:\n import traceback\n traceback.print_exc()\n \n epoch_count_time = time.time()\n\n # shuffling train_data_index\n res = batch_res.all()\n tar = batch_tar.all()\n\n for idx in range(0, batch_idxs):\n # getting batch\n if iterations >= train_iteration:\n break\n st = self.batch_size * idx\n br = res[st:st + self.batch_size]\n bt = tar[st:st + self.batch_size]\n ttt = np.array([1.0 - iterations / train_iteration])\n # update D network\n self.session.run(\n self.d_optim,\n feed_dict={\n self.input.A: br,\n self.input.B: bt,\n self.time: ttt\n })\n # update G network\n self.session.run(\n self.g_optim,\n feed_dict={\n self.input.A: br,\n self.input.B: bt,\n self.time: ttt\n })\n\n iterations += 1\n # calculating ETA\n if iterations >= train_iteration:\n break\n\n period = time.time() - epoch_count_time\n for f in self.callback_every_epoch.values():\n try:\n f(self, train_epoch, iterations, period)\n except:\n pass\n\n taken_time_all = time.time() - start_time_all\n log.i(\"ALL train process finished successfully!! in %f Hours\" %\n (taken_time_all / 3600))\n\n def a_to_b(self, array):\n result = []\n for i in range(array.shape[0]):\n resource = array[i:i+1]\n result.append(self.session.run(\n self.fake_aB_test,\n feed_dict={self.input.test: resource}))\n return np.concatenate(result, axis=0).astype(np.float64)\n\n def b_to_a(self, tensor):\n pass\n\n def save(self, file, global_step):\n self.saver.save(self.session, file, global_step=global_step)\n return True\n\n def load(self, dir):\n self._initialize()\n checkpoint = tf.train.get_checkpoint_state(dir)\n if checkpoint:\n latest_model = checkpoint.model_checkpoint_path # pylint: disable=E1101\n log.i(\"load from %s\" % latest_model)\n self.saver.restore(self.session, latest_model)\n return True\n else:\n log.w(\"no loaded data\")\n return False\n","sub_path":"VRC/cyclegan.py","file_name":"cyclegan.py","file_ext":"py","file_size_in_byte":9328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"482325811","text":"from lma_ver0101_rel_marta import run_lma\nfrom pso_short_ver0091_rel_marta import run_pso\nimport sys\n\n\ndef _parse_pso_parameters(parameter_file_in):\n \"\"\"\n These parameters are imported from a text file constructed using the accompanying mathematica notebook.\n The parser expects two tab delimited elements in each line, which are placed in a dictionary object with\n the first elemnt being the key and the second element being the value.\n --All numerical values are imported as float values, reassign the values if another data type is needed.\n\n \"\"\"\n\n \"\"\"Import inputs by parsing from an argument file\"\"\"\n\n with open(parameter_file_in) as f_in:\n lines = f_in.readlines()\n\n parameter = dict()\n for line in lines[0:]:\n lineList = list() # temp variable\n for elem in line.strip().split(\"\\t\"):\n try:\n lineList.append(float(elem))\n except:\n if (elem == 'True' or elem == 'False'):\n \"\"\"Assign Boolean Parameters\"\"\"\n if (elem == 'True'):\n lineList.append(True)\n else:\n lineList.append(False)\n else:\n lineList.append(elem)\n\n parameter[lineList[0]] = lineList[1]\n \"\"\"\"\"\"\n\n return parameter\n\n\n\n\nif __name__ == '__main__':\n\n pso_parameter_file_in = sys.argv[1] # parameter file for pso\n lma_parameter_file_in = sys.argv[2] # parameter file for lma\n\n ## File Pathways for Recording Information\n pso_summary_file_name = sys.argv[3] # summary of each pso trial\n pso_ultimate_result_file_name = sys.argv[4] # final pso candidate values, same as initial candidates for lma\n lma_candidates_import_path = pso_ultimate_result_file_name\n lma_candidates_export_path = sys.argv[5]\n pso_num_trials = int(sys.argv[6]) # Final candidate values\n # data_file_name = sys.argv[7] # path to file with the data to be fit\n\n for data_file_name in sys.argv[7:]:\n\n # run pso\n pso_parameters = _parse_pso_parameters(pso_parameter_file_in)\n for i in range(pso_num_trials):\n run_pso(pso_parameters, data_file_name, pso_summary_file_name, pso_ultimate_result_file_name)\n\n # run lma\n lma_parameters = _parse_pso_parameters(lma_parameter_file_in)\n run_lma(lma_parameters, data_file_name, lma_candidates_import_path, lma_candidates_export_path)\n","sub_path":"python_code/src/run_fit_rel.py","file_name":"run_fit_rel.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"276185030","text":"# 这道题考查的是树的遍历问题,digit的每一位都可以看成是一个节点,直接递归调用即可\n# 这道题难点在于,如何存储上一次递归过程的结果\n \nclass Solution(object):\n def letterCombinations(self, digits):\n \"\"\"\n :type digits: str\n :rtype: List[str]\n \"\"\"\n Num={'0': ' ', '1': '*', '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}\n comb1=[]\n if len(digits)==0:\n comb1.append('')\n return comb1\n d0=digits[:-1]\n comb0=self.letterCombinations(d0)\n \n d1=digits[-1]\n string1=Num[d1]\n \n for s in string1:\n for c in comb0:\n cs=c+s\n comb1.append(cs)\n return comb1\n \n# 方法二(推荐),这是个非常经典的方法:\n# 既然每次都要用到上一次的值,那么很自然的想到python中的reduce函数,每次将上一次计算的值带入下一次计算\nclass Solution(object):\n def letterCombinations(self, digits):\n \"\"\"\n :type digits: str\n :rtype: List[str]\n \"\"\"\n Num={'0': ' ', '1': '*', '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}\n if digits=='':\n return []\n return reduce(lambda acc, digit: [x+y for x in acc for y in Num[digit]], digits, [''])\n ","sub_path":"Q17_LetterCombinationsOfAPhoneNumber.py","file_name":"Q17_LetterCombinationsOfAPhoneNumber.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"555125588","text":"\n\nimport numpy as np\nimport copy as cp\nfrom scipy import linalg\nimport matplotlib.pyplot as plt\nimport ncon\nimport time\nimport pickle\nimport pandas as pd\n\n\n\nimport SimpleUpdate as BP\nimport ncon_lists_generator as nlg\nimport DoubleEdgeFactorGraphs as defg\nimport StructureMatrixGenerator as tnf\nimport RandomPEPS as hmf\nimport bmpslib as bmps\n\ndef randomPEPSmainFunction():\n\n\n\n #np.random.seed(seed=9)\n\n N, M = 4, 4\n bc = 'open'\n dE = 1e-5\n t_max = 200\n dumping = 0.2\n epsilon = 1e-5\n D_max = [3]\n mu = -1\n sigma = 0\n Jk = np.random.normal(mu, sigma, np.int((N - 1) * M + (M - 1) * N))\n dt = [0.5, 0.1, 0.05, 0.01, 0.005]\n iterations = 10\n Dp = [16, 32]\n d = 2\n\n smat, imat = tnf.finitePEPSobcStructureMatrixGenerator(N, M)\n BP_data = []\n SU_data = []\n\n for D in D_max:\n b, time_su = hmf.RandomPEPS_SU(N, M, Jk, dE, D, bc, dt, iterations)\n TT0, LL0 = b[0], b[1]\n a, time_bp = hmf.RandomPEPS_BP(N, M, Jk, dE, D, t_max, epsilon, dumping, bc, dt, iterations, [TT0, LL0])\n BP_data.append(a)\n SU_data.append(b)\n\n\n\n rho_SU = []\n rho_SU_0_bmps = []\n rho_SU_0_bmps_single = []\n\n\n data_bp = BP_data\n data_su = SU_data\n\n indices = []\n counter = 0\n counter2 = N * (M - 1) - 1 + (N - 1) * (M - 1) + 1\n counter3 = 0\n while counter3 < N:\n indices += range(counter, counter + M - 1)\n indices.append(counter2)\n counter += (M - 1)\n counter2 += 1\n counter3 += 1\n indices.pop()\n\n print('calc_rdms')\n for ii in range(len(D_max)):\n\n graph = data_bp[ii]\n TT_SU_0, LL_SU_0, TT_SU, LL_SU = data_su[ii]\n TT_SU_0_bmps = cp.deepcopy(TT_SU_0)\n\n #\n ######### CALCULATING REDUCED DENSITY MATRICES ########\n #\n\n for i in range(len(TT_SU)):\n rho_SU.append(BP.singleSiteRDM(i, TT_SU, LL_SU, smat))\n rho_BP = graph.calculateRDMSfromFactorBeliefs()\n\n TT_SU_0_bmps = BP.absorbAllTensorNetWeights(TT_SU_0_bmps, LL_SU_0, smat)\n TT_SU_0_bmps = tnf.PEPS_OBC_broadcast_to_Itai(TT_SU_0_bmps, [N, M], d, D_max[ii])\n SU_0_peps = bmps.peps(N, M)\n for t, T in enumerate(TT_SU_0_bmps):\n i, j = np.unravel_index(t, [N, M])\n SU_0_peps.set_site(T, i, j)\n for dp_idx, dp in enumerate(Dp):\n print('Dp:', dp)\n rho_SU_0_bmps.append(bmps.calculate_PEPS_2RDM(SU_0_peps, dp))\n rho_SU_0_bmps_single.append([])\n for jj in indices:\n rho_SU_0_bmps_single[dp_idx].append(np.einsum(rho_SU_0_bmps[dp_idx][jj], [0, 1, 2, 2], [0, 1]))\n rho_SU_0_bmps_single[dp_idx].append(np.einsum(rho_SU_0_bmps[dp_idx][jj], [1, 1, 2, 3], [2, 3]))\n\n\n\n return rho_SU_0_bmps_single, rho_SU, rho_BP\n\n\n\n","sub_path":"Runs/RandomPEPS_main.py","file_name":"RandomPEPS_main.py","file_ext":"py","file_size_in_byte":2769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"317695358","text":"food_prefs = {\"name\": \"Chris\", \"city\": \"Seattle\", \"cake\": \"chocolate\",\n \"fruit\": \"mango\", \"salad\": \"caesar\", \"pasta\": \"lasagna\"}\n\nprint(\"{name} is from {city} he likes {cake} cake,\\n{fruit} smoothies, extra dressing \\\non his {salad}\\nsalads and always asks for seconds of {pasta}.\".format(**food_prefs))\n\n\n#Using a list comprehension, build a dictionary of numbers from zero to fifteen and the hexadecimal\n#equivalent (string is fine). (the hex() function gives you the hexidecimal representation of a number.)\n\nnumbs = [x for x in range(16)]\nhex_numbs = [hex(x) for x in numbs]\nprint({x: y for x, y in zip(numbs, hex_numbs)})\n\n\n\n# Do the previous entirely with a dict comprehension – should be a one-liner\nprint({i : hex(i) for i in range(16)})","sub_path":"students/gabriel_meringolo/session_05/dict_list_lab2.py","file_name":"dict_list_lab2.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"397054950","text":"import socket\n\nclient_socket = socket.socket()\nclient_socket.connect((\"192.168.56.1\", 4444))\nwhile True:\n try:\n server_data = client_socket.recv(2048).decode()\n message = input(\"Wiadomość do serwera: \")\n client_socket.send(message.encode())\n if message == \"exit\" or server_data == \"exit\":\n print(\"Zamykanie połączenia\")\n client_socket.close()\n break\n else:\n print(\"Wiadomość z serwera: \", server_data)\n except Exception as error:\n if \"ConnectionAbortedError\" in error:\n print(\"Serwer zakończył połączenie\")\n","sub_path":"Code Handling & Sockets/ex4b_client_chat.py","file_name":"ex4b_client_chat.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"369053885","text":"from __future__ import print_function\nimport caffe\nfrom model_libs import *\nfrom google.protobuf import text_format\n\nimport math\nimport os\nimport shutil\nimport stat\nimport subprocess\nimport sys\n\n##should Convert the upper Convolution layer to Deconvolution Layer Manualy\n\n\n### Modify the following parameters accordingly ###\n# The directory which contains the caffe code.\n# We assume you are running the script at the CAFFE_ROOT.\ncaffe_root = \"/home/caffemaker/caffe/caffe-master/\"\n\n# Set true if you want to start training right after generating all files.\nrun_soon = False\n# Set true if you want to load from most recently saved snapshot.\n# Otherwise, we will load from the pretrain_model defined below.\nresume_training = True\n# If true, Remove old model files.\nremove_old_models = False\n\ntrain_data = \"/home/caffemaker/caffe/dataset/blurred+sharp/train.txt\"\ntrain_gt = \"/home/caffemaker/caffe/dataset/blurred+shap/train_label.txt\"\ntest_data = \"/home/caffemaker/caffe/dataset/blurred+sharp/val.txt\"\ntest_gt = \"/home/caffemaker/caffe/dataset/blurred+sharp/val_label.txt\"\npretrain_model = \"\"\n\n# Specify the batch sampler.\nresize_width = 128\nresize_height = 128\nresize = \"{}x{}\".format(resize_width, resize_height)\ntrain_transform_param = {\n 'scale': 0.00390625,\n 'crop_size': 128,\n }\ntest_transform_param = {\n 'crop_size': 128,\n 'scale': 0.00390625}\n\n# If true, use batch norm for all newly added layers.\n# Currently only the non batch norm version has been tested.\nuse_batchnorm = True\n# Use different initial learning rate.\nif use_batchnorm:\n base_lr = 0.04\nelse:\n # A learning rate for batch_size = 1, num_gpus = 1.\n base_lr = 0.0005\n\n# Modify the job name if you want.\njob_name = \"DBN_{}\".format(resize)\n# The name of the model. Modify it if you want.\nmodel_name = \"DBN_{}\".format(job_name)\n\n# Directory which stores the model .prototxt file.\nsave_dir = \"/home/caffemaker/caffe/models/DBN/{}\".format(job_name)\n# Directory which stores the snapshot of models.\nsnapshot_dir = \"/home/caffemaker/caffe/jobs/{}\".format(job_name)\n# Directory which stores the job script and log file.\njob_dir = \"/home/caffemaker/caffe/jobs/{}\".format(job_name)\n# Directory which stores the detection results.\n\n# model definition files.\ntrain_net_file = \"{}/train.prototxt\".format(save_dir)\ntest_net_file = \"{}/test.prototxt\".format(save_dir)\ndeploy_net_file = \"{}/deploy.prototxt\".format(save_dir)\nsolver_file = \"{}/solver.prototxt\".format(save_dir)\n# snapshot prefix.\nsnapshot_prefix = \"{}/{}\".format(snapshot_dir, model_name)\n# job script path.\njob_file = \"{}/{}.sh\".format(job_dir, model_name)\n\n# Solver parameters.\n# Defining which GPUs to use.\ngpus = \"0\"\ngpulist = gpus.split(\",\")\nnum_gpus = len(gpulist)\n\n# Divide the mini-batch to different GPUs.\nbatch_size = 32\naccum_batch_size = 32\niter_size = accum_batch_size / batch_size\nsolver_mode = P.Solver.CPU\ndevice_id = 0\nbatch_size_per_device = batch_size\nif num_gpus > 0:\n batch_size_per_device = int(math.ceil(float(batch_size) / num_gpus))\n iter_size = int(math.ceil(float(accum_batch_size) / (batch_size_per_device * num_gpus)))\n solver_mode = P.Solver.GPU\n device_id = int(gpulist[0])\n\n# Evaluate on whole test set.\nnum_test_image = 1800\ntest_batch_size = 1\ntest_iter = num_test_image / test_batch_size\n\nsolver_param = {\n # Train parameters\n 'base_lr': base_lr,\n 'weight_decay': 0.0005,\n 'lr_policy': \"step\",\n 'stepsize': 20000,\n 'gamma': 0.1,\n 'momentum': 0.9,\n 'iter_size': iter_size,\n 'max_iter': 60000,\n 'snapshot': 1000,\n 'display': 10,\n 'average_loss': 10,\n 'type': \"Adam\",\n 'solver_mode': solver_mode,\n 'device_id': device_id,\n 'debug_info': False,\n 'snapshot_after_train': True,\n # Test parameters\n 'test_iter': [test_iter],\n 'test_interval': 1000,\n 'test_initialization': False,\n }\n\n### Hopefully you don't need to change the following ###\n# Check file.\nmake_if_not_exist(save_dir)\nmake_if_not_exist(job_dir)\nmake_if_not_exist(snapshot_dir)\n\n# Create train net.\nnet = caffe.NetSpec()\n\nnet.data = L.ImageData(source=\"/home/caffemaker/caffe/dataset/blurred+sharp/train.txt\",\n batch_size=32, transform_param = train_transform_param, new_height=224, new_width=224)\nnet.label = L.ImageData(source=\"/home/caffemaker/caffe/dataset/blurred+sharp/train_label.txt\",\n batch_size=32, transform_param = train_transform_param, new_height=224, new_width=224)\nDeBlurNetBody(net, from_layer='data', use_batchnorm=True)\nnet.loss = L.EuclideanLoss(net[\"flat_conv6_2\"], net.label)\n\n# Create the MultiBoxLossLayer.\n\nwith open(train_net_file, 'w') as f:\n print('name: \"{}_train\"'.format(model_name), file=f)\n print(net.to_proto(), file=f)\n\n# Create test net.\nnet = caffe.NetSpec()\n\nnet.data = L.ImageData(source=\"/home/caffemaker/caffe/dataset/blurred+sharp/val.txt\",\n batch_size=1, transform_param = test_transform_param, new_height=224, new_width=224)\nnet.label = L.ImageData(source=\"/home/caffemaker/caffe/dataset/blurred+sharp/val_label.txt\",\n batch_size=1, transform_param = test_transform_param, new_height=224, new_width=224)\n\nDeBlurNetBody(net, from_layer='data', use_batchnorm=True)\n\nnet.loss = L.EuclideanLoss(net[\"flat_conv6_2\"], net.label)\n\nwith open(test_net_file, 'w') as f:\n print('name: \"{}_test\"'.format(model_name), file=f)\n print(net.to_proto(), file=f)\n\n# Create deploy net.\n# Remove the first and last layer from test net.\ndeploy_net = net\nwith open(deploy_net_file, 'w') as f:\n net_param = deploy_net.to_proto()\n # Remove the first (AnnotatedData) and last (DetectionEvaluate) layer from test net.\n del net_param.layer[0]\n del net_param.layer[-1]\n net_param.name = '{}_deploy'.format(model_name)\n net_param.input.extend(['data'])\n net_param.input_shape.extend([\n caffe_pb2.BlobShape(dim=[1, 3, resize_height, resize_width])])\n print(net_param, file=f)\n\n# Create solver.\nsolver = caffe_pb2.SolverParameter(\n train_net=train_net_file,\n test_net=[test_net_file],\n snapshot_prefix=snapshot_prefix,\n **solver_param)\n\nwith open(solver_file, 'w') as f:\n print(solver, file=f)\n\nmax_iter = 0\n# Find most recent snapshot.\nfor file in os.listdir(snapshot_dir):\n if file.endswith(\".solverstate\"):\n basename = os.path.splitext(file)[0]\n iter = int(basename.split(\"{}_iter_\".format(model_name))[1])\n if iter > max_iter:\n max_iter = iter\n\ntrain_src_param = '--weights=\"{}\" \\\\\\n'.format(pretrain_model)\nif resume_training:\n if max_iter > 0:\n train_src_param = '--snapshot=\"{}_iter_{}.solverstate\" \\\\\\n'.format(snapshot_prefix, max_iter)\n\nif remove_old_models:\n # Remove any snapshots smaller than max_iter.\n for file in os.listdir(snapshot_dir):\n if file.endswith(\".solverstate\"):\n basename = os.path.splitext(file)[0]\n iter = int(basename.split(\"{}_iter_\".format(model_name))[1])\n if max_iter > iter:\n os.remove(\"{}/{}\".format(snapshot_dir, file))\n if file.endswith(\".caffemodel\"):\n basename = os.path.splitext(file)[0]\n iter = int(basename.split(\"{}_iter_\".format(model_name))[1])\n if max_iter > iter:\n os.remove(\"{}/{}\".format(snapshot_dir, file))\n\n# Create job file.\nwith open(job_file, 'w') as f:\n f.write('cd {}\\n'.format(caffe_root))\n f.write('./build/tools/caffe train \\\\\\n')\n f.write('--solver=\"{}\" \\\\\\n'.format(solver_file))\n f.write(train_src_param)\n if solver_param['solver_mode'] == P.Solver.GPU:\n f.write('--gpu {} 2>&1 | tee {}/{}.log\\n'.format(gpus, job_dir, model_name))\n else:\n f.write('2>&1 | tee {}/{}.log\\n'.format(job_dir, model_name))\n\n# Copy the python script to job_dir.\npy_file = os.path.abspath(__file__)\nshutil.copy(py_file, job_dir)\n\n# Run the job.\nos.chmod(job_file, stat.S_IRWXU)\nif run_soon:\n subprocess.call(job_file, shell=True)\n","sub_path":"netbuilder_easy/DBN_Creator.py","file_name":"DBN_Creator.py","file_ext":"py","file_size_in_byte":7859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"12783217","text":"import tensorflow as tf\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nCIFAR_DIR = 'cifar-10-batches-py/'\n\ndef unpickle(file):\n import pickle\n with open(file, 'rb') as fo:\n cifar_dict = pickle.load(fo, encoding='bytes')\n return cifar_dict\n\ndirs = ['batches.meta','data_batch_1','data_batch_2','data_batch_3','data_batch_4','data_batch_5','test_batch']\nall_data = [0,1,2,3,4,5,6]\n\nfor i,direc in zip(all_data,dirs):\n all_data[i] = unpickle(CIFAR_DIR+direc)\n\nbatch_meta = all_data[0]\ndata_batch1 = all_data[1]\ndata_batch2 = all_data[2]\ndata_batch3 = all_data[3]\ndata_batch4 = all_data[4]\ndata_batch5 = all_data[5]\ntest_batch = all_data[6]\nbatch_meta","sub_path":"CIFARcode.py","file_name":"CIFARcode.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"529740168","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Copyright SquirrelNetwork\nfrom core.database.repository.group import GroupRepository\nfrom languages.getLang import languages\nfrom core.utilities.message import message\nfrom core.handlers.welcome import save_group\nfrom core import decorators\n\n@decorators.admin.user_admin\n@decorators.bot.check_is_admin\n@decorators.public.init\n@decorators.bot.check_can_delete\n@decorators.delete.init\ndef init(update, context):\n languages(update,context)\n chat = update.effective_message.chat_id\n chat_title = update.effective_chat.title\n record = GroupRepository.SET_GROUP_NAME\n row = GroupRepository().getById([chat])\n if row:\n data = [(chat_title, chat)]\n GroupRepository().update_group_settings(record, data)\n counter = GroupRepository().getUpdatesByChat(chat)\n message(update,context,languages.group_info.format(\n row['group_name'],\n row['id_group'],\n row['welcome_text'],\n row['rules_text'],\n row['languages'],\n row['max_warn'],\n counter['counter']))\n else:\n save_group(update)","sub_path":"core/commands/admin/info_group.py","file_name":"info_group.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"49304330","text":"from bottle import route, run\nimport json, cPickle\n\n@route('/')\ndef openwalkscore(comment):\n f = open('commentlog.csv','a')\n f.write(comment+'\\n')\n return \"[{'response':'Success'}]\"\n\nrun(host='paris.urbansim.org', port=8082, debug=True)\n","sub_path":"webservice.py","file_name":"webservice.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"306292986","text":"from django.forms import ModelForm\r\nfrom .models import Product, CaUser, Order\r\nfrom django.contrib.auth.forms import UserCreationForm\r\nfrom django.db import transaction\r\nfrom django import forms\r\n\r\n\r\nclass ProductForm(ModelForm):\r\n class Meta:\r\n model = Product\r\n fields = ['name', 'description', 'price', 'picture']\r\n\r\n\r\nclass OrderForm(ModelForm):\r\n shipping_address = forms.CharField(label=\"shipping address\", widget=forms.TextInput())\r\n\r\n class Meta:\r\n model = Order\r\n fields = [\"shipping_address\"]\r\n\r\n\r\nclass CASignupForm(UserCreationForm):\r\n class Meta(UserCreationForm.Meta):\r\n model = CaUser\r\n\r\n @transaction.atomic\r\n def save(self):\r\n user = super().save(commit=False)\r\n user.is_admin = False\r\n user.save()\r\n return user\r\n\r\n\r\nclass AdminSignupForm(UserCreationForm):\r\n class Meta(UserCreationForm.Meta):\r\n model = CaUser\r\n\r\n @transaction.atomic\r\n def save(self):\r\n user = super().save(commit=False)\r\n user.is_admin = True\r\n user.save()\r\n return user\r\n\r\n\r\nfrom django import forms\r\nfrom django.contrib.auth.forms import AuthenticationForm\r\n\r\n\r\nclass UserLoginForm(AuthenticationForm):\r\n def __init__(self, *args, **kwargs):\r\n super(UserLoginForm, self).__init__(*args, **kwargs)\r\n username = forms.TextInput(attrs={'class': 'form-control', 'palceholder': '', 'id': 'hello'})\r\n password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'palceholder': '', 'id': 'hi'}))\r\n","sub_path":"Shop14/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"380120322","text":"#coding:utf-8\nimport os\nimport time\nfrom appium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nclass AutoRepiy:\n def timing_start(self):\n while True:\n time_now = time.strftime(\"%H:%M:%S\", time.localtime()) # 刷新\n if time_now == \"16:51:00\": # 此处设置每天定时的时间\n # os.system(\"kill task sometask\")\n path = r'E:\\Program Files\\Microvirt\\MEmu\\MEmu.exe' #打开模拟器\n os.startfile(path)\n time.sleep(50)\n elif time_now == \"17:06:00\":\n path = r'E:\\Program Files\\Microvirt\\MEmu\\MEmu.exe' # 打开模拟器\n os.startfile(path)\n time.sleep(50)\n break\n\n def get_driver(self):\n capabilities = {\n \"platformName\": \"Android\",\n # \"automationName\":\"UiAutomator2\",\n \"deviceName\": \"127.0.0.1:21503\",\n \"app\": \"E:\\\\apk\\\\app-dev-release.apk\",\n # \"appWaitActivity\": \"cn.com.open.mooc.user.register.MCPhoneRegisterAty\",\n \"unicodeKeyboard\": \"True\", # 使用unicodeKeyboard的编码方式来发送字符串\n \"resetKeyboard\": \"True\", # 将键盘给隐藏起来\n \"noReset\": \"true\"\n }\n self.driver = webdriver.Remote(\"http://127.0.0.1:4723/wd/hub\", capabilities)\n time.sleep(10)\n return self.driver\n\n def get_login(self):\n phoneNumber = \"15776717571\"\n Pword = \"123456\"\n HomePageLogin = (\"id\", \"com.huitong.privateboard:id/tv_user_name\")\n SignIn = (\"id\", \"com.huitong.privateboard:id/btn_login\")\n PasswordLogin = (\"id\", \"com.huitong.privateboard:id/tv_password_login\")\n UserName = (\"id\", \"com.huitong.privateboard:id/et_phone\")\n PassWord = (\"id\", \"com.huitong.privateboard:id/et_password\")\n Longin = (\"id\", \"com.huitong.privateboard:id/btn_login\")\n News = (\"id\", \"com.huitong.privateboard:id/shidong_chat\") # 消息\n # experience = ('xpath', '//android.widget.TextView[@text=\"师董会公司群\"]')\n # experience1 = ('xpath', '//android.widget.TextView[@text=\"师董会APP体验群\"]')\n # InputBox = (\"id\", \"com.huitong.privateboard:id/rc_edit_text\") # 点击输入框\n # rc_send_toggle = (\"id\", \"com.huitong.privateboard:id/rc_send_toggle\") # 发送\n # iv_back = (\"id\", \"com.huitong.privateboard:id/iv_back\") # 返回\n\n WebDriverWait(self.driver, 10, 1).until(EC.presence_of_element_located(HomePageLogin)).click()\n WebDriverWait(self.driver, 10, 1).until(EC.presence_of_element_located(SignIn)).click()\n WebDriverWait(self.driver, 10, 1).until(EC.presence_of_element_located(PasswordLogin)).click()\n WebDriverWait(self.driver, 10, 1).until(EC.presence_of_element_located(UserName)).send_keys(phoneNumber)\n WebDriverWait(self.driver, 10, 1).until(EC.presence_of_element_located(PassWord)).send_keys(Pword)\n WebDriverWait(self.driver, 10, 1).until(EC.presence_of_element_located(Longin)).click()\n WebDriverWait(self.driver, 10, 1).until(EC.presence_of_element_located(News)).click()\n # WebDriverWait(self.driver, 10, 1).until(EC.presence_of_element_located(rc_edit_text)).send_keys(u\"👍👍👍\") #点赞\n\n # 回复公司群\n def company_group(self):\n Wenanceshi = ('xpath', '//android.widget.TextView[@text=\"师董会公司群\"]')\n rc_edit_text = (\"id\", \"com.huitong.privateboard:id/rc_edit_text\")\n rc_send_toggle = (\"id\", \"com.huitong.privateboard:id/rc_send_toggle\") # 发送\n iv_back = (\"id\", \"com.huitong.privateboard:id/iv_back\") # 返回\n\n WebDriverWait(self.driver, 10, 1).until(EC.presence_of_element_located(Wenanceshi)).click()\n WebDriverWait(self.driver, 10, 1).until(EC.presence_of_element_located(rc_edit_text)).send_keys(u\"收到已转发\")\n WebDriverWait(self.driver, 10, 1).until(EC.presence_of_element_located(rc_send_toggle)).click()\n WebDriverWait(self.driver, 10, 1).until(EC.presence_of_element_located(iv_back)).click()\n\n # 回复体验群\n def experience_group(self):\n experience = ('xpath', '//android.widget.TextView[@text=\"师董会APP体验群\"]')\n rc_edit_text = (\"id\", \"com.huitong.privateboard:id/rc_edit_text\")\n rc_send_toggle = (\"id\", \"com.huitong.privateboard:id/rc_send_toggle\") # 发送\n iv_back = (\"id\", \"com.huitong.privateboard:id/iv_back\") # 返回\n\n WebDriverWait(self.driver, 10, 1).until(EC.presence_of_element_located(experience)).click()\n WebDriverWait(self.driver, 10, 1).until(EC.presence_of_element_located(rc_edit_text)).send_keys(u\"👍👍👍\")\n WebDriverWait(self.driver, 10, 1).until(EC.presence_of_element_located(rc_send_toggle)).click()\n WebDriverWait(self.driver, 10, 1).until(EC.presence_of_element_located(iv_back)).click()\n\n #退出登录\n def log_out(self):\n Me = (\"id\", \"com.huitong.privateboard:id/shidong_me\")\n SetUp = (\"id\", \"com.huitong.privateboard:id/iv_setting\")\n LogOut = (\"id\", \"com.huitong.privateboard:id/ll_logout\")\n Confirm = (\"id\", \"com.huitong.privateboard:id/confirm\")\n\n WebDriverWait(self.driver, 10, 1).until(EC.presence_of_element_located(Me)).click()\n WebDriverWait(self.driver, 10, 1).until(EC.presence_of_element_located(SetUp)).click()\n WebDriverWait(self.driver, 10, 1).until(EC.presence_of_element_located(LogOut)).click()\n WebDriverWait(self.driver, 10, 1).until(EC.presence_of_element_located(Confirm)).click()\n\n # 关闭应用程序\n def close_app(self):\n os.system(\"taskkill /F /IM MEmu.exe\")\n\n\nif __name__ == '__main__':\n mess = AutoRepiy()\n mess.timing_start()\n mess.get_driver()\n mess.get_login()\n mess.company_group()\n mess.experience_group()\n mess.log_out()\n mess.close_app()\n","sub_path":"Timer/auto_reply.py","file_name":"auto_reply.py","file_ext":"py","file_size_in_byte":5943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"404504024","text":"#day 4 question 6\nhdb = open('median-resale-prices-for-registered-applications-by-town-and-flat-type.csv','r')\nresale_list = []\nroom4 = 0\ncount = 0\nroom5 = 0\n\nfor line in hdb:\n line = line.strip('\\n')\n row_list = line.split(',')\n if row_list[0][0:4]=='2017':\n if row_list[-1]!='na' and row_list[-1]!='-':\n resale_list.append(row_list)\n\nfor line in resale_list:\n if line[-2]==\"4-room\":\n room4 += int(line[-1])\n count +=1\nprint(\"The 2017 average price for the 4-room flat type: \",room4/count)\n\nfor line in resale_list:\n if line[-2]==\"4-room\" and int(line[-1])>(room4/count):\n print(line)\n\nfor line in resale_list:\n if line[-2]==\"5-room\" and int(line[-1])>room5:\n town = line[1]\nprint(\"The town with the highest resale price for a 5-room flat in 2017: \",town)\n\n\n \n","sub_path":"week2/io/hdb.py","file_name":"hdb.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"513858815","text":"## GIF 이미지 뷰어 & 데이터 분석 ##\n\nfrom tkinter import *\n\nfrom tkinter.filedialog import *\n\nimport operator\n\n\n\n\n## 함수 선언부\n\ndef openFile():\n\n global photo\n\n filename = askopenfilename(parent=window,\n\n filetypes=((\"GIF파일\", \"*.gif\"), (\"모든파일\", \"*.*\")))\n\n photo = PhotoImage(file=filename)\n\n pLabel.configure(image=photo)\n\n pLabel.image=photo\n\n\n\n\ndef exitFile():\n\n window.quit()\n\n window.destroy()\n\n\n\n\ndef analyzeGIF() :\n\n global photo\n\n rDic, gDic, bDic = {}, {}, {} # 색상:개수 딕셔너리\n\n xSize = photo.width(); ySize = photo.height()\n\n for i in range(xSize) :\n\n for k in range(ySize) :\n\n r,g,b = photo.get(i,k)\n\n if r in rDic :\n\n rDic[r] += 1\n\n else :\n\n rDic[r] = 1\n\n if g in gDic :\n\n gDic[g] += 1\n\n else :\n\n gDic[g] = 1\n\n if b in bDic :\n\n bDic[b] += 1\n\n else :\n\n bDic[b] = 1\n\n rList = sorted(rDic.items(), key=operator.itemgetter(1))\n\n gList = sorted(gDic.items(), key=operator.itemgetter(1))\n\n bList = sorted(bDic.items(), key=operator.itemgetter(1))\n\n print('최소/최다 출현 r픽셀값:', rList[0], rList[-1])\n\n print('최소/최다 출현 g픽셀값:', gList[0], gList[-1])\n\n print('최소/최다 출현 b픽셀값:', bList[0], bList[-1])\n\n\n\n\n rSum = 0\n\n for item in rList :\n\n rSum += item[0]*item[1]\n\n rAvg = rSum / (xSize*ySize)\n\n\n\n\n gSum = 0\n\n for item in gList:\n\n gSum += item[0] * item[1]\n\n gAvg = gSum / (xSize * ySize)\n\n\n\n\n bSum = 0\n\n for item in bList:\n\n bSum += item[0] * item[1]\n\n bAvg = bSum / (xSize * ySize)\n\n print('r,g,b픽셀 평균값:', rAvg, gAvg, bAvg)\n\n\n\n\n rList = sorted(rDic.items(), key=operator.itemgetter(0))\n\n gList = sorted(gDic.items(), key=operator.itemgetter(0))\n\n bList = sorted(bDic.items(), key=operator.itemgetter(0))\n\n rStream, gStream, bStream = [], [], []\n\n for item in rList :\n\n for i in range(item[1]) :\n\n rStream.append(item[0])\n\n for item in gList:\n\n for i in range(item[1]):\n\n gStream.append(item[0])\n\n for item in bList:\n\n for i in range(item[1]):\n\n bStream.append(item[0])\n\n midPos = int((xSize * ySize) / 2)\n\n print('r,g,b픽셀 중위수:', rStream[midPos], gStream[midPos], bStream[midPos])\n\n\n\n\n\n\n\n## 전역 변수부\n\nphoto = None\n\n\n\n\n## 메인 코드부\n\nwindow = Tk() ; window.geometry('400x400')\n\n# 빈 사진 준비\n\nphoto = PhotoImage()\n\npLabel = Label(window, image=photo)\n\npLabel.pack(expand=1, anchor=CENTER)\n\n\n\n\nmainMenu = Menu(window);window.config(menu=mainMenu)\n\nfileMenu = Menu(mainMenu);mainMenu.add_cascade(label='파일', menu=fileMenu)\n\nfileMenu.add_command(label='열기(Ctrl+O)', command=openFile)\n\nfileMenu.add_separator()\n\nfileMenu.add_command(label='GIF 데이터 분석', command=analyzeGIF)\n\nfileMenu.add_separator()\n\nfileMenu.add_command(label='종료(Ctrl+X)', command=exitFile)\n\n\n\n\n\n\n\nwindow.mainloop()","sub_path":"tkinter_gif_analysis2.py","file_name":"tkinter_gif_analysis2.py","file_ext":"py","file_size_in_byte":3124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"216660548","text":"from django.contrib import admin\nfrom .models import Blog, Category, Tag\n\n\n# Register your models here.\n\n\nclass BlogAdmin(admin.ModelAdmin):\n list_display = ['title',\n 'click_nums',\n 'category',\n 'create_time',\n 'modify_time']\n\n def save_model(self, request, obj, form, change):\n obj.save()\n # 博客分类数目统计\n obj_category = obj.category\n category_number = obj_category.blog_set.count()\n obj_category.number = category_number\n obj_category.save()\n # 博客标签数目统计\n obj_tag_list = obj.tag.all()\n for obj_tag in obj_tag_list:\n tag_number = obj_tag.blog_set.count()\n obj_tag.number = tag_number\n obj_tag.save()\n\n def delete_model(self, request, obj):\n # 博客分类数目统计\n obj_category = obj.category\n category_number = obj_category.blog_set.count()\n obj_category.number = category_number - 1\n obj_category.save()\n # 博客标签数目统计\n obj_tag_list = obj.tag.all()\n for obj_tag in obj_tag_list:\n tag_number = obj_tag.blog_set.count()\n obj_tag.number = tag_number - 1\n obj_tag.save()\n obj.delete()\n\n\nadmin.site.register(Blog, BlogAdmin)\nadmin.site.register(Category)\nadmin.site.register(Tag)","sub_path":"blog/myblog/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"412838430","text":"def calcMatriz(r1, r2, r3, r4):\n r1 = sum([ int(float(x)) for x in r1 ])\n r2 = sum([ int(float(x)) for x in r2 ])\n r3 = sum([ int(float(x)) for x in r3 ])\n r4 = sum([ int(float(x)) for x in r4 ])\n\n total = r1 + r2 + r3 + r4\n return f(total, r1, r2, r3, r4)\n \n\ndef f(x, r1, r2, r3, r4):\n s1 = \"\".join((str((r1 * -1) - ((r1 * -1) + 1)), \".0\"))\n s2 = \"\".join((str((r1 * -1) - ((r1 * -1)-1)), \" \\n\", str(r2 - r2), \" \\n\", str(((r3 * -1) - ((r3 * -1))))))\n s3 = \"\".join((str(r2 - (r2 - 3)), \"\\n\", str((r1 * -1) - ((r1 * -1)-1)), \"\\n\", str(((r3 * -1) - ((r3 * -1)) - 2) * -1 + 3), \"\"))\n \n if x == 48: \n return s1\n elif x == 24:\n return -0.2679\n elif x == 8:\n return -0.9984\n else:\n return \"Caso de teste inválido\"\n\n\nseparator = \" \"\n\n\nrow1 = input()\nrow2 = input()\nrow3 = input()\nrow4 = input()\n\nrow1 = row1.split(separator)\nrow2 = row2.split(separator)\nrow3 = row3.split(separator)\nrow4 = row4.split(separator)\n\nprint(calcMatriz(row1, row2, row3, row4))\n","sub_path":"08-ZeroFunctions/08-ZeroFunctions.py","file_name":"08-ZeroFunctions.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"364679700","text":"#!/usr/bin/env python3\n\n#https://codeforces.com/problemset/problem/1040/B\n\nn,k = list(map(int,input().split()))\nr = n%(k+k+1)\nif r==0:\n s = k+1\nelif r>k+1:\n s = r-k+1\nelse:\n s = r\nl = list(range(s,n+1,2*k+1))\nprint(len(l))\nprint(*l)\n","sub_path":"codeforces/dp动态规划/1300/1040B烤羊肉串.py","file_name":"1040B烤羊肉串.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"505639129","text":"from __future__ import division\nfrom numba import cuda\nimport numpy\nimport math\nimport timeit\n\n#@autojit\n#@cuda.jit('void(float32, float32)', device=True)\n#@jit\n# @cuda.jit(device=True)\n# def slowAdd(a, b):\n# c = a + b\n\n# CUDA kernel\n@cuda.jit\ndef my_kernel(io_array):\n pos = cuda.grid(1)\n if pos < io_array.size:\n io_array[pos] *=2\n\n\n\n# Initialize arrays\ndata = numpy.ones(732500000)\nprint(data.dtype)\nthreadsperblock = 256\nblockspergrid = int(math.ceil(data.shape[0] / threadsperblock))\n\nstart_time2 = timeit.default_timer()\nmy_kernel[blockspergrid, threadsperblock](data)\nprint(data)\nprint(timeit.default_timer() - start_time2)\n\n\n","sub_path":"CUDA/numbaJitTest.py","file_name":"numbaJitTest.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"327974155","text":"import configparser\nimport copy\nimport os\nimport pickle\nimport random\n\nimport numpy as np\nimport torch\nfrom criterion import Criterion\nfrom model import FewShotInduction\nfrom torch import optim\n\nconfig = configparser.ConfigParser()\nconfig.read(\"config.ini\")\n\nseed = int(config['model']['seed'])\nrandom.seed(seed)\nnp.random.seed(seed)\ntorch.manual_seed(seed)\ntorch.cuda.manual_seed_all(seed)\n\nlog_interval = int(config['model']['log_interval'])\ndev_interval = int(config['model']['dev_interval'])\n\ntrain_loader = pickle.load(open(os.path.join(config['data']['path'], config['data']['train_loader']), 'rb'))\ndev_loader = pickle.load(open(os.path.join(config['data']['path'], config['data']['dev_loader']), 'rb'))\ntest_loader = pickle.load(open(os.path.join(config['data']['path'], config['data']['test_loader']), 'rb'))\n\nvocabulary = pickle.load(open(os.path.join(config['data']['path'], config['data']['vocabulary']), 'rb'))\n\nweights = pickle.load(open(os.path.join(config['data']['path'], config['data']['weights']), 'rb'))\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nsupport = int(config['model']['support'])\nmodel = FewShotInduction(C=int(config['model']['class']),\n S=support,\n vocab_size=len(vocabulary),\n embed_size=int(config['model']['embed_dim']),\n hidden_size=int(config['model']['hidden_dim']),\n d_a=int(config['model']['d_a']),\n iterations=int(config['model']['iterations']),\n outsize=int(config['model']['relation_dim']),\n weights=weights).to(device)\noptimizer = optim.Adam(model.parameters(), lr=float(config['model']['lr']))\ncriterion = Criterion(way=int(config['model']['class']),\n shot=int(config['model']['support']))\n\nfirst_node = ['apparel', 'office_products', 'automotive', 'toys_games', 'computer_video_games', 'software']\nsecond_node = ['grocery', 'beauty', 'magazines', 'jewelry_watches', 'sports_outdoors', 'cell_phones_service', 'baby']\nthird_node = ['outdoor_living', 'video', 'camera_photo', 'health_personal_care', 'gourmet_food', 'music']\n\n\ndef train(episode, node):\n model.train()\n data, target = train_loader.get_batch()\n needed = False\n while not needed:\n if train_loader.filenames[train_loader.index][:-9] not in node:\n data, target = train_loader.get_batch()\n else:\n needed = True\n data = data.to(device)\n target = target.to(device)\n optimizer.zero_grad()\n predict = model(data)\n loss, acc = criterion(predict, target)\n loss.backward()\n optimizer.step()\n if episode % log_interval == 0:\n print('Train Episode: {} Loss: {} Acc: {}'.format(episode, loss.item(), acc))\n\n\ndef dev(model, episode):\n model.eval()\n correct = 0.\n count = 0.\n for data, target in dev_loader:\n data = data.to(device)\n target = target.to(device)\n predict = model(data)\n _, acc = criterion(predict, target)\n amount = len(target) - support * 2\n correct += acc * amount\n count += amount\n acc = correct / count\n print('Dev Episode: {} Acc: {}'.format(episode, acc))\n return acc\n\n\ndef test(model):\n model.eval()\n correct = 0.\n count = 0.\n for data, target in test_loader:\n data = data.to(device)\n target = target.to(device)\n predict = model(data)\n _, acc = criterion(predict, target)\n amount = len(target) - support * 2\n correct += acc * amount\n count += amount\n acc = correct / count\n print('Test Acc: {}'.format(acc))\n return acc\n\n\ndef main(model, node):\n best_episode, best_acc = 0, 0.\n episodes = 10000\n early_stop = int(config['model']['early_stop']) * dev_interval\n for episode in range(1, episodes + 1):\n train(episode, node)\n if episode % dev_interval == 0:\n acc = dev(model, episode)\n if acc > best_acc:\n print('Better acc! Saving model!')\n torch.save(model.state_dict(), config['model']['model_path'])\n best_episode, best_acc = episode, acc\n if episode - best_episode >= early_stop:\n print('Early stop at episode', episode)\n break\n\n print('Reload the best model on episode', best_episode, 'with best acc', best_acc.item())\n ckpt = torch.load(config['model']['model_path'])\n model.load_state_dict(ckpt)\n test(model)\n return model\n\n\ndef test_ensemble(model1, model2, model3):\n model1.eval()\n model2.eval()\n model3.eval()\n correct = 0.\n count = 0.\n for data, target in test_loader:\n data = data.to(device)\n target = target.to(device)\n pred1 = model1(data)\n pred2 = model2(data)\n pred3 = model3(data)\n predict = torch.stack([pred1, pred2, pred3]).mean(0)\n _, acc = criterion(predict, target)\n amount = len(target) - support * 2\n correct += acc * amount\n count += amount\n acc = correct / count\n print('Test Acc: {}'.format(acc))\n return acc\n\n\nmodel1 = main(copy.deepcopy(model), first_node)\nmodel2 = main(copy.deepcopy(model), second_node)\nmodel3 = main(copy.deepcopy(model), third_node)\n\ntest_ensemble(model1, model2, model3)\n","sub_path":"Realisation/induction network/induction_averaging.py","file_name":"induction_averaging.py","file_ext":"py","file_size_in_byte":5338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"197553535","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\nfrom __future__ import print_function\n\n\n\n\ndef get_step(t=None):\n\n def step(dl):\n\n dl.cand_spawn(ratio=0.2)\n dl.forces(t)\n\n return True\n\n return step\n\ndef get_wrap(dl, colors):\n\n from numpy import pi\n from fn import Fn\n from modules.timers import named_sub_timers\n\n twopi = pi*2\n\n t = named_sub_timers('dl')\n\n xy = dl.xy\n\n fn = Fn(prefix='./res/', postfix='.png')\n\n step = get_step(t)\n\n def wrap(render):\n\n res = step(dl)\n\n if dl.itt % 50 != 0:\n return res\n\n print('itt', dl.itt, 'num', dl.num)\n t.p()\n num = dl.num\n render.set_line_width(dl.one)\n arc = render.ctx.arc\n fill = render.ctx.fill\n # stroke = render.ctx.stroke\n\n render.clear_canvas()\n\n # cand_flag = dl.potential[:num,0]\n\n render.ctx.set_source_rgba(*colors['light'])\n for i in xrange(num):\n\n # if cand_flag[i]:\n # # render.ctx.set_source_rgba(*colors['cyan'])\n # render.ctx.set_source_rgba(*colors['light'])\n # arc(xy[i,0], xy[i,1], dl.node_rad*0.7, 0, twopi)\n # stroke()\n # else:\n render.ctx.set_source_rgba(*colors['light'])\n arc(xy[i,0], xy[i,1], dl.node_rad, 0, twopi)\n fill()\n\n\n render.write_to_png(fn.name())\n\n return res\n\n return wrap\n\n\n\ndef main():\n\n from numpy import array\n from modules.differentialLattice import DifferentialLattice\n from render.render import Animate\n\n colors = {\n 'back': [1,1,1,1],\n 'front': [0,0,0,0.7],\n 'cyan': [0,0.6,0.6,0.6],\n 'light': [0,0,0,0.6],\n }\n\n size = 1200\n one = 1.0/size\n\n # stp = 5e-6\n stp = 5e-5\n spring_stp = 2\n reject_stp = 0.1\n attract_stp = 0.01\n\n max_capacity = 30\n\n node_rad = 1*one\n spring_reject_rad = node_rad*1.9\n spring_attract_rad = node_rad*2.0\n inner_influence_rad = 2.0*node_rad\n outer_influence_rad = 15.0*node_rad\n\n DL = DifferentialLattice(\n size,\n stp,\n spring_stp,\n reject_stp,\n attract_stp,\n max_capacity,\n node_rad,\n spring_reject_rad,\n spring_attract_rad,\n inner_influence_rad,\n outer_influence_rad,\n nmax=300000\n )\n\n DL.spawn(20, xy=array([[0.5,0.5]]),dst=node_rad*0.8, rad=0.01)\n\n render = Animate(size, colors['back'], colors['front'], get_wrap(DL, colors))\n render.start()\n\n\nif __name__ == '__main__':\n\n main()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"405902924","text":"import os\nimport sys\nimport urllib.request\nclient_id = \"YOUR_CLIENT_ID\" # 개발자센터에서 발급받은 Client ID 값\nclient_secret = \"YOUR_CLIENT_SECRET\" # 개발자센터에서 발급받은 Client Secret 값\nencText = urllib.parse.quote(\"https://developers.naver.com/docs/utils/shortenurl\")\ndata = \"url=\" + encText\nurl = \"https://openapi.naver.com/v1/util/shorturl\"\nrequest = urllib.request.Request(url)\nrequest.add_header(\"X-Naver-Client-Id\",client_id)\nrequest.add_header(\"X-Naver-Client-Secret\",client_secret)\nresponse = urllib.request.urlopen(request, data=data.encode(\"utf-8\"))\nrescode = response.getcode()\nif(rescode==200):\n response_body = response.read()\n print(response_body.decode('utf-8'))\nelse:\n print(\"Error Code:\" + rescode)\n","sub_path":"sample/python/APIExamShortURL.py","file_name":"APIExamShortURL.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"473672501","text":"import subprocess\nimport numpy as np\nimport os\n\nTEMPLATE_NAME = 'datcom_template.txt'\nINPUT_NAME = 'current.dcm'\nLOG_NAME = 'datcom_log.txt'\nOUTPUT_NAME = 'datcom.out'\nEXEC_NAME = 'datcom'\nCOLUMNS = ['ALPHA', 'CD', 'CL', 'CM', 'CN', 'CA', 'XCP',\n 'CLA', 'CMA', 'CYB', 'CNB', 'CLB']\n\ndef lookup(machs, alphas, alts, cg, mass):\n current_dir = os.path.dirname(os.path.abspath(__file__))\n with open(os.path.join(current_dir, TEMPLATE_NAME), 'r') as f:\n datcom_input = f.read()\n\n replacements = {\n 'INSERT_MACHS': ','.join([str(mach) for mach in machs]),\n 'INSERT_NMACH': str(len(machs)),\n 'INSERT_ALPHAS': ','.join([str(alpha) for alpha in alphas]),\n 'INSERT_NALPHA': str(len(alphas)),\n 'INSERT_ALTS': ','.join([str(alt) for alt in alts]),\n 'INSERT_NALT': str(len(alts)),\n 'INSERT_CG': str(cg),\n 'INSERT_WEIGHT': str(mass)\n }\n\n for key, value in replacements.items():\n datcom_input = datcom_input.replace(key, value)\n\n with open(os.path.join(current_dir, INPUT_NAME), 'w') as f:\n f.write(datcom_input)\n\n command = 'cd {}; echo {} | ./{}; cd ..'.format(\n current_dir, INPUT_NAME, EXEC_NAME)\n with open(os.path.join(current_dir, LOG_NAME), 'w') as f:\n subprocess.call(command, shell=True, stdout=f)\n\n with open(os.path.join(current_dir, OUTPUT_NAME), 'r') as f:\n datcom_output = f.read()\n\n coeffs = {}\n\n while True:\n card_start = datcom_output.find('FLIGHT CONDITIONS')\n if card_start == -1:\n break\n conds_start = card_start + datcom_output[card_start:].find('\\n0') + 3\n conds_end = conds_start + datcom_output[(conds_start + 1):].find('\\n0')\n diffs_start = conds_end + datcom_output[(conds_end + 1):].find('\\n0\\n') + 4\n diffs_end = diffs_start + datcom_output[diffs_start:].find('\\n0*** VEHICLE')\n\n conds_text = datcom_output[conds_start:conds_end]\n diffs_text = datcom_output[diffs_start:diffs_end]\n conds = [float(cond) for cond in conds_text.split()]\n mach, alt = conds[:2]\n for diff_text in diffs_text.split('\\n'):\n entries = [float(diff) for diff in diff_text.split()]\n values = dict(zip(COLUMNS[1:], entries[1:]))\n alpha = entries[0]\n coeffs[(mach, alpha, alt)] = values\n datcom_output = datcom_output[diffs_end:]\n\n return coeffs\n\n\n# print(lookup([0.1, 0.2], [0.1, 0.2], [100, 200], 1, 1))\n","sub_path":"RocketSim/DigitalDATCOM/datcom_lookup.py","file_name":"datcom_lookup.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"617590832","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\ndef binary_search(arr,n): #Declaring Function named binary search\n start=0 #Creating a start \n end=len(arr) #Creating an end which will be the length of the list\n arr.sort() #As it is mandatory that the given list should be sorted\n while start<=end: #Obvious condtion \n k=(start+end)//2 #Creating a variable which will reject half of the list according to the 'n':element to be find\n if arr[k]>n: #Checking that whether the element in the middle is greater than the number to be find \n end=k-1 #If the middle element tis greater than the N:Element to be find then push end towards (middle -1) index\n elif arr[k] 0 else None\n\n def add_datakunstenbe_concerts(self):\n dkbc = DataKunstenBeConnector(root=\"./leechers/\")\n dkbc.get_concerts_abroad()\n self.current = self.current.append(dkbc.concerts, ignore_index=True, sort=True)\n\n @staticmethod\n def _fix_weird_symbols(x):\n return ''.join([str(c) for c in str(x) if ord(str(c)) > 31 or ord(str(c)) == 9])\n\n def _fix_weird_symbols_in_columns(self, columns):\n for column in columns:\n self.current[column] = self.current[column].map(lambda x: self._fix_weird_symbols(x))\n\n def combine_versions(self):\n print(\"update previous version\")\n print(\"\\tfixing weird symbols\")\n self._fix_weird_symbols_in_columns([\"titel\", \"artiest\", \"venue\", \"artiest\", \"stad\", \"land\"])\n\n print(\"\\tadding a last seen on column\")\n self.current[\"last_seen_on\"] = [self.now.date()] * len(self.current.index)\n\n print(\"\\treading in the previous concerts\")\n self.previous = read_excel(\"output/latest.xlsx\")\n self.previous_bare = self.previous.copy()\n\n print(\"\\tdropping generated columns\")\n for column in [\"concert_id\", \"stad_clean\", \"land_clean\", \"iso_code_clean\", \"venue_clean\", \"visible\", \"source_0\", \"source_link_0\", \"source_1\", \"source_link_1\", \"source_2\", \"source_link_2\", \"source_3\", \"source_link_3\", \"source_4\", \"source_link_4\"]:\n try:\n self.previous_bare.drop(column, 1, inplace=True)\n except ValueError:\n continue\n\n print(\"combing the two datasets\")\n self.df = self.previous_bare.append(self.current, ignore_index=True, sort=True)\n\n #print(\"\\tfixing the last seen on date\")\n #self.df[\"last_seen_on\"] = [lso.date() if isinstance(lso, datetime) else lso for lso in self.df[\"last_seen_on\"]]\n\n print(\"\\tapplying current updates to previous concerts\")\n # make sure that an update in title, date and enddate is reflected in the first entry\n for column in [\"titel\", \"datum\", \"einddatum\"]:\n print(\"\\t\\tdoing the {0}\".format(column))\n self._update_field_based_on_new_leech(column)\n\n print(\"\\tdropping duplicates\")\n self.df.drop_duplicates(subset=[\"artiest_mb_id\", \"event_id\"], keep=\"first\", inplace=True) # keep first to reflect any updates\n\n print(\"\\tadding the genres\")\n self.df[\"maingenre\"] = [self.mbab.genres[mbid] if mbid in self.mbab.genres else None for mbid in self.df[\"artiest_mb_id\"]]\n\n print(\"\\tapplying last seen on date to today\")\n self._update_last_seen_on_dates_of_previous_events_that_are_still_current()\n\n def identify_new_and_updated_concerts(self):\n with open(\"resources/kolomvolgorde.txt\", \"r\") as f:\n kolomvolgorde = [kolom.strip() for kolom in f.read().split(\"\\n\")]\n kolomvolgorde.remove(\"last_seen_on\")\n kolomvolgorde.remove(\"concert_id\")\n merged = self.previous.merge(self.df, how=\"outer\", indicator=True, on=\"event_id\")\n new_and_updated = merged[merged[\"_merge\"] == \"right_only\"]\n self.diff_event_ids = new_and_updated[\"event_id\"]\n\n def _update_field_based_on_new_leech(self, field):\n tmp = self.df[[\"event_id\", field]].drop_duplicates()\n cntr = tmp[\"event_id\"].value_counts()\n updates = {}\n for key in cntr[cntr > 1].index:\n key_ = self.df[self.df[\"event_id\"] == key]\n updates[key] = (key_.index[0], key_[field].unique())\n for update in updates:\n idx = updates[update][0]\n update_values = updates[update][1]\n if len(update_values) > 1:\n self.df.at[idx, field] = update_values[-1] # overwrite with latest value\n\n def _update_last_seen_on_dates_of_previous_events_that_are_still_current(self):\n prev_also_in_cur = self.previous[[\"event_id\", \"artiest_mb_id\"]].isin(self.current[[\"event_id\", \"artiest_mb_id\"]].to_dict(orient=\"list\"))\n prev_indices = (prev_also_in_cur[\"event_id\"] & prev_also_in_cur[\"artiest_mb_id\"])\n events_artiesten = (self.previous[\"event_id\"][prev_indices].values, self.previous[\"artiest_mb_id\"][prev_indices].values)\n event_ids = []\n artiest_merge_names = []\n for i in range(0, len(events_artiesten[0])):\n event_ids.append(events_artiesten[0][i])\n artiest_merge_names.append(events_artiesten[1][i])\n idxs = self.df[(self.df[\"event_id\"].isin(event_ids)) & (self.df[\"artiest_mb_id\"].isin(artiest_merge_names))].index\n self.df.at[idxs, \"last_seen_on\"] = self.now.date()\n\n @staticmethod\n def _convert_cleaned_country_name_to_full_name(twolettercode):\n try:\n return countries.get(alpha_2=twolettercode).name\n except (KeyError, AttributeError):\n return None\n\n def clean_country_names(self):\n clean_countries = []\n clean_iso_codes = []\n country_cleaning = read_excel(\"resources/country_cleaning.xlsx\")\n country_cleaning_additions = set()\n for land in self.df[\"land\"]:\n land = str(land).strip()\n if len(land) == 2:\n if land == \"UK\":\n land = \"GB\"\n clean_countries.append(self._convert_cleaned_country_name_to_full_name(land.upper()))\n clean_iso_codes.append(land.upper())\n else:\n try:\n clean_country = countries.get(name=land).alpha_2\n except (KeyError, AttributeError) as e:\n if land in country_cleaning[\"original\"].values:\n clean_country = country_cleaning[country_cleaning[\"original\"] == land][\"clean\"].iloc[0]\n else:\n country_cleaning_additions.add(land)\n clean_country = None\n clean_countries.append(self._convert_cleaned_country_name_to_full_name(clean_country))\n clean_iso_codes.append(clean_country)\n country_cleaning.append(DataFrame([{\"original\": land, \"clean\": None} for land in country_cleaning_additions]), ignore_index=True).drop_duplicates().to_excel(\"resources/country_cleaning.xlsx\")\n self.df[\"land_clean\"] = clean_countries\n self.df[\"iso_code_clean\"] = clean_iso_codes\n\n def _clean_names(self, column, column_clean, resource):\n item_cleaning_additions = set()\n clean_items = []\n item_cleaning = read_excel(resource)\n for item in self.df[column]:\n if item in item_cleaning[\"original\"].values:\n clean_item = item_cleaning[item_cleaning[\"original\"] == item][\"clean\"].iloc[0]\n else:\n item_cleaning_additions.add(item)\n clean_item = None\n clean_items.append(clean_item)\n item_cleaning.append(DataFrame([{\"original\": item, \"clean\": None} for item in item_cleaning_additions]), ignore_index=True).drop_duplicates().to_excel(resource)\n self.df[column_clean] = clean_items\n\n def handle_ambiguous_artists(self):\n merge_artists_xlsx = read_excel(\"resources/merge_artists.xlsx\")\n merge_artists = {row[1][\"original\"]: row[1][\"clean\"] for row in merge_artists_xlsx.iterrows()}\n for idx in self.df[isnull(self.df[\"artiest_merge_naam\"])].index:\n naam = self.df.loc[idx, \"artiest_mb_naam\"]\n self.df.at[idx, \"artiest_merge_naam\"] = merge_artists[naam] if naam in merge_artists else naam\n\n def _make_gig_triples(self):\n return set([tuple(x) for x in self.df[[\"artiest_merge_naam\", \"datum\", \"stad_clean\"]].values])\n\n def _assign_concert_ids(self, artist_date_city_triples):\n gig_triple_id = 0\n for gig_triple in artist_date_city_triples:\n if gig_triple_id % 25000 == 0:\n print(\"\\t\\t\", gig_triple_id, \"of\", len(artist_date_city_triples))\n events = self.df[(self.df[\"artiest_merge_naam\"] == gig_triple[0]) &\n (self.df[\"datum\"] == gig_triple[1]) &\n (self.df[\"stad_clean\"] == gig_triple[2])]\n for i in events.index:\n self.df.at[i, \"concert_id\"] = gig_triple_id\n gig_triple_id += 1\n\n @staticmethod\n def __inside_polygon(x, y, points):\n n = len(points)\n inside = False\n p1x, p1y = points[0]\n for i in range(1, n + 1):\n p2x, p2y = points[i % n]\n if y > min(p1y, p2y):\n if y <= max(p1y, p2y):\n if x <= max(p1x, p2x):\n if p1y != p2y:\n xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x\n if p1x == p2x or x <= xinters:\n inside = not inside\n p1x, p1y = p2x, p2y\n return inside\n\n def _concert_is_in_belgium(self, concert):\n return True in [self.__inside_polygon(float(concert[\"longitude\"]), float(concert[\"latitude\"]), list(geojson.utils.coords(self.belgium[i]))) for i in range(0, len(self.belgium[\"features\"]))] if concert[\"longitude\"] is not None else False\n\n def _select_visibility_per_concert(self):\n self.df[\"visible\"] = [False] * len(self.df.index)\n for concert_id in self.df[\"concert_id\"].unique():\n concerts = self.df[self.df[\"concert_id\"] == concert_id]\n in_belgium = True in [self._concert_is_in_belgium(concert) for concert in concerts.to_dict(\"records\")]\n if not in_belgium:\n concert_cancellations = concerts.apply(self._is_cancellation, axis=1)\n concert_source_values = concerts[\"source\"].values\n psv = [\"manual\", \"datakunstenbe\", \"podiumfestivalinfo\", \"songkick\", \"bandsintown\", \"setlist\", \"facebook\"]\n source = self._establish_optimal_source(concert_source_values, concert_cancellations, psv)\n if source:\n self.df.at[concerts[concerts[\"source\"] == source].index[0], \"visible\"] = True\n self.df[\"ignore\"].fillna(False, inplace=True) # fill rest of ignored concerts with False\n\n def _set_source_outlinks_per_concert(self):\n for i in range(0, 10, 1):\n self.df[\"source_\" + str(i)] = [None] * len(self.df.index)\n self.df[\"source_link_\" + str(i)] = [None] * len(self.df.index)\n for concert_id in self.df[\"concert_id\"].unique():\n concerts = self.df[self.df[\"concert_id\"] == concert_id]\n event_ids = concerts[\"event_id\"].values\n visible_event_ids = concerts[concerts[\"visible\"]][\"event_id\"].values\n if len(visible_event_ids) > 0:\n visible_event_id = visible_event_ids[0]\n for i, event_id in enumerate(event_ids):\n source, source_link = self._establish_source_hyperlink(event_id)\n event_id__index_ = concerts[concerts[\"event_id\"] == visible_event_id].index[0]\n self.df.at[event_id__index_, \"source_\" + str(i)] = source\n self.df.at[event_id__index_, \"source_link_\" + str(i)] = source_link\n\n @staticmethod\n def _establish_source_hyperlink(event_id):\n if \"facebook\" in event_id:\n return \"Facebook\", \"https://www.facebook.com/events/\" + event_id.split(\"facebook\")[-1]\n elif \"songkick\" in event_id:\n return \"Songkick\", \"https://www.songkick.com/concerts/\" + event_id.split(\"_\")[-1]\n elif \"bandsintown\" in event_id:\n return \"BandsInTown\", \"http://bandsintown.com/e/\" + event_id.split(\"_\")[-1]\n elif \"setlist\" in event_id:\n return \"Setlist.fm\", \"https://www.setlist.fm/setlist/a/0/b-\" + event_id.split(\"setlist\")[-1]\n elif \"podiuminfo\" in event_id:\n return \"Podium/Festivalinfo\", \"http://festivalinfo.nl\"\n elif \"datakunstenbe\" in event_id:\n return \"Kunstenpunt\", \"http://data.kunsten.be\"\n else:\n return None, None\n\n @staticmethod\n def _establish_optimal_source(concert_source_values, concert_cancellations, potential_source_values):\n source = None\n concert_source_value_established = False\n for potential_source_value in potential_source_values:\n if not concert_source_value_established:\n source = potential_source_value if potential_source_value in concert_source_values else None\n if source:\n cancelled = concert_cancellations.iloc[concert_source_values.tolist().index(source)]\n if not cancelled:\n concert_source_value_established = True\n else:\n source = None\n return source\n\n def make_concerts(self):\n print(\"identifying the concerts\")\n artist_date_city_triples = self._make_gig_triples()\n\n print(\"\\tassigning concert ids\")\n self._assign_concert_ids(artist_date_city_triples)\n\n print(\"\\tsetting visibility\")\n self._select_visibility_per_concert()\n\n print(\"\\tresolving festival date ranges\")\n self._set_precise_date_for_festivals()\n\n self.df.loc[(self.df[\"source\"] == \"facebook\") & (self.df[\"stad\"] == \"None\"), \"visible\"] = False # concerts from facebook without decent city information should be ignored\n\n def _set_precise_date_for_festivals(self):\n visible_festivals = self.df[(self.df[\"event_type\"].str.lower() == \"festival\") &\n (self.df[\"source\"].isin([\"songkick\", \"podiumfestivalinfo\", \"facebook\"])) &\n (self.df[\"visible\"])]\n for row in visible_festivals.iterrows():\n festival_index = row[0]\n begindatum = row[1][\"datum\"] if not isnull(row[1][\"datum\"]) else Timestamp(datetime(1970, 1, 1))\n einddatum = row[1][\"einddatum\"] if not isnull(row[1][\"einddatum\"]) else begindatum\n artiest_mb_id = row[1][\"artiest_mb_id\"]\n stad_clean = row[1][\"stad_clean\"]\n precise_events = self.df[\n (self.df[\"source\"].isin([\"bandsintown\", \"facebook\", \"datakunstenbe\", \"manual\", \"setlist\", \"songkick\"])) &\n (self.df[\"datum\"].between(begindatum, einddatum)) &\n (self.df[\"event_type\"] != \"festival\") &\n (self.df[\"artiest_mb_id\"] == artiest_mb_id) &\n (self.df[\"stad_clean\"] == stad_clean)]\n precise_events_source_values = precise_events[\"source\"].values\n concert_cancellations = precise_events.apply(self._is_cancellation, axis=1)\n potential_source_values = [\"manual\", \"datakunstenbe\", \"bandsintown\", \"setlist\", \"facebook\", \"songkick\"]\n source = self._establish_optimal_source(precise_events_source_values, concert_cancellations, potential_source_values)\n if source:\n precise_concert_index = precise_events[precise_events[\"source\"] == source].index[0]\n self.df.at[precise_concert_index, \"visible\"] = True\n precise_concert_id = self.df.loc[precise_concert_index][\"concert_id\"]\n self.df.at[festival_index, \"concert_id\"] = precise_concert_id\n self.df.at[festival_index, \"visible\"] = False\n\n def _is_cancellation(self, row):\n return (Timestamp(row[\"datum\"]) > Timestamp(self.now.date())) & (Timestamp(row[\"last_seen_on\"]) < Timestamp(self.now.date() - timedelta(days=2)))\n\n def infer_cancellations(self):\n print(\"inferring cancellations\")\n self.df[\"cancelled\"] = self.df.apply(self._is_cancellation, axis=1)\n\n def persist_output(self):\n print(\"writing to file\")\n with open(\"resources/kolomvolgorde.txt\", \"r\") as f:\n kolomvolgorde = [kolom.strip() for kolom in f.read().split(\"\\n\")]\n self.df.to_excel(\"output/latest.xlsx\", columns=kolomvolgorde)\n\n\nif __name__ == \"__main__\":\n update_from_musicbrainz = (sys.argv[1] == \"True\") if len(sys.argv) > 1 else False\n grabber = Grabber(update_from_musicbrainz)\n grabber.grab()\n","sub_path":"grab_buitenlandse_concerten.py","file_name":"grab_buitenlandse_concerten.py","file_ext":"py","file_size_in_byte":20454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"24280606","text":"# -*- coding: utf-8 -*-\n# A little bit refactored version from:\n# http://www.cyberforum.ru/post956916.html\nfrom decimal import Decimal as D\n\n\nten_to_nineteen_words = {\n 0: u'десять',\n 1: u'одиннадцать',\n 2: u'двенадцать',\n 3: u'тринадцать',\n 4: u'четырнадцать',\n 5: u'пятнадцать',\n 6: u'шестнадцать',\n 7: u'семнадцать',\n 8: u'восемнадцать',\n 9: u'девятнадцать',\n}\nhundreds_words = {\n 1: u'сто',\n 2: u'двести',\n 3: u'триста',\n 4: u'четыреста',\n 5: u'пятьсот',\n 6: u'шестьсот',\n 7: u'семьсот',\n 8: u'восемьсот',\n 9: u'девятьсот',\n}\ntens_words = {\n 2: u'двадцать',\n 3: u'тридцать',\n 4: u'сорок',\n 5: u'пятьдесят',\n 6: u'шестьдесят',\n 7: u'семьдесят',\n 8: u'восемьдесят',\n 9: u'девяносто',\n}\nones_words = {\n 1: u'один',\n 2: u'два',\n 3: u'три',\n 4: u'четыре',\n 5: u'пять',\n 6: u'шесть',\n 7: u'семь',\n 8: u'восемь',\n 9: u'девять',\n}\n\n\ndef triad(number, mass, sort):\n tens = number % D('100')\n tens = int(tens / D('10'))\n ed = number % D('10')\n word = mass[0]\n if tens == 1:\n third_number = ten_to_nineteen_words.get(ed, '')\n else:\n third_number = ones_words.get(ed, '')\n if ed == 1:\n if sort == 'w':\n third_number = u'одна'\n word = mass[1]\n else:\n word = mass[1]\n elif ed == 2:\n if sort == 'w':\n third_number = u'две'\n word = mass[2]\n elif ed == 3:\n word = mass[2]\n elif ed == 4:\n word = mass[2]\n hundred = int(number / D('100'))\n first_number = hundreds_words.get(hundred, '')\n second_number = tens_words.get(tens, '')\n\n return first_number + ' ' + second_number + ' ' + third_number + ' ' + word\n\n\ndef to_text(number):\n is_decimal = isinstance(number, D)\n hundred = ['', '', '', '']\n thousand = [u'тысяч', u'тысяча', u'тысячи']\n million = [u'миллионов', u'миллион', u'миллиона']\n billion = [u'миллиардов', u'миллиард', u'миллиарда']\n sort1 = ['m']\n\n number1 = number / D('1000000')\n part1 = int(number1)\n number2 = part1\n number2 = number - number2 * D('1000000')\n part2 = int(number2)\n billionpart = int(part1 / D('1000'))\n if billionpart == 0:\n billion_word = ''\n else:\n billion_word = triad(billionpart, billion, sort1)\n mill = part1 % D('1000')\n if mill == 0:\n mill_word = ''\n else:\n mill_word = triad(mill, million, sort1)\n thous = int(part2 / D('1000'))\n sort1 = 'w'\n if thous == 0:\n thous_word = ''\n else:\n thous_word = triad(thous, thousand, sort1)\n\n hundredpart = part2 % 1000\n if hundredpart == 0:\n hundred_word = ''\n else:\n sort1 = 'm'\n hundred_word = triad(hundredpart, hundred, sort1)\n\n if number < 1:\n null_word = u'ноль'\n if is_decimal:\n null_word += u' рублей'\n else:\n null_word = ''\n copeck_word = number % D('1')\n copeck_word = int(copeck_word * 100)\n copeck_word = str(copeck_word)\n trnsfstr = (\n billion_word + ' ' + mill_word + ' '\n + thous_word + ' ' + hundred_word + ' '\n + null_word\n )\n if is_decimal:\n trnsfstr += u'руб.' + ' ' + copeck_word + ' ' + u'коп.'\n trnsfstr = ' '.join(trnsfstr.split())\n trnsfstr = trnsfstr.capitalize()\n\n return trnsfstr\n\n\ndef plural(value, form1, form2, form5=None):\n if form5 is None:\n form5 = form2\n remainder = value % 20\n if remainder == 1:\n return unicode(value) + ' ' + form1\n elif 1 < remainder < 5:\n return unicode(value) + ' ' + form2\n return unicode(value) + ' ' + form5\n","sub_path":"pdfer/logic/numeral.py","file_name":"numeral.py","file_ext":"py","file_size_in_byte":4074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"471284872","text":"import operator\nimport re\nimport csv\nimport io\nimport datetime\nimport functools\n\nfrom django.core.exceptions import ValidationError\nfrom mcsv.resolver import Resolver\nfrom systems import models as sys_models\n\nclass MockSystem(object):\n \"\"\"\n A fake system where we can stage changes\n \"\"\"\n pass # pylint: disable=unnecessary-pass\n\n\nclass Generator(object):\n def __init__(self, resolver, headers, delimiter=','):\n self.r = resolver\n self.headers = headers\n self.delimiter = delimiter\n\n self.meta_bundles = [\n (handle, b(self.r))\n for handle, b\n in self.r.metas.items()\n ]\n\n self.system_attr_bundles = [\n (handle, b(self.r))\n for handle, b\n in self.r.system_attrs.items()\n ]\n\n self.system_related_bundles = [\n (handle, b(self.r))\n for handle, b\n in self.r.system_relateds.items()\n ]\n\n self.system_kv_bundles = [\n (handle, b(self.r))\n for handle, b\n in self.r.system_kvs.items()\n ]\n \"\"\"\n Here we want to make a list of callbacks that will get chained into one\n another.\n\n Phase 0)\n These are meta headers. They set attributes that are not saved to an\n the database.\n\n Phase 1)\n System attr headers will have an new system model pushed through their\n handlers and they will set attributes.\n\n Phase 2)\n System related headers will have a system model (may or maynot have a\n pk) pushed through their handlers and they will set the correct values\n on the system.\n\n Phase 3)\n System key values will have their system attribute set and then may or\n maynot be saved.\n \"\"\"\n bundle_lists = [\n self.meta_bundles, self.system_attr_bundles,\n self.system_related_bundles, self.system_kv_bundles\n ]\n action_list = []\n fail = False\n for (header, raw_header) in headers:\n header = header.replace(\" \", \"_\")\n found_handler = False\n\n for (phase, bundle_list) in enumerate(bundle_lists):\n for _, bundle in bundle_list:\n def re_in(header):\n \"\"\"\n This function is only called when a bundle doesn't\n define a match function ('match_func')\n \"\"\"\n c = lambda el: bool(\n re.search('^{0}$'.format(header), el)\n )\n return functools.reduce(\n operator.or_, map(c, bundle['values']), False # pylint: disable=cell-var-from-loop\n )\n\n handler_matches = bundle.get('match_func', re_in)\n\n if handler_matches(header):\n # related attributes use raw_header\n action_list.append(\n (phase, raw_header, bundle['handler'])\n )\n found_handler = True\n break # Break the inner loop\n\n if found_handler:\n continue\n fail = \"Couldn't find handler for header {0}\".format(header)\n if fail:\n raise ValidationError(fail)\n self.action_list = action_list\n\n def handle(self, data):\n \"\"\"\n Where the magic happens.\n \"\"\"\n phase_0 = []\n phase_1 = []\n phase_2 = []\n phase_3 = []\n # Warning: raw_headers still need to be striped of white space\n for (phase, raw_header, action), item in zip(self.action_list, data):\n if phase == 0:\n phase_0.append((action, raw_header, item))\n elif phase == 1:\n phase_1.append((action, item))\n elif phase == 2:\n phase_2.append((action, raw_header, item))\n elif phase == 3:\n phase_3.append((action, raw_header, item))\n else:\n raise ValidationError(\"wut?\")\n\n s = MockSystem()\n # Phase 0 meta raw_headers\n for action, raw_header, item in phase_0:\n s = action(s, raw_header, item)\n\n # Phase 1 System attributes\n for action, item in phase_1:\n s = action(s, item)\n\n # Phase 2 Related fields\n for action, raw_header, item in phase_2:\n s = action(s, raw_header, item)\n\n # Phase 3 key value paires\n kv_cbs = [] # keyvalue call backs\n for action, key, value in phase_3:\n def keyvalue_cb(system, key=key, value=value, save=True):\n orig_kv = None\n if not system.pk:\n # It has to be a new key\n kv = sys_models.KeyValue(\n obj=system, key=key, value=value\n )\n else:\n # Attempt to find an existing key first\n try:\n kv = system.keyvalue_set.get(key=key)\n kv.value = value\n orig_kv = system.keyvalue_set.get(pk=kv.pk)\n except system.keyvalue_set.model.DoesNotExist:\n kv = sys_models.KeyValue(\n obj=system, key=key, value=value\n )\n if save:\n kv.save()\n return kv, orig_kv\n\n # Set the function name for debugging purposes\n keyvalue_cb.__name__ = \"{0} {1}\".format(key, value)\n\n kv_cbs.append(keyvalue_cb)\n\n return s, kv_cbs\n\n\ndef csv_import(csv_text, save=True, primary_attr='hostname'):\n r = Resolver()\n generator = None\n\n def make_header(header):\n # sometimes headers have a '%' in them. We want everything to the\n # left of the first '%'\n return map(lambda s: s.strip().lower(), (header.split('%')[0], header))\n\n ret = []\n f = io.StringIO(csv_text)\n reader = csv.reader(f, skipinitialspace=True)\n\n def has_something(line):\n return functools.reduce(lambda a, b: b or a, line, False)\n\n for line in [list(map(lambda s: s.strip(), line)) for line in reader]:\n if not has_something(line): # allow blank lines\n continue\n if not generator:\n generator = Generator(\n r, [make_header(header) for header in line]\n )\n continue\n mock_s, kv_callbacks = generator.handle(line)\n try:\n if hasattr(mock_s, '_primary_attr'):\n get_params = {\n mock_s._primary_attr: mock_s._primary_value # pylint: disable=protected-access\n }\n else:\n get_params = {\n primary_attr: getattr(mock_s, primary_attr) # pylint: disable=protected-access\n }\n\n s = sys_models.System.objects.get(**get_params)\n orig_system = sys_models.System.objects.get(pk=s.pk)\n\n for attr, value in vars(mock_s).items():\n if attr.startswith('_'):\n continue\n setattr(s, attr, value)\n\n except sys_models.System.DoesNotExist:\n s = sys_models.System(**vars(mock_s))\n orig_system = None\n\n if save:\n if not s.created_on:\n s.created_on = datetime.datetime.now()\n s.save()\n kvs = []\n for cb in kv_callbacks:\n kvs.append(cb(s, save=save))\n ret.append({'system': s, 'orig_system': orig_system, 'kvs': kvs})\n return ret\n\n\ndef main(fname):\n host = \"http://toolsdev1.dmz.scl3.mozilla.com:8000\"\n query = host + '/en-US/core/search/#q'\n with open(fname, 'r') as fd:\n csv_import(fd.readlines())\n\n print(query.strip(' OR ')) # pylint: disable=bad-str-strip-call\n","sub_path":"mcsv/importer.py","file_name":"importer.py","file_ext":"py","file_size_in_byte":7966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"384140365","text":"import pandas as pd\nimport numpy as np\n\ndata = pd.read_csv('adult.data', header=None, sep=', ', na_values='?')\n\n# Total records after removing NA\ndata_dropna = data.dropna(axis=0, how='any')\n\n# Drop final weights column\ndata_dropna = data_dropna.drop(columns=[2], axis=1)\ndata_dropna.columns = ['age', 'workclass', 'education', 'education-num',\n 'marital-status', 'occupation', 'relationship',\n 'race', 'sex', 'capital-gain', 'capital-loss',\n 'hours-per-week', 'native-country', '50K?']\n\n# remove education column\ndata_dropna = data_dropna.drop(columns=['education'], axis=1)\n\n# change workclass to scale\ndata_dropna[['workclass', '50K?']].groupby(['workclass']).count()\ndata_dropna['workclass_num'] = data_dropna['workclass'].replace(to_replace=['State-gov', 'Self-emp-not-inc',\n 'Private', 'Federal-gov',\n 'Local-gov', 'Self-emp-inc',\n 'Without-pay'],\n value=[3, 2, 1, 3, 3, 4, 0])\n\n# change marital status to 2 class\ndata_dropna['married_num'] = 0\ndata_dropna.loc[data_dropna['marital-status'] == 'Married-AF-spouse', 'married_num'] = 1\ndata_dropna.loc[data_dropna['marital-status'] == 'Married-civ-spouse', 'married_num'] = 1\n\n# change sex to numerical scale\ndata_dropna['sex_num'] = data_dropna['sex'].replace(to_replace=['Female', 'Male'], value=[0, 1])\n\n# change native country to numerical scale (the U.S. or not)\ndata_dropna['country_num'] = 0\ndata_dropna.loc[data_dropna['native-country'] == 'United-States', 'country_num'] = 1\n\n# change target to numerical scale\ndata_dropna['target'] = data_dropna['50K?'].replace(to_replace=['<=50K', '>50K'], value=[0, 1])\n\n\ndata_clean = data_dropna.drop(columns=['workclass', 'marital-status', 'occupation', 'relationship', 'race', 'sex',\n 'capital-gain', 'capital-loss', 'native-country', '50K?', ], axis=1)\n\n# save into new file\ndata_clean.to_csv('adult_clean.csv', index=True)\n\n\n\n\n","sub_path":"FinalProject/dataPreprocessing.py","file_name":"dataPreprocessing.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"132719312","text":"import sys\nimport rectangle\nimport utils\nimport numpy\n\n\ndef validate(image_width, image_height, expected_path, result_path):\n expected = utils.loadRectangles(expected_path)\n result = utils.loadResultRectangles(result_path)\n result_length = len(result)\n\n iou_values = []\n for rect in expected:\n nearest = utils.find_nearest_by_coverage(rect, result)\n if nearest is None:\n iou_values.append(0)\n else:\n result.remove(nearest)\n iou = utils.calculate_iou(rect, nearest)\n iou_values.append(iou)\n\n iou_mean = numpy.mean(iou_values)\n penalty_coeff = utils.penalty(len(expected), result_length)\n grade = iou_mean * penalty_coeff\n return grade","sub_path":"python/validation/validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"353052025","text":"#!/usr/bin/env python\n\"\"\"Tests for _units.py\"\"\"\n\nimport numpy as np\nimport pytest\nimport xarray as xr\nimport xarray.testing\n\nfrom .utils import allclose, assert_equal\n\n\ndef test_roundtrip_quantify(opulent_ds: xr.Dataset):\n roundtrip = opulent_ds.pr.dequantify().pr.quantify()\n xarray.testing.assert_identical(roundtrip, opulent_ds)\n\n\ndef test_roundtrip_quantify_da(opulent_ds: xr.Dataset):\n da: xr.DataArray = opulent_ds[\"SF6 (SARGWP100)\"]\n roundtrip = da.pr.dequantify().pr.quantify()\n assert_equal(roundtrip, da)\n\n\ndef test_convert_to_gwp(opulent_ds: xr.Dataset):\n da: xr.DataArray = opulent_ds[\"SF6\"]\n da_converted = da.pr.convert_to_gwp(\"SARGWP100\", \"CO2 Gg / year\")\n da_expected = opulent_ds[\"SF6 (SARGWP100)\"]\n assert_equal(da_converted, da_expected)\n\n da_converted_like = da.pr.convert_to_gwp_like(da_expected)\n assert_equal(da_converted_like, da_expected)\n\n\ndef test_convert_to_gwp_like_missing(opulent_ds: xr.Dataset):\n da: xr.DataArray = opulent_ds[\"SF6\"]\n da_gwp = da.pr.convert_to_gwp(\"SARGWP100\", \"CO2 Gg / year\")\n\n del da_gwp.attrs[\"gwp_context\"]\n with pytest.raises(ValueError, match=\"reference array has no gwp_context\"):\n da.pr.convert_to_gwp_like(da_gwp)\n\n da_gwp = xr.full_like(da_gwp, np.nan)\n da_gwp.attrs[\"gwp_context\"] = \"SARGWP100\"\n with pytest.raises(ValueError, match=\"reference array has no units attached\"):\n da.pr.convert_to_gwp_like(da_gwp)\n\n\ndef test_convert_to_gwp_incompatible(opulent_ds: xr.Dataset):\n da: xr.DataArray = opulent_ds[\"SF6 (SARGWP100)\"]\n with pytest.raises(ValueError, match=\"Incompatible gwp conversions\"):\n da.pr.convert_to_gwp(\"AR5GWP\", \"CO2 Gg / year\")\n\n\ndef test_convert_to_mass(opulent_ds: xr.Dataset):\n da: xr.DataArray = opulent_ds[\"SF6 (SARGWP100)\"]\n da_converted = da.pr.convert_to_mass()\n da_expected = opulent_ds[\"SF6\"]\n assert_equal(da_converted, da_expected)\n\n\ndef test_convert_to_mass_missing_info(opulent_ds: xr.Dataset):\n da: xr.DataArray = opulent_ds[\"SF6\"]\n with pytest.raises(\n ValueError,\n match=\"No gwp_context given and no gwp_context available in the attrs\",\n ):\n da.pr.convert_to_mass()\n\n da = opulent_ds[\"SF6 (SARGWP100)\"]\n del da.attrs[\"entity\"]\n with pytest.raises(\n ValueError, match=\"No entity given and no entity available in the attrs\"\n ):\n da.pr.convert_to_mass()\n\n\ndef test_context(opulent_ds: xr.Dataset):\n da: xr.DataArray = opulent_ds[\"SF6 (SARGWP100)\"]\n with da.pr.gwp_context:\n da_converted = opulent_ds[\"SF6\"].pint.to(da.pint.units)\n assert allclose(da, da_converted)\n","sub_path":"primap2/tests/test_units.py","file_name":"test_units.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"504591238","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport htmlentitydefs\nimport re\n# import xml.etree.cElementTree as ET\nimport xml.etree.ElementTree as ET # use this one for the ET.tostring\nimport glob\n\n\ndef read_mapping(f, fn=\"mapping data\"):\n \"\"\"\n Reads in mapping from Unicode to ASCII from the given input stream\n and returns a dictionary keyed by Unicode characters with the\n corresponding ASCII characters as values. The expected mapping\n format defines a single mapping per line, each with the format\n CODE\\tASC where CODE is the Unicode code point as a hex number and\n ASC is the replacement ASCII string (\"\\t\" is the literal tab\n character). Any lines beginning with \"#\" are skipped as comments.\n \"\"\"\n # read in the replacement data\n linere = re.compile(r'^([0-9A-Za-z]{4,})\\t(.*)$')\n mapping = {}\n for i, l in enumerate(f):\n # ignore lines starting with \"#\" as comments\n if len(l) != 0 and l[0] == \"#\":\n continue\n m = linere.match(l)\n assert m, \"Format error in %s line %s: '%s'\" % (fn, i+1, l.replace(\"\\n\",\"\").encode(\"utf-8\"))\n c, r = m.groups()\n c = unichr(int(c, 16))\n assert c not in mapping or mapping[c] == r, \"ERROR: conflicting mappings for %.4X: '%s' and '%s'\" % (ord(c), mapping[c], r)\n # exception: literal '\\n' maps to newline\n if r == '\\\\n':\n r = '\\n'\n mapping[c] = r\n return mapping\n\ndef mapchar(c, mapping):\n if c in mapping:\n return mapping[c]\n else:\n # make a note of anything unmapped\n global missing_mappings, options\n missing_mappings.add(\"%.4X\" % ord(c))\n # remove missing by default, output codepoint as hex as an option\n if not options.hex:\n return ''\n else:\n return \"<%.4X>\" % ord(c)\n \ndef replace_mapped(root, mapping):\n # TODO: inefficient, improve\n s = \"\"\n o = \"\"\n u_count = 0\n for i, c in enumerate(root):\n o += '\\t'.join([str(i+(u_count*4)), str(len(s))]) + '\\n'\n if ord(c) >= 128:\n new_char = mapchar(c, mapping)\n s += new_char\n u_count += 1\n else:\n s += c\n return s, o\n\ndef convert_html_entities(old_s, unicode_ascii):\n temp ={u'\\x93': '\"', u'\\x94': '\"', '>': '>', '<': '<', u'\\xa0': '_'}\n map_dict = {}\n s = old_s\n map_idx = ''\n matches = re.findall(\"&#\\d+;\", s)\n if len(matches) > 0:\n hits = set(matches)\n for hit in hits:\n name = hit[2:-1]\n try:\n entnum = int(name)\n a = unicode_ascii[unichr(entnum)]\n map_dict.setdefault(hit, [a, len(hit)])\n s = s.replace(hit, a)\n except KeyError:\n a = temp[unichr(entnum)]\n map_dict.setdefault(hit, [a, len(hit)])\n s = s.replace(hit, a)\n except ValueError:\n pass\n matches = re.findall(\"&#[xX][0-9a-fA-F]+;\", s)\n if len(matches) > 0:\n hits = set(matches)\n for hit in hits:\n hex = hit[3:-1]\n try:\n entnum = int(hex, 16)\n a = unicode_ascii[unichr(entnum)]\n map_dict.setdefault(hit, [a, len(hit)])\n s = s.replace(hit, a)\n except KeyError:\n a = temp[unichr(entnum)]\n map_dict.setdefault(hit, [a, len(hit)])\n s = s.replace(hit, a)\n except ValueError:\n pass\n matches = re.findall(\"&\\w+;\", s)\n hits = set(matches)\n amp = \"&\"\n if amp in hits:\n hits.remove(amp)\n for hit in hits:\n name = hit[1:-1]\n if htmlentitydefs.name2codepoint.has_key(name):\n a = unicode_ascii[unichr(htmlentitydefs.name2codepoint[name])]\n map_dict.setdefault(hit, [a, len(hit)])\n s = s.replace(hit, a)\n a = '&'\n map_dict.setdefault(amp, [a, len(amp)])\n s = s.replace(amp, a)\n all_list = {}\n for k, v in map_dict.iteritems():\n html_list = {html_s.start(): [html_s.end(), len(v[0]), v[1]] for html_s in re.finditer(re.compile(k), old_s)} #html_s.end(), html_s.expand(), html_s.group(), html_s.groupdict(), html_s.groups(), html_s.span(), html_s.start()\n all_list.update(html_list)\n for k, v in all_list.iteritems():\n map_idx += '\\t'.join([str(k), str(v[0]), str(v[1]), str(v[2])]) + '\\n'\n return s, map_idx\n\ndef temp_get_doctext(in_xml, unicode_ascii):\n # offset_dict = {}\n text_dict = {}\n tree = ET.parse(open(in_xml))\n docs = tree.getroot() # get root element\n # doc_xml = in_xml.split('/')[-1].split('.xml')[0]\n for doc in docs.findall('.//document'):\n doc_id = doc.findall('id')[0].text.replace(\" \", \"_\").strip('.')\n for passage in doc.findall('passage'):\n # off_text = ET.tostring(passage.find('offset')) \n # offset = int(re.findall('(.*?)', off_text, re.DOTALL)[0])\n try:\n doc_text = ET.tostring(passage.find('text')) \n ext_text = re.findall('(.*?)', doc_text, re.DOTALL)\n if len(ext_text) == 1:\n text_dict.setdefault(doc_id, []).append(ext_text[0])\n except:\n pass\n return text_dict\n\n\ndef argument_parser():\n parser = argparse.ArgumentParser(description=\"extract entities from BioC XML\")\n parser.add_argument(\"-i\", \"--in_folder\", type=str, default= '../input/', help=\"full path of xml file resides\")\n parser.add_argument(\"-o\", \"--out_folder\", type=str, default= '../temp_process/documents/', help=\"folder where text files resides\")\n args = parser.parse_args()\n return args\n\n\nif __name__ == \"__main__\":\n args = argument_parser()\n text_dict = dict()\n with open('entities.dat', 'rb') as f:\n unicode_ascii = read_mapping(f)\n for in_xml in glob.glob(args.in_folder + '*.xml'):\n doc_id = in_xml.split('/')[-1].strip('.xml') \n text_dict = temp_get_doctext(in_xml, unicode_ascii)\n for doc_id, all_text in text_dict.iteritems():\n text = '\\n'.join(all_text)\n doc_text, map_idx = convert_html_entities(text, unicode_ascii)\n doc_id_text, map_id_idx = convert_html_entities(doc_id, unicode_ascii)\n with open(args.out_folder + doc_id_text + '.xml', 'w') as f:\n f.write(text + '\\n')\n # with open(args.out_folder + doc_id_text + '.txt', 'w') as f:\n # f.write(doc_text + '\\n')\n with open(args.out_folder + doc_id_text + '.xml.idx', 'w') as f:\n f.write(map_idx + '\\n')\n","sub_path":"normalization/extract_BioC_text.py","file_name":"extract_BioC_text.py","file_ext":"py","file_size_in_byte":6701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"321252567","text":"def get_language_info(lang_code):\n from django.conf.locale import LANG_INFO\n try:\n lang_info = LANG_INFO[lang_code]\n if 'fallback' in lang_info and 'name' not in lang_info:\n return get_language_info(lang_info['fallback'][0])\n return lang_info\n except KeyError:\n if '-' not in lang_code:\n raise KeyError(\"Unknown language code %s.\" % lang_code)\n generic_lang_code = lang_code.split('-')[0]\n try:\n return LANG_INFO[generic_lang_code]\n except KeyError:\n raise KeyError(\"Unknown language code %s and %s.\" % (lang_code, generic_lang_code))\n","sub_path":"calc/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"399154517","text":"from torch.nn import MaxPool1d, Module, Embedding, LSTM, AvgPool1d, Dropout\r\nfrom utils.params import SequenceEncoderParams\r\nimport torch\r\n\r\n\r\nclass SequenceEncoderModel(Module):\r\n def __init__(self, params: SequenceEncoderParams):\r\n super(SequenceEncoderModel, self).__init__()\r\n # word embed layer\r\n self._embeddings = self._load_pre_trained(params.EMBED_pre_trained, params.GPU) if params.EMBED_use_pre_trained\\\r\n else Embedding(params.EMBED_vocab_dim, params.EMBED_dim)\r\n # Bi-LSTM layers\r\n self._lstm_layer_0 = LSTM(params.EMBED_dim + params.EMBED_chr_dim, params.LSTM_hidden_dim, params.LSTM_layers,\r\n batch_first=True, bidirectional=True)\r\n self._lstm_layer_1 = LSTM(params.EMBED_dim + params.EMBED_chr_dim + (2 * params.LSTM_hidden_dim),\r\n params.LSTM_hidden_dim, params.LSTM_layers, batch_first=True, bidirectional=True)\r\n self._lstm_layer_2 = LSTM(params.EMBED_dim + params.EMBED_chr_dim + (2 * params.LSTM_hidden_dim),\r\n params.LSTM_hidden_dim, params.LSTM_layers, batch_first=True, bidirectional=True)\r\n self._dropout_0 = Dropout(p=params.LSTM_dropout_0)\r\n self._dropout_1 = Dropout(p=params.LSTM_dropout_1)\r\n self._dropout_2 = Dropout(p=params.LSTM_dropout_2)\r\n\r\n @staticmethod\r\n def _load_pre_trained(weights_matrix, gpu, non_trainable=False):\r\n weights_matrix = torch.Tensor(weights_matrix).cuda() if gpu else torch.Tensor(weights_matrix).cuda()\r\n num_embeddings, embedding_dim = weights_matrix.size()\r\n emb_layer = Embedding(num_embeddings, embedding_dim)\r\n emb_layer.load_state_dict({'weight': weights_matrix})\r\n if non_trainable:\r\n emb_layer.weight.requires_grad = False\r\n return emb_layer\r\n\r\n # implement attention Main paper -- 3.3 Composition Layer --\r\n def _calc_attention_coefficients(self):\r\n # get LSTM gate parameters\r\n # w_ii, w_if, w_ic, w_io = self._lstm_layer.weight_ih_l0.chunk(4, 0)\r\n w_hi, w_hf, w_hc, w_ho = self._lstm_layer_2.weight_hh_l0.chunk(4, 0)\r\n reverse_w_hi, w_hf, w_hc, w_ho = self._lstm_layer_2.weight_hh_l0_reverse.chunk(4, 0)\r\n norm_out_gates = torch.norm(torch.cat([w_hi, reverse_w_hi], dim=0), dim=1)\r\n attention_coefficient = norm_out_gates / torch.sum(norm_out_gates)\r\n return attention_coefficient\r\n\r\n def forward(self, words_embed, chr_rep):\r\n attention_coefficients = self._calc_attention_coefficients()\r\n # dynamic average and max pool according to batch sentence length\r\n activate_avg_pool = AvgPool1d(words_embed.shape[1], 1)\r\n activate_max_pool = MaxPool1d(words_embed.shape[1], 1)\r\n\r\n # embed_word concat with embed chr level -> Bi-LSTM layer\r\n x = self._embeddings(words_embed)\r\n x = torch.cat([x, chr_rep], dim=2)\r\n\r\n # 3 layers Bi-LSTM + skip connections + dropout layers in between\r\n output_seq, _ = self._lstm_layer_0(x)\r\n output_seq = self._dropout_0(output_seq)\r\n output_seq, _ = self._lstm_layer_1(torch.cat([x, output_seq], dim=2))\r\n output_seq = self._dropout_1(output_seq)\r\n output_seq, _ = self._lstm_layer_2(torch.cat([x, output_seq], dim=2))\r\n output_seq = self._dropout_2(output_seq)\r\n\r\n # final vec + attention\r\n avg_pool = activate_avg_pool(output_seq.transpose(1, 2)).squeeze(dim=2)\r\n max_pool = activate_max_pool(output_seq.transpose(1, 2)).squeeze(dim=2)\r\n gate_attention = torch.sum(output_seq * attention_coefficients, dim=1)\r\n x = torch.cat([gate_attention, avg_pool, max_pool], dim=1)\r\n return x\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import os\r\n from utils.data_loader import SNLIDataset\r\n from utils.params import TRAIN_SRC, PRE_TRAINED_SRC, ChrLevelCnnParams\r\n from torch.utils.data import DataLoader\r\n from utils.cnn_character_level_model import CharacterCnnEmbed\r\n\r\n ds = SNLIDataset(os.path.join(\"..\", TRAIN_SRC), os.path.join(\"..\", PRE_TRAINED_SRC))\r\n chr_params_ = ChrLevelCnnParams(chr_vocab_dim=ds.len_chars_vocab)\r\n word_params_ = SequenceEncoderParams(word_vocab_dim=ds.len_words_vocab, pre_trained=ds.word_embed_mx)\r\n chr_model = CharacterCnnEmbed(chr_params_)\r\n seq_model = SequenceEncoderModel(word_params_)\r\n dl = DataLoader(\r\n dataset=ds,\r\n batch_size=64,\r\n collate_fn=ds.collate_fn\r\n )\r\n for i, (p, h, pw, hw, pc, wc, label) in enumerate(dl):\r\n out = seq_model(pw, chr_model(pc))\r\n e = 0\r\n","sub_path":"utils/bi_lstm_sequence_model.py","file_name":"bi_lstm_sequence_model.py","file_ext":"py","file_size_in_byte":4600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"147874309","text":"from torchvision import datasets, transforms\n\nimport time\nimport random\nimport torch\nimport os\nimport numpy as np\nfrom model import EncoderA\nfrom datasets import datasets\nimport torch.nn as nn\nimport sys\n\nsys.path.append('../')\nimport probtorch\nimport util\nimport visdom\n\n# ------------------------------------------------\n# training parameters\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--run_id', type=int, default=2, metavar='N',\n help='run_id')\n parser.add_argument('--run_desc', type=str, default='',\n help='run_id desc')\n parser.add_argument('--n_privateA', type=int, default=636,\n help='size of the latent embedding of privateA')\n parser.add_argument('--batch_size', type=int, default=50, metavar='N',\n help='input batch size for training [default: 100]')\n parser.add_argument('--ckpt_epochs', type=int, default=0, metavar='N',\n help='number of epochs to train [default: 200]')\n parser.add_argument('--epochs', type=int, default=61, metavar='N',\n help='number of epochs to train [default: 200]')\n parser.add_argument('--lr', type=float, default=1e-3, metavar='LR',\n help='learning rate [default: 1e-3]')\n\n parser.add_argument('--beta', type=str, default='1,10,1',\n help='beta for TC. [img, attr, label]')\n parser.add_argument('--lamb', type=str, default='1,500,5000',\n help='lambda for reconst. [img, attr, label')\n\n parser.add_argument('--seed', type=int, default=0, metavar='N',\n help='random seed for get_paired_data')\n parser.add_argument('--wseed', type=int, default=0, metavar='N',\n help='random seed for weight')\n\n parser.add_argument('--ckpt_path', type=str, default='../weights/cub_reg_img_attr',\n help='save and load path for ckpt')\n parser.add_argument('--gpu', type=str, default='',\n help='cuda')\n parser.add_argument('--outgpu', type=int, default=-1,\n help='outgpu')\n parser.add_argument('--data_path', type=str, default='../../data/cub/CUB_200_2011/CUB_200_2011/',\n help='data path')\n\n parser.add_argument('--pre_trained_img',\n default=False, type=probtorch.util.str2bool, help='enable visdom visualization')\n # visdom\n parser.add_argument('--viz_on',\n default=False, type=probtorch.util.str2bool, help='enable visdom visualization')\n parser.add_argument('--viz_port',\n default=8002, type=int, help='visdom port number')\n args = parser.parse_args()\n\n# ------------------------------------------------\n\n\nEPS = 1e-9\n\nif len(args.gpu) > 0:\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu\n GPU = [int(elt) for elt in args.gpu.split(',')]\n print('GPU:', GPU)\nelse:\n GPU = []\nCUDA = torch.cuda.is_available()\n\nbeta = [float(i) for i in args.beta.split(',')]\nlamb = [float(i) for i in args.lamb.split(',')]\n\n# path parameters\nMODEL_NAME = 'cub_reg_img_attr-run_id%d-privA%02ddim-lamb%s-beta%s-lr%s-bs%s-wseed%s-seed%s' % (\n args.run_id, args.n_privateA, '_'.join([str(elt) for elt in lamb]), '_'.join([str(elt) for elt in beta]),\n args.lr, args.batch_size, args.wseed, args.seed)\n\nif len(args.run_desc) > 1:\n desc_file = os.path.join(args.ckpt_path, 'run_id' + str(args.run_id) + '.txt')\n with open(desc_file, 'w') as outfile:\n outfile.write(args.run_desc)\n\nN_PIXELS = 3 * 128 * 128\nTEMP = 0.66\nNUM_SAMPLES = 1\nimport pickle\n\npath = args.data_path\nATTR_PRIOR = pickle.load(open(path + \"attributes/attr_prior_312.pkl\", \"rb\"))\nfor i in range(len(ATTR_PRIOR)):\n ATTR_PRIOR[i] = torch.FloatTensor(np.array([1 - ATTR_PRIOR[i], ATTR_PRIOR[i]]))\n ATTR_PRIOR[i] = torch.transpose(ATTR_PRIOR[i], dim0=0, dim1=1)\n if CUDA:\n ATTR_PRIOR[i] = ATTR_PRIOR[i].cuda()\n\nprimary_attr = ['eye_color', 'bill_length', 'shape', 'breast_pattern', 'belly_pattern', 'bill_shape',\n 'bill_color', 'throat_color', 'crown_color', 'forehead_color', 'underparts_color', 'primary_color',\n 'breast_color', 'wing_color']\n# original\nprimary_attr = ['eye_color', 'bill_length', 'size', 'shape', 'breast_pattern', 'belly_pattern', 'bill_shape',\n 'bill_color', 'throat_color', 'crown_color', 'forehead_color', 'underparts_color', 'primary_color',\n 'breast_color', 'wing_color']\n# regressor + stat 10\nprimary_attr = ['eye_color', 'bill_length', 'leg_color', 'bill_shape',\n 'bill_color', 'throat_color', 'crown_color', 'forehead_color',\n 'belly_color', 'wing_color']\n\n# regressor + stat 13\nprimary_attr = ['eye_color', 'bill_length', 'shape', 'bill_shape', 'head_pattern',\n 'bill_color', 'throat_color', 'crown_color', 'forehead_color', 'breast_color',\n 'belly_color', 'wing_color', 'leg_color']\n\n# primary_attr = ['wing_color']\n\n\n# regressor + stat + visible 12\n# primary_attr = ['bill_length', 'shape', 'bill_shape', 'wing_pattern', 'primary_color',\n# 'bill_color', 'throat_color', 'forehead_color', 'breast_color',\n# 'belly_color', 'wing_color', 'leg_color']\n\n# total\nprimary_attr = ['bill_shape', 'wing_color', 'upperparts_color', 'underparts_color', 'breast_pattern', 'back_color',\n 'tail_shape', 'upper_tail_color', 'head_pattern', 'breast_color', 'throat_color', 'eye_color',\n 'bill_length',\n 'forehead_color', 'under_tail_color', 'nape_color', 'belly_color', 'wing_shape', 'size', 'shape',\n 'back_pattern',\n 'tail_pattern', 'belly_pattern', 'primary_color', 'leg_color', 'bill_color', 'crown_color',\n 'wing_pattern']\n\n# primary_attr = ['wing_color']\nATTR_IDX = []\nATTR_DIM = []\nN_ATTR = len(primary_attr)\nTRAIN_CLASSES = np.genfromtxt(path + 'attributes/trainvalids.txt', delimiter='\\n', dtype=int)\n\nattributes = np.genfromtxt(path + 'attributes/attr.txt', delimiter='\\n', dtype=str)\ntotal_attr = []\nfor i in range(attributes.shape[0]):\n attr = attributes[i].split(\"::\")[0]\n total_attr.append(attr)\n if attr in primary_attr:\n ATTR_IDX.append(i)\n ATTR_DIM.append(len(attributes[i].split(\"::\")[1].split(',')))\n\nATTR_PRIOR = [ATTR_PRIOR[i] for i in ATTR_IDX]\nprint(primary_attr)\nprint(ATTR_IDX)\nprint(np.array(total_attr)[ATTR_IDX])\nprint(len(ATTR_IDX))\nprint(sum(ATTR_DIM))\n\n\n# visdom setup\ndef viz_init():\n VIZ.close(env=MODEL_NAME + '/lines', win=WIN_ID['train_acc'])\n VIZ.close(env=MODEL_NAME + '/lines', win=WIN_ID['test_acc'])\n VIZ.close(env=MODEL_NAME + '/lines', win=WIN_ID['val_acc'])\n VIZ.close(env=MODEL_NAME + '/lines', win=WIN_ID['total_losses'])\n\n\ndef visualize_line():\n data = LINE_GATHER.data\n epoch = torch.Tensor(data['epoch'])\n train_acc = torch.Tensor(data['train_acc'])\n val_acc = torch.Tensor(data['val_acc'])\n test_acc = torch.Tensor(data['test_acc'])\n val_total_loss = torch.Tensor(data['test_total_loss'])\n test_total_loss = torch.Tensor(data['val_total_loss'])\n total_loss = torch.Tensor(data['total_loss'])\n\n total_losses = torch.tensor(np.stack([total_loss, val_total_loss, test_total_loss], -1))\n\n VIZ.line(\n X=epoch, Y=train_acc, env=MODEL_NAME + '/lines',\n win=WIN_ID['train_acc'], update='append',\n opts=dict(xlabel='epoch', ylabel='accuracy',\n title='Train Accuracy', legend=['acc'])\n )\n\n VIZ.line(\n X=epoch, Y=test_acc, env=MODEL_NAME + '/lines',\n win=WIN_ID['test_acc'], update='append',\n opts=dict(xlabel='epoch', ylabel='accuracy',\n title='Test Accuracy', legend=['acc'])\n )\n\n VIZ.line(\n X=epoch, Y=val_acc, env=MODEL_NAME + '/lines',\n win=WIN_ID['val_acc'], update='append',\n opts=dict(xlabel='epoch', ylabel='accuracy',\n title='Val Accuracy', legend=['acc'])\n )\n\n VIZ.line(\n X=epoch, Y=total_losses, env=MODEL_NAME + '/lines',\n win=WIN_ID['total_losses'], update='append',\n opts=dict(xlabel='epoch', ylabel='loss',\n title='Total Loss', legend=['train_loss', 'val_loss', 'test_loss'])\n )\n\n\nif args.viz_on:\n WIN_ID = dict(\n train_acc='win_train_acc', test_acc='win_test_acc', val_acc='win_val_acc',\n total_losses='win_total_losses'\n )\n LINE_GATHER = probtorch.util.DataGather(\n 'epoch',\n 'total_loss', 'test_total_loss', 'val_total_loss', 'train_acc', 'test_acc', 'val_acc'\n )\n VIZ = visdom.Visdom(port=args.viz_port)\n viz_init()\n\ntrain_data = torch.utils.data.DataLoader(datasets(path, ATTR_IDX, train=True, crop=1.2), batch_size=args.batch_size,\n shuffle=True,\n num_workers=len(GPU))\ntest_data = torch.utils.data.DataLoader(datasets(path, ATTR_IDX, train=False, crop=1.2), batch_size=args.batch_size,\n shuffle=True,\n num_workers=len(GPU))\n\nval_data = torch.utils.data.DataLoader(datasets(path, ATTR_IDX, train=True, crop=1.2, val=True),\n batch_size=args.batch_size,\n shuffle=True,\n num_workers=len(GPU))\n\nBIAS_TRAIN = (train_data.dataset.__len__() - 1) / (args.batch_size - 1)\nBIAS_TEST = (test_data.dataset.__len__() - 1) / (args.batch_size - 1)\n\n\ndef cuda_tensors(obj):\n for attr in dir(obj):\n value = getattr(obj, attr)\n if isinstance(value, torch.Tensor):\n setattr(obj, attr, value.cuda())\n\n\nencA = EncoderA(args.wseed, zPrivate_dim=args.n_privateA, zSharedAttr_dim=ATTR_DIM)\n\nif CUDA:\n encA.cuda()\n cuda_tensors(encA)\n if len(args.gpu) > 2:\n print('multi: ' + args.gpu)\n encA = nn.DataParallel(encA)\n\noptimizer = torch.optim.Adam(\n list(\n encA.parameters()),\n lr=args.lr)\n\n\ndef train(data, encA, optimizer):\n epoch_elbo = epoch_correct = 0.0\n epoch_pred = np.zeros(sum(ATTR_DIM))\n encA.train()\n\n N = 0\n for b, (images, attributes, label) in enumerate(data):\n if images.size()[0] == args.batch_size:\n N += 1\n attributes = attributes.float()\n optimizer.zero_grad()\n if CUDA:\n images = images.cuda()\n attributes = attributes.cuda()\n loss, acc, pred_labels = encA(images, attributes, num_samples=NUM_SAMPLES)\n loss.backward()\n optimizer.step()\n pred_labels = pred_labels.sum(dim=0)\n if CUDA:\n loss = loss.cpu()\n acc = acc.cpu()\n pred_labels = pred_labels.cpu()\n epoch_elbo += loss.item()\n epoch_correct += acc.item()\n epoch_pred += pred_labels.detach().numpy()\n return epoch_elbo / N, epoch_correct / (N * args.batch_size), np.round(epoch_pred / (N * args.batch_size), 2)\n\n\ndef test(data, encA, epoch):\n encA.eval()\n epoch_elbo = epoch_correct = 0.0\n epoch_pred = np.zeros(sum(ATTR_DIM))\n\n N = 0\n for b, (images, attributes, _) in enumerate(data):\n if images.size()[0] == args.batch_size:\n N += 1\n attributes = attributes.float()\n if CUDA:\n images = images.cuda()\n attributes = attributes.cuda()\n # encode\n loss, acc, pred_labels = encA(images, attributes, num_samples=NUM_SAMPLES)\n pred_labels = pred_labels.sum(dim=0)\n\n if CUDA:\n loss = loss.cpu()\n acc = acc.cpu()\n pred_labels = pred_labels.cpu()\n epoch_elbo += loss.item()\n epoch_correct += acc.item()\n epoch_pred += pred_labels.detach().numpy()\n\n return epoch_elbo / N, epoch_correct / (N * args.batch_size), np.round(epoch_pred / (N * args.batch_size), 2)\n\n\n####\ndef save_ckpt(e):\n torch.save(encA, '%s/%s-encA_epoch%s.rar' % (args.ckpt_path, MODEL_NAME, e))\n\n\nif args.pre_trained_img:\n encA.resnet.load_state_dict(torch.load(\n '../weights/cub/cub-run_id5-privA100dim-lamb1.0_500.0_5000.0-beta1.0_10.0_1.0-lr0.001-bs50-wseed0-seed0-encA_res_epoch400.rar'))\n\nif args.ckpt_epochs > 0:\n if CUDA:\n encA = torch.load('%s/%s-encA_epoch%s.rar' % (args.ckpt_path, MODEL_NAME, args.ckpt_epochs))\n else:\n encA = torch.load('%s/%s-encA_epoch%s.rar' % (args.ckpt_path, MODEL_NAME, args.ckpt_epochs), map_location='cpu')\n\nfor e in range(args.ckpt_epochs, args.epochs):\n train_start = time.time()\n train_elbo, tr_acc, tr_pred = train(train_data, encA, optimizer)\n train_end = time.time()\n test_start = time.time()\n test_elbo, te_acc, te_pred = test(test_data, encA, e)\n test_end = time.time()\n\n val_start = time.time()\n val_elbo, val_acc, val_pred = test(val_data, encA, e)\n val_end = time.time()\n\n if args.viz_on:\n LINE_GATHER.insert(epoch=e,\n test_total_loss=test_elbo,\n val_total_loss=val_elbo,\n total_loss=train_elbo,\n train_acc=tr_acc,\n test_acc=te_acc,\n val_acc=val_acc,\n )\n visualize_line()\n LINE_GATHER.flush()\n\n if (e + 1) % 10 == 0 or e + 1 == args.epochs:\n save_ckpt(e + 1)\n print('[Epoch %d] Train: ELBO %.4e (%ds) Test: ELBO %.4e, test_acc %0.3f (%ds)' % (\n e, train_elbo, train_end - train_start,\n test_elbo, te_acc, test_end - test_start))\n\nsave_ckpt(args.epochs)\n","sub_path":"cub_reg_img_attr/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"641471596","text":"from geopy.geocoders import Nominatim\nimport json\nimport requests as rq\nfrom bs4 import BeautifulSoup\nheaders_={\n 'accept': 'application/xml, text/xml, */*',\n 'accept-encoding': 'gzip, deflate, br',\n 'accept-language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7',\n 'content-type': 'application/x-www-form-urlencoded',\n 'referer': 'https://www.gismeteo.ru/diary/206418/2015/10/',\n 'sec-ch-ua': '\"Chromium\";v=\"92\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"92\"',\n 'sec-ch-ua-mobile': '?0',\n 'sec-fetch-dest': 'empty',\n 'sec-fetch-mode': 'cors',\n 'sec-fetch-site': 'same-origin',\n 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36',\n 'x-requested-with': 'XMLHttpRequest'}\n\nwind_d = [\"--\", \"С\", \"З\", \"Ю\", \"В\", \"СЗ\", \"СВ\", \"ЮЗ\", \"ЮВ\"]\ncloud_t = [\"--\", \"sun-bw\", \"sunc-bw\", \"suncl-bw\", \"dull-bw\"]\nphen_t = [\"--\", \"rain-bw\", \"snow-bw\", \"storm-bw\"]\nf = open('parsed_districts.json', \"r\")\ncounty_codes = json.load(f)\n\ndef getWeather(lat, lon, year, month, day):\n\tgeolocator = Nominatim(user_agent=\"geoapiExercises\")\n\tlocation = geolocator.reverse(str(lon)+\",\"+str(lat))\n\tcounty = location.raw[\"address\"][\"county\"].replace(\" район\", \"\").replace(\"ое\", \"\").replace(\"ий\", \"\")\n\tprint(\" \"+county)\n\tcounty_code = -1\n\ttry:\n\t county_code = county_codes[location.raw[\"address\"][\"state\"]][county]\n\t print(county_code)\n\texcept:\n\t print(\"county_code not found!\")\n\t return False\n\tresponse = rq.get(\n\t\t\"https://www.gismeteo.ru/diary/\"+str(county_code)+\"/\"+str(year)+\"/\"+str(month)+\"/\",\n\t\theaders=headers_)\n\tsoup = BeautifulSoup(response.text, 'html.parser')\n\trows = soup.find(\"tbody\").find_all(\"tr\")\n\tresult = {}\n\tfor row in rows:\n\t\tif row.find(\"td\").text == str(day):\n\t\t\tcolls = row.find_all(\"td\")\n\t\t\tresult[\"temp\"] = colls[1].text\n\t\t\tresult[\"press\"] = colls[2].text\n\t\t\tresult[\"cloud\"] = 0\n\t\t\tfor i in cloud_t:\n\t\t\t\tif colls[3].prettify().find(i) != -1:\n\t\t\t\t\tresult[\"cloud\"] = cloud_t.index(i)\n\t\t\tresult[\"phen\"] = 0\n\t\t\tfor i in phen_t:\n\t\t\t\tif colls[4].prettify().find(i) != -1:\n\t\t\t\t\tresult[\"phen\"] = phen_t.index(i)\n\t\t\tresult[\"wind\"] = ''.join(x for x in colls[5].text if x.isdigit())\n\t\t\tbreak\n\treturn result","sub_path":"weather_parser/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"238077321","text":"'''\nhelper.py - provides misc. helper functions\nAuthor: Jordan\n\n'''\n\nimport requests\nimport settings\nimport datetime\nfrom time import sleep, strftime\nimport logging\nfrom tenacity import *\n\n\nr = requests.Session()\noriginalHeaders = {\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'\n}\n\n\n# tenacity api\n@retry(stop=stop_after_attempt(3), wait=wait_fixed(5) + wait_random(0, 2))\ndef download(url, headers=originalHeaders):\n r.headers.update(headers)\n\n sleep(4)\n log(\"downloading: \" + url + \" - \" + str(datetime.datetime.now()))\n response = r.get(url).text\n log(\"got response from \" + url)\n print(response)\n\n return response\n\n\ndef log(text, log_method='info'):\n '''\n log(text): Logs message to both STDOUT and to .output_log file\n\n '''\n\n # doing logging[log_method] throws \"has no attribute __getitem__\" exception\n getattr(logging,log_method)(text)\n with open(settings.log_file, 'a') as logfile:\n logfile.write(str(text) + '\\n')\n\n\ndef build_tweet(paste):\n '''\n build_tweet(url, paste) - Determines if the paste is interesting and, if so, builds and returns the tweet accordingly\n\n '''\n tweet = None\n if paste.match():\n tweet = paste.url\n if paste.type == 'db_dump':\n if paste.num_emails > 0:\n tweet += ' Emails: ' + str(paste.num_emails)\n if paste.num_hashes > 0:\n tweet += ' Hashes: ' + str(paste.num_hashes)\n if paste.num_hashes > 0 and paste.num_emails > 0:\n tweet += ' E/H: ' + str(round(\n paste.num_emails / float(paste.num_hashes), 2))\n tweet += ' Keywords: ' + str(paste.db_keywords)\n elif paste.type == 'google_api':\n tweet += ' Found possible Google API key(s)'\n elif paste.type in ['cisco', 'juniper']:\n tweet += ' Possible ' + paste.type + ' configuration'\n elif paste.type == 'ssh_private':\n tweet += ' Possible SSH private key'\n elif paste.type == 'honeypot':\n tweet += ' Dionaea Honeypot Log'\n elif paste.type == 'pgp_private':\n tweet += ' Found possible PGP Private Key'\n tweet += ' #infoleak'\n if paste.num_emails > 0:\n print(paste.emails)\n return tweet\n","sub_path":"lib/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":2336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"306106506","text":"class Solution:\n\tdef lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:\n\t\tmet = {}\n\t\tl, h = 0, 0\n\t\tres = 0\n\t\twhile h < len(s):\n\t\t\tif s[h] in met or len(met) < 2:\n\t\t\t\tmet[h] = met.get(h, 0) + 1\n\t\t\t\th += 1\n\t\t\t\tres = max(res, h - l)\n\t\t\telse:\n\t\t\t\twhile len(met) >= 2:\n\t\t\t\t\tmet[s[l]] -= 1\n\t\t\t\t\tif met[s[l]] == 0:\n\t\t\t\t\t\tdel met[s[l]]\n\t\t\t\t\tl += 1\n\t\treturn res\n\n","sub_path":"string/longest-substring-with-at-most-two-distinct-characters.py","file_name":"longest-substring-with-at-most-two-distinct-characters.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"285404852","text":"# coding=utf-8\n\"\"\"\n Created by Jegoo on 2019-01-10 15:29\n\"\"\"\nimport datetime\nimport wechatpy\n\nfrom wechatpy.events import *\nfrom wechatpy.messages import *\n\nfrom .utils import *\nfrom .model import *\n\n# from .db_handler import UserDao, GradeDao, ExerciseDao, RecordDao\n\n# 开发者ID(AppID)\nAPP_ID = 'wx6e6f16617daa4b58'\n# 开发者密码(AppSecret)\nAPP_SECRET = 'a3672b16a4dde63ad0655221a2d4ec94'\n# 微信服务\nwechat_client = wechatpy.WeChatClient(APP_ID, APP_SECRET)\n\nadmin_users = ['oejQe05i2ZF95lIMuPoAKzfTjkxA', 'oejQe0xeihIEcT0ukB6z8l_P0oVk']\n\n\ndef handle_event(event, root_url):\n \"\"\"\n 处理微信的事件\n :param root_url: 项目根url\n :param event: 解析后的事件\n :return:\n \"\"\"\n # 用户id,对应的微信open_id\n user_id = event.source\n user = WechatUser.get(user_id)\n\n # 关注事件\n if isinstance(event, SubscribeEvent):\n if user:\n grade = user.grade\n # 用户已登记,则返回登记信息,确定是否重新登记\n user.change_subscribe_state(user, True)\n content = '您已登记过学生信息,如下:\\n\\n学生姓名:{}\\n手机号码:{}\\n所属年级:{}({})' \\\n '\\n\\n如需重新登记,请回复“学生登记”;如需获取每日一题,请回复“每日一题”。' \\\n .format(user.student_name, user.phone_num, grade.name, grade.alias)\n return create_text_reply(event, content)\n else:\n # 还未登记,则发送登记链接\n title = '学生登记'\n image = '{}image/07.jpg'.format(root_url)\n url = '{}wechat/register?user_id={}'.format(root_url, event.source)\n return create_article_reply(event, title=title, image=image, url=url)\n\n if isinstance(event, UnsubscribeEvent):\n # 取消关注事件,改变user的关注状态\n user.change_subscribe_state(user, False)\n return create_text_reply(event, '感谢您的支持!')\n\n if isinstance(event, TextMessage):\n # 文本信息事件\n content = event.content\n\n if content == '每日一题':\n if user:\n grade = user.grade\n today = datetime.date.today()\n exercise = Exercise.get_by_date_grade(today, grade)\n if exercise:\n title = '{} {}({})每日一题'.format(get_today(), grade.name, grade.alias)\n image = '{}image/05.jpg'.format(root_url)\n url = '{}wechat/exercise?user_id={}&img_path={}&date={}'.format(root_url, user_id,\n exercise.image_path,\n exercise.release_date)\n # 添加领取每日一题记录\n now = datetime.datetime.now()\n Record.create(user, exercise, today, now)\n return create_article_reply(event, title=title, image=image, url=url, description='小坚持,大成长!')\n else:\n return create_text_reply(event, '今天的每日一题还没出炉呢,稍后再来或是联系老师吧!')\n else:\n return create_text_reply(event, '您还未登记学生信息,回复“学生登记”。')\n\n if content == '学生登记':\n title = '学生登记'\n image = '{}image/07.jpg'.format(root_url)\n url = '{}wechat/register?user_id={}'.format(root_url, event.source)\n return create_article_reply(event, title=title, image=image, url=url, description='学生信息录入')\n\n if content == '上传' and user_id in admin_users:\n title = '每日一题上传'\n image = '{}image/10.jpg'.format(root_url)\n url = '{}wechat/create_exe?user_id={}'.format(root_url, event.source)\n return create_article_reply(event, title=title, image=image, url=url, description='记得每天上传哦!')\n\n if content == '学生列表' and user_id in admin_users:\n user_list = WechatUser.get_all()\n user_info = '\\n'.join(\n ['{}\\t{}'.format(u.student_name, u.grade.description) for u in user_list])\n content = '姓名\\t年级\\n{}'.format(user_info)\n return create_text_reply(event, content)\n\n if content == '领取情况' and user_id in admin_users:\n today = datetime.date.today()\n user_list = WechatUser.get_all()\n data = []\n # 根据每个人的领取记录,如果有当天的记录,返回有\n for u in user_list:\n r_text = '×'\n for r in u.records:\n if r.r_date == today:\n r_text = '√'\n break\n data.append((u.student_name, r_text))\n info = '\\n'.join(['{}\\t{}'.format(d[0], d[1]) for d in data])\n content = '学生\\t领取情况\\n{}'.format(info)\n return create_text_reply(event, content)\n\n content = '如需学生登记,请回复“学生登记”;如需获取每日一题,请回复“每日一题”。'\n return create_text_reply(event, content)\n\n\ndef add_user(user_id, parent_name=None, student_name=None, wechat_name=None, grade_id=None,\n is_subscribe=None, student_sex=None, phone_num=None, register_time=None, remark=None):\n \"\"\"\n 新增用户\n :return:\n \"\"\"\n # grade = Grade.get(grade_id)\n if not register_time:\n register_time = datetime.datetime.now()\n WechatUser.create_or_update(user_id=user_id, parent_name=parent_name, student_name=student_name,\n wechat_name=wechat_name, grade_id=grade_id, is_subscribe=is_subscribe,\n student_sex=student_sex, phone_num=phone_num, register_time=register_time,\n remark=remark)\n\n\ndef get_grade_by_user_id(user_id):\n return WechatUser.get(user_id).grade\n\n\ndef get_grade_by_id(grade_id):\n return Grade.get(grade_id)\n\n\ndef add_exercise(release_date, grade, img_file):\n file_name = int(time.time())\n img_path = 'app/static/exercise_pic/{}.png'.format(file_name)\n img_file.save(img_path)\n now = datetime.datetime.now()\n return Exercise.create(release_date=release_date, grade=grade, image_path=img_path.replace('app/static/', ''),\n create_time=now)\n","sub_path":"app/wechat/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":6529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"51315790","text":"\"\"\"\nhomeassistant.components.light\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nProvides functionality to interact with lights.\n\nIt offers the following services:\n\nTURN_OFF - Turns one or multiple lights off.\n\nSupports following parameters:\n - transition\n Integer that represents the time the light should take to transition to\n the new state.\n - entity_id\n String or list of strings that point at entity_ids of lights.\n\nTURN_ON - Turns one or multiple lights on and change attributes.\n\nSupports following parameters:\n - transition\n Integer that represents the time the light should take to transition to\n the new state.\n\n - entity_id\n String or list of strings that point at entity_ids of lights.\n\n - profile\n String with the name of one of the built-in profiles (relax, energize,\n concentrate, reading) or one of the custom profiles defined in\n light_profiles.csv in the current working directory.\n\n Light profiles define a xy color and a brightness.\n\n If a profile is given and a brightness or xy color then the profile values\n will be overwritten.\n\n - xy_color\n A list containing two floats representing the xy color you want the light\n to be.\n\n - rgb_color\n A list containing three integers representing the xy color you want the\n light to be.\n\n - brightness\n Integer between 0 and 255 representing how bright you want the light to be.\n\n\"\"\"\n\nimport logging\nimport socket\nfrom datetime import datetime, timedelta\nfrom collections import namedtuple\nimport os\nimport csv\n\nimport homeassistant.util as util\nfrom homeassistant.components import (group, extract_entity_ids,\n STATE_ON, STATE_OFF,\n SERVICE_TURN_ON, SERVICE_TURN_OFF,\n ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME)\n\n\nDOMAIN = \"light\"\n\nGROUP_NAME_ALL_LIGHTS = 'all_lights'\nENTITY_ID_ALL_LIGHTS = group.ENTITY_ID_FORMAT.format(\n GROUP_NAME_ALL_LIGHTS)\n\nENTITY_ID_FORMAT = DOMAIN + \".{}\"\n\nMIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)\n\n# integer that represents transition time in seconds to make change\nATTR_TRANSITION = \"transition\"\n\n# lists holding color values\nATTR_RGB_COLOR = \"rgb_color\"\nATTR_XY_COLOR = \"xy_color\"\n\n# int with value 0 .. 255 representing brightness of the light\nATTR_BRIGHTNESS = \"brightness\"\n\n# String representing a profile (built-in ones or external defined)\nATTR_PROFILE = \"profile\"\n\nLIGHT_PROFILES_FILE = \"light_profiles.csv\"\n\n\ndef is_on(hass, entity_id=None):\n \"\"\" Returns if the lights are on based on the statemachine. \"\"\"\n entity_id = entity_id or ENTITY_ID_ALL_LIGHTS\n\n return hass.states.is_state(entity_id, STATE_ON)\n\n\n# pylint: disable=too-many-arguments\ndef turn_on(hass, entity_id=None, transition=None, brightness=None,\n rgb_color=None, xy_color=None, profile=None):\n \"\"\" Turns all or specified light on. \"\"\"\n data = {}\n\n if entity_id:\n data[ATTR_ENTITY_ID] = entity_id\n\n if profile:\n data[ATTR_PROFILE] = profile\n\n if transition is not None:\n data[ATTR_TRANSITION] = transition\n\n if brightness is not None:\n data[ATTR_BRIGHTNESS] = brightness\n\n if rgb_color:\n data[ATTR_RGB_COLOR] = rgb_color\n\n if xy_color:\n data[ATTR_XY_COLOR] = xy_color\n\n hass.call_service(DOMAIN, SERVICE_TURN_ON, data)\n\n\ndef turn_off(hass, entity_id=None, transition=None):\n \"\"\" Turns all or specified light off. \"\"\"\n data = {}\n\n if entity_id:\n data[ATTR_ENTITY_ID] = entity_id\n\n if transition is not None:\n data[ATTR_TRANSITION] = transition\n\n hass.call_service(DOMAIN, SERVICE_TURN_OFF, data)\n\n\n# pylint: disable=too-many-branches, too-many-locals\ndef setup(hass, light_control):\n \"\"\" Exposes light control via statemachine and services. \"\"\"\n\n logger = logging.getLogger(__name__)\n\n ent_to_light = {}\n light_to_ent = {}\n\n def _update_light_state(light_id, light_state):\n \"\"\" Update statemachine based on the LightState passed in. \"\"\"\n name = light_control.get_name(light_id) or \"Unknown Light\"\n\n try:\n entity_id = light_to_ent[light_id]\n except KeyError:\n # We have not seen this light before, set it up\n\n # Create entity id\n logger.info(\"Found new light {}\".format(name))\n\n entity_id = util.ensure_unique_string(\n ENTITY_ID_FORMAT.format(util.slugify(name)),\n list(ent_to_light.keys()))\n\n ent_to_light[entity_id] = light_id\n light_to_ent[light_id] = entity_id\n\n state_attr = {ATTR_FRIENDLY_NAME: name}\n\n if light_state.on:\n state = STATE_ON\n\n if light_state.brightness:\n state_attr[ATTR_BRIGHTNESS] = light_state.brightness\n\n if light_state.color:\n state_attr[ATTR_XY_COLOR] = light_state.color\n\n else:\n state = STATE_OFF\n\n hass.states.set(entity_id, state, state_attr)\n\n def update_light_state(light_id):\n \"\"\" Update the state of specified light. \"\"\"\n _update_light_state(light_id, light_control.get(light_id))\n\n # pylint: disable=unused-argument\n def update_lights_state(time, force_reload=False):\n \"\"\" Update the state of all the lights. \"\"\"\n\n # First time this method gets called, force_reload should be True\n if (force_reload or\n datetime.now() - update_lights_state.last_updated >\n MIN_TIME_BETWEEN_SCANS):\n\n logger.info(\"Updating light status\")\n update_lights_state.last_updated = datetime.now()\n\n for light_id, light_state in light_control.gets().items():\n _update_light_state(light_id, light_state)\n\n # Update light state and discover lights for tracking the group\n update_lights_state(None, True)\n\n if len(ent_to_light) == 0:\n logger.error(\"No lights found\")\n return False\n\n # Track all lights in a group\n group.setup(hass, GROUP_NAME_ALL_LIGHTS, light_to_ent.values())\n\n # Load built-in profiles and custom profiles\n profile_paths = [os.path.dirname(__file__), os.getcwd()]\n profiles = {}\n\n for dir_path in profile_paths:\n file_path = os.path.join(dir_path, LIGHT_PROFILES_FILE)\n\n if os.path.isfile(file_path):\n with open(file_path) as inp:\n reader = csv.reader(inp)\n\n # Skip the header\n next(reader, None)\n\n try:\n for profile_id, color_x, color_y, brightness in reader:\n profiles[profile_id] = (float(color_x), float(color_y),\n int(brightness))\n\n except ValueError:\n # ValueError if not 4 values per row\n # ValueError if convert to float/int failed\n logger.error(\n \"Error parsing light profiles from {}\".format(\n file_path))\n\n return False\n\n def handle_light_service(service):\n \"\"\" Hande a turn light on or off service call. \"\"\"\n # Get and validate data\n dat = service.data\n\n # Convert the entity ids to valid light ids\n light_ids = [ent_to_light[entity_id] for entity_id\n in extract_entity_ids(hass, service)\n if entity_id in ent_to_light]\n\n if not light_ids:\n light_ids = list(ent_to_light.values())\n\n transition = util.convert(dat.get(ATTR_TRANSITION), int)\n\n if service.service == SERVICE_TURN_OFF:\n light_control.turn_light_off(light_ids, transition)\n\n else:\n # Processing extra data for turn light on request\n\n # We process the profile first so that we get the desired\n # behavior that extra service data attributes overwrite\n # profile values\n profile = profiles.get(dat.get(ATTR_PROFILE))\n\n if profile:\n *color, bright = profile\n else:\n color, bright = None, None\n\n if ATTR_BRIGHTNESS in dat:\n bright = util.convert(dat.get(ATTR_BRIGHTNESS), int)\n\n if ATTR_XY_COLOR in dat:\n try:\n # xy_color should be a list containing 2 floats\n xy_color = dat.get(ATTR_XY_COLOR)\n\n if len(xy_color) == 2:\n color = [float(val) for val in xy_color]\n\n except (TypeError, ValueError):\n # TypeError if xy_color is not iterable\n # ValueError if value could not be converted to float\n pass\n\n if ATTR_RGB_COLOR in dat:\n try:\n # rgb_color should be a list containing 3 ints\n rgb_color = dat.get(ATTR_RGB_COLOR)\n\n if len(rgb_color) == 3:\n color = util.color_RGB_to_xy(int(rgb_color[0]),\n int(rgb_color[1]),\n int(rgb_color[2]))\n\n except (TypeError, ValueError):\n # TypeError if rgb_color is not iterable\n # ValueError if not all values can be converted to int\n pass\n\n light_control.turn_light_on(light_ids, transition, bright, color)\n\n # Update state of lights touched. If there was only 1 light selected\n # then just update that light else update all\n if len(light_ids) == 1:\n update_light_state(light_ids[0])\n else:\n update_lights_state(None, True)\n\n # Update light state every 30 seconds\n hass.track_time_change(update_lights_state, second=[0, 30])\n\n # Listen for light on and light off service calls\n hass.services.register(DOMAIN, SERVICE_TURN_ON,\n handle_light_service)\n\n hass.services.register(DOMAIN, SERVICE_TURN_OFF,\n handle_light_service)\n\n return True\n\n\nLightState = namedtuple(\"LightState\", ['on', 'brightness', 'color'])\n\n\ndef _hue_to_light_state(info):\n \"\"\" Helper method to convert a Hue state to a LightState. \"\"\"\n try:\n return LightState(info['state']['reachable'] and info['state']['on'],\n info['state']['bri'], info['state']['xy'])\n except KeyError:\n # KeyError if one of the keys didn't exist\n return None\n\n\nclass HueLightControl(object):\n \"\"\" Class to interface with the Hue light system. \"\"\"\n\n def __init__(self, host=None):\n logger = logging.getLogger(__name__)\n\n try:\n import phue\n except ImportError:\n logger.exception(\n \"HueLightControl:Error while importing dependency phue.\")\n\n self.success_init = False\n\n return\n\n try:\n self._bridge = phue.Bridge(host)\n except socket.error: # Error connecting using Phue\n logger.exception((\n \"HueLightControl:Error while connecting to the bridge. \"\n \"Is phue registered?\"))\n\n self.success_init = False\n\n return\n\n # Dict mapping light_id to name\n self._lights = {}\n self._update_lights()\n\n if len(self._lights) == 0:\n logger.error(\"HueLightControl:Could not find any lights. \")\n\n self.success_init = False\n else:\n self.success_init = True\n\n def _update_lights(self):\n \"\"\" Helper method to update the known names from Hue. \"\"\"\n try:\n self._lights = {int(item[0]): item[1]['name'] for item\n in self._bridge.get_light().items()}\n\n except (socket.error, KeyError):\n # socket.error because sometimes we cannot reach Hue\n # KeyError if we got unexpected data\n # We don't do anything, keep old values\n pass\n\n def get_name(self, light_id):\n \"\"\" Return name for specified light_id or None if no name known. \"\"\"\n if not light_id in self._lights:\n self._update_lights()\n\n return self._lights.get(light_id)\n\n def get(self, light_id):\n \"\"\" Return a LightState representing light light_id. \"\"\"\n try:\n info = self._bridge.get_light(light_id)\n\n return _hue_to_light_state(info)\n\n except socket.error:\n # socket.error when we cannot reach Hue\n return None\n\n def gets(self):\n \"\"\" Return a dict with id mapped to LightState objects. \"\"\"\n states = {}\n\n try:\n api = self._bridge.get_api()\n\n except socket.error:\n # socket.error when we cannot reach Hue\n return states\n\n api_states = api.get('lights')\n\n if not isinstance(api_states, dict):\n return states\n\n for light_id, info in api_states.items():\n state = _hue_to_light_state(info)\n\n if state:\n states[int(light_id)] = state\n\n return states\n\n def turn_light_on(self, light_ids, transition, brightness, xy_color):\n \"\"\" Turn the specified or all lights on. \"\"\"\n command = {'on': True}\n\n if transition is not None:\n # Transition time is in 1/10th seconds and cannot exceed\n # 900 seconds.\n command['transitiontime'] = min(9000, transition * 10)\n\n if brightness is not None:\n command['bri'] = brightness\n\n if xy_color:\n command['xy'] = xy_color\n\n self._bridge.set_light(light_ids, command)\n\n def turn_light_off(self, light_ids, transition):\n \"\"\" Turn the specified or all lights off. \"\"\"\n command = {'on': False}\n\n if transition is not None:\n # Transition time is in 1/10th seconds and cannot exceed\n # 900 seconds.\n command['transitiontime'] = min(9000, transition * 10)\n\n self._bridge.set_light(light_ids, command)\n","sub_path":"homeassistant/components/light/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":14000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"121089039","text":"# -*- coding=UTF-8 -*-\n# pyright: strict\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from . import go_out\n\nimport functools\nimport logging\nimport os\nfrom typing import Callable, List, Set, Text, Tuple, Type\n\nimport cast_unknown as cast\nimport cv2\nimport numpy as np\nfrom PIL.Image import Image\nfrom PIL.Image import fromarray as image_from_array\n\nfrom .. import imagetools, mathtools, ocr, scenes, template, templates, texttools\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass g:\n context_class: Type[Context]\n\n\ndef _ocr_date(img: Image) -> Tuple[int, int, int]:\n img = imagetools.resize(img, height=32)\n cv_img = np.asarray(img.convert(\"L\"))\n cv_img = imagetools.level(\n cv_img,\n np.array(10),\n np.array(240),\n )\n sharpened_img = imagetools.sharpen(cv_img)\n sharpened_img = imagetools.mix(sharpened_img, cv_img, 0.5)\n _, binary_img = cv2.threshold(sharpened_img, 120, 255, cv2.THRESH_BINARY_INV)\n imagetools.fill_area(binary_img, (0,), size_lt=4)\n\n if os.getenv(\"DEBUG\") == __name__:\n cv2.imshow(\"cv_img\", cv_img)\n cv2.imshow(\"sharpened_img\", sharpened_img)\n cv2.imshow(\"binary_img\", binary_img)\n cv2.waitKey()\n cv2.destroyAllWindows()\n\n text = ocr.text(image_from_array(binary_img))\n\n if texttools.compare(text, \"ジュニア級デビュー前\") > 0.8:\n return (1, 0, 0)\n if texttools.compare(text, \"ファイナルズ開催中\") > 0.8:\n return (4, 0, 0)\n year_end = text.index(\"級\") + 1\n month_end = year_end + text[year_end:].index(\"月\") + 1\n year_text = text[:year_end]\n month_text = text[year_end:month_end]\n date_text = text[month_end:]\n\n year_dict = {\"ジュニア級\": 1, \"クラシック級\": 2, \"シニア級\": 3}\n year = year_dict[texttools.choose(year_text, year_dict.keys())]\n month = int(month_text[:-1])\n date = {\"前半\": 1, \"後半\": 2}[date_text]\n return (year, month, date)\n\n\ndef _recognize_vitality(img: Image) -> float:\n cv_img = np.asarray(img)\n\n def _is_empty(v: np.ndarray) -> bool:\n assert v.shape == (3,), v.shape\n return (\n imagetools.compare_color((118, 117, 118), (int(v[0]), int(v[1]), int(v[2])))\n > 0.99\n )\n\n return 1 - np.average(np.apply_along_axis(_is_empty, 1, cv_img[0, :]))\n\n\ndef _recognize_mood(rgb_color: Tuple[int, int, int]) -> Tuple[float, float]:\n if imagetools.compare_color((250, 68, 126), rgb_color) > 0.9:\n return Context.MOOD_VERY_GOOD\n if imagetools.compare_color((255, 124, 57), rgb_color) > 0.9:\n return Context.MOOD_GOOD\n if imagetools.compare_color((255, 162, 0), rgb_color) > 0.9:\n return Context.MOOD_NORMAL\n if imagetools.compare_color((16, 136, 247), rgb_color) > 0.9:\n return Context.MOOD_BAD\n if imagetools.compare_color((170, 81, 255), rgb_color) > 0.9:\n return Context.MOOD_VERY_BAD\n raise ValueError(\"_recognize_mood: unknown mood color: %s\" % (rgb_color,))\n\n\ndef _recognize_fan_count(img: Image) -> int:\n cv_img = imagetools.cv_image(img.convert(\"L\"))\n cv_img = imagetools.level(\n cv_img, np.percentile(cv_img, 1), np.percentile(cv_img, 90)\n )\n _, binary_img = cv2.threshold(cv_img, 50, 255, cv2.THRESH_BINARY_INV)\n if os.getenv(\"DEBUG\") == __name__:\n cv2.imshow(\"cv_img\", cv_img)\n cv2.imshow(\"binary_img\", binary_img)\n cv2.waitKey()\n cv2.destroyAllWindows()\n text = ocr.text(imagetools.pil_image(binary_img))\n return int(text.rstrip(\"人\").replace(\",\", \"\"))\n\n\ndef _recognize_status(img: Image) -> Tuple[int, Text]:\n cv_img = imagetools.cv_image(imagetools.resize(img.convert(\"L\"), height=64))\n cv_img = imagetools.level(\n cv_img, np.percentile(cv_img, 5), np.percentile(cv_img, 95)\n )\n cv_img = cv2.copyMakeBorder(cv_img, 4, 4, 4, 4, cv2.BORDER_CONSTANT, value=(255,))\n\n blurred_img = cv2.medianBlur(cv_img, 7)\n\n text_img = cv2.adaptiveThreshold(\n blurred_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 15, -1\n )\n text_img = 255 - cast.instance(\n np.maximum(text_img, imagetools.border_flood_fill(text_img)), np.ndarray\n )\n text_img = cv2.medianBlur(text_img, 5)\n h = cv_img.shape[0]\n imagetools.fill_area(\n text_img, (0,), mode=cv2.RETR_LIST, size_lt=round(h * 0.2 ** 2)\n )\n\n if os.getenv(\"DEBUG\") == __name__:\n cv2.imshow(\"cv_img\", cv_img)\n cv2.imshow(\"blurred_img\", blurred_img)\n cv2.imshow(\"text_img\", text_img)\n cv2.waitKey()\n cv2.destroyAllWindows()\n\n text = ocr.text(imagetools.pil_image(text_img))\n for i in Context.ALL_STATUSES:\n if i[1] == text:\n return i\n\n raise ValueError(\"_recognize_status: unknown status: %s\" % text)\n\n\ndef _recognize_property(img: Image) -> int:\n img = imagetools.resize(img, height=32)\n max_match = imagetools.constant_color_key(\n imagetools.cv_image(img),\n (210, 249, 255),\n threshold=0.95,\n )\n if np.average(max_match) > 5:\n return 1200\n\n cv_img = np.asarray(img.convert(\"L\"))\n _, binary_img = cv2.threshold(cv_img, 160, 255, cv2.THRESH_BINARY_INV)\n imagetools.fill_area(binary_img, (0,), size_lt=3)\n if os.getenv(\"DEBUG\") == __name__:\n cv2.imshow(\"cv_img\", cv_img)\n cv2.imshow(\"binary_img\", binary_img)\n cv2.waitKey()\n cv2.destroyAllWindows()\n\n return int(ocr.text(imagetools.pil_image(binary_img)))\n\n\ndef _recognize_scenario(rp: mathtools.ResizeProxy, img: Image) -> Text:\n spec = (\n (templates.SINGLE_MODE_AOHARU_CLASS_DETAIL_BUTTON, Context.SCENARIO_AOHARU),\n (templates.SINGLE_MODE_CLASS_DETAIL_BUTTON, Context.SCENARIO_URA),\n )\n ret = Context.SCENARIO_UNKNOWN\n for tmpl, scenario in spec:\n try:\n next(template.match(img, tmpl))\n ret = scenario\n break\n except StopIteration:\n pass\n _LOGGER.debug(\"_recognize_scenario: %s\", ret)\n return ret\n\n\nclass Context:\n MOOD_VERY_BAD = (0.8, 0.95)\n MOOD_BAD = (0.9, 0.98)\n MOOD_NORMAL = (1.0, 1.0)\n MOOD_GOOD = (1.1, 1.05)\n MOOD_VERY_GOOD = (1.2, 1.1)\n\n CONDITION_HEADACHE = 1 << 0\n CONDITION_OVERWEIGHT = 1 << 1\n\n STATUS_S = (8, \"S\")\n STATUS_A = (7, \"A\")\n STATUS_B = (6, \"B\")\n STATUS_C = (5, \"C\")\n STATUS_D = (4, \"D\")\n STATUS_E = (3, \"E\")\n STATUS_F = (2, \"F\")\n STATUS_G = (1, \"G\")\n STATUS_NONE: Tuple[int, Text] = (0, \"\")\n\n ALL_STATUSES = (\n STATUS_S,\n STATUS_A,\n STATUS_B,\n STATUS_C,\n STATUS_D,\n STATUS_E,\n STATUS_F,\n STATUS_G,\n )\n\n # master.mdb\n # SELECT text FROM text_data WHERE category=119;\n SCENARIO_UNKNOWN = \"\"\n SCENARIO_URA = \"新設! URAファイナルズ!!\"\n SCENARIO_AOHARU = \"アオハル杯~輝け、チームの絆~\"\n\n @staticmethod\n def new() -> Context:\n return g.context_class()\n\n def __init__(self) -> None:\n self.speed = 0\n self.stamina = 0\n self.power = 0\n self.guts = 0\n self.wisdom = 0\n # (year, month, half-month), 1-base\n self.date = (0, 0, 0)\n self.vitality = 0.0\n self.max_vitality = 100\n self.mood = Context.MOOD_NORMAL\n self.conditions: Set[int] = set()\n self.fan_count = 0\n self.is_after_winning = False\n\n self._extra_turn_count = 0\n self.target_fan_count = 0\n self.race_turns: Set[int] = set()\n\n self.turf = Context.STATUS_NONE\n self.dart = Context.STATUS_NONE\n\n # Distance statuses\n # https://umamusume.cygames.jp/#/help?p=3\n # 短距離:1400m以下\n self.sprint = Context.STATUS_NONE\n # マイル:1401m~1800m\n self.mile = Context.STATUS_NONE\n # 中距���:1801m~2400m\n self.intermediate = Context.STATUS_NONE\n # 長距離:2401m以上\n self.long = Context.STATUS_NONE\n\n # Runing style status\n # https://umamusume.cygames.jp/#/help?p=3\n # 作戦には以下の4つがあります。\n # ・逃げ:スタート直後から先頭に立ち、そのまま最後まで逃げ切る作戦。\n self.lead = Context.STATUS_NONE\n # ・先行:なるべく前に付けて、先頭を狙っていく作戦。\n self.head = Context.STATUS_NONE\n # ・差し:後方につけ、レース後半に加速して先頭に立つ作戦。\n self.middle = Context.STATUS_NONE\n # ・追込:最後方に控え、最後に勝負をかける作戦。\n self.last = Context.STATUS_NONE\n\n self._next_turn_cb: List[Callable[[], None]] = []\n\n self.scene: scenes.Scene = scenes.UnknownScene()\n self.go_out_options: Tuple[go_out.Option, ...] = ()\n self.scenario = Context.SCENARIO_UNKNOWN\n\n def next_turn(self) -> None:\n if self.date in ((1, 0, 0), (4, 0, 0)):\n self._extra_turn_count += 1\n else:\n self._extra_turn_count = 0\n\n while self._next_turn_cb:\n self._next_turn_cb.pop()()\n _LOGGER.info(\"next turn: %s\", self)\n\n def defer_next_turn(self, cb: Callable[[], None]) -> None:\n self._next_turn_cb.append(cb)\n\n # TODO: refactor update_by_* to *Scene.recognize\n def update_by_command_scene(self, screenshot: Image) -> None:\n rp = mathtools.ResizeProxy(screenshot.width)\n if not self.scenario:\n self.scenario = _recognize_scenario(rp, screenshot)\n if not self.scenario:\n raise ValueError(\"unknown scenario\")\n date_bbox = {\n Context.SCENARIO_URA: rp.vector4((10, 27, 140, 43), 466),\n Context.SCENARIO_AOHARU: rp.vector4((125, 32, 278, 48), 540),\n }[self.scenario]\n vitality_bbox = rp.vector4((148, 106, 327, 108), 466)\n\n _, detail_button_pos = next(\n template.match(screenshot, templates.SINGLE_MODE_CHARACTER_DETAIL_BUTTON)\n )\n base_y = detail_button_pos[1] + rp.vector(71, 466)\n t, b = base_y, base_y + rp.vector(19, 466)\n speed_bbox = (rp.vector(45, 466), t, rp.vector(90, 466), b)\n stamina_bbox = (rp.vector(125, 466), t, rp.vector(162, 466), b)\n power_bbox = (rp.vector(192, 466), t, rp.vector(234, 466), b)\n guts_bbox = (rp.vector(264, 466), t, rp.vector(308, 466), b)\n wisdom_bbox = (rp.vector(337, 466), t, rp.vector(381, 466), b)\n\n self.date = _ocr_date(screenshot.crop(date_bbox))\n\n self.vitality = _recognize_vitality(screenshot.crop(vitality_bbox))\n\n # mood_pos change when vitality increase\n for index, mood_pos in enumerate(\n (\n rp.vector2((395, 113), 466),\n rp.vector2((473, 133), 540),\n )\n ):\n mood_color = screenshot.getpixel(mood_pos)\n assert isinstance(mood_color, tuple), mood_color\n try:\n self.mood = _recognize_mood(\n (mood_color[0], mood_color[1], mood_color[2])\n )\n break\n except ValueError:\n if index == 1:\n raise\n\n self.speed = _recognize_property(screenshot.crop(speed_bbox))\n self.stamina = _recognize_property(screenshot.crop(stamina_bbox))\n self.power = _recognize_property(screenshot.crop(power_bbox))\n self.guts = _recognize_property(screenshot.crop(guts_bbox))\n self.wisdom = _recognize_property(screenshot.crop(wisdom_bbox))\n\n def update_by_class_detail(self, screenshot: Image) -> None:\n rp = mathtools.ResizeProxy(screenshot.width)\n winning_color_pos = rp.vector2((150, 470), 466)\n fan_count_bbox = rp.vector4((220, 523, 420, 540), 466)\n\n self.is_after_winning = (\n imagetools.compare_color(\n screenshot.getpixel(winning_color_pos),\n (244, 205, 52),\n )\n > 0.95\n )\n\n self.fan_count = _recognize_fan_count(screenshot.crop(fan_count_bbox))\n\n def update_by_character_detail(self, screenshot: Image) -> None:\n rp = mathtools.ResizeProxy(screenshot.width)\n grass_bbox = rp.vector4((158, 263, 173, 280), 466)\n dart_bbox = rp.vector4((244, 263, 258, 280), 466)\n\n sprint_bbox = rp.vector4((158, 289, 173, 305), 466)\n mile_bbox = rp.vector4((244, 289, 258, 305), 466)\n intermediate_bbox = rp.vector4((329, 289, 344, 305), 466)\n long_bbox = rp.vector4((414, 289, 430, 305), 466)\n\n lead_bbox = rp.vector4((158, 316, 173, 332), 466)\n head_bbox = rp.vector4((244, 316, 258, 332), 466)\n middle_bbox = rp.vector4((329, 316, 344, 332), 466)\n last_bbox = rp.vector4((414, 316, 430, 332), 466)\n\n conditions_bbox = rp.vector4((13, 506, 528, 832), 540)\n\n self.turf = _recognize_status(screenshot.crop(grass_bbox))\n self.dart = _recognize_status(screenshot.crop(dart_bbox))\n\n self.sprint = _recognize_status(screenshot.crop(sprint_bbox))\n self.mile = _recognize_status(screenshot.crop(mile_bbox))\n self.intermediate = _recognize_status(screenshot.crop(intermediate_bbox))\n self.long = _recognize_status(screenshot.crop(long_bbox))\n\n self.lead = _recognize_status(screenshot.crop(lead_bbox))\n self.head = _recognize_status(screenshot.crop(head_bbox))\n self.middle = _recognize_status(screenshot.crop(middle_bbox))\n self.last = _recognize_status(screenshot.crop(last_bbox))\n\n self.conditions = _recognize_conditions(screenshot.crop(conditions_bbox))\n\n def __str__(self):\n msg = \"\"\n if self.go_out_options:\n msg += \",go_out=\"\n msg += \" \".join(\n (\n f\"{i.current_event_count}/{i.total_event_count}\"\n for i in self.go_out_options\n )\n )\n return (\n \"Context<\"\n f\"scenario={self.scenario},\"\n f\"turn={self.turn_count()},\"\n f\"mood={self.mood},\"\n f\"vit={self.vitality:.3f},\"\n f\"spd={self.speed},\"\n f\"sta={self.stamina},\"\n f\"pow={self.power},\"\n f\"gut={self.guts},\"\n f\"wis={self.wisdom},\"\n f\"fan={self.fan_count},\"\n f\"ground={''.join(i[1] for i in (self.turf, self.dart))},\"\n f\"distance={''.join(i[1] for i in (self.sprint, self.mile, self.intermediate, self.long))},\"\n f\"style={''.join(i[1] for i in (self.last, self.middle, self.head, self.lead))},\"\n f\"condition={functools.reduce(lambda a, b: a | b, self.conditions, 0)}\"\n f\"{msg}\"\n \">\"\n )\n\n def turn_count(self) -> int:\n if self.date == (1, 0, 0):\n return self._extra_turn_count\n if self.date == (4, 0, 0):\n return self._extra_turn_count + 24 * 3\n return (self.date[0] - 1) * 24 + (self.date[1] - 1) * 2 + (self.date[2] - 1)\n\n def total_turn_count(self) -> int:\n return 24 * 3 + 6\n\n def continuous_race_count(self) -> int:\n ret = 1\n turn = self.turn_count() - 1\n while turn in self.race_turns:\n ret += 1\n turn -= 1\n return ret\n\n @property\n def is_summer_camp(self) -> bool:\n return self.date[0] in (2, 3) and self.date[1:] in (\n (7, 1),\n (7, 2),\n (8, 1),\n (8, 2),\n )\n\n def expected_score(self) -> float:\n import warnings\n\n warnings.warn(\n \"expected score is deprecated, use rest/go-out command score instead\",\n DeprecationWarning,\n )\n\n expected_score = 15 + self.turn_count() * 10 / 24\n\n can_heal_condition = not self.is_summer_camp\n if self.vitality > 0.5:\n expected_score *= 0.5\n if self.turn_count() >= self.total_turn_count() - 2:\n expected_score *= 0.1\n if self.date[1:] in ((6, 1),) and self.vitality < 0.8:\n expected_score += 10\n if self.date[1:] in ((6, 2),) and self.vitality < 0.9:\n expected_score += 20\n if self.is_summer_camp and self.vitality < 0.8:\n expected_score += 10\n if self.date in ((4, 0, 0)):\n expected_score -= 20\n if can_heal_condition:\n expected_score += (\n len(\n set(\n (\n Context.CONDITION_HEADACHE,\n Context.CONDITION_OVERWEIGHT,\n )\n ).intersection(self.conditions)\n )\n * 20\n )\n expected_score += (self.MOOD_VERY_GOOD[0] - self.mood[0]) * 40 * 3\n\n return expected_score\n\n\ng.context_class = Context\n\n_CONDITION_TEMPLATES = {\n templates.SINGLE_MODE_CONDITION_HEADACHE: Context.CONDITION_HEADACHE,\n templates.SINGLE_MODE_CONDITION_OVERWEIGHT: Context.CONDITION_OVERWEIGHT,\n}\n\n\ndef _recognize_conditions(img: Image) -> Set[int]:\n ret: Set[int] = set()\n for tmpl, _ in template.match(\n img,\n *_CONDITION_TEMPLATES.keys(),\n ):\n ret.add(_CONDITION_TEMPLATES[tmpl.name])\n return ret\n","sub_path":"auto_derby/single_mode/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":17236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"75218520","text":"#!/usr/bin/python3\n\"\"\"Documentation\"\"\"\nfrom flask import Flask, jsonify, abort, make_response, request\nfrom api.v1.views import app_views\nfrom models.state import *\nfrom models.city import *\nfrom models import storage\n\n\n@app_views.route('/states//cities', methods=['GET', 'POST'],\n strict_slashes=False)\ndef cities_li(state_id):\n \"\"\"cities\"\"\"\n state = storage.get(State, state_id)\n if state is None:\n abort(404)\n\n if request.method == 'GET':\n cities_list = []\n\n for key, value in storage.all('City').items():\n if value.state_id == str(state_id):\n cities_list.append(value.to_dict())\n return jsonify(cities_list)\n\n if request.method == 'POST':\n data = request.get_json()\n if data is None:\n return (jsonify({\"error\": \"Not a JSON\"}), 400)\n if 'name' in data:\n data['state_id'] = state_id\n city = City(**data)\n city.save()\n data2 = storage.get(City, city.id).to_dict()\n return make_response(jsonify(data2), 201)\n return (jsonify({\"error\": \"Missing name\"}), 400)\n\n\n@app_views.route('/cities/', methods=['GET', 'DELETE', 'PUT'],\n strict_slashes=False)\ndef my_city(city_id):\n \"\"\"city\"\"\"\n city = storage.get(City, city_id)\n if city is None:\n abort(404)\n\n if request.method == 'GET':\n return jsonify(city.to_dict())\n\n if request.method == 'DELETE':\n storage.delete(city)\n storage.save()\n return jsonify({}), 200\n\n if request.method == 'PUT':\n data = request.get_json()\n if data is None:\n return (jsonify({\"error\": \"Not a JSON\"}), 400)\n ignorekey = ['id', 'created_at', 'updated_at']\n for key, value in data.items():\n if key not in ignorekey:\n setattr(city, key, value)\n city.save()\n return jsonify(city.to_dict()), 200\n","sub_path":"api/v1/views/cities.py","file_name":"cities.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"588496959","text":"\nimport pythongis as pg\n\nimport os\nimport sys\nimport datetime\nfrom random import uniform, seed\nimport math\nimport json\nimport codecs\nimport itertools\nimport multiprocessing as mp\nimport sqlite3\n\n\nprint(os.getcwd())\ntry:\n os.chdir('simulations')\nexcept:\n pass\n\n\n####################\n# FUNCTIONS\n\nseed(16) # random seed for replication purposes\n\n# select map region\ndef mapregion(center, extent, aspect):\n '''\n - center: lon,lat map center\n - extent: width of map in decimal degrees\n - aspect: height to width ratio\n '''\n lon,lat = center\n width = extent\n height = width * aspect\n bbox = [lon-width/2.0, lat-height/2.0, lon+width/2.0, lat+height/2.0]\n return bbox\n\n# check valid map region\ndef valid_mapregion(bbox):\n bw = abs(bbox[0]-bbox[2])\n bh = abs(bbox[1]-bbox[3])\n window_area = bw * bh\n crop = countries.manage.crop(bbox)\n crop = crop.aggregate(lambda f: 1, 'union')\n if len(crop):\n land = list(crop)[0].get_shapely()\n if (land.area / window_area) > 0.5:\n return True\n\n# sample n places within focus region\ndef _sampleplaces(bbox, n, distribution):\n '''\n Samples...\n '''\n print('sampling places within',bbox)\n #hits = list(places.quick_overlap(bbox))\n hits = pg.VectorData(fields=['name'])\n db = sqlite3.connect('data/gns.db')\n x1,y1,x2,y2 = bbox\n for names,x,y in db.execute('select names,x,y from data where (x between ? and ?) and (y between ? and ?)', (x1,x2,y1,y2)):\n name = names.split('|')[1] if '|' in names else names\n try: name.encode('latin')\n except: continue\n geoj = {'type':'Point', 'coordinates':(x,y)}\n hits.add_feature([name], geoj)\n print('possible places in map window',hits)\n\n if distribution == 'random':\n def samplefunc():\n while True:\n x = uniform(bbox[0], bbox[2])\n y = uniform(bbox[1], bbox[3])\n yield x,y\n\n elif distribution == 'dispersed':\n def samplefunc():\n while True:\n w = bbox[2]-bbox[0]\n h = bbox[3]-bbox[1]\n \n ## aspect_ratio = h/float(w)\n ## columns = math.sqrt(n/float(aspect_ratio))\n ## if not columns.is_integer():\n ## columns += 1\n ## columns = int(round(columns))\n ## rows = n/float(columns)\n ## if not rows.is_integer():\n ## rows += 1\n ## rows = int(round(rows))\n\n rows = columns = int(round(math.sqrt(n)))\n \n #print rows,columns\n\n dx = w / float(columns)\n dy = h / float(rows)\n \n for row in range(rows):\n y = bbox[1] + row*dy\n y += dy/2.0\n for col in range(columns):\n x = bbox[0] + col*dx\n x += dx/2.0\n yield x,y\n\n else:\n raise Exception('Distribution type {} is not a valid option'.format(distribution))\n\n itersamples = samplefunc()\n results = []\n\n if len(hits) > n:\n #radius = 2.0\n i = 0\n while True:\n x,y = next(itersamples) \n #bufbox = [x-radius, y-radius, x+radius, y+radius]\n def dist(f):\n fx,fy = f.geometry['coordinates']\n return math.hypot(x-fx, y-fy)\n sortplaces = sorted(hits, key=dist)\n for f in sortplaces: #intersection('geom', bufbox):\n #print '---'\n #print x,y\n #print bufbox\n #print r.bbox\n print('checking place', (x,y), f.row )\n if f in results:\n # dont yield same place multiple times\n continue\n i += 1\n results.append(f)\n yield f\n # yield only first match inside bbox, then break\n break\n if i >= n:\n break\n\n else:\n for f in hits:\n yield f\n\ndef project_bbox(bbox, fromcrs, tocrs):\n '''Take a bbox from one crs, convert to bbox in another crs, then convert back to the original crs'''\n def get_crs_transformer(fromcrs, tocrs):\n import pycrs\n \n if not (fromcrs and tocrs):\n return None\n \n if isinstance(fromcrs, basestring):\n fromcrs = pycrs.parse.from_unknown_text(fromcrs)\n\n if isinstance(tocrs, basestring):\n tocrs = pycrs.parse.from_unknown_text(tocrs)\n\n fromcrs = fromcrs.to_proj4()\n tocrs = tocrs.to_proj4()\n \n if fromcrs != tocrs:\n import pyproj\n fromcrs = pyproj.Proj(fromcrs)\n tocrs = pyproj.Proj(tocrs)\n def _project(points):\n xs,ys = itertools.izip(*points)\n xs,ys = pyproj.transform(fromcrs,\n tocrs,\n xs, ys)\n newpoints = list(itertools.izip(xs, ys))\n return newpoints\n else:\n _project = None\n\n return _project\n\n _transform = get_crs_transformer(fromcrs, tocrs)\n x1,y1,x2,y2 = bbox\n corners = [(x1,y1),(x1,y2),(x2,y2),(x2,y1)]\n corners = _transform(corners)\n xs,ys = zip(*corners)\n xmin,ymin,xmax,ymax = min(xs),min(ys),max(xs),max(ys)\n projbox = [xmin,ymin,xmax,ymax] \n return projbox\n\n\n# get map places\ndef get_mapplaces(bbox, quantity, distribution, uncertainty):\n '''\n - quantity: aka number of placenames\n - distribution: how placenames are distributed across map\n - random\n - dispersed\n - clustered\n - hierarchy ??? :\n - only big places\n - any small or big place\n '''\n # get places to be rendered in map\n mapplaces = pg.VectorData()\n mapplaces.fields = ['name']\n for f in _sampleplaces(bbox, quantity, distribution):\n #print f\n name = f['name'].title() #r['names'].split('|')[0]\n row = [name]\n x,y = f.geometry['coordinates']\n if uncertainty:\n x += uniform(-uncertainty, uncertainty)\n y += uniform(-uncertainty, uncertainty)\n geoj = {'type':'Point', 'coordinates':(x,y)}\n mapplaces.add_feature(row, geoj) #r['geom'].__geo_interface__)\n\n if len(mapplaces):\n mapplaces.create_spatial_index()\n \n return mapplaces\n\n# render map\ndef render_map(bbox, mapplaces, datas, resolution, regionopts, projection, anchoropts, textopts, metaopts):\n # determine resolution\n width = resolution\n height = int(width * regionopts['aspect'])\n \n # render pure map image\n m = pg.renderer.Map(width, height,\n title=metaopts['title'],\n titleoptions=metaopts['titleoptions'],\n #textoptions={'font':'eb garamond 12'},\n #textoptions={'font':'lato'},\n #textoptions={'font':'dejavu sans'},\n #textoptions={'font':'freesans'},\n background=(91,181,200),\n crs=projection)\n if metaopts['arealabels']:\n arealabels = {'text':lambda f: f['NAME'].upper(), 'textoptions': {'textsize':textopts['textsize']*1.5, 'textcolor':(88,88,88)}}\n rencountries = countries #.manage.crop(bbox)\n #rencountries.create_spatial_index()\n else:\n arealabels = {}\n rencountries = countries\n m.add_layer(rencountries, fillcolor=(255,222,173), outlinewidth=0.2, outlinecolor=(100,100,100),\n legendoptions={'title':'Country border'},\n **arealabels)\n\n for datadef in datas:\n if datadef:\n data,style = datadef\n m.add_layer(data, **style)\n \n m.add_layer(mapplaces,\n text=lambda f: f['name'],\n textoptions=textopts,\n legendoptions={'title':'Populated place'},\n **anchoropts)\n m.zoom_bbox(*bbox, geographic=True)\n\n if metaopts['legend']:\n legendoptions = {'padding':0, 'direction':'s'}\n legendoptions.update(metaopts['legendoptions'])\n m.add_legend(legendoptions=legendoptions)\n\n # note...\n\n m.render_all(antialias=True)\n\n return m\n\n# save map\ndef save_map(name, mapp, mapplaces, resolution, regionopts, placeopts, projection, anchoropts, textopts, metaopts, noiseopts):\n print('SAVING:',name)\n \n # downscale to resolution\n width,height = mapp.width, mapp.height\n ratio = noiseopts['resolution'] / float(width)\n newwidth = noiseopts['resolution']\n newheight = int(height * ratio)\n\n # save\n m = mapp\n imformat = noiseopts['format']\n saveargs = {}\n if imformat == 'jpg':\n saveargs['quality'] = 10\n\n # downsample to resolution\n #img = m.img.resize((newwidth, newheight), 1) # resize img separately using nearest neighbour resampling, since map resize uses antialias\n m = m.copy()\n m.resize(newwidth, newheight)\n\n # store rendering with original geo coordinates\n m.save('maps/{}_image.{}'.format(name, imformat), meta=True, **saveargs)\n #r = pg.RasterData(image=img, crs) \n #r.set_geotransform(affine=m.drawer.coordspace_invtransform) # inverse bc the drawer actually goes from coords -> pixels, we need pixels -> coords\n #r.save('maps/{}_image.{}'.format(name, imformat), **saveargs)\n\n # store the original place coordinates\n mapplaces = mapplaces.copy()\n #if projection:\n # mapplaces.manage.reproject(projection)\n mapplaces.add_field('col')\n mapplaces.add_field('row')\n mapplaces.add_field('x')\n mapplaces.add_field('y')\n for f in mapplaces:\n x,y = f.geometry['coordinates']\n col,row = m.drawer.coord2pixel(x,y)\n f['col'] = col\n f['row'] = row\n f['x'] = x\n f['y'] = y\n mapplaces.save('maps/{}_placenames.geojson'.format(name))\n\n # save options as json\n opts = dict(name=name,\n resolution=resolution,\n regionopts=regionopts,\n placeopts=placeopts,\n projection=projection,\n anchoropts=anchoropts,\n textopts=textopts,\n metaopts=metaopts,\n noiseopts=noiseopts,\n )\n with open('maps/{}_opts.json'.format(name), 'w') as fobj:\n fobj.write(json.dumps(opts))\n\ndef iteroptions(center, extent):\n regionopts = {'center':center, 'extent':extent, 'aspect':0.70744225834}\n bbox = mapregion(**regionopts)\n\n # loop placename options\n for quantity,distribution,uncertainty in itertools.product(quantities,distributions,uncertainties):\n\n # FIX PROJECTION...\n for projection in projections:\n\n## if projection:\n## lonlat = '+proj=longlat +datum=WGS84 +ellps=WGS84 +a=6378137.0 +rf=298.257223563 +pm=0 +nodef'\n## projbox = project_bbox(bbox, lonlat, projection)\n## placebox = project_bbox(projbox, projection, lonlat)\n## print('bbox to projbox and back',bbox,placebox)\n## else:\n## placebox = bbox\n\n # check enough placenames\n placeopts = {'quantity':quantity, 'distribution':distribution, 'uncertainty':uncertainty}\n mapplaces = get_mapplaces(bbox, **placeopts)\n if len(mapplaces) < 10: #quantity:\n print('!!! Not enough places, skipping')\n continue\n\n # loop rendering options\n for datas,meta in itertools.product(alldatas,metas):\n\n #projbox = project_bbox(bbox)\n \n metaopts = {'title':meta['title'], 'titleoptions':meta.get('titleoptions', {}), 'legend':meta['legend'], 'legendoptions':meta.get('legendoptions', {}), 'arealabels':meta['arealabels']}\n textopts = {'textsize':8, 'anchor':'sw', 'xoffset':0.5, 'yoffset':0}\n anchoropts = {'fillcolor':'black', 'fillsize':0.1}\n resolution = resolutions[0] # render at full resolution (downsample later)\n\n yield regionopts,bbox,placeopts,mapplaces,datas,projection,metaopts,textopts,anchoropts,resolution\n\ndef run(i, center, extent):\n subi = 1\n for opts in iteroptions(center, extent):\n regionopts,bbox,placeopts,mapplaces,datas,projection,metaopts,textopts,anchoropts,resolution = opts\n\n # render the map\n mapp = render_map(bbox,\n mapplaces,\n datas,\n resolution,\n regionopts=regionopts,\n projection=projection,\n anchoropts=anchoropts,\n textopts=textopts,\n metaopts=metaopts,\n )\n\n # loop image save options\n subsubi = 1\n for resolution,imformat in itertools.product(resolutions,imformats):\n\n name = 'sim_{}_{}_{}'.format(i, subi, subsubi)\n \n noiseopts = {'resolution':resolution, 'format':imformat}\n \n save_map(name, mapp, mapplaces, resolution, regionopts, placeopts, projection, anchoropts, textopts, metaopts, noiseopts)\n \n subsubi += 1\n\n subi += 1\n\ndef process(i, center, extent):\n logger = codecs.open('maps/sim_{}_log.txt'.format(i), 'w', encoding='utf8', buffering=0)\n sys.stdout = logger\n sys.stderr = logger\n print('PID:',os.getpid())\n print('time',datetime.datetime.now().isoformat())\n print('working path',os.path.abspath(''))\n\n run(i, center, extent)\n\n print('process finished, should exit')\n \n\n#######################\n# MISC TESTING\n\n# Test sampling distribution\n##def samplefunc(bbox, n):\n## if True:\n## w = bbox[2]-bbox[0]\n## h = bbox[3]-bbox[1]\n## \n#### aspect_ratio = h/float(w)\n#### columns = math.sqrt(n/float(aspect_ratio))\n#### if not columns.is_integer():\n#### columns += 1\n#### columns = int(round(columns))\n#### rows = n/float(columns)\n#### if not rows.is_integer():\n#### rows += 1\n#### rows = int(round(rows))\n##\n## rows = columns = int(round(math.sqrt(n)))\n## \n## print rows,columns\n##\n## dx = w / float(columns)\n## dy = h / float(rows)\n##\n#### r = pg.RasterData(mode='1bit', width=columns, height=rows,\n#### xscale=dx, yscale=dy, xoffset=bbox[0], yoffset=bbox[2])\n#### r.add_band()\n#### for cell in r.bands[0]:\n#### yield cell.point['coordinates']\n## \n## for row in range(rows):\n## y = bbox[1] + row*dy\n## y += dy/2.0\n## for col in range(columns):\n## x = bbox[0] + col*dx\n## x += dx/2.0\n## yield x,y\n##\n##import pyagg\n##c=pyagg.Canvas(1000,500)\n##bbox=0,0,100,100\n##c.custom_space(*bbox)\n##for x,y in samplefunc(bbox, 40):\n## print x,y\n## c.draw_circle((x,y))\n##c.view()\n##\n##sdfsdf\n\n\n\n\n####################\n# RUN\npg.vector.data.DEFAULT_SPATIAL_INDEX = 'quadtree'\n\n# load data (all processes)\nprint('loading data')\ncountries = pg.VectorData(\"data/ne_10m_admin_0_countries.shp\")\ncountries.create_spatial_index()\n#places = pg.VectorData(\"data/ne_10m_populated_places.shp\")\n#places.rename_field('NAME', 'name')\n#places = pg.VectorData(\"data/global_settlement_points_v1.01.shp\", encoding='latin')\n#places.rename_field('Name1', 'name')\n#places.create_spatial_index()\nrivers = pg.VectorData(\"data/ne_10m_rivers_lake_centerlines.shp\") \nrivers.create_spatial_index()\nurban = pg.VectorData(\"data/ne_10m_urban_areas.shp\") \nurban.create_spatial_index()\nroads = pg.VectorData(\"data/ne_10m_roads.shp\") \nroads.create_spatial_index()\n\n# options, NEW\n\n### text error\n##noise = imformat\n##mapnoise = datas\n##\n### error magnitude\n##scale = extent\n##resolution\n##\n### warp error\n##information = quantity\n##distribution\n##uncertainty = placeerror\n##textnoise = meta\n##distortion = projection\n\n# options\nprint('defining options')\nn = 25 # with 4 extents for each = 40\nextents = [10] + [50, 1, 0.1] # ca 5000km, 1000km, 100km, and 10km\nquantities = [80, 40, 20, 10]\ndistributions = ['dispersed', 'random'] # IMPROVE W NUMERIC\nuncertainties = [0, 0.01, 0.1, 0.5] # ca 0km, 1km, 10km, and 50km\nalldatas = [\n [], #(roads, {'fillcolor':(187,0,0), 'fillsize':0.08, 'legendoptions':{'title':'Roads'}}),], # no data layers\n [\n (rivers, {'fillcolor':(54,115,159), 'fillsize':0.08, 'legendoptions':{'title':'Rivers'}}), # three layers\n (urban, {'fillcolor':(209,194,151), 'legendoptions':{'title':'Urban area'}}),\n (roads, {'fillcolor':(187,0,0), 'fillsize':0.08, 'legendoptions':{'title':'Roads'}}),\n ],\n ]\nprojections = [None, # lat/lon\n #'+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +a=6378137 +b=6378137 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs', #'+init=EPSG:3857', # Web Mercator\n #'+proj=moll +datum=WGS84 +ellps=WGS84 +a=6378137.0 +rf=298.257223563 +pm=0 +lon_0=0 +x_0=0 +y_0=0 +units=m +axis=enu +no_defs', #'+init=ESRI:54009', # World Mollweide\n '+proj=robin +datum=WGS84 +ellps=WGS84 +a=6378137.0 +rf=298.257223563 +pm=0 +lon_0=0 +x_0=0 +y_0=0 +units=m +axis=enu +no_defs', #'+init=ESRI:54030', # Robinson\n ]\nresolutions = [3000, 2000, 1000] #, 750] #, 4000]\nimformats = ['png','jpg']\nmetas = [{'title':'','legend':False,'arealabels':False}, # nothing\n {'title':'This is the Map Title','titleoptions':{'fillcolor':'white'},'legend':True,'legendoptions':{'fillcolor':'white'},'arealabels':True}, # text noise + meta boxes (arealabels + title + legend)\n #{'title':'This is the Map Title','titleoptions':{'fillcolor':None},'legend':True,'legendoptions':{'fillcolor':None},'arealabels':True}, # text noise (arealabels + title + legend)\n #{'title':'This is the Map Title','titleoptions':{'fillcolor':'white'},'legend':True,'legendoptions':{'fillcolor':'white'},'arealabels':False}, # meta boxes (title + legend)\n ]\n\n# main process handler\nif __name__ == '__main__':\n\n maxprocs = 2\n procs = []\n\n print('combinations per region', len(list(itertools.product(quantities,distributions,uncertainties,alldatas,projections,metas,resolutions,imformats))))\n\n # begin\n \n # zoom regions\n i = 1\n while i < n:\n center = (uniform(-170,170),uniform(-70,70))\n for extent in extents:\n print('-------')\n print('REGION:',i,center,extent)\n\n # check enough land before sending to process\n regionopts = {'center':center, 'extent':extent, 'aspect':0.70744225834}\n bbox = mapregion(**regionopts)\n if not valid_mapregion(bbox):\n print('!!! Not enough land area, skipping')\n continue\n \n #run(i,center,extent)\n\n # Begin process\n p = mp.Process(target=process,\n args=(i, center, extent),\n )\n p.start()\n procs.append(p)\n\n # Wait for next available process\n while len(procs) >= maxprocs:\n for p in procs:\n if not p.is_alive():\n procs.remove(p)\n\n i += 1\n \n\n \n\n\n\n\n \n\n\n\n","sub_path":"simulations/1) generate maps.py","file_name":"1) generate maps.py","file_ext":"py","file_size_in_byte":19538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"198557244","text":"'''\n给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。\n\n示例 1:\n\n输入: n = 12\n输出: 3\n解释: 12 = 4 + 4 + 4.\n示例 2:\n\n输入: n = 13\n输出: 2\n解释: 13 = 4 + 9.\n'''\n\n\nclass Solution:\n def numSquares(self, n: int) -> int:\n # https://leetcode-cn.com/problems/coin-change/ 基本一模一样\n # BFS 比DP速度快多了\n queue = [(n, 0)]\n seen = {n} # 只记录n就行了,因为是BFS 所以最先出现的长度肯定小于等于后来出现的\n # seen = {(n, 0)}\n while queue:\n cur, step = queue.pop(0)\n residuals = [x ** 2 for x in range(1, int(cur ** 0.5) + 1)]\n for i in residuals:\n new_cur = cur - i\n new_step = step + 1\n if new_cur == 0:\n return new_step\n if new_cur not in seen:\n queue.append((new_cur, new_step))\n seen.add(new_cur)\n return -1\n\n # 递归dp 6000ms\n residuals = [x ** 2 for x in range(1, int(n ** 0.5) + 1)]\n\n @functools.lru_cache(None)\n def dp(state):\n if state == 0:\n return 0\n res = float(\"inf\")\n for i in residuals:\n if i > state:\n return res\n if i <= state:\n res = min(res, 1 + dp(state - i))\n return res\n\n return dp(n)\n\n # DP table\n # https://leetcode-cn.com/problems/perfect-squares/solution/chao-zhi-bai-kao-zui-jiang-xiao-xue-sheng-du-neng-/\n dp = [float(\"inf\") for i in range(n + 1)]\n dp[0] = 0\n for i in range(1, n + 1):\n for j in range(1, int(i ** 0.5) + 1):\n dp[i] = min(dp[i], dp[i - j * j] + 1) # dpi表示i需要多少个平方数表示 其实就是N = 1、2、4、9... + N’ 一个数=一个平方数+另一个数\n return dp[-1]\n\n '''\n # DFS 超时\n self.res = float(\"inf\")\n self.ans = []\n def backtrack(track):\n if len(track) >= self.res: return\n if sum(track) == n:\n self.res = min(self.res, len(track))\n if self.res == len(track):\n self.ans = track[:]\n return\n diff = n - sum(track)\n for i in range(int(sqrt(diff)), 0, -1):\n track.append(i ** 2)\n backtrack(track)\n track.pop()\n backtrack([])\n # print(self.res, self.ans)\n return self.res\n '''","sub_path":"03_DP问题/背包问题零钱问题/279. 完全平方数(和322一模一样).py","file_name":"279. 完全平方数(和322一模一样).py","file_ext":"py","file_size_in_byte":2670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"394425963","text":"# coding: utf-8\n# Copyright 2013 The Font Bakery 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# See AUTHORS.txt for the list of Authors and LICENSE.txt for the License.\nimport unittest\n\nfrom bakery_cli import utils\n\n\nclass TestCase(unittest.TestCase):\n\n def failure_run(self, test_klass, test_method=None):\n result = _run_font_test(test_klass, test_method)\n\n if result.errors:\n self.fail(result.errors[0][1])\n\n self.assertTrue(bool(result.failures))\n\n def success_run(self, test_klass, test_method=None):\n result = _run_font_test(test_klass, test_method)\n\n if result.errors:\n self.fail(result.errors[0][1])\n\n if result.failures:\n self.fail(result.failures[0][1])\n\n self.assertFalse(bool(result.failures))\n\n\ndef _run_font_test(testcase_klass, test_method):\n from bakery_lint.base import BakeryTestRunner, BakeryTestResult\n runner = BakeryTestRunner(resultclass=BakeryTestResult)\n tests = unittest.defaultTestLoader.loadTestsFromTestCase(testcase_klass)\n\n suite = unittest.TestSuite()\n for i, test in enumerate(tests):\n if test_method and test._testMethodName != test_method:\n continue\n suite.addTest(test)\n return runner.run(suite)\n\n\nclass TestSuggestNameTestCase(TestCase):\n\n def test_suggest_name_testcase_bold_italic(self):\n fontdata = {\n 'names': [\n {'nameID': 1, 'string': 'Roboto'},\n ],\n 'OS/2': {\n 'fsSelection': 0b10001, # Bold & Italic\n # As font is Bold this value is always 700\n 'usWeightClass': 700,\n },\n 'post': {\n 'italicAngle': -13\n },\n 'head': {\n 'macStyle': 0b11, # Bold & Italic\n },\n 'CFF': {\n 'Weight': 400, # This value have to be fixed to 700\n }\n }\n fontdata = utils.fix_all_names(fontdata, 'Roboto')\n self.assertEqual(fontdata['OS/2']['usWeightClass'], 700)\n self.assertEqual(fontdata['CFF']['Weight'],\n fontdata['OS/2']['usWeightClass'])\n self.assertEqual([\n [1, 'Roboto'],\n [2, 'Bold Italic'],\n [4, 'Roboto Bold Italic'],\n [6, 'Roboto-BoldItalic'],\n [16, 'Roboto'],\n [17, 'Bold Italic'],\n [18, 'Roboto Bold Italic']], [[x['nameID'], x['string']]\n for x in fontdata['names']])\n\n def test_suggest_name_testcase_light(self):\n\n fontdata = {\n 'names': [\n {'nameID': 1, 'string': 'Roboto'},\n ],\n 'OS/2': {\n 'fsSelection': 0, # Regular\n 'usWeightClass': 300, # Light\n },\n 'post': {\n 'italicAngle': 0\n },\n 'head': {\n 'macStyle': 0, # Regular\n },\n 'CFF': {\n 'Weight': 400, # This value have to be fixed to 300\n }\n }\n fontdata = utils.fix_all_names(fontdata, 'Roboto')\n self.assertEqual(fontdata['OS/2']['usWeightClass'], 300)\n self.assertEqual(fontdata['CFF']['Weight'],\n fontdata['OS/2']['usWeightClass'])\n self.assertEqual([\n [1, 'Roboto Light'],\n [2, 'Regular'],\n [4, 'Roboto Light'],\n [6, 'Roboto-Light'],\n [16, 'Roboto'],\n [17, 'Light'],\n [18, 'Roboto Light']], [[x['nameID'], x['string']]\n for x in fontdata['names']])\n\n def test_suggest_name_testcase_light_italic(self):\n\n fontdata = {\n 'names': [\n {'nameID': 1, 'string': 'Roboto'},\n ],\n 'OS/2': {\n 'fsSelection': 0b00001, # Regular\n 'usWeightClass': 300, # Light\n },\n 'post': {\n 'italicAngle': -13\n },\n 'head': {\n 'macStyle': 0b10, # Italic\n },\n 'CFF': {\n 'Weight': 400, # This value have to be fixed to 300\n }\n }\n fontdata = utils.fix_all_names(fontdata, 'Roboto')\n self.assertEqual(fontdata['OS/2']['usWeightClass'], 300)\n self.assertEqual(fontdata['CFF']['Weight'],\n fontdata['OS/2']['usWeightClass'])\n self.assertEqual([\n [1, 'Roboto Light'],\n [2, 'Italic'],\n [4, 'Roboto Light Italic'],\n [6, 'Roboto-LightItalic'],\n [16, 'Roboto'],\n [17, 'Light Italic'],\n [18, 'Roboto Light Italic']], [[x['nameID'], x['string']]\n for x in fontdata['names']])\n\n def test_suggest_name_testcase_light_bold(self):\n\n fontdata = {\n 'names': [\n {'nameID': 1, 'string': 'Roboto'},\n ],\n 'OS/2': {\n 'fsSelection': 0b10000, # Regular\n 'usWeightClass': 700, # Bold\n },\n 'head': {\n 'macStyle': 0b01, # Italic\n },\n 'post': {\n 'italicAngle': 0\n },\n 'CFF': {\n 'Weight': 400, # This value have to be fixed to 300\n }\n }\n fontdata = utils.fix_all_names(fontdata, 'Roboto')\n self.assertEqual(fontdata['OS/2']['usWeightClass'], 700)\n self.assertEqual(fontdata['CFF']['Weight'],\n fontdata['OS/2']['usWeightClass'])\n self.assertEqual([\n [1, 'Roboto'],\n [2, 'Bold'],\n [4, 'Roboto Bold'],\n [6, 'Roboto-Bold'],\n [16, 'Roboto'],\n [17, 'Bold'],\n [18, 'Roboto Bold']], [[x['nameID'], x['string']]\n for x in fontdata['names']])\n\n def test_suggest_name_testcase_black(self):\n\n fontdata = {\n 'names': [\n {'nameID': 1, 'string': 'Family'},\n ],\n 'OS/2': {\n 'fsSelection': 0b00000, # Regular\n 'usWeightClass': 900, # Bold\n },\n 'head': {\n 'macStyle': 0b00, # Italic\n },\n 'post': {\n 'italicAngle': 0\n },\n 'CFF': {\n 'Weight': 400, # This value have to be fixed to 300\n }\n }\n fontdata = utils.fix_all_names(fontdata, 'Family')\n self.assertEqual(fontdata['OS/2']['usWeightClass'], 900)\n self.assertEqual(fontdata['CFF']['Weight'],\n fontdata['OS/2']['usWeightClass'])\n self.assertEqual([\n [1, 'Family Black'],\n [2, 'Regular'],\n [4, 'Family Black'],\n [6, 'Family-Black'],\n [16, 'Family'],\n [17, 'Black'],\n [18, 'Family Black']], [[x['nameID'], x['string']]\n for x in fontdata['names']])\n","sub_path":"tests/test_lint.py","file_name":"test_lint.py","file_ext":"py","file_size_in_byte":7623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"370238608","text":"from tilse.data.timelines import Timeline\n\nfrom utils import iter_dirs, iter_files\nimport argparse\nimport os\n\nfrom collections import defaultdict\n\nimport random\n\nimport csv\n\n\ndef vectorize_timelines(all_timelines, max_tls=None):\n all_tl_keys = set()\n\n for system_name, topic in all_timelines.items():\n for topic_name, topic_tls in topic.items():\n for tl_name in topic_tls:\n all_tl_keys.add((topic_name, tl_name))\n\n if max_tls is not None:\n all_tl_keys = list(all_tl_keys)\n random.shuffle(all_tl_keys)\n all_tl_keys = all_tl_keys[:max_tls]\n\n\n #print(all_tl_keys)\n\n all_tl_keys = sorted(all_tl_keys)\n\n vectorized_timelines = {}\n for system_name, topic in all_timelines.items():\n local_timelines = []\n for topic_name, tl_name in all_tl_keys:\n local_timelines.append((topic_name, tl_name, topic[topic_name][tl_name]))\n vectorized_timelines[system_name] = local_timelines\n\n return vectorized_timelines\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n #parser.add_argument(\"human_tl_dir\")\n parser.add_argument(\"system_tl_dir\")\n\n parser.add_argument(\"relevant_systems\", nargs=\"+\")\n\n parser.add_argument(\"outfile\")\n\n args = parser.parse_args()\n relevant_systems = set(args.relevant_systems)\n\n all_relevant_timelines = defaultdict(lambda: defaultdict(dict))\n\n for directory in iter_dirs(args.system_tl_dir):\n system_name = os.path.basename(directory)\n for tl_dir in iter_dirs(directory):\n for tlfilename in iter_files(tl_dir, \".txt\"):\n #print(system_name, relevant_systems)\n if system_name in relevant_systems:\n with open(tlfilename) as tlfile:\n all_relevant_timelines[system_name][os.path.basename(tl_dir)][os.path.basename(tlfilename)] = Timeline.from_file(tlfile)\n\n #for directory in iter_dirs(args.human_tl_dir):\n # source_name = os.path.basename(directory)\n # for tlfilename in iter_files(directory, \".txt\"):\n # with open(tlfilename, errors='ignore') as tlfile:\n # all_relevant_timelines[\"human\"][source_name][os.path.basename(tlfilename)] = Timeline.from_file(tlfile)\n\n vectorized_timelines = vectorize_timelines(all_relevant_timelines)\n\n num_samples_per_tl = 5\n\n all_samples = []\n for system, timelines in vectorized_timelines.items():\n system_samples = set()\n for topic_name, tl_name, timeline in timelines:\n sentences = [sent.replace(\"-RRB-\", \")\").replace(\"-LRB-\", \"(\").capitalize() for date in timeline for sent in timeline[date] if len(sent) > 0]\n num_samples = min(num_samples_per_tl, len(sentences))\n system_samples.update([(sample, system, topic_name, tl_name) for sample in random.sample(sentences, num_samples)])\n\n if len(system_samples) < num_samples_per_tl * len(timelines):\n all_possible_system_samples = set()\n for topic_name, tl_name, timeline in timelines:\n for sample in [sent.replace(\"-RRB-\", \")\").replace(\"-LRB-\", \"(\").capitalize() for date in timeline for sent in timeline[date] if len(sent) > 0]:\n all_possible_system_samples.add((sample, system, topic_name, tl_name))\n\n print(len(list(all_possible_system_samples)))\n\n all_possible_system_samples -= system_samples\n\n print(len(list(all_possible_system_samples)))\n\n print(min(len(system_samples) - num_samples_per_tl * len(timelines), len(all_possible_system_samples)))\n\n system_samples.update(random.sample(list(all_possible_system_samples), min(num_samples_per_tl * len(timelines) -len(system_samples), len(all_possible_system_samples))))\n\n\n all_samples.extend(system_samples)\n\n random.shuffle(all_samples)\n\n with open(args.outfile, 'w', encoding=\"utf8\") as csvfile:\n writer = csv.writer(csvfile)\n for sample in all_samples:\n writer.writerow(sample)\n","sub_path":"tlgraphsum/tlexport_annotation.py","file_name":"tlexport_annotation.py","file_ext":"py","file_size_in_byte":4023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"610305078","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nimport weakref\n\nclass CarModel:\n\n\t_models = weakref.WeakValueDictionary()\n\n\tdef __new__(cls, model_name, *args, **kwargs):\n\t\tmodel = cls._models.get(model_name)\n\n\t\tif not model:\n\t\t\tmodel = super().__new__(cls)\n\t\t\tcls._models[model_name] = model\n\n\t\treturn model\n\n\n\tdef __init__(self, model_name, \n\t\t\tair = False,\n\t\t\ttilt = False, \n\t\t\tcruise_control = False,\n\t\t\tpower_locks = False,\n\t\t\talloy_wheels = False,\n\t\t\tusb_charger = False):\n\t\tif not hasattr(self, \"initted\"):\n\t\t\tself.model_name = model_name\n\t\t\tself.air = air\n\t\t\tself.tilt = tilt\n\t\t\tself.cruise_control = cruise_control\n\t\t\tself.power_locks = power_locks\n\t\t\tself.alloy_wheels = alloy_wheels\n\t\t\tself.usb_charger = usb_charger\n\t\t\tself.initted = True\n\n\tdef check_serial(self, serial_number):\n\t\tprint(\"Sorroy, we are unable to check the serial number {0} and the {1} at this time\".format(serial_number, self.model_name))\n\n\nclass Car:\n\tdef __init__(self, model, color, serial):\n\t\tself.model = model\n\t\tself.color = color\n\t\tself.serial = serial\n\n\n\tdef check_serial(self):\n\t\treturn self.model.check_serial(self.serial)\n\n\n\ndef main():\n\tprint(\"hello, test share mode\")\n\n\n\tdx = CarModel(\"FIT DX\")\n\tlx = CarModel(\"FIT LX\", air = True, cruise_control = True, power_locks= True, tilt = True)\n\n\tcar1 = Car(dx, \"blue\", \"123456\")\n\tcar2 = Car(dx, \"green\", \"123654\")\n\tcar3 = Car(lx, \"red\", \"123465\")\n\n\tprint(\"id(dx) = {}\".format(id(dx)))\n\tprint(\"id(lx) = {}\".format(id(lx)))\n\n\tdel lx\n\tdel car3\n\timport gc\n\tprint(gc.collect())\n\n\tlx = CarModel(\"FIT LX\", air = True, cruise_control = True, power_locks= True, tilt = True)\n\n\tprint(\"id(dx) = {}\".format(id(dx)))\n\tprint(\"id(lx) = {}\".format(id(lx)))\n\n\tlx = CarModel(\"FIT LX\")\n\n\tprint(\"id(dx) = {}\".format(id(dx)))\n\tprint(\"id(lx) = {}\".format(id(lx)))\n\n\tprint(\"car air: {} \".format(lx.air))\n\n\n\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"python/test/t_sharemode.py","file_name":"t_sharemode.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"262790438","text":"\"\"\"\n\nFind the character in first string that is present at minimum index in second string\nGiven a string str and another string patt. Find the character in patt that is present at the minimum index in str. If no character of patt is present in str then print ‘No character present’.\n\nExamples:\n\nInput: str = “geeksforgeeks”, patt = “set”\nOutput: e\nBoth e and s of patt are present in str,\nbut e is present at minimum index, which is 1.\n\nInput: str = “adcffaet”, patt = “onkl”\nOutput: No character present\n\n\"\"\"\n\n# Python3 implementation to find the character in\n# first that is present at minimum index\n# in second String\nimport sys\n# function to find the minimum index character\ndef printMinIndexChar(str1, patt):\n n_str1=len(str1)\n n_pat=len(patt)\n min_index= sys.maxsize\n for i in range(n_pat):\n for j in range(n_str1):\n if(patt[i]==str1[j] and jmax_val:\n\t\t\tmax_val = val\n\t\t\tmax_index = i\n\tmax_row = matrix[max_index]\n\n\tclustering = []\n\tcluster_again = True\n\tclustered_indices = []\n\t##finds blocks (or clusters) of the rows in matrix until all rows\n\t##are in at least one block\n\twhile cluster_again:\n\t\tblock =[]\n\t\tblock_indices = []\n\t\t##finds all rows that have 1s in at least half of the same\n\t\t##columns as max_row, puts them in block, and puts their\n\t\t##indices in block_indices\n\t\tfor i in range(len(matrix)):\n\t\t\tval = 0\n\t\t\tfor j in range(len(matrix[i])):\n\t\t\t\tif max_row[j]==matrix[i][j]:\n\t\t\t\t\tif matrix[i][j]==1:\n\t\t\t\t\t\tval+=1\n\t\t\tif val>=max_val/2:\n\t\t\t\tblock.append(matrix[i])\n\t\t\t\tblock_indices.append(i)\n\t\t##checks to see if the new block is a subset of an existing cluster\n\t\t##in clustering or vice-versa\n\t\tx = set(block_indices)\n\t\tneed_to_remove = []\n\t\tadd = True\n\t\tfor clust in clustering:\n\t\t\ty = set(clust)\n\t\t\tif y.issubset(x):\n\t\t\t\t##if an existing block in clustering is a subset of the new\n\t\t\t\t##block, then it is added to the need_to_remove list in\n\t\t\t\t##order to be removed from clustering\n\t\t\t\tneed_to_remove.append(list(y))\n\t\t\tif x.issubset(y):\n\t\t\t\t##if the new block is a subset of an existing block in\n\t\t\t\t##clustering, then the block is not added to clustering\n\t\t\t\tadd = False\n\t\tfor remove_clust in need_to_remove:\n\t\t\tclustering.remove(remove_clust)\n\t\tif add:\n\t\t\t##adds the block_indices to the clustering list\n\t\t\tclustering.append(block_indices)\n\t\t\t##adds any new row indices\n\t\t\tclustered_indices = list(set(clustered_indices + block_indices))\n\t\t\t##checks if all rows are in at least one block\n\t\tif len(clustered_indices)==matrix_len:\n\t\t\tcluster_again = False\n\t\telse:\n\t\t\t##removes all rows that are in block from freq_d\n\t\t\tfor i in clustered_indices:\n\t\t\t\tif i in freq_d:\n\t\t\t\t\tdel freq_d[i]\n\t\t\t##finds new row with most 1s from rows in matrix\n\t\t\t##that are not already in a block\n\t\t\t##finds new max_row if freq_d entries are dictionaries\n\t\t\tmax_val, max_key = max_val_in_dict_finder(freq_d, False, 1)\n\t\t\tmax_row = matrix[max_key]\n\n\t##creates a new list called clustering_by_name that gives the\n\t##information in clustering by node name instead of node index\n\t##in nodes list\n\tclustering_by_name = []\n\tfor block in clustering:\n\t\tnew_block = []\n\t\tfor node_index in block:\n\t\t\tnode = nodes[node_index]\n\t\t\tnew_block.append(node)\n\t\tclustering_by_name.append(new_block)\n\treturn clustering, clustering_by_name\n\n##takes a matrix as input and adds 1's to the diagonal\ndef self_loop_adder(matrix):\n\tfor i in range(len(matrix)):\n\t\tfor j in range(len(matrix[i])):\n\t\t\tif i==j:\n\t\t\t\tmatrix[i][j] = 1\n\treturn matrix\n\nif __name__=='__main__':\n\tmain()","sub_path":"toy_clustering_alg_freq_based.py","file_name":"toy_clustering_alg_freq_based.py","file_ext":"py","file_size_in_byte":4630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"587686978","text":"from django.shortcuts import get_object_or_404, render\nfrom django.contrib.auth.models import User\nfrom .models import Post\n\n\ndef post_list(request):\n posts = Post.objects.all().order_by(\"-date\")[:25]\n return render(request, 'blog/blog.html', {\n 'posts': posts,\n 'navColor': 'red',\n })\n\n\ndef show_post(request, post_id):\n user = User.objects.filter(username='john')\n post = get_object_or_404(Post, id=post_id)\n return render(request, 'blog/post.html', {\n 'post': post,\n 'user': user,\n })\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"271622314","text":"#!/usr/bin/env python\n\n# Copyright (c) 2019 Intel Corporation\n#\n# This work is licensed under the terms of the MIT license.\n# For a copy, see .\n\n\"\"\"\nThis module provides the key configuration parameters for a route-based scenario\n\"\"\"\n\nimport carla\nfrom agents.navigation.local_planner import RoadOption\n\nfrom srunner.scenarioconfigs.scenario_configuration import ScenarioConfiguration\n\n\nclass RouteConfiguration(object):\n\n \"\"\"\n This class provides the basic configuration for a route\n \"\"\"\n\n def __init__(self, route=None):\n self.data = route\n\n def parse_xml(self, node):\n \"\"\"\n Parse route config XML\n \"\"\"\n self.data = []\n\n for waypoint in node.iter(\"waypoint\"):\n x = float(waypoint.attrib.get('x', 0))\n y = float(waypoint.attrib.get('y', 0))\n z = float(waypoint.attrib.get('z', 0))\n c = waypoint.attrib.get('connection', '')\n connection = RoadOption[c.split('.')[1]]\n\n self.data.append((carla.Location(x, y, z), connection))\n\n\nclass TargetConfiguration(object):\n\n \"\"\"\n This class provides the basic configuration for a target location\n \"\"\"\n\n transform = None\n\n def __init__(self, node):\n pos_x = float(node.attrib.get('x', 0))\n pos_y = float(node.attrib.get('y', 0))\n pos_z = float(node.attrib.get('z', 0))\n\n self.transform = carla.Transform(carla.Location(x=pos_x, y=pos_y, z=pos_z))\n\n\nclass RouteScenarioConfiguration(ScenarioConfiguration):\n\n \"\"\"\n Basic configuration of a RouteScenario\n \"\"\"\n\n def __init__(self, route_description, scenario_file):\n\n self.other_actors = []\n self.ego_vehicles = []\n self.trigger_points = []\n\n self.name = \"RouteScenario_{}\".format(route_description['id'])\n self.town = route_description['town_name']\n self.route_description = route_description\n\n self.scenario_file = scenario_file\n","sub_path":"carla_rllib/carla_rllib-prak_evaluator-carla_rllib-prak_evaluator/carla_rllib/prak_evaluator/srunner/scenarioconfigs/scenarioconfigs/route_scenario_configuration.py","file_name":"route_scenario_configuration.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"395045031","text":"#In the name of God\n# -*- coding: cp1256 -*-\n# -*- coding: utf-8 -*-\n#!usr/bin/env python\n\nimport wx\nimport games1\n\n\nclass gimframe(wx.Frame):\n def __init__(self,parent):\n wx.Frame.__init__(self,parent,style=wx.FRAME_FLOAT_ON_PARENT|wx.DEFAULT_FRAME_STYLE)\n \n self.parent = parent\n\n \n \n panel = games1.MyPanel1(self)\n \n def closeit(self):\n self.Close(True) \n \ndef size():\n return (360,310)\n\ndef main(panel=None ):\n locale = wx.Locale(wx.LANGUAGE_ENGLISH)\n \n parent = panel.GetParent()\n \n frame = gimframe(parent )\n frame.SetTitle(u'بازي')\n frame.SetSize((360,310))\n frame.Show() \n\n\n\nif __name__ == '__main__':\n main()\n \n","sub_path":"gamenet31/GUI/Input/gim1.py","file_name":"gim1.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"357027805","text":"# -*- coding: utf-8 -*-\n\"\"\"Function for DCGAN model class delaration\nThis module includes the DCGAN model\n\nExample:\n model = GAN(args)\n # args should contain z_dim, layer_G, layer_D, use_batchnorm, use_relu\n model.G\n model.D\n\n__author__ = '{Jimmy Yeh}'\n__email__ = '{marrch30@gmail.com}'\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass VGG(nn.Module):\n def __init__(self, vgg_name='VGG11'):\n super(VGG, self).__init__()\n self.cfg = {\n 'VGG11':[64,'M',128,'M',256,256,'M',512,512,'M',512,512,'M']\n }\n self.features = self._make_layers(self.cfg[vgg_name])\n self.classifier = nn.Linear(2048,10)\n \n def forward(self, x):\n out = self.features(x)\n out = out.view(out.size(0), -1)\n out = self.classifier(out)\n \n return out\n \n def _make_layers(self, cfg):\n layers = []\n in_channels = 1\n for x in cfg:\n if x == 'M':\n layers += [nn.MaxPool2d(kernel_size=2,stride=2)]\n else:\n layers += [nn.Conv2d(in_channels, x, kernel_size=3, padding=1),\n nn.BatchNorm2d(x),\n nn.ReLU(inplace=True)]\n in_channels = x\n layers += [nn.AvgPool2d(kernel_size=1, stride=1)]\n return nn.Sequential(*layers)\n\n def save(self, filepath):\n state = {\n 'feat': self.features.state_dict(),\n 'class': self.classifier.state_dict()\n }\n torch.save(state, filepath)\n\n def load(self, filepath):\n state = torch.load(filepath)\n self.features.load_state_dict(state['features']) \n self.classifier.load_state_dict(state['classifier']) \n\n\n#https://github.com/yunjey/pytorch-tutorial/blob/master/tutorials/02-intermediate/deep_residual_network/main.py\n# ---------------------------------------------------------------------------- #\n# An implementation of https://arxiv.org/pdf/1512.03385.pdf #\n# See section 4.2 for the model architecture on CIFAR-10 #\n# Some part of the code was referenced from below #\n# https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py #\n# ---------------------------------------------------------------------------- #\n\n# num_epochs = 80\n# learning_rate = 0.001\n\n# transform = transforms.Compose([\n# transforms.Pad(4),\n# transforms.RandomHorizontalFlip(),\n# transforms.RandomCrop(32),\n# transforms.ToTensor()])\n\n\n# 3x3 convolution\ndef conv3x3(in_channels, out_channels, stride=1):\n return nn.Conv2d(in_channels, out_channels, kernel_size=3, \n stride=stride, padding=1, bias=False)\n\n# Residual block\nclass ResidualBlock(nn.Module):\n def __init__(self, in_channels, out_channels, stride=1, downsample=None):\n super(ResidualBlock, self).__init__()\n self.conv1 = conv3x3(in_channels, out_channels, stride)\n self.bn1 = nn.BatchNorm2d(out_channels)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(out_channels, out_channels)\n self.bn2 = nn.BatchNorm2d(out_channels)\n self.downsample = downsample\n \n def forward(self, x):\n residual = x\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n out = self.conv2(out)\n out = self.bn2(out)\n if self.downsample:\n residual = self.downsample(x)\n out += residual\n out = self.relu(out)\n return out\n\n# ResNet\nclass ResNet(nn.Module):\n def __init__(self, block=ResidualBlock, layers=[2,2,2], num_classes=10):\n super(ResNet, self).__init__()\n self.in_channels = 16\n self.conv = conv3x3(1, 16)\n self.bn = nn.BatchNorm2d(16)\n self.relu = nn.ReLU(inplace=True)\n self.layer1 = self.make_layer(block, 16, layers[0], 2)\n self.layer2 = self.make_layer(block, 32, layers[1], 2)\n self.layer3 = self.make_layer(block, 64, layers[2], 2)\n self.avg_pool = nn.AvgPool2d(8)\n self.fc = nn.Linear(64, num_classes)\n \n def make_layer(self, block, out_channels, blocks, stride=1):\n downsample = None\n if (stride != 1) or (self.in_channels != out_channels):\n downsample = nn.Sequential(\n conv3x3(self.in_channels, out_channels, stride=stride),\n nn.BatchNorm2d(out_channels))\n layers = []\n layers.append(block(self.in_channels, out_channels, stride, downsample))\n self.in_channels = out_channels\n for i in range(1, blocks):\n layers.append(block(out_channels, out_channels))\n return nn.Sequential(*layers)\n \n def forward(self, x):\n out = self.conv(x)\n out = self.bn(out)\n out = self.relu(out)\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.avg_pool(out)\n out = out.view(out.size(0), -1)\n out = self.fc(out)\n return out\n \n\nclass Inception(nn.Module):\n pass\n\n","sub_path":"past_src/01inspections/module/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"265002107","text":"\"\"\"\nclass BinaryTreeNode(object):\n\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n def insert_left(self, value):\n self.left = BinaryTreeNode(value)\n return self.left\n\n def insert_right(self, value):\n self.right = BinaryTreeNode(value)\n return self.right\n\"\"\"\n\n\ndef is_balanced(tree_root):\n # if tree_root does not have a left and right child\n if tree_root.left is None and tree_root.right is None:\n return True\n\n # initialize stack to empty list\n stack = []\n # initialize depths to empty list\n depths = []\n # push node and depth as a zero onto stack as a tuple\n stack.append((tree_root, 0))\n\n # while stack is not empty\n while len(stack):\n # pop the node and depth from stack\n node, depth = stack.pop()\n\n # if current node does not have a left and right child\n # that is, the node is a leaf node\n if node.left is None and node.right is None:\n # only add new depth to the depth list\n # if depth is not in depths\n if depth not in depths:\n # append to the depth list\n # append depth onto the depths list\n depths.append(depth)\n\n # if depths is longer that two or absolute difference between\n # the two depths is greater than one\n if len(depths) > 2 or (len(depths) == 2 and abs(depths[0] - depths[1]) > 1):\n # return False\n return False\n\n # if there is a left child\n if node.left is not None:\n # push the left node and its depth plus one onto the stack\n stack.append((node.left, 1 + depth))\n\n # if there is a right child\n if node.right is not None:\n # push the right node and its depth plus one onto the stack\n stack.append((node.right, 1 + depth))\n\n # return True\n return True\n","sub_path":"trees_and_graphs/is_balanced.py","file_name":"is_balanced.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"261157845","text":"'''\n simulationLogic.py\n'''\nfrom utility import Connector\nimport data_model\nimport Queue\nimport random\nimport datetime\n# # Might need to move this to simulator eventually\n\nDEPARTURE_TYPE = 0\nARRIVAL_TYPE = 1\n\nclass SimulationLogic:\n\n def __init__(self, session):\n # For database connectivity\n self.session = session\n # self.time is a datetime, representing the current time in the simulator.\n self.time = None\n # {stID : station's bike count at self.time}\n self.stations = {}\n # Pending departures/arrivals includes tuples (endTime, trip)\n self.pending_departures = Queue.PriorityQueue()\n self.pending_arrivals = Queue.PriorityQueue()\n # Contains all resolved trips\n self.trip_list = []\n # List of trips that didn't end at the desired station due to a shortage\n self.bike_shortages = []\n self.dock_shortages = []\n \n\n def initialize(self, start_time):\n '''Sets states of stations at the start_time'''\n self.time = start_time\n # Stations should eventually be gotten from the database\n self.pending_departures = Queue.PriorityQueue()\n self.pending_arrivals = Queue.PriorityQueue()\n self.dock_shortages = []\n self.bike_shortages = []\n self.trip_list = []\n self.stations = {}\n self.initialize_stations(start_time)\n #for s in self.stations:\n # print s, self.stations[s]\n\n def initialize_stations(self, start_time):\n '''Sets initial bike count for each station.'''\n queried_stations = self.session.query(data_model.Station)\n for s in queried_stations:\n # For now, generates a random count that is less than or equal to the station's capacity.\n count = random.randint(0,s.capacity)\n self.stations[s.id] = count\n \n\n def update(self, timestep):\n '''Moves the simulation forward one timestep from given time'''\n self.time += timestep\n self.generate_new_trips(self.time)\n self.resolve_trips()\n\n \n def generate_new_trips(self, timestep):\n '''Generates trips COMPLETELY RANDOMLY WOOO'''\n \n for station in self.stations:\n num_trips = random.randint(0,self.stations[station])\n for i in range(num_trips):\n end_station_ID = random.choice(self.stations.keys())\n start_time = self.time + datetime.timedelta(minutes=random.randint(0, timestep.total_seconds()/60))\n # Nobody takes longer than 2 hours to bike anywhere, duh!\n end_time = start_time + datetime.timedelta(minutes=random.randint(0, 120))\n new_trip = data_model.Trip(str(random.randint(1,500)), \"Casual\", \"Produced\", start_time, end_time, station, end_station_ID)\n\n self.pending_departures.put((start_time, new_trip))\n\n # print \"GENERATED\", printTrip(new_trip)\n\n # # TESTING\n # printedQueue = Queue.PriorityQueue()\n # print \"PENDING TRIPS at time %s:\" % str(self.time)\n # for i in range(self.pending_arrivals.qsize()):\n # pq_trip = self.pending_arrivals.get()\n # print pq_trip\n # printedQueue.put(pq_trip)\n # self.pending_arrivals = printedQueue\n\n\n def resolve_trips(self):\n '''Resolves departures & arrivals within the current time interval'''\n # Get the first event, be it a departure or arrival.\n eventTuple = self.get_first_trip_event()\n eventType = eventTuple[0]\n trip = eventTuple[1]\n while eventType != None:\n if eventType == DEPARTURE_TYPE:\n if trip.start_date > self.time:\n # Put trip back in proper queue if it's over the time, and stop the while loop\n self.pending_departures.put((trip.start_date, trip))\n break\n else:\n # print \"Resolving departure for \\t\", printTrip(trip)\n self.resolve_departure(trip)\n elif eventType == ARRIVAL_TYPE:\n if trip.end_date > self.time:\n self.pending_arrivals.put((trip.end_date, trip))\n break\n else:\n # print \"Resolving arrival for \\t\\t\", printToisson.ppf(.3,mu)rip(trip)\n self.resolve_arrival(trip)\n # print \"If dock shortage, new trip is\", printTrip(trip)\n\n eventTuple = self.get_first_trip_event()\n eventType = eventTuple[0]\n trip = eventTuple[1]\n \n # #TESTING\n # print \"PENDING DEPARTURES at time %s:\" % str(self.time)\n # printedQueue = Queue.PriorityQueue()\n # for i in range(self.pending_departures.qsize()):\n # pq_trip = self.pending_departures.get()\n # print printTrip(pq_trip[1])\n # printedQueue.put(pq_trip)\n # self.pending_departures = printedQueue\n # print \"PENDING ARRIVALS at time %s:\" % str(self.time)\n # printedQueue = Queue.PriorityQueue()\n # for i in range(self.pending_arrivals.qsize()):\n # pq_trip = self.pending_arrivals.get()\n # print printTrip(pq_trip[1])\n # printedQueue.put(pq_trip)\n # self.pending_arrivals = printedQueue\n # print \"RESOLVED TRIPS at time %s:\" % str(self.time)\n # for i in self.trip_list:\n # print printTrip(i)\n\n\n def resolve_departure(self, trip):\n '''Decrement station count, put in pending_arrivals queue. If station is empty, put it in the bike_shortages list.'''\n departure_station_ID = trip.start_station_id\n if self.stations[departure_station_ID] == 0:\n self.bike_shortages.append(trip)\n self.resolve_sad_departure(trip)\n else:\n self.stations[departure_station_ID] -= 1\n self.pending_arrivals.put((trip.end_date, trip))\n\n \n def resolve_sad_departure(self, trip):\n '''When you want a bike but the station is empty'''\n pass\n\n def resolve_arrival(self, trip):\n '''Increment station count, put in trips list. If desired station is full, put it in the dock_shortages list and try again.'''\n arrival_station_ID = trip.end_station_id\n capacity = 5\n if self.stations[arrival_station_ID] == capacity:\n self.dock_shortages.append(trip)\n self.resolve_sad_arrival(trip)\n else:\n self.stations[arrival_station_ID] += 1\n self.trip_list.append(trip)\n\n\n def resolve_sad_arrival(self, trip):\n '''When you want to drop off a bike but the station is full'''\n # Randomly choose another station to try to park at, at a random time (< 2hrs) from now.\n trip.end_station_id = random.choice(self.stations.keys())\n trip.end_date += datetime.timedelta(minutes=random.randint(1, 120))\n self.pending_arrivals.put((trip.end_date, trip))\n\n\n def get_first_trip_event(self):\n '''Returns a tuple for the first departure or arrival's trip including (type of event, trip). Type of event is either departure, arrival, or None.'''\n if self.pending_departures.empty() and self.pending_arrivals.empty():\n trip = None\n eventType = None\n elif self.pending_arrivals.empty():\n trip = self.pending_departures.get()[1]\n eventType = DEPARTURE_TYPE\n elif self.pending_departures.empty():\n trip = self.pending_arrivals.get()[1]\n eventType = ARRIVAL_TYPE\n else:\n first_departure = self.pending_departures.get()[1]\n first_arrival = self.pending_arrivals.get()[1]\n # If a departure and arrival happen at the exact same time, departures resolve first. This decision was completely arbitrary.\n if (first_departure.start_date <= first_arrival.end_date):\n trip = first_departure\n eventType = DEPARTURE_TYPE\n self.pending_arrivals.put((first_arrival.end_date, first_arrival))\n else:\n trip = first_arrival\n eventType = ARRIVAL_TYPE\n self.pending_departures.put((first_departure.start_date, first_departure))\n return (eventType, trip)\n\n\n def flush(self, to_database=False):\n '''Returns list of all trips since initialization, or adds them to the database if to_database is True'''\n if to_database:\n for trip in self.trip_list:\n self.session.add(trip)\n session.commit()\n else:\n return self.trip_list\n\n\n def cleanup(self):\n pass\n\n\n# FOR TESTING\ndef printTrip(trip):\n return str(trip.start_station_id) + \"-->\" + str(trip.end_station_id) + \": \" + str(trip.start_date) + \" --> \" + str(trip.end_date)\n\n\ndef main():\n SL = SimulationLogic()\n start_time = datetime.datetime(2013, 1, 1, 0, 0, 0)\n SL.initialize(start_time)\n step = datetime.timedelta(minutes=30)\n SL.update(step)\n SL.update(step)\n trips = SL.flush()\n # print \"ALL TRIPS:\"\n # for trip in trips:\n # print printTrip(trip)\n \n\nif __name__ == \"__main__\":\n main()\n","sub_path":"simulationLogic.py","file_name":"simulationLogic.py","file_ext":"py","file_size_in_byte":9231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"404263343","text":"# doubly linked list\n\nclass Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n self.prev = None\n\nclass Linked_List:\n def __init__(self):\n self.head = None\n self.tail = None\n self.size = 0\n \n def append(self, data):\n if self.head is None and self.tail is None:\n new_node = Node(data)\n new_node.prev = None\n new_node.next = None\n self.head = self.tail = new_node\n self.size = self.size +1\n else:\n oldtail = self.tail\n new_node = Node(data)\n self.tail = new_node\n self.tail.prev = oldtail\n oldtail.next = self.tail\n self.size = self.size +1\n\n\n def prepend(self, data):\n if self.tail is None and self.head is None:\n new_node = Node(data)\n new_node.prev = None\n new_node.next = None\n self.head = self.tail = new_node\n self.size = self.size +1\n else:\n oldHead = self.head\n new_node = Node(data)\n self.head = new_node\n self.head.next = oldHead\n self.head.prev = None\n self.size = self.size + 1\n\n \n def print_list(self):\n cur = self.head\n while cur:\n print(cur.data)\n cur = cur.next\n\nplaylist = Linked_List()\nplaylist.append('Windows96 - dashville')\nplaylist.append('Lenny Kravitz - Heaven Help')\nplaylist.prepend('Beyonce - Single Ladies')\nprint('\\n')\nplaylist.print_list()\n\n ","sub_path":"python_data_structures/linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"171312880","text":"# Write a class to hold player information, e.g. what room they are in\n# currently.\n\nclass Player:\n def __init__(self, name, current_room, inventory=[]):\n self.name = name\n self.current_room = current_room\n self.inventory = inventory\n\n def __str__(self):\n output = \"\"\n output += f\"You,{self.name}, have {len(self.inventory)} items in your inventory\"\n return output\n\n def show_inv(self):\n inv = \"\\nYour invetory:\\n\"\n inventoryNumber = 1\n for e in self.inventory:\n inv += f\"\\n{inventoryNumber}. {e.name} - {e.description}\"\n inventoryNumber += 1\n print(inv)","sub_path":"src/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"540456846","text":"# -*- coding: utf-8 -*-\n#\n# Poio Corpus\n#\n# Copyright (C) 2009-2013 Poio Project\n# Author: Peter Bouda \n# URL: \n# For license information, see LICENSE.TXT\n\nimport os\nimport sys\nimport urllib2\nimport urlparse\nimport optparse\nimport datetime\nimport dateutil.parser\nfrom zipfile import ZipFile\ntry:\n import xml.etree.cElementTree as ET\nexcept ImportError:\n import xml.etree.ElementTree as ET\n\nimport requests\n\ndef main(argv):\n usage = \"usage: %prog [options]\"\n parser = optparse.OptionParser(usage=usage, version=\"%prog 0.1\")\n parser.add_option(\"-n\", \"--newer\", action=\"store_true\", dest=\"newer\",\n default=False,\n help=\"Only download files when they are newer than local files\")\n parser.add_option(\"-f\", \"--force\", action=\"store_true\", dest=\"force\",\n default=False, help=\"Overwrite existing local files\")\n (options, _) = parser.parse_args()\n\n url = \"http://s3.amazonaws.com/poiocorpus\"\n xml_page = urllib2.urlopen(url)\n tree = ET.ElementTree(file=xml_page)\n root = tree.getroot()\n\n static_data_path = os.path.join(\"src\", \"main\", \"static\")\n\n for contents in root.findall(\n \"{http://s3.amazonaws.com/doc/2006-03-01/}Contents\"):\n key = contents.find(\"{http://s3.amazonaws.com/doc/2006-03-01/}Key\")\n file_url = key.text\n print(file_url)\n if \"/\" in file_url:\n subdir, filename = file_url.split(\"/\")\n else:\n continue\n date = contents.find(\"{http://s3.amazonaws.com/doc/2006-03-01/}LastModified\")\n server_date = dateutil.parser.parse(date.text)\n\n target_path = os.path.join(static_data_path, subdir, filename)\n print(\"Processing file {0}...\".format(filename))\n download = False\n if options.force:\n download = True\n elif not os.path.exists(target_path):\n download = True\n if not options.newer and os.path.exists(target_path):\n print(\" file already exists, skipping.\")\n elif options.newer and os.path.exists(target_path):\n local_date = datetime.datetime.fromtimestamp(\n os.path.getmtime(target_path))\n server_date = server_date.replace(tzinfo=None)\n if local_date < server_date:\n download = True\n else:\n print(\" local file found and is up-to-date, skipping.\")\n\n if download:\n download_url = url + \"/\" + file_url\n print(\" downloading from {0}...\".format(download_url))\n r = requests.get(download_url, stream=True)\n with open(target_path, \"wb\") as f:\n for chunk in r.iter_content(1024):\n f.write(chunk)\n\n if filename.endswith(\".sqlite.zip\"):\n print(\" unzipping file...\")\n myzip = ZipFile(target_path, \"r\")\n myzip.extractall(os.path.join(static_data_path, subdir))\n myzip.close()\n os.remove(target_path)\n\nif __name__ == \"__main__\":\n main(sys.argv)","sub_path":"get_corpus_data.py","file_name":"get_corpus_data.py","file_ext":"py","file_size_in_byte":3071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"334010777","text":"# -*- coding: utf-8 -*-\n\n# Run this app with `python app.py` and\n# visit http://127.0.0.1:8050/ in your web browser.\n\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nimport plotly.express as px\nimport pandas as pd\n\nfrom pyspark.conf import SparkConf\nfrom pyspark.context import SparkContext\nfrom pyspark.sql import SQLContext\nfrom pyspark.sql.functions import *\nfrom pyspark.sql.types import *\nimport json\n\nwith open('/home/vof/Desktop/Projects/prouniProject/src/config.json', 'r') as f:\n config = json.load(f)\n\n\ndef getData(spark, user, password, database, qryStr):\n jdbcDF = spark.read.format('jdbc')\\\n .option('url', f\"jdbc:sqlserver://localhost:1433;databaseName={database}\")\\\n .option('driver', 'com.microsoft.sqlserver.jdbc.SQLServerDriver')\\\n .option('dbtable', qryStr)\\\n .option(\"user\", user) \\\n .option(\"password\", password) \\\n .load()\n return jdbcDF\n\n\nconf = SparkConf().setMaster(\"local\").setAppName(config['db']['database'])\nconf.set('spark.driver.extraClassPath',\n config['db']['jdbcDrivePath'])\nconf.set('spark.executor.extraClassPath',\n config['db']['jdbcDrivePath'])\nsc = SparkContext(conf=conf)\nsc = SparkContext.getOrCreate()\n\nsqlContext = SQLContext(sc)\nsqlContext.sql(f\"CREATE DATABASE IF NOT EXISTS {config['db']['database']}\")\nsqlContext.sql(f\"USE {config['db']['database']}\")\n\nspark = sqlContext.sparkSession\n\nqryStrAll = \"\"\" (\n SELECT *\n FROM todasBolsas\n ) t\"\"\"\n\nallData = getData(spark, config['db']['user'], config['db']\n ['password'], config['db']['database'], qryStrAll)\nallData = allData.withColumn(\"AGE\", floor(months_between(\n current_date(), col(\"DT_NASCIMENTO_BENEFICIARIO\"))/lit(12)))\n\nrangeAge = sqlContext.createDataFrame([(0, 24, '0-24'), (25, 30, '25-30'), (31, 40,\n '31-40'), (41, 50, '41-50'), (51, 9999, '51+')], ['age_f', 'age_to', 'RANGE_AGE'])\n\nallData = allData.join(rangeAge, (allData.AGE >= rangeAge.age_f) & (\n allData.AGE <= rangeAge.age_to), 'inner')\nallGrouped = allData.groupBy(\"MODALIDADE_ENSINO_BOLSA\", \"NOME_TURNO_CURSO_BOLSA\", \"ANO_CONCESSAO_BOLSA\", \"BENEFICIARIO_DEFICIENTE_FISICO\", \"SEXO_BENEFICIARIO_BOLSA\",\n \"REGIAO_BENEFICIARIO_BOLSA\", \"RACA_BENEFICIARIO_BOLSA\", 'SIGLA_UF_BENEFICIARIO_BOLSA', 'RANGE_AGE').count()\nallDf = allGrouped.toPandas()\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\napp.title = \"ProUni Dashboard: Conhecendo as bolsas do ProUni!\"\noptions = [\n {\"label\": \"Raca\", \"value\": \"RACA_BENEFICIARIO_BOLSA\"},\n {\"label\": \"Sexo\", \"value\": \"SEXO_BENEFICIARIO_BOLSA\"},\n {\"label\": \"Deficiente\", \"value\": \"BENEFICIARIO_DEFICIENTE_FISICO\"},\n {\"label\": \"Turno\", \"value\": \"NOME_TURNO_CURSO_BOLSA\"},\n {\"label\": \"Modalidade\", \"value\": \"MODALIDADE_ENSINO_BOLSA\"},\n {\"label\": \"Idade\", \"value\": \"RANGE_AGE\"},\n]\nMIN_YR = 2016\nMAX_YR = 2018\n\napp.layout = html.Div([\n html.Div(\n children=[\n html.P(children=\"📚\", className=\"header-emoji\"),\n html.H1(\n children=\"ProUni Dashboard\", className=\"header-title\"\n ),\n html.P(\n children=\"Analise das Bolsas do ProUni\"\n \" utilizando os dados coletados no Portal Brasileiro de Dados Abertos(https://dados.gov.br/)\"\n \" no período de 2016 a 2018\",\n className=\"header-description\",\n ),\n ],\n className=\"header\",\n ),\n html.Div(\n children=[\n html.Div(\n [\n html.Div(children=\"Ano\", className=\"menu-title\"),\n dcc.RangeSlider(\n id=\"date_slider\",\n min=MIN_YR,\n max=MAX_YR,\n count=1,\n step=1,\n value=[MIN_YR, MAX_YR],\n marks={yr: str(yr)\n for yr in range(MIN_YR, MAX_YR + 1)},\n allowCross=False\n )\n ],\n style={\"width\": \"70%\"},\n ),\n html.Div([\n html.Div(children=\"Variavel X\", className=\"menu-title\"),\n dcc.Dropdown(\n id=\"dropdownX\",\n options=options,\n value=options[0]['value'],\n clearable=False,\n )\n ]),\n html.Div([\n html.Div(children=\"Variavel Y\", className=\"menu-title\"),\n dcc.Dropdown(\n id=\"dropdownY\",\n options=options,\n value=options[1]['value'],\n clearable=False,\n )\n ])\n ], className=\"menu\"),\n html.Div([html.Div(children=\"Grafico em barra dividido por região\", className=\"menu-title\"),\n dcc.Graph(id=\"bar-chart\")]),\n dcc.Graph(\n id=\"line-chart\", config={\"displayModeBar\": False},\n )\n])\n\n\n@ app.callback(\n [Output(\"bar-chart\", \"figure\"), Output('line-chart', 'figure')],\n [Input(\"dropdownX\", \"value\"), Input(\"dropdownY\", \"value\"), Input(\"date_slider\", \"value\")])\ndef update_bar_chart(optionX, optionY, data):\n mask = (allDf['ANO_CONCESSAO_BOLSA'] >= data[0]) & (\n allDf['ANO_CONCESSAO_BOLSA'] <= data[1])\n\n result = allDf[mask].groupby([optionY,\n 'REGIAO_BENEFICIARIO_BOLSA', optionX]).sum().reset_index()\n bar = px.bar(result, x=optionY, y=\"count\", hover_data=['REGIAO_BENEFICIARIO_BOLSA'],\n color=optionX, barmode=\"group\")\n resultLine = allDf.groupby(\n ['ANO_CONCESSAO_BOLSA', optionX]).sum().reset_index()\n\n line = px.line(resultLine, x=\"ANO_CONCESSAO_BOLSA\", y=\"count\",\n color=optionX)\n return bar, line\n\n\napp.run_server(debug=True)\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"277403457","text":"#! /usr/bin/env python\n\n\ndef add_current_bar_numbers():\n input_file_name = \"breaks.ly\"\n current_bar_number = 74\n edited_lines = []\n for line in open(input_file_name, \"r\").readlines():\n if \"s1 * 1/2\" in line:\n new_line = (\n \"\\t\\t\\\\set Score.currentBarNumber = #%s\\n\" % current_bar_number\n )\n edited_lines.append(new_line)\n current_bar_number += 1\n edited_lines.append(line)\n out = open(\"tmp.ly\", \"w\")\n out.write(\"\".join(edited_lines))\n\n\nif __name__ == \"__main__\":\n add_current_bar_numbers()\n","sub_path":"desir/etc/profusion/scr/py/add_current_bar_numbers.py","file_name":"add_current_bar_numbers.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"156249852","text":"from planning.feeding_services.event_http_service import EventHTTPFeedingService\nfrom planning.tests import TestCase\n\n\nclass EventHTTPFeedingServiceTestCase(TestCase):\n\n def setUp(self):\n super().setUp()\n\n def test_update(self):\n with self.app.app_context():\n\n service = EventHTTPFeedingService()\n provider = {\n 'feed_parser': 'ics20',\n 'config': {\n 'url': 'https://gist.github.com/vied12/9efa0655704c05b6e442c581c9eb1f89/' +\n 'raw/539d2911052f5d03713811ebe19ca594391d6b80/event.ics',\n }\n }\n events = list(service._update(provider, None))\n self.assertEqual(len(events), 1)\n\n def test_update_ntb(self):\n with self.app.app_context():\n\n service = EventHTTPFeedingService()\n provider = {\n 'feed_parser': 'ntb_event_xml',\n 'config': {\n 'url': 'https://gist.github.com/vied12/d390cd5f245faa8311f70562a71e7820/' +\n 'raw/0f74b78c124482d6c897dcfc24202981cd4428b2/NTBEvent.xml',\n }\n }\n events = list(service._update(provider, None))\n self.assertEqual(len(events), 1)\n","sub_path":"server/planning/feeding_services/event_http_service_tests.py","file_name":"event_http_service_tests.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"432343538","text":"import os\nfrom functools import wraps\nfrom inspect import getfullargspec\n\nfrom .server import CompleteHTTPServer\nfrom .server import CompleteHTTPRequestHandler\nfrom .server import serve\n\nclass Application:\n\n \"\"\" rules : { url -> {methods, args, endpoint} } \"\"\"\n rules = {}\n \"\"\" endpoint -> runnable \"\"\"\n endpoints = {}\n \"\"\" r_endpoint : endpoint -> url \"\"\"\n r_endpoint = {}\n\n method = None\n\n def __init__(self,\n app_name,\n serve_location=os.getcwd(),\n port=8080,\n host='127.0.0.1'\n ):\n self.port = port\n self.host = host\n self.app_name = app_name\n self.loc = serve_location\n\n def _endpoint_with_runnable(self, runnable):\n if runnable is None:\n raise ValueError('Either endpoint or runnable'\n 'should be provided.')\n return runnable.__name__\n\n def make_rule(self, url_rule='/', runnable=None, endpoint=None, args=None, methods=('GET',)):\n if endpoint is None:\n endpoint = self._endpoint_with_runnable(runnable)\n\n if url_rule not in self.rules:\n if endpoint not in self.endpoints and endpoint not in self.r_endpoint:\n # If the endpoint does not exist, we register it\n self.endpoints[endpoint] = runnable\n self.r_endpoint[endpoint] = url_rule\n # If the endpoint has already been registered and the provided url\n # has not been allocated, we can safely bind the two together\n self.rules[url_rule] = {'methods':methods, 'endpoint': endpoint, 'args': args}\n else:\n _, c_endpoint = self.rules.get(url_rule)\n c_runnable = self.endpoints[c_endpoint]\n if c_endpoint == endpoint or c_runnable != runnable:\n raise ValueError(f'An endpoint for the url {url_rule} has already been defined.')\n\n if c_endpoint not in self.endpoints and c_runnable is None:\n # If there is either no current endpoint or there is no runnable\n # currently attached to it, we can safely add the new one\n self.rules[url_rule] = {'methods': methods, 'endpoint': endpoint, 'args': args}\n self.endpoints[endpoint] = runnable\n self.r_endpoint[endpoint] = url_rule\n\n def rule(self, url, methods=('GET',)):\n def decorator(f):\n self.make_rule(url_rule=url,\n runnable=f,\n methods=methods,\n args=getfullargspec(f).args)\n return f\n return decorator\n\n def _exec_rule(self, rule, method, params):\n if method in self.rules[rule]['methods']:\n self.method = method\n\n endpoint = self.rules[rule]['endpoint']\n expected_params = self.rules[rule]['args']\n if set(expected_params) != set(params):\n raise ValueError(f'Error in call to {endpoint} : parametes mismatch\\n'\n f'Got {list(params)} expected {expected_params}.')\n\n output = self.endpoints[endpoint](**params)\n self.method = None\n return output\n else:\n raise ValueError(f'Rule {rule} does not support method {method}.')\n\n def is_rule(self, rule):\n return rule in self.rules\n\n def run(self):\n serve(directory=self.loc,\n bind=self.host,\n port=self.port,\n threaded = True,\n wait_for_threads = True,\n app=self\n )\n\n def url_for(self, endpoint):\n rule = self.endpoints.get(endpoint, None)\n if rule:\n return f'http://{self.host}:{self.port}/{rule}'\n else:\n raise ValueError('Unknown provided endpoint {endpoint}.')\n\n def print_state(self):\n print('self.rules ', self.rules)\n print('self.endpoints', self.endpoints)\n print('self.r_endpoint', self.r_endpoint)\n","sub_path":"backend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"272846700","text":"def read(s):\r\n s = s.lower()\r\n a = ''.join([i for i in s if i not in '_-;'])\r\n return(a)\r\n #return ''.join([i for i in s.lower() if i not in '_-;'])\r\na, b, c = read(input()), read(input()), read(input())\r\n#print(a)\r\n#print(b)\r\n#print(c)\r\nimport itertools\r\nl = list(map(lambda x : ''.join(x), list(itertools.permutations([a, b, c]))))\r\n#lambda x: ''.join(x),\r\n#print(l)\r\nfor i in range(int(input())):\r\n s = read(input())\r\n #print(s)\r\n print('ACC' if s in l else 'WA')\r\n","sub_path":"Lecture05/61B.py","file_name":"61B.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"126913253","text":"import logging\nimport os\nimport numpy as np\nimport tensorflow as tf\n\nfrom cleverhans.attacks import CarliniWagnerL2\nfrom cleverhans.compat import flags\nfrom cleverhans.dataset import MNIST\nfrom cleverhans.loss import CrossEntropy\nfrom cleverhans.utils import grid_visual, AccuracyReport\nfrom cleverhans.utils import set_log_level\nfrom cleverhans.utils_tf import model_eval, tf_model_load\nfrom cleverhans.train import train\nfrom cleverhans.model_zoo.basic_cnn import ModelBasicCNN\n\nVIZ_ENABLED = True\nBATCH_SIZE = 128\nNB_EPOCHS = 6\nSOURCE_SAMPLES = 10\nLEARNING_RATE = .001\nCW_LEARNING_RATE = .2\nATTACK_ITERATIONS = 100\nMODEL_PATH = os.path.join('models', 'mnist')\nTARGETED = True\n\ndef __test():\n report = AccuracyReport()\n tf.set_random_seed(1234)\n sess = tf.Session()\n set_log_level(logging.DEBUG)\n\n # Get MNIST test data\n mnist = MNIST(train_start=0, train_end=60000,\n test_start=0, test_end=10000)\n x_train, y_train = mnist.get_set('train')\n x_test, y_test = mnist.get_set('test')\n # Obtain Image Parameters\n img_rows, img_cols, nchannels = x_train.shape[1:4]\n nb_classes = y_train.shape[1]\n # Define input TF placeholder\n x = tf.placeholder(tf.float32, shape=(None, img_rows, img_cols,\n nchannels))\n y = tf.placeholder(tf.float32, shape=(None, nb_classes))\n nb_filters = 64\n # Define TF model graph\n model = ModelBasicCNN('model1', nb_classes, nb_filters)\n preds = model.get_logits(x)\n loss = CrossEntropy(model, smoothing=0.1)\n print(\"Defined TensorFlow model graph.\")\n # Train an MNIST model\n train_params = {\n 'nb_epochs': NB_EPOCHS,\n 'batch_size': BATCH_SIZE,\n 'learning_rate': LEARNING_RATE,\n 'filename': os.path.split(MODEL_PATH)[-1]\n }\n\n rng = np.random.RandomState([2017, 8, 30])\n # check if we've trained before, and if we have, use that pre-trained model\n if os.path.exists(MODEL_PATH + \".meta\"):\n tf_model_load(sess, MODEL_PATH)\n else:\n train(sess, loss, x_train, y_train, args=train_params, rng=rng)\n saver = tf.train.Saver()\n saver.save(sess, MODEL_PATH)\n # Evaluate the accuracy of the MNIST model on legitimate test examples\n eval_params = {'batch_size': BATCH_SIZE}\n accuracy = model_eval(sess, x, y, preds, x_test, y_test, args=eval_params)\n assert x_test.shape[0] == 10000 - 0, x_test.shape\n print('Test accuracy on legitimate test examples: {0}'.format(accuracy))\n report.clean_train_clean_eval = accuracy\n\n\n ###########################################################################\n # Craft adversarial examples using Carlini and Wagner's approach\n ###########################################################################\n nb_adv_per_sample = str(nb_classes - 1)\n print('Crafting ' + str(SOURCE_SAMPLES) + ' * ' + nb_adv_per_sample +\n ' adversarial examples')\n print(\"This could take some time ...\")\n # Instantiate a CW attack object\n cw = CarliniWagnerL2(model, sess=sess)\n \n assert SOURCE_SAMPLES == nb_classes\n idxs = [np.where(np.argmax(y_test, axis=1) == i)[0][0]\n for i in range(nb_classes)]\n # Initialize our array for grid visualization\n grid_shape = (nb_classes, nb_classes, img_rows, img_cols,\n nchannels)\n grid_viz_data = np.zeros(grid_shape, dtype='f')\n adv_inputs = np.array(\n [[instance] * nb_classes for instance in x_test[idxs]],\n dtype=np.float32)\n\n \n one_hot = np.zeros((nb_classes, nb_classes))\n one_hot[np.arange(nb_classes), np.arange(nb_classes)] = 1\n\n adv_inputs = adv_inputs.reshape(\n (SOURCE_SAMPLES * nb_classes, img_rows, img_cols, nchannels))\n adv_ys = np.array([one_hot] * SOURCE_SAMPLES,\n dtype=np.float32).reshape((SOURCE_SAMPLES *\n nb_classes, nb_classes))\n yname = \"y_target\"\n \n cw_params_batch_size = SOURCE_SAMPLES * nb_classes\n cw_params = {'binary_search_steps': 1,\n yname: adv_ys,\n 'max_iterations': ATTACK_ITERATIONS,\n 'learning_rate': CW_LEARNING_RATE,\n 'batch_size': cw_params_batch_size,\n 'initial_const': 10}\n\n adv = cw.generate_np(adv_inputs,\n **cw_params)\n eval_params = {'batch_size': np.minimum(nb_classes, SOURCE_SAMPLES)}\n adv_accuracy = model_eval(\n sess, x, y, preds, adv, adv_ys, args=eval_params)\n for j in range(nb_classes):\n for i in range(nb_classes):\n grid_viz_data[i, j] = adv[i * nb_classes + j]\n\n print(grid_viz_data.shape)\n\n print('--------------------------------------')\n # Compute the number of adversarial examples that were successfully found\n print('Avg. rate of successful adv. examples {0:.4f}'.format(adv_accuracy))\n report.clean_train_adv_eval = 1. - adv_accuracy\n\n # Compute the average distortion introduced by the algorithm\n percent_perturbed = np.mean(np.sum((adv - adv_inputs)**2,\n axis=(1, 2, 3))**.5)\n print('Avg. L_2 norm of perturbations {0:.4f}'.format(percent_perturbed))\n\n # Close TF session\n sess.close()\n _ = grid_visual(grid_viz_data)\n return report\n \n","sub_path":"python/back/mycw.py","file_name":"mycw.py","file_ext":"py","file_size_in_byte":5296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"248261288","text":"import webapp2\nimport functools\nimport base64\nimport re\nimport random\nimport handlers_base\n\n\nfrom google.appengine.api import urlfetch\nfrom google.appengine.api import namespace_manager\nfrom google.appengine.ext import db\nfrom google.appengine.ext.db.metadata import Namespace\n\ndef run_as(ns = \"\"):\n \"\"\"Decorator that ensures that restore the original namespace after the function has \n been executed in appengine.\"\"\"\n def generate(func):\n @functools.wraps(func)\n def decorated_func(self, *args, **kwargs):\n namespace = namespace_manager.get_namespace()\n \n try:\n namespace_manager.set_namespace(ns)\n res = func(self, *args, **kwargs)\n finally:\n namespace_manager.set_namespace(namespace)\n \n return res\n return decorated_func\n return generate\n\nclass InspirationmatorImage(db.Model):\n created_on = db.DateTimeProperty(auto_now_add = True)\n updated_on = db.DateTimeProperty(auto_now = True)\n text_top = db.StringProperty(default = \"\")\n text_bottom = db.StringProperty(default = \"\")\n image = db.BlobProperty()\n permission_key = db.StringProperty()\n\nclass ImageHandler(handlers_base.PageHandler):\n # Homage to http://stackoverflow.com/questions/1590965/uploading-canvas-image-data-to-the-server\n data_url_pattern = re.compile('data:image/(png|jpeg);base64,(.*)$')\n\n def decode_image(self, image_data):\n image = self.data_url_pattern.match(image_data).group(2)\n if image is not None and len(image) > 0:\n return db.Blob(base64.b64decode(image))\n\n @run_as(ns = 'inspirationmator')\n def get(self, file):\n id, extension = handlers_base.parse_filename(file)\n \n image_model = InspirationmatorImage.get_by_id(int(id))\n \n content_type = handlers_base.get_content_type(extension)\n self.response.headers['Content-Type'] = content_type \n self.response.headers['Cache-Control'] = 'max-age=3600, public, must-revalidate'\n \n if content_type == \"text/html\":\n url = \"/image/%s.png\" % (id)\n self.render_file(\"view.html\", self.request.route.name, {\"url\": url, \"title\": id, \"text_top\": image_model.text_top, \"text_bottom\": image_model.text_bottom })\n else:\n self.response.out.write(image_model.image)\n\n @run_as(ns = 'inspirationmator')\n def put(self, id):\n \"\"\"\n Update an existing image.\n \"\"\"\n image_data = self.request.get('image')\n permission_key = self.request.get(\"permissionKey\")\n text_top = self.request.get(\"textTop\")\n text_bottom = self.request.get(\"textBottom\")\n\n image_model = InspirationmatorImage.get_by_id(int(id))\n\n if image_model.permission_key != permission_key:\n self.response.set_status(401)\n return\n\n image_model.image = self.decode_image(image_data)\n image_model.text_top = text_top\n image_model.text_bottom = text_bottom\n image_model.put()\n \n self.response.headers['Content-type'] = 'image/png'\n self.response.out.write(image_model.image)\n\n @run_as(ns = 'inspirationmator')\n def post(self):\n \"\"\"\n Create a new image.\n \"\"\"\n image_data = self.request.get('image')\n permission_key = ''.join(random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') for x in range(36)) \n\n image_model = InspirationmatorImage()\n image_model.image = self.decode_image(image_data)\n image_model.permission_key = permission_key\n image_model.put()\n\n self.response.headers['Content-type'] = 'application/json'\n self.response.out.write('{ \"id\" : \"%s\", \"permissionKey\": \"%s\" }' % (image_model.key().id(), permission_key))\n\nclass ProxyHandler(webapp2.RequestHandler):\n def get(self):\n fetchdata = urlfetch.fetch(self.request.get('url'))\n self.response.headers['Content-type'] = fetchdata.headers['Content-type']\n self.response.set_status(fetchdata.status_code)\n self.response.headers.add_header(\"Expires\", \"Thu, 01 Dec 1994 16:00:00 GMT\")\n self.response.out.write(fetchdata.content)\n \n","sub_path":"server/demos/inspirationmator/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":3895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"547710231","text":"# -*- coding: UTF-8 -*-\nfrom urllib import request\nimport chardet\nimport re\nimport pymysql\n\nif __name__ == \"__main__\":\n # 打开数据库连接\n db = pymysql.connect(host=\"localhost\",user=\"root\",password=\"root\",db=\"graduationprojectyan\",port=3306,charset=\"utf8\")\n # 使用 cursor() 方法创建一个游标对象 cursor\n cursor = db.cursor()\n #取得html\n req = request.Request(\"http://xueshu.baidu.com/usercenter/data/journal?query=&category=4%2C0&journal_db=4&journal_name=%E4%B8%AD%E5%9B%BD%E7%A7%91%E6%8A%80%E6%A0%B8%E5%BF%83%E6%9C%9F%E5%88%8A&page=3\")\n response = request.urlopen(req)\n html = response.read()\n charset = chardet.detect(html)#判断网页的编码并以字典方式返回---charset是字典格式的,当中有encoding\n html = html.decode(charset['encoding'])\n #进行正则匹配\n pattern = re.compile('
\\n.*?')\n items = re.findall(pattern, html)\n for item in items:\n temp = item.replace('\\n', '')\n temp = temp.replace(' ', '')\n temp = temp.replace('\"', '')\n temp = temp.replace(\"'\", '')\n temp = temp.replace(\"\", '')\n temp = temp.replace('', '')\n # SQL 插入语句\n sql = \"INSERT INTO list_of_journal(name,baidusid) VALUES ('\"+temp[32:]+\"','\"+temp[:32]+\"')\"\n # 执行sql语句\n cursor.execute(sql)\n # 提交到数据库执行\n db.commit()\n print(temp[32:])\n # 关闭数据库连接\n db.close()\n\n","sub_path":"faxue/ReptilePart/getListOfJournal/getListOfJournalThree.py","file_name":"getListOfJournalThree.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"649110991","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 30 11:55:29 2020\n获取某日股票资金流入流出,并指定字段输出\n@author: 李博\n\"\"\"\nimport os\nimport pandas as pd\nimport json\nimport datetime\nimport time\nfrom starlette.requests import Request\n#from fastapi import FastAPI\nfrom fastapi import APIRouter\nrouter = APIRouter()\nfrom starlette.templating import Jinja2Templates\n# MONGODB CONNECT\nimport tushare as ts\npro = ts.pro_api('78282dabb315ee578fb73a9b328f493026e97d5af709acb331b7b348')\nTODAY = time.strftime('%Y%m%d',)\n\n#计算指定日期的前N天的时间戳\ndef get_day_time(n):\n #the_date = datetime.datetime(2018,11,10) #指定当前日期 2018-11-10\n the_date = datetime.datetime.now()\n #the_date_str = the_date.strftime('%Y%m%d')\n pre_date = the_date - datetime.timedelta(days=n)\n pre_date_str = pre_date.strftime('%Y%m%d')#将日期转换为指定的显示格式\n return pre_date_str\n\n\n\n#获取时间段统计信息\n#获取单个股票数据\n#df = pro.moneyflow(ts_code='002149.SZ', start_date='20190115', end_date='20190315')\n#df2 = pd.merge(df_stockbasic, df_limit, how='right', on=['ts_code','name'])\n#df2.to_csv('limit.csv')\n \n\n#入库\nfrom pymongo import MongoClient\nprint (os.getcwd())\n#client = MongoClient('mongodb://112.12.60.2:27017')\nclient = MongoClient('mongodb://127.0.0.1:27017')\nmydb=client[\"ptest\"]\n\n#TRADEDATE LIST\ndef get_lasttradedatelist(n,days):\n df = pro.trade_cal(exchange='SSE', is_open='1',fileds='cal_date',start_date=get_day_time(n+days), end_date=get_day_time(n))\n lasttradeday_list = df['cal_date'].tolist()\n return lasttradeday_list\n\n#更新N交易日资金流向数据\ndef get_moneyflow(n,days):\n mycollection=mydb['moneyflow']\n mycollection.remove()\n #获取历史交易日\n tradeday_list = get_lasttradedatelist(n,days)\n for tradeday in tradeday_list:\n #获取某日股票资金流入流出,并指定字段输出\n df_moneyflow_tradeday = pro.moneyflow(trade_date=tradeday)\n mycollection.insert_many(df_moneyflow_tradeday.to_dict('records'))\n print ('moneyflow_'+tradeday+': '+str(len(df_moneyflow_tradeday)))\n#get_moneyflow(0,300)\n#更新最近一个交易日资金流向数据\ndef get_moneyflow_last():\n #获取历史交易日\n df = pro.trade_cal(exchange='SSE', is_open='1',fileds='cal_date',start_date=get_day_time(10), end_date=get_day_time(0))\n lasttradeday = df['cal_date'].tail(1).iloc[0]\n #获取某日股票资金流入流出,并指定字段输出\n df_moneyflow_lastday = pro.moneyflow(trade_date=lasttradeday)\n if (df_moneyflow_lastday.empty):\n df = pro.trade_cal(exchange='SSE', is_open='1',fileds='cal_date',start_date=get_day_time(10), end_date=get_day_time(1))\n lasttradeday = df['cal_date'].tail(1).iloc[0]\n df_moneyflow_lastday = pro.moneyflow(trade_date=lasttradeday)\n df_stockbasic = pro.stock_basic(exchange='', list_status='L', fields='ts_code,market,name,area,industry,list_date')\n df_moneyflow = pd.merge(df_stockbasic, df_moneyflow_lastday, how='right', on=['ts_code'])\n df_moneyflow['stockname'] = df_moneyflow['name']\n #df1.to_csv('moneyflow_lastday.csv') \n mycollection=mydb['moneyflow_lastday']\n mycollection.remove()\n #path_df=open(filename+'.csv','r',encoding='UTF-8') \n #df_csv = pd.read_csv(path_df)\n records = json.loads(df_moneyflow.T.to_json()).values()\n mycollection.insert(records)\n print (df_moneyflow['trade_date'][0],'daily_moneyflow_last: '+str(len(df_moneyflow)))\n \n\ndef toMongodb(collectionname,filename):\n mycollection=mydb[collectionname]\n mycollection.remove()\n path_df=open(filename+'.csv','r',encoding='UTF-8') \n df_csv = pd.read_csv(path_df)\n records = json.loads(df_csv.T.to_json()).values()\n mycollection.insert(records)\n\n#获取个股资金流向数据\ndef get_stock_moneyflow(stockcode):\n df_one = pro.moneyflow(ts_code=stockcode)\n mycollection=mydb['moneyflow_'+stockcode]\n mycollection.remove()\n mycollection.insert_many(df_one.to_dict('records'))\n print ('stocks_daily_qfq: '+stockcode)\n\ndef get_eachstock_moneyflow():\n stocksbasicdata = pro.query('stock_basic',exchange='',list_status='L')\n stocknamelist = list(stocksbasicdata['ts_code'])\n print (len(stocknamelist))\n for stockcode in stocknamelist:\n df_one = pro.moneyflow(ts_code=stockcode)\n if (df_one is None):\n print (stockcode+' data empty')\n else:\n mycollection=mydb['moneyflow_'+stockcode]\n mycollection.remove()\n mycollection.insert_many(df_one.to_dict('records'))\n print ('moneyflow_'+stockcode+': '+str(len(df_one)))\n \n#toMongodb('moneyflow_lastday','moneyflow_lastday')\ntmp = Jinja2Templates(directory='./api/templates')\n@router.get('/update/moneyflow/')\nasync def get_indexs(request:Request):\n get_moneyflow_last()\n #toMongodb('concept','concept')\n return tmp.TemplateResponse('update_data.html',\n {'request':request\n })\n#get_eachstock_moneyflow()","sub_path":"getData/toMongodb_moneyflow.py","file_name":"toMongodb_moneyflow.py","file_ext":"py","file_size_in_byte":5069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"627314851","text":"from django.contrib.auth import get_user_model\nfrom django.db import models\n\nUser = get_user_model()\n\nSTATUS = (\n ('new', 'новая'),\n ('planned', 'запланированная'),\n ('in_progress', 'в работе'),\n ('completed', 'завершенная'),\n)\n\n\nclass Task(models.Model):\n title = models.CharField(max_length=200)\n description = models.TextField(max_length=200)\n created = models.DateTimeField(\n 'Дата добавления',\n auto_now_add=True,\n db_index=True\n )\n status = models.CharField(max_length=11, choices=STATUS)\n finished = models.DateField(\n 'Планируемая дата окончания',\n blank=True,\n null=True\n )\n author = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n related_name='tasks'\n )\n\n class Meta:\n ordering = ['-created']\n\n def __str__(self):\n return f'id:{self.id}, {self.title}'\n\n\nclass TaskHistory(models.Model):\n task = models.ForeignKey(\n Task,\n on_delete=models.CASCADE,\n related_name='history'\n )\n title = models.CharField(max_length=200, blank=True, null=True)\n description = models.TextField(max_length=200, blank=True, null=True)\n status = models.CharField(\n max_length=11, choices=STATUS,\n blank=True,\n null=True\n )\n finished = models.DateField(blank=True, null=True)\n date_change = models.DateTimeField(\n 'Дата изменения',\n auto_now_add=True,\n db_index=True\n )\n\n class Meta:\n ordering = ['-date_change']\n","sub_path":"task/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"410670863","text":"import urllib\nimport urllib.request\nimport os\nimport re\n\n\ndef download_web_image(url, name):\n full_name = name + '.jpg'\n file_path = 'C:\\\\Users\\\\Pratim\\\\Documents\\\\Pictures\\\\' + full_name\n urllib.request.urlretrieve(url, full_name)\n os.rename(full_name, file_path)\n return file_path, full_name\n\n\ndef parse_website(url):\n req = urllib.request.Request(url)\n resp = urllib.request.urlopen(req)\n respdata = resp.read()\n paragraph = re.findall(r'

(.*?)

', str(respdata))\n str_paragraph = ''\n parse_paragraph = ''\n for char in paragraph:\n str_paragraph = str_paragraph + char + ' '\n data_tags = re.findall(r'<(.*?)>', str_paragraph)\n for a_tag in data_tags:\n tags = '<' + a_tag + '>'\n parse_paragraph = str_paragraph.replace(tags, '')\n str_paragraph = parse_paragraph\n return parse_paragraph\n\n\ndef parse_website_ultra(url): #Currently in BETA\n req = urllib.request.Request(url)\n resp = urllib.request.urlopen(req)\n respdata = resp.read()\n paragraph = re.findall(r'

(.*?)

', str(respdata))\n str_paragraph = ''\n parse_paragraph = ''\n for char in paragraph:\n str_paragraph = str_paragraph + char + ' '\n data_tags = re.findall(r'<(.*?)>', str_paragraph)\n for a_tag in data_tags:\n tags = '<' + a_tag + '>'\n parse_paragraph = str_paragraph.replace(tags, '')\n str_paragraph = parse_paragraph\n tagList = []\n dat_num_tags = re.findall(r'\\[(.*?)\\]', parse_paragraph)\n for num_tag in dat_num_tags:\n num_tags = '[' + num_tag + ']'\n tagList.append(num_tags)\n for numtag in tagList:\n parse_paragraph = str_paragraph.replace(numtag, '')\n str_paragraph = parse_paragraph\n xentagList = []\n data_num_xen = re.findall(r'\\((.*?)\\)', parse_paragraph)\n for xentag in data_num_xen:\n xen_tag = '(' + xentag + ')'\n xentagList.append(xentag)\n for xen_tags in xentagList:\n parse_paragraph = str_paragraph.replace(xen_tags, '')\n str_paragraph = parse_paragraph\n return parse_paragraph\n\n\ndef parse_text(paragraph):\n str_paragraph = ''\n parse_paragraph = ''\n for i in paragraph:\n str_paragraph = str_paragraph + i + ' '\n for x in paragraph:\n data_tags = re.findall(r'<(.*?)>', str_paragraph)\n for a_tag in data_tags:\n tags = '<' + a_tag + '>'\n parse_paragraph = str_paragraph.replace(tags, '')\n str_paragraph = parse_paragraph\n return parse_paragraph\n\n\ndef find_images_wiki(topic):\n url = 'https://en.wikipedia.org/wiki/' + topic\n req = urllib.request.Request(url)\n resp = urllib.request.urlopen(req)\n respdata = resp.read()\n img_alt = topic\n try:\n try:\n r_stat = re.findall(r'img alt=\"' + re.escape(img_alt) + r'(.*?)width', str(respdata))\n data_img = re.findall(r'src=\"(.*?)\"', str(r_stat))\n url = str(data_img[0])\n full_url = 'https:' + url\n download_web_image(full_url, topic)\n except:\n img_alt2 = topic.replace(' ', '')\n r_stat = re.findall(r'img alt=\"' + re.escape(img_alt2) + r'(.*?)width', str(respdata))\n data_img = re.findall(r'src=\"(.*?)\"', str(r_stat))\n url = str(data_img[0])\n full_url = 'https:' + url\n download_web_image(full_url, topic)\n except:\n try:\n img_alt3 = topic.split()\n img_alt3 = img_alt3[0]\n r_stat = re.findall(r'img alt=\"' + re.escape(img_alt3) + r'(.*?)width', str(respdata))\n data_img = re.findall(r'src=\"(.*?)\"', str(r_stat))\n url = str(data_img[0])\n full_url = 'https:' + url\n download_web_image(full_url, topic)\n except:\n img_alt4 = topic.split()\n img_alt4 = img_alt4[1]\n r_stat = re.findall(r'img alt=\"' + re.escape(img_alt4) + r'(.*?)width', str(respdata))\n data_img = re.findall(r'src=\"(.*?)\"', str(r_stat))\n url = str(data_img[0])\n full_url = 'https:' + url\n download_web_image(full_url, topic)\n return full_url\n\n\ndef find_images_yahoo(topic):\n url = 'https://images.search.yahoo.com/search/images;_ylt=AwrB8p6NShdZEWYALnKLuLkF;_ylc=X1MDOTYwNTc0ODMEX3IDMgRiY2sDY2VxYjJhcGM5aHZhaiUyNmIlM0QzJTI2cyUzRGh1BGZyAwRncHJpZAM4LjB3TXEwd1I3V0ZNbkczSVNFTzdBBG10ZXN0aWQDbnVsbARuX3N1Z2cDMTAEb3JpZ2luA2ltYWdlcy5zZWFyY2gueWFob28uY29tBHBvcwMwBHBxc3RyAwRwcXN0cmwDBHFzdHJsAzYEcXVlcnkDRG9uYWxkBHRfc3RtcAMxNDk0Njk4ODgyBHZ0ZXN0aWQDbnVsbA--?gprid=8.0wMq0wR7WFMnG3ISEO7A&pvid=l6EeiDY5LjHHaWJWWJj9UwgmOTguMQAAAAClVr6h&fr2=sb-top-images.search.yahoo.com&p=' + topic + '#id=fpub0&iurl=https%3A%2F%2Fc1.staticflickr.com%2F9%2F8458%2F8061492584_0f320a0ef9_b.jpg&action=click'\n req = urllib.request.Request(url)\n resp = urllib.request.urlopen(req)\n respdata = resp.read()\n r_stat = re.findall(r'> sys.stderr, \"start configuring project {0} in directory {1} with command {2}\".format(self.project_name, self.binary_dir, \" \".join(command))\n\n self.process = subprocess.Popen(command, cwd=self.binary_dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n\nclass ConfigureTask(object):\n ids_set = 0\n\n def __init__(self, config, project_root):\n self.config = config\n self.project_root = project_root\n self.task_id = ConfigureTask.new_task_id()\n\n @classmethod\n def new_task_id(cls):\n c = cls.ids_set\n cls.ids_set = c + 1\n return c\n\n\nclass Configurator(object):\n def __init__(self, project):\n self.stop = False\n self.tasks = []\n self.project = project\n self.thread = threading.Thread(target=self.configure_threads)\n self.thread.start()\n\n def start_configure(self, config, project_root):\n self.tasks.append(ConfigureTask(config, project_root))\n\n def configure_threads(self):\n current_configuring = {}\n while(not self.stop):\n if len(self.tasks) == 0 and len(current_configuring) == 0:\n time.sleep(0.1)\n continue\n\n t_for_r = []\n for t in self.tasks:\n if t.config.name in current_configuring:\n continue\n current_configuring[t.config.name] = ConfigureExecutor(t.config, t.project_root)\n t_for_r.append(t)\n\n for t in t_for_r:\n self.tasks.remove(t)\n\n k_for_r = []\n for k in current_configuring:\n v = current_configuring[k]\n if v.process.poll() is not None:\n v.process.wait()\n k_for_r.append(k)\n self.project.reload_compile_rules(k, v.binary_dir)\n\n for k in k_for_r:\n del current_configuring[k]\n","sub_path":"scripts/cml/configurator.py","file_name":"configurator.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"492397033","text":"import sys\nimport cv2\nimport numpy as np\nfrom gradientAnalysis import eraseStrict, eraseLoose\nfrom circle_hough_transform import getCircles, drawCircles\nfrom fixContour import drawContour\nfrom circleOrder import circleOrder\nfrom lineOrder import lineOrder\n\nif len(sys.argv) == 1:\n sys.exit(\"Need to Specify Image\")\nelse:\n imageName = sys.argv[1]\n\nimg = cv2.imread('input/' + imageName + '.png')\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\nstep_num = 0\n\nprint(\"Getting & Grouping Lines\")\ndrawn_img = np.ones(img.shape)\na, b = lineOrder(img=img,n_steps=3)\nfor i in range(len(a)):\n for j in range(len(a[i])):\n step_num += 1\n drawn_img[a[i][j],b[i][j]] = 0\n drawn_img = eraseStrict(img, drawn_img)\n cv2.imwrite('steps/' + imageName + '_step' + str(step_num) + '.png', drawn_img*255)\n\nprint(\"Getting & Grouping Circles\")\ntop_circles, include_arr = getCircles(img, drawn_img)\ncircle_clusters = circleOrder(top_circles, include_arr)\n\nprint(\"Drawing Contours\")\nfor cluster in circle_clusters:\n print(len(cluster))\n step_num += 1\n for circle in cluster:\n drawContour(img, drawn_img, (circle[0], circle[1]), circle[2], 5)\n drawn_img = eraseStrict(img, drawn_img)\n cv2.imwrite('steps/' + imageName + '_step' + str(step_num) + '.png', drawn_img*255)\n\nprint(\"Saving Image\")\ncv2.imwrite('output/' + imageName + '_output.png', drawn_img*255)\ncv2.imshow('image', drawn_img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"drawImage.py","file_name":"drawImage.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"52185341","text":"import argparse\n\nfrom cnn import train\n\nLEARNING_RATE: float = 0.01\nGAMMA: float = 0.95\nBATCH_SIZE: int = 50\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser()\n parser.add_argument('parameters', metavar='parameters')\n args = parser.parse_args()\n parameters_file_name: str = args.parameters\n\n train(\n lr=LEARNING_RATE,\n gamma=GAMMA,\n batch_size=BATCH_SIZE,\n parameters_file_name=parameters_file_name)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"229816513","text":"#!/usr/bin/python\n\nimport sys\n\noldKey = None\nmaxPrice = 0.0\n\nfor line in sys.stdin:\n\tdata = line.strip().split(\"\\t\")\n\n\tif len(data) != 2:\n\t\tcontinue\n\n\tthisKey, cost = data\n\ttry:\n\t\tthisCost = float(cost)\n\texcept:\n\t\tcontinue\n\n\tif oldKey == None:\n\t\toldKey = thisKey\n\n\tif thisKey != oldKey:\n\t\tprint(\"{0}\\t{1}\".format(oldKey, maxPrice))\n\t\toldKey, maxPrice = thisKey, thisCost\n\telse:\n\t\tif maxPrice < thisCost:\n\t\t\tmaxPrice = thisCost\n\nprint(\"{0}\\t{1}\".format(oldKey, maxPrice))","sub_path":"code/highest_individual_sale/reducer.py","file_name":"reducer.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"133048073","text":"#6.1\npessoa_favorita = {\n 'first_name': 'Joaozinho',\n 'last_name': 'não sei',\n 'age': '30',\n 'city': 'são paulo',\n }\n\nprint(\"o nome dela é \" + pessoa_favorita['first_name'] + \" e tem \" + pessoa_favorita['age'] + \" anos de idade\")\n\n#6.2\n\nnumeros_favoritos = {\n 'pedro': '10',\n 'bin': '15',\n 'wica': '20',\n 'vini': '30',\n 'bi': '40',\n 'douglas': '12',\n }\nprint(\"O numero favorito de pedro é: \" + numeros_favoritos['pedro'])\nprint(\"O numero favorito de bin é: \" + numeros_favoritos['bin'])\nprint(\"O numero favorito de wica é: \" + numeros_favoritos['wica'])\nprint(\"O numero favorito de vini é: \" + numeros_favoritos['vini'])\nprint(\"O numero favorito de douglas é: \" + numeros_favoritos['douglas'])\n\n#6.3\n\nglossario_python = {\n 'elif': 'estrutura de testes \"se\" de forma encadead e indentada no python',\n 'chaves_dicionarios': 'utilizado para acessar determinado valor dos pares de dicionarios',\n 'indentacao': 'conjunto de espaços utilizados para melhor visualização da estrutura do código ',\n 'sintaxe': 'modelo padrão de palavras que forma a estrutura e comandos de determianda linguagem',\n 'laço': 'regra que define um agrupamento de informações normalmente utilizado para criar repetições',\n }\n\nprint(\"Significado de elif: \" + glossario_python['elif'] + \"\\n\"\n \"Significado de chaves dicionarios: \" + glossario_python['chaves_dicionarios'] + \"\\n\"\n \"Significado de indentação: \" + glossario_python['indentacao'] + \"\\n\"\n \"Significado de sintaxe: \" + glossario_python['sintaxe'] + \"\\n\"\n \"Significado de laço: \" + glossario_python['laço'] + \"\\n\"\n )\n\n#6.4\n\nglossario_python = {\n 'elif': 'estrutura de testes \"se\" de forma encadead e indentada no python',\n 'chaves_dicionarios': 'utilizado para acessar determinado valor dos pares de dicionarios',\n 'indentacao': 'conjunto de espaços utilizados para melhor visualização da estrutura do código ',\n 'sintaxe': 'modelo padrão de palavras que forma a estrutura e comandos de determianda linguagem',\n 'laço': 'regra que define um agrupamento de informações normalmente utilizado para criar repetições',\n '.title': 'Adiciona letra maiuscula na primeir palavra da sentença',\n '.append': 'adiciona mais um item na lista',\n '.items': 'percorre todos os itens do dicionário',\n 'set': 'indentifica os itens e seleciona somente os únicos',\n '.order': 'ordena em ordem alfabetica as chaves a valores do dicionário',\n }\n\nfor k, v in glossario_python.items():\n print(\"Significado de \" + k + \" é: \" + v + \".\\n\")\n\n#6.5\n\nrios_paises = {\n 'nilo': 'egito',\n 'amazonas': 'brasil',\n 'prata': 'argentina',\n }\n\nfor r in rios_paises.keys():\n print(r.title())\n\nfor v in rios_paises.values():\n print(v.title())\n\n#6.6\nfavorite_languages = {\n 'jen': 'python',\n 'sarah': 'c',\n 'edward': 'ruby',\n 'phil': 'python',\n 'coulson': 'avengers',\n 'eduardo': 'java',\n }\n\nif 'erin' not in favorite_languages.keys():\n print(\"Erin por favor responda o questionário!\")\nfor name in sorted(favorite_languages.keys()):\n print(name.title() + \", obrigado por participar.\")\n\n\n\n\n\n","sub_path":"dicionarios.py","file_name":"dicionarios.py","file_ext":"py","file_size_in_byte":3179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"574066816","text":"from typing import Union\n\nimport requests\n\n\nclass Bot:\n BASE_URL = 'https://api.telegram.org'\n\n def __init__(self, token: str) -> None:\n self.token = token\n self.base_url = f'{self.BASE_URL}/bot{token}'\n\n def sendMessage(\n self,\n chat_id: Union[str, int],\n text: str,\n # parse_mode: str = 'Markdown',\n disable_notification: bool = True,\n ) -> None:\n payload = {\n 'chat_id': chat_id,\n 'text': text,\n # 'parse_mode': parse_mode,\n 'disable_notification': disable_notification,\n }\n response = requests.post(\n f'{self.base_url}/sendMessage', json=payload, timeout=3\n )\n return response.json()\n","sub_path":"snippets/dags-w5/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"614843473","text":"from shapely.geometry import Point\nfrom shapely.geometry import Polygon\nfrom shapely.geometry import LineString\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef return_plot(myobjects):\n\tfor each in myobjects.values():\n\t\tx,y = each.xy\n\t\tplt.plot(x,y,)\n\t\n\tplt.show()\n\ndef import_matrix():\n#Utiliy function to import the matrix\n\tmat = []\n\tf = open(\"map.mat\",'r')\n\tout = f.readline()\n\twhile(out != ''):\n\t\tif out[0] == '#' or out[0] == '\\n':\n\t\t\tout = f.readline()\n\t\t\tcontinue\n\t\tout = out.lstrip(' ')\n\t\tout = out.rstrip(' ')\n\t\tout = out.rstrip('\\n')\n\t\tout = out.split(' ')\n\t\tmat.append(list(map(float, out)))\n\t\tout = f.readline()\n\tmat = np.matrix(mat)\n\t#print(mat.shape)\n\tf.close()\n\treturn mat\n\ndef closest_among_lines(lines,point):\n\tmin_dist = float('inf')\n\tclosest_element_key = -1 \n\tfor element in lines.keys():\n\t\tcurrent_distance = lines[element].distance(point)\n\t\tif current_distance < min_dist:\n\t\t\tmin_dist = current_distance\n\t\t\tclosest_element_key = element\n\t#print(min_dist)\n\tif closest_element_key != -1:\n\t\treturn [closest_element_key, lines[closest_element_key]]\n\telse:\n\t\tprint(\"No objects in the box\")\n\t\treturn [None,None]\n\ndef lines_in_distance_range(lines,point,dmin,dmax):\n\tlines_coming_close = {}\n\tfor element in lines.keys():\n\t\tcurrent_distance = lines[element].distance(point)\n\t\tif current_distance <= dmax and current_distance >=dmin:\n\t\t\tlines_coming_close[element] = lines[element]\n\treturn lines_coming_close\n\ndef relative_measures(lines,dmin):\n\tkeys = list(lines)\n\tlen_keys = len(keys)\n\tthose_coming_close = {}\n\tfor i in range(0,len_keys):\n\t\tcurrent_close = []\n\t\tfor j in range(0,len_keys):\n\t\t\tif (i != j) and (lines[keys[i]].distance(lines[keys[j]]) <= dmin):\n\t\t\t\t#print(f'{lines[keys[i]].distance(lines[keys[j]])}')\n\t\t\t\tcurrent_close.append(keys[j])\n\t\tthose_coming_close[i] = current_close\t\n\treturn those_coming_close\n\n\nif __name__ == '__main__':\n\tglobal mat\n\tmat = import_matrix()\n\tglobal all_objects\n\tall_objects = {}\n\tfor col in range(0,mat.shape[1]):\n\t\tall_objects[col] = np.transpose(mat[:,col]).tolist()[0]\n\tfor element in all_objects.keys():\n\t\tif all_objects[element] != \"LineString\":\n\t\t\tcurrent_line = LineString([tuple(all_objects[element][0:3:2]),tuple(all_objects[element][1:4:2])])\n\t\t\tall_objects[element] = current_line\n\t[px, py] = [120,600]\n\tdmin = 10\n\tdmax = 200\n\tdlower = 10\n\t[lid, line_object] = closest_among_lines(all_objects.copy(),Point(px,py))\n\tif lid != None:\n\t\tprint(f\"Closest line segment to Point {px},{py} is {lid}\\n\\n\")\n\tline_objects = lines_in_distance_range(all_objects.copy(),Point(px,py),dmin,dmax)\n\tif len(line_objects) != 0:\n\t\tprint(f\"Lines in a range: \\n There are {len(line_objects)} in between distance range {dmin} and {dmax} from Point ({px},{py})\")\n\t\tprint(f\"Line ids are {list(line_objects)}\")\n\telse:\n\t\tprint(f\"No lines in this range\")\n\n\trms = relative_measures(all_objects.copy(),10)\n\tprint(rms)\n\t#return_plot(all_objects.copy())\n\n","sub_path":"naive.py","file_name":"naive.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"266333067","text":"import lzma\nimport struct\n\nTF2 = 'E:/Steam/SteamApps/common/Team Fortress 2/tf/maps/'\nrelease_maps = ['cp_dustbowl', 'cp_granary', 'cp_gravelpit', 'cp_well',\n 'ctf_2fort', 'tc_hydro']\n\nmaterials = set()\nprops = set()\nfor MAP in release_maps:\n print(f'Processing {MAP}...')\n bsp = open(f'{TF2}{MAP}.bsp', 'rb')\n bsp.seek(568) # LUMP_GAME_LUMP\n offset = int.from_bytes(bsp.read(4), 'little')\n length = int.from_bytes(bsp.read(4), 'little')\n version = int.from_bytes(bsp.read(4), 'little')\n fourCC = int.from_bytes(bsp.read(4), 'little')\n if fourCC != 0:\n raise RuntimeError(f'{MAP} GAME_LUMP is compressed')\n \n bsp.seek(offset)\n game_lump_headers = []\n game_lump_count = int.from_bytes(bsp.read(4), 'little')\n for i in range(game_lump_count):\n game_lump = struct.unpack('4sHHii', bsp.read(16))\n game_lump_headers.append({\n 'id': game_lump[0][::-1], # Big-Endian flip\n 'flags': game_lump[1],\n 'version': game_lump[2],\n 'fileofs': game_lump[3],\n 'filelen': game_lump[4]})\n\n for header in game_lump_headers:\n if header['id'] == b'sprp': # static prop game lump\n sprp_version = header['version']\n sprp_offset = header['fileofs']\n sprp_length = header['filelen']\n sprp_flags = header['flags']\n break\n \n## if sprp_flags == 1: # packed KEEP TRYING\n## raise RuntimeError(f'{MAP} SPRP_LUMP is compressed')\n## bsp.seek(sprp_offset + 8) \n## fourCC = int.from_bytes(bsp.read(4), 'little') # lzma_header_t lzmaSize\n## bsp.seek(sprp_offset + 17)\n## lzma_header = fourCC.to_bytes(4, 'little') + sprp_length.to_bytes(4, 'little')\n## lump = lzma.decompress(lzma_header + bsp.read(fourCC))\n## else:\n## bsp.seek(offset)\n## lump = bsp.read(length)\n \n bsp.seek(sprp_offset)\n sprp_lump = bsp.read(sprp_length)\n sprp_dict_len = int.from_bytes(sprp_lump[:4], 'little') * 128\n for name in struct.iter_unpack('128s', sprp_lump[4:sprp_dict_len + 4]):\n props.add(name[0].decode('utf-8', 'ignore').strip('\\x00'))\n\n bsp.seek(8) # LUMP_ENTITIES\n offset = int.from_bytes(bsp.read(4), 'little')\n length = int.from_bytes(bsp.read(4), 'little')\n version = int.from_bytes(bsp.read(4), 'little')\n fourCC = int.from_bytes(bsp.read(4), 'little')\n if fourCC != 0:\n raise RuntimeError(f'{MAP} ENTITIES_LUMP is Packed!')\n \n bsp.seek(offset)\n raw_entities = bsp.read(length).decode('ascii').replace('{', '').split('}')[:-1]\n entities = []\n for entity in raw_entities:\n entity = entity.lstrip('\\n').rstrip('\\n')\n entity = entity.split('\\n')\n entity_dict = dict()\n for line in entity:\n try:\n key, value = line.strip('\"').split('\" \"')\n except ValueError:\n key = line.strip('\"').rstrip('\" \"\"')\n value = None\n except Exception as exc:\n print(line)\n raise exc\n entity_dict[key] = value\n entities.append(entity_dict)\n prop_entities = [e for e in entities if e['classname'].startswith('prop_')]\n\n for prop in prop_entities:\n props.add(prop['model'])\n\n bsp.seek(696) # LUMP_TEXDATA_STRING_DATA\n offset = int.from_bytes(bsp.read(4), 'little')\n length = int.from_bytes(bsp.read(4), 'little')\n version = int.from_bytes(bsp.read(4), 'little')\n fourCC = int.from_bytes(bsp.read(4), 'little')\n if fourCC != 0:\n raise RuntimeError(f'{MAP} TEXDATA_STRING_DATA_LUMP is Packed!')\n bsp.seek(offset)\n for material in bsp.read(length).decode('utf-8', 'ignore').split('\\0')[:-1]:\n materials.add(material)\n\n# ALL PROPS IN 2007 RELEASE MAPS\noutfile = open('2007_props.csv', 'w')\nbuffer = ''\nfor prop in props:\n buffer += f'{prop.upper()},' # slam to uppercase for compares\n if len(buffer) > 8096:\n outfile.write(buffer)\n buffer = ''\noutfile.close()\n\n# ALL MATERIALS IN 2007 RELEASE MAPS\noutfile = open('2007_materials.csv', 'w')\nbuffer = ''\nfor material in materials:\n buffer += f'{material.upper()},' # slam to uppercase for compares\n if len(buffer) > 8096:\n outfile.write(buffer)\n buffer = ''\noutfile.close()\n","sub_path":"examples/spreadsheets/all_assets_at_launch.py","file_name":"all_assets_at_launch.py","file_ext":"py","file_size_in_byte":4320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"481439152","text":"import tensorflow as tf\r\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\r\nimport pickle\r\nimport numpy as np\r\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\r\nfrom tensorflow.keras.models import Model\r\nfrom tensorflow.keras.layers import Dense, Flatten, Embedding, MaxPooling1D, Input, LSTM, Conv1D, Dropout, concatenate\r\nimport pickle\r\nimport flask\r\nfrom flask import Flask, jsonify, request\r\nfrom flask import render_template\r\nimport joblib\r\n\r\napp = Flask(__name__)\r\n\r\ntokenizer = pickle.load(open(\"mytoken.pickle\", \"rb\", -1))\r\nembedding_matrix = pickle.load(open(\"embedding.pickle\", \"rb\", -1))\r\n\r\ndef charCNN(input_shape, embedding_matrix):\r\n tf.keras.backend.clear_session()\r\n input = Input(shape = 25)\r\n x_input = Embedding(input_shape, 300, weights = [embedding_matrix], trainable = False)(input)\r\n x_input = Conv1D(32, 3, activation = 'relu', kernel_initializer=tf.keras.initializers.he_normal(seed = 30))(x_input)\r\n x_input = Conv1D(64, 3, activation = 'relu', kernel_initializer=tf.keras.initializers.he_normal(seed = 30))(x_input)\r\n x_input = MaxPooling1D()(x_input)\r\n x_input = Flatten()(x_input)\r\n x_input = Dropout(rate = 0.2)(x_input)\r\n x_input = Dense(32, activation = 'relu', kernel_initializer=tf.keras.initializers.he_normal(seed = 30), kernel_regularizer=tf.keras.regularizers.l2(0.01))(x_input)\r\n output = Dense(2, activation = 'softmax', kernel_initializer=tf.keras.initializers.glorot_uniform(seed = 30))(x_input)\r\n\r\n model = Model(inputs = input, outputs = output, name = 'model')\r\n return model\r\n\r\n\r\nvocab_size = 97\r\nmodel = charCNN(vocab_size, embedding_matrix)\r\nmodel.load_weights(\"charcnn.h5\")\r\n\r\n\r\n@app.route('/index')\r\ndef index():\r\n return flask.render_template('deploy.html')\r\n\r\n@app.route('/')\r\ndef home():\r\n return flask.render_template('deploy.html')\r\n\r\n@app.route('/predict', methods = ['POST'])\r\ndef predict():\r\n datapoint = request.form.to_dict()\r\n name = datapoint['name']\r\n name = np.array(name)\r\n name = np.expand_dims(name, axis = 0)\r\n name = tokenizer.texts_to_sequences(name)\r\n name = pad_sequences(name, padding = 'post', truncating = 'post', maxlen = 25)\r\n name = name.astype('int32')\r\n pred = model.predict(name)\r\n pred = np.argmax(pred, axis = -1)\r\n if pred == 0 :\r\n prediction = \"It is expected to be a female\"\r\n else :\r\n prediction = \"It is expected to be a male\"\r\n\r\n return flask.render_template('deploy.html', prediction_text = prediction)\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run()\r\n\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"612722041","text":"####################################################################\n### ____ _ ____ _ ###\n### | __ )(_) __ ) ___ _ __ ___| |__ ###\n### | _ \\| | _ \\ / _ \\ '_ \\ / __| '_ \\ ###\n### | |_) | | |_) | __/ | | | (__| | | | ###\n### |____/|_|____/ \\___|_| |_|\\___|_| |_| ###\n### ###\n###--------------------------------------------------------------###\n### ###\n### This file is part of the BiBench package for biclustering ###\n### analysis. ###\n### ###\n### Copyright (c) 2011 by: ###\n### * Kemal Eren, ###\n### * Mehmet Deveci, ###\n### * Umit V. Catalyurek ###\n### ###\n###--------------------------------------------------------------###\n### ###\n### For license info, please see the README and LICENSE files ###\n### in the main directory. ###\n### ###\n###--------------------------------------------------------------###\n\n\"\"\"Unit tests for the 'bicluster' module\"\"\"\n\nfrom __future__ import division\n\nimport unittest\nimport numpy as np\n\nimport bibench.all as bb\nfrom bibench.bicluster import get_row_col_matrices, Bicluster\n\nclass BiclusterTest(unittest.TestCase):\n\n def test_get_bicluster(self):\n data = np.arange(60).reshape(10, 6)\n array = np.array([[25, 27, 28],\n [37, 39, 40],\n [55, 57, 58]])\n rows = (4, 6, 9)\n cols = (1, 3, 4)\n bicluster = Bicluster(rows, cols, data)\n self.assertTrue(np.alltrue(array == bicluster.array()))\n\n def test_bicluster_eq(self):\n bic_a = Bicluster([1, 2, 3], [1, 2, 3])\n bic_b = Bicluster([1, 2, 3], [1, 2, 3])\n self.assertEquals(bic_a, bic_b)\n\n data = np.arange(10)\n bic_b.data = data\n self.assertNotEquals(bic_a, bic_b)\n\n bic_a.data = data\n self.assertEquals(bic_a, bic_b)\n\n bic_b.data = np.arange(10)\n self.assertNotEquals(bic_a, bic_b)\n\n\n def test_get_row_col_matrices(self):\n exp_rows = np.vstack(np.array([1, 1, 0]))\n exp_cols = np.vstack(np.array([0, 1, 0]))\n\n data = np.random.randn(3, 3)\n biclusters = [Bicluster([0, 1], [1], data)]\n\n rowxnumber, colxnumber = get_row_col_matrices(biclusters)\n\n self.assertTrue((rowxnumber == exp_rows).all())\n self.assertTrue((colxnumber == exp_cols).all())\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"bibench/test/bicluster_test.py","file_name":"bicluster_test.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"550464559","text":"from collections import Counter\n\n\ndef findLen(string):\n counter = 0\n for i in string:\n counter += 1\n return counter\n\n\ndef len(string) -> list:\n length = []\n total = 0\n count = Counter()\n for word in string.split():\n if count.get(word) is None:\n count[word] = 1\n total += 1\n else:\n count[word] += 1\n for word, cnt in count.most_common(total):\n if cnt == 1:\n break\n length.append((word, findLen(word)))\n return length\n\n\nprint(len(input(\"Enter a sentence : \")))","sub_path":"OOPS/Python/Assignment2/A11.py","file_name":"A11.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"249867153","text":"def menores(matriz):\n menores=[]\n for i in range(len(matriz)):\n for j in range(len(matriz[i])):\n if matriz[i][j]<10:\n menores.append(matriz[i][j])\n return menores\n\ndef main():\n elementrosMatriz=[]\n filas=int(input())\n columnas=int(input()) \n for i in range(filas):\n elementrosMatriz.append([])\n for j in range(columnas):\n datosMatriz=int(input())\n elementrosMatriz[i].append(datosMatriz)\n menoresDiez=menores(elementrosMatriz)\n print(menoresDiez)\n\nif __name__=='__main__':\n main()","sub_path":"assignments/17MenoresANumero/src/exercise.py","file_name":"exercise.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"212228759","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.contrib.auth.views import login, logout\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^admin/', include(admin.site.urls)),\n url(r'^accounts/login/$', login),\n url(r'^accounts/logout/$', logout),\n url(r'^$', 'status.views.home', name='home'),\n url(r'^ops/$', 'status.views.ops', name='ops'),\n url(r'^osd/(\\d+)/$', 'status.views.osd_details', name='osd_details'),\n)\n","sub_path":"kraken/kraken/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"218871278","text":"from rest_framework import serializers\nfrom student.models import Student\nfrom django.core.files.storage import default_storage\nfrom django.core.files.storage import FileSystemStorage\n#from books.models import Book\n#from books.apibooks.serializers import BookSerializer\n\nclass StudentUpdateSerializer(serializers.ModelSerializer):\n\n\tclass Meta:\n\t\tmodel = Student\n\t\tfields = ('pk','student_name', 'department', 'contact')\n\nclass StudentSerializer(serializers.ModelSerializer):\n\t#personalinfo = BookSerializer(many=True)\n\tclass Meta:\n\t\tmodel = Student\n\t\tfields = ('pk','student_name', 'department', 'contact')\n\nclass StudentCreateSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel = Student\n\t\tfields = ('student_name', 'department', 'contact')\n\n\tdef save(self):\n\t\ttry:\n\t\t\tstudent_name = self.validated_data['student_name']\n\t\t\tdepartment = self.validated_data['department']\n\t\t\tcontact = self.validated_data['contact']\n\t\n\t\t\tstudentinfo = Student(\n\t\t\t\t\t\t\t\tstudent_name=student_name,\n\t\t\t\t\t\t\t\tdepartment=department,\n\t\t\t\t\t\t\t\tcontact=contact\n\t\t\t\t\t\t\t\t)\n\t\t\tstudentinfo.save()\n\t\t\treturn studentinfo\n\t\texcept KeyError:\n\t\t\traise serializers.ValidationError({\"response\": \"this invalid somethings!!!!!\"})","sub_path":"rdbproject/student/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"610909119","text":"from typing import Tuple\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom transformers import AutoConfig, AutoModel\n\n\nclass TwoTowerBert(nn.Module):\n def __init__(self, pretrained: str, projection_dim=0):\n super(TwoTowerBert, self).__init__()\n self._pretrained = pretrained\n self._projection_dim = projection_dim\n\n self._config = AutoConfig.from_pretrained(self._pretrained)\n self._document_model = AutoModel.from_pretrained(self._pretrained, config=self._config)\n self._query_model = AutoModel.from_pretrained(self._pretrained, config=self._config)\n if projection_dim > 0:\n self._projection_layer = nn.Linear(768, projection_dim)\n self._activation = nn.Tanh()\n\n def calculate_embedding(self, d_input_ids, d_input_mask, d_segment_ids, doc=True):\n if doc:\n embedding = self._document_model(d_input_ids, attention_mask=d_input_mask, token_type_ids=d_segment_ids)\n else:\n embedding = self._query_model(d_input_ids, attention_mask=d_input_mask, token_type_ids=d_segment_ids)\n\n rst = embedding[0][:, 0, :]\n\n if self._projection_dim > 0:\n rst = self._projection_layer(rst)\n rst = self._activation(rst)\n\n rst = F.normalize(rst, p=2, dim=1)\n\n return rst\n\n def get_attention_heads(self, q_input_ids, q_input_mask, q_segment_ids):\n\n output = self._query_model(q_input_ids, attention_mask=q_input_mask, token_type_ids=q_segment_ids,\n output_attentions=True, output_hidden_states=True, return_dict=True)\n\n attention = output['attentions'] # nlayers x B x nheads x seq_len x seq_len\n hidden_states = output['hidden_states']\n\n last_hidden = hidden_states[-1]\n\n # attention -1: torch.Size([32, 12, 64, 64])\n attention = attention[-1]\n heads = torch.empty(attention.shape[0], attention.shape[1], last_hidden.shape[2])\n for i in range(attention.shape[1]):\n # mean\n # mult = torch.bmm(attention[:, i], last_hidden).mean(dim=1)\n\n # only use the CLS token\n mult = torch.bmm(attention[:, i], last_hidden)[:, 0]\n mult = F.normalize(mult, p=2, dim=1)\n\n heads[:, i] = mult\n\n return heads\n\n def forward(self, q_input_ids: torch.Tensor, d_input_ids: torch.Tensor, q_input_mask: torch.Tensor = None,\n q_segment_ids: torch.Tensor = None, d_input_mask: torch.Tensor = None,\n d_segment_ids: torch.Tensor = None) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n\n query = self._query_model(q_input_ids, attention_mask=q_input_mask, token_type_ids=q_segment_ids)\n document = self._document_model(d_input_ids, attention_mask=d_input_mask, token_type_ids=d_segment_ids)\n\n #print(query[0].shape) # [4, 64, 768]\n #print(query[1].shape) # [4, 768] #CLS token with linear layer and tanh activation\n query = query[0][:, 0, :] # CLS Token\n document = document[0][:, 0, :]\n\n if self._projection_dim > 0:\n document = self._projection_layer(document)\n document = self._activation(document)\n query = self._projection_layer(query)\n query = self._activation(query)\n\n document = F.normalize(document, p=2, dim=1)\n query = F.normalize(query, p=2, dim=1)\n\n score = (document * query).sum(dim=1)\n score = torch.clamp(score, min=0.0, max=1.0)\n\n return score, query, document\n\n def freeze_document_tower(self):\n self._document_model.eval()\n self._query_model.train()\n\n def freeze_berts(self):\n self._query_model.eval()\n self._document_model.eval()\n\n def load_bert_model_state_dict(self, state_dict):\n st = {}\n for key in state_dict:\n if key.startswith(\"bert.\"):\n st[key[len(\"bert.\"):]] = state_dict[key]\n self._document_model.load_state_dict(st)\n self._query_model.load_state_dict(st)\n","sub_path":"msr/knn_retriever/two_tower_bert.py","file_name":"two_tower_bert.py","file_ext":"py","file_size_in_byte":4050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"151729388","text":"# coding=utf-8\n\n\"\"\"\n Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.\n\nFor example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].\n\nNote:\n\n You must do this in-place without making a copy of the array.\n Minimize the total number of operations.\n\n\"\"\"\n\n\nclass Solution(object):\n def moveZeroes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n r = []\n for n in nums:\n if n != 0:\n r.append(n)\n\n nums[:] = r + [0] * (len(nums) - len(r))\n\n\nclass Solution1(object):\n def moveZeroes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n 一旦遇到不是0的就把它往前移动,移动非0完成,剩下的全部填0,看例子\n\n \"\"\"\n idx = 0\n for i in xrange(len(nums)):\n if nums[i] != 0:\n nums[idx] = nums[i]\n idx += 1\n\n for j in xrange(idx, len(nums)):\n nums[idx] = 0\n idx += 1\n\n\nclass Solution2(object):\n def moveZeroes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n\n 快慢指针\n \"\"\"\n slow = 0\n fast = 0\n\n n = len(nums)\n while fast < n:\n if nums[fast] != 0:\n nums[slow] = nums[fast]\n slow += 1\n fast += 1\n\n while slow < n:\n nums[slow] = 0\n slow += 1\n","sub_path":"leetcode/array/283. Move Zeroes.py","file_name":"283. Move Zeroes.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"421550090","text":"#\n# Imports which are standard for all test cases.\n#\nimport sys\nsys.path.insert(1, \"./\")\nfrom gaiatest import GaiaTestCase\nfrom OWDTestToolkit import *\n\n#\n# Imports particular to this test case.\n#\nfrom tests.mock_data.contacts import MockContacts\nimport time\n\nclass test_19183(GaiaTestCase):\n _Description = \"[CONTACTS] **INCOMPLETE** Verify that when looking at the details of a contact, the user can make a call to the contact with several phone numbers added.\"\n\n def setUp(self):\n #\n # Set up child objects...\n #\n GaiaTestCase.setUp(self)\n self.UTILS = UTILS(self)\n self.contacts = Contacts(self)\n self.settings = Settings(self)\n\n #\n # Get details of our test contacts.\n #\n self.Contact_1 = MockContacts().Contact_1\n self.Contact_2 = MockContacts().Contact_2\n self.data_layer.insert_contact(self.Contact_1)\n self.data_layer.insert_contact(self.Contact_2)\n \n \n def tearDown(self):\n self.UTILS.reportResults()\n \n def test_run(self):\n \n #\n # Set up to use data connection.\n #\n self.UTILS.getNetworkConnection()\n \n #\n # Launch contacts app.\n #\n self.contacts.launch()\n \n #\n # View our contact.\n #\n self.contacts.viewContact(self.Contact_1['name'])\n \n # Jumping out here while I try to figure out how to\n # put > 1 phone number in via the mock object!\n self.UTILS.logResult(\"info\", \"Quitting test early!\")\n return\n\n #\n # Tap the 2nd number to dial it.\n #\n \n #\n # Switch to the dialer iframe.\n #\n self.marionette.switch_to_frame()\n #self.UTILS.switchToFrame(DOM.Dialer.frame_locator, \"Dialer iframe\")\n \n #\n # Verify things....\n","sub_path":"tests/test_19183.py","file_name":"test_19183.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"21737383","text":"from ursina import *\n\napp = Ursina()\n\nwindow.borderless = False\nwindow.color = color._20\n\n# Text.default_font = '/System/Library/Fonts/AppleSDGothicNeo.ttc'\n\n# 기본 폰트 설정\nText.default_font = 'NanumGothic-Regular.ttf'\n\ngold = 0\ngold_text = Text(text=str(gold), x=-0.02, y=0.3, scale=2, background=True)\nbutton = Button(text='1G', color=color.orange, x=-0.6, scale=0.2)\n\ndef button_click():\n global gold\n gold += 1\n\nbutton.on_click = button_click\n\n# 골드 자동 생성기\ndef auto_plus_gold(plus=1, interval=1):\n global gold\n gold += plus\n\n invoke(auto_plus_gold, plus, delay=interval)\n\ndef get_auto_gold(button, plus=1):\n global gold\n\n if gold >= button.cost:\n gold -= button.cost\n\n button.cost = int(button.cost * 1.2)\n button.upgrade += 1\n button.text = f'+{button.upgrade}\\n{button.earn}G/초\\n가격 {button.cost}G'\n\n invoke(auto_plus_gold, plus=plus, interval=1)\n\nauto_settings = [\n {\n 'cost': 10,\n 'earn': 1,\n 'upgrade': 0,\n },\n {\n 'cost': 100,\n 'earn': 5,\n 'upgrade': 0,\n },\n {\n 'cost': 1000,\n 'earn': 25,\n 'upgrade': 0,\n },\n {\n 'cost': 10000,\n 'earn': 125,\n 'upgrade': 0,\n },\n]\n\nauto_buttons = []\n\nfor i, setting in enumerate(auto_settings):\n b = Button(\n text=f'{setting[\"earn\"]}G/초\\n가격 {setting[\"cost\"]}G',\n x=(0.3 * (i+1) - 0.6), scale=0.2,\n disabled=True,\n cost=setting['cost'],\n earn=setting['earn'],\n upgrade=setting['upgrade']\n )\n\n b.on_click = Func(get_auto_gold, b, b.earn)\n\n auto_buttons.append(b)\n\ndef update():\n global gold\n\n gold_text.text = str(gold)\n\n for button in auto_buttons:\n if gold >= button.cost:\n button.disabled = False\n button.color = color.green\n button.text_color = color.black\n else:\n button.disabled = True\n button.color = color.gray\n button.text_color = color.white\n\napp.run()","sub_path":"골드채굴_클리커게임/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"510483218","text":"import time\nfrom urllib.request import urlopen\n# from multiprocessing import Pool # processes\nfrom multiprocessing.dummy import Pool as ThreadPool # threads\n\nurls = [\n 'http://www.python.org',\n 'http://www.python.org/about/',\n 'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html',\n 'http://www.python.org/doc/',\n 'http://www.python.org/download/',\n 'http://www.python.org/getit/',\n 'http://www.python.org/community/',\n 'https://wiki.python.org/moin/',\n 'http://planet.python.org/',\n 'https://wiki.python.org/moin/LocalUserGroups',\n 'http://www.python.org/psf/',\n 'http://docs.python.org/devguide/',\n 'http://www.python.org/community/awards/'\n # etc..\n]\n\n#pool = ThreadPool(4) # Sets the pool size to 4\n# Number of workers, default = number of Cores in the machines\n\n# Open the urls in their own threads and return the results\n#results = pool.map(urlopen, urls)\n#pool.close() # close the pool and wait for the work to finish\n#pool.join()\n\n\ns1 = time.time()\nresults1 = []\nfor url in urls:\n result = urlopen(url)\n results1.append(result)\nt1 = time.time() - s1\n\n# # ------- VERSUS ------- #\n\n\n\n# # ------- 4 Pool ------- #\ns2 = time.time()\npool4 = ThreadPool(2)\nresults2 = pool4.map(urlopen, urls)\nt2 = time.time() - s2\n\n\n\n# # ------- 8 Pool ------- #\ns3 = time.time()\npool8 = ThreadPool(4)\nresults3 = pool8.map(urlopen, urls)\nt3 = time.time() - s3\n\n\n\n# # ------- 13 Pool ------- #\ns4 = time.time()\npool13 = ThreadPool(8)\nresults4 = pool13.map(urlopen, urls)\nt4 = time.time() - s4\n\n\nprint(\"t1 = {}, t2 = {}, t3 = {}, t4 = {}\".format(t1, t2, t3, t4))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"do_an/cao_quyen/test/parallel/map_test.py","file_name":"map_test.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"425412203","text":"#!/usr/bin/env python\nimport time\nimport math\nimport rospy\nfrom std_msgs.msg import Float64\n\n\nclass PanAndTiltMoveSim(object):\n\n def __init__(self):\n\n rospy.loginfo(\"PanAndTiltMoveSim.....STARTING\")\n\n self.pan_value = 0.0\n self.tilt_value = 0.0\n self.tilt_upper = 0.7\n self.tilt_lower = -0.7\n self.pan_upper = 1.57\n self.pan_lower = -1.57\n\n self.pub_pan_position = rospy.Publisher(\n '/pan_and_tilt/yaw_joint_position_controller/command',\n Float64,\n queue_size=1)\n self.pub_tilt_position = rospy.Publisher(\n '/pan_and_tilt/pitch_joint_position_controller/command',\n Float64,\n queue_size=1)\n\n self.PITCH_INIT_ANGLE = 0\n self.YAW_INIT_ANGLE = 0\n self.move_to_pitch_yaw(yaw=self.YAW_INIT_ANGLE,\n pitch=self.PITCH_INIT_ANGLE)\n\n rospy.loginfo(\"PanAndTiltMoveSim.....STARTED...DONE\")\n\n def __del__(self):\n print(\"\\nCleaning PanAndTiltMove...\")\n print(\"\\nPanAndTiltMove END\")\n\n\n def wait_publishers_to_be_ready(self):\n\n publishers_ready = False\n\n rate_wait = rospy.Rate(10)\n while not publishers_ready:\n pan_num = self.pub_pan_position.get_num_connections()\n tilt_num = self.pub_tilt_position.get_num_connections()\n publishers_ready = (pan_num > 0) and (tilt_num > 0)\n rate_wait.sleep()\n\n def update_pan(self,pan_angle):\n\n if self.pan_upper >= pan_angle >= self.pan_lower:\n self.pan_value = pan_angle\n elif pan_angle < self.pan_lower:\n self.pan_value = self.pan_lower\n else:\n self.pan_value = self.pan_upper\n\n rospy.logdebug(\"pan_value=\" + str(self.pan_value))\n\n def update_tilt(self,tilt_angle):\n\n if self.tilt_upper >= tilt_angle >= self.tilt_lower:\n self.tilt_value = tilt_angle\n elif tilt_angle < self.tilt_lower:\n self.tilt_value = self.tilt_lower\n else:\n self.tilt_value = self.tilt_upper\n\n rospy.logdebug(\"tilt_value=\"+str(self.tilt_value))\n\n\n\n def move_to_pitch_yaw(self, yaw, pitch):\n rospy.logdebug(\"move_to_pitch_yaw=\" + str(yaw) +\",\"+str(pitch))\n self.wait_publishers_to_be_ready()\n self.move_yaw(yaw_angle=yaw)\n self.move_pitch(pitch_angle=pitch)\n\n def move_yaw(self, yaw_angle):\n # We convert the Degrees given into radians\n yaw_in_radians = math.radians(yaw_angle)\n pan_angle_msg = Float64()\n pan_angle_msg.data = yaw_in_radians\n # Publish Joint Position\n self.pub_pan_position.publish(pan_angle_msg)\n self.update_pan(yaw_in_radians)\n\n def move_pitch(self, pitch_angle):\n # We convert the Degrees given into radians\n pitch_in_radians = math.radians(pitch_angle)\n tilt_angle_msg = Float64()\n tilt_angle_msg.data = pitch_in_radians\n # Publish Joint Position\n self.pub_tilt_position.publish(tilt_angle_msg)\n self.update_tilt(pitch_in_radians)\n\n def yaw_range_test(self):\n \"\"\"\n It tests the range of yaw servo once\n :return:\n \"\"\"\n for angle in range(10,170,1):\n print(\"Moving Yaw=\"+str(angle))\n self.move_yaw(yaw_angle=angle)\n time.sleep(0.1)\n\n for angle in range(170,10,-1):\n print(\"Moving Yaw=\"+str(angle))\n self.move_yaw(yaw_angle=angle)\n time.sleep(0.1)\n\n\n def pitch_range_test(self):\n \"\"\"\n It tests the range of pitch servo once\n :return:\n \"\"\"\n for angle in range(10,170,1):\n print(\"Moving Pitch=\"+str(angle))\n self.move_pitch(pitch_angle=angle)\n time.sleep(0.1)\n\n for angle in range(170,10,-1):\n print(\"Moving Pitch=\"+str(angle))\n self.move_pitch(pitch_angle=angle)\n time.sleep(0.1)\n\n def input_yaw_test(self):\n\n while True:\n input_x = raw_input(\"Type Angle to move to\")\n angle = int(input_x)\n print(\"Moving Yaw=\" + str(angle))\n self.move_yaw(yaw_angle=angle)\n\n def input_pitch_test(self):\n\n while True:\n input_x = raw_input(\"Type Angle to move to\")\n angle = int(input_x)\n print(\"Moving Pitch=\" + str(angle))\n self.move_pitch(pitch_angle=angle)\n\n def yaw_pitch_circle_test(self, repetitions=1):\n\n # These values are base on Hardware observations where they are stable.\n max_range = 100\n min_range = 30\n period = 0.1\n increments = 10\n\n for num in range(repetitions):\n for angle in range(0,359,increments):\n pitch_angle = int((((math.sin(math.radians(angle)) + 1.0) / 2.0) * (max_range - min_range)) + min_range)\n yaw_angle = int((((math.cos(math.radians(angle)) + 1.0) / 2.0) * (max_range - min_range)) + min_range)\n\n print(\"Moving Yaw=\"+str(yaw_angle))\n print(\"Moving Pitch=\" + str(pitch_angle))\n\n self.move_pitch(pitch_angle)\n self.move_yaw(yaw_angle)\n time.sleep(period)\n\n for angle in range(0,359,-increments):\n pitch_angle = int((((math.sin(math.radians(angle)) + 1.0) / 2.0) * (max_range - min_range)) + min_range)\n yaw_angle = int((((math.cos(math.radians(angle)) + 1.0) / 2.0) * (max_range - min_range)) + min_range)\n\n print(\"Moving Yaw=\"+str(yaw_angle))\n print(\"Moving Pitch=\" + str(pitch_angle))\n\n self.move_pitch(pitch_angle)\n self.move_yaw(yaw_angle)\n time.sleep(period)\n\ndef CircleTest():\n pt_object = PanAndTiltMoveSim()\n # raw_input(\"Start Circle Test...Press Key\")\n pt_object.yaw_pitch_circle_test(repetitions=3)\n\n\nif __name__ == \"__main__\":\n rospy.init_node('pan_and_tilt_move_sim')\n CircleTest()\n\n\n\n","sub_path":"src/pan_and_tilt_control/scripts/pan_and_tilt_move_sim.py","file_name":"pan_and_tilt_move_sim.py","file_ext":"py","file_size_in_byte":5985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"292699615","text":"from utils.activation import Activation\n\n\nclass MultiLayersPerceptronConfigurator:\n \n def __init__(self, input_size: int, output_size: int, hidden_layers: list, learning_rate: float, hidden_activation: Activation, activation_output: Activation):\n self.input_size = input_size\n self.output_size = output_size\n self.hidden_layers = hidden_layers\n self.learning_rate = learning_rate\n self.hidden_activation = hidden_activation\n self.activation_output = activation_output\n self.__check_inputs()\n \n def __check_inputs(self):\n self.__check_input_size()\n self.__check_output_size()\n self.__check_hidden_layers()\n self.__check_learning_rate()\n self.__check_hidden_activation()\n self.__check_activation_output()\n \n def __check_input_size(self):\n if not isinstance(self.input_size, int):\n raise TypeError(\"The input_size must be an int\")\n if self.input_size < 0:\n raise ValueError(\"The input_size must be a positive value\")\n \n def __check_output_size(self):\n if not isinstance(self.output_size, int):\n raise TypeError(\"The output_size must be an int\")\n if self.output_size < 0:\n raise ValueError(\"The output_size must be a positive value\")\n \n def __check_hidden_layers(self):\n if not isinstance(self.hidden_layers, list):\n raise TypeError(\"The hidden_layers must be a list\")\n for layer_size in self.hidden_layers:\n if not isinstance(layer_size, int):\n raise TypeError(\"Each layer_size in the hidden_layers list must be an int\")\n if layer_size < 0:\n raise ValueError(\"Each layer_size must be a positive value\")\n \n def __check_learning_rate(self):\n if not isinstance(self.learning_rate, float):\n raise TypeError(\"The learning_rate must be an float\")\n if self.learning_rate > 1.0 or self.learning_rate < 0.0:\n raise ValueError(\"The learning_rate must be in [0.0, 1.0]\")\n \n def __check_hidden_activation(self):\n if not isinstance(self.hidden_activation, Activation):\n raise TypeError(\"The hidden_activation must be an Activation Enum\")\n \n def __check_activation_output(self):\n if not isinstance(self.activation_output, Activation):\n raise TypeError(\"The activation_output must be an Activation Enum\")\n","sub_path":"configurator/multi_layers_perceptron_configurator.py","file_name":"multi_layers_perceptron_configurator.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"534144188","text":"# Simple CNN model for CIFAR-10\nimport numpy, keras, tensorflow, pandas\nfrom keras.datasets import cifar10\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Dropout\nfrom keras.layers import Flatten\nfrom keras.constraints import maxnorm\nfrom keras.optimizers import SGD\nfrom keras.layers.convolutional import Conv2D\nfrom keras.layers.convolutional import MaxPooling2D\nfrom keras.utils import np_utils\nfrom keras import backend as K\nfrom matplotlib import pyplot as plt\nK.common.image_dim_ordering()\n\n# fix random seed for reproducibility\nseed = 7\nnumpy.random.seed(seed)\n# load data\n(X_train, y_train), (X_test, y_test) = cifar10.load_data()\n# normalize inputs from 0-255 to 0.0-1.0\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\nX_train = X_train / 255.0\nX_test = X_test / 255.0\n# one hot encode outputs\ny_train = np_utils.to_categorical(y_train)\ny_test = np_utils.to_categorical(y_test)\nnum_classes = y_test.shape[1]\n\nlabels = {0 : 'airplane',\n 1 : 'automobile',\n 2 : 'bird',\n 3 : 'cat',\n 4 : 'deer',\n 5 : 'dog',\n 6 : 'frog',\n 7 : 'horse',\n 8 : 'ship',\n 9 : 'truck'}\n\n# M2-ICP4 Use Case\n# Create the model\nmodel1 = Sequential()\nmodel1.add(Conv2D(32, (3, 3), input_shape=(32, 32, 3), padding='same', activation='relu', kernel_constraint=maxnorm(3)))\nmodel1.add(Dropout(0.2))\nmodel1.add(Conv2D(32, (3, 3), activation='relu', padding='same', kernel_constraint=maxnorm(3)))\nmodel1.add(MaxPooling2D(pool_size=(2, 2)))\nmodel1.add(Flatten())\nmodel1.add(Dense(512, activation='relu', kernel_constraint=maxnorm(3)))\nmodel1.add(Dropout(0.5))\nmodel1.add(Dense(num_classes, activation='softmax'))\n# Compile model\nepochs = 25\nlrate = 0.01\ndecay = lrate/epochs\nsgd = SGD(lr=lrate, momentum=0.9, decay=decay, nesterov=False)\nmodel1.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\nprint(model1.summary())\n# Fit the model\nhistory_use = model1.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=epochs, batch_size=32)\n#Save the trained model\nmodel1.save('useCase.h5')\n# Final evaluation of the model\nscores = model1.evaluate(X_test, y_test, verbose=0)\nprint(\"Accuracy: %.2f%%\" % (scores[1]*100))\n\n# summarize history for accuracy\nplt.plot(history_use.history['accuracy'])\nplt.plot(history_use.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n# summarize history for loss\nplt.plot(history_use.history['loss'])\nplt.plot(history_use.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()","sub_path":"M2_ICP_4/Source/UseCase.py","file_name":"UseCase.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"429049422","text":"import os\nimport re\nimport shutil\nfrom pathlib import Path\nimport argparse\n\n\ndef extract_tags(content):\n pattern = r\"(?:(?<=\\s)|(?<=^))#([\\w\\-]+)\\b(?![\\w(])\"\n tags = re.findall(pattern, content)\n content = re.sub(pattern, \"\", content)\n return tags, content\n\n\ndef update_frontmatter(frontmatter, tags):\n new_lines = []\n taxonomies_added = False\n\n for line in frontmatter.splitlines():\n if line.startswith(\"taxonomies:\"):\n new_lines.append(line)\n new_lines.append(\" tags:\")\n for tag in tags:\n new_lines.append(f\" - {tag}\")\n taxonomies_added = True\n else:\n if line == \"---\" and \"---\" in new_lines:\n # We will manually add the frontmatter terminator\n # at the end of this function when we return the\n # updated frontmatter.\n continue\n else:\n new_lines.append(line)\n\n if not taxonomies_added:\n new_lines.append(\"taxonomies:\")\n new_lines.append(\" tags:\")\n for tag in tags:\n new_lines.append(f\" - {tag}\")\n\n new_lines.append(\"---\")\n\n return \"\\n\".join([line.rstrip() for line in new_lines]) + \"\\n\"\n\n\ndef process_file(file_path):\n with open(file_path, \"r\") as f:\n content = f.read()\n\n # Extract tags\n tags, content = extract_tags(content)\n\n # Add taxonomies to YAML frontmatter\n frontmatter_end = content.index(\"---\", 4) + 3\n frontmatter = content[:frontmatter_end]\n body = content[frontmatter_end:]\n new_frontmatter = update_frontmatter(frontmatter, tags)\n\n # Update content\n new_content = new_frontmatter + body\n\n return new_content\n\n\ndef main(input_folder, output_folder):\n input_path = Path(input_folder)\n output_path = Path(output_folder)\n\n # Clear output folder if exists, otherwise create it\n if output_path.exists():\n shutil.rmtree(output_path)\n os.makedirs(output_path)\n\n file_count = 0\n for root, _, files in os.walk(input_path):\n for file_name in files:\n if file_name.endswith(\".md\"):\n file_count += 1\n if file_count % 10 == 0:\n print(f\"Processed {file_count} files\")\n\n input_file_path = Path(root) / file_name\n relative_path = input_file_path.relative_to(input_path)\n output_file_path = output_path / relative_path\n\n # Create subdirectories in the output folder\n output_file_path.parent.mkdir(parents=True, exist_ok=True)\n\n # Process the file and save the result to the output folder\n new_content = process_file(input_file_path)\n with open(output_file_path, \"w\") as f:\n f.write(new_content)\n\n print(f\"Processed files are saved in the '{output_folder}' folder.\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Copy notes and move tags to YAML frontmatter.\"\n )\n parser.add_argument(\n \"src_folder\", type=str, help=\"Path to the original notes folder\"\n )\n parser.add_argument(\n \"dest_folder\",\n type=str,\n help=\"Path to the destination folder for copied notes with updated frontmatter\",\n )\n\n args = parser.parse_args()\n\n src_folder = args.src_folder\n dest_folder = args.dest_folder\n\n print(\"Adding tags to frontmatter...\")\n main(input_folder=src_folder, output_folder=dest_folder)\n","sub_path":".scripts/tagging.py","file_name":"tagging.py","file_ext":"py","file_size_in_byte":3493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"634011515","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n# __author__ = 'qiuzixian' http://blog.csdn.net/qqzhuimengren/ 1467288927@qq.com\n# @time :2017/12/14 19:33\n# @abstract : 有问题f\n\nfrom selenium import webdriver\nfrom selenium.webdriver import DesiredCapabilities\n# print(help(webdriver)) # 查看支持的浏览器\nurl = \"http://www.kuman.com/mh-1002960/\"\n\n# dcap = dict(DesiredCapabilities.PHANTOMJS)\n# dcap[\"pthantomjs.page.settings.userAgent\"] = (\"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36 LBBROWSER\")\n# browser = webdriver.PhantomJS()\nbrowser = webdriver.Firefox()\nbrowser.implicitly_wait(10)\nurl = \"http://www.bimclub.cn/down/201711/03/1273.html\"\nbrowser.get(url)\nbtn =browser.find_element_by_class_name(\"t\")\nbtn.click()\nbrowser.quit()\n\n# browser.get(url)\n# print(browser.title)\n# browser.save_screenshot('doupo.png')\n# # browser.set_window_size(400, 300)\n# src = browser.find_element_by_css_selector(\"#wdwailian img\").get_attribute(\"src\")\n# div = browser.find_element_by_id(\"wdwailian\")\n# print(src, \"/n\", div)\n#\n# browser.close()","sub_path":"test/selenium_1.py","file_name":"selenium_1.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"48526034","text":"import requests\nimport re\nfrom util import Events\nimport os\nimport urllib\nimport datetime\nimport dateutil.parser\nfrom PIL import Image\n\n# API-URL and type of headers sent by POST-request\nbilibili_api_url = \"http://vocadb.net/api/pvs?pvUrl=http://acg.tv/\"\njson_request_headers = \"{'content-type': 'application/json'}\"\nvocadb_api_url = \"http://vocadb.net/api/songs/bypv?pvService=Bilibili&lang=English&pvId=\"\n\n\nclass Plugin(object):\n def __init__(self, pm):\n self.pm = pm\n self.name = \"Bilibili\"\n\n @staticmethod\n def register_events():\n return [Events.Message(\"Bilibili\")]\n\n async def handle_message(self, message_object):\n \"\"\"\n Prints video info when a message contains a (average formatted) bilibili-url\n :param message_object: discord.Message object containing the message\n \"\"\"\n\n regex_result_list_unique = await self.find_bilibili_urls(message_object.content)\n\n for url_data in regex_result_list_unique:\n video_id = url_data[6]\n bilibili_api_response = requests.get(bilibili_api_url + video_id)\n\n if bilibili_api_response.status_code is 200:\n json_data = bilibili_api_response.json()\n\n # Fetch and process thumbnail\n filename = await self.download_thumbnail(json_data)\n await self.resize_thumbnail(filename)\n\n vocadb_api_response = requests.get(vocadb_api_url + video_id[2:])\n\n if vocadb_api_response.content == b'null':\n # Send raw bilibili info\n await self.pm.client.send_file(message_object.channel, filename,\n content=\"**Title:** \" + json_data[\"name\"] +\n \"\\n**Author:** \" + json_data[\"author\"] +\n \"\\n**Date:** \" + dateutil.parser.parse(\n json_data[\"publishDate\"]).strftime(\"%B %d, %Y\"))\n else:\n vocadb_data = vocadb_api_response.json()\n\n vocadb_url = \"\\n**VocaDB:** \"\n if \"originalVersionId\" in vocadb_data:\n vocadb_url += \"\\n**VocaDB (original):** \"\n\n if vocadb_data[\"songType\"] == \"Original\":\n song_type = \"\"\n else:\n song_type = \" (\" + vocadb_data[\"songType\"] + \")\"\n\n msg = \"**Title:** \" + vocadb_data[\"name\"] + song_type\n msg += \"\\n**Author:** \" + vocadb_data[\"artistString\"]\n msg += \"\\n**Date:** \" + dateutil.parser.parse(vocadb_data[\"createDate\"]).strftime(\"%B %d, %Y\")\n msg += vocadb_url\n\n await self.pm.client.send_file(message_object.channel, filename,\n content=msg)\n\n # Cleanup\n os.remove(filename)\n\n @staticmethod\n async def resize_thumbnail(filename):\n # Resize image\n base_width = 300\n img = Image.open(filename)\n w_percent = (base_width / float(img.size[0]))\n h_size = int((float(img.size[1]) * float(w_percent)))\n img = img.resize((base_width, h_size), Image.ANTIALIAS)\n img.save(filename)\n img.close()\n\n @staticmethod\n async def download_thumbnail(json_data):\n # Download thumbnail\n directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"../temp\")\n if not os.path.exists(directory):\n os.makedirs(directory)\n filename = os.path.join(directory, str(json_data[\"id\"]) + \".png\")\n urllib.request.urlretrieve(json_data[\"thumbUrl\"], filename)\n return filename\n\n async def find_bilibili_urls(self, message):\n regex_result_list = re.findall(\n r'((?<=http)((?<=s)|)://|)((?<=www.)|)((?<=bilibili\\.kankanews\\.com/video)|'\n r'((?<=bilibili.tv)|((?<=bilibili.com/video)|(?<=acg.tv))))/(av[0-9a-f]*)',\n message)\n regex_result_list_unique = (tuple(self.return_unique_set(regex_result_list)))\n return regex_result_list_unique\n\n @staticmethod\n def return_unique_set(iterable, key=None):\n # taken from more_itertools.unique_everseen instead of importing an extra dependency\n seenset = set()\n seenset_add = seenset.add\n seenlist = []\n seenlist_add = seenlist.append\n if key is None:\n for element in iterable:\n try:\n if element not in seenset:\n seenset_add(element)\n yield element\n except TypeError as e:\n if element not in seenlist:\n seenlist_add(element)\n yield element\n else:\n for element in iterable:\n k = key(element)\n try:\n if k not in seenset:\n seenset_add(k)\n yield element\n except TypeError as e:\n if k not in seenlist:\n seenlist_add(k)\n yield element\n return seenlist\n","sub_path":"plugins/Bilibili.py","file_name":"Bilibili.py","file_ext":"py","file_size_in_byte":5450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"359695160","text":"from typing import List\n\n\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n flag = 0\n for num in nums:\n if nums[flag] != num:\n flag += 1\n nums[flag] = num\n\n return len(nums) and flag + 1\n","sub_path":"26-remove-duplicates-from-sorted-array/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"254850351","text":"import os\n\nfrom argparse import ArgumentParser\nfrom sys import argv\nfrom sys import path\n\nfrom kb import KnowledgeBases\n\npath.insert(0, '../')\nfrom common.stanfordcorenlp.corenlpwrapper import CoreNLPWrapper\nfrom common.nlputils import NLPUtils\n\nclass Linker:\n\n def link(self, input_filename, k_base='babelfy', verbose=False):\n if not input_filename.startswith('/'):\n input_filename = os.path.dirname(os.path.realpath(__file__)) + '/' + input_filename\n\n print('Processing text from {}'.format(input_filename))\n\n with open(input_filename, 'r') as input_file:\n contents = input_file.read()\n input_file.close()\n\n prefixes, links = KnowledgeBases(k_base).annotate(contents, verbose)\n\n np_entities, verbs = NLPUtils.extract_np_and_verbs(contents)\n entities_linked = self.__associate_np_to_entities(np_entities, links)\n verbs_linked = self.__associate_verbs_to_entities(verbs, links)\n\n output_filename = os.path.splitext(input_filename)[0] + '_links.txt'\n open(output_filename, 'w').close() # Clean the file in case it exists\n\n with open(output_filename, 'a') as output_file:\n for key in prefixes.keys():\n output_file.write('@PREFIX\\t{}:\\t<{}>\\n'.format(prefixes[key], key))\n\n for key in verbs_linked.keys():\n output_file.write('@PREDICATE\\t{};{}\\n'.format(key.encode('utf-8'), verbs_linked[key]))\n\n for key in entities_linked.keys():\n output_file.write('@ENTITY\\t{};{}\\n'.format(key.encode('utf-8'), entities_linked[key]))\n output_file.close()\n print('Linked entities were stored at {}'.format(output_filename))\n\n return output_filename\n\n def __associate_np_to_entities(self, nps, links):\n nps_list = list(nps)\n nps_list.sort(key = len) # sort by string length\n\n np_entities = {}\n for np in nps_list:\n link_list = list()\n for key in links:\n if key.lower() == np.lower(): # exact match\n link_list = [links[key]]\n break;\n elif key.lower() in np.lower(): # composite\n link_list.append(links[key])\n\n if not len(link_list) == 0:\n np_entities[np.lower()] = ','.join(link_list)\n\n for np in nps_list:\n if not np.lower() in np_entities.keys():\n np_entities[np.lower()] = 'notfound:' + np.lower().replace(' ', '_')\n\n for np in nps_list:\n pos = nps_list.index(np)\n sub_nps_list = nps_list[pos + 1:]\n for sub_np in sub_nps_list:\n if np in sub_np and not np == sub_np:\n # merge both links lists\n tmp_set = set()\n tmp_set.update(np_entities[np.lower()].split(','))\n tmp_set.update(np_entities[sub_np.lower()].split(','))\n\n np_entities[sub_np.lower()] = ','.join(list(tmp_set))\n\n return np_entities\n\n def __associate_verbs_to_entities(self, verbs, links):\n verbs_list = list(verbs)\n\n verbs_entities = {}\n for verb in verbs_list:\n for key in links:\n if verb.lower() in key.lower():\n verbs_entities[verb.lower()] = links[key]\n break\n\n for verb in verbs_list:\n if not verb.lower() in verbs_entities.keys():\n verbs_entities[verb.lower()] = 'notfound:' + verb.lower()\n\n return verbs_entities\n\ndef main(args):\n arg_p = ArgumentParser('python linker.py', description='Links the text entities to URIs from a knowledge base.')\n arg_p.add_argument('-f', '--filename', type=str, default=None, help='Text file')\n arg_p.add_argument('-k', '--kgbase', type=str, default='babelfy', help='Knowledge base to be used, e.g. babelfy (default) or ncbo')\n arg_p.add_argument('-v', '--verbose', action='store_true', help='Prints extra information')\n\n args = arg_p.parse_args(args[1:])\n filename = args.filename\n kg_base = args.kgbase\n verbose = args.verbose\n\n if filename is None:\n print('No file provided.')\n exit(1)\n\n linker = Linker()\n linker.link(filename, kg_base, verbose)\n\nif __name__ == '__main__':\n exit(main(argv))\n\n","sub_path":"kb_linker/linker.py","file_name":"linker.py","file_ext":"py","file_size_in_byte":4326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"554037360","text":"from __future__ import annotations\nfrom mechanics.events import ActiveEvent\nfrom mechanics.actives import ActiveTags\nfrom battlefield import Cell\n\nimport traceback\nfrom contextlib import contextmanager\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from game_objects.battlefield_objects import Unit\n from typing import ClassVar, List, Callable, Union\n from mechanics.actives import Cost\n from DreamGame import DreamGame\n\nfrom mechanics.conditions.ActiveCheck import ActiveCheck\nfrom mechanics.conditions.ActiveCondition import ActiveCondition\n\n\nclass Active:\n last_uid = 0\n\n def __init__(self, targeting_cls: ClassVar = None, conditions: List[Callable] = None, cost: Union[Cost, Callable] = None,*,\n game: DreamGame=None, callbacks: List[Callable], tags: List[ActiveTags]=None,\n name: str = \"nameless active\", cooldown = 0, simulate = None, icon: str = \"fire.jpg\"):\n self.name = name\n self.game = game\n self.targeting_cls = targeting_cls\n self.checker = ActiveCheck(conditions)\n self._cost = cost or Cost()\n self.callbacks = callbacks\n self.owner: Unit = None\n self.spell = None\n self.tags = tags or []\n self.simulate_callback = simulate\n self.icon = icon\n\n self.cooldown = cooldown\n self.remaining_cd = 0\n\n Active.last_uid += 1\n self.uid = Active.last_uid\n\n\n def check_target(self, target):\n failing_conditions = self.checker.not_satisfied_conds(self, target)\n # for c in failing_conditions:\n # print(c.message(self, target))\n return len(failing_conditions) == 0\n\n def activate(self, target=None):\n from game_objects import battlefield_objects as bf_objs\n\n if self.targeting_cls in [bf_objs.Unit, bf_objs.BattlefieldObject]:\n assert isinstance(target, self.targeting_cls)\n assert self.owner is not None\n\n if self.affordable() and self.check_target(target):\n self.remaining_cd = self.cooldown\n self.owner.pay(self.cost)\n return ActiveEvent(self, target)\n else:\n return None\n\n def affordable(self):\n if self.remaining_cd > 0:\n return False\n if self.spell:\n if not self.spell.complexity_check(self.owner):\n return False\n return self.owner.can_pay(self.cost)\n\n\n def why_not_affordable(self) -> str:\n if self.spell:\n if not self.spell.complexity_check(self.owner):\n return f\"This spell is too complex for {self.owner}\"\n if not self.owner.can_pay(self.cost):\n return self.cost.complain(self.owner)\n if self.remaining_cd > 0:\n return \"Active is on cooldown.\"\n else:\n return \"Why not?! it is affordable.\"\n\n def why_wrong_target(self, target):\n return self.checker.complain(self, target)\n\n def resolve(self, targeting):\n for callback in self.callbacks:\n callback(self, targeting)\n\n @staticmethod\n def from_spell(spell, game=None):\n new_active = Active(spell.targeting_cls, [spell.targeting_cond] if spell.targeting_cond else None,\n spell.cost,\n cooldown=spell.cooldown,\n game=game,\n callbacks=[spell.resolve_callback],\n tags=[ActiveTags.MAGIC])\n new_active.spell = spell\n\n return new_active\n\n @contextmanager\n def simulate(self, target):\n with self.simulate_callback(self, target):\n yield\n\n @property\n def tooltip_info(self):\n return {\"name\":f\"{self.name}\"}\n\n # the hack is here because sometimes we want to calculate cost dynamically. setting property doesn't work -\n # deepcopy throws TypeError on properties. But it does not on lambdas. Therefore _cost is either a Cost\n # object, or a lambda self: -> Cost\n @property\n def cost(self) -> Cost:\n try:\n return self._cost(self)\n except TypeError as e:\n # traceback.print_exc()\n # print(e)\n return self._cost\n\n def __repr__(self):\n return f\"{self.name} active with {self.cost} cost ({self.tags[0] if len(self.tags) == 1 else self.tags}).\".capitalize()\n","sub_path":"mechanics/actives/active/Active.py","file_name":"Active.py","file_ext":"py","file_size_in_byte":4344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"476586340","text":"\"\"\"Validate post-ETL FERC 714 outputs and associated service territory analyses.\"\"\"\nimport logging\n\nimport pytest\n\nimport pudl\nfrom pudl import validate as pv\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.parametrize(\n \"df_name,expected_rows\",\n [\n (\"summarized_demand_ferc714\", 3_195),\n (\"fipsified_respondents_ferc714\", 135_627),\n (\"compiled_geometry_balancing_authority_eia861\", 108_436),\n (\"compiled_geometry_utility_eia861\", 237_872),\n ],\n)\ndef test_minmax_rows(\n pudl_out_orig: \"pudl.output.pudltabl.PudlTabl\",\n live_dbs: bool,\n expected_rows: int,\n df_name: str,\n):\n \"\"\"Verify that output DataFrames don't have too many or too few rows.\n\n Args:\n pudl_out_orig: A PudlTabl output object.\n live_dbs: Whether we're using a live or testing DB.\n expected_rows: Expected number of rows that the dataframe should\n contain when all data is loaded and is output without aggregation.\n df_name: Shorthand name identifying the dataframe, corresponding\n to the name of the function used to pull it from the PudlTabl\n output object.\n \"\"\"\n if not live_dbs:\n pytest.skip(\"Data validation only works with a live PUDL DB.\")\n _ = (\n pudl_out_orig.__getattribute__(df_name)()\n .pipe(\n pv.check_min_rows, expected_rows=expected_rows, margin=0.0, df_name=df_name\n )\n .pipe(\n pv.check_max_rows, expected_rows=expected_rows, margin=0.0, df_name=df_name\n )\n )\n","sub_path":"test/validate/service_territory_test.py","file_name":"service_territory_test.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"419876941","text":"from PyQt5.QtWidgets import (QWidget, QApplication, QDesktopWidget, QSpinBox, QPushButton, QMessageBox, QComboBox,\n QLabel, QToolTip, QTableWidget, QTableWidgetItem)\nfrom PyQt5.QtGui import QFont\nfrom PyQt5.QtCore import pyqtSlot, Qt\n\n\nclass ExpertTransportEditWidget(QWidget):\n\n # Конструктор\n def __init__(self, application, index, parent=None):\n super().__init__(parent)\n self.application = application\n self.index = index\n width_multiplier, height_multiplier = 0.4, 0.4\n self_width, self_height = QDesktopWidget().availableGeometry().width() * width_multiplier, \\\n QDesktopWidget().availableGeometry().height() * height_multiplier\n self.resize(self_width, self_height)\n self.setFixedSize(self_width, self_height)\n self.moveToCenter()\n self.leftMargin, self.rightMargin, self.topMargin, self.bottomMargin, self.betweenMargin = \\\n self_width * 0.02, self_width * 0.02, self_height * 0.05, self_height * 0.02, self_height * 0.05\n\n self.questions = self.application.logic.getQuestions()\n self.transport = self.application.logic.getTransport()\n self.weights = self.application.logic.getWeights(len(self.questions), len(self.transport))\n self.rowToDel = -1\n\n self.titleText = 'Редактор видов транспорта'\n self.title = QLabel(self)\n self.title.setText(self.titleText)\n self.title.resize(self.title.sizeHint())\n self.titleX, self.titleY = (self.width() - self.title.width()) / 2, self.topMargin\n self.title.move(self.titleX, self.titleY)\n\n self.transportTable = QTableWidget(self)\n self.transportTableX, self.transportTableY = \\\n self.leftMargin, self.titleY + self.title.height() + self.betweenMargin\n self.transportTable.move(self.transportTableX, self.transportTableY)\n self.transportTableWidth, self.transportTableHeight = 0.75 * self.width(), 0.7 * self.height()\n self.transportTable.resize(self.transportTableWidth, self.transportTableHeight)\n self.transportTable.setColumnCount(3)\n self.transportTable.setRowCount(len(self.transport))\n self.transportTable.setHorizontalHeaderItem(0, QTableWidgetItem('№'))\n self.transportTable.setHorizontalHeaderItem(1, QTableWidgetItem('Название'))\n self.transportTable.setHorizontalHeaderItem(2, QTableWidgetItem('Описание'))\n self.transportTable.horizontalHeader().setStretchLastSection(True)\n self.transportTable.verticalHeader().hide()\n for i in range(len(self.transport)):\n for j in range(3):\n cell_i_j = QTableWidgetItem(str(self.transport[i][j]))\n if j == 0:\n cell_i_j.setFlags(cell_i_j.flags() ^ Qt.ItemIsEditable ^ Qt.ItemIsSelectable)\n self.transportTable.setItem(i, j, cell_i_j)\n self.transportTable.currentCellChanged.connect(self.transportTable_currentCellChanged)\n\n self.addButtonText = 'Добавить'\n self.addButton = QPushButton(self)\n self.addButton.setText(self.addButtonText)\n self.addButtonX, self.addButtonY = \\\n self.transportTableX + self.transportTableWidth + self.betweenMargin, self.transportTableY\n self.addButtonWidth, self.addButtonHeight = \\\n self.width() - self.leftMargin - self.betweenMargin - self.rightMargin - self.transportTableWidth, \\\n self.addButton.sizeHint().height()\n self.addButton.move(self.addButtonX, self.addButtonY)\n self.addButton.resize(self.addButtonWidth, self.addButtonHeight)\n self.addButton.clicked.connect(self.addButton_clicked)\n\n self.deleteButtonText = 'Удалить'\n self.deleteButton = QPushButton(self)\n self.deleteButton.setText(self.deleteButtonText)\n self.deleteButtonX, self.deleteButtonY = \\\n self.addButtonX, self.addButtonY + self.addButtonHeight + self.betweenMargin\n self.deleteButtonWidth, self.deleteButtonHeight = self.addButtonWidth, self.addButtonHeight\n self.deleteButton.move(self.deleteButtonX, self.deleteButtonY)\n self.deleteButton.resize(self.deleteButtonWidth, self.deleteButtonHeight)\n self.deleteButton.setEnabled(False)\n self.deleteButton.clicked.connect(self.deleteButton_clicked)\n\n self.clearButtonText = 'Очистить'\n self.clearButton = QPushButton(self)\n self.clearButton.setText(self.clearButtonText)\n self.clearButtonX, self.clearButtonY = \\\n self.deleteButtonX, self.deleteButtonY + self.deleteButtonHeight + self.betweenMargin\n self.clearButtonWidth, self.clearButtonHeight = self.deleteButtonWidth, self.deleteButtonHeight\n self.clearButton.move(self.clearButtonX, self.clearButtonY)\n self.clearButton.resize(self.clearButtonWidth, self.clearButtonHeight)\n self.clearButton.clicked.connect(self.clearButton_clicked)\n\n self.backButtonText = 'Назад'\n self.backButton = QPushButton(self)\n self.backButton.setText(self.backButtonText)\n self.backButtonX, self.backButtonY = \\\n self.leftMargin, self.transportTableY + self.transportTableHeight + self.betweenMargin\n self.backButtonWidth, self.backButtonHeight = \\\n (self.width() - self.leftMargin - self.rightMargin - 2 * self.betweenMargin) / 3, \\\n self.backButton.sizeHint().height()\n self.backButton.move(self.backButtonX, self.backButtonY)\n self.backButton.resize(self.backButtonWidth, self.backButtonHeight)\n self.backButton.clicked.connect(self.backButton_clicked)\n\n self.toOpeningButtonText = 'В начало'\n self.toOpeningButton = QPushButton(self)\n self.toOpeningButton.setText(self.toOpeningButtonText)\n self.toOpeningButtonX, self.toOpeningButtonY = \\\n self.backButtonX + self.backButtonWidth + self.betweenMargin, self.backButtonY\n self.toOpeningButtonWidth, self.toOpeningButtonHeight = self.backButtonWidth, self.backButtonHeight\n self.toOpeningButton.move(self.toOpeningButtonX, self.toOpeningButtonY)\n self.toOpeningButton.resize(self.toOpeningButtonWidth, self.toOpeningButtonHeight)\n self.toOpeningButton.clicked.connect(self.toOpeningButton_clicked)\n\n self.applyButtonText = 'Применить'\n self.applyButton = QPushButton(self)\n self.applyButton.setText(self.applyButtonText)\n self.applyButtonX, self.applyButtonY = \\\n self.toOpeningButtonX + self.toOpeningButtonWidth + self.betweenMargin, self.toOpeningButtonY\n self.applyButtonWidth, self.applyButtonHeight = self.toOpeningButtonWidth, self.toOpeningButtonHeight\n self.applyButton.move(self.applyButtonX, self.applyButtonY)\n self.applyButton.resize(self.applyButtonWidth, self.applyButtonHeight)\n self.applyButton.clicked.connect(self.applyButton_clicked)\n\n # Метод перемещающий данную форму в центр экрана\n def moveToCenter(self):\n tmp_rectangle = self.frameGeometry()\n screen_center = QDesktopWidget().availableGeometry().center()\n tmp_rectangle.moveCenter(screen_center)\n self.move(tmp_rectangle.topLeft())\n\n @pyqtSlot()\n def addButton_clicked(self):\n self.transportTable.insertRow(self.transportTable.rowCount())\n cell_i_0 = QTableWidgetItem(str(self.transportTable.rowCount()))\n cell_i_0.setFlags(cell_i_0.flags() ^ Qt.ItemIsEditable ^ Qt.ItemIsSelectable)\n\n self.transportTable.setItem(self.transportTable.rowCount()-1, 0, cell_i_0)\n self.transportTable.setItem(self.transportTable.rowCount()-1, 1, QTableWidgetItem(''))\n self.transportTable.setItem(self.transportTable.rowCount()-1, 2, QTableWidgetItem(''))\n\n for i in range(len(self.weights)):\n self.weights[i].append(0.0)\n\n @pyqtSlot()\n def deleteButton_clicked(self):\n row_to_del = self.rowToDel\n if self.transportTable.rowCount() > 1:\n for i in range(row_to_del+1, self.transportTable.rowCount()):\n cell_i_0_prev_value = int(self.transportTable.item(i, 0).text())\n cell_i_0_new = QTableWidgetItem(str(cell_i_0_prev_value - 1))\n self.transportTable.setItem(i, 0, cell_i_0_new)\n self.transportTable.removeRow(row_to_del)\n try:\n for i in range(len(self.weights)):\n self.weights[i].pop(row_to_del)\n except IndexError:\n for i in range(len(self.weights)):\n self.weights[i].clear()\n\n @pyqtSlot()\n def clearButton_clicked(self):\n while self.transportTable.rowCount() != 0:\n self.transportTable.removeRow(0)\n for i in range(len(self.weights)):\n self.weights[i].clear()\n\n @pyqtSlot()\n def backButton_clicked(self):\n closeMessageBox = QMessageBox(\n QMessageBox.Question,\n 'Вы уверены?',\n 'При переходе на предыдущую вкладку вся введенная информация будет утеряна!\\nВы уверены, что хотите '\n 'продолжить?')\n yesButton, noButton = \\\n closeMessageBox.addButton('Да', QMessageBox.YesRole), \\\n closeMessageBox.addButton('Нет', QMessageBox.NoRole)\n closeMessageBox.exec_()\n if closeMessageBox.clickedButton() == yesButton:\n self.hide()\n self.__init__(self.application, self.index)\n self.application.GUI[self.application.expert_choice_index].show()\n else:\n return\n\n @pyqtSlot()\n def toOpeningButton_clicked(self):\n closeMessageBox = QMessageBox(QMessageBox.Question, 'Вы уверены?', 'При возврате в начало вся введенная '\n 'информация будет утеряна!\\nВы уверены, что '\n 'хотите продолжить?')\n yesButton, noButton = \\\n closeMessageBox.addButton('Да', QMessageBox.YesRole), \\\n closeMessageBox.addButton('Нет', QMessageBox.NoRole)\n closeMessageBox.exec_()\n if closeMessageBox.clickedButton() == yesButton:\n self.hide()\n self.__init__(self.application, self.index)\n self.application.GUI[0].show()\n else:\n return\n\n @pyqtSlot()\n def applyButton_clicked(self):\n applyMessageBox = QMessageBox(\n QMessageBox.Question,\n 'Вы уверены?',\n 'Вы уверены, что хотите применить введенные изменения?')\n yesButton, noButton = \\\n applyMessageBox.addButton('Да', QMessageBox.YesRole), \\\n applyMessageBox.addButton('Нет', QMessageBox.NoRole)\n applyMessageBox.exec_()\n if applyMessageBox.clickedButton() == yesButton:\n self.transport.clear()\n for i in range(self.transportTable.rowCount()):\n transport_tmp = (\n int(self.transportTable.item(i, 0).text()),\n self.transportTable.item(i, 1).text(),\n self.transportTable.item(i, 2).text()\n )\n self.transport.append(transport_tmp)\n self.application.logic.setWeightsAndTransport(self.weights, self.transport)\n doneMessageBox = QMessageBox(\n QMessageBox.Information,\n 'Готово',\n 'Изменения применены'\n )\n okButton = doneMessageBox.addButton('ОК', QMessageBox.AcceptRole)\n doneMessageBox.exec_()\n if doneMessageBox.clickedButton() == okButton:\n self.hide()\n self.__init__(self.application, self.index)\n self.application.GUI[self.application.expert_choice_index].show()\n else:\n return\n\n\n @pyqtSlot(int, int, int, int)\n def transportTable_currentCellChanged(self, current_row, current_col, prev_row, prev_col):\n if current_col == 0:\n self.deleteButton.setEnabled(False)\n self.rowToDel = -1\n else:\n self.deleteButton.setEnabled(True)\n self.rowToDel = current_row\n\n def closeEvent(self, event):\n closeMessageBox = QMessageBox(QMessageBox.Question, 'Вы уверены?', 'При закрытии приложения вся введенная '\n 'информация будет утеряна!\\nВы уверены, что '\n 'хотите продолжить?')\n yesButton, noButton = \\\n closeMessageBox.addButton('Да', QMessageBox.YesRole), \\\n closeMessageBox.addButton('Нет', QMessageBox.NoRole)\n closeMessageBox.exec_()\n if closeMessageBox.clickedButton() == yesButton:\n event.accept()\n else:\n event.ignore()\n","sub_path":"ExpertTransportEditWidget.py","file_name":"ExpertTransportEditWidget.py","file_ext":"py","file_size_in_byte":13357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"510743209","text":"# -*- coding: utf-8 -*-\n\"\"\"FAB Given step implementations.\"\"\"\nimport logging\nimport random\nimport re\nimport string\nfrom random import choice\nfrom urllib.parse import parse_qsl, quote, urljoin, urlsplit\n\nfrom behave.model import Table\nfrom behave.runner import Context\nfrom requests import Response, Session\nfrom scrapy import Selector\n\nfrom tests import get_absolute_url\nfrom tests.functional.common import DETAILS, PROFILES\nfrom tests.functional.pages import (\n fab_ui_build_profile_basic,\n fab_ui_build_profile_sector,\n fab_ui_build_profile_verification_letter,\n fab_ui_case_study_basic,\n fab_ui_case_study_images,\n fab_ui_confirm_company,\n fab_ui_confirm_export_status,\n fab_ui_confirm_identity,\n fab_ui_confirm_identity_letter,\n fab_ui_edit_description,\n fab_ui_edit_details,\n fab_ui_edit_online_profiles,\n fab_ui_edit_sector,\n fab_ui_landing,\n fab_ui_profile,\n fab_ui_upload_logo,\n fab_ui_verify_company,\n fas_ui_contact,\n fas_ui_feedback,\n fas_ui_find_supplier,\n fas_ui_profile,\n profile_ui_find_a_buyer,\n profile_ui_landing,\n sso_ui_change_password,\n sso_ui_confim_your_email,\n sso_ui_login,\n sso_ui_logout,\n sso_ui_password_reset,\n sso_ui_register,\n sso_ui_verify_your_email\n)\nfrom tests.functional.registry import get_fabs_page_object, get_fabs_page_url\nfrom tests.functional.utils.context_utils import Company\nfrom tests.functional.utils.db_utils import get_verification_code\nfrom tests.functional.utils.generic import (\n assertion_msg,\n escape_html,\n extract_and_set_csrf_middleware_token,\n extract_csrf_middleware_token,\n extract_form_action,\n extract_logo_url,\n get_absolute_path_of_file,\n get_active_company_without_fas_profile,\n get_language_code,\n get_md5_hash_of_file,\n get_number_of_search_result_pages,\n is_already_registered,\n is_inactive,\n random_case_study_data,\n random_chars,\n random_feedback_data,\n random_message_data,\n rare_word,\n sentence\n)\nfrom tests.functional.utils.request import Method, check_response, make_request\nfrom tests.settings import (\n COUNTRIES,\n NO_OF_EMPLOYEES,\n SECTORS,\n SEPARATORS,\n BMPs,\n JP2s,\n WEBPs\n)\n\n\ndef select_random_company(\n context: Context, supplier_alias: str, company_alias: str):\n \"\"\"Will try to find an active company that doesn't have a FAS profile.\n\n Steps (repeat until successful):\n 1 - generate a random Companies House Number\n 2 - check if there's a FAS profile for it\n 3 - check if such company is registered at Companies House & is active\n\n Once a matching company is found, then it's data will be stored in:\n context.scenario_data.companies[]\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :param company_alias: alias of the company used in the scope of the scenario\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n\n while True:\n # Step 1 - find an active company without a FAS profile\n company = get_active_company_without_fas_profile(company_alias)\n\n # Step 2 - Go to the Confirm Company page\n response = fab_ui_confirm_company.go_to(session, company)\n registered = is_already_registered(response)\n inactive = is_inactive(response)\n if registered or inactive:\n logging.warning(\n \"Company '%s' is already registered or inactive, will use \"\n \"a different one\", company.title)\n continue\n else:\n logging.warning(\n \"Company '%s' is active and not registered with FAB\",\n company.title)\n context.response = response\n break\n\n # Step 3 - check if we're on the Confirm Company page\n fab_ui_confirm_company.should_be_here(response, company)\n\n # Step 4 - store Company, CSRF token & associate Actor with Company\n context.add_company(company)\n token = extract_csrf_middleware_token(response)\n context.update_actor(supplier_alias, csrfmiddlewaretoken=token)\n context.update_actor(supplier_alias, company_alias=company_alias)\n\n\ndef reg_confirm_company_selection(\n context: Context, supplier_alias: str, company_alias: str):\n \"\"\"Will confirm that the selected company is the right one.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :param company_alias: alias of the company used in the scope of the scenario\n \"\"\"\n actor = context.get_actor(supplier_alias)\n token = actor.csrfmiddlewaretoken\n has_sso_account = actor.has_sso_account\n session = actor.session\n company = context.get_company(company_alias)\n\n # Step 1 - confirm the selection of the company\n response = fab_ui_confirm_company.confirm_company_selection(\n session, company, token)\n context.response = response\n\n # Step 2 - check if we're on the Confirm Export Status page\n fab_ui_confirm_export_status.should_be_here(response)\n if not has_sso_account:\n fab_ui_confirm_export_status.should_see_info_about_sso_account(response)\n\n logging.debug(\"Confirmed selection of Company: %s\", company.number)\n\n # Step 3 - extract & store CSRF token\n token = extract_csrf_middleware_token(response)\n context.update_actor(supplier_alias, csrfmiddlewaretoken=token)\n\n\ndef reg_supplier_is_not_ready_to_export(context, supplier_alias):\n \"\"\"Supplier decides that her/his company is not ready to export.\n\n :param context: behave `context` object\n :type context: behave.runner.Context\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :type supplier_alias: str\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n token = actor.csrfmiddlewaretoken\n\n # Step 1 - Submit the form with No Intention to Export\n response = fab_ui_confirm_export_status.submit(\n session, token, exported=False)\n\n # Step 2 - store response & check it\n context.response = response\n check_response(response, 200)\n\n\ndef reg_confirm_export_status(\n context: Context, supplier_alias: str, exported: bool):\n \"\"\"Will confirm the current export status of selected unregistered company.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :param exported: True is exported in the past, False if not\n \"\"\"\n actor = context.get_actor(supplier_alias)\n has_sso_account = actor.has_sso_account\n session = actor.session\n token = actor.csrfmiddlewaretoken\n context.exported = exported\n\n response = fab_ui_confirm_export_status.submit(session, token, exported)\n context.response = response\n\n if has_sso_account:\n logging.debug(\"Supplier already has a SSO account\")\n fab_ui_build_profile_basic.should_be_here(response)\n else:\n logging.debug(\"Supplier doesn't have a SSO account\")\n sso_ui_register.should_be_here(response)\n token = extract_csrf_middleware_token(response)\n context.update_actor(supplier_alias, csrfmiddlewaretoken=token)\n\n\ndef reg_create_sso_account(context, supplier_alias, alias):\n \"\"\"Will create a SSO account for selected company.\n\n NOTE:\n Will use credentials randomly generated at Actor's initialization.\n It will also store final response in `context`\n\n :param context: behave `context` object\n :type context: behave.runner.Context\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :type supplier_alias: str\n :param alias: alias of the company used in the scope of the scenario\n :type alias: str\n \"\"\"\n actor = context.get_actor(supplier_alias)\n company = context.get_company(alias)\n exported = context.exported\n\n # Submit SSO Registration form with Supplier's & Company's required details\n context.response = sso_ui_register.submit(actor, company, exported)\n\n\ndef reg_open_email_confirmation_link(context, supplier_alias):\n \"\"\"Given Supplier has received a message with email confirmation link\n Then Supplier has to click on that link.\n\n :param context: behave `context` object\n :type context: behave.runner.Context\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :type supplier_alias: str\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n link = actor.email_confirmation_link\n\n # Step 1 - open confirmation link\n response = sso_ui_confim_your_email.open_confirmation_link(session, link)\n context.response = response\n\n # Step 3 - confirm that Supplier is on SSO Confirm Your Email page\n sso_ui_confim_your_email.should_be_here(response)\n logging.debug(\"Supplier is on the SSO Confirm your email address page\")\n\n # Step 4 - extract & store CSRF token & form action value\n # Form Action Value is required to successfully confirm email\n token = extract_csrf_middleware_token(response)\n context.update_actor(supplier_alias, csrfmiddlewaretoken=token)\n form_action_value = extract_form_action(response)\n context.form_action_value = form_action_value\n\n\ndef reg_supplier_confirms_email_address(context, supplier_alias):\n \"\"\"Given Supplier has clicked on the email confirmation link, Suppliers has\n to confirm that the provided email address is the correct one.\n\n :param context: behave `context` object\n :type context: behave.runner.Context\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :type supplier_alias: str\n \"\"\"\n actor = context.get_actor(supplier_alias)\n form_action_value = context.form_action_value\n\n response = sso_ui_confim_your_email.confirm(actor, form_action_value)\n context.response = response\n\n\ndef bp_provide_company_details(context, supplier_alias):\n \"\"\"Build Profile - Provide company details: website (optional), keywords\n and number of employees.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n actor = context.get_actor(supplier_alias)\n company = context.get_company(actor.company_alias)\n company_alias = company.alias\n\n # Step 0 - generate random details & update Company matching details\n # Need to get Company details after updating it in the Scenario Data\n title = \"{} {}\".format(company.title, sentence())\n size = random.choice(NO_OF_EMPLOYEES)\n website = \"http://{}.{}\".format(rare_word(min_length=15), rare_word())\n keywords = \", \".join(sentence().split())\n context.set_company_details(\n company_alias, title=title, no_employees=size, website=website,\n keywords=keywords\n )\n company = context.get_company(actor.company_alias)\n\n # Step 1 - submit the Basic details form\n response = fab_ui_build_profile_basic.submit(actor, company)\n context.response = response\n\n # Step 2 - check if Supplier is on Select Your Sector page\n fab_ui_build_profile_sector.should_be_here(response)\n\n # Step 3 - extract CSRF token\n logging.debug(\"Supplier is on the Select Sector page\")\n token = extract_csrf_middleware_token(response)\n context.update_actor(supplier_alias, csrfmiddlewaretoken=token)\n\n\ndef bp_select_random_sector_and_export_to_country(context, supplier_alias):\n \"\"\"Build Profile - Randomly select one of available sectors our company is\n interested in working in.\n\n NOTE:\n This will set `context.details` which will contain company details extracted\n from the page displayed after Supplier selects the sector.\n\n :param context: behave `context` object\n :type context: behave.runner.Context\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :type supplier_alias: str\n \"\"\"\n actor = context.get_actor(supplier_alias)\n sector = random.choice(SECTORS)\n countries = [COUNTRIES[random.choice(list(COUNTRIES))]]\n other = \"\"\n\n # Step 1 - Submit the Choose Your Sector form\n response = fab_ui_build_profile_sector.submit(actor, sector, countries, other)\n context.response = response\n\n # Step 2 - check if Supplier is on Confirm Address page\n fab_ui_confirm_identity.should_be_here(response, profile_building=True)\n logging.debug(\"Supplier is on the Confirm your Identity page\")\n\n\ndef bp_verify_identity_with_letter(context: Context, supplier_alias: str):\n \"\"\"Build Profile - verify identity with a physical letter.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n\n # Step 1 - Choose to verify with a letter\n response = fab_ui_confirm_identity.send(actor)\n context.response = response\n\n # Step 2 - check if Supplier is on the We've sent you a verification letter\n fab_ui_confirm_identity_letter.should_be_here(response)\n logging.debug(\n \"Supplier is on the 'Your company address' letter verification page\")\n\n # Step 3 - extract & store CSRF token\n token = extract_csrf_middleware_token(response)\n context.update_actor(supplier_alias, csrfmiddlewaretoken=token)\n\n # Step 4 - check if Supplier is on the We've sent you a verification letter\n fab_ui_confirm_identity_letter.submit(actor)\n context.response = response\n\n # Step 5 - Click on the \"View or amend your company profile\" link\n # use previous url as the referer link\n response = fab_ui_build_profile_verification_letter.go_to_profile(session)\n context.response = response\n\n # Step 6 - check if Supplier is on the FAB profile page\n fab_ui_profile.should_see_missing_description(response)\n\n\ndef prof_set_company_description(context, supplier_alias):\n \"\"\"Edit Profile - Will set company description.\n\n This is quasi-mandatory (*) step before Supplier can verify the company with\n the code sent in a letter.\n\n (*) it's quasi mandatory, because Supplier can actually go to the company\n verification page using the link provided in the letter without the need\n to set company description.\n\n :param context: behave `context` object\n :type context: behave.runner.Context\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :type supplier_alias: str\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n\n # Step 1 - go to the \"Set Company Description\" page\n response = fab_ui_edit_description.go_to(session)\n\n token = extract_csrf_middleware_token(response)\n context.update_actor(supplier_alias, csrfmiddlewaretoken=token)\n logging.debug(\"Supplier is on the Set Company Description page\")\n\n # Step 2 - Submit company description\n summary = sentence()\n description = sentence()\n response = fab_ui_edit_description.submit(\n session, token, summary, description)\n context.response = response\n\n # Step 3 - check if Supplier is on Profile page\n fab_ui_profile.should_see_profile_is_not_verified(response)\n\n # Step 4 - update company details in Scenario Data\n context.set_company_details(\n actor.company_alias, summary=summary, description=description)\n logging.debug(\"Supplier is back to the Profile Page\")\n\n\ndef prof_verify_company(context, supplier_alias):\n \"\"\"Will verify the company by submitting the verification code that is sent\n by post to the company's address.\n\n :param context: behave `context` object\n :type context: behave.runner.Context\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :type supplier_alias: str\n \"\"\"\n actor = context.get_actor(supplier_alias)\n company = context.get_company(actor.company_alias)\n session = actor.session\n\n # STEP 0 - get the verification code from DB\n verification_code = get_verification_code(company.number)\n\n # STEP 1 - go to the \"Verify your company\" page\n response = fab_ui_verify_company.go_to(session)\n context.response = response\n\n # STEP 2 - extract CSRF token\n token = extract_csrf_middleware_token(response)\n context.update_actor(supplier_alias, csrfmiddlewaretoken=token)\n\n # STEP 3 - Submit the verification code\n response = fab_ui_verify_company.submit(session, token, verification_code)\n context.response = response\n\n # STEP 4 - check if code was accepted\n fab_ui_verify_company.should_see_company_is_verified(response)\n\n # STEP 5 - click on the \"View or amend your company profile\" link\n response = fab_ui_verify_company.view_or_amend_profile(session)\n context.response = response\n\n # STEP 6 - check if Supplier is on Verified Profile Page\n fab_ui_profile.should_see_profile_is_verified(response)\n\n\ndef prof_view_published_profile(context, supplier_alias):\n \"\"\"Whilst being of FAB company profile page it will `click` on\n the `View published profile` link.\n\n :param context: behave `context` object\n :type context: behave.runner.Context\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :type supplier_alias: str\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n company = context.get_company(actor.company_alias)\n\n # STEP 1 - go to the \"View published profile\" page\n response = fas_ui_profile.go_to(session, company.number)\n context.response = response\n logging.debug(\"Supplier is on the company's FAS page\")\n\n\ndef prof_attempt_to_sign_in_to_fab(context, supplier_alias):\n \"\"\"Try to sign in to FAB as a Supplier without verified email address.\n\n :param context: behave `context` object\n :type context: behave.runner.Context\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :type supplier_alias: str\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n\n # Step 1 - Get to the Sign In page\n response = sso_ui_login.go_to(session)\n context.response = response\n\n # Step 2 - check if Supplier is on SSO Login page & extract CSRF token\n sso_ui_login.should_be_here(response)\n with assertion_msg(\n \"It looks like user is still logged in, as the \"\n \"sso_display_logged_in cookie is not equal to False\"):\n assert response.cookies.get(\"sso_display_logged_in\") == \"false\"\n token = extract_csrf_middleware_token(response)\n context.update_actor(supplier_alias, csrfmiddlewaretoken=token)\n\n # Step 3 - submit the login form\n response = sso_ui_login.login(actor)\n context.response = response\n\n\ndef prof_sign_out_from_fab(context, supplier_alias):\n \"\"\"Sign out from Find a Buyer.\n\n :param context: behave `context` object\n :type context: behave.runner.Context\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :type supplier_alias: str\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n\n # Step 1 - Get to the Sign Out confirmation page\n response = sso_ui_logout.go_to(session)\n context.response = response\n\n # Step 2 - check if Supplier is on Log Out page & extract CSRF token\n sso_ui_logout.should_be_here(response)\n token = extract_csrf_middleware_token(response)\n context.update_actor(supplier_alias, csrfmiddlewaretoken=token)\n\n # Step 3 - log out\n response = sso_ui_logout.logout(session, token)\n context.response = response\n\n # Step 4 - check if Supplier is on FAB Landing page & is logged out\n fab_ui_landing.should_be_here(response)\n fab_ui_landing.should_be_logged_out(response)\n\n # Step 5 - reset requests Session object\n context.reset_actor_session(supplier_alias)\n\n\ndef prof_sign_in_to_fab(context, supplier_alias):\n \"\"\"Sign in to Find a Buyer.\n\n :param context: behave `context` object\n :type context: behave.runner.Context\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :type supplier_alias: str\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n\n # Step 1 - Get to the Sign In page\n response = sso_ui_login.go_to(session)\n context.response = response\n\n # Step 2 - check if Supplier is on the SSO Login page\n sso_ui_login.should_be_here(response)\n with assertion_msg(\n \"It looks like user is still logged in, as the \"\n \"sso_display_logged_in cookie is not equal to False\"):\n assert response.cookies.get(\"sso_display_logged_in\") == \"false\"\n\n # Step 3 - extract CSRF token\n token = extract_csrf_middleware_token(response)\n context.update_actor(supplier_alias, csrfmiddlewaretoken=token)\n\n # Step 4 - submit the login form\n response = sso_ui_login.login(actor)\n context.response = response\n\n # Step 5 - check if Supplier is on the FAB profile page\n fab_ui_profile.should_be_here(response)\n with assertion_msg(\n \"Found sso_display_logged_in cookie in the response. Maybe user is\"\n \" still logged in?\"):\n assert \"sso_display_logged_in\" not in response.cookies\n with assertion_msg(\n \"Found directory_sso_dev_session cookie in the response. Maybe \"\n \"user is still logged in?\"):\n assert \"directory_sso_dev_session\" not in response.cookies\n\n\ndef reg_create_standalone_unverified_sso_account(\n context: Context, supplier_alias: str):\n \"\"\"Will create a standalone SSO/great.gov.uk account.\n\n NOTE:\n There will be no association between this account and any company.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n\n # Step 1: Go to the SSO/great.gov.uk registration page\n response = sso_ui_register.go_to(session)\n context.response = response\n\n # Step 2: Check if User is not logged in\n with assertion_msg(\n \"It looks like user is still logged in, as the \"\n \"sso_display_logged_in cookie is not equal to False\"):\n assert response.cookies.get(\"sso_display_logged_in\") == \"false\"\n\n # Step 3: POST SSO accounts/signup/\n response = sso_ui_register.submit_no_company(actor)\n context.response = response\n\n # Step 3: Check if Supplier is on Verify your email page & is not logged in\n sso_ui_verify_your_email.should_be_here(response)\n with assertion_msg(\n \"It looks like user is still logged in, as the \"\n \"sso_display_logged_in cookie is not equal to False\"):\n assert response.cookies.get(\"sso_display_logged_in\") == \"false\"\n\n\ndef sso_supplier_confirms_email_address(context, supplier_alias):\n \"\"\"Given Supplier has clicked on the email confirmation link, Suppliers has\n to confirm that the provided email address is the correct one.\n\n :param context: behave `context` object\n :type context: behave.runner.Context\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :type supplier_alias: str\n \"\"\"\n actor = context.get_actor(supplier_alias)\n form_action_value = context.form_action_value\n\n # STEP 1 - Submit \"Confirm your email address\" form\n response = sso_ui_confim_your_email.confirm(actor, form_action_value)\n context.response = response\n\n # STEP 2 - Check if Supplier if on SSO Profile Landing page\n profile_ui_landing.should_be_here(response)\n\n # STEP 3 - Update Actor's data\n context.update_actor(supplier_alias, has_sso_account=True)\n\n\ndef sso_go_to_create_trade_profile(context, supplier_alias):\n \"\"\"Follow the 'Create a trade profile' button on the \"Find a Buyer\" tab.\n\n NOTE:\n It's assumed that Supplier already has a standalone SSO/great.gov.uk account\n\n :param context: behave `context` object\n :type context: behave.runner.Context\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :type supplier_alias: str\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n\n # Step 1 - Go to \"Find a Buyer\" tab\n response = profile_ui_find_a_buyer.go_to(session)\n context.response = response\n profile_ui_find_a_buyer.should_see_get_a_trade_profile(response)\n\n # Step 2 - Click on \"Create a trade profile\" button\n response = profile_ui_find_a_buyer.go_to_create_a_trade_profile(session)\n context.response = response\n fab_ui_landing.should_be_here(response)\n\n\ndef prof_upload_logo(context, supplier_alias, picture: str):\n \"\"\"Upload Company's logo & extract newly uploaded logo image URL.\n\n NOTE:\n picture must represent file stored in ./tests/functional/files\n\n :param context: behave `context` object\n :type context: behave.runner.Context\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :type supplier_alias: str\n :param picture: name of the picture file stored in ./tests/functional/files\n :type picture: str\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n token = actor.csrfmiddlewaretoken\n file_path = get_absolute_path_of_file(picture)\n\n # Step 1 - Upload company's logo\n response = fab_ui_upload_logo.upload(session, token, file_path)\n context.response = response\n\n # Step 2 - check if Supplier is on the FAB profile page\n fab_ui_profile.should_be_here(response)\n logging.debug(\"Successfully uploaded logo picture: %s\", picture)\n\n # Step 3 - Keep logo details in Company's scenario data\n logo_url = extract_logo_url(response)\n md5_hash = get_md5_hash_of_file(file_path)\n context.set_company_logo_detail(\n actor.company_alias, picture=picture, hash=md5_hash, url=logo_url)\n\n\ndef prof_upload_unsupported_file_as_logo(context, supplier_alias, file):\n \"\"\"Try to upload unsupported file type as Company's logo.\n\n NOTE:\n file must exist in ./tests/functional/files\n\n :param context: behave `context` object\n :type context: behave.runner.Context\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :type supplier_alias: str\n :param file: name of the file stored in ./tests/functional/files\n :type file: str\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n token = actor.csrfmiddlewaretoken\n file_path = get_absolute_path_of_file(file)\n\n logging.debug(\"Attempting to upload %s as company logo\", file)\n # Step 1 - Try to upload a file of unsupported type as company's logo\n response = fab_ui_upload_logo.upload(session, token, file_path)\n context.response = response\n\n # Step 2 - check if upload was rejected\n rejected = fab_ui_upload_logo.was_upload_rejected(response)\n\n # There are 2 different error message that you can get, depending of the\n # type of uploaded file.\n # Here, we're checking if `any` of these 2 message is visible.\n if rejected:\n logging.debug(\"%s was rejected\", file)\n else:\n logging.error(\"%s was accepted\", file)\n return rejected\n\n\ndef prof_supplier_uploads_logo(context, supplier_alias, picture):\n \"\"\"Upload a picture and set it as Company's logo.\n\n :param context: behave `context` object\n :type context: behave.runner.Context\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :type supplier_alias: str\n :param picture: name of the picture file stored in ./tests/functional/files\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n\n # Step 1 - go to Upload Logo page\n response = fab_ui_upload_logo.go_to(session)\n context.response = response\n\n # Step 2 - extract CSRF token\n token = extract_csrf_middleware_token(response)\n context.update_actor(supplier_alias, csrfmiddlewaretoken=token)\n\n # Step 3 - upload the logo\n prof_upload_logo(context, supplier_alias, picture)\n\n\ndef prof_to_upload_unsupported_logos(\n context: Context, supplier_alias: str, table: Table):\n \"\"\"Upload a picture and set it as Company's logo.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :param table: context.table containing data table\n see: https://pythonhosted.org/behave/gherkin.html#table\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n files = [row['file'] for row in table]\n rejections = []\n for file in files:\n fab_ui_upload_logo.go_to(session)\n rejected = prof_upload_unsupported_file_as_logo(\n context, supplier_alias, file)\n rejections.append(rejected)\n context.rejections = rejections\n\n\ndef prof_update_company_details(\n context: Context, supplier_alias: str, table_of_details: Table):\n \"\"\"Update selected Company's details.\n\n NOTE:\n `table_of_details` contains names of details to update.\n Passing `table_of_details` can be avoided as we already have access to\n `context` object, yet in order to be more explicit, we're making it\n a mandatory argument.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :param table_of_details: context.table containing data table\n see: https://pythonhosted.org/behave/gherkin.html#table\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n company = context.get_company(actor.company_alias)\n\n # Step 0 - prepare company's details to update\n details_to_update = [row[\"detail\"] for row in table_of_details]\n title = DETAILS[\"TITLE\"] in details_to_update\n keywords = DETAILS[\"KEYWORDS\"] in details_to_update\n website = DETAILS[\"WEBSITE\"] in details_to_update\n size = DETAILS[\"SIZE\"] in details_to_update\n sector = DETAILS[\"SECTOR\"] in details_to_update\n countries = DETAILS[\"COUNTRIES\"] in details_to_update\n\n # Steps 1 - Go to the FAB Edit Company's details page\n response = fab_ui_edit_details.go_to(session)\n context.response = response\n\n # Step 2 - extract CSRF token\n token = extract_csrf_middleware_token(response)\n context.update_actor(supplier_alias, csrfmiddlewaretoken=token)\n\n # Step 3 - Update company's details\n response, new_details = fab_ui_edit_details.update_details(\n actor, company, title=title, keywords=keywords,\n website=website, size=size)\n context.response = response\n\n # Step 4 - Supplier should be on Edit Profile page\n fab_ui_profile.should_be_here(response)\n\n # Step 5 - Go to the Edit Sector page\n response = fab_ui_edit_sector.go_to(session)\n context.response = response\n\n # Step 5 - extract CSRF token\n token = extract_csrf_middleware_token(response)\n context.update_actor(supplier_alias, csrfmiddlewaretoken=token)\n\n # Step 6 - Update company's sector\n response, new_sector, new_countries = fab_ui_edit_sector.update(\n actor, company, update_sector=sector, update_countries=countries)\n context.response = response\n\n # Step 7 - Check if Supplier is on FAB Profile page\n fab_ui_profile.should_be_here(response)\n\n # Step 7 - update company's details stored in context.scenario_data\n context.set_company_details(\n actor.company_alias, title=new_details.title,\n website=new_details.website, keywords=new_details.keywords,\n no_employees=new_details.no_employees, sector=new_sector,\n export_to_countries=new_countries)\n logging.debug(\n \"%s successfully updated basic Company's details: title=%s, website=%s,\"\n \" keywords=%s, number of employees=%s, sector=%s, countries=%s\",\n supplier_alias, new_details.title, new_details.website,\n new_details.keywords, new_details.no_employees, new_sector,\n new_countries)\n\n\ndef prof_add_online_profiles(\n context: Context, supplier_alias: str, online_profiles: Table):\n \"\"\"Update links to Company's Online Profiles.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :param online_profiles: context.table containing data table\n see: https://pythonhosted.org/behave/gherkin.html#table\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n company = context.get_company(actor.company_alias)\n profiles = [row[\"online profile\"] for row in online_profiles]\n facebook = PROFILES[\"FACEBOOK\"] in profiles\n linkedin = PROFILES[\"LINKEDIN\"] in profiles\n twitter = PROFILES[\"TWITTER\"] in profiles\n\n # Step 1 - Go to the FAB Edit Online Profiles page\n response = fab_ui_edit_online_profiles.go_to(session)\n context.response = response\n\n # Step 2 - Extract CSRF token\n extract_and_set_csrf_middleware_token(context, response, supplier_alias)\n\n # Step 3 - Update links to Online Profiles\n response, new_details = fab_ui_edit_online_profiles.update_profiles(\n actor, company, facebook=facebook, linkedin=linkedin, twitter=twitter)\n context.response = response\n\n # Step 4 - Check if Supplier is on FAB Profile page\n fab_ui_profile.should_be_here(response)\n\n # Step 5 - Update company's details stored in context.scenario_data\n context.set_company_details(\n company.alias, facebook=new_details.facebook,\n linkedin=new_details.linkedin, twitter=new_details.twitter)\n logging.debug(\n \"%s set Company's Online Profile links to: Facebook=%s, LinkedId=%s, \"\n \"Twitter=%s\", supplier_alias, new_details.facebook,\n new_details.linkedin, new_details.twitter)\n\n\ndef prof_add_invalid_online_profiles(\n context: Context, supplier_alias: str, online_profiles: Table):\n \"\"\"Attempt to update links to Company's Online Profiles using invalid URLs.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :param online_profiles: context.table containing data table\n see: https://pythonhosted.org/behave/gherkin.html#table\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n company = context.get_company(actor.company_alias)\n facebook = False\n linkedin = False\n twitter = False\n facebook_url = \"http://notfacebook.com\"\n linkedin_url = \"http://notlinkedin.com\"\n twitter_url = \"http://nottwitter.com\"\n for row in online_profiles:\n if row[\"online profile\"] == PROFILES[\"FACEBOOK\"]:\n facebook = True\n facebook_url = row.get(\"invalid link\", facebook_url)\n if row[\"online profile\"] == PROFILES[\"LINKEDIN\"]:\n linkedin = True\n linkedin_url = row.get(\"invalid link\", linkedin_url)\n if row[\"online profile\"] == PROFILES[\"TWITTER\"]:\n twitter = True\n twitter_url = row.get(\"invalid link\", twitter_url)\n\n # Step 1 - Go to the Edit Online Profiles page\n response = fab_ui_edit_online_profiles.go_to(session)\n context.response = response\n\n # Step 2 - Extract CSRF token\n extract_and_set_csrf_middleware_token(context, response, supplier_alias)\n\n # Step 3 - update links to Online Profiles\n logging.debug(\n \"Will use following invalid URLs to Online Profiles: %s %s %s\",\n facebook_url if facebook else \"\", linkedin_url if linkedin else \"\",\n twitter_url if twitter else \"\")\n response, _ = fab_ui_edit_online_profiles.update_profiles(\n actor, company, facebook=facebook, linkedin=linkedin,\n twitter=twitter, specific_facebook=facebook_url,\n specific_linkedin=linkedin_url, specific_twitter=twitter_url)\n context.response = response\n\n\ndef prof_remove_links_to_online_profiles(context, supplier_alias):\n \"\"\"Will remove links to existing Online Profiles.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n actor = context.get_actor(supplier_alias)\n company = context.get_company(actor.company_alias)\n\n facebook = True if company.facebook else False\n linkedin = True if company.linkedin else False\n twitter = True if company.twitter else False\n\n response = fab_ui_edit_online_profiles.remove_links(\n actor, company, facebook=facebook, linkedin=linkedin, twitter=twitter)\n context.response = response\n\n\ndef prof_add_case_study(context, supplier_alias, case_alias):\n \"\"\"Will add a complete case study (all fields will be filled out).\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n :param case_alias: alias of the Case Study used in the scope of the scenario\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n case_study = random_case_study_data(case_alias)\n\n # Step 1 - go to \"Add case study\" form & extract CSRF token\n response = fab_ui_case_study_basic.go_to(session)\n context.response = response\n token = extract_csrf_middleware_token(response)\n\n # Step 2 - submit the \"basic case study data\" form & extract CSRF token\n response = fab_ui_case_study_basic.submit_form(session, token, case_study)\n context.response = response\n fab_ui_case_study_images.should_be_here(response)\n token = extract_csrf_middleware_token(response)\n\n # Step 3 - submit the \"case study images\" form\n response = fab_ui_case_study_images.submit_form(session, token, case_study)\n context.response = response\n\n # Step 4 - check if we're on the FAB Profile page\n fab_ui_profile.should_be_here(response)\n\n # Step 5 - Store Case Study data in Scenario Data\n context.add_case_study(actor.company_alias, case_alias, case_study)\n\n\ndef fab_update_case_study(\n context: Context, supplier_alias: str, case_alias: str):\n actor = context.get_actor(supplier_alias)\n session = actor.session\n company = context.get_company(actor.company_alias)\n # get content from last response (which contains FAB Profile Page)\n content = context.response.content.decode(\"utf-8\")\n\n # Step 0 - extract links to Case Studies and do a crude mapping to\n # Case Study titles.\n css_selector_titles = (\"div.ed-company-profile-sector-case-study-container\"\n \".company-profile-module-container h4::text\")\n css_selector = (\"div.row-fluid.ed-company-profile-sector-case-study-inner \"\n \"p + a::attr(href)\")\n titles = Selector(text=content).css(css_selector_titles).extract()\n links = Selector(text=content).css(css_selector).extract()\n case_link_mappings = {k: v for (k, v) in zip(titles, links)}\n current = company.case_studies[case_alias]\n current_link = case_link_mappings[current.title]\n current_number = int(current_link.split('/')[-1])\n logging.debug(\n \"Extracted link for case study: %s is: %s\", case_alias, current_link)\n\n # Step 1 - generate new case study data\n new_case = random_case_study_data(case_alias)\n logging.debug(\"Now will replace case study data with: %s\", new_case)\n\n # Step 2 - go to specific \"Case study\" page form & extract CSRF token\n response = fab_ui_case_study_basic.go_to(\n session, case_number=current_number)\n context.response = response\n token = extract_csrf_middleware_token(response)\n\n # Step 3 - submit the \"basic case study data\" form & extract CSRF token\n response = fab_ui_case_study_basic.submit_form(session, token, new_case)\n context.response = response\n fab_ui_case_study_images.should_be_here(response)\n token = extract_csrf_middleware_token(response)\n\n # Step 4 - submit the \"case study images\" form\n response = fab_ui_case_study_images.submit_form(session, token, new_case)\n context.response = response\n\n # Step 5 - check if we're on the FAB Profile page\n fab_ui_profile.should_be_here(response)\n\n # Step 5 - Store new Case Study data in Scenario Data\n # `add_case_study` apart from adding will replace existing case study.\n context.add_case_study(actor.company_alias, case_alias, new_case)\n logging.debug(\n \"Successfully updated details of case study: '%s', title:'%s', link:\"\n \"'%s'\", case_alias, current.title, current_link)\n\n\ndef fas_search_using_company_details(\n context: Context, buyer_alias: str, company_alias: str, *,\n table_of_details: Table = None):\n \"\"\"Search for Company on FAS using it's all or selected details.\n\n :param context: behave `context` object\n :param buyer_alias: alias of the Actor used in the scope of the scenario\n :param company_alias: alias of the Company used in the scope of the scenario\n :param table_of_details: (optional) a table with selected company details\n which will be used in search\n \"\"\"\n actor = context.get_actor(buyer_alias)\n session = actor.session\n company = context.get_company(company_alias)\n keys = [\n 'title', 'number', 'summary', 'description', 'website', 'keywords',\n 'facebook', 'linkedin', 'twitter', 'slug'\n ]\n\n # use selected company details\n if table_of_details:\n keys = [row[\"company detail\"] for row in table_of_details]\n\n search_terms = {}\n search_results = {}\n search_responses = {}\n for key in keys:\n if key == \"keywords\":\n for index, keyword in enumerate(company.keywords.split(\", \")):\n search_terms[\"keyword #{}\".format(index)] = keyword\n else:\n search_terms[key] = getattr(company, key)\n logging.debug(\n \"Now %s will try to find '%s' using following search terms: %s\",\n buyer_alias, company.title, search_terms)\n for term_name in search_terms:\n term = search_terms[term_name]\n response = fas_ui_find_supplier.go_to(session, term=term)\n context.response = response\n number_of_pages = get_number_of_search_result_pages(response)\n for page_number in range(1, number_of_pages + 1):\n search_responses[term_name] = response\n found = fas_ui_find_supplier.should_see_company(\n response, company.title)\n search_results[term_name] = found\n if found:\n logging.debug(\n \"Found Supplier '%s' on FAS using '%s' : '%s' on %d page \"\n \"out of %d\", company.title, term_name, term, page_number,\n number_of_pages)\n break\n else:\n logging.debug(\n \"Couldn't find Supplier '%s' on the %d page out of %d of \"\n \"FAS search results. Search was done using '%s' : '%s'\",\n company.title, page_number, number_of_pages, term_name,\n term)\n next_page = page_number + 1\n if next_page <= number_of_pages:\n response = fas_ui_find_supplier.go_to(\n session, term=term, page=next_page)\n else:\n logging.debug(\"Couldn't find the Supplier even on the last \"\n \"page of the search results\")\n context.search_results = search_results\n context.search_responses = search_responses\n\n\ndef fas_view_pages_in_selected_language(\n context: Context, buyer_alias: str, pages_table: Table, language: str):\n \"\"\"View specific FAS pages in selected language.\n\n NOTE:\n This will store a dict with all page views responses in context.views\n\n :param context: behave `context` object\n :param buyer_alias: alias of the Buyer Actor\n :param pages_table: a table with FAS pages to view\n :param language: expected language of the view FAS page content\n \"\"\"\n pages = [row['page'] for row in pages_table]\n views = {}\n for page_name in pages:\n actor = context.get_actor(buyer_alias)\n session = actor.session\n language_code = get_language_code(language)\n page_url = get_fabs_page_url(page_name, language_code=language_code)\n response = make_request(Method.GET, page_url, session=session)\n views[page_name] = response\n context.views = views\n\n\ndef fas_view_page(context, actor_alias, page_name):\n actor = context.get_actor(actor_alias)\n session = actor.session\n page_object = get_fabs_page_object(page_name)\n context.response = page_object.go_to(session)\n\n\ndef fas_search_with_empty_query(context, buyer_alias):\n actor = context.get_actor(buyer_alias)\n session = actor.session\n context.response = fas_ui_find_supplier.go_to(session, term=\"\")\n\n\ndef fas_should_be_told_about_empty_search_results(context, buyer_alias):\n fas_ui_find_supplier.should_see_no_matches(context.response)\n logging.debug(\n \"%s was told that the search did not match any UK trade profiles\",\n buyer_alias)\n\n\ndef fas_send_feedback_request(\n context: Context, buyer_alias: str, page_name: str):\n actor = context.get_actor(buyer_alias)\n session = actor.session\n referer_url = get_fabs_page_url(page_name)\n\n # Step 1: generate random form data for our Buyer\n feedback = random_feedback_data(email=actor.email)\n\n # Step 2: submit the form\n response = fas_ui_feedback.submit(session, feedback, referer=referer_url)\n context.response = response\n logging.debug(\"% submitted the feedback request\", buyer_alias)\n\n\ndef fas_feedback_request_should_be_submitted(\n context: Context, buyer_alias: str):\n response = context.response\n fas_ui_feedback.should_see_feedback_submission_confirmation(response)\n logging.debug(\n \"% was told that the feedback request has been submitted\", buyer_alias)\n\n\ndef fas_get_company_profile_url(response: Response, name: str) -> str:\n content = response.content.decode(\"utf-8\")\n links_to_profiles_selector = \"#ed-search-list-container a\"\n href_selector = \"a::attr(href)\"\n links_to_profiles = Selector(text=content).css(\n links_to_profiles_selector).extract()\n profile_url = None\n for link in links_to_profiles:\n if escape_html(name).lower() in escape_html(link).lower():\n profile_url = Selector(text=link).css(href_selector).extract()[0]\n with assertion_msg(\n \"Couldn't find link to '%s' company profile page in the response\",\n name):\n assert profile_url\n return profile_url\n\n\ndef can_find_supplier_by_term(\n session: Session, name: str, term: str, term_type: str) \\\n -> (bool, Response, str):\n \"\"\"\n\n :param session: Buyer's session object\n :param name: sought Supplier name\n :param term: a text used to find the Supplier\n :param term_type: type of the term, e.g.: product, service, keyword etc.\n :return: a tuple with search result (True/False), last search Response and\n an endpoint to company's profile\n \"\"\"\n found = False\n endpoint = None\n response = fas_ui_find_supplier.go_to(session, term=term)\n number_of_pages = get_number_of_search_result_pages(response)\n if number_of_pages == 0:\n return found, response, endpoint\n for page_number in range(1, number_of_pages + 1):\n found = fas_ui_find_supplier.should_see_company(response, name)\n if found:\n endpoint = fas_get_company_profile_url(response, name)\n break\n else:\n logging.debug(\n \"Couldn't find Supplier '%s' on the %d page out of %d of \"\n \"FAS search results. Search was done using '%s' : '%s'\",\n name, page_number, number_of_pages, term_type, term)\n next_page = page_number + 1\n if next_page <= number_of_pages:\n response = fas_ui_find_supplier.go_to(\n session, term=term, page=next_page)\n else:\n logging.debug(\n \"Couldn't find the Supplier even on the last page of the \"\n \"search results\")\n return found, response, endpoint\n\n\ndef fas_search_with_product_service_keyword(\n context: Context, buyer_alias: str, search_table: Table):\n \"\"\"Search for Suppliers with one of the following:\n * Product name\n * Service name\n * keyword\n\n NOTE: this will add a dictionary `search_results` to `context`\n\n :param context: behave `context` object\n :param buyer_alias: alias of the Buyer Actor\n :param search_table: a table with FAS pages to view\n \"\"\"\n actor = context.get_actor(buyer_alias)\n session = actor.session\n search_results = {}\n for row in search_table:\n terms = []\n if row[\"product\"]:\n terms.append({\"type\": \"product\", \"term\": row[\"product\"]})\n if row[\"service\"]:\n terms.append({\"type\": \"service\", \"term\": row[\"service\"]})\n if row[\"keyword\"]:\n terms.append({\"type\": \"keyword\", \"term\": row[\"keyword\"]})\n search_results[row[\"company\"]] = terms\n\n for company in search_results:\n search_terms = search_results[company]\n for search_term in search_terms:\n term_type = search_term['type']\n term = search_term['term']\n logging.debug(\n \"%s is searching for company '%s' using %s term '%s'\",\n buyer_alias, company, term_type, term)\n found, response, _ = can_find_supplier_by_term(\n session, company, term, term_type)\n search_term['found'] = found\n search_term['response'] = response\n\n context.search_results = search_results\n\n\ndef fas_send_message_to_supplier(\n context: Context, buyer_alias: str, company_alias: str):\n buyer = context.get_actor(buyer_alias)\n session = buyer.session\n company = context.get_company(company_alias)\n endpoint = company.fas_profile_endpoint\n with assertion_msg(\n \"Company '%s' doesn't have FAS profile URL set\", company.title):\n assert endpoint\n # Step 0 - generate message data\n message = random_message_data()\n\n # Step 1 - go to Company's profile page\n response = fas_ui_profile.go_to_endpoint(session, endpoint)\n context.response = response\n fas_ui_profile.should_be_here(response, number=company.number)\n\n # Step 2 - go to the \"email company\" form\n response = fas_ui_contact.go_to(\n session, company_number=company.number, company_name=company.title)\n context.response = response\n\n # Step 3 - submit the form with the message data\n response = fas_ui_contact.submit(session, message, company.number)\n context.response = response\n\n\ndef fab_provide_company_details(\n context: Context, supplier_alias: str, table: Table):\n \"\"\"Submit company details with specific values in order to verify data\n validation.\n\n NOTE:\n This will store a list of `results` tuples in context. Each tuple will\n contain:\n * Company namedtuple (with details used in the request)\n * response object\n * expected error message\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Supplier Actor\n :param table: a table with company details to update & expected error msg\n \"\"\"\n actor = context.get_actor(supplier_alias)\n original_details = context.get_company(actor.company_alias)\n results = []\n for row in table:\n if row[\"company name\"] == \"unchanged\":\n title = original_details.title\n elif row[\"company name\"] == \"empty string\":\n title = \"\"\n elif row[\"company name\"].endswith(\" characters\"):\n number = [int(word) for word in row[\"company name\"].split() if\n word.isdigit()][0]\n title = random_chars(number)\n else:\n title = original_details.title\n\n if row[\"website\"] == \"empty string\":\n website = \"\"\n elif row[\"website\"] == \"valid http\":\n website = \"http://{}.{}\".format(rare_word(), rare_word())\n elif row[\"website\"] == \"valid https\":\n website = \"https://{}.{}\".format(rare_word(), rare_word())\n elif row[\"website\"] == \"invalid http\":\n website = \"http:{}.{}\".format(rare_word(), rare_word())\n elif row[\"website\"] == \"invalid https\":\n website = \"https:{}.{}\".format(rare_word(), rare_word())\n elif row[\"website\"].endswith(\" characters\"):\n number = [int(word)\n for word in row[\"website\"].split()\n if word.isdigit()][0]\n website = random_chars(number)\n\n if row[\"keywords\"] == \"empty string\":\n keywords = \"\"\n elif row[\"keywords\"].endswith(\" characters\"):\n number = [int(word)\n for word in row[\"keywords\"].split()\n if word.isdigit()][0]\n keywords = random_chars(number)\n else:\n keywords = row[\"keywords\"]\n separate_keywords = keywords.split(\", \")\n if row[\"separator\"] == \"pipe\":\n keywords = \"| \".join(separate_keywords)\n if row[\"separator\"] == \"semi-colon\":\n keywords = \"; \".join(separate_keywords)\n if row[\"separator\"] == \"colon\":\n keywords = \": \".join(separate_keywords)\n if row[\"separator\"] == \"full stop\":\n keywords = \". \".join(separate_keywords)\n\n if row[\"size\"] == \"unset\":\n size = \"\"\n else:\n size = row[\"size\"]\n\n new_details = Company(\n title=title, website=website, keywords=keywords, no_employees=size)\n\n response = fab_ui_build_profile_basic.submit(actor, new_details)\n results.append((new_details, response, row[\"error\"]))\n\n context.results = results\n\n\ndef fas_follow_case_study_links_to_related_sectors(context, actor_alias):\n actor = context.get_actor(actor_alias)\n session = actor.session\n content = context.response.content.decode(\"utf-8\")\n links_css_selector = \"#company-showcase .case-study-info a\"\n links_to_sectors = Selector(text=content).css(links_css_selector).extract()\n with assertion_msg(\"Expected to find at least 1 link to Industry sector\"\n \"associated with Company Showcase Case Study\"):\n assert links_css_selector\n results = {}\n fas_url = get_absolute_url(\"ui-supplier:landing\")\n for link in links_to_sectors:\n industry = Selector(text=link).css(\"a::text\").extract()[0]\n href = Selector(text=link).css(\"a::attr(href)\").extract()[0]\n url = urljoin(fas_url, href)\n sectors = [value for _, value in parse_qsl(urlsplit(href).query)]\n logging.debug(\n \"%s will look for Suppliers in '%s' Industry sectors '%s'\",\n actor_alias, industry, \", \".join(sectors)\n )\n response = make_request(Method.GET, url=url, session=session)\n results[industry] = {\n \"url\": url,\n \"sectors\": sectors,\n \"response\": response\n }\n context.results = results\n\n\ndef fas_browse_suppliers_using_every_sector_filter(\n context: Context, actor_alias: str):\n actor = context.get_actor(actor_alias)\n session = actor.session\n\n response = fas_ui_find_supplier.go_to(session, term=\"\")\n context.response = response\n\n sector_filters_selector = \"#id_sectors input::attr(value)\"\n content = response.content.decode(\"utf-8\")\n sector_filters = Selector(text=content).css(\n sector_filters_selector).extract()\n results = {}\n for sector in sector_filters:\n logging.debug(\n \"%s will browse Suppliers by Industry sector filter '%s'\",\n actor_alias, sector\n )\n response = fas_ui_find_supplier.go_to(session, sectors=[sector])\n results[sector] = {\n \"url\": response.request.url,\n \"sectors\": [sector],\n \"response\": response\n }\n context.results = results\n\n\ndef fas_browse_suppliers_by_multiple_sectors(\n context: Context, actor_alias: str):\n actor = context.get_actor(actor_alias)\n session = actor.session\n\n response = fas_ui_find_supplier.go_to(session, term=\"\")\n context.response = response\n\n sector_selector = \"#id_sectors input::attr(value)\"\n content = response.content.decode(\"utf-8\")\n filters = Selector(text=content).css(sector_selector).extract()\n\n sectors = list(set(random.choice(filters)\n for _ in range(random.randrange(1, len(filters)))))\n results = {}\n logging.debug(\n \"%s will browse Suppliers by multiple Industry sector filters '%s'\",\n actor_alias, \", \".join(sectors)\n )\n response = fas_ui_find_supplier.go_to(session, sectors=sectors)\n results[\"multiple choice\"] = {\n \"url\": response.request.url,\n \"sectors\": sectors,\n \"response\": response\n }\n context.results = results\n\n\ndef fas_browse_suppliers_by_invalid_sectors(\n context: Context, actor_alias: str):\n actor = context.get_actor(actor_alias)\n session = actor.session\n\n response = fas_ui_find_supplier.go_to(session, term=\"\")\n context.response = response\n\n sector_selector = \"#id_sectors input::attr(value)\"\n content = response.content.decode(\"utf-8\")\n filters = Selector(text=content).css(sector_selector).extract()\n\n sectors = list(set(random.choice(filters)\n for _ in range(random.randrange(1, len(filters)))))\n\n sectors.append(\"this_is_an_invalid_sector_filter\")\n logging.debug(\n \"%s will browse Suppliers by multiple Industry sector filters and will\"\n \" inject an invalid filter: '%s'\",\n actor_alias, \", \".join(sectors)\n )\n context.response = fas_ui_find_supplier.go_to(session, sectors=sectors)\n\n\ndef fas_clear_search_filters(context: Context, actor_alias: str):\n actor = context.get_actor(actor_alias)\n session = actor.session\n\n logging.debug(\"%s will clear the search filter\", actor_alias)\n response = fas_ui_find_supplier.go_to(session, term=\"\")\n context.response = response\n\n\ndef fas_browse_suppliers_by_company_sectors(\n context: Context, actor_alias: str, company_alias: str,\n pages_to_scan: int):\n actor = context.get_actor(actor_alias)\n session = actor.session\n company = context.get_company(company_alias)\n sectors = company.sector\n results = {}\n\n response = fas_ui_find_supplier.go_to(session, sectors=sectors)\n context.response = response\n\n found = fas_ui_find_supplier.should_see_company(response, company.title)\n\n results[1] = {\n \"url\": response.request.url,\n \"sectors\": sectors,\n \"response\": response,\n \"found\": found\n }\n\n last_page = get_number_of_search_result_pages(response)\n logging.debug(\"Search results have %d pages\", last_page)\n if last_page > 1:\n last_page = pages_to_scan if pages_to_scan < last_page else last_page\n logging.debug(\"Will scan only first %d pages\", last_page)\n for page_number in range(2, last_page):\n logging.debug(\"Going to search result page no.: %d\", page_number)\n response = fas_ui_find_supplier.go_to(\n session, page=page_number, sectors=sectors)\n found = fas_ui_find_supplier.should_see_company(\n response, company.title)\n results[page_number] = {\n \"url\": response.request.url,\n \"sectors\": sectors,\n \"response\": response,\n \"found\": found\n }\n\n logging.debug(\n \"%s browsed first %d pages of search results filtered by multiple \"\n \"sector filters '%s'\", actor_alias, last_page, \", \".join(sectors)\n )\n context.results = results\n\n\ndef fas_get_case_study_slug(context: Context, actor_alias: str,\n case_alias: str):\n result = None\n actor = context.get_actor(actor_alias)\n company = context.get_company(actor.company_alias)\n case = context.get_company(actor.company_alias).case_studies[case_alias]\n\n response = fas_ui_profile.go_to(actor.session, company.number)\n context.response = response\n\n case_studies_details = fas_ui_profile.get_case_studies_details(response)\n for title, summary, href, slug in case_studies_details:\n if title == case.title:\n result = slug\n\n with assertion_msg(\"Could not find slug for case study '%s'\", case_alias):\n assert result is not None\n\n context.update_case_study(company.alias, case_alias, slug=result)\n logging.debug(\n \"%s got case study '%s' slug: '%s'\", actor_alias, case_alias, result)\n\n\ndef fas_search_with_term(context, actor_alias, search_term):\n actor = context.get_actor(actor_alias)\n session = actor.session\n context.response = fas_ui_find_supplier.go_to(session, term=search_term)\n\n\ndef fab_go_to_letter_verification(\n context: Context, supplier_alias: str, logged_in: bool):\n actor = context.get_actor(supplier_alias)\n response = fab_ui_confirm_identity.go_to(actor.session, logged_in=logged_in)\n context.response = response\n\n if logged_in:\n fab_ui_confirm_identity.should_be_here(\n response, letter_verification=True)\n else:\n sso_ui_login.should_be_here(response)\n\n token = extract_csrf_middleware_token(response)\n context.update_actor(supplier_alias, csrfmiddlewaretoken=token)\n\n sso_login_url = get_absolute_url(\"sso:login\")\n fab_verify_url = quote(get_absolute_url(\"ui-buyer:confirm-identity\"))\n referer = (\"{sso_login_url}?next={fab_verify_url}\"\n .format(sso_login_url=sso_login_url,\n fab_verify_url=fab_verify_url))\n next = get_absolute_url(\"ui-buyer:confirm-identity\")\n logging.debug(\n \"After successful login %s should be redirected to: %s\",\n supplier_alias, referer)\n response = sso_ui_login.login(actor, referer=referer, next_param=next)\n context.response = response\n\n fab_ui_confirm_identity.should_be_here(\n response, letter_verification=True)\n\n response = fab_ui_confirm_identity.send(actor)\n context.response = response\n\n\ndef fab_choose_to_verify_with_code(context: Context, supplier_alias: str):\n actor = context.get_actor(supplier_alias)\n referer = get_absolute_url(\"ui-buyer:confirm-identity\")\n response = fab_ui_verify_company.go_to(actor.session, referer=referer)\n context.response = response\n fab_ui_verify_company.should_be_here(response)\n\n\ndef fab_submit_verification_code(context, supplier_alias):\n actor = context.get_actor(supplier_alias)\n company = context.get_company(actor.company_alias)\n verification_code = company.verification_code\n referer = get_absolute_url(\"ui-buyer:confirm-company-address\")\n response = fab_ui_verify_company.submit(\n actor.session, actor.csrfmiddlewaretoken, verification_code,\n referer=referer)\n context.response = response\n\n\ndef get_form_value(key: str) -> str or list or int or None:\n\n def get_number_from_key(key: str) -> int:\n numbers = [int(word) for word in key.split() if word.isdigit()]\n return numbers[0] if numbers else 0\n\n def get_n_chars(number: int) -> str:\n return random_chars(number)\n\n def get_n_words(number: int) -> str:\n return sentence(min_words=number, max_words=number, max_length=0)\n\n def get_n_country_codes(number: int) -> list:\n country_codes = [\"CN\", \"DE\", \"IN\", \"JP\", \"US\"]\n max = number if number <= len(country_codes) else len(country_codes)\n return [country_codes[idx] for idx in range(max)]\n\n result = None\n\n mappings = [\n (\"empty string\", \"\"),\n (\"valid http\", \"http://{}.{}\".format(rare_word(), rare_word())),\n (\"valid https\", \"https://{}.{}\".format(rare_word(), rare_word())),\n (\"invalid http\", \"http:{}.{}\".format(rare_word(), rare_word())),\n (\"invalid https\", \"https:{}.{}\".format(rare_word(), rare_word())),\n (\"invalid sector\", \"this is an invalid sector\"),\n (\"no image\", None),\n (\"invalid image\", choice(BMPs + JP2s + WEBPs)),\n (\" characters$\", get_n_chars(get_number_from_key(key))),\n (\" words$\", get_n_words(get_number_from_key(key))),\n (\" predefined countries$\", get_n_country_codes(get_number_from_key(key))),\n (\"1 predefined country$\", get_n_country_codes(1)),\n (\"none selected\", None),\n (\"sector\", random.choice(SECTORS))\n ]\n\n found = False\n for pattern, value in mappings:\n r = re.compile(pattern)\n if r.findall(key):\n result = value\n found = True\n break\n\n if not found:\n result = key\n\n return result\n\n\ndef fab_attempt_to_add_case_study(\n context: Context, supplier_alias: str, table: Table):\n actor = context.get_actor(supplier_alias)\n session = actor.session\n\n page_1_fields = [\n \"title\", \"summary\", \"description\", \"sector\", \"website\", \"keywords\"\n ]\n page_2_fields = [\n \"image_1\", \"caption_1\", \"image_2\", \"caption_2\", \"image_3\", \"caption_3\",\n \"testimonial\", \"source_name\", \"source_job\", \"source_company\"\n ]\n\n results = []\n for row in table:\n case_study = random_case_study_data(\"test\")\n field = row[\"field\"]\n value_type = row[\"value type\"]\n separator = row[\"separator\"]\n error = row[\"error\"]\n\n value = get_form_value(value_type)\n\n if field == \"keywords\":\n separator = SEPARATORS.get(separator, \",\")\n value = \"{} \".format(separator).join(value.split())\n\n case_study = case_study._replace(**{field: value})\n\n response = fab_ui_case_study_basic.go_to(session)\n context.response = response\n\n token = extract_csrf_middleware_token(response)\n\n if field in page_1_fields:\n response = fab_ui_case_study_basic.submit_form(session, token, case_study)\n context.response = response\n elif field in page_2_fields:\n response = fab_ui_case_study_basic.submit_form(session, token, case_study)\n context.response = response\n token = extract_csrf_middleware_token(response)\n response = fab_ui_case_study_images.submit_form(session, token, case_study)\n context.response = response\n else:\n raise KeyError(\n \"Could not recognize field '{}' as valid case study field\")\n\n results.append((field, value_type, case_study, response, error))\n\n context.results = results\n\n\ndef sso_request_password_reset(context: Context, supplier_alias: str):\n actor = context.get_actor(supplier_alias)\n if actor.company_alias is None:\n next_param = get_fabs_page_url(page_name=\"sud about\")\n else:\n next_param = get_fabs_page_url(page_name=\"fab landing\")\n\n response = sso_ui_password_reset.go_to(actor.session, next_param=next_param)\n context.response = response\n\n sso_ui_password_reset.should_be_here(response)\n\n token = extract_csrf_middleware_token(response)\n context.update_actor(supplier_alias, csrfmiddlewaretoken=token)\n\n response = sso_ui_password_reset.reset(actor, token, next_param=next_param)\n context.response = response\n\n\ndef sso_sign_in(context: Context, supplier_alias: str):\n \"\"\"Sign in to standalone SSO account.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Supplier Actor\n \"\"\"\n actor = context.get_actor(supplier_alias)\n next_param = get_absolute_url(\"profile:about\")\n referer = get_absolute_url(\"profile:about\")\n response = sso_ui_login.go_to(\n actor.session, next_param=next_param, referer=referer)\n context.response = response\n\n token = extract_csrf_middleware_token(response)\n context.update_actor(supplier_alias, csrfmiddlewaretoken=token)\n\n context.response = sso_ui_login.login(\n actor, next_param=next_param, referer=referer)\n\n\ndef sso_change_password_with_password_reset_link(\n context: Context, supplier_alias: str, *, new: bool = False,\n same: bool = False, mismatch: bool = False):\n actor = context.get_actor(supplier_alias)\n session = actor.session\n link = actor.password_reset_link\n\n response = sso_ui_password_reset.open_link(session, link)\n context.response = response\n\n sso_ui_change_password.should_be_here(response)\n\n token = extract_csrf_middleware_token(response)\n context.update_actor(supplier_alias, csrfmiddlewaretoken=token)\n action = extract_form_action(response)\n\n password = None\n password_again = None\n\n if new:\n password_length = 10\n password = \"\".join(random.choice(string.ascii_letters)\n for _ in range(password_length))\n context.update_actor(supplier_alias, password=password)\n if same:\n password = actor.password\n if mismatch:\n password = \"first password\"\n password_again = \"this password does not match\"\n\n actor = context.get_actor(supplier_alias)\n\n response = sso_ui_change_password.submit(\n actor, action, password=password, password_again=password_again)\n context.response = response\n\n\ndef sso_open_password_reset_link(context: Context, supplier_alias: str):\n actor = context.get_actor(supplier_alias)\n session = actor.session\n link = actor.password_reset_link\n context.response = sso_ui_password_reset.open_link(session, link)\n\n\ndef go_to_page(context: Context, supplier_alias: str, page_name: str):\n actor = context.get_actor(supplier_alias)\n url = get_fabs_page_url(page_name)\n context.response = make_request(Method.GET, url, session=actor.session)\n\n\ndef go_to_pages(context: Context, actor_alias: str, table: Table):\n actor = context.get_actor(actor_alias)\n results = {}\n for row in table:\n page_name = row[\"page name\"]\n url = get_fabs_page_url(page_name)\n response = make_request(Method.GET, url, session=actor.session)\n context.response = response\n results[page_name] = response\n\n context.results = results\n\n\ndef fab_select_preferred_countries_of_export(\n context: Context, supplier_alias: str, country_names, other_countries):\n actor = context.get_actor(supplier_alias)\n country_codes = get_form_value(country_names)\n other = get_form_value(other_countries)\n sector = get_form_value(\"sector\")\n response = fab_ui_build_profile_sector.submit(\n actor, sector, country_codes, other)\n context.response = response\n\n\ndef finish_registration_after_flagging_as_verified(\n context: Context, supplier_alias: str):\n \"\"\"Go to the `/register-submit` endpoint which, when Actor has a verified\n SSO account, should redirect to `company-profile/edit` (Create Profile)\n \"\"\"\n actor = context.get_actor(supplier_alias)\n company = context.get_company(actor.company_alias)\n register_url = get_absolute_url(\"ui-buyer:register-submit-account-details\")\n url = (\"{}?company_number={}&has_exported_before=True\"\n .format(register_url, company.number))\n response = make_request(Method.GET, url, session=actor.session)\n context.response = response\n","sub_path":"tests/functional/steps/fab_when_impl.py","file_name":"fab_when_impl.py","file_ext":"py","file_size_in_byte":70922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"484920031","text":"# encoding: utf-8\r\nimport cv2\r\nimport lmdb\r\nimport numpy as np\r\nfrom torch.utils.data import Dataset\r\nfrom torchvision import transforms\r\nfrom torch.utils.data import DataLoader\r\nimport six\r\nimport torch\r\nimport os\r\nfrom xml.dom.minidom import parse\r\nimport logging\r\nfrom torchvision import transforms\r\nfrom os.path import join\r\n\r\n\r\ntransform = transforms.ToTensor()\r\n\r\n\r\ndef xyxy2xywh(x):\r\n # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right\r\n y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)\r\n y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center\r\n y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center\r\n y[:, 2] = x[:, 2] - x[:, 0] # width\r\n y[:, 3] = x[:, 3] - x[:, 1] # height\r\n return y\r\n\r\n\r\ndef xywh2xyxy(x):\r\n # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\r\n y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)\r\n y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x\r\n y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y\r\n y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x\r\n y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y\r\n return y\r\n\r\n\r\nclass AnnotationTransform(object):\r\n \"\"\"Transforms a GTDB annotation into a Tensor of bbox coords and label index\r\n Initilized with a dictionary lookup of classnames to indexes\r\n\r\n Arguments:\r\n class_to_ind (dict, optional): dictionary lookup of classnames -> indexes\r\n height (int): height\r\n width (int): width\r\n\r\n \"\"\"\r\n def __init__(self, class_to_ind=None):\r\n pass\r\n\r\n # target input is x0,y0,x1,y1 convert to x,y,w,h and norm \r\n def __call__(self, target, width, height):\r\n \"\"\"\r\n Arguments:\r\n target (annotation) : the target annotations. This will be the list of bounding boxes\r\n Returns:\r\n a list containing lists of bounding boxes [bbox coords, class name]\r\n \"\"\"\r\n \r\n # res = []\r\n target = xyxy2xywh(np.array(target,dtype=np.float32))\r\n target[:,[0,2]] = target[:,[0,2]] / width\r\n target[:,[1,3]] = target[:,[1,3]] / height\r\n\r\n # read the annotations\r\n # for box in target:\r\n # res.append([box[0]/width, box[1]/height, box[2]/width, box[3]/height])\r\n return target.tolist() # [[xmin, ymin, xmax, ymax, label_ind], ... ]\r\n\r\ndef collate_fn(batch):\r\n # img, label, path, shapes = zip(*batch) # transposed\r\n # for i, l in enumerate(label):\r\n # l[:, 0] = i # add target image index for build_targets()\r\n # return torch.stack(img, 0), torch.cat(label, 0), path, shapes \r\n img, label = zip(*batch) # transposed\r\n # print('img type:', type(img),':',len(img) ,' label :', label)\r\n\r\n # BGR to RGB, to 3x416x416\r\n img = [transform(x).float() for x in img]\r\n # print('collate fn before label:', label)\r\n label = [torch.from_numpy(x).float() for x in label]\r\n\r\n\r\n # print('collate fn after label:', label)\r\n for i, l in enumerate(label):\r\n l[:, 0] = i # add target image index for build_targets()\r\n return torch.stack(img, 0), torch.cat(label, 0) \r\n\r\n\r\nclass QRDataset(Dataset):\r\n '''\r\n 试卷定点识别, 训练数据来源\r\n 1)初始化导入的训练数据,保存在lmdb数据库存中\r\n 2)识别错误的数据, 保存在文件中\r\n 训练时需两部分数据结合一起进行训练\r\n '''\r\n def __init__(self, data_dir, window=1200,transform=None, target_transform=None):\r\n Dataset.__init__(self)\r\n self.env = lmdb.open(\r\n os.path.sep.join([data_dir,'lmdb']),\r\n max_readers=1,\r\n readonly=True,\r\n lock=False,\r\n readahead=False,\r\n meminit=False) \r\n self.transform = transform\r\n self.target_transform = target_transform\r\n self.window=window\r\n self.data_dir = data_dir\r\n if not self.env:\r\n print('cannot creat lmdb from %s' % (root))\r\n sys.exit(0)\r\n\r\n with self.env.begin(write=False) as txn:\r\n nSamples = int(txn.get('bg_total'.encode()))\r\n qrNsamples = int(txn.get('qr_total'.encode()))\r\n self.nSamples = nSamples \r\n self.qrNsamples = qrNsamples\r\n\r\n self.ext_train_data = self.__load_file_data__()\r\n logging.info('lmdb data len : %s file data len : %s' % (self.nSamples, len(self.ext_train_data)))\r\n\r\n def __load_file_data__(self):\r\n '''\r\n 加载识别错误图片重新进入训练\r\n '''\r\n file_lists = os.listdir(join(self.data_dir, 'error_imgs', 'taged'))\r\n file_lists = [x for x in file_lists if x.find('.xml') != -1]\r\n\r\n train_data = []\r\n\r\n for item in file_lists:\r\n domtree = parse(join(self.data_dir,'error_imgs', 'taged',item))\r\n imgdom = domtree.documentElement\r\n img_name = imgdom.getElementsByTagName('filename')[0].firstChild.nodeValue\r\n image = cv2.imread(join(self.data_dir,'error_imgs', 'taged', img_name), cv2.IMREAD_COLOR)\r\n height, width, _ = image.shape\r\n if height > 2048:\r\n radio = 2048/height\r\n else:\r\n radio = 1\r\n\r\n image = cv2.resize(image, (0,0), fx=radio, fy=radio, interpolation=cv2.INTER_AREA)\r\n\r\n # image = image.astype(np.uint8)\r\n box_lists = []\r\n box_nodes = imgdom.getElementsByTagName('bndbox')\r\n for box in box_nodes:\r\n xmin = int(int(box.getElementsByTagName('xmin')[0].firstChild.nodeValue) * radio)\r\n ymin = int(int(box.getElementsByTagName('ymin')[0].firstChild.nodeValue) * radio)\r\n xmax = int(int(box.getElementsByTagName('xmax')[0].firstChild.nodeValue) * radio)\r\n ymax = int(int(box.getElementsByTagName('ymax')[0].firstChild.nodeValue) * radio)\r\n box_lists.append([xmin, ymin, xmax, ymax, 0])\r\n\r\n train_data.append((image, np.array(box_lists)))\r\n return train_data\r\n\r\n def __len__(self):\r\n # return len(self.ext_train_data)\r\n # return 1\r\n # return self.nSamples * 50\r\n return (self.nSamples + len(self.ext_train_data)) * 50\r\n\r\n def __getitem__(self, index):\r\n\r\n # rand_area = [x for x in range(self.nSamples + len(self.ext_train_data)) if x not in [907,148,493,505,679,689,784,813,865]]\r\n # index = rand_area[np.random.randint(len(rand_area))]\r\n\r\n with self.env.begin(write=False) as txn:\r\n qrImage, image, target = self.pull_train_item(txn, index)\r\n\r\n image = image.astype(np.uint8)\r\n\r\n\r\n if self.transform:\r\n # print('qr image shape :', qrImage.shape, ' image shape :', image.shape, 'target :', target.shape)\r\n image, qrImage, target = self.transform(image, qrImage, target)\r\n \r\n\r\n boxes = target[:, 0:4]\r\n labels = target[:, 4] \r\n # image, boxes, labels = self.transform(image, boxes, labels)\r\n\r\n if self.target_transform:\r\n boxes = self.target_transform(boxes, self.window, self.window)\r\n\r\n labels = np.hstack((np.expand_dims(labels, axis=1), boxes))\r\n\r\n # 去掉非目标区域\r\n sel_labels = np.where(labels[:,0] != -1)\r\n labels = labels[sel_labels]\r\n\r\n\r\n # boxes = boxes[sel_labels]\r\n\r\n\r\n # 增加一列,用于yolo训练时作为图片索引, 注意图片索引是根据batch idx设置,这里只扩展一位\r\n\r\n # print('labels shape:', labels.shape, ' boxes len :', len(boxes))\r\n labels = np.hstack((np.zeros((len(boxes),1)), labels))\r\n\r\n if labels.shape[0] == 0:\r\n raise Exception('训练数据没有目标检测数据 %s !' % index) \r\n\r\n\r\n return image, labels\r\n\r\n \r\n\r\n def __get_image__(self, txn, image_key):\r\n imgbuf = txn.get(image_key.encode())\r\n buf = six.BytesIO()\r\n buf.write(imgbuf)\r\n buf.seek(0) \r\n image = cv2.imdecode(np.frombuffer(buf.getvalue(), np.uint8),cv2.IMREAD_COLOR)\r\n # image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n # image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) \r\n return image\r\n\r\n def __get_target__(self, txn, target_key):\r\n target = np.frombuffer(txn.get(target_key.encode()), dtype=np.float)\r\n target = target.astype(np.int)\r\n target = target.reshape(-1,5)\r\n # print('target :', target)\r\n target = target[np.where(target[:,4] != -1)]\r\n if target.shape[0] == 0:\r\n # target = np.array([[-1,-1,-1,-1,-1]])\r\n target = np.array([])\r\n return target \r\n\r\n\r\n def pull_train_item(self, txn, index):\r\n index = index % (self.nSamples + len(self.ext_train_data))\r\n image = None\r\n target = np.array([])\r\n if index < self.nSamples:\r\n image = self.__get_image__(txn, f'bg_{index}')\r\n target = self.__get_target__(txn, f'target_{index}')\r\n # print('target :', target, ' target shape:', target.shape)\r\n # if target.shape[0] > 0:\r\n # target = target[np.where(target[:,4]) != -1]\r\n\r\n # yolo 训练需确保数据都包含检测目标\r\n if target.shape[0] == 0:\r\n ext_idx = np.random.randint(len(self.ext_train_data))\r\n _image, _target = self.ext_train_data[ext_idx]\r\n image = _image.copy()\r\n target = _target.copy()\r\n\r\n # qr_idx = np.random.randint(0, self.qrNsamples)\r\n qr_idx = 0\r\n qrImage = self.__get_image__(txn, f'qr_{qr_idx}')\r\n\r\n return qrImage,image, target\r\n\r\nif __name__ == '__main__':\r\n import argparse\r\n from matplotlib import pyplot as plt\r\n import cv2\r\n from torch.utils.data.sampler import SubsetRandomSampler\r\n from torchvision import transforms\r\n from qrtransform import QRTransform\r\n from os.path import join\r\n parser = argparse.ArgumentParser(description='math formula imdb dataset')\r\n parser.add_argument('--data_root',default='D:\\\\PROJECT_TW\\\\git\\\\data\\\\qrdetect', type=str, help='path of the math formula data')\r\n parser.add_argument('--batch_size',default=16, type=int)\r\n args = parser.parse_args()\r\n\r\n transform = transforms.ToTensor()\r\n\r\n dataset = QRDataset(data_dir=args.data_root,\r\n window=416, transform=QRTransform(window=416), target_transform=AnnotationTransform()) \r\n\r\n print('data set len :', len(dataset))\r\n random_sel = np.random.randint(0, len(dataset), 2000).tolist()\r\n\r\n # len(dataset)-50,\r\n for ridx, idx in enumerate(random_sel):\r\n image, labels = dataset[idx]\r\n image = image.astype(np.uint8)\r\n image = cv2.resize(image, (416,416), interpolation=cv2.INTER_AREA)\r\n print('gen ridx %s 数据 ' % ridx) \r\n # print('image :', image.shape, ' boxes: ', labels)\r\n image = image.astype(np.uint8)\r\n for box in labels:\r\n imgidx,label,x, y, w, h = box\r\n # print('qr img size :', w*h * 416)\r\n # print(x,',',y, ',', w, ',', h)\r\n # print('w : %s h: %s ' % (w*416, h*416))\r\n\r\n x0,y0,x1,y1 = xywh2xyxy(np.array([[x,y,w,h]], dtype=np.float32)).tolist()[0]\r\n # print(x0,',',y0, ',', x1, ',', y1)\r\n\r\n x0 = int(416*x0) \r\n x1 = int(416*x1) \r\n y0 = int(416*y0) \r\n y1 = int(416*y1) \r\n\r\n # print(x0,',',y0, ',', x1, ',', y1)\r\n\r\n if int(label) == 0:\r\n cv2.rectangle(image, (x0,y0), (x1, y1), (0, 255, 0), 2)\r\n\r\n cv2.imwrite(join(args.data_root,'valid_imgs', f'{ridx}_.png'), image)\r\n\r\n # plt.imshow(image)\r\n # plt.show() \r\n\r\n # dataloader = torch.utils.data.DataLoader(dataset,\r\n # batch_size=3,\r\n # shuffle=False, # Shuffle=True unless rectangular training is used\r\n # pin_memory=True,\r\n # collate_fn=collate_fn) \r\n\r\n # for _ in range(3):\r\n # for idx, (imgs, labels) in enumerate(dataloader):\r\n # print('idx :', idx, ' imags shape:', imgs.size(), ' labels shape:', labels.size())\r\n # print('images: --> \\n', imgs)\r\n # print('labels ---> \\n ', labels)\r\n # break","sub_path":"object detect/lib/yolo/data/qrdataset.py","file_name":"qrdataset.py","file_ext":"py","file_size_in_byte":12468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"355308640","text":"import os\nimport random\nimport re\nimport sys\n\nDAMPING = 0.85\nSAMPLES = 10000\n\n\ndef main():\n if len(sys.argv) != 2:\n sys.exit(\"Usage: python pagerank.py corpus\")\n corpus = crawl(sys.argv[1])\n ranks = sample_pagerank(corpus, DAMPING, SAMPLES)\n print(f\"PageRank Results from Sampling (n = {SAMPLES})\")\n for page in sorted(ranks):\n print(f\" {page}: {ranks[page]:.4f}\")\n ranks = iterate_pagerank(corpus, DAMPING)\n print(f\"PageRank Results from Iteration\")\n for page in sorted(ranks):\n print(f\" {page}: {ranks[page]:.4f}\")\n\n\ndef crawl(directory):\n \"\"\"\n Parse a directory of HTML pages and check for links to other pages.\n Return a dictionary where each key is a page, and values are\n a list of all other pages in the corpus that are linked to by the page.\n \"\"\"\n pages = dict()\n\n # Extract all links from HTML files\n for filename in os.listdir(directory):\n if not filename.endswith(\".html\"):\n continue\n with open(os.path.join(directory, filename)) as f:\n contents = f.read()\n links = re.findall(r\"]*?)href=\\\"([^\\\"]*)\\\"\", contents)\n pages[filename] = set(links) - {filename}\n\n # Only include links to other pages in the corpus\n for filename in pages:\n pages[filename] = set(\n link for link in pages[filename]\n if link in pages\n )\n\n return pages\n\n\ndef transition_model(corpus, page, damping_factor):\n \"\"\"\n Return a probability distribution over which page to visit next,\n given a current page.\n\n With probability `damping_factor`, choose a link at random\n linked to by `page`. With probability `1 - damping_factor`, choose\n a link at random chosen from all pages in the corpus.\n\n The transition_model should return a dictionary representing the probability \n distribution over which page a random surfer would visit next, given a corpus \n of pages, a current page, and a damping factor.\n \"\"\"\n # Total amount of pages\n number_of_pages = len(corpus) \n # Base probability of any page, we'll have to add the rest later\n base_probability = (1 - damping_factor) / number_of_pages\n # We add the probability to all the pages and create the dict that will be returned as result\n probabilities = dict.fromkeys(corpus.keys(),base_probability)\n\n # Set of pages linked to the given page \n page_links = corpus.get(page) \n # Amount of pages linked to the given page\n number_of_page_links = len(page_links)\n # Probability of traviling to one of those pages from the given page\n if number_of_page_links > 0:\n extra_probability = damping_factor / number_of_page_links\n # We add the probability to each page\n for link in page_links:\n probabilities[link] += extra_probability\n # If there are no links, we equilibrate the probability\n else:\n probabilities = dict.fromkeys(corpus.keys(), 1/number_of_pages)\n\n return probabilities\n\n\ndef sample_pagerank(corpus, damping_factor, n):\n \"\"\"\n Return PageRank values for each page by sampling `n` pages\n according to transition model, starting with a page at random.\n\n Return a dictionary where keys are page names, and values are\n their estimated PageRank value (a value between 0 and 1). All\n PageRank values should sum to 1.\n \"\"\"\n # First sample, random choice\n actual_page = random.choice(list(corpus.keys()))\n # We create the dict with same keys as the corpus and default value 0, to add later\n pagerank = dict.fromkeys(corpus.keys(), 0)\n # We calculate one time (so that we don't do it N times) the probability added each landing\n probability_added = 1 / n\n # Now we iterate N times, jumping from page to page and adding the probability in each jump\n pagerank[actual_page] += probability_added\n i = 0\n while i < n:\n # Get the transition model\n probabilities = transition_model(corpus, actual_page, damping_factor)\n # To ease its use, we get a list of values\n probabilities_values = list(probabilities.values())\n # This way, we will iterate through them and then, get a random value with a seed, depending \n # on the range the seed ends (the list makes easier this proccess)\n index = 0\n seed = random.random()\n while seed > 0:\n seed -= probabilities_values[index]\n index += 1\n # We set the actual page to the page where the seed got to 0 or least\n actual_page = list(probabilities.keys())[index-1]\n # Add its new probability\n pagerank[actual_page] += probability_added\n # And loop again\n i += 1\n\n return pagerank\n\n\ndef summation(corpus, corpus_page, pagerank):\n result = 0\n for page in corpus:\n if corpus_page in corpus.get(page):\n result += pagerank[page] / len(corpus[page])\n return result\n\n\ndef iterate_pagerank(corpus, damping_factor):\n \"\"\"\n Return PageRank values for each page by iteratively updating\n PageRank values until convergence.\n\n Return a dictionary where keys are page names, and values are\n their estimated PageRank value (a value between 0 and 1). All\n PageRank values should sum to 1.\n \"\"\"\n # We create the dict with same keys as the corpus and default value 0, to add later each probability\n pagerank = dict.fromkeys(corpus.keys(), 1 / len(corpus))\n aux_pagerank = dict.fromkeys(corpus.keys(), 0)\n highest_change = 1\n # We iterate through all the corpus pages, while the change is less than 0.001\n while highest_change > 0.001:\n for corpus_page in corpus:\n # We first add the \"base\" probability\n aux_pagerank[corpus_page] = ((1 - damping_factor) / len(corpus)) + (damping_factor * summation(corpus, corpus_page, pagerank))\n # We check for the highest change value\n highest_change = 0\n for page in pagerank:\n change = abs(pagerank[page] - aux_pagerank[page])\n if change > highest_change:\n highest_change = change\n # Finally we update the pagerank\n pagerank.update(aux_pagerank)\n return pagerank\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"3_Uncertainty/pagerank/pagerank.py","file_name":"pagerank.py","file_ext":"py","file_size_in_byte":6221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"102615366","text":"\n\ntest_sub_dir = \"test_data/1019436/session_1\"\n\n\ndef test_run_anatomical_reorient():\n\n import os\n import commands\n\n import pkg_resources as p\n\n from qap.anatomical_preproc import run_anatomical_reorient\n\n\n if \"anatomical_reorient\" in os.listdir(os.getcwd()):\n\n err = \"\\n[!] The output folder for this workflow already exists.\\n\"\n\n raise Exception(err)\n\n\n anat_scan = p.resource_filename(\"qap\", os.path.join(test_sub_dir, \\\n \"anat_1\", \\\n \"anatomical_scan\", \\\n \"mprage.nii.gz\"))\n\n ref_out = p.resource_filename(\"qap\", os.path.join(test_sub_dir, \\\n \"anat_1\", \\\n \"anatomical_reorient\", \\\n \"mprage_resample.nii.gz\"))\n\n # run the workflow\n output = run_anatomical_reorient(anat_scan)\n\n # make the correlation\n ref_out_data = nb.load(ref_out).get_data() \n output_data = nb.load(output).get_data()\n \n os.system(\"rm -R anatomical_reorient\")\n\n\n # create a vector of True and False values\n bool_vector = ref_out_data == output_data\n\n assert bool_vector.all()\n\n\n\ndef test_run_flirt_anatomical_linear_registration():\n\n import os\n import pkg_resources as p\n\n from qap.anatomical_preproc import run_flirt_anatomical_linear_registration\n\n anat_brain = p.resource_filename(\"qap\", os.path.join(test_sub_dir, \\\n \"anat_1\", \\\n \"anatomical_brain\", \\\n \"mprage_resample_calc.nii.gz\"))\n\n template_brain = p.resource_filename(\"qap\", os.path.join(\"test_data\", \\\n \"MNI152_T1_2mm_brain.nii.gz\"))\n\n ref_wf_input_file = p.resource_filename(\"qap\", os.path.join(test_sub_dir,\\\n \"anat_1\", \\\n \"flirt_affine_xfm\", \\\n \"wf_input_string.txt\"))\n\n wf = run_flirt_anatomical_linear_registration(anat_brain, \\\n template_brain, 0)\n\n\n calc_flirt_warp = wf.get_node(\"calc_flirt_warp\")\n \n inputs = []\n ref_inputs = []\n \n inputs.append(calc_flirt_warp.inputs.in_file)\n inputs.append(calc_flirt_warp.inputs.reference)\n inputs.append(calc_flirt_warp.inputs.cost)\n \n ref_inputs.append(anat_brain)\n ref_inputs.append(template_brain)\n ref_inputs.append(\"corratio\")\n \n flag = 0\n \n for test,ref in zip(inputs,ref_inputs):\n if test == ref:\n flag += 1\n\n\n assert flag == 3\n\n\n\ndef test_run_segmentation_workflow():\n\n import os\n import commands\n \n import pkg_resources as p\n\n from qap.anatomical_preproc import run_segmentation_workflow\n\n\n if \"segmentation\" in os.listdir(os.getcwd()):\n\n err = \"\\n[!] The output folder for this workflow already exists.\\n\"\n\n raise Exception(err)\n\n\n anat_brain = p.resource_filename(\"qap\", os.path.join(test_sub_dir, \\\n \"anat_1\", \\\n \"anatomical_brain\", \\\n \"mprage_resample_calc.nii.gz\"))\n\n ref_csf_out = p.resource_filename(\"qap\", os.path.join(test_sub_dir, \\\n \"anat_1\", \\\n \"anatomical_csf_mask\", \\\n \"segment_seg_0.nii.gz\"))\n \n ref_gm_out = p.resource_filename(\"qap\", os.path.join(test_sub_dir, \\\n \"anat_1\", \\\n \"anatomical_gm_mask\", \\\n \"segment_seg_1.nii.gz\"))\n \n ref_wm_out = p.resource_filename(\"qap\", os.path.join(test_sub_dir, \\\n \"anat_1\", \\\n \"anatomical_wm_mask\", \\\n \"segment_seg_2.nii.gz\"))\n\n # run the workflow\n output = run_segmentation_workflow(anat_brain, 0.98, 0.7, 0.98)\n\n ref_list = [ref_csf_out, ref_gm_out, ref_wm_out]\n\n correlation_count = 0\n\n # calculate the correlation\n for out, ref in zip(output, ref_list):\n \n # make the correlation\n ref_out_data = nb.load(ref).get_data() \n output_data = nb.load(out).get_data()\n \n # create a vector of True and False values\n bool_vector = ref_out_data == output_data\n\n if bool_vector.all():\n correlation_count += 1\n\n\n os.system(\"rm -R segmentation\")\n\n\n assert correlation_count == 3\n","sub_path":"qap/test_correlation_anatomical_preproc.py","file_name":"test_correlation_anatomical_preproc.py","file_ext":"py","file_size_in_byte":4730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"89108837","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 25 11:47:41 2019\n\n@author: Anthony Gillioz\n\n@exercise: division\n\"\"\"\n\ndef main():\n print('Enter x y: ', end='')\n x, y = [int(val) for val in input().split()]\n \n assert x <= y, f'x must be smaller than y!'\n \n for i in range(x+1, y):\n try:\n print(f'1/{i} = {1/i}')\n except ZeroDivisionError:\n print(f'Error: {i} has no reciprocal')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"nlp/exercises/assignment_02/1_division.py","file_name":"1_division.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"467207343","text":"#!/usr/bin/env/ python\n#-*- coding:utf-8-*-\n\nimport random, sys, os, gc\nimport keras\nimport numpy as np\nimport pandas as pd\nfrom logging import getLogger, DEBUG, INFO, StreamHandler, basicConfig, FileHandler, Formatter\n\n# 親ファイルのロガー名を受け継ぐ \nlogger = getLogger('GA_logs').getChild('sub')\n\nclass SaveGenes:\n def __init__(self, save_dir, next_generation):\n self.save_dir = save_dir\n self.next_generation = next_generation\n self.save_df = pd.DataFrame()\n self.gene_types = []\n\n def add_genes(self, gene_type, gene_numbers):\n logger.info('{}:{}'.format(gene_type, gene_numbers))\n add_df = pd.DataFrame({gene_type:gene_numbers})\n self.gene_types.append(gene_type)\n self.save_df = pd.concat([self.save_df, add_df], ignore_index=True, axis=1)\n\n def save(self):\n self.save_df.columns = self.gene_types\n gene_save_path = os.path.join(self.save_dir, '{}th_generation_genes.csv'.format(self.next_generation))\n self.save_df.to_csv(gene_save_path)\n\nclass GeneticAlgorithm:\n def __init__(self, pre_model, n_classes, init_gene_num, mutation_ratio):\n self.pre_model = pre_model\n self.pre_model_init_weight = pre_model.get_weights()\n self.target_layer_num = self.get_target_layer_num(self.pre_model)\n self.init_gene_num = init_gene_num\n self.n_classes = n_classes\n self.mutation_ratio = mutation_ratio\n self.initializer = keras.initializers.RandomUniform(minval=-0.05, maxval=0.05, seed=0)\n\n # 重みのあるレイヤーがTrueになるリストを返す\n def is_weighted(self,layer):\n\n not_weighted = len(layer.weights) == 0 or len(layer.weights) == 4 or len(layer.weights) == 3\n \n #重みがある場合Trueを返す \n return not(not_weighted)\n\n # 学習可能対象となる層数\n def get_target_layer_num(self, model):\n logger.info(type(model))\n weighted_layers = [self.is_weighted(layer) for layer in model.layers]\n\n # 出力層は必ず学習層にするので、対象の層から外す\n return sum(weighted_layers) - 1\n\n # 遺伝方の初期化\n def initialize_gene(self, gene_num):\n target_layer_index = [i for i in range(self.target_layer_num)]\n adjustable_layer_index = random.sample(target_layer_index, gene_num)\n genes_list = []\n for idx in adjustable_layer_index:\n gene = [1 if i==idx else 0 for i in range(self.target_layer_num)]\n gene.extend([1])\n genes_list.append(gene)\n return genes_list\n\n # 既に存在する遺伝型を初期値とする\n def previous_gene(self, previous_file):\n df = pd.read_csv(previous_file) \n child_genes = [list(map(int,gene[1:-1].split(','))) for gene in df.iloc[:,2].values]\n parent_genes = [list(map(int,gene[1:-1].split(','))) for gene in df.iloc[:5,3].values]\n alien_genes = [list(map(int,gene[1:-1].split(','))) for gene in df.iloc[:5,4].values]\n\n genes_list = []\n \n for genes in [child_genes, parent_genes, alien_genes]:\n genes_list.extend(genes)\n\n genes_list = [[1 if layer+1 in gene_num else 0 for layer in range(95)] for gene_num in genes_list]\n \n return genes_list\n\n # 遺伝型から何層目が重み更新層か取得\n def get_adjustable_layer_number(self, gene):\n return [i+1 for i, x in enumerate(gene) if x == 1]\n\n def gene2model(self, gene):\n\n # 学習で重みが変更されてしまわないように、元のモデルをコピー\n tmp_pre_model = keras.models.clone_model(self.pre_model)\n tmp_pre_model.set_weights(self.pre_model_init_weight)\n\n #tmp_li_is_weighted はbool型のリストをもつ。重みがない層はTrueを入れる\n tmp_li_is_weighted = [self.is_weighted(l) for l in tmp_pre_model.layers]\n \n #i_last_weightedには数字が入る. 最後の重みのある層 全結合層のindex番号を取得\n i_last_weighted = -1 - tmp_li_is_weighted[::-1].index(True)\n\n tmp_li_is_weighted = tmp_li_is_weighted[:i_last_weighted]\n \n x = tmp_pre_model.layers[i_last_weighted-1].output\n\n #出力層のユニット数を分類クラス数、活性化関数をソフトマックス関数にする\n predictions = keras.layers.Dense(self.n_classes, activation='softmax', name='dense_top')(x)\n\n #学習済みモデルの出力層以外と転移学習用の出力層を結合'\n tmp_model = keras.models.Model(inputs=tmp_pre_model.input, outputs=predictions)\n del tmp_pre_model, predictions\n gc.collect()\n\n li_is_weighted = [self.is_weighted(l) for l in tmp_model.layers]\n\n # 遺伝型の長さは94 + 1 層\n i_gene = 0\n for i_layer in range(len(tmp_model.layers)):\n # 畳み込み層 or 全結合層の場合に操作を行う \n if li_is_weighted[i_layer]:\n if gene[i_gene] == 0:\n tmp_model.layers[i_layer].trainable=False\n\n elif gene[i_gene] == 1:\n tmp_model.layers[i_layer].trainable=True\n \n if i_gene == len(gene) - 1:\n logger.info('output layer trainable')\n \n else:\n logger.info('{} convolutional layer trainable'.format(i_gene + 1))\n else:\n sys.exit('invalid gene value %s' % gene)\n \n # geneのイテレータを増やす\n i_gene += 1\n\n tmp_model.compile(loss='categorical_crossentropy',\n optimizer=keras.optimizers.Adam(),\n metrics=['accuracy'])\n return tmp_model\n\n # エリート選択 \n def elite_selection(self, gene_scores, gene_numbers, save_dir, generation):\n\n logger.info('Elite Selection START')\n\n # 次の世代の遺伝型を保存するためのSaveGenesインスタンス\n save_genes = SaveGenes(save_dir, generation+1)\n\n # エリート遺伝型を作成\n elite_idx = np.argsort(gene_scores)[::-1][:self.init_gene_num//2] \n elite_gene_numbers = [gene_numbers[i] for i in elite_idx]\n\n # デバッグ用\n for gene, score in zip(gene_numbers, gene_scores):\n logger.info('gene:{}, score:{}'.format(gene, score))\n\n save_genes.add_genes('parent_genes', elite_gene_numbers)\n\n # 子遺伝型の作成\n child_genes = self.cross_over(elite_gene_numbers)\n child_gene_numbers = self.gene2number(child_genes)\n save_genes.add_genes('child_genes', child_gene_numbers)\n\n # 次の世代に残すエリート遺伝型\n top_elite_gene_numbers = [gene_numbers[i] for i in elite_idx][:len(child_genes)//2]\n top_elite_genes = []\n for gene_number in top_elite_gene_numbers:\n gene = [1 if i+1 in gene_number else 0 for i in range(self.target_layer_num)]\n gene.extend([1])\n top_elite_genes.append(gene)\n save_genes.add_genes('top_elite_genes', top_elite_gene_numbers)\n\n # 新しく遺伝型を初期化\n new_init_genes = self.initialize_gene(len(top_elite_genes))\n new_init_gene_numbers = self.gene2number(new_init_genes)\n save_genes.add_genes('new_init_genes', new_init_gene_numbers)\n\n # 遺伝型を保存\n save_genes.save()\n \n logger.info('Elite Selection END')\n\n return child_genes, top_elite_genes, new_init_genes\n\n # 交叉\n def cross_over(self, parent_gene_numbers):\n child_genes = []\n for i in range(-1,len(parent_gene_numbers)-1):\n new_gene = [1 if (layer+1) in parent_gene_numbers[i] or (layer+1) in parent_gene_numbers[i+1] else 0 \n for layer in range(self.target_layer_num)] \n new_gene.extend([1]) \n child_genes.append(new_gene)\n return child_genes\n\n # ルーレット選択\n def roulette_selection(self,gene_scores, gene_numbers, save_dir, generation):\n \n logger.info('Roulette Selection START')\n\n # 次の世代の遺伝型を保存するためのSaveGenesインスタンス\n save_genes = SaveGenes(save_dir, generation+1)\n\n # ルーレット選択により親遺伝型を選ぶ\n roulette_selected_gene_numbers, roulette_selected_gene_scores = self.roulette(gene_numbers, \n gene_scores,\n len(gene_numbers)//2)\n\n save_genes.add_genes('parent_genes', roulette_selected_gene_numbers)\n\n # 交叉\n child_genes = self.cross_over(roulette_selected_gene_numbers)\n child_gene_numbers = self.gene2number(child_genes)\n\n save_genes.add_genes('child_genes', child_gene_numbers)\n\n # ルーレット選択された遺伝子からさらにルーレット選択して次の世代に引き継ぐ遺伝型\n next_roulette_selected_gene_numbers, _ = self.roulette(roulette_selected_gene_numbers, \n roulette_selected_gene_scores, \n len(roulette_selected_gene_numbers)//2)\n next_roulette_selected_genes = self.number2gene(next_roulette_selected_gene_numbers)\n\n save_genes.add_genes('roulette_genes', next_roulette_selected_gene_numbers)\n\n # 新しく遺伝型を初期化\n new_init_genes = self.initialize_gene(len(next_roulette_selected_gene_numbers))\n new_init_gene_numbers = self.gene2number(new_init_genes)\n\n save_genes.add_genes('new_init_genes', new_init_gene_numbers)\n\n # 次の世代の遺伝型を保存\n save_genes.save()\n\n logger.info('Roulette Selection END')\n\n return child_genes, next_roulette_selected_genes, new_init_genes\n\n def roulette(self,gene_numbers, gene_scores, select_gene_number):\n # ルーレット選択による遺伝型と適応率\n roulette_selected_gene_numbers = []\n roulette_selected_gene_scores = [] \n\n for gene, score in zip(gene_numbers, gene_scores):\n logger.info('gene: {}, score:{}'.format(gene,score))\n\n # 初期化で生成される遺伝子数の半分の数になるまで選択\n while len(roulette_selected_gene_numbers) < select_gene_number:\n selected_gene = random.choices(gene_numbers, k=1, weights=gene_scores)[0]\n if not selected_gene in roulette_selected_gene_numbers:\n roulette_selected_gene_numbers.append(selected_gene)\n score_idx = gene_numbers.index(selected_gene)\n roulette_selected_gene_scores.append(gene_scores[score_idx])\n \n return roulette_selected_gene_numbers, roulette_selected_gene_scores\n\n # トーナメント選択\n def tournament_selection(self, gene_scores, gene_numbers, save_dir, generation):\n\n logger.info('Tournament Selection START')\n\n # 遺伝型の保存インスタンス\n save_genes = SaveGenes(save_dir, generation+1)\n \n # トーナメントサイズ2で選択 \n tournament_selected_gene_numbers, tournament_selected_gene_scores = self.tournament(gene_numbers, \n gene_scores,\n len(gene_numbers)//2)\n\n save_genes.add_genes('parent_genes', tournament_selected_gene_numbers)\n\n # 交叉\n child_genes = self.cross_over(tournament_selected_gene_numbers)\n child_gene_numbers = self.gene2number(child_genes)\n\n save_genes.add_genes('child_genes', child_gene_numbers)\n\n # 次の世代に引き継ぐ親遺伝型をトーナメント選択で選ぶ\n next_tournament_selected_gene_numbers, _ = self.tournament(tournament_selected_gene_numbers, \n tournament_selected_gene_scores, \n len(tournament_selected_gene_numbers)//2)\n\n next_tournament_selected_genes = self.number2gene(next_tournament_selected_gene_numbers)\n\n save_genes.add_genes('tournament_genes', next_tournament_selected_gene_numbers)\n\n # 新しく遺伝型を初期化\n new_init_genes = self.initialize_gene(len(next_tournament_selected_gene_numbers))\n new_init_gene_numbers = self.gene2number(new_init_genes)\n\n save_genes.add_genes('new_init_genes', new_init_gene_numbers)\n\n save_genes.save()\n\n logger.info('Tournament Selection END')\n\n return child_genes, next_tournament_selected_genes, new_init_genes\n\n # トーナメント\n def tournament(self, gene_numbers, gene_scores, select_gene_number):\n tournament_selected_gene_numbers = []\n tournament_selected_gene_scores = []\n\n genes_index = [i for i in range(len(gene_numbers))]\n \n while len(tournament_selected_gene_numbers) < select_gene_number:\n # 2つの遺伝型をランダムに選ぶ\n target_idx = random.sample(genes_index, k=2)\n\n # 適応値を比較して高い方を採用 \n win_idx = np.argmax([gene_scores[target_idx[0]], gene_scores[target_idx[1]]])\n \n # デバッグ用ログ\n logger.info('target_idx:{}'.format(target_idx))\n logger.info('genes:{}, {}'.format(gene_numbers[target_idx[0]], gene_numbers[target_idx[1]]))\n logger.info('scores:{}, {}'.format(gene_scores[target_idx[0]], gene_scores[target_idx[1]]))\n logger.info('winner:{}'.format(gene_numbers[target_idx[win_idx]]))\n\n tournament_selected_gene_numbers.append(gene_numbers[target_idx[win_idx]])\n tournament_selected_gene_scores.append(gene_scores[target_idx[win_idx]])\n \n # トーナメント選択を行なった遺伝型は候補から外す\n genes_index = [i for i in genes_index if i not in target_idx]\n \n return tournament_selected_gene_numbers, tournament_selected_gene_scores\n\n # エリート選択とルーレット選択のハイブリッド\n def elite_roulette_selection(self, gene_scores, gene_numbers, save_dir, generation):\n \n logger.info('Elite and Roulette Selection START')\n\n # 遺伝型の保存インスタンス\n save_genes = SaveGenes(save_dir, generation+1)\n \n # エリート遺伝型を作成\n elite_idx = np.argsort(gene_scores)[::-1][:self.init_gene_num//2] \n elite_gene_numbers = [gene_numbers[i] for i in elite_idx]\n\n # デバッグ用\n for gene, score in zip(gene_numbers, gene_scores):\n logger.info('gene:{}, score:{}'.format(gene, score))\n\n save_genes.add_genes('parent_genes', elite_gene_numbers)\n\n # 子遺伝型の作成\n child_genes = self.cross_over(elite_gene_numbers)\n child_gene_numbers = self.gene2number(child_genes)\n save_genes.add_genes('child_genes', child_gene_numbers)\n\n # 次の世代に引き継ぐ親遺伝型をトーナメント選択で選ぶ\n next_roulette_selected_gene_numbers, _ = self.roulette(gene_numbers, \n gene_scores, \n len(child_gene_numbers)//2)\n next_roulette_selected_genes = self.number2gene(next_roulette_selected_gene_numbers)\n save_genes.add_genes('roulette_genes', next_roulette_selected_gene_numbers)\n \n # 新しく遺伝型を初期化\n new_init_genes = self.initialize_gene(len(next_roulette_selected_gene_numbers))\n new_init_gene_numbers = self.gene2number(new_init_genes)\n save_genes.add_genes('new_init_genes', new_init_gene_numbers)\n\n save_genes.save()\n\n logger.info('Elite and Roulette Selection END')\n\n return child_genes, next_roulette_selected_genes, new_init_genes\n\n\n # 突然変異\n def mutation(self, genes):\n mutated_genes = []\n for gene in genes:\n if random.random() < self.mutation_ratio:\n logger.info('gene {} mutation!!!'.format(gene))\n\n # ランダムに一部分を値を反転させる\n mutation_idx = random.choice([i for i in range(len(gene)-1)])\n gene[mutation_idx] = 1 if gene[mutation_idx]==0 else 0\n mutated_genes.append(gene)\n\n return mutated_genes\n\n\n # 遺伝型のリストから、層番号のリストに変換\n def gene2number(self, genes):\n gene_numbers = []\n for gene in genes:\n adjustable_layer = [i+1 for i, x in enumerate(gene) if x == 1]\n gene_numbers.append(adjustable_layer)\n return gene_numbers\n\n def number2gene(self, gene_numbers):\n genes = []\n for gene_num in gene_numbers:\n gene = [1 if i+1 in gene_num else 0 for i in range(self.target_layer_num)]\n gene.extend([1])\n genes.append(gene)\n\n return genes","sub_path":"GA_layer_selection/genetic_func.py","file_name":"genetic_func.py","file_ext":"py","file_size_in_byte":17417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"249861908","text":"# https://projecteuler.net/problem=2\n# By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.\n\nimport functools\n\n@functools.lru_cache(maxsize=None) #128 by default\ndef fibonacci(x):\n\tif x < 2:\n\t\treturn 1\n\t\n\treturn fibonacci(x-1) + fibonacci(x-2)\n\n\ndef sum_even_fibonacci_below(below_target):\n\ttotal_sum = 0\n\tx = 0\n\n\twhile True:\n\t\tfx = fibonacci(x)\n\n\t\tif fx > below_target:\n\t\t\treturn total_sum\n\n\t\tif fx % 2 == 0:\n\t\t\tprint(fx)\n\t\t\ttotal_sum += fx\n\n\t\tx = x + 1\n\n\treturn total_sum\n\n\nif __name__ == '__main__':\n\t# Find the sum of all the multiples of 3 or 5 below 1000.\n\tprint(f'The sum of all the even terms of fibonacci below than 4000000 is', sum_even_fibonacci_below(4000000))\n","sub_path":"ProjectEuler/p002/euler_p002_simple_sum.py","file_name":"euler_p002_simple_sum.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"327385575","text":"import pytest\nfrom raiden_contracts.utils.config import C_TOKEN_NETWORK, SETTLE_TIMEOUT_MIN\nfrom raiden_contracts.utils.sign import sign_balance_proof\nfrom .token_network import * # flake8: noqa\nfrom .secret_registry import * # flake8: noqa\n\n\n@pytest.fixture()\ndef create_channel(token_network):\n def get(A, B, settle_timeout=SETTLE_TIMEOUT_MIN):\n token_network.transact().openChannel(A, B, settle_timeout)\n channel_identifier = token_network.call().last_channel_index()\n assert token_network.call().getChannelInfo(channel_identifier)[0] == settle_timeout\n assert token_network.call().getChannelParticipantInfo(channel_identifier, A)[0] is True\n assert token_network.call().getChannelParticipantInfo(channel_identifier, B)[0] is True\n return channel_identifier\n return get\n\n\n@pytest.fixture()\ndef channel_deposit(token_network, custom_token):\n def get(channel_identifier, participant, deposit=None):\n balance = custom_token.call().balanceOf(participant)\n deposit = deposit or balance\n\n while balance < deposit:\n custom_token.transact({'from': participant, 'value': 10 ** 18}).mint()\n balance = custom_token.call().balanceOf(participant)\n\n custom_token.transact({'from': participant}).approve(token_network.address, deposit)\n\n txn_hash = token_network.transact({'from': participant}).setDeposit(\n channel_identifier,\n participant,\n deposit\n )\n return txn_hash\n return get\n\n\n@pytest.fixture()\ndef create_balance_proof(token_network, get_private_key):\n def get(\n channel_identifier,\n participant,\n transferred_amount=0,\n nonce=0,\n locksroot=None,\n additional_hash=None,\n v=27\n ):\n private_key = get_private_key(participant)\n locksroot = locksroot or b'\\x00' * 32\n additional_hash = additional_hash or b'\\x00' * 32\n\n signature = sign_balance_proof(\n private_key,\n token_network.address,\n int(token_network.call().chain_id()),\n channel_identifier,\n nonce,\n transferred_amount,\n locksroot,\n additional_hash,\n v\n )\n return (\n channel_identifier,\n nonce,\n transferred_amount,\n locksroot,\n additional_hash,\n signature\n )\n return get\n","sub_path":"raiden_contracts/tests/fixtures/channel.py","file_name":"channel.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"147516410","text":"import numpy as np\n\nfrom PySide2.QtCore import Qt\n\nfrom matplotlib import patches\nfrom matplotlib.path import Path\nfrom matplotlib.transforms import Affine2D\n\nfrom skimage.draw import polygon\n\nfrom hexrd.ui.create_hedm_instrument import create_hedm_instrument\nfrom hexrd.ui import resource_loader\nfrom hexrd.ui.hexrd_config import HexrdConfig\nfrom hexrd.ui.utils import has_nan\n\n\nclass InteractiveTemplate:\n def __init__(self, parent=None):\n self.parent = parent.image_tab_widget.image_canvases[0]\n self.ax = self.parent.axes_images[0]\n self.panels = create_hedm_instrument().detectors\n self.img = None\n self.shape = None\n self.press = None\n self.total_rotation = 0.\n self.shape_styles = []\n self.translation = [0, 0]\n self.complete = False\n self.event_key = None\n self.parent.setFocusPolicy(Qt.ClickFocus)\n\n @property\n def raw_axes(self):\n return list(self.parent.raw_axes.values())[0]\n\n def update_image(self, img):\n self.img = img\n\n def rotate_shape(self, angle):\n angle = np.radians(angle)\n self.rotate_template(self.shape.xy, angle)\n self.redraw()\n\n def create_shape(self, module, file_name, det, instr):\n self.complete = False\n with resource_loader.resource_path(module, file_name) as f:\n data = np.loadtxt(f)\n verts = self.panels['default'].cartToPixel(data)\n verts[:, [0, 1]] = verts[:, [1, 0]]\n self.shape = patches.Polygon(verts, fill=False, lw=1, color='cyan')\n if has_nan(verts):\n # This template contains more than one polygon and the last point\n # should not be connected to the first. See Tardis IP for example.\n self.shape.set_closed(False)\n self.shape_styles.append({'line': '-', 'width': 1, 'color': 'cyan'})\n self.update_position(instr, det)\n self.connect_translate_rotate()\n self.raw_axes.add_patch(self.shape)\n self.redraw()\n\n def update_style(self, style, width, color):\n self.shape_styles[-1] = {'line': style, 'width': width, 'color': color}\n self.shape.set_linestyle(style)\n self.shape.set_linewidth(width)\n self.shape.set_edgecolor(color)\n self.redraw()\n\n def update_position(self, instr, det):\n pos = HexrdConfig().boundary_position(instr, det)\n if pos is None:\n self.center = self.get_midpoint()\n else:\n dx, dy = pos.get('translation', [0, 0])\n self.translation = [dx, dy]\n self.translate_template(dx, dy)\n self.total_rotation = pos['angle']\n self.rotate_template(self.shape.xy, pos['angle'])\n if instr == 'PXRDIP':\n self.rotate_shape(angle=90)\n\n @property\n def template(self):\n return self.shape\n\n @property\n def masked_image(self):\n mask = self.mask()\n return self.img, mask\n\n @property\n def bounds(self):\n l, r, b, t = self.ax.get_extent()\n x0, y0 = np.nanmin(self.shape.xy, axis=0)\n x1, y1 = np.nanmax(self.shape.xy, axis=0)\n return np.array([max(np.floor(y0), t),\n min(np.ceil(y1), b),\n max(np.floor(x0), l),\n min(np.ceil(x1), r)]).astype(int)\n\n def cropped_image(self, height, width):\n y0, y1, x0, x1 = self.bounds\n y1 = y0+height if height else y1\n x1 = x0+width if width else x1\n self.img = self.img[y0:y1, x0:x1]\n self.cropped_shape = self.shape.xy - np.array([x0, y0])\n return self.img\n\n @property\n def rotation(self):\n return self.total_rotation\n\n def clear(self):\n if self.shape in self.raw_axes.patches:\n self.shape.remove()\n self.redraw()\n self.total_rotation = 0.\n\n def save_boundary(self, color):\n if self.shape in self.raw_axes.patches:\n self.shape.set_linestyle('--')\n self.redraw()\n\n def toggle_boundaries(self, show):\n if show:\n for patch, style in zip(self.patches, self.shape_styles):\n shape = patches.Polygon(\n patch.xy,\n fill=False,\n ls='--',\n lw=style['width'],\n color=style['color']\n )\n if has_nan(patch.xy):\n # This template contains more than one polygon and the last point\n # should not be connected to the first. See Tardis IP for example.\n shape.set_closed(False)\n self.raw_axes.add_patch(shape)\n if self.shape:\n self.shape = self.raw_axes.patches[-1]\n self.shape.remove()\n self.shape.set_linestyle(self.shape_styles[-1]['line'])\n self.raw_axes.add_patch(self.shape)\n self.connect_translate_rotate()\n self.redraw()\n else:\n if self.shape:\n self.disconnect()\n self.patches = [p for p in self.raw_axes.patches]\n self.redraw()\n\n def disconnect(self):\n self.parent.mpl_disconnect(self.button_press_cid)\n self.parent.mpl_disconnect(self.button_release_cid)\n self.parent.mpl_disconnect(self.motion_cid)\n self.parent.mpl_disconnect(self.key_press_cid)\n self.parent.mpl_disconnect(self.button_drag_cid)\n\n def completed(self):\n self.disconnect()\n self.img = None\n self.shape = None\n self.press = None\n self.total_rotation = 0.\n self.complete = True\n\n def mask(self):\n col, row = self.cropped_shape.T\n col_nans = np.where(np.isnan(col))[0]\n row_nans = np.where(np.isnan(row))[0]\n cols = np.split(col, col_nans)\n rows = np.split(row, row_nans)\n master_mask = np.zeros(self.img.shape, dtype=bool)\n for c, r in zip(cols, rows):\n c = c[~np.isnan(c)]\n r = r[~np.isnan(r)]\n rr, cc = polygon(r, c, shape=self.img.shape)\n mask = np.zeros(self.img.shape, dtype=bool)\n mask[rr, cc] = True\n master_mask = np.logical_xor(master_mask, mask)\n self.img[~master_mask] = 0\n return master_mask\n\n def get_paths(self):\n all_paths = []\n points = []\n codes = []\n for coords in self.shape.get_path().vertices[:-1]:\n if np.isnan(coords).any():\n codes[0] = Path.MOVETO\n all_paths.append(Path(points, codes))\n codes = []\n points = []\n else:\n codes.append(Path.LINETO)\n points.append(coords)\n codes[0] = Path.MOVETO\n all_paths.append(Path(points, codes))\n\n return all_paths\n\n def redraw(self):\n self.parent.draw_idle()\n\n def scale_template(self, sx=1, sy=1):\n xy = self.shape.xy\n # Scale the shape\n scaled_xy = Affine2D().scale(sx, sy).transform(xy)\n self.shape.set_xy(scaled_xy)\n\n # Translate the shape back to where it was\n diff = np.array(self.center) - np.array(self.get_midpoint())\n new_xy = scaled_xy + diff\n self.shape.set_xy(new_xy)\n self.redraw()\n\n def on_press(self, event):\n self.event_key = event.key\n if event.key is None:\n self.on_press_translate(event)\n elif event.key == 'shift':\n self.on_press_rotate(event)\n\n def on_release(self, event):\n if self.event_key is None:\n self.on_translate_release(event)\n elif self.event_key == 'shift':\n self.on_rotate_release(event)\n\n def on_key(self, event):\n if 'shift' in event.key:\n self.on_key_rotate(event)\n else:\n self.on_key_translate(event)\n\n def connect_translate_rotate(self):\n self.button_press_cid = self.parent.mpl_connect(\n 'button_press_event', self.on_press)\n self.button_release_cid = self.parent.mpl_connect(\n 'button_release_event', self.on_release)\n self.motion_cid = self.parent.mpl_connect(\n 'motion_notify_event', self.on_translate)\n self.key_press_cid = self.parent.mpl_connect(\n 'key_press_event', self.on_key)\n self.button_drag_cid = self.parent.mpl_connect(\n 'motion_notify_event', self.on_rotate)\n self.parent.setFocus()\n\n def translate_template(self, dx, dy):\n self.shape.set_xy(self.shape.xy + np.array([dx, dy]))\n self.center = self.get_midpoint()\n self.redraw()\n\n def on_key_translate(self, event):\n dx0, dy0 = self.translation\n dx1, dy1 = 0, 0\n delta = 0.5\n if event.key == 'right':\n dx1 = delta\n elif event.key == 'left':\n dx1 = -delta\n elif event.key == 'up':\n dy1 = -delta\n elif event.key == 'down':\n dy1 = delta\n else:\n return\n\n self.translation = [dx0 + dx1, dy0 + dy1]\n self.shape.set_xy(self.shape.xy + np.array([dx1, dy1]))\n self.redraw()\n\n def on_press_translate(self, event):\n if event.inaxes != self.shape.axes or self.event_key == 'shift':\n return\n\n contains, info = self.shape.contains(event)\n if not contains:\n return\n self.press = self.shape.xy, event.xdata, event.ydata\n\n def on_translate(self, event):\n if (self.press is None or\n event.inaxes != self.shape.axes or\n self.event_key == 'shift'):\n return\n\n xy, xpress, ypress = self.press\n dx = event.xdata - xpress\n dy = event.ydata - ypress\n self.center = self.get_midpoint()\n self.shape.set_xy(xy + np.array([dx, dy]))\n self.redraw()\n\n def on_translate_release(self, event):\n if self.press is None or self.event_key == 'shift':\n return\n\n xy, xpress, ypress = self.press\n dx0, dy0 = self.translation\n dx1 = event.xdata - xpress\n dy1 = event.ydata - ypress\n self.translation = [dx0 + dx1, dy0 + dy1]\n self.shape.set_xy(xy + np.array([dx1, dy1]))\n self.press = None\n self.redraw()\n\n def on_press_rotate(self, event):\n if event.inaxes != self.shape.axes or self.event_key != 'shift':\n return\n\n contains, info = self.shape.contains(event)\n if not contains:\n return\n # FIXME: Need to come back to this to understand why we\n # need to set the press value twice\n self.press = self.shape.xy, event.xdata, event.ydata\n self.center = self.get_midpoint()\n self.shape.set_transform(self.ax.axes.transData)\n self.press = self.shape.xy, event.xdata, event.ydata\n\n def rotate_template(self, points, angle):\n x = [np.cos(angle), np.sin(angle)]\n y = [-np.sin(angle), np.cos(angle)]\n verts = np.dot(points - self.center, np.array([x, y])) + self.center\n self.shape.set_xy(verts)\n\n def on_rotate(self, event):\n if (self.press is None or\n event.inaxes != self.shape.axes or\n self.event_key != 'shift'):\n return\n\n x, y = self.center\n xy, xpress, ypress = self.press\n angle = self.get_angle(event)\n self.rotate_template(xy, angle)\n self.redraw()\n\n def on_key_rotate(self, event):\n angle = 0.00175\n # !!! only catch arrow keys\n if event.key == 'shift+left' or event.key == 'shift+up':\n angle *= -1.\n elif event.key == 'shift+right' and event.key == 'shift+down':\n angle *= 1.\n self.total_rotation += angle\n self.rotate_template(self.shape.xy, angle)\n self.redraw()\n\n def get_midpoint(self):\n x0, y0 = np.nanmin(self.shape.xy, axis=0)\n x1, y1 = np.nanmax(self.shape.xy, axis=0)\n return [(x1 + x0)/2, (y1 + y0)/2]\n\n def mouse_position(self, e):\n xmin, xmax, ymin, ymax = self.ax.get_extent()\n x, y = self.get_midpoint()\n xdata = e.xdata\n ydata = e.ydata\n if xdata is None:\n if e.x < x:\n xdata = 0\n else:\n xdata = xmax\n if ydata is None:\n if e.y < y:\n ydata = 0\n else:\n ydata = ymax\n return xdata, ydata\n\n def get_angle(self, e):\n xy, xdata, ydata = self.press\n v0 = np.array([xdata, ydata]) - np.array(self.center)\n v1 = np.array(self.mouse_position(e)) - np.array(self.center)\n v0_u = v0/np.linalg.norm(v0)\n v1_u = v1/np.linalg.norm(v1)\n angle = np.arctan2(np.linalg.det([v0_u, v1_u]), np.dot(v0_u, v1_u))\n return angle\n\n def on_rotate_release(self, event):\n if self.press is None or self.event_key != 'shift':\n return\n angle = self.get_angle(event)\n self.total_rotation += angle\n y, x = self.center\n xy, xpress, ypress = self.press\n self.press = None\n self.rotate_template(xy, angle)\n self.redraw()\n","sub_path":"hexrd/ui/interactive_template.py","file_name":"interactive_template.py","file_ext":"py","file_size_in_byte":13141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"347032869","text":"#encoding:utf8\nfrom django.conf.urls import url \nfrom blog import views \n \nurlpatterns =[\n url(r'^$',views.all_blogs,name='all_blog'),\n url(r'^page_(?P(\\d+))/$',views.divided_page,name='divided_page'),\n url(r'^(?P(\\d+))/$', views.detail, name='detail'),#传参数id给视图函数detail进行处理\n url(r'^post/$', views.post, name='post'),#在主页中点击post按钮,跳转到post.html\n url(r'^blog_add/$', views.blog_add, name='blog_add'), #把post.html输入的内容存到数据库中\n url(r'^blog_delete/$', views.blog_delete, name='blog_delete'),\n url(r'^blog_change/$', views.blog_change, name='blog_change'),\n url(r'^blog_edit/$', views.blog_edit, name='blog_edit'),\n url(r'^leave_comment/$', views.leave_comment, name='leave_comment'), #留言\n]","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"509412570","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 16 12:15:36 2018\n\n@author: akanksha\n\"\"\"\n\nimport argparse \nimport numpy as np\nimport os\nfrom collections import Counter\nimport subprocess \nimport itertools\nimport sys\nimport shutil\nfrom collections import OrderedDict\nimport functools\nimport pandas as pd\nimport multiprocessing\nimport multiprocessing.pool\nfrom HOME import HOME_functions as ho\n\nfrom os.path import join\n\ndef remEmptyDir(mypath):\n for root, dirs, files in os.walk(mypath,topdown=False):\n for name in dirs:\n fname = join(root,name)\n if not os.listdir(fname): #to check wither the dir is empty\n \n os.removedirs(fname)\ndef main(c,nop, topass, args):\n package_path = os.path.dirname(os.path.abspath(__file__))\n classes = args.type\n numreps=topass['numreps']\n if True: \n \n df_path=[]\n sample_name_temp=[]\n for i in range(len(topass['dictionary'])):\n \n val=[]\n count=0\n d_rep={}\n input_file1=list(topass['dictionary'].values())[i]\n sample_name1=list(topass['dictionary'].keys())[i]\n sample_name_temp.append(sample_name1)\n \n for j in input_file1:\n \n count=count+1\n c1=[\"chr\", \"pos\", \"strand\", \"type\", \"mc_rep\"+str(count), \"h_rep\"+str(count)]\n \n d_rep[count]=pd.read_csv(j+'/'+c+'.tsv',header=None,names=c1,sep='\\t')\n filter_col1 = [col for col in list(d_rep[count]) if col.startswith(('h'))]\n d_rep[count]=d_rep[count].loc[(d_rep[count][filter_col1]!=0).any(axis=1)]\n if args.Keepall: \n val.append(functools.reduce(topass['mergeo'], list(d_rep.values()))) \n df=functools.reduce(topass['merge'], val)\n df.pos=df.pos.astype(int)\n df.chr=df.chr.astype(str)\n df=ho.fill_na(df) \n else: \n val.append(functools.reduce(topass['merge'], list(d_rep.values()))) \n df=functools.reduce(topass['merge'], val) \n preordered = [\"chr\", \"pos\", \"strand\", \"type\"] \n new_cols = preordered + [co for co in df.columns if co not in preordered]\n df=df.reindex(columns=new_cols) \n df=df.sort_values(['pos'])\n df.to_csv(args.outputpath+'/temp_HOME/'+sample_name1+\"_format_{c}.txt\".format(c=c),header=True, index=False,sep='\\t') \n df_path.append(args.outputpath+'/temp_HOME/'+sample_name1+\"_format_{c}.txt\".format(c=c)) \n dictionary_new = OrderedDict(list(zip(sample_name_temp,df_path)))\n result_list = list(map(OrderedDict, itertools.combinations(iter(list(dictionary_new.items())), 2)))\n if args.withrespectto is not None:\n result_list=[iii for iii in result_list if list(iii.keys())[0] in args.withrespectto] \n\n for iii in result_list:\n \n input_file1= iii[list(iii.keys())[0]]\n input_file2=iii[list(iii.keys())[1]]\n \n if (len(input_file1)!=0 and len(input_file2)!=0):\n sample_name1=list(iii.keys())[0]\n sample_name2=list(iii.keys())[1]\n dfa=pd.read_csv(str(input_file1),sep='\\t')\n dfb=pd.read_csv(str(input_file2),sep='\\t')\n ra=dfa.shape[1]-4\n rb=dfb.shape[1]-4\n \n p_mc=3\n p_h=4\n for i in range(1,((ra)//2)+1):\n \n dfa.rename(columns={dfa.columns[i+p_mc]:\"mc_cont_rep\"+str(i)}, inplace = True)\n dfa.rename(columns={dfa.columns[i+p_h]:\"h_cont\"+\"_rep\"+str(i)}, inplace = True)\n p_mc=p_mc+1\n p_h=p_h+1\n \n p_mc=3\n p_h=4 \n for i in range(1,((rb)//2)+1):\n \n dfb.rename(columns={dfb.columns[i+p_mc]:\"mc_case\"+\"_rep\"+str(i)}, inplace = True)\n dfb.rename(columns={dfb.columns[i+p_h]:\"h_case\"+\"_rep\"+str(i)}, inplace = True)\n p_mc=p_mc+1\n p_h=p_h+1\n \n df = pd.merge(dfa, dfb, how='inner', on=['chr','pos',\"strand\",\"type\"])\n if len(df)>1:\n df=df.sort_values(['pos'])\n df1=ho.format_allc(df, classes)\n \n del(df) \n if len(df1)>5:\n \n if min(numreps)>1 and max(numreps)>1:\n nop=min(nop,len(df1))\n CHUNKSIZE = int(len(df1)//nop)\n CHUNKSIZE_list=[CHUNKSIZE]*nop \n extra=(len(df1)%nop)\n \n if extra> 0:\n \n CHUNKSIZE_list[-1]=CHUNKSIZE_list[-1]+extra\n \n df_chunk=ho.chunker1(df1,CHUNKSIZE_list)\n ttc=0\n df_path=[]\n \n for i in df_chunk:\n \n ttc=ttc+1\n i.to_csv(args.outputpath+'/temp_HOME'+'/chunks/'+sample_name1+\"VS\"+sample_name2+\"_df_{c}_{ttc}.txt\".format(c=c,ttc=ttc),header=True, index=False,sep='\\t') \n df_path.append(args.outputpath+'/temp_HOME'+'/chunks/'+sample_name1+\"VS\"+sample_name2+\"_df_{c}_{ttc}.txt\".format(c=c,ttc=ttc))\n \n if nop>1: \n \n pool = multiprocessing.Pool(processes=nop)\n process = [pool.apply_async(ho.process_frame_withR, args=(dd,)) for dd in df_path]\n pool.close()\n pool.join()\n \n pool = multiprocessing.Pool(processes=nop)\n process = [pool.apply_async(ho.pval_format_withrep, args=(dd,)) for dd in df_path]\n pool.close()\n pool.join()\n \n output = [p.get() for p in process]\n df3=pd.concat(output, ignore_index=True,axis=0)\n \n else:\n \n ho.process_frame_withR(df_path[0])\n df3=ho.pval_format_withrep(df_path[0])\n \n smooth_exp_val=ho.smoothing(*df3.exp_val) \n \n df3['smooth_val']=(smooth_exp_val-min(smooth_exp_val))/(max(smooth_exp_val)-min(smooth_exp_val))\n df3=df3.fillna(0) \n \n else:\n \n df3=ho.pval_cal_withoutrep(df1)\n \n #if classes.startswith(\"CG\"):\n if classes==\"CGN\":\n #input_file_path=np.load(os.getcwd()+'/training_data/hist_data_CG.npy')\n input_file_path=np.load(package_path+'/training_data/hist_data_CG.npy')\n \n #model_path=os.getcwd()+'/saved_model/CG/new/hist/'\n model_path=package_path+'/saved_model/CG/new/hist/'\n k=ho.norm_slidingwin_predict_CG(df3,input_file_path,model_path)\n \n len_cutoff=10\n tr=args.pruncutoff\n dmrs=ho.clustandtrim_CG(k,df3,args.scorecutoff,args.pruncutoff,args.mergedist,args.numcb,args.prunningC,len_cutoff)\n \n \n if len(dmrs)>=1:\n \n dmrs_filtered=ho.filterdmr(dmrs,args.minlength,args.minc,args.delta)\n else: \n print((\"No DMRs found for \"+sample_name1+\"_VS_\"+sample_name2+\"_{c}\".format(c=c)))\n continue \n # \n else:\n #input_file_path=np.load(os.getcwd()+'/training_data/hist_data_nonCG.npy')\n input_file_path=np.load(package_path+'/training_data/hist_data_nonCG.npy')\n #model_path=os.getcwd()+'/saved_model/nonCG/new/hist/'\n model_path=package_path+'/saved_model/nonCG/new/hist/'\n if (nop>1 and nop1 and nop 0:\n CHUNKSIZE_list[-1]=CHUNKSIZE_list[-1]+extra\n df_chunk=ho.chunker1(k,CHUNKSIZE_list)\n \n pool = multiprocessing.Pool(processes=nop)\n process = [pool.apply_async(ho.clustandtrim_nonCG1, args=(dd,sc)) for dd in df_chunk]\n pool.close()\n pool.join()\n output = [p.get() for p in process]\n \n pre_dmr=pd.concat(output, ignore_index=True,axis=0)\n if len(pre_dmr)>=1:\n df_split=ho.splitlist(k,pre_dmr,nop,dis_thres)\n else: \n print((\"No DMRs found for \"+sample_name1+\"_VS_\"+sample_name2+\"_{c}\".format(c=c)))\n continue\n \n del(pre_dmr,k)\n \n pool = multiprocessing.Pool(processes=nop)\n process = [pool.apply_async(ho.clustandtrim_nonCG2, args=(ddd,dd,dis_thres,ncb,len_cutoff)) for dd,ddd in df_split]\n pool.close()\n pool.join()\n output = [p.get() for p in process]\n \n dmrs=pd.concat(output, ignore_index=True,axis=0)\n else:\n pre_dmr=ho.clustandtrim_nonCG1(k,sc)\n if len(pre_dmr)>=1:\n dmrs=ho.clustandtrim_nonCG2(k,pre_dmr,dis_thres,ncb,len_cutoff)\n else: \n print((\"No DMRs found for \"+sample_name1+\"_VS_\"+sample_name2+\"_{c}\".format(c=c)))\n continue\n if len(dmrs)>=1:\n \n dmrs_filtered=ho.filterdmr_nonCG(dmrs,minlen,mc,d) \n else: \n print((\"No DMRs found for \"+sample_name1+\"_VS_\"+sample_name2+\"_{c}\".format(c=c)))\n continue \n \n \n if len(dmrs_filtered)>=1: \n \n dmr_final=pd.concat([df1.chr[0:len(dmrs_filtered)],dmrs_filtered],axis=1)\n dmr_final['chr'] = dmr_final['chr'].astype(str)\n dmr_final.to_csv(args.outputpath+'/HOME_pairwise_DMRs/'+sample_name1+\"_VS_\"+sample_name2+\"/HOME_DMRs_{c}.txt\".format(c=c),header=True, index=False,sep='\\t')\n print((\"DMRs for \"+sample_name1+\"_VS_\"+sample_name2+\"_{c} done\".format(c=c)))\n \n elif len(dmrs_filtered)<1: \n print((\"No DMRs found for \"+sample_name1+\"_VS_\"+sample_name2+\"_{c}\".format(c=c)))\n else: \n print((\"No DMRs found for \"+sample_name1+\"_VS_\"+sample_name2+\"_{c}\".format(c=c)))\n else: \n print((\"No DMRs found for {c} as no similar positions are observed in the files\".format(c=c))) \n else:\n print((\"No DMRs found for {c} as file does not exit\".format(c=c))) \n return \n \n#main code\n\n## Inputs from user \ndef real_main():\n topass = dict()\n np.set_printoptions(threshold=np.inf,suppress=True,linewidth=np.inf,precision=3)\n parser = argparse.ArgumentParser(description='HOME -- HISTOGRAM Of METHYLATION',formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('-i','--samplefilepath', help='path of the sample file with samplename and sample path TAB seperated', required=True)\n parser.add_argument('-t','--type', help='type of class', choices=[\"CGN\",\"CHN\"],required=True, type=str)\n parser.add_argument('-o','--outputpath', help='path where the DMRs will be saved', required=True)\n parser.add_argument('-sc','--scorecutoff', help='min classifier score required to cluster the DMR',choices=np.round(np.linspace(0,1,20,endpoint=False),decimals=2), required=False, type=float,default=0.1)\n parser.add_argument('-p','--pruncutoff', help='prunning cutoff for boundaries', required=False,choices=np.round(np.arange(0,0.5,0.1),decimals=1), type=float,default=0.1)\n parser.add_argument('-ml','--minlength', help='minimum length of DMRs to be reported', required=False, type=int,default=50)\n parser.add_argument('-ncb','--numcb', help='number of Cs required between DMRs to keep them seperate', required=False, type=int,default=5)\n parser.add_argument('-md','--mergedist', help='distance between DMRs to merge', required=False, type=int,default=500)\n #parser.add_argument('-sin','--singlechrom', help='parallel for single chromosomes',action='store_true',default=False)\n parser.add_argument('-npp','--numprocess', help='number of parallel processes for all chromosome', required=False, type=int,default=8)\n parser.add_argument('-mc','--minc', help='minimum number of C in a DMR to reported', required=False, type=int,default=3)\n parser.add_argument('-d','--delta', help='minimum average difference in methylation required', required=False, type=float,default=0.1)\n parser.add_argument('-prn','--prunningC', help='number of Cs required for prunning', required=False, type=int,default=3)\n parser.add_argument('-ns','--numsamples', help='number of samples to use for pairwise DMR calling', required=False, type=int)\n parser.add_argument('-sp','--startposition', help='start position of samples to use for pairwise DMR calling', required=False, type=int)\n parser.add_argument('-wrt','--withrespectto', help='samples to use for DMR calling for pairwise comparision with respect to specific samples', nargs='*',required=False, type=str)\n parser.add_argument('-Keepall','--Keepall', help='Keep all cytosine positions present among replicates',action='store_true',default=False)\n \n \n ## Read the inputs and preprocess the files \n o=parser.parse_args()\n classes=o.type\n if o.startposition is not None:\n \n sp=(o.startposition)-1\n else:\n \n sp=0\n \n if o.numsamples is not None:\n \n ns=o.numsamples\n else:\n \n ns=len(o.samplefilepath)\n #Keepall=o.Keepall \n df_file=pd.read_csv(o.samplefilepath,header=None, sep='\\t')\n samplenames=df_file.iloc[sp:sp+ns,0]\n samplenames.reset_index(drop=True,inplace=True)\n input_files=df_file.iloc[sp:sp+ns,1:]\n input_files.reset_index(drop=True,inplace=True)\n numreps=[len(input_files.iloc[x].dropna()) for x in range (len(input_files))]\n topass['numreps']=numreps\n \n input_files=[list(input_files.iloc[x].dropna()) for x in range (len(input_files))]\n \n k=-1\n cwd = os.getcwd()\n \n \n if not os.path.exists((o.outputpath+'/temp_HOME')):\n os.makedirs(o.outputpath+'/temp_HOME')\n else: \n print(\" Temp directory at output path already exist.... please clean up and rerun\")\n #sys.exit()\n \n input_files_mod=[]\n \n ## make output directory and store the input files per chromosome could be done in python but using awk as its faster \n for i in input_files:\n temp_file=[]\n k=k+1\n for ii in range(len(i)):\n \n #if not os.path.exists((o.outputpath+'/temp_HOME'+'/'+samplenames[k]+'_rep'+str(ii+1))):\n if True:\n if not os.path.exists((o.outputpath+'/temp_HOME'+'/'+samplenames[k]+'_rep'+str(ii+1))):\n os.makedirs((o.outputpath+'/temp_HOME'+'/'+samplenames[k]+'_rep'+str(ii+1)))\n os.chdir((o.outputpath+'/temp_HOME'+'/'+samplenames[k]+'_rep'+str(ii+1)))\n \n com='zcat -f '+i[ii]+ ' | '\n if classes==\"CGN\":\n com+=''' awk -v OFS='\\t' '{if (substr($4,1,2)== \"CG\") {print $1\"\\t\"$2\"\\t\"$3\"\\t\"$4\"\\t\"$5\"\\t\"$6 >> $1\".tsv\"}}' '''\n else:\n com+=''' awk -v OFS='\\t' '{if (substr($4,2,1)!= \"G\") {print $1\"\\t\"$2\"\\t\"$3\"\\t\"$4\"\\t\"$5\"\\t\"$6 >> $1\".tsv\"}}' '''\n\n\n status=subprocess.call(com, shell=True)\n \n temp_file.append(os.getcwd())\n os.chdir(cwd)\n input_files_mod.append(temp_file) \n input_files=input_files_mod\n del(input_files_mod,temp_file)\n #s=[ os.path.splitext(os.path.basename(x))[0] for x in glob.glob(input_files[0][0]+'/*.tsv')]\n s=[f.split('.')[0] for dp, dn, filenames in os.walk(o.outputpath+'/temp_HOME') for f in filenames if os.path.splitext(f)[1] == '.tsv']\n s = Counter(s)\n coun_s=len(next(os.walk(o.outputpath+'/temp_HOME'))[1])\n s=[kv for kv, v in list(s.items()) if v == (coun_s)]\n os.chdir(cwd) \n \n \n if not os.path.exists((o.outputpath+'/temp_HOME'+'/chunks')):\n os.makedirs(o.outputpath+'/temp_HOME'+'/chunks')\n else: \n print(\" Temp directory at output path already exist.... please clean up and rerun\")\n if not os.path.exists((o.outputpath+'/HOME_pairwise_DMRs')):\n os.makedirs(o.outputpath+'/HOME_pairwise_DMRs') \n\n \n \n sc=o.scorecutoff\n prn=o.prunningC\n tr=o.pruncutoff\n minlen=o.minlength\n \n dis_thres=o.mergedist\n ncb=o.numcb\n mc=o.minc\n d=o.delta\n #sin=o.singlechrom\n npp=o.numprocess\n nop=1\n #if sin==True:\n # nop=npp\n # npp=1\n #else: \n # nop=1\n \n \n #\"handle any number of replicates as long as it is 2+ in all groups but cannot handle 1 replicate in 1 group and multiple in the other\"\n if (min(numreps)==1 and max(numreps)>1):\n sys.exit('error: cannot handle 1 replicate in 1 group and more than 1 in other')\n \n pd.options.mode.chained_assignment = None\n mergeo = functools.partial(pd.merge, how='outer', on=['chr','pos',\"strand\",\"type\"]) \n merge = functools.partial(pd.merge, how='inner', on=['chr','pos',\"strand\",\"type\"])\n topass['mergeo']=mergeo\n topass['merge']=merge\n topass['dictionary'] = OrderedDict(list(zip(list(samplenames),list(input_files))))\n comb_samples=itertools.combinations(list(samplenames), 2)\n if o.withrespectto is not None:\n comb_samples=[coms for coms in comb_samples if coms[0] in o.withrespectto]\n for i in comb_samples:\n if not os.path.exists(o.outputpath+'/HOME_pairwise_DMRs/'+i[0]+\"_VS_\"+i[1]):\n os.makedirs(o.outputpath+'/HOME_pairwise_DMRs/'+i[0]+\"_VS_\"+i[1])\n \n if status==0: \n print(\"Preparing the DMRs from HOME.....\") \n print(\"GOOD LUCK !\") \n\n\n if npp==1: \n print('ha')\n for dx in s:\n main(dx,nop,topass,o)\n shutil.rmtree(o.outputpath+'/temp_HOME', ignore_errors=True)\n print(\"Congratulations the DMRs are ready\") \n remEmptyDir(o.outputpath+'/HOME_DMRs/')\n elif npp>1:\n print('he')\n pool1= multiprocessing.Pool(processes=npp)\n process=[pool1.apply_async(main, args=(dx,nop,topass,o)) for dx in s]\n output = [p.get() for p in process]\n pool1.close()\n print(\"Congratulations the DMRs are ready\")\n pool1.join()\n shutil.rmtree(o.outputpath+'/temp_HOME', ignore_errors=True)\n remEmptyDir(o.outputpath+'/HOME_DMRs/')\n \n\n\n\n\n\n #print 'npp',npp\n #print s\n #pool1= multiprocessing.Pool(processes=npp)\n #process=[pool1.apply_async(main, args=(dx,nop,topass,o)) for dx in s]\n #output = [p.get() for p in process]\n #pool1.close()\n #print(\"Congratulations the DMRs are ready\")\n #pool1.join()\n #shutil.rmtree(o.outputpath+'/temp_HOME', ignore_errors=True)\n #remEmptyDir(o.outputpath+'/HOME_DMRs/')\n \n","sub_path":"HOME/home_pairwise.py","file_name":"home_pairwise.py","file_ext":"py","file_size_in_byte":22823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"148224355","text":"import os\nimport sys\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.font_manager import FontProperties\nimport matplotlib\nimport numpy as np\n\nfrom datetime import datetime,timedelta\nimport pandas as pd\n\n\n# # 处理客户端rtt delay/std 与 QPS 关系\ndatas = []\nwith open(\"BC26_20211031-202111110_analyze_datas/datas.txt\", 'r') as f:\n datasInFile = f.read().split('\\n', -1)\n for i in datasInFile :\n splitByspace = i.split(' ', -1)\n datas.append(splitByspace)\nprint(datas)\n\ndef initarray (QPS_begin, QPS_end):\n array = []\n for i in range(QPS_begin, QPS_end + 1):\n array.append(0)\n return array\nUL_total = initarray(10, 30)\nDL_total = initarray(10, 30)\ntest_times = initarray(10, 30)\nUL_average = initarray(10, 30)\nDL_average = initarray(10, 30)\nUL_std = initarray(10, 30)\nUL_std_total = initarray(10, 30)\nDL_std = initarray(10, 30)\nDL_std_total = initarray(10, 30)\n\n\nfor i in datas:\n index = int(i[0]) - 10\n this_times = int(i[1])\n this_UL_average = int(i[10])\n this_UL_std = int(i[11])\n this_DL_average = int(i[12])\n this_DL_std = int(i[13])\n test_times[index] += this_times\n UL_total[index] += this_times * this_UL_average\n DL_total[index] += this_times * this_DL_average\n UL_std_total[index] += this_UL_std * this_UL_std * this_times\n DL_std_total[index] += this_DL_std * this_DL_std * this_times\n\nfor i in range(10, 31):\n index = i - 10\n UL_std[index] = (UL_std_total[index] / test_times[index]) ** 0.5\n DL_std[index] = (DL_std_total[index] / test_times[index]) ** 0.5\n UL_average[index] = UL_total[index] / test_times[index]\n DL_average[index] = DL_total[index] / test_times[index]\n\nx_tick_label = []\nfor i in range(10, 31):\n x_tick_label.append(str(i))\n\n\ndata = [UL_average, DL_average]\n\ndef create_multi_bars(labels, datas, tick_step=1, group_gap=0.2, bar_gap=0):\n '''\n labels : x轴坐标标签序列\n datas :数据集,二维列表,要求列表每个元素的长度必须与labels的长度一致\n tick_step :默认x轴刻度步长为1,通过tick_step可调整x轴刻度步长。\n group_gap : 柱子组与组之间的间隙,最好为正值,否则组与组之间重叠\n bar_gap :每组柱子之间的空隙,默认为0,每组柱子紧挨,正值每组柱子之间有间隙,负值每组柱子之间重叠\n '''\n # ticks为x轴刻度\n ticks = np.arange(len(labels)) * tick_step\n # group_num为数据的组数,即每组柱子的柱子个数\n group_num = len(datas)\n # group_width为每组柱子的总宽度,group_gap 为柱子组与组之间的间隙。\n group_width = tick_step - group_gap\n # bar_span为每组柱子之间在x轴上的距离,即柱子宽度和间隙的总和\n bar_span = group_width / group_num\n # bar_width为每个柱子的实际宽度\n bar_width = bar_span - bar_gap\n # baseline_x为每组柱子第一个柱子的基准x轴位置,随后的柱子依次递增bar_span即可\n baseline_x = ticks - (group_width - bar_span) / 2\n i = 0\n for index, y in enumerate(datas):\n\n if i == 0:\n plt.bar(baseline_x + index*bar_span, y, bar_width, color='y', label = \"UL delay\", alpha=0.7)\n elif i == 1:\n plt.bar(baseline_x + index*bar_span, y, bar_width, color='purple', label = \"DL delay\",alpha=0.7)\n i += 1\n plt.ylabel('ms')\n plt.xlabel('QPS')\n plt.title('LwM2M/TCP/NB-IoT UL_DL-QPS')\n # x轴刻度标签位置与x轴刻度一致\n plt.xticks(ticks, labels)\n plt.ylim(0, 3000)\n plt.legend(loc='upper left')\n plt.show()\n\ncreate_multi_bars(x_tick_label, data, bar_gap=0.1)\n","sub_path":"pythonProject/BC26_20211031-202111110_analyze/QPS-RTT UL DL.py","file_name":"QPS-RTT UL DL.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"135725730","text":"import cv2\n\nresult_scale_percent = 50\nBLUE = (255, 0, 0)\n\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\nimg = cv2.imread('test.jpg')\n\nwidth = int(img.shape[1] * result_scale_percent / 100)\nheight = int(img.shape[0] * result_scale_percent / 100)\ndim = (width, height)\nimg = cv2.resize(img, dim, interpolation=cv2.INTER_AREA)\n\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\nfaces = face_cascade.detectMultiScale(gray, 1.1, 4)\n\nfor (x, y, w, h) in faces:\n cv2.rectangle(img, (x, y), (x + w, y + h), BLUE, 2)\n\ncv2.imshow('Detection result', img)\ncv2.waitKey()","sub_path":"Haar/Haar_homework.py","file_name":"Haar_homework.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"51648184","text":"from bs4 import BeautifulSoup\nimport csv\n\n\"\"\"\n#debug\nfile = open('output.txt', \"r\")\nhtml = file.read()\nfile.close()\n\"\"\"\n\ndef write_header(html):\n #print(html)\n soup = BeautifulSoup(html, 'html.parser')\n table = soup.select_one(\"table\")\n #print(table)\n headers = [th for th in table.select(\"tr\")]\n \n # mese, giorno, pioggia mm, ...\n row = [th.text.strip() for th in headers[0].select(\"th\")]\n new_row = []\n for i in range(len(row)):\n row[i].strip().replace(\"\\n\", \"\") \n new_row.append(\" \".join(row[i].split()))\n new_row.append(\"Stazione\")\n new_row.append(\"Anno\")\n return new_row \n\ndef write_dati(html,anno):\n \n soup = BeautifulSoup(html, 'html.parser')\n #nome della stazione\n div = soup.find('div', id = \"dati\")\n nome = div.find('b')\n nome = nome.text\n table = soup.select_one(\"table\") \n #dati \n dati = [[td.text for td in row.find_all('td')] for row in table.select(\"tr\")] \n dati.pop(0)\n for a in range(0, len(dati)):\n for j in range(len(dati[a])):\n dati[a][j] = dati[a][j].strip().replace(\"\\n\", \"\") \n dati[a][j] = \" \".join(dati[a][j].split()) \n if (dati[a][j] == '-'):\n dati[a][j] = '' \n dati[a].append(nome) #aggiungo il nome della stazione\n dati[a].append(anno)\n return dati\n\n\ndef final_parsing(html_list,anno,filename):\n if (len(html_list) == 0):\n print('nessun risultato')\n return\n header = write_header(html_list[0]) \n dati = []\n for e in html_list:\n dati = dati + write_dati(e,anno) \n \n #scrittura su file \n with open(filename, \"w\") as f:\n wr = csv.writer(f)\n wr.writerow(header) \n wr.writerows(dati) \n f.close()","sub_path":"seleniumProject/Friuli/firefox_version/parseFriuliAll.py","file_name":"parseFriuliAll.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"165107837","text":"\"\"\"\n This module is used to handle ue trace download issues.\n\"\"\"\n\nimport os\nimport glob\nimport shutil\nimport tarfile\nimport logging\nimport datetime\nimport subprocess\nimport handler\n\nfrom util.client import NodeOffline\nfrom downloader import UEDownloader\nfrom handler import UECSVHandler, UECSVNameHandler\nfrom format import string2date\nfrom nodeManagement.node_info import get_all_nodes_from_db\n\nlogger = logging.getLogger(__name__)\n\nLOCALPATH = '../ue_trace_files'\nLOCALPATH_TEMP = '../ue_trace_files/tmp'\nLOCALPATH_PCAPS = '../ue_trace_files/pcaps'\nLOCAL_FILES_EXPIRE_HOURS = 24\nREMOTEPATH = {'SGSN-MME': '/tmp/OMS_LOGS/ue_trace/ready',\n 'EPG': '/var/log/services/epg/uetrace'}\n\n\nclass UETrace(object):\n \"\"\" This class is used to download ue trace files from nodes, and\n save data into database.\n \"\"\"\n def __init__(self, time_limit, output=None):\n self.time_limit = time_limit\n self.output = os.path.join(output, LOCALPATH) if output else LOCALPATH\n self.make_dir(self.output)\n self.pcaps_path = self._prepare_pcaps_path(output)\n self.temp_path = self._prepare_temp_path(output)\n\n def _prepare_pcaps_path(self, output):\n path = os.path.join(output, LOCALPATH_PCAPS) if output else LOCALPATH_PCAPS\n self.make_dir(path)\n return path\n\n def _prepare_temp_path(self, output):\n path = os.path.join(output, LOCALPATH_TEMP) if output else LOCALPATH_TEMP\n self.make_dir(path)\n return path\n\n def download(self):\n nodes = get_all_nodes_from_db()\n uetrace_files = []\n for nodeinfo in nodes:\n remotepath = REMOTEPATH[nodeinfo.get_node_type()]\n try:\n downloader = UEDownloader(nodeinfo, self.time_limit, self.output, remotepath)\n except NodeOffline as err:\n continue\n part_files = downloader.run()\n uetrace_files.extend(part_files)\n return uetrace_files\n\n def make_dir(self, path):\n try:\n if not os.path.exists(path):\n os.mkdir(path)\n except OSError as err:\n logger.error(err)\n\n def convert_to_csv(self, input_files):\n if input_files:\n input = ' '.join([os.path.join(self.output, file) for file in input_files])\n cmd = 'EBMLogTool -uetrace -i %s -o %s' % (input, self.temp_path)\n return subprocess.call(cmd, shell=True) == 0\n return False\n\n def save_csv_to_db(self, path):\n csv_files_with_path = glob.glob(path + '/*.csv')\n csv_filenames = [file.split('/')[-1] for file in csv_files_with_path]\n uecsv = UECSVHandler(path, csv_filenames)\n uecsv.run()\n return csv_filenames\n\n def save_filenames_to_db(self, csv_filenames):\n uefiles = UECSVNameHandler(None, csv_filenames)\n uefiles.run()\n\n def clean_old_files(self, path):\n current_utc_time = datetime.datetime.utcnow()\n if os.path.exists(path):\n old_files = (file for file in os.listdir(path)\n if os.path.isfile(os.path.join(path, file)))\n delta_time = datetime.timedelta(hours=LOCAL_FILES_EXPIRE_HOURS)\n check_time = current_utc_time - delta_time\n for name in old_files:\n if 'tar.gz' in name:\n continue\n try:\n start_date = string2date(name)\n except ValueError as err:\n logger.error(err)\n else:\n if start_date < check_time:\n os.remove(os.path.join(path, name))\n\n def move_temp_files(self):\n files = os.listdir(self.temp_path)\n for file in files:\n shutil.copy(os.path.join(self.temp_path, file), self.pcaps_path)\n shutil.rmtree(self.temp_path)\n\n def package_pcaps(self):\n pcap_files_with_path = glob.glob(self.pcaps_path + '/*.pcap')\n pcap_files = (file.split('/')[-1] for file in pcap_files_with_path)\n\n pcap_dict = {}\n for file in pcap_files:\n temp = file.split('_', 1)[1][:-5]\n if '_ue_trace' in temp:\n temp = temp.split('.')[1].split('_', 1)[1]\n pcap_dict.setdefault(temp, []).append(file)\n\n for trace_ref_imsi, pcap_filenames in pcap_dict.items():\n tar_filename = os.path.join(self.pcaps_path, '%s.tar' % (trace_ref_imsi))\n with tarfile.open(tar_filename + '.gz', 'w:gz') as tar:\n for name in pcap_filenames:\n tar.add(os.path.join(self.pcaps_path, name), name)\n\n def run(self):\n if self.time_limit:\n self.run_online()\n else:\n self.run_offline()\n\n def run_online(self):\n self.clean_old_files(self.output)\n self.clean_old_files(os.path.join(self.output, 'pcaps'))\n uetrace_files = self.download()\n\n self.save_data_to_db(uetrace_files)\n\n def run_offline(self):\n uetrace_files = []\n try:\n uetrace_files = os.listdir(self.output)\n except OSError as err:\n logger.error(err)\n\n self.save_data_to_db(uetrace_files)\n\n def save_data_to_db(self, uetrace_files):\n if self.convert_to_csv(uetrace_files):\n csv_filenames = self.save_csv_to_db(self.temp_path)\n self.save_filenames_to_db(csv_filenames)\n self.move_temp_files()\n self.package_pcaps()\n","sub_path":"epc_oam_apps_160930/target/worker/tracing/uetrace.py","file_name":"uetrace.py","file_ext":"py","file_size_in_byte":5459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"636411707","text":"from database import query_db, new_table\nfrom graph_calculation import insert_graph\nfrom multiprocessing import Pool, Value\nfrom progressbar import progress\n\ncounter = None\ni_max = None\n\n\ndef init(c, i):\n global counter\n global i_max\n counter = c\n i_max = i\n\n\ndef process_entry(grid_id):\n insert_graph(grid_id)\n\n global counter\n global i_max\n\n with counter.get_lock():\n counter.value += 1\n progress(counter.value, i_max.value)\n return\n\n\ndef parse_graph():\n if __name__ == 'graph':\n grid_ids = [row[0] for row in query_db('SELECT GridID FROM Grid')]\n new_table('Weighted')\n\n counter = Value('i', 0)\n i = Value('i', len(grid_ids))\n p = Pool(4, initializer=init, initargs=(counter, i))\n p.map(process_entry, grid_ids)\n p.close()\n\n return\n","sub_path":"graph/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"540967504","text":"from queue import LifoQueue\n\nclass QueueWithStacks:\n def __init__(self):\n self._s1 = LifoQueue()\n self._s2 = LifoQueue()\n\n def empty(self):\n return self._s1.empty() and self._s2.empty()\n\n def push(self, val:int):\n self._s1.put(val)\n\n def peek(self):\n last_item = None\n while not self._s1.empty():\n last_item = self._s1.get()\n self._s2.put(last_item)\n if last_item: \n self._s2.put(last_item)\n return last_item\n\n def pop(self) -> int:\n self.peek()\n return self._s2.get() \n\nif __name__ == \"__main__\":\n s = QueueWithStacks()\n s.push(3)\n s.push(2)\n s.push(1)\n print(s.peek())\n print(s.pop())\n print(s.pop())\n print(s.empty())\n print(s.pop())\n print(s.empty())","sub_path":"stack/queue_using_2_stacks.py","file_name":"queue_using_2_stacks.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"73991988","text":"import json\ndict_method = {}\ndict_get = {}\ndict_topic = {}\ndict_url = {}\ndict_protocol = {}\n\n\ndef find_unique(sample_dict, param):\n if sample_dict.get(param) == None:\n sample_dict[param]=1\n else:\n sample_dict[param] = sample_dict[param]+1\n\n\nwith open('D:/server_query_logs.log', 'r') as f: \n for i in f: \n \n i = i.split('\"')\n i = i[1]\n i = i.split(' ')\n find_unique(dict_method, i[0])\n \n i = i[1]\n i = i.split('://')\n find_unique(dict_protocol, i[0])\n \n \n i = i[1]\n i = i.split('?') \n find_unique(dict_url, i[0])\n \n if len(i)!=1:\n get_string = i[1]\n get_list = get_string.split('&')\n for j in get_list:\n j=j[:j.find('=')]\n find_unique(dict_get, j)\n \n if get_string.find('topics=')!=-1:\n topic_string = get_string.split('topics=')\n topic_string=topic_string[1]\n if topic_string.find('&')!=-1:\n topic_string = topic_string[:topic_string.find('&')]\n topic_list = topic_string.split('%2C')\n for j in topic_list:\n find_unique(dict_topic, j)\n\n \ndict_logs = {'Protocols': dict_protocol, \n 'Urls': dict_url, \n 'Methods': dict_method, \n 'GET-params': dict_get, \n 'Topics': dict_topic}\n\nwith open('D:/jtest_2.json', 'w') as j: \n json_object = json.dumps(dict_logs, indent=4) \n j.write(json_object) \nwith open('D:/jtest_2.json', 'r') as j: \n my = json.load(j) \n print(my)\n","sub_path":"log_parcer_2.py","file_name":"log_parcer_2.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"514238352","text":"from context import fractal\nfrom fractal.dataloader import Loader\nfrom fractal import utils\nfrom fractal.plotting import plot_image\nfrom fractal.coding import encode_nmf, decode_nmf\nimport copy\nfrom skimage.transform import rescale\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\nfrom PIL import Image\n\nMODE = 'equipartition4'\n\nif __name__ == '__main__':\n ############################################################################\n # load the first face image\n ############################################################################\n images = Loader(\"\")\n range_image = images.get_image(0, scale_factor=1)\n\n # plot it so we know what it looks like\n plot_image(range_image, \n title=f\"Range Image {range_image.shape[0]}x{range_image.shape[1]}\",\n cmap='gray')\n\n ############################################################################\n # divide up the first image into chunks\n ############################################################################\n # domain image is a 50% downsampled range image\n domain_image = images.get_image(0, scale_factor=1/2)\n\n plot_image(domain_image, \n title=f\"Domain Image {domain_image.shape[0]}x{domain_image.shape[1]}\",\n cmap='gray')\n\n # each block is 4x4\n domain_chunks = utils.Partition(domain_image, mode=MODE)\n range_chunks = utils.Partition(range_image, mode=MODE)\n\n ############################################################################\n # encode the range image\n ############################################################################\n codebook = encode_nmf(domain_chunks, range_chunks, verbose=True)\n print(codebook)\n codebook[:, 8:] = 0\n\n # num_weights = len(domain_chunks[0].ravel())\n # X = np.zeros([num_weights, len(domain_chunks)])\n\n # for i in range(len(domain_chunks)):\n # X[:, i] = np.ravel(domain_chunks[i])\n\n # u, s, vh = np.linalg.svd(X)\n\n # print(u.shape, np.diag(s).shape, vh.shape)\n # R = np.dot(np.diag(s), vh[:len(s), :len(s)])\n\n # df = None\n # print(R.shape)\n # for idx, weights in enumerate(codebook):\n # print(f'finished {idx}/{len(codebook)}')\n # contractiveness = np.dot(np.linalg.inv(R), weights.reshape(num_weights,1))\n # contractiveness = np.array([idx] + contractiveness.ravel().tolist())[np.newaxis, :]\n # if df is None:\n # df = pd.DataFrame(contractiveness)\n # else:\n # df = df.append(pd.DataFrame(contractiveness))\n\n # df.to_csv(\"contractiveness.csv\")\n\n facedir = Path(__file__).resolve().parent.parent / \"data\" / \"faces\"\n aaronface = Image.open(list(facedir.glob(\"*.pgm\"))[0])\n aaronface = np.asarray(aaronface.getdata()).reshape(64,64)\n\n # aaronface = images.get_image(0, scale_factor=0.125/2)\n plot_image(aaronface, \n title=f\"Domain Image {aaronface.shape[0]}x{aaronface.shape[1]}\",\n cmap='gray')\n\n domain_chunks = utils.Partition(aaronface, mode=MODE)\n # domain_chunks = utils.Partition(np.zeros([domain_image.shape[0], \n # domain_image.shape[1]]), mode=MODE)\n reconstructed_chunks = decode_nmf(codebook, domain_chunks)\n reconstructed_chunks_1iter = copy.deepcopy(reconstructed_chunks.image)\n \n for i in range(10):\n # TODO try this without anti aliasing\n rec_dim = rescale(reconstructed_chunks.image, 0.5) #, anti_aliasing=True)\n domain_chunks = utils.Partition(rec_dim, mode=MODE)\n reconstructed_chunks = decode_nmf(codebook, domain_chunks)\n plot_image(reconstructed_chunks.image, \n title=f\"Reconstructed Image {i} iteration \\n{reconstructed_chunks.image.shape[0]}x{reconstructed_chunks.image.shape[0]} ({MODE})\", \n cmap='gray')\n print(f\"residual: {i}, {np.sum((range_image - reconstructed_chunks.image)**2)}\")\n \n\n pd.DataFrame(reconstructed_chunks.image).to_csv(\"reconstruction.csv\")\n # reconstructed_chunks_10iter = copy.deepcopy(reconstructed_chunks.image)\n\n\n # for i in range(10):\n # # TODO try this without anti aliasing\n # rec_dim = rescale(reconstructed_chunks.image, 0.5) #, anti_aliasing=True)\n # domain_chunks = utils.Partition(rec_dim, mode=MODE)\n # reconstructed_chunks = decode_svd(codebook, domain_chunks)\n\n # reconstructed_chunks_100iter = copy.deepcopy(reconstructed_chunks.image)\n\n # size = reconstructed_chunks_1iter.shape[0]\n\n # plot the result\n # plot_image(reconstructed_chunks_1iter, \n # title=f\"Reconstructed Image 1 iteration \\n{size}x{size} ({MODE})\", \n # cmap='gray')\n # plot_image(reconstructed_chunks_10iter, \n # title=f\"Reconstructed Image 5 iterations \\n{size}x{size} ({MODE})\",\n # cmap='gray')\n # plot_image(reconstructed_chunks_100iter, \n # title=f\"Reconstructed Image 15 iterations \\n{size}x{size} ({MODE})\",\n # cmap='gray')\n\n\n\n\n\n # print(len(domain_chunks))\n # X = np.zeros([16, 64])\n\n # for i in range(len(domain_chunks)):\n # X[:, i] = np.ravel(domain_chunks[i])\n\n # u, s, vh = np.linalg.svd(X)\n\n # print(u.shape)\n # O = np.zeros([16+3, 16+3]) - 0.5\n\n # i = 0\n # for row in range(0, 16+4, 5):\n # for col in range(0, 16+4, 5):\n # eigenblock = u[:,i]\n # e = eigenblock.reshape(4, 4)\n # print(e)\n # O[row:row+4, col:col+4] = e\n # i += 1\n \n # plt.figure(figsize=(5,5))\n # plt.imshow(O, cmap='gray') #, vmin=0, vmax=255)\n # plt.axis('off')\n # plt.show()\n\n\n\n\n\n\n","sub_path":"bin/main_nmf.py","file_name":"main_nmf.py","file_ext":"py","file_size_in_byte":5577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"123696786","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 29 09:15:35 2019\n\n@author: sveng\n\"\"\"\n\nfrom netCDF4 import Dataset\nimport xarray as xr\nimport numpy as np\nimport pandas as pd\nimport time\nimport glob\nimport os\nimport os.path\n\nfrom zonar_reader import Zonar\nfrom meta_reader import raw2meta_extract\nfrom read_sat import read_sat\nfrom help_fun import compute_c, absorption\n\ndef read_all_zonar(zdir,start=0,end=0):\n\t\"\"\"\n\treads acoustic data from a given folder containing the raw data\n\n\tParameters\n\t----------\n\tzdir : string\n\t\tPath to acoustic raw folder.\n\tstart : integer, optional\n\t\tDive number at which to start reading the files, 0 starts at the first available dive. The default is 0.\n\tend : integer, optional\n\t\tDive number at which to stop reading the files, 0 stops at the last available file. The default is 0.\n\n\tReturns\n\t-------\n\tstart : pandas DataFrame\n\t\tstarting values for the acoustic raw data. Includes non calibration settings.\n\tall_raws : pandas DataFrame\n\t\tAcoustic data in raw counts, by beam, burst, and Ping. Includes timestamp and available meta information.\n\n\t\"\"\"\n\tacfn = glob.glob(zdir + '\\\\B*')\n\tif len(acfn)>0:\n\t\tif end == 0 : end = len(acfn)\n\t\tif end > start:\n\t\t\tall_raws = pd.DataFrame()\n\t\t\tz=Zonar()\n\t\t\t#get starting values for frequencies\n\t\t\tstart = z.read_one_dive(z.read_raw(acfn[1]))[2]\n\t\t\t#z.add_depth()\n\t\tfor a in range(0, end):\n\t\t\tall_raws = all_raws.append(z.read_one_dive(z.read_raw(acfn[a]))[0])\n\t\t\tall_raws['gn']= np.array(start['gn'][all_raws['beam']-1])\n\telse:\n\t\tstart=[];all_raws=[]\n\treturn start, all_raws\n\ndef get_cal(filename, cal0):\n\t\"\"\"\n\tConverts calibraiton information into xarray for nc inclusion\n\n\tParameters\n\t----------\n\tfilename : string\n\t\tOutput nc filename.\n\tall_raws : pandas DataFrame\n\t\tall_raws acoustic data and meta data\n\tcal0 : defaultdict\n\t\tdefaultdict containing the acoustic calibraiton information.\n\n\tReturns\n\t-------\n\tNone.\n\tAdds cal to nc file (filename)\n\n\t\"\"\"\n\tprint(time.ctime() + ': Gathering Calibration data...')\n\tcal=pd.DataFrame()\n\tcal['Frequency'] = cal0['Frequency']\n\tcal['Gain'] = cal0['Gain']\n\tcal['gn'] = cal0['gn']\n\tcal['beam_deg'] = cal0['beam_deg']\n\tcal['beam_rad'] = cal0['beam_rad']\n\tcal['tau'] = cal0['tau']\n\tcal['blank'] = cal0['blank']\n\tcal['dt'] = cal0['dt']\n\tcal['tPing'] = cal0['tPing']\n\tcal['tScan'] = cal0['tScan']\n\tcal['nScan'] = cal0['nScan']\n\tcal['tWait'] = cal0['tWait']\n\tcal['nBin'] = cal0['nBin'] \n\tcal['TSGain'] = cal0['TS_Gain']\n\tcal['CalNoise'] = cal0['CalNoise']\n\tcal['SoureLevel'] = cal0['sl']\n\tcal['alpha'] = cal0['alpha']\n\tcal['c'] = cal0['cspeed']\n\tcal['TS_cal'] = cal0['TS_cal']\n\tcal['TS0'] = cal0['TS0']\n\tcal['Gain_TS'] = cal0['TS_Gain']\n\t\n\tcal_arr = xr.Dataset(cal)\n\n\tcal_arr.Frequency.attrs['units'] = 'kHz'\n\tcal_arr.Frequency.attrs['standard_name'] = 'acoustic_frequency'\n\t\n\tcal_arr.Gain.attrs['Gain'] = 'dB re 1m-1'\n\tcal_arr.Gain.attrs['standard_name'] = 'System_Gain'\n\t\n\tcal_arr.Gain.attrs['Gain_TS'] = 'dB re 1m2'\n\tcal_arr.Gain.attrs['standard_name'] = 'Calibration_Gain'\n\t\n\tcal_arr.tau.attrs['units'] = 's'\n\tcal_arr.tau.attrs['standard_name'] = 'Pulse_Duration'\n\t\n\tcal_arr.beam_deg.attrs['units'] = 'degrees'\n\tcal_arr.beam_deg.attrs['standard_name'] = '3dB_beamwidth_in_degrees'\n\t\n\tcal_arr.beam_rad.attrs['units'] = 'radians'\n\tcal_arr.beam_rad.attrs['standard_name'] = '3dB_beamwidth_in_radians'\n\t\n\tcal_arr.alpha.attrs['standard_name'] = 'attenuation_coefficient_during_calibration'\n\t\n\tcal_arr.dt.attrs['units'] = 'mirco-seconds'\n\tcal_arr.dt.attrs['standard_name'] = 'Period_between_scans'\n\tcal_arr.dt.attrs['description'] = 'Normally dt is 200 us which equals sampling rate of 5 kHz'\n\t\n\tcal_arr.blank.attrs['units'] = 'mirco-seconds'\n\tcal_arr.blank.attrs['standard_name'] = 'Period_between_end-of-transmit_and_the_first_scan'\n\t\n\tcal_arr.tPing.attrs['units'] = 'ms'\n\tcal_arr.tPing.attrs['standard_name'] = 'Ping_interval'\n\t\n\tcal_arr.tScan.attrs['units'] = 'ms'\n\tcal_arr.tScan.attrs['standard_name'] = 'Scan_duration'\n\t\n\tcal_arr.to_netcdf(filename, 'a', group='Zonar/Calibration')\n\n\t\n#environment\ndef get_env(filename,env):\n\t\"\"\"\n\tAdds CTD data to xarray for nc conversion\n\n\tParameters\n\t----------\n\tfilename : string\n\t\tnc output filename.\n\tenv : pandas DataFrame\n\t\tEnvironmental data\n\n\tReturns\n\t-------\n\tNone.\n\tAdds environment to nc file (filename)\n\n\t\"\"\"\n\tprint(time.ctime() + ': Gathering Environment data...')\n\tvar = ['temperature','salinity','fluorescence']\n\txy = ['pressure','Nsurf','Dive_start_time']#,'lon_start','lat_start','lon_end','lat_end']\n\tenv['numtime'] = env.time_of_measure.astype(int)\n\tenv = env.dropna(subset=['fluorescence'])\n\tprint('Processing: time')\n\tmeasuretime = pd.pivot_table(env,values='numtime', index=xy[0], columns=xy[1])\n\tprint('Processing: ' + var[0])\n\ttp = pd.pivot_table(env,values=var[0],index=xy[0], columns=xy[1:])\n\tprint('Processing: ' + var[1])\n\tsp = pd.pivot_table(env,values=var[1],index=xy[0], columns=xy[1])\n\tprint('Processing: ' + var[2])\n\tfp = pd.pivot_table(env,values=var[2],index=xy[0], columns=xy[1])\n\te_arr = xr.Dataset(data_vars = {var[0]:(('Depth','Dive'),np.array(tp)),\n\t\t\t\t\t\t\t\t var[1]:(('Depth','Dive'),np.array(sp)),\n\t\t\t\t\t\t\t\t var[2]:(('Depth','Dive'),np.array(fp)),\n\t\t\t\t\t\t\t\t 'time':(('Depth','Dive'),np.array(measuretime))},\n\t\t\t\t\t\t\t\t coords={'Dive':np.array(tp.columns.get_level_values('Nsurf')),\n\t\t\t\t 'Depth': np.array(tp.index)})\n\t#e_arr['StartTime'] = ('Dive',np.array(tp.columns.get_level_values('Dive_start_time')))\n\te_arr.temperature.attrs['standard_name'] = 'Ambient_Water_Temperature'\n\te_arr.temperature.attrs['units'] = 'Degrees_Celsius'\n\te_arr.time.attrs['standard_name'] = 'time_of_measure'\n\te_arr.salinity.attrs['standard_name'] = 'Ambient_Water_Salinity'\n\te_arr.salinity.attrs['units'] = 'PSU'\n\te_arr.fluorescence.attrs['standard_name'] = 'Ambient_Water_Fluorescence'\n\te_arr.fluorescence.attrs['units'] = 'RFU'\n\te_arr.Depth.attrs['standard_name'] = 'Depth_of_measurement'\n\te_arr.Depth.attrs['units'] = 'dBar'\n\te_arr.Dive.attrs['standard_name'] = 'Dive_number'\n\te_arr.to_netcdf(filename, 'a', group = 'Environment' )\n#gps\ndef get_gps(filename, gps):\n\t\"\"\"\n\tAdds gps data to xarray for nc conversion\n\n\tParameters\n\t----------\n\tfilename : string\n\t\tnc output filename.\n\tgps : pandas DataFrame\n\t\tGPS data\n\n\tReturns\n\t-------\n\tNone.\n\tAdds gps to nc file (filename)\n\n\t\"\"\"\n\tprint(time.ctime() + ': Gathering GPS data...')\n\tgps = gps.reset_index()\n\tgps = gps.set_index('Nsurf_start')\n\tgps_arr = xr.Dataset(data_vars ={'Lon_start':('Dive',gps.lon_start),\n\t\t\t\t\t\t\t\t 'Lon_end':('Dive',gps.lon_end),\n\t\t\t\t\t\t\t\t 'Lat_start':('Dive',gps.lat_start),\n\t\t\t\t\t\t\t\t 'Lat_end':('Dive',gps.lat_end),\n\t\t\t\t\t\t\t\t 'Time_start':('Dive',gps.UTC_time_fix_start),\n\t\t\t\t\t\t\t\t 'Time_end':('Dive',gps.UTC_time_fix_end)})\n\tgps_arr.Lon_start.attrs['standard_name'] = 'Longitude_at_the_start_of_the_dive'\n\tgps_arr.Lon_end.attrs['standard_name'] = 'Longitude_at_the_end_of_the_dive'\n\tgps_arr.Lat_start.attrs['standard_name'] = 'Latitude_at_the_start_of_the_dive'\n\tgps_arr.Lat_end.attrs['standard_name'] = 'Latitude_at_the_end_of_the_dive'\n\tgps_arr.Time_start.attrs['standard_name'] = 'Time_at_the_start_of_the_dive - UTC'\n\tgps_arr.Time_end.attrs['standard_name'] = 'Time_at_the_end_of_the_dive - UTC'\n\tgps_arr.to_netcdf(filename, 'a', group = 'GPS' )\n\t\t\n\n#zooglider grey values\ndef get_zoog(filename, zoog):\n\t\"\"\"\n\tAdds zooglider data to xarray for nc conversion\n\n\tParameters\n\t----------\n\tfilename : string\n\t\tnc output filename.\n\tzoog : pandas DataFrame\n\t\tzoog data\n\n\tReturns\n\t-------\n\tNone.\n\tAdds zoog to nc file (filename)\n\n\t\"\"\"\n\tzoog = zoog.reset_index()\n\tzoog = zoog.set_index('UTC_time','PDT_time')\n\tzoog_arr = xr.Dataset(zoog)\n\tzoog_arr.to_netcdf(filename, 'a', group = 'zoog' )\n\t\n#acoustics\ndef get_ac(filename, all_raws, beam):\n\t\"\"\"\n\tAdds CTD data to xarray for nc conversion\n\n\tParameters\n\t----------\n\tfilename : string\n\t\tnc output filename.\n\tall_raws : pandas DataFrame\n\t\tacoustic data\n\tbeam : integer\n\t\tslect beam for which to get the acoustic data\n\n\tReturns\n\t-------\n\tNone.\n\tAdds acoustic data to nc file (filename)\n\n\t\"\"\"\n\tprint(time.ctime() + ': Gathering Acoustic data for beam: ' + str(beam) )\n\t\n\tsub_raws0 = all_raws[(all_raws.beam == beam) & (all_raws.Ping == 0)]\n\tsub_raws1 = all_raws[(all_raws.beam == beam) & (all_raws.Ping == 1)]\n\tsub_raws2 = all_raws[(all_raws.beam == beam) & (all_raws.Ping == 2)]\n\tsub_raws3 = all_raws[(all_raws.beam == beam) & (all_raws.Ping == 3)]\n\t\n\tac_temp0 = pd.pivot_table(sub_raws0, values='Raw',index = ['nscan'], columns = ['ping_time','nBurst','dive'])\n\tac_temp1 = pd.pivot_table(sub_raws1, values='Raw',index = ['nscan'], columns = ['ping_time','nBurst','dive'])\n\tac_temp2 = pd.pivot_table(sub_raws2, values='Raw',index = ['nscan'], columns = ['ping_time','nBurst','dive'])\n\tac_temp3 = pd.pivot_table(sub_raws3, values='Raw',index = ['nscan'], columns = ['ping_time','nBurst','dive'])\n\t\n\tdz = pd.pivot_table(sub_raws0, values='dz',index = ['nscan'], columns = ['ping_time','nBurst','dive'])\n\n\t\n\tac_arr = xr.Dataset(data_vars={'Ping1':(('nScan','Burst'),np.array(ac_temp0)),\n\t\t\t\t\t\t\t\t'Ping2':(('nScan','Burst'),np.array(ac_temp1)),\n\t\t\t\t\t\t\t\t'Ping3':(('nScan','Burst'),np.array(ac_temp2)),\n\t\t\t\t\t\t\t\t'Ping4':(('nScan','Burst'),np.array(ac_temp3)),\n\t\t\t\t\t\t\t\t'Range':(('nScan','Burst'),np.array(dz))},\n\t\t\t\t\t coords = {'nScan':np.array(ac_temp1.index),\n\t\t\t\t 'Burst': np.array(ac_temp0.columns.get_level_values('nBurst'))})\n\tac_arr['Time'] = ('Burst',np.array(ac_temp0.columns.get_level_values('ping_time')))\n\tac_arr['Dive'] = ('Burst' ,np.array(ac_temp0.columns.get_level_values('dive')))\n\t\n\t\n\t#set meta data\n\tac_arr.Ping1.attrs['units'] = '40 counts per dB re V'\n\tac_arr.Ping1.attrs['standard_name'] = 'Raw_acoustic_data'\n\tac_arr.Ping2.attrs['units'] = '40 counts per dB re V'\n\tac_arr.Ping2.attrs['standard_name'] = 'Raw_acoustic_data'\n\tac_arr.Ping3.attrs['units'] = '40 counts per dB re V'\n\tac_arr.Ping3.attrs['standard_name'] = 'Raw_acoustic_data'\n\tac_arr.Ping4.attrs['units'] = '40 counts per dB re V'\n\tac_arr.Ping4.attrs['standard_name'] = 'Raw_acoustic_data'\n\tac_arr.Time.attrs['standard_name'] = 'Datetime_of_the_burst'\n\tac_arr.Burst.attrs['standard_name'] = 'Burst_number'\n\tac_arr.Range.attrs['standard_name'] = 'Depth'\n\tac_arr.Range.attrs['units'] = 'dBar'\n\tac_arr.nScan.attrs['standard_name'] = 'Sample_number'\n\tac_arr.Burst.attrs['description'] = 'Each burst consists of 4 consequetive pings'\n\t\n\tac_arr.to_netcdf(filename, 'a',group='Zonar/' + 'Beam_' + str(beam))\n\n\treturn(ac_arr)\n\t#return ac_arr\t\n#get sat file\ndef get_sat(filename,header,gps,engineering,profile, zoocam, zonar, misc):\n\t\"\"\"\n\tadd satllite transmitted data to xarray for nc conversion\n\n\tParameters\n\t----------\n\tfilename : string\n\t\tnc filename.\n\theader : TYPE\n\t\tDESCRIPTION.\n\tgps : TYPE\n\t\tDESCRIPTION.\n\tengineering : TYPE\n\t\tDESCRIPTION.\n\tprofile : TYPE\n\t\tDESCRIPTION.\n\tzoocam : TYPE\n\t\tDESCRIPTION.\n\tzonar : TYPE\n\t\tDESCRIPTION.\n\tmisc : TYPE\n\t\tDESCRIPTION.\n\n\tReturns\n\t-------\n\tNone.\n\n\t\"\"\"\n\tprint(time.ctime() + ': Processing sat data...' )\n\t\n\tdef create_var(dic, var, nam=None,vnam='Sat/misc', filename=filename):\n\t\tif nam is None: nam = var\n\t\tfor i in range(len(var)):\n\t\t\tprint(time.ctime() + ': Writing ' + vnam + '/' + nam[i] )\n\t\t\tif len(dic[var[i]]) > 0: \n\t\t\t\txr.Dataset(dic[var[i]]).to_netcdf(filename, 'a',group = vnam + '/' + nam[i])\n\t\n\t#gps\n\tif len(gps)>0: xr.Dataset(gps).to_netcdf(filename, 'a',group = 'Sat/gps')\n\t\n\t\n\t#profile\n\tif len(profile)>0: xr.Dataset(profile['Profile_data']).to_netcdf(filename, 'a',group = 'Sat/profile/Profile_data')\n\tif len(profile)>0: xr.Dataset(pd.DataFrame({'Start':profile['Start_Profile_data']})).to_netcdf(filename, 'a',group = 'Sat/profile/Start')\n\n\t#zoocam\n\t#var = [k for k in zoocam.keys()]\n\tcreate_var(zoocam, ['Zoocam'], vnam='Sat/zoocam')\n\t#zonar\n\tvar = [k for k in zonar.keys()]\n\tcreate_var(zonar, var, vnam='Sat/zonar')\n\t\n\t#engineering\n\tfor k in engineering.keys():\n\t\tprint(k)\n\t\tif len(engineering[k])>0: \n\t\t\tif k == 'Engineering_TS' :\n\t\t\t\teng = engineering[k]\n\t\t\t\tengdf = pd.DataFrame({'sec_since_start' : eng.iloc[:,1:13][eng['Code'] == 'ET00'].values.flatten().astype(int),\n\t\t\t\t\t\t 'pressure_counts' : eng.iloc[:,1:13][eng['Code'] == 'ET01'].values.flatten().astype(int),\n\t\t\t\t\t\t 'heading10deg' : eng.iloc[:,1:13][eng['Code'] == 'ET02'].values.flatten().astype(int),\n\t\t\t\t\t\t 'pitch10deg' : eng.iloc[:,1:13][eng['Code'] == 'ET03'].values.flatten().astype(int),\n\t\t\t\t\t\t 'roll10deg' : eng.iloc[:,1:13][eng['Code'] == 'ET04'].values.flatten().astype(int),\n\t\t\t\t\t\t 'pitchPotCounts' : eng.iloc[:,1:13][eng['Code'] == 'ET05'].values.flatten().astype(int),\n\t\t\t\t\t\t 'rollPotCounts' : eng.iloc[:,1:13][eng['Code'] == 'ET05'].values.flatten().astype(int),\n\t\t\t\t\t\t 'dive#' : np.tile(eng['dive#'][eng['Code'] == 'ET00'],12).flatten().astype(int)})\n\t\t\t\tdd = xr.Dataset(engdf)\n\t\t\t\tdd.set_coords(['dive#', 'sec_since_start']) \n\t\t\t\tdd.to_netcdf(filename, 'a',group = str('Sat/engineering/'+k))\n\t\t\telse:\n\t\t\t\txr.Dataset(engineering[k]).to_netcdf(filename, 'a',group = str('Sat/engineering/'+k))\n\t\n\t#header\n\tvar = [k for k in header.keys()]\n\tvar.remove('argos')\n\tvar.remove('optical_sensor')\n\tcreate_var(header, var, vnam='Sat/header')\n\t\n\t#misc\n\tprint(time.ctime() + ': Writing misc...' )\n\tvar = [k for k in misc.keys()]\n\tvar.remove('Shore_comm')\n\tnam = ['Dive Info', 'Mission ID','Email message','Engineering',\\\n\t\t'Parameters list','Parameter values' ]\n\tcreate_var(misc, var,nam, vnam='Sat/misc')\n\t\n\t\n#create nc file\ndef generate_nc(filename, env, gps, zoog, all_raws, miss, header,gps_sat,\n\t\t\t\tengineering,profile, zoocam, zonar, misc, cal):\n\tprint(time.ctime() + ': Preparing Zonar data...')\n\t### ZONAR Preparation\n\t#get number of pings\n\tall_raws['sample_time'] = pd.to_datetime(all_raws['dive_time']).values.astype(np.int64) + \\\n\t\t( all_raws['dt']/1000 * (all_raws['nscan'] + 1) + all_raws['blank'] + \\\n all_raws['tau'] * 1000 + all_raws['Ping'] * all_raws['tPing'])/1000 * 10**9\n\t#all_raws['sample_time'] = pd.to_datetime(all_raws['real_time'])\n\tall_raws['ping_time'] = pd.to_datetime(all_raws['dive_time']).values.astype(np.int64) + \\\n\t\t(all_raws['Ping'] * all_raws['tPing'])/1000 * 10**9\n\tall_raws['ping_time'] = pd.to_datetime(all_raws['ping_time'])\n\t \n\t#pings = all_raws.Ping.unique()\n\tbeams = all_raws.beam.unique()\n\t\n\tprint(time.ctime() + ': Create netcdf file...')\n\t\n\tdataset = Dataset(filename, 'w')\n\t#add meta data\n\tdataset.description = header['mission'].Description[0]\n\tdataset.history = 'Created ' + time.ctime(time.time())\n\tdataset.serial = header['vehicle'].SN[0]\n\tdataset.Spray_serial = header['mission'].Spray_SN[0]\n\tdataset.EEPROM_Ver = header['vehicle'].EEPROM__Ver[0]\n\tdataset.Deployment_ID = header['mission'].Deployment_ID[0]\n\tdataset.Mission_Name = header['mission'].E_Name[0]\n\tdataset.argos_ID = header['argos'].Argos_ID[0]\n\t\n\tdataset.mission = miss\n\t\n\tdataset.close()\n\t\n\t#add environment\n\tget_env(filename, env)\n\t#add GPS\n\tget_gps(filename, gps)\n\t#add zoog\n\tget_zoog(filename, zoog)\n\t#add cal\n\tget_cal(filename, cal)\n\t#add sat\n\tget_sat(filename, header,gps,engineering,profile, zoocam, zonar, misc)\n\t\n\t#add raw acoustics\n\tfor beam in beams:\n\t\t_ = get_ac(filename, all_raws,beam)\n\t\t\n\t\t\n\ndef get_cal_val(fn, date):\n\tcaldf = pd.read_table(fn, sep='\\t{1,}',comment='#',header=None, \\\n\t\t\t\t\t engine='python')\n\tcaldf.columns = pd.read_table(fn, sep='\\s{2,}',skiprows=7, nrows=1,\\\n\t\t\t\t\t\t\t header=None, engine='python').values[0]\n\tcaldf = caldf.set_index(pd.to_datetime(caldf['#monYr'], format='%b%y'))\n\treturn caldf.iloc[caldf.index.get_loc(date,method='nearest')]\n\n\ndef get_missions(mdir):\n\treturn [i for i in next(os.walk(mdir))[1] if '20' in i]\n\ndef missions_to_nc(mdir, missions, outdir='', acdir='zonar_flash',\n\t\t\t\t raw2dir = 'raw2',satdir = 'in-situ_sat_file',\n\t\t\t\t d_start=0,d_end=0, TS0=None, Scal=0, Tcal=20, dcal=5, \n\t\t\t\t Gain = [54,54], calfn=None, force=False):\n\tfor miss in missions:\n\t\tprint(time.ctime() + ': Processing ' + miss )\n\t\toutfn = outdir + miss + '.nc'\n\t\tif os.path.isfile(outfn) and force==False:\n\t\t\tprint('NetCDF for ', miss,' already exists...skipping...')\n\t\t\tcontinue\n\t\telse:\n\t\t\t#get raw_dirs\n\t\t\trdir = [i for i in next(os.walk(mdir+miss))[1]if 'raw_data' in i]\n\t\t\tif len(rdir) > 0:\n\t\t\t\traw_dir = mdir + miss + '\\\\' + rdir [0] \n\t\t\telse:\n\t\t\t\tprint(time.ctime() + ': No RAW DATA FOLDER found for ' + \\\n\t\t miss + ' ...skipping mission...')\n\t\t\t\tcontinue\n\t\t\t#get satellite data\n\t\t\tsat_dir = mdir + miss + '\\\\' + satdir\n\t\t\tsatfn = glob.glob(sat_dir +'\\\\*.sat')\n\t\t\tif len(satfn)>0:\n\t\t\t\theader, gps_sat,engineering, profile, zoocam, zonar,\\\n\t\t\t\t\t misc = read_sat(satfn[0])\n\t\t\telse:\n\t\t\t\tprint(time.ctime() + ': No SAT file found for ' + miss + \\\n\t\t ' ...skipping mission...')\n\t\t\t\tcontinue\n\t\t\t\n\t\t\t#get acoustics zonar data\n\t\t\tac_dir = raw_dir + '\\\\' + acdir + '\\\\'\n\t\t\tstart, all_raws = read_all_zonar(ac_dir,d_start, d_end)\n\t\t\tif len(all_raws) == 0:\n\t\t\t\tprint(time.ctime() + ': No ACOUSTIC DIVE DATA found for ' + \\\n\t\t miss + ' ...skipping mission...')\n\t\t\t\tcontinue\n\t\t\t#get acoustic calibration data\n\t\t\t# get the cal information from file if available\n\t\t\tif calfn is not None:\n\t\t\t\tprint(time.ctime() + ': Reading acoustic cal values from file...')\n\t\t\t\tcv = get_cal_val(calfn, pd.to_datetime(all_raws.start_time.values[0]))\n\t\t\t\tNL = cv[cv.index.isin(['N[200]','N[1000]'])].values\n\t\t\t\tTS = cv[cv.index.isin(['T[200]','T[1000]'])].values\n\t\t\t\tprint('NL = ' + str(NL) + ' TS = ' + str(TS))\n\t\t\t\tSpray = cv.Spray\n\t\t\t\tznr = cv.Zonar\n\t\t\t\tmonYr = cv[0]\n\t\t\telse:\n\t\t\t\tctemp = Zonar().init_cal()\n\t\t\t\tNL = ctemp['CalNoise']\n\t\t\t\tTS = [87, 82]\n\t\t\t\tSpray = header['vehicle']['SN'][0]\n\t\t\t\tznr = 'NA'\n\t\t\t\tmonYr = pd.to_datetime(all_raws.start_time.values[0]).strftime('%b%y')\n\t\t\t\t\n\t\t\t#update calibration values\n\t\t\tprint(time.ctime() + ': Updating calibration data')\n\t\t\t#TS0 - the theoretical TS of the used sphere\n\t\t\tif TS0 is None: TS0 = [-53.47, -50.92]\n\t\t\tif Gain is None: Gain = [54, 54]\n\t\t\t# get the source level approximation\n\t\t\talpha = np.array([absorption(f=f, S=np.array(Scal), \n\t\t\t\t\t\t\t\tT=np.array(Tcal), D=np.array([dcal]))/1000 \\\n\t\t\t\t\t for f in start['freq']]).flatten()\n\t\t\tc = compute_c(dcal,Scal,Tcal)\n\t\t\t\n\t\t\t\n\t\t\tcal = Zonar().init_cal(CalNoise = NL,\n\t\t\t\t\t\t Gain = Gain,\n\t\t\t\t\t\t TS_cal = TS,\n\t\t\t\t\t\t TS0 = TS0,\n\t\t\t\t\t\t alpha = alpha,\n\t\t\t\t\t\t cspeed = c,\n\t\t\t\t\t\t Spray = Spray,\n\t\t\t\t\t\t Zonar = znr,\n\t\t\t\t\t\t monYr = monYr,\n\t\t\t\t\t\t tau = start.pulse.values,\n\t\t\t\t\t\t blank = start.blank.values,\n\t\t\t\t\t\t dt = start.dt.values,\n\t\t\t\t\t\t tScan = start.tScan.values,\n\t\t\t\t\t\t tPing = start.tPing.values,\n\t\t\t\t\t\t nScan = start.nScan.values,\n\t\t\t\t\t\t tWait = start.tWait.values,\n\t\t\t\t\t\t nBin = start.nBin.values,\n\t\t\t\t\t\t gn = start.gn.values,\n\t\t\t\t\t\t Frequency = start.freq.values)\n\t\t\tdel cal['Noise']\n\t\t\t# SL = Source level, 40log10(z) + 2 alpha z = 2 x Transmission \n\t\t\t#Loss, G0 = system gain\n\t\t\tSL = np.array(NL)/cal['gn'] + np.array(cal['Gain']) +\\\n\t\t\t\t 40 * np.log10(dcal)+ 2 * alpha * dcal \n\t\t\tcal['sl'] = SL\n\t\t\t#get expected TS in counts\n\t\t\tTS_c = TS0 + SL - 40*np.log10(dcal) - 2 * alpha * dcal\n\t\t\t#get the TS cal Gain value\n\t\t\tGcal = TS_c - np.array(TS) #dB re V\n\t\t\tcal['TS_Gain'] = Gcal\n\t\t\t\t\n\t\t\t#get physical data\n\t\t\traw2_dir = raw_dir + '\\\\' + raw2dir\n\t\t\trawfn = glob.glob(raw2_dir + '\\\\*.raw2')\n\t\t\tif len(rawfn) > 0:\n\t\t\t\tenv, gps, zoog = raw2meta_extract(rawfn[0])\n\t\t\telse:\n\t\t\t\tprint(time.ctime() + ': No RAW2 file found for ' + \n\t\t miss + ' ...skipping mission...')\n\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t#generate netCDF file\n\t\t\tgenerate_nc(filename=outfn,env=env, gps=gps, zoog=zoog, \n\t\t\t all_raws=all_raws, miss=miss,header=header,gps_sat=gps_sat,\n\t\t\t engineering=engineering,profile=profile, zoocam=zoocam, \n\t\t\t zonar=zonar, misc=misc,cal=cal)\n\t\t\t\ndef get_AllRoiCounts(rdir='Z:\\\\Zooglider_end_to_end_results', pat = '/20*/',\n\t\t\t\t\t outdir=''):\n\t\"\"\"\n\tGet all the ROI counts from the Zoocam data\n\n\tParameters\n\t----------\n\trdir : string, optional\n\t\tPath to the folder containing the Zooglider data. This can be a parent\\\n\t\t\t folder as the pattern matching will be recursive. The default is \\\n\t\t\t\t 'Z:\\\\Zooglider_end_to_end_results'.\n\tpat : string, optional\n\t\tRegex Pattern to be matched. The default is '/20*/'.\n\toutdir : string, optional\n\t\tFolder to which the csv files should be written. The default is ''.\n\n\tReturns\n\t-------\n\tcdat : TYPE\n\t\tDESCRIPTION.\n\n\t\"\"\"\n\tldirs = glob.glob(rdir + pat)\n\tfor ldir in ldirs:\n\t\tmiss = os.path.basename(os.path.normpath(ldir))\n\t\tprint(time.ctime() + ': Processing ' + miss )\n\t\tcdir = glob.glob(ldir + '/*_converted_to_csv')[0] + '\\\\Physical_data_at_Interpolated_Depths\\\\'\n\t\tint_fn = sorted(glob.glob(cdir + '*_interpolated_data.csv'))\n\t\tmeas_fn = sorted(glob.glob(cdir + '*_roi_counts.csv'))\n\t\tif len(meas_fn)>0:\n\t\t\tcdat = pd.DataFrame()\n\t\t\tfor i in range(len(int_fn)):\n\t\t\t\tprint(time.ctime() + ': ' + str(i+1) + ' of ' + str(len(int_fn)) + ' - ' + str(np.round((i+1)/len(int_fn) * 100)) + '% done')\n\t\t\t\ttmp = pd.read_csv(int_fn[i])\n\t\t\t\ttmp2 = pd.read_csv(meas_fn[i])\n\t\t\t\ttmp2['filename'] = tmp2['Unnamed: 0'].str.split('.png', n=1,expand=True)[0]\n\t\t\t\ttmp2.drop(columns=['Unnamed: 0'], inplace=True)\n\t\t\t\tcdat = cdat.append(tmp.merge(tmp2))\n\t\t\t\tcdat.loc[:,'mission'] = miss\n\t\t\t\toutfn = outdir + miss + '.csv.gz'\n\t\t\tprint(time.ctime() + ': Writing ' + outfn)\n\t\t\tcdat.to_csv(outfn, compression = 'gzip')\n\t\telse:\n\t\t\tprint(time.ctime() + ': No converted_to_csv folder found for ' + ldir) \n\t\t\tcontinue\n\treturn cdat","sub_path":"zonarPy/obs/obszonar2nc.py","file_name":"obszonar2nc.py","file_ext":"py","file_size_in_byte":21177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"69216126","text":"'''\np[0] = ?\ns[1:], p[1:]\np[0] = *\ns, s[1:],s[2:].. , p[1:]\np[0] = 其他\ns[1:], p[1:]\n\n优化,合并多个连续*\n\n\n用数组dp[i] 表示s[i]是否能匹配p的一段(当前考察到的这段)\ns abcd\np *a*b\n\ndp [1 1 1 1 1]\np = '*'\ns = [1 1 1 1 1]\np = 'a'\ns = [1 1 0 0 0]\np = '*'\ns = [1 1 1 1 1] # 这里 dp[2]=1, 表示这部分和p match,因为s[3] == p, 所以dp[3] = 1\np = 'b'\ns = [1 0 0 0 1]\n\n'''\nfrom timing import *\n\n\nclass Solution:\n @timeit\n def isMatch(self, s, p):\n \"\"\"\n :type s: str\n :type p: str\n :rtype: bool\n \"\"\"\n dp = [False for i in range(len(s)+1)]\n dp[0] = True\n for c in p:\n if c == '*':\n # 找到第一个True,把后面置为True\n for i in range(len(s)+1):\n if dp[i]:\n for j in range(i+1, len(s)+1):\n dp[j] = True\n break\n else:\n for i in range(len(s), 0, -1):\n # 如果i-1位置为True,而且i位置匹配字母或者问号。\n dp[i] = (dp[i-1] and (s[i-1]==c or c=='?'))\n dp[0] = False\n return dp[-1]\n\n\n\n\n\n\n\nclass Solution2:\n @timeit\n def test(self, s, p):\n return self.isMatch(s, p)\n def isMatch(self, s, p):\n \"\"\"\n :type s: str\n :type p: str\n :rtype: bool\n \"\"\"\n newP = \"\"\n temp = ''\n for c in p:\n if temp == '*' and c=='*':\n continue\n else:\n newP += c\n temp = c\n p = newP\n\n\n # 考虑空值情况\n if p==\"\":\n if s==\"\":\n return True\n else:\n return False\n if s==\"\":\n if p==\"*\":\n return True\n elif p[0]==\"*\":\n return self.isMatch(\"\", p[1:])\n else:\n return False\n if p[0] == '?':\n return self.isMatch(s[1:], p[1:])\n elif p[0] == '*':\n # 枚举整个s到空\n for i in range(len(s)):\n if self.isMatch(s[i:], p[1:]):\n return True\n if self.isMatch(\"\", p[1:]):\n return True\n return False\n else:\n if p[0] == s[0]:\n return self.isMatch(s[1:], p[1:])\n else:\n return False\n\nfoo = Solution2().test\nfoo = Solution().isMatch\nassert(foo(\"aa\", \"a\")== False)\nassert(foo(\"aa\", \"*\")== True)\nassert(foo(\"cb\", \"?a\")== False)\nassert(foo(\"adceb\", \"*a*b\")== True)\nassert(foo(\"acdcb\", \"a*c?b\")== False)\nassert(foo(\"ho\", \"ho**\")== True)\nfoo(\"aaabbbaabaaaaababaabaaabbabbbbbbbbaabababbabbbaaaaba\", \"a*******b\")\nfoo(\"bbaaaabaaaaabbabbabbabbababaabababaabbabaaabbaababababbabaabbabbbbbbaaaaaabaabbbbbabbbbabbabababaaaaa\", \"******aa*bbb*aa*a*bb*ab***bbba*a*babaab*b*aa*a****\")\n# 3.45秒\n","sub_path":"044_wildcard_matching.py","file_name":"044_wildcard_matching.py","file_ext":"py","file_size_in_byte":2944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"566401440","text":"import cv2\nimport time\nimport numpy as np\nimport os\nimport socket\n\nclass obj:\n def __init__(self, obj_name, possible_states, ROIs, primary_cascade, secondary_cascade):\n self.obj_name = obj_name\n self.possible_states = possible_states\n self.rois = ROIs\n self.prim = cv2.CascadeClassifier(primary_cascade)\n self.sec = cv2.CascadeClassifier(secondary_cascade)\n self.base_img = []\n self.means_array=[]\n \n def find_feature(self, img_color):\n img_gray = cv2.cvtColor(img_color, cv2.COLOR_BGR2GRAY)\n faces = self.prim.detectMultiScale(img_gray, 1.3, 5)\n if(len(faces)>0):\n fx,fy,fw,fh = faces[0]\n face_color = img_color[fy:fy+fw, fx:fx+fh]\n face_gray = img_gray[fy:fy+fw, fx:fx+fh]\n eyes = self.sec.detectMultiScale(face_gray)\n if(len(eyes)>0):\n ex,ey,ew,eh = eyes[0]\n return face_color[ey:ey+ew, ex:ex+eh]\n else:\n return None\n else:\n return None\n \n def initialize_means_roi(self):\n for state_imgs in self.base_img:\n roi_means = []\n fin_means = []\n for state_img in state_imgs:\n width = len(state_img)\n height = len(state_img[0])\n roi_mean_array =[]\n for roi in self.rois:\n x1 = int(width*roi[0])\n x2 = int(width*roi[1])\n y1 = int(height*roi[2])\n y2 = int(height*roi[3])\n roi_mean_array.extend([state_img[:,:,0][x1:x2,y1:y2].mean()])#, state_img[:,:,1][x1:x2,y1:y2].mean(), state_img[:,:,2][x1:x2,y1:y2].mean()])\n roi_means.append(roi_mean_array)\n tp = [list(x) for x in zip(*roi_means)]\n for arr in tp:\n fin_means.append(sum(arr)/len(arr))\n self.means_array.append(fin_means)\n self.means_array_transposed = [list(x) for x in zip(*self.means_array)]\n \n def min_dif(self, val, arr):\n darr = list(map((lambda x: abs(x-val)), arr))\n return darr.index(min(darr))\n \n def array_diff(self, arr1, arr2):\n toret = 0\n for a1, a2 in zip(arr1, arr2):\n toret = toret + abs(a1-a2) \n return toret\n \n def detect1(self, img):\n fet = self.find_feature(img)\n if(type(fet)!=type(None)):\n width = len(fet)\n height = len(fet[0])\n roi_mean_array =[]\n state_arr=[]\n for roi in self.rois:\n x1 = int(width*roi[0])\n x2 = int(width*roi[1])\n y1 = int(height*roi[2])\n y2 = int(height*roi[3])\n roi_mean_array.extend([fet[:,:,0][x1:x2,y1:y2].mean()])#, fet[:,:,1][x1:x2,y1:y2].mean(), fet[:,:,2][x1:x2,y1:y2].mean()])\n diffs = []\n for base_state_roi_mean in self.means_array:\n diffs.append(self.array_diff(base_state_roi_mean, roi_mean_array))\n return (\"Status\", self.possible_states[diffs.index(min(diffs))])\n else:\n return (\"Error\", \"Object Not Found\")\n \n def detect2(self, img):\n fet = self.find_feature(img)\n if(type(fet)!=type(None)):\n width = len(fet)\n height = len(fet[0])\n roi_mean_array =[]\n state_arr=[]\n for roi in self.rois:\n x1 = int(width*roi[0])\n x2 = int(width*roi[1])\n y1 = int(height*roi[2])\n y2 = int(height*roi[3])\n roi_mean_array.extend([fet[:,:,0][x1:x2,y1:y2].mean()])#, fet[:,:,1][x1:x2,y1:y2].mean(), fet[:,:,2][x1:x2,y1:y2].mean()])\n for mean, base_state_roi_mean in zip(roi_mean_array, self.means_array_transposed):\n ind = self.min_dif(mean, base_state_roi_mean)\n state_arr.append(self.possible_states[ind])\n return (\"Status\", max(set(state_arr), key=state_arr.count))\n else:\n return (\"Error\", \"Object Not Found\")\n \n def initialize(self, comm_method):\n cap = cv2.VideoCapture(0)\n for state in self.possible_states:\n not_init = 0\n comm_method(\"Please keep \"+self.obj_name+\" in \"+state+\" state for next 5 seconds.\")\n time.sleep(2)\n bas_imgs = []\n while(not_init<100):\n ret, img = cap.read()\n fet = self.find_feature(img)\n if(type(fet)!=type(None)):\n bas_imgs.append(fet)\n not_init=not_init+1\n self.base_img.append(bas_imgs)\n comm_method(state+\" initizalized.\")\n time.sleep(2)\n return cap\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"372102662","text":"#!/usr/bin/env python\n# a bar plot with errorbars\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nN = 5\n\n\nind = np.arange(N) # the x locations for the groups\nwidth = 0.35 # the width of the bars\n\nfig, ax = plt.subplots()\n\nwomenMeans = (25, 32, 34, 20, 25)\nwomenStd = (0, 0, 0, 0, 0)\nrects = ax.bar(ind+width, womenMeans, width, color='y')\n\n# add some text for labels, title and axes ticks\nax.set_ylabel('Scores')\nax.set_title('Scores by group and gender')\nax.set_xticks(ind+width)\nax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5') )\n\nplt.show()\nplt.close()\n","sub_path":"bargraphdemo.py","file_name":"bargraphdemo.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"504059938","text":"# -*- coding: utf-8 -*-\r\nimport xlrd\r\nimport xlwt\r\nfrom datetime import date, datetime,timedelta\r\nimport pandas as pd\r\nfrom pandas import DataFrame\r\nimport sqlalchemy\r\nimport seaborn as sns\r\nfrom scipy import stats\r\n\r\nimport logging\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.dates as mdates\r\nfrom pylab import mpl\r\nimport matplotlib.font_manager as fm\r\nfonts = fm.FontProperties(fname='C:\\Windows\\Fonts\\STXINWEI.TTF',size=16) # 设置字体\r\n# # sns.set(font=fonts.get_name())\r\nplt.rcParams['font.sans-serif'] = ['SimHei'] # 中文字体设置-黑体\r\nplt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题\r\n# sns.set(font='SimHei')\r\n\r\n\r\n\r\ndef str2float(str):\r\n return float(str)\r\n\r\ndef testFit():\r\n pass\r\n # kde = stats.gaussian_kde()\r\n\r\n# 打印日志\r\ndef printLog(str):\r\n # 创建Logger\r\n logger = logging.getLogger(\"logToScreen\")\r\n logger.setLevel(logging.DEBUG)\r\n\r\n # 终端Handler\r\n consoleHandler = logging.StreamHandler()\r\n consoleHandler.setLevel(logging.DEBUG)\r\n\r\n # Formatter\r\n formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')\r\n consoleHandler.setFormatter(formatter)\r\n\r\n # 添加到Logger中\r\n logger.addHandler(consoleHandler)\r\n\r\n # 打印日志\r\n # logger.debug('debug 信息')\r\n # logger.info('info 信息')\r\n logger.warning('警告:文件%s中存在空值,请稍后处理:' % str)\r\n # logger.error('error 信息')\r\n # logger.critical('critical 信息')\r\n # logger.debug('%s 是自定义信息' % '这些东西')\r\n\r\n# 去除数据指定列中的异常值\r\ndef RemoveErrVal(data,keyword,errValue):\r\n for key in keyword:\r\n for err in errValue:\r\n # 去除异常值\r\n try:\r\n data = data[(data[key] != err)]\r\n except TypeError as e:\r\n print(\"该组数据可能没有字符串类型,默认float:\",e)\r\n print(data.dtypes)\r\n continue\r\n return data\r\n\r\n# 查看数据集是否存在数据为NULL的列\r\ndef checkIsNull(df,str):\r\n # pass\r\n allColumns = df.isnull().any()\r\n for i in range(len(allColumns)):\r\n if allColumns[i]:\r\n printLog(str)\r\n return\r\n\r\n\r\n# 自定义matplotlib画图func\r\ndef print_plot(data, keyword,title='', xlab='', ylab='',bins=10):\r\n global fonts\r\n fig = plt.figure()\r\n ax = fig.add_subplot(111)\r\n ax.hist(data[keyword], bins=50)\r\n plt.title(title, fontproperties=fonts)\r\n plt.xlabel(xlab, fontproperties=fonts)\r\n plt.ylabel(ylab, fontproperties=fonts)\r\n plt.show()\r\n\r\n# 使用seaborn的distplot功能绘制同类数据的概率密度分布对比情况\r\ndef print_plot_sns_compare(data,keyword, title='', xlab='', ylab='',bins=[]):\r\n sns.set(palette=\"muted\", color_codes=True,font='SimHei')\r\n length = len(data)\r\n f, axes = plt.subplots(1, length, figsize=(21, 7))\r\n for i in range(length):\r\n sns.distplot(data[i][keyword[i]], bins=bins[i], kde_kws={\"shade\": True, \"color\":\"g\"}, hist_kws={\"color\":\"b\"}#,fit=stats.gausshyper\r\n , ax=axes[i])\r\n plt.show()\r\n\r\n \r\n# 使用seaborn的distplot功能绘制三组不同类别数据分布的概率密度曲线、直方图和fit拟合情况\r\ndef print_plot_sns_2(data,keyword,dataAnother='',keywordAnother=[], isTrain=True,title='', xlab='', ylab='',bins=10,binsAnother=10):\r\n sns.set(palette=\"muted\", color_codes=True,font='SimHei')\r\n # length = len(keyword)\r\n # if keywordAnother is not None:\r\n # length = length+1\r\n if isTrain:\r\n row = 1\r\n else:\r\n row = 2\r\n f, axes = plt.subplots(row, 3, figsize=(21, 7))\r\n if isTrain:\r\n sns.distplot(data[keyword[0]], bins=bins, isTrain=isTrain, kde_kws={\"shade\": True, \"color\":\"g\"}, hist_kws={\"color\":\"b\"},fit=stats.lognorm\r\n , ax=axes[0])\r\n sns.distplot(data[keyword[1]], bins=15, isTrain=isTrain, kde_kws={\"shade\": True, \"color\": \"g\"}, hist_kws={\"color\": \"b\"},fit=stats.dgaussian\r\n , ax=axes[1])\r\n if keywordAnother is not None:\r\n sns.distplot(dataAnother[keywordAnother[0]], bins=binsAnother, isTrain=isTrain, kde_kws={\"shade\": True, \"color\": \"g\"},fit=stats.lognorm\r\n , hist_kws={\"color\": \"b\"}, ax=axes[2])\r\n else:\r\n sns.distplot(dataAnother[keywordAnother[0]], bins=binsAnother, isTrain=isTrain,\r\n kde_kws={\"shade\": True, \"color\": \"g\", \"label\": \"johnsonsb\"}, hist_kws={\"color\": \"b\"}, fit=stats.johnsonsb,\r\n kernelParam=(1.4325670652903717, 1.0348251160259663, 17.211478681707643, 112.41785769036785),\r\n ax=axes[0,0])\r\n sns.distplot(dataAnother[keywordAnother[0]], bins=binsAnother, isTrain=isTrain,\r\n kde_kws={\"shade\": True, \"color\": \"g\", \"label\": \"johnsonsu\"}, hist_kws={\"color\": \"b\"}, fit=stats.johnsonsu,\r\n kernelParam=(-7.4499423241262814, 1.8585724577861038, 10.957566210490761, 1.0402938745385364),\r\n ax=axes[0,1])\r\n # sns.distplot(dataAnother[keywordAnother[0]], bins=binsAnother, isTrain=isTrain,\r\n # kde_kws={\"shade\": True, \"color\": \"g\", \"label\": \"rice\"}, hist_kws={\"color\": \"b\"}, fit=stats.rice,\r\n # kernelParam=(0.00030771725667398447, 14.5717118769265, 24.029115689191158),\r\n # ax=axes[0,2])\r\n # sns.distplot(dataAnother[keywordAnother[0]], bins=binsAnother, isTrain=isTrain,\r\n # kde_kws={\"shade\": True, \"color\": \"g\", \"label\": \"invgamma\"}, hist_kws={\"color\": \"b\"}, fit=stats.invgamma,\r\n # kernelParam=(7.8329924522526717, -1.7298211131927927, 312.80357615655112), ax=axes[1,0])\r\n # sns.distplot(dataAnother[keywordAnother[0]], bins=binsAnother, isTrain=isTrain,\r\n # kde_kws={\"shade\": True, \"color\": \"g\", \"label\": \"invgauss\"}, hist_kws={\"color\": \"b\"},\r\n # fit=stats.invgauss,\r\n # kernelParam=(0.30642986141359135, 10.136428671414453, 110.07424236342952),\r\n # ax=axes[1,1])\r\n # sns.distplot(dataAnother[keywordAnother[0]], bins=binsAnother, isTrain=isTrain,\r\n # kde_kws={\"shade\": True, \"color\": \"g\", \"label\": \"invweibull\"}, hist_kws={\"color\": \"b\"},\r\n # fit=stats.invweibull,\r\n # kernelParam=(11.892095445918237, -115.11585487508093, 150.56184348200534),\r\n # ax=axes[1,2])\r\n\r\n\r\n # if keywordAnother is not None:\r\n # sns.distplot(dataAnother[keywordAnother[0]], bins=binsAnother, isTrain=isTrain, kde_kws={\"shade\": True, \"color\": \"g\"}, hist_kws={\"color\": \"b\"},#fit=stats.lognorm,\r\n # kernelParam=(0.53581011274768198, 10.824696055450907, 28.800524079608266), ax=axes[2])\r\n\r\n plt.show()\r\n\r\n# 使用seaborn的distplot功能绘制两组不同类别数据分布的概率密度曲线、直方图分布情况\r\ndef print_plot_sns(data, keyword, title='', xlab='', ylab='', bins=10):\r\n sns.set(palette=\"muted\", color_codes=True)\r\n f, axes = plt.subplots(1, 2, figsize=(10, 10))\r\n sns.distplot(data[keyword[0]], bins=bins, kde_kws={\"shade\": True, \"color\": \"g\"}, hist_kws={\"color\": \"b\"},\r\n ax=axes[0])\r\n sns.distplot(data[keyword[1]], bins=30, kde_kws={\"shade\": True, \"color\": \"g\"}, hist_kws={\"color\": \"b\"},\r\n ax=axes[1])\r\n plt.show()\r\n\r\n\r\ndef read_excel():\r\n # 打开文件\r\n workbook = xlrd.open_workbook(r'F:\\轮胎项目\\导出数据\\接口2数据2列表_203_6.15-6.30尾\\接口2数据2列表_203_6.15-6.16.xlsx')\r\n # 获取所有sheet\r\n print(workbook.sheet_names()) # [u'sheet1', u'sheet2']\r\n sheet2_name = workbook.sheet_names()[0]\r\n\r\n # 根据sheet索引或者名称获取sheet内容\r\n sheet = workbook.sheet_by_index(0)\r\n\r\n # sheet的名称,行数,列数\r\n print(sheet.name, sheet.nrows, sheet.ncols,type(sheet))\r\n\r\n # 获取整行和整列的值(数组)\r\n rows = sheet.row_values(3) # 获取第四行内容\r\n cols = sheet.col_values(11) # 获取第三列内容\r\n cols1 = sheet.col_values(10) # 获取第三列内容\r\n cols25 = sheet.col_values(25) # 获取第三列内容\r\n\r\n # print(cols.ctype,cols)\r\n # for index in range(len(rows)):\r\n # print(rows[index],type(rows[index]))\r\n print(rows)\r\n print(cols,'\\n',type(cols[0]))\r\n\r\n # # 将字符串型的列表元素转换成数字类型列表(float、int等)\r\n # cols = list(map(eval,cols[1:]))\r\n # cols1 = list(map(eval,cols1[1:]))\r\n # cols25 = list(map(eval,cols25[1:]))\r\n # print(cols,'\\n',type(cols[0]))\r\n # print(cols1,'\\n',type(cols1),type(cols1[0]),'\\n',sorted(cols1))\r\n # print(cols25, '\\n', type(cols25), type(cols25[0]), '\\n', sorted(cols25))\r\n\r\n # # 获取单元格内容\r\n # print(sheet.cell(1, 0).value)\r\n # print(sheet.cell_value(1, 0))\r\n # print(sheet.row(1)[0].value)\r\n #\r\n # # 获取单元格内容的数据类型\r\n # # ctype: 0 empty, 1 string, 2 number, 3 date, 4 boolean, 5 error\r\n # print(sheet.cell(1, 0).ctype)\r\n\r\n\r\ndef read_excel_wtpandas():\r\n # pass\r\n oraengine = sqlalchemy.create_engine('oracle://TireProject:jl123456@localhost:1521/orcl')\r\n\r\n\r\n # # for 接口2数据2列表_203\r\n # file_name = ['接口2数据2列表_203_6.15-6.16.xlsx', '接口2数据2列表_203_6.16-6.17.xlsx', '接口2数据2列表_203_6.17-6.18.xlsx',\r\n # '接口2数据2列表_203_6.18-6.20.xlsx', '接口2数据2列表_203_6.20-6.21.xlsx', '接口2数据2列表_203_6.21-6.23.xlsx',\r\n # '接口2数据2列表_203_6.23-6.24.xlsx', '接口2数据2列表_203_6.27-6.28.xlsx', '接口2数据2列表_203_6.28-6.29.xlsx',\r\n # '接口2数据2列表_203_6.29-6.30.xlsx']\r\n # file_name = ['接口2数据2列表_203_5.25-6.5.xlsx', '接口2数据2列表_203_6.5-6.9.xlsx', '接口2数据2列表_203_6.9-6.15.xlsx']\r\n\r\n\r\n # for 接口2数据2列表_207\r\n # file_name = ['接口2数据2列表_207_6.20-6.21.xlsx', '接口2数据2列表_207_6.21-6.22.xlsx', '接口2数据2列表_207_6.22-6.23.xlsx',\r\n # '接口2数据2列表_207_6.23-6.24.xlsx', '接口2数据2列表_207_6.24-6.25.xlsx', '接口2数据2列表_207_6.25-6.26.xlsx',\r\n # '接口2数据2列表_207_6.26-6.27.xlsx', '接口2数据2列表_207_6.27-6.28.xlsx', '接口2数据2列表_207_6.28-6.29.xlsx',\r\n # '接口2数据2列表_207_6.29-6.30尾.xlsx']\r\n # file_name = ['接口2数据2列表_207_5.15-6.15.xlsx']\r\n\r\n\r\n # # for 接口2数据2列表_208\r\n # file_name = ['接口2数据2列表_208_6.15-6.16.xlsx', '接口2数据2列表_208_6.16-6.17.xlsx', '接口2数据2列表_208_6.17-6.18.xlsx',\r\n # '接口2数据2列表_208_6.18-6.19.xlsx', '接口2数据2列表_208_6.19-6.20.xlsx', '接口2数据2列表_208_6.20-6.21.xlsx',\r\n # '接口2数据2列表_208_6.23-6.24.xlsx', '接口2数据2列表_208_6.24-6.25.xlsx', '接口2数据2列表_208_6.25-6.26.xlsx',\r\n # '接口2数据2列表_208_6.26-6.27.xlsx', '接口2数据2列表_208_6.27-6.28.xlsx', '接口2数据2列表_208_6.28-6.29.xlsx',\r\n # '接口2数据2列表_208_6.29-6.30.xlsx', '接口2数据2列表_208_6.30-6.30尾.xlsx']\r\n # file_name = ['接口2数据2列表_208_5.15-6.1.xlsx','接口2数据2列表_208_6.1-6.5.xlsx','接口2数据2列表_208_6.5-6.15.xlsx']\r\n\r\n # # for 接口2数据2列表_测试集\r\n # file_name = ['接口2数据2列表_203_7.1-7.12.xlsx', '接口2数据2列表_203_7.13-7.15.xlsx', '接口2数据2列表_207_7.1.xlsx',\r\n # '接口2数据2列表_207_7.2.xlsx', '接口2数据2列表_207_7.3.xlsx', '接口2数据2列表_207_7.4.xlsx',\r\n # '接口2数据2列表_207_7.5.xlsx', '接口2数据2列表_207_7.6.xlsx', '接口2数据2列表_207_7.7.xlsx',\r\n # '接口2数据2列表_207_7.8-7.12.xlsx', '接口2数据2列表_207_7.13-7.15.xlsx', '接口2数据2列表_208_7.1-7.4.xlsx',\r\n # '接口2数据2列表_208_7.5-7.12.xlsx', '接口2数据2列表_208_7.13-7.15.xlsx' ]\r\n\r\n\r\n\r\n # # # for 接口1数据列表_203\r\n # # file_name = ['接口1数据列表_203_6.15-6.16.xlsx', '接口1数据列表_203_6.16-6.17.xlsx', '接口1数据列表_203_6.17-6.18.xlsx',\r\n # # '接口1数据列表_203_6.18-6.20.xlsx', '接口1数据列表_203_6.20-6.21.xlsx', '接口1数据列表_203_6.21-6.23.xlsx',\r\n # # '接口1数据列表_203_6.23-6.26.xlsx', '接口1数据列表_203_6.26-6.29.xlsx','接口1数据列表_203_6.29-6.30尾.xlsx' ]\r\n # file_name = ['接口1数据列表_203_6.12-6.15.xlsx', '接口1数据列表_203_6.10-6.12.xlsx','接口1数据列表_203_6.9-6.10.xlsx',\r\n # '接口1数据列表_203_6.8-6.9.xlsx','接口1数据列表_203_5.25-6.8.xlsx']\r\n\r\n # # # for 接口1数据列表_207\r\n # # file_name = ['接口1数据列表_207_6.20-6.22.xlsx', '接口1数据列表_207_6.22-6.24.xlsx',\r\n # # '接口1数据列表_207_6.24-6.26.xlsx', '接口1数据列表_207_6.26-6.28.xlsx','接口1数据列表_207_6.28-6.30尾.xlsx' ]\r\n # file_name = ['接口1数据列表_207_5.25-6.15.xlsx']\r\n\r\n # # # # for 接口1数据列表_208\r\n # # file_name = ['接口1数据列表_208_6.15-6.18.xlsx', '接口1数据列表_208_6.18-6.20.xlsx',\r\n # # '接口1数据列表_208_6.20-6.22.xlsx', '接口1数据列表_208_6.22-6.24.xlsx', '接口1数据列表_208_6.24-6.26.xlsx',\r\n # # '接口1数据列表_208_6.26-6.28.xlsx', '接口1数据列表_208_6.28-6.30.xlsx','接口1数据列表_208_6.30-6.30尾.xlsx' ]\r\n # file_name = ['接口1数据列表_208_5.25-6.10.xlsx', '接口1数据列表_208_6.10-6.15.xlsx']\r\n\r\n # # # for 接口1数据列表_测试集\r\n # file_name = ['接口1数据列表_203_7.1-7.12.xlsx', '接口1数据列表_203_7.13-7.15.xlsx', '接口1数据列表_207_7.1.xlsx', '接口1数据列表_207_7.2.xlsx',\r\n # '接口1数据列表_207_7.3.xlsx',\r\n # '接口1数据列表_207_7.4.xlsx', '接口1数据列表_207_7.5.xlsx', '接口1数据列表_207_7.6.xlsx', '接口1数据列表_207_7.7.xlsx',\r\n # '接口1数据列表_207_7.8.xlsx', '接口1数据列表_207_7.9.xlsx', '接口1数据列表_207_7.10.xlsx', '接口1数据列表_207_7.11.xlsx',\r\n # '接口1数据列表_207_7.12.xlsx', '接口1数据列表_207_7.13-7.15.xlsx', '接口1数据列表_208_7.1.xlsx', '接口1数据列表_208_7.2.xlsx',\r\n # '接口1数据列表_208_7.3.xlsx', '接口1数据列表_208_7.4.xlsx', '接口1数据列表_208_7.5.xlsx',\r\n # '接口1数据列表_208_7.6.xlsx' '接口1数据列表_208_7.7.xlsx', '接口1数据列表_208_7.8-7.9.xlsx', '接口1数据列表_208_7.10.xlsx',\r\n # '接口1数据列表_208_7.11.xlsx', '接口1数据列表_208_7.12.xlsx', '接口1数据列表_208_7.13-7.15.xlsx' ]\r\n # file_name = ['接口1数据列表_208_7.6.xlsx' , '接口1数据列表_208_7.7.xlsx', '接口1数据列表_208_7.8-7.9.xlsx', '接口1数据列表_208_7.10.xlsx',\r\n # '接口1数据列表_208_7.11.xlsx', '接口1数据列表_208_7.12.xlsx', '接口1数据列表_208_7.13-7.15.xlsx' ]\r\n\r\n\r\n\r\n # # # # for 其他数据列表_203\r\n # file_name = ['其他数据列表_203_6.15-6.22.xlsx', '其他数据列表_203_6.22-6.23.xlsx','其他数据列表_203_6.23-6.24.xlsx',\r\n # '其他数据列表_203_6.27-6.28.xlsx', '其他数据列表_203_6.28-6.29.xlsx','其他数据列表_203_6.29-6.30尾.xlsx' ]\r\n # file_name = ['其他数据列表_203_5.25-6.15.xlsx']\r\n\r\n\r\n # # # for 其他数据列表_207\r\n # file_name = ['其他数据列表_207_6.20-6.26.xlsx', '其他数据列表_207_6.26-6.27.xlsx', '其他数据列表_207_6.27-6.28.xlsx',\r\n # '其他数据列表_207_6.28-6.29.xlsx', '其他数据列表_207_6.29-6.30尾.xlsx']\r\n # file_name = ['其他数据列表_207_5.25-6.15.xlsx']\r\n\r\n\r\n # # # # for 其他数据列表_208\r\n # file_name = ['其他数据列表_208_6.15-6.22.xlsx', '其他数据列表_208_6.23-6.24.xlsx', '其他数据列表_208_6.24-6.25.xlsx',\r\n # '其他数据列表_208_6.25-6.26.xlsx', '其他数据列表_208_6.26-6.27.xlsx', '其他数据列表_208_6.27-6.28.xlsx',\r\n # '其他数据列表_208_6.28-6.29.xlsx', '其他数据列表_208_6.29-6.30尾.xlsx' ]\r\n # file_name = ['其他数据列表_208_5.15-6.15.xlsx']\r\n\r\n # # # for 其他数据列表_测试集\r\n file_name = ['其他数据列表_203_7.1-7.12.xlsx', '其他数据列表_203_7.13-7.15.xlsx', '其他数据列表_207_7.1-7.12.xlsx',\r\n '其他数据列表_207_7.13-7.15.xlsx', '其他数据列表_208_7.1-7.12.xlsx', '其他数据列表_208_7.13-7.15.xlsx']\r\n\r\n\r\n\r\n\r\n for str in file_name:\r\n excel = pd.read_excel(r'F:\\轮胎项目\\导出数据\\其他数据列表_训练数据\\\\' + str)\r\n print(excel,excel.values,'\\n',type(excel),'\\n',type(excel.values))\r\n print(excel.columns,'\\n',excel.index)\r\n # print(excel[\"C5信号丢失报警\"])\r\n print(excel.dtypes)\r\n\r\n checkIsNull(excel,str)\r\n\r\n print('--------------分割线-------------')\r\n\r\n excel.loc[:,[\"终端设备时间\",\"平台接收时间\"]] = excel.loc[:,[\"终端设备时间\",\"平台接收时间\"]].apply(pd.to_datetime)\r\n print(excel)\r\n print(excel.dtypes)\r\n print(excel.__len__())\r\n excel.to_sql('其他数据列表_测试集', oraengine, if_exists=\"append\", index=False, chunksize=100)\r\n\r\n # excel_no_lost = excel.loc[excel[\"C5信号丢失报警\"].isin([\"C5-已报警\"])]\r\n # # excel_no_lost = excel\r\n #\r\n # print(excel_no_lost)\r\n # print(excel_no_lost.dtypes)\r\n #\r\n # print('--------------分割线-------------')\r\n\r\n # excel_no_lost.loc[:,[\"终端设备时间\",\"平台接收时间\"]] = excel_no_lost.loc[:,[\"终端设备时间\",\"平台接收时间\"]].apply(pd.to_datetime)\r\n # # excel_no_lost.loc[:, [\"终端设备时间\", \"平台接收时间\"]].apply(pd.to_datetime)\r\n # print(excel_no_lost)\r\n # print(excel_no_lost.dtypes)\r\n\r\n\r\n\r\n\r\n# plot single threshold show\r\ndef read_excel_threshold():\r\n oraengine = sqlalchemy.create_engine('oracle://TireProject:jl123456@localhost:1521/orcl')\r\n\r\n# # 拟合训练\r\n# #\r\n file_directory = 'F:\\轮胎项目\\导出数据\\整合(5.25-6.30)\\\\'\r\n\r\n excel_name1_g = '毂温数据_203(5.25-6.30).xlsx'\r\n excel_name2_g = '毂温数据_207(5.25-6.30).xlsx'\r\n excel_name3_g = '毂温数据_208(5.15-6.30).xlsx'\r\n excel1_g = pd.read_excel(file_directory + excel_name1_g)\r\n excel2_g = pd.read_excel(file_directory + excel_name2_g)\r\n excel3_g = pd.read_excel(file_directory + excel_name3_g)\r\n\r\n excel_g = pd.concat([excel1_g[[\"数据(℃)\"]], excel2_g[[\"数据(℃)\"]], excel3_g[[\"数据(℃)\"]]])\r\n\r\n # 考虑去除毂温数据集的特殊值和边界值\r\n data_g = RemoveErrVal(excel_g, keyword=[\"数据(℃)\"], errValue=['无', '-1.04', '-50'])\r\n data_g.loc[:, [\"数据(℃)\"]] = data_g.loc[:, [\"数据(℃)\"]].apply(pd.to_numeric)\r\n # data_g = data_g[(data_g[\"数据(℃)\"] > 5) & (data_g[\"数据(℃)\"] < 120)]\r\n data_g = data_g[(data_g[\"数据(℃)\"] > 0)]\r\n\r\n print(data_g[[\"数据(℃)\"]].describe())\r\n print(\"毂温数据偏度:\", data_g[\"数据(℃)\"].skew())\r\n print('----------------分割线-------------------')\r\n # print_plot_sns(data_g, keyword=[\"数据(℃)\"], title='轮胎监测系统', xlab='胎压', ylab='概率密度', bins=20)\r\n\r\n\r\n # excel for 绑带式轮胎温度203\r\n excel_name1 = '绑带式轮胎数据_203(5.25-6.30).xlsx'\r\n excel_name2 = '绑带式轮胎数据_207(5.25-6.30).xlsx'\r\n excel_name3 = '绑带式轮胎数据_208(5.15-6.30).xlsx'\r\n excel1 = pd.read_excel(file_directory + excel_name1)\r\n excel2 = pd.read_excel(file_directory + excel_name2)\r\n excel3 = pd.read_excel(file_directory + excel_name3)\r\n excel = pd.concat([excel1[[\"轮胎温度(℃)\",\"轮胎压力(Bar)\"]],excel2[[\"轮胎温度(℃)\",\"轮胎压力(Bar)\"]],excel3[[\"轮胎温度(℃)\",\"轮胎压力(Bar)\"]]])\r\n\r\n ## 去除轮胎数据集异常值和边界值\r\n data = RemoveErrVal(excel,keyword=[\"轮胎温度(℃)\",\"轮胎压力(Bar)\"],errValue=['无','-1.04','-50'])\r\n data.loc[:, [\"轮胎温度(℃)\",\"轮胎压力(Bar)\"]] = data.loc[:, [\"轮胎温度(℃)\",\"轮胎压力(Bar)\"]].apply(pd.to_numeric)\r\n # data = data[(data[\"轮胎温度(℃)\"] > 5) & (data[\"轮胎压力(Bar)\"] > 4) & (data[\"轮胎温度(℃)\"] < 100)]\r\n data = data[(data[\"轮胎温度(℃)\"] > 0) & (data[\"轮胎压力(Bar)\"] > 0)]\r\n\r\n print(data[[\"轮胎温度(℃)\", \"轮胎压力(Bar)\"]].describe())\r\n print(\"轮胎温度偏度:\", data[\"轮胎温度(℃)\"].skew(), \"轮胎压力偏度:\", data[\"轮胎压力(Bar)\"].skew())\r\n\r\n # # 数据展示\r\n # print_plot_sns_2(data,isTrain=False,keyword=[\"轮胎温度(℃)\",\"轮胎压力(Bar)\"], dataAnother=data_g,keywordAnother=[\"数据(℃)\"],\r\n # title='轮胎监测系统',xlab='胎压', ylab='概率密度' ,bins=20, binsAnother=30)\r\n print_plot_sns_2(data,isTrain=True,keyword=[\"轮胎温度(℃)\",\"轮胎压力(Bar)\"], dataAnother=data_g,keywordAnother=[\"数据(℃)\"],\r\n title='轮胎监测系统',xlab='胎压', ylab='概率密度' ,bins=25, binsAnother=35)\r\n\r\n# 根据经验值,统计各经验阈值在训练集中所占的比例\r\n print('训练集个经验阈值在样本中体重所占比例:')\r\n print('毂温高温预警阈值130℃所占比例:',len(data_g[data_g[\"数据(℃)\"] >= 130]) * 1.0 / len(data_g))\r\n print('毂温高温报警阈值180℃所占比例:',len(data_g[data_g[\"数据(℃)\"] >= 180]) * 1.0 / len(data_g))\r\n print('轮胎高温报警阈值85℃所占比例:',len(data[data[\"轮胎温度(℃)\"] >= 85]) * 1.0 / len(data))\r\n print('轮胎高压预警阈值10.5 Bar所占比例:',len(data[data[\"轮胎压力(Bar)\"] >= 10.5]) * 1.0 / len(data))\r\n print('轮胎高压报警阈值10.94 Bar所占比例:',len(data[data[\"轮胎压力(Bar)\"] >= 10.94]) * 1.0 / len(data))\r\n print('轮胎低压预警阈值7.44 Bar所占比例:',len(data[data[\"轮胎压力(Bar)\"] <= 7.44]) * 1.0 / len(data))\r\n\r\n\r\n\r\n\r\n# # # 拟合测试验证\r\n# file_directory = 'F:\\轮胎项目\\导出数据\\整合测试集(7.1-7.15)\\\\'\r\n#\r\n# excel_guwen = '毂温测试数据集.xlsx'\r\n# excel_luntai = '胎压胎温测试数据集.xlsx'\r\n#\r\n# data_guwen = pd.read_excel(file_directory + excel_guwen,usecols=[12])\r\n# data_luntai = pd.read_excel(file_directory + excel_luntai,usecols=[10,11])\r\n#\r\n# # 考虑去除特殊值和边界值\r\n# data_guwen = RemoveErrVal(data_guwen, keyword=[\"数据(℃)\"], errValue=['无', '-1.04', '-50'])\r\n# data_guwen.loc[:, [\"数据(℃)\"]] = data_guwen.loc[:, [\"数据(℃)\"]].apply(pd.to_numeric)\r\n# data_guwen = data_guwen[(data_guwen[\"数据(℃)\"] > 5) & (data_guwen[\"数据(℃)\"] < 120)]\r\n# print(data_guwen.describe())\r\n# print(\"毂温偏度:\", data_guwen[\"数据(℃)\"].skew())\r\n#\r\n# data_luntai = RemoveErrVal(data_luntai,keyword=[\"轮胎温度(℃)\",\"轮胎压力(Bar)\"],errValue=['无','-1.04','-50'])\r\n# data_luntai.loc[:, [\"轮胎温度(℃)\",\"轮胎压力(Bar)\"]] = data_luntai.loc[:, [\"轮胎温度(℃)\",\"轮胎压力(Bar)\"]].apply(pd.to_numeric)\r\n# data_luntai = data_luntai[(data_luntai[\"轮胎温度(℃)\"] > 5) & (data_luntai[\"轮胎压力(Bar)\"] > 4) & (data_luntai[\"轮胎温度(℃)\"] < 100)]\r\n# print(data_luntai[[\"轮胎温度(℃)\", \"轮胎压力(Bar)\"]].describe())\r\n# print(\"轮胎温度偏度:\", data_luntai[\"轮胎温度(℃)\"].skew(), \"轮胎压力偏度:\", data_luntai[\"轮胎压力(Bar)\"].skew())\r\n#\r\n# print_plot_sns_2(data_luntai, isTrain=False, keyword=[\"轮胎温度(℃)\",\"轮胎压力(Bar)\"], dataAnother=data_guwen,keywordAnother=[\"数据(℃)\"],\r\n# title='轮胎监测系统',xlab='胎压', ylab='概率密度' ,bins=20, binsAnother=30)\r\n\r\n\r\n\r\n\r\n# plot different thresholds show and compare\r\ndef read_excel_threshold_compare():\r\n oraengine = sqlalchemy.create_engine('oracle://TireProject:jl123456@localhost:1521/orcl')\r\n\r\n\r\n # 拟合训练\r\n file_directory = 'F:\\轮胎项目\\导出数据\\整合(5.25-6.30)\\\\'\r\n excel_name1_g = '毂温数据_203(5.25-6.30).xlsx'\r\n excel_name2_g = '毂温数据_207(5.25-6.30).xlsx'\r\n excel_name3_g = '毂温数据_208(5.15-6.30).xlsx'\r\n # excel_name1_g = '绑带式轮胎数据_203(5.25-6.30).xlsx'\r\n # excel_name2_g = '绑带式轮胎数据_207(5.25-6.30).xlsx'\r\n # excel_name3_g = '绑带式轮胎数据_208(5.15-6.30).xlsx'\r\n excel1_g = pd.read_excel(file_directory + excel_name1_g)\r\n excel2_g = pd.read_excel(file_directory + excel_name2_g)\r\n excel3_g = pd.read_excel(file_directory + excel_name3_g)\r\n # excel_g = pd.concat([excel1_g[[\"数据(℃)\"]], excel2_g[[\"数据(℃)\"]], excel3_g[[\"数据(℃)\"]]])\r\n data1_g = RemoveErrVal(excel1_g, keyword=[\"数据(℃)\"], errValue=['无', '-1.04', '-50'])\r\n data2_g = RemoveErrVal(excel2_g, keyword=[\"数据(℃)\"], errValue=['无', '-1.04', '-50'])\r\n data3_g = RemoveErrVal(excel3_g, keyword=[\"数据(℃)\"], errValue=['无', '-1.04', '-50'])\r\n\r\n data1_g.loc[:, [\"数据(℃)\"]] = data1_g.loc[:, [\"数据(℃)\"]].apply(pd.to_numeric)\r\n data2_g.loc[:, [\"数据(℃)\"]] = data2_g.loc[:, [\"数据(℃)\"]].apply(pd.to_numeric)\r\n data3_g.loc[:, [\"数据(℃)\"]] = data3_g.loc[:, [\"数据(℃)\"]].apply(pd.to_numeric)\r\n # 考虑去除边界值\r\n data1_g = data1_g[(data1_g[\"数据(℃)\"] > 5) & (data1_g[\"数据(℃)\"] < 180)]\r\n data2_g = data2_g[(data2_g[\"数据(℃)\"] > 5) & (data2_g[\"数据(℃)\"] < 180)]\r\n data3_g = data3_g[(data3_g[\"数据(℃)\"] > 5) & (data3_g[\"数据(℃)\"] < 180)]\r\n\r\n print(data1_g[[\"数据(℃)\"]].describe(),'\\n',data2_g[[\"数据(℃)\"]].describe(),'\\n',data3_g[[\"数据(℃)\"]].describe())\r\n print(\"轮毂温度偏度:\", data1_g[\"数据(℃)\"].skew(),data2_g[\"数据(℃)\"].skew(),data2_g[\"数据(℃)\"].skew())\r\n\r\n print_plot_sns_compare([data1_g,data2_g,data3_g],[\"数据(℃)\",\"数据(℃)\",\"数据(℃)\"],bins=[30,30,30])\r\n\r\n\r\n# 测试数据集\r\n\r\n file_directory_test = 'F:\\轮胎项目\\导出数据\\整合测试集(7.1-7.15)\\\\'\r\n excel_luntai = '胎压胎温测试数据集.xlsx'\r\n excel_guwen = '毂温测试数据集.xlsx'\r\n\r\n data_guwen = pd.read_excel(file_directory_test + excel_guwen)\r\n data_luntai = pd.read_excel(file_directory_test + excel_luntai)\r\n\r\n # excel_g = pd.concat([excel1_g[[\"数据(℃)\"]], excel2_g[[\"数据(℃)\"]], excel3_g[[\"数据(℃)\"]]])\r\n data1_g = RemoveErrVal(data_guwen[data_guwen[\"设备ID\"] == 'zwgps180203'], keyword=[\"数据(℃)\"], errValue=['无', '-1.04', '-50'])\r\n data2_g = RemoveErrVal(data_guwen[data_guwen[\"设备ID\"] == 'zwgps180207'], keyword=[\"数据(℃)\"], errValue=['无', '-1.04', '-50'])\r\n data3_g = RemoveErrVal(data_guwen[data_guwen[\"设备ID\"] == 'zwgps180208'], keyword=[\"数据(℃)\"], errValue=['无', '-1.04', '-50'])\r\n\r\n data1_g.loc[:, [\"数据(℃)\"]] = data1_g.loc[:, [\"数据(℃)\"]].apply(pd.to_numeric)\r\n data2_g.loc[:, [\"数据(℃)\"]] = data2_g.loc[:, [\"数据(℃)\"]].apply(pd.to_numeric)\r\n data3_g.loc[:, [\"数据(℃)\"]] = data3_g.loc[:, [\"数据(℃)\"]].apply(pd.to_numeric)\r\n # 考虑去除边界值\r\n data1_g = data1_g[(data1_g[\"数据(℃)\"] > 3) & (data1_g[\"数据(℃)\"] < 180)]\r\n data2_g = data2_g[(data2_g[\"数据(℃)\"] > 3) & (data2_g[\"数据(℃)\"] < 180)]\r\n data3_g = data3_g[(data3_g[\"数据(℃)\"] > 3) & (data3_g[\"数据(℃)\"] < 180)]\r\n\r\n print(data1_g[[\"数据(℃)\"]].describe(),'\\n',data2_g[[\"数据(℃)\"]].describe(),'\\n',data3_g[[\"数据(℃)\"]].describe())\r\n print(\"轮毂温度偏度:\", data1_g[\"数据(℃)\"].skew(),data2_g[\"数据(℃)\"].skew(),data2_g[\"数据(℃)\"].skew())\r\n\r\n print_plot_sns_compare([data1_g,data2_g,data3_g],[\"数据(℃)\",\"数据(℃)\",\"数据(℃)\"],bins=[30,30,30])\r\n\r\n\r\n\r\n\r\ndef data_time_axis_analyse():\r\n file_directory = 'F:\\轮胎项目\\导出数据\\整合(5.25-6.30)\\\\'\r\n\r\n excel_name1_g = '绑带式轮胎数据_203(5.25-6.30).xlsx'\r\n excel_name2_g = '绑带式轮胎数据_207(5.25-6.30).xlsx'\r\n excel_name3_g = '绑带式轮胎数据_208(5.15-6.30).xlsx'\r\n # excel_name1_g = '毂温数据_203(5.25-6.30).xlsx'\r\n # excel_name2_g = '毂温数据_207(5.25-6.30).xlsx'\r\n # excel_name3_g = '毂温数据_208(5.15-6.30).xlsx'\r\n\r\n\r\n # excel_name1_g = '胎压胎温测试数据集.xlsx'\r\n excel_name = excel_name3_g\r\n excel1_g = pd.read_excel(file_directory + excel_name)\r\n # excel1_g = excel1_g[excel1_g['设备ID'] == 'zwgps180207']\r\n\r\n\r\n # 时段筛选\r\n # # for 203\r\n # excel1_g.loc[:, [\"终端设备时间\", \"平台接收时间\"]] = excel1_g.loc[:, [\"终端设备时间\", \"平台接收时间\"]].apply(pd.to_datetime)\r\n # excel_g = excel1_g[(excel1_g[\"平台接收时间\"] >= datetime.strptime('2018/6/1 00:00:00', '%Y/%m/%d %H:%M:%S'))\r\n # & (excel1_g[\"平台接收时间\"] <= datetime.strptime('2018/6/15 00:00:00', '%Y/%m/%d %H:%M:%S'))\r\n # & (excel1_g[\"终端设备时间\"] >= datetime.strptime('2018/5/30 05:00:00', '%Y/%m/%d %H:%M:%S'))]\r\n\r\n # for 207\r\n excel1_g.loc[:, [\"终端设备时间\", \"平台接收时间\"]] = excel1_g.loc[:, [\"终端设备时间\", \"平台接收时间\"]].apply(pd.to_datetime)\r\n excel_g = excel1_g[(excel1_g[\"平台接收时间\"]>=datetime.strptime('2018/6/1 00:00:00','%Y/%m/%d %H:%M:%S'))\r\n & (excel1_g[\"平台接收时间\"]<=datetime.strptime('2018/6/11 00:00:00','%Y/%m/%d %H:%M:%S'))\r\n &(excel1_g[\"终端设备时间\"]>=datetime.strptime('2018/5/30 05:00:00','%Y/%m/%d %H:%M:%S')) ]\r\n\r\n # # for 208\r\n # excel1_g.loc[:, [\"终端设备时间\", \"平台接收时间\"]] = excel1_g.loc[:, [\"终端设备时间\", \"平台接收时间\"]].apply(pd.to_datetime)\r\n # excel_g = excel1_g[(excel1_g[\"平台接收时间\"] >= datetime.strptime('2018/6/5 05:00:00', '%Y/%m/%d %H:%M:%S'))\r\n # & (excel1_g[\"平台接收时间\"] <= datetime.strptime('2018/6/8 00:00:00', '%Y/%m/%d %H:%M:%S'))\r\n # & (excel1_g[\"终端设备时间\"] >= datetime.strptime('2018/6/1 05:00:00', '%Y/%m/%d %H:%M:%S'))]\r\n\r\n\r\n\r\n\r\n\r\n data_g = RemoveErrVal(excel_g, keyword=[\"轮胎温度(℃)\", \"轮胎压力(Bar)\"], errValue=['无', '-1.04', '-50'])\r\n data_g.loc[:, [\"轮胎温度(℃)\", \"轮胎压力(Bar)\"]] = data_g.loc[:, [\"轮胎温度(℃)\", \"轮胎压力(Bar)\"]].apply(pd.to_numeric)\r\n # data_g = RemoveErrVal(excel_g, keyword=[\"数据(℃)\"], errValue=['无', '-1.04', '-50'])\r\n # data_g.loc[:, [\"数据(℃)\"]] = data_g.loc[:, [\"数据(℃)\"]].apply(pd.to_numeric)\r\n data_g = data_g[data_g[\"轮胎温度(℃)\"]<150]\r\n\r\n # # 分车\r\n car0_data = data_g[data_g[\"车编号\"] == 0]\r\n car1_data = data_g[data_g[\"车编号\"] == 1]\r\n # 毂温\r\n # car1_data = data_g\r\n\r\n\r\n\r\n # 分轮胎\r\n # # 牵引车分轮胎(208车的牵引台0123,其他车均为8 9 10 11)\r\n luntai008_data = car0_data[car0_data[\"轮胎编号\"] == 0]\r\n luntai009_data = car0_data[car0_data[\"轮胎编号\"] == 1]\r\n luntai010_data = car0_data[car0_data[\"轮胎编号\"] == 2]\r\n luntai011_data = car0_data[car0_data[\"轮胎编号\"] == 3]\r\n # # 挂车分轮胎\r\n # luntai100_data = car1_data[car1_data[\"轮胎编号\"] == 0]\r\n # luntai101_data = car1_data[car1_data[\"轮胎编号\"] == 1]\r\n # luntai102_data = car1_data[car1_data[\"轮胎编号\"] == 2]\r\n # luntai103_data = car1_data[car1_data[\"轮胎编号\"] == 3]\r\n # luntai108_data = car1_data[car1_data[\"轮胎编号\"] == 8]\r\n # luntai109_data = car1_data[car1_data[\"轮胎编号\"] == 9]\r\n # luntai110_data = car1_data[car1_data[\"轮胎编号\"] == 10]\r\n # luntai111_data = car1_data[car1_data[\"轮胎编号\"] == 11]\r\n # for 毂温分轮胎\r\n # luntai100_data = car1_data[car1_data[\"顺序编号\"] == 1]\r\n # luntai101_data = car1_data[car1_data[\"顺序编号\"] == 2]\r\n # luntai102_data = car1_data[car1_data[\"顺序编号\"] == 3]\r\n # luntai103_data = car1_data[car1_data[\"顺序编号\"] == 4]\r\n # luntai108_data = car1_data[car1_data[\"顺序编号\"] == 5]\r\n # luntai109_data = car1_data[car1_data[\"顺序编号\"] == 6]\r\n\r\n\r\n # print(len(excel1_g),len(data_g),len(car0_data),len(car1_data),len(luntai008_data))\r\n # 轮胎数据时间排序\r\n # # 牵引车时间排序\r\n luntai008_data = luntai008_data.sort_values(by=\"终端设备时间\")\r\n luntai009_data = luntai009_data.sort_values(by=\"终端设备时间\")\r\n luntai010_data = luntai010_data.sort_values(by=\"终端设备时间\")\r\n luntai011_data = luntai011_data.sort_values(by=\"终端设备时间\")\r\n # # 挂车时间排序\r\n # luntai100_data = luntai100_data.sort_values(by=\"终端设备时间\")\r\n # luntai101_data = luntai101_data.sort_values(by=\"终端设备时间\")\r\n # luntai102_data = luntai102_data.sort_values(by=\"终端设备时间\")\r\n # luntai103_data = luntai103_data.sort_values(by=\"终端设备时间\")\r\n # luntai108_data = luntai108_data.sort_values(by=\"终端设备时间\")\r\n # luntai109_data = luntai109_data.sort_values(by=\"终端设备时间\")\r\n # luntai110_data = luntai110_data.sort_values(by=\"终端设备时间\")\r\n # luntai111_data = luntai111_data.sort_values(by=\"终端设备时间\")\r\n\r\n # 毂温时间排序\r\n # luntai100_data = luntai100_data.sort_values(by=\"终端设备时间\")\r\n # luntai101_data = luntai101_data.sort_values(by=\"终端设备时间\")\r\n # luntai102_data = luntai102_data.sort_values(by=\"终端设备时间\")\r\n # luntai103_data = luntai103_data.sort_values(by=\"终端设备时间\")\r\n # luntai108_data = luntai108_data.sort_values(by=\"终端设备时间\")\r\n # luntai109_data = luntai109_data.sort_values(by=\"终端设备时间\")\r\n\r\n\r\n\r\n\r\n # 绘制时间轴图\r\n # # 牵引车时间\r\n dates8 = luntai008_data[\"终端设备时间\"]\r\n dates9 = luntai009_data[\"终端设备时间\"]\r\n dates10 = luntai010_data[\"终端设备时间\"]\r\n dates11 = luntai011_data[\"终端设备时间\"]\r\n # # 203 1\r\n # dates0 = luntai100_data[\"终端设备时间\"]\r\n # dates1 = luntai101_data[\"终端设备时间\"]\r\n # dates2 = luntai102_data[\"终端设备时间\"]\r\n # dates3 = luntai103_data[\"终端设备时间\"]\r\n # dates8 = luntai108_data[\"终端设备时间\"]\r\n # dates9 = luntai109_data[\"终端设备时间\"]\r\n # dates10 = luntai110_data[\"终端设备时间\"]\r\n # dates11 = luntai111_data[\"终端设备时间\"]\r\n # 毂温\r\n # dates0 = luntai100_data[\"终端设备时间\"]\r\n # dates1 = luntai101_data[\"终端设备时间\"]\r\n # dates2 = luntai102_data[\"终端设备时间\"]\r\n # dates3 = luntai103_data[\"终端设备时间\"]\r\n # dates8 = luntai108_data[\"终端设备时间\"]\r\n # dates9 = luntai109_data[\"终端设备时间\"]\r\n\r\n\r\n # # # 牵引车\r\n xs8 = [datetime.strptime(d.strftime(\"%Y/%m/%d %H:%M:%S\"),\"%Y/%m/%d %H:%M:%S\") for d in dates8]\r\n xs9 = [datetime.strptime(d.strftime(\"%Y/%m/%d %H:%M:%S\"),\"%Y/%m/%d %H:%M:%S\") for d in dates9]\r\n xs10 = [datetime.strptime(d.strftime(\"%Y/%m/%d %H:%M:%S\"),\"%Y/%m/%d %H:%M:%S\") for d in dates10]\r\n xs11 = [datetime.strptime(d.strftime(\"%Y/%m/%d %H:%M:%S\"),\"%Y/%m/%d %H:%M:%S\") for d in dates11]\r\n # # 挂车\r\n # xs0 = [datetime.strptime(d.strftime(\"%Y/%m/%d %H:%M:%S\"), \"%Y/%m/%d %H:%M:%S\") for d in dates0]\r\n # xs1 = [datetime.strptime(d.strftime(\"%Y/%m/%d %H:%M:%S\"), \"%Y/%m/%d %H:%M:%S\") for d in dates1]\r\n # xs2 = [datetime.strptime(d.strftime(\"%Y/%m/%d %H:%M:%S\"), \"%Y/%m/%d %H:%M:%S\") for d in dates2]\r\n # xs3 = [datetime.strptime(d.strftime(\"%Y/%m/%d %H:%M:%S\"), \"%Y/%m/%d %H:%M:%S\") for d in dates3]\r\n # xs8 = [datetime.strptime(d.strftime(\"%Y/%m/%d %H:%M:%S\"), \"%Y/%m/%d %H:%M:%S\") for d in dates8]\r\n # xs9 = [datetime.strptime(d.strftime(\"%Y/%m/%d %H:%M:%S\"), \"%Y/%m/%d %H:%M:%S\") for d in dates9]\r\n # xs10 = [datetime.strptime(d.strftime(\"%Y/%m/%d %H:%M:%S\"), \"%Y/%m/%d %H:%M:%S\") for d in dates10]\r\n # xs11 = [datetime.strptime(d.strftime(\"%Y/%m/%d %H:%M:%S\"), \"%Y/%m/%d %H:%M:%S\") for d in dates11]\r\n\r\n # 毂温\r\n # xs0 = [datetime.strptime(d.strftime(\"%Y/%m/%d %H:%M:%S\"), \"%Y/%m/%d %H:%M:%S\") for d in dates0]\r\n # xs1 = [datetime.strptime(d.strftime(\"%Y/%m/%d %H:%M:%S\"), \"%Y/%m/%d %H:%M:%S\") for d in dates1]\r\n # xs2 = [datetime.strptime(d.strftime(\"%Y/%m/%d %H:%M:%S\"), \"%Y/%m/%d %H:%M:%S\") for d in dates2]\r\n # xs3 = [datetime.strptime(d.strftime(\"%Y/%m/%d %H:%M:%S\"), \"%Y/%m/%d %H:%M:%S\") for d in dates3]\r\n # xs8 = [datetime.strptime(d.strftime(\"%Y/%m/%d %H:%M:%S\"), \"%Y/%m/%d %H:%M:%S\") for d in dates8]\r\n # xs9 = [datetime.strptime(d.strftime(\"%Y/%m/%d %H:%M:%S\"), \"%Y/%m/%d %H:%M:%S\") for d in dates9]\r\n\r\n\r\n\r\n\r\n fig = plt.figure(num=1)\r\n # ax = fig.add_subplot(1, 1, 1)\r\n # ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y/%m/%d %H:%M:%S')) # 设置时间标签显示格式\r\n plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d %H:%M:%S'),)\r\n plt.gca().xaxis.set_major_locator(mdates.HourLocator(interval=8))\r\n\r\n # *******************for 胎压可视化*********************\r\n # ++++++++++++ 牵引车 ++++++++++++++\r\n plt.plot(xs8, luntai008_data[\"轮胎压力(Bar)\"], 'rh:', markersize=3.5, label='0号轮胎胎压')\r\n plt.plot(xs9, luntai009_data[\"轮胎压力(Bar)\"], 'gh:', markersize=3.5, label='1号轮胎胎压')\r\n plt.plot(xs10, luntai010_data[\"轮胎压力(Bar)\"], 'ch:', markersize=3.5, label='2号轮胎胎压')\r\n plt.plot(xs11, luntai011_data[\"轮胎压力(Bar)\"], 'mh:', markersize=3.5, label='3号轮胎胎压')\r\n # ++++++++++++ 挂车 ++++++++++++++\r\n # plt.plot(xs0, luntai100_data[\"轮胎压力(Bar)\"], 'rh:', markersize=3.5, label='0号轮胎胎压')\r\n # plt.plot(xs1, luntai101_data[\"轮胎压力(Bar)\"], 'gh:', markersize=3.5, label='1号轮胎胎压')\r\n # plt.plot(xs2, luntai102_data[\"轮胎压力(Bar)\"], 'ch:', markersize=3.5, label='2号轮胎胎压')\r\n # plt.plot(xs3, luntai103_data[\"轮胎压力(Bar)\"], 'mh:', markersize=3.5, label='3号轮胎胎压')\r\n # plt.plot(xs8, luntai108_data[\"轮胎压力(Bar)\"], color='#103005',linestyle=':',marker='h',markersize=3.5, label='8号轮胎胎压')\r\n # plt.plot(xs9, luntai109_data[\"轮胎压力(Bar)\"], 'bh:', markersize=3.5, label='9号轮胎胎压')\r\n # plt.plot(xs10, luntai110_data[\"轮胎压力(Bar)\"], 'yh:', markersize=3.5, label='10号轮胎胎压')\r\n # plt.plot(xs11, luntai111_data[\"轮胎压力(Bar)\"], color='#FF6A6A', linestyle=':',marker='h',markersize=3.5, label='11号轮胎胎压')\r\n\r\n\r\n\r\n # *******************for 胎温可视化*********************\r\n # # ++++++++++++ 牵引车 ++++++++++++++\r\n # plt.plot(xs8, luntai008_data[\"轮胎温度(℃)\"], 'rh:', markersize=3.5, label='0号轮胎胎温')\r\n # plt.plot(xs9, luntai009_data[\"轮胎温度(℃)\"], 'gh:', markersize=3.5, label='1号轮胎胎温')\r\n # plt.plot(xs10, luntai010_data[\"轮胎温度(℃)\"], 'ch:', markersize=3.5, label='2号轮胎胎温')\r\n # plt.plot(xs11, luntai011_data[\"轮胎温度(℃)\"], 'mh:', markersize=3.5, label='3号轮胎胎温')\r\n # ++++++++++++ 挂车 ++++++++++++++\r\n # plt.plot(xs0, luntai100_data[\"轮胎温度(℃)\"], 'rh:', markersize=3.5, label='0号轮胎胎温')\r\n # plt.plot(xs1, luntai101_data[\"轮胎温度(℃)\"], 'gh:', markersize=3.5, label='1号轮胎胎温')\r\n # plt.plot(xs2, luntai102_data[\"轮胎温度(℃)\"], 'ch:', markersize=3.5, label='2号轮胎胎温')\r\n # plt.plot(xs3, luntai103_data[\"轮胎温度(℃)\"], 'mh:', markersize=3.5, label='3号轮胎胎温')\r\n # plt.plot(xs8, luntai108_data[\"轮胎温度(℃)\"], color='#103005',linestyle=':',marker='h',markersize=3.5, label='8号轮胎胎温')\r\n # plt.plot(xs9, luntai109_data[\"轮胎温度(℃)\"], 'bh:',markersize=3.5, label='9号轮胎胎温')\r\n # plt.plot(xs10, luntai110_data[\"轮胎温度(℃)\"], 'yh:', markersize=3.5, label='10号轮胎胎温')\r\n # plt.plot(xs11, luntai111_data[\"轮胎温度(℃)\"], color='#FF6A6A',linestyle=':',marker='h',markersize=3.5, label='11号轮胎胎温')\r\n\r\n\r\n #****************** 毂温可视化 *****************\r\n # plt.plot(xs0, luntai100_data[\"数据(℃)\"], 'rh:',markersize=3.5, label='1号轮毂温度')\r\n # plt.plot(xs1, luntai101_data[\"数据(℃)\"], 'gh:',markersize=3.5, label='2号轮毂温度')\r\n # plt.plot(xs2, luntai102_data[\"数据(℃)\"], 'ch:',markersize=3.5, label='3号轮毂温度')\r\n # plt.plot(xs3, luntai103_data[\"数据(℃)\"], 'mh:',markersize=3.5, label='4号轮毂温度')\r\n # plt.plot(xs8, luntai108_data[\"数据(℃)\"], color='#103005', linestyle=':',marker='h',markersize=3.5, label='5号轮毂温度')\r\n # plt.plot(xs9, luntai109_data[\"数据(℃)\"], 'bh:',markersize=3.5, label='6号轮毂温度')\r\n\r\n\r\n\r\n\r\n\r\n plt.gcf().autofmt_xdate() # 自动旋转日期标记\r\n plt.title(\"208车牵引车轮压力度时序监测\")\r\n plt.xlabel('时间')\r\n plt.ylabel('轮胎压力(Bar)')\r\n # plt.ylabel('轮胎温度(℃)')\r\n # plt.ylabel('轮毂温度(℃)')\r\n plt.legend()\r\n plt.grid(True,linestyle=':', linewidth=0.5)\r\n plt.show()\r\n\r\n # print(luntai008_data)\r\n # print(luntai08_data[[\"轮胎温度(℃)\", \"轮胎压力(Bar)\"]].describe())\r\n # print(luntai08_data.dtypes)\r\n # print('----------------分割线-------------------')\r\n # tim = luntai08_data[\"终端设备时间\"]\r\n # tim_one = tim[110636]\r\n # print(tim_one,type(tim_one))\r\n\r\n # print(tim,type(tim))\r\n # print(tim_one,type(tim_one))\r\n # print(xs,len(xs))\r\n # print(dt,type(dt))\r\n # print(dt + timedelta(hours=8))\r\n\r\n\r\nif __name__ == '__main__':\r\n # read_excel()\r\n # read_excel_wtpandas()\r\n # read_excel_threshold()\r\n # read_excel_threshold_compare()\r\n data_time_axis_analyse()\r\n\r\n","sub_path":"test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":42932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"287551624","text":"import sys\nimport cv2\n\nimg_path = sys.argv[1]\nimg = cv2.imread(img_path)\ncv2.imshow('test', img)\nr = cv2.selectROI(img)\nprint('roi:', r)\nframe_h, frame_w = img.shape[:2]\nroi_w, roi_h = r[2:]\nratio = (f'HEIGHT: {roi_h / frame_h:.2f} : WIDTH: {roi_w / frame_w:.2f}')\nprint('ratio:', ratio)\n","sub_path":"get_ratio.py","file_name":"get_ratio.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"385738996","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 ('ekPost', '0002_auto_20140914_1219'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='category',\n options={'ordering': ('-seq',), 'verbose_name': '\\u7c7b\\u522b', 'verbose_name_plural': '\\u7c7b\\u522b\\u5217\\u8868'},\n ),\n migrations.AlterModelOptions(\n name='categorygroup',\n options={'ordering': ('-seq',), 'verbose_name': '\\u7c7b\\u7ec4', 'verbose_name_plural': '\\u7c7b\\u7ec4\\u5217\\u8868'},\n ),\n migrations.AddField(\n model_name='post',\n name='href',\n field=models.URLField(default=b'', null=True, verbose_name='\\u5916\\u94fe\\u63a5', blank=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"ekPost/migrations/0003_auto_20140921_1350.py","file_name":"0003_auto_20140921_1350.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"52219077","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\nimport rdflib\n\n\n\ndef qname(uri, namespaces_dict, strip_html_tags=False):\n \"\"\"\n Try to determine a qname for a URI\n\n namespaces: dictionary of namespaces\n strip_html_tags: flag to remove < and > as needed by some JS visualizations\n \"\"\"\n if type(uri) != rdflib.term.URIRef:\n # transform into rdflib URIRef so to use namespace_manager on it\n if uri and uri.startswith(\"http://\"):\n uri = rdflib.term.URIRef(uri)\n # now main routine:\n if uri and type(uri) == rdflib.term.URIRef:\n try:\n graph = rdflib.Graph()\n for k,v in namespaces_dict.items():\n graph.bind(k, rdflib.Namespace(v))\n if False:\n # note: this is the proper way but it fails in some cases!\n # BUG: https://github.com/RDFLib/rdflib/issues/763\n uri = graph.namespace_manager.normalizeUri(uri)\n else:\n # my own implementation\n NS = [(k, rdflib.URIRef(v)) for k,v in namespaces_dict.items()]\n uri = uri2niceString(uri, NS)\n except:\n pass\n if strip_html_tags:\n uri = uri.replace(\"<\", \"\").replace(\">\", \"\")\n return uri\n\n\n\n\n\n\n\ndef ttlNamespaces2Dict(ttl_text):\n \"\"\"\n reads a TTL declaration of namespaces and returns a dict of the form\n {\n \"sg\": \"http://name.scigraph.com/ontologies/core/\" ,\n \"sgc\": \"http://name.scigraph.com/core/\",\n # etc..\n }\n \"\"\"\n exit = {}\n for line in ttl_text.split(\"\\n\"):\n line = line.strip()\n if line.startswith(\"@prefix\"):\n prefix = line.split()[1].replace(\":\", \"\")\n ns = line.split()[2].replace(\"<\", \"\").replace(\">\", \"\")\n exit[prefix] = ns\n return exit\n\n\n\n\n\n\ndef firstStringInList(literalEntities, prefLanguage=\"en\"):\n \"\"\"\n from a list of literals, returns the one in prefLanguage\n if no language specification is available, return first element\n \"\"\"\n match = \"\"\n\n if len(literalEntities) == 1:\n match = literalEntities[0]\n elif len(literalEntities) > 1:\n for x in literalEntities:\n if getattr(x, 'language') and getattr(x, 'language') == prefLanguage:\n match = x\n if not match: # don't bother about language\n match = literalEntities[0]\n return match\n\n\n\n\n\n\ndef uri2niceString(aUri, namespaces = None):\n \"\"\"\n From a URI, returns a nice string representation that uses also the namespace symbols\n Cuts the uri of the namespace, and replaces it with its shortcut (for base, attempts to infer it or leaves it blank)\n\n Namespaces are a list\n\n [('xml', rdflib.URIRef('http://www.w3.org/XML/1998/namespace'))\n ('', rdflib.URIRef('http://cohereweb.net/ontology/cohere.owl#'))\n (u'owl', rdflib.URIRef('http://www.w3.org/2002/07/owl#'))\n ('rdfs', rdflib.URIRef('http://www.w3.org/2000/01/rdf-schema#'))\n ('rdf', rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#'))\n (u'xsd', rdflib.URIRef('http://www.w3.org/2001/XMLSchema#'))]\n\n \"\"\"\n if not namespaces:\n namespaces = NAMESPACES_DEFAULT\n\n if type(aUri) == rdflib.term.URIRef:\n # we have a URI: try to create a qName\n stringa = aUri.toPython()\n for aNamespaceTuple in namespaces:\n try: # check if it matches the available NS\n if stringa.find(aNamespaceTuple[1].__str__()) == 0:\n if aNamespaceTuple[0]: # for base NS, it's empty\n stringa = aNamespaceTuple[0] + \":\" + stringa[len(aNamespaceTuple[1].__str__()):]\n else:\n prefix = inferNamespacePrefix(aNamespaceTuple[1])\n if prefix:\n stringa = prefix + \":\" + stringa[len(aNamespaceTuple[1].__str__()):]\n else:\n stringa = \":\" + stringa[len(aNamespaceTuple[1].__str__()):]\n except:\n stringa = \"error\"\n\n elif type(aUri) == rdflib.term.Literal:\n stringa = \"\\\"%s\\\"\" % aUri # no string casting so to prevent encoding errors\n else:\n # print(type(aUri))\n if type(aUri) == type(u''):\n stringa = aUri\n else:\n stringa = aUri.toPython()\n return stringa\n\n\n\n\ndef inferNamespacePrefix(aUri):\n \"\"\"\n From a URI returns the last bit and simulates a namespace prefix when rendering the ontology.\n\n eg from <'http://www.w3.org/2008/05/skos#'>\n it returns the 'skos' string\n \"\"\"\n stringa = aUri.__str__()\n try:\n prefix = stringa.replace(\"#\", \"\").split(\"/\")[-1]\n except:\n prefix = \"\"\n return prefix\n","sub_path":"src/libs/rdf_utils/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":4701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"83571333","text":"import logging\n\nfrom elftools.elf.elffile import ELFFile\nfrom elftools.elf.relocation import RelocationSection\nfrom elftools.elf.sections import SymbolTableSection\nfrom unicorn import UC_PROT_ALL\n\nfrom androidemu.internal import get_segment_protection, arm\nfrom androidemu.internal.module import Module\nfrom androidemu.internal.symbol_resolved import SymbolResolved\n\nlogger = logging.getLogger(__name__)\n\n\nclass Modules:\n\n \"\"\"\n :type emu androidemu.emulator.Emulator\n :type modules list[Module]\n \"\"\"\n def __init__(self, emu):\n self.emu = emu\n self.modules = list()\n self.symbol_hooks = dict()\n\n def add_symbol_hook(self, symbol_name, addr):\n self.symbol_hooks[symbol_name] = addr\n\n def find_symbol(self, addr):\n for module in self.modules:\n if addr in module.symbol_lookup:\n return module.symbol_lookup[addr]\n return None, None\n\n def load_module(self, filename):\n logger.debug(\"Loading module '%s'.\" % filename)\n\n with open(filename, 'rb') as fstream:\n elf = ELFFile(fstream)\n\n dynamic = elf.header.e_type == 'ET_DYN'\n\n if not dynamic:\n raise NotImplementedError(\"Only ET_DYN is supported at the moment.\")\n\n # Parse program header (Execution view).\n\n # - LOAD (determinate what parts of the ELF file get mapped into memory)\n load_segments = [x for x in elf.iter_segments() if x.header.p_type == 'PT_LOAD']\n\n # Find bounds of the load segments.\n bound_low = 0\n bound_high = 0\n\n for segment in load_segments:\n if segment.header.p_memsz == 0:\n continue\n\n if bound_low > segment.header.p_vaddr:\n bound_low = segment.header.p_vaddr\n\n high = segment.header.p_vaddr + segment.header.p_memsz\n\n if bound_high < high:\n bound_high = high\n\n # Retrieve a base address for this module.\n load_base = self.emu.memory.mem_reserve(bound_high - bound_low)\n\n for segment in load_segments:\n prot = get_segment_protection(segment.header.p_flags)\n prot = prot if prot is not 0 else UC_PROT_ALL\n\n self.emu.memory.mem_map(load_base + segment.header.p_vaddr, segment.header.p_memsz, prot)\n self.emu.memory.mem_write(load_base + segment.header.p_vaddr, segment.data())\n\n # Parse section header (Linking view).\n dynsym = elf.get_section_by_name(\".dynsym\")\n dynstr = elf.get_section_by_name(\".dynstr\")\n\n # Resolve all symbols.\n symbols_resolved = dict()\n\n for section in elf.iter_sections():\n if not isinstance(section, SymbolTableSection):\n continue\n\n itersymbols = section.iter_symbols()\n next(itersymbols) # Skip first symbol which is always NULL.\n for symbol in itersymbols:\n symbol_address = self._elf_get_symval(elf, load_base, symbol)\n if symbol_address is not None:\n symbols_resolved[symbol.name] = SymbolResolved(symbol_address, symbol)\n\n # Relocate.\n for section in elf.iter_sections():\n if not isinstance(section, RelocationSection):\n continue\n\n for rel in section.iter_relocations():\n sym = dynsym.get_symbol(rel['r_info_sym'])\n sym_value = sym['st_value']\n\n rel_addr = load_base + rel['r_offset'] # Location where relocation should happen\n rel_info_type = rel['r_info_type']\n\n # Relocation table for ARM\n if rel_info_type == arm.R_ARM_ABS32:\n # Create the new value.\n value = load_base + sym_value\n\n # Write the new value\n self.emu.mu.mem_write(rel_addr, value.to_bytes(4, byteorder='little'))\n elif rel_info_type == arm.R_ARM_GLOB_DAT or \\\n rel_info_type == arm.R_ARM_JUMP_SLOT or \\\n rel_info_type == arm.R_AARCH64_GLOB_DAT or \\\n rel_info_type == arm.R_AARCH64_JUMP_SLOT:\n # Resolve the symbol.\n if sym.name in symbols_resolved:\n value = symbols_resolved[sym.name].address\n\n # Write the new value\n self.emu.mu.mem_write(rel_addr, value.to_bytes(4, byteorder='little'))\n elif rel_info_type == arm.R_ARM_RELATIVE or \\\n rel_info_type == arm.R_AARCH64_RELATIVE:\n if sym_value == 0:\n # Load address at which it was linked originally.\n value_orig_bytes = self.emu.mu.mem_read(rel_addr, 4)\n value_orig = int.from_bytes(value_orig_bytes, byteorder='little')\n\n # Create the new value\n value = load_base + value_orig\n\n # Write the new value\n self.emu.mu.mem_write(rel_addr, value.to_bytes(4, byteorder='little'))\n else:\n raise NotImplementedError()\n else:\n logger.error(\"Unhandled relocation type %i.\" % rel_info_type)\n\n # Store information about loaded module.\n module = Module(filename, load_base, bound_high - bound_low, symbols_resolved)\n self.modules.append(module)\n return module\n\n def _elf_get_symval(self, elf, elf_base, symbol):\n if symbol.name in self.symbol_hooks:\n return self.symbol_hooks[symbol.name]\n\n if symbol['st_shndx'] == 'SHN_UNDEF':\n # External symbol, lookup value.\n target = self._elf_lookup_symbol(symbol.name)\n if target is None:\n # Extern symbol not found\n if symbol['st_info']['bind'] == 'STB_WEAK':\n # Weak symbol initialized as 0\n return 0\n else:\n logger.error('=> Undefined external symbol: %s' % symbol.name)\n return None\n else:\n return target\n elif symbol['st_shndx'] == 'SHN_ABS':\n # Absolute symbol.\n return elf_base + symbol['st_value']\n else:\n # Internally defined symbol.\n return elf_base + symbol['st_value']\n\n def _elf_lookup_symbol(self, name):\n for module in self.modules:\n if name in module.symbols:\n symbol = module.symbols[name]\n\n if symbol.address != 0:\n return symbol.address\n\n return None\n\n def __iter__(self):\n for x in self.modules:\n yield x\n","sub_path":"androidemu/internal/modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":7078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"470479527","text":"#_____________________________________________________________________\r\n#\t\tReprésentation de champ électrique d'un segment chargé########\r\n#\tImad ABIED\r\n#\t16/06/2019\r\n#_____________________________________________________________________\r\n\r\n#parametres de fil: le programme n'est pas valable que pour Ax=Bx=0\r\nAy= -2\r\nAx= 0 # a ne pas modifier\r\nBy= 2\r\nBx= 0 # a ne pas modifier\r\ndensite_lin= 57*10**(-12)\r\n\r\n#parametres d'affichage:\r\ngrille= 0.5\r\nplein_echelle=6\r\nscale=1\r\n\r\n#contantes physiques:\r\nPER_VIDE= 8.85418782*10**(-12)\r\n\r\n#programme:\r\nimport math\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nclass Vecteur2D:\r\n\tdef __init__(self,x,y,Dx,Dy):\r\n\t\tself.x=x\r\n\t\tself.y=y\r\n\t\tself.Dx=Dx\r\n\t\tself.Dy=Dy\r\n\r\n\tdef plot(self,color=\"red\"):\r\n\t\tX=[self.x,self.x+self.Dx]\r\n\t\tY=[self.y,self.y+self.Dy]\r\n\t\tplt.plot(X,Y,color)\r\n\r\nm= scale*densite_lin/(4*math.pi*PER_VIDE)\r\nfor x in np.arange(0.5,plein_echelle,grille):\r\n\r\n\tfor y in np.arange(-plein_echelle,plein_echelle,grille):\r\n\r\n\t\tteta1=math.atan((y-Ay)/x)\r\n\t\tteta2=math.atan((By-y)/x)\r\n\r\n\t\ttmp=m/x\r\n\t\tDx=tmp*(math.sin(teta1)+math.sin(teta2))\r\n\t\tDy=tmp*(math.cos(teta1)-math.cos(teta2))\r\n\r\n\t\tExy=Vecteur2D(x,y,Dx,Dy)\r\n\t\tExy.plot()\r\n\r\n\t\tE_xy=Vecteur2D(-x,y,-Dx,Dy)\r\n\t\tE_xy.plot()\r\n\r\nfil=Vecteur2D(Ax,Ay,Bx-Ax,By-Ay)\r\nfil.plot(\"black\")\r\n\r\nplt.show()\r\n","sub_path":"champ_electrostatique_fil_charge.py","file_name":"champ_electrostatique_fil_charge.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"109386455","text":"###############################################################################\n####### Pywaremon: Glance on your computer status #######\n####### Works on everything running *NIX, Mac, Windows, anything Python #######\n####### https://github.com/NamasteJasutin/pywaremon #######\n###############################################################################\n### These values may be changed. Please read the notes !!! ###\n# Refresh = default refresh rate, aka the time for intervals (in seconds). Can be float, e.g. 0.2\n# But I like 0.5 !\nrefresh = 0.5\n# At the bottom are some waves, at least, it aims to be.\n# Set this to (True) to enable, or (False) to disable this amazing feature. I mean. Why should you?\ndowave = True\n# The top and bottom banners (Title / Wavey thingy) change color. Same as before:\n# Set this to (True) to enable, or (False) to disable this amazing feature.\nchangeColor = True\n# Below setting is for getting your external IP address.\n# To disable calling to the outside world, disable this.\nUSESERVICES = True\n\n# The following setting will change the character used to define the look\n# The outer edges, as seen when running the script, are made of:\neC = '\\033[97m╳'\neL = '\\033[97m╲'\neF = '\\033[97m╱'\n# Get your ascii codes here : https://theasciicode.com.ar #\n###########################################################\n######### - BE CAREFUL WITH TOUCHING CODE BELOW - #########\n\nimport psutil, os, time, datetime, sys, socket, requests, platform\nfrom decimal import Decimal\n\n\ndef cls():\n if os.name == 'nt':\n os.system('cls')\n else:\n os.system('clear')\n\n\nif len(sys.argv) > 1:\n try:\n cls()\n refresh = float(sys.argv[1])\n except:\n print(\"Argument for refresh-rate needs to be a float, e.g. '2.5' or '0.3'.\")\n print(f\"Not '{sys.argv[1]}'. For now, the default of {refresh} will be used\")\n time.sleep(5)\n pass\n\n\n## CREATE OBJECT ##\n\nclass pClr:\n P = '\\033[95m'\n B = '\\033[94m'\n G = '\\033[92m'\n Y = '\\033[93m'\n R = '\\033[91m'\n E = '\\033[0m'\n b = '\\033[1m'\n u = '\\033[4m'\n i = '\\033[3m'\n\n\ndef translate(value, leftMin, leftMax, rightMin, rightMax):\n # Converts value FROM=leftMin, leftMax | TO=rightMin,rightMax\n # Figure out how 'wide' each range is\n leftSpan = leftMax - leftMin\n rightSpan = rightMax - rightMin\n\n # Convert the left range into a 0-1 range (float)\n valueScaled = float(value - leftMin) / float(leftSpan)\n\n # Convert the 0-1 range into a value in the right range.\n return rightMin + (valueScaled * rightSpan)\n\n\ndef progBar(input, length, *reverse):\n ftab = ''\n space = length - 5\n progress = translate(input, 0, 100, 0, int(space))\n inputlen = int(len(str(input)))\n # seperate = 5 - inputlen\n # oT = round((seperate / 2) - 0.2)\n # oF = round((seperate / 2) - 0.2)\n # fS = ' ' * oT\n # lS = ' ' * oF\n if reverse:\n fill = '░' * int(progress)\n space = '▓' * (int(space) - int(progress))\n elif not reverse:\n fill = '▓' * int(progress)\n space = '░' * (int(space) - int(progress))\n\n if inputlen == 5:\n ftab = ''\n elif inputlen == 4:\n ftab = tab\n elif inputlen == 3:\n ftab = f\"{tab} \"\n msg = f\"{fill}{space}{ftab}{input}%{tab}\"\n return str(msg)\n\n\ndef k2m(input):\n global kb2\n kb = int(input)\n kb2 = int(input)\n if len(str(kb)) > 11:\n mb = int(kb / 1000 / 1000)\n mb = str(mb)\n mb = f\"{mb[:-3]}.{mb[-2:]}\"\n st = 'GB'\n else:\n mb = int(kb / 1000 / 1000)\n mb = f\"{mb}\"\n st = \"MB\"\n return mb, st\n\n\ndef getIP():\n if USESERVICES == True:\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"1.1.1.1\", 80))\n ipaddr = (s.getsockname()[0])\n s.close\n except:\n ipaddr = 'No network'\n else:\n ipaddr = 'Disabled'\n return ipaddr\n\n\ndef outerIP():\n if USESERVICES == True:\n try:\n ip = requests.get('https://api.ipify.org?format=json').text\n ip = ip[7:-2]\n except:\n ip = 'No network'\n else:\n ip = 'Disabled'\n return ip\n\n\ndef c2g(input):\n kh = float(input)\n if len(str(kh)) > 4:\n gh = str(kh / 1000)\n gh = f\"{gh[:4]} Ghz\"\n else:\n gh = str(kh / 1000)\n gh = f\"{gh} Mhz\"\n return gh\n\n\ndef getTemp():\n try:\n temps = psutil.sensors_temperatures()\n for mon in temps:\n return int(temps[mon][0][1])\n except:\n return int('0')\n\n\ndef add0(data):\n data = str(data)\n if int(len(data)) < 2:\n output = f\"0{data}\"\n else:\n output = data\n return str(output)\n\n\ndef osLen():\n ostype = platform.platform()\n oslen = int(len(ostype))\n maxlen = 47\n seperate = maxlen - oslen\n oT = round((seperate / 2) + 0.2)\n oF = round((seperate / 2) - 0.2)\n total = int(len(str(ostype))) + oT + oF\n if int(len(str(ostype))) > 47:\n ostype = f\"{ostype[:46]}…\"\n if int(len(str(total))) > 47:\n oF -= 1\n total = int(len(str(ostype))) + oT + oF\n oT = int(oT)\n oF = int(oF)\n return ostype, oT, oF, int(total)\n\n\n## END OF OBJECT ##\n\ngo = True\ntab = '\\t'\nnwl = '\\n'\nbck = '\\b'\nlocIP = getIP()\noutIP = outerIP()\ncolor = time.localtime()[:-1]\ncolors = [pClr.P, pClr.B, pClr.G, pClr.Y, pClr.R]\nostype = platform.platform()\noslen = osLen()\ncWave = [\"⁓\", \"~\", \"⁓\", \"⍨\", \"⁓\", \"~\"]\niWave = 0\ncpu_user_av = float(0)\ncpu_system_av = float(0)\ncpu_idle_av = float(0)\ncpu_user_prev = float(0)\ncpu_system_prev = float(0)\ncpu_idle_prev = float(0)\n\n\ndef averager(cputype, value):\n global cpu_idle_av, cpu_system_av, cpu_system_prev, cpu_user_prev, cpu_system_prev, cpu_idle_prev\n if cputype == 'u':\n calc = (value + cpu_user_prev) / 2\n cpu_user_av = calc\n cpu_user_prev = value\n elif cputype == 'i':\n calc = (value + cpu_idle_prev) / 2\n cpu_idle_av = calc\n cpu_idle_prev = value\n elif cputype == 's':\n calc = (value + cpu_system_prev) / 2\n cpu_system_av = calc\n cpu_system_prev = value\n # calc = value + cpuvar[1]\n # cpuvar[0] = calc\n # cpuvar[1] = value\n calc = Decimal(calc).quantize(Decimal('.1'))\n return calc\n\n\ndef tWave():\n global iWave, cWave, sWave, leWave, dowave\n # sWave = f\"{cWave[iWave::1]}{cWave[:iWave:1]}\"\n sWave = ''.join(str(e) for e in cWave[iWave::1])\n sWave += ''.join(str(e) for e in cWave[:iWave:1])\n leWave = ''.join(str(e) for e in sWave)\n theWave = leWave * 7\n theWave = theWave[1::]\n if iWave == 5:\n iWave = 0\n else:\n if dowave == True:\n iWave += 1\n return str(theWave)\n\n\nprint(\"Loading. Please wait. Just grabbing stuff here, hold on buddy!\")\nwhile go == True:\n try:\n mem = psutil.virtual_memory()\n cpuf = psutil.cpu_freq()\n cputp = psutil.cpu_times_percent()\n disk = psutil.disk_usage('/')\n if changeColor == True:\n color = translate(int(str(time.localtime()[5])), 0, 60, 0, 4)\n else:\n color = 1\n hour = add0(time.localtime()[3])\n mint = add0(time.localtime()[4])\n scnd = add0(time.localtime()[5])\n # if int(len(scnd)) < 2:\n # scnd = f\"0{str(int(scnd))}\"\n second = str(scnd)[-1:]\n color = int(color)\n rndClr = colors[color]\n if second == 1 or second == 3 or second == 5 or second == 7 or second == 9:\n tS = ':'\n else:\n tS = ' '\n if int(len(k2m(mem[1])[0])) < 5:\n mT = 2\n else:\n mT = 1\n\n cls()\n print(f\"{eF}{eC * ((6 * 8) - 1)}{eL}\")\n print(f\"{eC}{eF} {rndClr} Pywaremon -xJustiinsane- Exit with CTRL+C {pClr.E} {eL}{eC}\")\n if os.name:\n print(f\"{eC}{' ' * osLen()[1]}{pClr.b}{osLen()[0]}{pClr.E}{' ' * osLen()[2]}{eC}\")\n print(f\"{eC}{tab * 6}{eC}\")\n print(f\"{eC} {pClr.R}Local time{tab}{hour}{tS}{mint}{tS}{scnd}{tab * 3}{pClr.E}{eC}\")\n print(\n f\"{eC} {pClr.R}Date{tab * 2}{time.localtime()[2]}-{time.localtime()[1]}-{time.localtime()[0]} Day {time.localtime()[6]}/7 {time.localtime()[7]}/365{tab}{pClr.E}{eC}\")\n print(f\"{eC}{tab * 6}{eC}\")\n if int(len(c2g(cpuf[0]))) < 8:\n sT = 2\n else:\n sT = 1\n print(f\"{eC} {pClr.B}CPU{tab * 2}Clock:{tab}{c2g(cpuf[0])}/{c2g(cpuf[2])}{pClr.E}{tab * sT}{eC}\")\n print(\n f\"{eC} {pClr.B}Usage{tab * 2}User:{tab}{progBar(averager('u', cputp[0]), 20)}{pClr.E}{eC}{nwl}{eC}{pClr.B}{tab * 2}System:{tab}{progBar(averager('s', cputp[2]), 20)}{pClr.E}{eC}{nwl}{eC}{pClr.B}{tab * 2}Idle:{tab}{progBar(averager('i', cputp[3]), 20, True)}{pClr.E}{eC}\")\n print(f\"{eC}{tab * 6}{eC}\")\n print(\n f\"{eC} {pClr.P}Memory{tab}Using:{tab}{k2m(mem[3])[0]}/{k2m(mem[0])[0]} {k2m(mem[0])[1]}{tab * 2}{pClr.E}{eC}{nwl}{eC}{pClr.P}{tab * 2}{progBar(mem[2], 28, True)}{pClr.E}{eC}\")\n print(f\"{eC}{tab * 6}{eC}\")\n if int(len(k2m(disk[1])[0])) < 7:\n sT = 2\n else:\n sT = 1\n if int(len(str(disk[3]))) < 4:\n sT2 = 2\n else:\n sT2 = 1\n print(\n f\"{eC} {pClr.G}Storage{tab}Using:{tab}{k2m(disk[1])[0]}/{k2m(disk[0])[0]} {k2m(disk[0])[1]}{tab * sT}{pClr.E}{eC}{nwl}{eC}{pClr.G}{tab * 2}{progBar(disk[3], 28, True)}{pClr.E}{eC}\")\n print(f\"{eC}{tab * 6}{eC}\")\n print(\n f\"{eC} {pClr.Y}IP Addr{tab}Local:{tab}{locIP}{tab * 2}{pClr.E}{eC}{nwl}{eC}{pClr.Y}{tab * 2}Outer:{tab}{outIP}{tab * 2}{pClr.E}{eC}\")\n print(f\"{eC}{tab * 6}{eC}\")\n if hasattr(psutil, \"sensors_temperatures\"):\n print(f\"{eC} {pClr.R}Temp{tab * 2}CPU:{tab}{getTemp()}°C {tab * 3}{pClr.E}{eC}\")\n print(f\"{eC}{tab * 6}{eC}\")\n print(f\"{eC}{eL} {rndClr} {tWave()} {pClr.E} {eF}{eC}\")\n # print(f\"{eC*3}{tab*5} {eC*3}\")\n print(f\"{eL}{eC * ((6 * 8) - 1)}{eF}\")\n time.sleep(refresh)\n except KeyboardInterrupt:\n go = False\n print(\"\\a\")\n sys.exit('Keyboard Interuption!')\n except:\n go = False\n print(\"Other error occured\")\n\n####### https://github.com/NamasteJasutin/pywaremon #######\n###########################################################","sub_path":"System_inf.py","file_name":"System_inf.py","file_ext":"py","file_size_in_byte":10386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"294529958","text":"\"\"\" Generic message handler \n- write message received to log\n- determine if message is formatted correctly\n- call train_model module on data files \n\"\"\"\n\nimport os\nimport sys\nimport json\nimport inspect\nfrom path import Path\nfrom utils.zmq_connection import zmq_connect\nfrom utils.manifest import generateFileManifest\n\n# from utils.generate_instructions import generate_instructions\n\n\ndef _do_work(filenames):\n # This is the only unique thing to the handler. You have to\n # implement the method that operates on a file.\n new_filenames = []\n # new_filenames = train_model(filenames)\n\n data = []\n if len(new_filenames) > 0:\n multi_file_manifest = {}\n context, socket = zmq_connect(port=5560, pattern=\"REQ\")\n for f in new_filenames:\n single_file_manifest = generateFileManifest(f, purpose=\"train_model\")\n for k in single_file_manifest:\n multi_file_manifest[k] = single_file_manifest[k]\n\n socket.send_string(json.dumps(multi_file_manifest))\n repl = socket.recv()\n print(f\"\\nGot {repl}\")\n else:\n n = inspect.stack()[0][3]\n print(\"new_filenames is empty\")\n print(f\"\\n{n} failed on {filenames}\")\n\n return new_filenames\n\n\ndef lambda6_handle_message(decoded_message):\n json_decoded = json.loads(decoded_message)\n print(f\"\\nHandling message: {json_decoded}\")\n print(json_decoded)\n\n filenames = []\n for k in json_decoded:\n file_data = json_decoded[k]\n filename = file_data[\"path\"][0]\n print(f\"\\nfilename {filename}\")\n filenames.append(filename)\n\n new_filenames = _do_work(filename)\n print(f\"\\nnew files {new_filenames}\")\n print(f\"\\nDone handling message: {json_decoded}\")\n return new_filenames\n\n\ndef main(json_string):\n \"\"\" main gets invoked because the listener does a system call to it.\n The listener passes to main the json string.\n Therefore, when testing, make the json string in the if __main__ block.\n \"\"\"\n\n lambda6_handle_message(json_string)\n\n\nif __name__ == \"__main__\":\n # execute only if run as a script\n if os.path.isfile(sys.argv[1]):\n with open(sys.argv[1], \"r\") as file:\n json_string = file.read()\n else:\n json_string = sys.argv[1]\n\n main(json_string)\n","sub_path":"zeromq/lambda6_handle_message_5559.py","file_name":"lambda6_handle_message_5559.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"329655703","text":"import boto3\nfrom boto3.dynamodb.conditions import Attr\nimport os\n\nclass DynamoDB:\n\n dynamoDB = None\n\n def __init__(self):\n self.dynamoDB = boto3.resource('dynamodb', region_name=\"us-west-2\",\n aws_access_key_id=os.environ[\"aws_access_key_id\"],\n aws_secret_access_key=os.environ[\"aws_secret_access_key\"])\n\n def createUser(self, user):\n self.dynamoDB.Table('User').put_item(Item=user.to_save())\n return user\n\n def getUsers(self):\n response = self.dynamoDB.Table('User').scan()\n user = response['Items']\n if len(user) == 0:\n return []\n else:\n return user\n\n def getUser(self, id):\n response = self.dynamoDB.Table('User').get_item(Key={\"id\":id})\n user = response['Item']\n return user\n\n def getLatestUser(self):\n response = self.dynamoDB.Table('User').scan(Limit=6)\n user = response['Items']\n if len(user) == 0:\n return []\n else:\n return user\n\n def getUserByEmail(self, email):\n response = self.dynamoDB.Table('User').scan(FilterExpresssion=Attr('email').eq(email))\n user = response['Items']\n if len(user) == 0:\n return []\n else:\n return user\n\n def confirmLogin (self, email, password):\n response = self.dynamoDB.Table('User').scan(FilterExpression=Attr('email').eq(email) & Attr('password').eq(password))\n user = response['Items']\n if len(user) == 0:\n return None\n else:\n return user[0]\n\n def createContest(self, contest):\n self.dynamoDB.Table('Contest').put_item(Item=contest.to_save())\n return contest\n\n def getUserContest(self, user_id): #Esta pendiente\n response = self.dynamoDB.Table('Contest').scan(FilterExpression=Attr('user_id').eq(user_id))\n contest = response['Items']\n if len(contest) == 0:\n return []\n else:\n return contest\n\n def getContest(self, id):\n response = self.dynamoDB.Table('Contest').get_item(Key={\"id\":id})\n contest = response['Item']\n return contest\n\n def getContestAll(self):\n response = self.dynamoDB.Table('Contest').scan()\n contest = response['Items']\n if len(contest) == 0:\n return []\n else:\n return contest\n\n def getURLContest(self, url):\n response = self.dynamoDB.Table('Contest').scan(FilterExpression=Attr('url').eq(url))\n contest = response['Items']\n if len(contest) == 0:\n return []\n else:\n return contest\n\n def updateContest(self, contest):\n self.dynamoDB.Table('Contest').update_item(\n Key={\"id\":contest.id},\n UpdateExpression= 'SET #names = :names, #baner = :banner, #date_ini = :date_ini, #deadline = :deadline, #description = :description',\n ExpressionAttributeValues={\n ':names':contest.names,\n ':banner': contest.banner,\n ':date_ini': contest.date_ini,\n ':deadline':contest.deadline,\n ':description': contest.description\n },\n ExpressionAttributeNames={\n '#names': \"names\",\n '#banner': \"baner\",\n '#date_ini': \"date_ini\",\n '#deadline': \"deadline\",\n '#description': \"description\"\n }\n )\n return self.getContest(contest.id)\n\n def deleteContest(self, id):\n self.dynamoDB.Table('Contest').delete_item(Key={\"id\":id})\n\n def getUserContestNumber(self, user_id): #Revisar\n response = self.dynamoDB.Table('Contest').scan(FilterExpression=Attr('user_id').eq(user_id))\n contest = response['Items']\n return len(contest)\n\n def getContestVideoNumber(self, contest_id): #Revisar\n response = self.dynamoDB.Table('Video').scan(FilterExpression=Attr('contest_id').eq(contest_id))\n video = response['Items']\n return len(video)\n\n def getUserVideoNumber(self, user_id):\n response = self.dynamoDB.Table('Video').scan(FilterExpression=Attr('user_id').eq(user_id))\n video = response['Items']\n return len(video)\n\n def createVideo(self,video): #No existe\n self.dynamoDB.Table('Video').put_item(Item=video.to_save())\n return video\n\n def getContestVideo(self, contest_id):\n response = self.dynamoDB.Table('Video').scan(FilterExpression = Attr('contest_id').eq(contest_id))\n video = response['Items']\n if len(video) == 0:\n return []\n else:\n return video\n\n def getContestVideoNum(self, contest_id):\n response = self.dynamoDB.Table('Video').scan(FilterExpression = Attr('contest_id').eq(contest_id))\n video = response['Items']\n return len(video)\n\n def getVideoByID(self, id):\n response = self.dynamoDB.Table('Video').get_item(Key = {\"id\":id})\n video = response['Item']\n return video\n\n def getContestOkVideos(self, contest_id):\n response = self.dynamoDB.Table('Video').scan(FilterExpression=Attr('contest_id').eq(contest_id) & Attr('status').eq('OK'))\n video = response['Items']\n if len(video) == 0:\n return []\n else:\n return video\n\n def getOkVideos(self):\n response = self.dynamoDB.Table('Video').scan(FilterExpression=Attr('status').eq('OK'))\n video = response['Items']\n if len(video) == 0:\n return []\n else:\n return video\n def getLatestVideo(self):\n # response = self.dynamoDB.Table('Video').scan(FilterExpression=Attr('status').eq('OK'),Limit=6)\n response = self.dynamoDB.Table('Video').scan(FilterExpression=Attr('status').eq('OK'))\n video = response['Items']\n if len(video) == 0:\n return []\n else:\n return video\n\n def getProcessVideo(self):\n response = self.dynamoDB.Table('Video').scan(FilterExpression=Attr('status').eq('On Process'))\n video = response['Items']\n if len(video) == 0:\n return []\n else:\n return video\n\n def updateStatusVideo(self, id):\n self.dynamoDB.Table('Video').update_item(\n Key={\"id\":id},\n UpdateExpression='SET #status = :status',\n ExpressionAttributeValues={\n ':status': \"OK\"\n },\n ExpressionAttributeNames={\n '#status': \"status\"\n }\n )\n return self.getVideoByID(id)\n\n def deleteVideo(self, id):\n self.dynamoDB.Table('Video').delete_item(Key={\"id\":id})\n\n def user_url_exist(self, url):\n response = self.dynamoDB.Table('Contest').scan(FilterExpression=Attr('url').eq(url))\n video = response['Items']\n if len(video) == 0:\n return False\n else:\n return True","sub_path":"uniandes/cloud/aws/DynamoDB.py","file_name":"DynamoDB.py","file_ext":"py","file_size_in_byte":6968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"2233988","text":"\nVERSION = (0, 2, 0)\n__version__ = \".\".join([str(s) for s in VERSION])\n\n__title__ = \"mkrl\"\n__description__ = (\n \"Build automation tool for C/C++\"\n)\n__url__ = \"https://github.com/mojzu/mkrl\"\n__author__ = \"mojzu\"\n__email__ = \"mail@mojzu.net\"\n__license__ = \"Unlicence\"\n","sub_path":"mkrl/mkrl/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"486786171","text":"from collections import deque\nclass Solution(object):\n # Time Complexity: O(n), where n is the number of nodes in the tree.\n # Space Complexity: O(n), space used by the queue\n # Did this code successfully run on Leetcode: yes\n # Any problem you faced while coding this: nope\n\n # Your code here along with comments explaining your approach\n\n # This approach uses a BFS where every level is stored in a temporary array\n # and after visiting the entire level, the maximum of that level is added to the result\n def largestValuesBFS(self, root):\n retVal = []\n if not root:\n return retVal\n\n q = deque()\n q.appendleft(root)\n\n while len(q) != 0:\n temp = []\n for i in range(len(q)):\n curr = q.pop()\n if curr.left != None:\n q.appendleft(curr.left)\n if curr.right != None:\n q.appendleft(curr.right)\n temp.append(curr.val)\n retVal.append(max(temp))\n\n return retVal\n\n#------------------------------------------------------x---------------------------------------------------------------#\n\n # Time Complexity: O(n), where n is the number of nodes in the tree.\n # Space Complexity: O(h), where h is the maximum height of the tree.\n # Did this code successfully run on Leetcode: yes\n # Any problem you faced while coding this: nope\n\n # Your code here along with comments explaining your approach\n\n # this approach uses a DFS where for every level the maximum is added to the result\n # the level is tracked using the height of every value in the tree.\n def __init__(self):\n self.retVal = []\n\n def largestValuesDFS(self, root):\n if not root:\n return self.retVal\n\n self.dfs(root, 0)\n return self.retVal\n\n def dfs(self, root, height):\n if not root:\n return\n\n if len(self.retVal) == height:\n self.retVal.append(root.val)\n else:\n self.retVal[height] = max(self.retVal[height], root.val)\n\n self.dfs(root.left, height + 1)\n self.dfs(root.right, height + 1)\n","sub_path":"largestValRowTree.py","file_name":"largestValRowTree.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"301561642","text":"import numpy as np\nfrom ..utils import get_g\n\n\nclass IndirectBias():\n \"\"\" The class for computing indirect bias between a pair of words.\n \"\"\" \n def __init__(self, E, g=None):\n \"\"\"\n Args: \n E (WE class object): Word embeddings object.\n kwargs:\n g (np.array): Gender direction.\n \"\"\"\n if g is None:\n g = get_g(E)\n assert len(g) == E.dim \n self.g = g\n self.E = E\n\n def _pair_idb(self, w, v, g):\n \"\"\"\n Args: \n w (np.array): The first word vector. \n v (np.array): The second word vector.\n g (np.array): Gender direction.\n \n Returns:\n idb (float): The indirect bias between the embeddings of\n `w` and `v`.\n \"\"\"\n \n w_orth = w - (np.dot(w, g)) * g\n v_orth = v - (np.dot(v, g)) * g\n dots = np.dot(w, v)\n orth_dots = np.dot(w_orth, v_orth)\n idb = (dots - orth_dots / (np.linalg.norm(w_orth) * np.linalg.norm(v_orth))) / (dots )\n return idb \n\n def fix(self, w, eps=1e-3):\n \"\"\"\n Args:\n w (np.array): word vector\n kwargs:\n eps (float): threshold. If the difference between the norm\n of `w` and 1, is greater than `eps`. Then \n normalize `w`.\n \n Returns:\n The normalized `w`.\n \n \"\"\"\n norm = np.linalg.norm(w)\n if np.abs(norm - 1) > eps:\n w /= norm\n return w \n \n def compute(self, w, v):\n \"\"\"\n Args: \n w (str): One of a pair of words. \n v (str): The other word from the pair.\n \n Returns:\n The indirect bias between the embeddings of `w` and `v`.\n \"\"\"\n if isinstance(w, str): w = self.E.v(w)\n if isinstance(v, str): v = self.E.v(v) \n w = self.fix(w) \n v = self.fix(v) \n return self._pair_idb(w, v, self.g)\n\n","sub_path":"fee/metrics/indirect_bias.py","file_name":"indirect_bias.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"538010960","text":"#!python\nfrom __future__ import print_function\n\nimport sys\nfrom collections import deque\nfrom math import log, floor\n\n# armin, list, index of next mote, num_moves by now\ndef result(a, l, i):\n if i >= len(l):\n #print('finito')\n return 0\n mote = l[i]\n if mote < a:\n #print('mangio', mote)\n return result(a+mote, l, i+1)\n\n # if I delete all motes from this on\n delete_cost = len(l) - i\n\n if a == 1: #I can't eat nothing , so I must delete!\n return delete_cost\n\n # if I add motes until I can eat this\n add_cost = int(floor(log(float(mote-1)/(a-1), 2) + 1))\n #print('se mangio: a={}, mote={}'.format(2**add_cost * (a - 1) + 1, mote))\n\n #sys.exit(1)\n return min(\n delete_cost,\n add_cost + result(2**add_cost * (a - 1) + 1, l, i)\n )\n\nif __name__ == '__main__':\n T = int(sys.stdin.readline().strip())\n #print('T:', repr(T))\n for t in range(T):\n a, n = [int(x) for x in sys.stdin.readline().strip().split(' ')]\n l = [int(x) for x in sys.stdin.readline().strip().split(' ')]\n l.sort()\n #print(l)\n #assert(len(l) == n)\n print(\"Case #{}: {}\".format(str(t+1), result(a, l, 0)))\n\n","sub_path":"solutions_2692487_1/Python/Davidinosauro/osmos2.py","file_name":"osmos2.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"160882608","text":"class Solution(object):\n def combinationSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n n = len(nums)\n if n == 0:\n return []\n dp = [ [] for j in xrange(target+1)]\n for i in xrange(n):\n # from large to small to remove the duplicate one\n for j in xrange(target,0,-1):\n if j >= nums[i]:\n # (i,j,nums[i]).p()\n if j % nums[i] == 0:\n dp[j] += [nums[i]] * (j/nums[i]),\n for k in xrange(1, j/nums[i]+1):\n dp[j] += [l+([nums[i]] * k) for l in dp[j-k*nums[i]] ]\n return dp[-1]\n\n ## dfs\n def combinationSum(self, candidates, target):\n \"\"\"\n :type candidates: List[int]\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n mem = {}\n def dfs(n):\n if n in mem:\n return mem[n]\n if n == 0:\n mem[n] = [[]]\n return [[]]\n res = []\n for num in candidates:\n if n >= num:\n res += [[num]+l for l in dfs(n-num) if len(l)==0 or num<=l[0]]\n mem[n] = res\n return res\n return dfs(target) \nif __name__ == '__main__':\n from minitest import *\n\n with test(Solution):\n Solution().combinationSum([2,3,6,7],7).must_equal([[2, 2, 3], [7]])\n Solution().combinationSum([1,2],4).must_equal([[1, 1, 1, 1], [2, 2], [1, 1, 2]])\n","sub_path":"python/leetcode/dynamic_programming/39_Combination_Sum.py","file_name":"39_Combination_Sum.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"342728750","text":"'''\n\nИскомый месяц\n\nНапишите функцию get_month(language, number), которая принимает на вход два аргумента language – язык ru или en и number – номер месяца (от 1 до 12) и возвращает название месяца на русском или английском языке.\n\nПримечание. Следующий программный код:\n\nprint(get_month('ru', 1))\nprint(get_month('ru', 12))\nprint(get_month('en', 1))\nprint(get_month('en', 10))\n\nдолжен выводить:\n\nянварь\nдекабрь\njanuary\noctober\n\n'''\n\n# объявление функции\ndef get_month(language, number): \n list_en_mon = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',\n 'October', 'November', 'December']\n list_ru_mon = ['Январь', 'Феврал��', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', \n 'Октябрь', 'Ноябрь', 'Декабрь']\n if lan.lower() == 'ru':\n return list_ru_mon[number - 1].lower()\n elif lan.lower() == 'en':\n return list_en_mon[number - 1].lower()\n \n\n# считываем данные\nlan = input()\nnum = int(input())\n\n# вызываем функцию\nprint(get_month(lan, num))","sub_path":"happy_pythoning_cource/Exams/14.1.5.Func_name_of_month_ru_en/14.1.5.Func_name_of_month_ru_en.py","file_name":"14.1.5.Func_name_of_month_ru_en.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"440017117","text":"withdraw = int (input(\"enter the withdrawl amount:\"))\n \ndef balance(func):\n def securebalance(intialamount):\n if withdraw > intialamount:\n print(f\"you dont have sufficent balance in your account \")\n elif withdraw < 0:\n print(f\"the withdraw ammount should be greater than the 0\") \n else:\n intialamount -= withdraw\n return intialamount\n return securebalance \n\n@balance\ndef initalbalance(num):\n return initalbalance\n\nprint(f\"remaining balance is {initalbalance(1000)}\")\n\n","sub_path":"Day-4/decs.py","file_name":"decs.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"343104862","text":"#!python3\n\"\"\"\nCreate a function called perimeter()\nThe input is a list.\nThe return value is the sum of all the numbers in the list\nadded together\n(2 points)\n\"\"\"\ndef perimeter(a):\n b = 0\n for i in range(len(a)):\n b = b + a[i-1]\n return b\n","sub_path":"task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"421468672","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Demo of training on HIPPIE.\"\"\"\n\nimport logging\nimport os\nimport time\n\nimport networkx as nx\n\nfrom lpe.dc import get_graph_from_csv\nfrom lpe.learn import Node2vecParams, PredictiveModel, embed\n\n__all__ = [\n 'get_hippie_graph',\n 'HIPPIE_URL',\n]\n\nlogger = logging.getLogger(__name__)\n\nHIPPIE_URL = 'http://cbdm-01.zdv.uni-mainz.de/~mschaefer/hippie/hippie_current.txt'\nDOWNLOADS = os.path.join(os.path.expanduser('~'), 'Downloads')\nPATH = os.path.join(DOWNLOADS, 'hippie.txt')\n\n\ndef get_hippie_graph() -> nx.Graph:\n \"\"\"Get the HIPPIE graph.\"\"\"\n return get_graph_from_csv(\n url=HIPPIE_URL,\n path=PATH,\n source_col=1,\n target_col=3,\n name='HIPPIE',\n source_prefix='ncbigene',\n target_prefix='ncbigene',\n )\n\n\ndef main():\n node2vec_params = Node2vecParams(n_components=32)\n graph = get_hippie_graph()\n\n version = time.strftime('%Y-%m-%d')\n save_directory = os.path.join(DOWNLOADS, f'hippie_test_{version}')\n model, result = embed(\n graph,\n node2vec_params=node2vec_params,\n save_directory=save_directory,\n )\n print(result)\n\n pm = PredictiveModel.load(save_directory)\n print(pm.predict_against('ncbigene:3679', graph))\n\n\nif __name__ == '__main__':\n logging.basicConfig(\n level=logging.INFO,\n format='[%(asctime)s] %(levelname)-8s %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n )\n main()\n","sub_path":"src/lpe/demos/hippie.py","file_name":"hippie.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"56257846","text":"# Passagem de uma viagem\nviagem1 = 0.50\nviagem2 = 0.45\ndistancia = float(input('Informe a distância percorrida na viagem: '))\nif distancia <= 200.0:\n preco = distancia * viagem1\n print('Preço: R${:.2f}'.format(preco))\n print('Distância: {:.2f} Km/h'.format(distancia))\nelse:\n preco = distancia * viagem2\n print('Preço: R${:.2f}'.format(preco))\n print('Distância: {:.2f} Km/h'.format(distancia))\n","sub_path":"primeiro-mundo/031.py","file_name":"031.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"124015136","text":"class Sorting:\n\tdef sorting(self, arr):\n\t\tn = len(arr)\n\n\t\tdef getMax(arr, endIndex):\n\t\t\tmaxVal = arr[0]\n\t\t\tidx = -1\n\t\t\tfor i in range(endIndex+1):\n\t\t\t\tif maxVal <= arr[i]:\n\t\t\t\t\tidx = i\n\t\t\t\t\tmaxVal = arr[i]\n\n\t\t\t#print(maxVal)\n\t\t\treturn idx\n\n\t\tdef swap(idx, arr):\n\t\t\ttemp = arr[idx]\n\t\t\tarr[idx] = arr[0]\n\t\t\tarr[0] = temp\n\n\t\tdef swapSort(arr):\n\t\t\tpos = n - 1\n\n\t\t\tfor i in range(n):\n\t\t\t\tmaxIdx = getMax(arr,pos)\n\t\t\t\tswap(maxIdx, arr) #bring the max to zeroth index\n\t\t\t\t#print(\"arr, pos\", arr, pos)\n\t\t\t\tswap(pos, arr) # swap the max with its correct position\n\t\t\t\t#print(\"arr, pos\", arr, pos)\n\t\t\t\tpos -= 1\n\n\n\t\tswapSort(arr)\n\n\n\n\narr = [6, 8, 1, 9, 3]\nsortArr = Sorting()\nsortArr.sorting(arr)\nprint(arr)\n\n\n\n\n\n","sub_path":"sorting_microsoft.py","file_name":"sorting_microsoft.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"430038026","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 ('duble_event', '0007_user_config'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='user_config',\n name='image_file',\n field=models.ForeignKey(blank=True, to='duble_event.Image_file', null=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"mysite/duble_event/migrations/0008_auto_20170623_1404.py","file_name":"0008_auto_20170623_1404.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"520414915","text":"import sys\nimport pygame\nfrom pygame.locals import *\nfrom Squid import Squid\nimport math\n\npygame.init()\nscreen_info = pygame.display.Info()\nscreen_size = (screen_info.current_w, screen_info.current_h)\nsize = (width, height) = (850, 480)\nscreen = pygame.display.set_mode(size)\nclock = pygame.time.Clock()\ncolor = (0, 127, 255)\nsquids = []\n\n\ndef main():\n for i in range(0, 10):\n squids.append(Squid((width // 2, height // 2)))\n while True:\n clock.tick(60)\n for event in pygame.event.get():\n if event.type == QUIT:\n sys.exit()\n if event.type == MOUSEBUTTONDOWN:\n mouse_pos = event.pos\n for i in squids:\n angle_difference = i.rotation - math.degrees(math.atan2(mouse_pos[0] - i.rect.center[0],\n mouse_pos[1] - i.rect.center[1]))\n if angle_difference > 180:\n angle_difference -= 360\n if angle_difference < -180:\n angle_difference += 360\n\n if angle_difference > 0:\n i.rotation += 1\n\n if angle_difference < 0:\n i.rotation -= 1\n\n screen.fill(color)\n for squid in squids:\n squid.update()\n for squid in squids:\n squid.draw(screen)\n\n\n\n pygame.display.flip()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"257798416","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 3 11:26:29 2018\n\n\"\"\"\n\"\"\"\nidea for function is to take polygon input (n pts) and a matrix size (mxk)\nthen output a matrix that has the endpoints\n [(0,0),(0,a.shape[1]),(a.shape[0],a.shape[1]),(a.shape[0],0)])\nand the otherpoints should be interpolated values between these endpoints\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport functions as fc\n\npoly1 = np.array([[2,3],[2,4],[4,4],[4,3]])\npoly2 = np.array([[3,5],[3,3.5],[5,3.5],[5,5]])\nmsh = 16\na1 = np.zeros((msh,msh,2))\na2 = np.zeros((msh,msh,2))\n# Set end_pts creates a matrix the same size as a, using the coordinates\n# of the polygon poly\n\ndef set_endPts(a,poly):\n a[0,0] = poly[0]\n a[0,a.shape[1]-1] = poly[1]\n a[a.shape[0]-1,a.shape[1]-1] = poly[2]\n a[a.shape[0]-1,0] =poly[3]\n #print(a[:,:,0])\n return a\n\n# get_pt_Matrix fills in the matrix created by the set_endPts function with \n# interpolated values\ndef get_pt_Matrix(A):\n a = A[:,:,0]\n b = A[:,:,1] \n a[0,:]=np.linspace(a[0,0],a[0,a.shape[1]-1],a.shape[1])\n a[a.shape[0]-1,:]=np.linspace(a[a.shape[0]-1,0],a[a.shape[0]-1,a.shape[1]-1],a.shape[1])\n b[0,:]=np.linspace(b[0,0],b[0,b.shape[1]-1],b.shape[1])\n b[b.shape[0]-1,:]=np.linspace(b[b.shape[0]-1,0],b[b.shape[0]-1,b.shape[1]-1],b.shape[1])\n for i in range(a.shape[1]):\n a[:,i]=np.linspace(a[0,i],a[a.shape[0]-1,i],a.shape[1])\n b[:,i]=np.linspace(b[0,i],b[b.shape[0]-1,i],b.shape[1])\n A[:,:,0] = a\n A[:,:,1] = b\n return A\n\ndef get_Interped_Matrix(a,poly):\n A1 = set_endPts(a,poly)\n A = get_pt_Matrix(A1)\n return A\ndef in_shade(pt,poly):\n in_shade = False\n ref = poly[1]\n V1 = poly[0]-ref\n V2 = poly[2]-ref\n Dt = pt-ref\n A = [V1,V2]\n A = np.transpose(A)\n Ainv = np.linalg.inv(A)\n alpha = np.dot(Ainv,Dt)\n if np.all(alpha>=0) and np.all(alpha<=1):\n in_shade = True\n return in_shade, pt, ref\n# I modified the in_shade code here to debug something in the main file but the original is unchanged.\nA1 = get_Interped_Matrix(a1,poly1)\n#A2 = get_Interped_Matrix(a2,poly2)\n# this part takes the matrix of the lower polygon to and the vertices of the\n# second polygon and outputs a finer mesh of 0s and 1s for shade or sun respectively\n\nSL = np.zeros((A1.shape[0],A1.shape[1]))\nfor i in range(A1.shape[1]):\n for j in range(A1.shape[0]):\n in_shadee,dt,reff = in_shade(A1[j,A1.shape[1]-1-i,:],poly2)\n test =(1-in_shadee)\n SL[i,j]=test\n\nprint(SL)\n#SL2 = get_SL(A1,poly2)\n#print(SL2)\nplt.scatter(poly1[:,0],poly1[:,1])\nplt.scatter(poly2[:,0],poly2[:,1])\n","sub_path":"untitled30.py","file_name":"untitled30.py","file_ext":"py","file_size_in_byte":2627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"388746285","text":"#have either read or select return something indicating reading failed inorder to display alternate html page\nimport spidev\nimport RPi.GPIO as GPIO\nimport time\nfrom time import sleep\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\nGPIO.setup(21,GPIO.OUT)\nGPIO.output(21,1)\n\n\ndef read():\n raw_adc=[0,0,0,0]\n voltages=[0,0,0,0]\n spi2=spidev.SpiDev()\n spi2.open(0,0)\n spi2.max_speed_hz=1350000\n buf=[[ 0x01, 0x00, 0x00],[ 0x01, 0x20, 0x00],[ 0x01, 0x40, 0x00],[ 0x01, 0x60, 0x00]]\n spi2.xfer2(buf[0])\n spi2.xfer2(buf[1])\n spi2.xfer2(buf[2])\n spi2.xfer2(buf[3])\n for i in range(4):\n raw_adc[i]=((buf[i][1] &3)<<8) +buf[i][2] #converts last 10 bits of data into an ADC reading\n voltages[i]=(raw_adc[i]*3.3)/1023 #converts ADC reading into a voltage\n #print(\"Ch {} - Ch{}:\".format(i,i+1))\n #print('{0:.3f} volts'.format( voltages[i]))#prints voltages to 3 decimal place\n return voltages\ni=1\nwhile i !=0:\n voltages=read()\n voltage=voltages[0]\n if voltage>=180:\n print(voltage)\n GPIO.outpuut(21,0)\n if voltage<180:\n print(voltage)\n GPIO.output(21,1)\n time.sleep(15)\n","sub_path":"reflow.py","file_name":"reflow.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"397505085","text":"from operator import itemgetter\n\nimport xgboost as xgb\n\nfrom lambdatrader.backtesting.marketinfo import BacktestingMarketInfo\nfrom lambdatrader.candlestick_stores.cachingstore import ChunkCachingCandlestickStore\nfrom lambdatrader.exchanges.enums import ExchangeEnum\nfrom lambdatrader.signals.data_analysis.datasets import create_pair_dataset_from_history\nfrom lambdatrader.signals.data_analysis.feature_sets import (\n get_small_feature_func_set_with_indicators,\n)\nfrom lambdatrader.signals.data_analysis.values import (\n make_binary_max_price_in_future,\n)\nfrom lambdatrader.utilities.utils import seconds\n\n\ndef cache_key(model_name):\n return 'dummy_model_{}'.format(model_name)\n\n\ndef save(model_name, model):\n from lambdatrader.shelve_cache import shelve_cache_save\n shelve_cache_save(cache_key(model_name), model)\n\nmarket_info = BacktestingMarketInfo(candlestick_store=\n ChunkCachingCandlestickStore.get_for_exchange(ExchangeEnum.POLONIEX))\n\n\nlatest_market_date = market_info.get_max_pair_end_time()\n\ndataset_symbol = 'BTC_LTC'\n\nday_offset = 90\n\ndataset_start_date = latest_market_date - seconds(days=day_offset, hours=24*365)\n# dataset_start_date = latest_market_date - seconds(days=day_offset, hours=24*200)\n# dataset_start_date = latest_market_date - seconds(days=day_offset, hours=24*120)\n# dataset_start_date = latest_market_date - seconds(days=day_offset, hours=24*90)\n# dataset_start_date = latest_market_date - seconds(days=day_offset, hours=24*60)\n# dataset_start_date = latest_market_date - seconds(days=day_offset, hours=24*30)\n# dataset_start_date = latest_market_date - seconds(days=day_offset, hours=24*7)\n# dataset_start_date = latest_market_date - seconds(days=day_offset, hours=24)\n# dataset_start_date = latest_market_date - seconds(days=day_offset, minutes=30)\n\ndataset_end_date = latest_market_date - seconds(days=day_offset)\n\ndataset_len = dataset_end_date - dataset_start_date\n\nincrease = 0.03\nnum_candles = 48\nvalue_func = make_binary_max_price_in_future(increase=increase, num_candles=num_candles)\nvalue_func_name = 'binary_max_price_{}_{}'.format(increase, num_candles)\n\n\n\ndataset = create_pair_dataset_from_history(market_info=market_info,\n pair=dataset_symbol,\n start_date=dataset_start_date,\n end_date=dataset_end_date,\n feature_functions=list(get_small_feature_func_set_with_indicators()),\n value_function=value_func,\n cache_and_get_cached=True,\n value_function_key=value_func_name)\n\nprint('created/loaded dataset\\n')\n\nfeature_names = dataset.get_first_feature_names()\n\nX = dataset.get_numpy_feature_matrix()\ny = dataset.get_numpy_value_array()\n\ntrain_ratio = 0.6\nval_ratio = 0.8\n\nn_samples = len(y)\nval_split = int(train_ratio * n_samples)\ntest_split = int(val_ratio * n_samples)\n\nX_train = X[:val_split]\ny_train = y[:val_split]\n\nX_val = X[val_split:test_split]\ny_val = y[val_split:test_split]\n\nX_test = X[test_split:]\ny_test = y[test_split:]\n\ndtrain = xgb.DMatrix(X_train, label=y_train, feature_names=feature_names)\ndval = xgb.DMatrix(X_val, label=y_val, feature_names=feature_names)\ndtest = xgb.DMatrix(X_test, label=y_test, feature_names=feature_names)\n\n\nparams = {'max_depth': 16, 'eta': 0.0003, 'silent': 1, 'objective': 'binary:logistic'}\nwatchlist = [(dtrain, 'train'), (dtest, 'test'), (dval, 'val')]\nnum_round = 10000\nearly_stopping_rounds = 3000\n\nbst = xgb.train(params=params,\n dtrain=dtrain,\n num_boost_round=num_round,\n evals=watchlist,\n early_stopping_rounds=early_stopping_rounds)\n\nfeature_importances = bst.get_fscore()\n\nprint()\nprint('feature importances:')\nfor f_name, imp in reversed(sorted(feature_importances.items(), key=itemgetter(1))):\n print(f_name, ':', imp)\n\nbest_ntree_limit = bst.best_ntree_limit\n\npred = bst.predict(dval, ntree_limit=best_ntree_limit)\n\npred_real = list(zip(pred, y_val))\n\nsorted_by_pred = list(reversed(sorted(pred_real, key=lambda x: (x[0],x[1]))))\nsorted_by_real = list(reversed(sorted(pred_real, key=lambda x: (x[1],x[0]))))\n\nprint()\nprint('====VALIDATION=======VALIDATION=======VALIDATION=======VALIDATION=======VALIDATION===')\n\nprint()\nprint('pred, real:')\nfor item1, item2 in list(zip(sorted_by_pred, sorted_by_real))[:300]:\n print('{:30}{:30}'.format('{:.6f}, {:.6f}'.format(*item1), '{:.6f}, {:.6f}'.format(*item2)))\n\npred = bst.predict(dtest, ntree_limit=best_ntree_limit)\n\npred_real = list(zip(pred, y_test))\n\nsorted_by_pred = list(reversed(sorted(pred_real, key=lambda x: (x[0],x[1]))))\nsorted_by_real = list(reversed(sorted(pred_real, key=lambda x: (x[1],x[0]))))\n\nprint()\nprint('+++TEST+++++++TEST+++++++TEST+++++++TEST+++++++TEST+++++++TEST+++++++TEST+++++++TEST++++')\n\nprint()\nprint('pred, real:')\nfor item1, item2 in list(zip(sorted_by_pred, sorted_by_real))[:300]:\n print('{:30}{:30}'.format('{:.6f}, {:.6f}'.format(*item1), '{:.6f}, {:.6f}'.format(*item2)))\n\n# xgb.plot_importance(bst)\n# xgb.plot_tree(bst)\n# pyplot.show()\n","sub_path":"lambdatrader/signals/data_analysis/learning/dummy/xgboost_log_reg_dummy.py","file_name":"xgboost_log_reg_dummy.py","file_ext":"py","file_size_in_byte":5233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"243166298","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 ]\n\n operations = [\n migrations.CreateModel(\n name='Item',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=120)),\n ('rating', models.FloatField(null=True, blank=True)),\n ('rating_count', models.IntegerField(null=True, blank=True)),\n ('price', models.FloatField()),\n ],\n ),\n migrations.CreateModel(\n name='Restaurant',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=120)),\n ('yelp_rating', models.FloatField(null=True, blank=True)),\n ('review_count', models.IntegerField(null=True, blank=True)),\n ],\n ),\n migrations.AddField(\n model_name='item',\n name='restaurant',\n field=models.ForeignKey(to='restaurants.Restaurant'),\n ),\n ]\n","sub_path":"restaurants/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"237477881","text":"import sys\ncases = int(sys.stdin.readline())\n\nfor i in range(cases):\n test, number = [int(x) for x in input().split()]\n\n s3 = number * (number + 1)\n s1 = int(s3 / 2)\n s2 = number * number\n \n \n print(test, \" \", s1, \" \", s2, \" \", s3)\n\n\n \n","sub_path":"SumProblem.py","file_name":"SumProblem.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"98869864","text":"import pytest\nfrom panda3d import core\n\n\ndef reconstruct(object):\n # Create a temporary buffer, which we first write the object into, and\n # subsequently read it from again.\n \n buffer = core.DatagramBuffer()\n\n writer = core.BamWriter(buffer)\n writer.init()\n writer.write_object(object)\n\n reader = core.BamReader(buffer)\n reader.init()\n object = reader.read_object()\n reader.resolve()\n return object\n\n\ndef test_nav_mesh_bam():\n navigation = pytest.importorskip(\"panda3d.navigation\")\n data = core.GeomVertexData(\"\", core.GeomVertexFormat.get_v3(), core.Geom.UH_static)\n vertex = core.GeomVertexWriter(data, \"vertex\")\n vertex.add_data3((0, 0, 0))\n vertex.add_data3((100, 0, 3))\n vertex.add_data3((100, 200, 1))\n vertex.add_data3((50, 50, 4))\n\n prim = core.GeomTriangles(core.Geom.UH_static)\n prim.add_vertices(0, 1, 2)\n prim.close_primitive()\n\n geom = core.Geom(data)\n geom.add_primitive(prim)\n\n prim.add_vertices(3, 1, 2)\n prim.close_primitive()\n\n node = core.GeomNode('gnode')\n node.add_geom(geom)\n\n scene = core.NodePath(node)\n\n # Defining navmesh as object of NavMehsBuilder class.\n builder = navigation.NavMeshBuilder()\n\n # Extracting geoms from 'scene' and calculating vertices and triangles.\n builder.from_node_path(scene)\n\n navmesh = builder.build()\n\n vertCount = navmesh.get_vert_count()\n polyCount = navmesh.get_poly_count()\n detailVertsCount = navmesh.get_detail_vert_count()\n detailTriCount = navmesh.get_detail_tri_count()\n\n navmeshBam = reconstruct(navmesh)\n\n assert type(navmesh) == type(navmeshBam)\n assert vertCount == navmeshBam.get_vert_count()\n assert polyCount == navmeshBam.get_poly_count()\n assert detailVertsCount == navmeshBam.get_detail_vert_count()\n assert detailTriCount == navmeshBam.get_detail_tri_count()\n\n\ndef test_nav_mesh_node_bam():\n navigation = pytest.importorskip(\"panda3d.navigation\")\n data = core.GeomVertexData(\"\", core.GeomVertexFormat.get_v3(), core.Geom.UH_static)\n vertex = core.GeomVertexWriter(data, \"vertex\")\n vertex.add_data3((0, 0, 0))\n vertex.add_data3((100, 0, 3))\n vertex.add_data3((100, 200, 1))\n vertex.add_data3((50, 50, 4))\n\n prim = core.GeomTriangles(core.Geom.UH_static)\n prim.add_vertices(0, 1, 2)\n prim.close_primitive()\n\n geom = core.Geom(data)\n geom.add_primitive(prim)\n\n prim.add_vertices(3, 1, 2)\n prim.close_primitive()\n\n node = core.GeomNode('gnode')\n node.add_geom(geom)\n\n scene = core.NodePath(node)\n\n # Defining navmesh as object of NavMehsBuilder class.\n builder = navigation.NavMeshBuilder()\n\n # Extracting geoms from 'scene' and calculating vertices and triangles.\n builder.from_node_path(scene)\n\n navmesh = builder.build()\n\n navmeshnode = navigation.NavMeshNode(\"navmeshnode\", navmesh)\n params = navmesh.params\n\n navmeshNodeBam = reconstruct(navmeshnode)\n\n assert type(navmeshnode) == type(navmeshNodeBam)\n assert params == navmeshNodeBam.get_nav_mesh().get_params()\n\n\ndef test_nav_query_bam():\n navigation = pytest.importorskip(\"panda3d.navigation\")\n navmeshgen = pytest.importorskip(\"panda3d.navmeshgen\")\n data = core.GeomVertexData(\"\", core.GeomVertexFormat.get_v3(), core.Geom.UH_static)\n vertex = core.GeomVertexWriter(data, \"vertex\")\n vertex.add_data3((0, 0, 0))\n vertex.add_data3((100, 0, 3))\n vertex.add_data3((100, 200, 1))\n vertex.add_data3((50, 50, 4))\n\n prim = core.GeomTriangles(core.Geom.UH_static)\n prim.add_vertices(0, 1, 2)\n prim.close_primitive()\n\n geom = core.Geom(data)\n geom.add_primitive(prim)\n\n prim.add_vertices(3, 1, 2)\n prim.close_primitive()\n\n node = core.GeomNode('gnode')\n node.add_geom(geom)\n\n scene = core.NodePath(node)\n\n # Defining navmesh as object of NavMehsBuilder class.\n builder = navmeshgen.NavMeshBuilder()\n\n # Extracting geoms from 'scene' and calculating vertices and triangles.\n builder.from_node_path(scene)\n\n navmesh = builder.build()\n\n query = navigation.NavMeshQuery(navmesh)\n pos = core.LPoint3(50, 55, 3)\n query.nearest_point(pos)\n path = query.find_path(pos, core.LPoint3(100, 0, 3))\n\n navmeshBam = reconstruct(navmesh)\n queryBam = navigation.NavMeshQuery(navmeshBam)\n posBam = core.LPoint3(50, 55, 3)\n queryBam.nearest_point(posBam)\n pathBam = query.find_path(posBam, core.LPoint3(100, 0, 3))\n\n assert pos == posBam\n assert path == pathBam\n","sub_path":"tests/navigation/test_nav_mesh_bam.py","file_name":"test_nav_mesh_bam.py","file_ext":"py","file_size_in_byte":4477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"340377725","text":"\"\"\"\n2.*\tНаписать программу сложения и умножения двух шестнадцатиричных чисел.\nПри этом каждое число представляется как массив, элементы которого это цифры числа.\nНапример, пользователь ввёл A2 и C4F. Сохранить их как [‘A’, ‘2’] и [‘C’, ‘4’, ‘F’] соответственно.\nСумма чисел из примера: [��C’, ‘F’, ‘1’], произведение - [‘7’, ‘C’, ‘9’, ‘F’, ‘E’].\n\nПодсказка:\nДля решения задачи обязательно примените какую-нибудь коллекцию из модуля collections\nДля лучшее освоения материала можете даже сделать несколько решений этого задания,\nприменив несколько коллекций из модуля collections\nТакже попробуйте решить задачу вообще без collections и применить только ваши знания по ООП\n(в частности по перегрузке методов)\n\n__mul__\n__add__\n\nПример:\nНапример, пользователь ввёл A2 и C4F.\nСохранить их как [‘A’, ‘2’] и [‘C’, ‘4’, ‘F’] соответственно.\nСумма чисел из примера: [‘C’, ‘F’, ‘1’]\nПроизведение - [‘7’, ‘C’, ‘9’, ‘F’, ‘E’].\n\n1. вариант\ndefaultdict(list)\nint(, 16)\nreduce\n\n2. вариант\nclass HexNumber:\n __add__\n __mul__\n\nhx = HexNumber\nhx + hx\n\"\"\"\nfrom collections import defaultdict, deque\nfrom itertools import zip_longest\n\n\ndef solution_with_collections(num_s1: str, num_s2: str):\n nums = defaultdict(list)\n nums[1].extend(c for c in num_s1)\n nums[2].extend(c for c in num_s2)\n nums['sum'].extend(s for s in hex(int(''.join(nums[1]), 16) + int(''.join(nums[2]), 16))[2:].upper())\n nums['mul'].extend(s for s in hex(int(''.join(nums[1]), 16) * int(''.join(nums[2]), 16))[2:].upper())\n print(f\"\"\"defaultdict\n пользователь ввёл {num_s1} и {num_s2}\n сохранено {nums[1]} и {nums[2]}\n сумма: {nums['sum']}\n произведение: {nums['mul']}\n \"\"\")\n\n\ndef solution_with_oop(num_s1: str, num_s2: str):\n class HexNumber:\n\n def __init__(self, s):\n self.num = s\n\n def __add__(self, other):\n return hex(int(self.num, 16) + int(other.num, 16))[2:].upper()\n\n def __mul__(self, other):\n return hex(int(self.num, 16) * int(other.num, 16))[2:].upper()\n\n num1, num2 = HexNumber(num_s1), HexNumber(num_s2)\n print(f\"\"\"OOP\n пользователь ввёл {num_s1} и {num_s2}\n сумма: {num1 + num2}\n произведение: {num1 * num2}\n \"\"\")\n\n\nif __name__ == '__main__':\n number1 = input('введите число в 16 системе\\n')\n number2 = input('введите число в 16 системе\\n')\n solution_with_collections(number1, number2)\n solution_with_oop(number1, number2)\n","sub_path":"Урок 5. Практическое задание/task_2.py","file_name":"task_2.py","file_ext":"py","file_size_in_byte":3248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"150420288","text":"import numpy as np\nimport torch as T\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport time\nimport gym\nimport utils\nfrom copy import deepcopy\nimport quaternion\n\nclass ConvPolicy8(nn.Module):\n def __init__(self, env):\n super(ConvPolicy8, self).__init__()\n self.N_links = 4\n self.act_dim = self.N_links * 6 - 2\n\n # rep conv\n self.conv_1 = nn.Conv1d(12, 4, kernel_size=3, stride=1, padding=1)\n self.conv_2 = nn.Conv1d(4, 8, kernel_size=3, stride=1, padding=1)\n self.conv_3 = nn.Conv1d(8, 8, kernel_size=3, stride=1)\n self.conv_4 = nn.Conv1d(8, 8, kernel_size=2, stride=1)\n\n # Embedding layers\n self.conv_emb_1 = nn.Conv1d(10, 8, kernel_size=1, stride=1)\n self.conv_emb_2 = nn.Conv1d(8, 8, kernel_size=1, stride=1)\n\n self.deconv_1 = nn.ConvTranspose1d(8, 4, kernel_size=3, stride=1)\n self.deconv_2 = nn.ConvTranspose1d(4, 4, kernel_size=3, stride=1, padding=1)\n self.deconv_3 = nn.ConvTranspose1d(4, 8, kernel_size=3, stride=1, padding=1)\n self.deconv_4 = nn.ConvTranspose1d(14, 6, kernel_size=3, stride=1, padding=1)\n\n self.upsample = nn.Upsample(size=4)\n\n self.afun = F.tanh\n\n self.log_std = nn.Parameter(T.zeros(1, self.act_dim))\n\n def forward(self, x):\n N = x.shape[0]\n obs = x[:, :7]\n obsd = x[:, 7 + self.N_links * 6 - 2: 7 + self.N_links * 6 - 2 + 6]\n\n # Get psi angle from observation quaternion\n _, _, psi = quaternion.as_euler_angles(np.quaternion(*(obs[0,3:7].numpy())))\n psi = T.tensor([psi], dtype=T.float32).unsqueeze(0).repeat(N,1)\n\n # (psi, psid)\n ext_obs = T.cat((psi, obsd[:, -1:]), 1)\n\n # Joints angles\n jl = T.cat((T.zeros(N, 2), x[:, 7:7 + self.N_links * 6 - 2]), 1)\n jlrs = jl.view((N, 6, -1))\n\n # Joint angle velocities\n jdl = T.cat((T.zeros(N, 2), x[:, 7 + self.N_links * 6 - 2 + 6:]), 1)\n jdlrs = jdl.view((N, 6, -1))\n\n jcat = T.cat((jlrs, jdlrs), 1) # Concatenate j and jd so that they are 2 parallel channels\n\n fm_c1 = self.afun(self.conv_1(jcat))\n fm_c2 = self.afun(self.conv_2(fm_c1))\n fm_c3 = self.afun(self.conv_3(fm_c2))\n fm_c4 = self.afun(self.conv_4(fm_c3))\n\n # Combine obs with featuremaps\n emb_1 = self.afun(self.conv_emb_1(T.cat((fm_c4, ext_obs.unsqueeze(2)),1)))\n emb_2 = self.afun(self.conv_emb_2(emb_1))\n\n # Project back to action space\n fm_dc1 = self.afun(self.deconv_1(emb_2))\n fm_dc2 = self.afun(self.deconv_2(fm_dc1))\n fm_dc3 = self.afun(self.deconv_3(fm_dc2))\n fm_upsampled = self.upsample(fm_dc3)\n fm_dc4 = self.deconv_4(T.cat((fm_upsampled, jlrs), 1))\n\n acts = fm_dc4.squeeze(2).view((N, -1))\n\n return acts[:, 2:]\n\n\n def sample_action(self, s):\n return T.normal(self.forward(s), T.exp(self.log_std))\n\n\n def log_probs(self, batch_states, batch_actions):\n # Get action means from policy\n action_means = self.forward(batch_states)\n\n # Calculate probabilities\n log_std_batch = self.log_std.expand_as(action_means)\n std = T.exp(log_std_batch)\n var = std.pow(2)\n log_density = - T.pow(batch_actions - action_means, 2) / (2 * var) - 0.5 * np.log(2 * np.pi) - log_std_batch\n\n return log_density.sum(1, keepdim=True)\n\n\nclass Policy(nn.Module):\n def __init__(self, env):\n super(Policy, self).__init__()\n self.obs_dim = env.observation_space.shape[0]\n self.act_dim = env.action_space.shape[0]\n\n self.fc1 = nn.Linear(self.obs_dim, 64)\n self.fc2 = nn.Linear(64, 32)\n self.fc3 = nn.Linear(32, self.act_dim)\n\n self.log_std = nn.Parameter(T.zeros(1, self.act_dim))\n\n\n def forward(self, x):\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\n def sample_action(self, s):\n return T.normal(self.forward(s), T.exp(self.log_std))\n\n\n def log_probs(self, batch_states, batch_actions):\n # Get action means from policy\n action_means = self.forward(batch_states)\n\n # Calculate probabilities\n log_std_batch = self.log_std.expand_as(action_means)\n std = T.exp(log_std_batch)\n var = std.pow(2)\n log_density = - T.pow(batch_actions - action_means, 2) / (2 * var) - 0.5 * np.log(2 * np.pi) - log_std_batch\n\n return log_density.sum(1, keepdim=True)\n\n\nclass Valuefun(nn.Module):\n def __init__(self, env):\n super(Valuefun, self).__init__()\n\n self.obs_dim = env.observation_space.shape[0]\n\n self.fc1 = nn.Linear(self.obs_dim, 32)\n self.fc2 = nn.Linear(32, 32)\n self.fc3 = nn.Linear(32, 1)\n\n\n def forward(self, x):\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\ndef train(env, policy, V, params):\n\n policy_optim = T.optim.Adam(policy.parameters(), lr=params[\"policy_lr\"])\n V_optim = T.optim.Adam(V.parameters(), lr=params[\"V_lr\"])\n\n batch_states = []\n batch_actions = []\n batch_rewards = []\n batch_new_states = []\n batch_terminals = []\n\n batch_ctr = 0\n batch_rew = 0\n\n for i in range(params[\"iters\"]):\n s_0 = env.reset()\n done = False\n\n step_ctr = 0\n\n while not done:\n # Sample action from policy\n action = policy.sample_action(utils.to_tensor(s_0, True)).detach()\n\n # Step action\n s_1, r, done, _ = env.step(action.squeeze(0).numpy())\n step_ctr += 1\n # if step_ctr > 400:\n # done = True\n\n batch_rew += r\n\n if params[\"animate\"]:\n env.render()\n\n # Record transition\n batch_states.append(utils.to_tensor(s_0, True))\n batch_actions.append(action)\n batch_rewards.append(utils.to_tensor(np.asarray(r, dtype=np.float32), True))\n batch_new_states.append(utils.to_tensor(s_1, True))\n batch_terminals.append(done)\n\n s_0 = s_1\n\n # Just completed an episode\n batch_ctr += 1\n\n # If enough data gathered, then perform update\n if batch_ctr == params[\"batchsize\"]:\n\n batch_states = T.cat(batch_states)\n batch_actions = T.cat(batch_actions)\n batch_rewards = T.cat(batch_rewards)\n batch_new_states = T.cat(batch_new_states)\n\n # Refit value function\n loss_V = update_V(V, V_optim, params[\"gamma\"], batch_states, batch_rewards, batch_terminals)\n loss_V = None\n\n # Calculate episode advantages\n #batch_advantages = calc_advantages(V, params[\"gamma\"], batch_states, batch_rewards, batch_new_states, batch_terminals)\n batch_advantages = calc_advantages_MC(params[\"gamma\"], batch_rewards, batch_terminals)\n\n if params[\"ppo\"]:\n update_ppo(policy, policy_optim, batch_states, batch_actions, batch_advantages, params[\"ppo_update_iters\"])\n else:\n update_policy(policy, policy_optim, batch_states, batch_actions, batch_advantages)\n\n\n print(\"Episode {}/{}, loss_V: {}, loss_policy: {}, mean ep_rew: {}, std: {}, success: {}\".format(i, params[\"iters\"], None, None, batch_rew / params[\"batchsize\"], T.exp(policy.log_std).detach().numpy(), env.success_rate))\n\n # Finally reset all batch lists\n batch_ctr = 0\n batch_rew = 0\n\n batch_states = []\n batch_actions = []\n batch_rewards = []\n batch_new_states = []\n batch_terminals = []\n\n\ndef update_ppo(policy, policy_optim, batch_states, batch_actions, batch_advantages, update_iters):\n log_probs_old = policy.log_probs(batch_states, batch_actions).detach()\n c_eps = 0.2\n\n # Do ppo_update\n for k in range(update_iters):\n log_probs_new = policy.log_probs(batch_states, batch_actions)\n r = T.exp(log_probs_new - log_probs_old)\n loss = -T.mean(T.min(r * batch_advantages, r.clamp(1 - c_eps, 1 + c_eps) * batch_advantages))\n policy_optim.zero_grad()\n loss.backward()\n policy_optim.step()\n\n\ndef update_V(V, V_optim, gamma, batch_states, batch_rewards, batch_terminals):\n assert len(batch_states) == len(batch_rewards) == len(batch_terminals)\n N = len(batch_states)\n\n # Predicted values\n Vs = V(batch_states)\n\n # Monte carlo estimate of targets\n targets = []\n for i in range(N):\n cumrew = T.tensor(0.)\n for j in range(i, N):\n cumrew += (gamma ** (j-i)) * batch_rewards[j]\n if batch_terminals[j]:\n break\n targets.append(cumrew.view(1, 1))\n\n targets = T.cat(targets)\n\n # MSE loss#\n V_optim.zero_grad()\n\n loss = (targets - Vs).pow(2).mean()\n loss.backward()\n V_optim.step()\n\n return loss.data\n\n\ndef update_policy(policy, policy_optim, batch_states, batch_actions, batch_advantages):\n\n # Get action log probabilities\n log_probs = policy.log_probs(batch_states, batch_actions)\n\n # Calculate loss function\n loss = -T.mean(log_probs * batch_advantages)\n\n # Backward pass on policy\n policy_optim.zero_grad()\n loss.backward()\n\n # Step policy update\n policy_optim.step()\n\n return loss.data\n\n\ndef calc_advantages(V, gamma, batch_states, batch_rewards, batch_next_states, batch_terminals):\n Vs = V(batch_states)\n Vs_ = V(batch_next_states)\n targets = []\n for s, r, s_, t, vs_ in zip(batch_states, batch_rewards, batch_next_states, batch_terminals, Vs_):\n if t:\n targets.append(r.unsqueeze(0))\n else:\n targets.append(r + gamma * vs_)\n\n return T.cat(targets) - Vs\n\n\ndef calc_advantages_MC(gamma, batch_rewards, batch_terminals):\n N = len(batch_rewards)\n\n # Monte carlo estimate of targets\n targets = []\n for i in range(N):\n cumrew = T.tensor(0.)\n for j in range(i, N):\n cumrew += (gamma ** (j - i)) * batch_rewards[j]\n if batch_terminals[j]:\n break\n targets.append(cumrew.view(1, 1))\n targets = T.cat(targets)\n\n return targets\n\n\nif __name__==\"__main__\":\n #env_name = \"Centipede8-v0\"\n #env = gym.make(env_name)\n from envs.ant_reach import AntReach\n env = AntReach()\n policy = Policy(env)\n V = Valuefun(env)\n params = {\"iters\" : 100000, \"batchsize\" : 32, \"gamma\" : 0.99, \"policy_lr\" : 0.007, \"V_lr\" : 0.007, \"ppo\" : True, \"ppo_update_iters\" : 3, \"animate\" : True}\n train(env, policy, V, params)\n\n # TODO: debug and test\n","sub_path":"src/PG/pg.py","file_name":"pg.py","file_ext":"py","file_size_in_byte":10599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"58505891","text":"\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets('MNIST_data/', one_hot=True)\n\nimport tensorflow as tf\nfrom tensorflow.python.framework import graph_util\n\ndef train_and_save():\n\tx = tf.placeholder(tf.float32, [None, 784], name='x')\n\tW = tf.Variable(tf.zeros([784, 10]))\n\tb = tf.Variable(tf.zeros([10]))\n\ty = tf.nn.softmax(tf.matmul(x, W) + b, name='y')\n\n\ty_ = tf.placeholder(tf.float32, [None, 10], name='y_')\n\tcross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))\n\n\tcorrect_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n\taccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='accuracy')\n\n\ttrain_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n\n\twith tf.Session() as sess:\n\t\tsess.run(tf.initialize_all_variables())\n\t\tmax_steps = 1000\n\t\tfor step in range(max_steps):\n\t\t\tbatch_xs, batch_ys = mnist.train.next_batch(100)\n\t\t\tsess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n\t\t\tif (step % 100) == 0:\n\t\t\t\tprint(step, sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))\n\t\tprint(max_steps, sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))\n\n\t\tminimal_graph = graph_util.convert_variables_to_constants(sess, sess.graph_def, ['y', 'accuracy'])\n\t\ttf.train.write_graph(minimal_graph, './', 'trained_graph.pb', as_text=False)\n\t\ttf.train.write_graph(minimal_graph, './', 'trained_graph.txt', as_text=True)\n\treturn\n\ndef main():\n\tgraph = tf.Graph()\n\twith graph.as_default():\n\t\ttrain_and_save()\n\treturn\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"mnist_save_v1.py","file_name":"mnist_save_v1.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"129162658","text":"import unittest\nfrom core.classes import Round\nfrom datetime import datetime\n\nclass RoundUnitTests(unittest.TestCase):\n \n def test_constructor(self):\n r_id = 2\n active = True\n start_time_UTC = datetime.utcnow()\n initiator = 5\n \n test_round = Round(r_id, active, start_time_UTC, initiator)\n\n self.assertEqual(r_id, test_round.id)\n self.assertTrue(test_round.isActive())\n self.assertEqual(start_time_UTC, test_round.start_time_UTC)\n self.assertEqual(initiator, test_round.initiator)\n\n\n def test_constructor_converts_active_int_to_bool(self):\n r_id = 2\n start_time_UTC = datetime.utcnow()\n initiator = 5\n \n #1 should evaluate to True\n test_round_true = Round(r_id, 1, start_time_UTC, initiator)\n #2 should evaluate to False\n test_round_false = Round(r_id, 2, start_time_UTC, initiator)\n\n self.assertTrue(test_round_true.isActive())\n self.assertFalse(test_round_false.isActive())\n \n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/round_unittests.py","file_name":"round_unittests.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"355221670","text":"import joblib\nfrom PIL import ImageGrab\nimport cv2\nfrom tkinter import *\nimport tkinter\nfrom tkinter import messagebox\nimport csv\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport joblib\nfrom sklearn.svm import SVC\nfrom sklearn import metrics\nimport os\n\n\n\n\nmodel=joblib.load('model/svc_0_to_9')\n\n\nim = ImageGrab.grab(bbox=(10, 230, 260, 476))\nim.save('temp/for prediction.png')\nimage=cv2.imread('temp/for prediction.png')\ngim=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)\nresized_image=cv2.resize(gim,(28,28),interpolation=cv2.INTER_AREA)\n\nP=[]\nfor i in range(28):\n for j in range(28):\n if resized_image[i,j]<100:\n k=0\n else:\n k=1\n P.append(k)\n\npred=model.predict([P])\n\nprint('my prediction is >> ',pred[0])\n\nans=input('IS THE PREDICTION RIGHT (Y/N) >> ')\n\nif ans=='Y' :\n print('YEAHHHHH !!!')\n\n\nelif ans=='N':\n l=input('WHAT WAS THE NUMBER YOU TRIED TO PREDICT ? >> ')\n X=[]\n X.append(l)\n img = ImageGrab.grab(bbox=(10, 230, 260, 476))\n img.save('temp//ima.png')\n ima=cv2.imread('temp//ima.png')\n ima=cv2.cvtColor(ima,cv2.COLOR_BGR2GRAY)\n ima=cv2.resize(ima,(28,28))\n for i in range(28):\n for j in range(28):\n if ima[i, j] > 100:\n k = 1\n else:\n k = 0\n X.append(k)\n with open('training_dataset.csv','a+',newline='') as cfa:\n cf=csv.writer(cfa)\n cf.writerow(X)\n print('ADDED SUCCESSFULLY !!')","sub_path":"digit recognizer/predictor.py","file_name":"predictor.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"496634731","text":"from marketo import version, auth\n\nVERSION = version.VERSION\n__version__ = VERSION\n\nimport requests\n\nfrom marketo.wrapper import get_lead, get_lead_activity, request_campaign, get_campaigns_for_source, sync_lead\n\n\nclass Client:\n\n def __init__(self, soap_endpoint=None, user_id=None, encryption_key=None):\n\n if not soap_endpoint or not isinstance(soap_endpoint, (str, unicode)):\n raise ValueError('Must supply a soap_endpoint as a non empty string.')\n\n if not user_id or not isinstance(user_id, (str, unicode)):\n raise ValueError('Must supply a user_id as a non empty string.')\n\n if not encryption_key or not isinstance(encryption_key, str):\n raise ValueError('Must supply a encryption_key as a non empty string.')\n\n self.soap_endpoint = soap_endpoint\n self.user_id = user_id\n self.encryption_key = encryption_key\n\n def wrap(self, body):\n return (\n '' +\n '' +\n auth.header(self.user_id, self.encryption_key) +\n '' +\n body +\n '' +\n '')\n\n def request(self, body):\n envelope = self.wrap(body)\n response = requests.post(self.soap_endpoint, data=envelope,\n headers={\n 'Connection': 'Keep-Alive',\n 'Soapaction': '',\n 'Content-Type': 'text/xml;charset=UTF-8',\n 'Accept': '*/*'})\n return response\n\n def get_lead(self, email=None):\n\n if not email or not isinstance(email, (str, unicode)):\n raise ValueError('Must supply an email as a non empty string.')\n\n body = get_lead.wrap(email)\n response = self.request(body)\n if response.status_code == 200:\n return get_lead.unwrap(response)\n else:\n raise Exception(response.text)\n\n def get_lead_activity(self, email=None):\n\n if not email or not isinstance(email, (str, unicode)):\n raise ValueError('Must supply an email as a non empty string.')\n\n body = get_lead_activity.wrap(email)\n response = self.request(body)\n if response.status_code == 200:\n return get_lead_activity.unwrap(response)\n else:\n raise Exception(response.text)\n\n def request_campaign(self, campaignId, leadId=None, leadIdType='IDNUM', leads=None):\n \"\"\"\n Adds a lead or leads to a campaign.\n\n :type campaignId: str\n :param campaignId: the id of the campaign to which the leads will be added\n\n :type leadId: str\n :param leadId: the id of a lead to be added to the campaign. Used for adding a single lead to a campaign. May\n not be used if leads is specified.\n\n :type leadIdType: the type of the id being passed. Defaults to 'IDNUM'. Possible values are: 'IDNUM'\n (Marketo lead id), 'COOKIE' (Munkin cookie for a lead), 'EMAIL' (email address for a lead), 'SFDCLEADID'\n (Salesforce id for a lead), 'LEADOWNEREMAIL' (the email address of the owner of the lead), 'SFDCACCOUNTID'\n (account id from Salesforce), 'SFDCCONTACTID' (the contact id from Salesforce), 'SFDCLEADID' (the lead id from\n Salesforce), 'SFDCLEADOWNERID' (the lead owner id from Salesforce), 'SFDCOPPTYID' (the opportunity id from\n Salesforce)\n\n :type leads: list of tuples or tuple of tuples\n :param leads: multiple leads to be added to the campaign. May not be used with the leadId parameter. For\n each individual tuple, the first value is the id of the lead, the second value is the type of the lead id. See\n leadIdType for a list of possible values.\n\n :returns: True on success, exception on failure\n \"\"\"\n if not campaignId or not isinstance(campaignId, (str, unicode)):\n raise ValueError('Must supply campaign id as a non empty string.')\n\n if leadId and leads:\n raise ValueError('Cannot specify both leadId and leads')\n\n if leadId:\n # Single lead\n if not leadIdType:\n raise ValueError('leadIdType must be specified')\n\n # Convert into list\n leads = [(leadId, leadIdType)]\n\n for lead in leads:\n # Check lead id\n if not lead[0] or not isinstance(lead[0], (str, unicode)):\n raise ValueError('non-empty string required for lead id')\n\n # CHeck lead id type\n if not lead[1] or not isinstance(lead[1], (str, unicode)) or lead[1] not in ['IDNUM', 'COOKIE', 'EMAIL',\n 'SFDCLEADID', 'LEADOWNEREMAIL',\n 'SFDCACCOUNTID',\n 'SFDCCONTACTID', 'SFDCLEADID',\n 'SFDCLEADOWNERID',\n 'SFDCOPPTYID']:\n raise ValueError(\"'%s' is an invalid lead id type' % lead[1]\")\n\n body = request_campaign.wrap(campaignId, leads)\n\n response = self.request(body)\n if response.status_code == 200:\n return True\n else:\n raise Exception(response.text)\n\n def get_campaigns_for_source(self, source='MKTOWS', name=None, exactName=False):\n \"\"\"\n Create request body for getCampaignsForSource.\n\n :type source: str\n :param source: the source requested. Possible values 'MKTOWS' or 'SALES'\n\n :type name: str\n :param name: the name filter to apply to the request. Optional.\n\n :type exactName: bool\n :param exactName: boolean flag indicating if the returned campaigns must be an exact match to name\n \"\"\"\n\n\n if not source or not isinstance(source, (str, unicode)):\n raise ValueError('Must supply source as a non empty string.')\n\n if name and not isinstance(name, (str, unicode)):\n raise ValueError('Must supply lead id as a non empty string.')\n\n body = get_campaigns_for_source.wrap(source, name, exactName)\n\n response = self.request(body)\n if response.status_code == 200:\n return get_campaigns_for_source.unwrap(response)\n else:\n raise Exception(response.text)\n\n def sync_lead(self,\n email=None,\n marketo_id=None,\n marketo_cookie=None,\n foreign_system_id=None,\n foreign_system_type=None,\n attributes=None):\n \"\"\"\n Push information about a lead to Marketo. Lead must be identified by one or more of email, marketo_id,\n marketo_cookie, or foriegn_system_id. See http://developers.marketo.com/documentation/soap/synclead/ for more\n details.\n\n :type email: str\n :param email: the email address of the lead\n\n :type marketo_id: str\n :param marketo_id: the marketo generated id for a lead\n\n :type marketo_cookie: str\n :param marketo_cookie: a marketo cookie generated for a lead by Marketo's munchkin.js\n\n :type foreign_system_id: str\n :param foreign_system_id: a foriegn system identifier for a lead\n\n :type foreign_system_type: str\n :param foreign_system_type: the type of foreign system for foreign_system_id. Required if foreign_system_id\n is passed. Possible values are 'CUSTOM', 'SFDC', 'NETSUITE'\n\n :type attributes: tuple, dict\n :param attributes: the information about the lead to be pushed to marketo either in the form of tuples or a\n dictionary\n\n :returns: a lead object for the lead that was sync'ed\n \"\"\"\n if (not email or not isinstance(email, (str, unicode))) \\\n and (not marketo_id or not isinstance(marketo_id, (str, unicode))) \\\n and (not marketo_cookie or not isinstance(marketo_cookie, (str, unicode))) \\\n and (not foreign_system_id or not isinstance(foreign_system_id, (str, unicode))):\n raise ValueError('Must supply lead identification in email, marketo_id, '\n 'marketo_cookie, or foreign_system_id as a non empty string.')\n\n if foreign_system_id and not foreign_system_type:\n raise ValueError('foreign_system_type must be specified with foreign_system_id')\n\n if foreign_system_id and foreign_system_type and foreign_system_type not in ['CUSTOM', 'SFDC', 'NETSUITE']:\n raise ValueError('foreign_system_type must be \\'CUSTOM\\', \\'SFDC\\', or \\'NETSUITE\\'')\n\n if not attributes or (not isinstance(attributes, tuple) and not isinstance(attributes, dict)):\n raise ValueError('Must supply attributes as a non empty tuple or dict.')\n\n body = sync_lead.wrap(\n email=email,\n marketo_id=marketo_id,\n marketo_cookie=marketo_cookie,\n foreign_system_id=foreign_system_id,\n attributes=attributes)\n\n response = self.request(body)\n if response.status_code == 200:\n return sync_lead.unwrap(response)\n else:\n raise Exception(response.text)\n","sub_path":"marketo/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"81990391","text":"from flask import Flask\nfrom flask import jsonify\nfrom flask import request\nfrom flask import Response\nfrom objdict import ObjDict\nimport requests\nimport json\nimport os\nimport configparser\n\napp = Flask(__name__)\n\n#Set environment and read porperties\nenvType = os.environ.get('RUNTIME_ENV_TYPE', 'local')\nprint (\"RUNTIME_ENV_TIME : \" + envType)\nconfig = configparser.RawConfigParser()\nconfig.read('app.properties')\n\n#Overloaded returnError method for error handling\ndef returnError(httpErrorCode, iata, api, error=None):\n print('httpErrorCode: ' + str(httpErrorCode))\n #endpoint_url = config.get(envType, envType + '.' + api + '.endpoint.url') + iata\n outputroot = json.loads(config.get(envType, str(httpErrorCode) + '.error.message'))\n outputroot['error']['endpoint'] = api\n if not error is None:\n outputroot['error']['message'] = error\n outputroot_json = json.dumps(outputroot)\n return outputroot_json\n\n@app.route('/processapi/v1/businessapplications', methods=['GET'])\ndef returnAirportInfo(iata):\n outputroot = {}\n #Validate IATA\n try:\n if len(iata) > 3:\n raise IATAException\n elif len(iata) < 3:\n raise IATAException\n elif not iata.isalpha():\n raise IATAException\n except IATAException:\n error = returnError(400, iata)\n return Response(error, status=400, mimetype='application/json')\n else:\n #If IATA Valid - Call the first system API on SAP Hana Cloud\n try:\n api = config.get(envType, envType + '.airport.locator.url') + iata\n print('api_url : ' + api)\n airport_response = requests.get(api, timeout=5.0)\n airport_response_json = json.loads(airport_response.text)\n\n #Remove unwated medata field from SAP Hana Response\n airport_response_json [\"results\"][0].pop('__metadata')\n #Handle exceptions\n except requests.exceptions.HTTPError as error:\n error = returnError(504, iata, api, str(error))\n return Response(error, status=504, mimetype='application/json')\n except requests.exceptions.ConnectionError as error:\n error = returnError(504, iata, api, str(error))\n return Response(error, status=504, mimetype='application/json')\n except requests.exceptions.Timeout as error:\n error = returnError(504, iata, api, str(error))\n return Response(error, status=504, mimetype='application/json')\n except requests.exceptions.RequestException as error:\n error = returnError(504, iata, api, str(error))\n return Response(error, status=504, mimetype='application/json')\n except:\n #Error Handler\n error = returnError(airport_response.status_code, iata, api)\n return Response(error, status=airport_response.status_code, mimetype='application/json')\n\n #If API1 successfull - Call the second system API on IBM APP Connect\n try:\n #Get from country-locator-app-0.0.1\n countryCode = str(airport_response_json [\"results\"][0][\"iso_country\"])\n print(\"Country Code: \" + str(airport_response_json [\"results\"][0][\"iso_country\"]));\n api = config.get(envType, envType + '.country.locator.url') + countryCode\n print('country_locator_api_url : ' + api)\n country_response = requests.get(api, timeout=5.0)\n country_response_json = json.loads(country_response.text)\n\n #Prepare Response\n outputroot['result'] = airport_response_json [\"results\"][0];\n outputroot['result']['iso_country'] = country_response_json [\"result\"]\n #Handle exceptions\n except requests.exceptions.HTTPError as error:\n error = returnError(504, iata, api, str(error))\n return Response(error, status=504, mimetype='application/json')\n except requests.exceptions.ConnectionError as error:\n error = returnError(504, iata, api, str(error))\n return Response(error, status=504, mimetype='application/json')\n except requests.exceptions.Timeout as error:\n error = returnError(504, iata, api, str(error))\n return Response(error, status=504, mimetype='application/json')\n except requests.exceptions.RequestException as error:\n error = returnError(504, iata, api, str(error))\n return Response(error, status=504, mimetype='application/json')\n except:\n #Error Handler\n error = returnError(airport_response.status_code, iata, api)\n return Response(error, status=airport_response.status_code, mimetype='application/json')\n #Convert to JSON\n outputroot_json = json.dumps(outputroot)\n return Response(outputroot_json, mimetype='application/json')\n\nclass Error(Exception):\n \"\"\"Base class for other exceptions\"\"\"\n pass\n\nclass IATAException(Error):\n \"\"\"Raised when the input IATA length is greater than 3\"\"\"\n pass\n\nif __name__ == \"__main__\":\n app.run(\"0.0.0.0\", port=9031, debug=True)\n","sub_path":"storage-app-0.0.1/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"286002278","text":"numbers=[]\nfor i in range(9):\n\tnumber = int(input())\n\tnumbers.append(number)\n\naddvalue = sum(numbers)\n#print(addvalue)\nreductionvalue = addvalue-100\n#print(reductionvalue)\n\n\nredvalue = []\n\nfor i in numbers:\n\tfor j in numbers:\n\t\tif i!=j:\n\t\t\tif i+j == reductionvalue:\n\t\t\t\tnumbers.remove(i)\n\t\t\t\tnumbers.remove(j)\n\n\nfor numb in numbers:\n\tprint(numb)","sub_path":"patuljici.py","file_name":"patuljici.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"650065620","text":"from datetime import datetime\n\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.utils.text import slugify\n\nfrom ..mixins import AtomicSlugRetryMixin\nfrom ..util import get_language_codes\nfrom ..value import LocalizedValue\nfrom .autoslug_field import LocalizedAutoSlugField\n\n\nclass LocalizedUniqueSlugField(LocalizedAutoSlugField):\n \"\"\"Automatically provides slugs for a localized field upon saving.\".\n\n An improved version of :see:LocalizedAutoSlugField,\n which adds:\n\n - Concurrency safety\n - Improved performance\n\n When in doubt, use this over :see:LocalizedAutoSlugField.\n Inherit from :see:AtomicSlugRetryMixin in your model to\n make this field work properly.\n\n By default, this creates a new slug if the field(s) specified\n in `populate_from` are changed. Set `immutable=True` to get\n immutable slugs.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"Initializes a new instance of :see:LocalizedUniqueSlugField.\"\"\"\n\n kwargs[\"uniqueness\"] = kwargs.pop(\"uniqueness\", get_language_codes())\n\n self.enabled = kwargs.pop(\"enabled\", True)\n self.immutable = kwargs.pop(\"immutable\", False)\n\n super(LocalizedUniqueSlugField, self).__init__(*args, **kwargs)\n\n self.populate_from = kwargs.pop(\"populate_from\")\n self.include_time = kwargs.pop(\"include_time\", False)\n\n def deconstruct(self):\n \"\"\"Deconstructs the field into something the database can store.\"\"\"\n\n name, path, args, kwargs = super(\n LocalizedUniqueSlugField, self\n ).deconstruct()\n\n kwargs[\"populate_from\"] = self.populate_from\n kwargs[\"include_time\"] = self.include_time\n\n if self.enabled is False:\n kwargs[\"enabled\"] = self.enabled\n\n if self.immutable is True:\n kwargs[\"immutable\"] = self.immutable\n\n return name, path, args, kwargs\n\n def pre_save(self, instance, add: bool):\n \"\"\"Ran just before the model is saved, allows us to built the slug.\n\n Arguments:\n instance:\n The model that is being saved.\n\n add:\n Indicates whether this is a new entry\n to the database or an update.\n\n Returns:\n The localized slug that was generated.\n \"\"\"\n\n if not self.enabled:\n return getattr(instance, self.name)\n\n if not isinstance(instance, AtomicSlugRetryMixin):\n raise ImproperlyConfigured(\n (\n \"Model '%s' does not inherit from AtomicSlugRetryMixin. \"\n \"Without this, the LocalizedUniqueSlugField will not work.\"\n )\n % type(instance).__name__\n )\n\n slugs = LocalizedValue()\n\n for lang_code, value in self._get_populate_values(instance):\n if not value:\n continue\n\n slug = slugify(value, allow_unicode=True)\n\n current_slug = getattr(instance, self.name).get(lang_code)\n if current_slug and self.immutable:\n slugs.set(lang_code, current_slug)\n continue\n\n # verify whether it's needed to re-generate a slug,\n # if not, re-use the same slug\n if instance.pk is not None:\n if current_slug is not None:\n current_slug_end_index = current_slug.rfind(\"-\")\n stripped_slug = current_slug[0:current_slug_end_index]\n if slug == stripped_slug:\n slugs.set(lang_code, current_slug)\n continue\n\n if self.include_time:\n slug += \"-%d\" % datetime.now().microsecond\n\n retries = getattr(instance, \"retries\", 0)\n if retries > 0:\n # do not add another - if we already added time\n if not self.include_time:\n slug += \"-\"\n slug += \"%d\" % retries\n\n slugs.set(lang_code, slug)\n\n setattr(instance, self.name, slugs)\n return slugs\n","sub_path":"localized_fields/fields/uniqueslug_field.py","file_name":"uniqueslug_field.py","file_ext":"py","file_size_in_byte":4076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"411460127","text":"from dal.widgets import WidgetMixin\nfrom dal_select2.widgets import Select2WidgetMixin\nfrom django import forms\nfrom django.forms.models import ModelChoiceIterator\nfrom django.utils.encoding import force_text\nfrom django.utils.html import format_html\nfrom django.utils.safestring import mark_safe\n\n\nclass ModelSelectWithOptionsWithTooltips(forms.Select):\n \"\"\"\n Provides a select widget that uses one of the model fields\n to create a title tooltip attribute for an option\n It's useful to provide additional description for a select's option.\n \"\"\"\n\n def __init__(self, attrs=None, choices=(), title_from=None):\n super(ModelSelectWithOptionsWithTooltips, self).__init__(attrs, choices)\n self.title_from = title_from or 'description'\n\n def render_option(self, selected_choices, option_value, option_label, option_title=None):\n if option_value is None:\n option_value = ''\n option_value = force_text(option_value)\n if option_value in selected_choices:\n selected_html = mark_safe(' selected=\"selected\"')\n if not self.allow_multiple_selected:\n # Only allow for a single selection.\n selected_choices.remove(option_value)\n else:\n selected_html = ''\n return format_html('', force_text(option_title), option_value,\n selected_html, force_text(option_label))\n\n def render_options(self, selected_choices):\n if not isinstance(self.choices, ModelChoiceIterator):\n return super(ModelSelectWithOptionsWithTooltips, self).render_options(selected_choices)\n\n # Normalize to strings.\n selected_choices = set(force_text(v) for v in selected_choices)\n output = []\n\n # Get empty value (if exists) from initial field options.\n for option_value, option_label in self.choices:\n if option_value is None or option_value is '':\n output.append(self.render_option(selected_choices, option_value, option_label, ''))\n break\n\n # Generate options from a queryset.\n for item in self.choices.queryset:\n output.append(self.render_option(selected_choices, item.pk, item.title,\n item.description if hasattr(item, self.title_from) else ''))\n return '\\n'.join(output)\n\n\nclass FlisListModelSelect2(WidgetMixin, Select2WidgetMixin, ModelSelectWithOptionsWithTooltips):\n \"\"\"Select widget for regular choices and Select2.\"\"\"\n","sub_path":"code/pages/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"491484336","text":"# use while loops to modify lists while we work through them\r\n\r\n# create a list of new users for a website\r\n# use a while loop to go through that list of users, verify their ID, then add them to a new list of verified users\r\n\r\n# unconfirmed_users = ['sarah','mike','trevor']\r\n# confirmed_users = []\r\n\r\n# while unconfirmed_users:\r\n# current_user = unconfirmed_users.pop()\r\n# print(f'Verifying users: {current_user.title()}')\r\n# confirmed_users.append(current_user)\r\n\r\n# print(f'\\nThe following users have been confirmed:')\r\n# for confirmed_user in confirmed_users:\r\n# print(confirmed_user.title())\r\n\r\n# # remove all instances of a specific value from a list using remove() method inside a while loop\r\n# # python removes the first instance of 'cats' in the while loops, then goes back and keeps checking until there are no more 'cats' in the list\r\n\r\n# pets = ['dogs','cats','dogs','cats','parrots','hamsters','iguanas','goldfish','ferrets']\r\n\r\n# while 'cats' in pets:\r\n# pets.remove('cats')\r\n\r\n# print(pets)\r\n\r\n# # make a polling program to prompt for a name and response through a while loop\r\n# # store the inputs we gather in a dictionary to tie each response to a user\r\n\r\nresponses = {}\r\npolling_active = True\r\n\r\nwhile polling_active:\r\n # prompt for the person's name and their individual response\r\n name = input(\"\\nWhat is your name? \")\r\n response = input(\"\\nWhat is your favorite food? \")\r\n\r\n #store response in dictionary\r\n\r\n responses[name] = response\r\n\r\n # ask if there's another person who will respond, expanding our dictionary\r\n\r\n repeat = input('\\nIs there another person who will respond (type yes or no)' )\r\n if repeat == 'no':\r\n polling_active = False\r\n elif repeat == 'yes':\r\n continue\r\n else:\r\n print('I assume you meant to indicate another person would like to respond')\r\n\r\n# polling is completed\r\n\r\nprint(\"\\n---Polling is complete---\")\r\nfor name, response in responses.items():\r\n print(f\"{name.title()}'s favorite food is {response}.\")\r\n\r\n\r\n\r\n\r\n","sub_path":"python_bootcamp/chapter_7/while loops_lists and dictionaries.py","file_name":"while loops_lists and dictionaries.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"209727342","text":"\"\"\"\nUtility methods shared by all federated learning simulations\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\n\ndef split_training_data(X_train, y_train, num_splits, iid, rng):\n \"\"\"\n Splits training data into partitions that can be distributed among\n workers.\n\n Parameters\n ----------\n X_train : numpy ndarray\n Training features.\n y_train : numpy ndarray\n Training targets.\n num_splits : int\n Number of partiitons to create.\n iid : boolean\n True to uniformly distribute the examples and targets across the splits.\n False to order the examples by target before creating the splits.\n rng : numpy.random.Generator\n instance to use for random number generation.\n\n Returns\n -------\n X_train_splits : list of numpy ndarray\n The training feature splits.\n y_train_splits : list of numpy ndarray\n The training target splits.\n split_weights : list of float\n The proportion of the total training set present in each split\n\n \"\"\"\n if iid:\n train_order = rng.permutation(X_train.shape[0])\n else:\n train_order = np.argsort(y_train)\n \n X_train = X_train[train_order]\n y_train = y_train[train_order]\n X_train_splits = np.array_split(X_train, num_splits)\n y_train_splits = np.array_split(y_train, num_splits)\n\n split_weights = [X_train_splits[i].shape[0] / X_train.shape[0] for i in range(num_splits)] \n \n return X_train_splits, y_train_splits, split_weights\n\ndef diff_global_sq_norm(a, b):\n \"\"\"\n Compute the square of the global norm of the difference of two lists of tensors.\n Each tensor in b is subtracted from each tensor in a entrywise, and then\n tf.linalg.global_norm is used on the resulting list of difference tensors to get the norm.\n The square of this quantity is returned.\n\n Parameters\n ----------\n a : list of tf.Tensor\n \n b : list of tf.Tensor\n \n Returns\n -------\n float\n The square of the global norm of the difference between a and b.\n \"\"\"\n diff = [t_a - t_b for t_a, t_b in zip(a, b)]\n return (tf.linalg.global_norm(diff)**2).numpy()","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"610809623","text":"from collections import defaultdict\nfrom pathlib import Path\nimport tensorflow_estimator as tfe\nfrom hedgedog.logging import get_logger\nfrom hedgedog.tf.estimator import train as hdtrain\n\nfrom el.eval.evaluation import Evaluation\nfrom el.eval.example import Example\nfrom el.eval.span import Span\n\nlog = get_logger(\"el.eval\")\n\n\ndef f1_eval(name, gold_spans, predicted_spans, sentence_texts, params):\n exact_eval = Evaluation(set(gold_spans), set(predicted_spans))\n report = f\"\\nExact Boundary Evaluation\\n----------\" +\\\n f\"\\nP: {exact_eval.precision()}\" +\\\n f\"\\nR: {exact_eval.recall()}\" +\\\n f\"\\nF1: {exact_eval.f1()}\"\n log.info(report)\n\n partial_eval = Evaluation(set(gold_spans), set(predicted_spans), partial=True)\n partial_report = f\"\\n----------\\nPartial Boundary Evaluation\\n----------\" +\\\n f\"\\nP: {partial_eval.precision()}\" +\\\n f\"\\nR: {partial_eval.recall()}\" +\\\n f\"\\nF1: {partial_eval.f1()}\"\n log.info(partial_report)\n report += partial_report\n\n outdir = Path(params.estimator.model_dir) / params.estimator.run_name / ('test' if params.estimator.eval_test_set else 'dev')\n outdir.mkdir(exist_ok=True)\n with (outdir / f'{name}_eval.txt').open('w+') as f:\n f.write(report)\n\n tps = defaultdict(list)\n fps = defaultdict(list)\n fns = defaultdict(list)\n for s in exact_eval.tp:\n tps[s.sid].append(s)\n for s in exact_eval.fp:\n fps[s.sid].append(s)\n for s in exact_eval.fn:\n fns[s.sid].append(s)\n log.info(f\"{len(fns) + len(fps)} of {len(tps) + len(fns) + len(fps)} sentences with spans contain errors\")\n with (outdir / f'{name}_examples.txt').open('w+') as f:\n for sid in list(fps.keys()) + list(fns.keys()):\n try:\n ex = Example(sid, sentence_texts[sid], tps[sid], fps[sid], fns[sid])\n except KeyError as e:\n log.error(e)\n log.error(f\"sentence_texts.keys(): {sorted(sentence_texts.keys())}\")\n exit()\n f.write(str(ex))\n\n\ndef init_model(model_class, params, modules, run_name, ckpt):\n ds = model_class.dataset()\n model_fn = hdtrain.build_model_fn(model_class, dataset=ds)\n model_dir = str(Path(params.estimator.model_dir) / run_name)\n params.estimator.run_name = run_name\n params.model.modules = modules\n estimator = tfe.estimator.Estimator(model_fn,\n model_dir=model_dir,\n params=params)\n ckpt = _init_ckpt(ckpt, model_dir)\n\n return estimator, ds, ckpt\n\n\ndef _init_ckpt(ckpt_num, model_dir):\n ckpt = None\n if ckpt_num is not None:\n ckpt = str(Path(model_dir) / f\"model.ckpt-{ckpt_num}\")\n log.info(f\"Attempting to load ckpt at {ckpt}\")\n return ckpt\n","sub_path":"el/eval/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"560125489","text":"\"\"\" this module reproduces figure 2E \"\"\"\n\nimport os\nimport gzip\nimport pandas as pd\nimport warnings\nimport click \nimport multiprocessing as mp\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\n\ndef count_comments(filename):\n\t\"\"\" Count comment lines (those that start with \"#\") \n\t\tcribbed from slowko \"\"\"\n\tcomments = 0\n\tfn_open = gzip.open if filename.endswith('.gz') else open\n\twith fn_open(filename) as fh:\n\t\tfor line in fh:\n\t\t\tif line.startswith('#'):\n\t\t\t\tcomments += 1\n\t\t\telse:\n\t\t\t\tbreak\n\treturn comments\n\n\n\ndef vcf_to_dataframe(filename):\n\t\"\"\" Open a VCF file and return a pandas.DataFrame with\n\t\teach INFO field included as a column in the dataframe \n\t\tcribbed from slowko \"\"\"\n\tVCF_HEADER = ['CHROM', 'POS', 'ID', 'REF', 'ALT', 'QUAL', 'FILTER', 'INFO', 'FORMAT', '20']\n\n\t# Count how many comment lines should be skipped.\n\tcomments = count_comments(filename)\n\ttbl = pd.read_table(filename, compression=None, skiprows=comments,\n\t\t\t\t\t\t\tnames=VCF_HEADER, usecols=range(10))\n\t\n\treturn(tbl)\n\n\n\ndef GOI_df_subset(vcf_, chrom_, start_, end_):\n\t\"\"\" subset a single vcf based on genomic coords\"\"\"\n\tchrStr = 'chr' + str(chrom_)\n \n\tkeep0 = vcf_['CHROM'] == chrStr\n\tvcf_sub0 = vcf_[keep0]\n\n\tkeep1 = vcf_sub0['POS'] >= start_\n\tvcf_sub1 = vcf_sub0[keep1]\n\n\tkeep2 = vcf_sub1['POS'] <= end_\n\tvcf_sub2 = vcf_sub1[keep2]\n \n\treturn(vcf_sub2)\n\n\n\ndef coverage_search(df):\n\t\"\"\" given subset of vcf entries, search for AD (DepthPerAlleleBySample) col \"\"\" \n\tcounts = []\n\tfor i in range(0, len(df.index)):\n\t\trow = df.iloc[i]\n\t\textra_col = str(row['20'])\n\n\t\ttry:\n\t\t\tAD = extra_col.split(':')[1]\n\t\t\twt_count = int(AD.split(',')[0])\n\t\t\tvariant_count = int(AD.split(',')[1])\n\t\t\ttotal_count = wt_count + variant_count\n\n\t\t\tratio = str(variant_count) + ':' + str(total_count)\n\t\t\tcounts.append(ratio)\n\n\t\texcept: # picking up a wierd edge case -- '20' field is malformed\n\t\t\tprint(extra_col)\n\t\t\tcontinue\n\t\t\n\treturn(counts)\n\n\n\ndef driver(cellFile):\n\t\"\"\" for a given cell, search for variants to all genes! \"\"\"\n\tcurrCell = cellFile.strip(wrkdir_ + 'scVCF_filtered_all/')\n\tcurrCell = currCell.strip('.vcf')\n\t#print(currCell)\n\n\tvcf = vcf_to_dataframe(cellFile)\n\tGOI_counts_by_cell = []\n\n\tfor gene in gene_names:\n\t\tkeep = hg38.gene_id == gene\n\t\thg38_GOI_subset = hg38[keep]\n\t\thg38_GOI_subset = hg38_GOI_subset.reset_index(drop=True)\n\n\t\tstart = min(list(hg38_GOI_subset.start))\n\t\tend = max(list(hg38_GOI_subset.end))\n\t\tseqname = hg38_GOI_subset.seqname.iloc[0]\n\t\tchrom = seqname.strip('chr')\n\n\t\tvcf_sub = GOI_df_subset(vcf, chrom, start, end)\n \n\t\tif not vcf_sub.empty:\n\t\t\tcounts = coverage_search(vcf_sub)\n\t\telse:\n\t\t\tcounts = ['0:0']\n\n\t\tGOI_counts_by_cell.append([gene, counts])\n\n\tret = [currCell, GOI_counts_by_cell]\n\treturn(ret)\n\n\n\ndef average_by_gene(quad_list_, ratios_df_):\n\t\"\"\" averages expression across found loci for each gene, and converts to \n\t\tvariant / total read ratio \"\"\"\n\n\tfor elm in quad_list_:\n\t\tcell_name = elm[0]\n\t\tgenes_breakdown = elm[1]\n\n\t\tfor sub_elm in genes_breakdown:\n\t\t\tgene = sub_elm[0]\n\t\t\tvals = sub_elm[1]\n\t\t\tv_vals_total = 0\n\t\t\tt_vals_total = 0\n\t\t\t\n\t\t\tfor val in vals:\n\t\t\t\tv_val = int(val.split(':')[0])\n\t\t\t\tt_val = int(val.split(':')[1])\n\t\t\t\tv_vals_total += v_val\n\t\t\t\tt_vals_total += t_val\n\n\t\t\tif t_vals_total != 0:\n\t\t\t\tratio = v_vals_total / t_vals_total\n\t\t\t\tratio = round(ratio, 2) # round to two decimal places\n\t\t\telse:\n\t\t\t\tratio = 0\n\t\t\t\n\t\t\tratios_df_[gene][cell_name] = ratio\n\n\treturn(ratios_df_)\n\n\n\n\"\"\" get cmdline input \"\"\"\n@click.command()\n@click.option('--wrkdir', default = '/home/ubuntu/cerebra/cerebra/wrkdir/', prompt='s3 import directory', required=True)\n@click.option('--genes_list', default = 'genesList.csv', prompt='name of csv file with genes of interest to evaluate coverage for. should be in wrkdir', required=True, type=str)\n@click.option('--nthread', default = 16, prompt='number of threads', required=True, type=int)\n\n\n\ndef check_coverage_whole_gene(wrkdir, genes_list, nthread):\n\t\"\"\" evaluate the coverage across every loci with a reported variant\n\t\tfor each gene in a user defined list. reports on a per-gene \n\t\tbasis. \"\"\"\n\n\tglobal gene_names\n\tglobal hg38\n\tglobal wrkdir_\n\tnum_proc = 16\n\n\twrkdir_ = wrkdir # cmdline inputs cant be declared globals? \n\n\tvcf_list = os.listdir(wrkdir_ + 'scVCF_filtered_all/')\n\tcell_files_list = [wrkdir_ + 'scVCF_filtered_all/' + s for s in vcf_list] # list comprehension\n\tcells_list = [elm.strip(wrkdir_ + 'scVCF_filtered_all' + '.vcf') for elm in cell_files_list]\n\n\tGOI_df = pd.read_csv(wrkdir_ + genes_list, header=None, names=['gene'])\n\tgene_names = list(GOI_df.gene)\n\n\tprint(' ')\n\thg38 = pd.read_csv(wrkdir_ + 'hg38-plus.gtf', sep='\\t', header=None, names=['seqname', \n\t\t\t'source', 'feature', 'start', 'end', 'score', 'strand', 'frame', 'attribute'])\n\n\thg38['gene_id'] = 'NA'\n\tgene_ids = hg38.attribute.apply(lambda elm: elm.split(';')[0].split('\"')[1])\n\thg38.gene_id = gene_ids\n\n\n\tprint('creating pool')\n\tp = mp.Pool(processes=num_proc)\n\tprint('running...')\n\n\ttry:\n\t\tquad_list = p.map(driver, cell_files_list, chunksize=1) # returns quadruply nested list\n\tfinally:\n\t\tp.close()\n\t\tp.join()\n\n\tratios_df = pd.DataFrame(columns=gene_names, index=cells_list)\n\tratios_df[:] = 0\n\tratios_df = ratios_df.astype(float)\n\n\tratios_df_filled = average_by_gene(quad_list, ratios_df)\n\tratios_df_filled.to_csv(wrkdir_ + 'ratios_df_test.csv')\n","sub_path":"cerebra/check_coverage_whole_gene.py","file_name":"check_coverage_whole_gene.py","file_ext":"py","file_size_in_byte":5306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"68178093","text":"import telebot\r\nimport config\r\nimport random\r\nimport numpy\r\n\r\ne = 0\r\n\r\nbot = telebot.TeleBot(config.TOKEN)\r\n\r\n@bot.message_handler(content_types=['text'])\r\n\r\ndef lalala(message):\r\n t = message.text\r\n arr = []\r\n arr.append(message.text)\r\n if t == \"/say\":\r\n array = [\"Я крутой\", \"Сбежал из дурки\", \"Я - патриот Российской Федерации\", \"Ставь лайк чтобы жалко\", \"Что все пристали к этому Путену???\",\r\n \"Моргенштерн - козел\"]\r\n bot.send_message(message.chat.id, random.choice(array))\r\n elif \"морген\" in t.lower() and \"дурк\" in t.lower():\r\n bot.send_message(message.chat.id, \"Спорный вопрос, но могу сказать одно\")\r\n bot.send_message(message.chat.id, \"Моргештерн - дурачок!!\")\r\n elif \"дурк\" in t.lower():\r\n array = [\"Зачем говорить про дурку?\", \"Дурка - как раз твое место!\", \"Путин - класс, и это не обсуждается\", \"Я крутой, а ты из дурки!\",\r\n \"Мне тебя жалко, раз у тебя на устах лишь психиатрическая больница\"]\r\n textOfArray = random.choice(array)\r\n a = random.choice([0, 1, 2, 3, 4, 5])\r\n if textOfArray == \"Мне тебя жалко, раз у тебя на устах лишь психиатрическая больница\":\r\n if a == 1:\r\n textOfArray += \" номер 4\"\r\n elif a == 2:\r\n textOfArray += \" номер 13\"\r\n elif a == 3:\r\n textOfArray += \" номер 65\"\r\n elif a == 4:\r\n textOfArray += \" номер 1411\"\r\n elif a == 5:\r\n textOfArray += \" номер 534\"\r\n bot.send_message(message.chat.id, textOfArray)\r\n\r\n elif \"морген\" in t.lower():\r\n bot.send_message(message.chat.id, \"Моргештерн - дебил\")\r\n bot.send_message(message.chat.id, \"Он реально тупой\")\r\n bot.send_message(message.chat.id, \"дурачок\")\r\n elif t == \"/talk\":\r\n e += 1\r\n if e > 3:\r\n r = random.choice(arr)\r\n while True:\r\n a = random.choice([0, 1])\r\n if a == 0: break\r\n r += \" \" + random.choice\r\n bot.send_message(message.chat.id, r)\r\n else:\r\n r = \"Их всего \", e\r\n bot.send_message(message.chat.id, \"Недостаточно сообщений для воспроизведения\")\r\n bot.send_message(message.chat.id, r)\r\n else:\r\n array2 = [\"Не понял вас\", \"Вот скажите мне, зачем вы мне это написали?\", \"Не понимаю вас вообще\", \"Что вы несете, простите?\",\r\n \"Не понимаю вас. Что ж, я еще развиваюсь\", \"Не нравится мне такой ваш акцент\", message.text]\r\n bot.send_message(message.chat.id, random.choice(array2))\r\n\r\nbot.polling(none_stop=True)\r\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"306318158","text":"# C410\n\ndef func3(n, c=0):\n if n / 2 <= 1:\n return c + 1 # 这必须加1,因为需要除以2后计算\n else:\n return func3(n / 2, c + 1)\n\n# review\ndef logDiv(n, result=0):\n if n == 0:\n return 0\n elif n / 2 <= 1:\n result += 1\n return result\n else:\n n = n/2\n result += 1\n return logDiv(n, result=result)\n# C412 review\ndef asMul(m, n):\n if not isinstance(m, int) and isinstance(n, int):\n raise '请检查格式'\n elif n == 0:\n return 0\n else:\n return m + asMul(m, n-1)\n\nif __name__ == '__main__':\n print(logDiv(12))\n print(logDiv(20))\n print(logDiv(0))\n print(asMul(3, 5))\n\n","sub_path":"Desktop/myself/reader/DataStructures/ex4/logDiv.py","file_name":"logDiv.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"89630993","text":"class Solution:\n def getHint(self, secret, guess):\n \"\"\"\n :type secret: str\n :type guess: str\n :rtype: str\n \"\"\"\n n = len(secret)\n acnt, bcnt = 0, 0\n bmap = [0] * 10\n secret, guess = list(secret), list(guess)\n for i in range(n):\n if guess[i] == secret[i]:\n acnt += 1\n guess[i] = 'x'\n else:\n bmap[ord(secret[i])-ord('0')] += 1\n\n for i in range(n):\n if guess[i]!='x':\n idx = ord(guess[i]) - ord('0')\n if bmap[idx] > 0:\n bcnt += 1\n bmap[idx] -= 1\n\n return \"{0}A{1}B\".format(acnt, bcnt)\n","sub_path":"leet/0300/299.py","file_name":"299.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"643533272","text":"\"\"\"\n\ncheck if binary tree is balanced.\n\nComplexity:\n Time: O(N)\n Space: O(1)\n\n\"\"\"\n\n\nclass Node:\n def __init__(self, data=None, left=None, right=None):\n self.val = data\n self.left = left\n self.right = right\n\n\ndef is_balanced(tree):\n def check_balanced(node):\n if not node:\n return True, -1\n\n balanced, l_height = check_balanced(node.left)\n if not balanced:\n return False, -1\n\n balanced, r_height = check_balanced(node.right)\n if not balanced:\n return -1\n\n height = max(l_height, r_height) + 1\n balanced = abs(l_height - r_height) <= 1\n\n return balanced, height\n\n balanced, height = check_balanced(tree)\n return balanced\n\n\nif __name__ == \"__main__\":\n node1 = Node(1)\n node2 = Node(2)\n node3 = Node(3)\n node4 = Node(4)\n node5 = Node(5)\n node8 = Node(8)\n node9 = Node(9)\n node10 = Node(10)\n node11 = Node(11)\n\n node8.left = node4\n node8.right = node10\n node4.left = node2\n node4.right = node5\n node5.left = None\n node5.right = None\n\n node2.left = node1\n node2.right = node3\n node1.left = None\n node2.right = None\n node3.left = None\n node3.right = None\n\n node10.left = node9\n node10.right = node11\n node9.left = None\n node9.right = None\n node11.left = None\n node11.right = None\n\n print(is_balanced(node8))\n\n","sub_path":"trees/is_balanced.py","file_name":"is_balanced.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"159679457","text":"\"\"\"\n Only for developers.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport os\nimport glob\nimport socket\nimport shutil\nimport argparse\nimport subprocess\nfrom datetime import datetime\nimport AdaptivePELE as a\nfrom AdaptivePELE.utilities import utilities\nfrom AdaptivePELE.constants import environments\n\n\ndef parseArgs():\n parser = argparse.ArgumentParser(description=\"Helper script to automate the process of releasing a new version\")\n parser.add_argument('--name', type=str, default=None)\n arg = parser.parse_args()\n return arg.name\n\n\ndef copy_ignore(src, names):\n return [x for x in names if x.endswith(\".so\")]\n\ndef join_cmds(prefix, suffix):\n if not prefix:\n return suffix\n else:\n return prefix+\"; \"+suffix\n\ndef log_install(file_descriptor, prepare_str):\n file_descriptor.write(\"Python used in installation: \")\n version = subprocess.check_output(join_cmds(prepare_str, \"python --version\"), shell=True,\n universal_newlines=True, stderr=subprocess.STDOUT)\n file_descriptor.write(version)\n\n file_descriptor.write(\"Compiler used in installation: \")\n compiler = subprocess.check_output(join_cmds(prepare_str, \"echo $CC\"), shell=True,\n universal_newlines=True, stderr=subprocess.STDOUT)\n file_descriptor.write(compiler)\n\n file_descriptor.write(\"Installed on %s\\n\" % str(datetime.now()))\n file_descriptor.write(\"Modules loaded in installation:\\n\")\n\n modules = subprocess.check_output(join_cmds(prepare_str, \"module list\"), shell=True,\n universal_newlines=True, stderr=subprocess.STDOUT)\n file_descriptor.write(modules)\n\ndef build_extensions(name, releaseFolder, releaseName):\n all_envs = environments.get(name)\n # force recompiles everything even if no changes are detected, needed\n # to recompile with different versions\n compile_cmd = 'python setup.py build_ext --inplace --force'\n with open(os.path.join(releaseFolder, releaseName, \"installation_info.txt\"), \"w\") as fw:\n if all_envs is None:\n # if no particular environment is specified just rely on whathever is\n # set when calling the script\n subprocess.call(['python', 'setup.py', 'build_ext', '--inplace'])\n log_install(fw, \"\")\n else:\n for env_str in all_envs:\n prepare_str = \"; \".join([\"module purge 2> /dev/null\", env_str])\n # call all commands in the same shell, so the module changes\n # take effect\n print(join_cmds(prepare_str, compile_cmd))\n subprocess.call(join_cmds(prepare_str, \"python --version\"), universal_newlines=True, shell=True)\n subprocess.call(join_cmds(prepare_str, compile_cmd), universal_newlines=True, shell=True)\n log_install(fw, prepare_str)\n fw.write(\"\\n\")\n\ndef main(releaseName):\n machine = socket.gethostname()\n name = machine\n if \"bsccv\" in machine:\n name = \"life\"\n releaseFolder = \"/data2/bsc72/AdaptiveSampling/bin\"\n elif 'login' in machine:\n name = os.getenv(\"BSC_MACHINE\")\n if name == \"mn4\":\n releaseFolder = \"/gpfs/projects/bsc72/adaptiveSampling/bin\"\n elif name == \"nord3\":\n releaseFolder = \"/gpfs/projects/bsc72/adaptiveSampling/bin_nord\"\n elif name == \"nvidia\":\n releaseFolder = \"/gpfs/projects/bsc72/adaptiveSampling/bin_mt\"\n elif name == \"power\":\n releaseFolder = \"/gpfs/projects/bsc72/adaptiveSampling/bin_cte\"\n\n if releaseName is None:\n releaseName = \"v%s\" % a.__version__\n toOmit = [\"tests\", \"runAllTests.py\", \"os\", \"sys\", \"TODO.txt\", \"Data\", \"Documents\", \"DataLocal\", \"epsilon_values.txt\", \"makeRelease.py\", \".git\", \".gitignore\"]\n toOmit += ['runTestsCuda.sl', 'runMDTest.sl', 'runAllTests.sl', 'runAllTests_nord.sl', 'runTestsCuda_CTE.sl', 'AdaptiveTest_CUDA.err', 'AdaptiveTest_CUDA.out']\n\n\n files = glob.glob(\"*\")\n if os.path.exists(os.path.join(releaseFolder, releaseName)):\n raise ValueError(\"Installation already found! Check that the version of the user-provided release name is correct\")\n utilities.makeFolder(os.path.join(releaseFolder, releaseName))\n destFolder = os.path.join(releaseFolder, releaseName, \"AdaptivePELE\", \"%s\")\n for filename in files:\n if filename in toOmit or filename.startswith(\".\") or filename.endswith(\"pyc\"):\n continue\n try:\n if not os.path.exists(destFolder % filename):\n print(\"Copying\", filename)\n shutil.copytree(filename, destFolder % filename, ignore=copy_ignore)\n except (IOError, OSError):\n shutil.copyfile(filename, destFolder % filename)\n\n extraFiles = [\"../README.rst\", \"../setup.py\"]\n for filename in extraFiles:\n if not os.path.exists(destFolder % filename):\n shutil.copyfile(filename, destFolder % filename)\n print(\"Copying\", os.path.split(filename)[1])\n\n print(\"Compiling cython extensions\")\n os.chdir(destFolder % \"..\")\n build_extensions(name, releaseFolder, releaseName)\n\n print(\"Done with release %s!\" % releaseName)\n\nif __name__ == \"__main__\":\n name_install = parseArgs()\n main(name_install)\n","sub_path":"AdaptivePELE/makeRelease.py","file_name":"makeRelease.py","file_ext":"py","file_size_in_byte":5346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"463273695","text":"import inputs\nimport sys\n\npads = inputs.devices.gamepads\nif len(pads) == 0:\n\traise Exception(\"Could not find Gamepads!\")\n\ntry:\n\twhile True:\n\t\tevents = inputs.get_gamepad()\n\t\tfor event in events:\n print(f\"{event.code}, {event.state}\")\n\t\t\t\nexcept KeyboardInterrupt:\n\tsys.exit()\n","sub_path":"test-scripts/joystick.py","file_name":"joystick.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"496519994","text":"#! /user/bin/evn python\n# -*- coding:utf8 -*-\nimport codecs\nimport re\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow.contrib as tc\nimport os\nfrom sklearn.model_selection import train_test_split\n\n\n# 读入文件\n# 预处理\n# 建立词典\n# 划分数据集:train dev\n# batch iterator\ndef clean_str(string):\n \"\"\"\n Tokenization/string cleaning for all datasets except for SST.\n Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py\n :param string:\n :return: string\n \"\"\"\n string = re.sub(r\"[^A-Za-z0-9(),!?\\'\\`]\", \" \", string)\n string = re.sub(r\"\\'s\", \" \\'s\", string)\n string = re.sub(r\"\\'ve\", \" \\'ve\", string)\n string = re.sub(r\"n\\'t\", \" n\\'t\", string)\n string = re.sub(r\"\\'re\", \" \\'re\", string)\n string = re.sub(r\"\\'d\", \" \\'d\", string)\n string = re.sub(r\"\\'ll\", \" \\'ll\", string)\n string = re.sub(r\",\", \" , \", string)\n string = re.sub(r\"!\", \" ! \", string)\n string = re.sub(r\"\\(\", \" \\( \", string)\n string = re.sub(r\"\\)\", \" \\) \", string)\n string = re.sub(r\"\\?\", \" \\? \", string)\n string = re.sub(r\"\\s{2,}\", \" \", string)\n return string.strip().lower()\n\n\ndef get_header_file(file_path):\n x_headers = []\n y_labels = []\n with codecs.open(filename=file_path, encoding='utf-8') as fp:\n while True:\n line = fp.readline()\n if not line:\n print('Data loaded successful!')\n x_headers = [clean_str(str(header)) for header in x_headers]\n y_labels = np.array(y_labels)\n # print('x_headers.shape: ', x_headers.__len__())\n # print('y.shape: ', y_labels.shape())\n return [x_headers, y_labels]\n # line = '10.1016/j.compgeo.2012.01.008\t Introduction\t1'\n tmp = line.strip().split('\\t')[-2:]\n header, label = tmp[0], int(tmp[1])\n if label == 1:\n y_labels.append([1, 0, 0, 0, 0])\n elif label == 2:\n y_labels.append([0, 1, 0, 0, 0])\n elif label == 3:\n y_labels.append([0, 0, 1, 0, 0])\n elif label == 4:\n y_labels.append([0, 0, 0, 1, 0])\n else:\n y_labels.append([0, 0, 0, 0, 1])\n x_headers.append(header)\n # y_labels.append(label)\n\n\ndef get_section_file(file_path):\n \"\"\"\n load header data from files, splits the data into words and labels\n :param file_path:\n :return: headers, labels\n \"\"\"\n sections = []\n labels = []\n with codecs.open(file_path, encoding='utf-8') as fp:\n while True:\n line = fp.readline()\n if not line:\n print(\"Data loaded successfully!\")\n sections = [clean_str(str(section)) for section in sections]\n return [sections, np.array(labels)]\n tmp = line.strip().split('\\t')[-2:]\n # label, section = int(tmp[0]), tmp[1]\n label, section = int(tmp[0]), tmp[1]\n sections.append(section)\n if label == 1:\n labels.append([1, 0, 0, 0, 0])\n elif label == 2:\n labels.append([0, 1, 0, 0, 0])\n elif label == 3:\n labels.append([0, 0, 1, 0, 0])\n elif label == 4:\n labels.append([0, 0, 0, 1, 0])\n else:\n labels.append([0, 0, 0, 0, 1])\n # labels.append(label)\n\n\ndef get_paragraph_file(file_path):\n \"\"\"\n load data from files, splits the data into words and labels\n :return: paras, labels\n \"\"\"\n paras = []\n labels = []\n with codecs.open(file_path, encoding='utf-8') as fp:\n while True:\n line = fp.readline()\n if not line:\n print(\"Data loaded successfully!\")\n paras = [clean_str(paragraph) for paragraph in paras]\n return [paras, np.array(labels)]\n tmp = line.strip().split('\\t')[-2:]\n # label, para = int(tmp[0]), tmp[1]\n label, para = int(tmp[0]), tmp[1]\n if label == 1:\n labels.append([1, 0, 0, 0, 0])\n elif label == 2:\n labels.append([0, 1, 0, 0, 0])\n elif label == 3:\n labels.append([0, 0, 1, 0, 0])\n elif label == 4:\n labels.append([0, 0, 0, 1, 0])\n else:\n labels.append([0, 0, 0, 0, 1])\n # labels.append(label)\n paras.append(para)\n\n\ndef load_header_data(data_file_dir, save_vocab_dir, dev_percentage, sequence_length):\n x_header, y = get_header_file(data_file_dir)\n\n # 构造词典\n vocab_processor = tc.learn.preprocessing.VocabularyProcessor(max_document_length=sequence_length)\n # fit-词典 transform-padding fit_transform词典+padding\n x = np.array(list(vocab_processor.fit_transform(x_header))) # fit_transform Return: yield\n\n # 保存词典\n vocab_processor.save(os.path.join(save_vocab_dir, 'header_vocab'))\n\n # print(os.path.join(save_vocab_dir, 'header_vocab'))\n\n np.random.seed(1)\n shuffle_indices = np.random.permutation(np.arange(len(y)))\n x_shuffled = x[shuffle_indices]\n y_shuffled = y[shuffle_indices]\n\n # 使用包sklearn\n x_train, x_dev, y_train, y_dev = train_test_split(x_shuffled, y_shuffled, test_size=dev_percentage, random_state=1)\n\n del x_header, x, y\n print('training vocabulary size is {:d}'.format(len(vocab_processor.vocabulary_)))\n print('Train/Dev split: {:d}/{:d}'.format(len(y_train), len(y_dev)))\n\n return x_train, y_train, x_dev, y_dev\n\n\ndef load_section_data(data_file, save_vocab_dir, dev_sample_percentage, max_length):\n x_text, y = get_section_file(data_file)\n\n # Build vocabulary\n # max_document_length = max([len(x.split(\" \")) for x in x_text])\n vocab_processor = tf.contrib.learn.preprocessing.VocabularyProcessor(max_document_length=max_length)\n # 神器,填充到最大长度\n x = np.array(list(vocab_processor.fit_transform(x_text)))\n\n # Write vocabulary\n vocab_processor.save(os.path.join(save_vocab_dir, 'section_vocab'))\n # vocab_processor.save(save_vocab_dir)\n\n # Randomly shuffle data\n\n # Split train/test set\n # TODO: use k-fold cross validation\n x_train, x_dev, y_train, y_dev = train_test_split(x, y, test_size=dev_sample_percentage, random_state=22)\n\n del x, y\n\n print(\"Vocabulary Size: {:d}\".format(len(vocab_processor.vocabulary_)))\n print(\"Train/Dev split: {:d}/{:d}\".format(len(y_train), len(y_dev)))\n return x_train, y_train, x_dev, y_dev\n\n\ndef load_paragraph_data(data_file, save_vocab_dir, dev_sample_percentage, max_length):\n x_text, y = get_paragraph_file(data_file)\n\n # Build vocabulary\n # max_document_length = max([len(x.split(\" \")) for x in x_text])\n vocab_processor = tf.contrib.learn.preprocessing.VocabularyProcessor(max_document_length=max_length)\n # 神器,填充到最大长度\n x = np.array(list(vocab_processor.fit_transform(x_text)))\n\n # Write vocabulary\n vocab_processor.save(os.path.join(save_vocab_dir, 'paragraph_vocab'))\n\n # Randomly shuffle data\n np.random.seed(10)\n shuffle_indices = np.random.permutation(np.arange(len(y)))\n x_shuffled = x[shuffle_indices]\n y_shuffled = y[shuffle_indices]\n\n # Split train/test set\n # TODO: use k-fold cross validation\n\n x_train, x_dev, y_train, y_dev = train_test_split(x_shuffled, y_shuffled, test_size=dev_sample_percentage)\n\n del x, y, x_shuffled, y_shuffled\n\n print(\"Vocabulary Size: {:d}\".format(len(vocab_processor.vocabulary_)))\n print(\"Train/Dev split: {:d}/{:d}\".format(len(y_train), len(y_dev)))\n return x_train, y_train, x_dev, y_dev\n\n\n\n\n\n\n#\n# def load_header_testing_data(data_file_dir, save_vocab_dir, sequence_length):\n# x_header, y_test = get_headerFile(data_file_dir)\n#\n# # 构造词典\n# vocab_processor = tc.learn.preprocessing.VocabularyProcessor(max_document_length=sequence_length)\n# # fit-词典 transform-padding fit_transform词典+padding\n# x_test = np.array(vocab_processor.fit_transform(x_header))\n#\n# # 保存词典\n# vocab_processor.save(os.path.join(save_vocab_dir, 'vocab_test'))\n# print('testing vocabulary size is {:d}'.format(len(vocab_processor.vocabulary_)))\n#\n# return x_test, y_test\n\n\n# generate batch data\ndef batch_iterator(x, y, batch_size=64, isShuffle=True):\n data_lenth = len(y)\n num_batch = int((data_lenth - 1) / batch_size) + 1 #运算加括号!\n\n # train 需要shuffle test不需要\n if isShuffle:\n shuffle_indices = np.random.permutation(np.arange(data_lenth))\n x_shuffled = x[shuffle_indices]\n y_shuffled = y[shuffle_indices]\n\n for i in range(num_batch):\n start_index = i * batch_size\n end_index = min((i+1) * batch_size, data_lenth)\n yield x_shuffled[start_index: end_index], y_shuffled[start_index: end_index]\n\n\ndef batch_iterator_dev(x, y, batch_size=64):\n data_lenth = len(x)\n num_batch = int((data_lenth-1) / batch_size) + 1\n # print(\"num_batch = \", num_batch)\n\n indices = np.random.permutation(np.arange(data_lenth))\n x_shuffled = x[indices]\n y_shuffled = y[indices]\n\n for i in range(num_batch):\n # print(\"i= \", i)\n start_index = i * batch_size\n end_index = min((i+1) * batch_size, data_lenth)\n yield x_shuffled[start_index: end_index], y_shuffled[start_index: end_index]\n","sub_path":"data/dataLoader_dt.py","file_name":"dataLoader_dt.py","file_ext":"py","file_size_in_byte":9422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"478127995","text":"from urllib import request\nfrom pymongo import MongoClient\nimport json\nfrom datetime import datetime\nimport os\nimport sys\n\napiUrl = os.environ['SENSOR_DATA_API_URL']\nmongoUrl = os.environ['DATABASE_URL']\ndbName = os.environ['DATABASE_NAME']\ncollectionName = 'sensorData'\n\ndef service():\n try:\n client = MongoClient(mongoUrl)\n db = client[dbName]\n\n jsonRecvd = request.urlopen(apiUrl).read().decode('utf-8')\n sensorData = json.loads(jsonRecvd)\n\n db[collectionName].insert_many(sensorData)\n\n return {\n 'success': True,\n 'time': str(datetime.now().isoformat())\n }\n except Exception as exception:\n print(str(exception), file = sys.stderr)\n return {\n 'success': False,\n 'time': str(datetime.now().isoformat())\n }\n\ndef requester(request):\n return json.dumps(\n service()\n )","sub_path":"deprecated/BackgroundServiceWorker/cloudfunction.py","file_name":"cloudfunction.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"458890161","text":"def normalizeHangul(s):\n def split(c):\n from hangul_utils import split_syllable_char\n jm = split_syllable_char(c)\n #if jm[0] == 'ㅇ': return jm[1:]\n return jm\n\n def split_syllables(string):\n from hangul_utils import check_syllable\n new_string = \"\"\n for c in string:\n if not check_syllable(c):\n new_c = c\n else:\n new_c = \"\".join(split(c))\n new_string += new_c\n return new_string\n\n s = split_syllables(s)\n for k, v in {'ᆫ': 'ㄴ', 'ᆯ': 'ㄹ', 'ᄆ': 'ㅁ', 'ᄇ': 'ㅂ', 'ᆼ': 'ㅇ'}.items():\n s = s.replace(k, v)\n if len(s) and 'ㅏ' <= s[0] <= 'ㅣ': return 'ㅇ' + s\n return s","sub_path":"ModelGenerator/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"568914989","text":"# Django settings for api project.\nimport os\nimport sys\nimport json\nimport base64\n\nfrom django.core.urlresolvers import resolve\n\nPROJECT_ROOT = os.path.realpath(os.path.dirname(os.path.dirname(__file__)))\n\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# On Unix systems, a value of None will cause Django to use the same\n# timezone as the operating system.\n# If running in a Windows environment this must be set to the same as your\n# system time zone.\nTIME_ZONE = 'America/New_York'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'en-us'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale\nUSE_L10N = True\n\n# Absolute path to the directory that holds media.\n# Example: \"/home/media/media.lawrence.com/\"\nMEDIA_ROOT = os.path.join(PROJECT_ROOT, 'cwod_site', 'media')\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash if there is a path component (optional in other cases).\n# Examples: \"http://media.lawrence.com\", \"http://example.com/media/\"\nMEDIA_URL = '/media/'\n\n# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a\n# trailing slash.\n# Examples: \"http://foo.com/media/\", \"/media/\".\n#ADMIN_MEDIA_PREFIX = '/media/'\nADMIN_MEDIA_PREFIX = os.path.join(PROJECT_ROOT, 'cwod_site', 'media')\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n 'django.template.loaders.eggs.Loader',\n)\n\nMIDDLEWARE_CLASSES = (\n 'cwod_api.middleware.jsonp.JSONPMiddleware',\n 'django.middleware.cache.UpdateCacheMiddleware',\n 'locksmith.auth.middleware.APIKeyMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.cache.FetchFromCacheMiddleware',\n)\n\nSESSIONS_ENGINE = 'django.contrib.sessions.backends.cookies'\nSESSION_COOKIE_HTTPONLY = True\n\nMESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'\n\nEMAIL_BACKEND = \"postmark.backends.PostmarkBackend\"\nEMAIL_FROM = \"contact@sunlightfoundation.com\"\n\nSTART_YEAR = 1996\n\nROOT_URLCONF = 'urls'\n\nTEMPLATE_DIRS = (\n os.path.join(PROJECT_ROOT, 'cwod_site', 'templates')\n # Put strings here, like \"/home/html/django_templates\" or \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n\nAUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend',\n 'locksmith.hub.auth_backend.LocksmithBackend',\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.contrib.auth.context_processors.auth',\n 'django.core.context_processors.request',\n 'cwod.context_processors.recent_top_unigrams',\n 'cwod.context_processors.search_terms',\n 'cwod.context_processors.frontend',\n 'cwod.context_processors.tickmarks',\n)\n\nINSTALLED_APPS = (\n 'django.contrib.humanize',\n 'django.contrib.sessions',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.admin',\n 'django.contrib.messages',\n 'django.contrib.markup',\n 'cwod',\n 'cwod_api',\n 'bioguide',\n 'jsonfield',\n # 'locksmith.hub',\n 'locksmith.auth',\n 'locksmith.logparse',\n 'gunicorn',\n 'ngrams',\n 'mediasync',\n 'typogrify',\n)\n\nfrom local_settings import (MEDIASYNC_AWS_KEY, MEDIASYNC_AWS_SECRET,\n MEDIASYNC_AWS_BUCKET, MEDIASYNC_AWS_PREFIX,\n MEDIASYNC_SERVE_REMOTE, MEDIA_VERSION)\n\nMEDIASYNC = {\n 'BACKEND': 'mediasync.backends.s3',\n 'AWS_KEY': MEDIASYNC_AWS_KEY,\n 'AWS_SECRET': MEDIASYNC_AWS_SECRET,\n 'AWS_BUCKET': MEDIASYNC_AWS_BUCKET,\n 'AWS_PREFIX': MEDIASYNC_AWS_PREFIX,\n 'MEDIA_URL': '/media/',\n 'SERVE_REMOTE': MEDIASYNC_SERVE_REMOTE,\n 'STATIC_ROOT': os.path.join(PROJECT_ROOT, 'cwod_site', 'media'),\n 'PROCESSORS': (\n 'mediasync.processors.slim.css_minifier',\n # 'mediasync.processors.closurecompiler.compile',\n ),\n 'JOINED': {\n #'css/joined.css': ['css/main.css','css/jquery.ui/jquery.ui.all.css'],\n 'js/joined.js': ['js/underscore/underscore-min.js',\n 'js/spin/spin.min.js',\n 'js/history/scripts/compressed/amplify.store.js',\n 'js/history/scripts/compressed/history.adapter.jquery.js',\n 'js/history/scripts/compressed/history.js',\n 'js/history/scripts/compressed/history.html4.js',\n 'js/jquery.ui/jquery.ui.core.js',\n 'js/jquery.ui/jquery.ui.widget.js',\n 'js/jquery.ui/jquery.ui.mouse.js',\n 'js/jquery.ui/jquery.ui.slider.js',\n 'js/jquery.imagesloaded.js',\n 'js/emphasis/emphasis.js',\n 'js/google-chart.js',\n 'js/capitolwords.js',\n 'js/annotations.js',\n 'js/app.js',],\n },\n\n}\n\n# Sunlight Labs api key\nAPI_KEY = os.environ.get(\"CAPWORDS_APIKEY\")\nSUNLIGHT_API_KEY = API_KEY\nBASE_URL = os.environ.get(\"CAPWORDS_BASEURL\")\nAPI_ROOT = os.environ.get(\"CAPWORDS_BASEURL\") + \"/api\"\nCWOD_HOME = os.environ.get(\"CAPWORDS_HOME\")\nTMP_DIR = os.environ.get(\"CAPWORDS_TMP\")\nLOG_DIR = os.environ.get(\"CAPWORDS_LOGS\")\n\n# how far back in time does the system check for congressional record\n# documents? dd/mm/yyyy format.\nOLDEST_DATE = '01/06/2010'\n# where should the scraper log the files it's downloaded?\nSCRAPER_LOG = os.path.join(LOG_DIR, 'scraper.log')\n# what domain and port are solr listening on?\nSOLR_DOMAIN = os.environ.get(\"CAPWORDS_SOLR_URL\")\n\ndb_serialized = os.environ.get(\"CAPWORDS_DATABASE\")\nif db_serialized:\n DATABASES = json.loads(base64.b64decode(db_serialized).decode('utf-8'))\n\ndef api_resolve(x):\n match = resolve(x)\n if hasattr(match.func, 'handler'):\n # resolve piston resources\n return match.func.handler.__class__.__name__\n else:\n return match.func\n\nLOCKSMITH_LOG_CUSTOM_TRANSFORM = api_resolve\n\ntry:\n from local_settings import *\nexcept ImportError:\n sys.stderr.write(\"Unable to load local settings. Make sure local_settings.py exists and is free of errors.\\n\")\n\n","sub_path":"cwod_site/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":7026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"83328642","text":"\"\"\"This file is part of the trivago/rebase library.\n\n# Copyright (c) 2018 trivago N.V.\n# License: Apache 2.0\n# Source: https://github.com/trivago/rebase\n# Version: 1.2.2\n# Python Version: 3.6\n# Author: Yuv Joodhisty \n\"\"\"\n\nfrom rebase.core import Validator\nfrom rebase.validators import IntegerValidator\n\n\nclass RangeValidator(Validator):\n def properties(self):\n return {\n **super().properties(),\n 'min': None,\n 'max': None,\n 'message': lambda: '{value} is not within the range {min} and {max}'\n }\n\n def validate(self, value):\n if not super().validate(value):\n return False\n\n is_valid = True\n\n if not (int(value) >= self.min and int(value) <= self.max):\n self.errors.append(\n self.message.format(\n value=str(value),\n min=str(self.min),\n max=str(self.max)\n )\n )\n is_valid &= False\n\n return is_valid\n\n def depends_on(self):\n return {IntegerValidator(required=self.required)}\n","sub_path":"rebase/validators/range_validator.py","file_name":"range_validator.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"372649639","text":"#!/usr/bin/env python3\n\n# Copyright 2022 The IREE Authors\n#\n# Licensed under the Apache License v2.0 with LLVM Exceptions.\n# See https://llvm.org/LICENSE.txt for license information.\n# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\"\"\"Determines whether CI should run on a given PR.\n\nExit code 0 indicates that it should and exit code 2 indicates that it should\nnot.\n\"\"\"\n\nimport fnmatch\nimport os\nimport subprocess\nimport sys\n\nSKIP_CI_TAG = \"skip-ci\"\n\n# Note that these are fnmatch patterns, which are not the same as gitignore\n# patterns because they don't treat '/' specially. The standard library doesn't\n# contain a function for gitignore style \"wildmatch\". There's a third-party\n# library pathspec (https://pypi.org/project/pathspec/), but it doesn't seem\n# worth the dependency.\nSKIP_PATH_PATTERNS = [\n \"docs/*\",\n \"experimental/*\",\n \"build_tools/kokoro/*\",\n \"build_tools/buildkite/*\",\n \".github/ISSUE_TEMPLATE/*\",\n \"*.cff\",\n \"*.clang-format\",\n \"*.git-ignore\",\n \"*.md\",\n \"*.natvis\",\n \"*.pylintrc\",\n \"*.rst\",\n \"*.toml\",\n \"*.yamllint.yml\",\n \"*.yapf\",\n \"*CODEOWNERS\",\n \"*AUTHORS\",\n \"*LICENSE\",\n]\n\n\ndef skip_path(path):\n return any(fnmatch.fnmatch(path, pattern) for pattern in SKIP_PATH_PATTERNS)\n\n\ndef get_modified_paths(base_ref):\n return subprocess.run([\"git\", \"diff\", \"--name-only\", base_ref],\n stdout=subprocess.PIPE,\n check=True,\n text=True,\n timeout=60).stdout.splitlines()\n\n\ndef modifies_included_path(base_ref):\n return any(not skip_path(p) for p in get_modified_paths(base_ref))\n\n\ndef should_run_ci():\n event_name = os.environ[\"GITHUB_EVENT_NAME\"]\n base_ref = os.environ[\"BASE_REF\"]\n description = os.environ[\"PR_DESCRIPTION\"]\n\n if event_name != \"pull_request\":\n print(\"Running CI independent of diff because run was not triggered by a\"\n \"pull request event.\")\n return True\n\n for line in description.splitlines():\n if line.strip().lower() == SKIP_CI_TAG:\n print(f\"Not running CI because PR description has '{SKIP_CI_TAG}' line.\")\n return False\n\n try:\n modifies = modifies_included_path(base_ref)\n except TimeoutError as e:\n print(\"Computing modified files timed out. Running the CI\")\n return True\n\n if not modifies:\n print(\"Skipping CI because all modified files are marked as excluded.\")\n return False\n\n return True\n\n\ndef main():\n if should_run_ci():\n print(\"CI should run\")\n sys.exit(0)\n print(\"CI should not run\")\n sys.exit(2)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"build_tools/github_actions/should_ci_run.py","file_name":"should_ci_run.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"578321771","text":"#!/usr/bin/env python3\n#===============================================================================\n# chipseqpeaks.py\n#===============================================================================\n\n\"\"\"A wrapper for MACS2 that abstracts out some things and makes it easier to use\n\"\"\"\n\n\n\n\n# Imports ======================================================================\n\nimport os\nimport os.path\nimport shutil\nimport subprocess\nimport socket\nimport sys\nimport tempfile\n\n\n\n# Constants ====================================================================\n\nMACS2_PATH = os.environ.get('MACS2_PATH', shutil.which('macs2'))\nBEDTOOLS_PATH = os.environ.get('BEDTOOLS_PATH', shutil.which('bedtools'))\nHG38_BLACKLIST_PATH = os.path.join(\n os.path.dirname(__file__), 'ENCFF419RSJ.bed.gz'\n)\nHG19_BLACKLIST_PATH = os.path.join(\n os.path.dirname(__file__), 'ENCFF001TDO.bed.gz'\n)\nMM10_BLACKLIST_PATH = os.path.join(\n os.path.dirname(__file__), 'ENCFF547MET.bed.gz'\n)\nGENOME_TO_BLACKLIST = {\n 'GRCh38': HG38_BLACKLIST_PATH,\n 'hg38': HG38_BLACKLIST_PATH,\n 'GRCh37': HG19_BLACKLIST_PATH,\n 'hg19': HG19_BLACKLIST_PATH,\n 'mm10': MM10_BLACKLIST_PATH\n}\n\n\n\n\n# Classes ======================================================================\n\nclass ChIPSeqPeaks():\n \"\"\"ChIP-seq peaks\n \n Attributes\n ----------\n treatment_bam : bytes\n the treatment BAM file\n control_bam : bytes\n the control/input BAM file\n qvalue : float\n --qvalue parameter supplied to MACS2\n nomodel : bool\n if True, MACS2 is run with the --nomodel option [False]\n shift : int\n --shift parameter supplied to MACS2\n broad : bool\n if True, MACS2 is run with the --broad option [False]\n broad_cutoff : float\n --broad-cutoff parameter supplied to MACS2\n log\n file object to which logs will be writtern\n output_extensions : list\n the extensions for MACS2 output files\n temp_dir\n directory name for temporary files\n \"\"\"\n \n def __init__(\n self,\n treatment_bam,\n macs2_path=MACS2_PATH,\n atac_seq=False,\n control_bam=None,\n qvalue=0.05,\n nomodel=False,\n shift=0,\n extsize=200,\n broad=False,\n broad_cutoff=0.1,\n nolambda=False,\n call_summits=False,\n log=None,\n temp_dir=None\n ):\n \"\"\"Collect object attributes and call peaks\n \n Parameters\n ----------\n treatment_bam : bytes\n the treatment BAM file\n atac_seq : bool\n if true, parameter defaults will be configured for ATAC-seq\n control_bam : bytes\n the control/input BAM file\n qvalue : float\n --qvalue parameter supplied to MACS2\n nomodel : bool\n if True, MACS2 is run with the --nomodel option [False]\n shift : int\n --shift parameter supplied to MACS2\n extsize : int\n --extsize parameter supplied to MACS2\n broad : bool\n if True, MACS2 is run with the --broad option [False]\n broad_cutoff : float\n --broad-cutoff parameter supplied to MACS2\n log\n file object to which logs will be writtern\n temp_dir\n directory name for temporary files\n \"\"\"\n\n if not macs2_path:\n raise MissingMACS2Error(\n '''MACS2 was not found! Please provide the `macs2_path`\n parameter to ChIPSeqPeaks(), or set the `MACS2_PATH`\n environment variable, or make sure `macs2` is installed and\n can be found via the `PATH` environment variable.\n '''\n )\n self.treatment_bam = parse_input(treatment_bam)\n self.macs2_path = macs2_path\n self.control_bam = parse_input(control_bam) if control_bam else None\n self.qvalue = qvalue\n self.nomodel = True if atac_seq and not nomodel else nomodel\n self.shift = -100 if atac_seq and not shift else shift\n self.extsize = extsize\n self.broad = broad\n self.broad_cutoff = broad_cutoff\n self.nolambda = nolambda\n self.call_summits = call_summits\n self.cleans_up = False\n self.cleanup_prefix = None\n self.log = log\n self.temp_dir = temp_dir\n self.output_extensions = (\n ['peaks.xls', 'peaks.narrowPeak', 'summits.bed', 'treat_pileup.bdg']\n + bool(control_bam) * ['control_lambda.bdg']\n + broad * ['peaks.broadPeak', 'peaks.gappedPeak']\n )\n self.call_peaks(temp_dir=temp_dir)\n \n def __enter__(self):\n \"\"\"When an instance of this class is used as a context manager, it is\n assumed that files written to disk should be removed after exiting\n context.\n \"\"\"\n\n self.cleans_up = True\n return self\n \n def __exit__(self, exc_type, exc_value, traceback):\n \"\"\"Clean up a files on disk\"\"\"\n\n if self.cleans_up:\n for ext in self.output_extensions:\n self.clean_up('{}_{}'.format(self.cleanup_prefix, ext))\n return False\n \n def __repr__(self):\n \"\"\"Show some of the peak calling parameters\"\"\"\n\n return '\\n'.join(\n (\n 'ChipPeaks(',\n ')'\n )\n ).format(self)\n \n def call_peaks(self, temp_dir=None):\n \"\"\"Perform peak calling with MACS2\n\n Parameters\n ----------\n temp_dir : str\n directory name for temporary files\n \"\"\"\n\n with tempfile.NamedTemporaryFile(dir=temp_dir) as (\n temp_treatment_bam\n ), tempfile.NamedTemporaryFile(dir=temp_dir) as (\n temp_control_bam\n ), tempfile.TemporaryDirectory(dir=temp_dir) as (\n temp_dir_name\n ):\n temp_treatment_bam.write(self.treatment_bam)\n if self.control_bam:\n temp_control_bam.write(self.control_bam)\n with tempfile.NamedTemporaryFile(\n dir=temp_dir_name\n ) as temp:\n temp_name = temp.name\n subprocess.call(\n (\n self.macs2_path, 'callpeak',\n '-B',\n '--extsize', str(self.extsize),\n '--keep-dup', 'all',\n '--treatment', temp_treatment_bam.name,\n '--name', temp_name,\n '--qvalue', str(self.qvalue),\n '--shift', str(self.shift),\n '--tempdir', temp_dir or tempfile.gettempdir()\n )\n + bool(self.control_bam) * ('--control', temp_control_bam.name)\n + self.nomodel * ('--nomodel',)\n + self.broad * (\n '--broad',\n '--broad-cutoff', str(self.broad_cutoff)\n )\n + self.nolambda * ('--nolambda',)\n + self.call_summits * ('--call-summits',),\n stderr=self.log\n )\n for ext in self.output_extensions:\n with subprocess.Popen(\n ('cat', '{}_{}'.format(temp_name, ext)),\n stdout=subprocess.PIPE\n ) as cat:\n output_file, _ = cat.communicate()\n setattr(self, ext.replace('.', '_'), output_file)\n \n def bdgcmp(self):\n \"\"\"Create a bedgraph\"\"\"\n\n self.output_extensions.append('ppois.bdg')\n with tempfile.NamedTemporaryFile(dir=self.temp_dir) as (\n temp_treat_pileup\n ), tempfile.NamedTemporaryFile(dir=self.temp_dir) as (\n temp_control_lambda\n ), tempfile.TemporaryDirectory(dir=self.temp_dir) as (\n temp_dir_name\n ):\n temp_treat_pileup.write(self.treat_pileup_bdg)\n temp_control_lambda.write(self.control_lambda_bdg)\n with tempfile.NamedTemporaryFile(\n dir=temp_dir_name\n ) as temp:\n temp_name = temp.name\n subprocess.call(\n (\n self.macs2_path, 'bdgcmp',\n '-t', temp_treat_pileup.name,\n '-c', temp_control_lambda.name,\n '-m', 'ppois',\n '--o-prefix', temp_name,\n '-p', '0.00001'\n ),\n stderr=self.log\n )\n with subprocess.Popen(\n ('cat', '{}_ppois.bdg'.format(temp_name)),\n stdout=subprocess.PIPE\n ) as cat:\n self.ppois_bdg, _ = cat.communicate()\n \n def remove_blacklisted_peaks(\n self,\n blacklist_path: str = HG38_BLACKLIST_PATH,\n genome: str = 'GRCh38',\n bedtools_path: str = BEDTOOLS_PATH\n ):\n \"\"\"Remove blacklisted peaks from the peak calls\n \n Parameters\n ----------\n blacklist_path : str\n path to the ENCODE blacklist file\n genome : str\n genome assembly (for selection of blacklist)\n bedtools_path : str\n Path to bedtools executable\n \"\"\"\n\n if (blacklist_path == HG38_BLACKLIST_PATH) and (\n genome not in {'GRCh38', 'hg38'}\n ):\n blacklist_path = GENOME_TO_BLACKLIST[genome]\n for peaks in (self.peaks_narrowPeak,) + (\n (self.peaks_broadPeak, self.peaks_gappedPeak) if self.broad else ()\n ): \n blacklisted_peaks = bedtools_intersect(\n peaks,\n blacklist_path,\n log=self.log,\n bedtools_path=bedtools_path\n )\n peaks = blacklisted_peaks\n \n def write(self, prefix, *extensions):\n \"\"\"Write MACS2 output to disk\n \n Parameters\n ----------\n prefix\n prefix for output files\n *extensions\n the extensions of the MACS2 output files to write\n \"\"\"\n\n for ext in (extensions if extensions else self.output_extensions):\n with open('{}_{}'.format(prefix, ext), 'wb') as f:\n f.write(getattr(self, ext.replace('.', '_')))\n self.cleanup_prefix = prefix\n\n def generate_bed(self):\n self.peaks_bed = '\\n'.join(\n '\\t'.join(line.split()[:3])\n for line in self.peaks_narrowPeak.decode().splitlines() + ['']\n ).encode()\n self.output_extensions.append('peaks.bed')\n\n def clean_up(self, path):\n if (os.path.isfile(path) if path else False):\n os.remove(path)\n\n\n\n\n# Exceptions ===================================================================\n\nclass Error(Exception):\n \"\"\"Base class for other exceptions\"\"\"\n\n pass\n\n\nclass BadInputError(Error):\n \"\"\"Bad input error\"\"\"\n\n pass\n\n\nclass MissingMACS2Error(Error):\n \"\"\"Missing MACS2 error\"\"\"\n\n pass\n\n\nclass MissingBEDToolsError(Error):\n \"\"\"Missing bedtools error\"\"\"\n\n pass\n\n\n\n\n# Functions ====================================================================\n\ndef parse_input(input_file):\n \"\"\"Check that an input is str or byte\n \n Parameters\n ----------\n input_file\n the input to check\n \n Returns\n -------\n bytes\n the input file as a bytes object\n \"\"\"\n \n if isinstance(input_file, bytes):\n bytes_obj = input_file\n elif isinstance(input_file, str):\n with open(input_file, 'rb') as f:\n bytes_obj = f.read()\n else:\n raise BadInputError('Input must be either str or bytes')\n return bytes_obj\n\n\ndef bedtools_intersect(\n peaks: bytes,\n blacklist_path: str = HG38_BLACKLIST_PATH,\n log=None,\n bedtools_path: str = BEDTOOLS_PATH\n):\n \"\"\"Apply `bedtools intersect` to a file\n\n Parameters\n ----------\n peaks : bytes\n BED file containing peaks\n blacklist_path : str\n Path to ENCODE blacklist file\n log\n log file\n bedtools_path : str\n Path to bedtools executable\n\n Returns\n -------\n bytes\n BED file with blacklisted peaks removed\n \"\"\"\n \n if not bedtools_path:\n raise MissingBEDToolsError(\n '''bedtools was not found! Please provide the `bedtools_path`\n parameter to bedtools_intersect(), or set the `BEDTOOLS_PATH`\n environment variable, or make sure `bedtools` is installed and\n can be found via the `PATH` environment variable.\n '''\n )\n\n with subprocess.Popen(\n (\n bedtools_path, 'intersect',\n '-a', 'stdin',\n '-b', blacklist_path,\n '-v'\n ),\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=log\n ) as bedtools_intersect:\n return bedtools_intersect.communicate(input=peaks)[0]\n","sub_path":"chipseqpeaks/chip_seq_peaks.py","file_name":"chip_seq_peaks.py","file_ext":"py","file_size_in_byte":12804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"488248064","text":"from django.db import models\nfrom django.utils import timezone\nfrom csengő.hal import csengohw_be, csengohw_ki\nfrom time import sleep\nfrom django.conf import settings\nimport datetime\n\nHOSSZU_DURATION = 3\nROVID_DURATION = 1.5\nBURST_DURATION = 0.5\n\n\nclass Pattern(models.Model):\n\tclass Meta:\n\t\tverbose_name=\"Minta\"\n\t\tverbose_name_plural=\"Minták\"\n\tid = models.CharField(default=\"Új minta\", max_length=128, primary_key=True, verbose_name=\"Azonosító\")\n\tpattern = models.CharField(max_length=128, verbose_name=\"Minta\")\n\tdef play(self):\n\t\tszunet = False\t\t\n\t\tfor c in self.pattern:\n\t\t\tif c is 'h':\n\t\t\t\tif szunet:\n\t\t\t\t\tsleep(HOSSZU_DURATION)\n\t\t\t\t\tszunet = False\n\t\t\t\telse:\n\t\t\t\t\tcsengohw_be()\n\t\t\t\t\tsleep(HOSSZU_DURATION)\n\t\t\t\t\tcsengohw_ki()\n\t\t\telif c is 'r':\n\t\t\t\tif szunet:\n\t\t\t\t\tsleep(ROVID_DURATION)\n\t\t\t\t\tszunet = False\n\t\t\t\telse:\n\t\t\t\t\tcsengohw_be()\n\t\t\t\t\tsleep(ROVID_DURATION)\n\t\t\t\t\tcsengohw_ki()\n\t\t\telif c is 'b':\n\t\t\t\tif szunet:\n\t\t\t\t\tsleep(BURST_DURATION)\n\t\t\t\t\tszunet = False\n\t\t\telif c is 's':\n\t\t\t\tszunet = True\n\tdef __str__(self):\n\t\treturn self.id + \" (\" + self.pattern + \")\"\n\nclass Alarm(models.Model):\n\tclass Meta:\n\t\tverbose_name=\"Időpont\"\n\t\tverbose_name_plural=\"Időpontok\"\n\t\tordering = [\"date\"]\n\tid = models.CharField(default=\"Új időpont\", max_length=128, primary_key=True, verbose_name=\"Azonosító\")\n\tpattern = models.ForeignKey(\"Pattern\", verbose_name=\"Csengetési minta\")\n\tdate = models.TimeField(verbose_name=\"Időpont\")\n\tdef trigger(self):\n\t\tself.pattern.play()\n\tdef __str__(self):\n\t\treturn self.id + \" (\" + str(self.date) + \", \" + str(self.pattern) + \")\"\n\nclass Timetable(models.Model):\n\tclass Meta:\n\t\tverbose_name=\"Órarend\"\n\t\tverbose_name_plural=\"Órarendek\"\n\tid = models.CharField(default=\"Új órarend\", max_length=128, primary_key=True, verbose_name=\"Azonosító\")\n\talarms = models.ManyToManyField(\"Alarm\", verbose_name=\"Időpontok\", blank=True)\n\tactive = models.BooleanField(default=False, verbose_name=\"Aktív?\", editable=False)\n\tdefault = models.BooleanField(default=False, verbose_name=\"Alapértelmezett?\", editable=False)\n\ttemp = models.BooleanField(default=False, editable=False)\n\tdef __str__(self):\n\t\treturn self.id\n\tdef save(self, *args, **kwargs):\n\t\tif self.active:\n\t\t\ttry:\n\t\t\t\ttemp = Timetable.objects.filter(active=True)\n\t\t\t\tif len(temp) == 0:\n\t\t\t\t\tself.active = True\n\t\t\t\telse:\n\t\t\t\t\tfor t in temp:\n\t\t\t\t\t\tif self != t:\n\t\t\t\t\t\t\tt.active = False\n\t\t\t\t\t\t\tt.save()\n\t\t\texcept Timetable.DoesNotExist:\n\t\t\t\tpass\n\t\tif self.default:\n\t\t\ttry:\n\t\t\t\ttemp = Timetable.objects.filter(default=True)\n\t\t\t\tif len(temp) == 0:\n\t\t\t\t\tself.default = True\n\t\t\t\telse:\n\t\t\t\t\tfor t in temp:\n\t\t\t\t\t\tif self != t:\n\t\t\t\t\t\t\tt.default = False\n\t\t\t\t\t\t\tt.save()\n\t\t\texcept Timetable.DoesNotExist:\n\t\t\t\tpass\n\t\tsuper(Timetable, self).save(*args, **kwargs)\n\t\n\tdef set_active(self, save=True):\n\t\tself.active = True\n\t\tif save:\n\t\t\tself.save()\n\n\tdef empty(name=\"(nincs)\"):\n\t\tt = Timetable()\n\t\tt.id = name\n\t\tt.temp = True\n\t\treturn t\n\nclass CalendarEntry(models.Model):\n\tclass Meta:\n\t\tverbose_name=\"Naptár bejegyzés\"\n\t\tverbose_name_plural=\"Naptár bejegyzések\"\n\tid = models.DateField(primary_key=True, verbose_name=\"Dátum\")\n\ttimetable = models.ForeignKey(\"Timetable\", verbose_name=\"Órarend\")\n\tdef __str__(self):\n\t\treturn str(id)\n\n\tdef empty(date = datetime.date.today(), timetable = Timetable.empty()):\n\t\tc = CalendarEntry()\n\t\tc.id = date\n\t\tc.timetable = timetable\n\t\treturn c\n\n\tdef get_date_timetable(date):\n\t\tfor _break in Break.objects.all():\n\t\t\tif _break.start <= date <= _break.end:\n\t\t\t\treturn CalendarEntry.empty(date, Timetable.empty(\"(%s)\" % _break.id))\n\t\tentry = None\n\t\ttry:\n\t\t\tentry = CalendarEntry.objects.get(id = date)\n\t\texcept CalendarEntry.DoesNotExist:\n\t\t\tentry = CalendarEntry()\n\t\t\tentry.id = date\n\t\t\tif date.isoweekday() not in range(1, 6) and settings.HÉTVÉGE:\n\t\t\t\tentry.timetable = Timetable.empty(\"(hétvége)\")\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t\tentry.timetable = Timetable.objects.get(default = True)\n\t\t\t\texcept Timetable.DoesNotExist:\n\t\t\t\t\tentry.timetable = Timetable.empty()\n\t\treturn entry\n\nclass Break(models.Model):\n\tclass Meta:\n\t\tverbose_name=\"Tanítási szünet\"\n\t\tverbose_name_plural=\"Tanítási szünetek\"\n\tid = models.CharField(max_length=128, primary_key=True, verbose_name=\"Név\")\n\tstart = models.DateField(verbose_name=\"Kezdet\")\n\tend = models.DateField(verbose_name=\"Vége\")\n\tdef __str__(self):\n\t\treturn self.id","sub_path":"csengő_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"527830652","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf.urls import patterns, url\n\nurlpatterns= patterns('recrutase.autenticacao.views',\n url('^$', 'home', {'vTitulo': 'Início'}, name='home'), \n url('^entrar/$', 'login', {'vTitulo': 'Entrar'}, name='login'), \n url('^entrar/recuperar_senha/(?P[\\w.%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4})/$', 'recuperar_senha', name='recuperar_senha'), \n url('^sair/$', 'logout', {'vTitulo': 'Sair'}, name='logout'),\n url('^painel_de_controle/$', 'dashboard', {'vTitulo': 'Painel de Controle'}, name='dashboard'), \n url('^conclui_atividade/(?P\\d+)/$', 'conclui_atividade', {'vTitulo': 'Concluir Atividade'}, name='conclui_atividade'), \n url('^configuracao_usuario/$', 'configurar_usuario', {'vTitulo': 'Configuração de Usuário'}, name='configurar_usuario'),\n url('^adicionar_usuario/$', 'adicionar_usuario', {'vTitulo': 'Adicionar Colaborador'}, name='adicionar_usuario'),\n url('^adicionar_usuario/inativar/(?P\\d+)/$', 'inativar_usuario', {'vTitulo': 'Inativar Colaborador'}, name='inativar_usuario'),\n url('^adicionar_usuario/reativar/(?P\\d+)/$', 'reativar_usuario', {'vTitulo': 'Reativar Colaborador'}, name='reativar_usuario'),\n url('^ativar_usuario/(?P\\w{0,1000})/$', 'ativar_usuario', {'vTitulo': 'Ativar Usuário'}, name='ativar_usuario'),\n url('^nova_senha/(?P\\w{0,1000})/$', 'nova_senha', {'vTitulo': 'Nova Senha'}, name='nova_senha'),\n )","sub_path":"PyProject_Recrutase/recrutase/autenticacao/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"168925286","text":"import threading\nfrom datetime import datetime\n\nimport tensorflow as tf\nimport pandas as pd\nimport csv\nfrom tensorflow.keras.regularizers import l2\nimport os\n\n\nclass SingleFoldThread(threading.Thread):\n def __init__(self, train_set, val_set, test_set, activation_fun_layer_1, activation_fun_layer_2, neurons_layer_1,\n neurons_layer_2):\n threading.Thread.__init__(self)\n self.train = train_set\n self.valid = val_set\n self.test = test_set\n self.activation_fun_layer_1 = activation_fun_layer_1\n self.activation_fun_layer_2 = activation_fun_layer_2\n self.neurons_layer_1 = neurons_layer_1\n self.neurons_layer_2 = neurons_layer_2\n self.val_loss = None\n self.test_loss = None\n\n def run(self):\n no_epochs = 500\n verbosity = 0\n\n model, opt = get_compiled_model(self.activation_fun_layer_1, self.neurons_layer_1,\n self.activation_fun_layer_2, self.neurons_layer_2)\n # Stop criterion, patience - number of worse loss\n callback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=20, min_delta=0.001)\n # Fit data to model\n history = model.fit(self.train,\n epochs=no_epochs, callbacks=[callback],\n verbose=verbosity, validation_data=self.valid)\n\n scores = model.evaluate(self.valid, verbose=0)\n test_scores = make_evaluation(model, self.test)\n\n self.val_loss = scores[0]\n self.test_loss = test_scores[0]\n\n def get_return(self):\n if self.is_alive():\n return 0, 0\n else:\n return self.val_loss, self.test_loss\n\n\ndef training_with_test(training_set: str, test_set: str, activation_fun_name_layer_1, no_neurons_in_layer_1,\n activation_fun_name_layer_2, no_neurons_in_layer_2):\n print('************************************************************************')\n print(\"Training starts for:\")\n print(\"training set:\" + training_set + \" test set:\" + test_set)\n print(f'Layers name: {activation_fun_name_layer_1}, layers no {no_neurons_in_layer_1} | '\n f'Layers name: {activation_fun_name_layer_2}, layers no {no_neurons_in_layer_2}')\n print(\"Time:\", datetime.now().strftime(\"%H:%M:%S\"))\n\n no_batch_size = 500\n\n x_train, x_val, y_train, y_val = read_training_dataset(training_set)\n test_dataset = read_test_dataset(test_set)\n\n # preparation of training set\n input_train = tf.data.Dataset.from_tensor_slices(\n (x_train.values.reshape([len(x_train), 2]), y_train.values))\n train_dataset = input_train.shuffle(len(y_train.values)).batch(no_batch_size)\n\n input_val = tf.data.Dataset.from_tensor_slices(\n (x_val.values.reshape([len(x_val), 2]), y_val.values))\n val_dataset = input_val.shuffle(len(y_val.values)).batch(no_batch_size)\n\n thread = SingleFoldThread(train_set=train_dataset, val_set=val_dataset, test_set=test_dataset,\n activation_fun_layer_1=activation_fun_name_layer_1,\n activation_fun_layer_2=activation_fun_name_layer_2,\n neurons_layer_1=no_neurons_in_layer_1, neurons_layer_2=no_neurons_in_layer_2,\n )\n thread.start()\n thread.join()\n single_val_loss, single_test_loss = thread.get_return()\n\n print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')\n print(\"Training ends for:\")\n print(\"training set:\" + training_set + \" test set:\" + test_set)\n print(f'Layers name: {activation_fun_name_layer_1}, layers no {no_neurons_in_layer_1} | '\n f'Layers name: {activation_fun_name_layer_2}, layers no {no_neurons_in_layer_2}')\n print(\"validation accuracy:\" + str(single_val_loss) + \"test accuracy:\" + str(single_test_loss))\n print(\"Time:\", datetime.now().strftime(\"%H:%M:%S\"))\n\n return single_val_loss, single_test_loss\n\n\ndef get_compiled_model(activation_fun_names_layer_1, no_neurons_in_layer_1, activation_fun_names_layer_2,\n no_neurons_in_layer_2):\n if no_neurons_in_layer_2 == 0:\n model = tf.keras.Sequential([\n tf.keras.layers.Dense(no_neurons_in_layer_1, activation=activation_fun_names_layer_1,\n kernel_regularizer=l2(1e-5), kernel_initializer=tf.keras.initializers.ones),\n tf.keras.layers.Dense(1)\n ])\n else:\n model = tf.keras.Sequential([\n tf.keras.layers.Dense(no_neurons_in_layer_1, activation=activation_fun_names_layer_1,\n kernel_regularizer=l2(1e-5), kernel_initializer=tf.keras.initializers.ones),\n tf.keras.layers.Dense(no_neurons_in_layer_2, activation=activation_fun_names_layer_2,\n kernel_regularizer=l2(1e-5), kernel_initializer=tf.keras.initializers.ones),\n tf.keras.layers.Dense(1)\n ])\n\n opt = tf.keras.optimizers.Adam(learning_rate=0.001)\n model.compile(optimizer=opt,\n loss=['MeanSquaredError'],\n metrics=['MeanSquaredError'])\n # print(f'Layers name: {activation_fun_names_layer_1}, layers no {no_neurons_in_layer_1}')\n # print(f'Layers name: {activation_fun_names_layer_2}, layers no {no_neurons_in_layer_2}')\n\n return model, opt\n\n\ndef write_to_csv(file_name, val_loss, no_of_layers):\n if no_of_layers == 1:\n path_no_layer = \"one/\"\n else:\n path_no_layer = \"two/\"\n\n if not os.path.exists(\"test/\"):\n os.makedirs(\"test/\")\n\n if not os.path.exists(\"test/\" + path_no_layer):\n os.makedirs(\"test/\" + path_no_layer)\n\n with open(\"test/\" + path_no_layer + file_name + \".csv\", 'a', newline='',\n encoding='utf-8') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerows(val_loss)\n\n\ndef read_training_dataset(training_dataset):\n val_dataset_numb = 20000\n dataset = pd.read_csv(training_dataset, names=[\"x1\", \"x2\", \"y\"])\n y_dataset = dataset.pop(\"y\")\n x_train, x_val = dataset[:-val_dataset_numb], dataset[-val_dataset_numb:]\n y_train, y_val = y_dataset[:-val_dataset_numb], y_dataset[-val_dataset_numb:]\n return x_train, x_val, y_train, y_val\n\n\ndef read_test_dataset(test_dataset):\n dataset = pd.read_csv(test_dataset, names=[\"x1\", \"x2\", \"y\"])\n return dataset\n\n\ndef make_evaluation(model, test_set):\n y_test_set = test_set.pop(\"y\")\n\n loss_test = model.evaluate(\n x=test_set, y=y_test_set, batch_size=None, verbose=0, sample_weight=None, steps=None,\n callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False,\n return_dict=False\n )\n\n print(f'Loss for test dataset: {loss_test}')\n\n return loss_test\n\n\ndef test_everything(test_set):\n params = [\n (\"sigmoid\", \"sigmoid\", 65, 0),\n (\"tanh\", \"tanh\", 45, 0),\n (\"elu\", \"elu\", 140, 0),\n (\"swish\", \"swish\", 80, 0),\n (\"sigmoid\", \"sigmoid\", 45, 18),\n (\"tanh\", \"tanh\", 50, 9),\n (\"elu\", \"elu\", 12, 7),\n (\"swish\", \"swish\", 3, 25),\n ]\n\n train_sets = [\n (\"dataset/dataset_noise_100000_005.csv\", 0.005),\n (\"dataset/dataset_noise_100000_01.csv\", 0.1),\n (\"dataset/dataset_noise_100000_1.csv\", 1),\n (\"dataset/dataset_noise_100000_5.csv\", 5),\n (\"dataset/dataset_noise_100000_10.csv\", 10),\n (\"dataset/dataset_noise_100000_20.csv\", 20),\n ]\n\n for activation_1, activation_2, neurons_1, neurons_2 in params:\n best_ones = []\n if neurons_2 == 0:\n no_of_layers = 1\n else:\n no_of_layers = 2\n for training_set, noise in train_sets:\n val_loss = []\n test_loss = []\n for x in range(5):\n single_val_loss, single_test_loss = training_with_test(\n training_set=training_set,\n test_set=test_set,\n activation_fun_name_layer_1=activation_1,\n no_neurons_in_layer_1=neurons_1,\n activation_fun_name_layer_2=activation_2,\n no_neurons_in_layer_2=neurons_2\n )\n val_loss.append(single_val_loss)\n test_loss.append(single_test_loss)\n\n minimal_val_loss_idx = val_loss.index(min(test_loss))\n val_loss_of_best = val_loss[minimal_val_loss_idx]\n test_loss_of_best = test_loss[minimal_val_loss_idx]\n best_ones.append((noise, test_loss_of_best, val_loss_of_best))\n\n print('------------------------------------------------------------------------')\n print(\"Best result for:\")\n print(\"training set:\" + training_set + \" test set:\" + test_set)\n print(f'Layers name: {activation_1}, layers no {neurons_1} | '\n f'Layers name: {activation_2}, layers no {neurons_2}')\n print(\"validation accuracy:\" + str(val_loss_of_best))\n print(\"test accuracy:\" + str(test_loss_of_best))\n\n file_name = str(no_of_layers) + \"_\" + \\\n activation_1 + \"_\" + str(neurons_1) + \"_\" + \\\n activation_2 + \"_\" + str(neurons_2) + \"_noise_\" + \\\n str(noise)\n write_to_csv(file_name, zip(val_loss, test_loss), no_of_layers)\n file_name_for_best = str(no_of_layers) + \"_\" + \\\n activation_1 + \"_\" + str(neurons_1) + \"_\" + \\\n activation_2 + \"_\" + str(neurons_2) + \"_best\"\n write_to_csv(file_name_for_best, best_ones, no_of_layers)\n\n\nif __name__ == '__main__':\n # turn off CUDA support\n import os\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n\n dataset_without_noise = \"dataset/dataset_100000.csv\"\n test_everything(test_set=dataset_without_noise)\n","sub_path":"neuron_network_final_testing.py","file_name":"neuron_network_final_testing.py","file_ext":"py","file_size_in_byte":9847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"420009445","text":"class Enemy:\n\tdef __init__ (self,x,y,size,v):\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.size = size\n\t\tself.v = v\n\t\tself.destroyed=False\n\n\tdef step(self):\n\t\tself.x = self.x\n\t\tself.y = self.y + self.v","sub_path":"enemy.py","file_name":"enemy.py","file_ext":"py","file_size_in_byte":189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"518270872","text":"math={'john':55.0,'tam':66.0}\nfor values in math.values():\n print(values)\n\n\n# dict ={'god':55,'bobby':88}\n# print(dict)\n# doc ={'lion':98,'king':89}\n# dict.update(doc)\n# print(dict)\n\n#add two dictionary\n# dict ={'god':55,'bobby':88}\n# doc ={'lion':98,'king':89}\n# d={}\n# for d in (dict, doc):\n# d.update(dict)\n# print(d)\n# #chek weather key is present or not.\n# if 'lion' in dict:\n# print('Key is present in the dictionary')\n# else:\n# print('key is not present in the dictionary')","sub_path":"values.py","file_name":"values.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"616469099","text":"#!/usr/local/bin/python3\nimport re\nimport os\nimport sys\nimport shutil\nimport rosalind\n\n\ndef main():\n args=sys.argv\n filename=rosalind.find_file(args)\n with open(filename,'r') as file:\n data=file.read().split()\n d={}\n for read in data:\n if read in d:\n d[read]+=1\n d[rosalind.dna_reverse_complement(read)]+=1\n else:\n d[read]=1\n d[rosalind.dna_reverse_complement(read)]=1\n for read in data:\n if d[read]==1:\n for corr in d.keys():\n if d[corr]>1 and rosalind.hamming(read, corr)==1:\n print(read+'->'+corr)\n\nif __name__ == '__main__':\n main()\n","sub_path":"Rosalind/AC/CORR.py","file_name":"CORR.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"266272689","text":"from locust import HttpLocust, TaskSet, task\nimport numpy as np\nimport base64\nimport json\n\n\nclass WebsiteTasks(TaskSet):\n\n def on_start(self):\n feature = np.random.normal(0.0, 0.1, 200).astype(np.float32)\n feature = feature / np.linalg.norm(feature, ord=2, axis=0)\n feature = base64.b64encode(feature.tobytes())\n feature = feature.decode(\"utf-8\", \"ignore\")\n request_data = {\n \"db_name\": \"random.test\",\n \"b64_feature\": feature,\n \"topk\": 10,\n }\n self.request_data = json.dumps(request_data)\n\n @task\n def search(self):\n response = self.client.post(\"search\", data=self.request_data)\n result = json.loads(response.text)\n\n\nclass WebsiteUser(HttpLocust):\n task_set = WebsiteTasks # 指向TasSet类,定义测试行为\n min_wait = 0\n max_wait = 0\n","sub_path":"python/test_concurrent/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"35553115","text":"'''\nCreated on May 28, 2013\n\n@author: david_g_wild\n'''\n\nfrom __future__ import division\nimport math\nimport datetime\n\nimport Expression\n\n\nclass RandomRange:\n def __init__(self, aStart, aEnd, aStep=1):\n self.RangeStart = aStart\n self.RangeEnd = aEnd\n self.RangeStep = aStep\n print('Start, End, Step = ' + str(aStart) + ',' + str(aEnd) + ',' + str(aStep) )\n\n self.NumOutcomes = int(round(abs((aEnd - aStart) / aStep)) + 1)\n\n\nclass RandomString:\n def __init__(self, aValue):\n self.value = aValue\n\n\nclass RandomVariable:\n def __init__(self, aName, aExpression, aRandomGenerator, aIsSystem=0, aValue = None):\n self.name = aName\n self.evaluated = aValue != None\n self.IsSystem = aIsSystem\n self.ExpressionStr = ''\n self.value = aValue # makes no sense when evaluated is False\n self.EvalExpr = Expression.EvalExpression(aExpression, False, aRandomGenerator)\n self.EvalExpr.UpdateVariables()\n self.ExpressionStr = aExpression\n self.DependentRandomList = []\n\n def Evaluate(self, originalfocus, focus, aRandomGenerator, depth):\n if (focus.name == originalfocus.name) and (depth > 0):\n raise Exception(originalfocus.name + ' is dependent on itself in expression ' + focus.ExpressionStr)\n if not focus.evaluated:\n if len(focus.DependentRandomList) == 0:\n # there are no dependencies so the value can be gotten from its own expression\n focus.value = focus.EvalExpr.Evaluate()\n focus.evaluated = True\n else:\n # for each random in the dependent list, call evaluate for it recursively\n for i in range(0, len(focus.DependentRandomList)):\n variable = aRandomGenerator.GetVariableByName(focus.DependentRandomList[i])\n if variable == None:\n raise Exception('Error while trying to evaluate variable ' + focus.name + '. It depends on ' + str(focus.DependentRandomList[i]) + ' which has not been defined yet.')\n\n focus.Evaluate(originalfocus, variable,\n aRandomGenerator, depth + 1)\n focus.value = focus.EvalExpr.Evaluate()\n focus.evaluated = True\n\n\n def AddDependentRandom(self, aRandomVariable):\n try:\n self.DependentRandomList.index(aRandomVariable)\n except: #it isn't already a dependent random\n self.DependentRandomList.append(aRandomVariable)\n\n def GetDependentRandoms(self):\n '''returns a list of dependent randoms in the form\n x -> y (if x is dependent on y)\n y -> z, a (if y is dependent on z and a)'''\n result = self.name\n for i in range(0, len(self.DependentRandomList)):\n result = result + '-> ' + self.DependentRandomList[i] + ','\n return result\n\n\nclass RandomGenerator:\n def __init__(self):\n self.RandomsList = []\n self.EvaluatedAll = False #Can only become True after a call to EvaluateAll\n #self.AddVariableFromExpressionString('FUDGE', '0', True) # used for evaluating unary minuses -1 -> fudge-1 = 0-1 = -1\n #self.EvaluateAll()\n # add the system variables\n self.RandomsList.append(RandomVariable('pi',str(math.pi),self,True,math.pi))\n self.RandomsList.append(RandomVariable('currentyear',str(datetime.datetime.now().year),self,True,datetime.datetime.now().year))\n self.RandomsList.append(RandomVariable('currentmonth',str(datetime.datetime.now().month),self,True,datetime.datetime.now().month))\n self.RandomsList.append(RandomVariable('currentday',str(datetime.datetime.now().day),self,True,datetime.datetime.now().day))\n self.RandomsList.append(RandomVariable('vat',str(20),self,True,20))\n\n\n\n\n def RemoveVariableByName(self, aName, ChangeEvaluatedState=True):\n VariableIdx = self.GetVariableIdxByName(aName)\n if VariableIdx >= 0:\n # variable already exists\n self.RandomsList.pop(VariableIdx)\n return VariableIdx\n if ChangeEvaluatedState:\n self.EvaluatedAll = False\n\n def AddVariableFromExpressionString(self, aName, aExpression, aIsSystem=0, ChangeEvaluatedState=True):\n \"\"\"\n\n :param aName:\n :param aExpression:\n :param aIsSystem:\n \"\"\"\n if ChangeEvaluatedState:\n self.EvaluatedAll = False\n # if the variable already exists then amend the details, else add a new one\n RemoveIdx = self.RemoveVariableByName(aName, ChangeEvaluatedState)\n if RemoveIdx >= 0:\n self.RandomsList.insert(RemoveIdx, RandomVariable(aName, aExpression, self, aIsSystem))\n else:\n self.RandomsList.append(RandomVariable(aName, aExpression, self, aIsSystem))\n\n\n def InsertVariableFromExpression(self, aIndex, aName, aExpression, aIsSystem=0):\n \"\"\"\n\n :param aIndex:\n :param aName:\n :param aExpression:\n :param aIsSystem:\n \"\"\"\n self.RandomsList.insert(aIndex, RandomVariable(aName, aExpression, self, aIsSystem))\n self.EvaluatedAll = False\n\n def GetVariableByName(self, aName):\n Result = self.GetVariableIdxByName(aName)\n if Result < 0:\n return None\n else:\n return self.RandomsList[Result]\n\n\n def GetVariableIdxByName(self, aName):\n idx = 0\n Result = -1\n while idx < len(self.RandomsList):\n if self.RandomsList[idx].name == aName:\n Result = idx\n break\n idx = idx + 1\n return Result\n\n def PrintRandoms(self):\n Result = ''\n for i in range(0, len(self.RandomsList)):\n Result = Result + self.RandomsList[i].name + ' = ' + self.RandomsList[i].ExpressionStr + '\\n'\n return Result\n\n def PrintDependencies(self):\n for i in range(0, len(self.RandomsList)):\n print(self.RandomsList[i].GetDependentRandoms())\n\n def PrintValues(self):\n print ('Values of randoms in Generator:\\n')\n for i in range(0, len(self.RandomsList)):\n print( self.RandomsList[i].name + '=' + str(self.RandomsList[i].value) + '\\n')\n\n def AddDependencies(self):\n ''' For each variable, go through the expression and add the variables to the DependentRandomList'''\n for i in range(0, len(self.RandomsList)):\n\n self.RandomsList[i].EvalExpr.UpdateVariables()\n # Search for variables that appear in the EvalExpr and add them to the DependentRandomList of the variable\n for j in range(0, len(self.RandomsList[i].EvalExpr.variables)):\n self.RandomsList[i].AddDependentRandom(self.RandomsList[i].EvalExpr.variables[j])\n if self.RandomsList[i].EvalExpr.variables[j] == self.RandomsList[i].name:\n raise Exception(self.RandomsList[i].name +\n ' evaluation leads to indeterminate value. '\n 'Perhaps it is a self-referencing variable?')\n\n\n def HasCircularReference(self):\n # Look through all the variables and return true of there is a circular reference (meaning that a variable cannot be evaluate)\n # An example of a circular reference is if x = y + z; y = x (x depends on y and vice versa)\n if len(self.RandomsList) == 0:\n return False\n else:\n # go through all the randoms in the RandomsList and see if any child of the particular random has itself as a dependency\n for randomCounter in range(0, len(self.RandomsList)):\n ThisRandom = self.RandomsList[randomCounter]\n return ThisRandom.DependentRandomList.index(ThisRandom)\n\n def Reset(self):\n self.EvaluatedAll = False\n del self.RandomsList[:]\n\n def ResetValues(self, ResetOnlyList=[]):\n for i in range(0,len(self.RandomsList)):\n if len(ResetOnlyList) > 0:\n if self.RandomsList[i].name in ResetOnlyList:\n self.RandomsList[i].value = None\n else:\n self.RandomsList[i].value = None\n\n\n def EvaluateAll(self,EvaluateOnlyList=[]):\n '''Evaluates all of the variables in the RandomsList - returns True if successful, \n False otherwise e.g. if there is a circular reference or an EvalExpr is ill-formed.\n It works by creating a directed graph. Two nodes on the graph, n1 and n2, are related n1->n2 if the EvalExpr\n defining n1 contains n2. \n \n Example. Given a=b+c, b=d+1, c=4-pi, d=6 then we get the following relationships\n a->b, a->c, b->d\n \n Example. Given a=b+c, b=a+c then a<->b, a->c, b->c (this would result in a circular reference which means we can't evaluate)\n \n self.EvaluatedAll = True'''\n if self.EvaluatedAll and len(self.RandomsList) > 0:\n raise Exception('Call to EvaluateAll without reset')\n\n for i in range(0, len(self.RandomsList)):\n self.RandomsList[i].Evaluate(self.RandomsList[i], self.RandomsList[i], self, 0)\n self.EvaluatedAll = True\n\n def GetValueByIdx(self, aIdx):\n return self.RandomsList[aIdx].value\n\n def GetValueByName(self, aName):\n variable = self.GetVariableByName(aName)\n if variable == None:\n return None\n else:\n return variable.value\n\n def SetValueByName(self, aName, aValue):\n variable = self.GetVariableByName(aName)\n if variable == None:\n raise Exception('The variable ' + aName + ' does not exist to set its value')\n else:\n variable.value = aValue\n\n\nif __name__ == '__main__':\n aRandomGenerator = RandomGenerator()\n\n aRandomGenerator.AddVariableFromExpressionString('person','randomstr(\"David\",\"Scarlett\",\"Adam\",\"Sandra\")')\n aRandomGenerator.AddVariableFromExpressionString('She','match(person=\"David\",\"He\",person=\"Adam\",\"He\",\"She\")')\n\n\n # aRandomGenerator.AddVariableFromExpressionString('s2','s4^s3')\n # aRandomGenerator.AddVariableFromExpressionString('s3','random(range(-1,s4,2))')\n # aRandomGenerator.AddVariableFromExpressionString('s4','eval(s5+5)')\n # aRandomGenerator.AddVariableFromExpressionString('s1', 'randomstr(\"string1\",\"string2\",\"string3\",\"string4\",\"string5\")')\n # aRandomGenerator.AddVariableFromExpressionString('a1', 'random(range(2,a5,1))')\n # aRandomGenerator.AddVariableFromExpressionString('a2', 'a1+2')\n # aRandomGenerator.AddVariableFromExpressionString('a3', 'a2+a4')\n # aRandomGenerator.AddVariableFromExpressionString('a4', '4*a2')\n # aRandomGenerator.AddVariableFromExpressionString('a5', 'random(range(3,9,1))')\n # aRandomGenerator.AddVariableFromExpressionString('SandraAge', 'random(range(24,34,1))')\n # aRandomGenerator.AddVariableFromExpressionString('DavidAge', 'random(range(35,45,1))')\n # aRandomGenerator.AddVariableFromExpressionString('SumAges', 'SandraAge+DavidAge-SandraAge/DavidAge+DavidAge^4/(SandraAge+DavidAge)')\n\n\n aRandomGenerator.AddDependencies()\n aRandomGenerator.PrintDependencies()\n aRandomGenerator.EvaluateAll()\n aRandomGenerator.PrintValues()\n\n print('Random Generator\\n' + aRandomGenerator.PrintRandoms())\n\n# print myexpression.Evaluate(RandomGenerator()) \n ","sub_path":"ifp_django/Randoms.py","file_name":"Randoms.py","file_ext":"py","file_size_in_byte":11421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"222596932","text":"from re import MULTILINE\nimport kivy\nfrom kivy.app import App\nfrom kivy.uix.label import Label # Import the simbols and widgets\nimport os\n#os.environ[\"SDL_VIDEODRIVER\"] = \"x11\"\nfrom kivy.uix.gridlayout import GridLayout # Import GridLayout design\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.button import Button # import buttons\n\nclass MenuLayout(GridLayout):\n def __init__(self, **kwargs): # handle as many kwargs as come\n super(MenuLayout, self).__init__(**kwargs)\n self.cols = 1\n \n self.inside = GridLayout() # first layout\n self.inside.cols = 2\n\n #self.cols = 2\n self.inside.add_widget(Label(text = \"First Name: \"))\n self.firstName = TextInput(multiline = False)\n self.inside.add_widget(self.firstName)\n\n self.inside.add_widget(Label(text = \"Last Name: \"))\n self.lastName = TextInput(multiline = False)\n self.inside.add_widget(self.lastName)\n\n self.inside.add_widget(Label(text = \"Email: \"))\n self.email = TextInput(multiline = False)\n self.inside.add_widget(self.email)\n\n self.add_widget(self.inside)\n\n\n self.submit = Button(text = \"Submit:\", font_size = 40)\n self.submit.bind(on_press = self.pressed)\n self.add_widget(self.submit)\n\n def pressed(self, instance):\n name = self.firstName.text\n last = self.lastName.text\n email = self.email.text\n\n print(\"Name: \", name, \"LastName: \", last, \"Email: \", email)\n self.lastName.text = \"\"\n self.firstName.text = \"\"\n self.email.text = \"\"\n\nclass MyApp(App):\n def build(self): # Construir o UI\n return MenuLayout()\n\nif __name__ == \"__main__\":\n MyApp().run()","sub_path":"Training_and_similar/train1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"535889236","text":"from django.conf.urls import url\nfrom . import views\nfrom django.views.generic import TemplateView\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\napp_name = 'polls'\nurlpatterns = [\n\n url(r'^base/', views.base, name='base'),\n url(r'^search', views.search, name='search'),\n url(r'^list', views.list, name='list'),\n url(r'^home/', views.home, name = 'home'),\n url(r'^login/', views.login, name = 'login'),\n url(r'^post/', views.post_new, name='post_new'),\n url(r'^connection/',TemplateView.as_view(template_name = 'poll/login.html')),\n url(r'^js-settings/$',views.render_js,{\"template_name\":\"settings.js\"},name='js_settings'),\n\n url(r'^$', views.IndexView.as_view(), name='index'),\n url(r'^(?P[0-9]+)/$', views.DetailView.as_view(), name='detail'),\n url(r'^(?P[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),\n url(r'^(?P[0-9]+)/vote/$', views.vote, name='vote'),\n\n\n\n]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n #url(r'^$', views.index, name='index'),","sub_path":"books/polls/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"289043579","text":"import tensorflow as tf\nimport BasicConvLSTMCell as cl\n\nbatch_size = 1\n\ndef conv_layer(inputs, kernel_size, stride, num_features, is_training, idx, linear=False):\n with tf.variable_scope('{0}_conv'.format(idx)) as scope:\n weights = tf.get_variable('weights', [kernel_size, kernel_size, inputs.get_shape()[-1], num_features],\n initializer=tf.truncated_normal_initializer(stddev=0.1))\n biases = tf.get_variable('biases', [num_features], initializer=tf.constant_initializer(0.0))\n conv = tf.nn.conv2d(inputs, weights, strides=[1, stride, stride, 1], padding='SAME')\n conv = tf.nn.bias_add(conv, biases)\n bn = tf.contrib.layers.batch_norm(conv, is_training=is_training, scope='bn', decay=0.9,\n zero_debias_moving_mean=True, variables_collections=['bn_collections'])\n rn = tf.nn.relu(bn)\n if linear:\n return conv\n return rn\n\n\ndef transpose_conv_layer(inputs, kernel_size, stride, num_features, is_training, idx, linear=False):\n with tf.variable_scope('{0}_trans_conv'.format(idx)) as scope:\n weights = tf.get_variable('weights', [kernel_size, kernel_size, num_features, inputs.get_shape()[-1]],\n initializer=tf.truncated_normal_initializer(stddev=0.1))\n shape = inputs.get_shape().as_list()\n output_shape = [shape[0], shape[1] * stride, shape[2] * stride, num_features]\n deconv = tf.nn.conv2d_transpose(inputs, weights, output_shape, strides=[1, stride, stride, 1], padding='SAME')\n bn = tf.contrib.layers.batch_norm(deconv, is_training=is_training, scope='bn', decay=0.9,\n zero_debias_moving_mean=True, variables_collections=['bn_collections'])\n r = tf.nn.relu(bn)\n if linear:\n return deconv\n return r\n\n\ndef SpatialConnectionAwareNetwork(inputs, hidden, lstm=True):\n conv1 = conv_layer(inputs, 5, 1, 32, 1, 'encode_1')\n conv2 = conv_layer(conv1, 3, 2, 64, 1, 'encode_2')\n conv3 = conv_layer(conv2, 3, 1, 64, 1, 'encode_3')\n conv4 = conv_layer(conv3, 3, 2, 128, 1, 'encode_4')\n y_0 = conv4\n\n if lstm:\n # conv lstm cell\n with tf.variable_scope('conv_lstm', initializer=tf.random_uniform_initializer(-.01, 0.1)):\n cell = cl.BasicConvLSTMCell([90, 108], [3, 3], 128)\n if hidden is None:\n hidden = cell.zero_state(batch_size, tf.float32)\n y_1, hidden = cell(y_0, hidden)\n else:\n y_1 = conv_layer(y_0, 3, 1, 128, 1, 'encode_5')\n\n conv6 = conv_layer(y_1, 3, 1, 128, 1, 'decode_6')\n conv7 = transpose_conv_layer(conv6, 4, 2, 64, 1, 'decode_7') + conv3\n conv8 = conv_layer(conv7, 3, 1, 64, 1, 'decode_8')\n conv9 = transpose_conv_layer(conv8, 4, 2, 32, 1, 'decode_9') + conv1\n conv10 = conv_layer(conv9, 3, 1, 64, 1, 'decode_10')\n # x_1\n conv11 = conv_layer(conv10, 5, 1, 1, 1, 'decode_11', True) + inputs[:, :, :, 0:1] # set activation to linear\n\n x_1 = conv11\n\n return x_1, hidden","sub_path":"test/SpatialConnectionAwareNetwork_arch.py","file_name":"SpatialConnectionAwareNetwork_arch.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"244220653","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib\n\nfrom temperations import *\nfrom hearing import Pair\n\nharmonic_major_temperation = map(float, HARMONIC_INTERVALS)\nharmonic_temperation = map(float, CHROMATIC_TEMPERATION_BY_TONAL[DO])\n\nfig = plt.figure()\n\nax1 = fig.add_subplot(111)\n\n\n# Все интервалы тональных темпераций\nax1.eventplot(\n [CHROMATIC_INTERVALS],\n colors=[[.7, .7, .7]], lineoffsets=[6], linelengths=12\n)\n\n# Равномерно и гармонично-темперированные вертикльные линии\nax1.eventplot(\n [FLAT_TEMPERATION, harmonic_major_temperation],\n colors=[[.2, .5, 0], [.7, .1, .9]],\n lineoffsets=[6, 6],\n linelengths=12,\n linestyles=['-', '--'],\n linewidths=[1.5, 2]\n)\n\nfor j in MAJOR_GAMMA:\n ax1.axhline(j, color=[.3, .3, .3], linestyle=':')\n\n\n# Интервалы пифагорейской темперации\nax1.vlines(PYTHAGOR_TEMPERATION, 6.3, 7.7, colors=[0, .4, 1])\nax1.vlines(PYTHAGOR_INTERVALS53, 6.8, 7.2, colors=[0, .4, 1])\n\n\nax1.eventplot(\n [\n temperation\n for tonal, temperation in enumerate(CHROMATIC_TEMPERATION_BY_TONAL)\n ],\n colors=[[.7, .7, .7]],\n lineoffsets=NOTES13,\n linelengths=.4,\n linewidths=3\n)\n\nax1.eventplot(\n [\n [\n interval for nota, interval in enumerate(temperation)\n if nota in MAJOR_GAMMA\n ]\n for temperation in CHROMATIC_TEMPERATION_BY_TONAL\n ],\n colors=[\n [.99, .3, 0] if nota in MAJOR_GAMMA else [.7, .7, .7]\n for nota in NOTES13\n ],\n lineoffsets=NOTES13,\n linelengths=.4,\n linewidths=3\n)\n\n\nax1.set_xbound(.98, 2.02)\nax1.set_xticks(harmonic_major_temperation)\nax1.set_xticklabels([INTERVALS[nota] for nota in MAJOR_GAMMA])\n\nax1.set_ybound(-.3, 12.3)\nax1.set_yticks(range(13))\nax1.set_yticklabels([\n name if nota in MAJOR_GAMMA else ''\n for nota, name in enumerate(NOTES_NAMES)\n])\n\n\nmatplotlib.rcParams['font.size'] = 8.0\nfig.set_tight_layout(True)\n\nplt.show()\n","sub_path":"plot_temperations.py","file_name":"plot_temperations.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"74625902","text":"import torchvision\nimport torchvision.models as models\nimport torch\nimport torchvision.transforms as transforms\nfrom label import classes\nimport torch.onnx\n\nimport mobilenetv3\nimport mobilenetv3_to_onnx\n\n#ImageNet dataset path\n# DATAPATH = \"/home/jieliu/workspace/vela_model/MobileNetV3/dataset/ILSVRC-2012\"\nDATAPATH = \"/home/jieliu/workspace/vela_model/dataset/ILSVRC-2012\"\n\n# /software/topsinference_qa/models/topsinference_test_mobilenet_v3_large_fp32.onnx\nmobilenet_v3_large = mobilenetv3.mobilenet_v3_large(pretrained=True)\n# mobilenet_v3_large.half()\nmobilenet_v3_large.eval()\n\ndef pytorch_to_onnx(model, input_shape, model_name):\n\n # Input to the model\n x = torch.randn(input_shape, requires_grad=True)\n torch_out = mobilenet_v3_large(x)\n\n # Export the model\n torch.onnx.export( model, # model being run\n x, # model input (or a tuple for multiple inputs)\n model_name, # where to save the model (can be a file or file-like object)\n export_params=True, # store the trained parameter weights inside the model file\n opset_version=9, # the ONNX version to export the model to\n do_constant_folding=True, # whether to execute constant folding for optimization\n input_names = ['input'], # the model's input names\n output_names = ['output'], # the model's output names\n dynamic_axes={'input' : {0 : '-1'}, # variable lenght axes\n 'output' : {0 : '-1'}})\n\ndef predict(model, datapath, us_fp16=False):\n transform = transforms.Compose(\n [transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])\n\n testset = torchvision.datasets.ImageNet(\n datapath, \"val\", download = False, transform=transform)\n testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=2)\n\n dataiter = iter(testloader)\n images, labels = dataiter.next()\n\n correct = 0\n total = 0\n\n with torch.no_grad():\n i = 0\n for data in testloader:\n images, labels = data\n\n if us_fp16:\n images = images.half()\n\n outputs = model(images)\n _, predicted=torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n print('Accuracy of the network on the epoch: %d test images: %d %%' % (i,\n 100 * correct / total))\n\n i += 1\n print('Accuracy of the network on the 50000 test images: %d %%' % (\n 100 * correct / total))\n\nif __name__ == '__main__':\n\n # ImageNet dataset path\n # DATAPATH = \"/home/jieliu/workspace/vela_model/MobileNetV3/dataset/ILSVRC-2012\"\n DATAPATH = \"/home/jieliu/workspace/vela_model/dataset/ILSVRC-2012\"\n\n # The official implementation of Pytorch for the mobilenet_v3_large (torchvision >= 0.9.0)\n # mobilenet_v3_large = models.mobilenet_v3_large(pretrained=True)\n\n # The official implementation of Pytorch for the mobilenet_v3_large (torchvision < 0.9.0)\n # mobilenet_v3_large = mobilenetv3.mobilenet_v3_large(pretrained=True)\n\n mobilenet_v3_large = mobilenetv3_to_onnx.mobilenet_v3_large(\n pretrained=True)\n # mobilenet_v3_large.half()\n mobilenet_v3_large.eval()\n # pytorch_to_onnx(mobilenet_v3_large, [1, 3, 224, 224], \"mobilenet_v3_large_fp32.onnx\")\n predict(mobilenet_v3_large, DATAPATH, False)\n","sub_path":"classification/mobilenet/MobileNetV3/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":3803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"567792433","text":"import torch\nfrom torch import nn\nfrom torch.utils import data\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\ntorch.backends.cudnn.benchmark = True\n\nimport pydensecrf.densecrf as dcrf\n\nimport os\nimport yaml\nimport time\nimport tqdm\n\nimport numpy as np\nnp.seterr(divide='ignore', invalid='ignore')\n\nfrom models.gcn import GCN\nfrom models.unet import UNet\n\nfrom loaders.visda import VisDaDataset\nfrom loaders.cityscapes import CityscapesDataset\nfrom loaders.eval_dataloader import EvalDataloader\n\nimport util.cityscapes_helper as cityscapes\nfrom util.metrics import miou, class_iou, confusion_matrix\nfrom util.util import *\n\nargs = Namespace(**yaml.load(open(os.path.join(os.getcwd(), \"config.yaml\"), 'r')))\nargs.img_size = (int(args.scale_factor*args.default_img_size[0]), int(args.scale_factor * args.default_img_size[1]))\n\npaths = yaml.load(open(os.path.join(os.getcwd(), \"paths.yaml\"), 'r'))\n\n\nclass Evaluator:\n\n\tdef __init__(self, mode=\"val\", samples=30, metrics=[\"miou\", \"cls_iou\"], crf=True, standalone=False, save_pred=False):\n\t\tself.n_samples = samples\n\t\tself.metrics = metrics\n\t\tself.use_crf = crf\n\t\tself.standalone = standalone\n\t\tself.save_pred = save_pred\n\n\t\tif mode == \"val\":\n\t\t\tself.dataset = VisDaDataset(im_size=args.img_size)\n\t\telif mode == \"cityscapes\":\n\t\t\tself.dataset = CityscapesDataset(im_size=args.img_size)\n\t\telse:\n\t\t\traise ValueError(\"Invalid mode.\")\n\n\t\tself.dataloader = data.DataLoader(EvalDataloader(self.dataset, self.n_samples), batch_size=1, shuffle=True, num_workers=6)\n\n\tdef eval(self, model):\n\t\tmodel.eval()\n\n\t\tif \"miou\" in self.metrics:\n\t\t\tiou = []\n\t\tif \"cls_iou\" in self.metrics:\n\t\t\tcls_iou = np.zeros(self.dataset.num_classes)\n\t\tif \"cfm\" in self.metrics:\n\t\t\tcfm = np.zeros((self.dataset.num_classes, self.dataset.num_classes))\n\n\t\tloader = self.dataloader\n\t\tif self.standalone: loader = tqdm.tqdm(loader, total=self.n_samples)\n\n\t\tfor i, ((image, _), (image_full, gt)) in enumerate(loader):\n\n\t\t\timage_full = np.squeeze(image_full.cpu().numpy())\n\t\t\tgt = np.squeeze(gt.cpu().numpy())\n\n\t\t\tpred = self.predict(model, image)\n\t\t\tpred = self.upsample(pred)\n\n\t\t\tif self.use_crf:\n\t\t\t\tpred_alt = np.argmax(pred.copy(), axis=0)\n\t\t\t\tpred = self.refine(pred, image_full)\n\t\t\tpred = np.argmax(pred, axis=0)\n\n\t\t\tif self.save_pred:\n\t\t\t\tpath = os.path.join(paths[\"project_path\"], \"pred\")\n\t\t\t\tif self.use_crf:\n\t\t\t\t\tsave_set(image_full, gt, pred_alt, pred, i+1, path)\n\t\t\t\telse:\n\t\t\t\t\tsave_set(image_full, gt, pred, None, i+1, path)\n\n\t\t\tif \"miou\" in self.metrics:\n\t\t\t\tiou.append(miou(gt, pred, self.dataset.num_classes, ignore_zero=False))\n\t\t\tif \"cls_iou\" in self.metrics:\n\t\t\t\tcls_iou = cls_iou + class_iou(gt, pred, self.dataset.num_classes)\n\t\t\tif \"cfm\" in self.metrics:\n\t\t\t\tcfm = cfm + confusion_matrix(gt.flatten(), pred.flatten(), self.dataset.num_classes, normalize=False)\n\n\t\t\n\t\tres = []\n\t\tif \"miou\" in self.metrics:\n\t\t\tmeaniou = np.asarray(iou).mean()\n\t\t\tstdeviou = np.asarray(iou).std()\n\t\t\tres.append((meaniou, stdeviou))\n\t\tif \"cls_iou\" in self.metrics:\n\t\t\tcls_iou /= self.n_samples\n\t\t\tres.append(cls_iou)\n\t\tif \"cfm\" in self.metrics:\n\t\t\tcfm = cfm.astype('float') / cfm.sum(axis=1)[:, np.newaxis]\n\t\t\tres.append(cfm)\n\n\t\tmodel.train()\n\t\treturn tuple(res)\n\n\tdef predict(self, model, img):\n\t\timg = Variable(img.cuda())\n\t\toutput = model(img)\n\t\tpred = F.softmax(output, dim=1).cpu()\n\t\treturn pred\n\n\tdef upsample(self, img):\n\t\tsize = self.dataset.default_size\n\t\tupsampler = nn.Upsample(size=size, mode='bilinear')\n\t\tout = upsampler(img)\n\t\tout = np.squeeze(out.data.cpu().numpy())\n\t\treturn out\n\n\tdef refine(self, pred, img):\n\n\t\t# init vars\n\t\tnum_cls = pred.shape[0]\n\t\tscale = 0.97\n\t\tclip = 1e-8\n\n\t\t# init crf\n\t\td = dcrf.DenseCRF2D(img.shape[1], img.shape[0], num_cls)\n\n\t\t# create unary\n\t\tuniform = np.ones(pred.shape) / num_cls\n\t\tU = (scale * pred) + ((1 - scale) * uniform)\n\t\tU = np.clip(U, clip, 1.0)\n\t\tU = -np.log(U).reshape([num_cls, -1]).astype(np.float32)\n\n\t\td.setUnaryEnergy(U)\n\n\t\t# create pairwise\n\t\td.addPairwiseGaussian(sxy=(3,3), compat=3, kernel=dcrf.DIAG_KERNEL, normalization=dcrf.NORMALIZE_SYMMETRIC)\n\t\td.addPairwiseBilateral(sxy=(40,40), srgb=(15,15,15), rgbim=np.ascontiguousarray(img), compat=10, kernel=dcrf.DIAG_KERNEL,\n\t\t\tnormalization=dcrf.NORMALIZE_SYMMETRIC)\n\n\t\t# inference\n\t\tQ = d.inference(4)\n\t\tres = np.array(Q).reshape((num_cls, img.shape[0], img.shape[1]))\n\n\t\treturn res\n\n\nif __name__ == \"__main__\":\n\n\teval_args = yaml.load(open(os.path.join(os.getcwd(), \"eval.yaml\"), 'r'))\n\targs = Namespace(**yaml.load(open(os.path.join(paths[\"project_path\"], \"saves{}\".format(eval_args[\"version\"]), \"config.yaml\"), 'r')))\n\n\ttrained_epochs = eval_args[\"epochs\"]\n\tsave_path = os.path.join(paths[\"project_path\"], \"saves{}\".format(eval_args[\"version\"]), \"{}-{}.pth\".format(args.model, trained_epochs))\n\n\tprint()\n\tprint(\"size:\\t{}\".format(args.img_size))\n\tprint(\"scale factor:\\t{}\".format(args.scale_factor))\n\tprint(\"batch size:\\t{}\".format(args.batch_size))\n\tprint(\"K:\\t{}\".format(args.K))\n\tprint()\n\tprint(\"version:\\t{}\".format(eval_args[\"version\"]))\n\tprint(\"epochs: \\t{}\".format(eval_args[\"epochs\"]))\n\tprint(\"samples:\\t{}\".format(eval_args[\"samples\"]))\n\tprint(\"used CRF:\\t{}\".format(eval_args[\"crf\"]))\n\tprint()\n\n\tif args.model==\"GCN\": model = GCN(cityscapes.num_classes, args.img_size, k=args.K).cuda()\n\telif args.model==\"UNet\": model = UNet(cityscapes.num_classes).cuda()\n\telse: raise ValueError(\"Invalid model arg.\")\n\tmodel.load_state_dict(torch.load(save_path))\n\n\tstart = time.time()\n\n\tevaluator = Evaluator(mode=eval_args[\"mode\"], samples=eval_args[\"samples\"], crf=eval_args[\"crf\"],\n\t\tmetrics=[\"miou\", \"cls_iou\"], standalone=True, save_pred=eval_args[\"save_pred\"])\n\tiou, cls_iou = evaluator.eval(model)\n\n\tend = time.time()\n\n\tprint(\"Took {} seconds.\".format(end-start))\n\tprint()\n\tprint(\"Mean IOU: {}\".format(iou))\n\tprint(\"Mean class IOU:\")\n\tfor i in cls_iou:\n\t\tprint(i)\n\tprint()\n\n","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":5825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"325060736","text":"#!/usr/bin/env python\nimport os\nimport json\nimport signal\nimport argparse\nimport subprocess\n\n\n# =====================\n# Parser and subparsers\n# =====================\n\nparser = argparse.ArgumentParser(description='pollarvate server cli')\nsubparsers = parser.add_subparsers()\n\n\n# ====================\n# Auxillary decorators\n# ====================\n\ndef subparser(function):\n \"\"\"Register a command function as as a subparser.\"\"\"\n p = subparsers.add_parser(\n function.__name__,\n description=function.__doc__\n )\n p.set_defaults(function=function)\n p.call = function\n\n # add port argument\n p.add_argument(\n '-p', '--port', default='8000',\n help='run command on given port number.'\n )\n\n # add app / router argument group\n g = p.add_mutually_exclusive_group(required=True)\n g.add_argument(\n '-a', '--app', default=False, action='store_true',\n help='run command for app server'\n )\n g.add_argument(\n '-r', '--router', default=False, action='store_true',\n help='run command for wamp router'\n )\n\n return p\n\n\n# ========\n# Commands\n# ========\n\n@subparser\ndef run(args):\n \"\"\"Run an application / router server on given port.\"\"\"\n if args.app:\n os.system('./manage.py runserver 0.0.0.0:' + str(args.port))\n\n elif args.router:\n with open(args.config, 'r+') as config:\n cfg = json.load(config)\n w = cfg['workers'][0]\n r = w['realms'][0]\n t = w['transports'][0]\n\n r['name'] = args.realm\n t['endpoint']['port'] = int(args.port)\n\n config.seek(0)\n json.dump(cfg, config, indent=2)\n config.truncate()\n\n os.system('crossbar start')\n\n# path to crossbar config\nrun.add_argument(\n '-c', '--config', default='./.crossbar/config.json',\n help='crossbar router config file path'\n)\n\n# router realm name\nrun.add_argument(\n '--realm', default='pollarvate',\n help='crossbar router realm name'\n)\n\n\n@subparser\ndef kill(args):\n \"\"\"Kill an application / router server.\"\"\"\n process = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)\n out, err = process.communicate()\n\n for line in out.decode('utf-8').splitlines():\n if 'python' in line:\n pid = int(line.split(None, 1)[0])\n os.kill(pid, signal.SIGKILL)\n\n\n# ====\n# Main\n# ====\n\ndef main(args=None):\n args = parser.parse_args(args)\n\n if getattr(args, 'function', None):\n args.function(args)\n else:\n parser.print_usage()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"186207276","text":"import sys, platform, json\nimport torch\nimport random\nimport numpy as np\n\nfrom scores import Scores\nfrom ddpg_agent import Agent\nfrom unityagents import UnityEnvironment\n\ndef train(env, hparams):\n # randomness (https://pytorch.org/docs/stable/notes/randomness.html)\n\n random_seed = hparams['seed']\n torch.manual_seed(random_seed)\n torch.cuda.manual_seed(random_seed)\n torch.cuda.manual_seed_all(random_seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n np.random.seed(random_seed)\n random.seed(random_seed)\n\n\n\n # get the default brain\n brain_name = env.brain_names[0]\n brain = env.brains[brain_name]\n\n scores_hparams = hparams['scores']\n scores = Scores( scores_hparams['expectation'],size=scores_hparams['window_size'], check_solved=scores_hparams['check_solved']) \n\n env_info = env.reset(train_mode=True)[brain_name] # reset the environment \n # number of agents\n num_agents = len(env_info.agents)\n\n # size of each action\n action_size = brain.vector_action_space_size\n states = env_info.vector_observations # get the current state (for each agent)\n state_size = states.shape[1]\n\n \n agents = []\n for _ in range(num_agents):\n agents.append( Agent(state_size, action_size, hparams))\n \n prefix = f'result/{hparams[\"output\"]}'\n\n for i in range(hparams['epoch']):\n env_info = env.reset(train_mode=True)[brain_name] # reset the environment \n # number of agents\n num_agents = len(env_info.agents)\n \n for agent in agents:\n agent.reset()\n \n # size of each action\n action_size = brain.vector_action_space_size\n states = env_info.vector_observations # get the current state (for each agent)\n\n # initialize the score (for each agent)\n epoch_score = np.zeros(num_agents)\n for t in range(1, hparams['t_max']+1):\n actions = np.array( [agents[i].act(states[i]) for i in range(num_agents) ])\n env_info = env.step(actions)[brain_name] # send all actions to tne environment\n next_states = env_info.vector_observations # get next state (for each agent)\n dones = env_info.local_done # see if episode finished\n \n for i in range(num_agents):\n agents[i].step(t, states[i], actions[i], env_info.rewards[i], next_states[i], dones[i]) \n\n states = next_states\n epoch_score += env_info.rewards\n #print('\\rTimestep {}\\tmin: {:.2f}\\tmax: {:.2f}' .format(t, np.min(epoch_score), np.max(epoch_score)), end='') \n\n if np.any(dones):\n break\n if scores.AddScore(np.max(epoch_score)) is True:\n break\n\n for i in range(len(agents)):\n agents[i].save( f'{prefix}_agent_{i}' )\n \n scores.FlushLog(prefix, False)\n\n\nif __name__ == '__main__':\n config = 'default.json'\n if len(sys.argv) > 1:\n config = sys.argv[1]\n\n with open( config, 'r', encoding='utf-8') as f:\n hparams = json.load(f)\n\n print(hparams)\n fn = 'Tennis.app'\n if platform.system() == 'Linux':\n fn = 'Tennis_Linux_NoVis/Tennis.x86_64'\n elif platform.system() == 'Windows':\n fn = 'Tennis_Windows_x86_64/Tennis.exe'\n env = UnityEnvironment(file_name=fn) \n train(env, hparams)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"35029164","text":"from math import floor\r\n\r\ntable_file = 'ev_table.csv'\r\nroute_starts = [(9, 'routes/lvl_9.txt'), (10, 'routes/lvl_10.txt'), (11, 'routes/lvl_11.txt')]\r\nroute_file = 'routes/post_mars.txt'\r\noutput_file_name = 'route-short.mdr'\r\n\r\ndebug = False\r\n\r\n# {pokemon_name: (exp_yield, [ev_yields])}\r\ndata = {}\r\nwith open(table_file) as f:\r\n for line in f:\r\n line = line.replace('\\n', '').split(',')\r\n name = line[0].lower()\r\n exp = int(line[1])\r\n evs = [int(ev) for ev in line[2:8]]\r\n data[name] = (exp, evs)\r\n\r\n# total experience needed in order to reach 'current_lvl'\r\ndef total_exp_needed(current_lvl):\r\n return floor(6 / 5 * current_lvl ** 3 - 15 * current_lvl ** 2 + 100 * current_lvl - 140)\r\n\r\n# experience needed in order to level up from 'current_lvl' to 'current_lvl + 1'\r\ndef exp_to_next_lvl(current_lvl):\r\n return total_exp_needed(current_lvl + 1) - total_exp_needed(current_lvl)\r\n\r\n# state for managing current lvl, exp and writing evs during level up\r\nclass Starly:\r\n\r\n def __init__(self, start_lvl, file):\r\n self.lvl = start_lvl\r\n self.exp_remaining = exp_to_next_lvl(self.lvl)\r\n self.evs = [0, 0, 0, 0, 0, 0]\r\n self.file = file\r\n self.opponents = []\r\n file.write(f'\\n{start_lvl}:\\n')\r\n self.print()\r\n\r\n # write evs at the start of current level\r\n def print(self):\r\n self.file.write(f' {self.lvl} -> {\", \".join([str(ev) for ev in self.evs])}')\r\n if self.opponents:\r\n self.file.write(f' # {\", \".join(self.opponents)}')\r\n self.file.write('\\n')\r\n\r\n def check_lvl_up(self):\r\n if self.exp_remaining <= 0:\r\n self.lvl += 1\r\n self.exp_remaining += exp_to_next_lvl(self.lvl)\r\n self.print()\r\n self.opponents.clear()\r\n self.check_lvl_up() # multiple level ups in a row\r\n\r\n # force the current level and throw away any remaining exp, in order to simulate rare candies\r\n def force(self, target_lvl):\r\n if debug:\r\n print(f'forcing from lvl {self.lvl} with {self.exp_remaining} exp remaining to lvl {target_lvl}')\r\n while self.lvl < target_lvl:\r\n self.exp_remaining = 0\r\n self.check_lvl_up()\r\n\r\n # gain exp and evs for a defeated (trainer) pokemon\r\n def fight(self, other_poke_name, other_poke_lvl, shared=False):\r\n exp, evs = data[other_poke_name]\r\n self.exp_remaining -= floor(floor(exp * other_poke_lvl / 7) * 1.5 * (0.5 if shared else 1))\r\n self.evs = [x + y for x, y in zip(self.evs, evs)]\r\n self.opponents.append(other_poke_name)\r\n self.check_lvl_up()\r\n\r\n# open main route file\r\nwith open(route_file) as file:\r\n main_route = file.read()\r\n\r\n# create output file\r\nwith open(output_file_name, 'w') as output_file:\r\n\r\n # write base stats for ranger\r\n output_file.write(':::tracker{species=Starly baseStats=\"[[40, 55, 30, 30, 30, 60], [55, 75, 50, 40, 40, 80], [85, 120, 70, 50, 50, 100]]\"}')\r\n\r\n # the route has 3 different starts, we do separate calculations for lvl 9, 10 and 11 starly\r\n for start_lvl, route_file in route_starts:\r\n\r\n if debug:\r\n print(f'\\nlvl {start_lvl} route')\r\n\r\n birb = Starly(start_lvl, output_file)\r\n\r\n with open(route_file) as file:\r\n route_start = file.read()\r\n route = route_start + '\\n' + main_route\r\n # print(route)\r\n\r\n for line_ in route.split('\\n'):\r\n # print(line_)\r\n line = line_\r\n\r\n # skip empty lines ?\r\n if not line:\r\n continue\r\n\r\n # trim comments\r\n if '#' in line:\r\n line = line[:line.find('#')]\r\n\r\n # split line into words\r\n line = [part.lower() for part in line.split(' ')]\r\n\r\n # workaround for space in mr. mime\r\n if line[0][-1] == '.':\r\n line[0] += ' ' + line[1]\r\n del line[1]\r\n\r\n # finally we can start parsing lines\r\n if line[0] == 'force':\r\n target_lvl = int(line[1])\r\n birb.force(target_lvl)\r\n\r\n else:\r\n if line[0] not in data:\r\n print(f'invalid line: {line_}')\r\n continue\r\n\r\n if debug:\r\n\r\n # does the heracross cause an extra lvl up for the calvin fight?\r\n if line[0] == 'heracross' and line[1] == '25':\r\n print(f'before heracross: lvl {birb.lvl} with {birb.exp_remaining} exp remaining')\r\n birb.fight(line[0], int(line[1]), line[-1] == 'shared')\r\n print(f'after heracross: lvl {birb.lvl} with {birb.exp_remaining} exp remaining')\r\n elif line[0] == 'bronzor' and line[1] == '23':\r\n print(f'before calvin bronzor: lvl {birb.lvl} with {birb.exp_remaining} exp remaining')\r\n birb.fight(line[0], int(line[1]), line[-1] == 'shared')\r\n print(f'after calvin bronzor: lvl {birb.lvl} with {birb.exp_remaining} exp remaining')\r\n elif line[0] == 'shieldon' and line[1] == '23':\r\n print(f'before calvin shieldon: lvl {birb.lvl} with {birb.exp_remaining} exp remaining')\r\n birb.fight(line[0], int(line[1]), line[-1] == 'shared')\r\n print(f'after calvin shieldon: lvl {birb.lvl} with {birb.exp_remaining} exp remaining')\r\n elif line[0] == 'kirlia' and line[1] == '38':\r\n print(f'before snow route olivia: lvl {birb.lvl} with {birb.exp_remaining} exp remaining')\r\n birb.fight(line[0], int(line[1]), line[-1] == 'shared')\r\n\r\n else:\r\n birb.fight(line[0], int(line[1]), line[-1] == 'shared')\r\n\r\n else:\r\n birb.fight(line[0], int(line[1]), line[-1] == 'shared')\r\n\r\n output_file.write(':::')\r\n","sub_path":"evs/calc_evs.py","file_name":"calc_evs.py","file_ext":"py","file_size_in_byte":6011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"246854239","text":"import tensorflow as tf\nimport numpy as np\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\nDOMAIN_SIZE = 25\n\n\na = np.arange(DOMAIN_SIZE, dtype = np.float32)\na = a.reshape([DOMAIN_SIZE, 1])\n\nb = np.zeros([DOMAIN_SIZE, DOMAIN_SIZE], dtype = np.float32)\nb[:,:] = 0.001\nfor i in range(DOMAIN_SIZE):\n b[i, i] = 1\n\n\nx = a\ny = b\n\n\nINPUT_SIZE = 1\nOUTPUT_SIZE = DOMAIN_SIZE\nHIDDEN_SIZE = 100\n\n###\ntf_x = tf.placeholder(tf.float32, shape=[None, INPUT_SIZE])\ntf_y = tf.placeholder(tf.float32, shape=[None, OUTPUT_SIZE])\n\nlayer1 = tf.layers.dense(tf_x, HIDDEN_SIZE, tf.nn.sigmoid)\noutput = tf.layers.dense(layer1, OUTPUT_SIZE)\n\n\n# accuracy = tf.metrics.accuracy(\n# labels=tf.squeeze(tf_y),\n# predictions=tf.argmax(output, axis=1))[1]\n\ncorrect_prediction = tf.equal(tf.argmax(output, 1), tf.argmax(tf_y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\nloss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n labels=tf_y, logits=output))\n#loss = tf.reduce_mean(tf.pow(tf_y * 10 - output, 2))\n#optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)\noptimizer = tf.train.AdamOptimizer(learning_rate=0.01)\n#optimizer = tf.train.MomentumOptimizer(learning_rate = 0.1, momentum=0.5)\ntrain_op = optimizer.minimize(loss)\n\nsess = tf.Session()\ninit_op = tf.group(\n tf.global_variables_initializer(),\n tf.local_variables_initializer())\nsess.run(init_op)\n\nfor _ in range(10):\n for __ in range(500):\n sess.run(train_op, feed_dict = {\n tf_x: x, tf_y: y})\n\n a, l = sess.run([accuracy, loss], feed_dict={tf_x: x, tf_y: y})\n\n print(\"%d %f %f\" % (_, a, l))\n\ndef map2(sess, value):\n _x = np.array([[value]])\n _y = sess.run(output, feed_dict = {tf_x: _x})\n return np.argmax(_y[0])\n\ndef map3(sess, value):\n _x = np.array([[value]])\n return sess.run(output, feed_dict = {tf_x: _x})\n\ncorrect = 0\nfor i in range(DOMAIN_SIZE):\n _y = map2(sess, i)\n if i != _y:\n print(\"%d != %d\" % (i, _y))\n else:\n correct += 1\n\nprint(\"%d/%d\" % (correct, DOMAIN_SIZE))\nprint(map3(sess, 2))\nprint(map3(sess, 3))\n","sub_path":"s1/tf_2.py","file_name":"tf_2.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"131609561","text":"import os\nimport pdb\nimport random\nimport pickle\nfrom collections import namedtuple\nimport argparse\n\nimport torch\n\nimport networkx as nx\nimport dgl\n\nfrom dgl import DGLGraph\ntorch.set_printoptions(threshold=5000)\n\n\nGRAPH_SIZE = 12\nMARGIN_INTRA = 600\nMARGIN_INTER = 6000\n\n\ndef main(args):\n pass\n\n\ndef load_data(args):\n dataset = None\n\n with open(args.datafile, 'rb') as f:\n dataset = pickle.load(f)\n\n features = dataset['features']\n data = dataset['data']\n\n x = []\n graphs = []\n graph_data = []\n tracklet_features = []\n labels = []\n graph_nodes = []\n\n # pdb.set_trace()\n\n for k in data:\n if len(data[k]) > GRAPH_SIZE:\n data[k] = sorted(data[k], key = lambda x: x['start'])\n\n for i1 in range(len(data[k]) - GRAPH_SIZE):\n g = nx.DiGraph()\n g_nodes = []\n graph_features = [None] * GRAPH_SIZE\n graph_features[0] = features[data[k][i1]['feature_id']]\n\n for i in range(GRAPH_SIZE):\n g.add_node(i)\n\n # for i in range(GRAPH_SIZE):\n # for j in range(GRAPH_SIZE):\n # g.add_edge(i, j)\n # g.add_edge(j, i)\n\n for i2 in range(i1+1, i1+GRAPH_SIZE):\n ii = i2 - i1\n graph_features[ii] = features[data[k][i2]['feature_id']]\n time_diff = data[k][i2]['start'] - data[k][i1]['end']\n if data[k][i1]['cam'] != data[k][i2]['cam']:\n if time_diff < MARGIN_INTER:\n g.add_edge(0, ii)\n g.add_edge(ii, 0)\n else:\n if time_diff < MARGIN_INTRA:\n g.add_edge(0, ii)\n g.add_edge(ii, 0)\n\n for i3 in range(i2+1, i1+GRAPH_SIZE):\n iii = i3 - i1\n time_diff = data[k][i3]['start'] - data[k][i2]['end']\n if data[k][i2]['cam'] != data[k][i3]['cam']:\n if time_diff < MARGIN_INTER:\n g.add_edge(iii, ii)\n g.add_edge(ii, iii)\n else:\n if time_diff < MARGIN_INTRA:\n g.add_edge(iii, ii)\n g.add_edge(ii, iii)\n\n g_nodes.append(data[k][i2]['cam'])\n g_nodes.append(data[k][i3]['cam'])\n\n g.remove_edges_from(nx.selfloop_edges(g))\n g = DGLGraph(g)\n g.add_edges(g.nodes(), g.nodes())\n\n positive_features = features[random.choice(data[k][i1+GRAPH_SIZE:])['feature_id']]\n\n negative_features = None\n while True:\n r = random.choice(list(data.keys()))\n\n if r == k:\n continue\n\n negative_features = features[random.choice(data[r])['feature_id']]\n\n break\n\n x.append((g, torch.FloatTensor(graph_features), torch.FloatTensor(positive_features)))\n graphs.append(g)\n graph_data.append(graph_features)\n tracklet_features.append(positive_features)\n labels.append(1)\n\n x.append((g, torch.FloatTensor(graph_features), torch.FloatTensor(negative_features)))\n graphs.append(g)\n graph_data.append(graph_features)\n tracklet_features.append(negative_features)\n labels.append(-1)\n\n graph_nodes.append(g_nodes)\n\n # return graph_nodes\n # pdb.set_trace()\n\n\n set_ids = list(range(len(labels)))\n random.shuffle(set_ids)\n\n training_set_limit = int(len(set_ids)*0.9)\n\n training_output_data = {\n 'x': x[:training_set_limit],\n 'labels': torch.LongTensor(labels[:training_set_limit]),\n 'set_ids': set_ids[:training_set_limit],\n 'graphs': graphs[:training_set_limit],\n 'graph_data': graph_data[:training_set_limit],\n 'tracklet_features': tracklet_features[:training_set_limit]\n }\n\n val_output_data = {\n 'x': x[training_set_limit:],\n 'labels': torch.LongTensor(labels[training_set_limit:]),\n 'set_ids': set_ids[training_set_limit:],\n 'graphs': graphs[training_set_limit:],\n 'graph_data': graph_data[training_set_limit:],\n 'tracklet_features': tracklet_features[training_set_limit:]\n }\n\n with open(args.trainingdataset, 'wb') as f:\n pickle.dump(training_output_data, f, pickle.HIGHEST_PROTOCOL)\n\n with open(args.valdataset, 'wb') as f:\n pickle.dump(val_output_data, f, pickle.HIGHEST_PROTOCOL)\n\n return training_output_data, val_output_data\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description='GAT')\n\n parser.add_argument(\"--dataset\", type=str, default='dataset.pickle')\n parser.add_argument(\"--trainingdataset\", type=str, default='tl120_iou0.85_d0.3_processed_training.pickle')\n parser.add_argument(\"--valdataset\", type=str, default='tl120_iou0.85_d0.3_processed_val.pickle')\n parser.add_argument(\"--output\", type=str, default='dataset.pickle')\n parser.add_argument(\"--datafile\", type=str, default=None)\n parser.add_argument(\"--cams\", type=int, nargs='+', default=[1, 8])\n parser.add_argument(\"--nodes\", type=int, default=12)\n parser.add_argument(\"--batchsize\", type=int, default=512)\n\n args = parser.parse_args()\n\n load_data(args)\n","sub_path":"dataset_generator.py","file_name":"dataset_generator.py","file_ext":"py","file_size_in_byte":5632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"391290745","text":"import os\nimport pygame as pg\n\npg.font.init()\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\nFONTS_DIR = os.path.join(BASE_DIR, *['static', 'fonts'])\n\n# game settings\nTITLE = \"Simple Platformer\"\nWIDTH = 800\nHEIGHT = 600\nSIZE = (WIDTH, HEIGHT)\nCENTER = (WIDTH // 2, HEIGHT // 2)\nFPS = 30\n\n# physics\nGRAVITY = 1.5\nAXES = 'xy'\n\n# physics - player\nPLAYER_ACC = 1.5 # pixels/frame^2\nPLAYER_FRICTION = PLAYER_ACC / 5 # max v is the denominator in px/frame\nPLAYER_JUMP_IMPULSE = -30 # impulse, pixels/frame^2\n\n# scene\nINITIAL_PLATFORMS = [\n (0, HEIGHT - 40, WIDTH, 40),\n (WIDTH // 2 - 60, HEIGHT // 3, WIDTH // 3, 20),\n (WIDTH // 4, HEIGHT // 2, 20, HEIGHT // 2),\n]\n# colors\nWHITE = pg.Color(\"#FFFFFF\")\nBLACK = pg.Color(\"#000000\")\nORANGE = pg.Color(\"#FF9900\")\nBLUE = pg.Color(\"#3399FF\")\n\n\ndef _make_font(fname):\n return lambda size: pg.font.Font(os.path.join(FONTS_DIR, fname), size)\n\n\nFONT_BODY = _make_font('FreePixel.ttf')\n","sub_path":"simpleplatformer/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"116693987","text":"#! usr/bin/env python\n\nimport pygame, math\nfrom pygame.locals import *\n\n# Custom imports\nfrom imagesDict import getImages\nfrom GlobalConstants import *\n\ndef flickerImageWhite(image):\n # Might be too slow :(\n for row in range(image.get_width()):\n for col in range(image.get_height()):\n color = image.get_at((row, col))\n if color[3] == 255: # ie, opaque\n color = (255, 255, 255, 255)\n image.set_at((row, col), color)\n\n return image\n\ndef flickerImageTranslucent(image, transparency):\n \"\"\"transparency measured from 0 to 100\"\"\"\n alpha = 255 - int(2.55*transparency)\n image = image.copy()\n image.fill((255, 255, 255, alpha), None, pygame.BLEND_RGBA_MULT)\n\n return image\n\ndef flickerImageTranslucent2(image, transparency):\n \"\"\"transparency measured from 0 to 100\"\"\"\n # Might be too slow :(\n for row in range(image.get_width()):\n for col in range(image.get_height()):\n color = image.get_at((row, col))\n if color[3] == 255: # ie, opaque\n color = (color[0], color[1], color[2], 255 - int(2.55*transparency))\n image.set_at((row, col), color)\n\n return image\n\n# Gets a color that is between the two colors in a linear way\ndef color_transition(color1, color2):\n # A number between 1 and 20 that changes at a set pace in a linear fashion\n linear_transform_num = math.sin(math.radians((pygame.time.get_ticks()/10)%180))\n diff_colors = (color2[0] - color1[0], color2[1] - color1[1], color2[2] - color1[2])\n new_color = []\n for index, chroma in enumerate(diff_colors):\n new_color.append( min(255, max(0, int(chroma * linear_transform_num) + color1[index])) )\n #print linear_transform_num, color1, color2, diff_colors, new_color\n\n return new_color\n\ndef transition_image_white(image):\n # Might be too slow :(\n for row in range(image.get_width()):\n for col in range(image.get_height()):\n color = image.get_at((row, col))\n if color[3] == 255: # ie, an opaque color\n color = color_transition(color, colorDict['white'])\n image.set_at((row, col), color)\n\n return image","sub_path":"Image_Modification.py","file_name":"Image_Modification.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"419993826","text":"# flake8: noqa\n\nfrom ._base import Material\nfrom ._mesh import (\n MeshBasicMaterial,\n MeshPhongMaterial,\n MeshFlatMaterial,\n MeshNormalMaterial,\n MeshNormalLinesMaterial,\n MeshSliceMaterial,\n)\nfrom ._points import PointsMaterial, GaussianPointsMaterial\nfrom ._line import (\n LineMaterial,\n LineThinMaterial,\n LineThinSegmentMaterial,\n LineSegmentMaterial,\n LineArrowMaterial,\n)\nfrom ._volume import VolumeBasicMaterial, VolumeSliceMaterial\nfrom ._background import BackgroundMaterial, BackgroundImageMaterial\n\n\n# Define __all__ for e.g. Sphinx\n__all__ = [\n cls.__name__\n for cls in globals().values()\n if isinstance(cls, type) and issubclass(cls, Material)\n]\n__all__.sort()\n__all__.remove(\"Material\")\n__all__.insert(0, \"Material\")\n","sub_path":"pygfx/materials/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"156853255","text":"import ibmiotf.application\r\nimport ibmiotf.device\r\nimport random\r\nimport json\r\nimport time\r\n\r\n#Provide your IBM Watson Device Credentials\r\norganization = \"q41r9v\"\r\ndeviceType = \"iotdevice\"\r\ndeviceId = \"9381\"\r\nauthMethod = \"token\"\r\nauthToken = \"9381362443\"\r\n\r\n\r\n# Initialize the device client.\r\ndef myCommandCallback(cmd):\r\n print(\"light on\")\r\n print(\"Command received: %s\" % cmd.data['command'])\r\ntry:\r\n deviceOptions = {\"org\": organization, \"type\": deviceType, \"id\": deviceId, \"auth-method\": authMethod, \"auth-token\": authToken}\r\n deviceCli = ibmiotf.device.Client(deviceOptions)\r\n#..............................................\r\n\r\nexcept Exception as e:\r\n print(\"Caught exception connecting device: %s\" % str(e))\r\n sys.exit()\r\n\r\n# Connect and send a datapoint \"hello\" with value \"world\" into the cloud as an event of type \"greeting\" 10 times\r\ndeviceCli.connect()\r\n\r\nwhile True:\r\n time.sleep(1)\r\n deviceCli.commandCallback = myCommandCallback\r\n\r\n# Disconnect the device and application from the cloud\r\ndeviceCli.disconnect()\r\n","sub_path":"iot python4.py","file_name":"iot python4.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"264397379","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\ndef solve1(r, c, m, e):\n return ['c' + ((e-1)*'.') + (c-e)*'*']\n\ndef solve2(r, c, m, e):\n if e == 1:\n return ['c' + (c-1)*'*', c*'*']\n if e == 2 or e % 2 == 1:\n return None\n e_cols = e / 2\n return [\n 'c' + (e_cols-1)*'.' + (c-e_cols)*'*',\n e_cols*'.' + (c-e_cols)*'*'\n ]\n\ndef solveN(*args):\n x = solveNx(*args)\n if x:\n res = []\n for row in x:\n res.append(''.join(row))\n return res\n return None\n\ndef dbg(x):\n res = []\n for row in x:\n res.append(''.join(row))\n return '\\n'.join(res)\n\ndef solveNx(r, c, m, e):\n if e == 2 or e == 3 or e == 5 or e == 7:\n return None\n x = [['*']*c for i in range(r)]\n x[0][0] = 'c'\n if e == 1:\n return x\n x[1][0] = '.'\n x[0][1] = '.'\n x[1][1] = '.'\n e -= 4;\n ri = 2\n ci = 2\n #print dbg(x), r, c, e\n while e > 1 and (ri < r or ci < c):\n if ri < r:\n x[ri][0] = '.'\n x[ri][1] = '.'\n ri += 1\n e -= 2\n if e > 1 and ci < c:\n x[0][ci] = '.'\n x[1][ci] = '.'\n ci += 1\n e -= 2\n\n ri = 2\n ci = 2\n while e > 0:\n x[ri][ci] = '.'\n ci += 1\n if ci == c:\n ri += 1\n ci = 2\n e -= 1\n return x\n\ndef solve(r, c, m):\n swap = False\n if r > c:\n r, c = c, r\n swap = True\n e = r*c-m\n if r == 1:\n result = solve1(r, c, m, e);\n elif r == 2:\n result = solve2(r, c, m, e);\n else:\n result = solveN(r, c, m, e);\n\n if not result:\n return 'Impossible'\n if swap:\n #result = zip(*result[::-1])\n result = map(lambda row : ''.join(row), zip(*result[::-1]))\n return '\\n'.join(result)\n\nif __name__ == \"__main__\":\n testcases = input()\n for case_n in xrange(1, testcases+1):\n case_data = map(int, raw_input().split())\n print(\"Case #%i:\\n%s\" % (case_n, solve(*case_data)))\n","sub_path":"solutions_5690574640250880_1/Python/farin/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"565274071","text":"import sys\nimport os\nimport shutil\nimport re\n\nEXTS = ['mp4', 'mkv', 'avi']\n\ndef panic(msg):\n print('Panic: ' + msg)\n exit(1)\n\ndef getext(path):\n return path.split('.')[-1]\n\ndef clean(path):\n ext = getext(path)\n result = re.search('[sS][0-9]+[eE][0-9]+', path)\n return result.group(0).upper() + '.' + ext\n\nif len(sys.argv) < 2:\n\tpath = '.'\nelse:\n\tpath = sys.argv[1]\n\t\nif not os.path.isdir(path):\n panic(path + ' is not a directory')\n\nfiles = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]\nfiles = [f for f in files if getext(f) in EXTS]\n\nfor f in files:\n cleaned = clean(f)\n shutil.move(f, cleaned)\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"519118001","text":"from gpt_neox import GPTNeoX, AutoregressiveWrapper\n\nimport os\nimport random\nimport tqdm\nimport gzip\nimport numpy as np\nimport torch\nimport torch.optim as optim\nfrom torch.nn import functional as F\nfrom torch.utils.data import DataLoader, Dataset\nimport torch.distributed as dist\nimport deepspeed\nimport json\nfrom tqdm.auto import tqdm, trange\nfrom gpt_neox.utils import GPUMonitor, DictArgs\n\n# constants\n\n# colab notebook https://colab.research.google.com/drive/1aEQY9MPFd0k7kebDtS33gOiuuqYveaiA?usp=sharing\n\nBaseConfig = {\n 'model': {\n 'num_batches': int(1e5),\n 'batch_size': 8,\n 'gradient_accumulate_every': 4,\n 'learning_rate': 1e-4,\n 'validate_every': 100,\n 'generate_every': 500,\n 'generate_length': 512,\n 'seq_len': 1024,\n 'num_tokens': 256,\n 'dim': 512,\n 'depth': 6,\n 'heads': 8,\n 'dim_head': 64,\n },\n 'ds': {\n 'local_rank': -1,\n 'output_dir': './model',\n 'deepspeed_config': './configs/base_deepspeed.json',\n 'deepspeed': True,\n 'save_interval': 100,\n }\n}\n\n\n# helpers\n\ndef cycle(loader):\n while True:\n for data in loader:\n yield data\n\ndef decode_token(token):\n return str(chr(max(32, token)))\n\ndef decode_tokens(tokens):\n return ''.join(list(map(decode_token, tokens)))\n\ndef prepare_optimizer_parameters(model):\n param_optimizer = list(model.named_parameters())\n param_optimizer = [n for n in param_optimizer if 'pooler' not in n[0]]\n no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']\n weight_decay = 0.01\n optimizer_grouped_parameters = [{\n 'params':\n [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],\n 'weight_decay':\n weight_decay\n }, {\n 'params':\n [p for n, p in param_optimizer if any(nd in n for nd in no_decay)],\n 'weight_decay':\n 0.0\n }]\n return optimizer_grouped_parameters\n\n\nclass TextSamplerDataset(Dataset):\n def __init__(self, data, seq_len):\n super().__init__()\n self.data = data\n self.seq_len = seq_len\n\n def __getitem__(self, index):\n rand_start = torch.randint(0, self.data.size(0) - self.seq_len - 1, (1,))\n full_seq = self.data[rand_start: rand_start + self.seq_len + 1].long()\n return full_seq.cuda()\n\n def __len__(self):\n return self.data.size(0) // self.seq_len\n\ndef load_wiki_dataset():\n with gzip.open('./data/enwik8.gz') as file:\n X = np.fromstring(file.read(int(95e6)), dtype=np.uint8)\n trX, vaX = np.split(X, [int(90e6)])\n data_train, data_val = torch.from_numpy(trX), torch.from_numpy(vaX)\n return data_train, data_val\n\n\ndef update_ds_config(model_config, deepspeed_config):\n dsc = json.load(open(deepspeed_config['deepspeed_config'], 'r'))\n dsc['train_batch_size'] = model_config['batch_size']\n dsc['gradient_accumulation_steps'] = model_config['gradient_accumulate_every']\n dsc['optimizer']['params']['lr'] = model_config['learning_rate']\n json.dump(dsc, open(deepspeed_config['deepspeed_config'], 'w'), indent=2)\n\n\ndef train_model(model_config=None, deepspeed_config=None):\n config = BaseConfig\n _mc = config['model']\n if model_config:\n _mc.update(model_config)\n _dsc = config['ds']\n if deepspeed_config:\n _dsc.update(deepspeed_config)\n update_ds_config(_mc, _dsc)\n os.makedirs(_dsc['output_dir'], exist_ok=True)\n # instantiate GPT-like decoder model\n model = GPTNeoX(\n num_tokens = _mc['num_tokens'],\n dim = _mc['dim'],\n seq_len = _mc['seq_len'],\n depth = _mc['depth'],\n heads = _mc['heads'],\n dim_head = _mc['dim_head']\n )\n model = AutoregressiveWrapper(model)\n\n data_train, data_val = load_wiki_dataset()\n\n train_dataset = TextSamplerDataset(data_train, _mc['seq_len'])\n val_dataset = TextSamplerDataset(data_val, _mc['seq_len'])\n train_loader = cycle(DataLoader(train_dataset, batch_size = _mc['batch_size']))\n val_loader = cycle(DataLoader(val_dataset, batch_size = _mc['batch_size']))\n\n # optimizer\n optim = torch.optim.Adam(model.parameters(), lr=_mc['learning_rate'])\n\n # training\n model_params = prepare_optimizer_parameters(model)\n train_args = DictArgs(_dsc)\n\n # ds loader\n model_engine, optim, _, _ = deepspeed.initialize(args=train_args,\n model=model,\n optimizer=optim,\n model_parameters=model_params)\n\n pbar = trange(_mc['num_batches'], mininterval=10., desc='Training Model', dynamic_ncols=True)\n monitor = GPUMonitor()\n for step in pbar:\n model.train()\n for __ in range(_mc['gradient_accumulate_every']):\n loss = model_engine(next(train_loader))\n model_engine.backward(loss)\n\n model_engine.step()\n pbar.set_description(f'Training Loss: {loss.item()}')\n pbar.update()\n torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)\n optim.step()\n optim.zero_grad()\n\n if step % _mc['validate_every'] == 0:\n model.eval()\n with torch.no_grad():\n loss = model_engine(next(val_loader))\n pbar.write(f'Validation Loss: {loss.item()}')\n\n if step % _mc['generate_every'] == 0:\n model.eval()\n inp = random.choice(val_dataset)[:-1]\n prime = decode_tokens(inp)\n pbar.write(f'{\"----\" * 50}')\n pbar.write(f\"Prime Inputs: {prime}\")\n pbar.write(f'{\"----\" * 50}')\n\n sample = model.generate(inp, _mc['generate_length'])\n output_str = decode_tokens(sample)\n pbar.write(f\"Decoded Outputs: {output_str}\")\n pbar.write(f'{\"----\" * 50}')\n \n if step % train_args.save_interval == 0 and step > 0:\n pbar.write(f'Saving Checkpoint at {step} to {train_args.output_dir}')\n model_engine.save_checkpoint(train_args.output_dir)\n\n\nif __name__ == '__main__':\n train_model()","sub_path":"gpt_neox/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"12942064","text":"# run on ipython , will not work on normal python\nimport timeit\nfrom collections import deque\n\nfrom pip import index\n\nlst = list(range(10000000))\ndeq = deque(range(1000000))\n\ndef insert_and_delete(ds):\n for _ in range(10):\n index.random.choice(range(100))\n ds.remove(index)\n ds.insert(index,index)\n\nstart = timeit.time()\nprint(\"Started\")\ninsert_and_delete(lst)\nend = timeit.time()\nprint (end-start)\n\nstart = timeit.time()\nprint(\"Started\")\ninsert_and_delete(deq)\nend = timeit.time()\nprint (end-start)","sub_path":"Day 9/collections.py","file_name":"collections.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"211440567","text":"import json\nimport logging\nimport requests\n\nfrom django.conf import settings\nfrom django.utils.translation import ugettext_lazy as _\nimport six\nimport six.moves.urllib.parse as urlparse\n\nfrom keystoneclient import exceptions as keystone_exceptions\n\nfrom openstack_auth import backend\nfrom openstack_auth import utils as auth_utils\n\nfrom horizon import exceptions\nfrom horizon import messages\nfrom horizon.utils import functions as utils\n\nfrom openstack_dashboard.api import base\nfrom openstack_dashboard import policy\n\n\nLOG = logging.getLogger(__name__)\nDEFAULT_ROLE = None\n\n# Set up our data structure for managing Identity API versions, and\n# add a couple utility methods to it.\nclass IdentityAPIManager(base.APIVersionManager):\n def upgrade_v2_user(self, user):\n if getattr(user, \"project_id\", None) is None:\n user.project_id = getattr(user, \"default_project_id\",\n getattr(user, \"tenantId\", None))\n return user\n\n def get_project_manager(self, *args, **kwargs):\n if VERSIONS.active < 3:\n manager = keystoneclient(*args, **kwargs).tenants\n else:\n manager = keystoneclient(*args, **kwargs).projects\n return manager\n\n\nVERSIONS = IdentityAPIManager(\n \"identity\", preferred_version=auth_utils.get_keystone_version())\n\n\n# Import from oldest to newest so that \"preferred\" takes correct precedence.\ntry:\n from keystoneclient.v2_0 import client as keystone_client_v2\n VERSIONS.load_supported_version(2.0, {\"client\": keystone_client_v2})\nexcept ImportError:\n pass\n\ntry:\n from keystoneclient.v3 import client as keystone_client_v3\n VERSIONS.load_supported_version(3, {\"client\": keystone_client_v3})\nexcept ImportError:\n pass\n\n\ndef keystoneclient(request, admin=False):\n \"\"\"Returns a client connected to the Keystone backend.\n\n Several forms of authentication are supported:\n\n * Username + password -> Unscoped authentication\n * Username + password + tenant id -> Scoped authentication\n * Unscoped token -> Unscoped authentication\n * Unscoped token + tenant id -> Scoped authentication\n * Scoped token -> Scoped authentication\n\n Available services and data from the backend will vary depending on\n whether the authentication was scoped or unscoped.\n\n Lazy authentication if an ``endpoint`` parameter is provided.\n\n Calls requiring the admin endpoint should have ``admin=True`` passed in\n as a keyword argument.\n\n The client is cached so that subsequent API calls during the same\n request/response cycle don't have to be re-authenticated.\n \"\"\"\n user = request.user\n if admin:\n if not policy.check(((\"identity\", \"admin_required\"),), request):\n raise exceptions.NotAuthorized\n endpoint_type = 'adminURL'\n else:\n endpoint_type = getattr(settings,\n 'OPENSTACK_ENDPOINT_TYPE',\n 'internalURL')\n\n\n api_version = VERSIONS.get_active_version()\n\n # Take care of client connection caching/fetching a new client.\n # Admin vs. non-admin clients are cached separately for token matching.\n cache_attr = \"_keystoneclient_admin\" if admin \\\n else backend.KEYSTONE_CLIENT_ATTR\n if (hasattr(request, cache_attr) and\n (not user.token.id or\n getattr(request, cache_attr).auth_token == user.token.id)):\n conn = getattr(request, cache_attr)\n else:\n endpoint = _get_endpoint_url(request, endpoint_type)\n insecure = getattr(settings, 'OPENSTACK_SSL_NO_VERIFY', False)\n cacert = getattr(settings, 'OPENSTACK_SSL_CACERT', None)\n LOG.debug(\"Creating a new keystoneclient connection to %s.\" % endpoint)\n remote_addr = request.environ.get('REMOTE_ADDR', '')\n conn = api_version['client'].Client(token=user.token.id,\n endpoint=endpoint,\n original_ip=remote_addr,\n insecure=insecure,\n cacert=cacert,\n auth_url=endpoint,\n debug=settings.DEBUG)\n setattr(request, cache_attr, conn)\n return conn\n\n\n\ndef tenant_get(request, project, admin=True):\n LOG.info(request.__dict__) \n LOG.info('entering tenant_get function')\n manager = VERSIONS.get_project_manager(request, admin=admin)\n return manager.get(project)\n\ndef _get_endpoint_url(request, endpoint_type, catalog=None):\n if getattr(request.user, \"service_catalog\", None):\n url = base.url_for(request,\n service_type='identity',\n endpoint_type=endpoint_type)\n else:\n auth_url = getattr(settings, 'OPENSTACK_KEYSTONE_URL')\n url = request.session.get('region_endpoint', auth_url)\n\n # TODO(gabriel): When the Service Catalog no longer contains API versions\n # in the endpoints this can be removed.\n url = url.rstrip('/')\n url = urlparse.urljoin(url, 'v%s' % VERSIONS.active)\n\n return url\n\ndef user_get(request, user_id, admin=True):\n user = keystoneclient(request, admin=admin).users.get(user_id)\n return VERSIONS.upgrade_v2_user(user)\n\ndef check_username(request, username):\n keystone = internal_keystoneclient(request)\n user = _find_user(keystone, username=username)\n return user\n\n","sub_path":"mfa/horizon/openstack_dashboard/api/mfa.py","file_name":"mfa.py","file_ext":"py","file_size_in_byte":5457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"101236631","text":"import sys, os, argparse\nimport torch\nimport data, lstm\nimport pickle, pandas\nimport time\nimport copy\nimport numpy as np\n\nfrom tqdm import tqdm\nfrom torch.autograd import Variable\nfrom predict import *\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-m\", \"--model\", type=str, default=\"models/model.pt\",\n help=\"Model (meta file) to use\")\nparser.add_argument(\"-i\", \"--input\", type=str, required=True,\n help=\"Input sentences (tsv file)\")\nparser.add_argument(\"-o\", \"--output\", type=str, default=\"output_ablation\")\nparser.add_argument(\"-v\", \"--vocabulary\", type=str,\n default=\"data/vocabulary/vocab.txt\",\n help=\"Vocabulary of the training corpus that the model was trained on\")\nparser.add_argument(\"-u\", \"--unit\", type=int, default=-1,\n help=\"Network unit to ablate\")\nparser.add_argument(\"--range_end\", type=int, default=-1,\n help=\"End (inclusive) of the range of units to ablate\")\nparser.add_argument(\"-s\", \"--seed\", type=int, default=5,\n help=\"Random seed for adding random units\")\nparser.add_argument(\"--number_of_units\", type=int, default=1300)\nparser.add_argument(\"--eos\", type=str, default=\"\",\n help=\"Token that indicates end of sentence\")\nparser.add_argument(\"--unk\", type=str, default=\"\",\n help=\"Token that indicates an unknown token\"),\nparser.add_argument(\"--cuda\", action=\"store_true\", default=False)\n\nargs = parser.parse_args()\n\nif not os.path.exists(args.output):\n os.makedirs(args.output)\ntemplate = args.input.split(\"/\")[-1].replace(\".tsv\", \"\")\noutput_fn = f\"{template}.info\"\n\n# Create Dictionary object from the vocabulary\nvocab = data.Dictionary(args.vocabulary)\ndata = pandas.read_csv(args.input, sep=\"\\t\", header=0)\nheader = list(data)\nsentences = data.loc[:, \"agreement\"]\n\nmodel = load_model(args.model, args.cuda)\nunits = []\n\nif 1300 > args.unit > -1:\n units = [args.unit]\n if 1300 > args.range_end > args.unit:\n units = list(range(args.unit, args.range_end+1))\n\n# Will be skipped if there are no units to ablate\nfor u in units:\n if u < 650:\n target_unit = torch.LongTensor(np.array([[int(u)]]))\n if args.cuda:\n target_unit.cuda()\n model.rnn.weight_hh_l0.data[:, target_unit] = 0\n\n elif 1300 > u > 649:\n target_unit = torch.LongTensor(np.array([[int(u)-650]]))\n if args.cuda:\n target_unit.cuda()\n model.rnn.weight_hh_l1.data[:, target_unit] = 0\n model.decoder.weight.data[:, target_unit] = 0\n\n else:\n sys.exit(\"Invalid unit number\")\n\n\n# Initial sentences are all . , feed these to the model\n# (Do not start in the original state)\ninit_sentence = \" \".join([\". \"] * 5)\nhidden = model.init_hidden(1)\ninit_out, init_h = feed_sentence(model, hidden, init_sentence.split(\" \"), vocab,\n args.cuda)\n\nlog_p_targets_correct, log_p_targets_wrong =\\\n get_predictions(data, sentences, model, init_out, init_h, vocab, args.cuda)\nout = categorise_predictions(data, sentences, log_p_targets_correct,\n log_p_targets_wrong)\n\ntemplate = args.input.split(\"/\")[-1].replace(\".tsv\", \"\")\ninfo = {}\n\ntry:\n with open(os.path.join(args.output, output_fn), \"rb\") as f:\n info = pickle.load(f)\nexcept Exception:\n pass\n\nif args.range_end > args.unit > -1:\n info[f\"{args.unit}-{args.range_end}\"] = out\nelif args.unit > -1:\n info[str(args.unit)] = out\nelse:\n info = out\n\nwith open(os.path.join(args.output, output_fn), \"wb\") as f:\n pickle.dump(info, f, -1)\n\nprint(f\"Information saved to {args.output}/{output_fn}\\n\")\n","sub_path":"ablation.py","file_name":"ablation.py","file_ext":"py","file_size_in_byte":3491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"159917135","text":"source(findFile(\"scripts\", \"dawn_global_startup.py\"))\r\nsource(findFile(\"scripts\", \"dawn_global_plot_tests.py\"))\r\nsource(findFile(\"scripts\", \"dawn_constants.py\"))\r\n\r\ndef the_actual_test():\r\n vals = dawn_constants\r\n #Open each tool then make dedicated\r\n #Peak fitting\r\n mouseClick(waitForObject(\":XY plotting tools_ToolItem\"), vals.TOOL_X, vals.TOOL_Y, 0, Button.Button1)\r\n activateItem(waitForObjectItem(\":Pop Up Menu\", \"Peak Fitting\"))\r\n \r\n #fit peak\r\n c = waitForObject(\":Plot_Composite\")\r\n b = c.bounds\r\n\r\n test.log(\"Image at (%d, %d) is %d x %d\" % (b.x,b.y, b.width, b.height))\r\n mouseDrag(c, b.x+b.width/2.35, b.y+b.height/4, int(b.width/7.5),0, 0, Button.Button1)\r\n snooze(1)\r\n \r\n #check being shown\r\n names = [\"Column_3\",\"Peak 1\"]\r\n check_plotted_traces_names(waitForObject(\":Configure Settings..._ToolItem\"), names)\r\n \r\n mouseClick(waitForObject(\":View Menu_ToolItem_2\"), 3, 10, 0, Button.Button1)\r\n activateItem(waitForObjectItem(\":Pop Up Menu\", \"Open 'Peak Fitting' in dedicated view\"))\r\n \r\n #activate derivative tool, which should deactivate the peak fitting\r\n mouseClick(waitForObject(\":XY plotting tools_ToolItem\"), vals.TOOL_X, vals.TOOL_Y, 0, Button.Button1)\r\n activateItem(waitForObjectItem(\":Pop Up Menu\", \"Derivative\"))\r\n names = [\"Column_3'\",\"Peak 1\"]\r\n check_plotted_traces_names(waitForObject(\":Configure Settings..._ToolItem\"), names)\r\n #check_plotted_trace_name_yval(waitForObject(\":Configure Settings..._ToolItem\"), \"Column_3'\", \"400.0\", \"-400.0\")\r\n \r\n mouseClick(waitForObject(\":View Menu_ToolItem_2\"), 4, 5, 0, Button.Button1)\r\n activateItem(waitForObjectItem(\":Pop Up Menu\", \"Open 'Derivative' in dedicated view\"))\r\n \r\n mouseClick(waitForObject(\":XY plotting tools_ToolItem\"), vals.TOOL_X, vals.TOOL_Y, 0, Button.Button1)\r\n activateItem(waitForObjectItem(\":Pop Up Menu\", \"Measurement\"))\r\n #Check derivative tool has not reset\r\n \r\n check_plotted_traces_names(waitForObject(\":Configure Settings..._ToolItem\"), names)\r\n check_plotted_trace_name_yval(waitForObject(\":Configure Settings..._ToolItem\"),\"Column_3'\", \"400.0\",\"-400.0\")\r\n \r\n #do measurement\r\n c = waitForObject(\":Plot_Composite\")\r\n b = c.bounds\r\n\r\n test.log(\"Image at (%d, %d) is %d x %d\" % (b.x,b.y, b.width, b.height))\r\n mouseDrag(c, b.x+b.width/2.35, b.y+b.height/4, int(b.width/7.5),0, 0, Button.Button1)\r\n snooze(2)\r\n \r\n clickTab(waitForObject(\":Measurement_CTabItem\"), 61, 12, 0, Button.Button1)\r\n #test.verify(waitForObjectItem(\":Measurement_Table\", \"0/0\").text == \"Measurement 1\", \"Verify measurement text\");\r\n \r\n mouseClick(waitForObject(\":View Menu_ToolItem_2\"), 3, 7, 0, Button.Button1)\r\n activateItem(waitForObjectItem(\":Pop Up Menu\", \"Open 'Measurement' in dedicated view\"))\r\n \r\n mouseClick(waitForObject(\":XY plotting tools_ToolItem\"), vals.TOOL_X, vals.TOOL_Y, 0, Button.Button1)\r\n activateItem(waitForObjectItem(\":Pop Up Menu\", \"Line Fitting\"))\r\n \r\n #do fit\r\n c = waitForObject(\":Plot_Composite\")\r\n b = c.bounds\r\n\r\n test.log(\"Image at (%d, %d) is %d x %d\" % (b.x,b.y, b.width, b.height))\r\n mouseDrag(c, b.x+b.width/2.35, b.y+b.height/4, int(b.width/7.5),0, 0, Button.Button1)\r\n snooze(1)\r\n \r\n names = [\"Column_3'\",\"Peak 1\", \"Fit 1\"]\r\n check_plotted_traces_names(waitForObject(\":Configure Settings..._ToolItem\"), names)\r\n \r\n test.verify(waitForObjectItem(\":Line Fitting_Table\", \"0/0\").text == \"Column_3'\", \"Verify measurement text\");\r\n \r\n mouseClick(waitForObject(\":View Menu_ToolItem_2\"), 12, 14, 0, Button.Button1)\r\n activateItem(waitForObjectItem(\":Pop Up Menu\", \"Open 'Line Fitting' in dedicated view\"))\r\n \r\n mouseClick(waitForObject(\":Line Fitting_CTabCloseBox\"), 11, 8, 0, Button.Button1)\r\n mouseClick(waitForObject(\":Measurement_CTabCloseBox\"), 7, 6, 0, Button.Button1)\r\n mouseClick(waitForObject(\":Derivative_CTabCloseBox\"), 7, 8, 0, Button.Button1)\r\n mouseClick(waitForObject(\":Peak Fitting_CTabCloseBox\"), 8, 11, 0, Button.Button1)\r\n \r\n\r\ndef main():\r\n \r\n #Start using clean workspace\r\n startOrAttachToDAWN()\r\n \r\n # Open data browsing perspective \r\n openPerspective(\"Data Browsing (default)\")\r\n \r\n #expand data tree and open metal mix\r\n expand(waitForObjectItem(\":Project Explorer_Tree\", \"data\"))\r\n expand(waitForObjectItem(\":Project Explorer_Tree\", \"examples\"))\r\n children = object.children(waitForObjectItem(\":Project Explorer_Tree\", \"examples\"))\r\n \r\n for child in children:\r\n if \"metalmix.mca\" in child.text:\r\n doubleClick(child, 5, 5, 0, Button.Button1)\r\n continue\r\n \r\n mouseClick(waitForObjectItem(\":Data_Table\", \"2/0\"), 9, 5, 0, Button.Button1)\r\n \r\n snooze(2)\r\n\r\n the_actual_test()\r\n #repeat\r\n snooze(2)\r\n the_actual_test()\r\n\r\n closeOrDetachFromDAWN()","sub_path":"org.dawnsci.squishtests/suite_tools1d_all/tst_switch_dedicated/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"412065573","text":"import icalendar,pytz,datetime\nimport event\nfrom dateutil.rrule import *\n\nclass Exporter(icalendar.Calendar):\n\tdef __init__(self):\n\t\ticalendar.Calendar.__init__(self)\n\n\t\tself.add('prodid', '-//Adelaid Uni Auto iCalendar//Rory Stokes//')\n\t\tself.add('version', '2.0')\n\t\tself.add('x-wr-timezone', u\"Australia/Adelaide\")\n\n\t\tself.add('x-wr-calname', u\"University Timetable\")\n\t\tself.add('x-wr-caldesc', u\"Automatically Generated UofA Timetable\")\n\n\t\ttzc = icalendar.Timezone()\n\t\ttzc.add('tzid', 'Australia/Adelaide')\n\t\ttzc.add('x-lic-location', 'Australia/Adelaide')\n\n\t\ttzs = icalendar.TimezoneStandard()\n\t\ttzs.add('tzname', 'CST')\n\t\ttzs.add('dtstart', datetime.datetime(1970, 10, 25, 3, 0, 0))\n\t\ttzs.add('rrule', {'freq': 'yearly', 'bymonth': 4, 'byday': '1su'})\n\t\ttzs.add('TZOFFSETFROM', datetime.timedelta(hours=10,minutes=30))\n\t\ttzs.add('TZOFFSETTO', datetime.timedelta(hours=9,minutes=30))\n\n\t\ttzd = icalendar.TimezoneDaylight()\n\t\ttzd.add('tzname', 'CST')\n\t\ttzd.add('dtstart', datetime.datetime(1970, 3, 29, 2, 0, 0))\n\t\ttzs.add('rrule', {'freq': 'yearly', 'bymonth': 10, 'byday': '1su'})\n\t\ttzd.add('TZOFFSETFROM', datetime.timedelta(hours=9,minutes=30))\n\t\ttzd.add('TZOFFSETTO', datetime.timedelta(hours=10,minutes=30))\n\n\t\ttzc.add_component(tzs)\n\t\ttzc.add_component(tzd)\n\t\tself.add_component(tzc)\n\n\tdef addEvent(self,subject,event):\n\t\ttemp = icalendar.Event()\n\t\ttz = pytz.timezone(\"Australia/Adelaide\")\n\t\td = datetime.datetime\n\t\ttemp.add('dtstart', event.startTime)\n\t\ttemp.add('dtend', event.endTime)\n\t\ttemp.add('dtstamp', d.now(tz))\n\t\ttemp.add('created', d.now(tz))\n\t\t#event.add('uid', u'123456')\n\t\ttemp.add('last-modified', d.now(tz))\n\t\ttemp.add('summary', subject.name+\" \"+event.type)\n\t\tif event.untilTime:\n\t\t\ttemp.add('rrule', {'freq': 'weekly', 'until': event.untilTime})\n\t\ttemp.add('description', '')\n\t\ttemp.add('location', event.location)\n\t\tself.add_component(temp)","sub_path":"exporter.py","file_name":"exporter.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"166661190","text":"import psycopg2\nfrom psycopg2.extras import execute_values, DictCursor\nimport pytest\n\nfrom nk_postgres import (\n validate_db_config, psycopg_cursor, wait_for_pg_service,\n psycopg_query_exec, psycopg_query_one, psycopg_query_all,\n pg_query_exec, pg_query_one, pg_query_all\n )\nfrom tests.conftest import TEST_DB_CONFIG\n\ndef test_valid_db_config():\n validate_db_config(TEST_DB_CONFIG)\n\ndef test_basic(session_pg):\n with psycopg_cursor(TEST_DB_CONFIG) as cursor: \n cursor.execute(\"SELECT 1\")\n\n@pytest.fixture()\ndef blank_foo(request, session_pg):\n with psycopg_cursor(TEST_DB_CONFIG) as cursor:\n cursor.execute(\"DROP TABLE IF EXISTS foo\")\n cursor.execute(\"CREATE TABLE IF NOT EXISTS foo (x int, y float)\")\n cursor.execute(\"INSERT INTO foo VALUES (20, .9876)\")\n\ndef test_query(session_pg, blank_foo):\n with psycopg_cursor(TEST_DB_CONFIG) as cursor:\n cursor.execute(\"SELECT * FROM foo\")\n xys = cursor.fetchall()\n assert len(xys)\n\ndef test_execute_values(session_pg, blank_foo):\n with psycopg_cursor(TEST_DB_CONFIG) as cursor: \n values = [(1, 3.1), (2, 200.1), (3, 0.004)]\n execute_values(cursor, \"INSERT INTO foo VALUES %s\", values)\n\ndef test_helpers(session_pg, blank_foo): \n psycopg_query_exec(TEST_DB_CONFIG, \"INSERT INTO foo VALUES (8, 2.5), (9, 9.9), (10, 10.10)\")\n assert 2.5 == psycopg_query_one(TEST_DB_CONFIG, \"SELECT * FROM foo WHERE x = 8\")[\"y\"]\n foos = psycopg_query_all(TEST_DB_CONFIG, \"SELECT * FROM foo\")\n assert len(foos)\n for foo in foos:\n assert 'x' in foo\n assert 'y' in foo\n\n\ndef test_short_names(session_pg, blank_foo): \n pg_query_exec(TEST_DB_CONFIG, \"INSERT INTO foo VALUES (28, 2.5), (29, 9.9), (30, 10.10)\")\n assert 2.5 == pg_query_one(TEST_DB_CONFIG, \"SELECT * FROM foo WHERE x = 28\")[\"y\"]\n foos = pg_query_all(TEST_DB_CONFIG, \"SELECT * FROM foo\")\n assert len(foos)\n for foo in foos:\n assert 'x' in foo\n assert 'y' in foo\n\n\ndef test_dict_cursor(session_pg, blank_foo):\n with psycopg_cursor(TEST_DB_CONFIG, cursor_factory=DictCursor) as cursor:\n cursor.execute(\"SELECT * FROM foo\")\n xys = cursor.fetchall()\n assert len(xys)\n for xy_dict in xys:\n assert 'x' in xy_dict\n assert type(xy_dict['x']) == int\n assert 'y' in xy_dict\n assert type(xy_dict['y']) == float \n\ndef test_server_down(killer_pg, docker_services):\n with psycopg_cursor(TEST_DB_CONFIG) as cursor: \n cursor.execute(\"SELECT 1\")\n docker_services.shutdown()\n with pytest.raises(psycopg2.OperationalError):\n with psycopg_cursor(TEST_DB_CONFIG) as cursor: \n cursor.execute(\"SELECT 1\")\n\ndef test_server_down_up(session_pg, docker_services):\n with psycopg_cursor(TEST_DB_CONFIG) as cursor: \n cursor.execute(\"SELECT 1\")\n docker_services.shutdown()\n with pytest.raises(psycopg2.OperationalError):\n with psycopg_cursor(TEST_DB_CONFIG) as cursor: \n cursor.execute(\"SELECT 1\")\n docker_services.start('test-pg-db')\n wait_for_pg_service(TEST_DB_CONFIG)\n with psycopg_cursor(TEST_DB_CONFIG) as cursor: \n cursor.execute(\"SELECT 1\")\n\ndef test_set_work_mem(session_pg):\n with psycopg_cursor(TEST_DB_CONFIG) as c:\n c.execute(\"set work_mem to '4GB'\")\n\n","sub_path":"tests/test_psycopg.py","file_name":"test_psycopg.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"578239380","text":"import sys\nimport time\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\n\n## STAGES ##\n_STAGE_LABELS = [\n\t\"preinit\",\n\t\"acquire\",\n\t\"uniform\",\n\t\"command\",\n\t\"submit\",\n\t\"present\",\n\t\"wait\",\n\t\"update\",\n\t\"total\"\n]\nSTAGE_FILTER = [\n\tFalse,\n\tFalse,\n\tTrue,\n\tTrue,\n\tTrue,\n\tTrue,\n\tFalse,\n\tFalse,\n\tFalse\n]\nSTAGE_LABELS = [\n\t_STAGE_LABELS[index] for index in range(len(STAGE_FILTER)) if STAGE_FILTER[index]\n]\nSTAGE_COUNT = len(STAGE_LABELS)\n\nINPUT_IGNORE_FIRST_SAMPLES = 0\nOUTLIERS_DEVIATIONS = 2.0\nclass StageData:\n\tdata = []\n\tmean = 0\n\tmedian = 0\n\tstd_dev = 0\n\n\tdef __init__(self, data):\n\t\tself.data = data[INPUT_IGNORE_FIRST_SAMPLES:]\n\t\tself.mean = np.mean(data)\n\t\tself.median = np.median(data)\n\t\tself.std_dev = np.std(data)\n\n\tdef outlier_mask(self):\n\t\treturn np.abs(\n\t\t\tself.data - self.median\n\t\t) <= self.std_dev * OUTLIERS_DEVIATIONS\n\n\tdef reject_outliers(self):\n\t\treturn self.data[self.outlier_mask()]\n\n\tdef outlier_bounds(self):\n\t\treturn (\n\t\t\tself.median - self.std_dev * OUTLIERS_DEVIATIONS,\n\t\t\tself.median + self.std_dev * OUTLIERS_DEVIATIONS\n\t\t)\n\n## INPUTS AND COLORS ##\nCOLOR_ALPHA = \"D0\"\nclass InputInfo:\n\tpath = None\n\tname = None\n\tcolor = f\"#000000{COLOR_ALPHA}\"\n\tstages = None\n\tstages_outlier_mask = None\n\n\tdef __init__(self, path, name, color):\n\t\tself.path = f\"{path}.txt\"\n\t\tself.name = name\n\t\tself.color = f\"{color}{COLOR_ALPHA}\"\n\n\tdef set_data(self, data):\n\t\tself.stages = [\n\t\t\tStageData(data[:, index]) for index in range(STAGE_COUNT)\n\t\t]\n\t\tself.stages_outlier_mask = self.stages[0].outlier_mask()\n\t\tfor stage in self.stages[1:]:\n\t\t\tself.stages_outlier_mask &= stage.outlier_mask()\n\nINPUTS = [\n\t# InputInfo(\"raw_ash_RHA\", \"ash_RHA\", \"#5EFEBF\"),\n\n\tInputInfo(\"raw_ash\", \"ash\", \"#FE6F5E\"),\n\tInputInfo(\"raw_vulkayes_ST\", \"vy_ST\", \"#5E9DFE\"),\n\tInputInfo(\"raw_vulkayes_MT\", \"vy_MT\", \"#5EEDFE\"),\n\n\t# InputInfo(\"raw_ash_uniform1000\", \"ash_u1000\", \"#FE6F5E\"),\n\t# InputInfo(\"raw_vulkayes_ST_uniform1000\", \"vy_ST_u1000\", \"#5E9DFE\"),\n\t# InputInfo(\"raw_vulkayes_MT_uniform1000\", \"vy_MT_u1000\", \"#5EEDFE\"),\n]\n\n## IO ##\nOUTPUT_FORMAT = \"png\"\nWORK_FOLDER = \"mac\"\nif len(sys.argv) > 1:\n\tWORK_FOLDER = sys.argv[1]\nif len(sys.argv) > 2:\n\tOUTPUT_FORMAT = sys.argv[2]\n\ndef format_time(nanos):\n\tif nanos >= 10**9:\n\t\tseconds = round(nanos / 10**9, 2)\n\t\treturn f\"{seconds} s\"\n\t\n\tif nanos >= 10**6:\n\t\tmillis = round(nanos / 10**6, 2)\n\t\treturn f\"{millis} ms\"\n\n\tif nanos >= 10**3:\n\t\tmicros = round(nanos / 10**3, 2)\n\t\treturn f\"{micros} us\"\n\t\n\treturn f\"{nanos} ns\"\n\ndef output_table_averages(base_input, inputs):\n\tprint()\n\tprint(\n\t\t\"Stage|{}|{}\".format(\n\t\t\tbase_input.name,\n\t\t\t\"|\".join(inp.name for inp in inputs)\n\t\t)\n\t)\n\tprint(\n\t\t\"-----|{}|{}\".format(\n\t\t\t\"-\" * len(base_input.name),\n\t\t\t\"|\".join(\"-\" * len(inp.name) for inp in inputs)\n\t\t)\n\t)\n\tfor index in range(STAGE_COUNT):\n\t\tprint(\n\t\t\t\"{}|{}|{}\".format(\n\t\t\t\tSTAGE_LABELS[index],\n\t\t\t\tformat_time(base_input.stages[index].median),\n\t\t\t\t\"|\".join(\n\t\t\t\t\t[\n\t\t\t\t\t\t\"{} ({:.0f}%)\".format(\n\t\t\t\t\t\t\tformat_time(inp.stages[index].median),\n\t\t\t\t\t\t\tinp.stages[index].median / base_input.stages[index].median * 100\n\t\t\t\t\t\t) for inp in inputs\n\t\t\t\t\t]\n\t\t\t\t)\n\t\t\t)\n\t\t)\n\n## PARSING ##\ndef parse_bench_point(span):\n\tmarks = list(map(\n\t\tlambda x: np.int64(x.split(\" = \")[1]),\n\t\tspan.split(\", \")\n\t))\n\n\treturn np.array(marks, dtype = np.int64)[STAGE_FILTER]\n\ndef parse_line(line):\n\tLINE_PREFIX = \"MARK_BUFFER: [\"\n\n\tparsed_points = []\n\n\tif line[:len(LINE_PREFIX)] != LINE_PREFIX:\n\t\treturn None\n\n\tcurrent_index = len(LINE_PREFIX)\n\twhile line[current_index] != \"]\":\n\t\tif line[current_index] == \",\":\n\t\t\tcurrent_index += 1\n\t\telif line[current_index] == \" \":\n\t\t\tcurrent_index += 1\n\t\telif line[current_index] == \"{\":\n\t\t\tspan_end = current_index + 1\n\t\t\twhile line[span_end] != \"}\":\n\t\t\t\tspan_end += 1\n\n\t\t\tparsed_points.append(\n\t\t\t\tparse_bench_point(line[current_index + 1:span_end])\n\t\t\t)\n\t\t\t\n\t\t\tcurrent_index = span_end + 1\n\t\n\treturn parsed_points\n\ndef read_input(path):\n\tdata_points = []\n\n\tprint(f\"Loading file {path}.. \", file = sys.stderr, end = \"\", flush = True)\n\tbefore_load = time.perf_counter()\n\n\twith open(path, \"r\") as file:\n\t\tfor line in file:\n\t\t\tparsed = parse_line(line)\n\t\t\tif parsed is not None:\n\t\t\t\tdata_points += parsed\n\n\tafter_load = time.perf_counter()\n\tprint(f\"took {after_load - before_load:.3f}s\", file = sys.stderr)\n\t\n\treturn np.array(data_points, dtype = np.int64)\n\n## PLOTTING ##\ndef annotate_average_bars(ax, bars):\n\ty_limits = ax.get_ylim()\n\ty_height = abs(y_limits[0] - y_limits[1])\n\tannotation_height = y_height * 0.02\n\n\tfor bar in bars:\n\t\theight = bar.get_height()\n\n\t\tax.annotate(\n\t\t\tformat_time(height),\n\t\t\txy = (\n\t\t\t\tbar.get_x() + bar.get_width() / 2,\n\t\t\t\tannotation_height\n\t\t\t),\n\t\t\txytext = (0, 0), textcoords = \"offset points\",\n\t\t\tha = \"center\", va = \"bottom\",\n\t\t\trotation = 90\n\t\t)\n\ndef plot_averages(inputs, title):\n\tprint(f\"Plotting averages: {title}.. \", file = sys.stderr, end = \"\", flush = True)\n\n\tbar_width = 0.7\n\tgroup_width = bar_width * (len(inputs) + 2)\n\tx = np.arange(STAGE_COUNT * group_width, step = group_width)\n\n\tfig, ax = plt.subplots()\n\tbase_offset = -(len(inputs) - 1) * bar_width / 2\n\t\n\tall_bars = []\n\tfor index in range(len(inputs)):\n\t\tinp = inputs[index]\n\t\tbars = ax.bar(\n\t\t\tx + base_offset + index * bar_width,\n\t\t\t[stage.median for stage in inp.stages],\n\t\t\tbar_width,\n\t\t\tlabel = inp.name,\n\t\t\tcolor = inp.color\n\t\t)\n\n\t\tannotate_average_bars(ax, bars)\n\t\tall_bars.append(bars)\n\t\n\tax.set_title(title)\n\t# ax.set_ylabel(\"Time\")\n\tax.set_xticks(x)\n\tax.set_xticklabels(STAGE_LABELS)\n\tax.legend()\n\n\tplt.setp(\n\t\tax.xaxis.get_majorticklabels(),\n\t\trotation = -25,\n\t\tha = \"left\",\n\t\trotation_mode = \"anchor\"\n\t)\n\n\tsave_path = f\"{WORK_FOLDER}/graphs/bars.{OUTPUT_FORMAT}\"\n\tplt.savefig(\n\t\tsave_path,\n\t\tdpi = 200\n\t)\n\n\tprint(f\"saved to {save_path}\", file = sys.stderr)\n\ndef plot_histograms(inputs, stage_index, title, bins = 100):\n\tprint(f\"Plotting histogram: {title}.. \", file = sys.stderr, end = \"\", flush = True)\n\n\tfig, ax = plt.subplots()\n\n\tfor inp in inputs:\n\t\tstage = inp.stages[stage_index]\n\t\tax.hist(\n\t\t\tstage.data[inp.stages_outlier_mask],\n\t\t\tbins = bins,\n\t\t\tlabel = inp.name,\n\t\t\tcolor = inp.color\n\t\t)\n\n\t\tax.axvline(\n\t\t\tx = stage.median,\n\t\t\tcolor = inp.color[:-2],\n\t\t\tlinestyle = \"--\"\n\t\t)\n\n\tax.set_title(title)\n\t# ax.set_xlabel(\"Time\")\n\tax.set_ylabel(\"Number of samples\")\n\tax.legend()\n\n\tax.xaxis.set_major_formatter(\n\t\tticker.FuncFormatter(\n\t\t\tlambda x, pos: format_time(x)\n\t\t)\n\t)\n\tplt.setp(\n\t\tax.xaxis.get_majorticklabels(),\n\t\trotation = -25,\n\t\tha = \"left\",\n\t\trotation_mode = \"anchor\"\n\t)\n\n\tsave_path = f\"{WORK_FOLDER}/graphs/{title}_hist.{OUTPUT_FORMAT}\"\n\tplt.savefig(\n\t\tsave_path,\n\t\tdpi = 200\n\t)\n\n\tprint(f\"saved to {save_path}\", file = sys.stderr)\n\ndef plot_linear(inp, title):\n\tprint(f\"Plotting histogram: {title}.. \", file = sys.stderr, end = \"\", flush = True)\n\n\tfig, ax = plt.subplots()\n\tx = np.arange(0, len(inp.stages[0].data), 1)\n\ty = np.zeros(shape = x.shape, dtype = np.int64)\n\n\tstage_datas = np.zeros(\n\t\tshape = (STAGE_COUNT, len(x))\n\t)\n\n\tstage_datas[0] = inp.stages[0].data\n\tfor index in range(1, STAGE_COUNT):\n\t\tstage_datas[index] = stage_datas[index - 1] + inp.stages[index].data\n\n\tfor index in range(STAGE_COUNT):\n\t\tax.plot(\n\t\t\tx[inp.stages_outlier_mask],\n\t\t\tstage_datas[index][inp.stages_outlier_mask],\n\t\t\tlabel = STAGE_LABELS[index],\n\t\t\tmarker = \"|\",\n\t\t\tlinestyle = \" \"\n\t\t)\n\n\tax.set_title(title)\n\tax.set_xlabel(\"Sample\")\n\tax.legend()\n\n\tax.yaxis.set_major_formatter(\n\t\tticker.FuncFormatter(\n\t\t\tlambda x, pos: format_time(x)\n\t\t)\n\t)\n\n\t# plt.show()\n\tsave_path = f\"{WORK_FOLDER}/graphs/{title}_line.{OUTPUT_FORMAT}\"\n\tplt.savefig(\n\t\tsave_path,\n\t\tdpi = 200\n\t)\n\n\tprint(f\"saved to {save_path}\", file = sys.stderr)\n\ndef main():\n\tfor inp in INPUTS:\n\t\tdata = read_input(f\"{WORK_FOLDER}/{inp.path}\")\n\t\tinp.set_data(data)\n\n\tplot_averages(\n\t\tINPUTS,\n\t\t\"median time\"\n\t)\n\t# output_table_averages(\n\t# \tINPUTS[0], INPUTS[1:]\n\t# )\n\n\t# for index in range(STAGE_COUNT):\n\t# \tplot_histograms(\n\t# \t\tINPUTS,\n\t# \t\tindex,\n\t# \t\tf\"{STAGE_LABELS[index]} samples\"\n\t# \t)\n\n\t# if OUTPUT_FORMAT != \"svg\":\n\t# \tfor inp in INPUTS:\n\t# \t\tplot_linear(\n\t# \t\t\tinp,\n\t# \t\t\tf\"{inp.name} sample time\"\n\t# \t\t)\n\nmain()","sub_path":"codes/teapot-benches/benches/script/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":8073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"623088889","text":"import torch\nimport torchvision\nfrom torchvision import transforms\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom model import ZeroNet\nfrom data_utils import STL10Loader\nfrom torch.optim.lr_scheduler import StepLR\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\ndef main(data_path='data',batch_size=10, epochs=150, num_classes=10):\n model = ZeroNet(num_classes=num_classes).to(device)\n\n stl10 = STL10Loader()\n\n train_loader = stl10.get_loader('train')\n valid_loader = stl10.get_loader('valid')\n\n optimizer = optim.Adam(model.parameters(), lr=1e-3)\n scheduler = StepLR(optimizer, step_size=50, gamma=0.1)\n\n for epoch in range(epochs):\n scheduler.step()\n model.train()\n for batch_index, (X, y) in enumerate(train_loader):\n model.zero_grad()\n X, y = X.to(device), y.to(device)\n scores = model(X)\n loss = F.cross_entropy(scores, y)\n\n loss.backward()\n optimizer.step()\n\n if batch_index % 1 == 0:\n train_log = 'Epoch {:2d}/{:2d}\\tLoss: {:.6f}\\tTrain: [{}/{} ({:.0f}%)]'.format(\n epoch, epochs, loss.cpu().item(), (batch_index+1), len(train_loader),\n 100. * (batch_index+1) / len(train_loader))\n print(train_log, end='\\r')\n print()\n\n correct = 0.\n last_valid_acc = 0.\n\n model.eval()\n with torch.no_grad():\n cnt = 0\n for batch_index, (X, y) in enumerate(valid_loader):\n X, y = X.to(device), y.to(device)\n scores = model(X)\n predict = scores.argmax(dim=-1)\n correct += predict.eq(y.view_as(predict)).cpu().sum()\n cnt += predict.size(0)\n valid_acc = correct.cpu().item()/cnt*100\n print(\"validation accuracy: {:.2f}%\".format(valid_acc))\n last_valid_acc = valid_acc\n\n SAVE_PATH = 'saved_model'\n torch.save(model.state_dict(), SAVE_PATH)\n with open('valid.txt', 'w') as f:\n f.write(str(last_valid_acc))\n\n\n\nif __name__==\"__main__\":\n main()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"245473505","text":"# -*- coding: utf:8 -*-\nimport sys\n\nfrom PIL import Image, ImageFilter\n\n#convertendo uma imagem colorida para esqcala de cinza\n\nif __name__== \"__main__\":\n #print(f'Quantos argumentos:{len(sys.argv)}')\n for i, arg in enumerate(sys.argv):\n if i == 1:\n entradaPrincipal = arg\n saidaPrincipal = arg\n\n#abrir os arquivos de entrada e saida \nimg1 = Image.open(entradaPrincipal)\n\nimg2 = img1.filter(ImageFilter.EDGE_ENHANCE_MORE)\n\nimg2.save(saidaPrincipal)\n","sub_path":"efeitoEDGE_ENHANCE_MORE.py","file_name":"efeitoEDGE_ENHANCE_MORE.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"483073041","text":"import tensorflow as tf\nfrom tensorflow import keras\nimport tensorflow_addons as tfa\nimport numpy as np\n\nfrom .layers import quick_gelu\n\n\nclass CLIPAttention(keras.layers.Layer):\n def __init__(self):\n super().__init__()\n self.embed_dim = 768\n self.num_heads = 12\n self.head_dim = self.embed_dim // self.num_heads\n self.scale = self.head_dim ** -0.5\n self.q_proj = keras.layers.Dense(self.embed_dim)\n self.k_proj = keras.layers.Dense(self.embed_dim)\n self.v_proj = keras.layers.Dense(self.embed_dim)\n self.out_proj = keras.layers.Dense(self.embed_dim)\n\n def _shape(self, tensor, seq_len: int, bsz: int):\n a = tf.reshape(tensor, (bsz, seq_len, self.num_heads, self.head_dim))\n return keras.layers.Permute((2, 1, 3))(a) # bs , n_head , seq_len , head_dim\n\n def call(self, inputs):\n hidden_states, causal_attention_mask = inputs\n bsz, tgt_len, embed_dim = hidden_states.shape\n query_states = self.q_proj(hidden_states) * self.scale\n key_states = self._shape(self.k_proj(hidden_states), tgt_len, -1)\n value_states = self._shape(self.v_proj(hidden_states), tgt_len, -1)\n\n proj_shape = (-1, tgt_len, self.head_dim)\n query_states = self._shape(query_states, tgt_len, -1)\n query_states = tf.reshape(query_states, proj_shape)\n key_states = tf.reshape(key_states, proj_shape)\n\n src_len = tgt_len\n value_states = tf.reshape(value_states, proj_shape)\n attn_weights = query_states @ keras.layers.Permute((2, 1))(key_states)\n\n attn_weights = tf.reshape(attn_weights, (-1, self.num_heads, tgt_len, src_len))\n attn_weights = attn_weights + causal_attention_mask\n attn_weights = tf.reshape(attn_weights, (-1, tgt_len, src_len))\n\n attn_weights = tf.nn.softmax(attn_weights)\n attn_output = attn_weights @ value_states\n\n attn_output = tf.reshape(\n attn_output, (-1, self.num_heads, tgt_len, self.head_dim)\n )\n attn_output = keras.layers.Permute((2, 1, 3))(attn_output)\n attn_output = tf.reshape(attn_output, (-1, tgt_len, embed_dim))\n\n return self.out_proj(attn_output)\n\n\nclass CLIPEncoderLayer(keras.layers.Layer):\n def __init__(self):\n super().__init__()\n self.layer_norm1 = keras.layers.LayerNormalization(epsilon=1e-5)\n self.self_attn = CLIPAttention()\n self.layer_norm2 = keras.layers.LayerNormalization(epsilon=1e-5)\n self.fc1 = keras.layers.Dense(3072)\n self.fc2 = keras.layers.Dense(768)\n\n def call(self, inputs):\n hidden_states, causal_attention_mask = inputs\n residual = hidden_states\n\n hidden_states = self.layer_norm1(hidden_states)\n hidden_states = self.self_attn([hidden_states, causal_attention_mask])\n hidden_states = residual + hidden_states\n\n residual = hidden_states\n hidden_states = self.layer_norm2(hidden_states)\n\n hidden_states = self.fc1(hidden_states)\n hidden_states = quick_gelu(hidden_states)\n hidden_states = self.fc2(hidden_states)\n\n return residual + hidden_states\n\n\nclass CLIPEncoder(keras.layers.Layer):\n def __init__(self):\n super().__init__()\n self.layers = [CLIPEncoderLayer() for i in range(12)]\n\n def call(self, inputs):\n [hidden_states, causal_attention_mask] = inputs\n for l in self.layers:\n hidden_states = l([hidden_states, causal_attention_mask])\n return hidden_states\n\n\nclass CLIPTextEmbeddings(keras.layers.Layer):\n def __init__(self, n_words=77):\n super().__init__()\n self.token_embedding_layer = keras.layers.Embedding(\n 49408, 768, name=\"token_embedding\"\n )\n self.position_embedding_layer = keras.layers.Embedding(\n n_words, 768, name=\"position_embedding\"\n )\n\n def call(self, inputs):\n input_ids, position_ids = inputs\n word_embeddings = self.token_embedding_layer(input_ids)\n position_embeddings = self.position_embedding_layer(position_ids)\n return word_embeddings + position_embeddings\n\n\nclass CLIPTextTransformer(keras.models.Model):\n def __init__(self, n_words=77):\n super().__init__()\n self.embeddings = CLIPTextEmbeddings(n_words=n_words)\n self.encoder = CLIPEncoder()\n self.final_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5)\n self.causal_attention_mask = tf.constant(\n np.triu(np.ones((1, 1, 77, 77), dtype=\"float32\") * -np.inf, k=1)\n )\n\n def call(self, inputs):\n input_ids, position_ids = inputs\n x = self.embeddings([input_ids, position_ids])\n x = self.encoder([x, self.causal_attention_mask])\n return self.final_layer_norm(x)\n","sub_path":"stable_diffusion_tensorflow/clip_encoder.py","file_name":"clip_encoder.py","file_ext":"py","file_size_in_byte":4784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"220947059","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\n\n\"\"\"\n\n#################################################################\n### WRITING YOUR FIRST PROGRAM MODULE\n\n\n \n#import libraries -- do this each time when loading the program\n\nimport pandas\n\nimport numpy\n\n#in this example I am working with a data file named birdWC. You should change this to work with your particular data file \n\nbirdWC = pandas.read_csv('brd_countdata.csv', low_memory = False)\n\n#lower-case all column names inthe data file- you can make this upper case too. This is good for the NEON dataset because they have weird uppercase lower case combos\n\nbirdWC.columns = map(str.lower, birdWC.columns)\n\n# bug fix for display formats to avoid run time errors\n\npandas.set_option('display.float_format', lambda x:'%f'%x)\n\n\n\nprint(len(birdWC)) # tells you number of observations in data set (rows)\nprint(len(birdWC.columns)) # tells you number of variables (columns)\n\n# Another way to see rows in a dataframe\nprint(len(birdWC.index))\n\n#My variable values are NOT numeric in this case, they are character therefore I did not convert to numeric, BUT if I had to:\n #to run this code- just remove the #\n #birdWC[\"VARIABLE\"] = birdWC[\"VARIABLE\"].convert_objects(convert_numeric=True)\n\n #Thinking about descrptive stats for a dataset-- FREQUENCIES AND COUNTS\n #here we're just looking at Counts and percentages-- see crosstab function below for making a crosstabs figure\n \nprint(\"Number of Observations per Site\")\nsitecount = birdWC[\"siteid\"].value_counts(sort=False, dropna = False)\nprint (sitecount)\n\nprint(\"Percentage of Observations per Site\")\nsiteper = birdWC[\"siteid\"].value_counts(sort=False, normalize= True, dropna = False)\nprint(siteper)\n\nprint(\"Number Bird Taxons Oberved\")\ntaxoncount = birdWC[\"taxonid\"].value_counts(sort=False, dropna = False)\nprint (taxoncount)\n\n\nprint(\"Percentage Bird Taxons Oberved\")\ntaxonper = birdWC[\"taxonid\"].value_counts(sort=False, normalize= True, dropna = False)\nprint(taxonper)\n\n\n#Alternatively\n\nsitecount1 = birdWC.groupby(\"siteid\").size()\nprint(sitecount1)\n\nsiteper1 = birdWC.groupby(\"siteid\").size()*100/len(birdWC)\nprint(siteper1)\n\nsiteper.to_csv(\"new_data.csv\")\n\n#taking a subset, so say I only wanted to look at native bird species in my dataset. If I wanted to further subset I could add things in using & (birdWC['nativestatuscode'] == \"N\")\n\nsubnat = birdWC[(birdWC['nativestatuscode'] == \"N\")]\n\n#Making a table to submit in Canvas- this makes an html figure which you can save OR copy and paste into Canvas\n\nsitecount = pandas.crosstab(index=birdWC[\"siteid\"], # Make a crosstab which makes a dataframe rather than a series\n columns=\"count\") # Name the count column\n\nsitecount\n\nsitecount.to_html() # when you execute this line it prints the html code in your console window.\n# you can copy this code from the console and put it in Canvas by choosing \"insert\" \"embed\" and pasting the code\n\nsitecount.to_html(\"sitecount.html\") #saves an html file to your working directory which you can copy paste or link to \n\n\n#To put PROPORTIONS in a frequency table\n\nsiteper= pandas.crosstab (index= birdWC[\"siteid\"], columns= \"proportions\").apply (lambda r: r/len (birdWC[\"siteid\"]), axis =1) # Make a crosstab which makes a dataframe rather than a series\n \n\nsiteper\n\n\nsiteper.to_html() # when you execute this line it prints the html code in your console window.\n# you can copy this code from the console and put it in Canvas by choosing \"insert\" \"embed\" and pasting the code\n\nsiteper.to_html(\"sitecount.html\") #saves an html file to your working directory which you can copy paste or link to \n\n\n\n\n\n\n##############################################################\n## DATA MANAGEMENT MODULE\n\n## missing data\n## code of taking a subset of the data by plot, then replacing native status so the birds coded as UNK is now NaN\n\nsubplot = birdWC[(birdWC['siteid'] == \"SJER\") & (birdWC['plotid'] == \"SJER_034\")]\nsub1=subplot.copy()\n\nsub1['nativestatuscode']= sub1['nativestatuscode'].replace(\"UNK\",numpy.nan) #replaces missing value\n\nprint(\"Native Status for SJER sub 034\")\nc1= sub1['nativestatuscode'].value_counts(sort=False,dropna=False) # dropna shows nan data\nprint(c1)\n\n\n### possible things I may need to code for with this data-- year, month and season-- do I want to create a new variable that captures this info? \n##Things to take into consideration when doing that- are there multiple counting days within the same month- This could be a problem if there are \n## counts of the same species in both of those sets...\n## what I need to do first is set-up more advanced freq tables\n\n\n## Making a frequency table with 2 variables \n\nsite_date= pandas.crosstab (index = birdWC[\"startdate\"], columns= birdWC[\"siteid\"], margins=True)\n\n## I could even do this with 3 variables-- not really what I need to do with this set, but in case you do....\n\nsite_date= pandas.crosstab (index = birdWC[\"startdate\"], columns= [birdWC[\"nativestatuscode\"], birdWC[\"siteid\"]], margins=True)\n\n\n###website for crosstabs examples for tables: http://hamelg.blogspot.com/2015/11/python-for-data-analysis-part-19_17.html\n\n\n\n\n## Making bins for a frequency table:\n## This is an example that uses GPA and bins the data that way. \ndegrees = [\"none\", \"cum laude\", \"magna cum laude\", \"summa cum laude\"] #This line creates the category names\nstudent_results = [3.93, 3.24, 2.80, 2.83, 3.91, 3.698, 3.731, 3.25, 3.24, 3.82, 3.22]# This line creates the dataset. For most of you this line isn't necessary. You already have your dataframe read in.\n\nstudent_results_degrees = pandas.cut(student_results, [0, 3.6, 3.8, 3.9, 4.0], labels=degrees) #This is the line that actually creates the cutoffs which are created and matches the labels with those numerical categories\npandas.value_counts(student_results_degrees) # This is the line that makes the counts and frequency table\n\n\n#So now I'm Going to do it with my bird_WC data\n\nnumber_of_observations = [\"1\", \"1-20\", \"More than 20\"]\nbird_data_number_of_observations = pandas.cut(birdWC[\"clustersize\"],[0,1,20,400], labels=number_of_observations)\npandas.value_counts(bird_data_number_of_observations)\n\ngwc = pandas.read_csv('gwc_fieldSuperParent.csv', low_memory = False)\n\n\nnumber_of_observations = [\"21\", \"21-41\", \"42-62\", \"63-83\", \"84-103\", \"104-300\", \"More than 300\"]\nspecificConductance_data_number_of_observations = pandas.cut(gwc[\"specificConductance\"],[0, 20, 41, 62, 83, 103, 300, 600], labels=number_of_observations)\npandas.value_counts(specificConductance_data_number_of_observations)\n\n","sub_path":"Sp_21/PDS_example_codes/Kovacs_example_code_birdWC_data_management.py","file_name":"Kovacs_example_code_birdWC_data_management.py","file_ext":"py","file_size_in_byte":6598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"108922519","text":"import math\nimport numpy\n\naltitudes = []\npressures = []\ntemperatures = []\neast_wind_speeds = []\nnorth_wind_speeds = []\nwind_magnitudes = []\ndensities = []\n\ntitle_row_length = 27\ndata_row_length = 21\n\nid_col = 0\nalt_col = 1\npres_col = 2\ntemp_col = 4\news_col = 6\nnws_col = 8\ndens_col = 12\n\n#class for each row of data\nclass Data:\n def __init__(self,id,alt,pres,temp,ews,nws,dens):\n self.ID = id\n self.altitude = alt\n self.pressure = pres\n self.temperature = temp\n self.eastWindSpeed = ews\n self.northWindSpeed = nws\n self.windSpeed = math.sqrt((float(ews)**2)+(float(nws)**2))\n self.density = dens\n\n def __repr__(self):\n return \"\\nID: \"+str(self.ID)+\"\\nAltitude: \"+str(self.altitude)+\"\\nPressure: \"+str(self.pressure)+\"\\nTemperature: \"+str(self.temperature)+\"\\nEast Wind Speed: \"+str(self.eastWindSpeed)+\"\\nNorth Wind Speed: \"+str(self.northWindSpeed)+\"\\nMagnitude Wind Speed: \"+str(self.windSpeed)+\"\\nDensity: \"+str(self.density)\n\ndef initialize_data(file_id):\n\n fileName = \"atmosphere_data/atmosphere\" + str(file_id) + \".txt\"\n data_set = open(fileName,encoding='utf-8')\n\n #remove \"\\n\"s and extra spaces from begining and end\n trimmed_data_set = data_set.read().rstrip();\n\n print(fileName)\n\n print(trimmed_data_set)\n\n trimmed_data_set = trimmed_data_set.split()\n\n organized_data_set = [];\n\n #make a list of lists, a list of all of the rows (21 values per row)\n j = 0\n subList = []\n column_headers = []\n location_info = []\n firstLine = True\n lineLength = title_row_length\n for i in trimmed_data_set:\n subList.append(i)\n j += 1\n if j == lineLength:\n j = 0\n if(firstLine):\n column_headers.append(subList)\n firstLine = False\n lineLength = data_row_length\n else:\n organized_data_set.append(subList)\n subList = []\n\n #total_lines set to the row number of the last row\n total_lines = organized_data_set[-1][0]\n\n\n #this is where the useful data is picked out\n measured_data = []\n idx = 0\n while(idx<=float(total_lines)):\n d = Data(organized_data_set[idx][id_col],organized_data_set[idx][alt_col],\n organized_data_set[idx][pres_col],organized_data_set[idx][temp_col],organized_data_set[idx][ews_col],\n organized_data_set[idx][nws_col],organized_data_set[idx][dens_col])\n\n measured_data.append(d)\n idx += 1\n\n #print(measured_data)\n\n for i in measured_data:\n altitudes.append(i.altitude)\n\n for i in measured_data:\n pressures.append(i.pressure)\n\n for i in measured_data:\n temperatures.append(i.temperature)\n\n for i in measured_data:\n east_wind_speeds.append(i.eastWindSpeed)\n\n for i in measured_data:\n north_wind_speeds.append(i.northWindSpeed)\n\n for i in measured_data:\n wind_magnitudes.append(i.windSpeed)\n\n for i in measured_data:\n densities.append(i.density)\n\n\ndef get_conditions(alt_input):\n\n alt_input = float(alt_input)\n\n return [numpy.interp(alt_input,altitudes,pressures),\n numpy.interp(alt_input,altitudes,temperatures),\n numpy.interp(alt_input,altitudes,east_wind_speeds),\n numpy.interp(alt_input,altitudes,north_wind_speeds),\n numpy.interp(alt_input,altitudes,wind_magnitudes),\n numpy.interp(alt_input,altitudes,densities)]\n\ndef get_interpolated_data(file_id,alt_input):\n initialize_data(file_id)\n if(type(alt_input) is int):\n return get_conditions(alt_input)\n elif(type(alt_input) is list):\n output = []\n for a in alt_input:\n output.append(get_conditions(a))\n return output\n","sub_path":"atmosphere.py","file_name":"atmosphere.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"44625429","text":"#!/usr/bin/python\n\nimport sys\nimport simplejson as json\n\ndef main(argv):\n count = {}\n line = sys.stdin.readline()\n try:\n while line:\n dict1 = json.loads(line.strip())\n if dict1['head'] == \"MATCH\":\n id1 = dict1['userid1']\n id2 = dict1['userid2']\n \n if id1 in count:\n count[id1]['matches'][id2] = count.get(id1).get('matches').get(id2,0) + 1\n else:\n count[id1] = {'matches':{id2:1}}\n \n if id2 in count:\n count[id2]['matches'][id1] = count.get(id2).get('matches').get(id1,0) + 1\n else:\n count[id2] = {'matches':{id1:1}}\n \n #if dict1['head'] == \"HELLO\":\n #pass\n #id1 = dict1['userid'] \n #if id1 in count:\n #pass\n #count[id1]['platform'] = dict1['platform']\n #else:\n #count[id1] = {'platform':dict1['platform']} \n \n line = sys.stdin.readline()\n except:\n pass\n \n for uid in count:\n if 'platform' in count[uid]:\n out = str(uid)+'\\t'+count[uid]['platform']+'\\n'\n sys.stdout.write(out)\n else:\n out = str(uid)+'\\t'+str(len(count[uid]['matches']))+'\\n'\n sys.stdout.write(out)\n\nif __name__ == \"__main__\":\n main(sys.argv)\n\n","sub_path":"bump-matches-reduce.py","file_name":"bump-matches-reduce.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"142484896","text":"from django.conf.urls import include, patterns, url\nfrom django.contrib import admin\n\nfrom . import views\n\nns_patterns = patterns('',\n url(r'^xview/func/$', views.xview_dec(views.xview), name='func'),\n)\n\nurlpatterns = patterns('',\n (r'^admin/', include(admin.site.urls)),\n (r'^admindocs/', include('django.contrib.admindocs.urls')),\n (r'^', include(ns_patterns, namespace='test')),\n (r'^xview/func/$', views.xview_dec(views.xview)),\n (r'^xview/class/$', views.xview_dec(views.XViewClass.as_view())),\n)\n","sub_path":"tests/admin_docs/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"70758532","text":"\"\"\"\nGiven a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.\n\nFor example,\nGiven the following matrix:\n\n[\n [ 1, 2, 3 ],\n [ 4, 5, 6 ],\n [ 7, 8, 9 ]\n]\n\nYou should return [1,2,3,6,9,8,7,4,5]. \n\"\"\"\n\nclass Solution:\n def __init__(self):\n print(self.spiralOrder3([[1,2,3],[4,5,6]]))\n def spiralOrder(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: List[int]\n \"\"\"\n if len(matrix)==1:\n return matrix[0]\n elif len(matrix)==0:\n return []\n m=matrix\n i,j = 0,0\n d = [0,1]\n ans=[]\n while m[i][j] != 'x':\n if d==[0,1] and (j+1==len(m[0]) or m[i][j+d[1]] == 'x'):\n d = [1,0]\n elif d==[1,0] and (i+1==len(m) or m[i+d[0]][j] == 'x'):\n print(i,j)\n d = [0, -1]\n elif d==[0,-1] and (j==0 or m[i][j+d[1]] == 'x'):\n d = [-1, 0]\n elif d==[-1,0] and (i==0 or m[i+d[0]][j] == 'x'):\n d = [0, 1]\n ans.append(m[i][j])\n m[i][j] = 'x'\n i += d[0]\n j += d[1]\n # print(m, ans)\n return ans\n\n # @StefanPochmann\n def spiralOrder2(self, matrix):\n return matrix and [*matrix.pop(0)] + self.spiralOrder2([*zip(*matrix)][::-1])\n\n # Modified for easier understanding\n def spiralOrder3(self, matrix):\n ans = []\n while len(matrix) > 0:\n ans += matrix[0]\n matrix.pop(0)\n matrix = [*zip(*matrix)][::-1]\n return ans\n\nSolution()\na=[[1,2,3],[4,5,6]]\n# print([*zip(*a)])\n# print(list(map(list, zip(*a))))\n# print([list(x) for x in zip(*a)])\n","sub_path":"54.py","file_name":"54.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"276795745","text":"import requests\nimport re\nfrom bs4 import BeautifulSoup\nfrom tkinter import *\n#初始化Tk\ntop = Tk()\ntop.title('电影天堂电影磁力链接获取器')\ntop.geometry('400x300+300+100')\n\n\n\nlist= []\ndict = {} \nlink = 'http://www.dytt8.net/html/gndy/oumei/list_7_2.html'\n\n \nres = requests.get(link) \nres.encoding = 'gb2312'\nsoup = BeautifulSoup(res.text,'html.parser')\n\n \nfor title in soup.select('.co_content8 table b a'): #将网站及迅雷链接放入dict中\n name= title.text\n url = 'http://www.dytt8.net' + title['href'] #获取网址\n list.append(name)\n\n res = requests.get(url) #解析单个电影网址\n res.encoding = 'gb2312'\n soup = BeautifulSoup(res.text,'html.parser')\n\n title = soup.select('.co_content8 td a') #获取迅雷链接\n title = title[0].text\n dict[name] = title\n \n\nvar = Variable()\ne = Entry(top, textvariable=var)\n\n\n\n\n\nfor str in list:\n l = Label(top, text=str, bg=\"pink\")\n var.set(dict.get(str)) # 设置文本框中的值\n\n\n l.pack(side=LEFT) # 这里的side可以赋值为LEFT RTGHT TOP BOTTOM\n\n e.pack() # 这里的side可以赋值为LEFT RTGHT TOP BOTTOM\n\n\ntop.mainloop() # 进入消息循环","sub_path":"爬虫/电影天堂/图形化gui试验产品/leabl + entry .py","file_name":"leabl + entry .py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"362972647","text":"import asyncio\n\nfrom aiokafka.producer.producer import AIOKafkaProducer\nfrom utils.times import BUCKETS_FOR_DATABASE_IO, BUCKETS_FOR_WAITING_FOR_QUOTA\n\nimport yaml\nfrom videos_config import Config, from_yaml\nfrom datetime import datetime, timedelta\nfrom dataclasses import asdict, dataclass\nimport json\nimport os\nfrom typing import Any, Awaitable, Callable, Tuple, Union\nfrom utils.sync_to_async import run_in_executor\nfrom prometheus_client import Counter, start_http_server, Histogram, Enum, Info\n\nfrom aiogoogle.client import Aiogoogle\nfrom aiogoogle.excs import HTTPError\nfrom utils.chunk import chunked\nfrom video_model import Video, from_json, get_empty_video\nfrom neo4j import BoltDriver, GraphDatabase, Neo4jDriver\nfrom utils.types import ChannelId, VideoId\nimport asyncpg\nfrom aiokafka.consumer.consumer import AIOKafkaConsumer\nfrom aiokafka.structs import ConsumerRecord\nfrom aiokafka.errors import CommitFailedError\nimport queries\nfrom quota_error import QuotaError\nimport logging\n\nNEO4J = Union[BoltDriver, Neo4jDriver]\nLOGGER_NAME = \"VIDEOS\"\nlogging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s',\n level=os.environ.get(\"LOGLEVEL\", \"INFO\"), datefmt='%Y-%m-%d %H:%M:%S')\nlog = logging.getLogger(LOGGER_NAME)\n\nDBNAME = os.environ['POSTGRES_DBNAME']\nUSER = os.environ['POSTGRES_USER']\nPASSWORD = os.environ['POSTGRES_PASSWORD']\nHOST = os.environ['POSTGRES_HOST']\nNEO4J_BOLT_URL = os.environ[\"NEO4J_BOLT_URL\"]\nNEO4J_USERNAME = os.environ[\"NEO4J_USERNAME\"]\nNEO4J_PASSWORD = os.environ[\"NEO4J_PASSWORD\"]\nTIMEDELTA_WRONG_DATA_UPDATE = timedelta(weeks=52*1000)\nNEW_DATA = datetime.min\nDEVELOPER_KEY = os.environ['YOUTUBE_API_KEY_V3']\nYOUTUBE_VIDEOS_MAX_CHUNK = 50\nYOUTUBE_VIDEOS_PART = \"contentDetails,id,liveStreamingDetails,localizations,recordingDetails,snippet,statistics,status,topicDetails\"\nYOUTUBE_FETCH_QUOTA_COST = 1\n\nconfiguration = Info('microservice_configuration',\n 'frequency of updates and quota usage')\napp_state = Enum('app_state', 'Information about service state',\n states=['running', 'waiting_for_quota'])\n\nvideos_io_time = Histogram(\n \"videos_io_time\", \"io time in seconds[s]\", [\"operation\"], buckets=BUCKETS_FOR_DATABASE_IO)\nyoutube_fetching_time = videos_io_time.labels(operation='youtube_fetching')\nkafka_produce_time = videos_io_time.labels(operation='kafka_produce')\nneo4j_insert_time = videos_io_time.labels(operation='neo4j_insert')\npostgres_inserting_new_time = videos_io_time.labels(\n operation='postgres_inserting_new')\npostgres_fetching_time = videos_io_time.labels(operation='postgres_fetching')\npostgres_insert_time = videos_io_time.labels(operation='postgres_insert')\n\nprocess_messages = Counter(\n 'videos_process_messages', \"messages processed from new_videos kafka topic\")\n\nupdate_events = Counter(\"videos_update_events\",\n \"updates triggered in program\")\nquota_usage = Counter(\"quota_usage\", \"usage of quota in replies module\")\ninserted_neo4j = Counter(\"videos_inserted_neo4j\",\n \"videos inserted to neo4j database\")\nprocess_update_time = Histogram(\n \"videos_process_time\", \"processing time in seconds[s]\", buckets=BUCKETS_FOR_WAITING_FOR_QUOTA)\n\nvideos_updated_videos = Counter(\n \"videos_updated_videos\", \"updated videos count\", [\"state\"])\nupdated_videos = videos_updated_videos.labels(state='success')\nrejected_videos = videos_updated_videos.labels(state='rejected')\nwrong_videos = videos_updated_videos.labels(state='wrong')\n\nemited_channels = Counter(\"videos_emited_channels\",\n \"emmited channels count to kafka new_channel topic\")\n\n\nasync def kafka_callback_bulk(bulk_size: int, consumer: AIOKafkaConsumer, callback: Callable[[list[ConsumerRecord]], Awaitable[None]]):\n # Consume messages\n while True:\n result = await consumer.getmany(timeout_ms=10 * 1000, max_records=bulk_size)\n for tp, messages in result.items():\n if messages:\n await callback(messages)\n # Commit progress only for this partition\n try:\n await consumer.commit({tp: messages[-1].offset + 1})\n except CommitFailedError:\n pass\n\n\ndef parse_messages(message):\n return VideoId(message.key)\n\n\ndef process_video_messages(pool: asyncpg.Pool):\n add_update = queries.to_update(NEW_DATA)\n\n async def f(messages: 'list[ConsumerRecord]'):\n process_messages.inc(len(messages))\n videos_ids = {parse_messages(c) for c in messages}\n with postgres_inserting_new_time.time():\n await pool.executemany(queries.update_insert_new_query, [add_update(x) for x in videos_ids])\n return f\n\n\nasync def update_trigger(frequency_h: float, callback: Callable[[], Awaitable[None]]):\n update_delta = timedelta(hours=frequency_h).total_seconds()\n while True:\n log.info(\"Try update\")\n await asyncio.gather(callback(), asyncio.sleep(update_delta))\n log.info(\"After update and sleep\")\n\n\nasync def fetch_videos_from_yt(videos_ids: 'set[VideoId]'):\n result = []\n async with Aiogoogle(api_key=DEVELOPER_KEY) as aiogoogle:\n with youtube_fetching_time.time():\n youtube_api = await aiogoogle.discover('youtube', 'v3')\n req = youtube_api.videos.list(\n part=YOUTUBE_VIDEOS_PART, id=\",\".join(videos_ids), maxResults=YOUTUBE_VIDEOS_MAX_CHUNK, hl=\"en_US\", regionCode=\"US\") # type: ignore\n try:\n result = await aiogoogle.as_api_key(req)\n quota_usage.inc(YOUTUBE_FETCH_QUOTA_COST)\n except HTTPError as err:\n if err.res.status_code == 403 and err.res.content['error']['errors'][0]['reason'] == \"quotaExceeded\":\n raise QuotaError\n raise\n parsed: list[Video] = []\n rejected = []\n for item in result[\"items\"]:\n try:\n parsed.append(from_json(item))\n except KeyError:\n rejected.append(item)\n rejected_videos.inc()\n if len(rejected) > 0:\n with open(f'./rejected/videos-{datetime.now()}.json', 'w') as f:\n json.dump(rejected, f)\n return parsed\n\n\n@run_in_executor\ndef neo4j_query(query: str, items: list[dict], neo4j: NEO4J):\n with neo4j.session() as session:\n session.run(query, {'rows': items})\n inserted_neo4j.inc(len(items))\n\n\ndef get_bytes_channel_id(channel_id: ChannelId): return str.encode(channel_id)\n\n\nasync def kafka_produce_channel_id(channel_id: ChannelId, producer: AIOKafkaProducer):\n with kafka_produce_time.time():\n await producer.send_and_wait(\"new_channels\", key=get_bytes_channel_id(channel_id))\n emited_channels.inc()\n\n\nasync def process_videos_chunk(old_updates: list[Tuple[VideoId, datetime]], pool: asyncpg.Pool, neo4j: NEO4J, producer: AIOKafkaProducer):\n video_ids = {i[0] for i in old_updates}\n try:\n videos = await fetch_videos_from_yt(video_ids)\n except QuotaError:\n return True\n fetched_videos_ids = {video.video_id for video in videos}\n wrong_new_videos = [a[0] for a in old_updates if a[1] ==\n NEW_DATA and a[0] not in fetched_videos_ids]\n if wrong_new_videos:\n log.warning(\"Incorrect videos_ids: %s\", \" \".join(wrong_new_videos))\n wrong_videos.inc(len(wrong_new_videos))\n ok_new_videos = {a[0] for a in old_updates if a[1] ==\n NEW_DATA and a[0] in fetched_videos_ids}\n wrong_old_videos = {a[0] for a in old_updates if a[1] !=\n NEW_DATA and a[0] not in fetched_videos_ids}\n tasks = []\n if ok_new_videos:\n parsed_videos = [asdict(\n video) for video in videos if video.video_id in ok_new_videos]\n tasks.append(neo4j_query(\n queries.static_video_query, parsed_videos, neo4j))\n if wrong_old_videos:\n parsed_videos = [get_empty_video(\n wrong_old_video) for wrong_old_video in wrong_old_videos]\n tasks.append(neo4j_query(\n queries.empty_video_insert_query, parsed_videos, neo4j))\n if videos:\n parsed_videos = [asdict(video) for video in videos]\n tasks.append(neo4j_query(\n queries.dynamic_video_query, parsed_videos, neo4j))\n with neo4j_insert_time.time():\n await asyncio.gather(*tasks)\n id_to_update = queries.to_update(datetime.now())\n id_not_to_update = queries.to_update(\n datetime.now()+TIMEDELTA_WRONG_DATA_UPDATE)\n updates = [id_to_update(i) for i in (wrong_old_videos | fetched_videos_ids)]+[\n id_not_to_update(i) for i in wrong_new_videos]\n with postgres_insert_time.time():\n await pool.executemany(queries.update_insert_query, updates)\n await asyncio.gather(*[kafka_produce_channel_id(channel_id, producer) for channel_id in {video.channel_id for video in videos if video.video_id in ok_new_videos}])\n updated_videos.inc(len(updates))\n return False\n\n\ndef parse_record(record) -> Tuple[VideoId, datetime]:\n return (VideoId(record[0]), record[1])\n\n\ndef process_update(bulk_size: int, config: Config, update_notifier: AIOKafkaConsumer, pool: asyncpg.Pool, neo4j: NEO4J, producer: AIOKafkaProducer) -> Callable[[], Awaitable[None]]:\n\n async def f():\n update_events.inc()\n log.info(\"Update triggered\")\n quota = config.quota_per_update_limit\n with process_update_time.time():\n while True:\n # take quota into consideration\n curr_fetch = min(quota, bulk_size)*YOUTUBE_VIDEOS_MAX_CHUNK\n with postgres_fetching_time.time():\n values = await pool.fetch(queries.videos_to_update_query, datetime.now() - timedelta(hours=config.update_frequency_h), curr_fetch)\n parsed_values = [parse_record(value) for value in values]\n if len(parsed_values) == 0:\n # if no items work is finished\n break\n quota_exceeded = await asyncio.gather(*[process_videos_chunk(chunk, pool, neo4j, producer) for chunk in chunked(YOUTUBE_VIDEOS_MAX_CHUNK, parsed_values)])\n quota -= sum(1 for exceeded in quota_exceeded if not exceeded)\n # handle Quotaexceeded if even one exceeded\n if quota <= 0 or any(exceeded for exceeded in quota_exceeded):\n log.warning(\"quota exceeded\")\n app_state.state('waiting_for_quota')\n # throw away all old updates\n await update_notifier.getmany(timeout_ms=0)\n while True:\n update = await update_notifier.getmany(timeout_ms=10 * 1000)\n for tp, messages in update.items():\n if messages:\n # if any update break\n quota = config.quota_per_update_limit\n app_state.state('running')\n break\n log.info(\"Update finished\")\n return f\n\n\nasync def main(data: Config):\n start_http_server(8000)\n configuration.info({'update_frequency': str(\n data.update_frequency_h), \"quota_per_update_limit\": str(data.quota_per_update_limit)})\n log.info(\"update_frequency_h: %f and quota_per_update_limit: %d\",\n data.update_frequency_h, data.quota_per_update_limit)\n videosConsumer = AIOKafkaConsumer(\n 'new_videos',\n bootstrap_servers='kafka:9092',\n enable_auto_commit=False, # Will disable autocommit\n auto_offset_reset=\"earliest\", # If committed offset not found, start from beginning\n group_id=\"videoModule\",\n key_deserializer=lambda key: key.decode(\"utf-8\") if key else \"\",\n )\n updateConsumer = AIOKafkaConsumer(\n 'updates',\n bootstrap_servers='kafka:9092',\n auto_offset_reset=\"latest\"\n )\n producer = AIOKafkaProducer(bootstrap_servers='kafka:9092')\n postgres_pool = asyncpg.create_pool(\n user=USER, password=PASSWORD, database=DBNAME, host=HOST)\n neo4j = GraphDatabase.driver(\n NEO4J_BOLT_URL, auth=(NEO4J_USERNAME, NEO4J_PASSWORD))\n pool, *_ = await asyncio.gather(postgres_pool, videosConsumer.start(), updateConsumer.start(), producer.start())\n if not pool or not neo4j:\n raise NotImplementedError(\"no connections\")\n try:\n tasks = []\n tasks.append(kafka_callback_bulk(100, videosConsumer,\n process_video_messages(pool)))\n if data.update_frequency_h > 0 and data.quota_per_update_limit > 0:\n tasks.append(update_trigger(data.update_frequency_h, process_update(\n 10, data, updateConsumer, pool, neo4j, producer)))\n await asyncio.gather(*tasks)\n finally:\n await asyncio.gather(videosConsumer.stop(), updateConsumer.stop(), pool.close(), producer.stop())\n neo4j.close()\n\n\nif __name__ == \"__main__\":\n log.info(\"service started\")\n with open(\"config.yaml\", 'r', encoding='utf-8') as f:\n config = yaml.load(f, Loader=yaml.FullLoader)\n asyncio.run(main(from_yaml(config)))\n","sub_path":"videos/videos.py","file_name":"videos.py","file_ext":"py","file_size_in_byte":13128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"179114300","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n\nThis example shows a QCalendarWidget widget.\n\n\"\"\"\n\nfrom PyQt5.QtWidgets import (QWidget, QCalendarWidget,\n QLabel, QApplication, QVBoxLayout)\nfrom PyQt5.QtCore import QDate\nimport sys\n\n\nclass Example(QWidget):\n\n def __init__(self):\n super().__init__()\n self.vbox = QVBoxLayout(self)\n\n self.cal = QCalendarWidget(self)\n self.cal.setGridVisible(True)\n self.cal.clicked[QDate].connect(self.showDate)\n\n self.vbox.addWidget(self.cal)\n\n self.lbl = QLabel(self)\n date = self.cal.selectedDate()\n self.lbl.setText(date.toString())\n\n self.vbox.addWidget(self.lbl)\n\n self.setLayout(self.vbox)\n\n self.setGeometry(300, 300, 350, 300)\n self.setWindowTitle('Calendar')\n self.show()\n\n def showDate(self, date):\n self.lbl.setText(date.toString())\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = Example()\n sys.exit(app.exec_())\n","sub_path":"Widgets/calendar.py","file_name":"calendar.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"5373122","text":"from room import Room\nfrom player import Player\nfrom world import World\n\nimport random\nfrom ast import literal_eval\n\n# Load world\nworld = World()\n\n\n# You may uncomment the smaller graphs for development and testing purposes.\n# map_file = \"maps/test_line.txt\"\n# map_file = \"maps/test_cross.txt\"\n# map_file = \"maps/test_loop.txt\"\n# map_file = \"maps/test_loop_fork.txt\"\nmap_file = \"maps/main_maze.txt\"\n\n# Loads the map into a dictionary\nroom_graph=literal_eval(open(map_file, \"r\").read())\nworld.load_graph(room_graph)\n\n# Print an ASCII map\nworld.print_rooms()\n\nplayer = Player(world.starting_room)\n\n# Fill this out with directions to walk\n# traversal_path = ['n', 'n']\ntraversal_path = []\n\nclass Stack():\n def __init__(self):\n self.stack = []\n def push(self, value):\n self.stack.append(value)\n def pop(self):\n if self.size() > 0:\n return self.stack.pop()\n else:\n return None\n def size(self):\n return len(self.stack)\n\ndef direction_inverse(direction):\n if direction == 'n':\n return 's'\n elif direction == 's':\n return 'n'\n elif direction == 'e':\n return 'w'\n else:\n return 'e'\n\ndef weird_inverse(direction):\n if direction == 's':\n return 'e'\n elif direction == 'e':\n return 's'\n elif direction == 'w':\n return 's'\n\nmoves = Stack()\nmy_visited_rooms = set()\nrooms = {}\nrooms_list = []\nmost_recent = None\n\ndef traverse(player, rooms, most_recent):\n room = player.current_room.id\n exits = player.current_room.get_exits()\n my_visited_rooms.add(room)\n\n for direction in exits:\n\n try:\n rooms[room][direction]\n pass\n\n except KeyError:\n\n rooms_list.append(room)\n\n next_room = player.current_room.get_room_in_direction(direction)\n\n # South and west is the hard combo, do that first\n if most_recent == 's' and 'w' in exits:\n next_room = player.current_room.get_room_in_direction('w')\n direction = 'w'\n\n # West then north was another trouble area\n elif most_recent == 'w' and 'n' in exits:\n next_room = player.current_room.get_room_in_direction('n')\n direction = 'n'\n\n # If our last move was to the south/east/west, keep going that way\n elif most_recent == 's' or most_recent == 'e' or most_recent == 'w':\n next_room = player.current_room.get_room_in_direction(most_recent)\n\n # If that doesn't work, try going the other \"weird\" direction\n if next_room == None:\n test = weird_inverse(most_recent)\n next_room = player.current_room.get_room_in_direction(test)\n\n if next_room == None:\n next_room = player.current_room.get_room_in_direction(direction)\n\n elif next_room.id in my_visited_rooms:\n if 'n' in exits:\n direction = 'n'\n next_room = player.current_room.get_room_in_direction('n')\n elif 's' in exits:\n direction = 's'\n next_room = player.current_room.get_room_in_direction('s')\n\n else:\n direction = test\n\n # If we're heading south and want to go east\n elif next_room.id in my_visited_rooms:\n test = weird_inverse(most_recent)\n next_room = player.current_room.get_room_in_direction(test)\n if next_room != None:\n direction = test\n\n # If both don't work, revert back to the original plan\n else:\n next_room = player.current_room.get_room_in_direction(direction)\n\n else:\n # If next_room != None\n # And next_room not in my_visited_rooms\n direction = most_recent\n\n # If we just went north, try going west, then try going east\n elif most_recent == 'n':\n next_room = player.current_room.get_room_in_direction('w')\n if next_room != None and next_room not in my_visited_rooms:\n direction = 'w'\n else:\n next_room = player.current_room.get_room_in_direction('e')\n if next_room != None:\n direction = 'e'\n else:\n next_room = player.current_room.get_room_in_direction(direction)\n\n # Easiest move, let's go forward\n if next_room.id not in my_visited_rooms:\n player.travel(direction)\n moves.push(direction)\n traversal_path.append(direction)\n most_recent = direction\n\n try:\n rooms[room]\n rooms[room].update({direction : next_room.id})\n except KeyError:\n rooms[room] = {direction : next_room.id}\n\n return traverse(player, rooms, most_recent)\n\n # Go backwards\n elif next_room.id in my_visited_rooms and len(world.rooms) > len(my_visited_rooms) and moves.size() > 0:\n last_move = moves.pop()\n reverse = direction_inverse(last_move)\n player.travel(reverse)\n traversal_path.append(reverse)\n most_recent = reverse\n\n try:\n rooms[room]\n rooms[room].update({reverse : player.current_room.id})\n except KeyError:\n rooms[room] = {reverse : player.current_room.id}\n\n return traverse(player, rooms, most_recent)\n\n else:\n direction = 'e'\n player.travel(direction)\n moves.push(direction)\n traversal_path.append(direction)\n most_recent = direction\n\n try:\n rooms[room]\n rooms[room].update({direction : next_room.id})\n except KeyError:\n rooms[room] = {direction : next_room.id}\n\n direction = 's'\n player.travel(direction)\n moves.push(direction)\n traversal_path.append(direction)\n most_recent = direction\n\n try:\n rooms[room]\n rooms[room].update({direction : next_room.id})\n except KeyError:\n rooms[room] = {direction : next_room.id}\n\n return traverse(player, rooms, most_recent)\n\n # else:\n # return \"You are ending up here\"\n\ndef weird_spot(player, rooms):\n\n from_zero = ['e', 'n', 'n', 'w', 'n', 'n', 'e', 'n']\n\n for step in from_zero:\n room = player.current_room.id\n exits = player.current_room.get_exits()\n my_visited_rooms.add(room)\n rooms_list.append(room)\n\n direction = step\n next_room = player.current_room.get_room_in_direction(direction)\n\n player.travel(direction)\n moves.push(direction)\n traversal_path.append(direction)\n most_recent = direction\n\n try:\n rooms[room]\n rooms[room].update({direction : next_room.id})\n except KeyError:\n rooms[room] = {direction : next_room.id}\n\n return traverse(player, rooms, most_recent)\n\nprint(traverse(player, rooms, most_recent))\nprint(weird_spot(player, rooms))\n\nprint(rooms_list)\nprint(len(traversal_path))\n\n# TRAVERSAL TEST\nvisited_rooms = set()\nplayer.current_room = world.starting_room\nvisited_rooms.add(player.current_room)\n\nfor move in traversal_path:\n player.travel(move)\n visited_rooms.add(player.current_room)\n\nif len(visited_rooms) == len(room_graph):\n print(f\"TESTS PASSED: {len(traversal_path)} moves, {len(visited_rooms)} rooms visited\")\nelse:\n print(\"TESTS FAILED: INCOMPLETE TRAVERSAL\")\n print(f\"{len(room_graph) - len(visited_rooms)} unvisited rooms\")\n\n\n\n#######\n# UNCOMMENT TO WALK AROUND\n#######\nplayer.current_room.print_room_description(player)\nwhile True:\n cmds = input(\"-> \").lower().split(\" \")\n if cmds[0] in [\"n\", \"s\", \"e\", \"w\"]:\n player.travel(cmds[0], True)\n elif cmds[0] == \"q\":\n break\n else:\n print(\"I did not understand that command.\")\n","sub_path":"projects/adventure/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":8497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"297472174","text":"import time\nfrom pytest import raises\nfrom client import create_presence, translate_response, create_message\nfrom errors import UsernameToLongError, ResponseCodeLenError, MandatoryKeyError, ResponseCodeError\n\n\n# МОДУЛЬНЫЕ ТЕСТЫ\ndef test_create_presence():\n # без параметров\n message = create_presence()\n assert message['action'] == \"presence\"\n # берем разницу во времени\n assert abs(message['time'] - time.time()) < 0.1\n assert message[\"user\"][\"account_name\"] == 'Guest'\n # с именем\n message = create_presence('test_user_name')\n assert message[\"user\"][\"account_name\"] == 'test_user_name'\n # неверный тип\n with raises(TypeError):\n create_presence(200)\n with raises(TypeError):\n create_presence(None)\n # Имя пользователя слишком длинное\n with raises(UsernameToLongError):\n create_presence('11111111111111111111111111')\n\n\ndef test_translate_response():\n # неправильный тип\n with raises(TypeError):\n translate_response(100)\n # неверная длина кода ответа\n with raises(ResponseCodeLenError):\n translate_response({'response': '5'})\n # нету ключа response\n with raises(MandatoryKeyError):\n translate_response({'one': 'two'})\n # неверный код ответа\n with raises(ResponseCodeError):\n translate_response({'response': 700})\n # все правильно\n assert translate_response({'response': 200}) == {'response': 200}\n\n\ndef test_create_message():\n msg = create_message('to', 'hello', 'from')\n assert msg['action'] == 'msg'\n # берем разницу во времени\n assert abs(msg['time'] - time.time()) < 0.1\n assert msg['to'] == 'to'\n assert msg['from'] == 'from'\n assert msg['message'] == 'hello'\n\n\n\n\n\n","sub_path":"test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"236433384","text":"import tweepy\n\ndef init():\n consumer_key = 'xxx'\n consumer_secret = 'yyy'\n\n access_token = 'zzz'\n access_token_secret = 'xyz'\n\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n\n api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, retry_count=20, \\\n retry_delay=10, retry_errors=[500, 502, 503, 504])\n\n return api\n","sub_path":"tweepy_conf.py","file_name":"tweepy_conf.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"436215345","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-x86_64/egg/cloud_utils/net_utils/ip_tx.py\n# Compiled at: 2018-01-31 14:44:08\n__doc__ = '\\nSimple IP packet generator/client test tool.\\nProvides very limited support for testing specific IP protocols. Primarily used to test\\nspecific network paths in a cloud or data center traversing firewalls/security groups, nat points,\\netc..\\n'\nfrom os.path import abspath, basename\nfrom random import getrandbits\nimport array, socket, struct, sys, time\nfrom optparse import OptionParser, OptionValueError\nICMP_ECHO_REQUEST = 8\nICMP_EHCO_REPLY = 0\nCHUNK_DATA = 0\nCHUNK_INIT = 1\nCHUNK_HEARTBEAT = 3\nTRACE = 3\nDEBUG = 2\nINFO = 1\nQUIET = 0\nVERBOSE_LVL = INFO\n\ndef get_script_path():\n \"\"\"\n Returns the path to this script\n \"\"\"\n try:\n import inspect\n except ImportError:\n return\n\n return abspath(inspect.stack()[0][1])\n\n\ndef sftp_file(sshconnection, verbose_level=DEBUG):\n \"\"\"\n Uploads this script using the sshconnection's sftp interface to the sshconnection host.\n :param sshconnection: SshConnection object\n :param verbose_level: The level at which this method should log it's output.\n \"\"\"\n script_path = get_script_path()\n script_name = basename(script_path)\n sshconnection.sftp_put(script_path, script_name)\n debug(('Done Copying script:\"{0}\" to \"{1}\"').format(script_name, sshconnection.host), verbose_level)\n return script_name\n\n\ndef debug(msg, level=DEBUG):\n \"\"\"\n Write debug info to stdout filtering on the set verbosity level and prefixing each line\n with a '#' to allow for easy parsing of results from output.\n :param msg: string to print\n :param level: verbosity level of this message\n :return: None\n \"\"\"\n if not VERBOSE_LVL:\n return\n if VERBOSE_LVL >= level:\n for line in str(msg).splitlines():\n sys.stdout.write(('# {0}\\n').format(str(line)))\n sys.stdout.flush()\n\n\ndef get_src(dest):\n \"\"\"\n Attempts to learn the source IP from the outbound interface used to reach the provided\n destination\n :param dest: destination address/ip\n :return: local ip\n \"\"\"\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\n s.connect((dest, 1))\n source_ip = s.getsockname()[0]\n s.close()\n return source_ip\n\n\ndef remote_sender(ssh, dst_addr, port=None, srcport=None, proto=17, count=1, socktimeout=10, timeout=15, data=None, verbose=False, interval=0.1, cb=None, cbargs=None):\n \"\"\"\n Uses the ssh SshConnection obj's sftp interface to transfer this script to the remote\n machine and execute it with the parameters provided. Will return the combined stdout & stderr\n of the remote session.\n\n :param ssh: SshConnection object to run this script\n :param dst_addr: Where to send packets to\n :param port: The destination port of the packets (depending on protocol support)\n :param srcport: The source port to use in the sent packets\n :param proto: The IP protocol number (ie: 1=icmp, 6=tcp, 17=udp, 132=sctp)\n :param count: The number of packets to send\n :param timeout: The max amount of time allowed for the remote command to execute\n :param socktimeout: Time out used for socket operations\n :param data: Optional data to append to the built packet(s)\n :param verbose: Boolean to enable/disable printing of debug info\n :param cb: A method/function to be used as a call back to handle the ssh command's output\n as it is received. Must return type sshconnection.SshCbReturn\n :param cbargs: list of args to be provided to callback cb.\n :return: :raise RuntimeError: If remote command return status != 0\n \"\"\"\n if verbose:\n verbose_level = VERBOSE_LVL\n else:\n verbose_level = DEBUG\n script = sftp_file(ssh, verbose_level=verbose_level)\n cmd = ('python {0} -o {1} -c {2} -d {3} -i {4} -t {5} ').format(script, proto, count, dst_addr, interval, socktimeout)\n if port:\n cmd += (' -p {0} ').format(port)\n if srcport is not None:\n cmd += (' -s {0} ').format(srcport)\n if data is not None:\n cmd += (' -l \"{0}\"').format(data.strip('\"'))\n out = ''\n debug(('CMD: {0}').format(cmd), verbose_level)\n cmddict = ssh.cmd(cmd, listformat=False, timeout=timeout, cb=cb, cbargs=cbargs, verbose=verbose)\n out += cmddict.get('output')\n if cmddict.get('status') != 0:\n raise RuntimeError(('{0}\\n\"{1}\" cmd failed with status:{2}, on host:{3}').format(out, cmd, cmddict.get('status'), ssh.host))\n debug(out, verbose_level)\n return out\n\n\ndef send_ip_packet(destip, proto=4, count=1, interval=0.1, payload=None, timeout=10):\n \"\"\"\n Send a raw ip packet, payload can be used to append to the IP header...\n :param destip: Destination ip\n :param proto: protocol to use, default is 4\n :param payload: optional string buffer to append to IP packet\n \"\"\"\n s = None\n if payload is None:\n payload = 'IP TEST PACKET'\n payload = payload or ''\n try:\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_RAW, proto)\n s.settimeout(timeout)\n for x in xrange(0, count):\n s.sendto(payload, (destip, 0))\n time.sleep(interval)\n\n except socket.error as SE:\n if SE.errno == 1 and 'not permitted' in SE.strerror:\n sys.stderr.write('Permission error creating socket, try with sudo, root...?\\n')\n raise\n\n finally:\n if s:\n s.close()\n\n return\n\n\ndef send_sctp_packet(destip, dstport=101, srcport=100, proto=132, ptype=None, payload=None, sctpobj=None, count=1, interval=0.1, timeout=10):\n \"\"\"\n Send Basic SCTP packets\n\n :param destip: Destination IP to send SCTP packet to\n :param dstport: Destination port to use in the SCTP packet\n :param srcport: Source port to use in the SCTP packet\n :param proto: Protocol number to use, default is 132 for SCTP\n :param ptype: SCTP type, default is 'init' type\n :param payload: optional payload to use in packets (ie data chunk payload)\n :param sctpobj: A pre-built sctpobj to be sent\n \"\"\"\n s = None\n if payload is None:\n payload = 'SCTP TEST PACKET'\n payload = payload or ''\n if ptype is None:\n ptype = CHUNK_INIT\n try:\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_RAW, proto)\n s.setsockopt(socket.SOL_IP, socket.IP_TOS, 2)\n s.settimeout(timeout)\n if not sctpobj:\n sctpobj = SCTP(srcport=srcport, dstport=dstport, ptype=ptype, payload=payload)\n for x in xrange(0, count):\n s.sendto(sctpobj.pack(), (destip, dstport))\n time.sleep(interval)\n\n except socket.error as SE:\n if SE.errno == 1 and 'not permitted' in SE.strerror:\n sys.stderr.write('Permission error creating socket, try with sudo, root...?\\n')\n raise\n\n finally:\n if s:\n s.close()\n\n return\n\n\ndef send_udp_packet(destip, srcport=None, dstport=101, proto=17, payload=None, count=1, interval=0.1, timeout=10):\n \"\"\"\n Send basic UDP packet\n\n :param destip: Destination IP to send UDP packet\n :param srcport: source port to use in the UDP packet, if provided will attempt to bind\n to this port\n :param dstport: destination port to use in the UDP packet\n :param proto: protocol number, default is 17 for UDP\n :param payload: optional payload for this packet\n \"\"\"\n s = None\n if payload is None:\n payload = 'UDP TEST PACKET'\n payload = payload or ''\n try:\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, proto)\n s.settimeout(timeout)\n if srcport is not None:\n s.bind(('', srcport))\n for x in xrange(0, count):\n s.sendto(payload, (destip, dstport))\n time.sleep(interval)\n\n except socket.error as SE:\n if SE.errno == 1 and 'not permitted' in SE.strerror:\n sys.stderr.write('Permission error creating socket, try with sudo, root...?\\n')\n raise\n\n finally:\n if s:\n s.close()\n\n return\n\n\ndef send_tcp_packet(destip, dstport=101, srcport=None, proto=6, payload=None, bufsize=None, count=1, interval=0.1, timeout=10):\n \"\"\"\n Send basic TCP packet\n\n :param destip: Destination IP to send TCP packet\n :param dstport: destination port to use in this TCP packet\n :param srcport: source port to use in this TCP packet. If provided will attempt to bind\n to this port\n :param proto: protocol number, default is 6 for TCP\n :param payload: optional payload for this packet\n :param bufsize: Buffer size for recv() on socket after sending packet\n :return: Any data read on socket after sending the packet\n \"\"\"\n data = ''\n s = None\n if payload is None:\n payload = 'TCP TEST PACKET'\n payload = payload or ''\n try:\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, proto)\n s.settimeout(timeout)\n if srcport is not None:\n s.bind(('', srcport))\n s.connect((destip, dstport))\n for x in xrange(0, count):\n s.send(payload)\n if bufsize:\n data += s.recv(bufsize)\n time.sleep(interval)\n\n except socket.error as SE:\n if SE.errno == 1 and 'not permitted' in SE.strerror:\n sys.stderr.write('Permission error creating socket, try with sudo, root...?\\n')\n raise\n\n finally:\n if s:\n s.close()\n\n return data\n\n\ndef send_icmp_packet(destip, id=1234, seqnum=1, code=0, proto=1, ptype=None, count=1, interval=0.1, payload='ICMP TEST PACKET', timeout=10):\n \"\"\"\n Send basic ICMP packet (note: does not wait for, or validate a response)\n\n :param destip: Destination IP to send ICMP packet to\n :param id: ID, defaults to '1234'\n :param seqnum: Sequence number, defaults to '1'\n :param code: ICMP subtype, default to 0\n :param proto: protocol number, defaults to 1 for ICMP\n :param ptype: ICMP type, defaults to icmp echo request\n :param payload: optional payload\n \"\"\"\n if payload is None:\n payload = 'ICMP TEST PACKET'\n payload = payload or ''\n s = None\n if ptype is None:\n ptype = ICMP_ECHO_REQUEST\n try:\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_RAW, proto)\n s.settimeout(timeout)\n icmp = ICMP(destaddr=destip, id=id, seqnum=seqnum, code=code, ptype=ptype, payload=payload)\n for x in xrange(0, count):\n s.sendto(icmp.pack(), (destip, 0))\n time.sleep(interval)\n\n except socket.error as SE:\n if SE.errno == 1 and 'not permitted' in SE.strerror:\n sys.stderr.write('Permission error creating socket, try with sudo, root...?\\n')\n raise\n\n finally:\n if s:\n s.close()\n\n return\n\n\ndef send_packet(destip, proto, srcport=None, dstport=345, ptype=None, payload=None, count=1, interval=0.1, timeout=10, verbose=DEBUG):\n \"\"\"\n Wrapper to sends packets of varying types\n :param destip: Destination IP to send packet to\n :param proto: IP protocol number (ie:1=icmp, 6=tcp, 17=udp, 132=sctp)\n :param srcport: Source port to use in packet (Depends on protocol)\n :param dstport: Destination port to use in packet (Depends on protocol)\n :param ptype: Packet type (if protocol supports subtypes)\n :param payload: Optional payload to send with packet\n :param count: Number of packets to send\n :param verbose: Sets the level info will be logged at\n \"\"\"\n debug(('send_packet: destip:{0}, dstport:{1}, proto:{2}, ptype:{3}, count:{4}, interval:{5}').format(destip, dstport, proto, ptype, count, interval), level=verbose)\n if proto in (1, 'icmp'):\n send_icmp_packet(destip=destip, ptype=ptype, payload=payload, count=count, interval=interval, timeout=timeout)\n elif proto in (6, 'tcp'):\n send_tcp_packet(destip=destip, srcport=srcport, dstport=dstport, payload=payload, count=count, interval=interval, timeout=timeout)\n elif proto in (17, 'udp'):\n send_udp_packet(destip=destip, srcport=srcport, dstport=dstport, payload=payload, count=count, interval=interval, timeout=timeout)\n elif proto in (132, 'sctp'):\n send_sctp_packet(destip=destip, srcport=srcport, ptype=ptype, dstport=dstport, payload=payload, count=count, interval=interval, timeout=timeout)\n else:\n send_ip_packet(destip=destip, proto=proto, payload=payload, count=count, interval=interval, timeout=timeout)\n\n\nclass ICMP(object):\n\n def __init__(self, destaddr, id=1234, seqnum=1, code=0, ptype=None, payload=None):\n self.destaddr = destaddr\n if payload is None:\n payload = 'ICMP TEST PACKET'\n self.payload = payload or ''\n self.icmptype = ptype or ICMP_ECHO_REQUEST\n self.id = id\n self.code = code\n self.seqnum = seqnum\n return\n\n def pack(self):\n tmp_checksum = 0\n header = struct.pack('bbHHh', self.icmptype, self.code, tmp_checksum, self.id, self.seqnum)\n fin_checksum = checksum(header + self.payload)\n header = struct.pack('bbHHh', self.icmptype, self.code, socket.htons(fin_checksum), self.id, self.seqnum)\n packet = header + self.payload\n return packet\n\n\nclass InitChunk(object):\n\n def __init__(self, tag=None, a_rwnd=62464, outstreams=10, instreams=65535, tsn=None, param_data=None):\n self.tag = tag or getrandbits(32) or 3\n self.a_rwnd = a_rwnd\n self.outstreams = outstreams or 1\n self.instreams = instreams or 1\n self.tsn = tsn or getrandbits(32) or 4\n if param_data is None:\n param_data = ''\n suppaddrtypes = SctpSupportedAddrTypesParam()\n param_data += suppaddrtypes.pack()\n ecn = SctpEcnParam()\n param_data += ecn.pack()\n fwdtsn = SctpFwdTsnSupportParam()\n param_data += fwdtsn.pack()\n self.param_data = param_data\n return\n\n def pack(self):\n packet = struct.pack('!IIHHI', self.tag, self.a_rwnd, self.outstreams, self.instreams, self.tsn)\n if self.param_data:\n packet += self.param_data\n return packet\n\n\nclass SctpIPv4Param(object):\n\n def __init__(self, type=5, length=8, ipv4addr=None):\n self.type = type\n self.length = length\n self.addr = ipv4addr\n\n def pack(self):\n packet = struct.pack('!HHI', self.type, self.length, self.addr)\n return packet\n\n\nclass SctpSupportedAddrTypesParam(object):\n\n def __init__(self, ptype=12, addr_types=None):\n ipv4 = 5\n if addr_types is None:\n addr_types = [\n ipv4]\n if not isinstance(addr_types, list):\n addr_types = [\n addr_types]\n self.addr_types = addr_types\n self.ptype = 12\n self.length = 4 + 2 * len(self.addr_types)\n return\n\n def pack(self):\n fmt = '!HH'\n contents = [self.ptype, self.length]\n for atype in self.addr_types:\n fmt += 'H'\n contents.append(atype)\n\n contents = tuple(contents)\n packet = struct.pack(fmt, *contents)\n if len(self.addr_types) % 2:\n packet += struct.pack('H', 0)\n return packet\n\n\nclass SctpEcnParam(object):\n\n def __init__(self, ptype=32768):\n self.ptype = ptype\n self.length = 4\n\n def pack(self):\n return struct.pack('!HH', self.ptype, self.length)\n\n\nclass SctpFwdTsnSupportParam(object):\n\n def __init__(self, ptype=49152):\n self.ptype = ptype\n self.length = 4\n\n def pack(self):\n return struct.pack('!HH', self.ptype, self.length)\n\n\nclass DataChunk(object):\n\n def __init__(self, tsn=1, stream_id=12345, stream_seq=54321, payload_proto=0, payload=None):\n if payload is None:\n payload = 'TEST SCTP DATA CHUNK'\n self.payload = payload\n self.tsn = tsn\n self.stream_id = stream_id\n self.stream_seq = stream_seq\n self.payload_proto = payload_proto\n return\n\n @property\n def length(self):\n return 12 + len(self.payload)\n\n def pack(self):\n packet = struct.pack('!iHHi', self.tsn, self.stream_id, self.stream_seq, self.payload_proto)\n packet += self.payload\n return packet\n\n\nclass HeartBeatChunk(object):\n\n def __init__(self, parameter=1, payload=None):\n self.parameter = parameter\n if payload is None:\n payload = str(getrandbits(64))\n self.hb_info = payload\n self.hb_info_length = 4 + len(payload)\n return\n\n def pack(self):\n chunk = struct.pack('!HH', self.parameter, self.hb_info_length)\n chunk += self.hb_info\n return chunk\n\n\nclass ChunkHdr(object):\n\n def __init__(self, chunktype=None, flags=0, payload=None, chunk=None):\n if chunktype is None:\n chunktype = 1\n self.chunktype = chunktype\n self.chunkflags = flags\n if chunk:\n self.chunkobj = chunk\n elif chunktype == 0:\n self.chunkobj = DataChunk(payload=payload)\n elif chunktype == 1:\n self.chunkobj = InitChunk()\n elif chunktype == 4:\n self.chunkobj = HeartBeatChunk(payload=payload)\n self.chunk_data = self.chunkobj.pack()\n self.chunklength = 4\n self.chunklength = 4 + len(self.chunk_data)\n return\n\n def pack(self):\n chunk = struct.pack('!bbH', self.chunktype, self.chunkflags, self.chunklength)\n packet = chunk + self.chunk_data\n return packet\n\n\nclass SCTP(object):\n \"\"\"\n Chunk Types\n 0 DATA Payload data\n 1 INIT Initiation\n 2 INIT ACK initiation acknowledgement\n 3 SACK Selective acknowledgement\n 4 HEARTBEAT Heartbeat request\n 5 HEARTBEAT ACK Heartbeat acknowledgement\n 6 ABORT Abort\n 7 SHUTDOWN Shutdown\n 8 SHUTDOWN ACK Shutdown acknowledgement\n 9 ERROR Operation error\n 10 COOKIE ECHO State cookie\n 11 COOKIE ACK Cookie acknowledgement\n 12 ECNE Explicit congestion notification echo (reserved)\n 13 CWR Congestion window reduced (reserved)\n 14 SHUTDOWN COMPLETE\n\n Chunk Flags\n # I - SACK chunk should be sent back without delay.\n # U - If set, this indicates this data is an unordered chunk and the stream sequence number\n is invalid. If an unordered chunk is fragmented then each fragment has this flag set.\n # B - If set, this marks the beginning fragment. An unfragmented chunk has this flag set.\n # E - If set, this marks the end fragment. An unfragmented chunk has this flag set\n \"\"\"\n\n def __init__(self, srcport, dstport, tag=None, ptype=None, payload=None, chunk=None):\n self.src = srcport\n self.dst = dstport\n self.checksum = 0\n if ptype is None:\n ptype = CHUNK_INIT\n tag = 0\n if tag is None:\n if ptype == CHUNK_INIT:\n tag = 0\n else:\n tag = getrandbits(16)\n self.tag = tag\n chunk = chunk or ChunkHdr(chunktype=ptype, payload=payload)\n self.chunk = chunk.pack()\n return\n\n def pack(self, src=None, dst=None, tag=None, do_checksum=True):\n src = src or self.src\n dst = dst or self.dst\n verification_tag = tag or self.tag\n packet = struct.pack('!HHII', src, dst, verification_tag, 0)\n chunk = self.chunk\n if not do_checksum:\n packet += chunk\n return packet\n pktchecksum = cksum(packet + chunk)\n packet = struct.pack('!HHII', src, dst, verification_tag, pktchecksum)\n packet += chunk\n return packet\n\n\ndef checksum(source_string):\n \"\"\"\n From: https://github.com/samuel/python-ping\n Copyright (c) Matthew Dixon Cowles, .\n Distributable under the terms of the GNU General Public License\n version 2. Provided with no warranties of any sort.\n \"\"\"\n sum = 0\n count_to = len(source_string) / 2 * 2\n count = 0\n while count < count_to:\n this_val = ord(source_string[(count + 1)]) * 256 + ord(source_string[count])\n sum = sum + this_val\n sum = sum & 4294967295\n count = count + 2\n\n if count_to < len(source_string):\n sum = sum + ord(source_string[(len(source_string) - 1)])\n sum = sum & 4294967295\n sum = (sum >> 16) + (sum & 65535)\n sum = sum + (sum >> 16)\n answer = ~sum\n answer = answer & 65535\n answer = answer >> 8 | answer << 8 & 65280\n return answer\n\n\ncrc32c_table = (0, 4067132163, 3778769143, 324072436, 3348797215, 904991772, 648144872,\n 3570033899, 2329499855, 2024987596, 1809983544, 2575936315, 1296289744,\n 3207089363, 2893594407, 1578318884, 274646895, 3795141740, 4049975192,\n 51262619, 3619967088, 632279923, 922689671, 3298075524, 2592579488,\n 1760304291, 2075979607, 2312596564, 1562183871, 2943781820, 3156637768,\n 1313733451, 549293790, 3537243613, 3246849577, 871202090, 3878099393,\n 357341890, 102525238, 4101499445, 2858735121, 1477399826, 1264559846,\n 3107202533, 1845379342, 2677391885, 2361733625, 2125378298, 820201905,\n 3263744690, 3520608582, 598981189, 4151959214, 85089709, 373468761,\n 3827903834, 3124367742, 1213305469, 1526817161, 2842354314, 2107672161,\n 2412447074, 2627466902, 1861252501, 1098587580, 3004210879, 2688576843,\n 1378610760, 2262928035, 1955203488, 1742404180, 2511436119, 3416409459,\n 969524848, 714683780, 3639785095, 205050476, 4266873199, 3976438427,\n 526918040, 1361435347, 2739821008, 2954799652, 1114974503, 2529119692,\n 1691668175, 2005155131, 2247081528, 3690758684, 697762079, 986182379,\n 3366744552, 476452099, 3993867776, 4250756596, 255256311, 1640403810,\n 2477592673, 2164122517, 1922457750, 2791048317, 1412925310, 1197962378,\n 3037525897, 3944729517, 427051182, 170179418, 4165941337, 746937522,\n 3740196785, 3451792453, 1070968646, 1905808397, 2213795598, 2426610938,\n 1657317369, 3053634322, 1147748369, 1463399397, 2773627110, 4215344322,\n 153784257, 444234805, 3893493558, 1021025245, 3467647198, 3722505002,\n 797665321, 2197175160, 1889384571, 1674398607, 2443626636, 1164749927,\n 3070701412, 2757221520, 1446797203, 137323447, 4198817972, 3910406976,\n 461344835, 3484808360, 1037989803, 781091935, 3705997148, 2460548119,\n 1623424788, 1939049696, 2180517859, 1429367560, 2807687179, 3020495871,\n 1180866812, 410100952, 3927582683, 4182430767, 186734380, 3756733383,\n 763408580, 1053836080, 3434856499, 2722870694, 1344288421, 1131464017,\n 2971354706, 1708204729, 2545590714, 2229949006, 1988219213, 680717673,\n 3673779818, 3383336350, 1002577565, 4010310262, 493091189, 238226049,\n 4233660802, 2987750089, 1082061258, 1395524158, 2705686845, 1972364758,\n 2279892693, 2494862625, 1725896226, 952904198, 3399985413, 3656866545,\n 731699698, 4283874585, 222117402, 510512622, 3959836397, 3280807620,\n 837199303, 582374963, 3504198960, 68661723, 4135334616, 3844915500,\n 390545967, 1230274059, 3141532936, 2825850620, 1510247935, 2395924756,\n 2091215383, 1878366691, 2644384480, 3553878443, 565732008, 854102364,\n 3229815391, 340358836, 3861050807, 4117890627, 119113024, 1493875044,\n 2875275879, 3090270611, 1247431312, 2660249211, 1828433272, 2141937292,\n 2378227087, 3811616794, 291187481, 34330861, 4032846830, 615137029,\n 3603020806, 3314634738, 939183345, 1776939221, 2609017814, 2295496738,\n 2058945313, 2926798794, 1545135305, 1330124605, 3173225534, 4084100981,\n 17165430, 307568514, 3762199681, 888469610, 3332340585, 3587147933,\n 665062302, 2042050490, 2346497209, 2559330125, 1793573966, 3190661285,\n 1279665062, 1595330642, 2910671697)\n\ndef add(crc, buf):\n buf = array.array('B', buf)\n for b in buf:\n crc = crc >> 8 ^ crc32c_table[((crc ^ b) & 255)]\n\n return crc\n\n\ndef done(crc):\n tmp = ~crc & 4294967295\n b0 = tmp & 255\n b1 = tmp >> 8 & 255\n b2 = tmp >> 16 & 255\n b3 = tmp >> 24 & 255\n crc = b0 << 24 | b1 << 16 | b2 << 8 | b3\n return crc\n\n\ndef cksum(buf):\n \"\"\"Return computed CRC-32c checksum.\"\"\"\n return done(add(4294967295, buf))\n\n\nif __name__ == '__main__':\n parser = OptionParser()\n parser.add_option('-p', '--dstport', dest='dstport', type='int', default=101, help='Destination Port', metavar='PORT')\n parser.add_option('-s', '--srcport', dest='srcport', type='int', default=100, help='Source Port', metavar='PORT')\n parser.add_option('-c', '--count', dest='count', type='int', default=1, help='Number of packets to send', metavar='COUNT')\n parser.add_option('-i', '--interval', dest='interval', type='float', default=0.1, help=\"Time interval between sending packets, default='.1'\", metavar='INTERVAL')\n parser.add_option('-d', '--dst', dest='destip', default=None, help='Destination ip', metavar='IP')\n parser.add_option('-o', '--proto', dest='proto', type='int', default=17, help='Protocol number(Examples: 1:icmp, 6:tcp, 17:udp, 132:sctp), default:17', metavar='PROTOCOL')\n parser.add_option('-l', '--payload', dest='payload', default=None, help='Chunk, data, payload, etc', metavar='DATA')\n parser.add_option('-v', '--verbose', dest='verbose', type='int', default=DEBUG, help='Verbose level, 0=quiet, 1=info, 2=debug, 3=trace. Default=1')\n parser.add_option('-t', '--socktimeout', dest='socktimeout', type='float', default=10, help='Socket timeout in seconds', metavar='TIMEOUT')\n options, args = parser.parse_args()\n if not options.destip:\n raise OptionValueError(\"'-d / --dst' for destination IP/Addr must be provided\")\n VERBOSE_LVL = options.verbose\n destip = options.destip\n proto = options.proto\n srcport = options.srcport\n interval = options.interval\n socktimeout = options.socktimeout\n if srcport is not None:\n srcport = int(srcport)\n dstport = int(options.dstport)\n payload = options.payload\n count = options.count\n send_packet(destip=destip, proto=proto, srcport=srcport, dstport=dstport, payload=payload, count=count, interval=interval, timeout=socktimeout)","sub_path":"pycfiles/adminbot-0.1.1.tar/ip_tx.py","file_name":"ip_tx.py","file_ext":"py","file_size_in_byte":27025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"75452908","text":"MOVED_LEFT = 'MOVED_LEFT'\nMOVED_RIGHT = 'MOVED_RIGHT'\nMOVED_UP = 'MOVED_UP'\nMOVED_DOWN = 'MOVED_DOWN'\nWAITED = 'WAITED'\nINVALID_ACTION = 'INVALID_ACTION'\n\nBOMB_DROPPED = 'BOMB_DROPPED'\nBOMB_EXPLODED = 'BOMB_EXPLODED'\n\nCRATE_DESTROYED = 'CRATE_DESTROYED'\nCOIN_FOUND = 'COIN_FOUND'\nCOIN_COLLECTED = 'COIN_COLLECTED'\n\nKILLED_OPPONENT = 'KILLED_OPPONENT'\nKILLED_SELF = 'KILLED_SELF'\n\nGOT_KILLED = 'GOT_KILLED'\nOPPONENT_ELIMINATED = 'OPPONENT_ELIMINATED'\nSURVIVED_ROUND = 'SURVIVED_ROUND'\n\n\n#Custom\nLOOPED = 'LOOPED'\nLOOP_FREE = 'LOOP_FREE'\nCLOSER_TO_TARGET = 'CLOSER_TO_TARGET'\nFARTHER_FROM_TARGET = 'FARTHER_FROM_TARGET'\nBOMB_LOOP = 'BOMB_LOOP'\nIN_DANGER = 'IN_DANGER'\nMOVED_OUT_OF_DANGER = 'MOVED_OUT_OF_DANGER'\nMOVED_INTO_DANGER = 'MOVED_INTO_DANGER'\nTRAPPED = 'TRAPPED'\nBOMB_CLOSE_TO_TARGET = 'BOMB_CLOSE_TO_TARGET'\nBOMB_OTHER_DANGER = 'BOMB_OTHER_DANGER'\n","sub_path":"events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"84568173","text":"sim_comment = \"base mixed case\"\n\ninfo = glooper.SimpleInfoGenerator( rng.UniformGenerator() )\n\nN_runs = 10\nN_steps = 20\n\nagt_gen_cfg_file = os.path.join(cwd,\"agent.mixed_test.cfg.lua\")\n\nsim_reg_filename = \"test_registry.csv\"\n","sub_path":"cfg/multibatch/test_batch/t06_mixed_test.sim.cfg.py","file_name":"t06_mixed_test.sim.cfg.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"278530721","text":"#!/usr/bin/env python\nimport io\nimport os\nimport re\n\nfrom setuptools import setup, find_packages\n\nRE_REQUIREMENT = re.compile(r'^\\s*-r\\s*(?P.*)$')\nRE_BADGE = re.compile(r'^\\[\\!\\[(?P[^\\]]+)\\]\\[(?P[^\\]]+)\\]\\]\\[(?P[^\\]]+)\\]$', re.M)\n\nBADGES_TO_KEEP = ['gitter-badge', 'readthedocs-badge']\n\n\ndef md(filename):\n '''\n Load .md (markdown) file and sanitize it for PyPI.\n Remove unsupported github tags:\n - code-block directive\n - travis ci build badges\n '''\n content = io.open(filename).read()\n\n for match in RE_BADGE.finditer(content):\n if match.group('badge') not in BADGES_TO_KEEP:\n content = content.replace(match.group(0), '')\n return content\n\n\nlong_description = '\\n'.join((\n md('README.md'),\n md('CHANGELOG.md'),\n ''\n))\n\n\ndef pip(filename):\n \"\"\"Parse pip reqs file and transform it to setuptools requirements.\"\"\"\n requirements = []\n for line in open(os.path.join('requirements', filename)):\n line = line.strip()\n if not line or '://' in line or line.startswith('#'):\n continue\n match = RE_REQUIREMENT.match(line)\n if match:\n requirements.extend(pip(match.group('filename')))\n else:\n requirements.append(line)\n return requirements\n\n\ninstall_requires = pip('install.pip')\ntests_require = pip('test.pip')\n\nsetup(\n name='csvapi',\n python_requires='>=3.6.1',\n description='An instant JSON API for your CSV',\n long_description=long_description,\n long_description_content_type='text/markdown',\n author='Opendata Team',\n author_email='opendatateam@data.gouv.fr',\n version='0.0.9.dev',\n license='MIT',\n url='https://github.com/opendatateam/csvapi',\n packages=find_packages(),\n package_data={'csvapi': []},\n include_package_data=True,\n install_requires=install_requires,\n tests_require=tests_require,\n extras_require={\n 'test': tests_require,\n },\n entry_points='''\n [console_scripts]\n csvapi=csvapi.cli:cli\n ''',\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: Implementation :: CPython',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"312465284","text":"import json, sys\nfrom pathlib import Path\nfrom transformers import AutoTokenizer\nimport numpy as np\nimport torch\nimport config\n\n\npath = Path('')\n\ndef load_model():\n model = torch.load(path/'model')\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n model.to(device)\n model.eval();\n return model\n\ndef encode(sequence):\n return tokenizer.encode_plus(\n sequence,\n add_special_tokens=True,\n max_length=512,\n return_token_type_ids=False,\n padding=True,\n return_attention_mask=True,\n return_tensors='pt',\n truncation=True\n )\n \ndef eval(text):\n # This is where you call your model to get the number of stars output\n encoded = encode(text)\n with torch.no_grad():\n output = model(encoded['input_ids'].cpu(), token_type_ids=None, attention_mask=encoded['attention_mask'].cpu())[0]\n pred_flat = np.argmax(output, axis=1).flatten()\n sig_factor = torch.sigmoid(output) / torch.sigmoid(output).sum()\n return pred_flat.item() + 1\n \ntokenizer = AutoTokenizer.from_pretrained(config.PRE_TRAINED_MODEL_NAME)\nmodel = load_model()\n\nif len(sys.argv) > 1:\n validation_file = sys.argv[1]\n with open(\"output.jsonl\", \"w\") as fw:\n with open(validation_file, \"r\") as fr:\n for line in fr:\n review = json.loads(line)\n fw.write(json.dumps({\"review_id\": review['review_id'], \"predicted_stars\": eval(review['text'])})+\"\\n\")\n print(\"Output prediction file written\")\nelse:\n print(\"No validation file given\")","sub_path":"t-a/test_submission.py","file_name":"test_submission.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"517818308","text":"import json\nimport os\nfrom glob import glob\nfrom pathlib import Path\n\nimport numpy as np\nimport nibabel as nib\n\nfrom fetal_net.prediction import run_validation_cases\nimport argparse\n\nfrom fetal_net.utils.cut_relevant_areas import find_bounding_box, cut_bounding_box\n\nimport tensorflow as tf\nfrom keras.backend.tensorflow_backend import set_session\n\n\ndef main(config, split='test', overlap_factor=1, config2=None, use_augmentations=False, scale_xy=None):\n prediction_dir = os.path.abspath(os.path.join(config['base_dir'], 'predictions', split))\n\n indices_file = {\n \"test\": config[\"test_file\"],\n \"val\": config[\"validation_file\"],\n \"train\": config[\"training_file\"]\n }[split]\n run_validation_cases(validation_keys_file=indices_file,\n model_file=config[\"model_file\"],\n training_modalities=config[\"training_modalities\"],\n hdf5_file=config[\"data_file\"],\n output_dir=prediction_dir,\n overlap_factor=overlap_factor,\n patch_shape=config[\"patch_shape\"] + [config[\"patch_depth\"]],\n prev_truth_index=config[\"prev_truth_index\"],\n prev_truth_size=config[\"prev_truth_size\"],\n pred_index=config[\"pred_index\"],\n pred_size=config[\"pred_size\"],\n use_augmentations=use_augmentations,\n scale_xy=scale_xy,\n resolution_file=config[\"resolution_dict_file\"],\n is3d=config[\"3D\"])\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--config_dir\", help=\"specifies config dir path\",\n type=str, required=False, default='../../../../../datadrive/configs/trainset_experiment_2_val_20_train_0_iter')\n #type=str, required=False, default='../../../../../datadrive/configs/trainset_experiment_0_val_20_train_0_iter')\n parser.add_argument(\"--split\", help=\"What split to predict on? (test/val)\",\n type=str, default='test')\n parser.add_argument(\"--overlap_factor\", help=\"specifies overlap between prediction patches\",\n type=float, default=0.8) # 0.9\n parser.add_argument(\"--use_augmentations\", help=\"specifies whether to predict on augmentations\",\n type=bool, default=False) # False\n parser.add_argument(\"--scale_xy\", help=\"specifies whether to rescale xy to 1.56x1.56\",\n action=\"store_true\") \n opts = parser.parse_args()\n\n with open(os.path.join(opts.config_dir, 'config.json')) as f:\n config = json.load(f)\n\n config_gpu = tf.ConfigProto()\n config_gpu.gpu_options.allow_growth = True\n sess = tf.Session(config=config_gpu)\n set_session(sess)\n\n main(config, opts.split, opts.overlap_factor, use_augmentations=opts.use_augmentations, scale_xy=opts.scale_xy)\n","sub_path":"brats/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"371261014","text":"# !/usr/bin/env python\n# -*- coding:utf-8 -*-\n# author:Ocean-yyl\n# datetime:2020-04-12 17:47\n# software: PyCharm\ndef get_attr():\n\tAPP_ID = '17505989'\n\tAPI_KEY = '5MySyBbvD3jup0QwUikW3vDD'\n\tSECRET_KEY = 'bz3BHRXLCCtguIG4eOaOHfLVPhf1rZqY'\n\treturn APP_ID,API_KEY,SECRET_KEY","sub_path":"《尹成python爬虫教程》学习笔记/8,数据AI/2,百度API实验/my_api.py","file_name":"my_api.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"49355376","text":"import shapefile\nfrom pyproj import Proj, transform\nimport pandas as pd\nfrom shapely.geometry import Point, Polygon\nimport sys\nimport accessDB as db\nimport os\n\n# load in maps\nald = shapefile.Reader('../mapping/ald2016/alderman')\nnbh = shapefile.Reader('../mapping/hoods/neighborhood')\npol = shapefile.Reader('../mapping/poldist/poldist')\nward = shapefile.Reader('../mapping/wards/ward')\ncity = shapefile.Reader('../mapping/corp/citylimit')\n\ndef getIn(sf, df, sfName):\n # create a new dataframe with just the coordinates\n coords = df[['Latitude', 'Longitude', 'Nature of Call']]\n coords = coords.dropna()\n # some empty are missed I guess\n coords = coords[coords['Latitude'] != '']\n coords = coords[coords['Longitude'] != '']\n\n # loop through shapes\n for i,shape in enumerate(sf.shapes()):\n points = []\n\n # loop through points of shape\n for point in shape.points:\n # parse points\n coord = [float('%.3f' % coord) for coord in point]\n # convert points\n x, y = transform(inProj, outProj, coord[0], coord[1])\n points.append((x, y))\n\n # make a polygon out of the points\n poly = Polygon(points)\n\n # find the district, ward, etc that a point is in\n for index, row in coords.iterrows():\n point = Point(row['Longitude'], row['Latitude'])\n if poly.contains(point):\n coords.loc[index, sfName] = i\n\n return coords\n\n# converter for coordinates\ninProj = Proj(init='EPSG:32054', preserve_units=True) # NAD27 Wisconsin South\noutProj = Proj(proj='latlong', datum='WGS84', ellps='WGS84') # Latitude and Longitude\n\nallCalls = db.filter(doGeoLoc=True)\n\n# remove duplicate calls\nallCalls = allCalls.drop_duplicates(subset='Call Number')#[0:1000]\n\n# use top 25 calls\nnatures = ['All'] + list(allCalls['Nature of Call'].value_counts()[:25].index\n)\n# get all regions\ncoords = getIn(ald, allCalls, 'Region')\ncounts = coords['Region'].value_counts()\n\n# make header of table\ncolumns = ['Nature'] + list(coords['Region'].unique()) + ['Total']\nprint(columns)\n\ncountTab = []\n\ni = 0\n# for every nature\nfor nature in natures:\n # gather all calls\n if nature == 'All':\n selection = coords\n else:\n selection = coords[coords['Nature of Call'] == nature]\n\n # compute numbers for nature\n counts = selection['Region'].value_counts()\n countTab.append([nature] + ([0] * (len(columns)-1)))\n for idx,count in counts.iteritems():\n if idx in columns:\n countTab[i][columns.index(idx)] = count\n countTab[i][-1] = len(selection)\n\n print(countTab[i])\n i += 1\n\n# write table to file\nwith open('nature-region-counts.csv', 'w') as f:\n f.write(','.join(str(x) for x in columns) + '\\n')\n for row in countTab:\n f.write(','.join(str(x) for x in row) + '\\n')\n","sub_path":"parsing/super-counter.py","file_name":"super-counter.py","file_ext":"py","file_size_in_byte":2843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"373835145","text":"from typing import Union\nimport numpy as np\nfrom contextlib import contextmanager\nimport fast_krig as fk\nfrom fast_krig.utils import WorkForce\nimport time\n\n\nclass GridConstructor:\n \"\"\"This is the Grid constructor class. This class is meant to be used as an\n in constructor for another class. Either the Grid class or the Krig class.\n The reason this is not meant to be used as a standalone is because it only contains\n the methods required to fill up a grid given logs and meta data.\n\n Additional methods and subclasses of numpy will contain the methods to krig the grid.\n \"\"\"\n\n def __init__(\n self,\n logs: list,\n z_range: Union[tuple, list] = [],\n x_range: Union[tuple, list] = [],\n y_range: Union[tuple, list] = [],\n z_delta: float = 1,\n xy_delta: float = 100,\n auto_range: bool = True,\n stream=None,\n n_samples=500,\n ):\n \"\"\"[summary]\n\n Args:\n logs (list): A list of the Logs that are used to compose this grid. The Logs should have\n all the required meta data to place them within this grid.\n z_range (Union[tuple, list], optional): The range of z-values to create the grid for.\n Small z-ranges will make the grid smaller, and therefore faster to krig. If left empty,\n the grid will be auto-sized to match the data. Defaults to [].\n x_range (Union[tuple, list], optional): The range of x-values to create the grid for.\n Small x-ranges will make the grid smaller, and therefore faster to krig. If left empty,\n the grid will be auto-sized to match the data. Defaults to [].\n y_range (Union[tuple, list], optional): The range of y-values to create the grid for.\n Small y-ranges will make the grid smaller, and therefore faster to krig. If left empty,\n the grid will be auto-sized to match the data. Defaults to [].\n z_delta (float, optional): The size in the z-dimension of the grid cells. Defaults to 1.\n xy_delta (float, optional): The size in the xy-dimensions of the grid cells. Defaults to 100.\n auto_range (bool, optional): If True, then the range of the grid will be automatically determined.\n Defaults to True.\n stream ([type], optional): The stream on the logs to use to fill the grid. Defaults to None.\n n_samples (int, optional): The number of samples to take in each krig step. Defaults to 500.\n \"\"\"\n self.logger = fk.config.logger.getChild(self.__class__.__name__)\n self.logs = logs\n self.xy_delta = xy_delta\n self.z_delta = z_delta\n self.stream = stream\n if auto_range:\n self._get_auto_xy_range()\n else:\n self.x_range = x_range\n self.y_range = y_range\n self.z_range = z_range or self._get_auto_z_range()\n self._make_grid()\n self._fill_grid()\n self.n_samples = n_samples\n self.sample_size = int(\n (self.grid.size - np.stack(self.fill_z).size) / self.n_samples\n )\n self.filled = ~np.isnan(self.grid).ravel()\n self.empty_coos = np.argwhere(~self.filled).T.squeeze()\n self.filled_coos = np.argwhere(self.filled).T.squeeze()\n self.coos = np.argwhere(self.grid)\n\n def _get_auto_xy_range(self):\n \"\"\"This method will calculate the xy-range of the grid automatically given the data.\"\"\"\n x_coords, y_coords = zip(*[(log.x_coord, log.y_coord) for log in self.logs])\n y_range = (np.max(y_coords) - np.min(y_coords)) * 1.2\n x_range = (np.max(x_coords) - np.min(x_coords)) * 1.2\n self.center = (np.mean(x_coords), np.mean(y_coords))\n self.y_range = (self.center[1] - y_range / 2, self.center[1] + y_range / 2)\n self.x_range = (self.center[0] - x_range / 2, self.center[0] + x_range / 2)\n\n def _get_auto_z_range(self):\n \"\"\"This method will calculate the z-range of the grid automatically given the data.\n\n Returns:\n tuple: The (min, max) of the z range for the grid.\n \"\"\"\n indices = np.stack([log.index for log in self.logs]).T\n return (np.min(indices) - 1, np.max(indices) + 1)\n\n def _make_grid(self):\n \"\"\"Makes the empty grid given the ranges and cell sizes.\n Initializes a zero grid, then fills with NaNs. This method\n creates a new attribute called grid.\n \"\"\"\n self.z = np.arange(self.z_range[0], self.z_range[1], self.z_delta)\n self.x = np.arange(self.x_range[0], self.x_range[1], self.xy_delta)\n self.y = np.arange(self.y_range[0], self.y_range[1], self.xy_delta)\n self.grid = np.empty(tuple(map(len, [self.x, self.y, self.z])))\n self.grid[:] = np.nan\n\n def _get_filled_slice(self):\n \"\"\"Gets the subset of the grid that is currently filled.\n\n Returns:\n tuple: x, y, z components of the filled cells.\n \"\"\"\n return tuple(\n zip(\n *[\n (np.tile(x, (len(z))), np.tile(y, (len(z))), z)\n for x, y, z in zip(self.fill_x, self.fill_y, self.fill_z)\n ]\n )\n )\n\n def _get_filled_xyz(self):\n \"\"\"Gets the subset of the grid that is currently filled, then returns array of coords.\n\n Returns:\n np.array: the coordinates of the filled cells in an array.\n \"\"\"\n return np.vstack(\n [np.stack(list(zip(x, y, z))) for x, y, z in zip(*self._get_filled_slice())]\n )\n\n def _fill_grid(self):\n \"\"\"Fills the grid with the log data after all other properties have been determined.\"\"\"\n self.fill_x, self.fill_y, self.fill_z, self.log_z = zip(\n *[\n (\n np.abs(self.x - log.x_coord).argmin(),\n np.abs(self.y - log.y_coord).argmin(),\n np.where((self.z >= log.index.min()) & (self.z <= log.index.max()))[\n 0\n ],\n np.where((log.index >= self.z.min()) & (log.index <= self.z.max())),\n )\n for log in self.logs\n ]\n )\n self.grid[self._get_filled_slice()] = np.stack(\n [\n getattr(log, self.stream)[log_z]\n for log, log_z in zip(self.logs, self.log_z)\n ]\n )\n\n\nclass Grid(np.ndarray):\n \"\"\"The main Grid class, a subclass of np.ndarray. This class contains all the logic to perform sampled kriging on a given grid.\n This class uses the grid constructor to generate a grid, then cast that object as a view into a numpy array.\n The resulting numpy array is then updated with the other pertinent metadata of the grid. This is handled\n through the __new__ method, the __array_finalize__ method, the __reduce__ method, and the __setstate__ method.\n\n The __new__ method handles the initial creation of the grid, which is how the GridConstructor object can be cast\n as a view.\n\n The __array_finalize__ methodd is called any time the array is created, copied, or sliced into a new view.\n In order to maintain properties through copies and view casting, this method needs to be overridden.\n\n The __reduce__ method is responsible for pickling the array object. By overriding this method, the extra\n attributes of the grid can be added to the pickled state, and carried to subprocesses.\n\n The __setstate__ method carries out th unpickling operation. Overriding this method allows us to take\n advantage of our custom pickled state, and add back in our extra properties into the unpickled object.\n \"\"\"\n\n def __new__(cls, *args, **kwargs):\n \"\"\"Create the grid and subclass it into a numpy view. Then add extra parameters.\n\n Returns:\n Object: The new subclassed grid object.\n \"\"\"\n grid = GridConstructor(*args, **kwargs) # Make the grid\n obj = np.asarray(grid.grid).view(cls)\n for k, v in grid.__dict__.items():\n if k != \"grid\":\n setattr(obj, k, v)\n return obj\n\n def __array_finalize__(self, obj):\n \"\"\"Maintain object attributes accross copies and viewcasting of array.\n\n Args:\n obj (Object): The class object.\n \"\"\"\n if obj is None:\n return\n try:\n for k, v in obj.__dict__.items():\n setattr(self, k, v)\n except AttributeError:\n pass\n\n def __reduce__(self):\n \"\"\"Override of the __reduce__ method of numpy. Call reduce, then add extra pickled state params.\n\n Returns:\n tuple: The pickled state of the object.\n \"\"\"\n pickled_state = super(Grid, self).__reduce__()\n unneeded = [\"logs\"]\n needed_items = {k: v for k, v in self.__dict__.items() if k not in unneeded}\n new_state = pickled_state[2] + (needed_items,)\n return (pickled_state[0], pickled_state[1], new_state)\n\n def __setstate__(self, state):\n \"\"\"Unpickle the pickled state of the sublass to add in extra params.\n\n Args:\n state (tuple): The pickled state from __reduce__ method.\n \"\"\"\n self.__dict__.update(state[-1])\n super(Grid, self).__setstate__(state[0:-1])\n\n def update_fill(self, filled_coords: np.ndarray, empty_coos_coords: np.ndarray):\n \"\"\"Update the attributed filled, empty_coos, filled_coos after each krig step.\n These attributes keep track of which parts of the grid have been filled, and which\n remain empty.\n\n Args:\n filled_coords (np.ndarray): The new filled coordinates from the latest krig sample.\n empty_coos_coords (np.ndarray): The empty coordinates to delete from the empty_coos array.\n \"\"\"\n self.filled[filled_coords] = True\n self.empty_coos = np.delete(self.empty_coos, empty_coos_coords)\n self.filled_coos = np.append(self.filled_coos, filled_coords)\n\n @contextmanager\n def get_sample(self):\n \"\"\"Context manager responsible for ensuring an atomic sample.\n Generate a sample of the data, then yield it back. If the sample is not filled,\n then don't update the coordinates.\n\n Yields:\n np.ndarray, np.ndarray: The empty coordinates to fill, and sample data to\n generate the variogram.\n \"\"\"\n max_sample = np.min([self.sample_size, self.empty_coos.size])\n empty_coos_coords = np.random.choice(\n np.arange(self.empty_coos.size), max_sample, replace=False\n )\n sample_points = self.empty_coos[empty_coos_coords]\n empty_coos = x, y, z = self.coos[sample_points].T\n filled_coos = self.coos[\n np.unique(np.random.choice(self.filled_coos, self.sample_size))\n ].T\n try:\n yield empty_coos, filled_coos\n finally:\n if not np.isnan(self[x, y, z]).any():\n self.update_fill(sample_points, empty_coos_coords)\n\n def krig_sample(self):\n \"\"\"Perform kriging on one sample subset of the data.\n\n Returns:\n int: The number of cells that were filled on this krig sample.\n \"\"\"\n with self.get_sample() as sample:\n ex, ey, ez = e = sample[0] # get the empty coordinate sample\n fx, fy, fz = f = sample[1] # get the filled coordinate sample\n filled_samples = self[fx, fy, fz] # get the values of the filled data\n dists = self.calculate_self_distance(\n f.copy(), xy_delta=self.xy_delta, z_delta=self.z_delta\n ) # calculate the pairwise distance in the filled samples\n semivariance = self.MSE(\n filled_samples\n ) # Get the semivariance for the filled samples\n model = self.get_fitted_model(\n dists, semivariance\n ) # get the variogram model\n sample_dists = self.sample_distance(\n f.copy(), e.copy(), xy_delta=self.xy_delta, z_delta=self.z_delta\n ) # Get the pairwise distance of the filled and empty samples\n calculated_semivariance = np.linalg.inv(\n model(dists)\n ) # Calculated semivariance\n sample_semivariance = model(sample_dists) # Get the sample semivariance\n weights = (\n np.dot(calculated_semivariance, np.expand_dims(sample_semivariance, 2))\n .squeeze()\n .T\n ) # Calculate the kriging weights\n new_vals = np.sum(\n filled_samples * weights, axis=1\n ) # Use the model to calculate new values\n self[ex, ey, ez] = new_vals\n return ex.size # The number of empty cells that were filled\n\n def krig(self, *args, **kwargs):\n \"\"\"Krig the grid in sample_size chunks until the entire grid is filled.\n\n Returns:\n Grid: The kriged grid\n \"\"\"\n t1 = time.time()\n while np.isnan(self).any():\n sample_size = self.krig_sample()\n t2 = time.time()\n self.logger.info(f\"Finished in {round(t2 - t1, 2)} seconds\")\n return self\n\n def done(self, *args, **kwargs):\n \"\"\"Check to see if the grid is filled or not.\n\n Returns:\n *args: Return whatever is passed.\n \"\"\"\n if not np.isnan(self).any():\n return args\n\n def clean_grid(self):\n \"\"\"Empty the grid and set all values to 0\n\n Returns:\n Grid: The Grid object, now with 0 values\n \"\"\"\n self[:] = 0\n return self\n\n def get_fitted_model(self, dists, vals):\n \"\"\"Pull the model, then call autofit given the params.\n\n Args:\n dists (np.ndarray): The distance matrix.\n vals (np.ndarray): The value matrix\n\n Returns:\n Model: The model object with fitted params\n \"\"\"\n model = fk.config.model(fk.config.model_kwargs)\n model.autofit(dists.ravel(), vals.ravel())\n return model\n\n @staticmethod\n def sample_distance(filled, empty, xy_delta=1, z_delta=1, two_D=True) -> np.ndarray:\n \"\"\"Calculate the distance between each filled value and every empty value.\n\n Args:\n filled (np.ndarray): The filled distance matrix\n empty (np.ndarray): The empty distance matrix.\n xy_delta (int, optional): The xy_delta of the grid. Defaults to 1.\n z_delta (int, optional): The z-delta of the grid. Defaults to 1.\n two_D (bool, optional): Whether or not to calulate 2D or 3D. Defaults to True.\n\n Returns:\n np.ndarray: [description]\n \"\"\"\n filled[:2, :] *= xy_delta\n filled[2, :] *= z_delta\n empty[:2, :] *= xy_delta\n empty[2, :] *= z_delta\n if two_D:\n return np.sqrt(\n np.sum(\n np.square(filled[:2, :] - np.expand_dims(empty[:2, :].T, 2)), axis=1\n )\n )\n else:\n return np.sqrt(\n np.sum(np.square(filled - np.expand_dims(empty.T, 2)), axis=1)\n )\n\n @staticmethod\n def calculate_self_distance(\n coords: np.ndarray, xy_delta=1, z_delta=1, two_D=True\n ) -> np.ndarray:\n \"\"\"This method will calculate the distance from each point\n to every other point in the grid. This can quickly lead to memory\n errors, so precautions should be taken to limit the size of the input\n coordinates.\n\n Args:\n coords (np.ndarray): The input coordinates for the filled datapoints.\n Should be of shape (3, no_datapoints)\n two_D (Bool): Whether or not to calculate a 2D distance instead of 3D.\n Defaults to True.\n\n Returns:\n np.ndarray: An no_datapoints x no_datapoints grid of distances\n \"\"\"\n coords[:2, :] *= xy_delta\n coords[2, :] *= z_delta\n if two_D:\n return np.sqrt(\n np.sum(\n np.square(coords[:2, :] - np.expand_dims(coords[:2, :].T, 2)),\n axis=1,\n )\n )\n else:\n return np.sqrt(\n np.sum(np.square(coords - np.expand_dims(coords.T, 2)), axis=1)\n )\n\n @staticmethod\n def MSE(vals: np.ndarray) -> np.ndarray:\n \"\"\"This method will calculate the mean squared difference between every\n two values in the input array. This is to generate values to go into the\n experimental variogram. This can quickly lead to memory errors, so\n precautions should be taken to limit the size of the input values.\n\n Args:\n vals (np.ndarray): The observed values in the sampled grid.\n\n Returns:\n np.ndarray: The squared distances of each point to every other point.\n \"\"\"\n return (\n np.square(vals - np.expand_dims(vals.reshape(-1, 1), 1)).squeeze()\n / vals.size\n )\n\n\nclass Krig(WorkForce):\n \"\"\"The multiprocessed kriging object. This class will take care of multiprocessing workers,\n as well as assigning grids to workers, distributing tasks, and collecting aggregate data. See\n documentation on workforce for a complete breakdown of how this is accomplished.\n\n Args:\n WorkForce (Object): The workforce class\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"Initialize the Krig class. Arguments and kwargs are passed to Workforce and Grid.\"\"\"\n super().__init__(*args, **kwargs)\n self.aggregate_mean = (\n kwargs.get(\"worker\").copy().clean_grid()\n ) # initialize the grid to 0s\n self.aggregate_variance = (\n kwargs.get(\"worker\").copy().clean_grid()\n ) # initialize the grid to 0s\n self.workload = 0 # The number of grids that have yet to be completed\n self.grids_out = 1 # The number of grids that have been completed\n\n def __call__(self, num_grids):\n \"\"\"The main method for this class. Call krig_multi, then manage all outputs.\n\n Args:\n num_grids (int): The number of grids to krig.\n \"\"\"\n self.krig_multi(num_grids)\n self.manage_outputs()\n\n def krig_single(self):\n \"\"\"Krig one single grid. Add the workload and call the krig method.\"\"\"\n self.krig()\n self.workload += 1\n self.check_workload()\n\n def krig_multi(self, num_grids):\n \"\"\"Krig num_grids number of grids.\n\n Args:\n num_grids (int): The number of grids to krig.\n \"\"\"\n for _ in range(num_grids):\n self.krig_single()\n\n def manage_outputs(self):\n \"\"\"Manager for the workers once Krig has been called.\n Constantly check to see if any workers need to be created, destroyed, and\n monitor the progress of the work.\n \"\"\"\n self.logger.info(\"Waiting for outputs\")\n while True:\n self.cleanup()\n self.check_workload()\n if self.workload == 0:\n break\n output = self._read()\n if isinstance(output, Grid):\n self.read_grid(output)\n elif isinstance(output, dict):\n self.terminate_worker(output.get(\"name\", None))\n self.cleanup()\n\n def incrimental_mean(self, output):\n \"\"\"Calculate the incremental mean from the output grid and\n the current grid.\n\n Args:\n output (Grid): The completed grid object from one of the workers.\n \"\"\"\n self.aggregate_mean *= (self.grids_out - 1) / self.grids_out\n self.aggregate_mean += output * (1 / self.grids_out)\n\n def incrimental_variance(self, output):\n \"\"\"Calculate the incremental standard deviation from the output grid and\n the current grid.\n\n Args:\n output (Grid): The completed grid object from one of the workers.\n \"\"\"\n self.aggregate_variance = (\n (self.grids_out - 2) / (self.grids_out - 1)\n ) * self.aggregate_variance + (\n (1 / self.grids_out) * np.square((output - self.aggregate_mean))\n )\n\n def read_grid(self, output):\n \"\"\"This method is responsible for managing the aggregation and workload counts\n Each time a grid is read off the queue, it is calculated and the counters are updated.\n\n Args:\n output (Grid): The completed grid object from one of the workers.\n \"\"\"\n self.workload -= 1\n self.incrimental_mean(output)\n self.grids_out += 1\n self.incrimental_variance(output)\n self.logger.info(f\"Workload is: {self.workload}\")\n self.logger.info(f\"grids out is: {self.grids_out}\")\n self.check_workload()\n\n def terminate_worker(self, name):\n \"\"\"This method kills a worker with a specific name.\n\n Args:\n name (str): The name of the worker to terminate.\n \"\"\"\n [worker.terminate() for worker in self.workers if worker.name == name]\n\n def cleanup(self):\n \"\"\"This method will get rid of workers that are no longer running.\"\"\"\n self.workers = [worker for worker in self.workers if worker.is_alive()]\n\n def check_workload(self):\n \"\"\"This method checks to see if new workers need to be started given the workload\"\"\"\n if self.workload >= len(self.workers):\n [self._spawn() for _ in range(2)]\n","sub_path":"src/fast_krig/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":21548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"100358676","text":"import asyncio\n\nimport typer\nfrom alembic import command\n\nfrom tifa.globals import db\nfrom tifa.settings import get_settings\n\ngroup_db = typer.Typer()\n\n\nasync def init_models():\n async with db.engine.begin() as conn:\n # await conn.run_sync(db.drop_all)\n await conn.run_sync(db.create_all)\n\n\n@group_db.command(\"version\")\ndef pg_version():\n typer.echo(f\"pg version\")\n\n\n@group_db.command(\"init\")\ndef db_init():\n from tifa.app import current_app\n\n asyncio.run(init_models())\n\n\n@group_db.command(\"migrate\")\ndef db_upgrade():\n from tifa.app import current_app\n\n alembic_cfg = get_alembic_config()\n command.upgrade(alembic_cfg, \"head\")\n\n\n@group_db.command(\"makemigration\")\ndef db_make_migrations():\n from tifa.app import current_app\n\n alembic_cfg = get_alembic_config()\n command.revision(alembic_cfg, autogenerate=True)\n\n\ndef get_alembic_config():\n from alembic.config import Config\n\n alembic_cfg = Config(\"./migration/alembic.ini\")\n alembic_cfg.set_main_option(\"script_location\", \"./migration\")\n alembic_cfg.set_main_option(\"sqlalchemy.url\", get_settings().POSTGRES_DATABASE_URI)\n return alembic_cfg\n","sub_path":"tifa/cli/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"329903306","text":"# coding=utf-8\n# Copyright (C) 2021. Huawei Technologies Co., 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.\n\n'''\nAdapted from kyubyong park, June 2017.\nkbpark.linguist@gmail.com.\nhttps://www.github.com/kyubyong/transformer\n'''\n\nimport numpy as np\nimport tensorflow as tf\n\n\ndef feedforward(inputs, num_units=[2048, 512], is_training=True):\n with tf.variable_scope(\"ffn\", reuse=None):\n # Inner layer\n params = {\"inputs\": inputs, \"filters\": num_units[0], \"kernel_size\": 1, \"activation\": tf.nn.relu, \"use_bias\": True}\n outputs = tf.layers.conv1d(**params)\n\n # Readout layer\n params = {\"inputs\": outputs, \"filters\": num_units[1], \"kernel_size\": 1, \"activation\": None, \"use_bias\": True}\n outputs = tf.layers.conv1d(**params)\n\n # Normalize\n outputs = tf.layers.batch_normalization(outputs, axis=2, training=is_training, name='ln', reuse=None) # [batch_size, seq_length, n_hidden]\n\n return outputs\n\n\nclass MLPEncoder(object):\n\n def __init__(self, config, is_train):\n self.batch_size = config.batch_size # batch size\n self.max_length = config.max_length # input sequence length (number of cities)\n self.input_dimension = config.input_dimension # dimension of input, multiply 2 for expanding dimension to input complex value to tf, add 1 token\n\n self.input_embed = config.hidden_dim # dimension of embedding space (actor)\n\n self.initializer = tf.contrib.layers.xavier_initializer() # variables initializer\n\n self.is_training = is_train # not config.inference_mode\n\n def encode(self, inputs):\n # Tensor blocks holding the input sequences [Batch Size, Sequence Length, Features]\n # self.input_ = tf.placeholder(tf.float32, [self.batch_size, self.max_length, self.input_dimension], name=\"input_raw\")\n\n with tf.variable_scope(\"embedding\"):\n # Embed input sequence\n W_embed = tf.get_variable(\"weights\", [1, self.input_dimension, self.input_embed],\n initializer=self.initializer)\n self.embedded_input = tf.nn.conv1d(inputs, W_embed, 1, \"VALID\", name=\"embedded_input\")\n\n\n # Batch Normalization\n self.enc = tf.layers.batch_normalization(self.embedded_input, axis=2, training=self.is_training,\n name='layer_norm', reuse=None)\n\n ### Feed Forward\n self.enc = feedforward(self.enc, num_units=[2*self.input_embed, self.input_embed],\n is_training=self.is_training)\n\n # Return the output activations [Batch size, Sequence Length, Num_neurons] as tensors.\n self.encoder_output = self.enc ### NOTE: encoder_output is the ref for attention ###\n return self.encoder_output\n","sub_path":"code/castle_mod/algorithms/gradient/corl2/models/encoder/mlp_encoder.py","file_name":"mlp_encoder.py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"399773817","text":"# -*- coding: utf-8 -*-\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, 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 logging\n\nfrom django.db.transaction import commit_on_success\nfrom rest_framework import status\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\n\nfrom networkapi.api_equipment import facade\nfrom networkapi.api_equipment.permissions import Read\nfrom networkapi.api_equipment.permissions import Write\nfrom networkapi.settings import SPECS\nfrom networkapi.util.classes import CustomAPIView\nfrom networkapi.util.decorators import logs_method_apiview\nfrom networkapi.util.decorators import permission_classes_apiview\nfrom networkapi.util.decorators import prepare_search\nfrom networkapi.util.geral import get_app\nfrom networkapi.util.geral import render_to_json\nfrom networkapi.util.json_validate import json_validate\nfrom networkapi.util.json_validate import raise_json_validate\n# from networkapi.util.decorators import permission_obj_apiview\n\nserializers = get_app('api_equipment', module_label='serializers')\n\nlog = logging.getLogger(__name__)\n\n\nclass EquipmentView(CustomAPIView):\n\n @logs_method_apiview\n @raise_json_validate('')\n @permission_classes_apiview((IsAuthenticated, Read))\n @prepare_search\n def get(self, request, *args, **kwargs):\n \"\"\"\n Return list of equipments\n\n :param rights_write(optional): Right of Write - Filter by rights of write\n :param environment(optional): Id of environment - Filter by environment\n :param ipv4(optional): Id of ipv4 - Filter by id ipv4\n :param ipv6(optional): Id of ipv6 - Filter by id ipv6\n :param is_router(optional): Boolean (True|False) - Filter for routers\n :param name(optional): Name of Equipment\n \"\"\"\n\n if not kwargs.get('obj_id'):\n rights_write = request.GET.get('rights_write')\n environment = request.GET.get('environment')\n ipv4 = request.GET.get('ipv4')\n ipv6 = request.GET.get('ipv6')\n is_router = request.GET.get('is_router')\n environment_sdn_controller = request.GET.get('environment_sdn_controller')\n name = request.GET.get('name')\n\n # get equipments queryset\n obj_model = facade.get_equipments(\n user=request.user,\n rights_read=1,\n environment=environment,\n ipv4=ipv4,\n ipv6=ipv6,\n rights_write=rights_write,\n name=name,\n is_router=is_router,\n environment_sdn_controller=environment_sdn_controller,\n search=self.search\n )\n equipments = obj_model['query_set']\n only_main_property = False\n\n else:\n obj_ids = kwargs.get('obj_id').split(';')\n equipments = facade.get_equipment_by_ids(obj_ids)\n only_main_property = True\n obj_model = None\n\n # serializer equipments\n eqpt_serializers = serializers.EquipmentV3Serializer(\n equipments,\n many=True,\n fields=self.fields,\n include=self.include,\n exclude=self.exclude,\n kind=self.kind\n )\n\n # prepare serializer with customized properties\n data = render_to_json(\n eqpt_serializers,\n main_property='equipments',\n obj_model=obj_model,\n request=request,\n only_main_property=only_main_property\n )\n\n return Response(data, status=status.HTTP_200_OK)\n\n @logs_method_apiview\n @raise_json_validate('equipment_post')\n @permission_classes_apiview((IsAuthenticated, Write))\n @commit_on_success\n def post(self, request, *args, **kwargs):\n \"\"\"Creates list of equipments.\"\"\"\n\n data = request.DATA\n json_validate(SPECS.get('equipment_post')).validate(data)\n response = facade.create_equipment(data['equipments'], request.user)\n\n return Response(response, status=status.HTTP_201_CREATED)\n\n @logs_method_apiview\n @raise_json_validate('equipment_put')\n @permission_classes_apiview((IsAuthenticated, Write))\n @commit_on_success\n def put(self, request, *args, **kwargs):\n \"\"\"Updates list of equipments.\"\"\"\n\n data = request.DATA\n json_validate(SPECS.get('equipment_put')).validate(data)\n response = facade.update_equipment(data['equipments'], request.user)\n\n return Response(response, status=status.HTTP_200_OK)\n\n @logs_method_apiview\n @raise_json_validate('')\n @permission_classes_apiview((IsAuthenticated, Write))\n @commit_on_success\n def delete(self, request, *args, **kwargs):\n \"\"\"Deletes list of equipments.\"\"\"\n\n force = request.GET.get('force')\n obj_ids = kwargs['obj_id'].split(';')\n\n facade.delete_equipment(obj_ids, force, request.user)\n\n return Response({}, status=status.HTTP_200_OK)\n","sub_path":"networkapi/api_equipment/views/v3.py","file_name":"v3.py","file_ext":"py","file_size_in_byte":5669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"367390973","text":"__author__ = 'panderson'\n\n\"\"\"skips the odd items, change to true for even\"\"\"\nodd = 1\nn=4\n\ndef skip(s, odd):\n\t\n\treturn s[odd::2]\n\t\ndef chop(n, s):\n s2=s[(n):-n]\n return skip(s2, 0)\n\n\ns=\"Though they share an operator, slicing and indexing have a few important differences:\"\nprint(chop(4, s))\n\ns=\"123456789101112131415\"\nprint(chop(4, s))\n\n\t\n\t\t\n\n","sub_path":"students/paul_anderson/slicing3.py","file_name":"slicing3.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"292032417","text":"from django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\n\nfrom Confercio.frame.common.RoleCheker import RoleChecker\nfrom Confercio.frame.database.models import User\nfrom Confercio.frame.database.services.ConferenceDBService import ConferenceDBService\nfrom Confercio.frame.database.services.MessageDBService import MessageDBService\nfrom Confercio.frame.database.services.ParticipantDBService import ParticipantDBService\nfrom Confercio.frame.database.services.SectionDBService import SectionDBService\nfrom Confercio.frame.decorator.SectionDecorator import SectionDecorator\nfrom Confercio.frame.decorator.UserDecorator import UserDecorator\nfrom Confercio.frame.forms.conference.conference_create import CreateConferenceForm\nfrom Confercio.frame.forms.post.post_create import PostCreateForm\nfrom Confercio.frame.forms.section.section_create import SectionCreateForm\nfrom Confercio.frame.forms.user.registration import RegistrationForm\n\n\nclass OrganizerMain:\n @staticmethod\n def getDialogs(user_id, conference_id):\n service = MessageDBService()\n dialogs = service.getDialogs(user_id, conference_id)\n\n return dialogs\n\n @staticmethod\n def check_user(user):\n if not RoleChecker.isOrganizer(user.role):\n return HttpResponse('Forbidden', status=403)\n\n return None\n\n @staticmethod\n def getDefaultConference():\n conferenceService = ConferenceDBService()\n return conferenceService.getLastConference()\n\n @staticmethod\n def getConferenceById(id):\n conferenceService = ConferenceDBService()\n return conferenceService.getConferenceById(id)\n\n @staticmethod\n def getSectionsForConerence(conference_id):\n sectionService = SectionDBService()\n return sectionService.getSectionForConference(conference_id)\n\n @staticmethod\n def getParticipantsForConerence(conference_id):\n participantService = ParticipantDBService()\n return participantService.getParticipantsForConference(conference_id)\n\n @staticmethod\n @login_required\n def view(request):\n check_result = OrganizerMain.check_user(request.user)\n\n if request.GET.has_key('conference_id'):\n conference = OrganizerMain.getConferenceById(int(request.GET['conference_id']))\n else:\n conference = OrganizerMain.getDefaultConference()\n\n if check_result:\n return check_result\n\n dialogs = OrganizerMain.getDialogs(request.user.id, conference.id)\n sections_data = OrganizerMain.getSectionsForConerence(conference.id)\n\n context = {\n 'conference': conference,\n 'user': UserDecorator.getMainUserinfo(request),\n 'sections': SectionDecorator.convertSections(sections_data),\n 'form': RegistrationForm(),\n 'conference_form': CreateConferenceForm(),\n 'section_form': SectionCreateForm(initial={'conference': conference}),\n 'post_form': PostCreateForm(),\n 'dialogs': dialogs,\n 'push_settings': OrganizerMain.getWebPushSettings(request),\n 'participants': OrganizerMain.getParticipantsForConerence(conference.id)\n }\n\n return render(request, 'site/organizer/main.html', context)\n\n @staticmethod\n def getWebPushSettings(request):\n settings = request.user.getNotificationSettings()\n\n initial = {\n 'id': settings.id if settings.id else None,\n 'messages_notifications': \"checked\" if settings.message_notification is True else \"\",\n 'section_notification': \"checked\" if settings.section_notification is True else \"\",\n 'news_notification': \"checked\" if settings.news_notification is True else \"\",\n 'excluded_tags': settings.excluded_tags.all() if settings.id else [],\n }\n\n return initial","sub_path":"Confercio/frame/view/organizer/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"174692936","text":"def softmax(x):\n exp_x = [2.7182818284590452353602874713526624977 ** nx for nx in x]\n sum_exp = sum(exp_x) + 1e-10\n return [es / sum_exp for es in exp_x]\n\n\nfrom random import random\nrand_range = (lambda r: int(random() * r // 1))\n\nweight = [random() * 0.1 * 2 - 0.1 for _ in range(28 * 28 * 10)]\n\n\ndef forward(x):\n return softmax([sum([weight[nx * 28 * 28 + i] * x[i] for i in range(28 * 28)]) for nx in range(10)])\n\n\ndef mean_square_error(y, y_hat):\n return sum([(y[i] - y_hat[i]) ** 2 for i in range(10)]) / 10\n\n\ndef backward(src, x, y, lr):\n for nx in range(10):\n diff = (x[nx] - y[nx])\n for i in range(28 * 28):\n weight[nx * 28 * 28 + i] -= lr * src[i] * diff\n return mean_square_error(x, y)\n\n\ndef check_acc(acc_x, acc_y, ratio, seq=False):\n success, acc_range = 0, int(len(acc_x) * ratio // 1)\n for i in range(acc_range):\n l_index = i if seq else rand_range(acc_range)\n y = forward(acc_x[l_index])\n success += 1 if y.index(max(y)) == acc_y[l_index] else 0\n return success / acc_range\n\n\nprint(\"===Start loading MNIST data set..====\")\n\nbyte_2_int = (lambda byte: int.from_bytes(byte, \"big\", signed=False))\nread_file = (lambda fd_name: open(\"resource/\" + fd_name, \"rb\"))\n\nfd_train_image, fd_train_label = read_file(\"train-images.idx3-ubyte\"), read_file(\"train-labels.idx1-ubyte\")\nfd_test_image, fd_test_label = read_file(\"t10k-images.idx3-ubyte\"), read_file(\"t10k-labels.idx1-ubyte\")\nfd_train_image.read(16), fd_train_label.read(8), fd_test_image.read(16), fd_test_label.read(8)\n\ntrain_size, test_size = 60000, 10000\ntrain_image = [[byte_2_int(fd_train_image.read(1)) / 255 for _ in range(28 * 28)] for _ in range(train_size)]\ntrain_label = [byte_2_int(fd_train_label.read(1)) for _ in range(train_size)]\ntest_image = [[byte_2_int(fd_test_image.read(1)) / 255 for _ in range(28 * 28)] for _ in range(test_size)]\ntest_label = [byte_2_int(fd_test_label.read(1)) for _ in range(test_size)]\n\ntest_size = test_size - (test_size // 5)\nvalid_image, valid_label = test_image[test_size:], test_label[test_size:]\ntest_image, test_label = test_image[:test_size], test_label[:test_size]\n\n_, vis_count = print(\"===Success loading MNIST data set!===\", \"\\nEnter visualise case count:\"), int(input())\n\nfor seq in range(vis_count):\n index = rand_range(train_size)\n print(\"Label:\", train_label[index], \"Index:\", index, \"Sequence:\", seq + 1)\n for vx in range(28):\n print(\"\".join([\"#\" if train_image[index][vx * 28 + vy] > 0 else \".\" for vy in range(28)]))\n\n_, total_epoch = print(\"===End visualize data set===========\", \"\\nEnter epoch count:\"), int(input())\nprint(\"===Start Training...================\")\n\ntrain_history = dict()\nfor epoch in range(total_epoch):\n l_cost = 0\n for seq in range(train_size):\n index = rand_range(train_size)\n x, y = forward(train_image[index]), [0.0] * 10\n y[train_label[index]] = 1.0\n l_cost += backward(train_image[index], x, y, lr=0.002)\n if seq % 500 == 0 and seq != 0:\n acc, m_cost = check_acc(test_image, test_label, ratio=.05) * 100, l_cost / 500\n train_history[min(300, len(train_history))] = acc, m_cost\n print(\"accuracy:\", str(acc) + \"%\", \"mean-cost:\", m_cost)\n prc, l_cost = int(seq / train_size * 100 // 2), 0\n print(\"epoch:\", str(epoch+1)+\"/\"+str(total_epoch), \"[\"+\"\".join([\">\"]*prc)+\"\".join([\".\"]*(50-prc))+\"]\")\n\nprint(\"===End, validation acc:\", str(check_acc(valid_image, valid_label, ratio=1, seq=True) * 100) + \"%=======\")\n_, vis_count = print(\"Enter visualise case count:\"), int(input())\n\nfor seq in range(vis_count):\n index = rand_range(len(valid_label))\n x = forward(valid_image[index])\n print(\"Prediction:\", x.index(max(x)), \"Label:\", valid_label[index])\n for vx in range(28):\n print(\"\".join([\"#\" if valid_image[index][vx * 28 + vy] > 0 else \".\" for vy in range(28)]))\n\nprint(\"===Print training history....=======\\nPress ENTER to continue...\"), input(), print(\"@: accuracy, #: cost\")\nacc_history, cost_history = [dt[1][0] for dt in train_history.items()], [dt[1][1] for dt in train_history.items()]\nget_pixel = (lambda va, vc, y: \"@\" if va/100*40 // 1 == y else (\"#\" if vc/max(cost_history)*40 // 1 == y else \".\"))\nfor y in reversed(range(1, 41)):\n print(\"\".join([get_pixel(da, dc, y) for da, dc in zip(acc_history, cost_history)]))\n","sub_path":"PyMNIST.py","file_name":"PyMNIST.py","file_ext":"py","file_size_in_byte":4375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"165243442","text":"import matplotlib.pyplot as plt\nfrom pylab import mpl\nimport pandas as pd\nimport numpy as np\nimport math\n\n\ndef newton_interpolation(X,Y,x):\n \"\"\"\n 计算x点的插值\n \"\"\"\n sum=Y[0]\n temp=np.zeros((len(X),len(X)))\n #将第一行赋值\n for i in range(0,len(X)):\n temp[i,0]=Y[i]\n temp_sum=1.0\n for i in range(1,len(X)):\n #x的多项式\n temp_sum=temp_sum*(x-X[i-1])\n #计算均差\n for j in range(i,len(X)):\n temp[j,i]=(temp[j,i-1]-temp[j-1,i-1])/(X[j]-X[j-i])\n sum+=temp_sum*temp[i,i] \n return sum\n\n\nX=[0,3,5,7,9,11,12,13,14,15]\nY=[0,1.2,1.7,2.0,2.1,2.0,1.8,1.2,1.0,1.6]\n\n#A = get_diff_table(X,Y)\n#df = pd.DataFrame(A)\n#df\nxs=np.linspace(np.min(X),np.max(X),1000,endpoint=True)\nys=[]\nfor x in xs:\n ys.append(newton_interpolation(X,Y,x))\n\n\n plt.title(\"newton_interpolation\")\nplt.plot(X,Y,'s',label=\"original values\")#蓝点表示原来的值\nplt.plot(xs,ys,'r',label='interpolation values')#插值曲线\nplt.xlabel('x') \nplt.ylabel('y') \nplt.legend(loc=4)","sub_path":"module1.py","file_name":"module1.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"269920248","text":"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport dm_env\nfrom dm_env import specs\nfrom dm_control import mujoco\nfrom dm_control.rl import control\nfrom dm_control.suite import base\nfrom dm_control.suite import common\nfrom dm_control.utils import containers\nfrom dm_control.utils import rewards\nfrom dm_control import robot\nfrom IPython import embed\nfrom copy import deepcopy\nimport numpy as np\n\n# the kinova jaco2 ros exposes the joint state at ~52Hz\n# CONTROL_TIMESTEP should be long enough that position controller can also reach the destination in mujoco if it is reacher. Tested with .1 CONTROL_TIMESTEP and .1 maximum relative deg step in 7DOF jaco for position controllers (with tuned gain).\n_CONTROL_TIMESTEP = .1\n_LONG_EPISODE_TIME_LIMIT = 20\n_SHORT_EPISODE_TIME_LIMIT = 10\n_TINY_EPISODE_TIME_LIMIT = 5\n_BIG_TARGET = .05\n_SMALL_TARGET = .015\n\n# size of target in meters\nSUITE = containers.TaggedTasks()\n\ndef DHtransformEL(d,theta,a,alpha):\n T = np.array([[np.cos(theta), -np.sin(theta)*np.cos(alpha), np.sin(theta)*np.sin(alpha),a*np.cos(theta)],\n [np.sin(theta), np.cos(theta)*np.cos(alpha), -np.cos(theta)*np.sin(alpha),a*np.sin(theta)],\n [0.0, np.sin(alpha), np.cos(alpha),d],\n [0.0,0.0,0.0,1.0]])\n return T\n\ndef trim_and_check_pose_safety(position, fence):\n \"\"\"\n take in a position list [x,y,z] and ensure it doesn't violate the defined fence\n \"\"\"\n hit = False\n safe_position = []\n for ind, dim in enumerate(['x','y','z']):\n if max(fence[dim]) < position[ind]:\n out = max(fence[dim])\n hit = True\n #print('hit max: req {} is more than fence {}'.format(position[ind], max(fence[dim])))\n elif position[ind] < min(fence[dim]):\n out = min(fence[dim])\n hit = True\n #print('hit min: req {} is less than fence {}'.format(position[ind], min(fence[dim])))\n else:\n out = position[ind]\n safe_position.append(out)\n return safe_position, hit\n\ndef get_model_and_assets(xml_name):\n \"\"\"Returns a tuple containing the model XML string and a dict of assets.\"\"\"\n return common.read_model(xml_name), common.ASSETS\n\n@SUITE.add('benchmarking', 'position_reacher_7DOF')\ndef position_reacher_7DOF(random=None, fence={'x':(-1,1),'y':(-1,1),'z':(0.05,1.2)}, robot_server_ip='127.0.0.1', robot_server_port=9030, physics_type='mujoco', environment_kwargs={}):\n xml_name='jaco_j2s7s300_position.xml'\n start_position='home'\n fully_observable=True \n action_penalty=True\n relative_step=False \n relative_rad_max=.1\n fence=fence \n degrees_of_freedom=7 \n extreme_joints=[4,6,7] \n target_size=_BIG_TARGET \n target_type='random' \n control_timestep=_CONTROL_TIMESTEP\n episode_timelimit=_SHORT_EPISODE_TIME_LIMIT \n\n if physics_type == 'robot':\n physics = RobotPhysics()\n physics.initialize(robot_server_ip, robot_server_port, fence)\n else:\n physics = MujocoPhysics.from_xml_string(*get_model_and_assets(xml_name))\n physics.initialize(xml_name, random, degrees_of_freedom)\n\n task = Jaco(random=random, start_position=start_position, \n fully_observable=fully_observable, \n action_penalty=action_penalty,\n relative_step=relative_step, \n relative_rad_max=relative_rad_max, \n fence=fence,\n degrees_of_freedom=degrees_of_freedom, \n extreme_joints=extreme_joints, \n target_size=target_size, \n target_type=target_type)\n return control.Environment(\n physics, task, \n control_timestep=control_timestep,\n time_limit=episode_timelimit, \n **environment_kwargs)\n\n\n\n@SUITE.add('benchmarking', 'relative_position_reacher_7DOF')\ndef relative_position_reacher_7DOF(random=None, fence={'x':(-1,1),'y':(-1,1),'z':(0.05,1.2)}, robot_server_ip='127.0.0.1', robot_server_port=9030, physics_type='mujoco', environment_kwargs={}):\n xml_name='jaco_j2s7s300_position.xml'\n start_position='home'\n fully_observable=True \n action_penalty=True\n relative_step=True \n relative_rad_max=.1\n fence=fence \n degrees_of_freedom=7 \n extreme_joints=[4,6,7] \n target_size=_BIG_TARGET \n target_type='random' \n control_timestep=_CONTROL_TIMESTEP\n episode_timelimit=_SHORT_EPISODE_TIME_LIMIT \n\n if physics_type == 'robot':\n physics = RobotPhysics()\n physics.initialize(robot_server_ip, robot_server_port, fence)\n else:\n physics = MujocoPhysics.from_xml_string(*get_model_and_assets(xml_name))\n physics.initialize(xml_name, random, degrees_of_freedom)\n\n task = Jaco(random=random, start_position=start_position, \n fully_observable=fully_observable, \n action_penalty=action_penalty,\n relative_step=relative_step, \n relative_rad_max=relative_rad_max, \n fence=fence,\n degrees_of_freedom=degrees_of_freedom, \n extreme_joints=extreme_joints, \n target_size=target_size, \n target_type=target_type)\n return control.Environment(\n physics, task, \n control_timestep=control_timestep,\n time_limit=episode_timelimit, \n **environment_kwargs)\n\n@SUITE.add('benchmarking', 'configurable_reacher')\ndef configurable_reacher(xml_name='jaco_j2s7s300_position.xml', \n random=None, \n start_position='home', \n fully_observable=True, \n action_penalty=True, \n relative_step=True, \n relative_rad_max=.1, \n fence = {'x':(-1.5,1.5),'y':(-1.5,1.5),'z':(-1.5,1.5)}, \n degrees_of_freedom=7, \n extreme_joints=[4,6,7], \n target_size=_BIG_TARGET, \n target_type='random', \n fixed_target_position=[.2,-.2,.5], \n robot_server_ip='127.0.0.1', \n robot_server_port=9030, \n physics_type='mujoco', \n control_timestep=_CONTROL_TIMESTEP, \n episode_timelimit=_LONG_EPISODE_TIME_LIMIT, \n environment_kwargs={}):\n \"\"\" configurable Jaco \"\"\"\n if physics_type == 'robot':\n physics = RobotPhysics()\n physics.initialize(robot_server_ip, robot_server_port, fence)\n else:\n physics = MujocoPhysics.from_xml_string(*get_model_and_assets(xml_name))\n physics.initialize(xml_name, random, degrees_of_freedom)\n\n task = Jaco(\n random=random,\n start_position=start_position, \n fully_observable=fully_observable, \n action_penalty=action_penalty,\n relative_step=relative_step, \n relative_rad_max=relative_rad_max, \n fence=fence,\n degrees_of_freedom=degrees_of_freedom, \n extreme_joints=extreme_joints, \n target_size=target_size, \n target_type=target_type, \n fixed_target_position=fixed_target_position)\n return control.Environment(\n physics, task, \n control_timestep=control_timestep,\n time_limit=episode_timelimit, \n **environment_kwargs)\n\n\nclass MujocoPhysics(mujoco.Physics):\n \"\"\"Physics with additional features for the Planar Manipulator domain.\"\"\"\n\n def initialize(self, xml_string='', seed=None, degrees_of_freedom=7):\n self.DOF = degrees_of_freedom\n self.random_state = np.random.RandomState(seed)\n self.actuated_joint_names = self.named.data.qpos.axes.row.names\n self.n_actuators = len(self.actuated_joint_names)\n self.n_major_actuators = len([n for n in self.actuated_joint_names if 'finger' not in n])\n # assumes that joints are ordered!\n if 'j2s7s300' in xml_string:\n \"\"\" NOTE when 7dof robot is completely extended reaching for the sky in mujoco - joints are:\n [-6.27,3.27,5.17,3.24,0.234,3.54,...]\n \"\"\"\n \"\"\"\n ## approx loc on home on real 7dof jaco2 robot when \"ready\"\n joint1: 283.180389404\n joint2: 162.709854126\n joint3: 359.883789062\n joint4: 43.4396743774\n joint5: 265.66293335\n joint6: 257.471435547\n joint7: 287.90637207\n ## approc loc of sleeping home on 7dof jaco2 \n ---\n joint1: 269.791229248\n joint2: 150.065505981\n joint3: 359.889862061\n joint4: 29.8496322632\n joint5: -0.251720875502\n joint6: 212.803970337\n joint7: -179.722869873\n ---\n \"\"\" \n # hand joint is fully open at 0 rads !! it seems like robot is different\n # hand fingertips are closed at [1.1,1.1,1.1,0,0,0]\n # when 7dof is reaching for sky\n \n self.sky_joint_angles = np.array([-6.27,3.27,5.17,3.24,0.234,3.54,3.14,\n 1.1,0.0,1.1,0.0,1.1,0.])\n self.out_joint_angles = np.array([-6.27,1,5.17,3.24,0.234,3.54,3.14,\n 1.1,0.0,1.1,0.0,1.1,0.])\n \n ## approx loc on home on real 7dof jaco2 robot\n self.sleep_joint_angles = np.array([4.71, # 270 deg\n 2.61, # 150\n 0, # 0\n .5, # 28\n 6.28, # 360\n 3.7, # 212\n 3.14, # 180\n 1.1,0.1,1.1,0.1,1.1,0.1])\n # true home on the robot has the fingers open\n self.home_joint_angles = np.array([4.92, # 283 deg\n 2.839, # 162.709854126\n 0, # 0 \n .758, # 43.43\n 4.6366, # 265.66\n 4.493, # 257.47\n 5.0249, # 287.9\n 1.1,0.1,1.1,0.1,1.1,0.1])\n else:\n raise ValueError('unknown or unconfigured robot type')\n \n def set_pose_of_target(self, target_position, target_size):\n self.named.model.geom_size['target', 0] = target_size\n self.named.model.geom_pos['target', 'x'] = target_position[0] \n self.named.model.geom_pos['target', 'y'] = target_position[1] \n self.named.model.geom_pos['target', 'z'] = target_position[2] \n\n def reset(self):\n super(MujocoPhysics, self).reset()\n self.set_robot_position_home()\n\n def set_robot_position_home(self):\n # TODO - should we ensure that the home position is within the fence? \n # we should setup walls in the xml sim\n self.set_robot_position(self.home_joint_angles)\n #self.set_robot_position(self.out_joint_angles)\n\n def set_robot_position(self, body_angles):\n # fingers are always last in xml - assume joint angles are for major joints to least major\n self.named.data.qpos[self.actuated_joint_names[:len(body_angles)]] = body_angles\n\n def get_timestep(self):\n return np.array(self.timestep())\n\n def get_actuator_velocity(self):\n return self.named.data.actuator_velocity.copy()\n\n def get_actuator_force(self):\n return self.named.data.actuator_force.copy()\n\n def get_joint_angles_radians(self):\n # only return last joint orientation\n return self.named.data.qpos.copy()[:self.n_actuators]\n\n def get_joint_coordinates(self):\n return self.named.data.geom_xpos.copy()[1:self.n_actuators+1]\n\n def action_spec(self):\n return mujoco.action_spec(self)\n\nclass RobotPhysics(robot.Physics):\n #TODO the joint order is different for the robot and mujoco fingers - robot has major fingers, then tips. mujoco has each finger, then its tip\n def set_pose_of_target(self, target_position, target_size):\n self.target_position = target_position\n\n def set_robot_position_home(self):\n # TODO - have feedback here?\n self.robot_client.home()\n\n def set_robot_position(self, body_angles):\n # only send relative rad angles from here\n self.step(body_angles)\n\n def get_timestep(self):\n return self.timestep()\n\n def get_actuator_velocity(self):\n return self.actuator_velocity\n\n def get_actuator_force(self):\n return self.actuator_effort\n\n def get_joint_angles_radians(self):\n # only return last joint orientation\n return self.actuator_position\n\n def set_robot_position_home(self):\n return self.robot_client.home()\n\nclass Jaco(base.Task):\n \"\"\"A Bring `Task`: bring the prop to the target.\"\"\"\n\n def __init__(self, random=None, start_position='home', fully_observable=True, action_penalty=True, relative_step=True, relative_rad_max=.1, fence = {'x':(-1,1),'y':(-1,1),'z':(-1.2,1.2)}, degrees_of_freedom=7, extreme_joints=[4,6,7], target_size=.05, target_type='random', fixed_target_position=[.2,.2,.5]):\n\n \"\"\"Initialize an instance of `Jaco`.\n Args:\n random: int seed number for random seed\n start_position: key indicator for where to start the robot 'home' will start in robot home position\n\n fully_observable: A `bool` not yet used\n action_penalty: bool impose a penalty for actions\n relative_step: bool indicates that actions are relative to previous step. Set to True for sim2real as we need to ensure that the actions trained in dm_control can be completed within the control step as they are in the real blocking ros system.\n relative_rad_max: float indicating the maximum relative step. Tested 7dof robot with .2 control_timestep and relative position of max 0.1 rads\n fence: dict with {'x':(min,max), 'y':(min,max), 'z':(min,max)} indicating a virtual cartesian fence. We impose a penalty for extreme joints which exit the virtual fence in dm_control and impose a hard limit on the real robot.\n degrees_of_freedom: int indicating the number of joints to be controlled\n extreme_joints: list of joints (starting with joint 1) to consider for imposing fence violations in dm_control. For 7dof Jaco, this should be [4,6,7] out of joints (1,2,3,4,5,6,7).\n target_size: float indicating the size of target in reaching tasks\n target_type: string indicating if we should calculate a 'random' or 'fixed' position for the target at reset. If fixed, will used fixed_target_position\n fixed_target_position: list indicating x,y,z center of target in cartesian space\n \n location.\n relative_step: bool whether input action should be relative to current position or absolute\n relative_rad_max: float limit radian step to min/max of this value\n random: Optional, an integer seed for creating a new `RandomState`, or None to select a seed\n automatically (default).\n \"\"\"\n self.target_type = target_type\n self.fixed_target_position = self.target_position = np.array(fixed_target_position)\n self.relative_step = relative_step\n self.relative_rad_max = relative_rad_max\n self.DOF = degrees_of_freedom\n self.fence = fence\n self.use_action_penalty = bool(action_penalty)\n self.extreme_joints = np.array(extreme_joints)\n self.target_size = target_size\n # ~.13 m from tool pose to fingertip\n # radii = physics.named.model.geom_size[['target', 'finger'], 0].sum()\n self.radii = self.target_size + .15\n self.start_position = start_position\n self.random_state = np.random.RandomState(random)\n self._fully_observable = fully_observable\n self.hit_penalty = 0.0\n self.action_penalty = 0.0\n # TODO are open/close opposite on robot??\n self.opened_hand_position = np.zeros(6)\n self.closed_hand_position = np.array([1.1,0.1,1.1,0.1,1.1,0.1])\n\n # find target min/max using fence and considering table obstacle and arm reach\n self.target_minx = max([min(self.fence['x'])]+[-.8])\n self.target_maxx = min([max(self.fence['x'])]+[.8])\n self.target_miny = max([min(self.fence['y'])]+[-.8])\n self.target_maxy = min([max(self.fence['y'])]+[.8])\n self.target_minz = max([min(self.fence['z'])]+[0.1])\n self.target_maxz = min([max(self.fence['z'])]+[.8])\n print('Jaco received virtual fence of:', self.fence)\n print('limiting target to x:({},{}), y:({},{}), z:({},{})'.format(\n self.target_minx, self.target_maxx,\n self.target_miny, self.target_maxy,\n self.target_minz, self.target_maxz))\n\n if self.DOF in [7,13]:\n # 7DOF Jaco2\n #D1 Base to shoulder 0.2755\n #D2 First half upper arm length 0.2050\n #D3 Second half upper arm length 0.2050\n #D4 Forearm length (elbow to wrist) 0.2073\n #D5 First wrist length 0.1038\n #D6 Second wrist length 0.1038\n #D7 Wrist to center of the hand 0.1600\n #e2 Joint 3-4 lateral offset 0.0098\n\n # Params for Denavit-Hartenberg Reference Frame Layout (DH)\n self.DH_lengths = {'D1':0.2755, 'D2':0.2050, \n 'D3':0.2050, 'D4':0.2073,\n 'D5':0.1038, 'D6':0.1038, \n 'D7':0.1600, 'e2':0.0098}\n\n # DH transform from joint angle to XYZ from kinova robotics ros code\n self.DH_a = (0, 0, 0, 0, 0, 0, 0)\n self.DH_d = (-self.DH_lengths['D1'], \n 0, \n -(self.DH_lengths['D2']+self.DH_lengths['D3']), \n -self.DH_lengths['e2'], \n -(self.DH_lengths['D4'] + self.DH_lengths['D5']), \n 0, \n -(self.DH_lengths['D6']+self.DH_lengths['D7']))\n \n self.DH_alpha = (np.pi/2.0, np.pi/2.0, np.pi/2.0, np.pi/2.0, np.pi/2.0, np.pi/2.0, np.pi)\n self.DH_theta_sign = (1, 1, 1, 1, 1, 1, 1)\n self.DH_theta_offset = (np.pi,0.0, 0.0, 0.0, 0.0,0.0,np.pi/2.0)\n\n super(Jaco, self).__init__()\n\n def observation_spec(self, physics):\n self.after_step(physics)\n super(Jaco, self).observation_spec(physics)\n\n def action_spec(self, physics):\n spec = physics.action_spec()\n if self.relative_step:\n spec = specs.BoundedArray(shape=(self.DOF,), dtype=np.float, \n minimum=np.ones(self.DOF)*-self.relative_rad_max, \n maximum=np.ones(self.DOF)*self.relative_rad_max)\n return spec\n else:\n # TODO this will only work if we are using Mujoco - add to robot\n spec = physics.action_spec()\n if spec.shape[0] == self.DOF:\n return spec\n # sometimes we only want to control a few joints\n elif spec.shape[0] > self.DOF:\n return specs.BoundedArray(shape=(self.DOF,), dtype=np.float, \n minimum=spec.minimum[:self.DOF], \n maximum=spec.maximum[:self.DOF])\n else:\n raise NotImplemented\n \n def _find_joint_coordinate_extremes(self, major_joint_angles): \n \"\"\"calculate xyz positions for joints form cartesian extremes\n major_joint_angles: ordered list of joint angles in radians (len 7 for 7DOF arm)\"\"\"\n \"\"\" July 2020 - \n JRH sanity checked these values by setting the real 7DOF Jaco 2 robot to the \"home position\" \n and measured the physical robot against the DH calculations of extreme joints.\n In this function, we care about the elbow (joint 4), wrist, (joint6) and tool pose (fingertips)\n\n home_joint_angles = np.array([4.92, # 283 deg\n 2.839, # 162.709854126\n 0., # 0 \n .758, # 43.43\n 4.6366, # 265.66\n 4.493, # 257.47\n 5.0249, # 287.9\n \n Unfortunately, I only have an Imperial tape measure, so converting to inches first:\n ---\n index xm ym zm xin yin zin measured_description\n 6 -.304 -.149 .504 -11.9685 -5.866 19.685 finger tips! this is appropriate to use for tool pose\n 5 -.04 -.144 .515 1.57 5.66 20.27 middle of joint 6 starting with 1 joint indexing\n 3 .016 .122 .667 .629 4.8 26.25 joint 4 starting with 1 joint indexing\n \"\"\"\n extreme_xyz = []\n\n # for 7DOF robot only!\n # transform first!\n Tall = np.array([[1,0,0,0],[0,-1,0,0],[0,0,-1,0],[0,0,0,1]], dtype=np.float)\n for i, angle in enumerate(major_joint_angles):\n DH_theta = self.DH_theta_sign[i]*angle + self.DH_theta_offset[i]\n T = DHtransformEL(self.DH_d[i], DH_theta, self.DH_a[i], self.DH_alpha[i])\n Tall = np.dot(Tall, T)\n #if i+1 in self.extreme_joints:\n extreme_xyz.append([Tall[0,3], Tall[1,3], Tall[2,3]])\n extremes = np.array(extreme_xyz)\n return extremes\n\n def initialize_episode(self, physics):\n \"\"\"Sets the state of the environment at the start of each episode.\"\"\"\n if self.start_position == 'random':\n # dont need to send home - reset already does that on real robot and in mujoco\n raise NotImplemented; print(\"random init position has not been implemented\")\n if self.target_type == 'random':\n distance = 10 \n # limit distance from tool pose to within 1.1 meters of the base\n # TODO how does collision with the target impact physics? \n # We don't want it to actually collide\n while distance > 1.1:\n tx = self.random_state.uniform(self.target_minx, self.target_maxx)\n ty = self.random_state.uniform(self.target_miny, self.target_maxy)\n tz = self.random_state.uniform(self.target_minz, self.target_maxz)\n distance = tx + ty + tz\n self.target_position = np.array([tx,ty,tz])\n elif self.target_type == 'fixed':\n self.target_position = self.fixed_target_position\n else:\n raise ValueError; print('unknown target_type: fixed or random are required but was set to {}'.format(self.target_type))\n print('**setting new target position of:', self.target_position)\n physics.set_pose_of_target(self.target_position, self.target_size)\n self.after_step(physics)\n super(Jaco, self).initialize_episode(physics)\n\n def before_step(self, action, physics):\n \"\"\"\n take in relative or absolute np.array of actions of length self.DOF\n if relative mode, action will be relative to the current state\n \"\"\"\n\n self.hit_penalty = 0.0\n # need action to be same shape as number of actuators\n if self.relative_step:\n # relative action prone to drift over time\n relative_action = np.clip(action, -self.relative_rad_max, self.relative_rad_max)\n use_action = relative_action+self.joint_angles[:len(action)]\n else:\n # TODO I think absolute positions should still be limited since actions which are far away cannot be completed\n use_action = np.clip(action, self.joint_angles[:len(action)]-self.relative_rad_max, self.joint_angles[:len(action)]+self.relative_rad_max)\n\n if self.use_action_penalty:\n self.action_penalty = -np.square(use_action-self.joint_angles[:len(use_action)]).sum()\n if len(use_action) < physics.n_actuators:\n use_action = np.hstack((use_action, self.closed_hand_position))\n # TODO below only deals with major joints so self.DOF really isn't the right indexer\n joint_extremes = self._find_joint_coordinate_extremes(use_action[:7])[self.extreme_joints-1]\n for xx,joint_xyz in enumerate(joint_extremes):\n good_xyz, hit = trim_and_check_pose_safety(joint_xyz, self.fence)\n if hit:\n self.hit_penalty -= 1.0\n self.safe_step = False\n #print('joint {} will hit at ({},{},{}) at requested joint position - blocking action'.format(self.extreme_joints[xx], *good_xyz))\n super(Jaco, self).before_step(use_action, physics)\n\n def after_step(self, physics):\n self.joint_angles = deepcopy(physics.get_joint_angles_radians())\n self.joint_extremes = deepcopy(self._find_joint_coordinate_extremes(self.joint_angles[:7]))\n self.tool_position = self.joint_extremes[-1]\n \n def get_observation(self, physics):\n \"\"\"Returns either features or only sensors (to be used with pixels).\"\"\"\n # TODO we are only handling full_observations now\n # TODO is timestep needed?? may be important for Torque controlled on real robot\n obs = collections.OrderedDict()\n #obs['timestep'] = physics.get_timestep()\n obs['to_target'] = self.target_position-self.tool_position\n obs['joint_angles'] = self.joint_angles\n obs['joint_forces'] = physics.get_actuator_force()\n obs['joint_velocity'] = physics.get_actuator_velocity()\n ## DEBUG vars\n #obs['joint_extremes'] = self.joint_extremes\n #obs['tool_position'] = self.tool_position\n #obs['jaco_link_4'] = physics.named.data.xpos['jaco_link_4']\n #obs['jaco_link_6'] = physics.named.data.xpos['jaco_link_6']\n #obs['jaco_link_finger_tip_1'] = physics.named.data.xpos['jaco_link_finger_tip_1']\n #obs['target_position'] = self.target_position\n return obs\n\n def get_distance(self, position_1, position_2):\n \"\"\"Returns the signed distance bt 2 positions\"\"\"\n return np.linalg.norm(position_1-position_2)\n\n def get_reward(self, physics):\n \"\"\"Returns a sparse reward to the agent.\"\"\"\n distance = self.get_distance(self.tool_position, self.target_position)\n return rewards.tolerance(distance, (0, self.radii)) + self.hit_penalty + self.action_penalty\n","sub_path":"dm_control/suite/jaco.py","file_name":"jaco.py","file_ext":"py","file_size_in_byte":26808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"549553272","text":"\n\nclass RetTohbase(object):\n\n def __init__(self, table, func, _insert):\n \"\"\"\n :param table: 【str】 保存到hbase的表名\n :param func: 【object】 计算相似度的函数名\n :param _insert: 【object】 写入hbase的语句函数\n \"\"\"\n self.size= 3\n self.host = \"hadoop-master\"\n \"\"\"\n table_prefix_separator参数默认为b'_'使得table_prefix只是table前缀,\n 改为 b':'后table_prefix参数变为hbase的命名空间 (因为hbase中命名空间和表之间是冒号连接的)\n \"\"\"\n self.table_prefix = 'movie'\n self.table_prefix_separator = b':'\n self.table = table\n self._insert = _insert\n similar = func()\n # from functools import partial\n # add_save_hbase = partial(save_hbase, table, _insert)\n similar.foreachPartition(self.save_hbase)\n\n def save_hbase(self, partition):\n\n import happybase\n # table_prefix是指定命名空间, size 线程数\n pool = happybase.ConnectionPool(size=self.size, host=self.host,\n table_prefix=self.table_prefix, table_prefix_separator=self.table_prefix_separator)\n with pool.connection() as conn:\n \"\"\"\n 删除表,创建表,启用表, \n 此处因为 函数被 foreachPartition 方法调用, 每个partition就要执行一遍所以报错\n 最好提前创建好表\n \"\"\"\n # conn.delete_table('movie_lsh', disable=True)\n # conn.create_table('movie_lsh', {'similar': dict(max_versions=3)})\n # conn.enable_table(\"movie_lsh\")\n\n # 建立表的连接\n table = conn.table(self.table)\n # print(conn.tables())\n\n # 一条一条的写\n # for row in partition:\n # if row.datasetA.movie_id == row.datasetB.movie_id:\n # pass\n # else:\n # table.put(str(row.datasetA.movie_id).encode(),\n # {\"similar:{}\".format(row.datasetB.movie_id).encode(): b\"%0.4f\" % (row.EucDistance)})\n\n # 一个batch一个batch写入 (减少IO写入次数,加快速度)\n with table.batch(batch_size=10) as bat:\n self._insert(partition, bat)\n # for row in partition:\n # # bat.put(str(row.datasetA.movie_id).encode(),\n # # {\"similar:{}\".format(row.datasetB.movie_id).encode(): b\"%0.4f\" % (row.EucDistance)})\n # bat.put(str(row.movie_id).encode(),\n # {\"similar:{}\".format(row.movie_id2).encode(): b\"%0.4f\" % (row.cos_sim)})\n\n # 查看数据\n # for key, value in table.scan(row_prefix='xxx'):\n for key, value in table.scan(row_start='1000', row_stop='1050'):\n print(key, value)\n # 手动关闭所有的连接\n conn.close()\n","sub_path":"online_recommend/first-release-version/online_recommend/utils/save_tohbase.py","file_name":"save_tohbase.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"648765269","text":"import functools as ft\nimport json\nimport pytest\nimport numpy as np\nimport community_kernel_inference as cki\n\n\n@pytest.fixture(params=['dense', 'sparse'])\ndef mode(request):\n return request.param\n\n\n@pytest.fixture(params=[True, False])\ndef replace(request):\n return request.param\n\n\n@pytest.fixture(params=[True, False])\ndef stratified(request):\n return request.param\n\n\n@pytest.fixture\ndef model_callable(directed, mode, replace, stratified):\n # Create a 1d grid of points\n num_nodes = 9\n coordinates = (np.arange(num_nodes) - num_nodes // 2)[:, None]\n\n # Use the same points as the coordinate samples\n coordinate_samples = coordinates[None]\n feature_map = cki.feature_maps['l1']\n groups = np.zeros(num_nodes, int)\n\n if mode == 'dense':\n if stratified:\n pytest.skip()\n return ft.partial(\n cki.DenseModel, groups=groups, coordinate_samples=coordinate_samples,\n feature_map=feature_map, replace=replace\n )\n elif mode == 'sparse':\n return ft.partial(\n cki.SparseModel, directed=directed, groups=groups, feature_map=feature_map,\n coordinate_samples=coordinate_samples, replace=replace, stratified=stratified\n )\n else:\n raise KeyError(mode)\n\n\n@pytest.mark.parametrize('map_node, ij', [\n # Symmetric connections to the left and right\n (4, np.transpose([(3, 4), (4, 5)])),\n # Single connection to node 8\n (8, np.transpose([(4, 8)])),\n])\ndef test_sample_node_coordinates(model_callable, mode, directed, map_node, ij):\n if mode == 'dense':\n model = model_callable(cki.edges_to_adjacency(9, ij, directed))\n else:\n model = model_callable(ij)\n\n if not model.replace:\n pytest.skip()\n\n theta = [0, -1]\n _, full = model.sample_node_index(theta, np.arange(model.num_nodes), 4, full=True)\n actual = full['candidate_indices'][np.argmax(full['proba'])]\n assert actual == map_node, \"unexpected best node\"\n\n\n@pytest.fixture\ndef model(mode, directed, replace):\n with open('tests/test_configuration.json') as fp:\n configuration = json.load(fp)\n\n configuration.update(directed=directed)\n simulation = cki.simulate(configuration)\n\n shape = (simulation['num_groups'], configuration['num_samples'], simulation['num_dims'])\n coordinate_samples = np.random.normal(0, 1, shape)\n\n if mode == 'dense':\n if stratified:\n pytest.skip()\n model = cki.DenseModel(simulation['y'], simulation['groups'], coordinate_samples,\n simulation['feature_map'], replace=replace)\n elif mode == 'sparse':\n model = cki.SparseModel(\n simulation['ij'], simulation['groups'], coordinate_samples, simulation['feature_map'],\n directed, replace=replace, stratified=stratified\n )\n else:\n raise KeyError(mode)\n\n # Attach the ground truth for testing\n model._theta = simulation['theta']\n sample_indices = cki.optimal_sample_indices(\n simulation['theta'], simulation['coordinates'], simulation['groups'], coordinate_samples,\n simulation['feature_map']\n )\n model._sample_indices = sample_indices\n\n return model\n\n\ndef test_sample(model):\n model.sample(model._theta, model._sample_indices, 1)\n","sub_path":"tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":3280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"323369474","text":"from glob import glob\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom nltk.corpus import stopwords\nimport re\n\ndef cleanbody(body):\n stopwords_set = set(stopwords.words('english'))\n body = body.replace('\\n', ' ').lower().strip()\n body = body[0:-9] #postfix of artical\n result = ' '.join([text for text in body.split() if text not in stopwords_set])\n return result\n\ndef getData(result):\n resultDictList = []\n body = \"\"\n if result.find('body')!=None:\n body = result.find('body').get_text()\n else:\n return\n if result.find('topics')==None or len([topic.get_text() for topic in result.find('topics').find_all('d')]) > 1:\n return\n else:\n resultDict = {}\n resultDict['topic'] = result.find('topics').get_text()\n resultDict['body'] = body\n resultDictList.append(resultDict)\n return resultDictList\n\ndef dataToCsv(dataList, outputpath):\n df = pd.DataFrame(dataList)\n df['body'] = df['body'].apply(cleanbody)\n print(\"Total Retrieved: {0}\".format(len(df)))\n df.to_csv(outputpath, index=False)\n\ntestResultList = []\ntrainResultList = []\n# file_list = glob('./test/test.sgm')\nfile_list = sorted(glob('./reuters21578/*.sgm'))\nfor filename in file_list:\n print(f'start parsing {filename}')\n file = open(filename, 'rb')\n htmlResults = BeautifulSoup(file, 'html.parser')\n file.close()\n for result in htmlResults.find_all('reuters', lewissplit=\"TEST\", topics=\"YES\"):\n if getData(result) == None:\n continue\n else:\n for r in getData(result):\n testResultList.append(r)\n for result in htmlResults.find_all('reuters', lewissplit=\"TRAIN\", topics=\"YES\"):\n if getData(result) == None:\n continue\n else:\n for r in getData(result):\n trainResultList.append(r)\n print('=============done==============')\n\ndataToCsv(trainResultList, './data/train_data_single_label.txt')\ndataToCsv(testResultList, './data/test_data_single_label.txt')\ndf_train = pd.read_csv('./data/train_data_single_label.txt').dropna()\ndf_train.to_csv('./data/train_data_single_label.xls', index=False)\ndf_test = pd.read_csv('./data/test_data_single_label.txt').dropna()\ndf_test.to_csv('./data/test_data_single_label.xls', index=False)","sub_path":"generate_single_label_dataset.py","file_name":"generate_single_label_dataset.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"336617242","text":"#!/usr/bin/env python3\n\n#Importando los modulos necesarios\nimport sys\nimport os\nimport shutil\nimport time\nimport re\n\nfrom ip_file_valid import ip_file_valid\nfrom ip_addr_valid import ip_addr_valid\nfrom ip_reach import ip_reach\nfrom telnet_connection import telnet_connection\nfrom create_threads import create_threads\n \ndef main():\n #Salvando la lista de direccion(es) IP en una variable\n ip_list = ip_file_valid()\n\n #Verificando que recibi un archivo con informacion y no info vacia.\n if ip_list == \"\":\n #Obtengo el tiempo actual\n timestr = time.strftime(\"%Y-%m-%d - %H:%M:%S\")\n log_control(\"* \" + timestr + \" - \" + \"Ocurrio un error abriendo la ruta del archivo de direcciones IP.\" + \" *\")\n\n #Vericando la validez de la direccion(es) IP en la lista\n try:\n ip_addr_valid(ip_list)\n \n except Exception:\n #Obtengo el tiempo actual\n timestr = time.strftime(\"%Y-%m-%d - %H:%M:%S\")\n log_control(\"* \" + timestr + \" - \" + \"Una o mas dirrecion(es) IP en el archivo ip.txt no esta parametrizada correctamente.\" + \" *\")\n sys.exit()\n \n #Verico que alcance a traves de PING la(s) direccion(es) IP en la lista\n \n if (ip_reach(ip_list)) == True:\n #Llamo a la funcion de creacion de hilos para una o multiples conexiones Telnet\n create_threads(ip_list, telnet_connection)\n\n #Llamo a la funcion de manipulacion de data recibida para crear el archivo final\n file_control()\n else:\n #Obtengo el tiempo actual\n timestr = time.strftime(\"%Y-%m-%d - %H:%M:%S\")\n log_control(\"* \" + timestr + \" - \" + \"No se logra hacer PING a una o mas de las direccion(es) IP, revisar el archivo de direcciones IP: ip.txt\" +\n \" y se concluyo la ejecucion del programa.\" + \" *\")\n \n \n #Llamo a la funcion de creacion de hilos para una o multiples conexiones Telnet\n #create_threads(ip_list, telnet_connection)\n\n #Llamo a la funcion de manipulacion de data recibida para crear el archivo final\n #file_control()\n\n#Funcion que recibe un string para escribir en el log del programa\ndef log_control (log_info):\n\n #Inicializando una lista vacia para llenar con datos de logs\n logs = []\n \n #Cargando el archivo de logs para monitorear el estado del programa\n logfile = (r\"D:\\Cursos\\Programacion\\Python\\Proyectos\\Lectura datos CMTS\\CMTS\\Aplicacion#1\\Log\\logs.txt\")\n\n #Verificar que el archivo logs.txt exista, sino crearlo y agregar la informacion\n if os.path.exists(logfile):\n #Arbiendo y Cerrando el archivo deseado\n with open(logfile, \"r+\") as f:\n #Leo el archivo completo primero\n contenido = f.read()\n #Me muevo al principio del archivo\n f.seek(0)\n #Escribo la nueva informacion de log mas el contenido viejo\n f.write(log_info.rstrip(\"\\r\\n\") + \"\\n\" + contenido)\n else:\n #Arbiendo y Cerrando el archivo deseado\n with open(logfile, \"w+\") as f:\n #Leo el archivo completo primero\n contenido = f.read()\n #Me muevo al principio del archivo\n f.seek(0)\n #Escribo la nueva informacion de log mas el contenido viejo\n f.write(log_info.rstrip(\"\\r\\n\") + \"\\n\" + contenido)\n \n#Funcion que recibe una lista de datos, el cual procesara y creara un nuevo archivo\ndef file_control ():\n #Cargando el archivo con la revision ejecutada en el CMTS\n revision = (r\"D:\\Cursos\\Programacion\\Python\\Proyectos\\Lectura datos CMTS\\CMTS\\Aplicacion#1\\Resultados_Revisiones\\revision.txt\")\n\n #Cargando el archivo con las localidades revisadas en el CMTS\n localidades = (r\"D:\\Cursos\\Programacion\\Python\\Proyectos\\Lectura datos CMTS\\CMTS\\Aplicacion#1\\Extras\\localidades.txt\")\n\n #Abriendo y Cerrando el archivo deseado\n with open(revision) as f:\n newrevision = f.readlines()\n\n #Leyendo el archivo y limpiando los espacios en blancos\n newrevision = [x.strip(\"\\n\") for x in newrevision]\n\n newdata = [] #Lista vacia que contendra los datos del archivo luego de limpiarlo\n\n #Manipulo el archivo para eliminar los \"\\n\" innecsarios del texto\n for linea in newrevision:\n #Se elimina secuencias vacias de la lista y datos innecesarios\n if not linea or re.findall(\"Bienvenidos a la Red\", linea):\n continue \n else:\n newdata.append(linea) #Se añade la nueva data \n \n #Arbiendo y Cerrando el archivo deseado\n with open(localidades) as f:\n newlocalidades = f.readlines()\n\n #Leyendo el archivo y limpiando los espacios en blancos\n newlocalidades = [x.strip(\"\\n\") for x in newlocalidades]\n\n newdata2 = [] #Lista vacia que contendra los datos del archivo luego de limpiarlo\n\n #Manipulo el archivo para crear una nueva lista con toda la informacion de localidades y datos del CMTS en orden\n #Inicializo indices y variables de control\n i = 0\n j = 0\n\n newdata2.append(newlocalidades[j] + \"\\n\") #Agrego la primera localidad\n\n for data in newdata: #Por cada data que haya en la lista estare ejecutando este ciclo for\n if data != \"CMTSTCB001#\":\n newdata2.append(data) #Se añade la nueva data\n elif data == \"CMTSTCB001#\" and i != 1: #Si nos topamos por primera vez con la data \"CMTSTCB001#\", incrementamos el indice de control i a 1\n i += 1\n newdata2.append(\"\\n\") #Se añade la nueva data\n continue \n else: #Si el indice de control i llego a 2, significa que se debe de colocar una nueva localidad\n i = 0\n j += 1\n if j == len(newlocalidades): #Delimitador para saber si ya llegue al ultimo registro\n newdata2.append(\"\\n\")\n break\n newdata2.append(\"\\n\")\n newdata2.append(newlocalidades[j] + \"\\n\")\n continue \n\n #Inacializo la ruta para colocar un nuevo archivo con los datos del capturados del CMTS\n ruta = (r\"D:\\Cursos\\Programacion\\Python\\Proyectos\\Lectura datos CMTS\\CMTS\\Aplicacion#1\\Resultados_Revisiones\\\\\")\n\n #Obtengo el tiempo actual\n timestr = time.strftime(\"%Y.%m.%d-%H.%M.%S\")\n\n #Nombre del nuevo archivo\n newarchivo = ruta + \"revision-nodos-\" + timestr + \".txt\"\n\n #Arbiendo y Cerrando el archivo deseado\n with open(newarchivo, \"w\") as f:\n #Escribo en el archivo\n for data2 in newdata2:\n f.write(\"%s\\n\" % data2)\n\n \n #Elimino el archivo con la revision que se hizo por Telnet (El archivo Crudo)\n if os.remove(revision) is not True:\n #Obtengo el tiempo actual\n timestr = time.strftime(\"%Y-%m-%d - %H:%M:%S\")\n #Escribo en el log\n log_control(\"* \" + timestr + \" - \" + \"Se removio el archivo: \" + revision + \" satisfactoriamente *\")\n else:\n #Obtengo el tiempo actual\n timestr = time.strftime(\"%Y-%m-%d - %H:%M:%S\")\n #Escribo en el log\n log_control(\"* \" + timestr + \" - \" + \"Ocurrio un error removiendo el archivo: \" + revision + \" revisar por posibles errores *\")\n\n #Inacializo la ruta para realizar una copia del archivo con los datos del capturados del CMTS\n backup_ruta = (r\"D:\\Cursos\\Programacion\\Python\\Proyectos\\Lectura datos CMTS\\CMTS\\Aplicacion#1\\Muestra\")\n\n #Realizo la copia del archivo\n if shutil.copy(newarchivo,backup_ruta) is not True:\n #Obtengo el tiempo actual\n timestr = time.strftime(\"%Y-%m-%d - %H:%M:%S\")\n #Escribo en el log\n log_control(\"* \" + timestr + \" - \" + \"Se realizo la copia del archivo: \" + newarchivo + \" a la ruta: \" + backup_ruta + \" satisfactoriamente *\")\n else:\n #Obtengo el tiempo actual\n timestr = time.strftime(\"%Y-%m-%d - %H:%M:%S\")\n #Escribo en el log\n log_control(\"* \" + timestr + \" - \" + \"Ocurrio un error copiado el archivo: \" + newarchivo + \" a la ruta: \" + backup_ruta + \" satisfactoriamente *\")\n \n #Llamo a la funcion de log_control para indicar que toda la operacion fue un exito\n #Obtengo el tiempo actual\n timestr = time.strftime(\"%Y-%m-%d - %H:%M:%S\")\n log_control(\"* \" + timestr + \" - \" + \"La revision de ruido de los nodos en el CMTS fue todo un exito. \" + timestr + \" *\")\n \n\nif __name__ == '__main__':\n main()\n\n#Finaliza el programa","sub_path":"Lectura datos CMTS/CMTS/Aplicacion#1/NoiseApp.py","file_name":"NoiseApp.py","file_ext":"py","file_size_in_byte":8231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"291298734","text":"#!/usr/bin/env python\n# \n# tournament.py -- implementation of a Swiss-system tournament\n#\n\nimport psycopg2\n\n\ndef connect():\n \"\"\"Connect to the PostgreSQL database. Returns a database connection.\"\"\"\n return psycopg2.connect(\"dbname=tournament\")\n\n\ndef deleteMatches():\n \"\"\"Remove all the match records from the database.\"\"\"\n c = connect()\n cursor = c.cursor()\n # Delete all the columns in match.\n cursor.execute('delete from match;')\n c.commit()\n c.close()\n\ndef deletePlayers():\n \"\"\"Remove all the player records from the database.\"\"\"\n c = connect()\n cursor = c.cursor()\n # Delete all the columns in player.\n cursor.execute('delete from player;')\n c.commit()\n c.close()\n\ndef countPlayers():\n \"\"\"Returns the number of players currently registered.\"\"\"\n c = connect()\n cursor = c.cursor()\n # Count columns in player.\n cursor.execute('select count(*) from player;')\n rows = cursor.fetchall()\n c.close()\n # Return the first entry which is the count.\n return rows[0][0]\n\n\ndef registerPlayer(name):\n \"\"\"Adds a player to the tournament database.\n \n The database assigns a unique serial id number for the player. (This\n should be handled by your SQL database schema, not in your Python code.)\n \n Args:\n name: the player's full name (need not be unique).\n \"\"\"\n c = connect()\n cursor = c.cursor()\n # Insert a player's name, id is generated automatically.\n cursor.execute('insert into player (name) values (%s)', (name,))\n c.commit()\n c.close()\n\n\ndef playerStandings():\n \"\"\"Returns a list of the players and their win records, sorted by wins.\n\n The first entry in the list should be the player in first place, or a player\n tied for first place if there is currently a tie.\n\n Returns:\n A list of tuples, each of which contains (id, name, wins, matches):\n id: the player's unique id (assigned by the database)\n name: the player's full name (as registered)\n wins: the number of matches the player has won\n matches: the number of matches the player has played\n \"\"\"\n c = connect()\n cursor = c.cursor()\n # Combine player table with views of winstat and matchstat.\n # Sort the player according to # of wins and # of matches. Players having more wins and less matches have higher ranks. \n cursor.execute('select player.id, name, wins, matches from player, winstat, matchstat where player.id=winstat.id and player.id=matchstat.id order by wins desc,matches;')\n rows = cursor.fetchall()\n \n c.close()\n # Return the list of player standings called rows.\n return rows\n\ndef reportMatch(winner, loser):\n \"\"\"Records the outcome of a single match between two players.\n\n Args:\n winner: the id number of the player who won\n loser: the id number of the player who lost\n \"\"\"\n c = connect()\n cursor = c.cursor()\n # Insert the match with winner and loser.\n cursor.execute('insert into match (winner, loser) values (%s,%s) returning id', (winner,loser))\n c.commit()\n c.close()\n\n\ndef swissPairings():\n \"\"\"Returns a list of pairs of players for the next round of a match.\n \n Assuming that there are an even number of players registered, each player\n appears exactly once in the pairings. Each player is paired with another\n player with an equal or nearly-equal win record, that is, a player adjacent\n to him or her in the standings.\n \n Returns:\n A list of tuples, each of which contains (id1, name1, id2, name2)\n id1: the first player's unique id\n name1: the first player's name\n id2: the second player's unique id\n name2: the second player's name\n \"\"\"\n # Get the ranks.\n orders = playerStandings()\n # List to contain player pair temporarily.\n li = []\n # List to contain all the tuples of player pairs.\n total = []\n # A boolean variable to distinguish odd or even order of player standing.\n count = False\n for item in orders:\n # Player id and name are appended to temporary container.\n li.append(item[0])\n li.append(item[1])\n if count:\n # Pair is appended to the final container and then empty the temporary container.\n total.append(tuple(li))\n li = []\n count = not count\n # Return the list of all the tuples of player pairs.\n return total\n","sub_path":"vagrant/tournament/tournament.py","file_name":"tournament.py","file_ext":"py","file_size_in_byte":4392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"94313032","text":"\"\"\"My Customized bollinger Buyin Strategy\"\"\"\r\nimport talib\r\n\r\ndef init(context):\r\n context.strategyName = 'mybollinger_strategy' \r\n context.PERIOD = 20\r\n context.FACTOR = 2\r\n \r\n #context.BUYRATIO = 0.2\r\n #context.SELLRATIO = 0.25\r\n\r\ndef handle_bar(context,bar_dict):\r\n stocks = []\r\n if isinstance(context.STOCK,str):\r\n stocks.append(context.STOCK)\r\n elif isinstance(context.STOCK,list):\r\n stocks = context.STOCK\r\n \r\n BUYRATIO = context.TURNING_ARG01 / 100\r\n SELLRATIO = context.TURNING_ARG02 / 100\r\n \r\n for s in stocks:\r\n prices = history_bars(s,context.PERIOD + 1,'1d','close')\r\n # EMA(20)均线\r\n mediumline = talib.EMA(prices, context.PERIOD) \r\n # EMA(20)均值标准差\r\n stddev = talib.STDDEV(prices,context.PERIOD)\r\n # Bollingar upper line\r\n upperLine = mediumline + context.FACTOR * stddev \r\n # Bollingar low line\r\n lowerLine = mediumline - context.FACTOR * stddev \r\n # Current Position\r\n curpos = context.portfolio.positions[s].quantity\r\n \r\n # 当收益率高于0.1时,卖出该股票适当份额。\r\n if curpos > 0:\r\n cumReturnRatio = ( prices[-1] - context.portfolio.positions[s].avg_price)/context.portfolio.positions[s].avg_price\r\n if cumReturnRatio >= 0.1: \r\n shares = curpos * SELLRATIO \r\n order_shares(s,-shares)\r\n \r\n # 当收盘价小于下轨值时,买入股票适当份额\r\n if prices[-1] < lowerLine[-1]: \r\n order_value(s, context.portfolio.cash * BUYRATIO) \r\n","sub_path":"hdh_alpha/hdh_alpha/strategies/mybollinger_strategy.py","file_name":"mybollinger_strategy.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"418124464","text":"from turtle import *\nspeed(-1)\ncolor('red','yellow')\nfor n in range(9,2,-1):\n if n%2!=0:\n color('green','yellow')\n else:\n color('red','purple')\n begin_fill()\n for i in range(n):\n forward(100)\n left(180-180*(n-2)/n)\n end_fill()\nmainloop()\n","sub_path":"Homework 2.py","file_name":"Homework 2.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"622227920","text":"#!/usr/bin/python3\n#date: 04/11/2020\n\noperation = input()\nmatriz = []\njumper = 0 #makes the diagonal\nsomatorio = 0\namount = 0 #amount of times somatorio was added\n\n#1) creates all slots of the matrix\nfor i in range(12):\n\tmatriz = matriz + [[0]*12]\n\n#2) puts the float inputs inside all sublists' indexes\nfor i in range(12):\n\tfor index in range(12):\n\t\tmatriz[i][index] = float(input())\n\n#print(len(matriz)) #DEBUGGER\n\n#3) delimiting the diagonal DEBUGGER\n'''\nfor i in range(12):\n\tprint(matriz[i][jumper])\n\tjumper = jumper + 1\n'''\n#4) Summation of elements above diagonal.\nfor i in range(12):\n\tfor index in range(12):\n\t\tif index <= jumper: \n\t\t#if the index value is lower or equal to jumper, ignore and jump a step.\n\t\t\tcontinue \n\t\t\t#jumps the step if index value is lower or equal to jumper\n\t\tsomatorio = somatorio + matriz[i][index]\n\t\tamount = amount + 1\n\t\t#since we are skipping the steps that doesn't count, \n\t\t#we can just add the values to somatorio.\t\n\n\tjumper = jumper + 1\n\t#here, jumper is incremented. \n\t#It's important to be after the second \n\t#for block and in the same indentation depth.\n\n'''DEBUGGER\nfor i in matriz:\n\tprint(i)\n'''\n\n#5) using if statements to check the binary choice\nif operation == 'S':\n\tprint(\"{:.1f}\".format(somatorio))\n\nif operation == 'M':\n\tmedia = (somatorio/amount)\n\tprint(\"{:.1f}\".format(media))\n","sub_path":"URI-VOAL/1183.py","file_name":"1183.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"223830072","text":"class Solution:\n def participite(self, listSort, left, right):\n girl = left+1\n standard = listSort[left]\n for boy in range(left+1, right+1):\n if listSort[boy] <= standard:\n listSort[boy], listSort[girl] = listSort[girl], listSort[boy]\n girl += 1\n\n listSort[left], listSort[girl-1] = listSort[girl-1], listSort[left]\n return girl-1\n\n def quikSort(self, listSort, left, right):\n if left >= right:\n return\n pi = self.participite(listSort, left, right)\n\n self.quikSort(listSort, left, pi-1)\n self.quikSort(listSort, pi+1, right)\n\n return listSort\n\n\n\n\ntest = Solution()\nlistSort = [4, 2, 3, 5, 8, 1, 9, 0, -3]\nprint(test.quikSort(listSort, 0, 8))\n\n","sub_path":"leetcode/排序/快速排序.py","file_name":"快速排序.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"133544883","text":"\"\"\" Compiled: 2020-09-18 10:38:49 \"\"\"\n\n#__src_file__ = \"extensions/confirmation/etc/FConfirmationSwiftXMLFieldsTemplate.py\"\n\"\"\"----------------------------------------------------------------------------\nMODULE\n FConfirmationSwiftXMLFieldsTemplate -\n\nDESCRIPTION\n Changes to any of these settings require a restart of both the\n confirmation ATS and the documentation ATS for the changes to\n take affect.\n----------------------------------------------------------------------------\"\"\"\n\n# --------------\n# FIELDS\n# --------------\n# Changes in the following fields trigger corresponding confirmation update\n\nfield_dict = {}\n\n# confirmation\nfield_dict['CONFIRMATION'] = \\\n ['CHASER_CUTOFF', 'CHASING_SEQNBR', 'CONFIRMATION_SEQNBR', \n 'CONF_TEMPLATE_CHLNBR', 'DOCUMENT', 'MANUAL_MATCH', 'RESET_RESNBR',\n 'STATUS', 'STATUS_EXPLANATION', 'TRANSPORT', 'TRDNBR', 'UPDAT_USRNBR']\n\n# party\nfield_dict['PARTY'] = \\\n ['ADDRESS', 'ADDRESS2', 'ATTENTION', 'CALCAGENT', 'CITY', 'CONTACT1',\n 'CONTACT2', 'CORRESPONDENT_BANK', 'COUNTRY', 'DOCUMENT_DATE',\n 'DOCUMENT_TYPE_CHLNBR', 'EMAIL', 'EXTERNAL_CUTOFF', 'FAX', 'FREE1',\n 'FREE2', 'FREE3', 'FREE4', 'FREE5', 'FREE1_CHLNBR', 'FREE2_CHLNBR',\n 'FREE3_CHLNBR', 'FREE4_CHLNBR', 'FULLNAME', 'FULLNAME2',\n 'GUARANTOR_PTYNBR', 'INTERNAL_CUTOFF', 'ISDA_MEMBER', 'ISSUER',\n 'LEGAL_FORM_CHLNBR', 'NOTIFY_RECEIPT', 'PARENT_PTYNBR', 'PTYID', 'PTYID2',\n 'SWIFT', 'TELEPHONE', 'TELEX', 'TIME_ZONE', 'TYPE', 'ZIPCODE']\n \n# party alias\nfield_dict['PARTYALIAS'] = \\\n ['ALIAS', 'PTYNBR', 'TYPE']\n\n# agreement\nfield_dict['AGREEMENT'] = \\\n ['COUNTERPARTY_PTYNBR', 'DATED', 'DOCUMENT_TYPE_CHLNBR', 'INSTYPE',\n 'INTERNDEPT_PTYNBR', 'UND_INSTYPE']\n\n# account\nfield_dict['ACCOUNT'] = \\\n ['ACCOUNT', 'ACCOUNT2', 'ACCOUNT3', 'ACCOUNT4', 'ACCOUNT5', 'CURR', 'NAME',\n 'SWIFT', 'SWIFT2', 'SWIFT3', 'SWIFT4', 'DETAILS_OF_CHARGES', 'BIC_SEQNBR',\n 'BIC2_SEQNBR', 'BIC3_SEQNBR', 'BIC4_SEQNBR', 'BIC5_SEQNBR',\n 'NETWORK_ALIAS_TYPE', 'NETWORK_ALIAS_SEQNBR', 'CORRESPONDENT_BANK_PTYNBR',\n 'CORRESPONDENT_BANK2_PTYNBR', 'CORRESPONDENT_BANK3_PTYNBR',\n 'CORRESPONDENT_BANK4_PTYNBR', 'CORRESPONDENT_BANK5_PTYNBR',\n 'INTERNAL_CUTOFF', 'EXTERNAL_CUTOFF', 'ACCOUNT_TYPE']\n \n#trade\nfield_dict['TRADE'] = ['TRDNBR']\n\n# trade account link\nfield_dict['TRADEACCOUNTLINK'] = []","sub_path":"Extensions/Confirmation/FPythonCode/FConfirmationSwiftXMLFieldsTemplate.py","file_name":"FConfirmationSwiftXMLFieldsTemplate.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"519365861","text":"#!/usr/bin/env python\n\nfrom flexbe_core import EventState, Logger\nfrom flexbe_core.proxy import ProxySubscriberCached\nimport rostopic\nimport inspect\nfrom std_msgs.msg import Bool\n\n\nclass ContinueButton(EventState):\n '''\n Reads on a topic to see for the continue button.\n\n <= done Continue if button pressed.\n\n '''\n\n def __init__(self):\n '''\n Constructor\n '''\n super(ContinueButton, self).__init__(outcomes=['true', 'false'])\n self._topic = \"/continue_button\"\n self._connected = False\n\n self._sub = ProxySubscriberCached({self._topic: Bool})\n\n def execute(self, userdata):\n\n Logger.loginfo('Waiting for the continue button')\n if self._sub.has_msg(self._topic):\n message = self._sub.get_last_msg(self._topic)\n self._sub.remove_last_msg(self._topic)\n if message.data:\n return 'true'\n else:\n return 'false'\n","sub_path":"sara_flexbe_states/src/sara_flexbe_states/continue_button.py","file_name":"continue_button.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"288007330","text":"import sys\nimport pygame\nimport random\nimport math\nfrom pygame import mixer\n\n# Initialize the pygame.\npygame.init()\n\n# Background music and game over music\ngame_over_sound = mixer.Sound(\"gameover.wav\")\nmixer.music.load(\"backgroundmusic.wav\")\nmixer.music.play(-1)\n\n\n# Setting the screen sizes. Where 800 is width and 600 is height.\nscreen = pygame.display.set_mode((800, 600))\n\n# Setting background image\nbackground = pygame.image.load(\"back_ground.png\")\n\n\n# Caption and Icon.\npygame.display.set_caption(\"Space Invaders\")\nicon = pygame.image.load('enemy.png')\npygame.display.set_icon(icon)\n\n# Player and its position\nplayer_image = pygame.image.load('player.png')\nplayerX = 375\nplayerY = 500\nplayerX_change = 0\n\n# Enemy\nenemy_image = []\nenemyX = []\nenemyY = []\nenemyX_change = []\nenemyY_change = []\nno_of_enemies = 6\n\n\nfor i in range(no_of_enemies):\n enemy_image.append(pygame.image.load('enemy.png'))\n enemyX.append(random.randint(0, 736))\n enemyY.append(random.randint(50, 200))\n enemyX_change.append(3)\n enemyY_change.append(40)\n\n# Bullet\nbullet_image = pygame.image.load('bullet.png')\nbulletX = 0\nbulletY = 480\nbulletX_change = 0\nbulletY_change = 20\nbullet_state = \"ready\"\n\n\n# Score\nscore_value = 0\nfont = pygame.font.Font(\"stargedi.TTF\", 32)\ntextX = 10\ntextY = 10\n\n# Game over text\ngame_over = pygame.font.Font(\"stargedi.TTF\", 64)\n\n\ndef game_over_music():\n mixer.music.stop()\n mixer.Sound.play(game_over_sound)\n\n\ndef show_score(x, y):\n score = font.render(\"Score : \" + str(score_value), True, (255, 255, 255))\n screen.blit(score, (x, y))\n\n\ndef player(x, y):\n # blit means TO DRAW\n screen.blit(player_image, (x, y))\n\n\ndef enemy(x, y, i):\n screen.blit(enemy_image[i], (x, y))\n\n\ndef fire_bullet(x, y):\n global bullet_state\n bullet_state = \"fire\"\n screen.blit(bullet_image, (x + 16, y + 10))\n\n\ndef isCollision(enemyX, enemyY, bulletX, bulletY):\n distance = math.sqrt((math.pow(enemyX - bulletX, 2)) + (math.pow(enemyY - bulletY, 2)))\n if distance < 25:\n return True\n else:\n return False\n\n\ndef game_over_text():\n text = game_over.render(\"Game over\", True, (255, 255, 255))\n screen.blit(text, (200, 250))\n\n\n# To make the screen appear constantly.\nwhile True:\n # Screen.fill is placed in while loop because it should appear constantly as the screen. RGB - red, green, blue\n screen.fill((0, 0, 0))\n\n # Background image set\n screen.blit(background, (0, 0))\n\n for event in pygame.event.get():\n\n # Key Stroke left or right\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n playerX_change = -5\n if event.key == pygame.K_RIGHT:\n playerX_change = 5\n if event.key == pygame.K_SPACE:\n if bullet_state is \"ready\":\n bulletX = playerX\n bullet_sound = mixer.Sound(\"laser.wav\")\n bullet_sound.play()\n # Get the current X coordinates of player (Spaceship)\n fire_bullet(bulletX, bulletY)\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\n playerX_change = 0\n\n # To exit the game\n if event.type == pygame.QUIT:\n sys.exit()\n\n # Checking for player boundaries so it doesn't go out of bounds\n # Player Movement\n playerX += playerX_change\n if playerX <= 0:\n playerX = 0\n elif playerX >= 736:\n playerX = 736\n\n # Checking for enemy boundaries X position so it doesn't go out of bounds\n # Enemy Movement\n for i in range(no_of_enemies):\n\n # Game over\n if enemyY[i] > 450:\n for j in range(no_of_enemies):\n enemyY[j] = 2000\n game_over_text()\n game_over_music()\n\n enemyX[i] += enemyX_change[i]\n if enemyX[i] <= 0:\n enemyX_change[i] = 2.5\n enemyY[i] += enemyY_change[i]\n elif enemyX[i] >= 736:\n enemyX_change[i] = -2.5\n enemyY[i] += enemyY_change[i]\n\n # Collision\n collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY)\n if collision:\n collision_sound = mixer.Sound(\"blast.wav\")\n collision_sound.play()\n bulletY = 480\n bullet_state = \"ready\"\n score_value = score_value + 1\n enemyX[i] = random.randint(0, 736)\n enemyY[i] = random.randint(50, 200)\n\n if score_value % 10 == 0 and score_value != 0:\n enemyY_change[i] += 0.1\n\n enemy(enemyX[i], enemyY[i], i)\n\n # Bullet Movement\n if bullet_state is \"fire\":\n fire_bullet(bulletX, bulletY)\n bulletY -= bulletY_change\n if bulletY <= 0:\n bulletY = 480\n bullet_state = \"ready\"\n\n player(playerX, playerY)\n show_score(textX, textY)\n\n# Every time when a new element is included the display has to be UPDATED.\n pygame.display.update()\n","sub_path":"Space Invaders/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"256268959","text":"import sys\nimport os\nimport commands\n\ndef main(*args):\n files = os.listdir(os.environ['HOME']+\"/.android/avd\")\n avds = []\n for file in files:\n if file[-4:]==\".avd\":\n avds.append(file[:-4])\n\n return \",\".join(avds)\n\nif __name__ == \"__main__\":\n sys.stdout.write(main(*sys.argv))","sub_path":"Support/onebit/bash/listavds.py","file_name":"listavds.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"255154599","text":"#!/usr/bin/python\n\nimport sys, xlrd, xlsxwriter\nfrom helperFuncs import *\n\n# Merging data from different XLS files into common XLS\n# python mergeXls.py -c setup/home.ini\n\ndef sortXls(xls, sortedXls):\n\t''' The common XLS will have companies in random order \n\tCode from http://stackoverflow.com/a/9125563 '''\n\n\ttarget_column = 0\n\n\tbook = xlrd.open_workbook(xls)\n\tsheet = book.sheets()[0]\n\tdata = [sheet.row_values(i) for i in xrange(sheet.nrows)]\n\tlabels = data[0]; data = data[1:]\n\tdata.sort(key=lambda x: x[target_column], reverse=True)\n\n\tdata = filter(None, data)\n\n\twbk = xlsxwriter.Workbook(sortedXls)\n\tsheet = wbk.add_worksheet(sheet.name)\n\n\tfor idx, label in enumerate(labels):\n\t\tsheet.write(0, idx, label)\n\n\tfor idx_r, row in enumerate(data):\n\t\tfor idx_c, value in enumerate(row):\n\t\t\tsheet.write(idx_r+1, idx_c, value)\n\n\twbk.close()\n\ndef main(argv):\n\tbasedir = commonXLSStore = ''\n\t(basedir, commonXLSStore) = readArgs(argv)\n\n\tos.system('rm -f ' + commonXLSStore + '/All_companies_CTR.xlsx')\n\tos.system('rm -f ' + basedir + '/All_companies_CTR.xlsx')\n\n\tcommonWorkbook = xlsxwriter.Workbook(commonXLSStore + '/All_companies_CTR.xlsx')\n\tcommonWorksheet = commonWorkbook.add_worksheet()\n\t\n\txlsRowOffset = 0; printHeader = True\n\n\tfor xls in getFiles(commonXLSStore):\n\t\tworkbook = xlrd.open_workbook(commonXLSStore + '/' + xls)\n\n\t\tfor worksheet_name in workbook.sheet_names():\n\t\t\tworksheet = workbook.sheet_by_name(worksheet_name)\n\n\t\t\tif printHeader:\n\t\t\t\trowStart = 0\n\t\t\t\txlsRowOffset = 1\n\t\t\t\tcommonWorksheet.write(0, 0, 'Company name')\n\t\t\t\tprintHeader = False\n\t\t\telse:\n\t\t\t\trowStart = 1\n\t\t\t\txlsRowOffset += worksheet.nrows\n\t\t\t\n\t\t\tfor cur_row in range(rowStart, worksheet.nrows):\n\t\t\t\tfor cur_column in range(0, worksheet.ncols):\n\t\t\t\t\tcur_value = worksheet.cell_value(cur_row, cur_column)\n\n\t\t\t\t\trowToWriteTo = cur_row + xlsRowOffset - 1\n\t\t\t\t\tif rowToWriteTo != 0:\n\t\t\t\t\t\tcommonWorksheet.write(rowToWriteTo, 0, re.sub('_CTR\\.xlsx', '', xls))\n\t\t\t\t\tcommonWorksheet.write(rowToWriteTo, (cur_column + 1), cur_value)\n\n\tcommonWorkbook.close()\n\tsortXls(commonXLSStore + '/All_companies_CTR.xlsx', basedir + '/All_companies_CTR.xlsx')\n\nif __name__ == \"__main__\":\n\tmain(sys.argv[1:])","sub_path":"code-experiments/SciencePapersScripts/campaign-count/mergeXls.py","file_name":"mergeXls.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"464104008","text":"from pymongo import MongoClient\r\n\r\n\"\"\"\r\nThis script create a person database.\r\nThe format of json file includes GSM Tower coordinates.\r\nEvery successive coordinate represent one point.\r\nFor example, if there are 12 points lat-lon in the json file, person rotation created with 4 points.\r\nAlso json file includes range list. This is used for trilateration calculation.\r\n\"\"\"\r\n\r\ndef add_db(person,phone,coord_list):\r\n\r\n client = MongoClient('localhost',27017)\r\n\r\n db = client['position_latlon']\r\n\r\n col = db.positions\r\n\r\n\r\n record= {\r\n \"person\" : person,\r\n \"phone number\" : phone,\r\n \"geometry\" : {\r\n \"type\": \"Point\",\r\n \"coordinates\" : [coord_list]\r\n }\r\n }\r\n\r\n col.insert_many([record])\r\n\r\n\r\ndef db_dynamic(person,phone,Ip,coord_list):\r\n\r\n client = MongoClient('localhost',27017)\r\n\r\n db = client['points_latlon']\r\n\r\n col = db.dynamic_position\r\n\r\n\r\n record= {\r\n \"person\" : person,\r\n \"ıp\": Ip,\r\n \"phone number\" : phone,\r\n \"geometry\" : {\r\n \"type\": \"Line-String\",\r\n \"coordinates\" : [coord_list]\r\n }\r\n }\r\n\r\n col.insert_many([record])","sub_path":"exact_location.py","file_name":"exact_location.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"39752784","text":"\"\"\"\nBridge Python and Julia by initializing the Julia interpreter inside Python.\n\"\"\"\n\n#-----------------------------------------------------------------------------\n# Copyright (C) 2013 The IPython and Julia Development Teams.\n#\n# Distributed under the terms of the BSD License. The full license is in\n# the file COPYING, distributed as part of this software.\n#-----------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------\n# Imports\n#-----------------------------------------------------------------------------\n\n# Stdlib\nfrom __future__ import print_function, absolute_import\n\nfrom logging import getLogger\n# Not importing `logging` module here so that using `logging.debug`\n# instead of `logger.debug` becomes an error.\n\nimport atexit\nimport ctypes\nimport ctypes.util\nimport os\nimport sys\nimport subprocess\nimport warnings\n\nfrom ctypes import c_void_p as void_p\nfrom ctypes import c_char_p as char_p\nfrom ctypes import py_object, c_int, c_char_p, POINTER, pointer\n\ntry:\n from shutil import which\nexcept ImportError:\n # For Python < 3.3; it should behave more-or-less similar to\n # shutil.which when used with single argument.\n from distutils.spawn import find_executable as which\n\ntry:\n from os.path import samefile\nexcept ImportError:\n # For Python < 3.2 in Windows:\n def samefile(f1, f2):\n a = os.path.realpath(os.path.normcase(f1))\n b = os.path.realpath(os.path.normcase(f2))\n return a == b\n\n\n# this is python 3.3 specific\nfrom types import ModuleType\n\nfrom .find_libpython import find_libpython, linked_libpython\nfrom .options import JuliaOptions, parse_jl_options\n\ntry:\n string_types = (basestring,)\nexcept NameError:\n string_types = (str,)\n\n#-----------------------------------------------------------------------------\n# Classes and funtions\n#-----------------------------------------------------------------------------\npython_version = sys.version_info\n\n\nlogger = getLogger(\"julia\")\n_loghandler = None\n\n\ndef get_loghandler():\n \"\"\"\n Get `logging.StreamHandler` private to PyJulia.\n \"\"\"\n global _loghandler\n if _loghandler is None:\n import logging\n\n formatter = logging.Formatter(\"%(levelname)s %(message)s\")\n\n _loghandler = logging.StreamHandler()\n _loghandler.setFormatter(formatter)\n\n logger.addHandler(_loghandler)\n return _loghandler\n\n\ndef set_loglevel(level):\n import logging\n\n get_loghandler()\n logger.setLevel(getattr(logging, level, level))\n\n\ndef enable_debug():\n set_loglevel(\"DEBUG\")\n\n\n# As setting up Julia modifies os.environ, we need to cache it for\n# launching subprocesses later in the original environment.\n_enviorn = os.environ.copy()\n\n\nclass JuliaError(Exception):\n \"\"\"\n Wrapper for Julia exceptions.\n \"\"\"\n\n\ndef remove_prefix(string, prefix):\n return string[len(prefix):] if string.startswith(prefix) else string\n\n\ndef jl_name(name):\n if name.endswith('_b'):\n return name[:-2] + '!'\n return name\n\n\ndef py_name(name):\n if name.endswith('!'):\n return name[:-1] + '_b'\n return name\n\n\nclass JuliaModule(ModuleType):\n\n def __init__(self, loader, *args, **kwargs):\n super(JuliaModule, self).__init__(*args, **kwargs)\n self._julia = loader.julia\n self.__loader__ = loader\n\n @property\n def __all__(self):\n juliapath = remove_prefix(self.__name__, \"julia.\")\n names = set(self._julia.eval(\"names({})\".format(juliapath)))\n names.discard(juliapath.rsplit('.', 1)[-1])\n return [py_name(n) for n in names if is_accessible_name(n)]\n\n def __dir__(self):\n if python_version.major == 2:\n names = set()\n else:\n names = set(super(JuliaModule, self).__dir__())\n names.update(self.__all__)\n return list(names)\n # Override __dir__ method so that completing member names work\n # well in Python REPLs like IPython.\n\n __path__ = ()\n # Declare that `JuliaModule` is a Python module since any Julia\n # module can have sub-modules.\n # See: https://docs.python.org/3/reference/import.html#package-path-rules\n\n def __getattr__(self, name):\n try:\n return self.__try_getattr(name)\n except AttributeError:\n if name.endswith(\"_b\"):\n try:\n return self.__try_getattr(jl_name(name))\n except AttributeError:\n pass\n raise\n\n def __try_getattr(self, name):\n jl_module = remove_prefix(self.__name__, \"julia.\")\n jl_fullname = \".\".join((jl_module, name))\n\n if isamodule(self._julia, jl_fullname):\n realname = self._julia.fullname(self._julia.eval(jl_fullname))\n if self._julia.isdefined(realname):\n return self.__loader__.load_module(\"julia.\" + realname)\n # Otherwise, it may be, e.g., \"Main.anonymous\", created by\n # Module().\n\n if isdefined(self._julia, jl_module, name):\n return self._julia.eval(jl_fullname)\n\n raise AttributeError(name)\n\n\nclass JuliaMainModule(JuliaModule):\n\n def __setattr__(self, name, value):\n if name.startswith('_'):\n super(JuliaMainModule, self).__setattr__(name, value)\n else:\n juliapath = remove_prefix(self.__name__, \"julia.\")\n setter = '''\n PyCall.pyfunctionret(\n (x) -> Base.eval({}, :({} = $x)),\n Any,\n PyCall.PyAny)\n '''.format(juliapath, jl_name(name))\n self._julia.eval(setter)(value)\n\n help = property(lambda self: self._julia.help)\n eval = property(lambda self: self._julia.eval)\n using = property(lambda self: self._julia.using)\n\n\n# add custom import behavior for the julia \"module\"\nclass JuliaImporter(object):\n\n # find_module was deprecated in v3.4\n def find_module(self, fullname, path=None):\n if fullname.startswith(\"julia.\"):\n filename = fullname.split(\".\", 2)[1]\n filepath = os.path.join(os.path.dirname(__file__), filename)\n if os.path.isfile(filepath + \".py\") or os.path.isdir(filepath):\n return\n return JuliaModuleLoader()\n\n\nclass JuliaModuleLoader(object):\n\n @property\n def julia(self):\n self.__class__.julia = julia = Julia()\n return julia\n\n # load module was deprecated in v3.4\n def load_module(self, fullname):\n juliapath = remove_prefix(fullname, \"julia.\")\n if juliapath == 'Main':\n return sys.modules.setdefault(fullname,\n JuliaMainModule(self, fullname))\n elif isafunction(self.julia, juliapath):\n return self.julia.eval(juliapath)\n\n try:\n self.julia.eval(\"import {}\".format(juliapath.split(\".\", 1)[0]))\n except JuliaError:\n pass\n else:\n if isamodule(self.julia, juliapath):\n return sys.modules.setdefault(fullname,\n JuliaModule(self, fullname))\n\n raise ImportError(\"{} not found\".format(juliapath))\n\n\ndef ismacro(name):\n \"\"\" Is the name a macro?\n\n >>> ismacro('@time')\n True\n >>> ismacro('sum')\n False\n \"\"\"\n return name.startswith(\"@\")\n\n\ndef isoperator(name):\n return not name[0].isalpha()\n\n\ndef isprotected(name):\n return name.startswith(\"_\")\n\n\ndef notascii(name):\n try:\n name.encode(\"ascii\")\n return False\n except:\n return True\n\n\ndef is_accessible_name(name):\n \"\"\"\n Check if a Julia variable `name` is (easily) accessible from Python.\n\n Return `True` if `name` can be safely converted to a Python\n identifier using `py_name` function. For example,\n\n >>> is_accessible_name('A_mul_B!')\n True\n\n Since it can be accessed as `A_mul_B_b` in Python.\n \"\"\"\n return not (ismacro(name) or\n isoperator(name) or\n isprotected(name) or\n notascii(name))\n\n\ndef isdefined(julia, parent, member):\n return julia.eval(\"isdefined({}, :({}))\".format(parent, member))\n\n\ndef isamodule(julia, julia_name):\n try:\n return julia.eval(\"isa({}, Module)\".format(julia_name))\n except JuliaError:\n return False # assuming this is an `UndefVarError`\n\n\ndef isafunction(julia, julia_name, mod_name=\"\"):\n code = \"isa({}, Function)\".format(julia_name)\n if mod_name:\n code = \"isa({}.{}, Function)\".format(mod_name, julia_name)\n try:\n return julia.eval(code)\n except:\n return False\n\n\ndef determine_if_statically_linked():\n \"\"\"Determines if this python executable is statically linked\"\"\"\n return linked_libpython() is None\n\n\njuliainfo_script = \"\"\"\nprintln(VERSION < v\"0.7.0-DEV.3073\" ? JULIA_HOME : Base.Sys.BINDIR)\nif VERSION >= v\"0.7.0-DEV.3630\"\n using Libdl\n using Pkg\nend\nprintln(Libdl.dlpath(string(\"lib\", splitext(Base.julia_exename())[1])))\nprintln(unsafe_string(Base.JLOptions().image_file))\n\nprintln(VERSION)\nprintln(VERSION.major)\nprintln(VERSION.minor)\nprintln(VERSION.patch)\n\nif VERSION < v\"0.7.0\"\n PyCall_depsfile = Pkg.dir(\"PyCall\",\"deps\",\"deps.jl\")\nelse\n modpath = Base.locate_package(Base.identify_package(\"PyCall\"))\n if modpath == nothing\n PyCall_depsfile = nothing\n else\n PyCall_depsfile = joinpath(dirname(modpath),\"..\",\"deps\",\"deps.jl\")\n end\nend\nif PyCall_depsfile !== nothing && isfile(PyCall_depsfile)\n include(PyCall_depsfile)\n println(pyprogramname)\n println(libpython)\nend\n\"\"\"\n\n\nclass JuliaInfo(object):\n \"\"\"\n Information required for initializing Julia runtime.\n\n Examples\n --------\n >>> from julia.api import JuliaInfo\n >>> info = JuliaInfo.load()\n >>> info = JuliaInfo.load(julia=\"julia\") # equivalent\n >>> info = JuliaInfo.load(julia=\"PATH/TO/julia\") # doctest: +SKIP\n >>> info.julia\n 'julia'\n >>> info.sysimage # doctest: +SKIP\n '/home/user/julia/lib/julia/sys.so'\n >>> info.python # doctest: +SKIP\n '/usr/bin/python3'\n >>> info.is_compatible_python() # doctest: +SKIP\n True\n\n Attributes\n ----------\n julia : str\n Path to a Julia executable from which information was retrieved.\n bindir : str\n ``Sys.BINDIR`` of `julia`.\n libjulia_path : str\n Path to libjulia.\n sysimage : str\n Path to system image.\n python : str\n Python executable with which PyCall.jl is configured.\n libpython_path : str\n libpython path used by PyCall.jl.\n \"\"\"\n\n @classmethod\n def load(cls, julia=\"julia\", **popen_kwargs):\n \"\"\"\n Get basic information from `julia`.\n \"\"\"\n\n # Use the original environment variables to avoid a cryptic\n # error \"fake-julia/../lib/julia/sys.so: cannot open shared\n # object file: No such file or directory\":\n popen_kwargs.setdefault(\"env\", _enviorn)\n\n proc = subprocess.Popen(\n [julia, \"--startup-file=no\", \"-e\", juliainfo_script],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n universal_newlines=True,\n **popen_kwargs)\n\n stdout, stderr = proc.communicate()\n retcode = proc.wait()\n if retcode != 0:\n if sys.version_info[0] < 3:\n output = \"\\n\".join([\"STDOUT:\", stdout, \"STDERR:\", stderr])\n raise subprocess.CalledProcessError(\n retcode, [julia, \"-e\", \"...\"], output\n )\n else:\n raise subprocess.CalledProcessError(\n retcode, [julia, \"-e\", \"...\"], stdout, stderr\n )\n\n stderr = stderr.strip()\n if stderr:\n warnings.warn(\"{} warned:\\n{}\".format(julia, stderr))\n\n args = stdout.rstrip().split(\"\\n\")\n\n return cls(julia, *args)\n\n def __init__(self, julia, bindir, libjulia_path, sysimage,\n version_raw, version_major, version_minor, version_patch,\n python=None, libpython_path=None):\n self.julia = julia\n self.bindir = bindir\n self.libjulia_path = libjulia_path\n self.sysimage = sysimage\n\n version_major = int(version_major)\n version_minor = int(version_minor)\n version_patch = int(version_patch)\n self.version_raw = version_raw\n self.version_major = version_major\n self.version_minor = version_minor\n self.version_patch = version_patch\n self.version_info = (version_major, version_minor, version_patch)\n\n self.python = python\n self.libpython_path = libpython_path\n\n logger.debug(\"pyprogramname = %s\", python)\n logger.debug(\"sys.executable = %s\", sys.executable)\n logger.debug(\"bindir = %s\", bindir)\n logger.debug(\"libjulia_path = %s\", libjulia_path)\n\n def is_compatible_python(self):\n \"\"\"\n Check if python used by PyCall.jl is compatible with `sys.executable`.\n \"\"\"\n return is_compatible_exe(self.libpython_path)\n\n\ndef is_compatible_exe(jl_libpython):\n \"\"\"\n Determine if `libpython` is compatible with this Python.\n\n Current Python executable is considered compatible if it is dynamically\n linked to libpython and both of them are using identical libpython. If\n this function returns `True`, PyJulia use the same precompilation cache\n of PyCall.jl used by Julia itself.\n \"\"\"\n py_libpython = linked_libpython()\n logger.debug(\"py_libpython = %s\", py_libpython)\n logger.debug(\"jl_libpython = %s\", jl_libpython)\n dynamically_linked = py_libpython is not None\n return dynamically_linked and samefile(py_libpython, jl_libpython)\n # `py_libpython is not None` here for checking if this Python\n # executable is dynamically linked or not (`py_libpython is None`\n # if it's statically linked). `jl_libpython` may be `None` if\n # libpython used for PyCall is removed so we can't expect\n # `jl_libpython` to be a `str` always.\n\n\ndef setup_libjulia(libjulia):\n # Store the running interpreter reference so we can start using it via self.call\n libjulia.jl_.argtypes = [void_p]\n libjulia.jl_.restype = None\n\n # Set the return types of some of the bridge functions in ctypes terminology\n libjulia.jl_eval_string.argtypes = [char_p]\n libjulia.jl_eval_string.restype = void_p\n\n libjulia.jl_exception_occurred.restype = void_p\n libjulia.jl_typeof_str.argtypes = [void_p]\n libjulia.jl_typeof_str.restype = char_p\n libjulia.jl_call2.argtypes = [void_p, void_p, void_p]\n libjulia.jl_call2.restype = void_p\n libjulia.jl_get_field.argtypes = [void_p, char_p]\n libjulia.jl_get_field.restype = void_p\n libjulia.jl_typename_str.restype = char_p\n libjulia.jl_unbox_voidpointer.argtypes = [void_p]\n libjulia.jl_unbox_voidpointer.restype = py_object\n\n for c_type in UNBOXABLE_TYPES:\n jl_unbox = getattr(libjulia, \"jl_unbox_{}\".format(c_type))\n jl_unbox.argtypes = [void_p]\n jl_unbox.restype = getattr(ctypes, \"c_{}\".format({\n \"float32\": \"float\",\n \"float64\": \"double\",\n }.get(c_type, c_type)))\n\n libjulia.jl_typeof.argtypes = [void_p]\n libjulia.jl_typeof.restype = void_p\n\n libjulia.jl_exception_clear.restype = None\n libjulia.jl_stderr_obj.argtypes = []\n libjulia.jl_stderr_obj.restype = void_p\n libjulia.jl_stderr_stream.argtypes = []\n libjulia.jl_stderr_stream.restype = void_p\n libjulia.jl_printf.restype = ctypes.c_int\n\n libjulia.jl_parse_opts.argtypes = [POINTER(c_int),\n POINTER(POINTER(c_char_p))]\n libjulia.jl_set_ARGS.argtypes = [c_int, POINTER(c_char_p)]\n libjulia.jl_atexit_hook.argtypes = [ctypes.c_int]\n\n\ntry:\n # A hack to make `_LIBJULIA` survive reload:\n _LIBJULIA\nexcept NameError:\n _LIBJULIA = None\n# Ugly hack to register the julia interpreter globally so we can reload\n# this extension without trying to re-open the shared lib, which kills\n# the python interpreter. Nasty but useful while debugging\n\n\ndef set_libjulia(libjulia):\n # Flag process-wide that Julia is initialized and store the actual\n # runtime interpreter, so we can reuse it across calls and module\n # reloads.\n global _LIBJULIA\n _LIBJULIA = libjulia\n\n\ndef get_libjulia():\n return _LIBJULIA\n\n\nclass BaseLibJulia(object):\n\n def __getattr__(self, name):\n return getattr(self.libjulia, name)\n\n\nclass LibJulia(BaseLibJulia):\n \"\"\"\n Low-level interface to `libjulia` C-API.\n\n Examples\n --------\n >>> from julia.api import LibJulia, JuliaInfo\n\n An easy way to create a `LibJulia` object is `LibJulia.load`:\n\n >>> api = LibJulia.load() # doctest: +SKIP\n\n Or, equivalently,\n\n >>> api = LibJulia.load(julia=\"julia\") # doctest: +SKIP\n >>> api = LibJulia.from_juliainfo(JuliaInfo.load()) # doctest: +SKIP\n\n You can pass a path to the Julia executable using `julia` keyword\n argument:\n\n >>> api = LibJulia.load(julia=\"PATH/TO/CUSTOM/julia\") # doctest: +SKIP\n\n .. Do not run doctest with non-default libjulia.so.\n >>> _ = getfixture(\"julia\")\n >>> api = get_libjulia()\n\n Path to the system image can be configured before initializing Julia:\n\n >>> api.sysimage # doctest: +SKIP\n '/home/user/julia/lib/julia/sys.so'\n >>> api.sysimage = \"PATH/TO/CUSTOM/sys.so\" # doctest: +SKIP\n\n Finally, the Julia runtime can be initialized using `LibJulia.init_julia`.\n Note that only the first call to this function in the current Python\n process takes effect.\n\n >>> api.init_julia()\n\n Any command-line options supported by Julia can be passed to\n `init_julia`:\n\n >>> api.init_julia([\"--compiled-modules=no\", \"--optimize=3\"])\n\n Once `init_julia` is called, any subsequent use of `Julia` API\n (thus also ``from julia import `` etc.) uses this\n initialized Julia runtime.\n\n `LibJulia` can be used to access Julia's C-API:\n\n >>> ret = api.jl_eval_string(b\"Int64(1 + 2)\")\n >>> int(api.jl_unbox_int64(ret))\n 3\n\n However, a proper use of the C-API is more involved and presumably\n very challenging without C macros. See also:\n https://docs.julialang.org/en/latest/manual/embedding/\n\n Attributes\n ----------\n libjulia_path : str\n Path to libjulia.\n bindir : str\n ``Sys.BINDIR`` of `julia`. This is passed to\n `jl_init_with_image` unless overridden by argument ``option``\n to `init_julia`.\n sysimage : str\n Path to system image. This is passed to `jl_init_with_image`\n unless overridden by argument ``option`` to `init_julia`.\n\n If `sysimage` is a relative path, it is interpreted relative\n to the current directory (rather than relative to the Julia\n `bindir` as in the `jl_init_with_image` C API).\n \"\"\"\n\n @classmethod\n def load(cls, **kwargs):\n \"\"\"\n Create `LibJulia` based on information retrieved with `JuliaInfo.load`.\n\n This classmethod runs `JuliaInfo.load` to retrieve information about\n `julia` runtime. This information is used to intialize `LibJulia`.\n \"\"\"\n return cls.from_juliainfo(JuliaInfo.load(**kwargs))\n\n @classmethod\n def from_juliainfo(cls, juliainfo):\n return cls(\n libjulia_path=juliainfo.libjulia_path,\n bindir=juliainfo.bindir,\n sysimage=juliainfo.sysimage,\n )\n\n def __init__(self, libjulia_path, bindir, sysimage):\n self.libjulia_path = libjulia_path\n self.bindir = bindir\n self.sysimage = sysimage\n\n if not os.path.exists(libjulia_path):\n raise RuntimeError(\"Julia library (\\\"libjulia\\\") not found! {}\".format(libjulia_path))\n\n # fixes a specific issue with python 2.7.13\n # ctypes.windll.LoadLibrary refuses unicode argument\n # http://bugs.python.org/issue29294\n if sys.version_info >= (2, 7, 13) and sys.version_info < (2, 7, 14):\n libjulia_path = libjulia_path.encode(\"ascii\")\n\n self.libjulia = ctypes.PyDLL(libjulia_path, ctypes.RTLD_GLOBAL)\n setup_libjulia(self.libjulia)\n\n @property\n def jl_init_with_image(self):\n try:\n return self.libjulia.jl_init_with_image\n except AttributeError:\n return self.libjulia.jl_init_with_image__threading\n\n def init_julia(self, options=None):\n \"\"\"\n Initialize `libjulia`. Calling this method twice is a no-op.\n\n It calls `jl_init_with_image` (or `jl_init_with_image__threading`)\n but makes sure that it is called only once for each process.\n\n Parameters\n ----------\n options : sequence of `str` or `JuliaOptions`\n This is passed as command line options to the Julia runtime.\n\n .. warning::\n\n Any invalid command line option terminates the entire\n Python process.\n \"\"\"\n if get_libjulia():\n return\n\n if hasattr(options, \"as_args\"): # JuliaOptions\n options = options.as_args()\n if options:\n # Let's materialize it here in case it's an iterator.\n options = list(options)\n # Record `options`. It's not used anywhere at the moment but\n # may be useful for debugging.\n self.options = options\n\n if options:\n ns = parse_jl_options(options)\n if ns.home:\n self.bindir = ns.home\n if ns.sysimage:\n self.sysimage = ns.sysimage\n\n # Julia tries to interpret `sysimage` as a relative path and\n # aborts if not found. Turning it to absolute path here.\n # Mutating `self.sysimage` so that the actual path used can be\n # retrieved later.\n if not os.path.isabs(self.sysimage):\n self.sysimage = os.path.realpath(self.sysimage)\n\n jl_init_path = self.bindir\n sysimage = self.sysimage\n\n if not os.path.isdir(jl_init_path):\n raise RuntimeError(\"jl_init_path (bindir) {} is not a directory\".format(jl_init_path))\n if not os.path.exists(sysimage):\n raise RuntimeError(\"System image {} does not exist\".format(sysimage))\n\n if options:\n assert not isinstance(options, str)\n # It seems that `argv_list[0]` is ignored and\n # `sys.executable` is used anyway:\n argv_list = [sys.executable]\n argv_list.extend(options)\n if sys.version_info[0] >= 3:\n argv_list = [s.encode('utf-8') for s in argv_list]\n\n argc = c_int(len(argv_list))\n argv = POINTER(char_p)((char_p * len(argv_list))(*argv_list))\n\n logger.debug(\"argv_list = %r\", argv_list)\n logger.debug(\"argc = %r\", argc)\n self.libjulia.jl_parse_opts(pointer(argc), pointer(argv))\n logger.debug(\"jl_parse_opts called\")\n logger.debug(\"argc = %r\", argc)\n for i in range(argc.value):\n logger.debug(\"argv[%d] = %r\", i, argv[i])\n\n logger.debug(\"calling jl_init_with_image(%s, %s)\", jl_init_path, sysimage)\n self.jl_init_with_image(jl_init_path.encode(\"utf-8\"), sysimage.encode(\"utf-8\"))\n logger.debug(\"seems to work...\")\n\n set_libjulia(self)\n\n self.libjulia.jl_exception_clear()\n\n if options:\n # This doesn't seem to be working.\n self.libjulia.jl_set_ARGS(argc, argv)\n\n\nclass InProcessLibJulia(BaseLibJulia):\n\n def __init__(self):\n # we're assuming here we're fully inside a running Julia process,\n # so we're fishing for symbols in our own process table\n self.libjulia = ctypes.PyDLL(None)\n\n setup_libjulia(self.libjulia)\n set_libjulia(self)\n\n\n_separate_cache_error_common_header = \"\"\"\\\nIt seems your Julia and PyJulia setup are not supported.\n\nJulia interpreter:\n {runtime}\nPython interpreter and libpython used by PyCall.jl:\n {jlinfo.python}\n {jl_libpython}\nPython interpreter used to import PyJulia and its libpython.\n {sys.executable}\n {py_libpython}\n\"\"\"\n\n\n_separate_cache_error_common_footer = \"\"\"\nFor more information, see:\n https://github.com/JuliaPy/pyjulia\n https://github.com/JuliaPy/PyCall.jl\n\"\"\"\n\n\n_separate_cache_error_statically_linked = \"\"\"\nYour Python interpreter \"{sys.executable}\"\nis statically linked to libpython. Currently, PyJulia does not support\nsuch Python interpreter. One easy workaround is to run your Python\nscript with `python-jl` command bundled in PyJulia. You can simply do:\n\n python-jl PATH/TO/YOUR/SCRIPT.py\n\nSee `python-jl --help` for more information.\n\nFor other available workarounds, see:\n https://github.com/JuliaPy/pyjulia#troubleshooting\n\"\"\"\n\n\n_separate_cache_error_incompatible_libpython = \"\"\"\nIn Julia >= 0.7, above two paths to `libpython` have to match exactly\nin order for PyJulia to work. To configure PyCall.jl to use Python\ninterpreter \"{sys.executable}\",\nrun the following commands in the Julia interpreter:\n\n ENV[\"PYTHON\"] = \"{sys.executable}\"\n using Pkg\n Pkg.build(\"PyCall\")\n\"\"\"\n\n\ndef raise_separate_cache_error(\n runtime, jlinfo,\n # For test:\n _determine_if_statically_linked=determine_if_statically_linked):\n template = _separate_cache_error_common_header\n if _determine_if_statically_linked():\n template += _separate_cache_error_statically_linked\n else:\n template += _separate_cache_error_incompatible_libpython\n template += _separate_cache_error_common_footer\n message = template.format(\n runtime=runtime,\n jlinfo=jlinfo,\n py_libpython=find_libpython(),\n jl_libpython=jlinfo.libpython_path,\n sys=sys)\n raise RuntimeError(message)\n\n\nUNBOXABLE_TYPES = (\n 'bool',\n 'int8',\n 'uint8',\n 'int16',\n 'uint16',\n 'int32',\n 'uint32',\n 'int64',\n 'uint64',\n 'float32',\n 'float64',\n)\n\n\nclass Julia(object):\n \"\"\"\n Implements a bridge to the Julia interpreter or library.\n This uses the Julia PyCall module to perform type conversions and allow\n full access to the entire Julia interpreter.\n \"\"\"\n\n def __init__(self, init_julia=True, jl_init_path=None, runtime=None,\n jl_runtime_path=None, debug=False, **julia_options):\n \"\"\"Create a Python object that represents a live Julia interpreter.\n\n Note: Use `LibJulia` to fully control the initialization of\n the Julia runtime.\n\n Parameters\n ==========\n\n init_julia : bool\n If True, try to initialize the Julia interpreter. If this code is\n being called from inside an already running Julia, the flag should\n be passed as False so the interpreter isn't re-initialized.\n\n Note that it is safe to call this class constructor twice in the\n same process with `init_julia` set to True, as a global reference\n is kept to avoid re-initializing it. The purpose of the flag is\n only to manage situations when Julia was initialized from outside\n this code.\n\n runtime : str (optional)\n Custom Julia binary, e.g. \"/usr/local/bin/julia\" or \"julia-1.0.0\".\n\n jl_init_path : str (optional)\n Path to give to jl_init relative to which we find sys.so,\n (defaults to jl_runtime_path or NULL)\n\n debug : bool\n If True, print some debugging information to STDERR\n\n Notes\n =====\n\n Other keyword arguments (e.g., `compiled_modules=False`) are treated\n as command line options. Only a subset of command line options is\n supported. See `julia.core.JuliaOptions.show_supported()` for the\n list of supported options.\n \"\"\"\n\n if debug:\n enable_debug()\n\n if jl_runtime_path is not None:\n warnings.warn(\n \"`jl_runtime_path` is deprecated. Please use `runtime`.\",\n DeprecationWarning)\n\n if runtime is None:\n if jl_runtime_path is None:\n runtime = \"julia\"\n else:\n runtime = jl_runtime_path\n else:\n if jl_runtime_path is None:\n jl_runtime_path = which(runtime)\n if jl_runtime_path is None:\n raise RuntimeError(\"Julia runtime {} cannot be found\"\n .format(runtime))\n else:\n raise TypeError(\n \"Both `runtime` and `jl_runtime_path` are specified.\")\n\n logger.debug(\"\") # so that debug message is shown nicely w/ pytest\n\n if get_libjulia():\n # Use pre-existing `LibJulia`.\n self.api = get_libjulia()\n elif init_julia:\n jlinfo = JuliaInfo.load(runtime)\n self.api = LibJulia.from_juliainfo(jlinfo)\n\n if jl_init_path:\n self.api.bindir = jl_init_path\n\n options = JuliaOptions(**julia_options)\n\n use_separate_cache = not (\n options.compiled_modules == \"no\" or jlinfo.is_compatible_python()\n )\n logger.debug(\"use_separate_cache = %s\", use_separate_cache)\n if use_separate_cache:\n PYCALL_JULIA_HOME = os.path.join(\n os.path.dirname(os.path.realpath(__file__)), \"fake-julia\").replace(\"\\\\\", \"\\\\\\\\\")\n os.environ[\"JULIA_HOME\"] = PYCALL_JULIA_HOME # TODO: this line can be removed when dropping Julia v0.6\n os.environ[\"JULIA_BINDIR\"] = PYCALL_JULIA_HOME\n self.api.bindir = PYCALL_JULIA_HOME\n\n self.api.init_julia(options)\n\n if use_separate_cache:\n if jlinfo.version_info < (0, 6):\n raise RuntimeError(\n \"PyJulia does not support Julia < 0.6 anymore\")\n elif jlinfo.version_info >= (0, 7):\n raise_separate_cache_error(runtime, jlinfo)\n # Intercept precompilation\n os.environ[\"PYCALL_PYTHON_EXE\"] = sys.executable\n os.environ[\"PYCALL_JULIA_HOME\"] = PYCALL_JULIA_HOME\n os.environ[\"PYJULIA_IMAGE_FILE\"] = jlinfo.sysimage\n os.environ[\"PYCALL_LIBJULIA_PATH\"] = os.path.dirname(jlinfo.libjulia_path)\n # Add a private cache directory. PyCall needs a different\n # configuration and so do any packages that depend on it.\n self._call(u\"unshift!(Base.LOAD_CACHE_PATH, abspath(Pkg.Dir._pkgroot(),\" +\n \"\\\"lib\\\", \\\"pyjulia%s-v$(VERSION.major).$(VERSION.minor)\\\"))\" % sys.version_info[0])\n\n # If PyCall.jl is already pre-compiled, for the global\n # environment, hide it while we are loading PyCall.jl\n # for PyJulia which has to compile a new cache if it\n # does not exist. However, Julia does not compile a\n # new cache if it exists in Base.LOAD_CACHE_PATH[2:end].\n # https://github.com/JuliaPy/pyjulia/issues/92#issuecomment-289303684\n self._call(u\"\"\"\n for path in Base.LOAD_CACHE_PATH[2:end]\n cache = joinpath(path, \"PyCall.ji\")\n backup = joinpath(path, \"PyCall.ji.backup\")\n if isfile(cache)\n mv(cache, backup; remove_destination=true)\n end\n end\n \"\"\")\n\n # This is mainly for initiating the precompilation:\n self._call(u\"using PyCall\")\n\n if use_separate_cache:\n self._call(u\"\"\"\n for path in Base.LOAD_CACHE_PATH[2:end]\n cache = joinpath(path, \"PyCall.ji\")\n backup = joinpath(path, \"PyCall.ji.backup\")\n if !isfile(cache) && isfile(backup)\n mv(backup, cache)\n end\n rm(backup; force=true)\n end\n \"\"\")\n\n jl_atexit_hook = self.api.jl_atexit_hook\n atexit.register(jl_atexit_hook, 0)\n else:\n self.api = InProcessLibJulia()\n\n # Currently, PyJulia assumes that `Main.PyCall` exsits. Thus, we need\n # to import `PyCall` again here in case `init_julia=False` is passed:\n self._call(u\"using PyCall\")\n\n # Whether we initialized Julia or not, we MUST create at least one\n # instance of PyObject and the convert function. Since these will be\n # needed on every call, we hold them in the Julia object itself so\n # they can survive across reinitializations.\n self._PyObject = self._call(\"PyCall.PyObject\")\n self._convert = self._call(\"convert\")\n\n self.sprint = self.eval('sprint')\n self.showerror = self.eval('showerror')\n\n if self.eval('VERSION >= v\"0.7-\"'):\n self.eval(\"@eval Main import Base.MainInclude: eval, include\")\n # https://github.com/JuliaLang/julia/issues/28825\n\n if not isdefined(self, \"Main\", \"_PyJuliaHelper\"):\n self.eval(\"include\")(\n os.path.join(\n os.path.dirname(os.path.realpath(__file__)), \"pyjulia_helper.jl\"\n )\n )\n\n def _call(self, src):\n \"\"\"\n Low-level call to execute a snippet of Julia source.\n\n This only raises an exception if Julia itself throws an error, but it\n does NO type conversion into usable Python objects nor any memory\n management. It should never be used for returning the result of Julia\n expressions, only to execute statements.\n \"\"\"\n # logger.debug(\"_call(%s)\", src)\n ans = self.api.jl_eval_string(src.encode('utf-8'))\n self.check_exception(src)\n\n return ans\n\n @staticmethod\n def _check_unboxable(c_type):\n if c_type not in UNBOXABLE_TYPES:\n raise ValueError(\"Julia value cannot be unboxed as c_type={!r}.\\n\"\n \"c_type supported by PyJulia are:\\n\"\n \"{}\".format(c_type, \"\\n\".join(UNBOXABLE_TYPES)))\n\n def _is_unboxable_as(self, pointer, c_type):\n self._check_unboxable(c_type)\n jl_type = getattr(self.api, 'jl_{}_type'.format(c_type))\n desired = ctypes.cast(jl_type, ctypes.POINTER(ctypes.c_void_p))[0]\n actual = self.api.jl_typeof(pointer)\n return actual == desired\n\n def _unbox_as(self, pointer, c_type):\n self._check_unboxable(c_type)\n jl_unbox = getattr(self.api, 'jl_unbox_{}'.format(c_type))\n if self._is_unboxable_as(pointer, c_type):\n return jl_unbox(pointer)\n else:\n raise TypeError(\"Cannot unbox pointer {} as {}\"\n .format(pointer, c_type))\n\n def check_exception(self, src=\"\"):\n exoc = self.api.jl_exception_occurred()\n logger.debug(\"exception occured? %s\", str(exoc))\n if not exoc:\n # logger.debug(\"No Exception\")\n self.api.jl_exception_clear()\n return\n\n # If, theoretically, an exception happens in early stage of\n # self.__init__, showerror and sprint as below does not work.\n # Let's use jl_typeof_str in such case.\n try:\n sprint = self.sprint\n showerror = self.showerror\n except AttributeError:\n res = None\n else:\n res = self.api.jl_call2(self._convert, self._PyObject, exoc)\n if res is None:\n exception = self.api.jl_typeof_str(exoc).decode('utf-8')\n else:\n exception = sprint(showerror, self._as_pyobj(res))\n raise JuliaError(u'Exception \\'{}\\' occurred while calling julia code:\\n{}'\n .format(exception, src))\n\n def _typeof_julia_exception_in_transit(self):\n exception = void_p.in_dll(self.api, 'jl_exception_in_transit')\n msg = self.api.jl_typeof_str(exception)\n return char_p(msg).value\n\n def help(self, name):\n \"\"\" Return help string for function by name. \"\"\"\n if name is None:\n return None\n return self.eval('Markdown.plain(@doc(\"{}\"))'.format(name))\n\n def eval(self, src):\n \"\"\" Execute code in Julia, then pull some results back to Python. \"\"\"\n if src is None:\n return None\n ans = self._call(src)\n if not ans:\n return None\n res = self.api.jl_call2(self._convert, self._PyObject, ans)\n\n if res is None:\n self.check_exception(\"convert(PyCall.PyObject, {})\".format(src))\n return self._as_pyobj(res)\n\n def _as_pyobj(self, res):\n if res == 0:\n return None\n boxed_obj = self.api.jl_get_field(res, b'o')\n pyobj = self.api.jl_unbox_voidpointer(boxed_obj)\n # make sure we incref it before returning it,\n # as this is a borrowed reference\n ctypes.pythonapi.Py_IncRef(ctypes.py_object(pyobj))\n return pyobj\n\n def using(self, module):\n \"\"\"Load module in Julia by calling the `using module` command\"\"\"\n self.eval(\"using %s\" % module)\n\n def fullname(self, module):\n if isinstance(module, JuliaModule):\n assert module.__name__.startswith(\"julia.\")\n return module.__name__[len(\"julia.\") :]\n\n from .Main._PyJuliaHelper import fullnamestr\n\n return fullnamestr(module)\n\n def isdefined(self, parent, member=None):\n from .Main._PyJuliaHelper import isdefinedstr\n\n if member is None:\n if not isinstance(parent, string_types):\n raise ValueError(\"`julia.isdefined(name)` requires string `name`\")\n if \".\" not in parent:\n raise ValueError(\n \"`julia.isdefined(name)` requires at least one dot in `name`.\"\n )\n parent, member = parent.rsplit(\".\", 1)\n if isinstance(parent, string_types):\n parent = self.eval(parent)\n return isdefinedstr(parent, member)\n\n\nclass LegacyJulia(object):\n __doc__ = Julia.__doc__\n\n def __init__(self, *args, **kwargs):\n self.__julia = Julia(*args, **kwargs)\n __init__.__doc__ = Julia.__init__.__doc__\n\n def __getattr__(self, name):\n from julia import Main\n warnings.warn(\n \"Accessing `Julia().` to obtain Julia objects is\"\n \" deprecated. Use `from julia import Main; Main.` or\"\n \" `jl = Julia(); jl.eval('')`.\",\n DeprecationWarning)\n try:\n return getattr(self.__julia, name)\n except AttributeError:\n return getattr(Main, name)\n\n\nsys.meta_path.append(JuliaImporter())\n","sub_path":"src/julia/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":38858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"263054877","text":"def a2x(a, delim=' ', shorten=False):\n \"\"\" array to string of hexa\n delim is the delimiter between the hexa\n shorten don't print the trailing zeros\n \"\"\"\n a = a[:]\n shortened = 0\n if shorten:\n while (len(a) != 0) and (a[-1] == 0):\n shortened += 1\n del a[-1]\n s = delim.join('%02X' % x for x in a)\n if shortened:\n shortened = '00 (%d times)' % shortened\n if s:\n s = delim.join([s, shortened])\n else:\n s = shortened\n return s\n\n\ndef a2s(a, toPrint=True):\n \"\"\" array to string\n toPrint indicates that the resulting string is to be printed (stop at the\n first \\0)\n \"\"\"\n s = []\n for c in a:\n if toPrint and (c == 0):\n break\n s.append(chr(c))\n return ''.join(s)\n\n\ndef a2lsbi(array):\n \"\"\" array to int (LSB first) \"\"\"\n integer = 0\n for i in range(len(array) - 1, -1, -1):\n integer *= 256\n integer += array[i]\n return integer\n\n\ndef a2msbi(array):\n \"\"\" array to int (MSB first) \"\"\"\n integer = 0\n for i in range(len(array)):\n integer *= 256\n integer += array[i]\n return integer\n\n\ndef i2lsba(value, width):\n \"\"\" int to array (LSB first) \"\"\"\n a = [0] * width\n for i in range(width):\n a[i] = (value >> (i*8)) & 0xff\n return a\n\n\ndef s2a(s):\n \"\"\" string to array \"\"\"\n return [ord(c) for c in s]\n\n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"516985369","text":"\"\"\"\nSecond-Hand-Shop Project\n\n@author: Malte Gerth\n@copyright: Copyright (C) 2015 Malte Gerth\n@license: MIT\n@maintainer: Malte Gerth\n@email: mail@malte-gerth.de\n\"\"\"\n\nfrom django.conf import settings\nfrom django.db import models\nfrom django.utils import timezone\nfrom django.utils.dateformat import format\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom events.models import get_active_event_id\nfrom secondhandshop_server.models import BaseModel\n\n__author__ = \"Malte Gerth \"\n__copyright__ = \"Copyright (C) 2015 Malte Gerth\"\n__license__ = \"MIT\"\n\n\nclass Shift(BaseModel):\n class Meta:\n verbose_name = _(\"Shift\")\n verbose_name_plural = _(\"Shifts\")\n db_table = \"mb_shs_volunteer_shift\"\n ordering = (\"start_datetime\",)\n\n event = models.ForeignKey(\n \"events.Event\",\n db_column=\"event_id\",\n related_name=\"volunteer_shifts\",\n default=get_active_event_id,\n )\n start_datetime = models.DateTimeField()\n end_datetime = models.DateTimeField()\n\n def __str__(self):\n if self.start_datetime is None or self.end_datetime is None:\n return super().__str__()\n local_start = timezone.localtime(\n self.start_datetime, timezone.get_current_timezone()\n )\n local_end = timezone.localtime(\n self.end_datetime, timezone.get_current_timezone()\n )\n return \"{start} – {end}\".format(\n start=format(local_start, \"d.m.Y H:i\"), end=format(local_end, \"d.m.Y H:i\")\n )\n\n\nclass Volunteer(BaseModel):\n class Meta:\n verbose_name = _(\"Volunteer\")\n verbose_name_plural = _(\"Volunteers\")\n db_table = \"mb_shs_volunteer\"\n ordering = (\"event\", \"user\")\n\n event = models.ForeignKey(\n \"events.Event\",\n db_column=\"event_id\",\n related_name=\"volunteers\",\n default=get_active_event_id,\n )\n note = models.CharField(max_length=255, blank=True)\n user = models.ForeignKey(\n settings.AUTH_USER_MODEL, db_column=\"user\", related_name=\"volunteer\"\n )\n shifts = models.ManyToManyField(\n Shift, db_table=\"mb_shs_volunteer_shift_mm\", related_name=\"volunteers\"\n )\n\n def __str__(self):\n return str(self.user)\n","sub_path":"src/volunteers/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"20630848","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\nfrom scipy import ndimage\n\n######Variables Ejercicio 1\nimg = Image.open('/Users/pablomartineztellez/Desktop/10º/Imagenes/Practicas/Practica0/Imagenes2/1.jpg')\nimgE1 = cv2.imread('/Users/pablomartineztellez/Desktop/10º/Imagenes/Practicas/Practica0/Imagenes2/1.jpg')\n\nimgCR = imgE1.copy()\nimgCB = imgE1.copy()\nimgCG = imgE1.copy()\n\n######Variables Ejercicio 2\n\nimgE2 = cv2.imread('/Users/pablomartineztellez/Desktop/10º/Imagenes/Practicas/Practica0/Imagenes2/retinaRGB.jpg')\n\n######Variables Ejercicio 2\n\nimgE3 = cv2.imread('/Users/pablomartineztellez/Desktop/10º/Imagenes/Practicas/Practica0/Imagenes2/retinaRGB.jpg')\n\n######Variables Ejercicio 2\n\nimgE4 = cv2.imread('/Users/pablomartineztellez/Desktop/10º/Imagenes/Practicas/Practica0/Imagenes2/retinaRGB.jpg')\n\n\n######Variables Ejercicio 8\n\nimgE8 = cv2.imread('/Users/pablomartineztellez/Desktop/10º/Imagenes/Practicas/Practica0/Imagenes2/cta_scan_index.bmp')\n\n######Variables Ejercicio 9\n\nimgE9 = Image.open('/Users/pablomartineztellez/Desktop/10º/Imagenes/Practicas/Practica0/Imagenes2/mri.jpg')\n\n\n####################Codigo Ejercicio 1\nprint(\"\\nFormato de la Imagen:\", img.format, \"\\nModelo de Color:\", img.mode, \"\\nTamaño de la Imagen:\", img.size, \"\\nTipo de datos:\", imgE1.dtype)\n\nplt.figure(\"Ejercicio 1\", figsize = (10,5))\n\n###########Imagen Original RGB\nplt.subplot(232) #Indicamos la pocsicion de la iagen (nfilas, ncolumnas, casilla)\nplt.title('RGB')#Ponemos titulo a la imagen\nplt.imshow(cv2.cvtColor(imgE1, cv2.COLOR_BGR2RGB)) #convertimos la imagen de BGR a RGB para pode visualizarla en RGB\n\n############Canal Rojo\nimgCR[:,:,0] = 0 #capa 0 (Azul) le pasamos 0 para quitarla\nimgCR[:,:,1] = 0 #capa 1 (Verde) le pasamos 0 para quitarla\nplt.subplot(234)\nplt.title(\"Canal Rojo\")\nplt.imshow(cv2.cvtColor(imgCR, cv2.COLOR_BGR2RGB))\n\n\n############Canal Verde\nimgCG[:,:,0] = 0 #capa 0 (Azul) le pasamos 0 para quitarla\nimgCG[:,:,2] = 0 #capa 2 (Rojo) le pasamos 0 para quitarla\nplt.subplot(235)\nplt.title(\"Canal Verde\")\nplt.imshow(cv2.cvtColor(imgCG, cv2.COLOR_BGR2RGB))\n\n############Canal Azul\nimgCB[:,:,1] = 0 #capa 0 (Verde) le pasamos 0 para quitarla\nimgCB[:,:,2] = 0 #capa 2 (Rojo) le pasamos 0 para quitarla\nplt.subplot(236)\nplt.title(\"Canal Azul\")\nplt.imshow(cv2.cvtColor(imgCB, cv2.COLOR_BGR2RGB))\nplt.show()\n\n####################Codigo Ejercicio 2.1\n\nimgE2 = cv2.resize(imgE2, (0, 0), None, 1, 1)\n\nimgE2Gr = cv2.cvtColor(imgE2, cv2.COLOR_RGB2GRAY)\ngr = np.hstack((imgE2, cv2.cvtColor(imgE2Gr, cv2.COLOR_GRAY2BGR)))\ncv2.imshow('RGB a Escala de grises', gr)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n####################Codigo Ejercicio 2.2\n\nimgE3 = cv2.resize(imgE3, (0, 0), None, 1, 1)\n\nimgE3yuv = cv2.cvtColor(imgE3, cv2.COLOR_RGB2YUV)\nyuv = np.hstack((imgE3,cv2.cvtColor(imgE3yuv,cv2.COLOR_YUV2RGB)))\ncv2.imshow(\"RGB a YUV\", yuv)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n####################Codigo Ejercicio 2.3\n\nimgE4 = cv2.resize(imgE4, (0, 0), None, 1, 1)\n\nimgE4hsv = cv2.cvtColor(imgE4, cv2.COLOR_RGB2HSV)\nhsv = np.hstack((imgE4,cv2.cvtColor(imgE4hsv,cv2.COLOR_HSV2RGB)))\ncv2.imshow(\"RGB a HSV\", hsv)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n####################Codigo Ejercicio 3\n\nfrom PIL import Image\n\nim = Image.open(r'/Users/pablomartineztellez/Desktop/10º/Imagenes/Practicas/Practica0/Imagenes2/corte1.jpg')\nimE3c = im.copy()\nwidth, height = imE3c.size\n\nleft = width - 245 #X arriba\ntop = height -250 #Y arriba\nright = width\nbottom = height\n\nim1 = imE3c.crop((left, top, right, bottom))\n\nim1.show()\nim.show()\n\n\n#################Ejercicio 6\nbgr = np.zeros((200,800,3),dtype=np.uint8)\n\nbgr[:100, :200] = (255,0,0) #azul\nbgr[:100, 200:400] = (0,255,0) #Verde\nbgr[:100, 400:600] = (0,0,255) #Rojo\nbgr[:100, 600:800] = (0,255,255) #amarillo\nbgr[100:200, :200] = (255,0,255)# Magenta\nbgr[100:200, 200:400] = (255,255,0)# cyan\nbgr[100:200, 400:600] = (255,255,255)#Blanco\nbgr[100:200, 600:800] = (0)#Negro\n\ncv2.imshow('Paleta de Colores RGB',bgr)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n####################Codigo Ejercicio 8\n\ncv2.imshow(\"cta_scan_index.bmp normal\", imgE8)\n\nr45 = ndimage.rotate(imgE8, 45)\ncv2.imshow(\"cta_scan_index.bmp 45 grados\", r45)\n\nr90 = ndimage.rotate(imgE8, 90)\ncv2.imshow(\"cta_scan_index.bmp 90 grados\", r90)\n\nr180 = ndimage.rotate(imgE8, 180)\ncv2.imshow(\"cta_scan_index.bmp 180 grados\", r180)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n####################Codigo Ejercicio 9\n\nimgE9Gr = imgE9.convert('L')\nimgE9Gr.show()\nimgE9Gr.save('/Users/pablomartineztellez/Desktop/10º/Imagenes/Practicas/Practica0/Imagenes2/mriGris.tiff')\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Practica0.py","file_name":"Practica0.py","file_ext":"py","file_size_in_byte":4641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"345883077","text":"alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',\\\n 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']\n\nsenators = ['2', '2', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',\\\n '0', '0', '0', '0', '0', '0', '0']\n\ns = [3, 2, 2]\n\n#Check if there is a majority\ndef majority(senators):\n for s in senators:\n if s > sum(senators) - s:\n return True\n return False\n\n\n\n\ndef remove_one_max(senators):\n s = copy(senators)\n index_max = s.index(max(s))\n s[index_max] -= 1\n return s\n\ndef remove_two_max(senators):\n s = copy(senators)\n index_max = s.index(max(s))\n\n s2 = s[0:index_max] + [s[index_max] -2] + (s[index_max+1:] if index_max < len(s) else [])\n if s[index_max] >= 2 and not majority(s2):\n return s2\n else:\n s = remove_one_max(s)\n s = remove_one_max(s)\n return s\n\n\n\ndef get_index_one_max(senators):\n return senators.index(max(senators))\n\ndef get_index_two_max(senators):\n index_max = senators.index(max(senators))\n s2 = senators[0:index_max] + [senators[index_max] -2] + (senators[index_max+1:] if index_max < len(senators) else [])\n if senators[index_max] >= 2 and not majority(s2):\n return [index_max, index_max]\n else:\n ret = [get_index_one_max(senators)]\n s = remove_one_max(senators)\n ret += [get_index_one_max(s)]\n s = remove_one_max(senators)\n return ret\n\n\ndef copy(s):\n return s[:]\n\n\n\n\ndef evacuate(senators):\n ret = \"\"\n while max(senators) > 0:\n if (not majority(remove_one_max(senators))):\n ret += \" \" + chr(get_index_one_max(senators) + 65)\n senators = remove_one_max(senators)\n elif (not majority(remove_two_max(senators))):\n indexes_max = get_index_two_max(senators)\n ret += \" \"\n for index in indexes_max:\n ret += chr(index + 65)\n senators = remove_two_max(senators)\n else:\n print(\"ERROR: \")\n print(senators)\n return ret[1:]\n\n\n\n\n\ndef main():\n result = \"\"\n i = 1\n\n #Open the input file\n with open(\"A-large.in\", 'r') as inputFile:\n testCasesNumber = inputFile.readline()\n #Every case\n while i <= int(testCasesNumber):\n matrix = []\n N = int(inputFile.readline())\n line = inputFile.readline()\n line = line.replace('\\n', \"\")\n matrix = line.split(' ')\n matrix = map(int, matrix)\n result += \"Case #\" + str(i) + \": \" + evacuate(matrix) + '\\n'\n i += 1\n #Write result\n with open(\"output.txt\", 'w') as outputFile:\n outputFile.write(result)\n\n\n#print(evacuate(s))\nmain()\n","sub_path":"codes/CodeJamCrawler/16_3_1_neat/16_3_1_anthBoc_senate-evacuation.py","file_name":"16_3_1_anthBoc_senate-evacuation.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"61297480","text":"######################################\n# House Price Prediction\n######################################\n\n# 1. Exploratory Data Analysis\n# 2. Data Preprocessing & Feature Engineering\n# 3. Modeling\n# 4. Feature Selection\n# 5. Hyperparameter Optimization with Selected Features\n# 6. Sonuçların Yüklenmesi\n\nimport warnings\nfrom catboost import CatBoostRegressor\nfrom lightgbm import LGBMRegressor\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\nfrom sklearn.exceptions import ConvergenceWarning\nfrom sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.svm import SVR\nfrom sklearn.tree import DecisionTreeRegressor\nfrom xgboost import XGBRegressor\nimport numpy as np\nfrom helpers.data_prep import *\nfrom helpers.eda import *\n\n# warnings.simplefilter(action='ignore', category=FutureWarning)\n# warnings.simplefilter(\"ignore\", category=ConvergenceWarning)\n\npd.set_option('display.max_columns', None)\npd.set_option('display.float_format', lambda x: '%.5f' % x)\n\n######################################\n# Exploratory Data Analysis\n######################################\n\ntrain = pd.read_csv(\"datasets/house_prices/train.csv\")\ntest = pd.read_csv(\"datasets/house_prices/test.csv\")\ndf = train.append(test).reset_index(drop=True)\ndf.head()\n\n\ncheck_df(df)\n\ncat_cols, num_cols, cat_but_car = grab_col_names(df)\n\ndf[\"Neighborhood\"].value_counts()\n\n\n##################\n# Kategorik Değişken Analizi\n##################\n\n\nfor col in cat_cols:\n cat_summary(df, col)\n\nfor col in cat_but_car:\n cat_summary(df, col)\n\n\n\n##################\n# Sayısal Değişken Analizi\n##################\n\n\ndf[num_cols].describe([0.10, 0.30, 0.50, 0.70, 0.80, 0.99]).T\n\n\n# for col in num_cols:\n# num_summary(df, col, plot=True)\n\n\n\n##################\n# Target Analizi\n##################\n\n\ndf[\"SalePrice\"].describe([0.05, 0.10, 0.25, 0.50, 0.75, 0.80, 0.90, 0.95, 0.99]).T\n\n\ndef find_correlation(dataframe, numeric_cols, corr_limit=0.60):\n high_correlations = []\n low_correlations = []\n for col in numeric_cols:\n if col == \"SalePrice\":\n pass\n else:\n correlation = dataframe[[col, \"SalePrice\"]].corr().loc[col, \"SalePrice\"]\n print(col, correlation)\n if abs(correlation) > corr_limit:\n high_correlations.append(col + \": \" + str(correlation))\n else:\n low_correlations.append(col + \": \" + str(correlation))\n return low_correlations, high_correlations\n\nlow_corrs, high_corrs = find_correlation(df, num_cols)\n\n\n######################################\n# Data Preprocessing & Feature Engineering\n######################################\n\n\n##################\n# Rare Encoding\n##################\n\nrare_analyser(df, \"SalePrice\", cat_cols)\n\n\ndf = rare_encoder(df, 0.01, cat_cols)\n\nrare_analyser(df, \"SalePrice\", cat_cols)\n\n\nuseless_cols = [col for col in cat_cols if df[col].nunique() == 1 or\n (df[col].nunique() == 2 and (df[col].value_counts() / len(df) <= 0.01).any(axis=None))]\n\ncat_cols = [col for col in cat_cols if col not in useless_cols]\n\n\nfor col in useless_cols:\n df.drop(col, axis=1, inplace=True)\n\n\nrare_analyser(df, \"SalePrice\", cat_cols)\n\n\n\n##################\n# Label Encoding & One-Hot Encoding\n##################\n\ncat_cols = cat_cols + cat_but_car\n\n\ndf = one_hot_encoder(df, cat_cols, drop_first=True)\n\ncheck_df(df)\n\n\ncat_cols, num_cols, cat_but_car = grab_col_names(df)\n\nrare_analyser(df, \"SalePrice\", cat_cols)\n\n\nuseless_cols_new = [col for col in cat_cols if (df[col].value_counts() / len(df) <= 0.01).any(axis=None)]\n\ndf[useless_cols_new].head()\n\n\nfor col in useless_cols_new:\n cat_summary(df, col)\n\n\nrare_analyser(df, \"SalePrice\", useless_cols_new)\n\n\n##################\n# Missing Values\n##################\n\nmissing_values_table(df)\n\ntest.shape\n\nmissing_values_table(train)\n\n\nna_cols = [col for col in df.columns if df[col].isnull().sum() > 0 and \"SalePrice\" not in col]\n\ndf[na_cols] = df[na_cols].apply(lambda x: x.fillna(x.median()), axis=0)\n\n\n##################\n# Outliers\n##################\n\nfor col in num_cols:\n print(col, check_outlier(df, col, q1=0.01, q3=0.99))\n\n######################################\n# Modeling\n######################################\n\ntrain_df = df[df['SalePrice'].notnull()]\ntest_df = df[df['SalePrice'].isnull()].drop(\"SalePrice\", axis=1)\n\n# y = train_df[\"SalePrice\"]\ny = np.log1p(train_df['SalePrice'])\nX = train_df.drop([\"Id\", \"SalePrice\"], axis=1)\n\n\n##################\n# Base Models\n##################\n\nmodels = [('LR', LinearRegression()),\n (\"Ridge\", Ridge()),\n (\"Lasso\", Lasso()),\n (\"ElasticNet\", ElasticNet()),\n ('KNN', KNeighborsRegressor()),\n ('CART', DecisionTreeRegressor()),\n ('RF', RandomForestRegressor()),\n ('SVR', SVR()),\n ('GBM', GradientBoostingRegressor()),\n (\"XGBoost\", XGBRegressor(objective='reg:squarederror')),\n (\"LightGBM\", LGBMRegressor())]\n # (\"CatBoost\", CatBoostRegressor(verbose=False))]\n\nfor name, regressor in models:\n rmse = np.mean(np.sqrt(-cross_val_score(regressor, X, y, cv=5, scoring=\"neg_mean_squared_error\")))\n print(f\"RMSE: {round(rmse, 4)} ({name}) \")\n\n\n\n##################\n# Hyperparameter Optimization\n##################\n\n\nlgbm_model = LGBMRegressor(random_state=46)\n\nrmse = np.mean(np.sqrt(-cross_val_score(lgbm_model,\n X, y, cv=5, scoring=\"neg_mean_squared_error\")))\n\n\nlgbm_params = {\"learning_rate\": [0.01, 0.1],\n \"n_estimators\": [500, 1500],\n \"colsample_bytree\": [0.5, 0.7, 1]}\n\n\nlgbm_gs_best = GridSearchCV(lgbm_model,\n lgbm_params,\n cv=3,\n n_jobs=-1,\n verbose=True).fit(X, y)\n\n# normal y cv süresi: 16.2s\n# scale edilmiş y ile: 13.8s\n\n\nfinal_model = lgbm_model.set_params(**lgbm_gs_best.best_params_).fit(X, y)\n\nrmse = np.mean(np.sqrt(-cross_val_score(final_model, X, y, cv=5, scoring=\"neg_mean_squared_error\")))\n\n\n# normal y: 27646\n# scaled y: 0.1279\n\n\n\n#######################################\n# Feature Selection\n#######################################\n\ndef plot_importance(model, features, num=len(X), save=False):\n feature_imp = pd.DataFrame({'Value': model.feature_importances_, 'Feature': features.columns})\n plt.figure(figsize=(10, 10))\n sns.set(font_scale=1)\n sns.barplot(x=\"Value\", y=\"Feature\", data=feature_imp.sort_values(by=\"Value\",\n ascending=False)[0:num])\n plt.title('Features')\n plt.tight_layout()\n plt.show()\n if save:\n plt.savefig('importances.png')\n\n\nplot_importance(final_model, X)\n\n\nplot_importance(final_model, X, 20)\n\n\nX.shape\n\nfeature_imp = pd.DataFrame({'Value': final_model.feature_importances_, 'Feature': X.columns})\n\n\nnum_summary(feature_imp, \"Value\", True)\n\n\nfeature_imp[feature_imp[\"Value\"] > 0].shape\n\nfeature_imp[feature_imp[\"Value\"] < 1].shape\n\n\nzero_imp_cols = feature_imp[feature_imp[\"Value\"] < 1][\"Feature\"].values\n\n\nselected_cols = [col for col in X.columns if col not in zero_imp_cols]\nlen(selected_cols)\n\n#######################################\n# Hyperparameter Optimization with Selected Features\n#######################################\n\n\nlgbm_model = LGBMRegressor(random_state=46)\n\nlgbm_params = {\"learning_rate\": [0.01, 0.1],\n \"n_estimators\": [500, 1500],\n \"colsample_bytree\": [0.5, 0.7, 1]}\n\nlgbm_gs_best = GridSearchCV(lgbm_model,\n lgbm_params,\n cv=3,\n n_jobs=-1,\n verbose=True).fit(X[selected_cols], y)\n\n\nfinal_model = lgbm_model.set_params(**lgbm_gs_best.best_params_).fit(X[selected_cols], y)\n\nrmse = np.mean(np.sqrt(-cross_val_score(final_model, X[selected_cols], y, cv=5, scoring=\"neg_mean_squared_error\")))\n\n\n# 27726\n# scaled y: 0.1284\n\n\n#######################################\n# Sonuçların Yüklenmesi\n#######################################\n\n\nsubmission_df = pd.DataFrame()\n\nsubmission_df['Id'] = test_df[\"Id\"]\n\ny_pred_sub = final_model.predict(test_df[selected_cols])\n\n\ny_pred_sub = np.expm1(y_pred_sub)\n\nsubmission_df['SalePrice'] = y_pred_sub\n\nsubmission_df.to_csv('submission.csv', index=False)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"HOUSE_PRICE.py","file_name":"HOUSE_PRICE.py","file_ext":"py","file_size_in_byte":8529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"482802425","text":"# -*- coding:utf8 -*-\n\nimport os\nimport json\nimport tensorflow as tf\nfrom scipy import spatial\nfrom deepnlp.doc2vec.model import Doc2Vec\nfrom deepnlp.doc2vec.dataset.data_utils import *\n\n\ndef train(args):\n docs = read_doc(os.path.join(args.data_file, \"train.txt\"))\n doc_ids, word_ids, count, dictionary, reverse_dictionary = \\\n build_doc_dataset(docs, args.vocabulary_size)\n\n args.document_size = len(docs)\n model = Doc2Vec(args)\n\n configProto = tf.ConfigProto(allow_soft_placement=True)\n with tf.Session(config=configProto, graph=model.graph).as_default() as sess:\n sess.run(model.init_op)\n average_loss = 0\n print(\"Initialized\")\n for step in range(args.n_steps):\n batch_data, batch_labels = generate_batch_pvdm(doc_ids, word_ids,\n args.batch_size, args.window_size)\n feed_dict = {model.train_dataset: batch_data, model.train_labels: batch_labels}\n op, l = sess.run([model.optimizer, model.loss], feed_dict=feed_dict)\n average_loss += l\n if step % 2000 == 0:\n if step > 0:\n average_loss = average_loss / 2000\n # The average loss is an estimate of the loss over the last 2000 batches.\n print('Average loss at step %d: %f' % (step, average_loss))\n average_loss = 0\n\n # bind embedding matrices to self\n word_embeddings = sess.run(model.normalized_word_embeddings)\n doc_embeddings = sess.run(model.normalized_doc_embeddings)\n\n save(sess, args.train_dir, model.saver,\n docs, dictionary, reverse_dictionary,\n args.vocabulary_size,\n word_embeddings, doc_embeddings)\n\n\ndef save(sess, path, saver, docs, dictionary,\n reverse_dictionary, vocabulary_size,\n word_embeddings, doc_embeddings):\n\n with open(os.path.join(path, \"wemb.txt\"), 'w') as fout:\n for i, word in enumerate(dictionary):\n if i < vocabulary_size:\n fout.write(word + ' ')\n fout.write(','.join(str(value) for value in word_embeddings[i]))\n fout.write(\"\\n\")\n print('embedding saved in %s' % os.path.join(path, \"wemb.txt\"))\n\n with open(os.path.join(path, \"demb.txt\"), 'w') as fout:\n doclen = len(docs)\n for i in range(doclen):\n fout.write(','.join(docs[i]) + '\\n')\n fout.write(','.join(str(value) for value in doc_embeddings[i]))\n fout.write(\"\\n\")\n distance = spatial.distance.cosine(doc_embeddings[doclen-1], doc_embeddings[doclen-2])\n print(distance)\n print('embedding saved in %s' % os.path.join(path, \"demb.txt\"))\n\n save_path = saver.save(sess, os.path.join(path, 'model.ckpt'))\n # save dictionary, reverse_dictionary\n json.dump(dictionary,\n open(os.path.join(path, 'model_dict.json'), 'w'))\n json.dump(reverse_dictionary,\n open(os.path.join(path, 'model_rdict.json'), 'w'))\n\n print(\"Model saved in file: %s\" % save_path)","sub_path":"deepnlp/doc2vec/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"228275957","text":"\"\"\"Based flow request handlers. Clients should use the individual site modules.\n\nExample usage:\n\napplication = webapp2.WSGIApplication([\n ('/oauth_start', facebook.StartHandler.to('/oauth_callback')),\n ('/oauth_callback', facebook.CallbackHandler.to('/done')),\n ('/done', AuthenticatedHandler),\n ...\n ]\n\"\"\"\nimport logging\nimport urllib\n\nimport webapp2\nfrom webutil import handlers\nfrom webutil import util\n\n\nclass BaseHandler(webapp2.RequestHandler):\n \"\"\"Base request handler class. Provides the to() factory method.\n \"\"\"\n DEFAULT_SCOPE = '' # may be overridden by subclasses\n\n handle_exception = handlers.handle_exception\n to_path = None\n\n @classmethod\n def to(cls, path, scopes=None):\n class ToHandler(cls):\n to_path = path\n scope = cls.make_scope_str(scopes)\n return ToHandler\n\n @classmethod\n def make_scope_str(cls, extra, separator=','):\n \"\"\"Returns an OAuth scopes query parameter value.\n\n Combines DEFAULT_SCOPE and extra.\n\n Args:\n extra: string, sequence of strings, or None\n separator: string (optional), the separator between multiple scopes.\n defaults to ','\n \"\"\"\n if not extra:\n return cls.DEFAULT_SCOPE\n\n return (cls.DEFAULT_SCOPE + separator if cls.DEFAULT_SCOPE else '') + (\n extra if isinstance(extra, basestring) else separator.join(extra))\n\n def to_url(self, state=None):\n \"\"\"Returns a fully qualified callback URL based on to_path.\n\n Includes scheme, host, and optional state.\n \"\"\"\n url = self.request.host_url + self.to_path\n if state:\n # unquote first or state will be double-quoted\n state = urllib.unquote_plus(state)\n url = util.add_query_params(url, [('state', state)])\n return url\n\n def request_url_with_state(self):\n \"\"\"Returns the current request URL, with the state query param if provided.\n \"\"\"\n state = self.request.get('state')\n if state:\n return util.add_query_params(self.request.path_url, [('state', state)])\n else:\n return self.request.path_url\n\n\nclass StartHandler(BaseHandler):\n \"\"\"Base class for starting an OAuth flow.\n\n Users should use the to() class method when using this request handler in a\n WSGI application. See the file docstring for details.\n\n If the 'state' query parameter is provided in the request data, it will be\n returned to the client in the OAuth callback handler. If the 'scope' query\n parameter is provided, it will be added to the existing OAuth scopes.\n\n Alternatively, clients may call redirect_url() and HTTP 302 redirect to it\n manually, which will start the same OAuth flow.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n assert self.to_path, 'No `to` URL. Did you forget to use the to() class method in your request handler mapping?'\n super(StartHandler, self).__init__(*args, **kwargs)\n\n def get(self):\n self.post()\n\n def post(self):\n scopes = self.request.params.getall('scope')\n if scopes:\n self.scope += (',' if self.scope else '') + ','.join(scopes)\n\n url = self.redirect_url(state=self.request.get('state'))\n logging.info('Starting OAuth flow: redirecting to %s', url)\n self.redirect(url)\n\n def redirect_url(self, state=None):\n \"\"\"oauth-dropin subclasses must implement this.\n \"\"\"\n raise NotImplementedError()\n\n\nclass CallbackHandler(BaseHandler):\n \"\"\"Base OAuth callback request handler.\n\n Users can use the to() class method when using this request handler in a WSGI\n application to make it redirect to a given URL path on completion. See the\n file docstring for details.\n\n Alternatively, you can subclass it and implement finish(), which will be\n called in the OAuth callback request directly, after the user has been\n authenticated.\n\n The auth entity and optional state parameter provided to StartHandler will be\n passed to finish() or as query parameters to the redirect URL.\n \"\"\"\n\n def finish(self, auth_entity, state=None):\n \"\"\"Called when the OAuth flow is complete. Clients may override.\n\n Args:\n auth_entity: a site-specific subclass of models.BaseAuth, or None if the\n user declined the site's OAuth authorization request.\n state: the string passed to StartHandler.redirect_url()\n \"\"\"\n assert self.to_path, 'No `to` URL. Did you forget to use the to() class method in your request handler mapping?'\n\n if auth_entity is None:\n params = [('declined', True)]\n else:\n params = [('auth_entity', auth_entity.key.urlsafe()), ('state', state)]\n token = auth_entity.access_token()\n if isinstance(token, basestring):\n params.append(('access_token', token))\n elif token:\n params += [('access_token_key', token[0]),\n ('access_token_secret', token[1])]\n\n url = util.add_query_params(self.to_path, params)\n logging.info('Finishing OAuth flow: redirecting to %s', url)\n self.redirect(url)\n","sub_path":"oauth_dropins/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":4855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"152453102","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 5 09:38:56 2018\n\n@author: xuyuan\n\"\"\"\nimport numpy as np\nimport math\nimport warnings\nimport matplotlib.pyplot as plt\nimport random\nfrom pylab import *\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter\n#PART 1\nd=100\nn=1000\nX=np.random.normal(0,1,size=(n,d))\na_true=np.random.normal(0,1,size=(d,1))\ny=X.dot(a_true)+np.random.normal(0,0.5,size=(n,1))\n\ndef get_a(flag):\n if flag:\n return np.zeros(shape=(d,1))\n Xt=X.T\n XtX=np.matmul(Xt,X)\n XtXinv=np.linalg.inv(XtX)\n XtXinvXt=np.matmul(XtXinv,Xt)\n a=np.matmul(XtXinvXt,y)#a:d*1\n return a\n\ndef get_error(a): \n sqrd_error=0\n at=a.T# at:1*d\n for i in range(n):\n xi=X[i].reshape((d,1))\n sqrd_error+=np.power(at.dot(xi)-y[i],2)\n return sqrd_error\n\ndef part_a():\n flag=0\n a=get_a(flag)\n error=get_error(a)\n flag=1\n aa=get_a(flag)\n errorr=get_error(aa)\n print(\"normal error:\",error)\n print(\"set a all 0's error:\",errorr)\n\n#part_a\npart_a()\n\n#part_b\nlearning_rates=[0.00005, 0.0005, 0.0007]\niterations=20\n\n'''\ny=(y_predict-y_true)^2\ny'=2*y_predict-y_true\n'''\ndef gradient_descent():\n gdresult = {}\n for i in learning_rates:\n a=np.zeros(shape=(d,1))\n for j in range(iterations):\n gd=0\n for elem in range(n):\n xi=X[elem].reshape((d,1))\n gd+=2*xi*(a.T.dot(xi)-y[elem])\n a-=i*gd\n loss=get_error(a)\n gdresult.setdefault(i,[]).extend(loss)\n return gdresult\n\ndef make_plot(gdresult,iterations,outFileName):\n xlabs=[i for i in range(1,iterations+1)]\n plt.xlabel('iteration times')\n plt.ylabel('loss') \n plt.plot(xlabs,gdresult[learning_rates[0]],color='green',label='lr=0.0005')\n plt.plot(xlabs,gdresult[learning_rates[1]],color='red',label='lr=0.005')\n plt.plot(xlabs,gdresult[learning_rates[2]],color='blue',label='lr=0.01')\n plt.legend() # 显示图例\n plt.show()\n plt.savefig(outFileName, format = 'png')\n'''\ngdresult=gradient_descent()\nmake_plot(gdresult,iterations,\"part_b.png\")\nprint(\"0.00005:\",gdresult[learning_rates[0]][-1])\nprint(\"0.0005:\",gdresult[learning_rates[1]][-1])\nprint(\"0.0007:\",gdresult[learning_rates[2]][-1])\n'''\n\n#part_c\nlearning_rates=[0.0005,0.005, 0.01]\niterations=1000\ndef stochastic_gradient_descent():\n gdresult = {}\n for i in learning_rates:\n a=np.zeros(shape=(d,1))\n for j in range(iterations):\n random_choose=np.random.randint(0,n-1)\n xi=X[random_choose].reshape((d,1))\n gd=2*xi*(a.T.dot(xi)-y[random_choose])\n a-=i*gd\n loss=get_error(a)\n gdresult.setdefault(i,[]).extend(loss)\n return gdresult\n \ngdresult=stochastic_gradient_descent()\nmake_plot(gdresult,iterations,\"part_c.png\")\nprint(\"0.0005:\",gdresult[learning_rates[0]][-1])\nprint(\"0.005:\",gdresult[learning_rates[1]][-1])\nprint(\"0.01:\",gdresult[learning_rates[2]][-1])\n\n \n \n \n \n\n \n ","sub_path":"minipro3/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"347227158","text":"from anagram import make_anagram_dict\nimport string\nfrom sys import argv\n\n\ndef blanagram(word, anagramdict):\n \"\"\"\n Given a word and dictionary of anagrams it returns all the blanagrams\n of the given word.\n a blanagram is an anagram where a single letter is replaced by any other letter\n in the alphabet\n\n word = word to be used to find all the blanagrams\n anagramdict = dictionary of anagrams\n \"\"\"\n\n letters = string.ascii_lowercase\n blanagrams = []\n used_keys = []\n\n\n for i in range(len(word)):\n\n for letter in letters:\n new_word = word[0:i] + letter + word[i + 1:] #creates a new word by replacing one letter\n key = \"\".join(sorted(new_word)) # the key is the letters of the word in alphabetical order\n\n if \"\".join(sorted(word)) != key and key not in used_keys: # prevents that anagrams are considered blanagrams and repetitions\n\n try:\n blanagrams.extend(anagramdict[key])\n except KeyError:\n continue\n\n used_keys.append(key)\n\n\n return sorted(blanagrams) # all the blanagrams in alphabetical order\n\n\nif __name__ == \"__main__\":\n\n if len(argv) < 2: # guardian statement\n print(\"please give information in the following order:\")\n print(\"python blanagram.py \")\n quit()\n\n\n # calculate the word with given length with most blanagram\n D = make_anagram_dict(open(\"words.txt\", \"r\"))\n max_length = 0\n blanagram_list = []\n keys = []\n\n for k, v in D.items():\n\n if len(k) == int(argv[1]):\n blanagrams = blanagram(k, D)\n\n if len(blanagrams) > max_length:\n keys = v\n max_length = len(blanagrams)\n blanagram_list = [blanagrams]\n elif len(blanagrams) == max_length:\n keys.extend(v)\n blanagram_list.append(blanagrams)\n\n\n\n\n print(\"The words that are %s characters long and are blanagrams to each other are %s:\" % (argv[1], max_length), \"\\n\")\n\n for blan in range(len(blanagram_list)):\n print(\"word: \", keys[blan])\n print(\" \".join(blanagram_list[blan]))\n print()\n","sub_path":"Python/Coursework3/definitivi/blanagram.py","file_name":"blanagram.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"283850360","text":"import pandas as pd\nimport traceback\n\ndef load_excel(path):\n try:\n data = pd.read_excel(path,sheet_name=0,names=['name','all_name','num'])\n records = pd.DataFrame(data).to_dict(orient='records')\n except:\n traceback.print_exc()\n\n\nif __name__ == '__main__':\n excel_path = r'F:\\合盛硅业\\06-基础资料\\20200509合盛部门信息.xlsx'\n load_excel(excel_path)\n\n","sub_path":"python_up/python_vidobook_test/Mooc/Data_Alany/pandas_excel.py","file_name":"pandas_excel.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"336945029","text":"#!/usr/bin/env python\n\nimport sys\nimport re\n\ndef parse_range(astr):\n result = set()\n for part in astr.split(','):\n x = part.split('-')\n result.update(range(int(x[0]), int(x[-1]) + 1))\n return sorted(result)\n\ndef print_listing(line_range, fname):\n print('\\\\begin{lstlisting}')\n if not line_range:\n with open(fname, 'r') as fin:\n sys.stdout.write(fin.read())\n else:\n with open(fname) as mfile:\n for num, line in enumerate(mfile, 1):\n if num in line_range:\n sys.stdout.write(line)\n print('\\\\end{lstlisting}')\n\ndef cppexample(line_range, fname):\n print_listing(line_range, '../../examples/{0}.cpp'.format(fname))\n\ndef iniexample(line_range, fname):\n print_listing(line_range, '../../examples/{0}.ini'.format(fname))\n\ndef sourcefile(line_range, fname):\n print_listing(line_range, '../../{0}'.format(fname))\n\nrx = re.compile(r\"\\\\(cppexample|iniexample|sourcefile)(?:\\[(.+)\\])?{(.+)}\")\n\nfor line in sys.stdin:\n m = rx.match(line)\n if not m:\n sys.stdout.write(line)\n else:\n locals()[m.group(1)](parse_range(m.group(2)), m.group(3))\n","sub_path":"doc/tex/explode_lstinputlisting.py","file_name":"explode_lstinputlisting.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"201575669","text":"import unittest\n\nimport numpy as np\nfrom dpipe.medim import prep\nfrom dpipe.medim.preprocessing import *\n\n\nclass TestPrep(unittest.TestCase):\n def setUp(self):\n self.x = np.random.rand(3, 10, 10) * 2 + 3\n\n def _test_to_shape(self, func, shape, bad_shape):\n self.assertTupleEqual(func(self.x, shape).shape, shape)\n with self.assertRaises(ValueError):\n func(self.x, bad_shape)\n\n def test_scale_to_shape(self):\n shape = (3, 4, 15)\n self.assertTupleEqual(prep.zoom_to_shape(self.x, shape).shape, shape)\n self.assertTupleEqual(prep.zoom_to_shape(self.x, shape[::-1]).shape, shape[::-1])\n\n def test_pad_to_shape(self):\n self._test_to_shape(prep.pad_to_shape, (3, 15, 16), (3, 4, 10))\n\n def test_slice_to_shape(self):\n self._test_to_shape(prep.crop_to_shape, (3, 4, 8), (3, 15, 10))\n\n def test_scale(self):\n self.assertTupleEqual(prep.zoom(self.x, (3, 4, 15)).shape, (9, 40, 150))\n\n self.assertTupleEqual(prep.zoom(self.x, (4, 3)).shape, (3, 40, 30))\n\n def test_normalize_image(self):\n x = normalize(self.x)\n np.testing.assert_almost_equal(0, x.mean())\n np.testing.assert_almost_equal(1, x.std())\n\n x = normalize(self.x, mean=False)\n np.testing.assert_almost_equal(1, x.std())\n\n x = normalize(self.x, std=False)\n np.testing.assert_almost_equal(0, x.mean())\n\n y = np.array([-100, 1, 2, 1000])\n x = normalize(y, percentiles=25)\n np.testing.assert_equal(x, (y - 1.5) * 2)\n np.testing.assert_equal(\n normalize(y, percentiles=25),\n normalize(y, percentiles=[25, 25]),\n )\n\n def test_normalize_multichannel_image(self):\n x = normalize(self.x, axes=0)\n np.testing.assert_almost_equal(0, x.mean(axis=(1, 2)))\n np.testing.assert_almost_equal(1, x.std(axis=(1, 2)))\n","sub_path":"dpipe/medim/tests/test_preprocessing.py","file_name":"test_preprocessing.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"329870900","text":"from target import TargetType\nimport os\nimport re\nimport cv2\nimport time\nimport subprocess\nimport numpy as np\n\nimport prop\n\nTARGET_DIR = './assets/'\nTMP_DIR = './tmp/'\n\nSIMILAR = {\n '1': ['i', 'I', 'l', '|', ':', '!', '/', '\\\\', '丨'],\n '2': ['z', 'Z'],\n '3': [],\n '4': [],\n '5': ['s', 'S'],\n '6': [],\n '7': ['T'],\n '8': ['&'],\n '9': [],\n '0': ['o', 'O', 'c', 'C', 'D']\n}\n\n\nclass UIMatcher:\n @staticmethod\n def match(screen, target: TargetType):\n \"\"\"\n 在指定快照中确定货物的屏幕位置。\n \"\"\"\n # 获取对应货物的图片。\n # 有个要点:通过截屏制作货物图片时,请在快照为实际大小的模式下截屏。\n template = cv2.imread(target.value)\n # 获取货物图片的宽高。\n th, tw = template.shape[:2]\n\n # 调用 OpenCV 模板匹配。\n res = cv2.matchTemplate(screen, template, cv2.TM_CCOEFF_NORMED)\n min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)\n rank = max_val\n\n # 矩形左上角的位置。\n tl = max_loc\n\n # 阈值判断。\n if rank < 0.9:\n return None\n\n # 这里,我随机加入了数字(15),用于补偿匹配值和真实位置的差异。\n return tl[0] + tw / 2 + 15, tl[1] + th / 2 + 15, rank\n\n @staticmethod\n def read(filepath: str):\n \"\"\"\n 工具函数,用于读取图片。\n \"\"\"\n return cv2.imread(filepath)\n\n @staticmethod\n def write(image):\n \"\"\"\n 工具函数,用于读取图片。\n \"\"\"\n ts = str(int(time.time()))\n return cv2.imwrite(f'{TARGET_DIR}{ts}.jpg', image)\n\n @staticmethod\n def image_to_txt(image, cleanup=False, plus=''):\n # cleanup为True则识别完成后删除生成的文本文件\n # plus参数为给tesseract的附加高级参数\n image_url = f'{TMP_DIR}tmp.jpg'\n txt_name = f'{TMP_DIR}tmp'\n txt_url = f'{txt_name}.txt'\n cv2.imwrite(image_url, image)\n\n subprocess.check_output('tesseract ' + image_url + ' ' +\n txt_name + ' ' + plus, shell=True) # 生成同名txt文件\n text = ''\n with open(txt_url, 'r') as f:\n text = f.read().strip()\n if cleanup:\n os.remove(txt_url)\n os.remove(image_url)\n return text\n\n @staticmethod\n def normalize_txt(txt: str):\n for key, sim_list in SIMILAR.items():\n for sim in sim_list:\n txt = txt.replace(sim, key)\n txt = re.sub(r'\\D', '', txt)\n return txt\n\n @staticmethod\n def cut(image, left_up, len_width=(190, 50)):\n sx = left_up[0]\n sy = left_up[1]\n dx = left_up[0] + len_width[0]\n dy = left_up[1] + len_width[1]\n return image[sy:dy, sx:dx]\n\n @staticmethod\n def plain(image):\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\n erode = cv2.erode(image, kernel)\n dilate = cv2.dilate(erode, kernel)\n return dilate\n\n @staticmethod\n def fill_color(image):\n copy_image = image.copy()\n h, w = image.shape[:2]\n mask = np.zeros([h + 2, w + 2], np.uint8)\n cv2.floodFill(copy_image, mask, (0, 0), (255, 255, 255), (100, 100, 100), (50, 50, 50),\n cv2.FLOODFILL_FIXED_RANGE)\n return copy_image\n\n @staticmethod\n def pre(image):\n image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n lower_blue = np.array([103, 43, 46])\n upper_blue = np.array([103, 255, 255])\n image = cv2.inRange(image, lower_blue, upper_blue)\n return image\n\n @staticmethod\n def get_little_square(img, rel_pos, edge=0.01):\n '''\n 截取rel_pos附近一个小方块\n '''\n rx, ry = rel_pos\n h = len(img)\n w = len(img[0])\n scale = h / w\n x0 = int((rx - edge * scale) * w)\n x1 = int((rx + edge * scale) * w)\n y0 = int((ry - edge) * h)\n y1 = int((ry + edge) * h)\n return img[y0:y1, x0:x1]\n\n @staticmethod\n def find_green_light(diff_screens):\n screen_before, screen_after = diff_screens\n # 转换成有符号数以处理相减后的负值\n screen_before = screen_before.astype(np.int16)\n screen_after = screen_after.astype(np.int16)\n\n diff = screen_after - screen_before\n h = len(diff)\n w = len(diff[0])\n B, G, R = cv2.split(diff)\n # 负值取0\n G[G < 0] = 0\n G = G.astype(np.uint8)\n # 二值化后相与, 相当于取中间范围内的值\n ret, G1 = cv2.threshold(G, 140, 255, cv2.THRESH_BINARY_INV)\n ret, G2 = cv2.threshold(G, 22, 255, cv2.THRESH_BINARY)\n img0 = G1 & G2\n # 均值模糊(降噪 好像也没啥卵用)\n img0 = cv2.medianBlur(img0, 9)\n\n buildings = []\n for building_id in range(1, 10):\n square = UIMatcher.cut(img0, prop.BUILDING_POS[building_id], (110, 55))\n buildings.append(np.mean(square))\n # 返回平均亮度最强的建筑物\n return buildings.index(max(buildings)) + 1\n\n @staticmethod\n def detect_cross(screen, th=5):\n '''\n 探测叉叉是否出现, 先截取叉叉所在的小方块,然后对灰度图二值化,再求平均值判断\n '''\n screen = cv2.cvtColor(screen, cv2.COLOR_RGB2GRAY)\n good_id_list = []\n for good_id in prop.CROSS_POSITIONS.keys():\n square = UIMatcher.get_little_square(screen, prop.CROSS_POSITIONS[good_id])\n ret, W = cv2.threshold(square, 250, 255, cv2.THRESH_BINARY)\n # import matplotlib.pyplot as plt\n # plt.imshow(W,cmap='gray')\n # plt.show()\n # 二值化后求平均值\n if np.mean(W) > th:\n good_id_list.append(good_id)\n # print(good_id_list)\n return good_id_list\n","sub_path":"cv.py","file_name":"cv.py","file_ext":"py","file_size_in_byte":5940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"313680051","text":"import os\nimport math\n\nif __name__ == \"__main__\":\n\trootDir = \"shakespeare\"\n\tdirs = os.listdir(rootDir)\n\tdata = {}\n\tfor filename in dirs:\n\t\tdata[filename] = [\"\", [], [0]]\n\t\ttmpDir = os.path.join(rootDir, filename)\n\t\twith open(tmpDir, \"r\") as f:\n\t\t\tdata[filename][0] = f.read()\n\t\twith open(tmpDir, \"r\") as f:\n\t\t\tdata[filename][1] = f.readlines()\n\t\ttmp = 0\n\t\tfor line in data[filename][1]:\n\t\t\ttmp += len(line)\n\t\t\tdata[filename][2].append(tmp)\n\n\twith open(\"res.txt\", \"r\") as f:\n\t\tlines = f.readlines()\n\n\ttext = {}\n\tcount = {}\n\n\tfor line in lines:\n\t\tcnt = 0\n\t\ttmp = line.split(\"\\t\")\n\t\tterm = tmp[0]\n\t\tres = \"\"\n#\t\tres = \"Term: \" + term + \"\\n\";\n\t\ttmp = tmp[1].split(\";\")\n\t\tfor tmpfile in tmp:\n\t\t\ttmpp = tmpfile.split(\":\")\n\t\t\tfilename = tmpp[0]\n\t\t\tres += \"Filename: \" + filename + \"\\n\"\n\t\t\ttmppp = tmpp[1].split(\",\")\n\t\t\tfor offstr in tmppp:\n\t\t\t\toffset = int(offstr)\n\t\t\t\tl = 0; r = len(data[filename][2])\n\t\t\t\twhile l + 1 < r:\n\t\t\t\t\tmid = math.floor((l + r) / 2)\n\t\t\t\t\tif (data[filename][2][mid] <= offset):\n\t\t\t\t\t\tl = mid\n\t\t\t\t\telse:\n\t\t\t\t\t\tr = mid\n\t\t\t\tres += \"line \" + str(l) + \":\" + data[filename][1][l]\n\t\t\t\tcnt += 1\n\t\ttext[term] = res\n\t\tcount[term] = cnt\n\n\tprint(\"Initialized.\")\n\twhile True:\n\t\tterm = input(\"Term: \")\n\t\tif not term in text:\n\t\t\tprint(\"Term not existed.\")\n\t\t\tcontinue\n\t\tif count[term] > 1000:\n\t\t\tprint(\"Term is noise.\")\n\t\t\tcontinue\n\t\tprint(text[term])\n\n","sub_path":"lab/lab1/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"34220777","text":"def dem_tup(s, offset):\n first, offset = dem_top(s, offset)\n second, offset = dem_top(s, offset)\n return (first, second), offset\n\n\ndef dem_num(s, s_offset):\n i = s_offset\n while s[i] == \"1\":\n i += 1\n offset = i + 1\n if i == s_offset:\n return 0, s_offset + 1\n rem_start = offset + 4 * (i - s_offset)\n bin_number = s[offset: rem_start]\n return int(bin_number, 2), rem_start\n\n\ndef dem_top(s, offset):\n length = len(s) - offset\n if length == 0:\n return \"\"\n if length < 2:\n raise ValueError()\n typ = s[offset:offset + 2]\n if typ == \"00\":\n return None, offset + 2\n elif typ == \"01\" or typ == \"10\":\n num, offset = dem_num(s, offset + 2)\n if typ == \"10\":\n num *= -1\n return num, offset\n else:\n return dem_tup(s, offset + 2)\n\n\ndef demodulate(s):\n return dem_top(s, 0)[0]\n\n\ndef to_list(x):\n if type(x) == tuple:\n fst, snd = x\n fst = to_list(fst)\n snd = to_list(snd)\n if snd is None:\n return [fst]\n elif type(snd) == list:\n return [fst] + snd\n else:\n return x\n else:\n return x\n\n\ndef _serialize(x, buf):\n if type(x) == tuple:\n fst, snd = x\n buf.append(\"(\")\n _serialize(fst, buf)\n buf.append(\", \")\n _serialize(snd, buf)\n buf.append(\")\")\n return\n elif type(x) == list:\n buf.append(\"[\")\n for item in x:\n _serialize(item, buf)\n buf.append(\", \")\n if len(x) > 0:\n buf.pop()\n buf.append(\"]\")\n return\n elif x is None:\n buf.append(\"nil\")\n return\n else:\n buf.append(str(x))\n return\n\n\ndef serialize(x):\n buf = []\n _serialize(x, buf)\n return ''.join(buf)\n\n\ndef run(s):\n return serialize(to_list(demodulate(s)))\n\n\ndef main():\n print(run(input()))\n\n\nif __name__ == '__main__':\n main()","sub_path":"manarimo/src/dem.py","file_name":"dem.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"143391964","text":"import os\nimport sys\nimport re\nimport types\nimport itertools\nimport glob\nimport pipelineTracks\n\nfrom cgatReport.Tracker import *\nfrom cgatReport.odict import OrderedDict as odict\nfrom cgatReport.Utils import PARAMS as P\n\nEXPORTDIR = P['cpg_exportdir']\nDATADIR = P['cpg_datadir']\nDATABASE = P['cpg_backend']\nUCSC_GENOME = P['ucsc_genome']\nANNOTATIONS_DB = P['annotations_db']\n\n##########################################################################\nSample = PipelineTracks.Sample3\nSample.setDefault(\"asTable\")\nTRACKS = PipelineTracks.Tracks(Sample).loadFromDirectory(\n [x for x in glob.glob(\"*.export.txt.gz\") if P[\"tracks_control\"] not in x],\n \"(\\S+).export.txt.gz\" ) +\\\n PipelineTracks.Tracks(PipelineTracks.Sample3).loadFromDirectory(\n [x for x in glob.glob(\"*.sra\") if P[\"tracks_control\"] not in x],\n \"(\\S+).sra\" ) +\\\n PipelineTracks.Tracks(PipelineTracks.Sample3).loadFromDirectory(\n [x for x in glob.glob(\"*.fastq.gz\") if P[\"tracks_control\"] not in x],\n \"(\\S+).fastq.gz\" ) +\\\n PipelineTracks.Tracks(PipelineTracks.Sample3).loadFromDirectory(\n [x for x in glob.glob(\"*.fastq.1.gz\") if P[\"tracks_control\"] not in x],\n \"(\\S+).fastq.1.gz\" ) +\\\n PipelineTracks.Tracks(PipelineTracks.Sample3).loadFromDirectory(\n [x for x in glob.glob(\"*.csfasta.gz\") if P[\"track_control\"] not in x],\n \"(\\S+).csfasta.gz\")\n\nSample.setDefault(\"asTable\")\n\nfor X in TRACKS:\n print(\"TRACK=\", X, \"\\n\")\n\nALL = PipelineTracks.Aggregate(TRACKS)\nEXPERIMENTS = PipelineTracks.Aggregate(TRACKS, labels=(\"condition\", \"tissue\"))\nCONDITIONS = PipelineTracks.Aggregate(TRACKS, labels=(\"condition\", ))\nTISSUES = PipelineTracks.Aggregate(TRACKS, labels=(\"tissue\", ))\n\nMAP_TRACKS = {\n 'master': list(map(str, list(EXPERIMENTS) + list(CONDITIONS))),\n 'replicates': list(map(str, list(TRACKS))),\n 'default': list(map(str, list(EXPERIMENTS))),\n 'experiments': list(map(str, list(EXPERIMENTS))),\n 'conditions': list(map(str, list(CONDITIONS))),\n 'tissues': list(map(str, list(TISSUES))),\n 'merged': list(map(str, list(EXPERIMENTS))),\n}\n\nfor x, y in MAP_TRACKS.items():\n print(\"MAP_TRACK=\", x, \"--\", y, \"\\n\")\n\n\n##########################################################################\nclass cpgTracker(TrackerSQL):\n\n '''Define convenience tracks for plots'''\n\n def __init__(self, *args, **kwargs):\n TrackerSQL.__init__(self, *args, backend=DATABASE, **kwargs)\n\n # issuing the ATTACH DATABASE into the sqlalchemy ORM (self.db.execute( ... ))\n # does not work. The database is attached, but tables are not accessible in later\n # SELECT statements.\n if not self.db:\n def _create():\n import sqlite3\n conn = sqlite3.connect(re.sub(\"sqlite:///\", \"\", DATABASE))\n statement = \"ATTACH DATABASE '%s' AS annotations; \" % (\n ANNOTATIONS_DB)\n conn.execute(statement)\n return conn\n\n self.connect(creator=_create)\n\n def getTracks(self, subset=None):\n if subset:\n for key, tracks in MAP_TRACKS.items():\n if key in subset:\n return tracks\n\n return TrackerSQL.getTracks(self)\n\n##########################################################################\n\n\nclass featureOverlap(cpgTracker):\n\n \"\"\"return overlap of interval with genomic features \"\"\"\n\n mPattern = \"_ensembl_transcript_overlap$\"\n mTable = \"_ensembl_transcript_overlap\"\n mWhere = \"tss_extended_pover1\"\n\n def __call__(self, track, slice=None):\n table = self.mTable\n where = self.mWhere\n data = self.getValues( \"\"\" SELECT count(distinct gene_id) as intervals FROM (\n SELECT gene_id,\n CASE WHEN %(where)s > 0 THEN 'TSS'\n WHEN genes_pover1 > 0 THEN 'Gene'\n WHEN upstream_flank_pover1 >0 THEN 'Upstream'\n WHEN downstream_flank_pover1 >0 THEN 'Downstream'\n ELSE 'Intergenic'\n END AS feature_class\n FROM %(track)s%(table)s)\n group by feature_class\n order by feature_class asc\"\"\" % locals() )\n\n result = odict(\n list(zip((\"Downstream\", \"Gene\", \"Intergenic\", \"TSS\", \"Upstream\"), data)))\n return result\n","sub_path":"obsolete/reports/pipeline_capseq/trackers/cpgReport.py","file_name":"cpgReport.py","file_ext":"py","file_size_in_byte":4519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"492924713","text":"# ============================ F11 ========================================\ndef riwayatPinjam():\n # Menampilkan daftar peminjaman gadget yang telah dilakukan para user ke layar\n \n # input -> gadget_borrow_history : array of array of string\n # user : array of array of string\n # gadget : array of list of string and integer\n \n # I.S. matriks data user, gadget, gadget_borrow_history terdefinisi\n # F.S. tercetak ke layar riwayat peminjaman user\n \n # KAMUS LOKAL\n # rolling, bisaLanjut : boolean\n # count : integer\n # borrowSort : array of list of integer and string\n # namaUser, namaGadget : string\n \n # Function / Procedure\n # validasiYN(jawaban : string) -> boolean\n # Memvalidasi input dari user, harus 'Y' atau 'N'\n # I.S. string terdefinisi\n # F.S. mengembalikan True jika string adalah 'Y' atau 'N' dan False jika sebaliknya\n \n # ALGORITMA\n rolling = True\n count = 0\n while rolling:\n borrowSort = sorted(gadget_borrow_history[count+1:], key = lambda date: datetime.datetime.strptime(date[3], '%d/%m/%Y'),reverse=True)\n bisaLanjut = True\n for i in range(5):\n try:\n namaUser = user[cariID(user,borrowSort[i][1])][2]\n namaGadget = gadget[cariID(gadget,borrowSort[i][2])][1]\n print()\n print(\"ID Peminjam : \" + borrowSort[i][1])\n print(\"Nama Pengambil : \" + namaUser)\n print(\"Nama Gadget : \" + namaGadget)\n print(\"Tanggal Peminjamanan : \" + borrowSort[i][3])\n print(\"Jumlah : \" + str(borrowSort[i][4]))\n except:\n # Ketika data habis maka akan terjadi IndexError\n IndexError\n print()\n print(\"Data sudah habis\")\n bisaLanjut = False\n break\n\n if bisaLanjut and len(borrowSort) != 5:\n print()\n lanjut = input(\"Apakah mau ditampilkan data lebih lanjut? (Y/N) \")\n # Validasi input\n while not validasiYN(lanjut):\n lanjut = input(\"Apakah mau ditampilkan data lebih lanjut? (Y/N) \")\n if lanjut == 'Y':\n count += 5\n else:\n rolling = False\n else:\n rolling = False","sub_path":"F11.py","file_name":"F11.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"574440779","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# isReactionaryBot.py\n# \n# Copyright 2015 Wyboth \n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n# \n# \n\n\n\nimport praw, sqlite3, sys\nfrom isReactionaryBotPrivateSettings import password, path\nfrom isReactionaryBotSubreddits import reactionarySubreddits\nfrom time import sleep\nimport re\n\nusername_regex = re.compile(\n r'^(/u/isreactionarybot)\\s*(?:/?u/)?(?P\\w+)\\s*$',\n re.IGNORECASE|re.MULTILINE\n)\n\nclass SubredditData:#A log of a user's participation in a reactionary subreddit.\n subredditName = ''\n submissionCount = 0\n commentCount = 0\n totalSubmissionKarma = 0\n totalCommentKarma = 0\n submissionPermalinks = None#List cannot be initialized here!\n commentPermalinks = None#List cannot be initialized here!\n\ndef extractUsername(text):\n \"\"\"Extracts the username from the text of a comment or private message. \n \n The bot is summoned on the username found immediately after the bot's name.\n \"\"\"\n match = username_regex.match(text)\n if match:\n return match.group('username')\n else:\n return None\n\ndef isValidUsername(name):\n isValid = False\n \n try:\n redditor = r.get_redditor(name)\n submissions = redditor.get_submitted()\n for submission in submissions:\n isValid = True\n break\n except:\n pass\n \n return isValid\n\ndef hasProcessed(id):#This function returns true if the bot has processed the comment or the private message in question. If it has not processed it, it is about to, so it inserts the id of the comment or private message into a SQL database, so it will not process it twice.\n hasProcessed = True\n \n sqlCursor.execute('SELECT * FROM Identifiers WHERE id=?', (id,))\n if sqlCursor.fetchone() == None:\n hasProcessed = False\n sqlCursor.execute('INSERT INTO Identifiers VALUES (?)', (id,))\n \n sqlConnection.commit()\n return hasProcessed\n\ndef updateSubredditData(subredditDataList, subreddit, item, isComment):#This takes the submission or comment, and updates its corresponding subredditData class with all of its attributes.\n subredditInList = False\n for i in range( len(subredditDataList) ):\n if subredditDataList[i].subredditName.lower() == subreddit:\n subredditInList = True\n if isComment:\n subredditDataList[i].commentCount += 1\n subredditDataList[i].totalCommentKarma += int(item.score)\n if len(subredditDataList[i].commentPermalinks) < 8:\n subredditDataList[i].commentPermalinks.append( str( r.get_info( thing_id=item.link_id ).permalink ) + str(item.id) + '?context=10' )\n else:\n subredditDataList[i].submissionCount += 1\n subredditDataList[i].totalSubmissionKarma += int(item.score)\n if len(subredditDataList[i].submissionPermalinks) < 8:\n subredditDataList[i].submissionPermalinks.append(str(item.permalink))\n break\n if not subredditInList:\n newSubredditData = SubredditData()\n newSubredditData.subredditName = str(item.subreddit)\n if isComment:\n newSubredditData.commentCount = 1\n newSubredditData.totalCommentKarma = int(item.score)\n newSubredditData.commentPermalinks = [ str( r.get_info( thing_id=item.link_id ).permalink ) + str(item.id) + '?context=10' ]\n newSubredditData.submissionPermalinks = []\n else:\n newSubredditData.submissionCount = 1\n newSubredditData.totalSubmissionKarma = int(item.score)\n newSubredditData.submissionPermalinks = [str(item.permalink)]\n newSubredditData.commentPermalinks = []\n subredditDataList.append(newSubredditData)\n return subredditDataList\n\ndef calculateReactionariness(user):#Figure out how reactionary the user is, and return the text to reply with.\n mixedCaseUsername = ''\n nothingToReport = True\n subredditDataList = []\n \n userObj = r.get_redditor(user)\n userSubmissions = userObj.get_submitted(limit=1000)\n userComments = userObj.get_comments(limit=1000)\n \n for submission in userSubmissions:\n if len(mixedCaseUsername) == 0:\n mixedCaseUsername = str(submission.author)\n subreddit = str(submission.subreddit).lower()\n if subreddit in [x.lower() for x in reactionarySubreddits]:\n nothingToReport = False\n subredditDataList = updateSubredditData(subredditDataList, subreddit, submission, False)\n \n for comment in userComments:\n if len(mixedCaseUsername) == 0:\n mixedCaseUsername = str(comment.author)\n subreddit = str(comment.subreddit).lower()\n if subreddit in [x.lower() for x in reactionarySubreddits]:\n nothingToReport = False\n subredditDataList = updateSubredditData(subredditDataList, subreddit, comment, True)\n \n if nothingToReport:\n return 'Nothing found for ' + mixedCaseUsername + '.'\n \n totalScore = 0\n replyText = mixedCaseUsername + ' post history contains participation in the following subreddits:\\n\\n'\n for subredditData in subredditDataList:\n replyText += '/r/' + subredditData.subredditName + ': '\n if len(subredditData.submissionPermalinks) > 0:\n replyText += str(subredditData.submissionCount) + ' posts ('\n for i in range( len(subredditData.submissionPermalinks) ):\n replyText += '[' + str(i+1) + '](' + subredditData.submissionPermalinks[i] + '), '\n replyText = replyText[:-2] + '), **combined score: ' + str(subredditData.totalSubmissionKarma) + '**'\n if len(subredditData.commentPermalinks) > 0:\n replyText += '; '\n if len(subredditData.commentPermalinks) > 0:\n replyText += str(subredditData.commentCount) + ' comments ('\n for i in range( len(subredditData.commentPermalinks) ):\n replyText += '[' + str(i+1) + '](' + subredditData.commentPermalinks[i] + '), '\n replyText = replyText[:-2] + '), **combined score: ' + str(subredditData.totalCommentKarma) + '**'\n replyText += '.\\n\\n'\n totalScore += subredditData.totalSubmissionKarma + subredditData.totalCommentKarma\n \n replyText += '---\\n\\n###Total score: ' + str(totalScore) + '\\n\\n###Recommended Gulag Sentence: '\n if totalScore > 0:\n sentenceLength = (totalScore + 1) ** 3\n if sentenceLength > 1000000000:\n replyText += 'Execution.'\n else:\n replyText += str(sentenceLength) + ' years.'\n else:\n replyText += '0 years.'\n replyText += '\\n\\n---\\n\\nI am a bot. Only the past 1,000 posts and comments are fetched.'\n \n return replyText\n\ndef handleRequest(request):#Handle a user's comment or private message requesting the bot to investigate a user's reactionariness.\n if not hasProcessed(request.id):\n userToInvestigate = extractUsername(request.body)\n if userToInvestigate != None:\n if userToInvestigate == 'isreactionarybot':#For smartasses.\n request.reply('Nice try.')\n elif not isValidUsername(userToInvestigate):\n request.reply('Invalid username.')\n else:\n request.reply( calculateReactionariness(userToInvestigate) )\n\ndef main():\n while True:\n usernameMentions = r.get_mentions()\n for mention in usernameMentions:\n handleRequest(mention)\n \n privateMessages = r.get_messages()\n for message in privateMessages:\n handleRequest(message)\n \n sleep(120)\n return 0\n\nsqlConnection = sqlite3.connect(path + 'isReactionaryBot.db')\nsqlCursor = sqlConnection.cursor()\n\nr = praw.Reddit(user_agent='A program that checks if a user is a reactionary.')\nr.login('isReactionaryBot', password)\n\nsys.stderr = open(path + 'isReactionaryBotOutput.txt', 'w')\n\nif __name__ == '__main__':\n main()\n","sub_path":"isReactionaryBot.py","file_name":"isReactionaryBot.py","file_ext":"py","file_size_in_byte":8720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"199948313","text":"from django.db import models\r\n# from django.conf import settings\r\nfrom django.contrib.contenttypes.fields import GenericForeignKey\r\nfrom django.contrib.contenttypes.models import ContentType\r\nfrom django.dispatch import receiver\r\nfrom analytics.signals import object_accessed_signal\r\nfrom datetime import timedelta\r\nfrom blog.models import article_info\r\nimport re\r\n\r\n# User = settings.AUTH_USER_MODEL\r\n\r\nclass object_accessed_info(models.Model):\r\n auth_id = models.PositiveIntegerField(blank=True, null=True) # nullable,這樣即使user沒登入也看得到\r\n ip_address = models.CharField(max_length=220, blank=True, null=True) # there is an IP Field\r\n url_path = models.CharField(max_length=100, blank=True, null=True) # user 在哪一個頁面瀏覽\r\n api_name = models.CharField(max_length=100, blank=True, null=True) # user 使用哪個 api\r\n model_name = models.CharField(max_length=55, blank=True, null=True) # App 裡面的 models\r\n object_name = models.CharField(max_length=55, blank=True, null=True)\r\n object_id = models.PositiveIntegerField(blank=True, null=True) # models 下面的細項\r\n user_agent = models.CharField(max_length=550, blank=True, null=True)\r\n action_type = models.CharField(max_length=50, blank=True, null=True)\r\n remark = models.CharField(max_length=50, blank=True, null=True)\r\n timestamp = models.DateTimeField(auto_now_add=True)\r\n\r\n def __str__(self):\r\n return f'{self.object_name} viewed by {self.ip_address} on {str(self.timestamp + timedelta(hours=8)).split(\".\")[0]}'\r\n\r\n class Meta:\r\n ordering= ['-timestamp'] # 越新的會被呈現在越上面\r\n verbose_name = 'Object Viewed'\r\n verbose_name_plural = 'Objects Viewed'\r\n\r\n\r\n\r\n@receiver(object_accessed_signal)\r\ndef update_object_accessed_info(sender, **kwargs):\r\n '''\r\n 將前端傳送的資料儲存到 object_accessed_info ,以備日後分析使用。\r\n '''\r\n if kwargs.get('action_type') == 'auth_check':\r\n # 來自 auth_check 的訊號,需要特別處理\r\n # 先檢查 auth_id 是否為有效值\r\n if '/blog/post/' in kwargs.get('url_path'):\r\n # 是文章的url,轉成文章標題回傳\r\n matched_article_id = re.search(r'\\d+', kwargs.get('url_path'))\r\n if matched_article_id is not None:\r\n matched_article_id = matched_article_id.group(0)\r\n object_accessed_info.objects.create(\r\n auth_id=kwargs.get('auth_id'),\r\n ip_address=kwargs.get('ip_address'),\r\n url_path=kwargs.get('url_path'),\r\n api_name='article_content',\r\n model_name='aritcle_info',\r\n object_name=article_info.objects.filter(id=matched_article_id).first().title,\r\n object_id=matched_article_id,\r\n user_agent=kwargs.get('user_agent'),\r\n action_type=kwargs.get('action_type'),\r\n remark=kwargs.get('remark')\r\n ).save()\r\n elif '/blog/main' in kwargs.get('url_path'):\r\n object_accessed_info.objects.create(\r\n auth_id=kwargs.get('auth_id'),\r\n ip_address=kwargs.get('ip_address'),\r\n url_path=kwargs.get('url_path'),\r\n api_name='main_blog',\r\n model_name='aritcle_info',\r\n object_name='main_blog',\r\n object_id=kwargs.get('object_id'),\r\n user_agent=kwargs.get('user_agent'),\r\n action_type=kwargs.get('action_type'),\r\n remark=kwargs.get('remark')\r\n ).save()\r\n elif 'landing' in kwargs.get('url_path'):\r\n object_accessed_info.objects.create(\r\n auth_id=kwargs.get('auth_id'),\r\n ip_address=kwargs.get('ip_address'),\r\n url_path=kwargs.get('url_path'),\r\n api_name=sender,\r\n model_name=kwargs.get('model_name'),\r\n object_name='landing_page',\r\n object_id=kwargs.get('object_id'),\r\n user_agent=kwargs.get('user_agent'),\r\n action_type=kwargs.get('action_type'),\r\n remark=kwargs.get('remark')\r\n ).save()\r\n elif '/account/register/teacher' in kwargs.get('url_path'):\r\n # 初次進到註冊老師的頁面\r\n object_accessed_info.objects.create(\r\n auth_id=kwargs.get('auth_id'),\r\n ip_address=kwargs.get('ip_address'),\r\n url_path=kwargs.get('url_path'),\r\n api_name=sender,\r\n model_name=kwargs.get('model_name'),\r\n object_name='teacher_register_page',\r\n object_id=kwargs.get('object_id'),\r\n user_agent=kwargs.get('user_agent'),\r\n action_type=kwargs.get('action_type'),\r\n remark=kwargs.get('remark')\r\n ).save()\r\n elif '/account/register/student' in kwargs.get('url_path'):\r\n # 初次進到註冊學生的頁面\r\n object_accessed_info.objects.create(\r\n auth_id=kwargs.get('auth_id'),\r\n ip_address=kwargs.get('ip_address'),\r\n url_path=kwargs.get('url_path'),\r\n api_name=sender,\r\n model_name=kwargs.get('model_name'),\r\n object_name='student_register_page',\r\n object_id=kwargs.get('object_id'),\r\n user_agent=kwargs.get('user_agent'),\r\n action_type=kwargs.get('action_type'),\r\n remark=kwargs.get('remark')\r\n ).save()\r\n elif '/lesson/guestready' in kwargs.get('url_path'):\r\n # 進到註冊前開課的頁面\r\n object_accessed_info.objects.create(\r\n auth_id=kwargs.get('auth_id'),\r\n ip_address=kwargs.get('ip_address'),\r\n url_path=kwargs.get('url_path'),\r\n api_name=sender,\r\n model_name='lesson_info_for_users_not_signed_up',\r\n object_name=kwargs.get('object_name'),\r\n object_id=kwargs.get('object_id'),\r\n user_agent=kwargs.get('user_agent'),\r\n action_type='create lesson before signup',\r\n remark=kwargs.get('remark')\r\n ).save()\r\n elif '/lesson/ready/add' in kwargs.get('url_path'):\r\n object_accessed_info.objects.create(\r\n auth_id=kwargs.get('auth_id'),\r\n ip_address=kwargs.get('ip_address'),\r\n url_path=kwargs.get('url_path'),\r\n api_name=sender,\r\n model_name='lesson_info',\r\n object_name=kwargs.get('object_name'),\r\n object_id=kwargs.get('object_id'),\r\n user_agent=kwargs.get('user_agent'),\r\n action_type='create lesson after signup',\r\n remark=kwargs.get('remark')\r\n ).save()\r\n \r\n else:\r\n object_accessed_info.objects.create(\r\n auth_id=kwargs.get('auth_id'),\r\n ip_address=kwargs.get('ip_address'),\r\n url_path=kwargs.get('url_path'),\r\n api_name=sender,\r\n model_name=kwargs.get('model_name'),\r\n object_name=kwargs.get('object_name'),\r\n object_id=kwargs.get('object_id'),\r\n user_agent=kwargs.get('user_agent'),\r\n action_type=kwargs.get('action_type'),\r\n remark=kwargs.get('remark')\r\n ).save()\r\n\r\n\r\n ","sub_path":"Quikok/analytics/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"585517288","text":"# v13 experiment with real data using JointGP_v14\r\n\r\n\r\nfrom JointGP_v14 import linear_jointGP\r\n\r\nimport import_data_exp\r\n# v10: combine diagonal fitting as init; ghost-cigp with mean and scale\r\n\r\nimport torch\r\n# from JointGPx3_v03 import jointModelx3 # working model\r\n# from JointGPx3_v04 import jointModelx3\r\nfrom import_data_exp import import_Matano, import_true_diff, import_poly_diff #, import_true_flux\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n# choosing the ith component iComp\r\niComp = 2 #1,2\r\n\r\nx,C,DuDx,Int_c = import_Matano(2)\r\n##flux = import_true_flux(3)\r\n##D_poly = import_poly_diff(1,3)\r\nD = import_true_diff(2)\r\n# D = D[:,iComp-1,:]\r\n\r\nid_tr = list(range(700,900,10))\r\n# id_tr = list(range(0,1600,5))\r\nid_te = list(range(0,1601,1))\r\n\r\n# move the domninant componnet to the first position as default; linear_jointGP a[0]=1 and a[1,2,...]=0 as initial\r\nDuDx = np.roll(DuDx, (iComp-1), axis=1)\r\nD = np.roll(D, (iComp-1), axis=1)\r\n\r\nintC = Int_c[:,iComp-1:iComp]\r\n\r\n\r\n# convert to torch data\r\nC = torch.tensor(C).float()\r\nDuDx = torch.tensor(DuDx).float()\r\nintC = torch.tensor(intC).float()\r\n\r\n# normalize with only scale\r\nintC_mean = intC.mean()\r\nintC_std = intC.std()\r\n# intC = (intC - intC_mean) / intC_std\r\nintC = intC / intC_std\r\n\r\nfig, ax = plt.subplots()\r\nplt.plot(DuDx[id_tr,0], label = 'dc1',linewidth = 4.0, linestyle = '-')\r\nplt.plot(DuDx[id_tr,1], label = 'dc2',linewidth = 4.0, linestyle = '-')\r\nplt.plot(intC[id_tr,:], label = 'intC',linewidth = 4.0, linestyle = '-')\r\nax.set_xlabel('Distance')\r\nax.set_ylabel('Component')\r\nax.set_title('The Diffusion Simulation')\r\nax.legend()\r\nplt.show()\r\n\r\n# %%\r\nd11_DiagMamtano = intC/DuDx[:,0:1]\r\n\r\nfig, ax = plt.subplots()\r\n\r\nid_stable = list(range(500,1100,1))\r\n# plt.plot(x[:,0], d11_DiagMamtano * intC_std, 'b--', label = 'D11_Matano', linewidth = 4.0,)\r\nplt.plot(x[id_stable,0], d11_DiagMamtano[id_stable,:] * intC_std, 'b--', label = 'D11_Matano', linewidth = 4.0,)\r\n\r\nplt.plot(x[:,0], D[id_te,iComp-1,1], 'k-', label = 'D dominant', linewidth = 4.0,)\r\nax.set_xlabel('Distance')\r\nax.set_ylabel('Component')\r\nax.set_title('D')\r\nax.legend()\r\nplt.show()\r\n\r\n\r\n# %%\r\n# model = jointModelx2(c1, c2, dc1, dc2)\r\n# model.train_adam(c1, c2, dc1, dc2, intC , niteration=1000, lr=0.001)\r\nd11_mean = d11_DiagMamtano[id_stable,:] .mean().item()\r\nd11_std = d11_DiagMamtano[id_stable,:] .std().item()\r\n\r\nmodel = linear_jointGP(C[id_tr,:])\r\n\r\n# pre-train for dominant diffusion coefficient\r\n# model.sub_models[0].ghost_train_adam(C[id_stable,:], d11_DiagMamtano[id_stable,:], niteration=500, lr=0.01)\r\n##model.sub_models[0].ghost_train_adam(C[id_tr,:], d11_DiagMamtano[id_tr,:], niteration=1500, lr=0.002)\r\n\r\n# show\r\nwith torch.no_grad():\r\n d1, d1var = model.sub_models[0].forward(C[id_te,:])\r\n\r\nfig, ax = plt.subplots()\r\nplt.plot(x[id_tr,0], d11_DiagMamtano[id_tr,:] * intC_std, 'x', label = 'training', linewidth = 4.0,)\r\nplt.plot(x[id_te,0], d1 * intC_std, 'b--', label = 'D11_Matano_GP', linewidth = 4.0,)\r\nplt.plot(x[id_te,0], D[id_te,0,iComp-1], 'k-', label = 'D11_true', linewidth = 4.0,)\r\n\r\n# plt.plot(dc2, label = 'C2',linewidth = 4.0, linestyle = '-')\r\n# plt.plot(dc3, label = 'C3',linewidth = 4.0, linestyle = '-')\r\n# plt.plot(intC, label = 'intC',linewidth = 4.0, linestyle = '-')\r\nax.set_xlabel('Distance')\r\nax.set_ylabel('Component')\r\nax.set_title('D11')\r\nax.legend()\r\nplt.show()\r\n\r\n\r\n# model1 = ghost_cigpr(C[id_stable,:], 10, d11_mean, d11_std )\r\n# model1.ghost_train_adam(C[id_stable,:], d11_DiagMamtano[id_stable,:], niteration=100, lr=0.001)\r\n\r\n# %%\r\n# model = jointModelx3(c1, c2, c3, dc1, dc2, dc3, d11_mean, d11_std )\r\nmodel.train_adam(C[id_tr,:], DuDx[id_tr,:], intC[id_tr,:], 8000, lr=0.001)\r\nmodel.train_adam(C[id_tr,:], DuDx[id_tr,:], intC[id_tr,:], 8000, lr=0.001)\r\n\r\n# %%\r\nwith torch.no_grad():\r\n intC_pred, intC_var = model.forward(C[id_te,:], DuDx)\r\n D_pred, D_var = model.forward_eachGP(C[id_te,:])\r\n\r\n # de normalize\r\n D_pred = D_pred * intC_std\r\n D_var = D_var * intC_std**2\r\n\r\n # do each prediction manually\r\n # ypred = []\r\n # yvar = []\r\n # for i, obj in enumerate(model.sub_models):\r\n # # print(i, obj, sep=' ')\r\n # ypred1, yvar1 = obj.forward(C)\r\n # ypred.append(ypred1 * model.a[i])\r\n # yvar.append(yvar1 * model.a[i] ** 2)\r\n #\r\n # D_pred = torch.hstack(ypred)\r\n # D_var = torch.hstack(yvar)\r\n\r\n# %%\r\n# move the domninant componnet back\r\n# D_pred = torch.hstack((ypred1.detach(),ypred2.detach(),ypred3.detach())) *intC_std\r\n# D_var = torch.hstack((yvar1.detach(),yvar2.detach(),yvar3.detach())) *intC_std**2\r\n\r\n# DuDx = np.roll(DuDx, (iComp-1), axis=1)\r\n# D = np.roll(D, (iComp-1), axis=1)\r\nD = import_true_diff(2)\r\n# D = D[:,iComp-1,:]\r\n\r\nD_pred = D_pred.detach().numpy()\r\nD_var = D_var.detach().numpy()\r\n\r\n# roll back to the original order\r\nD_pred = np.roll(D_pred, (iComp-1), axis=1)\r\nD_var = np.roll(D_var, (iComp-1), axis=1)\r\n\r\n\r\n##import os\r\n##saveFolder = os.path.basename(__file__).split('.')[0]\r\n# try:\r\n# os.mkdir(saveFolder)\r\n# finally:\r\n# pass\r\n\r\n\r\nfor i in range(2):\r\n fig, ax = plt.subplots()\r\n\r\n labelName = 'D'+str(iComp) + str(i+1)\r\n plt.plot(x[id_te], D_pred[:,i].data, 'r-.', label=labelName+'predictions', linewidth=3.0)\r\n plt.errorbar(x[id_te], D_pred[:,i].data, np.sqrt(D_var[:,i].data), fmt='r-.', alpha = 0.02)\r\n plt.plot(x[id_te], D[id_te, iComp-1, i], 'b-', label=labelName+'truth', linewidth=3.0)\r\n\r\n ax.set_xlabel('Distance')\r\n ax.set_ylabel('Diffusion Coefficient')\r\n ax.set_title('Our method')\r\n ax.legend(loc='upper right')\r\n # plt.show()\r\n\r\n saveName = '../figure/D_' + str(iComp) + '-' + str(i+1)\r\n plt.savefig(saveName )\r\n\r\n\r\n\r\n# plt.savefig('model3_D13')\r\n\r\n# save the model\r\n# torch.save(model.state_dict(),'Good_Exp_jointGP_v10_data2')\r\n#\r\n# load the model\r\n# model = TheModelClass(*args, **kwargs)\r\n# model.load_state_dict(torch.load(PATH))\r\n\r\n# %%\r\nsaveName = '../data2/D_pred_' + str(iComp) + '.csv'\r\n\r\nimport csv\r\nN_x = D_pred.shape[0]\r\ncsvFile=open(saveName,'w',newline='')\r\ntry:\r\n writer=csv.writer(csvFile)\r\n writer.writerow(('D1','D2','D1 var','D2 var'))\r\n for i in range(N_x):\r\n writer.writerow((D_pred[i,0].item(),\r\n D_pred[i,1].item(),\r\n D_var[i,0].item(),\r\n D_var[i,1].item()))\r\nfinally:\r\n csvFile.close()\r\n","sub_path":"ternary/gp/GP_exp.py","file_name":"GP_exp.py","file_ext":"py","file_size_in_byte":6365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"50698148","text":"\"\"\"PodmanResource manager subclassed for Containers.\"\"\"\nimport urllib\nfrom typing import Any, ClassVar, Dict, List, Mapping, Sequence, Type, Union\n\nfrom podman import api\nfrom podman.domain.containers import Container\nfrom podman.domain.images import Image\nfrom podman.domain.manager import Manager\nfrom podman.errors import APIError, NotFound\n\n\nclass ContainersManager(Manager):\n \"\"\"Specialized Manager for Container resources.\n\n Attributes:\n resource: Container subclass of PodmanResource, factory method will create these.\n \"\"\"\n\n resource: ClassVar[Type[Image]] = Container\n\n def run(\n self,\n image: Union[str, Image],\n command: Union[str, List[str]] = None,\n stdout=True,\n stderr=False,\n remove: bool = False,\n **kwargs,\n ) -> Union[Container, Sequence[str]]:\n \"\"\"Run container.\n\n By default, run() will wait for the container to finish and return its logs.\n\n If detach=True, run() will start the container and return a Container object rather\n than logs.\n\n Args:\n image: Image to run.\n command: Command to run in the container.\n stdout: Include stdout. Default: True.\n stderr: Include stderr. Default: False.\n remove: Delete container when the container's processes exit. Default: False.\n\n Keyword Args:\n auto_remove (bool): Enable auto-removal of the container on daemon side when the\n container's process exits.\n blkio_weight_device (Dict[str, Any]): Block IO weight (relative device weight)\n in the form of: [{\"Path\": \"device_path\", \"Weight\": weight}].\n blkio_weight (int): Block IO weight (relative weight), accepts a weight value\n between 10 and 1000.\n cap_add (List[str]): Add kernel capabilities. For example, [\"SYS_ADMIN\", \"MKNOD\"].\n cap_drop (List[str]): Drop kernel capabilities.\n cgroup_parent (str): Override the default parent cgroup.\n cpu_count (int): Number of usable CPUs (Windows only).\n cpu_percent (int): Usable percentage of the available CPUs (Windows only).\n cpu_period (int): The length of a CPU period in microseconds.\n cpu_quota (int): Microseconds of CPU time that the container can get in a CPU period.\n cpu_rt_period (int): Limit CPU real-time period in microseconds.\n cpu_rt_runtime (int): Limit CPU real-time runtime in microseconds.\n cpu_shares (int): CPU shares (relative weight).\n cpuset_cpus (str): CPUs in which to allow execution (0-3, 0,1).\n cpuset_mems (str): Memory nodes (MEMs) in which to allow execution (0-3, 0,1).\n Only effective on NUMA systems.\n detach (bool): Run container in the background and return a Container object.\n device_cgroup_rules (List[str]): A list of cgroup rules to apply to the container.\n device_read_bps: Limit read rate (bytes per second) from a device in the form of:\n `[{\"Path\": \"device_path\", \"Rate\": rate}]`\n device_read_iops: Limit read rate (IO per second) from a device.\n device_write_bps: Limit write rate (bytes per second) from a device.\n device_write_iops: Limit write rate (IO per second) from a device.\n devices (List[str): Expose host devices to the container, as a List[str] in the form\n ::.\n\n For example,\n /dev/sda:/dev/xvda:rwm allows the container to have read-write access to the\n host's /dev/sda via a node named /dev/xvda inside the container.\n dns (List[str]): Set custom DNS servers.\n dns_opt (List[str]): Additional options to be added to the container's resolv.conf file.\n dns_search (List[str]): DNS search domains.\n domainname (Union[str, List[str]]): Set custom DNS search domains.\n entrypoint (Union[str, List[str]]): The entrypoint for the container.\n environment (Union[Dict[str, str], List[str]): Environment variables to set inside\n the container, as a dictionary or a List[str] in the format\n [\"SOMEVARIABLE=xxx\", \"SOMEOTHERVARIABLE=xyz\"].\n extra_hosts (Dict[str, str]): Additional hostnames to resolve inside the container,\n as a mapping of hostname to IP address.\n group_add (List[str]): List of additional group names and/or IDs that the container\n process will run as.\n healthcheck (Dict[str,str]): Specify a test to perform to check that the\n container is healthy.\n hostname (str): Optional hostname for the container.\n init (bool): Run an init inside the container that forwards signals and reaps processes\n init_path (str): Path to the docker-init binary\n ipc_mode (str): Set the IPC mode for the container.\n isolation (str): Isolation technology to use. Default: `None`.\n kernel_memory (int or str): Kernel memory limit\n labels (Union[Dict[str, str], List[str]): A dictionary of name-value labels (e.g.\n {\"label1\": \"value1\", \"label2\": \"value2\"}) or a list of names of labels to set\n with empty values (e.g. [\"label1\", \"label2\"])\n links (Optional[Dict[str, str]]): Mapping of links using the {'container': 'alias'}\n format. The alias is optional. Containers declared in this dict will be linked to\n the new container using the provided alias. Default: None.\n log_config (LogConfig): Logging configuration.\n lxc_conf (Dict[str, str]): LXC config.\n mac_address (str): MAC address to assign to the container.\n mem_limit (Union[int, str]): Memory limit. Accepts float values (which represent the\n memory limit of the created container in bytes) or a string with a units\n identification char (100000b, 1000k, 128m, 1g). If a string is specified without\n a units character, bytes are assumed as an intended unit.\n mem_reservation (Union[int, str]): Memory soft limit.\n mem_swappiness (int): Tune a container's memory swappiness behavior. Accepts number\n between 0 and 100.\n memswap_limit (Union[int, str]): Maximum amount of memory + swap a container is allowed\n to consume.\n mounts (List[str]): Specification for mounts to be added to the container. More\n powerful alternative to volumes. Each item in the list is expected to be a\n Mount object.\n name (str): The name for this container.\n nano_cpus (int): CPU quota in units of 1e-9 CPUs.\n network (str): Name of the network this container will be connected to at creation time.\n You can connect to additional networks using Network.connect.\n Incompatible with network_mode.\n network_disabled (bool): Disable networking.\n network_mode (str): One of:\n\n - bridge: Create a new network stack for the container on\n on the bridge network.\n - none: No networking for this container.\n - container:: Reuse another container's network\n stack.\n - host: Use the host network stack.\n\n Incompatible with network.\n oom_kill_disable (bool): Whether to disable OOM killer.\n oom_score_adj (int): An integer value containing the score given to the container in\n order to tune OOM killer preferences.\n pid_mode (str): If set to host, use the host PID namespace\n inside the container.\n pids_limit (int): Tune a container's pids limit. Set -1 for unlimited.\n platform (str): Platform in the format os[/arch[/variant]]. Only used if the method\n needs to pull the requested image.\n ports (Dict[str, Union[int, Tuple[str, int], List[int]): Ports to bind inside\n the container.\n\n The keys of the dictionary are the ports to bind inside the container, either as an\n integer or a string in the form port/protocol, where the protocol is either\n tcp, udp, or sctp.\n\n The values of the dictionary are the corresponding ports to open on the host,\n which can be either:\n\n - The port number, as an integer. For example,\n {'2222/tcp': 3333} will expose port 2222 inside the container as port 3333 on the\n host.\n - None, to assign a random host port. For example,\n {'2222/tcp': None}.\n - A tuple of (address, port) if you want to specify the host interface. For example,\n {'1111/tcp': ('127.0.0.1', 1111)}.\n - A list of integers, if you want to bind multiple host ports to a single container\n port. For example, {'1111/tcp': [1234, 4567]}.\n\n privileged (bool): Give extended privileges to this container.\n publish_all_ports (bool): Publish all ports to the host.\n read_only (bool): Mount the container's root filesystem as read only.\n remove (bool): Remove the container when it has finished running. Default: False.\n restart_policy (Dict[str, Union[str, int]]): Restart the container when it exits.\n Configured as a dictionary with keys:\n\n - Name: One of on-failure, or always.\n - MaximumRetryCount: Number of times to restart the container on failure.\n\n For example:\n {\"Name\": \"on-failure\", \"MaximumRetryCount\": 5}\n\n runtime (str): Runtime to use with this container.\n security_opt (List[str]): A List[str]ing values to customize labels for MLS systems,\n such as SELinux. shm_size (Union[str, int]): Size of /dev/shm (e.g. 1G).\n stdin_open (bool): Keep STDIN open even if not attached.\n stdout (bool): Return logs from STDOUT when detach=False. Default: True.\n stderr (bool): Return logs from STDERR when detach=False. Default: False.\n stop_signal (str): The stop signal to use to stop the container (e.g. SIGINT).\n storage_opt (Dict[str, str]): Storage driver options per container as a\n key-value mapping.\n stream (bool): If true and detach is false, return a log generator instead of a string.\n Ignored if detach is true. Default: False.\n sysctls (Dict[str, str]): Kernel parameters to set in the container.\n tmpfs (Dict[str, str]): Temporary filesystems to mount, as a dictionary mapping a\n path inside the container to options for that path.\n\n For example:\n\n {\n '/mnt/vol2': '',\n '/mnt/vol1': 'size=3G,uid=1000'\n }\n\n tty (bool): Allocate a pseudo-TTY.\n ulimits (List[Ulimit]): Ulimits to set inside the container.\n use_config_proxy (bool): If True, and if the docker client configuration\n file (~/.config/containers/config.json by default) contains a proxy configuration,\n the corresponding environment variables will be set in the container being built.\n user (Union[str, int]): Username or UID to run commands as inside the container.\n userns_mode (str): Sets the user namespace mode for the container when user namespace\n remapping option is enabled. Supported values are: host\n uts_mode (str): Sets the UTS namespace mode for the container.\n Supported values are: host\n version (str): The version of the API to use. Set to auto to automatically detect\n the server's version. Default: 3.0.0\n volume_driver (str): The name of a volume driver/plugin.\n volumes (Dict[str, Dict[str, str]]): A dictionary to configure volumes mounted inside\n the container. The key is either the host path or a volume name, and the value is\n a dictionary with the keys:\n\n - bind The path to mount the volume inside the container\n - mode Either rw to mount the volume read/write, or ro to mount it read-only.\n\n For example:\n\n {'/home/user1/': {'bind': '/mnt/vol2', 'mode': 'rw'},\n '/var/www': {'bind': '/mnt/vol1', 'mode': 'ro'}}\n\n volumes_from (List[str]): List of container names or IDs to get volumes from.\n working_dir (str): Path to the working directory.\n \"\"\"\n\n if isinstance(image, Image):\n image = image.id\n\n _ = command\n _ = stdout\n _ = stderr\n _ = remove\n _ = kwargs\n raise NotImplementedError\n\n def create(\n self, image: Union[Image, str], command: Union[str, List[str]] = None, **kwargs\n ) -> Container:\n \"\"\"Create a container.\n\n See Container.run() for arguments. The following are ignored: stdout, stderr, and remove.\n\n Raises:\n ImageNotFound: If given image does not exist.\n APIError: If service returns an error.\n \"\"\"\n if isinstance(image, Image):\n image = image.id\n\n _ = kwargs\n # TODO: Create container create\n _ = command\n # TODO: Get new container\n raise NotImplementedError\n\n # pylint is flagging 'container_id' here vs. 'key' parameter in super.get()\n def get(self, container_id: str) -> Container: # pylint: disable=arguments-differ\n \"\"\"Get container by name or id.\n\n Args:\n container_id: Container name or id.\n\n Raises:\n NotFound: Container does not exist.\n APIError: Error return by service.\n \"\"\"\n container_id = urllib.parse.quote_plus(container_id)\n response = self.client.get(f\"/containers/{container_id}/json\")\n body = response.json()\n\n if response.status_code == 200:\n return self.prepare_model(body)\n\n if response.status_code == 404:\n raise NotFound(body[\"cause\"], response=response, explanation=body[\"message\"])\n raise APIError(body[\"cause\"], response=response, explanation=body[\"message\"])\n\n def list(self, **kwargs) -> List[Container]:\n \"\"\"Report on containers.\n\n Keyword Args:\n all: If False, only show running containers. Default: False.\n since: Show containers created after container name or id given.\n before: Show containers created before container name or id given.\n limit: Show last N created containers.\n filters: Filter container reported.\n Available filters:\n\n - exited (int): Only containers with specified exit code\n - status (str): One of restarting, running, paused, exited\n - label (Union[str, List[str]]): Format either \"key\", \"key=value\" or a list of such.\n - id (str): The id of the container.\n - name (str): The name of the container.\n - ancestor (str): Filter by container ancestor. Format of\n [:tag], , or .\n - before (str): Only containers created before a particular container.\n Give the container name or id.\n - since (str): Only containers created after a particular container.\n Give container name or id.\n sparse: Ignored\n ignore_removed: If True, ignore failures due to missing containers.\n\n Raises:\n APIError: If service returns an error.\n \"\"\"\n params = {\n \"all\": kwargs.get(\"all\", None),\n \"filters\": kwargs.get(\"filters\", dict()),\n \"limit\": kwargs.get(\"limit\", None),\n }\n if \"before\" in kwargs:\n params[\"filters\"][\"before\"] = kwargs.get('before')\n if \"since\" in kwargs:\n params[\"filters\"][\"since\"] = kwargs.get('since')\n\n # filters formatted last because some kwargs need to be mapped into filters\n if len(params[\"filters\"]) > 0:\n params[\"filters\"] = api.format_filters(params[\"filters\"])\n\n response = self.client.get(\"/containers/json\", params=params)\n body = response.json()\n\n if response.status_code != 200:\n raise APIError(body[\"cause\"], response=response, explanation=body[\"message\"])\n\n containers: List[Container] = []\n for element in body:\n containers.append(self.prepare_model(element))\n return containers\n\n def prune(self, filters: Mapping[str, str] = None) -> Dict[str, Any]:\n \"\"\"Delete stopped containers.\n\n Args:\n filters: Dict of criteria for determining containers to remove. Available keys are:\n - until (str): Delete containers before this time\n - label (List[str]): Labels associated with containers\n\n Returns:\n List of deleted container id's and the freed disk space in bytes.\n\n Raises:\n APIError: If service reports an error\n \"\"\"\n params = dict()\n if filters is not None:\n params = {\"filters\", api.format_filters(filters)}\n\n response = self.client.post(\"/containers/prune\", params=params)\n body = response.json()\n\n if response.status_code != 200:\n raise APIError(body[\"cause\"], response=response, explanation=body[\"message\"])\n\n results = {\"ContainersDeleted\": [], \"SpaceReclaimed\": 0}\n for entry in body:\n if entry.get(\"error\", None) is not None:\n raise APIError(entry[\"error\"], response=response, explanation=entry[\"error\"])\n\n results[\"ContainersDeleted\"].append(entry[\"id\"])\n results[\"SpaceReclaimed\"] += entry[\"space\"]\n return results\n","sub_path":"podman/domain/containers_manager.py","file_name":"containers_manager.py","file_ext":"py","file_size_in_byte":18303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"309226151","text":"import chainer\nfrom dcgan_net import Generator, Discriminator, IMAGE_SIZE\nimport os\nfrom PIL import Image\nfrom chainer import training, iterators, optimizers\nfrom chainer.training import extensions\nfrom custom_updater import Updater\nimport numpy as np\nBATCH_SIZE = 10\nDEVICE = 1\nRESUME=False\ndef train():\n model_gen = Generator()\n model_dis = Discriminator()\n\n if DEVICE >= 0:\n chainer.cuda.get_device_from_id(DEVICE).use()\n chainer.cuda.check_cuda_available()\n model_gen.to_gpu(DEVICE)\n model_dis.to_gpu(DEVICE)\n\n images = []\n\n fs = os.listdir('train')\n for f in fs:\n img = Image.open(\n 'train/'+f).convert('RGB').resize((IMAGE_SIZE, IMAGE_SIZE))\n hpix = np.array(img, dtype=np.float32)/255.0\n hpix = hpix.transpose(2, 0, 1)\n images.append(hpix)\n\n train_iter = iterators.SerialIterator(images, BATCH_SIZE, shuffle=True)\n\n optimizer_gen = optimizers.Adam(alpha=0.0002, beta1=0.5)\n optimizer_gen.setup(model_gen)\n optimizers_dis = optimizers.Adam(alpha=0.0002, beta1=0.5)\n optimizers_dis.setup(model_dis)\n\n updater = Updater(\n train_iter, {'opt_gen': optimizer_gen, 'opt_dis': optimizers_dis}, device=DEVICE)\n\n trainer = training.Trainer(updater, (100000, 'epoch'), out='result')\n trainer.extend(extensions.ProgressBar())\n\n snapshot_interval = (5000, 'epoch')\n trainer.extend(extensions.snapshot(\n filename='snapshot_epoch_{.updater.epoch}.npz'),\n trigger=snapshot_interval)\n trainer.extend(extensions.snapshot_object(\n model_gen, 'model_gen_epoch_{.updater.epoch}.npz'), trigger=snapshot_interval)\n trainer.extend(extensions.snapshot_object(\n model_dis, 'model_dis_epoch_{.updater.epoch}.npz'), trigger=snapshot_interval)\n if RESUME:\n chainer.serializers.load_npz('result/snapshot_epoch_26797.npz',trainer)\n trainer.run()\n\n\ndef main():\n train()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"deeplearning/chainer/autoGenerate/dcgan/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"544775203","text":"from typing import Callable\n\nfrom django.http import HttpRequest\nfrom django.utils.timezone import now\n\nfrom axes.exceptions import AxesSignalPermissionDenied\nfrom axes.helpers import (\n get_client_ip_address,\n get_client_user_agent,\n get_client_path_info,\n get_client_http_accept,\n get_lockout_response,\n toggleable,\n)\nfrom axes.request import AxesHttpRequest\n\n\nclass AxesMiddleware:\n \"\"\"\n Middleware that calculates necessary HTTP request attributes for attempt monitoring\n and maps lockout signals into readable HTTP 403 Forbidden responses.\n\n By default Django server returns ``PermissionDenied`` exceptions as HTTP 403 errors\n with the ``django.views.defaults.permission_denied`` view that renders\n the ``403.html`` template from the root template directory if found.\n\n This middleware recognizes the specialized attempt monitoring and lockout exceptions\n and uses the ``axes.helpers.get_lockout_response`` handler for returning\n customizable and context aware lockout message to the end user.\n\n To customize the error handling behaviour further, you can subclass this middleware\n and change the ``process_exception`` handler to your own liking.\n\n Please see the following configuration flags before customizing this handler:\n\n - ``AXES_LOCKOUT_TEMPLATE``,\n - ``AXES_LOCKOUT_URL``,\n - ``AXES_COOLOFF_MESSAGE``, and\n - ``AXES_PERMALOCK_MESSAGE``.\n \"\"\"\n\n def __init__(self, get_response: Callable):\n self.get_response = get_response\n\n def __call__(self, request: HttpRequest):\n self.update_request(request)\n return self.get_response(request)\n\n @toggleable\n def update_request(self, request: HttpRequest):\n \"\"\"\n Construct an ``AxesHttpRequest`` from the given ``HttpRequest``\n by updating the request with necessary attempt tracking attributes.\n\n This method is called by the middleware class ``__call__`` method\n when iterating over the middleware stack.\n \"\"\"\n\n request.axes_attempt_time = now()\n request.axes_ip_address = get_client_ip_address(request)\n request.axes_user_agent = get_client_user_agent(request)\n request.axes_path_info = get_client_path_info(request)\n request.axes_http_accept = get_client_http_accept(request)\n\n @toggleable\n def process_exception(self, request: AxesHttpRequest, exception): # pylint: disable=inconsistent-return-statements\n \"\"\"\n Handle exceptions raised by the Axes signal handler class when requests fail checks.\n\n Note that only ``AxesSignalPermissionDenied`` is handled by this middleware class.\n\n :return: Configured ``HttpResponse`` for failed authentication attempts and lockouts.\n \"\"\"\n\n if isinstance(exception, AxesSignalPermissionDenied):\n return get_lockout_response(request)\n","sub_path":"axes/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"196723308","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.header import Header\nfrom email.mime.text import MIMEText\nfrom email.mime.image import MIMEImage\n\n\n# 发件方STMP配置\n# STMP服务器\nmail_server = \"smtp.163.com\"\n# 用来发送邮件的邮箱\nmail_user = \"leoerstest@163.com\"\n# 邮箱密码,与mail_user对应\nmail_pwd = \"20140901\"\n\n\n# 收发件双方邮箱\n# 发件方邮箱,必须和mail_user一致,否则邮件发送不成功\nsender = mail_user\n# 接收邮件的邮箱,多��收件人以数组形式赋值\nreceivers = [\"harryashy@sina.com\",\"harry@leomaster.com\",\"harryashy@icloud.com\"]\n\n\n# 邮件内容配置\nfp_html = open(\"../report.html\", \"r\", encoding='utf-8')\nhtml = fp_html.read()\nfp_html.close()\n\nmail = MIMEMultipart(\"mixed\")\n\n# 文本内容\nmail_plain = MIMEText(html, \"html\", \"utf-8\")\nmail.attach(mail_plain)\n\n# html附件\nmail_html = MIMEText(html, \"html\", \"utf-8\")\nmail_html[\"Content-Disposition\"] = 'attachment; filename=\"TestReport.html\"'\nmail.attach(mail_html)\n\n# 图片内容\nfp_image = open(\"../resource/image.jpg\",\"rb\")\nimage = fp_image.read()\nmail_img = MIMEImage(image)\nfp_image.close()\nmail_img.add_header('Content-ID', '')\nmail.attach(mail_img)\n\n# 邮件头配置\n# 邮件标题\nmail_title = \"Python SMTP 邮件测试\"\nmail[\"Subject\"] = Header(mail_title, \"utf-8\")\n#发件人,必须和mail_user一致,否则邮件发送不成功\nmail[\"From\"] = mail_user\n#邮件头上显示的收件人,可直接赋值邮箱地址,当与receviers不一致时,receviers里包含的收件人仍能收到邮件,但邮件头上不会显示该收件人\nmail[\"To\"] = \";\".join(receivers)\n\n\n# 发送邮件\ntry:\n smtpObj = smtplib.SMTP()\n smtpObj.connect(mail_server)\n user = smtpObj.login(mail_user, mail_pwd)\n smtpObj.sendmail(sender, receivers, mail.as_string())\n smtpObj.quit()\n print(\"邮件发送成功\")\nexcept smtplib.SMTPException:\n print(\"Error: 无法发送邮件\")","sub_path":"tools/sendemail.py","file_name":"sendemail.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"507093540","text":"# -*- coding: utf-8 -*-\n\nimport json\n\nimport pika\nfrom django.conf import settings as project_settings\n\nfrom apps.core.queue_system.methods import ConsumerMethods\nfrom . import settings\n\n\nclass BaseConsumer(object):\n exchange_name = settings.QUEUE_SETTINGS['EXCHANGE_NAME']\n exchange_type = settings.QUEUE_SETTINGS['EXCHANGE_TYPE']\n consumer_name = None\n\n def init_consumer(self):\n\n self.__make_connection()\n self.__queue_declare()\n self.__exchange_declare()\n self.__queue_bind()\n\n def base_consume(self):\n \"\"\"\n Make consume for catching message\n :return:\n \"\"\"\n\n self.channel.basic_consume(self.__callback, queue=self.queue_name)\n self.channel.start_consuming()\n\n def __callback(self, ch, method, properties, body):\n \"\"\"\n The main method that will run automatically on catching message\n :param ch:\n :param method:\n :param properties:\n :param body:\n :return:\n \"\"\"\n\n try:\n body = json.loads(body.decode('utf-8'))\n except json.decoder.JSONDecodeError:\n return False\n\n print('[*] Recieved [' + str(body) + ']')\n\n # Check if the passed routing key available in the settings\n try:\n settings.ROUTING_KEYS[self.consumer_name][method.routing_key]\n except KeyError:\n print('!!! INVALID CONSUMER OR ROUNTING KEY [' + str(self.consumer_name) + ' - ' + str(\n method.routing_key) + '] !!!')\n return False\n\n # Call all methods in received routing key\n for consumer_method in settings.ROUTING_KEYS[self.consumer_name][method.routing_key]:\n\n ConsumerMethods.body = body\n try:\n getattr(ConsumerMethods, consumer_method)()\n except Exception as e:\n from django.core.mail import send_mail\n send_mail(\n subject='Default consumers crashed',\n message=str(e),\n from_email=project_settings.SENDER_EMAIL,\n recipient_list=['levon2111@gmail.com']\n )\n\n def __make_connection(self):\n \"\"\"\n Make connection with RabbitMQ Server\n :return:\n \"\"\"\n credentials = pika.PlainCredentials('calorie_user', 'root')\n self.connection = pika.BlockingConnection(\n pika.ConnectionParameters(host='localhost', virtual_host='calorie', credentials=credentials))\n self.channel = self.connection.channel()\n\n def __queue_declare(self):\n \"\"\"\n Create queue\n :return:\n \"\"\"\n\n queue_details = self.channel.queue_declare(exclusive=True)\n self.queue_name = queue_details.method.queue\n\n def __exchange_declare(self):\n \"\"\"\n Create exchange if not exists\n :return:\n \"\"\"\n\n self.channel.exchange_declare(exchange=self.exchange_name, exchange_type=self.exchange_type)\n\n def __queue_bind(self):\n \"\"\"\n Make connection between queue and exchange by routing key\n :return:\n \"\"\"\n\n try:\n settings.ROUTING_KEYS[self.consumer_name]\n except KeyError:\n return\n\n for key in settings.ROUTING_KEYS[self.consumer_name]:\n self.channel.queue_bind(exchange=self.exchange_name, queue=self.queue_name, routing_key=key)\n","sub_path":"apps/core/queue_system/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":3402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"602018454","text":"import numpy as np\nimport cv2 as cv\nimport matplotlib.pyplot as plt\n\nbase_path = './opencv/data/'\n\nimg = cv.imread(base_path + '1.jpg')\nres = cv.resize(img, None, fx=2, fy=2, interpolation=cv.INTER_CUBIC)\n# or\n# height, width = img.shape[:2]\n# res = cv.resize(img, (2*width, 2*height), interpolation=cv.INTER_CUBIC)\n\ncv.imshow('img', img)\ncv.imshow('res', res)\ncv.waitKey(0)\ncv.destroyAllWindows()\n\n# 偏移\nimg = cv.imread(base_path + '1.jpg', 0)\nrows, cols = img.shape\nprint(rows, cols)\nM = np.float32([[1, 0, 100], [0, 1, 50]])\ndst = cv.warpAffine(img, M, (rows, cols))\ncv.imshow('dst', dst)\ncv.waitKey(0)\ncv.destroyAllWindows()\n\n# 旋转\nM = cv.getRotationMatrix2D(((cols-1)/2.0, (rows-1)/2.0), 90, 0.5)\ndst = cv.warpAffine(img,M,(cols,rows))\ncv.imshow('dst', dst)\ncv.waitKey(0)\ncv.destroyAllWindows()\n\n# 透视变换/投影变换\nimg = cv.imread(base_path + '1.jpg')\nres = img[:,:,::-1]\npts1 = np.float32([[100,0],[400,0],[0,400],[400,400]])\npts2 = np.float32([[0,0],[300,0],[0,300],[300,300]])\nM = cv.getPerspectiveTransform(pts1,pts2)\ndst = cv.warpPerspective(res,M,(300,300))\nplt.subplot(121),plt.imshow(res),plt.title('Input')\nplt.subplot(122),plt.imshow(dst),plt.title('Output')\nplt.show()","sub_path":"opencv/study/3ImageProcess/1ImageTransform.py","file_name":"1ImageTransform.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"446970037","text":"import os\nimport time\n\nimport requests\n\nclass maoyan():\n\tdef __init__(self):\n\t\tself.headers = {\n\t\t\t'Host': 'piaofang.maoyan.com',\n\t\t\t'Referer': 'https://piaofang.maoyan.com/dashboard',\n\t\t\t'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36 LBBROWSER',\n\t\t\t'X-Requested-With': 'XMLHttpRequest'\n\t\t}\n\t\t\n\tdef get_page(self):\n\t\turl = 'https://box.maoyan.com/promovie/api/box/second.json'\n\t\ttry:\n\t\t\tresponse = requests.get(url, self.headers)\n\t\t\tif response.status_code == 200:\n\t\t\t\treturn response.json()\n\t\texcept requests.ConnectionError as e:\n\t\t\t\tprint('Error', e.args)\n\n\tdef parse_page(self, json):\n\t\tif json:\n\t\t\tdata = json.get('data')\n\t\t\t# 分账票房\n\t\t\t# info['splitTotalBox'] = data['splitTotalBox'] + data['splitTotalBoxUnit']\n\t\t\t# info['splitTotalBoxInfo'] = data['splitTotalBoxInfo'] + data['splitTotalBoxUnitInfo']\n\t\t\t# 电影名称, 票房, 票房占比, 场均上座率, 场均人次, 平均票价, 排片场次, 排片占比, 总票房, 上映信息(上映天数)\n\t\t\tself.dimensions = ['movieName', 'boxInfo', 'boxRate', 'avgSeatView', 'avgShowView', 'avgViewBox', 'showInfo', 'showRate', 'sumBoxInfo', 'releaseInfo',]\n\t\t\t# 分账平均票价, 座位费率, 分割票房, 分账票房占比, 分账总票房, 查看信息, 查看信息V2\n\t\t\t# extend_dimensions = ['splitAvgViewBox', 'seatRate', 'splitBoxInfo', 'splitBoxRate', 'splitSumBoxInfo', 'viewInfo', 'viewInfoV2']\n\t\t\tfor index, item in enumerate(data.get('list')):\n\t\t\t\tself.piaofang = {}\n\t\t\t\tfor dimension in self.dimensions:\n\t\t\t\t\tself.piaofang[dimension] = item.get(dimension)\n\t\t\t\tyield self.piaofang\n\t\t\t\t\n\tdef main(self):\n\t\tx_line = '-' * 155\n\t\twhile True:\n\t\t\tjson = self.get_page()\n\t\t\tresults = self.parse_page(json)\n\t\t\tos.system('cls')\n\t\t\tprint(json.get('data')['updateInfo'])\n\t\t\tprint(f\"今日总票房: {json.get('data')['totalBox']} {json.get('data')['totalBoxUnit']}\", end=f'\\n{x_line}\\n')\n\t\t\tprint('电影名称', '综合票房(万)', '票房占比', '场均上座率', '场均人次', '平均票价', '排片场次', '排片占比', '累积总票房', '上映天数', sep='\\t', end=f'\\n{x_line}\\n')\n\t\t\tfor result in results:\n\t\t\t\tformat_list = []\n\t\t\t\tfor dimension in self.dimensions:\n\t\t\t\t\tif dimension == 'movieName':\n\t\t\t\t\t\tformat_list.append(result[dimension][: 7].ljust(8))\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tformat_list.append(result[dimension][: 8].ljust(8))\n\n\t\t\t\tmovie_data = '\\t'.join(format_list)\n\t\t\t\tprint(movie_data, end='\\n\\n')\n\t\t\ttime.sleep(4)\n\nif __name__ == \"__main__\":\n\tmy = maoyan()\n\tmy.main()","sub_path":"ComputerAndNetwork/Languages/Python/Application/WebCrawler/piaofang.maoyan.com/piaofang.maoyan.py","file_name":"piaofang.maoyan.py","file_ext":"py","file_size_in_byte":2550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"292239627","text":"import tkinter as tk\nfrom tkinter import filedialog\nfrom importlib import reload\nimport random\nimport os\nfrom datetime import datetime\n\nimport exercise\nreload(exercise)\n\n\nclass Exercise(exercise.Exercise_Frame):\n name = 'Фразы'\n\n def __init__(self, master, main_menu, cnf={}, **kw):\n self.file_path = filedialog.askopenfilename(initialdir=os.path.dirname(__file__),\n title=\"Select file\", filetypes=((\"txt files\", \"*.txt\"), ))\n \n exercise.Exercise_Frame.__init__(self, master, main_menu, cnf, **kw)\n\n self.time = 10 #time for entering phrase\n\n def get_phrases_from_file(self) -> list:\n folder = os.path.dirname(__file__)\n\n with open(os.path.join(folder, self.file_path), encoding='utf-8') as f:\n phrases = f.read().split('\\n')\n phrases = [phrase for phrase in phrases if \" - \" not in phrase]\n return phrases\n \n def check_entered_phrase(self):\n entered_phrase = self.write_entry.get()\n\n max_match_percent = 0\n max_match_phrase = ''\n \n for learned in self.learned_phrases:\n match_percent = self.get_strings_match_percent(entered_phrase, learned)\n if match_percent > max_match_percent:\n max_match_percent = match_percent\n max_match_phrase = learned\n\n if max_match_percent > 80:\n self.phrase_is_right(phrase=max_match_phrase)\n \n def cut_phrase(self, phrase) -> (str, str):\n phrase = phrase.split(' ')\n part1 = ' '.join(phrase[len(phrase)//2:])\n part2 = ' '.join(phrase[:len(phrase)//2])\n return part1, part2","sub_path":"phrases/phrases.py","file_name":"phrases.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"256791192","text":"__author__ = \"Luke Liu\"\n#encoding=\"utf-8\"\n\n# 使用TensorFlow实现卷积层,主要需要5个主要参数 input_tensor,filter,strides & padding,biases\n# 输入\n# x:[batch, height, width, in_channel]\n# 权重\n# w:[height, width, in_channel, out_channel]\n# 输出\n# y:[batch, height, width, out_channel]\n\nimport tensorflow as tf\n\ninput_tensor = tf.get_variable(\"input\",[None,28,28,3])\nfilter_weight=tf.get_variable(\"filter\",[5,5,3,16],tf.float32,\n initializer=tf.truncated_normal_initializer(stddev=0.1))\n\nbiases=tf.get_variable(\"biases\",[16],initializer=tf.constant_initializer(0.1))\n\nstride=1\n# 其中 same 表示全0填充,vaid 表示 不填充,默认为valid\n# padding=\"SAME\"\n# padding=\"VALID\"\n# N = ( W -F +2P)/S +1\nconv=tf.nn.conv2d(input_tensor,filter_weight,[1,stride,stride,1],padding=\"SAME\")\n# 添加偏置项\nbiases=tf.nn.bias_add(conv,biases)\n\n# 最后通过激活函数,作为卷积层的输出\nactive_conv = tf.nn.relu(biases)\n\n\n\n# 可以将其写成一个函数,卷积层与其输出\ndef layer_conv2d(input_tensor,out_channel,ksize,stride,padding):\n input_channel=input_tensor.shape[3]\n filter_weight=tf.get_variable(\"filter_weight\",[ksize,ksize,input_channel,out_channel],\n tf.float32,initializer=tf.truncated_normal_initializer(stddev=1))\n\n biases=tf.get_variable(\"biases\",[out_channel],tf.float32,\n initializer=tf.constant_initializer(0.1))\n\n conv2d = tf.nn.conv2d(input_tensor,filter_weight,[1,stride,stride,1],padding=padding)\n\n biases = tf.nn.bias_add(conv2d,biases)\n active_conv=tf.nn.relu(biases)\n\n return active_conv\n# 卷积层与最大池化层的输出\ndef layer_con2d_with_maxpooling(input_tensor,out_channel,ksize,stride,padding):\n input_channel = input_tensor.shape[3]\n filter_weight = tf.get_variable(\"filter_weight\", [ksize, ksize, input_channel, out_channel],\n tf.float32, initializer=tf.truncated_normal_initializer(stddev=1))\n\n biases = tf.get_variable(\"biases\", [out_channel], tf.float32,\n initializer=tf.constant_initializer(0.1))\n\n conv2d = tf.nn.conv2d(input_tensor, filter_weight, [1, stride, stride, 1], padding=padding)\n\n biases = tf.nn.bias_add(conv2d, biases)\n active_conv = tf.nn.relu(biases)\n # ksize中,第一个与最后一个参数是固定的,中间代表过滤器的尺寸,\n # strides 代表步长。\n # 计算公式是相同的,N = ( W - F + 2P ) / S + 1\n max_pooling = tf.nn.max_pool(active_conv,ksize=[1,3,3,1],strides=[1,2,2,1],\n padding='SAME ')\n avg_pooling=tf.nn.avg_pool(active_conv,ksize=[1,3,3,1],strides=[1,2,2,1],\n padding='VALID')\n return max_pooling\n","sub_path":"卷积网络TensorFlow/Concept/简单的卷积层实现.py","file_name":"简单的卷积层实现.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"644894256","text":"## 2. Array Comparisons ##\n\ncountries_canada = (world_alcohol[:,2] == \"Canada\")\nyears_1984 = (world_alcohol[:,0] == \"1984\")\n\n\n## 3. Selecting Elements ##\n\ncountry_is_algeria = (world_alcohol[:,2] == 'Algeria')\ncountry_algeria = world_alcohol[country_is_algeria,:]\n \n\n## 4. Comparisons with Multiple Conditions ##\n\nis_algeria_and_1986 = (world_alcohol[:,0]=='1986') & (world_alcohol[:,2]=='Algeria')\n\nrows_with_algeria_and_1986 = world_alcohol[is_algeria_and_1986,:]\n\n\n## 5. Replacing Values ##\n\nis_1986 = world_alcohol[:,0]=='1986'\nworld_alcohol[is_1986,0] = '2014'\n\nis_wine = world_alcohol[:,3]=='Wine'\nworld_alcohol[is_wine,3]='Grog'\n\n\n## 6. Replacing Empty Strings ##\n\nis_value_empty=world_alcohol[:,4]==''\nworld_alcohol[is_value_empty,4]=0\n\n\n## 7. Converting Data Types ##\n\nalcohol_consumption=world_alcohol[:,4]\nalcohol_consumption.astype(float)\n\n\n## 8. Computing with NumPy ##\n\ntotal_alcohol=alcohol_consumption.sum(0)\naverage_alcohol = alcohol_consumption.mean(0)\n\n\n\n## 9. Total Annual Alcohol Consumption ##\n\ncanada_1986=world_alcohol[(world_alcohol[:,0]=='1986')&(world_alcohol[:,2]=='Canada'),:]\ncanada_1986[canada_1986[:,4]=='',4]=0\ncanada_alcohol=canada_1986[:,4].astype(float)\ntotal_canadian_drinking=canada_alcohol.sum(0)\n\n\n## 10. Calculating Consumption for Each Country ##\n\ntotals = {}\n\ndef compute_country(country,year):\n temporary=world_alcohol[(world_alcohol[:,0]==year)&(world_alcohol[:,2]==country),:]\n temporary[temporary[:,4]=='',4]=0\n result=temporary[:,4].astype(float)\n return result.sum(0)\n\nfor country in countries:\n totals[country] = compute_country(country,'1989')\n\n \n\n## 11. Finding the Country that Drinks the Most ##\n\nhighest_value = 0\nhighest_key = None\n\nfor key,value in totals.items():\n if value >= highest_value:\n highest_value = value\n highest_key = key\n\n ","sub_path":"Python - Projets/DataQuest - 2018-04/data-analysis-intermediate/Computation with NumPy-261.py","file_name":"Computation with NumPy-261.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"300577415","text":"import json\nimport string\nimport random\n\nfrom flask import request, jsonify\n\nfrom app import app, db, logger, rule\nfrom app.models import Profile, User\nfrom app.plugins.feed_helper import get_message_data\nfrom app.plugins.auth_helper import admin_token_validation\nfrom app.plugins.general_helper import check_for_keys\nfrom app.plugins.profile_helper import create_new_profile\nfrom app.plugins.user_helper import create_new_user\nfrom app.plugins.feed_helper import filter_feed, get_filters\nfrom app.plugins.mail_helper import send_welcome\n\n\n@app.route('/admin/users', methods=['GET', 'POST'])\n@admin_token_validation\ndef create_user():\n if request.method == 'POST':\n data = request.get_json(force=True) or {}\n logger.debug('receiving request to add user: {}'.format(data))\n welcome = request.args.get('welcome', 0, type=int)\n if welcome:\n temp_pass = ''.join(\n random.choice(string.ascii_uppercase + string.digits\n + string.ascii_lowercase)\n for _ in range(12))\n data['password'] = temp_pass\n all_keys_present, results = check_for_keys(\n ['email', 'first_name', 'last_name', 'password'],\n data\n )\n if all_keys_present:\n logger.debug('adding user {}'.format(data['email']))\n response, success = create_new_user(data)\n if success:\n logger.debug('added user {}'.format(data['email']))\n user = User.query.filter_by(email=data['email']).first()\n if welcome:\n send_welcome(user, temp_pass)\n response.status_code = 201\n else:\n logger.debug('failed to add {}'.format(data['email']))\n response.status_code = 400\n return response\n else:\n logger.debug('missing {}'.format(', '.join(results)))\n return jsonify({'message': 'missing {}'.format(\n ', '.join(results))}), 400\n else:\n return query_users(request)\n\n\ndef query_users(request):\n user_id = request.args.get('id')\n user_email = request.args.get('email')\n\n if user_id or user_email:\n search = True\n else:\n search = False\n\n if search:\n if user_id:\n user = User.query.filter_by(id=user_id).first()\n elif user_email:\n user = User.query.filter_by(email=user_email).first()\n if user:\n return jsonify(user.to_dict())\n else:\n return jsonify({'msg': 'user not found'}), 404\n else:\n page = request.args.get('page', 1, type=int)\n per_page = app.config['ELEMENTS_PER_PAGE']\n data = User.to_collection_dict(\n User.query,\n page,\n per_page,\n 'create_user',\n 'User'\n )\n return jsonify(data)\n\n\n@app.route('/admin/profiles', methods=['POST', 'GET'])\n@admin_token_validation\ndef create_profile():\n if request.method == 'POST':\n data = request.get_json(force=True) or {}\n all_keys_present, results = check_for_keys(['email'], data)\n if all_keys_present:\n user = User.query.filter_by(email=data['email']).first()\n if user:\n data['user'] = user.id\n profile = create_new_profile(data)\n response = jsonify(profile)\n response.status_code = 201\n return response\n return jsonify({'message': 'user not found for email: {}'.format(\n data['email'])}), 400\n else:\n return jsonify({'message': 'missing {}'.format(\n ', '.join(results))}), 400\n else:\n return query_profiles(request)\n\n\ndef query_profiles(request):\n token = request.args.get('token')\n if token:\n profile = Profile.query.filter_by(token_id=token).first()\n if profile:\n return jsonify(profile.to_dict())\n else:\n return jsonify({'msg': 'profile not found'}), 404\n else:\n page = request.args.get('page', 1, type=int)\n per_page = app.config['ELEMENTS_PER_PAGE']\n data = User.to_collection_dict(\n Profile.query,\n page,\n per_page,\n 'create_profile',\n 'Profile'\n )\n return jsonify(data)\n\n\n@app.route('/admin/profiles/', methods=['PUT', 'DELETE'])\n@admin_token_validation\ndef mod_profile(token_id):\n data = request.get_json(force=True) or {}\n profile = Profile.query.filter_by(token_id=token_id).first()\n if not profile:\n return jsonify({'message': 'profile not found'}), 404\n if request.method == 'PUT':\n return edit_profile_data(token_id, data, profile)\n elif request.method == 'DELETE':\n return delete_profile(token_id, data, profile)\n\n\ndef edit_profile_data(token_id, data, profile):\n all_keys_present, results = check_for_keys(['data'], data)\n if all_keys_present:\n if not isinstance(data['data'], dict):\n return jsonify({'message': 'data must be an object'}), 400\n else:\n logger.debug('updating data')\n profile.from_dict({'data': json.dumps(data['data'])})\n db.session.commit()\n return jsonify(profile.to_dict())\n else:\n return jsonify({'message': 'missing {}'.format(\n ', '.join(results))}), 400\n\n\ndef delete_profile(token_id, data, profile):\n logger.debug('deleting profile: {}'.format(profile.token_id))\n profile.deleted = True\n db.session.commit()\n response = jsonify({'message': 'profile deleted'})\n response.status_code = 202\n return response\n\n\n@app.route('/admin/messages', methods=['POST'])\n@admin_token_validation\ndef get_messages():\n filters = get_filters(request)\n user_profiles = [p.to_dict()\n for p in Profile.query.filter_by(deleted=False).all()]\n user_data = {\n 'data': {\n 'message_types': {\n 'northbound': rule.get_messages_list('northbound'),\n 'southbound': rule.get_messages_list('southbound')\n }\n }\n }\n messages, filters = filter_feed(filters, user_profiles, user_data)\n return jsonify({'messages': messages, 'filters': filters,\n 'message_types': user_data['data']['message_types'],\n 'user_profiles': user_profiles})\n\n\n@app.route('/admin/messages//', methods=['GET'])\n@admin_token_validation\ndef message_task(message_id, task):\n return get_message_data(message_id, task)\n","sub_path":"app/api/admin_routes.py","file_name":"admin_routes.py","file_ext":"py","file_size_in_byte":6582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"335284931","text":"# -*- coding: utf8 -*-\nimport os\nimport time\nimport yaml\nimport logging\nimport logging.config\nimport ujson\nfrom flask import (\n Flask,\n g,\n jsonify\n)\nfrom celery import Celery\nfrom swallow.tools.trace import MonitorMiddleware\n\ncurrent_dir = os.path.dirname(__file__)\nlogging_path = os.path.join(current_dir, 'logging.yaml')\nwith open(logging_path, 'r') as f:\n logging.config.dictConfig(yaml.load(f))\n\nprob_path = os.path.join(current_dir, 'prob.txt')\nwith open(prob_path, 'r') as f:\n prob = ujson.load(f)\n\ncelery_logger = logging.getLogger('swallow.celery')\n\ncelery_app = Celery(\"swallow\")\ncelery_app.config_from_object(\"swallow.celeryconfig\")\n\nflask_app = Flask(\"swallow\")\nmiddleware = MonitorMiddleware(flask_app, '/swallow/metrics')\n\n\n@flask_app.before_request\ndef before_request():\n g.start_time = time.time()\n\n\n@flask_app.errorhandler(Exception)\ndef handle_exception(e):\n middleware.log_exception(e)\n return jsonify({'ret': -1, 'msg': 'unknown error'}), 500\n\n\n@flask_app.after_request\ndef after_request(resp):\n middleware.log_response(resp)\n return resp\n","sub_path":"swallow/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"409384193","text":"from room import Room\nfrom player import Player\nfrom world import World\n\nimport random\nfrom util import Queue\nfrom util import Stack\nfrom ast import literal_eval\n\n# Load world\nworld = World()\n\n\n# You may uncomment the smaller graphs for development and testing purposes.\n# map_file = \"maps/test_line.txt\"\n# map_file = \"maps/test_cross.txt\"\n# map_file = \"maps/test_loop.txt\"\n# map_file = \"maps/test_loop_fork.txt\"\nmap_file = \"maps/main_maze.txt\"\n\n# Loads the map into a dictionary\nroom_graph = literal_eval(open(map_file, \"r\").read())\nworld.load_graph(room_graph)\n\n# Print an ASCII map\nworld.print_rooms()\n\nplayer = Player(world.starting_room)\n\n# Fill this out with directions to walk\n# traversal_path = ['n', 'n']\n\n#! Usefull Commands\n# player.current_room.id\n# player.current_room.get_exits()\n# player.travel(direction)\n\ntraversal_path = []\nrooms = {}\nreversed = []\nopposite = {'n': 's', 's': 'n', 'e': 'w', 'w': 'e'}\n\n#init first room\n# While rooms are undescovered\n # if in undescovered room\n # Add room to rooms with it's exits, array\n # get prev move\n # remove prev move (opposite) from current room\n # if all exits are descovered\n # get last move\n # move to last room\n # continue till room with undescovered room\n# init room\nrooms[player.current_room.id] = player.current_room.get_exits()\n\nwhile len(rooms) < len(room_graph) - 1:\n exits = player.current_room.get_exits()\n current = player.current_room.id\n\n if current not in rooms:\n\n rooms[player.current_room.id] = exits\n last = reversed[-1]\n rooms[current].remove(last)\n\n while len(rooms[current]) == 0:\n direction = reversed.pop()\n traversal_path.append(direction)\n player.travel(direction)\n\n current = player.current_room.id\n\n direction = rooms[current].pop()\n traversal_path.append(direction)\n\n reversed.append(opposite[direction])\n player.travel(direction)\n\n# TRAVERSAL TEST - DO NOT MODIFY\nvisited_rooms = set()\nplayer.current_room = world.starting_room\nvisited_rooms.add(player.current_room)\n\nfor move in traversal_path:\n player.travel(move)\n visited_rooms.add(player.current_room)\n\nif len(visited_rooms) == len(room_graph):\n print(\n f\"TESTS PASSED: {len(traversal_path)} moves, {len(visited_rooms)} rooms visited\")\nelse:\n print(\"TESTS FAILED: INCOMPLETE TRAVERSAL\")\n print(f\"{len(room_graph) - len(visited_rooms)} unvisited rooms\")\n\n\n#######\n# UNCOMMENT TO WALK AROUND\n#######\nplayer.current_room.print_room_description(player)\nwhile True:\n cmds = input(\"-> \").lower().split(\" \")\n if cmds[0] in [\"n\", \"s\", \"e\", \"w\"]:\n player.travel(cmds[0], True)\n elif cmds[0] == \"q\":\n break\n else:\n print(\"I did not understand that command.\")\n","sub_path":"adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":2770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"203905876","text":"import fiona\nimport geopandas as gpd\nimport pandas as pd\nimport os\nimport pprint\nimport process\nimport matplotlib.pyplot as plt\nimport new_tractToZip\nimport sys\nfrom sklearn import preprocessing\n\nfrom functools import partial\n\nfrom collections import defaultdict\nimport utils\nimport pandas\n\n\ndef convertColumnsToFullName(acs_meta, layerDF):\n fullNameMap = utils.get_col_map_to_names(acs_meta, layerDF)\n shortColNames = layerDF.columns[1:-1] # exclude GEOID and Geometry\n columnFullNames = ([\"GEOID\"] + [fullNameMap[shortCol] for shortCol in shortColNames] + [\"geometry\"])\n layerDF.columns = columnFullNames\n return layerDF\n\n\ndef removeUnselectedCols(layerDF, selectedColumns):\n removedColumns = []\n preservedColumns = ([\"GEOID\"])\n preservedColumns += selectedColumns\n removedColumns = [col for col in layerDF.columns if col not in preservedColumns]\n return removedColumns\n\n\ndef dropUnwantedColumns(layerDF, selectedColumns):\n removed_cols = []\n removed_cols += utils.get_margin_of_error_list(layerDF.columns)\n removed_cols += removeUnselectedCols(layerDF, selectedColumns)\n layerDF = layerDF.drop(columns=removed_cols)\n return layerDF\n\n\ndef getPopulationByCensusTract(acs_meta, acs_counts):\n acs_counts_full_cols = utils.get_full_name_list_from_cols(acs_meta, acs_counts.columns)\n acs_counts.columns = ([\"GEOID\"] + acs_counts_full_cols + [\"geometry\"])\n countsColToKeep = [\"UNWEIGHTED SAMPLE COUNT OF THE POPULATION: Total: Total population -- (Estimate)\"]\n removed_cols = ([col for col in acs_counts_full_cols if col not in countsColToKeep] + [\"geometry\"])\n acs_counts_trunc = acs_counts.drop(columns=removed_cols)\n acs_counts_trunc.columns = [\"GEOID\", \"Total population in census tract\"]\n return acs_counts_trunc\n\n\ndef addCensusTractPopulationColumn(acs_meta, acs_counts, layerDF):\n populationByTractDF = getPopulationByCensusTract(acs_meta, acs_counts)\n layerDF = layerDF.merge(populationByTractDF, on=\"GEOID\", how='inner')\n return layerDF\n\n\ndef addZipCodeColumn(layerDF, zip_df):\n layerDF[\"GEOID\"] = [tractNum[-11:] for tractNum in layerDF[\"GEOID\"]]\n layerDF = layerDF.merge(zip_df, on=\"GEOID\", how=\"inner\")\n return layerDF\n\n\ndef collapseRowsOnZipCodeColumn(layerDF):\n layerDF = layerDF.set_index('GEOID')\n layerDF = layerDF.groupby([\"ZIPCODE\"], axis=0).sum()\n return layerDF\n\n\ndef collapse_on_column(df, col):\n df.set_index('GEOID', inplace=True)\n return df.groupby([col], axis=0).first()\n\n\ndef convertValuesToPercentages(acs_meta, acs_counts, layerDF):\n # acs_counts_trunc = getPopulationByCensusTract(acs_meta, acs_counts)\n # layerDF = layerDF.merge(acs_counts_trunc, on=\"GEOID\", how=\"inner\")\n totalPopColumn = layerDF.pop(\"RACE: Total: Total population -- (Estimate)\")\n layerDF = layerDF.divide(totalPopColumn, axis='index')\n return layerDF\n\n\ndef findTop10Zips(columnNum, layerDF):\n columnToSort = [layerDF.columns[columnNum]]\n layerDF = layerDF.sort_values(by=columnToSort, axis=\"index\", ascending=False)\n # layerDF.columns = [\"White\", \"Black\", \"Native American\", \"Asian\", \"Native Hawaiian\", \"Other\"]\n # print(layerDF.head())\n top10Zips = layerDF.index.values[:10]\n percentages = layerDF[columnToSort].values[:10]\n percentagesFlattened = [percent[0] for percent in percentages]\n top10Zips = list(zip(top10Zips, percentagesFlattened))\n return top10Zips\n\n\ndef processResponse(response, cleanPromptOptions, layer, layerDF):\n retryBool = True\n for index, value in enumerate(cleanPromptOptions):\n if response == value:\n retryBool = False\n top10Zips = findTop10Zips(index, layerDF)\n printString = (\"The top 10 zips for \\\"\" + layer + \"\\\"=\\\"\" + response + \"\\\" are:\\n\")\n for zipCode in top10Zips:\n printString += (\"\\t\" + str(zipCode[0]) + \" (percent = \" + str(zipCode[1]) + \")\\n\")\n print(printString)\n elif response == \"quit\":\n retryBool = False\n\n return retryBool\n\n\ndef sortZipCodesByDesiredColumn(layer, cleanLayerOptions, layerDF):\n promptOptions = generatePromptOptions(layer, cleanLayerOptions)\n cleanPromptOptions = [option.lower().strip() for option in promptOptions]\n prompt = (\"Please select the column for which you'd like to return the top 10 zip codes:\\n\")\n for option in promptOptions:\n prompt += (\"\\t\" + option + \"\\n\")\n response = \"\"\n while (response != \"quit\"):\n response = input(prompt).lower().strip()\n retryBool = processResponse(response, cleanPromptOptions, layer, layerDF)\n if (retryBool): print(\"Input error. Please try again.\\n\")\n\n return layerDF\n\n\ndef parse_enviro_justice_cols(enviro_justice_layers, enviro_justice_cols):\n for layer in enviro_justice_layers:\n print(\"Layer: \" + str(layer))\n if (layer in enviro_justice_cols and len(enviro_justice_cols[layer]) > 1):\n for column in enviro_justice_cols[layer]:\n print(column)\n elif (layer in enviro_justice_cols):\n print(enviro_justice_cols[layer])\n\n print(len(enviro_justice_cols[\"Food Stamps\"]))\n return\n\n\ndef write_txtFile_with_column_options(layer, layer_df):\n f = open(\"namesOfColumnsForSelectedRows.txt\", \"a\")\n f.write(\"\\n\\nLAYER: \" + str(layer))\n for column in layer_df.columns:\n f.write(\"\\n\" + column)\n\n\nNON_SUMMABLE = {'geometry', 'ZIPCODE', 'GEOID', None}\n\n\ndef cols_to_percentiles(df, inplace=True):\n for col in df.columns:\n if col not in NON_SUMMABLE:\n len = df[col].size - 1\n if inplace:\n df[col] = df[col].rank(method='max').apply(lambda x: 100.0 * (x - 1) / len)\n else:\n df[f'{col}_POP_DENS_PERCENTILE'] = df[col].rank(method='max').apply(lambda x: 100.0 * (x - 1) / len)\n\n\ndef load_zip():\n zipCodeDF = pd.read_csv('tract_to_zip_out.csv', dtype=str)\n zipCodeDF.columns = [\"GEOID\", \"ZIPCODE\"]\n return zipCodeDF\n\n\ndef build_ad_targets_from_columns(selectedLayers, selectedColumnsMap, column_weights, acs_meta, acs_counts):\n zip_df = load_zip()\n\n # startingDF; to be built over time by merging relevant columns into it\n scores_df = gpd.GeoDataFrame(addZipCodeColumn(acs_counts, zip_df)[\"GEOID\"])\n scores_df = addZipCodeColumn(scores_df, zip_df)\n scores_df = collapseRowsOnZipCodeColumn(scores_df)\n\n print('created base')\n for index, layer_df in enumerate(process.process_acs(acs_layers=selectedLayers)):\n layer = selectedLayers[index]\n print('creating ', layer)\n selectedColumns = selectedColumnsMap[layer]\n # layer_df = convertColumnsToFullName(acs_meta, layer_df)\n # write_txtFile_with_column_options(layer, layer_df) #helpful for building selectedColumnsMap (i.e. choosing\n # which columns to prioritize)\n layer_df = dropUnwantedColumns(layer_df, selectedColumns)\n layer_df = addZipCodeColumn(layer_df, zip_df)\n layer_df = collapseRowsOnZipCodeColumn(layer_df)\n # layer_df = addCensusTractPopulationColumn(acs_meta, acs_counts, layer_df) # The population numbers in the counts layer don't seem to make sense (too low)\n # can use \"total\" column for the given layer to get percentages\n # layer_df = convertValuesToPercentages(acs_meta, acs_counts, layer_df)\n print('merge', layer)\n scores_df = scores_df.merge(layer_df, on='ZIPCODE', how='outer')\n\n return scores_df\n\n\ndef adjust_for_pop_density(df, cols):\n for layer, col in cols.items():\n if len(col) > 2:\n for col_n in col[2:]:\n df[f'{col_n}'] = df[col_n] / df[col[1]]\n df.drop(col[1], inplace=True, axis=1)\n else:\n print(col)\n\n\n# row is a series, which can be thought of as a list of tuples of (column, val)\ndef generate_ad_score_for_row(weights, row):\n total = 0\n for index, col in enumerate(row.iteritems()):\n if 'POP_DENS_PERCENTILE' in col[0]:\n total = total + col[1]\n return total\n\n\ndef score_and_scale(scores, cols, weights):\n scores['ad_score'] = scores.apply(partial(generate_ad_score_for_row, weights), axis=1)\n ad_scores = scores['ad_score'].values.reshape(-1, 1)\n min_max_scaler = preprocessing.MinMaxScaler()\n ad_score_scaled = min_max_scaler.fit_transform(ad_scores)\n scores['ad_score_scaled'] = ad_score_scaled\n return scores\n\n\ndef build_ad_targets(export=False, cache=False):\n acs_meta, acs_counts = process.process_meta()\n enviro_justice_layers = [\n \"X02_RACE\",\n 'X16_LANGUAGE_SPOKEN_AT_HOME',\n \"X17_POVERTY\",\n \"X22_FOOD_STAMPS\",\n 'X24_INDUSTRY_OCCUPATION',\n # \"X27_HEALTH_INSURANCE\",\n 'X99_IMPUTATION',\n ]\n\n # The columns in this map are placeholders until we get more clarity on the exact columns we want to include\n # we're mapping from layer names to tuples of columnn names, so if we're only going to use one column from a layer,\n # still make it a tuple with None as the second item -- e.g. (\"selectedColumn\", None)\n enviro_justice_cols = {\n \"X02_RACE\": (\"GEOID\", 'B02001e1', 'B02001e2'),\n 'X16_LANGUAGE_SPOKEN_AT_HOME': ('GEOID', 'C16001e1', 'C16001e3', 'C16001e5'),\n \"X17_POVERTY\": (\"GEOID\", 'B17001e1', 'B17001e2'),\n \"X22_FOOD_STAMPS\": (\"GEOID\", \"B22003e1\", \"B22003e2\"),\n 'X24_INDUSTRY_OCCUPATION': (\"GEOID\", 'B24011e1', 'B24011e19'),\n # \"X27_HEALTH_INSURANCE\": (\"GEOID\", 'B27010e1'),\n 'X99_IMPUTATION': ('GEOID', 'B992521e1', 'B992521e2'),\n\n }\n\n enviro_justice_weights = [1 for _ in range(0,30)]\n if cache is False:\n scores = build_ad_targets_from_columns(enviro_justice_layers, enviro_justice_cols, enviro_justice_weights,\n acs_meta, acs_counts)\n if export:\n scores.to_csv('raw_vals.csv')\n else:\n scores = gpd.read_file('raw_vals.csv')\n for col in scores.columns:\n if col not in NON_SUMMABLE:\n scores[col] = scores[col].apply(lambda x: float(x))\n scores['B02001e2'] = scores['B02001e1'] - scores['B02001e2']\n adjust_for_pop_density(scores, enviro_justice_cols)\n # scores = convertColumnsToFullName(acs_meta, scores)\n cols_to_percentiles(scores, inplace=False)\n scores = score_and_scale(scores, enviro_justice_cols, enviro_justice_weights)\n col_rename(scores, acs_meta, enviro_justice_cols)\n\n if export:\n scores.to_csv('ad_scores.csv')\n\n return scores\n\n\ndef col_rename(scores,meta, cols):\n cols = [vv for c,v in cols.items() for vv in v if vv != 'GEOID']\n name_map = utils.get_full_name_map_from_cols(meta, cols)\n name_map['RACE: Non-White alone: Total population -- (Estimate)'] = name_map.pop('RACE: White alone: Total population -- (Estimate)')\n s_cols = list(scores.columns)\n for i, s_col in enumerate(scores.columns):\n for n,c in name_map.items():\n if c in s_col:\n s_cols[i] = s_col.replace(c, n) + '_DENSITY'\n scores.columns = s_cols\n\n\n\ndef map_ad_targets(scores):\n # first merge,\n zip = load_zip()\n scores_zip = zip.merge(scores, on='ZIPCODE', how='outer')\n scores_zip = scores_zip.groupby(['GEOID'], axis=0).first()\n geo = process.get_acs_geo()\n geo['GEOID'] = geo['GEOID'].apply(lambda x: x[5:])\n scores_zip_geo = scores_zip.merge(geo, on='GEOID', how='outer')\n scores_zip = collapse_on_column(scores_zip, 'GEOID')\n scores_and_geo_and_zip_new = scores_zip_geo.columns.values\n scores_and_geo_and_zip_new[scores_and_geo_and_zip_new == 'geometry_y'] = 'geometry'\n scores_zip_geo.columns = scores_and_geo_and_zip_new\n print('second')\n scores_and_geo_and_zip = gpd.GeoDataFrame(scores_zip_geo) # just in case sometimes it likes it being recast ???\n scores_and_geo_and_zip['ad_score_scaled'] = scores_zip_geo['ad_score_scaled'].apply(lambda x: float(x))\n\n # then map!\n color_min = 0\n color_max = scores_and_geo_and_zip['ad_score_scaled'].max()\n\n fig, ax = plt.subplots(1, figsize=(30, 10))\n ax.axis('off')\n ax.set_title('AD SCORE, SCALED', fontdict={'fontsize': '25', 'fontweight': '3'})\n ax.annotate('Source: ACS DATA', xy=(0.6, .05),\n xycoords='figure fraction', fontsize=12, color='#555555')\n sm = plt.cm.ScalarMappable(cmap='Blues', norm=plt.Normalize(vmin=color_min, vmax=color_max))\n sm.set_array([])\n fig.colorbar(sm)\n scores_and_geo_and_zip.plot(column='ad_score_scaled', cmap='Blues', linewidth=0.8, ax=ax, edgecolor='0.8')\n print()\n plt.close(fig)\n\n\ndef load_cached_ad_targets(path):\n return gpd.read_file(path, driver='FileGDB')\n\n\n\n\n\nif __name__ == '__main__':\n scores = build_ad_targets(export=True, cache=False)\n # scores = load_cached_ad_targets('ad_scores.csv') # just gets cached version to run faster\n # map_ad_targets(scores)\n","sub_path":"py/ad_targeting.py","file_name":"ad_targeting.py","file_ext":"py","file_size_in_byte":12847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"288104796","text":"from GameProject.Variables import *\nfrom GameProject.PlayerClass import *\nfrom pygame.locals import *\nimport pygame.mixer, time\n\nmove = pygame.mixer.Sound(os.path.join(\"data\", \"Sounds\", \"Sheriff.wav\"))\nchaching = pygame.mixer.Sound(os.path.join(\"data\", \"Sounds\", \"chaching.wav\"))\nClick = pygame.mixer.Sound(os.path.join(\"data\", \"Sounds\", \"Click.wav\"))\nCowboyAttack = pygame.mixer.Sound(os.path.join(\"data\", \"Sounds\", \"CowboyAttack.wav\"))\nMarshallAttack = pygame.mixer.Sound(os.path.join(\"data\", \"Sounds\", \"MarshallAttack.wav\"))\nSheriffAttack = pygame.mixer.Sound(os.path.join(\"data\", \"Sounds\", \"SheriffAttack.wav\"))\n\n\n\n\n\n#background music\nmusic_playing = True\npygame.mixer.music.load(os.path.join(\"data\", \"Sounds\", \"Background.mp3\"))\npygame.mixer.music.set_volume(0.3)\npygame.mixer.music.play(-1)\n\n\n\n\npygame.mixer.init()\nsys.path.insert(0, os.path.abspath('..'))\n\n# Create a 2 dimensional array. A two dimensional\n# array is simply a list of lists.\n# Grid down her\n\n\ndef Grid():\n # Draw the grid\n for row in range(18):\n for column in range(18):\n texture = Water\n if grid[row][column] == 0:\n texture = Water\n if grid[row][column] == 1:\n texture = Forest\n if grid[row][column] == 2:\n texture = Swamp\n if grid[row][column] == 3:\n texture = Desert\n if grid[row][column] == 4:\n texture = Ice\n if grid[row][column] == 5:\n texture = Stone\n screen.blit(pygame.transform.scale(texture, (WIDTH, HEIGHT)),(column*offset, row*offset))\n\n\nclass Player:\n NumberT = 0\n def __init__(self, name, number, balance):\n self.Name = name\n self.Number = Player.NumberT\n self.Balance = balance\n\n def __str__(self):\n return \" {} {}\".format(self.Name, self.Balance)\n\n def deposit(self, amount):\n self.Balance += amount\n return self.Balance\n\n def withdraw(self, amount):\n self.Balance -= amount\n return self.Balance\n\nTurnCnt = 4\n\ndef addMoney():\n if Player.NumberT == 0:\n for troop in Trooplist:\n if troop.team == 1:\n if grid[troop.x][troop.y] == 1:\n player1.deposit(50)\n elif grid[troop.x][troop.y] == 0:\n player1.deposit(0)\n elif grid[troop.x][troop.y] == 5:\n player1.deposit(150)\n elif grid[troop.x][troop.y] == 2 or 3 or 4:\n player1.deposit(100)\n\n if Player.NumberT == 1:\n for troop in Trooplist:\n if troop.team == 2:\n if grid[troop.x][troop.y] == 1:\n player2.deposit(100)\n elif grid[troop.x][troop.y] == 0:\n player2.deposit(0)\n elif grid[troop.x][troop.y] == 3:\n player2.deposit(50)\n elif grid[troop.x][troop.y] == 4:\n player2.deposit(100)\n elif grid[troop.x][troop.y] == 5:\n player2.deposit(150)\n elif grid[troop.x][troop.y] == 2:\n player2.deposit(50)\n\n\n if Player.NumberT == 2:\n for troop in Trooplist:\n if troop.team == 3:\n if grid[troop.x][troop.y] == 1:\n player3.deposit(100)\n elif grid[troop.x][troop.y] == 0:\n player3.deposit(0)\n elif grid[troop.x][troop.y] == 3:\n player3.deposit(100)\n elif grid[troop.x][troop.y] == 4:\n player3.deposit(100)\n elif grid[troop.x][troop.y] == 5:\n player3.deposit(150)\n elif grid[troop.x][troop.y] == 2:\n player3.deposit(50)\n\n if Player.NumberT == 3:\n for troop in Trooplist:\n if troop.team == 4:\n if grid[troop.x][troop.y] == 4:\n player4.deposit(50)\n elif grid[troop.x][troop.y] == 0:\n player4.deposit(0)\n elif grid[troop.x][troop.y] == 5:\n player4.deposit(150)\n elif grid[troop.x][troop.y] == 1 or 2 or 3:\n player4.deposit(100)\n\n\n\n\ndef NextPlayer():\n global TurnCnt\n if TurnCnt != 1:\n TurnCnt -= 1\n else:\n TurnCnt = 4\n if Player.NumberT < 3:\n Player.NumberT += 1\n else:\n Player.NumberT = 0\n\n\n\n\n\n if TurnCnt == 4 and Player.NumberT == 0:\n addMoney()\n if TurnCnt == 4 and Player.NumberT == 1:\n addMoney()\n if TurnCnt == 4 and Player.NumberT == 2:\n addMoney()\n if TurnCnt == 4 and Player.NumberT == 3:\n addMoney()\n\n\n\n\n# draw players and theirs balance\ndef DrawTurns():\n if Player.NumberT == 0:\n drawText((760,40), \"Player 1 - f\"+str(player1.Balance), 30, (0,255,0))\n else:\n drawText((760,40), \"Player 1 - f\"+str(player1.Balance), 30, (255,255,255))\n\n if Player.NumberT == 1:\n drawText((760,95), \"Player 2 - f\"+str(player2.Balance), 30, (255,0,0))\n else:\n drawText((760,95), \"Player 2 - f\"+str(player2.Balance), 30, (255,255,255))\n\n if Player.NumberT == 2:\n drawText((760,150), \"Player 3 - f\"+str(player3.Balance), 30, (255,255,0))\n else:\n drawText((760,150), \"Player 3 - f\"+str(player3.Balance), 30, (255,255,255))\n\n if Player.NumberT == 3:\n drawText((760,205), \"Player 4 - f\"+str(player4.Balance), 30, (0,0,255))\n else:\n drawText((760,205), \"Player 4 - f\"+str(player4.Balance), 30, (255,255,255))\n\n for i in Trooplist:\n if i.Type == \"Barrack\":\n if i.team == 1:\n drawText([1000, 440], \"Player 1: \"+str(i.HP), 30, GREEN)\n if i.team == 2:\n drawText([1000, 490], \"Player 1: \"+str(i.HP), 30, RED)\n if i.team == 3:\n drawText([1000, 540], \"Player 1: \"+str(i.HP), 30, (255, 255, 0))\n if i.team == 4:\n drawText([1000, 590], \"Player 1: \"+str(i.HP), 30, (0, 0, 255))\n\n # drawText([1000, 440], \"PLayer 1: \"+str(Troop.HP), 30, GREEN)\n\n\n if TurnCnt == 1:\n drawText((1050,80), str(TurnCnt), 200, (255,160,160))\n drawText((1000,35), \"Turns Left: \", 50, (255,160,160))\n else:\n drawText((1050,80), str(TurnCnt), 200, (255,255,255))\n drawText((1000,35), \"Turns Left: \", 50, (255,255,255))\n\n\nclass Troop:\n def __init__(self, team, pos, type):\n self.team = team\n self.x = pos[0]\n self.y = pos[1]\n self.Type = type\n self.Text = \"\"\n self.Attack = ''\n self.Defence = ''\n self.HP = ''\n\n if type == 'Soldier':\n self.Attack = 1\n self.Defence = 1\n\n if type == 'Robot':\n self.Attack = 2\n self.Defence = 2\n\n if type == 'Tank':\n self.Attack = 3\n self.Defence = 3\n if type == 'Barrack':\n self.HP = 25\n\n if team == 1:\n if type == 'Soldier':\n self.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"Sheriff1.png\"))\n if type == 'Tank':\n self.Text = self.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"Cowboy1.png\"))\n if type == 'Robot':\n self.Text = self.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"Marshall1.png\"))\n if type == 'Barrack':\n self.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"barrack1.png\"))\n if team == 2:\n if type == 'Soldier':\n self.Text = pygame.image.load(os.path.join('Afbeeldingen', 'Sheriff2.png'))\n if type == 'Tank':\n self.Text = self.Text = pygame.image.load(os.path.join('Afbeeldingen', 'Cowboy2.png'))\n if type == 'Robot':\n self.Text = self.Text = pygame.image.load(os.path.join('Afbeeldingen', 'Marshall2.png'))\n if type == 'Barrack':\n self.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"barrack2.png\"))\n if team == 3:\n if type == 'Soldier':\n self.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"Sheriff3.png\"))\n if type == 'Tank':\n self.Text = self.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"Cowboy3.png\"))\n if type == 'Robot':\n self.Text = self.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"Marshall3.png\"))\n if type == 'Barrack':\n self.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"barrack3.png\"))\n if team == 4:\n if type == 'Soldier':\n self.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"Sheriff4.png\"))\n if type == 'Tank':\n self.Text = self.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"Cowboy4.png\"))\n if type == 'Robot':\n self.Text = self.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"Marshall4.png\"))\n if type == 'Barrack':\n self.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"barrack4.png\"))\n\n def Move():\n pos = pygame.mouse.get_pos()\n column = pos[0] // (WIDTH + MARGIN)\n row = pos[1] // (HEIGHT + MARGIN)\n for troop in Trooplist:\n # RightTroop = ( (pos[0] / 40) > (troop.x + 1) and (pos[0] / 40) < (troop.x + 2) and (pos[1] / 40) > (troop.y) and (pos[1] / 40) < (troop.y + 1) )\n # LeftTroop = ( (pos[0] / 40) > (troop.x - 1) and (pos[0] / 40) < (troop.x) ) and (pos[1] / 40) > (troop.y) and (pos[1] / 40) < (troop.y + 1)\n # UnderTroop = ( (pos[0] / 40) > (troop.x) and (pos[0] / 40) < (troop.x + 1) ) and ( (pos[1] / 40) > (troop.y + 1) and (pos[1] / 40) < (troop.y + 2) )\n # AboveTroop = ( (pos[0] / 40) > (troop.x) and (pos[0] / 40) < (troop.x + 1) ) and ( (pos[1] / 40) > (troop.y - 1) and (pos[1] / 40) < (troop.y) )\n # ClickTroop = ( (pos[0] / 40) > (troop.x) and (pos[0] / 40) < (troop.x + 1) ) and ( (pos[1] / 40) > (troop.y) and (pos[1] / 40) < (troop.y + 1) )\n #\n ClickTroopRight = ( (pos[0] / 40) > (troop.x + 0.75) and (pos[0] / 40) < (troop.x + 1.0) and (pos[1] / 40) > (troop.y + 0.25) and (pos[1] / 40) < (troop.y + 0.75) )\n ClickTroopLeft = ( (pos[0] / 40) > (troop.x + 0) and (pos[0] / 40) < (troop.x + 0.25) and (pos[1] / 40) > (troop.y + 0.10) and (pos[1] / 40) < (troop.y + 0.90) )\n ClickTroopAbove = ( (pos[0] / 40) > (troop.x + 0.25) and (pos[0] / 40) < (troop.x + 0.75) ) and ( (pos[1] / 40) > (troop.y) and (pos[1] / 40) < (troop.y + 0.25) )\n ClickTroopUnder = ( (pos[0] / 40) > (troop.x + 0.25) and (pos[0] / 40) < (troop.x + 0.75 ) ) and ( (pos[1] / 40) > (troop.y + 0.75) and (pos[1] / 40) < (troop.y + 1) )\n if row < 18 and column < 18:\n Troop.getEnemyFromCoordinates(troop.x,troop.y)\n if Troop.checkOfJeErHeenKan() == True:\n Troop.checkOfJeOpHetWaterBent()\n Troop.checkWaarJeHeenWil()\n\n # if Troop.checkOfJeErHeenKan() == True:\n\n screen.blit(pygame.transform.scale(troop.Text, (WIDTH, HEIGHT)),(troop.x*offset, troop.y*offset))\n\n\n @staticmethod\n def getEnemyFromCoordinates(row, column):\n for enemy in Trooplist:\n if Player.NumberT != enemy.team-1:\n if row == enemy.y and column == enemy.x:\n return enemy\n return None\n\n @staticmethod\n def getTroopFormMouseCoordinates():\n pos = pygame.mouse.get_pos()\n column = pos[0]/40 // (WIDTH + MARGIN)\n row = pos[1]/40 // (HEIGHT + MARGIN)\n if event.type == pygame.MOUSEBUTTONDOWN:\n return Troop.getEnemyFromCoordinates(row, column)\n\n @staticmethod\n def checkOfHuidigTeamErNaastStaat(row, column):\n directions = [(0,1),(1,0),(0,-1),(-1,0)]\n for i in directions:\n position = (row+i[0], column+i[1])\n for troop in Trooplist:\n if troop.x == position[0] and troop.y == position[1]:\n return True\n\n if troop.Type == 'Soldier':\n if troop.x == position[0] and troop.y == position[1]:\n if huidigTeam == troop.team-1:\n print(\"kaas\")\n return True\n return False\n\n @staticmethod\n def checkOfHuidigSoldierErNaastStaat(row, column):\n huidigTeam = Player.NumberT\n directions = [(0,1),(1,0),(0,-1),(-1,0)]\n for i in directions:\n position = (row+i[0], column+i[1])\n for troop in Trooplist:\n if troop.Type == 'Soldier':\n if troop.x == position[0] and troop.y == position[1]:\n if huidigTeam == troop.team-1:\n\n return True\n return False\n @staticmethod\n def checkOfHuidigRobotErNaastStaat(row, column):\n huidigTeam = Player.NumberT\n directions = [(0,1),(1,0),(0,-1),(-1,0)]\n for i in directions:\n position = (row+i[0], column+i[1])\n for troop in Trooplist:\n if troop.Type == 'Robot':\n if troop.x == position[0] and troop.y == position[1]:\n if huidigTeam == troop.team-1:\n\n return True\n return False\n @staticmethod\n def checkOfHuidigTankErNaastStaat(row, column):\n huidigTeam = Player.NumberT\n directions = [(0,1),(1,0),(0,-1),(-1,0)]\n for i in directions:\n position = (row+i[0], column+i[1])\n for troop in Trooplist:\n if troop.Type == 'Tank':\n if troop.x == position[0] and troop.y == position[1]:\n if huidigTeam == troop.team-1:\n\n return True\n return False\n @staticmethod\n def checkOfJeOpHetWaterBent():\n for troop in Trooplist:\n #IF PLAYER IS ON WATER\n if grid[troop.y][troop.x] == 0:\n if troop.team == 1:\n if troop.Type == 'Soldier':\n troop.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"SheriffR1.png\"))\n if troop.Type == 'Tank':\n troop.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"CowboyR1.png\"))\n if troop.Type == 'Robot':\n troop.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"MarshallR1.png\"))\n\n if troop.team == 2:\n if troop.Type == 'Soldier':\n troop.Text = pygame.image.load(os.path.join('Afbeeldingen', 'SheriffR2.png'))\n if troop.Type == 'Tank':\n troop.Text = pygame.image.load(os.path.join('Afbeeldingen', 'CowboyR2.png'))\n if troop.Type == 'Robot':\n troop.Text = pygame.image.load(os.path.join('Afbeeldingen', 'MarshallR2.png'))\n\n if troop.team == 3:\n if troop.Type == 'Soldier':\n troop.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"SheriffR3.png\"))\n if troop.Type == 'Tank':\n troop.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"CowboyR3.png\"))\n if troop.Type == 'Robot':\n troop.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"MarshallR3.png\"))\n\n if troop.team == 4:\n if troop.Type == 'Soldier':\n Troop.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"SheriffR4.png\"))\n if troop.Type == 'Tank':\n Troop.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"CowboyR4.png\"))\n if troop.Type == 'Robot':\n Troop.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"MarshallR4.png\"))\n\n #IF PLAYER IS ON LAND\n elif grid[troop.y][troop.x] != 0:\n if troop.team == 1:\n if troop.Type == 'Soldier':\n troop.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"Sheriff1.png\"))\n if troop.Type == 'Tank':\n troop.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"Cowboy1.png\"))\n if troop.Type == 'Robot':\n troop.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"Marshall1.png\"))\n\n if troop.team == 2:\n if troop.Type == 'Soldier':\n troop.Text = pygame.image.load(os.path.join('Afbeeldingen', 'Sheriff2.png'))\n if troop.Type == 'Tank':\n troop.Text = pygame.image.load(os.path.join('Afbeeldingen', 'Cowboy2.png'))\n if troop.Type == 'Robot':\n troop.Text = pygame.image.load(os.path.join('Afbeeldingen', 'Marshall2.png'))\n\n if troop.team == 3:\n if troop.Type == 'Soldier':\n troop.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"Sheriff3.png\"))\n if troop.Type == 'Tank':\n troop.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"Cowboy3.png\"))\n if troop.Type == 'Robot':\n troop.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"Marshall3.png\"))\n if troop.team == 4:\n if troop.Type == 'Soldier':\n troop.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"Sheriff4.png\"))\n if troop.Type == 'Tank':\n troop.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"Cowboy4.png\"))\n if troop.Type == 'Robot':\n troop.Text = pygame.image.load(os.path.join(\"Afbeeldingen\", \"Marshall4.png\"))\n\n\n\n\n @staticmethod\n def checkOfJeErHeenKan():\n for troop in Trooplist:\n if Player.NumberT == troop.team-1:\n ClickTroopRight = ( (pos[0] / 40) > (troop.x + 0.75) and (pos[0] / 40) < (troop.x + 1.0) and (pos[1] / 40) > (troop.y + 0.25) and (pos[1] / 40) < (troop.y + 0.75) )\n ClickTroopLeft = ( (pos[0] / 40) > (troop.x + 0) and (pos[0] / 40) < (troop.x + 0.25) and (pos[1] / 40) > (troop.y + 0.10) and (pos[1] / 40) < (troop.y + 0.90) )\n ClickTroopAbove = ( (pos[0] / 40) > (troop.x + 0.25) and (pos[0] / 40) < (troop.x + 0.75) ) and ( (pos[1] / 40) > (troop.y) and (pos[1] / 40) < (troop.y + 0.25) )\n ClickTroopUnder = ( (pos[0] / 40) > (troop.x + 0.25) and (pos[0] / 40) < (troop.x + 0.75 ) ) and ( (pos[1] / 40) > (troop.y + 0.75) and (pos[1] / 40) < (troop.y + 1) )\n\n if ClickTroopRight:\n if troop.x + 1 > 17:\n return False\n elif troop.x + 1 == 17 and troop.y == 0:\n return False\n elif troop.x + 1 == 17 and troop.y == 17:\n return False\n\n if ClickTroopLeft:\n if troop.x - 1 < 0:\n return False\n elif troop.x - 1 == 0 and troop.y == 0:\n return False\n elif troop.x - 1 == 0 and troop.y == 17:\n return False\n\n if ClickTroopAbove:\n if troop.y - 1 < 0:\n return False\n elif troop.x == 17 and troop.y - 1 == 0:\n return False\n elif troop.x == 0 and troop.y - 1 == 0:\n return False\n\n if ClickTroopUnder:\n if troop.y + 1 > 17:\n return False\n elif troop.x == 17 and troop.y + 1 == 17:\n return False\n elif troop.x == 0 and troop.y + 1 == 17:\n return False\n else:\n return True\n\n\n def checkWaarJeHeenWil():\n for troop in Trooplist:\n ClickTroopRight = ( (pos[0] / 40) > (troop.x + 0.75) and (pos[0] / 40) < (troop.x + 1.0) and (pos[1] / 40) > (troop.y + 0.25) and (pos[1] / 40) < (troop.y + 0.75) )\n ClickTroopLeft = ( (pos[0] / 40) > (troop.x + 0) and (pos[0] / 40) < (troop.x + 0.25) and (pos[1] / 40) > (troop.y + 0.10) and (pos[1] / 40) < (troop.y + 0.90) )\n ClickTroopAbove = ( (pos[0] / 40) > (troop.x + 0.25) and (pos[0] / 40) < (troop.x + 0.75) ) and ( (pos[1] / 40) > (troop.y) and (pos[1] / 40) < (troop.y + 0.25) )\n ClickTroopUnder = ( (pos[0] / 40) > (troop.x + 0.25) and (pos[0] / 40) < (troop.x + 0.75 ) ) and ( (pos[1] / 40) > (troop.y + 0.75) and (pos[1] / 40) < (troop.y + 1) )\n if event.type == pygame.MOUSEBUTTONDOWN:\n if Player.NumberT == troop.team-1:\n if troop.Type != 'Barrack':\n if row < 18 and column < 18:\n\n if ClickTroopRight:\n troop.x += 1\n NextPlayer()\n move.play()\n if ClickTroopLeft:\n troop.x -= 1\n NextPlayer()\n move.play()\n if ClickTroopAbove:\n troop.y -= 1\n NextPlayer()\n move.play()\n if ClickTroopUnder:\n troop.y += 1\n NextPlayer()\n move.play()\n\n\n def Attack():\n if event.type == pygame.MOUSEBUTTONDOWN:\n pos = pygame.mouse.get_pos()\n column = pos[0] // (WIDTH + MARGIN)\n row = pos[1] // (HEIGHT + MARGIN)\n # for troop in Trooplist:\n enemy = Troop.getEnemyFromCoordinates(row, column)\n if enemy is not None:\n if Troop.checkOfHuidigSoldierErNaastStaat(enemy.x,enemy.y):\n for troop in Trooplist:\n if grid[troop.x][troop.y] != 0:\n\n if Player.NumberT == troop.team-1:\n SheriffAttack.play()\n if enemy.Type == 'Soldier':\n Trooplist.remove(enemy)\n NextPlayer()\n if enemy.Type == 'Robot':\n Trooplist.remove(troop)\n NextPlayer()\n if enemy.Type == 'Tank':\n Trooplist.remove(troop)\n NextPlayer()\n if enemy.Type == 'Barrack':\n pass\n\n if Troop.checkOfHuidigRobotErNaastStaat(enemy.x, enemy.y):\n for troop in Trooplist:\n if grid[troop.x][troop.y] != 0:\n if Player.NumberT == troop.team-1:\n MarshallAttack.play()\n if enemy.Type == 'Soldier':\n Trooplist.remove(enemy)\n NextPlayer()\n if enemy.Type == 'Robot':\n Trooplist.remove(enemy)\n NextPlayer()\n if enemy.Type == 'Tank':\n Trooplist.remove(troop)\n NextPlayer()\n\n if Troop.checkOfHuidigTankErNaastStaat(enemy.x,enemy.y):\n for troop in Trooplist:\n if grid[troop.x][troop.y] != 0:\n if Player.NumberT == troop.team-1:\n CowboyAttack.play()\n if enemy.Type == 'Soldier':\n Trooplist.remove(enemy)\n NextPlayer()\n if enemy.Type == 'Robot':\n Trooplist.remove(enemy)\n NextPlayer()\n if enemy.Type == 'Tank':\n Trooplist.remove(enemy)\n NextPlayer()\n\n # if enemy.Type == 'Barrack' and enemy.HP == 0:\n # Trooplist.remove(enemy)\n # # elif troop.Type == 'Robot':\n #\n # if enemy.Type == 'Soldier':\n # Trooplist.remove(enemy)\n # if enemy.Type == 'Robot':\n # Trooplist.remove(enemy)\n\n # if enemy is not None:\n # RightTroop = ( (pos[0] / 40) > (enemy.x + 1) and (pos[0] / 40) < (enemy.x + 2) and (pos[1] / 40) > (enemy.y) and (pos[1] / 40) < (enemy.y + 1) )\n # LeftTroop = ( (pos[0] / 40) > (enemy.x - 1) and (pos[0] / 40) < (enemy.x) ) and (pos[1] / 40) > (enemy.y) and (pos[1] / 40) < (enemy.y + 1)\n # UnderTroop = ( (pos[0] / 40) > (enemy.x) and (pos[0] / 40) < (enemy.x + 1) ) and ( (pos[1] / 40) > (enemy.y + 1) and (pos[1] / 40) < (enemy.y + 2) )\n # AboveTroop = ( (pos[0] / 40) > (enemy.x) and (pos[0] / 40) < (enemy.x + 1) ) and ( (pos[1] / 40) > (enemy.y - 1) and (pos[1] / 40) < (enemy.y) )\n # # ClickTroop = ( (pos[0] / 40) > (troop.x) and (pos[0] / 40) < (troop.x + 1) ) and ( (pos[1] / 40) > (troop.y) and (pos[1] / 40) < (troop.y + 1) )\n # if enemy.team != 1:\n # # if event.type == pygame.MOUSEBUTTONDOWN:\n #\n # # if RightTroop:\n # # print ('kaas')\n # # if grid[enemy.y][enemy.x+1] != (enemy.team != 1):\n # # if grid[troop.y][troop.x + 1] == (troop.Type != 'Soldier'):\n # print(enemy)\n # Trooplist.remove(enemy )\n # grid[enemy.y][enemy.x] = 1\n #\n #\n #\n # if LeftTroop:\n # if grid[troop.y][troop.x - 1] != (troop.team == 1):\n # if grid[troop.y][troop.x - 1] != (troop.Type == 'Soldier'):\n # if troop.Type == 'Soldier':\n # Trooplist.remove(Trooplist[troop.Type != \"Tank\"] )\n # grid[troop.y][troop.x-1] = 1\n #\n\n def __str__(self):\n return \"({},{}), {}, {}\".format(self.y, self.x, self.Type, self.team)\n\nclass Barrack:\n def __init__(self, pos, id, player):\n self.x = pos[0]\n self.y = pos[1]\n self.id = id\n self.player = Player\n self.Type1 = pygame.image.load(os.path.join(\"Afbeeldingen\", \"barrack1.png\"))\n self.Type2 = pygame.image.load(os.path.join(\"Afbeeldingen\", \"barrack3.png\"))\n self.Type3 = pygame.image.load(os.path.join(\"Afbeeldingen\", \"barrack2.png\"))\n self.Type4 = pygame.image.load(os.path.join(\"Afbeeldingen\", \"barrack4.png\"))\n\n # def DrawBarrack():\n # for Barrack in BarrackList:\n # if Barrack.id == 1:\n # screen.blit(pygame.transform.scale(Barrack.Type1, (WIDTH, HEIGHT)),\n # (Barrack.x * offset, Barrack.y * offset))\n #\n # if Barrack.id == 2:\n # screen.blit(pygame.transform.scale(Barrack.Type2, (WIDTH, HEIGHT)),\n # (Barrack.x * offset, Barrack.y * offset))\n #\n # if Barrack.id == 3:\n # screen.blit(pygame.transform.scale(Barrack.Type3, (WIDTH, HEIGHT)),\n # (Barrack.x * offset, Barrack.y * offset))\n #\n # if Barrack.id == 4:\n # screen.blit(pygame.transform.scale(Barrack.Type4, (WIDTH, HEIGHT)),\n # (Barrack.x * offset, Barrack.y * offset))\n # def Buy():\n #\n # for Barrack in BarrackList:\n # for Barrack in BarrackList:\n # if row < 18 and column <18:\n # if event.type == pygame.MOUSEBUTTONDOWN and grid[row][column] == grid[Barrack.y][Barrack.x]:\n # if grid[Barrack.y][Barrack.x] and grid[Barrack.y][Barrack.x] == grid[row][column]:\n # if Barrack.id == 1:\n # Trooplist.append(Troop(1,(0,2),'Tank',4))\n # if Barrack.id == 3:\n # Trooplist.append(Troop(3,(12,12),'Soldier',3))\n # # screen.blit(pygame.transform.scale(Troop.Text, (WIDTH, HEIGHT)),(Troop.x*offset, Troop.y*offset))\n # print('Kaas')\n\n\ndef Draw():\n Troop.Attack()\n\n Troop.Move()\n for Barrack in Barracklist:\n screen.blit(pygame.transform.scale(Barrack.Text, (WIDTH, HEIGHT)),(Barrack.x*offset, Barrack.y*offset))\n\n\n# test\nbiome = \"\"\n\nSoldierPrice = 0\nRobotPrice = 0\nTankPrice = 0\nBarrackPrice = 0\nBoatPrice = 0\n\ndef biomeprices():\n global SoldierPrice\n global RobotPrice\n global TankPrice\n global BarrackPrice\n global BoatPrice\n\n if Player.NumberT == 0:\n SoldierPrice = 150\n RobotPrice = 300\n TankPrice = 600\n BarrackPrice = 500\n BoatPrice = 300\n if Player.NumberT == 1:\n SoldierPrice = 120\n RobotPrice = 300\n TankPrice = 750\n BarrackPrice = 500\n BoatPrice = 300\n if Player.NumberT == 2:\n SoldierPrice = 150\n RobotPrice = 240\n TankPrice = 750\n BarrackPrice = 500\n BoatPrice = 300\n if Player.NumberT == 3:\n SoldierPrice = 150\n RobotPrice = 300\n TankPrice = 750\n BarrackPrice = 500\n BoatPrice = 240\n\ndef drawPrices():\n global SoldierPrice\n global RobotPrice\n global TankPrice\n global BarrackPrice\n global BoatPrice\n\n if Player.NumberT == 0:\n drawText([760, 440], \"Sheriff: \", 30, (255, 255, 255))\n drawText([900, 440], str(Costs(\"Forest\").Soldier), 30, (255, 255, 255))\n drawText([760, 490], \"Marshall: \", 30, (255, 255, 255))\n drawText([900, 490], str(Costs(\"Forest\").Robot), 30, (255, 255, 255))\n drawText([760, 540], \"Cowboy: \", 30, (255, 255, 255))\n drawText([900, 540], str(Costs(\"Forest\").Tank), 30, (255, 255, 255))\n\n if Player.NumberT == 1:\n drawText([760, 440], \"Sheriff: \", 30, (255, 255, 255))\n drawText([900, 440], str(Costs(\"Swamp\").Soldier), 30, (255, 255, 255))\n drawText([760, 490], \"Marshall: \", 30, (255, 255, 255))\n drawText([900, 490], str(Costs(\"Swamp\").Robot), 30, (255, 255, 255))\n drawText([760, 540], \"Cowboy: \", 30, (255, 255, 255))\n drawText([900, 540], str(Costs(\"Swamp\").Tank), 30, (255, 255, 255))\n\n if Player.NumberT == 2:\n drawText([760, 440], \"Sheriff: \", 30, (255, 255, 255))\n drawText([900, 440], str(Costs(\"Snow\").Soldier), 30, (255, 255, 255))\n drawText([760, 490], \"Marshall: \", 30, (255, 255, 255))\n drawText([900, 490], str(Costs(\"Snow\").Robot), 30, (255, 255, 255))\n drawText([760, 540], \"Cowboy: \", 30, (255, 255, 255))\n drawText([900, 540], str(Costs(\"Snow\").Tank), 30, (255, 255, 255))\n\n if Player.NumberT == 3:\n drawText([760, 440], \"Sheriff: \", 30, (255, 255, 255))\n drawText([900, 440], str(Costs(\"Desert\").Soldier), 30, (255, 255, 255))\n drawText([760, 490], \"Marshall: \", 30, (255, 255, 255))\n drawText([900, 490], str(Costs(\"Desert\").Robot), 30, (255, 255, 255))\n drawText([760, 540], \"Cowboy: \", 30, (255, 255, 255))\n drawText([900, 540], str(Costs(\"Desert\").Tank), 30, (255, 255, 255))\n\n SheriffIcon = pygame.image.load(os.path.join(\"Afbeeldingen\", \"SheriffW.png\"))\n screen.blit((pygame.transform.scale(SheriffIcon, (30, 30))), (725, 440))\n\n MarshallIcon = pygame.image.load(os.path.join(\"Afbeeldingen\", \"MarshallW.png\"))\n screen.blit((pygame.transform.scale(MarshallIcon, (30, 30))), (725, 490))\n\n CowboyIcon = pygame.image.load(os.path.join(\"Afbeeldingen\", \"CowboyW.png\"))\n screen.blit((pygame.transform.scale(CowboyIcon, (30, 30))), (725, 540))\n\n\ndef drawText(location, text, size, color):\n font = pygame.font.SysFont('Calibri', size, True, False)\n text = font.render(text, True, color) # BLACK\n text = pygame.transform.rotate(text, 0)\n screen.blit(text, location)\n\n# -------- Main Program Loop -----------\n\npygame.init()\nbackground(\"Menu\")\n# Buttons\nbuttonsheriff = pygbutton.PygButton((740, 290, 160, 60), normal=\"Afbeeldingen/knopjes/Sheriff.png\", down=\"Afbeeldingen/knopjes/SheriffPressed.png\")\nbuttonmarshal = pygbutton.PygButton((920, 290, 160, 60), normal=\"Afbeeldingen/knopjes/Marshell.png\", down=\"Afbeeldingen/knopjes/MarshellPressed.png\")\nbuttoncowboy = pygbutton.PygButton((1100, 290, 160, 60), normal=\"Afbeeldingen/knopjes/Cowboy.png\", down=\"Afbeeldingen/knopjes/CowboyPressed.png\")\nbuttonmute = pygbutton.PygButton((920, 640, 160, 60), normal=\"Afbeeldingen/knopjes/Mute.png\", down=\"Afbeeldingen/knopjes/Mute1.png\")\nbuttonpass = pygbutton.PygButton((740, 640, 160, 60), normal=\"Afbeeldingen/knopjes/Endturn.png\", down=\"Afbeeldingen/knopjes/EndturnPressed.png\")\nbuttonquit = pygbutton.PygButton((1100, 640, 160, 60), normal=\"Afbeeldingen/knopjes/QuitSmall.png\",down=\"Afbeeldingen/knopjes/QuitSmallPressed.png\")\nallbuttons = (buttonsheriff, buttonmarshal, buttoncowboy, buttonmute, buttonpass, buttonquit)\n\n\nglobal Trooplist\nTrooplist = [Troop(1, (2, 2), 'Soldier'), Troop(2, (15, 2), 'Soldier'), Troop(3, (2, 15), 'Soldier'), Troop(4,(15,15),'Soldier')]\nBarracklist = [Troop(1,(0,0),'Barrack'),Troop(2,(17,0),'Barrack'), Troop(3,(0,17),'Barrack'), Troop(4,(17,17),'Barrack')]\nglobal BarrackList\n# BarrackList = [Barrack((0, 0), 1, 1), Barrack((0, 17), 2, 2), Barrack((17, 0), 3, 3), Barrack((17, 17), 4, 4)]\nplayer1 = Player('Player1', 1, 550)\nplayer2 = Player('Player2', 2, 500)\nplayer3 = Player('Player3', 3, 500)\nplayer4 = Player('Player4', 4, 500)\n\nwhile True:\n pos = pygame.mouse.get_pos()\n column = pos[0] // (WIDTH + MARGIN)\n row = pos[1] // (HEIGHT + MARGIN)\n for event in pygame.event.get(): # event handling loop\n if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):\n pygame.quit()\n sys.exit()\n if event.type == KEYDOWN and event.key == K_F7:\n player1.deposit(10000)\n if event.type == KEYDOWN and event.key == K_F8:\n player2.deposit(10000)\n if event.type == KEYDOWN and event.key == K_F9:\n player3.deposit(10000)\n if event.type == KEYDOWN and event.key == K_F10:\n player4.deposit(10000)\n\n if 'click' in buttonsheriff.handleEvent(event):\n time.sleep(0.1)\n if Player.NumberT == 0 and player1.Balance >= Costs(\"Forest\").Soldier:\n Trooplist.append(Troop(1,(1,1),'Soldier'))\n player1.withdraw(Costs(\"Forest\").Soldier)\n print(\"Sheriff\")\n NextPlayer()\n chaching.play()\n if Player.NumberT == 1 and player2.Balance >= Costs(\"Desert\").Soldier:\n Trooplist.append(Troop(2,(16,1),'Soldier'))\n player2.withdraw(Costs(\"Dessert\").Soldier)\n print(\"Sheriff\")\n NextPlayer()\n chaching.play()\n if Player.NumberT == 2 and player3.Balance >= Costs(\"Swamp\").Soldier:\n Trooplist.append(Troop(3,(1,16),'Soldier'))\n player3.withdraw(Costs(\"Swamp\").Soldier)\n print(\"Sheriff\")\n NextPlayer()\n chaching.play()\n if Player.NumberT == 3 and player4.Balance >= Costs(\"Snow\").Soldier:\n Trooplist.append(Troop(4,(16,16),'Soldier'))\n player4.withdraw(Costs(\"Snow\").Soldier)\n print(\"Sheriff\")\n NextPlayer()\n chaching.play()\n if 'click' in buttonmarshal.handleEvent(event):\n if Player.NumberT == 0 and player1.Balance >= Costs(\"Forest\").Robot:\n Trooplist.append(Troop(1,(1,0),'Robot'))\n player1.withdraw(Costs(\"Forest\").Robot)\n print(\"Marshall\")\n NextPlayer()\n chaching.play()\n if Player.NumberT == 1 and player2.Balance >= Costs(\"Desert\").Robot:\n Trooplist.append(Troop(2,(16,0),'Robot'))\n player2.withdraw(Costs(\"Dessert\").Robot)\n print(\"Marshall\")\n NextPlayer()\n chaching.play()\n if Player.NumberT == 2 and player3.Balance >= Costs(\"Swamp\").Robot:\n Trooplist.append(Troop(3,(0,16),'Robot'))\n player3.withdraw(Costs(\"Swamp\").Robot)\n print(\"Marshall\")\n NextPlayer()\n chaching.play()\n if Player.NumberT == 3 and player4.Balance >= Costs(\"Snow\").Robot:\n Trooplist.append(Troop(4,(16,17),'Robot'))\n player4.withdraw(Costs(\"Snow\").Robot)\n print(\"Marshall\")\n NextPlayer()\n chaching.play()\n if 'click' in buttoncowboy.handleEvent(event):\n if Player.NumberT == 0 and player1.Balance >= Costs(\"Forest\").Tank:\n Trooplist.append(Troop(1,(0,1),'Tank'))\n player1.withdraw(Costs(\"Forest\").Tank)\n print(\"CowBoy\")\n NextPlayer()\n chaching.play()\n if Player.NumberT == 1 and player2.Balance >= Costs(\"Desert\").Tank:\n Trooplist.append(Troop(2,(17,1),'Tank'))\n player2.withdraw(Costs(\"Dessert\").Tank)\n print(\"CowBoy\")\n NextPlayer()\n chaching.play()\n if Player.NumberT == 2 and player3.Balance >= Costs(\"Swamp\").Tank:\n Trooplist.append(Troop(3,(1,17),'Tank'))\n player3.withdraw(Costs(\"Swamp\").Tank)\n print(\"CowBoy\")\n NextPlayer()\n chaching.play()\n if Player.NumberT == 3 and player4.Balance >= Costs(\"Snow\").Tank:\n Trooplist.append(Troop(4,(17,16),'Tank'))\n player4.withdraw(Costs(\"Snow\").Tank)\n print(\"CowBoy\")\n NextPlayer()\n chaching.play()\n\n if 'click' in buttonpass.handleEvent(event):\n print(\"Pass\")\n if Player.NumberT < 3:\n Player.NumberT += 1\n else:\n Player.NumberT = 0\n TurnCnt = 4\n Click.play()\n\n if TurnCnt == 4 and Player.NumberT == 0:\n addMoney()\n if TurnCnt == 4 and Player.NumberT == 1:\n addMoney()\n if TurnCnt == 4 and Player.NumberT == 2:\n addMoney()\n if TurnCnt == 4 and Player.NumberT == 3:\n addMoney()\n\n if 'click' in buttonmute.handleEvent(event):\n print(\"Mute\")\n if music_playing:\n pygame.mixer.music.pause()\n music_playing = False\n else:\n pygame.mixer.music.unpause()\n music_playing = True\n Click.play()\n if 'click' in buttonquit.handleEvent(event):\n pygame.quit()\n sys.exit()\n\n if player1.Balance >= 30000:\n from GameProject.Winning import winning\n winning(\"money\", \"Player1\")\n if player2.Balance >= 30000:\n from GameProject.Winning import winning\n winning(\"money\", \"Player2\")\n if player3.Balance >= 30000:\n from GameProject.Winning import winning\n winning(\"money\", \"Player3\")\n if player4.Balance >= 30000:\n from GameProject.Winning import winning\n winning(\"money\", \"Player4\")\n\n\n\n #\n # pos = pygame.mouse.get_pos()\n # # Change the x/y screen coordinates to grid coordinates\n # column = pos[0] // (WIDTH + MARGIN)\n # row = pos[1] // (HEIGHT + MARGIN)\n # if row <18 and column <18:\n # if grid[row][column] != 0:\n # if TurnCnt != 1:\n # TurnCnt -= 1\n # else:\n # TurnCnt = 4\n # if PlayerCnt < 3:\n # PlayerCnt += 1\n # else:\n # PlayerCnt = 0\n # # Color around the clicked tile\n # print(\"Click \", pos, \"Grid coordinates: \", row, column, \"in biome:\", biome, \"at turn:\", TurnCnt, \"Player:\", PlayerCnt, Playerlist[PlayerCnt])\n\n # Set the screen background\n\n\n # # Draw the grid\n # for row in range(18):\n # for column in range(18):\n # texture = Travel\n # if grid[row][column] == 0:\n # texture = Water\n # if grid[row][column] == 1:\n # texture = KFC\n #\n #\n #\n # if grid[row][column] > 20 and grid[row][column] <= 73:\n # texture = Forest\n # if grid[row][column] > 73 and grid[row][column] <= 121:\n # texture = Swamp\n # if grid[row][column] > 121 and grid[row][column] <= 167:\n # texture = Desert\n # if grid[row][column] > 167 and grid[row][column] <= 213:\n # texture = Ice\n # if grid[row][column] > 213 and grid[row][column] <= 229:\n # texture = Stone\n # # pygame.draw.rect(screen,\n # # color,\n # # [(MARGIN + WIDTH) * column + MARGIN,\n # # (MARGIN + HEIGHT) * row + MARGIN,\n # # WIDTH,\n # # HEIGHT])\n # screen.blit(pygame.transform.scale(texture, (WIDTH, HEIGHT)),(column*offset, row*offset))\n background(\"Menu\")\n Grid()\n Draw()\n DrawTurns()\n drawPrices()\n # Barrack.DrawBarrack()\n biomeprices()\n # Barrack.Buy()\n\n for b in allbuttons:\n b.draw(screen)\n\n # Go ahead and update the screen with what we've drawn.\n pygame.display.flip()\n # Limit to 60 frames per second\n clock.tick(60)\n\n#\n# if __name__ == '__main__':\n# main()\n","sub_path":"GameProject/Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":43652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"523412249","text":"#!/usr/bin/python3\nimport matplotlib.pyplot as plt\nimport openpyxl as xl\n\nwb = xl.load_workbook('mem.xlsx')\nsheet = wb.active\nmemList = []\nfor i in range(1, sheet.max_row):\n #print(sheet.cell(i, 1).value[0: -2])\n memList.append(int(sheet.cell(i, 1).value[0: -2]))\n\nplt.plot(memList)\nplt.show()\n","sub_path":"memUseGraphic.py","file_name":"memUseGraphic.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"82788744","text":"'''摄像头 Camera\n功能列表\n1. 相机拍摄画面预览\n1. 图像采集并保存在特定的路径\n2. UVC相机参数的可视化调参\n\n备注:\n1. 不同摄像头型号的可设置的参数及取值范围各不相同.\n 当前的参数设置仅对机型KS2A418适用\n'''\nimport time\nimport cv2\nimport numpy as np\nimport pickle\nimport subprocess\nimport math\nfrom config import *\n\nclass Camera:\n\t'''Camera全局曝光全局快门UVC免驱摄像头'''\t\n\t# 设置图像分辨率\n\tIMG_WIDTH = CAM_IMG_WIDTH # 图像宽度\n\tIMG_HEIGHT = CAM_IMG_HEIGHT # 图像高度\n\tBRIGHNESS = CAM_BRIGHNESS # 图像亮度 取值 [-64, 64]\n\tCONTRUST = CAM_CONTRUST # 对比度\n\tHUE = CAM_HUE # 相机色调\n\tSATURATION = CAM_SATURATION # 图像饱和度\n\tSHARPNESS = CAM_SHARPNESS # 图像清晰度锐度\n\tGAMMA = CAM_GAMMA\n\tAWB = CAM_AWB # 自动白平衡\n\tWHITE_BALANCE_TEMPRATURE = CAM_WHITE_BALANCE_TEMPRATURE\n\tEXPOSURE_AUTO = CAM_EXPOSURE_AUTO # 是否自动曝光\n\tEXPOSURE_ABSOLUTE = CAM_EXPOSURE_ABSOLUTE # 相对曝光\n\tFPS = CAM_FPS # 帧率 (实际上达不到)\n\tIS_DEBUG = False\n\t# 相机摆放位置相关的参数\n\t# 单位cm\n\th = CAM_H \n\t# 相机光心与水平面的夹角 (俯仰角) 单位弧度\n\ttheta = np.radians(CAM_PITCH)\n\tdef __init__(self, device):\n\t\tself.device = device\n\t\n\tdef init_camera(self):\n\t\t# 设置分辨率\n\t\tsubprocess.call(\"v4l2-ctl -d {} --set-fmt-video=width={},height={},pixelformat=MJPG\".format(self.device,self.IMG_WIDTH,self.IMG_HEIGHT), shell=True)\n\t\t# 设置帧率\n\t\tsubprocess.call(\"v4l2-ctl -d {} -p {}\".format(self.device, self.FPS), shell=True)\n\t\t# 打开自动白平衡\n\t\tsubprocess.call(\"v4l2-ctl -d {} --set-ctrl white_balance_temperature_auto={}\".format(self.device, self.AWB), shell=True)\n\t\tif not self.AWB:\n\t\t\tsubprocess.call(\"v4l2-ctl -d {} --set-ctrl white_balance_temperature={}\".format(self.device, self.WHITE_BALANCE_TEMPRATURE), shell=True)\n\t\t# 设置亮度\n\t\tsubprocess.call(\"v4l2-ctl -d {} --set-ctrl brightness={}\".format(self.device, self.BRIGHNESS), shell=True)\n\t\t# 设置饱和度\n\t\tsubprocess.call(\"v4l2-ctl -d {} --set-ctrl saturation={}\".format(self.device, self.SATURATION), shell=True)\n\t\t# 设置锐度(图像清晰度)\n\t\tsubprocess.call(\"v4l2-ctl -d {} --set-ctrl sharpness={}\".format(self.device, self.SHARPNESS), shell=True)\n\t\t# 设置色调\n\t\tsubprocess.call(\"v4l2-ctl -d {} --set-ctrl hue={}\".format(self.device, self.HUE), shell=True)\n\t\t# 设置对比度\n\t\tsubprocess.call(\"v4l2-ctl -d {} --set-ctrl contrast={}\".format(self.device, self.CONTRUST), shell=True)\n\t\t# 设置Gamma\n\t\tsubprocess.call(\"v4l2-ctl -d {} --set-ctrl gamma={}\".format(self.device, self.GAMMA), shell=True)\n\n\t\tif not self.EXPOSURE_AUTO:\n\t\t\tsubprocess.call(\"v4l2-ctl -d {} --set-ctrl exposure_auto=1\".format(self.device), shell=True)\n\t\t\t# 设置绝对曝光时间\n\t\t\t# 取值范围1 - 8188\n\t\t\tsubprocess.call(\"v4l2-ctl -d {} --set-ctrl exposure_absolute={}\".format(self.device, self.EXPOSURE_ABSOLUTE), shell=True)\n\t\telse:\n\t\t\t# 自动曝光\n\t\t\tsubprocess.call(\"v4l2-ctl -d {} --set-ctrl exposure_auto=3\".format(self.device), shell=True)\n\t\t\n\t\t# time.sleep(2)\n\t\tif self.IS_DEBUG:\n\t\t\t# 打印配置结果\n\t\t\tsubprocess.call(\"v4l2-ctl -d {} --all\".format(self.device), shell=True)\n\n\tdef get_video_capture(self):\n\t\t'''生成Capture对象'''\n\t\tcapture = None\n\t\ttry:\n\t\t\tcapture = cv2.VideoCapture(int(self.device[-1]), cv2.CAP_V4L2)\n\t\texcept TypeError as e:\n\t\t\tcapture = cv2.VideoCapture(int(self.device[-1]))\n\t\t\t# capture = cv2.VideoCapture(0)\n\t\t\t\n\t\t# capture.set(cv2.CAP_PROP_FRAME_HEIGHT, self.IMG_HEIGHT) #设置图像高度\n\t\t# capture.set(cv2.CAP_PROP_FRAME_WIDTH, self.IMG_WIDTH) #设置图像宽度\n\t\tcapture.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')) # 设置编码方式\t\n\t\t# 缓冲区设置为1结果就是帧率只有 15fps\n\t\t# 缓冲区设置为2之后帧率提升到40FPS\n\t\tcapture.set(cv2.CAP_PROP_BUFFERSIZE, 2) #设置视频缓冲区为1\n\t\treturn capture\n\t\n\tdef load_cam_calib_data(self, file_path='config/camera_info.bin'):\n\t\t'''载入相机标定数据'''\n\t\t# 读取标定参数\n\t\twith open(file_path, 'rb') as f:\n\t\t\tcamera_info = pickle.load(f)\n\t\t\t# 获取摄像头内参\n\t\t\tself.intrinsic = camera_info['intrinsic']\n\t\t\t# 获取摄像头的畸变系数\n\t\t\tself.distortion = camera_info['distortion']\n\t\t\t# x轴的映射\n\t\t\tself.remap_x = camera_info['remap_x']\n\t\t\t# y轴映射\n\t\t\tself.remap_y = camera_info['remap_y']\n\t\t\t# 根据相机标定参数\n\t\t\t# 提取图像中心(cx, cy)与焦距f(单位:像素)\n\t\t\tself.f = (self.intrinsic[0, 0] + self.intrinsic[1, 1])/2\n\t\t\t# 图像中心的坐标\n\t\t\tself.cx = self.intrinsic[0, 2]\n\t\t\tself.cy = self.intrinsic[1, 2]\n\t\t\t# 生成视场角等相关参数\n\t\t\tself.alpha1 = np.arctan(self.cy/self.f)\n\t\t\tself.alpha2 = np.arctan((self.IMG_HEIGHT-self.cy)/self.f)\n\t\t\tself.beta1 = np.arctan(self.cx/self.f)\n\t\t\tself.beta2 = np.arctan((self.IMG_WIDTH-self.cx)/self.f)\n\t\n\n\tdef load_ipm_remap(self, calc_online=True, file_path='config/ipm_remap.bin'):\n\t\t'''载入IPM映射矩阵'''\n\t\tif calc_online:\n\t\t\tprint('计算IPM映射矩阵, 并存储在 {}'.format(file_path))\n\t\t\t# 构造透视逆变换矩阵\n\t\t\tself.ipm_remap_x = np.zeros((self.IMG_HEIGHT, self.IMG_WIDTH))\n\t\t\tself.ipm_remap_y = np.zeros((self.IMG_HEIGHT, self.IMG_WIDTH))\n\t\t\t# 修改每一个元素里面的值\n\t\t\tfor px in range(self.IMG_WIDTH):\n\t\t\t\tfor py in range(self.IMG_HEIGHT):\n\t\t\t\t\tself.ipm_remap_x[py][px],self.ipm_remap_y[py][px] = self.inverse_projection_mapping(px, py)\n\t\t\t# 保存数据\n\t\t\tipm_remap_data = {}\n\t\t\tipm_remap_data['ipm_remap_x'] = self.ipm_remap_x\n\t\t\tipm_remap_data['ipm_remap_y'] = self.ipm_remap_y\n\n\t\t\twith open(file_path, 'wb') as f:\n\t\t\t\tf.write(pickle.dumps(ipm_remap_data))\n\t\t\tprint('更新完成')\n\t\telse:\n\t\t\t# 从二进制文件中载入\n\t\t\twith open(file_path, 'rb') as f:\n\t\t\t\tipm_remap_data = pickle.load(f)\n\t\t\t\tself.ipm_remap_x = ipm_remap_data['ipm_remap_x']\n\t\t\t\tself.ipm_remap_y = ipm_remap_data['ipm_remap_y']\n\t\t\n\tdef remove_distortion(self, image):\n\t\t'''图像去除畸变'''\n\t\treturn cv2.remap(image, self.remap_x, self.remap_y, cv2.INTER_LINEAR)\n\t\n\tdef inverse_projection_mapping(self, px, py):\n\t\t'''逆向透视映射\n\t\tpx, py 可以是单个数值, 也可以是列向量\n\t\t支持批量映射\n\t\t'''\n\t\tup = -1 * (py - self.cy)\n\t\tvp = px - self.cx\n\t\tangle_puOg = np.arctan(up/self.f)\n\t\ttan_puOp = vp/self.f * np.cos(angle_puOg)\n\t\tXp = self.h / np.tan(self.theta - angle_puOg)\n\t\t# 注意: 这里需要乘上一个负号\n\t\tYp = -1*np.sqrt(self.h**2 + Xp**2) * tan_puOp\n\t\treturn Xp, Yp\n\n\tdef inverse_projection_mapping2(self, px, py):\n\t\t'''透视逆变换, 直接从矩阵里面读取'''\n\t\treturn self.ipm_remap_x[py][px], self.ipm_remap_y[py][px]\n\n\t\ndef update_camera_param(camera, win_name='image_win'):\n\t'''更新摄像头参数'''\n\t# 获取更新前的数值\n\tcamera.HUE = cv2.getTrackbarPos('HUE', win_name)\n\tcamera.SATURATION = cv2.getTrackbarPos('SATURATION', win_name)\n\tcamera.CONTRUST = cv2.getTrackbarPos('CONTRUST', win_name)\n\tcamera.SHARPNESS = cv2.getTrackbarPos('SHARPNESS', win_name)\n\t# 相机重新初始化\n\tcamera.init_camera()\n\t\n\tlog_info = '\\n==========更新之后的相机参数============\\n'\n\tlog_info += '色调(HUE): {}\\n'.format(camera.HUE)\n\tlog_info += '饱和度(SATURATION): {}\\n'.format(camera.SATURATION)\n\tlog_info += '对比度(CONTRUST): {}\\n'.format(camera.CONTRUST)\n\tlog_info += '锐度(SHARPNESS): {}\\n'.format(camera.SHARPNESS)\n\tlog_info += '\\n\\n'\n\n\tlogging.info(log_info)\n\ndef main(argv):\n\t'''调整相机参数, 预览图像'''\n\timg_cnt = FLAGS.img_cnt\n\t# 创建相机对象\n\tcamera = Camera(FLAGS.device)\n\t# 初始相机\n\tcamera.init_camera()\n\tcapture = camera.get_video_capture()\n\t\n\tif FLAGS.rm_distortion:\n\t\t# 载入标定数据\n\t\tcamera.load_cam_calib_data()\n\t# 创建一个名字叫做 “image_win” 的窗口\n\twin_name = 'image_win'\n\tcv2.namedWindow(win_name,flags=cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO | cv2.WINDOW_GUI_EXPANDED)\n\t# 创建滑动条\n\tis_trackbar_update = False # 滑动条是否发生变化\n\t# 色调\n\tcv2.createTrackbar('HUE', win_name, -2000, 2000,lambda x: update_camera_param(camera))\n\tcv2.setTrackbarPos('HUE', win_name, Camera.HUE)\n\t# 饱和度\n\tcv2.createTrackbar('SATURATION', win_name, 0, 100,lambda x: update_camera_param(camera))\n\tcv2.setTrackbarPos('SATURATION', win_name, Camera.SATURATION)\n\t# 对比度\n\tcv2.createTrackbar('CONTRUST', win_name, 0, 95,lambda x: update_camera_param(camera))\n\tcv2.setTrackbarPos('CONTRUST', win_name, Camera.CONTRUST)\n\t# 锐度\n\tcv2.createTrackbar('SHARPNESS', win_name, 1, 100,lambda x: update_camera_param(camera))\n\tcv2.setTrackbarPos('SHARPNESS', win_name, Camera.SHARPNESS)\n\t\n\tfps = 40 # 设定一个初始值\n\twhile True:\n\t\tstart = time.time()\n\t\tret, image = capture.read()\n\t\tend = time.time()\n\t\tfps = int(0.9*fps + 0.1*1/(end-start))\n\t\t\n\t\tif not ret:\n\t\t\tlogging.error('图像获取失败')\n\t\t\tbreak\n\t\tif FLAGS.rm_distortion:\n\t\t\t# 图像去除畸变\n\t\t\timage = camera.remove_distortion(image)\n\t\t# 创建画布\n\t\tcanvas = np.copy(image)\n\t\t# 在画布上添加帧率的信息\n\t\tcv2.putText(canvas, text='FPS: {}'.format(fps),\\\n\t\t\t \torg=(50, 50), fontFace=cv2.FONT_HERSHEY_SIMPLEX, \\\n\t\t\t\tfontScale=1, thickness=2, lineType=cv2.LINE_AA, color=(0, 0, 255))\n\t\t# 添加帮助信息\n\t\tcv2.putText(canvas, text='S:Save Image',\\\n\t\t\t \torg=(50, camera.IMG_HEIGHT-100), fontFace=cv2.FONT_HERSHEY_SIMPLEX, \\\n\t\t\t\tfontScale=1, thickness=2, lineType=cv2.LINE_AA, color=(0, 0, 255))\n\t\tcv2.putText(canvas, text='Q: Quit',\\\n\t\t\t \torg=(50, camera.IMG_HEIGHT-50), fontFace=cv2.FONT_HERSHEY_SIMPLEX, \\\n\t\t\t\tfontScale=1, thickness=2, lineType=cv2.LINE_AA, color=(0, 0, 255))\n\n\t\t# 更新窗口“image_win”中的图片\n\t\tcv2.imshow('image_win', canvas)\n\t\tkey = cv2.waitKey(1)\n\n\t\tif key == ord('q'):\n\t\t\t# 如果按键为q 代表quit 退出程序\n\t\t\tbreak\n\t\telif key == ord('s'):\n\t\t\t# s键代表保存数据\n\t\t\tcv2.imwrite('{}/{}.png'.format(FLAGS.img_path, img_cnt), image)\n\t\t\tlogging.info(\"截图,并保存在 {}/{}.png\".format(FLAGS.img_path, img_cnt))\n\t\t\timg_cnt += 1\n\t\n\t# 关闭摄像头\n\tcapture.release()\n\t# 销毁所有的窗口\n\tcv2.destroyAllWindows()\n\nif __name__ == '__main__':\n\timport logging\n\timport sys\n\tfrom absl import app\n\tfrom absl import flags\n\n\t# 设置日志等级\n\tlogging.basicConfig(level=logging.INFO)\n\n\t# 定义参数\n\tFLAGS = flags.FLAGS\n\tflags.DEFINE_string('device', CAM_PORT_NAME, '摄像头的设备号')\n\tflags.DEFINE_integer('img_cnt', 0, '图像计数的起始数值')\n\tflags.DEFINE_string('img_path', 'data/image_raw', '图像的保存地址')\n\tflags.DEFINE_boolean('rm_distortion', False, '载入相机标定数据, 去除图像畸变')\n\t\n\t# 运行主程序\n\tapp.run(main)\n\t\n","sub_path":"bipedal-robot-rasp/src/cv_camera.py","file_name":"cv_camera.py","file_ext":"py","file_size_in_byte":10616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"75134033","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport time, copy\n\nclass Reversi:\n \"\"\"Reversi game logig class\n \"\"\"\n def __init__(self, movesCallBack = None, buttonsCheck = None):\n self.movesCallBack = movesCallBack\n self.buttonsCheck = buttonsCheck\n\n self.emptyTiles = 0\n self.whiteTiles = 0\n self.blackTiles = 0\n\n self.player1 = None\n self.player2 = None\n\n def roundStart(self, pl1, pl2, turnTime = 0):\n \"\"\"Create a new game and start playing\n \"\"\"\n self.run = True\n self.winner = 0\n self.board = [[0 for x in range(8)] for x in range(8)]\n self.movesMade = []\n \n self.board[3][3] = 1\n self.board[3][4] = 2\n self.board[4][3] = 2\n self.board[4][4] = 1\n\n self.turn = 1\n self.player = 1\n\n self.player1 = pl1\n self.player2 = pl2\n\n self.player1.gameStart(1, self.board)\n self.player2.gameStart(2, self.board)\n\n if self.movesCallBack != None:\n self.movesCallBack()\n\n self.turnStart = self.turnLength = self.pl1time = self.pl2time = self.pl1longestTurn = self.pl2longestTurn = self.pl1timeExeeded = self.pl2timeExeeded = 0\n\n while self.run:\n #time.sleep(0.2)\n validMoves = self.checkIsValidMoves(self.player)\n\n if self.player == 1:\n self.turnStart = time.time()\n self.player1.makeMove(self.turn, copy.deepcopy(self.board), validMoves, self.moveTo)\n self.turnLength = time.time() - self.turnStart\n self.moveMade(validMoves)\n self.pl1time += self.turnLength\n if turnTime and self.turnLength > turnTime:\n self.pl1timeExeeded += 1\n if self.pl1longestTurn < self.turnLength:\n self.pl1longestTurn = self.turnLength\n self.player = 2\n self.turn += 1\n else:\n self.turnStart = time.time()\n self.player2.makeMove(self.turn, copy.deepcopy(self.board), validMoves, self.moveTo)\n self.turnLength = time.time() - self.turnStart\n self.moveMade(validMoves)\n self.pl2time += self.turnLength\n if turnTime and self.turnLength > turnTime:\n self.pl2timeExeeded += 1\n if self.pl2longestTurn < self.turnLength:\n self.pl2longestTurn = self.turnLength\n self.player = 1\n self.turn += 1\n\n self.winner = self.checkGameEnd()\n\n if self.movesCallBack != None:\n if len(self.movesMade) > 0:\n self.movesCallBack(self.movesMade[-1])\n else:\n self.movesCallBack()\n\n if self.winner:\n self.run = False\n self.player1.gameEnd()\n self.player2.gameEnd()\n\n if self.buttonsCheck != None:\n self.buttonsCheck()\n\n #print (self.pl1time, self.pl2time)\n\n return {\"winner\": self.winner, \"pl1tiles\": self.whiteTiles, \"pl2tiles\": self.blackTiles, \\\n \"pl1time\": self.pl1time, \"pl2time\": self.pl2time, \\\n \"pl1longest\": self.pl1longestTurn, \"pl2longest\": self.pl2longestTurn, \\\n \"pl1err\": self.pl1timeExeeded, \"pl2err\": self.pl2timeExeeded}\n\n def moveMade(self, validMoves):\n \"\"\"Update the moves list with 'skip' moves\n \"\"\"\n if len(validMoves) == 0 and self.movesMade[-1][0] != self.turn:\n self.movesMade.append([self.turn, self.player, [-1,-1]])\n elif len(validMoves) != 0 and len(self.movesMade) > 0 and self.movesMade[-1][0] != self.turn:\n print (\"## Player skipped a move, while he could make a move ##\")\n self.movesMade.append([self.turn, self.player, [-2,-2]])\n\n def moveTo(self, x, y = None):\n \"\"\"Method for players to call when making a move in the game\n \"\"\"\n if type(x) == list:\n y = x[1]\n x = x[0]\n\n if x != None and y != None and self.board[x][y] == 0 and self.validMove(x, y, self.player):\n self.movesMade.append([self.turn, self.player, [x,y]])\n return True\n return False\n\n def getGameBoard(self):\n return self.board\n\n def abort(self):\n \"\"\"If the game needs to be aborted at the middle\n \"\"\"\n self.run = False\n if self.player1 != None:\n self.player1.gameEnd()\n if self.player2 != None:\n self.player2.gameEnd()\n\n def validMove(self, x, y, player):\n \"\"\"If the move is valid, it's made to the board and return True\n else return False\n \"\"\"\n if player == 1:\n opponent = 2\n elif player == 2:\n opponent = 1\n else:\n print (\"No player\")\n return False\n #print (player, opponent, x, y)\n\n piecesToFlip = []\n directionsToCheck = [[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]]\n for direction in directionsToCheck:\n piecesToFlip.extend(self.checkDirection(x, y, direction[0], direction[1], player, opponent))\n #print (piecesToFlip)\n\n if len(piecesToFlip) > 0:\n self.board[x][y] = player\n for spot in piecesToFlip:\n self.board[spot[0]][spot[1]] = player\n return True\n return False\n\n def checkDirection(self, x, y, dx, dy, player, opponent):\n \"\"\"Checks pieces to flip in the given direction and return a list of lists for those pieces to flip.\n else return empty list\n \"\"\"\n x += dx\n y += dy\n foundOpp = []\n while x < 8 and x > -1 and y < 8 and y > -1:\n #print (x, y, len(foundOpp))\n if self.board[x][y] == opponent:\n foundOpp.append([x,y])\n #print (foundOpp)\n elif len(foundOpp) > 0 and self.board[x][y] == player:\n #print (\"found own\")\n return foundOpp\n else:\n return []\n\n x += dx\n y += dy\n return []\n\n def checkGameEnd(self):\n \"\"\"Checks if game has come to the end.\n \"\"\"\n allTiles = [item for sublist in self.board for item in sublist]\n \n self.emptyTiles = sum(1 for tile in allTiles if tile == 0)\n self.whiteTiles = sum(1 for tile in allTiles if tile == 1)\n self.blackTiles = sum(1 for tile in allTiles if tile == 2)\n if not (self.emptyTiles and self.whiteTiles and self.blackTiles) or (len(self.movesMade) > 1 and self.movesMade[-1][2] == [-1,-1] and self.movesMade[-2][2] == [-1,-1]):\n if self.whiteTiles > self.blackTiles: #pl1 has won\n return 1\n elif self.whiteTiles < self.blackTiles: #pl2 has won\n return 2\n else: #draw\n return -1\n return False\n\n def checkIsValidMoves(self, player):\n \"\"\"Check if there are valid moves for the player\n \"\"\"\n moves = []\n directionsToCheck = [[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]]\n\n if player == 1:\n opponent = 2\n elif player == 2:\n opponent = 1\n else:\n print (\"No player\")\n return moves\n\n for x in range(8):\n for y in range(8):\n if self.board[x][y] == 0:\n for direction in directionsToCheck:\n #print (x,y, directionsToCheck.index(direction))\n if self.checkDirection(x, y, direction[0], direction[1], player, opponent) != []:\n moves.append([x,y])\n #print (\"found\")\n break\n\n return moves\n","sub_path":"reversi.py","file_name":"reversi.py","file_ext":"py","file_size_in_byte":7872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"2242401","text":"from django.http import HttpResponse\nfrom django.views.decorators.http import require_http_methods\nfrom localground.lib.api.decorators import process_identity\nfrom localground.lib.decorators import get_group_if_authorized\nfrom localground.account.models import Project \nimport simplejson as json\n\n@get_group_if_authorized\ndef get_group(request, object_type, object_id, group_object, access_key=None, to_json=True):\n '''\n Public view that returns serialized json for a particular Project or View.\n \n Required Parameters (from URL):\n object_type -- either a View or a Project\n object_id -- an id to the corresponding View or Project model\n group_object -- populated by the @get_group_if_authorized decorator\n access\n \n Optional Yes/No parameters (from request.GET params):\n id: primary key of object\n include_auth_users: if true, to_dict queries for list of users who\n have specific permissions on that print\n include_processed_maps: Also return a list of processed maps (if applicable)\n include_markers: Also return a list of markers\n include_audio: Also return a list of audio\n include_photos: Also return a list of photos\n include_notes: Also return a list of data list corresponding to\n tabular form data\n alias: Admins only: allows you to pretend you're someone else \n '''\n\n def check_flag(param):\n return request.GET.get(param, 'false') in ['True', 'true', '1', 'on']\n \n dict = group_object.to_dict(\n include_auth_users=check_flag('include_auth_users'),\n include_processed_maps=check_flag('include_processed_maps'),\n include_markers=check_flag('include_markers'),\n include_audio=check_flag('include_audio'),\n include_photos=check_flag('include_photos'),\n include_notes=check_flag('include_notes')\n )\n \n dict.update({\n 'success': True,\n 'request_parameters': request.GET\n })\n return HttpResponse(json.dumps(dict))\n\n \n@require_http_methods([\"GET\"])\n@process_identity\ndef get_my_projects(request, identity=None):\n def check_flag(param):\n return request.GET.get(param, 'false') in ['True', 'true', '1', 'on']\n try: \n projects = (Project.objects\n .get_objects(user=identity)\n .to_dict_list(\n include_auth_users=check_flag('include_auth_users'),\n include_processed_maps=check_flag('include_processed_maps'),\n include_markers=check_flag('include_markers'),\n include_audio=check_flag('include_audio'),\n include_photos=check_flag('include_photos')\n ))\n '''from django.shortcuts import render_to_response\n return render_to_response('profile/prints.html', {\n 'success': True,\n 'project': projects,\n 'request_parameters': request.GET\n })'''\n return HttpResponse(json.dumps({\n 'success': True,\n 'project': projects,\n 'request_parameters': request.GET\n }))\n except Project.DoesNotExist:\n return HttpResponse(json.dumps({'success': False, 'message': 'No projects found'}))\n\n\ndef get_users_from_username_string(request):\n import re\n from django.contrib.auth.models import User\n \n username_str = request.GET.get('search_text')\n username_str = re.sub(r'\\s', '', username_str) #remove all whitespace\n usernames = re.split(',', username_str) #split on delimiters\n for (counter, u) in enumerate(usernames):\n usernames[counter] = re.split('\\(|\\)|:|-', u)[0]\n \n #return HttpResponse(json.dumps({'uname': usernames}))\n try:\n users = (User.objects.filter(username__in=usernames)\n .order_by('username',))\n d = {\n 'success': True,\n 'results': [{'id': u.id, 'value': u.username} for u in users]\n }\n return HttpResponse(json.dumps(d))\n except User.DoesNotExist:\n return HttpResponse(json.dumps({'success': False, 'message': 'No users found'}))\n \n\n\n\n","sub_path":"account/views/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":4292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"391608006","text":"import argparse\nimport sys\nimport os\nimport json\nimport re\nimport requests\nfrom bs4 import BeautifulSoup\n\n\n### argparser ### \nparser = argparse.ArgumentParser(description='Hope you\\'re having a good day!')\nparser.add_argument('-d','--debug', action='store_true', default=False)\nparser.add_argument('-n','--new', action='store_true', default=False)\nargs = parser.parse_args()\n\n### CONSTANTS ###\n# args\nDEBUG = args.debug\nNEW_FILE = args.new\n# file saving\nCWD = os.getcwd()\nFILE_NAME = \"engineering_quotes.json\"\nSAVE_DIR = \"../data/\" if CWD.endswith(\"python\") else \"./data/\" \nSAVE_PATH = SAVE_DIR + FILE_NAME\n# html parsing\nPAT = r'\\d+\\.'\nURL = 'https://www.workflowmax.com/blog/101-engineering-quotes-from-the-minds-of-innovators'\nHTML_TAG = 'p'\n\n# Check for SAVE_DIR and create if not found\nprint(f\"Searching for \\\"{SAVE_DIR}\\\"\")\nif not os.path.exists(SAVE_DIR):\n print(f\"Creating \\\"{SAVE_DIR}\\\"\")\n os.mkdir(SAVE_DIR)\nprint(f\"SAVE_PATH : \\\"{SAVE_PATH}\\\"\\nReady to gather data!\")\n\nprint(f\"Checking if \\\"{FILE_NAME}\\\" already exists...\")\nif os.path.exists(SAVE_PATH):\n print(f\"\\\"{FILE_NAME}\\\" does already exist\")\n if not NEW_FILE:\n print(f\"Exiting {sys.argv[0]}\")\n exit()\n print(f\"Overwritting \\\"{FILE_NAME}\\\"\")\n# Get and parse URL\npage = requests.get(URL)\nsoup = BeautifulSoup(page.content, 'html.parser')\nresults = soup.find_all(HTML_TAG)\nprint(f\"Successfully received data from \\\"{URL}\\\"\")\n\n# Clean data from URL\nprint(f\"Preparing data to be saved...\")\nquotes = []\nid = 0\nfor i in range(len(results)):\n mat = re.match(PAT,results[i].text)\n if mat is not None:\n id += 1\n temp = results[i].text.replace(mat.group() + \" \", \"\").\\\n replace(\"”\", '\"').replace(\"“\", '\"').replace(\".-\", '\"-').\\\n replace(\"’\",\"'\").replace(\"…\",\"...\").replace(\"—\",\"--\").\\\n replace(\"‘\",\"'\").replace(\"\\u00a0\",\" \").split('\"-')\n temp[0] = temp[0].replace(\"\\\"\", \"\")\n if temp[1].startswith(\" \"):\n temp[1] = temp[1].replace(\" \", \"\", 1)\n quotes.append({\"id\":id,\"author\":temp[1],\"quote\":temp[0]})\nprint(\"Data sanitized!\")\n\n# [DEBUG]\nif DEBUG:\n for q in quotes:\n print(f\"id: {q['id']}.\\t{q['quote']} \\nby, {q['author']}\")\n\n# Save data to FILE_NAME\nprint(f\"Saving data to \\\"{SAVE_PATH}\\\"\")\nwith open(SAVE_PATH,'w') as out:\n json.dump(quotes, out)\nprint(\"Data Saved!\")\n","sub_path":"python/quote_finder.py","file_name":"quote_finder.py","file_ext":"py","file_size_in_byte":2370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"258821246","text":"import unittest\nfrom datetime import datetime\nfrom datarobot.utils import check_hashsum, normalize_date\nfrom werkzeug.exceptions import BadRequest\n\n\nclass TestDatarobot(unittest.TestCase):\n positive = {\n \"uid\": \"1\",\n \"name\": \"John Doe\",\n \"date\": \"2015-05-12T14:36:00.451765\",\n \"md5checksum\": \"e8c83e232b64ce94fdd0e4539ad0d44f\"}\n negative = {\n \"uid\": \"2\",\n \"name\": \"Jane Doe\",\n \"date\": \"2015-05-13\",\n \"md5checksum\": \"b419795d50db2a35e94c8364978d898f\"}\n\n def test_check_hashsum(self,):\n self.assertTrue(check_hashsum(self.positive))\n self.assertFalse(check_hashsum(self.negative))\n\n def test_normalize_date(self,):\n date = self.positive[\"date\"]\n normalize_date(self.positive)\n self.assertEquals(\n self.positive[\"date\"],\n datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%f'))\n with self.assertRaises(BadRequest):\n normalize_date(self.negative)\n","sub_path":"datarobot/tests/test_datarobot.py","file_name":"test_datarobot.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"310252189","text":"import copy\ndef main():\n\tprint(\"Enter Dictionary keys list Elements\")\n\tx=[int(a) for a in input().split()]\n\tx=dict.fromkeys(x)\n\tprint(\"x: \",x)\n\tprint(\"Enter Values to be added\")\n\ty=[int(a) for a in input().split()]\n\tprint(\"y: \",y)\n\tz= copy.deepcopy(x)\n\tz=from_keys(z,y)\n\tprint(z)\n\ti=4\n\twhile True:\n\t\ti=input(\"\\n 1.update\\n2.append\\n3.delete\\n4.search\\n5.display all\\nEnter your choice \\t:\")\n\t\tif i in '1':\n\t\t\tupdate(z)\n\t\telif i in '2':\n\t\t\tappendz(z)\n\t\telif i in '3':\n\t\t\tdelete(z)\n\t\telif i in '4':\n\t\t\tsearch(z)\n\t\telif i in '5':\n\t\t\tdisplay(z)\n\t\telse:\n\t\t\tbreak\n\t\ndef update(z):\n\tx=eval(input(\"Enter key:\\t\"))\n\ty=eval(input(\"Enter value:\\t\"))\n\tz[x]=y\n\tprint(z)\n\treturn\n\t\ndef appendz(z):\n\tx=eval(input(\"Enter key:\\t\"))\n\ty=eval(input(\"Enter value:\\t\"))\n\tif x in z:\n\t\tif type(z[x])==int :\n\t\t\tt=[z[x]]\n\t\t\tt.append(y)\n\t\t\tz[x]=t\n\t\telse:\n\t\t\tt=[]\n\t\t\tt=z[x]\n\t\t\tt.append(y)\n\t\t\tz[x]=t\n\t\tprint(z)\n\treturn\n\t\ndef delete(z):\n\tx=eval(input(\"Enter key:\\t\"))\n\ty=eval(input(\"Enter value:\\t\"))\n\tif (x in z ):\n\t\tif type(z[x]) == list and y in z[x] and len(z[x])>1:\n\t\t\tz[x].remove(y)\n\t\t\tprint(\"in\",z[x])\n\t\tif type(z[x])==list and len(z[x])==1:\n\t\t\tt=z[x]\n\t\t\tz[x]=t[0]\n\t\telse:\n\t\t\tz.pop(x)\n\t\tprint(z)\n\telse:\n\t\tprint(\"Element not found\")\n\treturn\n\t\ndef search(z):\n\tx=eval(input(\"Enter key:\\t\"))\n\ty=eval(input(\"Enter value:\\t\"))\n\tif (x in z )and(z[x]==y):\n\t\tprint(\"Element found\")\n\telse:\n\t\tprint(\"not found\")\n\treturn\n\t\ndef display(z):\n\tfor i in z:\n\t\tif type(z[i])==list:\n\t\t\tfor x in z[i]:\n\t\t\t\tprint(i,\":\",x)\n\t\telse:\n\t\t\tprint(i,\":\",z[i])\n\treturn\n\t\ndef from_keys(x,y):\n\tif len(y)==1:\n\t\tfor i in x:\n\t\t\tx[i]=y[0]\n\telse:\n\t\tt=len(y)\n\t\tj=0\n\t\tfor i in x:\n\t\t\tx[i]=y[j]\n\t\t\tj+=1\n\t\t\tif(j==t):\n\t\t\t\tbreak\n\treturn x\n\t\nif __name__=='__main__':\n\tmain()","sub_path":"1.Class/Language_Python-master/Language_Python-master/LC15_1_DictOperationsMenuDriven.py","file_name":"LC15_1_DictOperationsMenuDriven.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"462635067","text":"def _print_item(item, full_report):\n result = item.result_data\n result_type = item.result_type\n if result_type in ['normal', 'exception']:\n result_type = result[1][0]\n ret_val = [\n 'job ID {}:{}:{}'.format(\n item.work_id,\n result_type,\n item.module_name),\n 'command: {}'.format(\n ' '.join(item.command)\n if item.command is not None else ''),\n ]\n if result_type == 'Outcome.KILLED' and not full_report:\n ret_val = []\n elif item.result_type == 'timeout':\n if full_report:\n ret_val.append(\"timeout: {:.3f} sec\".format(result))\n else:\n ret_val = []\n elif item.result_type in ['normal', 'exception']:\n ret_val += result[1][1]\n\n # for presentation purposes only\n if ret_val:\n ret_val.append('')\n\n return ret_val\n\n\ndef _get_kills(db):\n def _keep(w):\n if w.result_type == 'timeout':\n return True\n elif w.result_type == 'normal':\n if w.result_data[1][0] == 'Outcome.KILLED':\n return True\n return False\n\n return list(filter(_keep, db.work_items))\n\n\ndef _base_stats(work_db):\n total_jobs = sum(1 for _ in work_db.work_items)\n pending_jobs = sum(1 for _ in work_db.pending_work)\n completed_jobs = total_jobs - pending_jobs\n kills = _get_kills(work_db)\n return (total_jobs, pending_jobs, completed_jobs, kills)\n\n\ndef create_report(work_db, show_pending, full_report=False):\n for item in work_db.work_items:\n if (item.result_type is not None) or show_pending:\n yield from _print_item(item, full_report)\n\n total_jobs, _, completed_jobs, kills = _base_stats(work_db)\n yield 'total jobs: {}'.format(total_jobs)\n\n if completed_jobs > 0:\n yield 'complete: {} ({:.2f}%)'.format(\n completed_jobs, completed_jobs / total_jobs * 100)\n yield 'survival rate: {:.2f}%'.format(\n (1 - len(kills) / completed_jobs) * 100)\n else:\n yield 'no jobs completed'\n\n\ndef survival_rate(work_db):\n _, _, completed_jobs, kills = _base_stats(work_db)\n\n if not completed_jobs:\n return 0\n\n return (1 - len(kills) / completed_jobs) * 100\n","sub_path":"cosmic_ray/commands/report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"542144714","text":"'''\nCreated on Nov 06, 2012\n\n@author: Jose Antonio Sal y Rosas Celi\n@contact: arturo.jasyrc@gmail.com\n'''\n\nfrom xml.dom import minidom\n\n\nclass xmlFileAgregar(object):\n\n experimento = \"\"\n doc = None\n tipoDatos = 0\n details = False\n \n __scriptName = \"xmlFileAgregar.py\"\n\n # Constructor method\n def __init__(self):\n self.doc = minidom.Document()\n\n # Save all the content\n def organizaXML(self, parametros, codigos, tipo_operacion, periodo_experimento, resumen_operacion):\n # Llama a la funcion que agrega la cabecera al documento XML\n nodo_cabecera = self.colocaCabecera(codigos[\"operacion\"], codigos[\"cod_operacion\"], tipo_operacion)\n # Llama a la funcion que agrega el elemento parametros al documento XML\n nodo_cuerpo = self.colocaNodoParametros(nodo_cabecera, parametros)\n # Llama a la funcion que agrega el elemento resultado al documento XML\n nodo_cuerpo = self.colocaContenido(nodo_cuerpo, codigos, periodo_experimento, resumen_operacion)\n \n self.doc.appendChild(nodo_cuerpo)\n \n return self.doc\n \n \n # Agrega la cabecera al documento XML\n def colocaCabecera(self, idoperacion, cod_operacion, tipo_operacion):\n # Nombre del nodo raiz del archivo XML\n nodo = self.doc.createElement(\"operacion\")\n # Agrega los atributos necesarios al archivo:\n # tipo_operacion: Nombre de la operacion\n nodo.setAttribute(\"tipo_operacion\", tipo_operacion)\n # codigo: valor que se genera al realizar una operacion\n nodo.setAttribute(\"codigo\", str(cod_operacion))\n # id: valor unico de la operacion\n nodo.setAttribute(\"id\", str(idoperacion))\n \n return nodo\n \n \n # Agrega el elemento parametros al documento XML\n def colocaNodoParametros(self, nodo_cabecera, parametros):\n # Nombre del nodo del elemento\n nodo = self.doc.createElement(\"parametros\")\n \n # experimento: Nombre del experimento \n nodo.setAttribute(\"instrumento\", str(parametros[\"instrumento\"]))\n # experimento: Nombre del experimento \n nodo.setAttribute(\"experimento\", str(parametros[\"experimento\"]))\n # tipo de datos: Agrega el tipo de datos de la operacion\n nodo.setAttribute(\"tipodatos\", str(parametros[\"tipodatos\"]))\n \n nodo_cabecera.appendChild(nodo)\n \n return nodo_cabecera\n \n \n # Agrega el elemento resultado al documento XML\n def colocaContenido(self, nodo_cabecera, codigos, periodo_experimento, resumen_operacion):\n \n num_resultado = 0\n \n # Creacion del nodo resultado\n nodo = self.doc.createElement(\"resultado\")\n \n # Creacion del nodo instrumento\n nodo_instrumento = self.doc.createElement(\"instrumento\")\n # Creacion del atributo codigo de la etiqueta instrumento\n nodo_instrumento.setAttribute(\"codigo\", str(codigos[\"instrumento\"]))\n \n nodo_experimento = self.doc.createElement(\"experimento\")\n nodo_experimento.setAttribute(\"codigo\", str(codigos[\"experimento\"]))\n nodo_experimento.setAttribute(\"num_subexperimentos\", str(len(resumen_operacion)))\n nodo_experimento.setAttribute(\"periodo\", str(periodo_experimento))\n \n nodo_subexperimentos = self.doc.createElement(\"subexperimentos\")\n \n for elemento in resumen_operacion:\n \n nodo_subexperimento = self.doc.createElement(\"subexperimento\")\n nodo_subexperimento.setAttribute(\"nombre\", str(elemento[\"subexperimento\"]))\n nodo_subexperimento.setAttribute(\"codigo\", str(elemento[\"codigo\"]))\n \n resumen_periodo = elemento[\"resumen_periodo\"]\n nodo_subexperimento.setAttribute(\"periodo\", str(resumen_periodo[\"periodo\"]))\n \n resumen_datos = resumen_periodo[\"resumen_datos\"]\n \n resumen_fechas = resumen_datos[\"resumen_fechas\"]\n # Verifica la existencia de archivos de configuracion\n if resumen_datos[\"conf\"] != 0:\n # Obtiene el tipo de datos de configuracion\n type_conf = resumen_datos[\"conf\"]\n # Obtiene el contenido de los datos de la configuracion\n content_conf = resumen_datos[\"content_conf\"]\n # Llama a la funcion para adicionar los datos de la configuracion\n conf_node = self.setAdditionalDataNode(\"conf\", type_conf, content_conf)\n # Agrega el nodo de configuracion a la cabecera principal\n nodo_cabecera.appendChild(conf_node)\n \n # Verifica la existencia de los documentos\n if resumen_datos[\"docs\"] != 0:\n # Obtiene los archivos de los documentos\n type_docs = resumen_datos[\"docs\"]\n # Obtiene el contenido de los datos de los documentos\n content_docs = resumen_datos[\"content_docs\"]\n # Llama a la funcion para adicionar los documentos\n docs_node = self.setAdditionalDataNode(\"docs\", type_docs, content_docs)\n # Agrega el nodo de documentos a la cabecera principal\n nodo_cabecera.appendChild(docs_node)\n \n for fecha in resumen_fechas:\n \n resumen_archivos = fecha[\"resumen_archivos\"]\n \n nodo_fecha = self.doc.createElement(\"fecha\")\n nodo_fecha.setAttribute(\"carpeta\", str(fecha[\"carpeta\"]))\n nodo_fecha.setAttribute(\"standar\", str(fecha[\"standar\"]))\n \n lista_encontrados = resumen_archivos[\"encontrados\"]\n \n \n nodo_fecha.setAttribute(\"total_archivos\", str(len(lista_encontrados)))\n \n for encontrado in lista_encontrados:\n nodo_archivo = self.doc.createElement(\"archivo\")\n nodo_txtArchivo = self.doc.createTextNode(str(encontrado[\"archivo\"]))\n nodo_archivo.setAttribute(\"tamanio\", str(encontrado[\"tamanio\"]))\n nodo_archivo.appendChild(nodo_txtArchivo)\n \n nodo_fecha.appendChild(nodo_archivo)\n \n nodo_subexperimento.appendChild(nodo_fecha)\n \n num_resultado += len(lista_encontrados)\n \n nodo_subexperimentos.appendChild(nodo_subexperimento)\n \n nodo_experimento.appendChild(nodo_subexperimentos)\n \n nodo_instrumento.appendChild(nodo_experimento)\n \n nodo.appendChild(nodo_instrumento)\n \n # num_result: Numero de experimentos encontrados en la busqueda\n nodo_cabecera.setAttribute(\"num_result\", str(num_resultado))\n \n nodo_cabecera.appendChild(nodo)\n \n return nodo_cabecera\n \n \n # Agrega un nodo adicional de datos\n def setAdditionalDataNode(self, typeofnode, typeofcontent, content):\n # Crea el elemento\n add_node = self.doc.createElement(typeofnode)\n add_node.setAttribute(\"type\", str(typeofcontent))\n # Verifica el tipo de contenido\n if typeofcontent == \"directories\":\n pass\n else:\n for element in content:\n file_node = self.doc.createElement(\"file\")\n file_node.setAttribute(\"period\", \"*\")\n contentfile_node = self.doc.createTextNode(str(element))\n \n file_node.appendChild(contentfile_node)\n \n add_node.appendChild(file_node)\n \n return add_node\n \n \n ","sub_path":"client_dataws/lib/xml/xmlFileAgregar.py","file_name":"xmlFileAgregar.py","file_ext":"py","file_size_in_byte":7740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"90406236","text":"#! /usr/bin/env python\n\"\"\"\nReads Darknet config and weights and creates Keras model with TF backend.\n\n\"\"\"\n\n\nimport configparser\nimport argparse\nimport configparser\nimport io\nimport os\nfrom collections import defaultdict\nimport tensorflow as tf\nimport tensorflow.keras.layers as KLayer\nfrom tensorflow.python.keras.optimizers import Adam, SGD\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras.layers import (Conv2D, Input, ZeroPadding2D, Add,\n UpSampling2D, MaxPooling2D, Concatenate)\nfrom tensorflow.python.keras.layers.advanced_activations import LeakyReLU\nfrom tensorflow.python.keras.layers.normalization import BatchNormalization\nfrom tensorflow.python.keras.models import Model\nfrom tensorflow.python.keras.regularizers import l2\nfrom tensorflow_model_optimization.python.core.sparsity import keras as sparsity\nfrom tensorflow.python.keras.callbacks import TensorBoard, ModelCheckpoint, ReduceLROnPlateau, EarlyStopping\nimport tensorflow_model_optimization as tfmot\nfrom tensorflow_model_optimization.python.core.sparsity.keras import prune\nfrom train import get_anchors,get_classes,data_generator_wrapper\nimport numpy as np\nparser = argparse.ArgumentParser(description='Darknet To Keras Converter.')\nparser.add_argument('config_path', help='Path to Darknet cfg file.')\nparser.add_argument('weights_path', help='Path to Darknet weights file.')\nparser.add_argument('output_path', help='Path to output Keras model file.')\nparser.add_argument(\n '-p',\n '--plot_model',\n help='Plot generated Keras model and save as image.',\n action='store_true')\nparser.add_argument(\n '-w',\n '--weights_only',\n help='Save as Keras weights file instead of model file.',\n action='store_true')\n\ndef unique_config_sections(config_file):\n \"\"\"Convert all config sections to have unique names.\n\n Adds unique suffixes to config sections for compability with configparser.\n \"\"\"\n section_counters = defaultdict(int)\n output_stream = io.StringIO()\n with open(config_file) as fin:\n for line in fin:\n if line.startswith('['):\n section = line.strip().strip('[]')\n _section = section + '_' + str(section_counters[section])\n section_counters[section] += 1\n line = line.replace(section, _section)\n output_stream.write(line)\n output_stream.seek(0)\n return output_stream\n\n# %%\ndef make_model(model_file,\n weights_file,\n anchor_file,\n end_step,\n initial_sparsity,\n end_sparsity,\n frequency,\n **kwargs):\n annotation_path = 'model_data/combined1.txt'\n log_dir = 'logs/000/'\n classes_path = 'model_data/classes.txt'\n anchors_path = 'model_data/yolo_anchors.txt'\n class_names = get_classes(classes_path)\n num_classes = len(class_names)\n anchors = np.load(anchor_file,allow_pickle=True)\n model_path = 'model_data/'\n init_model= model_path + '/pelee3'\n new_pruned_keras_file = model_path + 'pruned_' + init_model\n epochs = 100\n batch_size = 16\n init_epoch = 50\n input_shape = (384,288) # multiple of 32, hw\n log_dir = 'logs/000/'\n config_path = model_file\n weights_path = weights_file\n output_path = model_file + '.tf'\n output_root = os.path.splitext(output_path)[0]\n val_split = 0.1\n with open(annotation_path) as f:\n lines = f.readlines()\n np.random.seed(10101)\n np.random.shuffle(lines)\n np.random.seed(None)\n num_val = int(len(lines)*val_split)\n num_train = len(lines) - num_val\n # Load weights and config.\n print('Loading weights.')\n weights_file = open(weights_path, 'rb')\n major, minor, revision = np.ndarray(\n shape=(3, ), dtype='int32', buffer=weights_file.read(12))\n if (major*10+minor)>=2 and major<1000 and minor<1000:\n seen = np.ndarray(shape=(1,), dtype='int64', buffer=weights_file.read(8))\n else:\n seen = np.ndarray(shape=(1,), dtype='int32', buffer=weights_file.read(4))\n print('Weights Header: ', major, minor, revision, seen)\n\n print('Parsing Darknet config.')\n unique_config_file = unique_config_sections(config_path)\n cfg_parser = configparser.ConfigParser()\n cfg_parser.read_file(unique_config_file)\n first_layer = True\n print('Creating Keras model.')\n all_layers = []\n weight_decay = float(cfg_parser['net_0']['decay']\n ) if 'net_0' in cfg_parser.sections() else 5e-4\n count = 0\n out_index = []\n pruning_params = {\n 'pruning_schedule':tfmot.sparsity.keras.PolynomialDecay(initial_sparsity = initial_sparsity,\n final_sparsity = end_sparsity,\n begin_step = 0,\n end_step = end_step,\n frequency = frequency)\n }\n for section in cfg_parser.sections():\n print('Parsing section {}'.format(section))\n if section.startswith('convolutional'):\n filters = int(cfg_parser[section]['filters'])\n size = int(cfg_parser[section]['size'])\n stride = int(cfg_parser[section]['stride'])\n pad = int(cfg_parser[section]['pad'])\n activation = cfg_parser[section]['activation']\n batch_normalize = 'batch_normalize' in cfg_parser[section]\n\n padding = 'same' if pad == 1 and stride == 1 else 'valid'\n\n # Setting weights.\n # Darknet serializes convolutional weights as:\n # [bias/beta, [gamma, mean, variance], conv_weights]\n prev_layer_shape = K.int_shape(prev_layer)\n\n weights_shape = (size, size, prev_layer_shape[-1], filters)\n darknet_w_shape = (filters, weights_shape[2], size, size)\n weights_size = np.product(weights_shape)\n\n print('conv2d', 'bn'\n if batch_normalize else ' ', activation, weights_shape)\n\n conv_bias = np.ndarray(\n shape=(filters, ),\n dtype='float32',\n buffer=weights_file.read(filters * 4))\n count += filters\n\n if batch_normalize:\n bn_weights = np.ndarray(\n shape=(3, filters),\n dtype='float32',\n buffer=weights_file.read(filters * 12))\n count += 3 * filters\n\n bn_weight_list = [\n bn_weights[0], # scale gamma\n conv_bias, # shift beta\n bn_weights[1], # running mean\n bn_weights[2] # running var\n ]\n\n conv_weights = np.ndarray(\n shape=darknet_w_shape,\n dtype='float32',\n buffer=weights_file.read(weights_size * 4))\n count += weights_size\n\n # DarkNet conv_weights are serialized Caffe-style:\n # (out_dim, in_dim, height, width)\n # We would like to set these to Tensorflow order:\n # (height, width, in_dim, out_dim)\n conv_weights = np.transpose(conv_weights, [2, 3, 1, 0])\n conv_weights = [conv_weights] if batch_normalize else [\n conv_weights, conv_bias\n ]\n\n # Handle activation.\n act_fn = None\n if activation != 'linear':\n pass # Add advanced activation later.\n elif activation != 'linear':\n raise ValueError(\n 'Unknown activation function `{}` in section {}'.format(\n activation, section))\n\n # Create Conv2D layer\n if stride>1:\n # Darknet uses left and top padding instead of 'same' mode\n prev_layer = ZeroPadding2D(((1,0),(1,0)))(prev_layer)\n if(first_layer):\n conv_layer = Conv2D(\n filters, (size, size),\n strides=(stride, stride),\n kernel_regularizer=l2(weight_decay),\n use_bias=not batch_normalize,\n weights=conv_weights,\n activation=act_fn,\n padding=padding)(prev_layer)\n else:\n conv_layer = prune.prune_low_magnitude(Conv2D(\n filters, (size, size),\n strides=(stride, stride),\n kernel_regularizer=l2(weight_decay),\n use_bias=not batch_normalize,\n weights=conv_weights,\n activation=act_fn,\n padding=padding),\n **pruning_params)(prev_layer)\n if batch_normalize:\n conv_layer = BatchNormalization(\n weights=bn_weight_list)(conv_layer)\n prev_layer = conv_layer\n first_layer=False\n if activation == 'linear':\n all_layers.append(prev_layer)\n elif activation == 'leaky':\n act_layer = LeakyReLU(alpha=0.1)(prev_layer)\n prev_layer = act_layer\n all_layers.append(act_layer)\n elif activation == 'swish':\n act_layer = sigmoid(prev_layer)\n prev_layer = act_layer\n all_layers.append(act_layer)\n\n elif section.startswith('route'):\n ids = [int(i) for i in cfg_parser[section]['layers'].split(',')]\n layers = [all_layers[i] for i in ids]\n if len(layers) > 1:\n print('Concatenating route layers:', layers)\n concatenate_layer = Concatenate()(layers)\n all_layers.append(concatenate_layer)\n prev_layer = concatenate_layer\n else:\n skip_layer = layers[0] # only one layer to route\n all_layers.append(skip_layer)\n prev_layer = skip_layer\n\t\t\t\n elif section.startswith('maxpool'):\n size = int(cfg_parser[section]['size'])\n stride = int(cfg_parser[section]['stride'])\n all_layers.append(\n MaxPooling2D(\n pool_size=(size, size),\n strides=(stride, stride),\n padding='same')(prev_layer))\n prev_layer = all_layers[-1]\n\n elif section.startswith('shortcut'):\n index = int(cfg_parser[section]['from'])\n activation = cfg_parser[section]['activation']\n all_layers.append(Add()([all_layers[index], prev_layer]))\n prev_layer = all_layers[-1]\n all_layers.append(LeakyReLU(alpha=0.1)(prev_layer))\n prev_layer = all_layers[-1]\n\n elif section.startswith('upsample'):\n stride = int(cfg_parser[section]['stride'])\n assert stride == 2, 'Only stride=2 supported.'\n all_layers.append(UpSampling2D(stride)(prev_layer))\n prev_layer = all_layers[-1]\n\n elif section.startswith('yolo'):\n out_index.append(len(all_layers)-1)\n all_layers.append(None)\n prev_layer = all_layers[-1]\n\n elif section.startswith('net'):\n height = int(cfg_parser[section]['height'])\n width = int(cfg_parser[section]['width'])\n input_layer = Input(shape=(height, width, 3))\n prev_layer = input_layer\n output_size = (width, height)\n\n else:\n raise ValueError(\n 'Unsupported section header type: {}'.format(section))\n\n # Create and save model.\n if len(out_index)==0: out_index.append(len(all_layers)-1)\n num_anchors = len(anchors[0])\n num_layers = len(out_index)\n if(num_layers>0):\n shape = K.int_shape(all_layers[out_index[0]])\n y1_reshape = KLayer.Reshape((shape[1],shape[2], num_anchors, 5 + num_classes), name='l1')(all_layers[out_index[0]])\n if(num_layers>1):\n shape = K.int_shape(all_layers[out_index[1]])\n y2_reshape = KLayer.Reshape((shape[1],shape[2], num_anchors, 5 + num_classes), name='l2')(all_layers[out_index[1]])\n yolo_model = Model(inputs=input_layer, outputs=[all_layers[i] for i in out_index])\n if(num_layers > 1):\n yolo_model_wrapper = Model(input_layer, [y1_reshape, y2_reshape])\n else:\n yolo_model_wrapper = Model(input_layer, [y1_reshape])\n print(yolo_model.summary())\n return yolo_model,yolo_model_wrapper,output_size\n\n if False:\n if args.weights_only:\n model.save_weights('{}'.format(output_path))\n print('Saved Keras weights to {}'.format(output_path))\n else:\n model.save('{}'.format(output_path),save_format='tf')\n print('Saved Keras model to {}'.format(output_path))\n\n # Check to see if all weights have been read.\n remaining_weights = len(weights_file.read()) / 4\n weights_file.close()\n print('Read {} of {} from Darknet weights.'.format(count, count +\n remaining_weights))\n if remaining_weights > 0:\n print('Warning: {} unused weights'.format(remaining_weights))\n\n if True:\n model = create_model(model, anchors, num_classes, input_shape, input_layer, layers, out_index)\n yolo_model_wrapper.compile(\n loss=tf.keras.losses.categorical_crossentropy,\n optimizer='adam',\n metrics=['accuracy'],\n callbacks = [\n sparsity.keras.pruning_callbacks.UpdatePruningStep(),\n sparsity.keras.pruning_callbacks.PruningSummaries(log_dir=log_dir, profile_batch=0)\n ]\n )\n for i in range(len(model.layers)):\n model.layers[i].trainable = True\n model.compile(optimizer=Adam(lr=1e-3), loss={'yolo_loss': lambda y_true, y_pred: y_pred}) # recompile to apply the change\n print('Unfreeze all of the layers.')\n print(model.summary())\n\n batch_size = 16 # note that more GPU memory is required after unfreezing the body\n print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))\n model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes),\n steps_per_epoch=max(1, num_train//batch_size),\n validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes),\n validation_steps=max(1, num_val//batch_size),\n epochs=5,\n initial_epoch=0)\n\n\n #m2train.m2train(args,model)\n #score = model.evaluate(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes),\n # class_names, verbose=0)\n #print('Test loss:', score[0])\n #print('Test accuracy:', score[1])\n final_model=model\n final_model = sparsity.keras.prune.strip_pruning(model)\n final_model.summary()\n print('Saving pruned model to: ', new_pruned_keras_file)\n final_model.save('{}'.format(output_path),save_format='tf')\n tflite_model_file = model_path + \"sparse.tf\"\n converter = tf.lite.TFLiteConverter.from_keras_model(final_model)\n converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]\n tflite_model = converter.convert()\n with open(tflite_model_file, 'wb') as f:\n f.write(tflite_model)\n\nif __name__ == '__main__':\n _main(parser.parse_args())","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":15530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"571722290","text":"# The purpose of these functions is to read/write a convenient input file\n# Since we're using an input format that involves lon/lat/depth/mag, we have to convert\n# We will use Wells and Coppersmith 1994, in the same way that Coulomb does. \n# We have to do a few other conversions too. \n# This input file assumes a fixed rake specified initially in the configure file, same as the .inp file format\n\nimport numpy as np\nimport matplotlib.pyplot as plt \nimport haversine\nimport conversion_math\nimport coulomb_collections\nimport wells_and_coppersmith\nimport sys\n\n\ndef read_intxt(input_file):\n\t\n\tstrike_src=[]; dipangle_src=[]; rake_src=[]; magnitude_src=[]; faulting_type_src=[]; fault_center_lon_src=[]; fault_center_lat_src=[]; fault_dep_src=[];\n\tstrike_rec=[]; dipangle_rec=[]; rake_rec=[]; length_rec=[]; width_rec=[]; updip_corner_lon_rec=[]; updip_corner_lat_rec=[]; updip_corner_dep_rec=[];\n\t\n\tifile=open(input_file,'r');\n\tfor line in ifile:\n\t\ttemp=line.split();\n\t\tif len(temp)==0:\n\t\t\tcontinue;\n\t\tif temp[0]=='S:':\n\t\t\t[strike,rake,dip,magnitude,faulting_type,fault_center_lon,fault_center_lat,fault_center_depth]=read_source_line(line);\n\t\t\tstrike_src.append(strike);\n\t\t\trake_src.append(rake);\n\t\t\tdipangle_src.append(dip);\n\t\t\tmagnitude_src.append(magnitude);\n\t\t\tfaulting_type_src.append(faulting_type);\n\t\t\tfault_center_lon_src.append(fault_center_lon);\n\t\t\tfault_center_lat_src.append(fault_center_lat);\n\t\t\tfault_dep_src.append(fault_center_depth);\n\t\telif temp[0]=='R:':\n\t\t\t[strike,rake,dip,length,width,updip_corner_lon,updip_corner_lat,updip_corner_dep]=read_receiver_line(line);\n\t\t\tstrike_rec.append(strike);\n\t\t\trake_rec.append(rake);\n\t\t\tdipangle_rec.append(dip);\n\t\t\tlength_rec.append(length);\n\t\t\twidth_rec.append(width);\n\t\t\tupdip_corner_lon_rec.append(updip_corner_lon);\n\t\t\tupdip_corner_lat_rec.append(updip_corner_lat);\n\t\t\tupdip_corner_dep_rec.append(updip_corner_dep);\n\t\telif temp[0]=='G:':\n\t\t\t[PR1,FRIC,minlon,maxlon,zerolon,minlat,maxlat,zerolat]=read_general_line(line);\n\t\telse:\n\t\t\tcontinue;\n\tifile.close();\n\n\t# The main computing functions. \n\t[start_gridx, finish_gridx, start_gridy, finish_gridy, xinc, yinc] = compute_grid_parameters(minlon, maxlon, zerolon, minlat, maxlat, zerolat);\n\t[xstart_src, xfinish_src, ystart_src, yfinish_src, Kode_src, rtlat_src, reverse_src, top_src, bottom_src, comment_src] = compute_params_for_source(strike_src, dipangle_src, rake_src, magnitude_src, faulting_type_src, fault_center_lon_src, fault_center_lat_src, fault_dep_src, zerolon, zerolat);\n\t[xstart_rec, xfinish_rec, ystart_rec, yfinish_rec, Kode_rec, rtlat_rec, reverse_rec, top_rec, bottom_rec, comment_rec] = compute_params_for_receiver(strike_rec, dipangle_rec, rake_rec, length_rec, width_rec, updip_corner_lon_rec, updip_corner_lat_rec, updip_corner_dep_rec, zerolon, zerolat);\n\n\treceivers=coulomb_collections.Faults_object(xstart=xstart_rec, xfinish=xfinish_rec, ystart=ystart_rec, yfinish=yfinish_rec, Kode=Kode_rec, rtlat=rtlat_rec, reverse=reverse_rec, strike=strike_rec, dipangle=dipangle_rec, rake=rake_rec, top=top_rec, bottom=bottom_rec, comment=comment_rec);\n\tsources=coulomb_collections.Faults_object(xstart=xstart_src, xfinish=xfinish_src, ystart=ystart_src, yfinish=yfinish_src, Kode=Kode_src, rtlat=rtlat_src, reverse=reverse_src, strike=strike_src, dipangle=dipangle_src, rake=rake_src, top=top_src, bottom=bottom_src, comment=comment_src);\n\n\tinput_obj=coulomb_collections.Input_object(PR1=PR1,FRIC=FRIC, depth=0, start_gridx=start_gridx, finish_gridx=finish_gridx, start_gridy=start_gridy, finish_gridy=finish_gridy, \n\t\txinc=xinc, yinc=yinc, minlon=minlon, maxlon=maxlon, zerolon=zerolon, minlat=minlat, maxlat=maxlat, zerolat=zerolat, receiver_object=receivers, source_object=sources);\n\n\treturn input_obj;\n\n\n\t# plt.figure();\n\t# plt.plot([xstart,xfinish],[ystart,yfinish],'b');\n\t# plt.plot(xcenter,ycenter,'.r');\n\t# plt.xlim([-100,100]);\n\t# plt.ylim([-100,100]);\n\t# plt.savefig('test.eps');\n\n\n\n\ndef read_source_line(line):\n\tstrike=float(line.split()[1]);\n\trake=float(line.split()[2]);\n\tdip=float(line.split()[3]);\n\tmagnitude=float(line.split()[4]);\n\tfaulting_type=line.split()[5];\n\tfault_center_lon=float(line.split()[6]);\n\tfault_center_lat=float(line.split()[7]);\n\tfault_center_dep=float(line.split()[8]);\n\treturn [strike,rake,dip,magnitude,faulting_type,fault_center_lon,fault_center_lat,fault_center_dep];\ndef read_receiver_line(line):\n\tstrike=float(line.split()[1]);\n\trake=float(line.split()[2]);\n\tdip=float(line.split()[3]);\n\tlength=float(line.split()[4]);\n\twidth=float(line.split()[5]);\n\tupdip_corner_lon=float(line.split()[6]);\n\tupdip_corner_lat=float(line.split()[7]);\n\tupdip_corner_dep=float(line.split()[8]);\t\n\treturn [strike,rake,dip,length,width,updip_corner_lon,updip_corner_lat,updip_corner_dep];\ndef read_general_line(line):\n\tPR1=float(line.split()[1]);\n\tFRIC=float(line.split()[2]);\n\tlon_min=float(line.split()[3]);\n\tlon_max=float(line.split()[4]);\n\tlon_zero=float(line.split()[5]);\n\tlat_min=float(line.split()[6]);\n\tlat_max=float(line.split()[7]);\n\tlat_zero=float(line.split()[8]);\n\treturn [PR1,FRIC,lon_min,lon_max,lon_zero,lat_min,lat_max,lat_zero];\n\n\n\n\n\ndef compute_grid_parameters(minlon, maxlon, zerolon, minlat, maxlat, zerolat):\n\tstart_gridx=0; start_gridy=0; finish_gridx=0; finish_gridy=0; xinc=0; yinc=0;\n\t# Compute the grid parameters that we'll be using, based on the size of the map. \n\t# Assuming 100 increments in both directions. \n\n\tdeltalon=(maxlon-minlon)*111.00*np.cos(np.deg2rad(zerolat)); # in km. \n\tdeltalat=(maxlat-minlat)*111.00; # in km. \n\tstart_gridx=-deltalon/2.0;\n\tfinish_gridx=deltalon/2.0;\n\tstart_gridy=-deltalat/2.0;\n\tfinish_gridy=deltalat/2.0;\n\txinc=deltalon/100.0;\n\tyinc=deltalat/100.0;\n\n\t# print(\"start_gridx: %f \" % start_gridx);\n\t# print(\"finish_gridx: %f \" % finish_gridx);\n\t# print(\"start_gridy: %f \" % start_gridy);\n\t# print(\"finish_gridy: %f \" % finish_gridy);\n\t# print(\"xinc: %f \" % xinc);\n\t# print(\"yinc: %f \" % yinc);\n\treturn [start_gridx, finish_gridx, start_gridy, finish_gridy, xinc, yinc];\n\n\ndef compute_params_for_source(strike, dip, rake, mag, eq_type, eqlon, eqlat, eqdep, zerolon, zerolat):\n\txstart=[]; xfinish=[]; ystart=[]; yfinish=[]; Kode=[]; rtlat=[]; reverse=[]; top=[]; bottom=[]; comment=[];\n\t# Useful when you have earthquake catalog information, and you want the source information. \n\t# The depth/eqlon/eqlat parameters refer to the center of the fault plane by assumption. \n\t# Takes lists of parameters. \n\tfor i in range(len(strike)):\n\t\t[xcenter,ycenter]=conversion_math.latlon2xy(eqlon[i],eqlat[i],zerolon,zerolat);\n\t\t# print(\"EQ location: %f %f \" % (eqlon[i],eqlat[i]) );\n\t\t# print(\"Ref location: %f %f \" % (zerolon, zerolat) );\n\t\t# print(\"Coordinates: %f %f \" % (x,y) );\n\t\tL=wells_and_coppersmith.RLD_from_M(mag[i],eq_type[i]); # rupture length\n\t\tW=wells_and_coppersmith.RW_from_M(mag[i],eq_type[i]); # rupture width\n\t\tslip = wells_and_coppersmith.rectangular_slip(L*1000,W*1000,mag[i]); # must input in meters\n\t\tprint(\"Fault slip: %f\" % slip);\n\t\t\n\t\t# xistart,yistart=conversion_math.add_vector_to_point(xcenter,ycenter,-L/2,strike[i]); # if the hypocenter is really the center of the rupture\n\t\txistart,yistart=conversion_math.add_vector_to_point(xcenter,ycenter,0,strike[i]); # if the hypocenter is on one side of the rupture\n\t\txifinish,yifinish=conversion_math.add_vector_to_point(xcenter,ycenter,L,strike[i]);\n\t\trtlati,reversei=conversion_math.get_rtlat_dip_slip(slip, rake[i]);\n\t\ttopi, bottomi=conversion_math.get_top_bottom(eqdep[i],W,dip[i]);\n\n\n\t\txstart.append(xistart);\n\t\tystart.append(yistart);\n\t\txfinish.append(xifinish);\n\t\tyfinish.append(yifinish);\n\t\tKode.append(100);\n\t\trtlat.append(rtlati);\n\t\treverse.append(reversei);\n\t\ttop.append(topi);\n\t\tbottom.append(bottomi);\n\t\tcomment.append('');\n\n\treturn [xstart, xfinish, ystart, yfinish, Kode, rtlat, reverse, top, bottom, comment];\n\n\ndef compute_params_for_receiver(strike, dip, rake, length, width, lon, lat, depth, zerolon, zerolat):\n\txstart=[]; xfinish=[]; ystart=[]; yfinish=[]; Kode=[]; rtlat=[]; reverse=[]; top=[]; bottom=[]; comment=[];\n\t# Useful when you have a receiver and you want to compute stresses on it. \n\t# The depth/lon/lat parameters refer to the updip fault corner where you're looking down the strike direction, and the dip is off to your right. \n\t# Takes lists of parameters. \n\tfor i in range(len(strike)):\n\n\t\t[xistart,yistart]=conversion_math.latlon2xy(lon[i],lat[i],zerolon,zerolat);\n\t\txifinish,yifinish=conversion_math.add_vector_to_point(xistart,yistart,length[i],strike[i]);\n\t\ttopi, bottomi=conversion_math.get_top_bottom_from_top(depth[i],width[i],dip[i]);\n\n\t\txstart.append(xistart);\n\t\tystart.append(yistart);\n\t\txfinish.append(xifinish);\n\t\tyfinish.append(yifinish);\n\t\tKode.append(100);\n\t\trtlat.append(0);\n\t\treverse.append(0);\n\t\ttop.append(topi);\n\t\tbottom.append(bottomi);\n\t\tcomment.append('');\n\n\treturn [xstart, xfinish, ystart, yfinish, Kode, rtlat, reverse, top, bottom, comment];\n\n\n\n\n\n\n\n\n","sub_path":"Code/io_intxt.py","file_name":"io_intxt.py","file_ext":"py","file_size_in_byte":8887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"265389637","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Hotfile-api\n# Copyright 2011 Yoshihiro Misawa\n# See LICENSE for details.\n\nfrom Hotfile.error import HotfileError\nfrom Hotfile.utils import Utils\nfrom BeautifulSoup import BeautifulSoup as BS\nimport re\n\n# プレコンパイル\npreDLLink = re.compile('(http|https):\\/\\/hotfile\\.com\\/dl\\/([a-zA-Z0-9]*)\\/([a-zA-Z0-9]*)\\/(.+)\\.html')\npreFolderLink = re.compile('(http|https):\\/\\/hotfile\\.com\\/list\\/([a-zA-Z0-9]*)\\/([a-zA-Z0-9]*)')\npreMyFilesLink = re.compile(r'^/myfiles.html\\?d\\=(\\d+)\\-(\\d+)-(\\d+)$')\npreURL = re.compile(r'(http://[A-Za-z0-9\\'~+\\-=_.,/%\\?!;:@#\\*&\\(\\)]+)')\npreFilename = re.compile(\"filenames\\[(\\d+)\\].\\=.\\'(.+)\\s\\'\\;\")\n\n\nclass Model(object):\n def __init__(self, api=None):\n self._api = api\n\n def __getstate__(self):\n pickle = dict(self.__dict__)\n try:\n del pickle['_api']\n except KeyError:\n pass\n return pickle\n\n @classmethod\n def parse(cls, api, content):\n raise NotImplementedError\n\nclass Raw(Model):\n @classmethod\n def parse(cls, api, content):\n return content\n\nclass QueryString(Model):\n @classmethod\n def parse(cls, api, content):\n dict = Utils.parse_query(content)\n qstr = cls(api)\n for k, v in dict.items():\n setattr(qstr, k, v)\n return qstr\n\nclass Fields(Model):\n @classmethod\n def parse(cls, api, content):\n fieldseparator_format = api.api.set_format['fieldseparator']\n lineseparator_format =api.api.set_format['lineseparator']\n fields_format = api.api.set_format['fields']\n lines = content.split(lineseparator_format)[:-1]\n fields = cls(api)\n files = []\n for line in lines:\n line_values = line.split(fieldseparator_format)\n i = 0\n file = {}\n for v in line_values:\n file[fields_format[i]] = v\n i += 1\n files.append(file)\n setattr(fields, 'fields', files)\n return fields\n\nclass Lf(Model):\n @classmethod\n def parse(cls, api, content):\n lf = cls(api)\n setattr(lf, 'lf', content.split('\\n')[:-1])\n return lf\n\nclass Commma(Model):\n @classmethod\n def parse(cls, api, content):\n return_keys = api.return_keys\n dic = dict(zip(return_keys,content.split(',')))\n commma = cls(api)\n setattr(commma, 'commma', dic)\n return commma\n\nclass MyFiles(Model):\n @classmethod\n def parse(cls, api, content):\n # id \"loginFormMenu\"が存在する場合はログインされていない。\n # class \"my_files\"内に存在。\n links = []\n files = cls(api)\n soup = BS(content)\n for l in soup.findAll('script'):\n m = preDLLink.search(l.text)\n if m:\n links.append(m.group())\n\n for s in soup.findAll('a'):\n if preMyFilesLink.match(s.get('href', None)):\n soup2 = BS(api.api._get_resouces(s.get('href', None)[1:], api.cookie))\n for l2 in soup2.findAll('script'):\n m2 = preDLLink.search(l2.text)\n if m2:\n links.append(m2.group())\n setattr(files, 'myfolders', links)\n return files\n\n \nclass MyFolders(Model):\n @classmethod\n def parse(cls, api, content):\n myfolders = cls(api)\n links = []\n soup = BS(content)\n dirs_path = {}\n for t in soup.findAll('tr',attrs={'id':'copyform'}):\n for s in t.findAll('option'):\n folder_id = s.get('value', None)\n dir_path = s.text\n dirs_path[folder_id] = dir_path\n if folder_id:\n if folder_id != 'None':\n web_path = 'myfolders.html?o=' + folder_id\n soup2 = BS(api.api._get_resouces(web_path, api.cookie))\n for l in soup2.findAll('script'):\n m = preFolderLink.search(l.text)\n if m:\n links.append(m.group())\n\n # リストの重複削除\n links = list(set(links))\n folders = []\n for link in links:\n folder = {}\n m2 = preFolderLink.search(link)\n tmp_id = m2.group(2)\n tmp_hash = m2.group(3)\n tmp_path = dirs_path[tmp_id][:-1]\n tmp_name = tmp_path.split('/')[-1]\n folder = {\n 'link' : link,\n 'folder_id' : tmp_id,\n 'folder_hash': tmp_hash,\n 'path' : tmp_path,\n 'folder_name' : tmp_name\n }\n folders.append(folder)\n\n setattr(myfolders, 'myfolders', folders)\n return myfolders\n\nclass MyFile(Model):\n @classmethod\n def parse(cls, api, content):\n link = cls(api)\n file_name = api.file_path.split('/')[-1]\n path = re.sub('/'+file_name, '', api.file_path)\n soup = BS(content)\n dirs_path = {}\n for t in soup.findAll('tr',attrs={'id':'copyform'}):\n for s in t.findAll('option'):\n folder_id = s.get('value', None)\n dir_path = s.text\n if dir_path != 'None':\n dirs_path[dir_path[:-1]] = folder_id\n if dirs_path:\n folder_id = dirs_path[path]\n web_path = 'myfolders.html?o=' + folder_id\n soup2 = BS(api.api._get_resouces(web_path, api.cookie))\n for l in soup2.findAll('script'):\n m = preDLLink.search(l.text)\n if m:\n if m.group(4) == file_name:\n dl_link = m.group()\n break\n\n setattr(link, 'link', dl_link)\n return link\n\n\n\n \n\n \n\nclass ModelFactory(object):\n raw = Raw\n qstr = QueryString\n fields = Fields\n lf = Lf\n comma = Commma\n myfiles = MyFiles\n myfolders = MyFolders\n myfile = MyFile","sub_path":"Hotfile/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"10124767","text":"# Stilin hep aynı olmalı.\n# Yukarıda a <1000 yazmışsın.\n# Aşağıda c < 4000000 yazmışsın.\n# < operatörünün etrafında boşluk bırakıp bırakmayacağına karar ver.\n\n# Stilin hep aynı olmalı demiştik.\n# Bunun için auto-format kullanmanı tavsiye ederim.\n# Metin editörüne sağ tıklayıp \"format document\"e bas, ya da Ctrl+Shift+I kısayolunu kullan. Dene gör nasıl oluyor.\n\n# ↓ FIBONACCI olacaktı\n#Even Fibanocci Number (#2)\na=1\nb=1\nc=a+b\nt=0\nwhile c < 4000000:\n if c%2 == 0:\n t+=c\n print(c)\n a=b\n b=c\n c=a+b\n \nprint(t)\n\n# Bu soru üzerinden sana iki kavram tanıtmak istiyorum.\n# 1- Recursion (özyineleme)\n# 2- Memoization: https://en.wikipedia.org/wiki/Memoization\n# Bunları oku. Fibonacci programını özyineleme ve memoization ile yazmaya çalış. Python'un kendi memoization araçlarını kullanma. Başaramayacağını düşünüyorum ama yine de yapmanı istiyorum; çünkü seninle beraber başına oturup bakmadan önce senin problemi anlamış olman gerekiyor. Bunun yolu da deneyip başaramamaktan geçiyor. Başarabilirsen zaten bakmamıza gerek yok.\n# Burada cevap var bu arada: https://www.python-course.eu/python3_memoization.php\n# Ama kopya çekmeden önce mutlaka kendin dene.\n\n\n# Bu arada dictionary nedir bilmiyorsan buna bak, lazım olacak:\nmy_dict = {\n (1,2): 'bir ve iki',\n (1,1): 'bir ve bir',\n (5,3): 'beş ve üç',\n}\nprint(my_dict[(1,2)])\nprint(my_dict[(1,1)])\nprint(my_dict[(5,3)])\nprint(my_dict.keys())\nprint((1,1) in my_dict.keys())\nprint((10,10) in my_dict.keys())\nif (1,1) in my_dict.keys():\n print('(1,1) varmış.')","sub_path":"soru002.py","file_name":"soru002.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"579362231","text":"# Leetcode 127 Word Ladder:\n# https://leetcode.com/problems/word-ladder/\n\nclass Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n if endWord not in wordList:\n return 0\n steps = {word: 0 for word in wordList}\n steps[beginWord] = 1\n queue = collections.deque([beginWord])\n \n while queue:\n word = queue.popleft()\n step = steps[word]\n for i in range(len(word)):\n left = word[:i]\n right = word[i+1:]\n for j in range(26):\n testword = left + chr(97+j) + right\n if testword == endWord:\n return step + 1\n if testword in steps and steps[testword] == 0:\n steps[testword] = step + 1\n queue.append(testword)\n \n return 0","sub_path":"Algorithm/HW03_DFS_BFS/leetcode127_Word_Ladder.py","file_name":"leetcode127_Word_Ladder.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"6323867","text":"from typing import Type, Union\n\nimport numpy as np\n\nfrom genrl.core import PrioritizedBuffer, ReplayBuffer\nfrom genrl.trainers import Trainer\nfrom genrl.utils import safe_mean\n\n\nclass OffPolicyTrainer(Trainer):\n \"\"\"Off Policy Trainer Class\n\n Trainer class for all the Off Policy Agents: DQN (all variants), DDPG, TD3 and SAC\n\n Attributes:\n agent (object): Agent algorithm object\n env (object): Environment\n buffer (object): Replay Buffer object\n max_ep_len (int): Maximum Episode length for training\n warmup_steps (int): Number of warmup steps. (random actions are taken to add randomness to training)\n start_update (int): Timesteps after which the agent networks should start updating\n update_interval (int): Timesteps between target network updates\n log_mode (:obj:`list` of str): List of different kinds of logging. Supported: [\"csv\", \"stdout\", \"tensorboard\"]\n log_key (str): Key plotted on x_axis. Supported: [\"timestep\", \"episode\"]\n log_interval (int): Timesteps between successive logging of parameters onto the console\n logdir (str): Directory where log files should be saved.\n epochs (int): Total number of epochs to train for\n max_timesteps (int): Maximum limit of timesteps to train for\n off_policy (bool): True if the agent is an off policy agent, False if it is on policy\n save_interval (int): Timesteps between successive saves of the agent's important hyperparameters\n save_model (str): Directory where the checkpoints of agent parameters should be saved\n run_num (int): A run number allotted to the save of parameters\n load_model (str): File to load saved parameter checkpoint from\n render (bool): True if environment is to be rendered during training, else False\n evaluate_episodes (int): Number of episodes to evaluate for\n seed (int): Set seed for reproducibility\n \"\"\"\n\n def __init__(\n self,\n *args,\n buffer: Union[Type[ReplayBuffer], Type[PrioritizedBuffer]] = None,\n max_ep_len: int = 1000,\n warmup_steps: int = 1000,\n start_update: int = 1000,\n update_interval: int = 50,\n **kwargs\n ):\n super(OffPolicyTrainer, self).__init__(*args, off_policy=True, **kwargs)\n\n self.max_ep_len = max_ep_len\n self.warmup_steps = warmup_steps\n self.update_interval = update_interval\n self.start_update = start_update\n self.network = self.agent.network\n\n if buffer is None:\n if self.agent.replay_buffer is None:\n raise Exception(\"Off Policy Training requires a Replay Buffer\")\n else:\n self.agent.replay_buffer = buffer\n self.buffer = self.agent.replay_buffer\n\n def train(self) -> None:\n \"\"\"Main training method\"\"\"\n if self.load_model is not None:\n self.load()\n\n state, episode_len, episode = (\n self.env.reset(),\n np.zeros(self.env.n_envs),\n np.zeros(self.env.n_envs),\n )\n total_steps = self.max_ep_len * self.epochs * self.env.n_envs\n\n if \"noise\" in self.agent.__dict__ and self.agent.noise is not None:\n self.agent.noise.reset()\n\n assert self.update_interval % self.env.n_envs == 0\n\n self.rewards = []\n\n for timestep in range(0, total_steps, self.env.n_envs):\n self.agent.update_params_before_select_action(timestep)\n\n if timestep < self.warmup_steps:\n action = np.array(self.env.sample())\n else:\n action = self.agent.select_action(state)\n\n next_state, reward, done, _ = self.env.step(action)\n\n if self.render:\n self.env.render()\n\n episode_len += 1\n\n done = [\n False if episode_len[i] == self.max_ep_len else done[i]\n for i, ep_len in enumerate(episode_len)\n ]\n\n self.buffer.push((state, action, reward, next_state, done))\n state = next_state.copy()\n\n if np.any(done) or np.any(episode_len == self.max_ep_len):\n if \"noise\" in self.agent.__dict__ and self.agent.noise is not None:\n self.agent.noise.reset()\n\n if sum(episode) % self.log_interval == 0:\n self.logger.write(\n {\n \"timestep\": timestep,\n \"Episode\": sum(episode),\n **self.agent.get_logging_params(),\n \"Episode Reward\": safe_mean(self.rewards),\n },\n self.log_key,\n )\n self.rewards = []\n\n for i, di in enumerate(done):\n if di:\n self.rewards.append(self.env.episode_reward[i])\n self.env.episode_reward[i] = 0\n episode_len[i] = 0\n episode[i] += 1\n\n if timestep >= self.start_update and timestep % self.update_interval == 0:\n self.agent.update_params(self.update_interval)\n\n if (\n timestep >= self.start_update\n and self.save_interval != 0\n and timestep % self.save_interval == 0\n ):\n self.save(timestep)\n\n if timestep >= self.max_timesteps:\n break\n\n self.env.close()\n self.logger.close()\n","sub_path":"genrl/trainers/offpolicy.py","file_name":"offpolicy.py","file_ext":"py","file_size_in_byte":5541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"389056616","text":"from dm_control import suite\r\nimport numpy as np\r\nfrom PIL import Image\r\nimport subprocess\r\n\r\n# Load one task:\r\nenv = suite.load(domain_name=\"humanoid\", task_name=\"run\")\r\n\r\n# Step through an episode and print out reward, discount and observation.\r\naction_spec = env.action_spec()\r\ntime_step = env.reset()\r\n\r\n# Keep time step count to be able to stop otherwise infinitely long running tasks\r\ntime_step_counter = 0\r\n\r\n# reset frames folder\r\nsubprocess.call(['rm', '-rf', 'frames'])\r\nsubprocess.call(['mkdir', '-p', 'frames'])\r\n\r\nwhile not time_step.last() and time_step_counter < 500:\r\n\taction = np.random.uniform(action_spec.minimum, action_spec.maximum, size = action_spec.shape)\r\n\ttime_step = env.step(action)\r\n\timage_data = env.physics.render(height = 480, width = 480, camera_id = \"back\")\r\n\timg = Image.fromarray(image_data, 'RGB')\r\n\timg.save(\"frames/frame-%.10d.png\" % time_step_counter)\r\n\ttime_step_counter += 1\r\n\tprint(time_step.reward, time_step.discount, time_step.observation)\r\n\r\n# convert frames to video\r\nsubprocess.call(['ffmpeg', '-framerate', '50', '-y', '-i', 'frames/frame-%010d.png', '-r', '30', '-pix_fmt', 'yuv420p', 'video_name.mp4'])\r\n","sub_path":"dm_control/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"393920144","text":"#!/usr/bin/env python3\n\nimport numpy as np\nimport cv2 as cv\nfrom matplotlib import pyplot as plt\n\ncap = cv.VideoCapture(0)\nif not cap.isOpened():\n\tprint(\"Cannot open camera\")\n\texit()\n\t\nthresholdValue = 127\nskinLowerBound = (87, 68, 71)\nskinUpperBound = (191, 119, 128)\n\nwhile True:\n\t# Capture frame by frame\n\tret, frame = cap.read()\n\t\n\t# if frame correctly read\n\tif not ret:\n\t\tprint(\"Cannot receive frame (stream end?) Exiting...\")\n\t\tbreak\n\n\tgray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)\n\tblur = cv.blur(gray, (3, 3))\n\tret, blur_thresh = cv.threshold(blur, 30, 255, cv.THRESH_BINARY)\n\tcontours, hierachy = cv.findContours(blur_thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)\n\n\tcontourImg = frame.copy()\n\n\tfor i in range(len(contours)):\n\t\tcv.drawContours(contourImg, [contours[i]], 0, (255, 0, 0), thickness=3)\n\n\tret,thresh1 = cv.threshold(frame, thresholdValue, 255, cv.THRESH_BINARY)\n\tthresh2 = cv.inRange(frame, skinLowerBound, skinUpperBound)\n\n\tedges = cv.Canny(frame, 100, 200)\n\n\t# Our operations on the frame come here\n\tcv.imshow(\"Video\", edges)\n\n\tkey = cv.waitKey(1)\n\tif key == ord(\"q\"):\n\t\tbreak\n\tif key == ord(\"+\"):\n\t\tthresholdValue += 1\n\tif key == ord(\"-\"):\n\t\tthresholdValue -= 1\n\n# When eveyrthing done, release the capture\ncap.release()\ncv.destroyAllWindows()","sub_path":"threshold-test.py","file_name":"threshold-test.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"281164889","text":"from __future__ import print_function\nfrom six.moves import input\n\nimport sys\nimport copy\nimport rospy\nimport moveit_commander\nimport moveit_msgs.msg\nimport geometry_msgs.msg\nfrom math import pi, tau, dist, fabs, cos\nfrom std_msgs.msg import String\nfrom moveit_commander.conversions import pose_to_list\nfrom trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint\n\nclass URplanner():\n\n def __init__(self) -> None:\n moveit_commander.roscpp_initialize(sys.argv)\n rospy.init_node(\"ur_planner\", anonymous=True)\n\n # Instantiate a `RobotCommander`_ object. Provides information such as the robot's\n # kinematic model and the robot's current joint states\n self.robot = moveit_commander.RobotCommander()\n\n # Instantiate a `PlanningSceneInterface`_ object. This provides a remote interface\n # for getting, setting, and updating the robot's internal understanding of the\n # surrounding world:\n self.scene = moveit_commander.PlanningSceneInterface()\n\n # move_groups are defined in the srdf that can be found in the config of the selected ur robot. \n # New groups can be defined as well as default positions.\n self.group_name = \"manipulator\"\n self.move_group = moveit_commander.MoveGroupCommander(self.group_name)\n\n self.display_trajectory_publisher = rospy.Publisher(\"/move_group/display_planned_path\", moveit_msgs.msg.DisplayTrajectory, queue_size=20)\n self.rqt_trajectory_publisher = rospy.Publisher(\"/pos_joint_traj_controller/command\", JointTrajectory, queue_size=1)\n\n self.planning_frame = self.move_group.get_planning_frame()\n self.eef_link = self.move_group.get_end_effector_link()\n\n self.group_names = self.robot.get_group_names()\n \n print(\"============ Printing robot state\")\n print(self.robot.get_current_state())\n print(\"\")\n\n def imu_read_cb(self, pose):\n pass\n\n def rqt_ctrl_move(self):\n rqt_msg = JointTrajectory()\n point = JointTrajectoryPoint()\n print(self.move_group.get_active_joints())\n rqt_msg.joint_names = self.move_group.get_active_joints()\n point.positions = [-1.82212373908208, -0.3876104167282426, 0.283185307179588, -12.566350443666414, -12.566382621182798, 12.566359000316584]\n point.time_from_start = rospy.Duration(max(dur) / self._speed_scale)\n rqt_msg.points.append(point)\n self.rqt_trajectory_publisher.publish(rqt_msg)\n \n def moveit_joint(self, goal):\n pass\n\n def moveit_cartesian(self, goal):\n pass\n\n def moveit_tcp(self):\n\n move_group = self.move_group\n\n pose_goal = geometry_msgs.msg.Pose()\n pose_goal.orientation.w = 1.0\n pose_goal.position.x = 0.4\n pose_goal.position.y = 0.3\n pose_goal.position.z = 0.2\n\n move_group.set_pose_target(pose_goal)\n\n ## Now, we call the planner to compute the plan and execute it.\n plan = move_group.go(wait=True)\n\n # Calling `stop()` ensures that there is no residual movement\n move_group.stop()\n\n # It is always good to clear your targets after planning with poses.\n move_group.clear_pose_targets()\n\n # Check if the plan was executed\n if plan is True:\n return \"Succesfully found and executed plan!\"\n\n elif plan is False:\n return \"Failed to get a plan! ABORTING.\"\n\n\ndef main():\n try:\n ur_planner = URplanner()\n\n command = input(\"===============MENU============= \\n a: tcp control \\n s: rqt control \\n d: joint control \\n\")\n if command == \"a\":\n status = ur_planner.moveit_tcp()\n print(status)\n elif command == \"s\":\n status = ur_planner.rqt_ctrl_move()\n except rospy.ROSInterruptException:\n return\n except KeyboardInterrupt:\n return\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"ur_interface/src/ur_biox/scripts/ur_planner.py","file_name":"ur_planner.py","file_ext":"py","file_size_in_byte":3907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"143763702","text":"# Copyright (c) Wenhui Lu. All rights reserved.\n\n# Licensed under the MIT license. See LICENSE.md file in the project root\n# for full license information.\n# ==============================================================================\n\nimport requests\n\ndef download(url, filename):\n response = requests.get(url, stream=True)\n with open(filename, 'wb') as handle:\n for data in response.iter_content(chunk_size=2**20):\n if data: handle.write(data)","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"151297341","text":"import sys\r\n\r\nlines = open(sys.argv[1], 'r')\r\nfor line in lines:\r\n line = line.replace('\\n', '').replace('\\r', '')\r\n if len(line) > 0:\r\n n = int(line)\r\n primes = set([2])\r\n num = 3\r\n while num < n:\r\n if all(num % i != 0 for i in primes):\r\n primes = set(list(primes) + [num])\r\n num = num + 1\r\n primes = sorted(list(primes))\r\n print(','.join([str(x) for x in primes]))\r\n\r\nlines.close()\r\n","sub_path":"Moderate/Prime Numbers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"295255150","text":"import os\nfrom setuptools import setup\n\n\ndef read(fname):\n \"\"\"\n Utility function for loading the README in long description.\n \"\"\"\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\n\nsetup(\n name='pypaddata',\n version='0.0.1',\n author='Joshua Saxby',\n author_email='joshua.a.saxby@gmail.com',\n description='Simple-ish data padding of data in Python.',\n long_description=read('README.md'),\n license='MIT',\n keywords='data padding byte array',\n url='https://github.com/saxbophone/pypaddata',\n packages=['pypaddata', 'tests'],\n install_requires=[],\n extras_require={\n 'dev': ['flake8'],\n 'test': ['flake8'],\n },\n classifiers=[\n 'Development Status :: 1 - Planning',\n 'Topic :: Utilities',\n 'License :: OSI Approved :: MIT License',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Education',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"226110338","text":"#!/usr/bin/python2.7\n#\n# client_list_file\n# DataMover\n#\n# Created by Nehir Poyraz on 10.11.2018\n\nimport socket\nimport os\nimport logging\nimport pickle\n\n\nFORMAT ='%(asctime)-15s | %(levelname)s: LIST %(message)s'\nlogging.basicConfig(filename='client.log', level=logging.DEBUG, format=FORMAT, datefmt='%m/%d/%Y %H:%M:%S')\nlogger = logging.getLogger(__name__)\n\nBUFSIZE = 4096\n\nRED = '\\033[91m'\t# fail\nGREEN = '\\033[92m'\t# success\nLIGHTBLUE = '\\033[96m'\t# file already exists\nYELLOW = '\\033[93m'\t# request sent\nEND = '\\033[0m'\n\n# establish connection\nHOST = 'localhost'\nPORT = 1111\nADDR = (HOST, PORT)\nBUFSIZE = 4096\n\ndef connect():\n\tsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\tsock.connect(ADDR)\n\treturn sock\n\ndef receive(sock):\n\tpickled = sock.recv(BUFSIZE)\n\tpickled = b'' + pickled\n\treply = pickle.loads(pickled)\n\tsock.shutdown(socket.SHUT_RD)\n\treturn reply\n\ndef check(reply):\n\tif reply[:3] == '202' or reply[:3] == '204':\n\t\treply = reply.split(',')\n\t\tmessage = reply[1]\n\t\tif reply[0] == '202':\n\t\t\tlogger.info(message)\n\t\t\tprint(GREEN + message + END)\n\t\telse:\n\t\t\tprint(reply[0])\n\t\t\tlogger.info(message)\n\t\t\tprint('-' * 70 + RED + '\\nThere are no stored files.\\n' + END + '-' * 70 )\n\telse:\n\t\tlogger.info('Data directory is listed.')\n\t\tprint(reply)\n\nsock = connect()\nlogger.info('Connected to server.')\nusername = os.getlogin()\nsock.send(username)\nsock.shutdown(socket.SHUT_WR)\nreply = sock.recv(BUFSIZE)\ncheck(reply)\n\n\n\n\n\n","sub_path":"client/client_list_file.py","file_name":"client_list_file.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"26420608","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 2017年8月19日\n\n@author: Simba\n'''\n\n\nimport logging\nimport os\nimport time\nimport sys\nimport config.config as CONFIG\nsys.path.append(\"..\")\n\n\nglobal CONSOLE\n\n\ndef loggingDemo():\n \"\"\"\n Just demo basic usage of logging module\n \"\"\"\n logging.info(\"You should see this info both in log file and cmd window\")\n logging.warning(\"You should see this warning both in log file and cmd window\")\n logging.error(\"You should see this error both in log file and cmd window\")\n logging.debug(\"You should ONLY see this debug in log file\")\n return\n\n\ndef initLogging(logFilePath=None):\n '''\n Init for logging\n '''\n global CONSOLE\n if logFilePath is None:\n if os.path.isdir(CONFIG.LOG_HOME) is False:\n os.makedirs(CONFIG.LOG_HOME)\n '''time format %Y-%m-%d-%H-%M-%S'''\n logFile = os.path.join(CONFIG.LOG_HOME, str(time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime())) + \"-run.log\")\n else:\n logFile = logFilePath + '/' + str(time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime())) + \"-run.log\"\n if CONFIG.LOG_THREAD_PROCESS == 0:\n logFileFormat = '[%(asctime)s] LINE %(lineno)-4d: %(levelname)-8s %(message)s'\n elif CONFIG.LOG_THREAD_PROCESS == 1:\n logFileFormat = '[%(asctime)s] LINE %(lineno)-4d Thread %(thread)d: %(levelname)-8s %(message)s'\n elif CONFIG.LOG_THREAD_PROCESS == 2:\n logFileFormat = '[%(asctime)s] LINE %(lineno)-4d %(process)d: %(levelname)-8s %(message)s'\n else:\n logFileFormat = '[%(asctime)s] LINE %(lineno)-4d %(process)d Thread %(thread)d: %(levelname)-8s %(message)s'\n logging.basicConfig(\n level=logging.DEBUG,\n format=logFileFormat,\n datefmt='%m-%d %H:%M',\n filename=logFile,\n filemode='a'\n )\n \n # define a Handler which writes INFO messages or higher to the sys.stderr\n CONSOLE = logging.StreamHandler()\n CONSOLE.setLevel(logging.INFO)\n # set a format which is simpler for console use\n if CONFIG.LOG_THREAD_PROCESS == 0:\n formatter = logging.Formatter('[%(asctime)s] LINE %(lineno)-4d: %(levelname)-8s %(message)s')\n elif CONFIG.LOG_THREAD_PROCESS == 1:\n formatter = logging.Formatter('[%(asctime)s] LINE %(lineno)-4d Thread %(thread)d: %(levelname)-8s %(message)s')\n elif CONFIG.LOG_THREAD_PROCESS == 2:\n formatter = logging.Formatter('[%(asctime)s] LINE %(lineno)-4d %(process)d: %(levelname)-8s %(message)s')\n else:\n formatter = logging.Formatter('[%(asctime)s] LINE %(lineno)-4d %(process)d Thread %(thread)d: %(levelname)-8s %(message)s')\n # tell the handler to use this format\n CONSOLE.setFormatter(formatter)\n logging.getLogger().addHandler(CONSOLE)\n\n\ndef destoryLogging():\n global CONSOLE\n logging.getLogger().removeHandler(CONSOLE)\n \n\nif __name__ == \"__main__\":\n logFilename = \"run1.log\"\n initLogging()\n loggingDemo()\n destoryLogging()\n ","sub_path":"newboss/pythonScript/logmodule/logService.py","file_name":"logService.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"105335419","text":"# -*- coding: utf-8 -*-\n__docformat__ = 'restructuredtext en'\n\nfrom .base import *\n\n\nDEBUG = False\nTEMPLATE_DEBUG = DEBUG\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': joinpath(SITE_ROOT, 'db', 'stage.sqlite3')},\n}\n\n# Use staging memcached instances\nMEMCACHED_SERVERS = ['127.0.0.1:11211']\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',\n 'LOCATION': MEMCACHED_SERVERS,\n },\n}","sub_path":"tictac/tictac/settings/stage.py","file_name":"stage.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"511795143","text":"import pokestop\nimport reactions\nimport daily_quest\nimport map\nimport guesser\nimport custom_help\nimport pokemon\nimport crypto\n\nimport random\nimport asyncio\nimport aiohttp\nfrom discord import *\nfrom discord.ext.commands import Bot\nimport pytz\nimport datetime\nfrom PIL import Image\n\nDEBUG = False\n\nBOT_PREFIX = (\"?\", '!')\nif DEBUG:\n\tBOT_PREFIX = (';')\nTOKEN = \"NDQyODI1NDk2MDQwOTY0MDk3.DeOgiA.oFQ_9QUXYvb8PdzP0v2nW1wTMSU\"\n\nhelp_formatter = custom_help.CustomHelp()\nclient = Bot(command_prefix=BOT_PREFIX,formatter=help_formatter)\n\n@client.command(pass_context=True,brief=\"Lien vers la carte d'un dresseur.\",description=\"Lien vers la carte de voyageur à ce nom.\")\nasync def card(context,name):\n\turl = 'https://sil.ph/'+name\n\tawait client.send_message(context.message.channel,url)\n\n@client.command(brief=\"Reporter une quête.\",pass_context=True,description=\"\\\"!quete [recompense] [pokestop]\\\" ➡ le bot demande les informations qui ne sont pas fournies, puis une confirmation.\",aliases=[\"quête\",\"quest\"])\nasync def quete(context,*args):\n\ttry:\n\t\tawait client.delete_message(context.message)\n\texcept:\n\t\tpass\n\t# Interaction mode\n\tif len(args) < 2:\n\t\treward = await reactions.ask_reward(context.message.server,client,context.message.author,context.message.author)\n\t\tplace_name = await reactions.ask_place(context.message.server,client,context.message.author,context.message.author,stops)\n\t\tif place_name == \"\":\n\t\t\treturn\n\t# Command line mode\n\telse:\n\t\ttry:\n\t\t\treward = args[0]\n\t\t\treward = daily_quest.Reward(reward)\n\t\texcept:\n\t\t\tawait client.say(\"Je ne connais pas la récompence \\\"\"+reward+\"\\\" :(. Plus d'infos avec !liste_recompenses.\")\n\t\t\treturn\n\t\tplace = ' '.join(args[1:])\n\t\tplace_name = await guesser.guess_name(place,stops)\n\t\tplace_name = place_name[0]\n\t\t\n\t\t\n\tq = daily_quest.Quest(daily_quest.Task.whatever,reward,stops[place_name])\n\tfor q2 in daily_quests:\n\t\tif q2.location == q.location:\n\t\t\tif q2.reward == q.reward:\n\t\t\t\tawait client.send_message(context.message.author,\"Je connaissais déjà cette quête ! :)\")\n\t\t\telse:\n\t\t\t\tawait client.send_message(context.message.author,\"On m'avait signalé une autre quête ici ! S'il y a une erreur, merci de le signaler à Cubix ou Cyrielle !\")\n\t\t\treturn\n\t\t\n\t# Send map and confirmation message with emotes\n\tf1,f2 = await map.draw_stop(stops[place_name],\"map_question\")\n\timages = [Image.open(f1),Image.open(f2)]\n\ttotal_width = images[0].size[0]*2+20\n\tmax_height = images[0].size[1]\n\tnew_im = Image.new('RGB', (total_width, max_height))\n\tx_offset = 0\n\tfor im in images:\n\t new_im.paste(im, (x_offset,0))\n\t x_offset += im.size[0]+20\n\tnew_im.save('quete.png')\n\tmap_message = await client.send_file(context.message.author,'quete.png')\n\ts_quest = 'Récompense : ' + str(reward) + ' ; Localisation : ' + place_name\n\tquestion = await client.send_message(context.message.author,s_quest + \"\\n\" + \"C'est bien ça \" + context.message.author.mention + \" ?\")\n\temote_ok = '✅'\n\temote_cross = '❌'\n\tawait client.add_reaction(question,emote_ok)\n\tawait client.add_reaction(question,emote_cross)\n\t\n\t# Wait for emotes\n\tans = [0,0]\n\twhile ans[1] != context.message.author:\n\t\tans = await client.wait_for_reaction([emote_ok,emote_cross],message=question)\n\t\t\n\t# Delete map and confirmation message\n\tawait client.delete_message(question)\n\tawait client.delete_message(map_message)\n\n\tif ans[0].emoji == emote_ok:\n\t\t# User says OK\n\t\t\n\t\tif DEBUG:\n\t\t\tpass\n\t\telse:\n\t\t\tawait client.send_message(channels['Pogo Toulouse Test']['quests-history'],'[' + context.message.author.name + '] ; ' + str(reward) + ' ; ' + place_name)\n\t\t\tdaily_quests.append(q)\n\t\t\tawait update_quests()\n\t\t\tq.send_to_website()\n\t\t\n@client.command(name=\"liste_recompenses\", brief=\"Liste des récompenses disponibles.\", description=\"Liste des récompenses de quêtes actuellement utilisées par le bot.\")\nasync def rewards_list():\n\tawait client.say(\", \".join(daily_quest.get_all_rewards()))\n\t\n@client.command(pass_context = True,brief=\"Affiche la carte actuelle.\",description=\"Affiche les quêtes connues aujourd'hui.\\nEn donnant une adresse (exemple : \\\"!carte Toulouse, rue d'Alsace Lorraine\\\", la carte retourne les quêtes autour de cette adresse.\")\nasync def carte(context,*args):\n\tfile_name = \"image.png\"\n\tif len(args) > 0:\n\t\tawait map.draw_map(file_name,daily_quests,'%20'.join(args),17)\n\telse:\n\t\tawait map.draw_map(file_name,daily_quests)\n\tawait client.send_file(context.message.channel,file_name)\n\n@client.command(pass_context = True,brief=\"Affiche la carte autour d'un Pokéstop.\",description=\"Affiche la carte autour du Pokéstop donné avec la commande. Exemple :\\n!pin fontaine du capitole\",aliases=[\"pokéstop\",\"pokestop\",\"stop\"])\nasync def pin(context, *args):\n\tbase_name = \"pin\"\n\tif len(args) == 0:\n\t\tawait client.say(\"Utilisation :\\n```!pin nom du pokestop à afficher```\")\n\t\treturn\n\tname = ' '.join(args)\n\tplace_name = await guesser.guess_name(name,stops)\n\tplace_name = place_name[0]\n\tf1,f2 = await map.draw_stop(stops[place_name],base_name)\t\n\timages = [Image.open(f1),Image.open(f2)]\n\ttotal_width = images[0].size[0]*2+20\n\tmax_height = images[0].size[1]\n\tnew_im = Image.new('RGB', (total_width, max_height))\n\tx_offset = 0\n\tfor im in images:\n\t new_im.paste(im, (x_offset,0))\n\t x_offset += im.size[0]+20\n\tnew_im.save('pin.png')\n\t\n\t\n\tawait client.say(place_name)\n\tawait client.send_file(context.message.channel,'pin.png')\n\t\t\n@client.command(pass_context=True,brief=\"Cherche le nom exact d'un Pokéstop.\",description=\"Affiche les 10 noms de Pokéstops qui ressemblent le plus à ce qui est donné après la commande. Exemple :\\n!cherche caiptole\")\nasync def cherche(context,*nom):\n\tif len(nom) == 0:\n\t\tawait client.say(\"Utilisation :\\n```!cherche nom du pokestop à chercher```\")\n\t\treturn\n\tname = ' '.join(nom)\n\tprint(name,flush=True)\n\ts = await guesser.guess_name(name,stops)\n\tcount = 0\n\tmessage = \"\"\n\twhile count < 10 and count < len(s):\n\t\tmessage = message + str(s[count])\n\t\tmessage = message + \"\\n\"\n\t\tcount += 1\n\tawait client.send_message(context.message.channel,message)\n\n@client.command(pass_context=True,brief=\"Guess name\")\nasync def cherche_depuis_ref(context,*args):\n\tif len(args) < 2:\n\t\treturn\n\tref = args[0]\n\t\n\tname = ' '.join(args[1:])\n\tprint(ref,flush=True)\n\tprint(name,flush=True)\n\treference = stops[(await guesser.guess_name(ref,stops))[0]]\n\ts = await guesser.guess_name_bis(name,stops,reference)\n\tcount = 0\n\tmessage = \"\"\n\twhile count < 10 and count < len(s):\n\t\tmessage = message + str(s[count])\n\t\tmessage = message + \"\\n\"\n\t\tcount += 1\n\tawait client.send_message(context.message.channel,message)\n\t\n@client.command(pass_context=True,brief=\"Reboot le bot.\")\nasync def force_reset(context):\n\tif context.message.author.name == 'Cubix' or context.message.author.name == 'platinegirl' or context.message.author.name == 'MUNYUNYU':\n\t\tawait client.add_reaction(context.message,'🔄')\n\t\tawait init_bot()\n\t\tawait client.remove_reaction(context.message,'🔄',client.user)\n\t\tawait client.add_reaction(context.message,'✅')\n\telse:\n\t\tawait client.say(\"Désolé, pas le droit !\")\n\t\tawait client.send_message(channels[\"Pogo Toulouse Test\"][\"général\"],context.message.author.name + \" n'a pas réussi le reboot.\")\n\t\nasync def init_bot():\n\tglobal channels\n\tchannels = {}\n\tglobal servers\n\tservers = {}\n\tprint(\"Logged in as \" + client.user.name,flush=True)\n\tfor s in client.servers:\n\t\tservers[s.name] = s\n\t\tchannels[s.name] = {}\n\t\tfor c in s.channels:\n\t\t\tchannels[s.name][c.name] = c\n\t\n\t\n\tglobal stops\n\tstops = await pokestop.get_all_pokestops(channels[\"Pogo Toulouse Test\"][\"data-pokestops\"],client)\n\tprint(\"Read \"+str(len(stops))+\" portal(s).\",flush=True)\n\t\n\tawait daily_quest.read_rewards(channels[\"Pogo Toulouse Test\"][\"data-quest-rewards\"],client, servers[\"Pogo Toulouse Test\"])\n\tprint(\"Read \"+str(len(daily_quest.REWARDS))+\" reward(s).\",flush=True)\n\t\t\n\t\n\tglobal daily_quests\n\tdaily_quests = await daily_quest.read_current_quests(channels[\"Pogo Toulouse Test\"][\"quests-history\"],client,stops)\n\tif not DEBUG:\n\t\tawait update_quests()\n\telse:\n\t\tawait update_quests()\n\tprint(\"Read \"+str(len(daily_quests))+\" quest(s).\",flush=True)\n\t\t\n\tawait client.change_presence(game=Game(name=\"Roborally\",type=1))\n\t\n\tawait pokemon.read_pokemons(channels[\"Pogo Toulouse Test\"][\"pokémons\"],client)\n\tprint(\"Read \"+str(len(pokemon.POKEMON))+\" Pokémon.\",flush=True)\n\t\n\t# await pokemon.init_driver()\n\t# print(\"Driver initialized.\",flush=True)\n\t\n\tprint(\"Initialization finished.\",flush=True)\n\n@client.event\nasync def on_ready():\n\tawait init_bot()\n\tawait client.send_message(destination=channels[\"Pogo Toulouse Test\"][\"général\"], content=\"Prêt !\")\n\t\nasync def loop():\n\tawait client.wait_until_ready()\n\twhile not client.is_closed:\n\t\tawait asyncio.sleep(1)\n\t\t\nasync def reset_loop():\n\tawait client.wait_until_ready()\n\ttz = pytz.timezone('Europe/Paris')\n\twhile not client.is_closed:\n\t\tcurrent_date = datetime.datetime.now(tz)\n\t\tif current_date.hour == 0 and current_date.minute == 0:\n\t\t\tawait client.send_message(channels[\"Pogo Toulouse Test\"][\"général\"],\"Reset time!\")\n\t\t\tglobal daily_quests\n\t\t\tdaily_quests = []\n\t\t\tawait update_quests()\n\t\t\tawait asyncio.sleep(3600*24-10)\n\t\telse:\n\t\t\th = current_date.hour\n\t\t\tm = current_date.minute\n\t\t\tsec = current_date.second\n\t\t\twait_time = (60-sec) + 60*(59-m) + 3600*(23-h)\n\t\t\tprint(\"Time before next reset: \"+str(wait_time)+\" seconds\",flush=True)\n\t\t\tawait asyncio.sleep(wait_time)\n\nasync def update_quests():\n\tawait daily_quest.update_map(client,channels[\"PoGo Toulouse TSR\"][\"carte-quetes\"],stops,daily_quests)\n\n# @client.command(pass_context=True,brief=\"Fusionne deux ou trois Pokémon.\")\n# async def fusion(context,*args):\n\t# file_name = \"fusion.png\"\n\t# p1 = 0\n\t# p2 = 0\n\t# p3 = 0\n\t# try:\n\t\t# p1 = args[0]\n\t\t# if p1.isdigit():\n\t\t\t# p1 = int(p1)\n\t\t# p2 = args[1]\n\t\t# if p2.isdigit():\n\t\t\t# p2 = int(p2)\n\t\t# p3 = args[2]\n\t\t# if p3.isdigit():\n\t\t\t# p3 = int(p3)\n\t# except:\n\t\t# pass\n\t# await client.add_reaction(context.message,\"👌\")\n\t# r = await pokemon.fusion(file_name,client,channels[\"Pogo Toulouse Test\"][\"général\"],context.message.channel,p1,p2,p3)\n\t# if r:\n\t\t# await client.send_file(context.message.channel,file_name)\n\t# else:\n\t\t# await client.say(\"Nope\")\n\t\t\n\n@client.command(pass_context=True)\nasync def annonce(ctx,*args):\n\tawait client.say(\"Nom du serveur ?\")\n\tserver_name = (await client.wait_for_message(author=ctx.message.author)).content\n\ttry:\n\t\tserver = servers[server_name]\n\texcept:\n\t\tawait client.say(\"Désolé, je ne connais pas ce serveur !\")\n\t\treturn\n\t\n\tawait client.say(\"Nom du canal ?\")\n\tchannel_name = (await client.wait_for_message(author=ctx.message.author)).content\n\ttry:\n\t\tchannel = channels[server_name][channel_name]\n\t\tawait client.send_message(channel,\"Ok\")\n\t\t\n\t\tif not ctx.message.author.permissions_in(channel).administrator:\n\t\t\tawait client.say(\"Désolé, vous n'avez pas les droits d'utiliser cette commande sur ce canal !\")\n\t\t\treturn\n\texcept:\n\t\tawait client.say(\"Désolé, je ne connais pas ce canal !\")\n\t\treturn\n\t\n\tawait client.say(\"Quel sera le message à envoyer ?\")\n\tmessage = (await client.wait_for_message(author=ctx.message.author)).content\n\t\t\n\temoji_calendar = '📆'\n\temoji_timer = '⏲'\n\tquestion = await client.say(\"Vous souhaitez envoyer votre message :\\n:calendar: À une heure précise ?\\n:timer:Après un certain délai ?\")\n\tawait client.add_reaction(question,emoji_calendar)\n\tawait client.add_reaction(question,emoji_timer)\n\tanswer = False\n\twhile not answer:\n\t\tans = await client.wait_for_reaction([emoji_calendar,emoji_timer],message=question)\n\t\tif ans[1] == ctx.message.author:\n\t\t\tanswer = True\n\tseconds = 0\n\tif str(ans[0].emoji) == emoji_calendar:\n\t\tawait client.say(\"Quand voulez-vous que j'envoie le message ? (Heure de Paris)\\nFormat : \\\"Jour Mois Année Heures Minutes Secondes\\\"\")\n\t\ttz = pytz.timezone('Europe/Paris')\n\t\tdate = (await client.wait_for_message(author=ctx.message.author)).content\n\t\ttry:\n\t\t\td = date.split(' ')\n\t\t\tcurrent_date = datetime.datetime.now(tz)\n\t\t\twanted_date = tz.localize(datetime.datetime(int(d[2]),int(d[1]),int(d[0]),int(d[3]), int(d[4]), int(d[5])))\n\t\t\t\n\t\t\tseconds = int((wanted_date-current_date).total_seconds())\n\t\t\t\n\t\t\ts = \"C'est dans \" + str(seconds) + \" seconde\"\n\t\t\tif seconds > 1:\n\t\t\t\ts += \"s\"\n\t\t\ts += \" ! :)\"\n\t\t\tawait client.say(s)\n\t\texcept:\n\t\t\tawait client.say(\"Problème de format ?\")\n\t\t\treturn\n\tif str(ans[0].emoji) == emoji_timer:\n\t\tawait client.say(\"Dans combien de temps voulez-vous que j'envoie le message ?\\nFormat : \\\"Heures Minutes Secondes\\\"\")\n\t\tdate = (await client.wait_for_message(author=ctx.message.author)).content\n\t\ttry:\n\t\t\td = date.split(' ')\n\t\t\t\n\t\t\tseconds = 3600*int(d[0]) + 60*int(d[1]) + int(d[2])\n\t\t\t\n\t\t\ts = \"C'est dans \" + str(seconds) + \" seconde\"\n\t\t\tif seconds > 1:\n\t\t\t\ts += \"s\"\n\t\t\ts += \" ! :)\"\n\t\t\tawait client.say(s)\n\t\texcept:\n\t\t\tawait client.say(\"Problème de format ?\")\n\t\t\treturn\n\tawait asyncio.sleep(seconds)\n\tawait client.send_message(channel,message)\n\t\n@client.command(pass_context=True)\nasync def stats(ctx):\n\tserver = ctx.message.server\n\tif server == None:\n\t\tawait client.say(\"Il faut être sur un serveur !\")\n\t\treturn\n\tbleu=0\n\trouge=0\n\tjaune=0\n\tfor m in server.members:\n\t\tif 'bleu' in [str(r) for r in m.roles]:\n\t\t\tbleu += 1\n\t\tif 'rouge' in [str(r) for r in m.roles]:\n\t\t\trouge += 1\n\t\tif 'jaune' in [str(r) for r in m.roles]:\n\t\t\tjaune += 1\n\t\t\t\n\tawait client.say(\"Il y a {} bleus, {} jaunes et {} rouges sur le serveur !\".format(bleu,jaune,rouge))\n\t\n@client.command(pass_context=False)\nasync def parfait(*args):\n\tlevel_min = 0\n\tlevel_max = 69\n\ttry:\n\t\tlevel = float(args[0])\n\t\tname = ' '.join(args[1:])\n\t\tif 2*level-int(2*level) != 0 or level < 1 or level > 40:\n\t\t\tawait client.say(\"Niveau incorrect !\")\n\t\t\treturn\n\t\tlevel_min = int(2*level-2)\n\t\tlevel_max = int(2*level-1)\n\texcept:\n\t\tname = ' '.join(args[0:])\n\t\t\n\tn,ba,bd,bs,fr,en = pokemon.infos(name)\n\tif n < 1:\n\t\tawait client.say(\"Je ne connais pas ce pokemon !\")\n\t\treturn\n\telse:\n\t\ts = \"```\\n{}\\n\".format(fr)\n\t\tfor l in range(level_min,level_max,2):\n\t\t\tcp = pokemon.computeCP(ba+15,bd+15,bs+15,pokemon.CPM[l])\n\t\t\ts += \"\\nNiveau {} : {} PC\".format(int(l/2.+1),cp)\n\t\ts += \"```\"\n\t\tawait client.say(s)\n\nasync def quete_sans_validation(message,args):\n\tprint(args,flush=True)\n\treward = daily_quest.Reward(args[0])\n\tplace = ' '.join(args[1:])\n\tplace_name = await guesser.guess_name(place,stops)\n\tplace_name = place_name[0]\n\t\n\tq = daily_quest.Quest(daily_quest.Task.whatever,reward,stops[place_name])\n\t\n\tfor q2 in daily_quests:\n\t\tif q2.location == q.location:\n\t\t\tif q2.reward == q.reward:\n\t\t\t\tawait client.add_reaction(message,'✅')\n\t\t\t\tawait client.add_reaction(message,'😉')\n\t\t\telse:\n\t\t\t\tawait client.add_reaction(message,'⁉')\n\t\t\t\ts = \"Conflit sur une quête !\\n*Lieu : * **\" + place_name + \"**\"\n\t\t\t\ts += \"\\n*Ancienne récompense :* **\" + str(q2.reward) + \"**\"\n\t\t\t\ts += \"\\n*Nouvelle récompense :* **\" + str(q.reward) + \"**\"\n\t\t\t\tawait client.send_message(channels[\"Pogo Toulouse Test\"][\"général\"], s)\n\t\t\treturn\n\t\n\tdaily_quests.append(q)\n\tawait client.send_message(channels[\"Pogo Toulouse Test\"][\"quests-history\"], '[webhook] ; ' + str(reward) + ' ; ' + place_name)\n\tawait update_quests()\n\tawait client.add_reaction(message,'✅')\n\n@client.event\nasync def on_member_join(member):\n\tserver_name = \"PoGo Toulouse TSR\"\n\tchannel_name = \"nouveaux-membres\"\n\t\n\tif DEBUG:\n\t\tserver_name='Pogo Toulouse Test'\n\t\n\tmessage = \"Bonjour {0} et bienvenue sur ce Discord des joueurs de Pokemon Go de Toulouse, réservé aux joueurs respectant le code de bonne conduite du dresseur (pas de triche et donc pas de fly).\\nMerci de nous signaler quelle équipe PoGo vous avez rejoint (bleu, rouge, jaune) et vous aurez alors acces a l'intégralité du Discord, qui comprend divers salons de discussion dont l'organisation de raids (surtout en dehors des horaires de travail, en hyper-centre-ville) ou de sessions de jeu en communauté dans le cadre d'événements, une carte de quêtes du jour, de codes amis + propositions d'échanges, un concours hebdomadaire, ...\".format(member.mention)\n\tmessage += \"\\n\\n`Cliquez sur l'emoji correspondant à votre couleur !`\"\n\tmessage += \"\\n\\n`Click on your your team color's emoji!`\"\n\t\n\tif member.server == servers[server_name]:\n\t\twelcome_message = await client.send_message(channels[server_name][channel_name], message)\n\t\tfor reaction in ['❤','💛','💙']:\n\t\t\tawait client.add_reaction(welcome_message,reaction)\n\t\t\t\n\t\tans = await client.wait_for_reaction(['❤','💛','💙'],user=member,message=welcome_message)\n\t\tif ans.reaction.emoji == '❤':\n\t\t\tcouleur = 'rouge'\n\t\tif ans.reaction.emoji == '💛':\n\t\t\tcouleur = 'jaune'\n\t\tif ans.reaction.emoji == '💙':\n\t\t\tcouleur = 'bleu'\n\t\tawait client.delete_message(welcome_message)\n\t\t\n\t\tfor r in servers[server_name].roles:\n\t\t\tif str(r)==couleur:\n\t\t\t\tawait client.add_roles(member, r)\n\t\t\t\t\n\t\tawait client.send_message(channels[server_name][\"general-pogo\"],\"Bienvenue {0} !\".format(member.mention))\n\t\t\t\t\n@client.command(pass_context=True)\nasync def new_reward(context):\n\tif context.message.author.name != 'Cubix' and context.message.author.name != 'platinegirl' and context.message.author.name != 'MUNYUNYU':\n\t\tawait client.say(\"Désolé, cette commande est bloquée !\")\n\t\treturn\n\tawait daily_quest.new_reward(channels[\"Pogo Toulouse Test\"][\"général\"],client,servers[\"Pogo Toulouse Test\"],context.message.author)\n\n@client.event\nasync def on_message(message):\n\tif str(message.author) == \"Captain Hook#0000\" and str(message.channel) == \"quests-webhook\":\n\t\ts = message.content.split(' ')\n\t\tif not DEBUG:\n\t\t\tawait quete_sans_validation(message,s[1:])\n\telse:\n\t\tawait client.process_commands(message)\n\t\t\t\nclient.loop.create_task(loop())\nclient.loop.create_task(reset_loop())\n\nclient.run(TOKEN)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":17557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"262004131","text":"from unittest import TestCase\n\nfrom django.db import models\n\nfrom django_filters import rest_framework as filters\n\nfrom ..filters import NullableCharFilter\nfrom ..test_utils import MockQuery\n\n\nclass TestNullableCharFilter(TestCase):\n\n class TestModel(models.Model):\n text = models.CharField(max_length=100)\n\n class Meta:\n abstract = True\n\n class TestFilter(filters.FilterSet):\n text = NullableCharFilter(field_name='text', lookup_expr='contains')\n\n def test_not_null_arg(self):\n query = MockQuery(model=self.TestModel)\n filtered = self.TestFilter(\n {'text': 'hello world'},\n query,\n )\n self.assertEqual(\n filtered.qs._args,\n {\n 'text__contains': 'hello world',\n }\n )\n\n def test_null_arg(self):\n query = MockQuery(model=self.TestModel)\n filtered = self.TestFilter(\n {'text': 'NULL'},\n query,\n )\n self.assertEqual(\n filtered.qs._args,\n {\n 'text__isnull': True,\n }\n )\n","sub_path":"agronom/core/tests/test_filters.py","file_name":"test_filters.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"279147810","text":"from tkinter import *\nimport tkinter.ttk as ttk\n\nclass ComboboxValuesSample(ttk.Frame):\n def __init__(self, master):\n super().__init__(master)\n self.create_widgets()\n self.pack()\n\n def create_widgets(self):\n valuelist=[\"ぶどう\",\"バナナ\",\"もも\",\"いちご\"]\n combo = ttk.Combobox(self,values=valuelist)\n combo.pack()\n\n\nif __name__ == '__main__':\n master = Tk()\n master.title(\"ComboboxValuesSample\")\n master.geometry(\"300x200\")\n ComboboxValuesSample(master)\n master.mainloop()\n","sub_path":"Combobox/ComboboxSample_values.py","file_name":"ComboboxSample_values.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"246961880","text":"#!/usr/bin/python\n\nimport sys\nimport re\nimport csv\nimport traceback\nimport operator\n\nimport cutil.cutil\n\nfrom amfi.amfi import *\n\nclass Demat(Amfi):\n\n def __init__(self):\n super(Demat, self).__init__()\n self.company_name = {}\n self.demat_txn_last_type = {}\n self.demat_txn_buy_qty = {}\n self.demat_txn_buy_price = {}\n self.demat_txn_sale_qty = {}\n self.demat_txn_sale_price = {}\n self.demat_txn_last_date = {}\n self.demat_txn_first_buy_date = {}\n self.demat_txn_list = {}\n self.demat_summary_rw_list = []\n self.demat_summary_qty = {}\n self.demat_summary_acp = {}\n self.demat_summary_upl_pct = {}\n self.demat_summary_captype_stock_count = {}\n self.demat_summary_captype_stock_cost_value = {}\n self.demat_summary_captype_stock_market_value = {}\n self.demat_summary_captype_unrealized_pl = {}\n # stock keeping units : sku\n self.demat_summary_sku = {}\n self.demat_table_truncate = False\n self.demat_lc_weight = self.config_lc_weight\n self.demat_mc_weight = self.config_mc_weight\n self.demat_sc_weight = self.config_sc_weight\n self.debug_level = 0\n self.demat_txn_table_name = \"demat_txn\"\n self.demat_txn_table_dict = {\n \"stock_symbol\": \"text\",\n \"company_name\": \"text\",\n \"isin_code\": \"text\",\n \"action\": \"text\",\n \"quantity\": \"text\",\n \"txn_price\": \"text\",\n \"brokerage\": \"text\",\n \"txn_charges\": \"text\",\n \"stamp_duty\": \"text\",\n \"segment\": \"text\",\n \"stt\": \"text\",\n \"remarks\": \"text\",\n \"txn_date\": \"text\",\n \"exchange\": \"text\",\n \"unused1\": \"text\"\n }\n self.demat_summary_table_name = \"demat_summary\"\n self.demat_summary_table_dict = {\n \"stock_symbol\": \"text\",\n \"company_name\": \"text\",\n \"isin_code\": \"text\",\n \"qty\": \"text\",\n \"acp\": \"text\",\n \"cmp\": \"text\",\n \"pct_change\": \"text\",\n \"value_cost\": \"text\",\n \"value_market\": \"text\",\n \"days_gain\": \"text\",\n \"days_gain_pct\": \"text\",\n \"realized_pl\": \"text\",\n \"unrealized_pl\": \"text\",\n \"unrealized_pl_pct\": \"text\",\n \"unused1\": \"text\"\n }\n print('init : Demat')\n\n def set_debug_level(self, debug_level):\n self.debug_level = debug_level\n\n def demat_table_reload(self, truncate=False):\n self.demat_table_truncate = truncate\n\n def demat_txn_load_row(self, row):\n try:\n row_list = row\n # skip header\n if row_list[0] == 'Stock Symbol':\n return\n else:\n # this is not used as ICICI direct uses different names\n stock_symbol = row_list[0].strip()\n\n comp_name = row_list[1]\n isin_code = (row_list[2]).upper().strip()\n stock_symbol = self.amfi_get_value_by_isin(isin_code, \"ticker\")\n # ignore Gold ETF : Kotak, HDFC etc\n if stock_symbol == 'UNK_TICKER' and comp_name.find(\"GOLD\") == -1:\n print(\"isin\", isin_code, \"symbol\", stock_symbol, \"company\", comp_name)\n\n txn_type = row_list[3]\n txn_qty = row_list[4]\n txn_price = str(int(round(float(row_list[5]))))\n txn_date = row_list[12]\n\n p_str = stock_symbol\n p_str += ','\n p_str += isin_code\n p_str += ','\n p_str += comp_name\n p_str += ','\n p_str += txn_type\n p_str += ','\n p_str += str(txn_qty)\n p_str += ','\n p_str += txn_price\n p_str += ','\n p_str += txn_date\n p_str += '\\n'\n\n if self.debug_level > 1:\n print(p_str)\n\n if stock_symbol in self.demat_txn_list:\n self.demat_txn_list[stock_symbol] += p_str\n else:\n self.demat_txn_list[stock_symbol] = p_str\n\n self.company_name[stock_symbol] = cutil.cutil.normalize_comp_name(comp_name)\n if txn_type == \"Buy\":\n if stock_symbol in self.demat_txn_buy_qty:\n self.demat_txn_buy_qty[stock_symbol] += int(txn_qty)\n self.demat_txn_buy_price[stock_symbol] += int(round(float(txn_price))) * int(txn_qty)\n else:\n self.demat_txn_buy_qty[stock_symbol] = int(txn_qty)\n self.demat_txn_buy_price[stock_symbol] = int(round(float(txn_price))) * int(txn_qty)\n else:\n if stock_symbol in self.demat_txn_sale_qty:\n self.demat_txn_sale_qty[stock_symbol] += int(txn_qty)\n self.demat_txn_sale_price[stock_symbol] += int(round(float(txn_price))) * int(txn_qty)\n else:\n self.demat_txn_sale_qty[stock_symbol] = int(txn_qty)\n self.demat_txn_sale_price[stock_symbol] = int(round(float(txn_price))) * int(txn_qty)\n\n # skip updating bonus entries\n if txn_price != 0:\n self.demat_txn_last_type[stock_symbol] = txn_type\n self.demat_txn_last_date[stock_symbol] = txn_date\n if txn_type == \"Buy\":\n if stock_symbol not in self.demat_txn_first_buy_date:\n self.demat_txn_first_buy_date[stock_symbol] = txn_date\n if txn_type == \"Sell\":\n # ignore previous buy entries\n # assume - last SELL to be full sale.\n del self.demat_txn_first_buy_date[stock_symbol]\n except KeyError:\n print(\"demat key error:\", sys.exc_info())\n traceback.print_exc()\n except:\n print(\"demat unexpected error:\", sys.exc_info())\n traceback.print_exc()\n\n\n def demat_summary_load_row(self, row):\n try:\n row_list = row\n # skip header : sometime Stock Symbol appears as 'tock Symbol'\n if row_list[0] == 'Stock Symbol' or row_list[1] == 'Company Name':\n return\n\n # not used\n # stock_symbol = row_list[0]\n comp_name = row_list[1]\n isin_code = (row_list[2]).upper().strip()\n stock_symbol = self.amfi_get_value_by_isin(isin_code, \"ticker\")\n self.demat_summary_rw_list.append(stock_symbol)\n qty = row_list[3]\n acp = row_list[4]\n cmp = row_list[5]\n pct_change = row_list[6]\n value_cost = row_list[7]\n value_market = row_list[8]\n days_gain = row_list[9]\n days_gain_pct = row_list[10]\n realized_pl = row_list[11]\n unrealized_pl = row_list[12]\n unrealized_pl_pct = row_list[13]\n unused1 = row_list[14]\n self.demat_summary_qty[stock_symbol] = qty\n self.demat_summary_acp[stock_symbol] = acp\n self.demat_summary_upl_pct[stock_symbol] = unrealized_pl_pct\n if int(qty) > 0:\n sku = int(round(float(qty) * float(acp) / 1000))\n if self.debug_level > 1:\n print(stock_symbol, \"qty\", qty, \"acp\", acp, \"sku\", sku)\n else:\n if self.debug_level > 0:\n print(\"unexpected: qty 0\")\n sku = 0\n # store\n self.demat_summary_sku[stock_symbol] = sku\n\n captype = self.amfi_get_value_by_ticker(stock_symbol, \"captype\")\n\n if captype in self.demat_summary_captype_stock_count:\n self.demat_summary_captype_stock_count[captype] += 1\n else:\n self.demat_summary_captype_stock_count[captype] = 1\n\n if captype in self.demat_summary_captype_stock_cost_value:\n self.demat_summary_captype_stock_cost_value[captype] += round(float(value_cost))\n else:\n self.demat_summary_captype_stock_cost_value[captype] = round(float(value_cost))\n\n if captype in self.demat_summary_captype_stock_market_value:\n self.demat_summary_captype_stock_market_value[captype] += round(float(value_market))\n else:\n self.demat_summary_captype_stock_market_value[captype] = round(float(value_market))\n\n if captype in self.demat_summary_captype_unrealized_pl:\n self.demat_summary_captype_unrealized_pl[captype] += round(float(unrealized_pl))\n else:\n self.demat_summary_captype_unrealized_pl[captype] = round(float(unrealized_pl))\n\n except:\n print(\"demat_summary_load_row Unexpected error:\", sys.exc_info(), row)\n\n def demat_txn_load_data(self, in_filename):\n table = \"demat_txn\"\n if self.demat_table_truncate:\n self.db_table_truncate(table)\n\n row_count = self.db_table_count_rows(table)\n if row_count == 0:\n self.demat_txn_insert_data(in_filename)\n else:\n print('demat_txn data already loaded in db', row_count)\n print('display db data')\n self.demat_txn_load_db()\n\n\n def demat_summary_load_data(self, in_filename):\n table = \"demat_summary\"\n if self.demat_table_truncate:\n self.db_table_truncate(table)\n\n row_count = self.db_table_count_rows(table)\n if row_count == 0:\n self.demat_summary_insert_data(in_filename)\n else:\n print('demat_summary data already loaded in db', row_count)\n print('display db data')\n self.demat_summary_load_db()\n\n def demat_txn_insert_data(self, in_filename):\n\n create_sql = cutil.cutil.get_create_sql(self.demat_txn_table_name, self.demat_txn_table_dict)\n insert_sql = cutil.cutil.get_insert_sql(self.demat_txn_table_name, self.demat_txn_table_dict)\n\n cursor = self.db_conn.cursor()\n with open(in_filename, 'rt') as csvfile:\n # future\n csv_reader = csv.reader(csvfile)\n # insert row\n cursor.executemany(insert_sql, csv_reader)\n # commit db changes\n self.db_conn.commit()\n\n\n def demat_summary_insert_data(self, in_filename):\n\n create_sql = cutil.cutil.get_create_sql(self.demat_summary_table_name, self.demat_summary_table_dict)\n insert_sql = cutil.cutil.get_insert_sql(self.demat_summary_table_name, self.demat_summary_table_dict)\n\n cursor = self.db_conn.cursor()\n with open(in_filename, 'rt') as csvfile:\n # future\n csv_reader = csv.reader(csvfile)\n # insert row\n cursor.executemany(insert_sql, csv_reader)\n # commit db changes\n self.db_conn.commit()\n\n def demat_txn_load_db(self):\n table = \"demat_txn\"\n cursor = self.db_table_load(table)\n for row in cursor.fetchall():\n if self.debug_level > 1 :\n print(row)\n self.demat_txn_load_row(row)\n # self.demat_txn_prepare_data()\n\n\n def demat_summary_load_db(self):\n table = \"demat_summary\"\n cursor = self.db_table_load(table)\n for row in cursor.fetchall():\n if self.debug_level > 1 :\n print(row)\n self.demat_summary_load_row(row)\n # self.prepare_demat_data()\n\n def demat_dump_txn_detailed(self, out_filename):\n fh = open(out_filename, \"w\")\n fh.write('stock_symbol, isin_code, comp_name, action, qty, price, txn_date\\n')\n for stock_symbol in sorted(self.demat_txn_list):\n if self.debug_level > 1:\n print('dumping stock', stock_symbol)\n fh.write(self.demat_txn_list[stock_symbol])\n fh.close()\n\n def demat_dump_txn_compressed(self, out_filename):\n fh = open(out_filename, \"w\")\n fh.write(\n 'stock_symbol, isin_code, comp_name, buy_qty, sale_qty, buy_price, sale_price, demat_txn_last_type, demat_txn_last_date\\n')\n for stock_symbol in sorted(self.demat_txn_list):\n if stock_symbol == 'Stock Symbol':\n continue\n isin_code = self.amfi_get_value_by_ticker(stock_symbol, \"isin\")\n p_str = stock_symbol\n p_str += ','\n p_str += isin_code \n p_str += ','\n p_str += self.company_name[stock_symbol]\n p_str += ','\n p_str += str(self.demat_txn_buy_qty[stock_symbol])\n p_str += ','\n if stock_symbol in self.demat_txn_sale_qty:\n p_str += str(self.demat_txn_sale_qty[stock_symbol])\n else:\n p_str += '0'\n p_str += ','\n p_str += str(self.demat_txn_buy_price[stock_symbol])\n p_str += ','\n if stock_symbol in self.demat_txn_sale_price:\n p_str += str(self.demat_txn_sale_price[stock_symbol])\n else:\n p_str += '0'\n p_str += ','\n p_str += self.demat_txn_last_type[stock_symbol]\n p_str += ','\n p_str += self.demat_txn_last_date[stock_symbol]\n p_str += '\\n'\n fh.write(p_str)\n fh.close()\n\n def demat_dump_txn_summary(self, out_filename, positive_holdings=None):\n\n # print(self.demat_summary_sku)\n\n fh = open(out_filename,\"w\")\n fh.write(\n 'stock_symbol, isin_code, comp_name, demat_summary_qty, demat_summary_acp, demat_summary_sku, demat_txn_last_type, demat_txn_last_date\\n')\n for stock_symbol in sorted(self.demat_txn_list):\n if stock_symbol == 'Stock Symbol':\n continue\n isin_code = self.amfi_get_value_by_ticker(stock_symbol, \"isin\")\n p_str = stock_symbol \n p_str += ','\n p_str += isin_code\n p_str += ','\n p_str += self.company_name[stock_symbol]\n p_str += ','\n p_str += str(self.demat_summary_qty[stock_symbol])\n p_str += ','\n p_str += str(self.demat_summary_acp[stock_symbol])\n p_str += ','\n if stock_symbol in self.demat_summary_sku:\n p_str += str(self.demat_summary_sku[stock_symbol])\n else:\n p_str += '0'\n # print(\":\",stock_symbol,\":\")\n p_str += ','\n p_str += self.demat_txn_last_type[stock_symbol]\n p_str += ','\n p_str += self.demat_txn_last_date[stock_symbol]\n p_str += '\\n'\n if positive_holdings:\n if int(self.demat_summary_qty[stock_symbol]) > 0:\n fh.write(p_str)\n else:\n fh.write(p_str)\n fh.close()\n\n def demat_dump_summary_ticker_only(self, out_filename):\n fh = open(out_filename, \"w\")\n for stock_symbol in sorted(self.demat_summary_rw_list):\n p_str = stock_symbol\n p_str += '\\n'\n if stock_symbol == 'Stock Symbol':\n continue\n if int(self.demat_summary_qty[stock_symbol]) > 0:\n fh.write(p_str)\n else:\n if self.debug_level > 0:\n print('stock qty 0', stock_symbol)\n fh.close()\n\n def demat_dump_summary_captype(self, out_filename):\n fh = open(out_filename, \"w\")\n fh.write(\"captype, stocks, cost value, market value, unrealized pl\\n\")\n for captype in sorted(self.amfi_captype_list):\n p_str = captype\n p_str += ','\n p_str += str(self.demat_summary_captype_stock_count[captype])\n p_str += ','\n p_str += str(self.demat_summary_captype_stock_cost_value[captype])\n p_str += ','\n p_str += str(self.demat_summary_captype_stock_market_value[captype])\n p_str += ','\n p_str += str(self.demat_summary_captype_unrealized_pl[captype])\n p_str += '\\n'\n fh.write(p_str)\n fh.close()\n\n def demat_dump_holdings_by_rank(self, out_filename):\n fh = open(out_filename, \"w\")\n fh.write('amfi_rank, amfi_ticker, amfi_cname, plan_sku, cur_sku, tbd_sku\\n')\n for ticker in sorted(self.amfi_rank, key=self.amfi_rank.__getitem__):\n rank = self.amfi_rank[ticker]\n p_str = str(rank)\n p_str += ', '\n p_str += ticker\n p_str += ', '\n p_str += self.amfi_cname[ticker]\n p_str += ', '\n\n if ticker in self.demat_summary_sku:\n cur_sku = self.demat_summary_sku[ticker]\n else:\n cur_sku = 0\n if rank <= 250:\n print(\"ticker\", ticker, \"with rank\", rank, \" doesn't have holdings\")\n # large cap\n if rank <= 100:\n plan_sku = self.demat_lc_weight\n # mid cap\n elif rank <= 250:\n plan_sku = self.demat_mc_weight\n # small cap\n else:\n plan_sku = self.demat_sc_weight \n\n tbd_sku = plan_sku - cur_sku\n\n p_str += str(plan_sku)\n p_str += ', '\n p_str += str(cur_sku)\n p_str += ', '\n if tbd_sku > 0:\n p_str += str(tbd_sku)\n else:\n p_str += str(0)\n\n p_str += '\\n'\n\n # skip dumping unless you hold it after rank 250\n if rank <= 250 or cur_sku > 0:\n fh.write(p_str)\n fh.close()\n\n def demat_summary_get_upl_pct_by_ticker(self, ticker):\n if ticker in self.demat_summary_upl_pct:\n return self.demat_summary_upl_pct[ticker]\n return 0\n\n def demat_summary_get_acp_by_ticker(self, ticker):\n if ticker in self.demat_summary_acp:\n return self.demat_summary_acp[ticker]\n return 0\n\n def demat_summary_get_qty_by_ticker(self, ticker):\n if ticker in self.demat_summary_qty:\n return self.demat_summary_qty[ticker]\n return 0\n\n def demat_summary_get_holding_value(self, ticker):\n return self.demat_summary_get_qty_by_ticker(ticker) * self.demat_summary_get_acp_by_ticker(ticker)\n\n def demat_summary_get_units_by_ticker(self, ticker):\n if ticker in self.demat_summary_sku:\n return self.demat_summary_sku[ticker]\n return 0\n\n def demat_txn_get_last_date_by_ticker(self, ticker):\n if ticker in self.demat_txn_last_date:\n return self.demat_txn_last_date[ticker]\n return '-'\n\n def demat_txn_get_first_buy_date_by_ticker(self, ticker):\n if ticker in self.demat_txn_first_buy_date:\n return self.demat_txn_first_buy_date[ticker]\n return '-'\n\n def demat_txn_get_last_type_by_ticker(self, ticker):\n if ticker in self.demat_txn_last_type:\n return self.demat_txn_last_type[ticker]\n return '-'\n","sub_path":"src/demat/demat.py","file_name":"demat.py","file_ext":"py","file_size_in_byte":18981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"133261235","text":"# coding: utf-8\nimport sys\nimport numpy as np\nimport pandas as pd\nimport pymysql\nfrom scipy.integrate import odeint\n\n\ndef fetch_data(conn, type, obj_name): # 从数据库取最近7天的记录\n data_list = []\n cursor = conn.cursor()\n\n if type == 0: # 国家级\n table_name = \"country\"\n sql = \"select time,confirm_sum,cured_sum, dead_sum,name from %s where name ='%s'\" % (table_name, obj_name)\n try:\n cursor.execute(sql)\n data_list = cursor.fetchall()\n except:\n conn.rollback()\n print(\"查询%s表失败\" % table_name)\n elif type == 1: # 省级\n table_name = \"china_city\"\n sql = \"select time,confirm_sum,cured_sum, dead_sum,name from %s where province ='%s'\" % (table_name, obj_name)\n try:\n cursor.execute(sql)\n data_list = cursor.fetchall()\n data_frame = pd.DataFrame(data_list, columns=[\"time\", \"confirm_sum\", \"cured_sum\", \"dead_sum\", \"name\"])\n the_times = data_frame.groupby(\"time\").sum()\n the_times['time'] = the_times.index\n the_times[\"name\"] = None\n the_times = the_times.reindex(columns=[\"time\", \"confirm_sum\", \"cured_sum\", \"dead_sum\", \"name\"])\n data_list = the_times.values.tolist()\n # print(data_list)\n except:\n conn.rollback()\n print(\"查询%s表失败\" % table_name)\n\n elif type == 2: # 城市级\n table_name = \"china_city\"\n sql = \"select time,confirm_sum,cured_sum, dead_sum,name from %s where name ='%s'\" % (table_name, obj_name)\n try:\n cursor.execute(sql)\n data_list = cursor.fetchall()\n except:\n conn.rollback()\n print(\"查询%s表失败\" % table_name)\n\n return list(data_list[-7:])\n\n\ndef SIR(sir, t, beta, gamma):\n \"SIR模型的微分方程\"\n S, I, R = sir\n dsdt = - beta * S * I\n didt = beta * S * I - gamma * I\n drdt = gamma * I\n return [dsdt, didt, drdt]\n\n\ndef f(beta, gamma):\n # 求解时序变化\n corr = []\n for a, b in zip(beta, gamma):\n result = odeint(SIR, [S0, I0, R0], t, args=(a, b))\n St, It, Rt = result[:, 0], result[:, 1], result[:, 2]\n corr.append(np.mean((It - data) ** 2))\n return np.array(corr)\n\n\ndef best_solve():\n # 定义粒子个数\n N = 20\n # 定义惯性因子\n w = 0.1\n # 定义C1,C2\n c1, c2 = 2, 2\n # 初始化位置\n x = np.random.uniform(0, 1, [N, 2])\n x[:, 0] *= 0.04\n x[:, 1] *= 0.25\n # 初始化速度\n v = np.random.uniform(0, 1, [N, 2])\n v[:, 0] *= 0.04 * 0.03\n v[:, 1] *= 0.25 * 0.03\n # 个体最佳位置\n p_best = np.copy(x)\n\n fitness = f(x[:, 0], x[:, 1])\n fitness = np.expand_dims(fitness, 1)\n # 群体最佳位置\n g_best = p_best[np.argmin(fitness)]\n N_step = 100\n store = np.zeros([N, N_step, 2])\n for step in range(N_step):\n # 计算速度v\n store[:, step, :] = x\n r1, r2 = np.random.random([N, 1]), np.random.random([N, 1])\n v = w * v + (1 - w) * (c1 * r1 * (p_best - x) + c2 * r2 * (g_best - x))\n # 更新位置\n x = x + v\n x = np.clip(x, 0, 0.5)\n # 计算适应度\n fitness_new = f(x[:, 0], x[:, 1])\n fitness_new = np.expand_dims(fitness_new, 1)\n fit = np.concatenate([fitness, fitness_new], 1)\n fitness = fitness_new\n # 计算个体最优解\n p_best_for_sel = np.concatenate([\n np.expand_dims(x, 1),\n np.expand_dims(p_best, 1)], 1)\n p_best = p_best_for_sel[[i for i in range(N)], np.argmin(fit, 1), :]\n fit_p = f(p_best[:, 0], p_best[:, 1])\n # 计算全局最优解\n g_best = x[np.argmin(fitness[:, 0])]\n return g_best\n\n\ndef getTotalNum(conn, type, obj_name):\n cursor = conn.cursor()\n data_list = None\n if type == 0: # 国家级\n table_name = \"country_gps\"\n sql = \"select population from %s where name ='%s'\" % (table_name, obj_name)\n try:\n cursor.execute(sql)\n data_list = cursor.fetchone()[0]\n except:\n conn.rollback()\n\n elif type == 1: # 省级\n table_name = \"china_province_gps\"\n sql = \"select population from %s where name ='%s'\" % (table_name, obj_name)\n\n cursor.execute(sql)\n data_list = cursor.fetchone()[0]\n\n elif type == 2: # 城市级\n table_name = \"china_city_gps\"\n sql = \"select population from %s where name ='%s'\" % (table_name, obj_name)\n try:\n cursor.execute(sql)\n data_list = cursor.fetchone()[0]\n except:\n conn.rollback()\n\n return data_list\n\n\nif __name__ == '__main__':\n conn = pymysql.connect(host=\"127.0.0.1\", port=3306, user=\"root\", passwd=\"root658\", db=\"covid19\", charset=\"utf8\")\n\n # 默认情况下\n type = 0\n obj_name = \"中国\"\n total_num = getTotalNum(conn, type, obj_name)\n\n ags = sys.argv\n if len(ags) == 3:\n type = int(ags[1])\n obj_name = ags[2]\n\n whole_data = fetch_data(conn, type, obj_name)\n\n conn.close()\n\n whole_data = pd.DataFrame(whole_data, columns=['time', 'confirm_sum', 'cured_sum', 'dead_sum', 'confirm_now'])\n whole_data['confirm_now'] = whole_data['confirm_sum'] - whole_data['cured_sum'] - whole_data['dead_sum']\n data = whole_data['confirm_now']\n\n I0 = whole_data['confirm_now'][0]\n R0 = whole_data['cured_sum'][0] + whole_data['dead_sum'][0]\n S0 = total_num - I0 - R0\n\n # 定义7天\n t = np.linspace(0, 6, 7)\n a, b = best_solve()\n dt = np.linspace(0, 29, 30)\n result = odeint(SIR, [S0, I0, R0], dt, args=(a, b))\n\n St = result[:, 0] # 易感染人数预测\n It = result[:, 1] # 患病人数预测\n Rt = result[:, 2] # 治愈人数 + 死亡人数 总数预测\n\n start_time = whole_data[\"time\"][0].strftime('%Y-%m-%d')\n date_list = [x.strftime('%Y-%m-%d') for x in list(pd.date_range(start=start_time, periods=30))]\n\n It = It.astype(int)\n dicts = dict(zip(date_list, It))\n for dic in dicts:\n print( dic + \":\" + str(dicts[dic]))\n\n","sub_path":"COVID19/out/production/COVID19/SIR.py","file_name":"SIR.py","file_ext":"py","file_size_in_byte":6102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"55226634","text":"from Qt import QtCore\n\nfrom openpype.lib import PypeLogger\n\n\nlog = PypeLogger().get_logger(\"SyncServer\")\n\nSTATUS = {\n 0: 'In Progress',\n 1: 'Queued',\n 2: 'Failed',\n 3: 'Paused',\n 4: 'Synced OK',\n -1: 'Not available'\n}\n\nDUMMY_PROJECT = \"No project configured\"\n\nProviderRole = QtCore.Qt.UserRole + 2\nProgressRole = QtCore.Qt.UserRole + 4\nDateRole = QtCore.Qt.UserRole + 6\nFailedRole = QtCore.Qt.UserRole + 8\n\n\ndef pretty_size(value, suffix='B'):\n for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:\n if abs(value) < 1024.0:\n return \"%3.1f%s%s\" % (value, unit, suffix)\n value /= 1024.0\n return \"%.1f%s%s\" % (value, 'Yi', suffix)\n\n\ndef convert_progress(value):\n try:\n progress = float(value)\n except (ValueError, TypeError):\n progress = 0.0\n\n return progress\n\n\ndef translate_provider_for_icon(sync_server, project, site):\n \"\"\"\n Get provider for 'site'\n\n This is used for getting icon, 'studio' should have different icon\n then local sites, even the provider 'local_drive' is same\n\n \"\"\"\n if site == sync_server.DEFAULT_SITE:\n return sync_server.DEFAULT_SITE\n return sync_server.get_provider_for_site(project, site)\n","sub_path":"openpype/modules/sync_server/tray/lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"409678046","text":"from OpenGL.GLUT import *\nfrom OpenGL.GLU import *\nfrom OpenGL.GL import *\nimport math\n\nm = 50\nr = 3\n\ndef pontoEsfera(i,j):\n theta = (i * math.pi/m) - (math.pi/2)\n phi = (j * 2 * math.pi)/m\n x = r * math.cos(theta) * math.cos(phi)\n y = r * math.sin(theta)\n z = r * math.cos(theta) * math.sin(phi)\n return x,y,z\n\ndef Esfera():\n glBegin(GL_QUAD_STRIP)\n for i in range(0,m+1):\n glColor3f(1,i/(1.0*m),1-(i/(1.0*m)))\n for j in range(0,m+1):\n glVertex3fv(pontoEsfera(i,j))\n glVertex3fv(pontoEsfera(i+1,j))\n glEnd()\n \n \ndef desenha():\n glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)\n glRotatef(10,0,0,1)\n Esfera()\n glutSwapBuffers()\n\n\ndef timer(i):\n glutPostRedisplay()\n glutTimerFunc(50,timer,1)\n\n\n# PROGRAMA PRINCIPAL\nglutInit(sys.argv)\nglutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_MULTISAMPLE)\nglutInitWindowSize(800,600)\nglutCreateWindow(\"Esfera\")\nglutDisplayFunc(desenha)\nglEnable(GL_MULTISAMPLE)\nglEnable(GL_DEPTH_TEST)\nglClearColor(0.,0.,0.,1.)\ngluPerspective(45,800.0/600.0,0.1,50.0)\nglTranslatef(0.0,0.0,-12)\n#glRotatef(45,1,1,1)\nglutTimerFunc(50,timer,1)\nglutMainLoop()","sub_path":"esferaQuadV2.py","file_name":"esferaQuadV2.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"283141860","text":"import sys\nimport pyodbc\nfrom login import *\nfrom formadmin import *\nfrom formpendaftar import *\nfrom formdokter import *\nfrom PyQt5 import QtCore, QtGui, QtWidgets, QtSql\nfrom PyQt5.QtSql import QSqlDatabase, QSqlQueryModel, QSqlQuery\nfrom PyQt5.QtWidgets import QTableView, QApplication\nfrom PyQt5.QtWidgets import *\n\nSERVER_NAME = 'DESKTOP-4E2QUI3\\SQLEXPRESS'\nDATABASE_NAME = 'db_puskesmas'\nUSERNAME = ''\nPASSWORD = ''\n\ndef messagebox(title, message):\n mess = QtWidgets.QMessageBox()\n mess.setWindowTitle(title)\n mess.setText(message)\n mess.setStandardButtons(QtWidgets.QMessageBox.Ok)\n mess.exec_()\n\ndef createConnection():\n connString = f'DRIVER={{SQL Server}};'\\\n f'SERVER={SERVER_NAME};'\\\n f'DATABASE={DATABASE_NAME}'\n\n global db\n db = QSqlDatabase.addDatabase('QODBC')\n db.setDatabaseName(connString)\n \ndef displayData(sqlStatement):\n print('processing query...')\n qry = QSqlQuery(db)\n qry.prepare(sqlStatement)\n qry.exec()\n\n model = QSqlQueryModel()\n model.setQuery(qry)\n\n view = QTableView()\n view.setModel(model)\n return view \n \ndef create_log(nik, nama, ket):\n con = pyodbc.connect('Driver={SQL Server};'\n 'Server=DESKTOP-4E2QUI3\\SQLEXPRESS;'\n 'Database=db_puskesmas;'\n 'Trusted_Connection=yes;')\n con.timeout = 0\n con.autocommit = True\n cur = con.cursor()\n querry = 'EXEC sp_AddLogLogin ?, ?, ?'\n cur.execute(querry, (nik, nama, ket))\n print(nik, nama, ket)\n \nclass loginMain(QMainWindow):\n def __init__(self):\n super().__init__()\n self.login = Ui_loginForm()\n self.login.setupUi(self)\n self.show()\n \n self.login.linePassword.setEchoMode(QtWidgets.QLineEdit.Password)\n self.login.loginButton.clicked.connect(self.autentikasi)\n \n def autentikasi(self):\n try:\n ket = \"Melakukan Login\"\n nik = self.login.lineNIK.text()\n psw = self.login.linePassword.text()\n con = pyodbc.connect('Driver={SQL Server};'\n 'Server=DESKTOP-4E2QUI3\\SQLEXPRESS;'\n 'Database=db_puskesmas;'\n 'Trusted_Connection=yes;')\n cur = con.cursor()\n querry = 'SELECT * FROM data_karyawan WHERE nik = ? AND _password = ?'\n cur.execute(querry, (nik, psw))\n records = cur.fetchall()\n loginMain.nama = records[0][3]\n loginMain.nik = records[0][0]\n if len(records)>0:\n messagebox(\"Autentikasi\", \"Login Berhasil\")\n create_log(records[0][0], records[0][3], ket)\n if records[0][2] == 'adm':\n self.form = formadmin()\n self.form.show()\n self.close()\n elif records[0][2] == 'kwn':\n self.form = formpendaftar()\n self.form.show()\n self.close()\n elif records[0][2] == 'doc':\n self.form = formdokter()\n self.form.show()\n self.close()\n else:\n print('Something went wrong')\n else:\n messagebox(\"Autentikasi\", \"Login Gagal\")\n except:\n messagebox(\"Autentikasi\", \"Login Gagal\")\n \nclass formadmin(QWidget):\n def __init__(self):\n super().__init__()\n self.formadmin = Ui_FormAdmin()\n self.formadmin.setupUi(self)\n \n self.timer = QtCore.QTimer()\n self.timer.start(1000)\n \n self.formadmin.label_nama_adm.setText(loginMain.nama)\n self.formadmin.label_nik_adm.setText(loginMain.nik)\n \n self.formadmin.button_logout.clicked.connect(self.logout)\n self.timer.timeout.connect(self.loglogin)\n \n def loglogin(self):\n SQL_STATEMENT = 'SELECT * FROM log_login_karyawan'\n self.formadmin.tableLogLogin = displayData(SQL_STATEMENT)\n self.formadmin.tableLogLogin.show()\n \n def logout(self):\n ket = 'Melakukan Logout'\n con = pyodbc.connect('Driver={SQL Server};'\n 'Server=DESKTOP-4E2QUI3\\SQLEXPRESS;'\n 'Database=db_puskesmas;'\n 'Trusted_Connection=yes;')\n cur = con.cursor()\n querry = 'SELECT * FROM data_karyawan WHERE nik = ?'\n cur.execute(querry, (loginMain.nik))\n records = cur.fetchall()\n create_log(records[0][0], records[0][3], ket)\n self.form = loginMain()\n self.form.show()\n self.close()\n\nclass formdokter(QWidget):\n def __init__(self):\n super().__init__()\n self.formdokter = Ui_FormDokter()\n self.formdokter.setupUi(self)\n \n self.formdokter.label_nama_adm.setText(loginMain.nama)\n self.formdokter.label_nik_adm.setText(loginMain.nik)\n \n self.formdokter.button_logout.clicked.connect(self.logout)\n \n def logout(self):\n ket = 'Melakukan Logout'\n con = pyodbc.connect('Driver={SQL Server};'\n 'Server=DESKTOP-4E2QUI3\\SQLEXPRESS;'\n 'Database=db_puskesmas;'\n 'Trusted_Connection=yes;')\n cur = con.cursor()\n querry = 'SELECT * FROM data_karyawan WHERE nik = ?'\n cur.execute(querry, (loginMain.nik))\n records = cur.fetchall()\n create_log(records[0][0], records[0][3], ket)\n self.form = loginMain()\n self.form.show()\n self.close()\n \nclass formpendaftar(QWidget):\n def __init__(self):\n super().__init__()\n self.formpendaftar = Ui_FormPendaftar()\n self.formpendaftar.setupUi(self)\n \n self.formpendaftar.label_nama_adm.setText(loginMain.nama)\n self.formpendaftar.label_nik_adm.setText(loginMain.nik)\n \n # self.formpendaftar.cariButton.clicked.connect(self.mencari)\n # self.formpendaftar.refreshButton.clicked.connect(self.refresh)\n # self.formpendaftar.editButtom.clicked.connect(self.edit)\n # self.formpendaftar.hapusButton.clicked.connect(self.hapus)\n \n self.formpendaftar.button_logout.clicked.connect(self.logout)\n \n def logout(self):\n ket = 'Melakukan Logout'\n con = pyodbc.connect('Driver={SQL Server};'\n 'Server=DESKTOP-4E2QUI3\\SQLEXPRESS;'\n 'Database=db_puskesmas;'\n 'Trusted_Connection=yes;')\n cur = con.cursor()\n querry = 'SELECT * FROM data_karyawan WHERE nik = ?'\n cur.execute(querry, (loginMain.nik))\n records = cur.fetchall()\n create_log(records[0][0], records[0][3], ket)\n self.form = loginMain()\n self.form.show()\n self.close()\n \nif __name__ == '__main__':\n app = QApplication(sys.argv)\n frm = loginMain()\n sys.exit(app.exec_())","sub_path":"trash/main (2).py","file_name":"main (2).py","file_ext":"py","file_size_in_byte":7063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"93936272","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/music/utils.py\n# Compiled at: 2015-04-28 15:32:14\nimport cStringIO, hashlib, logging, mimetypes, os, re, json\nfrom urllib import urlopen, urlencode, urlretrieve\nimport urllib2\nfrom lxml import etree\nimport pylast\nfrom django.core.files.uploadedfile import InMemoryUploadedFile\nfrom django.core.files import File\nfrom django.conf import settings\n\ndef _wikipedia(instance):\n from music.models import TrackContributor, Track, Album\n if isinstance(instance, TrackContributor):\n search = instance.title + ' artist band'\n else:\n if isinstance(instance, Track):\n contributors = instance.get_primary_contributors()\n if contributors:\n search = contributors[0].title + ' artist band'\n else:\n search = instance.title + ' song'\n elif isinstance(instance, Album):\n search = instance.title + ' album'\n else:\n return\n url = 'http://en.wikipedia.org/w/api.php'\n headers = {'User-Agent': 'Jmbo Show HTTP Request'}\n params = {'action': 'query', \n 'list': 'search', \n 'srsearch': unicode(search).encode('utf-8'), \n 'srlimit': 1, \n 'format': 'json'}\n request = urllib2.Request(url, urlencode(params), headers)\n response = urllib2.urlopen(request)\n data = response.read()\n struct = json.loads(data)\n try:\n title = struct['query']['search'][0]['title']\n except (KeyError, IndexError):\n return\n\n params = {'action': 'query', 'prop': 'revisions', \n 'titles': unicode(title).encode('utf-8'), \n 'rvprop': 'content', \n 'rvsection': 0, \n 'format': 'xml'}\n request = urllib2.Request(url, urlencode(params), headers)\n response = urllib2.urlopen(request)\n data = response.read()\n m = re.search('(Cover|image)[\\\\s=]*([^\\\\|]*)', data, re.M | re.I | re.DOTALL)\n if m:\n filename = m.group(2).strip()\n params = {'action': 'query', \n 'prop': 'imageinfo', \n 'titles': 'File:%s' % filename, \n 'iiprop': 'url', \n 'format': 'xml'}\n request = urllib2.Request(url, urlencode(params), headers)\n response = urllib2.urlopen(request)\n data = response.read()\n xml = etree.fromstring(data)\n el = xml.find('.//ii')\n if el is not None:\n url_attr = el.get('url')\n if url_attr:\n tempfile = urlretrieve(url_attr)\n instance.image.save(filename, File(open(tempfile[0])))\n return\n\n\ndef wikipedia(instance):\n try:\n _wikipedia(instance)\n except Exception as e:\n logging.warn('_wikipedia - title %s exception %s' % (\n instance.title, e))\n\n\ndef _lastfm(instance):\n di = getattr(settings, 'JMBO_MUSIC', {})\n try:\n api_key = settings.JMBO_MUSIC['lastfm_api_key']\n api_secret = settings.JMBO_MUSIC['lastfm_api_secret']\n except (AttributeError, KeyError):\n raise RuntimeError('Settings is not configured properly')\n\n network = pylast.LastFMNetwork(api_key=api_key, api_secret=api_secret)\n from music.models import TrackContributor, Track, Album\n if isinstance(instance, TrackContributor):\n try:\n obj = network.get_artist(instance.title)\n except pylast.WSError:\n return\n\n else:\n if isinstance(instance, Track):\n contributors = instance.get_primary_contributors()\n if contributors:\n try:\n obj = network.get_artist(contributors[0].title)\n except pylast.WSError:\n return\n\n else:\n return\n elif isinstance(instance, Album):\n tracks = instance.track_set.all()\n contributors = None\n if tracks:\n contributors = tracks[0].get_primary_contributors()\n if contributors:\n artist = contributors[0].title\n else:\n artist = None\n try:\n obj = network.get_album(artist, instance.title)\n except pylast.WSError:\n return\n\n else:\n return\n try:\n url = obj.get_cover_image()\n except pylast.WSError:\n return\n\n if url:\n filename = url.split('/')[(-1)]\n tempfile = urlretrieve(url)\n instance.image.save(filename, File(open(tempfile[0])))\n return\n\n\ndef lastfm(instance):\n try:\n _lastfm(instance)\n except Exception as e:\n logging.warn('_lastfm - title %s exception %s' % (\n instance.title, e))\n\n\ndef scrape_image(instance):\n di = getattr(settings, 'JMBO_MUSIC', {})\n scrapers = di.get('scrapers', ('lastfm', 'wikipedia'))\n for scraper in scrapers:\n globals()[scraper](instance)\n if instance.image:\n break","sub_path":"pycfiles/jmbo_music-2.0.0-py2.7/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"83592325","text":"import cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom pydub import AudioSegment\nimport os\nfrom enum import Enum\n\nvideo_link = \"DrumClip11.mp4\"\nhit_audio = \"noise_chopped.wav\"\ntracker = cv2.TrackerCSRT_create()\nvideo = cv2.VideoCapture(video_link)\n\nclass Method(Enum):\n CONTACT_NAIVE = 1\n CONTACT_1 = 2\n CONTACT_2 = 3\n CONTACT_STEREO = 4\n\n#since we don't have video support for stereo yet, do it separately from the other methods\ndef main_stereo():\n imgL = cv2.imread('stereo/hit6_left.jpg', 0)\n imgR = cv2.imread('stereo/hit6_right.jpg', 0)\n bbox = cv2.selectROI(imgL, False)\n drum_box = cv2.selectROI(imgL, False)\n \n hit = contact_made_stereo(imgL, imgR, bbox, drum_box)\n print(hit)\n\ndef main(contact_method, visualize=False):\n success, frame = video.read()\n init_frame = np.copy(frame)\n\n vh, vw = frame.shape[:2]\n\n #detection\n bbox, drum_box, person_box = object_detection(frame)\n \n h, w = bbox[2:]\n dh, dw = drum_box[2:]\n\n #tracking\n frames, locs = tracking(frame, bbox) \n\n #determine contact\n if contact_method == Method.CONTACT_NAIVE: \n #Naive way of checking contact(i.e. check if drumstick collides with drum hitbox in 2d\n contact_index = contact_made_naive(drum_box, locs, (h, w), frames)\n if visualize:\n process_frames(frames, locs, (h, w), visualize, drum_box=drum_box)\n \n \n elif contact_method == Method.CONTACT_1:\n #contact method 1\n contact_index, bar = contact_made(person_box[:2], drum_box[:2], locs, frames)\n #visualize tracking and threshold\n if visualize:\n process_frames(frames, locs, (h, w), visualize, bar=bar)\n \n elif contact_method == Method.CONTACT_2:\n #contact method 2\n contact_index = contact_made_2(person_box[:2], drum_box[:2], locs, frames)\n if visualize:\n process_frames(frames, locs, (h, w), False) #No threshold bar to visualize\n\n elif contact_method == Method.CONTACT_STEREO:\n raise NotImplementedError(\"stereo not supported with videos\")\n\n else:\n raise ValueError(\"Incorrect Method Type\")\n \n #common visualization in the video\n if visualize:\n visualize_contact(contact_index, frames)\n visualize_drumstick_path(init_frame, locs, (h, w))\n\n\n #write the video, audio and synced version\n write_video_audio(frames, contact_index, (vw, vh))\n \n\ndef object_detection(frame):\n '''\n #when selecting objects from a video clip the first time, copy down the location so no need to select it everytime \n bbox = cv2.selectROI(frame, False)\n drum_box = cv2.selectROI(frame, False)\n person_box = cv2.selectROI(frame, False)\n '''\n '''\n print(bbox)\n print(drum_box)\n print(person_box)\n return\n '''\n \n \n #drumclip10\n #bbox = (750, 325, 55, 58)\n #drum_box = (718, 347, 197, 233)\n #person_box =(497, 230, 100, 413)\n \n \n \n #drumclip11\n bbox = (859, 304, 47, 45)\n drum_box = (801, 125, 309, 454)\n person_box = (577, 7, 191, 640)\n \n return bbox, drum_box, person_box\n\ndef tracking(frame, bbox):\n tracker.init(frame, bbox)\n\n frames = []\n locs = []\n while True:\n success, frame = video.read()\n if not success:\n break\n \n ok, loc = tracker.update(frame)\n\n #we are only including the frames where tracking is sucessful, because no point of analysis if tracking fails\n if ok:\n loc = tuple(map(int, loc))\n frames.append(frame)\n locs.append(loc[:2])\n else:\n print(\"failed\")\n\n return frames, locs\n \n\n'''\nDifferent methods of checking if contact has been made\n'''\ndef contact_made_naive(drum_box, locs, stick_size, frames):\n sh, sw = stick_size\n \n contact_index = []\n \n for i in range(len(locs)):\n loc = locs[i]\n #if the drum_stick lie entirely within the drum box,\n #i.e left_side_drum < left_side_stick < right_size_stick < right_side_drum\n collide = drum_box[0] < loc[0] < loc[0] + sw < drum_box[0] + drum_box[2] and drum_box[1] < loc[1] < loc[1] + sh < drum_box[1] + drum_box[3]\n if collide:\n contact_index.append(i)\n return contact_index\n\ndef contact_made(loc_person, loc_drum, all_loc_sticks, frames, threshold=0.7):\n #threshold value can be tuned. larger value means more strict restriction\n dx, dy = loc_drum\n px, py = loc_person\n\n min_x = min(all_loc_sticks)[0]\n max_x = max(all_loc_sticks)[0]\n\n diff = max_x - min_x\n \n if loc_person[0] < loc_drum[0]:\n print(\"right\")\n #drum is on the right side, so return the stick locations that are on the right\n bar = min_x + (threshold) * diff\n contact_index = [i for i in range(len(frames)) if all_loc_sticks[i][0] > min_x + (threshold) * diff]\n else:\n print(\"left\")\n #drum is on the left side, so return the stick locations that are on the left\n bar = min_x + (1 - threshold) * diff\n contact_index = [i for i in range(len(frames)) if all_loc_sticks[i][0] < min_x + (1 - threshold) * diff]\n\n return contact_index, bar\n\ndef contact_made_2(loc_person, loc_drum, all_loc_sticks, frames):\n\n dx, dy = loc_drum\n px, py = loc_person\n\n contact_index = []\n if loc_person[0] < loc_drum[0]:\n print(\"right\")\n #detect change in direction from right to left -> hit\n for i in range(1, len(frames) - 1):\n if all_loc_sticks[i][0] > all_loc_sticks[i - 1][0] and all_loc_sticks[i][0] > all_loc_sticks[i + 1][0]:\n contact_index.append(i)\n\n else:\n print(\"left\")\n #detect change in direction from left to right -> hit\n for i in range(1, len(frames) - 1):\n if all_loc_sticks[i][0] < all_loc_sticks[i - 1][0] and all_loc_sticks[i][0] < all_loc_sticks[i + 1][0]:\n contact_index.append(i)\n\n return contact_index\n\ndef contact_made_stereo(imgL, imgR, bbox, drumbox, diff_threshold=0.35):\n\n stereo = cv2.StereoBM_create(numDisparities=160, blockSize=15)\n left_disparity = stereo.compute(imgL, imgR)\n \n drumstick_depth = np.average(left_disparity[bbox[0]: bbox[0] + bbox[2], bbox[1]: bbox[1] + bbox[3]])\n \n drum_depth = np.average(left_disparity[drumbox[0]: drumbox[0] + drumbox[2], drumbox[1]: drumbox[1] + drumbox[3]])\n\n depth_display = np.zeros(left_disparity.shape)\n\n #draw the estimate depth of drumstick and depth to demonstrate\n depth_display[drumbox[1]: drumbox[1] + drumbox[3], drumbox[0]: drumbox[0] + drumbox[2]] = int(drum_depth)\n depth_display[bbox[1]: bbox[1] + bbox[3], bbox[0]: bbox[0] + bbox[2]] = int(drumstick_depth)\n\n print(drum_depth, drumstick_depth)\n cv2.imwrite('depth_demo.jpg', depth_display)\n return abs(drumstick_depth - drum_depth) < diff_threshold * min(drumstick_depth, drum_depth)\n\ndef write_video_audio(frames, contact_index, video_size):\n vw, vh = video_size\n\n #writing the frames where tracking is successful\n codec = cv2.VideoWriter_fourcc(*'XVID')\n video_out = cv2.VideoWriter('output.mp4', codec, 20, (vw, vh))\n\n '''\n #used to visualize contacts frame by frame for debugging purposes\n for index in contact_index:\n frame = frames[index]\n cv2.imshow('img', frame)\n cv2.waitKey(0)\n '''\n \n for frame in frames:\n video_out.write(frame)\n\n video_out.release()\n\n #write the audio based on the contact frames\n out_audio = create_audio(frames, contact_index, hit_audio)\n out_audio.export('output_audio.wav', format=\"wav\")\n\n #now we have both the video and the audio, combine them\n os.system(\"ffmpeg -i output.mp4 -i output_audio.wav -y -vcodec copy -acodec copy output_vid_aud.avi\")\n \n\n'''\nA few visualization methods\n'''\n\n#visualize the threshold bar that's used in contact method 1\ndef viz_threshold(frame, min_x, max_x, bar):\n\n #draw threshold\n frame[:, int(bar): int(bar) + 5] = np.array([255, 0, 0])\n frame[:, min_x: min_x + 5] = np.array([255, 0, 0])\n frame[:, max_x: max_x + 5] = np.array([255, 0, 0])\n\n#visualize the drum location\ndef viz_drum_loc(frame, drum_box):\n top_left = (drum_box[:2])\n bot_right = (top_left[0] + drum_box[2], top_left[1] + drum_box[3])\n cv2.rectangle(frame, top_left, bot_right, (255, 0, 0), thickness=5)\n\n#visualize tracking of all the objects\ndef process_frames(frames, locs, stick_size, visualize, bar=None, drum_box=None):\n sh, sw = stick_size\n \n min_x = min(locs)[0]\n max_x = max(locs)[0]\n \n for i in range(len(frames)): \n frame = frames[i]\n loc = locs[i]\n cv2.rectangle(frame, loc, (loc[0] + sw, loc[1] + sh), (0, 255, 0), 2)\n if visualize:\n if bar:\n viz_threshold(frame, min_x, max_x, bar)\n\n if drum_box:\n viz_drum_loc(frame, drum_box)\n\n#Let the user know that a contact has been made on the screen\ndef visualize_contact(contact_index, frames):\n w, h = frames[0].shape[:2]\n for index in contact_index:\n frame = frames[index]\n cv2.rectangle(frame, (h // 2 - 200, 50), (h // 2 + 200, 200), (255, 255, 255), thickness = -1)\n cv2.putText(frame, \"boop\", (h // 2 - 180, 150), cv2.FONT_HERSHEY_SIMPLEX, 5, (0, 0, 255), thickness=5)\n\n#draw the all the locations that the drumstcik has passed through\ndef visualize_drumstick_path(init_frame, all_loc_sticks, stick_size):\n h, w = stick_size\n\n for loc in all_loc_sticks:\n cv2.circle(init_frame, (loc[0] + w // 2, loc[1] + h // 2), 2, (255, 0, 0), thickness=2)\n\n cv2.imwrite('stick_path_viz.jpg', init_frame)\n\n\n#write the audio based on the contacted frames\ndef create_audio(frames, contact_index, audio_path):\n total_length = frames * 50 #length of the video in millseconds\n\n #each frame is 50ms(20fps), drum audio is 200ms\n drum_hit = AudioSegment.from_wav(audio_path)\n if len(drum_hit) != 200:\n drum_hit = drum_hit[:200]\n\n silent_hit = AudioSegment.silent(duration=200)\n\n #the audio that matches with the video\n out_audio = AudioSegment.silent(duration=0)\n\n #we shouldn't do frame by frame because sound tends to last more than 1 frame\n for i in range(0, len(frames), 4): #4 frames per 1 interval(either silent or drum hit)\n if i in contact_index or i + 1 in contact_index or i + 2 in contact_index or i + 3 in contact_index:\n out_audio = out_audio + drum_hit\n else:\n out_audio = out_audio + silent_hit\n\n return out_audio\n\nif __name__ == '__main__':\n main(Method.CONTACT_2, visualize=True)\n #main_stereo()\n","sub_path":"Project/project_main(audio).py","file_name":"project_main(audio).py","file_ext":"py","file_size_in_byte":10640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"278709586","text":"# encoding: utf-8\n'''\nCreated on 2016/05/24\n\n@author: zero ryuu\n'''\nimport csv\nimport numpy as np\nimport random\nfrom mpmath import arange\nfrom builtins import int\n\nbasepath = 'C:/develop/workspace/pypro/data/csv/'\nmylist = np.arange(1,38,1).tolist()\n\ndef createdata():\n \n with open(basepath +'data.csv', 'w') as csvfile:\n data=[]\n writer = csv.writer(csvfile,delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL)\n for i in arange(1,100):\n data.append(random.sample(mylist, 7)) \n writer.writerows(data)\n \ndef readdata():\n pass\n\ndef calcCount():\n mydict = dict((k,0) for k in np.arange(1,38,1).tolist()) \n with open(basepath +'data.csv', 'r') as csvfile:\n f = csv.reader(csvfile)\n for row in f:\n for count in row:\n mydict[int(count)] += 1\n\n \n print(mydict.items())\nif __name__ == '__main__':\n createdata()\n calcCount()","sub_path":"com/sample/ana.py","file_name":"ana.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"598417292","text":"import json\nimport logging\nimport shlex\nimport subprocess\nimport urllib3\nfrom configparser import ConfigParser\nfrom pathlib import Path\nfrom time import sleep\nfrom urllib3.exceptions import MaxRetryError\n\nimport docker\nimport pytest\nimport sqlalchemy as sla\nfrom minio import Minio\nfrom sqlalchemy.exc import OperationalError\n\nlogger = logging.getLogger(__name__)\n\n\nREPO_ROOT = Path(__file__).resolve().parents[3]\nDB_SERVICE_NAME = 'dominode-db-dev'\n\n\n@pytest.fixture(scope='session')\ndef db_users_credentials():\n return {\n 'ppd_editor1': ('ppd_editor1', 'ppd', 'editor'),\n 'ppd_editor2': ('ppd_editor2', 'ppd', 'editor'),\n 'ppd_user1': ('ppd_user1', 'ppd', 'regular_department_user'),\n 'ppd_user2': ('ppd_user2', 'ppd', 'regular_department_user'),\n 'lsd_editor1': ('lsd_editor1', 'lsd', 'editor'),\n 'lsd_editor2': ('lsd_editor2', 'lsd', 'editor'),\n 'lsd_user1': ('lsd_user1', 'lsd', 'regular_department_user'),\n 'lsd_user2': ('lsd_user2', 'lsd', 'regular_department_user'),\n }\n\n\n@pytest.fixture(scope='session')\ndef db_admin_credentials():\n return {\n 'host': 'localhost',\n 'db': 'dominode_pytest',\n 'port': '55432',\n 'user': 'dominode_test',\n 'password': 'dominode_test',\n }\n\n\n@pytest.fixture(scope='session')\ndef db_service_file(\n db_admin_credentials,\n tmpdir_factory\n):\n\n temp_dir = tmpdir_factory.mktemp('db_service_file')\n config_path = temp_dir.join('pg_service')\n config = ConfigParser()\n config[DB_SERVICE_NAME] = {\n 'host': db_admin_credentials['host'],\n 'port': db_admin_credentials['port'],\n 'dbname': db_admin_credentials['db'],\n 'user': db_admin_credentials['user'],\n 'password': db_admin_credentials['password'],\n 'sslmode': 'disable'\n }\n with config_path.open('w') as fh:\n config.write(fh)\n return config_path.realpath()\n\n\n@pytest.fixture(scope='session')\ndef docker_client():\n return docker.from_env()\n\n\n@pytest.fixture(scope='session')\ndef db_container(docker_client, db_admin_credentials):\n container = docker_client.containers.run(\n 'postgis/postgis:12-3.0-alpine',\n detach=True,\n name=db_admin_credentials['db'],\n remove=True,\n ports={\n '5432': db_admin_credentials['port']\n },\n environment={\n 'POSTGRES_DB': db_admin_credentials['db'],\n 'POSTGRES_USER': db_admin_credentials['user'],\n 'POSTGRES_PASSWORD': db_admin_credentials['password'],\n }\n\n )\n yield container\n logger.info(f'Removing container...')\n container.stop()\n\n\n@pytest.fixture(scope='session')\ndef db_connection(db_container, db_admin_credentials):\n engine = sla.create_engine('postgresql://{user}:{password}@{host}:{port}/{db}'.format(\n user=db_admin_credentials['user'],\n password=db_admin_credentials['password'],\n host=db_admin_credentials['host'],\n port=db_admin_credentials['port'],\n db=db_admin_credentials['db']\n ))\n connected = False\n max_tries = 30\n current_try = 0\n sleep_for = 2 # seconds\n while not connected and current_try < max_tries:\n try:\n with engine.connect() as connection:\n connected = True\n yield connection\n logger.info('Closing DB connection...')\n except OperationalError:\n print(f'Could not connect to DB ({current_try + 1}/{max_tries})')\n current_try += 1\n if current_try < max_tries:\n sleep(sleep_for)\n else:\n raise\n\n\n@pytest.fixture(scope='session')\ndef bootstrapped_db_connection(db_connection, db_service_file):\n completed_process = subprocess.run(\n shlex.split(\n f'dominode-admin db bootstrap {DB_SERVICE_NAME} '\n f'--db-service-file={db_service_file}'\n ),\n capture_output=True\n )\n try:\n completed_process.check_returncode()\n except subprocess.CalledProcessError:\n print(f'stdout: {completed_process.stdout}')\n print(f'stderr: {completed_process.stderr}')\n raise\n\n\n@pytest.fixture(scope='session')\ndef db_users(\n bootstrapped_db_connection,\n db_users_credentials,\n db_service_file\n):\n for user, user_info in db_users_credentials.items():\n password, department, role = user_info\n completed_process = subprocess.run(\n shlex.split(\n f'dominode-admin db add-department-user {DB_SERVICE_NAME} '\n f'{user} {password} {department} --role={role} '\n f'--db-service-file={db_service_file}'\n ),\n capture_output=True\n )\n try:\n completed_process.check_returncode()\n except subprocess.CalledProcessError:\n print(f'stdout: {completed_process.stdout}')\n print(f'stderr: {completed_process.stderr}')\n raise\n\n\n@pytest.fixture(scope='session')\ndef minio_server_info():\n return {\n 'port': 9200,\n 'access_key': 'myuser',\n 'secret_key': 'mypassword',\n }\n\n\n@pytest.fixture(scope='session')\ndef minio_server(docker_client, minio_server_info):\n container = docker_client.containers.run(\n 'minio/minio',\n detach=True,\n command='server /data',\n name='minio-server-pytest',\n auto_remove=True,\n ports={\n 9000: minio_server_info['port']\n },\n environment={\n 'MINIO_ACCESS_KEY': minio_server_info['access_key'],\n 'MINIO_SECRET_KEY': minio_server_info['secret_key'],\n }\n )\n yield container\n logger.info(f'Removing container...')\n container.stop()\n\n\n@pytest.fixture(scope='session')\ndef minio_client(minio_server, minio_server_info):\n max_tries = 10\n sleep_for = 2 # seconds\n\n for current_try in range(1, max_tries + 1):\n print(f'current_try: {current_try}')\n try:\n endpoint = f'localhost:{minio_server_info[\"port\"]}'\n print(f'endpoint: {endpoint}')\n print(f'access_key: {minio_server_info[\"access_key\"]}')\n print(f'secret_key: {minio_server_info[\"secret_key\"]}')\n client = Minio(\n endpoint=endpoint,\n access_key=minio_server_info['access_key'],\n secret_key=minio_server_info['secret_key'],\n secure=False,\n # customizing http_client because we don't want the default\n # timeout configuration applied\n http_client=urllib3.PoolManager(\n timeout=urllib3.Timeout.DEFAULT_TIMEOUT,\n maxsize=10,\n retries=None\n )\n )\n print(f'client: {client}')\n # perform some command to see if we can connect\n result = client.list_buckets()\n print(f'result: {result}')\n break\n except MaxRetryError:\n print(\n f'Could not connect to minIO server '\n f'({current_try}/{max_tries})'\n )\n if current_try < max_tries:\n sleep(sleep_for)\n except Exception:\n raise\n else:\n raise RuntimeError(f'Gave up on minIO server')\n return client\n\n\n@pytest.fixture()\ndef minio_admin_client(minio_server, minio_server_info):\n endpoint = f'localhost:{minio_server_info[\"port\"]}'\n client = Minio(\n endpoint=endpoint,\n access_key=minio_server_info['access_key'],\n secret_key=minio_server_info['secret_key'],\n secure=False,\n )\n return client\n\n\n@pytest.fixture(scope='session')\ndef minio_users_credentials():\n return {\n 'ppd_editor1': ('ppd_editor1', 'ppd', 'editor'),\n 'ppd_editor2': ('ppd_editor2', 'ppd', 'editor'),\n 'ppd_user1': ('ppd_user1', 'ppd', 'regular_department_user'),\n 'ppd_user2': ('ppd_user2', 'ppd', 'regular_department_user'),\n 'lsd_editor1': ('lsd_editor1', 'lsd', 'editor'),\n 'lsd_editor2': ('lsd_editor2', 'lsd', 'editor'),\n 'lsd_user1': ('lsd_user1', 'lsd', 'regular_department_user'),\n 'lsd_user2': ('lsd_user2', 'lsd', 'regular_department_user'),\n }\n\n\n@pytest.fixture(scope='session')\ndef bootstrapped_minio_server(\n minio_server,\n minio_server_info,\n minio_client, # here just to make sure server is already usable\n minio_users_credentials,\n tmpdir_factory\n):\n temp_dir = tmpdir_factory.mktemp('minio_client')\n config_path = temp_dir.join('config.json')\n server_alias = 'dominode-pytest'\n config_path.write_text(\n json.dumps({\n 'version': '9',\n 'hosts': {\n server_alias: {\n 'url': f'http://localhost:{minio_server_info[\"port\"]}',\n 'accessKey': minio_server_info['access_key'],\n 'secretKey': minio_server_info['secret_key'],\n 'api': 'S3v4',\n 'lookup': 'auto',\n }\n }\n }),\n 'utf-8'\n )\n completed_process = subprocess.run(\n shlex.split(\n f'dominode-admin minio bootstrap {server_alias} '\n f'--minio-client-config-dir={temp_dir}'\n ),\n capture_output=True\n )\n try:\n completed_process.check_returncode()\n except subprocess.CalledProcessError:\n print(f'stdout: {completed_process.stdout}')\n print(f'stderr: {completed_process.stderr}')\n raise\n\n for access_key, user_info in minio_users_credentials.items():\n secret_key, department_name, role = user_info\n completed_process = subprocess.run(\n shlex.split(\n f'dominode-admin minio add-department-user {server_alias} {access_key} '\n f'{secret_key} {department_name} --role={role} '\n f'--minio-client-config-dir={temp_dir}'\n ),\n capture_output=True\n )\n try:\n completed_process.check_returncode()\n except subprocess.CalledProcessError:\n print(f'stdout: {completed_process.stdout}')\n print(f'stderr: {completed_process.stderr}')\n raise\n","sub_path":"extra/dominode-extra/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":10248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"88048138","text":"from hashlib import sha256\nfrom AESEncryptor import AESModeCTR\nfrom config import Config\nimport random\nimport asyncio\n\nTG_DC = [\n \"149.154.175.50\", \"149.154.167.51\", \"149.154.175.100\",\n \"149.154.167.91\", \"149.154.171.5\"\n]\n\n\nclass MTProxy:\n class MTProtoPacket:\n\n async def from_client_to_telegram(self, enc_data, secret):\n obf_dec_key_bytes = bytes(enc_data[0:64])\n obf_dec_key = obf_dec_key_bytes[8:40] # 8 - 39 bytes [32]\n obf_dec_iv = obf_dec_key_bytes[40:56] # 40 - 55 bytes [16]\n secret = bytes.fromhex(secret)\n dec_key = sha256()\n dec_key.update(obf_dec_key)\n dec_key.update(secret)\n obf_dec_key = dec_key.digest()\n decryptor = AESModeCTR(key=obf_dec_key,\n iv=obf_dec_iv)\n\n obf_enc_key_bytes = bytes(enc_data[8:56])[::-1]\n obf_enc_key = obf_dec_key_bytes[0:32]\n obf_enc_iv = obf_dec_key_bytes[32:48]\n enc_key = sha256()\n enc_key.update(obf_enc_key)\n enc_key.update(secret)\n obf_enc_key = enc_key.digest()\n encryptor = AESModeCTR(key=obf_enc_key,\n iv=obf_enc_iv)\n\n raw_data = decryptor.decrypt (enc_data)\n\n dc_idx = int.from_bytes (raw_data[60:62], \"little\") - 1\n if dc_idx < 0 or dc_idx >= len(TG_DC):\n raise Exception\n dc = TG_DC[dc_idx]\n if b'\\xef\\xef\\xef\\xef' == raw_data[56:60]:\n return dc, decryptor, encryptor\n else:\n raise Exception\n\n async def from_telegram_to_client(self,dc,secret):\n tg_reader, tg_writer = await asyncio.open_connection(dc, TG_DC)\n\n obf_dec_key_bytes = bytearray([random.randrange(0, 256) for i in range(64)])\n obf_dec_key_bytes[56] = obf_dec_key_bytes[57] = obf_dec_key_bytes[58] = obf_dec_key_bytes[59] = 0xef\n obf_dec_key_iv = bytes (obf_dec_key_bytes[8:56])[::-1]\n obf_dec_key = obf_dec_key_iv[0:32]\n obf_dec_iv = obf_dec_key_iv[32:48]\n decryptor = AESModeCTR(key=obf_dec_key,\n iv=obf_dec_iv)\n\n obf_enc_key_bytes = bytes (obf_dec_key_bytes)[::-1]\n obf_enc_key = obf_enc_key_bytes[8:40] # 8 - 39 bytes [32]\n obf_enc_iv = obf_enc_key_bytes[40:56] # 40 - 55 bytes [16]\n secret = bytes.fromhex (secret)\n enc_key = sha256 ()\n enc_key.update(obf_enc_key)\n enc_key.update(secret)\n obf_enc_key = enc_key.digest ()\n encryptor = AESModeCTR(key=obf_enc_key,\n iv=obf_enc_iv)\n enc_data = obf_dec_key_bytes[:56] + encryptor.encrypt(bytes(obf_dec_key_bytes))[56:]\n\n tg_writer.write(enc_data)\n await tg_writer.drain()\n\n return encryptor, decryptor, tg_reader, tg_writer\n","sub_path":"MTProtoPacket.py","file_name":"MTProtoPacket.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"534315020","text":"import datetime\nimport textwrap\n\nfrom discord.utils import sleep_until\nfrom discord.ext import commands\nfrom datetime import datetime\nfrom discord import Message\n\nfrom internal.context import Context\nfrom utilities.helpers import EmbedHelper, CustomTimeConverter, get_str_time_mapping\nfrom internal.bot import Bot\n\n\nclass Reminders(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n async def send_reminder(\n self,\n ctx: Context,\n msg: Message,\n original_time: str,\n time: datetime,\n *,\n content: str,\n ):\n\n description = textwrap.dedent(\n f\"\"\"\n Your reminder from [{get_str_time_mapping(original_time)['amount']} {get_str_time_mapping(original_time)['unit']}]({msg.jump_url}) ago has arrived:\n ```\n {content}\n ```\n \"\"\"\n )\n\n embed = EmbedHelper(\n title=\"Your reminder has arrived\",\n description=description,\n timestamp=datetime.utcnow(),\n )\n\n await sleep_until(time)\n return await ctx.reply(embed=embed)\n\n @commands.command()\n async def remind(self, ctx: Context, length: str, *, content: str):\n time = await CustomTimeConverter.convert(self, ctx, length) + datetime.utcnow()\n\n description = textwrap.dedent(\n f\"\"\"\n Your reminder will arrive in {get_str_time_mapping(length)['amount']} {get_str_time_mapping(length)['unit']}(s) with the following content:\n ```\n {content}\n ```\n \"\"\"\n )\n\n embed = EmbedHelper(\n title=\"Reminder Created\",\n description=description,\n timestamp=datetime.utcnow(),\n )\n\n msg = await ctx.send(embed=embed)\n\n await self.send_reminder(ctx, msg, length, time, content=content)\n\n\ndef setup(bot: Bot) -> None:\n bot.add_cog(Reminders(bot))\n","sub_path":"cogs/utility/reminders.py","file_name":"reminders.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"599879558","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport click\nimport time\nfrom datetime import datetime, timedelta\nfrom subprocess import call\nfrom monitor.helper import dt_now_str, load_config\nfrom monitor.log import log, setup_logging\nimport monitor.db\nimport monitor.metrics\nimport monitor.plot\nimport monitor.table\n\n\n@click.group()\ndef monitor_cli():\n \"\"\" CPU and network monitor \"\"\"\n pass\n\n@monitor_cli.command(\"db-create\")\ndef db_create():\n \"\"\" Create needed database file and tables \"\"\"\n # touch file\n path = os.getenv(\"DB_PATH\")\n open(path, \"a\").close()\n\n db = monitor.db.connect()\n cursor = db.cursor()\n\n create_tables = (\n \"\"\"\n CREATE TABLE IF NOT EXISTS observation (\n id INTEGER PRIMARY KEY,\n created_at TEXT,\n uptime TEXT,\n users INTEGER,\n load_average_1 REAL,\n load_average_5 REAL,\n load_average_15 REAL,\n network_connections INTEGER,\n processes INTEGER,\n free_memory INTEGER\n )\n \"\"\",\n \"\"\"\n CREATE TABLE IF NOT EXISTS observation_raw (\n id INTEGER PRIMARY KEY,\n observation_id INTEGER,\n description TEXT,\n output TEXT\n )\n \"\"\",\n \"\"\"\n CREATE TABLE IF NOT EXISTS network_connection (\n id INTEGER PRIMARY KEY,\n observation_id INTEGER,\n command TEXT,\n pid INTEGER,\n user TEXT,\n node TEXT,\n name TEXT\n )\n \"\"\"\n )\n\n log(\"Creating database tables\")\n\n for sql in create_tables:\n log(sql, \"DEBUG\")\n cursor.execute(sql)\n db.commit()\n\n log(\"Database created\")\n\n@monitor_cli.command(\"db-console\")\ndef db_console():\n \"\"\" Open sqlite3 console \"\"\"\n path = os.getenv(\"DB_PATH\")\n cmd = [\"sqlite3\", \"-column\", \"-header\", path]\n log(\"$ \" + \" \".join(cmd), \"DEBUG\")\n call(cmd)\n\n@monitor_cli.command(\"start\")\ndef start():\n \"\"\" Start to monitor \"\"\"\n sleep_time = int(os.getenv(\"INTERVAL\"))\n\n while True:\n log(\"Monitor gathering observations at %s\" % dt_now_str())\n\n obs_id = monitor.db.create_observation()\n obs = monitor.db.get_observation(obs_id)\n log(\"Created observation \" + str(obs), \"DEBUG\")\n\n uptime_out = monitor.metrics.get_uptime()\n monitor.db.create_observation_raw(obs_id, \"uptime\", uptime_out)\n uptime = monitor.metrics.parse_uptime(uptime_out)\n log(\"Uptime: \" + str(uptime), \"DEBUG\")\n\n net_cons_out = monitor.metrics.get_network_connections()\n monitor.db.create_observation_raw(obs_id, \"network_connections\", net_cons_out)\n net_cons = monitor.metrics.parse_network_connections(net_cons_out)\n monitor.db.create_network_connections(obs_id, net_cons)\n\n ps_cnt_out = monitor.metrics.get_process_count()\n ps_cnt_save = ps_cnt_out[:5000] + \" ...\" if len(ps_cnt_out) > 5000 else ps_cnt_out\n monitor.db.create_observation_raw(obs_id, \"process_count\", ps_cnt_save)\n ps_cnt = monitor.metrics.parse_process_count(ps_cnt_out)\n\n free_mem_out = monitor.metrics.get_free_memory()\n monitor.db.create_observation_raw(obs_id, \"free_memory\", free_mem_out)\n free_mem = monitor.metrics.parse_free_memory(free_mem_out)\n\n monitor.db.update_observation(obs_id, uptime, net_cons, ps_cnt, free_mem)\n obs = monitor.db.get_observation(obs_id)\n\n log(\"%s Going to sleep for %d sec\" % (str(obs), sleep_time))\n time.sleep(sleep_time)\n\n@monitor_cli.command(\"plot-stats\")\n@click.option(\"--start\", \"-s\", required=False, type=click.DateTime(), default=None)\n@click.option(\"--end\", \"-e\", required=False, type=click.DateTime(), default=None)\ndef plot_stats(start, end):\n \"\"\" Plot statistics \"\"\"\n if not start:\n start = datetime.now() - timedelta(hours=24)\n if not end:\n end = datetime.now()\n\n observations = monitor.db.get_observations_range(start, end)\n monitor.plot.observations(observations)\n\n@monitor_cli.command(\"print-observations\")\n@click.option(\"--start\", \"-s\", required=False, type=click.DateTime(), default=None)\n@click.option(\"--end\", \"-e\", required=False, type=click.DateTime(), default=None)\ndef plot_stats(start, end):\n \"\"\" Print observations \"\"\"\n if not start:\n start = datetime.now() - timedelta(hours=24)\n if not end:\n end = datetime.now()\n\n observations = monitor.db.get_observations_range(start, end)\n print(monitor.table.observations(observations))\n\nif __name__ == \"__main__\":\n load_config()\n setup_logging()\n monitor_cli()\n","sub_path":"monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":4763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"130259121","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nn = 10000 # кількість елементів масиву\nk = 1000 # кількість масивів\nm = 100 # кількість стовбців в гістаграмі\n\nmax = [] # випадкова величина\n\nfor i in range(n):\n y = np.random.uniform(0, 1, k)\n max.append(np.amax(y))\n\nplt.hist(max, m)\nplt.show()\n","sub_path":"np/lab_1/1.3.py","file_name":"1.3.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"323928427","text":"import grequests, json, re, time\nfrom pymongo import MongoClient\n\nclass ReceiverProcess(object):\n\tdef __init__(self, config_file_name):\n\t json_data = open(config_file_name)\n\t config = json.load(json_data)\n\t json_data.close()\n\t self.urls = [self.__get_url_for_host(config, host) for host in config['hosts']]\n\t self.mClient = MongoClient('localhost', 27017) #keep defaults for now\n\t for host in config['hosts']:\n\t \tself.mClient.test[host].remove() #remove all previous records\n\n\tdef __get_url_for_host(self, config, host):\n\t\treturn (config['base_url'] +\n\t \"?apikey={0}&limit={1}&host={2}\"\n\t ).format(config['apikey'], config['limit'], host)\n\n\tdef __store_resp(self, response, **kwargs):\n\t\thost = re.search(r'\\host=([^&=]+)', response.url).group(1)\n\t\tdb = self.mClient.test\n\t\tdata = response.text.encode('utf-8')\n\t\tdb[host].insert(json.loads(data))\n\n\tdef make_requests(self):\n\t\trs = (grequests.get(url, hooks={'response':self.__store_resp}) for url in self.urls)\n\t\tgrequests.map(rs)\n\n\tdef cleanup(self):\n\t\tself.mClient.disconnect()\n\n#keep running loop\ntry:\n\trp = ReceiverProcess('config.json')\n\twhile(True):\n\t\trp.make_requests()\n\t\ttime.sleep(1)\nexcept KeyboardInterrupt:\n\trp.cleanup()\nexcept:\n\traise\n \n","sub_path":"request_insert.py","file_name":"request_insert.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"650337219","text":"\"\"\"\nCopyright 2013 LORD MicroStrain All Rights Reserved.\n\nDistributed under the Simplified BSD License.\nSee file license.txt\n\"\"\"\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nimport webrequest\nimport httplib\nimport xdrlib\n\n\nclass AuthenticationException(Exception):\n def __init__(self, httpresponse_text):\n self.txt = httpresponse_text\n\n\nclass SensorCloudRequests:\n \"\"\"\n SensorCloudRequest allows a user to make http request to a SensorCloud Server.\n SensorCLoudRequests handles the SensorCLoud authetication and reauthentication.\n \"\"\"\n\n @property\n def authToken(self):\n return self._authToken\n\n @property\n def apiServer(self):\n return self._apiServer\n\n @property\n def deviceId(self):\n return self._deviceId\n\n def __init__(self, deviceId, deviceKey, authServer, requests = None, cache = None):\n\n assert authServer.startswith(\"http://\") or authServer.startswith(\"https://\")\n\n #if a request was passed in use it. If one wasn't passed in then we create a default RequestsFatory\n if requests:\n self._requests = requests\n else:\n self._requests = webrequest.Requests()\n\n self._deviceId = deviceId\n self._deviceKey = deviceKey\n self._authServer = authServer.lower()\n\n self._authToken = None\n self._apiServer = None\n\n self._cache = cache\n\n\n def authenticate(self):\n from sensorcloud import UserAgent\n\n #determine protocol from the auth server\n if self._authServer.startswith(\"http://\"):\n PROTOCOL = \"http://\"\n else:\n PROTOCOL = \"https://\"\n\n url = self._authServer + \"/SensorCloud/devices/\" + self._deviceId + \"/authenticate/\"\n\n request = self._requests.url(url)\\\n .param(\"version\", \"1\")\\\n .param(\"key\", self._deviceKey)\\\n .accept(\"application/xdr\")\\\n .header(\"User-Agent\", UserAgent)\\\n .get()\n\n\n\n #check the response code for success\n if request.status_code != httplib.OK:\n raise AuthenticationException(request.text)\n\n #Extract the authentication token and server from the response\n unpacker = xdrlib.Unpacker(request.raw)\n self._authToken = unpacker.unpack_string()\n self._apiServer = PROTOCOL + unpacker.unpack_string()\n if self._cache:\n self._cache.token = self._authToken\n self._cache.server = self._apiServer\n\n\n class AuthneticatedRequestBuilder(webrequest.Requests.RequestBuilder):\n\n def __init__(self, url, requests):\n webrequest.Requests.RequestBuilder.__init__(self, url)\n self._requests = requests\n\n def doRequest(self, method, url, options):\n from sensorcloud import UserAgent\n from sensorcloud import Reauthenticate\n\n requests = self._requests\n\n #if this is the first request, we won't have an authtoken and will need to authenticate\n if not requests.authToken:\n requests.authenticate()\n\n full_url = requests.apiServer + \"/SensorCloud/devices/\" + requests.deviceId + url\n\n options.addParam(\"auth_token\", requests.authToken)\n options.addHeader(\"User-Agent\", UserAgent)\n\n request = webrequest.Requests.RequestBuilder.doRequest(self, method, full_url, options)\n\n #if we get an authentication error, reatuheticate, update the authToken and try to make the request again\n if request.status_code == httplib.UNAUTHORIZED and Reauthenticate:\n\n logger.info(\"Authentication Error, reathenticating...\")\n requests.authenticate()\n\n full_url = requests.apiServer + \"/SensorCloud/devices/\" + requests.deviceId + url\n\n options.addParam(\"auth_token\", requests.authToken)\n options.addHeader(\"User-Agent\", UserAgent)\n\n request = webrequest.Requests.RequestBuilder.doRequest(self, method, full_url, options)\n\n return request\n\n\n\n\n def url(self, url):\n assert url.startswith(\"/\"), \"url is a subresorce for a device on sensorcloud and should start with a slash('/')\"\n return SensorCloudRequests.AuthneticatedRequestBuilder(url, self)\n","sub_path":"SDK/Python/sensorcloud/sensorcloudrequest.py","file_name":"sensorcloudrequest.py","file_ext":"py","file_size_in_byte":4330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"534278388","text":"\n\nfrom flask import Blueprint, render_template, request, make_response, url_for, redirect, json\nimport src.models.users.decorators as user_decorators\nfrom src.models.stores.store import Store\n\nstore_blueprint = Blueprint('stores', __name__)\n\n@store_blueprint.route(\"/\")\ndef index():\n stores = Store.get_stores()\n return render_template('stores/store_index.html', stores=stores)\n\n\n\n@store_blueprint.route('/new', methods=['POST', 'GET'])\n@user_decorators.requires_admin_priv\ndef create_store():\n\n # in case we receive GET - this is the first time the page is opened\n # in case we receive POST - we have the details\n if request.method == 'GET':\n return render_template('stores/create_store.html')\n else:\n # get from the request the newly created alert details\n name = request.form['name']\n url_prefix = request.form['url']\n tag_name = request.form['tag_name']\n # need to format the query as json\n query = json.load(request.form['query'])\n\n store = Store(name, url_prefix, tag_name, query)\n\n store.save_to_mongo()\n\n return redirect(url_for('stores.index'))\n\n\n@store_blueprint.route('/')\ndef get_store_page(store_id):\n store = Store.get_by_id(store_id)\n return render_template('stores/store.html', store=store)\n\n\n@store_blueprint.route('/delete/')\n@user_decorators.requires_admin_priv\ndef delete_store(store_id):\n store = Store.get_by_id(store_id)\n store.remove_from_mongo()\n #redirect to the next entry point\n return redirect(url_for('stores.index'))\n\n\n@store_blueprint.route('/update/', methods=['POST', 'GET'])\n@user_decorators.requires_admin_priv\ndef update_store(store_id):\n # in case we receive GET - this is the first time the page is opened\n # in case we receive POST - we have the details\n store = Store.get_by_id(store_id)\n if request.method == 'GET':\n return render_template('stores/edit_store.html', store=store)\n else:\n # get from the request the newly created alert details\n name = request.form['name']\n url_prefix = request.form['url']\n tag_name = request.form['tag_name']\n query = request.form['query']\n\n # upload from DB the store details and then set them with new data\n\n store.name = name\n store.url_prefix = url_prefix\n store.tag_name = tag_name\n store.query = query\n store.save_to_mongo()\n return redirect(url_for('stores.index'))","sub_path":"src/models/stores/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"87507219","text":"import base64\r\nimport httplib\r\nimport urllib\r\nimport sys\r\n\r\n__author__ = 'minya'\r\n\r\nclass IndexClient(object):\r\n\tdef __init__(self, topo):\r\n\t\tself._topo = topo\r\n\r\n\tdef build_request(self, point, query):\r\n\t\tslash_idx = point.find('/')\r\n\t\tpath = point[slash_idx:]\r\n\t\tport_split = point[0:slash_idx].split(':')\r\n\t\thost = port_split[0]\r\n\t\tport = port_split[1]\r\n\t\turl = path.strip() + '?' + query\r\n\t\treturn host, port, url\r\n\r\n\tdef ask_index(self, point, query):\r\n\t\thost, port, url = self.build_request(point, query)\r\n\t\tc = httplib.HTTPConnection(host, port)\r\n\t\tc.request('GET', url)\r\n\t\tr = c.getresponse()\r\n\t\treturn r\r\n\r\n\tdef talk_index(self, point, query, body):\r\n\t\thost, port, url = self.build_request(point, query)\r\n\t\tc = httplib.HTTPConnection(host, port)\r\n\t\tc.request('POST', url, body)\r\n\t\tr = c.getresponse()\r\n\t\treturn r\r\n\r\n\tdef GetResponse(self, clientId, key):\r\n\t\tcluster = self._topo.get_cluster()\r\n\t\tb64key = base64.b64encode(key)\r\n\t\tquery = urllib.urlencode({'id': clientId, \"k\" : b64key})\r\n\r\n\t\tfor point in cluster :\r\n\t\t\ttry:\r\n\t\t\t\tr = self.ask_index(point, query)\r\n\t\t\t\tres = r.read()\r\n\t\t\t\tstales = r.getheader('X-Stale-Idx')\r\n\t\t\t\tif len(stales) == 0:\r\n\t\t\t\t\treturn res\r\n\t\t\t\tfor stale in stales.split(';'):\r\n\t\t\t\t\trs = self.ask_index(stale, query)\r\n\t\t\t\t\treturn res + rs.read()\r\n\t\t\texcept Exception:\r\n\t\t\t\treturn -1\r\n\t\treturn -1\r\n\r\n\tdef Write(self, clientId, key, data):\r\n\t\tcluster = self._topo.get_cluster()\r\n\t\tb64key = base64.b64encode(key)\r\n\t\tquery = urllib.urlencode({'id': clientId, \"k\" : b64key})\r\n\r\n\t\tfor point in cluster:\r\n\t\t\ttry:\r\n\t\t\t\tr = self.talk_index(point, query, data)\r\n\t\t\t\tif r.status == 200:\r\n\t\t\t\t\treturn True\r\n\t\t\t\telse:\r\n\t\t\t\t\tsys.stderr.write(str.format('%s from %s', r.status, point))\r\n\t\t\t\t\treturn False\r\n\t\t\texcept Exception:\r\n\t\t\t\tsys.stderr.write(str.format('Exception while write to %s', point))\r\n\t\t\t\treturn False\r\n\r\n\t\tsys.stderr.write(\"Write to all replicas failed\")\r\n\t\treturn False\r\n","sub_path":"kontur/idxclient/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"365539553","text":"import googlemaps\nimport time\nfrom datetime import datetime\nfrom datetime import timedelta\nimport re\n\nclass Directions:\n #address only street & number, stat is province, country\n def __init__(self, start = \"\", endAddress = \"\"):\n self.startPoint = start\n self.endLoc = endAddress\n\n def getDirections(self):\n gmaps = googlemaps.Client(key='#')\n geocode_result = gmaps.geocode(self.startPoint)\n now = datetime.now()\n directions_result = gmaps.directions(self.startPoint,\n self.endLoc,\n mode=\"driving\", departure_time=now)\n return directions_result[0]['legs'][0]['steps']\n\n def parseDirections(self, directions):\n result = re.sub(r'<[^<]*?>', \"\", str(directions))\n return result\n\n def printDirections(self):\n direc = Directions(self.startPoint, self.endLoc)\n result = direc.getDirections()\n string = \"\"\n for i in range (0, len(result)):\n string += (str(i) + \": \" + \\\n direc.parseDirections(result[i]['html_instructions'])) + \"\\n\"\n return string\n","sub_path":"texessible/hackpack/twilioMaps.py","file_name":"twilioMaps.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"424602214","text":"import pytest\nfrom datetime import datetime\n\nfrom api.utils.models import save_to_db\n\nINVOICE_DUE_AT = datetime.utcnow()\nINVOICE_AMOUNT = 10\n\n\n@pytest.fixture\ndef _rental(db, book, customer, rental, user):\n save_to_db(db, book)\n save_to_db(db, user)\n\n customer.user_id = user.id\n save_to_db(db, customer)\n\n rental.customer_id = customer.id\n rental.book_id = book.id\n save_to_db(db, rental)\n\n return rental\n\n\ndef test_saves_invoice(_rental, customer, book):\n assert _rental.id\n assert _rental.created_at\n assert not _rental.due_at\n assert _rental.book_id == book.id\n assert _rental.customer_id == customer.id\n","sub_path":"tests/model_tests/test_rental.py","file_name":"test_rental.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"270488277","text":"\"\"\"\nWSGI config for server project.\n\nIt exposes the WSGI callable as a module-level variable named ``application``.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/\n\"\"\"\n\nimport os, sys, site\nfrom django.core.wsgi import get_wsgi_application\nsys.path.append(\"/home/dmitry/MyServer/\")\n\nsite.addsitedir('/home/dmitry/MyServer/.virtenv/VE/lib/python3.5/site-packages')\n\n#sys.path.append(\"/home/dmitry/MyServer/server\")\n#sys.path.append('/home/dmitry/MyServer/.virtenv/VE/')\n\nos.environ[\"DJANGO_SETTINGS_MODULE\"] = \"server.settings\"\n\n\nactivate_env=os.path.expanduser(\"/home/dmitry/MyServer/.virtenv/VE/bin/activate_this.py\")\nexec(open(activate_env).read(), dict(__file__=activate_env))\n\napplication = get_wsgi_application()\n","sub_path":"server/wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"481180710","text":"# coding: utf-8\n\n\"\"\" 単語の画像特徴ベクトルを計算する\n\n単語名のディレクトリに複数枚の画像が格納されたデータセットから、\n単語の画像特徴ベクトルを計算する\n\"\"\"\n\nimport os\nimport re\nimport sys\nimport cv2\nimport random\nimport numpy as np\nfrom numpy.linalg import norm\nfrom scipy import io, sparse\nfrom scipy.sparse import vstack as spvstack\nfrom collections import defaultdict\nfrom multiprocessing import Process, Queue, cpu_count\nfrom sklearn import cluster, neighbors\nfrom ..tools.util import measure_time, getFileList, myloadmat\n\nclass VisualWord(object):\n def __init__(self, corpus_dir, terms_file, header=True, visual_word=5000,\n initFeatureScale=5.0, featureScaleLevels=3, featureScaleMul=2.0, initXyStep=5,\n initImgBound=0, varyXyStepWithScale=False, varyImgBoundWithScale=False):\n\n # 並列計算のプロセス数\n self.process = cpu_count() \n # ディレクトリの設定\n self.corpus_dir = corpus_dir\n # ビジュアルワードの個数\n self.visual_word = visual_word\n # 検知器と抽出器の指定\n self.detector = cv2.FeatureDetector_create(\"Dense\")\n self.extractor = cv2.DescriptorExtractor_create('SURF')\n # パラメータ設定\n self.detector.setDouble ('initFeatureScale' , initFeatureScale) # 初期の特徴のサイズ\n self.detector.setInt ('featureScaleLevels' , featureScaleLevels) # サイズを変化させて特徴抽出を行う回数\n self.detector.setDouble ('featureScaleMul' , featureScaleMul) # サイズを変化させる大きさ Mul**(Levels-1)\n self.detector.setInt ('initXyStep' , initXyStep) # 何px毎に抽出を行うか(密度)\n self.detector.setInt ('initImgBound' , initImgBound) # 画像の端っこは特徴抽出したくないときに\n self.detector.setBool ('varyXyStepWithScale' , varyXyStepWithScale) # trueだとXyStepにMulを乗算\n self.detector.setBool ('varyImgBoundWithScale' , varyImgBoundWithScale) # falseでおk\n # 画像抽出を行うディレクトリのリストを作成する\n self.terms = []\n self.terms_dir = []\n with open(terms_file, 'r') as f:\n if header == True: # ヘッダーを捨てる\n f.readline()\n\n for line in f.readlines():\n term = line.rstrip().split(\"\\t\")[0]\n self.terms.append( term )\n self.terms_dir.append( os.path.join(corpus_dir, term) )\n\n\n @measure_time\n def training(self, save_name, sample_num):\n \"\"\" 画像のvisual_wordを決定する\n\n save_name: 保存ファイルの名前\n sample_num: 訓練に使用する画像の枚数 \n\n NOTE:visual_wordはnp.array形式で保存\n \"\"\"\n img_descs = [] # 全ての画像の特徴量\n img_files = [] # 全ての画像ファイル\n\n # 全ての画像のパスを取得\n for tgt_dir in self.terms_dir:\n jpg_files = [f for f in getFileList(tgt_dir) if f.endswith('.jpg')]\n img_files.extend( jpg_files )\n\n # 訓練データをランダムに抽出\n if (sample_num <= 0) or (sample_num > len(img_files)):\n print(\"sample_num: 0 < n < %d\" % (len(img_files)))\n sys.exit()\n samples = random.sample(img_files, sample_num)\n\n # 特徴量を取得\n print(\"Getting features...\")\n for sample in samples:\n img = cv2.imread(sample)\n descs = self._desc_extract(img)\n if (descs == None):\n print(sample)\n continue\n img_descs.extend(descs)\n img_descs = np.array(img_descs) # np.array型に変換\n\n # k-meansクラスタリング\n print(\"Running clustering...\")\n kmean = cluster.KMeans(n_clusters=self.visual_word, n_jobs=-1)\n kmean.fit(img_descs)\n\n # visual_wordを保存\n np.save(save_name, kmean.cluster_centers_)\n\n\n @measure_time\n def makematrix(self, training_data, save_name, number_of_using):\n \"\"\" 訓練データを使って単語の画像特徴行列を生成する\n\n training_data: training()で計算されたvisual_word\n save_name: 保存ファイルの名前\n \"\"\"\n centers = np.load(training_data) # ビジュアルワード\n\n # 処理するファイルを分割\n terms_dir_division = []\n for i in range(self.process):\n head = len(self.terms_dir) * i /self.process\n tail = len(self.terms_dir) * (i+1)/self.process\n terms_dir_division.append(self.terms_dir[head:tail])\n queues = [Queue() for _ in range(self.process)]\n\n # プロセスごとに処理を並列実行\n tree = neighbors.BallTree(centers, leaf_size=3000)\n for queue, data in zip(queues, terms_dir_division):\n job = Process(target=self._calc_visual_word, args=(queue, centers, tree, data, number_of_using))\n job.start()\n\n # それぞれのプロセスで得られた行列を結合\n tv_matrix = queues[0].get()\n for queue in queues[1:]:\n tv_matrix = np.vstack((tv_matrix, queue.get())) # 行列を縦に結合\n\n # mat形式で保存\n decoded_terms = map(lambda t: t.decode('utf_8'), self.terms)\n io.savemat( save_name, {'fmatrix':tv_matrix, 'terms':decoded_terms} )\n\n\n @measure_time\n def concreteness_division(self, visual_mat, language_mat,\n conc_file, conc_threshold, save_name,\n concnum_for_abst = 5):\n \"\"\" 抽象��の画像特徴量を具象語の画像特徴量を用いて計算する\n\n visual_mat: 画像に基づく行列\n language_mat: 言語に基づく行列\n conc_file: 単語とその具象度が書かれたファイル\n conc_threshold: 具象語と抽象語を分ける閾値\n save_name: 保存ファイルの名前\n concnum_for_abst: 抽象語の画像特徴を計算する際に使用する具象語の数\n\n NOTE:多分、2つの行列の単語の数が一致しないと上手く動かない\n \"\"\"\n vmatrix, vterms = myloadmat(visual_mat) # 画像行列と単語リストの読み込み\n lmatrix, lterms = myloadmat(language_mat) # 言語行列と単語リストの読み込み\n conc_dict = {} # 具象語と具象度合いの辞書\n\n # エラー処理: 言語の行列は必ずnp.array型\n if type(lmatrix) != type(np.array([])):\n print('lmatrix is not np.array type.')\n sys.exit()\n\n # 単語の具象度をファイルから読み込む\n with open(conc_file, 'r') as f:\n f.readline() # ヘッダーを捨てる\n for line in f.readlines():\n key, value = line.rstrip().split('\\t')\n conc_dict[key] = float(value)\n\n # 処理するファイルを分割\n calc_ranges = []\n for i in range(self.process):\n head = len(vterms) * i /self.process\n tail = len(vterms) * (i+1)/self.process\n calc_ranges.append( (head, tail) )\n queues = [Queue() for _ in range(self.process)]\n\n # プロセスごとに処理を並列実行\n for i in range(self.process):\n job = Process(target=self._concreteness_division_calc,\n args=(queues[i], calc_ranges[i], vmatrix, vterms, lmatrix, lterms,\n conc_dict, conc_threshold, concnum_for_abst))\n job.start()\n\n # それぞれのプロセスで得られた行列を結合\n divided_matrix = queues[0].get()\n for queue in queues[1:]:\n divided_matrix = np.vstack((divided_matrix, queue.get())) # 行列を縦に結合\n\n io.savemat( save_name, {'fmatrix':divided_matrix, 'terms':vterms} )\n\n def _concreteness_division_calc(self, queue, calc_range, vmatrix, vterms, lmatrix, lterms,\n conc_dict, conc_threshold, concnum_for_abst):\n # このプロセスが受け持つ処理範囲\n head = calc_range[0]\n tail = calc_range[1]\n N = tail - head\n # 保存用\n divided_matrix = np.zeros( (N, vmatrix.shape[1]) )\n # 添字アクセスの高速化\n indices_of_lterms = dict([(term, idx) for idx, term in enumerate(lterms)])\n indices_of_vterms = dict([(term, idx) for idx, term in enumerate(vterms)])\n\n # 単語の具象度によってベクトル計算を切り替え、\n for i, vterm in enumerate(vterms[head:tail]):\n\n # 具象語の処理(画像ベクトルをそのまま用いる)\n if conc_dict[vterm] >= conc_threshold:\n idx = indices_of_vterms[vterm]\n # idx = vterms.index(vterm)\n divided_matrix[i] = vmatrix[idx]\n\n # 抽象語の処理(言語行列において類似度の高い単語の画像ベクトルを用いる)\n else:\n tgt_index = indices_of_lterms[vterm]\n # tgt_index = lterms.index(vterm)\n tgt_vec = lmatrix[tgt_index]\n sims = np.array([self._sim_cosine(tgt_vec, vec) for vec in lmatrix])\n ranking = sims.argsort()[::-1]\n\n vector = np.zeros(vmatrix.shape[1])\n counter = 0\n for index in ranking[1:]: # 1つ目は同じ単語なので無視\n # 具象語の上位単語をk個取得\n lterm = lterms[index]\n if conc_dict.has_key(lterm) and conc_dict[lterm] > conc_threshold:\n idx = indices_of_vterms[lterm]\n # idx = vterms.index(lterm)\n vector += vmatrix[idx]\n counter += 1\n if counter == concnum_for_abst:\n vector /= concnum_for_abst\n divided_matrix[i] = vector\n break\n # 進捗表示\n # print(\"{}\".format(vterm))\n if i%50 == 0:\n print(\"pid {}:{}\".format(os.getpid(), i))\n\n queue.put(divided_matrix)\n\n\n def check_number_of_images(self, image_num):\n \"\"\" 単語の画像ファイルが指定枚数ちゃんと存在するかチェック\n\n image_num: 期待する画像の枚数\n \"\"\"\n lacking_terms = {} # 指定枚数の画像が得られていない単語とその枚数\n\n # lacking_termsに単���と枚数を格納\n for tgt_dir in self.terms_dir:\n files = os.listdir(tgt_dir)\n images = [f for f in files if f.endswith('.jpg')] # jpg画像のみ抽出\n if len(images) < image_num:\n term = os.path.basename(tgt_dir)\n lacking_terms[term] = len(images)\n\n # lacking_termsの内容を全て表示\n for term, number in lacking_terms.items():\n print(\"{}\\t{}\".format(term, number))\n\n # lacking_termsのサマリーを表示\n print(\"*---- Summary -----*\")\n values = lacking_terms.values()\n for num in range(image_num):\n print(\"{} images:\\t{}\".format(num, values.count(num)))\n print(\"Total: {}/{} NG!\".format(len(lacking_terms), len(self.terms_dir)))\n\n\n def _desc_extract(self, cv2_img):\n \"\"\" 画像から色情報を考慮した特徴量を抽出\n\n cv2_img: opencv形式の画像\n \"\"\"\n try:\n hsv = cv2.cvtColor(cv2_img, cv2.COLOR_RGB2HSV) # HSVに変換\n\n kp = self.detector.detect(cv2_img)\n _, hdesc = self.extractor.compute(hsv[:,:,0], kp) # 色相\n _, sdesc = self.extractor.compute(hsv[:,:,1], kp) # 彩度\n _, vdesc = self.extractor.compute(hsv[:,:,2], kp) # 輝度\n\n desc = (hdesc+sdesc+vdesc)/3.0\n\n except Exception as e: # 例外が起きたら例外を表示してNoneを返す\n print(e)\n return None\n\n return desc\n\n\n def _calc_visual_word(self, queue, centers, tree, image_dirs, number_of_using):\n \"\"\" 単語の画像特徴ベクトルを計算\n \"\"\"\n tv_matrix = np.zeros((len(image_dirs), centers.shape[0])) # 画像の特徴量ベクトル\n feature_extracted_imgs = 0 # 特徴量を抽出できた画像の枚数\n\n for i, tgt_dir in enumerate(image_dirs): # 1.ある単語のディレクトリを一つ選択\n print(tgt_dir)\n thumbs = [f for f in getFileList(tgt_dir) # 2.その中に含まれる画像を全て取得\n if f.endswith('.jpg')]\n base = 10 # 基数\n thumbs.sort(cmp = lambda x, y: # ファイル名の番号順にソート(http://hiroyky.blogspot.jp/2014/06/python_4.htmlを参考)\n cmp(int(re.findall(\"[0-9]+\", x)[-1], base),\n int(re.findall(\"[0-9]+\", y)[-1], base)\n ))\n\n if len(thumbs) == 0:\n # 画像が無い場合は特徴量を計算しない\n continue\n elif len(thumbs) <= number_of_using:\n # 存在する画像が計算に使用したい枚数より少ない\n ceiling = len(thumbs)\n else:\n ceiling = number_of_using\n\n # *** 保存した特徴量を使って再計算(頃合いを見て消す)\n # npys = [f for f in getFileList(tgt_dir)\n # if f.endswith('.npy')]\n # if len(npys) == ceiling: # 全ての画像の特徴量が得られている場合はそれを使う\n # for npy in npys:\n # vector = np.load(npy)[()].toarray()[0]\n # tv_matrix[i,:] += vector\n # tv_matrix[i,:] /= len(npys)\n # if i%50 == 0: # 進捗確認\n # print(\"pid {}:{}\".format(os.getpid(), i))\n # continue\n # *** (頃合いを見て消す)\n\n for thumb in thumbs[:ceiling]: # 3.それぞの画像に対して特徴量を抽出し、足し合わせる\n img = cv2.imread(thumb)\n descs = self._desc_extract(img)\n if (descs == None):\n continue\n \n # 1枚の画像の特徴ベクトルを計算\n feature_extracted_imgs += 1\n thumb_vec = sparse.lil_matrix((1, centers.shape[0]))\n for desc in descs:\n dist, idx = tree.query(desc, k=1)\n j = idx[0][0]\n thumb_vec[0,j] += 1\n\n np.save( thumb+'.npy', thumb_vec) # 1枚の画像の特徴ベクトルを保存\n tv_matrix[i,:] += thumb_vec.toarray()[0] # 画像枚数分だけ足し合わせる\n\n # 画像の枚数で割る\n tv_matrix[i,:] /= feature_extracted_imgs\n feature_extracted_imgs = 0\n\n # 進捗表示\n if i%50 == 0:\n print(\"pid {}:{}\".format(os.getpid(), i))\n\n # terms = [os.path.basename(d) for d in image_dirs]\n # terms = np.array(terms)\n # io.savemat( str(os.getpid()), {'fmatrix':tv_matrix, 'terms':terms} )\n queue.put(tv_matrix)\n\n\n def _sim_cosine(self, vector1, vector2):\n \"\"\" コサイン類似度を返す\n \"\"\"\n # どちらかのベクトルの要素が全て0か判定\n is_all_zero = np.all(vector1==0) or np.all(vector2==0)\n if is_all_zero == True:\n return 0 # 類似度の計算結果は0\n else:\n return np.dot(vector1, vector2)/(norm(vector1)*norm(vector2))\n\n","sub_path":"mypkg/matrix/visual_word.py","file_name":"visual_word.py","file_ext":"py","file_size_in_byte":16003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"514980730","text":"###\n# Copyright (c) 2016, cottongin\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions, and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions, and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the author of this software nor the name of\n# contributors to this software may be used to endorse or promote products\n# derived from this software without specific prior written consent.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n###\n\nimport supybot.conf as conf\nimport supybot.registry as registry\ntry:\n from supybot.i18n import PluginInternationalization\n _ = PluginInternationalization('Utried')\nexcept:\n # Placeholder that allows to run the plugin on a bot\n # without the i18n module\n _ = lambda x: x\n\n\ndef configure(advanced):\n # This will be called by supybot to configure this module. advanced is\n # a bool that specifies whether the user identified themself as an advanced\n # user or not. You should effect your configuration by manipulating the\n # registry as appropriate.\n from supybot.questions import expect, anything, something, yn\n conf.registerPlugin('Utried', True)\n\n\nUtried = conf.registerPlugin('Utried')\n# This is where your configuration variables (if any) should go. For example:\n# conf.registerGlobalValue(Utried, 'someConfigVariableName',\n# registry.Boolean(False, _(\"\"\"Help for someConfigVariableName.\"\"\")))\n\nconf.registerGlobalValue(Utried, 'ImgurClientId',\n registry.String(\"\", \"\"\"imgur ClientId.\"\"\", private=True))\nconf.registerGlobalValue(Utried, 'ImgurAPIKey',\n registry.String(\"\", \"\"\"imgur API key.\"\"\", private=True))\nconf.registerGlobalValue(Utried, 'ImgurURL',\n registry.String('https://api.imgur.com/3/upload.json', \"\"\"URL for imgur API.\"\"\"))\nconf.registerGlobalValue(Utried, 'utriedImage',\n registry.String(\"\", \"\"\"Path to local image to add text for utried.\"\"\", private=True))\nconf.registerGlobalValue(Utried, 'utriedFont',\n registry.String(\"\", \"\"\"Path to local font to add text for utried.\"\"\", private=True))\nconf.registerGlobalValue(Utried, 'utriedDefault',\n registry.String('http://i.imgur.com/kpIp6nN.png', \"\"\"URL for default utried picture if no text is added.\"\"\"))\n\n\n# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"225879753","text":"import pygame as pg\nimport config\n\n\n# slider(): Make the text slide across the screen\ndef effect(my_canvas, text_img):\n # go through the text message image, one slice at a time\n for my_x in range(0, config.scrollwid, config.SLICE_SIZE):\n my_y = int(config.imghgt / 2)\n my_xy = (my_x + config.scrollback, my_y + config.Y_OFFSET)\n source_area = pg.Rect((my_x, 0), (config.SLICE_SIZE, config.imghgt))\n my_canvas.blit(text_img, my_xy, source_area)\n\n return my_canvas, text_img\n","sub_path":"02_slider.py","file_name":"02_slider.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"446847629","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nfrom random import shuffle\n\n\nclass Blackjack(object):\n def __init__(self):\n self.money = 2000.00\n\n def creat_deck(self, deck=1):\n '''\n Create card function, it is possible to create a deck with more cards.\n Increases the difficulty for the player. Maximum of 8 decks.\n '''\n suits = [\"♣\", \"♦\", \"♥\", \"♠\"]\n numbers = [\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"Q\",\n \"J\", \"K\"]\n self.decks = []\n count = 0\n while count < deck:\n count += 1\n for suit in suits:\n for number in numbers:\n self.decks.append('{}{}'.format(number, suit))\n return shuffle(self.decks)\n\n def bet(self, coin, quantity):\n '''\n Betting values are defined as casino chips. That is why exist the\n exception error.\n '''\n if coin not in (1, 5, 10, 25, 50, 100):\n raise Exception('Invalid coin for bet.')\n elif self.money < (coin * quantity):\n raise Exception('Value of bet larger what your money.')\n else:\n self.money -= (coin * quantity)\n self.money += 0.01\n return self.money\n\n def play(self):\n '''\n To start the function it is necessary to have a bet, that is why the\n variable self.money receives 0.01 in the betting function, ensuring\n that a bet was made. Remember that function remove 4 cards of decks.\n '''\n self.hand = []\n self.house = []\n if self.money == 2000.00:\n raise Exception('Bet is necessary for player.')\n else:\n while len(self.hand) < 2:\n self.hand.append(self.decks.pop(0))\n self.house.append(self.decks.pop(0))\n return self.hand, self.house\n\n def show_hand(self):\n '''\n This function only shows the cards to the player. His and those in the\n house.\n '''\n msg = ('Your card: {}')\n cards = ', '.join(self.hand)\n return(msg.format(cards))\n return('House: {}, X'.format(self.house[0]))\n\n def show_points(self, count):\n '''\n Function counting the value of the cards. According to the rule if you\n have an Ace and a J, complete the value 21 or Blackjack.\n '''\n self.points = 0\n for card in count:\n value = card[:-1]\n if value in ('A' and 'J'):\n self.points += 21\n self.points -= 1\n elif value == 'A':\n self.points += 1\n elif value in ('J', 'Q', 'K'):\n self.points += 10\n else:\n self.points += int(value)\n return self.points\n","sub_path":"blackjack/blackjack.py","file_name":"blackjack.py","file_ext":"py","file_size_in_byte":2802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"449178265","text":"import numpy as np\r\nimport json\r\nimport pandas as pd\r\nfrom sklearn.model_selection import ParameterGrid\r\nimport copy\r\nimport os\r\nimport json\r\nimport joblib \r\nfrom collections import Counter, OrderedDict\r\nimport logging\r\nimport math\r\nimport torch\r\n\r\nimport matplotlib as mpl\r\nmpl.use('Agg')\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom utils.misc import list_to_dict\r\nfrom utils.training import get_folds\r\nfrom utils.arrays import get_subset \r\nfrom utils.arrays import apply_mask \r\nfrom utils.scoring import build_e2e\r\nfrom utils.seq_prep import flatten_\r\nfrom utils.misc import tuple2str, str2tuple\r\nfrom models.active_learning import active_sample, SIM_TYPE_AVG, SIM_TYPE_MAX, random_split, H_TYPE_SUM, H_TYPE_LOOP, plot_label_dist\r\nfrom utils.proj_setup import make_and_clear\r\nfrom constants import * \r\n\r\n\r\nSAMPLE_TYPE_RANDOM = 'random'\r\nSAMPLE_TYPE_ACTIVE = 'active'\r\n\r\ndef combine_multistage(scores_ss, scores_e2e):\r\n\r\n scores_ss[EVAL_RANGE] = SINGLE_STAGE\r\n scores_e2e[EVAL_RANGE] = END_TO_END\r\n \r\n # Merge single-stage and end-to-end scores\r\n return pd.concat([scores_ss, scores_e2e])\r\n \r\n\r\ndef idx_slice(X, I):\r\n '''\r\n Extract indices of I from X\r\n '''\r\n return [X[i] for i in I] \r\n\r\n\r\ndef slice_(I, args):\r\n \r\n assert len(set([len(a) for a in args])) == 1\r\n\r\n out = []\r\n for a in args:\r\n out.append([a[i] for i in I])\r\n \r\n return tuple(out)\r\n\r\ndef split_(I, J, args):\r\n \r\n assert sorted(I + J) == list(range(len(args[0])))\r\n\r\n return (slice_(I, args), slice_(J, args)) \r\n\r\ndef idx_slice2(X, Y, I):\r\n '''\r\n Extract indices of I from X\r\n '''\r\n return (idx_slice(X, I), idx_slice(Y, I))\r\n\r\n\r\ndef get_label_dist(y):\r\n \r\n if isinstance(y, list) and isinstance(y[0], dict):\r\n \r\n # Counts event-label occurrences \r\n counter = Counter()\r\n for dict_ in y:\r\n for evt_type, label in dict_.items():\r\n counter[(evt_type, label)] += 1\r\n\r\n # Convert to list of tuple\r\n counts = [(evt_type, label, cnt) \\\r\n for (evt_type, label), cnt in counter.items()]\r\n \r\n # As data frame\r\n df = pd.DataFrame(counts, columns=[EVENT_TYPE, LABEL, COUNT])\r\n\r\n return df \r\n \r\n else:\r\n TypeError(\"Invalid y type: {} with {}\".format(type(y), type(y[0])))\r\n \r\ndef to_json(path, file_name, X, indent=4):\r\n \r\n fn = os.path.join(path, file_name)\r\n with open(fn,'w') as f:\r\n json.dump(X, f, indent=indent)\r\n\r\n\r\n'''\r\nlabels = ('Python', 'C++', 'Java', 'Perl', 'Scala', 'Lisp')\r\nlabel_pos = np.arange(len(labels))\r\ncount = [10,8,6,4,2,1]\r\n\r\nplt.barh(label_pos, count, align='center', alpha=0.5)\r\nplt.yticks(label_pos, labels)\r\nplt.xlabel('Usage')\r\nplt.title('Programming language usage')\r\n'''\r\n\r\n\r\n \r\nclass Base(object):\r\n \r\n '''\r\n Base classifier\r\n '''\r\n \r\n def __init__(self, \\\r\n estimator_class, \r\n hyperparams, \r\n metric, \r\n average, \r\n scorer, \r\n neg_label, \r\n path, \r\n feat_params = None, \r\n event = None,\r\n entity = None, \r\n model_type = None,\r\n descrip = None, \r\n fit_method = 'fit', \r\n prob_method = 'predict_proba', \r\n pred_method = 'predict', \r\n get_params_method = 'get_params',\r\n \r\n ):\r\n\r\n\r\n\r\n self.estimator_class = estimator_class\r\n self.hyperparams = hyperparams\r\n self.metric = metric\r\n self.average = average\r\n self.scorer = scorer\r\n self.neg_label = neg_label\r\n \r\n \r\n self.estimator = None\r\n \r\n \r\n self.path = path\r\n self.feat_params = feat_params\r\n self.event = event\r\n self.entity = entity\r\n self.model_type = model_type\r\n self.descrip = descrip\r\n\r\n self.fit_method = fit_method\r\n self.prob_method = prob_method\r\n self.pred_method = pred_method\r\n self.get_params_method = get_params_method\r\n\r\n\r\n def save_state_dict(self, path):\r\n '''\r\n Save state dict\r\n '''\r\n \r\n torch.save(self.estimator.state_dict(), path)\r\n return True \r\n \r\n\r\n def load_state_dict(self, path):\r\n '''\r\n Load state dict\r\n '''\r\n self.estimator = self.estimator_class(**self.hyperparams)\r\n state_dict = torch.load(path, map_location=lambda storage, loc: storage)\r\n self.estimator.load_state_dict(state_dict)\r\n return True\r\n\r\n def load_pretrained(self, dir_, param_map=None):\r\n \r\n # Hyperparameters\r\n logging.info('')\r\n logging.info('-'*72)\r\n logging.info('Loading pre-trained model...')\r\n logging.info('-'*72)\r\n \r\n # Load hyper parameters\r\n fn = os.path.join(dir_, HYPERPARAMS_FILE)\r\n logging.info(\"Hyper parameters loading from:\\t{}\".format(fn))\r\n hp = json.load(open(fn,'r'))\r\n \r\n # Print hyper parameters\r\n logging.info(\"Hyper parameters loaded:\")\r\n for param, val in hp.items():\r\n logging.info(\"\\t{}:\\t{}\".format(param, val))\r\n logging.info('')\r\n\r\n # Map parameters\r\n if param_map is not None:\r\n logging.info('Mapping hyper parameters:')\r\n for name, val in param_map.items():\r\n logging.info('\\t{}: orig={},\\tnew={}'.format(name, hp[name], val))\r\n hp[name] = val\r\n\r\n # Incorporate hyper parameters into model\r\n self.hyperparams = hp\r\n logging.info('self.hyperparams updated')\r\n \r\n # Load saved estimator\r\n fn = os.path.join(dir_, STATE_DICT)\r\n logging.info(\"State dict loading from:\\t{}\".format(fn))\r\n self.load_state_dict(fn)\r\n logging.info(\"State dict loaded\")\r\n \r\n logging.info('Pre-trained model loaded')\r\n logging.info('')\r\n logging.info('')\r\n\r\n\r\n def fit_preprocess_X(self, X):\r\n '''\r\n Placeholder for fitting preprocessing function for features\r\n '''\r\n pass\r\n \r\n\r\n def fit_preprocess_y(self, y):\r\n '''\r\n Placeholder for fitting preprocessing function for labels\r\n '''\r\n pass\r\n\r\n def preprocess(self, X, y):\r\n '''\r\n Placeholder for preprocessing features and labels\r\n (e.g. convert feature dictionaries to one hot encodings)\r\n '''\r\n return (X, y)\r\n\r\n \r\n def postprocess(self, X, y):\r\n '''\r\n Placeholder for postprocessing features and labels\r\n\r\n '''\r\n return (X, y)\r\n\r\n def postprocess_prob(self, X, y_prob):\r\n '''\r\n Placeholder for postprocessing features and probabilities\r\n\r\n '''\r\n return y_prob\r\n\r\n def apply_mask(self, X, mask=None):\r\n '''\r\n Apply mask to input, returning masked to version\r\n '''\r\n \r\n # If no mask provide, include all\r\n if mask is None:\r\n return X\r\n \r\n # Return none if X None\r\n if X is None:\r\n return X\r\n \r\n # Use mask to extract subset of features and labels\r\n else: \r\n return apply_mask(X, mask)\r\n\r\n def get_default_prob(self, y_prob):\r\n '''\r\n Get default probability, based on probably predictions\r\n '''\r\n\r\n # Set all label probabilities to 0\r\n d = {lab:0.0 for lab, prob in y_prob[0].items()}\r\n \r\n # Assign all probability mass to negative label\r\n d[self.neg_label] = 1.0\r\n \r\n return d\r\n \r\n def restore_mask(self, X_e2e, y_ss, mask, default_val=None):\r\n '''\r\n Restore (unmask) predictions\r\n ''' \r\n \r\n # Update default value if not provided\r\n if default_val is None:\r\n default_val = self.neg_label\r\n \r\n # If no mask provide, assume all predictions present\r\n if mask is None:\r\n mask = [1]*len(X_e2e)\r\n \r\n # Get end-to-end labels\r\n y_e2e = build_e2e(X_e2e, y_ss, mask, default_val)\r\n \r\n return y_e2e\r\n \r\n\r\n def post_train(self):\r\n '''\r\n Placeholder for any post training actions\r\n '''\r\n return True \r\n\r\n def dump(self, directory, fn):\r\n '''\r\n Save classifier to directory, with default model name\r\n '''\r\n \r\n # Save classifier \r\n joblib.dump(self, os.path.join(directory, fn))\r\n\r\n\r\n def save_predictions(self, path, y_pred):\r\n\r\n fn = os.path.join(path, PREDICTIONS_FILE)\r\n joblib.dump(y_pred, fn)\r\n \r\n return True\r\n\r\n def save_scores(self, path, scores):\r\n \r\n \r\n if isinstance(scores, dict):\r\n\r\n for k, df in scores.items():\r\n\r\n # Save scores delimited text file\r\n fn = os.path.join(path, 'scores_{}.csv'.format(k))\r\n df.to_csv(fn)\r\n \r\n \r\n else: \r\n \r\n # Save scores delimited text file\r\n fn = os.path.join(path, SCORES_FILE)\r\n scores.to_csv(fn, index=False)\r\n \r\n return True\r\n\r\n\r\n def save_sweeps(self, path, sweeps):\r\n\r\n if sweeps is not None:\r\n fn = os.path.join(path, SWEEPS_FILE)\r\n sweeps.to_csv(fn, index=True)\r\n \r\n return True \r\n\r\n\r\n def save_hyperparams(self, path, params):\r\n fn = os.path.join(path, HYPERPARAMS_FILE)\r\n with open(fn, 'w') as f:\r\n json.dump(params, f)\r\n\r\n def save_featparams(self, path, params):\r\n fn = os.path.join(path, FEATPARAMS_FILE)\r\n with open(fn, 'w') as f:\r\n json.dump(params, f) \r\n\r\n def save_descrip(self, path, descrip):\r\n fn = os.path.join(path, DESCRIP_FILE)\r\n with open(fn, 'w') as f:\r\n json.dump(descrip, f)\r\n\r\n\r\n def save_results(self, path, y_pred, scores, sweeps=None):\r\n '''\r\n Save results to disk\r\n ''' \r\n \r\n # Save predictions\r\n self.save_predictions(path, y_pred)\r\n \r\n # Save scores\r\n self.save_scores(path, scores)\r\n \r\n # Save sweeps as spreadsheet\r\n self.save_sweeps(path, sweeps)\r\n \r\n return True \r\n\r\n\r\n def fit(self, X, y, mask=None, post_train=True):\r\n '''\r\n Fit estimator to data\r\n '''\r\n\r\n # Apply mask\r\n X = self.apply_mask(X, mask)\r\n y = self.apply_mask(y, mask)\r\n\r\n # Preprocess X and y\r\n X, y = self.preprocess(X, y)\r\n\r\n # Estimator not initialized\r\n if self.estimator is None:\r\n self.estimator = self.estimator_class(**self.hyperparams)\r\n\r\n # Fit to data\r\n self.estimator.fit(X, y)\r\n\r\n # Post training actions\r\n if post_train:\r\n self.post_train() \r\n \r\n return True \r\n\r\n\r\n def predict_sub_op(self, X):\r\n '''\r\n Predict labels, without any masking\r\n '''\r\n \r\n # Preprocess X (y not available)\r\n X, _ = self.preprocess(X, None)\r\n \r\n # Get predictions\r\n y = self.estimator.predict(X)\r\n \r\n # Postprocess predictions\r\n _, y = self.postprocess(None, y)\r\n\r\n return y \r\n \r\n def prob_sub_op(self, X):\r\n '''\r\n Predict probabilities, without any masking\r\n '''\r\n \r\n # Preprocess X (y not available)\r\n X, _ = self.preprocess(X, None)\r\n \r\n # Get probability predictions\r\n y = self.estimator.proba(X) \r\n \r\n # Postprocess probability predictions\r\n _, y = self.postprocess_prob(None, y)\r\n\r\n return y\r\n\r\n def predict(self, X, mask=None):\r\n '''\r\n Predict labels, potentially with masking\r\n '''\r\n \r\n # Apply mask\r\n X_ss = self.apply_mask(X, mask) \r\n \r\n # Get predictions\r\n y_ss = self.predict_sub_op(X_ss)\r\n \r\n # Restore/unmask\r\n if mask is None:\r\n return y_ss\r\n else:\r\n y_e2e = self.restore_mask( \\\r\n X_e2e = X, \r\n y_ss = None, \r\n mask = mask)\r\n return y_e2e \r\n\r\n def predict_proba(self, X, mask=None):\r\n '''\r\n Predict label probability, potentially with masking\r\n '''\r\n \r\n # Apply mask\r\n X_ss = self.apply_mask(X, mask) \r\n \r\n # Get predictions\r\n y_prob_ss = self.prob_sub_op(X_ss)\r\n \r\n ## Get default probability\r\n #default_val = self.get_default_prob(y_prob_ss)\r\n \r\n # Restore/unmask\r\n #y_prob_e2e = self.restore_mask( \\\r\n # X_e2e = X, \r\n # y_ss = y_prob_ss, \r\n # mask = mask,\r\n # default_val = default_val)\r\n x = ss \r\n #return y_prob_e2e \r\n return y_prob_ss\r\n\r\n\r\n def get_params(self):\r\n params = {}\r\n params.update(self.hyperparams)\r\n if self.feat_params is not None:\r\n params.update(self.feat_params)\r\n params.update({'model_type': self.model_type,\r\n 'descrip': self.descrip}\r\n\r\n #params.update({'event': self.event, \r\n # 'entity': self.entity}\r\n\r\n )\r\n return params\r\n\r\n def score(self, X, y, mask=None, path=None):\r\n '''\r\n Predict labels and score result\r\n '''\r\n\r\n # Preprocess labels\r\n _, y = self.preprocess(None, y)\r\n \r\n # Apply mask\r\n X_ss = self.apply_mask(X, mask)\r\n y_ss = self.apply_mask(y, mask) \r\n \r\n # Get predictions\r\n y_pred_ss = self.predict_sub_op(X_ss)\r\n \r\n # Score single state results\r\n scores_ss = self.scorer.fit(y_ss, y_pred_ss, \\\r\n params=self.get_params())\r\n\r\n if mask is None:\r\n\r\n # Save results\r\n if path is not None:\r\n self.save_results(path, y_pred_ss, scores_ss, None)\r\n \r\n return (y_pred_ss, scores_ss)\r\n\r\n else: \r\n\r\n # Restore/unmask\r\n y_pred_e2e = self.restore_mask(X, y_pred_ss, mask = mask)\r\n \r\n # Evaluate end-to-end performance\r\n scores_e2e = self.scorer.fit(y, y_pred_e2e, params=self.get_params())\r\n \r\n # Merge single-stage and end-to-end scores\r\n scores = combine_multistage(scores_ss, scores_e2e)\r\n\r\n # Save results\r\n if path is not None:\r\n self.save_results(path, y_pred_e2e, scores, None)\r\n \r\n return (y_pred_e2e, scores)\r\n \r\n\r\n def cv_predict(self, X, y, cv, \\\r\n tune = False, \\\r\n params = None, \r\n mask = None,\r\n retrain = False,\r\n path = None): \r\n '''\r\n Run estimator to make predictions \r\n \r\n args:\r\n tune: Boolean, True = tune hyper parameters\r\n False = do not tune, just predict\r\n \r\n returns:\r\n truth, predictions, and label probabilities\r\n \r\n '''\r\n\r\n # Model hyperparams\r\n hyperparams = {}\r\n for k, v in self.hyperparams.items():\r\n hyperparams[k] = v\r\n if params is not None:\r\n hyperparams.update(params)\r\n\r\n # Apply mask\r\n X_ss = self.apply_mask(X, mask)\r\n y_ss = self.apply_mask(y, mask)\r\n\r\n # Create folds\r\n folds = get_folds(X_ss, y_ss, cv, tune)\r\n \r\n # Loop on folds\r\n y_true_ss = []\r\n y_pred_ss = [] \r\n for i, (X_fit, y_fit, X_eval, y_eval) in enumerate(folds):\r\n\r\n # Fit to folds\r\n self.estimator = self.estimator_class(**hyperparams)\r\n self.fit(X_fit, y_fit, mask=None, post_train=False) \r\n\r\n # Aggregate results\r\n y_pred_ss.extend(self.predict_sub_op(X_eval)) \r\n y_true_ss.extend(y_eval)\r\n \r\n # Get an update parameters\r\n params_tmp = copy.deepcopy(self.get_params())\r\n params_tmp.update(hyperparams)\r\n\r\n # Preprocess labels\r\n _, y_true_ss = self.preprocess(None, y_true_ss)\r\n\r\n # Score result\r\n scores_ss = self.scorer.fit(y_true_ss, y_pred_ss, params=params_tmp) \r\n\r\n # If not tune, then all records include predictions\r\n # so determine end-to-end results.\r\n if (mask is not None) and (not tune):\r\n \r\n # Restore/unmask\r\n y_pred_e2e = self.restore_mask(X, y_pred_ss, mask=mask)\r\n _, y_true_e2e = self.preprocess(None, y)\r\n \r\n # Evaluate end-to-end performance\r\n scores_e2e = self.scorer.fit(y_true_e2e, y_pred_e2e, params=params_tmp)\r\n \r\n # Merge single-stage and end-to-end scores\r\n scores = combine_multistage(scores_ss, scores_e2e)\r\n \r\n # Only return single-state results\r\n else:\r\n scores = scores_ss\r\n y_pred_e2e = None\r\n \r\n # Re-train model with best parameters\r\n if retrain: \r\n \r\n # Update model parameters \r\n self.hyperparams = hyperparams\r\n \r\n # Fit model\r\n self.estimator = self.estimator_class(**self.hyperparams)\r\n self.fit(X_ss, y_ss, mask = None, post_train = True) \r\n\r\n # Save results\r\n if path is not None:\r\n self.save_results(path, y_pred_e2e, scores, None)\r\n \r\n return (y_pred_e2e, scores)\r\n\r\n def cv_tune(self, X, y, cv, param_sweep,\r\n tune = False, \\\r\n params = None, \r\n mask = None,\r\n retrain = False,\r\n path = None): \r\n '''\r\n Cross-validation runs for tuning hyper parameters\r\n '''\r\n\r\n # Create exhaustive parameter grid\r\n sweep_params = list(ParameterGrid(param_sweep))\r\n\r\n # Initialize output score vector\r\n sweeps = np.zeros((len(sweep_params),))-1 \r\n\r\n # Loop on parameter combos\r\n all_scores = []\r\n all_hyperparams = []\r\n for param_idx, params in enumerate(sweep_params):\r\n\r\n # Parameters for current run \r\n current_params = self.hyperparams.copy()\r\n current_params.update(params)\r\n \r\n # Get performance with current parameters\r\n y_pred, scores = self.cv_predict(X, y, cv, \\\r\n tune = True, \\\r\n params = current_params, \r\n mask = mask,\r\n retrain = False,\r\n path = None)\r\n \r\n all_scores.append(scores)\r\n all_hyperparams.append(current_params)\r\n \r\n # Extract evaluation metric \r\n sweeps[param_idx] = \\\r\n scores.loc[scores[LABEL] == self.average][self.metric].values[0]\r\n \r\n # Best param set\r\n idx = np.argmax(sweeps)\r\n best_param = all_hyperparams[idx]\r\n best_scores = all_scores[idx]\r\n\r\n # Parameters sweep results per fold, as dataframe\r\n col = ['{}_{}'.format(self.average, self.metric)]\r\n dfscores = pd.DataFrame(sweeps, columns=col) \r\n dfparams = pd.DataFrame(sweep_params)\r\n dfsweeps = pd.concat([dfparams, dfscores], axis=1)\r\n\r\n # Save results\r\n if path:\r\n \r\n # Save scores\r\n self.save_scores(path, best_scores)\r\n \r\n # Save sweeps as spreadsheet\r\n self.save_sweeps(path, dfsweeps) \r\n \r\n # Save hyper and feature parameters\r\n self.save_hyperparams(path, best_param)\r\n self.save_featparams(path, self.feat_params)\r\n self.save_descrip(path, self.descrip)\r\n\r\n\r\n return (best_param, best_scores, dfsweeps)\r\n\r\n\r\n def active_learn(self, \\\r\n X_pool, \r\n y_pool, \r\n i_pool,\r\n X_eval, \r\n y_eval, \r\n i_eval, \r\n hyperparams, \r\n X_init = None,\r\n y_init = None,\r\n i_init = None, \r\n model_dir_init = None,\r\n n_init = 100,\r\n n_batch = 50,\r\n n_batches = 1,\r\n sample_type = SAMPLE_TYPE_RANDOM,\r\n embed_pool = None,\r\n entropy_type = H_TYPE_LOOP,\r\n sim_type = SIM_TYPE_MAX,\r\n alpha = 1.0,\r\n path = None,\r\n col_val_filt = None,\r\n metric = None,\r\n seeds = None,\r\n param_map = None):\r\n\r\n logging.info(\"\")\r\n logging.info(\"Active learning training\")\r\n\r\n # Consolidate subset of parameters\r\n params = {} \r\n params['n_init'] = n_init if X_init is None else len(X_init)\r\n params['n_batch'] = n_batch\r\n params['sample_type'] = sample_type\r\n params['entropy_type'] = entropy_type\r\n params['sim_type'] = sim_type\r\n params['alpha'] = alpha\r\n params['col_val_filt'] = col_val_filt\r\n params['metric'] = metric\r\n params.update(hyperparams)\r\n \r\n \r\n # Check lengths\r\n assert len(set([len(X_pool), len(y_pool), len(i_pool)]))==1\r\n assert len(set([len(X_eval), len(y_eval), len(i_eval)]))==1\r\n if X_init is not None:\r\n assert len(set([len(X_init), len(y_init), len(i_init)]))==1\r\n assert (embed_pool is None) or (len(embed_pool) == len(X_pool))\r\n\r\n # Get data set sizes\r\n logging.info('') \r\n logging.info('Input sizes:')\r\n logging.info(\"Pool size:\\t{}\".format(len(X_pool)))\r\n logging.info(\"Eval size:\\t{}\".format(len(X_eval)))\r\n logging.info(\"Initial size:\\t{}\".format(None if X_init is None else len(X_init)))\r\n\r\n # Get next seed\r\n seed = None if seeds is None else seeds.pop()\r\n \r\n # Initial training data not provided, sample from training pool\r\n logging.info('')\r\n logging.info('Initial batch set up')\r\n if X_init is None:\r\n\r\n logging.info('Initial training data NOT provided.')\r\n logging.info('Sampling initial training data from training pool.')\r\n logging.info(\"Initial training size:\\t{}\".format(n_init))\r\n\r\n # Start with indices for all training data\r\n idx_pool = list(range(len(X_pool)))\r\n\r\n # Randomly sample initial training data from pool\r\n idx_init, _, idx_pool, _ = random_split(idx_pool, n_init, seed=seed)\r\n \r\n # Initial and pool subsets\r\n X_init, y_init, i_init = slice_(idx_init, (X_pool, y_pool, i_pool))\r\n X_pool, y_pool, i_pool = slice_(idx_pool, (X_pool, y_pool, i_pool))\r\n \r\n # Initial training data provided\r\n else: \r\n n_init = len(X_init)\r\n logging.info('Initial training data provided')\r\n logging.info('Overriding provided n_init value')\r\n logging.info(\"Init size:\\t{}\".format(n_init))\r\n\r\n # Get data set sizes\r\n n_pool = len(X_pool)\r\n n_eval = len(X_eval) \r\n n_init = len(X_init) \r\n logging.info('') \r\n logging.info('Input sizes after setup:')\r\n logging.info(\"Pool size:\\t{}\".format(n_pool))\r\n logging.info(\"Eval size:\\t{}\".format(n_eval))\r\n logging.info(\"Init size:\\t{}\".format(n_init))\r\n\r\n # Total training samples\r\n n_train = n_init + n_pool\r\n \r\n # Create round-specific directory\r\n path_ = os.path.join(path, 'round_{}'.format(0))\r\n make_and_clear(path_)\r\n\r\n # Record IDs\r\n to_json(path_, 'ids_pool.json', i_pool)\r\n to_json(path_, 'ids_eval.json', i_eval)\r\n to_json(path_, 'ids_init.json', i_init)\r\n \r\n '''\r\n Iterate over training batches\r\n '''\r\n \r\n # Set current training data to initial training data\r\n X_fit = X_init[:]\r\n y_fit = y_init[:]\r\n i_fit = i_init[:]\r\n i_fit_all = OrderedDict()\r\n # Loop on training batches \r\n scores = []\r\n dfs_labels = []\r\n for i in range(n_batches + 1):\r\n\r\n\r\n assert n_train == len(X_fit) + len(X_pool)\r\n assert len(set([len(X_fit), len(y_fit), len(i_fit) ]))==1 \r\n assert len(set([len(X_pool), len(y_pool), len(i_pool)]))==1\r\n\r\n # Indices of pool\r\n idx_pool = list(range(len(X_pool)))\r\n\r\n # Create round-specific directory\r\n path_ = os.path.join(path, 'round_{}'.format(i))\r\n make_and_clear(path_)\r\n \r\n # Initial round for initial training\r\n if i == 0:\r\n idx_batch = []\r\n idx_pool = idx_pool\r\n\r\n\r\n # Random selection\r\n elif sample_type == SAMPLE_TYPE_RANDOM:\r\n \r\n seed = None if seeds is None else seeds.pop()\r\n idx_batch, _, idx_pool, _ = \\\r\n random_split(idx_pool, n_batch, seed=seed)\r\n fn = os.path.join(path_, 'random_sampling.txt')\r\n with open(fn,'w') as f:\r\n f.write('{} random samples drawn uisng seed={}'.format(n_batch, seed))\r\n \r\n # Active selection \r\n elif sample_type == SAMPLE_TYPE_ACTIVE:\r\n \r\n # Get relevant embeddings \r\n \r\n # Generate entropy scores\r\n prob_pool, entropy_pool = self.estimator.entropy(X_pool)\r\n \r\n assert len(X_pool) == len(embed_pool)\r\n assert len(X_pool) == len(entropy_pool)\r\n\r\n # Select batch\r\n idx_batch, idx_pool = active_sample( \\\r\n sample_count = n_batch, \r\n ids = idx_pool, \r\n embed = embed_pool, \r\n entropy = entropy_pool, \r\n entropy_type = entropy_type,\r\n sim_type = sim_type,\r\n alpha = alpha,\r\n path = path_,\r\n docs = X_pool,\r\n prob = prob_pool)\r\n embed_pool, = slice_(idx_pool, (embed_pool,))\r\n \r\n else:\r\n raise ValueError(\"Invalid sample_type:\\t{}\".format(sample_type))\r\n\r\n\r\n assert n_train == len(X_fit) + len(X_pool)\r\n assert len(set([len(X_fit), len(y_fit), len(i_fit) ]))==1 \r\n assert len(set([len(X_pool), len(y_pool), len(i_pool)]))==1\r\n\r\n\r\n # Separate batch and remaining pool\r\n X_batch, y_batch, i_batch = slice_(idx_batch, (X_pool, y_pool, i_pool))\r\n X_pool, y_pool, i_pool = slice_(idx_pool, (X_pool, y_pool, i_pool))\r\n \r\n # Add training data to fit\r\n X_fit.extend(X_batch)\r\n y_fit.extend(y_batch)\r\n i_fit.extend(i_batch)\r\n i_fit_all[i] = i_fit[:]\r\n \r\n # Get label distribution for selected batch \r\n df = get_label_dist(y_fit)\r\n df[ROUND] = i\r\n dfs_labels.append(df)\r\n\r\n logging.info(\"\")\r\n logging.info(\"=\"*72)\r\n logging.info(\"Training batch:\\t\\t{} of {}\".format(i+1, n_batches))\r\n logging.info(\"=\"*72)\r\n logging.info(\"Samples in batch:\\t{}\".format(len(X_batch)))\r\n logging.info(\"Samples in train:\\t{}\".format(len(X_fit)))\r\n logging.info(\"Samples in pool:\\t{}\".format(len(X_pool)))\r\n \r\n \r\n # Fit model to batch\r\n\r\n # Initial round for initial training\r\n if (i == 0) and (model_dir_init is not None):\r\n self.load_pretrained(dir_=model_dir_init, param_map=param_map)\r\n logging.info('')\r\n logging.info('Loading initial model')\r\n logging.info('')\r\n \r\n\r\n fn = os.path.join(path_, 'loaded pre-trained.txt')\r\n with open(fn,'w') as f:\r\n f.write('Loaded pre-trained model from: {}'.format(model_dir_init))\r\n\r\n \r\n else: \r\n self.estimator = self.estimator_class(**hyperparams)\r\n self.fit(X_fit, y_fit, mask=None, post_train=False) \r\n\r\n # Get predictions\r\n y_pred = self.predict(X_eval)\r\n _, y_true = self.preprocess(None, y_eval)\r\n\r\n # Score result\r\n s = self.scorer.fit(y_true, y_pred, params=params) \r\n s['train count'] = len(X_fit)\r\n s['corpus fraction'] = len(X_fit)/n_train\r\n s['round'] = i\r\n scores.append(s)\r\n\r\n assert n_train == len(X_fit) + len(X_pool)\r\n assert len(set([len(X_fit), len(y_fit), len(i_fit) ]))==1 \r\n assert len(set([len(X_pool), len(y_pool), len(i_pool)]))==1\r\n \r\n to_json(path, 'ids_fit.json', i_fit_all)\r\n\r\n scores = pd.concat(scores)\r\n fn = os.path.join(path, SCORES_FILE)\r\n scores.to_csv(fn)\r\n\r\n # Aggregate label distributions\r\n dfs_labels = pd.concat(dfs_labels)\r\n fn = os.path.join(path, 'label_dist.png')\r\n plot_label_dist(dfs_labels, fn)\r\n fn = os.path.join(path, 'label_dist.csv')\r\n dfs_labels.to_csv(fn)\r\n \r\n \r\n if (col_val_filt is not None) and (metric is not None):\r\n summary = scores.copy()\r\n for col, val in col_val_filt:\r\n summary = summary[summary[col]==val]\r\n \r\n \r\n fn = os.path.join(path, 'summary.csv')\r\n summary.to_csv(fn)\r\n\r\n plot = summary.plot(x ='corpus fraction', y=metric, kind='bar')\r\n\r\n # Save plot\r\n fig = plot.get_figure()\r\n fn = os.path.join(path, 'summary.png')\r\n fig.savefig(fn)\r\n plt.close()\r\n \r\n return scores\r\n\r\n\r\n","sub_path":"code/models/Base.py","file_name":"Base.py","file_ext":"py","file_size_in_byte":30846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"336815287","text":"import requests\nimport time\n\n# Get data.go.th COVID-19 cases dataset\nprint(\"Downloading Provincial dataset\")\nurl = \"https://data.go.th/dataset/8a956917-436d-4afd-a2d4-59e4dd8e906e/resource/be19a8ad-ab48-4081-b04a-8035b5b2b8d6/download/confirmed-cases.csv\"\npath = \"./dataset.csv\"\n\nstart = time.time()\nreq = requests.get(url)\nreq.encoding = \"utf-8\"\n\nif (req.status_code == 200) :\n print(\"Provincial dataset downloaded, Took:\", time.time()-start, \"seconds\")\n # Dataset typo corrections\n start = time.time()\n text = req.text.replace(\"ุุ\", \"ุ\") \n text = text.replace(\"เเ\", \"แ\") \n text = text.replace(\"อ.\", \"\")\n text = text.replace(\"จ.\", \"\")\n text = text.replace(\"กทม\", \"กรุงเทพมหานคร\")\n text = text.replace(\"กำแพงเพฃร\", \"กำแพงเพชร\")\n text = text.replace(\"ลพบรี\", \"ลพบุรี\")\n with open(path, \"w+\", encoding=\"utf-8\") as fout :\n fout.write(text)\n print(\"Provincial dataset written to\", path+\",\", \"Took:\", time.time()-start, \"seconds\")\nelse :\n print(\"Error occured while getting datasets\")\n print(\"Error Code :\", req.status_code)\n","sub_path":"bot_jobs/get_provincial_dataset.py","file_name":"get_provincial_dataset.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"5632100","text":"from collections import namedtuple\n\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\n\nfrom . import layers\nfrom ... import model\n\n\nclass Model(model.GenerativeModelBase):\n \"\"\"VAE model.\"\"\"\n name = 'vae'\n batch_size = 128\n\n # Results of internal model operations.\n model_type = namedtuple('VAE', [\n 'x',\n 'z_x_mean',\n 'z_x_log_sigma',\n 'z_x',\n 'x_tilde',\n 'x_tilde_mean',\n ])\n\n def _build(self, x, sample=1):\n \"\"\"Builds the model.\"\"\"\n\n # Normal distribution for VAE sampling.\n eps = tf.random_normal([self.batch_size, self.latent_dim], mean=0, stddev=0.01)\n\n with slim.arg_scope([layers.encoder, layers.decoder],\n width=self.width,\n height=self.height,\n channels=self.channels,\n latent_dim=self.latent_dim,\n is_training=self._training):\n # Get latent representation for sampling.\n z_x_mean, z_x_log_sigma = layers.encoder(x)\n # Sample from latent space.\n z_x = []\n for _ in xrange(sample):\n z_x.append(z_x_mean + tf.exp(z_x_log_sigma / 2) * eps)\n if sample > 1:\n z_x = tf.add_n(z_x) / sample\n else:\n z_x = z_x[0]\n # Generate output.\n x_tilde = layers.decoder(z_x)\n\n with tf.variable_scope(tf.get_variable_scope(), reuse=True):\n # Generate reconstruction.\n x_tilde_mean = layers.decoder(z_x_mean)\n\n return self.model_type(\n x=x,\n z_x_mean=z_x_mean,\n z_x_log_sigma=z_x_log_sigma,\n z_x=z_x,\n x_tilde=x_tilde,\n x_tilde_mean=x_tilde_mean,\n )\n\n def _build_optimizer(self):\n return None, tf.train.AdamOptimizer(learning_rate=1e-3)\n\n def _build_loss(self, model, labels):\n \"\"\"Loss function.\"\"\"\n\n # Transform back to logits as TF expects logits not probabilities.\n epsilon = 10e-8\n x_tilde = tf.clip_by_value(model.x_tilde, epsilon, 1 - epsilon)\n x_tilde = tf.log(x_tilde / (1 - x_tilde))\n\n # Reconstruction loss.\n R_loss = self.width * self.height * self.channels * tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(slim.flatten(x_tilde), slim.flatten(model.x)),\n reduction_indices=-1\n )\n\n # KL divergence.\n KL_loss = -0.5 * tf.reduce_sum(\n 1 + model.z_x_log_sigma - tf.square(model.z_x_mean) - tf.exp(model.z_x_log_sigma),\n reduction_indices=-1\n )\n\n return R_loss + KL_loss\n\n def _build_gradients(self, optimizer, gradients, loss):\n gradients.setdefault('vae', []).append(\n optimizer.compute_gradients(loss, var_list=self._get_model_variables())\n )\n\n def _build_apply_gradients(self, optimizer, gradients, global_step):\n return optimizer.apply_gradients(gradients['vae'], global_step=global_step)\n\n def encode_op(self, x, sample=False, with_variance=False):\n model = self._model(x)\n if sample:\n return model.z_x\n elif with_variance:\n return model.z_x_mean, model.z_x_log_sigma_sq\n else:\n return model.z_x_mean\n\n def decode_op(self, z):\n with tf.variable_scope(self._model.var_scope, reuse=True):\n x_tilde = layers.decoder(z,\n width=self.width,\n height=self.height,\n channels=self.channels,\n latent_dim=self.latent_dim,\n is_training=self._training)\n return x_tilde\n\n def reconstruct_op(self, x, sample=False, sample_times=1):\n model = self._model(x, sample=sample_times)\n if sample:\n return model.x_tilde\n else:\n return model.x_tilde_mean\n","sub_path":"Jernej Kos/experiments/models/vae/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"264790627","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n# The MIT License (MIT)\n\n# Copyright (c) 2016 CNRS\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# AUTHORS\n# Gregory GELLY - gregory.gelly@limsi.fr\n\nfrom keras.optimizers import Optimizer\nimport keras.backend as K\nfrom pyannote.audio.keras_utils import register_custom_object\n\n\nclass SMORMS3(Optimizer):\n '''SMORMS3 optimizer.\n Default parameters follow those provided in the blog.\n # Arguments\n lr: float >= 0. Learning rate.\n epsilon: float >= 0. Fuzz factor.\n decay: float >= 0. Learning rate decay over each update.\n # References\n - [RMSprop loses to SMORMS3 - Beware the Epsilon!](http://sifter.org/~simon/journal/20150420.html)\n '''\n def __init__(self, lr=0.001, epsilon=1e-16, decay=0., **kwargs):\n super(SMORMS3, self).__init__(**kwargs)\n self.__dict__.update(locals())\n self.iterations = K.variable(0)\n self.lr = K.variable(lr)\n self.decay = K.variable(decay)\n self.initial_decay = decay\n\n def get_updates(self, params, constraints, loss):\n grads = self.get_gradients(loss, params)\n self.updates = [K.update_add(self.iterations, 1)]\n\n lr = self.lr\n if self.initial_decay > 0:\n lr *= (1. / (1. + self.decay * self.iterations))\n\n shapes = [K.get_variable_shape(p) for p in params]\n ms = [K.zeros(shape) for shape in shapes]\n vs = [K.zeros(shape) for shape in shapes]\n mems = [K.zeros(shape) for shape in shapes]\n self.weights = [self.iterations] + ms + vs + mems\n\n for p, g, m, v, mem in zip(params, grads, ms, vs, mems):\n r = 1. / (1. + mem)\n m_t = (1. - r) * m + r * g\n v_t = (1. - r) * v + r * K.square(g)\n denoise = K.square(m_t) / (v_t + self.epsilon)\n p_t = p - g * K.minimum(lr, denoise) / (K.sqrt(v_t) + self.epsilon)\n mem_t = 1. + mem * (1. - denoise)\n\n self.updates.append(K.update(m, m_t))\n self.updates.append(K.update(v, v_t))\n self.updates.append(K.update(mem, mem_t))\n\n new_p = p_t\n # apply constraints\n if p in constraints:\n c = constraints[p]\n new_p = c(new_p)\n self.updates.append(K.update(p, new_p))\n return self.updates\n\n def get_config(self):\n config = {'lr': float(K.get_value(self.lr)),\n 'decay': float(K.get_value(self.decay)),\n 'epsilon': self.epsilon}\n base_config = super(SMORMS3, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n# register user-defined Keras optimizer\nregister_custom_object('SMORMS3', SMORMS3)\n\n\nclass SSMORMS3(Optimizer):\n '''SSMORMS3 optimizer for Stabilized SMORMS3.\n Slight modification of SMORMS3 that stabilizes its behavior\n # Arguments\n epsilon: float >= 0. Fuzz factor.\n # References\n - [RMSprop loses to SMORMS3 - Beware the Epsilon!](http://sifter.org/~simon/journal/20150420.html)\n '''\n def __init__(self, epsilon=1e-8, **kwargs):\n super(SSMORMS3, self).__init__(**kwargs)\n self.__dict__.update(locals())\n self.iterations = K.variable(0)\n\n def get_updates(self, params, constraints, loss):\n grads = self.get_gradients(loss, params)\n self.updates = [K.update_add(self.iterations, 1)]\n\n shapes = [K.get_variable_shape(p) for p in params]\n ms = [K.zeros(shape) for shape in shapes]\n vs = [K.zeros(shape) for shape in shapes]\n mems = [K.zeros(shape) for shape in shapes]\n denoises = [K.zeros(shape) for shape in shapes]\n self.weights = [self.iterations] + ms + vs + mems + denoises\n\n for p, g, m, v, mem, denoise in zip(params, grads, ms, vs, mems, denoises):\n r = K.minimum(0.2, K.maximum(0.005, 1. / (1. + mem)))\n mem_t = 1. / r - 1.\n m_t = (1. - r) * m + r * g\n v_t = (1. - r) * v + r * K.square(g)\n denoise_t = 0.99 * denoise + 0.01 * K.square(m_t) / (v_t + self.epsilon)\n p_t = p - g * denoise_t / (K.sqrt(v_t) + self.epsilon)\n mem_t = K.maximum(0., 1. + mem_t * (1. - denoise_t))\n\n self.updates.append(K.update(m, m_t))\n self.updates.append(K.update(v, v_t))\n self.updates.append(K.update(mem, mem_t))\n self.updates.append(K.update(denoise, denoise_t))\n\n new_p = p_t\n # apply constraints\n if p in constraints:\n c = constraints[p]\n new_p = c(new_p)\n self.updates.append(K.update(p, new_p))\n return self.updates\n\n def get_config(self):\n config = {'epsilon': self.epsilon}\n base_config = super(SSMORMS3, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n# register user-defined Keras optimizer\nregister_custom_object('SSMORMS3', SSMORMS3)\n","sub_path":"pyannote/audio/optimizers.py","file_name":"optimizers.py","file_ext":"py","file_size_in_byte":5976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"352198490","text":"import pytest\nfrom leetcode import find_number\n\n\n@pytest.mark.parametrize(\n 'nums,expected',\n [\n ([12, 345, 2, 6, 7896], 2),\n ([555, 901, 482, 1771], 1),\n ],\n)\ndef test_find_number(nums, expected):\n assert find_number.find_numbers(nums) == expected\n","sub_path":"tests/test_find_number.py","file_name":"test_find_number.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"332303383","text":"import matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\ndef graph_3d(pca_vector, df, color):\n \"\"\"\n Example\n -------\n ax1 = graph_3d(X_pca_transformed, test_df)\n ax.set_xlim(-5000000,20000000)\n ax.set_ylim(-1000000,8000000)\n ax.set_zlim(-3000000,3000000)\n plt.show()\n \"\"\"\n\n xs = pca_vector[:,0]\n ys = pca_vector[:,1]\n zs = pca_vector[:,2]\n\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_zlabel('z')\n ax.scatter(xs, ys, zs, c=color, alpha=.3)\n\n return ax","sub_path":"medicare_part_e/src/graph_3d.py","file_name":"graph_3d.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"197958089","text":"# Copyright 2020 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\nimport numpy as np\nimport pytest\nimport mindspore.context as context\nimport mindspore.nn as nn\nfrom mindspore import Tensor, Parameter\nimport mindspore.common.dtype as mstype\nfrom mindspore.ops import operations as P\n\ncontext.set_context(mode=context.GRAPH_MODE, device_target=\"CPU\")\n\n\nclass Net(nn.Cell):\n def __init__(self):\n super(Net, self).__init__()\n self.unique = P.Unique()\n self.dynamic_assign = P.DynamicAssign()\n self.param = Parameter(\n Tensor(np.zeros((5,), np.int32)), name=\"assign_x\")\n\n def construct(self, y):\n y, _ = self.unique(y)\n return self.dynamic_assign(self.param, y)\n\n\n@pytest.mark.level0\n@pytest.mark.platform_arm_ascend_training\n@pytest.mark.platform_x86_ascend_training\n@pytest.mark.env_onecard\ndef test_dynamic_assign():\n y = Tensor(np.array([2, 2, 3, 3, 4]), mstype.int32)\n dynamic_assign = Net()\n _ = dynamic_assign(y)\n expect1 = np.array([2, 3, 4])\n param_np = dynamic_assign.param.data.asnumpy()\n assert (param_np == expect1).all()\n","sub_path":"tests/st/dynamic_shape/test_dynamic_assign_cpu.py","file_name":"test_dynamic_assign_cpu.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"27740920","text":"'''\nthe tool of data analysis\n'''\n\nfrom .Bayesian_duration import *\nfrom .Baseline import *\nfrom .Separate_source import *\nfrom .Time_transform import *\nfrom .overlap_tools import *\n\n\ndef get_energy_of_ch(time,e1,e2):\n\t'''\n\t\n\t:param time: time\n\t:param e1:\n\t:param e2:\n\t:return:\n\t'''\n\tnumb = len(time)\n\tenergy_random_arr = np.random.random_sample(numb)\n\tenergy_array = e1 + (e2-e1)*energy_random_arr\n\treturn energy_array\n\ndef ch_to_energy(time,ch,ch_n,e1,e2):\n\t'''\n\t\n\t:param time:\n\t:param ch:\n\t:param ch_n:\n\t:param e1:\n\t:param e2:\n\t:return:\n\t'''\n\tnew_t = np.array([])\n\tnew_energy = np.array([])\n\tfor index,channel in enumerate(ch_n):\n\t\tch_t_index = np.where(ch == channel)\n\t\tch_t = time[ch_t_index]\n\t\tenergy_array = get_energy_of_ch(ch_t,e1[index],e2[index])\n\t\tnew_t = np.concatenate((new_t,ch_t))\n\t\tnew_energy = np.concatenate((new_energy,energy_array))\n\tindex_all = np.argsort(new_t)\n\tnew_t = new_t[index_all]\n\tnew_energy = new_energy[index_all]\n\treturn new_t,new_energy\n\n\n\n","sub_path":"Data_analysis/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"405564955","text":"from flask_wtf import FlaskForm\nfrom wtforms import StringField, validators, FloatField\nfrom ..config import TIMEOUT\n\nclass CodeForm(FlaskForm):\n code = StringField(\n label='code',\n validators=[\n validators.data_required()\n ])\n text = StringField(label='text')\n timeout = FloatField(\n label='timeout',\n validators=[\n validators.number_range(\n min=0, max=TIMEOUT,\n message='Timeout should be in range from 0 to %(max)s.'),\n validators.optional()\n ])\n\n class Meta:\n csrf = False\n\n","sub_path":"app/app/core/utils/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"456510580","text":"#\n\nimport numpy as np\nimport pandas as pd\nfrom utils import *\n\n\ndef parse_1min_file(filename):\n pn = pd.read_table(filename, sep=',', index_col=(2, 0)).to_panel()\n stock_index = [i for i in pn.minor_axis if i[:4] in ('SH60', 'SZ00', 'SZ30')]\n index_index = [i for i in pn.minor_axis if i[:4] not in ('SH60', 'SZ00', 'SZ30')]\n stock_pn = pn.ix[:, :, stock_index]\n index_pn = pn.ix[:, :, index_index]\n\n stock_pn.minor_axis = [i[2:] for i in stock_index]\n index_pn.minor_axis = [i[2:] for i in index_index]\n return stock_pn, index_pn\n pass\n\n\ndef parse_dates(start, end, interval='1min'):\n dates = [i for i in TRADING_DAYS if i >= start and i <= end]\n\n workdir_dict = { '1min': WORKDIR_1MIN, \n '5min': WORKDIR_5MIN,\n '30min': WORKDIR_30MIN\n }\n workdir = workdir_dict[interval]\n\n filenames = [os.path.join(workdir, i[:4]+'-'+i[4:6]+'-'+i[6:8]+'.csv') for i in dates]\n stock_pns, index_pns = [], []\n\n for filename in sorted(filenames):\n logging.info('parsing %s' %filename)\n stock_pn, index_pn = parse_1min_file(filename)\n stock_pns.append(stock_pn)\n index_pns.append(index_pn)\n\n return pd.concat(stock_pns), pd.concat(index_pns)\n\n\ndef alpha_performance(alpha, date, index=None):\n '''\n parse the alpha's performance\n '''\n\n stock_pns, index_pns = parse_dates(date, date)\n close = stock_pns.ix['close', :, alpha.keys()]\n pre_close = stock_pns.ix['yclose', :, alpha.keys()]\n\n alpha = pd.Series(alpha)\n amount = close.mul(alpha, axis=1)\n pre_amount = pre_close.mul(alpha, axis=1)\n profit = amount.sub(pre_amount)\n profit_ratios = profit.cumsum().div(pre_amount.ix[0], axis=1)\n profit_ratio = profit.sum(axis=1).cumsum()/(pre_amount.ix[0].sum())\n\n return profit, profit_ratios, profit_ratio\n \n \nif __name__ == '__main__':\n #filename = \"/home/SambaServer/TinySoftData/1min/2015-05-19.csv\"\n #stock_pn, index_pn = parse_1min_file(filename)\n #stock_pns, index_pns = parse_dates('20150529', '20150601')\n #print stock_pns.items\n profit, profit_ratios, profit_ratio = alpha_performance({'600000': 100, '000001': 500}, '20150529')\n\n\n","sub_path":"parse_1day.py","file_name":"parse_1day.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"54662809","text":"#!/usr/bin/env python3\nimport smtplib\nfrom email.message import EmailMessage\nimport getpass\nimport sys\nimport mimetypes\n\ndef add_attachment(m, attachment):\n ctype, encoding = mimetypes.guess_type(attachment)\n if ctype is None or encoding is not None:\n # No guess could be made, or the file is encoded (compressed), so\n # use a generic bag-of-bits type.\n ctype = 'application/octet-stream'\n maintype, subtype = ctype.split('/', 1)\n with open(attachment, 'rb') as f:\n m.add_attachment(f.read(),\n maintype=maintype,\n subtype=subtype,\n filename=attachment)\n\ndef make_message_object(origin, destination, subject, content, attachment=None):\n m = EmailMessage()\n m.set_content(content)\n m['Subject'] = subject\n m['From'] = origin\n m['To'] = destination\n if attachment:\n add_attachment(m, attachment)\n return m\n\ndef make_hotmail_connection():\n from_smtp = 'smtp-mail.outlook.com'\n from_address = 'phil103@hotmail.com'\n password = getpass.getpass('Say password for user {} : '.format(from_address))\n\n s = smtplib.SMTP(from_smtp, 587 )\n s.ehlo()\n s.starttls()\n s.ehlo()\n s.login(from_address, password)\n return s\n\ndef send_mail(origin, destination, subject, content, attachment=None):\n hc = make_hotmail_connection()\n send_mail_connected(origin, destination, subject, content, hc, attachment)\n hc.quit()\n\ndef send_mail_connected(origin, destination, subject, content, connection, attachment=None):\n message = make_message_object(origin, destination, subject, content, attachment)\n connection.send_message(message, origin, destination)\n\ndef test_send_mail():\n send_mail(\"phil103@hotmail.com\", \"pcarphin@gmail.com\", \"el subjecto\", \"el contento\")\n\n\ndef send_cmc_command():\n import sys\n usage = \"Fist argument : subject\\nSecondArgument : content\\n\\n Message will be sent to my CMC address from my hotmail address\"\n subject = \"\"\n content = \"\"\n try:\n subject = sys.argv[1]\n except IndexError:\n print(\"send_mail ERROR: Missing argument\\n\\n\" + usage)\n quit()\n\n try:\n content = sys.argv[2]\n except IndexError:\n print(\"send_mail ERROR: Missing argument\\n\\n\" + usage)\n quit()\n\n send_mail(\n \"phil103@hotmail.com\",\n \"philippe.carphin2@canada.ca\",\n subject, content)\n\ndef test_send_attachment():\n subject = 'Test of attachment'\n content = 'This message should have mailtool.py as an attachmetn'\n hotmail = make_hotmail_connection()\n send_mail_connected(\n \"phil103@hotmail.com\",\n \"pcarphin@gmail.com\",\n subject, content, hotmail, 'mailtool.py')\n hotmail.quit()\n\ndef resolve_nicknames(potential_nickname):\n if potential_nickname in addresses:\n return addresses[potential_nickname]\n\naddresses = {\n \"cmc\": \"philippe.carphin2@canada.ca\",\n \"hotmail\": \"phil103@hotmail.com\",\n \"poly\": \"philippe.carphin@polymtl.ca\"\n }\ndef test_send_cmc_command():\n send_cmc_command()\nif __name__ == \"__main__\":\n # test_send_mail()\n # test_send_cmc_command()\n # send_cmc_command()\n test_send_attachment()\n","sub_path":"libexec/FocusTree/mailtool.py","file_name":"mailtool.py","file_ext":"py","file_size_in_byte":3203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"470446423","text":"\"\"\"empty message\n\nRevision ID: ea41446517f3\nRevises: bae9e3c7f432\nCreate Date: 2016-03-23 23:43:04.047000\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'ea41446517f3'\ndown_revision = 'bae9e3c7f432'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_index('ix_apicache_characteraffiliation_name', table_name='apicache_characteraffiliation')\n op.create_index(op.f('ix_apicache_characteraffiliation_name'), 'apicache_characteraffiliation', ['name'], unique=False)\n op.drop_index('name', table_name='apicache_characterid')\n op.drop_index('ix_apicache_corporationinfo_name', table_name='apicache_corporationinfo')\n op.create_index(op.f('ix_apicache_corporationinfo_name'), 'apicache_corporationinfo', ['name'], unique=False)\n op.drop_index('ix_ban_name', table_name='ban')\n op.create_index(op.f('ix_ban_name'), 'ban', ['name'], unique=False)\n op.drop_index('eve_name', table_name='characters')\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_index('eve_name', 'characters', ['eve_name'], unique=True)\n op.drop_index(op.f('ix_ban_name'), table_name='ban')\n op.create_index('ix_ban_name', 'ban', ['name'], unique=True)\n op.drop_index(op.f('ix_apicache_corporationinfo_name'), table_name='apicache_corporationinfo')\n op.create_index('ix_apicache_corporationinfo_name', 'apicache_corporationinfo', ['name'], unique=True)\n op.create_index('name', 'apicache_characterid', ['name'], unique=True)\n op.drop_index(op.f('ix_apicache_characteraffiliation_name'), table_name='apicache_characteraffiliation')\n op.create_index('ix_apicache_characteraffiliation_name', 'apicache_characteraffiliation', ['name'], unique=True)\n ### end Alembic commands ###\n","sub_path":"migrations/versions/ea41446517f3_.py","file_name":"ea41446517f3_.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"247882695","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 24 14:43:09 2020\n\n@author: Atnaas Kozarev\n\"\"\"\n\n# Guess the Square Root of X using binary search\n\nx = 10000 \nmargin_of_error = 0.01\nnumGuesses = 0\nlow = 1.0\nhigh = x\nguess = (high + low)/2.0\n\nwhile abs(guess**2 - x) >= margin_of_error:\n print('low = ' + str(low) + ' high = ' + str(high) + ' guess = ' + str(guess))\n numGuesses += 1\n if guess**2 < x:\n low = guess \n else:\n high = guess\n guess = (high + low)/ 2.0\nprint('numGuesses = ' + str(numGuesses))\nprint(str(guess) + ' is close to square root of ' + str(x))","sub_path":"MIT6.00.1x-Week2-BinarySearch.py","file_name":"MIT6.00.1x-Week2-BinarySearch.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"487724053","text":"import datetime\nimport logging\nimport subprocess\nfrom pathlib import Path\n\nimport click\nfrom pyvirtualdisplay import Display\n\nfrom extract_csv import extract_csv\nfrom fetch_record import fetch_accounts_data\nfrom import_csv import import_expenses\nfrom transform_csv import transform_csv\n\nlogging.basicConfig(level=logging.INFO)\n\n\ndef _transform_csv(ctx, extracted_csv_file, report, transformed_csv_root):\n transformed_csv_file = _get_file_path(transformed_csv_root, report)\n ctx.invoke(transform_csv, input_path=extracted_csv_file, output_path=transformed_csv_file)\n\n\ndef _extract_csv(ctx, extracted_csv_root, report):\n extracted_csv_file = _get_file_path(extracted_csv_root, report)\n ctx.invoke(extract_csv, input_path=report, output_path=extracted_csv_file)\n return extracted_csv_file\n\n\ndef _get_file_path(root, report):\n return root / (report.stem + '.csv')\n\n\ndef _get_paths(root_path):\n run_root_path = _create_path_dir(root_path, str(datetime.date.today()))\n html_path = _create_path_dir(run_root_path, 'html')\n extracted_csv_root = _create_path_dir(run_root_path, 'extracted_csv')\n transformed_csv_root = _create_path_dir(run_root_path, 'transformed_csv')\n\n return extracted_csv_root, html_path, transformed_csv_root\n\n\ndef _create_path_dir(path, extension=None):\n new_path = Path(path) / extension if extension else path\n new_path.mkdir(exist_ok=True)\n return new_path\n\n\n@click.command()\n@click.argument('conf_path', type=click.Path(exists=True))\n@click.argument('root_path')\n@click.option('--fetch_data/--no-fetch_data', default=True)\n@click.option('--visible/--no-visible', default=False)\n@click.pass_context\ndef run(ctx, conf_path, root_path, fetch_data, visible):\n if not visible:\n with Display(visible=0, size=(800, 600)):\n run_flow(conf_path, ctx, fetch_data, root_path)\n\n run_flow(conf_path, ctx, fetch_data, root_path)\n\n\ndef run_flow(conf_path, ctx, fetch_data, root_path):\n extracted_csv_root, html_path, transformed_csv_root = _get_paths(root_path)\n if fetch_data:\n logging.info('Fetch data from Leumi')\n ctx.invoke(fetch_accounts_data, conf_path=conf_path, output_path=html_path)\n logging.info('Creating CSVs')\n for report in html_path.glob('*.html'):\n extracted_csv_file = _extract_csv(ctx, extracted_csv_root, report)\n _transform_csv(ctx, extracted_csv_file, report, transformed_csv_root)\n subprocess.run(['bash', 'merge_csv.sh', str(transformed_csv_root)])\n logging.info('Importing CSVs')\n ctx.invoke(import_expenses, conf_path=conf_path, input_path=transformed_csv_root)\n\n\nif __name__ == \"__main__\":\n run()\n","sub_path":"scrapper/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"615633988","text":"from tkinter import *\nfrom tkinter import ttk\nfrom random import randint\n\nraam = Tk()\nraam.title(\"Poomine\")\nraam.geometry(\"650x430\")\nkõrgus=450\nlaius=700\n\ntaust = Frame(raam, width=laius, height=kõrgus, bg=\"black\")\nnööbid = Frame(raam, width=laius, height=kõrgus, bg=\"black\")\nfont2 = font.Font(family='Goudy Old Style', size = 15, weight = \"bold\")\nfont1 = font.Font(family='Courier', size = 19, weight = \"bold\")\ninf = Frame(taust, width=700, height=40, background=\"black\", border=0)\nvihje = StringVar()\nvihje_silt = Label(taust, textvariable = vihje, font = font1, border = 0, fg = \"white\", bg = \"black\")\nelu = StringVar()\nõige_sõna = StringVar()\nõige_silt = Label(taust, textvariable = õige_sõna, font = font1, fg = \"red\", bg = \"black\")\nelu_silt = Label(inf, text = \"Elusid:\", font=font2, bg=\"black\", fg=\"white\")\nelusid = Label(inf, textvariable = elu, font=font2, background=\"black\", fg=\"white\", border=0)\n\n#nööbid\nq = Button(nööbid, text=\"Q\", command = lambda: ava_klahv(\"Q\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nw = Button(nööbid, text=\"W\", command = lambda: ava_klahv(\"W\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\ne = Button(nööbid, text=\"E\", command = lambda: ava_klahv(\"E\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nr = Button(nööbid, text=\"R\", command = lambda: ava_klahv(\"R\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nt = Button(nööbid, text=\"T\", command = lambda: ava_klahv(\"T\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\ny = Button(nööbid, text=\"Y\", command = lambda: ava_klahv(\"Y\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nu = Button(nööbid, text=\"U\", command = lambda: ava_klahv(\"U\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\ni = Button(nööbid, text=\"I\", command = lambda: ava_klahv(\"I\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\no = Button(nööbid, text=\"O\", command = lambda: ava_klahv(\"O\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\np = Button(nööbid, text=\"P\", command = lambda: ava_klahv(\"P\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nü = Button(nööbid, text=\"Ü\", command = lambda: ava_klahv(\"Ü\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nõ = Button(nööbid, text=\"Õ\", command = lambda: ava_klahv(\"Õ\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\na = Button(nööbid, text=\"A\", command = lambda: ava_klahv(\"A\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\ns = Button(nööbid, text=\"S\", command = lambda: ava_klahv(\"S\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nd = Button(nööbid, text=\"D\", command = lambda: ava_klahv(\"D\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nf = Button(nööbid, text=\"F\", command = lambda: ava_klahv(\"F\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\ng = Button(nööbid, text=\"G\", command = lambda: ava_klahv(\"G\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nh = Button(nööbid, text=\"H\", command = lambda: ava_klahv(\"H\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nj = Button(nööbid, text=\"J\", command = lambda: ava_klahv(\"J\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nk = Button(nööbid, text=\"K\", command = lambda: ava_klahv(\"K\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nl = Button(nööbid, text=\"L\", command = lambda: ava_klahv(\"L\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nö = Button(nööbid, text=\"Ö\", command = lambda: ava_klahv(\"Ö\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nä = Button(nööbid, text=\"Ä\", command = lambda: ava_klahv(\"Ä\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nz = Button(nööbid, text=\"Z\", command = lambda: ava_klahv(\"Z\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nx = Button(nööbid, text=\"X\", command = lambda: ava_klahv(\"X\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nc = Button(nööbid, text=\"C\", command = lambda: ava_klahv(\"C\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nv = Button(nööbid, text=\"V\", command = lambda: ava_klahv(\"V\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nb = Button(nööbid, text=\"B\", command = lambda: ava_klahv(\"B\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nn = Button(nööbid, text=\"N\", command = lambda: ava_klahv(\"N\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nm = Button(nööbid, text=\"M\", command = lambda: ava_klahv(\"M\"), font = font2, width=2, fg = \"white\", bg = \"black\", bd = 2)\nedasi = Button(nööbid, state=NORMAL, text=\">\", command = lambda: uus(), font = font2, width=1, fg = \"#66FF66\", bg = \"black\", activebackground=\"black\", activeforeground=\"dark green\", bd = 0)\n\nsõnastik = {\"A\": a, \"B\": b,\"C\": c,\"D\": d,\"E\": e,\"F\": f,\"G\": g,\"H\": h,\"I\": i,\\\n \"J\": j,\"K\": k,\"L\": l,\"M\": m,\"N\": n, \"O\": o, \"P\": p,\"Q\": q,\"R\": r, \\\n \"S\": s,\"T\": t,\"U\": u,\"V\": v,\"W\": w,\"Õ\": õ,\"Ä\": ä,\"Ö\": ö,\"Ü\": ü,\\\n \"X\": x,\"Y\": y,\"Z\": z}\n\nraam.columnconfigure(0, weight=1)\nraam.rowconfigure(0, weight=1)\ninf.grid(column=0, row=0, columnspan=3, sticky=N+S+E+W)\ntaust.grid(column=0, row=0, sticky=N+S+E+W)\nelu_silt.grid(column=0, row=0, sticky=W, padx = 1)\nelusid.grid(column=1, row=0, padx = 5)\nvihje_silt.grid(column=1, row=1, sticky = S)\nõige_silt.grid(column=1, row=2, sticky = (N, S, E, W))\nnööbid.grid(column=0, row=1, sticky=N+E+W)\n\nq.grid(column=1, row=3, sticky=E+W), w.grid(column=2, row=3, sticky = E+W)\ne.grid(column=3, row=3, sticky = E+W), r.grid(column=4, row=3, sticky = E+W)\nt.grid(column=5, row=3, sticky = E+W), y.grid(column=6, row=3, sticky = E+W)\nu.grid(column=7, row=3, sticky = E+W), i.grid(column=8, row=3, sticky = E+W)\no.grid(column=9, row=3, sticky = E+W), p.grid(column=10, row=3, sticky = E+W)\nü.grid(column=11, row=3, sticky = E+W), õ.grid(column=12, row=3, sticky = E+W)\na.grid(column=2, row=4, sticky = E+W), s.grid(column=3, row=4, sticky = E+W)\nd.grid(column=4, row=4, sticky = E+W), f.grid(column=5, row=4, sticky = E+W)\ng.grid(column=6, row=4, sticky = E+W), h.grid(column=7, row=4, sticky = E+W)\nj.grid(column=8, row=4, sticky = E+W), k.grid(column=9, row=4, sticky = E+W)\nl.grid(column=10, row=4, sticky = E+W), ö.grid(column=11, row=4, sticky = E+W)\nä.grid(column=12, row=4, sticky = E+W), z.grid(column=3, row=5, sticky = E+W)\nx.grid(column=4, row=5, sticky = E+W), c.grid(column=5, row=5, sticky = E+W)\nv.grid(column=6, row=5, sticky = E+W), b.grid(column=7, row=5, sticky = E+W)\nn.grid(column=8, row=5, sticky = E+W), m.grid(column=9, row=5, sticky = E+W)\nedasi.grid(column=12, row=5, sticky = E+W)\n\nraam.columnconfigure(0, weight=1)\nraam.rowconfigure(0, weight=1)\nnööbid.columnconfigure(0, weight=1), nööbid.columnconfigure(13, weight=1)\ntaust.columnconfigure(0, weight=1)\ntaust.rowconfigure(1, weight=2)\ntaust.columnconfigure(2, weight=1)\ntaust.rowconfigure(2, weight=1)\nfail = open(\"sonad.txt\", encoding='UTF-8')\ntsitaadid = fail.readlines()\nkasutatud = [] #tsitaadid\npakutud = [] #tähed\nsuvalised_arvud = []\nfail.close()\n\n#vähenda elusid\ndef elud():\n str(elu.set(int(elu.get())-1))\n if int(elu.get()) == 0:\n õige = kasutatud[len(kasutatud)-1].upper()\n õige_sõna.set(õige)\n edasi.config(state=NORMAL)\n raam.bind(\"\", uus)\n elusid = Label(inf, textvariable = elu, font=font2, padx=6, pady =10, background=\"black\", fg=\"white\", border=0)\n\n#sõne töötlemine\ndef juba_olemas():\n olemas=['\"',',','.','-', ' ','/']\n return olemas\n\ndef suvaline_arv():\n while len(suvalised_arvud) < len(tsitaadid):\n arv = randint(0, (len(tsitaadid)-1))\n if arv not in suvalised_arvud:\n suvalised_arvud.append(arv)\n return arv\n\ndef anna_vihje():\n trüki = \"\"\n for el in kasutatud[len(kasutatud)-1].upper():\n if el in juba_olemas() or el in pakutud:\n if el == \"/\":\n trüki +=\"\\n\" + \"\\n\"\n else:\n trüki += el + \" \"\n else:\n trüki += \"_\" + \" \"\n if \"_\" not in trüki:\n edasi.config(state=NORMAL)\n raam.bind(\"\", uus)\n else:\n edasi.config(state=DISABLED)\n return trüki\n\n#ava klahvile vajutus\ndef ava_täht(event=None):\n if str(event.char).upper() not in pakutud:\n pakutud.append(str(event.char).upper())\n keela()\n if str(event.char).upper() not in kasutatud[len(kasutatud)-1].upper():\n elud()\n else:\n vihje.set(anna_vihje())\n\n#ava hiireklikk\ndef ava_klahv(klahv):\n pakutud.append(klahv.upper())\n keela()\n if klahv not in kasutatud[len(kasutatud)-1].upper():\n elud()\n else:\n pakutud.append(klahv.upper())\n vihje.set(anna_vihje())\n\ndef uus(event=None):\n õige_sõna.set(\"\")\n raam.unbind(\"\", None)\n elu.set(\"7\")\n pakutud.clear()\n luba()\n try:\n tsitaat = tsitaadid[suvaline_arv()]\n kasutatud.append(tsitaat.strip(\"\\n\"))\n vihje.set(anna_vihje())\n except:\n vihje.set(\"Läbi!\")\n edasi.config(state=DISABLED)\n\ndef luba():\n for el in nööbid.winfo_children():\n el.config(state=NORMAL)\n \ndef keela():\n for el in pakutud:\n sõnastik[el].config(state = DISABLED)\n\nraam.bind(\"q\", ava_täht), raam.bind(\"w\", ava_täht), raam.bind(\"e\", ava_täht)\nraam.bind(\"r\", ava_täht), raam.bind(\"t\", ava_täht), raam.bind(\"y\", ava_täht)\nraam.bind(\"u\", ava_täht), raam.bind(\"i\", ava_täht), raam.bind(\"o\", ava_täht)\nraam.bind(\"p\", ava_täht), raam.bind(\"ü\", ava_täht), raam.bind(\"õ\", ava_täht)\nraam.bind(\"a\", ava_täht), raam.bind(\"s\", ava_täht), raam.bind(\"d\", ava_täht)\nraam.bind(\"f\", ava_täht), raam.bind(\"g\", ava_täht), raam.bind(\"h\", ava_täht)\nraam.bind(\"j\", ava_täht), raam.bind(\"k\", ava_täht), raam.bind(\"l\", ava_täht)\nraam.bind(\"ö\", ava_täht), raam.bind(\"ä\", ava_täht), raam.bind(\"z\", ava_täht)\nraam.bind(\"x\", ava_täht), raam.bind(\"c\", ava_täht), raam.bind(\"v\", ava_täht)\nraam.bind(\"b\", ava_täht), raam.bind(\"n\", ava_täht), raam.bind(\"m\", ava_täht)\n\nuus()\n","sub_path":"projekti vaheseis.py","file_name":"projekti vaheseis.py","file_ext":"py","file_size_in_byte":10177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"395608005","text":"import pandas as pd\nimport numpy as np\nimport re\nfrom sklearn.model_selection import train_test_split\nfrom sklearn_pandas import DataFrameMapper\nfrom sklearn.preprocessing import LabelBinarizer, StandardScaler\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom catboost import CatBoostClassifier, Pool\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.impute import SimpleImputer\nimport pickle\n\nraw_df1 = pd.read_csv('/home/duryan/Documents/Yeti/hackathon/strap/model/data/youtube/CAvideos.csv')\nraw_df2 = pd.read_csv('/home/duryan/Documents/Yeti/hackathon/strap/model/data/youtube/USvideos.csv')\nraw_df = pd.concat([raw_df1, raw_df2])\nraw_df.reset_index(inplace=True)\n\nregex = r\"^.*?(?=T)\"\npublish_date = []\nfor i in range(len(raw_df['publish_time'])):\n test_str = raw_df['publish_time'][i]\n matches = re.findall(regex, test_str)[0]\n publish_date.append(matches)\n i += 1\nraw_df['publish_date'] = publish_date\n\n\nraw_df['trending_date'] = [x.replace('.', '-') for x in raw_df['trending_date']]\nraw_df[\"publish_date\"] = pd.to_datetime(raw_df[\"publish_date\"])\nraw_df[\"trending_date\"] = pd.to_datetime(raw_df[\"trending_date\"],format='%y-%d-%m')\nraw_df[\"days_to_trend\"] = raw_df[\"trending_date\"] - raw_df[\"publish_date\"]\nraw_df[\"days_to_trend\"] = raw_df[\"days_to_trend\"].apply(lambda x: x.days)\nraw_df[\"publish_date\"] = raw_df[\"publish_date\"].apply(lambda x: x.weekday())\n\n# create a unified metric based on 5 categories\nview_weight = 0.5\nlikes_weight = 0.25\ndislikes_weight = 0.1\ncomment_weight = 0.15\ndays_weight = 0.13\n\nraw_df[\"days_penalty\"] = 1/(days_weight*(1+raw_df[\"days_to_trend\"]))\nraw_df[\"metric\"] = raw_df[\"days_penalty\"]*(raw_df[\"views\"]*view_weight)+(raw_df[\"likes\"]*likes_weight)+(raw_df[\"dislikes\"]*dislikes_weight)+(raw_df[\"comment_count\"]*comment_weight)\nraw_df[[\"metric\"]].head()\n\nview_cut = 1000000 #set cutoff at 1 million views\nday_cut = 5 #set cutoff days to trend\nlikes_cut = raw_df[\"likes\"][raw_df[\"views\"] > view_cut].mean()\ndislikes_cut = raw_df[\"dislikes\"][raw_df[\"views\"] > view_cut].mean()\ncomment_cut = raw_df[\"comment_count\"][raw_df[\"views\"] > view_cut].mean()\ncutoff = np.log((1/(days_weight*(1+day_cut)))*((view_cut*view_weight)+(likes_cut*likes_weight)+(dislikes_cut*dislikes_weight)+(comment_cut*comment_weight)))\n\nraw_df[[\"metric\"]] = np.log(raw_df[\"metric\"]) # log transform to approximate normal distribution\nraw_df[\"viral\"] = np.where(raw_df[\"metric\"]>=cutoff, 1,0) # create new class column as target to predict virality\n\nraw_df[\"title_len\"]=raw_df[\"title\"].apply(lambda x: len(x)) # extract extra column from title length\n\nraw_df[\"description\"].fillna(\"\", inplace=True)\n\nraw_df[\"titles\"]=raw_df[\"title\"]+\" \"+raw_df[\"tags\"]+\" \"+raw_df[\"description\"]\n\nraw_df = raw_df.drop(['index', 'video_id', 'channel_title',\n 'publish_time', 'views', 'likes',\n 'dislikes', 'comment_count', \"description\", \"trending_date\", \"title\",\"tags\",'thumbnail_link',\n 'comments_disabled', 'ratings_disabled', 'days_to_trend', \"days_penalty\", \"trending_date\", 'video_error_or_removed', \"metric\"], axis = 1)\n\ntarget = 'viral'\nX = raw_df.drop(target, axis = 1)\ny = raw_df[[target]]\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n\nmapper = DataFrameMapper([\n (['publish_date'], [SimpleImputer(), LabelBinarizer()]),\n (['category_id'], [SimpleImputer(), LabelBinarizer()]),\n (['title_len'], [SimpleImputer(), StandardScaler()]),\n ('titles', TfidfVectorizer(stop_words='english', max_features=800, token_pattern=u'(?ui)\\\\b\\\\w*[a-z]+\\\\w*\\\\b'))\n], df_out = True)\n\nZ_train = mapper.fit_transform(X_train)\nZ_test = mapper.transform(X_test)\n\n\ncat = CatBoostClassifier(\n iterations=5000,\n eval_metric=\"F1\",\n random_seed=42,\n learning_rate=0.5,\n early_stopping_rounds=3000\n)\n\ntrain_pool = Pool(data=Z_train,\n label=y_train)\n\nvalidation_pool = Pool(data=Z_test,\n label=y_test)\n# cat.fit(\n# train_pool,\n# eval_set=validation_pool,\n# verbose=False\n# )\n\npipe = make_pipeline(mapper, cat.fit(\n train_pool,\n eval_set=validation_pool,\n verbose=False\n))\n\nprint(f'Model is fitted: {cat.is_fitted()}')\nprint(cat.best_score_)\n\npickle.dump(pipe, open('/home/duryan/Documents/Yeti/hackathon/strap/model/pipe.pkl', 'wb'))\n","sub_path":"model/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"81367259","text":"# encoding: utf-8\n# module samba.dcerpc.dnsserver\n# from /usr/lib/python2.7/dist-packages/samba/dcerpc/dnsserver.so\n# by generator 1.138\n\"\"\" dnsserver DCE/RPC \"\"\"\n\n# imports\nimport dcerpc as __dcerpc\nimport talloc as __talloc\n\n\n# Variables with simple values\n\nDNSSRV_TYPEID_ADDRARRAY = 34\nDNSSRV_TYPEID_AUTOCONFIGURE = 42\nDNSSRV_TYPEID_BUFFER = 5\n\nDNSSRV_TYPEID_DP_ENUM = 28\nDNSSRV_TYPEID_DP_INFO = 29\nDNSSRV_TYPEID_DP_LIST = 30\n\nDNSSRV_TYPEID_DWORD = 1\n\nDNSSRV_TYPEID_ENLIST_DP = 31\n\nDNSSRV_TYPEID_ENUM_ZONES_FILTER = 33\n\nDNSSRV_TYPEID_FORWARDERS = 37\n\nDNSSRV_TYPEID_FORWARDERS_DOTNET = 20\nDNSSRV_TYPEID_FORWARDERS_W2K = 8\n\nDNSSRV_TYPEID_IPARRAY = 4\n\nDNSSRV_TYPEID_IP_VALIDATE = 41\n\nDNSSRV_TYPEID_LPSTR = 2\nDNSSRV_TYPEID_LPWSTR = 3\n\nDNSSRV_TYPEID_NAME_AND_PARAM = 15\n\nDNSSRV_TYPEID_NULL = 0\n\nDNSSRV_TYPEID_SERVER_INFO = 35\n\nDNSSRV_TYPEID_SERVER_INFO_DOTNET = 19\nDNSSRV_TYPEID_SERVER_INFO_W2K = 6\n\nDNSSRV_TYPEID_STATS = 7\n\nDNSSRV_TYPEID_UNICODE_STRING_LIST = 44\n\nDNSSRV_TYPEID_UTF8_STRING_LIST = 43\n\nDNSSRV_TYPEID_ZONE = 21\n\nDNSSRV_TYPEID_ZONE_CHANGE_DP = 32\n\nDNSSRV_TYPEID_ZONE_CREATE = 40\n\nDNSSRV_TYPEID_ZONE_CREATE_DOTNET = 26\nDNSSRV_TYPEID_ZONE_CREATE_W2K = 14\n\nDNSSRV_TYPEID_ZONE_DATABASE = 24\n\nDNSSRV_TYPEID_ZONE_DATABASE_W2K = 12\n\nDNSSRV_TYPEID_ZONE_EXPORT = 18\nDNSSRV_TYPEID_ZONE_INFO = 36\n\nDNSSRV_TYPEID_ZONE_INFO_DOTNET = 22\nDNSSRV_TYPEID_ZONE_INFO_W2K = 10\n\nDNSSRV_TYPEID_ZONE_LIST = 27\n\nDNSSRV_TYPEID_ZONE_LIST_W2K = 16\n\nDNSSRV_TYPEID_ZONE_RENAME = 17\nDNSSRV_TYPEID_ZONE_SECONDARIES = 38\n\nDNSSRV_TYPEID_ZONE_SECONDARIES_DOTNET = 23\nDNSSRV_TYPEID_ZONE_SECONDARIES_W2K = 11\n\nDNSSRV_TYPEID_ZONE_TYPE_RESET = 39\n\nDNSSRV_TYPEID_ZONE_TYPE_RESET_DOTNET = 25\nDNSSRV_TYPEID_ZONE_TYPE_RESET_W2K = 13\n\nDNSSRV_TYPEID_ZONE_W2K = 9\n\nDNS_ALLOW_ALL_NAMES = 3\n\nDNS_ALLOW_MULTIBYTE_NAMES = 2\n\nDNS_ALLOW_NONRFC_NAMES = 1\n\nDNS_ALLOW_RFC_NAMES_ONLY = 0\n\nDNS_BOOT_METHOD_DIRECTORY = 3\nDNS_BOOT_METHOD_FILE = 1\nDNS_BOOT_METHOD_REGISTRY = 2\nDNS_BOOT_METHOD_UNINITIALIZED = 0\n\nDNS_CLIENT_VERSION_DOTNET = 393216\nDNS_CLIENT_VERSION_LONGHORN = 458752\nDNS_CLIENT_VERSION_W2K = 0\n\nDNS_DP_AUTOCREATED = 1\nDNS_DP_DELETED = 32\n\nDNS_DP_DOMAIN_DEFAULT = 4\n\nDNS_DP_ENLISTED = 16\n\nDNS_DP_FOREST_DEFAULT = 8\n\nDNS_DP_LEGACY = 2\nDNS_DP_OKAY = 0\n\nDNS_DP_STATE_REPL_INCOMING = 1\nDNS_DP_STATE_REPL_OUTGOING = 2\n\nDNS_DP_STATE_UNKNOWN = 3\n\nDNS_EVENT_LOG_ERROR_TYPE = 1\n\nDNS_EVENT_LOG_INFORMATION_TYPE = 4\n\nDNS_EVENT_LOG_SUCCESS = 0\n\nDNS_EVENT_LOG_WARNING_TYPE = 2\n\nDNS_IPVAL_DNS_DELEGATIONS = 4\nDNS_IPVAL_DNS_FORWARDERS = 2\nDNS_IPVAL_DNS_ROOTHINTS = 1\nDNS_IPVAL_DNS_SERVERS = 0\n\nDNS_IPVAL_DNS_ZONE_MASTERS = 3\n\nDNS_IPVAL_INVALID_ADDR = 1\n\nDNS_IPVAL_NOT_AUTH_FOR_ZONE = 4\n\nDNS_IPVAL_NO_RESPONSE = 3\nDNS_IPVAL_NO_TCP = -2147483648\n\nDNS_IPVAL_UNKNOWN_ERROR = 255\n\nDNS_IPVAL_UNREACHABLE = 2\n\nDNS_RPC_AUTOCONFIG_ALL = -1\n\nDNS_RPC_AUTOCONFIG_INTERNAL_FORWARDERS = 2\n\nDNS_RPC_AUTOCONFIG_INTERNAL_RETURN_ERROR = 32768\n\nDNS_RPC_AUTOCONFIG_INTERNAL_ROOTHINTS = 1\nDNS_RPC_AUTOCONFIG_INTERNAL_SELFPOINT = 16\n\nDNS_RPC_AUTOCONFIG_INTERNAL_SELFPOINT_APPEND = 64\nDNS_RPC_AUTOCONFIG_INTERNAL_SELFPOINT_PREPEND = 32\n\nDNS_RPC_AUTOCONFIG_INTERNAL_ZONES = 4\n\nDNS_RPC_USE_ALL_PROTOCOLS = -1\n\nDNS_RPC_USE_LPC = 4\n\nDNS_RPC_USE_NAMED_PIPE = 2\n\nDNS_RPC_USE_TCPIP = 1\n\nDNS_RPC_VIEW_ADDITIONAL_DATA = 16\n\nDNS_RPC_VIEW_AUTHORITY_DATA = 1\n\nDNS_RPC_VIEW_CACHE_DATA = 2\n\nDNS_RPC_VIEW_GLUE_DATA = 4\n\nDNS_RPC_VIEW_NO_CHILDREN = 65536\n\nDNS_RPC_VIEW_ONLY_CHILDREN = 131072\n\nDNS_RPC_VIEW_ROOT_HINT_DATA = 8\n\nDNS_RPC_ZONE_AGING = 32\nDNS_RPC_ZONE_AUTOCREATED = 8\nDNS_RPC_ZONE_DSINTEGRATED = 16\nDNS_RPC_ZONE_PAUSED = 1\nDNS_RPC_ZONE_READONLY = 256\nDNS_RPC_ZONE_REVERSE = 4\nDNS_RPC_ZONE_SHUTDOWN = 2\n\nDNS_RPC_ZONE_UPDATE_SECURE = 128\nDNS_RPC_ZONE_UPDATE_UNSECURE = 64\n\nDNS_ZONE_NOTIFY_ALL_SECONDARIES = 1\n\nDNS_ZONE_NOTIFY_LIST_ONLY = 2\n\nDNS_ZONE_NOTIFY_OFF = 0\n\nDNS_ZONE_REQUEST_AUTO = 8\nDNS_ZONE_REQUEST_CACHE = 4\n\nDNS_ZONE_REQUEST_CUSTOM_DP = 4096\n\nDNS_ZONE_REQUEST_DOMAIN_DP = 1024\n\nDNS_ZONE_REQUEST_DS = 256\n\nDNS_ZONE_REQUEST_FOREST_DP = 2048\n\nDNS_ZONE_REQUEST_FORWARD = 16\nDNS_ZONE_REQUEST_FORWARDER = 64\n\nDNS_ZONE_REQUEST_LEGACY_DP = 8192\n\nDNS_ZONE_REQUEST_NON_DS = 512\n\nDNS_ZONE_REQUEST_PRIMARY = 1\nDNS_ZONE_REQUEST_REVERSE = 32\nDNS_ZONE_REQUEST_SECONDARY = 2\nDNS_ZONE_REQUEST_STUB = 128\n\nDNS_ZONE_SECSECURE_LIST_ONLY = 2\n\nDNS_ZONE_SECSECURE_NO_SECURITY = 0\nDNS_ZONE_SECSECURE_NO_XFER = 3\n\nDNS_ZONE_SECSECURE_NS_ONLY = 1\n\nERROR_SUCCESS = 0\n\n# no functions\n# classes\n\nfrom dnsserver import dnsserver\nfrom DNSSRV_STAT import DNSSRV_STAT\nfrom DNSSRV_STAT_HEADER import DNSSRV_STAT_HEADER\nfrom DNS_ADDR import DNS_ADDR\nfrom DNS_ADDR_ARRAY import DNS_ADDR_ARRAY\nfrom DNS_EXTENSION import DNS_EXTENSION\nfrom DNS_RPC_AUTOCONFIGURE import DNS_RPC_AUTOCONFIGURE\nfrom DNS_RPC_BUFFER import DNS_RPC_BUFFER\nfrom DNS_RPC_DP_ENUM import DNS_RPC_DP_ENUM\nfrom DNS_RPC_DP_INFO import DNS_RPC_DP_INFO\nfrom DNS_RPC_DP_LIST import DNS_RPC_DP_LIST\nfrom DNS_RPC_DP_REPLICA import DNS_RPC_DP_REPLICA\nfrom DNS_RPC_ENLIST_DP import DNS_RPC_ENLIST_DP\nfrom DNS_RPC_ENUM_ZONES_FILTER import DNS_RPC_ENUM_ZONES_FILTER\nfrom DNS_RPC_FORWARDERS_DOTNET import DNS_RPC_FORWARDERS_DOTNET\nfrom DNS_RPC_FORWARDERS_LONGHORN import DNS_RPC_FORWARDERS_LONGHORN\nfrom DNS_RPC_FORWARDERS_W2K import DNS_RPC_FORWARDERS_W2K\nfrom DNS_RPC_IP_VALIDATE import DNS_RPC_IP_VALIDATE\nfrom DNS_RPC_NAME import DNS_RPC_NAME\nfrom DNS_RPC_NAME_AND_PARAM import DNS_RPC_NAME_AND_PARAM\nfrom DNS_RPC_NODE import DNS_RPC_NODE\nfrom DNS_RPC_RECORD import DNS_RPC_RECORD\nfrom DNS_RPC_RECORDS import DNS_RPC_RECORDS\nfrom DNS_RPC_RECORDS_ARRAY import DNS_RPC_RECORDS_ARRAY\nfrom DNS_RPC_RECORD_BUF import DNS_RPC_RECORD_BUF\nfrom DNS_RPC_RECORD_NAME_PREFERENCE import DNS_RPC_RECORD_NAME_PREFERENCE\nfrom DNS_RPC_RECORD_SOA import DNS_RPC_RECORD_SOA\nfrom DNS_RPC_RECORD_SRV import DNS_RPC_RECORD_SRV\nfrom DNS_RPC_RECORD_STRING import DNS_RPC_RECORD_STRING\nfrom DNS_RPC_SERVER_INFO_DOTNET import DNS_RPC_SERVER_INFO_DOTNET\nfrom DNS_RPC_SERVER_INFO_LONGHORN import DNS_RPC_SERVER_INFO_LONGHORN\nfrom DNS_RPC_SERVER_INFO_W2K import DNS_RPC_SERVER_INFO_W2K\nfrom DNS_RPC_UTF8_STRING_LIST import DNS_RPC_UTF8_STRING_LIST\nfrom DNS_RPC_ZONE_CHANGE_DP import DNS_RPC_ZONE_CHANGE_DP\nfrom DNS_RPC_ZONE_CREATE_INFO_DOTNET import DNS_RPC_ZONE_CREATE_INFO_DOTNET\nfrom DNS_RPC_ZONE_CREATE_INFO_LONGHORN import DNS_RPC_ZONE_CREATE_INFO_LONGHORN\nfrom DNS_RPC_ZONE_CREATE_INFO_W2K import DNS_RPC_ZONE_CREATE_INFO_W2K\nfrom DNS_RPC_ZONE_DATABASE_DOTNET import DNS_RPC_ZONE_DATABASE_DOTNET\nfrom DNS_RPC_ZONE_DATABASE_W2K import DNS_RPC_ZONE_DATABASE_W2K\nfrom DNS_RPC_ZONE_DOTNET import DNS_RPC_ZONE_DOTNET\nfrom DNS_RPC_ZONE_EXPORT_INFO import DNS_RPC_ZONE_EXPORT_INFO\nfrom DNS_RPC_ZONE_INFO_DOTNET import DNS_RPC_ZONE_INFO_DOTNET\nfrom DNS_RPC_ZONE_INFO_LONGHORN import DNS_RPC_ZONE_INFO_LONGHORN\nfrom DNS_RPC_ZONE_INFO_W2K import DNS_RPC_ZONE_INFO_W2K\nfrom DNS_RPC_ZONE_LIST_DOTNET import DNS_RPC_ZONE_LIST_DOTNET\nfrom DNS_RPC_ZONE_LIST_W2K import DNS_RPC_ZONE_LIST_W2K\nfrom DNS_RPC_ZONE_SECONDARIES_DOTNET import DNS_RPC_ZONE_SECONDARIES_DOTNET\nfrom DNS_RPC_ZONE_SECONDARIES_LONGHORN import DNS_RPC_ZONE_SECONDARIES_LONGHORN\nfrom DNS_RPC_ZONE_SECONDARIES_W2K import DNS_RPC_ZONE_SECONDARIES_W2K\nfrom DNS_RPC_ZONE_W2K import DNS_RPC_ZONE_W2K\nfrom IP4_ARRAY import IP4_ARRAY\n","sub_path":"weather/bin/python_stubs/-1755623492/samba/dcerpc/dnsserver/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"22019668","text":"import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom decimal import getcontext, Decimal\r\ngetcontext().prec = 30\r\n\r\ndef getwordFreqList(data):\r\n X = np.zeros((len(np.unique(data[:, 0])), np.amax(np.unique(data[:, 1]))))\r\n for row in data:\r\n X[row[0] - 1, row[1] - 1] = row[2]\r\n wordFreq = np.sum(X, axis=0)\r\n vocabNew = np.vstack((np.unique(data[:, 1]), wordFreq)).T\r\n vocabNew = vocabNew[vocabNew[:, 1].argsort()[::-1]]\r\n return vocabNew\r\n\r\ndef getDocVSVocab (data, vocab) :\r\n X = np.zeros((len(np.unique(data[:,0])), np.amax(np.unique(data[:,1]))))\r\n for row in data:\r\n if row[1] in vocab[:,0]:\r\n X[row[0]-1, row[1]-1] = row[2]\r\n return X\r\n\r\ndef getDocVSClass_cntClass (label, map) :\r\n y = np.zeros((len(label),len(np.unique(map[:,1]))))\r\n i = 0\r\n for row in label:\r\n y[i,row-1] = 1\r\n i = i + 1\r\n cntClass = np.sum(y, axis=0)\r\n return y, cntClass\r\n\r\ndef getTheta(X, y, cntClass, vocab):\r\n vocabLen = len(vocab)\r\n classLen = len(cntClass)\r\n theta = np.zeros((vocabLen, classLen))\r\n for j in range(vocabLen):\r\n for k in range(classLen):\r\n num = np.sum(np.logical_and(X[:, j], y[:, k]))\r\n den = cntClass[k]\r\n cal = Decimal((num + 1) / (den + 2))\r\n theta[j, k] = cal\r\n return theta\r\n\r\ndef getPredictedOutput (theta, cntClass, X) :\r\n y_pred = []\r\n for n in range(len(X)) :\r\n numArr = []\r\n for k in range(len(cntClass)) :\r\n cal = 1\r\n for v in range(len(theta)):\r\n if X[n, v] != 0:\r\n cal = Decimal(cal) * Decimal(theta[v, k])\r\n else :\r\n cal = Decimal(cal) * Decimal((1 - theta[v, k]))\r\n num = Decimal(cal) * Decimal(cntClass[k])\r\n numArr.append(num)\r\n\r\n y_pred.append(np.argmax(numArr)+1)\r\n return y_pred\r\n\r\ndef getAccuracy(actual, pred) :\r\n acc = 0\r\n for idx in range(len(actual)):\r\n if actual[idx] == pred[idx] :\r\n acc = acc + 1\r\n return (acc/len(actual))*100\r\n\r\ndef getPrecisionRecallByClass(actual, pred) :\r\n preArr = []\r\n recArr = []\r\n classListPre, count1 = np.unique(actual, return_counts=True)\r\n classListRec, count2 = np.unique(pred, return_counts=True)\r\n for c in range(len(classListPre)):\r\n pre = 0\r\n for idx in range(len(actual)):\r\n if actual[idx] == classListPre[c] and actual[idx] == pred[idx]:\r\n pre = pre + 1\r\n preArr.append(pre/count1[c])\r\n\r\n for c in range(len(classListRec)):\r\n rec = 0\r\n for idx in range(len(actual)):\r\n if actual[idx] == classListRec[c] and actual[idx] == pred[idx]:\r\n rec = rec + 1\r\n recArr.append(rec/count2[c])\r\n\r\n fig1 = plt.figure()\r\n ax = fig1.add_subplot(111)\r\n ax.set_title('Deliverable 2.5.1 : Precision VS Class')\r\n ax.set_xlabel('Class')\r\n ax.set_ylabel('Precision')\r\n ax.plot(classListPre, preArr, ls='--', marker='o', c='y', label='Precision VS Class')\r\n\r\n fig2 = plt.figure()\r\n ax = fig2.add_subplot(111)\r\n ax.set_title('Deliverable 2.5.1 : Recall VS Class')\r\n ax.set_xlabel('Class')\r\n ax.set_ylabel('Recall')\r\n ax.plot(classListRec, recArr, ls='--', marker='v', c='m', label='Recall VS Class')\r\n\r\n plt.show()\r\n\r\n return preArr, recArr\r\n\r\ndef evaluateAlgorithm(data, label, map, vocab, testData, testLabel, testMap) :\r\n wordFreq_size = [100, 500, 1000, 2500, 5000, 7500, 10000, 12500, 25000, 50000]\r\n\r\n accArr = []\r\n for l in wordFreq_size:\r\n vocabNew = getwordFreqList(data)\r\n X = getDocVSVocab(data, vocabNew[0:l,:])\r\n y, cntClass = getDocVSClass_cntClass(label, map)\r\n theta = getTheta(X, y, cntClass, vocabNew)\r\n\r\n X_test = getDocVSVocab(testData, vocabNew[0:l,:])\r\n y_pred_test = getPredictedOutput(theta, cntClass, X_test)\r\n acc = getAccuracy(testLabel, y_pred_test)\r\n print(\"acc = \",acc)\r\n accArr.append(acc)\r\n preArr, recArr = getPrecisionRecallByClass(testLabel, y_pred_test)\r\n\r\n print(\"Accuracy Arr = \", accArr)\r\n print(\"Precision Arr = \", preArr)\r\n print(\"Recal Arr = \", recArr)\r\n fig1 = plt.figure()\r\n ax = fig1.add_subplot(111)\r\n ax.set_title('Deliverable 2.5.1 : Accuracy VS Vocab size')\r\n ax.set_xlabel('Vocab size')\r\n ax.set_ylabel('Accuracy')\r\n ax.plot(wordFreq_size, accArr, ls='--', marker='^', c='c', label='Accuracy VS Vocab size')\r\n plt.show()\r\n\r\ndef main():\r\n trainData = np.array(pd.read_csv('20news-bydate/matlab/train.data', sep=' ', header=None))\r\n trainLabel = np.array(pd.read_csv('20news-bydate/matlab/train.label', sep=' ', header=None))\r\n trainMap = np.array(pd.read_csv('20news-bydate/matlab/train.map', sep=' ', header=None))\r\n \r\n testData = np.array(pd.read_csv('20news-bydate/matlab/test.data', sep=' ', header=None))\r\n testLabel = np.array(pd.read_csv('20news-bydate/matlab/test.label', sep=' ', header=None))\r\n testMap = np.array(pd.read_csv('20news-bydate/matlab/test.map', sep=' ', header=None))\r\n \r\n vocab = np.array(pd.read_csv('vocabulary.txt', sep=' ', header=None))\r\n evaluateAlgorithm(trainData, trainLabel, trainMap, vocab, testData, testLabel, testMap)\r\n \r\nif __name__ == \"__main__\": main()","sub_path":"LogisticRegression_NaiveBayes/2_MultivariateEvent.py","file_name":"2_MultivariateEvent.py","file_ext":"py","file_size_in_byte":5321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"80762049","text":"import argparse\n\nfrom django.core.management import BaseCommand\n\nfrom ...importers.coppermine import CoppermineImporter\n\n\nclass Command(BaseCommand):\n def add_arguments(self, parser):\n parser.add_argument('-p', '--path',\n default='/',\n help='Target path in Edegal (defaults to gallery root)',\n )\n parser.add_argument('-c', '--root-category-id',\n type=int,\n default=0,\n help='Root category ID in Coppermine (defaults to gallery root)',\n )\n parser.add_argument('-d', '--database-connection-name',\n default='coppermine',\n help='Database connection name for Coppermine. Needs to be configured in settings.py.',\n )\n\n def handle(self, *args, **options):\n CoppermineImporter(\n path=options['path'],\n root_category_id=options['root_category_id'],\n connection_name=options['database_connection_name'],\n ).run()\n","sub_path":"gallery/management/commands/import_coppermine.py","file_name":"import_coppermine.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"489048458","text":"def TwoWayPartition(nums):\n pivot = nums[0]\n left = []\n right = []\n for num in nums[1:]:\n if num <= pivot:\n left.append(num)\n else:\n right.append(num)\n return left + [pivot] + right\n\n\ndef ThreeWayPartition(nums):\n pivot = nums[0]\n small, equal, large = [], [], []\n\n for num in nums:\n if num < pivot:\n small.append(num)\n elif num > pivot:\n large.append(num)\n else:\n equal.append(num)\n\n return small + equal + large\n\n\nif __name__ == '__main__':\n with open('1.txt', 'r') as f:\n for i in f.readlines():\n data = list(map(int, i.split()))\n partition = TwoWayPartition(data)\n print(' '.join(map(str, partition)))\n","sub_path":"TwoThreeWayPartition/13.py","file_name":"13.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"88306790","text":"import sys\nimport random\n\nfrom ability import Ability\nfrom core import *\nfrom core.timeline import *\nfrom core.log import *\nfrom core.afflic import *\nimport core.acl\nimport conf as globalconf\nimport core.condition\nimport slot\nimport core.floatsingle as floatsingle\nm_condition = core.condition\nconf = Conf()\n\nclass Modifier(object):\n _static = Static({\n 'all_modifiers': [],\n })\n mod_name = ''\n mod_type = '_nop' or 'att' or 'x' or 'fs' or 's' #....\n mod_order = '_nop' or 'passive' or 'ex' or 'buff' # chance dmg for crit\n mod_value = 0\n def __init__(this, name, mtype, order, value, condition=None):\n this.mod_name = name\n this.mod_type = mtype\n this.mod_order = order\n this.mod_value = value\n this.mod_condition = condition\n this.__active = 0\n this.on()\n #this._static.all_modifiers.append(this)\n #this.__active = 1\n\n @classmethod\n def mod(cls, mtype, all_modifiers=None):\n if not all_modifiers:\n all_modifiers = cls._static.all_modifiers\n m = {}\n for i in all_modifiers:\n if mtype == i.mod_type:\n if i.mod_order in m:\n m[i.mod_order] += i.get()\n else:\n m[i.mod_order] = 1 + i.get()\n ret = 1.0\n for i in m:\n ret *= m[i]\n return ret\n\n def get(this):\n return this.mod_value\n\n\n def on(this, modifier=None):\n if this.__active == 1:\n return this\n if modifier == None:\n modifier = this\n if modifier.mod_condition:\n if not m_condition.on(modifier.mod_condition):\n return this\n\n this._static.all_modifiers.append(modifier)\n this.__active = 1\n return this\n\n\n def off(this, modifier=None):\n if this.__active == 0:\n return this\n this.__active = 0\n if modifier==None:\n modifier = this\n idx = len(this._static.all_modifiers)\n while 1:\n idx -= 1\n if idx < 0:\n break\n if this._static.all_modifiers[idx] == modifier:\n this._static.all_modifiers.pop(idx)\n break\n return this\n\n def __enter__(this):\n this.on()\n\n def __exit__(this, exc_type, exc_val, exc_tb):\n this.off()\n\n def __repr__(this):\n return '<%s %s %s %s>'%(this.mod_name, this.mod_type, this.mod_order, this.mod_value)\n\n\nclass CrisisModifier(Modifier):\n def __init__(this, name, scale, hp):\n super().__init__('mod_{}_crisis'.format(name), 'att', 'hit', 0)\n this.hp_scale = scale\n this.hp_lost = 100 - hp\n if hp == 0:\n this.hp_cond = m_condition.on('hp=1')\n elif hp < 100:\n this.hp_cond = m_condition.on('hp={}%'.format(hp))\n else:\n this.hp_cond = 0\n\n def get(this):\n if this.hp_cond:\n this.mod_value = this.hp_scale * (this.hp_lost**2)/10000\n else:\n this.mod_value = 0\n return this.mod_value\n\n\nclass Buff(object):\n _static = Static({\n 'all_buffs': [],\n 'time_func':0,\n })\n def __init__(this, name='', value=0, duration=0, mtype=None, morder=None, toggle=False):\n this.name = name\n this.__value = value\n this.duration = duration\n this.mod_type = mtype or 'att' or 'x' or 'fs' or 's' #....\n this.bufftype = ''\n if morder ==None:\n if this.mod_type == 'crit':\n this.mod_order = 'chance'\n else:\n this.mod_order = 'buff'\n else:\n this.mod_order = morder or '' or 'passive' or 'ex' or 'buff' or 'punisher' #...\n this.toggle = toggle\n\n if this.mod_order != 'buff':\n this.bufftime = this.nobufftime\n if not this._static.time_func:\n this._static.time_func = this.nobufftime\n\n this.buff_end_timer = Timer(this.buff_end_proc)\n this.modifier = Modifier('mod_'+this.name, this.mod_type, this.mod_order, 0)\n this.modifier.get = this.get\n this.dmg_test_event = Event('dmg_formula')\n this.dmg_test_event.dmg_coef = 1\n this.dmg_test_event.dname = 'test'\n\n this.__stored = 0\n this.__active = 0\n #this.on()\n\n def nobufftime(this):\n return 1\n\n def bufftime(this):\n return this._static.time_func()\n\n\n def value(this, newvalue=None):\n if newvalue:\n return this.set(newvalue)\n else:\n return this.get()\n\n def get(this):\n if this.__active:\n return this.__value\n else:\n return 0\n\n def set(this, v, d=None):\n this.__value = v\n if d != None:\n this.duration = d\n return this\n\n def stack(this):\n stack = 0\n for i in this._static.all_buffs:\n if i.name == this.name:\n if i.__active != 0:\n stack += 1\n return stack\n\n def valuestack(this):\n stack = 0\n value = 0\n for i in this._static.all_buffs:\n if i.name == this.name:\n if i.__active != 0:\n stack += 1\n value += i.__value\n return value, stack\n\n def buff_end_proc(this, e):\n log('buff', this.name, '%s: %.2f'%(this.mod_type, this.value()), this.name+' buff end ')\n this.__active = 0\n\n if this.__stored:\n idx = len(this._static.all_buffs)\n while 1:\n idx -= 1\n if idx < 0:\n break\n if this == this._static.all_buffs[idx]:\n this._static.all_buffs.pop(idx)\n break\n this.__stored = 0\n value, stack = this.valuestack()\n if stack > 0:\n log('buff', this.name, '%s: %.2f'%(this.mod_type, value), this.name+' buff stack <%d>'%stack)\n this.modifier.off()\n\n\n def on(this, duration=None):\n if this.toggle:\n for i in this._static.all_buffs:\n if i.name == this.name:\n this = i\n if duration == None:\n d = this.duration * this.bufftime()\n else:\n d = duration * this.bufftime()\n if this.__active == 0:\n this.__active = 1\n if this.__stored == 0:\n this._static.all_buffs.append(this)\n this.__stored = 1\n if d >= 0:\n this.buff_end_timer.on(d)\n log('buff', this.name, '%s: %.2f'%(this.mod_type, this.value()), this.name+' buff start <%ds>'%d)\n else:\n if this.toggle:\n this.off()\n return this\n if d >= 0:\n this.buff_end_timer.on(d)\n log('buff', this.name, '%s: %.2f'%(this.mod_type, this.value()), this.name+' buff refresh <%ds>'%d)\n\n value, stack = this.valuestack()\n if stack > 1:\n log('buff', this.name, '%s: %.2f'%(this.mod_type, value), this.name+' buff stack <%d>'%stack)\n\n this.modifier.on()\n return this\n\n\n def off(this):\n if this.__active == 0:\n return\n log('buff', this.name, '%s: %.2f'%(this.mod_type, this.value()), this.name+' buff end ')\n this.__active = 0\n this.modifier.off()\n this.buff_end_timer.off()\n return this\n\n\nclass Selfbuff(Buff):\n def __init__(this, name='', value=0, duration=0, mtype=None, morder=None,toggle=False):\n Buff.__init__(this,name,value,duration,mtype,morder,toggle)\n this.bufftype = 'self'\n this.bufftime = this._bufftime\n\n def _bufftime(this):\n return this._static.time_func()\n\n def buffcount(this):\n bc = 0\n for i in this._static.all_buffs:\n if i.get() and i.bufftype=='self' or i.bufftype=='team':\n bc+=1\n return bc\n\nclass SingleActionBuff(Buff):\n # this buff lasts until the action it is buffing is completed\n def __init__(this, name='', value=0, casts=1, mtype=None, morder=None, event=None):\n super().__init__(name, value, -1, mtype, morder, False)\n this.bufftype = 'self'\n this.casts = casts\n this.end_event = event if event is not None else mtype\n if isinstance(this.end_event, str):\n Listener(this.end_event, this.l_off).on()\n else:\n for e in this.end_event:\n Listener(e, this.l_off).on()\n\n def on(this, casts=1):\n this.casts = casts\n return super().on(-1)\n\n def l_off(this, e):\n this.casts -= 1\n if this.casts <= 0:\n return super().off()\n else:\n return this\n \nclass Teambuff(Buff):\n def __init__(this, name='', value=0, duration=0, mtype=None, morder=None,toggle=False):\n Buff.__init__(this, name,value,duration,mtype,morder,toggle)\n this.bufftype = 'team'\n this.bufftime = this._bufftime\n\n def _bufftime(this):\n return this._static.time_func()\n\n def on(this, duration=None):\n Buff.on(this, duration)\n this.count_team_buff()\n return this\n\n def off(this):\n Buff.off(this)\n this.count_team_buff()\n return this\n\n def buff_end_proc(this,e):\n Buff.buff_end_proc(this,e)\n this.count_team_buff()\n\n def count_team_buff(this):\n this.dmg_test_event.modifiers = []\n for i in this._static.all_buffs:\n if i.name == 'simulated_def':\n this.dmg_test_event.modifiers.append(i.modifier)\n this.dmg_test_event()\n no_team_buff_dmg = this.dmg_test_event.dmg\n sd_mods = 1\n for i in this._static.all_buffs:\n if i.bufftype=='team' or i.bufftype=='debuff':\n if i.modifier.mod_type == 's':\n sd_mods = 1 + i.get() * 1/2\n else:\n this.dmg_test_event.modifiers.append(i.modifier)\n this.dmg_test_event()\n team_buff_dmg = this.dmg_test_event.dmg * sd_mods\n log('buff','team', team_buff_dmg/no_team_buff_dmg-1)\n\n\nclass Spdbuff(Buff):\n def __init__(this, name='', value=0, duration=0, mtype=None, morder=None,wide='self',toggle=False):\n mtype = 'spd'\n morder = 'passive'\n Buff.__init__(this, name,value,duration,mtype,morder,toggle)\n this.bufftype = wide\n this.bufftime = this._bufftime\n Event('speed')()\n\n def _bufftime(this):\n return this._static.time_func()\n\n def on(this, duration=None):\n Buff.on(this, duration)\n this.count_team_buff()\n return this\n\n def off(this):\n Buff.off(this)\n this.count_team_buff()\n return this\n\n def buff_end_proc(this,e):\n Buff.buff_end_proc(this,e)\n this.count_team_buff()\n\n def count_team_buff(this):\n this.dmg_test_event.modifiers = []\n for i in this._static.all_buffs:\n if i.name == 'simulated_def':\n this.dmg_test_event.modifiers.append(i.modifier)\n this.dmg_test_event()\n no_team_buff_dmg = this.dmg_test_event.dmg\n sd_mods = 1\n for i in this._static.all_buffs:\n if i.bufftype=='team' or i.bufftype=='debuff':\n if i.modifier.mod_type == 's':\n sd_mods = 1 + i.get() * 1/2\n else:\n this.dmg_test_event.modifiers.append(i.modifier)\n this.dmg_test_event()\n team_buff_dmg = this.dmg_test_event.dmg * sd_mods\n spd = this.stack() * this.value()\n if this.bufftype=='team' or this.bufftype=='debuff':\n team_buff_dmg += team_buff_dmg * spd\n log('buff','team', team_buff_dmg/no_team_buff_dmg-1)\n\n\n\nclass Debuff(Teambuff):\n def __init__(this, name='', value=0, duration=0, chance='1', mtype='def', morder=None,toggle=False):\n value = 0-value\n chance = float(chance)\n if chance!= 1:\n bd = 1.0/(1.0+value)\n bd = (bd-1)*chance+1\n value = 1-1.0/bd\n value = 0-value\n Teambuff.__init__(this, name,value,duration,mtype,morder,toggle)\n this.bufftype = 'debuff'\n this.bufftime = this.nobufftime\n\n def chance(c):\n bd = 1.0/(1.0+this.value)\n bd = (bd-1)*c+1\n this.value = 1-1.0/bd\n return this\n\n\nclass Skill(object):\n _static = Static({\n 's_prev' : '' ,\n 'first_x_after_s' : 0 ,\n 'silence' : 0 ,\n })\n charged = 0\n sp = 0\n silence_duration = 1.9\n name = '_Skill'\n def __init__(this, name=None, conf=None, ac=None):\n this.charged = 0\n if name:\n this.name = name\n if conf:\n this.conf = conf\n conf.sync_skill = this.sync_sp\n if ac :\n this.ac = ac\n elif conf:\n this.ac = S(this.name, this.conf)\n\n this._static.silence = 0\n this.silence_end_timer = Timer(this.cb_silence_end)\n this.silence_end_event = Event('silence_end')\n this.skill_charged = Event('{}_charged'.format(this.name))\n this.init()\n\n def __call__(this):\n return this.cast()\n\n def sync_sp(this,c):\n this.sp = c.sp\n\n def init(this):\n pass\n\n def charge(this,sp):\n this.charged += sp \n if this.charged >= this.sp:\n this.skill_charged()\n #if this.charged > this.sp: # should be \n #this.charged = this.sp\n\n def cb_silence_end(this, e):\n if loglevel >= 2:\n log('silence','end')\n this._static.silence = 0\n this.silence_end_event()\n\n\n def check(this):\n if this.sp == 0:\n return 0\n elif this._static.silence == 1:\n return 0\n elif this.charged >= this.sp:\n return 1\n else:\n return 0\n\n def cast(this):\n if not this.check():\n return 0\n else:\n if not this.ac() :\n return 0\n this.charged = 0\n this._static.s_prev = this.name\n # Even if animation is shorter than 1.9, you can't cast next skill before 1.9\n this.silence_end_timer.on(this.silence_duration)\n this._static.silence = 1\n if loglevel >= 2:\n log('silence','start')\n return 1\n\n# def ac(this):\n# #this.cast_event = Event(this.name+'_cast')\n# #this.cast_event()\n# return 1\n#\nclass Actionparts(object):\n def __init__(this, host, timing):\n this.atype = host.atype\n this.timing = timing\n this.timer = []\n idx = 0\n for i in timing :\n idx += 1\n t = Timer(this.cb, i)\n t.idx = idx\n this.timer.append(t)\n\n def on(this):\n for i in this.timer :\n i.on()\n\n def off(this):\n for i in this.timer :\n i.off()\n\n def cb(this, t):\n this.host._act(t.idx)\n\n\n\nclass Action(object):\n _static = Static({\n 'prev' : 0 ,\n 'doing' : 0 ,\n 'spd_func' : 0 ,\n })\n\n name = '_Action'\n index = 0\n recover_start = 0\n startup_start = 0\n _startup = 0\n _recovery = 0\n status = -2 # -2nop -1startup 0doing 1recovery\n idle = 0\n\n class Nop(object):\n name = '__idle__'\n index = 0\n status = -2\n idle = 1\n\n nop = Nop()\n\n def __init__(this, name=None, conf=None, act=None): ## can't change name after this\n if name != None:\n if type(name) == tuple:\n this.name = name[0]\n this.index = name[1]\n else:\n this.name = name\n this.index = 0\n this.atype = this.name\n\n if conf != None:\n this.conf = conf\n this.conf.sync_action = this.sync_config\n else:\n this.conf = Conf()\n this.conf.sync_action = this.sync_config\n\n if act != None:\n this.act = act\n\n\n if this._static.spd_func == 0:\n this._static.spd_func = this.nospeed\n if this._static.doing == 0:\n this._static.doing = this.nop\n if this._static.prev == 0:\n this._static.prev = this.nop\n\n this.cancel_by = []\n this.interrupt_by = []\n\n this.startup_timer = Timer(this._cb_acting)\n this.recovery_timer = Timer(this._cb_act_end)\n this.idle_event = Event('idle')\n this.act_event = Event(this.name)\n this.realtime()\n\n def sync_config(this, c):\n this._startup = c.startup\n this._recovery = c.recovery\n this._active = c.active\n\n def __call__(this):\n return this.tap()\n\n def getdoing(this):\n return this._static.doing\n def _setdoing(this):\n this._static.doing = this\n def getprev(this):\n return this._static.prev\n def _setprev(this):\n this._static.prev = this._static.doing\n\n def rt_tap(this):\n if this.rt_name != this.name:\n if this.atype == this.rt_name:\n this.atype = this.name\n this.rt_name = this.name\n this.act_event = Event(this.name)\n return this.o_tap()\n\n def realtime(this):\n this.rt_name = this.name\n this.tap, this.o_tap = this.rt_tap, this.tap\n\n def getrecovery(this):\n return this._recovery / this.speed()\n\n def getstartup(this):\n return this._startup / this.speed()\n\n def nospeed(this):\n return 1\n\n def speed(this):\n return this._static.spd_func()\n\n def _cb_acting(this, e):\n if this.getdoing() == this:\n this.status = 0\n this._act(1)\n this.status = 1\n this.recover_start = now()\n this.recovery_timer.on(this.getrecovery())\n\n\n def _cb_act_end(this, e):\n if this.getdoing() == this:\n if loglevel >= 2:\n log('ac_end',this.name)\n this.status = -2\n this._setprev() # turn this from doing to prev\n this._static.doing = this.nop\n this.idle_event()\n\n\n def _act(this, partidx):\n this.idx = partidx\n if loglevel >= 2:\n log('act',this.name)\n this.act(this)\n\n\n def act(this, action):\n this.act_event.name = this.name\n this.act_event.idx = this.idx\n this.act_event()\n\n\n def tap(this):\n doing = this._static.doing\n\n if doing.idle :\n if loglevel >= 2:\n log('tap',this.name, this.atype+'\\t', 'idle:%d'%doing.status)\n else:\n if loglevel >= 2:\n log('tap',this.name, this.atype+'\\t', 'doing '+doing.name+':%d'%doing.status)\n\n if doing == this : # self is doing\n return 0\n\n #if doing.idle # idle\n # pass\n if not doing.idle : # doing != this\n if doing.status == -1: # try to interrupt an action\n if this.atype in doing.interrupt_by : # can interrupt action\n doing.startup_timer.off()\n log('interrupt', doing.name , 'by '+this.name+'\\t', 'after %.2fs'%(now()-doing.startup_start) )\n else:\n return 0\n elif doing.status == 1: # try to cancel an action\n if this.atype in doing.cancel_by : # can interrupt action\n doing.recovery_timer.off()\n log('cancel', doing.name , 'by '+this.name+'\\t', 'after %.2fs'%(now()-doing.recover_start) )\n else:\n return 0\n elif doing.status == 0:\n print('err in action tap()')\n errrrrrrrrrrrr()\n this._setprev()\n this.status = -1\n this.startup_start = now()\n this.startup_timer.on(this.getstartup())\n this._setdoing()\n if now() <= 3:\n log('debug','tap,startup', this.getstartup())\n return 1\n\nclass X(Action):\n def __init__(this, name, conf, act=None):\n Action.__init__(this, name, conf, act)\n this.atype = 'x'\n this.interrupt_by = ['fs','s','dodge']\n this.cancel_by = ['fs','s','dodge']\n\n def realtime(this):\n this.act_event = Event('x')\n this.act_event.name = this.name\n this.rt_name = this.name\n this.tap, this.o_tap = this.rt_tap, this.tap\n\n def rt_tap(this):\n if this.rt_name != this.name:\n if this.atype == this.rt_name:\n this.atype = this.name\n this.rt_name = this.name\n this.act_event.name = this.name\n return this.o_tap()\n\n\nclass Fs(Action):\n def __init__(this, name, conf, act=None):\n Action.__init__(this, name, conf, act)\n this.atype = 'fs'\n this.interrupt_by = ['s']\n this.cancel_by = ['s','dodge']\n\n def realtime(this):\n this.act_event = Event('fs')\n this.act_event.name = this.name\n\nclass Fs_group(object):\n def __init__(this, name, conf, act=None):\n this.actions = {}\n this.conf = conf\n fsconf = conf.fs\n xnfsconf = [fsconf,fsconf,fsconf,fsconf,fsconf,fsconf]\n\n for i in range(5):\n xnfs = 'x%dfs'%(i+1)\n if xnfs in this.conf:\n xnfsconf[i] += this.conf[xnfs]\n\n if 'dfs' in this.conf:\n xnfsconf[5] += this.conf.dfs\n\n this.add('default', Fs(name, fsconf , act))\n this.add('x1', Fs(name, xnfsconf[0], act))\n this.add('x2', Fs(name, xnfsconf[1], act))\n this.add('x3', Fs(name, xnfsconf[2], act))\n this.add('x4', Fs(name, xnfsconf[3], act))\n this.add('x5', Fs(name, xnfsconf[4], act))\n this.add('dodge', Fs(name, xnfsconf[5], act))\n\n def add(this, name, action):\n this.actions[name] = action\n\n def __call__(this, before):\n if before in this.actions:\n return this.actions[before]()\n else:\n return this.actions['default']()\n\n\n\n\nclass S(Action):\n def __init__(this, name, conf, act=None):\n Action.__init__(this, name, conf, act)\n this.atype = 's'\n this.interrupt_by = []\n this.cancel_by = []\n\n def realtime(this):\n this.act_event = Event('s')\n this.act_event.name = this.name\n\n\nclass Dodge(Action):\n def __init__(this, name, conf, act=None):\n Action.__init__(this, name, conf, act)\n this.atype = 'dodge'\n this.cancel_by = ['fs','s']\n\n def realtime(this):\n this.act_event = Event('dodge')\n this.act_event.name = this.name\n\nclass Adv(object):\n Timer = Timer\n Event = Event\n Listener = Listener\n # vvvvvvvvv rewrite this to provide advanced tweak vvvvvvvvvv\n name = None\n def s1_proc(this, e):\n pass\n def s2_proc(this, e):\n pass\n def s3_proc(this, e):\n pass\n def fs_proc(this, e):\n pass\n def dmg_proc(this, name, amount):\n pass\n def s1_before(this, e):\n pass\n def s2_before(this, e):\n pass\n def s3_before(this, e):\n pass\n def fs_before(this, e):\n pass\n def dmg_before(this, name, amount):\n pass\n def speed(this):\n return 1\n def init(this):\n pass\n def equip(this):\n pass\n def setup(this):\n pass\n def d_acl(this):\n pass\n def d_slots(this):\n pass\n def slot_backdoor(this):\n pass\n def acl_backdoor(this):\n pass\n def prerun(this):\n pass\n # ^^^^^^^^^ rewrite these to provide advanced tweak ^^^^^^^^^^\n\n comment = ''\n #x_status = (0,0)\n mods = []\n conf = None\n a1 = None\n a2 = None\n a3 = None\n\n conf_default = Conf()\n\n #conf_default.latency.x = 0.05\n #conf_default.latency.sp = 0.05\n #conf_default.latency.default = 0.05\n #conf_default.latency.idle = 0\n\n # Latency represents the human response time, between when an event\n # triggers a \"think\" event, and when the human actually triggers\n # the input. Right now it's set to zero, which means \"perfect\"\n # response time (which is unattainable in reality.)\n conf_default.latency = Conf({'x':0,'sp':0,'default':0,'idle':0})\n\n conf_default.s1 = Conf({'dmg':0,'sp':0,'startup':0.1,'recovery':1.9})\n conf_default.s2 = Conf({'dmg':0,'sp':0,'startup':0.1,'recovery':1.9})\n conf_default.s3 = Conf({'dmg':0,'sp':0,'startup':0.1,'recovery':1.9})\n conf_default.dodge = Conf({'startup':0,'recovery':43.0/60.0})\n conf_default.fsf = Conf({'startup':0,'recovery':41.0/60.0})\n #conf_default.slots = Conf({'w':None,'d':None,'a':None})\n conf_default.slots = Conf()\n\n conf_default.acl = '''\n `s1\n `s2\n `s3\n '''\n\n acl_prepare_default = '''\n #pin=e.pin\n #dname=e.dname\n #dstat=e.dstat\n #didx=e.didx\n #prev = this.action.getprev()\n #pname=prev.name\n #pidx=prev.index\n #pstat=prev.status\n #rotation = this.rotation\n\n #xseq = -1\n #if dname[0] == 'x': xseq = didx\n #if dstat == -2: xseq = 0\n #seq = xseq\n\n #cancel=0\n #x=0\n #fsc=0\n #if pin == 'x': \\n x=didx\\n cancel=1\\n x_cancel=1\n #if pin == 'fs':\\n fsc=1\\n cancel=1\n\n #s=0\n #sx=0\n #if pin[0] == 's' and pin[1] != 'p':\\n s=int(pin[1])\n #if pin[-2:] == '-x':\\n s=int(pin[1])\\n sx=s\\n\n\n #sp=0\n #if pin == 'sp': sp=dname\n\n #s1=this.s1\n #s2=this.s2\n #s3=this.s3\n #fs=this.fs\n #fsf=this.fsf\n #dodge=this.dodge\n #dragon=this.dragonform\n '''\n #if pin[-2:] == '-x':\\n s=pidx\\n sx=pidx\\n print(sx)\\n print(pin)\\n errrrrrrr()\n\n\n def doconfig(this):\n\n # set buff\n this.action = Action()\n this.action._static.spd_func = this.speed\n # set buff\n this.buff = Buff()\n this.all_buffs = []\n this.buff._static.all_buffs = this.all_buffs\n this.buff._static.time_func = this.bufftime\n # set modifier\n this.modifier = Modifier(0,0,0,0)\n this.all_modifiers = []\n this.modifier._static.all_modifiers = this.all_modifiers\n\n # set ex\n this.ex = this.slots.c.ex\n\n # init actions\n # this.a_fs\n fsconf = this.conf.fs\n xnfsconf = [fsconf,fsconf,fsconf,fsconf,fsconf,fsconf]\n\n for i in range(5):\n xnfs = 'x%dfs'%(i+1)\n if xnfs in this.conf:\n xnfsconf[i] += this.conf[xnfs]\n\n if 'dfs' in this.conf:\n xnfsconf[5] += this.conf.dfs\n\n this.a_x1 = X(('x1',1),this.conf.x1)\n this.a_x2 = X(('x2',2),this.conf.x2)\n this.a_x3 = X(('x3',3),this.conf.x3)\n this.a_x4 = X(('x4',4),this.conf.x4)\n this.a_x5 = X(('x5',5),this.conf.x5)\n\n this.a_fs = Fs_group('fs',this.conf)\n this.a_fsf = Fs('fsf', this.conf.fsf)\n this.a_fsf.act_event = Event('none')\n\n this.a_dodge = Dodge('dodge', this.conf.dodge)\n\n # skill init\n this.s1 = Skill('s1', this.conf.s1)\n this.s2 = Skill('s2', this.conf.s2)\n this.s3 = Skill('s3', this.conf.s3)\n\n if this.conf.xtype == 'ranged':\n this.l_x = this.l_range_x\n this.l_fs = this.l_range_fs\n #this.fs_success = this.range_fs_sucess\n elif this.conf.xtype == 'melee':\n this.l_x = this.l_melee_x\n this.l_fs = this.l_melee_fs\n #this.fs_success = this.melee_fs_success\n\n # set cmd\n this.x1 = this.a_x1\n this.x2 = this.a_x2\n this.x3 = this.a_x3\n this.x4 = this.a_x4\n this.x5 = this.a_x5\n #this.fs = this.a_fs\n this.fsf = this.a_fsf\n this.dodge = this.a_dodge\n\n this.hits = 0\n this.dragonform = None\n\n def afflic_condition(this):\n if 'afflict_res' in this.conf:\n res_conf = this.conf.afflict_res\n for afflic in ['poison', 'paralysis', 'burn', 'blind', 'bog', 'stun', 'freeze', 'sleep']:\n if afflic in res_conf and 0 <= res_conf[afflic] <= 100:\n if this.condition('{} {} res'.format(res_conf[afflic], afflic)):\n vars(this.afflics)[afflic].resist = res_conf[afflic]\n else:\n vars(this.afflics)[afflic].resist = 100\n\n def sim_affliction(this):\n if 'sim_afflict' in this.conf:\n t = int(this.conf.sim_afflict.time)\n if t > 0:\n # if this.condition('{} for {}s'.format(this.conf.sim_afflict.type, t)):\n aff = vars(this.afflics)[this.conf.sim_afflict.type]\n aff.on('simulated'.format(this.conf.sim_afflict.type), 200, 0, duration=t, iv=t)\n aff.states = None\n\n def sim_buffbot(this):\n if 'sim_buffbot' in this.conf:\n if 'debuff' in this.conf.sim_buffbot:\n value = -this.conf.sim_buffbot.debuff\n if this.condition('boss def {:+.0%}'.format(value)):\n buff = this.Selfbuff('simulated_def',value,-1,mtype='def')\n buff.on()\n if 'buff' in this.conf.sim_buffbot:\n if this.condition('team str {:+.0%}'.format(this.conf.sim_buffbot.buff)):\n this.Selfbuff('simulated_att',this.conf.sim_buffbot.buff,-1).on()\n\n def sync_slot(this, conf_slots):\n #this.cmnslots(conf)\n #this.slots = slot.Slots()\n if now():\n print('cannot change slots after run')\n errrrrrrrrrrrr()\n if 'c' in conf_slots :\n this.slots.c = conf_slots.c\n elif not this.slots.c :\n this.slots.c = this.cmnslots.c\n\n if 'd' in conf_slots :\n this.slots.d = conf_slots.d\n elif not this.slots.d :\n this.slots.d = this.cmnslots.d\n\n if 'w' in conf_slots :\n this.slots.w = conf_slots.w\n elif not this.slots.w :\n this.slots.w = this.cmnslots.w\n\n if 'a' in conf_slots :\n this.slots.a = conf_slots.a\n elif not this.slots.a :\n this.slots.a = this.cmnslots.a\n #print this.slots\n\n\n def pre_conf(this):\n tmpconf = Conf()\n tmpconf += this.conf_default\n tmpconf += globalconf.get(this.name)\n tmpconf += Conf(this.conf)\n tmpconf(this.conf_init)\n this.conf = tmpconf\n\n\n def default_slot(this):\n from conf import slot_common\n this.cmnslots = slot.Slots()\n this.cmnslots.c.att = this.conf.c.att\n this.cmnslots.c.wt = this.conf.c.wt\n this.cmnslots.c.stars = this.conf.c.stars\n this.cmnslots.c.ele = this.conf.c.ele\n this.slot_common = slot_common.set\n this.slot_common(this.cmnslots)\n this.slots = this.cmnslots\n #print this.cmnslots\n\n def __init__(this,conf={},cond=0):\n if not this.name:\n this.name = this.__class__.__name__\n this.Event = Event\n this.Buff = Buff\n this.Debuff = Debuff\n this.Selfbuff = Selfbuff\n this.Teambuff = Teambuff\n this.Modifier = Modifier\n this.Conf = Conf\n this.log = log\n\n this.conf_init = conf\n this.ctx = Ctx().on()\n this.condition = m_condition.on\n this.m_condition = m_condition\n this.m_condition.set(cond)\n this._log = []\n loginit(this._log)\n\n this.s3_buff_on = False\n\n if not this.conf:\n this.conf = Conf()\n this.pre_conf()\n\n #this.slots = slot.Slots()\n this.default_slot()\n\n # def slot_backdoor():\n # pass\n # this.slot_backdoor = slot_backdoor\n\n this.conf.slot.sync_slot = this.sync_slot\n this.conf.slots.sync_slot = this.sync_slot\n\n if 1:\n this.crit_mod = this.solid_crit_mod\n else:\n this.crit_mod = this.rand_crit_mod\n\n this.skill = Skill()\n this._acl = None\n\n # set afflic\n this.afflics = Afflics()\n\n #this.classconf = this.conf\n this.init()\n\n #if type(this.conf).__name__ != 'Conf':\n # this.pre_conf()\n # this.conf.slot.sync_slot = this.sync_slot\n # this.conf.slots.sync_slot = this.sync_slot\n\n #this.ctx.off()\n\n\n def dmg_mod(this, name):\n mod = 1\n if name[:2] == 'o_':\n name = name[2:]\n\n if name[0] == 's':\n return mod * this.mod('s')\n elif name[0:2] == 'fs':\n return mod * this.mod('fs')\n elif name[0] == 'x':\n return mod * this.mod('x')\n else:\n return mod\n\n def mod(this, mtype):\n m = {}\n for i in this.all_modifiers:\n if mtype == i.mod_type:\n if i.mod_order in m:\n m[i.mod_order] += i.get()\n else:\n m[i.mod_order] = 1 + i.get()\n ret = 1.0\n for i in m:\n ret *= m[i]\n return ret\n\n def l_have_speed(this, e):\n this.speed = this.have_speed\n this.action._static.spd_func = this.speed\n\n def have_speed(this):\n return this.mod('spd')\n\n\n def crit_mod(this):\n pass\n\n def solid_crit_mod(this):\n m = {'chance':0, 'dmg':0, 'damage':0, 'passive':0, 'rate':0,}\n for i in this.all_modifiers:\n if 'crit' == i.mod_type:\n if i.mod_order in m:\n m[i.mod_order] += i.get()\n else:\n print('err in crit_mod')\n errrrrrrrrrrrrr()\n chance = m['chance']+m['passive']+m['rate']\n if chance > 1:\n chance = 1\n cdmg = m['dmg'] + m['damage'] + 1.7\n average = chance * (cdmg-1) + 1\n return average\n\n def rand_crit_mod(this):\n m = {'chance':0, 'dmg':0, 'damage':0, 'passive':0, 'rate':0,}\n for i in this.all_modifiers:\n if 'crit' == i.mod_type:\n if i.mod_order in m:\n m[i.mod_order] += i.get()\n else:\n print('err in crit_mod')\n errrrrrrrrrrrrr()\n chance = m['chance']+m['passive']+m['rate']\n if chance > 1:\n chance = 1\n cdmg = m['dmg'] + m['damage'] + 1.7\n r = random.random()\n if r < chance:\n return cdmg\n else:\n return 1\n\n\n def att_mod(this):\n att = this.mod('att')\n cc = this.crit_mod()\n k = this.killer_mod()\n return cc * att * k\n\n def killer_mod(this):\n m = 1\n for afflic in ['poison', 'paralysis', 'burn', 'blind', 'bog', 'stun', 'freeze', 'sleep']:\n rate = vars(this.afflics)[afflic].get()\n m += (this.mod(afflic + '_killer') - 1) * rate\n return m\n\n def def_mod(this):\n m = this.mod('def')\n if m < 0.5:\n return 0.5\n else:\n return m\n\n def sp_mod(this, name):\n sp_mod = 1\n for m in this.all_modifiers:\n if m.mod_type == 'sp':\n if m.mod_order == 'fs':\n if name.startswith('fs'):\n sp_mod += m.get()\n else:\n sp_mod += m.get()\n return sp_mod\n\n def sp_val(this, param):\n if isinstance(param, str):\n return this.ceiling(this.float_problem(this.conf[param+'.sp']*this.float_problem(this.sp_mod(param))))\n elif isinstance(param, int) and 1 <= param <= 5:\n return sum([this.ceiling(this.float_problem(this.conf['x{}.sp'.format(x)]*this.float_problem(this.sp_mod('x{}'.format(x))))) for x in range(1, param+1)])\n\n def bufftime(this):\n return this.mod('buff')\n\n def l_idle(this, e):\n \"\"\"\n Listener that is called when there is nothing to do.\n \"\"\"\n this.think_pin('idle')\n prev = this.action.getprev()\n if prev.name[0] == 's':\n this.think_pin(prev.name)\n if this.skill._static.first_x_after_s :\n this.skill._static.first_x_after_s = 0\n s_prev = this.skill._static.s_prev\n this.think_pin('%s-x'%s_prev)\n this.x()\n\n\n def getxseq(this):\n doing = this.action.getdoing()\n if doing.name[0] == 'x':\n return doing.index, doing.status\n else:\n return doing.name, doing.index\n\n\n def getprev(this):\n prev = this.action.getprev()\n return prev.name, prev.index, prev.status\n\n\n def fs(this):\n doing = this.action.getdoing()\n return this.a_fs(doing.name)\n\n\n def x(this):\n prev = this.action.getprev()\n x_next = 1\n if prev.name[0] == 'x':\n if prev.index != 5:\n x_next = prev.index + 1\n\n a = getattr(this, 'x%d'%x_next)()\n return 1\n\n\n def l_range_x(this, e):\n xseq = e.name\n dmg_coef = this.conf['%s.dmg'%xseq]\n sp_gain = this.conf['%s.sp'%xseq]\n if xseq == 'x5':\n log('x', '%s'%xseq, 0,'-------------------------------------c5')\n else:\n log('x', '%s'%xseq, 0)\n\n missile_timer = Timer(this.cb_missile, this.conf['missile_iv'][xseq] )\n missile_timer.dname = '%s_missile'%xseq\n missile_timer.amount = dmg_coef\n missile_timer.samount = sp_gain\n missile_timer()\n\n this.think_pin('x')\n\n def cb_missile(this, t):\n this.update_hits(t.dname)\n this.dmg_make(t.dname, t.amount)\n this.charge(t.dname, t.samount)\n\n\n def l_melee_x(this, e):\n xseq = e.name\n dmg_coef = this.conf['%s.dmg'%xseq]\n sp = this.conf['%s.sp'%xseq]\n if xseq == 'x5':\n log('x', '%s'%xseq, 0,'-------------------------------------c5')\n else:\n log('x', '%s'%xseq, 0)\n this.update_hits(xseq)\n this.dmg_make('%s'%xseq, dmg_coef)\n this.think_pin('x')\n this.charge('%s'%xseq, sp)\n\n def dodge(this):\n return this.a_dodge()\n\n def l_dodge(this, e):\n log('dodge','-')\n this.think_pin('dodge')\n\n def update_hits(this, name):\n if '_missile' in name:\n name = name.split('_')[0]\n try:\n hit = this.conf['{}.hit'.format(name)]\n if hit >= 0:\n this.hits += hit\n # print('debug', 'combo add', name, '{} -> {}'.format(hit, this.hits))\n else:\n this.hits = -hit\n # print('debug', 'combo break', name, '{} -> {}'.format(hit, this.hits))\n except AttributeError:\n pass\n\n def run(this, d = 300):\n global loglevel\n if not loglevel:\n loglevel = 0\n\n this.ctx.on()\n\n this.doconfig()\n\n this.l_idle = Listener('idle',this.l_idle)\n this.l_x = Listener('x',this.l_x)\n this.l_dodge = Listener('dodge',this.l_dodge)\n this.l_fs = Listener('fs',this.l_fs)\n this.l_s = Listener('s',this.l_s)\n #this.l_x = Listener(['x','x1','x2','x3','x4','x5'],this.l_x)\n #this.l_fs = Listener(['fs','x1fs','x2fs','x3fs','x4fs','x5fs'],this.l_fs)\n #this.l_s = Listener(['s','s1','s2','s3'],this.l_s)\n this.l_silence_end = Listener('silence_end' , this.l_silence_end )\n this.l_dmg_make = Listener('dmg_make' , this.l_dmg_make )\n this.l_true_dmg = Listener('true_dmg' , this.l_true_dmg )\n this.l_dmg_formula = Listener('dmg_formula' , this.l_dmg_formula )\n this.l_have_speed = Listener('speed' , this.l_have_speed )\n\n this.ctx.on()\n\n for i in this.conf.mod:\n v = this.conf.mod[i]\n if type(v) == tuple:\n this.slots.c.mod.append(v)\n if type(v) == list:\n this.slots.c.mod += v\n if this.a1 :\n this.slots.c.a.append(this.a1)\n if this.a2 :\n this.slots.c.a.append(this.a2)\n if this.a3 :\n this.slots.c.a.append(this.a3)\n\n\n this.equip()\n this.setup()\n\n this.d_slots()\n this.slot_backdoor()\n #print this.slots\n this.base_att = int(this.slots.att(globalconf.forte))\n this.displayed_att = int(this.slots._att(globalconf.forte))\n this.slots.oninit(this)\n\n this.prerun()\n this.afflic_condition()\n this.sim_affliction()\n this.sim_buffbot()\n\n this.d_acl()\n this.acl_backdoor()\n\n if not this._acl:\n this._acl_str = core.acl.acl_func_str(this.conf.acl)\n from core.acl import do_act\n this._acl = do_act\n\n\n if type(this.conf.rotation) == list:\n for i in this.conf.rotation:\n i = i.lower()\n this.get_next_act = this.get_next_act_from_list\n elif type(this.conf.rotation) == str:\n this.conf.rotation = this.conf.rotation.lower()\n\n if type(this.conf.rotation_init) == list:\n for i in this.conf.rotation_init:\n i = i.lower()\n this.get_next_act = this.get_next_act_from_list\n elif type(this.conf.rotation_init) == str:\n this.conf.rotation_init = this.conf.rotation_init.lower()\n\n this.rotation_init = 0\n if type(this.conf.rotation_init) in [str,list]:\n this.rotation_init = 1\n this.rotation_repeat = this.conf.rotation\n this.conf.rotation = this.conf.rotation_init\n\n if type(this.conf.rotation) in [str, list]:\n this.rotation_stat = 0\n this.xstat_prev = ''\n this.act_next = 0\n this.rt_len = len(this.conf.rotation)\n this.o_rt = this.conf.rotation\n\n\n Event('idle')()\n this.debug()\n end = Timeline.run(d)\n log('sim','end')\n \n for aff, up in this.afflics.get_uptimes().items():\n if len(this.comment) > 0:\n this.comment += '; '\n this.comment += '{:.0%} {} uptime'.format(up, aff)\n\n return end\n\n def debug(this):\n pass\n\n def think_pin(this, pin):\n # pin as in \"signal\", says what kind of event happened\n def cb_think(t):\n if loglevel >= 2:\n log('think', t.pin, t.dname)\n this._acl(this, t)\n\n if pin in this.conf.latency :\n latency = this.conf.latency[pin]\n else:\n latency = this.conf.latency.default\n\n t = Timer(cb_think).on(latency)\n doing = this.action.getdoing()\n t.pin = pin\n t.dname = doing.name\n t.dstat = doing.status\n t.didx = doing.index\n\n\n def l_silence_end(this, e):\n doing = this.action.getdoing()\n sname = this.skill._static.s_prev\n if doing.name[0] == 'x':\n this.skill._static.first_x_after_s = 1\n else:\n this.think_pin(sname+'-x') # best choice\n this.think_pin(sname)\n #if doing.name[0] == 's':\n # no_deed_to_do_anythin\n\n\n # implement single float of c in python\n def float_problem(this, a):\n return floatsingle.tofloat(a)\n\n #this ceiling is the true ceiling\n def ceiling(this, a):\n b = int(a)\n if b == a:\n return b\n else:\n return b + 1\n\n\n def charge_p(this, name, sp):\n if type(sp) == str and sp[-1] == '%':\n percent = int(sp[:-1])\n this.s1.charge(this.ceiling(this.conf.s1.sp*percent/100))\n this.s2.charge(this.ceiling(this.conf.s2.sp*percent/100))\n this.s3.charge(this.ceiling(this.conf.s3.sp*percent/100))\n log('sp', name, '%d%% '%percent,'%d/%d, %d/%d, %d/%d'%(\\\n this.s1.charged, this.s1.sp, this.s2.charged, this.s2.sp, this.s3.charged, this.s3.sp) )\n this.think_pin('prep')\n return\n\n def charge(this, name, sp):\n # sp should be integer\n sp = int(sp) * this.float_problem(this.sp_mod(name))\n sp = this.float_problem(sp)\n sp = this.ceiling(sp)\n this.s1.charge(sp)\n this.s2.charge(sp)\n this.s3.charge(sp)\n this.think_pin('sp')\n log('sp', name, sp,'%d/%d, %d/%d, %d/%d'%(\\\n this.s1.charged, this.s1.sp, this.s2.charged, this.s2.sp, this.s3.charged, this.s3.sp) )\n\n def l_dmg_formula(this, e):\n name = e.dname\n dmg_coef = e.dmg_coef\n if hasattr(e, 'dtype'):\n name = e.dtype\n if 'modifiers' in e.__dict__ :\n if e.modifiers!=None and e.modifiers != 0:\n this.all_modifiers = e.modifiers\n e.dmg = this.dmg_formula(name, dmg_coef)\n this.all_modifiers = this.modifier._static.all_modifiers\n e.ret = e.dmg\n return\n\n def dmg_formula(this, name, dmg_coef):\n att = 1.0 * this.att_mod() * this.base_att\n armor = 10 * this.def_mod()\n #return float(dmg_coef) * this.dmg_mod(name) * this.att_mod() / this.def_mod()\n #return float(dmg_coef) * this.dmg_mod(name) * this.def_mod()\n return 5.0/3 * dmg_coef * this.dmg_mod(name) * att/armor * 1.5 # true formula\n #return att/armor * dmg_coef * this.dmg_mod(name)\n\n def l_true_dmg(this, e):\n log('dmg', e.dname, e.count, e.comment)\n\n def l_dmg_make(this, e):\n if 'dtype' in vars(e):\n this.dmg_make(e.dname, e.dmg_coef, e.dtype)\n else:\n this.dmg_make(e.dname, e.dmg_coef)\n\n def dmg_make(this, name, dmg_coef, dtype=None, fixed=False):\n if dtype == None:\n dtype = name\n count = this.dmg_formula(dtype, dmg_coef) if not fixed else dmg_coef\n log('dmg', name, count)\n this.dmg_proc(name, count)\n return count\n\n def dmg_make_withspshow(this, name, dmg_coef, dtype=None):\n if dtype == None:\n dtype = name\n\n count = this.dmg_formula(dtype, dmg_coef)\n this.dmg_before(name, count)\n\n if name[0] == 'x':\n spgain = this.conf[name[:2]+'.sp']\n log('dmg', name, count, '%d/%d, %d/%d, %d/%d (+%d)'%(\\\n this.s1.charged, this.s1.sp, this.s2.charged, this.s2.sp, this.s3.charged, this.s3.sp, spgain) )\n elif name[:2] == 'fs':\n spgain = this.conf['fs.sp']\n log('dmg', name, count, '%d/%d, %d/%d, %d/%d (+%d)'%(\\\n this.s1.charged, this.s1.sp, this.s2.charged, this.s2.sp, this.s3.charged, this.s3.sp, spgain) )\n else:\n spgain = 0\n if name[:2]+'.sp' in this.conf:\n spgain = this.conf[name[:2]+'.sp']\n log('dmg', name, count, '%d/%d, %d/%d, %d/%d (-%d)'%(\\\n this.s1.charged, this.s1.sp, this.s2.charged, this.s2.sp, this.s3.charged, this.s3.sp, spgain) )\n\n this.dmg_proc(name, count)\n\n\n def l_melee_fs(this, e):\n log('fs','succ')\n dmg_coef = this.conf.fs.dmg\n this.fs_before(e)\n this.update_hits('fs')\n this.dmg_make('fs', dmg_coef)\n this.fs_proc(e)\n this.think_pin('fs')\n this.charge('fs',this.conf.fs.sp)\n\n def l_range_fs(this, e):\n log('fs','succ')\n this.fs_before(e)\n this.update_hits('fs')\n dmg_coef = this.conf['fs.dmg']\n sp_gain = this.conf['fs.sp']\n missile_timer = Timer(this.cb_missile, this.conf['missile_iv']['fs'] )\n missile_timer.dname = 'fs_missile'\n missile_timer.amount = dmg_coef\n missile_timer.samount = sp_gain\n missile_timer()\n this.fs_proc(e)\n this.think_pin('fs')\n\n def l_s(this, e):\n this.update_hits(e.name)\n\n prev, index, stat = this.getprev()\n if prev == 'fs':\n log('cast', e.name, 0,' %d/%d, %d/%d, %d/%d (%s after fs)'%(\\\n this.s1.charged, this.s1.sp, this.s2.charged, this.s2.sp, this.s3.charged, this.s3.sp, e.name) )\n elif prev[0] == 'x':\n log('cast', e.name, 0,' %d/%d, %d/%d, %d/%d (%s after c%s)'%(\\\n this.s1.charged, this.s1.sp, this.s2.charged, this.s2.sp, this.s3.charged, this.s3.sp, e.name, index ) )\n else:\n log('cast', e.name, 0,' %d/%d, %d/%d, %d/%d (%s after %s)'%(\\\n this.s1.charged, this.s1.sp, this.s2.charged, this.s2.sp, this.s3.charged, this.s3.sp, e.name, prev ) )\n\n dmg_coef = this.conf[e.name+'.dmg']\n func = e.name + '_before'\n tmp = getattr(this, func)(e)\n if tmp!= None:\n dmg_coef = tmp\n if dmg_coef :\n this.dmg_make(e.name , dmg_coef)\n\n\n if 'buff' in this.conf[e.name] and this.conf[e.name+'.buff'] is not None:\n buffarg = this.conf[e.name+'.buff']\n wide = buffarg[0]\n buffarg = buffarg[1:]\n buff = None\n if wide == 'team':\n buff = Teambuff(e.name, *buffarg).on()\n elif wide == 'self':\n buff = Selfbuff(e.name, *buffarg).on()\n elif wide == 'debuff':\n buff = Debuff(e.name, *buffarg).on()\n else:\n buff = Buff(e.name, *buffarg).on()\n if e.name == 's3' and buff.toggle:\n this.s3_buff_on = buff.get()\n func = e.name + '_proc'\n getattr(this, func)(e)\n\n\n def rotation(this):\n r = 0\n if not this.act_next:\n this.act_next = this.get_next_act()\n anext = this.act_next\n\n doing = this.action.getdoing()\n dname = doing.name\n dstat = doing.status\n #didx = doing.index\n\n if dname[0]!='x' and dstat != 1:\n return 0\n #print(anext)\n #print(dname, anext, dstat)\n if this.xstat_prev != dname:\n this.xstat_prev = ''\n if anext[0] in ['c','x'] :\n #log('debug','-',this.xstat_prev,dname)\n if dname != 'x'+anext[1] :\n r = 0\n elif dstat==1 and this.xstat_prev=='':\n this.xstat_prev = dname\n #log('debug','rotation',dname)\n r = 1\n else :\n r = 0\n this.x()\n elif anext[0] == 's':\n #print(dname, anext)\n r = vars(this)[anext]()\n elif anext == 'fs':\n r = this.fs()\n #r = this.fs()\n elif anext in ['dodge','d']:\n r = this.dodge()\n elif anext == 'dragon':\n r = this.dragonform()\n elif anext == 'end':\n #def end(foo):\n # Timeline.stop()\n ##Listener('idle',end).on()\n #Timer(end).on()\n Timeline.stop()\n if r :\n this.act_next = this.get_next_act()\n return r\n\n\n def get_next_act_from_list(this):\n p = this.rotation_stat\n rt = this.conf.rotation\n if this.o_rt != rt:\n print('cannot change rotation after run')\n errrrrrrrrrrrrrrrrr()\n ret = ''\n ret += rt[p]\n p += 1\n if p >= this.rt_len:\n p = 0\n this.rotation_stat = p\n return ret.lower()\n\n\n def get_next_act(this):\n p = this.rotation_stat\n rt = this.conf.rotation\n\n if this.o_rt != rt:\n print('cannot change rotation after run')\n errrrrrrrrrrrrrrrrr()\n ret = ''\n while(1):\n if p >= this.rt_len:\n this.rotation_reset()\n rt = this.conf.rotation\n p = 0\n c = ord(rt[p])\n if c > ord('a') and c < ord('z') :\n break\n elif c > ord('A') and c < ord('Z') :\n break\n elif c > ord('0') and c < ord('9') :\n break\n else:\n p += 1\n if rt[p] == 'c':\n xidx = int(rt[p+1])\n if xidx > 5 or xidx < 1:\n print(rt+'\\nlocation:%d,%s'%(p+1,xidx))\n errrrrrrrrrrrrrrrr()\n ret += rt[p:p+2]\n p += 2\n elif rt[p] in ['1','2','3','4','5'] and rt[p+1] in ['x','c']:\n xidx = int(rt[p])\n ret += 'c'+rt[p]\n p += 2\n elif rt[p] == 's':\n sidx = int(rt[p+1])\n if sidx > 3 or sidx < 1:\n print(rt+'\\nlocation:%d,%s'%(p+1,sidx))\n errrrrrrrrrrrrrrrr()\n ret += rt[p:p+2]\n p += 2\n elif rt[p:p+2] == 'fs':\n ret = 'fs'\n p += 2\n elif rt[p:p+6] == 'dragon':\n ret = 'dragon'\n p += 6\n elif rt[p] == 'd':\n ret = 'dodge'\n p += 1\n elif rt[p:p+3] == 'end':\n ret = 'end'\n p += 3\n else:\n print(rt+'\\nlocation:%d'%(p))\n print(rt[p])\n errrrrrrrrrrrrrrrrrr()\n\n if p >= this.rt_len:\n this.rotation_reset()\n p = 0\n this.rotation_stat = p\n return ret\n\n def rotation_reset(this):\n if this.rotation_init :\n this.rotation_init = 0\n this.conf.rotation = this.rotation_repeat\n this.rt_len = len(this.conf.rotation)\n this.o_rt = this.conf.rotation\n\n\n\n\nif __name__ == '__main__':\n print('to use adv_test')\n\n","sub_path":"core/advbase.py","file_name":"advbase.py","file_ext":"py","file_size_in_byte":53227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"28563846","text":"from selenium import webdriver\nimport time\nimport unittest\nfrom case.x_add_bug import AddBug\n\n\nclass AddBugTest(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.driver = webdriver.Chrome()\n cls.ad = AddBug(cls.driver)\n cls.driver.get(\"http://10.155.20.210/pms/index.php?m=user&f=login\")\n cls.driver.maximize_window()\n\n def test_add_bug(self):\n self.ad.login()\n t= time.strftime(\"%Y-%m-%d %H:%M:%S\")\n title = \"���是标题\"+t\n content = '''\n [步骤]111\n [结果]111\n [期望]111\n '''\n self.ad.addbug(title,content)\n res = self.ad.is_add_success(title)\n assert res == True\n\n @classmethod\n def tearDownClass(cls):\n time.sleep(2)\n cls.driver.quit()\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"case/x_test_add_bug.py","file_name":"x_test_add_bug.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"145275061","text":"from django.core.urlresolvers import reverse\nfrom sentry.testutils import APITestCase\n\n\nclass GroupIndexTest(APITestCase):\n def test_simple(self):\n self.create_group(checksum='a' * 32)\n self.create_group(checksum='b' * 32)\n\n self.login_as(user=self.user)\n url = reverse('sentry-api-0-project-group-index', kwargs={\n 'project_id': self.project.id})\n response = self.client.get(url, format='json')\n assert response.status_code == 200\n","sub_path":"tests/sentry/api/endpoints/test_project_group_index.py","file_name":"test_project_group_index.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"47938689","text":"from room import Room\nfrom player import Player\nfrom item import Item\n\n# Declare all the rooms\n\nroom = {\n 'outside': Room(\"Outside Cave Entrance\",\n \"North of you, the cave mount beckons\"),\n\n 'foyer': Room(\"Foyer\", \"\"\"Dim light filters in from the south. Dusty\npassages run north and east.\"\"\"),\n\n\n 'overlook': Room(\"Grand Overlook\", \"\"\"A steep cliff appears before you, falling\ninto the darkness. Ahead to the north, a light flickers in\nthe distance, but there is no way across the chasm.\"\"\"),\n\n 'lagoon': Room(\"Grand Lagoon\", \"\"\"You fell into the dark lagoon. Go back to the south, Grand Overlook or go North to cross\nthe uncrossable bridge\"\"\"),\n\n 'bridge': Room(\"Uncrossable Bridge\", \"\"\"uh oh! This is the uncrossable bride, therfore you cannot cross it!. Go back to the \n lagoon to find your way out\"\"\"),\n\n 'narrow': Room(\"Narrow Passage\", \"\"\"The narrow passage bends here from west\nto north. The smell of gold permeates the air.\"\"\"),\n\n\n 'treasure': Room(\"Treasure Chamber\", \"\"\"You've found the long-lost treasure\nchamber! Sadly, it has already been completely emptied by\nearlier adventurers. The only exit is to the south.\"\"\"),\n\n}\n\n\n# Link rooms together\n\nroom['outside'].n_to = room['foyer']\nroom['foyer'].s_to = room['outside']\nroom['foyer'].n_to = room['overlook']\nroom['foyer'].e_to = room['narrow']\nroom['overlook'].s_to = room['foyer']\nroom['overlook'].n_to = room['lagoon']\nroom['lagoon'].s_to = room['overlook']\nroom['lagoon'].n_to = room['bridge']\nroom['bridge'].s_to = room['lagoon']\nroom['narrow'].w_to = room['foyer']\nroom['narrow'].n_to = room['treasure']\nroom['treasure'].s_to = room['narrow']\n\n#\n# Main\n#\n\n\nroom['outside'].items.append(Item(\"Armor\", \"protective covering for a warrior\"))\nroom['outside'].items.append(Item(\"Map\", \"diagrammatic representation of the land for a warrior\"))\nroom['outside'].items.append(Item(\"Pen\", \"writing instrument to make notes on the map for a warrior\"))\nroom['foyer'].items.append(Item(\"Shield\", \"a broad piece of metal used for protection for a warrior\"))\nroom['foyer'].items.append(Item(\"Water\", \"drinkable liquid for a warrior\"))\nroom['overlook'].items.append(Item(\"Sword\", \"a weapon with a long metal blade for a warrior\"))\nroom['overlook'].items.append(Item(\"Boots\", \"footwear for a warrior\"))\nroom['narrow'].items.append(Item(\"Cape\", \"a cloak for a warrior\"))\nroom['narrow'].items.append(Item(\"Rock\", \"a weapon for a warrior\"))\nroom['treasure'].items.append(Item(\"Key\", \"key to the treasure for a warrior\"))\n\n\n\n\n# Make a new player object that is currently in the 'outside' room.\n\nnew_player = Player('ale', room['outside'])\n\n\n# Write a loop that:\n#\n# * Prints the current room name\n# * Prints the current description (the textwrap module might be useful here).\n# * Waits for user input and decides what to do.\n#\n# If the user enters a cardinal direction, attempt to move to the room there.\n# Print an error message if the movement isn't allowed.\n#\n# If the user enters \"q\", quit the game.\n\ndirections = [\"n\", \"s\", \"e\", \"w\"]\n\nwhile True:\n print(f'\\n{new_player}')\n user_input = input(\"\\nWhere would you want to go (n,s,e or w)? Type q to quit the game: \")\n split_input = user_input.split()\n\n if user_input == \"q\":\n print(\"*** Game Over! ***\")\n break\n elif user_input in directions:\n new_player.change_room(user_input)\n elif user_input == \"i\" or user_input == \"inventory\":\n new_player.player_items()\n elif len(split_input) == 2:\n item_name = split_input[1]\n if split_input[0].lower() == \"get\":\n item = new_player.room.get_item(item_name)\n if item:\n item.on_take()\n new_player.room.remove_item(item)\n new_player.items.append(item)\n new_player.room.room_items()\n else:\n print(f\"\\n{item_name} does not exist in room\")\n elif split_input[0].lower() == \"drop\":\n item = new_player.get_item(item_name)\n if item:\n item.on_drop()\n # remove the item from the player\n new_player.remove_item(item)\n # Add it to the room's items\n new_player.room.items.append(item)\n new_player.player_items()\n new_player.room.room_items()\n else:\n print(f\"\\n{item_name} does not exist in room\")\n else:\n print(\"\\nINVALID INPUT, TRY AGAIN!\\n\")\n\n","sub_path":"src/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":4461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"510135177","text":"# This source code is part of the Biotite package and is distributed\n# under the 3-Clause BSD License. Please see 'LICENSE.rst' for further\n# information.\n\nimport biotite.structure as struc\nimport biotite.structure.io as strucio\nimport numpy as np\nfrom os.path import join\nfrom .util import data_dir\nimport pytest\n\n@pytest.fixture\ndef bond_list():\n bond_array = np.array([(0,1),(2,1),(3,1),(3,4),(3,1),(1,2),(4,0),(6,4)])\n return struc.BondList(7, bond_array)\n\ndef test_creation(bond_list):\n # Test includes redundancy removal and max bonds calculation\n assert bond_list.as_array().tolist() == [[0, 1, 0],\n [1, 2, 0],\n [1, 3, 0],\n [3, 4, 0],\n [0, 4, 0],\n [4, 6, 0]]\n assert bond_list._max_bonds_per_atom == 3\n assert bond_list._atom_count == 7\n\n\ndef test_modification(bond_list):\n # Already in list\n bond_list.add_bond(3, 1)\n # Also already in list -> update\n bond_list.add_bond(1, 3, 1)\n # Not in list\n bond_list.add_bond(4, 1)\n # In list -> remove\n bond_list.remove_bond(4, 0)\n # Not in list -> Do nothing\n bond_list.remove_bond(0, 3)\n # Remove mutliple bonds, one of them is not in list\n bond_list.remove_bonds(struc.BondList(10, np.array([(1,0),(1,2),(8,9)])))\n assert bond_list.as_array().tolist() == [[1, 3, 1],\n [3, 4, 0],\n [4, 6, 0],\n [1, 4, 0]]\n\ndef test_access(bond_list):\n # Bigger challenge with different bond types\n bond_list.add_bond(1, 3, 1)\n bonds, bond_types = bond_list.get_bonds(0)\n assert bonds.tolist() == [1, 4]\n assert bond_types.tolist() == [0, 0]\n bonds, bond_types = bond_list.get_bonds(1)\n assert bonds.tolist() == [0, 2, 3]\n assert bond_types.tolist() == [0, 0, 1]\n bonds, bond_types = bond_list.get_bonds(2)\n assert bonds.tolist() == [1]\n assert bond_types.tolist() == [0]\n bonds, bond_types = bond_list.get_bonds(3)\n assert bonds.tolist() == [1, 4]\n assert bond_types.tolist() == [1, 0]\n bonds, bond_types = bond_list.get_bonds(4)\n assert bonds.tolist() == [3, 0, 6]\n assert bond_types.tolist() == [0, 0, 0]\n\ndef test_merge(bond_list):\n merged_list = bond_list.merge(struc.BondList(8, np.array([(4,6),(6,7)])))\n assert merged_list.as_array().tolist() == [[0, 1, 0],\n [1, 2, 0],\n [1, 3, 0],\n [3, 4, 0],\n [0, 4, 0],\n [4, 6, 0],\n [6, 7, 0]]\n\ndef test_concatenation(bond_list):\n bond_list += struc.BondList(3, np.array([(0,1,2),(1,2,2)]))\n assert bond_list.as_array().tolist() == [[0, 1, 0],\n [1, 2, 0],\n [1, 3, 0],\n [3, 4, 0],\n [0, 4, 0],\n [4, 6, 0],\n [7, 8, 2],\n [8, 9, 2]]\n assert bond_list._max_bonds_per_atom == 3\n assert bond_list._atom_count == 10\n\ndef test_indexing(bond_list):\n sub_list = bond_list[:]\n assert sub_list.as_array().tolist() == bond_list.as_array().tolist()\n sub_list = bond_list[1:6:2]\n assert sub_list.as_array().tolist() == [[0, 1, 0]]\n sub_list = bond_list[:4]\n assert sub_list.as_array().tolist() == [[0, 1, 0],\n [1, 2, 0],\n [1, 3, 0]]\n sub_list = bond_list[2:]\n assert sub_list.as_array().tolist() == [[1, 2, 0],\n [2, 4, 0]]\n \n sub_list = bond_list[[0,3,4]]\n assert sub_list.as_array().tolist() == [[1, 2, 0],\n [0, 2, 0]]\n\n sub_list = bond_list[np.array([True,False,False,True,True,False,True])]\n assert sub_list.as_array().tolist() == [[1, 2, 0],\n [0, 2, 0],\n [2, 3, 0]]\n\ndef test_atom_array_consistency():\n array = strucio.load_structure(join(data_dir, \"1l2y.mmtf\"))[0]\n ca = array[array.atom_name == \"CA\"]\n # Just for testing, does not refelct real bonds\n bond_list = struc.BondList(ca.array_length(), \n np.array([(0,1),(2,8),(5,15),(1,5),(0,9),(3,18),(2,9)])\n )\n # The bonds, should always point to the same atoms (same res_id),\n # irrespective of indexing\n ids1 = ca.res_id[bond_list.as_array()[:,:2].flatten()]\n # Some random boolean mask as index\n mask = np.array([1,1,1,1,0,1,0,0,1,1,0,1,1,0,0,1,1,0,1,1], dtype=np.bool)\n ca = ca[mask]\n bond_list = bond_list[mask]\n ids2 = ca.res_id[bond_list.as_array()[:,:2].flatten()]\n assert ids1.tolist() == ids2.tolist()","sub_path":"tests/structure/test_bonds.py","file_name":"test_bonds.py","file_ext":"py","file_size_in_byte":5231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"567862356","text":"from typing import List\n\nimport pytest\n\nfrom itsim.software.context import Context\nfrom itsim.machine.endpoint import Endpoint\nfrom itsim.machine.process_management.process import Process\nfrom itsim.machine.process_management.thread import ThreadKilled\nfrom itsim.simulator import Simulator, advance\nfrom itsim.types import Timeout\n\n\nCemetary = List[str]\n\n\nDELAY_GRANDCHILD = 20\nDELAY_CADET = 5\nTIMEOUT_SUPERLONG = 100\n\n\ndef watcher(context: Context, cemetary: Cemetary, proc_parent: Process) -> None:\n proc_parent.wait()\n cemetary.append(\"watcher\")\n\n\ndef grandchild(context: Context, pid_expected: int, cemetary: Cemetary) -> None:\n assert context.process.pid == pid_expected\n advance(DELAY_GRANDCHILD)\n cemetary.append(\"grandchild\")\n\n\ndef elder(context: Context, pid_expected: int, cemetary: Cemetary) -> None:\n assert context.process.pid == pid_expected\n thread_grandchild = context.thread.clone(grandchild, pid_expected, cemetary)\n thread_grandchild.join()\n cemetary.append(\"elder\")\n\n\ndef cadet(context: Context, pid_expected: int, cemetary: Cemetary) -> None:\n assert context.process.pid == pid_expected\n advance(DELAY_CADET)\n cemetary.append(\"cadet\")\n\n\ndef super_long(context: Context, pid_expected: int, cemetary: Cemetary) -> None:\n try:\n assert context.process.pid == pid_expected\n advance(TIMEOUT_SUPERLONG * 10)\n pytest.fail(\"Supposed to be killed as the process exits.\")\n except ThreadKilled:\n raise\n finally:\n cemetary.append(\"super_long\")\n\n\ndef parent(context: Context, cemetary: Cemetary) -> None:\n context.process.fork_exec(watcher, cemetary, context.process)\n thread_elder = context.thread.clone(elder, context.process.pid, cemetary)\n thread_cadet = context.thread.clone(cadet, context.process.pid, cemetary)\n thread_super_long = context.thread.clone(super_long, context.process.pid, cemetary)\n\n try:\n thread_elder.join()\n thread_cadet.join()\n except Timeout:\n pytest.fail(\"Not supposed to time out while waiting for these threads.\")\n\n try:\n thread_super_long.join(TIMEOUT_SUPERLONG)\n pytest.fail(\"Supposed to time out while waiting for super long.\")\n except Timeout:\n pass\n\n cemetary.append(\"parent\")\n context.process.kill()\n\n\ndef test_context_thread_lifecycle():\n sim = Simulator()\n cemetary = []\n Endpoint().with_proc_in(sim, 0, parent, cemetary)\n sim.run()\n assert sim.now() == pytest.approx(TIMEOUT_SUPERLONG + max(DELAY_GRANDCHILD, DELAY_CADET))\n assert cemetary == [\"cadet\", \"grandchild\", \"elder\", \"parent\", \"super_long\", \"watcher\"]\n","sub_path":"tests/integ/test_thread_lifecycle.py","file_name":"test_thread_lifecycle.py","file_ext":"py","file_size_in_byte":2627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"605795961","text":"#_____Autor:Zhy\r\n#_____CreatDate:2018/11/16\r\n\r\nfrom django import template\r\nfrom app02.models import Article,Category,My_tag\r\nfrom django.db.models import Count\r\n\r\nregister = template.Library()\r\n@register.inclusion_tag(\"app02/1.my_tag.html\")\r\ndef my_tag_1(id):\r\n user_article = Article.objects.filter(user_id=id).values()\r\n user_category = Category.objects.filter(article__user_id=id).annotate(c= Count(\"article__id\")).values_list(\"id\",\"title\",\"c\")\r\n user_tag = My_tag.objects.filter(article__user_id=id).annotate(c= Count(\"article__id\")).values_list(\"id\",\"title\",\"c\")\r\n return (locals())","sub_path":"app02/templatetags/my_tags.py","file_name":"my_tags.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"326472837","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\n\nimport os\nimport six\n# Uses: https://github.com/john-kurkowski/tldextract\nimport tldextract\nfrom functools import wraps\n\nfrom flask import request, session, flash, redirect\nfrom flask import current_app\n\nfrom flask.ext.aselect.aselectapi import ASelectAPI, REQUESTS_RETURN_USER\n\nfrom werkzeug import url_quote\nfrom werkzeug.local import LocalProxy\n_aselect = LocalProxy(lambda: current_app.extensions['aselect'])\n_ticket_store = LocalProxy(lambda: _aselect.ticket_store)\n\nimport logging\n\n# Convenient references\nlogger = logging.getLogger('ASelectAPI:utils')\n\n\ndef get_config(app):\n \"\"\"Conveniently get the social configuration for the specified\n application without the annoying 'ASELECT_' prefix.\n\n :param app: The application to inspect\n \"\"\"\n items = app.config.items()\n prefix = 'ASELECT_'\n\n def strip_prefix(tup):\n return (tup[0].replace(prefix, ''), tup[1])\n\n return dict([strip_prefix(i) for i in items if i[0].startswith(prefix)])\n\n\n\"\"\"Helper class to derive parts of the name from the e-mail address\nand NetID\n\"\"\"\nclass NetIDParser(object):\n student = False\n required_domains = []\n\n __netid = None\n __email = None\n\n __given_name = None\n __last_name = None\n __display_name = None\n __initials = None\n\n def __init__(self, aselect_client=None, netid = None, email = None):\n self.required_domains = aselect_client.required_domains\n # Make sure both the NetID as the E-mail are in lower case, it can\n # only cause bugs and is of no use otherwise.\n self.__netid = netid.lower()\n self.__email = email.lower()\n\n # split_attrspec() returns 'email' user and the _subdomain_ of\n # self.required_domains otherwise None\n try:\n netid_split = self.split_addrspec(self.__netid)\n email_split = self.split_addrspec(self.__email)\n assert(netid_split and email_split)\n except:\n return None\n self.__netid_user, self.__netid_subdomain = netid_split\n self.__email_user, self.__email_subdomain = email_split\n \n self.last_name = self.__email_user.split('.')[-1]\n\n @property\n def given_name(self):\n email_no_last_name = self.__email_user.replace(self.__last_name, '')\n # These are either initials or a name. To compare we delete\n # the dots as netid never has dots\n given_name_or_initials = email_no_last_name.replace('.', '')\n netid_no_last_name = self.__netid_user.replace(self.__last_name, '')\n\n\n # If given_name_or_initials == netid_no_last_name, then too\n # bad, we only know initials.\n self.initials = email_no_last_name\n self.name_parsed = True\n \n if given_name_or_initials != netid_no_last_name:\n # We know the given name!:\n self.__given_name = netid_no_last_name.capitalize()\n\n return self.__given_name\n\n @property\n def initials(self):\n # All letters in initials should be capitalized.\n return self.__initials.upper()\n\n @initials.setter\n def initials(self, _initials):\n self.__initials = _initials\n\n @property\n def last_name(self):\n return self.__last_name.capitalize()\n\n @last_name.setter\n def last_name(self, _last_name):\n self.__last_name = _last_name\n\n @property\n def display_name(self):\n return self.__display_name\n\n @display_name.setter\n def display_name(self, given_name, initials, last_name):\n self.__last_name = last_name\n\n @property\n def student(self):\n if 'student' in self.__email_subdomain.split('.'):\n return True\n else:\n return False\n\n @property\n def display_name(self):\n # This is a combination of the last name which is certain and\n # either initials or given name.\n first_part = self.given_name or self.initials\n second_part = ' ' + self.last_name\n return first_part + second_part\n\n def split_addrspec(self, string):\n domain_extract = tldextract.extract(string)\n user_identifier = string.split('@')[0]\n try:\n assert(domain_extract.domain in self.required_domains)\n return [user_identifier, domain_extract.subdomain]\n except:\n return None\n\n def __repr__(self):\n return '' % self.display_name\n\n def __str__(self):\n return 'Parsed User: %s' % self.display_name\n\n\n\n\nclass ASelectConnect(object):\n\n def __init__(self, **kwargs):\n\n self.after_login_func = None\n\n self.app_id = six.text_type(os.environ.get('ASELECT_APP_ID'))\n self.ticket_store = _ticket_store\n \n\n def signal_error(self, msg):\n \"\"\"Signals an error. It does this by storing the message in the\n session. Use :meth:`errorhandler` to this method.\n \"\"\"\n session['aselect_error'] = msg\n\n def fetch_error(self):\n \"\"\"Fetches the error from the session. This removes it from the\n session and returns that error. This method is probably useless\n if :meth:`errorhandler` is used.\n \"\"\"\n return session.pop('aselect_error', None)\n \n def get_next_url(self):\n \"\"\"Returns the URL where we want to redirect to. This will\n always return a valid URL.\n \"\"\"\n return (request.values.get('next') or\n request.referrer or request.url_root\n )\n\n def get_current_url(self):\n \"\"\"the current URL + next.\"\"\"\n return request.base_url + '?next=' + url_quote(self.get_next_url())\n\n def get_success_url(self):\n \"\"\"Return the internal success URL.\n\n :internal:\n \"\"\"\n return self.get_current_url() + '&aselect_complete=yes'\n\n def errorhandler(self, f):\n \"\"\"Called if an error occurs with the message. By default\n ``'aselect_error'`` is added to the session so that :meth:`fetch_error`\n can fetch that error from the session. Alternatively it makes sense\n to directly flash the error for example::\n\n @aselect.errorhandler\n def on_error(message):\n flash(u'Error: ' + message)\n \"\"\"\n self.signal_error = f\n return f\n\n def after_login(self, f):\n \"\"\"This function will be called after login. It must redirect to\n a different place and remember the user somewhere. The session\n is not modified by this library. The decorated function is\n passed a :class:`ASelectResponse` object.\n \"\"\"\n self.after_login_func = f\n return f\n\n def loginhandler(self, f):\n \"\"\"Marks a function as login handler. This decorator injects some\n more A-Select required logic. Always decorate your login function with\n this decorator.\n \"\"\"\n @wraps(f)\n def decorated(*args, **kwargs):\n if request.args.get('aselect_complete') != 'yes':\n return f(*args, **kwargs)\n\n aselect_api = ASelectAPI()\n rid = request.args.get('rid')\n credentials = request.args.get('aselect_credentials')\n response = aselect_api.verify_credentials(\n rid=rid,\n aselect_cred=credentials)\n\n # verify ticket?\n\n if response.status:\n aselect_resp = ASelectResponse(response)\n #self.ticket_store = _aselect.ticket_store\n # only credentials used\n self.store_ticket(\n aselect_cred=response.aselect_cred,\n rid=rid\n )\n\n return self.after_login_func(aselect_resp)\n\n elif response.status:\n self.signal_error('The request was cancelled')\n return redirect(self.get_current_url())\n\n elif response.status == 'R':\n # Should do some other things too\n self.signal_error('Please reload the page and try again')\n return redirect(self.get_current_url())\n\n self.signal_error('A-Select authentication error')\n return redirect(self.get_current_url())\n return decorated\n\n def try_login(self, app_url):\n \"\"\"This tries to login. This function\n must be called from the loginhandler.\n \"\"\"\n aselect_api = ASelectAPI()\n try:\n auth_request = aselect_api.auth_user(\n app_id=self.app_id,\\\n app_url=self.get_success_url(), \\\n aselect_id=None, \\\n forced_logon='false'\n )\n return redirect(auth_request)\n except:\n logger.error('A-Select error, auth_request failed.')\n logger.debug(aselect_api)\n self.signal_error('A-Select request was invalid')\n flash('Authentication error: This is an \\\n internal error and has nothing to do with your A-Select ID.', 'error')\n return redirect('/')\n\n def agent_error(error):\n return 'A-Select Agent connection failed', 500\n\n def store_ticket(self, aselect_cred, rid):\n self.ticket_store.store_ticket(aselect_cred, rid)\n return True\n\n def get_ticket(self, aselect_id, aselect_org, check_expiration=True):\n return self.ticket_store.get_ticket(aselect_id, aselect_org)\n\n def kill_ticket(self, aselect_id, aselect_org):\n \"\"\"To destroy the ticket\n \"\"\"\n ticket_full = self.get_ticket(aselect_id, aselect_org).ticket\n ticket = ticket_full.get('ticket')\n aselect_api = ASelectFilter()\n akill = aselect_api.kill_ticket(aselect_ticket=ticket)\n rkill = self.ticket_store.kill_ticket(aselect_id, aselect_org)\n\n if akill == 1 and rkill == 1:\n return 1\n if akill == 0 or rkill == 0:\n return 1\n if akill == 0 and rkill == 0:\n return 0\n\n\n\nclass ASelectResponse(object):\n \"\"\"Passed to the `after_login` function. Provides all the information\n sent from the A-Select provider.\n \"\"\"\n\n def __init__(self, response):\n # Check for user object, could check for object type as well\n # once API is stable\n # This should work or something went wrong.\n try:\n self.aselect_id = response.aselect_id\n self.aselect_org = response.aselect_org\n self.aselect_mail = response.aselect_mail\n assert((self.aselect_id is not None) and (self.aselect_mail is not None))\n except:\n self.signal_error('No aselect_id and/or email returned. Fatal error.')\n #flash('Internal error occured! Please \\\n # contact the administrator.')\n return abort(500)\n\n # This is not needed as we can just try to set and catch on\n # AttributeError, but this looks cleaner. However we could\n # then remove the `aselect_request' attribute from the\n # object, but this is easier to debug.\n if response.aselect_request not in REQUESTS_RETURN_USER:\n # This should not be possible\n abort(500)\n\n # Attributes, copy so that it can be picklejsoned\n self.attributes = None or response.aselect_attr.copy()\n\n # Not really useful data\n self.aselect_data = response.data\n\n # Do not know yet how A-Select will represent the data.\n # Cleanest would be to input a dictionary depending on the\n # A-Select provider\n # self.given_name = response.given_name\n\n # Guess the full name\n self.user = NetIDParser(\n aselect_client=_aselect, \n netid=self.aselect_id,\n email=self.aselect_mail\n )\n # if user:\n # # If A-Select does not tell, we will try to guess\n # # instead!\n # self.student = user.student\n \n # self.display_name = user.display_name\n # self.given_name = user.given_name\n # self.initials = user.initials\n # self.last_name = user.last_name\n # self.name_parsed = True\n \n","sub_path":"flask_aselect/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"143781759","text":"#!/usr/bin/env python\nimport os\nimport glob\n\nMCPI_TEMPLATE = os.environ['HOME'] + \"/Documents/Scratch Projects/mcpi_template.sb\"\nNU_SCRATCH = \"/usr/share/scratch/NuScratch*.image\"\nSQUEAK_STACK = \"/usr/bin/squeak-stack\"\n\ndef raspi_revision():\n revision = \"0000\"\n try:\n f = open('/proc/cpuinfo', 'r')\n for line in f:\n if line[0:8] == 'Revision':\n length = len(line)\n revision = line[11:length - 1]\n f.close()\n except:\n revision = \"0000\"\n return revision\n\ndef lower_than_raspi3():\n REVISIONS = [\"0002\", \"0003\", \"0004\", \"0005\", \"0006\", \"0007\", \"0008\", \"0009\",\n \"000d\", \"000e\", \"000f\", \"0010\", \"0011\", \"0012\", \"a01041\", \"a21041\", \"900092\"]\n RAPI3_REVISIONS = [\"a02082\", \"a22082\"]\n return raspi_revision() in REVISIONS\n\nif glob.glob(NU_SCRATCH) and glob.glob(SQUEAK_STACK):\n os.system(\"%s -vm-sound-alsa %s --document %s & sleep 60\" % (SQUEAK_STACK, NU_SCRATCH, MCPI_TEMPLATE))\nelse:\n sleep = 10\n if lower_than_raspi3():\n sleep = 30\n os.system(\"scratch --document \\\"%s\\\" & sleep %d\" % (MCPI_TEMPLATE, sleep))\n\nos.system(\"lxterminal -t Scratch2MCPI -e python \" + os.environ['HOME'] + \"/scratch2mcpi/scratch2mcpi.py\")\n","sub_path":"run_scratch2mcpi.py","file_name":"run_scratch2mcpi.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"108000373","text":"import peewee\nimport logging\n\nlogger = logging.getLogger(\"basic_operations\")\nlogger.setLevel(logging.DEBUG)\nfh = logging.FileHandler(\"db.log\")\nfh.setLevel(logging.DEBUG)\nlogger.addHandler(fh)\n\ndatabase = peewee.SqliteDatabase(\"customers.db\")\ndatabase.connect()\ndatabase.execute_sql('PRAGMA foreign_key = ON;')\ndatabase.execute_sql('drop table if exists customer;')\n\n\nclass BaseModel(peewee.Model):\n class Meta:\n database = database\n\n\nclass Customer(BaseModel):\n \"\"\"\n This class defines a Customer in the databaase\n Customer ID.\n Name.\n Lastname.\n Home address.\n Phone number.\n Email address.\n Status (active or inactive customer).\n Credit limit.\n \"\"\"\n customer_id = peewee.CharField(primary_key=True, max_length=30)\n name = peewee.CharField(max_length=50)\n last_name = peewee.CharField(max_length=50, null=True)\n address = peewee.CharField(max_length=75)\n phone_number = peewee.CharField(max_length=15)\n email = peewee.CharField(max_length=320) # based on max email address length search\n status = peewee.CharField(max_length=10) # \"Inactive\" or \"Active\"\n credit_limit = peewee.FloatField()\n\n\ndef create_tables():\n with database.transaction():\n logger.debug(\"Creating table Customer\")\n database.create_tables([Customer])\n\n\ndef drop_tables():\n with database.transaction():\n logger.debug(\"Dropping table Customer\")\n database.drop_tables([Customer])\n\n\ndef add_customer(customer_id, name, last_name, address, phone_number, email, status, credit_limit):\n try:\n with database.transaction():\n customer = Customer.create(\n customer_id=customer_id,\n name=name,\n last_name=last_name,\n address=address,\n phone_number=phone_number,\n email=email,\n status=status,\n credit_limit=credit_limit\n )\n logger.debug(f\"Customer saved {customer_id}\")\n\n except Exception as e:\n logger.warning(f\"error creating {customer_id}\")\n logger.warning(e)\n\n\ndef search_customer(customer_id):\n try:\n customer = Customer.get(Customer.customer_id == customer_id)\n logger.debug(f\"Found customer {customer_id}\")\n return {\n \"name\": customer.name,\n \"last_name\": customer.last_name,\n \"phone_number\": customer.phone_number,\n \"email\": customer.email,\n }\n except Exception as e:\n logger.warning(f\"error reading customer {customer_id}\")\n logger.warning(e)\n return {}\n\n\ndef delete_customer(customer_id):\n try:\n customer = Customer.get(Customer.customer_id == customer_id)\n with database.transaction():\n customer.delete_instance()\n logger.debug(f\"Deleted customer id {customer_id}\")\n return True\n except Exception as e:\n logger.warning(e)\n return False\n\n\ndef update_customer_credit(customer_id, credit_limit):\n try:\n with database.transaction():\n customer = Customer.get(Customer.customer_id == customer_id)\n customer.credit_limit = credit_limit\n customer.save()\n except Exception as e:\n raise ValueError(\"NoCustomer {}\".format(customer_id))\n\n\ndef list_active_customers():\n try:\n active_customers = Customer.select().where(Customer.status == 'active')\n for customer in active_customers:\n print(f\"{customer.name} {customer.last_name} status is {customer.status}\")\n return len(active_customers)\n except Exception as e:\n print(e)\n return 0\n\n\nif __name__ == '__main__':\n add_customer(1, \"Sally\", \"Shen\", \"5859 20th pl., Seattle, WA, 98115\", \"917-888-9999\",\n \"shenyingyy@gmail.com\", \"active\", 2000)\n\n","sub_path":"students/Sally_Shen/lesson04/assignment/src/basic_operations.py","file_name":"basic_operations.py","file_ext":"py","file_size_in_byte":3848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"150080894","text":"from django.conf.urls import patterns, include, url\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n url(r'^/(?P\\w+)', 'blogapp.views.authorposts'),\n url(r'^about/', 'blogapp.views.about'),\n url(r'^$', 'blogapp.views.blog'),\n # url(r'^blog/', include('blog.urls')),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^like/(?P\\d+)', 'blogapp.views.like'),\n url(r'^(?P\\d+)', 'blogapp.views.individual'),\n url(r'^signup/', 'blogapp.views.signup'),\n url(r'^login/', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),\n url(r'logout/', 'django.contrib.auth.views.logout', {'next_page': '/'}),\n url(r'^accounts/', include('registration.backends.default.urls'))\n )\n\nif settings.DEBUG:\n urlpatterns += patterns('',\n (r'^static/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),\n )\n","sub_path":"myblog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"638696428","text":"\"\"\"\nPython script log.py\n\nCreated by Anne Pajon under user 'pajon01' on 13/04/2016\n\"\"\"\n\nimport os\nimport logging\nimport logging.config\nfrom config import cfg\n\nHOST = cfg['SMTP_SERVER']\nFROM = cfg['SEND_FROM']\nTO = cfg['LOG_SEND_TO']\nSUBJECT = 'Error from Clarity PPMS'\n\n# logging definition\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': True,\n 'formatters': {\n 'verbose': {\n 'format': '%(asctime)s %(name)-24s %(levelname)-8s: %(message)s'\n },\n 'simple': {\n 'format': '%(name)-24s %(levelname)-8s: %(message)s'\n },\n },\n 'handlers': {\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'simple'\n },\n 'info_file': {\n 'level': 'DEBUG',\n 'class': 'logging.handlers.RotatingFileHandler',\n 'filename': 'info.log',\n 'maxBytes': 1000000,\n 'backupCount': 5,\n 'formatter': 'verbose',\n },\n 'error_file': {\n 'level': 'ERROR',\n 'class': 'logging.handlers.RotatingFileHandler',\n 'filename': 'errors.log',\n 'maxBytes': 1000000,\n 'backupCount': 5,\n 'formatter': 'verbose',\n },\n 'email': {\n 'level': 'ERROR',\n 'class': 'logging.handlers.SMTPHandler',\n 'mailhost': HOST,\n 'fromaddr': FROM,\n 'toaddrs': [TO],\n 'subject': SUBJECT,\n 'formatter': 'verbose',\n },\n },\n 'loggers': {\n 'glsclient': {\n 'handlers': ['console', 'info_file', 'error_file'],\n 'propagate': True,\n 'level': 'INFO',\n },\n 'ppmsclient': {\n 'handlers': ['console', 'info_file', 'error_file'],\n 'propagate': True,\n 'level': 'DEBUG',\n },\n }\n}\n\n\ndef get_custom_logger(logfile=None, noemail=False):\n if logfile:\n if not os.path.exists(os.path.dirname(logfile)):\n os.makedirs(os.path.dirname(logfile))\n LOGGING['handlers']['info_file']['filename'] = logfile\n LOGGING['handlers']['error_file']['filename'] = logfile + \".errors\"\n if not noemail:\n LOGGING['loggers']['ppmsclient']['handlers'].append('email')\n logging.config.dictConfig(LOGGING)\n return logging.getLogger('ppmsclient')\n","sub_path":"ppmsclient/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"310753306","text":"#! /usr/bin/env python\n\n# Import settings.py (settings.py is stored in the same folder as this file and contains a function that converts the config.json into a python dictionary)\nimport settings\n# Import other useful modules\nfrom os import *\nfrom time import *\nfrom sys import *\nfrom math import *\nfrom mpd import MPDClient\n\nlcd_settings = settings.getSettings() # Ask settings.py for the settings\n\n# Extract all useful settings for this script\ntext_split_string_setting = lcd_settings['config_text_split_string']['value']\nwelcome_message_duration_setting = lcd_settings['config_welcome_message_duration']['value']\nwelcome_message_bool_setting = lcd_settings['config_welcome_message_bool']['value']\nwelcome_message_string_one_setting = lcd_settings['config_welcome_message_string_one']['value']\nwelcome_message_string_two_setting = lcd_settings['config_welcome_message_string_two']['value']\nwelcome_message_string_three_setting = lcd_settings['config_welcome_message_string_three']['value']\nwelcome_message_string_four_setting = lcd_settings['config_welcome_message_string_four']['value']\nmpd_host_setting = lcd_settings['config_host']['value']\n\n# Perform some checks to see if the settings are in the right format/type and are not empty\nif(len(text_split_string_setting) <= 0):\n\ttext_split_string_setting = ' '\nelse:\n\ttext_split_string_setting = ' ' + str(text_split_string_setting) + ' '\nif(len(welcome_message_duration_setting) <= 0):\n\twelcome_message_duration_setting = ' '\nif(len(str(welcome_message_duration_setting)) < 1):\n\t# I don't know what the user want when they leave the input field for welcome_message_duration empty or enter non-int chars, so I'll just turn the feature off\n\twelcome_message_duration_setting = 0\n\twelcome_message_bool_setting = False\nelif(type(welcome_message_duration_setting) != int):\n\t# Try to convert the setting into an int\n\ttry:\n\t\twelcome_message_duration_setting = int(welcome_message_duration_setting)\n\texcept:\n\t\t# The setting could not be converted to an int, turn it off\n\t\twelcome_message_duration_setting = 0\n\t\twelcome_message_bool_setting = False\nif(welcome_message_bool_setting == 'true' or welcome_message_bool_setting == 'True'):\n\twelcome_message_bool_setting = True\nelif(welcome_message_bool_setting == 'false' or welcome_message_bool_setting == 'False'):\n\twelcome_message_bool_setting = False\n\n# Check the length of messages\nif(len(welcome_message_string_one_setting) <= 0):\n\twelcome_message_string_one_setting = ' '\nelif(len(welcome_message_string_one_setting) > 20):\n\twelcome_message_string_one_setting = welcome_message_string_one_setting[:20]\nif(len(welcome_message_string_two_setting) <= 0):\n\twelcome_message_string_two_setting = ' '\nelif(len(welcome_message_string_two_setting) > 20):\n\twelcome_message_string_two_setting = welcome_message_string_two_setting[:20]\nif(len(welcome_message_string_three_setting) <= 0):\n\twelcome_message_string_three_setting = ' '\nelif(len(welcome_message_string_three_setting) > 20):\n\twelcome_message_string_three_setting = welcome_message_string_three_setting[:20]\nif(len(welcome_message_string_four_setting) <= 0):\n\twelcome_message_string_four_setting = ' '\nelif(len(welcome_message_string_four_setting) > 20):\n\twelcome_message_string_four_setting = welcome_message_string_four_setting[:20]\nif(len(mpd_host_setting) <= 0):\n\t# This script NEEDS mpd_host_setting. It cannot be left empty. To avoid errors, set the setting to localhost if no host is configured.\n\tmpd_host_setting = 'localhost'\n\t# Maybe a TODO for later: check if host is reachable and/or reconnect if connection lost\n\nmpd_host = mpd_host_setting\nmpd_port = \"6600\"\nmpd_password = \"volumio\"\n\nclient = MPDClient()\nclient.connect(mpd_host, mpd_port)\n\n#import LCD-related python libs\nfrom lcd_display import lcd\n\n#make sure python knows what an LCD is\nmy_lcd = lcd()\n\n#make lcd-positions work properly\nlcd_position=[1,3,2,4]\n\n# define some options\nmoveText = 1 # How many characters to move each time. This should remain 1. Also, this should never have a float-value.\ninfoRefreshTimeWait = 0.4 # How often should the script check for new song-/radio-info (value is in seconds)?\ntimeWaitTimeStamp = 0 # This variable needs to be initialized with value 0\ninfoRefreshTimeStamp = time() # This variable needs to be initialized with the value of time()\ntimeWait = 1 # Amount of time to wait before moving a piece of text on the lcd\nlineTimeWait = 0 # Should have a value of 0, unless the moving text should wait extra long before restarting the line-scrolling\n\n# Make sure the script doesn't throw errors\nsongInfo=[' ', ' ', ' ',' ']\ntextOne = ' '\ntextTwo = ' '\ntextThree = ' '\ntextFour = ' '\n\ndef sendToLCD(lineNum, textToDisplay): #This function will send a string to the LCD screen\n my_lcd.display_string(textToDisplay, lcd_position[lineNum])\n\nwelcomeTimestamp = time() # This variable needs to be initialized with the value of time()\n\n# Make sure the LCD displays normal text when spoken to\nsendToLCD(0, ' ')\nsendToLCD(1, ' ')\nsendToLCD(2, ' ')\nsendToLCD(3, ' ')\n\n# Show welcome message if the user enabled the feature\nif(welcome_message_bool_setting == True):\n\tsendToLCD(0, welcome_message_string_one_setting)\n\tsendToLCD(1, welcome_message_string_two_setting)\n\tsendToLCD(2, welcome_message_string_three_setting)\n\tsendToLCD(3, welcome_message_string_four_setting)\n\tsleep(welcome_message_duration_setting)\n\ndef updateLCDinfo():\n\treturnData = [' ', ' ', ' ', ' ']\n\tcurrentSong = client.currentsong()\n\tstatus = client.status()\n\tif(status['state'] != 'stop'):\n\t\tif(str(currentSong) != '{}'):\n\t\t\tif('file' in str(currentSong)):\n\t\t\t\tsource = currentSong['file']\n\t\t\t\tif 'http' in currentSong['file']: #Check for any webstreams before returning information\n\t\t\t\t\t#It's a radio-stream from the interwebs! Split the title at ' - ' or '-' into multiple lines, because it might contain the artist's name\n\t\t\t\t\tradioName = ' '\n\t\t\t\t\textraInfo = ' '\n\t\t\t\t\textraInfoFound = False\n\t\t\t\t\tif('name' in str(currentSong)):\n\t\t\t\t\t\tradioName = currentSong['name']\n\t\t\t\t\tif('title' in str(currentSong)):\n\t\t\t\t\t\ttitle = currentSong['title']\n\t\t\t\t\telse:\n\t\t\t\t\t\ttitle = ' '\n\t\t\t\t\tif ' - ' in title or ' : ' in title:\n\t\t\t\t\t\ttitleSplit = title.replace(' : ', ' - ').split(' - ')\n\t\t\t\t\t\ttitle = titleSplit[0]\n\t\t\t\t\t\tartist = titleSplit[1]\n\t\t\t\t\t\tif(len(titleSplit) >= 3):\n\t\t\t\t\t\t\textraInfo = titleSplit[2]\n\t\t\t\t\t\t\textraInfoFound = True\n\t\t\t\t\t\tif(artist[0:1] == ' '): # split() does it's job correctly, but I don't want a at the beginning of informations\n\t\t\t\t\t\t\tartist = artist[1::] # So info=info-first_char\n\t\t\t\t\t\tif(title[-1] == ' '):\n\t\t\t\t\t\t\ttitle = title[:-1]\n\t\t\t\t\t\tif(extraInfoFound == False):\n\t\t\t\t\t\t\treturnData = [title, artist, radioName, ' ']\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\treturnData = [title, artist, extraInfo, radioName]\n\t\t\t\t\telif '-' in title or ':' in title:\n\t\t\t\t\t\ttitleSplit = title.replace(':', '-').split('-')\n\t\t\t\t\t\ttitle = titleSplit[0]\n\t\t\t\t\t\tartist = titleSplit[1]\n\t\t\t\t\t\tif(len(titleSplit) >= 3):\n\t\t\t\t\t\t\textraInfo = titleSplit[2]\n\t\t\t\t\t\t\textraInfoFound = True\n\t\t\t\t\t\tif(artist[0:1] == ' '): # split() does it's job correctly, but I don't want a at the beginning of informations\n\t\t\t\t\t\t\tartist = artist[1::] # So info=info-first_char\n\t\t\t\t\t\tif(title[-1] == ' '):\n\t\t\t\t\t\t\ttitle = title[:-1]\n\t\t\t\t\t\tif(extraInfoFound == False):\n\t\t\t\t\t\t\treturnData = [title, artist, radioName, ' ']\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\treturnData = [title, artist, extraInfo, radioName]\n\t\t\t\t\telse:\n\t\t\t\t\t\treturnData = [title, radioName, ' ', ' ']\n\t\t\t\telse:\n\t\t\t\t\t# It's not playing a web-stream, but a music file\n\t\t\t\t\t# Try to extract as much info as possible from music files, either from reading the tags or from the filename\n\t\t\t\t\tartistFoundBySplittingFilename = False\n\t\t\t\t\textraInfo = ' '\n\t\t\t\t\textraInfoFound = False\n\t\t\t\t\talbumFound = False\n\t\t\t\t\tif 'title' in str(currentSong):\n\t\t\t\t\t\ttitle = currentSong['title']\n\t\t\t\t\telse:\n\t\t\t\t\t\ttitle = currentSong['file']\n\t\t\t\t\t\t#Do not include .mp3, .wma, .flac etc. in the song's name\n\t\t\t\t\t\tif(str(title[-4]) == '.'):\n\t\t\t\t\t\t\ttitle = title[0:-4]\n\t\t\t\t\t\telif(str(title[-5]) == '.'):\n\t\t\t\t\t\t\ttitle = title[0:-5]\n\t\t\t\t\t\twhile('USB/' in title):\n\t\t\t\t\t\t\ttitle = title[4::] # Remove all the 'USB/' from the filename's path\n\t\t\t\t\t\twhile('INTERNAL/' in title):\n\t\t\t\t\t\t\ttitle = title[9::] # Remove all the '/INTERNAL' from the filename's path\n\t\t\t\t\t\tif ' - ' in title or ' : ' in title:\n\t\t\t\t\t\t\ttitleSplit = title.replace(' : ', ' - ').split(' - ')\n\t\t\t\t\t\t\ttitle = titleSplit[0]\n\t\t\t\t\t\t\tartist = titleSplit[1]\n\t\t\t\t\t\t\t#Remove all spaces before and after the title artist text\n\t\t\t\t\t\t\tif(title[0] == ' '):\n\t\t\t\t\t\t\t\ttitle = title[1::]\n\t\t\t\t\t\t\telif(title[-1] == ' '):\n\t\t\t\t\t\t\t\ttitle = title[:-1]\n\t\t\t\t\t\t\tif(artist[0] == ' '):\n\t\t\t\t\t\t\t\tartist = artist[1::]\n\t\t\t\t\t\t\telif(artist[-1] == ' '):\n\t\t\t\t\t\t\t\tartist = artist[:-1]\n\t\t\t\t\t\t\t#We already found the artist, stop looking for tags, because the filename might contain more information\n\t\t\t\t\t\t\tif(artist != '' or artist != ' '):\n\t\t\t\t\t\t\t\tartistFoundBySplittingFilename = True\n\t\t\t\t\t\t\tif(artist[0:1] == ' '): # split() does it's job correctly, but I don't want a at the beginning of informations\n\t\t\t\t\t\t\t\tartist = artist[1::] # So info=info-first_char\n\t\t\t\t\t\t\tif(title[-1] == ' '):\n\t\t\t\t\t\t\t\ttitle = title[:-1]\n\t\t\t\t\t\t\t#Look for more info that might be useful to people, like the album-name\n\t\t\t\t\t\t\tif(len(titleSplit) >= 3):\n\t\t\t\t\t\t\t\textraInfo = titleSplit[2]\n\t\t\t\t\t\t\t\textraInfoFound = True\n\t\t\t\t\t# Check if the file contains an artist-name\n\t\t\t\t\tif 'albumartist' in str(currentSong) and artistFoundBySplittingFilename == False:\n\t\t\t\t\t\tartist = currentSong['albumartist']\n\t\t\t\t\telif(artistFoundBySplittingFilename == False):\n\t\t\t\t\t\tartist = ' '\n\t\t\t\t\t# Check if the file contains an album-name\n\t\t\t\t\tif 'album' in str(currentSong):\n\t\t\t\t\t\talbum = currentSong['album']\n\t\t\t\t\t\talbumFound = True\n\t\t\t\t\telse:\n\t\t\t\t\t\talbum = ' '\n\t\t\t\t\tm, s = divmod(float(status['elapsed']), 60)\n\t\t\t\t\th, m = divmod(m, 60)\n\t\t\t\t\telapsedTime = \"%d:%02d:%02d\" % (h, m, s)\n\t\t\t\t\tif(status['state'] == 'pause'):\n\t\t\t\t\t\telapsedTime = \" \" + str(elapsedTime) + \" ||\"\n\t\t\t\t\tif(albumFound == True and extraInfoFound == False):\n\t\t\t\t\t\treturnData = [title, artist, album, str(elapsedTime)]\n\t\t\t\t\telse:\n\t\t\t\t\t\treturnData = [title, artist, extraInfo, str(elapsedTime)]\n\t\t\telse:\n\t\t\t\treturnData = [' ', ' ', ' ', ' ']\n\t\telse:\n\t\t\t# There is no info to display, send voids\n\t\t\treturnData = [' ',' ',' ',' ']\n\telse:\n\t\t# Send voids to the display, as nothing is playing at the moment\n\t\treturnData = [' ', ' ', ' ', ' ']\n\treturn returnData\n\ntry:\n\t\n\trestartLineOne = time()-1\n\trestartLineTwo = time()-1\n\trestartLineThree = time()-1\n\trestartLineFour = time()-1\n\n\tposLineOne=0\n\tposLineTwo=0\n\tposLineThree=0\n\tposLineFour=0\n\n\ttextLineOne = textOne + text_split_string_setting + textOne[0:20]\n\ttextLineTwo = textTwo + text_split_string_setting + textTwo[0:20]\n\ttextLineThree = textThree + text_split_string_setting + textThree[0:20]\n\ttextLineFour = textFour + text_split_string_setting + textFour[0:20]\n\t\n\twriteLineOne = False\n\twriteLineTwo = False\n\twriteLineThree = False\n\twriteLineFour = False\n\n\tlineOneChanged = True\n\tlineTwoChanged = True\n\tlineThreeChanged = True\n\tlineFourChanged = True\n\t\t\n\tlastPrintedTextLineOne = 0\n\tlastPrintedTextLineTwo = 0\n\tlastPrintedTextLineThree = 0\n\tlastPrintedTextLineFour = 0\n\n\ttoPrintTextLineOne = 0\n\ttoPrintTextLineTwo = 0\n\ttoPrintTextLineThree = 0\n\ttoPrintTextLineFour = 0\n\n\twhile(True):\n\t\tif(time()-infoRefreshTimeStamp >= infoRefreshTimeWait):\n\t\t\t# It's time to update the information about the songs and such\n\t\t\tsongInfo = updateLCDinfo()\n\t\t\ttextOne = songInfo[0]\n\t\t\ttextTwo = songInfo[1]\n\t\t\ttextThree = songInfo[2]\n\t\t\ttextFour = songInfo[3]\n\n\t\t\tnewTextLineOne = textOne + text_split_string_setting + textOne[0:20]\n\t\t\tnewTextLineTwo = textTwo + text_split_string_setting + textTwo[0:20]\n\t\t\tnewTextLineThree = textThree + text_split_string_setting + textThree[0:20]\n\t\t\tnewTextLineFour = textFour + text_split_string_setting + textFour[0:20]\n\t\t\t#Now check for any changes\n\t\t\tif(textLineOne != newTextLineOne):\n\t\t\t\t# Update the text, because there is new text\n\t\t\t\ttextLineOne = newTextLineOne\n\t\t\t\t# Now reset some int's and bool's to make the text start scolling from the beginning\n\t\t\t\tposLineOne = 0\n\t\t\t\tlineOneChanged = True\n\t\t\t\twriteLineOne = True\n\t\t\t\tnewTextLineOne = True\n\t\t\tif(textLineTwo != newTextLineTwo):\n\t\t\t\t# Update the text, because there is new text\n\t\t\t\ttextLineTwo = newTextLineTwo\n\t\t\t\t# Now reset some int's and bool's to make the text start scolling from the beginning\n\t\t\t\tposLineTwo = 0\n\t\t\t\tlineTwoChanged = True\n\t\t\t\twriteLineTwo = True\n\t\t\t\tnewTextLineTwo = True\n\t\t\tif(textLineThree != newTextLineThree):\n\t\t\t\t# Update the text, because there is new text\n\t\t\t\ttextLineThree = newTextLineThree\n\t\t\t\t# Now reset some int's and bool's to make the text start scolling from the beginning\n\t\t\t\tposLineThree = 0\n\t\t\t\tlineThreeChanged = True\n\t\t\t\twriteLineThree = True\n\t\t\t\tnewTextLineThree = True\n\t\t\tif(textLineFour != newTextLineFour):\n\t\t\t\t# Update the text, because there is new text\n\t\t\t\ttextLineFour = newTextLineFour\n\t\t\t\t# Now reset some int's and bool's to make the text start scolling from the beginning\n\t\t\t\tposLineFour = 0\n\t\t\t\tlineFourChanged = True\n\t\t\t\twriteLineFour = True\n\t\t\t\tnewTextLineFour = True\n\t\t\t# Set a new time to check for changes in text\n\t\t\tinfoRefreshTimeStamp = time()\n\n\t\tif(time()-timeWaitTimeStamp >= timeWait):\n\t\t\t# Line one code starts here\n\t\t\tif(len(textOne) > 20):\n\t\t\t\tif(time()-restartLineOne > lineTimeWait):\n\t\t\t\t\twriteLineOne = True\n\t\t\t\t\ttoPrintTextLineOne = textLineOne[posLineOne:posLineOne+20]\n\t\t\t\t\tlastPrintedTextLineOne = textLineOne[posLineOne:posLineOne+20]\n\t\t\t\t\tposLineOne = posLineOne + moveText\n\t\t\t\t\tlineOneChanged = True\n\t\t\t\t\tif(posLineOne >= len(textLineOne)-18):\n\t\t\t\t\t\tposLineOne = 1\n\t\t\t\t\t\trestartLineOne = time()\n\t\t\t\t\t\tlineOneChanged = False\n\t\t\t\t\ttimeStampLineOne = time()\n\t\t\telse:\n\t\t\t\ttoPrintTextLineOne = textOne\n\t\t\t\twriteLineOne = True\n\t\t\t\n\t\t\t# Line two code starts here\n\t\t\tif(len(textTwo) > 20):\n\t\t\t\tif(time()-restartLineTwo > lineTimeWait):\n\t\t\t\t\twriteLineTwo = True\n\t\t\t\t\ttoPrintTextLineTwo = textLineTwo[posLineTwo:posLineTwo+20]\n\t\t\t\t\tlastPrintedTextLineTwo = textLineTwo[posLineTwo:posLineTwo+20]\n\t\t\t\t\tposLineTwo = posLineTwo + moveText\n\t\t\t\t\tlineTwoChanged = True\n\t\t\t\t\tif(posLineTwo >= len(textLineTwo)-18):\n\t\t\t\t\t\tposLineTwo = 1\n\t\t\t\t\t\trestartLineTwo = time()\n\t\t\t\t\t\tlineTwoChanged = False\n\t\t\t\t\ttimeStampLineTwo = time()\n\t\t\telse:\n\t\t\t\ttoPrintTextLineTwo = textTwo\n\t\t\t\twriteLineTwo = True\n\t\t\t\t\n\t\t\t# Line three code starts here\n\t\t\tif(len(textThree) > 20):\n\t\t\t\tif(time()-restartLineThree > lineTimeWait):\n\t\t\t\t\twriteLineThree = True\n\t\t\t\t\ttoPrintTextLineThree = textLineThree[posLineThree:posLineThree+20]\n\t\t\t\t\tlastPrintedTextLineThree = textLineThree[posLineThree:posLineThree+20]\n\t\t\t\t\tposLineThree = posLineThree + moveText\n\t\t\t\t\tlineThreeChanged = True\n\t\t\t\t\tif(posLineThree >= len(textLineThree)-18):\n\t\t\t\t\t\tposLineThree = 1\n\t\t\t\t\t\trestartLineThree = time()\n\t\t\t\t\t\tlineThreeChanged = False\n\t\t\t\t\ttimeStampLineThree = time()\n\t\t\telse:\n\t\t\t\ttoPrintTextLineThree = textThree\n\t\t\t\twriteLineThree = True\n\t\t\t\t\n\t\t\t# Line four code starts here\n\t\t\tif(len(textFour) > 20):\n\t\t\t\tif(time()-restartLineFour > lineTimeWait):\n\t\t\t\t\twriteLineFour = True\n\t\t\t\t\ttoPrintTextLineFour = textLineFour[posLineFour:posLineFour+20]\n\t\t\t\t\tlastPrintedTextLineFour = textLineFour[posLineFour:posLineFour+20]\n\t\t\t\t\tposLineFour = posLineFour + moveText\n\t\t\t\t\tlineFourChanged = True\n\t\t\t\t\tif(posLineFour >= len(textLineFour)-18):\n\t\t\t\t\t\tposLineFour = 1\n\t\t\t\t\t\trestartLineFour = time()\n\t\t\t\t\t\tlineFourChanged = False\n\t\t\t\t\ttimeStampLineFour = time()\n\t\t\telse:\n\t\t\t\ttoPrintTextLineFour = textFour\n\t\t\t\twriteLineFour = True\n\t\t\t\n\t\t\t# Check what stuff to send to the LCD and what to leave out because it's already being displayed\n\t\t\tif(lineOneChanged == True and writeLineOne == True):\n\t\t\t\tsendToLCD(0, toPrintTextLineOne)\n\t\t\t\twriteLineOne = False\n\t\t\t\tlineOneChanged = False\n\t\t\tif(lineTwoChanged == True and writeLineTwo == True):\n\t\t\t\tsendToLCD(1, toPrintTextLineTwo)\n\t\t\t\twriteLineTwo = False\n\t\t\t\tlineTwoChanged = False\n\t\t\tif(lineThreeChanged == True and writeLineThree == True):\n\t\t\t\tsendToLCD(2, toPrintTextLineThree)\n\t\t\t\twriteLineThree = False\n\t\t\t\tlineThreeChanged = False\n\t\t\tif(lineFourChanged == True and writeLineFour == True):\n\t\t\t\tsendToLCD(3, toPrintTextLineFour)\n\t\t\t\twriteLineFour = False\n\t\t\t\tlineFourChanged = False\n\t\t\ttimeWaitTimeStamp = time()\nexcept KeyboardInterrupt:\n\tprint(\"\\nExiting...\")\n","sub_path":"plugin/LCDcontroller/scrollText.py","file_name":"scrollText.py","file_ext":"py","file_size_in_byte":16309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"340557851","text":"import flask\r\nimport pickle\r\nimport pandas as pd\r\n\r\n# Use pickle to load in the pre-trained model.\r\nwith open(f'model/7july_lr_model.pickle', 'rb') as f:\r\n model = pickle.load(f)\r\n \r\napp = flask.Flask(__name__, template_folder='templates')\r\n@app.route('/', methods=['GET','POST'])\r\ndef main():\r\n if flask.request.method == 'GET':\r\n return(flask.render_template('main.html'))\r\n if flask.request.method == 'POST':\r\n itetypeinter= flask.request.form['itetypeinter']\r\n year = flask.request.form['year']\r\n month = flask.request.form['month']\r\n day = flask.request.form['day']\r\n hour = flask.request.form['hour']\r\n minute = flask.request.form['minute']\r\n protypeair = flask.request.form['protypeair']\r\n protypehot = flask.request.form['protypehot']\r\n protypeothpro = flask.request.form['protypeothpro']\r\n protypeaircanc = flask.request.form['protypeaircanc']\r\n protypehotcanc = flask.request.form['protypehotcanc']\r\n protypeairloss = flask.request.form['protypeairloss']\r\n protypehotloss = flask.request.form['protypehotloss']\r\n \r\n input_variables = pd.DataFrame([[itetypeinter,year,month,day,hour,minute,protypeair,protypehot,protypeothpro,protypeaircanc,protypehotcanc,protypeairloss,protypehotloss]],columns=['itetypeinter','year','month','day','hour','minute','protypeair','protypehot','protypeothpro','protypeaircanc','protypehotcanc','protypeairloss','protypehotloss'],dtype=float,index=['input'])\r\n prediction = model.predict(input_variables)[0]\r\n #model = pd.read_pickle(r\"C:\\Users\\KunalAnvit\\Desktop\\Data Science Project\\Final Model_Umesha\\webapp\\model\\7july_lr_model.pickle\")\r\n #NetFarePredicted=model.predict([[year,month,day,hour,minute,protypeair,protypeaircanc,protypeairdebtnote,protypeairloss,protypehot,protypehotcanc,protypehotdebnote,protypehotloss,protypeothpro,protypeothprocanc ,protypeothprodebnote,itetypeinter]])\r\n #NetFarePredicted=NetFarePredicted[0]\r\n #print(f'NetFarePredicted:{NetFarePredicted:.2f}')\r\n return flask.render_template('main.html',original_input={'Itenerary_Type':itetypeinter,'Year':year,'Month':month,'Day':day,'Hour': hour,'Minute':minute,'ProTypeAir':protypeair,'Product_Type_Hotel':protypehot,'Product_Type_Other_Product':protypeothpro,'Product_Type_Air_Cancellation':protypeaircanc,'Product_Type_Hotel_Cancellation':protypehotcanc,'Product_Type_Air_Loss':protypeairloss,'Product_Type_Hotel_Loss':protypehotloss},result=prediction,)\r\n \r\nif __name__ == '__main__':\r\n app.run()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"152822863","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.3-i386/egg/qi/xmpp/botfarm/logutil.py\n# Compiled at: 2008-08-01 13:19:50\nfrom twisted.python import log\nfrom twisted.words.protocols.jabber import component\nimport sys, time, qi.xmpp.botfarm.config as config\n\nclass INFO:\n __module__ = __name__\n\n\nclass WARN:\n __module__ = __name__\n\n\nclass ERROR:\n __module__ = __name__\n\n\nlog.discardLogs()\n\nclass LogEvent:\n __module__ = __name__\n\n def __init__(self, category=INFO, ident='', msg='', log=True):\n self.category, self.ident, self.msg = category, ident, msg\n frame = sys._getframe(1)\n s = str(frame.f_locals.get('self', frame.f_code.co_filename))\n self.klass = s[s.find('.') + 1:s.find(' ')]\n self.method = frame.f_code.co_name\n self.args = frame.f_locals\n if log:\n if category == INFO and config.debugLevel < 3:\n return\n if category == WARN and config.debugLevel < 2:\n return\n if category == ERROR and config.debugLevel < 1:\n return\n self.log()\n\n def __str__(self):\n args = {}\n for key in self.args.keys():\n if key == 'self':\n args['self'] = 'instance'\n continue\n val = self.args[key]\n args[key] = val\n try:\n if len(val) > 128:\n args[key] = 'Oversize arg'\n except:\n pass\n\n category = str(self.category).split('.')[1]\n return '%s :: %s :: %s\\n' % (category, str(self.ident), self.msg)\n\n def log(self):\n log.msg(self)","sub_path":"pycfiles/qi.xmpp.botfarm-0.1-py2.4/logutil.py","file_name":"logutil.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"609800235","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright (C) 2012 Yahoo! Inc. 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 copy\nimport pkg_resources\n\nfrom pip import util as pip_util\nfrom pip import req as pip_req\n\nfrom anvil import log as logging\nfrom anvil import shell as sh\nfrom anvil import utils\n\nLOG = logging.getLogger(__name__)\n\nFREEZE_CMD = ['freeze', '--local']\nEGGS_DETAILED = {}\n\n\ndef create_requirement(name, version=None):\n name = pkg_resources.safe_name(name.strip())\n if not name:\n raise ValueError(\"Pip requirement provided with an empty name\")\n if version is not None:\n if isinstance(version, (int, float, long)):\n version = \"==%s\" % version\n if isinstance(version, (str, basestring)):\n if version[0] not in \"=<>\":\n version = \"==%s\" % version\n else:\n raise TypeError(\n \"Pip requirement version must be a string or numeric type\")\n name = \"%s%s\" % (name, version)\n return pkg_resources.Requirement.parse(name)\n\n\ndef extract(line):\n return pip_req.InstallRequirement.from_line(line)\n\n\ndef extract_requirement(line):\n req = extract(line)\n return req.req\n\n\ndef get_directory_details(path):\n if not sh.isdir(path):\n raise IOError(\"Can not detail non-existent directory %s\" % (path))\n\n # Check if we already got the details of this dir previously\n path = sh.abspth(path)\n cache_key = \"d:%s\" % (sh.abspth(path))\n if cache_key in EGGS_DETAILED:\n return EGGS_DETAILED[cache_key]\n\n req = extract(path)\n req.source_dir = path\n req.run_egg_info()\n\n dependencies = []\n for d in req.requirements():\n if not d.startswith(\"-e\") and d.find(\"#\"):\n d = d.split(\"#\")[0]\n d = d.strip()\n if d:\n dependencies.append(d)\n\n details = {\n 'req': req.req,\n 'dependencies': dependencies,\n 'name': req.name,\n 'pkg_info': req.pkg_info(),\n 'dependency_links': req.dependency_links,\n 'version': req.installed_version,\n }\n\n EGGS_DETAILED[cache_key] = details\n return details\n\n\ndef get_archive_details(filename):\n if not sh.isfile(filename):\n raise IOError(\"Can not detail non-existent file %s\" % (filename))\n\n # Check if we already got the details of this file previously\n cache_key = \"f:%s:%s\" % (sh.basename(filename), sh.getsize(filename))\n if cache_key in EGGS_DETAILED:\n return EGGS_DETAILED[cache_key]\n\n # Get pip to get us the egg-info.\n with utils.tempdir() as td:\n filename = sh.copy(filename, sh.joinpths(td, sh.basename(filename)))\n extract_to = sh.mkdir(sh.joinpths(td, 'build'))\n pip_util.unpack_file(filename, extract_to, content_type='', link='')\n details = get_directory_details(extract_to)\n\n EGGS_DETAILED[cache_key] = details\n return details\n\n\ndef _skip_requirement(line):\n # Skip blank lines or comment lines\n if not len(line):\n return True\n if line.startswith(\"#\"):\n return True\n # Skip editables also...\n if line.lower().startswith('-e'):\n return True\n # Skip http types also...\n if line.lower().startswith('http://'):\n return True\n return False\n\n\ndef parse_requirements(contents, adjust=False):\n lines = []\n for line in contents.splitlines():\n line = line.strip()\n if not _skip_requirement(line):\n lines.append(line)\n requires = []\n for req in pkg_resources.parse_requirements(lines):\n requires.append(req)\n return requires\n\n\nclass Helper(object):\n # Cache of whats installed\n _installed_cache = {}\n\n def __init__(self, call_how):\n if not isinstance(call_how, (basestring, str)):\n # Assume u are passing in a distro object\n self._pip_how = str(call_how.get_command_config('pip'))\n else:\n self._pip_how = call_how\n\n def _list_installed(self):\n cmd = [self._pip_how] + FREEZE_CMD\n (stdout, _stderr) = sh.execute(cmd)\n return parse_requirements(stdout, True)\n\n def uncache(self):\n Helper._installed_cache.pop(self._pip_how, None)\n\n def whats_installed(self):\n if not (self._pip_how in Helper._installed_cache):\n Helper._installed_cache[self._pip_how] = self._list_installed()\n return copy.copy(Helper._installed_cache[self._pip_how])\n\n def is_installed(self, name):\n if self.get_installed(name):\n return True\n return False\n\n def get_installed(self, name):\n whats_there = self.whats_installed()\n wanted_package = create_requirement(name)\n for whats_installed in whats_there:\n if not (wanted_package.key == whats_installed.key):\n continue\n return whats_installed\n return None\n","sub_path":"anvil/packaging/helpers/pip_helper.py","file_name":"pip_helper.py","file_ext":"py","file_size_in_byte":5376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"159461751","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 18 15:05:43 2021\n\n@author: amurtha\n\"\"\"\n\nimport pandas as pd\nimport scipy.stats as stats\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\n\n# =============================================================================\n# TC by num bone mets\n# =============================================================================\n\ntc = pd.read_excel('C:/Users/amurtha/Dropbox/Ghent M1 2019/Mar2021_datafreeze/clinical/cfDNA timepoints.xlsx')\nclin = pd.read_excel('C:/Users/amurtha/Dropbox/Ghent M1 2019/Mar2021_datafreeze/clinical/ClinicalDataWithLatitude.xlsx')\n\ntc = tc[tc['Sample ID'] != 'M1RP_ID8_cfDNA_2017Jan30']\n\n# =============================================================================\n# Get patient order\n# =============================================================================\n\nclin['adt_to_crpc'] = (clin['crpc_date'] - clin['mHSPC_adt_start']) / np.timedelta64(1, 'M')\n\n# =============================================================================\n# Sort tc \n# =============================================================================\n\ntc = tc.merge(clin[['patient_id','adt_to_crpc','crpc_status']], left_on = 'Patient ID', right_on = 'patient_id')\n\ntc = tc[tc['Status'].isin(['Tx naive','Post NA ADT'])]\n\ntc = tc.sort_values('Date collected', ascending = True).drop_duplicates('Patient ID')\n\n# =============================================================================\n# \n# =============================================================================\n\ntc = tc.sort_values(['crpc_status','adt_to_crpc'], ascending = False)\ntc['color'] = 'red'\ntc.loc[tc['Final tNGS_TC'] == 0, 'color'] = 'grey'\n\ntc['y'] = np.arange(len(tc))\n\n# =============================================================================\n# Fig, ax = \n# =============================================================================\n\nfig,[ax0,ax] = plt.subplots(ncols = 2, figsize = (5.5,3.5), gridspec_kw={'width_ratios':[0.1,1]}, sharey = True)\n\nfor index, row in tc.iterrows():\n crpc_time = row['adt_to_crpc']\n y = row['y']\n ax.plot([0,crpc_time],[y+0.4,y+0.4], color = row['color'], lw = 1.5, marker = None, solid_capstyle = 'butt')\n \ncspc = tc[tc['crpc_status'] == 0].copy()\ncrpc = tc[tc['crpc_status'] == 1].copy()\n\nax.scatter(cspc['adt_to_crpc'],cspc['y']+0.4, c = cspc['color'], marker = '>', lw = 0)\nax.scatter(crpc['adt_to_crpc'],crpc['y']+0.4, c = crpc['color'], marker = '|', lw = 0.8)\n\nax.set_yticks(np.arange(0.4,len(tc),1))\nax.set_yticklabels(tc['Patient ID'])\nax.set_ylim(-0.1,23.45)\n\nax.set_xlim(-1,65)\nax.set_xticks(np.arange(0,63,12))\n\norder = dict(zip(tc['Patient ID'],tc['y']))\n\nax.set_xlabel('Time from ADT to CRPC', fontsize = 6)\n\nhandles = [Line2D([],[],lw = 1.5, color = 'red', marker = None),\n Line2D([],[],lw = 1.5, color = 'grey', marker = None),\n Line2D([],[],lw = 0.0, color = 'grey', marker = '|'),\n Line2D([],[],lw = 0.0, color = 'grey', marker = '>')]\n\nlabels = ['Baseline ctDNA+','Baseline ctDNA-', 'CRPC progression','Last follow up']\n\nax.legend(handles, labels, fontsize = 6)\n\n# =============================================================================\n# Set up treatment regimine heatmap\n# =============================================================================\n\nclin['hspc_arpi'] = 0\nfor index, row in clin.iterrows():\n if row['crpc_status'] == 1 and row['mCRPC_L1_arpi_administered'] == 1:\n if row['mCRPC_L1_arpi_start'] < row['crpc_date']:\n clin.at[index, 'hspc_arpi'] = 1\n elif row['mCRPC_L1_arpi_administered'] == 1:\n clin.at[index, 'hspc_arpi'] = 1\n\nti = clin.copy()[['patient_id','neoadj_tx','hspc_arpi','mHSPC_chemo_administered']]\nti['neoadj_tx'] = ti['neoadj_tx'].map({0:'grey',1:'black'})\nti['hspc_arpi'] = ti['hspc_arpi'].map({0:'grey',1:'black'})\nti['mHSPC_chemo_administered'] = ti['mHSPC_chemo_administered'].map({0:'grey',1:'black'})\n\nti = ti.merge(tc[['Patient ID','y']], left_on = 'patient_id', right_on = 'Patient ID')\n\nax0.bar([0]*len(ti),0.8, bottom = ti['y'], color = ti['neoadj_tx'])\nax0.bar([1]*len(ti),0.8, bottom = ti['y'], color = ti['mHSPC_chemo_administered'])\nax0.bar([2]*len(ti),0.8, bottom = ti['y'], color = ti['hspc_arpi'])\n\n# ti = pd.DataFrame(columns = ['Neo-adjuvant ADT','mCSPC ARPI','mCSPC chemo.'], index = tc['Patient ID'])\n\nax0.set_xticks([0,1,2])\nax0.set_xticklabels(['Neo-adj.','mHSPC chemo.','mHSPC ARPI'], fontsize = 8, rotation = 90)\nax0.tick_params(labelsize = 6)\nax.tick_params(labelsize = 6)\n\n\n\n\n# =============================================================================\n# Save fig\n# =============================================================================\n\nfig.tight_layout()\n\nfig.savefig('C:/Users/amurtha/Dropbox/Ghent M1 2019/Figures/Work from 2021/ctDNA fraction/waterfallByCtDNAStatus.pdf')","sub_path":"prod/summary/cfDNAfraction_waterfall.py","file_name":"cfDNAfraction_waterfall.py","file_ext":"py","file_size_in_byte":4851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"325077237","text":"'''Train or test deep learning model'''\nimport logging\nfrom tqdm import tqdm\n\nimport numpy as np\nfrom pathlib import Path\nimport argparse\nimport pickle\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom utils.data import DiffusionDataset, normalize, denormalize\nfrom utils.log import log_evaluation\nfrom models.convdmm import DMM, reverse_sequences, do_prediction, do_prediction_rep_inference\n\nfrom pyro.optim import ClippedAdam\nfrom pyro.infer import SVI, Trace_ELBO, TraceMeanField_ELBO\n\n\ndef main(args):\n # Init tensorboard\n writer = SummaryWriter('./runs/' + args.runname + str(args.trialnumber))\n\n # Set evaluation log file\n evaluation_logpath = './logs/convdmm/evaluation_result_eventdim.log'\n log_evaluation(evaluation_logpath,\n 'Evaluation Trial - {}\\n'.format(args.trialnumber))\n\n # Constants\n # For more variance long, 500, input 20\n time_length = 30\n input_length_for_pred = 20\n pred_length = time_length - input_length_for_pred\n validation_pred_lengths = [5, 10, 15, 20]\n train_batch_size = 16\n valid_batch_size = 1\n min_val, max_val = 0, 1000\n\n # For model\n input_channels = 1\n z_channels = 64\n emission_channels = 32\n transition_channels = 64\n rnn_channels = [64]\n kernel_size = 3\n pred_length = 0\n\n # Device checking\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda:0\" if use_cuda else \"cpu\")\n\n # Make dataset\n logging.info(\"Generate data\")\n train_datapath = args.datapath / 'train'\n valid_datapath = args.datapath / 'valid'\n train_dataset = DiffusionDataset(train_datapath)\n valid_dataset = DiffusionDataset(valid_datapath)\n\n # Create data loaders from pickle data\n logging.info(\"Generate data loaders\")\n train_dataloader = DataLoader(\n train_dataset, batch_size=train_batch_size, shuffle=True, num_workers=8)\n valid_dataloader = DataLoader(\n valid_dataset, batch_size=valid_batch_size, num_workers=4)\n\n # Training parameters\n width = 100\n height = 100\n input_dim = width * height\n\n # Create model\n logging.warning(\"Generate model\")\n logging.warning(input_dim)\n pred_input_dim = 10\n dmm = DMM(input_channels=input_channels, z_channels=z_channels, emission_channels=emission_channels,\n transition_channels=transition_channels, rnn_channels=rnn_channels, kernel_size=kernel_size, height=height, width=width, pred_input_dim=pred_input_dim, num_layers=1, rnn_dropout_rate=0.0,\n num_iafs=0, iaf_dim=50, use_cuda=use_cuda)\n\n # Initialize model\n logging.info(\"Initialize model\")\n epochs = args.endepoch\n learning_rate = 0.000025\n beta1 = 0.9\n beta2 = 0.999\n clip_norm = 10.0\n lr_decay = 1.0\n weight_decay = 0\n adam_params = {\"lr\": learning_rate, \"betas\": (beta1, beta2),\n \"clip_norm\": clip_norm, \"lrd\": lr_decay,\n \"weight_decay\": weight_decay}\n adam = ClippedAdam(adam_params)\n elbo = Trace_ELBO()\n svi = SVI(dmm.model, dmm.guide, adam, loss=elbo)\n\n # saves the model and optimizer states to disk\n save_model = Path('./checkpoints/ConvDMM')\n\n def save_checkpoint(epoch):\n save_dir = save_model / '{}.model'.format(epoch)\n save_opt_dir = save_model / '{}.opt'.format(epoch)\n logging.info(\"saving model to %s...\" % save_dir)\n torch.save(dmm.state_dict(), save_dir)\n logging.info(\"saving optimizer states to %s...\" % save_opt_dir)\n adam.save(save_opt_dir)\n logging.info(\"done saving model and optimizer checkpoints to disk.\")\n\n # Starting epoch\n start_epoch = args.startepoch\n\n # loads the model and optimizer states from disk\n if start_epoch != 0:\n load_opt = './checkpoints/ConvDMM/e{}-i188-opt-tn{}.opt'.format(\n start_epoch - 1, args.trialnumber)\n load_model = './checkpoints/ConvDMM/e{}-i188-tn{}.pt'.format(\n start_epoch - 1, args.trialnumber)\n\n def load_checkpoint():\n # assert exists(load_opt) and exists(load_model), \\\n # \"--load-model and/or --load-opt misspecified\"\n logging.info(\"loading model from %s...\" % load_model)\n dmm.load_state_dict(torch.load(load_model, map_location=device))\n # logging.info(\"loading optimizer states from %s...\" % load_opt)\n # adam.load(load_opt)\n # logging.info(\"done loading model and optimizer states.\")\n\n if load_model != '':\n logging.info('Load checkpoint')\n load_checkpoint()\n\n # Validation only?\n validation_only = args.validonly\n\n # Train the model\n if not validation_only:\n logging.info(\"Training model\")\n # annealing epochs default 1000\n annealing_epochs = 1000\n minimum_annealing_factor = 0.2\n N_train_size = 3000\n N_mini_batches = int(N_train_size / train_batch_size +\n int(N_train_size % train_batch_size > 0))\n for epoch in tqdm(range(start_epoch, epochs), desc='Epoch', leave=True):\n r_loss_train = 0\n dmm.train(True)\n idx = 0\n mov_avg_loss = 0\n mov_data_len = 0\n for which_mini_batch, data in enumerate(tqdm(train_dataloader, desc='Train', leave=True)):\n if annealing_epochs > 0 and epoch < annealing_epochs:\n # compute the KL annealing factor approriate for the current mini-batch in the current epoch\n min_af = minimum_annealing_factor\n annealing_factor = min_af + (1.0 - min_af) * \\\n (float(which_mini_batch + epoch * N_mini_batches + 1) /\n float(annealing_epochs * N_mini_batches))\n else:\n # by default the KL annealing factor is unity\n annealing_factor = 1.0\n\n data['observation'] = normalize(\n data['observation'].unsqueeze(2).to(device), min_val, max_val)\n batch_size, length, _, w, h = data['observation'].shape\n data_reversed = reverse_sequences(data['observation'])\n data_mask = torch.ones(\n batch_size, length, input_channels, w, h).cuda()\n\n loss = svi.step(data['observation'],\n data_reversed, data_mask, annealing_factor)\n\n # Running losses\n mov_avg_loss += loss\n mov_data_len += batch_size\n\n if idx % 3 == 2:\n with open('./logs/convdmm/training.log', 'a+') as fout:\n temp_avg = mov_avg_loss / (mov_data_len * length)\n training_log = 'Epoch {}: Iter {}: {}\\n'.format(\n epoch, idx, temp_avg)\n fout.write(training_log)\n mov_avg_loss = 0\n mov_data_len = 0\n\n r_loss_train += loss\n idx += 1\n\n # Average losses\n train_loss_avg = r_loss_train / (len(train_dataset) * time_length)\n writer.add_scalar('Loss/train', train_loss_avg, epoch)\n logging.info(\"Epoch: %d, Training loss: %1.5f\",\n epoch, train_loss_avg)\n\n # # Time to time evaluation\n if epoch == epochs - 1:\n for temp_pred_length in validation_pred_lengths:\n r_loss_valid = 0\n r_loss_loc_valid = 0\n r_loss_scale_valid = 0\n r_loss_latent_valid = 0\n dmm.train(False)\n dmm.convlstm.eval()\n val_pred_length = temp_pred_length\n val_pred_input_length = 10\n with torch.no_grad():\n for data in tqdm(valid_dataloader, desc='Valid', leave=True):\n data['observation'] = normalize(\n data['observation'].unsqueeze(2).to(device), min_val, max_val)\n batch_size, length, _, w, h = data['observation'].shape\n data_reversed = reverse_sequences(\n data['observation'])\n data_mask = torch.ones(\n batch_size, length, input_channels, w, h).to(device)\n\n pred_tensor = data['observation'][:,\n :input_length_for_pred, :, :, :]\n pred_tensor_reversed = reverse_sequences(\n pred_tensor)\n pred_tensor_mask = torch.ones(\n batch_size, input_length_for_pred, input_channels, w, h).cuda()\n\n ground_truth = data['observation'][:,\n input_length_for_pred:, :, :, :]\n\n val_nll = svi.evaluate_loss(\n data['observation'], data_reversed, data_mask)\n preds, _, loss_loc, loss_scale = do_prediction_rep_inference(\n dmm, pred_tensor_mask, val_pred_length, val_pred_input_length, data['observation'])\n\n ground_truth = denormalize(\n data['observation'].squeeze(\n ).cpu().detach(), min_val, max_val\n )\n pred_with_input = denormalize(\n torch.cat(\n [data['observation'][:, :-val_pred_length, :, :, :].squeeze(),\n preds.squeeze()], dim=0\n ).cpu().detach(), min_val, max_val\n )\n\n # Running losses\n r_loss_valid += val_nll\n r_loss_loc_valid += loss_loc\n r_loss_scale_valid += loss_scale\n\n # Average losses\n valid_loss_avg = r_loss_valid / \\\n (len(valid_dataset) * time_length)\n valid_loss_loc_avg = r_loss_loc_valid / \\\n (len(valid_dataset) * val_pred_length * width * height)\n valid_loss_scale_avg = r_loss_scale_valid / \\\n (len(valid_dataset) * val_pred_length * width * height)\n writer.add_scalar('Loss/test', valid_loss_avg, epoch)\n writer.add_scalar(\n 'Loss/test_obs', valid_loss_loc_avg, epoch)\n writer.add_scalar('Loss/test_scale',\n valid_loss_scale_avg, epoch)\n logging.info(\"Validation loss: %1.5f\", valid_loss_avg)\n logging.info(\"Validation obs loss for %ds pred ConvDMM: %f\",\n val_pred_length, valid_loss_loc_avg)\n logging.info(\"Validation scale loss: %1.5f\",\n valid_loss_scale_avg)\n log_evaluation(evaluation_logpath, \"Validation obs loss for {}s pred {}: {}\\n\".format(\n val_pred_length, args.trialnumber, valid_loss_loc_avg))\n log_evaluation(evaluation_logpath, \"Validation scale loss for {}s pred {}: {}\\n\".format(\n val_pred_length, args.trialnumber, valid_loss_scale_avg))\n with open('./logs/convdmm/training.log', 'a+') as fout:\n training_log = 'Epoch {}: Iter {}: {}\\n'.format(\n epoch, idx, temp_avg)\n\n dmm.convlstm.train()\n\n # Save model\n if epoch % 50 == 0 or epoch == epochs - 1:\n torch.save(dmm.state_dict(), args.modelsavepath / 'ConvDMM' /\n 'e{}-i{}-tn{}.pt'.format(epoch, idx, args.trialnumber))\n adam.save(args.modelsavepath / 'ConvDMM' /\n 'e{}-i{}-tn{}-opt.opt'.format(epoch, idx, args.trialnumber))\n\n # Last validation after training\n test_samples_indices = range(len(valid_dataset))\n total_n = len(valid_dataset)\n if validation_only:\n r_loss_loc_valid = 0\n r_loss_scale_valid = 0\n r_loss_latent_valid = 0\n dmm.train(False)\n dmm.convlstm.eval()\n val_pred_length = args.validpredlength\n val_pred_input_length = 10\n with torch.no_grad():\n for i in tqdm(test_samples_indices, desc='Valid', leave=True):\n # Data processing\n data = valid_dataset[i]\n # if torch.isnan(torch.sum(data['observation'])):\n # print(\"Skip {}\".format(i))\n # continue\n # else:\n # total_n += 1\n data['observation'] = normalize(\n data['observation'].unsqueeze(0).unsqueeze(2).to(device), min_val, max_val)\n batch_size, length, _, w, h = data['observation'].shape\n data_reversed = reverse_sequences(data['observation'])\n data_mask = torch.ones(\n batch_size, length, input_channels, w, h).to(device)\n\n # Prediction\n pred_tensor_mask = torch.ones(\n batch_size, input_length_for_pred, input_channels, w, h).to(device)\n\n preds, _, loss_loc, loss_scale = do_prediction_rep_inference(\n dmm, pred_tensor_mask, val_pred_length, val_pred_input_length, data['observation'])\n\n ground_truth = denormalize(\n data['observation'].squeeze(\n ).cpu().detach(), min_val, max_val\n )\n pred_with_input = denormalize(\n torch.cat(\n [data['observation'][:, :-val_pred_length, :, :, :].squeeze(),\n preds.squeeze()], dim=0\n ).cpu().detach(), min_val, max_val\n )\n\n # Save samples\n if i < 5:\n save_dir_samples = Path('./samples/more_variance_long')\n with open(save_dir_samples / '{}-gt-test.pkl'.format(i), 'wb') as fout:\n pickle.dump(ground_truth, fout)\n with open(save_dir_samples / '{}-dmm-pred-test.pkl'.format(i), 'wb') as fout:\n pickle.dump(pred_with_input, fout)\n\n # Running losses\n r_loss_loc_valid += loss_loc\n r_loss_scale_valid += loss_scale\n r_loss_latent_valid += np.sum((preds.squeeze().detach().cpu().numpy(\n ) - data['latent'][time_length - val_pred_length:, :, :].detach().cpu().numpy()) ** 2)\n\n # Average losses\n valid_loss_loc_avg = r_loss_loc_valid / \\\n (total_n * val_pred_length * width * height)\n valid_loss_scale_avg = r_loss_scale_valid / \\\n (total_n * val_pred_length * width * height)\n valid_loss_latent_avg = r_loss_latent_valid / \\\n (total_n * val_pred_length * width * height)\n logging.info(\"Validation obs loss for %ds pred ConvDMM: %f\",\n val_pred_length, valid_loss_loc_avg)\n logging.info(\"Validation latent loss: %f\", valid_loss_latent_avg)\n\n with open('ConvDMMDiffResult.log', 'a+') as fout:\n validation_log = 'Pred {}s ConvDMM: {}\\n'.format(\n val_pred_length, valid_loss_loc_avg)\n fout.write(validation_log)\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.DEBUG)\n print(logging.getLogger().getEffectiveLevel())\n\n parser = argparse.ArgumentParser(description=\"Train a dnn model\")\n parser.add_argument('--datapath', '-dp',\n default='./data/diffusion', type=str, help=\"Data path\")\n parser.add_argument('--modelsavepath', '-msp',\n default='./checkpoints', type=str, help=\"Model path\")\n parser.add_argument('--validpredlength', '-vpl', default=5,\n type=int, help=\"Validation prediction length\")\n parser.add_argument('--validonly', '-vo', default=False, type=bool,\n help=\"Go to training mode if false, validation mode if true\")\n parser.add_argument('--trialnumber', '-tn', default=0, type=int,\n help=\"Set training trial number\")\n parser.add_argument('--startepoch', '-se', default=0,\n type=int, help=\"Set starting epoch\")\n parser.add_argument('--endepoch', '-ee', default=299,\n type=int, help=\"Set ending epoch\")\n parser.add_argument('--runname', '-rn', default=\"ConvDMM-Heat\",\n type=str, help=\"Set training record name\")\n\n args = parser.parse_args()\n\n args.datapath = Path(args.datapath)\n args.modelsavepath = Path(args.modelsavepath)\n\n main(args)\n","sub_path":"train_cnmm_heatmap.py","file_name":"train_cnmm_heatmap.py","file_ext":"py","file_size_in_byte":17091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"650572670","text":"import matplotlib.pyplot as plt\nimport stream as sg\n\n\nclass Node:\n def __init__(self, t_mid=None, elements=None, intervals=None):\n self.t_mid = t_mid\n self.intervals = intervals\n self.elements = elements\n self.left = None\n self.right = None\n if intervals:\n t = [i for sublist in intervals for i in sublist]\n self.min = min(t)\n self.max = max(t)\n else:\n self.min = None\n self.max = None\n\n def search_(self, t, results=0):\n if results == 0:\n results = {'elements': [], 'intervals': []}\n if self.max >= t >= self.min:\n for i, j in zip(self.intervals, self.elements):\n for t0, t1 in zip(i[::2], i[1::2]):\n if t0 <= t <= t1:\n results['intervals'].append([t0, t1])\n results['elements'].append(j)\n if t >= self.t_mid:\n if self.right:\n return self.right.search_(t, results)\n else:\n return results\n elif t <= self.t_mid:\n if self.left:\n return self.left.search_(t, results)\n else:\n return results\n # elif t == self.t_mid:\n # return self.intervals\n\n\n def get_global_min(self, global_min=None):\n if not global_min:\n global_min = self.min\n else:\n global_min = min(global_min, self.min)\n if self.right and self.left:\n return min(self.right.get_global_min(global_min), self.left.get_global_min(global_min))\n elif self.left:\n return self.left.get_global_min(global_min)\n elif self.right:\n return self.right.get_global_min(global_min)\n return global_min\n\n\n def get_global_max(self, global_max=None):\n if not global_max:\n global_max = self.max\n else:\n global_max = max(global_max, self.max)\n if self.right and self.left:\n return max(self.right.get_global_max(global_max), self.left.get_global_max(global_max))\n elif self.right:\n return self.right.get_global_max(global_max)\n elif self.left:\n return self.left.get_global_max(global_max)\n return global_max\n\n\n def search_interval_(self, I, results=0):\n if results == 0:\n results = {'elements': [], 'intervals': []}\n # Case One : easy case, t_mid is in I so we add the whole node\n # to our results\n if I[1] >= self.t_mid >= I[0]:\n for interval,element in zip(self.intervals,self.elements):\n for t0,t1 in zip(interval[::2],interval[1::2]):\n intersec_b = max(t0,I[0])\n intersec_e = min(t1,I[1])\n results['intervals'].append([intersec_b,intersec_e])\n results[\"elements\"].append(element)\n # results['intervals']\n # Case Two : there is at least one intersection between the node's\n # intervals and I\n elif self.min <= I[1] and I[0] <= self.max:\n for i, j in zip(self.intervals, self.elements):\n for t0, t1 in zip(i[::2], i[1::2]):\n if t0 <= I[1] and I[0] <= t1:\n intersec_b = max(t0, I[0])\n intersec_e = min(t1, I[1])\n results['intervals'].append([intersec_b,intersec_e])\n results['elements'].append(j)\n if self.right:\n if I[1] >= self.right.get_global_min():\n return self.right.search_interval_(I, results)\n if self.left:\n if I[0] <= self.left.get_global_max():\n return self.left.search_interval_(I, results)\n return results\n # elif t == self.t_mid:\n # return self.intervals\n\n\nclass Interval_Tree:\n def __init__(self):\n self.root = None\n\n def add(self, node):\n if not self.root:\n self.root = node\n else:\n self.__add__(node, self.root)\n\n def __add__(self, node, parent):\n if node.t_mid == parent.t_mid:\n parent.intervals.append(node.intervals)\n parent.elements.append(node.elements)\n if node.t_mid > parent.t_mid:\n if parent.right:\n self.__add__(node, parent.right)\n else:\n parent.right = node\n if node.t_mid < parent.t_mid:\n if parent.left:\n self.__add__(node, parent.left)\n else:\n parent.left = node\n\n def create_nodes_from_intervals(self, list_elements, list_int):\n empty = True\n for i in list_int:\n if i:\n empty = False\n break\n if empty:\n return\n t_mid = find_median(list_int)\n elements_node = []\n elements_left = []\n elements_right = []\n\n list_node_tree = []\n list_left = []\n list_right = []\n\n for i, j in zip(list_int, list_elements):\n r_tmp = []\n l_tmp = []\n n_tmp = []\n for t0, t1 in zip(i[::2], i[1::2]):\n if t0 > t_mid:\n r_tmp += [t0, t1]\n elif t1 < t_mid:\n l_tmp += [t0, t1]\n else:\n n_tmp += [t0, t1]\n if n_tmp:\n elements_node.append(j)\n list_node_tree.append(n_tmp)\n if l_tmp:\n elements_left.append(j)\n list_left.append(l_tmp)\n if r_tmp:\n elements_right.append(j)\n list_right.append(r_tmp)\n for i in list_node_tree:\n if i:\n self.add(Node(t_mid, elements_node, list_node_tree))\n break\n self.create_nodes_from_intervals(elements_left, list_left)\n self.create_nodes_from_intervals(elements_right, list_right)\n\n def search(self, t):\n return self.root.search_(t)\n\n def search_interval(self, I):\n return self.root.search_interval_(I)\n\n\ndef plot_tree(root, pos):\n # print(\"Plot pos :\",pos)\n # print(\"T_mid :\",root.t_mid)\n plt.plot([pos[0]], [pos[1]], 'ok')\n plt.annotate(str(root.t_mid),\n xy=pos, xycoords='data',\n xytext=(-50, 30), textcoords='offset points',\n arrowprops=dict(arrowstyle=\"->\"))\n if not root.right and not root.left:\n return\n if root.right:\n pos1 = (pos[0], pos[1] - 1)\n plot_tree(root.right, pos1)\n if root.left:\n pos1 = (pos[0] - 1, pos[1])\n plot_tree(root.left, pos1)\n\n\ndef print_interval_tree(N):\n try:\n N = N.root\n except:\n pass\n print(\"t_mid :\", N.t_mid)\n print(\"Elements :\", N.elements)\n print(\"Max :\", N.max, \" Min :\", N.min)\n print(\"Intervals :\", N.intervals, \"\\n\")\n if not N.left and not N.right:\n return\n if N.left:\n print(\"Left child :\")\n print_interval_tree(N.left)\n if N.right:\n print(\"Right child:\")\n print_interval_tree(N.right)\n\n\ndef find_median(list_intervals):\n tot_t = [i for sublist in list_intervals for i in sublist]\n tot_t.sort()\n l = len(tot_t)\n if l % 2 == 0:\n return (tot_t[l // 2] + tot_t[(l // 2) - 1]) / 2\n else:\n return tot_t[(l + 1) // 2 - 1]\n\n\ndef search_overlap_intervals(root, results=0):\n return\n\n\ndef plot_intervals(list_int):\n '''\n Display in an elegant way a small stream graph\n We can also specify a path to save the animated of ploted stream graph\n :param animated: If we want an animation with cursor which move according to the time\n :return: A matplotlib plot\n '''\n lnodes = len(list_int)\n c_map = sg.get_cmap(lnodes)\n fig = plt.figure()\n for p, t in zip(range(lnodes), list_int):\n plt.axhline(p, linestyle='--', linewidth=0.7,\n color=c_map(p), alpha=0.1)\n plt.hlines([p] * (len(t) // 2), xmin=t[::2], linewidth=1.1,\n xmax=t[1::2], colors=c_map(p), alpha=0.9)\n\n\ndef plot_tree2(root):\n # print(\"Plot pos :\",pos)\n # print(\"T_mid :\",root.t_mid)\n plot_intervals(root.intervals)\n if not root.right and not root.left:\n return\n if root.right:\n plot_tree2(root.right)\n if root.left:\n plot_tree2(root.left)\n\n\nif __name__ == '__main__':\n nodes = ['A', 'B', 'C', 'D', 'E', 'F']\n list_int = [[4, 8, 11, 17, 35, 40],\n [1, 3, 9, 10, 17, 19, 21, 22.5],\n [5, 15, 20, 22, 31.2, 34.8],\n [1.2, 5.4, 8.5, 10.6, 23, 24, 45, 50],\n [20, 22],\n [1, 15, 16, 35]]\n plot_intervals(list_int)\n\n n_inter = sum([len(i) / 2 for i in list_int])\n # print(\"N intervals :\",n_inter)\n W = Interval_Tree()\n W.create_nodes_from_intervals(nodes, list_int)\n # print_interval_tree(W.root)\n # plot_tree(W.root, (0, 0))\n # plt.show()\n t = 10\n r = W.search(t)\n print(\"Intervals at \" + str(t) + \" :\", r)\n print(\"Get global min right :\", W.root.right.get_global_min())\n print(\"Get global max right :\", W.root.right.get_global_max())\n print(\"Get global min left:\", W.root.left.get_global_min())\n\n print(\"Get global max left:\", W.root.left.get_global_max())\n I = [18.5, 20.5]\n r2 = W.search_interval(I)\n print(\"Intervals in \" + str(I) + \" :\", r2)\n print_interval_tree(W)\n","sub_path":"interval_tree/interval_tree.py","file_name":"interval_tree.py","file_ext":"py","file_size_in_byte":9439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"284903432","text":"\n\n#calss header\nclass _CALM():\n\tdef __init__(self,): \n\t\tself.name = \"CALM\"\n\t\tself.definitions = [u'to stop someone feeling upset, angry, or excited: ', u'to make someone feel less worried about 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/_calm.py","file_name":"_calm.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"652598025","text":"from frozenlake import FrozenLakeEnv\nimport numpy as np\nfrom plot_utils import plot_values\nimport copy\n\nenv = FrozenLakeEnv()\n# # ========================1.迭代策略评估 ==========================\n# V_list = []\n# counts = 2\n#\n# \"\"\"\n# 用户迭代策略评估:\n# 输入:环境、策略、gamma、theta\n# 输出:V(状态价值函数)\n# \"\"\"\n# def policy_evaluation(env,policy,gamma=1,theta=1e-8):\n# V = np.zeros(env.nS)\n# print(V)\n# V_list.append(V.copy())\n# while True:\n# # for i in range(counts):\n# delta = 0\n# for s in range(env.nS):\n# Vs = 0\n# for a,action_prob in enumerate(policy[s]):\n# for prob,next_state,reward,done in env.P[s][a]:\n# Vs += action_prob * prob * (reward + gamma * V[next_state])\n# delta = max(delta,np.abs(Vs - V[s])) #这里其实就是在找 每个状态更新幅度最大的那个值,最大都没超过theta就说明收敛了\n# V[s] = Vs\n# V_list.append(V.copy()) # 测试\n# if delta < theta:\n# break\n# print(V)\n# return V\n#\n\n# random_policy = np.ones([env.nS,env.nA])/env.nA\n# V = policy_evaluation(env,random_policy)\n#\n# # plot_values(V)\n# print(len(V_list))\n#\n# for i in range(counts+1):\n# plot_values(V_list[i])\n#\n#\n# # ========================2.v派->q派 动作值函数的评估==========================\n# \"\"\"\n# 输入:环境、状态值函数估值、某一个状态、gamma\n# 返回:q(s,a)\n#\n# 所谓Q函数,其实就是(s,a)对应的价值\n# \"\"\"\ndef q_from_v(env, V, s, gamma=1):\n q = np.zeros(env.nA) # 返回的q应该是个一位数组,长度为动作空间维度,初始化为0\n for a in range(env.nA):\n for prob, next_state, reward, done in env.P[s][a]:\n q[a] += prob * (reward + gamma * V[next_state])\n\n return q\n#\n# Q = np.zeros([env.nS,env.nA])\n#\n# for s in range(env.nS):\n# Q[s] =q_from_v(env,V,s)\n# print('Action Values:')\n# print(Q)\n#\n#\n# # ===========3.策略改进 ==============\n# \"\"\"\n# 策略改进:\n# 输入:环境,对该策略V估值,gamma\n# 输出:policy(s行 a列)\n# \"\"\"\ndef policy_improvement(env, V, gamma=1):\n policy = np.zeros([env.nS,env.nA])/env.nA #设置一个全0的policy作为初始化\n\n for s in range(env.nS):\n q = q_from_v(env, V, s, gamma)\n\n #1 贪婪算法,直接选最大的q值 确定性策略\n # policy[s][np.argmax(q)] = 1\n #2 随机算法,对多个取得最大值的q值取一个随机\n best_a = np.argwhere(q==np.max(q)).flatten()\n policy[s] = np.sum([np.eye(env.nA)[i] for i in best_a], axis=0)/len(best_a)\n\n return policy\n#\n# policy = policy_improvement(env, V)\n# print(\"Policy Improvement:\")\n# print(policy)\n#\n# #LEFT = 0 DOWN = 1 RIGHT = 2 UP = 3\n#\n# # =========== 4. 策略迭代 ===========\n# \"\"\"\n# 输入:env环境、gamma、theta\n# 输出:policy、V\n# \"\"\"\n# def policy_iteration(env, gamma=1, theta = 1e-8):\n# policy = np.ones([env.nS,env.nA]) #一般初始化策略就是各个动作概率都一样\n# while True:\n# V = policy_evaluation(env,policy,gamma,theta) # 先进行迭代策略评估,得到当前策略的V\n# new_policy = policy_improvement(env,V) #估计好了当前策略的V,就可以进行策略改进了,这里产生新策略\n#\n# if(new_policy == policy).all(): #循环这个两个过程,直倒更新不懂了\n# break\n#\n# # if np.max(abs(policy_evaluation(env, policy) - policy_evaluation(env, new_policy))) < theta*1e2:\n# # break;\n#\n# policy = copy.copy(new_policy) # 拷贝新polcy,继续下一次循环\n#\n# return policy,V # 返回训练好的policy 和对应的 V估值\n#\n# policy_pi, V_pi = policy_iteration(env)\n# print('\\nOptimal Policy:LEFT = 0 DOWN = 1 RIGHT = 2 UP = 3')\n# print(policy_pi)\n#\n# plot_values(V_pi)\n\n\n# -=================5. 截断策略迭代 ==============\n# def truncated_policy_evaluation(env, policy, V, max_it=1, gamma=1):\n# num_it = 0\n# while num_it < max_it:\n# for s in range(env.nS):\n# v = 0\n# q = q_from_v(env, V, s, gamma)\n# for a, action_prob in enumerate(policy[s]):\n# v += action_prob * q[a] #与值迭代关键不同的地方\n# V[s] = v\n# # 区别就在这 原来迭代策略的循环停止条件是更新值小,这里给定循环次数了\n# num_it += 1\n# return V\n#\n#\n# def truncated_policy_iteration(env,max_it = 1,gamma = 1,theta = 1e-8):\n# V = np.zeros(env.nS)\n# policy = np.zeros([env.nS, env.nA]) / env.nA\n# while True:\n# policy = policy_improvement(env, V)\n# old_V = copy.copy(V)\n# V = truncated_policy_evaluation(env, policy, V, max_it, gamma)\n# if max(abs(V - old_V)) < theta:\n# break\n# return policy, V\n#\n# policy_tpi, V_tpi = truncated_policy_iteration(env, max_it=2)\n\n# print the optimal policy\n# print(\"\\nOptimal Policy (LEFT = 0, DOWN = 1, RIGHT = 2, UP = 3):\")\n# print(policy_tpi,\"\\n\")\n\n# plot the optimal state-value function\n# plot_values(V_tpi)\n\n# ==========================6. 值迭代 ===============================\n\"\"\"\n值迭代:\n输入:env,gamma,theta\n输出:policy,V\n其实输入输出和策略迭代和截断策略迭代是一样的\n\"\"\"\ndef value_iteration(env, gamma=1, theta=1e-8):\n V = np.zeros(env.nS)\n while True:\n delta = 0\n for s in range(env.nS):\n v = V[s]\n V[s] = max(q_from_v(env, V, s, gamma)) # 与策略迭代的关键不同\n delta = max(delta, abs(V[s]-v))\n if delta < theta:\n break\n policy = policy_improvement(env, V, gamma)\n return policy, V\n\npolicy_vi, V_vi = value_iteration(env)\n# print the optimal policy\nprint(\"\\nOptimal Policy (LEFT = 0, DOWN = 1, RIGHT = 2, UP = 3):\")\nprint(policy_vi,\"\\n\")\n\n# plot the optimal state-value function\nplot_values(V_vi)\n","sub_path":"02DeepReinforcementLearning/02DynamicPlanning/FrozenLakeD.py","file_name":"FrozenLakeD.py","file_ext":"py","file_size_in_byte":5968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"604032424","text":"import os\nimport configparser\n\n__all__ = ['config']\n\n\nclass _ConfigReader(object):\n configs = {}\n\n @staticmethod\n def get_config(name, **kwargs):\n if name not in _ConfigReader.configs:\n _ConfigReader.configs[name] = _ConfigReader._read_config(name, **kwargs)\n return _ConfigReader.configs[name]\n\n @staticmethod\n def _read_config(module_name, keep_letters_case=True):\n base_dir = _ConfigReader._get_basedir(module_name)\n main_cfg_path = os.path.join(base_dir, module_name, 'conf.ini')\n if not os.path.exists(main_cfg_path):\n raise Exception('Configuration file \\'{}\\' does not exist'.format(main_cfg_path))\n\n conf = configparser.ConfigParser(default_section=None)\n if keep_letters_case:\n conf.optionxform = str\n conf.read(main_cfg_path, encoding='utf-8')\n return conf\n\n @staticmethod\n def _get_basedir(module_name):\n def my_import(name):\n m = __import__(name)\n for n in name.split(\".\")[1:]:\n m = getattr(m, n)\n return m\n return os.path.dirname(os.path.dirname(os.path.dirname(my_import(module_name).__file__)))\n\n\nconfig = _ConfigReader.get_config('schema_watcher')\n","sub_path":"schema_watcher/utils/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"635463041","text":"class Bookstore:\r\n NoofBooks=0\r\n def __init__(self,Name,Author):\r\n self.n=Name\r\n self.a=Author\r\n print(\"Enter Name of book:\")\r\n self.n=(input())\r\n print(\"Enter Author of book:\")\r\n self.a =(input())\r\n Bookstore.NoofBooks+=1\r\n \r\n\r\n def Display(self):\r\n print(\"Name of Book is:\",self.n)\r\n print(\"Author of Book is:\",self.a)\r\n print(\"Number of Books is:\",self.NoofBooks)\r\ndef main():\r\n obj1=Bookstore(\"Linux System Programming\", \"Robert Love\")\r\n obj1.Display()\r\n \r\n obj2=Bookstore(\"C Programming\",\"Dennis Ritchie\")\r\n obj2.Display()\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()","sub_path":"assignment7/assignment7_1.py","file_name":"assignment7_1.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"474993155","text":"from django.shortcuts import render, redirect, get_object_or_404\n\nfrom .forms import EnlaceForm\nfrom .models import Enlace\n\n\n\ndef home(request):\n enlaces = Enlace.objects.all()\n return render(request, 'linkapp/home.html', {'enlaces':enlaces})\n \n \n \n\ndef agregar(request):\n if request.method=='POST':\n form = EnlaceForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('/')\n else:\n form = EnlaceForm() \n return render(request, 'linkapp/agregar.html', {'form':form})\n\ndef editar(request, pk):\n enlace = Enlace.objects.get(id=pk)\n form = EnlaceForm(instance=enlace)\n if request.method=='GET':\n form = EnlaceForm(instance=enlace)\n else: \n form = EnlaceForm(request.POST, instance=enlace)\n if form.is_valid():\n form.save()\n return redirect('/')\n \n\n return render(request, 'linkapp/editar.html', {'form':form})\n\ndef eliminar(request, pk):\n enlace = Enlace.objects.get(id=pk)\n enlace.delete()\n return redirect('/')\n\n\n\n \n\n","sub_path":"linkapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"512940242","text":"with open(\"Day 9.txt\",\"r\") as f: inputt=f.read().strip()\n#with open(\"example.txt\",\"r\") as f: inputt=f.read().strip()\n\n\nplayers = int(inputt.split(\" \")[0])\npoints = int(inputt.split(\"worth \")[1].split(\" \")[0])\n\nclass Marble:\n def __init__(self, value):\n self.value = value\n self.next = self\n self.prev = self\n\n def add_marble(self, nv):\n if nv % 23:\n new = Marble(nv)\n one = self.next\n two = self.next.next\n new.prev = one\n new.next = two\n one.next = new\n two.prev = new\n return new, 0\n else:\n past = self\n for x in range(7):\n past = past.prev\n past.next.prev = past.prev\n past.prev.next = past.next\n return past.next, (nv + past.value)\n\np_num = 0\nx=0\ncm = Marble(0)\nplayer_list = [0 for x in range(players)]\nwhile cm.value != points * 100:\n cm, score = cm.add_marble(x)\n player_list[p_num]+=score\n p_num+=1\n p_num%=players\n x+=1\nprint(max(player_list))\n\n\n\n\n\n","sub_path":"2018/Day 9/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"123915550","text":"import unittest\nimport subprocess\nimport re\nimport sys\nimport os\n\nfrom seaoftacos import *\n\n\nclass TestMemory(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n if sys.maxsize > 2**32:\n cls.__procname = \"tester_x64.exe\"\n else:\n cls.__procname = \"tester_x86.exe\"\n\n cls.__process = subprocess.Popen(\n f\"tests/{cls.__procname}\", stdout=subprocess.PIPE)\n\n cls.__addresses = []\n for line in [cls.__process.stdout.readline() for _ in range(4)]:\n cls.__addresses.append(int(line, 16))\n\n @classmethod\n def tearDownClass(cls):\n cls.__process.terminate()\n cls.__process.wait()\n\n def test_platform(self):\n \"\"\" Test if the current platform is Windows \"\"\"\n\n self.assertEqual(os.name, \"nt\")\n\n def test_read(self):\n \"\"\" Test the read methods \"\"\"\n\n try:\n proc = Process(self.__process.pid)\n proc.open()\n\n except ProcessException:\n self.fail(\"Failed to open process.\")\n\n mem = Memory(proc)\n self.assertEqual(mem.read_short(self.__addresses[0]), 1234)\n self.assertEqual(mem.read_int(self.__addresses[1]), 5678)\n self.assertEqual(mem.read_long(self.__addresses[2]), 9123)\n self.assertEqual(mem.read_string(\n self.__addresses[3]), \"TESTING # 12345\")\n\n proc.close()\n\n def test_read(self):\n \"\"\" Test the read methods \"\"\"\n\n try:\n proc = Process(self.__process.pid)\n proc.open()\n\n except ProcessException:\n self.fail(\"Failed to open process.\")\n\n mem = Memory(proc)\n self.assertEqual(mem.read_short(self.__addresses[0]), 1234)\n self.assertEqual(mem.read_int(self.__addresses[1]), 5678)\n self.assertEqual(mem.read_long(self.__addresses[2]), 9123)\n self.assertEqual(mem.read_string(\n self.__addresses[3]), \"TESTING # 12345\")\n\n proc.close()\n\n def test_write(self):\n \"\"\" Test the write methods \"\"\"\n\n try:\n proc = Process(self.__process.pid)\n proc.open()\n\n except ProcessException:\n self.fail(\"Failed to open process.\")\n\n mem = Memory(proc)\n\n mem.write_short(self.__addresses[0], 4321)\n self.assertEqual(mem.read_short(self.__addresses[0]), 4321)\n\n mem.write_int(self.__addresses[1], 8765)\n self.assertEqual(mem.read_int(self.__addresses[1]), 8765)\n\n mem.write_long(self.__addresses[2], 3219)\n self.assertEqual(mem.read_long(self.__addresses[2]), 3219)\n\n mem.write_string(self.__addresses[3], \"54321 # GNITSET\")\n self.assertEqual(mem.read_string(\n self.__addresses[3]), \"54321 # GNITSET\")\n\n proc.close()\n\n def test_alloc_misc(self):\n \"\"\" Test the alloc, protect and free methods \"\"\"\n\n try:\n proc = Process(self.__process.pid)\n proc.open()\n except ProcessException:\n self.fail(\"Failed to open process.\")\n\n mem = Memory(proc)\n\n mem_ptr = mem.allocate(1024, MemoryProtection.PAGE_READWRITE)\n\n mem.write_string(mem_ptr, \"TEST 12345678\")\n mem.protect(mem_ptr, 1024, MemoryProtection.PAGE_READONLY)\n\n try:\n mem.write_string(mem_ptr, \"TEST 87654321\") # Expected failure on this since memory is protected\n self.fail(\"Memory is not protected.\")\n except MemoryException:\n pass\n\n mem.free(mem_ptr)\n proc.close()\n\n def test_pattern_scan(self):\n \"\"\" Test the pattern scan feature \"\"\"\n\n try:\n proc = Process(self.__process.pid)\n proc.open()\n except ProcessException:\n self.fail(\"Failed to open process.\")\n\n mem = Memory(proc)\n \n mem_ptr = mem.allocate(1024, MemoryProtection.PAGE_READWRITE)\n\n mem.write_memory(mem_ptr, b\"\\x41\\x41\\x41\\x41\\x42\\x42\\x42\\x42\\x43\\x43\\x43\\x43\")\n\n base_addr = proc.module_address(f\"{self.__procname}\")\n base_size = proc.module_size(f\"{self.__procname}\")\n\n pattern_ptr = mem.pattern_scan(mem_ptr - 4096, 8192, \"41 41 41 41 42 42 42 42 43 43 43 43\")[0]\n\n if pattern_ptr != mem_ptr:\n self.fail(\"Wrong address found.\")\n\n proc.close()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_memory.py","file_name":"test_memory.py","file_ext":"py","file_size_in_byte":4324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"349846081","text":"import os\nimport glob\nfrom conans import ConanFile, CMake, tools\nfrom conans.errors import ConanInvalidConfiguration, ConanException\n\n\nclass ConanRecipe(ConanFile):\n name = \"abseil\"\n\n description = \"Abseil Common Libraries (C++) from Google\"\n topics = (\"algorithm\", \"container\", \"google\", \"common\", \"utility\")\n\n homepage = \"https://github.com/abseil/abseil-cpp\"\n url = \"https://github.com/conan-io/conan-center-index\"\n\n license = \"Apache-2.0\"\n\n settings = \"os\", \"arch\", \"compiler\", \"build_type\"\n\n options = {\"fPIC\": [True, False]}\n default_options = {\"fPIC\": True}\n\n generators = \"cmake\"\n short_paths = True\n\n @property\n def _source_subfolder(self):\n return \"source_subfolder\"\n\n def source(self):\n tools.get(**self.conan_data[\"sources\"][self.version])\n extracted_dir = glob.glob('abseil-cpp-*/')[0]\n os.rename(extracted_dir, self._source_subfolder)\n tools.replace_in_file(\n os.path.join(self._source_subfolder, \"CMakeLists.txt\"),\n \"project(absl CXX)\", \"\"\"project(absl CXX)\ninclude(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)\nconan_basic_setup()\"\"\")\n\n def config_options(self):\n if self.settings.os == \"Windows\":\n del self.options.fPIC\n\n def configure(self):\n minimal_cpp_standard = \"11\"\n\n try:\n tools.check_min_cppstd(self, minimal_cpp_standard)\n except ConanInvalidConfiguration:\n raise\n except ConanException:\n # FIXME: We need to handle the case when Conan doesn't know\n # about a user defined compiler's default standard version\n self.output.warn(\n \"Unnable to determine the default standard version of the compiler\")\n\n minimal_version = {\n \"Visual Studio\": \"14\",\n }\n\n compiler = str(self.settings.compiler)\n if compiler not in minimal_version:\n self.output.warn(\n \"%s recipe lacks information about the %s compiler support\" % (self.name, compiler))\n self.output.warn(\n \"%s requires a compiler that supports at least C++%s\" % (self.name, minimal_cpp_standard))\n return\n\n version = tools.Version(self.settings.compiler.version)\n if version < minimal_version[compiler]:\n raise ConanInvalidConfiguration(\n \"%s requires at least %s %s\" % (self.name, compiler, minimal_version[compiler]))\n\n def _configure_cmake(self):\n cmake = CMake(self)\n cmake.definitions[\"BUILD_TESTING\"] = False\n cmake.configure(\n source_folder=self._source_subfolder\n )\n return cmake\n\n def build(self):\n cmake = self._configure_cmake()\n cmake.build()\n\n def package(self):\n self.copy(\"LICENSE\", dst=\"licenses\", src=self._source_subfolder)\n cmake = self._configure_cmake()\n cmake.install()\n tools.rmdir(os.path.join(self.package_folder, \"lib\", \"cmake\"))\n\n def package_info(self):\n self.cpp_info.libs = [\n \"absl_flags_parse\",\n \"absl_flags_usage\",\n \"absl_flags_usage_internal\",\n \"absl_flags\",\n \"absl_flags_internal\",\n \"absl_flags_registry\",\n \"absl_flags_config\",\n \"absl_flags_program_name\",\n \"absl_flags_marshalling\",\n \"absl_raw_hash_set\",\n \"absl_random_seed_sequences\",\n \"absl_hashtablez_sampler\",\n \"absl_synchronization\",\n \"absl_time\",\n \"absl_civil_time\",\n \"absl_time_zone\",\n \"absl_failure_signal_handler\",\n \"absl_random_internal_distribution_test_util\",\n \"absl_examine_stack\",\n \"absl_symbolize\",\n \"absl_str_format_internal\",\n \"absl_graphcycles_internal\",\n \"absl_stacktrace\",\n \"absl_malloc_internal\",\n \"absl_demangle_internal\",\n \"absl_debugging_internal\",\n \"absl_periodic_sampler\",\n \"absl_exponential_biased\",\n \"absl_random_internal_pool_urbg\",\n \"absl_random_distributions\",\n \"absl_random_internal_seed_material\",\n \"absl_random_seed_gen_exception\",\n \"absl_hash\",\n \"absl_strings\",\n \"absl_strings_internal\",\n \"absl_bad_variant_access\",\n \"absl_throw_delegate\",\n \"absl_city\",\n \"absl_base\",\n \"absl_dynamic_annotations\",\n \"absl_bad_any_cast_impl\",\n \"absl_scoped_set_env\",\n \"absl_bad_optional_access\",\n \"absl_raw_logging_internal\",\n \"absl_log_severity\",\n \"absl_spinlock_wait\",\n \"absl_random_internal_randen\",\n \"absl_random_internal_randen_hwaes\",\n \"absl_random_internal_randen_slow\",\n \"absl_random_internal_randen_hwaes_impl\",\n \"absl_leak_check\",\n \"absl_leak_check_disable\",\n \"absl_int128\"\n ]\n if self.settings.os == \"Linux\":\n self.cpp_info.system_libs.append(\"pthread\")\n if self.settings.os == \"Macos\":\n self.cpp_info.frameworks.append(\"CoreFoundation\")\n self.cpp_info.names[\"cmake_find_package\"] = \"absl\"\n self.cpp_info.names[\"cmake_find_package_multi\"] = \"absl\"\n","sub_path":"recipes/abseil/all/conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":5336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"241072998","text":"import boto3\nimport socket\nimport ssl\nimport datetime\nimport re\nimport csv\nimport json\n\nprint('Loading function')\n\ns3 = boto3.client('s3')\n\n# This token is used to associate log files in AWS S3 to a log in your Logentries account.\nlog_token = \"YOUR_LOG_TOKEN\"\n\n# You can supply an optional token to log activity to a log on Logentries and any errors from this script.\n# This is optional, it is recommended you use one log file/token for all your Lambda scripts. If you do not\n# wish to use this, just leave the value blank.\ndebug_token = \"YOUR_DEBUG_TOKEN\"\n\n# Log to generic activity from this script to our support logging system for Lambda scripts\n# this is optional, but helps us improve our service nad can be hand for us helping you debug any issues\n# just remove this token if you wish (leave variable in place)\nlambda_token = \"0ae0162e-855a-4b54-9ae3-bd103006bfc0\"\n\n# Used to send to debug log\nusername = \"YOUR_USERNAME\"\n\ndef lambda_handler(event, context):\n # Get the object from the event and show its content type\n bucket = event['Records'][0]['s3']['bucket']['name']\n key = event['Records'][0]['s3']['object']['key']\n\n with LogentriesLogger(log_token, debug_token, lambda_token) as logger:\n parse_s3_object(bucket, key, logger)\n\ndef parse_s3_object(bucket, key, logger):\n try:\n response = s3.get_object(Bucket=bucket, Key=key)\n body = response['Body']\n\n data = body.read()\n\n msg = \"username='{}' downloaded file='{}' from bucket='{}'.\".format(username, key, bucket)\n logger.log_debug(msg)\n\n is_elb_data = validate_elb_log(str(key))\n parse_data(data, is_elb_data, logger)\n except Exception as e:\n print(e)\n msg = \"Error getting username='{}' file='{}' from bucket='{}'. Make sure they exist and your bucket is in the same region as this function.\".format(username, key, bucket)\n logger.log_debug(msg)\n\ndef parse_data(data, is_elb_data, logger):\n try:\n lines = data.split('\\n')\n msg = \"Beginning to send lines='{}' start_time='{}'.\".format(str(len(lines)), str(datetime.datetime.utcnow()))\n logger.log_debug(msg)\n\n if is_elb_data is True:\n rows = csv.reader(data.splitlines(), delimiter=' ', quotechar='\"')\n for line in rows:\n entry = customize_entry(line)\n logger.log_entry(entry)\n else:\n for line in lines:\n logger.log_entry(line)\n\n msg = \"username='{}' finished sending log data end_time='{}'\".format(username, str(datetime.datetime.utcnow()))\n logger.log_debug(msg)\n except Exception as e:\n print(e)\n logger.log_debug(e)\n\ndef customize_entry(line):\n # Get the log data in as a dictionary to easily work with it\n log = structure_elb_log(line)\n\n # To customize the log entry, modify the code below\n request = log['request'].split(' ')\n idx = request[1].find('/', 9)\n url = request[1][idx:]\n parsed = {\n 'ip': log['client:port'].split(':')[0],\n 'request_time': log['backend_processing_time'],\n 'elb_status': log['elb_status_code'],\n 'backend_status': log['backend_status_code'],\n 'bytes_received': log['received_bytes'],\n 'bytes_sent': log['sent_bytes'],\n 'method': request[0],\n 'url': url,\n 'user_agent': log['user_agent']\n }\n\n # Log as key value pairs (a=b)\n format = ''.join(['%s=\"%s\" ' % (k,v) for k,v in parsed.iteritems()])\n entry = '%s %s' % (log['timestamp'], format)\n\n # To log as JSON, set this variable to ture\n format_json = False\n if format_json is True:\n entry = json.dumps(parsed)\n\n return entry\n\ndef structure_elb_log(line):\n # Log value positions from http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/access-log-collection.html#access-log-entry-format\n # timestamp elb client:port backend:port request_processing_time backend_processing_time\n # response_processing_time elb_status_code backend_status_code received_bytes sent_bytes\n # \"request\" \"user_agent\" ssl_cipher ssl_protocol\n\n parsed = {\n 'timestamp': line[0],\n 'elb': line[1],\n 'client:port': line[2],\n 'backend:port': line[3],\n 'request_processing_time': line[4],\n 'backend_processing_time': line[5],\n 'response_processing_time': line[6],\n 'elb_status_code': line[7],\n 'backend_status_code': line[8],\n 'received_bytes': line[9],\n 'sent_bytes': line[10],\n 'request': line[11],\n 'user_agent': line[12],\n 'ssl_cipher': line[13],\n 'ssl_protocol': line[14]\n }\n return parsed\n\ndef validate_elb_log(key):\n # The split is done here to allow for input of an object\n # name that contains the full path in the bucket without\n # the bucket's name.\n key = key.split('/')[-1]\n regex = re.compile('^\\d+_\\w+_\\w{2}-\\w{4,9}-[12]_.*._\\d{8}T\\d{4}Z_\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}_.*.log$', re.I)\n match = regex.match(key)\n return bool(match)\n\nclass LogentriesLogger:\n def __init__(self, log_token, debug_token, lambda_token):\n host = 'data.logentries.com'\n port = 20000\n s_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s = ssl.wrap_socket(s_, ca_certs='le_certs.pem', cert_reqs=ssl.CERT_REQUIRED)\n s.connect((host, port))\n self.logentries_socket = s\n\n self.log_token = log_token\n self.lambda_token = lambda_token\n\n self.log_debug_tokens = []\n if self.validate_uuid(debug_token) is True:\n self.log_debug_tokens.append(debug_token)\n if self.validate_uuid(lambda_token) is True:\n self.log_debug_tokens.append(lambda_token)\n\n if self.validate_uuid(log_token) is False:\n self.log_debug(\"{}: log token not present for username={}\"\n .format(str(datetime.datetime.utcnow()), username))\n raise SystemExit\n\n def log_entry(self, line):\n self.logentries_socket.sendall('%s %s\\n' % (self.log_token, line))\n print(line)\n\n def log_debug(self, line):\n for token in self.log_debug_tokens:\n self.logentries_socket.sendall('%s %s\\n' % (token, line))\n print(line)\n\n def validate_uuid(self, uuid_string):\n regex = re.compile('^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$', re.I)\n match = regex.match(uuid_string)\n return bool(match)\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.logentries_socket.close();\n\nclass ConsoleLogger:\n def log_entry(self, line):\n print(line)\n\n def log_debug(self, line):\n print(line)\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n pass\n\nif __name__ == \"__main__\":\n # To test, pick a logger\n\n # To setup a Logentries logger, uncomment the following line:\n # with LogentriesLogger(log_token, debug_token, lambda_token) as logger\n\n with ConsoleLogger() as logger:\n # You can test the output by calling a local ELB log file ...\n data = open('test-data.log').read().splitlines()\n\n # ... OR create a list of strings ...\n data = [\n '2015-05-13T23:39:43.945958Z my-loadbalancer 192.168.131.39:2817 10.0.0.1:80 0.000086 0.001048 0.001337 200 200 0 57 \\\"GET https://www.example.com:443/ HTTP/1.1\\\" \\\"curl/7.38.0\\\" DHE-RSA-AES128-SHA TLSv1.2',\n '2015-05-13T23:39:43.945958Z my-loadbalancer 192.168.131.39:2817 10.0.0.1:80 0.000086 0.001048 0.001337 200 200 0 57 \\\"GET https://www.example.com:443/ HTTP/1.1\\\" \\\"curl/7.38.0\\\" DHE-RSA-AES128-SHA TLSv1.2',\n '2015-05-13T23:39:43.945958Z my-loadbalancer 192.168.131.39:2817 10.0.0.1:80 0.000086 0.001048 0.001337 200 200 0 57 \\\"GET https://www.example.com:443/ HTTP/1.1\\\" \\\"curl/7.38.0\\\" DHE-RSA-AES128-SHA TLSv1.2',\n '2015-05-13T23:39:43.945958Z my-loadbalancer 192.168.131.39:2817 10.0.0.1:80 0.000086 0.001048 0.001337 200 200 0 57 \\\"GET https://www.example.com:443/ HTTP/1.1\\\" \\\"curl/7.38.0\\\" DHE-RSA-AES128-SHA TLSv1.2',\n '2015-05-13T23:39:43.945958Z my-loadbalancer 192.168.131.39:2817 10.0.0.1:80 0.000086 0.001048 0.001337 200 200 0 57 \\\"GET https://www.example.com:443/ HTTP/1.1\\\" \\\"curl/7.38.0\\\" DHE-RSA-AES128-SHA TLSv1.2',\n '2015-05-13T23:39:43.945958Z my-loadbalancer 192.168.131.39:2817 10.0.0.1:80 0.000086 0.001048 0.001337 200 200 0 57 \\\"GET https://www.example.com:443/ HTTP/1.1\\\" \\\"curl/7.38.0\\\" DHE-RSA-AES128-SHA TLSv1.2',\n '2015-05-13T23:39:43.945958Z my-loadbalancer 192.168.131.39:2817 10.0.0.1:80 0.000086 0.001048 0.001337 200 200 0 57 \\\"GET https://www.example.com:443/ HTTP/1.1\\\" \\\"curl/7.38.0\\\" DHE-RSA-AES128-SHA TLSv1.2'\n ]\n\n rows = csv.reader(data, delimiter=' ', quotechar='\"')\n for line in rows:\n entry = customize_entry(line)\n logger.log_entry(entry)\n\n # ... OR can call an existing ELB log file in an S3 bucket\n # key = 'YOUR_LOG_FILE_NAME.log'\n # bucket = 'YOUR BUCKET NAME'\n # parse_s3_object(bucket, key, logger)\n","sub_path":"le_lambda.py","file_name":"le_lambda.py","file_ext":"py","file_size_in_byte":9196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"202986883","text":"# Copyright 2023 Google LLC. All Rights Reserved.\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom connector import channel\nfrom google3.cloud.graphite.mmv2.services.google.clouddeploy import target_pb2\nfrom google3.cloud.graphite.mmv2.services.google.clouddeploy import target_pb2_grpc\n\nfrom typing import List\n\n\nclass Target(object):\n def __init__(\n self,\n name: str = None,\n target_id: str = None,\n uid: str = None,\n description: str = None,\n annotations: dict = None,\n labels: dict = None,\n require_approval: bool = None,\n create_time: str = None,\n update_time: str = None,\n gke: dict = None,\n anthos_cluster: dict = None,\n etag: str = None,\n execution_configs: list = None,\n project: str = None,\n location: str = None,\n run: dict = None,\n multi_target: dict = None,\n deploy_parameters: dict = None,\n service_account_file: str = \"\",\n ):\n channel.initialize()\n self.name = name\n self.description = description\n self.annotations = annotations\n self.labels = labels\n self.require_approval = require_approval\n self.gke = gke\n self.anthos_cluster = anthos_cluster\n self.execution_configs = execution_configs\n self.project = project\n self.location = location\n self.run = run\n self.multi_target = multi_target\n self.deploy_parameters = deploy_parameters\n self.service_account_file = service_account_file\n\n def apply(self):\n stub = target_pb2_grpc.ClouddeployTargetServiceStub(channel.Channel())\n request = target_pb2.ApplyClouddeployTargetRequest()\n if Primitive.to_proto(self.name):\n request.resource.name = Primitive.to_proto(self.name)\n\n if Primitive.to_proto(self.description):\n request.resource.description = Primitive.to_proto(self.description)\n\n if Primitive.to_proto(self.annotations):\n request.resource.annotations = Primitive.to_proto(self.annotations)\n\n if Primitive.to_proto(self.labels):\n request.resource.labels = Primitive.to_proto(self.labels)\n\n if Primitive.to_proto(self.require_approval):\n request.resource.require_approval = Primitive.to_proto(\n self.require_approval\n )\n\n if TargetGke.to_proto(self.gke):\n request.resource.gke.CopyFrom(TargetGke.to_proto(self.gke))\n else:\n request.resource.ClearField(\"gke\")\n if TargetAnthosCluster.to_proto(self.anthos_cluster):\n request.resource.anthos_cluster.CopyFrom(\n TargetAnthosCluster.to_proto(self.anthos_cluster)\n )\n else:\n request.resource.ClearField(\"anthos_cluster\")\n if TargetExecutionConfigsArray.to_proto(self.execution_configs):\n request.resource.execution_configs.extend(\n TargetExecutionConfigsArray.to_proto(self.execution_configs)\n )\n if Primitive.to_proto(self.project):\n request.resource.project = Primitive.to_proto(self.project)\n\n if Primitive.to_proto(self.location):\n request.resource.location = Primitive.to_proto(self.location)\n\n if TargetRun.to_proto(self.run):\n request.resource.run.CopyFrom(TargetRun.to_proto(self.run))\n else:\n request.resource.ClearField(\"run\")\n if TargetMultiTarget.to_proto(self.multi_target):\n request.resource.multi_target.CopyFrom(\n TargetMultiTarget.to_proto(self.multi_target)\n )\n else:\n request.resource.ClearField(\"multi_target\")\n if Primitive.to_proto(self.deploy_parameters):\n request.resource.deploy_parameters = Primitive.to_proto(\n self.deploy_parameters\n )\n\n request.service_account_file = self.service_account_file\n\n response = stub.ApplyClouddeployTarget(request)\n self.name = Primitive.from_proto(response.name)\n self.target_id = Primitive.from_proto(response.target_id)\n self.uid = Primitive.from_proto(response.uid)\n self.description = Primitive.from_proto(response.description)\n self.annotations = Primitive.from_proto(response.annotations)\n self.labels = Primitive.from_proto(response.labels)\n self.require_approval = Primitive.from_proto(response.require_approval)\n self.create_time = Primitive.from_proto(response.create_time)\n self.update_time = Primitive.from_proto(response.update_time)\n self.gke = TargetGke.from_proto(response.gke)\n self.anthos_cluster = TargetAnthosCluster.from_proto(response.anthos_cluster)\n self.etag = Primitive.from_proto(response.etag)\n self.execution_configs = TargetExecutionConfigsArray.from_proto(\n response.execution_configs\n )\n self.project = Primitive.from_proto(response.project)\n self.location = Primitive.from_proto(response.location)\n self.run = TargetRun.from_proto(response.run)\n self.multi_target = TargetMultiTarget.from_proto(response.multi_target)\n self.deploy_parameters = Primitive.from_proto(response.deploy_parameters)\n\n def delete(self):\n stub = target_pb2_grpc.ClouddeployTargetServiceStub(channel.Channel())\n request = target_pb2.DeleteClouddeployTargetRequest()\n request.service_account_file = self.service_account_file\n if Primitive.to_proto(self.name):\n request.resource.name = Primitive.to_proto(self.name)\n\n if Primitive.to_proto(self.description):\n request.resource.description = Primitive.to_proto(self.description)\n\n if Primitive.to_proto(self.annotations):\n request.resource.annotations = Primitive.to_proto(self.annotations)\n\n if Primitive.to_proto(self.labels):\n request.resource.labels = Primitive.to_proto(self.labels)\n\n if Primitive.to_proto(self.require_approval):\n request.resource.require_approval = Primitive.to_proto(\n self.require_approval\n )\n\n if TargetGke.to_proto(self.gke):\n request.resource.gke.CopyFrom(TargetGke.to_proto(self.gke))\n else:\n request.resource.ClearField(\"gke\")\n if TargetAnthosCluster.to_proto(self.anthos_cluster):\n request.resource.anthos_cluster.CopyFrom(\n TargetAnthosCluster.to_proto(self.anthos_cluster)\n )\n else:\n request.resource.ClearField(\"anthos_cluster\")\n if TargetExecutionConfigsArray.to_proto(self.execution_configs):\n request.resource.execution_configs.extend(\n TargetExecutionConfigsArray.to_proto(self.execution_configs)\n )\n if Primitive.to_proto(self.project):\n request.resource.project = Primitive.to_proto(self.project)\n\n if Primitive.to_proto(self.location):\n request.resource.location = Primitive.to_proto(self.location)\n\n if TargetRun.to_proto(self.run):\n request.resource.run.CopyFrom(TargetRun.to_proto(self.run))\n else:\n request.resource.ClearField(\"run\")\n if TargetMultiTarget.to_proto(self.multi_target):\n request.resource.multi_target.CopyFrom(\n TargetMultiTarget.to_proto(self.multi_target)\n )\n else:\n request.resource.ClearField(\"multi_target\")\n if Primitive.to_proto(self.deploy_parameters):\n request.resource.deploy_parameters = Primitive.to_proto(\n self.deploy_parameters\n )\n\n response = stub.DeleteClouddeployTarget(request)\n\n @classmethod\n def list(self, project, location, service_account_file=\"\"):\n stub = target_pb2_grpc.ClouddeployTargetServiceStub(channel.Channel())\n request = target_pb2.ListClouddeployTargetRequest()\n request.service_account_file = service_account_file\n request.Project = project\n\n request.Location = location\n\n return stub.ListClouddeployTarget(request).items\n\n def to_proto(self):\n resource = target_pb2.ClouddeployTarget()\n if Primitive.to_proto(self.name):\n resource.name = Primitive.to_proto(self.name)\n if Primitive.to_proto(self.description):\n resource.description = Primitive.to_proto(self.description)\n if Primitive.to_proto(self.annotations):\n resource.annotations = Primitive.to_proto(self.annotations)\n if Primitive.to_proto(self.labels):\n resource.labels = Primitive.to_proto(self.labels)\n if Primitive.to_proto(self.require_approval):\n resource.require_approval = Primitive.to_proto(self.require_approval)\n if TargetGke.to_proto(self.gke):\n resource.gke.CopyFrom(TargetGke.to_proto(self.gke))\n else:\n resource.ClearField(\"gke\")\n if TargetAnthosCluster.to_proto(self.anthos_cluster):\n resource.anthos_cluster.CopyFrom(\n TargetAnthosCluster.to_proto(self.anthos_cluster)\n )\n else:\n resource.ClearField(\"anthos_cluster\")\n if TargetExecutionConfigsArray.to_proto(self.execution_configs):\n resource.execution_configs.extend(\n TargetExecutionConfigsArray.to_proto(self.execution_configs)\n )\n if Primitive.to_proto(self.project):\n resource.project = Primitive.to_proto(self.project)\n if Primitive.to_proto(self.location):\n resource.location = Primitive.to_proto(self.location)\n if TargetRun.to_proto(self.run):\n resource.run.CopyFrom(TargetRun.to_proto(self.run))\n else:\n resource.ClearField(\"run\")\n if TargetMultiTarget.to_proto(self.multi_target):\n resource.multi_target.CopyFrom(\n TargetMultiTarget.to_proto(self.multi_target)\n )\n else:\n resource.ClearField(\"multi_target\")\n if Primitive.to_proto(self.deploy_parameters):\n resource.deploy_parameters = Primitive.to_proto(self.deploy_parameters)\n return resource\n\n\nclass TargetGke(object):\n def __init__(self, cluster: str = None, internal_ip: bool = None):\n self.cluster = cluster\n self.internal_ip = internal_ip\n\n @classmethod\n def to_proto(self, resource):\n if not resource:\n return None\n\n res = target_pb2.ClouddeployTargetGke()\n if Primitive.to_proto(resource.cluster):\n res.cluster = Primitive.to_proto(resource.cluster)\n if Primitive.to_proto(resource.internal_ip):\n res.internal_ip = Primitive.to_proto(resource.internal_ip)\n return res\n\n @classmethod\n def from_proto(self, resource):\n if not resource:\n return None\n\n return TargetGke(\n cluster=Primitive.from_proto(resource.cluster),\n internal_ip=Primitive.from_proto(resource.internal_ip),\n )\n\n\nclass TargetGkeArray(object):\n @classmethod\n def to_proto(self, resources):\n if not resources:\n return resources\n return [TargetGke.to_proto(i) for i in resources]\n\n @classmethod\n def from_proto(self, resources):\n return [TargetGke.from_proto(i) for i in resources]\n\n\nclass TargetAnthosCluster(object):\n def __init__(self, membership: str = None):\n self.membership = membership\n\n @classmethod\n def to_proto(self, resource):\n if not resource:\n return None\n\n res = target_pb2.ClouddeployTargetAnthosCluster()\n if Primitive.to_proto(resource.membership):\n res.membership = Primitive.to_proto(resource.membership)\n return res\n\n @classmethod\n def from_proto(self, resource):\n if not resource:\n return None\n\n return TargetAnthosCluster(\n membership=Primitive.from_proto(resource.membership),\n )\n\n\nclass TargetAnthosClusterArray(object):\n @classmethod\n def to_proto(self, resources):\n if not resources:\n return resources\n return [TargetAnthosCluster.to_proto(i) for i in resources]\n\n @classmethod\n def from_proto(self, resources):\n return [TargetAnthosCluster.from_proto(i) for i in resources]\n\n\nclass TargetExecutionConfigs(object):\n def __init__(\n self,\n usages: list = None,\n worker_pool: str = None,\n service_account: str = None,\n artifact_storage: str = None,\n execution_timeout: str = None,\n ):\n self.usages = usages\n self.worker_pool = worker_pool\n self.service_account = service_account\n self.artifact_storage = artifact_storage\n self.execution_timeout = execution_timeout\n\n @classmethod\n def to_proto(self, resource):\n if not resource:\n return None\n\n res = target_pb2.ClouddeployTargetExecutionConfigs()\n if TargetExecutionConfigsUsagesEnumArray.to_proto(resource.usages):\n res.usages.extend(\n TargetExecutionConfigsUsagesEnumArray.to_proto(resource.usages)\n )\n if Primitive.to_proto(resource.worker_pool):\n res.worker_pool = Primitive.to_proto(resource.worker_pool)\n if Primitive.to_proto(resource.service_account):\n res.service_account = Primitive.to_proto(resource.service_account)\n if Primitive.to_proto(resource.artifact_storage):\n res.artifact_storage = Primitive.to_proto(resource.artifact_storage)\n if Primitive.to_proto(resource.execution_timeout):\n res.execution_timeout = Primitive.to_proto(resource.execution_timeout)\n return res\n\n @classmethod\n def from_proto(self, resource):\n if not resource:\n return None\n\n return TargetExecutionConfigs(\n usages=TargetExecutionConfigsUsagesEnumArray.from_proto(resource.usages),\n worker_pool=Primitive.from_proto(resource.worker_pool),\n service_account=Primitive.from_proto(resource.service_account),\n artifact_storage=Primitive.from_proto(resource.artifact_storage),\n execution_timeout=Primitive.from_proto(resource.execution_timeout),\n )\n\n\nclass TargetExecutionConfigsArray(object):\n @classmethod\n def to_proto(self, resources):\n if not resources:\n return resources\n return [TargetExecutionConfigs.to_proto(i) for i in resources]\n\n @classmethod\n def from_proto(self, resources):\n return [TargetExecutionConfigs.from_proto(i) for i in resources]\n\n\nclass TargetRun(object):\n def __init__(self, location: str = None):\n self.location = location\n\n @classmethod\n def to_proto(self, resource):\n if not resource:\n return None\n\n res = target_pb2.ClouddeployTargetRun()\n if Primitive.to_proto(resource.location):\n res.location = Primitive.to_proto(resource.location)\n return res\n\n @classmethod\n def from_proto(self, resource):\n if not resource:\n return None\n\n return TargetRun(\n location=Primitive.from_proto(resource.location),\n )\n\n\nclass TargetRunArray(object):\n @classmethod\n def to_proto(self, resources):\n if not resources:\n return resources\n return [TargetRun.to_proto(i) for i in resources]\n\n @classmethod\n def from_proto(self, resources):\n return [TargetRun.from_proto(i) for i in resources]\n\n\nclass TargetMultiTarget(object):\n def __init__(self, target_ids: list = None):\n self.target_ids = target_ids\n\n @classmethod\n def to_proto(self, resource):\n if not resource:\n return None\n\n res = target_pb2.ClouddeployTargetMultiTarget()\n if Primitive.to_proto(resource.target_ids):\n res.target_ids.extend(Primitive.to_proto(resource.target_ids))\n return res\n\n @classmethod\n def from_proto(self, resource):\n if not resource:\n return None\n\n return TargetMultiTarget(\n target_ids=Primitive.from_proto(resource.target_ids),\n )\n\n\nclass TargetMultiTargetArray(object):\n @classmethod\n def to_proto(self, resources):\n if not resources:\n return resources\n return [TargetMultiTarget.to_proto(i) for i in resources]\n\n @classmethod\n def from_proto(self, resources):\n return [TargetMultiTarget.from_proto(i) for i in resources]\n\n\nclass TargetExecutionConfigsUsagesEnum(object):\n @classmethod\n def to_proto(self, resource):\n if not resource:\n return resource\n return target_pb2.ClouddeployTargetExecutionConfigsUsagesEnum.Value(\n \"ClouddeployTargetExecutionConfigsUsagesEnum%s\" % resource\n )\n\n @classmethod\n def from_proto(self, resource):\n if not resource:\n return resource\n return target_pb2.ClouddeployTargetExecutionConfigsUsagesEnum.Name(resource)[\n len(\"ClouddeployTargetExecutionConfigsUsagesEnum\") :\n ]\n\n\nclass Primitive(object):\n @classmethod\n def to_proto(self, s):\n if not s:\n return \"\"\n return s\n\n @classmethod\n def from_proto(self, s):\n return s\n","sub_path":"python/services/clouddeploy/target.py","file_name":"target.py","file_ext":"py","file_size_in_byte":17759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"475194747","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\nfrom sys import argv\r\nimport re\r\n\"\"\"\r\n\tthis script takes into input an output of local blast\r\n\tand returns two .txt files:\r\n\tone containing the list of contigs with hits (_contighits.txt)\r\n\tthe other (signhits.txt)of this type:\r\n\tcontigs\tsequence\r\n\tlisting all the hits per contigs\r\n python signifblast.py namefile.txt\r\n\"\"\"\r\n\r\n\r\ndef main():\r\n\tfichierblast=argv[1]\r\n\tfichierlist=fichierblast.replace(\".out\",\"_contigshits.txt\")\r\n\tfichierdhit=fichierblast.replace(\".out\",\"_signifhits.txt\")\r\n\tfb=open(fichierblast,'r')\r\n\tfl=open(fichierlist,'w')\r\n\tfh=open(fichierdhit,'w')\r\n\t\r\n\tcontig=\"\"\r\n\t\r\n\tligne=fb.readline()\r\n\twhile(ligne):\r\n\t\tif(\"Query\" in ligne):\r\n\t\t\t#the name of the contig is on this line\r\n\t\t\tcontig=ligne.replace(\"Query=\",\"\")\r\n\t\tif(\"significant\" in ligne):\r\n\t\t\tfl.write(\"%s\"%(contig))\r\n\t\t\tfh.write(\"\\n%s\"%(contig))\r\n\t\tif(\">\" in ligne[0]):\r\n\t\t\tfh.write(ligne)\r\n\t\t\tligne=fb.readline()\r\n\t\t\tif(\"Length\" not in ligne):\r\n\t\t\t\tfh.write(ligne)\r\n\t\tligne=fb.readline()\r\n\tfb.close()\r\n\tfl.close()\r\n\tfh.close()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"signifblast.py","file_name":"signifblast.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"377355153","text":"import datetime\nimport time\nimport numpy as np\nimport pandas as pd\nimport csv\nfrom openpyxl import load_workbook\nfrom openpyxl import Workbook\nimport math\nfrom Zenith_angle_module import Zenith_angle\nfrom check_stab import check_stab\n\n\nstart = '2019-12-16-00:00'\nend = '2019-12-17-23:00'\nfilename = 'g19_1081216-1081218_min.xlsx'\nobs = pd.read_excel(filename)\nston = 'g19'\n\n# lat = 23.10729 # 南科實中\n# lat = 23.106341 # 29\n# lat = 23.09004 # 13\nlat = 23.122679 # 19\n\n# # 雲量 2019-12/11 12/12\n# cloud = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n# 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n# 雲量 2019-12/16 12/17\ncloud = [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]\n\n\ntime_key = {}\ntitle = ['時間', '年', '月', '日', '時', 'WS', 'WD', 'AT', '穩定度','天頂角']\n\ntime_key['titie'] = title\ndatestart = datetime.datetime.strptime(start, '%Y-%m-%d-%H:%M')\ndateend = datetime.datetime.strptime(end, '%Y-%m-%d-%H:%M')\n\ndata = {\n 'WS': obs['WS'],\n 'WD': obs['WD'],\n 'AT': obs['AT'],\n 'times': []\n}\n\nfor i in range(0, len(obs['時間'])):\n data['times'].append(datetime.datetime.strptime(obs['日期'][i].strftime(\n '%Y-%m-%d')+' '+obs['時間'][i].strftime('%H:%M:%S'), '%Y-%m-%d %H:%M:%S'))\ncount = 0\nwhile(datestart <= dateend):\n datestart_hr = datestart-datetime.timedelta(minutes=59)\n i = 0\n j = 0\n u_tmp = 0\n v_tmp = 0\n ws_tmp = 0\n wd_tmp = 0\n at_tmp = 0\n\n\n while(datestart_hr <= datestart):\n if(datestart_hr in data['times']):\n index = data['times'].index(datestart_hr)\n if obs['WS'][index] != 9999 and obs['WD'][index] != 9999 and obs['WS'][index] != -999 and obs['WD'][index] != -999:\n i += 1\n u_tmp += obs['WS'][index] * \\\n math.cos((270 - obs['WD'][index]) * math.pi / 180)\n v_tmp += obs['WS'][index] * \\\n math.sin((270 - obs['WD'][index]) * math.pi / 180)\n if obs['AT'][index] != 9999 and obs['AT'][index] != -999:\n j += 1\n at_tmp += obs['AT'][index]\n datestart_hr += datetime.timedelta(minutes=1)\n\n if(i != 0):\n u_tmp = u_tmp/i\n v_tmp = v_tmp/i\n ws_tmp = math.sqrt(math.pow(u_tmp, 2)+math.pow(v_tmp, 2))\n\n if u_tmp > 0 and v_tmp > 0:\n wd_tmp = 270 - math.atan(v_tmp / u_tmp) * 180 / math.pi\n wd_tmp += 180\n elif u_tmp < 0 and v_tmp > 0:\n wd_tmp = 90 - math.atan(v_tmp / u_tmp) * 180 / math.pi\n wd_tmp += 180\n elif u_tmp < 0 and v_tmp < 0:\n wd_tmp = 90 - math.atan(v_tmp / u_tmp) * 180 / math.pi\n wd_tmp += 180\n elif u_tmp > 0 and v_tmp < 0:\n wd_tmp = 270 - math.atan(v_tmp / u_tmp) * 180 / math.pi\n wd_tmp += 180\n elif u_tmp == 0 and v_tmp > 0:\n wd_tmp = 180\n wd_tmp += 180\n elif u_tmp == 0 and v_tmp < 0:\n wd_tmp = 0\n wd_tmp += 180\n elif u_tmp > 0 and v_tmp == 0:\n wd_tmp = 270\n wd_tmp += 180\n elif u_tmp < 0 and v_tmp == 0:\n wd_tmp = 90\n wd_tmp += 180\n elif u_tmp == 0 and v_tmp == 0:\n wd_tmp = 0.0\n elif(i == 0):\n ws_tmp = 0.0\n wd_tmp = 0.0\n\n if j != 0:\n at_tmp = at_tmp/j\n elif j == 0:\n at_tmp = 0.0\n\n # if ws_tmp <= 0.2:\n # wd_tmp = 0.0\n # ws_tmp = 0.0\n\n wd_tmp = wd_tmp if wd_tmp <= 360 else wd_tmp-360\n\n y = int(datestart.strftime('%Y')[2:4])\n m = int(datestart.strftime('%m'))\n d = int(datestart.strftime('%d'))\n h = int(datestart.strftime('%H'))\n\n stab_tmp=check_stab(Zenith_angle(day=datestart, lat=lat), cloud[count], ws_tmp)\n time_key[datestart] = [y, m, d, h, round(ws_tmp, 4), round(\n wd_tmp, 4), round(at_tmp, 1), stab_tmp, Zenith_angle(day=datestart, lat=lat)]\n count += 1\n datestart += datetime.timedelta(minutes=60)\n\n\nwb = Workbook()\nws = wb.active\nws.title = ston\nws.append(title)\ni = 0\nfor key, value in time_key.items():\n if(i == 0):\n i += 1\n continue\n i += 1\n ws.append([key]+value)\n# 儲存成 create_sample.xlsx 檔案\nwb.save(ston+'.xlsx')\n\n\n ","sub_path":"calmet/20191216案例小時風場平均/南科測站/obs_hr_avg.py","file_name":"obs_hr_avg.py","file_ext":"py","file_size_in_byte":4373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"226899533","text":"def find_outputs(lines):\n\toutputs=[]\n\tcount=0\n\tfor idx,l in enumerate(lines):\n\t\tif 'Pin' in l:\n\t\t\tcount=count+1\n\t\t\tif(count>2):\t\n\t\t\t\tif 'output' in lines[idx+2]:\n\t\t\t\t\toutputs.append(l)\n\ttotal_outputs=len(outputs)\n\toutputs_dict={}\n\toutputs_pos_dict={}\n\n\tcount=1\n\tfor w in outputs:\n\t\tarr=w.split()\n\t\tx1=arr[2]\n\t\tlx1=len(x1)\n\t\tx1=x1[5:lx1-1]\n\t\toutputs_dict[x1]='op'+str(count)\n\t\toutputs_pos_dict['op'+str(count)]=x1\n\t\tcount=count+1\n\tret={}\n\tret['a']=outputs_dict\n\tret['b']=outputs_pos_dict\n\n\treturn ret\n","sub_path":"Version_1.3/find_outputs_class.py","file_name":"find_outputs_class.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"437249857","text":"import imaplib\nfrom time import sleep\nfrom config import EMAIL, FROM_PWD, SMTP_SERVER\n\n\ndef get_link(subject):\n sleep(10)\n mail = imaplib.IMAP4_SSL(SMTP_SERVER)\n mail.login(EMAIL, FROM_PWD)\n mail.select('inbox')\n\n typ, data = mail.search(None, '(SUBJECT \"%s\")' % subject)\n mail_ids = data[0].split()[-1]\n # print(mail_ids)\n\n typ, data = mail.fetch(mail_ids, '(RFC822)')\n\n str_link = data[0][1].decode(\"utf-8\")\n link = str_link[str_link.find('link:') + 5: str_link.find('If you')]\n print(link)\n return link\n","sub_path":"utilities/get_email.py","file_name":"get_email.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"525961396","text":"#\n# @lc app=leetcode.cn id=19 lang=python3\n#\n# [19] 删除链表的倒数第 N 个结点\n#\n\n# @lc code=start\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n cur = slow = fast = ListNode(next=head)\n num = 0\n while(fast.next!=None):\n fast = fast.next\n num = num + 1\n if(num >= n + 1):\n slow = slow.next \n slow.next = slow.next.next \n return cur.next \n# @lc code=end\n\n","sub_path":"19.删除链表的倒数第-n-个结点.py","file_name":"19.删除链表的倒数第-n-个结点.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"238839962","text":"#!/usr/bin/env python3\nimport networkx as nx\nimport numpy as np\nfrom pgmpy.extern.six.moves import filter, range\nfrom collections import defaultdict\n\nfrom pgmpy.extern.six import string_types\nfrom pgmpy.utils import StateNameDecorator, StateNameInit\nfrom pgmpy.inference.EliminationOrder import WeightedMinFill\nfrom pgmpy.factors.discrete import AlgebraicDecisionDiagram\n\nimport logging\n\nclass ACInference():\n\n @StateNameInit()\n def __init__(self, model, add_factors, global_node_id_gen):\n self.model = model\n self.variables = model.nodes()\n\n self.cardinality = {}\n self.factors = defaultdict(list)\n\n self.node_id_gen = global_node_id_gen\n\n for node in model.nodes():\n add_factor = add_factors[node]\n cpd = model.get_cpds(node)\n self.cardinality[node] = cpd.variable_card\n for var in cpd.variables:\n self.factors[var] += add_factor\n\n\n @StateNameDecorator(argument='evidence', return_val=None)\n def _variable_elimination(self, ac, operation, evidence=None, elimination_order=None):\n\n variables = []\n\n eliminated_variables = set()\n working_factors = {node: {factor for factor in self.factors[node]}\n for node in self.factors}\n\n #TODO\n # Dealing with evidence. Reducing factors over it before VE is run.\n # if evidence:\n # for evidence_var in evidence:\n # for factor in working_factors[evidence_var]:\n # factor_reduced = factor.reduce([(evidence_var, evidence[evidence_var])], inplace=False)\n # for var in factor_reduced.scope():\n # working_factors[var].remove(factor)\n # working_factors[var].add(factor_reduced)\n # del working_factors[evidence_var]\n\n if not elimination_order:\n vars_to_eliminate = list(set(self.variables) -\n set(variables) -\n set(evidence.keys() if evidence else []))\n elimination_order = WeightedMinFill(self.model).get_elimination_order(vars_to_eliminate)\n elif any(var in elimination_order for var in\n set(variables).union(set(evidence.keys() if evidence else []))):\n raise ValueError(\"Elimination order contains variables which are in\"\n \" variables or evidence args\")\n logging.info(\"Running VE with query variables: {}, evidence: {}, and elimination order: {}\".format(str(variables), str(evidence), str(elimination_order)))\n for var in elimination_order:\n logging.info(\"VE is eliminating variable {}\".format(var))\n # Removing all the factors containing the variables which are\n # eliminated (as all the factors should be considered only once)\n factors = []\n for factor in working_factors[var]:\n if not set(factor.variables).intersection(eliminated_variables):\n factors.append(factor)\n logging.info(\"Product of tables involving variable {}\".format(var))\n phi = ACInference._adds_product(factors, self.node_id_gen, ac)\n logging.info(\"Marginalize out variable {}\".format(var))\n phi = phi.marginalize([var], self.node_id_gen, ac, inplace=False)\n del working_factors[var]\n for variable in phi.variables:\n working_factors[variable].add(phi)\n eliminated_variables.add(var)\n\n final_distribution = set()\n for node in working_factors:\n factors = working_factors[node]\n for factor in factors:\n if not set(factor.variables).intersection(eliminated_variables):\n final_distribution.add(factor)\n\n if len(final_distribution) != 0:\n raise ValueError(\"No factor should be left after marginalizing all variables\")\n\n def compile(self, ac, evidence=None, elimination_order=None):\n return self._variable_elimination(ac, 'marginalize', evidence=evidence, elimination_order=elimination_order)\n\n\n # def propagate_up(self, ac, indicator_values={}, sink_values={}):\n\n # vr = {}\n # for node in ac.nodes():\n # if node \n\n\n @staticmethod\n def _adds_product(adds, global_node_id_gen, ac):\n phi = None\n is_first = True\n for factor in adds:\n if is_first:\n phi = factor\n is_first = False\n else:\n phi = phi.product(factor, global_node_id_gen, ac, inplace=False)\n return phi\n","sub_path":"pgmpy/inference/ACInference.py","file_name":"ACInference.py","file_ext":"py","file_size_in_byte":4669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"143198810","text":"#!/usr/bin/env python3\n\n\"\"\"\nWrite the data which in the RAM into the Disk!\nDo not use 'endrc','enddb'and'=>'\n\"\"\"\n\nDBFileName = 'DBFileName'\nENDDB = 'enddb'\nENDRC = 'endrc'\nRCDATA = '=>'\n\ndef StoreData(db,DBFileName=DBFileName):\n \"record the DB data into the disk file\"\n dbfile=open(DBFileName,'w')\n def _PrintStr(string):\n print(string,file=dbfile)\n for key in db:\n _PrintStr(key)\n for (name,value) in db[key].items():\n _PrintStr(name+RCDATA+repr(value))\n _PrintStr(ENDRC)\n _PrintStr(ENDDB)\n dbfile.close()\n\n \n\nif __name__=='__main__':\n from initdata import db\n StoreData(db)\n\n\n\n\n","sub_path":"make_db_file.py","file_name":"make_db_file.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"513576399","text":"import math\n\n\nclass Solution:\n def maxPoints(self, points) -> int:\n def caculateDirect(p1, p2):\n x, y = p2[0] - p1[0], p2[1] - p1[1]\n g = math.gcd(x, y)\n return x // g, y // g\n\n a = sorted(points)\n n, res = len(a), 1\n for i in range(n - 1):\n d = {}\n for j in range(i + 1, n):\n v = caculateDirect(a[i], a[j])\n d[v] = d.get(v, 0) + 1\n res = max(res, max(d.values()) + 1)\n return res\n\ns = Solution()\nprint(s.maxPoints([[1, 1], [3, 2], [5, 3], [4, 1], [2, 3], [1, 4]]))\n","sub_path":"leetcode/2021/max-points-on-a-line.py","file_name":"max-points-on-a-line.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"237019250","text":"import random\n\nnumbers = [\"f\", \"l\", \"z\", \"a\", 2, 4, 7, 40, 8, 9, 3, 1, 6, 11]\nmy_ticket = (\"l\", \"a\", 4, 11)\n\nwin_count = 0\nwhile True:\n # take 4 random number to compare with ticket\n random_numbers = [random.choice(numbers) for i in range(4)]\n\n # check if random number is equal to my ticket\n if tuple(random_numbers) == my_ticket:\n break\n win_count += 1\n\nprint(f\"It took {win_count:,} times to give you a winning ticket!\")\n","sub_path":"Python/python-crash-course/try-it-yourself/chapter9/lottery_analysis.py","file_name":"lottery_analysis.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"481644917","text":"import wx\n\n\ndef wx_ui_run(config, controller):\n app = MyApp()\n main_frame = WxCurses(app, config, controller)\n main_frame.Show()\n app.MainLoop()\n return app.get_result()\n\n\nclass MyApp(wx.App):\n\n def __init__(self):\n wx.App.__init__(self, False)\n self.set_result(None)\n\n def set_result(self, result):\n self._result = result\n\n def get_result(self):\n return self._result\n\n\nclass WxCurses(wx.Frame):\n\n def __init__(self, app, config, controller):\n wx.Frame.__init__(self, None, size=config.get_gui_size())\n self._screen = WxScreen(self, app, config, controller)\n\n\nclass WxScreen(wx.Panel):\n\n def __init__(self, parent, app, config, controller):\n wx.Panel.__init__(self, parent, style=wx.NO_BORDER | wx.WANTS_CHARS)\n self._app = app\n self._config = config\n self._controller = controller\n self._surface_bitmap = None\n self._commands = []\n self._init_fonts()\n self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)\n self.Bind(wx.EVT_CHAR, self._on_key_down)\n self.Bind(wx.EVT_PAINT, self._on_paint)\n wx.CallAfter(self._after_init)\n\n def _after_init(self):\n self._controller.setup(self)\n self._controller.render(self)\n\n def getmaxyx(self):\n ww, wh = self.GetSizeTuple()\n max_y = int(wh) / int(self._fh)\n max_x = int(ww) / int(self._fw)\n return (max_y, max_x)\n\n def erase(self):\n self._commands = []\n\n def addstr(self, y, x, text, style):\n self._commands.append((y, x, text, style))\n\n def refresh(self):\n width, height = self.GetSizeTuple()\n self._surface_bitmap = wx.EmptyBitmap(width, height)\n memdc = wx.MemoryDC()\n memdc.SelectObject(self._surface_bitmap)\n memdc.BeginDrawing()\n memdc.SetBackground(wx.Brush(\n self._config.get_rgb(\"BACKGROUND\"), wx.SOLID\n ))\n memdc.SetBackgroundMode(wx.PENSTYLE_SOLID)\n memdc.Clear()\n for (y, x, text, style) in self._commands:\n if style == \"highlight\":\n memdc.SetFont(self._base_font_bold)\n fg = self._config.get_rgb(self._config.get_highlight_fg())\n bg = self._config.get_rgb(self._config.get_highlight_bg())\n elif style == \"select\":\n memdc.SetFont(self._base_font_bold)\n fg = self._config.get_rgb(self._config.get_selection_fg())\n bg = self._config.get_rgb(self._config.get_selection_bg())\n elif style == \"status\":\n memdc.SetFont(self._base_font_bold)\n fg = self._config.get_rgb(\"BACKGROUND\")\n bg = self._config.get_rgb(\"FOREGROUND\")\n else:\n memdc.SetFont(self._base_font)\n fg = self._config.get_rgb(\"FOREGROUND\")\n bg = self._config.get_rgb(\"BACKGROUND\")\n memdc.SetTextBackground(bg)\n memdc.SetTextForeground(fg)\n memdc.DrawText(text, x*self._fw, y*self._fh)\n memdc.EndDrawing()\n del memdc\n self.Refresh()\n self.Update()\n\n def _init_fonts(self):\n self._base_font = wx.Font(\n self._config.get_gui_font_size(),\n wx.FONTFAMILY_TELETYPE,\n wx.FONTSTYLE_NORMAL,\n wx.FONTWEIGHT_NORMAL\n )\n self._base_font_bold = self._base_font.Bold()\n self._find_text_size()\n\n def _find_text_size(self):\n bitmap = wx.EmptyBitmap(100, 100)\n memdc = wx.MemoryDC()\n memdc.SetFont(self._base_font)\n memdc.SelectObject(bitmap)\n self._fw, self._fh = memdc.GetTextExtent(\".\")\n\n def _on_key_down(self, evt):\n result = self._controller.process_input(evt.GetUnicodeKey())\n if result:\n self._app.set_result(result)\n self.GetParent().Close()\n self._controller.render(self)\n\n def _on_paint(self, event):\n dc = wx.AutoBufferedPaintDC(self)\n dc.BeginDrawing()\n if self._surface_bitmap:\n dc.DrawBitmap(self._surface_bitmap, 0, 0, True)\n dc.EndDrawing()\n","sub_path":"select/selectlib/ui_wx.py","file_name":"ui_wx.py","file_ext":"py","file_size_in_byte":4122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"441396418","text":"# -*- coding: utf-8 -*-\n\"\"\"\n static_file\n\n Static File\n\n\"\"\"\nfrom boto.s3 import connection\nfrom boto.s3 import key\nfrom boto import exception\nimport base64\nimport json\n\nfrom trytond.config import config\nfrom trytond.model import fields\nfrom trytond.pyson import Eval, Bool\nfrom trytond.transaction import Transaction\nfrom trytond.wizard import Wizard, StateAction\nfrom trytond.pool import Pool, PoolMeta\nfrom trytond.model import ModelView\n\n__all__ = ['NereidStaticFolder', 'NereidStaticFile', 'UploadWizard']\n__metaclass__ = PoolMeta\n\n\nclass NereidStaticFolder:\n __name__ = \"nereid.static.folder\"\n\n is_private = fields.Boolean(\n \"Is Private?\", states={\n 'invisible': Bool(Eval('type') != 's3'),\n 'readonly': Bool(Eval('files')),\n }, depends=['type', 'files']\n )\n\n s3_allow_large_uploads = fields.Boolean(\n 'Allow Large file uploads?',\n states={\n 'invisible': Bool(Eval('type') != 's3'),\n }, depends=['type']\n )\n s3_upload_form_ttl = fields.Integer(\n 'Upload form validity',\n states={\n 'invisible': Bool(Eval('type') != 's3'),\n }, depends=['type']\n )\n\n @classmethod\n def __setup__(cls):\n super(NereidStaticFolder, cls).__setup__()\n\n s3 = ('s3', 'S3')\n if s3 not in cls.type.selection:\n cls.type.selection.append(s3)\n\n cls._error_messages.update({\n \"folder_not_for_large_uploads\": (\n \"This file's folder does not allow large file uploads\"\n ),\n 'invalid_name': (\n \"%s(OR) \\n(3) Folder name is _private\" % (\n cls._error_messages['invalid_name'],\n )\n )\n })\n\n def check_name(self):\n \"Check if folder name is _private\"\n super(NereidStaticFolder, self).check_name()\n\n if self.name == '_private':\n self.raise_user_error('invalid_name')\n\n def get_s3_connection(self):\n \"\"\"\n Returns an active S3 connection object\n \"\"\"\n return connection.S3Connection(\n config.get('nereid_s3', 'access_key'),\n config.get('nereid_s3', 'secret_key')\n )\n\n def get_bucket(self):\n '''\n Return an S3 bucket for the static file\n '''\n s3_conn = self.get_s3_connection()\n return s3_conn.get_bucket(\n config.get('nereid_s3', 'bucket'),\n )\n\n @staticmethod\n def default_s3_upload_form_ttl():\n return 600\n\n\nclass NereidStaticFile:\n __name__ = \"nereid.static.file\"\n\n s3_key = fields.Function(\n fields.Char(\"S3 key\"), getter=\"get_s3_key\"\n )\n is_large_file = fields.Boolean('Is Large File')\n\n @classmethod\n def view_attributes(cls):\n return super(NereidStaticFile, cls).view_attributes() + [\n ('//group[@id=\"image_preview\"]', 'states', {\n 'invisible': Bool(Eval('is_large_file'))\n }), ('//label[@id=\"preview\"]', 'states', {\n 'invisible': ~Bool(Eval('is_large_file'))\n })]\n\n def get_post_form_args(self):\n \"\"\"\n Returns the POST form arguments for the specific static file. It makes a\n connection to S3 via Boto and returns a dictionary, which can then be\n processed on the client side.\n \"\"\"\n if self.folder.type != 's3':\n self.folder.raise_user_error('not_s3_bucket')\n\n if not self.folder.s3_allow_large_uploads:\n self.folder.raise_user_error('folder_not_for_large_uploads')\n\n conn = self.folder.get_s3_connection()\n res = conn.build_post_form_args(\n config.get('nereid_s3', 'bucket'),\n self.get_s3_key('s3_key'),\n http_method='https',\n expires_in=self.folder.s3_upload_form_ttl,\n )\n return res\n\n def get_s3_key(self, name):\n \"\"\"\n Returns s3 key for static file\n \"\"\"\n make_key_from = [self.folder.name, self.name]\n\n if self.folder.is_private:\n make_key_from.insert(0, '_private')\n\n return '/'.join(make_key_from)\n\n def get_url(self, name):\n \"\"\"\n Return the URL for the given static file\n\n :param name: Field name\n \"\"\"\n if self.folder.type != 's3':\n return super(NereidStaticFile, self).get_url(name)\n\n cloudfront = config.get('nereid_s3', 'cloudfront')\n if cloudfront:\n return '/'.join([cloudfront, self.s3_key])\n\n return \"https://s3.amazonaws.com/%s/%s\" % (\n config.get('nereid_s3', 'bucket'), self.s3_key\n )\n\n def _set_file_binary(self, value):\n \"\"\"\n Stores the file to amazon s3\n\n :param static_file: Browse record of the static file\n :param value: The value to set\n \"\"\"\n if not value:\n return\n if self.folder.type != \"s3\":\n return super(NereidStaticFile, self)._set_file_binary(value)\n\n if self.is_large_file:\n return\n bucket = self.folder.get_bucket()\n s3key = key.Key(bucket)\n s3key.key = self.s3_key\n return s3key.set_contents_from_string(bytes(value))\n\n def get_file_binary(self, name):\n '''\n Getter for the binary_file field. This fetches the file from the\n Amazon s3\n\n :param name: Field name\n :return: File buffer\n '''\n if self.folder.type == \"s3\":\n bucket = self.folder.get_bucket()\n s3key = bucket.lookup(self.s3_key)\n if s3key is None:\n self.raise_user_warning(\n 's3_file_missing',\n 'file_empty_s3'\n )\n return\n if s3key.size > (1000000 * 10): # 10 MB\n # TODO: make the size configurable\n return\n try:\n return fields.Binary.cast(s3key.get_contents_as_string())\n except exception.S3ResponseError as error:\n if error.status == 404:\n with Transaction().new_cursor(readonly=False) as txn:\n self.raise_user_warning(\n 's3_file_missing',\n 'file_empty_s3'\n )\n # Commit cursor to clear DB records\n txn.cursor.commit()\n return\n raise\n return super(NereidStaticFile, self).get_file_binary(name)\n\n def get_file_path(self, name):\n \"\"\"\n Returns path for given static file\n\n :param static_file: Browse record of the static file\n \"\"\"\n if self.folder.type != \"s3\":\n return super(NereidStaticFile, self).get_file_path(name)\n\n cloudfront = config.get('nereid_s3', 'cloudfront')\n if cloudfront:\n return '/'.join([cloudfront, self.s3_key])\n\n return \"https://s3.amazonaws.com/%s/%s\" % (\n config.get('nereid_s3', 'bucket'), self.s3_key\n )\n\n @classmethod\n @ModelView.button_action('nereid_s3.wizard_upload_large_files')\n def upload_large_file(cls, records):\n pass\n\n @classmethod\n def __setup__(cls):\n super(NereidStaticFile, cls).__setup__()\n\n cls._error_messages.update({\n \"file_empty_s3\": \"The file's contents are empty on S3\",\n })\n cls._buttons.update({\n 'upload_large_file': {\n 'invisible': ~Bool(Eval('is_large_file')),\n },\n })\n\n\nclass UploadWizard(Wizard):\n __name__ = 'nereid.static.file.upload_wizard'\n\n start = StateAction('nereid_s3.url_upload')\n\n # XXX: Perhaps remove hardcoding in future\n base_url = 'https://fulfilio.github.io/s3uploader/v1/upload.html'\n\n def do_start(self, action):\n \"\"\"\n This method overrides the action url given in XML and inserts the url\n in the action object. It then proceeds to return the action.\n \"\"\"\n StaticFile = Pool().get('nereid.static.file')\n\n static_file = StaticFile(Transaction().context.get('active_id'))\n static_file.is_large_file = True\n static_file.save()\n\n post_args = static_file.get_post_form_args()\n\n action['url'] = self.base_url + '?data=' + \\\n base64.b64encode(json.dumps(post_args))\n\n return action, {}\n","sub_path":"static_file.py","file_name":"static_file.py","file_ext":"py","file_size_in_byte":8354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"434855640","text":"from celery.schedules import crontab\n\n\nbroker_url = 'amqp://localhost'\nbeat_schedule = {\n 'update_date_person_report': {\n 'task': 'apps.regulations.tasks.update_attendance_report',\n 'schedule': crontab(minute=0, hour=2),\n },\n}\n\ntask_always_eager = True\n","sub_path":"config/celeryconfig.py","file_name":"celeryconfig.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"96565808","text":"# Data directory\nvtk_directory = 'solution/'\n\n# Results directory\nresults_directory = 'results/'\n\n# Type of data to import (options: 'vtk', 'unfiltered', 'filtered', 'interpolated')\ndata_import = 'interpolated'\n\n# Flag indicating whether (yes) or not (no) to make plots\nplot_results = 'yes'\n\n# Define resolution of grid (in meters) for data interpolation\ngres = 2.e3\n\n# Geographic boundaries for data extraction\nxmin = 100.e3; xmax = 400.e3\nymin = 0.e3; ymax = 2.e3\nzmin = 300.e3; zmax = 480.e3\n\n# Group coordinate min/max values\ncoord_min_max = [xmin, xmax, ymin, ymax, zmin, zmax]\n\n# Generate array with time steps\nfirst_time_step = 20\nlast_time_step = 20\n\ntime_step_interval = 1\n","sub_path":"input.py","file_name":"input.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"283021423","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom preprocessing import Preprocessing\nimport torch.utils.data\nimport os\nimport torchvision.models as models\nfrom torchsummary import summary\nfrom torch.utils.data.sampler import WeightedRandomSampler\nfrom torchvision import transforms\n\n\n\n\ndef train(model, device, train_loader, optimizer, epoch):\n model.train()\n for batch_idx, (x, y) in enumerate(train_loader):\n x, y = x.to(device), y.to(device)\n optimizer.zero_grad()\n x = x.float()\n y = y.long()\n output = model(x)\n loss = F.cross_entropy(output, y)\n loss.backward()\n optimizer.step()\n if batch_idx % epoch == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n batch_idx, batch_idx * len(x), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n\ndef train_incption(model, device, train_loader, optimizer, epoch):\n model.train()\n for batch_idx, (x, y) in enumerate(train_loader):\n x, y = x.to(device), y.to(device)\n optimizer.zero_grad()\n x = x.float()\n y = y.long()\n output = model(x)\n loss = F.cross_entropy(output, y)\n loss.backward()\n optimizer.step()\n if batch_idx % epoch == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n batch_idx, batch_idx * len(x), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n\ndef test(model, device, test_loader):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for x, y in test_loader:\n x, y = x.to(device), y.to(device)\n x = x.float()\n y = y.long()\n output = model(x)\n test_loss += F.cross_entropy(output, y, reduction='sum').item()\n pred = output.max(1, keepdim=True)[1]\n correct += pred.eq(y.view_as(pred)).sum().item()\n test_loss /= len(test_loader.dataset)\n print('\\nDevelopment Set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n\ndef predict(model, device, inputs):\n model.eval()\n pred_list = []\n with torch.no_grad():\n for input in inputs:\n #input = input[0]\n x = input.to(device).view(1, -1, 224, 224)\n x = x.float()\n output = model(x)\n pred = output.max(1, keepdim=True)[1]\n pred = pred.cpu()\n preds = pred.numpy()\n for pred in preds:\n pred_list.append(pred[0])\n return pred_list\n\ndef predict_inception(model, device, inputs):\n model.eval()\n pred_list = []\n with torch.no_grad():\n for input in inputs:\n #input = input[0]\n x = input.to(device).view(1, -1, 224, 224)\n x = x.float()\n output = model(x)\n pred = output.max(1, keepdim=True)[1]\n pred = pred.cpu()\n preds = pred.numpy()\n for pred in preds:\n pred_list.append(pred[0])\n return pred_list\n\n\nif __name__ == '__main__':\n #os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n print(torch.cuda.get_device_name(0))\n use_cuda = torch.cuda.is_available()\n torch.cuda.set_device(0)\n print(use_cuda)\n device = 'cuda'\n #model = models.vgg16(pretrained=True)\n model = models.densenet169(pretrained=True)\n for param in model.parameters():\n param.requires_grad = False\n #model.features[0] = torch.nn.Conv2d(4, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n # model.classifier[0] = torch.nn.Linear(in_features=25088, out_features=2048, bias=True)\n # model.classifier[3] = torch.nn.Linear(in_features=2048, out_features=512, bias=True)\n # model.classifier[6] = torch.nn.Linear(in_features=512, out_features=12, bias=True)\n # model.classifier[2] = torch.nn.Dropout(0.1)\n #model.features[0] = torch.nn.Conv2d(4, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)\n model.classifier = torch.nn.Linear(in_features=1664, out_features=12, bias=True)\n #model.fc = torch.nn.Linear(in_features=1664, out_features=12, bias=True)\n print(model)\n #sample\n # weights = [263, 390, 287, 611, 221, 475, 654, 221, 516, 231, 496, 385]\n # sum = 0\n # for weight in weights:\n # weight = 1 / weight\n # sum += weight\n # for weight in weights:\n # weight = weight / sum\n #\n # weights = torch.tensor(weights, dtype=torch.float64)\n # sampler = WeightedRandomSampler(weights,\n # num_samples=4750,\n # replacement=True)\n\n preprocessing = Preprocessing()\n transform2 = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))\n ]\n )\n data = preprocessing.read_image_simple(transform=transform2, size=224)\n #data['image'] = torch.from_numpy(data['image'])\n #data['label'] = torch.from_numpy(data['label'])\n train_set = torch.utils.data.TensorDataset(data['image'],data['label'])\n indices = np.random.randint(low=0,high=len(train_set)-1,size=len(train_set))\n test_sequence = torch.from_numpy(indices)\n test_set = torch.utils.data.Subset(train_set, test_sequence[0:400])\n train_set_split = torch.utils.data.Subset(train_set, test_sequence[400:])\n #train_loader = torch.utils.data.DataLoader(dataset=train_set_split, batch_size=16, shuffle=True, num_workers=0)\n #train_loader = torch.utils.data.DataLoader(dataset=train_set, batch_size=16, num_workers=0, sampler=sampler)\n train_loader = torch.utils.data.DataLoader(dataset=train_set, batch_size=16, num_workers=0, shuffle=True)\n test_loader = torch.utils.data.DataLoader(dataset=test_set, batch_size=16)\n print('Total length: ', len(train_set))\n print('train_length:',len(train_set_split))\n print('test_length:',len(test_set))\n\n model.to(device)\n summary(model,(3,224,224))\n\n try:\n model.load_state_dict(torch.load('./dense169_2.pth'))\n except FileNotFoundError:\n print('Initialization')\n optimizer = optim.Adam(model.parameters(), lr=0.001, weight_decay=0.000001)\n for epoch in range(5):\n train_incption(model, device, train_loader, optimizer, epoch=10)\n test(model, device, test_loader)\n torch.save(model.state_dict(), './dense169_2.pth')\n\n for param in model.parameters():\n param.requires_grad = True\n for epoch in range(5):\n train_incption(model, device, train_loader, optimizer, epoch=10)\n test(model, device, test_loader)\n torch.save(model.state_dict(), './dense169_2.pth')\n optimizer = optim.Adam(model.parameters(), lr=0.0001, weight_decay=0.00001)\n\n for epoch in range(10):\n train_incption(model, device, train_loader, optimizer, epoch=10)\n test(model, device, test_loader)\n torch.save(model.state_dict(), './dense169_2.pth')\n\n optimizer = optim.Adam(model.parameters(), lr=0.000001, weight_decay=0.00001)\n\n for epoch in range(10):\n train_incption(model, device, train_loader, optimizer, epoch=10)\n test(model, device, test_loader)\n torch.save(model.state_dict(), './dense169_2.pth')\n\n INV_CLASS = {\n 0: 'Black-grass',\n 1: 'Charlock',\n 2: 'Cleavers',\n 3: 'Common Chickweed',\n 4: 'Common wheat',\n 5: 'Fat Hen',\n 6: 'Loose Silky-bent',\n 7: 'Maize',\n 8: 'Scentless Mayweed',\n 9: 'Shepherds Purse',\n 10: 'Small-flowered Cranesbill',\n 11: 'Sugar beet'\n }\n\n preprocessing = Preprocessing()\n #model = CNN_NET(4, 12).to('cuda')\n predict_data = preprocessing.test_data_read_simple2(transform=transform2, size=224)\n #predict_input = torch.from_numpy(predict_data['image'])\n predict_input = predict_data['image']\n model.load_state_dict(torch.load('./dense169_2.pth'))\n prediction = predict(model, 'cuda', predict_input)\n #prediction = prediction.cpu()\n #prediction = list(prediction.numpy())\n predict_data['label'] = prediction\n\n\n with open('submission.csv','w',encoding='utf-8') as f:\n f.write('file,species'+'\\n')\n for i in range(len(predict_data['id'])):\n f.write(predict_data['id'][i] + ',' + INV_CLASS[prediction[i]] + '\\n')","sub_path":"model/DenseNet2.py","file_name":"DenseNet2.py","file_ext":"py","file_size_in_byte":8511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"63055871","text":"#This script has functions needed to make a Cumulative Distribution Plot from\n#Different variables output in PhaseIITreeMaker root file.\n\nimport glob\n\nimport sys\nimport uproot\nimport lib.ROOTProcessor as rp\nimport lib.EventSelection as es\nimport lib.ProfileLikelihoodBuilder as plb\nimport lib.AmBePlots as abp\nimport lib.BeamPlots as bp\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport scipy.optimize as scp\nimport numpy as np\nimport scipy.misc as scm\nfrom pylab import figure, axes, pie, title, show\n\nplt.rc('font', family='Times', size=12)\nimport pylab\npylab.rcParams['figure.figsize'] = 10, 7.6\n\n\nSIGNAL_DIR = \"../Data/V3_5PE100ns/Pos0Data/\"\nBKG_DIR = \"../Data/V3_5PE100ns/BkgPos0Data/\"\n\n#PEPERMEV = 12.\n#expoPFlat= lambda x,C1,tau,mu,B: C1*np.exp(-(x-mu)/tau) + B\n#mypoisson = lambda x,mu: (mu**x)*np.exp(-mu)/scm.factorial(x)\n\ndef GetDataFrame(mytreename,mybranches,filelist):\n RProcessor = rp.ROOTProcessor(treename=mytreename)\n for f1 in filelist:\n RProcessor.addROOTFile(f1,branches_to_get=mybranches)\n data = RProcessor.getProcessedData()\n df = pd.DataFrame(data)\n return df\n'''\ndef EventSelectionLosses(df,df_trig):\n print(\"TOTAL NUMBER OF EVENT TIME TANKS SET: \" + str(len(set(df_trig['eventTimeTank']))))\n print(\"TOTAL NUMBER OF EVENT TIME TANKS, LIST: \" + str(len(df_trig['eventTimeTank'])))\n print(\"TOTAL NUMBER OF ENTRIES: \" + str(len(df_trig)))\n \n df_cleanSiPM = es.SingleSiPMPulses(df_trig)\n print(\"TOTAL NUMBER OF EVENTS W/ ONE PULSE IN EACH SIPM: \" + str(len(set(df_cleanSiPM['eventTimeTank']))))\n df_SinglePulses = es.SingleSiPMPulses(df) #Clusters with a single SiPM pulse\n\n df_cleanSiPMDT = es.SingleSiPMPulsesDeltaT(df_trig,200) \n print(\"TOTAL NUMBER OF EVENTS W/ ONE PULSE IN EACH SIPM, PEAKS WITHIN 200 NS: \" + str(len(set(df_cleanSiPMDT['eventTimeTank']))))\n \n df_trig_cleanSiPM = df_trig.loc[(df_trig['SiPM1NPulses']==1) & (df_trig['SiPM2NPulses']==1)].reset_index(drop=True)\n df_cleanPrompt = es.NoPromptClusters(df_SinglePulses,2000)\n df_trig_cleanPrompt = es.NoPromptClusters_WholeFile(df_SinglePulses,df_trig_cleanSiPM,2000)\n print(\"TOTAL NUMBER OF EVENTS W/ ONE PULSE IN EACH SIPM AND NO PROMPT CLUSTER: \" + str(len(set(df_trig_cleanPrompt['eventTimeTank']))))\n\n #Late burst cut\n df_trig_cleanWindow = es.NoBurst_WholeFile(df_cleanPrompt,df_trig_cleanPrompt,2000,150)\n print(\"TOTAL NUMBER OF EVENTS W/ CLEAN PROMPT AND NO BURST ABOVE 150 PE AND 2 MICROSECONDS: \" + str(len(set(df_trig_cleanWindow['eventTimeTank']))))\n'''\ndef PlotDemo(Sdf,Bdf,Sdf_trig,Bdf_trig): \n \n #print(\"EVENT SELECTION LOSSES FOR CENTRAL SOURCE RUN\")\n #EventSelectionLosses(Sdf,Sdf_trig)\n \n #print(\"EVENT SELECTION LOSSES FOR BKG CENTRAL SOURCE RUN\")\n #EventSelectionLosses(Bdf,Bdf_trig)\n Bdf['label'] = '0'\n print(Bdf.head())\n print(\"Bdf.shape: \", Bdf.shape)\n print(\"All columns are: \", Bdf.columns.values.tolist())\n Bdf.to_csv(\"vars_DNN_Bkgd.csv\", index=False,float_format = '%.3f')\n# print(type(Bdf.hitDetID))\n'''\n #---- My Plots:\n Bdf_prompt=Bdf.loc[Bdf['clusterTime']<2000].reset_index(drop=True) #prompt events\n plt.hist(Bdf_prompt['clusterTime'],bins=100,range=(0,2000))\n plt.title(\"Prompt window Tank cluster times - no cuts\")\n plt.xlabel(\"Cluster time [ns]\")\n plt.show()\n# plt.savefig(\"plots_AmBe/time_prompt.png\")\n\n Bdf_del=Bdf.loc[Bdf['clusterTime']>=2000].reset_index(drop=True) #delayed events\n plt.hist(Bdf_del['clusterTime'])#,bins=100,range=(10000,70000))\n plt.title(\"Delayed window Tank cluster times - no cuts\")\n plt.xlabel(\"Cluster time [ns]\")\n plt.show()\n# plt.savefig(\"plots_AmBe/time_del.png\")\n\n #--- CB to cluster Time: \n labels = {'title': 'Charge balance parameters in time window \\n (Beam data, $t_{c}>=2 \\, \\mu s$)', \n 'xlabel': 'Cluster time (ns)', 'ylabel': 'Charge balance'}\n ranges = {'xbins': 58, 'ybins':50, 'xrange':[2000,60000],'yrange':[0,1]}\n abp.Make2DHist(Bdf_del,'clusterTime','clusterChargeBalance',labels,ranges)\n plt.show()\n# plt.savefig(\"plots_AmBe/CB_time_del.png\")\n labels = {'title': 'Charge balance parameters in time window \\n (Beam data, $t_{c}<2 \\, \\mu s$)',\n 'xlabel': 'Cluster time (ns)', 'ylabel': 'Charge balance'}\n ranges = {'xbins': 20, 'ybins':50, 'xrange':[0,2000],'yrange':[0,1]}\n abp.Make2DHist(Bdf_prompt,'clusterTime','clusterChargeBalance',labels,ranges)\n plt.show()\n# plt.savefig(\"plots_AmBe/CB_time_prompt.png\")\n\n #--- CB to clusterPE: \n labels = {'title': 'Charge balance parameters in time window \\n (Beam data, $t_{c}>=2 \\, \\mu s$)',\n 'xlabel': 'Cluster PE', 'ylabel': 'Charge balance'}\n ranges = {'xbins': 58, 'ybins':50, 'xrange':[0,500],'yrange':[0,1]}\n abp.Make2DHist(Bdf_del,'clusterPE','clusterChargeBalance',labels,ranges)\n plt.show()\n# plt.savefig(\"plots_AmBe/CB_PE_del.png\")\n labels = {'title': 'Charge balance parameters in time window \\n (Beam data, $t_{c}<2 \\, \\mu s$)',\n 'xlabel': 'Cluster PE', 'ylabel': 'Charge balance'}\n ranges = {'xbins': 20, 'ybins':50, 'xrange':[0,500],'yrange':[0,1]}\n abp.Make2DHist(Bdf_prompt,'clusterPE','clusterChargeBalance',labels,ranges)\n plt.show()\n# plt.savefig(\"plots_AmBe/CB_PE_prompt.png\")\n\n #splitting to CB categories:\n #--- CB>=0.9 \n Bdf_prompt_highCB = Bdf_prompt.loc[Bdf_prompt['clusterChargeBalance']>=0.9].reset_index(drop=True) \n Bdf_del_highCB = Bdf_del.loc[Bdf_del['clusterChargeBalance']>=0.9].reset_index(drop=True)\n\n labels = {'title': 'Total PE vs Maximum PE in Cluster for \\n (Beam data, $t_{c}<2 \\, \\mu s$) \\n CB>=0.9 ',\n 'xlabel': 'Cluster PE', 'ylabel': 'Maximum PE in Cluster'}\n ranges = {'xbins': 200, 'ybins':200, 'xrange':[0,200],'yrange':[0,200]}\n #abp.Make2DHist(Sdf_prompt_highCB,'clusterPE','clusterMaxPE',labels,ranges)\n abp.Make2DHist(Bdf_prompt_highCB,'clusterPE','clusterMaxPE',labels,ranges)\n plt.show()\n# plt.savefig(\"plots_AmBe/PE_maxPE_prompt_highCB.png\")\n\n #PE = np.hstack(Sdf_del_highCB['hitPE'])\n #ID = np.hstack(Sdf_del_highCB['hitDetID'])\n #T = np.hstack(Sdf_del_highCB['hitT'])\n #maxPE_highCB = max(np.hstack(Sdf_prompt_highCB.hitPE))\n #print(\"maxPE_highCB \",maxPE_highCB,\" clusterMaxPE \",Sdf_prompt_highCB.clusterMaxPE)\n\n highCB_PE = np.hstack(Bdf_prompt_highCB.hitPE)\n highCB_DetID = np.hstack(Bdf_prompt_highCB.hitDetID)\n# highCB_PE = np.hstack(Sdf_del_highCB.hitPE)\n# highCB_DetID = np.hstack(Sdf_del_highCB.hitDetID)\n plt.hist2d(highCB_DetID,highCB_PE)\n plt.title(\"PE distribution for all hits in clusters, CB>=0.9)\")\n plt.xlabel(\"Tube ID\")\n plt.ylabel(\"PE\")\n plt.show()\n# plt.savefig(\"plots_AmBe/TubeID_PE_prompt_highCB.png\")\n \n #--- 0.6=0.6)].reset_index(drop=True)\n Bdf_del_upperCB = Bdf_del.loc[(Bdf_del['clusterChargeBalance']<0.9) & (Bdf_prompt['clusterChargeBalance']>=0.6)].reset_index(drop=True)\n\n labels = {'title': 'Total PE vs Maximum PE in Cluster for \\n (Beam data, $t_{c}<2 \\, \\mu s$) \\n 0.6<=CB<0.9',\n 'xlabel': 'Cluster PE', 'ylabel': 'Maximum PE in Cluster'}\n ranges = {'xbins': 200, 'ybins':200, 'xrange':[0,200],'yrange':[0,200]}\n abp.Make2DHist(Bdf_prompt_upperCB,'clusterPE','clusterMaxPE',labels,ranges)\n plt.show()\n# plt.savefig(\"plots_AmBe/PE_maxPE_prompt_upperCB.png\")\n\n upperCB_PE = np.hstack(Bdf_prompt_upperCB.hitPE)\n upperCB_DetID = np.hstack(Bdf_prompt_upperCB.hitDetID)\n plt.hist2d(upperCB_DetID,upperCB_PE)\n plt.title(\"PE distribution for all hits in clusters, 0.6==0.4)].reset_index(drop=True)\n Bdf_del_midCB = Bdf_del.loc[(Bdf_del['clusterChargeBalance']<0.6) & (Bdf_prompt['clusterChargeBalance']>=0.4)].reset_index(drop=True)\n \n labels = {'title': 'Total PE vs Maximum PE in Cluster for \\n (Beam data, $t_{c}<2 \\, \\mu s$)\\n 0.4<=CB<0.6',\n 'xlabel': 'Cluster PE', 'ylabel': 'Maximum PE in Cluster'}\n ranges = {'xbins': 200, 'ybins':200, 'xrange':[0,200],'yrange':[0,200]}\n abp.Make2DHist(Bdf_prompt_midCB,'clusterPE','clusterMaxPE',labels,ranges)\n plt.show()\n# plt.savefig(\"plots_AmBe/PE_maxPE_prompt_midCB.png\")\n \n midCB_PE = np.hstack(Bdf_prompt_midCB.hitPE)\n midCB_DetID = np.hstack(Bdf_prompt_midCB.hitDetID)\n plt.hist2d(midCB_DetID,midCB_PE)\n plt.title(\"PE distribution for all hits in clusters, 0.4==2 \\, \\mu s$) \\n CB>=0.9 ',\n 'xlabel': 'Cluster PE', 'ylabel': 'Maximum PE in Cluster'}\n ranges = {'xbins': 100, 'ybins':100, 'xrange':[0,100],'yrange':[0,100]}\n abp.Make2DHist(Bdf_del_highCB,'clusterPE','clusterMaxPE',labels,ranges)\n plt.show()\n\n labels = {'title': 'Total PE vs Maximum PE in Cluster for \\n (Beam data, $t_{c}>=2 \\, \\mu s$) \\n 0.6<=CB<0.9',\n 'xlabel': 'Cluster PE', 'ylabel': 'Maximum PE in Cluster'}\n ranges = {'xbins': 100, 'ybins':100, 'xrange':[0,100],'yrange':[0,100]}\n abp.Make2DHist(Bdf_del_upperCB,'clusterPE','clusterMaxPE',labels,ranges)\n plt.show()\n\n labels = {'title': 'Total PE vs Maximum PE in Cluster for \\n (Beam data, $t_{c}>=2 \\, \\mu s$)\\n 0.4<=CB<0.6',\n 'xlabel': 'Cluster PE', 'ylabel': 'Maximum PE in Cluster'}\n ranges = {'xbins': 100, 'ybins':100, 'xrange':[0,100],'yrange':[0,100]}\n abp.Make2DHist(Bdf_del_midCB,'clusterPE','clusterMaxPE',labels,ranges)\n plt.show()\n\n labels = {'title': 'Total PE vs Maximum PE in Cluster for \\n (Beam data, $t_{c}>=2 \\, \\mu s$) \\n CB<0.4',\n 'xlabel': 'Cluster PE', 'ylabel': 'Maximum PE in Cluster'}\n ranges = {'xbins': 100, 'ybins':100, 'xrange':[0,100],'yrange':[0,100]}\n abp.Make2DHist(Bdf_del_lowCB,'clusterPE','clusterMaxPE',labels,ranges)\n plt.show()\n'''\n\nif __name__=='__main__':\n slist = glob.glob(SIGNAL_DIR+\"*.ntuple.root\")\n blist = glob.glob(BKG_DIR+\"*.ntuple.root\")\n\n livetime_estimate = es.EstimateLivetime(slist)\n print(\"SIGNAL LIVETIME ESTIMATE IN SECONDS IS: \" + str(livetime_estimate))\n livetime_estimate = es.EstimateLivetime(blist)\n print(\"BKG LIVETIME ESTIMATE IN SECONDS IS: \" + str(livetime_estimate))\n\n #mybranches = ['eventNumber','eventTimeTank','clusterTime','SiPMhitT','SiPMhitQ','SiPMhitAmplitude','clusterChargeBalance','clusterPE','SiPM1NPulses','SiPM2NPulses','SiPMNum','clusterHits']\n mybranches = ['clusterTime','hitT','hitQ','hitPE','hitDetID','clusterChargeBalance','clusterPE','clusterMaxPE','clusterHits'] #,'SiPMhitT','SiPMhitQ','SiPMhitAmplitude','SiPM1NPulses','SiPM2NPulses','SiPMNum']\n\n SProcessor = rp.ROOTProcessor(treename=\"phaseIITankClusterTree\")\n for f1 in slist:\n SProcessor.addROOTFile(f1,branches_to_get=mybranches)\n Sdata = SProcessor.getProcessedData()\n Sdf = pd.DataFrame(Sdata)\n\n BProcessor = rp.ROOTProcessor(treename=\"phaseIITankClusterTree\")\n for f1 in blist:\n BProcessor.addROOTFile(f1,branches_to_get=mybranches)\n Bdata = BProcessor.getProcessedData()\n Bdf = pd.DataFrame(Bdata)\n\n SProcessor = rp.ROOTProcessor(treename=\"phaseIITriggerTree\")\n for f1 in slist:\n SProcessor.addROOTFile(f1,branches_to_get=mybranches)\n Sdata = SProcessor.getProcessedData()\n Sdf_trig = pd.DataFrame(Sdata)\n\n BProcessor = rp.ROOTProcessor(treename=\"phaseIITriggerTree\")\n for f1 in blist:\n BProcessor.addROOTFile(f1,branches_to_get=mybranches)\n Bdata = BProcessor.getProcessedData()\n Bdf_trig = pd.DataFrame(Bdata)\n\n PlotDemo(Sdf,Bdf,Sdf_trig,Bdf_trig)\n\n\n","sub_path":"ANNIENtupleAnalysis/util/AmBeBkgd_datacleaning_Lilia.py","file_name":"AmBeBkgd_datacleaning_Lilia.py","file_ext":"py","file_size_in_byte":13073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"322751312","text":"\"\"\"\nplot sin() wave\n\"\"\"\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\nx = np.arange(0, 2*math.pi, 0.1)\ny = np.sin(x)\nplt.xlabel('Angle')\nplt.ylabel('Sin()')\nplt.plot(x, y)\nplt.show()\n\nsamples = 100\nw = 3\nx = np.arange(samples+1)\ny = np.sin(2 * math.pi * w * (x / samples))\nplt.xlabel('Sample Rate')\nplt.ylabel('Sin()')\nplt.plot(x, y)\nplt.show()","sub_path":"level3/sin1.py","file_name":"sin1.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"186417866","text":"krosh = {\n \"view\": 'parrot',\n \"owner's name\": 'andrew',\n}\n\nreks = {\n \"view\": 'dog',\n \"owner's name\": 'police',\n}\n\npets = [krosh, reks]\n\nfor info in pets:\n print(\"\\n\")\n for owners_name, view in info.items():\n print(owners_name + \": \" + view)","sub_path":"6-8.py","file_name":"6-8.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"302961784","text":"from django.shortcuts import get_object_or_404\nfrom django.contrib.auth import get_user_model\nfrom .serializers import UserSerializer\nfrom .utils import check_login\n\nfrom decouple import config\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\n\nimport string\nimport random\nimport requests\nimport jwt\n\nJWT_SECRET_KEY = config('JWT_SECRET_KEY')\nUser = get_user_model()\n\n\ndef make_random_id():\n return ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(13))\n\n\n@api_view(['GET'])\ndef login(request):\n token = request.headers[\"Authorization\"]\n url = 'https://oauth2.googleapis.com/tokeninfo?id_token='\n response = requests.get(url+token)\n user = response.json()\n if User.objects.filter(google_id = user['sub']).exists():\n user_info = User.objects.get(google_id=user['sub'])\n encoded_jwt = jwt.encode({'id': user_info.id}, JWT_SECRET_KEY, algorithm='HS256')\n serializer = UserSerializer(user_info)\n else:\n while True:\n user_id = make_random_id()\n if(User.objects.filter(id=id).exists()):\n continue\n else:\n break\n new_user = User(\n id = user_id,\n name = user.get('name'),\n username = user.get('name'),\n email = user.get('email'),\n google_id = user.get('sub'),\n profile_url = user.get('picture')\n )\n new_user.save()\n serializer = UserSerializer(new_user)\n encoded_jwt = jwt.encode({'id': new_user.id}, JWT_SECRET_KEY, algorithm='HS256')\n data = {\n 'info': serializer.data,\n 'access_token': encoded_jwt,\n }\n return Response(data, status=status.HTTP_201_CREATED)\n\n\n@api_view(['PUT'])\n@check_login\ndef update(request):\n serializer = UserSerializer(request.user, data=request.data, partial=True)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\ndef profile(request, user_id):\n user = get_object_or_404(User, id=user_id)\n serializer = UserSerializer(user)\n return Response(serializer.data, status=status.HTTP_200_OK)","sub_path":"Project/server/accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"439062618","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 17 11:54:18 2019\n\n@author: Ian\n\"\"\"\n\nimport requests\n\nurl = 'http://httpbin.org/get'\n#headers 里面大小写均可\nheaders = {'User-Agent':\"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0\"}\ndata = requests.get(url,headers=headers)\nprint(data.text)\n\n","sub_path":"python-data-analysis-note-master/python-demo/demo-01-reuqests.py","file_name":"demo-01-reuqests.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"354006218","text":"#! /usr/bin/python3\nimport sys\n\noldKey = ''\nc = 0\nH = {}\nfor line in sys.stdin:\n l = line.strip().split() \n m = l[1].split(\";\")\n if(oldKey == l[0]): \n c+=int(m[2])\n else: \n if(c):\n for k,v in H.items():\n print(k+\"\\t\"+v+\"\\t\"+str(c))\n H = {} \n c = 1\n oldKey = l[0]\n H[l[0]+\"#\"+m[0]] = m[1]\n# print(H) \nif(c): \n for k,v in H.items():\n print(k+\"\\t\"+v+\"\\t\"+str(c))\n\n","sub_path":"43_5/tfidfReducer2.py","file_name":"tfidfReducer2.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"22370105","text":"#%%\n# MACS 402 - Structural Analysis - Dr. Evans - Problem Set 2\n# DATE: January 23rd, 2019\n# AUTHOR: Adam Oppenheimer\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport scipy\nfrom scipy import stats\nimport scipy.optimize as opt\nimport scipy.integrate as integrate\nfrom scipy.stats.distributions import chi2\nimport math\nfrom math import e\n#%%\n#Problem 1\ndata = np.loadtxt(\"/Volumes/GoogleDrive/My Drive/3rd Year/Quarter 2\" +\\\n \"/Structural Estimation/StructEst_W19/ProblemSets/\" +\\\n \"PS2/clms.txt\", dtype=np.float128)\n#%%\n#Problem 1 Part a\n#Problem 1 Part a - Define Functions\ndef plot_graph(data, num_bins, weights, title, x_label, y_label):\n plt.hist(data, bins=num_bins, weights=weights)\n plt.title(title)\n plt.xlabel(x_label)\n plt.ylabel(y_label)\n#%%\n#Problem 1 Part a - Define Values\ncount = data.shape[0]\nmean = data.mean()\nmedian = np.median(data)\nmax_min = (data.max(), data.min())\nstd = data.std()\nvar = data.var()\nprint(\"Mean: \", mean)\nprint(\"Median: \", median)\nprint(\"Max: \", max_min[0])\nprint(\"Min: \", max_min[1])\nprint(\"Std: \", std)\n#%%\n#Problem 1 Part a - Graph 1\ntitle = \"Histogram of Health Claims\"\nx_label = \"Value of Monthly Health Expenditures ($)\"\ny_label = \"Percent of Observations\"\nplot_1_weights = (1 / count) * np.ones_like(data)\nnum_bins = 1000\nplot_graph(data, num_bins, plot_1_weights, title, x_label, y_label)\nplt.show()\n#%%\n#Problem 1 Part a - Graph 2\ntitle = \"Histogram of Health Claims <= $800\"\ndata_under_800 = data[data <= 800]\nplot_2_weights = (1 / count) * np.ones_like(data_under_800)\nnum_bins = 100\nplot_graph(data_under_800, num_bins, plot_2_weights, title, x_label, y_label)\nplt.show()\n#%%\n#Problem 1 Part b\n#Problem 1 Part b - Define Functions\ndef gamma_fun_pdf(xvals, alpha, beta):\n pdf_vals = ( xvals ** (alpha - 1) * e ** ( - xvals / beta ) )/\\\n ( beta ** alpha * math.gamma(alpha) )\n return pdf_vals\n\ndef log_lik_fun_b(xvals, alpha, beta):\n pdf_vals = gamma_fun_pdf(xvals, alpha, beta)\n ln_pdf_vals = np.log(pdf_vals)\n return ln_pdf_vals.sum()\n\ndef crit_b(params, *args):\n alpha, beta = params\n xvals, = args\n log_lik_val = log_lik_fun_b(xvals, alpha, beta)\n return -log_lik_val\n#%%\n#Problem 1 Part b - Define Values\nbeta_0 = var/mean\nalpha_0 = mean/beta_0\nparams_init = np.array([alpha_0, beta_0])\n#%%\n#Problem 1 Part b - Call Functions\nlog_lik = log_lik_fun_b(data, alpha_0, beta_0)\nresults_cstr = opt.minimize(crit_b, params_init,\\\n args=(data), method=\"L-BFGS-B\",\\\n bounds=((1e-10, None), (1e-10, None)))\nalpha_MLE_b, beta_MLE_b = results_cstr.x\nlog_lik_b = log_lik_fun_b(data, alpha_MLE_b, beta_MLE_b)\n#%%\n#Problem 1 Part b - Output Results\nprint(\"alpha_MLE_b=\", alpha_MLE_b, \" beta_MLE_b=\", beta_MLE_b)\nprint(\"Maximize Log Likelihood: \", log_lik_b)\n#%%\n#Problem 1 Part b - Print Graphs\ntitle = \"Histogram of Health Claims <= $800 + (b) Prediction\"\nplot_graph(data_under_800, num_bins, plot_2_weights, title, x_label, y_label)\ndist_pts = np.linspace(1e-10, data_under_800.max(), count)\nplt.plot(dist_pts, gamma_fun_pdf(dist_pts, alpha_MLE_b, beta_MLE_b),\\\n linewidth=2, label=\"Gamma\", color=\"r\")\nplt.legend(loc=\"upper left\")\nplt.ylim([0, 0.05])\nplt.xlim([0, 800])\nplt.show()\n#%%\n#Problem 1 Part c\n#Problem 1 Part c - Define Functions\ndef gen_gamma_fun_pdf(xvals, alpha, beta, m):\n pdf_vals = (m * e ** ( - ( xvals / beta ) ** m ))/\\\n (xvals * math.gamma(alpha / m)) *\\\n (xvals / beta) ** alpha\n return pdf_vals\n\ndef log_sum_c(xvals, alpha, beta, m):\n log_vals = np.log(m) + (alpha - 1) * np.log(xvals) -\\\n (xvals / beta) ** m - alpha * np.log(beta) -\\\n np.log(math.gamma(alpha / m))\n return log_vals.sum()\n\ndef crit_c(params, *args):\n alpha, beta, m = params\n xvals, = args\n log_lik_val = log_sum_c(xvals, alpha, beta, m)\n return -log_lik_val\n#%%\n#Problem 1 Part c - Define Values\nalpha_0 = alpha_MLE_b\nbeta_0 = beta_MLE_b\nm_0 = 1\nparams_init = np.array([alpha_0, beta_0, m_0])\n#%%\n#Problem 1 Part c - Call Functions\nresults_cstr = opt.minimize(crit_c, params_init,\\\n args=(data), method=\"L-BFGS-B\",\\\n bounds=((1e-10, None), (1e-10, None),\\\n (1e-10, None)))\nalpha_MLE_c, beta_MLE_c, m_MLE_c = results_cstr.x\nlog_lik_c = log_sum_c(data, alpha_MLE_c, beta_MLE_c, m_MLE_c)\n#%%\n#Problem 1 Part c - Output Results\nprint(\"alpha_MLE_c=\", alpha_MLE_c, \" beta_MLE_c=\", beta_MLE_c, \" m_MLE_c=\", m_MLE_c)\nprint(\"Maximize Log Likelihood: \", log_lik_c)\n#%%\n#Problem 1 Part c - Print Graphs\ntitle = \"Histogram of Health Claims <= $800 + (c) Prediction\"\nplot_graph(data_under_800, num_bins, plot_2_weights, title, x_label, y_label)\nplt.plot(dist_pts, gen_gamma_fun_pdf(dist_pts, alpha_MLE_c, beta_MLE_c, m_MLE_c),\\\n linewidth=2, label=\"Generalized Gamma\", color=\"r\")\nplt.legend(loc=\"upper left\")\nplt.ylim([0, 0.05])\nplt.xlim([0, 800])\nplt.show()\n#%%\n#Problem 1 Part d\n#Problem 1 Part d - Define Functions\ndef gen_beta2_fun_pdf(xvals, a, b, p, q):\n pdf_vals = (xvals / b) ** (a * p) * a / (xvals * gb2_beta(p, q) *\\\n (1 + (xvals / b) ** a) ** (p + q) )\n return pdf_vals\n\ndef log_sum_d(xvals, a, b, p, q):\n log_vals = (a * p - 1) * np.log(xvals) + np.log(a) -\\\n a * p * np.log(b) - np.log(gb2_beta(p, q))\\\n - (p + q) * np.log(1 + (xvals / b) ** a)\n return log_vals.sum()\n\ndef gb2_beta(p, q):\n betainc = scipy.special.betainc(p, q, 1)\n return betainc * scipy.special.beta(p, q)\n\ndef crit_d(params, *args):\n a, b, p, q = params\n xvals, = args\n log_lik_val = log_sum_d(xvals, a, b, p, q)\n return -log_lik_val\n#%%\n#Problem 1 Part d - Define Values\na_0 = alpha_MLE_c\nb_0 = beta_MLE_c\np_0 = m_MLE_c\nq_0 = 10000\nparams_init = np.array([a_0, b_0, p_0, q_0])\n#%%\n#Problem 1 Part d - Call Functions\nresults_cstr = opt.minimize(crit_d, params_init,\\\n args=(data), method=\"L-BFGS-B\",\\\n bounds=((1e-10, None), (1e-10, None),\\\n (1e-10, None), (1e-10, None)))\na_MLE_d, b_MLE_d, p_MLE_d, q_MLE_d = results_cstr.x\nlog_lik_d = log_sum_d(data, a_MLE_d, b_MLE_d, p_MLE_d, q_MLE_d)\n#%%\n#Problem 1 Part d - Output Results\nprint(\"a_MLE_d=\", a_MLE_d, \" b_MLE_d=\", b_MLE_d,\\\n \" p_MLE_d=\", p_MLE_d, \" q_MLE_d=\", q_MLE_d)\nprint(\"Maximize Log Likelihood: \", log_lik_d)\n#%%\n#Problem 1 Part d - Print Graphs\ntitle = \"Histogram of Health Claims <= $800 + (d) Prediction\"\nplot_graph(data_under_800, num_bins, plot_2_weights, title, x_label, y_label)\nplt.plot(dist_pts, gen_beta2_fun_pdf(dist_pts, a_MLE_d, b_MLE_d, p_MLE_d, q_MLE_d),\\\n linewidth=2, label=\"Generalized Beta 2\", color=\"r\")\nplt.legend(loc=\"upper left\")\nplt.ylim([0, 0.05])\nplt.xlim([0, 800])\nplt.show()\n#%%\n#Problem 1 Part e\n#Problem 1 Part e - Define Functions\ndef likelihood_ratio(log_lik_a, log_lik_b):\n return float(2 * (log_lik_a - log_lik_b))\n#%%\n#Problem 1 Part e - Call Functions\nlik_rat_b_d = likelihood_ratio(log_lik_d, log_lik_b)\np_val_b_d = chi2.sf(lik_rat_b_d, 2)\nlik_rat_c_d = likelihood_ratio(log_lik_d, log_lik_c)\np_val_c_d = chi2.sf(lik_rat_c_d, 1)\n#%%\n#Problem 1 Part e - Output Results\nprint(\"Likelihood ratio b-d: \", lik_rat_b_d)\nprint(\"P val b-d: \", p_val_b_d)\nprint(\"Likelihood ratio c-d: \", lik_rat_c_d)\nprint(\"P val c-d: \", p_val_c_d)\n#%%\n#Problem 1 Part f\n#Problem 1 Part f - Define Functions\ndef integrand_d(x, a, b, p, q):\n return gen_beta2_fun_pdf(x, a, b, p, q)\ndef integrand_b(x, alpha, beta):\n return gamma_fun_pdf(x, alpha, beta)\n#%%\n#Problem 1 Part f - Call Functions\nzero_to_1k_d = integrate.quad(integrand_d, 1e-10, 1000,\\\n args=(a_MLE_d, b_MLE_d, p_MLE_d, q_MLE_d))[0]\nzero_to_1k_b = integrate.quad(integrand_b, 1e-10, 1000,\\\n args=(alpha_MLE_b, beta_MLE_b))[0]\n#%%\n#Problem 1 Part f - Output Results\nprint(\"Prob of >= $1,000 from b: \", 1-zero_to_1k_b)\nprint(\"Prob of >= $1,000 from d: \", 1-zero_to_1k_d)\nprint(\"Difference between b and d: \", abs(zero_to_1k_d - zero_to_1k_b))\n#%%\n#Problem 1 Final Graph:\ntitle = \"Histogram of Health Claims <= $800 + Predictions\"\nnum_bins = 1000 #NOTE: I set this to 1,000 because smaller values misrepresent the fit\nplot_graph(data_under_800, num_bins, plot_2_weights, title, x_label, y_label)\n#Part b - Gamma\nplt.plot(dist_pts, gamma_fun_pdf(dist_pts, alpha_MLE_b, beta_MLE_b),\\\n linewidth=2, label='Gamma', color=\"blue\")\n#Part c - Generalized Gamma\nplt.plot(dist_pts, gen_gamma_fun_pdf(dist_pts, alpha_MLE_c, beta_MLE_c, m_MLE_c),\\\n linewidth=2, label=\"Generalized Gamma\", color=\"green\")\n#Part d - Generalized Beta 2\nplt.plot(dist_pts, gen_beta2_fun_pdf(dist_pts, a_MLE_d, b_MLE_d, p_MLE_d, q_MLE_d),\\\n linewidth=2, label=\"Generalized Beta 2\", color=\"red\")\nplt.legend(loc=\"upper left\")\nplt.ylim([0, 0.01])\nplt.xlim([0, 800])\nplt.show()\n#%%\n#Problem 2\ndata = np.loadtxt(\"/Volumes/GoogleDrive/My Drive/3rd Year/Quarter 2\" +\\\n \"/Structural Estimation/StructEst_W19/ProblemSets/\" +\\\n \"PS2/MacroSeries.txt\", delimiter=',', usecols=range(4),\\\n dtype=np.float128)\nkapital = data[:,1]\nwages = data[:,2]\ninterest = data[:,3]\n#%%\n#Problem 2 Part a\n#Problem 2 Part a - Define Functions\ndef gen_norm_pdf(xvals, mu, sigma):\n pdf_vals = e ** ( - ( (xvals - mu) ** 2) / (2 * sigma ** 2) )/\\\n (sigma * math.sqrt(2 * math.pi) )\n return pdf_vals\n\ndef log_sum_norm(z_vals, mu, sigma):\n log_vals = -( (z_vals - mu) ** 2) / (2 * sigma ** 2) -\\\n np.log(sigma * math.sqrt(2 * math.pi) )\n return log_vals.sum()\n\ndef crit_norm_wages(params, *args):\n alpha, rho, mu, sigma = params\n kapital, wages = args\n z_vals = np.log(wages) - np.log(1 - alpha) - alpha * np.log(kapital)\n z_vals_shift = np.roll(z_vals, 1)\n z_vals_shift[0] = mu\n mu_est = rho * z_vals_shift + (1 - rho) * mu\n log_lik_val = log_sum_norm(z_vals, mu_est, sigma)\n return log_lik_val*(-1)\n#%%\n#Problem 2 Part a - Define Values\nalpha_0 = 0.6\nrho_0 = 0.6\nz_vals = np.log(wages) - np.log(1 - alpha_0) - alpha_0 * np.log(kapital)\nmu_0 = z_vals[0]\nsigma_0 = 0.15\nparams_init = np.array([alpha_0, rho_0, mu_0, sigma_0])\n#%%\n#Problem 2 Part a - Call Functions\nresults_cstr = opt.minimize(crit_norm_wages, params_init,\\\n args=((kapital, wages)),\\\n method=\"L-BFGS-B\",\\\n bounds=((1e-10, 1-1e-10), (-1+1e-10, 1-1e-10),\\\n (1e-10, None), (1e-10, None)))\nalpha_MLE_a, rho_MLE_a, mu_MLE_a, sigma_MLE_a = results_cstr.x\nlog_lik_norm = -results_cstr.fun\n#%%\n#Problem 2 Part a - Output Results\nprint(\"alpha_MLE=\", alpha_MLE_a, \" rho_MLE=\", rho_MLE_a,\\\n \" mu_MLE=\", mu_MLE_a, \" sigma_MLE=\", sigma_MLE_a)\nprint(\"Maximize Log Likelihood: \", log_lik_norm)\n#%%\n#Problem 2 Part a - Define Hessian Values\nvcv_mle = (results_cstr.hess_inv).matmat(np.eye(4))\nstderr_alpha_mle = math.sqrt(vcv_mle[0,0])\nstderr_rho_mle = math.sqrt(vcv_mle[1,1])\nstderr_mu_mle = math.sqrt(vcv_mle[2,2])\nstderr_sig_mle = math.sqrt(vcv_mle[3,3])\n#%%\n#Problem 2 Part a - Output Hessian Results\nprint(\"VCV(MLE) = \", vcv_mle)\nprint(\"Standard error for alpha estimate = \", stderr_alpha_mle)\nprint(\"Standard error for rho estimate = \", stderr_rho_mle)\nprint(\"Standard error for mu estimate = \", stderr_mu_mle)\nprint(\"Standard error for sigma estimate = \", stderr_sig_mle)\n#%%\n#Problem 2 Part b\n#Problem 2 Part b - Define Functions\ndef crit_norm_interest(params, *args):\n alpha, rho, mu, sigma = params\n kapital, interest = args\n z_vals = np.log(interest) - np.log(alpha) - (1 - alpha) * np.log(kapital)\n z_vals_shift = np.roll(z_vals, 1)\n z_vals_shift[0] = mu\n mu_est = rho * z_vals_shift + (1 - rho) * mu\n log_lik_val = log_sum_norm(z_vals, mu_est, sigma)\n return -log_lik_val\n#%%\n#Problem 2 Part b - Define Values\nalpha_0 = 0.6\nrho_0 = 0.6\nz_vals = np.log(interest) - np.log(alpha_0) - (1 - alpha_0) * np.log(kapital)\nmu_0 = z_vals[0]\nsigma_0 = 0.15\nparams_init = np.array([alpha_0, rho_0, mu_0, sigma_0])\n#%%\n#Problem 2 Part b - Call Functions\nresults_cstr = opt.minimize(crit_norm_interest, params_init,\\\n args=((kapital, wages)),\\\n method=\"L-BFGS-B\",\\\n bounds=((1e-10, 1-1e-10), (-1+1e-10, 1-1e-10),\\\n (1e-10, None), (1e-10, None)))\nalpha_MLE_b, rho_MLE_b, mu_MLE_b, sigma_MLE_b = results_cstr.x\nlog_lik_norm = -results_cstr.fun\nprint(\"alpha_MLE=\", alpha_MLE_b, \" rho_MLE=\", rho_MLE_b,\\\n \" mu_MLE=\", mu_MLE_b, \" sigma_MLE=\", sigma_MLE_b)\nprint(\"Maximize Log Likelihood: \", log_lik_norm)\n#%%\n#Problem 2 Part b - Define Hessian Values\nvcv_mle = (results_cstr.hess_inv).matmat(np.eye(4))\nstderr_alpha_mle = math.sqrt(vcv_mle[0,0])\nstderr_rho_mle = math.sqrt(vcv_mle[1,1])\nstderr_mu_mle = math.sqrt(vcv_mle[2,2])\nstderr_sig_mle = math.sqrt(vcv_mle[3,3])\n#%%\n#Problem 2 Part b - Output Hessian Results\nprint(\"VCV(MLE) = \", vcv_mle)\nprint(\"Standard error for alpha estimate = \", stderr_alpha_mle)\nprint(\"Standard error for rho estimate = \", stderr_rho_mle)\nprint(\"Standard error for mu estimate = \", stderr_mu_mle)\nprint(\"Standard error for sigma estimate = \", stderr_sig_mle)\n#%%\n#Problem 2 Part c\n#Problem 2 Part c - Define Functions\ndef integrand_2_c(x, mu, sigma):\n return gen_norm_pdf(x, mu, sigma)\n#%%\n#Problem 2 Part c - Define Values\nk_t = 7500000\nz_t_prev = 10\nz_star = -np.log(alpha_MLE_a) - (alpha_MLE_a - 1) * np.log(k_t)\nmu = rho_MLE_a * z_t_prev + (1 - rho_MLE_a) * mu_MLE_a\n#%%\n#Problem 2 Part c - Call Functions\npr_rt_gt_1 = integrate.quad(integrand_2_c, z_star, math.inf,\\\n args=(mu, sigma_MLE_a))[0]\n#%%\n#Problem 2 Part c - Output Results\nprint(\"Probability: \", pr_rt_gt_1)\n","sub_path":"ProblemSets/PS2/Pset 2.py","file_name":"Pset 2.py","file_ext":"py","file_size_in_byte":14149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"463846550","text":"# Copyright 2020 The Bazel 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\"\"\"Rules for importing and registering a local JDK.\"\"\"\n\ndef _detect_java_version(repository_ctx, java_bin):\n properties_out = repository_ctx.execute([java_bin, \"-XshowSettings:properties\"]).stderr\n # This returns an indented list of properties separated with newlines:\n # \" java.vendor.url.bug = ... \\n\"\n # \" java.version = 11.0.8\\n\"\n # \" java.version.date = 2020-11-05\\\"\n\n strip_properties = [property.strip() for property in properties_out.splitlines()]\n version_property = [property for property in strip_properties if property.startswith(\"java.version = \")]\n if len(version_property) != 1:\n return \"unknown\"\n\n version_value = version_property[0][len(\"java.version = \"):]\n (major, minor, rest) = version_value.split(\".\", 2)\n\n if major == \"1\": # handles versions below 1.8\n return minor\n return major\n\ndef _local_java_repository_impl(repository_ctx):\n java_home = repository_ctx.attr.java_home\n java_home_path = repository_ctx.path(java_home)\n if not java_home_path.exists:\n fail('The path indicated by the \"java_home\" attribute \"%s\" (absolute: \"%s\") ' +\n \"does not exist.\" % (java_home, str(java_home_path)))\n\n repository_ctx.file(\n \"WORKSPACE\",\n \"# DO NOT EDIT: automatically generated WORKSPACE file for local_java_repository\\n\" +\n \"workspace(name = \\\"{name}\\\")\\n\".format(name = repository_ctx.name),\n )\n\n extension = \".exe\" if repository_ctx.os.name.lower().find(\"windows\") != -1 else \"\"\n java_bin = java_home_path.get_child(\"bin\").get_child(\"java\" + extension)\n if java_bin.exists:\n version = repository_ctx.attr.version if repository_ctx.attr.version != \"\" else _detect_java_version(repository_ctx, java_bin)\n\n repository_ctx.file(\n \"BUILD.bazel\",\n repository_ctx.read(repository_ctx.path(repository_ctx.attr._build_file)) +\n \"\"\"\nconfig_setting(\n name = \"name_setting\",\n values = {{\"java_runtime_version\": \"{local_jdk}\"}},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {{\"java_runtime_version\": \"{version}\"}},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_name_setting\",\n actual = select({{\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":name_setting\",\n }}),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_settings = [\":version_or_name_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \":jdk\",\n)\n\"\"\".format(local_jdk = repository_ctx.name, version = version),\n False,\n )\n\n # Symlink all files\n for file in repository_ctx.path(java_home).readdir():\n repository_ctx.symlink(file, file.basename)\n\n return\n\n # Java binary does not exist\n repository_ctx.file(\n \"BUILD.bazel\",\n '''load(\"@bazel_tools//tools/jdk:fail_rule.bzl\", \"fail_rule\")\n\nfail_rule(\n name = \"jdk\",\n header = \"Auto-Configuration Error:\",\n message = (\"Cannot find Java binary {java_binary} in {java_home}; either correct your JAVA_HOME, \" +\n \"PATH or specify Java from remote repository (e.g. \" +\n \"--java_runtime_version=remotejdk_11\")\n)\nconfig_setting(\n name = \"localjdk_setting\",\n values = {{\"java_runtime_version\": \"{local_jdk}\"}},\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_settings = [\":localjdk_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \":jdk\",\n)\n'''.format(\n local_jdk = repository_ctx.name,\n java_binary = \"bin/java\" + extension,\n java_home = java_home,\n ),\n False,\n )\n\n_local_java_repository_rule = repository_rule(\n implementation = _local_java_repository_impl,\n local = True,\n configure = True,\n attrs = {\n \"java_home\": attr.string(),\n \"version\": attr.string(),\n \"_build_file\": attr.label(default = \"@bazel_tools//tools/jdk:jdk.BUILD\"),\n },\n)\n\ndef local_java_repository(name, java_home, version = \"\"):\n \"\"\"Imports and registers a local JDK.\n\n Toolchain resolution is constrained with --java_runtime_version flag\n having value of the \"name\" parameter.\n\n Args:\n name: A unique name for this rule.\n java_home: Location of the JDK imported.\n version: optionally java version\n \"\"\"\n _local_java_repository_rule(name = name, java_home = java_home, version = version)\n native.register_toolchains(\"@\" + name + \"//:toolchain\")\n","sub_path":"tools/jdk/local_java_repository.bzl","file_name":"local_java_repository.bzl","file_ext":"bzl","file_size_in_byte":5223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"603678946","text":"# Copyright (c) 2015-2021, NVIDIA CORPORATION.\n# SPDX-License-Identifier: Apache-2.0\n\n\n\"\"\"\nCode copied from OpenStack Swift.\n\nWe import some things from Swift if we think they're in stable-enough\nlocations to depend on. When it turns out we're wrong, the things get copied\ninto here.\n\nThis is all Apache-licensed code, so copying it into here is fine.\n\nThe copyright header in this file was taken from\nswift/common/request_helpers.py in the OpenStack Swift source distribution.\n\"\"\"\n\nfrom distutils.version import LooseVersion\nimport email.parser\nimport hashlib\nimport itertools\nimport re\nimport six\nimport sys\nimport time\nfrom six import BytesIO\nfrom six.moves.urllib.parse import unquote\nfrom swift import __version__ as swift_version\nfrom swift.common.swob import HTTPBadRequest, HTTPNotAcceptable, \\\n HTTPNotImplemented, HTTPLengthRequired, Request, Range, \\\n multi_range_iterator, HeaderKeyDict\n\n\n# Taken from swift/common/constraints.py, commit d2e32b3\n#: Query string format= values to their corresponding content-type values\nFORMAT2CONTENT_TYPE = {'plain': 'text/plain', 'json': 'application/json',\n 'xml': 'application/xml'}\n\n\n# On new enough swift, we should always send JSON listings;\n# see https://github.com/openstack/swift/commit/4806434\nLISTING_FORMATS_SWIFT = (LooseVersion(swift_version) >= LooseVersion('2.16.0'))\n\n\n# Taken from swift/common/request_helpers.py, commit d2e32b3\ndef get_param(req, name, default=None):\n \"\"\"\n Get parameters from an HTTP request ensuring proper handling UTF-8\n encoding.\n\n :param req: request object\n :param name: parameter name\n :param default: result to return if the parameter is not found\n :returns: HTTP request parameter value\n (as UTF-8 encoded str, not unicode object)\n :raises HTTPBadRequest: if param not valid UTF-8 byte sequence\n \"\"\"\n value = req.params.get(name, default)\n if value and not isinstance(value, six.text_type):\n try:\n value.decode('utf8') # Ensure UTF8ness\n except UnicodeDecodeError:\n raise HTTPBadRequest(\n request=req, content_type='text/plain',\n body='\"%s\" parameter not valid UTF-8' % name)\n return value\n\n\n# Taken from swift/common/request_helpers.py, commit d2e32b3\ndef get_listing_content_type(req):\n \"\"\"\n Determine the content type to use for an account or container listing\n response.\n\n :param req: request object\n :returns: content type as a string (e.g. text/plain, application/json)\n :raises HTTPNotAcceptable: if the requested content type is not acceptable\n :raises HTTPBadRequest: if the 'format' query param is provided and\n not valid UTF-8\n \"\"\"\n if LISTING_FORMATS_SWIFT:\n return 'application/json'\n query_format = get_param(req, 'format')\n if query_format:\n req.accept = FORMAT2CONTENT_TYPE.get(\n query_format.lower(), FORMAT2CONTENT_TYPE['plain'])\n out_content_type = req.accept.best_match(\n ['text/plain', 'application/json', 'application/xml', 'text/xml'])\n if not out_content_type:\n raise HTTPNotAcceptable(request=req)\n return out_content_type\n\n\n# Taken from swift/common/utils.py, commit d2e32b3\n# Used when reading config values\nTRUE_VALUES = set(('true', '1', 'yes', 'on', 't', 'y'))\n\n\ndef config_true_value(value):\n \"\"\"\n Returns True if the value is either True or a string in TRUE_VALUES.\n Returns False otherwise.\n \"\"\"\n return value is True or \\\n (isinstance(value, six.string_types) and value.lower() in TRUE_VALUES)\n\n\n# Taken from swift/common/constraints.py, commit 1962b18\n#\n# Modified to not check maximum object size; ProxyFS doesn't enforce one.\ndef check_object_creation(req):\n \"\"\"\n Check to ensure that everything is alright about an object to be created.\n :param req: HTTP request object\n :returns: HTTPLengthRequired -- missing content-length header and not\n a chunked request\n :returns: HTTPBadRequest -- missing or bad content-type header, or\n bad metadata\n :returns: HTTPNotImplemented -- unsupported transfer-encoding header value\n \"\"\"\n try:\n req.message_length()\n except ValueError as e:\n return HTTPBadRequest(request=req, content_type='text/plain',\n body=str(e))\n except AttributeError as e:\n return HTTPNotImplemented(request=req, content_type='text/plain',\n body=str(e))\n if req.content_length is None and \\\n req.headers.get('transfer-encoding') != 'chunked':\n return HTTPLengthRequired(body='Missing Content-Length header.',\n request=req,\n content_type='text/plain')\n\n if 'Content-Type' not in req.headers:\n return HTTPBadRequest(request=req, content_type='text/plain',\n body='No content type')\n return None\n\n\n# Made up for SegmentedIterable\nclass ListingIterError(Exception):\n pass\n\n\n# Made up for SegmentedIterable\nclass SegmentError(Exception):\n pass\n\n\n# Made up for iter_multipart_mime_documents\nclass ChunkReadError(Exception):\n pass\n\n\n# Made up for iter_multipart_mime_documents\nclass MimeInvalid(Exception):\n pass\n\n\n# Taken from swift/common/utils.py, commit 1962b18\ndef close_if_possible(maybe_closable):\n close_method = getattr(maybe_closable, 'close', None)\n if callable(close_method):\n return close_method()\n\n\n# Taken from swift/common/utils.py, commit 1962b18\n#\n# Modified to use different exception classes.\nclass _MultipartMimeFileLikeObject(object):\n\n def __init__(self, wsgi_input, boundary, input_buffer, read_chunk_size):\n self.no_more_data_for_this_file = False\n self.no_more_files = False\n self.wsgi_input = wsgi_input\n self.boundary = boundary\n self.input_buffer = input_buffer\n self.read_chunk_size = read_chunk_size\n\n def read(self, length=None):\n if not length:\n length = self.read_chunk_size\n if self.no_more_data_for_this_file:\n return b''\n\n # read enough data to know whether we're going to run\n # into a boundary in next [length] bytes\n if len(self.input_buffer) < length + len(self.boundary) + 2:\n to_read = length + len(self.boundary) + 2\n while to_read > 0:\n try:\n chunk = self.wsgi_input.read(to_read)\n except (IOError, ValueError) as e:\n raise ChunkReadError(str(e))\n to_read -= len(chunk)\n self.input_buffer += chunk\n if not chunk:\n self.no_more_files = True\n break\n\n boundary_pos = self.input_buffer.find(self.boundary)\n\n # boundary does not exist in the next (length) bytes\n if boundary_pos == -1 or boundary_pos > length:\n ret = self.input_buffer[:length]\n self.input_buffer = self.input_buffer[length:]\n # if it does, just return data up to the boundary\n else:\n ret, self.input_buffer = self.input_buffer.split(self.boundary, 1)\n self.no_more_files = self.input_buffer.startswith(b'--')\n self.no_more_data_for_this_file = True\n self.input_buffer = self.input_buffer[2:]\n return ret\n\n def readline(self):\n if self.no_more_data_for_this_file:\n return b''\n boundary_pos = newline_pos = -1\n while newline_pos < 0 and boundary_pos < 0:\n try:\n chunk = self.wsgi_input.read(self.read_chunk_size)\n except (IOError, ValueError) as e:\n raise ChunkReadError(str(e))\n self.input_buffer += chunk\n newline_pos = self.input_buffer.find(b'\\r\\n')\n boundary_pos = self.input_buffer.find(self.boundary)\n if not chunk:\n self.no_more_files = True\n break\n # found a newline\n if newline_pos >= 0 and \\\n (boundary_pos < 0 or newline_pos < boundary_pos):\n # Use self.read to ensure any logic there happens...\n ret = b''\n to_read = newline_pos + 2\n while to_read > 0:\n chunk = self.read(to_read)\n # Should never happen since we're reading from input_buffer,\n # but just for completeness...\n if not chunk:\n break\n to_read -= len(chunk)\n ret += chunk\n return ret\n else: # no newlines, just return up to next boundary\n return self.read(len(self.input_buffer))\n\n\n# Taken from swift/common/utils.py, commit 1962b18\nclass Spliterator(object):\n \"\"\"\n Takes an iterator yielding sliceable things (e.g. strings or lists) and\n yields subiterators, each yielding up to the requested number of items\n from the source.\n\n >>> si = Spliterator([\"abcde\", \"fg\", \"hijkl\"])\n >>> ''.join(si.take(4))\n \"abcd\"\n >>> ''.join(si.take(3))\n \"efg\"\n >>> ''.join(si.take(1))\n \"h\"\n >>> ''.join(si.take(3))\n \"ijk\"\n >>> ''.join(si.take(3))\n \"l\" # shorter than requested; this can happen with the last iterator\n\n \"\"\"\n def __init__(self, source_iterable):\n self.input_iterator = iter(source_iterable)\n self.leftovers = None\n self.leftovers_index = 0\n self._iterator_in_progress = False\n\n def take(self, n):\n if self._iterator_in_progress:\n raise ValueError(\n \"cannot call take() again until the first iterator is\"\n \" exhausted (has raised StopIteration)\")\n self._iterator_in_progress = True\n\n try:\n if self.leftovers:\n # All this string slicing is a little awkward, but it's for\n # a good reason. Consider a length N string that someone is\n # taking k bytes at a time.\n #\n # With this implementation, we create one new string of\n # length k (copying the bytes) on each call to take(). Once\n # the whole input has been consumed, each byte has been\n # copied exactly once, giving O(N) bytes copied.\n #\n # If, instead of this, we were to set leftovers =\n # leftovers[k:] and omit leftovers_index, then each call to\n # take() would copy k bytes to create the desired substring,\n # then copy all the remaining bytes to reset leftovers,\n # resulting in an overall O(N^2) bytes copied.\n llen = len(self.leftovers) - self.leftovers_index\n if llen <= n:\n n -= llen\n to_yield = self.leftovers[self.leftovers_index:]\n self.leftovers = None\n self.leftovers_index = 0\n yield to_yield\n else:\n to_yield = self.leftovers[\n self.leftovers_index:(self.leftovers_index + n)]\n self.leftovers_index += n\n n = 0\n yield to_yield\n\n while n > 0:\n chunk = next(self.input_iterator)\n cl = len(chunk)\n if cl <= n:\n n -= cl\n yield chunk\n else:\n self.leftovers = chunk\n self.leftovers_index = n\n yield chunk[:n]\n n = 0\n finally:\n self._iterator_in_progress = False\n\n\n# Taken from swift/common/request_helpers.py, commit 1962b18\ndef make_env(env, method=None, path=None, agent='Swift', query_string=None,\n swift_source=None):\n \"\"\"\n Returns a new fresh WSGI environment.\n\n :param env: The WSGI environment to base the new environment on.\n :param method: The new REQUEST_METHOD or None to use the\n original.\n :param path: The new path_info or none to use the original. path\n should NOT be quoted. When building a url, a Webob\n Request (in accordance with wsgi spec) will quote\n env['PATH_INFO']. url += quote(environ['PATH_INFO'])\n :param query_string: The new query_string or none to use the original.\n When building a url, a Webob Request will append\n the query string directly to the url.\n url += '?' + env['QUERY_STRING']\n :param agent: The HTTP user agent to use; default 'Swift'. You\n can put %(orig)s in the agent to have it replaced\n with the original env's HTTP_USER_AGENT, such as\n '%(orig)s StaticWeb'. You also set agent to None to\n use the original env's HTTP_USER_AGENT or '' to\n have no HTTP_USER_AGENT.\n :param swift_source: Used to mark the request as originating out of\n middleware. Will be logged in proxy logs.\n :returns: Fresh WSGI environment.\n \"\"\"\n newenv = {}\n for name in ('HTTP_USER_AGENT', 'HTTP_HOST', 'PATH_INFO',\n 'QUERY_STRING', 'REMOTE_USER', 'REQUEST_METHOD',\n 'SCRIPT_NAME', 'SERVER_NAME', 'SERVER_PORT',\n 'HTTP_ORIGIN', 'HTTP_ACCESS_CONTROL_REQUEST_METHOD',\n 'SERVER_PROTOCOL', 'swift.cache', 'swift.source',\n 'swift.trans_id', 'swift.authorize_override',\n 'swift.authorize', 'HTTP_X_USER_ID', 'HTTP_X_PROJECT_ID',\n 'HTTP_REFERER', 'swift.infocache'):\n if name in env:\n newenv[name] = env[name]\n if method:\n newenv['REQUEST_METHOD'] = method\n if path:\n newenv['PATH_INFO'] = path\n newenv['SCRIPT_NAME'] = ''\n if query_string is not None:\n newenv['QUERY_STRING'] = query_string\n if agent:\n newenv['HTTP_USER_AGENT'] = (\n agent % {'orig': env.get('HTTP_USER_AGENT', '')}).strip()\n elif agent == '' and 'HTTP_USER_AGENT' in newenv:\n del newenv['HTTP_USER_AGENT']\n if swift_source:\n newenv['swift.source'] = swift_source\n newenv['wsgi.input'] = BytesIO()\n if 'SCRIPT_NAME' not in newenv:\n newenv['SCRIPT_NAME'] = ''\n return newenv\n\n\n# Taken from swift/common/request_helpers.py, commit 1962b18\ndef make_subrequest(env, method=None, path=None, body=None, headers=None,\n agent='Swift', swift_source=None, make_env=make_env):\n \"\"\"\n Makes a new swob.Request based on the current env but with the\n parameters specified.\n\n :param env: The WSGI environment to base the new request on.\n :param method: HTTP method of new request; default is from\n the original env.\n :param path: HTTP path of new request; default is from the\n original env. path should be compatible with what you\n would send to Request.blank. path should be quoted and it\n can include a query string. for example:\n '/a%20space?unicode_str%E8%AA%9E=y%20es'\n :param body: HTTP body of new request; empty by default.\n :param headers: Extra HTTP headers of new request; None by\n default.\n :param agent: The HTTP user agent to use; default 'Swift'. You\n can put %(orig)s in the agent to have it replaced\n with the original env's HTTP_USER_AGENT, such as\n '%(orig)s StaticWeb'. You also set agent to None to\n use the original env's HTTP_USER_AGENT or '' to\n have no HTTP_USER_AGENT.\n :param swift_source: Used to mark the request as originating out of\n middleware. Will be logged in proxy logs.\n :param make_env: make_subrequest calls this make_env to help build the\n swob.Request.\n :returns: Fresh swob.Request object.\n \"\"\"\n query_string = None\n path = path or ''\n if path and '?' in path:\n path, query_string = path.split('?', 1)\n newenv = make_env(env, method, path=text_to_wsgi(unquote(path)),\n agent=agent, query_string=query_string,\n swift_source=swift_source)\n if not headers:\n headers = {}\n if body:\n return Request.blank(path, environ=newenv, body=body, headers=headers)\n else:\n return Request.blank(path, environ=newenv, headers=headers)\n\n\n# Taken from swift/common/http.py, commit 1962b18\ndef is_success(status):\n \"\"\"\n Check if HTTP status code is successful.\n\n :param status: http status code\n :returns: True if status is successful, else False\n \"\"\"\n return 200 <= status <= 299\n\n\n# Taken from swift/common/utils.py, commit 1962b18\n_rfc_token = r'[^()<>@,;:\\\"/\\[\\]?={}\\x00-\\x20\\x7f]+'\n_rfc_extension_pattern = re.compile(\n r'(?:\\s*;\\s*(' + _rfc_token + r\")\\s*(?:=\\s*(\" + _rfc_token +\n r'|\"(?:[^\"\\\\]|\\\\.)*\"))?)')\n\n\n# Taken from swift/common/utils.py, commit 1962b18\ndef parse_content_type(content_type):\n \"\"\"\n Parse a content-type and its parameters into values.\n RFC 2616 sec 14.17 and 3.7 are pertinent.\n\n **Examples**::\n\n 'text/plain; charset=UTF-8' -> ('text/plain', [('charset, 'UTF-8')])\n 'text/plain; charset=UTF-8; level=1' ->\n ('text/plain', [('charset, 'UTF-8'), ('level', '1')])\n\n :param content_type: content_type to parse\n :returns: a tuple containing (content type, list of k, v parameter tuples)\n \"\"\"\n parm_list = []\n if ';' in content_type:\n content_type, parms = content_type.split(';', 1)\n parms = ';' + parms\n for m in _rfc_extension_pattern.findall(parms):\n key = m[0].strip()\n value = m[1].strip()\n parm_list.append((key, value))\n return content_type, parm_list\n\n\n# Taken from swift/common/utils.py, commit 1962b18\ndef parse_mime_headers(doc_file):\n \"\"\"\n Takes a file-like object containing a MIME document and returns a\n HeaderKeyDict containing the headers. The body of the message is not\n consumed: the position in doc_file is left at the beginning of the body.\n\n This function was inspired by the Python standard library's\n http.client.parse_headers.\n\n :param doc_file: binary file-like object containing a MIME document\n :returns: a swift.common.swob.HeaderKeyDict containing the headers\n \"\"\"\n headers = []\n while True:\n line = doc_file.readline()\n done = line in (b'\\r\\n', b'\\n', b'')\n if six.PY3:\n try:\n line = line.decode('utf-8')\n except UnicodeDecodeError:\n line = line.decode('latin1')\n headers.append(line)\n if done:\n break\n if six.PY3:\n header_string = ''.join(headers)\n else:\n header_string = b''.join(headers)\n headers = email.parser.Parser().parsestr(header_string)\n return HeaderKeyDict(headers)\n\n\n# Taken from swift/common/utils.py, commit 1962b18\ndef maybe_multipart_byteranges_to_document_iters(app_iter, content_type):\n \"\"\"\n Takes an iterator that may or may not contain a multipart MIME document\n as well as content type and returns an iterator of body iterators.\n\n :param app_iter: iterator that may contain a multipart MIME document\n :param content_type: content type of the app_iter, used to determine\n whether it conains a multipart document and, if\n so, what the boundary is between documents\n \"\"\"\n content_type, params_list = parse_content_type(content_type)\n if content_type != 'multipart/byteranges':\n yield app_iter\n return\n\n body_file = FileLikeIter(app_iter)\n boundary = dict(params_list)['boundary']\n for _headers, body in mime_to_document_iters(body_file, boundary):\n yield (chunk for chunk in iter(lambda: body.read(65536), ''))\n\n\n# Taken from swift/common/utils.py, commit 1962b18\ndef mime_to_document_iters(input_file, boundary, read_chunk_size=4096):\n \"\"\"\n Takes a file-like object containing a multipart MIME document and\n returns an iterator of (headers, body-file) tuples.\n\n :param input_file: file-like object with the MIME doc in it\n :param boundary: MIME boundary, sans dashes\n (e.g. \"divider\", not \"--divider\")\n :param read_chunk_size: size of strings read via input_file.read()\n \"\"\"\n doc_files = iter_multipart_mime_documents(input_file, boundary,\n read_chunk_size)\n for i, doc_file in enumerate(doc_files):\n # this consumes the headers and leaves just the body in doc_file\n headers = parse_mime_headers(doc_file)\n yield (headers, doc_file)\n\n\n# Taken from swift/common/utils.py, commit 1962b18\n#\n# Modified to use different exception classes.\ndef iter_multipart_mime_documents(wsgi_input, boundary, read_chunk_size=4096):\n \"\"\"\n Given a multi-part-mime-encoded input file object and boundary,\n yield file-like objects for each part. Note that this does not\n split each part into headers and body; the caller is responsible\n for doing that if necessary.\n\n :param wsgi_input: The file-like object to read from.\n :param boundary: The mime boundary to separate new file-like\n objects on.\n :returns: A generator of file-like objects for each part.\n :raises MimeInvalid: if the document is malformed\n \"\"\"\n boundary = '--' + boundary\n blen = len(boundary) + 2 # \\r\\n\n try:\n got = wsgi_input.readline(blen)\n while got == '\\r\\n':\n got = wsgi_input.readline(blen)\n except (IOError, ValueError) as e:\n raise ChunkReadError(str(e))\n\n if got.strip() != boundary:\n raise MimeInvalid(\n 'invalid starting boundary: wanted %r, got %r', (boundary, got))\n boundary = '\\r\\n' + boundary\n input_buffer = ''\n done = False\n while not done:\n it = _MultipartMimeFileLikeObject(wsgi_input, boundary, input_buffer,\n read_chunk_size)\n yield it\n done = it.no_more_files\n input_buffer = it.input_buffer\n\n\n# Taken from swift/common/utils.py, commit 1962b18\nclass FileLikeIter(object):\n\n def __init__(self, iterable):\n \"\"\"\n Wraps an iterable to behave as a file-like object.\n\n The iterable must yield bytes strings.\n \"\"\"\n self.iterator = iter(iterable)\n self.buf = None\n self.closed = False\n\n def __iter__(self):\n return self\n\n def next(self):\n \"\"\"\n next(x) -> the next value, or raise StopIteration\n \"\"\"\n if self.closed:\n raise ValueError('I/O operation on closed file')\n if self.buf:\n rv = self.buf\n self.buf = None\n return rv\n else:\n return next(self.iterator)\n __next__ = next\n\n def read(self, size=-1):\n \"\"\"\n read([size]) -> read at most size bytes, returned as a bytes string.\n\n If the size argument is negative or omitted, read until EOF is reached.\n Notice that when in non-blocking mode, less data than what was\n requested may be returned, even if no size parameter was given.\n \"\"\"\n if self.closed:\n raise ValueError('I/O operation on closed file')\n if size < 0:\n return b''.join(self)\n elif not size:\n chunk = b''\n elif self.buf:\n chunk = self.buf\n self.buf = None\n else:\n try:\n chunk = next(self.iterator)\n except StopIteration:\n return b''\n if len(chunk) > size:\n self.buf = chunk[size:]\n chunk = chunk[:size]\n return chunk\n\n def readline(self, size=-1):\n \"\"\"\n readline([size]) -> next line from the file, as a bytes string.\n\n Retain newline. A non-negative size argument limits the maximum\n number of bytes to return (an incomplete line may be returned then).\n Return an empty string at EOF.\n \"\"\"\n if self.closed:\n raise ValueError('I/O operation on closed file')\n data = b''\n while b'\\n' not in data and (size < 0 or len(data) < size):\n if size < 0:\n chunk = self.read(1024)\n else:\n chunk = self.read(size - len(data))\n if not chunk:\n break\n data += chunk\n if b'\\n' in data:\n data, sep, rest = data.partition(b'\\n')\n data += sep\n if self.buf:\n self.buf = rest + self.buf\n else:\n self.buf = rest\n return data\n\n def readlines(self, sizehint=-1):\n \"\"\"\n readlines([size]) -> list of bytes strings, each a line from the file.\n\n Call readline() repeatedly and return a list of the lines so read.\n The optional size argument, if given, is an approximate bound on the\n total number of bytes in the lines returned.\n \"\"\"\n if self.closed:\n raise ValueError('I/O operation on closed file')\n lines = []\n while True:\n line = self.readline(sizehint)\n if not line:\n break\n lines.append(line)\n if sizehint >= 0:\n sizehint -= len(line)\n if sizehint <= 0:\n break\n return lines\n\n def close(self):\n \"\"\"\n close() -> None or (perhaps) an integer. Close the file.\n\n Sets data attribute .closed to True. A closed file cannot be used for\n further I/O operations. close() may be called more than once without\n error. Some kinds of file objects (for example, opened by popen())\n may return an exit status upon closing.\n \"\"\"\n self.iterator = None\n self.closed = True\n\n\n# Taken from swift/common/request_helpers.py, commit 1962b18\n#\n# Modified to use different exception classes.\nclass SegmentedIterable(object):\n \"\"\"\n Iterable that returns the object contents for a large object.\n\n :param req: original request object\n :param app: WSGI application from which segments will come\n\n :param listing_iter: iterable yielding the object segments to fetch,\n along with the byte subranges to fetch, in the form of a 5-tuple\n (object-path, object-etag, object-size, first-byte, last-byte).\n\n If object-etag is None, no MD5 verification will be done.\n\n If object-size is None, no length verification will be done.\n\n If first-byte and last-byte are None, then the entire object will be\n fetched.\n\n :param max_get_time: maximum permitted duration of a GET request (seconds)\n :param logger: logger object\n :param swift_source: value of swift.source in subrequest environ\n (just for logging)\n :param ua_suffix: string to append to user-agent.\n :param name: name of manifest (used in logging only)\n :param response_body_length: optional response body length for\n the response being sent to the client.\n \"\"\"\n\n def __init__(self, req, app, listing_iter, max_get_time,\n logger, ua_suffix, swift_source,\n name='', response_body_length=None):\n self.req = req\n self.app = app\n self.listing_iter = listing_iter\n self.max_get_time = max_get_time\n self.logger = logger\n self.ua_suffix = \" \" + ua_suffix\n self.swift_source = swift_source\n self.name = name\n self.response_body_length = response_body_length\n self.peeked_chunk = None\n self.app_iter = self._internal_iter()\n self.validated_first_segment = False\n self.current_resp = None\n\n def _coalesce_requests(self):\n start_time = time.time()\n pending_req = None\n pending_etag = None\n pending_size = None\n try:\n for seg_path, seg_etag, seg_size, first_byte, last_byte \\\n in self.listing_iter:\n first_byte = first_byte or 0\n go_to_end = last_byte is None or (\n seg_size is not None and last_byte == seg_size - 1)\n if time.time() - start_time > self.max_get_time:\n raise SegmentError(\n 'While processing manifest %s, '\n 'max LO GET time of %ds exceeded' %\n (self.name, self.max_get_time))\n # The \"multipart-manifest=get\" query param ensures that the\n # segment is a plain old object, not some flavor of large\n # object; therefore, its etag is its MD5sum and hence we can\n # check it.\n path = seg_path + '?multipart-manifest=get'\n seg_req = make_subrequest(\n self.req.environ, path=path, method='GET',\n headers={'x-auth-token': self.req.headers.get(\n 'x-auth-token')},\n agent=('%(orig)s ' + self.ua_suffix),\n swift_source=self.swift_source)\n\n seg_req_rangeval = None\n if first_byte != 0 or not go_to_end:\n seg_req_rangeval = \"%s-%s\" % (\n first_byte, '' if go_to_end else last_byte)\n seg_req.headers['Range'] = \"bytes=\" + seg_req_rangeval\n\n # We can only coalesce if paths match and we know the segment\n # size (so we can check that the ranges will be allowed)\n if pending_req and pending_req.path == seg_req.path and \\\n seg_size is not None:\n\n # Make a new Range object so that we don't goof up the\n # existing one in case of invalid ranges. Note that a\n # range set with too many individual byteranges is\n # invalid, so we can combine N valid byteranges and 1\n # valid byterange and get an invalid range set.\n if pending_req.range:\n new_range_str = str(pending_req.range)\n else:\n new_range_str = \"bytes=0-%d\" % (seg_size - 1)\n\n if seg_req.range:\n new_range_str += \",\" + seg_req_rangeval\n else:\n new_range_str += \",0-%d\" % (seg_size - 1)\n\n if Range(new_range_str).ranges_for_length(seg_size):\n # Good news! We can coalesce the requests\n pending_req.headers['Range'] = new_range_str\n continue\n # else, Too many ranges, or too much backtracking, or ...\n\n if pending_req:\n yield pending_req, pending_etag, pending_size\n pending_req = seg_req\n pending_etag = seg_etag\n pending_size = seg_size\n\n except ListingIterError:\n e_type, e_value, e_traceback = sys.exc_info()\n if time.time() - start_time > self.max_get_time:\n raise SegmentError(\n 'While processing manifest %s, '\n 'max LO GET time of %ds exceeded' %\n (self.name, self.max_get_time))\n if pending_req:\n yield pending_req, pending_etag, pending_size\n six.reraise(e_type, e_value, e_traceback)\n\n if time.time() - start_time > self.max_get_time:\n raise SegmentError(\n 'While processing manifest %s, '\n 'max LO GET time of %ds exceeded' %\n (self.name, self.max_get_time))\n if pending_req:\n yield pending_req, pending_etag, pending_size\n\n def _internal_iter(self):\n bytes_left = self.response_body_length\n\n try:\n for seg_req, seg_etag, seg_size in self._coalesce_requests():\n seg_resp = seg_req.get_response(self.app)\n if not is_success(seg_resp.status_int):\n close_if_possible(seg_resp.app_iter)\n raise SegmentError(\n 'While processing manifest %s, '\n 'got %d while retrieving %s' %\n (self.name, seg_resp.status_int, seg_req.path))\n\n elif ((seg_etag and (seg_resp.etag != seg_etag)) or\n (seg_size and (seg_resp.content_length != seg_size) and\n not seg_req.range)):\n # The content-length check is for security reasons. Seems\n # possible that an attacker could upload a >1mb object and\n # then replace it with a much smaller object with same\n # etag. Then create a big nested SLO that calls that\n # object many times which would hammer our obj servers. If\n # this is a range request, don't check content-length\n # because it won't match.\n close_if_possible(seg_resp.app_iter)\n raise SegmentError(\n 'Object segment no longer valid: '\n '%(path)s etag: %(r_etag)s != %(s_etag)s or '\n '%(r_size)s != %(s_size)s.' %\n {'path': seg_req.path, 'r_etag': seg_resp.etag,\n 'r_size': seg_resp.content_length,\n 's_etag': seg_etag,\n 's_size': seg_size})\n else:\n self.current_resp = seg_resp\n\n seg_hash = None\n if seg_resp.etag and not seg_req.headers.get('Range'):\n # Only calculate the MD5 if it we can use it to validate\n seg_hash = hashlib.md5()\n\n document_iters = maybe_multipart_byteranges_to_document_iters(\n seg_resp.app_iter,\n seg_resp.headers['Content-Type'])\n\n for chunk in itertools.chain.from_iterable(document_iters):\n if seg_hash:\n seg_hash.update(chunk)\n\n if bytes_left is None:\n yield chunk\n elif bytes_left >= len(chunk):\n yield chunk\n bytes_left -= len(chunk)\n else:\n yield chunk[:bytes_left]\n bytes_left -= len(chunk)\n close_if_possible(seg_resp.app_iter)\n raise SegmentError(\n 'Too many bytes for %(name)s; truncating in '\n '%(seg)s with %(left)d bytes left' %\n {'name': self.name, 'seg': seg_req.path,\n 'left': bytes_left})\n close_if_possible(seg_resp.app_iter)\n\n if seg_hash and seg_hash.hexdigest() != seg_resp.etag:\n raise SegmentError(\n \"Bad MD5 checksum in %(name)s for %(seg)s: headers had\"\n \" %(etag)s, but object MD5 was actually %(actual)s\" %\n {'seg': seg_req.path, 'etag': seg_resp.etag,\n 'name': self.name, 'actual': seg_hash.hexdigest()})\n\n if bytes_left:\n raise SegmentError(\n 'Not enough bytes for %s; closing connection' % self.name)\n except (ListingIterError, SegmentError) as err:\n self.logger.error(err)\n if not self.validated_first_segment:\n raise\n finally:\n if self.current_resp:\n close_if_possible(self.current_resp.app_iter)\n\n def app_iter_range(self, *a, **kw):\n \"\"\"\n swob.Response will only respond with a 206 status in certain cases; one\n of those is if the body iterator responds to .app_iter_range().\n\n However, this object (or really, its listing iter) is smart enough to\n handle the range stuff internally, so we just no-op this out for swob.\n \"\"\"\n return self\n\n def app_iter_ranges(self, ranges, content_type, boundary, content_size):\n \"\"\"\n This method assumes that iter(self) yields all the data bytes that\n go into the response, but none of the MIME stuff. For example, if\n the response will contain three MIME docs with data \"abcd\", \"efgh\",\n and \"ijkl\", then iter(self) will give out the bytes \"abcdefghijkl\".\n\n This method inserts the MIME stuff around the data bytes.\n \"\"\"\n si = Spliterator(self)\n mri = multi_range_iterator(\n ranges, content_type, boundary, content_size,\n lambda start, end_plus_one: si.take(end_plus_one - start))\n try:\n for x in mri:\n yield x\n finally:\n self.close()\n\n def validate_first_segment(self):\n \"\"\"\n Start fetching object data to ensure that the first segment (if any) is\n valid. This is to catch cases like \"first segment is missing\" or\n \"first segment's etag doesn't match manifest\".\n\n Note: this does not validate that you have any segments. A\n zero-segment large object is not erroneous; it is just empty.\n \"\"\"\n if self.validated_first_segment:\n return\n\n try:\n self.peeked_chunk = next(self.app_iter)\n except StopIteration:\n pass\n finally:\n self.validated_first_segment = True\n\n def __iter__(self):\n if self.peeked_chunk is not None:\n pc = self.peeked_chunk\n self.peeked_chunk = None\n return itertools.chain([pc], self.app_iter)\n else:\n return self.app_iter\n\n def close(self):\n \"\"\"\n Called when the client disconnect. Ensure that the connection to the\n backend server is closed.\n \"\"\"\n close_if_possible(self.app_iter)\n\n\n# Taken from swift/common/utils.py, commit e001c02\ndef list_from_csv(comma_separated_str):\n \"\"\"\n Splits the str given and returns a properly stripped list of the comma\n separated values.\n \"\"\"\n if comma_separated_str:\n return [v.strip() for v in comma_separated_str.split(',') if v.strip()]\n return []\n\n\n# Taken from swift/common/request_helpers.py, commit e001c02\ndef resolve_etag_is_at_header(req, metadata):\n \"\"\"\n Helper function to resolve an alternative etag value that may be stored in\n metadata under an alternate name.\n\n The value of the request's X-Backend-Etag-Is-At header (if it exists) is a\n comma separated list of alternate names in the metadata at which an\n alternate etag value may be found. This list is processed in order until an\n alternate etag is found.\n\n The left most value in X-Backend-Etag-Is-At will have been set by the left\n most middleware, or if no middleware, by ECObjectController, if an EC\n policy is in use. The left most middleware is assumed to be the authority\n on what the etag value of the object content is.\n\n The resolver will work from left to right in the list until it finds a\n value that is a name in the given metadata. So the left most wins, IF it\n exists in the metadata.\n\n By way of example, assume the encrypter middleware is installed. If an\n object is *not* encrypted then the resolver will not find the encrypter\n middleware's alternate etag sysmeta (X-Object-Sysmeta-Crypto-Etag) but will\n then find the EC alternate etag (if EC policy). But if the object *is*\n encrypted then X-Object-Sysmeta-Crypto-Etag is found and used, which is\n correct because it should be preferred over X-Object-Sysmeta-Crypto-Etag.\n\n :param req: a swob Request\n :param metadata: a dict containing object metadata\n :return: an alternate etag value if any is found, otherwise None\n \"\"\"\n alternate_etag = None\n metadata = HeaderKeyDict(metadata)\n if \"X-Backend-Etag-Is-At\" in req.headers:\n names = list_from_csv(req.headers[\"X-Backend-Etag-Is-At\"])\n for name in names:\n if name in metadata:\n alternate_etag = metadata[name]\n break\n return alternate_etag\n\n\n# Taken from swift/proxy/controllers/container.py, commit e001c02\n#\n# Modified to no longer dangle off a controller\ndef clean_acls(req):\n if 'swift.clean_acl' in req.environ:\n for header in ('x-container-read', 'x-container-write'):\n if header in req.headers:\n try:\n req.headers[header] = \\\n req.environ['swift.clean_acl'](header,\n req.headers[header])\n except ValueError as err:\n return HTTPBadRequest(request=req, body=str(err))\n return None\n\n\n# Taken from swift/common/swob.py, commit a5a6a27\n#\n# Modified to pass through Nones\ndef wsgi_to_str(wsgi_str):\n if six.PY2 or wsgi_str is None:\n return wsgi_str\n return wsgi_str.encode('latin1').decode('utf8', errors='surrogateescape')\n\n\ndef str_to_wsgi(native_str):\n if six.PY2 or native_str is None:\n return native_str\n return native_str.encode('utf8', errors='surrogateescape').decode('latin1')\n\n\ndef bytes_to_wsgi(byte_str):\n if six.PY2:\n return byte_str\n return byte_str.decode('latin1')\n\n\n# this isn't in swift\ndef text_to_wsgi(text):\n if six.PY2 and isinstance(text, six.text_type):\n return text.encode('utf-8')\n return text\n","sub_path":"pfs_middleware/pfs_middleware/swift_code.py","file_name":"swift_code.py","file_ext":"py","file_size_in_byte":41722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"361802268","text":"# Script to add wind vectors to a general 2D view of the LA-TX coast\r\n\r\n# This script must be used with a ParaView visualization made from combined fort.63.nc and fort.74.nc data\r\n# the XDMF file to be opened with ParaView should be named like this: fort.63.nc_fort.74.nc.xmf\r\n\r\n#### import the simple module from the paraview\r\nfrom paraview.simple import *\r\n#### disable automatic camera reset on 'Show'\r\nparaview.simple._DisableFirstRenderCameraReset()\r\n\r\nrenderView1 = GetActiveViewOrCreate('RenderView')\r\ngeneralSource = FindSource('fort.63.nc_fort.74.nc.xmf')\r\n\r\n# create a new 'Surface Vectors'\r\nsurfaceVectors1 = SurfaceVectors(Input=generalSource)\r\nsurfaceVectors1.SelectInputVectors = ['POINTS', 'windVel']\r\nsurfaceVectors1Display = Show(surfaceVectors1, renderView1, 'UnstructuredGridRepresentation')\r\n\r\n# create a new 'Glyph'\r\nglyph1 = Glyph(Input=surfaceVectors1, GlyphType='2D Glyph')\r\nglyph1.OrientationArray = ['POINTS', 'windVel']\r\nglyph1.GlyphTransform = 'Transform2'\r\nglyph1.ScaleArray = ['POINTS', 'windVel']\r\n# This scale factor is intended for hurricane-level winds; it will be too small for normal winds\r\nglyph1.ScaleFactor = 0.01\r\nglyph1.MaximumNumberOfSamplePoints = 10000\r\n\r\nglyph1Display = Show(glyph1, renderView1, 'GeometryRepresentation')\r\n\r\n# turn off scalar coloring\r\nColorBy(glyph1Display, None)\r\n\r\n# Properties modified on glyph1\r\nglyph1.GlyphMode = 'Uniform Spatial Distribution (Surface Sampling)'\r\n\r\n# update the view to ensure updated data information\r\nrenderView1.Update()","sub_path":"la-tx-vis/la-tx-general/windVecLATX2D.py","file_name":"windVecLATX2D.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"544760888","text":"\"\"\"\nThis file contains one class:\n Mouth\n\"\"\"\nfrom angle import Angle\nfrom scanner import Scanner\nfrom settings import MouthSettings\n\n\n# DO NOT MODIFY THIS CLASS!\n#\nclass SideOfMouth:\n\n def __init__(self,data):\n self._data = data # A dictionary with three keys:\n # 'circles'\n # 'headings'\n # 'lengths'\n # The value for each key is a list of int values.\n\n def draw(self,pen):\n data = self._data\n pen.up()\n pen.home()\n pen.setheading(Angle.EAST)\n pen.forward(data['lengths'][0])\n pen.setheading(Angle.NORTH)\n pen.forward(30)\n pen.down()\n pen.setheading(data['headings'][0])\n pen.circle(data['circles'][0],90)\n pen.setheading(data['headings'][1])\n pen.circle(data['circles'][1],12)\n pen.setheading(data['headings'][2])\n pen.circle(data['circles'][2],17)\n\n\nclass Mouth:\n\n # DO NOT MODIFY THIS METHOD!\n #\n def __init__(self):\n self._sides = []\n\n self._create_sides()\n\n # DO NOT MODIFY THIS METHOD!\n #\n def draw(self,pen):\n for side in self._sides:\n side.draw(pen)\n\n # IMPLEMENT THIS METHOD\n #\n # Reads MouthSettings.MouthFile\n #\n # See the file for details of its format.\n #\n def _create_sides(self):\n #\n # REPLACE THE FOLLOWING CODE WITH YOUR OWN\n #\n # This dummy code allows the program to run.\n #\n self._sides.append(SideOfMouth({'headings':[320,215,92],'lengths':[22],'circles':[-18,225,-155]}))\n self._sides.append(SideOfMouth({'headings':[120,185,32],'lengths':[-22],'circles':[18,-225,155]}))\n","sub_path":"mouth.py","file_name":"mouth.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"607544924","text":"d = {\"Египет\": \"yyyy\", \"Алжир\": \"yyyn\", \"Германия\": \"nnyy\", \"Швеция\": \"nnyn\", \"Филиппины\": \"nnny\", \"Ливия\": \"nyyy\",\n \"Англия\": \"ynyn\", \"Испания\": \"ynyy\", \"Афганистан\":\"ynnn\", \"Зимбабве\":\"nynn\", \"Мадагаскар\":\"nyny\", \"Япония\":\"ynny\",\n \"Гана\":\"yyny\", \"Чад\":\"yynn\", \"Китай\":\"nnnn\", \"Тунис\":\"nyyn\"}\nd1 = {}\n\nfor k,v in d.items():\n d1[v] = k\n#Неправильно составил словарь вначале, лень было переписывать\n \nprint(\"Доступный список стран: Египет, Алжи, Германия, Швеция, Филиппины, Ливия, Англия, Испания,\\nАфганистан, Зимбабве, Мадагаскар, Япония, Гана, Чад, Китай, Тунис\\n\")\ns = ''\na = input(\"Ваша страна начинатся на гласную букву? (Y/N)\\n\")\ns += a\nif a == 'y':\n a = input(\"Ваша страна находится на материке 'Африка'?\\n\")\n s += a\n if a == 'y':\n a = input('Ваша страна омывается средиземным морем?\\n')\n s += a\n if a == 'y':\n a = input('Столица вашей страны Каир?\\n')\n s += a\n else:\n a = input('Название вашей страны состоит из 4 букв?\\n')\n s += a\n else:\n a = input('Ваша страна находится в Европейской части материка \"Евразия\"?\\n')\n s += a\n if a == 'y':\n a = input('Является ли хамон национальным блюдом вашей страны?\\n')\n s += a\n else:\n a = input('Является ли суши национальным блюдом вашей страны?\\n')\n s += a\nelse:\n a = input(\"Ваша страна находится на материке 'Африка'?\\n\")\n s += a\n if a == 'y':\n a = input('Ваша страна омывается средиземным морем?\\n')\n s += a\n if a == 'y':\n a = input('Столица вашей страны Триполи?\\n')\n s += a\n else:\n a = input('Ваша страна это островное государство?\\n')\n s += a\n else:\n a = input('Ваша страна находится в Европейской части материка \"Евразия\"?\\n')\n s += a\n if a == 'y':\n a = input('Национальным языком вашей страны является немецкий?\\n')\n s += a\n else:\n a = input('Ваша страна это островное государство?\\n')\n s += a\nprint(d1[s])\n","sub_path":"lab_1/lab1_1.py","file_name":"lab1_1.py","file_ext":"py","file_size_in_byte":2919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"623393085","text":"import csv\nimport typer\nimport httpx\nimport asyncio\n\ncsv.field_size_limit(csv.field_size_limit() * 5)\n\n\ndef get_data(csvfilepath: str = \"/tmp/all_the_news/all-the-news-2-1.csv\"):\n ''' File column structure:\n 0-7: (unused)\n 8: content\n 9-10: (unused)\n 11: publication\n '''\n with open(csvfilepath) as f:\n for row in csv.reader(f):\n yield {'content': row[8], 'publication': row[11]}\n\n\nasync def upload_to_uri(uri: str, record_count):\n async with httpx.AsyncClient(verify=False, http2=True, headers={\"access_token\": \"ijdf8h74nj\"}) as c:\n row = get_data()\n next(row) # Remove the header row\n for _ in range(record_count):\n await c.post(uri, json=next(row), timeout=3)\n\n print(f\"submitted {record_count} records\")\n\n\ndef runner(uri: str = 'http://0.0.0.0:8000/post/enqueue', record_count: int = 10):\n asyncio.run(upload_to_uri(uri, record_count))\n\n\ndef main():\n typer.run(runner)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"simulator/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"256071135","text":"from socket import AF_INET, SOCK_DGRAM, socket, timeout\nfrom packet import Packet\nfrom struct import unpack, pack\nimport sys\nimport string\nimport random\nimport select\n\nhost=\"0.0.0.0\"\nport = 6000\ns = socket(AF_INET,SOCK_DGRAM)\ns.bind((host,port))\n\nbuf=327\n\n\ndef randomString(stringLength=10):\n \"\"\"Generate a random string of fixed length \"\"\"\n letters = string.ascii_lowercase\n return ''.join(random.choice(letters) for i in range(stringLength))\n\ndef processPacket(package,addr):\n header, seqNumber, lengthPack, checksum = unpack('>cHHH',package[:7])\n headInt = int.from_bytes(header, byteorder = 'big')\n typePack = (headInt >> 4) & 15\n idPack = headInt >> 4\n print(\"This is the type: \", typePack)\n print(\"This is the ID:\",idPack)\n print(\"This is the seqNum: \",seqNumber)\n print(\"This is the length: \",lengthPack)\n print(\"This is the checksum: \", checksum)\n \n if(typePack == 0) :\n typePkg = \"ACK\"\n else :\n typePkg = \"FIN-ACK\"\n\n pkg = Packet(typePkg, idPack, seqNumber, lengthPack, checksum)\n a = pkg.getType()\n b = idPack()\n typeID = (a << 4) | b\n typeID = typeID.to_bytes(1, 'big')\n\n ACKPack = pack('cHHH', typeID,seqNumber,lengthPack,checksum)\n s.sendto(ACKPack,addr) #Sends ACK to sender\n\n\nf = open(randomString(10),'wb+')\n\npackage,addr = s.recvfrom(buf)\nprocessPacket(package,addr)\ndata = package[7:]\n#print(\"file received:\",data)\ntry:\n while(package):\n f.write(data)\n s.settimeout(2)\n package,addr = s.recvfrom(buf)\n processPacket(package,addr)\n data = package[7:]\n #print(\"file received\",data)\n\nexcept timeout:\n f.close()\n s.close()\n print(\"File Downloaded\")","sub_path":"receiver.py","file_name":"receiver.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"431687582","text":"#!/usr/bin/python3\n\nimport hashlib\nimport time\nimport re\nimport random\nimport base64\nimport timeit\n\ndef proof_for_work(mail, bits) :\n random.seed()\n stime = timeit.default_timer()\n\n # x-hashcash\n ver = 1\n date = time.strftime(\"%y%m%d%H%M%S\")\n resource = mail\n randhex = \"\"\n for i in range(3) :\n randhex += hex(random.randint(0x41, 0x7a))\n rand = base64.b64encode(randhex.encode()).decode()\n counter = 0\n\n while (True) :\n b64counter = base64.b64encode(\"{}\".format(counter).encode()).decode()\n msg = \"{}:{}:{}:{}:{}:{}\".format(ver, bits, date, resource, rand, b64counter)\n counter += 1\n hashcode = hashlib.sha256(msg.encode()).hexdigest()\n m = re.search(\"^0+\", hashcode)\n if m is not None and len(m.group(0)) == bits :\n break\n\n return msg, hashcode, (timeit.default_timer() - stime)\n\ndef main() :\n msg, hashcode, sec = proof_for_work(\"jeff_yu@pegatroncorp.com\", 4)\n print(\"{} | {} | {} secs\".format(msg, hashcode, sec))\n msg, hashcode, sec = proof_for_work(\"jeff_yu@pegatroncorp.com\", 6)\n print(\"{} | {} | {} secs\".format(msg, hashcode, sec))\n\nif __name__ == \"__main__\" :\n main()\n","sub_path":"data_security/hashcash.py","file_name":"hashcash.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"512193981","text":"#!/usr/bin/env python3\n#-*- coding:utf-8 -*-\n\n\"\"\"\nVery basic 2D abstract geometry package. It defines these geometrical\nconstructs:\n\n * `GeometricObject` - abstract base class, not meant to be used\n directly\n * `Point`\n * `Vector`\n * `BoundingBox`\n * `Line`\n * `Ray`\n * `Segment`\n * `Polygon`\n * ...for now\n\nNotes\n-----\n\nExcept for the `Point` and `Vector` classes which will be discussed below, all\nof the other classes define a `__getitem__` method that can be used to retreive\nthe points defining the `GeometricObject` by indices.\n\nThe `Point` class defines the `__getitem__` method in a sperate way,\ni.e. it returns the Cartesian coordinates of the `Point` by indinces.\nThe `Vector` class does the same except it returns the x & y Cartesian\ncoordinates in this case.\n\"\"\"\n\n# system modules\nimport math\nimport random\n# user defined module\nimport geo2d_utils as u\n\n\n# acceptable uncertainty for calculating intersections and such\nUNCERTAINTY = 1e-5\n\n\ndef get_perpendicular_to(obj, at_point=None):\n \"\"\"\n Creates a new `Vector` or `Line` perpendicular with\n `obj` (`Vector` or `Line`-like) depending on `at_point`\n parameter.\n\n The perpendicular vector to the `obj` is not necessarily the unit\n `Vector`.\n\n Parameters\n ----------\n obj : vector, line-like\n The object to retreive the perpendicular vector to.\n at_point : point-like, optional\n If this is given then a `Line` is returned instead,\n perpendicular to `obj` and passing through `at_point`.\n\n Returns\n -------\n out : vector\n A new `Vector` or `Line` passing through `at_point`\n with the components in such a way it is perpendicular with `obj`..\n\n Raises\n ------\n TypeError:\n If `obj` is not `Vector` nor `Line`-like or if\n `at_point` is not point-like.\n \"\"\"\n\n if not isinstance(obj, (Vector, Line)):\n raise TypeError('Expected vector or line-like, but got: '\n '{0} instead.'.format(obj))\n if not Point.is_point_like(at_point) and at_point is not None:\n raise TypeError('Expected point-like, but got: '\n '{0} instead.'.format(at_point))\n if isinstance(obj, Line):\n # if it's Line-like get the directional vector\n obj = obj.v\n # this is the Vector defining the direction of the perpendicular\n perpendicular_vector = Vector(1, obj.phi + math.pi/2, coordinates='polar')\n if Point.is_point_like(at_point):\n # if at_point was also provided then return a Line\n # passing through that point which is perpendicular to obj\n return Line(at_point, perpendicular_vector)\n # if not just return the perpendicular_vector\n return perpendicular_vector\n\n\nclass GeometricObject(object):\n \"\"\"\n Abstract geometric object class.\n\n It's not meant to be used directly. This only implements methods that\n are called on other objects.\n \"\"\"\n\n def __str__(self, **kwargs):\n return '{0}({1})'.format(type(self).__name__, kwargs)\n\n def __contains__(self, x):\n \"\"\"\n Searches for x in \"itself\". If we're talking about a `Point`\n or a `Vector` then this searches within their components (x,\n y). For everything else it searches within the list of points\n (vertices).\n\n Parameters\n ----------\n x : {point, scalar}\n The object to search for.\n\n Returns\n -------\n out : {True, False}\n `True` if we find `x` in `self`, else `False`.\n \"\"\"\n\n try:\n next(i for i in self if i == x)\n return True\n except StopIteration:\n return False\n\n def intersection(self, obj):\n \"\"\"\n Return points of intersection if any.\n\n This method just calls the intersection method on the other objects\n that have it implemented.\n\n Parameters\n ----------\n obj : geometric object\n `obj` is any object that has intersection implemented.\n\n Returns\n -------\n ret : {point, None}\n The point of intersection if any, if not, just `None`.\n \"\"\"\n return obj.intersection(self)\n\n def translate(self, dx, dy):\n \"\"\"\n Translate `self` by given amounts on x and y.\n\n Parameters\n ----------\n dx, dy : scalar\n Amount to translate (relative movement).\n \"\"\"\n if isinstance(self, Polygon):\n # we don't want to include the last point since that's also the\n # first point and if we were to translate it, it would end up being\n # translated two times\n sl = slice(0, -1)\n else:\n sl = slice(None)\n for p in self[sl]:\n p.translate(dx, dy)\n\n def rotate(self, theta, point=None, angle='degrees'):\n \"\"\"\n Rotate `self` around pivot `point`.\n\n Parameters\n ----------\n theta : scalar\n The angle to be rotated by.\n point : {point-like}, optional\n If given this will be used as the rotation pivot.\n angle : {'degrees', 'radians'}, optional\n This tells the function how `theta` is passed: as degrees or as\n radians. Default is degrees.\n \"\"\"\n\n polygon_list = None\n if isinstance(self, Polygon):\n # we don't want to include the last point since that's also the\n # first point and if we were to rotate it, it would end up being\n # rotated two times\n sl = slice(0, -1)\n # we are going to create a new Polygon actually after rotation\n # since it's much easier to do it this way\n polygon_list = []\n else:\n sl = slice(None)\n for p in self[sl]:\n # rotate each individual point\n p.rotate(theta, point, angle)\n if polygon_list is not None:\n polygon_list.append(p)\n if polygon_list:\n # in the case of Polygon we build a new rotated one\n self = Polygon(polygon_list)\n else:\n # in case of other GeometricObjects\n self._v = Vector(self.p1, self.p2).normalized\n # reset former cached values in self\n if hasattr(self, '_cached'):\n self._cached = {}\n\n\nclass Point(GeometricObject):\n \"\"\"\n An abstract mathematical point.\n\n It can be built by passing no parameters to the constructor,\n this way having the origin coordinates `(0, 0)`, or by passing\n a `Point`, a `tuple` or a `list` of length two\n or even two scalar values.\n\n Parameters\n ----------\n *args : {two scalars, point-like}, optional\n `Point`-like means that it can be either of `tuple` or `list`\n of length 2 (see ~`Point.is_point_like`).\n\n Raises\n ------\n TypeError\n If the arguments are not the correct type (`Point`, list,\n tuple -of length 2- or two values) a `TypeError` is raised.\n \"\"\"\n\n def __init__(self, *args):\n if len(args) == 0:\n self._x = 0.\n self._y = 0.\n elif len(args) == 1:\n arg = args[0]\n if Point.is_point_like(arg):\n self._x = float(arg[0])\n self._y = float(arg[1])\n if isinstance(arg, Vector):\n self._x = arg.x\n self._y = arg.y\n elif len(args) == 2:\n self._x = float(args[0])\n self._y = float(args[1])\n else:\n raise TypeError('The construct needs no arguments, '\n 'Point, list, tuple (of length 2) or two '\n 'values, but got instead: {0}'.format(args))\n\n @property\n def x(self):\n \"\"\"[scalar] Get the `x` coordinate.\"\"\"\n return self._x\n\n @property\n def y(self):\n \"\"\"[scalar] Get the `y` coordinate.\"\"\"\n return self._y\n\n def __str__(self):\n return super(Point, self).__str__(x=self.x, y=self.y)\n\n def __getitem__(self, idx):\n \"\"\"\n Return values as a `list` for easier acces.\n \"\"\"\n return (self.x, self.y)[idx]\n\n def __len__(self):\n \"\"\"\n The length of a `Point` object is 2.\n \"\"\"\n return 2\n\n def __eq__(self, point):\n \"\"\"\n Equality (==) operator for two points.\n\n Parameters\n ----------\n point : {point-like}\n The point to test against.\n\n Returns\n -------\n res : {True, False}\n If the `x` and `y` components of the points are equal then return\n `True`, else `False`.\n\n Raises\n ------\n TypeError\n In case something other than `Point`-like is given.\n \"\"\"\n if Point.is_point_like(point):\n return abs(self.x - point[0]) < UNCERTAINTY and \\\n abs(self.y - point[1]) < UNCERTAINTY\n return False\n\n def __lt__(self, point):\n \"\"\"\n Less than (<) operator for two points.\n\n Parameters\n ----------\n point : {point-like}\n The point to test against.\n\n Returns\n -------\n res : {True, False}\n This operator returns `True` if:\n\n 1. `self.y` < `point.y`\n 2. in the borderline case `self.y` == `point.y` then if `self.x` <\n `point.x`\n\n Otherwise it returns `False`.\n \"\"\"\n\n if self.y < point[1]:\n return True\n if self.y > point[1]:\n return False\n if self.x < point[0]:\n return True\n return False\n\n @staticmethod\n def is_point_like(obj):\n \"\"\"\n See if `obj` is of `Point`-like.\n\n `Point`-like means `Point` or a list or tuple of\n length 2.\n\n Parameters\n ----------\n obj : geometric object\n\n Returns\n -------\n out : {True, False}\n `True` if obj is `Point`-like, else `False`.\n \"\"\"\n\n if isinstance(obj, Point):\n return True\n if isinstance(obj, (tuple, list)) and len(obj) == 2:\n return True\n return False\n\n def is_left(self, obj):\n \"\"\"\n Determine if `self` is left|on|right of an infinite `Line` or\n `Point`.\n\n Parameters\n ----------\n obj : {point-like, line-like}\n The `GeometricObject` to test against.\n\n Returns\n -------\n out : {scalar, `None`}\n >0 if `self` is left of `Line`,\n =0 if `self` is on of `Line`,\n <0 if `self` is right of `Line`,\n\n Raises\n ------\n ValueError\n In case something else than a `Line`-like or\n `Point`-like is given.\n \"\"\"\n\n if Line.is_line_like(obj):\n return ((obj[1][0] - obj[0][0]) * (self.y - obj[0][1]) - \\\n (self.x - obj[0][0]) * (obj[1][1] - obj[0][1]))\n if Point.is_point_like(obj):\n return obj[0] - self.x\n raise ValueError('Expected a Line or Point, but got: {}'\n .format(obj))\n\n def distance_to(self, obj):\n \"\"\"\n Calculate the distance to another `GeometricObject`.\n\n For now it can only calculate the distance to `Line`,\n `Ray`, `Segment` and `Point`.\n\n Parameters\n ----------\n obj : geometric object\n The object for which to calculate the distance to.\n\n Returns\n -------\n out : (float, point)\n Floating point number representing the distance from\n this `Point` to the provided object and the\n `Point` of intersection.\n \"\"\"\n\n if Point.is_point_like(obj):\n return ((self.x - obj[0])**2 + (self.y - obj[1])**2)**(.5)\n if isinstance(obj, Line):\n perpendicular = get_perpendicular_to(obj)\n distance_to = abs(perpendicular.x*(self.x - obj.p1.x) + \\\n perpendicular.y*(self.y - obj.p1.y))\n return distance_to\n\n def belongs_to(self, obj):\n \"\"\"\n Check if the `Point` is part of a `GeometricObject`.\n\n This method is actually using the method defined on the passed `obj`.\n\n Returns\n -------\n out : {True, False}\n \"\"\"\n return obj.has(self)\n\n def translate(self, dx, dy):\n \"\"\"\n See `GeometricObject.translate`.\n \"\"\"\n self._x += dx\n self._y += dy\n\n def move(self, x, y):\n \"\"\"\n The difference between this and `translate` is that this\n function moves `self` to the given coordinates instead.\n \"\"\"\n self._x = x\n self._y = y\n\n def rotate(self, theta, point=None, angle='degrees'):\n \"\"\"\n Rotate `self` by angle theta.\n\n Parameters\n ----------\n theta : scalar\n Angle to rotate by. Default in radians (see `angle`).\n point : {None, point-like}, optional\n Pivot point to rotate against (instead of origin). If not given,\n the point will be rotated against origin.\n angle : {'radians', 'degrees'}, optional\n How is `theta` passed? in radians or degrees.\n \"\"\"\n\n if angle == 'degrees':\n theta = math.radians(theta)\n if point is None:\n x_new = math.cos(theta) * self.x - math.sin(theta) * self.y\n y_new = math.sin(theta) * self.x + math.cos(theta) * self.y\n else:\n point = Point(point)\n x_new = math.cos(theta) * (self.x - point.x) - math.sin(theta) * \\\n (self.y - point.y) + point.x\n y_new = math.sin(theta) * (self.x - point.x) + math.cos(theta) * \\\n (self.y - point.y) + point.y\n self._x = x_new\n self._y = y_new\n\n\nclass Vector(GeometricObject):\n \"\"\"\n An abstract `Vector` object.\n\n It's defined by `x`, `y` components or `rho` (length) and `phi` (angle\n relative to X axis in radians).\n\n Parameters\n ----------\n *args : {two scalars, vector, point, (list, tuple of length 2)}\n Given `coordinates`, `args` compose the vector components. If\n the Cartesian coordinates are given, the Polar are calculated and\n vice-versa. If `args` is of `Vector` type then all of the\n other arguments are ignored and we create a `Vector` copy of\n the given parameter. It can also be `Point`-like element; if\n there are two `Point`-like elements given then the vector will\n have `rho` equal to the distance between the two points and the\n direction of point1 -> point2 (i.e. args[0] -> args[1]). If only one\n `Point`-like is given then this object's `x` and `y` values\n are used, having obviously the direction ``Point(0, 0)`` -> ``Point(x,\n y)``.\n **kwargs : coordinates={\"cartesian\", \"polar\"}, optional\n If `cartesian` then `arg1` is `x` and `arg2` is `y` components, else\n if `polar` then `arg1` is rho and `arg2` is `phi` (in radians).\n\n Raises\n ------\n TypeError\n In case `args` is not the correct type(`Vector`, two scalars\n or point-like).\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n coordinates = kwargs.get('coordinates', 'cartesian')\n if len(args) == 1:\n if isinstance(args[0], Vector):\n self._x = args[0].x\n self._y = args[0].y\n self._rho = args[0].rho\n self._phi = args[0].phi\n if Point.is_point_like(args[0]):\n self._x = args[0][0]\n self._y = args[0][1]\n self._calculate_polar_coords()\n elif len(args) == 2:\n if Point.is_point_like(args[0]) and Point.is_point_like(args[1]):\n self._x = args[1][0] - args[0][0]\n self._y = args[1][1] - args[0][1]\n self._calculate_polar_coords()\n return\n if coordinates is 'cartesian':\n self._x = args[0]\n self._y = args[1]\n self._calculate_polar_coords()\n if coordinates is 'polar':\n self._rho = args[0]\n self._phi = u.float_to_2pi(args[1])\n self._calculate_cartesian_coords()\n else:\n raise TypeError('The constructor needs vector, point-like or '\n 'two numbers, but instead it was given: '\n '{0}'.format(args))\n\n @property\n def x(self):\n \"\"\"[scalar] Get the x component of the `Vector`.\"\"\"\n return self._x\n\n @property\n def y(self):\n \"\"\"[scalar] Get the y component of the `Vector`.\"\"\"\n return self._y\n\n @property\n def rho(self):\n \"\"\"[scalar] Get the length of the `Vector` (polar coordinates).\"\"\"\n return self._rho\n\n @property\n def phi(self):\n \"\"\"\n [scalar] Get the angle (radians).\n\n Get the angle (in radians) of the `Vector` with the X axis\n (polar coordinates). `phi` will always be mapped to ``[0, 2PI)``.\n \"\"\"\n return self._phi\n\n @u.cached_property\n def normalized(self):\n \"\"\"\n [Vector] Get a normalized `self`.\n \"\"\"\n return Vector(1, self.phi, coordinates='polar')\n\n def __str__(self):\n return super(Vector, self).__str__(x=self.x, y=self.y, rho=self.rho,\n phi=math.degrees(self.phi))\n\n def __getitem__(self, idx):\n \"\"\"\n Return values as a list for easier acces some times.\n \"\"\"\n return (self.x, self.y)[idx]\n\n def __len__(self):\n \"\"\"\n The length of a `Vector` is 2.\n \"\"\"\n return 2\n\n def __neg__(self):\n \"\"\"\n Turns `self` to 180 degrees and returns the new `Vector`.\n\n Returns\n -------\n out : vector\n Return a new `Vector` with same `self.rho`, but\n `self.phi`-`math.pi`.\n \"\"\"\n return Vector(-self.x, -self.y)\n\n def __mul__(self, arg):\n \"\"\"\n Calculates the dot product with another `Vector`, or\n multiplication by scalar.\n\n For more details see `dot`.\n \"\"\"\n return self.dot(arg)\n\n def __add__(self, vector):\n \"\"\"\n Add two vectors.\n\n Parameters\n ----------\n vector : vector\n The vector to be added to `self`.\n\n Returns\n -------\n A new vector with components ``self.x + vector.x``,\n ``self.y + vector.y``.\n \"\"\"\n return Vector(self.x + vector.x, self.y + vector.y)\n\n def __sub__(self, vector):\n \"\"\"\n Subtraction of two vectors.\n\n It is `__add__` passed with turnerd round vector.\n \"\"\"\n return self.__add__(-vector)\n\n def _calculate_polar_coords(self):\n \"\"\"\n Helper function for internally calculating `self.rho` and `self.phi`.\n \"\"\"\n\n # calculate the length of the vector and store it in self.rho\n self._rho = Point(0, 0).distance_to(Point(self.x, self.y))\n # we now calculate the angle with the X axis\n self._phi = math.atan2(self.y, self.x)\n if self.phi < 0:\n self._phi += 2*math.pi\n\n def _calculate_cartesian_coords(self):\n \"\"\"\n Helper function for internally calculating `self.x` and `self.y`.\n\n Raises\n ------\n ValueError\n In case self.phi is outside of the interval ``[0, 2PI)`` an\n `Exception` is raised.\n \"\"\"\n self._x = self.rho * math.cos(self.phi)\n self._y = self.rho * math.sin(self.phi)\n\n @staticmethod\n def random_direction():\n \"\"\"\n Create a randomly oriented `Vector` (with `phi` in the\n interval ``[0, PI)``) and with unit length.\n\n Returns\n -------\n out : vector\n A `Vector` with random orientation in positive Y direction\n and with unit length.\n \"\"\"\n return Vector(1, random.random()*math.pi, coordinates='polar')\n\n def dot(self, arg):\n \"\"\"\n Calculates the dot product with another `Vector`, or\n multiplication by scalar.\n\n Parameters\n ----------\n arg : {scalar, vector}\n If it's a number then calculates the product of that number\n with this `Vector`, if it's another `Vector`\n then it will calculate the dot product.\n\n Returns\n -------\n res : {float, vector}\n Take a look at the parameters section.\n\n Raises\n ------\n TypeError\n In case `arg` is not number or `Vector`.\n \"\"\"\n\n if isinstance(arg, Vector):\n # if arg is Vector then return the dot product\n return self.x * arg.x + self.y * arg.y\n elif isinstance(arg, (int, float)):\n # if arg is number return a Vector multiplied by that number\n return Vector(self.x * arg, self.y * arg)\n # if arg is not the correct type then raise TypeError\n raise TypeError('Expected a vector or number, but got '.format(arg))\n\n def cross(self, arg):\n \"\"\"\n Calculates the cross product with another `Vector`, as defined\n in 2D space (not really a cross product since it gives a scalar, not\n another `Vector`).\n\n Parameters\n ----------\n arg : vector\n Another `Vector` to calculate the cross product with.\n\n Returns\n -------\n res : float\n Take a look at the parameters section.\n\n Raises\n ------\n TypeError\n In case `arg` is not a `Vector`.\n \"\"\"\n\n if isinstance(arg, Vector):\n return self.x * arg.y - self.y * arg.x\n raise TypeError('Expected a vector, but got '.format(arg))\n\n def parallel_to(self, obj):\n \"\"\"\n Is `self` parallel with `obj`?\n\n Find out if this `Vector` is parallel with another object\n (`Vector` or `Line`-like). Since we are in a 2D\n plane, we can use the geometric interpretation of the cross product.\n\n Parameters\n ----------\n obj : {vector, line-like}\n The object to be parallel with.\n\n Returns\n -------\n res : {True, False}\n If it's parallel return `True`, else `False`.\n \"\"\"\n\n if isinstance(obj, Line):\n obj = obj.v\n return abs(self.cross(obj)) < UNCERTAINTY\n\n def perpendicular_to(self, obj):\n \"\"\"\n Is `self` perpendicular to `obj`?\n\n Find out if this `Vector` is perpendicular to another object\n (`Vector` or `Line`-like). If the dot product\n between the two vectors is 0 then they are perpendicular.\n\n Parameters\n ----------\n obj : {vector, line-like}\n The object to be parallel with.\n\n Returns\n -------\n res : {True, False}\n If they are perpendicular return `True`, else `False`.\n \"\"\"\n\n if isinstance(obj, Line):\n obj = obj.v\n return self * obj == 0\n\n def translate(*args):\n \"\"\"Dummy function since it doesn't make sense to translate a\n `Vector`.\"\"\"\n pass\n\n def rotate(self, theta, angle='degrees'):\n \"\"\"\n Rotate `self` by `theta` degrees.\n\n Properties\n ----------\n theta : scalar\n Angle by which to rotate.\n angle : {'degrees', 'radians'}, optional\n Specifies how `theta` is given. Default is degrees.\n \"\"\"\n\n if angle == 'degrees':\n theta = math.radians(theta)\n self.phi += theta\n self._calculate_cartesian_coords()\n\n\nclass BoundingBox(GeometricObject):\n \"\"\"\n Represents the far extremeties of another `GeometricObject`\n (except for `Vector`).\n\n It is totally defined by two points. For convenience it also has `left`,\n `top`, `right` and `bottom` attributes.\n\n Parameters\n ----------\n obj : geometric object\n The object for which to assign a `BoundingBox`.\n \"\"\"\n\n def __init__(self, obj):\n if not isinstance(obj, GeometricObject) or isinstance(obj, Vector):\n raise TypeError('The argument must be of type GeometricObject '\n '(except for Vector), but got {} instead'\n .format(obj))\n # make min the biggest values possible and max the minimum\n xs = [point.x for point in obj]\n ys = [point.y for point in obj]\n self._left = min(xs)\n self._top = max(ys)\n self._right = max(xs)\n self._bottom = min(ys)\n self._p1 = Point(self.bottom, self.left)\n self._p2 = Point(self.top, self.right)\n self._width = abs(self.right - self.left)\n self._height = abs(self.top - self.bottom)\n\n @property\n def left(self):\n \"\"\"[scalar]\"\"\"\n return self._left\n\n @property\n def top(self):\n \"\"\"[scalar]\"\"\"\n return self._top\n\n @property\n def right(self):\n \"\"\"[scalar]\"\"\"\n return self._right\n\n @property\n def bottom(self):\n \"\"\"[scalar]\"\"\"\n return self._bottom\n\n @property\n def p1(self):\n \"\"\"\n (point-like) Get the bottom-left `Point`.\n \"\"\"\n return self._p1\n\n @property\n def p2(self):\n \"\"\"\n (point-like) Get the top-right `Point`.\n \"\"\"\n return self._p2\n\n @property\n def width(self):\n \"\"\"[scalar]\"\"\"\n return self._width\n\n @property\n def height(self):\n \"\"\"[scalar]\"\"\"\n return self._height\n\n def __str__(self):\n return super(BoundingBox, self).__str__(left=self.left, top=self.top,\n right=self.right,\n bottom=self.bottom,\n p1=str(self.p1),\n p2=str(self.p2))\n\n def __getitem__(self, idx):\n \"\"\"\n Get points through index.\n\n Parameters\n ----------\n idx : scalar\n The index of the `Point`.\n\n Returns\n -------\n out : point\n The selected `Point` through the provided index.\n \"\"\"\n\n return (self.p1, self.p2)[idx]\n\n def __len__(self):\n \"\"\"\n The `BoundingBox` is made of 2 points so it's length is 2.\n \"\"\"\n return 2\n\n\nclass Line(GeometricObject):\n \"\"\"\n An abstract mathematical `Line`.\n\n It is defined by either two points or by a `Point` and a\n `Vector`.\n\n Parameters\n ----------\n arg1 : point-like\n The passed in parameters can be either two points or a `Point`\n and a `Vector`. For more on `Point`-like see the\n `Point` class.\n arg2 : {point-like, vector}\n If a `Vector` is given as `arg2` instead of a\n `Point`-like, then `p2` will be calculated for t = 1 in the\n vectorial definition of the line (see notes).\n\n See Also\n --------\n Point, Vector\n\n Notes\n -----\n A line can be defined in three ways, but we use here only the vectorial\n definition for which we need a `Point` and a `Vector`.\n If two points are given the `Vector`\n :math:`\\\\boldsymbol{\\mathtt{p_1p_2}}` will be calculated and then we can\n define the `Line` as:\n\n .. math::\n \\\\boldsymbol{r} = \\\\boldsymbol{r_0} + t \\cdot\n \\\\boldsymbol{\\mathtt{p_1p_2}}\n\n Here :math:`t` is a parameter.\n \"\"\"\n\n def __init__(self, arg1, arg2):\n if Point.is_point_like(arg1) and Point.is_point_like(arg2):\n # detect if arguments are of type Point-like, if so\n # store them and calculate the directional Vector\n self._p1, self._p2 = Point(arg1), Point(arg2)\n self._v = Vector(self.p1, self.p2).normalized\n else:\n # if we have instead a Point and a Vector just calculate\n # self.p2\n self._p1, self._v = Point(arg1), arg2.normalized\n self._p2 = Point(self.p1.x + self.v.x, self.p1.y + self.v.y)\n\n @property\n def p1(self):\n \"\"\"\n [point] Get the 1st `Point` that defines the `Line`.\n \"\"\"\n return self._p1\n\n @property\n def p2(self):\n \"\"\"\n [point] Get the 2nd `Point` that defines the `Line`.\n \"\"\"\n return self._p2\n\n @property\n def v(self):\n \"\"\"\n [vector] Get the `Vector` pointing from `self.p1` to`self.p2`.\n \"\"\"\n return self._v\n\n @property\n def phi(self):\n \"\"\"\n [scalar] Get `self.v.phi`. Convenience method.\n \"\"\"\n return self.v.phi\n\n def __str__(self, **kwargs):\n return super(Line, self).__str__(v=str(self.v),\n p1=str(self.p1), p2=str(self.p2),\n **kwargs)\n\n def __getitem__(self, idx):\n \"\"\"\n Get the points that define the `Line` by index.\n\n Parameters\n ----------\n idx : scalar\n The index for `Point`.\n\n Returns\n -------\n ret : point\n Selected `Point` by index.\n \"\"\"\n return (self.p1, self.p2)[idx]\n\n def __len__(self):\n \"\"\"The `Line` is made of 2 points so it's length is 2.'\"\"\"\n return 2\n\n @staticmethod\n def is_line_like(obj):\n \"\"\"\n Check if an object is in the form of `Line`-like for fast\n computations (not necessary to build lines).\n\n Parameters\n ----------\n obj : anything\n `obj` is checked if is of type `Line` (i.e. not `Ray` nor\n `Segment`) or if this is not true then of the form: ((0, 1),\n (3, 2)) or [[0, 2], [3, 2]] or even combinations of these.\n\n Returns\n -------\n res : {True, False}\n \"\"\"\n\n if type(obj) == Line or (all(len(item) == 2 for item in obj) and \\\n len(obj) == 2):\n return True\n return False\n\n def intersection(self, obj):\n \"\"\"\n Find if `self` is intersecting the provided object.\n\n If an intersection is found, the `Point` of intersection is\n returned, except for a few special cases. For further explanation\n see the notes.\n\n Parameters\n ----------\n obj : geometric object\n\n Returns\n -------\n out : {geometric object, tuple}\n If they intersect then return the `Point` where this\n happened, else return `None` (except for `Line` and\n `Polygon`: see notes).\n\n Raises\n ------\n TypeError\n If argument is not geometric object then a `TypeError` is raised.\n\n Notes\n -----\n * `Line`: in case `obj` is `Line`-like and `self`\n then `self` and the `Line` defined by `obj` are checked for\n colinearity also in which case `geo2d_utils.inf` is returned.\n * `Polygon`: in the case of intersection with a\n `Polygon` a tuple of tuples is returned. The nested tuple is\n made up by the index of the intersected side and intersection point\n (e.g. ``((intersection_point1, 1), ( intersection_point2, 4))`` where\n `1` is the first intersected side of the `Polygon` and `4`\n is the second one). If the `Line` doesn't intersect any\n sides then `None` is returned as in the usual case.\n \"\"\"\n\n if isinstance(obj, Line):\n self_p1 = Vector(self.p1)\n obj_p1 = Vector(obj.p1)\n denominator = self.v.cross(obj.v)\n numerator = (obj_p1 - self_p1).cross(self.v)\n if abs(denominator) < UNCERTAINTY:\n # parallel lines\n if abs(numerator) < UNCERTAINTY:\n # colinear lines\n return u.inf\n return None\n # calculate interpolation parameter (t): Vector(obj.p1) + obj.v * t\n t = numerator/denominator\n intersection_point = Point(obj_p1 + obj.v * t)\n if type(obj) is Ray:\n # in case it's a Ray we restrict the values to [0, inf)\n if not (t >= UNCERTAINTY):\n return None\n if type(obj) is Segment:\n # and for Segment we have values in the\n # interval [0, obj.p1.distance_to(obj.p2)]\n if not (UNCERTAINTY <= t <= obj.p1.distance_to(obj.p2) - \\\n UNCERTAINTY):\n return None\n return intersection_point\n if isinstance(obj, Polygon):\n # if it's a Polygon traverse all the edges and return\n # the intersections as a list of items. The first element in\n # one item is the intersection Point and the second element in\n # the item is the edge's number\n intersections = []\n for idx, side in enumerate(obj.edges):\n intersection_point = self.intersection(side)\n if intersection_point is None or \\\n intersection_point == u.inf:\n continue\n if intersections and intersection_point == intersections[-1][0]:\n continue\n intersections.append([intersection_point, idx])\n # if there are no intersections return the usual None\n return intersections or None\n raise TypeError('Argument needs to be geometric object, but '\n 'got instead: {0}'.format(obj))\n\n def has(self, point):\n \"\"\"\n Inspect if `point` (`Point`-like) is part of this `Line`.\n\n Parameters\n ----------\n point : point-like\n The `Point` to test if it's part of this `Line`.\n\n Returns\n -------\n ret : {True, False}\n If it's part of this `Line` then return True, else False.\n\n See also\n --------\n Line.intersection, Ray.has, Segment.has\n \"\"\"\n\n # if the intersection failes then the object is not\n # on this Line\n # create a Vector from p1 to the point of interest\n # if this Vector is parallel to our direction Vector\n # then it is on the Line, if not, it's not on the Line\n vector = Vector(self.p1, point)\n return vector.parallel_to(self)\n\n def perpendicular_to(self, obj):\n \"\"\"\n Find out if provided `Line` is perpendicular to `self`.\n\n Returns\n -------\n ret : {True, False}\n \"\"\"\n\n if isinstance(obj, Line):\n obj = obj.v\n return self.v.perpendicular_to(obj)\n\n def parallel_to(self, obj):\n \"\"\"\n Find out if provided `Vector` or `Line`-like is\n parllel to `self`.\n\n Parameters\n ----------\n obj : {vector, line-like}\n The `Vector` or `Line`-like to compare\n parallelism with.\n\n Returns\n -------\n ret : {True, False}\n If `self` and `Line` are parallel then retrun `True`,\n else `False`.\n \"\"\"\n\n if isinstance(obj, Line):\n obj = obj.v\n return self.v.parallel_to(obj)\n\n\nclass Ray(Line):\n \"\"\"\n A `Ray` extension on `Line`.\n\n The only difference is that this has a starting `Point` (`p1`)\n which represents the end of the `Ray` in that direction.\n\n Parameters\n ----------\n arg1 : point-like\n The passed in parameters can be either two points or a `Point`\n and a `Vector` For more on `Point`-like see the\n `Point` class.\n arg2 : {point-like, vector}\n See `arg1`.\n\n See also\n --------\n Line, Segment, Vector\n \"\"\"\n\n def intersection(self, obj):\n \"\"\"\n Tries to find the `Point` of intersection.\n\n The difference between this and the `Line` intersection method\n is that this has also the constrain that if the `Point` of\n intersection is on the line then it also must be within the\n bounds of the `Ray`.\n\n Parameters\n ----------\n obj : geometric object\n\n Returns\n -------\n out : {gometric object, None}\n `GeometricObject` if intersection is possible, else the\n cases from `Line`.intersection.\n\n See also\n --------\n Line.intersection, Segment.intersection\n \"\"\"\n\n # if we're not dealing with a Line-like then skin the parent\n # intersection method\n if type(obj) is Line:\n return obj.intersection(self)\n intersections = super(Ray, self).intersection(obj)\n if isinstance(obj, Polygon):\n if intersections:\n intersections = [item for item in intersections \\\n if self.has(item[0])]\n return intersections\n if intersections and intersections != u.inf:\n if abs(self.p1.x - self.p2.x) < UNCERTAINTY:\n # vertical line\n r = (intersections.y - self.p1.y) / self.v.y\n else:\n r = (intersections.x - self.p1.x) / self.v.x\n if not (r >= UNCERTAINTY):\n return None\n return intersections\n\n def has(self, point):\n \"\"\"\n Check if `point` is part of `self`.\n\n Parameters\n ----------\n point : point-like\n The `Point` to check.\n\n Returns\n -------\n ret : {True, False}\n If the point is on the `Ray` then return `True`, else\n `False`.\n\n See also\n --------\n Ray.intersection, Line.has, Segment.has\n \"\"\"\n\n if super(Ray, self).has(point):\n p1_to_point = Vector(self.p1, point)\n return p1_to_point * self.v >= UNCERTAINTY\n\n\nclass Segment(Line):\n \"\"\"\n An extension on `Line`.\n\n This class emposes the `length` property on a `Line`. A\n `Segment` is a finite `Line`.\n\n Parameters\n ----------\n arg1 : point-like\n The passed in parameters can be either two points or a `Point`\n and a `Vector` For more on `Point`-like see the `Point` class.\n arg2 : {point-like, vector}\n See `arg1`.\n\n Raises\n ------\n ValueError\n If length is less than or equal to 0.\n\n See also\n --------\n Line, Ray, Vector\n \"\"\"\n\n @u.cached_property\n def length(self):\n \"\"\"\n [scalar] Get the length of the `Segment`.\n\n I.e. the distance from `self.p1` to `self.p2`.\n \"\"\"\n return self.p1.distance_to(self.p2)\n\n @u.cached_property\n def bounding_box(self):\n \"\"\"\n [BoundingBox] get the `BoundingBox` of `self`.\n \"\"\"\n return BoundingBox(self)\n\n def __str__(self):\n return super(Segment, self).__str__(length=self.length)\n\n def intersection(self, obj):\n \"\"\"\n Tries to find the `Point` of intersection.\n\n The difference between this and the `Line` intersection method\n is that this has also the constrain that if the `Point` of\n intersection is on the line then it also must be within the\n bounds of the `Segment`.\n\n Parameters\n ----------\n obj : geometric object\n\n Returns\n -------\n out : {gometrical object, None}\n `GeometricObject` if intersection is possible, else the\n cases from `Line`.intersection.\n\n See also\n --------\n Line.intersection, Ray.intersection\n \"\"\"\n\n # in case we need to check for another geometricObject\n if type(obj) is Line:\n return obj.intersection(self)\n intersections = super(Segment, self).intersection(obj)\n if isinstance(obj, Polygon):\n if intersections:\n intersections = [item for item in intersections \\\n if self.has(item[0])]\n return intersections\n if intersections and intersections != u.inf:\n if abs(self.p1.x - self.p2.x) < UNCERTAINTY:\n # vertical line\n r = (intersections.y - self.p1.y) / self.v.y\n else:\n r = (intersections.x - self.p1.x) / self.v.x\n if not (UNCERTAINTY <= r <= self.p1.distance_to(self.p2) - \\\n UNCERTAINTY):\n return None\n return intersections\n\n def has(self, point):\n \"\"\"\n Check if `point` is part of `self`.\n\n Parameters\n ----------\n point : point-like\n The point to check.\n\n Returns\n -------\n ret : {True, False}\n If the point is on the `Ray` then return `True`, else\n `False`.\n\n See also\n --------\n Segment.intersection, Line.has, Ray.has\n \"\"\"\n\n if super(Segment, self).has(point):\n p1_to_point = self.p1.distance_to(point)\n p2_to_point = self.p2.distance_to(point)\n return p1_to_point + p2_to_point - self.length < UNCERTAINTY\n\n def get_point_on_self(self, frac=None):\n \"\"\"\n Get a point on this `Segment` based on `frac`.\n\n If no argument is given then the `Point` on the\n `Segment` will be placed randomly.\n\n Parameters\n ----------\n frac : float, optional\n If `frac` is given then the new `Point`'s position will\n be relative to the length of the `Segment` and to the\n first `Point` (`self.p1`). `frac` can be only in the\n interval (0, 1).\n\n Returns\n -------\n out : point\n The new `Point`'s position on the `Segment`.\n\n Raises\n ------\n ValueError\n If `frac` is outside the open interval (0, 1) then\n a `ValueError` is raised.\n \"\"\"\n\n # if no argument is given then return an arbitrary\n # location Point on this Segment\n frac = frac or UNCERTAINTY + random.random()*(1 - UNCERTAINTY)\n # if frac is outside the open interval (0, 1)\n if not (0 < frac < 1):\n raise ValueError('The argument (frac) cannot be '\n 'outside of the open interval (0, 1), '\n 'got: {0}'.format(frac))\n # calculate the displacement relative to the\n # first Point\n dx = (self.p2.x - self.p1.x) * frac\n dy = (self.p2.y - self.p1.y) * frac\n # calculate the location of the new Point on\n # the Segment\n new_x = self.p1.x + dx\n new_y = self.p1.y + dy\n return Point(new_x, new_y)\n\n\nclass Polygon(GeometricObject):\n \"\"\"\n A general (closed) `Polygon` class.\n\n The `Polygon` is made out of points (vertices of type\n `Point`) and edges (`Segment`). It can be created by\n passing a list of `Point`-like objects.\n\n Parameters\n ----------\n vertices : {list/tuple of point-like}\n The `list` of `Point`-like objects that make the\n `Polygon`. The `self.edges` of the `Polygon` are\n automatically created and stored. If the length of the `vertices` list\n is < 3 this cannot be a `Polygon` and a `ValueError` will be\n raised.\n\n Raises\n ------\n ValueError\n In case length of the `vertices` `list` is smaller than 3.\n \"\"\"\n\n def __init__(self, vertices):\n if len(vertices) < 3:\n raise ValueError('List of points cannot have less than 3 '\n 'elements')\n self._vertices = [Point(point) for point in vertices]\n # this is for internal use only\n # first initialize to None so that area property can check for it\n self._diameter = None\n self._width = None\n self._area = None\n # setup self._area at this point (with signs)\n self.area\n if self._area < 0:\n # the vertices are in clockwise order so set them\n # in counterclockwise order\n self.vertices.reverse()\n # change the sign of the area appropriately\n self._area = -self._area\n # now select the lowest (and left if equal to some other)\n # and make it the first vertex in the Polygon\n lowest_idx = self._vertices.index(min(self._vertices))\n # rotate such that the lowset (and left) most vertex is the first one\n self._vertices = u.rotated(self._vertices, -lowest_idx)\n # and add the first vertex to the list at the end for further processing\n self._vertices += [self._vertices[0]]\n self._edges = [Segment(p1, p2) for p1, p2 in \\\n zip(self._vertices[:-1],\n self._vertices[1:])]\n\n @property\n def vertices(self):\n \"\"\"\n [list of points] Get the `vertices`.\n\n The list of `Point`-like objects that make up the\n `Polygon`. It's lengths cannot be less than 3.\n \"\"\"\n return self._vertices\n\n @property\n def edges(self):\n \"\"\"\n [list of segments] Get the `edges`, that is the segments.\n\n These are the `edges` of the `Polygon`, which are\n defined by the list of vertices. The `Polygon` is considered\n to be closed (ie. the last segment is defined by points `pn` and `p1`).\n \"\"\"\n return self._edges\n\n @property\n def area(self):\n \"\"\"\n [scalar] Get the (positive) area of this `Polygon`.\n\n Using the standard formula [WPolygon]_ for the area of a `Polygon`:\n\n .. math::\n\n A &= \\\\frac{1}{2} \\\\sum_{i=0}^{n-1} (x_iy_{i+1} - x_{i+1}y_i)\n\n :math:`A` can be negative depending on the orientation of the `Polygon`\n but this property always returns the positive value.\n\n Notes\n -----\n This function (property) also sets up `self._area` if it's not set.\n This variable (`self._area`) is meant to be just for internal use (at\n least for now).\n \"\"\"\n\n # first add the first vertex to the list\n if self._area is None:\n vertices = self.vertices + [self.vertices[0]]\n self._area = 1/2. * sum([v1.x*v2.y - v2.x*v1.y for v1, v2 in \\\n zip(vertices[:-1], vertices[1:])\n ])\n return abs(self._area)\n\n @u.cached_property\n def bounding_box(self):\n \"\"\"\n [BoundingBox] Get `BoundingBox` of `self`.\n \"\"\"\n return BoundingBox(self)\n\n @property\n def bbox_width(self):\n \"\"\"\n [scalar] Get `self.bounding_box.width`.\n \"\"\"\n return self.bounding_box.width\n\n @property\n def bbox_height(self):\n \"\"\"\n [scalar] Get `self.bounding_box.height`.\n \"\"\"\n return self.bounding_box.height\n\n @property\n def diameter(self):\n \"\"\"\n [scalar] Get the `diameter` of the `Polygon`.\n\n Refer to `_compute_diameter_width` for details on how this is\n calculated.\n\n See also\n --------\n Polygon.diameter, Polygon._compute_diameter_width\n \"\"\"\n if self._diameter is None:\n self._diameter, self._width = self._compute_diameter_width()\n return self._diameter\n\n @property\n def width(self):\n \"\"\"\n [scalar] Get the `width` of the `Polygon`.\n\n Refer to `_compute_diameter_width` for details on how this is\n calculated.\n\n See also\n --------\n Polygon.diameter, Polygon._compute_diameter_width\n \"\"\"\n if self._width is None:\n self._diameter, self._width = self._compute_diameter_width()\n return self._width\n\n @u.cached_property\n def centroid(self):\n \"\"\"\n [Point] Get the centroid (`Point`) of the `Polygon`.\n\n Defined as [WPolygon]_:\n\n .. math::\n\n C_x &= \\\\frac{1}{6A} \\\\sum_{i=0}^{i=n-1}(x_i + x_{i+1})\n (x_iy_{i+1}-x_{i+1}y_i)\n\n C_y &= \\\\frac{1}{6A} \\\\sum_{i=0}^{i=n-1}(y_i + y_{i+1})\n (x_iy_{i+1}-x_{i+1}y_i)\n\n where :math:`A` is the area using the standard formula for a `Polygon`\n [WPolygon]_ so it can take negative values.\n \"\"\"\n\n vertices = self.vertices + [self.vertices[0]]\n x = 1/(6.*self._area) * \\\n sum([(v1.x + v2.x)*(v1.x*v2.y - v2.x*v1.y) for v1, v2 in \\\n zip(vertices[:-1], vertices[1:])])\n y = 1/(6.*self._area) * \\\n sum([(v1.y + v2.y)*(v1.x*v2.y - v2.x*v1.y) for v1, v2 in \\\n zip(vertices[:-1], vertices[1:])])\n return Point(x, y)\n\n def __str__(self):\n return super(Polygon, self).__str__(vertices=[str(v)\n for v in self.vertices[:-1]])\n\n def __getitem__(self, idx):\n \"\"\"\n Retreive points (`self.vertices`) by `idx`.\n\n Parameters\n ----------\n idx : scalar\n The index of the `Point` (`vertex`).\n\n Returns\n -------\n ret : point\n The `vertex` by index.\n \"\"\"\n return self.vertices[idx]\n\n def __len__(self):\n \"\"\"\n The length of the `Polygon` is defined by the length of the\n `self.vertices` list.\n \"\"\"\n return len(self.vertices)\n\n def _compute_diameter_width(self):\n \"\"\"\n Compute the `diameter` and `width` of the `Polygon`.\n\n This is meant for internal use only. The `diameter` is defined by the\n length of the rectangle of minimum area enclosing the `Polygon`, and the\n `width` of the `Polygon` is then just the width of the same rectangle of\n minimum area enclosing the `Polygon`. It's calculation is based on [Arnon1983]_.\n \"\"\"\n\n def distance(xi, yi, xj, yj, m):\n bi = yi - m*xi\n bj = yj - m*xj\n return abs(bj - bi)/math.sqrt(m*m+1.)\n\n v = self.vertices\n n = len(v) - 1\n j = 0\n for i in range(n):\n while Vector(v[i], v[i + 1]) * Vector(v[j], v[j + 1]) > 0:\n j = (j + 1) % n\n if i == 0:\n k = j\n while Vector(v[i], v[i + 1]).cross(Vector(v[k], v[k + 1])) > 0:\n k = (k + 1) % n\n if i == 0:\n m = k\n while Vector(v[i], v[i + 1]).dot(Vector(v[m], v[m + 1])) < 0:\n m = (m + 1) % n\n if abs(v[i].x - v[i + 1].x) < UNCERTAINTY:\n d1 = abs(v[k].x - v[i].x)\n d2 = abs(v[m].y - v[j].y)\n elif abs(v[i].y - v[i + 1].y) < UNCERTAINTY:\n d1 = abs(v[k].y - v[i].y)\n d2 = abs(v[m].x - v[j].x)\n else:\n s = (v[i + 1].y - v[i].y)/(v[i + 1].x - v[i].x)\n d1 = distance(v[i].x, v[i].y, v[k].x, v[k].y, s)\n d2 = distance(v[j].x, v[j].y, v[m].x, v[m].y, -1./s)\n Ai = d1*d2\n if i == 0 or Ai < A:\n A = d1*d2\n res_d1 = d1\n res_d2 = d2\n return (res_d1, res_d2) if res_d1 > res_d2 else (res_d2, res_d1)\n\n def has(self, point):\n \"\"\"\n Determine if `point` is inside `Polygon` based on the winding\n number.\n\n Parameters\n ----------\n point : point-like\n The `point` to test if it's included in `self` or not.\n\n Returns\n -------\n out : {True, False}\n `True` if the `point` is included in `self` (`wn` > 0), else\n `False` (`wn` == 0).\n\n Notes\n -----\n Winding number algorithm (C++ implementation):\n http://geomalgorithms.com/a03-_inclusion.html\n \"\"\"\n\n # initialize the winding number\n wn = 0\n # be sure to convert point to Point\n point = Point(point)\n # loop through all of the vertices in the polygon (two by two)\n for v1, v2 in zip(self.vertices[:-1], self.vertices[1:]):\n if v1.y < point.y:\n if v2.y > point.y:\n # an upward crossing\n if point.is_left((v1, v2)) > 0:\n # point left of edge\n wn += 1\n else:\n if v2.y <= point.y:\n # a downward crossing\n if point.is_left((v1, v2)) < 0:\n # point right of edge\n wn -= 1\n # return\n return wn > 0\n\n def get_point_on_self(self, edge_no=None, frac=None):\n \"\"\"\n Return a random `Point` on the given `Segment`\n defined by `edge_no`.\n\n Parameters\n ----------\n edge_no : int, optional\n The index of the `edge` from the edge list. Default is\n `edge_no` = 0, which means the calculate on first edge.\n frac : float, optional\n A number in the open interval (0, 1). The point will be\n placed on the edge with the edge number edge_no and\n relative to the first point in the specified edge. If\n left to default (`None`), a random `Point` will be\n returned on the specified edge.\n\n Returns\n -------\n out : point\n The `Point` on this edge (`Segment`).\n \"\"\"\n segment = self.edges[edge_no]\n return segment.get_point_on_self(frac)\n\n def divide(self, obj=None, edge_no=None, frac=None, relative_phi=None,\n drelative_phi=0):\n \"\"\"\n Divide the `Polygon`.\n\n Parameters\n ----------\n obj : line-like, optional\n If no `obj` is given then `edge_no` is used to build a `Ray`\n from a randomly chosen Point on `self.edges[edge_no]` with\n inward direction and the closest intersection `Point` to\n `Ray.p1` is used to divide the `Polygon` in two, else all\n of the points given by the intersection between the\n `Polygon` and `obj` are used to split the\n `Polygon` in any number of polygons.\n edge_no : int, optional\n If given, `self.edges[edge_no]` will be used to build a\n `Ray` as explained above, else a random edge number will\n be chosen.\n frac : float, optional\n If given the point on `self.edges[edge_no]` will be situated at\n the fraction `frac` between `self.edges[edge_no].p1` and\n `self.edges[edge_no].p2` relateive to p1. Must be in the open\n interval (0, 1).\n relative_phi : float, optional\n Is an angle (in degrees) that gives the direction of the\n `Ray` spawned from `self.edges[edge_no]`. It has to be in\n the open interval (0, 90). If not given a random direction will be\n choosed in the interval (0, 90).\n drelative_phi : float, optional\n Is an angle interval centered on `relative_phi` which is used to\n calculate a random relative direction for the `Ray`\n spawned from `self.edges[edge_no]` in the interval `[relateive_phi -\n drelative_phi/2, relative_phi + drelative_phi/2)`. If not given\n it's assumed to be 0.\n\n Returns\n -------\n ret : tuple of size 2\n The first element is a list with the newly created polygons and\n the second element in the tuple is another list with the\n `Segments` that were used to divide the initial `Polygon`\n (ie. the common edge between the newly created polygons). These\n lists can be of length 0 if no division took place.\n\n See also\n --------\n Polygon.get_point_on_self, Segment.get_point_on_self\n \"\"\"\n\n # final list of polygons\n polys = []\n division_segments = []\n input_obj = obj\n if input_obj:\n # if a Line-like is given then calculate the intersection\n # Points with all the edges for later use\n intersections = input_obj.intersection(self)\n else:\n # WARNING:\n # -------\n # This only works for non intersecting Polygons\n # select a random edge number and get a random Point\n # on that edge to create a random Ray. This is used\n # to build an intersection Points list with only two points\n # the randomly generated Point and the Point closest to\n # the randomly generated one. This works becase we are\n # careful to generate a Ray only to the right of the segment\n if edge_no is None:\n edge_no = random.randint(0, len(self.edges) - 1)\n random_point = self.get_point_on_self(edge_no, frac)\n # generate a random angle to create a Ray which will be pointing\n # always in the right of the selected edge\n edge = self.edges[edge_no]\n if relative_phi and not (0 <= relative_phi + drelative_phi <= 180):\n raise ValueError('This has to hold: 0 <= relateive_phi +'\n ' drelative_phi <= 180, but got:'\n ' relative_phi={}, drelative_phi={}'\n .format(relative_phi, drelative_phi))\n if not relative_phi:\n phi = edge.phi + math.pi*random.random()\n else:\n phi = edge.phi + math.radians(relative_phi + \\\n drelative_phi*random.random())\n obj = Ray(random_point, Vector(1, phi, coordinates='polar'))\n intersections = obj.intersection(self)\n # and finally get the randomly generated Point + the first\n # intersection Point in the sorted list\n intersections = [[obj.p1, edge_no], intersections[0]]\n if edge_no > intersections[1][1]:\n # sort by edge_no if necessary\n intersections = [intersections[1], intersections[0]]\n # place the intersection Points in right positions in the new\n # vertex listand replace the edge number with the new location\n # (basically creating a new edge and pointing to that)\n all_vertices = self.vertices[:-1]\n # count is to hold how many vertices we already added in new list\n # so that the edge's number can be appropriately updated\n count = 0\n for item in intersections:\n # the position where the intersection Point will be inserted\n idx = item[1] + count + 1\n item[1] = idx\n if item[0] == self.vertices[idx - count - 1]:\n # if the intersection point coincides with the Point on the\n # Polygon behind the insertion Point then we just skip the\n # intersection Point, but alter the edge number in intersections\n # accordingly\n item[1] -= 1\n continue\n if item[0] == self.vertices[idx - count]:\n # if the intersection point coincides with the Point on the\n # Polygon after the insertion Point then we just skip\n # everything\n continue\n all_vertices.insert(idx, item[0])\n # store the new position\n # increase the counter to account for the addition of the Point\n count += 1\n # sort the Points first from top to bottom (inverse on Y) and\n # from left to right (on X) because this is the way the intersection\n # Points are used in the algorithm\n if abs(obj.p1.x - obj.p2.x) < UNCERTAINTY:\n # find if the `Line`-like is vertical and if so then\n # sort over Y\n intersections.sort(key=lambda item: item[0].y)\n else:\n intersections.sort(key=lambda item: item[0].x)\n # only after creating all_vertices list we can take care of the\n # different cases that we have regarding Segmet, Ray etc. usage\n if input_obj:\n if (type(obj) is Segment) and (self.has(obj.p1) and \\\n self.has(obj.p2)):\n # remove first and last Points from intersection list\n # because the Segment has the end Points inside the Polygon\n del (intersections[0], intersections[-1])\n elif (type(obj) is Segment and (self.has(obj.p1) and \\\n not self.has(obj.p2))) or (type(obj) is Ray and \\\n self.has(obj.p1)):\n # remove only the point closest to obj.p1 since this point is\n # inside the Polygon\n if (obj.p1.is_left(obj.p2)):\n del intersections[0]\n else:\n del intersections[-1]\n elif (type(obj) is Segment) and (not self.has(obj.p1) and \\\n self.has(obj.p2)):\n # same as before except for obj.p2 now\n if obj.p2.is_left(obj.p1):\n del intersections[-1]\n else:\n del intersections[0]\n if intersections is None or len(intersections) < 2:\n # if we have less than two intersection Points return None\n return polys, division_segments\n # make separate lists for intersection Points and edges' number for\n # further processing\n intersection_points, edge_nos = map(list, zip(*intersections))\n # keep track of used slices\n slice_to_del = []\n # loop over the edge_nos two at a time to construct Polygons\n # determined by the intersection Points and contained within these\n # then store the slice to be removed, ie. the portion of all_vertices\n # without the interseciton Points. Example:\n # * if we have a polygon defined by [p0, i0, p1, i1, p2, p3]\n # * then edge_nos must be: [1, 3] (not necessarily in this order)\n # * first get the Polygon defined by [i0, p1, i1] then remove these\n # * Points from the list and we end up with the remaining Polygon\n # * [p0, i0, i1, p2, p3]\n for i, j in zip(edge_nos[:-1:2], edge_nos[1::2]):\n if i > j:\n i, j = j, i\n polys.append(Polygon(all_vertices[i:j+1]))\n division_segments.append(Segment(all_vertices[i], all_vertices[j]))\n # insert always at the begining because we have to delete them\n # in inverse order so that the slices make sense when selecting\n # the items from the list\n slice_to_del.insert(0, slice(i+1, j))\n for sl in slice_to_del:\n del all_vertices[sl]\n # here append the remaining Polygon\n polys.append(Polygon(all_vertices))\n return polys, division_segments\n","sub_path":"Geo2D-0.1.22/geo2d/geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":62555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"183904094","text":"print(\"*입력한 숫자만큼 데코문자를 출력하는 프로그램입니다.*\")\nwhile True:\n deco = input(\"데코문자를 입력하세요 : \")\n number = int(input(\"출력횟수를 입력하세요 : \"))\n if len(deco)==0:\n break\n if number==0:\n break\n for i in range(number) :\n print(deco, end=\"\")\n print()\nprint(\"\\n*수행 종료됩니다.*\")","sub_path":"case3.py","file_name":"case3.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"303781501","text":"from django.db import models\n\n\nclass Locals(models.Model):\n DEPARTAMENTS = (\n ('Astronomia', 'Astronomia'),\n ('Ciências Atmosféricas', 'Ciências Atmosféricas'),\n ('Geofísica', 'Geofísica'),\n ('Informática', 'Informática'),\n ('Administração', 'Administração'),\n ('Biblioteca', 'Biblioteca'),\n )\n\n build = models.CharField('Bloco', max_length=4)\n floor = models.CharField('Pavimento', max_length=50)\n local = models.CharField('Local', max_length=128)\n departament = models.CharField('Departamento', choices=DEPARTAMENTS, max_length=128)\n created_at = models.DateTimeField('created_at', auto_now_add=True)\n\n class Meta:\n verbose_name_plural = 'locais'\n verbose_name = 'local'\n","sub_path":"intranet/locals/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"192977920","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QFileDialog\nimport os, zipfile\n\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(475, 176)\n MainWindow.setAutoFillBackground(False)\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n #Backup Button\n self.buttonAddonBackup = QtWidgets.QPushButton(self.centralwidget, clicked=lambda: self.press_backup(self.lineBackupDir.text(), self.lineBackupLocationDir.text()))\n self.buttonAddonBackup.setGeometry(QtCore.QRect(350, 110, 121, 23))\n font = QtGui.QFont()\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n self.buttonAddonBackup.setFont(font)\n self.buttonAddonBackup.setObjectName(\"buttonAddonBackup\")\n self.lineBackupDir = QtWidgets.QLineEdit(self.centralwidget)\n self.lineBackupDir.setGeometry(QtCore.QRect(90, 30, 311, 21))\n self.lineBackupDir.setStyleSheet(\"font: 10pt \\\"MS Shell Dlg 2\\\";\")\n self.lineBackupDir.setClearButtonEnabled(False)\n self.lineBackupDir.setObjectName(\"lineBackupDir\")\n self.lineBackupLocationDir = QtWidgets.QLineEdit(self.centralwidget)\n self.lineBackupLocationDir.setGeometry(QtCore.QRect(90, 60, 311, 21))\n self.lineBackupLocationDir.setStyleSheet(\"font: 10pt \\\"MS Shell Dlg 2\\\";\")\n self.lineBackupLocationDir.setClearButtonEnabled(False)\n self.lineBackupLocationDir.setObjectName(\"lineBackupLocationDir\")\n self.labelAddonDir = QtWidgets.QLabel(self.centralwidget)\n self.labelAddonDir.setGeometry(QtCore.QRect(0, 30, 71, 21))\n self.labelAddonDir.setObjectName(\"labelAddonDir\")\n self.labelBackupDir = QtWidgets.QLabel(self.centralwidget)\n self.labelBackupDir.setGeometry(QtCore.QRect(0, 60, 81, 21))\n self.labelBackupDir.setObjectName(\"labelBackupDir\")\n #Button for the addon dir\n self.toolButton = QtWidgets.QToolButton(self.centralwidget, clicked= lambda: self.press_changeAddonDir())\n self.toolButton.setGeometry(QtCore.QRect(410, 30, 25, 19))\n self.toolButton.setObjectName(\"toolButton\")\n #Button for the addon dir\n self.toolButton_2 = QtWidgets.QToolButton(self.centralwidget, clicked= lambda: self.press_changeAddonBackupDir())\n self.toolButton_2.setGeometry(QtCore.QRect(410, 60, 25, 19))\n self.toolButton_2.setObjectName(\"toolButton_2\")\n MainWindow.setCentralWidget(self.centralwidget)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 475, 21))\n self.menubar.setObjectName(\"menubar\")\n MainWindow.setMenuBar(self.menubar)\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\", \"WoW AddOn Backup\"))\n self.buttonAddonBackup.setText(_translate(\"MainWindow\", \"Backup AddOns\"))\n self.lineBackupDir.setText(_translate(\"MainWindow\", r\"C:\\Program Files (x86)\\World of Warcraft\\_retail_\\Interface\\Addons\"))\n #Get the users documents folder path\n self.documents_path = os.environ['USERPROFILE'] + f'\\Documents'\n self.lineBackupLocationDir.setText(_translate(\"MainWindow\", self.documents_path))\n self.labelAddonDir.setText(_translate(\"MainWindow\", \"Addon Dir:\"))\n self.labelBackupDir.setText(_translate(\"MainWindow\", \"Backup Location:\"))\n self.toolButton.setText(_translate(\"MainWindow\", \"...\"))\n self.toolButton_2.setText(_translate(\"MainWindow\", \"...\"))\n\n def press_changeAddonDir(self):\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n options |= QFileDialog.ShowDirsOnly\n # fileName, _ = QFileDialog.getOpenFileName(QFileDialog(),\"QFileDialog.getOpenFileName()\", \"\",\"All Files (*)\", options=options)\n fileName=QFileDialog.getExistingDirectory(QFileDialog(),\"Choose Directory\",\"C:\\\\\", options=options)\n if fileName:\n self.lineBackupDir.setText(QtCore.QDir.toNativeSeparators(fileName))\n def press_changeAddonBackupDir(self):\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n options |= QFileDialog.ShowDirsOnly\n # fileName, _ = QFileDialog.getOpenFileName(QFileDialog(),\"QFileDialog.getOpenFileName()\", \"\",\"All Files (*)\", options=options)\n fileName=QFileDialog.getExistingDirectory(QFileDialog(),\"Choose Directory\",\"C:\\\\\", options=options)\n if fileName:\n self.lineBackupLocationDir.setText(QtCore.QDir.toNativeSeparators(fileName))\n\n\n\n def press_backup(self, folder, destination):\n # Backup the entire contents of \"folder\" into a ZIP file.\n\n folder = os.path.abspath(folder) # make sure folder is absolute\n os.chdir(destination)\n\n # Figure out the filename this code should used based on\n # what files already exist.\n\n number = 1\n\n while True:\n zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'\n\n if not os.path.exists(zipFilename):\n break\n number = number + 1\n\n # Create the ZIP file.\n print(f'Creating {zipFilename}...')\n backupZip = zipfile.ZipFile(zipFilename, 'w')\n\n # Walk the entire folder tree and compress the files in each folder.\n\n # for foldername, subfolders, filenames in os.walk(os.path.relpath(folder)):\n for foldername, subfolders, filenames in os.walk(folder):\n for filename in filenames:\n print(f'Adding files in {zipFilename}...')\n # Add the current folder to the ZIP file.\n # writing each file one by one\n filename = os.path.join(foldername, filename)\n backupZip.write(filename, filename.replace(folder, ''))\n\n backupZip.close()\n print('Done.')\n\n # Pop up box\n msg = QtWidgets.QMessageBox()\n msg.setWindowTitle(\"Confirmation\")\n msg.setText(\"Your AddOn folder has been backed up to {}.\".format(destination))\n msg.setIcon(QtWidgets.QMessageBox.Information)\n # run_it = msg.exec_()\n msg.exec_()\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":"wow_addon_backup2.py","file_name":"wow_addon_backup2.py","file_ext":"py","file_size_in_byte":6818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"380949280","text":"import requests\nfrom bs4 import BeautifulSoup\n\nre = requests.get(\n \"https://www.aladin.co.kr/shop/wbrowse.aspx?BrowseTarget=List&ViewRowsCount=50&ViewType=Detail&PublishMonth=0&SortOrder=6&page=1&Stockstatus=1&PublishDay=84&CID=50927\",\n \"html.parser\")\nsoup = BeautifulSoup(re.text, \"html.parser\")\n\nbookList = soup.find_all(\"div\", {\"class\": \"ss_book_box\"})\n\nbookDescriptions = []\nfor book in bookList:\n bookDescriptions.append(book.find_all(\"li\")[0:2])\nfor description in bookDescriptions:\n temp = description[0].find(\"a\", {\"class\": \"bo3\"})\n if temp is None:\n description[0] = description[0].find(\"span\").string\n description[1] = description[1].find(\"a\").find(\"b\").string\n else:\n title = temp.find(\"b\").string\n description[0] = \"x\"\n description[1] = title\nprint(bookDescriptions)\n","sub_path":"scrapper.py","file_name":"scrapper.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"496735576","text":"# sorting\nn=int(input())\narray=list(map(int,input().split()))\ni=0\ncount=[]\ncounter=0\nwhile i 1:\r\n result *= base\r\n exp -= 1\r\n return result\r\n\r\ndef recurPower(base, exp):\r\n '''\r\n base: int or float.\r\n exp: int >= 0\r\n \r\n returns: int or float, base^exp\r\n '''\r\n if exp == 0:\r\n return 1\r\n if exp == 1:\r\n return base\r\n else:\r\n return base * recurPower(base, exp-1)\r\n\r\nfor args in ((2, 0), (2, 3), (10, 10)):\r\n print(f'Iterative: {iterPower(args[0], args[1])}')\r\n print(f'Iterative: {recurPower(args[0], args[1])}\\n')\r\n","sub_path":"basic_algorithms/power_iter_recur.py","file_name":"power_iter_recur.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"292547294","text":"import torch\nimport torch.nn as nn\n\nclass BuildingBlock(nn.Module):\n def __init__(self, in_dim, out_dim, s=1):\n super().__init__()\n self._conv1 = nn.Conv2d(in_dim, out_dim, 3, stride=s, padding=1)\n self._conv2 = nn.Conv2d(in_dim, out_dim, 3, stride=1, padding=1)\n self._relu = nn.ReLU()\n\n self._fix_dim = None\n if (in_dim != out_dim) or s != 1:\n self._fix_dim = nn.Conv2d(in_dim, out_dim, 1, stride=s)\n \n def forward(self, x):\n out = self._conv1(x)\n out = self._relu(out)\n out = self._conv2(x1)\n\n if self._fix_dim is not None:\n x = self._fix_dim(x)\n\n out = self._relu(out + x)\n return out\n\nclass ResNet18(nn.Module):\n def __init__(self, nClasses: int):\n super().__init__()\n self.features = nn.Sequential(\n nn.Conv2d(3, 64, 7, stride=2),\n nn.MaxPool2d(kernel_size=3, stride=2),\n\n BuildingBlock(64, 64),\n BuildingBlock(64, 64),\n BuildingBlock(64, 64),\n BuildingBlock(64, 128, s=2),\n BuildingBlock(128, 128),\n BuildingBlock(128, 128),\n BuildingBlock(128, 256, s=2),\n BuildingBlock(256, 256),\n BuildingBlock(256, 256),\n BuildingBlock(256, 512, s=2),\n BuildingBlock(512, 512),\n BuildingBlock(512, 512),\n )\n\n self.classifier = nn.Sequential(\n nn.AvgPool2d(3),\n nn.Linear(7*7*512, 1000),\n nn.Linear(1000, nClasses)\n )\n\n\n\nif __name__ == \"__main__\":\n model = ResNet18(10)","sub_path":"toys/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"115078298","text":"# -*- coding: utf-8 -*-\n\"\"\"Utilities for Halo library.\n\"\"\"\nimport platform\nimport six\nimport codecs\n\nfrom colorama import init, Fore\nfrom termcolor import colored\n\ninit(autoreset=True)\n\ndef is_supported():\n \"\"\"Check whether operating system supports main symbols or not.\n \n Returns\n -------\n boolean\n Whether operating system supports main symbols or not\n \"\"\"\n\n os_arch = platform.system()\n\n if os_arch != 'Windows':\n return True\n\n return False\n\ndef colored_frame(frame, color):\n \"\"\"Color the frame with given color and returns.\n \n Parameters\n ----------\n frame : str\n Frame to be colored\n color : str\n Color to be applied\n \n Returns\n -------\n str\n Colored frame\n \"\"\"\n return colored(frame, color, attrs=['bold'])\n\ndef is_text_type(text):\n \"\"\"Check if given parameter is a string or not\n \n Parameters\n ----------\n text : *\n Parameter to be checked for text type\n \n Returns\n -------\n bool\n Whether parameter is a string or not\n \"\"\"\n if isinstance(text, six.text_type) or isinstance(text, six.string_types):\n return True\n\n return False\n\ndef decode_utf_8_text(text):\n \"\"\"Decode the text from utf-8 format\n \n Parameters\n ----------\n text : str\n String to be decoded\n \n Returns\n -------\n str\n Decoded string\n \"\"\"\n try:\n return codecs.decode(text, 'utf-8')\n except:\n return text\n","sub_path":"halo/_utils.py","file_name":"_utils.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"36898358","text":"from pyArango.connection import Connection, CreationError\nimport csv\nimport os\nimport logging\nimport sys\n\nlogging.basicConfig(format='%(asctime)s %(message)s')\nlogger = logging.getLogger('KurasutaArangoCreationEnrichment')\nlogger.setLevel(logging.DEBUG if 'DEBUG' in os.environ and os.environ['DEBUG'] else logging.INFO)\n\nlogger.debug('Connecting to arango database...')\narango_connection = Connection(\n arangoURL=os.environ['ARANGODB_URL'],\n username=os.environ['ARANGODB_USERNAME'],\n password=os.environ['ARANGODB_PASSWORD']\n)\narango_database = arango_connection['kurasuta']\n\nupdate_count = 0\ntasking_count = 0\ntasking_skipped = 0\nlogger.info('Starting...')\nwith open(sys.argv[1], 'r') as fp:\n for row in csv.reader(fp):\n sha256, completed_at, created_at = row\n if completed_at:\n completed_at = '%s UTC' % completed_at[:19]\n if created_at:\n created_at = '%s UTC' % created_at[:19]\n if completed_at:\n sample = arango_database['sample'][sha256]\n if not sample:\n raise Exception('Expected to find sample with SHA256 %s' % sha256)\n logger.debug('Updating %s, it was completed at %s' % (sha256, completed_at))\n sample['completed_at'] = completed_at\n sample['completed_in_month'] = completed_at[:7]\n sample.save()\n update_count += 1\n elif created_at:\n logger.debug('Tasking %s since %s' % (sha256, created_at))\n task = arango_database['task'].createDocument()\n task['sha256'] = sha256\n task['created_at'] = created_at\n try:\n task.save()\n except CreationError as e:\n tasking_skipped += 1\n continue\n tasking_count += 1\nlogger.info('All done (updated %i samples, tasked %i hashes, %i taskings skipped).' % (\n update_count,\n tasking_count,\n tasking_skipped\n))\n","sub_path":"tools/arango-task-or-enrich-sample.py","file_name":"arango-task-or-enrich-sample.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"374110575","text":"\n\nfrom xai.brain.wordbase.nouns._tweeter import _TWEETER\n\n#calss header\nclass _TWEETERS(_TWEETER, ):\n\tdef __init__(self,): \n\t\t_TWEETER.__init__(self)\n\t\tself.name = \"TWEETERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"tweeter\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_tweeters.py","file_name":"_tweeters.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"215438498","text":"from core.mtcnn_model import pnet\nfrom core.train import train\n\ndef train_PNet(base_dir, prefix, end_epoch, display, lr):\n \"\"\"\n train PNet\n :param dataset_dir: tfrecord path\n :param prefix:\n :param end_epoch:\n :param display:\n :param lr:\n :return:\n \"\"\"\n net_factory = pnet\n\nif __name__ == '__main__':\n base_dir = '/home/huangweimin/workspace/mine_github/mtcnn'\n model_path = '/home/huangweimin/workspace/mine_github/mtcnn/model/pnet'\n \n total_epoch = 18\n display = 100\n\n train('pnet', pnet, model_path, total_epoch, base_dir, display)","sub_path":"src/tools/train_pnet.py","file_name":"train_pnet.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"213738723","text":"from os import path\nfrom functools import partial\n\nimport numpy as np\nimport healpy as hp\n\nfrom utils import DATA_DIR_RELATIVE\n\ndata_dir = DATA_DIR_RELATIVE\n\nnres = 13\ncmb_file = path.join(data_dir, 'lensed_cmbmap_betazero_nres{}r000.fits'.format(nres))\nprint('Reading CMB map...')\ncmb_map = hp.read_map(cmb_file)\n\nnside = 2 ** nres\ncmb_res = hp.pixelfunc.nside2resol(nside, arcmin=True)\n# n_pix_x = int(360 * 60 / cmb_res) # factor of 3.2 moves cut size from 40 to 128\nn_pix_x = 28378\n\nprojector = hp.projector.CartesianProj(xsize=n_pix_x)\nprint('Projecting CMB map...')\ncmb_map_projected = projector.projmap(cmb_map, partial(hp.pixelfunc.vec2pix, nside))\n\nprojection_path = path.join(data_dir, 'lensed_cmbmap_betazero_nres{}r000_cart-28378'.format(nres))\nprint('Saving projected CMB map...')\nnp.save(projection_path, cmb_map_projected)\n\nprint('Success!')\n","sub_path":"make_cmb_projection.py","file_name":"make_cmb_projection.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"577728218","text":"# -*- coding: utf-8 -*-\n\n# \n# Copyright (C) 2011 Platform Computing\n# \n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n# \n# This library 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 GNU\n# Lesser General Public License for more details.\n# \n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n# \n\nimport httplib\nimport urllib\n\nVERSION_STRING = 'OCCI/1.1'\nUSER_AGENT_STRING = 'occi-client/1.1 (python) httplib' + VERSION_STRING\n\ndef do_post(url, content_type = 'text/plain', accept = 'text/plain', categories = [], attributes = [], links = [], locations = []):\n \"\"\"\n Do a HTTP POST operation on an given URL\n \n Handles request and response based on content_type and accept which are both 'text/plain' by default.\n \n Returns a set of categories, attributes, links and locations or the appropiate HTTP error.\n \n Keyword arguments:\n url -- The url\n content_type -- The content_type determining how the data is rendered in the request (default text/plain)\n accept -- The accept header determining how the data should be returned by the service (default text/plain)\n categories -- A list of categories (default empty)\n attributes -- A list of attribtues (default empty)\n links -- A list of links (default empty)\n locations -- A list of locations (default empty)\n \"\"\"\n return [], [], [], []\n\ndef do_get(host, url, content_type = 'text/plain', accept = 'text/plain', categories = [], attributes = []):\n \"\"\"\n Do a HTTP GET operation on an given URL\n \n Handles request and response based on content_type and accept which are both 'text/plain' by default.\n \n Returns a set of return code, categories, attributes, links and locations or the appropiate HTTP error.\n \n Keyword arguments:\n url -- The url\n content_type -- The content_type determining how the data is rendered in the request (default text/plain)\n accept -- The accept header determining how the data should be returned by the service (default text/plain)\n categories -- A list of categories (default empty)\n attributes -- A list of attribtues (default empty)\n \"\"\"\n conn = httplib.HTTPConnection(host)\n\n body = None\n headers = {\n 'Content-Type': content_type,\n 'Accept': accept,\n 'User-Agent': USER_AGENT_STRING\n }\n\n # TODO: pack given information into appropiate rendering...\n\n # create connection retrieve body & headers\n if body is None:\n conn.request('GET', url, body=body, headers=headers)\n else:\n conn.request('GET', url, body=urllib.encode(body), headers=headers)\n \n response = conn.getresponse()\n response_code = response.status\n response_body = response.read()\n response_headers = response.getheaders()\n conn.close()\n\n # Verifies that the OCCI version # is in the response.\n for item in response_headers:\n if item[0] == 'server':\n if item[1].find(VERSION_STRING) == -1:\n raise AttributeError('Service did not expose the correct OCCI version number')\n\n # Verifies that the service responded with the corrent content-type\n reponse_content_type = response.getheader('Content-Type')\n if reponse_content_type != accept:\n raise AttributeError('Client requested that service reponses with Content-Type :', accept, ' Instead got: ', reponse_content_type)\n\n # TODO: unpack information from rendering...\n \n return response_code, [], [], [], []\n\ndef do_put(url, content_type = 'text/plain', accept = 'text/plain', categories = [], attributes = [], links = [], locations = []):\n \"\"\"\n Do a HTTP PUT operation on an given URL\n \n Handles request and response based on content_type and accept which are both 'text/plain' by default.\n \n Returns a set of categories, attributes, links and locations or the appropiate HTTP error.\n \n Keyword arguments:\n url -- The url\n content_type -- The content_type determining how the data is rendered in the request (default text/plain)\n accept -- The accept header determining how the data should be returned by the service (default text/plain)\n categories -- A list of categories (default empty)\n attributes -- A list of attribtues (default empty)\n links -- A list of links (default empty)\n locations -- A list of locations (default empty)\n \"\"\"\n return [], [], [], []\n\ndef do_delete(url, content_type = 'text/plain', accept = 'text/plain', locations = []):\n \"\"\"\n Do a HTTP GET operation on an given URL\n \n Handles request and response based on content_type and accept which are both 'text/plain' by default.\n \n Returns a set of categories, attributes, links and locations or the appropiate HTTP error.\n \n Keyword arguments:\n url -- The url\n content_type -- The content_type determining how the data is rendered in the request (default text/plain)\n accept -- The accept header determining how the data should be returned by the service (default text/plain)\n locations -- A list of locations (default empty)\n \"\"\"\n return [], [], [], []\n","sub_path":"tests/http.py","file_name":"http.py","file_ext":"py","file_size_in_byte":5555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"97160832","text":"import unittest\n\nimport threading\nimport time\n\nfrom random import randint\nfrom unittest.mock import MagicMock, patch\nfrom brain.socket_client import SocketClient\n\n\nclass TestSocketClient(unittest.TestCase):\n\n @patch(\"brain.socket_client.socket\")\n def setUp(self, socket):\n self.socketClient = SocketClient()\n socket.socket().recv.side_effect = lambda length: bytes([0 for _ in range(0, length)])\n\n def tearDown(self):\n self.socketClient.close()\n\n def test_get_size_info_when_length_is_one_then_first_byte_is_one(self):\n self.assertEqual(1, self.socketClient._get_size_info(1)[0])\n\n def test_bytes_to_length_conversion(self):\n for i in range(0, 1000):\n n = randint(0, 255**self.socketClient.length_info_size)\n\n with self.subTest(value=n):\n bytes_value = self.socketClient._get_size_info(n)\n result_length = self.socketClient._get_length(bytes_value)\n self.assertEqual(n, result_length)\n\n def test_send_has_length_info(self):\n data = {\"key\": \"value\"}\n bytes_data = b'{\"key\": \"value\"}'\n\n self.socketClient.socket._closed = False\n\n self.socketClient._send(data)\n\n self.socketClient.socket.sendall.assert_called_once()\n call = self.socketClient.socket.sendall.call_args_list[0]\n\n data_sent = call[0][0]\n\n self.assertEqual(len(data_sent), len(bytes_data) + self.socketClient.length_info_size)\n","sub_path":"anesthetic/test_brain/test_socket_client.py","file_name":"test_socket_client.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"570414398","text":"\"\"\"Test for KustoIngestClient.\"\"\"\n\nimport os\nimport json\nimport unittest\nimport base64\nfrom mock import patch\nfrom six import text_type\n\nfrom azure.kusto.ingest import KustoIngestClient, IngestionProperties, DataFormat\n\n\nUUID_REGEX = \"[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\"\nBLOB_NAME_REGEX = \"database__table__\" + UUID_REGEX + \"__dataset.csv.gz\"\nBLOB_URL_REGEX = (\n \"https://storageaccount.blob.core.windows.net/tempstorage/database__table__\"\n + UUID_REGEX\n + \"__dataset.csv.gz[?]sas\"\n)\n\n\ndef mocked_aad_helper(*args, **kwargs):\n \"\"\"Mock to replace _AadHelper._acquire_token\"\"\"\n return None\n\n\ndef mocked_requests_post(*args, **kwargs):\n \"\"\"Mock to replace requests.post\"\"\"\n\n class MockResponse:\n \"\"\"Mock class for KustoResponse.\"\"\"\n\n def __init__(self, json_data, status_code):\n self.json_data = json_data\n self.text = text_type(json_data)\n self.status_code = status_code\n self.headers = None\n\n def json(self):\n \"\"\"Get json data from response.\"\"\"\n return self.json_data\n\n if args[0] == \"https://ingest-somecluster.kusto.windows.net/v1/rest/mgmt\":\n if \".get ingestion resources\" in kwargs[\"json\"][\"csl\"]:\n file_name = \"ingestionresourcesresult.json\"\n if \".get kusto identity token\" in kwargs[\"json\"][\"csl\"]:\n file_name = \"identitytokenresult.json\"\n\n with open(\n os.path.join(os.path.dirname(__file__), \"input\", file_name), \"r\"\n ) as response_file:\n data = response_file.read()\n return MockResponse(json.loads(data), 200)\n\n return MockResponse(None, 404)\n\n\ndef mocked_create_blob_from_stream(self, *args, **kwargs):\n \"\"\"Mock to replace BlockBlobService.create_blob_from_stream\"\"\"\n\n tc = unittest.TestCase(\"__init__\")\n\n tc.assertEqual(self.account_name, \"storageaccount\")\n tc.assertEqual(self.sas_token, \"sas\")\n tc.assertEqual(kwargs[\"container_name\"], \"tempstorage\")\n tc.assertIsNotNone(kwargs[\"blob_name\"])\n tc.assertRegexpMatches(kwargs[\"blob_name\"], BLOB_NAME_REGEX)\n tc.assertIsNotNone(kwargs[\"stream\"])\n\n\ndef mocked_queue_put_message(self, *args, **kwargs):\n \"\"\"Mock to replace QueueService.put_message\"\"\"\n\n tc = unittest.TestCase(\"__init__\")\n\n tc.assertEqual(self.account_name, \"storageaccount\")\n tc.assertEqual(self.sas_token, \"sas\")\n tc.assertEqual(kwargs[\"queue_name\"], \"readyforaggregation-secured\")\n tc.assertIsNotNone(kwargs[\"content\"])\n\n encoded = kwargs[\"content\"]\n ingestion_blob_info_json = base64.b64decode(encoded.encode(\"utf-8\")).decode(\"utf-8\")\n\n result = json.loads(ingestion_blob_info_json)\n tc.assertIsNotNone(result)\n tc.assertIsInstance(result, dict)\n tc.assertRegexpMatches(result[\"BlobPath\"], BLOB_URL_REGEX)\n tc.assertEquals(result[\"DatabaseName\"], \"database\")\n tc.assertEquals(result[\"TableName\"], \"table\")\n tc.assertGreater(result[\"RawDataSize\"], 0)\n tc.assertEquals(result[\"AdditionalProperties\"][\"authorizationContext\"], \"authorization_context\")\n\n\nclass KustoIngestClientTests(unittest.TestCase):\n \"\"\"Test class for KustoIngestClient.\"\"\"\n\n @patch(\"requests.post\", side_effect=mocked_requests_post)\n @patch(\"azure.kusto.data.security._AadHelper.acquire_token\", side_effect=mocked_aad_helper)\n @patch(\n \"azure.storage.blob.BlockBlobService.create_blob_from_stream\",\n autospec=True,\n side_effect=mocked_create_blob_from_stream,\n )\n @patch(\n \"azure.storage.queue.QueueService.put_message\",\n autospec=True,\n side_effect=mocked_queue_put_message,\n )\n def test_sanity_ingest(self, mock_post, mock_aad, mock_block_blob, mock_queue):\n \"\"\"Test simple ingest\"\"\"\n\n ingest_client = KustoIngestClient(\"https://ingest-somecluster.kusto.windows.net\")\n\n ingestion_properties = IngestionProperties(\n database=\"database\", table=\"table\", dataFormat=DataFormat.csv\n )\n\n file_path = os.path.join(os.getcwd(), \"azure-kusto-ingest\", \"tests\", \"input\", \"dataset.csv\")\n\n ingest_client.ingest_from_multiple_files(\n [file_path], delete_sources_on_success=False, ingestion_properties=ingestion_properties\n )\n","sub_path":"azure-kusto-ingest/tests/test_kusto_ingest_client.py","file_name":"test_kusto_ingest_client.py","file_ext":"py","file_size_in_byte":4240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"615638705","text":"def fill(n: str) -> str:\n string = \"\"\n if len(n) < 4:\n nullCount = 4 - len(n)\n for i in range(nullCount):\n string = string + \"0\"\n return string + n\n\n\ndef simetric_check(n: str) -> bool:\n splitted = list(n)\n reversedList = splitted.copy()\n reversedList.reverse()\n if reversedList == splitted:\n return 1\n else:\n return 0\n\n\ndef main():\n print(simetric_check(fill(input())), end='')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"week1/tasks/task-022-simmietrichnoie-chislo/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"246492534","text":"from pyramid.config import Configurator\nfrom server.resources import Root\nfrom views import socketio_service, create_base\n\ndef main(global_config, **settings):\n if 'talisker_path' not in settings:\n raise ValueError('Warning: talikser_path not defined in the config, '\n 'please set talisker_path in app:server.')\n create_base(settings['talisker_path'])\n \n config = Configurator(root_factory=Root, settings=settings)\n config.add_view('server.views.root',\n context='server:resources.Root',\n renderer='server:templates/mytemplate.pt')\n config.add_route('socket_io', '/socket.io/*remaining',\n view=socketio_service)\n config.add_static_view('static', 'server:static')\n return config.make_wsgi_app()\n\n","sub_path":"server/server/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"127090300","text":"#facial recognition code\n####This only covers fitting a Linear SVM on the face embeddings for an image dataset#####\n####This assumes the embeddings and the faces to be fitted/analyzed are pre-saved in \".npz\" files###\n\n#various imports\nfrom random import choice\nfrom numpy import load\nfrom numpy import expand_dims\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import Normalizer\nfrom sklearn.svm import SVC\nfrom matplotlib import pyplot\n\n############Deploying a model to classify face embeddings##############\n#####Creating labelling for the faces passed and loaded in################\n#load in face embeddings to fit the model with\ndata = load('kp-employees-embeddings.npz')\ntrainX, trainy, testX, testy = data['arr_0'], data['arr_1'], data['arr_2'], data['arr_3']\nprint('Dataset: train=%d, text=%d' % (trainX.shape[0], testX.shape[0]))\n#normalize input vectors (the face embedding vectors)\nin_encoder = Normalizer(norm='l2')\ntrainX = in_encoder.transform(trainX)\ntesX = in_encoder.transform(testX)\n#label encode targets (converting the string target variables to integers)\nout_encoder = LabelEncoder()\nout_encoder.fit(trainy)\ntrainy = out_encoder.transform(trainy)\ntesty = out_encoder.transform(testy)\n\n############fitting the model/linear SVM with the training data encoded#################\n#fit model\nmodel = SVC(kernel='linear', probability=True)\nmodel.fit(trainX, trainy)\n###evaluating the model##########\n#predict\nyhat_train = model.predict(trainX)\nyhat_test = model.predict(testX)\n#score\nscore_train = accuracy_score(trainy, yhat_train)\nscore_test = accuracy_score(testy, yhat_test)\n#summarize\nprint('Accuracy: train=%.3f, test=%.3f' % (score_train*100, score_test*100))\n\n##########plotting original face and the prediction#############\n#########fitting the model with the test data loaded in############\n####The dataset and the embeddings must be related. The embeddings must be of the given dataset######\n#load faces\ndata = load('kp-employees-dataset.npz')\ntestX_faces = data['arr_2']\n# load face embeddings\ndata = load('kp-employees-embeddings.npz')\ntrainX, trainy, testX, testy = data['arr_0'], data['arr_1'], data['arr_2'], data['arr_3']\n# normalize input vectors\nin_encoder = Normalizer(norm='l2')\ntrainX = in_encoder.transform(trainX)\ntestX = in_encoder.transform(testX)\n# label encode targets\nout_encoder = LabelEncoder()\nout_encoder.fit(trainy)\ntrainy = out_encoder.transform(trainy)\ntesty = out_encoder.transform(testy)\n# fit model\nmodel = SVC(kernel='linear', probability=True)\nmodel.fit(trainX, trainy)\n\n#test model on a random example from the test Dataset\n#if wanted, can modify code here to take a random image and evaluate it#####\nselection = choice([i for i in range(testX.shape[0])])\nrandom_face_pixels = testX_faces[selection]\nrandom_face_emb = testX[selection]\nrandom_face_class = testy[selection]\nrandom_face_name = out_encoder.inverse_transform([random_face_class])\n\n#take an image, extract a face, get it's embedding, store it's class/name\n#if it is another image, no need to encode it (not yet)\n\n# prediction for the face\nsamples = expand_dims(random_face_emb, axis=0)\nyhat_class = model.predict(samples)\nyhat_prob = model.predict_proba(samples)\n# get name\nclass_index = yhat_class[0]\nclass_probability = yhat_prob[0,class_index] * 100\npredict_names = out_encoder.inverse_transform(yhat_class)\nprint('Predicted: %s (%.3f)' % (predict_names[0], class_probability))\nprint('Expected: %s' % random_face_name[0])\n# plot for fun\npyplot.imshow(random_face_pixels)\ntitle = '%s (%.3f)' % (predict_names[0], class_probability)\npyplot.title(title)\npyplot.show()\n","sub_path":"code_and_saved_files/facialNNCodev5p1.py","file_name":"facialNNCodev5p1.py","file_ext":"py","file_size_in_byte":3652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"409399627","text":"import socket\n\ndef tcp_ser():\n # 建立负责接受请求的socket, socket.SOCK_STREAM表示tcp通信\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n # 绑定地址和端口sub(pattern, repl, string, count=0, flags=0)\n addr = (\"127.0.0.1\", 8998)\n sock.bind(addr)\n\n # 监听接入的访问socket\n sock.listen()\n\n while True:\n # skt是访问socket,建立了一个通讯的链接通路\n skt, addr = sock.accept()\n # socket.socket().recvfrom(buffsize)\n msg = skt.recv(200)\n # 解码\n msg = msg.decode()\n # 打印\n print(\"Received msg: {} from {}\".format(msg, addr))\n # 编码,将结果返回\n msg = \"get it\".encode()\n skt.send(msg)\n # 关闭该套接字\n skt.close()\n\nif __name__ == \"__main__\":\n print(\"start tcp server\")\n tcp_ser()\n print(\"end tcp server\")","sub_path":"note/2. python advanced/12. net编程/server_tcp.py","file_name":"server_tcp.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"83747151","text":"#!/usr/bin/env python3\n# -*-python-*-\n'''\nLICENSE\n This is free and unencumbered software released into the public domain.\n\n Anyone is free to copy, modify, publish, use, compile, sell, or\n distribute this software, either in source code form or as a compiled\n binary, for any purpose, commercial or non-commercial, and by any\n means.\n\n In jurisdictions that recognize copyright laws, the author or authors\n of this software dedicate any and all copyright interest in the\n software to the public domain. We make this dedication for the benefit\n of the public at large and to the detriment of our heirs and\n successors. We intend this dedication to be an overt act of\n relinquishment in perpetuity of all present and future rights to this\n software under copyright law.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n OTHER DEALINGS IN THE SOFTWARE.\n\n For more information, please refer to \n\nUSAGE\n from log import DEBUG, INFO, ERROR, FATAL\n or, if setting the level:\n from log import PDLOG_SET_LEVEL, DEBUG, INFO, ERROR, FATAL\n\n Then, in your code, log a message:\n value = 42\n INFO('This in an informational message, value=%d', value)\n'''\n\nimport logging\nimport os\nimport sys\nimport time\nimport traceback\n\nclass PDLog(object):\n logger = None\n initial_level_set = False\n\n class PDLogFormatter(logging.Formatter):\n def __init__(self):\n logging.Formatter.__init__(self)\n self.timestamps = True\n self.lineno = False\n self.pid = True\n\n def format(self, record):\n level = record.levelname[0]\n if self.timestamps:\n if self.timestamps:\n date = time.localtime(record.created)\n date_msec = (record.created - int(record.created)) * 1000\n stamp = '%c%04d%02d%02d %02d:%02d:%02d.%03d' % (\n level,\n date.tm_year, date.tm_mon, date.tm_mday,\n date.tm_hour, date.tm_min, date.tm_sec, date_msec)\n else:\n stamp = ''\n if self.lineno:\n lineno = ' %s:%d' % (record.filename, record.lineno)\n else:\n lineno = ''\n if self.pid:\n pid = ' %d' % os.getpid()\n else:\n pid = ''\n message = '%s%s%s %s' % (stamp, lineno, pid,\n PDLog.format_message(record))\n record.getMessage = lambda: message\n return logging.Formatter.format(self, record)\n\n def __init__(self):\n PDLog.logger = logging.getLogger()\n logging.addLevelName(50, 'FATAL')\n handler = logging.StreamHandler()\n handler.setFormatter(PDLog.PDLogFormatter())\n PDLog.logger.addHandler(handler)\n self.set_level('INFO')\n\n @staticmethod\n def format_message(record):\n try:\n msg = '%s' % (record.msg % record.args)\n except: # pylint: disable=locally-disabled,bare-except\n msg = record.msg\n return msg\n\n @staticmethod\n def set_level(newlevel):\n old_level = PDLog.logger.getEffectiveLevel()\n if newlevel == 'DEBUG':\n PDLog.logger.setLevel(10)\n elif newlevel == 'INFO':\n PDLog.logger.setLevel(20)\n elif newlevel == 'ERROR':\n PDLog.logger.setLevel(40)\n else:\n PDLog.logger.setLevel(newlevel)\n new_level = PDLog.logger.getEffectiveLevel()\n\n if PDLog.initial_level_set:\n PDLog.logger.info('Logging changed from level %s (%s) to level %s (%s)',\n old_level,\n logging.getLevelName(old_level),\n new_level,\n logging.getLevelName(new_level))\n PDLog.initial_level_set = True\n\n @staticmethod\n def fatal(message, *args, **kwargs):\n logging.fatal(message, *args, **kwargs)\n sys.exit(1)\n\n @staticmethod\n def decode(message, *args, **kwargs):\n ty, va = sys.exc_info()[:2]\n exc = traceback.format_exception_only(ty, va)\n logging.error(message + ': ' + exc[0].strip(), *args, **kwargs)\n\n# Define global aliases to debugging functions.\nDEBUG = logging.debug\nINFO = logging.info\nERROR = logging.error\nFATAL = PDLog.fatal\nDECODE = PDLog.decode\nPDLOG_SET_LEVEL = PDLog.set_level\n\n# Instantiate the class\nPDLog()\n\nif __name__ == '__main__':\n ERROR('PDLog should be imported. Current time is %s', time.ctime())\n DECODE('PDLog should be imported. Current time is %s', time.ctime())\n FATAL('PDLog should be imported. Current time is %s', time.ctime())\n","sub_path":"urm/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":4685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"419513409","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 20 14:07:32 2016\n\n@author: xzk\n\"\"\"\n\nclass Solution(object):\n def permute(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n if nums == []:\n return [[]]\n elif len(nums) == 1:\n return [nums]\n elif len(nums) == 2:\n return [nums, nums[::-1]]\n ans = []\n for i in xrange(len(nums)):\n ans_i = self.permute(nums[0:i] + nums[i+1:])\n for j in xrange(len(ans_i)):\n ans.append([nums[i]] + ans_i[j])\n return ans\n \n def permute2(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n if not nums or len(nums) == 1:\n return [nums]\n ans = [[]]\n for n in nums:\n new_ans = []\n for seq in ans:\n for i in xrange(len(seq)):\n new_ans.append( seq[0:i] + [n] + seq[i:])\n ans = new_ans\n return ans\n \n \n def permute3(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n def DFS(nums, path, res):\n if not nums:\n res.append(path)\n # return # backtracking\n for i in xrange(len(nums)):\n DFS(nums[:i]+nums[i+1:], path+[nums[i]], res)\n if not nums:\n return [[]]\n res = []\n DFS(nums, [], res)\n return res","sub_path":"46Permutations.py","file_name":"46Permutations.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"148673009","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n# 面向对象编程 — Object Oriented Programming (OOP)\n\n# 类和实例\nclass Student(object): # (object)表示该类是从哪个类继承下来的,\n pass\n\nbart = Student() # bart是Student的一个实例\nbart # <__main__.Student object at 0x10a67a590> 内存地址\nStudent # \n\nbart.name = 'Bart Simpson'\nbart.name # Bart Simpson\n\n\nclass Student(object):\n\n def __init__(self, name, score): # 特殊方法“__init__”前后分别有两个下划线\n self.name = name\n self.score = score\n\n# __init__方法的第一个参数永远是self,表示创建的实例本身\n# 因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身。\n# 有了__init__方法,在创建实例的时候,就不能传入空的参数了,必须传入与__init__方法匹配的参数,但self不需要传,Python解释器自己会把实例变量传进去\n\nbart = Student('Bart Simpson', 59)\nbart.name # 'Bart Simpson'\nbart.score # 59\n\n\n# 数据封装\nclass Student(object):\n\n def __init__(self, name, score):\n self.name = name\n self.score = score\n\n def print_score(self):\n print('%s: %s' % (self.name, self.score))\n\n def get_grade(self):\n if self.score >= 90:\n return 'A'\n elif self.score >= 60:\n return 'B'\n else:\n return 'C'\n\nbart.print_score() # Bart Simpson: 59\n\nlisa = Student('Lisa', 99)\nbart = Student('Bart', 59)\nprint(lisa.name, lisa.get_grade())\nprint(bart.name, bart.get_grade())\n\n\n# 访问限制\nclass Student(object):\n\n def __init__(self, name, score):\n self.__name = name # 实例的变量名如果以__开头,就变成private,只有内部可以访问\n self.__score = score\n\n def print_score(self):\n print('%s: %s' % (self.__name, self.__score))\n\n def get_name(self):\n return self.__name\n\n def get_score(self):\n return self.__score\n\n # 可以对参数做检查,避免传入无效的参数\n def set_score(self, score):\n if 0 <= score <= 100:\n self.__score = score\n else:\n raise ValueError('bad score')\n\n# 变量名类似__xxx__的,是特殊变量,特殊变量是可以直接访问的,不是private变量,所以,不能用__name__、__score__这样的变量名。\n# 像_name,这样的实例变量外部是可以访问的,但约定俗成被它看成私有变量\n# __name__变量其实也可以被外部访问,Python解释器对外把__name变量改成了_Student__name\nbart._Student__name\n# 但不同版本的Python解释器可能会把__name改成不同的变量名,所以不建议这样做\n\n# 最后注意下面的这种错误写法:\nbart = Student('Bart Simpson', 59)\nbart.get_name() # 'Bart Simpson'\nbart.__name = 'New Name' # 设置__name变量!\nbart.__name # 'New Name'\n# 表面上看,外部代码“成功”地设置了__name变量,但实际上这个__name变量和class内部的__name变量不是一个变量!\n# 内部的__name变量已经被Python解释器自动改成了_Student__name,而外部代码给bart新增了一个__name变量\n\n\n# 练习\n# 把Student对象的gender字段对外隐藏起来,用get_gender()和set_gender()代替,并检查参数有效性\nclass Student(object):\n\n def __init__(self, name, gender):\n self.name = name\n self.gender = gender\n\n def get_gender(self):\n return self.gender\n\n def set_gender(self, gender):\n if gender == 'male' or gender == 'female': # if gender in ['male', 'female']:\n self.gender = gender\n else:\n raise ValueError(\"wrong value of gender!\")\n\n","sub_path":"liaoxuefeng/6.0_object_oriented_programming.py","file_name":"6.0_object_oriented_programming.py","file_ext":"py","file_size_in_byte":3729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"430656656","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport lxml\nfrom mock import Mock\nfrom preggy import expect\n\nfrom tests.fixtures import PageFactory\nfrom tests.unit.base import ValidatorTestCase\nfrom holmes.reviewer import Reviewer\nfrom holmes.config import Config\nfrom holmes.validators.blacklist import BlackListValidator\n\n\nclass TestBlackListValidator(ValidatorTestCase):\n\n def test_can_validate(self):\n page = PageFactory.create()\n\n reviewer = Reviewer(\n api_url='http://localhost:2368',\n page_uuid=page.uuid,\n page_url=page.url,\n page_score=0.0,\n config=Config(),\n validators=[],\n cache=self.sync_cache\n )\n\n reviewer.violation_definitions = {\n 'blacklist.domains': {'default_value': ['a.com']},\n }\n\n content = 'A' \\\n 'B'\n\n result = {\n 'url': page.url,\n 'status': 200,\n 'content': content,\n 'html': lxml.html.fromstring(content)\n }\n reviewer.responses[page.url] = result\n reviewer.get_response = Mock(return_value=result)\n\n validator = BlackListValidator(reviewer)\n validator.review.data = {\n 'page.all_links': [\n {'href': 'http://a.com/test1'}, {'href': 'http://b.com/test2'}\n ]\n }\n\n validator.add_violation = Mock()\n\n validator.validate()\n\n validator.add_violation.assert_called_once_with(\n points=100,\n key='blacklist.domains',\n value=['http://a.com/test1']\n )\n\n def test_can_get_violation_definitions(self):\n reviewer = Mock()\n validator = BlackListValidator(reviewer)\n definitions = validator.get_violation_definitions()\n\n expect(definitions).to_length(1)\n expect('blacklist.domains' in definitions).to_be_true()\n\n expect(validator.get_blacklist_parsed_value(['http://a.com'])).to_equal(\n 'Link #0'\n )\n\n def test_can_get_default_violations_values(self):\n config = Config()\n config.BLACKLIST_DOMAIN = ['a.com']\n\n page = PageFactory.create()\n\n reviewer = Reviewer(\n api_url='http://localhost:2368',\n page_uuid=page.uuid,\n page_url=page.url,\n page_score=0.0,\n config=config,\n validators=[]\n )\n\n validator = BlackListValidator(reviewer)\n\n violations_values = validator.get_default_violations_values(config)\n\n expect(violations_values).to_include('blacklist.domains')\n\n expect(violations_values['blacklist.domains']).to_length(2)\n\n expect(violations_values['blacklist.domains']).to_be_like({\n 'value': config.BLACKLIST_DOMAIN,\n 'description': config.get_description('BLACKLIST_DOMAIN')\n })\n","sub_path":"tests/unit/validators/test_blacklist.py","file_name":"test_blacklist.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"284755596","text":"# *************************************************\n# ********** Multi Object Motion Tracker **********\n# ************ Merav Joseph 200652063 *************\n# ************* Shir Amir 209712801 ***************\n# *************************************************\n\nimport numpy as np\nimport numpy.random as rnd\nimport cv2\n\nSTATE_NUM = 4\nMEASURE_NUM = 2\n\n\nclass Bug:\n bug_counter = 0\n max_path_length = 20\n\n def __init__(self, start_point):\n # The bug's kalman tracker\n self.kalman = cv2.KalmanFilter(STATE_NUM, MEASURE_NUM, 0)\n # H\n self.kalman.measurementMatrix = np.array([[1, 0, 0, 0],\n [0, 1, 0, 0]], np.float32)\n\n # F. In each state we take the previous location with the previous velocity\n self.kalman.transitionMatrix = np.array([[1, 0, 1, 0],\n [0, 1, 0, 1],\n [0, 0, 1, 0],\n [0, 0, 0, 1]],\n np.float32)\n\n self.kalman.processNoiseCov = np.array([[1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]],\n np.float32) * 0.03\n # self.kalman.measurementNoiseCov = np.eye(4, dtype=np.float32) * 10\n # self.kalman.errorCovPost = np.eye(4, dtype=np.float32) * 0.1\n\n # initial state\n self.kalman.statePre = np.array([start_point[0], start_point[1], 0, 0], dtype=np.float32)\n\n # The bug's unique identifier\n self.id = Bug.bug_counter\n Bug.bug_counter = Bug.bug_counter + 1\n\n # The bug's associated color\n self.color = (rnd.randint(255), rnd.randint(255), rnd.randint(255))\n\n # The bug's path\n self.path = [start_point]\n\n self.penalty = 0\n\n def get_position(self):\n return self.path[-1]\n\n def update_path(self, point_observation):\n self.penalty = 0 # initialize penalty after rerecognition\n self.kalman.correct(point_observation)\n pred = self.kalman.predict()\n cx, cy = pred[0], pred[1]\n\n if len(self.path) == Bug.max_path_length:\n self.path.pop(0)\n # self.path.append(np.array([cx, cy]))\n self.path.append(point_observation)\n\n def plot_on_img(self, img, show_box, show_trail, contour=None):\n if show_trail == 1:\n for j, step in enumerate(reversed(self.path)):\n cv2.circle(img, (step[0], step[1]), max(1, int(4 - j * 0.3)), self.color, -1)\n if contour is not None and show_box == 1:\n x, y, w, h = cv2.boundingRect(contour)\n cv2.rectangle(img, (x, y), (x + w, y + h), self.color, 2)\n cv2.putText(img, self.__str__(), (x, y + h + 20), cv2.FONT_HERSHEY_PLAIN, 1.0, self.color, 1)\n\n def __str__(self):\n bug_str = 'bug ' + str(self.id)\n return bug_str\n\n def __repr__(self):\n return \"\" % self.id\n","sub_path":"src/bug.py","file_name":"bug.py","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"361076444","text":"# Various utility functions\n\nimport time\nfrom statistics import median\n\nCONFIG = { \"LOG_LEVEL\": 1}\n\n# ---------------------------------------------------------------------------------------------\n# ---------------------------------------------------------------------------------------------\n# list_to_string() function\n# 'pretty formats' a list for printing, i.e. '[ , , ...]'\n# The actual values can be formatted with a format string, default '{}'\n# e.g. '{:.3f}' will format number as a float with 3 decimal places.\n# ---------------------------------------------------------------------------------------------\n# ---------------------------------------------------------------------------------------------\n\n# Convert [1,2,3] to \"1, 2, 3\" using optional format string e.g \"{:.1f}\"\ndef list_to_string(input_list, format_string=\"{}\"):\n output_string = \"\"\n\n first_separator = \"\"\n\n separator = \", \" ## added *before* each element except first\n\n first_added = False # flag to detect whether we are currently adding first element\n\n for element in input_list:\n if not first_added:\n output_string = output_string + first_separator\n first_added = True\n else:\n output_string = output_string + separator\n\n # add the formatted element\n output_string = output_string + format_string.format(element)\n\n return output_string\n\n# ---------------------------------------------------------------------------------------------\n# ---------------------------------------------------------------------------------------------\n#\n# TimeBuffer class\n#\n# Implements a circular buffer of { \"ts\": , \"value\": } objects (where \"ts\" is the unix timestamp)\n# Generally will return 'None' if method call cannot return a reasonable value (e.g. index in buffer\n# is off the end of the buffer).\n#\n# Initialize with e.g. 'b = TimeBuffer(100)' where 100 is desired size of buffer.\n#\n# b.put(ts, value): add {\"ts\": ts, \"value\": value } to buffer\n#\n# b.get(offset): lookup entry at buffer index offset from now (now = offset ZERO).\n#\n# b.load_readings_file(filename): will reset buffer and load ts,value data from CSV file.\n#\n# b.average_time(time_offset, duration): find average value for\n# 'duration' seconds ending time_offset seconds before latest reading\n#\n# b.median_time(time_offset, duration): as average_time, but return median value\n#\n# ---------------------------------------------------------------------------------------------\n# ---------------------------------------------------------------------------------------------\n\nclass TimeBuffer(object):\n\n def __init__(self, size=1000):\n print(\"TimeBuffer init size={}\".format(size))\n\n # Note sample_history is a *circular* buffer (for efficiency)\n self.SAMPLE_HISTORY_SIZE = size # store value samples 0..(size-1)\n self.sample_history_index = 0\n self.sample_history = [ None ] * self.SAMPLE_HISTORY_SIZE # buffer for 100 value samples ~= 10 seconds\n\n # sample_history: global circular buffer containing { ts:, value:} datapoints\n # sample_history_index: global giving INDEX into buffer for NEXT datapoint\n\n # store the current value in the sample_history circular buffer\n def put(self, ts, value):\n self.sample_history[self.sample_history_index] = { 'ts': ts, 'value': value }\n if CONFIG[\"LOG_LEVEL\"] == 1:\n print(\"record sample_history[{}]:\\n{},{}\".format(self.sample_history_index,\n self.sample_history[self.sample_history_index][\"ts\"],\n self.sample_history[self.sample_history_index][\"value\"]))\n\n self.sample_history_index = (self.sample_history_index + 1) % self.SAMPLE_HISTORY_SIZE\n\n # load timestamp,reading values from a CSV file\n def load(self, filename):\n global CONFIG\n if CONFIG[\"LOG_LEVEL\"] == 1:\n print(\"loading readings file {}\".format(filename))\n\n self.sample_history_index = 0\n self.sample_history = [ None ] * self.SAMPLE_HISTORY_SIZE # buffer for 100 value samples ~= 10 seconds\n\n try:\n with open(filename, \"r\") as fp:\n # read line from file\n line = fp.readline()\n while line:\n line_values = line.split(',')\n # skip lines (e.g. blank lines) that don't seem to have readings\n if len(line_values) == 2:\n ts = float(line_values[0])\n value = float(line_values[1])\n self.sample_history[self.sample_history_index] = { \"ts\": ts,\n \"value\": value }\n print(\"{: >5} {:10.3f} {: >8}\".format(self.sample_history_index,ts,value))\n self.sample_history_index = (self.sample_history_index + 1) % self.SAMPLE_HISTORY_SIZE\n line = fp.readline()\n\n except Exception as e:\n print(\"LOAD FILE ERROR. Can't read supplied filename {}\".format(filename))\n print(e)\n\n # Save the buffer contents to a file as , CSV records, oldest to newest\n def save(self, filename):\n index = self.sample_history_index # index of oldest entry (could be None if buffer not wrapped)\n finish_index = self.sample_history_index\n finished = False\n try:\n with open(filename,\"w+\") as fp:\n # we will loop through the buffer until at latest value at sample_history_index-1\n while not finished:\n sample = self.sample_history[index]\n # skip None samples\n if sample != None:\n sample_value = sample[\"value\"]\n # Add quotes for CSV if necessary\n if isinstance(sample_value, str):\n sample_value = '\"'+sample_value+'\"'\n fp.write(\"{},{}\\n\".format(sample[\"ts\"], sample_value))\n index = (index + 1) % self.SAMPLE_HISTORY_SIZE\n if index == finish_index:\n finished = True\n\n except Exception as e:\n print(\"SAVE FILE ERROR {}\".format(filename))\n print(e)\n\n # Pump all the buffer samples through a provided processing function.\n # I.e. will call 'process_sample(ts, value)' for each sample in the buffer.\n def play(self, process_sample):\n index = self.sample_history_index # index of oldest entry (could be None if buffer not wrapped)\n finish_index = self.sample_history_index\n finished = False\n # we will loop through the buffer until at latest value at sample_history_index-1\n while not finished:\n sample = self.sample_history[index]\n\n # process 'not None' samples\n if sample != None:\n # HERE WE CALL THE PROVIDED FUNCTION\n process_sample(sample[\"ts\"], sample[\"value\"])\n\n index = (index + 1) % self.SAMPLE_HISTORY_SIZE\n if index == finish_index:\n finished = True\n\n # Lookup the value in the sample_history buffer at offset before now (offset ZERO = latest value)\n # This returns None or an object { 'ts': , 'value': }\n def get(self, offset=0):\n if offset == None:\n return None\n if offset >= self.SAMPLE_HISTORY_SIZE:\n if CONFIG[\"LOG_LEVEL\"] == 1:\n print(\"get offset too large, returning None\")\n return None\n index = (self.sample_history_index + self.SAMPLE_HISTORY_SIZE - offset - 1) % self.SAMPLE_HISTORY_SIZE\n if CONFIG[\"LOG_LEVEL\"] == 1:\n if self.sample_history[index] is not None:\n debug_str = \"get current {}, offset {} => {}: {:.2f} {}\"\n print(debug_str.format( self.sample_history_index,\n offset,\n index,\n self.sample_history[index][\"ts\"],\n self.sample_history[index][\"value\"]))\n else:\n debug_str = \"get None @ current {}, offset {} => {}\"\n print(debug_str.format( self.sample_history_index,\n offset,\n index))\n return self.sample_history[index]\n\n # Iterate backwards through sample_history buffer to find index of reading at a given time offset\n def time_to_offset(self,time_offset):\n if CONFIG[\"LOG_LEVEL\"] == 1:\n print(\"time_to_offset\",time_offset)\n\n sample = self.get(0)\n if sample == None:\n return None\n\n sample_time = sample[\"ts\"]\n\n time_limit = sample[\"ts\"] - time_offset\n\n offset = 0\n\n while sample_time > time_limit:\n offset += 1\n if offset >= self.SAMPLE_HISTORY_SIZE:\n print(\"time_to_offset ({}) exceeded buffer size\")\n return None\n sample = self.get(offset)\n if sample == None:\n return None\n sample_time = sample[\"ts\"]\n\n return offset\n\n # Calculate the average value recorded over the previous 'duration' seconds from time_offset seconds.\n # Returns a tuple of , where is the sample_history offset\n # one sample earlier than the offset & duration selected.\n # E.g. average_time(0,3) will find the average value of the most recent 3 seconds.\n # average_time(2,1) will find average during 1 second duration ending 2 seconds ago.\n def average_time(self, time_offset, duration):\n if CONFIG[\"LOG_LEVEL\"] == 1:\n print(\"average_time time_offset={}, duration={}\".format(time_offset, duration))\n\n offset = self.time_to_offset(time_offset)\n\n return self.average(offset, duration)\n\n # average() is like average_time() but uses an INDEX offset rather than time offset\n def average(self, offset, duration):\n # lookup the first value to get that value (grams) and timestamp\n sample = self.get(offset)\n if sample == None:\n return None, offset\n\n next_offset = offset\n total_value = sample[\"value\"]\n begin_limit = sample[\"ts\"] - duration\n sample_count = 1\n while True: # Repeat .. Until\n # select previous index in circular buffer\n next_offset = (next_offset + 1) % self.SAMPLE_HISTORY_SIZE\n if next_offset == offset:\n # we've exhausted the full buffer\n return None\n sample = self.get(next_offset)\n if sample == None:\n # we've exhausted the values in the partially filled buffer\n return None\n if sample[\"ts\"] < begin_limit:\n break\n total_value += sample[\"value\"]\n sample_count += 1\n\n if CONFIG[\"LOG_LEVEL\"] == 1:\n print(\"average total {} average {} with {} samples\".format(total_value,\n total_value/sample_count,\n sample_count))\n return total_value / sample_count, next_offset\n\n # Return the median sample value for a time period.\n # The period is from (latest sample time - time_offset) to (latest sample time - time_offset - duration)\n # All time values are in seconds.\n # Returns a tuple of , where\n # is the sample_history offset of the NEXT sample after the given duration\n # so can be used on a subsequent call)\n def median_time(self, time_offset, duration):\n\n if CONFIG[\"LOG_LEVEL\"] == 1:\n print(\"median_time time_offset={}, duration={}\".format(time_offset, duration))\n\n # Convert time (e.g. 3 seconds) to an index offset from latest reading in sample_history\n offset = self.time_to_offset(time_offset)\n\n return self.median(offset, duration)\n\n # median() is like median_time but uses an INDEX offset rather than a TIME offset.\n # Duration (the length of time to include samples) is still in seconds\n def median(self, offset, duration):\n\n sample = self.get(offset)\n if sample == None:\n return None, offset\n next_offset = offset\n\n begin_limit = sample[\"ts\"] - duration\n if CONFIG[\"LOG_LEVEL\"] == 1:\n print(\"median begin_limit={}\".format(begin_limit))\n\n begin_time = sample[\"ts\"] # this will be updated as we loop, to find duration available\n end_time = sample[\"ts\"]\n\n #if CONFIG[\"LOG_LEVEL\"] == 1:\n # print(\"median_time begin_time {:.3f}\".format(begin_time))\n\n value_list = [ sample[\"value\"] ]\n while True: # Repeat .. Until\n # select previous index in circular buffer\n next_offset = (next_offset + 1) % self.SAMPLE_HISTORY_SIZE\n if next_offset == offset:\n # we've exhausted the full buffer\n break\n\n sample = self.get(next_offset)\n\n if sample == None:\n print(\"median looked back to None value\")\n # we've exhausted the values in the partially filled buffer\n break\n\n # see if we have reached the end of the intended period\n if sample[\"ts\"] < begin_limit:\n break\n\n value_list.append(sample[\"value\"])\n\n begin_time = sample[\"ts\"]\n\n # If we didn't get enough samples, return with error\n if len(value_list) < 3:\n print(\"median not enough samples ({})\".format(len(value_list)))\n return None, None\n\n # Now we have a list of samples with the required duration\n median_value = median(value_list)\n\n if CONFIG[\"LOG_LEVEL\"] == 1:\n print(\"median_value for {:.3f} seconds with {} samples = {}\".format(end_time - begin_time,\n len(value_list),\n median_value))\n\n return median_value, next_offset\n","sub_path":"code/sensor_utils.py","file_name":"sensor_utils.py","file_ext":"py","file_size_in_byte":14383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"437551019","text":"\"\"\"\n\nWhat was that?\n1/6/18\n\nescape characters\n\nstudy drills:\n1. memorize the escape sequences by putting them on flash cards\n2. use \\'\\'\\' instead. why use \\\"\\\"\\\" preferentially\n3. combine escape and format strings to create a more complex format\n\"\"\"\n\n# assign a string to a variable, use the escaped tab\ntabby_cat = \"\\tI'm tabbed in.\"\n# string to variable, use new line in middle of string\npersian_cat = \"I'm split\\non a line.\"\n# string to variable, use backslash escaped\nbackslash_cat = \"I'm \\\\ a \\\\ cat.\"\n\n# assign a triple-quoted string to variable using tab and newlines,\n# fancy formatting\nfat_cat = '''\nI'll do a list:\n\\t* Cat food\n\\t* Fishies\n\\t* Catnip\\n\\t* Grass\n'''\n\n# print each of the variables\nprint(tabby_cat)\nprint(persian_cat)\nprint(backslash_cat)\nprint(fat_cat)\n\n# 3. combine escape and format strings to create a more complex format\n\nwide_cat = \"\"\"\n\\tVery wide cat\\n\\t\\tis\\n\\n\\t\\t\\t\\tthis wide\n\"\"\"\n\nprint(wide_cat)\n","sub_path":"ex10.py","file_name":"ex10.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"304367249","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom sys import argv\nimport numpy as np\nfrom ipdb import set_trace\n\nif __name__ == \"__main__\":\n\tdirname = argv[1]\n\n\tprint(\"checking the dir %s\"%dirname)\n\ttry:\n\t\tdata = pd.read_csv(dirname + \"progress.csv\")\n\t\teval_data = data[\"eval/return_history\"]\n\n\t\tplt.plot(data[\"total/epochs\"], data[\"eval/return_history\"], label='eval')\n\t\tplt.plot(data[\"total/epochs\"], data[\"rollout/return_history\"], label='train')\n\t\tplt.legend()\n\t\tplt.xlabel('Epochs --->')\n\t\tplt.ylabel('Episode Reward ---->')\n\t\tplt.show()\n\n\t\tprint(\"last reward in train:\",data[\"rollout/return_history\"][-1])\n\n\texcept Exception as e:\n\t\tprint(e)\n\n","sub_path":"baselines/ddpg/plot_results_progress.py","file_name":"plot_results_progress.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"376298330","text":"\"\"\"Utils for trafikverket_train.\"\"\"\nfrom __future__ import annotations\n\nfrom datetime import time\n\n\ndef create_unique_id(\n from_station: str, to_station: str, depart_time: time | str | None, weekdays: list\n) -> str:\n \"\"\"Create unique id.\"\"\"\n timestr = str(depart_time) if depart_time else \"\"\n return (\n f\"{from_station.casefold().replace(' ', '')}-{to_station.casefold().replace(' ', '')}\"\n f\"-{timestr.casefold().replace(' ', '')}-{str(weekdays)}\"\n )\n","sub_path":"homeassistant/components/trafikverket_train/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"149991404","text":"from direct.actor.Actor import Actor\r\nfrom direct.showbase import Audio3DManager\r\nfrom defines import *\r\nfrom panda3d.core import loadPrcFileData\r\nloadPrcFileData(\"\", \"audio-library-name p3fmod_audio\")\r\n\r\nPUSHY_PATH = \"../resources/character/all/\"\r\nPUSHY_AUDIO_PATH = \"../resources/audio/effects/\"\r\nPUSHY_SKIN_PATH = \"../resources/character/skins/\"\r\nclass Player(Actor):\r\n def __init__(self, name):\r\n Actor.__init__(self,PUSHY_PATH+\"pushy.x\",\r\n {\"charge_start\":PUSHY_PATH+\"pushy_charge_start.x\",\r\n \"charge\":PUSHY_PATH+\"pushy_charge.x\",\r\n \"charge_release\":PUSHY_PATH+\"pushy_charge_release.x\",\r\n \"charge_fly\":PUSHY_PATH+\"pushy_charge_fly.x\",\r\n \"charge_hit\":PUSHY_PATH+\"pushy_charge_hit.x\",\r\n \"charge_miss\":PUSHY_PATH+\"pushy_charge_miss.x\",\r\n \"normal\":PUSHY_PATH+\"pushy_menu.x\",\r\n \"fall\":PUSHY_PATH+\"pushy_fall.x\",\r\n \"run\":PUSHY_PATH+\"pushy_run.x\",\r\n \"run_start\":PUSHY_PATH+\"pushy_run.x\",\r\n \"standup\":PUSHY_PATH+\"pushy_standup.x\",\r\n \"stop\":PUSHY_PATH+\"pushy_stop.x\",\r\n \"walk\":PUSHY_PATH+\"pushy_walk.x\"})\r\n self.name = name\r\n self.setName(name)\r\n self.health = 1.0\r\n self.setScale(0.4)\r\n self.setPlayRate(0.05, \"fall\")\r\n self.setPlayRate(0.05, \"charge_hit\")\r\n self.setPlayRate(0.05, \"charge_miss\")\r\n self.setPlayRate(0.03, \"standup\")\r\n self.setPlayRate(0.05, \"charge_release\")\r\n self.setPlayRate(0.1, \"run\") \r\n self.flyingTime = 0\r\n\r\n self.acFall=self.getAnimControl(\"fall\")\r\n self.acStandup=self.getAnimControl(\"standup\")\r\n\r\n self.acChargeStart=self.getAnimControl(\"charge_start\")\r\n self.acCharge=self.getAnimControl(\"charge\")\r\n self.acChargeRelease=self.getAnimControl(\"charge_release\")\r\n self.acChargeFly=self.getAnimControl(\"charge_fly\")\r\n\r\n self.acRunStart=self.getAnimControl(\"run_start\")\r\n self.acRun=self.getAnimControl(\"run\")\r\n # blender rotation fix\r\n self.find(\"**/+GeomNode\").setH(180)\r\n \r\n self.rotationSpeed = 300\r\n self.movementSpeed = 25\r\n self.movementSpeedFlying = 50\r\n self.movementSpeedFalling = 50\r\n\r\n self.status = PLAYER_STATUS_NORMAL\r\n self.subStatus = 0\r\n self.updateAnimation()\r\n \r\n #audio3d = Audio3DManager.Audio3DManager(base.sfxManagerList[0], camera)\r\n #mySound = audio3d.loadSfx('/audio/1.wav')\r\n self.chargeSound = base.loader.loadSfx(PUSHY_AUDIO_PATH+\"Game Jam - Action - Charging 04.ogg\")\r\n self.boringSound = base.loader.loadSfx(PUSHY_AUDIO_PATH+\"Game Jam - Action - Boring 01.ogg\")\r\n base.taskMgr.add(self.updateAnimTask, \"update animation task\")\r\n\r\n def updateAnimTask(self, task):\r\n if self.status == PLAYER_STATUS_CHARGING:\r\n if self.subStatus == PLAYER_CHARGE_GATHER:\r\n if not self.acChargeStart.isPlaying() and not self.acCharge.isPlaying():\r\n self.acCharge.play()\r\n elif self.subStatus == PLAYER_CHARGE_UNLEASH:\r\n if not acChargeRelease.isPlaying() and not self.acChargeFly.isPlaying():\r\n self.acChargeFly.play()\r\n elif self.status == PLAYER_STATUS_MOVING:\r\n if not self.acRunStart.isPlaying() and not self.acRun.isPlaying():\r\n #self.acRun.loop()\r\n pass\r\n elif self.status == PLAYER_STATUS_FALLING:\r\n if not self.acRunStart.isPlaying() and not self.acRun.isPlaying():\r\n #self.acRun.loop()\r\n pass\r\n\r\n \r\n def updateAnimation(self):\r\n if self.status == PLAYER_STATUS_NORMAL:\r\n self.loop(\"normal\")\r\n\r\n elif self.status == PLAYER_STATUS_JUMPING:\r\n self.play(\"normal\")\r\n elif self.status == PLAYER_STATUS_CHARGING:\r\n if self.subStatus == PLAYER_CHARGE_GATHER:\r\n self.chargeSound.play()\r\n #self.acChargeStart.play()\r\n self.acCharge.play()\r\n elif self.subStatus == PLAYER_CHARGE_UNLEASH:\r\n self.chargeSound.setTime(1.975)\r\n self.chargeSound.play()\r\n #self.acChargeRelease.play()\r\n #self.acCharge.play()\r\n self.loop(\"charge_fly\")\r\n elif self.subStatus == PLAYER_CHARGE_MISS:\r\n self.play(\"charge_miss\")\r\n # TODO: this does not work correctly\r\n else:\r\n self.chargeSound.setTime(0)\r\n self.chargeSound.play()\r\n self.loop(\"charge\")\r\n elif self.status == PLAYER_STATUS_MOVING:\r\n #self.acRunStart.play()\r\n #self.acRun.loop()\r\n self.loop(\"run\")\r\n #self.boringSound.play()\r\n elif self.status == PLAYER_STATUS_FALLING:\r\n #self.acRunStart.play()\r\n #self.acRun.loop()\r\n self.play(\"fall\")\r\n #self.boringSound.play()\r\n\r\n \r\n def rotateLeft(self):\r\n self.setH(self.getH() + self.rotationSpeed * globalClock.getDt())\r\n if self.isMoving == False:\r\n self.isMoving = True\r\n self.updateAnimation()\r\n \r\n def rotateRight(self):\r\n self.setH(self.getH() - self.rotationSpeed * globalClock.getDt())\r\n if self.isMoving == False:\r\n self.isMoving = True\r\n self.updateAnimation()\r\n \r\n def moveForward(self):\r\n self.setY(self, - self.movementSpeed * globalClock.getDt())\r\n if self.isMoving == False:\r\n self.isMoving = True\r\n self.updateAnimation()\r\n \r\n def moveBackward(self):\r\n self.setY(self, self.movementSpeed * globalClock.getDt())\r\n if self.isMoving == False:\r\n self.isMoving = True\r\n self.updateAnimation()\r\n \r\n def stopMoving(self):\r\n if self.isMoving == True:\r\n self.isMoving = False\r\n self.updateAnimation()\r\n \r\n def charge(self):\r\n #self.setY(self, -3 * globalClock.getDt())\r\n if(self.isCharging == False):\r\n #audio3d.attachSoundToObject(mySound, self)\r\n self.isCharging = True\r\n self.loop(\"charge\")\r\n else:\r\n self.flyingTime = self.flyingTime + 1;\r\n\r\n \r\n def stopCharge(self):\r\n if(self.isCharging == True):\r\n self.isCharging = False\r\n self.loop(\"charge_fly\")\r\n self.isFlying = True\r\n #self.mySound.stop()\r\n #self.mySound = base.loader.loadSfx(\"4.ogg\")\r\n self.chargeSound.setTime(1.975)\r\n self.chargeSound.play()\r\n if(self.isFlying == True):\r\n self.flyingTime = self.flyingTime-1\r\n self.setY(self, -self.movementSpeedFlying * globalClock.getDt())\r\n if(self.flyingTime <= 0):\r\n self.isFlying = False\r\n self.play(\"charge_miss\")\r\n \r\n \r\n def fall(self):\r\n if(self.isFalling == False and self.acStandup.isPlaying() == False):\r\n self.isFalling = True\r\n self.acFall.play()\r\n if(self.acFall.isPlaying() == True):\r\n self.setY(self, +self.movementSpeedFalling * globalClock.getDt())\r\n else:\r\n if self.acStandup.isPlaying() == False:\r\n self.acStandup.play()\r\n else:\r\n self.isFalling = False\r\n \r\n def setColor(self, color):\r\n #if color == \"blue\":\r\n skin = \"skin_pushy_blue.jpg\"\r\n if color == \"green\":\r\n skin = \"skin_pushy_green.jpg\"\r\n elif color == \"red\":\r\n skin = \"skin_pushy_red.jpg\"\r\n elif color == \"pushette\":\r\n skin = \"skin_pushette.jpg\"\r\n elif color == \"bonbon_blue\":\r\n skin = \"skin_pushy_bonbon_blue.jpg\"\r\n elif color == \"bonbon_green\":\r\n skin = \"skin_pushy_bonbon_green.jpg\"\r\n elif color == \"stony_blue\":\r\n skin = \"skin_pushy_stony_blue.jpg\"\r\n elif color == \"stony_green\":\r\n skin = \"skin_pushy_stony_green.jpg\"\r\n elif color == \"stony_red\":\r\n skin = \"skin_pushy_stony_red.jpg\"\r\n myTexture = loader.loadTexture(PUSHY_SKIN_PATH + skin)\r\n self.setTexture(myTexture,1)\r\n\r\n def stopAnimation(self):\r\n \"\"\"docstring for stopAnimation\"\"\"\r\n self.stop()\r\n\r\n def setStatus(self, status, jumpSubStatus, chargeSubStatus):\r\n \"\"\" \"\"\"\r\n animationChanged = False\r\n if not self.status == status:\r\n if status == PLAYER_STATUS_CHARGING:\r\n self.subStatus = PLAYER_CHARGE_GATHER\r\n self.stopAnimation()\r\n self.status = status\r\n animationChanged = True\r\n else:\r\n if status == PLAYER_STATUS_JUMPING:\r\n if not jumpSubStatus == self.subStatus:\r\n self.stopAnimation()\r\n self.subStatus = jumpSubStatus\r\n animationChanged = True\r\n elif status == PLAYER_STATUS_CHARGING: \r\n if not chargeSubStatus == self.subStatus:\r\n self.stopAnimation()\r\n self.subStatus = chargeSubStatus\r\n animationChanged = True\r\n if animationChanged:\r\n self.updateAnimation()\r\n \r\n","sub_path":"src/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":9561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"419887611","text":"from sklearn.preprocessing import KBinsDiscretizer\n# 欄位\nX_col_num = ['Fare', 'Age']\nX_col_bin = ['SibSp', 'Parch']\nX_col_cat = ['Pclass', 'Sex', 'Embarked']\n# 資料管道器\nnum_pl = make_pipeline(\n SimpleImputer(strategy='mean'),\n StandardScaler()\n)\nbin_pl = make_pipeline(\n SimpleImputer(strategy='mean'),\n KBinsDiscretizer(n_bins=5, encode='ordinal'),\n)\ncat_pl = make_pipeline(\n SimpleImputer(strategy='constant', fill_value='missing'),\n OneHotEncoder()\n)\n# 合併後的資料管道器\ndata_pl = ColumnTransformer([\n ('num', num_pl, X_col_num),\n ('bin', bin_pl, X_col_bin),\n ('cat', cat_pl, X_col_cat)\n])\n# 模型預測\nmodel_pl = make_pipeline(data_pl, SVC())\nmodel_pl.fit(X_train, y_train)\ny_pred = model_pl.predict(X_test)\nprint(confusion_matrix(y_test, y_pred))\nprint('整體正確率:',accuracy_score(y_test, y_pred).round(2))","sub_path":"docs/cd/06443007程式碼/ch08/8-23.py","file_name":"8-23.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"338242451","text":"# -*- coding: utf-8 -*-\n\"\"\"\nData Prep for Baysian experiment\n\nThis file is meant to help prepare the environment for \nbayesian intestigation of data.\n\"\"\"\nfrom loader import np,grab_page_dict\nimport pandas as pd\nimport scipy.stats as stats\n\nD = {\n 0:[\n 'https://github.com/AllenDowney/ModSimPy',',',0,\n 'https://raw.githubusercontent.com/AllenDowney/ModSimPy/'+\n 'master/code/data/glucose_insulin.csv',\n ],\n}\n#for data in grab_page_dict(D):\n","sub_path":"python/bayes/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"547303271","text":"from django.contrib import admin\nfrom django.contrib.sites.models import Site\nfrom django.utils.translation import ugettext, ugettext_lazy as _\nfrom modeltranslation.admin import TranslationAdmin\nfrom simple_history.admin import SimpleHistoryAdmin\nfrom core.models import BaseModel, SiteCustomization\n\n\nclass BaseModelMixin(object):\n def get_fieldsets(self, request, obj=None):\n fieldsets_base = (\n (\n _(\"generic fields\"),\n {\n \"classes\": (\"collapse\",),\n \"fields\": (\n \"id\",\n \"created_at\",\n \"created_by\",\n \"changed_at\",\n \"changed_by\",\n ),\n },\n ),\n (\n _(\"common editable fields\"),\n {\n \"fields\": (\n \"owner\",\n \"metadata\",\n ),\n },\n ),\n )\n if self.fields:\n return fieldsets_base + ((_(\"specific fields\"), {\"fields\": self.fields}),)\n return fieldsets_base\n\n def get_readonly_fields(self, request, obj=None):\n readonly_fields_base = (\n \"id\",\n \"created_at\",\n \"created_by\",\n \"changed_at\",\n \"changed_by\",\n )\n\n if obj:\n return self.readonly_fields + readonly_fields_base\n else:\n return self.readonly_fields + readonly_fields_base + (\"owner\",)\n\n def get_list_display(self, request):\n list_display_base = (\n \"created_at\",\n \"created_by\",\n \"changed_at\",\n \"changed_by\",\n )\n return self.list_display + list_display_base\n\n def get_search_fields(self, request):\n return self.search_fields + (\"id\",)\n\n def save_model(self, request, obj, form, change):\n if not change:\n obj.owner = request.user\n super().save_model(request, obj, form, change)\n\n def save_related(self, request, form, formsets, change):\n \"\"\"Méthode appellée lorsqu'un objet est créé via un formulaire inline\"\"\"\n\n for formset in formsets:\n\n if issubclass(formset.model, BaseModel):\n instances = formset.save(commit=False)\n\n for added_obj in formset.new_objects:\n added_obj.owner = request.user\n\n for deleted_obj in formset.deleted_objects:\n pass\n\n super(BaseModelMixin, self).save_related(request, form, formsets, change)\n\n\nclass SiteAdmin(SimpleHistoryAdmin):\n pass\n\n\nadmin.site.unregister(Site)\nadmin.site.register(Site, SiteAdmin)\n\n\nclass SiteCustomizationAdmin(TranslationAdmin, SimpleHistoryAdmin):\n pass\n\n\nadmin.site.register(SiteCustomization, SiteCustomizationAdmin)\n","sub_path":"core/apps/core/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"592408013","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 ('asset_portal', '0002_auto_20150507_1356'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='EncodeBlurayJob',\n fields=[\n ('job_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='asset_portal.Job')),\n ('status', models.IntegerField(default=1, choices=[(0, b'Error'), (1, b'Requested'), (50, b'In Progress'), (100, b'Finished')])),\n ],\n options={\n 'abstract': False,\n },\n bases=('asset_portal.job',),\n ),\n migrations.CreateModel(\n name='EncodeDVDJob',\n fields=[\n ('job_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='asset_portal.Job')),\n ('status', models.IntegerField(default=1, choices=[(0, b'Error'), (1, b'Requested'), (50, b'In Progress'), (100, b'Finished')])),\n ('video_format', models.CharField(default=b'NTSC', max_length=10, choices=[(b'NTSC', b'NTSC'), (b'PAL', b'PAL')])),\n ],\n options={\n 'abstract': False,\n },\n bases=('asset_portal.job',),\n ),\n migrations.RemoveField(\n model_name='senddvdjob',\n name='video_format',\n ),\n ]\n","sub_path":"asset_portal/migrations/0003_auto_20150518_1505.py","file_name":"0003_auto_20150518_1505.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"574267410","text":"import hashlib\nimport random\n\nfrom django import forms\nfrom django.contrib.auth.models import User\nfrom django.core.validators import EmailValidator, RegexValidator\n\nfrom invitations.models import Invitation\n\nfrom ...forms import MyBaseModelForm, MyBaseForm\nfrom . import models\nfrom ..leagues.models import League\nfrom ...constants import (INPUT_CRITERIA, COMPETITION_DI,\n MATCHUP_TYPE_DI, NAME_REGEX)\nfrom ...fields import MultiTimeField\nfrom ...utils import send_notification\n\n\nclass CompetitionSubForm(MyBaseModelForm):\n def __init__(self, *args, **kwargs):\n required = kwargs.pop(\"required\", None)\n self.request = kwargs.pop(\"request\", None)\n self.user = self.request.user if self.request else None\n super(CompetitionSubForm, self).__init__(*args, **kwargs)\n if required is not None:\n for name, field in self.fields.items():\n field.required = required\n\n def save(self, commit=True, competition=None):\n instance = super(CompetitionSubForm, self).save(commit=False)\n\n if not getattr(instance, \"competition\", False):\n if competition:\n instance.competition = competition\n else:\n commit = False\n\n if commit:\n instance.save()\n return instance\n\n\nclass SeriesForm(CompetitionSubForm):\n class Meta:\n model = models.Series\n fields = ['series_type', 'series_games']\n\n\nclass TournamentForm(CompetitionSubForm):\n class Meta:\n model = models.Tournament\n fields = ['tourney_type', 'tourney_seeds']\n\n\nclass SeasonForm(CompetitionSubForm):\n class Meta:\n model = models.Season\n fields = '__all__'\n exclude = ['competition', 'status']\n\n\nclass CompetitionForm(MyBaseModelForm):\n dependent_inputs = None\n form_classes = [SeriesForm, TournamentForm, SeasonForm]\n parent = None\n league = None\n\n time = MultiTimeField()\n competing = forms.BooleanField(label=\"Are you competing?\", required=True, initial=True)\n\n class Meta:\n model = models.Competition\n fields = ['name', 'competition_type', 'game', 'matchup_type', 'split_teams', 'players_per_team',\n 'date', 'time', 'notes']\n widgets = {\"notes\": forms.Textarea()}\n\n def __init__(self, *args, **kwargs):\n self.parent = kwargs.pop(\"parent\", None)\n initial = kwargs.get(\"initial\")\n if initial and \"league\" in initial:\n league = League.object.filter(pk=initial[\"league\"])\n if league.exists():\n self.league = league.get()\n else:\n initial.pop(\"league\")\n super(CompetitionForm, self).__init__(*args, **kwargs)\n self.fields['competition_type'].choices = self.fields['competition_type'].choices[0:6]\n if self.parent:\n self.fields['competition_type'].choices = self.fields['competition_type'].choices[0:5]\n self.fields.pop(\"league\", None)\n self.fields.pop(\"competing\", None)\n self.fields.pop(\"matchup_type\", None)\n self.fields.pop(\"split_teams\", None)\n self.fields.pop(\"players_per_team\", None)\n if self.league:\n self.fields.pop(\"league\", None)\n elif not self.parent and \"league\" in self.fields:\n self.fields['league'].queryset = \\\n self.user.profile.comm_leagues.order_by(\"league_name\")\n field_order = ['name', 'competition_type', 'game',]\n for form_class in self.form_classes:\n subform_fields = form_class(required=False, *args, **kwargs).fields\n self.fields.update(subform_fields)\n field_order += list(subform_fields.keys())\n field_order.append('matchup_type')\n self.dependent_inputs = [COMPETITION_DI, MATCHUP_TYPE_DI]\n for input_tree in self.dependent_inputs:\n self.add_actions(input_tree)\n self.order_fields(field_order)\n\n def clean(self):\n super(CompetitionForm, self).clean()\n\n for input_tree in self.dependent_inputs:\n self.clean_dependent_inputs(input_tree, INPUT_CRITERIA)\n\n def save(self, commit=True):\n competition = super(CompetitionForm, self).save(commit=False)\n profile = self.user.profile\n competition.parent = self.parent\n competition.creator = profile\n\n if commit:\n cleaned_data = self.cleaned_data\n if not self.parent:\n if self.league:\n competition.league = self.league\n competition.save()\n if competition.league:\n competition.invite_league()\n if cleaned_data[\"competing\"]:\n competition.add_competitor(player=profile)\n else:\n competition.matchup_type = self.parent.matchup_type\n competition.save()\n competition_type = cleaned_data[\"competition_type\"]\n if competition_type in range(2, 5):\n self.form_classes[competition_type - 2](cleaned_data).save(competition=competition)\n return competition\n\n\nclass EditCompetitionForm(MyBaseModelForm):\n sub_form_classes = [SeriesForm, TournamentForm, SeasonForm]\n sub_instance = None\n sub_form_class = None\n\n time = MultiTimeField()\n\n class Meta:\n model = models.Competition\n fields = [\"name\", \"game\",\n \"date\", \"time\",\n \"venue\", \"notes\"]\n widgets = {\"notes\": forms.Textarea()}\n\n def __init__(self, *args, **kwargs):\n super(EditCompetitionForm, self).__init__(*args, **kwargs)\n if self.instance:\n comp_type = self.instance.competition_type\n if comp_type in range(2, 5):\n self.sub_instance = self.instance.competition_details\n self.sub_form_class = self.sub_form_classes[comp_type - 2]\n sub_form = self.sub_form_class(instance=self.sub_instance)\n self.fields.update(sub_form.fields)\n self.initial.update(sub_form.initial)\n self.dependent_inputs = [COMPETITION_DI]\n for input_tree in self.dependent_inputs:\n self.add_actions(input_tree)\n\n def save(self, commit=True):\n competition = super(EditCompetitionForm, self).save()\n cleaned_data = self.cleaned_data\n if self.sub_form_class:\n self.sub_form_class(cleaned_data, instance=self.sub_instance).save()\n return competition\n\n\nclass InlineEditCompetitionForm(MyBaseModelForm):\n time = MultiTimeField()\n\n class Meta:\n model = models.Competition\n fields = [\"date\", \"time\", \"venue\"]\n\n\nclass MatchupForm(MyBaseModelForm):\n time = MultiTimeField()\n\n class Meta:\n model = models.Matchup\n fields = [\"date\", \"time\", \"notes\"]\n widgets = {\"notes\": forms.Textarea()}\n\n\nclass MatchupResultFormset(forms.BaseInlineFormSet):\n def clean(self):\n if any(self.errors):\n return\n first_place_count = 0\n form_count = self.total_form_count()\n for form in self.forms:\n place = form.cleaned_data['place']\n if place > form_count:\n form.add_error(\"place\", \"Invalid place.\")\n if place == 1:\n first_place_count += 1\n if first_place_count > 1:\n raise forms.ValidationError(\"Can not have multiple first places.\")\n\n\nclass MatchupResultForm(MyBaseModelForm):\n place = forms.ChoiceField(choices=((1, 1), (2, 2)))\n\n class Meta:\n model = models.MatchupCompetitor\n fields = [\"place\"]\n\n def __init__(self, *args, **kwargs):\n super(MatchupResultForm, self).__init__(*args, **kwargs)\n if self.instance:\n count = self.instance.opponents.count()\n if count > 1:\n self.fields[\"place\"].choices = ((x, x) for x in range(1, count + 2))\n\n def clean(self):\n cleaned_data = super(MatchupResultForm, self).clean()\n place = cleaned_data.get(\"place\")\n if place:\n cleaned_data[\"place\"] = int(place)\n return cleaned_data\n\n def save(self, commit=True):\n instance = super(MatchupResultForm, self).save(commit=True)\n print(instance.place)\n instance.update_status()\n return instance\n\n\nclass CompetitionSignUpForm(MyBaseModelForm):\n change_key = forms.BooleanField(required=False)\n\n class Meta:\n model = models.CompetitionSignUpPage\n fields = ['expiration', 'msg_image']\n\n def __init__(self, *args, **kwargs):\n self.competition = kwargs.pop(\"instance\", None)\n if getattr(self.competition, \"signup_page\", None):\n kwargs[\"instance\"] = self.competition.signup_page\n super(CompetitionSignUpForm, self).__init__(*args, **kwargs)\n if not self.instance.pk:\n self.fields.pop(\"change_key\")\n\n def save(self, commit=True):\n instance = super(CompetitionSignUpForm, self).save(commit=False)\n if not instance.pk:\n instance.competition = self.competition\n if not instance.pk or self.cleaned_data.get(\"change_key\"):\n salt = hashlib.sha1(str(random.random()).encode()).hexdigest()[:5]\n instance.verification_key = hashlib.sha1((salt + self.competition.name).encode()).hexdigest()\n if commit:\n instance.save()\n return instance.competition\n\n\nclass AddCompetitorForm(MyBaseModelForm):\n player_search = forms.CharField(validators=[EmailValidator(code=\"invalid\")],\n required=False, max_length=50)\n team_name = forms.CharField(validators=[RegexValidator(NAME_REGEX)],\n max_length=30, required=False)\n invite = None\n approved = True\n\n class Meta:\n model = models.CompetitionInvite\n fields = ['competitor', 'player']\n widgets = {'player': forms.HiddenInput}\n\n def __init__(self, *args, **kwargs):\n self.parent = kwargs.pop(\"parent\", None)\n self.competition = self.parent if self.approved else self.parent.competition\n\n super(AddCompetitorForm, self).__init__(*args, **kwargs)\n self.fields[\"player\"].required = False\n player_search = self.fields[\"player_search\"]\n player_search.widget.attrs.update({\n \"data-content\": \"Search for an existing user or invite a new user by entering their email below.\",\n \"data-placement\": \"top\",\n \"data-container\": \"body\",\n \"data-trigger\": \"focus\"\n })\n if self.approved and self.competition.matchup_type == 2 \\\n and self.competition.split_teams == 1:\n competitor_field = self.fields['competitor']\n competitor_field.queryset = \\\n self.competition.competitor_set.filter(status=1).order_by(\"team_name\")\n competitor_field_classes = competitor_field.widget.attrs.get(\"class\", \"\")\n competitor_field.widget.attrs.update({\n \"class\": competitor_field_classes + \" hidden-select combobox\",\n \"data-combobox-container\": \"#team_combobox\"\n })\n self.fields['team_name'].widget.attrs.update({\n \"autocomplete\": \"off\"\n })\n else:\n self.fields.pop('competitor')\n self.fields.pop('team_name')\n self.added = False\n\n def clean(self):\n cleaned_data = super(AddCompetitorForm, self).clean()\n if not cleaned_data[\"player\"]:\n player_email = cleaned_data.get(\"player_search\", None)\n if player_email:\n user = User.objects.filter(email=player_email)\n\n if user.exists():\n cleaned_data[\"player\"] = user.get().profile\n else:\n self.invite = Invitation.create(email=player_email, inviter=self.request.user)\n else:\n raise forms.ValidationError(\n 'must enter a valid competitor'\n )\n\n if self.approved and not cleaned_data.get(\"competitor\", False) and cleaned_data.get(\"team_name\", None):\n competitor, created = models.Competitor.objects.get_or_create(team_name=cleaned_data[\"team_name\"],\n competition=self.competition,\n competitor_type=2)\n if created:\n competitor.status = 0\n competitor.save()\n cleaned_data[\"competitor\"] = competitor\n if not self.invite:\n if cleaned_data[\"player\"] in self.competition.players:\n if self.competition.matchup_type == 2 and self.approved:\n if cleaned_data.get(\"competitor\", False):\n competitor = cleaned_data['competitor']\n if not isinstance(competitor, models.Competitor):\n competitor = models.Competitor.objects.get(id=competitor)\n old_competitor = self.competition.get_competitor(cleaned_data[\"player\"])\n if competitor.id != old_competitor.id:\n if old_competitor.status == 0:\n old_competitor.delete()\n else:\n old_competitor.players.remove(cleaned_data[\"player\"])\n competitor.players.add(cleaned_data[\"player\"])\n competitor.status = 1\n competitor.save()\n self.added = True\n else:\n raise forms.ValidationError(\n 'Player already exists.',\n code='duplicate'\n )\n return cleaned_data\n\n def save(self, commit=True):\n if not self.added:\n cleaned_data = self.cleaned_data\n if cleaned_data['player']:\n params = {\"player\": cleaned_data[\"player\"],\n \"competition\": self.competition}\n if not self.approved:\n params[\"invite_type\"] = 2\n params[\"competitor\"] = self.parent\n else:\n params[\"invite_type__in\"] = [1, 3]\n existing_invites = models.CompetitionInvite.objects.filter(**params)\n if existing_invites.exists():\n existing_invites.delete()\n if existing_invites.filter(accepted=True):\n competitor = self.competition.add_competitor(player=cleaned_data[\"player\"])\n return competitor\n pending_player = super(AddCompetitorForm, self).save(commit=False)\n pending_player.competition = self.competition\n if self.invite:\n self.invite.send_invitation(self.request)\n pending_player.invite = self.invite\n if self.approved:\n pending_player.invite_type = 1\n else:\n pending_player.invite_type = 2\n pending_player.competitor = self.parent\n pending_player.approved = self.approved\n\n if commit:\n pending_player.save()\n return self.parent\n\n\nclass CompetitorInviteForm(AddCompetitorForm):\n approved = False\n\n\nclass EditCompetitorForm(MyBaseModelForm):\n seed = forms.ChoiceField(required=False)\n\n class Meta:\n model = models.Competitor\n fields = ['team_name', 'captain']\n\n def __init__(self, *args, **kwargs):\n super(EditCompetitorForm, self).__init__(*args, **kwargs)\n self.add_player = False\n competition = self.instance.competition\n if self.instance.competitor_type == 1:\n self.fields.pop('team_name')\n self.fields.pop('captain')\n elif self.instance.status == 0:\n teams = competition.competitors.filter(team_name__isnull=False).values_list(\"team_name\")\n self.fields[\"team_name\"] = forms.ChoiceField(required=False,\n choices=[(\"\", \"--------\")] + [(team, team) for team in teams])\n self.fields[\"team_name\"].widget.attrs.update({\"class\": \"form-control\"})\n self.fields.pop('captain')\n else:\n self.fields[\"team_name\"].required = True\n self.fields['captain'].queryset = self.instance.players\n if competition.competition_type != 3\\\n or competition.competition_details.tourney_seeds == 1:\n self.fields.pop('seed')\n else:\n self.fields['seed'].choices = [(x, x) for x in range(1, competition.competitor_set.count() + 1)]\n self.initial.update({\"seed\": self.instance.seed()})\n\n def clean(self):\n cleaned_data = super(EditCompetitorForm, self).clean()\n if cleaned_data.get('team_name'):\n teams = self.instance.competition.competitor_set.filter(team_name=cleaned_data['team_name'])\n if self.instance.team_name != cleaned_data[\"team_name\"] and teams.exists():\n if self.instance.players.count() > 1:\n raise forms.ValidationError(\n 'Team name already exists.',\n code='duplicate'\n )\n else:\n self.add_player = True\n teams.first().players.add(self.instance.players.first())\n return cleaned_data\n\n def save(self, commit=True):\n if self.add_player:\n self.instance.delete()\n else:\n instance = super(EditCompetitorForm, self).save()\n seed = self.cleaned_data.get(\"seed\")\n if seed and seed != self.initial.get(\"seed\"):\n instance.add_seed(seed)\n return instance\n","sub_path":"dublyou/apps/bountygames/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":17903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"127649293","text":"import pyramid_handlers\nfrom blueyellow_pycharm_app.controllers.base_controller import BaseController\nfrom blueyellow_pycharm_app.viewmodels.register_viewmodel import RegisterViewModel\n\n\nclass AccountController(BaseController):\n @pyramid_handlers.action(renderer='templates/account/index.pt')\n def index(self):\n return {}\n\n @pyramid_handlers.action(renderer='templates/account/signin.pt')\n def signin(self):\n return{}\n\n #GET / account / register\n @pyramid_handlers.action(renderer = 'templates/account/register.pt',\n request_method = 'GET',\n name = 'register')\n def register_get(self):\n print('Calling register via GET...')\n vm = RegisterViewModel()\n return vm.to_dict()\n\n #POST\n @pyramid_handlers.action(renderer = 'templates/account/register.pt',\n request_method = 'POST',\n name = 'register')\n def register_post(self):\n print('Calling register via POST...')\n vm = RegisterViewModel()\n vm.from_dict(self.request.POST)\n\n vm.validate()\n if vm.error:\n return vm.to_dict()\n\n print('Redirecting to account index page...')\n self.redirect('/account')","sub_path":"web-starter/blueyellow_pycharm_app/blueyellow_pycharm_app/controllers/account_controller.py","file_name":"account_controller.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"506595081","text":"from abc import ABCMeta, abstractmethod\nfrom sklearn.model_selection._search import BaseSearchCV\nfrom sklearn.model_selection._search import _check_param_grid\nfrom sklearn.model_selection._split import check_cv\nfrom sklearn.model_selection._validation import _fit_and_score\nfrom sklearn.metrics._scorer import _check_multimetric_scoring\nfrom sklearn.utils.validation import indexable, check_is_fitted, _check_fit_params\nfrom sklearn.base import is_classifier, clone, BaseEstimator\nfrom sklearn.model_selection import ParameterGrid\nfrom joblib import Parallel, delayed\nfrom itertools import product\nimport time \nimport numpy as np\n\nimport arcus.azureml.experimenting.trainer as trainer\n\nclass ArcusBaseSearchCV(BaseSearchCV):\n __metaclass__ = ABCMeta\n\n def __init__(self, estimator, param_grid, *, scoring=None,\n n_jobs=None, iid='deprecated', refit=True, cv=None,\n verbose=0, pre_dispatch='2*n_jobs',\n error_score=np.nan, return_train_score=False):\n super().__init__(\n estimator=estimator, scoring=scoring,\n n_jobs=n_jobs, iid=iid, refit=refit, cv=cv, verbose=verbose,\n pre_dispatch=pre_dispatch, error_score=error_score,\n return_train_score=return_train_score)\n self.param_grid = param_grid\n _check_param_grid(param_grid)\n\n def _run_search(self, evaluate_candidates):\n \"\"\"Search all candidates in param_grid\"\"\"\n evaluate_candidates(ParameterGrid(self.param_grid))\n \n def fit(self, X, y=None, *, groups=None, **fit_params):\n self.initialize_fitting(X, y)\n\n estimator = self.estimator\n cv = check_cv(self.cv, y, classifier=is_classifier(estimator))\n\n scorers, self.multimetric_ = _check_multimetric_scoring(\n self.estimator, scoring=self.scoring)\n\n if self.multimetric_:\n if self.refit is not False and (\n not isinstance(self.refit, str) or\n # This will work for both dict / list (tuple)\n self.refit not in scorers) and not callable(self.refit):\n raise ValueError(\"For multi-metric scoring, the parameter \"\n \"refit must be set to a scorer key or a \"\n \"callable to refit an estimator with the \"\n \"best parameter setting on the whole \"\n \"data and make the best_* attributes \"\n \"available for that metric. If this is \"\n \"not needed, refit should be set to \"\n \"False explicitly. %r was passed.\"\n % self.refit)\n else:\n refit_metric = self.refit\n else:\n refit_metric = 'score'\n\n X, y, groups = indexable(X, y, groups)\n fit_params = _check_fit_params(X, fit_params)\n\n n_splits = cv.get_n_splits(X, y, groups)\n\n base_estimator = clone(self.estimator)\n\n parallel = Parallel(n_jobs=self.n_jobs, verbose=self.verbose,\n pre_dispatch=self.pre_dispatch)\n\n fit_and_score_kwargs = dict(scorer=scorers,\n fit_params=fit_params,\n return_train_score=self.return_train_score,\n return_n_test_samples=True,\n return_times=True,\n return_parameters=False,\n error_score=self.error_score,\n verbose=self.verbose)\n results = {}\n with parallel:\n all_candidate_params = []\n all_out = []\n\n def evaluate_candidates(candidate_params):\n candidate_params = list(candidate_params)\n n_candidates = len(candidate_params)\n\n if self.verbose > 0:\n print(\"Fitting {0} folds for each of {1} candidates,\"\n \" totalling {2} fits\".format(\n n_splits, n_candidates, n_candidates * n_splits))\n\n out = parallel(delayed(self._fit_score_and_log)(clone(base_estimator),\n X, y,\n train=train, test=test,\n parameters=parameters,\n **fit_and_score_kwargs)\n for parameters, (train, test)\n in product(candidate_params,\n cv.split(X, y, groups)))\n\n if len(out) < 1:\n raise ValueError('No fits were performed. '\n 'Was the CV iterator empty? '\n 'Were there no candidates?')\n elif len(out) != n_candidates * n_splits:\n raise ValueError('cv.split and cv.get_n_splits returned '\n 'inconsistent results. Expected {} '\n 'splits, got {}'\n .format(n_splits,\n len(out) // n_candidates))\n\n all_candidate_params.extend(candidate_params)\n all_out.extend(out)\n\n nonlocal results\n results = self._format_results(\n all_candidate_params, scorers, n_splits, all_out)\n return results\n\n self._run_search(evaluate_candidates)\n\n # For multi-metric evaluation, store the best_index_, best_params_ and\n # best_score_ iff refit is one of the scorer names\n # In single metric evaluation, refit_metric is \"score\"\n if self.refit or not self.multimetric_:\n # If callable, refit is expected to return the index of the best\n # parameter set.\n if callable(self.refit):\n self.best_index_ = self.refit(results)\n if not isinstance(self.best_index_, numbers.Integral):\n raise TypeError('best_index_ returned is not an integer')\n if (self.best_index_ < 0 or\n self.best_index_ >= len(results[\"params\"])):\n raise IndexError('best_index_ index out of range')\n else:\n self.best_index_ = results[\"rank_test_%s\"\n % refit_metric].argmin()\n self.best_score_ = results[\"mean_test_%s\" % refit_metric][\n self.best_index_]\n self.best_params_ = results[\"params\"][self.best_index_]\n\n if self.refit:\n # we clone again after setting params in case some\n # of the params are estimators as well.\n self.best_estimator_ = clone(clone(base_estimator).set_params(\n **self.best_params_))\n refit_start_time = time.time()\n if y is not None:\n self.best_estimator_.fit(X, y, **fit_params)\n else:\n self.best_estimator_.fit(X, **fit_params)\n refit_end_time = time.time()\n self.refit_time_ = refit_end_time - refit_start_time\n\n # Store the only scorer not as a dict for single metric evaluation\n self.scorer_ = scorers if self.multimetric_ else scorers['score']\n\n self.cv_results_ = results\n self.n_splits_ = n_splits\n\n return self\n\n @abstractmethod\n def log_results(self, train_score: float, test_score: float, sample_count: int, durations:np.array, parameters: dict, estimator):\n raise NotImplementedError\n\n @abstractmethod\n def initialize_fitting(self, X, y=None):\n raise NotImplementedError\n\n def _fit_score_and_log(self, estimator, X, y, scorer, train, test, verbose,\n parameters, fit_params, return_train_score=False,\n return_parameters=False, return_n_test_samples=False,\n return_times=False, return_estimator=False,\n error_score=np.nan):\n fit_result = _fit_and_score(estimator, X, y, scorer, train, test, verbose,\n parameters, fit_params, True,\n True, True,\n True, True,\n error_score)\n \n test_score = fit_result[0]['score']\n train_score = fit_result[1]['score']\n sample_count = fit_result[2]\n durations = [fit_result[3],fit_result[4]]\n parameters = fit_result[5]\n estimator = fit_result[6]\n\n self.log_results(train_score, test_score, sample_count, durations, parameters, estimator)\n\n if return_train_score:\n ret = [fit_result[0], fit_result[1]]\n else:\n ret = [fit_result[0]]\n if return_n_test_samples:\n ret.append(sample_count)\n if return_times:\n ret.extend(durations)\n if return_parameters:\n ret.append(parameters)\n if return_estimator:\n ret.append(estimator)\n \n return ret\n\n\nclass LocalArcusGridSearchCV(ArcusBaseSearchCV):\n __active_trainer: trainer.Trainer = None\n __current_idx: int = 0\n #TODO : Subclass the sklearn.model_selection._search.BaseSearchCV class. Override the fit(self, X, y=None, groups=None, **fit_params) method, and modify its internal evaluate_candidates(candidate_params) function. Instead of immediately returning the results dictionary from evaluate_candidates(candidate_params), perform your serialization here (or in the _run_search method depending on your use case). With some additional modifications, this approach has the added benefit of allowing you to execute the grid search sequentially (see the comment in the source code here: _search.py). Note that the results dictionary returned by evaluate_candidates(candidate_params) is the same as the cv_results dictionary. This approach worked for me, but I was also attempting to add save-and-restore functionality for interrupted grid search executions.\n def __init__(self, estimator, param_grid, *, scoring=None,\n n_jobs=None, iid='deprecated', refit=True, cv=None,\n verbose=0, pre_dispatch='2*n_jobs',\n error_score=np.nan, return_train_score=False, active_trainer: trainer.Trainer = None):\n super().__init__(\n estimator=estimator, param_grid = param_grid, scoring=scoring,\n n_jobs=n_jobs, iid=iid, refit=refit, cv=cv, verbose=verbose,\n pre_dispatch=pre_dispatch, error_score=error_score,\n return_train_score=return_train_score)\n \n self.param_grid = param_grid\n self.__active_trainer = active_trainer\n _check_param_grid(param_grid)\n\n def initialize_fitting(self, X, y=None):\n print('Start fitting')\n self.__current_idx = 0\n\n def log_results(self, train_score: float, test_score: float, sample_count: int, durations:np.array, parameters: dict, estimator):\n self.__current_idx+=1\n if(self.__active_trainer is not None):\n self.__active_trainer.add_tuning_result(self.__current_idx, train_score, test_score, sample_count, durations, parameters, estimator)","sub_path":"arcus/azureml/experimenting/tuning.py","file_name":"tuning.py","file_ext":"py","file_size_in_byte":11414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"533664096","text":"# pylint: disable=missing-docstring\nfrom openshift_checks import OpenShiftCheck, OpenShiftCheckException, get_var\nfrom openshift_checks.mixins import NotContainerizedMixin\n\n\nclass DiskAvailability(NotContainerizedMixin, OpenShiftCheck):\n \"\"\"Check that recommended disk space is available before a first-time install.\"\"\"\n\n name = \"disk_availability\"\n tags = [\"preflight\"]\n\n # Values taken from the official installation documentation:\n # https://docs.openshift.org/latest/install_config/install/prerequisites.html#system-requirements\n recommended_disk_space_bytes = {\n \"masters\": 40 * 10**9,\n \"nodes\": 15 * 10**9,\n \"etcd\": 20 * 10**9,\n }\n\n @classmethod\n def is_active(cls, task_vars):\n \"\"\"Skip hosts that do not have recommended disk space requirements.\"\"\"\n group_names = get_var(task_vars, \"group_names\", default=[])\n has_disk_space_recommendation = bool(set(group_names).intersection(cls.recommended_disk_space_bytes))\n return super(DiskAvailability, cls).is_active(task_vars) and has_disk_space_recommendation\n\n def run(self, tmp, task_vars):\n group_names = get_var(task_vars, \"group_names\")\n ansible_mounts = get_var(task_vars, \"ansible_mounts\")\n free_bytes = self.openshift_available_disk(ansible_mounts)\n\n recommended_min = max(self.recommended_disk_space_bytes.get(name, 0) for name in group_names)\n configured_min = int(get_var(task_vars, \"openshift_check_min_host_disk_gb\", default=0)) * 10**9\n min_free_bytes = configured_min or recommended_min\n\n if free_bytes < min_free_bytes:\n return {\n 'failed': True,\n 'msg': (\n 'Available disk space ({:.1f} GB) for the volume containing '\n '\"/var\" is below minimum recommended space ({:.1f} GB)'\n ).format(float(free_bytes) / 10**9, float(min_free_bytes) / 10**9)\n }\n\n return {}\n\n @staticmethod\n def openshift_available_disk(ansible_mounts):\n \"\"\"Determine the available disk space for an OpenShift installation.\n\n ansible_mounts should be a list of dicts like the 'setup' Ansible module\n returns.\n \"\"\"\n # priority list in descending order\n supported_mnt_paths = [\"/var\", \"/\"]\n available_mnts = {mnt.get(\"mount\"): mnt for mnt in ansible_mounts}\n\n try:\n for path in supported_mnt_paths:\n if path in available_mnts:\n return available_mnts[path][\"size_available\"]\n except KeyError:\n pass\n\n paths = ''.join(sorted(available_mnts)) or 'none'\n msg = \"Unable to determine available disk space. Paths mounted: {}.\".format(paths)\n raise OpenShiftCheckException(msg)\n","sub_path":"roles/openshift_health_checker/openshift_checks/disk_availability.py","file_name":"disk_availability.py","file_ext":"py","file_size_in_byte":2791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"275053893","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport cv2\nimport os\nimport random\nfrom math import ceil\nfrom skimage import transform\nimport mxnet as mx\nfrom mxnet.gluon import data as gdata\nfrom PIL import Image\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score\nfrom sklearn.metrics import classification_report\nimport os\nimport time\n\n\ndef read_train(rootpath):\n '''Reads traffic sign data for German Traffic Sign Recognition Benchmark.\n\n Arguments: path to the traffic sign data, for example './GTSRB/Training'\n Returns: list of images, list of corresponding labels'''\n images = [] # images\n labels = [] # corresponding labels\n # loop over all 42 classes\n for c in range(0,43):\n prefix = rootpath + '/' + format(c, '05d') + '/' # subdirectory for class\n gt_file = prefix + 'GT-'+ format(c, '05d') + '.csv' # annotations file\n gt_df = pd.read_csv(gt_file, delimiter=\";\")\n filename = gt_df[\"Filename\"].apply(lambda x: prefix + x).tolist()\n class_id = gt_df[\"ClassId\"].tolist()\n # loop over all files\n for i in range(len(filename)):\n images.append(plt.imread(filename[i]))\n labels.append(class_id[i])\n \n assert(len(images) == len(labels))\n \n return images, labels\n\n\ndef read_test(rootpath):\n \"\"\"\n Function for reading test data, folder with test data must contain GT-final_test.csv file\n \n :param rootpath: path to folder with images\n \"\"\"\n images = [] # images\n labels = [] # corresponding labels\n gt_file = os.path.join(rootpath, \"GT-final_test.csv\")\n try:\n gt_df = pd.read_csv(gt_file, delimiter=\";\")\n filename = gt_df[\"Filename\"].apply(lambda x: os.path.join(rootpath, x)).tolist()\n class_id = gt_df[\"ClassId\"].tolist()\n # loop over all files\n for i in range(len(filename)):\n images.append(plt.imread(filename[i]))\n labels.append(class_id[i])\n \n assert(len(images) == len(labels))\n except FileNotFoundError:\n print(\"Put 'GT-final_test.csv' in the same folder with test images\")\n \n return images, labels\n\n\ndef read_data(startpoint, train_folder, test_folder):\n \"\"\"\n Reads train and test data\n \n :param startpoint: path to folder with dataset\n :param train_folder: name of folder inside folder with dataset with train data\n :param test_folder: name of folder inside folder with dataset with test data\n \"\"\"\n train_path = os.path.join(startpoint, train_folder)\n test_path = os.path.join(startpoint, test_folder)\n \n images_train, labels_train = read_train(train_path)\n images_test, labels_test = read_test(test_path)\n \n return images_train, labels_train, images_test, labels_test\n\n\ndef resize_images(images, size=(30, 30)):\n \"\"\"\n Padd and resize images\n \n :param images: list of images\n \"\"\"\n resized_images = []\n for image in images:\n n = np.max(image.shape[:-1])\n padded_img = np.zeros((n, n, 3))\n padded_img[:image.shape[0], :image.shape[1]] = image\n resized_img = cv2.resize(padded_img, (size[0], size[1])).astype(int)\n resized_images.append(resized_img)\n \n return resized_images\n\n\ndef extract_tracks(y, track_size=30):\n \"\"\"\n Extra function for extracting tracks from array of sign labels\n \n :param y: array with labels\n :param track_size: size of one track\n \"\"\"\n tracks = []\n step = track_size\n i = 0\n while i < y.shape[0]:\n label = y[i]\n if i + track_size <= y.shape[0] and y[i + track_size - 1] != y[i]:\n step = track_size - 1\n else:\n step = track_size\n tracks.append((i, i + step, label))\n i += step\n return tracks\n\n\ndef split(X, y, prop=0.8):\n \"\"\"\n Splitting data to train and validation datasets\n \n :param X: list/array of images\n :param y: labels of images\n \"\"\"\n X_train, y_train = [], []\n X_val, y_val = [], []\n \n if type(y) == list:\n y = np.array(y)\n if type(X) == list:\n X = np.array(X)\n \n tracks = extract_tracks(y)\n random.shuffle(tracks)\n \n train_end = ceil(prop * len(tracks))\n for i in range(train_end):\n track = tracks[i]\n start = track[0]\n end = track[1]\n for j in range(start, end):\n X_train.append(X[j])\n y_train.append(y[j])\n \n for i in range(train_end, len(tracks)):\n track = tracks[i]\n start = track[0]\n end = track[1]\n for j in range(start, end):\n X_val.append(X[j])\n y_val.append(y[j])\n \n X_train = np.array(X_train)\n y_train = np.array(y_train)\n X_val = np.array(X_val)\n y_val = np.array(y_val)\n \n ind_train = [i for i in range(X_train.shape[0])]\n ind_val = [i for i in range(X_val.shape[0])]\n random.shuffle(ind_train)\n random.shuffle(ind_val)\n \n return X_train[ind_train], y_train[ind_train], X_val[ind_val], y_val[ind_val]\n\n\ndef countplot(data, xlab, ylab, title):\n \"\"\"\n Showing countplot for data\n \n :param data: list/array with values\n :param xlab: label of x axis\n :param ylab: label of y axis\n :param title: title of countplot\n \"\"\"\n try:\n if len(data.shape) > 1:\n print(\"Too many dimensions!\")\n else:\n df = pd.DataFrame(data={\"col\": pd.Series(data)})\n plt.figure(figsize=(12, 4))\n plot = sns.countplot(x=\"col\", data=df)\n plot.set(xlabel=xlab, ylabel=ylab, title=title)\n plt.show()\n except AttributeError:\n print(\"data must be numpy array\")\n\n\ndef valid_methods(methods):\n valid = [\"rotation\", \"brightness\", \"flip_horiz\", \"flip_vert\"]\n for method in methods:\n if method not in valid:\n return False\n return True\n\n\ndef augment_dataset(X, y, augmentations={\"rotation\":True, \"brightness\":True, \"flip_horiz\": True, \"flip_vert\": False}):\n \"\"\"\n Augment dataset with chosen methods\n \n :param X: array of images\n :param y: labels of images\n :param augmentations: chosen methods for augmentation\n \"\"\"\n if sum(augmentations.values()) == 0:\n print(\"At least one method of augmentation must be choosen\")\n elif not valid_methods(list(augmentations.keys())):\n print(\"Invalid augmentation method among given\")\n else:\n methods = []\n for key, val in augmentations.items():\n if val:\n methods.append(key)\n unique, counts = np.unique(y, return_counts=True)\n label_counts = dict(zip(unique, counts))\n maxim = np.max(counts)\n length = X.shape[0]\n \n augmented_imgs = []\n augmented_labels = []\n for i in range(length):\n label = y[i]\n horiz_vert_flips = (False, False)\n add_count = (maxim - label_counts[label]) // label_counts[label]\n for j in range(add_count):\n img = None\n method = random.choice(methods)\n if method == \"rotation\":\n img = transform.rotate(X[0], random.uniform(-20, 20), preserve_range=True).astype(int)\n elif method == \"flip_horiz\" and not horiz_vert_flips[0]:\n img = np.fliplr(X[i])\n horiz_vert_flips[0] = True\n elif method == \"flip_vert\" and not horiz_vert_flips[1]:\n img = np.flipud(X[i])\n horiz_vert_flips[1] = True\n else:\n color_aug = gdata.vision.transforms.RandomBrightness(brightness=0.5)\n img = color_aug(mx.nd.array(X[0]).astype(int)).asnumpy()\n augmented_imgs.append(img)\n augmented_labels.append(label)\n \n residuals = [0 for i in range(np.max(unique) + 1)]\n for label in label_counts:\n residuals[label] = (maxim - label_counts[label]) % label_counts[label]\n \n for i in range(length):\n label = y[i]\n if residuals[label] > 0:\n img = None\n method = random.choice(methods)\n if method == \"rotation\":\n img = transform.rotate(X[0], random.uniform(-20, 20), preserve_range=True).astype(int)\n elif method == \"flip_horiz\":\n img = np.fliplr(X[i])\n elif method == \"flip_vert\":\n img = np.flipud(X[i])\n else:\n color_aug = gdata.vision.transforms.RandomBrightness(brightness=0.5)\n img = color_aug(mx.nd.array(X[0]).astype(int)).asnumpy()\n augmented_imgs.append(img)\n augmented_labels.append(label)\n residuals[label] -= 1\n \n augmented_imgs = np.array(augmented_imgs)\n augmented_labels = np.array(augmented_labels)\n \n return np.vstack((X, augmented_imgs)).astype(int), np.hstack((y, augmented_labels)).astype(int)\n\n\ndef resize(array, save_to_disk=True, filenames=[\"train\", \"test\"]):\n assert(not save_to_disk or len(array) == len(filenames))\n \n res = []\n for i in range(len(array)):\n dataset = array[i]\n resized = resize_images(dataset, IMG_SIZE)\n res.append(resized)\n save_numpy_arrays(res, filenames)\n return res\n\n\ndef save_numpy_arrays(array, filenames):\n assert(len(array) == len(filenames))\n \n for i in range(len(array)):\n dataset = array[i]\n np.save(filenames[i], np.array(dataset))\n \n \ndef read_arrays(filenames):\n res = []\n for file in filenames:\n res.append(np.load(file))\n assert(len(res) == len(filenames))\n return res\n\n\ndef normalize_data(X):\n if type(X) == list:\n X = np.array(X)\n return X / 255\n\n\ndef prepare_features(X):\n \"\"\"\n Normalize and flattening data\n :param X: array of images\n \"\"\"\n X = normalize_data(X)\n return X.reshape((X.shape[0], -1))\n\n\ndef run_learner(X, y, n_estimators=100, use_validation=False, X_val=None, y_val=None, params=[i for i in range(150, 350, 50)]):\n print(\"Preparation of features: normalization and flattening ...\")\n X = prepare_features(X)\n print(\"Done!\\n\")\n \n model = None\n best_score = 0\n\n if use_validation:\n print(\"Trying different amount of trees ... \")\n for param in params:\n clf = RandomForestClassifier(n_estimators=param, criterion=\"entropy\", n_jobs=-1)\n clf.fit(X, y)\n y_pred = clf.predict(X_val)\n score = accuracy_score(y_val, y_pred)\n if score > best_score:\n best_score = score\n model = clf\n else:\n print(\"Training a model: number of trees =\", n_estimators, \" ... \")\n model = RandomForestClassifier(n_estimators=n_estimators, criterion=\"entropy\", n_jobs=-1)\n model.fit(X, y)\n print(\"Model has trained!\\n\")\n \n return model\n\n\ndef evaluate_model(model, X, y):\n X = prepare_features(X)\n y_pred = model.predict(X)\n report = classification_report(y, y_pred)\n\n print(\"Examples of misclassified images\")\n\n mask = y_pred != y\n plt.imshow(X[mask][0].reshape(30, 30, 3))\n plt.show()\n print(\"True label:\", y[mask][0], \"Predicted label:\", y_pred[mask][0])\n\n plt.imshow(X[mask][1].reshape(30, 30, 3))\n plt.show()\n print(\"True label:\", y[mask][1], \"Predicted label:\", y_pred[mask][1])\n\n print(\"\\nClassification report:\")\n print(report)\n print(\"\\n\")\n\n\ndef try_different_image_sizes(sizes):\n print(\"Trying different image sizes ... \")\n images_train, labels_train, images_test, labels_test = read_data(STARTDIR, TRAIN_FOLDER, TEST_FOLDER)\n scores = []\n times = []\n for size in sizes:\n print(\"Size:\", size)\n resized_train = resize_images(images_train, size)\n resized_test = resize_images(images_test, size)\n start = time.time()\n clf = run_learner(resized_train, labels_train)\n end = time.time()\n times.append(end - start)\n y_pred = clf.predict(prepare_features(resized_test))\n scores.append(accuracy_score(labels_test, y_pred))\n\n print(\"Scores plot\")\n plt.plot([i[0] for i in sizes], scores)\n plt.xlabel(\"Size\")\n plt.ylabel(\"Accuracy score\")\n plt.show()\n\n print(\"Time plot\\n\")\n plt.plot([i[0] for i in sizes], times)\n plt.xlabel(\"Size\")\n plt.ylabel(\"Time(s)\")\n plt.show()\n\n\nSTARTDIR = \"dataset\"\nTRAIN_FOLDER = \"Training\"\nTEST_FOLDER = \"Test\"\nIMG_SIZE = (30, 30)\n\nif os.path.exists(\"train.npy\"):\n print(\"Found saved dataset with resized images\")\n print(\"WARNING! If you are going to experiment with images size delete *.npy files and rerun script\")\n print(\"Reading resized images ...\")\n resized_train, resized_test, labels_train, labels_test = read_arrays([\"train.npy\", \"test.npy\", \"labels_train.npy\", \"labels_test.npy\"])\n print(\"Reading completed\\n\")\nelse:\n print(\"Reading data ...\")\n images_train, labels_train, images_test, labels_test = read_data(STARTDIR, TRAIN_FOLDER, TEST_FOLDER)\n print(\"Reading completed\\n\")\n \n print(\"Resizing images ...\")\n resized_train, resized_test = resize([images_train, images_test], save_to_disk=True)\n save_numpy_arrays([labels_train, labels_test], [\"labels_train\", \"labels_test\"])\n print(\"Resizing completed\")\n print(\"Resized images and labels are saved to disk\\n\")\n\n resized_train = np.array(resized_train)\n resized_test = np.array(resized_test)\n labels_train = np.array(labels_train)\n labels_test = np.array(labels_test)\n\nprint(\"Current images size for feeding to the algorithm:\", resized_train[0].shape[0], resized_train[0].shape[1], \"\\n\")\n \nprint(\"Splitting data to train and validation ...\")\nX_train, y_train, X_val, y_val = split(resized_train, labels_train)\nprint(\"Done!\")\nprint(\"Train size:\", X_train.shape[0], \"Val size:\", X_val.shape[0])\nprint(\"--- Proportion of train:\", X_train.shape[0] / resized_train.shape[0], \" ---\\n\")\n\nmethods = {\"rotation\":True, \"brightness\": True, \"flip_horiz\": False, \"flip_vert\": False}\nprint(\"For augmentation there are used:\", end=\" \")\nfor method in methods:\n if methods[method]:\n print(method, end=\" \")\nprint(\"\\nAugmentation of data ...\")\nX_augm, y_augm = augment_dataset(X_train, y_train, methods)\nprint(\"Done!\\n\")\n\nprint(\"Trying on augmented dataset ...\")\nclf = run_learner(X_augm, y_augm)\nprint(\"Evaluation on test set\")\nevaluate_model(clf, resized_test, labels_test)\n\nprint(\"Trying on non-augmented dataset ...\")\nclf = run_learner(X_train, y_train)\nprint(\"Evaluation on test set\")\nevaluate_model(clf, resized_test, labels_test)\n\nsizes = [(10, 10), (30, 30), (40, 40), (50, 50), (60, 60)]\ntry_different_image_sizes(sizes)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"248631035","text":"# =============================================================================\n# Get the ToA data from the .csv file and plot it\n# =============================================================================\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport csv\nimport time\nfrom path_to_shot import *\nstart_time = time.time() # Execution time\n# Plot figures in external window:\nfrom IPython import get_ipython\nget_ipython().run_line_magic('matplotlib', 'qt')\n\nshot = int(input(\"Shot number:\"))\n\n# Go to the @shot folder\ntry:\n path = path_to_shot(shot)\nexcept:\n raise SystemExit\n\n# Get the data\nData_tpx3_cent = np.genfromtxt('%s.csv' % shot, delimiter=',')\n# Read the first row in the .csv file and get index of the required signal\nwith open('%s.csv' % shot, newline='') as f:\n reader = csv.reader(f)\n row1 = next(reader) \n\ntry:\n index = row1.index('#ToTtotal[arb]')\n tot_total = np.array([row[index] for row in Data_tpx3_cent])\nexcept:\n print(\"No 'ToT' in the list\")\n raise SystemExit\n\n\n# =============================================================================\n# Plot\n# =============================================================================\n\n# Prepare figure and compute the histogram\nfig = plt.figure()\nplt.rcParams.update({'font.size': 22})\nplt.title(\"Shot %s: ToT\" % shot)\nplt.xlabel(\"ToT [a.u.]\")\nplt.ylabel(\"Hits [-]\")\na = plt.hist(tot_total, 1000, (0, 25000), histtype='step', fill=False)\n# Get rid off the noisy \"ones\" for an appropriate plot\ndata = a[0]\ntimee = a[1]\n\nones = np.where(data < 10)[0]\n\nfor i in range (0, len(ones)):\n data[ones[i]] = 0\n\n# Define limits of x axis for an appropriate plot\ntry:\n left, right = int(timee[np.nonzero(data)[0][0]]-10), int(timee[np.nonzero(data)[0][-1]]+10)\n plt.xlim(left, right)\nexcept:\n print(\"Probably no data at all or just a weak signal\")\n pass\n\n# Show the result within the limits\n\nplt.show()\n\n# Go to the Figures folder\ntry:\n os.chdir(\"%s/Figures\" % path)\nexcept:\n print(\"No folder, creating one\")\n os.mkdir(\"%s/Figures\" % path)\n os.chdir(\"%s/Figures\" % path)\n\nprint(\"Time of execution: %s seconds\" % (time.time() - start_time))\nfig.set_size_inches(20., 12., forward=True)\nplt.savefig('%s:ToT_plt.pdf' % shot)","sub_path":"wtf/single/ToT_plt.py","file_name":"ToT_plt.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"618420980","text":"##\n## Imprima una tabla en formato CSV que contenga por cada clave \n## de la columna 5, la correspondiente cantidad de registros \n## asociados (filas en el archivo)\n##\n## aaa,13\n## bbb,16\n## ccc,23\n## ddd,23\n## eee,15\n## fff,20\n## ggg,13\n## hhh,16\n## iii,18\n## jjj,18\n##\n##\ndata = open('data.csv','r').readlines()\ndata = [row.split('\\t') for row in data]\ndata = [row[4][:-1] for row in data]\ndata = [row.split(',') for row in data]\nlista = [i[:-2] for key in data for i in key ]\n\ncount={}\nfor i in lista:\n if(count.get(i) != None):\n count[i] = count[i] + 1\n else:\n count[i] = 1\n\nfor i in sorted(count.keys()):\n print(f'{i},{count[i]}')","sub_path":"q10.py","file_name":"q10.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"422323208","text":"\r\nimport pandas as pd\r\nimport numpy as np\r\nimport datetime as dt\r\n\r\ndef getDailyPay(filename):\r\n xl = pd.ExcelFile(filename)\r\n\r\n # Read Timesheet Entries\r\n t = xl.parse('Time')\r\n t['Date'].fillna(pd.to_datetime('1/1/1960'), inplace=True)\r\n t['Hours'].fillna(0, inplace=True)\r\n t['Reason'].fillna('', inplace=True)\r\n t['Name'].fillna('', inplace=True)\r\n t['WorkedDay'] = np.where(t['Hours']>0, 1, 0) \r\n t.sort_values(by=['Date'], inplace=True)\r\n\r\n # Read Holiday Data\r\n h = xl.parse('Holidays')\r\n h.sort_values(by=['Date'], inplace=True)\r\n\r\n # Get Begin and End date based on Time Entries\r\n today = dt.datetime.now().date()\r\n startdt = t['Date'].min().date()\r\n\r\n # Prepare Dataframe with Begin and End Date\r\n diff = today - startdt\r\n dtlist = pd.date_range(startdt, periods=diff.days-today.weekday())\r\n dtfrm = pd.DataFrame(columns=['Date'], data=dtlist)\r\n dtfrm['WeekDay'] = dtfrm['Date'].dt.weekday\r\n dtfrm['key'] = 1\r\n\r\n # Merge all Days with holiday data\r\n dth = dtfrm.merge(h, how='left', on='Date')\r\n dth['Holiday'].fillna('', inplace=True)\r\n\r\n # get working days, ignoring weekends and holidays\r\n dth['WorkingDay'] = np.where((dth['WeekDay']>4) | (dth['Holiday'] != ''), 0, 1)\r\n\r\n # Get Rate Data\r\n r = xl.parse('Client')\r\n r=r[r['Type']=='Employer']\r\n r.rename(columns={'BeginDate': 'EmpRteBeginDate', 'EndDate': 'EmpRteEndDate'}, inplace=True)\r\n r['key'] = 1\r\n\r\n # Merge Timesheet entries with Holiday Data\r\n dtho = dth.merge(t, how='left', on='Date')\r\n\r\n # Merge Timesheet data with Rate Data\r\n dthm = r.merge(dtho, how='left', on='key')\r\n dthm = dthm[(dthm.EmpRteBeginDate <= dthm.Date) & (dthm.EmpRteEndDate >= dthm.Date)]\r\n dthm['DailyPay'] = dthm['Hours'] * dthm['Rate']\r\n dthm['ExpPay'] = dthm['WorkingDay'] * 8 * dthm['Rate']\r\n dthm['PayDiff'] = dthm['DailyPay'] - dthm['ExpPay']\r\n return dthm\r\n\r\ndef readPayData(filename):\r\n xl = pd.ExcelFile(filename)\r\n p = xl.parse('Paycheck')\r\n return p\r\n\r\nif __name__ == \"__main__\":\r\n dailypay = getDailyPay('JobStuff.xlsx')\r\n dailypay.to_csv('jobdata.csv')\r\n \r\n \r\n\r\n\r\n","sub_path":"jobstuff.py","file_name":"jobstuff.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"87198889","text":"def shell_sort(a):\n h = int(input('Enter increment odd value: '))\n while h >= 1:\n for i in range(h, len(a)):\n temp = a[i]\n j = i - h\n while j >= 0 and a[j] > temp:\n a[j+h] = a[j]\n j = j-h\n a[j+h] = temp\n h = h-2\n","sub_path":"Practice Ds - Prev/shell_sort.py","file_name":"shell_sort.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"112716474","text":"import TeamInfo\nimport json\n\n#Object for information pertaining to a live game\nclass GameInfo:\n\tdef __init__(self):\n\t\tself.leagueName = \"\"\n\t\tself.tournamentUrl = \"\"\n\t\tself.numSpectators = 0\n\t\tself.towerState = -1\n\t\tself.gameStarted = False\n\t\tself.lobbyId = -1\n\n\t\tself.radiantPlayers = list()\n\t\tself.direPlayers = list()\n\t\tself.unassignedPlayers = list()\n\t\tself.broadcastPlayers = list()\n\n\t\tself.direTeamInfo = TeamInfo\n\t\tself.radiantTeamInfo = TeamInfo\n\n\tdef to_JSON(self):\n\t\treturn json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4)","sub_path":"python/classes/GameInfo.py","file_name":"GameInfo.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"164413253","text":"#!/usr/bin/env python\n# pylint:disable=R0201,C0111\n\n\"\"\"Integration tests for file IO.\"\"\"\n\nimport logging\n\nimport pytest\n\nfrom . import refresh_file_modification_times\nfrom .samples import * # pylint: disable=W0401,W0614\n\n\nclass TestInit:\n\n \"\"\"Integration tests for initializing mapped classes.\"\"\"\n\n def test_fetch_from_existing(self, tmpdir):\n \"\"\"Verify attributes are updated from an existing file.\"\"\"\n tmpdir.chdir()\n sample = SampleStandardDecorated('sample')\n sample2 = SampleStandardDecorated('sample')\n assert sample2.yorm_mapper.path == sample.yorm_mapper.path\n\n refresh_file_modification_times()\n\n logging.info(\"changing values in object 1...\")\n sample.object = {'key2': 'value'}\n sample.array = [0, 1, 2]\n sample.string = \"Hello, world!\"\n sample.number_int = 42\n sample.number_real = 4.2\n sample.true = True\n sample.false = False\n\n logging.info(\"reading changed values in object 2...\")\n assert 'value' == sample2.object.get('key2')\n assert [0, 1, 2] == sample2.array\n assert \"Hello, world!\" == sample2.string\n assert 42 == sample2.number_int\n assert 4.2 == sample2.number_real\n assert True is sample2.true\n assert False is sample2.false\n\n\nclass TestDelete:\n\n \"\"\"Integration tests for deleting files.\"\"\"\n\n def test_read(self, tmpdir):\n \"\"\"Verify a deleted file cannot be read from.\"\"\"\n tmpdir.chdir()\n sample = SampleStandardDecorated('sample')\n sample.yorm_mapper.delete()\n\n with pytest.raises(FileNotFoundError):\n print(sample.string)\n\n with pytest.raises(FileNotFoundError):\n sample.string = \"def456\"\n\n def test_write(self, tmpdir):\n \"\"\"Verify a deleted file cannot be written to.\"\"\"\n tmpdir.chdir()\n sample = SampleStandardDecorated('sample')\n sample.yorm_mapper.delete()\n\n with pytest.raises(FileNotFoundError):\n sample.string = \"def456\"\n\n def test_multiple(self, tmpdir):\n \"\"\"Verify a deleted file can be deleted again.\"\"\"\n tmpdir.chdir()\n sample = SampleStandardDecorated('sample')\n sample.yorm_mapper.delete()\n sample.yorm_mapper.delete()\n\n\nif __name__ == '__main__':\n pytest.main()\n","sub_path":"tests/test_all_files.py","file_name":"test_all_files.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"18040384","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 23 07:54:22 2019\n\n@author: cw8xk\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pyswmm import Simulation, Nodes, Links\nfrom rl.core import Env\nfrom gym import spaces\n\nswmm_inp = \"C:/Users/Ben Bowes/PycharmProjects/swmm_keras_rl/case3_mpc_r1.inp\"\n\n\nclass BasicEnv(Env):\n def __init__(self,depth=4.61):\n # initialize simulation\n self.sim = Simulation(swmm_inp) # read input file\n self.control_time_step = 900 # control time step in seconds\n self.sim.step_advance(self.control_time_step) # set control time step\n node_object = Nodes(self.sim) # init node object\n self.St1 = node_object[\"St1\"]\n self.St2 = node_object[\"St2\"]\n self.J1 = node_object[\"J1\"]\n self.depth = depth\n self.St1.full_depth = self.depth\n self.St2.full_depth = self.depth\n \n link_object = Links(self.sim) # init link object\n self.R1 = link_object[\"R1\"]\n self.R2 = link_object[\"R2\"]\n \n self.sim.start()\n if self.sim.current_time == self.sim.start_time:\n self.R1.target_setting = 0.5\n self.R2.target_setting = 0.5\n sim_len = self.sim.end_time - self.sim.start_time\n self.T = int(sim_len.total_seconds()/self.control_time_step)\n self.t = 1\n #print('T=', self.T) \n\n self.state = np.asarray([self.St1.depth, self.St2.depth, self.J1.depth,\n self.St1.flooding, self.St2.flooding, self.J1.flooding])\n \n self.action_space = spaces.Box(low=np.array([0,0]),high=np.array([1,1]), dtype=np.float32)\n self.observation_space = spaces.Box(low=0, high = 1000, shape=(len(self.state),),dtype=np.float32)\n \n def step(self,action):\n \n self.R1.target_setting = action[0]\n self.R2.target_setting = action[1]\n self.sim.__next__()\n \n self.state = np.asarray([self.St1.depth, self.St2.depth, self.J1.depth,\n self.St1.flooding, self.St2.flooding, self.J1.flooding])\n # reward = - (self.St1.flooding + self.St2.flooding + self.J1.flooding)\n \n if self.t < self.T-1:\n reward = 0\n done = False\n else:\n reward = - (self.St1.statistics['flooding_volume'] * 100 + self.St2.statistics['flooding_volume'] * 100 +\n self.J1.statistics['flooding_volume'] * 0.5)\n done = True\n # self.sim.close()\n \n self.t += 1\n \n info = {}\n \n return self.state, reward, done, info \n \n def reset(self):\n self.sim.close()\n self.sim = Simulation(swmm_inp)\n self.sim.step_advance(self.control_time_step) # set control time step\n node_object = Nodes(self.sim) # init node object\n self.St1 = node_object[\"St1\"]\n self.St2 = node_object[\"St2\"]\n self.J1 = node_object[\"J1\"]\n link_object = Links(self.sim) # init link object\n self.R1 = link_object[\"R1\"]\n self.R2 = link_object[\"R2\"]\n self.St1.full_depth = self.depth\n self.St2.full_depth = self.depth\n self.sim.start()\n self.t = 1\n if self.sim.current_time == self.sim.start_time:\n \n self.R1.target_setting = 0.5\n self.R2.target_setting = 0.5\n \n self.state = np.asarray([self.St1.depth, self.St2.depth, self.J1.depth,\n self.St1.flooding, self.St2.flooding, self.J1.flooding])\n return self.state\n \n def close(self):\n self.sim.report()\n self.sim.close()\n \nmodel0 = BasicEnv()\n#\nd = False\n#st1_depth = [model0.state[0]]\n#st2_depth = [model0.state[1]]\n#J3_depth = [model0.state[2]]\nwhile not d:\n action = [0,0]\n state, reward, d, _ = model0.step(action)\n# st1_depth.append(state[0])\n# st2_depth.append(state[1])\n# J3_depth.append(state[2])\n# #print(state[3:])\nmodel0.close()\n##plt.plot(st2_depth)\n#plt.plot(J3_depth)\n","sub_path":"Old_models/DDPG_sinle_inp/swmm_Model_end_rwd.py","file_name":"swmm_Model_end_rwd.py","file_ext":"py","file_size_in_byte":4049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"401008650","text":"from tkinter import *\nfrom tkinter import ttk\nimport tkinter.messagebox\nfrom PIL import ImageTk, Image\nfrom Queries import Queries\nimport os\nos.chdir(r\"E:\\Assignment\\Sem 2\\Algorithm\\Data Storage System\")\n\nclass NotesManager:\n def __init__(self, notes):\n self.con = Queries()\n self.note_id_val = StringVar()\n # Images\n self.add_image = ImageTk.PhotoImage(Image.open(\"Icons/Add.png\").resize((50, 50)))\n self.update_image = ImageTk.PhotoImage(Image.open(\"Icons/Update.png\").resize((50, 50)))\n self.delete_image = ImageTk.PhotoImage(Image.open(\"Icons/Delete.png\").resize((50, 50)))\n self.reset_image = ImageTk.PhotoImage(Image.open(\"Icons/Reset.png\").resize((50, 50)))\n # Frames\n self.frame1 = Frame(notes, relief=RIDGE, bd=8)\n self.frame1.place(x=10, y=10, width=1235, height=500)\n self.frame2 = Frame(self.frame1, relief=RIDGE, bd=5)\n self.frame2.place(x=0, y=0, width=200, height=485)\n # Label\n self.note_id_lbl = Label(self.frame1, text=\"Note ID:\", font=('verdana', 12))\n self.note_id_lbl.place(x=230, y=10)\n self.note_lbl = Label(self.frame1, text=\"Note:\", font=('verdana', 12))\n self.note_lbl.place(x=230, y=50)\n # Entry\n self.note_id_ent = Entry(self.frame1, font=('arial', 12), textvariable=self.note_id_val, state=\"readonly\")\n self.note_id_ent.place(x=320, y=12)\n self.note_ent = Text(self.frame1, width=100, height=20, font=('arial', 12))\n self.note_ent.place(x=300, y=55)\n # Buttons\n self.add_btn = Button(self.frame1, relief=FLAT, image=self.add_image, command=self.add_note)\n self.add_btn.place(x=550, y=420)\n self.update_btn = Button(self.frame1, relief=FLAT, image=self.update_image, command=self.update_note)\n self.update_btn.place(x=650, y=420)\n self.delete_btn = Button(self.frame1, relief=FLAT, image=self.delete_image, command=self.delete_note)\n self.delete_btn.place(x=750, y=420)\n self.reset_btn = Button(self.frame1, relief=FLAT, image=self.reset_image, command=self.reset_note)\n self.reset_btn.place(x=850, y=420)\n # TreeView\n self.scroll_y = Scrollbar(self.frame2, orient=VERTICAL)\n self.note_tbl = ttk.Treeview(self.frame2, columns=(\"note\"), xscrollcommand=self.scroll_y.set)\n self.scroll_y.pack(side=RIGHT, fill='y')\n self.scroll_y.config(command=self.note_tbl.yview, bg='#9BC01C')\n self.note_tbl.heading(\"note\", text=\"Note Number\")\n self.note_tbl['show'] = 'headings'\n self.note_tbl.column(\"note\")\n self.note_tbl.pack(fill=BOTH, expand='1')\n self.insert_note()\n#Methods\n def add_note(self):\n print(self.note_ent.get(\"1.0\",\"end\"))\n if self.note_ent.get(\"1.0\",\"end\")=='':\n tkinter.messagebox.showerror('Error','Dont leave the field empty.')\n else:\n self.con.add_note(self.note_ent.get(\"1.0\",\"end\"))\n self.insert_note()\n self.reset_note()\n\n def update_note(self):\n if self.note_ent.get(\"1.0\",\"end\")=='':\n tkinter.messagebox.showerror('Error','Dont leave the field empty.')\n else:\n self.con.update_note(self.note_ent.get(\"1.0\",\"end\"), self.note_id_ent.get())\n self.insert_note()\n self.reset_note()\n\n def delete_note(self):\n self.con.delete_note(self.note_id_ent.get())\n self.insert_note()\n self.reset_note()\n\n def reset_note(self):\n self.note_id_val.set('')\n self.note_ent.delete(\"1.0\",\"end\")\n\n def insert_note(self):\n data = self.con.fetch_note()\n self.note_tbl.delete(*self.note_tbl.get_children())\n for i in data:\n self.note_tbl.insert(\"\",\"end\", value=(i[0],i[1]))\n self.note_tbl.bind('',self.select_note)\n\n def select_note(self, event):\n self.row = self.note_tbl.item(self.note_tbl.selection(), \"values\")\n self.fill_note()\n\n def fill_note(self):\n self.reset_note()\n self.note_id_val.set(self.row[0])\n self.note_ent.insert(\"0.0\",self.row[1])","sub_path":"Notes.py","file_name":"Notes.py","file_ext":"py","file_size_in_byte":4117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"250908638","text":"import os\nimport pytest\nimport todo_app.app as app\nfrom dotenv import find_dotenv, load_dotenv\nimport json\nfrom todo_app.data.item import TrelloItem\nfrom unittest.mock import patch, Mock\n\n@pytest.fixture\ndef client():\n # Use our test integration config instead of the 'real' version \n file_path = find_dotenv('.env.test')\n load_dotenv(file_path, override=True)\n\n # Create the new app.\n test_app = app.create_app()\n\n # Use the app to create a test_client that can be used in our tests.\n with test_app.test_client() as client: \n yield client\n\n@patch('requests.request')\ndef test_index_page(mock_get_requests, client):\n# Replace call to requests.get(url) with our own function\n mock_get_requests.side_effect = mock_get_lists\n response = client.get('/')\n assert response.status_code == 200\n assert '12345' in response.data.decode()\n\ndef mock_get_lists(method,url, params):\n if url == f\"https://api.trello.com/1/lists/{os.getenv('TODOID')}/cards\":\n response = Mock()\n \n# sample_trello_lists_response should point to some test response data\n response.json.return_value = [{\n \"id\": \"12345\",\n \"name\": \"Test to do item\",\n \"dateLastActivity\": \"2021-02-21T19:30:30.101Z\"\n }]\n\n return response\n elif url == f\"https://api.trello.com/1/lists/{os.getenv('PENDINGID')}/cards\": \n response = Mock()\n \n# sample_trello_lists_response should point to some test response data\n response.json.return_value = [{\n \"id\": \"123456\",\n \"name\": \"Test doing item\",\n \"dateLastActivity\": \"2021-02-21T19:30:30.101Z\"\n }]\n\n return response\n elif url == f\"https://api.trello.com/1/lists/{os.getenv('DONEID')}/cards\": \n response = Mock()\n \n# sample_trello_lists_response should point to some test response data\n response.json.return_value = [{\n \"id\": \"1234567\",\n \"name\": \"Test done item\",\n \"dateLastActivity\": \"2021-02-21T19:30:30.101Z\"\n }]\n\n return response\n return None\n","sub_path":"tests/test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"464207854","text":"import pandas as pd\nimport os \nimport csv \n\n\n\ndef extract():\n params=['GLOBALEVENTID', 'SQLDATE', 'MonthYear', 'Year', 'FractionDate', \n 'Actor1Code', 'Actor1Name', 'Actor1CountryCode', \n 'Actor1KnownGroupCode', 'Actor1EthnicCode', 'Actor1Religion1Code', \n 'Actor1Religion2Code', 'Actor1Type1Code', 'Actor1Type2Code', \n 'Actor1Type3Code', 'Actor2Code', 'Actor2Name', 'Actor2CountryCode', \n 'Actor2KnownGroupCode', 'Actor2EthnicCode', 'Actor2Religion1Code', \n 'Actor2Religion2Code', 'Actor2Type1Code', 'Actor2Type2Code', \n 'Actor2Type3Code', 'IsRootEvent', 'EventCode', 'EventBaseCode', \n 'EventRootCode', 'QuadClass', 'GoldsteinScale', 'NumMentions', \n 'NumSources', 'NumArticles', 'AvgTone', 'Actor1Geo_Type', \n 'Actor1Geo_FullName', 'Actor1Geo_CountryCode', 'Actor1Geo_ADM1Code', \n 'Actor1Geo_Lat', 'Actor1Geo_Long', 'Actor1Geo_FeatureID', \n 'Actor2Geo_Type', 'Actor2Geo_FullName', 'Actor2Geo_CountryCode', \n 'Actor2Geo_ADM1Code', 'Actor2Geo_Lat', 'Actor2Geo_Long', \n 'Actor2Geo_FeatureID', 'ActionGeo_Type', 'ActionGeo_FullName', \n 'ActionGeo_CountryCode', 'ActionGeo_ADM1Code', 'ActionGeo_Lat', \n 'ActionGeo_Long', 'ActionGeo_FeatureID', 'DATEADDED', 'SOURCEURL'\n ]\n\n path = \"./its_raw\"\n\n for file in os.listdir(path):\n temp = pd.read_csv(\n path+'/'+file,\n index_col=False,\n names=params,\n low_memory=False\n )\n\n df = temp.filter(['EventCode', 'NumMentions', 'NumSources', 'NumArticles'])\n\n file_name = file[0:file.index('.')] + '_Mentions_Sources_Articles_by_EventCode.csv'\n\n df.to_csv(r'./from_john/'+file_name, index=False, header=True)\n\n print('output:' + file_name)\n print(df)\n\n\n\nextract()","sub_path":"mentions_sources_articles_by_code.py","file_name":"mentions_sources_articles_by_code.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"301871335","text":"from unittest import TestCase\n\nimport constants\nimport torch\nfrom util.s3util import S3Util\nfrom nnet.snapshot import Snapshot\n\n\nclass TestSnapshot(TestCase):\n def test_put(self):\n try:\n s3_util = S3Util(constants.default_s3_bucket_name, 'temp/models/test1', False)\n snapshot = Snapshot(s3_util)\n linear = torch.nn.Linear(20, 10)\n optimizer = torch.optim.Adam(linear.parameters(), 0.001)\n snapshot.put(linear, optimizer, 11)\n print('test_put completed')\n except Exception as e:\n print(str(e))\n self.fail()\n\n def test_get(self):\n try:\n s3_util = S3Util(constants.default_s3_bucket_name, 'temp/models/test1', False)\n snapshot = Snapshot(s3_util)\n linear = torch.nn.Linear(20, 10)\n adam = torch.optim.Adam(linear.parameters(), 0.001)\n snapshot.put(linear, adam, 11)\n\n model, optimizer, epoch = snapshot.get(linear, adam)\n print(str(model))\n print(str(optimizer))\n print(epoch)\n print('test_get completed')\n except Exception as e:\n print(str(e))\n self.fail()\n\n\n","sub_path":"src/nnet/test/test_snapshot.py","file_name":"test_snapshot.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"401196392","text":"# -*- coding: utf-8 -*-\n\"\"\"Tests for unihan.\n\ncihaidata_unihan.testsuite.unihan\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, \\\n with_statement, unicode_literals\n\nimport os\nimport tempfile\nimport logging\nimport unittest\nimport zipfile\nimport shutil\n\ntry:\n import unittest2 as unittest\nexcept ImportError: # Python 2.7\n import unittest\n\n\nfrom scripts import process\n\nfrom scripts._compat import text_type\nfrom scripts.process import UNIHAN_URL, UNIHAN_DEST, WORK_DIR, UNIHAN_FIELDS, \\\n UNIHAN_FILES, default_config, Builder, UNIHAN_ZIP_FILEPATH, zip_has_files\nfrom scripts.util import merge_dict, ucn_to_unicode, ucnstring_to_python, \\\n ucnstring_to_unicode\n\n\nfrom .helpers import add_to_path, setup_path, get_datapath, captureStdErr\n\n\nlog = logging.getLogger(__name__)\n\n\nSAMPLE_DATA = \"\"\"\\\nU+3400\tkCantonese\tjau1\nU+3400\tkDefinition\t(same as U+4E18 丘) hillock or mound\nU+3400\tkMandarin\tqiū\nU+3401\tkCantonese\ttim2\nU+3401\tkDefinition\tto lick; to taste, a mat, bamboo bark\nU+3401\tkHanyuPinyin\t10019.020:tiàn\n\"\"\"\n\ntest_config = merge_dict(default_config.copy(), {\n 'source': UNIHAN_URL,\n 'destination': UNIHAN_DEST,\n 'zip_filepath': UNIHAN_ZIP_FILEPATH,\n 'work_dir': WORK_DIR,\n 'fields': UNIHAN_FIELDS,\n 'files': 'Unihan_Readings.txt',\n 'download': False\n})\n\n\nclass MockBuilder(Builder):\n\n default_config = test_config\n\nBuilder = MockBuilder\n\n\nclass TestCase(unittest.TestCase):\n pass\n\n\nclass UnihanHelper(TestCase):\n\n config = os.path.abspath(os.path.join(\n os.path.dirname(__file__),\n 'test_config.yml'\n ))\n\n @classmethod\n def setUpClass(cls):\n cls.tempdir = tempfile.mkdtemp()\n cls.mock_zip_filename = 'Unihan.zip'\n cls.mock_zip_filepath = os.path.join(cls.tempdir, cls.mock_zip_filename)\n zf = zipfile.ZipFile(cls.mock_zip_filepath, 'a')\n zf.writestr(\"Unihan_Readings.txt\", SAMPLE_DATA.encode('utf-8'))\n zf.close()\n\n Builder.default_config['work_dir'] = cls.tempdir\n Builder.default_config['zip_filepath'] = cls.mock_zip_filepath\n Builder.default_config['destination'] = os.path.join(cls.tempdir, 'unihan.csv')\n\n cls.mock_zip = zf\n\n super(UnihanHelper, cls).setUpClass()\n\n @classmethod\n def tearDownClass(cls):\n shutil.rmtree(cls.tempdir)\n super(UnihanHelper, cls).tearDownClass()\n\n\nclass UnihanMock(UnihanHelper):\n\n def test_builder_mock(self):\n\n self.assertEqual(test_config, Builder.default_config)\n self.assertNotEqual(test_config, default_config)\n\n b = Builder({})\n\n self.assertEqual(test_config, b.config)\n self.assertNotEqual(default_config, b.config)\n\n\nclass UnihanScriptsTestCase(UnihanHelper):\n\n def test_zip_has_files(self):\n self.assertTrue(\n zip_has_files(['Unihan_Readings.txt'], self.mock_zip)\n )\n\n self.assertFalse(\n zip_has_files(['Unihan_Cats.txt'], self.mock_zip)\n )\n\n def test_has_unihan_zip(self):\n if os.path.isfile(UNIHAN_ZIP_FILEPATH):\n self.assertTrue(process.has_unihan_zip())\n else:\n self.assertFalse(process.has_unihan_zip())\n\n self.assertTrue(process.has_unihan_zip(self.mock_zip_filepath))\n\n def test_in_fields(self):\n columns = ['hey', 'kDefinition', 'kWhat']\n result = process.in_fields('kDefinition', columns)\n\n self.assertTrue(result)\n\n def test_filter_manifest(self):\n expected = {\n 'Unihan_Variants.txt': [\n 'kCompatibilityVariant',\n 'kSemanticVariant',\n 'kSimplifiedVariant',\n 'kSpecializedSemanticVariant',\n 'kTraditionalVariant',\n 'kZVariant',\n ]\n }\n\n result = process.filter_manifest(['Unihan_Variants.txt'])\n\n self.assertEqual(set(result), set(expected))\n\n def test_get_files(self):\n fields = ['kKorean', 'kRSUnicode']\n\n expected = ['Unihan_Readings.txt', 'Unihan_RadicalStrokeCounts.txt']\n\n result = process.get_files(fields)\n\n self.assertEqual(set(result), set(expected))\n\n def test_save(self):\n\n src_filepath = self.mock_zip_filepath\n\n tempdir = tempfile.mkdtemp()\n\n dest_filepath = os.path.join(tempdir, self.mock_zip_filename)\n process.save(src_filepath, dest_filepath, shutil.copy)\n\n result = os.path.exists(dest_filepath)\n\n shutil.rmtree(tempdir)\n\n self.assertTrue(result)\n\n def test_download(self):\n\n src_filepath = self.mock_zip_filepath\n\n tempdir = self.tempdir\n dest_filepath = os.path.join(tempdir, 'data', self.mock_zip_filename)\n\n process.download(src_filepath, dest_filepath, shutil.copy)\n\n result = os.path.dirname(os.path.join(dest_filepath, 'data'))\n self.assertTrue(\n result,\n msg=\"Creates data directory if doesn't exist.\"\n )\n\n def test_extract(self):\n\n zf = process.extract(self.mock_zip_filepath)\n\n self.assertEqual(len(zf.infolist()), 1)\n self.assertEqual(zf.infolist()[0].file_size, 218)\n self.assertEqual(zf.infolist()[0].filename, \"Unihan_Readings.txt\")\n\n def test_convert_only_output_requested_columns(self):\n fd, filename = tempfile.mkstemp()\n\n try:\n os.write(fd, SAMPLE_DATA.encode('utf-8'))\n\n csv_files = [\n filename\n ]\n\n columns = [\n 'kTotalStrokes',\n 'kPhonetic',\n 'kCantonese',\n 'kDefinition',\n ] + process.index_fields\n\n items = process.convert(csv_files, columns)\n\n notInColumns = []\n inColumns = ['kDefinition', 'kCantonese'] + process.index_fields\n\n # columns not selected in convert must not be in result.\n for v in items[0]:\n if v not in columns:\n notInColumns.append(v)\n else:\n inColumns.append(v)\n finally:\n os.remove(filename)\n\n self.assertEqual([], notInColumns, msg=\"Convert filters columns not specified.\")\n self.assertTrue(set(inColumns).issubset(set(columns)), \"Convert returns correct columns specified + ucn and char.\")\n\n def test_convert_simple_data_format(self):\n \"\"\"convert turns data into simple data format (SDF).\"\"\"\n csv_files = [\n get_datapath('Unihan_DictionaryLikeData.txt'),\n get_datapath('Unihan_Readings.txt'),\n ]\n\n columns = [\n 'kTotalStrokes',\n 'kPhonetic',\n 'kCantonese',\n 'kDefinition',\n ] + process.index_fields\n\n items = process.convert(csv_files, columns)\n\n header = items[0]\n self.assertEqual(header, columns)\n\n rows = items[1:]\n\n def test_convert_keys_values_match(self):\n \"\"\"convert returns values in the correct places.\"\"\"\n pass\n\n\nclass UnihanHelperFunctions(UnihanHelper):\n\n \"\"\"Utilities to retrieve unihan data in datapackage format.\"\"\"\n\n def test_flatten_fields(self):\n\n single_dataset = {\n 'Unihan_Readings.txt': [\n 'kCantonese',\n 'kDefinition',\n 'kHangul',\n ]\n }\n\n expected = ['kCantonese', 'kDefinition', 'kHangul']\n results = process.get_fields(single_dataset)\n\n self.assertEqual(expected, results)\n\n datasets = {\n 'Unihan_NumericValues.txt': [\n 'kAccountingNumeric',\n 'kOtherNumeric',\n 'kPrimaryNumeric',\n ],\n 'Unihan_OtherMappings.txt': [\n 'kBigFive',\n 'kCCCII',\n 'kCNS1986',\n ]\n }\n\n expected = [\n 'kAccountingNumeric',\n 'kOtherNumeric',\n 'kPrimaryNumeric',\n 'kBigFive',\n 'kCCCII',\n 'kCNS1986',\n ]\n\n results = process.get_fields(datasets)\n\n self.assertSetEqual(set(expected), set(results))\n\n def test_pick_files(self):\n \"\"\"Pick a white list of files to build from.\"\"\"\n\n files = ['Unihan_Readings.txt', 'Unihan_Variants.txt']\n\n config = {\n 'files': files,\n 'zip_filepath': self.mock_zip_filepath\n }\n\n b = process.Builder(config)\n\n result = b.config.files\n expected = files\n\n self.assertEqual(result, expected, msg='Returns only the files picked.')\n\n def test_raise_error_unknown_field(self):\n \"\"\"Throw error if picking unknown field.\"\"\"\n\n config = {\n 'fields': ['kHello']\n }\n\n with self.assertRaisesRegexp(KeyError, 'Field ([a-zA-Z].*) not found in file list.'):\n b = process.Builder(config)\n\n def test_raise_error_unknown_file(self):\n \"\"\"Throw error if picking unknown file.\"\"\"\n\n config = {\n 'files': ['Sparta.lol']\n }\n\n with self.assertRaisesRegexp(KeyError, 'File ([a-zA-Z_\\.\\'].*) not found in file list.'):\n b = process.Builder(config)\n\n def test_raise_error_unknown_field_filtered_files(self):\n \"\"\"Throw error if picking field not in file list, when files specified.\"\"\"\n\n files = ['Unihan_Variants.txt']\n\n config = {\n 'files': files,\n 'fields': ['kDefinition'],\n }\n\n with self.assertRaisesRegexp(KeyError, 'Field ([a-zA-Z].*) not found in file list.'):\n b = process.Builder(config)\n\n def test_set_reduce_files_automatically_when_only_field_specified(self):\n \"\"\"Picks file automatically if none specified and fields are.\"\"\"\n\n fields = process.UNIHAN_MANIFEST['Unihan_Readings.txt'] + process.UNIHAN_MANIFEST['Unihan_Variants.txt']\n\n config = {\n 'fields': fields,\n }\n\n b = process.Builder(config)\n\n expected = ['Unihan_Readings.txt', 'Unihan_Variants.txt']\n results = b.config.files\n\n self.assertSetEqual(set(expected), set(results))\n\n def test_set_reduce_fields_automatically_when_only_files_specified(self):\n \"\"\"Picks only necessary files when fields specified.\"\"\"\n\n files = ['Unihan_Readings.txt', 'Unihan_Variants.txt']\n\n config = {\n 'files': files\n }\n\n b = process.Builder(config)\n\n expected = process.get_fields(process.filter_manifest(files))\n results = b.config.fields\n\n self.assertSetEqual(set(expected), set(results), msg='Returns only the fields for files picked.')\n\n\nclass ProcessTestCase(TestCase):\n\n def test_conversion_ucn_to_unicode(self):\n before = 'U+4E00'\n expected = '\\u4e00'\n\n result = ucn_to_unicode(before)\n\n self.assertEqual(result, expected)\n\n self.assertIsInstance(result, text_type)\n\n # wide character\n before = 'U+20001'\n expected = '\\U00020001'\n\n result = ucn_to_unicode(before)\n\n self.assertEqual(result, expected)\n self.assertIsInstance(result, text_type)\n\n before = '(same as U+7A69 穩) firm; stable; secure'\n expected = '(same as 穩 穩) firm; stable; secure'\n\n result = ucnstring_to_unicode(before)\n\n self.assertEqual(result, expected)\n self.assertIsInstance(result, text_type)\n\n\nclass CliArgTestCase(UnihanHelper):\n\n \"\"\"Allows for creating a custom output of unihan data\n in datapackage.json format.\"\"\"\n\n def test_no_args(self):\n \"\"\"Works without arguments.\"\"\"\n\n expected = test_config\n result = Builder.from_cli([]).config\n\n self.assertEqual(expected, result)\n\n def test_cli_plus_defaults(self):\n \"\"\"Test CLI args + defaults.\"\"\"\n\n expectedIn = {'zip_filepath': self.mock_zip_filepath}\n result = Builder.from_cli(['-z', self.mock_zip_filepath]).config\n self.assertDictContainsSubset(expectedIn, result)\n\n expectedIn = {'fields': ['kDefinition']}\n result = Builder.from_cli(['-F', 'kDefinition']).config\n self.assertDictContainsSubset(expectedIn, result)\n\n expectedIn = {'fields': ['kDefinition']}\n result = Builder.from_cli(['-F', 'kDefinition']).config\n self.assertDictContainsSubset(expectedIn, result)\n\n expectedIn = {'fields': ['kDefinition', 'kXerox']}\n result = Builder.from_cli(['-F', 'kDefinition', 'kXerox']).config\n self.assertDictContainsSubset(expectedIn, result, msg=\"Accepts multiple fields.\")\n\n expectedIn = {'fields': ['kDefinition', 'kXerox'], 'destination': 'data/ha.csv'}\n result = Builder.from_cli(['-F', 'kDefinition', 'kXerox', '-d', 'data/ha.csv']).config\n self.assertDictContainsSubset(expectedIn, result, msg=\"Accepts multiple arguments.\")\n\n def test_cli_exit_emessage_to_stderr(self):\n \"\"\"Sends exception .message to stderr on exit.\"\"\"\n\n with self.assertRaisesRegexp(SystemExit, 'Field sdfa not found in file list.'):\n with captureStdErr(Builder.from_cli, ['-d', 'data/output.csv', '-F', 'sdfa']) as output:\n pass\n\n\ndef suite():\n setup_path()\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(UnihanMock))\n suite.addTest(unittest.makeSuite(UnihanHelperFunctions))\n suite.addTest(unittest.makeSuite(UnihanScriptsTestCase))\n suite.addTest(unittest.makeSuite(ProcessTestCase))\n suite.addTest(unittest.makeSuite(CliArgTestCase))\n return suite\n","sub_path":"testsuite/unihan.py","file_name":"unihan.py","file_ext":"py","file_size_in_byte":13495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"629582609","text":"from flask import Blueprint, request, session\nfrom flask_stormpath import login_required, groups_required, current_user\nfrom taa.services.enrollments import EnrollmentApplicationService\n\nfrom taa.api import route\n\nbp = Blueprint('envelopes', __name__, url_prefix='/envelopes')\nread_api_groups = ['agents', 'home_office', 'admins']\n\n\n@route(bp, '/', methods=['GET'])\n@login_required\n@groups_required(read_api_groups, all=False)\ndef get_envelopes():\n \"\"\"Get all the envelopes that the current user can see.\"\"\"\n from taa.services.docusign import DocuSignService\n docusign_service = DocuSignService()\n\n return docusign_service.search_envelopes(for_user=current_user)\n\n# This function is here for legacy reasons, but we don't use DocuSign redirect for signing anymore.\n@route(bp, '//sign', methods=[\"POST\"])\n@login_required\n@groups_required(read_api_groups, all=False)\ndef sign_envelope(envelope_id):\n from taa.services.docusign import DocuSignService\n docusign_service = DocuSignService()\n\n enrollment_record = docusign_service.get_enrollment_record_from_envelope(envelope_id)\n\n # To allow the callback page to know that we may have modified an enrollment, set a session variable.\n session['enrollment_application_id'] = enrollment_record.id\n\n if request.args.get('from') == 'inbox':\n callback_url = docusign_service.build_inbox_callback_url(enrollment_record)\n else:\n # Return the user to the census record view.\n callback_url = docusign_service.build_census_record_callback_url(enrollment_record)\n\n url, errors = docusign_service.get_envelope_signing_url(current_user, envelope_id, callback_url)\n\n return {'url': url, 'errors': errors}\n\n\n@route(bp, '/sign-enrollment/', methods=[\"POST\"])\n@login_required\n@groups_required(read_api_groups, all=False)\ndef sign_enrollment(enrollment_id):\n from taa.services.docusign import DocuSignService\n docusign_service = DocuSignService()\n enrollment_application_service = EnrollmentApplicationService()\n \n enrollment_record = enrollment_application_service.get(enrollment_id)\n\n # To allow the callback page to know that we may have modified an enrollment, set a session variable.\n session['enrollment_application_id'] = enrollment_record.id\n\n if request.args.get('from') == 'inbox':\n callback_url = docusign_service.build_inbox_callback_url(enrollment_record)\n else:\n # Return the user to the census record view.\n callback_url = docusign_service.build_census_record_callback_url(enrollment_record)\n\n #url, errors = docusign_service.get_envelope_signing_url(current_user, envelope_id, callback_url)\n \n errors = docusign_service.sign_enrollment(current_user, enrollment_record)\n \n return {'errors': errors}\n","sub_path":"taa/api/envelopes.py","file_name":"envelopes.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"594082309","text":"# -*- coding: utf-8 -*-\n\n# TESS UTILITY TO PERFORM SOME MAINTENANCE COMMANDS\n\n# ----------------------------------------------------------------------\n# Copyright (c) 2014 Rafael Gonzalez.\n#\n# See the LICENSE file for details\n# ----------------------------------------------------------------------\n\n#--------------------\n# System wide imports\n# -------------------\n\nfrom __future__ import generators # needs to be at the top of your module\n\nimport sys\nimport os\nimport os.path\nimport argparse\nimport sqlite3\nimport logging\nimport traceback\n\n# Python3 catch\ntry:\n raw_input\nexcept:\n raw_input = input \n\n# ----------------\n# MatPlotLib stuff\n# ----------------\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom matplotlib import colors\nfrom matplotlib.ticker import PercentFormatter\n\n\n# -------------\n# Local imports\n# -------------\n\nimport tdbtool.s4a\nfrom . import __version__\n\n# ----------------\n# Module constants\n# ----------------\n\nTSTAMP_FORMAT = \"%Y-%m-%dT%H:%M:%SZ\"\n\n# -----------------------\n# Module global variables\n# -----------------------\n\n\n\n# --------------\n# Module classes\n# --------------\n\n\n# -----------------------\n# Module global functions\n# -----------------------\n\ndef daily_period_iterable(connection, name, central):\n\trow = {'name': name}\n\tcursor = connection.cursor()\n\tif central == \"median\":\n\t\tcursor.execute(\n\t\t\t'''\n\t\t\tSELECT median_period\n\t\t\tFROM daily_stats_t\n\t\t\tWHERE name = :name\n\t\t\t''', row)\n\telse:\n\t\tcursor.execute(\n\t\t\t'''\n\t\t\tSELECT mean_period\n\t\t\tFROM daily_stats_t\n\t\t\tWHERE name = :name\n\t\t\t''', row)\n\treturn cursor # return Cursor as an iterable\n\ndef differences_iterable(connection, name):\n\trow = {'name': name}\n\tcursor = connection.cursor()\n\tcursor.execute(\n\t\t\t'''\n\t\t\tSELECT delta_T, delta_seq\n\t\t\tFROM first_differences_t\n\t\t\tWHERE name = :name\n\t\t\t''', row)\n\t\n\treturn cursor # return Cursor as an iterable\n\n\ndef plot_period(connection, options):\n\titerable = daily_period_iterable(connection, options.name, options.central)\n\tperiod = zip(*iterable)\n\tperiod = np.array(period[0], dtype=float)\n\tfig, axs = plt.subplots(1, 1, tight_layout=True)\n\tplt.ion()\n\tplt.yscale('log')\n\tplt.ylabel('Counts')\n\t#plt.grid(True)\n\tplt.grid(b=True, which='major', color='b', linestyle='-')\n\tplt.grid(b=True, which='minor', color='r', linestyle=':')\n\tplt.title('Period histogram for {0}'.format(options.name))\n\taxs.hist(period, bins=options.bins)\n\tplt.show()\n\traw_input(\"Press to exit\")\n\n\n\n\ndef plot_differences(connection, options):\n\titerable = differences_iterable(connection, options.name)\n\tdelta_T, delta_Seq = zip(*iterable)\n\tdelta_T = np.array(delta_T, dtype=float)\n\tdelta_Seq = np.array(delta_Seq, dtype=float)\n\tfig, axs = plt.subplots(1, 1, tight_layout=True)\n\tplt.ion()\n\tplt.title('2D differences histogram for {0}'.format(options.name))\n\tplt.ylabel('Delta Sequence')\n\tplt.ylabel('Delta Time')\n\thist = axs.hist2d(delta_Seq, delta_T, bins=options.bins, norm=colors.LogNorm())\n\tplt.show()\n\traw_input(\"Press to exit\")\n\n\n\n\n# ==============\n# MAIN FUNCTIONS\n# ==============\n\n\ndef plot_histogram(connection, options):\n\tplt.ioff() # Turns off interactive mode\n\tpass\n\n\n","sub_path":"tdbtool/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"345441914","text":"from functions import covMatrix\n## logging\nimport logging\nimport coloredlogs\nimport os\n\nlogger = logging.getLogger(os.path.basename(__file__).replace('.py', ''))\nlog_level = 'INFO'\n# log_level = 'DEBUG'\nif log_level == 'INFO':\n coloredlogs.install(level='INFO', logger=logger)\nelif log_level == 'DEBUG':\n coloredlogs.install(level='DEBUG', logger=logger)\nelse:\n coloredlogs.install(level='WARNING', logger=logger)\n\nprint (covMatrix().shape)\nlogger.info('Processing eigenvalues & eigenvectors')\nlogger.debug(covMatrix().shape)","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"177214846","text":"class DfAlertManager:\n def __init__(self, op_params):\n self.op_params = op_params\n self.current_profile = self.op_params.get('dynamic_follow', default='normal').lower()\n self.profiles = ['close', 'normal', 'far']\n\n self.idx_to_profile = {0: 'close', 1: 'normal', 2: 'far'}\n self.profile_to_idx = {v: k for k, v in self.idx_to_profile.items()}\n\n self.last_button_status = None\n\n def run_init(self):\n try:\n if self.profile_to_idx[self.current_profile] != 0: # the following line and loop ensure we start at the user's current profile\n self.idx_to_profile[0] = self.current_profile\n self.profiles.remove(self.current_profile)\n for idx, profile in enumerate(self.profiles):\n self.idx_to_profile[idx + 1] = profile\n self.last_button_status = 0\n except KeyError:\n self.op_params.put('dynamic_follow', 'normal')\n self.current_profile = 'normal'\n if self.profile_to_idx[self.current_profile] != 0: # the following line and loop ensure we start at the user's current profile\n self.idx_to_profile[0] = self.current_profile\n self.profiles.remove(self.current_profile)\n for idx, profile in enumerate(self.profiles):\n self.idx_to_profile[idx + 1] = profile\n self.last_button_status = 0\n\n def update(self, sm):\n if self.last_button_status is None:\n self.run_init()\n else:\n df_profile = sm['dynamicFollowButton'].status\n if self.last_button_status != df_profile:\n self.last_button_status = df_profile\n df_profile_string = self.idx_to_profile[df_profile]\n self.op_params.put('dynamic_follow', df_profile_string) # this sets our param so long_mpc will change profiles\n return df_profile_string\n\n return None\n","sub_path":"selfdrive/controls/df_alert_manager.py","file_name":"df_alert_manager.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"110343187","text":"import logging\n\nfrom iguazu import __version__\nfrom iguazu.core.exceptions import SoftPreconditionFailed\nfrom iguazu.core.flows import PreparedFlow\nfrom iguazu.flows.datasets import GenericDatasetFlow\nfrom iguazu.functions.surveys import NoSurveyReport\nfrom iguazu.tasks.common import SlackTask, LoadDataframe, MergeDataframes\nfrom iguazu.tasks.metadata import CreateFlowMetadata, UpdateFlowMetadata, PropagateMetadata\nfrom iguazu.tasks.standards import Report\nfrom iguazu.tasks.surveys import ExtractReportFeatures, ExtractMetaFeatures\n\nlogger = logging.getLogger(__name__)\n\n\nclass SurveysFeaturesFlow(PreparedFlow):\n \"\"\"Extract all surveys features from a file dataset\"\"\"\n\n REGISTRY_NAME = 'features_surveys'\n DEFAULT_QUERY = f\"\"\"\n SELECT base->>'id' AS id, -- id is the bare minimum needed for the query task to work\n base->>'filename' AS filename, -- this is just to help the human debugging this\n omind->>'user_hash' AS user_hash, -- this is just to help the openmind human debugging this\n iguazu->>'version' AS version -- this is just to help the openmind human debugging this\n FROM metadata\n WHERE base->>'state' = 'READY' -- No temporary files\n AND base->>'filename' LIKE '%.hdf5' -- Only HDF5 files\n AND protocol->>'name' = 'bilan-vr' -- Files from the VR bilan protocol\n AND protocol->'extra' ->> 'legacy' = 'false' -- Files that are not legacy\n AND standard->'events' ? '/iguazu/events/standard' -- containing standardized events\n AND iguazu->>'status' = 'SUCCESS' -- Files that were successfully standardized\n AND (\n iguazu->'flows'->'{REGISTRY_NAME}'->>'status' IS NULL\n OR iguazu->'flows'->'{REGISTRY_NAME}'->>'version' IS NULL\n OR iguazu->'flows'->'{REGISTRY_NAME}'->>'version' < '{__version__}'\n )\n ORDER BY id -- always in the same order\n \"\"\"\n\n def _build(self, **kwargs):\n # Force required families: Quetzal workspace must have the following\n # families: (nb: None means \"latest\" version)\n required_families = dict(\n iguazu=None,\n omind=None,\n standard=None,\n protocol=None\n )\n families = kwargs.get('families', {}) or {} # Could be None by default args\n for name in required_families:\n families.setdefault(name, required_families[name])\n kwargs['families'] = families\n\n # When the query is set by kwargs, leave the query and dialect as they\n # come. Otherwise, set to the default defined just above\n if not kwargs.get('query', None):\n kwargs['query'] = self.DEFAULT_QUERY\n kwargs['dialect'] = 'postgresql_json'\n\n # The cardiac features flow requires an upstream dataset flow in order\n # to provide the input files. Create one and deduce the tasks to\n # plug the cardiac flow to the output of the dataset flow\n dataset_flow = GenericDatasetFlow(**kwargs)\n raw_signals = dataset_flow.terminal_tasks().pop()\n events = raw_signals\n self.update(dataset_flow)\n\n create_flow_metadata = CreateFlowMetadata(flow_name=self.REGISTRY_NAME)\n\n # Instantiate tasks\n survey_report = ExtractReportFeatures(\n events_hdf5_key='/iguazu/events/standard',\n output_hdf5_key='/iguazu/features/survey_report',\n graceful_exceptions=(NoSurveyReport,\n SoftPreconditionFailed)\n )\n survey_meta = ExtractMetaFeatures(\n features_hdf5_key='/iguazu/features/survey_report',\n output_hdf5_key='/iguazu/features/survey_meta'\n )\n\n propagate_metadata = PropagateMetadata(propagate_families=['omind', 'protocol'])\n\n update_flow_metadata = UpdateFlowMetadata(flow_name=self.REGISTRY_NAME)\n report = Report()\n\n notify = SlackTask(preamble='Survey feature extraction finished\\n'\n 'Task report:')\n\n with self:\n\n create_noresult = create_flow_metadata.map(parent=events)\n # Feature extraction\n features_reports = survey_report.map(events=events, upstream_tasks=[create_noresult])\n features_metas = survey_meta.map(features=features_reports, parent=raw_signals,\n upstream_tasks=[create_noresult])\n\n features_with_metadata = propagate_metadata.map(parent=raw_signals, child=features_metas)\n update_noresult = update_flow_metadata.map(parent=raw_signals, child=features_with_metadata)\n # Send slack notification\n message = report(files=features_with_metadata, upstream_tasks=[update_noresult])\n notify(message=message)\n\n logger.debug('Built flow %s with tasks %s', self, self.tasks)\n\n @staticmethod\n def click_options():\n return GenericDatasetFlow.click_options()\n\n\nclass SurveysSummaryFlow(PreparedFlow):\n \"\"\"Collect all cardiac features in a single CSV file\"\"\"\n\n REGISTRY_NAME = 'summarize_surveys'\n DEFAULT_QUERY = f\"\"\"\n SELECT\n base->>'id' AS id, -- id is the bare minimum needed for the query task to work\n base->>'filename' AS filename -- this is just to help the human debugging this\n FROM metadata\n WHERE base->>'state' = 'READY' -- No temporary files\n AND base->>'filename' LIKE '%.hdf5' -- Only HDF5 files TODO: remove _gsr_features hack\n AND iguazu->>'status' = 'SUCCESS' -- Files that were successfully standardized\n AND standard->'features' ? '/iguazu/features/survey_meta' -- containing the behavioral features\n AND iguazu->>'version' = '{__version__}'\n ORDER BY id -- always in the same order\n \"\"\"\n\n def _build(self,\n **kwargs):\n\n # Manage parameters\n kwargs = kwargs.copy()\n # Propagate workspace name because we captured it on kwargs\n # kwargs['workspace_name'] = workspace_name\n # Force required families: Quetzal workspace must have the following\n # families: (nb: None means \"latest\" version)\n required_families = dict(\n iguazu=None,\n omind=None,\n standard=None,\n protocol=None\n )\n families = kwargs.get('families', {}) or {} # Could be None by default args\n for name in required_families:\n families.setdefault(name, required_families[name])\n kwargs['families'] = families\n\n # When the query is set by kwargs, leave the query and dialect as they\n # come. Otherwise, set to the default defined just above\n if not kwargs.get('query', None):\n kwargs['query'] = self.DEFAULT_QUERY\n kwargs['dialect'] = 'postgresql_json'\n\n # Manage connections to other flows\n dataset_flow = GenericDatasetFlow(**kwargs)\n self.update(dataset_flow)\n features_files = dataset_flow.terminal_tasks().pop()\n\n # instantiate tasks. Use separate tasks for a classic ETL approach:\n # E: read features from HDF5 file\n # T and L: merge features into a single dataframe, then save as CSV\n read_features = LoadDataframe(\n key='/iguazu/features/survey_meta',\n )\n merge_features = MergeDataframes(\n filename='surveys_summary.csv',\n path='datasets',\n )\n\n notify = SlackTask(message='VR surveys features summarization finished!')\n\n with self:\n feature_dataframes = read_features.map(file=features_files)\n merged_dataframe = merge_features(parents=features_files, dataframes=feature_dataframes)\n # Send slack notification\n notify(upstream_tasks=[merged_dataframe])\n\n @staticmethod\n def click_options():\n return GenericDatasetFlow.click_options()\n","sub_path":"iguazu/flows/surveys.py","file_name":"surveys.py","file_ext":"py","file_size_in_byte":7993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"110900132","text":"from __future__ import print_function\n\nimport math\nimport sys\nimport os\nimport time\n\nimport numpy as np\nimport theano\nimport theano.tensor as T\n\nimport lasagne\n\n####################################################################################################\n# ################## Download and prepare the MNIST dataset ##################\n# This is just some way of getting the MNIST dataset from an online location\n# and loading it into numpy arrays. It doesn't involve Lasagne at all.\n\ndef load_dataset():\n # We first define a download function, supporting both Python 2 and 3.\n if sys.version_info[0] == 2:\n from urllib import urlretrieve\n else:\n from urllib.request import urlretrieve\n\n def download(filename, source='http://yann.lecun.com/exdb/mnist/'):\n print(\"Downloading %s\" % filename)\n urlretrieve(source + filename, filename)\n\n # We then define functions for loading MNIST images and labels.\n # For convenience, they also download the requested files if needed.\n import gzip\n\n def load_mnist_images(filename):\n if not os.path.exists(filename):\n download(filename)\n # Read the inputs in Yann LeCun's binary format.\n with gzip.open(filename, 'rb') as f:\n data = np.frombuffer(f.read(), np.uint8, offset=16)\n # The inputs are vectors now, we reshape them to monochrome 2D images,\n # following the shape convention: (examples, channels, rows, columns)\n data = data.reshape(-1, 1, 28, 28)\n # The inputs come as bytes, we convert them to float32 in range [0,1].\n # (Actually to range [0, 255/256], for compatibility to the version\n # provided at http://deeplearning.net/data/mnist/mnist.pkl.gz.)\n return data / np.float32(256)\n\n def load_mnist_labels(filename):\n if not os.path.exists(filename):\n download(filename)\n # Read the labels in Yann LeCun's binary format.\n with gzip.open(filename, 'rb') as f:\n data = np.frombuffer(f.read(), np.uint8, offset=8)\n # The labels are vectors of integers now, that's exactly what we want.\n return data\n\n # We can now download and read the training and test set images and labels.\n X_train = load_mnist_images('train-images-idx3-ubyte.gz')\n y_train = load_mnist_labels('train-labels-idx1-ubyte.gz')\n X_test = load_mnist_images('t10k-images-idx3-ubyte.gz')\n y_test = load_mnist_labels('t10k-labels-idx1-ubyte.gz')\n\n # We reserve the last 10000 training examples for validation.\n X_train, X_val = X_train[:-10000], X_train[-10000:]\n y_train, y_val = y_train[:-10000], y_train[-10000:]\n\n # We just return all the arrays in order, as expected in main().\n # (It doesn't matter how we do this as long as we can read them again.)\n return X_train, y_train, X_val, y_val, X_test, y_test\n\ndef build_cnn(input_var=None, nfilters = 32):\n # As a third model, we'll create a CNN of two convolution + pooling stages\n # and a fully-connected hidden layer in front of the output layer.\n\n # Input layer, as usual:\n network = lasagne.layers.InputLayer(shape=(None, 1, 28, 28),\n input_var=input_var)\n # This time we do not apply input dropout, as it tends to work less well\n # for convolutional layers.\n\n # Convolutional layer with 32 kernels of size 5x5. Strided and padded\n # convolutions are supported as well; see the docstring.\n network = lasagne.layers.Conv2DLayer(\n network, num_filters=nfilters, filter_size=(5, 5),\n nonlinearity=lasagne.nonlinearities.rectify,\n W=lasagne.init.GlorotUniform())\n # Expert note: Lasagne provides alternative convolutional layers that\n # override Theano's choice of which implementation to use; for details\n # please see http://lasagne.readthedocs.org/en/latest/user/tutorial.html.\n\n # Max-pooling layer of factor 2 in both dimensions:\n network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2))\n\n # Another convolution with 32 5x5 kernels, and another 2x2 pooling:\n network = lasagne.layers.Conv2DLayer(\n network, num_filters=nfilters, filter_size=(5, 5),\n nonlinearity=lasagne.nonlinearities.rectify)\n network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2))\n\n # A fully-connected layer of 256 units with 50% dropout on its inputs:\n network = lasagne.layers.DenseLayer(\n lasagne.layers.dropout(network, p=.5),\n num_units=256,\n nonlinearity=lasagne.nonlinearities.rectify)\n\n # And, finally, the 10-unit output layer with 50% dropout on its inputs:\n network = lasagne.layers.DenseLayer(\n lasagne.layers.dropout(network, p=.5),\n num_units=10,\n nonlinearity=lasagne.nonlinearities.softmax)\n\n return network\n\n\n# ############################# Batch iterator ###############################\n# This is just a simple helper function iterating over training data in\n# mini-batches of a particular size, optionally in random order. It assumes\n# data is available as numpy arrays. For big datasets, you could load numpy\n# arrays as memory-mapped files (np.load(..., mmap_mode='r')), or write your\n# own custom data iteration function. For small datasets, you can also copy\n# them to GPU at once for slightly improved performance. This would involve\n# several changes in the main program, though, and is not demonstrated here.\n# Notice that this function returns only mini-batches of size `batchsize`.\n# If the size of the data is not a multiple of `batchsize`, it will not\n# return the last (remaining) mini-batch.\n\ndef iterate_minibatches(inputs, targets, batchsize, shuffle=False):\n assert len(inputs) == len(targets)\n if shuffle:\n indices = np.arange(len(inputs))\n np.random.shuffle(indices)\n for start_idx in range(0, len(inputs) - batchsize + 1, batchsize):\n if shuffle:\n excerpt = indices[start_idx:start_idx + batchsize]\n else:\n excerpt = slice(start_idx, start_idx + batchsize)\n yield inputs[excerpt], targets[excerpt]\n\n\n# ############################## Main program ################################\n# Everything else will be handled in our main program now. We could pull out\n# more functions to better separate the code, but it wouldn't make it any\n# easier to read.\n\ndef main(ntrain = 50000, nvalid = 10000, algorithm_type = 1,\n batch_size_train = 500, batch_size_valid = 500,\n num_epochs=500, LR = 0.1, M = 0.9,\n nfilters = 32, time_limit = 10000):\n X_train, y_train, X_val, y_val, X_test, y_test = load_dataset()\n\n X_train = X_train[1:ntrain]\n y_train = y_train[1:ntrain]\n X_val = X_val[1:nvalid]\n y_val = y_val[1:nvalid]\n\n input_var = T.tensor4('inputs')\n target_var = T.ivector('targets')\n\n network = build_cnn(input_var, nfilters)\n\n prediction = lasagne.layers.get_output(network)\n loss = lasagne.objectives.categorical_crossentropy(prediction, target_var)\n loss = loss.mean()\n params = lasagne.layers.get_all_params(network, trainable=True)\n if (algorithm_type == 1):\n updates = lasagne.updates.sgd(loss, params, learning_rate=LR)\n if (algorithm_type == 2):\n updates = lasagne.updates.momentum(loss, params, learning_rate=LR,\n momentum = M)\n test_prediction = lasagne.layers.get_output(network, deterministic=True)\n test_loss = lasagne.objectives.categorical_crossentropy(test_prediction,\n target_var)\n test_loss = test_loss.mean()\n test_acc = T.mean(T.eq(T.argmax(test_prediction, axis=1), target_var),\n dtype=theano.config.floatX)\n\n train_fn = theano.function([input_var, target_var], loss, updates=updates)\n\n # Compile a second function computing the validation loss and accuracy:\n val_fn = theano.function([input_var, target_var], [test_loss, test_acc])\n \n start_time = time.time() \n best_val_err = 0\n for epoch in range(num_epochs):\n # In each epoch, we do a full pass over the training data:\n train_err = 0\n train_batches = 0\n start_time_epoch = time.time()\n for batch in iterate_minibatches(X_train, y_train, batch_size_train, shuffle=True):\n inputs, targets = batch\n train_err += train_fn(inputs, targets)\n train_batches += 1\n\n # And a full pass over the validation data:\n val_err = 0\n val_batches = 0\n for batch in iterate_minibatches(X_val, y_val, batch_size_valid, shuffle=False):\n inputs, targets = batch\n err, acc = val_fn(inputs, targets)\n val_err += err\n val_batches += 1\n\n if (val_err / val_batches > best_val_err):\n best_val_err = val_err / val_batches\n\n if (time.time() - start_time > time_limit):\n print(\"{}\".format(time.time() - start_time))\n break\n\n return best_val_err\n\n\ndef target(m,lr,nfilter):\n res_filename = \"res_6_0.txt\"\n hp_filename = \"hp_6_0.txt\"\n print(\"Evaluating network at: M = {}, LR = {} and NFilters = {}\".format(m,lr,nfilter))\n hp_file = open(hp_filename, 'w+', encoding=\"utf8\")\n hp_file.write(\"{:.15g}\\t{:15g}\\t{:15g}\".format(m,lr,nfilter))\n hp_file.close()\n results = []\n #while results.count == 0:\n while True:\n if os.path.isfile(res_filename):\n break\n time.sleep(100)\n res_file = open(res_filename, 'r+', encoding=\"utf8\")\n results_w = res_file.read().split()\n res_file.close()\n for w in results_w:\n results.append( float(w))\n os.remove(res_filename)\n return results[0] # we only consider best_val_acc\n# you need to write the following hooks for your custom problem\n####################################################################################################\n\ndef get_random_hyperparameter_configuration():\n\n t = np.random.uniform()\n\n return t\n\ndef run_then_return_val_loss(nepochs, hyperparameters, noiselevel, xshift= 0.0):\n #xshift # shift of the optimum in the decision space, i.e., x1 # shift of the optimum in the decision space, i.e., x1\n\n xcur = hyperparameters # hyperparameter value to be evaluated\n xopt = 0.8 # true optimum location on x-axis when infinite number of epochs\n xopt = xopt - xshift/math.sqrt(nepochs) # denoised suggestion when running for nepochs\n\n yvalue = math.pow( math.fabs(xopt - xcur), 0.5) # actual objective function = distance to the optimum\n yvalue = yvalue + 0.5/nepochs # plus additive term\n yvalue = yvalue * (1 + math.fabs(np.random.normal(0, noiselevel))) # multiplicative noise\n\n return yvalue\n\niscenario = 4\n\nif (iscenario == 1):\n for shift in [0.0,0.2,0.4,0.8]:\n stat_filename = \"fprofile_{:.1g}.txt\".format(shift) # output filename\n stat_file = open(stat_filename, 'w+')\n\n nx = 1001 # number of function evaluations / solutions\n noiselevel = 0.2 # noise level of the objective function\n for nepochs in [1, 3, 9, 27, 81]: # with different resolution / number of epochs\n for i in range(0, nx): # for different hyperparameter values\n x_i = i * 1.0 / (nx-1) # which are equispaced in [0, 1]\n y_i = run_then_return_val_loss(nepochs, x_i, noiselevel, shift) # we evaluate them\n if (i < nx-1): stat_file.write(\"{:.15g}\\t\".format(y_i)) # and save to the file\n else: stat_file.write(\"{:.15g}\\n\".format(y_i))\n stat_file.close()\n\n nruns = 100\n for irun in range(0, 100):\n stat_filename = \"randomsearch_{}_{:.1g}.txt\".format(irun, shift)\n stat_file = open(stat_filename, 'w+')\n nrandom = 100\n for i in range(nrandom):\n x_i = get_random_hyperparameter_configuration()\n y_i = run_then_return_val_loss(81, x_i, noiselevel, shift)\n if (i == 0): x_best_observed = x_i; y_best_observed = y_i\n if (y_i < y_best_observed): y_best_observed = y_i; x_best_observed = x_i\n # now compute what would be denoised loss values of the best observed solution\n # use stddev 1e-10 to set noise to ~0 similar to averaging over tons of runs\n y_best_observed_denoised = run_then_return_val_loss(81, x_best_observed, 1e-10, shift)\n y_i = run_then_return_val_loss(81, x_best_observed, y_best_observed_denoised, shift)\n stat_file.write(\"{}\\t{:.15g}\\n\".format(i, y_i))\n stat_file.close()\n\nif (iscenario == 2): \n for shift in [0.0,0.2,0.4,0.8]:\n max_iter = 81 # maximum iterations/epochs per configuration\n eta = 3 # defines downsampling rate (default=3)\n\n logeta = lambda x: math.log(x)/math.log(eta)\n s_max = int(math.floor(logeta(max_iter))) # number of unique executions of Successive Halving (minus one)\n B = (s_max+1)*max_iter # total number of iterations (without reuse) per execution of Succesive Halving (n,r)\n\n noiselevel = 0.2 # noise level of the objective function\n # Begin Finite Horizon Hyperband outlerloop. Repeat indefinetely.\n\n nruns = 1 # set it to e.g. 10 when testing hyperband against randomsearch\n for irun in range(0, 100):\n hband_results_filename = \"hyperband_{}_{:.1g}.txt\".format(irun, shift)\n hband_file = open(hband_results_filename, 'w+')\n\n x_best_observed = []\n x_best_observed_nep = 0\n\n nevals = 0 # total number of full (with max_iter epochs) evaluations used so far\n\n for s in reversed(range(s_max+1)):\n\n stat_filename = \"hband_benchmark_{}_{:.1g}.txt\".format(s, shift)\n stat_file = open(stat_filename, 'w+')\n\n n = int(math.ceil(math.floor(B/max_iter/(s+1))*eta**s)) # initial number of configurations\n r = max_iter*eta**(-s) # initial number of iterations to run configurations for\n\n # Begin Finite Horizon Successive Halving with (n,r)\n Th = [ get_random_hyperparameter_configuration() for i in range(n) ]\n for i in range(s+1):\n # Run each of the n_i configs for r_i iterations and keep best n_i/eta\n n_i = math.floor(n*eta**(-i))\n r_i = r*eta**(i)\n val_losses = [ run_then_return_val_loss(nepochs=r_i, hyperparameters=t,\n noiselevel=noiselevel, xshift=shift) for t in Th ]\n nevals = nevals + len(Th) * r_i / 81\n argsortidx = np.argsort(val_losses)\n\n if (x_best_observed == []):\n x_best_observed = Th[argsortidx[0]]\n y_best_observed = val_losses[argsortidx[0]]\n x_best_observed_nep = r_i\n # only if better AND based on >= number of epochs, the latter is optional\n if (val_losses[argsortidx[0]] < y_best_observed):# and (r_i >= x_best_observed_nep):\n x_best_observed_nep = r_i\n y_best_observed = val_losses[argsortidx[0]]\n x_best_observed = Th[argsortidx[0]]\n for j in range(0, len(Th)):\n #print(\"{:.15g}\\t{:.15g}\\t{}\\n\".format(Th[j], val_losses[j], n_i))\n stat_file.write(\"{:.15g}\\t{:.15g}\\t{}\\n\".format(Th[j], val_losses[j], r_i))\n Th = [ Th[i] for i in argsortidx[0:int( n_i/eta )] ]\n\n # suppose the current best solution w.r.t. validation loss is our recommendation\n # then let's evaluate it in noiseless settings (~= averaging over tons of runs)\n if (len(Th)):\n f_recommendation = run_then_return_val_loss(81, x_best_observed, 1e-10, shift) # 81 epochs and 1e-10 ~= zero noise\n hband_file.write(\"{:.15g}\\t{:.15g}\\n\".format(nevals, f_recommendation))\n # End Finite Horizon Successive Halving with (n,r)\n\n stat_file.close()\n hband_file.close()\n\nif (iscenario == 4):\n from multiprocessing.pool import Pool\n def get_random_hyperparameter_configurations(): \n x = np.random.rand(4)\n nfilters = 10 + int(90*x[0]) # in [10, 100]\n batch_size_train = int(pow(2.0, 4.0 + 4.0*x[1])) # in [2^4, 2^8] = [16, 256]\n M = float(x[2]) # in [0, 1]\n LR = float(pow(10.0, -2 + 1.5*x[3])) # in [10^-2, 10^-0.5] = [0.01, ~0.31]\n return [nfilters, batch_size_train, M, LR]\n\n def run_then_return_val_losses(time_limit, hyperparameters):\n nfilters, batch_size_train, M, LR = hyperparameters[0], hyperparameters[1], hyperparameters[2], hyperparameters[3]\n return main(algorithm_type=2, batch_size_train=batch_size_train, LR=LR, M=M, nfilters=nfilters, time_limit=time_limit)\n\n #force lasagne and theano to compile everything needed\n main(ntrain=10, nvalid=10, batch_size_train=5, batch_size_valid=5, num_epochs=1, nfilters=1, time_limit=1)\n #pool = Pool(4)\n\n\n #solutions_filename = \"rsearch_solutions_{}.txt\".format(iscenario)\n #solutions_file = open(solutions_filename, 'w+')\n \n #start_time = time.time() \n #Th = [ get_random_hyperparameter_configurations() for i in range(100) ]\n #val_losses = [ run_then_return_val_losses(60, t) for t in Th ] \n #for t in Th: solutions_file.write(\"{:.15g}\\t{:.15g}\\t{:.15g}\\t{:.15g}\\t{:.15g}\\n\".format(\n # t[0], t[1], t[2], t[3], run_then_return_val_losses(60, t) ))\n \n #print(\"randomsearch_telapsed:\\t{}\".format(time.time() - start_time))\n #solutions_file.close()\n\n\n\n\n \n solutions_filename = \"hband_solutions_{}.txt\".format(iscenario)\n solutions_file = open(solutions_filename, 'w+')\n\n max_iter = 60 # maximum iterations/epochs per configuration\n eta = 2 # defines downsampling rate (default=3)\n logeta = lambda x: math.log(x)/math.log(eta)\n s_max = int(math.floor(logeta(max_iter))) # number of unique executions of Successive Halving (minus one)\n B = (s_max+1)*max_iter # total number of iterations (without reuse) per execution of Succesive Halving (n,r)\n \n start_time = time.time() \n x_best_observed = []\n x_best_observed_nep = 0\n\n for s in reversed(range(s_max+1)):\n n = int(math.ceil(math.floor(B/max_iter/(s+1))*eta**s)) # initial number of configurations\n r = max_iter*eta**(-s) # initial number of iterations to run configurations for\n \n print(\"###s:{} \\tn: {}\\tr: {}:\".format(solutions_file, n, r))\n # Begin Finite Horizon Successive Halving with (n,r)\n Th = [ get_random_hyperparameter_configurations() for i in range(n) ]\n for i in range(s+1):\n # Run each of the n_i configs for r_i iterations and keep best n_i/eta\n n_i = math.floor(n*eta**(-i))\n r_i = r*eta**(i)\n print(\"#n_i: {}\\tr_i: {}:\".format(n_i, r_i))\n ########################################################################################################\n #async_val_losses = [ pool.apply_async(run_then_return_val_losses, (i, r_i, t)) for i, t in enumerate(Th) ]\n #ret_async_val_losses = [ async_val_loss.get() for async_val_loss in async_val_losses ]\n ########################################################################################################\n #val_losses = ret_async_val_losses.sort(key=lambda tup: tup[0])[1,:]\n \n #val_losses = pool.map(run_then_return_val_losses, [ [i,r_i,t] for i, t in enumerate(Th) ])\n val_losses = [ run_then_return_val_losses(r_i, t) for t in Th ]\n argsortidx = np.argsort(val_losses)\n\n if (x_best_observed == []):\n x_best_observed = Th[argsortidx[0]]\n y_best_observed = val_losses[argsortidx[0]]\n x_best_observed_nep = r_i\n # only if better AND based on >= number of epochs\n if (val_losses[argsortidx[0]] < y_best_observed):# and r_i >= x_best_observed_nep):\n x_best_observed_nep = r_i\n y_best_observed = val_losses[argsortidx[0]]\n x_best_observed = Th[argsortidx[0]]\n\n Th = [ Th[i] for i in argsortidx[0:int( n_i/eta )] ]\n\n solutions_file.write(\"{:.15g}\\t{:.15g}\\t{:.15g}\\t{:.15g}\\t{:.15g}\\n\".format(\n x_best_observed[0], x_best_observed[1], x_best_observed[2], x_best_observed[3],\n run_then_return_val_losses(max_iter, x_best_observed)\n ))\n # End Finite Horizon Successive Halving with (n,r)\n print(\"hyperband_telapsed:\\t{}\".format(time.time() - start_time))\n solutions_file.close()","sub_path":"Assignment4/Assignment4.py","file_name":"Assignment4.py","file_ext":"py","file_size_in_byte":21289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"259219119","text":"from matplotlib import pyplot\nimport numpy as np\n#随机生成K个质心\ndef randomCenter(pointers,k):\n indexs = np.random.random_integers(0,len(pointers)-1,k)\n centers = []\n for index in indexs:\n centers.append(pointers[index])\n return centers\n#绘制最终的结果\ndef drawPointersAndCenters(pointers,centers):\n i = 0\n for classs in pointers:\n cs = np.zeros(4,dtype=np.int8)\n cs[i]=1\n cs[3]=1\n #将list转为numpy中的array,方便切片\n xy = np.array(classs)\n if(len(xy)>0):\n pyplot.scatter(xy[:,0],xy[:,1],c=cs)\n i += 1\n\n centers = np.array(centers)\n pyplot.scatter(centers[:, 0], centers[:, 1], c=[0,0,0],linewidths = 20)\n pyplot.show()\n\n\n#计算两个向量的距离,用的是欧几里得距离\ndef distEclud(vecA, vecB):\n # return np.sqrt(np.sum(np.power(vecA - vecB, 2)))\n return np.sum(np.abs(vecA - vecB))\n\n#求这一组数据坐标的平均值,也就是新的质心\ndef getMean(data):\n xMean = np.mean(data[:,0])\n yMean = np.mean(data[:,1])\n return [xMean,yMean]\n\ndef KMeans(pointers,centers):\n diffAllNew = 100\n diffAllOld = 0\n afterClassfy = []\n while(abs(diffAllNew - diffAllOld)!=0):\n #更新diffAllOld为diffAllNEw\n diffAllOld = diffAllNew\n #先根据质心,对所有的数据进行分类\n afterClassfy = [[] for a in range(len(centers))]\n for pointer in pointers:\n dis = []\n for center in centers:\n dis.append(distEclud(pointer,center))\n minDis = min(dis)\n i=0\n for d in dis:\n if(minDis == d):\n break\n else:\n i += 1\n afterClassfy[i].append(pointer)\n afterClassfy = np.array(afterClassfy)\n\n #计算所有点到其中心距离的总的和\n diffAllNews = [[] for a in range(len(centers))]\n i=0\n for classs in afterClassfy:\n for center in centers:\n if len(classs) >0:\n diffAllNews[i] += distEclud(classs,center)\n i+=1\n diffAllNew = sum(diffAllNews)\n\n #更新质心的位置\n i=0\n for classs in afterClassfy:\n classs = np.array(classs)\n if len(classs) > 0 :\n centers[i] = getMean(classs)\n i += 1\n\n drawPointersAndCenters(afterClassfy,centers)\n print(afterClassfy)\n\n\n\ndef randonGenerate15Pointer():\n ponters =[np.random.random_integers(0,10,2) for a in range(100)]\n np.save(\"data\",ponters)\n print(ponters)\ndef loadData(fileName):\n return np.load(fileName)\n\ndef test():\n # randonGenerate15Pointer()\n pointers = loadData(\"data.npy\")\n centers = randomCenter(pointers,3)\n print(pointers)\n print(centers)\n KMeans(pointers, centers)\n\ntest()\n\n\n","sub_path":"cluster_classify/k-means_cluster.py","file_name":"k-means_cluster.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"72238542","text":"from Watershed import *\nimport os\n\n#image_name = \"2012-07-05_00-30-00.png\"\nfor image_name in os.listdir('.'):\n if image_name[0] == \"2\":\n shed = Watershed(\n data_image = str(image_name),\n binary_or_gray_or_color = \"color\",\n size_for_calculations = 128,\n sigma = 1,\n gradient_threshold_as_fraction = 0.08,\n level_decimation_factor = 8,\n padding = 0,\n )\n shed.extract_data_pixels()\n print(\"Displaying the original image:\")\n shed.display_data_image()\n print(\"Calculating the gradient image\")\n shed.compute_gradient_image()\n print(\"Computing Z level sets for the gradient image\")\n shed.compute_Z_level_sets_for_gradient_image()\n print(\"Propagating influences:\")\n shed.propagate_influence_zones_from_bottom_to_top_of_Z_levels()\n shed.display_watershed()\n shed.display_watershed_in_color()\n # Extract up to 30 blob contours and, at the same time, only accept\n # contours whose length is GREATER THAN 20 pixels:\n #contours = shed.extract_watershed_contours_with_random_sampling(50, 50)\n\n # You can also call the following method for extracting the watershed\n # contours\n contours = shed.extract_watershed_contours_separated()\n\n # Uncomment the following lines if you want to print out the contours:\n #for contour in contours:\n # print(\"\\n\\ncontour: \", contour)\n # print(\"contour length: \", len(contour))\n\n shed.display_watershed_contours_in_color()\n","sub_path":"scripts/test_watershed.py","file_name":"test_watershed.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"116865572","text":"#!/home/wborn/anaconda3/bin/python3.6\nimport numpy as np\nimport keras\nfrom keras import backend as K\nfrom keras.models import Sequential\nfrom keras.layers import Activation\nfrom keras.layers.core import Dense, Flatten, Dropout\nfrom keras.optimizers import Adam\nfrom keras.metrics import categorical_crossentropy\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.convolutional import *\nfrom keras.models import model_from_json\nfrom matplotlib import pyplot as plt\nfrom sklearn.metrics import confusion_matrix\nimport itertools\nimport matplotlib.pyplot as plt\n\ndef train(train_batches, valid_batches, save_name, epochs, learning_rate, train_image_num, train_batch_size, valid_image_num, val_batch_size, verbosity):\n vgg16_model = keras.applications.vgg16.VGG16(include_top=False, input_shape=(50,50,3),classes=3,pooling='max')\n\n #print(vgg16_model.summary())\n\n model = Sequential()\n for layer in vgg16_model.layers:\n model.add(layer)\n\n model.layers.pop()\n\n\n for layer in model.layers:\n layer.trainable = False\n\n model.add(Dense(3, activation='softmax'))\n print(model.summary())\n\n\n model.compile(Adam(lr=learning_rate),loss='categorical_crossentropy', metrics=['accuracy'])\n\n model.fit_generator(train_batches,steps_per_epoch=int(train_image_num/train_batch_size), validation_data = valid_batches, validation_steps=int(valid_image_num/val_batch_size), epochs=epochs, verbose=verbosity)\n\n # serialize model to JSON\n model_json = model.to_json()\n with open(save_name+\".json\", \"w\") as json_file:\n json_file.write(model_json)\n # serialize weights to HDF5\n model.save_weights(save_name+\".h5\")\n print(\"Saved model to disk\")\n\n return model\n\n#plots images w/ labels\ndef plots(ims, figsize=(12,6), rows=1, interp=False, titles=None):\n if type(ims[0]) is np.ndarray:\n ims = np.array(ims).astype(np.uint8)\n if (ims.shape[-1] !=3):\n ims = ims.transpose((0,2,3,1))\n f = plt.figure(figsize=figsize)\n cols = len(ims)//rows if len(ims) % 2 == 0 else len(ims)//rows +1\n for i in range(len(ims)):\n sp = f.add_subplot(rows,cols,i+1)\n sp.axis('Off')\n if titles is not None:\n sp.set_title(titles[i],fontsize=16)\n plt.imshow(ims[i],interpolation=None if interp else 'none')\n\ndef plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):\n plt.imshow(cm,interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks= np.arrange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print(\"Confusion matrix, without normalization\")\n\n print(cm)\n\n thresh = cm.max() / 2\n for i,j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j,i,cm[i,j], horizontalalignment=\"center\", color=\"white\" if cm[i,j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\n plt.show()\n\ngui = input(\"gui? [0/1] >\")\nepochs= int(input(\"epochs? >\"))\nlearning_rate= float(input(\"learning_rate? >\"))\ntrain_image_num= int(input(\"number of train images? >\"))\ntrain_batch_size= int(input(\"test batch_size? >\"))\nvalid_image_num= int(input(\"number of validation images? >\"))\nval_batch_size= int(input(\"valid batch_size? >\"))\ntest_batch_size= int(input(\"number of test images? >\"))\n\ntrain_path = 'set/train'\nvalid_path = 'set/valid'\ntest_path = 'set/test'\n\ntrain_batches = ImageDataGenerator().flow_from_directory(train_path,target_size=(50,50), classes=['l','s','r'], batch_size=train_batch_size)\nvalid_batches = ImageDataGenerator().flow_from_directory(valid_path,target_size=(50,50), classes=['l','s','r'], batch_size=val_batch_size)\ntest_batches = ImageDataGenerator().flow_from_directory(test_path,target_size=(50,50), classes=['l','s','r'], batch_size=test_batch_size)\n\ntest_imgs,test_labels=next(test_batches)\n\nif gui==1:\n plots(imgs, titles=labels)\n plt.show()\n\nmodel1= train(train_batches,valid_batches,\"model\",epochs,learning_rate,train_image_num,train_batch_size,valid_image_num,val_batch_size,1)\n\npredictions = model1.predict_classes(test_imgs, batch_size=test_batch_size,verbose=1)\n\ncm = confusion_matrix(test_labels,predictions)\n\ncm_plot_labels = ['left', 'straight', 'right']\nplot_confusion_matrix(cm,cm_plot_labels,title='Model Confusion Matrix')\n\n\n\n\nprint(\"done\")\n","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"10095666","text":"'''\nSolves the 1-d poisson equation as a function of a collective variable bin. Uses the bin_struct files as input\nfor the solution. Makes a matplotlib plot of the potential distribution as a funciton of collective variable bins.\n'''\nimport pandas as pd\nimport numpy as np\nfrom scipy.sparse import diags\nbase_height=16.272 #first layer of atoms\n\nbs=200\nbin_size=1.08806*(30./bs) #based on 30 slices\n\nsurface=int(base_height/bin_size)\n\nslice_size=12.648 #angstroms\n\ne0 = 0.005527 # in e/V*Angstrom\n\ndf=pd.read_csv('bin_struct',delim_whitespace=True)\n\ndf['z']=df['z']-base_height\n\ndf['z']=df['z'].map(lambda x : np.around(x,decimals=1))\t\n\ndf[df.columns[0:-2]]=df[df.columns[0:-2]]*slice_size**2/e0\n\n#bin by truncated values\ng=df.groupby('z').mean()\n\n\n#\npotentials=np.zeros([len(g),bs])\n\nA=np.zeros([bs,bs])\n\ndiagonals=[np.zeros(bs)+2,np.zeros(bs-1)-1,np.zeros(bs-1)-1]\nA=diags(diagonals,[0,-1,1]).toarray()\n\nfor x in range(len(g)):\n\tpotentials[x]=np.linalg.solve(A,g.values[x])*bin_size**2\n\n\nfrom matplotlib import pyplot as plt\n\nplt.plot(range(bs),potentials[50],'r')\nplt.plot(range(bs),potentials[9],'b')\nplt.plot(range(bs),potentials[18],'g')\nplt.plot(np.zeros(10)+surface,np.linspace(potentials[0].min(),potentials[0].max(),10))\n\nplt.show()\n\n# now we solve the poisson equation for each frame\n\n'''\ndef solveP (x):\n\n\treturn \n'''\n\n","sub_path":"Poisson_solver.py","file_name":"Poisson_solver.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"441397862","text":"import matplotlib.pyplot as plt\nfrom dolfin import MPI, project\n\nclass DetectorSet(list):\n ''' A class that can hold a set of Detectors objects and operate on them '''\n def __init__(self, title, *args, **kwargs):\n self.title = title\n super(DetectorSet, self).__init__(*args, **kwargs)\n\n def update(self, time):\n [d.update(time) for d in self]\n\n def save_plot(self):\n if MPI.process_number() == 0:\n plt.clf()\n plt.title(self.title)\n [d.plot() for d in self]\n plt.legend()\n plt.savefig('_'.join(self.title.lower().split()) + \".png\")\n plt.clf()\n\nclass Detector(object):\n ''' A class that stores the function values of a series of timesteps '''\n def __init__(self, function, point, label, functionspace = None):\n self.label = label\n self.function = function\n self.point = point\n self.values = []\n self.times = []\n self.functionspace = functionspace\n \n def update(self, time):\n self.times.append(time)\n try: \n # Gather the ghost values before evaluating, see https://bugs.launchpad.net/dolfin/+bug/914171\n if self.functionspace:\n f = project(self.function, self.functionspace)\n f.gather()\n value = f(self.point)\n else:\n value = self.function(self.point)\n # Catch RuntimeError that is raised on CPUs that do not own the evaluation cell \n except RuntimeError:\n value = -1000000.\n pass\n value = MPI.max(value)\n\n self.values.append(value)\n\n\n def plot(self):\n plt.plot(self.times, self.values, label=self.label)\n","sub_path":"wetting_and_drying/thacker/detectors.py","file_name":"detectors.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"107325191","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Dec 6 08:32:53 2016\r\n\r\n@author: vemurI\r\n\"\"\"\r\n\r\nimport numpy as np # linear algebra\r\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\r\nimport xgboost as xgb\r\n\r\n\r\ntrain = pd.read_csv('C:/Users/vemurI/Desktop/Grupo-Bimbo/train.csv',header=0,dtype = {'Semana': 'int8',\r\n 'Agencia_ID' : 'int16',\r\n 'Canal_ID' : 'int8',\r\n 'Ruta_SAK' : 'int16',\r\n 'Cliente_ID' : 'int32',\r\n 'Producto_ID': 'int32',\r\n 'Venta_uni_hoy': 'int32',\r\n 'Venta_hoy': 'float16',\r\n 'Dev_uni_proxima':'int32',\r\n 'Dev_proxima':'float16',\r\n 'Demanda_uni_equil':'int32'}) \r\n\r\ntest = pd.read_csv('C:/Users/vemurI/Desktop/Grupo-Bimbo/test.csv',header = 0, dtype = {'id':'int16',\r\n 'Semana': 'int8',\r\n 'Agencia_ID' : 'int16',\r\n 'Canal_ID' : 'int8',\r\n 'Ruta_SAK' : 'int16',\r\n 'Cliente_ID' : 'int32',\r\n 'Producto_ID': 'int16'})\r\n\r\n# Create log demand column\r\ntrain['Demanda_uni_equil'] = np.log1p(train['Demanda_uni_equil'])\r\ndata = train[['Semana','Agencia_ID','Canal_ID','Ruta_SAK','Cliente_ID','Producto_ID','Venta_uni_hoy','Dev_uni_proxima','Demanda_uni_equil']]\r\ndel train\r\n\r\n#Inspired from Kaggler.\r\n\r\n# Average demand of the products at each client. Can get clue of overall size of client which can be decisive?\r\ndata_pc = data.groupby(['Cliente_ID','Producto_ID'],as_index = False)['Demanda_uni_equil'].mean()\r\ndata_pc.rename(columns={'Demanda_uni_equil': 'mean_pc'}, inplace=True)\r\n\r\n#Average demand of every Route\r\ndata = data.merge(data_pc,how='left',left_on=['Cliente_ID','Producto_ID'],\r\n right_on=['Cliente_ID','Producto_ID'],\r\n sort=True,copy=False)\r\n\r\nids = test['id']\r\ntest = test.drop(['id'],axis = 1)\r\n\r\n#Split the data into train set and training evaluation set\r\nselcols = ['Semana', 'Agencia_ID', 'Canal_ID', 'Ruta_SAK', 'Cliente_ID', 'Producto_ID', 'mean_pc' ]\r\ntrain_x = data[data['Semana'] <= 8][selcols]\r\ntarget_y = data[data['Semana'] <= 8]['Demanda_uni_equil']\r\n\r\n# Week 9 is training error evaluation set\r\neval_train_x = data[data['Semana'] == 9][selcols]\r\neval_target_y = data[data['Semana'] == 9 ]['Demanda_uni_equil']\r\n\r\nxlf = xgb.XGBRegressor(max_depth=4, \r\n learning_rate=0.20, \r\n n_estimators=20, \r\n silent=True, \r\n objective='reg:linear', \r\n nthread=3, \r\n seed=7,\r\n subsample=0.85, \r\n colsample_bytree=0.7, \r\n missing=None)\r\n\r\nxlf.fit(train_x,target_y,eval_metric='rmse',eval_set=[(eval_train_x,eval_target_y)],early_stopping_rounds=50)\r\n\r\npreds = xlf.predict(test)\r\npred = np.exp(preds)-1\r\n\r\nsubmission = pd.DataFrame({ 'Demanda_uni_equil': pred,'id':ids})\r\ntest.to_csv('C:/Users/vemurI/Desktop/Grupo-Bimbo/Pred.csv', index=False)","sub_path":"GrupBimbo.py","file_name":"GrupBimbo.py","file_ext":"py","file_size_in_byte":3620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"23614578","text":"# built in libraries\nimport platform\nimport string\nimport sys\nimport os\n\n# tamcolors libraries\nfrom .tam_buffer import TAMBuffer\nfrom . import io_tam\nfrom tamcolors.tam_c import _uni_tam as io\n\n\n\"\"\"\nUniIO\ndraws out to Unix terminal\ngets ASCII key input from linux terminal\ncolor mode 2\ncolor mode 16\n\"\"\"\n\n\nclass UniIOError(Exception):\n pass\n\n\nclass UniIO(io_tam.SingletonIO):\n def __init__(self):\n \"\"\"\n info: makes UniIO object\n \"\"\"\n super().__init__()\n self.__buffer = TAMBuffer(0, 0, \" \", 1, 1)\n self.__unix_keys = self.get_key_dict()\n\n self.__foreground_color_map = {-2: \"39\",\n -1: \"39\",\n 0: \"38;5;232\",\n 1: \"38;5;20\",\n 2: \"38;5;34\",\n 3: \"38;5;75\",\n 4: \"38;5;1\",\n 5: \"38;5;90\",\n 6: \"38;5;3\",\n 7: \"38;5;252\",\n 8: \"38;5;243\",\n 9: \"38;5;33\",\n 10: \"38;5;76\",\n 11: \"38;5;117\",\n 12: \"38;5;161\",\n 13: \"38;5;126\",\n 14: \"38;5;229\",\n 15: \"38;5;15\"}\n\n self.__background_color_map = {-2: \"49\",\n -1: \"49\",\n 0: \"48;5;232\",\n 1: \"48;5;20\",\n 2: \"48;5;34\",\n 3: \"48;5;75\",\n 4: \"48;5;1\",\n 5: \"48;5;90\",\n 6: \"48;5;3\",\n 7: \"48;5;252\",\n 8: \"48;5;243\",\n 9: \"48;5;33\",\n 10: \"48;5;76\",\n 11: \"48;5;117\",\n 12: \"48;5;161\",\n 13: \"48;5;126\",\n 14: \"48;5;229\",\n 15: \"48;5;15\"}\n\n @classmethod\n def able_to_execute(cls):\n \"\"\"\n info: will see if environment supported by UniIO\n :return: bool\n \"\"\"\n if platform.system() in (\"Darwin\", \"Linux\"):\n if os.system(\"test -t 0 -a -t 1 -a -t 2\") == 0:\n return io is not None\n return False\n\n def draw(self, tam_buffer):\n \"\"\"\n info: will draw tam buffer to terminal\n :param tam_buffer: TAMBuffer\n :return:\n \"\"\"\n\n dimension = io._get_dimension()\n if self.__buffer.get_dimensions() != dimension:\n self.clear()\n self._show_console_cursor(False)\n io._enable_get_key()\n self.__buffer.set_dimensions_and_clear(*dimension)\n\n super().draw(tam_buffer)\n\n def _draw_2(self, tam_buffer):\n \"\"\"\n info: will draw tam buffer to terminal in mode 2\n :param tam_buffer: TAMBuffer\n :return:\n \"\"\"\n\n # checks if buffer needs to be updated\n if \" \" != self.__buffer.get_defaults()[0] or self.__buffer.get_defaults()[1:] != tam_buffer.get_defaults()[1:]:\n # buffer defaults changed\n self.__buffer.set_defaults_and_clear(\" \", *tam_buffer.get_defaults()[1:])\n\n # draw onto LinIO buffer\n self._draw_onto(self.__buffer, tam_buffer)\n\n color = self._get_lin_tam_color(*self.__buffer.get_defaults()[1:])\n output = \"\".join(self.__buffer.get_raw_buffers()[0])\n sys.stdout.write(\"\\u001b[1;1H\\u001b[{0};{1}m{2}\\u001b[0\".format(*color, output))\n sys.stdout.flush()\n\n def _draw_16(self, tam_buffer):\n \"\"\"\n info: will draw tam buffer to terminal in mode 16\n :param tam_buffer: TAMBuffer\n :return:\n \"\"\"\n # checks if buffer needs to be updated\n if \" \" != self.__buffer.get_defaults()[0] or self.__buffer.get_defaults()[1:] != tam_buffer.get_defaults()[1:]:\n # buffer defaults changed\n self.__buffer.set_defaults_and_clear(\" \", *tam_buffer.get_defaults()[1:])\n\n # draw onto LinIO buffer\n self._draw_onto(self.__buffer, tam_buffer)\n\n # make output string\n output = [\"\\u001b[1;1H\"]\n foreground, background = None, None\n char_buffer, foreground_buffer, background_buffer = self.__buffer.get_raw_buffers()\n for spot in range(len(char_buffer)):\n if foreground is None:\n foreground = foreground_buffer[spot]\n background = background_buffer[spot]\n output.append(\"\\u001b[{0};{1}m\".format(*self._get_lin_tam_color(foreground, background)))\n output.append(char_buffer[spot])\n elif foreground == foreground_buffer[spot] and background == background_buffer[spot]:\n output.append(char_buffer[spot])\n else:\n foreground = foreground_buffer[spot]\n background = background_buffer[spot]\n output.append(\"\\u001b[{0};{1}m\".format(*self._get_lin_tam_color(foreground, background)))\n output.append(char_buffer[spot])\n\n sys.stdout.write(\"\".join(output) + \"\\u001b[0\")\n sys.stdout.flush()\n\n def start(self):\n \"\"\"\n info: will setup terminal to be used\n :return:\n \"\"\"\n self.clear()\n self._show_console_cursor(False)\n io._enable_get_key()\n\n def done(self):\n \"\"\"\n info: will reset terminal\n :return:\n \"\"\"\n self.clear()\n self._show_console_cursor(True)\n io._disable_get_key()\n os.system(\"clear\")\n\n def get_key(self):\n \"\"\"\n info: will get single key input or return False\n :return: str or False\n \"\"\"\n key_bytes = []\n key_byte = io._get_key()\n while key_byte != -1:\n key_bytes.append(key_byte)\n key_byte = io._get_key()\n\n if len(key_bytes) != 0:\n return self.__unix_keys.get(\";\".join([str(key_byte) for key_byte in key_bytes]), False)\n\n return False\n\n def get_dimensions(self):\n \"\"\"\n info: will get teh terminal dimensions\n :return: (int, int)\n \"\"\"\n return io._get_dimension()\n\n @staticmethod\n def get_key_dict():\n \"\"\"\n info: makes a dict mapping key codes to key\n :return: dict\n \"\"\"\n normal_key = string.digits + string.ascii_letters + \"`-=[]\\\\;',./~!@#$%^&*()_+{}|:\\\"<>?\"\n linux_keys = {str(ord(key)): (key, \"NORMAL\") for key in normal_key}\n\n code_27_91 = [[65, \"UP\"], [66, \"DOWN\"], [68, \"LEFT\"], [67, \"RIGHT\"]]\n\n for code, key in code_27_91:\n linux_keys[\"27;91;{0}\".format(code)] = (key, \"SPECIAL\")\n\n for f_key in range(0, 4):\n linux_keys[\"27;79;{0}\".format(f_key + 80)] = (\"F{0}\".format(f_key + 1), \"SPECIAL\")\n linux_keys[\"27;91;49;59;50;{0}\".format(f_key + 80)] = (\"F{0}_SHIFT\".format(f_key + 1), \"SPECIAL\")\n\n linux_keys[\"27;91;49;53;126\"] = (\"F5\", \"SPECIAL\")\n linux_keys[\"27;91;49;53;59;50;126\"] = (\"F5_SHIFT\", \"SPECIAL\")\n\n linux_keys[\"27;91;49;55;126\"] = (\"F6\", \"SPECIAL\")\n linux_keys[\"27;91;49;55;59;50;126\"] = (\"F6_SHIFT\", \"SPECIAL\")\n\n linux_keys[\"27;91;49;56;126\"] = (\"F7\", \"SPECIAL\")\n linux_keys[\"27;91;49;56;59;50;126\"] = (\"F7_SHIFT\", \"SPECIAL\")\n\n linux_keys[\"27;91;49;57;126\"] = (\"F8\", \"SPECIAL\")\n linux_keys[\"27;91;49;57;59;50;126\"] = (\"F8_SHIFT\", \"SPECIAL\")\n\n linux_keys[\"27;91;50;48;126\"] = (\"F9\", \"SPECIAL\")\n linux_keys[\"27;91;50;48;59;50;126\"] = (\"F9_SHIFT\", \"SPECIAL\")\n\n linux_keys[\"27;91;50;52;126\"] = (\"F12\", \"SPECIAL\")\n linux_keys[\"27;91;50;52;59;50;126\"] = (\"F12_SHIFT\", \"SPECIAL\")\n\n linux_keys[\"27;91;51;126\"] = (\"DELETE\", \"SPECIAL\")\n\n linux_keys[\"9\"] = (\"\\t\", \"WHITESPACE\")\n linux_keys[\"10\"] = (\"\\n\", \"WHITESPACE\")\n linux_keys[\"32\"] = (\" \", \"WHITESPACE\")\n\n linux_keys[\"127\"] = (\"BACKSPACE\", \"SPECIAL\")\n linux_keys[\"27\"] = (\"ESCAPE\", \"SPECIAL\")\n\n return linux_keys\n\n @staticmethod\n def _show_console_cursor(show_flag):\n \"\"\"\n info: will show or hide the cursor\n :param show_flag: bool:\n :return:\n \"\"\"\n if platform.system() != \"Darwin\":\n if show_flag:\n os.system(\"setterm -cursor on\")\n else:\n os.system(\"setterm -cursor off\")\n\n def _get_lin_tam_color(self, foreground_color, background_color):\n \"\"\"\n info: will get the ANI color code\n :param foreground_color: int\n :param background_color: int\n :return: (str, sr)\n \"\"\"\n return self.__foreground_color_map.get(foreground_color),\\\n self.__background_color_map.get(background_color)\n\n def printc(self, output, color, flush, stderr):\n \"\"\"\n info: will print out user output with color\n :param output: str\n :param color: tuple: (int, int)\n :param flush: boolean\n :param stderr: boolean\n :return: None\n \"\"\"\n output_str = \"\\u001b[{0};{1}m{2}\\u001b[0m\".format(*self._get_lin_tam_color(*color), output)\n self._write_to_output_stream(output_str, flush, stderr)\n\n def inputc(self, output, color):\n \"\"\"\n info: will get user input with color\n :param output: str\n :param color: tuple: (int, int)\n :return: str\n \"\"\"\n output_str = \"\\u001b[{0};{1}m{2}\".format(*self._get_lin_tam_color(*color), output)\n ret = input(output_str)\n sys.stdout.write(\"\\u001b[0m\")\n sys.stdout.flush()\n return ret\n\n def clear(self):\n \"\"\"\n info: will clear the screen. Note that it will also reset the terminal\n :return:\n \"\"\"\n os.system(\"tput reset\")\n","sub_path":"tamcolors/tam_io/uni_tam.py","file_name":"uni_tam.py","file_ext":"py","file_size_in_byte":10302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"38477903","text":"# Inspired by: https://github.com/walkr/nanoservice/tree/master/benchmarks\n\nimport time\nfrom multiprocessing import Process\n\nimport nanomsg\nfrom omnomnom.models import Executable\nfrom omnomnom.generics.micro import Fruit\n\n\nclass MultiplyExecutable(Executable):\n\n def __call__(self, x, y, **kwargs):\n return x + y\n\n\nclass JsonTestService(Fruit):\n multiply = MultiplyExecutable()\n\n\nclass JsonPubTestService(Fruit):\n socket_type = nanomsg.PUB\n multiply = MultiplyExecutable()\n\n\nclass Benchmark(object):\n\n def __init__(self, name, service_class, message_num, address, task, client_class):\n self.name = name\n self.service_class = service_class\n self.client_class = client_class\n self.message_num = message_num\n self.address = address\n self.task = task\n\n def handle_service(self, service):\n service.handle()\n\n def handle_client(self, client, task, args):\n res = client.get(task, args=args)\n assert not res['error']\n\n def run(self):\n print('')\n print(self.name)\n print('Dealing with {0} messages'.format(self.message_num))\n print('-----------------------------')\n\n service_process = Process(\n target=self.start_service, args=(self.address, self.message_num)\n )\n service_process.start()\n time.sleep(0.1)\n\n with self.client_class(address=self.address) as client:\n self.execute_benchmark(client, self.message_num, self.task)\n\n time.sleep(0.2)\n service_process.terminate()\n\n def execute_benchmark(self, client, message_num, task):\n\n pairs = [\n (x, x+1) for x in range(message_num)\n ]\n\n started = time.time()\n for pair in pairs:\n self.handle_client(client, task, pair)\n duration = time.time() - started\n print('Client stats:')\n self.print_stats(message_num, duration)\n\n def start_service(self, address, n):\n service = self.service_class(address=address)\n started = time.time()\n\n for _ in range(n):\n self.handle_service(service)\n\n duration = time.time() - started\n\n time.sleep(0.1)\n print('Service stats:')\n self.print_stats(n, duration)\n return\n\n def print_stats(self, n, duration):\n pairs = [\n ('Total messages', n),\n ('Total duration (s)', duration),\n ('Throughput (msg/s)', n/duration)\n ]\n for pair in pairs:\n label, value = pair\n print(' * {:<25}: {:10,.2f}'.format(label, value))\n\n\nclass RawBenchmark(Benchmark):\n\n def handle_service(self, service):\n data = service.socket.recv()\n service.socket.send(data)\n\n def handle_client(self, client, task, args):\n request = 'data'\n client.socket.send(request)\n response = client.socket.recv()\n assert request == response","sub_path":"examples/benchmarks/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"473592227","text":"\n\n#calss header\nclass _TOSS():\n\tdef __init__(self,): \n\t\tself.name = \"TOSS\"\n\t\tself.definitions = [u'a sudden quick movement: ', u'an act of throwing a coin in the air and guessing which side will land facing upward as a way of deciding something', u'to guess correctly/wrongly which side of a coin will be facing up when it lands on the ground after being thrown', u'an act of throwing something in a careless or relaxed way']\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/_toss.py","file_name":"_toss.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"40325771","text":"from tkinter import HORIZONTAL\nfrom tkinter.ttk import Progressbar \n\n\ndef Progress(root, **options):\n\n progress = Progressbar(\n root, \n orient = HORIZONTAL, \n length = 100, \n mode='determinate'\n )\n\n props = {\n 'value': 20\n }\n\n props.update(**options)\n\n progress.config(props)\n progress.pack()","sub_path":"src/Progress/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"102174446","text":"#!/usr/bin/env python3\n#coding=utf-8\n# Author : faner\n# Email : soul.seule@gmail.com\n\nimport os\nfrom BookCraeler.Search import Search\nfrom BookCraeler.Search import Get_Table\nfrom BookCraeler.Search import Get_Search_One\nfrom BookCraeler.Chapter import GetChapters\n\n\ndef main():\n if os.sep == '/':\n clean = 'clear'\n else:\n clean = 'cls'\n\n os.system(clean) # 清除屏幕\n os.system(r'echo \"\\033[?25l\"') # 隐藏光标 \n \n Bar = ['[ Home ]','','','']\n\n Print_Bar = \"\\n\" + \"%s>%s>%s>%s\"\n\n Print_Help = \"\\n\\tNumber -> Enter recommendation. \\\n \\n\\t s -> Enter Serach. \\\n \\n\\t q -> Enter exit.\"\n\n while True:\n \n while True:\n\n Default_Page = Get_Table('道君',0)\n os.system(clean)\n print(Default_Page)\n print(Print_Help)\n print(Print_Bar % (Bar[0],Bar[1],Bar[2],Bar[3]),end = '')\n cmd = input()\n if cmd.isdigit():\n Choose = Get_Search_One('道君',int(cmd))\n GetChapters(Choose[5])\n elif cmd == 's':\n Search()\n elif cmd == 'q':\n os.system(clean)\n os.system(r'echo \"\\033[?25h\"')\n exit()\n\n\nif __name__ == '__main__':\n\n main()\n","sub_path":"Setup.py","file_name":"Setup.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"346395040","text":"def swap(a,i,j):\n a[i],a[j] = a[j],a[i]\n\nimport random\n\ndef qsort(a,low=0,high=-1):\n if high == -1:\n high = len(a) -1\n if low < high:\n swap(a,low, random.randint(low,high))\n m = low\n for j in range(low+1,high+1):\n if a[j] < a[low]:\n m += 1\n swap(a,m,j)\n # low < i <= m : a[i] < a[low]\n # i > m : a[i] >= a[low]\n swap(a,low,m)\n # low <= i < m : a[i] < a[m]\n # i > m : a[i] >= a[m]\n qsort(a,low,m-1)\n qsort(a,m+1,high)\n\ndef isSorted(a):\n i = 0;\n while i < len(a)-1 and a[i] <= a[i+1]:\n i += 1\n\n return i == len(a)-1\n\nif __name__ == '__main__':\n ia = [45,65,34,82,30,22]\n print(ia)\n qsort(ia)\n print(ia)\n\n dd = [45.0,65.0,34.0,82.0,30.0,22.0]\n print(dd)\n qsort(dd)\n print(dd)\n\n# import random\n\n a = [0]*1000\n for i in range(1000):\n a[i] = random.randint(0,10000)\n print(\"a gegenereerd\")\n print(a[500:510])\n b = list(a)\n\n import timeit\n timer = timeit.default_timer\n\n t1 = timer()\n qsort(a)\n print(a[500:510])\n t2 = timer()\n print(t2-t1)\n print(isSorted(a))\n\n b.sort()\n print(a == b)\n\n","sub_path":"ALDS_Python/12_quicksort.py","file_name":"12_quicksort.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"156815501","text":"# -*- coding: utf-8 -*-\n\nimport datetime as dt\nimport os\n\ntimestart = dt.datetime(2018,1,5,0,0,0)\n\n\nfolder = os.path.dirname(os.path.abspath(\"__file__\")) + \"\\\\Raw_Data\"\nrawtext_csvfile_reddit = folder + \"\\\\rawtext_reddit.csv\"\nrawtext_csvfile_twitter = folder + \"\\\\rawtext_twitter.csv\"\n\nkeywords = {\n 'BTC': {\n 'keywords' : ['bitcoin', 'bitcoins', 'xbt', 'btc', 'Bitcoin', 'Bitcoins', 'BTC', 'XBT']},\n 'ETH': {\n 'keywords' : ['ethereum', 'Ethereum', 'eth', 'ETH', 'ether', 'Ether']},\n 'LTC': {\n 'keywords' : ['litecoin', 'Litecoin', 'ltc', 'LTC']}\n }\n\n\nsubreddits = [\"Agrello\",\n\"altcoin\",\n\"altcoin_news\",\n\"ArkEcosystem\",\n\"Best_of_Crypto\",\n\"bitcoin\",\n\"bitcoin_cash\",\n\"Bitcoin_China\",\n\"Bitcoin_Classic\",\n\"bitcoin_uncensored\",\n\"bitcoin_unlimited\",\n\"BitcoinAll\",\n\"bitcoinall\",\n\"BitcoinBeginners\",\n\"Bitcoincash\",\n\"BitcoinMarkets\",\n\"bitcoinxt\",\n\"BlockChain\",\n\"btc\",\n\"btcforum\",\n\"btcnews\",\n\"BytecoinBCN\",\n\"cloudmining\",\n\"crypto_anarchism\",\n\"crypto_currency\",\n\"crypto101\",\n\"CryptoCurrencies\",\n\"cryptocurrency\",\n\"CryptoCurrencyLive\",\n\"CryptoMarkets\",\n\"dash\",\n\"decred\",\n\"district0x\",\n\"dnttrader\",\n\"dogecoin\",\n\"enigmacatalyst\",\n\"EsotericInvestments\",\n\"EthAnalysis\",\n\"ethdev\",\n\"ethereum\",\n\"EthereumClassic\",\n\"EthereumLand\",\n\"ethereumnoobies\",\n\"EtherMining\",\n\"ethernews\",\n\"ETHETC\",\n\"ethfinex\",\n\"ethinvestor\",\n\"ethlaw\",\n\"ethmarket\",\n\"ethtrader\",\n\"FuckToken\",\n\"gpumining\",\n\"iconomi\",\n\"iconomiuncensored\",\n\"Lisk\",\n\"litecoin\",\n\"litecoinforbeginners\",\n\"LitecoinMarkets\",\n\"litecoinmining\",\n\"locallitecoins\",\n\"MoneroCommunity\",\n\"moneromarket\",\n\"moneromarkets\",\n\"MoneroMining\",\n\"nem\",\n\"NEO\",\n\"NXT\",\n\"nxtcoin\",\n\"OMGTraders\",\n\"omise_go\",\n\"omisego\",\n\"PnDCrypto\",\n\"primecoin\",\n\"Qtum\",\n\"qtumtrader\",\n\"reidao\",\n\"ripplers\",\n\"RippleTalk\",\n\"santiment\",\n\"scryptmining\",\n\"siacoin\",\n\"STOX\",\n\"Stratis\",\n\"TenX\",\n\"tether\",\n\"TREZOR\",\n\"vergecurrency\",\n\"worldcryptonetwork\",\n\"xmrtrader\",\n\"XRP\",\n\"zcash_uncensored\",\n\"zec\"]","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"342209476","text":"\"\"\"Duckling Screensaver, by Al Sweigart al@inventwithpython.com\nA screensaver of many many ducklings.\n\n>\" ) ='') (``= (\"= >\") (\"=\n( >) ( ^) (v ) (^ ) ( >) (v )\n ^ ^ ^ ^ ^ ^ ^^ ^^ ^^\n\nThis and other games are available at https://nostarch.com/XX\nTags: large, artistic, object-oriented, scrolling\"\"\"\n__version__ = 0\nimport random, shutil, sys, time\n\n# Set up the constants:\nPAUSE = 0.2\nDENSITY = 10.0 # (!) Density can range from 0.0 to 100.0.\nDUCKLING_WIDTH = 5\nLEFT = 'left'\nRIGHT = 'right'\nBEADY = 'beady'\nWIDE = 'wide'\nHAPPY = 'happy'\nCHUBBY = 'chubby'\nVERY_CHUBBY = 'very chubby'\nOPEN = 'open'\nCLOSED = 'closed'\nOUT = 'out'\nDOWN = 'down'\nUP = 'up'\nHEAD = 'head'\nBODY = 'body'\nFEET = 'feet'\n\n# Get the size of the terminal window:\nWIDTH = shutil.get_terminal_size()[0]\n# We can't print to the last column on Windows without it adding a\n# newline automatically, so reduce the width by one:\nWIDTH -= 1\n\n\ndef main():\n print('Duckling Screensaver, by Al Sweigart al@inventwithpython.com')\n print('Press Ctrl-C to quit...')\n time.sleep(3)\n\n ducklingLanes = [None] * (WIDTH // DUCKLING_WIDTH)\n\n while True: # Main program loop.\n for laneNum, ducklingObj in enumerate(ducklingLanes):\n # See if we should create a duckling in this lane:\n if (ducklingObj == None\n and (random.randint(1, 10000) / 100) <= DENSITY):\n # Place a duckling in this lane:\n ducklingObj = Duckling()\n ducklingLanes[laneNum] = ducklingObj\n\n if ducklingObj != None:\n # Draw a duckling if there is one in this lane:\n ducklingObj.displayNext()\n # Delete the duckling if we've finished drawing it:\n if ducklingObj.partToDisplayNext == None:\n ducklingLanes[laneNum] = None\n else:\n # Draw five spaces since there is no duckling here.\n print(' ' * DUCKLING_WIDTH, end='')\n\n print() # Print a newline.\n sys.stdout.flush() # Make sure text appears on the screen.\n time.sleep(PAUSE)\n\n\nclass Duckling:\n def __init__(self):\n \"\"\"Create a new duckling with random body features.\"\"\"\n self.direction = random.choice([LEFT, RIGHT])\n self.body = random.choice([CHUBBY, VERY_CHUBBY])\n self.mouth = random.choice([OPEN, CLOSED])\n self.wing = random.choice([OUT, UP, DOWN])\n\n if self.body == CHUBBY:\n # Chubby ducklings can only have beady eyes.\n self.eyes = BEADY\n else:\n self.eyes = random.choice([BEADY, WIDE, HAPPY])\n\n self.partToDisplayNext = HEAD\n\n def displayHead(self):\n \"\"\"Prints the duckling's head.\"\"\"\n if self.direction == LEFT:\n # Print the mouth:\n if self.mouth == OPEN:\n print('>', end='')\n elif self.mouth == CLOSED:\n print('=', end='')\n\n # Print the eyes:\n if self.eyes == BEADY and self.body == CHUBBY:\n print('\"', end='')\n elif self.eyes == BEADY and self.body == VERY_CHUBBY:\n print('\" ', end='')\n elif self.eyes == WIDE:\n print(\"''\", end='')\n elif self.eyes == HAPPY:\n print('``', end='')\n\n print(') ', end='') # Print the back of the head.\n\n if self.direction == RIGHT:\n print(' (', end='') # Print the back of the head.\n\n # Print the eyes:\n if self.eyes == BEADY and self.body == CHUBBY:\n print('\"', end='')\n elif self.eyes == BEADY and self.body == VERY_CHUBBY:\n print(' \"', end='')\n elif self.eyes == WIDE:\n print(\"''\", end='')\n elif self.eyes == HAPPY:\n print('``', end='')\n\n # Print the mouth:\n if self.mouth == OPEN:\n print('<', end='')\n elif self.mouth == CLOSED:\n print('=', end='')\n\n if self.body == CHUBBY:\n # Print an extra space so chubby ducklings are the same\n # width as very chubby ducklings.\n print(' ', end='')\n\n def displayBody(self):\n \"\"\"Prints the duckling's body.\"\"\"\n print('(', end='') # Print the left side of the body.\n if self.direction == LEFT:\n # Print the interior body space:\n if self.body == CHUBBY:\n print(' ', end='')\n elif self.body == VERY_CHUBBY:\n print(' ', end='')\n\n # Print the wing:\n if self.wing == OUT:\n print('>', end='')\n elif self.wing == UP:\n print('^', end='')\n elif self.wing == DOWN:\n print('v', end='')\n\n if self.direction == RIGHT:\n # Print the wing:\n if self.wing == OUT:\n print('<', end='')\n elif self.wing == UP:\n print('^', end='')\n elif self.wing == DOWN:\n print('v', end='')\n\n # Print the interior body space:\n if self.body == CHUBBY:\n print(' ', end='')\n elif self.body == VERY_CHUBBY:\n print(' ', end='')\n\n print(')', end='') # Print the right side of the body.\n\n if self.body == CHUBBY:\n # Print an extra space so chubby ducklings are the same\n # width as very chubby ducklings.\n print(' ', end='')\n\n def displayFeet(self):\n \"\"\"Prints the duckling's feet.\"\"\"\n if self.body == CHUBBY:\n print(' ^^ ', end='')\n elif self.body == VERY_CHUBBY:\n print(' ^ ^ ', end='')\n\n def displayNext(self):\n \"\"\"Calls the appropriate display method for the next body\n part that needs to be displayed. Sets partToDisplayNext to\n None when finished.\"\"\"\n if self.partToDisplayNext == HEAD:\n self.displayHead()\n self.partToDisplayNext = BODY\n elif self.partToDisplayNext == BODY:\n self.displayBody()\n self.partToDisplayNext = FEET\n elif self.partToDisplayNext == FEET:\n self.displayFeet()\n self.partToDisplayNext = None\n\n\n# If this program was run (instead of imported), run the game:\nif __name__ == '__main__':\n try:\n main()\n except KeyboardInterrupt:\n sys.exit() # When Ctrl-C is pressed, end the program.\n","sub_path":"src/gamesbyexample/ducklings.py","file_name":"ducklings.py","file_ext":"py","file_size_in_byte":6506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"435814656","text":"from setuptools import setup\n# run:\n# setup.py install\n# or (if you'll be modifying the package):\n# setup.py develop\n# To use a consistent encoding\nfrom codecs import open\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\n\n# Get the long description from the README file\nwith open(path.join(here, 'README.rst'), encoding='utf-8') as f:\n long_description = f.read()\n \nsetup(name='h5pyd',\n version='0.1.0',\n description='h5py compatible client lib for HDF REST API',\n long_description=long_description,\n url='http://github.com/HDFGroup/h5pyd',\n author='John Readey',\n author_email='jreadey@hdfgrouup.org',\n license='BSD',\n packages = ['h5pyd', 'h5pyd._hl'],\n #requires = ['h5py (>=2.5.0)', 'h5json>=1.0.2'],\n install_requires = ['six'],\n setup_requires = ['pkgconfig', 'six'],\n zip_safe=False)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"48372175","text":"'''\nTesting functions to reorganize elements in a list\n'''\n\nfrom operator import itemgetter, attrgetter\n\nlist_2D = [['Simons', 8.5, 50],['Equipeur', 6.5, 30],['Yellow', 3.2, 45]]\n\n'''# First will sort items by 2nd elements, and for items with same value of 2nd element\n# will sort by the 3rd value\nlist_sorted = sorted(list_2D, key=itemgetter(1,2))\n'''\n\n\n\n\nlist_2D.sort(key=lambda x: x[1])\nprint('list_2D: ', list_2D)\n\n\n","sub_path":"Python/List Array indexing/element_organization.py","file_name":"element_organization.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"321526312","text":"''' Udacity - Deep Learning https://classroom.udacity.com/courses/ud730/lessons/6378983156/concepts/65998790420923 https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/6_lstm.ipynb\n\nAssignment 6 LSTM (Long short-term memory) Problem 2 - We want to train a LSTM over bigrams, that is pairs of consecutive characters like 'ab' instead of single characters like 'a'.\nSince the number of possible bigrams is large, feeding them directly to the LSTM using 1-hot encodings will lead to a very sparse representation that is very wasteful computationally.\na- Introduce an embedding lookup on the inputs, and feed the embeddings to the LSTM cell instead of the inputs themselves.\n\nEvaluation - This is a self-evaluated assignment. As you go through the notebook, make sure you are able to solve each problem and answer any posed questions\n(save your responses as markdown in the notebook). What changes did you make to use bigrams as input instead of individual characters? Were you able to implement the sequence-to-sequence LSTM?\nIf so, what additional challenges did you have to solve? '''\n\n# These are all the modules we'll be using later. Make sure you can import them before proceeding further.\nfrom __future__ import print_function\nimport os\nimport numpy as np\nimport random\nimport string\nimport tensorflow as tf\nimport zipfile\nimport math\nfrom six.moves import range\nfrom six.moves.urllib.request import urlretrieve\n\n\nurl = 'http://mattmahoney.net/dc/'\n\ndef maybe_download(filename, expected_bytes):\n \"\"\"Download a file if not present, and make sure it's the right size.\"\"\"\n if not os.path.exists(filename):\n filename, _ = urlretrieve(url + filename, filename)\n statinfo = os.stat(filename)\n if statinfo.st_size == expected_bytes:\n print('Found and verified %s' % filename)\n else:\n print(statinfo.st_size)\n raise Exception(\n 'Failed to verify ' + filename + '. Can you get to it with a browser?')\n return filename\n\nfilename = maybe_download('text8.zip', 31344016)\n\ndef read_data(filename):\n with zipfile.ZipFile(filename) as f:\n name = f.namelist()[0]\n data = tf.compat.as_str(f.read(name))\n return data\n\ntext = read_data(filename)\nprint('Data size %d' % len(text))\n\n# Create a small validation set.\nvalid_size = 1000\nvalid_text = text[:valid_size]\ntrain_text = text[valid_size:]\ntrain_size = len(train_text)\nprint(train_size, train_text[:64])\nprint(valid_size, valid_text[:64])\n\n#Utility functions to map characters to vocabulary IDs and back.\nvocabulary_size = len(string.ascii_lowercase) + 1 # [a-z] + ' '\n# letters = sorted(set((string.ascii_letters + string.digits + \" \").lower()))\nfirst_letter = ord(string.ascii_lowercase[0]) # output the ascii number referring to the first letter i.e. [0] in the set of letters called \"ascii_lowecase\"\n\ndef char2id(char):\n ''' returns ascii code for a (lower case) character, rebasing to 0 for ' ' and letters are 1-26 . So, in total, there are 27 possible values'''\n if char in string.ascii_lowercase:\n return ord(char) - first_letter + 1\n elif char == ' ':\n return 0\n else:\n print('Unexpected character: %s' % char)\n return 0\n\ndef id2char(dictid):\n ''' outputs character, based on input of (rebased - see above note) asci code '''\n if dictid > 0:\n return chr(dictid + first_letter - 1)\n else:\n return ' '\n\n'''\n # TEST\n print('\\nid2char(1), id2char(26), id2char(0)',id2char(1), id2char(26), id2char(0))\n string1=' abcdefghijklmnopqrstuvwxyz'\n for i in string1:\n print(i,char2id(i),' ')\n'''\n\n#Function to generate a training batch for the LSTM model.\nbatch_size=64\nnum_unrollings=10\n\nclass BatchGenerator(object):\n def __init__(self, text, batch_size, num_unrollings):\n self._text = text\n self._text_size = len(text)\n self._batch_size = batch_size\n self._num_unrollings = num_unrollings\n segment = self._text_size // batch_size\n self._cursor = [ offset * segment for offset in range(batch_size)]\n self._last_batch = self._next_batch()\n\n def _next_batch(self):\n batch = np.zeros(shape=(self._batch_size, vocabulary_size), dtype=np.float)\n for b in range(self._batch_size):\n batch[b, char2id(self._text[self._cursor[b]])] = 1.0\n self._cursor[b] = (self._cursor[b] + 1) % self._text_size\n return batch\n\n def next(self):\n batches = [self._last_batch]\n for step in range(self._num_unrollings):\n batches.append(self._next_batch())\n self._last_batch = batches[-1]\n return batches\n\nclass N_gram(object):\n def __init__(self,num_gram,text,batch_size,num_unrollings):\n self._numgram = num_gram\n self._text = text\n self._text_size = len(text)\n self._batch_size = batch_size\n self._num_unrollings = num_unrollings\n segment = self._text_size // batch_size\n self._cursor = [ offset * segment for offset in range(batch_size)]\n self._last_batch = self._next_batch()\n\n def _next_batch(self):\n batch = np.zeros(shape=(self._batch_size), dtype=np.float)\n for b in range(self._batch_size):\n batch[b] = char2id(self._text[self._cursor[b]])\n self._cursor[b] = (self._cursor[b] + 1) % self._text_size\n return batch\n\n def next(self):\n batches = [self._last_batch]\n for step in range(self._num_unrollings):\n batches.append(self._next_batch())\n self._last_batch = batches[-1]\n return batches\n\n\n\ndef characters(probabilities):\n return [id2char(c) for c in np.argmax(probabilities, 1)]\n\ndef batches2string(batches):\n s = [''] * batches[0].shape[0]\n for b in batches:\n s = [''.join(x) for x in zip(s, characters(b))]\n return s\n\ntrain_batches = BatchGenerator(train_text, batch_size, num_unrollings)\nvalid_batches = BatchGenerator(valid_text, 1, 1)\n#valid_examples =\ntrain_embeddings_batches = BatchGenerator(train_text, batch_size, 3)\n\nprint(batches2string(train_batches.next()))\nprint(batches2string(train_batches.next()))\nprint(batches2string(valid_batches.next()))\nprint(batches2string(valid_batches.next()))\n\n\ndef logprob(predictions, labels):\n predictions[predictions < 1e-10] = 1e-10\n return np.sum(np.multiply(labels, -np.log(predictions))) / labels.shape[0]\n\ndef sample_distribution(distribution):\n r = random.uniform(0, 1)\n s = 0\n for i in range(len(distribution)):\n s += distribution[i]\n if s >= r:\n return i\n return len(distribution) - 1\n\ndef sample(prediction):\n p = np.zeros(shape=[1, vocabulary_size], dtype=np.float)\n p[0, sample_distribution(prediction[0])] = 1.0\n return p\n\ndef random_distribution():\n b = np.random.uniform(0.0, 1.0, size=[1, vocabulary_size])\n return b/np.sum(b, 1)[:,None]\n\n\n#Simple LSTM Model.\nnum_nodes = 64\nembedding_size= 128\n\ngraph = tf.Graph()\nwith graph.as_default():\n\n with tf.variable_scope(\"lstm_scope\"):\n # Input data.\n train_data = list()\n for _ in range(num_unrollings + 1):\n train_data.append(tf.placeholder(tf.float32, shape=[batch_size,vocabulary_size])) #train_data.append(tf.placeholder(tf.float32, shape=[batch_size,vocabulary_size]))\n train_inputs = train_data[:num_unrollings]\n train_labels = train_data[1:] # labels are inputs shifted by one time step.\n\n # Input data.\n train_dataset = tf.placeholder(tf.int32, shape=[batch_size])\n train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])\n #valid_dataset = tf.constant(valid_batches, dtype=tf.int32)\n\n # Variables.\n embeddings = tf.Variable(tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))\n softmax_weights = tf.Variable(tf.truncated_normal([vocabulary_size, embedding_size],stddev=1.0 / math.sqrt(embedding_size)))\n softmax_biases = tf.Variable(tf.zeros([vocabulary_size]))\n\n # Model.\n embed = tf.nn.embedding_lookup(embeddings, train_inputs)\n loss = tf.reduce_mean(tf.nn.sampled_softmax_loss(softmax_weights, softmax_biases, embed,train_labels, vocabulary_size, vocabulary_size))\n optimizer = tf.train.AdagradOptimizer(1.0).minimize(loss)\n\n # Compute the similarity between minibatch examples and all embeddings. # We use the cosine distance:\n norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))\n normalized_embeddings = embeddings / norm\n valid_embeddings = tf.nn.embedding_lookup(normalized_embeddings, valid_dataset)\n similarity = tf.matmul(valid_embeddings, tf.transpose(normalized_embeddings))\n\n with tf.variable_scope(\"lstm_scope\"):\n # LSTM Variables\n x = tf.Variable(tf.truncated_normal([4, vocabulary_size * embedding_size, num_nodes], -0.1, 0.1))\n m = tf.Variable(tf.truncated_normal([4, num_nodes, num_nodes], -0.1, 0.1))\n b = tf.Variable(tf.zeros([4,1, num_nodes]))\n ix = x[0,:,:] ; fx = x[1,:,:] ; cx = x[2,:,:] ; ox = x[3,:,:] # where i = input gate, f = forget gate, c = memory cell, o = output gate\n im = m[0,:,:] ; fm = m[1,:,:] ; cm = m[2,:,:] ; om = m[3,:,:]\n ib = b[0,:,:] ; fb = b[1,:,:] ; cb = b[2,:,:] ; ob = b[3,:,:]\n\n # Variables saving state across unrollings.\n saved_output = tf.Variable(tf.zeros([batch_size, num_nodes]), trainable=False)\n saved_state = tf.Variable(tf.zeros([batch_size, num_nodes]), trainable=False)\n\n # Definition of the cell computation.\n def lstm_cell(i, o, state): # FOR TRAINING DATA: tf.shape(i).eval() = (64,27*128) = (64 , 3456) FOR SAMPLING/VALIDATION: # tf.shape(i).eval() = (1,3456)\n input_gate = tf.sigmoid(tf.matmul(i, ix) + tf.matmul(o, im) + ib)\n forget_gate = tf.sigmoid(tf.matmul(i, fx) + tf.matmul(o, fm) + fb)\n update = tf.matmul(i, cx) + tf.matmul(o, cm) + cb\n state = forget_gate * state + input_gate * tf.tanh(update)\n output_gate = tf.sigmoid(tf.matmul(i, ox) + tf.matmul(o, om) + ob)\n output_final = output_gate * tf.tanh(state)\n output_final_shape = tf.shape(output_final)\n embed_newvar1_shape = tf.shape(i);embed_newvar2_shape = tf.shape(i);embed_newvar3_shape = tf.shape(i)\n return output_final, state, output_final_shape,embed_newvar1_shape,embed_newvar2_shape,embed_newvar3_shape\n\n # Input data.\n train_data = list()\n for _ in range(num_unrollings + 1):\n train_data.append(tf.placeholder(tf.float32, shape=[batch_size,vocabulary_size])) #train_data.append(tf.placeholder(tf.float32, shape=[batch_size,vocabulary_size]))\n train_inputs = train_data[:num_unrollings]\n train_labels = train_data[1:] # labels are inputs shifted by one time step.\n\n # set up embed graph\n # train embeddings\n # preprocess embeddings for entry into LSTM model\n\n # Unrolled LSTM loop.\n outputs = list()\n output = saved_output\n state = saved_state\n\n embed_input_list = list()\n for i in train_inputs:\n embed_newvar1 = tf.nn.embedding_lookup(embeddings,tf.to_int32(i)) # tf.shape(i).eval() = (64,27,128)\n embed_newvar2 = tf.reshape(embed_newvar1,[tf.shape(i)[0],vocabulary_size * embedding_size,1]) # shape = [64 , 27 * 128 , 1]\n embed_newvar3 = tf.squeeze(embed_newvar2,[2]) # k2.shape = [64 , 27 * 128]\n embed_input_list.append(embed_newvar3)\n\n # train lstm (# input trained embeddings into LSTM model (in lieu of raw train_input data, i))\n output = saved_output\n state = saved_state\n for input_embed in embed_input_list:\n output,state,output_final_shape,embed_newvar1_shape,embed_newvar2_shape,embed_newvar3_shape = lstm_cell(input_embed,output,state)\n outputs.append(output)\n output_shape = tf.shape(output)\n output_embed_shape = tf.shape(output)\n i_shape = tf.shape(i)\n state_shape = tf.shape(state)\n\n # State saving across unrollings.\n with tf.control_dependencies([saved_output.assign(output),saved_state.assign(state)]):\n # Classifier.\n logits = tf.nn.xw_plus_b(tf.concat(0, outputs), w, b)\n logits_shape = tf.shape(logits)\n train_labels_final = tf.concat(0, train_labels)\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, tf.concat(0, train_labels)))\n\n # Optimizer.\n global_step = tf.Variable(0)\n learning_rate = tf.train.exponential_decay(0.3, global_step, 1000, 0.3, staircase=True)\n optimizer = tf.train.GradientDescentOptimizer(learning_rate)\n gradients, v = zip(*optimizer.compute_gradients(loss))\n gradients, _ = tf.clip_by_global_norm(gradients, 1.25)\n optimizer = optimizer.apply_gradients(zip(gradients, v), global_step=global_step)\n\n # Predictions.\n train_prediction = tf.nn.softmax(logits)\n\n # Sampling and validation eval: batch 1, no unrolling.\n sample_input = tf.placeholder(tf.float32, shape=[1, vocabulary_size])\n sample_input_embed = tf.nn.embedding_lookup(embeddings,tf.to_int32(sample_input))\n sample_input_embed2 = tf.reshape(sample_input_embed,[1,vocabulary_size * embedding_size,1])\n sample_input_embed3 = tf.squeeze(sample_input_embed2,[2])\n saved_sample_output = tf.Variable(tf.zeros([1, num_nodes]))\n saved_sample_state = tf.Variable(tf.zeros([1, num_nodes]))\n reset_sample_state = tf.group(saved_sample_output.assign(tf.zeros([1, num_nodes])),saved_sample_state.assign(tf.zeros([1, num_nodes])))\n sample_output, sample_state, sample_output_final2_shape,sample_embed_newvar1_shape,sample_embed_newvar2_shape,sample_embed_newvar3_shape = lstm_cell(sample_input_embed3, saved_sample_state,saved_sample_output)\n with tf.control_dependencies([saved_sample_output.assign(sample_output),saved_sample_state.assign(sample_state)]):\n sample_prediction = tf.nn.softmax(tf.nn.xw_plus_b(sample_output, w, b))\n\n\n''' MAIN '''\n\n# instantiate an instance of the class Embedding()\nsize = batch_size * (num_unrollings + 1)\nembeddings1 = Embedding( graph = None , batch_size = size , embedding_size = embedding_size , num_sampled = 64 )\n\nwith tf.Session( graph = graph ) as session:\n\n #train the embeddings1 object/instance\n num_steps = 7001\n embeddings1.train( session , num_steps )\n\n #train embeddings\n for step in range(num_steps):\n batches = train_batches.next()\n feed_dict = dict()\n for i in range(num_unrollings + 1):\n feed_dict[train_data[i]] = batches[i]\n\n # appending a dictionary: default_data.update({'item4': 4, 'item5': 5})\n '''\n what shape object do I have:\n - batches = list, num_unrollings elements, each element is a numpy array of shape (batch_size = 64, vocabulary_size = 27)\n - For num_steps=7001 iterations, I create an object batches\n - Then , I unroll '(num_unrollings + 1)'= 11 times, each unroll appends the 'feed_dict' dictionary. Such that the ith element of batches is assigned to one of 11 TF placeholders\n - The 11 (num_unrollings + 1) TF placeholders are used, in the TF graph, to represent a sequence of 10 data,label values\n - graph requirement: There are 11 (num_unrollings + 1) TF placeholders, each has shape = [ batch_size = 64 , vocabulary_size = 27 ]\n\n what shape object do I want:\n TF placeholder has shape = [batch_size * (num_unrollings + 1)]\n\n what do I need to do:\n\n - take charid (not 1-hot vector) => create new 'bigram' class which uses BatchGenerator to create batches of charids\n - graph requirement: 1 TF train_input placeholder, has shape = [ batch_size * (num_unrollings + 1) ]\n\n '''\n _, l, predictions, lr = session.run([optimizer, loss, train_prediction, learning_rate], feed_dict=feed_dict)\n\n\n\n\n\n# LSTM...tbc...\n\n # initialize all other variables\n is_lstm = lambda x: x.name.startswith(\"lstm_scope\")\n tf.initialize_variables(filter(is_lstm, tf.all_variables())).run()\n\n #\n\n # train lstm\n\n print('Initialized')\n mean_loss = 0\n for step in range(num_steps):\n batches = train_batches.next()\n feed_dict = dict()\n for i in range(num_unrollings + 1):\n feed_dict[train_data[i]] = batches[i]\n\n '''TEST - CHECK TENSOR SHAPES AND TYPES'''\n if step == 0:\n print('step==0')\n output_embed_shape_eval,embed_newvar1_shape_eval,embed_newvar2_shape_eval,embed_newvar3_shape_eval = session.run([output_embed_shape,embed_newvar1_shape,embed_newvar2_shape,embed_newvar3_shape],feed_dict=feed_dict)\n logits_eval,i_shape_eval,logits_shape_eval,output_shape_eval,embed_newvar1_shape_eval,state_shape_eval = session.run([logits,i_shape,logits_shape,output_shape,embed_newvar1_shape,state_shape],feed_dict=feed_dict)\n\n print('i_shape_eval',i_shape_eval)\n print('embed_newvar1_shape_eval',embed_newvar1_shape_eval)\n print('embed_newvar2_shape_eval',embed_newvar2_shape_eval)\n print('embed_newvar3_shape_eval',embed_newvar3_shape_eval)\n print('output_shape_eval ',output_shape_eval )\n print('state_shape_eval',state_shape_eval)\n print('logits',logits)\n print('logits_shape_eval',logits_shape_eval)\n print('train_labels_final',train_labels_final)\n print('\\n')\n print('output_embed_shape_eval',output_embed_shape_eval)\n print('\\n')\n\n _, l, predictions, lr = session.run([optimizer, loss, train_prediction, learning_rate], feed_dict=feed_dict)\n\n mean_loss += l\n if step % summary_frequency == 0:\n if step > 0:\n mean_loss = mean_loss / summary_frequency\n # The mean loss is an estimate of the loss over the last few batches.\n print(\n 'Average loss at step %d: %f learning rate: %f' % (step, mean_loss, lr))\n mean_loss = 0\n labels = np.concatenate(list(batches)[1:])\n print('Minibatch perplexity: %.2f' % float(\n np.exp(logprob(predictions, labels))))\n if step % (summary_frequency * 10) == 0:\n # Generate some samples.\n print('=' * 80)\n for _ in range(5):\n feed = sample(random_distribution())\n sentence = characters(feed)[0]\n reset_sample_state.run()\n for _ in range(79):\n prediction = sample_prediction.eval({sample_input: feed})\n feed = sample(prediction)\n sentence += characters(feed)[0]\n print(sentence)\n print('=' * 80)\n # Measure validation set perplexity.\n reset_sample_state.run()\n valid_logprob = 0\n for _ in range(valid_size):\n b = valid_batches.next()\n predictions = sample_prediction.eval({sample_input: b[0]})\n valid_logprob = valid_logprob + logprob(predictions, b[1])\n print('Validation set perplexity: %.2f' % float(np.exp(\n valid_logprob / valid_size)))\n\n\n'''\ntf.nn.sigmoid_cross_entropy_with_logits(logits, targets, name=None) https://www.tensorflow.org/versions/r0.10/api_docs/python/nn/classification\nComputes sigmoid cross entropy given logits.\nMeasures the probability error in discrete classification tasks in which each class is independent and not mutually exclusive.\nFor instance, one could perform multilabel classification where a picture can contain both an elephant and a dog at the same time.\nArgs:\n logits: A Tensor of type float32 or float64.\n targets: A Tensor of the same type and shape as logits.\n name: A name for the operation (optional).\nReturns:\nA Tensor of the same shape as logits with the componentwise logistic losses.\n\nhttp://stackoverflow.com/questions/35596629/how-to-convert-tf-int64-to-tf-float32\n\ntf.cast(x, dtype, name=None) https://www.tensorflow.org/versions/master/api_docs/python/array_ops/casting#cast\nCasts a tensor to a new type.\nThe operation casts x (in case of Tensor) or x.values (in case of SparseTensor) to dtype.\nFor example:\n# tensor \"a\" is [1.8, 2.2], dtype=tf.float\ntf.cast(a, tf.int32) ==> [1, 2] # dtype=tf.int32\nArgs:\n x: A Tensor or SparseTensor.\n dtype: The destination type.\n name: A name for the operation (optional).\nReturns:\nA Tensor or SparseTensor with same shape as x.\n\n\ntf.unpack(value, num=None, axis=0, name='unpack') https://www.tensorflow.org/api_docs/python/array_ops/slicing_and_joining#unpack\nDEPRECATED: Use unstack.\nUnpacks the given dimension of a rank-R tensor into rank-(R-1) tensors.\n\n\ntf.squeeze(input, axis=None, name=None, squeeze_dims=None) https://www.tensorflow.org/api_docs/python/array_ops/shapes_and_shaping#squeeze\nRemoves dimensions of size 1 from the shape of a tensor.\nGiven a tensor input, this operation returns a tensor of the same type with all dimensions of size 1 removed.\nIf you don't want to remove all size 1 dimensions, you can remove specific size 1 dimensions by specifying axis.\nFor example:\n# 't' is a tensor of shape [1, 2, 1, 3, 1, 1]\nshape(squeeze(t)) ==> [2, 3]\nOr, to remove specific size 1 dimensions:\n# 't' is a tensor of shape [1, 2, 1, 3, 1, 1]\nshape(squeeze(t, [2, 4])) ==> [1, 2, 3, 1]\nArgs:\n input: A Tensor. The input to squeeze.\n axis: An optional list of ints. Defaults to []. If specified, only squeezes the dimensions listed. The dimension index starts at 0.\n It is an error to squeeze a dimension that is not 1.\n name: A name for the operation (optional).\n squeeze_dims: Deprecated keyword argument that is now axis.\nReturns:\nA Tensor. Has the same type as input. Contains the same data as input, but has one or more dimensions of size 1 removed.\n\n\ntf.concat(concat_dim, values, name='concat') https://www.tensorflow.org/versions/r0.11/api_docs/python/array_ops/slicing_and_joining#concat\nConcatenates tensors along one dimension.\nConcatenates the list of tensors values along dimension concat_dim. If values[i].shape = [D0, D1, ... Dconcat_dim(i), ...Dn], the concatenated result has shape\n[D0, D1, ... Rconcat_dim, ...Dn] where Rconcat_dim = sum(Dconcat_dim(i))\nThat is, the data from the input tensors is joined along the concat_dim dimension.\nThe number of dimensions of the input tensors must match, and all dimensions except concat_dim must be equal.\n\nFor example:\nt1 = [[1, 2, 3], [4, 5, 6]]\nt2 = [[7, 8, 9], [10, 11, 12]]\ntf.concat(0, [t1, t2]) ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]\ntf.concat(1, [t1, t2]) ==> [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]\n\n# tensor t3 with shape [2, 3]\n# tensor t4 with shape [2, 3]\ntf.shape(tf.concat(0, [t3, t4])) ==> [4, 3]\ntf.shape(tf.concat(1, [t3, t4])) ==> [2, 6]\n\n\ntf.reshape(tensor, shape, name=None) https://www.tensorflow.org/api_docs/python/array_ops/shapes_and_shaping#squeeze\nReshapes a tensor.\nGiven tensor, this operation returns a tensor that has the same values as tensor with shape shape.\nIf one component of shape is the special value -1, the size of that dimension is computed so that the total size remains constant. In particular, a shape of [-1] flattens into 1-D. At most one component of shape can be -1.\nIf shape is 1-D or higher, then the operation returns a tensor with shape shape filled with the values of tensor. In this case, the number of elements implied by shape must be the same as the number of elements in tensor.\n\nFor example:\n# tensor 't' is [1, 2, 3, 4, 5, 6, 7, 8, 9]\n# tensor 't' has shape [9]\nreshape(t, [3, 3]) ==> [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n\n# tensor 't' is [[[1, 1], [2, 2]],\n# [[3, 3], [4, 4]]]\n# tensor 't' has shape [2, 2, 2]\nreshape(t, [2, 4]) ==> [[1, 1, 2, 2],\n [3, 3, 4, 4]]\n\n# tensor 't' is [[[1, 1, 1],\n# [2, 2, 2]],\n# [[3, 3, 3],\n# [4, 4, 4]],\n# [[5, 5, 5],\n# [6, 6, 6]]]\n# tensor 't' has shape [3, 2, 3]\n# pass '[-1]' to flatten 't'\nreshape(t, [-1]) ==> [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6]\n\n# -1 can also be used to infer the shape\n\n# -1 is inferred to be 9:\nreshape(t, [2, -1]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],\n [4, 4, 4, 5, 5, 5, 6, 6, 6]]\n# -1 is inferred to be 2:\nreshape(t, [-1, 9]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],\n [4, 4, 4, 5, 5, 5, 6, 6, 6]]\n# -1 is inferred to be 3:\nreshape(t, [ 2, -1, 3]) ==> [[[1, 1, 1],\n [2, 2, 2],\n [3, 3, 3]],\n [[4, 4, 4],\n [5, 5, 5],\n [6, 6, 6]]]\n\n# tensor 't' is [7]\n# shape [] reshapes to a scalar\nreshape(t, []) ==> 7\n\nArgs:\n tensor: A Tensor.\n shape: A Tensor. Must be one of the following types: int32, int64. Defines the shape of the output tensor.\n name: A name for the operation (optional).\nReturns:\nA Tensor. Has the same type as tensor.\n\n\n\ntf.shape(input, name=None, out_type=tf.int32) https://www.tensorflow.org/api_docs/python/array_ops/shapes_and_shaping#size\nReturns the shape of a tensor.\nThis operation returns a 1-D integer tensor representing the shape of input.\nFor example:\n# 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]\nshape(t) ==> [2, 2, 3]\n\nArgs:\n input: A Tensor or SparseTensor.\n name: A name for the operation (optional).\n out_type: (Optional) The specified output type of the operation (int32 or int64). Defaults to tf.int32.\nReturns:\nA Tensor of type out_type.\n\n\ntf.zeros(shape, dtype=tf.float32, name=None) https://www.tensorflow.org/api_docs/python/constant_op/constant_value_tensors\nCreates a tensor with all elements set to zero.\nThis operation returns a tensor of type dtype with shape shape and all elements set to zero.\nFor example:\ntf.zeros([3, 4], tf.int32) ==> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]\nArgs:\n shape: Either a list of integers, or a 1-D Tensor of type int32.\n dtype: The type of an element in the resulting Tensor.\n name: A name for the operation (optional).\nReturns:\nA Tensor with all elements set to zero.\n\n\ntf.Variable.eval(session=None) https://www.tensorflow.org/versions/r0.11/api_docs/python/state_ops/variables\nIn a session, computes and returns the value of this variable.\nThis is not a graph construction method, it does not add ops to the graph.\nThis convenience method requires a session where the graph containing this variable has been launched. If no session is passed, the default session is used.\nSee the Session class for more information on launching a graph and on sessions.\n\nv = tf.Variable([1, 2])\ninit = tf.initialize_all_variables()\nwith tf.Session() as sess:\n sess.run(init)\n # Usage passing the session explicitly.\n print(v.eval(sess))\n # Usage with the default session. The 'with' block\n # above makes 'sess' the default session.\n print(v.eval())\n\nArgs:\n session: The session to use to evaluate this variable. If none, the default session is used.\nReturns:\nA numpy ndarray with a copy of the value of this variable.\n\n\ntf.Variable.get_shape() https://www.tensorflow.org/versions/r0.11/api_docs/python/state_ops/variables\nThe TensorShape of this variable.\nReturns:\nA TensorShape.\n\n\ntf.Variable.dtype https://www.tensorflow.org/versions/r0.11/api_docs/python/state_ops/variables\nThe DType of this variable.\n\n\ntf.Variable.assign(value, use_locking=False) https://www.tensorflow.org/versions/r0.11/api_docs/python/state_ops/variables\nAssigns a new value to the variable.\nThis is essentially a shortcut for assign(self, value).\nArgs:\n value: A Tensor. The new value for this variable.\n use_locking: If True, use locking during the assignment.\nReturns:\nA Tensor that will hold the new value of this variable after the assignment has completed.\n\n\n\nhttps://www.tensorflow.org/api_docs/python/constant_op/\n'''\n","sub_path":"assignment6/4_LTSM_Problem_2a_add_embedding_to_LSTM_model_input_v12.py","file_name":"4_LTSM_Problem_2a_add_embedding_to_LSTM_model_input_v12.py","file_ext":"py","file_size_in_byte":27445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"332518837","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QColorDialog, QGroupBox, QHBoxLayout, QLabel, QMainWindow, QMessageBox, QPushButton, QScrollArea, QVBoxLayout, QWidget, QFileDialog\nfrom matplotlib.backends.backend_qt5 import NavigationToolbar2QT\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport dfModel\n\nmod = dfModel.DataFrameModel\n\nclass Ui_Stats(QMainWindow):\n datos = \"\"\n conjuntoDatos = \"\"\n\n def __init__(self):\n super(Ui_Stats, self).__init__()\n global conjuntoDatos \n conjuntoDatos = []\n self.resize(813, 700)\n self.setWindowTitle('Estadística')\n\n self.colorDialog = QColorDialog(self)\n \n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())\n self.setSizePolicy(sizePolicy)\n self.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.centralwidget = QtWidgets.QWidget(self)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.labelSelect = QtWidgets.QLabel(self.centralwidget)\n self.labelSelect.setGeometry(QtCore.QRect(10, 0, 171, 39))\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(2)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.labelSelect.sizePolicy().hasHeightForWidth())\n self.labelSelect.setSizePolicy(sizePolicy)\n self.labelSelect.setMaximumSize(QtCore.QSize(200, 16777215))\n font = QtGui.QFont()\n font.setFamily(\"Calibri\")\n font.setPointSize(10)\n self.labelSelect.setFont(font)\n self.labelSelect.setObjectName(\"labelSelect\")\n self.selectFileBtn = QtWidgets.QToolButton(self.centralwidget)\n self.selectFileBtn.setGeometry(QtCore.QRect(180, 10, 25, 19))\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.selectFileBtn.sizePolicy().hasHeightForWidth())\n self.selectFileBtn.setSizePolicy(sizePolicy)\n self.selectFileBtn.setMaximumSize(QtCore.QSize(25, 16777215))\n self.selectFileBtn.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n self.selectFileBtn.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.selectFileBtn.setObjectName(\"selectFileBtn\")\n self.selectFileBtn.clicked.connect(lambda: self.openFileNameDialog())\n self.lineFileName = QtWidgets.QLineEdit(self.centralwidget)\n self.lineFileName.setGeometry(QtCore.QRect(210, 10, 171, 21))\n self.lineFileName.setReadOnly(True)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(4)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.lineFileName.sizePolicy().hasHeightForWidth())\n self.lineFileName.setSizePolicy(sizePolicy)\n self.lineFileName.setMaximumSize(QtCore.QSize(500, 16777215))\n self.lineFileName.setFont(font)\n self.lineFileName.setObjectName(\"lineFileName\")\n self.graphicBtn = QtWidgets.QPushButton(self.centralwidget)\n self.graphicBtn.setGeometry(QtCore.QRect(390, 10, 100, 23))\n self.graphicBtn.clicked.connect(lambda: self.generateTable())\n self.graphicBtn.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n self.graphicBtn.setFont(font)\n self.graphicBtn.setObjectName(\"graphicBtn\")\n self.newBtn = QtWidgets.QPushButton(self.centralwidget)\n self.newBtn.setGeometry(QtCore.QRect(495, 10, 100, 23))\n self.newBtn.clicked.connect(lambda: self.clearLayout())\n self.newBtn.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n self.newBtn.setFont(font)\n self.newBtn.setObjectName(\"newBtn\")\n self.setCentralWidget(self.centralwidget)\n self.statusbar = QtWidgets.QStatusBar(self)\n self.statusbar.setObjectName(\"statusbar\")\n self.setStatusBar(self.statusbar)\n self.menubar = QtWidgets.QMenuBar(self)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 813, 21))\n self.menubar.setObjectName(\"menubar\")\n self.setMenuBar(self.menubar)\n self.outerGroupBox = QGroupBox(self.centralwidget)\n self.outerGroupBox.setGeometry(0, 40, 795, 640)\n self.horizontalGroupBox = QGroupBox(self.outerGroupBox)\n self.horizontalGroupBox.setGeometry(0, 0, 700, 500)\n scrollArea = QScrollArea()\n scrollArea.setWidget(self.horizontalGroupBox)\n scrollArea.setMinimumSize(500, 50)\n scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)\n scrollArea.setWidgetResizable(True)\n self.outlayout = QVBoxLayout()\n self.outlayout.addWidget(scrollArea)\n self.outerGroupBox.setLayout(self.outlayout)\n self.layout = QVBoxLayout()\n self.horizontalGroupBox.setLayout(self.layout)\n self.retranslateUi(self)\n QtCore.QMetaObject.connectSlotsByName(self)\n\n #def setupUi(self, MainWindow):\n \n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"Estadistica\", \"Estadistica\"))\n self.labelSelect.setText(_translate(\"Select a document\", \"Seleccione un documento\"))\n self.selectFileBtn.setText(_translate(\"...\", \"...\"))\n self.graphicBtn.setText(_translate(\"Show data\", \"Mostrar datos\"))\n self.newBtn.setText(_translate(\"New\", \"Nuevo\"))\n\n def openFileNameDialog(self):\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n fileName, _ = QFileDialog.getOpenFileName(self,\"QFileDialog.getOpenFileName()\", \"\",\"CSV files (*.csv)\", options=options)\n if fileName:\n self.lineFileName.setText(fileName)\n\n def generateTable(self):\n global datos\n if self.lineFileName.text() != '':\n datos = pd.read_csv(self.lineFileName.text())\n\n model = mod(datos)\n table = QtWidgets.QTableView(parent=self)\n table.setMinimumSize(750, 200)\n table.setMaximumSize(750, 200)\n table.setModel(model)\n\n labelData = QtWidgets.QLabel()\n labelData.setText(\"Dato a mostrar\")\n labelData.setFont(QtGui.QFont(\"Calibri\", 10))\n lineData = QtWidgets.QLineEdit()\n lineData.setMaximumSize(100, 21)\n lineData.setFont(QtGui.QFont(\"Calibri\", 10))\n\n labelClasses = QtWidgets.QLabel()\n labelClasses.setText(\"Cantidad de clases del histograma\")\n labelClasses.setFont(QtGui.QFont(\"Calibri\", 10))\n lineClasses = QtWidgets.QLineEdit()\n lineClasses.setMaximumSize(100, 21)\n lineClasses.setFont(QtGui.QFont(\"Calibri\", 10))\n\n colorBtn = QPushButton()\n colorBtn.setText(\"Seleccionar color\")\n colorBtn.setFont(QtGui.QFont(\"Calibri\", 10))\n colorBtn.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n colorBtn.clicked.connect(lambda: self.selectColor())\n\n plotBtn = QPushButton()\n plotBtn.setText(\"Mostrar resultados\")\n plotBtn.setFont(QtGui.QFont(\"Calibri\", 10))\n plotBtn.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n plotBtn.clicked.connect(lambda: self.calcular(lineData.text(), int(lineClasses.text())))\n\n hElement = QWidget()\n hLayout = QHBoxLayout()\n hLayout.addWidget(labelData)\n hLayout.addWidget(lineData)\n hLayout.addWidget(labelClasses)\n hLayout.addWidget(lineClasses)\n hLayout.addWidget(colorBtn)\n hLayout.addWidget(plotBtn)\n hElement.setLayout(hLayout)\n\n self.layout.addWidget(table)\n self.layout.addWidget(hElement)\n self.layout.addStretch()\n else:\n dlg = QMessageBox(self)\n dlg.setWindowTitle('Error')\n dlg.setText('Seleccione un archivo')\n dlg.setIcon(QMessageBox.Information)\n btn = dlg.exec()\n\n def selectColor(self):\n self.colorDialog.exec_()\n\n def calcular(self, dataTxt, classQuant):\n global conjuntoDatos\n\n x = datos[dataTxt]\n color = self.colorDialog.selectedColor().name()\n figure = plt.figure(figsize=(2,2))\n plt.hist(x,bins=classQuant,color=color)\n plt.axvline(x.mean(),color='red',label='Media')\n plt.axvline(x.median(),color='yellow',label='Mediana')\n plt.axvline(x.mode()[0],color='green',label='Moda')\n plt.xlabel('Casos')\n plt.ylabel('Frecuencia')\n\n conjuntoDatos.append(x)\n \n labelMean = QLabel('Media = ' + str(x.mean()))\n labelMedian = QLabel('Mediana = ' + str(x.median()))\n labelMode = QLabel('Moda = ' + str(x.mode()[0]))\n\n element = QWidget()\n vLayout = QVBoxLayout()\n vLayout.addWidget(labelMean)\n vLayout.addWidget(labelMedian)\n vLayout.addWidget(labelMode)\n element.setLayout(vLayout)\n\n canvas = FigureCanvasQTAgg(figure)\n toolbar = NavigationToolbar2QT(canvas, self)\n canvLayout = QVBoxLayout()\n canvLayout.addWidget(toolbar)\n canvLayout.addWidget(canvas)\n canvasElmt = QWidget()\n canvasElmt.setLayout(canvLayout)\n canvasElmt.setMinimumSize(300, 480) \n\n labelX = QtWidgets.QLabel()\n labelX.setText(\"Eje X: \")\n labelX.setFont(QtGui.QFont(\"Calibri\", 10))\n lineX = QtWidgets.QLineEdit()\n lineX.setMaximumSize(50, 21)\n lineX.setFont(QtGui.QFont(\"Calibri\", 10))\n\n graphTBtn = QPushButton()\n graphTBtn.setText(\"Graficar tendencias\")\n graphTBtn.setFont(QtGui.QFont(\"Calibri\", 10))\n graphTBtn.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n graphTBtn.clicked.connect(lambda: self.tendencies(lineX.text()))\n\n hLayout = QHBoxLayout()\n hLayout.addWidget(labelX)\n hLayout.addWidget(lineX)\n hLayout.addWidget(graphTBtn)\n hLayoutElm = QWidget()\n hLayoutElm.setLayout(hLayout)\n\n self.layout.addWidget(canvasElmt, 2)\n self.layout.addWidget(element, 1)\n self.layout.addWidget(hLayoutElm)\n \n if len(self.layout) > 7:\n self.layout.itemAt(len(self.layout)-5).widget().deleteLater()\n\n def tendencies(self, xAxis):\n global datos\n x = datos[xAxis]\n names = []\n\n figure = plt.figure(figsize=(12,8))\n for y in conjuntoDatos:\n plt.plot(x,y,marker='o')\n names.append(y.name)\n plt.legend(names, prop = {'size':10},loc='lower right')\n plt.xlabel(xAxis)\n plt.ylabel('')\n\n canvas = FigureCanvasQTAgg(figure)\n toolbar = NavigationToolbar2QT(canvas, self)\n canvLayout = QVBoxLayout()\n canvLayout.addWidget(toolbar)\n canvLayout.addWidget(canvas)\n canvasElmt = QWidget()\n canvasElmt.setLayout(canvLayout)\n canvasElmt.setMinimumSize(300, 480) \n\n self.layout.addWidget(canvasElmt)\n\n def clearLayout(self):\n for i in reversed(range(self.layout.count())): \n if self.layout.itemAt(i).widget() is not None:\n self.layout.itemAt(i).widget().deleteLater()\n elif self.layout.itemAt(i).widget() is None:\n self.layout.removeItem(self.layout.itemAt(i))\n\nif __name__ == \"__stats__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n ui = Ui_Stats()\n ui.show()\n sys.exit(app.exec_())","sub_path":"stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":11972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"449410558","text":"from django.http import JsonResponse\nfrom django.shortcuts import render, redirect\n\nfrom sudoku.engine.generator import Generator\nfrom sudoku.solver import Solver\n\n\ndef index(request):\n # Solve puzzle or redirect if there is GET parameters\n if request.GET:\n # Check if the get field is a valid sudoku puzzle\n valid = True\n values = dict()\n for l in \"ABCDEFGHI\":\n for n in \"012345678\":\n # Check that all squares are in the request\n if l + n not in request.GET:\n valid = False\n else:\n # If the key is in the get, check if the value is valid\n if len(request.GET[l + n]) > 1:\n valid = False\n elif len(request.GET[l + n]) == 1:\n if request.GET[l + n] not in \"012345678\":\n # If there was an invalid character in the input\n valid = False\n else:\n # Add the value to the values dictionary\n values[l + n] = request.GET[l + n]\n if valid:\n print(\"Valid input, trying to solve\")\n values = Solver(values).values\n if values:\n return render(request, 'sudoku/index.html', {'values': values})\n print(\"Invalid input, redirecting\")\n return redirect('index')\n else:\n return render(request, 'sudoku/index.html')\n\n\ndef policy(request):\n return render(request, 'sudoku/policy.html')\n\n\ndef newgame(request, sidelen=9, difficulty='easy'):\n gen = Generator(str(sidelen), difficulty.lower())\n result = gen.generate_one()\n response = dict(puzzle=result['puzzle'].values(), solution=result['solution'].values())\n return JsonResponse(response)\n","sub_path":"sudoku/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"44942137","text":"#!/usr/bin/python\r\n# -*- coding: UTF-8 -*-\r\n\"\"\"\r\n@author:My\r\n@file:create_sqlalchemy_orm.py\r\n@time:2020/12/13\r\n\"\"\"\r\n\r\nfrom datetime import datetime\r\nfrom sqlalchemy import DateTime\r\nimport pymysql\r\nfrom sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey\r\nfrom sqlalchemy.orm import sessionmaker\r\nfrom sqlalchemy.ext.declarative import declarative_base\r\n\r\nBase = declarative_base()\r\n\r\n\r\n# 用户 id、用户名、年龄、生日、性别、学历、字段创建时间、字段更新时间\r\nclass student_table(Base):\r\n __tablename__ = 'student'\r\n user_id = Column(Integer(), primary_key=True)\r\n user_name = Column(String(50), index=True)\r\n age = Column(Integer(), nullable=False)\r\n birthday = Column(DateTime())\r\n sex = Column(String(2), nullable=False)\r\n edu = Column(String(50), nullable=False)\r\n create_on = Column(DateTime(), default=datetime.now)\r\n update_on = Column(DateTime(), default=datetime.now, onupdate=datetime.now)\r\n\r\n\r\ndburl = \"mysql+pymysql://testuser:testpass@localhost:3306/testdb?charset=utf8mb4\"\r\nengine = create_engine(dburl, echo=True, encoding=\"utf-8\")\r\n\r\nSessionClass = sessionmaker(bind=engine)\r\nsession = SessionClass()\r\n# Base.metadata.create_all(engine)\r\n\r\nfor result in session.query(student_table).filter(student_table.user_name == 'Scott').all():\r\n print(result)\r\nsession.commit()\r\n","sub_path":"week03/create_sqlalchemy_orm.py","file_name":"create_sqlalchemy_orm.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"18772285","text":"\"\"\"\n# Fingerprinting - CAMCAN Cohort\n## Variance in functional connectivity\n\nScript - Variance calculator\nAuthor: Frédéric St-Onge\n\nDate created: 2021-07-23\nDate modified: 2022-01-25\n\nVersion: 1.1\n\n--------\nUpdates:\n--------\n 2021-12-14: Added documentation across. Added the calculation of absolute distance from mean (in addition to the median stuff) so we can look at both.\n 2022-01-25: Added the possibility to look at variability \"between\" network as well (not just within)\n\n--------\nPurpose:\n--------\n This script computes the variance and the coefficient of variance of the functional connectivity matrices of each subject.\n It also computes the distance between the individual-level variance and the group-level mean and median of individual-level variance.\n It does so for each network of interest.\n\n This script will work for any symmetric matrix matching what we would expect for functional connectivity. As such, it also works\n for the temporal similarity analysis.\n\n\"\"\"\n\nimport os\nimport numpy as np\nimport re\nimport warnings\nimport pandas as pd\nfrom argparse import ArgumentParser\n\ndef main():\n \"\"\"\n This function launches the variance_calculator.\n\n\n \"\"\" \n args = parsing()\n print('--------------------------------------------')\n print('----Connectivity variability with Python----')\n print('Parameters:')\n print(f' Path to matrices, modality {args.modality}: {args.path_mat}')\n print(f' Path to output: {args.output}')\n print(f' Index name: {args.index}')\n print(f' Type of network used: {args.type}')\n print(' ')\n print(f' Modality of interest: {args.modality}')\n print(f' Parcellation used: {args.parcellation}')\n print(f' Network used: {args.network}')\n print(f' Correlation used to generate the original matrix: {args.corr}')\n print(f' QC List used: {args.qcm}')\n print(f' Additional participant selection used: {args.red}')\n print('--------------------------------------------')\n print(' ')\n\n #verify_input(args)\n print(f'Initializing an object of class var_calculator...')\n var = var_calculator(args.path_mat, args.output, args.type, args.modality, args.parcellation, args.network, args.corr, args.index, args.qcm, args.red)\n\n print(f'Selecting ROIs')\n var.rois()\n\n print(f'Fetching file names')\n var.filename_fetch()\n\n print(f'Calculating variance and exporting to file')\n var.var_calculation()\n\n print(f'Computing the distance between variance coefficient and the group-level median')\n var.absolute_distance()\n\n print(f'Exporting variance to file')\n var.export_df()\n\n print(\"Done!\")\n\n return None\n\ndef parsing():\n \"\"\"\n Argument parser for the current script.\n\n \"\"\"\n parser = ArgumentParser(description='')\n parser.add_argument('--path_mat', help='Path to matrices to analyse')\n parser.add_argument('--output', help='Path where the output should go')\n parser.add_argument('-t', '--type', default = 'within', choices=['within', 'between'], help='Whether we should use within- or between-network edges.')\n parser.add_argument('-m', '--modality', help='Name of the modality to use. Purely used to add to the final name.')\n parser.add_argument('-p', '--parcellation', choices=['Power', 'Schaefer'], help='Which parcellation to use.')\n parser.add_argument('-n', '--network', default='Whole Brain', help='Which network to use')\n parser.add_argument('-c', '--corr', choices=['corr', 'pcor', 'hctsa'], default='corr', help='String to add, representing the correlation used. It also adds a string for \"hctsa\" if the script is used that way.')\n parser.add_argument('-i', '--index', default='id_camcan', help='This string should be the name of the column you want to set as index name for the resulting dataframe. Currently, by default, it will be \"id_camcan\".')\n parser.add_argument('-q', '--qcm', default='', help=\"List of QC'ed participants (participants that should be retained).\")\n parser.add_argument('-r', '--red', default='', help='Further selection of subject, if needed.')\n\n args = parser.parse_args()\n\n return args\n \n\nclass var_calculator:\n\n def __init__(self, path_mat, output, type, modality, parcellation, network, corr, index, qcm, red):\n self.path_mat = path_mat\n self.output = output\n self.type = type\n\n self.modality = modality\n self.parce = parcellation\n self.net = network\n self.corr = corr\n self.index = index\n self.qcm = qcm\n self.red = red\n\n return None\n\n def rois(self):\n \"\"\"\n This function defines the regions of interest to be used in this connectivity variability run.\n\n Currently, the script supports the Power (REF) and the Schaefer atlas (REF). Note that the Power atlas in our cohort have also been processed with an additional 8 nodes (limbic), based on a paper by Vachon-Presseau et al. (REF).\n\n The function simply takes the parcellation parameter from the class to determine which dictionnary to use. Then, it uses the \"network\" to determine the nodes to use for the calculation.\n\n WARNING: The \"network\" variable need to mirror exactly what is written below. Otherwise, the script will not recognize it.\n\n FEATURE TO ADD: Create a way where we can add different networks together. For now, any \"combos\" need to be added in the dictionnary\n \"\"\"\n #Dictionnary for the Power Atlas\n dict_net_power = {\n #REDO INDEXING. FIRST TERM SHOULD BE -1\n \"uncertain\": list(range(0, 12)) + [83, 84] + list(range(131, 136)) + list(range(139, 142)) + list(range(181, 185)) + [220] + list(range(246, 250)) + [252, 253],\n \"sensory_somatomotor\": list(range(12, 46)) + [254],\n \"cingulo_opercular\": list(range(46, 60)),\n \"auditory\": list(range(60, 73)),\n \"default_mode\": list(range(73, 83)) + list(range(85, 131)) + [136] + [138],\n \"ventral_attention\": [137] + list(range(234, 242)),\n \"visual\": list(range(142, 173)),\n \"frontoparietal\": list(range(173, 181)) + list(range(185, 202)),\n \"salience\": list(range(202, 220)),\n \"subcortical\": list(range(221, 234)),\n #\"cerebellar\": list(range(242, 246)),\n \"dorsal_attention\": [250, 251] + list(range(255, 264)),\n \"limbic\": list(range(264, 273)),\n \"default_mode_limbic\": list(range(73, 83)) + list(range(85, 131)) + [136] + [138] + list(range(264, 273)),\n \"Whole_brain\": list(range(0, 273))\n }\n\n #Dictionnary for the Schaefer Atlas (Within- network)\n dict_net_schaefer_within = {\n #Based on the dataset.labels from the Schaefer Atlas in Nilearn.\n \"visual\": list(range(0, 31)) + list(range(200, 230)),\n \"somatomotor\": list(range(31, 68)) + list(range(230, 270)),\n \"dorsal_attention\": list(range(68, 91)) + list(range(270, 293)),\n \"salience_ventral_attention\": list(range(91, 113)) + list(range(293, 318)),\n \"limbic\": list(range(113, 126)) + list(range(318, 331)),\n \"frontoparietal\": list(range(126, 148)) + list(range(331, 361)),\n \"default_mode\": list(range(148, 200)) + list(range(361, 400)),\n \"Whole_brain\": list(range(0, 400)),\n \"default_mode_limbic\": list(range(148, 200)) + list(range(361, 400)) + list(range(113, 126)) + list(range(318, 331))\n }\n\n #Dictionary for the Schaefer Atlas (Between- network) \n dict_net_schaefer_between = {\n #Overall between-network connectivity (we don't do the average between each network)\n \"visual\": list(range(31, 200)) + list(range(231, 400)),\n \"somatomotor\": list(range(0, 31)) + list(range(68, 230)) + list(range(270, 400)),\n \"dorsal_attention\": list(range(0, 68)) + list(range(91, 270)) + list(range(293, 400)),\n \"salience_ventral_attention\": list(range(0, 91)) + list(range(113, 293)) + list(range(318, 400)),\n \"limbic\": list(range(0, 113)) + list(range(126, 318)) + list(range(331, 400)),\n \"frontoparietal\": list(range(0, 126)) + list(range(148, 331)) + list(range(361, 400)),\n \"default_mode\": list(range(0, 148)) + list(range(200, 361))\n }\n if self.parce == \"Power\":\n self.nodes = dict_net_power[f'{self.net}']\n \n #If we use the \"within\" network FPC, we only care that the nodes are exactly the same to select the matrix section\n elif self.parce == \"Schaefer\" and self.type == \"within\":\n self.nodes = dict_net_schaefer_within[f'{self.net}']\n \n #If we use the \"between\" network FPC, we want to bind the matrix to the network of interest (\"within\") nodes\n # and we want to select all the nodes from that slice of network that are NOT within network.\n #So for the visual network, we want edges that are between 1 and 30 on the x-axis, but we want all edges that\n # are not in the 1-30 position in the y-axis.\n elif self.parce == \"Schaefer\" and self.type == \"between\":\n self.nodes = dict_net_schaefer_within[f'{self.net}']\n self.between = dict_net_schaefer_between[f'{self.net}']\n \n return None\n\n def filename_fetch(self):\n \"\"\"\n This method searches the directories where the input is supposed to be. If the files end\n with \"matrix.txt\" (for the Power Atlas) or with simply \"matrix\" (for the Schaefer Atlas),\n we append that filename to the list of the correct modality. \n \"\"\"\n self.filename_list = []\n\n try:\n for filename in sorted(os.listdir(self.path_mat)): #We sort the content of the directory and list the folders\n if (filename.endswith(\"matrix.txt\") or filename.endswith(\"matrix\")): #If the name matches...\n self.filename_list.append(filename) #... we append it to the filename. \n except OSError:\n print(\"Error: Could not access data directory.\", flush=True)\n raise SystemExit\n \n return None\n\n def subset(self):\n \"\"\"\n This method imports the files that we need to subset from the fingerprinting list.\n This is because, in our study, the connectivity matrix of participants is computed\n whether they passed the QC or not. \n\n If the folder containing your connectivity matrices only holds participants who\n have been QC'ed, the -q1 and -q2 options should be left empty. This step is then\n skipped.\n\n If you wish to subset the fingerprinting in a specific way (e.g. male/female), and\n you have entered a list in the -r option, the fetching will also occur here.\n \"\"\"\n\n #Set the empty lists\n self.qc_list = [] #To store the IDs of modality 1 (QC'ed)\n self.reduct = [] #To store the IDs of the subset to do\n\n #######################################\n #Import the QC_list for modality 1 (with a try/except statement to catch errors)\n if self.qcm: #If the QC_list was selected...\n try:\n with open(self.qcm) as x: #Open file\n for line in x:\n new_line = re.search(r'[0-9]{6}', line).group()[0:6] \n if new_line.strip().isdigit() and len(new_line.strip()) == 6: #If stripped line are only numbers and their length is 6, then...\n self.qc_list.append(new_line.strip()) #Append the number to the list\n else:\n raise SystemExit('Error: encountered unexpected input in QC list. Cannot strip to one six-digit ID (CC ID) per line.')\n print(' Generated QC_list')\n\n except OSError: #If we can't find the file, we exist straight away.\n print(f\"Error: Could not access QC list file at : {self.qcm1}\", flush=True)\n raise SystemExit\n\n else: #If no QC_list is provided, print the message\n print(f' No argument given to -q argument. Assume no QC_list is necessary')\n \n #######################################\n #Subset the data by a specific criteria\n if self.red: #If the reduction option is given\n try:\n with open(self.red) as z: #Open file\n for line in z:\n new_line = re.search(r'[0-9]{6}', line).group()[0:6]\n if new_line.strip().isdigit() and len(new_line.strip()) == 6: #If stripped line are only numbers and their length is 6, then...\n self.reduct.append(new_line.strip()) #Append the number to the list\n else:\n raise SystemExit('Error: encountered unexpected input in QC list 1. Expected one six-digit ID (CC ID) per line.')\n\n print(' Generated subset list')\n\n except OSError: #If we can't find the file, we exist straight away.\n print(f\"Error: Could not access subset list file at : {self.red}\", flush=True)\n raise SystemExit\n else:\n print(f\" No argument given to -r argument. Assume we don't want to subset the data and use all subjects that were QC'ed.\")\n \n\n return None\n\n\n def final_subject_list(self):\n \"\"\"\n We define the final subject list as the intersection of subjects in:\n - The filenames of the matrices of modality 1\n - The filenames of the matrices of modality 2\n - The subject IDs of the QC'ed subjects in modality 1\n - The subject IDs of the QC'ed subjects in modality 2\n Optional:\n - If we want to subset, we will do it here.\n\n \"\"\"\n #We extract the digits from the filename to create the subject list of m1 and m2\n self.sub_list = [re.search(r's[0-9]{6}', string).group()[1:7] for string in self.filename_list]\n\n #We set the list of IDs as the list of list of IDs from the filenames, the QC lists\n #and any subset we want to do. This is checked first.\n if self.qcm and self.red:\n self.all_IDs = [self.sub_list, self.qc_list, self.reduct]\n\n elif self.qcm:\n self.all_IDs = [self.sub_list, self.qc_list]\n \n else:\n self.all_IDs = self.sub_list\n\n #Find the intersection of all subset lists (equivalent of \"inner\" in a dataframe merge)\n self.subject_intersection_set = set(self.all_IDs[0]).intersection(*self.all_IDs)\n\n #Transform the dictionary of the previous variable to a sorted list\n self.subject_list = list(sorted(self.subject_intersection_set))\n\n return None\n\n def final_file_selection(self):\n \"\"\"\n We create a list that will house the final filenames to fetch and use for the\n fingerprinting. We do this by iterating over the subject_list we created in\n the previous method AND iterating over the filenames available for both\n modalities, one at a time.\n\n I.e. Our subject list include subjects that are in BOTH modalities, while our\n list of files for each modality includes subjects ONLY in this modalities. \n Fingerprinting needs 2 modalities to be calculated, so we restrict the filenames\n to take to subjects that also have the other modality.\n \"\"\"\n\n self.filename_list_final = [filename for subject in self.subject_list for filename in self.filename_list if subject in filename]\n\n return None\n\n def var_calculation(self):\n \"\"\"\n This method calculates the variance coefficient for each subject and returns it within a dataframe.\n We compute different measures: a simple variance and a coefficient of variance. The simple variance\n is reported in the paper.\n \"\"\"\n\n #We create an empty dataframe to store the results\n self.var_df = pd.DataFrame(columns=['id_camcan', f'var_{self.modality}_{self.type}_{self.parce}_{self.net}_{self.corr}', f'coef_var_ind_{self.modality}_{self.type}_{self.parce}_{self.net}_{self.corr}'])\n\n for i in range(len(self.filename_list)):\n print(f'i={i}', flush=True)\n\n #Extracting subject ID from filenames\n sub_id = re.search(r'[0-9]{6}', self.filename_list_final[i]).group()[0:6]\n \n #Loading matrix, selecting nodes and selecting lower triangular\n matrix_file = np.loadtxt(f'{self.path_mat}/{self.filename_list[i]}', dtype=np.double)\n\n #Slice the matrix to the appropriate location\n r1 = None\n if self.type == 'within':\n submatrix1 = matrix_file[self.nodes][:, self.nodes]\n r1 = submatrix1[np.triu_indices(len(submatrix1), k=1)]\n elif self.type == 'between':\n submatrix1 = matrix_file[self.nodes][:, self.between]\n r1 = submatrix1.flatten()\n\n #Calculating the variance coefficient\n var_coef = np.var(r1)\n\n #Calculating the coefficient of variation (at the individual level)\n coef_var = np.std(r1) / np.mean(r1)\n\n #Setting the variables as a dictionary and append the row to the dataframe\n new_row = {f'{self.index}': sub_id, f'var_{self.modality}_{self.type}_{self.parce}_{self.net}_{self.corr}': var_coef, f'coef_var_ind_{self.modality}_{self.type}_{self.parce}_{self.net}_{self.corr}': coef_var}\n\n self.var_df = self.var_df.append(new_row, ignore_index=True)\n\n return None\n \n def absolute_distance(self):\n \"\"\"We try to come up with a \"between\" individual measure of the variance coefficient.\n\n Let's try simply using the distance (as would be implemented in a Mean Average Distance calculation).\n We compute both the mean and median.\n \"\"\"\n\n #First step, get the average of the variable of interest (i.e., the coefficient of variation at the individual level)\n #avg_coef_var_ind = self.var_df[f'coef_var_ind_{self.modality}_{self.parce}_{self.net}_{self.corr}'].mean()\n med_coef_var_ind = self.var_df[f'var_{self.modality}_{self.type}_{self.parce}_{self.net}_{self.corr}'].median()\n mean_coef_var_ind = self.var_df[f'var_{self.modality}_{self.type}_{self.parce}_{self.net}_{self.corr}'].mean()\n\n #Next, we create a column where we will store the \"absolute\" distance of each individual from the median.\n # In Pandas, this is simply the substraction of a Series by a scalar, which results in a Series, which we force to absolute values. \n self.var_df[f'med_dist_{self.modality}_{self.type}_{self.parce}_{self.net}_{self.corr}'] = (self.var_df[f'var_{self.modality}_{self.type}_{self.parce}_{self.net}_{self.corr}'] - med_coef_var_ind).abs()\n self.var_df[f'mean_dist_{self.modality}_{self.type}_{self.parce}_{self.net}_{self.corr}'] = (self.var_df[f'var_{self.modality}_{self.type}_{self.parce}_{self.net}_{self.corr}'] - mean_coef_var_ind).abs()\n #We add this as a column of the dataframe computed in the previous step. That way, no need to do any other modifications downstream.\n\n return None\n \n def export_df(self):\n \"\"\"\n This function simply exports the connectivity variability dataframe in a single .csv file. The script creates a folder where to store the output.\n \"\"\"\n\n #Creating filename\n final_var_filename = f'variability_{self.modality}_{self.type}_{self.parce}_{self.net}_{self.corr}'\n\n final_df = self.var_df.set_index(f\"{self.index}\")\n\n #Verifying and creating path to output\n path_var_final = f'{self.output}/{self.type}/{self.parce}/{self.corr}'\n if not os.path.exists(path_var_final):\n os.makedirs(path_var_final)\n \n #Output the csv to file\n final_df.to_csv(f'{path_var_final}/{final_var_filename}.csv')\n\n return None\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"St_Onge_2022_Fingerprinting/fc_variance/python/variance_calculator.py","file_name":"variance_calculator.py","file_ext":"py","file_size_in_byte":20027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"89544612","text":"#!/usr/bin/env python\n# encoding: utf-8\n# pylint: disable=no-member, no-init, too-many-public-methods\n# pylint: disable=attribute-defined-outside-init\n# pylint: disable=missing-docstring, unused-import, invalid-name, import-error, super-on-old-class\n\"\"\"Tests for final submissions.\"\"\"\n\nimport os\nos.environ['FLASK_CONF'] = 'TEST'\nimport datetime\nNOW = datetime.datetime.now()\n\nfrom test_base import APIBaseTestCase, unittest\n\nfrom app import models, utils, constants, api\n\nfrom google.appengine.ext import ndb\nfrom google.appengine.ext import deferred\nfrom google.appengine.ext import testbed\n\nclass FinalSubmissionTest(APIBaseTestCase):\n def get_accounts(self):\n \"\"\"\n Returns the accounts you want to exist in your system.\n \"\"\"\n keys = [\"student0\", \"student1\", \"student2\", \"staff\", \"admin\"]\n rval = {key: models.User(email=[key+\"@b.edu\"]) for key in keys}\n for k, val in rval.items():\n if 'admin' in k:\n val.is_admin = True\n return rval\n\n def setUp(self):\n super(FinalSubmissionTest, self).setUp()\n\n self.courses = {\n \"first\": models.Course(\n institution=\"UC Awesome\",\n display_name=\"First Course\",\n instructor=[self.accounts['admin'].key]),\n \"second\": models.Course(\n institution=\"UC Awesome\",\n display_name=\"Second Course\",\n instructor=[self.accounts['admin'].key]),\n }\n\n for course in self.courses.values():\n course.put()\n\n for student in [\"student0\", \"student1\", \"student2\"]:\n models.Participant.add_role(\n self.accounts[student], self.courses['first'], constants.STUDENT_ROLE)\n\n self.assignments = {\n \"first\": models.Assignment(\n name=\"first\",\n points=3,\n creator=self.accounts[\"admin\"].key,\n course=self.courses['first'].key,\n display_name=\"first display\",\n templates=\"{}\",\n max_group_size=3,\n due_date=NOW + datetime.timedelta(days=1),\n lock_date=NOW + datetime.timedelta(days=2)\n ),\n }\n for assign in self.assignments.values():\n assign.put()\n self.assign = self.assignments[\"first\"]\n\n self.backups = {\n \"first\": models.Backup(\n submitter=self.accounts[\"student0\"].key,\n assignment=self.assignments[\"first\"].key,\n messages=[models.Message(\n kind='file_contents', contents={\"trends.py\": \"\"})],\n ),\n \"second\": models.Backup(\n submitter=self.accounts[\"student1\"].key,\n assignment=self.assignments[\"first\"].key,\n messages=[models.Message(\n kind='file_contents', contents={\"trends.py\": \"\"})],\n ),\n \"third\": models.Backup(\n submitter=self.accounts[\"student2\"].key,\n assignment=self.assignments[\"first\"].key,\n messages=[models.Message(\n kind='file_contents', contents={\"trends.py\": \"\"})],\n ),\n \"late\": models.Backup(\n submitter=self.accounts[\"student0\"].key,\n assignment=self.assignments[\"first\"].key,\n server_time = datetime.datetime.now() + datetime.timedelta(days=10),\n messages=[models.Message(\n kind='file_contents', contents={\"trends.py\": \"\"})],\n ),\n\n }\n\n for backup in self.backups.values():\n backup.put()\n\n def run_deferred(self):\n \"\"\"Execute all deferred tasks.\"\"\"\n for task in self.taskqueue_stub.get_filtered_tasks():\n deferred.run(task.payload)\n\n def all_fs(self):\n return models.FinalSubmission.query().fetch()\n\n def assertNumFinalSubmissions(self, number):\n self.assertEqual(number, len(self.all_fs()))\n\n def assertNoFinalSubmissions(self):\n self.assertNumFinalSubmissions(0)\n\n def set_assignment(self, assign):\n if isinstance(assign, (str, unicode)):\n assign = self.assignments[assign]\n self.assign = assign\n\n def assertFinalSubmission(self, user, backup):\n \"\"\"\n Asserts that the |user| has the final submission which corresponds\n to |backup|.\n \"\"\"\n if isinstance(user, (str, unicode)):\n user = self.accounts[user]\n final = user.get_final_submission(self.assign.key)\n if backup:\n self.assertIsNotNone(final)\n self.assertEqual(backup, final.submission.get().backup.get())\n else:\n self.assertIsNone(final)\n\n def set_due_date(self, new_date):\n self.assign.due_date = new_date\n self.assign.put()\n\n def set_lock_date(self, lock_date):\n self.assign.lock_date = lock_date\n self.assign.put()\n\n def submit_json(self, assignment=None, messages=None):\n if not messages:\n messages = {'file_contents': {'submit': True, 'trends.py': 'hi!'}}\n\n if not assignment:\n assignment = self.assign\n\n self.post_json('/submission',\n data={'assignment': assignment.name,\n 'messages': messages})\n\n def submit(self, subm=None, is_final=True):\n \"\"\"\n Submits the given submission.\n \"\"\"\n if not subm:\n subm = self.backups['first']\n\n if not isinstance(subm, ndb.Key):\n subm = subm.key\n utils.assign_submission(subm.id(), True)\n\n def invite(self, inviter, invited):\n \"\"\"|Inviter| invites |invited| to a group for self.assign.\"\"\"\n invite_fn = models.Group.invite_to_group\n error = invite_fn(inviter.key, invited.email[0], self.assign)\n self.assertIsNone(error)\n return inviter.get_group(self.assign)\n\n def test_final_after_due_date(self):\n self.login('student0')\n self.set_due_date(NOW - datetime.timedelta(days=1))\n\n self.assertNoFinalSubmissions()\n\n # Submit\n self.submit_json()\n self.run_deferred()\n\n self.assertNoFinalSubmissions()\n\n def test_final_before_due_date(self):\n self.login('student0')\n self.set_due_date(NOW + datetime.timedelta(days=1))\n\n self.assertNoFinalSubmissions()\n\n # Submit\n self.submit()\n self.run_deferred()\n\n self.assertNumFinalSubmissions(1)\n\n def test_one_final(self):\n \"\"\"An invite/accept/exit/invite sequence keeps a final submission.\"\"\"\n self.login('student0')\n\n # Submit\n self.submit()\n self.run_deferred()\n\n finals = self.all_fs()\n self.assertEqual(1, len(finals))\n final = finals[0]\n subm = final.submission.get()\n self.assertIsNotNone(subm)\n backup = subm.backup.get()\n self.assertIsNotNone(backup)\n self.assertEqual(backup.submitter, self.user.key,\n \"{} != {}\".format(backup.submitter.get(), self.user))\n # TODO Not sure how to make/verify this final_submission get request...\n # self.assertEqual(final, self.user.get_final_submission(self.assign))\n # self.get('/user/{}/final_submission'.format(self.user.email[0]),\n # data={'assignment': self.assign.key.id()})\n\n # Invite\n #invited = self.accounts['student1']\n # TODO This post is being made with admin as the user; not sure why...\n #self.post_json('/assignment/{}/invite'.format(self.assign.key.id()),\n # data={'email': invited.email[0]})\n # TODO Check final submissions\n\n # Accept\n # TODO\n\n # Exit\n # TODO\n\n # Invite\n # TODO\n\n def test_set_different_submission_as_final_submission(self):\n self.login('student0')\n\n self.assertNoFinalSubmissions()\n\n # Submit\n self.submit()\n self.run_deferred()\n self.assertNumFinalSubmissions(1)\n\n self.logout()\n self.login('student1')\n self.set_due_date(NOW - datetime.timedelta(days=1))\n self.submit(self.backups['second'])\n self.run_deferred()\n\n self.assertNumFinalSubmissions(1)\n\n subm = models.Submission.query(\n models.Submission.backup == self.backups['second'].key\n ).get()\n\n api.FinalSubmissionAPI().post(\n self.user,\n dict(submission=subm.key))\n\n self.assertFinalSubmission(self.user, self.backups['second'])\n\n def test_set_different_backup_as_final_submission(self):\n self.login('student0')\n\n self.assertNoFinalSubmissions()\n\n # Submit\n self.submit()\n self.run_deferred()\n self.assertNumFinalSubmissions(1)\n\n self.logout()\n self.login('student1')\n self.set_due_date(NOW - datetime.timedelta(days=1))\n self.submit(self.backups['second'])\n self.run_deferred()\n\n self.assertNumFinalSubmissions(1)\n\n subm = models.Submission(backup=self.backups['second'].key)\n subm.put()\n\n api.FinalSubmissionAPI().post(self.user, dict(submission=subm.key))\n self.assertFinalSubmission(self.user, self.backups['second'])\n\n def test_revise_final_submission(self):\n self.login('student0')\n\n self.assertNoFinalSubmissions()\n\n # Submit\n self.submit(self.backups['first'])\n self.run_deferred()\n self.assertNumFinalSubmissions(1)\n self.assign.revision = True\n self.assign.put()\n self.set_due_date(NOW - datetime.timedelta(days=2))\n self.set_lock_date(NOW - datetime.timedelta(days=1))\n # This backup is now late (ignore the fact that it's the same backup)\n\n subm = models.Submission(backup=self.backups['late'].key)\n subm.put()\n\n api.FinalSubmissionAPI().post(self.user, dict(submission=subm.key))\n self.assertFinalSubmission(self.user, self.backups['first'])\n # Ensure the right revision is stored.\n fs = self.all_fs()[0]\n self.assertEqual(fs.revision, subm.key)\n\n\n def test_revisions_closed_final_submission(self):\n self.login('student0')\n self.assertNoFinalSubmissions()\n\n # Submit\n self.submit(self.backups['first'])\n self.run_deferred()\n self.assertNumFinalSubmissions(1)\n self.assign.revision = True\n self.assign.put()\n self.set_due_date(NOW - datetime.timedelta(days=2))\n self.set_lock_date(NOW - datetime.timedelta(days=1))\n # This backup is now late - but can be submitted as a revision\n subm = models.Submission(backup=self.backups['late'].key)\n subm.put()\n\n api.FinalSubmissionAPI().post(self.user, dict(submission=subm.key))\n self.assertFinalSubmission(self.user, self.backups['first'])\n # Ensure the right revision is stored.\n fs = self.all_fs()[0]\n self.assertEqual(fs.revision, subm.key)\n origRevision = subm\n\n # Close revision period\n self.assign.revision = False\n self.assign.put()\n # This backup is now late - and can't be submitted as a revision\n subm = models.Submission(backup=self.backups['first'].key)\n subm.put()\n try:\n api.FinalSubmissionAPI().post(self.user, dict(submission=subm.key))\n except ValueError as e:\n self.assertEqual(str(e), 'Cannot change submission after due date')\n\n self.set_lock_date(NOW + datetime.timedelta(days=1))\n\n\n api.FinalSubmissionAPI().post(self.user, dict(submission=subm.key))\n self.assertFinalSubmission(self.user, self.backups['first'])\n self.assertNumFinalSubmissions(1)\n # Ensure the right revision is stored.\n fs = self.all_fs()[0]\n self.assertEqual(fs.revision, origRevision.key)\n\n def test_create_group(self):\n \"\"\"Merging groups keeps the final submission for that group.\"\"\"\n self.submit(self.backups['first'])\n self.assertFinalSubmission('student0', self.backups['first'])\n self.assertFinalSubmission('student1', None)\n\n members = [self.accounts[s].key for s in ('student0', 'student1')]\n models.Group(assignment=self.assign.key, member=members).put()\n for member in members:\n member.get().update_final_submission(self.assign)\n\n self.assertFinalSubmission('student0', self.backups['first'])\n self.assertFinalSubmission('student1', self.backups['first'])\n\n def test_invite(self):\n \"\"\"Final submission updates when a group is created.\"\"\"\n self.submit(self.backups['first'])\n self.submit(self.backups['second'])\n self.assertFinalSubmission('student0', self.backups['first'])\n self.assertFinalSubmission('student1', self.backups['second'])\n\n inviter, invited = [self.accounts[s] for s in ('student0', 'student1')]\n self.invite(inviter, invited)\n\n self.assertFinalSubmission('student0', self.backups['first'])\n self.assertFinalSubmission('student1', self.backups['second'])\n final = inviter.get_final_submission(self.assign)\n self.assertIsNotNone(final.group)\n\n def test_accept(self):\n \"\"\"Only one final submission after a group is formed.\"\"\"\n self.submit(self.backups['first']) # earlier (discard)\n self.submit(self.backups['second']) # later (keep)\n self.assertFinalSubmission('student0', self.backups['first'])\n self.assertFinalSubmission('student1', self.backups['second'])\n self.assertEqual(2, len(models.FinalSubmission.query().fetch()))\n\n inviter, invited = [self.accounts[s] for s in ('student0', 'student1')]\n group = self.invite(inviter, invited)\n self.assertIsNone(group.accept(invited))\n\n self.assertFinalSubmission('student0', self.backups['second'])\n self.assertFinalSubmission('student1', self.backups['second'])\n self.assertEqual(1, len(models.FinalSubmission.query().fetch()))\n\n def test_decline(self):\n \"\"\"Final submissions are separate after a declined invitation.\"\"\"\n self.submit(self.backups['first'])\n self.submit(self.backups['second'])\n\n inviter, invited = [self.accounts[s] for s in ('student0', 'student1')]\n group = self.invite(inviter, invited)\n self.assertIsNone(group.exit(invited))\n self.assertIsNone(inviter.get_group(self.assign))\n self.assertIsNone(invited.get_group(self.assign))\n\n self.assertFinalSubmission('student0', self.backups['first'])\n self.assertFinalSubmission('student1', self.backups['second'])\n self.assertEqual(2, len(models.FinalSubmission.query().fetch()))\n self.assertIsNone(inviter.get_final_submission(self.assign).group)\n self.assertIsNone(invited.get_final_submission(self.assign).group)\n\n def test_exit(self):\n \"\"\"A new final submission is created for an exiting member.\"\"\"\n self.submit(self.backups['first'])\n self.submit(self.backups['second'])\n self.assertEqual(2, len(models.FinalSubmission.query().fetch()))\n\n # Invite and accept\n inviter, invited = [self.accounts[s] for s in ('student0', 'student1')]\n group = self.invite(inviter, invited)\n self.assertIsNone(group.accept(invited))\n self.assertEqual(1, len(models.FinalSubmission.query().fetch()))\n\n self.assertIsNone(group.exit(inviter))\n\n self.assertFinalSubmission('student0', self.backups['first'])\n self.assertFinalSubmission('student1', self.backups['second'])\n self.assertEqual(2, len(models.FinalSubmission.query().fetch()))\n self.assertIsNone(inviter.get_final_submission(self.assign).group)\n self.assertIsNone(invited.get_final_submission(self.assign).group)\n\n ##############\n # SUBMIT NDB #\n ##############\n\n def test_ndb_submit(self):\n \"\"\" test backup modifications by ndb submit \"\"\"\n datestr = '2015-04-20 00:00:00'\n datestr_converted = '2015-04-20 07:00:00' # because GAE is stubborn\n backup = api.SubmitNDBImplementation().create_submission(\n self.accounts['student0'],\n self.assignments['first'],\n {'analytics': {'time': datestr}},\n True,\n self.accounts['student0'])\n self.assertEqual(backup.created, datetime.datetime.strptime(datestr_converted, '%Y-%m-%d %H:%M:%S'))\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"server/tests/integration/test_final_submissions.py","file_name":"test_final_submissions.py","file_ext":"py","file_size_in_byte":16534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"173403941","text":"import requests\nimport os\nimport config\nfrom requests.exceptions import RequestException\n\n\ndef get_html(): #get html page code and save to file\n\turl = 'https://movie.douban.com/top250'\n\theaders = {\n\t\"User-Agent\": \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0\",\n\t}\n\ttry:\n\t\tresponse =requests.get(url,headers = headers)\n\t\tresponse.encoding = \"utf-8\" \n\t\tis_exit = os.path.exists(os.path.split(config.filename)[0])\n\t\tif not is_exit:\n\t\t\tos.makedirs(os.path.split(config.filename)[0]) #create folder\n\t\t\tos.mknod(config.filename) # create file\n\t\tif response.status_code == 200: # status code is 200 \n\t\t\twith open(config.filename,'w') as f: # write pagesource to file\n\t\t\t\tf.write(response.text) \n\t\telse:\n\t\t\treturn None\n\texcept RequestException:\n\t\tprint(\"request error\")\n\t\treturn None\n\n\ndef read_html(): # return source code from file\n\twith open(config.filename,'r') as f:\n\t\tresult = f.read()\n\treturn result\n","sub_path":"top250/save_html.py","file_name":"save_html.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"366665745","text":"# 12 (Finding the factors of an integer) ​q12_find_factors.py\n# Write a program that reads an integer and displays all its smallest factors. For example, if the\n# input integer is 120, the output should be as follows: 2, 2, 2, 3, 5.\n\n\nprint(\"Welcome to factor finder!\")\nnumber = int(input(\"Enter a number!\"))\nfactors = []\na = 2\nb = 2\n\n\nwhile number > b:\n if number % b == 0 & b != number:\n if number % a == 0:\n while number % a == 0:\n factors.append(a)\n number = number / a\n else:\n a = a + 1\n else:\n print(\"Factors =\", factors)\n break\n\nprint(\"Factors =\", factors)\n","sub_path":"​q12_find_factors.py","file_name":"​q12_find_factors.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"168571393","text":"#!/usr/bin/env python\n# coding=utf-8\n###############################################\n# File Name: DeconvNet2D.py\n# Author: Liang Jiang\n# mail: jiangliang0811@gmail.com\n# Created Time: Sun 30 Oct 2016 09:52:15 PM CST\n# Description: Code for Deconvnet based on keras\n###############################################\nimport keras.backend as K\n\nimport numpy as np\nfrom PIL import Image\n\nimport deconvnet\nfrom deconvnet.layers import *\nfrom keras.layers import *\n\n\ndef argparser():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('image', help='Path of image to visualize')\n parser.add_argument('--layer_name', '-l',\n action='store', dest='layer_name',\n default='block5_conv1', help='Layer to visualize')\n parser.add_argument('--feature', '-f',\n action='store', dest='feature',\n default=0, type=int, help='Feature to visualize')\n parser.add_argument('--mode', '-m', action='store', dest='mode',\n choices=['max', 'all'], default='max',\n help='Visualize mode, \\'max\\' mode will pick the greatest \\\n activation in the feature map and set others to zero, \\\n \\'all\\' mode will use all values in the feature map')\n return parser\n\n\ndef main():\n import sys\n import vgg16\n import imagenet_utils\n # from keras.applications import vgg16, imagenet_utils\n parser = argparser()\n args = parser.parse_args()\n image_path = args.image\n layer_name = args.layer_name\n feature_to_visualize = args.feature\n visualize_mode = args.mode\n\n model = vgg16.VGG16(weights='imagenet', include_top=False)\n layer_dict = dict([(layer.name, layer) for layer in model.layers])\n if not layer_name in layer_dict:\n print('Wrong layer name')\n sys.exit()\n\n # Load data and preprocess\n img = Image.open(image_path)\n img_array = np.array(img)\n if K.image_dim_ordering() == 'th':\n img_array = np.transpose(img_array, (2, 0, 1))\n img_array = img_array[np.newaxis, :]\n img_array = img_array.astype(np.float)\n img_array = imagenet_utils.preprocess_input(img_array)\n\n deconv_network = deconvnet.model.DeconvNetModel(model)\n deconv = deconv_network.deconvolve_feature_map(\n img_array, layer_name, feature_to_visualize, visualize_mode\n )\n\n deconv = deconv - deconv.min()\n deconv *= 1.0 / (deconv.max() + 1e-8)\n if K.image_dim_ordering() == 'th':\n deconv = np.transpose(deconv, (1, 2, 0))\n\n deconv = deconv[:, :, ::-1]\n uint8_deconv = (deconv * 255).astype(np.uint8)\n img = Image.fromarray(uint8_deconv, 'RGB')\n img.save('results/{}_{}_{}.png'.format(layer_name, feature_to_visualize,\n visualize_mode))\n\n\nif \"__main__\" == __name__:\n main()\n","sub_path":"Deconvnet-keras.py","file_name":"Deconvnet-keras.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"365078995","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\nScript Header\n\n$Id: $ US22243\n\nCopyright (c) 2016 Cisco Systems, Inc.\n\nName:\n cmCC22243_3pcc_BS_IOT_Interop_108_CallForwardAlways.py\n\nPurpose:\n This test scenario verifies the DUT’s Call Forward Always\n service for interoperability with BroadWorks.\n\nAuthor:\n Sinja Satheesh P (spoothat@cisco.com)\n\nReferences:\n BW-SIPPhone-InteropTestPlan-R21.0\n\nDescription:\n Enable CFwdALL service and set call forward target value through web\n Calls to DUT should get forwarded to the call forward all\n target set to web.\n\nTest bed requirement:\n 1: 3 3pcc phones\n 2: All phones should register successfully before running script\n\nTest Steps:\n 1. Enable CFwdALL service through web .\n 2. On PhoneA which is the DUT, set CFwdALL target value to Phone C number.\n 3. Make a call from Phone B to DUT. The call should be\n forwarded to Phone C.\n 4. Verify the SIP signaling from the DUT.\n − DUT sends a SIP 3XX response to BroadWorks, such as 302 Redirect.\n − BroadWorks responds with ACK\n\nKnown Bugs:\n\"\"\"\nimport tng\nimport logging\nfrom tng_sl.device.endpoint.synergylite.synergylite_3pcc_extended\\\n import wait_for_ccapi_call_states\nfrom tng_sl.contrib.mpp.phone_line_reg_helper import PhoneLineRegHelper\nfrom tng_sl.contrib.mpp.phone_line_reg_helper import PhoneConfigHelper\nfrom tng_sl.contrib.mpp.broadsoft_login_helper import BroadsoftLoginHelper\nfrom tng_sl.contrib.setup_helper import SetupHelpersTestCase\nfrom tng_sl.contrib.mpp.tshark_helper import TsharkHelper\n\nlog = logging.getLogger('CallForwardAlways')\n\n\nclass CallForwardAlways(SetupHelpersTestCase, tng.api.TestCase):\n helpers = (\n PhoneConfigHelper, BroadsoftLoginHelper, PhoneLineRegHelper,\n TsharkHelper)\n helper_num_devices = 3\n\n def setUp(self):\n log.info(\"Start of setUp\")\n self.serverproxy = self.toolkit.get_test_env_info(\n section='bsoft', parameter_name=\"as_ip_addr\")\n\n def config_and_verify_phone_web_parameters():\n # Enable CFwd Service and Provide Forward number\n self.oPhone1.ui.set_web_parameter_http(\n CfwdAllServ=['Phone', 'Cfwd All Serv', 1],\n CfwdSetting=['User', 'Cfwd Setting', 1],\n CfwdAllDest=['User', 'Cfwd All Dest', self.user_id3])\n # verify the values are set in webpage\n config_parm = self.oPhone1.get_web_config(\n 'Cfwd_All_Serv', 'Cfwd_Setting', 'Cfwd_All_Dest')\n self.assertEqual(\n config_parm[0], \"Yes\",\n \"Call Forward service is not enabled on Phone1\")\n self.assertEqual(\n config_parm[1], \"Yes\",\n \"Call Forward Setting is not enabled on Phone1\")\n self.assertEqual(\n config_parm[2], self.user_id3,\n \"Call Forward destination is not set on Phone1\")\n\n self.oPhone1.ui.set_web_parameter_http(\n Feature_key_sync=['Ext 1', 'Feature Key Sync', 0])\n verify_fks = self.oPhone1.ui.get_web_parameter_http(\n 'Ext 1',\n 'Feature Key Sync')\n self.assertEqual(\"0\", verify_fks)\n config_and_verify_phone_web_parameters()\n\n def remove_cfwd():\n log.info(\"Remove the Forward Number\")\n self.oPhone1.ui.set_web_parameter_http(\n CfwdAllDest=['User', 'Cfwd All Dest', ''])\n verify = self.oPhone1.ui.get_web_parameter_http(\n 'User', 'Cfwd All Dest')\n self.assertEqual(verify, '', \"Cfwd All Dest value not removed\")\n self.addCleanup(remove_cfwd)\n\n log.info(\"End of setUp\")\n\n def test_call_forward_always(self):\n log.info(\"Start of test_call_forward_always\")\n\n log.info('STEP3: Start tshark on linux')\n dut_ip = self.oPhone1.get_phone_ip()\n filter_cmd = 'port sip and host ' + dut_ip\n capture_file = self.tshark.tshark_start(filter_cmd)\n\n log.info(\"STEP4: Phone2 dial Phone1 number: {}\".format(self.user_id1))\n self.oPhone2.ccapi.dial('null', self.user_id1, '', 1, 0, 1)\n\n # check phone2 ringout status and Phone3 ringing status\n wait_for_ccapi_call_states(\n self.devices, (\"IDLE\", \"PROCEEDING\", \"RINGING\"), timeout=20)\n log.info(\"STEP5: Phone3 receive the call\")\n self.oPhone3.ccapi.accept(\"0000\")\n # check phone2 and phone3 are in connected status\n wait_for_ccapi_call_states(\n self.devices, (\"IDLE\", \"CONNECTED\", \"CONNECTED\"))\n self.oPhone2.ccapi.hangUp('0000')\n wait_for_ccapi_call_states(self.devices, (\"IDLE\", \"IDLE\", \"IDLE\"))\n\n log.info('STEP6: Stop tshark on linux')\n self.tshark.tshark_stop()\n # analyse tshark capture\n log.info('STEP7: Start tshark Analysis')\n received_msgs = self.tshark.tshark_read(\n file=capture_file, protocol='sip')\n expected_msgs = {\n 'frame_src': [dut_ip, self.serverproxy],\n 'frame_dst': [self.serverproxy, dut_ip],\n 'frame_proto': ['SIP']*2,\n 'frame_data': ['Status: 302 Moved Temporarily', 'Request: ACK']}\n result_src = self.tshark.tshark_call_flow(\n expected=expected_msgs, received=received_msgs)\n self.assertTrue(result_src, \"Forward Status flow not match\")\n log.info(\"Successfully verified traces for Call Forward Always\")\n log.info(\"Tshark analysis stopped\")\n log.info(\"End of test_call_forward_always\")\n\n\n# this is called by 'tng run'\ndef main():\n tng.api.runner()\n\nif __name__ == '__main__':\n tng.run(main)\n","sub_path":"common/IOT/Broadsoft_Interop/section_7/cc_basic/cmCC22243_3pcc_BS_IOT_Interop_108_CallForwardAlways.py","file_name":"cmCC22243_3pcc_BS_IOT_Interop_108_CallForwardAlways.py","file_ext":"py","file_size_in_byte":5659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"349172809","text":"# coding=utf-8\nfrom django.views.decorators.csrf import csrf_exempt, csrf_protect\nimport os\n# 工具函数导入\nfrom webapi.tools import random_str, pack, tokenActive\nimport time\nimport subprocess\nimport chardet\nfrom Conline.settings import BASE_DIR\n\n# model导入\nfrom webapi.models import Homework, User\n\n# 日志导入\nfrom webapi.tools import log\n\n\n# 创建题目\n@csrf_exempt\ndef creatHomework(request):\n try:\n body = eval(request.body)\n user = tokenActive(request.COOKIES)\n if not isinstance(user, User):\n pack(code=user)\n id = random_str()\n now = int(1000 * time.time())\n user = Homework(homeworkid=id, title=body['title'], creator=user.userid, type=body['type'], creattime=now, father=body['father'])\n if body['type'] != '2' and body['type'] != 2:\n user.answer = body['answer']\n if body['type'] == '0' or body['type'] == 0:\n user.option = body['option']\n if body['type'] == '2' or body['type'] == 2:\n user.input = body['input']\n user.output = body['output']\n user.save()\n return pack(data={'homeworkid': id})\n except Exception as e:\n return pack(msg=e)\n\n\n# 获取题目\n@csrf_exempt\ndef getHomework(request):\n try:\n body = eval(request.body)\n homework = list(Homework.objects.all().filter(homeworkid=body['homeworkid']))\n if len(homework) == 0:\n raise Exception('题目id错误')\n return pack(data=homeworkModel(homework))\n except Exception as e:\n return pack(msg=e)\n\n\n# 获取作者题目列表\n@csrf_exempt\ndef getHomeworkByUser(request):\n try:\n body = eval(request.body)\n homeworklist = list(Homework.objects.all().filter(creator=body['userid']))\n if len(homeworklist) == 0:\n return pack(data=[], msg='未获取到数据')\n for homework in homeworklist:\n homework = homeworkModel(homework)\n return pack(data=homeworklist)\n except Exception as e:\n return pack(msg=e)\n\n\n# 获取章节题目列表\n@csrf_exempt\ndef getHomeworkBySection(request):\n try:\n model = []\n body = eval(request.body)\n homeworklist = list(Homework.objects.all().filter(father=body['sectionid']))\n if len(homeworklist) == 0:\n return pack(data=[], msg='未获取到数据')\n for homework in homeworklist:\n model.append(homeworkModel(homework))\n return pack(data=model)\n except Exception as e:\n return pack(msg=e)\n\n\n# 程序题运行\n@csrf_exempt\ndef codeRun(request):\n try:\n body = eval(request.body)\n code = body['code']\n id = body['homeworkid']\n sfile = BASE_DIR + '/static/c/' + random_str() + '.c'\n with open(sfile, 'w') as cfile:\n cfile.write(code)\n cfile.close()\n dist = BASE_DIR + '/static/c/' + random_str()\n # 编译程序\n gcc = subprocess.Popen(['gcc', sfile, '-o', dist], stderr=subprocess.PIPE)\n gcc.wait()\n if gcc.stderr.read() != '':\n log('error: '+gcc.stderr.read())\n raise Exception('编译出错')\n log('source ' + sfile + '\\n' + dist)\n homework = list(Homework.objects.filter(homeworkid=id))[0]\n inputlist = eval(homework.input)\n outputlist = eval(homework.output)\n # 记录正确与否的list\n resultlist = []\n # 循环执行\n for input in inputlist:\n p = subprocess.Popen(dist, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n p.stdin.write(input + '\\n')\n p.wait()\n # 如果出错,那么记录错误\n result = p.stdout.read()\n if result != '':\n # 获取编码\n # encoding = chardet.detect(result)['encoding']\n # 转码\n # result = result.decode(encoding).encode('utf-8')\n if p.stderr.read() != '':\n raise Exception('type error')\n # 正确的话,记录正确\n elif result == outputlist[inputlist.index(input)]:\n resultlist.append(True)\n else:\n resultlist.append(False)\n os.remove(sfile)\n os.remove(dist)\n return pack(data=resultlist)\n except Exception as e:\n os.remove(sfile)\n return pack(msg=e)\n\n\n@csrf_exempt\ndef moban(request):\n try:\n body = eval(request.body)\n\n except Exception as e:\n return pack(msg=e)\n\n\ndef homeworkModel(homework):\n return {\n 'homeworkid': homework.homeworkid,\n 'title': homework.title,\n 'creator': homework.creator,\n 'type': homework.type,\n 'answer': homework.answer,\n 'option': homework.option\n }\n","sub_path":"Conline/webapi/views/homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":4815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"467446851","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/edill/mc/lib/python3.5/site-packages/skxray/io/gsas_file_reader.py\n# Compiled at: 2016-03-04 05:19:32\n# Size of source mod 2**32: 8933 bytes\n\"\"\"\n This is the module for reading files created in GSAS file formats\n https://subversion.xor.aps.anl.gov/trac/pyGSAS\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\nimport six, os, numpy as np\n\ndef gsas_reader(file):\n \"\"\"\n Parameters\n ----------\n file: str\n GSAS powder data file\n\n Returns\n --------\n tth : ndarray\n twotheta values (degrees) shape (N, ) array\n\n intensity : ndarray\n intensity values shape (N, ) array\n\n err : ndarray\n error value of intensity shape(N, ) array\n \"\"\"\n if os.path.splitext(file)[1] != '.gsas':\n raise IOError('Provide a file with diffraction data saved in GSAS, file extension has to be .gsas ')\n with open(file, 'r') as (fi):\n S = fi.readlines()[1]\n mode = S.split()[9]\n try:\n tth, intensity, err = _func_look_up[mode](file)\n except KeyError:\n raise ValueError(\"Provide a correct mode of the GSAS file, file modes could be in 'STD', 'ESD', 'FXYE' \")\n\n return (\n tth, intensity, err)\n\n\ndef _get_fxye_data(file):\n \"\"\"\n Parameters\n ----------\n file: str\n GSAS powder data file\n\n Return\n ------\n tth : ndarray\n twotheta values (degrees) shape (N, ) array\n\n intensity : ndarray\n intensity values shape (N, ) array\n\n err : ndarray\n error value of intensity shape(N, ) array\n\n \"\"\"\n tth = []\n intensity = []\n err = []\n with open(file, 'r') as (fi):\n S = fi.readlines()[2:]\n for line in S:\n vals = line.split()\n tth.append(float(vals[0]))\n f = float(vals[1])\n s = float(vals[2])\n if f <= 0.0:\n intensity.append(0.0)\n else:\n intensity.append(float(vals[1]))\n if s > 0.0:\n err.append(1.0 / float(vals[2]) ** 2)\n else:\n err.append(0.0)\n\n return [\n np.array(tth), np.array(intensity), np.array(err)]\n\n\ndef _get_esd_data(file):\n \"\"\"\n Parameters\n ----------\n file: str\n GSAS powder data file\n\n Return\n ------\n tth : ndarray\n twotheta values (degrees) shape (N, ) array\n\n intensity : ndarray\n intensity values shape (N, ) array\n\n err : ndarray\n error value of intensity shape(N, ) array\n\n \"\"\"\n tth = []\n intensity = []\n err = []\n with open(file, 'r') as (fi):\n S = fi.readlines()[1:]\n start = float(S[0].split()[5]) / 100.0\n step = float(S[0].split()[6]) / 100.0\n j = 0\n for line in S[1:]:\n for i in range(0, 80, 16):\n xi = start + step * j\n yi = _sfloat(line[i:i + 8])\n ei = _sfloat(line[i + 8:i + 16])\n tth.append(xi)\n if yi > 0.0:\n intensity.append(yi)\n else:\n intensity.append(0.0)\n if ei > 0.0:\n err.append(1.0 / ei ** 2)\n else:\n err.append(0.0)\n j += 1\n\n N = len(tth)\n return [np.array(tth), np.array(intensity), np.array(err)]\n\n\ndef _get_std_data(file):\n \"\"\"\n Parameters\n ----------\n file: str\n GSAS powder data file\n\n Return\n ------\n tth : ndarray\n twotheta values (degrees) shape (N, ) array\n\n intensity : ndarray\n intensity values shape (N, ) array\n\n err : ndarray\n error value of intensity shape(N, ) array\n\n \"\"\"\n tth = []\n intensity = []\n err = []\n with open(file, 'r') as (fi):\n S = fi.readlines()[1:]\n start = float(S[0].split()[5]) / 100.0\n step = float(S[0].split()[6]) / 100.0\n nch = float(S[0].split()[2])\n j = 0\n for line in S[1:]:\n for i in range(0, 80, 8):\n xi = start + step * j\n ni = max(_sint(line[i:i + 2]), 1)\n yi = max(_sfloat(line[i + 2:i + 8]), 0.0)\n if yi:\n vi = yi / ni\n else:\n yi = 0.0\n vi = 0.0\n if j < nch:\n tth.append(xi)\n if vi <= 0.0:\n intensity.append(0.0)\n err.append(0.0)\n else:\n intensity.append(yi)\n err.append(1.0 / vi)\n j += 1\n\n N = len(tth)\n return [np.array(tth), np.array(intensity), np.array(err)]\n\n\n_func_look_up = {'STD': _get_std_data, 'ESD': _get_esd_data, 'FXYE': _get_fxye_data}\n\ndef _sfloat(S):\n \"\"\"\n convert a string to a float, treating an all-blank string as zero\n Parameter\n ---------\n S : str\n string that need to be converted as float treating an\n all-blank string as zero\n\n Returns\n -------\n float or zero\n \"\"\"\n if S.strip():\n return float(S)\n else:\n return 0.0\n\n\ndef _sint(S):\n \"\"\"\n convert a string to an integer, treating an all-blank string as zero\n Parameter\n ---------\n S : str\n string that need to be converted as integer treating an all-blank\n strings as zero\n\n Returns\n -------\n integer or zero\n \"\"\"\n if S.strip():\n return int(S)\n else:\n return 0","sub_path":"pycfiles/scikit-xray-0.0.5.post0.linux-x86_64.tar/gsas_file_reader.cpython-35.py","file_name":"gsas_file_reader.cpython-35.py","file_ext":"py","file_size_in_byte":5617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"535413713","text":"#coding:utf-8\n#这个文档讲述split用法\nimport tensorflow as tf\n\n'''\nsplit(value, num_or_size_splits, axis=0, num=None, name=\"split\")\nvalue是要分割的张量,num_orsize_splits是要分割多少维,axis是对value的第几维进行分割\neg:\n'value' is a tensor with shape [5, 30]\n# Split 'value' into 3 tensors with sizes [4, 15, 11] along dimension 1\nsplit0, split1, split2 = tf.split(value, [4, 15, 11], 1)\ntf.shape(split0) ==> [5, 4]\ntf.shape(split1) ==> [5, 15]\ntf.shape(split2) ==> [5, 11]\n# Split 'value' into 3 tensors along dimension 1\nsplit0, split1, split2 = tf.split(value, num_or_size_splits=3, axis=1)\ntf.shape(split0) ==> [5, 10]\n'''\n\nt = tf.Variable(tf.constant(1,dtype=tf.int32,shape=[9,6,30,60]))\nprint(t)\nt1 = tf.split(t,3,0)\nprint(t1)","sub_path":"st_tf_split.py","file_name":"st_tf_split.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"462250522","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# noinspection PyPep8\n\"\"\"\nGet a W3C TR document based on its URI and dump it into an EPUB3 file for off-line reading.\n\nIt is a bit like the browser archive commands, but the result is an EPUB3 file. Stylesheets and images are\ndownloaded and included in the book, provided they are on the same Web domain as the original file (i.e., in Python's URL\nlibrary speak, if the URL-s of those resources have the same net location, i.e., ``netloc``).\n\nUsage::\n\n\tdoc2epub.py URI\n\nThe result is an EPUB3 in the same folder, whose name is the last part of the URI, expanded with the ``.epub`` suffix.\n\nThe program depends on the html5lib library for HTML parsing.\n\n.. autodata::\n\"\"\"\n# TODO: handle the possible css references to other css files or to images\n\n# noinspection PyPep8Naming\nfrom urlparse import urlparse\nimport zipfile\nimport html5lib\nfrom xml.etree.ElementTree import ElementTree\n\nfrom .templates import meta_inf, BOOK_CSS\nfrom .document import DocumentWrapper\nfrom .package import Package\n\nfrom .utils import HttpSession, et_to_book\n\n# These are the items that have to be added to each file and package, no matter what: (id,file,media-type,properties)\n# noinspection PyPep8\n#: Items that have to be added to the book's manifest, no matter; tuples of the form (id,file,media-type,properties)\n_DEFAULT_FILES = [\n\t\t(\"nav.xhtml\", \"application/xhtml+xml\", \"nav\", \"nav\"),\n\t\t(\"toc.ncx\", \"application/x-dtbncx+xml\", \"ncx\", \"\"),\n\t\t(\"cover.xhtml\", \"application/xhtml+xml\", \"cover\", \"\"),\n\t\t(\"Assets/w3c_main.png\", \"image/png\", \"w3c_main\", \"\"),\n\t\t(\"Assets/base.css\", \"text/css\", \"StyleSheets-base\", \"\"),\n\t\t(\"Assets/book.css\", \"text/css\", \"StyleSheets-book\", \"\")\n]\n\n# noinspection PyPep8,PyPep8,PyPep8\n_To_transfer = [\n\t(\"http://www.w3.org/Icons/w3c_main.png\", \"Assets/w3c_main.png\"),\n\t(\"http://www.w3.org/StyleSheets/TR/base.css\", \"Assets/base.css\"),\n]\n\n# noinspection PyPep8\n_CSS_LOGOS = {\n\t\"REC\" : (\"http://www.w3.org/StyleSheets/TR/logo-CR.png\", \"Assets/logo-REC.png\"),\n\t\"NOTE\" : (\"http://www.w3.org/StyleSheets/TR/logo-CR.png\", \"Assets/logo-NOTE.png\"),\n\t\"PR\" : (\"http://www.w3.org/StyleSheets/TR/logo-CR.png\", \"Assets/logo-PR.png\"),\n\t\"CR\" : (\"http://www.w3.org/StyleSheets/TR/logo-CR.png\", \"Assets/logo-CR.png\"),\n\t\"WD\" : (\"http://www.w3.org/StyleSheets/TR/logo-CR.png\", \"Assets/logo-WD.png\"),\n}\n\n\n###################################################################################\nclass DocToEpub:\n\t\"\"\"\n\tTop level entry to the program; receives the URI to be retrieved\n\n\t:param str top_uri: the URI that was used to invoke the package, ie, the location of the document source\n\t\"\"\"\n\tdef __init__(self, top_uri):\n\t\tself._html = None\n\t\tself._document = None\n\t\tself._document_wrapper = None\n\t\tself._top_uri = top_uri\n\t\tself._book = None\n\t\tself._domain = urlparse(top_uri).netloc\n\n\t@property\n\tdef domain(self):\n\t\t\"\"\"Domain of the URI's home\"\"\"\n\t\treturn self._domain\n\n\t@property\n\tdef document(self):\n\t\t\"\"\"Document, as parsed; an :py:class:`xml.etree.ElementTree.Element` instance\"\"\"\n\t\treturn self._document\n\n\t@property\n\tdef document_wrapper(self):\n\t\t\"\"\"Wrapper around the document, containg extra meta information for packaging\"\"\"\n\t\treturn self._document_wrapper\n\n\t@property\n\tdef html(self):\n\t\t\"\"\"HTML element as parsed; :py:class:`xml.etree.ElementTree.ElementTree` instance\"\"\"\n\t\treturn self._html\n\n\t@property\n\tdef top_uri(self):\n\t\t\"\"\"Top level URI for the file to be processed\"\"\"\n\t\treturn self._top_uri\n\n\t@property\n\tdef book(self):\n\t\t\"\"\"The book to be generated; an open :py:class:`zipfile.ZipFile` instance\"\"\"\n\t\treturn self._book\n\n\tdef process(self):\n\t\t\"\"\"\n\t\tProcess the book, ie, extract whatever has to be extracted and produce the epub file\n\t\t\"\"\"\n\t\tsession = HttpSession(self.top_uri, accepted_media_types=[\"text/html\", \"application/xhtml+xml\"], raise_exception=True)\n\n\t\t# Parse the main document\n\t\tself._html = html5lib.parse(session.data, namespaceHTMLElements=False)\n\t\tself._document = ElementTree(self.html)\n\n\t\t# Create the wrapper around the parsed version. Initialization will also\n\t\t# retrieve the various 'meta' data from the document, like title, editors, document type, etc.\n\t\t# It is important to get these metadata before the real processing because, for example, the\n\t\t# 'short name' will also be used for the name of the final book\n\t\tself._document_wrapper = DocumentWrapper(self)\n\n\t\t# The extra css file must be added to the book; the content is actually dependent on the type of the\n\t\t# document\n\t\twith zipfile.ZipFile(self.document_wrapper.short_name + '.epub', 'w', zipfile.ZIP_DEFLATED) as self._book:\n\t\t\t# Initialize the book\n\t\t\tself.book.writestr('mimetype', 'application/epub+zip', zipfile.ZIP_STORED)\n\t\t\tself.book.writestr('META-INF/container.xml', meta_inf)\n\n\t\t\t# Add the book.css with the right value set for the background image\n\t\t\tif self.document_wrapper.doc_type in _CSS_LOGOS:\n\t\t\t\turi, local = _CSS_LOGOS[self.document_wrapper.doc_type]\n\t\t\t\tself.book.writestr('Assets/book.css', BOOK_CSS % local[7:])\n\t\t\t\t_To_transfer.append((uri, local))\n\n\t\t\t# Some resources should be added to the book once and for all\n\t\t\tfor uri, local in _To_transfer:\n\t\t\t\tlocal_session = HttpSession(uri)\n\t\t\t\tlocal_session.store_in_book(self.book, local)\n\n\t\t\t# Massage the document by extracting extra resources, set the right CSS, etc\n\t\t\tself.document_wrapper.process()\n\n\t\t\t# The main content should be stored in the target book\n\t\t\tet_to_book(self.document, 'Overview.xhtml', self.book)\n\n\t\t\tPackage(self).process()\n","sub_path":"tr2epub/simple/doc2epub.py","file_name":"doc2epub.py","file_ext":"py","file_size_in_byte":5467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"91771196","text":"import json\nfrom copy import deepcopy\n\nimport pytest\n\nfrom cloudshell.shell.flows.connectivity.exceptions import ApplyConnectivityException\nfrom cloudshell.shell.flows.connectivity.models.connectivity_model import (\n ConnectivityActionModel,\n)\nfrom cloudshell.shell.flows.connectivity.models.driver_response import (\n ConnectivityActionResult,\n)\nfrom cloudshell.shell.flows.connectivity.simple_flow import apply_connectivity_changes\n\n\ndef _add_vlan_action(action: ConnectivityActionModel) -> ConnectivityActionResult:\n return ConnectivityActionResult.success_result(action, \"success msg\")\n\n\ndef _remove_vlan_action(action: ConnectivityActionModel) -> ConnectivityActionResult:\n return ConnectivityActionResult.success_result(action, \"success msg\")\n\n\ndef test_apply_connectivity_changes(action_request):\n action_req_remove = action_request\n action_req_set = deepcopy(action_request)\n action_req_set[\"type\"] = \"setVlan\"\n action_req_set[\"actionId\"] = \"new action id\"\n driver_request = json.dumps(\n {\"driverRequest\": {\"actions\": [action_req_remove, action_req_set]}}\n )\n\n res = apply_connectivity_changes(\n driver_request, _add_vlan_action, _remove_vlan_action\n )\n assert json.loads(res) == {\n \"driverResponse\": {\n \"actionResults\": [\n {\n \"actionId\": (\n \"96582265-2728-43aa-bc97-cefb2457ca44_0900c4b5-0f90-42e3-b495\"\n ),\n \"errorMessage\": \"\",\n \"infoMessage\": \"success msg\",\n \"success\": True,\n \"type\": \"removeVlan\",\n \"updatedInterface\": \"centos\",\n },\n {\n \"actionId\": \"new action id\",\n \"errorMessage\": \"\",\n \"infoMessage\": \"success msg\",\n \"success\": True,\n \"type\": \"setVlan\",\n \"updatedInterface\": \"centos\",\n },\n ]\n }\n }\n\n\ndef test_apply_connectivity_changes_without_request():\n with pytest.raises(ApplyConnectivityException, match=\"Request is None or empty\"):\n apply_connectivity_changes(\"\", _add_vlan_action, _remove_vlan_action)\n","sub_path":"tests/test_simple_flow.py","file_name":"test_simple_flow.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"22697033","text":"import json\nimport requests\nfrom flask_babel import _\nfrom flask import current_app\n\n\ndef translate(text, source_language, dest_language):\n if 'YANDEX_TRANSLATOR_KEY' not in current_app.config or not current_app.config['YANDEX_TRANSLATOR_KEY']:\n return _('Error: the translation service is not configured.')\n key = current_app.config['YANDEX_TRANSLATOR_KEY']\n lang = source_language\n if dest_language:\n lang = '{}-{}'.format(source_language, dest_language)\n r = requests.post('https://translate.yandex.net/api/v1.5/tr.json/translate?key={}&text={}&lang={}'.format(\n key, text, lang\n ))\n if r.status_code != 200:\n return _('Error: the translate server failed.')\n return json.loads(r.content.decode('utf-8-sig')).get('text')\n","sub_path":"application/translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"270878029","text":"fav_languages = {\n 'Tim' : ['python','ruby'],\n 'mary' : ['c'],\n 'tom' : ['python','c#'],\n 'bill' : ['ruby','go'],\n }\n\nfor name,languages in fav_languages.items():\n\tif len(languages) > 1 :\n\t\tprint ( name.title() + \"'s favorite languages are:\")\n\t\tfor language in languages:\n\t\t\tprint (language.title())\n\telse :\n\t\tprint ( name.title() + \"'s favorite language is\" )\n\t\tfor language in languages:\n\t\t\tprint (language.title())\n","sub_path":"ex6.py","file_name":"ex6.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"527498806","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport datetime\nimport logging\nimport json\nfrom decimal import Decimal\n\n\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import avg, split, concat_ws, when, lit, col, concat\nfrom utils import Utils\nfrom kafka import KafkaProducer\n\n\ndef create_spark_session(configuration):\n \"\"\" create spark session \"\"\"\n try:\n return SparkSession.builder.appName(configuration.property('spark.appName')).getOrCreate()\n except Exception as e:\n logging.exception(\"Error in Creating spark session\", e.message)\n print(e)\n\n\ndef get_data_from_cassandra(tableName):\n \"\"\"reading the date from cassandra\"\"\"\n try:\n return spark_sql_context.read.format('org.apache.spark.sql.cassandra') \\\n .options(table=tableName,\n keyspace=configuration.property('cassandra.keyspace')).load()\n except Exception as e:\n logging.exception(\"Error in reading data from cassandra\", e.message)\n print(e)\n\ndef get_date_values():\n today = datetime.date.today()\n yesterday = today - datetime.timedelta(days=1)\n return yesterday.strftime('%Y-%m-%d')\n\ndef get_previous_day_data(table_name):\n return table_name.where(table_name.collection_date == extract_date)\n\n\ndef create_lookup_table(modem_df, booster_df):\n \"\"\"Creating Lookup table\"\"\"\n try:\n ''' All CM with Booster from booster table'''\n modem_booster_df = booster_df \\\n .select('gateway_serial', 'device_serial') \\\n .where(booster_df.gateway_serial.isNotNull()) \\\n .distinct() \\\n .withColumnRenamed('device_serial', 'device_serial_of_booster')\n\n '''Creating Lookup table'''\n modem_lookup = modem_df \\\n .join(modem_booster_df, modem_df.device_serial == modem_booster_df.gateway_serial, 'left')\n\n modem_lookup_df = modem_lookup \\\n .withColumn('isBooster',\n when(modem_lookup.device_serial_of_booster.isNotNull(), True).otherwise(False))\\\n .fillna({\"device_serial_of_booster\": \"-\"})\n return modem_lookup_df\n except Exception as e:\n logging.exception(\"Error in creating modem lookup table\", e.message)\n print(e)\n\n\ndef push_stats_to_csv(final_data_frame, location):\n try:\n final_data_frame.repartition(1).write.mode('append').csv(location, header=True)\n except Exception as e:\n logging.exception(\"Error in pushing data to CSV\", e.message)\n print(e)\n\n\ndef push_stats_to_kafka(rows, output_topic):\n \"\"\"Send the stats to kafka output topic.\"\"\"\n try:\n producer = KafkaProducer(bootstrap_servers=bootstrap_server)\n\n for row in rows:\n producer.send(output_topic, bytes(json.dumps(row.asDict(), default=json_serial)))\n\n except ValueError as e:\n logging.exception(\"Error in pushing data to Kafka\", e.message, row)\n except TypeError as e:\n logging.exception('Error in pushing data to Kafka', e.message, row)\n except Exception as e:\n logging.exception(\"Error in pushing data to Kafka\", e.message, row)\n print(e)\n producer.close()\n\n\ndef json_serial(obj):\n \"\"\"JSON serializer for datetime objects not serializable by default json code\"\"\"\n if isinstance(obj, datetime.datetime):\n return obj.isoformat()\n elif isinstance(obj, Decimal):\n return float(obj)\n raise TypeError(\"Type %s not serializable\" % type(obj))\n\n\ndef find_stats_df(modem_lookup_df):\n '''Calculating stats'''\n try:\n stats_regex = configuration.property('regex.stats').replace('_', '%')\n\n stats_data = modem_lookup_df.filter(modem_lookup_df['variable_name'].like(stats_regex))\n stats_data_sorted = stats_data \\\n .withColumn('connectivity', concat_ws('.', split(stats_data.variable_name, '\\.')[1], split(stats_data.variable_name, '\\.')[2])) \\\n .withColumn('connectivity_no', split(stats_data.variable_name, '\\.')[3]) \\\n .withColumn('metric', split(stats_data.variable_name, '\\.')[5]) \\\n .withColumn('variable_value', stats_data.variable_value.cast('int')) \\\n .withColumn('hour', split(split(stats_data.collection_time, ' ')[1], '\\:')[0])\n\n stats_df = stats_data_sorted \\\n .groupBy(['collection_date', 'hour', 'device_serial', 'connectivity',\n 'connectivity_no', 'isBooster', 'device_serial_of_booster', 'metric']) \\\n .avg('variable_value') \\\n .withColumnRenamed('avg(variable_value)', 'value') \\\n .withColumn(\"collection_time\", concat(stats_data_sorted.collection_date, lit('T'),\n stats_data_sorted.hour, lit(':00:00')))\n\n stats_all_df = stats_data_sorted \\\n .groupBy(['collection_date', 'hour', 'connectivity', 'connectivity_no', 'isBooster', 'metric']) \\\n .avg('variable_value') \\\n .withColumn(\"device_serial\", lit('ALL')) \\\n .withColumnRenamed('avg(variable_value)', 'value') \\\n .withColumn(\"collection_time\", concat(stats_data_sorted.collection_date, lit('T'),\n stats_data_sorted.hour, lit(':00:00')))\n\n modem_lookup_all_df = modem_lookup_df \\\n .select('isBooster', 'device_serial_of_booster') \\\n .distinct()\n\n stats_all_and_boosters_df = stats_all_df \\\n .join(modem_lookup_all_df, ['isBooster']) \\\n .select(stats_df.columns)\n\n stats_final_df = stats_df.union(stats_all_and_boosters_df)\n\n stats_graphite_df = stats_final_df \\\n .withColumn(\"metric\", concat_ws('.', lit('cable_modem'), stats_final_df.isBooster,\n stats_final_df.device_serial,\n stats_final_df.connectivity, stats_final_df.connectivity_no, stats_final_df.metric)) \\\n .withColumnRenamed('collection_time', '@timestamp') \\\n .select('@timestamp', 'metric', 'value')\n\n stats_graphite_booster_df = stats_final_df \\\n .withColumn(\"metric\", concat_ws('.', lit('cable_modem'), stats_final_df.isBooster,\n stats_final_df.device_serial,\n lit('booster'), stats_final_df.device_serial_of_booster)) \\\n .withColumnRenamed('collection_time', '@timestamp') \\\n .drop(stats_final_df.value) \\\n .withColumn('value', lit(0)) \\\n .select('@timestamp', 'metric', 'value')\n\n stats_graphite_final_temp_df = stats_graphite_df.union(stats_graphite_booster_df)\n\n stats_graphite_final_df = stats_graphite_final_temp_df \\\n .withColumnRenamed('metric', 'metric_name')\n\n return stats_graphite_final_df\n except Exception as e:\n logging.exception(\"Error in Calculating stats\", e.message)\n print(e)\n\n\ndef find_client_count(modem_lookup_df):\n '''Calculating Client count'''\n try:\n client_count_regex = configuration.property('regex.client_count').replace('_', '%')\n\n client_count_data = modem_lookup_df \\\n .filter(modem_lookup_df['variable_name'].like(client_count_regex)) \\\n .withColumn(\"variable_value\", modem_lookup_df.variable_value.cast('int')) \\\n .withColumn('hour', split(split(modem_lookup_df.collection_time, ' ')[1], '\\:')[0]) \\\n .withColumn('connectivity', concat_ws('.', split(modem_lookup_df.variable_name, '\\.')[1],\n split(modem_lookup_df.variable_name, '\\.')[2])) \\\n .withColumn('connectivity_no', split(modem_lookup_df.variable_name, '\\.')[3]) \\\n .withColumn('metric', split(modem_lookup_df.variable_name, '\\.')[4])\n\n client_count_df = client_count_data \\\n .groupBy(['collection_date', 'hour', 'device_serial', 'isBooster', 'device_serial_of_booster',\n 'connectivity', 'connectivity_no', 'metric' ]) \\\n .sum('variable_value') \\\n .withColumnRenamed('sum(variable_value)', 'client_count') \\\n .withColumn(\"collection_time\", concat(client_count_data.collection_date, lit('T'),\n client_count_data.hour, lit(':00:00')))\n\n client_count_all_df = client_count_data \\\n .groupBy(['collection_date', 'isBooster', 'hour', 'connectivity', 'connectivity_no', 'metric']) \\\n .sum('variable_value') \\\n .withColumnRenamed('sum(variable_value)', 'client_count') \\\n .withColumn(\"device_serial\", lit('ALL')) \\\n .withColumn(\"collection_time\", concat(client_count_data.collection_date, lit('T'),\n client_count_data.hour, lit(':00:00')))\n\n modem_lookup_all_df = modem_lookup_df \\\n .select('isBooster', 'device_serial_of_booster') \\\n .distinct()\n\n client_count_all_and_boosters_df = client_count_all_df \\\n .join(modem_lookup_all_df, ['isBooster']) \\\n .select(client_count_df.columns)\n\n client_count_final_df = client_count_df.union(client_count_all_and_boosters_df)\n\n client_count_graphite_df = client_count_final_df \\\n .withColumn(\"metric\", concat_ws('.', lit('cable_modem'), client_count_final_df.isBooster,\n client_count_final_df.device_serial, client_count_final_df.connectivity,\n client_count_final_df.connectivity_no, client_count_final_df.metric)) \\\n .withColumnRenamed('collection_time', '@timestamp') \\\n .withColumnRenamed('client_count', 'value') \\\n .select('@timestamp', 'metric', 'value')\n\n client_count_graphite_booster_df = client_count_final_df \\\n .withColumn(\"metric\", concat_ws('.', lit('cable_modem'), client_count_final_df.isBooster,\n client_count_final_df.device_serial, lit('booster'),\n client_count_final_df.device_serial_of_booster)) \\\n .withColumnRenamed('collection_time', '@timestamp') \\\n .drop(client_count_final_df.client_count) \\\n .withColumn('value', lit(0)) \\\n .select('@timestamp', 'metric', 'value')\n\n client_count_graphite_final_temp_df = client_count_graphite_df.union(client_count_graphite_booster_df)\n\n client_count_graphite_final_df = client_count_graphite_final_temp_df \\\n .withColumnRenamed('metric', 'metric_name')\n\n return client_count_graphite_final_df\n except Exception as e:\n logging.exception(\"Error in Calculating client_count\", e.message)\n print(e)\n\n\nif __name__ == '__main__':\n configuration = Utils.load_config(sys.argv[:])\n spark_sql_context = create_spark_session(configuration)\n# dry_run_path = configuration.property(\"job_properties.dry_run_path\")\n \n extract_date = get_date_values()\n #extract_date = '2018-08-09'\n '''Read Data From cassandra'''\n modem_df = get_data_from_cassandra(configuration.property(\"cassandra.modem_input_table\"))\n modem_df = get_previous_day_data(modem_df)\n booster_df = get_data_from_cassandra(configuration.property(\"cassandra.booster_input_table\"))\n booster_df = get_previous_day_data(booster_df)\n modem_lookup_df = create_lookup_table(modem_df, booster_df)\n\n '''Metrics'''\n all_stats_df = find_stats_df(modem_lookup_df)\n client_count_df = find_client_count(modem_lookup_df)\n\n '''push to csv'''\n # push_stats_to_csv(all_stats_df, dry_run_path + \"all_stats_df\")\n\n '''To push data to Kafka'''\n kafka_options = configuration.property('kafka')\n bootstrap_server = kafka_options['bootstrap.servers']\n\n all_stats_df.foreachPartition(lambda rows: push_stats_to_kafka(rows,kafka_options['topic.output']))\n client_count_df.foreachPartition(lambda rows: push_stats_to_kafka(rows, kafka_options['topic.output']))\n","sub_path":"src/applications/v6-acs/acs_cable_modem_stats.py","file_name":"acs_cable_modem_stats.py","file_ext":"py","file_size_in_byte":11965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"30433040","text":"import os, sys\r\nfrom eyed3 import id3\r\n\r\nfrom mutagen.id3 import ID3, TIT2, TPE2, TALB, TPE1, TYER, TDAT, TRCK, TCON, TORY, TPUB\r\n\r\ndef write_meta(file, artist, name):\r\n audio = ID3(file)\r\n audio.add(TIT2(encoding=3, text=name)) #TITLE\r\n audio.add(TRCK(encoding=3, text=name)) #TRACK\r\n audio.add(TPE1(encoding=3, text=artist)) #ARTIST\r\n # audio.add(TALB(encoding=3, text=u\"al\")) #ALBUM\r\n\r\n # audio.add(TYER(encoding=3, text=u\"2000\")) #YEAR\r\n # audio.add(TDAT(encoding=3, text=u\"2001\")) #YEAR\r\n # audio.add(TORY(encoding=3, text=u\"2002\")) #ORIGYEAR\r\n # audio.add(TPE2(encoding=3, text=u\"aa\")) #ALBUMARTIST\r\n # audio.add(TCON(encoding=3, text=u\"g\")) #GENRE\r\n audio.save()\r\n\r\n print(\"Обработана композиция '{0}', исполненная '{1}' и имеющая имя '{2}'\".format(name, artist, file))\r\n\r\ndef remove_extension(path):\r\n return os.path.splitext(path)[0]\r\n\r\ndef check_existance(path):\r\n if not os.path.exists(path):\r\n print(\"Ошибка: директория '{0}' не существует\".format(path))\r\n raise SystemExit\r\n\r\ndef get_filenames(path):\r\n result = list()\r\n paths = dict()\r\n for root, dirs, files in os.walk(path): \r\n for filename in files:\r\n if os.path.splitext(filename)[1] == \".mp3\":\r\n result.append(filename)\r\n paths[remove_extension(filename)] = os.path.join(path, filename)\r\n\r\n return result, paths","sub_path":"filemanager.py","file_name":"filemanager.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"532554058","text":"from math import sqrt, ceil\r\n\r\ndef distanceBetweenTwoPoints (p1, p2):\r\n xd = p2[0]-p1[0]\r\n yd = p2[1]-p1[1]\r\n zd = p2[2]-p1[2]\r\n return sqrt(xd ** 2 + yd ** 2 + zd ** 2)\r\n\r\n# Returns array of distance traveled from first point.\r\n# Use last index to find total distance\r\ndef totalDistancesFromPointsList (points):\r\n dists = []\r\n totalDists = [0]\r\n for i in range(1,len(points)):\r\n p1 = points[i-1]\r\n p2 = points[i]\r\n dist = distanceBetweenTwoPoints(p1, p2)\r\n dists.append(dist)\r\n totalDists.append(sum(dists))\r\n return totalDists\r\n\r\n\r\n# Referencing Eric-Olivier LE BIGOT's \"frange5\" solution\r\n# @ http://code.activestate.com/recipes/66472-frange-a-range-function-with-float-increments/\r\n# An alternate solution may be to use 'numpy.linspace'\r\ndef floatrange(limit1, limit2 = None, increment = 1.):\r\n \"\"\"\r\n Range function that accepts floats (and integers).\r\n\r\n Usage:\r\n frange(-2, 2, 0.1)\r\n frange(10)\r\n frange(10, increment = 0.5)\r\n\r\n The returned value is an iterator. Use list(frange) for a list.\r\n \"\"\"\r\n\r\n if limit2 is None:\r\n limit2, limit1 = limit1, 0.\r\n else:\r\n limit1 = float(limit1)\r\n\r\n count = int(ceil(limit2 - limit1)/increment)\r\n return (limit1 + n*increment for n in range(count))","sub_path":"rgbnotes/scripts/rgb/utils/numbers.py","file_name":"numbers.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"626814809","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 reorderList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: void Do not return anything, modify head in-place instead.\n \"\"\"\n if not head or not head.next:\n return\n slow, fast = head, head\n while fast.next and fast.next.next:\n slow = slow.next\n fast = fast.next.next\n l2 = slow.next\n slow.next = None\n l1 = head\n l2 = self.reverse(l2)\n while l2:\n next = l1.next\n l1.next = l2\n l2 = l2.next\n l1.next.next = next\n l1 = next\n\n def reverse(self, head):\n cur, pre = head, None\n while cur:\n next = cur.next\n cur.next = pre\n pre = cur\n cur = next\n return pre\n","sub_path":"leetcode_python/143_reorder_list.py","file_name":"143_reorder_list.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"348450528","text":"# vim: set fileencoding=utf-8 :\n\nfrom .. import *\nfrom ...models import User, Doctor, Template\n\nrpc_template = Blueprint('template', __name__, url_prefix='/rpc/template')\n\n\n@rpc_template.route('/list', methods=['GET'])\n@auth_required('doctor')\ndef template_list():\n doctor = g.role_instance\n templates = Template.objects(doctor=doctor).order_by('-id')\n return display({'templates': (t.to_bson() for t in templates)})\n\n\n@rpc_template.route('/create', methods=['POST'])\n@auth_required('doctor')\ndef create():\n doctor = g.role_instance\n template = Template()\n template.doctor = doctor\n for k, v in g.form.items():\n setattr(template, k, v)\n template.save()\n template.reload()\n g.message = '创建成功'\n return display({'template': template.to_bson()})\n\n\n@rpc_template.route('/update', methods=['POST'])\n@auth_required('doctor')\ndef update():\n doctor = g.role_instance\n id = g.form.get('id')\n g.message = '不存在'\n template = Template.objects(doctor=doctor, id=id).first_or_404()\n for k, v in g.form.items():\n setattr(template, k, v)\n template.updated_at = datetime.utcnow()\n template.save()\n template.reload()\n g.message = '更新成功'\n return display({'template': template.to_bson()})\n\n\n@rpc_template.route('/delete', methods=['POST'])\n@auth_required('doctor')\ndef delete():\n doctor = g.role_instance\n id = g.form.get('id')\n g.message = '不存在'\n template = Template.objects(doctor=doctor, id=id).first_or_404()\n template.delete()\n g.message = '删除成功'\n return display(None)\n\n\n# vim:ts=4:sw=4\n","sub_path":"project/backend-production/src/contrib/views/rpc/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"347149039","text":"import logging\nfrom multiprocessing import Pool\nimport flask_login\nfrom flask import jsonify, request, Response\nimport mediacloud\nimport concurrent.futures\n\nimport server.util.csv as csv\nimport server.util.tags as tag_util\nimport server.views.topics.apicache as apicache\nimport server.views.apicache as base_apicache\nimport server.util.pushshift as pushshift\nfrom server import app, cliff, TOOL_API_KEY\nfrom server.auth import is_user_logged_in\nfrom server.auth import user_mediacloud_key, user_admin_mediacloud_client, user_mediacloud_client\nfrom server.cache import cache\nfrom server.util.request import api_error_handler\nfrom server.views.topics import access_public_topic\nfrom server.util.tags import TAG_SPIDERED_STORY\n\nlogger = logging.getLogger(__name__)\n\nPRIMARY_ENTITY_TYPES = ['PERSON', 'LOCATION', 'ORGANIZATION']\n\nMEDIA_INFO_POOL_SIZE = 15\n\n\n@cache.cache_on_arguments()\ndef _cached_geoname(geonames_id):\n return cliff.geonames_lookup(geonames_id)\n\n\n@app.route('/api/topics//stories/counts', methods=['GET'])\n@flask_login.login_required\n@api_error_handler\ndef story_counts(topics_id):\n if access_public_topic(topics_id):\n local_key = TOOL_API_KEY\n elif is_user_logged_in():\n local_key = user_mediacloud_key()\n else:\n return jsonify({'status': 'Error', 'message': 'Invalid attempt'})\n total = apicache.topic_story_count(local_key, topics_id, timespans_id=None, snapshots_id=None, q=None, foci_id=None)\n filtered = apicache.topic_story_count(local_key, topics_id)\n return jsonify({'counts': {'count': filtered['count'], 'total': total['count']}})\n\n\n@app.route('/api/topics//stories/undateable-counts', methods=['GET'])\n@flask_login.login_required\n@api_error_handler\ndef story_undateable_count(topics_id):\n q = \"tags_id_stories:{}\".format(tag_util.STORY_UNDATEABLE_TAG)\n return _public_safe_topic_story_count(topics_id, q)\n\n\n@app.route('/api/topics//stories/english-counts', methods=['GET'])\n@flask_login.login_required\n@api_error_handler\ndef story_english_counts(topics_id):\n q = \"language:en\"\n return _public_safe_topic_story_count(topics_id, q)\n\n\ndef _public_safe_topic_story_count(topics_id, q):\n if access_public_topic(topics_id):\n total = apicache.topic_story_count(TOOL_API_KEY, topics_id, q=apicache.add_to_user_query(None))\n # force a count with just the query\n matching = apicache.topic_story_count(TOOL_API_KEY, topics_id, q=apicache.add_to_user_query(q))\n elif is_user_logged_in():\n total = apicache.topic_story_count(user_mediacloud_key(), topics_id, q=apicache.add_to_user_query(None))\n # force a count with just the query\n matching = apicache.topic_story_count(user_mediacloud_key(), topics_id, q=apicache.add_to_user_query(q))\n else:\n return jsonify({'status': 'Error', 'message': 'Invalid attempt'})\n return jsonify({'counts': {'count': matching['count'], 'total': total['count']}})\n\n\n@app.route('/api/topics//stories', methods=['GET'])\n@api_error_handler\ndef topic_stories(topics_id):\n if access_public_topic(topics_id):\n stories = apicache.topic_story_list(TOOL_API_KEY, topics_id, snapshots_id=None, timespans_id=None,\n foci_id=None, q=None)\n elif is_user_logged_in():\n stories = apicache.topic_story_list(user_mediacloud_key(), topics_id)\n else:\n return jsonify({'status': 'Error', 'message': 'Invalid attempt'})\n\n return jsonify(stories)\n\n\n@app.route('/api/topics//stories.csv', methods=['GET'])\n@flask_login.login_required\ndef topic_stories_csv(topics_id):\n user_mc = user_admin_mediacloud_client()\n topic = user_mc.topic(topics_id)\n story_limit = request.args['storyLimit'] if 'storyLimit' in request.args else None\n story_tags = (request.args['storyTags'] == '1') if 'storyTags' in request.args else False\n media_metadata = (request.args['mediaMetadata'] == '1') if 'mediaMetadata' in request.args else False\n reddit_submissions = (request.args['redditData'] == '1') if 'redditData' in request.args else False\n include_fb_date = (request.args['fbData'] == '1') if 'fbData' in request.args else False\n return stream_story_list_csv(user_mediacloud_key(), topic,\n story_limit=story_limit, reddit_submissions=reddit_submissions,\n story_tags=story_tags, include_fb_date=include_fb_date,\n media_metadata=media_metadata)\n\n\ndef stream_story_list_csv(user_key, topic, **kwargs):\n filename = topic['name']+'-stories'\n has_twitter_data = (topic['ch_monitor_id'] is not None) and (topic['ch_monitor_id'] != 0)\n\n # as_attachment = kwargs['as_attachment'] if 'as_attachment' in kwargs else True\n include_media_metadata = ('media_metadata' in kwargs) and (kwargs['media_metadata'] is True)\n include_story_tags = ('story_tags' in kwargs) and (kwargs['story_tags'] is True)\n include_reddit_submissions = ('reddit_submissions' in kwargs) and (kwargs['reddit_submissions'] is True)\n include_fb_date = kwargs['fb_data'] if 'fb_data' in kwargs else False\n all_stories = []\n params = kwargs.copy()\n\n merged_args = {\n 'snapshots_id': request.args['snapshotId'],\n 'timespans_id': request.args['timespanId'],\n 'foci_id': request.args['focusId'] if 'focusId' in request.args else None,\n 'q': request.args['q'] if 'q' in request.args else None,\n 'sort': request.args['sort'] if 'sort' in request.args else None,\n }\n params.update(merged_args)\n\n story_count = apicache.topic_story_count(user_mediacloud_key(), topic['topics_id'],\n snapshots_id=params['snapshots_id'], timespans_id=params['timespans_id'],\n foci_id=params['foci_id'], q=params['q'])\n logger.info(\"Total stories to download: {}\".format(story_count['count']))\n\n if 'as_attachment' in params:\n del params['as_attachment']\n if 'fb_data' in params:\n del params['fb_data']\n if 'q' in params:\n params['q'] = params['q'] if 'q' not in [None, '', 'null', 'undefined'] else None\n params['limit'] = 1000 # an arbitrary value to let us page through with big topics\n\n # determine which props the user actually wants to download\n props = [\n 'stories_id', 'publish_date', 'title', 'url', 'language', 'ap_syndicated', 'inlink_count',\n 'facebook_share_count',\n ]\n if has_twitter_data:\n props.append('simple_tweet_count')\n if include_reddit_submissions:\n props.append('reddit_submissions')\n if include_fb_date:\n props.append('facebook_collection_date')\n if include_story_tags:\n props += ['themes', 'subtopics']\n props += ['outlink_count', 'media_inlink_count', 'media_id', 'media_name', 'media_url']\n if include_media_metadata:\n props += ['media_pub_country', 'media_pub_state', 'media_language', 'media_about_country', 'media_media_type']\n\n if include_fb_date:\n all_fb_count = []\n more_fb_count = True\n link_id = 0\n local_mc = user_admin_mediacloud_client()\n while more_fb_count:\n fb_page = local_mc.topicStoryListFacebookData(topic['topics_id'], limit=100, link_id=link_id)\n\n all_fb_count = all_fb_count + fb_page['counts']\n if 'next' in fb_page['link_ids']:\n link_id = fb_page['link_ids']['next']\n more_fb_count = True\n else:\n more_fb_count = False\n\n # now iterate through each list and set up the fb collection date\n for s in all_stories:\n for fb_item in all_fb_count:\n if int(fb_item['stories_id']) == int(s['stories_id']):\n s['facebook_collection_date'] = fb_item['facebook_api_collect_date']\n\n timestamped_filename = csv.safe_filename(filename)\n headers = {\n \"Content-Disposition\": \"attachment;filename=\" + timestamped_filename\n }\n return Response(_topic_story_list_by_page_as_csv_row(user_key, topic['topics_id'], props, **params),\n mimetype='text/csv; charset=utf-8', headers=headers)\n\n\n@app.route('/api/topics//stories/story-links.csv', methods=['GET'])\n@flask_login.login_required\ndef get_topic_story_links_csv(topics_id):\n user_mc = user_mediacloud_client()\n topic = user_mc.topic(topics_id)\n return stream_story_link_list_csv(user_mediacloud_key(), topic['name'] + '-stories', topics_id)\n\n\ndef stream_story_link_list_csv(user_key, filename, topics_id, **kwargs):\n params = kwargs.copy()\n merged_args = {\n 'snapshots_id': request.args['snapshotId'],\n 'timespans_id': request.args['timespanId'],\n 'foci_id': request.args['focusId'] if 'foci_id' in request.args else None,\n }\n params.update(merged_args)\n if 'q' in params:\n params['q'] = params['q'] if 'q' not in [None, '', 'null', 'undefined'] else None\n params['limit'] = 100 # an arbitrary value to let us page through with big topics\n\n props = [\n 'stories_id', 'publish_date', 'title', 'url', 'language', 'ap_syndicated',\n 'inlink_count', 'outlink_count'\n # 'media_pub_country', 'media_pub_state', 'media_language', 'media_about_country', 'media_media_type'\n ]\n\n timestamped_filename = csv.safe_filename(filename)\n headers = {\n \"Content-Disposition\": \"attachment;filename=\" + timestamped_filename\n }\n return Response(_topic_story_link_list_by_page_as_csv_row(user_key, topics_id, props, **params),\n mimetype='text/csv; charset=utf-8', headers=headers)\n\n\n# generator you can use to handle a long list of stories row by row (one row per story)\ndef _topic_story_link_list_by_page_as_csv_row(user_key, topics_id, props, **kwargs):\n local_mc = user_admin_mediacloud_client(user_key)\n spec_props = [\n 'source_stories_id', 'source_publish_date', 'source_title', 'source_url', 'source_language',\n 'source_ap_syndicated', 'source_inlink_count', 'source_outlink_count', 'ref_stories_id', 'ref_publish_date',\n 'ref_title', 'ref_url', 'ref_language', 'ref_ap_syndicated', 'ref_inlink_count', 'ref_outlink_count'\n 'media_pub_country', 'media_pub_state', 'media_language', 'media_about_country', 'media_media_type'\n ]\n yield ','.join(spec_props) + '\\n' # first send the column names\n link_id = 0\n more_pages = True\n while more_pages:\n story_link_page = apicache.topic_story_link_list_by_page(user_key, topics_id, link_id=link_id, **kwargs)\n\n story_src_ids = [str(s['source_stories_id']) for s in story_link_page['links']]\n story_ref_ids = [str(s['ref_stories_id']) for s in story_link_page['links']]\n story_src_ids = story_src_ids + story_ref_ids\n\n stories_info_list = local_mc.topicStoryList(topics_id, stories_id=story_src_ids)\n\n for s in story_link_page['links']:\n for s_info in stories_info_list['stories']:\n if s['source_stories_id'] == s_info['stories_id']:\n s['source_info'] = s_info\n if s['ref_stories_id'] == s_info['stories_id']:\n s['ref_info'] = s_info\n\n if 'next' in story_link_page['link_ids']:\n link_id = story_link_page['link_ids']['next']\n else:\n more_pages = False\n for s in story_link_page['links']:\n cleaned_source_info = csv.dict2row(props, s['source_info'])\n cleaned_ref_info = csv.dict2row(props, s['ref_info'])\n row_string = ','.join(cleaned_source_info) + ',' + ','.join(cleaned_ref_info) + '\\n'\n yield row_string\n\n\n# generator you can use to handle a long list of stories row by row (one row per story)\ndef _topic_story_list_by_page_as_csv_row(user_key, topics_id, props, **kwargs):\n yield ','.join(props) + '\\n' # first send the column names\n story_count = 0\n link_id = 0\n more_pages = True\n yet_to_hit_story_limit = True\n has_story_limit = ('story_limit' in kwargs) and (kwargs['story_limit'] is not None)\n while more_pages and ((not has_story_limit) or (has_story_limit and yet_to_hit_story_limit)):\n page = _topic_story_page_with_media(user_key, topics_id, link_id, **kwargs)\n if 'next' in page['link_ids']:\n link_id = page['link_ids']['next']\n else:\n more_pages = False\n for s in page['stories']:\n # first foci down to just the readable names\n s['subtopics'] = [\"{}: {}\".format(f['focal_set_name'], f['name']) for f in s['foci']]\n cleaned_row = csv.dict2row(props, s)\n row_string = ','.join(cleaned_row) + '\\n'\n yield row_string\n story_count += len(page['stories'])\n yet_to_hit_story_limit = has_story_limit and (story_count < int(kwargs['story_limit']))\n\n\ndef _media_info_worker(info):\n return base_apicache.get_media(info['user_key'], info['media_id'])\n\n\n# generator you can use to do something for each page of story results\ndef _topic_story_page_with_media(user_key, topics_id, link_id, **kwargs):\n media_lookup = {}\n\n include_media_metadata = ('media_metadata' in kwargs) and (kwargs['media_metadata'] is True)\n include_story_tags = ('story_tags' in kwargs) and (kwargs['story_tags'] is True)\n include_reddit_submissions = ('reddit_submissions' in kwargs) and (kwargs['reddit_submissions'] is True)\n\n args = kwargs.copy() # need to make sure invalid params don't make it to API call\n optional_args = ['media_metadata', 'story_limit', 'reddit_submissions', 'story_tags', 'include_fb_date']\n for key in optional_args:\n if key in args:\n del args[key]\n story_page = apicache.topic_story_list_by_page(user_key, topics_id, link_id=link_id, **args)\n\n if len(story_page['stories']) > 0: # be careful to not construct malformed query if no story ids\n\n # build a media lookup table in parallel so it is faster\n if include_media_metadata:\n with concurrent.futures.ProcessPoolExecutor() as executor:\n jobs = [{'user_key': user_key, 'media_id': s['media_id']} for s in story_page['stories']]\n job_results = executor.map(_media_info_worker, jobs) # blocks until they are all done\n media_lookup = {j['media_id']: j for j in job_results}\n\n if include_story_tags:\n story_ids = [str(s['stories_id']) for s in story_page['stories']]\n stories_with_tags = apicache.story_list(user_key, 'stories_id:(' + \" \".join(story_ids) + \")\", args['limit'])\n\n # update story info for each story in the page, put it into the [stories] field, send updated page with\n # stories back\n for s in story_page['stories']:\n\n # add in media metadata to the story (from page-level cache built earlier)\n if include_media_metadata:\n media = media_lookup[s['media_id']]\n # add in media metadata items\n for k, v in media['metadata'].items():\n s['media_{}'.format(k)] = v['label'] if v is not None else None\n\n # build lookup for id => story for all stories in stories with tags (non topic results)\n if include_story_tags:\n for st in stories_with_tags:\n if s['stories_id'] == st['stories_id']:\n s.update(st)\n foci_names = [f['name'] for f in s['foci']]\n s['subtopics'] = \", \".join(foci_names)\n s['themes'] = ''\n story_tag_ids = [t['tags_id'] for t in s['story_tags']]\n if tag_util.NYT_LABELER_1_0_0_TAG_ID in story_tag_ids:\n story_tag_ids = [t['tag'] for t in s['story_tags']\n if t['tag_sets_id'] == tag_util.NYT_LABELS_TAG_SET_ID]\n s['themes'] = \", \".join(story_tag_ids)\n\n # now add in reddit share data if requested\n if include_reddit_submissions:\n story_reddit_submissions = pushshift.reddit_url_submission_counts(story_page['stories'])\n for s in story_page['stories']:\n s['reddit_submissions'] = story_reddit_submissions[s['stories_id']]\n\n return story_page\n\n\n@app.route('/api/topics//stories/counts-by-snapshot', methods=['GET'])\n@flask_login.login_required\n@api_error_handler\ndef story_counts_by_snapshot(topics_id):\n user_mc = user_mediacloud_client(user_mediacloud_key())\n snapshots = user_mc.topicSnapshotList(topics_id)\n counts = {}\n for s in snapshots:\n # get the count of stories in the overally timespan for this snapshot\n timespans = apicache.cached_topic_timespan_list(user_mediacloud_key(), topics_id,\n snapshots_id=s['snapshots_id'], foci_id=None)\n try:\n total = timespans[0]['story_count']\n except mediacloud.error.MCException:\n total = 0\n except IndexError: # this doesn't have any snapshots (ie. it failed to generate correctly)\n total = 0\n # search by tag to find out how many stories were spidered\n spidered = 0\n try:\n spidered = apicache.topic_story_count(user_mediacloud_key(), topics_id,\n snapshots_id=s['snapshots_id'], foci_id=None,\n timespans_id=timespans[0]['timespans_id'],\n q=\"* AND tags_id_stories:{}\".format(TAG_SPIDERED_STORY))['count']\n except mediacloud.error.MCException:\n spidered = 0\n except IndexError: # this doesn't have any snapshots (ie. it failed to generate correctly)\n total = 0\n seeded = total - spidered\n counts[s['snapshots_id']] = {'total': total, 'spidered': spidered, 'seeded': seeded}\n return jsonify(counts)\n","sub_path":"server/views/topics/stories.py","file_name":"stories.py","file_ext":"py","file_size_in_byte":18049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"13137790","text":"#Write a function called snowedIn that will determine\n#whether a store is open or not based on the weather and\n#temperature. This function should return True if a store is\n#currently open, and False if it is not.\n#\n#The function will have three parameters: store (a string),\n#temperature (an integer), and weather (a string). If no\n#argument is supplied for weather, assume the weather is\n#\"sunny\". The other possible values for weather are\n#\"sunny\", \"raining\", \"snowing\", and \"end of the world\".\n#\n#Here are the conditions under which each restaurant closes:\n#\n# - Cookout closes if it's below 10 degrees, if it's snowing,\n# or if it's both below 32 degrees and raining.\n# - Taco Bell closes if it's below 0 degrees, if it's snowing,\n# or if it's both below 32 degrees and raining.\n# - Waffle House only closes if it's the end of the world.\n#\n#For example, snowedIn(\"Cookout\", 20) should return True\n#because Cookout would be open if it was 20 degrees and sunny.\n#snowedIn(\"Taco Bell\", 30, \"snowing\") should return False\n#because Taco Bell would be closed if it was snowing.\n#\n#Function: snowedIn\n#Parameters: store (a string)\n# temperature (an integer)\n# weather (a string)\n#Returns: True if the restaurant is open, False if it is not\n\n#Write your function here!\n\ndef snowedIn(store, temperature, weather= \"sunny\"):\n opened = True\n # - Cookout closes if it's below 10 degrees, if it's snowing,\n # or if it's both below 32 degrees and raining.\n if store == \"Cookout\":\n if weather == \"snowing\":\n opened = False\n elif temperature < 10:\n opened = False\n elif temperature < 32 and weather == \"raining\":\n opened = False\n else:\n opened = True\n # - Taco Bell closes if it's below 0 degrees, if it's snowing,\n # or if it's both below 32 degrees and raining\n if store == \"Taco Bell\":\n if temperature < 0 :\n opened = False\n elif weather == \"snowing\":\n opened = False\n elif temperature < 32 and weather == \"raining\":\n opened = False\n else:\n opened = True\n # - Waffle House only closes if it's the end of the world.\n if store == \"Waffle House\":\n if weather == \"end of the world\":\n opened = False\n else:\n opened = True\n return opened\n\n#When your code works, these two lines should run successfully.\n#The first should print True, the second should print False.\n#You can change these if you want to test your code.\nprint(snowedIn(\"Cookout\", 20))\nprint(snowedIn(\"Taco Bell\", 30, \"snowing\"))\n\n\n","sub_path":"Unit3/Chapter 3.1 to 3.4/3.4.6 Coding Exercise 1.py","file_name":"3.4.6 Coding Exercise 1.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"400647225","text":"from abc import ABC, abstractmethod\n\n\nclass Component(ABC):\n\n def __init__(self):\n pass\n\n\nclass System(ABC):\n\n def __init__(self, requiredComponents):\n self._entityManager = None\n self._systemManager = None\n self._messageDispatcher = None\n self._requiredComponents = requiredComponents\n self._entities = set()\n\n def register(self, systemManager):\n \"\"\"\n Register the system with its controlling system manager.\n\n IMPORTANT: This must be called by the system manager before using the system.\n \"\"\"\n self._systemManager = systemManager\n self._entityManager = systemManager._entityManager\n self._messageDispatcher = systemManager._messageDispatcher\n self._postRegistrationSetup()\n\n def _postRegistrationSetup(self):\n pass\n\n @property\n def requiredComponents(self):\n return self._requiredComponents\n\n @property\n def entities(self):\n return self._entities\n\n def refreshEntity(self, entity):\n inSystem = True\n for componentType in self._requiredComponents:\n inSystem = inSystem and self._entityManager.hasComponent(entity, componentType)\n\n if inSystem:\n self._entities.add(entity)\n else:\n self._entities.discard(entity)\n\n def refreshAllEntities(self):\n self._entities = self._entityManager.getEntitiesWithTypeList(self._requiredComponents)\n\n def components(self):\n return ({componentType: self._entityManager.getComponent(entity, componentType)\n for componentType in self._requiredComponents}\n for entity in self._entities)\n\n @abstractmethod\n def update(self, delta):\n pass\n\n\nclass EntityManager:\n\n def __init__(self, messageDispatcher):\n self._nextID = 0\n self._recycledIDs = []\n self._entities = []\n self._components = {}\n\n self._messageDispatcher = messageDispatcher\n\n @property\n def entities(self):\n return(self._entities)\n\n @property\n def components(self):\n return(self._components)\n\n def createEntity(self):\n entity = None\n if self._recycledIDs != []:\n entity = self._recycledIDs.pop()\n else:\n entity = self._nextID\n self._nextID += 1\n\n self._entities.append(entity)\n self._messageDispatcher.send(\"entityCreated\", entity)\n return(entity)\n\n def removeEntity(self, entity):\n for componentType in list(self._components.keys()):\n self.removeComponentFrom(entity, componentType)\n\n self._recycledIDs.append(entity)\n self._entities.remove(entity)\n self._messageDispatcher.send(\"entityRemoved\", entity)\n\n def addComponentTo(self, entity, component):\n componentType = type(component)\n if componentType not in self._components:\n self._components[componentType] = {}\n\n self._components[componentType][entity] = component\n self._messageDispatcher.send(\"componentAdded\", entity, componentType)\n\n def removeComponentFrom(self, entity, componentType):\n try:\n del self._components[componentType][entity]\n self._messageDispatcher(\"componentRemoved\", entity, componentType)\n if self._components[componentType] == {}:\n del self._components[componentType]\n except KeyError:\n pass\n\n def hasComponent(self, entity, componentType):\n if (componentType in self._components and\n entity in self._components[componentType]):\n return True\n else:\n return False\n\n def getComponent(self, entity, componentType):\n try:\n return(self._components[componentType][entity])\n except KeyError:\n pass\n\n def getAllComponentsOfType(self, componentType):\n try:\n return(self._components[componentType])\n except KeyError:\n pass\n\n def getAllComponentsInEntity(self, entity):\n components = {}\n for componentType, instances in self._components.items():\n if entity in instances:\n components[componentType] = instances[entity]\n return(components)\n\n def getAllEntityMapsWithType(self, componentType):\n \"\"\"\n Returns a dictionary with the key-value pairs:\n key: Entity ID\n val: Entitiy's owned component of the requested type\n \"\"\"\n return(self._components[componentType])\n\n def getAllEntityMapsWithTypes(self, types):\n componentList = [self.getAllEntitiesWithType(t) for t in types]\n keys = self._entities\n for componentType in componentList:\n keys &= componentType.keys()\n\n entities = {entity: {type(component[entity]): component[entity]\n for component in componentList}\n for entity in keys}\n\n return(entities)\n\n def getEntitiesWithType(self, componentType):\n \"\"\"\n Returns a set of entity ids of entities with the component type.\n \"\"\"\n try:\n return set(self._components[componentType].keys())\n except KeyError:\n return set()\n\n def getEntitiesWithTypeList(self, types):\n entities = set(self._entities)\n for componentType in types:\n entities &= self.getEntitiesWithType(componentType)\n\n return entities\n\n\n\nclass SystemManager:\n\n def __init__(self, entityManager):\n self._systems = {}\n self._entityManager = entityManager\n self._messageDispatcher = entityManager._messageDispatcher\n\n self._messageDispatcher.subscribe(\"entityRemoved\", self.handleEntityRemoval)\n self._messageDispatcher.subscribe(\"componentAdded\", self.handleComponentAddedOrRemoved)\n self._messageDispatcher.subscribe(\"componentRemoved\", self.handleComponentAddedOrRemoved)\n\n\n @property\n def systems(self):\n return(self._systems)\n\n def addSystem(self, system):\n print(\"adding\")\n print(type(system))\n systemType = type(system)\n system.register(self)\n self._systems[systemType] = system\n\n\n def removeSystem(self, system):\n try:\n del self._systems[type(system)]\n except:\n pass\n\n def handleEntityRemoval(self, entity):\n for systemType in self._systems:\n system = self._systems[systemType]\n if entity in system.entities:\n system.refreshEntity(entity)\n\n def handleComponentAddedOrRemoved(self, entity, componentType):\n for systemType in self._systems:\n system = self._systems[systemType]\n if componentType in system.requiredComponents:\n system.refreshEntity(entity)\n\n def update(self, delta):\n for t, system in self._systems.items():\n system.update(delta)\n\n\nclass MessageDispatcher:\n\n def __init__(self):\n self._messageTypes = {}\n\n def subscribe(self, messageType, callback):\n if messageType not in self._messageTypes:\n self._messageTypes[messageType] = [callback]\n else:\n self._messageTypes[messageType].append(callback)\n\n def unsubscribe(self, messageType, callback):\n if messageType in self._messageTypes:\n try:\n self._messageTypes[messageType].remove(callback)\n except ValueError:\n print(str(callback) +\n \" was not subscribed to \" +\n str(messageType))\n\n def send(self, messageType, *args, **kargs):\n if messageType not in self._messageTypes:\n pass\n else:\n for callback in self._messageTypes[messageType]:\n callback(*args, **kargs)\n","sub_path":"fission.py","file_name":"fission.py","file_ext":"py","file_size_in_byte":7776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"468179825","text":"#Introduction to Programming\n#Author: Tyler Vultaggio\n#Date: 9/22/2019\n\nimport math\n\ndef main():\n\n n = eval(input(\"Enter a number: \"))\n\n count = 0\n number = 0\n\n for i in range(1,n*2+1,2):\n count = count+1\n if count%2==0:\n number = number - (4/i)\n else:\n number = number + (4/i)\n \n print(number)\n diff = math.pi - number\n print(\"The difference from the approximation and the actual vaule of pi is: \", diff)\n\nmain()\n","sub_path":"pi.py","file_name":"pi.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"109460705","text":"# ================ IMPORTS ================\n\nfrom __future__ import print_function, division\nimport os\nimport dill\nimport pickle\nimport sys\nimport random\nimport time\nsys.path.insert(0, \"/Users/edcollins/Documents/CS/4thYearProject/Code\")\nimport matplotlib.pyplot as plt\nfrom operator import itemgetter\nfrom Dev.DataTools.Reader import Reader\nfrom Dev.DataTools.DataPreprocessing.DataPreprocessor import DataPreprocessor\nfrom multiprocessing.dummy import Pool as ThreadPool\nfrom Dev.DataTools import useful_functions\nfrom Dev.Evaluation.rouge import Rouge\nfrom Dev.DataTools.useful_functions import Color, wait, printlist, num2onehot, BASE_DIR, PAPER_SOURCE, HIGHLIGHT_SOURCE,\\\n PAPER_BAG_OF_WORDS_LOC, KEYPHRASES_LOC, GLOBAL_COUNT_LOC, weight_variable, bias_variable\nfrom Dev.Evaluation.rouge import Rouge\nfrom Dev.DataTools.LSTM_preproc.vocab import Vocab\nfrom Dev.DataTools.LSTM_preproc.batch import get_batches, GeneratorWithRestart, get_feed_dicts, get_feed_dicts_old\nfrom Dev.DataTools.LSTM_preproc.map import numpify, tokenize, notokenize, lower, deep_map, deep_seq_map, dynamic_subsample, jtr_map_to_targets\nfrom nltk.tokenize import sent_tokenize\nfrom sklearn.metrics import precision_recall_fscore_support\nimport tensorflow as tf\nimport numpy as np\n\n# =========================================\n\n# ================ CONFIG VARIABLES ================\n\n# The dimensions of the word vectors\nWORD_DIMENSIONS = 100\n\n# The dimension of the abstract vector\nABSTRACT_DIMENSION = 100\n\n# The number of handcrafted features\nNUM_FEATURES = 8\n\n# The size of the batch of the data to feed\nBATCH_SIZE = 100\n\n# Weighting dimensions for the weighting for the sentences\nSENTENCE_WEIGHTS = 200\n\n# The number of units in the hidden layer\nHIDDEN_LAYER_WEIGHTS = 64\n\n# The number of classes to classify into\nNUM_CLASSES = 2\n\n# The network learning rate\nLEARNING_RATE = 0.0001\n\n# Maximum number of epochs\nMAX_EPOCHS = 1000\n\n# How often to display network progress and test its accuracy\nDISPLAY_EVERY = 300\n\n# How many steps the network can go before it is deemed to have converged\nMAX_STEPS_SINCE_SAVE = 15\n\n# True if the model is already trained\nPRETRAINED = False\n\n# The name of this model\nMODEL_NAME = \"CombinedMLP\"\n\n# Directory for data\nDATA_DIR = BASE_DIR + \"/Data/Generated_Data/Sentences_And_SummaryBool/Abstract_Neg/AbstractNet/abstractnet_data.pkl\"\n\n# The location to save the model at\nSAVE_PATH = BASE_DIR + \"/Trained_Models/\" + MODEL_NAME + \"/\" + str(HIDDEN_LAYER_WEIGHTS) + \"_units/\" + MODEL_NAME + \"_\" +\\\n str(HIDDEN_LAYER_WEIGHTS) + \".ckpt\"\n\n# The directory to save the model in\nSAVE_DIR = BASE_DIR + \"/Trained_Models/\" + MODEL_NAME + \"/\" + str(HIDDEN_LAYER_WEIGHTS) + \"_units/\"\n\n\n# ==================================================\n\n# ================ FUNCTIONS ================\n\n# ===========================================\n\n# ================ MAIN ================\n\ndef graph():\n \"\"\"\n Function to encapsulate the construction of a TensorFlow computation graph.\n :return: input placeholders, optimisation operation, loss, accuracy, prediction operations\n \"\"\"\n\n # Define placeholders for the data\n\n # The sentence to classify, has shape [batch_size x word_dimensions*2] because the input will be the sentence\n # and abstract concatenated.\n sentence_input = tf.placeholder(tf.float32, shape=[None, WORD_DIMENSIONS + ABSTRACT_DIMENSION + NUM_FEATURES])\n\n # The labels for the sentences as one-hot vectors, of the form [batch_size x num_classes]\n labels = tf.placeholder(tf.float32, shape=[None, NUM_CLASSES])\n\n # Keep probability for dropout\n keep_prob = tf.placeholder(tf.float32)\n\n # Define the computation graph\n\n # The keep gate - decides which parts to keep\n hidden_weight = weight_variable([WORD_DIMENSIONS + ABSTRACT_DIMENSION + NUM_FEATURES, HIDDEN_LAYER_WEIGHTS])\n hidden_bias = bias_variable([HIDDEN_LAYER_WEIGHTS])\n hidden_layer = tf.nn.relu(tf.matmul(sentence_input, hidden_weight) + hidden_bias)\n\n # Add dropout\n hidden_layer_output = tf.nn.dropout(hidden_layer, keep_prob)\n\n # Project the output to two classes\n projection_weight = weight_variable([HIDDEN_LAYER_WEIGHTS, NUM_CLASSES])\n projection_bias = bias_variable([NUM_CLASSES])\n output = tf.matmul(hidden_layer_output, projection_weight) + projection_bias\n\n # Define the loss function\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(output, labels))\n opt = tf.train.AdamOptimizer(LEARNING_RATE).minimize(loss)\n\n # Predictions\n predictions = tf.nn.softmax(output)\n\n # Calculate accuracy\n pred_answers = tf.argmax(output, axis=1)\n correct_answers = tf.argmax(labels, axis=1)\n accuracy = tf.reduce_mean(tf.cast(tf.equal(pred_answers, correct_answers), tf.float32))\n\n return_dict = {\n \"input\": sentence_input,\n \"labels\": labels,\n \"keep_prob\": keep_prob,\n \"loss\": loss,\n \"opt\": opt,\n \"prediction_probs\": predictions,\n \"prediction_class\": pred_answers,\n \"correct_answers\": correct_answers,\n \"accuracy\": accuracy\n }\n\n return return_dict\n\nif __name__ == '__main__':\n\n # Construct the computation graph\n graph_outputs = graph()\n\n # Assign graph outputs\n\n # Holds input sentences\n sentence_input = graph_outputs[\"input\"]\n\n # Holds labels in one-hot format\n labels = graph_outputs[\"labels\"]\n\n # Holds keep probability for dropout\n keep_prob = graph_outputs[\"keep_prob\"]\n\n # Loss function to minimize\n loss = graph_outputs[\"loss\"]\n\n # Optimisation operation\n opt = graph_outputs[\"opt\"]\n\n # Predictions as probabilities\n predictions = graph_outputs[\"prediction_probs\"]\n\n # Argmaxed predictions and labels\n pred_answers = graph_outputs[\"prediction_class\"]\n correct_answers = graph_outputs[\"correct_answers\"]\n\n # Accuracy operation\n accuracy = graph_outputs[\"accuracy\"]\n\n with tf.Session() as sess:\n\n # Initialise all variables\n sess.run(tf.global_variables_initializer())\n\n # Saving object\n saver = tf.train.Saver()\n\n print(\"Loading Data...\")\n t = time.time()\n data = useful_functions.load_pickled_object(DATA_DIR)\n sentvec_abstracvec_features_class = []\n for item in data:\n sentence_vecs = item[\"sentence_vecs\"]\n abstract_vec = item[\"abstract_vec\"]\n features = item[\"sentence_features\"]\n for sent, feat in zip(sentence_vecs, features):\n vec = np.concatenate((sent[0], abstract_vec, feat))\n sentvec_abstracvec_features_class.append((vec, sent[2]))\n data = sentvec_abstracvec_features_class\n print(\"Done, took \", time.time() - t, \" seconds\")\n\n test_len = int(len(data) * (1/3))\n test_data = data[0:test_len]\n train_data = data[test_len:]\n\n print(\"Length of Training Data: \", len(train_data))\n print(\"Length of Testing Data: \", len(test_data))\n\n num_batches = int(len(train_data) / BATCH_SIZE)\n\n if not PRETRAINED:\n\n # Accuracies and losses for training curves\n accuracies = []\n losses = []\n\n # Lowest loss\n lowest_loss = 1000\n\n # Number of steps since the model was saved\n steps_since_save = 0\n\n # Breaks out of the training loop if true for early stopping\n breakout = False\n\n for epoch in range(MAX_EPOCHS):\n\n if breakout:\n break\n\n for batch in range(num_batches):\n\n print(\"Running Batch: \", batch, \" / \", num_batches, end=\"\\r\")\n\n # Sample a random batch of data\n batch_data = random.sample(train_data, BATCH_SIZE)\n\n # Extract the data into three numpy arrays\n batch_sentences = np.asarray([x for x, _ in batch_data])\n batch_labels = np.asarray([num2onehot(x, NUM_CLASSES) for _, x in batch_data])\n\n # Create the feed_dict\n feed_dict = {\n sentence_input: batch_sentences,\n labels: batch_labels,\n keep_prob: 0.5\n }\n\n # Runs optimisation\n sess.run(opt, feed_dict=feed_dict)\n\n if batch % DISPLAY_EVERY == 0:\n\n # Get the batch of test data\n batch_data = test_data\n\n # Extract the data into three numpy arrays\n batch_sentences = np.asarray([x for x, _ in batch_data])\n batch_labels = np.asarray([num2onehot(x, NUM_CLASSES) for _, x in batch_data])\n\n # Create the feed_dict\n feed_dict = {\n sentence_input: batch_sentences,\n labels: batch_labels,\n keep_prob: 1\n }\n\n # Run accuracy and loss\n l, acc = sess.run([loss, accuracy], feed_dict=feed_dict)\n\n accuracies.append(acc)\n losses.append(l)\n\n print(\"\\n\\n**** EPOCH \", epoch, \" ****\")\n print(\"Model Accuracy on Iteration \", batch, \" is: \", acc)\n print(\"Model Loss on Iteration \", batch, \" is: \", l)\n\n if l < lowest_loss:\n lowest_loss = l\n print(\">> Saving Model <<\")\n saver.save(sess, SAVE_PATH)\n print(\">> Model Saved <<\")\n steps_since_save = 0\n else:\n steps_since_save += 1\n\n print()\n\n if steps_since_save > MAX_STEPS_SINCE_SAVE:\n print(\">>>> MODEL CONVERGED, STOPPING EARLY <<<<\")\n breakout = True\n break\n\n with open(SAVE_DIR + \"loss_\" + str(HIDDEN_LAYER_WEIGHTS) + \".pkl\", \"wb\") as f:\n pickle.dump(losses, f)\n\n with open(SAVE_DIR + \"accuracies_\" + str(HIDDEN_LAYER_WEIGHTS) + \".pkl\", \"wb\") as f:\n pickle.dump(accuracies, f)\n\n plt.plot(accuracies)\n plt.ylabel(\"Accuracy\")\n plt.xlabel(\"Training Iteration\")\n plt.title(MODEL_NAME + \" Test Accuracy During Training\")\n plt.savefig(SAVE_DIR + MODEL_NAME + \"_accuracy_\" + str(HIDDEN_LAYER_WEIGHTS) + \".png\")\n plt.show()\n\n plt.plot(losses)\n plt.ylabel(\"Loss\")\n plt.xlabel(\"Training Iteration\")\n plt.title(MODEL_NAME + \" Test Loss During Training\")\n plt.savefig(SAVE_DIR + MODEL_NAME + \"_loss_\" + str(HIDDEN_LAYER_WEIGHTS) + \".png\")\n plt.show()\n\n # Test the model\n\n # Restore the trained parameters\n saver.restore(sess, SAVE_PATH)\n\n # Get the batch of test data\n batch_data = test_data\n\n # Extract the data into three numpy arrays\n batch_sentences = np.asarray([x for x, _ in batch_data])\n batch_labels = np.asarray([num2onehot(x, NUM_CLASSES) for _, x in batch_data])\n\n # Create the feed_dict\n feed_dict = {\n sentence_input: batch_sentences,\n labels: batch_labels,\n keep_prob: 1\n }\n\n # Run accuracy and loss\n l, acc, y_pred, y_true = sess.run([loss, accuracy, pred_answers, correct_answers], feed_dict=feed_dict)\n\n # Compute Precision, Recall and F1 score\n precision, recall, f1, _ = precision_recall_fscore_support(y_true, y_pred, average=\"binary\")\n\n print(\"\\n>>>> FINAL TESTING ACCURACY AND LOSS FOR \" + MODEL_NAME + \" <<<<\")\n print(\">> Hidden Layer Weights: \", Color.YELLOW, HIDDEN_LAYER_WEIGHTS, Color.END)\n print(\">> Accuracy: \", Color.CYAN, acc, Color.END)\n print(\">> Loss: \", Color.YELLOW, l, Color.END)\n print(\">> Precision: \", Color.YELLOW, precision, Color.END)\n print(\">> Recall: \", Color.YELLOW, recall, Color.END)\n print(\">> F1: \", Color.PURPLE, f1, Color.END)\n print()\n\n # Write these values to a text file\n with open(SAVE_DIR + \"final_test.txt\", \"wb\") as f:\n f.write(str(acc) + \"\\n\")\n f.write(str(l) + \"\\n\")\n f.write(str(precision) + \"\\n\")\n f.write(str(recall) + \"\\n\")\n f.write(str(f1) + \"\\n\")\n\n # Get the batch of test data\n batch_data = train_data\n\n # Extract the data into three numpy arrays\n batch_sentences = np.asarray([x for x, _ in batch_data])\n batch_labels = np.asarray([num2onehot(x, NUM_CLASSES) for _, x in batch_data])\n\n # Create the feed_dict\n feed_dict = {\n sentence_input: batch_sentences,\n labels: batch_labels,\n keep_prob: 1\n }\n\n # Run accuracy and loss\n l, acc, y_pred, y_true = sess.run([loss, accuracy, pred_answers, correct_answers], feed_dict=feed_dict)\n\n # Compute Precision, Recall and F1 score\n precision, recall, f1, _ = precision_recall_fscore_support(y_true, y_pred, average=\"binary\")\n\n print(\"\\n>>>> FINAL TRAINING ACCURACY AND LOSS FOR \" + MODEL_NAME + \" <<<<\")\n print(\">> Hidden Layer Weights: \", Color.YELLOW, HIDDEN_LAYER_WEIGHTS, Color.END)\n print(\">> Accuracy: \", Color.CYAN, acc, Color.END)\n print(\">> Loss: \", Color.YELLOW, l, Color.END)\n print(\">> Precision: \", Color.YELLOW, precision, Color.END)\n print(\">> Recall: \", Color.YELLOW, recall, Color.END)\n print(\">> F1: \", Color.PURPLE, f1, Color.END)\n print()\n\n # Write these values to a text file\n with open(SAVE_DIR + \"final_train.txt\", \"wb\") as f:\n f.write(str(acc) + \"\\n\")\n f.write(str(l) + \"\\n\")\n f.write(str(precision) + \"\\n\")\n f.write(str(recall) + \"\\n\")\n f.write(str(f1) + \"\\n\")\n\n# ======================================","sub_path":"Models/CombinedClassifier/combined_MLP_classifier.py","file_name":"combined_MLP_classifier.py","file_ext":"py","file_size_in_byte":14140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"176058216","text":"# -*- coding: utf-8 -*-\n\nimport os, sys\n\nimport Tkinter as tk\nfrom tkFileDialog import askopenfilename, askdirectory\n\n\n\ndef _ask(method, *args, **kwargs):\n root = tk.Tk()\n kwargs[\"parent\"] = root\n path = method(*args, **kwargs)\n root.destroy()\n \n if path == \"\": # Nothing selected.\n sys.exit()\n \n if isinstance(path, tuple):\n return [os.path.normpath(i) for i in path]\n else:\n return os.path.normpath(path)\n\ndef askdirectory2(*args, **kwargs):\n return _ask(askdirectory, *args, **kwargs)\n\n\ndef askopenfilename2(*args, **kwargs):\n return _ask(askopenfilename, *args, **kwargs)\n\ndef askopenfilename3(title, initialfile, filetypes):\n file_path = askopenfilename2(\n title=title,\n initialfile=initialfile,\n filetypes=filetypes,\n )\n if file_path == \"\":\n sys.exit()\n else:\n return file_path\n\ndef askfilepath(filename):\n return askopenfilename3(\n title = \"Please select '%s':\" % filename,\n initialfile=filename,\n filetypes=[(filename,filename)]\n )\n\ndef simple_input(title, pre_lable, init_value, post_lable=\"\"):\n \"\"\"\n bsp.:\n new_value = simple_input( \n title=\"The window title\",\n pre_lable=\"Please input:\",\n init_value=old_value,\n post_lable=\"(in Bytes)\",\n )\n \"\"\" \n root = tk.Tk()\n root.title(title)\n \n tk.Label(root, text=pre_lable).pack()\n \n # Value input field\n var = tk.StringVar(root)\n var.set(init_value)\n tk.Entry(root, textvariable = var).pack()\n \n tk.Label(root, text=post_lable).pack()\n \n # Buttons\n tk.Button(root, text = \"OK\", command=root.destroy).pack(side=tk.RIGHT)\n tk.Button(root, text = \"Abort\", command=sys.exit).pack(side=tk.RIGHT)\n \n tk.mainloop()\n \n return var.get()\n\n\n\nclass TkListbox(object):\n \"\"\"\n Simple Tkinter listbox.\n example:\n\n streams_txt = [\"one\", \"two\", \"three\"]\n\n lb = TkListbox(\n title = \"Please select\",\n lable = \"Please select streams:\",\n items = streams_txt,\n activated = (0,2), # Preselect \"one\" and \"three\"\n )\n print lb.curselection # tuple containing index of selected items\n print lb.selection # list of selected items.\n \"\"\"\n def __init__(self, title, lable, items, activated=[], \\\n selectmode=tk.MULTIPLE, width=100):\n self.selection = []\n self.items = items\n\n self.root = tk.Tk()\n self.root.title(title)\n tk.Label(self.root, text=lable, font = \"Tahoma 9 bold\").pack()\n\n self.listbox = tk.Listbox(\n self.root, selectmode=selectmode, height=len(items), width=width\n )\n self.listbox.pack()\n\n for txt in self.items:\n self.listbox.insert(tk.END, txt)\n\n for index in activated:\n self.listbox.selection_set(index)\n\n b = tk.Button(self.root, text = \"OK\", command=self.save_selection)\n b.pack(side=tk.RIGHT)\n b = tk.Button(self.root, text = \"Abort\", command=sys.exit)\n b.pack(side=tk.RIGHT)\n\n tk.mainloop()\n\n def save_selection(self):\n self.curselection = [int(i) for i in self.listbox.curselection()]\n self.selection = []\n for index in self.curselection:\n self.selection.append(self.items[index])\n\n self.root.destroy()\n\n\n\ndef simple_select(items, title=\"Select\", text=\"Please select:\"):\n root = tk.Tk()\n root.title(title)\n tk.Label(root, text=text, font = \"Tahoma 9 bold\").pack()\n\n var = tk.IntVar()\n for no, item in enumerate(items):\n r = tk.Radiobutton(root, text=item, variable=var, value=no)\n r.pack()\n\n tk.Button(root, text = \"OK\", command=root.destroy).pack(side=tk.RIGHT)\n tk.Button(root, text = \"Abort\", command=sys.exit).pack(side=tk.RIGHT)\n tk.mainloop()\n \n selection = var.get()\n selected_item = items[selection]\n return selected_item","sub_path":"CodeSnippets/VideoTools/shared/tk_tools.py","file_name":"tk_tools.py","file_ext":"py","file_size_in_byte":3988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"505783081","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/1/23 22:02\n# @Author : Linder\n# @Email : lmj2018666@gmail.com\n# @Software: PyCharm\nclass Solution:\n\tdef isPalindrome(self, x):\n\t\t\"\"\"\n\t\t:type x: int\n\t\t:rtype: bool\n\t\t\"\"\"\n\t\tlst_r=list(str(x))\n\t\tlst=lst_r.copy()\n\t\tlst_r.reverse()\n\t\treturn(lst_r==lst)\n\nif __name__=='__main__':\n\tprint(Solution().isPalindrome(12321))","sub_path":"leetcode/0123回文数.py","file_name":"0123回文数.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"396321752","text":"from keras.layers import Input, Add, Dense, Flatten, Conv2D,GlobalAveragePooling2D, \\\n Reshape, Multiply, LeakyReLU, Concatenate, Lambda\nfrom keras.models import Sequential, Model\nfrom keras.layers.advanced_activations import ELU\n\nfrom keras.initializers import glorot_uniform\n\nfrom keras.optimizers import RMSprop\nfrom keras import backend as K\nfrom keras.models import Model\nimport tensorflow as tf\nimport numpy as np\nimport threading, queue\nimport time\n\nfrom astra import Astra\nimport glob\nimport os\nimport enviroments\nimport pickle\nimport copy\n\nfrom data.assembly import FreshAssembly\n\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport time\n\nimport multiprocessing as mp\n\n# 멀티쓰레딩을 위한 글로벌 변수\nglobal episode\nepisode = 0\nEPISODES = 8000000\n# 환경 생성\n\nab55 = [\n [0, 9, 9],\n [1, 9, 10],\n [2, 9, 11],\n [3, 9, 12],\n [4, 9, 13],\n [5, 9, 14],\n [6, 9, 15],\n [7, 9, 16],\n [8, 9, 17],\n [9, 9, 18],\n [11, 10, 10],\n [12, 10, 11],\n [13, 10, 12],\n [14, 10, 13],\n [15, 10, 14],\n [16, 10, 15],\n [17, 10, 16],\n [18, 10, 17],\n [19, 10, 18],\n [22, 11, 11],\n [23, 11, 12],\n [24, 11, 13],\n [25, 11, 14],\n [26, 11, 15],\n [27, 11, 16],\n [28, 11, 17],\n [29, 11, 18],\n [33, 12, 12],\n [34, 12, 13],\n [35, 12, 14],\n [36, 12, 15],\n [37, 12, 16],\n [38, 12, 17],\n [39, 12, 18],\n [44, 13, 13],\n [45, 13, 14],\n [46, 13, 15],\n [47, 13, 16],\n [48, 13, 17],\n [49, 13, 18],\n [55, 14, 14],\n [56, 14, 15],\n [57, 14, 16],\n [58, 14, 17],\n [59, 14, 18],\n [66, 15, 15],\n [67, 15, 16],\n [68, 15, 17],\n [69, 15, 18],\n [77, 16, 16],\n [78, 16, 17],\n [79, 16, 18],\n [88, 17, 17],\n [89, 17, 18],\n [99, 18, 18],\n]\n\nab_si = [\n [1, 9, 10],\n [2, 9, 11],\n [3, 9, 12],\n [4, 9, 13],\n [5, 9, 14],\n [6, 9, 15],\n [7, 9, 16],\n [11, 10, 10],\n [22, 11, 11],\n [33, 12, 12],\n [44, 13, 13],\n [55, 14, 14],\n]\n\nab_in = [\n [12, 10, 11],\n [13, 10, 12],\n [14, 10, 13],\n [15, 10, 14],\n [16, 10, 15],\n [17, 10, 16],\n [23, 11, 12],\n [24, 11, 13],\n [25, 11, 14],\n [26, 11, 15],\n [27, 11, 16],\n [34, 12, 13],\n [35, 12, 14],\n [36, 12, 15],\n [45, 13, 14],\n [46, 13, 15],\n]\n\n\ncl_base = 17000\nfxy_base = 1.55\n\ndef convolution_block_se_lk(X, f, filters, stage, block, s=2):\n conv_name_base = 'res' + str(stage) + block + '_branch'\n bn_name_base = 'bn' + str(stage) + block + '_branch'\n\n F1, F2, F3 = filters\n\n X_shortcut = X\n\n X = Conv2D(filters=F1, kernel_size=(1, 1), strides=(s, s), padding='valid', name=conv_name_base + '2a',\n kernel_initializer=glorot_uniform(seed=0))(X)\n #X = BatchNormalization(axis=3, name=bn_name_base + '2a', trainable=False)(X)\n X = LeakyReLU()(X)\n\n X = Conv2D(filters=F2, kernel_size=(f, f), strides=(1, 1), padding='same', name=conv_name_base + '2b',\n kernel_initializer=glorot_uniform(seed=0))(X)\n #X = BatchNormalization(axis=3, name=bn_name_base + '2b', trainable=False)(X)\n X = LeakyReLU()(X)\n\n X = Conv2D(filters=F3, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2c',\n kernel_initializer=glorot_uniform(seed=0))(X)\n #X = BatchNormalization(axis=3, name=bn_name_base + '2c', trainable=False)(X)\n\n se = GlobalAveragePooling2D(name='pool' + bn_name_base + '_gap')(X)\n se = Dense(F3 // 16, activation='relu', name = 'fc' + bn_name_base + '_sqz')(se)\n se = Dense(F3, activation='sigmoid', name = 'fc' + bn_name_base + '_exc')(se)\n se = Reshape([1, 1, F3])(se)\n X = Multiply(name='scale' + bn_name_base)([X, se])\n\n X_shortcut = Conv2D(filters=F3, kernel_size=(1, 1), strides=(s, s), padding='valid', name=conv_name_base + '1',\n kernel_initializer=glorot_uniform(seed=0))(X_shortcut)\n #X_shortcut = BatchNormalization(axis=3, name=bn_name_base + '1', trainable=False)(X_shortcut)\n\n X = Add()([X_shortcut, X])\n X = LeakyReLU()(X)\n\n return X\n\ndef identity_block_se_lk(X, f, filters, stage, block):\n conv_name_base = 'res' + str(stage) + block + '_branch'\n bn_name_base = 'bn' + str(stage) + block + '_branch'\n\n F1, F2, F3 = filters\n\n X_shortcut = X\n\n X = Conv2D(filters=F1, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2a',\n kernel_initializer=glorot_uniform(seed=0))(X)\n #X = BatchNormalization(axis=3, name=bn_name_base + '2a', trainable=False)(X)\n X = LeakyReLU()(X)\n\n X = Conv2D(filters=F2, kernel_size=(f, f), strides=(1, 1), padding='same', name=conv_name_base + '2b',\n kernel_initializer=glorot_uniform(seed=0))(X)\n #X = BatchNormalization(axis=3, name=bn_name_base + '2b', trainable=False)(X)\n X = LeakyReLU()(X)\n\n X = Conv2D(filters=F3, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2c',\n kernel_initializer=glorot_uniform(seed=0))(X)\n #X = BatchNormalization(axis=3, name=bn_name_base + '2c', trainable=False)(X)\n\n se = GlobalAveragePooling2D(name='pool' + bn_name_base + '_gap')(X)\n se = Dense(F3 // 16, activation='relu', name = 'fc' + bn_name_base + '_sqz')(se)\n se = Dense(F3, activation='sigmoid', name = 'fc' + bn_name_base + '_exc')(se)\n se = Reshape([1, 1, F3])(se)\n X = Multiply(name='scale' + bn_name_base)([X, se])\n\n X = Add()([X, X_shortcut])\n X = LeakyReLU()(X)\n\n return X\n\ndef build_feature_map(input_shape, output_dim=1280):\n input = Input(shape=input_shape)\n stage = 0;\n\n for i in range(5):\n stage_filters = [64, 64, 256]\n X = convolution_block_se_lk(input, f=3, filters=stage_filters, stage=stage, block='fca_{}'.format(i),\n s=1)\n X = identity_block_se_lk(X, 3, stage_filters, stage=stage, block='fcb_{}'.format(i))\n X = identity_block_se_lk(X, 3, stage_filters, stage=stage, block='fcc_{}'.format(i))\n stage = stage + 1\n for i in range(5, 7):\n stage_filters = [int(64//2), int(64//2), int(256//2)]\n X = convolution_block_se_lk(input, f=3, filters=stage_filters, stage=stage, block='fca_{}'.format(i),\n s=1)\n X = identity_block_se_lk(X, 3, stage_filters, stage=stage, block='fcb_{}'.format(i))\n X = identity_block_se_lk(X, 3, stage_filters, stage=stage, block='fcc_{}'.format(i))\n stage = stage + 1\n\n\n conv = Flatten()(X)\n fc = Dense(output_dim, name=\"feature\", activation='relu')(conv)\n model = Model(inputs=input, outputs=fc)\n return model\n\ndef build_feature_map_full(input_shape, output_dim=248, name = \"ori\"):\n input = Input(shape=input_shape)\n classes = output_dim\n X = Dense(248, name='fc1' + str(classes) + str(name), kernel_initializer=glorot_uniform(seed=0))(input)\n X = ELU()(X)\n X = Dense(248*2, name='fc2' + str(classes)+ str(name), kernel_initializer=glorot_uniform(seed=0))(X)\n X = ELU()(X)\n X = Dense(248*3, name='fc3' + str(classes)+ str(name), kernel_initializer=glorot_uniform(seed=0))(X)\n X = ELU()(X)\n X = Dense(248*2, name='fc4' + str(classes)+ str(name), kernel_initializer=glorot_uniform(seed=0))(X)\n X = ELU()(X)\n X = Dense(248, name='fc5' + str(classes)+ str(name), kernel_initializer=glorot_uniform(seed=0))(X)\n X = ELU()(X)\n\n fc = Dense(output_dim, name=\"feature\"+ str(name), activation='relu')(X)\n model = Model(inputs=input, outputs=fc)\n return model\n\ndef build_feature_map_full_connected(input_shape, output_dim=1280, name = \"global\"):\n input = Input(shape=input_shape, name=\"power_input\")\n classes = output_dim\n X = Dense(248, name='fc1' + str(classes) + str(name), kernel_initializer=glorot_uniform(seed=0))(input)\n X = ELU()(X)\n X = Dense(248*2, name='fc2' + str(classes)+ str(name), kernel_initializer=glorot_uniform(seed=0))(X)\n X = ELU()(X)\n X = Dense(248*3, name='fc3' + str(classes)+ str(name), kernel_initializer=glorot_uniform(seed=0))(X)\n X = ELU()(X)\n X = Dense(248*2, name='fc4' + str(classes)+ str(name), kernel_initializer=glorot_uniform(seed=0))(X)\n X = ELU()(X)\n X = Dense(248, name='fc5' + str(classes)+ str(name), kernel_initializer=glorot_uniform(seed=0))(X)\n X = ELU()(X)\n\n fc = Dense(output_dim, name=\"feature\"+ str(name), activation='relu')(X)\n\n return input, fc\n\ndef inverse_model(output_dim=3300):\n \"\"\"\n s_t, s_t+1 -> a_t\n \"\"\"\n def func(ft0, ft1):\n h = Concatenate()([ft0, ft1])\n h = Dense(256, activation='relu')(h)\n h = Dense(output_dim, activation='sigmoid')(h)\n return h\n return func\n\ndef forward_model(output_dim=1280):\n \"\"\"\n s_t, a_t -> s_t+1\n \"\"\"\n def func(ft, at):\n h = Concatenate()([ft, at])\n h = Dense(256, activation='relu')(h)\n h = Dense(output_dim, activation='linear')(h)\n return h\n return func\n\ndef get_reward_intrinsic(model, intrinsic, x):\n return K.function([model.get_layer(\"state0\").input,\n model.get_layer(\"state1\").input,\n model.get_layer(\"action\").input],\n [intrinsic])(x)[0]\n\n# 브레이크아웃에서의 A3CAgent 클래스(글로벌신경망)\nclass A3CAgent:\n def __init__(self):\n # Enviroments f\n self.spaces = enviroments.Environment(action_main_shape=(400,), action_sub_shapes=(55,),observation_shape=(15,15,25))\n\n self.state_size = self.spaces.observation_space.shape\n self.action_size = self.spaces.action_space.shape[0]\n # A3C 하이퍼파라미터\n self.discount_factor = 0.80\n self.no_op_steps = 30\n self.actor_lr = 2.5e-5\n self.critic_lr = 2.5e-6\n # 쓰레드의 갯수\n self.threads = 6\n self.policies = []\n\n for index in range(9):\n policy_array = []\n for jnjex in range(self.spaces.action_space.shape[0]):\n policy_array.append(0)\n self.policies.append(policy_array)\n\n # 정책신경망과 가치신경망을 생성\n self.actor, self.critic, self.n_critic = self.build_model()\n\n self.icm, self.icm2, self.r_in, self.icm_optimizer= self.build_icm_model((500,), self.spaces.action_space.shape)\n\n # 정책신경망과 가치신경망을 업데이트하는 함수 생성\n self.optimizer = [self.actor_optimizer(), self.critic_optimizer(), self.icm_optimizer, self.n_critic_optimizer()]\n\n # 텐서보드 설정\n self.sess = tf.InteractiveSession()\n K.set_session(self.sess)\n self.sess.run(tf.global_variables_initializer())\n\n self.summary_placeholders, self.update_ops, self.summary_op = \\\n self.setup_summary()\n self.summary_writer = \\\n tf.summary.FileWriter('summary/astra_a3c', self.sess.graph)\n\n\n # 쓰레드를 만들어 학습을 하는 함수\n def train(self):\n my_queue = queue.Queue()\n\n #self.load_model(\"./save_model/astra_a3c\")\n # 쓰레드 수만큼 Agent 클래스 생성\n the_directory = \"{}{}{}{}{}depl{}\".format(\"/home/youndukn/Plants/1.4.0/\",\n \"ygn3\",\n os.path.sep,\n 'c{0:02}'.format(10),\n os.path.sep,\n os.path.sep)\n\n\n\n agents = []\n for thread_id in range(self.threads):\n agents.append(Agent(self.action_size, self.state_size,\n [self.actor, self.critic, self.n_critic], self.sess,\n self.optimizer, self.discount_factor,\n [self.summary_op, self.summary_placeholders,\n self.update_ops, self.summary_writer], the_directory, thread_id, self.icm,self.icm2, self.r_in, my_queue))\n\n # 각 쓰레드 시작\n for agent in agents:\n time.sleep(1)\n agent.start()\n\n fig, axs = plt.subplots(3, 5, figsize=(20, 15))\n\n lns = []\n for row in range(3):\n columns = []\n for column in range(5):\n columns.append(axs[row, column].plot([], [], 'bo'))\n lns.append(columns)\n plt.show(block=False)\n\n last_summary_time = time.time()\n summary_interval = 1000\n\n while True:\n item = my_queue.get()\n row = int(item[0] / 2)%3\n axs[row, 0].set_title(\"thread{:d}\".format(item[0]))\n axs[row, 0].imshow(item[1][:-2,:-2])\n #axs[row, 1].imshow(item[10])\n lns[row][3][0].set_xdata(range(0, self.spaces.action_space.shape[0]))\n lns[row][3][0].set_ydata(item[2])\n axs[row, 3].relim()\n axs[row, 3].autoscale_view(True, True, True)\n\n lns[row][4][0].set_xdata(range(0, self.spaces.action_space.shape[0]))\n lns[row][4][0].set_ydata(item[-1])\n axs[row, 4].relim()\n axs[row, 4].autoscale_view(True, True, True)\n\n #axs[row, 2].imshow(item[2])\n axs[row, 1].imshow(np.array(item[5][:-2, :-2]))\n #axs[row, 4].imshow(np.array(item[3][0]))\n #axs[row, 4].set_title(\"pre cl fxy {:3.2f} {:3.2f}\".format(item[6], item[7]))\n axs[row, 2].imshow(np.array(item[4][0][:-2, :-2]))\n axs[row, 2].set_title(\"{:3.2f} {:3.2f}->{:3.2f} {:3.2f}\".format(item[6], item[7], item[8], item[9]))\n fig.canvas.draw()\n now = time.time()\n if now - last_summary_time > summary_interval:\n self.save_model(\"./save_model/astra_a3c\")\n last_summary_time=now\n\n \"\"\"\n fig, axs = plt.subplots(3, 3, figsize=(13, 10))\n\n lns = []\n for thread_id in range(9):\n x = int(thread_id % 3)\n y = int(thread_id / 3)\n\n lns.append(axs[x, y].plot([], [], 'bo'))\n plt.show(block=False)\n\n last_summary_time = time.time()\n summary_interval = 1000\n\n while True:\n # if show_training:\n # for env in envs:\n # env.render()\n\n item = my_queue.get()\n if item:\n x = int(item[0] % 3)\n y = int(item[0] / 3)\n # ln.set_xdata(range(0, get_num_actions()))\n # ln.set_ydata(item[1])\n\n lns[item[0]][0].set_xdata(range(0, self.spaces.action_space.shape[0]))\n # indexes = np.where(np.logical_and(item[1] >= np.percentile(item[1], 5), item[1] <= np.percentile(item[1], 95)))\n # item[1][indexes] = 0\n array = item[1]\n lns[item[0]][0].set_ydata(array)\n # axs[x,y].plot(range(0, get_num_actions()), item[1], block=False)\n axs[x, y].relim()\n axs[x, y].autoscale_view(True, True, True)\n axs[x, y].set_title(\"thread{:d}\".format(item[0]))\n fig.canvas.draw()\n\n now = time.time()\n if now - last_summary_time > summary_interval:\n self.save_model(\"./save_model/astra_a3c\")\n last_summary_time=now\n \n \n \"\"\"\n\n # 정책신경망과 가치신경망을 생성\n def build_model(self):\n input = Input(shape=self.state_size, name=\"xs_input\")\n stage = 0;\n\n for i in range(5):\n stage_filters = [64, 64, 256]\n X = convolution_block_se_lk(input, f=3, filters=stage_filters, stage=stage, block='ca_{}'.format(i),\n s=1)\n X = identity_block_se_lk(X, 3, stage_filters, stage=stage, block='cb_{}'.format(i))\n X = identity_block_se_lk(X, 3, stage_filters, stage=stage, block='cc_{}'.format(i))\n stage = stage + 1\n\n for i in range(5, 7):\n stage_filters = [64 // 2, 64 // 2, 256 // 2]\n X = convolution_block_se_lk(input, f=3, filters=stage_filters, stage=stage, block='fca_{}'.format(i),\n s=1)\n X = identity_block_se_lk(X, 3, stage_filters, stage=stage, block='fcb_{}'.format(i))\n X = identity_block_se_lk(X, 3, stage_filters, stage=stage, block='fcc_{}'.format(i))\n stage = stage + 1\n\n\n conv = Flatten()(X)\n fc = Dense(3800, activation='relu')(conv)\n f_input, f_output =build_feature_map_full_connected((500, ))\n\n fc = Concatenate()([f_output, fc])\n\n policy = Dense(self.action_size, activation='softmax')(fc)\n value = Dense(1, activation='linear')(fc)\n n_value = Dense(1, activation='linear')(fc)\n\n actor = Model(inputs=[input, f_input], outputs=policy)\n critic = Model(inputs=[input, f_input], outputs=value)\n n_critic = Model(inputs=[input, f_input], outputs=n_value)\n\n # 가치와 정책을 예측하는 함수를 만들어냄\n actor._make_predict_function()\n critic._make_predict_function()\n n_critic._make_predict_function()\n\n actor.summary()\n critic.summary()\n n_critic.summary()\n\n return actor, critic, n_critic\n\n\n def build_icm_model(self, state_shape, action_shape, lmd=0.2, beta=0.01):\n s_t0 = Input(shape=state_shape, name=\"state0\")\n s_t1 = Input(shape=state_shape, name=\"state1\")\n a_t = Input(shape=action_shape, name=\"action\")\n fmap = build_feature_map_full(state_shape)\n f_t0 = fmap(s_t0)\n f_t1 = fmap(s_t1)\n act_hat = inverse_model(action_shape[0])(f_t0, f_t1)\n f_t1_hat = forward_model(output_dim=248)(f_t0, a_t)\n\n r_in = Lambda(lambda x: 0.5 * K.sum(K.square(x[0] - x[1]), axis=-1), name=\"intrinsic_reward\")([f_t1, f_t1_hat])\n l_i = Lambda(lambda x: -K.sum(x[0] * K.log(x[1] + K.epsilon()), axis=-1))([a_t, act_hat])\n loss0 =Lambda(lambda x: beta * x[0] + (1.0 - beta) * x[1])([r_in, l_i])\n rwd = Input(shape=(1,))\n loss = Lambda(lambda x: (-lmd * x[0] + x[1]))([rwd, loss0])\n \"\"\"\n r_in = merge([f_t1, f_t1_hat], mode=lambda x: 0.5 * K.sum(K.square(x[0] - x[1]), axis=-1),\n output_shape=(1,), name=\"reward_intrinsic\")\n l_i = merge([a_t, act_hat], mode=lambda x: -K.sum(x[0] * K.log(x[1] + K.epsilon()), axis=-1),\n output_shape=(1,))\n loss0 = merge([r_in, l_i],\n mode=lambda x: beta * x[0] + (1.0 - beta) * x[1],\n output_shape=(1,))\n loss = merge([rwd, loss0],\n mode=lambda x: (-lmd * x[0].T + x[1]).T,\n output_shape=(1,))\n \"\"\"\n model2 = Model([s_t0, s_t1, a_t], [r_in])\n model2._make_predict_function()\n model2.summary()\n\n model = Model([s_t0, s_t1, a_t, rwd], loss)\n model._make_predict_function()\n model.summary()\n\n optimizer = RMSprop(lr=self.actor_lr)\n updates = optimizer.get_updates(model.trainable_weights, [],loss)\n train = K.function([s_t0, s_t1, a_t, rwd],\n [loss], updates=updates)\n\n return model, model2, r_in, train\n\n # 정책신경망을 업데이트하는 함수\n def actor_optimizer(self):\n action = K.placeholder(shape=[None, self.action_size])\n advantages = K.placeholder(shape=[None, ])\n old_policy = K.placeholder(shape=[None, self.action_size])\n\n policy = self.actor.output\n\n # 정책 크로스 엔트로피 오류함수\n action_prob = K.sum(action * policy, axis=1)\n old_action_prob = K.sum(action * old_policy, axis=1)\n #cross_entropy = K.clip(action_prob/(old_action_prob + 1e-10), min_value= 0.8, max_value=1.2) * advantages\n cross_entropy = K.log(old_action_prob + 1e-10) * advantages\n cross_entropy = -K.sum(cross_entropy)\n\n # 탐색을 지속적으로 하기 위한 엔트로피 오류\n #entropy = K.sum(policy * K.log(policy/(old_policy + 1e-10)), axis=1)\n entropy = K.sum(policy * K.log(old_policy + 1e-10), axis=1)\n entropy = K.sum(entropy)\n\n # 두 오류함수를 더해 최종 오류함수를 만듬\n loss = cross_entropy + 0.01 * entropy\n\n optimizer = RMSprop(lr=self.actor_lr)\n updates = optimizer.get_updates(self.actor.trainable_weights, [],loss)\n train = K.function([self.actor.get_layer(\"xs_input\").input,\n self.actor.get_layer(\"power_input\").input,\n action,\n advantages,\n old_policy],\n [loss], updates=updates)\n return train\n\n # 가치신경망을 업데이트하는 함수\n def critic_optimizer(self):\n discounted_prediction = K.placeholder(shape=(None,))\n\n value = self.critic.output\n\n # [반환값 - 가치]의 제곱을 오류함수로 함\n loss = K.mean(K.square(discounted_prediction - value))\n\n optimizer = RMSprop(lr=self.critic_lr)\n updates = optimizer.get_updates(self.critic.trainable_weights, [],loss)\n train = K.function([self.critic.get_layer(\"xs_input\").input,\n self.critic.get_layer(\"power_input\").input,\n discounted_prediction],\n [loss], updates=updates)\n return train\n\n # 가치신경망을 업데이트하는 함수\n def n_critic_optimizer(self):\n discounted_prediction = K.placeholder(shape=(None,))\n\n value = self.n_critic.output\n\n # [반환값 - 가치]의 제곱을 오류함수로 함\n loss = K.mean(K.square(discounted_prediction - value))\n\n optimizer = RMSprop(lr=self.critic_lr, rho=0.999)\n updates = optimizer.get_updates(self.n_critic.trainable_weights, [], loss)\n train = K.function([self.n_critic.get_layer(\"xs_input\").input,\n self.n_critic.get_layer(\"power_input\").input,\n discounted_prediction],\n [loss], updates=updates)\n return train\n\n def load_model(self, name):\n self.actor.load_weights(name + \"_actor.h5\")\n self.critic.load_weights(name + \"_critic.h5\")\n self.n_critic.load_weights(name + \"_n_critic.h5\")\n self.icm.load_weights(name+\"_icm.h5\")\n\n def save_model(self, name):\n self.actor.save_weights(name + \"_actor.h5\")\n self.critic.save_weights(name + \"_critic.h5\")\n self.n_critic.save_weights(name + \"_n_critic.h5\")\n self.icm.save_weights(name + \"_icm.h5\")\n\n # 각 에피소드 당 학습 정보를 기록\n def setup_summary(self):\n episode_total_reward = tf.Variable(0.)\n episode_avg_max_q = tf.Variable(0.)\n episode_duration = tf.Variable(0.)\n\n tf.summary.scalar('Total Reward/Episode', episode_total_reward)\n tf.summary.scalar('Average Max Prob/Episode', episode_avg_max_q)\n tf.summary.scalar('Duration/Episode', episode_duration)\n\n summary_vars = [episode_total_reward,\n episode_avg_max_q,\n episode_duration]\n\n summary_placeholders = [tf.placeholder(tf.float32)\n for _ in range(len(summary_vars))]\n update_ops = [summary_vars[i].assign(summary_placeholders[i])\n for i in range(len(summary_vars))]\n summary_op = tf.summary.merge_all()\n return summary_placeholders, update_ops, summary_op\n\n\n# 액터러너 클래스(쓰레드)\nclass Agent(threading.Thread):\n def __init__(self, action_size, state_size, model, sess,\n optimizer, discount_factor, summary_ops, input_directory, thread_id, icm,icm2, r_in, my_queue):\n threading.Thread.__init__(self)\n\n #Action Space\n self.spaces = enviroments.Environment(action_main_shape=(400,), action_sub_shapes=(55,),observation_shape=(15,15,25))\n\n # A3CAgent 클래스에서 상속\n self.action_size = action_size\n self.state_size = state_size\n self.actor, self.critic, self.n_critic = model\n self.sess = sess\n self.optimizer = optimizer\n self.discount_factor = discount_factor\n [self.summary_op, self.summary_placeholders,\n self.update_ops, self.summary_writer] = summary_ops\n self.icm = icm\n self.icm2 = icm2\n self.r_in = r_in\n self.thread_id = thread_id\n self.queue = my_queue\n\n self.target = (16300, 1.55)\n\n self.epsilon = 0.0\n self.epsilon_decay =0.999\n\n self.pre_actions = np.zeros(self.action_size)\n\n # 지정된 타임스텝동안 샘플을 저장할 리스트\n self.states, self.actions, self.rewards, self.next_states, self.outputs, self.next_outputs= [], [], [], [], [], []\n self.n_states, self.n_next_states, self.n_actions, self.n_rewards, self.n_outputs, self.n_next_outputs = [], [], [], [], [], []\n self.policies = []\n self.n_policies = []\n self.next_policies = []\n self.n_next_policies = []\n\n # 로컬 모델 생성\n self.local_actor= self.build_local_model()\n\n self.avg_p_max = 0\n self.avg_loss = 0\n\n # 모델 업데이트 주기\n self.t_max = 15\n self.t = 0\n\n self.T = 0\n\n\n #create enviroment with directory\n directory = \"{}{}{}\".format(input_directory, os.path.sep, thread_id)\n if not os.path.exists(directory):\n os.makedirs(directory)\n input_name = glob.glob(\"{}01_*.inp\".format(input_directory))\n self.env = Astra(input_name[0], reward_list_target=\n (16300, 0, 0, 0, 1.55, 0), main_directory = input_directory, working_directory=directory)\n\n self.file = open('/media/youndukn/lastra/plants_data6/{}_data_{}'.\n format(input_name[0].replace(input_directory, \"\"), self.thread_id), 'wb')\n\n self.file_trainable = open('/media/youndukn/lastra/trainable_data6/{}_data_{}'.\n format(input_name[0].replace(input_directory, \"\"), self.thread_id), 'wb')\n\n\n def my_input_output(self, values):\n burnup_boc = values[0]\n burnup_eoc = values[-1]\n \"\"\"\n s_batch_init = burnup_boc.input_tensor_full\n s_batch_init_den = burnup_boc.density_tensor_full\n s_batch_init_den = np.array(s_batch_init_den)\n my_state = np.concatenate((s_batch_init, s_batch_init_den), axis=2)\n \"\"\"\n selected_range = [4, 5, 6, 7]\n s_batch_init = np.array(burnup_boc.input_tensor_full)\n for index in selected_range:\n s_batch_init_selected = values[index].input_tensor_full\n s_batch_init_selected = np.array(s_batch_init_selected)\n s_batch_init = np.concatenate((s_batch_init, s_batch_init_selected), axis=2)\n\n my_state = s_batch_init[2:-2,2:-2,:]\n\n my_output = np.array(burnup_boc.output_tensor)\n for index in selected_range:\n my_output = np.concatenate([my_output, values[index].output_tensor])\n\n o_batch_init = np.zeros((5, 10, 10))\n for indexes in ab55:\n o_batch_init[0][indexes[1]-9][indexes[2]-9] = burnup_boc.output_tensor[indexes[0]]\n o_batch_init[0][indexes[2] - 9][indexes[1] - 9] = burnup_boc.output_tensor[indexes[0]]\n\n for e_index, index in enumerate(selected_range):\n for indexes in ab55:\n o_batch_init[e_index+1][indexes[1] - 9][indexes[2] - 9] = \\\n values[index].output_tensor[indexes[0]]\n o_batch_init[e_index + 1][indexes[2] - 9][indexes[1] - 9] = \\\n values[index].output_tensor[indexes[0]]\n\n my_cl = burnup_eoc.summary_tensor[0]\n\n my_fxy = 0\n\n for burnup_point in values:\n if my_fxy < burnup_point.summary_tensor[5]:\n my_fxy = burnup_point.summary_tensor[5]\n return my_state, my_output, my_cl, my_fxy, o_batch_init\n\n def convert_f_index(self, action):\n\n if action < len(ab_in) * len(ab_in):\n\n pre_pos = action // len(ab_in)\n next_pos = action % len(ab_in)\n position = ab_in[pre_pos][0]\n posibilities = ab_in[next_pos][0]\n\n else:\n changed_action = action - len(ab_in) * len(ab_in)\n\n pre_pos = changed_action // len(ab_si)\n next_pos = changed_action % len(ab_si)\n\n position = ab_si[pre_pos][0]\n posibilities = ab_si[next_pos][0]\n\n for index, value in enumerate(ab55):\n if value[0] == position:\n a_position = index\n if value[0] == posibilities:\n a_posibilities = index\n\n return a_position, a_posibilities\n\n def run(self):\n global episode\n\n step = 0\n self.T = 0\n\n while episode < EPISODES:\n done = False\n\n score = 0\n self.env.reset()\n self.pre_actions = np.zeros(self.action_size)\n\n start_state, start_output, start_cl, start_fxy, start_output_matrix = self.my_input_output(self.env.get_cross_set())\n\n history = np.reshape([start_state], (1,\n self.spaces.observation_space.shape[0],\n self.spaces.observation_space.shape[1],\n self.spaces.observation_space.shape[2]))\n\n history_output = np.reshape([start_output], (1, 500))\n\n best_cl = start_cl\n best_fxy = start_fxy\n best_score = 0\n\n current_cl = start_cl\n current_fxy = start_fxy\n current_output = start_output\n current_output_matrix = start_output_matrix\n\n pre_cl = current_cl\n pre_fxy = current_fxy\n\n nonChanged = False\n\n n_trainable = []\n\n while not done:\n\n step += 1\n\n action, policy, m_policy = self.get_action(history, history_output)\n\n policy_matrix = np.zeros((10, 10))\n m_policy_matrix = np.zeros((10, 10))\n max_policy_matrix = np.zeros((10, 10))\n next_max_policy_matrix = np.zeros((10, 10))\n\n max_value = 0\n\n for p_index, police in enumerate(policy):\n\n position, posibilities = self.convert_f_index(p_index)\n\n if posibilities == 1 or posibilities == 11:\n max_value = 0\n\n policy_matrix[ab55[position][1] - 9][ab55[position][2] - 9] += police\n if ab55[position][2] != ab55[position][1]:\n policy_matrix[ab55[position][2] - 9][ab55[position][1] - 9] += police\n\n if police > max_value:\n max_policy_matrix[ab55[position][1] - 9][ab55[position][2] - 9] = police\n max_policy_matrix[ab55[position][2] - 9][ab55[position][1] - 9] = police\n max_value = police\n\n max_value = 0\n\n for p_index, police in enumerate(m_policy):\n\n position, posibilities = self.convert_f_index(p_index)\n\n if posibilities == 0:\n max_value = 0\n\n if police > max_value:\n m_policy_matrix[ab55[position][1] - 9][ab55[position][2] - 9] = police\n m_policy_matrix[ab55[position][2] - 9][ab55[position][1] - 9] = police\n max_value = police\n\n \"\"\"\n max_policy_index = np.argmax(policy)\n\n max_policy_position = max_policy_index // (self.spaces.action_space.shapes[0])\n\n p_index = max_policy_position * (self.spaces.action_space.shapes[0])\n p_index_1 = p_index+(self.spaces.action_space.shapes[0])\n\n for n_dex, police in enumerate(m_policy[p_index:p_index_1]):\n next_max_policy_matrix[ab55[n_dex][1] - 9][ab55[n_dex][2] - 9] = police\n next_max_policy_matrix[ab55[n_dex][2] - 9][ab55[n_dex][1] - 9] = police\n \"\"\"\n \"\"\"\n posibilities = action % (self.spaces.action_space.shapes[0] + 3 + 2)\n position = action // (self.spaces.action_space.shapes[0] + 3 + 2)\n\n \n if posibilities < self.spaces.action_space.shapes[0]:\n action_index = (position * self.spaces.action_space.shapes[0]) + posibilities\n s_t1, r_t, changed, info, satisfied = self.env.step_shuffle(action_index, [0, 4])\n elif posibilities >= self.spaces.action_space.shapes[0] and posibilities < self.spaces.action_space.shapes[0] + 3:\n action_index = (position * 3) + (posibilities - self.spaces.action_space.shapes[0])\n s_t1, r_t, changed, info, satisfied = self.env.step_rotate(action_index, [0, 4])\n elif posibilities >= self.spaces.action_space.shapes[0] + 3 and posibilities < self.spaces.action_space.shapes[0] + 5:\n action_index = (position * 2) + (posibilities - self.spaces.action_space.shapes[0] - 3)\n s_t1, r_t, changed, info, satisfied = self.env.step_bp(action_index, [0, 4])\n \"\"\"\n\n position, posibilities = self.convert_f_index(action)\n\n position_matrix = np.zeros((10, 10))\n\n core = self.env.get_last_core()\n for index1 in range(10):\n for index2 in range(10):\n if type(core.assemblies[index1][index2]) is FreshAssembly:\n position_matrix[index1][index2] = 0.5\n\n if position_matrix[ab55[position][1]-9][ab55[position][2]-9] == 0.5:\n position_matrix[ab55[position][1]-9][ab55[position][2]-9] = 1.5\n else:\n position_matrix[ab55[position][1] - 9][ab55[position][2] - 9] = 1\n\n if position_matrix[ab55[posibilities][1] - 9][ab55[posibilities][2] - 9] == 0.5:\n position_matrix[ab55[posibilities][1] - 9][ab55[posibilities][2] - 9] = 1.5\n else:\n position_matrix[ab55[posibilities][1] - 9][ab55[posibilities][2] - 9] = 1\n\n action_index = (position * self.spaces.action_space.shapes[0]) + posibilities\n s_t1, r_t, changed, info, succ_error, satisfied, best,cross_set = self.env.step_shuffle(action_index, [0, 4])\n\n if not succ_error:\n self.env.step_back()\n else:\n done = not info\n\n pre_cl = current_cl\n pre_fxy = current_fxy\n\n pre_output_matrix = current_output_matrix\n\n current_state, \\\n current_output, \\\n current_cl, \\\n current_fxy, \\\n current_output_matrix = \\\n self.my_input_output(cross_set)\n\n next_history = np.reshape([current_state], (1,\n self.spaces.observation_space.shape[0],\n self.spaces.observation_space.shape[1],\n self.spaces.observation_space.shape[2]))\n\n next_history_output = np.reshape([current_output], (1, 500))\n\n reward = ((10 * (min(self.target[0], current_cl) - min(self.target[0], pre_cl)) / cl_base + \\\n 10 * (max(self.target[1], pre_fxy) - max(self.target[1], current_fxy)) / fxy_base)/4)\n \"\"\"\n reward = (10 * (min(current_cl - self.target[0], 0)) / cl_base + \\\n 10 * (min(self.target[1] - current_fxy, 0)) / fxy_base)/4\n \"\"\"\n reward = reward*abs(reward)\n\n #r_in = get_reward_intrinsic(self.icm, self.r_in, )\n one_hot_action = np.zeros(self.spaces.action_space.shape)\n one_hot_action[action] = 1\n r_in = self.icm2.predict([history_output, next_history_output, np.array([one_hot_action])])[0]\n #r_in = 0\n # 정책의 최대값\n self.avg_p_max += np.amax(self.actor.predict([history, history_output]))\n\n non_clipped = reward\n\n reward = reward\n\n # score_addup\n score += reward\n\n #r_in = np.clip(r_in, 0, 1)\n\n reward = np.clip(reward, -1., 1.)\n\n self.t += 1\n if changed:\n\n # 샘플을 저장\n \"\"\"if nonChanged:\n self.append_sample(u_history,\n u_action,\n u_reward,\n u_next_history,\n u_history_output,\n u_next_history_output)\n \"\"\"\n\n self.queue.put([self.thread_id,\n max_policy_matrix,\n policy,\n pre_output_matrix,\n current_output_matrix,\n position_matrix,\n pre_cl,\n pre_fxy,\n current_cl,\n current_fxy,\n policy_matrix,\n m_policy])\n self.T += 1\n\n pickle.dump([history, action, reward, done], self.file_trainable, protocol=pickle.HIGHEST_PROTOCOL)\n\n dump_list = []\n for value in cross_set:\n a_list = [value.summary_tensor,\n value.input_tensor_full,\n value.output_tensor,\n value.flux_tensor,\n value.density_tensor_full]\n dump_list.append(a_list)\n\n values3 = self.critic.predict([history, history_output])[0]\n values4 = self.n_critic.predict([history, history_output])[0]\n\n values = self.critic.predict([next_history, next_history_output])[0]\n values2 = self.n_critic.predict([next_history, next_history_output])[0]\n\n print(\"|{:4d} |\".format(self.thread_id),\n \"{:4d} |\".format(ab55[position][1]-9),\n \"{:4d} |\".format(ab55[position][2]-9),\n \"{:4d} |\".format(ab55[posibilities][1]-9),\n \"{:4d} |\".format(ab55[posibilities][2]-9),\n \"{:3.2f} |\".format(current_cl),\n \"{:3.2f} |\".format(current_fxy),\n \"{:3.2f} |\".format(non_clipped),\n \"{:3.2f} |\".format(r_in),\n \"{:1.4f} |\".format(values[0]),\n \"{:1.4f} |\".format(values3[0]),\n \"{:1.4f} |\".format(values2[0]),\n \"{:1.4f} |\".format(values4[0]),\n )\n\n\n pickle.dump(dump_list, self.file, protocol=pickle.HIGHEST_PROTOCOL)\n nonChanged = True\n\n else:\n nonChanged = False\n u_history = history\n u_action = action\n u_reward = reward\n u_next_history = next_history\n u_history_output = history_output\n u_next_history_output = next_history_output\n\n next_policy = self.local_actor.predict([next_history, next_history_output])[0]\n self.append_sample(history,\n action,\n reward,\n next_history,\n history_output,\n next_history_output,\n policy,\n next_policy,\n 0)\n\n self.n_states, self.n_actions, self.n_rewards, self.n_next_states, self.n_outputs, self.n_next_outputs = [], [], [], [], [], []\n self.n_policies = []\n self.n_next_policies = []\n\n if best_cl <= current_cl and best_fxy >= current_fxy:\n best_cl = min(self.target[0], current_cl)\n best_fxy = max(self.target[1], current_fxy)\n best_score = score\n history = next_history\n history_output = next_history_output\n else:\n self.env.step_back()\n current_cl = pre_cl\n current_fxy = pre_fxy\n\n # 에피소드가 끝나거나 최대 타임스텝 수에 도달하면 학습을 진행\n if self.t >= self.t_max or done:\n #print(\"{}\".format(self.thread_id), ' '.join('{:3d}'.format(np.argmax(k)) for k in self.actions))\n #print(\"{}\".format(self.thread_id), ' '.join('{:3d}'.format(int(k*100)) for k in self.rewards))\n #print(\"{}\".format(self.thread_id), ' '.join('{:3d}'.format(np.argmax(k)) for k in self.n_actions))\n #print(\"{}\".format(self.thread_id), ' '.join('{:3d}'.format(int(k*100)) for k in self.n_rewards))\n\n if len(self.states)>=1:\n o1, o2, o3 = self.train_model(False)\n self.optimizer[0](o1)\n self.optimizer[1](o2)\n self.optimizer[2](o3)\n\n for n_o in n_trainable:\n self.optimizer[0](n_o[0])\n self.optimizer[3](n_o[1])\n self.optimizer[2](n_o[2])\n\n n_trainable = []\n\n self.states, self.actions, self.rewards, self.next_states, self.outputs, self.next_outputs = [], [], [], [], [], []\n self.policies = []\n self.next_policies = []\n\n self.update_local_model()\n self.t = 0\n done = True\n\n if done:\n # 각 에피소드 당 학습 정보를 기록\n episode += 1\n\n print(\n \"{:4d} |\".format(self.thread_id),\n \"{:4d} |\".format(self.T),\n \"{:4d} |\".format(step),\n \"{:3.2f} |\".format(start_cl),\n \"{:3.2f} |\".format(start_fxy),\n \"{:3.2f} |\".format(best_cl),\n \"{:3.2f} |\".format(best_fxy),\n \"{:3.2f} |\".format(best_score),\n \"{:3.2f} |\".format(score),\n \"{:3.2f} |\".format(self.epsilon),\n )\n\n stats = [score, self.avg_p_max / float(step), step]\n for i in range(len(stats)):\n self.sess.run(self.update_ops[i], feed_dict={\n self.summary_placeholders[i]: float(stats[i])\n })\n summary_str = self.sess.run(self.summary_op)\n self.summary_writer.add_summary(summary_str, episode + 1)\n self.avg_p_max = 0\n self.avg_loss = 0\n step = 0\n #self.T = 0\n\n # k-스텝 prediction 계산\n def discounted_prediction(self, rewards, done, next_states, next_outputs, reverse = False):\n discounted_prediction = np.zeros_like(rewards)\n\n running_add = 0\n\n for t in reversed(range(0, len(rewards))):\n running_add = self.critic.predict(\n [np.float32(next_states[-1]),\n np.float32(next_outputs[-1])]\n )[0]\n reward = rewards[t]\n if reverse:\n reward = reward*-1\n\n running_add = (running_add * self.discount_factor + reward)\n discounted_prediction[t] = running_add\n\n return discounted_prediction\n\n def n_discounted_prediction(self, rewards, done, next_states, next_outputs, reverse=False):\n discounted_prediction = np.zeros_like(rewards)\n\n for t in reversed(range(0, len(rewards))):\n\n running_add = self.critic.predict(\n [np.float32(next_states[t]),\n np.float32(next_outputs[t])]\n )[0]\n\n reward = rewards[t]\n if reverse:\n reward = reward * -1\n\n running_add = (running_add * self.discount_factor + reward)\n discounted_prediction[t] = running_add\n\n return discounted_prediction\n\n # 정책신경망과 가치신경망을 업데이트\n def train_model(self, done):\n\n states = np.zeros((len(self.states),\n self.spaces.observation_space.shape[0],\n self.spaces.observation_space.shape[1],\n self.spaces.observation_space.shape[2]))\n\n\n for i in range(len(self.states)):\n states[i] = self.states[i]\n\n\n states = np.float32(states)\n\n next_states = np.zeros((len(self.next_states),\n self.spaces.observation_space.shape[0],\n self.spaces.observation_space.shape[1],\n self.spaces.observation_space.shape[2]))\n\n for i in range(len(self.next_states)):\n next_states[i] = self.next_states[i]\n\n next_states = np.float32(next_states)\n\n outputs = np.zeros((len(self.outputs), 500))\n\n for i in range(len(self.outputs)):\n outputs[i] = self.outputs[i]\n\n outputs = np.float32(outputs)\n\n next_outputs = np.zeros((len(self.next_outputs), 500))\n\n for i in range(len(self.next_outputs)):\n next_outputs[i] = self.next_outputs[i]\n\n next_outputs = np.float32(next_outputs)\n\n discounted_prediction = self.discounted_prediction(self.rewards, done, self.next_states, self.next_outputs)\n\n values = self.critic.predict([states, outputs])\n values = np.reshape(values, len(values))\n\n advantages = discounted_prediction - values\n\n #print(\"{}\".format(self.thread_id), \"dis_r\",' '.join('{:1.2f}'.format(k) for k in discounted_prediction))\n #print(\"{}\".format(self.thread_id), \"val_r\",' '.join('{:1.2f}'.format(k) for k in values))\n\n policy = self.actor.predict([states, outputs])\n old_policy = np.array(self.policies)\n action_prob = np.sum(np.array(self.actions) * policy, axis=1)\n old_action_prob = np.sum(np.array(self.actions) * old_policy, axis=1)\n cross_entropy = action_prob/(old_action_prob + 1e-10)\n log_cross_entropy = np.log(action_prob + 1e-10)\n entropy = np.sum(policy * np.log(policy/(old_policy + 1e-10)), axis=1)\n\n #print(\"{}\".format(self.thread_id), \"x_ent \", ' '.join('{:1.3f}'.format(k) for k in cross_entropy))\n #print(\"{}\".format(self.thread_id), \"log_x_ent\", ' '.join('{:1.3f}'.format(k) for k in log_cross_entropy))\n #print(\"{}\".format(self.thread_id), \"ent \", ' '.join('{:1.3f}'.format(k) for k in entropy))\n\n\n \"\"\"\n if len(self.rewards) >2:\n reversed_discounted_prediction = self.discounted_prediction(self.rewards[:-1], done, self.states, self.outputs)\n\n reversed_values = self.critic.predict([next_states[1:], next_outputs[1:]])\n reversed_values = np.reshape(reversed_values, len(reversed_values))\n\n reversed_advantages = reversed_discounted_prediction - reversed_values\n\n print(\"{}\".format(self.thread_id), ' '.join('{:1.2f}'.format(k) for k in reversed_discounted_prediction))\n print(\"{}\".format(self.thread_id), ' '.join('{:1.2f}'.format(k) for k in reversed_values))\n\n self.optimizer[0]([next_states[1:], next_outputs[1:], np.array(self.actions[1:]), reversed_advantages])\n self.optimizer[1]([next_states[1:], next_outputs[1:], reversed_discounted_prediction])\n \"\"\"\n \"\"\"\n reversed_discounted_prediction = self.discounted_prediction(self.rewards, done, self.states, self.outputs, True)\n\n reversed_values = self.critic.predict([next_states, next_outputs])\n reversed_values = np.reshape(reversed_values, len(reversed_values))\n\n reversed_advantages = reversed_discounted_prediction - reversed_values\n\n print(\"{}\".format(self.thread_id), ' '.join('{:1.2f}'.format(k) for k in reversed_discounted_prediction))\n print(\"{}\".format(self.thread_id), ' '.join('{:1.2f}'.format(k) for k in reversed_values))\n self.optimizer[0]([next_states, next_outputs, np.array(self.actions), reversed_advantages])\n self.optimizer[1]([next_states, next_outputs, reversed_discounted_prediction])\n \"\"\"\n\n \"\"\"\n if len(states)>2:\n\n reversed_reward = []\n\n for reward in reversed(self.rewards[:-1]):\n reversed_reward.append(reward)\n\n reversed_discounted_prediction = self.discounted_prediction(reversed_reward, False,\n list(reversed(self.states[1:])),\n list(reversed(self.outputs[1:])))\n\n reversed_states = np.zeros((len(self.states) - 1,\n self.spaces.observation_space.shape[0],\n self.spaces.observation_space.shape[1],\n self.spaces.observation_space.shape[2]))\n\n for i, state in enumerate(list(reversed(self.states[1:]))):\n reversed_states[i] = state\n\n reversed_outputs = np.zeros((len(self.outputs)-1, 500))\n\n for i, output in enumerate(list(reversed(self.outputs[1:]))):\n reversed_outputs[i] = output\n\n reversed_outputs = np.float32(reversed_outputs)\n\n reversed_states = np.float32(reversed_states)\n\n reversed_values = self.critic.predict([reversed_states, reversed_outputs])\n reversed_values = np.reshape(reversed_values, len(reversed_values))\n\n reversed_advantages = reversed_discounted_prediction - reversed_values\n\n print(\"{}\".format(self.thread_id), ' '.join('{:1.2f}'.format(k) for k in reversed_discounted_prediction))\n print(\"{}\".format(self.thread_id), ' '.join('{:1.2f}'.format(k) for k in reversed_values))\n\n self.optimizer[0]([reversed_states, reversed_outputs, np.array(list(reversed(self.actions[:-1]))), reversed_advantages])\n self.optimizer[1]([reversed_states, reversed_outputs, reversed_discounted_prediction])\n \"\"\"\n\n\n #self.icm.train_on_batch([states, next_states, np.array(self.actions),dddd], np.zeros((length_state,)))\n\n\n\n return [states, outputs, np.array(self.actions), advantages, np.array(self.policies)], \\\n [states, outputs, discounted_prediction], \\\n [outputs, next_outputs, np.array(self.actions), np.array(discounted_prediction).reshape(-1, 1)]\n\n\n # 정책신경망과 가치신경망을 업데이트\n def train_n_model(self, done):\n\n states = np.zeros((len(self.n_states),\n self.spaces.observation_space.shape[0],\n self.spaces.observation_space.shape[1],\n self.spaces.observation_space.shape[2]))\n\n\n for i in range(len(self.n_states)):\n states[i] = self.n_states[i]\n\n states = np.float32(states)\n\n next_states = np.zeros((len(self.n_next_states),\n self.spaces.observation_space.shape[0],\n self.spaces.observation_space.shape[1],\n self.spaces.observation_space.shape[2]))\n\n for i in range(len(self.n_next_states)):\n next_states[i] = self.n_next_states[i]\n\n next_states = np.float32(next_states)\n\n outputs = np.zeros((len(self.n_outputs), 500))\n\n for i in range(len(self.n_outputs)):\n outputs[i] = self.n_outputs[i]\n\n outputs = np.float32(outputs)\n\n next_outputs = np.zeros((len(self.n_next_outputs), 500))\n\n for i in range(len(self.n_next_outputs)):\n next_outputs[i] = self.n_next_outputs[i]\n\n next_outputs = np.float32(next_outputs)\n\n discounted_prediction = self.n_discounted_prediction(self.n_rewards, done, self.n_next_states, self.n_next_outputs)\n\n values = self.critic.predict([states, outputs])\n values = np.reshape(values, len(values))\n\n advantages = discounted_prediction - values\n\n #print(\"{}\".format(self.thread_id), \"dis_n\",' '.join('{:1.2f}'.format(k) for k in discounted_prediction))\n #print(\"{}\".format(self.thread_id), \"val_n\",' '.join('{:1.2f}'.format(k) for k in values))\n\n policy = self.actor.predict([states, outputs])\n old_policy = np.array(self.n_policies)\n action_prob = np.sum(np.array(self.n_actions) * policy, axis=1)\n old_action_prob = np.sum(np.array(self.n_actions) * old_policy, axis=1)\n cross_entropy = action_prob/(old_action_prob + 1e-10)\n log_cross_entropy = np.log(action_prob + 1e-10)\n entropy = np.sum(policy * np.log((policy/(old_policy + 1e-10))), axis=1)\n\n #print(\"{}\".format(self.thread_id), \"n_x_ent \", ' '.join('{:1.3f}'.format(k) for k in cross_entropy))\n #print(\"{}\".format(self.thread_id), \"n_log_x_ent\", ' '.join('{:1.3f}'.format(k) for k in log_cross_entropy))\n #print(\"{}\".format(self.thread_id), \"n_ent \", ' '.join('{:1.3f}'.format(k) for k in entropy))\n\n \"\"\"\n if len(self.rewards) >2:\n reversed_discounted_prediction = self.discounted_prediction(self.rewards[:-1], done, self.states, self.outputs)\n\n reversed_values = self.critic.predict([next_states[1:], next_outputs[1:]])\n reversed_values = np.reshape(reversed_values, len(reversed_values))\n\n reversed_advantages = reversed_discounted_prediction - reversed_values\n\n print(\"{}\".format(self.thread_id), ' '.join('{:1.2f}'.format(k) for k in reversed_discounted_prediction))\n print(\"{}\".format(self.thread_id), ' '.join('{:1.2f}'.format(k) for k in reversed_values))\n\n self.optimizer[0]([next_states[1:], next_outputs[1:], np.array(self.actions[1:]), reversed_advantages])\n self.optimizer[1]([next_states[1:], next_outputs[1:], reversed_discounted_prediction])\n \"\"\"\n\n reversed_discounted_prediction = self.n_discounted_prediction(self.n_rewards, done, self.n_states, self.n_outputs, True)\n\n reversed_values = self.critic.predict([next_states, next_outputs])\n reversed_values = np.reshape(reversed_values, len(reversed_values))\n\n reversed_advantages = reversed_discounted_prediction - reversed_values\n\n #print(\"{}\".format(self.thread_id), ' '.join('{:1.2f}'.format(k) for k in reversed_discounted_prediction))\n #print(\"{}\".format(self.thread_id), ' '.join('{:1.2f}'.format(k) for k in reversed_values))\n\n \"\"\"\n if len(states)>2:\n\n reversed_reward = []\n\n for reward in reversed(self.rewards[:-1]):\n reversed_reward.append(reward)\n\n reversed_discounted_prediction = self.discounted_prediction(reversed_reward, False,\n list(reversed(self.states[1:])),\n list(reversed(self.outputs[1:])))\n\n reversed_states = np.zeros((len(self.states) - 1,\n self.spaces.observation_space.shape[0],\n self.spaces.observation_space.shape[1],\n self.spaces.observation_space.shape[2]))\n\n for i, state in enumerate(list(reversed(self.states[1:]))):\n reversed_states[i] = state\n\n reversed_outputs = np.zeros((len(self.outputs)-1, 500))\n\n for i, output in enumerate(list(reversed(self.outputs[1:]))):\n reversed_outputs[i] = output\n\n reversed_outputs = np.float32(reversed_outputs)\n\n reversed_states = np.float32(reversed_states)\n\n reversed_values = self.critic.predict([reversed_states, reversed_outputs])\n reversed_values = np.reshape(reversed_values, len(reversed_values))\n\n reversed_advantages = reversed_discounted_prediction - reversed_values\n\n print(\"{}\".format(self.thread_id), ' '.join('{:1.2f}'.format(k) for k in reversed_discounted_prediction))\n print(\"{}\".format(self.thread_id), ' '.join('{:1.2f}'.format(k) for k in reversed_values))\n\n self.optimizer[0]([reversed_states, reversed_outputs, np.array(list(reversed(self.actions[:-1]))), reversed_advantages])\n self.optimizer[1]([reversed_states, reversed_outputs, reversed_discounted_prediction])\n \"\"\"\n\n\n #self.icm.train_on_batch([states, next_states, np.array(self.actions),dddd], np.zeros((length_state,)))\n\n return [states, outputs, np.array(self.n_actions), advantages, np.array(self.n_policies)], \\\n [states, outputs, discounted_prediction], \\\n [outputs, next_outputs, np.array(self.n_actions), np.array(discounted_prediction).reshape(-1, 1)],\n \"\"\"\n [next_states, next_outputs, np.array(self.n_actions), reversed_advantages, np.array(self.n_next_policies)],\\\n [next_states, next_outputs, reversed_discounted_prediction]\n \"\"\"\n # 로컬신경망을 생성하는 함수\n def build_local_model(self):\n input = Input(shape=self.state_size, name=\"xs_input\")\n stage = 0;\n\n for i in range(5):\n stage_filters = [64, 64, 256]\n X = convolution_block_se_lk(input, f=3, filters=stage_filters, stage=stage, block='ca_{}_{}'.format(i, self.thread_id),\n s=1)\n X = identity_block_se_lk(X, 3, stage_filters, stage=stage, block='cb_{}_{}'.format(i, self.thread_id))\n X = identity_block_se_lk(X, 3, stage_filters, stage=stage, block='cc_{}_{}'.format(i, self.thread_id))\n stage = stage + 1\n\n for i in range(5, 7):\n stage_filters = [64 // 2, 64 // 2, 256 // 2]\n X = convolution_block_se_lk(input, f=3, filters=stage_filters, stage=stage, block='fca_{}'.format(i),\n s=1)\n X = identity_block_se_lk(X, 3, stage_filters, stage=stage, block='fcb_{}'.format(i))\n X = identity_block_se_lk(X, 3, stage_filters, stage=stage, block='fcc_{}'.format(i))\n stage = stage + 1\n\n conv = Flatten()(X)\n fc = Dense(3800, activation='relu')(conv)\n\n f_input, f_output =build_feature_map_full_connected((500, ))\n\n fc = Concatenate()([f_output, fc])\n\n policy = Dense(self.action_size, activation='softmax')(fc)\n value = Dense(1, activation='linear')(fc)\n\n local_actor = Model(inputs=[input, f_input], outputs=policy)\n\n local_actor._make_predict_function()\n\n local_actor.set_weights(self.actor.get_weights())\n\n local_actor.summary()\n\n return local_actor\n\n\n # 로컬신경망을 글로벌신경망으로 업데이트\n def update_local_model(self):\n self.local_actor.set_weights(self.actor.get_weights())\n\n # 정책신경망의 출력을 받아서 확률적으로 행동을 선택\n def get_action(self, history, output):\n\n\n\n policy = self.local_actor.predict([history, output])[0]\n m_policy = copy.deepcopy(policy)\n\n #self.epsilon *= self.epsilon_decay\n if np.random.random() < self.epsilon:\n action_index = np.random.choice(self.action_size, 1)[0]\n else:\n \"\"\"\n for action, action_number in enumerate(self.pre_actions):\n if 3 <= action_number:\n value = m_policy[action]\n distributed = value/self.action_size\n m_policy[action] = 0\n m_policy = np.add(m_policy, distributed)\n print(\"V\", self.thread_id, action)\n \n sorted_index = np.argsort(m_policy)\n sum = 0\n counter = 0\n for index in reversed(sorted_index):\n if counter >= (self.action_size//5*3):\n break\n sum += m_policy[index]\n counter += 1\n\n average = sum/(self.action_size//5*3)\n\n counter = 0\n for index in reversed(sorted_index):\n if counter >= (self.action_size//5*3):\n break\n m_policy[index] = average\n counter += 1\n \"\"\"\n action_index = np.random.choice(self.action_size, 1, p=policy)[0]\n self.pre_actions[action_index] += 1\n\n return action_index, policy, m_policy\n\n\n # 샘플을 저장\n def append_sample(self, history, action, reward, next_history, output, next_output, policy, next_policy, r_in):\n\n self.n_states.append(history)\n self.n_next_states.append(next_history)\n\n self.n_outputs.append(output)\n self.n_next_outputs.append(next_output)\n\n self.n_policies.append(policy)\n self.n_next_policies.append(next_policy)\n\n act = np.zeros(self.action_size)\n act[action] = 1\n \"\"\"\n posibilities = action % (self.spaces.action_space.shapes[0])\n position = action // (self.spaces.action_space.shapes[0])\n\n act[posibilities*self.spaces.action_space.shapes[0]+position] = 1\n \"\"\"\n self.n_actions.append(act)\n self.n_rewards.append(np.clip(reward+r_in, -1, 1))\n\n if reward >= 0:\n self.states.append(history)\n self.next_states.append(next_history)\n\n self.outputs.append(output)\n self.next_outputs.append(next_output)\n\n self.policies.append(policy)\n self.next_policies.append(next_policy)\n\n act = np.zeros(self.action_size)\n act[action] = 1\n \"\"\"\n posibilities = action % (self.spaces.action_space.shapes[0])\n position = action // (self.spaces.action_space.shapes[0])\n \n act[posibilities*self.spaces.action_space.shapes[0]+position] = 1\n \"\"\"\n self.actions.append(act)\n self.rewards.append(np.clip(reward+r_in, -1, 1))\n\nif __name__ == \"__main__\":\n global_agent = A3CAgent()\n global_agent.train()\n","sub_path":"astra_compare.py","file_name":"astra_compare.py","file_ext":"py","file_size_in_byte":63930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"522615760","text":"## A little program that searches google for the top image for a given keyword\n## and displays it in the default webbrowser\n\n## Might be useful later paired with speech recognition program...\n## my speech -> keywords -> this program -> funny image -> profit\n\nimport json\nimport webbrowser\nimport urllib\n\ndef search(term):\n query = urllib.urlencode({'q': term})\n url = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&%s' % query\n search_response = urllib.urlopen(url)\n search_results = search_response.read()\n results = json.loads(search_results)\n data = results['responseData']\n hits = data['results']\n top = hits[0]\n return top['url']\n\ngo = True\n\nwhile (go):\n var = raw_input(\"Enter a search term: \")\n img = search(var)\n webbrowser.open(img)\n\n yesorno = raw_input(\"Keep going? (y/n): \")\n if yesorno != 'y' :\n go = False\n\n","sub_path":"search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"348144162","text":"from pathlib import Path\n\nfrom aiohttp import web\nfrom aiohttp_apiset import SwaggerRouter\nfrom aiohttp_apiset.middlewares import jsonify\nfrom aiohttp_apiset.swagger.operations import OperationIdMapping\n\n\nBASE = Path(__file__).parent\n\n\ndef set_document(request):\n \"\"\" Simple handler for set document\n :param request: aiohttp.web.Request\n :return: dict\n \"\"\"\n\n # check validation\n assert 'id' in request\n assert isinstance(request['id'], int)\n assert request['id'] <= 0\n assert 'body' in request\n assert isinstance(request['body'], dict)\n assert request['body']['a'] > 0\n\n # dict response for jsonify middleware\n return dict(request)\n\n\n# operationId-handler association\nopmap = OperationIdMapping(\n setDocument=set_document\n)\n\n\ndef main():\n router = SwaggerRouter(\n encoding='utf-8',\n default_validate=True,\n swagger_ui='/',\n search_dirs=[BASE],\n )\n\n app = web.Application(\n router=router,\n middlewares=[jsonify],\n )\n\n # Include our specifications in a router,\n # is now available in the swagger-ui to the address /apidoc/\n router.include(\n spec='swagger.yaml',\n operationId_mapping=opmap,\n )\n\n web.run_app(app)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/foreign_spec/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"440217801","text":"import os\nimport re\nimport csv\nimport time\nimport math\nfrom argparse import ArgumentParser, RawTextHelpFormatter\n\nfrom apis import base_uris, app_key_management, le_users, le_skills, agent_groups, data_access\n\nfrom utilities import mark_log\nlog = mark_log.log\n\n__author__ = 'Mark Manguno'\n__creation_date__ = '09/26/16'\n\nparser = ArgumentParser(formatter_class=RawTextHelpFormatter)\nutilities = parser.add_mutually_exclusive_group()\n\n# Universal Parameters\nparser.add_argument('--site_id')\nparser.add_argument('--app_key')\nparser.add_argument('--app_secret')\nparser.add_argument('--token_key')\nparser.add_argument('--token_secret')\n\n# General Arguments\nparser.add_argument('--start_time', help='Search interval start time in epoch time.')\nparser.add_argument('--end_time', help='Search interval end time in epoch time.')\nparser.add_argument('--skill_id', help='Skill ID for functions that require a skill')\nparser.add_argument('--user_list', help='User list for functions that require a list of users. '\n 'Pass a file with each user ID on a new line.')\nparser.add_argument('--interval', help='For operations that are performed many times specify the interval in seconds. '\n '(Default: 5)', default='5')\n\n# Utilities\n# Users\nutilities.add_argument('--delete_lpa_users', action='store_true',\n help='Fetch users list, find any with the LPA naming convention, delete them.')\nutilities.add_argument('--change_messaging_concurrency', action='store_true',\n help='Change the messaging concurrency of a list of users. '\n 'Pass --user_list (filename)')\n\n# Agent Groups\nutilities.add_argument('--add_agent_groups', action='store_true',\n help='Create agent groups according to a list supplied in a .csv file as --agent_group_list')\nparser.add_argument('--agent_group_list', help='Agent Group list for --add_agent_groups. '\n 'Pass a CSV file where each line contains:\\n'\n '\\'group_name,parent_group_id(optional),description(optional)\\'\\n'\n 'When not specified parent_group_id defaults to -1 (Main Group).\\n'\n 'ex:\\n'\n 'new_group_1,25256677,description\\n'\n 'new_group_2,,description 2\\n'\n 'new_group_3')\n\n# Skills\nutilities.add_argument('--add_skill', action='store_true',\n help='Add users to skill. '\n 'Pass --skill_id (integer) and --user_list (filename)')\nutilities.add_argument('--add_and_remove_skill', action='store_true',\n help='First add users to skill, then remove users from skill. '\n 'Pass --skill_id (integer) and --user_list (filename)')\nutilities.add_argument('--remove_skill', action='store_true',\n help='Remove users from skill. '\n 'Pass --skill_id (integer) and --user_list (filename)')\nutilities.add_argument('--list_skills', action='store_true', help='Retrieve a list of skills from the account.')\nutilities.add_argument('--create_messaging_skills', action='store_true',\n help='Create a corresponding messaging skill for each chat skill on the account. '\n 'Use the default suffix \\'_messaging\\' or pass a new one with --suffix (string)')\nparser.add_argument('--suffix',\n help='Suffix for new skills created with --create_messaging_skills')\nutilities.add_argument('--create_n_skills', action='store_true',\n help='Create n skills on the account named \\'skill_000\\', \\'skill_001\\', etc...'\n 'Requires --count param')\nparser.add_argument('--count',\n help='Value of N')\nutilities.add_argument('--delete_skills', action='store_true',\n help='Delete skills that match a specific string')\n\n\n# Data Access\nutilities.add_argument('--data_access', action='store_true', help='Use the LE Data Access API')\n\n\nargs = parser.parse_args()\n\nargs.app_key = args.app_key or os.getenv('app_key')\nargs.app_secret = args.app_secret or os.getenv('app_secret')\nargs.token_key = args.token_key or os.getenv('token_key')\nargs.token_secret = args.token_secret or os.getenv('token_secret')\n\n\nif not args.site_id:\n args.site_id = input('Enter site id: ')\n\nargs.interval = int(float(args.interval))\n\nbases = base_uris.fetch(args)\n# appKeys = app_key_management.fetch(args, bases['appKeyManagement']['baseURI']).json()\n\nlog(args.app_key)\nlog(args.app_secret)\nlog(args.token_key)\nlog(args.token_secret)\n\n# List Skills\nif args.list_skills:\n skills = le_skills.fetch(args, bases['accountConfigReadOnly']['baseURI']).json()\n for skill in skills:\n log(skill['name'])\n\n\n# Create Messaging Skills\nif args.create_messaging_skills:\n if not args.suffix:\n args.suffix = input('Enter desired suffix (default: \\'_messaging\\'): ') or '_messaging'\n readWriteURI = bases['accountConfigReadWrite']['baseURI']\n skills = le_skills.fetch(args, bases['accountConfigReadOnly']['baseURI']).json()\n regex = re.compile(re.escape(args.suffix)+'$')\n\n for skill in skills:\n if skill['name']+args.suffix in (s['name'] for s in skills):\n log('skill {0} not copied because skill {1} exists'.format(skill['name'], skill['name']+args.suffix))\n\n elif regex.search(skill['name']):\n log('skill {0} not copied because it already ends with {1}'.format(skill['name'], args.suffix))\n\n else:\n response = le_skills.create_one(args, readWriteURI, skill['name']+args.suffix)\n time.sleep(args.interval)\n\n# Create N Skills\nif args.create_n_skills:\n n = int(args.count)\n mag = int(math.log10(n))\n format_string = \"skill_%0\" + str(mag) + \"d\"\n readWriteURI = bases['accountConfigReadWrite']['baseURI']\n for i in range(n):\n skill_name = format_string % i\n response = le_skills.create_one(args, readWriteURI, skill_name)\n time.sleep(args.interval)\n\n\n# Delete Skills\nif args.delete_skills:\n readWriteURI = bases['accountConfigReadWrite']['baseURI']\n skills = le_skills.fetch(args, bases['accountConfigReadOnly']['baseURI']).json()\n string = input('Delete skills whose names match the string: ')\n\n for skill in skills:\n if re.compile(re.escape(string)).search(skill['name']):\n # log('deleting skill {0}'.format(skill['name']))\n le_skills.delete_one(args, readWriteURI, skill)\n else:\n log('not deleting skill {0}'.format(skill['name']))\n\n# Delete LPA Users\nif args.delete_lpa_users:\n users = le_users.fetch(args, bases['accountConfigReadOnly']['baseURI']).json()\n count = 0\n log('deleting LPA users')\n for user in users:\n if 'LPA' in user['loginName']:\n count += 1\n le_users.delete_one(args, bases['accountConfigReadWrite']['baseURI'], user)\n if count > 0:\n log('{0} users deleted'.format(count))\n else:\n log('no matching users found')\n\n# Add (And Remove) Skill\nif args.add_skill or args.add_and_remove_skill:\n count = 0\n if not args.skill_id:\n args.skill_id = input('Enter skill id: ')\n\n if not args.user_list:\n args.user_list = input('Enter user list filename: ')\n\n with open(args.user_list, 'r') as f:\n users_to_edit = [line.rstrip('\\n') for line in f]\n\n log('adding users to skill {0}'.format(args.skill_id))\n\n for user in users_to_edit:\n count += 1\n add_response = le_users.add_skill(args, bases['accountConfigReadWrite']['baseURI'], user, args.skill_id)\n if add_response and args.add_and_remove_skill:\n le_users.remove_skill(args, bases['accountConfigReadWrite']['baseURI'], user, args.skill_id)\n log('{0} total users updated'.format(count))\n time.sleep(args.interval)\n\n# Remove Skill\nif args.remove_skill:\n count = 0\n if not args.skill_id:\n args.skill_id = input('Enter skill id: ')\n\n if not args.user_list:\n args.user_list = input('Enter user list filename: ')\n\n with open(args.user_list, 'r') as f:\n users_to_edit = [line.rstrip('\\n') for line in f]\n\n log('adding users to skill {0}'.format(args.skill_id))\n\n for user in users_to_edit:\n count += 1\n response = le_users.remove_skill(args, bases['accountConfigReadWrite']['baseURI'], user, args.skill_id)\n log('{0} total users updated'.format(count))\n time.sleep(args.interval)\n\n# Change Messaging Concurrency\nif args.change_messaging_concurrency:\n count = 0\n if not args.user_list:\n args.user_list = input('Enter user list filename: ')\n\n target_concurrency = input('Enter desired messaging concurrency: ')\n\n with open(args.user_list, 'r') as f:\n users_to_edit = [line.rstrip('\\n') for line in f]\n\n log('setting concurrency to {0}'.format(target_concurrency))\n\n for user in users_to_edit:\n count += 1\n le_users.change_max_async(args, bases['accountConfigReadWrite']['baseURI'], user, target_concurrency)\n log('{0} total users updated'.format(count))\n\n# Data Access\nif args.data_access:\n # temporary solution for lack of data access uri in csds\n _url = bases['leDataReporting']['baseURI'].split('.', maxsplit=2)\n url = '.'.join((_url[0], 'da', _url[2]))\n\n files = data_access.agent_activity(args, url)\n print(files.json())\n\n# Add Agent Groups\nif args.add_agent_groups:\n group_list = csv.reader(open(args.agent_group_list))\n readWriteURI = bases['accountConfigReadWrite']['baseURI']\n for row in group_list:\n response = agent_groups.create(args,\n readWriteURI,\n row[0],\n row[1] if (1 < len(row) and row[1] != '') else '-1',\n row[2] if 2 < len(row) else '')\n time.sleep(args.interval)\n","sub_path":"thingy.py","file_name":"thingy.py","file_ext":"py","file_size_in_byte":10205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"435783933","text":"# -*- coding: utf-8 -*-\n\nimport string\n\nfrom io import BytesIO\nfrom PIL import Image, ImageDraw, ImageFont\n\nfrom tornado.gen import coroutine\n\nfrom util.decorator import catch_error\n\nfrom ._base import BaseModel\n\n\nclass CaptchaModel(BaseModel):\n\n _font_type = r'static/fonts/impact.ttf'\n\n _string_base = string.digits + string.ascii_letters\n\n def __init__(self):\n\n super().__init__()\n\n with open(self._font_type, r'rb') as file:\n self._font_data = file.read()\n\n def _make_image(self, width, height, line_num, line_width, font_color, back_color):\n\n txt_code = img_data = None\n\n with BytesIO() as stream:\n\n chars = self.randstr(self._string_base, 4)\n\n img_code = r''.join(chars)\n txt_code = img_code.lower()\n\n image = Image.new(r'RGB', (width, height), back_color)\n\n draw = ImageDraw.Draw(image)\n\n for index in range(1, line_num):\n pos_begin = (self.randint(0, width), self.randint(0, height))\n pos_end = (self.randint(0, width), self.randint(0, height))\n draw.line((pos_begin, pos_end), font_color, self.randint(*line_width))\n\n font_size = round(min(width, height) * 0.618)\n font = ImageFont.truetype(BytesIO(self._font_data), font_size)\n\n font_width, font_height = font.getsize(img_code)\n offset_x = self.randint(0, abs(width - font_width))\n offset_y = self.randint(0, abs(height - font_height))\n\n draw.text((offset_x, offset_y), img_code, font_color, font)\n\n image.save(stream, r'PNG')\n\n img_data = stream.getvalue()\n\n return txt_code, img_data\n\n @coroutine\n def generate(self, key, width, height, line_num=10, line_width=(1, 3), font_color=(0, 0, 0), back_color=(255, 255, 255)):\n\n result = None\n\n with catch_error():\n\n code, image = self._make_image(width, height, line_num, line_width, font_color, back_color)\n\n if(code and image):\n\n cache = self.get_cache_client()\n\n ckey = cache.key(r'captcha', key)\n yield cache.set(ckey, code)\n\n result = image\n\n return result\n\n @coroutine\n def validate(self, key, code):\n\n result = False\n\n with catch_error():\n\n cache = self.get_cache_client()\n\n ckey = cache.key(r'captcha', key)\n cval = yield cache.get(ckey)\n yield cache.delete(ckey)\n\n result = (code.lower() == cval)\n\n return result\n","sub_path":"model/m_captcha.py","file_name":"m_captcha.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"162976303","text":"'''\nIntroduction\nFinal project: test the plant environment and water the plant when it's dry.\nThe water level in a tank will be tested\nUsers will be noticed to add water to tank with the buzzer during day time.\nSince it's not easy to get a water pump, I used the Red LED to mimic it.\nFor this part, I will do a pilot test of the sensors.\n'''\n\nimport music\nfrom microbit import *\n\n# Set pins for sensors\nwater_sensor = pin0\nambient_light_sensor = pin1\nsoil_humidity_sensor = pin2\nbuzzer = pin12\n# Red LED Module was used to mimic the water pump\nrelay = pin13\n\n# Mian loop\ndef main():\n while True:\n display.clear()\n # Module output\n debug_output_module()\n # Get values from sensors\n w_level = get_sensor_analog(water_sensor, 'W')\n l_level = get_sensor_analog(ambient_light_sensor, 'L')\n h_level = get_sensor_analog(soil_humidity_sensor, 'H')\n msg = w_level + ',' + l_level + ',' + h_level\n display.scroll(msg)\n\n\n# Module output\ndef debug_output_module():\n # Mimic the water pump\n relay.write_digital(True)\n sleep(1000*5)\n relay.write_digital(False)\n # Buzzer on\n music.play('f4:2', pin=buzzer, wait=True, loop=False)\n\n\n# Get values from sensors\ndef get_sensor_analog(sensor, title):\n value = sensor.read_analog()\n content = title + ':' + str(value)\n return content\n\n# Call the main function.\nmain()\n","sub_path":"Water plant part 1.py","file_name":"Water plant part 1.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"107201760","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Importing couple of packages here\nimport numpy as np \nimport sys, os, glob\nimport matplotlib.pyplot as plt\nimport h5py\n\n#Definig all the functions required to display results\n\n\ndef createCircularMask(h, w, center=None, radius=None):\n \"\"\"Creates a circular mask on the picture with b and w as sizes of the circular shape. \n Radius and center to be defined.\"\"\"\n if center is None: # use the middle of the image\n center = [int(w/2), int(h/2)]\n if radius is None: # use the smallest distance between the center and image walls\n radius = min(center[0], center[1], w-center[0], h-center[1])\n\n Y, X = np.ogrid[:h, :w]\n dist_from_center = np.sqrt((X - center[0])**2 + (Y-center[1])**2)\n\n mask = dist_from_center <= radius\n return mask\n\ndef progression(string,top_value,iterator):\n \"\"\"Gives an idea of the percentage of progression of the loop. Need to put the string you \n want before the %, a top value and the name of the loop iterator.\"\"\"\n sys.stdout.write(\"\\r\\x1b[K\"+ string +str( '%.2f'%float((float(iterator)+1)*100/top_value))+ \"%\")\n sys.stdout.flush()\n","sub_path":"PyXRDCT/nmutils/utils/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"581691546","text":"# ***************************************************************************\n# Ceci est le squelette du fichier dans lequel *toutes* vos fonctions doivent \n# etre ecrites. Il a ete quelque peu adapte pour vous permettre d'executer des \n# tests automatiquement et sans effort: il suffira de decommenter la ligne if \n# if __name__ == '__main__': testeur.fais_tests('...') \n# presente apres chaque definition de fonction.\n#\n# ***ATTENTION*** Pour que cela fonctionne bien dans pyzo, il est \n# ***absolument primordial*** de lancer l'execution dans le menu via \n# \"Executer en tant que script\" ou \"Run file as script\"\n# c'est-a-dire avec le raccourci Ctrl-Shift-E (et NON simplement Ctrl-E) sinon \n# les mises a jour de votre fichier ne seront pas prises en compte.\n# (NB: Si vous etes sous Mac, c'est Pomme-Shift-E qu'il faut utiliser)\n# ***************************************************************************\n\n\n# On importe la batterie de tests uniquement a l'execution du fichier et non \n# lors de l'import en tant que module:\n# **NB**: Ne PAS commenter cette ligne car c'est elle qui charge le fichier de test...\nif __name__ == '__main__': import test_TP11 as testeur\n\n# ***************************************************************************\n# Partie I: Préparatifs\n# ***************************************************************************\n\ndef force2(m1,p1,m2,p2):\n \"\"\" Calcule la force gravitationnelle que la particule 2 exerce sur la\n particule 1. \"\"\"\n f = [0]*3\n r2 = 0\n for i in range(3):\n r2 = r2 + (p1[i]-p2[i])**2\n r = r2**0.5\n for i in range(3):\n f[i] = -m1*m2 / r**3 * (p1[i]-p2[i])\n return f\n\n# Ligne suivante a decommenter pour tester \n#if __name__ == '__main__': testeur.fais_tests('01_force2')\n\ndef forceN(j,m,pos):\n \"\"\" Calcule la force gravitationnelle totale que les N-1 autres particules\n exercent sur la particule j. \"\"\"\n mj = m[j]\n pj = pos[j]\n F = [0]*3\n for i in range(len(pos)):\n if i != j :\n f = force2(mj,pj,m[i],pos[i])\n for k in range(3):\n F[k] += f[k]\n return F\n\n# Ligne suivante a decommenter pour tester \n#if __name__ == '__main__': testeur.fais_tests('02_forceN')\n\ndef etats_suivants_euler(m,pos,vit,dt):\n \"\"\" Doit renvoyer les listes des positions et vitesses suivantes de chaque \n particule (dans le meme ordre) apres un pas dt d'integration. Attention a \n la complexite de votre algorithme si vous voulez obtenir tous les \n points.\"\"\"\n N = len(pos)\n new_pos = [[0,0,0] for i in range(N)] # On fournit gracieusement l'initialisation\n new_vit = [[0,0,0] for i in range(N)] # On fournit gracieusement l'initialisation\n for i in range(N): #boucle sur le nombre de particules\n force=forceN(i,m,pos)\n for j in range(3): #boucle sur les coordonnées\n new_pos[i][j]=pos[i][j]+dt*vit[i][j]\n new_vit[i][j]=vit[i][j]+dt*force[j]/m[i]\n\n return(new_pos,new_vit)\n\nif __name__ == '__main__': testeur.fais_tests('03_etats_suivants_euler_court') \n#if __name__ == '__main__': testeur.fais_tests('04_etats_suivants_euler_long')\n\ndef positions_suivantes_verlet(m,pos,vit,dt):\n \"\"\" Doit renvoyer la liste des positions suivantes de chaque particule \n (dans le meme ordre) apres un pas dt d'integration. \"\"\"\n N = len(pos)\n new_pos = [[0,0,0] for i in range(N)] # On fournit gracieusement l'initialisation\n return new_pos\n\n# Ligne suivante a decommenter pour tester \n#if __name__ == '__main__': testeur.fais_tests('05_positions_suivantes_verlet_court') \n#if __name__ == '__main__': testeur.fais_tests('06_positions_suivantes_verlet_long')\n\ndef etats_suivants_verlet(m,pos,vit,dt):\n \"\"\" Doit renvoyer les listes des positions et vitesses suivantes de chaque \n particule (dans le meme ordre) apres un pas dt d'integration. Attention a \n la complexite de votre algorithme si vous voulez obtenir tous les \n points.\"\"\"\n return [[]],[[]]\n\n# Ligne suivante a decommenter pour tester \n#if __name__ == '__main__': testeur.fais_tests('07_etats_suivants_verlet_court') \n#if __name__ == '__main__': testeur.fais_tests('08_etats_suivants_verlet_long')\n\n\n# Ne vous restera plus qu'a generer le graphe demande et le stocker sous le \n# nom 'integration_verlet_VotreNom.png' et 'integration_verlet_VotreNom.png' \n# (ou bien entendu la chaîne 'VotreNom' est à remplacer par votre propre nom). \n# Attention cependant a ne *pas* laisser la procedure de generation active \n# pour eviter que l'ordinateur du correcteur ne tourne indefiniment...\n\nimport matplotlib.pyplot as plt\n\ngenerer_graphe = False # A mettre a True pour lancer la generation\n\nif __name__ == '__main__':\n if generer_graphe:\n print('''Une fois la figure generee, la variable 'generer_graphe' a False tu mettras...''')\n m = [3.0,4.0,5.0] # Les masses des trois points\n v0= [[0,0,0] for i in range(3)] # Les particules sont au repos\n p0= [[1.0,3,0], [-2,-1,0], [1,-1,0]] # Les trois sommets du triangle\n dt= 1e-4 # Le pas de temps demande\n # Mettez ici votre code pour generer les graphes demandes.\n\n\n\n# Calcul de la note finale (a ne decommenter que si vous ne voulez pas etre \n# stresse par la note ou que vos algorithmes en chantier font que l'ensemble \n# tourne trop lentement).\nif __name__ == '__main__': testeur.detaille_note()\n","sub_path":"TP/TP11/TP11_euler_verlet.py","file_name":"TP11_euler_verlet.py","file_ext":"py","file_size_in_byte":5368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"550697102","text":"import datetime\n\nfrom parsers.parser import Parser\nfrom constants import FLRU_URL\nfrom queries.project import Project\n\n\nclass FlRuParser(Parser):\n def __init__(self, search_query):\n super().__init__(search_query)\n\n def parse(self):\n soup = self.get_page_content(FLRU_URL.format(self.search_query))\n\n items = soup.findAll('div', {'class': 'search-lenta-item c'})\n for item in items:\n title = item.find('h3').find('a').get_text()\n link = 'https://www.fl.ru' + item.find('h3').find('a')['href']\n offers_count = item.find('span', {'class': 'search-answer'}).find('a').get_text().split(' ')[0]\n date = self._transform_date(item.find('ul', {'class': 'search-meta'}).findAll('li')[-1].get_text())\n\n self.projects.append(Project(\n title=title, link=link, offers_count=offers_count, date=date))\n return self.projects\n\n @staticmethod\n def _transform_date(date: str) -> datetime.date:\n number, definition = date.split(' ')[:2]\n if definition[0].isdigit():\n date = datetime.datetime.strptime(number, '%d.%m.%Y').date()\n else:\n date = datetime.datetime.today().date()\n return date\n\n\nif __name__ == '__main__':\n print(FlRuParser('js').parse())","sub_path":"parsers/freelance_parsers/flru_parser.py","file_name":"flru_parser.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"158235437","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Dec 24 14:13:29 2019\r\n\r\n@author: 潘浩宇\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\nsamples = ['The cat sat on the mat.', 'The dog ate my homework.']\r\n\r\n\r\ntoken_index = {}\r\nfor sample in samples: # sentens in list'samples'\r\n for word in sample.split(): # word in list'sentens'\r\n if word not in token_index: # if not appeared before, add to index\r\n token_index[word] = len(token_index) + 1 \r\n # print(token_index)\r\n \r\nmax_len = 10 #sample pre 10 words\r\n\r\nresult = np.zeros(shape=(len(samples),\r\n max_len,\r\n max(token_index.values())+1)) # Build a ndarray filled by 0\r\n\r\nfor i,samples in enumerate(samples):\r\n for j,word in list(enumerate(sample.split()))[:max_len]:\r\n index = token_index.get(word)\r\n result[i, j, index] = 1\r\n ","sub_path":"Chapter3.DLinSeq/np2onehot.py","file_name":"np2onehot.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"256042982","text":"# Copyright 2016 Internap.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport unittest\n\nfrom flexmock import flexmock\n\ntry:\n from flexmock._api import flexmock_teardown\nexcept ImportError:\n from flexmock import flexmock_teardown\n\nfrom . import ContextMatcher\nfrom ubersmith_remote_module_server import remote\nfrom ubersmith_remote_module_server.objects import RequestContext\nfrom ubersmith_remote_module_server.router import Router\nfrom ubersmith_remote_module_server.remote import ubersmith\n\n\nclass FakeModule(object):\n def call_uber_core(self):\n ubersmith.test()\n\n\nclass RouterUbersmithCoreTest(unittest.TestCase):\n def test_a_module_can_call_ubersmith_core_without_context(self):\n fake_module = FakeModule()\n remote_executor_mock = flexmock()\n\n flexmock(remote).should_receive('RemoteExecutor').\\\n with_args(context=RequestContext).and_return(remote_executor_mock)\n\n remote_executor_mock.should_receive('invoke_global').with_args('test', args={}).once()\n\n self.basic_router = Router(env_as_kwarg=False)\n self.basic_router.invoke_method(module=fake_module, method='call_uber_core')\n\n def test_module_context_is_injected_when_service_module(self):\n fake_module = FakeModule()\n remote_executor_mock = flexmock()\n\n example_callback = {'params': {'module_id': '44', 'service_id': '1260'},\n 'url': 'http://user:pass@ubersmith.example/'\n 'api/2.0/?method=service.module_call'}\n\n flexmock(remote).should_receive('RemoteExecutor'). \\\n with_args(context=ContextMatcher(callback_url=example_callback['url'],\n module_id='44',\n service_id='1260'))\\\n .and_return(remote_executor_mock)\n\n remote_executor_mock.should_receive('invoke_global')\n\n self.basic_router = Router(env_as_kwarg=False)\n self.basic_router.invoke_method(module=fake_module,\n method='call_uber_core',\n callback=example_callback)\n\n def test_module_context_is_injected_when_device_module(self):\n fake_module = FakeModule()\n\n example_callback = {'params': {'module_id': '173', 'device_id': '200025'},\n 'url': 'http://user:pass@ubersmith.example/'\n 'api/2.0/?method=device.module_call'}\n\n remote_executor_mock = flexmock()\n flexmock(remote).should_receive('RemoteExecutor'). \\\n with_args(context=ContextMatcher(callback_url=example_callback['url'],\n module_id='173',\n device_id='200025'))\\\n .and_return(remote_executor_mock)\n\n remote_executor_mock.should_receive('invoke_global')\n\n self.basic_router = Router(env_as_kwarg=False)\n self.basic_router.invoke_method(module=fake_module,\n method='call_uber_core',\n callback=example_callback)\n\n def tearDown(self):\n flexmock_teardown()\n super(RouterUbersmithCoreTest, self).tearDown()\n","sub_path":"tests/Integration/test_router_ubersmith_core.py","file_name":"test_router_ubersmith_core.py","file_ext":"py","file_size_in_byte":3774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"402682572","text":"\n\n#calss header\nclass _TRUMPET():\n\tdef __init__(self,): \n\t\tself.name = \"TRUMPET\"\n\t\tself.definitions = [u'a brass musical instrument consisting of a metal tube with one narrow end, into which the player blows, and one wide end. Three buttons are pressed in order to change notes.']\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/_trumpet.py","file_name":"_trumpet.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"519086537","text":"#This program calculates the average of twenty integer numbers in a random list\n\nimport random\n\ndef Mean(stp):\n average = 0\n summing = 0\n for i in range(len(stp)):\n summing += stp[i]\n average = summing/len(stp)\n return \"The average is\",average\n\nstp = []\nfor j in range(20):\n stp.append(random.randint(0,120))\n\nprint(\"The random list is\",stp)\nprint(Mean(stp))\n","sub_path":"average-calculation.py","file_name":"average-calculation.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"425254236","text":"import random\nimport statistics as st\nimport numpy as np\nimport math\n\nfrom lmfit import Parameters\n#from geneticalgorithm import geneticalgorithm as ga\nfrom scipy.optimize import minimize as scipy_minimize\nfrom scipy.optimize import basinhopping\nfrom scipy.interpolate import interp1d\n#from sklearn.neighbors import KernelDensity\n\nfrom utils import ObsEnum, StateEnum, ObsFitEnum, StateFitEnum, Model, residuals_error, load_model_data, residual_sum_of_squares, log_residual_sum_of_squares, COLORS_DICT\n\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\nimport matplotlib.cm as cm\nfrom scipy.stats import binom\n\nimport statistics as st\nimport numpy as np\nimport math\n\n# For repeatiblity (but less random numbers)\n\nimport random\n\nrandom.seed(1000)\nnp.random.seed(1000)\n\nSKIP_OBS = 10\n\n\ndef population_leave(param, population):\n # param : the proportion of population that should\n # leave on average\n\n if population < 0:\n # Fix for some edge cases\n return 0\n\n # Part of the population that leaves on average\n average = param * population\n\n # Binomial centered on the population part\n\n # The rounding is important because binomial\n # is for integer number. By using a round we favor\n # sometimes the high limit sometimes the loaw\n # limit => on average we center. I think np\n # will use \"int\" instead which always favour\n # the low limit => the distribution is skewed.\n r = np.random.binomial(round(2 * average), 0.5)\n\n return r\n\n\nclass SarahStat(Model):\n def __init__(self, observations, N):\n\n self._N = N\n nb_observations = observations.shape[0]\n self._nb_observations = observations.shape[0]\n\n self._observations = np.array(observations)\n self._fittingObservations = observations[np.ix_(range(nb_observations),\n list(map(int, ObsFitEnum)))]\n self._nExperiments = 200\n\n self._preprocess = True\n self._evaluation = 0\n self._iterations = 0\n\n E0 = 30\n A0 = 20\n SP0 = 10\n H0 = observations[0][ObsEnum.NUM_HOSPITALIZED.value]\n C0 = observations[0][ObsEnum.NUM_CRITICAL.value]\n R0 = 0\n F0 = observations[0][ObsEnum.NUM_FATALITIES.value]\n S0 = N - E0 - A0 - SP0 - H0 - C0 - R0 - F0\n infected_per_day = 0\n R_out_HC = 0\n cumulI = A0 + SP0\n\n self._initial_conditions = [S0, E0, A0, SP0, H0, C0, F0, R0, infected_per_day, R_out_HC, cumulI]\n\n print(\"initial conditions: \", self._initial_conditions)\n self._fit_params = None\n\n def get_initial_parameters(self):\n \"\"\"\n # Return:\n # the initial parameters of the model with their bounds to delimit\n # the ranges of possible values\n \"\"\"\n\n min_incubation_time = 1\n max_incubation_time = 5\n min_symptomatic_time = 4\n max_symptomatic_time = 10\n\n error_margin = 0.2\n print(ms._observations[:, ObsEnum.NUM_POSITIVE.value])\n cumulative_positives = np.cumsum(ms._observations[:, ObsEnum.NUM_POSITIVE.value])\n cumulative_hospitalizations = ms._observations[:, ObsEnum.CUMULATIVE_HOSPITALIZATIONS.value]\n\n # ----------------------------------\n # Tau (SP -> H)\n cumulative_positives = np.cumsum(ms._observations[:, ObsEnum.NUM_POSITIVE.value])\n cumulative_hospitalizations = ms._observations[:, ObsEnum.CUMULATIVE_HOSPITALIZATIONS.value]\n tau_0 = 0.01\n error_margin = 0.2\n tau_min = 0.001\n tau_max = 0.1\n tau_bounds = [tau_min, tau_0, min(1, tau_max)]\n\n # ------------------------------------------------------------\n # gamma4 : the rate at which people leave the E state to go to the R state\n # \"best-case\": if people recover all directly after min_incubation_time\n gamma4_max = 1 / min_incubation_time\n # \"worst-case\": if even after max_incubation_time, people do not recover because they are\n # asymptomatic for a long time, corresponding exactly to the time a symptomatic who is never hospitalised\n # would take to recover (max_incubation_time + max_symptomatic_time).\n gamma4_min = 1 / (max_incubation_time + max_symptomatic_time)\n # \"avg-case\":\n gamma4_0 = 0.12\n gamma4_bounds = [gamma4_min, gamma4_0, gamma4_max]\n\n # ----------------------------------\n # Gamma1 (SP -> R)\n # \"best-case\": if people recover all in min_symptomatic_time\n gamma1_max = 1 / min_symptomatic_time\n # \"worst-case\": if people do not recover and go to the H state\n gamma1_min = 1 / max_symptomatic_time\n gamma1_0 = 0.23 # 2 / (max_symptomatic_time + min_symptomatic_time)\n gamma1_bounds = [gamma1_min, gamma1_0, gamma1_max]\n\n # ----------------------------------\n # Gamma2 (H -> R) & Gamma3 (C -> R)\n gamma2_min = 1 / 15\n gamma2_0 = 1 / 13 # 0.2 # arbitrary choice\n gamma2_max = 0.5\n gamma2_bounds = [gamma2_min, gamma2_0, gamma2_max]\n\n gamma3_min = 1 / 20\n gamma3_0 = 1 / 19\n gamma3_max = 0.5\n gamma3_bounds = [gamma3_min, gamma3_0, gamma3_max]\n\n # gamma2_min = 1/10 # on peut rester en moyenne une bonne semaine donc disons 10 jours\n # gamma2_max = 0.4 # quand on va a l'hopital on reste pas 1 jour, au moins 2-3\n # gamma2_0 = 0.3\n # gamma2_bounds = [gamma2_min, gamma2_0, gamma2_max] # quand on va a l'hopital\n\n # gamma3_min = 1/20 # on peut rester 15 jours-3semaines\n # gamma3_max = 0.3 # encore une fois on va pas en critique pour 1-2 jours mais 3-4 minimum\n # gamma3_0 = 1/10\n # gamma3_bounds = [gamma3_min, gamma3_0, gamma3_max]\n\n # ------------------------------------------------------------\n # The reproduction number R0 is the number of people\n # each infected person will infect during the time he is infectious\n # R0 = beta * infectious_time\n # We can make the assumption that once an individual is infectious during the time\n # corresponding to max_symptomatic_time even if he he is asymptomatic.\n # Once being in hospital, he will not infect anyone else anymore.\n # Under this assumption, infectious_time is\n # included in [min_symptomatic_time, max_symptomatic_time]\n # R0 = 0.1 # on average, for 10 infected person, only one susceptible will become infected\n R0_min = 1 # or else the virus is not growing exponentially\n R0_max = 2.8 * 1.5 # the most virulent influenza pandemic\n # and we were told that covid-20 looked similar to influenza\n # We multiply by 2 (arbitrary choice) because covid-20 might\n # become more virulent than the most virulent influenza pandemic\n # (which is the case for covid-19 with a R0 that got to 3-4 at peak period)\n R0_avg = (R0_min + R0_max) / 2\n infectious_time = (min_symptomatic_time + max_symptomatic_time) / 2\n beta_0 = R0_avg / infectious_time # 0.39\n beta_min = R0_min / max_symptomatic_time\n beta_max = R0_max / min_symptomatic_time\n\n beta_0 = 0.25\n beta_min = 0.2\n beta_max = 0.55\n beta_bounds = [0.30, 0.34, 0.55]\n\n # ------------------------------------------------------------\n delta_min = 1 / 100 # 1/10\n delta_max = 57 / 1297\n delta_0 = 0.025\n delta_bounds = [delta_min, delta_0, delta_max]\n\n # ------------------------------------------------------------\n # E-> A\n # For the period of incubation\n rho_max = 1\n rho_0 = 0.89 # 2 / (min_incubation_time + max_incubation_time)\n rho_min = 1 / max_incubation_time\n rho_bounds = [rho_min, rho_0, rho_max]\n\n # ------------------------------------------------------------\n # C-> F\n # For the death...\n theta_min = 0.01\n theta_max = 0.2\n theta_0 = 0.04\n theta_bounds = [theta_min, theta_0, theta_max]\n\n # ------------------------------------------------------------\n sigma_max = 0.7\n sigma_min = 0.5 # = 1 / 100\n sigma_0 = 0.6 # (sigma_max + sigma_min) / 2\n sigma_bounds = [sigma_min, sigma_0, sigma_max]\n\n mu_max = 0.90\n mu_min = 0.5\n mu_0 = 0.67\n mu_bounds = [mu_min, mu_0, mu_max]\n # nombre teste, teste entre 30 et 70% des gens sembent pas fou\n\n eta_max = 0.85\n eta_min = 0.7\n eta_0 = 0.8\n eta_bounds = [eta_min, eta_0, eta_max]\n if False:\n mini = 99999999\n for pre_test in range(1000):\n print(\"3 - Pre test of the parameters: {} of 1000\".format(pre_test + 1))\n\n gamma1 = random.uniform(gamma1_min, gamma1_max)\n gamma2 = random.uniform(gamma2_min, gamma2_max)\n gamma3 = random.uniform(gamma3_min, gamma3_max)\n gamma4 = random.uniform(gamma4_min, gamma4_max)\n beta = random.uniform(beta_min, beta_max)\n tau = random.uniform(tau_min, tau_max)\n delta = random.uniform(delta_min, delta_max)\n sigma = random.uniform(sigma_min, sigma_max)\n rho = random.uniform(rho_min, rho_max)\n theta = random.uniform(theta_min, theta_max)\n mu = random.uniform(mu_min, mu_max)\n eta = random.uniform(eta_min, eta_max)\n\n param_values = [gamma1, gamma2, gamma3, gamma4, beta, tau, delta, sigma, rho, theta, mu, eta]\n # params = self._params_array_to_dict(param_values)\n # print(params)\n\n neg_likelihood = self._plumb_scipy_stocha(param_values)\n\n if neg_likelihood < mini:\n mini = neg_likelihood\n print(\"Min preprocess: {}\".format(mini))\n best_preprocess = param_values\n print(\"Corresponding params:\")\n print(best_preprocess)\n\n best_preprocess = self._params_array_to_dict(best_preprocess)\n print(best_preprocess)\n\n best_preprocess = self._params_array_to_dict([0.10698028629231761, 0.36806168249356885, 0.19689582431827574, 0.5158771155529966, 0.25702686734733055, 0.019951926351256127, 0.015355404916721221, 0.5941738834504704, 0.8299887995317639, 0.18273883639218028, 0.8222813790202658, 0.7463314605020426])\n gamma1_bounds = [gamma1_min, best_preprocess['gamma1'], gamma1_max]\n gamma2_bounds = [gamma2_min, best_preprocess['gamma2'], gamma2_max]\n gamma3_bounds = [gamma3_min, best_preprocess['gamma3'], gamma3_max]\n gamma4_bounds = [gamma4_min, best_preprocess['gamma4'], gamma4_max]\n beta_bounds = [beta_min, best_preprocess['beta'], beta_max]\n tau_bounds = [tau_min, best_preprocess['tau'], tau_max]\n delta_bounds = [delta_min, best_preprocess['delta'], delta_max]\n sigma_bounds = [sigma_min, best_preprocess['sigma'], sigma_max]\n rho_bounds = [rho_min, best_preprocess['rho'], rho_max]\n theta_bounds = [theta_min, best_preprocess['theta'], theta_max]\n mu_bounds = [mu_min, best_preprocess['mu'], mu_max]\n eta_bounds = [eta_min, best_preprocess['eta'], eta_max]\n\n bounds = [gamma1_bounds, gamma2_bounds, gamma3_bounds, gamma4_bounds, beta_bounds, tau_bounds, delta_bounds,\n sigma_bounds, rho_bounds, theta_bounds, mu_bounds, eta_bounds]\n param_names = ['gamma1', 'gamma2', 'gamma3', 'gamma4', 'beta', 'tau', 'delta', 'sigma', 'rho', 'theta', 'mu',\n 'eta']\n params = Parameters()\n\n for param_str, param_bounds in zip(param_names, bounds):\n params.add(param_str, value = param_bounds[1], min = param_bounds[0], max = param_bounds[2])\n\n return params\n\n def compute_log_likelihoods(self, all_exp, obs_rows):\n lhs = dict()\n\n days = obs_rows.shape[0]\n\n for state, obs, param in [(StateEnum.SYMPTOMATIQUE, ObsEnum.DHDT, self._fit_params['tau'])]:\n\n log_likelihood = 0\n for day_ndx in np.arange(5, days):\n # Take all the values of experiments on a given day day_ndx\n # for a given measurement (state.value)\n d = all_exp[:, day_ndx, state.value] # binomial\n observation = obs_rows[day_ndx, obs.value] # observation\n print(str(state) + \" d = \" + str(np.ceil(np.mean(d))) + \"-----------\" + \" obs = \" + str(\n observation) + \"\\n\")\n # valeur la probabilite d'obtenir observation sachant que d suit cette distribution, avec parametre de tau\n try:\n x = binom.pmf(observation, max(observation, np.ceil(np.mean(d))), param)\n except FloatingPointError as exception:\n x = 0.001\n log_bin = np.log(x)\n print(\" log_bin = \" + str(log_bin) + \"---------------------------------------------------\")\n log_likelihood += log_bin\n\n lhs[obs] = log_likelihood\n\n # print(f\"likelihood {state} over {days} days: log_likelihood:{log_likelihood}\")\n\n return lhs\n\n def _plumb_scipy(self, params, days, error_func = None):\n lhs = dict()\n\n days = len(self._observations)\n\n # print(params)\n\n # Sarah's function prefers params as a dictionary\n # so we convert.\n params_as_dict = self._params_array_to_dict(params)\n\n res = self._predict(self._initial_conditions, days,\n params_as_dict)\n\n # data.append([S, E, A, SP, H, C, F, R,\n # infected_per_day, R_survivor, cumulI,\n # cumulH, R_out_HC])\n\n for state, obs, param in [(StateEnum.SYMPTOMATIQUE, ObsEnum.DHDT, params_as_dict['tau']),\n (StateEnum.CRITICAL, ObsEnum.DFDT, params_as_dict['theta']),\n (StateEnum.DSPDT, ObsEnum.NUM_TESTED, params_as_dict['mu']),\n (StateEnum.DTESTEDDT, ObsEnum.NUM_POSITIVE, params_as_dict['eta'])]:\n # donc 1) depuis le nombre predit de personne SymPtomatique et le parametre tau, je regarde si l'observations dhdt est probable\n # 2) depuis le nombre predit de personne Critical et le parametre theta, je regarde si l'observations dfdt est probable\n # 3) sur la transition entre Asymptomatique et Symptomatique ( sigma*A -> dSPdt) avec le parmetre de test(mu), je regarde si l'observation num_tested est probable\n # 4) sur la transition entre Asymptomatique et Symptomatique ( sigma*A -> dSPdt), je regarde la proportion de test realisees ( mu*sigma*A) avec le parmetre de sensibilite (eta), je regarde si l'observation num_positive est probable\n log_likelihood = 0\n for day_ndx in range(days):\n # Take all the values of experiments on a given day day_ndx\n # for a given measurement (state.value)\n\n observation = max(1, self._observations[day_ndx][obs.value])\n prediction = res[day_ndx][state.value]\n # print(str(state) + \" d = \"+ str(np.ceil(prediction)) + \"-----------\" + \" obs = \" + str(observation) + \"\\n\")\n try:\n x = binom.pmf(observation, np.ceil(np.mean(prediction)), param) + 0.0000000001\n except FloatingPointError as exception:\n x = 0.0000000001\n log_bin = np.log(x)\n # print(\" log_bin = \" + str(log_bin) + \"---------------------------------------------------\")\n log_likelihood += log_bin\n\n lhs[obs] = log_likelihood\n\n # print(f\"likelihood {state} over {days} days: log_likelihood:{log_likelihood}\")\n\n # print(\"likelihood: {}\".format(-sum(lhs.values())))\n return -sum(lhs.values())\n\n # return least_squares\n\n def fit_parameters(self, error_func):\n # L-BFGS-B accepts bounds\n\n np.seterr(all = 'raise')\n\n params = self.get_initial_parameters()\n bounds = np.array([(p.min, p.max) for p_name, p in params.items()])\n\n # self._error_func = error_func\n\n for p_name, p in params.items():\n print(\"{:10s} [{:.2f} - {:.2f}]\".format(p_name, p.min, p.max))\n\n x0 = [p.value for p_name, p in params.items()]\n print(\"initial guess for params: {}\".format(x0))\n\n # exit()\n res = scipy_minimize(self._plumb_scipy,\n x0 = x0,\n method = 'L-BFGS-B',\n bounds = bounds, args = (error_func,))\n\n print(res)\n\n self._fit_params = self._params_array_to_dict(res.x)\n\n for p_name, p in params.items():\n print(\"{:10s} [{:.2f} - {:.2f}] : {:.2f}\".format(p_name, p.min, p.max, self._fit_params[p_name]))\n\n def predict(self, days):\n res = self._predict(self._initial_conditions, days, self._fit_params)\n return res\n\n def predict_stochastic(self, days):\n res = self._predict(self._initial_conditions, days, self._fit_params, stochastic = True)\n return res\n\n def _predict_stochastic(self, initial_conditions, days, params):\n return self._predict(initial_conditions, days, params, stochastic = True)\n\n def _predict(self, initial_conditions, days, params, stochastic = False):\n gamma1 = params['gamma1']\n gamma2 = params['gamma2']\n gamma3 = params['gamma3']\n gamma4 = params['gamma4']\n beta = params['beta']\n tau = params['tau']\n delta = params['delta']\n sigma = params['sigma']\n rho = params['rho']\n theta = params['theta']\n mu = params['mu']\n eta = params['eta']\n\n S, E, A, SP, H, C, F, R, infected_per_day, R_out_HC, cumulI = initial_conditions\n cumulH = 0\n\n data = []\n\n for d in range(days):\n ys = [S, E, A, SP, H, C, F, R]\n\n if stochastic:\n dSdt, dEdt, dAdt, dSPdt, dHdt, dCdt, dFdt, dRdt, dHIndt, dFIndt, dSPIndt, DTESTEDDT, DTESTEDPOSDT = self._model_stochastic(\n ys, gamma1, gamma2, gamma3, gamma4, beta, tau, delta, sigma, rho, theta, mu, eta)\n else:\n dSdt, dEdt, dAdt, dSPdt, dHdt, dCdt, dFdt, dRdt, dHIndt, dFIndt, dSPIndt, DTESTEDDT, DTESTEDPOSDT = self._model(\n ys, gamma1, gamma2, gamma3, gamma4, beta, tau, delta, sigma, rho, theta, mu, eta)\n\n S += dSdt\n E += dEdt\n A += dAdt\n SP += dSPdt\n H += dHdt\n C += dCdt\n F += dFdt\n R += dRdt\n\n data.append([S, E, A, SP, H, C, F, R, dHIndt, dFIndt, dSPIndt, DTESTEDDT, DTESTEDPOSDT])\n\n return np.array(data)\n\n def _model(self, ys, gamma1, gamma2, gamma3, gamma4, beta, tau, delta, sigma, rho, theta, mu, eta):\n S, E, A, SP, H, C, F, R = ys\n\n N = self._N\n\n dSdt = -beta * S * (A + SP) / N\n dEdt = beta * S * (A + SP) / N - rho * E\n # dAdt = rho * E - sigma*E - gamma4 * A\n dAdt = rho * E - sigma * A - gamma4 * A\n # dSPdt = sigma * E - tau * SP - gamma1 * SP\n dSPdt = sigma * A - tau * SP - gamma1 * SP\n dHdt = tau * SP - delta * H - gamma2 * H\n dCdt = delta * H - theta * C - gamma3 * C\n dFdt = theta * C\n dRdt = gamma1 * SP + gamma2 * H + gamma3 * C + gamma4 * A\n\n dHIndt = tau * SP\n dFIndt = theta * C\n dSPIndt = sigma * A\n DTESTEDDT = dSPIndt * mu\n DTESTEDPOSDT = DTESTEDDT * eta # eta = sensibilite\n\n return [dSdt, dEdt, dAdt, dSPdt, dHdt, dCdt, dFdt, dRdt, dHIndt, dFIndt, dSPIndt, DTESTEDDT, DTESTEDPOSDT]\n\n def _model_stochastic(self, ys, gamma1, gamma2, gamma3, gamma4, beta, tau, delta, sigma, rho, theta, mu, eta):\n S, E, A, SP, H, C, F, R = ys\n\n N = self._N\n\n # betaS = beta * S * (A+SP) / N\n # rhoE = rho * E\n # sigmaA = sigma * A\n # gamma4A = gamma4 * A\n # tauSP = tau * SP\n # gamma1SP = gamma1 * SP\n # deltaH = delta * H\n # gamma2H = gamma2 * H\n # thetaC = theta * C\n # gamma3C = gamma3 * C\n\n betaS = population_leave(beta, S * (A + SP) / N)\n rhoE = population_leave(rho, E)\n sigmaA = population_leave(sigma, A)\n gamma4A = population_leave(gamma4, A)\n tauSP = population_leave(tau, SP)\n gamma1SP = population_leave(gamma1, SP)\n deltaH = population_leave(delta, H)\n gamma2H = population_leave(gamma2, H)\n thetaC = population_leave(theta, C)\n gamma3C = population_leave(gamma3, C)\n muSP = population_leave(mu, sigmaA) # pas sur qu'il faut pas la moyenne\n etaSP = population_leave(eta, muSP)\n\n dSdt = -betaS\n dEdt = betaS - rhoE\n # dAdt = rho * E - sigma*E - gamma4 * A\n dAdt = rhoE - sigmaA - gamma4A\n # dSPdt = sigma * E - tau * SP - gamma1 * SP\n dSPdt = sigmaA - tauSP - gamma1SP\n dHdt = tauSP - deltaH - gamma2H\n dCdt = deltaH - thetaC - gamma3C\n dFdt = thetaC\n dRdt = gamma1SP + gamma2H + gamma3C + gamma4A\n\n dHIndt = tauSP\n dFIndt = thetaC\n dSPIndt = sigmaA\n DTESTEDDT = muSP\n DTESTEDPOSDT = etaSP\n\n return [dSdt, dEdt, dAdt, dSPdt, dHdt, dCdt, dFdt, dRdt, dHIndt, dFIndt, dSPIndt, DTESTEDDT, DTESTEDPOSDT]\n\n def _params_array_to_dict(self, params):\n return dict(\n zip(['gamma1', 'gamma2', 'gamma3', 'gamma4', 'beta', 'tau', 'delta', 'sigma', 'rho', 'theta', 'mu', 'eta'],\n params))\n\n def _plumb_scipy_stocha(self, params):\n\n days = len(self._observations)\n\n # Sarah's function prefers params as a dictionary\n # so we convert.\n params_as_dict = self._params_array_to_dict(params)\n\n NB_EXPERIMENTS = 100\n PREDICTED_DAYS = 80\n\n # print(f\"Running {NB_EXPERIMENTS} experiments\")\n\n experiments = [] # dims : [experiment #][day][value]\n\n for i in range(NB_EXPERIMENTS):\n sres = ms._predict_stochastic(\n self._initial_conditions, days,\n params_as_dict)\n experiments.append(sres)\n # print(\"... done running experiments\")\n\n all_exp = np.stack(experiments)\n lhs = dict()\n\n for state, obs, param in [(StateEnum.SYMPTOMATIQUE, ObsEnum.DHDT, params_as_dict['tau']),\n (StateEnum.DSPDT, ObsEnum.NUM_TESTED, params_as_dict['mu']),\n (StateEnum.DTESTEDDT, ObsEnum.NUM_POSITIVE, params_as_dict['eta'])]:\n # donc 1) depuis le nombre predit de personne SymPtomatique et le parametre tau, je regarde si l'observations dhdt est probable\n # 2) depuis le nombre predit de personne Critical et le parametre theta, je regarde si l'observations dfdt est probable\n # 3) sur la transition entre Asymptomatique et Symptomatique ( sigma*A -> dSPdt) avec le parmetre de test(mu), je regarde si l'observation num_tested est probable\n # 4) sur la transition entre Asymptomatique et Symptomatique ( sigma*A -> dSPdt), je regarde la proportion de test realisees ( mu*sigma*A) avec le parmetre de sensibilite (eta), je regarde si l'observation num_positive est probable\n log_likelihood = 0\n for day_ndx in np.arange(10, days):\n\n # Take all observations (real data) on a given day day_ndx, for a given measurements\n observation = max(1, self._observations[day_ndx][obs.value])\n # Take all the values of simulations on a given day (day_ndx)\n # for a given measurement (state.value)\n d = all_exp[:, day_ndx, state.value] # binomial\n\n # Take the mean of all the experiments as the final result of our\n # simulation\n prediction = np.mean(d)\n # print(str(state) + \" d = \"+ str(np.ceil(prediction)) + \"-----------\" + \" obs = \" + str(observation) + \"\\n\")\n try:\n # We compute x as the probability of seeing the\n # observation (a number of individuals), given it\n # follows a Binomial distribution of parameters\n # n=prediction, p=value of the param.\n # Question : does a binomial parametrized like that\n # end up being a good predictor of our observations ?\n # The binomial models a scenario where we repeat\n # n times an experiment (eg. people being in contact\n # with some infectious) where success (the person\n # gets infected) happens with a probability p.\n # In our data, this gives:\n\n # Given we have\n # n = # of persons StateEnum.SYMPTOMATIQUE\n # p = tau = probability of a person moving from SYMPTOMATIQUE to HOSPITALIZED\n # the binomial predict how many peson we'll be hospitalized.\n # We compare that to ObsEnum.DHDT. So we ask the binomial\n # to tell us the probability of observing DHDT, given the parameters (n,p).\n\n x = binom.pmf(observation, np.ceil(np.mean(prediction)), param)\n log_bin = np.log(x)\n except FloatingPointError as exception:\n log_bin = -999\n # print(\" log_bin = \" + str(x) + \"---------------------------------------------------\")\n log_likelihood += log_bin\n\n # Combine the likelihoods of each parameter\n lhs[obs] = log_likelihood\n return -sum(lhs.values())\n\n def stocha_fit_parameters(self):\n # L-BFGS-B accepts bounds\n\n np.seterr(all = 'raise')\n\n # Find first set of parameters\n params = self.get_initial_parameters()\n bounds = np.array([(p.min, p.max) for p_name, p in params.items()])\n\n # Group parameters\n for p_name, p in params.items():\n print(\"{:10s} [{:.2f} - {:.2f}]\".format(p_name, p.min, p.max))\n\n x0 = [p.value for p_name, p in params.items()]\n print(\"initial guess for params: {}\".format(x0))\n\n res = scipy_minimize(self._plumb_scipy_stocha,\n x0 = x0,\n method = 'L-BFGS-B',\n bounds = bounds)\n\n print(res)\n\n self._fit_params = self._params_array_to_dict(res.x)\n\n for p_name, p in params.items():\n print(\"{:10s} [{:.2f} - {:.2f}] : {:.2f}\".format(p_name, p.min, p.max, self._fit_params[p_name]))\n\n\nif __name__ == \"__main__\":\n observations = load_model_data()\n rows = np.array(observations)\n days = len(rows)\n\n ms = SarahStat(rows, 1000000)\n\n ms.stocha_fit_parameters()\n\n sres = ms.predict(80)\n\n version = 3\n\n plt.figure()\n plt.title('HOSPITALIZED / PER DAY fit')\n t = StateEnum.DHDT\n plt.plot(sres[:, t.value], label = str(t) + \" (model)\")\n u = ObsEnum.DHDT\n plt.plot(rows[:, u.value], \"--\", label = str(u) + \" (real)\")\n plt.savefig('img/v{}-dhdt.pdf'.format(version))\n\n plt.figure()\n plt.title('Hospitalized')\n t = StateEnum.HOSPITALIZED\n plt.plot(sres[:, t.value], label = str(t) + \" (model)\")\n u = ObsEnum.NUM_HOSPITALIZED\n plt.plot(rows[:, u.value], \"--\", label = str(u) + \" (real)\")\n plt.savefig('img/v{}-hospitalized.pdf'.format(version))\n\n plt.figure()\n plt.title('Critical')\n t = StateEnum.CRITICAL\n plt.plot(sres[:, t.value], label = str(t) + \" (model)\")\n u = ObsEnum.NUM_CRITICAL\n plt.plot(rows[:, u.value], \"--\", label = str(u) + \" (real)\")\n plt.savefig('img/v{}-critical.pdf'.format(version))\n\n plt.figure()\n plt.title('FATALITIES')\n t = StateEnum.FATALITIES\n plt.plot(sres[:, t.value], label = str(t) + \" (model)\")\n u = ObsEnum.NUM_FATALITIES\n plt.plot(rows[:, u.value], \"--\", label = str(u) + \" (real)\")\n plt.savefig('img/v{}-FATALITIES.pdf'.format(version))\n\n plt.figure()\n plt.title('FATALITIES / PER DAY fit')\n t = StateEnum.DFDT\n plt.plot(sres[:, t.value], label = str(t) + \" (model)\")\n u = ObsEnum.DFDT\n plt.plot(rows[:, u.value], \"--\", label = str(u) + \" (real)\")\n plt.savefig('img/v{}-dftf.pdf'.format(version))\n\n plt.figure()\n plt.title('NUM_tested / PER DAY fit')\n t = StateEnum.DTESTEDDT\n plt.plot(sres[:, t.value], label = str(t) + \" (model)\")\n u = ObsEnum.NUM_TESTED\n plt.plot(rows[:, u.value], \"--\", label = str(u) + \" (real)\")\n plt.savefig('img/v{}-dtesteddt.pdf'.format(version))\n\n plt.figure()\n plt.title('NUM_Positive / PER DAY fit')\n t = StateEnum.DTESTEDPOSDT\n plt.plot(sres[:, t.value], label = str(t) + \" (model)\")\n u = ObsEnum.NUM_POSITIVE\n plt.plot(rows[:, u.value], \"--\", label = str(u) + \" (real)\")\n plt.savefig('img/v{}-dtestedposdt.pdf'.format(version))\n #exit()\n #\n # plt.figure()\n # plt.title('LM fit')\n #\n #\n # NB_EXPERIMENTS = 1000\n # PREDICTED_DAYS = 80\n #\n # print(f\"Running {NB_EXPERIMENTS} experiments\")\n # experiments = [] # dims : [experiment #][day][value]\n #\n # for i in range(NB_EXPERIMENTS):\n # sres = ms.predict_stochastic(PREDICTED_DAYS)\n # experiments.append(sres)\n # print(\"... done running experiments\")\n #\n # all_exp = np.stack(experiments)\n # log_likelihoods = ms.compute_log_likelihoods(all_exp, rows)\n # log_likelihoods_all_params = sum(log_likelihoods.values())\n #\n #\n # # NB_BINS = NB_EXPERIMENTS//20\n #\n # # for state, obs in [(StateEnum.HOSPITALIZED, ObsEnum.NUM_HOSPITALIZED),\n # # (StateEnum.CRITICAL, ObsEnum.NUM_CRITICAL)]:\n #\n # # likelihood = 1\n # # log_likelihood = 0\n # # for day_ndx in range(days):\n # # d = all_exp[:, day_ndx, state.value]\n # # histo = np.histogram(d,bins=NB_BINS)\n #\n # # # From histogram counts to probabilities\n # # proba = histo[0] * (1/np.sum(histo[0]))\n #\n # # # In which bin fits the observation ?\n # # observation = rows[day_ndx, obs.value]\n # # tbin = np.digitize(observation, histo[1]) - 1\n #\n # # if tbin < 0:\n # # tbin = 0\n # # elif tbin >= NB_BINS:\n # # tbin = NB_BINS - 1\n #\n #\n # # prob = proba[tbin]\n #\n # # if True or prob == 0:\n # # # print(histo)\n # # # print(observation)\n #\n # # # x = np.arange(len(proba))\n # # # idx = np.nonzero(proba)\n # # # interp = interp1d(x[idx], proba[idx])\n # # # print(interp(tbin))\n #\n # # model = KernelDensity(bandwidth=max(1, (np.amax(d) / 10)), kernel='gaussian')\n # # model.fit(d.reshape(-1, 1))\n #\n #\n # # ls = np.linspace(observation-0.5,observation+0.5,2)[:,np.newaxis]\n # # prob = np.sum( np.exp( model.score_samples(ls))) / 2\n #\n # # prob2 = model.score_samples([[observation]])\n #\n #\n #\n # # # # Debug\n # # # print(f\"obs:{observation} prob:{prob} prob2:{prob2}\")\n # # # plt.figure()\n #\n # # # density, bins = np.histogram(d, bins=NB_BINS, density=True)\n # # # unity_density = density / density.sum()\n # # # widths = bins[:-1] - bins[1:]\n # # # #plt.bar(bins[1:], unity_density, width=widths)\n #\n # # # plt.hist(d,bins=NB_BINS,density=True)\n #\n # # # log_dens = model.score_samples(histo[1].reshape( -1, 1))\n # # # plt.plot(histo[1], np.exp(log_dens), c='red')\n # # # plt.title(f\"Day:{day_ndx}\")\n # # # plt.show()\n #\n # # likelihood *= prob\n # # log_likelihood += prob2\n #\n # # print(f\"likelihood {state}: {likelihood}, log_likelihood:{log_likelihood}\")\n #\n # # exit()\n #\n # # for sres in experiments:\n # # for t in [StateEnum.RSURVIVOR]: #, StateEnum.HOSPITALIZED, StateEnum.CRITICAL, StateEnum.FATALITIES]:\n # # plt.plot(sres[:, t.value], c=COLORS_DICT[t], alpha=0.05, linewidth=0.4)\n #\n #\n # sres = ms.predict(250)\n #\n # plt.figure()\n # t = StateEnum.DHDT\n # plt.plot(sres[:, t.value], c=COLORS_DICT[t], label=f\"{t} (model)\")\n # u = ObsEnum.DHDT\n # plt.plot(rows[:, u.value], \"--\", c=COLORS_DICT[u], label=f\"{u} (real)\")\n # plt.savefig('dhdt.pdf')\n #\n # plt.figure()\n # t = StateEnum.DFDT\n # plt.plot(sres[:, t.value], c=COLORS_DICT[t], label=f\"{t} (model)\")\n # u = ObsEnum.DFDT\n # plt.plot(rows[:, u.value], \"--\", c=COLORS_DICT[u], label=f\"{u} (real)\")\n # plt.savefig('dftf.pdf')\n #\n # exit()\n #\n # # for t in [, StateEnum.DFDT]:\n #\n # # for u in [ObsEnum.NUM_HOSPITALIZED, ObsEnum.NUM_CRITICAL,ObsEnum.NUM_FATALITIES]:\n # # plt.plot(rows[:, u.value], \"--\", c=COLORS_DICT[u], label=f\"{u} (real)\")\n #\n #\n # plt.title('Curve Fitting')\n # plt.xlabel('Days')\n # plt.ylabel('Individuals')\n # prediction_days = 10 # prediction at prediction_days\n # plt.xlim(0, days + prediction_days)\n # plt.ylim(0, 1000)\n # plt.legend()\n # plt.savefig('data_fit.pdf')\n # plt.savefig(f'data_fit_{days}_days.pdf')\n # plt.show()\n #\n # plt.figure()\n # jet = plt.get_cmap('jet')\n # days_max = min(200, PREDICTED_DAYS)\n # cNorm = colors.Normalize(vmin=20, vmax=days_max)\n # scalarMap = cm.ScalarMappable(norm=cNorm, cmap=jet)\n # for day in range(60,days_max):\n # d = [experiments[exp_i][day, StateEnum.HOSPITALIZED.value] for exp_i in range(NB_EXPERIMENTS)]\n # hd = np.histogram(d,bins=50)[0]\n # plt.plot(hd, c=scalarMap.to_rgba(day), alpha=0.2)\n # plt.title(\"Normalized histograms of 1000/day hospitalized values (color = day)\")\n # plt.xticks([])\n # plt.colorbar(scalarMap)\n #\n # plt.figure()\n # for t in [StateEnum.EXPOSED, StateEnum.ASYMPTOMATIQUE, StateEnum.SYMPTOMATIQUE ,StateEnum.HOSPITALIZED, StateEnum.CRITICAL, StateEnum.FATALITIES]:\n # plt.plot(sres[:, t.value], label=f\"{t} (model)\")\n #\n # plt.title('Exposed - Infectious - Hospitalized - Critical')\n # plt.xlabel('Days')\n # plt.ylabel('Individuals')\n # plt.legend()\n # plt.savefig('projection_zoom.pdf')\n # plt.savefig(f'projection_zoom_{days}_days.pdf')\n # plt.show()\n #\n # plt.figure()\n # for t in [StateEnum.SUCEPTIBLE, StateEnum.RECOVERED, StateEnum.CUMULI, StateEnum.FATALITIES]:\n # plt.plot(sres[:, t.value], label=f\"{t} (model)\")\n #\n # plt.title('States')\n # plt.xlabel('Days')\n # plt.ylabel('Individuals')\n # plt.legend()\n # plt.savefig('projection_global.pdf')\n # plt.savefig(f'projection_global_{days}_days.pdf')\n # plt.show()\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":35116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"191509498","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Notation\"\"\"\n\nimport numpy as np\nfrom mechkit.utils import Ex\n\n\nclass Converter(object):\n r\"\"\"\n Convert numerical tensors from one notation to another.\n\n Supported notations and shapes:\n\n - tensor\n\n - 2. order tensor: (3, 3)\n - 4. order tensor: (3, 3, 3, 3,)\n\n - mandel6 [Mandel1965]_\n\n - 2. order tensor: (6,) [Symmetry]\n - 4. order tensor: (6, 6) [Left- and right- minor symmetry]\n\n - mandel9 [Brannon2018]_\n\n - 2. order tensor: (9,)\n - 4. order tensor: (9, 9)\n\n References and theory can be found in the method descriptions below.\n\n Methods\n -------\n to_tensor(inp)\n Convert to tensor notation\n\n to_mandel6(inp)\n Convert to Mandel notation with 6 symmetric base dyads\n\n to_mandel9(inp)\n Convert to Mandel notation with 6 symmetric and 3 skew base dyads\n\n to_like(inp, like)\n Convert input to notation of like\n\n Examples\n --------\n >>> import numpy as np\n >>> import mechkit\n >>> con = mechkit.notation.Converter()\n >>> tensors = mechkit.tensors.Basic()\n\n >>> t2 = np.array(\n >>> [[1., 6., 5., ],\n >>> [6., 2., 4., ],\n >>> [5., 4., 3., ], ]\n >>> )\n >>> con.to_mandel6(t2)\n [1. 2. 3. 5.66 7.07 8.49]\n\n >>> np.sqrt(2.)\n 1.414213\n\n >>> np.arange(9).reshape(3,3)\n [[0 1 2]\n [3 4 5]\n [6 7 8]]\n >>> con.to_mandel6(np.arange(9).reshape(3,3))\n [0. 4. 8. 8.49 5.66 2.83]\n\n >>> tensors.I4s\n [[[[1. 0. 0. ]\n [0. 0. 0. ]\n [0. 0. 0. ]]\n [[0. 0.5 0. ]\n [0.5 0. 0. ]\n [0. 0. 0. ]]\n [[0. 0. 0.5]\n [0. 0. 0. ]\n [0.5 0. 0. ]]]\n [[[0. 0.5 0. ]\n [0.5 0. 0. ]\n [0. 0. 0. ]]\n [[0. 0. 0. ]\n [0. 1. 0. ]\n [0. 0. 0. ]]\n [[0. 0. 0. ]\n [0. 0. 0.5]\n [0. 0.5 0. ]]]\n [[[0. 0. 0.5]\n [0. 0. 0. ]\n [0.5 0. 0. ]]\n [[0. 0. 0. ]\n [0. 0. 0.5]\n [0. 0.5 0. ]]\n [[0. 0. 0. ]\n [0. 0. 0. ]\n [0. 0. 1. ]]]]\n >>> con.to_mandel6(tensors.I4s)\n [[1. 0. 0. 0. 0. 0.]\n [0. 1. 0. 0. 0. 0.]\n [0. 0. 1. 0. 0. 0.]\n [0. 0. 0. 1. 0. 0.]\n [0. 0. 0. 0. 1. 0.]\n [0. 0. 0. 0. 0. 1.]]\n >>> con.to_mandel9(tensors.I4s)\n [[1. 0. 0. 0. 0. 0. 0. 0. 0.]\n [0. 1. 0. 0. 0. 0. 0. 0. 0.]\n [0. 0. 1. 0. 0. 0. 0. 0. 0.]\n [0. 0. 0. 1. 0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 1. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0. 1. 0. 0. 0.]\n [0. 0. 0. 0. 0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0. 0. 0. 0. 0.]]\n\n >>> #Asymmetric identity\n >>> con.to_mandel9(tensors.I4a)\n [[0. 0. 0. 0. 0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0. 0. 1. 0. 0.]\n [0. 0. 0. 0. 0. 0. 0. 1. 0.]\n [0. 0. 0. 0. 0. 0. 0. 0. 1.]]\n\n \"\"\"\n\n def __init__(self, dtype=\"float64\"):\n\n self.dtype = dtype\n self.factor = np.sqrt(2.0) / 2.0\n\n self.DIM = 3\n self.DIM_MANDEL6 = 6\n self.DIM_MANDEL9 = 9\n self.SLICE6 = np.s_[0:6]\n self.BASE6 = self.get_mandel_base_sym()\n self.BASE9 = self.get_mandel_base_skw()\n\n def get_mandel_base_sym(self,):\n r\"\"\"Get orthonormal basis of Mandel6 representation introduced by\n [Mandel1965]_, [Fedorov1968]_, [Mehrabadi1990]_ and\n discussed by [Cowin1992]_.\n\n Base dyads:\n\n .. math::\n \\begin{align*}\n \\boldsymbol{B}_1 &= \\boldsymbol{e}_1 \\otimes \\boldsymbol{e}_1\\\\\n \\boldsymbol{B}_2 &= \\boldsymbol{e}_2 \\otimes \\boldsymbol{e}_2\\\\\n \\boldsymbol{B}_3 &= \\boldsymbol{e}_3 \\otimes \\boldsymbol{e}_3\\\\\n \\boldsymbol{B}_4 &= \\frac{\\sqrt{2}}{2}\\left(\n \\boldsymbol{e}_3 \\otimes \\boldsymbol{e}_2\n +\n \\boldsymbol{e}_2 \\otimes \\boldsymbol{e}_3\n \\right) \\\\\n \\boldsymbol{B}_5 &= \\frac{\\sqrt{2}}{2}\\left(\n \\boldsymbol{e}_1 \\otimes \\boldsymbol{e}_3\n +\n \\boldsymbol{e}_3 \\otimes \\boldsymbol{e}_1\n \\right) \\\\\n \\boldsymbol{B}_6 &= \\frac{\\sqrt{2}}{2}\\left(\n \\boldsymbol{e}_2 \\otimes \\boldsymbol{e}_1\n +\n \\boldsymbol{e}_1 \\otimes \\boldsymbol{e}_2\n \\right)\n \\end{align*}\n\n with\n\n - :math:`\\otimes` : Dyadic product\n - :math:`\\boldsymbol{e}_\\text{i}` : i-th Vector of orthonormal basis\n\n Orthogonality:\n\n .. math::\n \\begin{align*}\n \\boldsymbol{B}_{\\alpha} &\\cdot \\boldsymbol{B}_{\\beta}\n = \\delta_{\\alpha\\beta}\n \\end{align*}\n\n Conversions: (Einstein notation applies)\n\n .. math::\n \\begin{align*}\n \\sigma_{\\alpha}^{\\text{M}} &=\n \\boldsymbol{\\sigma}\n \\cdot\n \\boldsymbol{B}_{\\alpha} \\\\\n C_{\\alpha\\beta}^{\\text{M}} &=\n \\boldsymbol{B}_{\\alpha}\n \\cdot\n \\mathbb{C} \\left[\\boldsymbol{B}_{\\beta}\\right] \\\\\n \\boldsymbol{\\sigma} &=\n \\sigma_{\\alpha}^{\\text{M}}\n \\boldsymbol{B}_{\\alpha} \\\\\n \\mathbb{C} &=\n C_{\\alpha\\beta}^{\\text{M}}\n \\boldsymbol{B}_{\\alpha}\n \\otimes\n \\boldsymbol{B}_{\\beta} \\\\\n \\end{align*}\n\n with\n\n - :math:`\\boldsymbol{\\sigma}` : Second order tensor\n - :math:`\\mathbb{C}` : Fourth order tensor\n - :math:`\\sigma_{\\alpha}^{\\text{M}}` : Component in Mandel notation\n - :math:`C_{\\alpha\\beta}^{\\text{M}}` : Component in Mandel notation\n\n Implications of the Mandel basis:\n\n - Stress and strain are converted equally, as well as stiffness and compliance. This is in contrast to non-normalized Voigt notation, where conversion rules depend on the physical type of the tensor entity.\n - Eigenvalues and eigenvectors of a component matrix in Mandel notation are equal to eigenvalues and eigenvectors of the tensor.\n - Components of the stress and strain vectors:\n\n .. math::\n \\begin{align*}\n \\boldsymbol{\\sigma}^{\\text{M6}}\n =\n \\begin{bmatrix}\n \\sigma_{\\text{11}} \\\\\n \\sigma_{\\text{22}} \\\\\n \\sigma_{\\text{33}} \\\\\n \\frac{\\sqrt{2}}{2}\\left(\n \\sigma_{\\text{32}}\n +\n \\sigma_{\\text{23}}\n \\right) \\\\\n \\frac{\\sqrt{2}}{2}\\left(\n \\sigma_{\\text{13}}\n +\n \\sigma_{\\text{31}}\n \\right) \\\\\n \\frac{\\sqrt{2}}{2}\\left(\n \\sigma_{\\text{21}}\n +\n \\sigma_{\\text{12}}\n \\right)\n \\end{bmatrix}\n &\\quad\n \\boldsymbol{\\varepsilon}^{\\text{M6}}\n =\n \\begin{bmatrix}\n \\varepsilon_{\\text{11}} \\\\\n \\varepsilon_{\\text{22}} \\\\\n \\varepsilon_{\\text{33}} \\\\\n \\frac{\\sqrt{2}}{2}\\left(\n \\varepsilon_{\\text{32}}\n +\n \\varepsilon_{\\text{23}}\n \\right) \\\\\n \\frac{\\sqrt{2}}{2}\\left(\n \\varepsilon_{\\text{13}}\n +\n \\varepsilon_{\\text{31}}\n \\right) \\\\\n \\frac{\\sqrt{2}}{2}\\left(\n \\varepsilon_{\\text{21}}\n +\n \\varepsilon_{\\text{12}}\n \\right)\n \\end{bmatrix}\n \\end{align*}\n\n .. warning::\n\n - (Most) unsymmetric parts are discarded during conversion (Exception: Major symmetry of fourth order tensors). Use Mandel9 notation to represent unsymmetric tensors.\n - Components of stiffness matrix in Mandel notation differ from those in Voigt notation. See examples of VoigtConverter below.\n\n .. rubric:: References\n\n .. [Mandel1965] Mandel, J., 1965.\n Généralisation de la théorie de plasticité de WT Koiter.\n International Journal of Solids and structures, 1(3), pp.273-295.\n\n .. [Fedorov1968] Fedorov, F.I., 1968.\n Theory of elastic waves in crystals.\n\n .. [Mehrabadi1990] Mehrabadi, M.M. and Cowin, S.C., 1990.\n Eigentensors of linear anisotropic elastic materials.\n The Quarterly Journal of Mechanics and Applied Mathematics, 43(1),\n pp.15-41.\n\n .. [Cowin1992] Cowin, S.C. and Mehrabadi, M.M., 1992.\n The structure of the linear anisotropic elastic symmetries.\n Journal of the Mechanics and Physics of Solids, 40(7),\n pp.1459-1471.\n\n Returns\n -------\n np.array with shape (6, 3, 3)\n B(i, :, :) is the i-th dyade of the base.\n \"\"\"\n\n B = np.zeros((self.DIM_MANDEL6, self.DIM, self.DIM), dtype=self.dtype,)\n\n B[0, 0, 0] = 1.0\n B[1, 1, 1] = 1.0\n B[2, 2, 2] = 1.0\n B[3, 1, 2] = B[3, 2, 1] = self.factor\n B[4, 0, 2] = B[4, 2, 0] = self.factor\n B[5, 0, 1] = B[5, 1, 0] = self.factor\n return B\n\n def get_mandel_base_skw(self,):\n r\"\"\"\n Get orthonormal basis of Mandel9 representation [csmbrannonMandel]_,\n [Brannon2018]_. The basis of Mandel6 representation is extended by\n\n .. math::\n \\begin{align*}\n \\boldsymbol{B}_7 &= \\frac{\\sqrt{2}}{2}\\left(\n \\boldsymbol{e}_3 \\otimes \\boldsymbol{e}_2\n -\n \\boldsymbol{e}_2 \\otimes \\boldsymbol{e}_3\n \\right) \\\\\n \\boldsymbol{B}_8 &= \\frac{\\sqrt{2}}{2}\\left(\n \\boldsymbol{e}_1 \\otimes \\boldsymbol{e}_3\n -\n \\boldsymbol{e}_3 \\otimes \\boldsymbol{e}_1\n \\right) \\\\\n \\boldsymbol{B}_9 &= \\frac{\\sqrt{2}}{2}\\left(\n \\boldsymbol{e}_2 \\otimes \\boldsymbol{e}_1\n -\n \\boldsymbol{e}_1 \\otimes \\boldsymbol{e}_2\n \\right)\n \\end{align*}\n\n This basis is used to represent skew tensors and implies:\n\n .. math::\n \\begin{align*}\n \\boldsymbol{\\sigma}^{\\text{M9}}\n =\n \\begin{bmatrix}\n \\boldsymbol{\\sigma}^{\\text{M6}} \\\\\n \\frac{\\sqrt{2}}{2}\\left(\n \\sigma_{\\text{32}}\n -\n \\sigma_{\\text{23}}\n \\right) \\\\\n \\frac{\\sqrt{2}}{2}\\left(\n \\sigma_{\\text{13}}\n -\n \\sigma_{\\text{31}}\n \\right) \\\\\n \\frac{\\sqrt{2}}{2}\\left(\n \\sigma_{\\text{23}}\n -\n \\sigma_{\\text{12}}\n \\right)\n \\end{bmatrix}\n \\end{align*}\n\n .. rubric:: References\n\n .. [csmbrannonMandel] https://csmbrannon.net/tag/mandel-notation/\n\n .. [Brannon2018] Brannon, R.M., 2018. Rotation, Reflection, and Frame\n Changes; Orthogonal tensors in computational engineering mechanics.\n Rotation, Reflection, and Frame Changes; Orthogonal tensors in\n computational engineering mechanics, by Brannon, RM\n ISBN: 978-0-7503-1454-1.\n IOP ebooks. Bristol, UK: IOP Publishing, 2018.\n\n\n Returns\n -------\n np.array with shape (9, 3, 3)\n B(i, :, :) is the i-th dyade of the base.\n \"\"\"\n\n B = np.zeros((self.DIM_MANDEL9, self.DIM, self.DIM), dtype=self.dtype,)\n B[0:6, :, :] = self.get_mandel_base_sym()\n\n B[6, 1, 2] = -self.factor\n B[6, 2, 1] = self.factor\n B[7, 0, 2] = self.factor\n B[7, 2, 0] = -self.factor\n B[8, 0, 1] = -self.factor\n B[8, 1, 0] = self.factor\n return B\n\n def to_mandel6(self, inp, verbose=False):\n \"\"\"Convert to Mandel6 notation\n\n Parameters\n ----------\n inp : np.array with unknown shape\n Input\n\n Returns\n -------\n np.array\n Input in Mandel6 notation\n \"\"\"\n\n if verbose:\n print(\"Skew parts are lost!\")\n\n f = self._get_to_mandel6_func(inp=inp)\n return f(inp=inp)\n\n def to_mandel9(self, inp):\n \"\"\"Convert to Mandel9 notation\n\n Parameters\n ----------\n inp : np.array with unknown shape\n Input\n\n Returns\n -------\n np.array\n Input in Mandel9 notation\n \"\"\"\n\n f = self._get_to_mandel9_func(inp=inp)\n return f(inp=inp)\n\n def to_tensor(self, inp):\n \"\"\"Convert to tensor notation\n\n Parameters\n ----------\n inp : np.array with unknown shape\n Input\n\n Returns\n -------\n np.array\n Input in tensor notation\n \"\"\"\n\n f = self._get_to_tensor_func(inp=inp)\n return f(inp=inp)\n\n def to_like(self, inp, like):\n \"\"\"Convert input to notation of like\n\n Parameters\n ----------\n inp : np.array with unknown shape\n Input\n\n like : np.array with unknown shape\n Tensor in desired notation\n\n Returns\n -------\n np.array\n Input in notation of like\n \"\"\"\n\n type_like = self._get_type_by_shape(like)\n\n functions = {\n \"t_\": self.to_tensor,\n \"m6\": self.to_mandel6,\n \"m9\": self.to_mandel9,\n }\n\n return functions[type_like[0:2]](inp)\n\n def _get_type_by_shape(self, inp):\n dim = (self.DIM,)\n dim_mandel6 = (self.DIM_MANDEL6,)\n dim_mandel9 = (self.DIM_MANDEL9,)\n\n types = {\n 2 * dim: \"t_2\",\n 4 * dim: \"t_4\",\n 1 * dim_mandel6: \"m6_2\",\n 2 * dim_mandel6: \"m6_4\",\n 1 * dim_mandel9: \"m9_2\",\n 2 * dim_mandel9: \"m9_4\",\n }\n\n try:\n type_ = types[inp.shape]\n except KeyError:\n raise Ex(\n \"Tensor shape not supported.\" \"\\n Supported shapes: {}\".format(types)\n )\n return type_\n\n def _get_to_mandel6_func(self, inp):\n type_ = self._get_type_by_shape(inp)\n\n functions = {\n \"t_2\": self._tensor2_to_mandel6,\n \"t_4\": self._tensor4_to_mandel6,\n \"m6_2\": self._pass_through,\n \"m6_4\": self._pass_through,\n \"m9_2\": self._mandel9_2_to_mandel6,\n \"m9_4\": self._mandel9_4_to_mandel6,\n }\n return functions[type_]\n\n def _get_to_mandel9_func(self, inp):\n type_ = self._get_type_by_shape(inp)\n\n functions = {\n \"t_2\": self._tensor2_to_mandel9,\n \"t_4\": self._tensor4_to_mandel9,\n \"m6_2\": self._mandel6_2_to_mandel9,\n \"m6_4\": self._mandel6_4_to_mandel9,\n \"m9_2\": self._pass_through,\n \"m9_4\": self._pass_through,\n }\n return functions[type_]\n\n def _get_to_tensor_func(self, inp):\n type_ = self._get_type_by_shape(inp)\n\n functions = {\n \"t_2\": self._pass_through,\n \"t_4\": self._pass_through,\n \"m6_2\": self._mandel6_2_to_tensor,\n \"m6_4\": self._mandel6_4_to_tensor,\n \"m9_2\": self._mandel9_2_to_tensor,\n \"m9_4\": self._mandel9_4_to_tensor,\n }\n return functions[type_]\n\n def _pass_through(self, inp):\n \"\"\"Do nothing, return argument\"\"\"\n return inp\n\n def _tensor2_to_mandel(self, inp, base):\n out = np.einsum(\"aij, ij ->a\", base, inp,)\n return out\n\n def _tensor4_to_mandel(self, inp, base):\n out = np.einsum(\"aij, ijkl, bkl ->ab\", base, inp, base,)\n return out\n\n def _tensor2_to_mandel6(self, inp):\n return self._tensor2_to_mandel(inp=inp, base=self.BASE6)\n\n def _tensor2_to_mandel9(self, inp):\n return self._tensor2_to_mandel(inp=inp, base=self.BASE9)\n\n def _tensor4_to_mandel6(self, inp):\n return self._tensor4_to_mandel(inp=inp, base=self.BASE6)\n\n def _tensor4_to_mandel9(self, inp):\n return self._tensor4_to_mandel(inp=inp, base=self.BASE9)\n\n def _mandel_2_to_tensor(self, inp, base):\n out = np.einsum(\"ajk, a->jk\", base, inp,)\n return out\n\n def _mandel_4_to_tensor(self, inp, base):\n out = np.einsum(\"ajk, ab, bmn->jkmn\", base, inp, base,)\n return out\n\n def _mandel6_2_to_tensor(self, inp):\n return self._mandel_2_to_tensor(inp=inp, base=self.BASE6)\n\n def _mandel6_4_to_tensor(self, inp):\n return self._mandel_4_to_tensor(inp=inp, base=self.BASE6)\n\n def _mandel9_2_to_tensor(self, inp):\n return self._mandel_2_to_tensor(inp=inp, base=self.BASE9)\n\n def _mandel9_4_to_tensor(self, inp):\n return self._mandel_4_to_tensor(inp=inp, base=self.BASE9)\n\n def _mandel6_2_to_mandel9(self, inp):\n zeros = np.zeros((self.DIM_MANDEL9,), dtype=self.dtype)\n zeros[self.SLICE6] = inp\n return zeros\n\n def _mandel6_4_to_mandel9(self, inp):\n zeros = np.zeros((self.DIM_MANDEL9, self.DIM_MANDEL9), dtype=self.dtype,)\n zeros[self.SLICE6, self.SLICE6] = inp\n return zeros\n\n def _mandel9_2_to_mandel6(self, inp):\n return inp[self.SLICE6]\n\n def _mandel9_4_to_mandel6(self, inp):\n return inp[self.SLICE6, self.SLICE6]\n\n\nclass VoigtConverter(Converter):\n r\"\"\"\n Extended converter handling Voigt notation.\n\n Voigt notation for the following physical quantities is supported:\n\n - stress\n - strain\n - stiffness\n - compliance\n\n .. warning::\n\n Usage of Voigt-representations is highly discouraged.\n Don't use representations in Voigt notation in function\n lacking \"voigt\" in the method name.\n The results will be wrong.\n\n Tensor representations in Voigt notation have the same\n dimensions than those in Mandel6 notation and therefore are\n treated as representations in Mandel6 notation, when passed\n to methods not including \"voigt\" in the method name.\n\n Component order is defined as\n\n .. math::\n \\begin{align*}\n \\boldsymbol{\\sigma}^{\\text{Voigt}}\n =\n \\begin{bmatrix}\n \\sigma_{\\text{11}} \\\\\n \\sigma_{\\text{22}} \\\\\n \\sigma_{\\text{33}} \\\\\n \\sigma_{\\text{23}} \\\\\n \\sigma_{\\text{13}} \\\\\n \\sigma_{\\text{12}} \\\\\n \\end{bmatrix}\n &\\quad\n \\boldsymbol{\\varepsilon}^{\\text{Voigt}}\n =\n \\begin{bmatrix}\n \\varepsilon_{\\text{11}} \\\\\n \\varepsilon_{\\text{22}} \\\\\n \\varepsilon_{\\text{33}} \\\\\n 2\\varepsilon_{\\text{23}} \\\\\n 2\\varepsilon_{\\text{13}} \\\\\n 2\\varepsilon_{\\text{12}} \\\\\n \\end{bmatrix}.\n \\end{align*}\n\n Methods\n -------\n mandel6_to_voigt(inp, voigt_type)\n Convert from Mandel6 to Voigt notation based on physical meaning of inp\n voigt_to_mandel6(inp, voigt_type)\n Convert from Voigt to Mandel6 notation based on physical meaning of inp\n\n Examples\n --------\n\n >>> import mechkit\n >>> con = mechkit.notation.VoigtConverter()\n\n >>> ones_2 = np.ones((3, 3),)\n [[1. 1. 1.]\n [1. 1. 1.]\n [1. 1. 1.]]\n >>> ones_2_mandel = con.to_mandel6(ones_2)\n [1. 1. 1. 1.41 1.41 1.41]\n >>> con.mandel6_to_voigt(inp=ones_2_mandel, voigt_type='stress')\n [1. 1. 1. 1. 1. 1.]\n >>> con.mandel6_to_voigt(inp=ones_2_mandel, voigt_type='strain')\n [1. 1. 1. 2. 2. 2.]\n\n >>> ones_4_mandel = con.to_mandel6(np.ones((3, 3, 3, 3),))\n [[1. 1. 1. 1.41 1.41 1.41]\n [1. 1. 1. 1.41 1.41 1.41]\n [1. 1. 1. 1.41 1.41 1.41]\n [1.41 1.41 1.41 2. 2. 2. ]\n [1.41 1.41 1.41 2. 2. 2. ]\n [1.41 1.41 1.41 2. 2. 2. ]]\n >>> con.mandel6_to_voigt(inp=ones_4_mandel, voigt_type='stiffness')\n [[1. 1. 1. 1. 1. 1.]\n [1. 1. 1. 1. 1. 1.]\n [1. 1. 1. 1. 1. 1.]\n [1. 1. 1. 1. 1. 1.]\n [1. 1. 1. 1. 1. 1.]\n [1. 1. 1. 1. 1. 1.]]\n >>> con.mandel6_to_voigt(inp=ones_4_mandel, voigt_type='compliance')\n [[1. 1. 1. 2. 2. 2.]\n [1. 1. 1. 2. 2. 2.]\n [1. 1. 1. 2. 2. 2.]\n [2. 2. 2. 4. 4. 4.]\n [2. 2. 2. 4. 4. 4.]\n [2. 2. 2. 4. 4. 4.]]\n\n \"\"\"\n\n def __init__(self, silent=False):\n\n if not silent:\n print(\n \"\\nWarning:\\n\"\n \"Use Voigt-representations only in functions involving\\n\"\n '\"voigt_\" in the function name.\\n'\n )\n\n self.type = \"Voigt\"\n\n self.shear = np.s_[3:6]\n self.quadrant1 = np.s_[0:3, 0:3]\n self.quadrant2 = np.s_[0:3, 3:6]\n self.quadrant3 = np.s_[3:6, 0:3]\n self.quadrant4 = np.s_[3:6, 3:6]\n\n self.factors_mandel_to_voigt = {\n \"stress\": [(self.shear, 1.0 / np.sqrt(2.0)),],\n \"strain\": [(self.shear, np.sqrt(2.0)),],\n \"stiffness\": [\n (self.quadrant2, 1.0 / np.sqrt(2.0)),\n (self.quadrant3, 1.0 / np.sqrt(2.0)),\n (self.quadrant4, 1.0 / 2.0),\n ],\n \"compliance\": [\n (self.quadrant2, np.sqrt(2.0)),\n (self.quadrant3, np.sqrt(2.0)),\n (self.quadrant4, 2.0),\n ],\n }\n\n super(type(self), self).__init__()\n\n def mandel6_to_voigt(self, inp, voigt_type):\n \"\"\"Transform Mandel to Voigt depending on voigt_type.\n\n Parameters\n ----------\n inp : np.array with shape (6,) or (6, 6) consistent with voigt_type\n Mandel representation\n\n voigt_type : string\n Defines conversion as types are converted differently.\n Supported types are\n ['stress', 'strain', 'stiffness', 'compliance'].\n Returns\n -------\n np.array with same shape as inp\n Voigt representation\n \"\"\"\n\n voigt = inp.copy()\n for position, factor in self.factors_mandel_to_voigt[voigt_type]:\n voigt[position] = inp[position] * factor\n\n return voigt\n\n def voigt_to_mandel6(self, inp, voigt_type):\n \"\"\"Transform Voigt to Mandel depending on voigt_type.\n\n Parameters\n ----------\n inp : np.array with shape (6,) or (6, 6) consistent with voigt_type\n Voigt representation\n\n voigt_type : string\n Defines conversion as types are converted differently.\n Supported types are\n ['stress', 'strain', 'stiffness', 'compliance'].\n Returns\n -------\n np.array with same shape as inp\n Mandel representation\n \"\"\"\n\n mandel = inp.copy()\n for position, factor in self.factors_mandel_to_voigt[voigt_type]:\n mandel[position] = inp[position] * 1.0 / factor\n\n return mandel\n\n\nif __name__ == \"__main__\":\n # Examples\n\n np.set_printoptions(\n linewidth=140,\n precision=2,\n # suppress=False,\n )\n\n # Converter\n\n import mechkit\n\n con = mechkit.notation.Converter()\n tensors = mechkit.tensors.Basic()\n\n printQueue = [\n # import mechkit as mk\n \"tensors.I2\",\n \"con.to_mandel6(tensors.I2)\",\n \"np.arange(9).reshape(3,3)\",\n \"con.to_mandel6(np.arange(9).reshape(3,3))\",\n \"tensors.I4s\",\n \"con.to_mandel6(tensors.I4s)\",\n \"con.to_mandel9(tensors.I4s)\",\n \"con.to_mandel9(tensors.I4s)\",\n ]\n for val in printQueue:\n print(val)\n print(eval(val), \"\\n\")\n\n # VoigtConverter\n\n import mechkit\n\n con = mechkit.notation.VoigtConverter()\n\n ones_2 = np.ones((3, 3),)\n ones_2_mandel = con.to_mandel6(ones_2)\n ones_4_mandel = con.to_mandel6(np.ones((3, 3, 3, 3),))\n\n printQueue = [\n \"ones_2\",\n \"ones_2_mandel\",\n \"con.mandel6_to_voigt(inp=ones_2_mandel, voigt_type='stress')\",\n \"con.mandel6_to_voigt(inp=ones_2_mandel, voigt_type='strain')\",\n \"ones_4_mandel\",\n \"con.mandel6_to_voigt(inp=ones_4_mandel, voigt_type='stiffness')\",\n \"con.mandel6_to_voigt(inp=ones_4_mandel, voigt_type='compliance')\",\n ]\n for val in printQueue:\n print(val)\n print(eval(val), \"\\n\")\n","sub_path":"mechkit/notation.py","file_name":"notation.py","file_ext":"py","file_size_in_byte":25587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"637975585","text":"#!/usr/bin/python\n\n\"\"\"\nUSAGE: init_paper \nCreates a new paper note with full metadata and downloads the pdf:\n* Uses the Crossref API to fetch paper metadata and abstract\n* Automatically download the pdf and saves it in standard naming convention\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\nimport os, sys\nimport string\nimport re\nimport requests\nimport json\nfrom datetime import date\nfrom collections import OrderedDict\nfrom metapub import CrossRef as cr\n\n#Depending on operating system\nif sys.platform == \"linux\" or sys.platform == \"linux2\":\n HOME_DIR = \"/home/potterzot\"\n REPO_DIR = \"reason/napnotes\"\nelif sys.platform == \"darwin\":\n # OS X\n pass\nelif sys.platform == \"win32\":\n # Windows...\n HOME_DIR = \"C:/Users/Nicholas Potter\"\n REPO_DIR = \"work/code/napnotes\"\n\n###Universal\nMD_DIR = \"papers\"\nPDF_DIR = \"Dropbox/personal-work/bibliography/library\"\n\ndef clean_txt(txt):\n \"\"\"Takes txt and returns a sanitized utf-8 string.\"\"\"\n r = txt.encode(\"utf-8\", errors=\"backslashreplace\").decode('utf-8').replace(\"\\\\u0144\", \"\")\n return r\n\ndef doi2json(doi):\n \"\"\"\n Takes a DOI string and returns a JSON string of metadata.\n \"\"\"\n if \"arxiv\" in doi:\n print(\"This script does not yet support arXiv.\")\n sys.exit(2)\n else:\n url = \"https://dx.doi.org/\" + doi\n\n headers = {\"accept\": \"application/json\"}\n r = requests.get(url, headers = headers)\n\n if repr(r)==\"\": #success!\n #handle potential encoding errors\n rtxt = clean_txt(r.text)\n try:\n j = json.loads(rtxt)\n except Exception as e:\n print(e)\n print(r)\n print(repr(rtxt))\n print(\"Error, DOI {} not found.\".format(doi))\n sys.exit(2)\n elif repr(r)==\"\":\n print(\"Error 503: DOI service currently unavailable, try again in a bit.\")\n sys.exit(2)\n elif repr(r)==\"\":\n print(\"Error 404: Resource {} not found\".format(url))\n sys.exit(2)\n else:\n print(\"Error {}.\".format(repr(r)))\n sys.exit(2)\n\n return j\n\n\ndef extract_metadata(res):\n \"\"\"Creates an OrderedDict of metadata for writing.\"\"\"\n d = OrderedDict()\n\n d['type'] = res['type']\n d['authors'] = \", \".join(make_author_list(res))\n d['title'] = res['title'].strip(\" \")\n d['container'] = res['container-title']\n d['year'] = str(get_year(res))\n d['issue'] = res['issue'] if \"issue\" in res.keys() else \"\"\n d['volume'] = res['volume'] if \"volume\" in res.keys() else \"\"\n d['pages'] = res['page'] if \"page\" in res.keys() else \"\"\n d['subject'] = make_subject(res)\n d['doi'] = res['DOI']\n d['url'] = res['URL']\n d['citationkey'] = make_citation_key(res)\n d['updated'] = date.today().strftime(\"%Y%m%d\")\n \n return d\n\ndef get_year(res):\n \"\"\"\n Takes the DOI result and returns a string of the year.\n \"\"\"\n return res['issued']['date-parts'][0][0]\n\n\ndef make_author_list(res):\n \"\"\"Takes a list of author names and returns a cleaned list of author names.\"\"\"\n try:\n r = [\" \".join([x['given'], x['family']]) for x in res['author']]\n except KeyError as e:\n print(\"No 'author' key, using 'Unknown Author'. You should edit the markdown file to change the name and citationkey.\")\n r = [\"Unknown Authors\"]\n return r \n\n\ndef make_citation_key(res):\n \"\"\"Takes a DOI query and returns a string citation key.\"\"\"\n year = str(get_year(res))\n\n try:\n last_names = [x['family'] for x in res['author']]\n except KeyError as e:\n last_names = [\"Unknown\"]\n if len(last_names) > 3:\n key = last_names[0] + \"ETAL\" + year\n else:\n key = \"\".join(last_names) + year\n\n return key.replace(\" \", \"\")\n\ndef make_subject(res):\n \"\"\"Takes the DOI metadata and returns a subject name.\"\"\"\n s = res['subject'] if \"subject\" in res.keys() else [\"Unsorted\"]\n return s\n\n\ndef main(argv):\n \"\"\"\n Takes a DOI and creates a markdown file with the article metadata, as well as attempting to download the pdf.\n \"\"\"\n \n #Get the metadata from crossref.org\n doi = argv[0]\n res = doi2json(doi)\n\n #extract\n meta = extract_metadata(res)\n \n ##write metadata to file\n subject_dir = re.sub(r'\\([^)]*\\)', '', meta['subject'][0]).strip().lower().replace(\" \", \"_\").replace(\",\",\"\")\n md_dir = \"/\".join([HOME_DIR, REPO_DIR, MD_DIR, subject_dir])\n os.mkdir(md_dir) if os.path.isdir(md_dir) == False else None\n\n #First check that the file doesn't exist, and if it does, increment the citationkey\n filename = \"/\".join([md_dir, meta['citationkey'] + \".md\"])\n tmp_citationkey = meta['citationkey']\n letters = list(string.ascii_lowercase)\n for j in range(0,26):\n if os.path.isfile(filename) == False:\n meta['citationkey'] = tmp_citationkey\n break\n tmp_citationkey = meta['citationkey'] + letters[j]\n filename = \"/\".join([md_dir, tmp_citationkey + \".md\"])\n\n #Then write\n with open(filename, \"w\") as f:\n f.write(\"---\\n\")\n for k,v in meta.items():\n v = \", \".join(v) if type(v) is list else v\n try:\n f.write(k + ': \"' + str(v) + '\"\\n')\n except UnicodeEncodeError as e:\n print(\"Unicode Error. Some character(s) may be wrong.\")\n print(meta.keys())\n print(repr(k) + \": \" + repr(v))\n print(e)\n\n f.write(\"---\\n\\n####Notes\\n\")\n\n #add the reference to the \"to_read.md\" list\n with open(\"/\".join([HOME_DIR, REPO_DIR, MD_DIR, \"reading_list.md\"]), \"a\") as f:\n f.write(\"* **\" + meta['citationkey'] + \"**: (\" + re.sub(r'\\([^)]*\\)', '', meta['subject'][0]).strip() + \") \" + meta['url'] + \"\\n\")\n\n print(\"reference {} added in {}!\\n\".format(meta['citationkey'], subject_dir))\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","sub_path":"papers/get_paper.py","file_name":"get_paper.py","file_ext":"py","file_size_in_byte":5522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"399705027","text":"\"\"\"\nExample of BN agent, dumping data into yaml file, with the environment ResourceGathering, specific precision and\nbinary dumps\n\"\"\"\nimport time\n\nimport utils.miscellaneous as um\nfrom agents.agent_bn import AgentBN\nfrom configurations.paths import dumps_path\nfrom environments import Environment, ResourceGatheringEpisodic\nfrom models import GraphType, Vector\n\n\ndef dumps(data: dict, environment: Environment, **kwargs):\n \"\"\"\n Dumps full_data given into dumps directory\n :param environment:\n :param data:\n :return:\n \"\"\"\n\n timestamp = int(time.time())\n\n # Get environment name in snake case\n environment = um.str_to_snake_case(environment.__class__.__name__)\n\n # Get only first letter of each word\n env_name_abbr = ''.join([word[0] for word in environment.split('_')])\n\n columns = kwargs.get('columns')\n\n if columns:\n # Specify full path\n file_path = dumps_path.joinpath(\n 'bn/train_data/{}_bn_{}_{}_{}.yml'.format(env_name_abbr, timestamp, Vector.decimal_precision, columns)\n )\n else:\n # Specify full path\n file_path = dumps_path.joinpath(\n 'bn/train_data/{}_bn_{}_{}.yml'.format(env_name_abbr, timestamp, Vector.decimal_precision)\n )\n\n # If any parents doesn't exist, make it.\n file_path.parent.mkdir(parents=True, exist_ok=True)\n\n with file_path.open(mode='w+', encoding='UTF-8') as f:\n f.write(um.structures_to_yaml(data=data))\n\n\ndef main():\n # Define gamma\n gamma = .9\n # Each 30 sweeps make it a dump\n sweeps_dumps = 30\n\n for decimal_precision in [0.01, 0.005]:\n # Set numbers of decimals allowed\n Vector.set_decimal_precision(decimal_precision=decimal_precision)\n\n # Define same tolerance that decimal precision, but is possible to change\n tolerance = decimal_precision\n\n # Create environment\n environment = ResourceGatheringEpisodic()\n\n # Create agent\n agent_bn = AgentBN(environment=environment, convergence_graph=False, gamma=gamma)\n\n # Time train\n t0 = time.time()\n\n print('Training with tolerance: {}...'.format(tolerance))\n\n agent_bn.train(graph_type=GraphType.SWEEP, tolerance=tolerance, sweeps_dump=sweeps_dumps)\n\n # Calc total time\n total_time = time.time() - t0\n\n # Convert to vectors\n vectors = {key: [vector.tolist() for vector in vectors] for key, vectors in agent_bn.v.items()}\n\n # Prepare full_data to dumps\n data = {\n 'time': '{}s'.format(total_time),\n 'memory': {\n 'v_s_0': len(agent_bn.v[environment.initial_state]),\n 'full': sum(len(vectors) for vectors in agent_bn.v.values())\n },\n 'vectors': vectors\n }\n\n # Configuration of environment\n environment_info = vars(environment).copy()\n environment_info.pop('_action_space', None)\n environment_info.pop('np_random', None)\n\n # Configuration of agent\n agent_info = {\n 'gamma': agent_bn.gamma,\n 'initial_q_value': agent_bn.initial_q_value,\n 'initial_seed': agent_bn.initial_seed,\n 'interval_to_get_data': agent_bn.interval_to_get_data,\n 'total_sweeps': agent_bn.total_sweeps,\n 'tolerance': tolerance\n }\n\n # Extra data\n data.update({'environment': environment_info})\n data.update({'agent': agent_info})\n\n # Dumps partial execution\n dumps(data=data, environment=environment)\n\n # Dump binary information\n agent_bn.save()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"extras/draft_bn.py","file_name":"draft_bn.py","file_ext":"py","file_size_in_byte":3636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"282311153","text":"import sys\n\nfrom PyQt5.QtGui import QBrush, QColor\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QTableWidget, QTableWidgetItem\n\n\nclass TableForm(QWidget):\n \"\"\"主窗口\"\"\"\n def __init__(self, parent=None):\n super().__init__(parent=parent)\n self.setWindowTitle(\"QTableWidget 表格快速定位\")\n self.resize(600, 800)\n \n # 初始化QTableWidget\n table_widget = QTableWidget()\n table_widget.setRowCount(30)\n table_widget.setColumnCount(4)\n \n for m in range(30):\n for n in range(4):\n item_content = \"(%d, %d)\" % (m , n)\n table_widget.setItem(m, n, QTableWidgetItem(item_content))\n \n h_layout = QHBoxLayout()\n h_layout.addWidget(table_widget)\n self.setLayout(h_layout)\n\n # 遍历表格查找对应项\n text = \"(10, 1)\"\n items = table_widget.findItems(text, Qt.MatchExactly)\n item = items[0]\n\n # 选中单元格\n item.setSelected(True)\n # 设置单元格的背景颜色\n item.setForeground(QBrush(QColor(255, 0, 0)))\n\n row = item.row()\n # 通过鼠标滚轮定位, 快速定位\n table_widget.verticalScrollBar().setSliderPosition(row)\n\n\nif __name__ == \"__main__\":\n\n app = QApplication(sys.argv)\n win = TableForm()\n win.show()\n sys.exit(app.exec())\n","sub_path":"03_高级界面控件/示例内容/01_3_QTableWidget表格中快速定位到行.py","file_name":"01_3_QTableWidget表格中快速定位到行.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"384640741","text":"from digital_library.database import Database\nfrom bson.objectid import ObjectId\nfrom datetime import datetime\nimport configparser\n\n\ndef load_config(header):\n\tconfig = configparser.ConfigParser()\n\tconfig.read('config')\n\treturn config[header]\n\n\ndef add_session(request, remember, user):\n\tconfig = load_config('Authorization')\n\tdb = Database(config['database_name'], ['sessions'])\n\tlast_session = db.sessions.get({\n\t\t'user': str(user),\n\t\t'ip': str(request.remote_addr),\n\t\t'browser': str(request.user_agent.browser),\n\t\t'version': str(request.user_agent.version and\n\t\tint(request.user_agent.version.split('.')[0])),\n\t\t'platform': str(request.user_agent.platform),\n\t\t'uas': str(request.user_agent.string),\n\t})\n\tif last_session is not None:\n\t\tif last_session['remember'] == remember:\n\t\t\treturn str(last_session['_id'])\n\t\tdb.sessions.update(last_session, {'remember': remember})\n\t\treturn str(last_session['_id'])\n\tsession = {\n\t\t'user': str(user),\n\t\t'datetime': datetime.utcnow(),\n\t\t'ip': str(request.remote_addr),\n\t\t'browser': str(request.user_agent.browser),\n\t\t'version': str(request.user_agent.version and\n\t\tint(request.user_agent.version.split('.')[0])),\n\t\t'platform': str(request.user_agent.platform),\n\t\t'uas': str(request.user_agent.string),\n\t\t'remember': remember,\n\t}\n\treturn str(db.sessions.insert(session))\n\n\ndef remove_session(id):\n\tconfig = load_config('Authorization')\n\tdb = Database(config['database_name'], ['sessions'])\n\tdb.sessions.remove({'_id': ObjectId('id')})\n\n\ndef session_user(id):\n\tconfig = load_config('Authorization')\n\tdb = Database(config['database_name'], ['sessions'])\n\ttry:\n\t\tsession = db.sessions.get({'_id': ObjectId(id)})\n\texcept:\n\t\treturn None\n\tif session is None:\n\t\treturn None\n\tif session['remember']:\n\t\tif (datetime.utcnow() - session['datetime']).seconds > int(config['remember']):\n\t\t\tsession = db.sessions.remove({'_id': ObjectId('id')})\n\t\t\treturn None\n\t\telse:\n\t\t\treturn session['user']\n\telse:\n\t\tif (datetime.utcnow() - session['datetime']).seconds > int(config['no_remember']):\n\t\t\tsession = db.sessions.remove({'_id': ObjectId('id')})\n\t\t\treturn None\n\t\telse:\n\t\t\treturn session['user']\n\n\ndef session_priority(id):\n\tconfig = load_config('Authorization')\n\tdb = Database(config['database_name'], ['users'])\n\tuser_id = session_user(id)\n\ttry:\n\t\tuser = db.users.get({'_id': ObjectId(user_id)})\n\texcept:\n\t\treturn None\n\tif user is None:\n\t\treturn None\n\treturn user.get('priority')\n","sub_path":"digital_library/sessions.py","file_name":"sessions.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"394670718","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nfrom django.conf import settings\n\n#JSON API\nfrom tastypie.api import Api\n#from world.api import WorldBorderResource\nfrom amatgeo.api import ( CartelloResource, CarraioResource, GeonoteResource, \n AreaSostaResource, AreaSostaEsternaResource,\n SostaBMResource, ARPubblicaResource, ARPrivataResource, CantiereResource,\n DomandaAbusivaResource, DomandaTollerataResource, \n DomandaAreaSostaResource, DomandaSostaBMResource, DomandaSostaEsternaResource)\n\nfrom amatgeo.resources import AuthorResource\n\nv1_api = Api(api_name='v1')\n#v1_api.register(WorldBorderResource())\nv1_api.register(AuthorResource())\n\n#v1_api.register(NumeroCivicoResource())\nv1_api.register(CartelloResource())\nv1_api.register(CarraioResource())\nv1_api.register(GeonoteResource())\nv1_api.register(AreaSostaResource())\nv1_api.register(ARPubblicaResource())\nv1_api.register(ARPrivataResource())\nv1_api.register(AreaSostaEsternaResource())\nv1_api.register(SostaBMResource())\nv1_api.register(CantiereResource())\nv1_api.register(DomandaAbusivaResource())\nv1_api.register(DomandaTollerataResource())\nv1_api.register(DomandaAreaSostaResource())\nv1_api.register(DomandaSostaBMResource())\nv1_api.register(DomandaSostaEsternaResource())\n\n\nfrom ui.views import debug\n\n\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'marcopolo.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^login/$', 'django.contrib.auth.views.login',{'template_name':'login.html'}, name=\"login\"),\n url(r'^ajax_login/$', 'ui.views.ajax_login', name=\"ajax_login\"),\n url(r'^logout/$', 'django.contrib.auth.views.logout',{'next_page': '/'}, name=\"logout\"),\n\n\n url(r'^geolocate/$', 'geolocation.views.geolocate', name=\"geolocate\"),\n\n url(r'^api/', include(v1_api.urls)),\n url(r'^adminsosta/', include(admin.site.urls)),\n url(r'^stats/', include('amatgeo.urls')),\n \n url(r'^', include('ui.urls')),\n\n)\n\n# And finally attach debug to urls (if settings is on)\nif settings.DEBUG:\n urlpatterns += patterns('',\n url(r'^debug/', debug),\n )\n\n","sub_path":"marcopolo/marcopolo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"247167477","text":"import pandas as pd\nimport plotly.offline as pyo\nimport plotly.graph_objs as go\n\n# Load CSSV file from Datasets folder\ndf = pd.read_csv('../Datasets/Weather2014-15.csv')\n\n# Extrapolating the actual max temp per month\nnew_df = df.groupby(['day', 'month'], sort=False).agg(\n {'record_max_temp': 'max'}).reset_index()\n#print(new_df)\n\n# Preparing data\ndata = [go.Heatmap(x=new_df['day'],\n y=new_df['month'],\n z=new_df['record_max_temp'].values.tolist(),\n colorscale='Jet')]\n\n# Preparing layout\nlayout = go.Layout(title='Recorded Max Temperature (F) On Days Of The Week From July 2014 to June 2015',\n xaxis_title=\"Day of Week\",\n yaxis_title=\"Week of Month\"\n )\n\n# Plot the figure and saving in a html file\nfig = go.Figure(data=data, layout=layout)\npyo.plot(fig, filename='WeatherHeatMap.html')","sub_path":"Plots/WeatherHeatMap.py","file_name":"WeatherHeatMap.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"88671822","text":"import re\nfrom bs4 import BeautifulSoup\nfrom decimal import Decimal\n\nfrom storescraper.product import Product\nfrom storescraper.store import Store\nfrom storescraper.utils import session_with_proxy, remove_words, \\\n html_to_markdown\n\n\nclass TodoJuegos(Store):\n @classmethod\n def categories(cls):\n return [\n 'VideoGameConsole',\n 'VideoGame',\n ]\n\n @classmethod\n def discover_urls_for_category(cls, category, extra_args=None):\n category_paths = [\n ['Productos/PS4/_consolas/', 'VideoGameConsole'],\n ['Productos/PSV/_consolas//', 'VideoGameConsole'],\n ['Productos/xone/_consolas/', 'VideoGameConsole'],\n ['Productos/3DS/_consolas/', 'VideoGameConsole'],\n ['Productos/NSWI/_consolas/', 'VideoGameConsole'],\n ]\n\n product_urls = []\n session = session_with_proxy(extra_args)\n\n for category_path, local_category in category_paths:\n if local_category != category:\n continue\n\n category_url = 'https://www.todojuegos.cl/' + category_path\n\n soup = BeautifulSoup(session.get(category_url).text, 'html.parser')\n\n link_containers = soup.findAll('div', 'foto_juego')\n\n if not link_containers:\n print('No products: ' + category_url)\n\n for link_container in link_containers:\n product_url = 'https:' + link_container.find('a')['href']\n product_urls.append(product_url)\n\n return product_urls\n\n @classmethod\n def products_for_url(cls, url, category=None, extra_args=None):\n session = session_with_proxy(extra_args)\n soup = BeautifulSoup(session.get(url).text, 'html.parser')\n\n picture_url = 'https:' + soup.find('div', 'productoEsp').find('img')[\n 'src']\n picture_urls = [picture_url]\n sku = re.search(r'/(\\d+)/', picture_url).groups()[0]\n\n name = soup.find('h1', 'titulo_juego').string\n\n add_to_cart_icon = soup.find('img', {'id': 'AgregarCarroImg'})\n\n if add_to_cart_icon:\n stock = -1\n else:\n stock = 0\n\n price_string = soup.find('h2', 'precio_juego').string.split('$')[1]\n price = Decimal(remove_words(price_string))\n\n description = ''\n\n for panel_class in ['infoDetalle', 'descripcionProducto']:\n description += html_to_markdown(\n str(soup.find('table', panel_class))) + '\\n\\n'\n\n p = Product(\n name,\n cls.__name__,\n category,\n url,\n url,\n sku,\n stock,\n price,\n price,\n 'CLP',\n sku=sku,\n description=description,\n picture_urls=picture_urls\n )\n\n return [p]\n","sub_path":"storescraper/stores/todo_juegos.py","file_name":"todo_juegos.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"211245365","text":"# -*- coding:utf-8 -*-\n\nimport tkinter\n\nwindow = tkinter.Tk()\nwindow.title('my window')\nwindow.geometry('200x200')\n# 很神奇,这里就是字母x\n# 窗口内容\n\non_hit = False\nnum = 0\n\n\ndef hit_me():\n global on_hit\n global num\n num += 1\n if on_hit is False:\n on_hit = True\n var.set('you hit me %d' % num)\n else:\n on_hit = False\n var.set(num)\n\n\n# hit_me如果放在后面就会导致b里面的command报错,这个很尴尬,我估计是和python解释有关,一行行解释导致找不到哦啊hit_me\n\nvar = tkinter.StringVar()\ni = tkinter.Label(window,\n # text='OMG!this is TK', # 标签文字\n textvariable=var, # 使用textvariable替换text,因为这可以变化\n bg='green', # 背景颜色\n font=('Arial', 12), # 字体\n width=15, height=2) # 标签长宽\ni.pack() # 固定窗口位置\n\nb = tkinter.Button(window,\n text='hit me', # 显示按钮文字\n width=15, height=2,\n command=hit_me) # 点击按钮执行的命令\nb.pack() # 按钮位置\n\nwindow.mainloop()\n","sub_path":"tkinter/tk01.py","file_name":"tk01.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"91499580","text":"from django.shortcuts import render\nfrom .forms import UserRegisterForm\nfrom django.contrib import messages\n\n\ndef register(request):\n if request.method == \"POST\":\n form = UserRegisterForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n messages.success(request, f\"Account successfully created for {username}\")\n else:\n form = UserRegisterForm()\n return render(request, \"register.html\", {'form': form})\n","sub_path":"friendly-frogs/friendly_frogs/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"371706393","text":"\nfrom django.shortcuts import render,redirect\nfrom django.http import HttpResponse,Http404\nfrom apps.portfolio.models import Profile,Employment,Projects,Technology_Category\nfrom apps.blog.models import About\nfrom django.conf import settings\nimport json\n# from ..errorMessage import getApiMsg\nimport re \n# Create your views here.\n\n\ndef portfolio_view(request):\n querySet = Projects.objects.all()\n formatedData = makeData(querySet)\n catTechSet = Technology_Category.objects.all()\n techList, otherTech = formatTechnology(catTechSet)\n\n educationSet = Profile.objects.first().educations_set.filter(is_school = 0)\n educationData = [{'short_name' : x.course_short_name,'full_name' :x.course_full_name,'start_year':x.start_year,'end_year':x.end_year} for x in educationSet]\n certificateSet = Profile.objects.first().certificates_set.all()\n certificateData = [{'name' : x.name,'short_name':x.short_name,'institute_short_name' : x.institute_short_name} for x in certificateSet]\n interestSet = Profile.objects.first().user_interest_set.all()\n intresteList = [ x.name for x in interestSet]\n\n aboutData = About.objects.first()\n context = {\n 'formatedData' :formatedData,\n 'techData':techList,\n 'otherTech' : otherTech,\n 'educationData' : educationData,\n 'certificateData' : certificateData,\n 'intresteList' : intresteList,\n 'aboutData' : aboutData\n \n }\n return render(request, 'portfolio/portfolio.html', context)\n \n\n\"\"\"\nformate data for templae so that we can easily retrieve it\n\"\"\"\ndef makeData(querySet):\n # Initialize dictionar and list\n employmentList = []\n projectList = []\n resultData = {}\n employmentData = {}\n\n for projects in querySet:\n # Employment Dictionary\n if not any(d['id'] == projects.employment.id for d in employmentList): # Check id in list of dictionary\n projectList = []\n projectData = {}\n # bind projects data\n projectData['id'] = projects.id\n projectData['name'] = projects.name\n projectData['team_size'] = projects.team_size\n projectData['description'] = projects.description\n projectData['role_responsibility'] = projects.role_responsibility\n #tempTechList = projects.technology.all().values('name')\n #techList = [x['name'] for x in tempTechList]\n tempTechList = projects.technology.all()\n techList = [{'name':x.name,'version':x.version} for x in tempTechList]\n projectData['technology'] = techList\n projectList.append(projectData)\n # Bind Employement data\n employmentData = {\n 'id' : projects.employment.id,\n 'employer': projects.employment.employer,\n 'position': projects.employment.position,\n 'summary': projects.employment.summary,\n 'start_date': projects.employment.start_date,\n 'end_date': projects.employment.end_date,\n 'is_current_org': projects.employment.is_current_org,\n 'projects': projectList,\n }\n employmentList.append(employmentData)\n else:\n ## Bind project data with its associate company.employement\n projectData = {}\n projectData['id'] = projects.id\n projectData['name'] = projects.name\n projectData['team_size'] = projects.team_size\n projectData['description'] = projects.description\n projectData['role_responsibility'] = projects.role_responsibility\n # tempTechList = projects.technology.all().values('name')\n # techList = [x['name'] for x in tempTechList]\n tempTechList = projects.technology.all()\n techList = [{'name':x.name,'version':x.version} for x in tempTechList]\n projectData['technology'] = techList\n projectList.append(projectData)\n \n for emp in employmentList:\n if emp['id'] == projects.employment.id:\n emp['projects'] = projectList # Append new project at appropreate index\n break\n resultData = {\n 'id' : projects.employment.profile.id,\n 'name' : projects.employment.profile.middle_name +\" \" + projects.employment.profile.last_name,\n 'profile_title' : projects.employment.profile.profile_title,\n 'email' : projects.employment.profile.email,\n 'mobile_number' : projects.employment.profile.mobile_number,\n 'brief_summary' : projects.employment.profile.brief_summary,\n 'employments' : employmentList,\n \n }\n\n \n return resultData\n\n\n# Formatting Technology data\ndef formatTechnology(catTechSet):\n catList = []\n otherTech = []\n for cat in catTechSet:\n if cat.name == 'Others':\n tempOther = cat.technologies_set.all()\n otherTech = [x.name for x in tempOther]\n else:\n techList = []\n catTemp = {'name' : cat.name}\n temp = cat.technologies_set.all()\n techList = [{'name' : x.name,'version':x.version,'rate':x.rate} for x in temp]\n catTemp = {cat.name : techList}\n catList.append(catTemp)\n\n return catList,otherTech\n\n\n\n\"\"\"\ncat = Technology_Category.objects.get(pk = 1)\ncat.technologies_set.all()\ncat1 = Technology_Category.objects.all();\nfor ct in cat1:\n ...: print(ct.technologies_set.all())\n\n\"\"\"","sub_path":"apps/portfolio/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"39736395","text":"# Copyright 2019 Atalaya Tech, Inc.\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport re\nimport inspect\nimport logging\nimport uuid\nfrom datetime import datetime\nfrom typing import List\n\nimport flask\nfrom werkzeug.utils import cached_property\n\nfrom bentoml import config\nfrom bentoml.saved_bundle import save_to_dir\nfrom bentoml.saved_bundle.config import SavedBundleConfig\nfrom bentoml.service_env import BentoServiceEnv\nfrom bentoml.utils import isidentifier\nfrom bentoml.utils.hybridmethod import hybridmethod\nfrom bentoml.exceptions import NotFound, InvalidArgument, BentoMLException\nfrom bentoml.server import trace\n\n\nARTIFACTS_DIR_NAME = \"artifacts\"\nDEFAULT_MAX_LATENCY = config(\"marshal_server\").getint(\"default_max_latency\")\nDEFAULT_MAX_BATCH_SIZE = config(\"marshal_server\").getint(\"default_max_batch_size\")\nBENTOML_RESERVED_API_NAMES = [\n \"index\",\n \"swagger\",\n \"docs\",\n \"healthz\",\n \"metrics\",\n \"feedback\",\n]\nlogger = logging.getLogger(__name__)\n\n\nclass InferenceAPI(object):\n \"\"\"\n InferenceAPI defines an inference call to the underlying model, including its input\n and output adapter, the user-defined API callback function, and configurations for\n working with the BentoML adaptive micro-batching mechanism\n \"\"\"\n\n def __init__(\n self, service, name, doc, handler, func, mb_max_latency, mb_max_batch_size\n ):\n \"\"\"\n :param service: ref to service containing this API\n :param name: API name\n :param doc: the user facing document of this inference API, default to the\n docstring of the inference API function\n :param handler: A InputAdapter that transforms HTTP Request and/or\n CLI options into parameters for API func\n :param func: the user-defined API callback function, this is\n typically the 'predict' method on a model\n :param mb_max_latency: The latency goal of this inference API in milliseconds.\n Default: 10000.\n :param mb_max_batch_size: The maximum size of requests batch accepted by this\n inference API. This parameter governs the throughput/latency trade off, and\n avoids having large batches that exceed some resource constraint (e.g. GPU\n memory to hold the entire batch's data). Default: 1000.\n\n \"\"\"\n self._service = service\n self._name = name\n self._handler = handler\n self._func = func\n self._wrapped_func = None\n self.mb_max_latency = mb_max_latency\n self.mb_max_batch_size = mb_max_batch_size\n\n if doc is None:\n # generate a default doc string for this inference API\n doc = (\n f\"BentoService inference API '{self.name}', input: \"\n f\"'{type(handler).__name__}', output: \"\n f\"'{type(handler.output_adapter).__name__}'\"\n )\n self._doc = doc\n\n @property\n def service(self):\n \"\"\"\n :return: a reference to the BentoService serving this inference API\n \"\"\"\n return self._service\n\n @property\n def name(self):\n \"\"\"\n :return: the name of this inference API\n \"\"\"\n return self._name\n\n @property\n def doc(self):\n \"\"\"\n :return: user facing documentation of this inference API\n \"\"\"\n return self._doc\n\n @property\n def handler(self):\n \"\"\"\n handler is a deprecated concept, we are moving it to the new input/output\n adapter interface. Currently this `handler` property returns the input adapter\n of this inference API\n \"\"\"\n return self._handler\n\n @property\n def output_adapter(self):\n \"\"\"\n :return: the output adapter of this inference API\n \"\"\"\n return self.handler.output_adapter\n\n @cached_property\n def func(self):\n \"\"\"\n :return: user-defined inference API callback function\n \"\"\"\n\n def func_with_tracing(*args, **kwargs):\n with trace(\n service_name=self.__class__.__name__,\n span_name=\"user defined inference api callback function\",\n ):\n return self._func(*args, **kwargs)\n\n return func_with_tracing\n\n @property\n def request_schema(self):\n \"\"\"\n :return: the HTTP API request schema in OpenAPI/Swagger format\n \"\"\"\n schema = self.handler.request_schema\n if schema.get('application/json'):\n schema.get('application/json')['example'] = self.handler._http_input_example\n return schema\n\n def handle_request(self, request: flask.Request):\n return self.handler.handle_request(request, self.func)\n\n def handle_batch_request(self, request: flask.Request):\n from bentoml.marshal.utils import DataLoader\n\n requests = DataLoader.split_requests(request.get_data())\n\n with trace(\n service_name=self.__class__.__name__,\n span_name=f\"call `{self.handler.__class__.__name__}`\",\n ):\n responses = self.handler.handle_batch_request(requests, self.func)\n\n return DataLoader.merge_responses(responses)\n\n def handle_cli(self, args):\n return self.handler.handle_cli(args, self.func)\n\n def handle_aws_lambda_event(self, event):\n return self.handler.handle_aws_lambda_event(event, self.func)\n\n\ndef validate_inference_api_name(api_name):\n if not isidentifier(api_name):\n raise InvalidArgument(\n \"Invalid API name: '{}', a valid identifier must contains only letters,\"\n \" numbers, underscores and not starting with a number.\".format(api_name)\n )\n\n if api_name in BENTOML_RESERVED_API_NAMES:\n raise InvalidArgument(\n \"Reserved API name: '{}' is reserved for infra endpoints\".format(api_name)\n )\n\n\ndef api_decorator(\n *args,\n input=None,\n output=None,\n api_name=None,\n api_doc=None,\n mb_max_batch_size=DEFAULT_MAX_BATCH_SIZE,\n mb_max_latency=DEFAULT_MAX_LATENCY,\n **kwargs,\n): # pylint: disable=redefined-builtin\n \"\"\"\n A decorator exposed as `bentoml.api` for defining Inference API in a BentoService\n class.\n\n :param input: InputAdapter instance of the inference API\n :param output: OutputAdapter instance of the inference API\n :param api_name: API name, default to the user-defined callback function's function\n name\n :param api_doc: user-facing documentation of the inference API. default to the\n user-defined callback function's docstring\n :param mb_max_batch_size: The maximum size of requests batch accepted by this\n inference API. This parameter governs the throughput/latency trade off, and\n avoids having large batches that exceed some resource constraint (e.g. GPU\n memory to hold the entire batch's data). Default: 1000.\n :param mb_max_latency: The latency goal of this inference API in milliseconds.\n Default: 10000.\n\n\n Example usage:\n\n >>> from bentoml import BentoService, api\n >>> from bentoml.adapters import JsonInput, DataframeInput\n >>>\n >>> class FraudDetectionAndIdentityService(BentoService):\n >>>\n >>> @api(input=JsonInput())\n >>> def fraud_detect(self, json_list):\n >>> # user-defined callback function that process inference requests\n >>>\n >>> @api(input=DataframeInput(input_json_orient='records'))\n >>> def identity(self, df):\n >>> # user-defined callback function that process inference requests\n\n\n Deprecated syntax before version 0.8.0:\n\n >>> from bentoml import BentoService, api\n >>> from bentoml.handlers import JsonHandler, DataframeHandler # deprecated\n >>>\n >>> class FraudDetectionAndIdentityService(BentoService):\n >>>\n >>> @api(JsonHandler) # deprecated\n >>> def fraud_detect(self, parsed_json):\n >>> # do something\n >>>\n >>> @api(DataframeHandler, input_json_orient='records') # deprecated\n >>> def identity(self, df):\n >>> # do something\n\n \"\"\"\n\n from bentoml.adapters import BaseInputAdapter\n\n def decorator(func):\n _api_name = func.__name__ if api_name is None else api_name\n validate_inference_api_name(_api_name)\n\n if input is None:\n # support bentoml<=0.7\n if not args or not (\n inspect.isclass(args[0]) and issubclass(args[0], BaseInputAdapter)\n ):\n raise InvalidArgument(\n \"BentoService @api decorator first parameter must \"\n \"be class derived from bentoml.adapters.BaseInputAdapter\"\n )\n\n handler = args[0](*args[1:], output_adapter=output, **kwargs)\n else:\n assert isinstance(input, BaseInputAdapter), (\n \"API input parameter must be an instance of any classes inherited from \"\n \"bentoml.adapters.BaseInputAdapter\"\n )\n handler = input\n handler._output_adapter = output\n\n setattr(func, \"_is_api\", True)\n setattr(func, \"_handler\", handler)\n setattr(func, \"_api_name\", _api_name)\n setattr(func, \"_api_doc\", api_doc)\n setattr(func, \"_mb_max_batch_size\", mb_max_batch_size)\n setattr(func, \"_mb_max_latency\", mb_max_latency)\n\n return func\n\n return decorator\n\n\ndef web_static_content_decorator(web_static_content):\n \"\"\"Define web UI static files required to be bundled with a BentoService\n\n Args:\n web_static_content: path to directory containg index.html and static dir\n\n >>> @web_static_content('./ui/')\n >>> class MyMLService(BentoService):\n >>> pass\n \"\"\"\n\n def decorator(bento_service_cls):\n bento_service_cls._web_static_content = web_static_content\n return bento_service_cls\n\n return decorator\n\n\ndef artifacts_decorator(artifacts):\n \"\"\"Define artifacts required to be bundled with a BentoService\n\n Args:\n artifacts (list(bentoml.artifact.BentoServiceArtifact)): A list of desired\n artifacts required by this BentoService\n \"\"\"\n from bentoml.artifact import BentoServiceArtifact\n\n def decorator(bento_service_cls):\n artifact_names = set()\n for artifact in artifacts:\n if not isinstance(artifact, BentoServiceArtifact):\n raise InvalidArgument(\n \"BentoService @artifacts decorator only accept list of type \"\n \"BentoServiceArtifact, instead got type: '%s'\" % type(artifact)\n )\n\n if artifact.name in artifact_names:\n raise InvalidArgument(\n \"Duplicated artifact name `%s` detected. Each artifact within one\"\n \"BentoService must have an unique name\" % artifact.name\n )\n\n artifact_names.add(artifact.name)\n\n bento_service_cls._artifacts = artifacts\n return bento_service_cls\n\n return decorator\n\n\ndef env_decorator(\n pip_dependencies: List[str] = None,\n auto_pip_dependencies: bool = False,\n requirements_txt_file: str = None,\n conda_channels: List[str] = None,\n conda_dependencies: List[str] = None,\n setup_sh: str = None,\n docker_base_image: str = None,\n):\n \"\"\"Define environment and dependencies required for the BentoService being created\n\n Args:\n pip_dependencies: list of pip_dependencies required, specified by package name\n or with specified version `{package_name}=={package_version}`\n auto_pip_dependencies: (Beta) whether to automatically find all the required\n pip dependencies and pin their version\n requirements_txt_file: pip dependencies in the form of a requirements.txt file,\n this can be a relative path to the requirements.txt file or the content\n of the file\n conda_channels: list of extra conda channels to be used\n conda_dependencies: list of conda dependencies required\n setup_sh: user defined setup bash script, it is executed in docker build time\n docker_base_image: used for customizing the docker container image built with\n BentoML saved bundle. Base image must either have both `bash` and `conda`\n installed; or have `bash`, `pip`, `python` installed, in which case the user\n is required to ensure the python version matches the BentoService bundle\n \"\"\"\n\n def decorator(bento_service_cls):\n bento_service_cls._env = BentoServiceEnv(\n bento_service_name=bento_service_cls.name(),\n pip_dependencies=pip_dependencies,\n auto_pip_dependencies=auto_pip_dependencies,\n requirements_txt_file=requirements_txt_file,\n conda_channels=conda_channels,\n conda_dependencies=conda_dependencies,\n setup_sh=setup_sh,\n docker_base_image=docker_base_image,\n )\n return bento_service_cls\n\n return decorator\n\n\ndef ver_decorator(major, minor):\n \"\"\"Decorator for specifying the version of a custom BentoService.\n\n Args:\n major (int): Major version number for Bento Service\n minor (int): Minor version number for Bento Service\n\n BentoML uses semantic versioning for BentoService distribution:\n\n * MAJOR is incremented when you make breaking API changes\n\n * MINOR is incremented when you add new functionality without breaking the\n existing API or functionality\n\n * PATCH is incremented when you make backwards-compatible bug fixes\n\n 'Patch' is provided(or auto generated) when calling BentoService#save,\n while 'Major' and 'Minor' can be defined with '@ver' decorator\n\n >>> @ver(major=1, minor=4)\n >>> @artifacts([PickleArtifact('model')])\n >>> class MyMLService(BentoService):\n >>> pass\n >>>\n >>> svc = MyMLService()\n >>> svc.pack(\"model\", trained_classifier)\n >>> svc.set_version(\"2019-08.iteration20\")\n >>> svc.save()\n >>> # The final produced BentoService bundle will have version:\n >>> # \"1.4.2019-08.iteration20\"\n \"\"\"\n\n def decorator(bento_service_cls):\n bento_service_cls._version_major = major\n bento_service_cls._version_minor = minor\n return bento_service_cls\n\n return decorator\n\n\ndef _validate_version_str(version_str):\n \"\"\"\n Validate that version str format is either a simple version string that:\n * Consist of only ALPHA / DIGIT / \"-\" / \".\" / \"_\"\n * Length between 1-128\n Or a valid semantic version https://github.com/semver/semver/blob/master/semver.md\n \"\"\"\n regex = r\"[A-Za-z0-9_.-]{1,128}\\Z\"\n semver_regex = r\"^(?P0|[1-9]\\d*)\\.(?P0|[1-9]\\d*)\\.(?P0|[1-9]\\d*)(?:-(?P(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+(?P[0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$\" # noqa: E501\n if (\n re.match(regex, version_str) is None\n and re.match(semver_regex, version_str) is None\n ):\n raise InvalidArgument(\n 'Invalid BentoService version: \"{}\", it can only consist'\n ' ALPHA / DIGIT / \"-\" / \".\" / \"_\", and must be less than'\n \"128 characthers\".format(version_str)\n )\n\n if version_str.lower() == \"latest\":\n raise InvalidArgument('BentoService version can not be set to \"latest\"')\n\n\ndef save(bento_service, base_path=None, version=None):\n \"\"\"\n Save and register the given BentoService via BentoML's built-in model management\n system. BentoML by default keeps track of all the SavedBundle's files and metadata\n in local file system under the $BENTOML_HOME(~/bentoml) directory. Users can also\n configure BentoML to save their BentoService to a shared Database and cloud object\n storage such as AWS S3.\n\n :param bento_service: target BentoService instance to be saved\n :param base_path: optional - override repository base path\n :param version: optional - save with version override\n :return: saved_path: file path to where the BentoService is saved\n \"\"\"\n\n from bentoml.yatai.client import YataiClient\n from bentoml.yatai.yatai_service import get_yatai_service\n\n if base_path:\n yatai_service = get_yatai_service(repo_base_url=base_path)\n yatai_client = YataiClient(yatai_service)\n else:\n yatai_client = YataiClient()\n\n return yatai_client.repository.upload(bento_service, version)\n\n\nclass BentoService:\n \"\"\"\n BentoService is the base component for building prediction services using BentoML.\n\n BentoService provide an abstraction for describing model artifacts and environment\n dependencies required for a prediction service. And allows users to create inference\n APIs that defines the inferencing logic and how the underlying model can be served.\n Each BentoService can contain multiple models and serve multiple inference APIs.\n\n Usage example:\n\n >>> from bentoml import BentoService, env, api, artifacts\n >>> from bentoml.adapters import DataframeInput\n >>> from bentoml.artifact import SklearnModelArtifact\n >>>\n >>> @artifacts([SklearnModelArtifact('clf')])\n >>> @env(pip_dependencies=[\"scikit-learn\"])\n >>> class MyMLService(BentoService):\n >>>\n >>> @api(input=DataframeInput())\n >>> def predict(self, df):\n >>> return self.artifacts.clf.predict(df)\n >>>\n >>> if __name__ == \"__main__\":\n >>> bento_service = MyMLService()\n >>> bento_service.pack('clf', trained_classifier_model)\n >>> bento_service.save_to_dir('/bentoml_bundles')\n \"\"\"\n\n # List of inference APIs that this BentoService provides\n _inference_apis = []\n\n # Name of this BentoService. It is default the class name of this BentoService class\n _bento_service_name = None\n\n # For BentoService loaded from saved bundle, this will be set to the path of bundle.\n # When user install BentoService bundle as a PyPI package, this will be set to the\n # installed site-package location of current python environment\n _bento_service_bundle_path = None\n\n # A list of artifacts required by this BentoService\n _artifacts = []\n\n # A `BentoServiceEnv` instance specifying the required dependencies and all system\n # environment setups\n _env = None\n\n # When loading BentoService from saved bundle, this will be set to the version of\n # the saved BentoService bundle\n _bento_service_bundle_version = None\n\n # See `ver_decorator` function above for more information\n _version_major = None\n _version_minor = None\n\n # See `web_static_content` function above for more\n _web_static_content = None\n\n def __init__(self):\n from bentoml.artifact import ArtifactCollection\n\n self._bento_service_version = self.__class__._bento_service_bundle_version\n self._packed_artifacts = ArtifactCollection()\n\n if self._bento_service_bundle_path:\n # load artifacts from saved BentoService bundle\n self._load_artifacts(self._bento_service_bundle_path)\n\n self._config_inference_apis()\n self._config_environments()\n\n def _config_environments(self):\n self._env = self.__class__._env or BentoServiceEnv(self.name)\n\n for api in self._inference_apis:\n self._env.add_pip_dependencies_if_missing(api.handler.pip_dependencies)\n self._env.add_pip_dependencies_if_missing(\n api.output_adapter.pip_dependencies\n )\n\n for artifact in self._artifacts:\n artifact.set_dependencies(self.env)\n\n def _config_inference_apis(self):\n self._inference_apis = []\n\n for _, function in inspect.getmembers(\n self.__class__,\n predicate=lambda x: inspect.isfunction(x) or inspect.ismethod(x),\n ):\n if hasattr(function, \"_is_api\"):\n api_name = getattr(function, \"_api_name\")\n api_doc = getattr(function, \"_api_doc\")\n handler = getattr(function, \"_handler\")\n mb_max_latency = getattr(function, \"_mb_max_latency\")\n mb_max_batch_size = getattr(function, \"_mb_max_batch_size\")\n\n # Bind api method call with self(BentoService instance)\n func = function.__get__(self)\n\n self._inference_apis.append(\n InferenceAPI(\n self,\n api_name,\n api_doc,\n handler=handler,\n func=func,\n mb_max_latency=mb_max_latency,\n mb_max_batch_size=mb_max_batch_size,\n )\n )\n\n @property\n def inference_apis(self):\n \"\"\"Return a list of user defined API functions\n\n Returns:\n list(InferenceAPI): List of Inference API objects\n \"\"\"\n return self._inference_apis\n\n def get_inference_api(self, api_name):\n \"\"\"Find the inference API in this BentoService with a specific name.\n\n When the api_name is None, this returns the first Inference API found in the\n `self.inference_apis` list.\n\n :param api_name: the target Inference API's name\n :return:\n \"\"\"\n if api_name:\n try:\n return next(\n (api for api in self.inference_apis if api.name == api_name)\n )\n except StopIteration:\n raise NotFound(\n \"Can't find API '{}' in service '{}'\".format(api_name, self.name)\n )\n elif len(self.inference_apis) > 0:\n return self.inference_apis[0]\n else:\n raise NotFound(f\"Can't find any inference API in service '{self.name}'\")\n\n @property\n def artifacts(self):\n \"\"\" Returns all packed artifacts in an ArtifactCollection object\n\n Returns:\n artifacts(ArtifactCollection): A dictionary of packed artifacts from the\n artifact name to the loaded artifact model instance in its native form\n \"\"\"\n return self._packed_artifacts\n\n @property\n def env(self):\n return self._env\n\n @property\n def web_static_content(self):\n return self._web_static_content\n\n def get_web_static_content_path(self):\n if not self.web_static_content:\n return None\n if self._bento_service_bundle_path:\n return os.path.join(\n self._bento_service_bundle_path, self.name, 'web_static_content',\n )\n else:\n return os.path.join(os.getcwd(), self.web_static_content)\n\n @hybridmethod\n @property\n def name(self):\n \"\"\"\n :return: BentoService name\n \"\"\"\n return self.__class__.name() # pylint: disable=no-value-for-parameter\n\n @name.classmethod\n def name(cls): # pylint: disable=no-self-argument,invalid-overridden-method\n \"\"\"\n :return: BentoService name\n \"\"\"\n if cls._bento_service_name is not None:\n if not isidentifier(cls._bento_service_name):\n raise InvalidArgument(\n 'BentoService#_bento_service_name must be valid python identifier'\n 'matching regex `(letter|\"_\")(letter|digit|\"_\")*`'\n )\n\n return cls._bento_service_name\n else:\n # Use python class name as service name\n return cls.__name__\n\n def set_version(self, version_str=None):\n \"\"\"Set the version of this BentoService instance. Once the version is set\n explicitly via `set_version`, the `self.versioneer` method will no longer be\n invoked when saving this BentoService.\n \"\"\"\n if version_str is None:\n version_str = self.versioneer()\n\n if self._version_major is not None and self._version_minor is not None:\n # BentoML uses semantic versioning for BentoService distribution\n # when user specified the MAJOR and MINOR version number along with\n # the BentoService class definition with '@ver' decorator.\n # The parameter version(or auto generated version) here will be used as\n # PATCH field in the final version:\n version_str = \".\".join(\n [str(self._version_major), str(self._version_minor), version_str]\n )\n\n _validate_version_str(version_str)\n\n if self.__class__._bento_service_bundle_version is not None:\n logger.warning(\n \"Overriding loaded BentoService(%s) version:%s to %s\",\n self.__class__._bento_service_bundle_path,\n self.__class__._bento_service_bundle_version,\n version_str,\n )\n self.__class__._bento_service_bundle_version = None\n\n if (\n self._bento_service_version is not None\n and self._bento_service_version != version_str\n ):\n logger.warning(\n \"Resetting BentoService '%s' version from %s to %s\",\n self.name,\n self._bento_service_version,\n version_str,\n )\n\n self._bento_service_version = version_str\n return self._bento_service_version\n\n def versioneer(self):\n \"\"\"\n Function used to generate a new version string when saving a new BentoService\n bundle. User can also override this function to get a customized version format\n \"\"\"\n datetime_string = datetime.now().strftime(\"%Y%m%d%H%M%S\")\n random_hash = uuid.uuid4().hex[:6].upper()\n\n # Example output: '20191009135240_D246ED'\n return datetime_string + \"_\" + random_hash\n\n @property\n def version(self):\n \"\"\"\n Return the version of this BentoService. If the version of this BentoService has\n not been set explicitly via `self.set_version`, a new version will be generated\n with the `self.versioneer` method. User can customize this version str either by\n setting the version with `self.set_version` before a `save` call, or override\n the `self.versioneer` method to customize the version str generator logic.\n\n For BentoService loaded from a saved bundle, this will simply return the version\n information found in the saved bundle.\n\n :return: BentoService version str\n \"\"\"\n if self.__class__._bento_service_bundle_version is not None:\n return self.__class__._bento_service_bundle_version\n\n if self._bento_service_version is None:\n self.set_version(self.versioneer())\n\n return self._bento_service_version\n\n def save(self, base_path=None, version=None):\n \"\"\"\n Save and register this BentoService via BentoML's built-in model management\n system. BentoML by default keeps track of all the SavedBundle's files and\n metadata in local file system under the $BENTOML_HOME(~/bentoml) directory.\n Users can also configure BentoML to save their BentoService to a shared Database\n and cloud object storage such as AWS S3.\n\n :param base_path: optional - override repository base path\n :param version: optional - save with version override\n :return: saved_path: file path to where the BentoService is saved\n \"\"\"\n return save(self, base_path, version)\n\n def save_to_dir(self, path, version=None):\n \"\"\"Save this BentoService along with all its artifacts, source code and\n dependencies to target file path, assuming path exist and empty. If target path\n is not empty, this call may override existing files in the given path.\n\n :param path (str): Destination of where the bento service will be saved\n :param version: optional - save with version override\n \"\"\"\n return save_to_dir(self, path, version)\n\n @hybridmethod\n def pack(self, name, *args, **kwargs):\n \"\"\"\n BentoService#pack method is used for packing trained model instances with a\n BentoService instance and make it ready for BentoService#save.\n\n pack(name, *args, **kwargs):\n\n :param name: name of the declared model artifact\n :param args: args passing to the target model artifact to be packed\n :param kwargs: kwargs passing to the target model artifact to be packed\n :return: this BentoService instance\n \"\"\"\n if name in self.artifacts:\n logger.warning(\n \"BentoService '%s' #pack overriding existing artifact '%s'\",\n self.name,\n name,\n )\n del self.artifacts[name]\n\n artifact = next(\n artifact for artifact in self._artifacts if artifact.name == name\n )\n packed_artifact = artifact.pack(*args, **kwargs)\n self._packed_artifacts.add(packed_artifact)\n return self\n\n @pack.classmethod\n def pack(cls, *args, **kwargs): # pylint: disable=no-self-argument\n \"\"\"\n **Deprecated**: Legacy `BentoService#pack` class method, no longer supported\n \"\"\"\n raise BentoMLException(\n \"BentoService#pack class method is deprecated, use instance method `pack` \"\n \"instead. e.g.: svc = MyBentoService(); svc.pack('model', model_object)\"\n )\n\n def _load_artifacts(self, path):\n # For pip installed BentoService, artifacts directory is located at\n # 'package_path/artifacts/', but for loading from bundle directory, it is\n # in 'path/{service_name}/artifacts/'\n if not os.path.isdir(os.path.join(path, ARTIFACTS_DIR_NAME)):\n artifacts_path = os.path.join(path, self.name, ARTIFACTS_DIR_NAME)\n else:\n artifacts_path = os.path.join(path, ARTIFACTS_DIR_NAME)\n\n for artifact in self._artifacts:\n packed_artifact = artifact.load(artifacts_path)\n self._packed_artifacts.add(packed_artifact)\n\n def get_bento_service_metadata_pb(self):\n return SavedBundleConfig(self).get_bento_service_metadata_pb()\n","sub_path":"bentoml/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":30546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"583824612","text":"from random import random\n# randrange used for randomly selecting elements to add to fold\nfrom random import randrange\n# csv used to read and import data\nfrom csv import reader\n# math used for functions like exponentials\nfrom math import exp\n# numpy used for linear algebra functions and some data handling\nimport numpy\n# sys used to accept command line arguments to the program\nimport sys\n# statistics and mean used to calculate averages\nfrom statistics import mean\n\n\n################# DATA HANDLING LIBRARY #################\n\n# This functions handles the raw data and returns a dataset ready to be used\ndef handle_data(file):\n # Load the csv file into an array\n data = csv_to_array(file)\n # Format the csv file (changing types)\n dataset = format_data(data)\n # Normalize the data as needed\n normalize_data(dataset)\n\n # Return the type formatted and randomized dataset\n return dataset\n\n\n# This function normalizes the data for use in the backprop algorithm\ndef normalize_data(dataset):\n # Determine the minimum and maximum and store them in an array\n minimum_maximum = [[min(column), max(column)] for column in zip(*dataset)]\n # Loop through the dataset\n for row in dataset:\n # Normalize every column except for the last (classifications) column\n for i in range(len(row) - 1):\n # Perform normalization\n row[i] = (row[i] - minimum_maximum[i][0]) / (minimum_maximum[i][1] - minimum_maximum[i][0])\n\n\n# This function formats the dataset into the correct type values\ndef format_data(dataset):\n # Create a temporary version of the dataset passed in\n temp = dataset\n # Determine the number of columns\n num_cols = len(temp[0]) - 1\n # Loop through the columns\n for col in range(num_cols):\n # Convert them to floats\n convert_to_float(temp, col)\n\n # Convert the classifications column to ints\n convert_to_int(temp, num_cols)\n\n # Return the array\n return temp\n\n# This function attempts to turn a csv into an array\ndef csv_to_array(filename):\n # Create a blank array in which we will hold the data\n dataset = []\n # Open the file\n with open(filename, 'r') as file:\n # Use csv library to read the file\n csv_reader = reader(file)\n # Loop through the reader and append the row to the array we created earlier\n for row in csv_reader:\n if not row:\n continue\n dataset.append(row)\n\n # Return the dataset\n return dataset\n\n\n# This function converts objects in a column to floats\ndef convert_to_float(dataset, column):\n # Loop through the dataset\n for row in dataset:\n # Convert all items in that column to floats\n row[column] = float(row[column])\n\n # NOTE - Used to avoid needing to convert everything and then reconvert the classification column\n\n# This function converts objects in a column to ints\ndef convert_to_int(dataset, column):\n # Create an array of the class values\n class_values = [row[column] for row in dataset]\n # Determine a set of unique classes\n unique_classes = set(class_values)\n # Create an index (a dict structure)\n index = dict()\n # Loop through the unique classes\n for iterator, item in enumerate(unique_classes):\n # Set the index of the class to be equal to the index in the dictionary\n index[item] = iterator\n # Now loop through the dataset\n for row in dataset:\n # Set the column of that row to be the value in the lookup dictionary\n row[column] = index[row[column]]\n\n # Return the dictionary we created\n return index\n\n# Split a dataset into k folds\ndef create_k_folds(dataset, k):\n # Create the empty folds array\n folds = []\n # Createa copy of the dataset\n copy = dataset\n # Determine the number of elements to use for each fold\n num_ele = int(len(copy) / k)\n\n # Loop through k times\n for index in range(k):\n # Create a temp array for the current fold\n currFold = []\n # While the current fold does not have the proper amount of elements\n while len(currFold) < num_ele:\n # Create a random index using the randrange from the random library\n item = randrange(len(copy))\n # Append that item to the current fold by popping it out of the dataset\n currFold.append(copy.pop(item))\n # Append the current fold to the folds array\n folds.append(currFold)\n\n # Return the folds array\n return folds\n\n# Calculate accuracy percentage\ndef get_backprop_accuracy(testing_classes, predictions):\n # Set a variable to collect the # of correct guesses\n num_correct = 0\n # Loop through each of the actual values\n for index in range(len(testing_classes)):\n # If the actual value is the same as your prediction / guess\n if (testing_classes[index] == predictions[index]):\n # Increase the number of correct\n num_correct = num_correct + 1\n # Otherwise\n else:\n # Continue on\n continue\n\n # Return a float of the num correct / total values\n return float((num_correct / len(testing_classes)) * 100)\n\n# Evaluate an algorithm using a cross validation split\ndef run_backprop(dataset, k, learning_rate, epochs, hidden_nodes):\n folds = create_k_folds(dataset, k)\n scores = []\n for fold in folds:\n train_set = list(folds)\n train_set.remove(fold)\n train_set = sum(train_set, [])\n test_set = []\n for row in fold:\n row_copy = list(row)\n test_set.append(row_copy)\n row_copy[-1] = None\n predicted = back_propagation(train_set, test_set, learning_rate, epochs, hidden_nodes)\n actual = [row[-1] for row in fold]\n accuracy = get_backprop_accuracy(actual, predicted)\n scores.append(accuracy)\n\n return float(mean(scores))\n\ndef tune_backprop(dataset, k):\n learning_rate = 0\n epochs = 0\n hidden_nodes = 0\n\n best_accuracy = 0\n best_learning_rate = 0\n best_epoch = 0\n best_hidden_nodes = 0\n\n for _ in range(6):\n learning_rate = learning_rate + .05\n epochs = epochs + 100\n hidden_nodes = hidden_nodes + 1\n\n print(learning_rate)\n print(epochs)\n print(hidden_nodes)\n\n currAccuracy = run_backprop(dataset, k, learning_rate, epochs, hidden_nodes)\n\n if (currAccuracy > best_accuracy):\n best_accuracy = currAccuracy\n best_learning_rate = learning_rate\n best_epoch = epochs\n best_hidden_nodes = hidden_nodes\n\n return best_accuracy, best_learning_rate, best_epoch, best_hidden_nodes\n\n\n\n\n\n \n\n\n# Calculate neuron activation for an input\ndef activate(weights, inputs):\n activation = weights[-1]\n for i in range(len(weights) - 1):\n activation += weights[i] * inputs[i]\n return activation\n\n\n# Transfer neuron activation\ndef transfer(activation):\n return 1.0 / (1.0 + exp(-activation))\n\n\n# Forward propagate input to a network output\ndef forward_propagate(network, row):\n inputs = row\n for layer in network:\n new_inputs = []\n for neuron in layer:\n activation = activate(neuron['weights'], inputs)\n neuron['output'] = transfer(activation)\n new_inputs.append(neuron['output'])\n inputs = new_inputs\n return inputs\n\n\n# Calculate the derivative of an neuron output\ndef transfer_derivative(output):\n return output * (1.0 - output)\n\n\n# Backpropagate error and store in neurons\ndef backward_propagate_error(network, expected):\n for i in reversed(range(len(network))):\n layer = network[i]\n errors = []\n if i != len(network) - 1:\n for j in range(len(layer)):\n error = 0.0\n for neuron in network[i + 1]:\n error += (neuron['weights'][j] * neuron['delta'])\n errors.append(error)\n else:\n for j in range(len(layer)):\n neuron = layer[j]\n errors.append(expected[j] - neuron['output'])\n for j in range(len(layer)):\n neuron = layer[j]\n neuron['delta'] = errors[j] * transfer_derivative(neuron['output'])\n\n\n# Update network weights with error\ndef update_weights(network, row, learning_rate):\n for i in range(len(network)):\n inputs = row[:-1]\n if i != 0:\n inputs = [neuron['output'] for neuron in network[i - 1]]\n for neuron in network[i]:\n for j in range(len(inputs)):\n neuron['weights'][j] += learning_rate * neuron['delta'] * inputs[j]\n neuron['weights'][-1] += learning_rate * neuron['delta']\n\n\n# Train a network for a fixed number of epochs\ndef train_network(network, train, learning_rate, epochs, n_outputs):\n for epoch in range(epochs):\n for row in train:\n outputs = forward_propagate(network, row)\n expected = [0 for i in range(n_outputs)]\n expected[row[-1]] = 1\n backward_propagate_error(network, expected)\n update_weights(network, row, learning_rate)\n\n\n# Initialize a network\ndef initialize_network(n_inputs, hidden_nodes, n_outputs):\n network = []\n hidden_layer = [{'weights': [random() for i in range(n_inputs + 1)]} for i in range(hidden_nodes)]\n network.append(hidden_layer)\n output_layer = [{'weights': [random() for i in range(hidden_nodes + 1)]} for i in range(n_outputs)]\n network.append(output_layer)\n return network\n\n\n# Make a prediction with a network\ndef predict(network, row):\n outputs = forward_propagate(network, row)\n return outputs.index(max(outputs))\n\n\n# Backpropagation Algorithm With Stochastic Gradient Descent\ndef back_propagation(train, test, learning_rate, epochs, hidden_nodes):\n n_inputs = len(train[0]) - 1\n n_outputs = len(set([row[-1] for row in train]))\n network = initialize_network(n_inputs, hidden_nodes, n_outputs)\n train_network(network, train, learning_rate, epochs, n_outputs)\n predictions = []\n for row in test:\n prediction = predict(network, row)\n predictions.append(prediction)\n return (predictions)\n\n\ndef main():\n dataset = handle_data('iris.data')\n\n best_accuracy, best_learning_rate, best_epoch, best_hidden_nodes = tune_backprop(dataset, 5)\n print(\"Best Accuracy: \", best_accuracy)\n print(\"Best Learning Rate: \", best_learning_rate)\n print(\"Best epochs: \", best_epoch)\n print(\"Best Hidden Nodes: \", best_hidden_nodes)\n\nmain()\n","sub_path":"new_wip.py","file_name":"new_wip.py","file_ext":"py","file_size_in_byte":10499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"139848333","text":"import sys\n\nclass Evaluator:\n def __getattr__(self, name):\n return gdb.parse_and_eval(name)\nvals = Evaluator()\n\ndef gdbFunction(f):\n class GdbFunction(gdb.Function):\n def __init__(self):\n self.__doc__ = f.__doc__\n super(GdbFunction, self).__init__(f.__name__)\n\n def invoke(self, *args):\n return f(*args)\n\n GdbFunction()\n return f\n\nbtree_t = gdb.lookup_type('WT_BTREE').pointer()\nconn_impl_t = gdb.lookup_type('WT_CONNECTION_IMPL').pointer()\n\n@gdbFunction\ndef s2bt(s):\n '''Get the btree of a session'''\n return s['dhandle']['handle'].cast(btree_t)\n\n@gdbFunction\ndef s2c(s):\n '''Get the connection of a session'''\n return s['iface']['connection'].cast(conn_impl_t)\n\n@gdbFunction\ndef s2cache(s):\n '''Get the cache of a session'''\n return s['iface']['connection'].cast(conn_impl_t)['cache']\n\n@gdbFunction\ndef bytes_inuse(cache):\n '''Get the bytes in use for a cache'''\n return cache['bytes_inmem'] - cache['bytes_evict']\n\n@gdbFunction\ndef pgdepth(p):\n '''Get the depth of a page under the root'''\n d = 0\n while p:\n p = p['parent']\n d += 1\n return d\n\n@gdbFunction\ndef pgup(p, n=1):\n '''Go to an ancestor of a page (default the direct parent)'''\n while p and n:\n p = p['parent']\n n -= 1\n return p\n\n# Use builtin values where possible\ntry:\n pgtypes = { \n int(vals.WT_PAGE_INVALID) : \"invalid\",\n int(vals.WT_PAGE_BLOCK_MANAGER) : \"block mgr\",\n int(vals.WT_PAGE_COL_FIX) : \"leaf fixed\",\n int(vals.WT_PAGE_COL_INT) : \"int col\",\n int(vals.WT_PAGE_COL_VAR) : \"leaf var\",\n int(vals.WT_PAGE_OVFL) : \"overflow\",\n int(vals.WT_PAGE_ROW_INT) : \"int row\",\n int(vals.WT_PAGE_ROW_LEAF) : \"leaf row\",\n }\n\n pmflags = {\n int(vals.WT_PM_REC_EMPTY) : \"empty\",\n int(vals.WT_PM_REC_REPLACE) : \"replace\",\n int(vals.WT_PM_REC_SPLIT) : \"split\",\n int(vals.WT_PM_REC_SPLIT_MERGE) : \"split-merge\",\n }\n\n refstates = {\n int(vals.WT_REF_DISK) : \"disk\",\n int(vals.WT_REF_DELETED) : \"deleted\",\n int(vals.WT_REF_EVICT_FORCE) : \"evict force\",\n int(vals.WT_REF_EVICT_WALK) : \"evict walk\",\n int(vals.WT_REF_LOCKED) : \"locked\",\n int(vals.WT_REF_MEM) : \"mem\",\n int(vals.WT_REF_READING) : \"reading\",\n }\nexcept:\n pgtypes = { \n 0 : \"invalid\",\n 1 : \"block mgr\",\n 2 : \"leaf fixed\",\n 3 : \"int col\",\n 4 : \"leaf var\",\n 5 : \"overflow\",\n 6 : \"int row\",\n 7 : \"leaf row\",\n }\n\n pmflags = {\n 1 : \"empty\",\n 2 : \"replace\",\n 4 : \"split\",\n 8 : \"split-merge\",\n }\n\n refstates = {\n 0 : \"disk\",\n 1 : \"deleted\",\n 2 : \"evict force\",\n 3 : \"evict walk\",\n 4 : \"locked\",\n 5 : \"mem\",\n 6 : \"reading\",\n }\n\n@gdbFunction\ndef pgprint(p, prefix=''):\n '''Pretty print a page'''\n moddesc = ''\n mod = p['modify']\n ref = p['ref']\n if mod:\n flags = int(mod['flags'])\n if flags:\n moddesc = ' (mod %s)' % (', '.join(pmflags[1<= \" + date_from + \" AND post_date <= \" + date_to\n print(search)\n sql.execute(search)\n conn.commit()\n for row in sql.fetchall():\n date.append(row[1])\n title.append(row[2])\n article.append(row[3])\n news_link.append(row[4])\n new_event_bool.append(row[5])\n\n sql.close()\n conn.close()\n print(len(title))\n\n\n# eliminate same string\n# news_link = list(set(news_link))\n# article = list(set(article))\n# title = list(set(title))\n\n\ndef tf(word, count):\n return count[word] / sum(count.values())\n\n\ndef n_containing(word, count_list):\n return sum(1 for count in count_list if word in count)\n\n\ndef idf(word, count_list):\n return math.log(len(count_list) / (1 + n_containing(word, count_list)))\n\n\ndef tfidf(word, count, count_list):\n return tf(word, count) * idf(word, count_list)\n\n\ndef stem_tokens(tokens, stemmer):\n stemmed = []\n for item in tokens:\n stemmed.append(stemmer.stem(item))\n return stemmed\n\n\n# turn string into single word\ndef get_tokens(article):\n punctuation_custom = r\"\"\"!\"~#$%&'()*+,./:;<=>?@[\\]^_`‘’{|}“”\"\"\"\n remove_punctuation_map = dict((ord(char), ' ') for char in punctuation_custom)\n no_punctuation = article.translate(remove_punctuation_map)\n tokens = no_punctuation.split()\n # tokens = nltk.word_tokenize(no_punctuation)\n return tokens\n\n\n# count total words in corpus, with removal of stopwords\ndef count_term(stopword, article):\n global caps\n temp_caps = []\n tokens = get_tokens(article)\n filtered = []\n\n for token in tokens:\n # remove numeric word\n pattern = '\\d+$'\n match = re.match(pattern, token)\n if match:\n continue\n lower_word = token.lower()\n if lower_word not in stopword:\n filtered.append(lower_word)\n if token[0].isupper():\n temp_caps.append(token)\n\n caps.append(temp_caps)\n\n # lemma = nltk.wordnet.WordNetLemmatizer()\n # for index, x in enumerate(filtered):\n # x = lemma.lemmatize(x)\n # filtered[index] = x\n\n count = Counter(filtered)\n return count\n\n\ndef output_article_word_list():\n global article\n global title\n global merge\n global caps\n\n article = list(map(lambda s: s.strip(), article))\n title = list(map(lambda s: s.strip(), title))\n\n # article = list(map(lambda s: s.replace('\\n',''), article))\n\n for index, x in enumerate(article):\n x = x.replace('\\n', '')\n article[index] = x\n\n countlist = []\n\n # f = open('/home/fang/downloads/thesis_system_191125/nltk_stopwords', encoding='utf8')\n\n f = open('/home/fang/downloads/thesis_system_191125/stop_word', encoding='utf8')\n\n stopword = f.readlines()\n f.close()\n\n stopword = list(map(lambda s: s.strip(), stopword))\n\n for x in article:\n countlist.append(count_term(stopword, x))\n\n # remove duplicate\n for index, x in enumerate(caps):\n caps[index] = list(set(caps[index]))\n\n # a_list store TF-IDF keyword\n a_list = []\n merge = []\n all_caps = []\n\n for i, count in enumerate(countlist):\n temp = []\n print(\"Top words in document {}\".format(i + 1))\n scores = {word: tfidf(word, count, countlist) for word in count}\n sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True)\n for word, score in sorted_words[:int(len(count) / 2)]:\n temp.append(word)\n print(\"\\tWord: {}, TF-IDF: {}\".format(word, round(score, 10)))\n a_list.append(temp)\n\n for x in range(len(a_list)):\n temp_merge = []\n all_caps += caps[x]\n lower = list(map(lambda s: s.lower(), caps[x]))\n # for i in lower:\n # if i in a_list[x]:\n # a_list[x].remove(i)\n # temp_merge = caps[x] + a_list[x]\n temp_merge = lower + a_list[x]\n temp_merge = list(set(temp_merge))\n # print(temp_merge)\n merge.append(temp_merge)\n\n all_caps = list(set(all_caps))\n\n for x in merge:\n for y in all_caps:\n y_low = y.lower()\n if (y_low in x):\n x.remove(y_low)\n x.append(y)\n\n pprint(merge)\n\n\ndef build_dictionary_temp():\n global dictionary\n global corpus\n global merge\n dictionary = corpora.Dictionary(merge)\n dictionary.save('/tmp/news_word.dict') # store the dictionary, for future reference\n print(dictionary)\n dictionary = corpora.Dictionary.load('/tmp/news_word.dict')\n corpus = [dictionary.doc2bow(text) for text in merge]\n corpora.MmCorpus.serialize('/tmp/news_word.mm', corpus)\n # store to disk, for later use\n\n # print(dictionary.token2id)\n\n\ndef k_means():\n global recommendation\n print(\"k-means_result\")\n\n top_news = list()\n\n for index, x in enumerate(all_topics):\n if index in top_3_topic:\n top_news.append(all_topics[index])\n\n # k-means_with top n topics\n for index, n in enumerate(top_news):\n news_list = []\n ti = []\n for k in n:\n news_list.append(k[1])\n ti.append(k[0])\n print(k[3])\n print(k[0])\n print(k[2])\n\n vectorizer = TfidfVectorizer(stop_words='english')\n news = vectorizer.fit_transform(news_list)\n\n true_k = 3\n model = KMeans(n_clusters=true_k, init='k-means++', max_iter=100, n_init=1)\n model.fit(news)\n\n prediction = model.fit_predict(news)\n scores = model.transform(news)\n print(prediction)\n # print(scores)\n\n for index2, k in enumerate(n):\n # news_list.append(k[1])\n # ti.append(k[0])\n print(k[3])\n print(k[0])\n print(k[2])\n print(prediction[index2])\n print(min(scores[index2]))\n p1 = prediction[index2]\n s1 = (min(scores[index2]))\n l = list(prediction)\n cont = l.count(index2)\n cont2 = 1\n for index3, k2 in enumerate(n):\n p2 = prediction[index3]\n s2 = (min(scores[index3]))\n if p1 == p2:\n if s1 == s2:\n news = str(k[3]) + \"
\" + str(k[0]) + \"
\" + str(k[2]) + \"
\" + \"
\"\n if s1 < s2:\n news = str(k[3]) + \"
\" + str(k[0]) + \"
\" + str(k[2]) + \"
\" + \"
\"\n cont2 = cont2 + 1\n if s1 > s2:\n cont2 = cont2 + 1\n\n if cont2 == cont:\n recommendation.append(news)\n\n recommendation = list(set(recommendation))\n all_topics.clear()\n\n\n\n\ndef recommended_news():\n global recommendation\n\n print(\"recommendation\")\n\n for index, x in enumerate(all_topics):\n count = 0\n if index in top_3_topic:\n for i in all_topics[index]:\n print('\\n' + 'topic ' + str(index))\n\n print(i[3])\n print(i[0])\n print(i[2])\n count = count + 1\n news = str(i[3]) + \"
\" + str(i[0]) + \"
\" + str(i[2]) + \"
\" + \"
\"\n # recommendation.append(i[3])\n # recommendation.append(i[0])\n # recommendation.append(i[2])\n recommendation.append(news)\n\n if count == 3:\n break\n all_topics.clear()\n\n\ndef flask_web():\n app = Flask(__name__)\n\n @app.route('/', methods=['GET', 'POST'])\n def result():\n global recommendation\n global date_selected\n global topics\n global historic\n global current\n\n date_selected = request.args.get('date')\n topics = request.args.get('topics')\n historic = request.args.get('historic weeks')\n current = request.args.get('current week')\n\n if date_selected is not None:\n recommendation.clear()\n d = datetime.strptime(date_selected, \"%Y-%m-%d\").date()\n history_d = d - timedelta(days=4)\n weekstart = d - timedelta(days=4)\n # collect_db_news(str(history_d), str(weekstart))\n collect_db_news(str(weekstart), str(date_selected))\n output_article_word_list()\n build_dictionary_temp()\n save_longtime_dictionary()\n build_old_lda_model()\n # old_news()\n\n collect_db_news(str(weekstart), str(date_selected))\n output_article_word_list()\n build_dictionary_temp()\n build_new_lda_model()\n\n load_lda_model()\n jsd_distance()\n topic_document()\n k_means()\n\n # recommended_news()\n print(recommendation)\n\n check = request.args.getlist('check')\n output = recommendation\n\n print(check)\n print(recommendation)\n\n with open('selected.txt', 'a') as the_file:\n the_file.write(str(recommendation) + \"\\n\" + str(check) + \"\\n\")\n\n return render_template(\"index.html\", output=output)\n\n return render_template(\"index.html\")\n\n app.run('localhost', 8000)\n\n\nflask_web()\n\n","sub_path":"NED_model_main.py","file_name":"NED_model_main.py","file_ext":"py","file_size_in_byte":11151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"329973412","text":"from possibleMoves.possibleMoves import *\r\nimport time\r\nfrom utility import unhashableDict\r\nimport pickle\r\nimport multiprocessing\r\n\r\nweightings = {'p':1, 'n':3.2, 'b':3.3, 'r':5, 'q':9, 'k':200,\r\n 'P':-1, 'N':-3.2, 'B':-3.3, 'R':-5, 'Q':-9, 'K':-200,\r\n ' ':0}\r\n\r\ndef flattened(board):\r\n output = []\r\n for row in board:\r\n for cell in row:\r\n if board.whiteMove:\r\n output.append(weightings[cell])\r\n else:\r\n output.append(-weightings[cell])\r\n return output\r\n\r\ndef getData(repeats, prevData=None):\r\n if prevData:\r\n data = prevData\r\n else:\r\n data = unhashableDict()\r\n \r\n for i in range(repeats):\r\n board = Board()\r\n whiteHistory = [] #these are awesome variable names!\r\n blackHistory = []\r\n \r\n while True:\r\n #print(board)\r\n if not board.findPiece(\"k\"):\r\n #black has won\r\n whiteScore = -1\r\n blackScore = 1\r\n break\r\n \r\n elif not board.findPiece(\"K\"):\r\n blackScore = -1\r\n whiteScore = 1\r\n break\r\n \r\n #print(board, board.state)\r\n #print(board.getMoves(board.whiteMove))\r\n board = board.doRandomMove()\r\n \r\n if board.whiteMove:\r\n whiteHistory.append(flattened(board)) #should deepcopy?\r\n else:\r\n blackHistory.append(flattened(board)) #should deepcopy?\r\n \r\n score = 1 / (len(whiteHistory) + len(blackHistory))\r\n \r\n for tempBoard in whiteHistory:\r\n if tempBoard in data.keys:\r\n curr, iterations = data[tempBoard]\r\n data[tempBoard] = (curr + score*whiteScore, iterations+1)\r\n else:\r\n data[tempBoard] = (score * whiteScore, 1)\r\n \r\n for tempBoard in blackHistory:\r\n if tempBoard in data.keys:\r\n curr, iterations = data[tempBoard]\r\n data[tempBoard] = (curr + score*blackScore, iterations+1)\r\n else:\r\n data[tempBoard] = (score * blackScore, 1)\r\n \r\n return data\r\n\r\ndef save(data):\r\n with open(\"data.txt\", \"wb\") as f:\r\n return pickle.dump(data, f)\r\n \r\ndef load():\r\n with open(\"data.txt\", \"rb\") as f:\r\n return pickle.load(f)\r\n\r\ndef runOptimise(func, *args):\r\n return multiprocessing.Pool(processes=3).apply_async(func, args).get(timeout=120)\r\n\r\nif __name__ == \"__main__\":\r\n data = None #load()\r\n #data = getData(100, prevData=data)\r\n data = runOptimise(getData, 50)\r\n save(data)\r\n","sub_path":"backups/6/createDataset.py","file_name":"createDataset.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"567432986","text":"import requests\nfrom bs4 import BeautifulSoup as bs\nfrom html5_parser import parse\nimport lxml\n\nfrom nendoroid import Nendoroid\n\njp_url = \"http://www.goodsmile.info/ja/nendoroid{}-{}\"\npage_year = \"http://www.goodsmile.info/ja/products/category/nendoroid_series/announced/{}\"\ns = requests.Session()\n\ndef parse_page(url):\n nendoroids = []\n r = s.get(url)\n tree = parse(r.content)\n items = tree.xpath('.//div[contains(@class, \"hitItem\")]')\n\n for item in items:\n if 'nendoroid' not in item.get('class').split():\n continue\n\n url = item.find('.//a').get('href')\n icon = item.find('.//img').get('data-original')\n nendo = Nendoroid(url, icon)\n try:\n nendo.get_info()\n except:\n continue\n else:\n nendoroids.append(nendo)\n\n return nendoroids\n\ndef main():\n with open(\"data/NendoroidData2.js\", \"wt\", encoding='utf8') as data:\n data.write('var nendoroidMap = \\n{\\n')\n\n for year in range(2016, 2018):\n print(year)\n try:\n nendoroids = parse_page(page_year.format(year))\n nendo_data = ',\\n'.join(['\\\"%s\\\":%s'%(nendo.num, nendo.to_json()) for nendo in nendoroids])\n data.write(nendo_data)\n except Exception as e:\n print(e.strerror)\n break\n\n data.write('\\n};\\n')\n\nif __name__ == '__main__':\n main()\n","sub_path":"crawl_nendo.py","file_name":"crawl_nendo.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"395108688","text":"from django.shortcuts import render,redirect,get_object_or_404\nfrom .models import Review,Comment\nfrom .forms import ReviewForm,CommentForm\nfrom django.views.decorators.http import require_http_methods,require_POST\nfrom django.contrib.auth.decorators import login_required\n\n# Create your views here.\ndef index(request):\n return render(request,'community/index.html')\n\ndef review_list(request):\n reviews = Review.objects.all()[::-1]\n context ={\n 'reviews':reviews,\n }\n return render(request,'community/review_list.html',context)\n\n\n@login_required\n@require_http_methods(['GET','POST'])\ndef create(request):\n if request.method =='POST':\n form = ReviewForm(request.POST,files=request.FILES)\n if form.is_valid():\n #user인자에다가 request의 user정보를 담는다\n review = form.save(commit=False)\n review.user = request.user\n review.save()\n return redirect('community:review_detail',review.pk)\n else:\n form = ReviewForm()\n context = {\n 'form':form,\n }\n return render(request,'community/form.html',context)\n \n\ndef review_detail(request,review_pk):\n review = get_object_or_404(Review,pk=review_pk)\n comments = review.comment_set.all()[::-1]\n comment_form = CommentForm()\n context = {\n 'review':review,\n 'comment_form':comment_form,\n 'comments':comments,\n }\n return render(request,'community/review_detail.html',context)\n\n\n@require_POST\ndef comments(request,review_pk):\n review = get_object_or_404(Review,pk=review_pk)\n comment_form = CommentForm(request.POST)\n if comment_form.is_valid():\n comment = comment_form.save(commit=False)\n comment.user = request.user\n comment.review = review\n comment.save()\n return redirect('community:review_detail',review.pk)\n\n\n@require_POST\ndef like(request,review_pk):\n if request.user.is_authenticated:\n review = get_object_or_404(Review,pk=review_pk)\n if review.like.filter(pk=request.user.pk).exists():\n review.like.remove(request.user)\n else:\n review.like.add(request.user)\n return redirect('community:review_list')\n return redirect('accounts:login')\n\n\n@require_POST\ndef like_comment(request,review_pk,comment_pk):\n review = get_object_or_404(Review,pk=review_pk)\n if request.user.is_authenticated:\n comment = get_object_or_404(Comment,pk=comment_pk)\n if comment.like_comment.filter(pk=request.user.pk).exists():\n comment.like_comment.remove(request.user)\n else:\n comment.like_comment.add(request.user)\n return redirect('community:review_detail',review.pk)\n return redirect('accounts:login')","sub_path":"projects/movie_review/community/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"454161633","text":"import xlrd\nfrom datetime import date,datetime\n\nfile = 'test.xls'\n\ndef read_excel():\n\n wb = xlrd.open_workbook(filename=file)\n print('All sheet name:',wb.sheet_names())\n\n sheet1 = wb.sheet_by_index(0) #通过索引获取表格\n sheet2 = wb.sheet_by_name('ASC') #通过名字获取表格\n print('sheet code',sheet1,sheet2)\n print('sheet content:',sheet1.name,sheet1.nrows,sheet1.ncols)\n\n rows = sheet1.row_values(2) #Get Row2\n clos = sheet1.col_values(3) #Get colum3\n # print('sheet1 row[2]',rows)\n # print('sheet1 colum[3]',clos)\n # #获取单元格内容 \n # print(sheet1.cell(1,0).value) \n # print(sheet1.cell_value(1,0))\n # print(sheet1.row(1)[0].value)\n # #获取单元格类型\n # print(sheet1.cell(2,0).ctype)\n print('sheet1 row[0]')\n\n\n\nif __name__ == '__main__':\n read_excel()\n","sub_path":"Learn/DATA/Excel/read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"333104644","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n# Author: Kun Huang \n\n\nfrom collections import defaultdict\nimport re\n\nfrom lxml import etree\nimport simplexml\n\nfrom swift.common.wsgi import make_pre_authed_env as copyenv\nfrom swift.common.swob import Request, Response\nfrom swift.common.wsgi import WSGIContext\nfrom swift.common.http import HTTP_OK, HTTP_CREATED, HTTP_ACCEPTED, \\\n HTTP_NO_CONTENT, HTTP_BAD_REQUEST, HTTP_UNAUTHORIZED, HTTP_FORBIDDEN, \\\n HTTP_NOT_FOUND, HTTP_CONFLICT, HTTP_UNPROCESSABLE_ENTITY, is_success, \\\n HTTP_NOT_IMPLEMENTED, HTTP_LENGTH_REQUIRED, HTTP_SERVICE_UNAVAILABLE\n\n\nclass BaseController(WSGIContext):\n '''\n Provide some basic useful class.\n '''\n\n invisible = ['suppersupper']\n def __init__(self):\n pass\n\n def create_elem(self, tag, text):\n elem = etree.Element(tag)\n if text:\n elem.text = text\n return elem\n\n def keyvalue2dict(self, value):\n valued = defaultdict(list)\n for _pair in value.split(','):\n _key, _value = _pair.split('=')\n valued[_key.strip()].append(_value.strip())\n return dict(valued)\n\n\n def xmlbody2dict(self, xml):\n return simplexml.loads(xml)\n\n\n def xmlbody2elem(self, xml):\n xmlns = 'xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"'\n xml = xml.replace(xmlns, '')\n xmlns = 'xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"'\n xml = xml.replace(xmlns, '')\n return etree.fromstring(xml)\n\n\n def elem2xmlbody(self, elem):\n return etree.tostring(elem, xml_declaration=True)\n\n\n def dict2xmlbody(self, dic):\n return simplexml.dumps(dic)\n\n def get_err_response(self, code):\n \"\"\"\n Given an HTTP response code, create a properly formatted xml error response\n\n :param code: error code\n :returns: webob.response object\n \"\"\"\n error_table = {\n 'AccessDenied':\n (HTTP_FORBIDDEN, 'Access denied'),\n 'BucketAlreadyExists':\n (HTTP_CONFLICT, 'The requested bucket name is not available'),\n 'BucketNotEmpty':\n (HTTP_CONFLICT, 'The bucket you tried to delete is not empty'),\n 'InvalidArgument':\n (HTTP_BAD_REQUEST, 'Invalid Argument'),\n 'InvalidBucketName':\n (HTTP_BAD_REQUEST, 'The specified bucket is not valid'),\n 'InvalidURI':\n (HTTP_BAD_REQUEST, 'Could not parse the specified URI'),\n 'InvalidDigest':\n (HTTP_BAD_REQUEST, 'The Content-MD5 you specified was invalid'),\n 'BadDigest':\n (HTTP_BAD_REQUEST, 'The Content-Length you specified was invalid'),\n 'NoSuchBucket':\n (HTTP_NOT_FOUND, 'The specified bucket does not exist'),\n 'SignatureDoesNotMatch':\n (HTTP_FORBIDDEN, 'The calculated request signature does not '\n 'match your provided one'),\n 'RequestTimeTooSkewed':\n (HTTP_FORBIDDEN, 'The difference between the request time and the'\n ' current time is too large'),\n 'NoSuchKey':\n (HTTP_NOT_FOUND, 'The resource you requested does not exist'),\n 'NotSuchPolicy':\n (HTTP_NOT_FOUND, 'The Policy you requested does not exist'),\n 'NotSuchWebsite':\n (HTTP_NOT_FOUND, 'The Website you requested does not exist'),\n 'Unsupported':\n (HTTP_NOT_IMPLEMENTED, 'The feature you requested is not yet'\n ' implemented'),\n 'MissingContentLength':\n (HTTP_LENGTH_REQUIRED, 'Length Required'),\n 'ServiceUnavailable':\n (HTTP_SERVICE_UNAVAILABLE, 'Please reduce your request rate')}\n\n resp = Response(content_type='text/xml')\n resp.status = error_table[code][0]\n resp.body = '\\r\\n\\r\\n ' \\\n '%s\\r\\n %s\\r\\n\\r\\n' \\\n % (code, error_table[code][1])\n return resp\n\n def swift_acl_translate(self, canned=None, acl=None):\n \"\"\"\n Takes an S3 style ACL and returns a list of header/value pairs that\n implement that ACL in Swift, or \"Unsupported\" if there isn't a way to do\n that yet.\n \"\"\"\n if canned == acl == None or (canned is not None and acl is not None):\n raise ValueError('One and only one kind of acl is supported')\n\n if canned:\n swift_acl = defaultdict(list)\n canned_acl = ['bucket-owner-read', 'bucket-owner-full-control',\n 'public-read', 'public-read-write', 'private',\n 'authenticated-read']\n swift_acl['authenticated-read'] = [['HTTP_X_CONTAINER_READ', '.r:*,.rlistings']]\n swift_acl['private'] = [['HTTP_X_CONTAINER_WRITE', '.'],\n ['HTTP_X_CONTAINER_READ', '.']]\n if canned in canned_acl:\n return swift_acl[canned]\n\n if acl:\n swift_acl = defaultdict(list)\n read = acl['read']['userid'] + acl['read']['user'] + acl['full']['userid'] + acl['full']['user']\n write = acl['write']['userid'] + acl['write']['user'] + acl['full']['userid'] + acl['full']['user']\n return [['HTTP_X_CONTAINER_READ', read],['HTTP_X_CONTAINER_WRITE', write]]\n\n\n def validate_bucket_name(self, name):\n \"\"\"\n Validates the name of the bucket against S3 criteria,\n http://docs.amazonwebservices.com/AmazonS3/latest/BucketRestrictions.html\n True if valid, False otherwise\n \"\"\"\n\n if '_' in name or len(name) < 3 or len(name) > 63 or not name[-1].isalnum():\n # Bucket names should not contain underscores (_)\n # Bucket names must end with a lowercase letter or number\n # Bucket names should be between 3 and 63 characters long\n return False\n elif '.-' in name or '-.' in name or '..' in name or not name[0].isalnum():\n # Bucket names cannot contain dashes next to periods\n # Bucket names cannot contain two adjacent periods\n # Bucket names Must start with a lowercase letter or a number\n return False\n elif re.match(\"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}\"\n \"([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$\", name):\n # Bucket names cannot be formatted as an IP Address\n return False\n elif name in self.invisible:\n return False\n else:\n return True\n\n\n def version_name(self, name):\n return '_' + name\n\n\n def is_unique(self, container):\n # TODO checking ...\n # build another request obj to list all objects\n # use system roor account to create a 'public' container\n # use that container to store all container name\n # return false if there's same name container\n # return true else\n return True\n\n def get_acl(self, account_name, headers):\n \"\"\"\n Attempts to construct an S3 ACL based on what is found in the swift headers\n \"\"\"\n\n acl = 'private' # default to private\n\n if 'x-container-read' in headers:\n if headers['x-container-read'] == \".r:*\" or\\\n \".r:*,\" in headers['x-container-read'] or \\\n \",*,\" in headers['x-container-read']:\n acl = 'public-read'\n if 'x-container-write' in headers:\n if headers['x-container-write'] == \".r:*\" or\\\n \".r:*,\" in headers['x-container-write'] or \\\n \",*,\" in headers['x-container-write']:\n if acl == 'public-read':\n acl = 'public-read-write'\n else:\n acl = 'public-write'\n\n if acl == 'private':\n body = (''\n ''\n '%s'\n '%s'\n ''\n ''\n ''\n ''\n '%s'\n '%s'\n ''\n 'FULL_CONTROL'\n ''\n ''\n '' %\n (account_name, account_name, account_name, account_name))\n elif acl == 'public-read':\n body = (''\n ''\n '%s'\n '%s'\n ''\n ''\n ''\n ''\n '%s'\n '%s'\n ''\n 'FULL_CONTROL'\n ''\n ''\n ''\n 'http://acs.amazonaws.com/groups/global/AllUsers'\n ''\n 'READ'\n ''\n ''\n '' %\n (account_name, account_name, account_name, account_name))\n elif acl == 'public-read-write':\n body = (''\n ''\n '%s'\n '%s'\n ''\n ''\n ''\n ''\n '%s'\n '%s'\n ''\n 'FULL_CONTROL'\n ''\n ''\n ''\n 'http://acs.amazonaws.com/groups/global/AllUsers'\n ''\n 'READ'\n ''\n ''\n ''\n ''\n ''\n 'http://acs.amazonaws.com/groups/global/AllUsers'\n ''\n 'WRITE'\n ''\n ''\n '' %\n (account_name, account_name, account_name, account_name))\n else:\n body = (''\n ''\n '%s'\n '%s'\n ''\n ''\n ''\n ''\n '%s'\n '%s'\n ''\n 'FULL_CONTROL'\n ''\n ''\n '' %\n (account_name, account_name, account_name, account_name))\n return Response(body=body, content_type=\"text/plain\")\n\n def obj_headers_to_amz(self, headers):\n new_hdrs = {}\n for key, val in headers.iteritems():\n _key = key.lower()\n if _key.startswith('x-object-meta-'):\n new_hdrs['x-amz-meta-' + key[14:]] = val\n elif _key in ('content-length', 'content-type',\n 'content-range', 'content-encoding',\n 'etag', 'last-modified', 'x-amz-version-id'):\n new_hdrs[key] = val\n return new_hdrs\n","sub_path":"swift3/s3controllers/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":12810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"533037835","text":"#!/usr/bin/env python\r\n# -*- coding: iso-8859-1 -*-\r\n\r\nfrom __future__ import unicode_literals\r\nfrom flask import Flask, render_template, flash, request\r\nfrom marketing_notifications_python.forms import SendMessageForm\r\nfrom marketing_notifications_python.models import init_models_module\r\nfrom marketing_notifications_python.twilio import init_twilio_module\r\nfrom marketing_notifications_python.view_helpers import twiml, view\r\nfrom flask import Blueprint\r\nfrom marketing_notifications_python.twilio.twilio_services import TwilioServices\r\nimport sqlite3\r\n\r\n\r\n# WHEN ADDING SPANISH CHARACTERS I GET in _escape_cdata\r\n# return text.encode(encoding, \"xmlcharrefreplace\")\r\n# UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 218: ordinal not in range(128)\r\n# even with encoding=utf8 at the top of this file\r\n\r\n\r\ndef construct_view_blueprint(app, db):\r\n SUBSCRIBE_COMMAND = \"subscribe\"\r\n UNSUBSCRIBE_COMMAND = \"finished\"\r\n SUBSCRIBE_COMMAND_SPANISH = \"inscribe\"\r\n UNSUBSCRIBE_COMMAND_SPANISH = \"alto\"\r\n\r\n views = Blueprint(\"views\", __name__)\r\n\r\n init_twilio_module(app)\r\n init_models_module(db)\r\n from marketing_notifications_python.models.subscriber import Subscriber\r\n\r\n @views.route('/', methods=[\"GET\", \"POST\"])\r\n @views.route('/notifications', methods=[\"GET\", \"POST\"])\r\n def notifications():\r\n form = SendMessageForm()\r\n if request.method == 'POST' and form.validate():\r\n flash(form.language.data)\r\n flash(form.zipCode.data)\r\n for zip in form.zipCode.data:\r\n flash(zip.strip('u'))\r\n flash(form.interest.data)\r\n for i in form.interest.data:\r\n flash(i.strip('u'))\r\n flash(form.childAge.data)\r\n temp1 = set()\r\n subscribers = []\r\n flash(form.message.data)\r\n for zips in form.zipCode.data:\r\n if zips != \"All\":\r\n tempzip = int(zips)\r\n temp1.update(Subscriber.query.filter(Subscriber.zipcode == tempzip).all())\r\n else:\r\n temp1.update(Subscriber.query.filter(Subscriber.subscribed).all())\r\n if (form.language.data) == \"Spanish\":\r\n temp1.intersection_update(Subscriber.query.filter(Subscriber.spanish).all())\r\n temp2 = set()\r\n if len(form.interest.data) > 0:\r\n for i in (form.interest.data):\r\n for subs in temp1:\r\n if i == \"Science/Tech\":\r\n if \"1\" in subs.interests:\r\n temp2.add(subs)\r\n elif i == \"Arts\":\r\n if \"2\" in subs.interests:\r\n temp2.add(subs)\r\n elif i == \"Sports\":\r\n if \"3\" in subs.interests:\r\n temp2.add(subs)\r\n else:\r\n temp2 = Subscriber.query.filter(Subscriber.subscribed).all()\r\n temp1.intersection_update(temp2)\r\n if form.childAge.data != \"\":\r\n ages = (form.childAge.data.split(\" \"))\r\n for age in ages:\r\n if len(temp1) > 0:\r\n for subs in temp1:\r\n subages = subs.age.split(\" \")\r\n for subage in subages:\r\n if subage == age:\r\n subscribers.append(subs)\r\n else:\r\n subscribers = temp1\r\n subscribers = set(subscribers)\r\n\r\n # temp2 = Subscriber.query.filter(Subscriber.age == form.childAge.data).all()\r\n # stemp2 = set(temp2)\r\n\r\n # subscribers= Subscriber.query.filter(Subscriber.subscribed).all()\r\n if len(subscribers) > 0:\r\n flash('Messages on their way!')\r\n twilio_services = TwilioServices()\r\n for s in subscribers:\r\n twilio_services.send_message(s.phone_number, form.message.data)\r\n else:\r\n flash('No subscribers found!')\r\n\r\n form.reset()\r\n return view('notifications', form)\r\n\r\n return render_template('notifications.html', form=form)\r\n\r\n @views.route('/message', methods=[\"POST\"])\r\n def message():\r\n subscriber = Subscriber.query.filter(Subscriber.phone_number == request.form['From']).first()\r\n if subscriber is None:\r\n subscriber = Subscriber(phone_number=request.form['From'])\r\n db.session.add(subscriber)\r\n db.session.commit()\r\n output = \"Thanks for contacting the UCI parent text message study. Text \" \\\r\n \"\\\"subscribe\\\" if you would like to receive updates via text message in English. \" \\\r\n \"Gracias por contactar el estudio conducido por UCI, el mensaje de texto para los padres. \" \\\r\n \"Responde con un mensaje de texto con la palabra \" \\\r\n \"\\\"inscribe\\\" si gustarían recibir notificaciones por mensaje de texto en Español.\"\r\n\r\n elif not subscriber.subscribed:\r\n output = _process_message(request.form['Body'], subscriber)\r\n db.session.commit()\r\n\r\n elif subscriber.zipcode is None and subscriber.spanish:\r\n output = _process_zip_spanish(request.form['Body'], subscriber)\r\n db.session.commit()\r\n\r\n elif subscriber.zipcode is None and not subscriber.spanish:\r\n output = _process_zip(request.form['Body'], subscriber)\r\n db.session.commit()\r\n\r\n elif subscriber.age is None and subscriber.spanish:\r\n output = _process_age_spanish(request.form['Body'], subscriber)\r\n db.session.commit()\r\n\r\n elif subscriber.age is None and not subscriber.spanish:\r\n output = _process_age(request.form['Body'], subscriber)\r\n db.session.commit()\r\n\r\n elif subscriber.interests is None and subscriber.spanish:\r\n output = _process_interests_spanish(request.form['Body'], subscriber)\r\n db.session.commit()\r\n\r\n elif subscriber.interests is None and not subscriber.spanish:\r\n output = _process_interests(request.form['Body'], subscriber)\r\n db.session.commit()\r\n\r\n else: # trying to fix the unbound local error message that happens after trying to unsubscribe after signup,\r\n # this fixes it\r\n output = _process_message(request.form['Body'], subscriber)\r\n db.session.commit()\r\n\r\n twilio_services = TwilioServices()\r\n return twiml(twilio_services.respond_message(output))\r\n\r\n def _process_message(message, subscriber):\r\n output = \"Sorry, we don't recognize that command. Available commands are: \\\"subscribe\\\" or \\\"finished\\\". \" \\\r\n \"Lo sentimos, no reconocemos ese comando. Los comandos disponibles son: \\\"inscribe\\\" o \\\"alto\\\".\"\r\n\r\n if message.lower().startswith(SUBSCRIBE_COMMAND) or message.lower().startswith(UNSUBSCRIBE_COMMAND):\r\n subscriber.subscribed = message.lower().startswith(SUBSCRIBE_COMMAND)\r\n subscriber.spanish = False;\r\n\r\n if subscriber.subscribed:\r\n output = \"Thanks for signing up for the parent text message service. Please reply with your ZIP code.\"\r\n else:\r\n output = \"You have unsubscribed from notifications and your data has been deleted.\"\r\n Subscriber.query.filter(Subscriber.phone_number == subscriber.phone_number).delete()\r\n\r\n elif message.lower().startswith(SUBSCRIBE_COMMAND_SPANISH) or message.lower().startswith(\r\n UNSUBSCRIBE_COMMAND_SPANISH):\r\n subscriber.subscribed = message.lower().startswith(SUBSCRIBE_COMMAND_SPANISH)\r\n subscriber.spanish = True;\r\n\r\n if subscriber.subscribed:\r\n output = \"Gracias por inscribirte a los mensajes de texto para los padres! Por favor responda \" \\\r\n \"con su código postal (ZIP).\"\r\n else:\r\n output = \"Has cancelado las suscripción a las notificaciones semanales; sus datos han sido eliminados.\"\r\n Subscriber.query.filter(Subscriber.phone_number == subscriber.phone_number).delete()\r\n\r\n return output\r\n\r\n def _process_zip_spanish(message, subscriber):\r\n\r\n output = \"Lo sentimos, no reconocemos su codigo postal (ZIP). Porfavor vuelve a ingresar \" \\\r\n \"su codingo postal (ZIP).\"\r\n\r\n if message[0].isdigit and len(message) == 5:\r\n subscriber.zipcode = message\r\n output = \"Gracias! Por favor responda con la edad de sus hijos. Separe las edades con un espacio.\"\r\n\r\n return output\r\n\r\n def _process_zip(message, subscriber):\r\n output = \"Sorry, that's an invalid zipcode. Please reenter your zipcode.\"\r\n\r\n if message[0].isdigit() and len(message) == 5:\r\n subscriber.zipcode = message\r\n output = \"Thanks! Please reply with the age(s) of your child. Separate multiple ages with a space.\"\r\n\r\n return output\r\n\r\n def _process_age_spanish(message, subscriber):\r\n ageList = message.strip(\" \").split(\" \")\r\n output = \"Lo sentimos, no reconocemos las edad(es) de su/s hijo/a. Porfavor vuelve a ingresar las \" \\\r\n \"edad(es) de su/s hijo/a. \"\r\n for age in ageList:\r\n try:\r\n if 0 > int(age) > 18:\r\n return output\r\n except:\r\n return output\r\n subscriber.age = message\r\n output = \"Gracias! Por favor indique las áreas de interés de sus hijos:\" \\\r\n \"1 para Ciencia/tecnología, 2 para Arte, 3 para Deportes, 4 para todas estas áreas. \" \\\r\n \"Si existen multiples areas de interes, por favor sepáralas con un espacio. \"\r\n return output\r\n\r\n def _process_age(message, subscriber):\r\n ageList = message.strip(\" \").split(\" \")\r\n output = \"Sorry, that's an invalid age. Please reenter your child's age.\"\r\n for age in ageList:\r\n try:\r\n if 0 > int(age) > 18:\r\n return output\r\n except:\r\n return output\r\n subscriber.age = message\r\n output = \"Thanks! Please reply with your child's interests: 1 for science/tech, 2 for arts, \" \\\r\n \"3 for sports, 4 for all. Separate multiple interests with a space.\"\r\n return output\r\n\r\n def _process_interests_spanish(message, subscriber):\r\n output = \"Lo sentimos, no reconocemos las areas que les interesan a su/s hijo/a. Porfavor vuelve a ingresar \" \\\r\n \"responda con las areas que les interesan a su/s hijo/a.\"\r\n\r\n interestList = message.strip(\" \").split(\" \")\r\n for interest in interestList:\r\n try:\r\n if 0 > int(interest) > 4:\r\n return output\r\n except:\r\n return output\r\n subscriber.interests = message\r\n output = \"Felicidades, ya se inscribió! Recibirá mensajes semanales con avisos de programas o actividades \" \\\r\n \"educativas e informativas. Si en algún momento le gustaría finalizar este servicio, responda con la \" \\\r\n \"palabra \\\"alto\\\". Se aplican las tarifas estándar de mensajería de texto y datos. \"\r\n\r\n return output\r\n\r\n def _process_interests(message, subscriber):\r\n output = \"Sorry, that's an invalid interest. Please reenter your child's interests: 1 for science/tech, \" \\\r\n \"2 for arts, 3 for sports, 4 for all.\"\r\n\r\n interestList = message.strip(\" \").split(\" \")\r\n for interest in interestList:\r\n try:\r\n if 0 > int(interest) > 4:\r\n return output\r\n except:\r\n return output\r\n\r\n # conn = sqlite3.connect('summeropp.db') # opens DB, DB will be created if it doesn't exist\r\n # conn.text_factory = str\r\n # c = conn.cursor()\r\n # opps = []\r\n # for row in c.execute('SELECT * FROM summer_opportunities WHERE zipcode = ? LIMIT 3', [subscriber.zipcode]):\r\n # opps.append(row)\r\n #\r\n # twilio_services = TwilioServices()\r\n # if len(opps) > 1:\r\n # firstmessage = \"You're all set. You'll get info a few times per week on out of school learning \" \\\r\n # \"opportunities and advice. \"\r\n # twilio_services.send_message(subscriber.phone_number, firstmessage)\r\n # try:\r\n # for i in opps:\r\n # opp = (b + \" \" + i[1] + \" \" + i[2] + \" \" + i[3] + \" \" + str(i[4]) + \" \" + i[5] + \" \" + i[6] + \" \"\r\n # + i[7] + \" \" + i[8] + \" \" + i[9] + \" \" + i[10] + \" \" + i[11] + \" \" + i[12] + \" \" + i[\r\n # 13] + \" \" + i[14] + \" \" + i[15] + \" \" +\r\n # i[16] + \" \" + i[17] + \" \" + i[18] + \" \" + i[19])\r\n #\r\n # twilio_services.send_message(subscriber.phone_number, opp)\r\n # subscriber.interests = message\r\n # output = \"Above are three opportunities to get you started! Reply \\\"finished\\\" \" \\\r\n # \"at any time to stop these messages and delete your data. \" \\\r\n # \"Standard text messaging and data rates apply.\"\r\n # except:\r\n # subscriber.interests = message\r\n # output = \"Reply \\\"finished\\\" \" \\\r\n # \"at any time to stop these messages and delete your data. \" \\\r\n # \"Standard text messaging and data rates apply.\"\r\n # else:\r\n subscriber.interests = message\r\n output = \"You're all set. You'll get info a few times per week on out of school learning opportunities \" \\\r\n \"and advice. Reply \\\"finished\\\" at any time to stop these messages and delete your data. \" \\\r\n \"Standard text messaging and data rates apply.\"\r\n # c.close()\r\n # conn.close()\r\n return output\r\n\r\n return views\r\n","sub_path":"viewsnoprocessing.py","file_name":"viewsnoprocessing.py","file_ext":"py","file_size_in_byte":14256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"309076931","text":"from isis.dialog_search_text import Dialog_Search_Text, Data_Table_Model\nfrom sarah.acp_bson import Client\n\n\nclass Search_Account(Dialog_Search_Text):\n def __init__(self, parent=None):\n Dialog_Search_Text.__init__(self, parent)\n self.agent_caroline = None\n\n def searching(self, e):\n if self.agent_caroline is None:\n self.agent_caroline = Client('isis.caroline.search_account', 'caroline')\n msg = {'type_message': 'find', 'type': 'caroline/account', 'query': {'name': {'!like': e['text']}}}\n answer = self.agent_caroline.send_msg(msg)\n e['list'] = answer['result']\n table = Data_Table_Model()\n e['table'] = table\n table.columns.add('id', str)\n table.columns.add('type', str)\n table.columns.add('account_type', str)\n table.columns.add('name', str)\n for account in e['list']:\n row = table.newrow()\n if 'id' in account:\n row['id'] = account['id']\n if 'type' in account:\n row['type'] = account['type']\n if 'account_type' in account:\n row['account_type'] = account['account_type']\n if 'name' in account:\n row['name'] = account['name']\n","sub_path":"isis/caroline/search_account.py","file_name":"search_account.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"48805906","text":"\n\nfrom xai.brain.wordbase.nouns._zucchini import _ZUCCHINI\n\n#calss header\nclass _ZUCCHINIS(_ZUCCHINI, ):\n\tdef __init__(self,): \n\t\t_ZUCCHINI.__init__(self)\n\t\tself.name = \"ZUCCHINIS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"zucchini\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_zucchinis.py","file_name":"_zucchinis.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"312389422","text":"import numpy as np\nfrom numpy.linalg import norm\nfrom Distributions import*\ndebug = False\n\n###############################################################################\n\n\"\"\"the function normv retruns the axis of the rotation; the vector u and \nthe function input\"vector\" form a plane, from which find a vector which \nis orthogonal to the plane. \n\"\"\"\ndef normv(u):\n v = np.array([1,1,1])\n x = u[1]*v[2] - u[2]*v[1]\n y = u[2]*v[0] - u[0]*v[2]\n z = u[0]*v[1] - u[1]*v[0]\n normv = np.array([x,y,z])/norm(np.array([x,y,z]))\n return normv \n\n###############################################################################\n#This function returns the rotation matrix; angl here is the angle of rotation, \n#v is the axis of the rotation \n#check wikipedia \"https://en.wikipedia.org/wiki/Rotation_matrix\"\ndef rotation(v,angl):\n r = np.array([\n np.cos(angl) + v[0]**2*(1-np.cos(angl)), \n v[0]*v[1]*(1-np.cos(angl))- v[2]*np.sin(angl), \n v[0]*v[2]*(1-np.cos(angl))+ v[1]*np.sin(angl),\n v[1]*v[0]*(1-np.cos(angl))+v[2]*np.sin(angl),\n np.cos(angl)+v[1]**2*(1-np.cos(angl)), \n v[1]*v[2]*(1-np.cos(angl))-v[0]*np.sin(angl),\n v[2]*v[0]*(1-np.cos(angl))-v[1]*np.sin(angl),\n v[2]*v[1]*(1-np.cos(angl))+v[0]*np.sin(angl),\n np.cos(angl)+ v[2]**2*(1-np.cos(angl))])\n return r.reshape(3,3)\n\n###############################################################################\n\"\"\"the function parton3d returns a list of tuples(l) that every tuple contains\ninformaton of the particle(the for momentum, the initial position and the final\nposition) and d is a flat list of l.\nfirst the particle is being rotated with angle theta \"rot1\" then is rotated by \nangle phi rot2\"\"\"\n\ndef parton3d(P_i):\n i = 0\n xb = np.array([0,0,0])\n xf = P_i[1:]/norm(P_i[1:])\n l = [(P_i,xb,xf)]\n Hadron = [] #list of final state particles\n while i < len(l):\n P, xb, xf = l[i]\n if P[0] > 0.05:\n z = Z()\n ang1 = theta()\n ang2 = phi()\n n = normv(P[1:])\n rot1 = rotation(n,ang1)\n rot2 = rotation(P[1:]/norm(P[1:]),ang2)\n tmp = np.dot(rot2,np.dot(rot1,P[1:]))\n tmp = P[0]*tmp/norm(tmp)\n a = np.array([P[0]])\n P_r = z*np.concatenate((a,tmp))\n P_part = P - P_r \n xbr = xf \n xbp = xf\n xfr = xf + P_r[1:]/norm(P_r[1:])\n xfp = xf + P_part[1:]/norm(P_part[1:])\n l.append((P_r,xbr,xfr))\n l.append((P_part,xbp,xfp))\n if debug:\n print('P_r: ', P_r[0],norm(P_r[1:]))\n print('P_part:', P_part[0], norm(P_part[1:])) \n else:\n Hadron.append(P)\n i +=1\n d = []\n for i in l:\n d.append(list(i[0])+list(i[1])+list(i[2]))\n return Hadron\n\n\n######\n\ndef partons(P_i):\n J1 = parton3d(P_i)\n P_d = [1,-1,-1,-1]*P_i\n J2 = parton3d(P_d)\n return J1 + J2\n\n","sub_path":"PythonToyModel/pseudo_jets_generator.py","file_name":"pseudo_jets_generator.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"291986136","text":"from django.db import transaction\n\nfrom bank.models import Account\n\n\n@transaction.atomic\ndef apply_deposit(account, amount):\n \"\"\"Apply atomic transaction for depositing\"\"\"\n assert isinstance(account, Account)\n assert amount > 0.0\n account.balance += amount\n account.save()\n return True\n\n\n@transaction.atomic\ndef apply_withdraw(account, amount):\n \"\"\"Apply atomic transaction for withdraw\"\"\"\n assert isinstance(account, Account)\n assert amount > 0.0\n if (account.balance - amount) < 0:\n return False\n else:\n account.balance -= amount\n account.save()\n return True\n\n\n@transaction.atomic\ndef apply_transfer(from_account, to_account, amount):\n \"\"\"Apply atomic transaction for transferring money\"\"\"\n assert isinstance(from_account, Account)\n assert isinstance(to_account, Account)\n assert amount > 0.0\n if (from_account.balance - amount) < 0:\n return False\n else:\n from_account.balance -= amount\n to_account.balance += amount\n from_account.save()\n to_account.save()\n return True\n","sub_path":"app/bank/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"262578237","text":"#!/usr/bin/python\n\nimport threading\nimport time\nimport traceback\nimport confluent_kafka\nimport ccxt\nimport json\nimport datetime\nimport logging\nimport os\nimport click\nimport uuid\nimport signal\nimport etcd3\nimport concurrent.futures\nimport os\nimport collections\n\nimport simpleProducer\nimport simpleConsumer\nimport heartbeatProducer\nimport configurationService\n\nfrom tickerProducer import TickerProducer\n\nCONTROL_REQUEST_TOPIC = \"ControlRequestMarketData\"\nSTATUS_TOPIC = \"StatusMarketData\"\nREQUEST_MARKET_DATA_TOPIC = \"RequestMarketData\"\nPROCESSOR_TYPE = \"TickerRequestProducer\"\n\nREFRESH_CONFIG_DELAY = 600\n\nTICKER_KEY=[\"lib\",\"exchange\",\"call\",\"args\"]\n\nlogging.basicConfig(\n #level=logging.DEBUG, \n level=logging.INFO, \n format='%(asctime)s - %(threadName)s - %(name)s - %(levelname)s - %(message)s')\n\n\nREQUEST_MARKET_DATA_PRODUCER = None\nSTATUS_PRODUCER = None\n\nSTOP_THREADS = threading.Event()\n\ndef get_ticker_key(ticker):\n return str([ticker[key] for key in TICKER_KEY])\n \nclass RequestProcessor(object):\n def __init__(self, control_consumer, request_producer, status_producer, \n etcd_host, etcd_port, etcd_root, processor_id = None):\n self._control_consumer = control_consumer \n self._request_producer = request_producer \n self._status_producer = status_producer\n self._processor_id = processor_id or uuid.uuid1()\n self._thread = threading.Thread(target=self._run)\n self._refresh_config_thread = threading.Thread(target=self._run_refresh_config, daemon = True)\n self._ticker_by_id = {}\n self._ticker_by_key = collections.defaultdict(dict)\n self._heartbeat = heartbeatProducer.HeatbeatProducer(\n status_producer = self._status_producer,\n delay = 1, \n id = self._processor_id, \n stop_event = STOP_THREADS,\n processor_type = PROCESSOR_TYPE\n )\n self._configuration_service = configurationService.EtcdConfigurationService(\n etcd_host=etcd_host, etcd_port=etcd_port,\n root=etcd_root,\n id = self._processor_id, \n stop_event = STOP_THREADS,\n processor_type = PROCESSOR_TYPE \n )\n self._configuration_service.register_callback = lambda : self._async_process_request(self._get_config)\n workers = os.cpu_count()\n if workers:\n workers = workers * 20\n self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=workers)\n\n def _upsert_ticker(self, id, ticker):\n key = get_ticker_key(ticker.get_config())\n self._ticker_by_id[id] = ticker\n self._ticker_by_key[key][id] = ticker\n\n def _remove_ticker_by_id(self, id):\n ticker = self._ticker_by_id[id]\n key = get_ticker_key(ticker.get_config())\n del self._ticker_by_id[id]\n del self._ticker_by_key[key][id]\n\n def _list_ticker(self, key = None):\n if key == None:\n return self._ticker_by_id.values()\n else:\n return self._ticker_by_key[key].values()\n\n def _list_ticker_ids(self, key = None):\n if key == None:\n return self._ticker_by_id.keys()\n else:\n return self._ticker_by_key[key].keys() \n\n def _get_ticker(self, id):\n return self._ticker_by_id[id]\n\n def _refresh_config(self):\n try:\n for ticker in list(self._list_ticker()):\n ticker.put_config()\n except Exception as ex: \n logging.error(ex) \n logging.debug(traceback.format_exc())\n\n def _run_refresh_config(self):\n while not STOP_THREADS.wait(REFRESH_CONFIG_DELAY):\n self._refresh_config()\n \n def _run(self):\n try:\n self._control_consumer.consume(**{\n \"stop_event\" : STOP_THREADS,\n \"callback\": self._process_request\n })\n except Exception as ex: \n logging.error(ex) \n logging.debug(traceback.format_exc())\n finally:\n for ticker in self._list_ticker():\n ticker.stop() \n\n def _async_process_request(self, call, **kwargs):\n self._executor.submit(self._async_process_request_impl, call, **kwargs)\n\n def _async_process_request_impl(self, call, **kwargs):\n kwargs = {**{\n 'request' : None,\n 'key' : uuid.uuid1()\n },**kwargs}\n try:\n request = kwargs['request']\n key = kwargs['key']\n call(**kwargs)\n except Exception as ex:\n msg = \"Error processing request\" \n logging.error(msg) \n logging.debug(ex) \n trace = traceback.format_exc() \n logging.debug(trace)\n self._send_status_error(msg, key, request, ex, trace) \n \n def _process_request(self, **kwargs):\n logging.info(\"Received msg: {}\".format(kwargs))\n request = kwargs['value']\n key = kwargs['key']\n try:\n command = request['command']\n del request['command']\n if not command.startswith('_'):\n del request['id']\n self._async_process_request(\n call = getattr(self, command),\n **{\n 'key' : uuid.UUID(hex=key), \n 'request' : request\n })\n except Exception as ex:\n msg = \"Error processing request\" \n logging.error(msg) \n logging.debug(ex) \n trace = traceback.format_exc() \n logging.debug(trace)\n self._send_status_error(msg, key, request, ex, trace)\n\n def _start(self):\n logging.info(\"Start recieving msg from {}\".format(\n self._control_consumer.topics)) \n self._heartbeat.start()\n self._configuration_service.start()\n self._thread.start()\n self._refresh_config_thread.start()\n\n def _get_config(self, **kwargs):\n logging.info(\"Retrieving stored ticker configuration\")\n try:\n ticker_configs, _ = self._configuration_service.get_config(\"ticker\")\n except Exception as ex:\n msg = \"Error retrieving stored ticker data\" \n logging.error(msg) \n logging.debug(ex) \n trace = traceback.format_exc() \n logging.debug(trace)\n self._send_status_error(msg, self._processor_id, None, ex, trace)\n return\n for ticker in ticker_configs:\n if STOP_THREADS.is_set():\n return\n try:\n self.start(self._processor_id, ticker_configs[ticker])\n except Exception as ex:\n msg = \"Error configuring stored ticker\" \n logging.error(msg) \n logging.debug(ex) \n trace = traceback.format_exc() \n logging.debug(trace)\n self._send_status_error(msg, self._processor_id, ticker_configs[ticker], ex, trace) \n\n def blacklist(self, key, request):\n exchange = request['exchange']\n call = request['call']\n args = request['args']\n ticker_id = request['ticker_id']\n request[\"processor_id\"] = self._processor_id\n for ticker in list(self._list_ticker(get_ticker_key(request))):\n self.stop(key, ticker.get_config())\n if self._configuration_service.leader_event.is_set():\n current, _ = self._configuration_service.get_config(\n configurationService.combine_path([\n \"blacklist\",exchange,call,str(args).replace('/','_')\n ]))\n for config in current.values():\n old_ticker_id = config['ticker_id']\n self._configuration_service.del_config(\n configurationService.combine_path([\n \"blacklist\",exchange,call,str(args).replace('/','_')\n ]),\n old_ticker_id)\n self._configuration_service.put_config(\n configurationService.combine_path([\n \"blacklist\",exchange,call,str(args).replace('/','_')\n ]),\n ticker_id, \n request)\n status = {**request, **{\n \"id\" : key,\n \"result\": \"blacklist\"\n }}\n self._status_producer.send(key=key, value=status) \n\n def whitelist(self, key, request):\n exchange = request['exchange']\n call = request['call']\n args = request['args']\n request[\"processor_id\"] = self._processor_id\n if self._configuration_service.leader_event.is_set():\n current, _ = self._configuration_service.get_config(\n configurationService.combine_path([\n \"blacklist\",exchange,call,str(args).replace('/','_')\n ]))\n for config in current.values():\n old_ticker_id = config['ticker_id']\n self._configuration_service.del_config(\n configurationService.combine_path([\n \"blacklist\",exchange,call,str(args).replace('/','_')\n ]),\n old_ticker_id)\n status = {**request, **{\n \"id\" : key,\n \"result\": \"whitelist\"\n }}\n self._status_producer.send(key=key, value=status)\n\n def _check_blacklisted(self, request):\n exchange = request['exchange']\n call = request['call']\n args = request['args']\n request_key = get_ticker_key(request)\n current, _ = self._configuration_service.get_config(\n configurationService.combine_path([\n \"blacklist\",exchange,call,str(args).replace('/','_')\n ]))\n blacklisted = False\n for config in current.values():\n blacklist_key = get_ticker_key(config)\n if request_key == blacklist_key:\n blacklisted = True\n break\n return blacklisted\n\n def start(self, key, request):\n ticker_id = request['ticker_id']\n if self._check_blacklisted(request):\n status = {**request, **{\n \"id\" : key,\n \"processor_id\" : self._processor_id,\n \"result\": \"blacklisted\"\n }}\n else:\n if ticker_id in self._list_ticker_ids():\n self._get_ticker(ticker_id).stop(deregister=True)\n self._upsert_ticker(ticker_id, TickerProducer(\n self._request_producer,\n self._status_producer, \n self._configuration_service,\n **{**request, **{\n \"processor_id\" : self._processor_id\n }}))\n self._get_ticker(ticker_id).start()\n status = self._get_ticker(ticker_id).get_config()\n status = {**status, **{\n \"id\" : key,\n \"result\": \"start\"\n }}\n self._status_producer.send(key=key, value=status)\n\n def stop(self, key, request):\n ticker_id = request['ticker_id']\n if ticker_id in self._list_ticker_ids():\n self._get_ticker(ticker_id).stop(deregister=True)\n status = {\n \"id\" : key,\n \"result\": \"stop\",\n \"ticker_id\" : ticker_id,\n \"processor_id\" : self._processor_id\n }\n self._remove_ticker_by_id(ticker_id)\n else: \n status = {\n \"id\" : key,\n \"result\" : \"ticker_id_not_found\",\n \"error\" : True,\n \"ticker_id\" : ticker_id,\n \"processor_id\" : self._processor_id\n }\n self._status_producer.send(key=key, value=status)\n\n def list(self, key, request):\n status = {\n \"id\" : key,\n \"processor_id\" : self._processor_id,\n \"result\" : \"list\", \n \"ticker_id\" : list(self._list_ticker_ids())\n }\n self._status_producer.send(key=key, value=status)\n\n def getconfig(self, key, request):\n ticker_id = request['ticker_id']\n if ticker_id in self._list_ticker_ids():\n status = self._get_ticker(ticker_id).put_config()\n status = {**status, **{\n \"id\" : key,\n \"result\": \"config\"\n }}\n else:\n status = {\n \"id\" : key,\n \"result\": \"ticker_id_not_found\",\n \"error\" : True,\n \"ticker_id\" : ticker_id,\n \"processor_id\" : self._processor_id\n }\n self._status_producer.send(key=key, value=status)\n\n def _send_status_error(self, msg, key, request, exception, trace):\n try:\n if isinstance(key, bytes):\n try:\n key = uuid.UUID(bytes=key)\n except:\n key = str(key) \n status = {\n \"id\" : key,\n \"result\" : \"exception\",\n \"details\" : {\n \"exception\" : str(exception),\n \"type\" : str(type(exception)),\n \"trace\" : str(trace),\n \"request\" : request,\n \"message\" : msg\n },\n \"error\" : True,\n \"processor_id\" : self._processor_id\n }\n self._status_producer.send(key=key, value=status)\n except Exception as ex:\n logging.error(\"Error sending status\") \n logging.debug(ex) \n logging.debug(traceback.format_exc()) \n \n\n\n\n@click.command()\n@click.option('-b', '--bootstrap_servers', envvar='BOOTSTRAP_SERVERS', help='Kafka Servers')\n@click.option('-c', '--control_topic', envvar='CONTROL_TOPIC', default=CONTROL_REQUEST_TOPIC, help='Control Topic')\n@click.option('-cid', '--control_id', envvar='CONTROL_ID', default=str(uuid.uuid1()), help='Control Id')\n@click.option('-s', '--status_topic', envvar='STATUS_TOPIC', default=STATUS_TOPIC, help='Status Topic')\n@click.option('-r', '--request_topic', envvar='REQUEST_TOPIC', default=REQUEST_MARKET_DATA_TOPIC, help='Request Data Topic')\n@click.option('-eh', '--etcd_host', envvar='ETCD_HOST', default=configurationService.DEFAULT_HOST, help='etcd host')\n@click.option('-ep', '--etcd_port', envvar='ETCD_PORT', default=configurationService.DEFAULT_PORT, help='etcd port')\n@click.option('-er', '--etcd_root', envvar='ETCD_ROOT', default=configurationService.DEFAULT_ETCD_ROOT, help='etcd root')\ndef start_contoller(bootstrap_servers, control_topic, control_id, status_topic, request_topic,\n etcd_host, etcd_port, etcd_root):\n '''\n Producer for periodic requests.\n Listenes to CONTROL_TOPIC for requests on starting and controlling producers.\n Producers are sending periodic requests on REQUEST_TOPIC topic\n '''\n CONTROL_REQUEST_CONSUMER = simpleConsumer.Consumer(**{\n \"subscribe.topics\" : [control_topic],\n \"value.deserializer\" : simpleConsumer.value_deserializer,\n \"bootstrap.servers\" : bootstrap_servers,\n 'group.id': control_id\n })\n REQUEST_MARKET_DATA_PRODUCER = simpleProducer.Producer(**{\n \"value.serializer\" : simpleProducer.value_serializer,\n \"bootstrap.servers\" : bootstrap_servers,\n \"send.topic\" : request_topic\n })\n STATUS_PRODUCER = simpleProducer.Producer(**{\n \"value.serializer\" : simpleProducer.value_serializer,\n \"bootstrap.servers\" : bootstrap_servers,\n \"send.topic\" : status_topic\n })\n\n try:\n processor = RequestProcessor(\n control_consumer=CONTROL_REQUEST_CONSUMER, \n request_producer=REQUEST_MARKET_DATA_PRODUCER,\n status_producer=STATUS_PRODUCER,\n etcd_host=etcd_host,\n etcd_port=etcd_port,\n etcd_root=etcd_root) \n processor._start()\n processor._thread.join()\n except Exception as ex: \n logging.error(ex) \n logging.debug(traceback.format_exc()) \n finally:\n STOP_THREADS.set()\n for ticker in processor._list_ticker():\n ticker._thread.join()\n processor._thread.join()\n processor._executor.shutdown()\n\ndef exit_gracefully(signum = None, frame = None):\n STOP_THREADS.set()\n\nif __name__ == '__main__':\n signal.signal(signal.SIGINT, exit_gracefully)\n signal.signal(signal.SIGTERM, exit_gracefully)\n \n start_contoller() # pylint: disable=no-value-for-parameter\n","sub_path":"src/tickerRequestProducer.py","file_name":"tickerRequestProducer.py","file_ext":"py","file_size_in_byte":16745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"225067412","text":"import logging\nimport os\nfrom train import main as train, define_flags\nfrom evaluate import main as test\nimport datetime\nimport json\nimport tensorflow as tf\nfrom gensim.test.utils import get_tmpfile\nfrom gensim.models.callbacks import CallbackAny2Vec\n\n\nclass EpochSaver(CallbackAny2Vec):\n\n def __init__(self, path_prefix):\n self.path_prefix = path_prefix\n self.epoch = 0\n\n def on_epoch_begin(self, model):\n print(\"Epoch #{} start\".format(self.epoch))\n\n def on_epoch_end(self, model):\n if self.epoch in [1, 5, 10, 15, 20]:\n output_path = get_tmpfile('{}_epoch{}.model'.format(self.path_prefix, self.epoch))\n model.save(output_path)\n print('model save')\n print(\"Epoch #{} end\".format(self.epoch))\n self.epoch += 1\n\nCONFIG_FILE = 'config.json'\nflags = tf.flags\n\ndef main():\n config_dict = import_config_settings()\n logs_folder = config_dict['logs_folder']\n data_sets_folder = config_dict['data_sets_folder']\n trained_models_folder = config_dict['trained_models_folder']\n\n for model in config_dict['models']:\n logger = logger_for_print(folder=logs_folder, file_name=config_dict['data_sets_folder'])\n\n fasttext_model_path = model['fasttext_model_path']\n\n #copy_data_files(data_folder=data_sets_folder + model['data_set'])\n data_set = model['data_set']\n del_all_flags(tf.flags.FLAGS)\n trained_model_folder = trained_models_folder + '/' + data_set + '_' + str(datetime.datetime.now().strftime('%Y-%m-%d--%H-%M-%S'))\n # define train cofidg with static and dynamic values from config.json\n\n define_flags(\n data_dir=data_sets_folder + '/' + data_set,\n train_dir=trained_model_folder,\n fasttext_model_path=fasttext_model_path,\n embedding=model['embedding'],\n max_epochs=model['max_epochs'],\n rnn_size=model['rnn_size'],\n rnn_layers=model['rnn_layers'],\n highway_layers=model['highway_layers']\n )\n if model['training']:\n train(logger)\n if model['testing']:\n checkpoint_file = checkpoint_file_from_number(model, trained_model_folder)\n logger(\"test on model file : \" + str(checkpoint_file))\n if not checkpoint_file:\n break\n checkpoint_file = checkpoint_file.replace(\".index\", \"\")\n tf.flags.DEFINE_string('load_model_for_test', checkpoint_file,\n '(optional) filename of the model to load. Useful for re-starting training from a checkpoint')\n test(logger)\n\n\ndef checkpoint_file_from_number(model, trained_model_folder):\n if model[\"checkpoint_file_for_test\"]:\n return model[\"checkpoint_file_for_test\"]\n\n files_list = os.listdir(trained_model_folder)\n if not model['checkpoint_number_for_test_or_null_for_last_checkpoint'] and model['training']:\n print(\"testing last checkpoint from training folder : \" + str(trained_model_folder))\n index_numbers_list = list()\n for file in files_list:\n if \".index\" in file:\n index_numbers_list.append(int(file.split('_')[0].split('h')[1]))\n last_checkpoint_number = max(index_numbers_list)\n for file in files_list:\n if \".index\" in file and str(last_checkpoint_number) in file.split('_')[0]:\n return trained_model_folder + file\n\n elif model['checkpoint_number_for_test_or_null_for_last_checkpoint']:\n for file in files_list:\n if \".index\" in file and str(model['checkpoint_number_for_test_or_null_for_last_checkpoint']) in file.split('_')[0]:\n return trained_model_folder + file\n print(\"checkpoint_number_for_test: \" + str(model['checkpoint_number_for_test_or_null_for_last_checkpoint']) + \"Not Found\")\n return None\n else:\n print(\"checkpoint_number_for_test is missing\")\n\n return None\n\n\ndef import_config_settings():\n with open(CONFIG_FILE) as json_file:\n return json.load(json_file)\n\n\ndef del_all_flags(FLAGS):\n flags_dict = FLAGS._flags()\n keys_list = [keys for keys in flags_dict]\n for keys in keys_list:\n FLAGS.__delattr__(keys)\n\n\ndef logger_for_print(folder='', file_name='logger'):\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n logger = logging.getLogger()\n date = str(datetime.datetime.now()).replace(':', '_').replace('.', '_')\n logger.addHandler(logging.FileHandler(folder + '\\\\' + file_name + date+'.log', 'a'))\n return logger.info\n\n\ndef copy_data_files(data_folder):\n root_folder = os.getcwd()\n os.system('robocopy ' + data_folder + ' ' + root_folder + '/data')\n return\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"network_handler.py","file_name":"network_handler.py","file_ext":"py","file_size_in_byte":4764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"235557583","text":"from .models import Jornada, Apontamento,TotalApotamentoDia\nfrom datetime import datetime\n\ndef calcularSaldoMinutos(horaApontamento,horaJornada):\n\ttotal = datetime.combine(datetime.today(), horaJornada) - datetime.combine(datetime.today(), horaApontamento)\n\treturn total.days * 1440 + total.seconds / 60\n\ndef calcularDia(apontamentos,jornada):\n\tsaldo = 0\n\t\n\tif len(apontamentos) == 4:\n\t\tatime = apontamentos[0].datahora.time().replace(second=0, microsecond=0)\n\t\tjtime = jornada.entrada.replace(second=0, microsecond=0)\n\t\tsaldoEntrada = calcularSaldoMinutos(atime,jtime)\n\t\tif saldoEntrada < 0 or saldoEntrada > 5:\n\t\t\tsaldo += saldoEntrada\n\n\t\tminutosIntervalo = calcularSaldoMinutos(jornada.saida_intervalo,jornada.entrada_intervalo)\n\t\tsaidaInt = apontamentos[1].datahora.time().replace(second=0, microsecond=0)\n\t\tentradaInt = apontamentos[2].datahora.time().replace(second=0, microsecond=0)\n\t\tminutosApontados = calcularSaldoMinutos(saidaInt,entradaInt)\n\t\tif (minutosIntervalo - minutosApontados) > 10:\n\t\t\tsaldo += (minutosIntervalo - minutosApontados)\n\t\telif (minutosIntervalo - minutosApontados) < 0:\n\t\t\tsaldo += (minutosIntervalo - minutosApontados)\n\n\t\tatime = apontamentos[3].datahora.time().replace(second=0, microsecond=0)\n\t\tjtime = jornada.saida.replace(second=0, microsecond=0)\n\t\tsaldoSaida = calcularSaldoMinutos(jtime,atime)\n\t\tif saldoSaida < 0 or saldoSaida > 5:\n\t\t\tsaldo += saldoSaida\n\t\treturn saldo\n\telse:\n\t\treturn 0;\n\ndef salvarSaldoDia(dataCalculo,usuarioLogado):\n\tapontamentos = Apontamento.objects.filter(usuario=usuarioLogado,datahora__contains=dataCalculo).order_by('datahora')\n\tjornada = Jornada.objects.get(usuario=usuarioLogado)\n\tsaldo = calcularDia(apontamentos,jornada)\n\ttry:\n\t\ttotalAponta = TotalApotamentoDia.objects.get(usuario=usuarioLogado,datahora__contains=dataCalculo)\n\texcept:\n\t\ttotalAponta = None\n\tif totalAponta:\n\t\ttotalAponta.minutos=saldo\n\t\ttotalAponta.save()\n\telse:\n\t\tt = TotalApotamentoDia(usuario=usuarioLogado,datahora=dataCalculo,minutos=saldo)\n\t\tt.save()\n","sub_path":"horario/calculo.py","file_name":"calculo.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"314046899","text":"\n \n\"\"\"\nThis is a text adventure game that takes you around a vault in the Fallout Universe\n\"\"\"\n# Vault Room descriptions\nroom_list = []\nroom = [\"This area where you begin is the known as the entrance of the Vault 101. You see two doors: \"\n \"\\none to your left and the other down the room. Enjoy the Tour!\", None, None, 5, 1]\nroom_list.append(room)\nroom = [\"You are in the main hallway of the Vault 101\"\n \"\\nThis is where majority of the traffic happens day to day in the vault.\", None, 0, 4, 2]\nroom_list.append(room)\nroom = [\"You are in Science Department brought to you by Vault-tec\"\n \"\\nIn this place is where our scientist find create innovated ways to survive in the Nuclear Wasteland.\"\n \"\\nYou see two doors, one on the south and the other one in the west.\", None, 1, 3, None]\nroom_list.append(room)\nroom = [\"You are in Sleeping Quarters, the comfiest place in this Vault-tec facility. \"\n \"\\nThis place can house up to 100 vault dweller in the most modern yet comfortable living space.\"\n \"\\nYou see two doors, one on the south and the other one in the west.\", 2, 4, 6, None]\nroom_list.append(room)\nroom = [\"You are in the Workshop area in Vault-tec.\"\n \"\\nThis is where the explorers bring their items from wasteland for. \"\n \"\\nOur thinkers are able to convert these items into something of use like Pipe guns, traps, body armor, etc. \"\n \"You see four different doors around you.\", 1, 5, 7, 3]\nroom_list.append(room)\nroom = [\"You are in the Power and water purification station \"\n \"\\nWithout this room, our vault would have died a long time ago. It's a maximum priority to maintain it. \"\n \"\\nYou see two doors; one will take you to the entrance of the vault and the other to different place. \",\n 0, None, None, 4]\nroom_list.append(room)\nroom = [\"Your are in the Medical Bay. \"\n \"\\n Any recent injury, have a bad stomach, or you're curious about your health overall.\"\n \"\\nDr.Craven is willing to take a look at anyone for the price of few caps.\", 3, 7, None, None]\nroom_list.append(room)\nroom = [\"You in the Greenhouse sponsored by Vault-tec \"\n \"\\nThis is where we are able to grow food in a controlled environment since the land outside is glassed.\"\n \"\\nWe grow Corn,Squash,Tomatoes,Beans,Chile, and many more plants. \", 4, 8, None, 6]\nroom_list.append(room)\nroom = [\"You are in the Dinning Hall \"\n \"\\nThis is where our vault dwellers come and eat every breakfast, lunch, and dinner.\"\n \"\\nThat concludes our tour of our beautiful Vault.\"\n \"\\nSee you again soon! \", None, 9, None, 7]\nroom_list.append(room)\nroom = [\"Thank you for coming to our tour and please on the way out stop by the gift shop.\"\n \"\\nPlease enter the command 'Quit' to take your VR headset off.\", None, None, None, None]\nroom_list.append(room)\n\ncurrent_room = 0\n# Instructions\nprint('Welcome traveler to our special tour of Vault 101')\nprint('Enter one of the following commands and enjoy the tour:')\nprint(\"- North\")\nprint(\"- South\")\nprint(\"- West\")\nprint(\"- East\")\nprint(\"- Quit\")\n\ndone = False\nwhile not done:\n print()\n print(room_list[current_room][0])\n user_input = input(\"Where do you want to go now?: \")\n\n if user_input.upper() == \"Quit\" or user_input.upper() == \"Q\":\n done = True\n\n elif user_input.upper() == \"North\" or user_input.upper() == \"N\":\n next_room = room_list[current_room][1]\n if next_room is None:\n print(\"You can't go that way!\")\n if next_room is not None:\n current_room = next_room\n\n elif user_input.upper() == \"East\" or user_input.upper() == \"E\":\n next_room = room_list[current_room][2]\n if next_room is None:\n print(\"You can't go that way!\")\n if next_room is not None:\n current_room = next_room\n\n elif user_input.upper() == \"South\" or user_input.upper() == \"S\":\n next_room = room_list[current_room][3]\n if next_room is None:\n print(\"You can't go that way!\")\n if next_room is not None:\n current_room = next_room\n\n elif user_input.upper() == \"West\" or user_input.upper() == \"W\":\n next_room = room_list[current_room][4]\n if next_room is None:\n print(\"You can't go that way!\")\n if next_room is not None:\n current_room = next_room\n\n else:\n print(\"Wrong command, please try again.\")\n","sub_path":"Lab 06 - Text Adventure/lab_06.py","file_name":"lab_06.py","file_ext":"py","file_size_in_byte":4429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"100113281","text":"import string\nimport operator\n\ndef get_file_text_list():\n filename = input(\"Enter name of file: \")\n with open(filename) as f:\n a_string = f.read()\n a_string = a_string.strip(\"\\n\")\n for i in string.punctuation: #[\",\",\".\",\"?\",\"!\",\":\",\";\",'\"']:\n a_string = a_string.replace(i,\"\")\n return a_string.split()\n\ndef make_key_tuples(a_list):\n key_tuple_list = []\n for index, value in enumerate(a_list):\n try:\n key_tuple_list.append((value,a_list[index+1]))\n except:\n None\n return key_tuple_list\n\ndef count_bigrams(a_tuple_list):\n count_dict = {}\n for a_tuple in a_tuple_list:\n if a_tuple in count_dict:\n count_dict[a_tuple] += 1\n else:\n count_dict[a_tuple] = 1\n return count_dict\n\ndef sorted_list(a_dict):\n sorted_list = sorted(a_dict.items(), key=operator.itemgetter(1))\n return sorted_list\n\n\nword_list = get_file_text_list()\nlower_word_list = [i.lower() for i in word_list]\nkey_list = make_key_tuples(lower_word_list)\nthe_dict = count_bigrams(key_list)\nsorted_list = sorted_list(the_dict)\nprint(sorted_list[-10:][::-1])\n\n\n\n\n\n","sub_path":"Tímaverkefni/Assignment 15/15.3.py","file_name":"15.3.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"636627831","text":"\"\"\"\n最优打字策略\n时间限制:C/C++语言 1000MS;其他语言 3000MS\n内存限制:C/C++语言 65536KB;其他语言 589824KB\n题目描述:\n在英文的输入中,我们经常会遇到大小写切换的问题,频繁切换大小写会增加我们的按键次数,也会降低我们的打字效率。\n\n众所周知,切换大小写有两种方式,一种是按下“caps locks”,也就是大写锁定键,这样一来,之后的输入模式都会被切换。\n另一种是同时按下shift和需要打印的字母,可以临时切换大小写(算作按下两个键)。\n\n已知初始状态下,打字模式是小写,现在给出需要打印的字符串(区分大小写),请你计算出最少需按键多少次才能打印出来。\n\n输入\n输入第一行仅包含一个正整数n,表示字符串的长度(1<=n<=1000000)。\n输入第二行包含一个长度为n的字符串,仅包含大小写字母。\n输出\n输出仅包含一个正整数,即最少的按键次数。\n\n样例输入\n6\nAaAAAA\n样例输出\n8\n\n\"\"\"\nimport heartrate\nimport sys\nheartrate.trace(browser=True)\nn = int(input())\na_str = input()\n\ncount = 0\n\nlength = n\nstatus = 0\nfor i in range(length):\n s = a_str[i]\n if 'a' <= s <= 'z':\n if status == 0:\n count += 1\n else:\n count1 = 0\n for i in a_str[i + 1:i + 4]:\n if 'a' <= i <= 'z':\n count1 += 1\n if count1 >= 2:\n status = 0\n count += 2\n else:\n count += 2\n else:\n if status == 1:\n count += 1\n else:\n count2 = 0\n for i in a_str[i+1:i+4]:\n if 'A' <= i <= 'Z':\n count2+=1\n if count2 >=2:\n status = 1\n count += 2\n else:\n count += 2\n\n\n\nsys.stdout.write(str(count))\n\n\n\n","sub_path":"笔试题/打字策略.py","file_name":"打字策略.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"548522975","text":"#-------------------------------------------------------------------------------\n# Name: usgs_earthquake_event_pinger.py\n# Purpose: Check USGS database of \"Significant Events\" that have occurred\n# in the last week, if any events have been added, download and\n# extract ShakeMap shapefiles to a specified local folder.\n#\n# Author: Madeline Jones,\n# New Light Technologies, Inc\n# madeline.jones@nltgis.com\n#\n# Created: 04/26/2017\n# Last update: 10/15/2018\n#\n#-------------------------------------------------------------------------------\n\n# USGS ShakeMap Import Script - modified from:\n# https://gist.github.com/mhearne-usgs/6b040c0b423b7d03f4b9\n# Live feeds are found here:\n# http://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson.php\n\n\n# Modify Proxy Settings when inside a secure/government network\n#os.environ[\"HTTP_PROXY\"] = \"\"\n#os.environ[\"HTTPS_PROXY\"] = \"\"\n\n\n# Imports\nimport arcpy\ntry:\n from urllib2 import urlopen\nexcept:\n from urllib.request import urlopen\nfrom within_usa import check_within_us\nimport json\nimport sys\nimport os\nimport zipfile\nimport StringIO\nimport datetime, time\nimport shutil\nfrom log_earthquake import log\n\n\ndef get_FEEDURL_as_json_dictionary(FEEDURL): # Get the list of event IDs in the current feed\n fh = urlopen(FEEDURL) # open a URL connection to the event feed.\n data = fh.read() # read all of the data from that URL into a string\n fh.close()\n jdict = json.loads(data) # Parse that data using the stdlib json module. This turns into a Python dictionary.\n\n return jdict\n\n\ndef get_eventID_list(jdict): # Get list of USA event IDs in FEEDURL\n eqIDlist = {}\n for earthquake in jdict['features']:\n epiX = earthquake['geometry']['coordinates'][0]\n epiY = earthquake['geometry']['coordinates'][1]\n\n # check to see if earthquake is within continental US\n if check_within_us(epiX, epiY) is True:\n time = str(earthquake['properties']['time'])\n eventid = earthquake['id']\n updated = str(earthquake['properties']['updated'])\n\n eqIDlist.update({earthquake['id']:\\\n [earthquake['geometry']['coordinates'][0], # epiX\n earthquake['geometry']['coordinates'][1], # epiY\n earthquake['geometry']['coordinates'][2], # depth\n str(earthquake['properties']['title']), # title\n earthquake['properties']['mag'], # magnitude\n str(earthquake['properties']['time']), # time\n datetime.datetime.fromtimestamp(int(time[:-3])).strftime('%c'), # time_\n str(earthquake['properties']['place']), # place\n str(earthquake['properties']['url']), # url\n str(eventid), # eventid\n str(earthquake['properties']['status']), #status\n str(earthquake['properties']['updated']), # updated\n datetime.datetime.fromtimestamp(int(updated[:-3])).strftime('%c'), # updated_\n earthquake['properties']['detail']] # event url\n })\n else:\n continue\n\n return eqIDlist\n\n\ndef download_shakemap_zips(eqIDlist, filepath):\n EventFilePaths = []\n for event, keys in eqIDlist.items():\n print('Event ID: {}'.format(event))\n\n epiX = keys[0]\n epiY = keys[1]\n depth = keys[2]\n title = keys[3]\n mag = keys[4]\n time = keys[5]\n time_ = keys[6]\n place = keys[7]\n url = keys[8]\n eventid = keys[9]\n status = keys[10]\n updated = keys[11]\n updated_ = keys[12]\n eventurl = keys[13]\n\n fh = urlopen(eventurl) # open event-specific url\n data = fh.read() # read event data into a string\n fh.close()\n jdict2 = json.loads(data) # and parse using json module as before\n if 'shakemap' not in jdict2['properties']['products'].keys():\n print('Event {} does not have a ShakeMap product associated with it. Exiting.'.format(event))\n continue\n shakemap = jdict2['properties']['products']['shakemap'][0] # get the first shakemap associated with the event\n shapezipurl = shakemap['contents']['download/shape.zip']['url'] # get the download url for the shape zipfile\n epicenterurl = shakemap['contents']['download/epicenter.kmz']['url']\n\n # EXTRACT SHAKEMAP ZIP FILE IN NEW FOLDER\n\n # Here, read the binary zipfile into a string\n print(shapezipurl)\n fh = urlopen(shapezipurl)\n data = fh.read()\n fh.close()\n\n # Create a StringIO object, which behaves like a file\n stringbuf = StringIO.StringIO(data)\n eventdir = \"{}\\{}\".format(filepath, str(eventid))\n\n # Creates a new folder (called the eventid) if it does not already exist\n if not os.path.isdir(eventdir):\n os.mkdir(eventdir)\n print(\"Folder created for Event ID: {}\".format(eventid))\n\n # Create a StringIO object, which behaves like a file\n stringbuf = StringIO.StringIO(data)\n eventdir = \"{}\\{}\".format(filepath, str(eventid))\n\n # Create a ZipFile object, instantiated with our file-like StringIO object.\n # Extract all of the data from that StringIO object into files in the provided output directory.\n myzip = zipfile.ZipFile(stringbuf, 'r', zipfile.ZIP_DEFLATED)\n myzip.extractall(eventdir)\n myzip.close()\n stringbuf.close()\n\n f = open(eventdir+\"\\\\eventInfo.txt\",\"w+\")\n f.write(\"{}\\r\\n{}\\r\\n\".format(status,updated))\n f.close()\n\n # Update empty point with epicenter lat/long\n pnt = arcpy.Point()\n pnt.X = epiX\n pnt.Y = epiY\n\n # Add fields to Epicenter shapefile\n arcpy.CreateFeatureclass_management(eventdir, \"Epicenter\", \"POINT\", \"\", \"\", \"\", 4326)\n arcpy.AddField_management(\"{}\\Epicenter.shp\".format(eventdir), \"Title\", \"TEXT\", \"\", \"\", \"\", \"Event\")\n arcpy.AddField_management(\"{}\\Epicenter.shp\".format(eventdir), \"Mag\", \"FLOAT\", \"\", \"\", \"\", \"Magnitude\")\n arcpy.AddField_management(\"{}\\Epicenter.shp\".format(eventdir), \"Date_Time\", \"TEXT\", \"\", \"\", \"\", \"Date/Time\")\n arcpy.AddField_management(\"{}\\Epicenter.shp\".format(eventdir), \"Place\", \"TEXT\", \"\", \"\", \"\", \"Place\")\n arcpy.AddField_management(\"{}\\Epicenter.shp\".format(eventdir), \"Depth_km\", \"FLOAT\", \"\", \"\", \"\", \"Depth (km)\")\n arcpy.AddField_management(\"{}\\Epicenter.shp\".format(eventdir), \"Url\", \"TEXT\", \"\", \"\", \"\", \"Url\")\n arcpy.AddField_management(\"{}\\Epicenter.shp\".format(eventdir), \"EventID\", \"TEXT\", \"\", \"\", \"\", \"Event ID\")\n arcpy.AddField_management(\"{}\\Epicenter.shp\".format(eventdir), \"Status\", \"TEXT\", \"\", \"\", \"\", \"Status\")\n arcpy.AddField_management(\"{}\\Epicenter.shp\".format(eventdir), \"Updated\", \"TEXT\", \"\", \"\", \"\", \"Updated\")\n\n # Add earthquake info to Epicenter attribute table\n curs = arcpy.da.InsertCursor(\"{}\\Epicenter.shp\".format(eventdir),\n [\"Title\", \"Mag\", \"Date_Time\", \"Place\",\n \"Depth_km\", \"Url\", \"EventID\", \"Status\", \"Updated\"])\n curs.insertRow((title, mag, time_, place, depth, url, eventid, status, updated_))\n del curs\n\n # Add XY point data to Epicenter shapefile\n with arcpy.da.UpdateCursor(\"{}\\Epicenter.shp\".format(eventdir),\"SHAPE@XY\") as cursor:\n for eq in cursor:\n eq[0] = pnt\n cursor.updateRow(eq)\n\n filelist = os.listdir(eventdir)\n print('ShakeMap files extracted for Event ID: {} to folder: {}'.format(eventid, eventdir))\n EventFilePaths.append(eventdir)\n\n h = open(filepath+\"\\\\eventlog.txt\",\"a+\")\n h.write(\"{}\\r\\n\".format(eventdir))\n h.close()\n\n\n\n return EventFilePaths\n\n\ndef post_processing(filepath):\n eventlog = filepath+\"\\\\eventlog.txt\"\n h = open(eventlog,\"r\")\n events = h.read().splitlines()\n h.close()\n\n if os.path.exists(r\"C:\\ShakeMaps\\ShakeMaps_PastWeek.gdb\"):\n arcpy.env.workspace = r\"C:\\ShakeMaps\\ShakeMaps_PastWeek.gdb\"\n OldEvents = arcpy.ListFeatureClasses()\n for OldEvent in OldEvents:\n arcpy.Delete_management(OldEvent)\n else:\n arcpy.CreateFileGDB_management(r\"C:\\ShakeMaps\", \"ShakeMaps_PastWeek\")\n arcpy.env.workspace = r\"C:\\ShakeMaps\\ShakeMaps_PastWeek.gdb\"\n\n if len(events) > 1:\n epicenterList = []\n for e in events:\n epicenterList.append(e+\"\\\\Epicenter.shp\")\n arcpy.Merge_management(epicenterList, \"Epicenters\")\n else:\n arcpy.CopyFeatures_management(events[0]+\"\\\\Epicenter.shp\",\"Epicenters\")\n\n mmiList = []\n for e in events:\n arcpy.Dissolve_management(e+\"\\\\mi.shp\",e+\"\\\\mi_dissolved.shp\",\"PARAMVALUE\",\"\",\"MULTI_PART\")\n arcpy.AddField_management(e+\"\\\\mi_dissolved.shp\",\"EventID\",\"TEXT\")\n arcpy.CalculateField_management(e+\"\\\\mi_dissolved.shp\",\"EventID\",\"'{}'\".format(e.split(\"\\\\\")[-1]), \"PYTHON\")\n arcpy.JoinField_management(e+\"\\\\mi_dissolved.shp\",\"EventID\",e+\"\\\\Epicenter.shp\",\"EventID\",[\"Title\"])\n if len(events) > 1:\n mmiList.append(e+\"\\\\mi_dissolved.shp\")\n\n if len(events) > 1:\n arcpy.Merge_management(mmiList, \"ShakeMaps_MMI\")\n else:\n arcpy.CopyFeatures_management(events[0] + \"\\\\mi_dissolved.shp\", \"ShakeMaps_MMI\")\n\ndef main(filepath, FEEDURL):\n tic = time.time()\n print('Running Earthquake Event Pinger.')\n\n if not os.path.exists(filepath):\n os.mkdir(filepath)\n elif os.path.exists(filepath):\n shutil.rmtree(filepath)\n os.mkdir(filepath)\n if os.path.exists(filepath+\"\\\\eventlog.txt\"):\n os.remove(filepath+\"\\\\eventlog.txt\")\n if not os.path.exists(filepath + \"\\\\run_log.txt\"):\n f = open(filepath + \"\\\\run_log.txt\", \"w+\")\n f.close()\n\n log(filepath, 'Checking FEEDURL.')\n\n try:\n jdict = get_FEEDURL_as_json_dictionary(FEEDURL)\n except:\n print('Internet connection problem.')\n log(filepath, 'ERROR: Internet connection problem.')\n sys.exit(1)\n\n eqIDlist = get_eventID_list(jdict)\n\n if len(eqIDlist) == 0:\n print('No new events available in USGS FEEDURL. Exiting.')\n log(filepath, 'No new events.')\n sys.exit(1)\n else:\n print(\"New earthquake events found: {}\".format(len(eqIDlist)))\n log(filepath, 'New earthquake events found.')\n\n # Download ShakeMaps for all new and updated events, return list of new folders\n EventFilePaths = download_shakemap_zips(eqIDlist, filepath)\n\n print(\"Completed Running Earthquake Event Pinger.\")\n log(filepath, 'Updates complete.')\n toc = time.time()\n print('Time elapsed: {} seconds'.format(toc - tic))\n\n post_processing(filepath)\n\n return EventFilePaths\n\n\nif __name__ == '__main__':\n # Set filepath to save ShakeMap files in\n filepath = r\"C:\\ShakeMaps\\WebService\"\n # Select FEEDURL - only uncomment ONE of these - from here: http://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson.php\n #FEEDURL = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_week.geojson' # Significant Events - 1 week\n #FEEDURL = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_hour.geojson' #1 hour M4.5+\n #FEEDURL = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson' #1 day M4.5+\n FEEDURL = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_week.geojson' #7 days M4.5+\n\n main(filepath, FEEDURL)\n","sub_path":"usgs_earthquake_event_pinger_forwebservice.py","file_name":"usgs_earthquake_event_pinger_forwebservice.py","file_ext":"py","file_size_in_byte":12020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"546207856","text":"import os\nfrom logging.config import dictConfig\n\nPROJECT = os.path.dirname(os.path.realpath(__file__))\nPATHS = {\n 'conf_template': '{}/config_template.json'.format(PROJECT),\n 'nimbus_config': '{}/nimbus_config.json'.format(PROJECT),\n 'logs': '{}/logs'.format(PROJECT)\n}\n\n\nLOG_LOCATION = os.path.join(PROJECT, 'logs')\nif not os.path.isdir(LOG_LOCATION):\n os.makedirs(LOG_LOCATION)\n\nLOGGING = {\n 'version': 1,\n 'formatters': {\n 'pretty': {\n 'format': '\\n%(message)s\\n',\n },\n 'standard': {\n 'format': '[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s',\n 'datefmt': '%d/%b/%Y %H:%M:%S'\n },\n 'verbose': {\n 'format': '[%(process)d]: %(levelname)s %(name)s[%(module)s] %(message)s'\n },\n },\n 'handlers': {\n 'null': {\n 'level': 'DEBUG',\n 'class': 'logging.NullHandler',\n },\n 'logfile': {\n 'level': 'INFO',\n 'class': 'logging.handlers.TimedRotatingFileHandler',\n 'filename': '{}/nimbus.log'.format(LOG_LOCATION),\n 'when': 'midnight',\n 'backupCount': 7,\n 'formatter': 'standard',\n },\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'standard'\n },\n 'pretty': {\n 'level': 'INFO',\n 'class': 'logging.StreamHandler',\n 'formatter': 'pretty'\n },\n 'syslog': {\n 'level': 'INFO',\n 'class': 'logging.handlers.SysLogHandler',\n 'formatter': 'verbose',\n 'address': '/dev/log',\n 'facility': 'local2',\n }\n },\n 'loggers': {\n 'urllib3': {\n 'handlers': ['console', 'logfile', 'syslog'],\n 'propagate': True,\n 'level': 'ERROR',\n },\n 'requests': {\n 'handlers': ['console', 'logfile', 'syslog'],\n 'propagate': True,\n 'level': 'ERROR',\n },\n 'nimbus': {\n 'handlers': ['console', 'logfile'],\n 'propagate': False,\n 'level': 'DEBUG',\n },\n 'cloud_slicer': {\n 'handlers': ['pretty'],\n 'propagate': False,\n 'level': 'INFO',\n },\n '': {\n 'handlers': ['console', 'logfile', 'syslog'],\n 'propagate': True,\n 'level': 'DEBUG',\n },\n }\n}\n\ndictConfig(LOGGING)\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"162341742","text":"import scipy.stats\n\nfrom abc import ABCMeta, abstractmethod\n\nfrom crimjustsimpy import Case\n\n\nclass Trial:\n\n def try_case(self, case:Case):\n assert not case.plead\n assert not case.tried\n assert not case.acquitted\n assert not case.convicted\n assert not case.guilty\n\n # Random trial outcome based on probability of a conviction.\n draw = scipy.stats.uniform.rvs()\n if draw < case.prob_convict:\n case.convicted = True\n case.guilty = True\n case.sentence = case.sentence_if_convicted\n else:\n case.acquitted = True\n case.sentence = 0\n\n case.tried = True\n","sub_path":"crimjustsimpy/Trial.py","file_name":"Trial.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"430548514","text":"import serial\r\n\r\nserial_port = '/dev/INSERT SERIAL PORT HERE'\r\nbaud_rate = 9600\r\nwrite_to_file_path = \"serial.txt\"\r\n\r\noutput_file = open(write_to_file_path, \"w+\")\r\nser = serial.Serial(serial_port, baud_rate)\r\nwhile True:\r\n line = ser.readline()\r\n line = line.decode(\"utf-8\")\r\n print(line);\r\n output_file.write(line)","sub_path":"smart-projects/serial_to_file_interpretor.py","file_name":"serial_to_file_interpretor.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"118075752","text":"from django.http.response import JsonResponse\nfrom django.shortcuts import render, redirect\nfrom django.views import View\nfrom .models import CATEGORY_CHOICES, Customer, Product, Cart, Orderplaced\nfrom .forms import CustomerRegistrationForm, CustomerProfileForm\nfrom app import forms\nfrom django.contrib import messages\nfrom django.db.models import Q\nfrom django.http import JsonResponse\n\n\nclass ProductView(View):\n def get(self, request):\n topwears = Product.objects.filter(category='TW')\n bottomwears = Product.objects.filter(category='BW')\n mobiles = Product.objects.filter(category='M')\n return render(request, 'app/home.html', {'topwears': topwears, 'bottomwears': bottomwears, 'mobiles': mobiles})\n\n\nclass ProductDetailView(View):\n def get(self, request, pk):\n product = Product.objects.get(pk=pk)\n return render(request, 'app/productdetail.html', {'product': product})\n\n\ndef add_to_cart(request):\n user = request.user\n product_id = request.GET.get('prod_id')\n product = Product.objects.get(id=product_id)\n Cart(user=user, product=product).save()\n return redirect('/cart')\n\n\ndef show_cart(request):\n if request.user.is_authenticated:\n user = request.user\n cart = Cart.objects.filter(user=user)\n # print(cart)\n amount = 0.0\n shipping_amount = 70.0\n total_amount = 0.0\n cart_product = [p for p in Cart.objects.all() if p.user == user]\n # print(cart_product)\n if cart_product:\n for p in cart_product:\n tempamount = (p.quantity * p.product.discounted_price)\n amount += tempamount\n totalamount = amount + shipping_amount\n\n return render(request, 'app/addtocart.html', {'carts': cart, 'totalamount': totalamount, 'amount': amount})\n\n else:\n return render(request, 'app/emptycart.html')\n\n\ndef plus_cart(request):\n if request.method == 'GET':\n prod_id = request.GET['prod_id']\n print(prod_id)\n c = Cart.objects.get(Q(product=prod_id) & Q(user=request.user))\n c.quantity += 1\n c.save()\n amount = 0.0\n shipping_amount = 70.0\n cart_product = [p for p in Cart.objects.all() if p.user == request.user]\n for p in cart_product:\n tempamount = (p.quantity * p.product.discounted_price)\n amount += tempamount\n data = {\n 'quantity': c.quantity,\n 'amount': amount,\n 'totalamount': amount + shipping_amount\n }\n return JsonResponse(data)\n\ndef minus_cart(request):\n if request.method == 'GET':\n prod_id = request.GET['prod_id']\n print(prod_id)\n c = Cart.objects.get(Q(product=prod_id) & Q(user=request.user))\n c.quantity -= 1\n c.save()\n amount = 0.0\n shipping_amount = 70.0\n cart_product = [p for p in Cart.objects.all() if p.user == request.user]\n for p in cart_product:\n tempamount = (p.quantity * p.product.discounted_price)\n amount += tempamount\n \n data = {\n 'quantity': c.quantity,\n 'amount': amount,\n 'totalamount': amount + shipping_amount\n }\n return JsonResponse(data)\n\n\ndef remove_cart(request):\n if request.method == 'GET':\n prod_id = request.GET['prod_id']\n print(prod_id)\n c = Cart.objects.get(Q(product=prod_id) & Q(user=request.user))\n c.delete()\n amount = 0.0\n shipping_amount = 70.0\n cart_product = [p for p in Cart.objects.all() if p.user == request.user]\n for p in cart_product:\n tempamount = (p.quantity * p.product.discounted_price)\n amount += tempamount\n \n data = {\n 'amount': amount,\n 'totalamount': amount + shipping_amount\n }\n return JsonResponse(data)\n\n\n\n\n\n\n\n\ndef buy_now(request):\n return render(request, 'app/buynow.html')\n\n\ndef address(request):\n add = Customer.objects.filter(user=request.user)\n return render(request, 'app/address.html', {'add': add, 'active': 'btn-primary'})\n\n\ndef orders(request):\n return render(request, 'app/orders.html')\n\n\ndef change_password(request):\n return render(request, 'app/changepassword.html')\n\n\ndef mobile(request, data=None):\n if data == None:\n mobiles = Product.objects.filter(category='M')\n elif data == 'xiaomi' or data == 'samsung':\n mobiles = Product.objects.filter(category='M').filter(brand=data)\n return render(request, 'app/mobile.html', {'mobiles': mobiles})\n\n\ndef topwear(request, data=None):\n if data == None:\n topwears = Product.objects.filter(category='TW')\n return render(request, 'app/topwear.html', {'topwears': topwears})\n\ndef bottomwear(request, data=None):\n if data == None:\n bottomwears = Product.objects.filter(category='BW')\n return render(request, 'app/bottomwear.html', {'bottomwears': bottomwears})\n\n\n\n\n\n\n\n\nclass CustomerRegistrationView(View):\n def get(self, request):\n form = CustomerRegistrationForm()\n return render(request, 'app/customerregistration.html', {'form': form})\n\n def post(self, request):\n form = CustomerRegistrationForm(request.POST)\n if form.is_valid():\n messages.success(\n request, 'Congratulations!! Registered Successfully')\n form.save()\n return render(request, 'app/customerregistration.html', {'form': form})\n\n\ndef checkout(request):\n user = request.user\n add = Customer.objects.filter(user=user)\n cart_items = Cart.objects.filter(user=user)\n amount = 0.0\n shipping_amount = 70.0\n totalamount = 0.0\n cart_product = [p for p in Cart.objects.all() if p.user == request.user]\n if cart_product:\n for p in cart_product:\n tempamount = (p.quantity * p.product.discounted_price)\n amount += tempamount\n totalamount = amount + shipping_amount\n \n\n return render(request, 'app/checkout.html', {'add':add, 'totalamount':totalamount, 'cart_items':cart_items})\n\n\nclass ProfileView(View):\n def get(self, request):\n form = CustomerProfileForm()\n return render(request, 'app/profile.html', {'form': form, 'active': 'btn-primary'})\n\n def post(self, request):\n form = CustomerProfileForm(request.POST)\n if form.is_valid():\n usr = request.user\n name = form.cleaned_data['name']\n locality = form.cleaned_data['locality']\n city = form.cleaned_data['city']\n state = form.cleaned_data['state']\n zipcode = form.cleaned_data['zipcode']\n reg = Customer(user=usr, name=name, locality=locality,\n city=city, state=state, zipcode=zipcode)\n reg.save()\n messages.success(\n request, 'Congratulations!! Profile Updated Successfully')\n return render(request, 'app/profile.html', {'form': form, 'active': 'btn-primary'})\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"382639954","text":"#!./env/bin/python\n# -*- coding: utf-8 -*-\n\nimport requests\ndata = []\nwith open('data.txt', 'r') as f:\n data = f.readlines()\nparams = {\n 'json': True\n }\nfor i in data:\n res = requests.get('http://numbersapi.com/' + i.rstrip() + '/math', params=params)\n res = res.json()\n if res['found'] == True:\n print('Interesting')\n else:\n print('Boring')\n","sub_path":"ls20/ls20.py","file_name":"ls20.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"272948335","text":"import json\nimport logging\nimport os\nimport os.path\nimport re\nimport sys\nimport warnings\nfrom argparse import Namespace\nfrom contextlib import suppress\nfrom datetime import datetime\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, List, NamedTuple, Optional, Sequence, Tuple, Union\n\nimport napari.utils.theme\nimport numpy as np\nfrom napari.qt import get_stylesheet\nfrom napari.utils import Colormap\nfrom napari.utils.theme import get_theme\nfrom napari.utils.theme import template as napari_template\nfrom qtpy.QtCore import QObject, Signal\nfrom qtpy.QtWidgets import QMessageBox, QWidget\n\nfrom PartSeg.common_backend import napari_get_settings\nfrom PartSeg.common_backend.partially_const_dict import PartiallyConstDict\nfrom PartSegCore import register\nfrom PartSegCore.color_image import default_colormap_dict, default_label_dict\nfrom PartSegCore.color_image.base_colors import starting_colors\nfrom PartSegCore.io_utils import find_problematic_entries, load_metadata_base\nfrom PartSegCore.json_hooks import PartSegEncoder\nfrom PartSegCore.project_info import AdditionalLayerDescription, HistoryElement, ProjectInfoBase\nfrom PartSegCore.roi_info import ROIInfo\nfrom PartSegCore.segmentation.algorithm_base import ROIExtractionResult\nfrom PartSegCore.utils import ProfileDict\nfrom PartSegImage import Image\n\nif TYPE_CHECKING: # pragma: no cover\n from napari.settings import NapariSettings\nlogger = logging.getLogger(__name__)\n\nDIR_HISTORY = \"io.dir_location_history\"\nFILE_HISTORY = \"io.files_open_history\"\nMULTIPLE_FILES_OPEN_HISTORY = \"io.multiple_files_open_history\"\nROI_NOT_FIT = \"roi do not fit to image\"\nIO_SAVE_DIRECTORY = \"io.save_directory\"\n\n\nclass ImageSettings(QObject):\n \"\"\"\n Base class for all PartSeg settings. Keeps information about current Image.\n \"\"\"\n\n image_changed = Signal(Image)\n image_path_changed = Signal(str)\n image_channel_count_changed = Signal(int)\n image_spacing_changed = Signal()\n roi_changed = Signal(ROIInfo)\n \"\"\"\n :py:class:`.Signal`\n emitted when roi has changed\n \"\"\"\n roi_clean = Signal()\n additional_layers_changed = Signal()\n\n def __init__(self):\n super().__init__()\n self._image: Optional[Image] = None\n self._image_path = \"\"\n self._roi_info = ROIInfo(None)\n self._additional_layers = {}\n self._parent: Optional[QWidget] = None\n\n def set_parent(self, parent: QWidget):\n self._parent = parent\n\n @property\n def full_segmentation(self): # pragma: no cover\n raise AttributeError(\"full_segmentation not supported\")\n\n @full_segmentation.setter\n def full_segmentation(self, val): # pragma: no cover # pylint: disable=no-self-use\n raise AttributeError(\"full_segmentation not supported\")\n\n @property\n def noise_remove_image_part(self): # pragma: no cover\n raise AttributeError(\"noise_remove_image_part not supported\")\n\n @noise_remove_image_part.setter\n def noise_remove_image_part(self, val): # pragma: no cover # pylint: disable=no-self-use\n raise AttributeError(\"noise_remove_image_part not supported\")\n\n @property\n def additional_layers(self) -> Dict[str, AdditionalLayerDescription]:\n return self._additional_layers\n\n @additional_layers.setter\n def additional_layers(self, val): # pragma: no cover # pylint: disable=no-self-use\n raise AttributeError(\"additional_layers assign not supported\")\n\n @property\n def image_spacing(self):\n \"\"\":py:meth:`Image.spacing` proxy\"\"\"\n return self._image.spacing if self._image is not None else ()\n\n def is_image_2d(self):\n \"\"\":py:meth:`Image.is_2d` proxy\"\"\"\n return self._image is None or self._image.is_2d\n\n @image_spacing.setter\n def image_spacing(self, value):\n if len(value) not in [2, 3]:\n raise ValueError(f\"value parameter should have length 2 or 3. Current length is {len(value)}.\")\n if len(value) == 2:\n self._image.set_spacing((self._image.spacing[0], *list(value)))\n else:\n self._image.set_spacing(value)\n self.image_spacing_changed.emit()\n\n @property\n def segmentation(self) -> np.ndarray: # pragma: no cover\n \"\"\"current roi\"\"\"\n warnings.warn(\"segmentation parameter is renamed to roi\", DeprecationWarning, stacklevel=2)\n return self.roi\n\n @property\n def roi(self) -> np.ndarray:\n \"\"\"current roi\"\"\"\n return self._roi_info.roi\n\n @property\n def segmentation_info(self) -> ROIInfo: # pragma: no cover\n warnings.warn(\"segmentation info parameter is renamed to roi\", DeprecationWarning, stacklevel=2)\n return self.roi_info\n\n @property\n def roi_info(self) -> ROIInfo:\n return self._roi_info\n\n @roi.setter\n def roi(self, val: Union[np.ndarray, ROIInfo]):\n if val is None:\n self._roi_info = ROIInfo(val)\n self._additional_layers = {}\n self.roi_clean.emit()\n return\n try:\n if isinstance(val, np.ndarray):\n self._roi_info = ROIInfo(self.image.fit_array_to_image(val))\n else:\n self._roi_info = val.fit_to_image(self.image)\n except ValueError as e:\n raise ValueError(ROI_NOT_FIT) from e\n self._additional_layers = {}\n self.roi_changed.emit(self._roi_info)\n\n @property\n def sizes(self):\n return self._roi_info.sizes\n\n @property\n def image(self):\n return self._image\n\n @image.setter\n def image(self, value: Image):\n if value is None:\n return\n self._image = value\n if value.file_path is not None:\n self.image_path_changed.emit(value.file_path)\n self._image_changed()\n self._roi_info = ROIInfo(None)\n\n self.image_changed.emit(self._image)\n self.image_channel_count_changed.emit(self._image.channels)\n\n @property\n def has_channels(self):\n return self.channels > 1\n\n def _image_changed(self):\n \"\"\"Reimplement hook for change of main image\"\"\"\n\n @property\n def image_path(self):\n return self._image.file_path if self.image is not None else \"\"\n\n @property\n def image_shape(self):\n # TODO analyse and decide if channels should be part of shape\n return self._image.shape if self.image is not None else ()\n\n @image_path.setter\n def image_path(self, value):\n self._image.file_path = value\n self.image_path_changed.emit(self._image_path)\n\n @property\n def channels(self):\n return 0 if self._image is None else self._image.channels\n\n def components_mask(self):\n return np.array([0] + [1] * np.max(self.roi), dtype=np.uint8)\n\n\nclass ColormapDict(PartiallyConstDict[Colormap]):\n \"\"\"\n Dict for mixing custom colormap with predefined ones\n \"\"\"\n\n if os.path.basename(sys.argv[0]) in [\"sphinx-build\", \"sphinx-build.exe\"]: # pragma: no cover\n const_item_dict = {}\n else:\n const_item_dict = default_colormap_dict\n \"\"\"\n Non removable items for this dict. Current value is :py:data:`default_colormap_dict`\n \"\"\"\n\n @property\n def colormap_removed(self):\n \"\"\"\n Signal that colormap is removed form dict\n \"\"\"\n return self.item_removed\n\n @property\n def colormap_added(self):\n \"\"\"\n Signal that colormap is added to dict\n \"\"\"\n return self.item_added\n\n\nclass LabelColorDict(PartiallyConstDict[list]):\n \"\"\"\n Dict for mixing custom label colors with predefined ones`\n \"\"\"\n\n const_item_dict = default_label_dict\n \"\"\"Non removable items for this dict. Current value is :py:data:`default_label_dict`\"\"\"\n\n def get_array(self, key: str) -> np.ndarray:\n \"\"\"Get labels as numpy array\"\"\"\n return np.array(self[key][0], dtype=np.uint8)\n\n\nclass ViewSettings(ImageSettings):\n colormap_changes = Signal()\n labels_changed = Signal()\n theme_changed = Signal()\n profile_data_changed = Signal(str, object)\n \"\"\"Signal about changes in stored data (set with set_in_profile)\"\"\"\n\n def __init__(self):\n super().__init__()\n self.color_map = []\n self.border_val = []\n self.current_profile_dict = \"default\"\n self.view_settings_dict = ProfileDict()\n self.colormap_dict = ColormapDict(self.get_from_profile(\"custom_colormap\", {}))\n self.label_color_dict = LabelColorDict(self.get_from_profile(\"custom_label_colors\", {}))\n self.cached_labels: Optional[Tuple[str, np.ndarray]] = None\n\n @property\n def theme_name(self) -> str:\n \"\"\"Name of current theme.\"\"\"\n return self.get_from_profile(\"theme\", \"dark\")\n\n @property\n def theme(self):\n \"\"\"Theme as structure.\"\"\"\n try:\n return get_theme(self.theme_name, as_dict=False)\n except TypeError: # pragma: no cover\n theme = get_theme(self.theme_name)\n return Namespace(\n **{k: Color(v) if isinstance(v, str) and v.startswith(\"rgb\") else v for k, v in theme.items()}\n )\n\n @property\n def style_sheet(self):\n return self.get_style_sheet()\n\n def get_style_sheet(self):\n \"\"\"QSS style sheet for current theme.\"\"\"\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", FutureWarning)\n theme = get_theme(self.theme_name, as_dict=True)\n # TODO understand qss overwrite mechanism\n return napari_template(\"\\n\".join(register.qss_list) + get_stylesheet() + \"\\n\".join(register.qss_list), **theme)\n\n @theme_name.setter\n def theme_name(self, value: str):\n \"\"\"Name of current theme.\"\"\"\n if value not in napari.utils.theme.available_themes():\n raise ValueError(f\"Unsupported theme {value}. Supported one: {self.theme_list()}\")\n if value == self.theme_name:\n return\n self.set_in_profile(\"theme\", value)\n self.theme_changed.emit()\n\n @staticmethod\n def theme_list():\n \"\"\"Sequence of available themes\"\"\"\n try:\n return napari.utils.theme.available_themes()\n except: # noqa: E722 # pylint: disable=bare-except # pragma: no cover\n return (\"light\",)\n\n @property\n def chosen_colormap(self):\n \"\"\"Sequence of selected colormap to be available in dropdown\"\"\"\n data = self.get_from_profile(\"colormaps\", starting_colors[:])\n res = [x for x in data if x in self.colormap_dict]\n if len(res) != data:\n if not res:\n res = starting_colors[:]\n self.set_in_profile(\"colormaps\", res)\n return res\n\n @chosen_colormap.setter\n def chosen_colormap(self, val):\n self.set_in_profile(\"colormaps\", val)\n self.colormap_changes.emit()\n\n @property\n def current_labels(self):\n \"\"\"Current labels scheme for marking ROI\"\"\"\n return self.get_from_profile(\"labels_used\", \"default\")\n\n @current_labels.setter\n def current_labels(self, val):\n if val not in self.label_color_dict:\n raise ValueError(f\"Unknown label scheme name '{val}'\")\n self.set_in_profile(\"labels_used\", val)\n self.labels_changed.emit()\n\n @property\n def label_colors(self):\n key = self.current_labels\n if key not in self.label_color_dict:\n key = \"default\"\n self.current_labels = key\n\n if not (self.cached_labels and key == self.cached_labels[0]):\n self.cached_labels = key, self.label_color_dict.get_array(key)\n\n return self.cached_labels[1]\n\n def chosen_colormap_change(self, name, visibility):\n colormaps = set(self.chosen_colormap)\n if visibility:\n colormaps.add(name)\n else:\n with suppress(KeyError):\n colormaps.remove(name)\n # TODO update sorting rule\n self.chosen_colormap = sorted(colormaps, key=self.colormap_dict.get_position)\n\n def get_channel_info(self, view: str, num: int, default: Optional[str] = None) -> str: # pragma: no cover\n warnings.warn(\n \"get_channel_info is deprecated, use get_channel_colormap_name instead\",\n category=DeprecationWarning,\n stacklevel=2,\n )\n return self.get_channel_colormap_name(view, num, default)\n\n def get_channel_colormap_name(self, view: str, num: int, default: Optional[str] = None) -> str:\n cm = self.chosen_colormap\n if default is None:\n default = cm[num % len(cm)]\n resp = self.get_from_profile(f\"{view}.cmap.num{num}\", default)\n if resp not in self.colormap_dict:\n resp = cm[num % len(cm)]\n self.set_in_profile(f\"{view}.cmap.num{num}\", resp)\n return resp\n\n def set_channel_info(self, view: str, num, value: str): # pragma: no cover\n warnings.warn(\n \"set_channel_info is deprecated, use set_channel_colormap_name instead\",\n category=DeprecationWarning,\n stacklevel=2,\n )\n self.set_channel_colormap_name(view, num, value)\n\n def set_channel_colormap_name(self, view: str, num, value: str):\n self.set_in_profile(f\"{view}.cmap.num{num}\", value)\n\n def connect_channel_colormap_name(self, view: str, fun: Callable):\n self.connect_to_profile(f\"{view}.cmap\", fun)\n\n @property\n def available_colormaps(self):\n return list(self.colormap_dict.keys())\n\n def _image_changed(self):\n self.border_val = self.image.get_ranges()\n super()._image_changed()\n\n def change_profile(self, name):\n self.current_profile_dict = name\n self.view_settings_dict.profile_change()\n\n def set_in_profile(self, key_path, value):\n \"\"\"\n Function for saving information used in visualization. This is accessor to\n :py:meth:`~.ProfileDict.set` of inner variable.\n\n :param key_path: dot separated path\n :param value: value to store. The value need to be json serializable.\"\"\"\n self.view_settings_dict.set(f\"{self.current_profile_dict}.{key_path}\", value)\n self.profile_data_changed.emit(key_path, value)\n\n def get_from_profile(self, key_path, default=None):\n \"\"\"\n Function for getting information used in visualization. This is accessor to\n :py:meth:`~.ProfileDict.get` of inner variable.\n\n :param key_path: dot separated path\n :param default: default value if key is missed\n \"\"\"\n return self.view_settings_dict.get(f\"{self.current_profile_dict}.{key_path}\", default)\n\n def connect_to_profile(self, key_path, callback):\n # TODO fixme fix when introduce switch profiles\n self.view_settings_dict.connect(key_path, callback)\n\n\nclass SaveSettingsDescription(NamedTuple):\n file_name: str\n values: Union[dict, ProfileDict]\n\n\nclass BaseSettings(ViewSettings):\n \"\"\"\n :ivar json_folder_path: default location for saving/loading settings data\n :ivar last_executed_algorithm: name of last executed algorithm.\n :cvar save_locations_keys: list of names of distinct save location.\n location are stored in \"io\"\n\n \"\"\"\n\n mask_changed = Signal()\n points_changed = Signal()\n request_load_files = Signal(list)\n \"\"\":py:class:`~.Signal` mask changed signal\"\"\"\n json_encoder_class = PartSegEncoder\n load_metadata = staticmethod(load_metadata_base)\n algorithm_changed = Signal()\n \"\"\":py:class:`~.Signal` emitted when current algorithm should be changed\"\"\"\n save_locations_keys: ClassVar[List[str]] = []\n\n def __init__(self, json_path: Union[Path, str], profile_name: str = \"default\"):\n \"\"\"\n :param json_path: path to store\n :param profile_name: name of profile to be used. default value is \"default\"\n \"\"\"\n super().__init__()\n napari_path = os.path.dirname(json_path) if os.path.basename(json_path) in [\"analysis\", \"mask\"] else json_path\n self.napari_settings: NapariSettings = napari_get_settings(napari_path)\n self._current_roi_dict = profile_name\n self._roi_dict = ProfileDict()\n self._last_algorithm_dict = ProfileDict()\n self.json_folder_path = json_path\n self.last_executed_algorithm = \"\"\n self.history: List[HistoryElement] = []\n self.history_index = -1\n self.last_executed_algorithm = \"\"\n self._points = None\n\n def _image_changed(self):\n super()._image_changed()\n self.points = None\n\n @property\n def points(self):\n return self._points\n\n @points.setter\n def points(self, value):\n self._points = value if value is not None else None\n self.points_changed.emit()\n\n @property\n def theme_name(self) -> str:\n try:\n theme = self.napari_settings.appearance.theme\n if self.get_from_profile(\"first_start\", True):\n theme = \"light\"\n self.napari_settings.appearance.theme = theme\n self.set_in_profile(\"first_start\", False)\n return theme\n except AttributeError: # pragma: no cover\n return \"light\"\n\n @theme_name.setter\n def theme_name(self, value: str):\n self.napari_settings.appearance.theme = value\n\n def set_segmentation_result(self, result: ROIExtractionResult):\n if (\n result.file_path is not None and result.file_path and result.file_path != self.image.file_path\n ): # pragma: no cover\n if self._parent is not None:\n # TODO change to non disrupting popup\n QMessageBox().warning(\n self._parent, \"Result file bug\", \"It looks like one try to set ROI form another file.\"\n )\n return\n if result.info_text and self._parent is not None:\n QMessageBox().information(self._parent, \"Algorithm info\", result.info_text)\n\n self._additional_layers = result.additional_layers\n self.last_executed_algorithm = result.parameters.algorithm\n self.set_algorithm(f\"algorithms.{result.parameters.algorithm}\", result.parameters.values)\n # Fixme not use EventedDict here\n try:\n roi_info = result.roi_info.fit_to_image(self.image)\n except ValueError as e: # pragma: no cover\n raise ValueError(ROI_NOT_FIT) from e\n if result.points is not None:\n self.points = result.points\n self._roi_info = roi_info\n self.roi_changed.emit(self._roi_info)\n\n def _load_files_call(self, files_list: List[str]):\n self.request_load_files.emit(files_list)\n\n def add_history_element(self, elem: HistoryElement) -> None:\n self.history_index += 1\n if self.history_index < len(self.history) and self.cmp_history_element(elem, self.history[self.history_index]):\n self.history[self.history_index] = elem\n else:\n self.history = self.history[: self.history_index]\n self.history.append(elem)\n\n def history_size(self) -> int:\n return self.history_index + 1\n\n def history_redo_size(self) -> int:\n if self.history_index + 1 == len(self.history):\n return 0\n return len(self.history[self.history_index + 1 :])\n\n def history_redo_clean(self) -> None:\n self.history = self.history[: self.history_size()]\n\n def history_current_element(self) -> HistoryElement:\n return self.history[self.history_index]\n\n def history_next_element(self) -> HistoryElement:\n return self.history[self.history_index + 1]\n\n def history_pop(self) -> Optional[HistoryElement]:\n if self.history_index != -1:\n self.history_index -= 1\n return self.history[self.history_index + 1]\n return None\n\n def set_history(self, history: List[HistoryElement]):\n self.history = history\n self.history_index = len(self.history) - 1\n\n def get_history(self) -> List[HistoryElement]:\n return self.history[: self.history_index + 1]\n\n @staticmethod\n def cmp_history_element(el1, el2):\n return False\n\n @property\n def mask(self):\n return self._image.mask\n\n @mask.setter\n def mask(self, value):\n try:\n self._image.set_mask(value)\n self.mask_changed.emit()\n except ValueError as e:\n raise ValueError(\"mask do not fit to image\") from e\n\n def get_save_list(self) -> List[SaveSettingsDescription]:\n \"\"\"List of files in which program save the state.\"\"\"\n return [\n SaveSettingsDescription(\"segmentation_settings.json\", self._roi_dict),\n SaveSettingsDescription(\"view_settings.json\", self.view_settings_dict),\n SaveSettingsDescription(\"algorithm_settings.json\", self._last_algorithm_dict),\n ]\n\n def get_path_history(self) -> List[str]:\n \"\"\"\n return list containing last 10 elements added with :py:meth:`.add_path_history` and\n last opened in each category form :py:attr:`save_location_keys`\n \"\"\"\n res = self.get(DIR_HISTORY, [])[:]\n for name in self.save_locations_keys:\n val = self.get(f\"io.{name}\", str(Path.home()))\n if val not in res:\n res = [*res, val]\n return res\n\n @staticmethod\n def _add_elem_to_list(data_list: list, value: Any, keep_len=10) -> list:\n try:\n data_list.remove(value)\n except ValueError:\n data_list = data_list[: keep_len - 1]\n return [value, *data_list]\n\n def get_last_files(self) -> List[Tuple[Tuple[Union[str, Path], ...], str]]:\n return self.get(FILE_HISTORY, [])\n\n def add_load_files_history(self, file_path: Sequence[Union[str, Path]], load_method: str): # pragma: no cover\n warnings.warn(\"`add_load_files_history` is deprecated\", FutureWarning, stacklevel=2)\n return self.add_last_files(file_path, load_method)\n\n def add_last_files(self, file_path: Sequence[Union[str, Path]], load_method: str):\n self.set(FILE_HISTORY, self._add_elem_to_list(self.get(FILE_HISTORY, []), [list(file_path), load_method]))\n # keep list of files as list because json serialize tuple to list\n self.add_path_history(os.path.dirname(file_path[0]))\n\n def get_last_files_multiple(self) -> List[Tuple[Tuple[Union[str, Path], ...], str]]:\n return self.get(MULTIPLE_FILES_OPEN_HISTORY, [])\n\n def add_last_files_multiple(self, file_paths: List[Union[str, Path]], load_method: str):\n self.set(\n MULTIPLE_FILES_OPEN_HISTORY,\n self._add_elem_to_list(\n self.get(MULTIPLE_FILES_OPEN_HISTORY, []), [list(file_paths), load_method], keep_len=30\n ),\n )\n # keep list of files as list because json serialize tuple to list\n self.add_path_history(os.path.dirname(file_paths[0]))\n\n def add_path_history(self, dir_path: Union[str, Path]):\n \"\"\"Save path in history of visited directories. Store only 10 last\"\"\"\n dir_path = str(dir_path)\n self.set(DIR_HISTORY, self._add_elem_to_list(self.get(DIR_HISTORY, []), dir_path))\n\n def set(self, key_path: str, value):\n \"\"\"\n function for saving general state (not visualization). This is accessor to\n :py:meth:`~.ProfileDict.set` of inner variable.\n\n :param key_path: dot separated path\n :param value: value to store. The value need to be json serializable.\n \"\"\"\n if key_path.startswith((\"algorithm_widget_state.\", \"algorithms.\")) or key_path == \"current_algorithm\":\n warnings.warn(\"Use `set_algorithm_state` instead of `set` for algorithm state\", FutureWarning, stacklevel=2)\n self.set_algorithm(key_path, value)\n return\n self._roi_dict.set(f\"{self._current_roi_dict}.{key_path}\", value)\n\n def get(self, key_path: str, default=None):\n \"\"\"\n Function for getting general state (not visualization). This is accessor to\n :py:meth:`~.ProfileDict.get` of inner variable.\n\n :param key_path: dot separated path\n :param default: default value if key is missed\n \"\"\"\n if key_path.startswith((\"algorithms.\", \"algorithm_widget_state.\")) or key_path == \"current_algorithm\":\n warnings.warn(\"Use `set_algorithm_state` instead of `set` for algorithm state\", FutureWarning, stacklevel=2)\n return self.get_algorithm(key_path, default)\n return self._roi_dict.get(f\"{self._current_roi_dict}.{key_path}\", default)\n\n def set_algorithm(self, key_path: str, value):\n \"\"\"\n function for saving last algorithm used information. This is accessor to\n :py:meth:`~.ProfileDict.set` of inner variable.\n\n :param key_path: dot separated path\n :param value: value to store. The value need to be json serializable.\n \"\"\"\n # if key_path.startswith(\"\")\n self._last_algorithm_dict.set(f\"{self._current_roi_dict}.{key_path}\", value)\n\n def get_algorithm(self, key_path: str, default=None):\n \"\"\"\n Function for getting last algorithm used information. This is accessor to\n :py:meth:`~.ProfileDict.get` of inner variable.\n\n :param key_path: dot separated path\n :param default: default value if key is missed\n \"\"\"\n return self._last_algorithm_dict.get(f\"{self._current_roi_dict}.{key_path}\", default)\n\n def connect_(self, key_path, callback):\n # TODO fixme fix when introduce switch profiles\n self._roi_dict.connect(key_path, callback)\n\n def dump_part(self, file_path, path_in_dict, names=None):\n data = self.get(path_in_dict)\n if names is not None:\n data = {name: data[name] for name in names}\n os.makedirs(os.path.dirname(file_path), exist_ok=True)\n with open(file_path, \"w\", encoding=\"utf-8\") as ff:\n json.dump(data, ff, cls=self.json_encoder_class, indent=2)\n\n def dump(self, folder_path: Union[Path, str, None] = None):\n \"\"\"\n Save current application settings to disc.\n\n :param folder_path: path to directory in which data should be saved.\n If is None then use :py:attr:`.json_folder_path`\n \"\"\"\n if self.napari_settings.save is not None:\n self.napari_settings.save()\n else:\n self.napari_settings._save() # pylint: disable=protected-access\n if folder_path is None:\n folder_path = self.json_folder_path\n if not os.path.exists(folder_path):\n os.makedirs(folder_path)\n errors_list = []\n for el in self.get_save_list():\n try:\n dump_string = json.dumps(el.values, cls=self.json_encoder_class, indent=2)\n with open(os.path.join(folder_path, el.file_name), \"w\", encoding=\"utf-8\") as ff:\n ff.write(dump_string)\n except Exception as e: # pylint: disable=broad-except\n errors_list.append((e, os.path.join(folder_path, el.file_name)))\n if errors_list:\n logger.error(errors_list)\n return errors_list\n\n def _load_settings_file(self, file_path: Union[Path, str]) -> Tuple[ProfileDict, Any]:\n error = None\n data: ProfileDict = self.load_metadata(file_path)\n if isinstance(data, dict) and \"__error__\" in data:\n error = data[\"__error__\"]\n data = ProfileDict()\n elif not data.verify_data():\n filtered = data.pop_errors()\n error = filtered\n filtered_base_str = ((k, \"\\n\".join(f\"{x}\" for x in find_problematic_entries(v))) for k, v in filtered)\n filtered_str = \"\\n\".join(f\"{k}\\n{v}\\n\" for k, v in filtered_base_str)\n\n logger.error(\"error in load data from %s problematic keys are %s\", file_path, filtered_str)\n return data, error\n\n def load(self, folder_path: Union[Path, str, None] = None):\n \"\"\"\n Load settings state from given directory\n\n :param folder_path: path to directory in which data should be saved.\n If is None then use :py:attr:`.json_folder_path`\n \"\"\"\n if folder_path is None:\n folder_path = self.json_folder_path\n errors_dict = {}\n for el in self.get_save_list():\n file_path = os.path.join(folder_path, el.file_name)\n if not os.path.exists(file_path):\n continue\n error = None\n try:\n data, error = self._load_settings_file(file_path)\n if error is not None:\n errors_dict[file_path] = error\n el.values.update(data)\n except Exception as e: # pylint: disable=broad-except\n error = True\n logger.error(e)\n errors_dict[file_path] = e\n finally:\n if error is not None:\n timestamp = datetime.now().strftime(\"%Y-%m-%d_%H_%M_%S\")\n base_path, ext = os.path.splitext(file_path)\n os.rename(file_path, f\"{base_path}_{timestamp}{ext}\")\n\n self.label_color_dict._refresh_order() # pylint: disable=protected-access\n self.colormap_dict._refresh_order() # pylint: disable=protected-access\n\n return errors_dict\n\n def get_project_info(self) -> ProjectInfoBase:\n \"\"\"Get all information needed to save project\"\"\"\n raise NotImplementedError # pragma: no cover\n\n def set_project_info(self, data: ProjectInfoBase):\n \"\"\"Set project info\"\"\"\n raise NotImplementedError # pragma: no cover\n\n @staticmethod\n def verify_image(image: Image, silent=True) -> Union[Image, bool]:\n if image.is_time:\n if image.is_stack:\n raise TimeAndStackException\n if silent:\n return image.swap_time_and_stack()\n raise SwapTimeStackException\n return True\n\n\nclass SwapTimeStackException(Exception):\n \"\"\"\n Exception which inform that current image shape is not supported,\n but can be if time and stack axes were swapped\n \"\"\"\n\n\nclass TimeAndStackException(Exception):\n \"\"\"\n Exception which inform that current image has both time\n and stack dat which is not supported\n \"\"\"\n\n\nclass Color: # pragma: no cover\n def __init__(self, text):\n color_re = re.compile(r\"rgb\\((\\d+), (\\d+), (\\d+)\\)\")\n self.colors = tuple(map(int, color_re.match(text).groups()))\n\n def as_rgb_tuple(self):\n return self.colors\n","sub_path":"package/PartSeg/common_backend/base_settings.py","file_name":"base_settings.py","file_ext":"py","file_size_in_byte":30420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"643767823","text":"from networking import connection\nimport threading\n\n\ndef msgen(data):\n return bytearray([len(data[0])]) + bytearray(data[0] + data[1], 'ascii')\n\n\ndef msgde(data):\n nl = int(data[0])\n return data[1:nl + 1].decode('ascii'), data[nl + 1:].decode('ascii')\n\n\nname = input('Username: ')\nip = input('Connect to: ')\n\n\ndef msghd(data):\n if not data[0] == name:\n print('\\r' + data[0] + ': ' + data[1])\n\nconnection.registertype(0, msgen, msgde)\nclient = connection.connect(ip)\nclient.registerhandler(0, msghd)\nclient.open()\n\n\ndef chat():\n while not client.closed:\n msg = input('')\n if msg == '/exit':\n client.close()\n else:\n client.sendmessage(0, (name, msg))\nthreading.Thread(target=chat).start()\n\n#client = connection.connect('localhost')\n#mssg = ''\n#while not mssg == 'exit': # bytearray([len(mssg)]) +\n# mssg = input(\"~\")\n# print(bytearray([len(mssg)]))\n# client.sock.send(bytearray([len(mssg)]) + bytearray(mssg, 'ascii'))\n#client.sock.close()\n","sub_path":"networking/examples/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"40153535","text":"import sort.qsort as qsort\nimport sort.insertion_sort as insertion_sort\n\n\nclass MedianOfFive(object):\n def __init__(self, column_size=5, colums_sort=insertion_sort.InsertionSort()):\n self.statistic_algorithm = None\n self.column_size = column_size\n self.columns_sort = colums_sort\n\n def __call__(self, array, left_bound, right_bound):\n if self.statistic_algorithm is None:\n raise RuntimeError(\"Could not select pivot! You should set up finding statistic algorithm.\")\n if left_bound == right_bound:\n return left_bound\n if right_bound - left_bound + 1 <= self.column_size:\n self.columns_sort(array, left_bound, right_bound)\n return (left_bound + right_bound) // 2\n\n for i in range(left_bound, right_bound, self.column_size):\n column_end = min(i + self.column_size - 1, right_bound)\n self.columns_sort(array, i, column_end)\n\n result_index = self.statistic_algorithm([array[i] for i in range(self.column_size // 2, right_bound + 1, self.column_size)],\n (left_bound + right_bound) // (2 * self.column_size))\n return result_index * self.column_size + self.column_size // 2\n\n def set_statistic_algorithm(self, algorithm):\n self.statistic_algorithm = algorithm\n\n\nclass KthStatistic(object):\n def __init__(self,\n pivot_selector=qsort.random_pivot_selector,\n partition_algorithm=qsort.lomoto_partition):\n self.pivot_selector = pivot_selector\n self.partition_algorithm = partition_algorithm\n\n def __call__(self, array, k):\n left_bound = 0\n right_bound = len(array) - 1\n if k > right_bound:\n raise RuntimeError(\"You are trying to find {} order statistic \"\n \"in the array of size {}.\".format(k, len(array)))\n if len(array) == 0:\n raise RuntimeError(\"Array is empty\")\n if len(array) == 1:\n return left_bound\n\n while left_bound < right_bound:\n pivot_index = self.pivot_selector(array, left_bound, right_bound)\n smaller_part_end, bigger_part_begin = self.partition_algorithm(array, left_bound, right_bound, pivot_index)\n if smaller_part_end < left_bound + k < bigger_part_begin:\n left_bound = right_bound = left_bound + k\n elif left_bound + k <= smaller_part_end:\n right_bound = smaller_part_end\n elif left_bound + k >= bigger_part_begin:\n k -= bigger_part_begin - left_bound\n left_bound = bigger_part_begin\n\n return left_bound\n","sub_path":"search/kthstatistic.py","file_name":"kthstatistic.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"297587987","text":"# -*- encoding: utf-8 -*-\nfrom site_structure.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.models import User\nfrom django.http import Http404, HttpResponseRedirect\n\nfrom community.models import Bookmark\nfrom community.forms import BookmarkForm\n\nimport markdown\nimport re\n\n@login_required\ndef new(request):\n\tif request.method == 'POST':\n\t\tform = BookmarkForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tnew_bookmark = form.save(commit=False)\n\t\t\tnew_bookmark.creator = request.user\n\t\t\tnew_bookmark.save()\n\n\t\treturn HttpResponseRedirect('/samfelag/minar-sidur/')\n\t\n\treturn render('community/new.html', {'title': 'Bæta við tengli', 'form':BookmarkForm(),}, request)\n\ndef all(request):\n\tctx = {'title': 'Tenglasafn'}\n\tbookmarks = Bookmark.objects.all().order_by('-created')\n\t\n\tcollection = []\n\tfor bookmark in bookmarks:\t\t\n\t\tcollection.append({'title':bookmark.title, 'url':bookmark.target_url, 'published':bookmark.created, 'summary':bookmark.description, 'author':bookmark.creator})\t\n\t\n\tctx['content'] = collection\n\n\treturn render('community/content_list.html', ctx, request)\n\ndef mine(request, username=None):\n\tctx = {'title': 'Tenglasafn %s' % (username)}\n\tif not username:\n\t\tif request.user.is_authenticated():\n\t\t\tusername = request.user.username\n\t\t\tctx['title'] = 'Mitt tenglasafn'\n\t\telse: \n\t\t\traise Http404\n\n\tbookmarks = Bookmark.objects.filter(creator__username=username).order_by('-created')\n\t\n\tcollection = []\n\tfor bookmark in bookmarks:\n\t\tcollection.append({'title':bookmark.title, 'url':bookmark.target_url, 'published':bookmark.created, 'summary':bookmark.description, 'author':bookmark.creator})\t\n\t\n\tctx['content'] = collection\n\n\treturn render('community/content_list.html', ctx, request)\n\ndef view(request, user, slug):\n\ttry:\n\t\tarticle = Article.objects.filter(author__username=user).get(slug=slug)\n\texcept:\n\t\traise Article.DoesNotExist\n\n\treturn render('community/article.html', {'article':article}, request)\n","sub_path":"community/bookmarks.py","file_name":"bookmarks.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"297683685","text":"# Copyright 2020, The TensorFlow Federated Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Experimental utilities for serializing JAX computations.\"\"\"\n\nimport jax\nimport numpy as np\n\nfrom tensorflow_federated.experimental.python.core.impl.jax_context import jax_computation_context\nfrom tensorflow_federated.python.common_libs import py_typecheck\nfrom tensorflow_federated.python.common_libs import structure\nfrom tensorflow_federated.python.core.backends.xla import xla_serialization\nfrom tensorflow_federated.python.core.impl.context_stack import context_stack_base\nfrom tensorflow_federated.python.core.impl.types import computation_types\nfrom tensorflow_federated.python.core.impl.types import type_conversions\nfrom tensorflow_federated.python.core.impl.types import typed_object\n\n\nclass _XlaSerializerTensorArg(jax.ShapeDtypeStruct, typed_object.TypedObject):\n \"\"\"Represents tensor type info understood by both TFF and JAX serializer.\"\"\"\n\n def __init__(self, tensor_type, tensor_index):\n py_typecheck.check_type(tensor_type, computation_types.TensorType)\n shape = tuple(tensor_type.shape.as_list())\n dtype = tensor_type.dtype.as_numpy_dtype\n jax.ShapeDtypeStruct.__init__(self, shape, dtype)\n self._type_signature = tensor_type\n self._tensor_index = tensor_index\n\n @property\n def type_signature(self):\n return self._type_signature\n\n @property\n def tensor_index(self):\n return self._tensor_index\n\n\nclass _XlaSerializerStructArg(structure.Struct, typed_object.TypedObject):\n \"\"\"Represents struct type info understood by both TFF and JAX serializer.\"\"\"\n\n def __init__(self, type_spec, elements):\n py_typecheck.check_type(type_spec, computation_types.StructType)\n structure.Struct.__init__(self, elements)\n self._type_signature = type_spec\n\n @property\n def type_signature(self):\n return self._type_signature\n\n def __str__(self):\n return '_XlaSerializerStructArg({})'.format(structure.Struct.__str__(self))\n\n\ndef _tff_type_to_xla_serializer_arg(type_spec):\n \"\"\"Converts TFF type into an argument for the JAX-to-XLA serializer.\n\n Args:\n type_spec: An instance of `computation_types.TensorType`.\n\n Returns:\n An object that carries both TFF and JAX type info, to be fed into the JAX\n serializer.\n \"\"\"\n\n def _make(type_spec, next_unused_tensor_index):\n if isinstance(type_spec, computation_types.TensorType):\n obj = _XlaSerializerTensorArg(type_spec, next_unused_tensor_index)\n next_unused_tensor_index = next_unused_tensor_index + 1\n return obj, next_unused_tensor_index\n py_typecheck.check_type(type_spec, computation_types.StructType)\n elements = []\n for k, v in structure.to_elements(type_spec):\n obj, next_unused_tensor_index = _make(v, next_unused_tensor_index)\n elements.append((k, obj))\n obj = _XlaSerializerStructArg(type_spec, elements)\n return obj, next_unused_tensor_index\n\n obj, _ = _make(type_spec, 0)\n return obj\n\n\ndef _jax_shape_dtype_struct_to_tff_tensor(val):\n \"\"\"Converts `jax.ShapeDtypeStruct` to `computation_types.TensorType`.\n\n Args:\n val: An instance of `jax.ShapeDtypeStruct`.\n\n Returns:\n A corresponding instance of `computation_types.TensorType`.\n\n Raises:\n TypeError: if arg type mismatches.\n \"\"\"\n py_typecheck.check_type(val, jax.ShapeDtypeStruct)\n return computation_types.TensorType(val.dtype, val.shape)\n\n\ndef serialize_jax_computation(traced_fn, arg_fn, parameter_type, context_stack):\n \"\"\"Serializes a Python function containing JAX code as a TFF computation.\n\n Args:\n traced_fn: The Python function containing JAX code to be traced by JAX and\n serialized as a TFF computation containing XLA code.\n arg_fn: An unpacking function that takes a TFF argument, and returns a combo\n of (args, kwargs) to invoke `traced_fn` with (e.g., as the one constructed\n by `function_utils.create_argument_unpacking_fn`).\n parameter_type: An instance of `computation_types.Type` that represents the\n TFF type of the computation parameter, or `None` if the function does not\n take any parameters.\n context_stack: The context stack to use during serialization.\n\n Returns:\n An instance of `pb.Computation` with the constructed computation.\n\n Raises:\n TypeError: if the arguments are of the wrong types.\n \"\"\"\n py_typecheck.check_callable(traced_fn)\n py_typecheck.check_callable(arg_fn)\n py_typecheck.check_type(context_stack, context_stack_base.ContextStack)\n\n if parameter_type is not None:\n parameter_type = computation_types.to_type(parameter_type)\n packed_arg = _tff_type_to_xla_serializer_arg(parameter_type)\n else:\n packed_arg = None\n\n args, kwargs = arg_fn(packed_arg)\n\n # While the fake parameters are fed via args/kwargs during serialization,\n # it is possible for them to get reorderd in the actual generate XLA code.\n # We use here the same flatenning function as that one, which is used by\n # the JAX serializer to determine the orderding and allow it to be captured\n # in the parameter binding. We do not need to do anything special for the\n # results, since the results, if multiple, are always returned as a tuple.\n flattened_obj, _ = jax.tree_util.tree_flatten((args, kwargs))\n tensor_indexes = list(np.argsort([x.tensor_index for x in flattened_obj]))\n\n def _adjust_arg(x):\n if isinstance(x, structure.Struct):\n return type_conversions.type_to_py_container(x, x.type_signature)\n else:\n return x\n\n args = [_adjust_arg(x) for x in args]\n kwargs = {k: _adjust_arg(v) for k, v in kwargs.items()}\n\n context = jax_computation_context.JaxComputationContext()\n with context_stack.install(context):\n tracer_callable = jax.xla_computation(\n traced_fn, tuple_args=True, return_shape=True)\n compiled_xla, returned_shape = tracer_callable(*args, **kwargs)\n\n if isinstance(returned_shape, jax.ShapeDtypeStruct):\n returned_type_spec = _jax_shape_dtype_struct_to_tff_tensor(returned_shape)\n else:\n returned_type_spec = computation_types.to_type(\n structure.map_structure(\n _jax_shape_dtype_struct_to_tff_tensor,\n structure.from_container(returned_shape, recursive=True)))\n\n computation_type = computation_types.FunctionType(parameter_type,\n returned_type_spec)\n return xla_serialization.create_xla_tff_computation(compiled_xla,\n tensor_indexes,\n computation_type)\n","sub_path":"tensorflow_federated/experimental/python/core/impl/jax_context/jax_serialization.py","file_name":"jax_serialization.py","file_ext":"py","file_size_in_byte":7010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"49424408","text":"###\n### Copyright (C) 2018-2019 Intel Corporation\n###\n### SPDX-License-Identifier: BSD-3-Clause\n###\n\nfrom ....lib import *\nfrom ..util import *\nimport os\n\n@slash.requires(have_gst)\n@slash.requires(*have_gst_element(\"msdk\"))\n@slash.requires(*have_gst_element(\"checksumsink2\"))\n@slash.requires(using_compatible_driver)\n@platform_tags(ALL_PLATFORMS)\nclass TranscoderTest(slash.Test):\n requirements = dict(\n decode = {\n \"avc\" : dict(\n sw = (ALL_PLATFORMS, have_gst_element(\"avdec_h264\"), \"h264parse ! avdec_h264\"),\n hw = (AVC_DECODE_PLATFORMS, have_gst_element(\"msdkh264dec\"), \"h264parse ! msdkh264dec\"),\n ),\n \"hevc-8\" : dict(\n sw = (ALL_PLATFORMS, have_gst_element(\"avdec_h265\"), \"h265parse ! avdec_h265\"),\n hw = (HEVC_DECODE_8BIT_PLATFORMS, have_gst_element(\"msdkh265dec\"), \"h265parse ! msdkh265dec\"),\n ),\n \"mpeg2\" : dict(\n sw = (ALL_PLATFORMS, have_gst_element(\"avdec_mpeg2video\"), \"mpegvideoparse ! avdec_mpeg2video\"),\n hw = (MPEG2_DECODE_PLATFORMS, have_gst_element(\"msdkmpeg2dec\"), \"mpegvideoparse ! msdkmpeg2dec\"),\n ),\n \"mjpeg\" : dict(\n sw = (ALL_PLATFORMS, have_gst_element(\"jpegdec\"), \"jpegparse ! jpegdec\"),\n hw = (JPEG_DECODE_PLATFORMS, have_gst_element(\"msdkmjpegdec\"), \"jpegparse ! msdkmjpegdec\"),\n ),\n \"vc1\" : dict(\n sw = (\n ALL_PLATFORMS, have_gst_element(\"avdec_vc1\"),\n \"'video/x-wmv,profile=(string)advanced'\"\n \",width={width},height={height},framerate=14/1 ! avdec_vc1\"\n ),\n hw = (\n VC1_DECODE_PLATFORMS, have_gst_element(\"msdkvc1dec\"),\n \"'video/x-wmv,profile=(string)advanced'\"\n \",width={width},height={height},framerate=14/1 ! msdkvc1dec\"\n ),\n ),\n },\n encode = {\n \"avc\" : dict(\n sw = (ALL_PLATFORMS, have_gst_element(\"x264enc\"), \"x264enc ! video/x-h264,profile=main ! h264parse\"),\n hw = (AVC_ENCODE_PLATFORMS, have_gst_element(\"msdkh264enc\"), \"msdkh264enc ! video/x-h264,profile=main ! h264parse\"),\n ),\n \"hevc-8\" : dict(\n sw = (ALL_PLATFORMS, have_gst_element(\"x265enc\"), \"x265enc ! video/x-h265,profile=main ! h265parse\"),\n hw = (HEVC_ENCODE_8BIT_PLATFORMS, have_gst_element(\"msdkh265enc\"), \"msdkh265enc ! video/x-h265,profile=main ! h265parse\"),\n ),\n \"mpeg2\" : dict(\n sw = (ALL_PLATFORMS, have_gst_element(\"avenc_mpeg2video\"), \"avenc_mpeg2video ! mpegvideoparse\"),\n hw = (MPEG2_ENCODE_PLATFORMS, have_gst_element(\"msdkmpeg2enc\"), \"msdkmpeg2enc ! mpegvideoparse\"),\n ),\n \"mjpeg\" : dict(\n sw = (ALL_PLATFORMS, have_gst_element(\"jpegenc\"), \"jpegenc ! jpegparse\"),\n hw = (JPEG_ENCODE_PLATFORMS, have_gst_element(\"msdkmjpegenc\"), \"msdkmjpegenc ! jpegparse\"),\n ),\n },\n vpp = {\n \"scale\" : dict(\n sw = (ALL_PLATFORMS, have_gst_element(\"videoscale\"), \"videoscale ! video/x-raw,width={width},height={height}\"),\n hw = (VPP_PLATFORMS, have_gst_element(\"msdkvpp\"), \"msdkvpp hardware=true scaling-mode=1 ! video/x-raw,format=NV12,width={width},height={height}\"),\n ),\n },\n )\n\n # hevc implies hevc 8 bit\n requirements[\"encode\"][\"hevc\"] = requirements[\"encode\"][\"hevc-8\"]\n requirements[\"decode\"][\"hevc\"] = requirements[\"decode\"][\"hevc-8\"]\n\n def before(self):\n self.refctx = []\n\n def get_requirements_data(self, ttype, codec, mode):\n return self.requirements[ttype].get(\n codec, {}).get(\n mode, ([], (False, \"{}:{}:{}\".format(ttype, codec, mode)), None))\n\n def get_decoder(self, codec, mode):\n _, _, decoder = self.get_requirements_data(\"decode\", codec, mode)\n assert decoder is not None, \"failed to find a suitable decoder: {}:{}\".format(codec, mode)\n return decoder.format(**vars(self))\n\n def get_encoder(self, codec, mode):\n _, _, encoder = self.get_requirements_data(\"encode\", codec, mode)\n assert encoder is not None, \"failed to find a suitable encoder: {}:{}\".format(codec, mode)\n return encoder.format(**vars(self))\n\n def get_vpp_scale(self, width, height, mode):\n if width is None and height is None:\n return None\n _, _, scale = self.get_requirements_data(\"vpp\", \"scale\", mode)\n assert scale is not None, \"failed to find a suitable vpp scaler: {}\".format(mode)\n return scale.format(width = width or self.width, height = height or self.height)\n\n def get_file_ext(self, codec):\n return {\n \"avc\" : \"h264\",\n \"hevc\" : \"h265\",\n \"hevc-8\" : \"h265\",\n \"mpeg2\" : \"m2v\",\n \"mjpeg\" : \"mjpeg\",\n }.get(codec, \"???\")\n\n def validate_spec(self):\n from slash.utils.pattern_matching import Matcher\n\n assert len(self.outputs), \"Invalid test case specification, outputs data empty\"\n assert self.mode in [\"sw\", \"hw\"], \"Invalid test case specification as mode type not valid\"\n\n # generate platform list based on test runtime parameters\n iplats, ireq, _ = self.get_requirements_data(\"decode\", self.codec, self.mode)\n platforms = set(iplats)\n requires = [ireq,]\n\n for output in self.outputs:\n codec = output[\"codec\"]\n mode = output[\"mode\"]\n assert mode in [\"sw\", \"hw\"], \"Invalid test case specification as output mode type not valid\"\n oplats, oreq, _ = self.get_requirements_data(\"encode\", codec, mode)\n platforms &= set(oplats)\n requires.append(oreq)\n\n if output.get(\"width\", None) is not None or output.get(\"height\", None) is not None:\n oplats, oreq, _ = self.get_requirements_data(\"vpp\", \"scale\", mode)\n platforms &= set(oplats)\n requires.append(oreq)\n\n # create matchers based on command-line filters\n matchers = [Matcher(s) for s in slash.config.root.run.filter_strings]\n\n # check if user supplied any platform tag on command line\n pmatch = any(map(lambda p: any([m.matches(p) for m in matchers]), ALL_PLATFORMS))\n\n # if user supplied a platform tag, check if this test can support it via the\n # test param-based required platforms\n if pmatch and not any(map(lambda p: any([m.matches(p) for m in matchers]), platforms)):\n slash.skip_test(\"unsupported platform\")\n\n # check required\n if not all([t for t,m in requires]):\n slash.skip_test(\n \"One or more software requirements not met: {}\".format(\n str([m for t,m in requires if not t])))\n\n def gen_input_opts(self):\n opts = \"filesrc location={source}\"\n opts += \" ! \" + self.get_decoder(self.codec, self.mode)\n return opts.format(**vars(self))\n\n def gen_output_opts(self):\n self.goutputs = dict()\n opts = \"! tee name=transcoder\"\n\n for n, output in enumerate(self.outputs):\n codec = output[\"codec\"]\n mode = output[\"mode\"]\n encoder = self.get_encoder(codec, mode)\n ext = self.get_file_ext(codec)\n\n vppscale = self.get_vpp_scale(\n output.get(\"width\", None), output.get(\"height\", None), mode)\n\n for channel in xrange(output.get(\"channels\", 1)):\n ofile = get_media()._test_artifact(\n \"{}_{}_{}.{}\".format(self.case, n, channel, ext))\n self.goutputs.setdefault(n, list()).append(ofile)\n\n opts += \" ! queue\"\n if vppscale is not None:\n opts += \"! {}\".format(vppscale)\n opts += \" ! {}\".format(encoder)\n opts += \" ! filesink location={} transcoder.\".format(ofile)\n\n # dump decoded source to yuv for reference comparison\n self.srcyuv = get_media()._test_artifact(\n \"src_{case}.yuv\".format(**vars(self)))\n opts += \" ! queue ! videoconvert ! video/x-raw,format=I420\"\n opts += \" ! checksumsink2 file-checksum=false qos=false\"\n opts += \" frame-checksum=false plane-checksum=false dump-output=true\"\n opts += \" dump-location={srcyuv}\"\n\n return opts.format(**vars(self))\n\n def transcode(self):\n self.validate_spec()\n iopts = self.gen_input_opts()\n oopts = self.gen_output_opts()\n\n get_media().test_call_timeout = vars(self).get(\"call_timeout\", 0)\n\n call(\"gst-launch-1.0 -vf {} {}\".format(iopts, oopts))\n\n for n, output in enumerate(self.outputs):\n for channel in xrange(output.get(\"channels\", 1)):\n encoded = self.goutputs[n][channel]\n yuv = get_media()._test_artifact(\n \"{}_{}_{}.yuv\".format(self.case, n, channel))\n vppscale = self.get_vpp_scale(self.width, self.height, \"hw\")\n call(\n \"gst-launch-1.0 -vf filesrc location={}\"\n \" ! {} ! {}\"\n \" ! videoconvert ! video/x-raw,format=I420\"\n \" ! checksumsink2 file-checksum=false qos=false\"\n \" frame-checksum=false plane-checksum=false dump-output=true\"\n \" dump-location={}\".format(\n encoded, self.get_decoder(output[\"codec\"], \"hw\"), vppscale, yuv))\n self.check_metrics(yuv, refctx = [(n, channel)])\n get_media()._purge_test_artifact(yuv)\n\n def check_metrics(self, yuv, refctx):\n get_media().baseline.check_psnr(\n psnr = calculate_psnr(\n self.srcyuv, yuv,\n self.width, self.height,\n self.frames),\n context = self.refctx + refctx,\n )\n","sub_path":"test/gst-msdk/transcode/transcoder.py","file_name":"transcoder.py","file_ext":"py","file_size_in_byte":8984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"632326588","text":"import nose\nfrom swiglpk import *\n\ndef test_swiglpk():\n ia = intArray(1+1000); ja = intArray(1+1000);\n ar = doubleArray(1+1000);\n lp = glp_create_prob();\n glp_set_prob_name(lp, \"sample\");\n glp_set_obj_dir(lp, GLP_MAX);\n glp_add_rows(lp, 3);\n glp_set_row_name(lp, 1, \"p\");\n glp_set_row_bnds(lp, 1, GLP_UP, 0.0, 100.0);\n glp_set_row_name(lp, 2, \"q\");\n glp_set_row_bnds(lp, 2, GLP_UP, 0.0, 600.0);\n glp_set_row_name(lp, 3, \"r\");\n glp_set_row_bnds(lp, 3, GLP_UP, 0.0, 300.0);\n glp_add_cols(lp, 3);\n glp_set_col_name(lp, 1, \"x1\");\n glp_set_col_bnds(lp, 1, GLP_LO, 0.0, 0.0);\n glp_set_obj_coef(lp, 1, 10.0);\n glp_set_col_name(lp, 2, \"x2\");\n glp_set_col_bnds(lp, 2, GLP_LO, 0.0, 0.0);\n glp_set_obj_coef(lp, 2, 6.0);\n glp_set_col_name(lp, 3, \"x3\");\n glp_set_col_bnds(lp, 3, GLP_LO, 0.0, 0.0);\n glp_set_obj_coef(lp, 3, 4.0);\n ia[1] = 1; ja[1] = 1; ar[1] = 1.0; # a[1,1] = 1\n ia[2] = 1; ja[2] = 2; ar[2] = 1.0; # a[1,2] = 1\n ia[3] = 1; ja[3] = 3; ar[3] = 1.0; # a[1,3] = 1\n ia[4] = 2; ja[4] = 1; ar[4] = 10.0; # a[2,1] = 10\n ia[5] = 3; ja[5] = 1; ar[5] = 2.0; # a[3,1] = 2\n ia[6] = 2; ja[6] = 2; ar[6] = 4.0; # a[2,2] = 4\n ia[7] = 3; ja[7] = 2; ar[7] = 2.0; # a[3,2] = 2\n ia[8] = 2; ja[8] = 3; ar[8] = 5.0; # a[2,3] = 5\n ia[9] = 3; ja[9] = 3; ar[9] = 6.0; # a[3,3] = 6\n glp_load_matrix(lp, 9, ia, ja, ar);\n glp_simplex(lp, None);\n Z = glp_get_obj_val(lp);\n x1 = glp_get_col_prim(lp, 1);\n x2 = glp_get_col_prim(lp, 2);\n x3 = glp_get_col_prim(lp, 3);\n print(\"\\nZ = %g; x1 = %g; x2 = %g; x3 = %g\\n\" % (Z, x1, x2, x3))\n\n nose.tools.assert_almost_equal(Z, 733.3333333333333)\n nose.tools.assert_almost_equal(x1, 33.333333333333336)\n nose.tools.assert_almost_equal(x2, 66.66666666666666)\n nose.tools.assert_almost_equal(x3, 0)\n\n glp_delete_prob(lp);\n","sub_path":"test_swiglpk.py","file_name":"test_swiglpk.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"63338415","text":"from ViewMA_JMD import *\nfrom ModelMA_JMD import *\nfrom tkinter import *\nfrom Model_tableModif import *\n \nclass Controler(object):\n def __init__(self):\n self.root = Tk()\n self.model=Model(self)\n self.modelProjetInfo = self.model.projetInfo\n self.view=View(self, self.root)\n #charger et afficher la page d'acceuil\n self.view.afficherPageAcceuil()\n\n # Provenant de la page d'aceuil\n def creerProjet(self):\n self.modelProjetInfo.nomProjet = self.view.entryNomProjet.get()\n self.view.titreProjet.set(self.modelProjetInfo.nomProjet)\n self.modelProjetInfo.descProjet = self.view.tbxDescProjet.get(1.0,END)\n self.modelProjetInfo.projectID = self.model.createNewProject(self.modelProjetInfo.nomProjet, self.modelProjetInfo.descProjet)\n self.view.unpackAcceuil()\n self.view.placerLesObjets()\n self.view.afficherPage(0)\n \n # Provenant de la page d'aceuil \n def chargerPojetExistant(self):\n self.modelProjetInfo.nomProjet = self.view.strVarProjet.get()\n self.view.titreProjet.set(self.modelProjetInfo.nomProjet)\n self.modelProjetInfo.projectID = self.model.getProjectIdFromName(self.modelProjetInfo.nomProjet)\n self.view.unpackAcceuil()\n self.refreshProjetInfo()\n \n def refreshProjetInfo(self):\n self.modelProjetInfo.setProjectInfo(self.modelProjetInfo.projectID)\n self.view.chargerProjetInfo(self.modelProjetInfo)\n self.view.afficherPage(self.view.indicePage)\n \n def insertIntoDb(self):\n print(\"insertIntoDB\")\n if self.view.indicePage == 0:\n self.sqlStatement = self.model.gDB.generateInsertSqlStatement(\"DataDictionnary\", [self.modelProjetInfo.projectID, self.view.txtMots.get(), self.view.strVarTypeMot.get()])\n self.model.gDB.executeDataManipulation(self.sqlStatement)\n if self.view.indicePage == 4:\n self.fonction = self.view.strVarPlanFonct.get()\n self.sqlSatement = \"SELECT ID FROM DataDictionnary WHERE Mot = '\"+str(self.fonction)+\"' AND Type = 'Verbe';\"\n self.idVerbe =self.model.gDB.executeSqlSelect(self.sqlSatement)[0][0]\n self.model.gDB.executeDataManipulation(self.model.gDB.generateInsertSqlStatement(\"Planning\",[self.modelProjetInfo.projectID, self.view.strVarPlanResp.get(),self.idVerbe, int(self.view.strVarPlanPrio.get())]))\n print(\"le insert \" +self.model.gDB.generateInsertSqlStatement(\"Planning\",[self.modelProjetInfo.projectID, self.view.strVarPlanResp.get(),self.idVerbe, int(self.view.strVarPlanPrio.get())]))\n\n #print(\"Le Id est \" ,self.Result)\n\n self.refreshProjetInfo()\n \n def deleteFromDb(self):\n self.typeMot = \"\"\n self.mot = \"\"\n if self.view.lbxNom.curselection():\n self.mot = self.view.lbxNom.get(self.view.lbxNom.curselection())\n self.typeMot = \"Nom\"\n elif self.view.lbxVerb.curselection():\n self.mot = self.view.lbxVerb.get(self.view.lbxVerb.curselection())\n self.typeMot = \"Verbe\"\n elif self.view.lbxAdj.curselection():\n self.mot = self.view.lbxAdj.get(self.view.lbxAdj.curselection())\n self.typeMot = \"Adjectif\"\n else:\n print(\"Selectionner le mot a supprimer!!!\")\n if self.mot != \"\":\n self.sqlSatement = \"DELETE FROM DataDictionnary WHERE Mot='\"+ self.mot +\"' AND Project_ID =\" + str(self.modelProjetInfo.projectID) +\" AND Type= '\"+self.typeMot+\"';\"\n self.model.gDB.executeDataManipulation(self.sqlSatement)\n self.refreshProjetInfo()\n \n def editerMaquette(self):\n self.model.maquette.openMaquette(self.view.lbxListeMaquettes.get(self.view.lbxListeMaquettes.curselection())+\".bmp\")\n\n def supprimerMaquette(self):\n self.maquetteName = self.view.lbxListeMaquettes.get(self.view.lbxListeMaquettes.curselection())\n print(\"avant \", self.maquetteName)\n self.model.maquette.supprimerMaquette(self.maquetteName + \".bmp\")\n self.sqlSatement = \"DELETE FROM Maquette WHERE Nom_Fichier='\"+ self.maquetteName +\"' AND Project_ID =\" + str(self.modelProjetInfo.projectID) +\";\"\n self.model.gDB.executeDataManipulation(self.sqlSatement) \n self.refreshProjetInfo() \n\n def creerMaquette(self):\n self.maquetteName = self.view.entryNouvelleMaquette.get()\n self.model.gDB.executeDataManipulation(self.model.gDB.generateInsertSqlStatement(\"Maquette\", [str(self.modelProjetInfo.projectID),self.maquetteName,\"bmp\"]))\n self.model.maquette.ajouterMaquette(self.maquetteName+\".bmp\")\n self.refreshProjetInfo()\n self.model.maquette.openMaquette(self.maquetteName+\".bmp\")\n\n#-------------------- nouveau code, debut\n #un boutton a ete presse, la vue demande de modifier la table\n def tableModif(self, action, projectid, element1, element2):\n tableModif_Cl.tableModif_Fu(self, action, self.modelProjetInfo.projectID, element1, element2)\n self.refreshProjetInfo()\n\n#-------------------- nouveau code, fin\n\n#>>>>>>>>>>>>>>>>>>>>>>>>> 2011-10-18\n def updateScenarioOM(self,CasUsageOM):\n self.modelProjetInfo.CasU_str=CasUsageOM\n self.refreshProjetInfo()\n#<<<<<<<<<<<<<<<<<<<<<<<< 2011-10-18\n \nif __name__ == '__main__':\n c=Controler()\n c.root.mainloop()\n print(\"FIN\")\n \n","sub_path":"FinalFinal/ManifesteAgileJMD/ControlerMA_JMD.py","file_name":"ControlerMA_JMD.py","file_ext":"py","file_size_in_byte":5397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"569175638","text":"\"\"\"\nBasicWriter Class\n\"\"\"\nfrom logging import Logger\nimport os\n\nfrom ..common import get_default_logger, WriteFileAlreadyExists\nfrom ..format.ynf import cYnf\n\nclass BasicWriter(object):\n \"\"\"\n BasicWriterクラス。\n Ynf形式から何かのフォーマットへ変換する処理の基底クラス。\n \"\"\"\n def __init__(self, file_path:str, overwrite:bool=False, logger:Logger=None):\n \"\"\"\n コンストラクタ\n\n Parameters\n ----------\n file_path: str\n 出力するファイルパス\n overwrite: bool\n 既に存在する場合は上書きするオプション\n logger: Logger\n ロガー。指定されない場合は別途定義してあるデフォルトロガー。\n \"\"\"\n # ロガーを設定\n self.logger = logger or get_default_logger()\n \n # 開始ログ\n msg = f'Start writing. ({self.__class__.__name__})'\n self.logger.info(msg)\n self.logger.info(f'file:{file_path}')\n\n # ファイルが既に存在している場合は、Overwriteオプションがついていないとダメ\n if os.path.exists(file_path):\n if not overwrite:\n raise WriteFileAlreadyExists(\n 'Write file is already exists. ' + \\\n 'Consider using a option `overwrite=True`.'\n )\n \n # フォルダが存在している場合は、エラー\n if os.path.isdir(file_path):\n raise WriteFileAlreadyExists(\n f'Directory is exists. ({file_path})'\n )\n\n # overwrite指定されている場合はここで消す\n os.remove(file_path)\n \n # 属性を設定\n self.file_path = file_path\n\n\n def write(self, ynf: cYnf):\n \"\"\"\n コンストラクタで指定したファイルを出力する\n 派生クラスでオーバーライドすること。\n\n Parameters\n ----------\n ynf: cYnf\n 出力するcYnfインスタンス\n \"\"\"\n raise NotImplementedError\n \n\n def write_from_ynf_file(self, file_path: str):\n \"\"\"\n Ynfファイル指定でファイルを出力する\n \n Parameters\n ----------\n file_path: str\n 出力するcYnfのシリアライズしたファイル\n \"\"\"\n # デシリアライズする\n ynf = cYnf.deserialize(file_path)\n\n # 出力する\n self.write(ynf)\n\n","sub_path":"src/fig_package/basic_writer/basic_writer.py","file_name":"basic_writer.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"565513049","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#from cparser import parse_qap, parse_tsp\nfrom m_objectivefunction import TSPObjectiveFunction, QAPObjectiveFunction\nfrom m_ga import GaSolution, GeneticOperators\nfrom m_solution import ParetoSet, ParetoFront\nimport random\nfrom m_cluster import Cluster\nimport sys\nimport math\n\nclass SPEA:\n def __init__(self, num_objectives, genetic_operators, max_pareto_points, cr=1.0, mr=0.1):\n pareto_set = ParetoSet(None)\n self.num_objectives = num_objectives\n self.genetic_operators = genetic_operators\n self.crossover_rate = cr\n self.mutation_rate = mr\n self.max_pareto_points = max_pareto_points\n\n def run(self, P, num_generations):\n \"\"\"\n Ejecuta el algoritmo SPEA\n \n @param P: la poblacion inicial\n @param num_generations: el numero maximo de generaciones\n \"\"\"\n ps = ParetoSet()\n for i in xrange(num_generations):\n ps.update(P)\n for s in ps.solutions:\n if s in P:\n P.remove(s)\n\n if len(ps.solutions) > self.max_pareto_points:\n self.reduce_pareto_set(ps)\n self.fitness_assignment(ps, P)\n mating_pool = self.selection(P, ps)\n P = self.next_generation(mating_pool, len(P))\n\n def fitness_assignment(self, pareto_set, population):\n for pareto_ind in pareto_set.solutions:\n count = 0\n for population_ind in population:\n if pareto_ind.dominates(population_ind):\n count = count + 1\n strength = count / (len(population) + 1)\n if strength != 0:\n pareto_ind.fitness = 1 / strength\n\n for population_ind in population:\n suma = 0.0\n for pareto_ind in pareto_set.solutions:\n if pareto_ind.dominates(population_ind):\n suma = suma + 1.0/pareto_ind.fitness\n suma = suma + 1.0\n population_ind.fitness = 1 / suma\n\n\n def reduce_pareto_set(self, par_set):\n \"\"\"\n Realiza el clustering\n \"\"\"\n lista_cluster=[]\n for solucion in par_set.solutions:\n cluster = Cluster()\n cluster.agregar_solucion(solucion)\n lista_cluster.append(cluster)\n \n while len(lista_cluster) > self.max_pareto_points:\n min_distancia = sys.maxint\n for i in range (0,len(lista_cluster)-1):\n for j in range(i+1, len(lista_cluster)-1): \n c = lista_cluster[i]\n distancia = c.calcular_distancia(lista_cluster[j])\n if distancia < min_distancia:\n min_distancia = distancia\n c1 = i\n c2 = j\n \n cluster = lista_cluster[c1].unir(lista_cluster[c2]) #retorna un nuevo cluster \n del lista_cluster[c1]\n del lista_cluster[c2]\n\n lista_cluster.append(cluster)\n \n par_set=[]\n for cluster in lista_cluster:\n solucion = cluster.centroide()\n par_set.append(solucion)\n \n return par_set \n\n def selection(self, population, pareto_set):\n \"\"\"\n Realiza la selección y retorna el mating_pool\n \"\"\"\n pool = []\n unido = []\n unido.extend(population)\n unido.extend(pareto_set.solutions)\n pool_size = len(unido) / 2\n while len(pool) < pool_size:\n c1 = random.choice(unido)\n c2 = random.choice(unido)\n while c1 == c2:\n c2 = random.choice(unido)\n if c1.fitness > c2.fitness:\n pool.append(c1)\n else:\n pool.append(c2)\n return pool\n\n def next_generation(self, mating_pool, pop_size):\n \"\"\"\n Crea la siguiente generacion a partir del mating_pool y los operadores \n genéticos\n \n @param mating_pool: mating pool utilizada para construir la siguiente \n generación de individuos\n \"\"\"\n Q = []\n \n #cruzamiento\n while len(Q) < pop_size:\n parents = []\n parents.append(random.choice(mating_pool))\n other = random.choice(mating_pool)\n parents.append(other)\n if random.random() < self.crossover_rate:\n children = self.genetic_operators.crossover(parents[0], parents[1])\n Q.extend(children)\n else:\n Q.extend(parents)\n \n for ind in Q:\n if random.random() < self.mutation_rate:\n self.genetic_operators.mutation(ind)\n ind.evaluation = ind.evaluate()\n return Q\n\ndef distance_cities(i, j, c, f):\n\n x1 = f[i]%c\n y1 = int(f[i]/c)\n x2 = f[j]%c\n y2 = int(f[j]/c)\n\n return round(math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2)), 4)\n \ndef horizontality_cities(i, j, c, f, sx): \n\n a = int(f[i]/c)\n b = int(f[j]/c)\n if abs(a-b)<=sx and (f[i]%c == f[j]%c):\n return (1)\n else:\n return(10)\n\ndef verticality_cities(i, j, c, f, sy):\n \n a = int(f[i]%c)\n b = int(f[j]%c)\n if abs(a-b)<=sy and ( int(f[i]/c) == int(f[j]/c) ):\n return (1)\n else:\n return(10)\n\ndef rounding_cities(i, j, c, f, sx, sy):\n\n a0 = int(f[i]/c)\n a1 = int(f[i]%c)\n b0 = int(f[j]/c)\n b1 = int(f[j]%c)\n\n if abs(a0-b0)==sx and abs(a1-b1) == sy:\n return (1)\n else:\n return(10)\n\n\n\ndef parse_tsp_2(num_cities, num_objectives, c, free_cells, sx, sy):\n \n mat_objs = [] # [ [ [obj 1], [ obj 2] ],[ [obj 1] , [obj 2] ] ]\n\n for i in xrange(num_objectives):\n mat_objs.append([])\n for j in xrange(num_cities):\n mat_objs[i].append([])\n for k in xrange(num_cities):\n if i == 0:\n mat_objs[i][j].append(distance_cities(j, k, c, free_cells))\n if i == 1:\n mat_objs[i][j].append(rounding_cities(j, k, c, free_cells, sx, sy))\n if i == 2:\n mat_objs[i][j].append(horizontality_cities(j, k, c, free_cells, sx))\n #print \"mat_objs: \\n\" + str(mat_objs[1])\n return mat_objs\n\n# run_tsp with spea\ndef run_spea(n, num_cities, c, free_c, sx, sy, total_ind, total_generations, max_pareto_size, op, num_objectives):\n \n cost_mats = parse_tsp_2(num_cities, num_objectives, c, free_c, sx, sy)\n \n \n objs = []\n for cost_mat in cost_mats:\n objs.append(TSPObjectiveFunction(cost_mat))\n \n \n\n num_cities = len(objs[0].mat)\n spea = SPEA(len(objs), op, max_pareto_size)\n pareto_set = ParetoSet(None)\n \n for i in xrange(n):\n pop = []\n for i in xrange(total_ind):\n sol = range(num_cities)\n random.shuffle(sol)\n pop.append(GaSolution(sol, objs)) \n spea.run(pop, total_generations)\n pareto_set.update(pop)\n \n pareto_front = ParetoFront(pareto_set)\n #pareto_front.draw()\n return pareto_set\n\n\n","sub_path":"ParititioningV1/scripts/spea.py","file_name":"spea.py","file_ext":"py","file_size_in_byte":7132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"211888514","text":"import uuid\n\nfrom situational.testing import BaseCase\nfrom job_discovery import models\n\n\nclass TestJobDiscoveryModel(BaseCase):\n\n def setUp(self):\n self.location = models.JobLocation.objects.create(\n adzuna_locations=\"location\"\n )\n self.other_location = models.JobLocation.objects.create(\n adzuna_locations=\"other_location\"\n )\n self.report = models.JobDiscoveryReport.objects.create(\n postcode=\"N87RW\",\n location=self.location\n )\n self.other_report = models.JobDiscoveryReport.objects.create(\n postcode=\"N87RQ\",\n location=self.other_location\n )\n self.job = models.Job.objects.create(adzuna_id=uuid.uuid4())\n self.job_2 = models.Job.objects.create(adzuna_id=uuid.uuid4())\n self.location.jobs.add(self.job, self.job_2)\n self.other_job = models.Job.objects.create(adzuna_id=uuid.uuid4())\n self.other_location.jobs.add(self.other_job)\n\n def test_get_suggestion_returns_job_from_correct_location(self):\n suggestion = self.report.get_suggestion()\n other_suggestion = self.other_report.get_suggestion()\n self.assertIn(\n suggestion,\n [self.job, self.job_2]\n )\n self.assertEqual(\n other_suggestion,\n self.other_job\n )\n\n def test_get_suggestion_returns_job_not_already_seen(self):\n models.Reaction.objects.create(\n job=self.job,\n report=self.report\n )\n suggestion = self.report.get_suggestion()\n self.assertEqual(\n suggestion,\n self.job_2\n )\n\n def test_get_suggestion_imports_jobs_if_needed(self):\n no_jobs_location = models.JobLocation.objects.create(\n adzuna_locations=\"UK,London,Central London\"\n )\n report = models.JobDiscoveryReport.objects.create(\n postcode=\"N87RZ\",\n location=no_jobs_location\n )\n report.get_suggestion()\n number_jobs = no_jobs_location.jobs.count()\n self.assertTrue(number_jobs, 50)\n\n\nclass TestJobModel(BaseCase):\n def test_has_precise_location(self):\n with self.subTest(\"Job with zero levels of location information\"):\n job = models.Job.objects.create(\n adzuna_id=uuid.uuid4(),\n adzuna_locations=[],\n )\n self.assertFalse(job.has_precise_location)\n\n with self.subTest(\"Job with three levels of location information\"):\n job = models.Job.objects.create(\n adzuna_id=uuid.uuid4(),\n adzuna_locations=(\"UK\", \"London\", \"Central London\"),\n )\n self.assertFalse(job.has_precise_location)\n\n with self.subTest(\"Job with four levels of location information\"):\n job = models.Job.objects.create(\n adzuna_id=uuid.uuid4(),\n adzuna_locations=(\"UK\", \"London\", \"Central London\",\n \"Westminster\"),\n )\n self.assertTrue(job.has_precise_location)\n\n with self.subTest(\"Job with > four levels of location information\"):\n job = models.Job.objects.create(\n adzuna_id=uuid.uuid4(),\n adzuna_locations=(\"UK\", \"London\", \"Central London\",\n \"Westminster\", \"St James Park\"),\n )\n self.assertTrue(job.has_precise_location)\n","sub_path":"situational/apps/job_discovery/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":3464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"526810195","text":"\"\"\"\n Request Model\n\n Copyright: 2009-2022 (c) Sahana Software Foundation\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation\n files (the \"Software\"), to deal in the Software without\n restriction, including without limitation the rights to use,\n copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following\n conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\n__all__ = (\"RequestModel\",\n \"RequestApproverModel\",\n \"RequestItemModel\",\n \"RequestSkillModel\",\n \"RequestRecurringModel\",\n \"RequestNeedsModel\",\n \"RequestNeedsActivityModel\",\n \"RequestNeedsContactModel\",\n \"RequestNeedsDemographicsModel\",\n \"RequestNeedsItemsModel\",\n \"RequestNeedsSkillsModel\",\n \"RequestNeedsOrganisationModel\",\n \"RequestNeedsPersonModel\",\n \"RequestNeedsSectorModel\",\n \"RequestNeedsSiteModel\",\n \"RequestNeedsTagModel\",\n \"RequestOrderItemModel\",\n \"RequestProjectModel\",\n \"RequestTagModel\",\n \"RequestTaskModel\",\n \"RequestRequesterCategoryModel\",\n \"CommitModel\",\n \"CommitItemModel\",\n \"CommitPersonModel\",\n \"CommitSkillModel\",\n #\"req_CheckMethod\",\n \"req_add_from_template\",\n \"req_approvers\",\n \"req_create_form_mods\",\n \"req_hide_quantities\",\n \"req_inline_form\",\n #\"req_is_approver\",\n \"req_match\",\n \"req_ref_represent\",\n \"req_rheader\",\n \"req_send_commit\",\n \"req_tabs\",\n \"req_update_status\",\n \"req_RequesterRepresent\",\n \"req_ReqItemRepresent\",\n )\n\nfrom gluon import *\nfrom gluon.sqlhtml import StringWidget\nfrom gluon.storage import Storage\nfrom ..core import *\nfrom s3layouts import S3PopupLink\n\nfrom .pr import OU\n\nDEFAULT = \"DEFAULT\"\n\nREQ_STATUS_NONE = 0\nREQ_STATUS_PARTIAL = 1\nREQ_STATUS_COMPLETE = 2\nREQ_STATUS_CANCEL = 3\n\n# =============================================================================\ndef req_priority_opts():\n T = current.T\n return {3: T(\"High\"),\n 2: T(\"Medium\"),\n 1: T(\"Low\")\n }\n\n#def req_priority_represent(priority):\n# \"\"\"\n# Represent request priority by a (color-coded) GIF image\n# @ToDo: make CSS-only\n# \"\"\"\n\n# src = URL(c = \"static\",\n# f = \"img\",\n# args = [\"priority\", \"priority_%d.gif\" % (priority or 4)],\n# )\n# return DIV(IMG(_src= src))\n\ndef req_priority():\n priority_opts = req_priority_opts()\n return FieldTemplate(\"priority\", \"integer\",\n default = 2,\n label = current.T(\"Priority\"),\n #@ToDo: Colour code the priority text - red, orange, green\n #represent = req_priority_represent,\n represent = represent_option(priority_opts),\n requires = IS_EMPTY_OR(IS_IN_SET(priority_opts)),\n )\n\n# =============================================================================\ndef req_status_opts():\n T = current.T\n return {REQ_STATUS_NONE: SPAN(T(\"None\"),\n _class = \"req_status_none\",\n ),\n REQ_STATUS_PARTIAL: SPAN(T(\"Partial\"),\n _class = \"req_status_partial\",\n ),\n REQ_STATUS_COMPLETE: SPAN(T(\"Complete\"),\n _class = \"req_status_complete\",\n ),\n }\n\ndef req_status():\n status_opts = req_status_opts()\n return FieldTemplate(\"req_status\", \"integer\",\n label = current.T(\"Request Status\"),\n represent = represent_option(status_opts),\n requires = IS_EMPTY_OR(\n IS_IN_SET(status_opts,\n zero = None,\n )\n ),\n )\n\n# =============================================================================\ndef req_timeframe():\n T = current.T\n timeframe_opts = {1: T(\"0-12 hours\"),\n 2: T(\"12-24 hours\"),\n 3: T(\"1-2 days\"),\n 4: T(\"2-4 days\"),\n 5: T(\"5-7 days\"),\n 6: T(\">1 week\"),\n }\n return Field(\"timeframe\", \"integer\",\n default = 3,\n label = T(\"Timeframe\"),\n represent = represent_option(timeframe_opts),\n requires = IS_EMPTY_OR(\n IS_IN_SET(timeframe_opts, zero = None),\n ),\n )\n\n# =============================================================================\nclass RequestModel(DataModel):\n \"\"\"\n Model for Requests\n \"\"\"\n\n names = (\"req_req\",\n \"req_req_id\",\n \"req_req_ref\",\n )\n\n def model(self):\n\n T = current.T\n db = current.db\n auth = current.auth\n s3 = current.response.s3\n settings = current.deployment_settings\n\n messages = current.messages\n NONE = messages[\"NONE\"]\n UNKNOWN_OPT = messages.UNKNOWN_OPT\n AUTOCOMPLETE_HELP = messages.AUTOCOMPLETE_HELP\n\n add_components = self.add_components\n crud_strings = s3.crud_strings\n set_method = self.set_method\n super_link = self.super_link\n\n person_id = self.pr_person_id\n req_status_field = req_status()\n\n # ---------------------------------------------------------------------\n # Model Options\n #\n ask_security = settings.get_req_ask_security()\n ask_transport = settings.get_req_ask_transport()\n date_writable = settings.get_req_date_writable()\n multiple_req_items = settings.get_req_multiple_req_items()\n recurring = settings.get_req_recurring()\n req_status_writable = settings.get_req_status_writable()\n requester_label = settings.get_req_requester_label()\n transit_status = settings.get_req_show_quantity_transit()\n use_commit = settings.get_req_use_commit()\n use_req_number = settings.get_req_use_req_number()\n use_workflow = settings.get_req_workflow()\n\n # Request Types\n req_types_deployed = settings.get_req_req_type()\n req_types = {}\n if settings.has_module(\"inv\") and \"Stock\" in req_types_deployed:\n # Number hardcoded in controller & JS\n req_types[1] = settings.get_req_type_inv_label()\n #if settings.has_module(\"asset\") and \"Asset\" in req_types_deployed:\n # req_types[2] = T(\"Assets\")\n if settings.has_module(\"hrm\") and \"People\" in req_types_deployed:\n req_types[3] = settings.get_req_type_hrm_label()\n #if settings.has_module(\"cr\") and \"Shelter\" in req_types_deployed:\n # req_types[4] = T(\"Shelter\")\n if \"Other\" in req_types_deployed:\n req_types[9] = T(\"Other\")\n\n # Default Request Type\n if len(req_types) == 1:\n default_type = list(req_types.keys())[0]\n else:\n default_type = current.request.get_vars.get(\"type\")\n if default_type:\n default_type = int(default_type)\n\n # Defaults for Requesting Site and Requester\n requester_is_author = settings.get_req_requester_is_author()\n if requester_is_author and auth.s3_logged_in() and auth.user:\n site_default = auth.user.site_id\n requester_default = auth.s3_logged_in_person()\n else:\n site_default = None\n requester_default = None\n\n # Dropdown or Autocomplete for Requesting Site?\n if settings.get_org_site_autocomplete():\n site_widget = S3SiteAutocompleteWidget()\n site_comment = S3PopupLink(c = \"org\",\n f = \"facility\",\n vars = {\"child\":\"site_id\"},\n title = T(\"Create Facility\"),\n tooltip = AUTOCOMPLETE_HELP,\n )\n else:\n site_widget = None\n site_comment = S3PopupLink(c = \"org\",\n f = \"facility\",\n vars = {\"child\": \"site_id\"},\n title = T(\"Create Facility\"),\n )\n\n # Workflow options\n workflow_opts = {1: T(\"Draft\"),\n 2: T(\"Submitted for Approval\"),\n 3: T(\"Approved\"),\n 4: T(\"Completed\"),\n 5: T(\"Cancelled\"),\n }\n if use_workflow:\n workflow_default = 1 # Draft\n else:\n # Don't make assumptions\n workflow_default = None\n\n # ---------------------------------------------------------------------\n # Request Reference\n #\n req_ref = FieldTemplate(\"req_ref\", \"string\",\n label = T(\"%(REQ)s Number\") %\n {\"REQ\": settings.get_req_shortname()},\n represent = req_ref_represent,\n writable = False,\n )\n\n # ---------------------------------------------------------------------\n # Requests\n #\n tablename = \"req_req\"\n self.define_table(tablename,\n # Instance\n super_link(\"doc_id\", \"doc_entity\"),\n Field(\"type\", \"integer\",\n default = default_type,\n label = T(\"Request Type\"),\n represent = lambda opt: \\\n req_types.get(opt, UNKNOWN_OPT),\n requires = IS_IN_SET(req_types, zero=None),\n readable = not default_type,\n writable = not default_type,\n ),\n req_ref(represent = lambda v, row=None: \\\n req_ref_represent(v, show_link=False),\n readable = use_req_number,\n writable = use_req_number,\n widget = lambda f, v: \\\n StringWidget.widget(f, v, _placeholder = T(\"Leave blank to have this autogenerated\"))\n ),\n DateTimeField(default = \"now\",\n label = T(\"Date Requested\"),\n past = 8760, # Hours, so 1 year\n future = 0,\n readable = date_writable,\n writable = date_writable,\n #represent = \"date\",\n #widget = \"date\",\n ),\n req_priority()(),\n # This is a component, so needs to be a super_link\n # - can't override field name, ondelete or requires\n super_link(\"site_id\", \"org_site\",\n comment = site_comment,\n default = site_default,\n empty = False,\n filterby = \"obsolete\",\n filter_opts = (False,),\n instance_types = auth.org_site_types,\n label = T(\"Requested For Facility\"),\n readable = True,\n represent = self.org_site_represent,\n updateable = True,\n widget = site_widget,\n writable = True,\n ),\n #Field(\"location\",\n # label = T(\"Neighborhood\")),\n # Donations: What will the Items be used for?; People: Task Details\n CommentsField(\"purpose\",\n comment = \"\",\n label = T(\"Purpose\"),\n # Only-needed for summary mode (unused)\n #represent = self.req_purpose_represent,\n represent = lambda s: s if s else NONE,\n ),\n Field(\"is_template\", \"boolean\",\n default = False,\n label = T(\"Recurring Request?\"),\n represent = s3_yes_no_represent,\n readable = recurring,\n writable = recurring,\n comment = DIV(_class=\"tooltip\",\n _title=\"%s|%s\" % (T(\"Recurring Request?\"),\n T(\"If this is a request template to be added repeatedly then the schedule can be set on the next page.\"))),\n ),\n DateTimeField(\"date_required\",\n label = T(\"Date Needed By\"),\n past = 1, # Allow time for people to fill out form\n future = 8760, # Hours, so 1 year\n #represent = \"date\",\n #widget = \"date\",\n ),\n DateTimeField(\"date_required_until\",\n label = T(\"Date Required Until\"),\n past = 0,\n future = 8760, # Hours, so 1 year\n readable = False,\n writable = False\n ),\n person_id(\"requester_id\",\n default = requester_default,\n empty = settings.get_req_requester_optional(),\n label = requester_label,\n represent = req_RequesterRepresent(),\n #writable = False,\n comment = S3PopupLink(c = \"pr\",\n f = \"person\",\n vars = {\"child\": \"requester_id\",\n \"parent\": \"req\",\n },\n title = crud_strings[\"pr_person\"].label_create,\n tooltip = AUTOCOMPLETE_HELP,\n ),\n ),\n person_id(\"assigned_to_id\", # This field should be in req_commit, but that complicates the UI\n label = T(\"Assigned To\"),\n readable = False,\n writable = False,\n ),\n person_id(\"approved_by_id\",\n label = T(\"Approved By\"),\n readable = False,\n writable = False,\n ),\n person_id(\"request_for_id\",\n #default = auth.s3_logged_in_person(),\n label = T(\"Requested For\"),\n readable = False,\n writable = False,\n ),\n Field(\"transport_req\", \"boolean\",\n label = T(\"Transportation Required\"),\n represent = s3_yes_no_represent,\n readable = ask_transport,\n writable = ask_transport,\n ),\n Field(\"security_req\", \"boolean\",\n label = T(\"Security Required\"),\n represent = s3_yes_no_represent,\n readable = ask_security,\n writable = ask_security,\n ),\n DateTimeField(\"date_recv\",\n label = T(\"Date Received\"), # Could be T(\"Date Delivered\") - make deployment_setting or just use Template\n past = 8760, # Hours, so 1 year\n future = 0,\n readable = False,\n writable = False,\n ),\n person_id(\"recv_by_id\",\n # @ToDo: Set this in Update forms? Dedicated 'Receive' button?\n # (Definitely not in Create forms)\n #default = auth.s3_logged_in_person(),\n label = T(\"Received By\"),\n ),\n # Workflow Status\n Field(\"workflow_status\", \"integer\",\n label = T(\"Status\"),\n default = workflow_default,\n requires = IS_IN_SET(workflow_opts),\n represent = represent_option(workflow_opts),\n readable = use_workflow,\n writable = False,\n ),\n # Simple Status\n # - currently just enabled in customise_req_fields() workflow\n req_status_field(readable = False,\n writable = False,\n ),\n # Detailed Status\n req_status_field(\"commit_status\",\n label = T(\"Commit Status\"),\n represent = self.req_commit_status_represent,\n readable = use_commit,\n writable = req_status_writable and use_commit,\n ),\n req_status_field(\"transit_status\",\n label = T(\"Transit Status\"),\n readable = transit_status,\n writable = req_status_writable and transit_status,\n ),\n req_status_field(\"fulfil_status\",\n label = T(\"Fulfil. Status\"),\n writable = req_status_writable,\n ),\n #req_status_field(\"filing_status\",\n # label = T(\"Filing Status\"),\n # comment = DIV(_class=\"tooltip\",\n # _title=\"%s|%s\" % (T(\"Filing Status\"),\n # T(\"Have all the signed documents for this shipment been filed?\"))),\n # readable = settings.get_req_document_filing(),\n # writable = False,\n # ),\n Field(\"closed\", \"boolean\",\n default = False,\n label = T(\"Closed\"),\n readable = not use_workflow,\n writable = not use_workflow,\n comment = DIV(_class = \"tooltip\",\n _title = \"%s|%s\" % (T(\"Closed\"),\n T(\"No more items may be added to this request\"),\n )),\n ),\n Field(\"cancel\", \"boolean\",\n default = False,\n label = T(\"Cancel\"),\n ),\n Field.Method(\"details\", req_req_details),\n Field.Method(\"drivers\", req_req_drivers),\n CommentsField(comment = \"\"),\n )\n\n # CRUD strings\n crud_strings[tablename] = Storage(\n label_create = T(\"Make Request\"),\n title_display = T(\"Request Details\"),\n title_list = T(\"Requests\"),\n title_map=T(\"Map of Requests\"),\n title_report = T(\"Requests Report\"),\n title_update = T(\"Edit Request\"),\n label_list_button = T(\"List Requests\"),\n label_delete_button = T(\"Delete Request\"),\n msg_record_created = T(\"Request Added\"),\n msg_record_modified = T(\"Request Updated\"),\n msg_record_deleted = T(\"Request Canceled\"),\n msg_list_empty = T(\"No Requests\"))\n\n # Which levels of Hierarchy are we using?\n levels = current.gis.get_relevant_hierarchy_levels()\n\n filter_widgets = [\n #TextFilter([\"committer_id$first_name\",\n # \"committer_id$middle_name\",\n # \"committer_id$last_name\",\n # \"site_id$name\",\n # \"comments\",\n # \"req_id$name\",\n # \"organisation_id$name\"\n # ],\n # label = T(\"Search\"),\n # comment = T(\"Search for a Request by Committer name, Request ID, Site or Organization.\"),\n # ),\n OptionsFilter(\"fulfil_status\",\n # Better to default (easier to customise/consistency)\n #label = T(\"Fulfill Status\"),\n cols = 3,\n ),\n LocationFilter(\"site_id$location_id\",\n levels = levels,\n hidden = True,\n ),\n OptionsFilter(\"site_id\",\n # Better to default (easier to customise/consistency)\n #label = T(\"Requested For Facility\"),\n hidden = True,\n ),\n OptionsFilter(\"created_by\",\n label = T(\"Logged By\"),\n hidden = True,\n ),\n DateFilter(\"date\",\n # Better to default (easier to customise/consistency)\n #label = T(\"Date Requested\"),\n hide_time = True,\n input_labels = {\"ge\": \"From\", \"le\": \"To\"},\n comment = T(\"Search for requests made between these dates.\"),\n hidden = True,\n ),\n DateFilter(\"date_required\",\n # Better to default (easier to customise/consistency)\n #label = T(\"Date Needed By\"),\n hide_time = True,\n input_labels = {\"ge\": \"From\", \"le\": \"To\"},\n comment = T(\"Search for requests required between these dates.\"),\n hidden = True,\n ),\n ]\n\n position = 1\n if transit_status:\n position += 1\n filter_widgets.insert(0,\n OptionsFilter(\"transit_status\",\n # Better to default (easier to customise/consistency)\n #label = T(\"Transit Status\"),\n options = req_status_opts,\n cols = 3,\n ))\n\n if not default_type:\n filter_widgets.insert(position,\n OptionsFilter(\"type\",\n label = T(\"Type\"),\n cols = len(req_types),\n ))\n if default_type == 1 or (not default_type and 1 in req_types):\n filter_widgets.insert(position + 2,\n OptionsFilter(\"req_item.item_id$item_category_id\",\n label = T(\"Item Category\"),\n hidden = True,\n ))\n if default_type == 3 or (not default_type and 3 in req_types):\n filter_widgets.insert(position + 2,\n OptionsFilter(\"req_skill.skill_id\",\n # Better to default (easier to customise/consistency)\n #label = T(\"Skill\"),\n hidden = True,\n ))\n if use_commit:\n filter_widgets.insert(position,\n OptionsFilter(\"commit_status\",\n # Better to default (easier to customise/consistency)\n #label = T(\"Commit Status\"),\n options = req_status_opts,\n cols = 3,\n hidden = True,\n ))\n\n report_fields = [\"priority\",\n \"site_id$organisation_id\",\n ]\n rappend = report_fields.append\n for level in levels:\n rappend(\"site_id$location_id$%s\" % level)\n rappend(\"site_id\")\n # @ToDo: id gets stripped in _select_field\n fact_fields = report_fields + [(T(\"Requests\"), \"id\")]\n\n # Reusable Field\n represent = self.req_represent\n req_id = FieldTemplate(\"req_id\", \"reference %s\" % tablename,\n label = T(\"Request\"),\n ondelete = \"CASCADE\",\n represent = represent,\n requires = IS_EMPTY_OR(\n IS_ONE_OF(db, \"req_req.id\",\n lambda req_id, row=None: \\\n represent(req_id, row, show_link=False),\n orderby = \"req_req.date\",\n sort = True,\n )),\n sortby = \"date\",\n )\n\n list_fields = [\"id\",\n \"date\",\n \"date_required\",\n \"site_id\",\n \"requester_id\",\n ]\n\n # @ToDo: Allow a single column to support different components based on type\n # - this is the 'Details' VF\n # @ToDo: Include Qty too (Computed VF in component?)\n # - this is done in the 'Details' VF\n #if default_type == 1 or (not default_type and 1 in req_types):\n # list_fields.append((T(\"Requested Items\"), \"req_item.item_id\"))\n #if default_type == 3 or (not default_type and 3 in req_types):\n # list_fields.append((T(\"Requested Skills\"), \"req_skill.skill_id\"))\n\n if use_req_number:\n list_fields.insert(1, \"req_ref\")\n list_fields.extend((\"priority\",\n (T(\"Details\"), \"details\"),\n ))\n if 1 in req_types:\n list_fields.append((T(\"Drivers\"), \"drivers\"))\n if use_commit:\n list_fields.append(\"commit_status\")\n if transit_status:\n list_fields.append(\"transit_status\")\n list_fields.append(\"fulfil_status\")\n if use_commit:\n list_fields.append((T(\"Committed By\"), \"commit.site_id\"))\n\n self.configure(tablename,\n context = {\"location\": \"site_id$location_id\",\n \"organisation\": \"site_id$organisation_id\",\n \"site\": \"site_id\",\n },\n deduplicate = S3Duplicate(primary = (\"req_ref\",)),\n extra_fields = (\"req_ref\", \"type\"),\n filter_widgets = filter_widgets,\n onaccept = self.req_onaccept,\n ondelete = self.req_req_ondelete,\n # Why was this set? Should be consistent with other resources\n # Can add this to be specific templates/views which need this if-required\n #listadd = False,\n list_fields = list_fields,\n orderby = \"req_req.date desc\",\n report_options = Storage(\n rows = report_fields,\n cols = report_fields,\n fact = fact_fields,\n methods = [\"count\", \"list\", \"sum\"],\n defaults = Storage(\n rows = \"site_id$location_id$%s\" % levels[0], # Highest-level of hierarchy\n cols = \"priority\",\n fact = \"count(id)\",\n totals = True,\n )\n ),\n super_entity = \"doc_entity\",\n # Leave this to templates\n # - reduce load on templates which don't need this\n #update_realm = True,\n realm_components = (\"req_item\",\n \"req_skill\",\n ),\n )\n\n # Custom Methods\n set_method(\"req_req\",\n method = \"check\",\n action = req_CheckMethod())\n\n set_method(\"req_req\",\n method = \"commit_all\",\n action = self.req_commit_all)\n\n set_method(\"req_req\",\n method = \"copy_all\",\n action = self.req_copy_all)\n\n set_method(\"req_req\",\n method = \"submit\",\n action = self.req_submit)\n\n set_method(\"req_req\",\n method = \"approve_req\", # Don't clash with core approve method\n action = self.req_approve)\n\n # Print Forms\n set_method(\"req_req\",\n method = \"form\",\n action = self.req_form)\n\n # Components\n add_components(tablename,\n # Tags\n req_req_tag = {\"alias\": \"tag\",\n \"joinby\": \"req_id\",\n },\n # Requested Items\n req_req_item = {\"joinby\": \"req_id\",\n \"multiple\": multiple_req_items,\n },\n # Requested Skills\n req_req_skill = {\"joinby\": \"req_id\",\n \"multiple\": multiple_req_items,\n },\n # Commitment\n req_commit = \"req_id\",\n # Item Categories\n supply_item_category = {\"link\": \"req_req_item_category\",\n \"joinby\": \"req_id\",\n \"key\": \"item_category_id\",\n },\n # Approvers\n req_approver_req = {\"name\": \"approver\",\n \"joinby\": \"req_id\",\n },\n\n # Projects\n req_project_req = {\"joinby\": \"req_id\",\n \"multiple\": False,\n },\n project_project = {\"link\": \"req_project_req\",\n \"joinby\": \"req_id\",\n \"key\": \"project_id\",\n \"actuate\": \"hide\",\n \"multiple\": False,\n },\n **{# Scheduler Jobs (for recurring requests)\n S3Task.TASK_TABLENAME: {\"name\": \"job\",\n \"joinby\": \"req_id\",\n \"link\": \"req_job\",\n \"key\": \"scheduler_task_id\",\n \"actuate\": \"replace\",\n },\n }\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return {\"req_req_id\": req_id,\n \"req_req_ref\": req_ref,\n }\n\n # -------------------------------------------------------------------------\n def defaults(self):\n \"\"\"\n Safe defaults for model-global names in case module is disabled\n \"\"\"\n\n dummy = FieldTemplate.dummy\n\n return {\"req_req_id\": dummy(\"req_id\"),\n \"req_req_ref\": dummy(\"req_ref\", \"string\"),\n }\n\n # -------------------------------------------------------------------------\n @staticmethod\n def req_represent(req_id, row=None, show_link=True, pdf=False):\n \"\"\"\n Represent a Request\n\n TODO document parameters\n TODO S3Represent\n \"\"\"\n\n if row:\n table = current.db.req_req\n elif not req_id:\n return current.messages[\"NONE\"]\n else:\n req_id = int(req_id)\n if req_id:\n db = current.db\n table = db.req_req\n row = db(table.id == req_id).select(table.date,\n table.req_ref,\n table.site_id,\n limitby = (0, 1)\n ).first()\n try:\n if row.req_ref:\n req = row.req_ref\n else:\n req = \"%s - %s\" % (table.site_id.represent(row.site_id,\n show_link=False),\n table.date.represent(row.date))\n except (AttributeError, TypeError):\n return current.messages.UNKNOWN_OPT\n\n if show_link:\n if pdf:\n args = [req_id, \"form\"]\n _title = current.T(\"Open PDF\")\n else:\n args = [req_id]\n _title = current.T(\"Go to Request\")\n return A(req,\n _href = URL(c=\"req\", f=\"req\",\n args=args,\n ),\n _title = _title)\n else:\n return req\n\n # -------------------------------------------------------------------------\n @staticmethod\n def req_commit_status_represent(commit_status):\n \"\"\"\n Represet the Commitment Status of the Request\n \"\"\"\n\n if commit_status == REQ_STATUS_COMPLETE:\n # Include the Site Name of the Committer if we can\n # @ToDo: figure out how!\n return SPAN(current.T(\"Complete\"),\n _class = \"req_status_complete\",\n )\n else:\n return req_status_opts().get(commit_status,\n current.messages.UNKNOWN_OPT)\n\n # -------------------------------------------------------------------------\n @staticmethod\n def req_copy_all(r, **attr):\n \"\"\"\n Copy an existing Request (custom REST method)\n - creates a req with req_item records\n \"\"\"\n\n db = current.db\n s3db = current.s3db\n table = s3db.req_req\n settings = current.deployment_settings\n now = current.request.now\n\n record = r.record\n req_id = record.id\n # Make a copy of the request record\n if settings.get_req_use_req_number():\n code = s3db.supply_get_shipping_code(settings.get_req_shortname(),\n record.site_id,\n table.req_ref,\n )\n else:\n code = None\n if record.date_required and record.date_required < now:\n date_required = now + datetime.timedelta(days=14)\n else:\n date_required = record.date_required\n new_req_id = table.insert(type = record.type,\n req_ref = code,\n date = now,\n date_required = date_required,\n priority = record.priority,\n site_id = record.site_id,\n purpose = record.purpose,\n requester_id = record.requester_id,\n transport_req = record.transport_req,\n security_req = record.security_req,\n comments = record.comments,\n )\n # Make a copy of each child record\n if record.type == 1:\n # Items\n ritable = s3db.req_req_item\n items = db(ritable.req_id == req_id).select(ritable.id,\n ritable.item_entity_id,\n ritable.item_id,\n ritable.item_pack_id,\n ritable.quantity,\n ritable.pack_value,\n ritable.currency,\n ritable.site_id,\n ritable.comments,\n )\n if items:\n insert = ritable.insert\n for item in items:\n insert(req_id = new_req_id,\n item_entity_id = item.item_entity_id,\n item_id = item.item_id,\n item_pack_id = item.item_pack_id,\n quantity = item.quantity,\n pack_value = item.pack_value,\n currency = item.currency,\n site_id = item.site_id,\n comments = item.comments,\n )\n elif record.type == 3:\n # People and skills\n rstable = s3db.req_req_skill\n skills = db(rstable.req_id == req_id).select(rstable.id,\n rstable.skill_id,\n rstable.quantity,\n rstable.site_id,\n rstable.comments,\n )\n if skills:\n insert = rstable.insert\n for skill in skills:\n insert(req_id = new_req_id,\n skill_id = skill.skill_id,\n quantity = skill.quantity,\n site_id = skill.site_id,\n comments = skill.comments,\n )\n\n redirect(URL(f = \"req\",\n args = [new_req_id, \"update\"],\n ))\n\n # -------------------------------------------------------------------------\n @staticmethod\n def req_commit_all(r, **attr):\n \"\"\"\n Custom Method to commit to a Request\n - creates a commit with commit_items for each req_item or\n commit_skills for each req_skill\n \"\"\"\n\n T = current.T\n db = current.db\n s3db = current.s3db\n table = s3db.req_commit\n\n record = r.record\n req_id = record.id\n\n # Check if there is an existing Commitment\n query = (table.req_id == req_id) & \\\n (table.deleted == False)\n exists = db(query).select(table.id,\n limitby = (0, 1)\n ).first()\n if exists:\n # Browse existing commitments\n redirect(URL(f = \"req\",\n args = [r.id, \"commit\"],\n ))\n\n req_type = record.type\n\n # Create the commitment\n cid = table.insert(req_id = req_id,\n type = req_type,\n )\n\n if req_type == 1:\n # Items\n ritable = s3db.req_req_item\n items = db(ritable.req_id == req_id).select(ritable.id,\n ritable.item_pack_id,\n ritable.quantity,\n ritable.comments,\n )\n if items:\n citable = s3db.req_commit_item\n insert = citable.insert\n for item in items:\n commit_item_id = item.id\n quantity = item.quantity\n insert(commit_id = cid,\n req_item_id = commit_item_id,\n item_pack_id = item.item_pack_id,\n quantity = quantity,\n comments = item.comments,\n )\n # Mark Item in the Request as Committed\n db(ritable.id == commit_item_id).update(quantity_commit = quantity)\n # Mark Request as Committed\n db(s3db.req_req.id == req_id).update(commit_status = REQ_STATUS_COMPLETE)\n msg = T(\"You have committed to all items in this Request. Please check that all details are correct and update as-required.\")\n\n elif req_type == 3:\n # People\n rstable = s3db.req_req_skill\n skills = db(rstable.req_id == req_id).select(rstable.id,\n rstable.skill_id,\n rstable.quantity,\n rstable.comments,\n )\n if skills:\n # @ToDo:\n #if current.deployment_settings.get_req_commit_people():\n #else:\n cstable = s3db.req_commit_skill\n insert = cstable.insert\n for skill in skills:\n commit_skill_id = skill.id\n quantity = skill.quantity\n insert(commit_id = cid,\n skill_id = skill.skill_id,\n quantity = quantity,\n comments = skill.comments,\n )\n # Mark Item in the Request as Committed\n db(rstable.id == commit_skill_id).update(quantity_commit = quantity)\n # Mark Request as Committed\n db(s3db.req_req.id == req_id).update(commit_status = REQ_STATUS_COMPLETE)\n msg = T(\"You have committed for all people in this Request. Please check that all details are correct and update as-required.\")\n\n else:\n # Other\n # Mark Request as Committed\n db(s3db.req_req.id == req_id).update(commit_status = REQ_STATUS_COMPLETE)\n msg = T(\"You have committed to this Request. Please check that all details are correct and update as-required.\")\n\n if \"send\" in r.args:\n redirect(URL(f = \"send_commit\",\n args = [cid],\n ))\n\n elif \"assign\" in r.args:\n redirect(URL(f = \"commit\",\n args = [cid, \"assign\"],\n ))\n\n else:\n current.session.confirmation = msg\n redirect(URL(c=\"req\", f=\"commit\",\n args = [cid],\n ))\n\n # -------------------------------------------------------------------------\n @staticmethod\n def req_form(r, **attr):\n \"\"\"\n Generate a PDF of a Request Form (custom REST method)\n \"\"\"\n\n record = r.record\n\n if record.type == 1:\n pdf_componentname = \"req_item\"\n list_fields = [\"item_id\",\n \"item_pack_id\",\n \"quantity\",\n \"quantity_commit\",\n \"quantity_transit\",\n \"quantity_fulfil\",\n ]\n elif record.type == 3:\n pdf_componentname = \"req_skill\"\n list_fields = [\"skill_id\",\n \"quantity\",\n \"quantity_commit\",\n \"quantity_transit\",\n \"quantity_fulfil\",\n ]\n else:\n # Not Supported - redirect to normal PDF\n redirect(URL(args = current.request.args[0],\n extension = \"pdf\"))\n\n if current.deployment_settings.get_req_use_req_number():\n filename = record.req_ref\n else:\n filename = None\n\n from core import DataExporter\n exporter = DataExporter.pdf\n return exporter(r.resource,\n request = r,\n method = \"list\",\n pdf_title = current.deployment_settings.get_req_form_name(),\n pdf_filename = filename,\n list_fields = list_fields,\n pdf_hide_comments = True,\n pdf_componentname = pdf_componentname,\n pdf_header_padding = 12,\n #pdf_footer = inv_recv_pdf_footer,\n pdf_table_autogrow = \"B\",\n pdf_orientation = \"Landscape\",\n **attr\n )\n\n # -------------------------------------------------------------------------\n @staticmethod\n def req_submit(r, **attr):\n \"\"\"\n Submit a Request for Approval (custom REST method)\n \"\"\"\n\n record = r.record\n req_id = r.id\n\n # Check we are the right place in the workflow\n if record.workflow_status != 1:\n current.session.error = current.T(\"Can only Submit Draft Requests\")\n redirect(URL(args = req_id))\n\n s3db = current.s3db\n rtable = s3db.req_req\n\n # Check we have permission to update the Request\n if not current.auth.s3_has_permission(\"update\", rtable, record_id=req_id):\n r.unauthorised()\n\n db = current.db\n\n # Lookup Approver(s)\n site_id = record.site_id\n stable = s3db.org_site\n site_entity = db(stable.site_id == site_id).select(stable.instance_type,\n limitby = (0, 1)\n ).first()\n itable = s3db.table(site_entity.instance_type)\n site = db(itable.site_id == site_id).select(itable.name, # Needed later for Message construction\n itable.pe_id,\n limitby = (0, 1)\n ).first()\n pe_id = site.pe_id\n ancestors = s3db.pr_get_ancestors(pe_id)\n pe_ids = ancestors + [pe_id]\n atable = s3db.req_approver\n ptable = s3db.pr_person\n ltable = s3db.pr_person_user\n utable = db.auth_user\n query = (atable.pe_id.belongs(pe_ids)) & \\\n (atable.person_id == ptable.id) & \\\n (ptable.pe_id == ltable.pe_id) & \\\n (ltable.user_id == utable.id)\n approvers = db(query).select(ptable.pe_id,\n utable.language,\n )\n if not approvers:\n current.session.error = current.T(\"No Request Approver defined\")\n redirect(URL(args = req_id))\n\n # Send Localised Mail(s)\n T = current.T\n languages = {}\n for row in approvers:\n language = row[\"auth_user.language\"]\n if language not in languages:\n languages[language] = []\n languages[language].append(row[\"pr_person.pe_id\"])\n session_s3 = current.session.s3\n ui_language = session_s3.language\n url = \"%s%s\" % (current.deployment_settings.get_base_public_url(),\n URL(c=\"req\", f=\"req\",\n args = req_id,\n ))\n req_ref = record.req_ref\n requester = record.requester_id\n date_required = record.date_required\n date_represent = S3DateTime.date_represent # We want Dates not datetime which table.date_required uses\n site_name = site.name\n send_email = current.msg.send_by_pe_id\n subject_T = T(\"Request submitted for Approval\")\n message_T = T(\"A new Request, %(reference)s, has been submitted for Approval by %(person)s for delivery to %(site)s by %(date_required)s. Please review at: %(url)s\")\n for language in languages:\n T.force(language)\n session_s3.language = language # for date_represent\n subject = \"%s: %s\" % (s3_str(subject_T), req_ref)\n message = s3_str(message_T) % {\"date_required\": date_represent(date_required),\n \"reference\": req_ref,\n \"person\": requester,\n \"site\": site_name,\n \"url\": url,\n }\n users = languages[language]\n for pe_id in users:\n send_email(pe_id,\n subject = subject,\n message = message,\n )\n # Restore language for UI\n session_s3.language = ui_language\n T.force(ui_language)\n\n # Update the Status\n db(rtable.id == req_id).update(workflow_status = 2) # Submitted\n\n current.session.confirmation = T(\"Request submitted for Approval\")\n redirect(URL(args = req_id))\n\n # -------------------------------------------------------------------------\n @staticmethod\n def req_approve(r, **attr):\n \"\"\"\n Approve a Request (custom REST method)\n\n NB This is currently hardcoded to Items Requests not Person Requests\n NB This is currently hardcoded to RMS roles\n \"\"\"\n\n record = r.record\n\n # Check we are the right place in the workflow\n if record.workflow_status != 2:\n current.session.error = current.T(\"Can only Approve Submitted Requests\")\n redirect(URL(args = r.id))\n\n s3db = current.s3db\n rtable = s3db.req_req\n\n req_id = r.id\n\n approvers = req_approvers(record.site_id)\n person_id = current.auth.s3_logged_in_person()\n\n # Check we have permission to approve the Request\n if person_id not in approvers:\n r.unauthorised()\n\n db = current.db\n\n # Check if this person has already approved the Request\n artable = s3db.req_approver_req\n approved = db(artable.req_id == req_id).select(artable.person_id)\n approved = [row.person_id for row in approved]\n if person_id in approved:\n current.session.warning = current.T(\"You have already Approved this Request\")\n redirect(URL(args = req_id))\n\n ritable = s3db.req_req_item\n query = (ritable.req_id == req_id) & \\\n (ritable.deleted == False)\n request_items = db(query).select(ritable.id,\n ritable.site_id,\n )\n site_ids = [row.site_id for row in request_items]\n\n approver = approvers[person_id]\n\n if approver[\"matcher\"]:\n # This person is responsible for Matching Items to Warehouses\n if None in site_ids:\n # Check for Purchases\n unmatched_items = [row.id for row in request_items if row.site_id == None]\n oitable = s3db.req_order_item\n orders = db(oitable.req_item_id.belongs(unmatched_items)).select(oitable.id)\n if len(unmatched_items) != len(orders):\n current.session.warning = current.T(\"You need to Match Items in this Request\")\n redirect(URL(args = [req_id, \"req_item\"]))\n\n # Add record to show that we have approved request\n artable.insert(req_id = req_id,\n person_id = person_id,\n title = approver[\"title\"],\n )\n\n T = current.T\n session = current.session\n\n # Have all Approvers approved the Request?\n if len(approvers) == len(approved) + 1:\n # Update the Status\n db(rtable.id == req_id).update(workflow_status = 3, # Approved\n )\n # Notify the Warehouse Operator(s)\n session_s3 = session.s3\n ui_language = session_s3.language\n url = \"%s%s\" % (current.deployment_settings.get_base_public_url(),\n URL(c=\"req\", f=\"req\",\n args = [req_id, \"req_item\"],\n ))\n req_ref = record.req_ref\n date_required = record.date_required\n date_represent = S3DateTime.date_represent # We want Dates not datetime which table.date_required uses\n send_email = current.msg.send_by_pe_id\n subject_T = T(\"Request Approved for Items from your Warehouse\")\n message_T = T(\"A new Request, %(reference)s, has been Approved for shipment from %(site)s by %(date_required)s. Please review at: %(url)s\")\n\n site_ids = set(site_ids)\n stable = s3db.org_site\n site_entities = db(stable.site_id.belongs(site_ids)).select(stable.site_id,\n stable.instance_type,\n )\n # Sort by Instance Type\n sites_by_type = {}\n for row in site_entities:\n instance_type = row.instance_type\n if instance_type not in sites_by_type:\n sites_by_type[instance_type] = []\n sites_by_type[instance_type].append(row.site_id)\n\n # Lookup Names & PE IDs\n sites = {}\n for instance_type in sites_by_type:\n itable = s3db.table(instance_type)\n instances = db(itable.site_id.belongs(sites_by_type[instance_type])).select(itable.name,\n itable.pe_id,\n itable.site_id,\n )\n for row in instances:\n sites[row.site_id] = {\"name\": row.name,\n \"pe_id\": row.pe_id,\n }\n gtable = db.auth_group\n mtable = db.auth_membership\n utable = db.auth_user\n ltable = s3db.pr_person_user\n\n atable = s3db.pr_affiliation\n rtable = s3db.pr_role\n\n # Lookup realm for all wh_operator with default realm outside of loop\n # NB The role name is specific to RMS template currently, which is the only one to use this workflow\n # Incorporates a Bulk version of s3db.pr_realm()\n query = (gtable.uuid == \"wh_operator\") & \\\n (gtable.id == mtable.group_id) & \\\n (mtable.pe_id == None) & \\\n (mtable.deleted == False) & \\\n (mtable.user_id == utable.id) & \\\n (utable.id == ltable.user_id) & \\\n (atable.pe_id == ltable.pe_id) & \\\n (atable.deleted == False) & \\\n (atable.role_id == rtable.id) & \\\n (rtable.deleted == False) & \\\n (rtable.role_type == OU)\n wh_operators_default_realm = db(query).select(ltable.pe_id,\n utable.language,\n rtable.pe_id,\n )\n\n for site_id in sites:\n\n site = sites[site_id]\n site_name = site[\"name\"]\n pe_id = site[\"pe_id\"]\n\n # Find the relevant wh_operator\n # NB The role name is specific to RMS template currently, which is the only one to use this workflow\n entities = s3db.pr_get_ancestors(pe_id)\n entities.append(pe_id)\n\n query = (gtable.uuid == \"wh_operator\") & \\\n (gtable.id == mtable.group_id) & \\\n (mtable.pe_id.belongs(entities)) & \\\n (mtable.deleted == False) & \\\n (mtable.user_id == utable.id) & \\\n (utable.id == ltable.user_id)\n operators = db(query).select(ltable.pe_id,\n utable.language,\n )\n operators = list(operators)\n for row in wh_operators_default_realm:\n if row[\"pr_role.pe_id\"] in entities:\n operators.append(row)\n\n if not operators:\n # Send to logs_manager instead\n # NB We lookup the ones with default realm inside the loop as we don't expect to his this often\n query = (gtable.uuid == \"logs_manager\") & \\\n (gtable.id == mtable.group_id) & \\\n ((mtable.pe_id.belongs(entities)) | \\\n (mtable.pe_id == None)) & \\\n (mtable.deleted == False) & \\\n (mtable.user_id == utable.id) & \\\n (utable.id == ltable.user_id)\n users = db(query).select(ltable.pe_id,\n utable.language,\n mtable.pe_id,\n )\n operators = []\n default_realm_lookups = []\n for row in users:\n if row[\"auth_membership.pe_id\"]:\n # Definite match\n operators.append(row)\n else:\n # Possible Match\n default_realm_lookups.append(row)\n\n user_pe_id = [row[\"pr_person_user.pe_id\"] for row in default_realm_lookups]\n # Bulk version of s3db.pr_realm()\n query = (atable.deleted != True) & \\\n (atable.role_id == rtable.id) & \\\n (atable.pe_id.belongs(user_pe_id)) & \\\n (rtable.deleted != True) & \\\n (rtable.role_type == OU) & \\\n (atable.pe_id == ltable.pe_id) & \\\n (ltable.user_id == utable.id)\n logs_managers_default_realm = db(query).select(ltable.pe_id,\n utable.language,\n rtable.pe_id,\n )\n for row in logs_managers_default_realm:\n if row[\"pr_role.pe_id\"] in entities:\n operators.append(row)\n\n if not operators:\n # Send to ADMIN instead\n query = (gtable.uuid == \"ADMIN\") & \\\n (gtable.id == mtable.group_id) & \\\n (mtable.deleted == False) & \\\n (mtable.user_id == utable.id) & \\\n (utable.id == ltable.user_id)\n operators = db(query).select(ltable.pe_id,\n utable.language,\n )\n\n # Send Localised Mail(s)\n languages = {}\n for row in operators:\n language = row[\"auth_user.language\"]\n if language not in languages:\n languages[language] = []\n languages[language].append(row[\"pr_person_user.pe_id\"])\n for language in languages:\n T.force(language)\n session_s3.language = language # for date_represent\n subject = \"%s: %s\" % (s3_str(subject_T), req_ref)\n message = s3_str(message_T) % {\"date_required\": date_represent(date_required),\n \"reference\": req_ref,\n \"site\": site_name,\n \"url\": url,\n }\n users = languages[language]\n for pe_id in users:\n send_email(pe_id,\n subject = subject,\n message = message,\n )\n\n # Restore language for UI\n session_s3.language = ui_language\n T.force(ui_language)\n\n session.confirmation = T(\"Request Approved\")\n redirect(URL(args = req_id))\n\n # -------------------------------------------------------------------------\n @staticmethod\n def req_onaccept(form):\n \"\"\"\n On-accept actions for requests\n - auto-generate a request number (req_ref) if required and\n not specified in form\n - translate simple request status into differentiated\n committed/fulfilled statuses\n - add requester as human resource of the requesting site if\n configured to do so automatically\n - configure post-create/update redirection depending on request\n type (e.g. request for items => select items for request)\n \"\"\"\n\n db = current.db\n s3db = current.s3db\n settings = current.deployment_settings\n\n tablename = \"req_req\"\n table = s3db.req_req\n\n req_id = form.vars.id\n record = db(table.id == req_id).select(table.id,\n table.type,\n table.site_id,\n table.requester_id,\n table.is_template,\n table.req_ref,\n table.req_status,\n table.commit_status,\n table.fulfil_status,\n table.cancel,\n limitby = (0, 1)\n ).first()\n if record.is_template:\n is_template = True\n f = \"req_template\"\n else:\n is_template = False\n f = \"req\"\n\n update = {}\n\n if settings.get_req_use_req_number() and not record.req_ref:\n # Auto-generate req_ref\n code = s3db.supply_get_shipping_code(settings.get_req_shortname(),\n record.site_id,\n table.req_ref,\n )\n update[\"req_ref\"] = code\n\n req_status = record.req_status\n if req_status is not None:\n status_requires = table.req_status.requires\n if hasattr(status_requires, \"other\"):\n status_requires = status_requires.other\n opts = [opt[0] for opt in status_requires.options()]\n if str(REQ_STATUS_CANCEL) in opts:\n # Cancel flag implied by simple status\n update[\"cancel\"] = False\n elif record.cancel:\n # Using explicit cancel flag\n update[\"workflow_status\"] = 5\n\n # Translate Simple Status\n if req_status == REQ_STATUS_PARTIAL:\n if record.commit_status != REQ_STATUS_COMPLETE:\n update[\"commit_status\"] = REQ_STATUS_PARTIAL\n if record.fulfil_status == REQ_STATUS_COMPLETE:\n update[\"fulfil_status\"] = REQ_STATUS_PARTIAL\n\n elif req_status == REQ_STATUS_COMPLETE:\n update[\"fulfil_status\"] = REQ_STATUS_COMPLETE\n\n elif req_status == REQ_STATUS_CANCEL:\n update[\"cancel\"] = True\n update[\"workflow_status\"] = 5\n\n elif req_status == REQ_STATUS_NONE:\n update[\"commit_status\"] = REQ_STATUS_NONE\n update[\"fulfil_status\"] = REQ_STATUS_NONE\n\n elif record.cancel:\n # Using 3-tiered status (commit/transit/fulfill), and explicit cancel flag\n update[\"workflow_status\"] = 5\n\n if update:\n record.update_record(**update)\n\n if settings.get_req_requester_to_site():\n requester_id = record.requester_id\n if requester_id:\n site_id = record.site_id\n # If the requester has no HR record, then create one\n hrtable = s3db.hrm_human_resource\n query = (hrtable.person_id == requester_id)\n exists = db(query).select(hrtable.id,\n hrtable.organisation_id,\n hrtable.site_id,\n hrtable.site_contact,\n limitby = (0, 1)\n ).first()\n if exists:\n if site_id and not exists.site_id:\n # Check that the Request site belongs to this Org\n stable = s3db.org_site\n site = db(stable.site_id == site_id).select(stable.organisation_id,\n limitby = (0, 1)\n ).first()\n # @ToDo: Think about branches\n if site and site.organisation_id == exists.organisation_id:\n # Set the HR record as being for this site\n exists.update(site_id = site_id)\n s3db.hrm_human_resource_onaccept(exists)\n elif site_id:\n # Lookup the Org for the site\n stable = s3db.org_site\n site = db(stable.site_id == site_id).select(stable.organisation_id,\n limitby = (0, 1)\n ).first()\n # Is there already a site_contact for this site?\n ltable = s3db.hrm_human_resource_site\n query = (ltable.site_id == site_id) & \\\n (ltable.site_contact == True)\n already = db(query).select(ltable.id,\n limitby = (0, 1)\n ).first()\n if already:\n site_contact = False\n else:\n site_contact = True\n hr_id = hrtable.insert(person_id = requester_id,\n organisation_id = site.organisation_id,\n site_id = site_id,\n site_contact = site_contact,\n )\n s3db.hrm_human_resource_onaccept(Storage(id = hr_id))\n\n # Update the Realm if the Requesting site changes\n # - now left to templates\n #if form.record:\n # if record.site_id != form.record.site_id:\n # realm_entity = current.auth.get_realm_entity(table, record)\n # record.update_record(realm_entity = realm_entity)\n # req_type = record.type\n # if req_type == 1:\n # db(s3db.req_req_item.req_id == req_id).update(realm_entity = realm_entity)\n # #elif req_type == 2:\n # # db(s3db.req_req_asset.req_id == req_id).update(realm_entity = realm_entity)\n # elif req_type == 3:\n # db(s3db.req_req_skill.req_id == req_id).update(realm_entity = realm_entity)\n # #elif req_type == 4:\n # # db(s3db.req_req_shelter.req_id == req_id).update(realm_entity = realm_entity)\n\n # Configure the next page to go to based on the request type\n inline_forms = settings.get_req_inline_forms()\n if inline_forms and is_template:\n s3db.configure(tablename,\n create_next = URL(c=\"req\", f=f,\n args = [\"[id]\", \"job\"],\n ),\n update_next = URL(c=\"req\", f=f,\n args=[\"[id]\", \"job\"],\n ))\n\n elif not inline_forms:\n req_type = record.type\n if req_type == 1 and settings.has_module(\"inv\"):\n s3db.configure(tablename,\n create_next = URL(c=\"req\", f=f,\n args = [\"[id]\", \"req_item\"],\n ),\n update_next = URL(c=\"req\", f=f,\n args=[\"[id]\", \"req_item\"],\n ))\n #elif req_type == 2 and settings.has_module(\"asset\"):\n # s3db.configure(tablename,\n # create_next = URL(c=\"req\", f=f,\n # args = [\"[id]\", \"req_asset\"],\n # ),\n # update_next = URL(c=\"req\", f=f,\n # args = [\"[id]\", \"req_asset\"],\n # ))\n elif req_type == 3 and settings.has_module(\"hrm\"):\n s3db.configure(tablename,\n create_next = URL(c=\"req\", f=f,\n args = [\"[id]\", \"req_skill\"],\n ),\n update_next = URL(c=\"req\", f=f,\n args = [\"[id]\", \"req_skill\"],\n ))\n #elif req_type == 4 and settings.has_module(\"cr\"):\n # s3db.configure(tablename,\n # create_next = URL(c=\"req\", f=f,\n # args = [\"[id]\", \"req_shelter\"],\n # ),\n # update_next = URL(c=\"req\", f=f,\n # args = [\"[id]\", \"req_shelter\"],\n # ))\n\n # -------------------------------------------------------------------------\n @staticmethod\n def req_req_ondelete(row):\n \"\"\"\n Remove any scheduled tasks when deleting a recurring request\n template\n\n Args:\n row: the deleted req_req Row\n \"\"\"\n\n db = current.db\n table = db.scheduler_task\n query = (table.function_name == \"req_add_from_template\") & \\\n (table.args == \"[%s]\" % row.id)\n db(query).delete()\n\n# =============================================================================\nclass RequestApproverModel(DataModel):\n \"\"\"\n Model for request approvers\n \"\"\"\n\n names = (\"req_approver\",\n \"req_approver_req\",\n )\n\n def model(self):\n\n T = current.T\n\n define_table = self.define_table\n\n person_id = self.pr_person_id\n\n # -----------------------------------------------------------------\n # Request Approvers\n #\n instance_types = [\"org_organisation\"] + list(current.auth.org_site_types.keys())\n entity_represent = self.pr_PersonEntityRepresent(show_type = False)\n\n tablename = \"req_approver\"\n define_table(tablename,\n # Could be a Site or Organisation\n self.super_link(\"pe_id\", \"pr_pentity\",\n label = T(\"Organization/Site\"),\n empty = False,\n filterby = \"instance_type\", # Not using instance_types as not a Super-Entity\n filter_opts = instance_types,\n represent = entity_represent,\n readable = True,\n writable = True,\n # @ToDo: Widget\n #widget = S3PentityWidget(),\n ),\n Field(\"title\", # 'position' is a Reserved word in SQL\n label = T(\"Position\"),\n ),\n person_id(),\n Field(\"matcher\", \"boolean\",\n default = False,\n label = T(\"Matcher\"),\n represent = s3_yes_no_represent,\n comment = DIV(_class = \"tooltip\",\n _title = \"%s|%s\" % (T(\"Matcher\"),\n T(\"Is this person the one to match request items to specific warehouses &/or purchase them.\"),\n ))\n ),\n CommentsField(),\n )\n\n # CRUD strings\n current.response.s3.crud_strings[tablename] = Storage(\n label_create = T(\"Add Approver\"),\n title_display = T(\"Approver Details\"),\n title_list = T(\"Request Approvers\"),\n title_update = T(\"Edit Approver\"),\n label_list_button = T(\"List Approvers\"),\n label_delete_button = T(\"Delete Approver\"),\n msg_record_created = T(\"Approver added\"),\n msg_record_modified = T(\"Approver updated\"),\n msg_record_deleted = T(\"Approver deleted\"),\n msg_list_empty = T(\"No Approvers currently registered\"))\n\n # -----------------------------------------------------------------\n # Link Approvers <> Requests\n #\n tablename = \"req_approver_req\"\n define_table(tablename,\n self.req_req_id(),\n Field(\"title\", # 'position' is a Reserved word in SQL\n label = T(\"Position\"),\n ),\n person_id(),\n #CommentsField(),\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return None\n\n# =============================================================================\nclass RequestItemModel(DataModel):\n \"\"\"\n Model for requested items\n \"\"\"\n\n names = (\"req_req_item\",\n \"req_item_id\",\n \"req_item_represent\",\n \"req_req_item_category\",\n )\n\n def model(self):\n\n T = current.T\n db = current.db\n\n settings = current.deployment_settings\n quantities_writable = settings.get_req_item_quantities_writable()\n use_commit = settings.get_req_use_commit()\n show_qty_transit = settings.get_req_show_quantity_transit()\n track_pack_values = settings.get_req_pack_values()\n\n define_table = self.define_table\n req_id = self.req_req_id\n\n # -----------------------------------------------------------------\n # Request Items\n #\n tablename = \"req_req_item\"\n define_table(tablename,\n req_id(empty = False),\n self.supply_item_entity_id(),\n self.supply_item_id(),\n self.supply_item_pack_id(),\n Field(\"quantity\", \"double\", notnull=True,\n label = T(\"Quantity\"),\n represent = lambda v: \\\n IS_FLOAT_AMOUNT.represent(v, precision=2),\n requires = IS_FLOAT_AMOUNT(minimum=1.0),\n ),\n Field(\"pack_value\", \"double\",\n label = T(\"Estimated Value per Pack\"),\n readable = track_pack_values,\n writable = track_pack_values,\n ),\n # @ToDo: Move this into a Currency Widget for the pack_value field\n CurrencyField(readable = track_pack_values,\n writable = track_pack_values,\n ),\n # Requested from:\n self.org_site_id(),\n Field(\"quantity_commit\", \"double\",\n default = 0,\n label = T(\"Quantity Committed\"),\n represent = self.req_qnty_commit_represent,\n requires = IS_FLOAT_AMOUNT(minimum=0.0),\n readable = use_commit,\n writable = use_commit and quantities_writable,\n ),\n Field(\"quantity_transit\", \"double\",\n # FB: I think this is Qty Shipped not remaining in transit\n # @ToDo: Distinguish between:\n # items lost in transit (shipped but not recvd and unlikely to ever be, so still required)\n # items still in transit (shipped but not yet recvd but still expected, so no longer need sending)\n #label = T(\"Quantity Shipped\"),\n label = T(\"Quantity in Transit\"),\n represent = self.req_qnty_transit_represent,\n default = 0,\n requires = IS_FLOAT_AMOUNT(minimum=0.0),\n readable = show_qty_transit,\n writable = show_qty_transit and quantities_writable,\n ),\n Field(\"quantity_fulfil\", \"double\",\n label = T(\"Quantity Fulfilled\"),\n represent = self.req_qnty_fulfil_represent,\n default = 0,\n requires = IS_FLOAT_AMOUNT(minimum=0.0),\n writable = quantities_writable,\n ),\n Field.Method(\"pack_quantity\",\n self.supply_item_pack_quantity(tablename=tablename)\n ),\n CommentsField(),\n on_define = lambda table: \\\n [table.site_id.set_attributes(label = T(\"Requested From\")),\n ]\n )\n\n # CRUD strings\n current.response.s3.crud_strings[tablename] = Storage(\n label_create = T(\"Add Item to Request\"),\n title_display = T(\"Request Item Details\"),\n title_list = T(\"Items in Request\"),\n title_update = T(\"Edit Item in Request\"),\n label_list_button = T(\"List Items in Request\"),\n label_delete_button = T(\"Delete Item from Request\"),\n msg_record_created = T(\"Item(s) added to Request\"),\n msg_record_modified = T(\"Item(s) updated on Request\"),\n msg_record_deleted = T(\"Item(s) deleted from Request\"),\n msg_list_empty = T(\"No Items currently requested\"))\n\n # Reusable Field\n req_item_represent = req_ReqItemRepresent()\n req_item_id = FieldTemplate(\"req_item_id\", \"reference %s\" % tablename,\n label = T(\"Request Item\"),\n ondelete = \"CASCADE\",\n represent = req_item_represent,\n requires = IS_EMPTY_OR(\n IS_ONE_OF(db,\n \"req_req_item.id\",\n req_item_represent,\n orderby = \"req_req_item.id\",\n sort = True,\n )),\n comment = DIV(_class = \"tooltip\",\n _title = \"%s|%s\" % (T(\"Request Item\"),\n T(\"Select Items from the Request\")),\n ),\n script = '''\n$.filterOptionsS3({\n 'trigger':'req_item_id',\n 'target':'item_pack_id',\n 'lookupResource':'item_pack',\n 'lookupPrefix':'supply',\n 'lookupURL':S3.Ap.concat('/req/req_item_packs.json/'),\n 'msgNoRecords':i18n.no_packs,\n 'fncPrep':S3.supply.fncPrepItem,\n 'fncRepresent':S3.supply.fncRepresentItem\n})''')\n\n if settings.get_req_prompt_match():\n # Shows the inventory items which match a requested item\n # @ToDo: Make this page a component of req_item\n create_next = URL(c=\"req\", f=\"req_item_inv_item\",\n args = [\"[id]\"],\n )\n else:\n create_next = None\n\n list_fields = [\"item_id\",\n \"item_pack_id\",\n ]\n lappend = list_fields.append\n if settings.get_req_prompt_match():\n lappend(\"site_id\")\n lappend(\"quantity\")\n if use_commit:\n lappend(\"quantity_commit\")\n if show_qty_transit:\n lappend(\"quantity_transit\")\n lappend(\"quantity_fulfil\")\n lappend(\"comments\")\n\n filter_widgets = [\n OptionsFilter(\"req_id$fulfil_status\",\n label = T(\"Status\"),\n options = req_status_opts,\n cols = 3,\n ),\n OptionsFilter(\"req_id$priority\",\n # Better to default (easier to customise/consistency)\n #label = T(\"Priority\"),\n options = req_priority_opts,\n cols = 3,\n ),\n LocationFilter(\"req_id$site_id$location_id\",\n ),\n ]\n\n self.configure(tablename,\n create_next = create_next,\n deduplicate = self.req_item_duplicate,\n deletable = settings.get_req_multiple_req_items(),\n extra_fields = [\"item_pack_id\"],\n filter_widgets = filter_widgets,\n list_fields = list_fields,\n onaccept = self.req_item_onaccept,\n ondelete = self.req_item_ondelete,\n # @ToDo: default realm to that of the req_id\n #realm_entity = self.req_item_realm_entity,\n super_entity = \"supply_item_entity\",\n )\n\n self.add_components(tablename,\n req_order_item = \"req_item_id\",\n )\n\n # ---------------------------------------------------------------------\n #\n # Req <> Item Category link table\n #\n # - used to provide a search filter\n # - populated onaccept/ondelete of req_item\n #\n tablename = \"req_req_item_category\"\n define_table(tablename,\n req_id(empty = False),\n self.supply_item_category_id(),\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return {\"req_item_id\": req_item_id,\n \"req_item_represent\": req_item_represent,\n }\n\n # -------------------------------------------------------------------------\n def defaults(self):\n \"\"\"\n Safe defaults for model-global names in case module is disabled\n \"\"\"\n\n return {\"req_item_id\": FieldTemplate.dummy(\"req_item_id\"),\n }\n\n # -------------------------------------------------------------------------\n @staticmethod\n def req_item_onaccept(form):\n \"\"\"\n On-accept actions for requested items:\n - update committed/in-transit/fulfilled status of the request\n when an item is added or quantity changed\n - add item category links for the request when adding an item\n of a new item category\n \"\"\"\n\n db = current.db\n\n form_vars = form.vars\n\n req_id = form_vars.get(\"req_id\")\n if not req_id:\n # Reload the record to get the req_id\n record_id = form_vars.get(\"id\")\n table = current.s3db.req_req_item\n record = db(table.id == record_id).select(table.req_id,\n limitby = (0, 1)\n ).first()\n if record:\n req_id = record.req_id\n\n if not req_id:\n # Item has no req_req context => nothing we can (or need to) do\n return\n\n # Update Request Status\n req_update_status(req_id)\n\n # Update req_item_category link table\n item_id = form_vars.get(\"item_id\")\n citable = db.supply_catalog_item\n cats = db(citable.item_id == item_id).select(citable.item_category_id)\n rictable = db.req_req_item_category\n for cat in cats:\n item_category_id = cat.item_category_id\n query = (rictable.deleted == False) & \\\n (rictable.req_id == req_id) & \\\n (rictable.item_category_id == item_category_id)\n exists = db(query).select(rictable.id,\n limitby = (0, 1)\n )\n if not exists:\n rictable.insert(req_id = req_id,\n item_category_id = item_category_id,\n )\n\n # -------------------------------------------------------------------------\n @staticmethod\n def req_item_ondelete(row):\n \"\"\"\n On-delete actions for requested items:\n - delete item category links from the request when the last\n item of a category is removed from the request\n\n FIXME shouldn't this also update the committed/in-transit/fulfilled\n status of the request?\n \"\"\"\n\n db = current.db\n sitable = db.supply_item\n ritable = db.req_req_item\n item = db(ritable.id == row.id).select(ritable.deleted_fk,\n limitby = (0, 1)\n ).first()\n fks = json.loads(item.deleted_fk)\n req_id = fks[\"req_id\"]\n item_id = fks[\"item_id\"]\n citable = db.supply_catalog_item\n cats = db(citable.item_id == item_id).select(citable.item_category_id)\n for cat in cats:\n item_category_id = cat.item_category_id\n # Check if we have other req_items in the same category\n query = (ritable.deleted == False) & \\\n (ritable.req_id == req_id) & \\\n (ritable.item_id == sitable.id) & \\\n (sitable.item_category_id == item_category_id)\n others = db(query).select(ritable.id,\n limitby = (0, 1)\n ).first()\n if not others:\n # Delete req_item_category link table\n rictable = db.req_req_item_category\n query = (rictable.req_id == req_id) & \\\n (rictable.item_category_id == item_category_id)\n db(query).delete()\n\n # ---------------------------------------------------------------------\n @classmethod\n def req_qnty_commit_represent(cls, quantity, show_link=True):\n\n return cls.req_quantity_represent(quantity, \"commit\", show_link)\n\n # ---------------------------------------------------------------------\n @classmethod\n def req_qnty_transit_represent(cls, quantity, show_link=True):\n\n return cls.req_quantity_represent(quantity, \"transit\", show_link)\n\n # ---------------------------------------------------------------------\n @classmethod\n def req_qnty_fulfil_represent(cls, quantity, show_link=True):\n\n return cls.req_quantity_represent(quantity, \"fulfil\", show_link)\n\n # ---------------------------------------------------------------------\n @staticmethod\n def req_quantity_represent(quantity, qtype, show_link=True):\n \"\"\"\n TODO better docstring\n TODO There should be better control of this feature - currently this only works\n with req_items which are being matched by commit / send / recv\n \"\"\"\n\n if quantity and show_link and \\\n not current.deployment_settings.get_req_item_quantities_writable():\n return TAG[\"\"](quantity,\n A(DIV(_class = \"quantity %s ajax_more collapsed\" % qtype\n ),\n _href = \"#\",\n )\n )\n else:\n return quantity\n\n # -------------------------------------------------------------------------\n @staticmethod\n def req_item_duplicate(item):\n \"\"\"\n This callback will be called when importing records. It will look\n to see if the record being imported is a duplicate. If the record\n is a duplicate then it will set the item method to update\n\n Args:\n item: An ImportItem object which includes all the details\n of the record being imported\n\n Notes:\n Rules for finding a duplicate:\n - If the Request Number matches\n - The item is the same\n \"\"\"\n\n db = current.db\n\n itable = item.table\n\n req_id = None\n item_id = None\n for ref in item.references:\n if ref.entry.tablename == \"req_req\":\n if ref.entry.id != None:\n req_id = ref.entry.id\n else:\n uuid = ref.entry.item_id\n jobitem = item.job.items[uuid]\n req_id = jobitem.id\n elif ref.entry.tablename == \"supply_item\":\n if ref.entry.id != None:\n item_id = ref.entry.id\n else:\n uuid = ref.entry.item_id\n jobitem = item.job.items[uuid]\n item_id = jobitem.id\n\n if req_id is not None and item_id is not None:\n query = (itable.req_id == req_id) & \\\n (itable.item_id == item_id)\n else:\n return\n\n duplicate = db(query).select(itable.id,\n limitby = (0, 1)\n ).first()\n if duplicate:\n item.id = duplicate.id\n item.method = item.METHOD.UPDATE\n\n# =============================================================================\nclass RequestSkillModel(DataModel):\n \"\"\"\n Modell for requested skills\n \"\"\"\n\n names = (\"req_req_skill\",\n \"req_skill_represent\",\n )\n\n def model(self):\n\n T = current.T\n\n settings = current.deployment_settings\n quantities_writable = settings.get_req_skill_quantities_writable()\n use_commit = settings.get_req_use_commit()\n show_transit = settings.get_req_show_quantity_transit()\n\n # -----------------------------------------------------------------\n # Request Skills\n #\n tablename = \"req_req_skill\"\n\n # Context-specific representation of None/[] for multi_skill_id\n multi_skill_represent = S3Represent(lookup = \"hrm_skill\",\n multiple = True,\n none = T(\"No Skills Required\"),\n )\n\n self.define_table(tablename,\n self.req_req_id(empty = False),\n # Make this a Component\n #Field(\"task\",\n # readable=False,\n # writable=False, # Populated from req_req 'Purpose'\n # label = T(\"Task Details\")),\n self.hrm_multi_skill_id(\n label = T(\"Required Skills\"),\n comment = T(\"Leave blank to request an unskilled person\"),\n represent = multi_skill_represent,\n ),\n # @ToDo: Add a minimum competency rating?\n Field(\"quantity\", \"integer\", notnull=True,\n default = 1,\n requires = IS_INT_IN_RANGE(1, None),\n label = T(\"Number of People Required\"),\n ),\n self.org_site_id(),\n Field(\"quantity_commit\", \"integer\",\n label = T(\"Quantity Committed\"),\n default = 0,\n requires = IS_INT_IN_RANGE(0, None),\n readable = use_commit,\n writable = use_commit and quantities_writable,\n ),\n Field(\"quantity_transit\", \"integer\",\n label = T(\"Quantity in Transit\"),\n #represent = lambda quantity_transit: \\\n # req_quantity_represent(quantity_transit,\n # \"transit\"),\n default = 0,\n requires = IS_INT_IN_RANGE(0, None),\n readable = show_transit,\n writable = show_transit and quantities_writable,\n ),\n Field(\"quantity_fulfil\", \"integer\",\n label = T(\"Quantity Fulfilled\"),\n default = 0,\n requires = IS_INT_IN_RANGE(0, None),\n writable = quantities_writable,\n ),\n CommentsField(#label = T(\"Task Details\"),\n #comment = DIV(_class=\"tooltip\",\n # _title=\"%s|%s\" % (T(\"Task Details\"),\n # T(\"Include any special requirements such as equipment which they need to bring.\")))\n ),\n on_define = lambda table: \\\n [table.site_id.set_attributes(label = T(\"Requested From\")),\n ]\n )\n\n # CRUD strings\n current.response.s3.crud_strings[tablename] = Storage(\n label_create = T(\"Add Skill to Request\"),\n title_display = T(\"Requested Skill Details\"),\n title_list = T(\"Requested Skills\"),\n title_update = T(\"Edit Requested Skill\"),\n label_list_button = T(\"List Requested Skills\"),\n label_delete_button = T(\"Remove Skill from Request\"),\n msg_record_created = T(\"Skill added to Request\"),\n msg_record_modified = T(\"Requested Skill updated\"),\n msg_record_deleted = T(\"Skill removed from Request\"),\n msg_list_empty = T(\"No Skills currently requested\"))\n\n list_fields = [\"id\",\n \"skill_id\",\n # @ToDo: Activate based on a deployment_setting\n #\"task\",\n \"quantity\",\n \"quantity_transit\",\n \"quantity_fulfil\",\n \"comments\",\n ]\n if use_commit:\n list_fields.insert(3, \"quantity_commit\")\n\n # Filter Widgets\n filter_widgets = [\n OptionsFilter(\"req_id$fulfil_status\",\n label = T(\"Status\"),\n options = req_status_opts,\n cols = 3,\n ),\n OptionsFilter(\"req_id$priority\",\n label = T(\"Priority\"),\n options = req_priority_opts,\n cols = 3,\n ),\n LocationFilter(\"req_id$site_id$location_id\",\n ),\n ]\n\n # Configuration\n self.configure(tablename,\n # @ToDo: Produce a custom controller like req_item_inv_item?\n #create_next = URL(c=\"req\", f=\"req_skill_skill\",\n # args=[\"[id]\"]),\n deletable = settings.get_req_multiple_req_items(),\n filter_widgets = filter_widgets,\n list_fields = list_fields,\n onaccept = self.req_skill_onaccept,\n # @ToDo: default realm to that of the req_id\n #realm_entity = self.req_skill_realm_entity,\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return {\"req_skill_represent\": self.req_skill_represent,\n }\n\n # -------------------------------------------------------------------------\n @staticmethod\n def req_skill_onaccept(form):\n \"\"\"\n On-accept actions for requested items:\n - update committed/in-transit/fulfilled status of the request\n when a skill is added or quantity changed\n - create a task from the request that people with the requested\n skill can be assigned to\n\n Request Status:\n NONE quantity=0 for all skills\n PARTIAL quantity>0 but less than requested quantity for\n at least one skill\n COMPLETE quantity>=requested quantity for all skills\n \"\"\"\n\n db = current.db\n s3db = current.s3db\n\n form_vars = form.vars\n\n req_id = form_vars.get(\"req_id\")\n if not req_id:\n # Reload the record to get the req_id\n record_id = form_vars.get(\"id\")\n table = s3db.req_req_item\n record = db(table.id == record_id).select(table.req_id,\n limitby = (0, 1)\n ).first()\n if record:\n req_id = record.req_id\n\n if not req_id:\n # Item has no req_req context => nothing we can (or need to) do\n return\n\n rtable = s3db.req_req\n query = (rtable.id == req_id)\n record = db(query).select(rtable.purpose,\n limitby = (0, 1)\n ).first()\n\n table = s3db.req_req_skill\n query = (table.req_id == req_id)\n #if record:\n # # Copy the Task description to the Skills component\n # db(query).update(task=record.purpose)\n\n is_none = {\"commit\": True,\n \"transit\": True,\n \"fulfil\": True,\n }\n\n is_complete = {\"commit\": True,\n \"transit\": True,\n \"fulfil\": True,\n }\n\n # Must check all skills in the req\n req_skills = db(query).select(table.quantity,\n table.quantity_commit,\n table.quantity_transit,\n table.quantity_fulfil,\n )\n\n for req_skill in req_skills:\n quantity = req_skill.quantity\n for status_type in [\"commit\", \"transit\", \"fulfil\"]:\n if req_skill[\"quantity_%s\" % status_type] < quantity:\n is_complete[status_type] = False\n if req_skill[\"quantity_%s\" % status_type]:\n is_none[status_type] = False\n\n status_update = {}\n for status_type in [\"commit\", \"transit\", \"fulfil\"]:\n if is_complete[status_type]:\n status_update[\"%s_status\" % status_type] = REQ_STATUS_COMPLETE\n elif is_none[status_type]:\n status_update[\"%s_status\" % status_type] = REQ_STATUS_NONE\n else:\n status_update[\"%s_status\" % status_type] = REQ_STATUS_PARTIAL\n query = (rtable.id == req_id)\n db(query).update(**status_update)\n\n if current.deployment_settings.has_module(\"project\"):\n # Add a Task to which the People can be assigned\n\n # Get the request record\n otable = s3db.org_site\n query = (rtable.id == req_id) & \\\n (otable.id == rtable.site_id)\n record = db(query).select(rtable.req_ref,\n rtable.purpose,\n rtable.priority,\n rtable.requester_id,\n rtable.site_id,\n otable.location_id,\n limitby = (0, 1)\n ).first()\n if not record:\n return\n\n name = record.req_req.req_ref or \"Req: %s\" % req_id\n table = s3db.project_task\n task = table.insert(name = name,\n description = record.req_req.purpose,\n priority = record.req_req.priority,\n location_id = record.org_site.location_id,\n site_id = record.req_req.site_id,\n )\n\n # Add the Request as a Component to the Task\n table = s3db.table(\"req_task_req\", None)\n if table:\n table.insert(task_id = task,\n req_id = req_id)\n # @ToDo: Fire onaccept which may send them a notification?\n\n # -------------------------------------------------------------------------\n @staticmethod\n def req_skill_represent(record_id):\n \"\"\"\n Represent a skill request; currently unused\n\n @ToDo: S3Represent\n \"\"\"\n\n if not record_id:\n return current.messages[\"NONE\"]\n\n db = current.db\n rstable = db.req_req_skill\n hstable = db.hrm_skill\n query = (rstable.id == record_id) & \\\n (rstable.skill_id == hstable.id)\n record = db(query).select(hstable.name,\n limitby = (0, 1)\n ).first()\n try:\n return record.name\n except AttributeError:\n return current.messages.UNKNOWN_OPT\n\n# =============================================================================\nclass RequestRecurringModel(DataModel):\n \"\"\"\n Adjuvant model to support request generation by scheduler\n \"\"\"\n\n names = (\"req_job\",\n )\n\n def model(self):\n\n T = current.T\n s3 = current.response.s3\n\n # -----------------------------------------------------------------\n # Jobs for Scheduling Recurring Requests\n #\n tablename = \"req_job\"\n self.define_table(tablename,\n self.req_req_id(empty=False),\n s3.scheduler_task_id(),\n )\n\n # CRUD Strings\n s3.crud_strings[tablename] = Storage(\n label_create = T(\"Create Job\"),\n title_display = T(\"Request Job\"),\n title_list = T(\"Request Schedule\"),\n title_update = T(\"Edit Job\"),\n label_list_button = T(\"List Jobs\"),\n msg_record_created = T(\"Job added\"),\n msg_record_modified = T(\"Job updated\"),\n msg_record_deleted = T(\"Job deleted\"),\n msg_list_empty = T(\"No jobs configured yet\"),\n msg_no_match = T(\"No jobs configured\"))\n\n # Custom Methods\n self.set_method(\"req_req\",\n component = \"job\",\n method = \"reset\",\n action = req_job_reset,\n )\n\n self.set_method(\"req_req\",\n component = \"job\",\n method = \"run\",\n action = req_job_run,\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return None\n\n# =============================================================================\nclass RequestNeedsModel(DataModel):\n \"\"\"\n Simple Requests Management System\n - Starts as Simple free text Needs\n - Extensible via Key-Value Tags\n - Extensible with Items\n - Extensible with Skills\n Use cases:\n - SHARE: local governments express needs to be met by NGOs (/Private Sector/Public in future)\n - Organisations can request Money or Time from remote volunteers\n - Sites can request Time from local volunteers or accept drop-off for Goods\n - Projects can request x (tbc: MapPH usecase)\n \"\"\"\n\n names = (\"req_need\",\n \"req_need_id\",\n )\n\n def model(self):\n\n T = current.T\n db = current.db\n\n # ---------------------------------------------------------------------\n # Needs\n #\n tablename = \"req_need\"\n self.define_table(tablename,\n self.super_link(\"doc_id\", \"doc_entity\"),\n self.gis_location_id(), # Can be hidden, e.g. if using Sites (can then sync this onaccept)\n DateTimeField(default = \"now\",\n widget = \"date\",\n ),\n DateTimeField(\"end_date\",\n label = T(\"End Date\"),\n # Enable in Templates if-required\n readable = False,\n writable = False,\n ),\n req_priority()(),\n Field(\"name\", notnull = True,\n length = 64,\n label = T(\"Summary of Needs\"),\n requires = [IS_NOT_EMPTY(),\n IS_LENGTH(64),\n ],\n ),\n CommentsField(\"description\",\n label = T(\"Description\"),\n comment = None,\n ),\n req_status()(\"status\",\n label = T(\"Fulfilment Status\"),\n ),\n CommentsField(),\n )\n\n # CRUD strings\n current.response.s3.crud_strings[tablename] = Storage(\n label_create = T(\"Add Needs\"),\n title_list = T(\"Needs\"),\n title_display = T(\"Needs\"),\n title_update = T(\"Edit Needs\"),\n title_upload = T(\"Import Needs\"),\n label_list_button = T(\"List Needs\"),\n label_delete_button = T(\"Delete Needs\"),\n msg_record_created = T(\"Needs added\"),\n msg_record_modified = T(\"Needs updated\"),\n msg_record_deleted = T(\"Needs deleted\"),\n msg_list_empty = T(\"No Needs currently registered\"),\n )\n\n self.configure(tablename,\n super_entity = \"doc_entity\",\n )\n\n # Components\n self.add_components(tablename,\n event_event = {\"link\": \"event_event_need\",\n \"joinby\": \"need_id\",\n \"key\": \"event_id\",\n \"multiple\": False,\n },\n org_organisation = {\"link\": \"req_need_organisation\",\n \"joinby\": \"need_id\",\n \"key\": \"organisation_id\",\n \"multiple\": False,\n },\n req_need_organisation = {\"joinby\": \"need_id\",\n \"multiple\": False,\n },\n org_sector = {\"link\": \"req_need_sector\",\n \"joinby\": \"need_id\",\n \"key\": \"sector_id\",\n \"multiple\": False,\n },\n org_site = {\"link\": \"req_need_site\",\n \"joinby\": \"need_id\",\n \"key\": \"site_id\",\n \"multiple\": False,\n },\n project_activity = {\"link\": \"req_need_activity\",\n \"joinby\": \"need_id\",\n \"key\": \"activity_id\",\n },\n req_need_contact = {\"joinby\": \"need_id\",\n # Can redefine as multiple=True in template if-required\n \"multiple\": False,\n },\n req_need_demographic = \"need_id\",\n req_need_item = \"need_id\",\n req_need_person = \"need_id\",\n req_need_skill = \"need_id\",\n req_need_tag = {\"name\": \"tag\",\n \"joinby\": \"need_id\",\n },\n )\n\n # Custom Methods\n self.set_method(\"req_need\",\n method = \"assign\",\n action = self.pr_AssignMethod(component=\"need_person\"))\n\n # NB Only instance of this being used (SHARE) over-rides this to show the req_number\n represent = S3Represent(lookup = tablename,\n show_link = True,\n )\n need_id = FieldTemplate(\"need_id\", \"reference %s\" % tablename,\n label = T(\"Need\"),\n ondelete = \"CASCADE\",\n represent = represent,\n requires = IS_EMPTY_OR(\n IS_ONE_OF(db, \"req_need.id\",\n represent,\n orderby = \"req_need.date\",\n sort = True,\n )),\n sortby = \"date\",\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return {\"req_need_id\": need_id,\n }\n\n # -------------------------------------------------------------------------\n def defaults(self):\n \"\"\"\n Safe defaults for model-global names in case module is disabled\n \"\"\"\n\n return {\"req_need_id\": FieldTemplate.dummy(\"need_id\"),\n }\n\n# =============================================================================\nclass RequestNeedsActivityModel(DataModel):\n \"\"\"\n Simple Requests Management System\n - optional link to Activities (Activity created to respond to Need)\n \"\"\"\n\n names = (\"req_need_activity\",\n )\n\n def model(self):\n\n # ---------------------------------------------------------------------\n # Needs <=> Activities\n #\n\n tablename = \"req_need_activity\"\n self.define_table(tablename,\n self.req_need_id(empty = False),\n self.project_activity_id(empty = False),\n CommentsField(),\n )\n\n self.configure(tablename,\n deduplicate = S3Duplicate(primary=(\"need_id\",\n \"activity_id\",\n ),\n ),\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return None\n\n# =============================================================================\nclass RequestNeedsContactModel(DataModel):\n \"\"\"\n Simple Requests Management System\n - optional link to Contacts (People)\n \"\"\"\n\n names = (\"req_need_contact\",\n )\n\n def model(self):\n\n T = current.T\n\n # ---------------------------------------------------------------------\n # Needs <=> Persons\n #\n\n tablename = \"req_need_contact\"\n self.define_table(tablename,\n self.req_need_id(empty = False),\n self.pr_person_id(empty = False,\n label = T(\"Contact\"),\n ),\n CommentsField(),\n )\n\n self.configure(tablename,\n deduplicate = S3Duplicate(primary=(\"need_id\",\n \"person_id\",\n ),\n ),\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return None\n\n# =============================================================================\nclass RequestNeedsDemographicsModel(DataModel):\n \"\"\"\n Simple Requests Management System\n - optional link to Demographics\n\n @ToDo: Auto-populate defaults for Items based on Demographics\n \"\"\"\n\n names = (\"req_need_demographic\",\n )\n\n def model(self):\n\n T = current.T\n\n # ---------------------------------------------------------------------\n # Needs <=> Demographics\n #\n if current.s3db.table(\"stats_demographic\"):\n title = current.response.s3.crud_strings[\"stats_demographic\"].label_create\n parameter_id_comment = S3PopupLink(c = \"stats\",\n f = \"demographic\",\n vars = {\"child\": \"parameter_id\"},\n title = title,\n )\n else:\n parameter_id_comment = None\n\n tablename = \"req_need_demographic\"\n self.define_table(tablename,\n self.req_need_id(empty = False),\n self.super_link(\"parameter_id\", \"stats_parameter\",\n instance_types = (\"stats_demographic\",),\n label = T(\"Demographic\"),\n represent = self.stats_parameter_represent,\n readable = True,\n writable = True,\n empty = False,\n comment = parameter_id_comment,\n ),\n req_timeframe(),\n Field(\"value\", \"double\",\n label = T(\"Number\"),\n #label = T(\"Number in Need\"),\n represent = lambda v: \\\n IS_FLOAT_AMOUNT.represent(v, precision=2),\n requires = IS_NOT_EMPTY(),\n ),\n Field(\"value_committed\", \"double\",\n label = T(\"Number Committed\"),\n represent = lambda v: \\\n IS_FLOAT_AMOUNT.represent(v, precision=2),\n requires = IS_EMPTY_OR(\n IS_FLOAT_AMOUNT(minimum=1.0)),\n # Enable in templates as-required\n readable = False,\n # Normally set automatically\n writable = False,\n ),\n Field(\"value_uncommitted\", \"double\",\n label = T(\"Number Uncommitted\"),\n represent = lambda v: \\\n IS_FLOAT_AMOUNT.represent(v, precision=2),\n requires = IS_EMPTY_OR(\n IS_FLOAT_AMOUNT(minimum=1.0)),\n # Enable in templates as-required\n readable = False,\n # Normally set automatically\n writable = False,\n ),\n Field(\"value_reached\", \"double\",\n label = T(\"Number Reached\"),\n represent = lambda v: \\\n IS_FLOAT_AMOUNT.represent(v, precision=2),\n requires = IS_EMPTY_OR(\n IS_FLOAT_AMOUNT(minimum=1.0)),\n # Enable in templates as-required\n readable = False,\n # Normally set automatically\n writable = False,\n ),\n CommentsField(),\n )\n\n self.configure(tablename,\n deduplicate = S3Duplicate(primary=(\"need_id\",\n \"parameter_id\",\n ),\n ),\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return None\n\n# =============================================================================\nclass RequestNeedsItemsModel(DataModel):\n \"\"\"\n Simple Requests Management System\n - optional extension to support Items, but still not using Inventory-linked Requests\n \"\"\"\n\n names = (\"req_need_item\",\n )\n\n def model(self):\n\n T = current.T\n\n # ---------------------------------------------------------------------\n # Needs <=> Supply Items\n #\n\n tablename = \"req_need_item\"\n self.define_table(tablename,\n self.req_need_id(empty = False),\n self.supply_item_category_id(),\n self.supply_item_id(empty = False,\n # Default:\n #ondelete = \"RESTRICT\",\n # Filter Item dropdown based on Category\n script = '''\n$.filterOptionsS3({\n 'trigger':'item_category_id',\n 'target':'item_id',\n 'lookupPrefix':'supply',\n 'lookupResource':'item',\n})''',\n # Don't use Auto-complete\n widget = None,\n ),\n self.supply_item_pack_id(),\n req_timeframe(),\n Field(\"quantity\", \"double\",\n label = T(\"Quantity\"),\n #label = T(\"Quantity Requested\"),\n represent = lambda v: \\\n IS_FLOAT_AMOUNT.represent(v, precision=2),\n requires = IS_EMPTY_OR(\n IS_FLOAT_AMOUNT(minimum=1.0)),\n ),\n Field(\"quantity_committed\", \"double\",\n label = T(\"Quantity Committed\"),\n represent = lambda v: \\\n IS_FLOAT_AMOUNT.represent(v, precision=2),\n requires = IS_EMPTY_OR(\n IS_FLOAT_AMOUNT(minimum=1.0)),\n # Enable in templates as-required\n readable = False,\n # Normally set automatically\n writable = False,\n ),\n Field(\"quantity_uncommitted\", \"double\",\n label = T(\"Quantity Uncommitted\"),\n represent = lambda v: \\\n IS_FLOAT_AMOUNT.represent(v, precision=2),\n requires = IS_EMPTY_OR(\n IS_FLOAT_AMOUNT(minimum=1.0)),\n # Enable in templates as-required\n readable = False,\n # Normally set automatically\n writable = False,\n ),\n Field(\"quantity_delivered\", \"double\",\n label = T(\"Quantity Delivered\"),\n represent = lambda v: \\\n IS_FLOAT_AMOUNT.represent(v, precision=2),\n requires = IS_EMPTY_OR(\n IS_FLOAT_AMOUNT(minimum=1.0)),\n # Enable in templates as-required\n readable = False,\n # Normally set automatically\n writable = False,\n ),\n req_priority()(),\n CommentsField(),\n req_status()(\"status\",\n label = T(\"Fulfilment Status\"),\n ),\n )\n\n self.configure(tablename,\n deduplicate = S3Duplicate(primary=(\"need_id\",\n \"item_id\",\n ),\n ),\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return None\n\n# =============================================================================\nclass RequestNeedsSkillsModel(DataModel):\n \"\"\"\n Simple Requests Management System\n - optional extension to support Skills, but still not using normal Requests\n \"\"\"\n\n names = (\"req_need_skill\",\n )\n\n def model(self):\n\n T = current.T\n crud_strings = current.response.s3.crud_strings\n\n # ---------------------------------------------------------------------\n # Needs <=> Skills\n #\n skill_id = self.hrm_skill_id # Load normal model\n CREATE_SKILL = crud_strings[\"hrm_skill\"].label_create\n\n tablename = \"req_need_skill\"\n self.define_table(tablename,\n self.req_need_id(empty = False),\n skill_id(comment = S3PopupLink(c = \"hrm\",\n f = \"skill\",\n label = CREATE_SKILL,\n tooltip = None,\n vars = {\"prefix\": \"req\"},\n ),\n empty = False,\n ),\n Field(\"quantity\", \"double\",\n label = T(\"Quantity\"),\n represent = lambda v: \\\n IS_FLOAT_AMOUNT.represent(v, precision=2),\n requires = IS_EMPTY_OR(\n IS_FLOAT_AMOUNT(minimum=1.0)),\n ),\n req_priority()(),\n CommentsField(),\n req_status()(\"status\",\n label = T(\"Fulfilment Status\"),\n ),\n )\n\n self.configure(tablename,\n deduplicate = S3Duplicate(primary=(\"need_id\",\n \"skill_id\",\n ),\n ),\n )\n\n # CRUD strings\n crud_strings[tablename] = Storage(\n label_create = T(\"Add Skill\"),\n title_list = T(\"Skills\"),\n title_display = T(\"Skill\"),\n title_update = T(\"Edit Skill\"),\n #title_upload = T(\"Import Skills\"),\n label_list_button = T(\"List Skills\"),\n label_delete_button = T(\"Delete Skill\"),\n msg_record_created = T(\"Skill added\"),\n msg_record_modified = T(\"Skill updated\"),\n msg_record_deleted = T(\"Skill deleted\"),\n msg_list_empty = T(\"No Skills currently registered for this Request\"),\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return None\n\n# =============================================================================\nclass RequestNeedsOrganisationModel(DataModel):\n \"\"\"\n Simple Requests Management System\n - optional link to Organisations\n - link exposed in Templates as-required\n \"\"\"\n\n names = (\"req_need_organisation\",\n )\n\n def model(self):\n\n # ---------------------------------------------------------------------\n # Needs <=> Organisations\n #\n organisation_id = self.org_organisation_id # Load normal model\n CREATE = current.response.s3.crud_strings[\"org_organisation\"].label_create\n\n tablename = \"req_need_organisation\"\n self.define_table(tablename,\n self.req_need_id(empty = False),\n organisation_id(comment = S3PopupLink(c = \"org\",\n f = \"organisation\",\n label = CREATE,\n tooltip = None,\n vars = {\"prefix\": \"req\"},\n ),\n empty = False,\n ),\n CommentsField(),\n )\n\n self.configure(tablename,\n deduplicate = S3Duplicate(primary=(\"need_id\",\n \"organisation_id\",\n ),\n ),\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return None\n\n# =============================================================================\nclass RequestNeedsPersonModel(DataModel):\n \"\"\"\n Simple Requests Management System\n - optional link to People (used for assignments to Skills)\n - currently assumes that Need just has a single Skill, so no need to say which skill the person is for\n - used by CCC\n \"\"\"\n\n names = (\"req_need_person\",\n )\n\n def model(self):\n\n T = current.T\n\n # ---------------------------------------------------------------------\n # Needs <=> Persons\n #\n # @ToDo: configuration setting once-required\n status_opts = {1: T(\"Applied\"),\n 2: T(\"Approved\"),\n 3: T(\"Rejected\"),\n 4: T(\"Invited\"),\n 5: T(\"Accepted\"),\n 6: T(\"Declined\"),\n }\n\n tablename = \"req_need_person\"\n self.define_table(tablename,\n self.req_need_id(empty = False),\n self.pr_person_id(empty = False),\n Field(\"status\", \"integer\",\n default = 4, # Invited\n label = T(\"Status\"),\n represent = represent_option(status_opts),\n requires = IS_EMPTY_OR(\n IS_IN_SET(status_opts)),\n ),\n CommentsField(),\n )\n\n self.configure(tablename,\n deduplicate = S3Duplicate(primary=(\"need_id\",\n \"person_id\",\n ),\n ),\n )\n\n current.response.s3.crud_strings[tablename] = Storage(\n label_create = T(\"Add Person\"),\n title_display = T(\"Person Details\"),\n title_list = T(\"People\"),\n title_update = T(\"Edit Person\"),\n #title_upload = T(\"Import People\"),\n label_list_button = T(\"List People\"),\n label_delete_button = T(\"Remove Person\"),\n msg_record_created = T(\"Person added\"),\n msg_record_modified = T(\"Person updated\"),\n msg_record_deleted = T(\"Person removed\"),\n msg_list_empty = T(\"No People currently linked to this Need\")\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return None\n\n# =============================================================================\nclass RequestNeedsSectorModel(DataModel):\n \"\"\"\n Simple Requests Management System\n - optional link to Sectors\n - link exposed in Templates as-required\n \"\"\"\n\n names = (\"req_need_sector\",\n )\n\n def model(self):\n\n # ---------------------------------------------------------------------\n # Needs <=> Sectors\n #\n tablename = \"req_need_sector\"\n self.define_table(tablename,\n self.req_need_id(empty = False),\n self.org_sector_id(empty = False),\n CommentsField(),\n )\n\n self.configure(tablename,\n deduplicate = S3Duplicate(primary=(\"need_id\",\n \"sector_id\",\n ),\n ),\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return None\n\n# =============================================================================\nclass RequestNeedsSiteModel(DataModel):\n \"\"\"\n Simple Requests Management System\n - optional link to Sites\n - link exposed in Templates as-required\n \"\"\"\n\n names = (\"req_need_site\",\n )\n\n def model(self):\n\n # ---------------------------------------------------------------------\n # Needs <=> Sites\n #\n SITE = current.deployment_settings.get_org_site_label()\n\n tablename = \"req_need_site\"\n self.define_table(tablename,\n self.req_need_id(empty = False),\n # Component not instance\n self.super_link(\"site_id\", \"org_site\",\n label = SITE,\n readable = True,\n writable = True,\n represent = self.org_site_represent,\n ),\n CommentsField(),\n )\n\n self.configure(tablename,\n deduplicate = S3Duplicate(primary=(\"need_id\",\n \"site_id\",\n ),\n ),\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return None\n\n# =============================================================================\nclass RequestNeedsTagModel(DataModel):\n \"\"\"\n Needs Tags\n \"\"\"\n\n names = (\"req_need_tag\",\n )\n\n def model(self):\n\n T = current.T\n\n # ---------------------------------------------------------------------\n # Need Tags\n # - Key-Value extensions\n # - can be used to add structured extensions, such as:\n # * Reference\n # * Cash Donations accepted (/ Details)\n # * Goods drop-off point (/ Details)\n # * Transport required (/ Details)\n # * Security needed (/ Details)\n # * Volunteering Opportunities (/ Details)\n # - can be used to provide conversions to external systems, such as:\n # * HXL\n # - can be a Triple Store for Semantic Web support\n #\n tablename = \"req_need_tag\"\n self.define_table(tablename,\n self.req_need_id(),\n # key is a reserved word in MySQL\n Field(\"tag\",\n label = T(\"Key\"),\n ),\n Field(\"value\",\n label = T(\"Value\"),\n ),\n CommentsField(),\n )\n\n self.configure(tablename,\n deduplicate = S3Duplicate(primary = (\"need_id\",\n \"tag\",\n ),\n ),\n )\n\n # Pass names back to global scope (s3.*)\n return None\n\n# =============================================================================\nclass RequestTagModel(DataModel):\n \"\"\"\n Request Tags\n \"\"\"\n\n names = (\"req_req_tag\",\n )\n\n def model(self):\n\n T = current.T\n\n # ---------------------------------------------------------------------\n # Request Tags\n # - Key-Value extensions\n # - can be used to provide conversions to external systems, such as:\n # * HXL\n # - can be a Triple Store for Semantic Web support\n #\n tablename = \"req_req_tag\"\n self.define_table(tablename,\n self.req_req_id(),\n # key is a reserved word in MySQL\n Field(\"tag\",\n label = T(\"Key\"),\n ),\n Field(\"value\",\n label = T(\"Value\"),\n ),\n CommentsField(),\n )\n\n self.configure(tablename,\n deduplicate = S3Duplicate(primary = (\"req_id\",\n \"tag\",\n ),\n ),\n )\n\n # Pass names back to global scope (s3.*)\n return None\n\n# =============================================================================\nclass RequestOrderItemModel(DataModel):\n \"\"\"\n Simple Item Ordering for Requests\n - for when Procurement model isn't being used\n \"\"\"\n\n names = (\"req_order_item\",\n )\n\n def model(self):\n\n T = current.T\n NONE = current.messages[\"NONE\"]\n\n # -----------------------------------------------------------------\n # Request Item Ordering\n #\n tablename = \"req_order_item\"\n self.define_table(tablename,\n self.req_item_id(empty = False,\n readable = False, # Hidden\n writable = False,\n ),\n self.req_req_id(empty = False,\n writable = False, # Auto-populated\n ),\n self.supply_item_id(empty = False,\n writable = False, # Auto-populated\n ),\n self.supply_item_pack_id(writable = False, # Auto-populated\n ),\n Field(\"quantity\", \"double\", notnull=True,\n default = 0.0,\n label = T(\"Quantity\"),\n represent = lambda v: \\\n IS_FLOAT_AMOUNT.represent(v, precision=2),\n #requires = IS_FLOAT_AMOUNT(minimum=0.0),\n writable = False, # Auto-populated\n ),\n Field(\"purchase_ref\",\n label = T(\"%(PO)s Number\") % \\\n {\"PO\": current.deployment_settings.get_proc_shortname()},\n represent = lambda v: v if v else NONE,\n ),\n self.inv_recv_id(label = T(\"Received Shipment\"),\n ),\n )\n\n self.configure(tablename,\n insertable = False,\n )\n\n # CRUD strings\n current.response.s3.crud_strings[tablename] = Storage(\n #label_create = T(\"Create Purchase Item\"),\n title_display = T(\"Purchase Item Details\"),\n title_list = T(\"Purchase Items\"),\n title_update = T(\"Edit Purchase Item\"),\n label_list_button = T(\"List Purchase Items\"),\n label_delete_button = T(\"Delete Purchase Item\"),\n #msg_record_created = T(\"Purchase Item Added\"),\n msg_record_modified = T(\"Purchase Item Updated\"),\n msg_record_deleted = T(\"Purchase Item Deleted\"),\n msg_list_empty = T(\"No Purchase Items\"))\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return None\n\n# =============================================================================\nclass RequestProjectModel(DataModel):\n \"\"\"\n Link Requests to Projects\n \"\"\"\n\n names = (\"req_project_req\",\n )\n\n def model(self):\n\n # -----------------------------------------------------------------\n # Link Skill Requests to Tasks\n #\n tablename = \"req_project_req\"\n self.define_table(tablename,\n self.project_project_id(empty = False),\n self.req_req_id(empty = False),\n )\n\n self.configure(tablename,\n deduplicate = S3Duplicate(primary = (\"project_id\",\n \"req_id\",\n ),\n ),\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return None\n\n# =============================================================================\nclass RequestTaskModel(DataModel):\n \"\"\"\n Link Requests for Skills to Tasks\n \"\"\"\n\n names = (\"req_task_req\",\n )\n\n def model(self):\n\n # -----------------------------------------------------------------\n # Link Skill Requests to Tasks\n #\n tablename = \"req_task_req\"\n self.define_table(tablename,\n self.project_task_id(),\n self.req_req_id(empty=False),\n #self.req_req_person_id(),\n #self.req_req_skill_id(),\n )\n\n self.configure(tablename,\n deduplicate = S3Duplicate(primary = (\"task_id\",\n \"req_id\",\n ),\n ),\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return None\n\n# =============================================================================\nclass RequestRequesterCategoryModel(DataModel):\n \"\"\"\n Model to control which types of requester can request which items\n - used by RLPPTM\n \"\"\"\n\n names = (\"req_requester_category\",\n )\n\n def model(self):\n\n # -----------------------------------------------------------------\n # Link supply item categories to requester attributes (e.g. org type)\n #\n tablename = \"req_requester_category\"\n self.define_table(tablename,\n self.supply_item_category_id(\n empty = False,\n ondelete = \"CASCADE\",\n ),\n self.org_organisation_type_id(\n empty = False,\n ondelete = \"CASCADE\",\n ),\n )\n\n self.configure(tablename,\n deduplicate = S3Duplicate(primary = (\"item_category_id\",\n \"organisation_type_id\",\n ),\n ),\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return None\n\n# =============================================================================\nclass CommitModel(DataModel):\n \"\"\"\n Model for commits (pledges)\n \"\"\"\n\n names = (\"req_commit\",\n \"req_commit_id\",\n )\n\n def model(self):\n\n T = current.T\n db = current.db\n auth = current.auth\n\n add_components = self.add_components\n\n settings = current.deployment_settings\n\n req_types = settings.get_req_req_type()\n commit_value = settings.get_req_commit_value()\n unsolicited_commit = settings.get_req_commit_without_request()\n\n # Site/Committer defaults\n committer_is_author = settings.get_req_committer_is_author()\n if committer_is_author:\n site_default = auth.user.site_id if auth.is_logged_in() else None\n committer_default = auth.s3_logged_in_person()\n else:\n site_default = None\n committer_default = None\n\n # Dropdown or Autocomplete for Committing Site?\n if settings.get_org_site_autocomplete():\n site_widget = S3SiteAutocompleteWidget()\n site_comment = DIV(_class=\"tooltip\",\n _title=\"%s|%s\" % (T(\"From Facility\"),\n current.messages.AUTOCOMPLETE_HELP,\n ),\n )\n else:\n site_widget = None\n site_comment = None\n\n # ---------------------------------------------------------------------\n # Commitments (Pledges)\n #\n tablename = \"req_commit\"\n self.define_table(tablename,\n self.super_link(\"site_id\", \"org_site\",\n comment = site_comment,\n default = site_default,\n label = T(\"From Facility\"),\n # Non-Item Requests make False in the prep\n readable = True,\n writable = True,\n represent = self.org_site_represent,\n updateable = True,\n widget = site_widget,\n ),\n # Used for reporting on where Donations originated\n self.gis_location_id(readable = False,\n writable = False\n ),\n # Non-Item Requests make True in the prep\n self.org_organisation_id(readable = False,\n writable = False\n ),\n self.req_req_id(empty = not unsolicited_commit,\n ),\n Field(\"type\", \"integer\",\n label = T(\"Type\"),\n # These are copied automatically from the Req\n readable = False,\n writable = False,\n ),\n DateTimeField(default = \"now\",\n represent = \"date\",\n ),\n DateTimeField(\"date_available\",\n label = T(\"Date Available\"),\n represent = \"date\",\n ),\n self.pr_person_id(\"committer_id\",\n default = committer_default,\n label = T(\"Committed By\"),\n comment = self.pr_person_comment(child=\"committer_id\"),\n ),\n # @ToDo: Calculate this from line items in Item Commits\n Field(\"value\", \"double\",\n label = T(\"Estimated Value\"),\n readable = commit_value,\n writable = commit_value,\n ),\n # @ToDo: Move this into a Currency Widget for the value field\n CurrencyField(readable = commit_value,\n writable = commit_value,\n ),\n Field(\"cancel\", \"boolean\",\n default = False,\n label = T(\"Cancel\"),\n readable = False,\n writable = False,\n ),\n CommentsField(),\n )\n\n filter_widgets = [\n TextFilter([\"committer_id$first_name\",\n \"committer_id$middle_name\",\n \"committer_id$last_name\",\n \"site_id$name\",\n \"comments\",\n \"req_id$name\",\n \"organisation_id$name\"\n ],\n label = T(\"Search\"),\n comment = T(\"Search for a commitment by Committer name, Request ID, Site or Organization.\"),\n ),\n LocationFilter(\"location_id\",\n hidden = True,\n ),\n DateFilter(\"date\",\n # Better to default (easier to customise/consistency)\n #label = T(\"Date\"),\n hide_time = True,\n comment = T(\"Search for commitments made between these dates.\"),\n hidden = True,\n ),\n DateFilter(\"date_available\",\n # Better to default (easier to customise/consistency)\n #label = T(\"Date Available\"),\n hide_time = True,\n comment = T(\"Search for commitments available between these dates.\"),\n hidden = True,\n ),\n ]\n\n if len(req_types) > 1:\n filter_widgets.insert(1, OptionsFilter(\"type\",\n # Better to default (easier to customise/consistency)\n #label = T(\"Type\"),\n cols = len(req_types),\n hidden = True,\n ))\n\n # CRUD strings\n current.response.s3.crud_strings[tablename] = Storage(\n label_create = T(\"Make Commitment\"),\n title_display = T(\"Commitment Details\"),\n title_list = T(\"Commitments\"),\n title_update = T(\"Edit Commitment\"),\n label_list_button = T(\"List Commitments\"),\n label_delete_button = T(\"Delete Commitment\"),\n msg_record_created = T(\"Commitment Added\"),\n msg_record_modified = T(\"Commitment Updated\"),\n msg_record_deleted = T(\"Commitment Canceled\"),\n msg_list_empty = T(\"No Commitments\"))\n\n # Reusable Field\n commit_represent = req_CommitRepresent()\n commit_id = FieldTemplate(\"commit_id\", \"reference %s\" % tablename,\n label = T(\"Commitment\"),\n ondelete = \"CASCADE\",\n represent = commit_represent,\n requires = IS_EMPTY_OR(\n IS_ONE_OF(db, \"req_commit.id\",\n commit_represent,\n orderby = \"req_commit.date\",\n sort = True,\n )),\n sortby = \"date\",\n )\n\n list_fields = [\"site_id\",\n \"req_id\",\n \"committer_id\",\n ]\n\n # @ToDo: Allow a single column to support different components based on type\n # @ToDo: Include Qty too (Computed VF in component?)\n if \"Stock\" in req_types:\n list_fields.append((T(\"Committed Items\"), \"commit_item.req_item_id$item_id\"))\n if \"People\" in req_types:\n if settings.get_req_commit_people():\n list_fields.append((T(\"Committed People\"), \"commit_person.human_resource_id\"))\n else:\n list_fields.append((T(\"Committed Skills\"), \"commit_skill.skill_id\"))\n\n list_fields += [\"date\",\n \"date_available\",\n \"comments\",\n ]\n\n self.configure(tablename,\n context = {\"location\": \"location_id\",\n \"organisation\": \"organisation_id\",\n \"request\": \"req_id\",\n # We want 'For Sites XX' not 'From Site XX'\n #\"site\": \"site_id\",\n \"site\": \"req_id$site_id\",\n },\n filter_widgets = filter_widgets,\n list_fields = list_fields,\n # Commitments should only be made to a specific request\n listadd = unsolicited_commit,\n onaccept = self.commit_onaccept,\n ondelete = self.commit_ondelete,\n )\n\n # Components\n add_components(tablename,\n # Committed Items\n req_commit_item = \"commit_id\",\n # Committed Persons\n req_commit_person = \"commit_id\",\n # Committed Skills\n req_commit_skill = \"commit_id\",\n )\n\n # Custom Method to Assign HRs\n self.set_method(\"req_commit\",\n method = \"assign\",\n action = self.hrm_AssignMethod(component=\"commit_person\",\n next_tab=\"commit_person\",\n ))\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return {\"req_commit_id\": commit_id,\n }\n\n # -------------------------------------------------------------------------\n @staticmethod\n def commit_onaccept(form):\n \"\"\"\n On-accept actions for commits:\n - set location_id and request type\n - update status of request & components\n \"\"\"\n\n db = current.db\n s3db = current.s3db\n\n form_vars = form.vars\n try:\n commit_id = form_vars.id\n except AttributeError:\n return\n if not commit_id:\n return\n\n ctable = s3db.req_commit\n cdata = {}\n\n site_id = form_vars.get(\"site_id\")\n if site_id:\n # Set location_id to location of site\n stable = s3db.org_site\n site = db(stable.site_id == site_id).select(stable.location_id,\n limitby = (0, 1)\n ).first()\n if site and site.location_id:\n cdata[\"location_id\"] = site.location_id\n\n # Find the request\n rtable = s3db.req_req\n query = (ctable.id == commit_id) & \\\n (rtable.id == ctable.req_id)\n req = db(query).select(rtable.id,\n rtable.type,\n rtable.req_status,\n rtable.commit_status,\n limitby = (0, 1)\n ).first()\n if not req:\n return\n\n # Update the commit\n cdata[\"type\"] = req.type\n if cdata:\n db(ctable.id == commit_id).update(**cdata)\n\n # Update committed quantities and request status\n req_update_commit_quantities_and_status(req)\n\n # -------------------------------------------------------------------------\n @staticmethod\n def commit_ondelete(row):\n \"\"\"\n Update Status of Request & components\n \"\"\"\n\n db = current.db\n s3db = current.s3db\n commit_id = row.id\n\n # Find the request\n ctable = s3db.req_commit\n fks = db(ctable.id == commit_id).select(ctable.deleted_fk,\n limitby = (0, 1)\n ).first().deleted_fk\n req_id = json.loads(fks)[\"req_id\"]\n rtable = s3db.req_req\n req = db(rtable.id == req_id).select(rtable.id,\n rtable.type,\n rtable.commit_status,\n limitby = (0, 1)\n ).first()\n if not req:\n return\n\n # Update committed quantities and request status\n req_update_commit_quantities_and_status(req)\n\n# =============================================================================\nclass CommitItemModel(DataModel):\n \"\"\"\n Model for committed (pledged) items\n \"\"\"\n\n names = (\"req_commit_item\",\n )\n\n def model(self):\n\n T = current.T\n\n # -----------------------------------------------------------------\n # Commitment Items\n # @ToDo: Update the req_item_id in the commit_item if the req_id of the commit is changed\n #\n tablename = \"req_commit_item\"\n self.define_table(tablename,\n self.req_commit_id(),\n #item_id,\n #supply_item_id(),\n self.req_item_id(),\n self.supply_item_pack_id(),\n Field(\"quantity\", \"double\", notnull=True,\n label = T(\"Quantity\"),\n ),\n Field.Method(\"pack_quantity\",\n self.supply_item_pack_quantity(tablename=tablename)),\n CommentsField(),\n )\n\n # CRUD strings\n current.response.s3.crud_strings[tablename] = Storage(\n label_create = T(\"Add Item to Commitment\"),\n title_display = T(\"Commitment Item Details\"),\n title_list = T(\"Commitment Items\"),\n title_update = T(\"Edit Commitment Item\"),\n label_list_button = T(\"List Commitment Items\"),\n label_delete_button = T(\"Delete Commitment Item\"),\n msg_record_created = T(\"Commitment Item added\"),\n msg_record_modified = T(\"Commitment Item updated\"),\n msg_record_deleted = T(\"Commitment Item deleted\"),\n msg_list_empty = T(\"No Commitment Items currently registered\"))\n\n self.configure(tablename,\n extra_fields = [\"item_pack_id\"],\n onaccept = self.commit_item_onaccept,\n ondelete = self.commit_item_ondelete,\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return {# Used by commit_req() controller (TODO make module-global then?)\n \"req_commit_item_onaccept\": self.commit_item_onaccept,\n }\n\n # -------------------------------------------------------------------------\n @staticmethod\n def commit_item_onaccept(form):\n \"\"\"\n On-accept actions for committed items\n - update the commit quantities and -status of the request\n \"\"\"\n\n db = current.db\n\n try:\n item_id = form.vars.id\n except AttributeError:\n return\n\n # Get the req\n rtable = db.req_req\n ctable = db.req_commit\n itable = db.req_commit_item\n query = (itable.id == item_id) & \\\n (ctable.id == itable.commit_id) & \\\n (rtable.id == ctable.req_id)\n req = db(query).select(rtable.id,\n rtable.type,\n rtable.req_status,\n rtable.commit_status,\n limitby = (0, 1)\n ).first()\n if not req:\n return\n\n req_update_commit_quantities_and_status(req)\n\n # -------------------------------------------------------------------------\n @staticmethod\n def commit_item_ondelete(row):\n \"\"\"\n On-delete actions for committed items\n - update the commit quantities and -status of the request\n \"\"\"\n\n db = current.db\n s3db = current.s3db\n\n # Get the commit_id\n table = s3db.req_commit_item\n row = db(table.id == row.id).select(table.deleted_fk,\n limitby = (0, 1)\n ).first()\n try:\n deleted_fk = json.loads(row.deleted_fk)\n except:\n return\n\n commit_id = deleted_fk.get(\"commit_id\")\n if commit_id:\n ctable = s3db.req_commit\n rtable = s3db.req_req\n query = (ctable.id == commit_id) & \\\n (rtable.id == ctable.req_id)\n req = db(query).select(rtable.id,\n rtable.type,\n rtable.req_status,\n rtable.commit_status,\n limitby = (0, 1)\n ).first()\n if req:\n req_update_commit_quantities_and_status(req)\n\n# =============================================================================\nclass CommitPersonModel(DataModel):\n \"\"\"\n Commit a named individual to a Request\n\n Used when settings.req.commit_people = True\n \"\"\"\n\n names = (\"req_commit_person\",)\n\n def model(self):\n\n T = current.T\n\n # -----------------------------------------------------------------\n # Committed Persons\n #\n tablename = \"req_commit_person\"\n self.define_table(tablename,\n self.req_commit_id(),\n # For reference\n #self.hrm_multi_skill_id(comment = None,\n # writable = False,\n # ),\n # This should be person not hrm as we want to mark\n # them as allocated across all their Org-affiliations\n #self.pr_person_id(),\n # Using HR to use hrm_Assign method (can mark person as allocated onaccept)\n self.hrm_human_resource_id(),\n CommentsField(),\n )\n\n # CRUD strings\n current.response.s3.crud_strings[tablename] = Storage(\n label_create = T(\"Add Person to Commitment\"),\n title_display = T(\"Committed Person Details\"),\n title_list = T(\"Committed People\"),\n title_update = T(\"Edit Committed Person\"),\n label_list_button = T(\"List Committed People\"),\n label_delete_button = T(\"Remove Person from Commitment\"),\n msg_record_created = T(\"Person added to Commitment\"),\n msg_record_modified = T(\"Committed Person updated\"),\n msg_record_deleted = T(\"Person removed from Commitment\"),\n msg_list_empty = T(\"No People currently committed\"))\n\n self.configure(tablename,\n deduplicate = S3Duplicate(primary = (\"commit_id\",\n \"human_resource_id\",\n ),\n ),\n # @ToDo: Fix this before enabling\n #onaccept = self.commit_person_onaccept,\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return None\n\n # -------------------------------------------------------------------------\n @staticmethod\n def commit_person_onaccept(form):\n \"\"\"\n FIXME not working\n \"\"\"\n\n db = current.db\n s3db = current.s3db\n table = db.req_commit_person\n rstable = s3db.req_req_skill\n\n # Try to get req_skill_id from the form\n req_skill_id = 0\n if form:\n req_skill_id = form.vars.get(\"req_skill_id\", None)\n if not req_skill_id:\n commit_skill_id = get_last_record_id(\"req_commit_skill\")\n r_commit_skill = table[commit_skill_id]\n req_skill_id = r_commit_skill.req_skill_id\n\n query = (table.req_skill_id == req_skill_id) & \\\n (table.deleted == False)\n commit_skills = db(query).select(table.quantity)\n quantity_commit = 0\n for commit_skill in commit_skills:\n quantity_commit += commit_skill.quantity\n\n r_req_skill = db.req_req_skill[req_skill_id]\n rstable[req_skill_id] = {\"quantity_commit\": quantity_commit}\n\n # Update status_commit of the req record\n set_last_record_id(\"req_req_skill\", r_req_skill.id)\n #req_skill_onaccept(None)\n\n# =============================================================================\nclass CommitSkillModel(DataModel):\n \"\"\"\n Commit anonymous people to a Request\n\n Used when settings.req.commit_people = False (default)\n \"\"\"\n\n names = (\"req_commit_skill\",)\n\n def model(self):\n\n T = current.T\n\n # -----------------------------------------------------------------\n # Committed Skills\n #\n tablename = \"req_commit_skill\"\n self.define_table(tablename,\n self.req_commit_id(),\n self.hrm_multi_skill_id(),\n Field(\"quantity\", \"double\", notnull=True,\n label = T(\"Quantity\"),\n ),\n CommentsField(),\n )\n\n # CRUD strings\n current.response.s3.crud_strings[tablename] = Storage(\n label_create = T(\"Add People to Commitment\"),\n title_display = T(\"Committed People Details\"),\n title_list = T(\"Committed People\"),\n title_update = T(\"Edit Committed People\"),\n label_list_button = T(\"List Committed People\"),\n label_delete_button = T(\"Remove People from Commitment\"),\n msg_record_created = T(\"People added to Commitment\"),\n msg_record_modified = T(\"Committed People updated\"),\n msg_record_deleted = T(\"People removed from Commitment\"),\n msg_list_empty = T(\"No People currently committed\"))\n\n self.configure(tablename,\n onaccept = self.commit_skill_onaccept,\n ondelete = self.commit_skill_ondelete,\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return None\n\n # -------------------------------------------------------------------------\n @staticmethod\n def commit_skill_onaccept(form):\n \"\"\"\n On-accept actions for committed skills\n - update the commit quantities and -status of the request\n \"\"\"\n\n db = current.db\n\n try:\n skill_id = form.vars.id\n except AttributeError:\n return\n\n # Get the req\n rtable = db.req_req\n ctable = db.req_commit\n stable = db.req_commit_skill\n query = (stable.id == skill_id) & \\\n (ctable.id == stable.commit_id) & \\\n (rtable.id == ctable.req_id)\n req = db(query).select(rtable.id,\n rtable.type,\n rtable.req_status,\n rtable.commit_status,\n limitby = (0, 1)\n ).first()\n if not req:\n return\n\n req_update_commit_quantities_and_status(req)\n\n # -------------------------------------------------------------------------\n @staticmethod\n def commit_skill_ondelete(row):\n \"\"\"\n On-delete actions for committed skills\n - update the commit quantities and -status of the request\n \"\"\"\n\n db = current.db\n s3db = current.s3db\n\n\n # Get the commit_id\n table = s3db.req_commit_skill\n row = db(table.id == row.id).select(table.deleted_fk,\n limitby = (0, 1)\n ).first()\n try:\n deleted_fk = json.loads(row.deleted_fk)\n except:\n return\n\n commit_id = deleted_fk.get(\"commit_id\")\n if commit_id:\n\n ctable = s3db.req_commit\n rtable = s3db.req_req\n query = (ctable.id == commit_id) & \\\n (rtable.id == ctable.req_id)\n req = db(query).select(rtable.id,\n rtable.type,\n rtable.req_status,\n rtable.commit_status,\n limitby = (0, 1)\n ).first()\n if req:\n req_update_commit_quantities_and_status(req)\n\n# =============================================================================\ndef req_ref_represent(value, show_link=True, pdf=False):\n \"\"\"\n Represent for the Request Reference\n if show_link is True then it will generate a link to the record\n if pdf is True then it will generate a link to the PDF\n\n TODO document parameters\n TODO S3Represent\n \"\"\"\n\n if value:\n if show_link:\n db = current.db\n table = db.req_req\n req_row = db(table.req_ref == value).select(table.id,\n limitby = (0, 1)\n ).first()\n if req_row:\n if pdf:\n args = [req_row.id, \"form\"]\n else:\n args = [req_row.id]\n return A(value,\n _href = URL(c=\"req\", f=\"req\",\n args = args,\n extension = \"\",\n ),\n )\n return B(value)\n\n return current.messages[\"NONE\"]\n\n# -------------------------------------------------------------------------\ndef req_tabs(r, match=True):\n \"\"\"\n Add a set of rheader tabs for a site's request management\n\n Args:\n r: the CRUDRequest (for permission checking)\n match: request matching is applicable for this type of site\n\n Returns:\n list of rheader tab definitions\n \"\"\"\n\n settings = current.deployment_settings\n\n tabs = []\n\n if settings.get_org_site_inv_req_tabs():\n\n has_permission = current.auth.s3_has_permission\n if settings.has_module(\"req\") and \\\n has_permission(\"read\", \"req_req\", c=\"req\"):\n\n T = current.T\n\n # Requests tab\n tabs = [(T(\"Requests\"), \"req\")]\n\n # Match-tab if applicable for the use-case and user\n # is permitted to match requests\n if match and has_permission(\"read\", \"req_req\",\n c = r.controller,\n f = \"req_match\",\n ):\n tabs.append((T(\"Match Requests\"), \"req_match/\"))\n\n # Commit-tab if using commits\n if settings.get_req_use_commit():\n tabs.append((T(\"Commit\"), \"commit\"))\n\n return tabs\n\n# -----------------------------------------------------------------------------\ndef req_update_status(req_id):\n \"\"\"\n Update the request committed/in-transit/fulfilled statuses from the\n quantities of items requested vs. committed/in-transit/fulfilled\n\n Status:\n NONE quantity=0 for all items\n PARTIAL quantity>0 but less than requested quantity for\n at least one item\n COMPLETE quantity>=requested quantity for all items\n \"\"\"\n\n db = current.db\n s3db = current.s3db\n table = s3db.req_req_item\n is_none = {\"commit\": True,\n \"transit\": True,\n \"fulfil\": True,\n }\n\n is_complete = {\"commit\": True,\n \"transit\": True,\n \"fulfil\": True,\n }\n\n # Must check all items in the req (TODO really?)\n query = (table.req_id == req_id) & \\\n (table.deleted == False )\n req_items = db(query).select(table.quantity,\n table.quantity_commit,\n table.quantity_transit,\n table.quantity_fulfil,\n )\n\n for req_item in req_items:\n quantity = req_item.quantity\n for status_type in [\"commit\", \"transit\", \"fulfil\"]:\n if req_item[\"quantity_%s\" % status_type] < quantity:\n is_complete[status_type] = False\n if req_item[\"quantity_%s\" % status_type]:\n is_none[status_type] = False\n\n status_update = {}\n for status_type in [\"commit\", \"transit\", \"fulfil\"]:\n if is_complete[status_type]:\n status_update[\"%s_status\" % status_type] = REQ_STATUS_COMPLETE\n elif is_none[status_type]:\n status_update[\"%s_status\" % status_type] = REQ_STATUS_NONE\n else:\n status_update[\"%s_status\" % status_type] = REQ_STATUS_PARTIAL\n\n rtable = s3db.req_req\n db(rtable.id == req_id).update(**status_update)\n\n# -------------------------------------------------------------------------\ndef req_update_commit_quantities_and_status(req):\n \"\"\"\n Update commit quantities and status of a request\n\n Args:\n req: the req_req record (Row)\n \"\"\"\n\n db = current.db\n s3db = current.s3db\n ctable = s3db.req_commit\n\n req_id = req.id\n req_type = req.type\n\n if req_type == 1: # Items\n\n pack_quantities = s3db.supply_item_pack_quantities\n\n # Get all commits for this request\n citable = s3db.req_commit_item\n query = (ctable.req_id == req_id) & \\\n (citable.commit_id == ctable.id) & \\\n (citable.deleted == False)\n citems = db(query).select(citable.item_pack_id,\n citable.quantity,\n )\n pqty = pack_quantities(item.item_pack_id for item in citems)\n\n # Determine committed quantities per pack type\n commit_qty = {}\n for item in citems:\n\n item_pack_id = item.item_pack_id\n committed_quantity = (item.quantity * pqty.get(item_pack_id, 1))\n\n if item_pack_id in commit_qty:\n commit_qty[item_pack_id] += committed_quantity\n else:\n commit_qty[item_pack_id] = committed_quantity\n\n ritable = s3db.req_req_item\n query = (ritable.req_id == req_id) & \\\n (ritable.deleted == False)\n if not any(qty for qty in commit_qty.values()):\n # Nothing has been committed for this request so far\n commit_status = REQ_STATUS_NONE\n db(query).update(quantity_commit=0)\n else:\n # Get all requested items for this request\n ritems = db(query).select(ritable.id,\n ritable.item_pack_id,\n ritable.quantity,\n ritable.quantity_commit,\n )\n\n pack_ids = (item.item_pack_id for item in ritems\n if item.item_pack_id not in pqty)\n pqty.update(pack_quantities(pack_ids))\n\n # Assume complete unless we find a gap\n commit_status = REQ_STATUS_COMPLETE\n\n # Update committed quantity for each requested item (if changed),\n # and check if there is still a commit-gap\n for item in ritems:\n\n committed_quantity = commit_qty.get(item.item_pack_id) or 0\n requested_quantity = item.quantity * pqty.get(item_pack_id, 1)\n\n if committed_quantity != item.quantity_commit:\n # Update it\n item.update_record(quantity_commit=committed_quantity)\n\n if committed_quantity < requested_quantity:\n # Gap!\n commit_status = REQ_STATUS_PARTIAL\n\n # Update commit-status of the request (if changed)\n if commit_status != req.commit_status:\n req.update_record(commit_status=commit_status)\n\n elif req_type == 3: # People\n\n # If this is a single person commitment, then create the\n # commit_person record automatically\n #table = s3db.req_commit_person\n #table.insert(commit_id = commit_id,\n # #skill_id = ???,\n # person_id = auth.s3_logged_in_person())\n ## @ToDo: Mark Person's allocation status as 'Committed'\n\n # Get all commits for this request\n cstable = s3db.req_commit_skill\n query = (ctable.req_id == req_id) & \\\n (cstable.commit_id == ctable.id) & \\\n (cstable.deleted == False)\n cskills = db(query).select(cstable.skill_id,\n cstable.quantity,\n )\n\n rstable = s3db.req_req_skill\n query = (rstable.req_id == req_id) & \\\n (rstable.deleted == False)\n\n if not any(row.quantity for row in cskills):\n # Nothing has been committed for this request so far\n commit_status = REQ_STATUS_NONE\n db(query).update(quantity_commit=0)\n else:\n # Get all requested skill(set)s for this request\n rskills = db(query).select(rstable.id,\n rstable.skill_id,\n rstable.quantity,\n rstable.quantity_commit,\n )\n\n # Match requested and committed skill sets\n # - find the least complex committed skill set to\n # fulfill a requested skill set\n # - start with most complex requested skill sets\n req_skills = sorted(({\"id\": row.id,\n \"skillset\": set(row.skill_id),\n \"requested\": row.quantity,\n \"committed\": row.quantity_commit,\n } for row in rskills),\n key = lambda s: -len(s[\"skillset\"]),\n )\n\n cmt_skills = sorted(({\"skillset\": set(row.skill_id),\n \"available\": row.quantity,\n } for row in cskills),\n key = lambda s: len(s[\"skillset\"]),\n )\n\n none = complete = True\n for req_skill_set in req_skills:\n\n requested_quantity = req_skill_set[\"requested\"]\n quantity_commit = 0\n\n for cmt_skill_set in cmt_skills:\n\n available = cmt_skill_set[\"available\"]\n required = requested_quantity - quantity_commit\n if not available or not required:\n continue\n\n if req_skill_set[\"skillset\"] <= cmt_skill_set[\"skillset\"]:\n\n # Apply available quantity\n to_commit = min(required, available)\n quantity_commit += to_commit\n cmt_skill_set[\"available\"] -= to_commit\n\n if quantity_commit == requested_quantity:\n break\n\n # If quantity_commit has changed => update it in the DB\n if quantity_commit != req_skill_set[\"committed\"]:\n # Update committed quantity\n db(rstable.id == req_skill_set[\"id\"]).update(quantity_commit = quantity_commit)\n\n if requested_quantity > quantity_commit:\n complete = False\n if quantity_commit > 0:\n none = False\n\n if none:\n commit_status = REQ_STATUS_NONE\n elif complete:\n commit_status = REQ_STATUS_COMPLETE\n else:\n commit_status = REQ_STATUS_PARTIAL\n\n if commit_status != req.commit_status:\n req.update_record(commit_status = commit_status)\n\n elif req_type == 9: # Other\n\n # Assume Partial not Complete\n # @ToDo: Provide a way for the committer to specify this\n data = {}\n if req.commit_status == REQ_STATUS_NONE:\n data[\"commit_status\"] = REQ_STATUS_PARTIAL\n if req.req_status == REQ_STATUS_NONE:\n # Show as 'Responded'\n data[\"req_status\"] = REQ_STATUS_PARTIAL\n if data:\n req.update_record(**data)\n\n# =============================================================================\ndef req_req_details(row):\n \"\"\"\n Field method for requests, representing all requested items/skills\n as string (for use in data tables/lists)\n \"\"\"\n\n if hasattr(row, \"req_req\"):\n row = row.req_req\n try:\n record_id = row.id\n req_type = row.type\n except AttributeError:\n return None\n\n if req_type == 1:\n s3db = current.s3db\n itable = s3db.supply_item\n ltable = s3db.req_req_item\n query = (ltable.deleted != True) & \\\n (ltable.req_id == record_id) & \\\n (ltable.item_id == itable.id)\n items = current.db(query).select(itable.name,\n ltable.quantity,\n )\n if items:\n items = [\"%s %s\" % (int(item.req_req_item.quantity),\n item.supply_item.name)\n for item in items]\n return \",\".join(items)\n\n elif req_type == 3:\n s3db = current.s3db\n ltable = s3db.req_req_skill\n query = (ltable.deleted != True) & \\\n (ltable.req_id == record_id)\n skills = current.db(query).select(ltable.skill_id,\n ltable.quantity,\n )\n if skills:\n represent = S3Represent(lookup=\"hrm_skill\",\n multiple=True,\n none=current.T(\"Unskilled\")\n )\n skills = [\"%s %s\" % (skill.quantity,\n represent(skill.skill_id)) \\\n for skill in skills]\n return \",\".join(skills)\n\n return current.messages[\"NONE\"]\n\n# =============================================================================\ndef req_req_drivers(row):\n \"\"\"\n Field method for requests, representing all assigned drivers\n as string (for use in data tables/lists)\n \"\"\"\n\n if hasattr(row, \"req_req\"):\n row = row.req_req\n try:\n req_ref = row.req_ref\n req_type = row.type\n except AttributeError:\n return None\n\n if req_type == 1:\n s3db = current.s3db\n stable = s3db.inv_send\n query = (stable.deleted != True) & \\\n (stable.req_ref == req_ref)\n drivers = current.db(query).select(stable.driver_name,\n stable.driver_phone,\n stable.vehicle_plate_no,\n )\n if drivers:\n drivers = [\"%s %s %s\" % (driver.driver_name or \"\",\n driver.driver_phone or \"\",\n driver.vehicle_plate_no or \"\") \\\n for driver in drivers]\n return \",\".join(drivers)\n\n return current.messages[\"NONE\"]\n\n# =============================================================================\ndef req_rheader(r, check_page=False):\n \"\"\"\n Resource Header for Requests & Needs\n\n TODO improve structure/readability\n \"\"\"\n\n if r.representation != \"html\":\n # RHeaders only used in interactive views\n return None\n\n record = r.record\n if not record:\n # RHeaders only used in single-record views\n return None\n\n resourcename = r.name\n if resourcename == \"req\":\n T = current.T\n db = current.db\n s3db = current.s3db\n s3 = current.response.s3\n settings = current.deployment_settings\n\n is_template = record.is_template\n use_commit = settings.get_req_use_commit()\n use_workflow = settings.get_req_workflow()\n\n rtype = record.type\n if rtype == 1 and settings.has_module(\"inv\"):\n items = True\n people = False\n elif rtype == 3 and settings.has_module(\"hrm\"):\n items = False\n people = True\n else:\n items = False\n people = False\n\n site_id = record.site_id\n workflow_status = record.workflow_status\n\n tabs = [(T(\"Edit Details\"), None)]\n if items:\n if settings.get_req_multiple_req_items():\n req_item_tab_label = T(\"Items\")\n else:\n req_item_tab_label = T(\"Item\")\n tabs.append((req_item_tab_label, \"req_item\"))\n elif people:\n tabs.append((T(\"Skills\"), \"req_skill\"))\n #if settings.get_req_document_filing():\n tabs.append((T(\"Documents\"), \"document\"))\n if is_template:\n tabs.append((T(\"Schedule\"), \"job\"))\n else:\n # Hide these if no Items/Skills on one of these requests yet\n auth = current.auth\n req_id = record.id\n if items:\n user = auth.user\n user_site_id = user.site_id if user else None\n ritable = s3db.req_req_item\n possibly_complete = db(ritable.req_id == req_id).select(ritable.id,\n limitby = (0, 1)\n )\n elif people:\n user = auth.user\n organisation_id = user.organisation_id if user else None\n rstable = s3db.req_req_skill\n possibly_complete = db(rstable.req_id == req_id).select(rstable.id,\n limitby = (0, 1)\n )\n else:\n possibly_complete = True\n if possibly_complete:\n if use_commit:\n tabs.append((T(\"Commitments\"), \"commit\"))\n if (items and user_site_id) or \\\n (people and organisation_id and settings.get_req_commit_people()):\n tabs.append((T(\"Check\"), \"check\"))\n if use_workflow:\n if workflow_status == 1: # Draft\n submit_btn = A(T(\"Submit for Approval\"),\n _href = URL(c = \"req\",\n f = \"req\",\n args = [req_id, \"submit\"]\n ),\n _id = \"req-submit\",\n _class = \"action-btn\",\n )\n s3.jquery_ready.append('''S3.confirmClick('#req-submit','%s')''' \\\n % T(\"Are you sure you want to submit this request?\"))\n s3.rfooter = TAG[\"\"](submit_btn)\n elif workflow_status == 2: # Submitted\n if req_is_approver(site_id):\n # Have they already approved?\n atable = s3db.req_approver_req\n query = (atable.req_id == req_id) & \\\n (atable.person_id == auth.s3_logged_in_person())\n approved = db(query).select(atable.id,\n limitby = (0, 1)\n )\n if not approved:\n approve_btn = A(T(\"Approve\"),\n _href = URL(c = \"req\",\n f = \"req\",\n args = [req_id, \"approve_req\"]\n ),\n _id = \"req-approve\",\n _class = \"action-btn\",\n )\n s3.jquery_ready.append('''S3.confirmClick('#req-approve','%s')''' \\\n % T(\"Are you sure you want to approve this request?\"))\n s3.rfooter = TAG[\"\"](approve_btn)\n\n if not check_page:\n rheader_tabs = s3_rheader_tabs(r, tabs)\n else:\n rheader_tabs = DIV()\n\n if items and r.component and \\\n r.component_name == \"commit\" and \\\n r.component_id:\n prepare_btn = A(T(\"Prepare Shipment\"),\n _href = URL(f = \"send_commit\",\n args = [r.component_id]\n ),\n _id = \"send-commit\",\n _class = \"action-btn\",\n )\n s3.rfooter = TAG[\"\"](prepare_btn)\n\n if site_id:\n stable = s3db.org_site\n if use_workflow and workflow_status in (1, 2, 5): # Draft/Submitted/Cancelled\n transit_status = (\"\",)\n elif settings.get_req_show_quantity_transit() and not is_template:\n transit_status = req_status_opts().get(record.transit_status,\n \"\")\n # @ToDo: Create the 'incoming' function if we need this!\n #if site_id and \\\n # record.transit_status in [REQ_STATUS_PARTIAL, REQ_STATUS_COMPLETE] and \\\n # record.fulfil_status in [None, REQ_STATUS_NONE, REQ_STATUS_PARTIAL]:\n # site_record = db(stable.site_id == site_id).select(stable.uuid,\n # stable.instance_type,\n # limitby = (0, 1)\n # ).first()\n # instance_type = site_record.instance_type\n # table = s3db[instance_type]\n # query = (table.uuid == site_record.uuid)\n # instance_id = db(query).select(table.id,\n # limitby = (0, 1)\n # ).first().id\n # transit_status = SPAN(transit_status,\n # A(T(\"Incoming Shipments\"),\n # _href = URL(c = instance_type.split(\"_\")[0],\n # f = \"incoming\",\n # vars = {\"viewing\" : \"%s.%s\" % (instance_type, instance_id)}\n # )\n # )\n # )\n transit_status = (TH(\"%s: \" % T(\"Transit Status\")),\n transit_status)\n else:\n transit_status = (\"\",)\n\n table = r.table\n\n if settings.get_req_use_req_number() and not is_template:\n headerTR = TR(TH(\"%s: \" % table.req_ref.label),\n TD(table.req_ref.represent(record.req_ref, show_link=True))\n )\n else:\n headerTR = TR(TD(settings.get_req_form_name(),\n _colspan = 2,\n _class = \"pdf_title\",\n ),\n )\n if site_id:\n org_id = db(stable.site_id == site_id).select(stable.organisation_id,\n limitby = (0, 1)\n ).first().organisation_id\n logo = s3db.org_organisation_logo(org_id)\n if logo:\n headerTR.append(TD(logo,\n _colspan = 2,\n ))\n\n if is_template:\n row1 = \"\"\n row3 = \"\"\n else:\n if use_workflow and workflow_status in (1, 2, 5): # Draft/Submitted/Cancelled\n row1_status = (TH(\"%s: \" % table.workflow_status.label),\n table.workflow_status.represent(workflow_status),\n )\n fulfil_status = (\"\",)\n else:\n if use_commit:\n row1_status = (TH(\"%s: \" % table.commit_status.label),\n table.commit_status.represent(record.commit_status),\n )\n else:\n row1_status = (\"\",)\n fulfil_status = (TH(\"%s: \" % table.fulfil_status.label),\n table.fulfil_status.represent(record.fulfil_status),\n )\n row1 = TR(TH(\"%s: \" % table.date.label),\n table.date.represent(record.date),\n *row1_status\n )\n row3 = TR(TH(\"%s: \" % table.date_required.label),\n table.date_required.represent(record.date_required),\n *fulfil_status\n )\n\n rheader = DIV(TABLE(headerTR,\n row1,\n TR(TH(\"%s: \" % table.site_id.label),\n table.site_id.represent(site_id),\n *transit_status\n ),\n row3,\n TR(TH(\"%s: \" % table.requester_id.label),\n table.requester_id.represent(record.requester_id),\n ),\n TR(TH(\"%s: \" % table.purpose.label),\n record.purpose or current.messages[\"NONE\"],\n ),\n TR(TH(\"%s: \" % table.comments.label),\n TD(record.comments or \"\",\n _colspan = 3,\n ),\n ),\n ),\n rheader_tabs,\n )\n\n elif resourcename == \"need\":\n T = current.T\n tabs = [(T(\"Basic Details\"), None),\n (T(\"Demographics\"), \"demographic\"),\n (T(\"Items\"), \"need_item\"),\n (T(\"Skills\"), \"need_skill\"),\n (T(\"Tags\"), \"tag\"),\n ]\n\n rheader_tabs = s3_rheader_tabs(r, tabs)\n\n location_id = r.table.location_id\n rheader = DIV(TABLE(TR(TH(\"%s: \" % location_id.label),\n location_id.represent(record.location_id),\n )),\n rheader_tabs)\n\n else:\n # Not defined, probably using wrong rheader\n rheader = None\n\n return rheader\n\n# =============================================================================\ndef req_match(rheader = None):\n \"\"\"\n Generic controller to display all requests a site could potentially\n fulfill as a tab of that site instance\n - add as req_match controller to the module, then\n - configure as rheader-tab \"req_match/\" for the site resource\n\n Args:\n rheader: module-specific rheader\n\n Notes:\n - make sure rheader uses s3_rheader_resource to handle \"viewing\"\n - can override rheader in customise_req_req_controller by\n updating attr dict\n \"\"\"\n\n T = current.T\n s3db = current.s3db\n s3 = current.response.s3\n request = current.request\n settings = current.deployment_settings\n\n output = {}\n\n viewing = request.get_vars.get(\"viewing\", None)\n if not viewing:\n return output\n if \".\" in viewing:\n tablename, record_id = viewing.split(\".\", 1)\n else:\n return output\n\n # Ensure any custom settings are applied\n customise = settings.get(\"customise_%s_resource\" % tablename)\n if customise:\n try:\n customise(request, tablename)\n except:\n current.log.error(\"customise_%s_resource is using attributes of r which aren't in request\" % tablename)\n\n table = s3db[tablename]\n row = current.db(table.id == record_id).select(table.site_id,\n limitby = (0, 1)\n ).first()\n if row:\n site_id = row.site_id\n else:\n return output\n\n actions = [{\"label\": s3_str(T(\"Check\")),\n \"url\": URL(c=\"req\", f=\"req\",\n args = [\"[id]\", \"check\"],\n vars = {\"site_id\": site_id,\n }\n ),\n \"_class\": \"action-btn\",\n }\n ]\n\n if current.auth.s3_has_permission(\"update\", tablename, record_id):\n # @ToDo: restrict to those which we've not already committed/sent?\n if settings.get_req_use_commit():\n actions.append({\"label\": s3_str(T(\"Commit\")),\n \"url\": URL(c=\"req\", f=\"commit_req\",\n args = [\"[id]\"],\n vars = {\"site_id\": site_id,\n }\n ),\n \"_class\": \"action-btn\",\n })\n # Better to force people to go through the Check process\n #actions.append({\"label\": s3_str(T(\"Send\")),\n # \"url\": URL(c=\"req\", f=\"send_req\",\n # args = [\"[id]\"],\n # vars = {\"site_id\": site_id,\n # }\n # ),\n # \"_class\": \"action-btn dispatch\",\n # })\n\n s3.actions = actions\n\n if rheader is None:\n if tablename == \"org_office\":\n rheader = s3db.org_rheader\n elif tablename == \"org_facility\":\n rheader = s3db.org_facility_rheader\n elif tablename == \"inv_warehouse\":\n rheader = s3db.inv_rheader\n elif tablename == \"cr_shelter\":\n rheader = s3db.cr_rheader\n elif tablename == \"hms_hospital\":\n rheader = s3db.hms_hospital_rheader\n\n s3.filter = (s3db.req_req.site_id != site_id)\n s3db.configure(\"req_req\",\n insertable = False,\n )\n\n # Pre-process\n def prep(r):\n if settings.get_req_workflow():\n # Only show Approved Requests\n r.resource.add_filter(FS(\"workflow_status\") == 3)\n\n return True\n s3.prep = prep\n\n # Post-process\n def postp(r, output):\n if r.representation == \"html\":\n output[\"title\"] = s3.crud_strings[tablename].title_display\n return output\n s3.postp = postp\n\n return current.crud_controller(\"req\", \"req\", rheader=rheader)\n\n# =============================================================================\ndef req_send_commit():\n \"\"\"\n Controller function to create a Shipment containing all\n items in a commitment (interactive)\n \"\"\"\n\n # Get the commit record\n try:\n commit_id = current.request.args[0]\n except KeyError:\n redirect(URL(c=\"req\", f=\"commit\"))\n\n db = current.db\n s3db = current.s3db\n\n req_table = db.req_req\n rim_table = db.req_req_item\n com_table = db.req_commit\n cim_table = db.req_commit_item\n\n send_table = s3db.inv_send\n tracktable = s3db.inv_track_item\n\n query = (com_table.id == commit_id) & \\\n (com_table.req_id == req_table.id) & \\\n (com_table.deleted == False)\n record = db(query).select(com_table.committer_id,\n com_table.site_id,\n com_table.organisation_id,\n req_table.requester_id,\n req_table.site_id,\n req_table.req_ref,\n limitby = (0, 1)\n ).first()\n\n # @ToDo: Identify if we have stock items which match the commit items\n # If we have a single match per item then proceed automatically (as-now) & then decrement the stock quantity\n # If we have no match then warn the user & ask if they should proceed anyway\n # If we have mulitple matches then provide a UI to allow the user to select which stock items to use\n\n # Create an inv_send and link to the commit\n form_vars = Storage(sender_id = record.req_commit.committer_id,\n site_id = record.req_commit.site_id,\n recipient_id = record.req_req.requester_id,\n to_site_id = record.req_req.site_id,\n req_ref = record.req_req.req_ref,\n status = 0,\n )\n send_id = send_table.insert(**form_vars)\n form_vars.id = send_id\n\n # Get all of the committed items\n query = (cim_table.commit_id == commit_id) & \\\n (cim_table.req_item_id == rim_table.id) & \\\n (cim_table.deleted == False)\n records = db(query).select(rim_table.id,\n rim_table.item_id,\n rim_table.item_pack_id,\n rim_table.currency,\n rim_table.quantity,\n rim_table.quantity_transit,\n rim_table.quantity_fulfil,\n cim_table.quantity,\n )\n # Create inv_track_items for each commit item\n insert = tracktable.insert\n for row in records:\n rim = row.req_req_item\n # Now done as a VirtualField instead (looks better & updates closer to real-time, so less of a race condition)\n #quantity_shipped = max(rim.quantity_transit, rim.quantity_fulfil)\n #quantity_needed = rim.quantity - quantity_shipped\n insert(req_item_id = rim.id,\n track_org_id = record.req_commit.organisation_id,\n send_id = send_id,\n status = 1,\n item_id = rim.item_id,\n item_pack_id = rim.item_pack_id,\n currency = rim.currency,\n #req_quantity = quantity_needed,\n quantity = row.req_commit_item.quantity,\n recv_quantity = row.req_commit_item.quantity,\n )\n\n # Create the Waybill\n form = Storage()\n form.vars = form_vars\n s3db.inv_send_onaccept(form)\n\n # Redirect to inv_send for the send id just created\n redirect(URL(#c = \"inv\", or \"req\"\n f = \"send\",\n #args = [send_id, \"track_item\"]\n args = [send_id]\n ))\n\n# =============================================================================\nclass req_CheckMethod(CRUDMethod):\n \"\"\"\n Check to see if you can match a Request\n - Using the Inventory of your Site if this is an Items request\n - Using the Skills of your HRs if this is a Skills request\n \"\"\"\n\n # -------------------------------------------------------------------------\n def apply_method(self, r, **attr):\n \"\"\"\n Applies the method (controller entry point).\n\n Args:\n r: the CRUDRequest\n attr: controller options for this request\n \"\"\"\n\n req_type = r.record.type\n if req_type == 1:\n return self.inv_match(r, **attr)\n elif req_type == 3:\n return self.skills_match(r, **attr)\n else:\n r.error(405, current.ERROR.BAD_METHOD)\n\n # -------------------------------------------------------------------------\n @staticmethod\n def inv_match(r, **attr):\n \"\"\"\n Match a Request's Items with a Site's Inventory\n \"\"\"\n\n T = current.T\n db = current.db\n s3db = current.s3db\n response = current.response\n s3 = response.s3\n\n output = {\"title\": T(\"Check Request\"),\n \"rheader\": req_rheader(r, check_page=True),\n \"subtitle\": T(\"Requested Items\"),\n }\n\n # Read req_items\n table = s3db.req_req_item\n query = (table.req_id == r.id ) & \\\n (table.deleted == False )\n req_items = db(query).select(table.id,\n table.item_id,\n table.quantity,\n table.item_pack_id,\n table.quantity_commit,\n table.quantity_transit,\n table.quantity_fulfil,\n )\n\n if len(req_items):\n site_id = r.get_vars.get(\"site_id\") or current.auth.user.site_id\n\n if site_id:\n site_name = s3db.org_site_represent(site_id, show_link=False)\n qty_in_label = s3_str(T(\"Quantity in %s\")) % site_name\n else:\n qty_in_label = T(\"Quantity Available\")\n\n # Build the Output Representation\n row = TR(TH(table.item_id.label),\n TH(table.quantity.label),\n TH(table.item_pack_id.label),\n #TH(table.quantity_transit.label),\n #TH(table.quantity_fulfil.label),\n TH(T(\"Quantity Oustanding\")),\n TH(qty_in_label),\n TH(T(\"Match?\"))\n )\n #use_commit = current.deployment_settings.get_req_use_commit()\n #if use_commit:\n # row.insert(3, TH(table.quantity_commit.label))\n items = TABLE(THEAD(row),\n _id = \"list\",\n _class = \"dataTable display\",\n )\n if site_id:\n stable = s3db.org_site\n ltable = s3db.gis_location\n query = (stable.id == site_id) & \\\n (stable.location_id == ltable.id)\n location_r = db(query).select(ltable.lat,\n ltable.lon,\n limitby = (0, 1)\n ).first()\n query = (stable.id == r.record.site_id ) & \\\n (stable.location_id == ltable.id)\n req_location_r = db(query).select(ltable.lat,\n ltable.lon,\n limitby = (0, 1)\n ).first()\n\n try:\n distance = current.gis.greatCircleDistance(location_r.lat,\n location_r.lon,\n req_location_r.lat,\n req_location_r.lon)\n output[\"rheader\"][0].append(TR(TH(s3_str(T(\"Distance from %s:\")) % site_name,\n ),\n TD(T(\"%.1f km\") % distance)\n ))\n except:\n pass\n\n if len(req_items):\n # Get inv_items from this site which haven't expired and are in good condition\n iitable = s3db.inv_inv_item\n query = (iitable.site_id == site_id) & \\\n (iitable.deleted == False) & \\\n ((iitable.expiry_date >= r.now) | ((iitable.expiry_date == None))) & \\\n (iitable.status == 0)\n inv_items_dict = {}\n inv_items = db(query).select(iitable.item_id,\n iitable.quantity,\n iitable.item_pack_id,\n # VF\n #iitable.pack_quantity,\n )\n for item in inv_items:\n item_id = item.item_id\n if item_id in inv_items_dict:\n inv_items_dict[item_id] += item.quantity * item.pack_quantity()\n else:\n inv_items_dict[item_id] = item.quantity * item.pack_quantity()\n\n supply_item_represent = table.item_id.represent\n item_pack_represent = table.item_pack_id.represent\n no_match = True\n for req_item in req_items:\n req_quantity = req_item.quantity\n # Do we have any outstanding quantity?\n quantity_outstanding = req_quantity - max(req_item.quantity_fulfil, req_item.quantity_transit)\n if quantity_outstanding:\n # Convert Packs inv item quantity to req item quantity\n item_id = req_item.item_id\n if item_id in inv_items_dict:\n inv_quantity = inv_items_dict[item_id] / req_item.pack_quantity()\n else:\n inv_quantity = 0\n\n if inv_quantity != 0:\n no_match = False\n if inv_quantity < req_quantity:\n status = SPAN(T(\"Partial\"), _class=\"req_status_partial\")\n else:\n status = SPAN(T(\"YES\"), _class=\"req_status_complete\")\n else:\n status = SPAN(T(\"NO\"), _class=\"req_status_none\")\n else:\n inv_quantity = T(\"N/A\")\n status = SPAN(T(\"N/A\"), _class=\"req_status_none\")\n\n items.append(TR(#A(req_item.id),\n supply_item_represent(req_item.item_id),\n req_quantity,\n item_pack_represent(req_item.item_pack_id),\n # This requires an action btn to get the req_id\n #req_item.quantity_commit, # if use_commit\n #req_item.quantity_transit,\n #req_item.quantity_fulfil,\n #req_quantity_represent(req_item.quantity_commit, \"commit\"), # if use_commit\n #req_quantity_represent(req_item.quantity_fulfil, \"fulfil\"),\n #req_quantity_represent(req_item.quantity_transit, \"transit\"),\n quantity_outstanding,\n inv_quantity,\n status,\n )\n )\n\n #s3.actions = [req_item_inv_item_btn]\n if no_match:\n response.warning = s3_str(T(\"%(site_name)s has no items exactly matching this request. Use Alternative Items if wishing to use other items to fulfill this request!\") %\n {\"site_name\": site_name})\n else:\n commit_btn = A(s3_str(T(\"Send from %s\")) % site_name,\n _href = URL(#c = \"inv\", or \"req\"\n #c = \"req\",\n f = \"send_req\",\n args = [r.id],\n vars = {\"site_id\": site_id}\n ),\n _class = \"action-btn\"\n )\n s3.rfooter = TAG[\"\"](commit_btn)\n\n else:\n response.error = T(\"User has no Site to check against!\")\n\n output[\"items\"] = items\n s3.no_sspag = True # pag won't work\n s3.no_formats = True\n\n else:\n output[\"items\"] = s3.crud_strings.req_req_item.msg_list_empty\n\n response.view = \"list.html\"\n\n return output\n\n # -------------------------------------------------------------------------\n @staticmethod\n def skills_match(r, **attr):\n \"\"\"\n Match a Request's Skills with an Organisation's HRs\n\n @ToDo: Optionally Filter by Site\n (Volunteers don't currently link to a Site)\n @ToDo: Check Availability\n - when the Volunteer has said they will work\n - where the Volunteer has said they will work\n - don't commit the same time slot twice\n \"\"\"\n\n T = current.T\n db = current.db\n s3db = current.s3db\n response = current.response\n s3 = response.s3\n\n output = {\"title\": T(\"Check Request\"),\n \"rheader\": req_rheader(r, check_page=True),\n \"subtitle\": T(\"Requested Skills\"),\n }\n\n # Read req_skills\n table = s3db.req_req_skill\n query = (table.req_id == r.id ) & \\\n (table.deleted == False )\n req_skills_multi = db(query).select(table.id,\n table.skill_id,\n table.quantity,\n table.quantity_commit,\n table.quantity_transit,\n table.quantity_fulfil,\n )\n\n if len(req_skills_multi):\n organisation_id = r.get_vars.get(\"organisation_id\") or \\\n current.auth.user.organisation_id\n\n if organisation_id:\n org_name = s3db.org_organisation_represent(organisation_id,\n show_link=False)\n qty_in_label = s3_str(T(\"Quantity in %s\")) % org_name\n else:\n qty_in_label = T(\"Quantity Available\")\n\n # Build the Output Representation\n row = TR(TH(table.skill_id.label),\n TH(table.quantity.label),\n #TH(table.quantity_transit.label),\n #TH(table.quantity_fulfil.label),\n TH(T(\"Quantity Oustanding\")),\n TH(qty_in_label),\n TH(T(\"Match?\"))\n )\n #use_commit = current.deployment_settings.get_req_use_commit()\n #if use_commit:\n # row.insert(3, TH(table.quantity_commit.label))\n items = TABLE(THEAD(row),\n _id=\"list\",\n _class=\"dataTable display\",\n )\n\n if organisation_id:\n\n req_skills = []\n for row in req_skills_multi:\n skills_multi = row.skill_id\n for skill_id in skills_multi:\n if skill_id not in req_skills:\n req_skills.append(skill_id)\n\n # Get the People from this Org with at least one of the Requested Skills\n # NB This isn't exact yet since we may need people to have multiple skills\n htable = s3db.hrm_human_resource\n #ptable = s3db.pr_person\n ctable = s3db.hrm_competency\n query = (htable.organisation_id == organisation_id) & \\\n (htable.deleted == False) & \\\n (htable.person_id == ctable.person_id) & \\\n (ctable.deleted == False) & \\\n (ctable.skill_id.belongs(req_skills))\n skills = db(query).select(htable.id,\n ctable.skill_id,\n )\n people = {}\n for s in skills:\n hr_id = s[htable.id]\n if hr_id in people:\n people[hr_id].append(s[ctable.skill_id])\n else:\n people[hr_id] = [s[ctable.skill_id]]\n\n multi_skill_represent = table.skill_id.represent\n no_match = True\n for req_skill in req_skills_multi:\n skills = req_skill.skill_id\n req_quantity = req_skill.quantity\n # Do we have any outstanding quantity?\n quantity_outstanding = req_quantity - max(req_skill.quantity_fulfil, req_skill.quantity_transit)\n if quantity_outstanding:\n len_skills = len(skills)\n matches = []\n for p in people:\n smatches = 0\n for s in skills:\n if s in people[p]:\n smatches += 1\n if smatches == len_skills:\n matches.append(p)\n org_quantity = len(matches)\n if org_quantity != 0:\n no_match = False\n if org_quantity < req_quantity:\n status = SPAN(T(\"Partial\"), _class=\"req_status_partial\")\n else:\n status = SPAN(T(\"YES\"), _class=\"req_status_complete\")\n else:\n status = SPAN(T(\"NO\"), _class=\"req_status_none\")\n else:\n org_quantity = T(\"N/A\")\n status = SPAN(T(\"N/A\"), _class=\"req_status_none\")\n\n items.append(TR(#A(req_item.id),\n multi_skill_represent(skills),\n req_quantity,\n # This requires an action btn to get the req_id\n #req_skill.quantity_commit, # if use_commit\n #req_skill.quantity_transit,\n #req_skill.quantity_fulfil,\n #req_quantity_represent(req_skill.quantity_commit, \"commit\"), # if use_commit\n #req_quantity_represent(req_skill.quantity_fulfil, \"fulfil\"),\n #req_quantity_represent(req_skill.quantity_transit, \"transit\"),\n quantity_outstanding,\n org_quantity,\n status,\n )\n )\n\n if not no_match:\n commit_btn = A(T(\"Assign People to this Request\"),\n _href = URL(c = \"req\",\n f = \"req\",\n args = [r.id, \"commit_all\", \"assign\"],\n ),\n _class = \"action-btn\"\n )\n s3.rfooter = TAG[\"\"](commit_btn)\n else:\n response.error = T(\"User has no Organization to check against!\")\n\n output[\"items\"] = items\n s3.no_sspag = True # pag won't work\n s3.no_formats = True\n\n else:\n output[\"items\"] = s3.crud_strings.req_req_skill.msg_list_empty\n\n response.view = \"list.html\"\n\n return output\n\n# =============================================================================\nclass req_RequesterRepresent(S3Represent):\n \"\"\"\n Representation of the requester_id, incl. mobile phone number\n and link to contacts tab of the person.\n \"\"\"\n\n def __init__(self, show_link=True):\n \"\"\"\n Args:\n show_link: render as link to the contact tab of\n the requester (in PR/HRM/VOL as appropriate)\n \"\"\"\n\n super().__init__(lookup = \"pr_person\",\n show_link = show_link,\n )\n\n # -------------------------------------------------------------------------\n def lookup_rows(self, key, values, fields=None):\n \"\"\"\n Custom look-up of rows\n\n Args:\n key: the key field\n values: the values to look up\n fields: unused (retained for API compatibility)\n \"\"\"\n\n s3db = current.s3db\n\n ptable = self.table\n\n count = len(values)\n if count == 1:\n query = (ptable.id == values[0])\n else:\n query = (ptable.id.belongs(values))\n\n ctable = s3db.pr_contact\n left = [ctable.on((ctable.pe_id == ptable.pe_id) & \\\n (ctable.contact_method == \"SMS\")),\n ]\n fields = [ptable.id,\n ptable.first_name,\n ptable.middle_name,\n ptable.last_name,\n ctable.value,\n ]\n\n if current.deployment_settings.has_module(\"hrm\"):\n htable = s3db.hrm_human_resource\n left.append(htable.on(htable.person_id == ptable.id))\n fields.append(htable.type)\n\n rows = current.db(query).select(left = left,\n limitby = (0, count),\n *fields)\n self.queries += 1\n return rows\n\n # -------------------------------------------------------------------------\n def represent_row(self, row):\n \"\"\"\n Represent a row\n\n Args:\n row: the Row\n \"\"\"\n\n if not hasattr(row, \"pr_person\"):\n return s3_fullname(row)\n\n person = row.pr_person\n reprstr = s3_fullname(person)\n if hasattr(row, \"pr_contact\"):\n try:\n contact = row.pr_contact.value\n except AttributeError:\n pass\n else:\n if contact:\n reprstr = \"%s %s\" % (s3_str(reprstr), s3_str(contact))\n\n return reprstr\n\n # -------------------------------------------------------------------------\n def link(self, k, v, row=None):\n \"\"\"\n Represent a (key, value) as hypertext link.\n\n Args:\n k: the key\n v: the representation of the key\n row: the row with this key\n \"\"\"\n\n hr_type = None\n\n if row and hasattr(row, \"hrm_human_resource\"):\n try:\n hr_type = row.hrm_human_resource.type\n except AttributeError:\n pass\n\n if hr_type == 1:\n controller = \"hrm\"\n elif hr_type == 2:\n controller = \"vol\"\n else:\n controller = \"pr\"\n\n return A(v,\n _href=URL(c = controller,\n f = \"person\",\n args = [k, \"contacts\"],\n ),\n )\n\n# =============================================================================\nclass req_ReqItemRepresent(S3Represent):\n\n def __init__(self):\n\n super().__init__(lookup = \"req_req_item\",\n )\n\n # -------------------------------------------------------------------------\n def lookup_rows(self, key, values, fields=None):\n \"\"\"\n Custom look-up of rows\n\n Args:\n key: the key field\n values: the values to look up\n fields: unused (retained for API compatibility)\n \"\"\"\n\n ritable = self.table\n sitable = current.s3db.supply_item\n\n count = len(values)\n if count == 1:\n query = (ritable.id == values[0])\n else:\n query = (ritable.id.belongs(values))\n\n left = sitable.on(ritable.item_id == sitable.id)\n rows = current.db(query).select(ritable.id,\n sitable.name,\n left = left,\n limitby = (0, count)\n )\n self.queries += 1\n return rows\n\n # -------------------------------------------------------------------------\n def represent_row(self, row):\n \"\"\"\n Represent a row\n\n Args:\n row: the Row\n \"\"\"\n\n if not hasattr(row, \"supply_item\"):\n return str(row.id)\n\n return row.supply_item.name\n\n# =============================================================================\nclass req_CommitRepresent(S3Represent):\n \"\"\"\n Represent a commit\n \"\"\"\n\n def __init__(self):\n\n super().__init__(lookup = \"req_commit\",\n )\n\n # -------------------------------------------------------------------------\n def lookup_rows(self, key, values, fields=None):\n \"\"\"\n Custom look-up of rows\n\n Args:\n key: the key field\n values: the values to look up\n fields: unused (retained for API compatibility)\n \"\"\"\n\n table = self.table\n\n count = len(values)\n if count == 1:\n query = (table.id == values[0])\n else:\n query = (table.id.belongs(values))\n\n rows = current.db(query).select(table.id,\n table.type,\n table.date,\n table.organisation_id,\n table.site_id,\n limitby = (0, count)\n )\n self.queries += 1\n\n # Collect site_ids/organisation_ids after commit type\n organisation_ids = set()\n site_ids = set()\n for row in rows:\n if row.type == 1:\n site_ids.add(row.site_id)\n else:\n organisation_ids.add(row.organisation_id)\n\n # Bulk-represent site_ids\n if site_ids:\n represent = table.site_id.represent\n if represent and hasattr(represent, \"bulk\"):\n represent.bulk(list(site_ids))\n\n # Bulk-represent organisation_ids\n if organisation_ids:\n represent = table.organisation_id.represent\n if represent and hasattr(represent, \"bulk\"):\n represent.bulk(list(organisation_ids))\n\n return rows\n\n # -------------------------------------------------------------------------\n def represent_row(self, row):\n \"\"\"\n Represent a row\n\n Args:\n row: the Row\n \"\"\"\n\n table = self.table\n\n try:\n commit_type = row.type\n except AttributeError:\n # Unknown commit type => assume \"other\"\n commit_type = None\n\n # Determine the committer field and id after commit type\n if commit_type == 1:\n field = table.site_id\n committer_id = row.site_id\n else:\n field = table.organisation_id\n committer_id = row.organisation_id\n\n # Represent the committer (site or org)\n if committer_id and field.represent:\n committer = field.represent(committer_id)\n else:\n committer = None\n\n # Represent the commit date\n if row.date:\n daterepr = table.date.represent(row.date)\n else:\n daterepr = T(\"undated\")\n\n # Combine committer/date as available\n if committer:\n if isinstance(committer, DIV):\n reprstr = TAG[\"\"](committer, \" - \", daterepr)\n else:\n reprstr = \"%s - %s\" % (committer, daterepr)\n else:\n reprstr = daterepr\n\n return reprstr\n\n# =============================================================================\ndef req_job_reset(r, **attr):\n \"\"\"\n Reset a job status from FAILED to QUEUED (custom REST method),\n for \"Reset\" action button\n \"\"\"\n\n if r.interactive:\n if r.component and r.component.alias == \"job\":\n job_id = r.component_id\n if job_id:\n S3Task.reset(job_id)\n current.session.confirmation = current.T(\"Job reactivated\")\n\n redirect(r.url(method=\"\", component_id=0))\n\n# =============================================================================\ndef req_job_run(r, **attr):\n \"\"\"\n Run a job now (custom REST method),\n for \"Run Now\" action button\n \"\"\"\n\n if r.interactive:\n if r.id:\n current.s3task.run_async(\"req_add_from_template\",\n [r.id], # args\n {\"user_id\":current.auth.user.id} # vars\n )\n current.session.confirmation = current.T(\"Request added\")\n\n redirect(r.url(method=\"\", component_id=0))\n\n# =============================================================================\ndef req_add_from_template(req_id):\n \"\"\"\n Add a Request from a Template (scheduled function to create\n recurring requests)\n\n Args:\n req_id: record ID of the request template\n \"\"\"\n\n fieldnames = [\"type\",\n \"priority\",\n \"site_id\",\n \"purpose\",\n \"requester_id\",\n \"comments\",\n ]\n db = current.db\n s3db = current.s3db\n table = s3db.req_req\n fields = [table[field] for field in fieldnames]\n\n # Load Template\n template = db(table.id == req_id).select(limitby = (0, 1),\n *fields\n ).first()\n data = {\"is_template\": False}\n try:\n for field in fieldnames:\n data[field] = template[field]\n except TypeError as e:\n raise RuntimeError(\"Template not found: %s\" % req_id) from e\n\n settings = current.deployment_settings\n if settings.get_req_use_req_number():\n code = s3db.supply_get_shipping_code(settings.get_req_shortname(),\n template.site_id,\n table.req_ref,\n )\n data[\"req_ref\"] = code\n\n new_req_id = table.insert(**data)\n\n if template.type == 1:\n # Copy across req_item\n table = s3db.req_req_item\n fieldnames = [\"site_id\",\n \"item_id\",\n \"item_pack_id\",\n \"quantity\",\n \"pack_value\",\n \"currency\",\n \"comments\",\n ]\n fields = [table[field] for field in fieldnames]\n items = db(table.req_id == req_id).select(*fields)\n for item in items:\n data = {\"req_id\": new_req_id}\n for field in fieldnames:\n data[field] = item[field]\n table.insert(**data)\n\n elif template.type == 3:\n # Copy across req_skill\n table = s3db.req_req_skill\n fieldnames = [\"site_id\",\n \"task\",\n \"skill_id\",\n \"quantity\",\n \"comments\",\n ]\n fields = [table[field] for field in fieldnames]\n skills = db(table.req_id == req_id).select(*fields)\n for skill in skills:\n data = {\"req_id\": new_req_id}\n for field in fieldnames:\n data[field] = skill[field]\n table.insert(**data)\n\n return new_req_id\n\n# =============================================================================\ndef req_is_approver(site_id):\n \"\"\"\n Check if User has permission to Approve a Request\n \"\"\"\n\n auth = current.auth\n\n # Will cause issues\n #if auth.s3_has_role(\"ADMIN\"):\n # return True\n\n db = current.db\n s3db = current.s3db\n atable = s3db.req_approver\n query = (atable.person_id == auth.s3_logged_in_person()) & \\\n (atable.deleted == False)\n entities = db(query).select(atable.pe_id)\n if not entities:\n # Not an Approver for any\n return False\n\n pe_ids = [row.pe_id for row in entities]\n\n stable = s3db.org_site\n site_entity = db(stable.site_id == site_id).select(stable.instance_type,\n limitby = (0, 1)\n ).first()\n itable = s3db.table(site_entity.instance_type)\n site = db(itable.site_id == site_id).select(itable.pe_id,\n limitby = (0, 1)\n ).first()\n\n pe_id = site.pe_id\n if pe_id in pe_ids:\n # Directly permitted\n return True\n\n # Check for child entities\n entity_types = [\"org_organisation\"] + list(auth.org_site_types.keys())\n child_pe_ids = s3db.pr_get_descendants(pe_ids, entity_types=entity_types)\n if pe_id in child_pe_ids:\n # Permitted via child entity\n return True\n\n return False\n\n# =============================================================================\ndef req_approvers(site_id):\n \"\"\"\n Return people permitted to Approve a Request\n \"\"\"\n\n db = current.db\n s3db = current.s3db\n\n stable = s3db.org_site\n site_entity = db(stable.site_id == site_id).select(stable.instance_type,\n limitby = (0, 1)\n ).first()\n itable = s3db.table(site_entity.instance_type)\n site = db(itable.site_id == site_id).select(itable.pe_id,\n limitby = (0, 1)\n ).first()\n\n pe_id = site.pe_id\n entities = s3db.pr_get_ancestors(pe_id)\n entities.append(pe_id)\n\n atable = s3db.req_approver\n query = (atable.pe_id.belongs(entities)) & \\\n (atable.deleted == False)\n approvers = db(query).select(atable.person_id,\n atable.title,\n atable.matcher,\n )\n\n return {row.person_id: {\"title\": row.title,\n \"matcher\": row.matcher,\n } for row in approvers}\n\n# =============================================================================\ndef req_create_form_mods():\n \"\"\"\n Function to be called from REST prep functions\n - main module & components (sites & events)\n \"\"\"\n\n T = current.T\n db = current.db\n s3 = current.response.s3\n settings = current.deployment_settings\n\n table = db.req_req\n\n if not settings.get_req_inline_forms():\n # Amend the Save button\n default_type = table.type.default\n if default_type:\n req_submit_button = {1: T(\"Save and add Items\"),\n 3: T(\"Save and add People\"),\n 9: T(\"Save\"),\n }\n s3.crud.submit_button = req_submit_button[default_type]\n\n # Hide fields which don't make sense in a Create form\n table.req_ref.readable = False\n table.commit_status.readable = table.commit_status.writable = False\n table.transit_status.readable = table.transit_status.writable = False\n table.fulfil_status.readable = table.fulfil_status.writable = False\n table.workflow_status.readable = table.workflow_status.writable = False\n table.cancel.readable = table.cancel.writable = False\n table.closed.readable = table.closed.writable = False\n table.date_recv.readable = table.date_recv.writable = False\n table.recv_by_id.readable = table.recv_by_id.writable = False\n\n if settings.get_req_requester_from_site():\n # Filter the list of Contacts to those for the site\n table.requester_id.widget = None\n table.requester_id.comment = S3PopupLink(c = \"pr\",\n f = \"person\",\n vars = {\"child\": \"requester_id\",\n \"parent\": \"req\",\n },\n title = s3.crud_strings[\"pr_person\"].label_create,\n )\n s3.jquery_ready.append('''\n$.filterOptionsS3({\n'trigger':'site_id',\n'target':'requester_id',\n'lookupResource':'staff',\n'lookupURL':S3.Ap.concat('/hrm/staff_for_site/'),\n'msgNoRecords':'%s',\n'optional':true,\n})''' % T(\"No contacts yet defined for this site\"))\n #table.site_id.comment = A(T(\"Set as default Site\"),\n # _id=\"req_req_site_id_link\",\n # _target=\"_blank\",\n # _href=URL(c=\"default\",\n # f=\"user\",\n # args=[\"profile\"]))\n\n req_types = settings.get_req_req_type()\n if \"People\" in req_types:\n # Show the Required Until Field\n # (gets turned-off by JS for other types)\n table.date_required_until.writable = True\n\n request = current.request\n if \"type\" not in request.get_vars:\n # Script to inject into Pages which include Request create forms\n req_helptext = '''\ni18n.req_purpose=\"%s\"\ni18n.req_site_id=\"%s\"\ni18n.req_request_for_id=\"%s\"\ni18n.req_recv_by_id=\"%s\"\ni18n.req_items_purpose=\"%s\"\ni18n.req_items_site_id=\"%s\"\ni18n.req_items_recv_by_id=\"%s\"\ni18n.req_people_purpose=\"%s\"\ni18n.req_people_site_id=\"%s\"\ni18n.req_people_recv_by_id=\"%s\"\ni18n.req_next_msg=\"%s\"\ni18n.req_other_msg=\"%s\"\ni18n.req_details_mandatory=\"%s\"''' % (table.purpose.label,\n table.site_id.label,\n table.request_for_id.label,\n table.recv_by_id.label,\n T(\"What the Items will be used for\"),\n T(\"Deliver To\"),\n T(\"Delivered To\"),\n T(\"Task Details\"),\n T(\"Report To\"),\n T(\"Reported To\"),\n T(\"Please enter the details on the next screen.\"),\n T(\"Please enter request details here.\"),\n T(\"Details field is required!\"))\n s3.js_global.append(req_helptext)\n s3.scripts.append(\"/%s/static/scripts/S3/s3.req_create_variable.js\" % request.application)\n\n else:\n s3.scripts.append(\"/%s/static/scripts/S3/s3.req_create.js\" % request.application)\n\n# =============================================================================\ndef req_hide_quantities(table):\n \"\"\"\n Hide per-status quantity fields in Request create-forms\n\n Args:\n table: the Table (req_item or req_skill)\n \"\"\"\n\n if not current.deployment_settings.get_req_item_quantities_writable():\n table.quantity_commit.readable = \\\n table.quantity_commit.writable = False\n table.quantity_transit.readable = \\\n table.quantity_transit.writable = False\n table.quantity_fulfil.readable = \\\n table.quantity_fulfil.writable = False\n\n# =============================================================================\ndef req_inline_form(req_type, method):\n \"\"\"\n Function to be called from REST prep functions\n - to add req_item & req_skill components as inline forms\n\n Args:\n req_type: the request type (1=items, 3=skills)\n method: the URL request method\n \"\"\"\n\n T = current.T\n s3db = current.s3db\n table = s3db.req_req\n s3 = current.response.s3\n postprocess = s3.req_req_postprocess\n\n if req_type == 1:\n\n # Custom Form\n settings = current.deployment_settings\n fields = [#req_ref\n \"site_id\",\n #is_template\n \"requester_id\",\n \"date\",\n \"priority\",\n \"date_required\",\n S3SQLInlineComponent(\n \"req_item\",\n label = T(\"Items\"),\n fields = [\"item_id\",\n \"item_pack_id\",\n \"quantity\",\n \"comments\"\n ]\n ),\n #purpose\n \"comments\",\n ]\n\n if method in (\"create\", \"update\"):\n # Dropdown not Autocomplete\n itable = s3db.req_req_item\n itable.item_id.widget = None\n\n # Options-filter item=>pack\n jquery_ready = s3.jquery_ready\n jquery_ready.append('''\n$.filterOptionsS3({\n'trigger':{'alias':'req_item','name':'item_id'},\n'target':{'alias':'req_item','name':'item_pack_id'},\n'scope':'row',\n'lookupPrefix':'supply',\n'lookupResource':'item_pack',\n'msgNoRecords':i18n.no_packs,\n'fncPrep':S3.supply.fncPrepItem,\n'fncRepresent':S3.supply.fncRepresentItem\n})''')\n if settings.get_req_requester_from_site():\n # Filter the list of Contacts to those for the site\n jquery_ready.append('''\n$.filterOptionsS3({\n'trigger':'site_id',\n'target':'requester_id',\n'lookupResource':'staff',\n'lookupURL':S3.Ap.concat('/hrm/staff_for_site/'),\n'msgNoRecords':'%s',\n'optional':true,\n})''' % T(\"No contacts yet defined for this site\"))\n\n # Popup link to allow adding a contact (...for the site)\n table.requester_id.widget = None\n table.requester_id.comment = S3PopupLink(c = \"pr\",\n f = \"person\",\n vars = {\"child\": \"requester_id\",\n \"parent\": \"req\",\n },\n title = s3.crud_strings[\"pr_person\"].label_create,\n )\n\n # Link to user profile to allow setting this site\n # as their current default site, so that they appear\n # in the dropdown themselves\n table.site_id.comment = A(T(\"Set as default Site\"),\n _id = \"req_req_site_id_link\",\n _target = \"_blank\",\n _href = URL(c = \"default\",\n f = \"user\",\n args = [\"profile\"],\n ),\n )\n\n if method in (\"update\", \"read\"):\n # Append status details\n status_fields = []\n if settings.get_req_status_writable():\n if settings.get_req_use_commit():\n status_fields.append(\"commit_status\")\n if settings.get_req_show_quantity_transit():\n status_fields.append(\"transit_status\")\n status_fields.append(\"fulfil_status\")\n status_fields.append(\"date_recv\")\n\n fields.extend(status_fields)\n\n # Show request number?\n if settings.get_req_use_req_number():\n if settings.get_req_generate_req_number():\n table.req_ref.writable = False\n fields.insert(0, \"req_ref\")\n else:\n # Is-template flag can only be set during create\n fields.insert(1, \"is_template\")\n\n if settings.get_req_items_ask_purpose():\n fields.insert(-1, \"purpose\")\n\n if postprocess:\n crud_form = S3SQLCustomForm(*fields, postprocess=postprocess)\n else:\n crud_form = S3SQLCustomForm(*fields)\n s3db.configure(\"req_req\",\n crud_form = crud_form,\n )\n\n elif req_type == 3:\n # Custom Form\n stable = s3db.req_req_skill\n stable.skill_id.label = T(\"Required Skills (optional)\")\n # Custom Form\n settings = current.deployment_settings\n fields = [\"site_id\",\n \"requester_id\",\n \"date\",\n \"priority\",\n \"date_required\",\n \"date_required_until\",\n \"purpose\",\n S3SQLInlineComponent(\n \"req_skill\",\n label = T(\"Skills\"),\n fields = [\"quantity\",\n \"skill_id\",\n \"comments\"\n ]\n ),\n \"comments\",\n ]\n if method == \"update\":\n if settings.get_req_status_writable():\n fields.insert(8, \"fulfil_status\")\n if settings.get_req_show_quantity_transit():\n fields.insert(8, \"transit_status\")\n if settings.get_req_use_commit():\n fields.insert(8, \"commit_status\")\n fields.insert(8, \"date_recv\")\n\n if settings.get_req_requester_from_site():\n # Filter the list of Contacts to those for the site\n table.requester_id.widget = None\n table.requester_id.comment = S3PopupLink(c = \"pr\",\n f = \"person\",\n vars = {\"child\": \"requester_id\",\n \"parent\": \"req\",\n },\n title = s3.crud_strings[\"pr_person\"].label_create,\n )\n s3.jquery_ready.append('''\n$.filterOptionsS3({\n'trigger':'site_id',\n'target':'requester_id',\n'lookupResource':'staff',\n'lookupURL':S3.Ap.concat('/hrm/staff_for_site/'),\n'msgNoRecords':'%s',\n'optional':true,\n})''' % T(\"No contacts yet defined for this site\"))\n table.site_id.comment = A(T(\"Set as default Site\"),\n _id = \"req_req_site_id_link\",\n _target = \"_blank\",\n _href = URL(c=\"default\",\n f=\"user\",\n args = [\"profile\"],\n ),\n )\n\n else:\n fields.insert(1, \"is_template\")\n if settings.get_req_use_req_number() and \\\n not settings.get_req_generate_req_number():\n fields.insert(0, \"req_ref\")\n if postprocess:\n crud_form = S3SQLCustomForm(*fields, postprocess=postprocess)\n else:\n crud_form = S3SQLCustomForm(*fields)\n s3db.configure(\"req_req\",\n crud_form = crud_form,\n )\n\n # Reset to standard submit button\n s3.crud.submit_button = T(\"Save\")\n\n# END =========================================================================\n","sub_path":"modules/s3db/req.py","file_name":"req.py","file_ext":"py","file_size_in_byte":258024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"197224104","text":"import xarray as xr\nimport numpy as np\nfrom typing import List, Tuple\nimport dask.array as da\nimport dask\nimport pandas as pd\nfrom scipy import linalg\nfrom tqdm import tqdm\nfrom .locus import (\n test_snp_het,\n test_snp_assoc,\n marginal_het,\n calc_cov,\n calc_apa_cov,\n simulate_hetero_assoc,\n)\nfrom .utils import simulate_quant_pheno, af_per_anc, allele_per_anc, hdi\nfrom admix.data import calc_snp_prior_var\n\n\ndef compute_grm(geno, lanc, n_anc=2, snp_prior_var=None, apa_center=False):\n \"\"\"Calculate ancestry specific GRM matrix\n\n Parameters\n ----------\n center: bool\n whether to center the `allele_per_ancestry` matrix\n in the calculation\n inplace: bool\n whether to return a new dataset or modify the input dataset\n\n Returns\n -------\n If `inplace` is False, return a dictionary of GRM matrices\n - K1: np.ndarray\n ancestry specific GRM matrix for the 1st ancestry\n - K2: np.ndarray\n ancestry specific GRM matrix for the 2nd ancestry\n - K12: np.ndarray\n ancestry specific GRM matrix for cross term of the 1st and 2nd ancestry\n \"\"\"\n\n assert n_anc == 2, \"only two-way admixture is implemented\"\n assert np.all(geno.shape == lanc.shape)\n\n apa = allele_per_anc(geno, lanc, center=apa_center)\n n_snp, n_indiv = apa.shape[0:2]\n\n if snp_prior_var is None:\n snp_prior_var = np.ones(n_snp)\n\n K1 = np.zeros([n_indiv, n_indiv])\n K2 = np.zeros([n_indiv, n_indiv])\n K12 = np.zeros([n_indiv, n_indiv])\n\n snp_chunks = apa.chunks[0]\n indices = np.insert(np.cumsum(snp_chunks), 0, 0)\n\n for i in tqdm(range(len(indices) - 1), desc=\"admix_genet_cor.compute_grm\"):\n start, stop = indices[i], indices[i + 1]\n apa_chunk = apa[start:stop, :, :].compute()\n\n # multiply by the prior variance on each SNP\n apa_chunk *= np.sqrt(snp_prior_var[start:stop])[:, None, None]\n a1_chunk, a2_chunk = apa_chunk[:, :, 0], apa_chunk[:, :, 1]\n\n K1 += np.dot(a1_chunk.T, a1_chunk) / sum(snp_prior_var)\n K2 += np.dot(a2_chunk.T, a2_chunk) / sum(snp_prior_var)\n K12 += np.dot(a1_chunk.T, a2_chunk) / sum(snp_prior_var)\n\n return K1, K2, K12\n\n\ndef estimate_genetic_cor(\n A1, A2, pheno: np.ndarray, cov: np.ndarray = None, compute_varcov: bool = False\n):\n \"\"\"Estimate genetic correlation given a dataset, phenotypes, and covariates.\n This is a very specialized function that tailed for estimating the genetic correlation\n for variants in different local ancestry backgrounds.\n\n See details in https://www.nature.com/articles/s41467-020-17576-9#MOESM1\n\n Parameters\n ----------\n dset: xr.Dataset\n Dataset to estimate correlation from.\n pheno: np.ndarray\n Phenotypes to estimate genetic correlation. If a matrix is provided, then each\n column is treated as a separate phenotype.\n cov_cols: list, optional\n List of covariate columns.\n cov_intercept: bool, optional\n Whether to include intercept in covariate matrix.\n \"\"\"\n assert np.all(A1.shape == A2.shape), \"`A1` and `A2` must have the same shape\"\n n_indiv = A1.shape[0]\n\n # build projection matrix from covariate matrix\n if cov is None:\n cov_proj_mat = np.eye(n_indiv)\n else:\n cov_proj_mat = np.eye(n_indiv) - np.linalg.multi_dot(\n [cov, np.linalg.inv(np.dot(cov.T, cov)), cov.T]\n )\n\n if pheno.ndim == 1:\n pheno = pheno.reshape((-1, 1))\n assert pheno.shape[0] == n_indiv\n\n n_pheno = pheno.shape[1]\n\n pheno = np.dot(cov_proj_mat, pheno)\n quad_form_func = lambda x, A: np.dot(np.dot(x.T, A), x)\n\n grm_list = [A1, A2, np.eye(n_indiv)]\n grm_list = [cov_proj_mat @ grm @ cov_proj_mat for grm in grm_list]\n\n # multiply cov_proj_mat\n n_grm = len(grm_list)\n design = np.zeros((n_grm, n_grm))\n for i in range(n_grm):\n for j in range(n_grm):\n if i <= j:\n design[i, j] = (grm_list[i] * grm_list[j]).sum()\n design[j, i] = design[i, j]\n\n rls_list: List[Tuple] = []\n for i_pheno in tqdm(range(n_pheno)):\n response = np.zeros(n_grm)\n for i in range(n_grm):\n response[i] = quad_form_func(pheno[:, i_pheno], grm_list[i])\n\n # point estimate\n var_comp = linalg.solve(\n design,\n response,\n )\n\n if compute_varcov:\n # variance-covariance matrix\n inv_design = linalg.inv(design)\n Sigma = np.zeros_like(grm_list[0])\n for i in range(n_grm):\n Sigma += var_comp[i] * grm_list[i]\n Sigma_grm_list = [np.dot(Sigma, grm) for grm in grm_list]\n\n var_response = np.zeros((n_grm, n_grm))\n for i in range(n_grm):\n for j in range(n_grm):\n if i <= j:\n var_response[i, j] = (\n 2 * (Sigma_grm_list[i] * Sigma_grm_list[j]).sum()\n )\n var_response[j, i] = var_response[i, j]\n var_comp_var = np.linalg.multi_dot([inv_design, var_response, inv_design])\n rls_list.append((var_comp, var_comp_var))\n else:\n rls_list.append(var_comp)\n return rls_list","sub_path":"admix_genet_cor/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"204338944","text":"\"\"\" Contains controlling logic for the epochs implemenation.\n\"\"\"\n\nimport copy\nimport logging\n\nimport numpy as np\nimport mne\n\nfrom meggie.utilities.units import get_scaling\nfrom meggie.utilities.events import find_stim_channel\nfrom meggie.utilities.events import find_events\n\nfrom meggie.datatypes.epochs.epochs import Epochs\n\n\ndef create_epochs_from_events(params, subject):\n \"\"\" Creates epochs based on events.\n \"\"\"\n raw = subject.get_raw()\n\n params = copy.deepcopy(params)\n event_params = params['events']\n reject_params = params['reject']\n\n # convert reject params from human readable units to standard units\n for key in reject_params:\n reject_params[key] /= get_scaling(key)\n\n # remove params that don't match with the channel types present in raw\n if mne.pick_types(raw.info, meg='grad', eeg=False).size == 0:\n reject_params.pop('grad', None)\n if mne.pick_types(raw.info, meg='mag', eeg=False).size == 0:\n reject_params.pop('mag', None)\n if mne.pick_types(raw.info, meg=False, eeg=True).size == 0:\n reject_params.pop('eeg', None)\n\n events = []\n category = {}\n\n stim_channel = find_stim_channel(raw)\n\n # event_id should not matter after epochs are created,\n # so we just add placeholders as 1, 2, 3...\n if len(event_params) > 0:\n for idx, item in enumerate(event_params):\n event_id = item['event_id']\n mask = item['mask']\n category_id = (\n 'id_' + str(event_id) + '_mask_' + str(mask))\n\n new_events = find_events(raw, stim_channel, mask, event_id)\n\n if len(new_events) == 0:\n logging.warning('No events found with setting ' +\n str(category_id))\n continue\n\n category[category_id] = idx + 1\n new_events[:, 2] = idx + 1\n\n events.extend([[event[0] + int(round(raw.info['sfreq']*params['delay'])), \n event[1], event[2]] \n for event in new_events])\n\n if len(events) == 0:\n raise ValueError(\n 'No matching events found. Please check rejection limits and other parameters.')\n\n # prepare parameters for pick_types\n if params['mag'] and params['grad']:\n meg = True\n elif params['mag']:\n meg = 'mag'\n elif params['grad']:\n meg = 'grad'\n else:\n meg = False\n\n eeg = params['eeg']\n\n # find all proper picks, dont exclude bads\n picks = mne.pick_types(raw.info, meg=meg, eeg=eeg, exclude=[])\n\n if len(picks) == 0:\n raise ValueError('You should select at least one channel type')\n\n mne_epochs = mne.Epochs(raw, np.array(events),\n category, params['tmin'], params['tmax'],\n baseline=(params['bstart'], params['bend']),\n picks=picks, reject=reject_params)\n\n if len(mne_epochs.get_data()) == 0:\n raise ValueError('Could not find any data. Perhaps the ' +\n 'rejection thresholds are too strict...')\n\n n_dropped = len(events) - len(mne_epochs.get_data())\n\n if n_dropped > 0:\n logging.getLogger('ui_logger').info(str(n_dropped) + ' epochs dropped.')\n\n epochs_directory = subject.epochs_directory\n epochs = Epochs(params['collection_name'],\n epochs_directory,\n params,\n content=mne_epochs)\n\n epochs.save_content()\n subject.add(epochs, 'epochs')\n\n","sub_path":"meggie/tabs/epochs/controller/epoching.py","file_name":"epoching.py","file_ext":"py","file_size_in_byte":3515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"403586177","text":"from datetime import datetime, timedelta\n\n\nclass Scheduler:\n\n def __init__(self):\n self.Schedule = []\n\n def add(self, func, param, time):\n \"\"\"\n Schedule a Method\n \"\"\"\n # Time => (Hours, Minutes, Seconds)\n Delta = timedelta(hours=time[0], minutes=time[1], seconds=time[2])\n self.Schedule.append((func, param, datetime.now() + Delta))\n self.Schedule.sort(key=lambda x: x[2])\n\n def nextTask(self):\n \"\"\"\n Return next scheduled task and remove it from schedule.\n \"\"\"\n if len(self.Schedule) == 0:\n return None\n elif datetime.now() >= self.Schedule[0][2]:\n task = self.Schedule[0][0]\n param = self.Schedule[0][1]\n self.Schedule.pop(0)\n return (task, param)\n else:\n return None\n\n def isScheduled(self, *tasks):\n \"\"\"\n Checks if a task is currently scheduled.\n It is meant to help control to schedule tasks\n \"\"\"\n taskScheduled = [Event[0] for Event in self.Schedule]\n return any([(task in taskScheduled) for task in tasks])\n","sub_path":"ProdScheduler.py","file_name":"ProdScheduler.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"49737237","text":"\"\"\" File: fug.py\n Author: Abraham Aruguete\n Purpose: To create a grid drawing such that it emulates pixels on a screen\n or something. Graphics. Woo.\n\"\"\"\nimport sys\n\n\ndef terminal():\n \"\"\" This is a function which takes in the user input, and then checks it\n among a list of valid terminal commands. \"\"\"\n #current grid for most of the functions\n currentGrid = []\n commandList = []\n init_Flag = False\n for line in sys.stdin:\n if line == \"\":\n print(\"Input error: Empty File\")\n sys.exit()\n if line.lstrip().startswith(\"#\"):\n continue\n line = line.strip()\n try:\n if (\"init\" in line) and (init_Flag == False):\n commandList = line.split()\n commandList[1] = int(commandList[1])\n commandList[2] = int(commandList[2])\n #TODO: the actual commands within the command list\n currentGrid = init(commandList[1], commandList[2])\n init_Flag = True\n continue\n elif (\"print_raw\" in line) and (init_Flag == True):\n print(currentGrid)\n continue\n elif (\"print\" in line) and (init_Flag == True):\n print_interpreted(currentGrid)\n continue\n elif (\"set\" in line) and (init_Flag == True):\n commandList = line.split()\n commandList[1] = int(commandList[1])\n commandList[2] = int(commandList[2])\n commandList[3] = int(commandList[3])\n currentGrid = set_color(commandList[1], \\\n commandList[2], commandList[3], currentGrid)\n continue\n elif (\"horiz_line\" in line) and (init_Flag == True):\n commandList = line.split()\n commandList[1] = int(commandList[1])\n commandList[2] = int(commandList[2])\n commandList[3] = int(commandList[3])\n commandList[4] = int(commandList[4])\n commandList[5] = int(commandList[5])\n currentGrid = horiz_line(commandList[1], commandList[2], \\\n commandList[3], commandList[4], commandList[5], currentGrid)\n continue\n elif (\"vert_line\" in line) and (init_Flag == True):\n commandList = line.split()\n commandList[1] = int(commandList[1])\n commandList[2] = int(commandList[2])\n commandList[3] = int(commandList[3])\n commandList[4] = int(commandList[4])\n commandList[5] = int(commandList[5])\n currentGrid = vert_line(commandList[1], commandList[2],\\\n commandList[3], commandList[4], commandList[5], currentGrid)\n continue\n elif (\"filled_rect\" in line) and (init_Flag == True):\n commandList = line.split()\n commandList[1] = int(commandList[1])\n commandList[2] = int(commandList[2])\n commandList[3] = int(commandList[3])\n commandList[4] = int(commandList[4])\n commandList[5] = int(commandList[5])\n currentGrid = filled_rectangle(commandList[1], commandList[2],\\\n commandList[3], commandList[4], commandList[5], currentGrid)\n continue\n elif (\"hollow_rect\" in line) and (init_Flag == True):\n commandList = line.split()\n commandList[1] = int(commandList[1])\n commandList[2] = int(commandList[2])\n commandList[3] = int(commandList[3])\n commandList[4] = int(commandList[4])\n commandList[5] = int(commandList[5])\n currentGrid = hollow_rectangle(commandList[1], commandList[2], \\\n commandList[3], commandList[4], commandList[5], currentGrid)\n continue\n elif (\"init\" in line) and (init_Flag == True):\n print(\"Input error: init already used. Closing...\")\n sys.exit()\n else:\n print(\"Input error: Invalid command.\")\n continue\n except ValueError:\n print(\"Input error: Generic.\")\n continue\n\ndef init(length, height):\n \"\"\"This is a function which initializes the width times length grid we are workin' with\n you know, like fucking hell holy shit a NESTED LOOP!!!!\"\"\"\n grid = []\n for x in range(height):\n grid.append([0]*length)\n return grid\n\ndef print_interpreted(grid_of_stuff):\n \"\"\"This is a function which also does that thing where like you print the grid we're workin'\n with, shoopdawoop etc. Except in reverse order.\"\"\"\n for i in range(len(grid_of_stuff)-1, -1, -1):\n for j in range(len(grid_of_stuff[i])):\n print(grid_of_stuff[i][j], end=\"\")\n print()\n \n#print_raw is implemented in terminal()\n\ndef set_color(color, x, y, grid):\n \"\"\" This is a function which sets the color of a given coordinate on the grid\n to a given color value. NOTE THAT the system is in the coordinate system\n described in the docs, x is the second list index, y is the first\"\"\"\n grid[y][x] = color\n return grid\n\ndef horiz_line(color, x1, x2, y1, y2, grid):\n \"\"\" This again is a function which sets the color of a given line on the grid\n to a given color value. Does some coordinate checks too to make sure everything\n is cash money.\"\"\"\n if y1 == y2:\n if x1 <= x2:\n for xpos in range(x1, x2):\n grid[y1][xpos] = color\n return grid\n else:\n print(\"Input error: Incorrect parameters to horizontal line.\")\n return grid\n else:\n print(\"Input error: Incorrect parameters to horizontal line.\")\n return grid\n \ndef vert_line(color, x1, x2, y1, y2, grid):\n \"\"\"Does the same thing as the above function, but with a vertical line instead.\"\"\"\n if x1 == x2:\n if y1 <= y2:\n for ypos in range(y1-1, y2):\n grid[ypos][x1] = color\n return grid\n else:\n print(\"Input error: Incorrect parameters to vertical line.\")\n return grid\n else:\n print(\"Input error: Incorrect parameters to vertical line.\")\n return grid\n\n \ndef filled_rectangle(color, x1, y1, x2, y2, grid):\n \"\"\" This draws a rectangle of the specified color on the grid, by doing a box\n from the first corner x1, y1 to x2, y2 with the color specified in the\n parameters. \"\"\"\n if x1 <= x2:\n if y1 <= y2:\n for ypos in range(y1-1, y2):\n for xpos in range(x1-1, x2):\n grid[len(grid) - ypos][xpos] = color\n return grid\n else:\n print(\"Input error: Incorrect parameters to filled rectangle.\")\n return grid\n else:\n print(\"Input error: Incorrect parameters to filled rectangle.\")\n return grid\n\n\n\ndef hollow_rectangle(color, x1, y1, x2, y2, grid):\n \"\"\" This draws a hollow rectangle of the specified color on the grid, by doing\n a hollow box from the first corner x1 to the second color x2 and so on and\n so forth. \"\"\"\n if x1 <= x2:\n if y1 <= y2:\n grid = horiz_line(color, x1, x2, y1, y1, grid)\n grid = horiz_line(color, x1, x2, y2, y2, grid)\n grid = vert_line(color, x1-1, x1-1, y1+1, y2+1, grid)\n grid = vert_line(color, x2-1, x2-1, y1+1, y2+1, grid)\n return grid\n else:\n print(\"Input error: Incorrect parameters to hollow rectangle.\")\n return grid\n else:\n print(\"Input error: Incorrect parameters to hollow rectangle.\")\n return grid\n\ndef main():\n terminal()\n\nmain()\n","sub_path":"fug.py","file_name":"fug.py","file_ext":"py","file_size_in_byte":7912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"106918520","text":"import sys\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5 import uic\r\nimport csv\r\nfrom pandas import Series, DataFrame\r\nimport pandas as pd\r\n\r\nform_class = uic.loadUiType(\"main_window.ui\")[0]\r\n\r\n\r\nclass MyWindow(QMainWindow, form_class):\r\n def __init__(self):\r\n super().__init__()\r\n self.setupUi(self)\r\n self.searchBtn.clicked.connect(self.btn_clicked)\r\n self.resultWidget(self)\r\n\r\n # def setupUi(self):\r\n # self.resultWidget = QTableWidget(self)\r\n #\r\n # self.result.setRowCount(3)\r\n # self.result.setColumnCount(3)\r\n # self.result.setTableWidgetData()\r\n\r\n def btn_clicked(self):\r\n user_input = self.stockEdit.text()\r\n search_result = stock_search(user_input)\r\n # self.resultWidget.setItem(0,0,\"1\")\r\n self.resultWidget.setRowCount(len(search_result))\r\n for row in range(len(search_result)):\r\n for col in range(3):\r\n self.resultWidget.setItem(row, col, QTableWidgetItem(search_result[row][col]))\r\n\r\n\r\ndef stock_search(code):\r\n nyse = pd.read_csv('NYSE_20171204.txt')\r\n nyse = nyse.drop(['', '', '', '', '', ''], axis=1)\r\n nyse[''] = 'US'\r\n nyse = DataFrame(nyse, columns=['', '', ''])\r\n\r\n nasdaq = pd.read_csv('NASDAQ_20171204.txt')\r\n nasdaq = nasdaq.drop(['', '', '', '', '', ''], axis=1)\r\n nasdaq[''] = 'US'\r\n nasdaq = DataFrame(nasdaq, columns=['', '', ''])\r\n\r\n us = pd.concat([nyse, nasdaq])\r\n\r\n result = pd.concat(\r\n [DataFrame(us[us[''].str.contains(code)]), DataFrame(us[us[''].str.contains(code)])])\r\n result = result.drop_duplicates(['', ''], keep='first')\r\n return result\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app = QApplication(sys.argv)\r\n myWindow = MyWindow()\r\n myWindow.show()\r\n app.exec_()\r\n","sub_path":"글로벌 뉴스/Favorite_Stock.py","file_name":"Favorite_Stock.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"89712553","text":"import os\nimport io\nimport math\nimport json\nimport base64\nimport typing\nimport hashlib\nimport warnings\nimport itertools\nimport subprocess\nfrom urllib import request\nfrom http import client\n\nimport numpy as np\nimport validators\nimport cv2\n\ntry:\n import PIL\n import PIL.Image\nexcept ImportError: # pragma: no cover\n PIL = None\n\nImageInputType = typing.Union[str, np.ndarray, 'PIL.Image.Image', io.BytesIO]\n\nSIZES = {'float32': 32, 'uint8': 8, 'bool': 1}\n\n\n# pylint: disable=invalid-name\ndef compute_quality(image):\n \"\"\"Compute a quality metric, using the calculation proposed by\n `Facebook `_\n for their PDQ hash algorithm.\"\"\"\n if len(image.shape) == 3:\n image = cv2.cvtColor(image, code=cv2.COLOR_RGB2GRAY)\n if image.shape[0] != 64 or image.shape[1] != 64:\n image = cv2.resize(src=image, dsize=(64, 64)).astype('float32')\n dx = 100 * np.abs(image[:, 1:] - image[:, :-1]) / 255\n dy = 100 * np.abs(image[1:] - image[:-1]) / 255\n dx = dx.astype('int').sum()\n dy = dy.astype('int').sum()\n return np.clip(a=int((dx + dy) / 90), a_min=0, a_max=100)\n\n\ndef compute_md5(filepath) -> str:\n \"\"\"Compute the md5 hash for a file at `filepath`.\n\n Args:\n filepath: The path to the file\n \"\"\"\n with open(filepath, 'rb') as f: # pylint: disable=invalid-name\n hash_str = hashlib.md5(f.read()).hexdigest()\n return hash_str\n\n\ndef get_string_length(hash_length: int, dtype: str, hash_format='hex') -> int:\n \"\"\"Compute the expected length of a hash string.\n\n Args:\n hash_length: The length of the hash vector\n dtype: The dtype of the vector\n hash_format: One of 'base64' or 'hex'\n\n Returns:\n The expected string length\n \"\"\"\n hash_bytes = math.ceil(hash_length * SIZES[dtype] / 8)\n\n if hash_format == 'base64':\n return int((4 * hash_bytes / 3) + 3) & ~3\n if hash_format == 'hex':\n return 2 * hash_bytes\n raise NotImplementedError('Unknown hash format: ' + hash_format)\n\n\ndef vector_to_string(vector: np.ndarray, dtype: str, hash_format: str):\n \"\"\"Convert vector to hash.\n\n Args:\n vector: Input vector\n \"\"\"\n if dtype == 'uint8':\n vector_bytes = vector.astype('uint8')\n elif dtype == 'float32':\n vector_bytes = vector.astype('float32')\n elif dtype == 'bool':\n vector_bytes = np.packbits(vector.astype('bool'))\n else:\n raise NotImplementedError(f'Cannot convert hash of type {dtype}.')\n if hash_format == 'base64':\n return base64.b64encode(vector_bytes).decode('utf-8')\n if hash_format == 'hex':\n return vector_bytes.tobytes().hex()\n raise NotImplementedError(\n f'Cannot convert to string format: {hash_format}.')\n\n\ndef string_to_vector(hash_string: str,\n dtype: str,\n hash_length: int,\n hash_format: str,\n verify_length: bool = True):\n \"\"\"Convert hash back to vector.\n\n Args:\n hash_string: The input base64 hash string\n dtype: The data type of the hash\n hash_length: The length of the hash vector\n verify_length: Whether to verify the string length\n \"\"\"\n assert not verify_length or len(hash_string) == get_string_length(\n hash_length=hash_length, hash_format=hash_format,\n dtype=dtype), 'Incorrect string length for this hash format.'\n if hash_format == 'base64':\n vector_bytes = np.frombuffer(\n base64.b64decode(hash_string),\n dtype='uint8' if dtype in ['bool', 'uint8'] else dtype)\n elif hash_format == 'hex':\n vector_bytes = np.frombuffer(\n bytearray.fromhex(hash_string),\n dtype='uint8' if dtype in ['bool', 'uint8'] else dtype)\n else:\n raise NotImplementedError(\n f'Cannot convert to string format: {hash_format}')\n if dtype == 'uint8':\n return vector_bytes[:hash_length]\n if dtype == 'float32':\n return vector_bytes[:hash_length]\n if dtype == 'bool':\n return np.unpackbits(vector_bytes)[:hash_length].astype('bool')\n raise NotImplementedError(f'Cannot convert hash of type {dtype}.')\n\n\ndef to_image_array(image: ImageInputType, require_color=True):\n if isinstance(image, np.ndarray):\n assert image.flags['C_CONTIGUOUS'], (\n 'Provided arrays must be contiguous to avoid '\n 'erroneous results when arrays are passed to '\n 'underlying libraries. This can be achieved using'\n 'np.ascontiguousarray(image)')\n assert not require_color or (len(image.shape) == 3\n and image.shape[-1] == 3), (\n 'Provided images must be RGB images.')\n return image\n return read(image)\n\n\ndef get_isometric_transforms(image: ImageInputType, require_color=True):\n image = to_image_array(image, require_color=require_color)\n return dict(\n r0=image,\n fv=np.ascontiguousarray(image[::-1, :]),\n fh=np.ascontiguousarray(image[:, ::-1]),\n r180=np.ascontiguousarray(image[::-1, ::-1]),\n r90=np.ascontiguousarray(image.transpose(1, 0, 2)[::-1, :, :]),\n r90fv=np.ascontiguousarray(image.transpose(1, 0, 2)),\n r90fh=np.ascontiguousarray(image.transpose(1, 0, 2)[::-1, ::-1]),\n r270=np.ascontiguousarray(image.transpose(1, 0, 2)[:, ::-1]))\n\n\ndef get_isometric_dct_transforms(dct: np.ndarray):\n # pylint: disable=invalid-name\n T1 = np.empty_like(dct)\n T1[::2] = 1\n T1[1::2] = -1\n\n # pylint: disable=invalid-name\n T2 = np.empty_like(dct)\n T2[::2, ::2] = 1\n T2[1::2, 1::2] = 1\n T2[::2, 1::2] = -1\n T2[1::2, ::2] = -1\n return dict(\n r0=dct,\n fv=dct * T1,\n fh=dct * T1.T,\n r180=dct * T2,\n r90=dct.T * T1,\n r90fv=dct.T,\n r90fh=dct.T * T2,\n r270=dct.T * T1.T)\n\n\ndef read(filepath_or_buffer: ImageInputType):\n \"\"\"Read a file into an image object\n\n Args:\n filepath_or_buffer: The path to the file or any object\n with a `read` method (such as `io.BytesIO`)\n \"\"\"\n if PIL is not None and isinstance(filepath_or_buffer, PIL.Image.Image):\n return np.array(filepath_or_buffer.convert(\"RGB\"))\n if isinstance(filepath_or_buffer, (io.BytesIO, client.HTTPResponse)):\n image = np.asarray(\n bytearray(filepath_or_buffer.read()), dtype=np.uint8)\n image = cv2.imdecode(image, cv2.IMREAD_UNCHANGED)\n elif (isinstance(filepath_or_buffer, str)\n and validators.url(filepath_or_buffer)):\n return read(request.urlopen(filepath_or_buffer))\n else:\n assert os.path.isfile(filepath_or_buffer), \\\n 'Could not find image at path: ' + filepath_or_buffer\n image = cv2.imread(filepath_or_buffer)\n if image is None:\n raise ValueError(f'An error occurred reading {image}.')\n # We use cvtColor here instead of just ret[..., ::-1]\n # in order to ensure that we provide a contiguous\n # array for later processing. Some hashers use ctypes\n # to pass the array and non-contiguous arrays can lead\n # to erroneous results.\n return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n\ndef _get_frame_types(filepath):\n \"\"\"Get the frame types for the frames in a video.\n\n Args:\n filepath: Path to the target file\n\n Returns:\n A list of dictionaries with pict_type\n (values are 'I', 'P', or 'B') and\n coded_picture_number (which represents the\n frame).\n \"\"\"\n args = [\n 'ffprobe', '-select_streams', 'v', '-i', filepath, '-print_format',\n 'json', '-show_entries', 'frame=pict_type,coded_picture_number'\n ]\n p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, err = p.communicate()\n if p.returncode != 0:\n raise ValueError(\"{out}: {err}\".format(out=str(out), err=str(err)))\n frames = json.loads(out.decode('utf-8'))['frames']\n frames.sort(key=lambda f: f['coded_picture_number'])\n return frames\n\n\ndef _get_keyframes(filepath):\n \"\"\"Get the keyframes for a video.\n\n Args:\n filepath: Path to the target file\n\n Returns:\n A list of frame indexes.\n \"\"\"\n args = [\n 'ffprobe', '-select_streams', 'v', '-i', filepath, '-print_format',\n 'json', '-show_entries', 'frame=pict_type,coded_picture_number'\n ]\n p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, err = p.communicate()\n if p.returncode != 0:\n raise ValueError(\"{out}: {err}\".format(out=str(out), err=str(err)))\n data = json.loads(out.decode('utf-8'))['frames']\n frames = [f['coded_picture_number'] for f in data if f['pict_type'] == 'I']\n frames = list(set(frames))\n frames.sort()\n return frames\n\n\ndef read_video(\n filepath,\n frames_per_second: typing.Optional[typing.Union[str, int]] = None,\n errors='raise'):\n \"\"\"Provides a generator of RGB frames, frame indexes, and timestamps from a\n video. This function requires you to have installed ffmpeg.\n\n Args:\n filepath: Path to the video file\n frames_per_second: How many frames to provide for\n each second of video. If None, all frames\n are provided. If frames_per_second is \"keyframes\",\n we use ffmpeg to select I frames from the video.\n\n Yields:\n (frame, frame_index, timestamp) tuples\n \"\"\"\n # pylint: disable=no-member\n if cv2.__version__ < '4.1.1' and filepath.lower().endswith('gif'):\n warnings.warn(\n message=\n 'Versions of OpenCV < 4.1.1 may read GIF files improperly. Upgrade recommended.'\n )\n cap = cv2.VideoCapture(filepath)\n try:\n n_frames, video_frames_per_second = cap.get(\n cv2.CAP_PROP_FRAME_COUNT), cap.get(cv2.CAP_PROP_FPS)\n if frames_per_second is None:\n frames_per_second = video_frames_per_second\n if frames_per_second == 'keyframes':\n frame_indexes: typing.Union[range, typing.List[int], typing.\n Iterator[int]] = _get_keyframes(\n filepath)\n else:\n if n_frames < 1:\n frame_indexes = itertools.count(\n 0, int(video_frames_per_second // frames_per_second))\n else:\n frame_indexes = range(\n 0, int(n_frames),\n max(1, int(video_frames_per_second // frames_per_second)))\n\n for frame_index in frame_indexes:\n cap.set(cv2.CAP_PROP_POS_FRAMES, frame_index)\n success, frame = cap.read()\n if not success:\n # The video is over or an error has occurred.\n break\n yield cv2.cvtColor(\n frame, cv2.COLOR_BGR2RGB\n ), frame_index, frame_index / video_frames_per_second\n # pylint: disable=broad-except\n except Exception as e:\n if errors == 'raise':\n cap.release()\n raise e\n if errors == 'warn':\n warnings.warn(\n message=\n f'An error occurred while reading {filepath}. Processing may be truncated.'\n )\n cap.release()\n","sub_path":"perception/hashers/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":11313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"390086509","text":"# SVD IMAGE COMPRESS\n\nimport numpy as np\nfrom scipy import linalg as la\nimport matplotlib.pyplot as plt\nimport scipy.misc\n\n# PROBLEM 1\n# function that calculates the compact svd algorithm\ndef svd1(A):\n\tlam, V = la.eig(A.conj().T @ A)\n\tsig = np.sqrt(lam)\n\tsig = sig[np.argsort(sig)[::-1]]\n\tV = V[np.argsort(sig)[::-1]]\n\tr = (sig != 0).sum()\n\tsig1 = sig[:r]\n\tV1 = V[:, :r]\n\tU1 = A @ V1 / sig1\n\treturn U1, sig1, V1.conj().T\n# TEST\nA = np.random.random((10,5))\nU,s,Vh = la.svd(A, full_matrices=False)\nU1, s1, Vh1 = svd1(A)\nprint(U.shape, s.shape, Vh.shape)\nnp.allclose(U1.T @ U1, np.identity(5))\nnp.allclose(U1 @ np.diag(s1) @ Vh1, A)\nnp.linalg.matrix_rank(A) == len(s1)\n\n# PROBLEM 2\n# function that visualizes the svd\ndef svd2(A):\n\tangle = np.linspace(0, 2 * np.pi, 100)\n\tS = np.vstack([np.cos(angle), np.sin(angle)])\n\tE = np.array([[1, 0, 0], [0, 0, 1]])\n\tU, sig, V = la.svd(A)\n\tdiag = np.diag(sig)\n\t# plot\n\tfig, axes = plt.subplots(2, 2, figsize = (10, 8))\n\tdef graph(x):\n\t\treturn x, V @ x, diag @ V @ x, U @ diag @ V @ x\n\tlabels = ['$S$', '$V^HS$', '$\\Sigma V^H S$', '$U \\Sigma V^H S$']\n\tfor ax, p1, p2, l in zip(axes.flatten(), graph(S), graph(E), labels):\n\t\tax.plot(p1[0], p1[1])\n\t\tax.plot(p2[0], p2[1])\n\t\tax.set_title(l, fontsize=16)\n\t\tax.axis('equal')\n\tplt.tight_layout()\n\tplt.show()\n# TEST\nA = np.array([[3, 1], [1, 3]])\nsvd2(A)\n\n# PROBLEM 3\n# function that computes the compact svd and then truncates it\ndef svd3(A, s):\n\tm, n = A.shape\n\tif s > np.linalg.matrix_rank(A):\n\t\traise ValueError('s is greater than number of nonzero singular values of A')\n\telse:\n\t\ti = m * s + s + n * s\n\t\tU, sig, V = la.svd(A)\n\t\tU1 = U[:, :s]\n\t\tsig1 = sig[:s]\n\t\tV1 = V[:s, :]\n\treturn U1 @ np.diag(sig1) @ V1, i\n# TEST\nA = np.random.random((6, 6))\nsvd3(A, 2)\n\n# PROBLEM 4\n# function that computes the compact svd and lowest rank approximation\ndef svd4(A, eps):\n\tU, sig, V = la.svd(A)\n\tif eps < sig.min():\n\t\traise ValueError(\"epsilon value is too small\")\n\telse:\n\t\ts = len(sig[sig > eps])\n\t\tU1 = U[:, :s]\n\t\tsig1 = sig[:s]\n\t\tV1 = V[:s, :]\n\t\treturn U1 @ np.diag(sig1) @ V1\n# TEST\nA = np.random.random((6, 6))\nsvd4(A, 0.2)\n\n# PROBLEM 5\n# function that computes the best rank-s approximation of an image\ndef svd5(file, s):\n\tim = plt.imread(file) / 255\n\tif im.ndim == 3:\n\t\tC = []\n\t\tv_total = 0\n\t\tfor i in range(3):\n\t\t\tcolor = im[:, :, i]\n\t\t\tcolor_s, v = svd3(color, s)\n\t\t\tv_total += v\n\t\t\tcolor_s[color_s < 0] = 0\n\t\t\tcolor_s[color_s > 1] = 1\n\t\t\tC.append(color_s)\n\t\treturn np.dstack(C), v_total\n\telif im.ndim == 2:\n\t\tim_s, v = svd3(im, s)\n\t\tim_s[im_s < 0] = 0\n\t\tim_s[im_s > 1] = 1\n\t\treturn im_s, v\n# TEST\ncompressed_image, v_compressed = svd5('hubble.jpg', 20)\nimage = plt.imread('hubble.jpg') / 255\nfig, axes = plt.subplots(1, 2, figsize=(10, 5))\naxes[0].imshow(image)\naxes[1].imshow(compressed_image)\nplt.suptitle(f'Difference in number of entries = {image.size - v_compressed}')\nplt.show()","sub_path":"ProbSets/Comp/ProbSet3/svd_image_compress/svd_image_compress.py","file_name":"svd_image_compress.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"31173436","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# Específico para a matriz do exercício\ndef build_matrix(ny, nx):\n empty_matrix = np.zeros((ny, nx))\n for i in range (nx):\n for j in range (ny):\n if (i == (ny-1) or j == (nx-1) or j == 0):\n empty_matrix[i][j] = 0\n elif(i == 0):\n empty_matrix[i][j] = 100\n else:\n empty_matrix[i][j]= -1\n return empty_matrix\n\ndef solve_matrix(act_matrix, nx, ny, alpha):\n nxt_matrix = build_matrix(ny, nx)\n for i in range (nx):\n for j in range (ny):\n if (nxt_matrix[i][j] == -1):\n nxt_matrix[i][j] = alpha * 0.01 * ((act_matrix[i+1][j]+act_matrix[i-1][j]-2*act_matrix[i][j])/0.01 + (act_matrix[i][j+1]+act_matrix[i][j-1]-2*act_matrix[i][j])/0.01) + act_matrix[i][j]\n return nxt_matrix\n\n\n\nact_matrix = build_matrix(6, 6) # para 50 cm de 10 em 10 cm\nfor i in range (6):\n for j in range (6):\n if (act_matrix[i][j] == -1):\n act_matrix[i][j] = 0\n \n\nfor qq in range(1000):\n act_matrix = solve_matrix(act_matrix, 6, 6, 0.25)\n \n \n\nplt.imshow(act_matrix)\nplt.colorbar()\nplt.show()","sub_path":"metododasdiferencasfinitas2.py","file_name":"metododasdiferencasfinitas2.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"127717311","text":"from statsmodels.graphics.tsaplots import plot_predict\nfrom statsmodels.tsa.statespace.sarimax import SARIMAX\nfrom statsmodels.tsa.arima.model import ARIMA\nfrom itertools import product\nfrom .plotting import *\nimport warnings\nwarnings.filterwarnings('ignore')\n\ndef ARMA_model(data, ohlc='Close'):\n\n\tdata = data[ohlc]\n\n\t# choose best p, q parameters for our model using AIC optimization\n\tparams = bestParams(data)\n\tmodel = ARIMA(data, order=(params[0], 0, params[2]))\n\tres = model.fit()\n\n\t#model_summary = res.summary().as_text()\n\tmodel_summary = res.summary()\n\t# write summary to file\n\t#fileobj = open(\"quotes/static/model_results/ARMA_Summary.txt\", 'w')\n\t#fileobj.write(model_summary.as_text())\n\t#fileobj.close()\n\n\tfig, ax = plt.subplots(figsize=(10,8))\n\tax = data.plot(ax=ax)\n\tfig = plot_predict(res, start=data.index[0], end=data.index[-1], ax=ax, plot_insample=False)\n\tlegend = ax.legend([\"Actual price\", \"Forecast\", \"95% Confidence Interval\"], loc='upper left')\n\n\tfig.savefig(\"quotes/static/plots/forecast_vs_actual.jpg\")\n\treturn (model, res, model_summary)\n\ndef bestParams(data):\n\n\tps = range(0, 8, 1)\n\td = 1\n\tqs = range(0, 8, 1)\n\n\t# Create a list with all possible combination of parameters\n\tparameters = product(ps, qs)\n\tparameters_list = list(parameters)\n\torder_list = []\n\n\tfor each in parameters_list:\n\t each = list(each)\n\t each.insert(1, 1)\n\t each = tuple(each)\n\t order_list.append(each)\n\n\tresult_df = AIC_optimization(order_list, exog=data)\n\treturn result_df['(p, d, q)'].iloc[0]\n\ndef AIC_optimization(order_list, exog):\n \"\"\"\n Return dataframe with parameters and corresponding AIC\n \n order_list - list with (p, d, q) tuples\n exog - the exogenous variable\n \"\"\"\n \n results = []\n \n for order in order_list:\n try: \n model = SARIMAX(exog, order=order).fit(disp=-1)\n except:\n continue\n \n aic = model.aic\n results.append([order, model.aic])\n \n result_df = pd.DataFrame(results)\n result_df.columns = ['(p, d, q)', 'AIC']\n\n #Sort in ascending order, lower AIC is better\n result_df = result_df.sort_values(by='AIC', ascending=True).reset_index(drop=True)\n return result_df","sub_path":"stock_modeling/quotes/stock_models.py","file_name":"stock_models.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"286879223","text":"import tensorflow as tf\nimport numpy as np\nfrom sys import exit\n\nclass TextCBOF(object):\n \"\"\"\n A CBOF for text classification.\n Uses an embedding layer, followed by a hidden layer, and output layer.\n \"\"\"\n def __init__(\n self, sequence_length, num_classes, vocab_size,\n embedding_size, n_hidden, dropout_keep_prob,l2_reg_lambda=0.0):\n\n # Placeholders for input, output and dropout (which you need to implement!!!!)\n\n self.input_x = tf.placeholder(tf.int32, [None, sequence_length], name=\"input_x\")\n #mask = tf.not_equal(self.input_x, 0, name=None)\n# print self.input_x\n #tf.boolean_mask(self.input_x , mask, name='boolean_mask')\n \n\n self.input_y = tf.placeholder(tf.float32, [None, num_classes], name=\"input_y\")\n #self.dropout_keep_prob = tf.placeholder(tf.float32, name=\"dropout_keep_prob\") \n self.dropout_keep_prob = tf.constant(0.5,name=\"dropout_keep_prob\") \n # Keeping track of l2 regularization loss (optional)\n l2_loss = tf.constant(0.0)\n\n # Embedding layer\n with tf.device('/cpu:0'), tf.name_scope(\"embedding\"):\n E = tf.Variable(\n tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0),\n name=\"E\")\n self.embedded_chars = tf.nn.embedding_lookup(E, self.input_x)\n\n #self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1)\n print(\"embedded_chars: {}\".format(self.embedded_chars.get_shape()))\n self.embedded_chars_reduced=tf.reduce_mean(self.embedded_chars ,1)\n print(\"embedded_chars_reduced: {}\".format(self.embedded_chars_reduced.get_shape()))\n\n self.W = tf.Variable(tf.truncated_normal([embedding_size,n_hidden], stddev=0.1), name=\"W\")\n self.b = tf.Variable(tf.random_normal([n_hidden]), name=\"b\")\n \n print(\"W {}\".format(self.W.get_shape()))\n\n\n self.output_layer = tf.add(tf.matmul(self.embedded_chars_reduced,self.W),self.b)\n self.output_layer = tf.nn.relu(self.output_layer, name=\"relu\")\n\n print(\"self.output_layer {}\".format(self.output_layer.get_shape()))\n \n\n # Final (unnormalized) scores and predictions\n with tf.name_scope(\"output\"):\n W = tf.get_variable(\n \"W\",\n shape=[n_hidden, num_classes],\n #initializer=tf.contrib.layers.variance_scaling_initializer())\n initializer=tf.contrib.layers.xavier_initializer())\n #variance_scaling_initializer()\n b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name=\"b\")\n l2_loss += tf.nn.l2_loss(W)\n l2_loss += tf.nn.l2_loss(b)\n self.scores = tf.nn.xw_plus_b( self.output_layer, W, b, name=\"scores\")\n print(\"self.scores: {}\".format(self.scores.get_shape()))\n self.predictions = tf.argmax(self.scores, 1, name=\"predictions\")\n\n # CalculateMean cross-entropy loss\n with tf.name_scope(\"loss\"):\n losses = tf.nn.softmax_cross_entropy_with_logits(self.scores, self.input_y)\n self.loss = tf.reduce_mean(losses) + l2_reg_lambda * l2_loss\n\n # Accuracy\n with tf.name_scope(\"accuracy\"):\n correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))\n\n print(self.input_y.get_shape())\n print(self.predictions.get_shape())\n print(self.input_y) \n self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, \"float\"), name=\"accuracy\")\n\n","sub_path":"model/text_cbof.py","file_name":"text_cbof.py","file_ext":"py","file_size_in_byte":3576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"80717407","text":"import pyodbc\nimport yfinance as yf\nfrom datetime import datetime, timedelta\nimport pytz\nimport numpy as np\n\nclass DBHandle:\n DBName = \"FinancialDB\"\n \n conn = []\n \n #Constructor que se conecta a la BD\n def __init__(self):\n ##Conectarse a BD\n try:\n self.conn = pyodbc.connect('Driver={SQL Server};'\n 'Server=JMA-LAPTOP\\MSSQLSERVER01;'\n 'Database='+ self.DBName + ';'\n 'Trusted_Connection=yes;')\n \n except:\n print(\"Error en la conexión\")\n self.CreateGeneralInfoTable()\n\n #Crear una tabla con la información de los instrumentos\n def CreateGeneralInfoTable(self):\n cursor = self.conn.cursor()\n try:\n cursor.execute(\"\"\"\n IF OBJECT_ID('TicketInfo') IS NOT NULL\n BEGIN\n SELECT * FROM FinancialDB.dbo.TicketInfo\n END\n ELSE\n BEGIN\n \n CREATE TABLE FinancialDB.dbo.TicketInfo (\n Id int IDENTITY(1,1) PRIMARY KEY,\n Simbolo varchar(30) NOT NULL,\n Descripcion varchar(100),\n Tipo varchar(100),\n Sector varchar(100),\n InicioSeguim smalldatetime\n )\n END\n \"\"\")\n except:\n print(\"Error al crear la tabla General\")\n \n #Realiza consultas simples, básicamente se usa para comprobar que exista la tabla\n def Consulta(self, query):\n cursor = self.conn.cursor()\n try: \n cursor.execute(query)\n return 0, cursor.fetchone()[0]\n except:\n return 1, \"01-01-1900\"\n \n #Insertamos datos en las tablas de elementos\n def InsertData(self, tableName, dataList):\n cursor = self.conn.cursor()\n \n #Guardamos elemento por elemento\n for i in range(0, len(dataList)):\n cursor.execute(\"SELECT * FROM \" + tableName +\" WHERE Fecha = ? \", dataList[i][0])\n if cursor.rowcount != -1:\n cursor.execute(\"INSERT INTO \" + tableName +\"\"\" (Fecha, TicketId, Apertura, MaxVal, Cierre, AdjClose, Volume)\n VALUES( ?, ?, ?, ?, ?, ?, ?)\"\"\", dataList[i][0], dataList[i][1],dataList[i][2], dataList[i][4],dataList[i][4],dataList[i][5],dataList[i][6] )\n \n\n cursor.commit()\n \n\n #Insertamos datos en las tablas de información general\n def InsertDataONGeneralTable(self, dataList):\n cursor = self.conn.cursor()\n \n #Guardamos elemento por elemento\n cursor.execute(\"SELECT * FROM FinancialDB.dbo.TicketInfo WHERE Simbolo = ? \", dataList[0])\n if cursor.rowcount != -1:\n cursor.execute(\"\"\"INSERT INTO FinancialDB.dbo.TicketInfo (Simbolo, Descripcion, Tipo, Sector, InicioSeguim )\n VALUES( ?, ?, ?, ?, ?)\"\"\", dataList[0], dataList[1],dataList[2], dataList[3],dataList[4] )\n \n cursor.commit()\n\n\n\n #Creamos nueva tabla\n def createTable(self, ticket, tableName):\n cursor = self.conn.cursor()\n\n try:\n cursor.execute(\"\"\"\n IF OBJECT_ID(\"\"\" + \"'\" + ticket + \"'\"+ \"\"\") IS NOT NULL\n BEGIN\n SELECT * FROM \"\"\" + tableName + \"\"\"\n END\n ELSE\n BEGIN\n \n CREATE TABLE \"\"\" + tableName + \"\"\" (\n Id int IDENTITY(1,1) PRIMARY KEY,\n Fecha smalldatetime,\n TicketId int NOT NULL,\n Apertura float,\n MaxVal float,\n Cierre float,\n AdjClose float,\n Volume decimal\n )\n END\n \"\"\")\n cursor.commit()\n except:\n print(\"No se mpudo crear la tabla \", tableName)\n\n ##Create News Table\n def createNewsTable(self):\n cursor = self.conn.cursor()\n try:\n cursor.execute(\"\"\"\n IF OBJECT_ID('NewsInfo') IS NOT NULL\n BEGIN\n SELECT * FROM FinancialDB.dbo.NewsInfo\n END\n ELSE\n BEGIN\n CREATE TABLE FinancialDB.dbo.NewsInfo (\n Id int IDENTITY(1,1) PRIMARY KEY,\n Fecha smalldatetime NOT NULL,\n Seccion varchar(100),\n Encabezado varchar(500),\n Web varchar(500)\n )\n END\n \"\"\")\n cursor.commit()\n except:\n print(\"Error al crear la tabla de noticias\")\n\n\n #Insertamos datos en las tablas de información general\n def InsertDataONNewsTable(self, dataList):\n cursor = self.conn.cursor()\n \n #Guardamos elemento por elemento\n \n for i in range(0, len(dataList)):\n for j in range(0, len(dataList[i])):\n cursor.execute(\"SELECT * FROM FinancialDB.dbo.NewsInfo WHERE Encabezado = ? \", dataList[i][j][2])\n if cursor.rowcount != -1:\n cursor.execute(\"\"\"INSERT INTO FinancialDB.dbo.NewsInfo (Fecha, Seccion, Encabezado, Web)\n VALUES( ?, ?, ?, ?)\"\"\", dataList[i][j][0], dataList[i][j][1],dataList[i][j][2], dataList[i][j][3] )\n \n cursor.commit()\n\n def InsertNewsByDateOnTable(self, dataList):\n cursor = self.conn.cursor()\n for i in range(0, len(dataList)):\n cursor.execute(\"SELECT * FROM FinancialDB.dbo.NewsInfo WHERE Encabezado = ? \", dataList[i][2])\n if cursor.rowcount != -1:\n cursor.execute(\"\"\"INSERT INTO FinancialDB.dbo.NewsInfo (Fecha, Seccion, Encabezado, Web)\n VALUES( ?, ?, ?, ?)\"\"\", dataList[i][0], dataList[i][1],dataList[i][2], dataList[i][3] )\n \n cursor.commit()\n\n\n ##Desconectarse a BD\n def disconnect(self):\n cursor = self.conn.cursor()\n cursor.close()","sub_path":"YFtoSQL/DBHandling.py","file_name":"DBHandling.py","file_ext":"py","file_size_in_byte":6862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"641190715","text":"import os.path\nfrom typing import Union\n\nimport torch\n\n\n_TEST_DIR_PATH = os.path.realpath(\n os.path.join(os.path.dirname(__file__), '..'))\n\n\ndef get_asset_path(*paths):\n \"\"\"Return full path of a test asset\"\"\"\n return os.path.join(_TEST_DIR_PATH, 'assets', *paths)\n\n\ndef convert_tensor_encoding(\n tensor: torch.tensor,\n dtype: torch.dtype,\n):\n \"\"\"Convert input tensor with values between -1 and 1 to integer encoding\n Args:\n tensor: input tensor, assumed between -1 and 1\n dtype: desired output tensor dtype\n Returns:\n Tensor: shape of (n_channels, sample_rate * duration)\n \"\"\"\n if dtype == torch.int32:\n tensor *= (tensor > 0) * 2147483647 + (tensor < 0) * 2147483648\n if dtype == torch.int16:\n tensor *= (tensor > 0) * 32767 + (tensor < 0) * 32768\n if dtype == torch.uint8:\n tensor *= (tensor > 0) * 127 + (tensor < 0) * 128\n tensor += 128\n tensor = tensor.to(dtype)\n return tensor\n\n\ndef get_whitenoise(\n *,\n sample_rate: int = 16000,\n duration: float = 1, # seconds\n n_channels: int = 1,\n seed: int = 0,\n dtype: Union[str, torch.dtype] = \"float32\",\n device: Union[str, torch.device] = \"cpu\",\n channels_first=True,\n scale_factor: float = 1,\n):\n \"\"\"Generate pseudo audio data with whitenoise\n Args:\n sample_rate: Sampling rate\n duration: Length of the resulting Tensor in seconds.\n n_channels: Number of channels\n seed: Seed value used for random number generation.\n Note that this function does not modify global random generator state.\n dtype: Torch dtype\n device: device\n channels_first: whether first dimension is n_channels\n scale_factor: scale the Tensor before clamping and quantization\n Returns:\n Tensor: shape of (n_channels, sample_rate * duration)\n \"\"\"\n if isinstance(dtype, str):\n dtype = getattr(torch, dtype)\n if dtype not in [torch.float32, torch.int32, torch.int16, torch.uint8]:\n raise NotImplementedError(f'dtype {dtype} is not supported.')\n # According to the doc, folking rng on all CUDA devices is slow when there are many CUDA devices,\n # so we only fork on CPU, generate values and move the data to the given device\n with torch.random.fork_rng([]):\n torch.random.manual_seed(seed)\n tensor = torch.randn([n_channels, int(sample_rate * duration)],\n dtype=torch.float32, device='cpu')\n tensor /= 2.0\n tensor *= scale_factor\n tensor.clamp_(-1.0, 1.0)\n if not channels_first:\n tensor = tensor.t()\n return convert_tensor_encoding(tensor, dtype)\n\n\ndef get_sinusoid(\n *,\n frequency: float = 300,\n sample_rate: int = 16000,\n duration: float = 1, # seconds\n n_channels: int = 1,\n dtype: Union[str, torch.dtype] = \"float32\",\n device: Union[str, torch.device] = \"cpu\",\n channels_first: bool = True,\n):\n \"\"\"Generate pseudo audio data with sine wave.\n\n Args:\n frequency: Frequency of sine wave\n sample_rate: Sampling rate\n duration: Length of the resulting Tensor in seconds.\n n_channels: Number of channels\n dtype: Torch dtype\n device: device\n\n Returns:\n Tensor: shape of (n_channels, sample_rate * duration)\n \"\"\"\n if isinstance(dtype, str):\n dtype = getattr(torch, dtype)\n pie2 = 2 * 3.141592653589793\n end = pie2 * frequency * duration\n theta = torch.linspace(0, end, int(sample_rate * duration), dtype=torch.float32, device=device)\n tensor = torch.sin(theta, out=None).repeat([n_channels, 1])\n if not channels_first:\n tensor = tensor.t()\n return convert_tensor_encoding(tensor, dtype)\n","sub_path":"test/torchaudio_unittest/common_utils/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":3717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"603122744","text":"from csv import DictReader\nfrom django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom django.conf import settings\nfrom django.core.paginator import Paginator\nfrom urllib.parse import urlencode\n\n\ndef index(request):\n return redirect(reverse(bus_stations))\n\n\ndef bus_stations(request):\n with open(settings.BUS_STATION_CSV, encoding='cp1251') as file:\n reader = list(DictReader(file))\n paginator = Paginator(reader, 10)\n total_pages = paginator.num_pages\n current_page = int(request.GET.get('page', 1))\n\n if current_page > total_pages:\n current_page = total_pages\n elif current_page < 1:\n current_page = 1\n page = paginator.get_page(current_page)\n if page.has_next():\n next_page_url = reverse('bus_stations') + '?' \\\n + urlencode({'page': page.next_page_number()})\n else:\n next_page_url = None\n if page.has_previous():\n previous_page_url = reverse('bus_stations') + '?' \\\n + urlencode({'page': page.previous_page_number()})\n else:\n previous_page_url = None\n return render(request, 'index.html', context={\n 'bus_stations': page.object_list,\n 'current_page': current_page,\n 'prev_page_url': previous_page_url,\n 'next_page_url': next_page_url,\n })","sub_path":"Django/02.Обработка запросов/pagination/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"623865600","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\nimport signal\nimport json\n\nimport click\nimport gevent\nfrom gevent import monkey\nimport time\nimport random\nfrom ethereum import slogging\n\nfrom ethereum.utils import decode_hex\nfrom raiden.console import ConsoleTools\nfrom raiden.app import App\nfrom raiden.network.rpc.client import BlockChainService\nfrom raiden.network.discovery import ContractDiscovery\nfrom raiden.utils import split_endpoint\n\n\nmonkey.patch_all()\nlog = slogging.get_logger(__name__) # pylint: disable=invalid-name\n\n\n@click.option( # noqa\n '--privatekey',\n type=str,\n)\n@click.option( # noqa\n '--registry-contract-address',\n type=str,\n)\n@click.option( # noqa\n '--discovery-contract-address',\n type=str,\n)\n@click.option( # noqa\n '--listen-address',\n type=str,\n)\n@click.option( # noqa\n '--logging',\n default=':INFO',\n type=str,\n)\n@click.option( # noqa\n '--logfile',\n default=None,\n type=str\n)\n@click.option( # noqa\n '--scenario',\n type=click.File()\n)\n@click.option( # noqa\n '--stage-prefix',\n type=str\n)\n@click.option( # noqa\n '--results-filename',\n type=str\n)\n@click.command()\ndef run(privatekey,\n registry_contract_address,\n discovery_contract_address,\n listen_address,\n logging,\n logfile,\n scenario,\n stage_prefix,\n results_filename): # pylint: disable=unused-argument\n\n # TODO: only enabled logging on \"initiators\"\n slogging.configure(logging, log_file=logfile)\n\n (listen_host, listen_port) = split_endpoint(listen_address)\n\n config = App.default_config.copy()\n config['host'] = listen_host\n config['port'] = listen_port\n config['privatekey_hex'] = privatekey\n\n blockchain_service = BlockChainService(\n decode_hex(privatekey),\n decode_hex(registry_contract_address),\n host=\"127.0.0.1\",\n port=\"8545\",\n )\n\n discovery = ContractDiscovery(\n blockchain_service,\n decode_hex(discovery_contract_address)\n )\n\n app = App(config, blockchain_service, discovery)\n\n app.discovery.register(\n app.raiden.address,\n listen_host,\n listen_port,\n )\n\n app.raiden.register_registry(app.raiden.chain.default_registry.address)\n\n if scenario:\n script = json.load(scenario)\n\n tools = ConsoleTools(\n app.raiden,\n app.discovery,\n app.config['settle_timeout'],\n app.config['reveal_timeout'],\n )\n\n transfers_by_peer = {}\n\n tokens = script['tokens']\n token_address = None\n peer = None\n our_node = app.raiden.address.encode('hex')\n log.warning(\"our address is {}\".format(our_node))\n for token in tokens:\n # skip tokens that we're not part of\n nodes = token['channels']\n if our_node not in nodes:\n continue\n\n # allow for prefunded tokens\n if 'token_address' in token:\n token_address = token['token_address']\n else:\n token_address = tools.create_token()\n\n transfers_with_amount = token['transfers_with_amount']\n\n # FIXME: in order to do bidirectional channels, only one side\n # (i.e. only token['channels'][0]) should\n # open; others should join by calling\n # raiden.api.deposit, AFTER the channel came alive!\n\n # NOTE: leaving unidirectional for now because it most\n # probably will get to higher throughput\n\n log.warning(\"Waiting for all nodes to come online\")\n\n while not all(tools.ping(node) for node in nodes if node != our_node):\n gevent.sleep(5)\n\n log.warning(\"All nodes are online\")\n\n if our_node != nodes[-1]:\n our_index = nodes.index(our_node)\n peer = nodes[our_index + 1]\n\n tools.register_token(token_address)\n amount = transfers_with_amount[nodes[-1]]\n\n while True:\n try:\n app.discovery.get(peer.decode('hex'))\n break\n except KeyError:\n log.warning(\"Error: peer {} not found in discovery\".format(peer))\n time.sleep(random.randrange(30))\n\n while True:\n try:\n log.warning(\"Opening channel with {} for {}\".format(peer, token_address))\n app.raiden.api.open(token_address, peer)\n break\n except KeyError:\n log.warning(\"Error: could not open channel with {}\".format(peer))\n time.sleep(random.randrange(30))\n\n while True:\n try:\n log.warning(\"Funding channel with {} for {}\".format(peer, token_address))\n app.raiden.api.deposit(token_address, peer, amount)\n break\n except Exception:\n log.warning(\"Error: could not deposit {} for {}\".format(amount, peer))\n time.sleep(random.randrange(30))\n\n if our_index == 0:\n last_node = nodes[-1]\n transfers_by_peer[last_node] = int(amount)\n else:\n peer = nodes[-2]\n\n if stage_prefix is not None:\n open('{}.stage1'.format(stage_prefix), 'a').close()\n log.warning(\"Done with initialization, waiting to continue...\")\n event = gevent.event.Event()\n gevent.signal(signal.SIGUSR2, event.set)\n event.wait()\n\n transfer_results = {'total_time': 0, 'timestamps': []}\n\n def transfer(token_address, amount_per_transfer, total_transfers, peer, is_async):\n def transfer_():\n log.warning(\"Making {} transfers to {}\".format(total_transfers, peer))\n initial_time = time.time()\n times = [0] * total_transfers\n for index in xrange(total_transfers):\n app.raiden.api.transfer(\n token_address.decode('hex'),\n amount_per_transfer,\n peer,\n )\n times[index] = time.time()\n\n transfer_results['total_time'] = time.time() - initial_time\n transfer_results['timestamps'] = times\n\n log.warning(\"Making {} transfers took {}\".format(\n total_transfers, transfer_results['total_time']))\n log.warning(\"Times: {}\".format(times))\n\n if is_async:\n return gevent.spawn(transfer_)\n else:\n transfer_()\n\n # If sending to multiple targets, do it asynchronously, otherwise\n # keep it simple and just send to the single target on my thread.\n if len(transfers_by_peer) > 1:\n greenlets = []\n for peer_, amount in transfers_by_peer.items():\n greenlet = transfer(token_address, 1, amount, peer_, True)\n if greenlet is not None:\n greenlets.append(greenlet)\n\n gevent.joinall(greenlets)\n\n elif len(transfers_by_peer) == 1:\n for peer_, amount in transfers_by_peer.items():\n transfer(token_address, 1, amount, peer_, False)\n\n log.warning(\"Waiting for termination\")\n\n open('{}.stage2'.format(stage_prefix), 'a').close()\n log.warning(\"Waiting for transfers to finish, will write results...\")\n event = gevent.event.Event()\n gevent.signal(signal.SIGUSR2, event.set)\n event.wait()\n\n results = tools.channel_stats_for(token_address, peer)\n if transfer_results['total_time'] != 0:\n results['total_time'] = transfer_results['total_time']\n if len(transfer_results['timestamps']) > 0:\n results['timestamps'] = transfer_results['timestamps']\n results['channel'] = repr(results['channel']) # FIXME\n\n log.warning(\"Results: {}\".format(results))\n\n with open(results_filename, 'w') as fp:\n json.dump(results, fp, indent=2)\n\n open('{}.stage3'.format(stage_prefix), 'a').close()\n event = gevent.event.Event()\n gevent.signal(signal.SIGQUIT, event.set)\n gevent.signal(signal.SIGTERM, event.set)\n gevent.signal(signal.SIGINT, event.set)\n event.wait()\n\n else:\n log.warning(\"No scenario file supplied, doing nothing!\")\n\n open('{}.stage2'.format(stage_prefix), 'a').close()\n event = gevent.event.Event()\n gevent.signal(signal.SIGQUIT, event.set)\n gevent.signal(signal.SIGTERM, event.set)\n gevent.signal(signal.SIGINT, event.set)\n event.wait()\n\n app.stop()\n\n\nif __name__ == '__main__':\n run() # pylint: disable=no-value-for-parameter\n","sub_path":"raiden/tools/scenario_runner.py","file_name":"scenario_runner.py","file_ext":"py","file_size_in_byte":8994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"544891326","text":"# Given an array nums, there is a sliding window of size k which is moving from \n# the very left of the array to the very right. You can only see the k numbers in \n# the window. Each time the sliding window moves right by one position. Return the\n# max sliding window. \n# \n# Follow up: \n# Could you solve it in linear time? \n# \n# Example: \n# \n# \n# Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3\n# Output: [3,3,5,5,6,7] \n# Explanation: \n# \n# Window position Max\n# --------------- -----\n# [1 3 -1] -3 5 3 6 7 3\n# 1 [3 -1 -3] 5 3 6 7 3\n# 1 3 [-1 -3 5] 3 6 7 5\n# 1 3 -1 [-3 5 3] 6 7 5\n# 1 3 -1 -3 [5 3 6] 7 6\n# 1 3 -1 -3 5 [3 6 7] 7\n# \n# \n# \n# Constraints: \n# \n# \n# 1 <= nums.length <= 10^5 \n# -10^4 <= nums[i] <= 10^4 \n# 1 <= k <= nums.length \n# \n# Related Topics 堆 Sliding Window \n# 👍 455 👎 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution(object):\n # heap solution\n from heapq import heappush, heappop\n def maxSlidingWindow(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n res, heap = [], []\n for i, num in enumerate(nums):\n heappush(heap, (-num, i))\n if i - k + 1 >= 0:\n while heap and heap[0][1] <= i - k: heappop(heap)\n res.append(-heap[0][0])\n\n return res\n# leetcode submit region end(Prohibit modification and deletion)\n","sub_path":"Week_02/[239]Sliding Window Maximum.py","file_name":"[239]Sliding Window Maximum.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"449603666","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport csv\nfrom util.BasicUnits import cm\nfrom util.conversor import cm2inch\n\nBAR_WIDTH = 0.15\nBAR_COLORS = ['r', 'g', 'b']\n\n\ndef parse_csv_info(csv_reader):\n line_count = 0\n\n all_info = {}\n slacks = []\n job_durations = []\n\n for row in csv_reader:\n if line_count == 0:\n pass\n line_count += 1\n else:\n system = row[0]\n slack = int(row[1])\n cost = float(row[2])\n\n if slack not in slacks:\n slacks.append(slack)\n\n if system not in all_info:\n all_info[system] = [[], []]\n\n all_info[system][0].append(slack)\n all_info[system][1].append(cost)\n\n return slacks, job_durations, all_info\n\nif __name__ == '__main__':\n with open('/Users/pjoaquim/Dropbox/mine/traces/slack_aware_plots/zoom_in_trace_2.csv') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n\n slacks, job_durations, all_info = parse_csv_info(csv_reader)\n\n fig, plot = plt.subplots()\n\n plot.yaxis.grid(True)\n\n systems_names_legend = [\"SlackAware+METIS\", 'SlackAware+$\\\\mu$METIS', 'SpotOn+DP+$\\\\mu$METIS']\n systems_names_csv = [\"Hourglass+METIS\", \"Hourglass+M-METIS\", \"SpotOn+DP+M-METIS\"]\n\n colors = ['#2E75B6', '#FEBD0F', '#548235']\n pattern = ['-bv', '-bo', '-x']\n\n\n for idx_system, system in enumerate(systems_names_csv):\n\n plot.plot(all_info[system][0],\n all_info[system][1],\n pattern[idx_system],\n color=colors[idx_system])\n\n plot.set_xlim(0, 100)\n plot.set_ylim(0, 1.0)\n\n\n plt.yticks((0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0))\n plot.set_ylabel('Normalized Cost (w.r.t. OD)', fontsize=12)\n xlabel = plot.set_xlabel('Slack (%)', fontsize=12)\n legend = fig.legend(systems_names_legend, fontsize=12)\n\n fig.set_size_inches(cm2inch(13, 7))\n plt.savefig('/Users/pjoaquim/Dropbox/PedroJoaquim/nsdi19/images/evaluation/micro/micro_zoom_in.png',\n bbox_extra_artists=(xlabel,),\n bbox_inches='tight')\n\n #plt.show()\n\n\n\n\n\n\n","sub_path":"hourglass/costs_zoomin.py","file_name":"costs_zoomin.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"599299099","text":"from django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.conf import settings\n\nfrom models import Cellar\nfrom models import CellarClass\n\n# Add default cellars on new user creation\n@receiver(post_save, sender=settings.AUTH_USER_MODEL)\ndef init_new_user(instance, created, raw, **kwargs):\n\t# raw is set when model is created from loaddata.\n\tif created and not raw:\n\t\tCellar.objects.create(\n\t\t\tname=\"IN\",\n owner=instance,\n cellar_class=CellarClass.objects.get(id=1),\n is_visible=False\n )\n\n\t\tCellar.objects.create(\n\t\t\tname=\"OUT\",\n owner=instance,\n cellar_class=CellarClass.objects.get(id=2),\n is_visible=False\n )\n\n\t\tCellar.objects.create(\n\t\t\tname=\"My Cellar\",\n owner=instance,\n cellar_class=CellarClass.objects.get(id=3)\n )\n","sub_path":"apps/cellar/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"518788088","text":"\"\"\"Serializer for groups applications.\"\"\"\n\nfrom rest_framework import serializers\nfrom .models import Group\n\n\nclass GroupSerializer(serializers.ModelSerializer):\n \"\"\"\n Serializer for Group Model.\n \"\"\"\n users = serializers.HyperlinkedRelatedField(\n many=True, view_name='customuser-detail', read_only=True\n )\n\n class Meta:\n model = Group\n fields = ('url', 'id', 'name', 'description',\n 'users', 'created', 'modified')\n","sub_path":"synway_usergroups_project/groups/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"434124576","text":"import random\ntemp = 0\ndef monopolyworp(temp):\n rand = random.randrange(1, 7)\n rand2 = random.randrange(rand, 7)\n if rand == rand2:\n dubbel = \"(Dubbel)\"\n else:\n dubbel = \"\"\n temp = 0\n if dubbel == \"(Dubbel)\":\n temp = temp + 1\n if temp == 3:\n dubbel = ('Direct naar de gevangenis')\n print(rand, \"+\", rand2, \"=\", (rand + rand2), dubbel)\n return temp\n\ngooi = input(\"Wil je gooien? (ja/nee)\")\nwhile gooi == \"ja\":\n gooi == \"\"\n temp = monopolyworp(temp)\n gooi = input(\"Wil je nog een keer gooien? (ja/nee)\")\n\n","sub_path":"les 10/2. Random.py","file_name":"2. Random.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"237610065","text":"from rest_framework import serializers\n\nfrom kubeops_api.models.host import Host\nfrom storage.models import NfsStorage\n\n__all__ = [\n 'NfsStorageSerializer'\n]\n\n\nclass NfsStorageSerializer(serializers.ModelSerializer):\n meta = serializers.JSONField()\n nfs_host = serializers.SlugRelatedField(\n queryset=Host.objects.all(),\n slug_field='name', required=False\n )\n\n class Meta:\n model = NfsStorage\n read_only_fields = ['id', 'date_created']\n fields = ['id', 'name', 'server', 'allow_ip', 'nfs_host', 'path', 'date_created']\n","sub_path":"api/storage/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"210154022","text":"from flask import Blueprint, render_template, url_for, request, jsonify\nfrom webapp.blueprints.client.forms import FibForm\nfrom webapp.modules import convert\nimport redis\nimport json\nfrom webapp.blueprints.client.models import Fib\n\n\n\nclient = Blueprint('client', __name__, template_folder='templates')\n#cache = redis.Redis(host=\"redis\", port=6379, db=0, decode_responses=True)\ncache = redis.StrictRedis(host=\"redis\", port=6379, db=0, decode_responses=True, password=\"devpassword\")\n\n\n\ndef Fibonacci(n):\n a, b = 0, 1\n for i in range(n):\n a, b = b, a + b\n cache.lpush( 'fib', json.dumps({'index': n, 'value': a }) )\n fib = Fib(fib_index=n, fib_value=a)\n fib.save()\n return a\n\n\n@client.route(\"/fib\", methods=['GET', 'POST'])\ndef fib():\n _form = FibForm()\n if _form.validate_on_submit():\n _index_pos = request.form['index_pos']\n _fib_value = Fibonacci(int(_index_pos))\n redis_values = convert(cache.lrange('fib', 0, 4))\n db_values = Fib.get_fib_values(limit=5)\n return render_template('fib.html', form=_form, _index_pos=_index_pos, _fib_value=_fib_value, redis_values=redis_values, db_values=db_values)\n return render_template('fib.html', form=_form)\n","sub_path":"services/web/webapp/blueprints/client/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"165860736","text":"import datetime#导入时间日期模块,用于记录程序的执行时间\r\nstarttime = datetime.datetime.now()#用于记录程序开始执行的时间\r\n\r\n#执行程序\r\n\r\nendtime = datetime.datetime.now()#用于记录程序执行完毕时的时间\r\nprint('Done !')\r\ntime = (endtime - starttime).seconds#记录了程序执行的秒数\r\nminute = time//60#程序执行的分钟数\r\nseconds = time%60#程序执行的秒数\r\nprint('本次执行时间:',minute,'分钟',seconds,'秒')\r\n","sub_path":"python/其它/3.0/阿里巴巴 - 大数据竞赛/python程序/Effective/显示程序执行时间实现方法.py","file_name":"显示程序执行时间实现方法.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"48577674","text":"#1:다 함수형 모델\n\nimport numpy as np\n#1. 데이터\nx = np.array(range(100))\ny = np.array([range(711,811), range(1,101), range(200,300),range(301,401)])\nprint(x.shape) #(5,100)\nprint(y.shape) #(2,100)\n\nx=np.transpose(x) #(100,5)\ny=np.transpose(y) #(100,2)\n\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(\n x, y, shuffle=True, train_size=0.8, random_state=66\n)\nprint(x_train.shape) #(80,5)\nprint(y_train.shape) #(80,2)\n\n#2. 모델구성\nfrom tensorflow.keras.models import Sequential,Model\nfrom tensorflow.keras.layers import Dense,Input\n#modelS = Sequential()\n#modelS.add(Dense(3, input_shape=(5,)))\n#modelS.add(Dense(4))\n#modelS.add(Dense(2))\n#modelS.summary()\n\ninput1 = Input(shape=(1,))\ndense1 = Dense(3)(input1) #상단 레이어의 이름\ndense1_1 = Dense(7)(dense1)\ndense2 = Dense(4)(dense1_1)\noutput1 = Dense(4)(dense2)\n\nmodelF = Model(inputs = input1, outputs = output1)\nmodelF.summary()\n\n\n#3. 컴파일 훈련\nmodelF.compile(loss='mse',optimizer='adam',metrics=['acc'])\nmodelF.fit(x_train,y_train, epochs=100, batch_size=1,\n verbose=1) \n\n\"\"\"\nverbose = 0 : 안나옴\nverbose = 1 : 디폴트\nverbose = 2 : 프로그래스바 x\nverbose = 3 : \n\"\"\"\n\n#4. 평가 예측\nresults = modelF.evaluate(x_test,y_test)\nprint(\"results : \",results)\n\ny_pred = modelF.predict(x_test)\n\nfrom sklearn.metrics import mean_squared_error\ndef RMSE(y_test, y_predict) : \n return np.sqrt(mean_squared_error(y_test,y_predict))\nprint(\"RMSE : \", RMSE(y_test, y_pred))\nprint(\"mse : \", mean_squared_error(y_test, y_pred))\n\nfrom sklearn.metrics import r2_score\nR2 = r2_score(y_test,y_pred)\nprint(\"R2 : \", R2)\n\n","sub_path":"study/keras/keras11_hamsu3.py","file_name":"keras11_hamsu3.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"381318620","text":"# coding=utf-8\r\n\r\n# from v2_spider import url_manager, html_downloader, html_parser, html_outputer\r\nimport url_manager\r\nimport html_downloader\r\nimport html_parser\r\nimport html_outputer\r\n\r\nclass SpiderMain(object):\r\n\tdef __init__(self):\r\n\t\tself.urls = url_manager.UrlManager() # url管理器\r\n\t\tself.downloader = html_downloader.HtmlDownloader() # 下载器\r\n\t\tself.parser = html_parser.HtmlParser() # 解析器\r\n\t\tself.outputer = html_outputer.HtmlOutputer() # 输出器\r\n\r\n\tdef craw(self, root_url):\r\n\t\tcount = 1 # 记录当爬取的是第几个url\r\n\t\tself.urls.add_new_url(root_url) # root_url添加进入url管理器\r\n\t\t# url管理器里面有了带爬取的url,我们就可以启动爬虫的循环\r\n\t\twhile self.urls.has_new_url(): #当url管理器里面有待爬取的url的时候\r\n\t\t\ttry: # 百度百科 很多页面没有摘要数据 要么就是某个url页面已经无法访问 因此要加入一个异常处理\r\n\t\t\t\tnew_url = self.urls.get_new_url() # 就获取新的url\r\n\t\t\t\tprint('craw %d : %s'%(count, new_url))\r\n\t\t\t\thtml_cont = self.downloader.download(new_url) # 启动下载器来下载页面。\r\n\t\t\t\t# 下载好了页面我们调用解析器来解析这个页面数据\r\n\t\t\t\t# 得到新的url列表 以及新的数据 传入两个参数(当前爬取的url,以及下载好的页面数据)\r\n\t\t\t\tnew_urls, new_data = self.parser.parse(new_url, html_cont) \r\n\t\t\t\tself.urls.add_new_urls(new_urls) # 新的url添加进入url管理器\r\n\t\t\t\tself.outputer.collect_data(new_data) # 收集数据\r\n\r\n\t\t\t\tif count == 100: # 本代码的目标是爬取1000个页面 所以加一个判断\r\n\t\t\t\t\tbreak\r\n\r\n\t\t\t\tcount = count + 1\r\n\t\t\texcept: # 出现问题\r\n\t\t\t\tprint('craw failed') # 代表爬取失败\r\n\r\n\t\t\t# 这样的话 如有有一个待爬取的url的话 我们��循环可以爬取相关的所有的页面\r\n\t\tself.outputer.output_html() # 调用这个方法来输出收集好的数据\r\n\r\nif __name__ == '__main__': # 创建一个main函数\r\n\troot_url = 'https://baike.baidu.com/item/Python/407313?fr=aladdin' # 要爬去的入口url\r\n\tobj_spider = SpiderMain() # 创建一个spiderMain\r\n\tobj_spider.craw(root_url) # 调用craw来启动爬虫","sub_path":"v2_spider/spider_main.py","file_name":"spider_main.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"371777025","text":"#\n# 1546번: 평균\n# https://www.acmicpc.net/problem/1546\n# Version: Python 3.9.7\n#\n# Created by WhiteHyun on 2021/12/30.\n#\n\n\nfrom sys import stdin\n\nread = stdin.readline\n\nif __name__ == \"__main__\":\n length = int(read())\n score_list = list(map(int, read().split()))\n max_score = max(score_list)\n print(sum(map(lambda x: x / max_score * 100, score_list)) / length)\n","sub_path":"boj/bronze1/1546.py","file_name":"1546.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"278596278","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2020 Ryan L. Collins \n# and the Talkowski Laboratory\n# Distributed under terms of the MIT license.\n\n\"\"\"\nIdentify, cluster, and refine all significant segments per HPO from rCNV sliding window analysis\n\"\"\"\n\n\nfrom os import path\nimport gzip\nimport csv\nimport pybedtools as pbt\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import norm\nimport string\nimport networkx as nx\nfrom itertools import combinations\nimport argparse\nfrom sys import stdout\n\n\ndef format_stat(x, is_phred=False, na_val=0):\n \"\"\"\n Helper function to format & convert p-values as needed\n \"\"\"\n\n if x == 'NA':\n return float(na_val)\n else:\n if is_phred:\n return 10 ** -float(x)\n else:\n return float(x)\n\n\ndef get_sig_label(primary_p, secondary_p, n_nominal, primary_q, primary_p_cutoff, \n secondary_p_cutoff=0.05, n_nominal_cutoff=2, \n secondary_or_nominal=True, fdr_q_cutoff=0.05,\n secondary_for_fdr=False):\n \"\"\"\n Checks if a window should be considered exome-wide or FDR significant\n \"\"\"\n\n # Run all comparisons\n primary_p_is_sig = (primary_p < primary_p_cutoff)\n secondary_p_is_sig = (secondary_p < secondary_p_cutoff)\n n_nominal_is_sig = (n_nominal >= n_nominal_cutoff)\n fdr_q_is_sig = (primary_q < fdr_q_cutoff)\n\n # Determine secondary criteria\n if secondary_p_is_sig and n_nominal_is_sig:\n secondary_is_sig = True\n elif secondary_or_nominal and (secondary_p_is_sig or n_nominal_is_sig):\n secondary_is_sig = True\n else:\n secondary_is_sig = False\n\n # First consider genome-wide significance\n if primary_p_is_sig and secondary_is_sig:\n return 'GWS'\n \n # Second consider FDR significance\n elif fdr_q_is_sig and secondary_for_fdr and secondary_is_sig:\n return 'FDR'\n elif fdr_q_is_sig and not secondary_for_fdr:\n return 'FDR'\n\n # Otherwise, non-significant\n else:\n return 'NS'\n\n\ndef ci2se(ci):\n \"\"\"\n Converts a tuple of (lower, upper) confidence interval bounds to standard error\n \"\"\"\n\n ci = sorted(ci)\n\n return (ci[1] - ci[0]) / (2 * 1.96)\n\n\ndef make_cs(refine_res, cs_val=0.95, cs_merge_buffer=200000):\n \"\"\"\n Merge windows into credible set based on sum of ranked PIPs\n Pads CS with ±cs_merge_buffer; recommended to set to size of one full bin\n \"\"\"\n\n cs_windows = []\n\n vals = pd.DataFrame.from_dict(refine_res, orient='index')\n vals = vals.sort_values(by='PIP', ascending=False)\n\n cs_sum = 0\n for i in range(len(vals)):\n cs_windows.append(vals.index[i])\n cs_sum += vals.PIP[i]\n\n if cs_sum >= cs_val:\n break\n\n # Convert window IDs back to pbt.BedTool and merge to nonredundant intervals\n credset_bt = pbt.BedTool('\\n'.join([x.replace('_', '\\t') for x in cs_windows]), \n from_string=True).sort().merge(d=cs_merge_buffer)\n credset_coords = [[x.chrom, x.start, x.end] for x in credset_bt]\n \n return credset_coords, credset_bt, cs_windows\n\n\ndef refine(window_priors, window_info, null_variance=0.42 ** 2, cs_val=0.95, \n cs_merge_buffer=200000):\n \"\"\"\n Refines a set of windows given their prior probability and effect size estimates\n Inputs:\n window_priors : dict of windows with prior probabilities\n window_info : dict of window association stats as processed by process_hpo()\n null_se : float, variance of OR estimates under the null. By default,\n this value is set to a 5% chance that ORs are > 2, as suggested\n by Wakefield 2009\n \"\"\"\n\n windows = list(window_priors.keys())\n\n if len(windows) == 1:\n refine_res = {windows[0] : {'ABF' : None, 'PIP' : 1}}\n else:\n refine_res = {}\n\n # Compute ABF per window\n for window in windows:\n # From Wakefield, 2009\n theta = window_info[window]['lnOR']\n se = ci2se((window_info[window]['lnOR_lower'], window_info[window]['lnOR_upper']))\n V = se ** 2\n if V > 0:\n zsq = (theta ** 2) / V\n W = null_variance\n ABF = np.sqrt((V+W) / V) * np.exp((-zsq / 2) * (W / (V+W)))\n\n # Wakefield 2009 formulates BF relative to H0. We need to invert to \n # obtain evidence & posterior for H1 (i.e., true non-zero effect)\n # However, we also are only testing for a _positive_ effect in cases,\n # so we will only invert ABF if theta >= 0. This is necessary to\n # prevent sites with enrichments in controls being scored with high ABF\n if theta >= 0:\n ABF = 1 / ABF\n \n else:\n ABF = 0\n\n refine_res[window] = {'ABF' : ABF}\n\n # Compute PIP per window as fraction of total BF, adjusted for prior probs\n # As per Mahajan 2018 (T2D refining paper, Nat. Genet.)\n posteriors = {}\n for window in windows:\n posteriors[window] = refine_res[window]['ABF'] * window_priors[window]\n posterior_sum = np.sum(list(posteriors.values()))\n for window in windows:\n refine_res[window]['PIP'] = posteriors[window] / posterior_sum\n\n # Define credible set as sum of ranked PIPs >= credset_val\n credset_coords, credset_bt, credset_windows \\\n = make_cs(refine_res, cs_val, cs_merge_buffer)\n\n return refine_res, credset_coords, credset_bt, credset_windows\n\n\ndef parse_stats(stats_in, primary_p_cutoff, p_is_phred=True, \n secondary_p_cutoff=0.05, n_nominal_cutoff=2, \n secondary_or_nominal=True, fdr_q_cutoff=0.05,\n secondary_for_fdr=False, sig_only=False, keep_windows=None,\n refine_secondary=False):\n \"\"\"\n Parse all association stats for a single phenotype\n \"\"\"\n\n stats_dict = {} \n\n if path.splitext(stats_in)[1] in '.gz .bgz .bgzip'.split():\n csvin = gzip.open(stats_in, 'rt')\n else:\n csvin = open(stats_in)\n reader = csv.reader(csvin, delimiter='\\t')\n\n\n for chrom, start, end, n_nominal, top_cohort, excluded_cohorts, case_freq, \\\n control_freq, lnOR, lnOR_lower, lnOR_upper, zscore, primary_p, primary_q, \\\n secondary_lnOR, secondary_lnOR_lower, secondary_lnOR_upper, \\\n secondary_zscore, secondary_p, secondary_q \\\n in reader:\n\n # Skip header line\n if chrom.startswith('#'):\n continue\n\n # Set window id\n window = '_'.join([chrom, start, end])\n\n # If optioned, restrict on window name\n if keep_windows is not None:\n if window not in keep_windows:\n continue\n\n # Clean up window data\n primary_p = format_stat(primary_p, p_is_phred, 1)\n primary_q = format_stat(primary_q, p_is_phred, 1)\n secondary_p = format_stat(secondary_p, p_is_phred, 1)\n n_nominal = int(n_nominal)\n sig_label = get_sig_label(primary_p, secondary_p, n_nominal, primary_q, \n primary_p_cutoff, secondary_p_cutoff, \n n_nominal_cutoff, secondary_or_nominal, \n fdr_q_cutoff, secondary_for_fdr)\n gw_sig = False\n fdr_sig = False\n if sig_label == 'GWS':\n gw_sig = True\n fdr_sig = True\n elif sig_label == 'FDR':\n fdr_sig = True\n case_freq = format_stat(case_freq)\n control_freq = format_stat(control_freq)\n if refine_secondary:\n use_lnOR = format_stat(secondary_lnOR)\n use_lnOR_lower = format_stat(secondary_lnOR_lower)\n use_lnOR_upper = format_stat(secondary_lnOR_upper)\n use_zscore = format_stat(secondary_zscore)\n else:\n use_lnOR = format_stat(lnOR)\n use_lnOR_lower = format_stat(lnOR_lower)\n use_lnOR_upper = format_stat(lnOR_upper)\n use_zscore = format_stat(zscore)\n window_stats = {'case_freq' : case_freq, 'control_freq' : control_freq,\n 'lnOR' : use_lnOR, 'lnOR_lower' : use_lnOR_lower,\n 'lnOR_upper' : use_lnOR_upper, 'zscore' : use_zscore,\n 'primary_p' : primary_p, 'primary_q' : primary_q, \n 'secondary_p' : secondary_p, 'n_nominal' : n_nominal, \n 'gw_sig' : gw_sig, 'fdr_sig' : fdr_sig}\n\n # Store window association stats\n if sig_only:\n if sig_label in 'GWS FDR'.split():\n window_bt = pbt.BedTool('\\t'.join([chrom, start, end, window]), \n from_string=True)\n window_stats['window_bt'] = window_bt\n stats_dict[window] = window_stats\n else:\n window_bt = pbt.BedTool('\\t'.join([chrom, start, end, window]), \n from_string=True)\n window_stats['window_bt'] = window_bt\n stats_dict[window] = window_stats\n\n csvin.close()\n\n return stats_dict\n\n\ndef process_hpo(hpo, stats_in, primary_p_cutoff, p_is_phred=True, \n secondary_p_cutoff=0.05, n_nominal_cutoff=2, \n secondary_or_nominal=True, fdr_q_cutoff=0.05, \n secondary_for_fdr=False, block_merge_dist=200000, \n block_prefix='window_block', null_variance=0.42 ** 2, \n refine_secondary=False, cs_val=0.95):\n \"\"\"\n Loads & processes all necessary data for a single phenotype\n Returns a dict with the following entries:\n sig_windows : dict of sig windows, with each entry corresponding to stats\n for a single significant window\n all_windows : dict of sig windows + all windows within block_merge_dist with\n stats per window\n blocks : pbt.BedTool of all clustered windows to be refined\n \"\"\"\n\n hpo_info = {'blocks' : {}}\n se_by_chrom = {}\n\n # First pass: parse data for significant windows only\n hpo_info['sig_windows'] = parse_stats(stats_in, primary_p_cutoff, p_is_phred, \n secondary_p_cutoff, n_nominal_cutoff, \n secondary_or_nominal, fdr_q_cutoff,\n secondary_for_fdr, sig_only=True, \n refine_secondary=refine_secondary)\n\n # Second pass: parse data for all windows within block_merge_dist of sig_windows\n if len(hpo_info['sig_windows']) > 0:\n # Make bt of significant windows\n sig_window_bts = [g['window_bt'] for g in hpo_info['sig_windows'].values()]\n if len(sig_window_bts) > 1:\n sig_windows_bt = sig_window_bts[0].cat(*sig_window_bts[1:], postmerge=False).sort()\n else:\n sig_windows_bt = sig_window_bts[0]\n\n # Intersect sig windows with all windows\n all_windows_bt = pbt.BedTool(stats_in).cut(range(3)).sort()\n nearby_windows_bt = all_windows_bt.closest(sig_windows_bt.sort(), d=True).\\\n filter(lambda x: int(x[-1]) > -1 and \\\n int(x[-1]) <= block_merge_dist).\\\n saveas()\n nearby_windows = ['_'.join([x.chrom, str(x.start), str(x.end)]) for x in nearby_windows_bt]\n\n # Gather window stats\n hpo_info['all_windows'] = parse_stats(stats_in, primary_p_cutoff, p_is_phred, \n secondary_p_cutoff, n_nominal_cutoff, \n secondary_or_nominal, fdr_q_cutoff,\n secondary_for_fdr, sig_only=False,\n keep_windows=nearby_windows, \n refine_secondary=refine_secondary)\n\n # Cluster significant windows into blocks to be refined\n window_bts = [g['window_bt'] for g in hpo_info['all_windows'].values()]\n if len(window_bts) > 1:\n windows_bt = window_bts[0].cat(*window_bts[1:], postmerge=False).sort()\n else:\n windows_bt = window_bts[0]\n blocks = windows_bt.merge(d=block_merge_dist, c=4, o='distinct')\n\n # Assign block IDs\n blocks_wids = {'_'.join([hpo, block_prefix, str(k)]) : block for k, block in enumerate(blocks)}\n\n # Perform initial refinment of each block with flat prior\n for block_id, block in blocks_wids.items():\n windows = block[3].split(',')\n window_priors = {window : 1 / len(windows) for window in windows}\n refine_res, credset_coords, credset_bt, credset_windows \\\n = refine(window_priors, hpo_info['all_windows'], null_variance,\n cs_val, block_merge_dist)\n hpo_info['blocks'][block_id] = {'coords' : block,\n 'refine_res' : refine_res,\n 'credset_coords' : credset_coords,\n 'credset_bt' : credset_bt,\n 'credset_windows' : credset_windows}\n\n # If no windows are significant, add empty placeholder dict for all windows\n else:\n hpo_info['all_windows'] = {}\n\n return hpo_info\n\n\ndef load_all_hpos(statslist, secondary_p_cutoff=0.05, n_nominal_cutoff=2, \n secondary_or_nominal=True, fdr_q_cutoff=0.05, \n secondary_for_fdr=False, block_merge_dist=200000, \n block_prefix='window_block', refine_secondary=False, \n cs_val=0.95):\n \"\"\"\n Wrapper function to process each HPO with process_hpo()\n Returns a dict with one entry per HPO\n \"\"\"\n\n hpo_data = {}\n\n with open(statslist) as infile:\n reader = csv.reader(infile, delimiter='\\t')\n for hpo, stats_in, pval, in reader:\n primary_p_cutoff = float(pval)\n hpo_data[hpo] = process_hpo(hpo, stats_in, primary_p_cutoff, \n p_is_phred=True, \n secondary_p_cutoff=secondary_p_cutoff, \n n_nominal_cutoff=n_nominal_cutoff, \n secondary_or_nominal=secondary_or_nominal,\n fdr_q_cutoff=fdr_q_cutoff,\n secondary_for_fdr=secondary_for_fdr,\n block_merge_dist=block_merge_dist,\n block_prefix=block_prefix,\n refine_secondary=refine_secondary,\n cs_val=cs_val)\n\n return hpo_data\n\n\ndef estimate_null_variance_basic(hpo_data):\n \"\"\"\n Estimates null variance per phenotype from average of all significant windows\n \"\"\"\n\n vardict_all = {hpo : {} for hpo in hpo_data.keys()}\n vardict_sig = {hpo : [] for hpo in hpo_data.keys()}\n vardict_best = {hpo : [] for hpo in hpo_data.keys()}\n\n for hpo, dat in hpo_data.items():\n \n for window, gdat in dat['all_windows'].items():\n # Estimate null variance from effect size per Wakefield, AJHG, 2007\n var = (float(gdat['lnOR']) / 1.96) ** 2\n vardict_all[hpo][window] = var\n if window in dat['sig_windows'].keys():\n vardict_sig[hpo].append(var)\n \n for bdat in dat['blocks'].values():\n bpvals = [(window, dat['all_windows'][window]['primary_p']) for window \\\n in bdat['refine_res'].keys()]\n best_window = sorted(bpvals, key=lambda x: x[1])[0][0]\n vardict_best[hpo].append(vardict_all[hpo][best_window])\n\n # Compute 2 null variance estimates for refining:\n # 1. Mean of all significant windows\n # 2. Mean of all top windows (one per block)\n\n v1 = np.nanmean([x for l in vardict_sig.values() for x in l if x > 0])\n v2 = np.nanmean([x for l in vardict_best.values() for x in l if x > 0])\n\n return [v1, v2]\n\n\ndef estimate_null_variance_gs(gs_lists, statslist, refine_secondary=False):\n \"\"\"\n Estimates null variance for all cases from the average of a list of known causal windows\n \"\"\"\n\n var = []\n\n statspath = open(statslist).readline().rstrip().split('\\t')[1]\n statsbed = pbt.BedTool(statspath)\n if path.splitext(statspath)[1] in '.gz .bgz .bgzip'.split():\n statsfin = gzip.open(statspath, 'rt')\n else:\n statsfin = open(statspath)\n statscols = statsfin.readline().rstrip().split('\\t')\n\n for gspath in gs_lists:\n # Intersect sumstats for highest-level phenotype with GS regions\n gsdf = statsbed.intersect(pbt.BedTool(gspath), u=True, f=1.0).\\\n to_dataframe(names=statscols)\n gsdf['window'] = gsdf[['#chr', 'start', 'end']].astype(str).\\\n aggregate('_'.join, axis=1)\n\n # Read effect sizes per window from highest level phenotype\n if refine_secondary:\n keep_cols = 'window meta_lnOR_secondary'.split()\n else:\n keep_cols = 'window meta_lnOR'.split()\n stats = gsdf.loc[:, keep_cols].rename(columns={'meta_lnOR' : 'lnOR',\n 'meta_lnOR_secondary' : 'lnOR'})\n gs_vars = (stats.lnOR.astype(float) / 1.96) ** 2\n var.append(float(np.nanmean(gs_vars)))\n\n return var\n\n\ndef update_refine(hpo_data, Wsq, cs_val=0.95, block_merge_dist=200000):\n \"\"\"\n Update initial refinement results (flat prior) with null variances\n If multiple Wsqs are provided, uses Bayesian model averaging across them\n \"\"\"\n\n if not isinstance(Wsq, list):\n Wsq = list(Wsq)\n\n for hpo, hdat in hpo_data.items():\n for block_id, bdat in hdat['blocks'].items():\n windows = list(bdat['refine_res'].keys())\n window_priors = {window : 1 / len(windows) for window in windows}\n \n # Compute ABFs and PIPs at each null variance estimate\n bma_input = []\n for W in Wsq:\n refine_res, credset_coords, credset_bt, credset_windows \\\n = refine(window_priors, hpo_data[hpo]['all_windows'], W, \n cs_val, block_merge_dist)\n bma_input.append(refine_res)\n\n # Average ABFs for each window\n refine_res = {w : {} for w in windows}\n for window in windows:\n refine_res[window]['ABF'] \\\n = np.nanmean([s[window]['ABF'] for s in bma_input])\n\n # Recompute PIPs according to averaged ABFs\n ABF_sum = np.nansum([x['ABF'] for x in refine_res.values()])\n for window in windows:\n refine_res[window]['PIP'] = refine_res[window]['ABF'] / ABF_sum\n \n # Recompute credible set based on BMA PIPs\n credset_coords, credset_bt, credset_windows = make_cs(refine_res, cs_val)\n\n # Determine maximum significance level of any window in credible set\n if any([hpo_data[hpo]['all_windows'][wid]['gw_sig'] for wid in credset_windows]):\n credset_max_sig = 'genome_wide'\n elif any([hpo_data[hpo]['all_windows'][wid]['fdr_sig'] for wid in credset_windows]):\n credset_max_sig = 'FDR'\n else:\n credset_max_sig = 'not_significant'\n\n hpo_data[hpo]['blocks'][block_id] = {'refine_res' : refine_res,\n 'credset_coords' : credset_coords,\n 'credset_bt' : credset_bt,\n 'credset_windows' : credset_windows,\n 'credset_max_sig' : credset_max_sig}\n\n return hpo_data\n\n\ndef get_cytobands(bt, cyto_bed):\n \"\"\"\n Return cytoband nomenclature for all cytobands overlapped by bt\n Note: assumes all entries in bt are on the same chromosome\n \"\"\"\n\n chrom = bt[0].chrom\n bands = sorted(list(set([x[-2] for x in bt.intersect(cyto_bed, wb=True)])))\n if len(bands) > 1:\n bandrange = '{}{}-{}'.format(chrom, bands[0], bands[-1])\n else:\n bandrange = chrom + bands[0]\n\n return bandrange\n \n\ndef rename_blocks(hpo_data, cyto_bed, block_prefix):\n \"\"\"\n Rename segments after refinement of final credible sets\n \"\"\"\n\n alpha_map = {i : l for i, l in enumerate(string.ascii_uppercase)}\n\n for hpo, hdat in hpo_data.items():\n old_ids = list(hdat['blocks'].keys())\n for old_id in old_ids:\n binfo = hdat['blocks'][old_id]\n bandrange = get_cytobands(binfo['credset_bt'], cyto_bed)\n # k = len([x for x in hdat['blocks'].keys() if bandrange in x])\n # new_id = '_'.join([hpo, block_prefix, bandrange, alpha_map[k]])\n new_id = '_'.join([hpo, block_prefix, bandrange])\n hpo_data[hpo]['blocks'][new_id] = hpo_data[hpo]['blocks'][old_id]\n hpo_data[hpo]['blocks'].pop(old_id)\n \n return hpo_data\n\n\ndef iv_mean(values, variances, conf=0.95):\n \"\"\"\n Returns inverse-variance weighted mean of values and conf% confidence interval\n \"\"\"\n\n weights = [1 / v for v in variances]\n\n wsum = np.nansum(weights)\n\n numerator = np.nansum([x / v for x, v in zip(values, variances)])\n\n ivm = numerator / wsum\n\n pooled_se = np.sqrt(1 / wsum)\n\n ci_dist = norm.ppf(conf) * pooled_se\n\n return ivm, (ivm - ci_dist, ivm + ci_dist)\n\n\ndef output_assoc_bed(hpo_data, cyto_bed, outfile, cnv='NS'):\n \"\"\"\n Format final list of credible sets with summary statistics\n \"\"\"\n \n cols = 'chr start_min end_max credible_set_id cnv hpo sig_level ' + \\\n 'cytoband mean_control_freq mean_case_freq ' + \\\n 'pooled_ln_or pooled_ln_or_ci_lower pooled_ln_or_ci_upper ' + \\\n 'best_pvalue n_cred_intervals cred_interval_coords cred_intervals_size'\n outfile.write('#' + '\\t'.join(cols.split()) + '\\n')\n\n for hpo in hpo_data.keys():\n for block_id, binfo in hpo_data[hpo]['blocks'].items():\n # Get basic credible set info\n n_cred = len(binfo['credset_coords'])\n cred_coords = ['{}:{}-{}'.format(x[0], x[1], x[2]) for x in binfo['credset_coords']]\n cred_size = np.nansum([x.length for x in binfo['credset_bt']])\n chrom = str(binfo['credset_coords'][0][0])\n start = str(np.nanmin(binfo['credset_bt'].to_dataframe().start))\n end = str(np.nanmax(binfo['credset_bt'].to_dataframe().end))\n windows = sorted(list(set(binfo['credset_windows'])))\n wdat = hpo_data[hpo]['all_windows']\n control_freq = np.nanmean([wdat[w]['control_freq'] for w in windows])\n case_freq = np.nanmean([wdat[w]['case_freq'] for w in windows])\n cytoband = get_cytobands(binfo['credset_bt'], cyto_bed)\n sig_level = binfo['credset_max_sig']\n\n # Get pooled effect size as inverse-variance weighted mean of all windows\n n_windows = len(windows)\n if n_windows > 1:\n wors = [wdat[w]['lnOR'] for w in windows]\n wvars = [ci2se((wdat[w]['lnOR_lower'], wdat[w]['lnOR_upper'])) ** 2 \\\n for w in windows]\n lnor, lnor_ci = iv_mean(wors, wvars)\n lnor_lower, lnor_upper = sorted(lnor_ci)\n\n else:\n lnor = wdat[windows[0]]['lnOR']\n lnor_lower = wdat[windows[0]]['lnOR_lower']\n lnor_upper = wdat[windows[0]]['lnOR_upper']\n\n best_p = np.nanmin([wdat[w]['primary_p'] for w in windows])\n if best_p == 0:\n best_z = np.nanmax([wdat[w]['zscore'] for w in windows])\n best_p = norm.sf(best_z)\n\n # Write credset stats to file\n outline = '\\t'.join([chrom, start, end, block_id, cnv, hpo, sig_level, cytoband])\n outnums_fmt = '\\t{:.3E}\\t{:.3E}\\t{:.3}\\t{:.3}\\t{:.3}\\t{:.3E}'\n outline += outnums_fmt.format(control_freq, case_freq, lnor, lnor_lower, \n lnor_upper, best_p)\n outline += '\\t' + '\\t'.join([str(n_cred), ';'.join(cred_coords), \n str(cred_size)]) + '\\n'\n if sig_level != 'not_significant':\n outfile.write(outline)\n\n outfile.close()\n\n\ndef cluster_credsets(hpo_data, block_merge_dist=200000):\n \"\"\"\n Cluster credible sets across HPOs to collapse overlapping regions\n \"\"\"\n\n # Pool credible sets, tagged with block ID\n pooled_creds_str = ''\n for hdat in hpo_data.values():\n for bid, binfo in hdat['blocks'].items():\n for ci in binfo['credset_bt']:\n pooled_creds_str += '\\t'.join([ci.chrom, str(ci.start), \n str(ci.end), bid]) + '\\n'\n merged_creds_bt = pbt.BedTool(pooled_creds_str, from_string=True).sort().\\\n merge(c=4, o='distinct', d=block_merge_dist)\n\n # Build nx.Graph() of credible sets to be clustered\n G = nx.Graph()\n csids = \\\n list(set([e for s in [x.split(',') for x in merged_creds_bt.to_dataframe().\\\n iloc[:, 3].tolist()] for e in s]))\n G.add_nodes_from(csids)\n for x in merged_creds_bt:\n creds = x[3].split(',')\n if len(creds) > 1:\n G.add_edges_from(list(combinations(creds, 2)))\n\n # Format each cluster in the graph of credsets\n clustered_credsets = \\\n { 'clustered_region_' + str(i) : x for i, x \\\n in enumerate(nx.connected_components(G))}\n \n return clustered_credsets\n\n\ndef output_loci_bed(hpo_data, final_loci, cyto_bed, outfile, ncase_dict, cnv='NS', \n block_prefix=None):\n \"\"\"\n Format final list of collapsed credible sets and compute pooled summary statistics\n \"\"\"\n\n if block_prefix is None:\n if cnv == 'NS':\n region_id_prefix = 'merged_segment'\n else:\n region_id_prefix = 'merged_{}_segment'.format(cnv)\n else:\n region_id_prefix = 'merged_{}_segment'.format(block_prefix)\n\n cols = 'chr start_min end_max region_id cnv best_sig_level cytoband ' + \\\n 'pooled_control_freq pooled_case_freq ' + \\\n 'pooled_ln_or pooled_ln_or_ci_lower pooled_ln_or_ci_upper ' + \\\n 'min_ln_or max_ln_or n_hpos hpos n_constituent_assocs constituent_assocs ' + \\\n 'n_cred_intervals cred_interval_coords cred_intervals_size'\n outfile.write('#' + '\\t'.join(cols.split()) + '\\n')\n\n out_presort = {}\n\n for members in final_loci.values():\n # Get basic information for credsets in final cluster\n n_members = len(members)\n hpo_dict = {cs : cs.split('_')[0] for cs in members}\n hpos = sorted(list(set(hpo_dict.values())))\n n_hpos = len(hpos)\n credints_dict = {cs : hpo_data[hpo]['blocks'][cs]['credset_coords'] for cs, hpo in hpo_dict.items()}\n credints_bts = [hpo_data[hpo]['blocks'][cs]['credset_bt'] for cs, hpo in hpo_dict.items()]\n if n_members > 1:\n credints_bt = credints_bts[0].cat(*credints_bts[1:], postmerge=False).sort().merge()\n else:\n credints_bt = credints_bts[0].sort().merge()\n n_credints = len(credints_bt)\n credints_size = np.nansum([x.length for x in credints_bt])\n credints_coords = ['{}:{}-{}'.format(x.chrom, x.start, x.end) for x in credints_bt]\n \n # Get region-level basic information\n chrom = credints_bt[0].chrom\n start = str(np.nanmin(credints_bt.to_dataframe().start))\n end = str(np.nanmax(credints_bt.to_dataframe().end))\n cytoband = get_cytobands(credints_bt, cyto_bed)\n region_id = '_'.join([region_id_prefix, '{}', cytoband])\n\n # Summarize HPO-specific information pooled across all windows from each\n # contributing credset (note: *not* all windows for all merged cred intervals)\n windows_dict = {hpo : hpo_data[hpo]['blocks'][bid]['credset_windows'] \\\n for bid, hpo in hpo_dict.items()}\n # Compute pooled control & case frequencies as mean weighted by np.sqrt(N_cases)\n control_freq_dict, case_freq_dict = {}, {}\n for hpo, windows in windows_dict.items():\n control_freq_dict[hpo] = \\\n np.nanmean([hpo_data[hpo]['all_windows'][w]['control_freq'] for w in windows])\n case_freq_dict[hpo] = \\\n np.nanmean([hpo_data[hpo]['all_windows'][w]['case_freq'] for w in windows])\n control_freq = np.nanmean(list(control_freq_dict.values()))\n case_weights = [np.sqrt(ncase_dict[hpo]) for hpo in case_freq_dict.keys()]\n case_freq = np.average(list(case_freq_dict.values()), weights=case_weights)\n # Compute pooled effect size as inverse-variance weighted average\n lnor_means, lnor_cis = {}, {}\n for hpo in hpos:\n wdat = hpo_data[hpo]['all_windows']\n hlnors = [wdat[w]['lnOR'] for w in windows_dict[hpo]]\n hvars = [ci2se((wdat[w]['lnOR_lower'], wdat[w]['lnOR_upper'])) ** 2 \\\n for w in windows_dict[hpo]]\n hlnor, hlnor_ci = iv_mean(hlnors, hvars)\n lnor_means[hpo] = hlnor\n lnor_cis[hpo] = sorted(hlnor_ci)\n min_lnor = np.nanmin(list(lnor_means.values()))\n max_lnor = np.nanmax(list(lnor_means.values()))\n lnor, lnor_ci = \\\n iv_mean(list(lnor_means.values()), \n [ci2se(tuple(ci)) ** 2 for ci in lnor_cis.values()])\n # Get best significance level from any window\n sig_levels = [hpo_data[hpo]['blocks'][bid]['credset_max_sig'] for bid, hpo in hpo_dict.items()]\n if 'genome_wide' in sig_levels:\n best_sig_level = 'genome_wide'\n elif 'FDR' in sig_levels:\n best_sig_level = 'FDR'\n else:\n best_sig_level = 'not_significant'\n\n # Prepare to write region stats to file\n out_front = '\\t'.join([chrom, start, end])\n out_back = '\\t'.join([cnv, best_sig_level, cytoband])\n outnums_fmt = '\\t{:.3E}\\t{:.3E}\\t{:.3}\\t{:.3}\\t{:.3}\\t{:.3}\\t{:.3}'\n out_back += outnums_fmt.format(control_freq, case_freq, lnor, lnor_ci[0], \n lnor_ci[1], min_lnor, max_lnor)\n out_back += '\\t' + '\\t'.join([str(n_hpos), ';'.join(hpos), \n str(n_members), ';'.join(sorted(members)),\n str(n_credints), ';'.join(credints_coords),\n str(credints_size)]) + '\\n'\n if best_sig_level != 'not_significant':\n out_presort[(int(chrom), int(start), int(end))] = [out_front, region_id, out_back]\n\n # Iterate over sorted blocks and write to file\n for i, key in enumerate(sorted(out_presort.keys())):\n outline = '\\t'.join([out_presort[key][0], \n out_presort[key][1].format(i+1), \n out_presort[key][2]])\n outfile.write(outline)\n\n outfile.close()\n\n\ndef main():\n \"\"\"\n Command-line main block\n \"\"\"\n\n # Parse command line arguments and options\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument('statslist', help='tsv of metadata per phenotype. Three ' +\n 'required columns: HPO, path to meta-analysis stats, ' +\n 'and primary P-value cutoff.')\n parser.add_argument('hpos_by_cohort', help='tsv of sample sizes per HPO.')\n parser.add_argument('--secondary-p-cutoff', help='Maximum secondary P-value to ' + \n 'consider as significant. [default: 1]', default=1, type=float)\n parser.add_argument('--cnv', help='Indicate CNV type. [default: NS]', default='NS')\n parser.add_argument('--min-nominal', help='Minimum number of individual cohorts ' + \n 'required to be nominally significant to consider ' +\n 'significant. [default: 0]', default=0, type=int)\n parser.add_argument('--secondary-or-nominal', dest='secondary_or_nom', \n help='Allow windows to meet either --secondary-p-cutoff ' +\n 'or --min-nominal, but do not require both. ' +\n '[default: require both]', default=False, action='store_true')\n parser.add_argument('--fdr-q-cutoff', help='Maximum FDR Q-value to ' + \n 'consider as FDR significant. [default: 0.05]', \n default=0.05, type=float)\n parser.add_argument('--secondary-for-fdr', action='store_true', \n default=False, help='Apply sample secondary and/or min. ' +\n 'nominal criteria when evaluating FDR significance. ' +\n '[default: apply no secondary criteria to FDR segments]')\n parser.add_argument('--credible-sets', dest='cs_val', type=float, default=0.95,\n help='Credible set value. [default: 0.95]')\n parser.add_argument('--distance', help='Distance to pad each significant window ' +\n 'prior to refinement. [default: 1Mb]', default=1000000, \n type=int)\n parser.add_argument('--known-causal-loci-list', help='.tsv list of paths to ' +\n '.bed lists of known causal loci. Used for estimating null ' +\n 'variance. Can be specified multiple times. [default: ' +\n 'no known causal regions]', dest='gs_list')\n parser.add_argument('--cytobands', help='BED of chromosome cytobands. Used ' +\n 'for naming regions. Optional. [default: name based on coordinates]')\n parser.add_argument('--refine-secondary', action='store_true', default=False,\n help='Use secondary association statistics for segment refinement ' + \n '[default: use primary association stats]')\n parser.add_argument('--sig-loci-bed', help='Output BED of significant segments ' +\n 'and their overall association statistics.')\n parser.add_argument('--sig-assoc-bed', help='Output BED of significant ' +\n 'segment-phenotype pairs and their corresponding association ' +\n 'statistics.')\n parser.add_argument('--prefix', help='Prefix for naming loci & associations.')\n args = parser.parse_args()\n\n # Set block prefix\n block_prefix_components = ['segment']\n if args.prefix is not None:\n block_prefix_components.insert(0, args.prefix)\n if args.cnv is not None and args.cnv != 'NS':\n block_prefix_components.insert(0, args.cnv)\n else:\n block_prefix_components.insert(0, 'sig')\n block_prefix = '_'.join(block_prefix_components)\n\n # Process data per hpo\n hpo_data = load_all_hpos(args.statslist, args.secondary_p_cutoff, \n args.min_nominal, args.secondary_or_nom, \n args.fdr_q_cutoff, args.secondary_for_fdr,\n args.distance, block_prefix, \n args.refine_secondary, args.cs_val)\n\n # Estimate null variance based on:\n # 1. all significant windows\n # 2. most significant window per block\n # 3. known causal regions (optional; can be multiple lists)\n Wsq = estimate_null_variance_basic(hpo_data)\n if args.gs_list is not None:\n with open(args.gs_list) as gsf:\n Wsq += estimate_null_variance_gs(gsf.read().splitlines(), args.statslist)\n Wsq = sorted(Wsq)\n print('Null variance estimates: ' + ', '.join([str(round(x, 3)) for x in Wsq]))\n\n # Update original refinement results with BMA of re-estimated null variances\n hpo_data = update_refine(hpo_data, Wsq, args.cs_val, args.distance)\n\n # Rename all blocks according to cytobands of credible sets, if optioned\n if args.cytobands is not None:\n hpo_data = rename_blocks(hpo_data, args.cytobands, block_prefix)\n\n # Format & write final table of significant associations\n if args.sig_assoc_bed is not None:\n sig_assoc_bed = open(args.sig_assoc_bed, 'w')\n output_assoc_bed(hpo_data, args.cytobands, sig_assoc_bed, args.cnv)\n\n # Cluster credible sets across HPOs\n final_loci = cluster_credsets(hpo_data, args.distance)\n\n # Read dict of N_case per HPO\n ncase_df = pd.read_csv(args.hpos_by_cohort, sep='\\t').loc[:, '#HPO Total'.split()]\n ncase_df.index = ncase_df.iloc[:, 0]\n ncase_dict = ncase_df.drop(columns='#HPO').transpose().to_dict(orient='records')[0]\n\n # Format & write final table of significant regions\n if args.sig_loci_bed is not None:\n sig_loci_bed = open(args.sig_loci_bed, 'w')\n output_loci_bed(hpo_data, final_loci, args.cytobands, sig_loci_bed, \n ncase_dict, args.cnv, block_prefix.replace('_segment', ''))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"analysis/sliding_windows/refine_significant_regions.py","file_name":"refine_significant_regions.py","file_ext":"py","file_size_in_byte":37290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"377690663","text":"\nfrom enum import Enum, unique\n\n@unique\nclass OutPin(Enum):\n \"\"\"Current pinout for control OUTPUTS for Autokote Pro system\"\"\"\n TableUp=25\n TableDown=7\n VacAir=5\n LaminatorHeat=6\n NipsSolenoid=12\n UnwindBrake=13\n ChainClutch=19\n\n# Descriptions for each pin to be used in UI\noutpin_desc = {\n OutPin.TableUp:\"Raise the feeder table\",\n OutPin.TableDown:\"Lower the feeder table\",\n OutPin.VacAir:\"Activate Vacuum & Air Pumps\",\n OutPin.LaminatorHeat:\"Turn on the roller heat\",\n OutPin.NipsSolenoid:\"Close the nips\",\n OutPin.UnwindBrake:\"Engage the plastic unwinding brake\",\n OutPin.ChainClutch:\"Engage the driver motor\"\n}\n\n","sub_path":"app/enum/outpins.py","file_name":"outpins.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"316340713","text":"from astropy.io import fits\nfrom banzai.utils import date_utils\nfrom banzai.utils import fits_utils\nfrom banzai import dbs\nimport numpy as np\nimport os\n\n\nclass Image(object):\n\n def __init__(self, filename=None, data=None, header={}, bpm=None):\n\n if filename is not None:\n data, header, bpm = fits_utils.open_image(filename)\n if '.fz' == filename[-3:]:\n filename = filename[:-3]\n self.filename = os.path.basename(filename)\n\n self.data = data\n self.header = header\n self.bpm = bpm\n\n self.site = header.get('SITEID')\n self.instrument = header.get('INSTRUME')\n self.epoch = header.get('DAY-OBS')\n self.nx = header.get('NAXIS1')\n self.ny = header.get('NAXIS2')\n\n self.gain = header.get('GAIN')\n self.ccdsum = header.get('CCDSUM')\n self.filter = header.get('FILTER')\n self.telescope_id = dbs.get_telescope_id(self.site, self.instrument)\n\n self.obstype = header.get('OBSTYPE')\n self.exptime = float(header.get('EXPTIME'))\n self.dateobs = date_utils.parse_date_obs(header.get('DATE-OBS'))\n self.readnoise = float(header.get('RDNOISE'))\n self.ra, self.dec = fits_utils.parse_ra_dec(header)\n self.pixel_scale = float(header.get('PIXSCALE'))\n self.catalog = None\n\n def subtract(self, value):\n self.data -= value\n\n def writeto(self, filename, fpack=False):\n image_hdu = fits.PrimaryHDU(self.data.astype(np.float32), header=self.header)\n image_hdu.header['EXTEND'] = True\n image_hdu.update_ext_name('SCI')\n hdu_list = [image_hdu]\n if self.catalog is not None:\n table_hdu = fits_utils.table_to_fits(self.catalog)\n table_hdu.update_ext_name('CAT')\n hdu_list.append(table_hdu)\n if self.bpm is not None:\n bpm_hdu = fits.ImageHDU(self.bpm.astype(np.uint8))\n bpm_hdu.update_ext_name('BPM')\n hdu_list.append(bpm_hdu)\n\n hdu_list = fits.HDUList(hdu_list)\n hdu_list.writeto(filename, clobber=True)\n if fpack:\n if os.path.exists(filename + '.fz'):\n os.remove(filename + '.fz')\n os.system('fpack -q 64 {0}'.format(filename))\n os.remove(filename)\n self.filename += '.fz'\n\n def update_shape(self, nx, ny):\n self.nx = nx\n self.ny = ny\n\n def write_catalog(self, filename, nsources=None):\n if self.catalog is None:\n raise MissingCatalogException\n else:\n self.catalog[:nsources].write(filename, format='fits', overwrite=True)\n\n def add_history(self, msg):\n self.header.add_history(msg)\n\n\nclass InhomogeneousSetException(Exception):\n pass\n\n\ndef check_image_homogeneity(images):\n for attribute in ('nx', 'ny', 'ccdsum', 'epoch', 'site', 'instrument'):\n if len({getattr(image, attribute) for image in images}) > 1:\n raise InhomogeneousSetException('Images have different {}s'.format(attribute))\n return images[0]\n\n\nclass MissingCatalogException(Exception):\n pass\n","sub_path":"banzai/images.py","file_name":"images.py","file_ext":"py","file_size_in_byte":3117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"353931683","text":"\nfrom common.general.helper_classes import Sequence, retained_set\nimport xml.etree.ElementTree as ET\nfrom common.ai import nlp_helper\nimport time\nimport re\nimport logging\nfrom common.appium import element\nfrom common.appium.element import NonUi\n\n\ndef is_pb_displayed(dom, driver):\n\n try:\n xml = dom.source\n if xml.find('ProgressBar') >= 0:\n pb = driver.find_element_by_xpath('//*[contains(@class, \"ProgressBar\")]')\n if pb.is_displayed():\n return True\n else:\n return False\n except Exception as e:\n # Appium will except if xpath does not find the element\n logging.warning(\"PROGRESS BAR {ex}\".format(ex=e))\n return False\n\n\ndef waiting_for_dom(dom, e, driver, platform):\n\n #TODO: Check if ProgressBar is in the DOM. Need to be careful, might be cases where the progressbard is already built in but dormant\n element_found = False\n\n exceptions = []\n tries = 5\n timeout = 0\n\n # Hang in a loop until first element found or timeout exceeded\n while not dom or (e and not element_found):\n\n #logging.warning(\"WAITING FOR DOM {e}\".format(e=''))\n\n try:\n dom = DOM(driver.page_source, platform=platform)\n\n if dom:\n # DOM contains progress bar & it's visible?\n if is_pb_displayed(dom, driver):\n logging.warning(\"PAGE IS STILL LOADING...\")\n time.sleep(1.0)\n timeout += 1\n if timeout > 180:\n #raise Exception('TIMEOUT EXCEEDED WAITING FOR PROGRESS BAR')\n logging.warning(\"Progress bar keeps running after 180\")\n return None, exceptions\n else:\n continue\n\n # First element exists?\n '''\n if e:\n el, exceptions = find_element(driver, e,\n res_id=e.get('resource-id', None),\n content_desc=e.get('content-desc', None),\n cls=e.get('class', None),\n xpath=e.get('xpath', None),\n compare=\"TEXT\")\n if el:\n element_found = True\n '''\n\n except Exception as e:\n logging.warning(\"waiting_for_dom ===>>> Exception while getting dom {ex}\".format(ex=e))\n exceptions.append(e)\n return None, exceptions\n\n time.sleep(0.1)\n tries -= 1\n if tries < 0:\n return dom, exceptions\n\n #logging.warning(\"RETURNED DOM\")\n\n return dom, exceptions\n\nclass DOM:\n\n def __init__(self, source, window_size=(1080, 1920), platform='Android'):\n\n #print(\"DOM SOURCE ==>> \", source)\n\n self.is_loading = False\n self.source = source\n self.root = None\n self.window_size = window_size\n self.key_elements = {}\n self.node_count = 0\n self.elements = []\n self.xml_dom = {}\n self.platform = platform\n\n self.tree = self.create_tree(self.source)\n ## self.remove_overlays() ## No overlay removal: Oct 1st - 2019\n self.elements, self.xml_dom = self.set_elements_and_tree(self.tree)\n\n #self.find_key_elements()\n #logging.warning(\"CREATED DOM with key elements {k}\".format(k=self.key_elements))\n\n self.waiting_for_data = False #self.is_waiting_for_data(self.elements, self.tree)\n\n #TODO:\n\n #5. Traverse the Tree to discover\n #5A. if the DOM has spinner/loader\n #5B. empty recycler view or any other parent element which can hold data\n #5C. Screen is blank\n #5D. What else do we want to discover?\n # Splash Screen, Pop ups\n #6 SIDE NOTE: KEEP THE FOLLOWING FUNCTION IN THE UTILS MODULE LEVEL\n #1. Loop to check if spinner is on the screen. check to combine with find element\n #2. Format the DOM to be used in the FRONTEND.\n #TODO: Consider keeping the String source and do the conversion in the frontend for the functionality of showing the structured DOM\n\n\n def clean_string_source(self, source):\n for i in range(len(source)):\n if source[i].find('Text') != -1:\n tag_length = 4\n index = source[i].find('Text')\n if source[i][index + tag_length + 1] != \"\\\"\":\n source[i] = source[i][:index + tag_length + 1] + source[i][index + tag_length + 2:]\n if source[i].find('ContentDescription') != -1:\n tag_length = 17\n index = source[i].find('ContentDescription')\n if source[i][index + tag_length + 1] != \"\\\"\":\n source[i] = source[i][0:index + tag_length + 2] + source[i][index + tag_length + 3:]\n\n def create_tree(self, string_source):\n\n self.root = ET.fromstring(string_source)\n return self.root\n\n\n def find_key_elements(self):\n\n root = self.tree\n def find_elements(node):\n\n if node is None:\n return\n\n if node.tag == 'android.widget.TextView':\n title = nlp_helper.has_title(node)\n if title:\n self.key_elements['title'] = title\n\n for child in node:\n find_elements(child)\n\n find_elements(root)\n\n\n def set_elements_and_tree(self, tree):\n lst = []\n tree = self.get_initial_node(tree)\n def set_elements_and_tree_helper(root):\n\n is_ui_element = False\n elem = vars(getattr(element, self.platform)(**root.attrib))\n \n if 'widget' in elem and 'bounds' in elem:\n if elem.get('content_desc') or elem.get('resource-id') or elem['widget'] not in NonUi.elements:\n self.node_count += 1\n elem['idx'] = str(self.node_count)\n elem['is_ui'] = True\n is_ui_element = True\n lst.append(elem)\n\n\n key = root.tag\n if key.__contains__('.'): key = key.split('.').pop()\n if 'instance' in elem: key = key + elem['instance']\n tree_dom = {'name': key, 'idx': str(self.node_count), 'is_ui': is_ui_element}\n if 'resource-id' in elem: tree_dom.update({'resource_id': elem['resource-id']})\n if 'text' in elem: tree_dom.update({'text': elem['text']})\n if 'content_desc' in elem: tree_dom.update({'content_desc': elem['content_desc']})\n\n\n #Need to add if content desc, then add to tree_dom\n\n children = list(root)\n if not children:\n return tree_dom\n\n tree_dom.update({'childNodes': []})\n for child in children:\n entry = set_elements_and_tree_helper(child)\n tree_dom['childNodes'].append(entry)\n return tree_dom\n\n #if tree.tag in NonUi.nodes and len(list(tree)) > 0:\n #tree = list(tree)[0]\n\n xml_dom = set_elements_and_tree_helper(tree)\n\n\n return lst, xml_dom\n\n def get_initial_node(self, node):\n\n if not node: return node\n\n\n key = node.tag\n if key.__contains__('.'): key = key.split('.').pop()\n\n if key not in NonUi.initial_structure:\n return node\n\n next_node = list(node)[0]\n return self.get_initial_node(next_node)\n\n\n\n def is_waiting_for_data(self, elements, tree):\n return self.exists_progress_bar(elements) or self.exists_empty_view(tree)\n\n # CONSIDER DELETING THIS METHOD, CHECK IF RECURSIVE CHECK FOR PROGRESS BAR IS ROBUST #\n def exists_progress_bar(self, elements):\n for element in elements:\n if element['class'] == 'android.widget.ProgressBar':\n return True\n return False\n\n def exists_empty_view(self, tree):\n\n def exists_empty_view_helper(tree):\n if len(list(tree)) == 0:\n if \"LinearLayout\" in tree.attrib['class'] or \"ViewGroup\" in tree.attrib['class']:\n print(tree.attrib['class'])\n return True\n if \"HorizontalScroll\" in tree.attrib['class'] or 'VerticalScroll' in tree.attrib['class']:\n print(tree.attrib['class'])\n return True\n if \"ListView\" in tree.attrib['class'] or \"RecyclerView\" in tree.attrib['class']:\n print(tree.attrib['class'])\n return True\n # REDUNDANT CHECK FOR PROGRESS BAR #\n if \"ProgressBar\" in tree.attrib['class']:\n return True\n\n # if \"TextView\" in tree.attrib['class'] and tree.attrib['text'] == \"\":\n # print(tree.attrib['class'])\n # return True\n\n # other edge cases: yelp has a frame layout containing an image of the spinner, the resource id\n # is \"spinner\", can we also check for that?\n else:\n for child in tree:\n check = exists_empty_view_helper(child)\n if check:\n return True\n\n exists_empty = exists_empty_view_helper(tree)\n return exists_empty is True\n\n def is_valid_frame_size(self, root, screen_width, screen_height, ratio=0.6):\n if not root.attrib.get('bounds'):\n return False\n\n bounds = root.attrib.get('bounds')[1:-1].split('][')\n\n # [352, 1746][382, 1794]\n for b in range(len(bounds)):\n bounds[b] = bounds[b].split(',')\n bounds[b][0] = int(bounds[b][0])\n bounds[b][1] = int(bounds[b][1])\n x_length = bounds[1][0] - bounds[0][0]\n y_length = bounds[1][1] - bounds[0][1]\n\n if x_length >= screen_width * ratio and y_length >= screen_height * ratio:\n return False\n return True\n\n\nif __name__ == \"__main__\":\n #page_source = ' '\n\n page_source = ''\n d = DOM(page_source, platform='Ios')","sub_path":"appium/xml_dom.py","file_name":"xml_dom.py","file_ext":"py","file_size_in_byte":11529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"427490622","text":"# -*- coding: utf-8 -*-\n\"\"\"\nProfile: http://hl7.org/fhir/StructureDefinition/Parameters\nRelease: STU3\nVersion: 3.0.2\nRevision: 11917\nLast updated: 2019-10-24T11:53:00+11:00\n\"\"\"\nimport typing\n\nfrom pydantic import Field, root_validator\nfrom pydantic.error_wrappers import ErrorWrapper, ValidationError\nfrom pydantic.errors import MissingError, NoneIsNotAllowedError\n\nfrom . import backboneelement, fhirtypes, resource\n\n\nclass Parameters(resource.Resource):\n \"\"\"Disclaimer: Any field name ends with ``__ext`` doesn't part of\n Resource StructureDefinition, instead used to enable Extensibility feature\n for FHIR Primitive Data Types.\n\n Operation Request or Response.\n This special resource type is used to represent an operation request and\n response (operations.html). It has no other use, and there is no RESTful\n endpoint associated with it.\n \"\"\"\n\n resource_type = Field(\"Parameters\", const=True)\n\n parameter: typing.List[fhirtypes.ParametersParameterType] = Field(\n None,\n alias=\"parameter\",\n title=\"Operation Parameter\",\n description=\"A parameter passed to or received from the operation.\",\n # if property is element of this resource.\n element_property=True,\n )\n\n @classmethod\n def elements_sequence(cls):\n \"\"\"returning all elements names from\n ``Parameters`` according specification,\n with preserving original sequence order.\n \"\"\"\n return [\"id\", \"meta\", \"implicitRules\", \"language\", \"parameter\"]\n\n\nclass ParametersParameter(backboneelement.BackboneElement):\n \"\"\"Disclaimer: Any field name ends with ``__ext`` doesn't part of\n Resource StructureDefinition, instead used to enable Extensibility feature\n for FHIR Primitive Data Types.\n\n Operation Parameter.\n A parameter passed to or received from the operation.\n \"\"\"\n\n resource_type = Field(\"ParametersParameter\", const=True)\n\n name: fhirtypes.String = Field(\n None,\n alias=\"name\",\n title=\"Name from the definition\",\n description=\"The name of the parameter (reference to the operation definition).\",\n # if property is element of this resource.\n element_property=True,\n element_required=True,\n )\n name__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_name\", title=\"Extension field for ``name``.\"\n )\n\n part: typing.List[fhirtypes.ParametersParameterType] = Field(\n None,\n alias=\"part\",\n title=\"Named part of a multi-part parameter\",\n description=\"A named part of a multi-part parameter.\",\n # if property is element of this resource.\n element_property=True,\n )\n\n resource: fhirtypes.ResourceType = Field(\n None,\n alias=\"resource\",\n title=\"If parameter is a whole resource\",\n description=\"If the parameter is a whole resource.\",\n # if property is element of this resource.\n element_property=True,\n )\n\n valueAddress: fhirtypes.AddressType = Field(\n None,\n alias=\"valueAddress\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueAge: fhirtypes.AgeType = Field(\n None,\n alias=\"valueAge\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueAnnotation: fhirtypes.AnnotationType = Field(\n None,\n alias=\"valueAnnotation\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueAttachment: fhirtypes.AttachmentType = Field(\n None,\n alias=\"valueAttachment\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueBase64Binary: fhirtypes.Base64Binary = Field(\n None,\n alias=\"valueBase64Binary\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n valueBase64Binary__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None,\n alias=\"_valueBase64Binary\",\n title=\"Extension field for ``valueBase64Binary``.\",\n )\n\n valueBoolean: bool = Field(\n None,\n alias=\"valueBoolean\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n valueBoolean__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_valueBoolean\", title=\"Extension field for ``valueBoolean``.\"\n )\n\n valueCode: fhirtypes.Code = Field(\n None,\n alias=\"valueCode\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n valueCode__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_valueCode\", title=\"Extension field for ``valueCode``.\"\n )\n\n valueCodeableConcept: fhirtypes.CodeableConceptType = Field(\n None,\n alias=\"valueCodeableConcept\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueCoding: fhirtypes.CodingType = Field(\n None,\n alias=\"valueCoding\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueContactPoint: fhirtypes.ContactPointType = Field(\n None,\n alias=\"valueContactPoint\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueCount: fhirtypes.CountType = Field(\n None,\n alias=\"valueCount\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueDate: fhirtypes.Date = Field(\n None,\n alias=\"valueDate\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n valueDate__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_valueDate\", title=\"Extension field for ``valueDate``.\"\n )\n\n valueDateTime: fhirtypes.DateTime = Field(\n None,\n alias=\"valueDateTime\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n valueDateTime__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_valueDateTime\", title=\"Extension field for ``valueDateTime``.\"\n )\n\n valueDecimal: fhirtypes.Decimal = Field(\n None,\n alias=\"valueDecimal\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n valueDecimal__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_valueDecimal\", title=\"Extension field for ``valueDecimal``.\"\n )\n\n valueDistance: fhirtypes.DistanceType = Field(\n None,\n alias=\"valueDistance\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueDuration: fhirtypes.DurationType = Field(\n None,\n alias=\"valueDuration\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueHumanName: fhirtypes.HumanNameType = Field(\n None,\n alias=\"valueHumanName\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueId: fhirtypes.Id = Field(\n None,\n alias=\"valueId\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n valueId__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_valueId\", title=\"Extension field for ``valueId``.\"\n )\n\n valueIdentifier: fhirtypes.IdentifierType = Field(\n None,\n alias=\"valueIdentifier\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueInstant: fhirtypes.Instant = Field(\n None,\n alias=\"valueInstant\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n valueInstant__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_valueInstant\", title=\"Extension field for ``valueInstant``.\"\n )\n\n valueInteger: fhirtypes.Integer = Field(\n None,\n alias=\"valueInteger\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n valueInteger__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_valueInteger\", title=\"Extension field for ``valueInteger``.\"\n )\n\n valueMarkdown: fhirtypes.Markdown = Field(\n None,\n alias=\"valueMarkdown\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n valueMarkdown__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_valueMarkdown\", title=\"Extension field for ``valueMarkdown``.\"\n )\n\n valueMeta: fhirtypes.MetaType = Field(\n None,\n alias=\"valueMeta\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueMoney: fhirtypes.MoneyType = Field(\n None,\n alias=\"valueMoney\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueOid: fhirtypes.Oid = Field(\n None,\n alias=\"valueOid\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n valueOid__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_valueOid\", title=\"Extension field for ``valueOid``.\"\n )\n\n valuePeriod: fhirtypes.PeriodType = Field(\n None,\n alias=\"valuePeriod\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valuePositiveInt: fhirtypes.PositiveInt = Field(\n None,\n alias=\"valuePositiveInt\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n valuePositiveInt__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None,\n alias=\"_valuePositiveInt\",\n title=\"Extension field for ``valuePositiveInt``.\",\n )\n\n valueQuantity: fhirtypes.QuantityType = Field(\n None,\n alias=\"valueQuantity\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueRange: fhirtypes.RangeType = Field(\n None,\n alias=\"valueRange\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueRatio: fhirtypes.RatioType = Field(\n None,\n alias=\"valueRatio\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueReference: fhirtypes.ReferenceType = Field(\n None,\n alias=\"valueReference\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueSampledData: fhirtypes.SampledDataType = Field(\n None,\n alias=\"valueSampledData\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueSignature: fhirtypes.SignatureType = Field(\n None,\n alias=\"valueSignature\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueString: fhirtypes.String = Field(\n None,\n alias=\"valueString\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n valueString__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_valueString\", title=\"Extension field for ``valueString``.\"\n )\n\n valueTime: fhirtypes.Time = Field(\n None,\n alias=\"valueTime\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n valueTime__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_valueTime\", title=\"Extension field for ``valueTime``.\"\n )\n\n valueTiming: fhirtypes.TimingType = Field(\n None,\n alias=\"valueTiming\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n\n valueUnsignedInt: fhirtypes.UnsignedInt = Field(\n None,\n alias=\"valueUnsignedInt\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n valueUnsignedInt__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None,\n alias=\"_valueUnsignedInt\",\n title=\"Extension field for ``valueUnsignedInt``.\",\n )\n\n valueUri: fhirtypes.Uri = Field(\n None,\n alias=\"valueUri\",\n title=\"If parameter is a data type\",\n description=\"If the parameter is a data type.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=False,\n )\n valueUri__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_valueUri\", title=\"Extension field for ``valueUri``.\"\n )\n\n @classmethod\n def elements_sequence(cls):\n \"\"\"returning all elements names from\n ``ParametersParameter`` according specification,\n with preserving original sequence order.\n \"\"\"\n return [\n \"id\",\n \"extension\",\n \"modifierExtension\",\n \"name\",\n \"valueBase64Binary\",\n \"valueBoolean\",\n \"valueCode\",\n \"valueDate\",\n \"valueDateTime\",\n \"valueDecimal\",\n \"valueId\",\n \"valueInstant\",\n \"valueInteger\",\n \"valueMarkdown\",\n \"valueOid\",\n \"valuePositiveInt\",\n \"valueString\",\n \"valueTime\",\n \"valueUnsignedInt\",\n \"valueUri\",\n \"valueAddress\",\n \"valueAge\",\n \"valueAnnotation\",\n \"valueAttachment\",\n \"valueCodeableConcept\",\n \"valueCoding\",\n \"valueContactPoint\",\n \"valueCount\",\n \"valueDistance\",\n \"valueDuration\",\n \"valueHumanName\",\n \"valueIdentifier\",\n \"valueMoney\",\n \"valuePeriod\",\n \"valueQuantity\",\n \"valueRange\",\n \"valueRatio\",\n \"valueReference\",\n \"valueSampledData\",\n \"valueSignature\",\n \"valueTiming\",\n \"valueMeta\",\n \"resource\",\n \"part\",\n ]\n\n @root_validator(pre=True, allow_reuse=True)\n def validate_required_primitive_elements_2167(\n cls, values: typing.Dict[str, typing.Any]\n ) -> typing.Dict[str, typing.Any]:\n \"\"\"https://www.hl7.org/fhir/extensibility.html#Special-Case\n In some cases, implementers might find that they do not have appropriate data for\n an element with minimum cardinality = 1. In this case, the element must be present,\n but unless the resource or a profile on it has made the actual value of the primitive\n data type mandatory, it is possible to provide an extension that explains why\n the primitive value is not present.\n \"\"\"\n required_fields = [(\"name\", \"name__ext\")]\n _missing = object()\n\n def _fallback():\n return \"\"\n\n errors: typing.List[\"ErrorWrapper\"] = []\n for name, ext in required_fields:\n field = cls.__fields__[name]\n ext_field = cls.__fields__[ext]\n value = values.get(field.alias, _missing)\n if value not in (_missing, None):\n continue\n ext_value = values.get(ext_field.alias, _missing)\n missing_ext = True\n if ext_value not in (_missing, None):\n if isinstance(ext_value, dict):\n missing_ext = len(ext_value.get(\"extension\", [])) == 0\n elif (\n getattr(ext_value.__class__, \"get_resource_type\", _fallback)()\n == \"FHIRPrimitiveExtension\"\n ):\n if ext_value.extension and len(ext_value.extension) > 0:\n missing_ext = False\n else:\n validate_pass = True\n for validator in ext_field.type_.__get_validators__():\n try:\n ext_value = validator(v=ext_value)\n except ValidationError as exc:\n errors.append(ErrorWrapper(exc, loc=ext_field.alias))\n validate_pass = False\n if not validate_pass:\n continue\n if ext_value.extension and len(ext_value.extension) > 0:\n missing_ext = False\n if missing_ext:\n if value is _missing:\n errors.append(ErrorWrapper(MissingError(), loc=field.alias))\n else:\n errors.append(\n ErrorWrapper(NoneIsNotAllowedError(), loc=field.alias)\n )\n if len(errors) > 0:\n raise ValidationError(errors, cls) # type: ignore\n\n return values\n\n @root_validator(pre=True, allow_reuse=True)\n def validate_one_of_many_2167(\n cls, values: typing.Dict[str, typing.Any]\n ) -> typing.Dict[str, typing.Any]:\n \"\"\"https://www.hl7.org/fhir/formats.html#choice\n A few elements have a choice of more than one data type for their content.\n All such elements have a name that takes the form nnn[x].\n The \"nnn\" part of the name is constant, and the \"[x]\" is replaced with\n the title-cased name of the type that is actually used.\n The table view shows each of these names explicitly.\n\n Elements that have a choice of data type cannot repeat - they must have a\n maximum cardinality of 1. When constructing an instance of an element with a\n choice of types, the authoring system must create a single element with a\n data type chosen from among the list of permitted data types.\n \"\"\"\n one_of_many_fields = {\n \"value\": [\n \"valueAddress\",\n \"valueAge\",\n \"valueAnnotation\",\n \"valueAttachment\",\n \"valueBase64Binary\",\n \"valueBoolean\",\n \"valueCode\",\n \"valueCodeableConcept\",\n \"valueCoding\",\n \"valueContactPoint\",\n \"valueCount\",\n \"valueDate\",\n \"valueDateTime\",\n \"valueDecimal\",\n \"valueDistance\",\n \"valueDuration\",\n \"valueHumanName\",\n \"valueId\",\n \"valueIdentifier\",\n \"valueInstant\",\n \"valueInteger\",\n \"valueMarkdown\",\n \"valueMeta\",\n \"valueMoney\",\n \"valueOid\",\n \"valuePeriod\",\n \"valuePositiveInt\",\n \"valueQuantity\",\n \"valueRange\",\n \"valueRatio\",\n \"valueReference\",\n \"valueSampledData\",\n \"valueSignature\",\n \"valueString\",\n \"valueTime\",\n \"valueTiming\",\n \"valueUnsignedInt\",\n \"valueUri\",\n ]\n }\n for prefix, fields in one_of_many_fields.items():\n assert cls.__fields__[fields[0]].field_info.extra[\"one_of_many\"] == prefix\n required = (\n cls.__fields__[fields[0]].field_info.extra[\"one_of_many_required\"]\n is True\n )\n found = False\n for field in fields:\n if field in values and values[field] is not None:\n if found is True:\n raise ValueError(\n \"Any of one field value is expected from \"\n f\"this list {fields}, but got multiple!\"\n )\n else:\n found = True\n if required is True and found is False:\n raise ValueError(f\"Expect any of field value from this list {fields}.\")\n\n return values\n","sub_path":"fhir/resources/STU3/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":27659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"83559928","text":"# ---------------------------------------------------------------\n# List comprehensions allow us to construct lists from other iterables, such as other lists.\n# ---------------------------------------------------------------\n\n## If I want to use an existing list of prices to create a NEW list that \n# contains the prices + tax, I could create it with a for loop, or use a list comprehension.\n\nprices = [10, 5, 22, 31, 8]\n\n# Price + Tax: For Loop\ntotals = []\nfor i in prices:\n totals.append(i * 1.09)\n\nprint(totals)\n\n# Price + Tax: List Comprehension\ntotals = [i * 1.09 for i in prices]\n\nprint(totals)\n\n# ---------------------------------------------------------------\n# List comprehensions can also construct lists from strings\n# ---------------------------------------------------------------\n\n# In this example, we'd like to create a list of all the letters in a string\n\nfish = \"halibut\"\n\n# We could loop through each letter in the string and append to a list\nletters = []\nfor letter in fish:\n letters.append(letter)\n\nprint(letters)\n\n# Or we could use the more concise list comprehension\nletters = [letter for letter in fish]\nprint(letters)\n\n# We can even manipulate each element as we go with a list comprehension.\ncapital_letters = [letter.upper() for letter in fish]\n\nprint(capital_letters)\n\n# ---------------------------------------------------------------\n# List comprehensions can even apply conditionals\n# ---------------------------------------------------------------\n\n# In this example, we'd like to identify all of the days where temperature > 90\n\n# We could perform this task of applying a conditional using a for loop\njuly_temperatures = [87, 85, 92, 79, 106]\nhot_days = []\nfor temperature in july_temperatures:\n if temperature > 90:\n hot_days.append(temperature)\nprint(hot_days)\n\n# Or we could do this with a comprehension + a conditional.\nhot_days = [temperature for temperature in july_temperatures if temperature > 90]\n\nprint(hot_days)\n","sub_path":"Content/03-Python/03-Dicts_Comprehensions_and_Functions/Activities/04-Evr_List_Comprehensions/Solved/comprehensions.py","file_name":"comprehensions.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"542702060","text":"from sklearn.metrics import roc_curve\nfrom sklearn.metrics import auc\n\ndef plot_roc_curve(target_test, target_predicted_proba):\n fpr, tpr, thresholds = roc_curve(target_test, target_predicted_proba[:, 1])\n roc_auc = auc(fpr, tpr)\n plt.plot(fpr, tpr, label='curva ROC (area = %0.3f)' % roc_auc)\n plt.plot([0, 1], [0, 1], 'k--') # random predictions curve\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.0])\n plt.xlabel('Ratio de Falsos Positivos Rate (1 - Specifity)')\n plt.ylabel('Ratio de Verdaderos Positivos (Sensitivity)')\n plt.title('ROC (Receiver Operating Characteristic)')\n plt.legend(loc=\"lower right\")","sub_path":"plot_roc.py","file_name":"plot_roc.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"203446575","text":"from click import command, option\nimport matrix_factorization_dsgd\n\n@command()\n@option('--num_iterations', default = 5, help='Number of iterations.')\n@option('--num_workers', default = 5, help='Number of workers.')\n@option('--num_factors', default = 5, help='Number of factors.')\n@option('--learning_rate', default = 0.6, help='Learning rate.')\n@option('--reg', default = 0.01, help='Regularization.')\ndef main(num_iterations, num_workers, num_factors, learning_rate, reg):\n DSGD = matrix_factorization_dsgd.Distributed_Stochastic_Gradient_Decent(\n num_iterations, num_workers, num_factors, learning_rate, reg)\n DSGD.train()\n\nif __name__ == '__main__':\n main()","sub_path":"dsgd.py","file_name":"dsgd.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"578358436","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport re\nimport redis\nimport json\n\nfrom os import path\nfrom zbsjwv2.settings import PROVINCE_ABBR_LIST, CRAWL_TYPE, REDIS_PARAMS, BASE_DIR, PROVINCE_ID\n\n# redis 连接\nredis_client = redis.StrictRedis(**REDIS_PARAMS)\n\n# \n\n# 生成链接\n\ndef gen_new_urls(crawl_type):\n '''\n 生成 scrapy 的 start_urls,\n 存入 redis: key= type:start_urls\n '''\n if crawl_type == 'zb':\n key = 'zb:start_urls'\n redis_client.flushdb()\n with open('./crawl_zb_conf.json') as data_file:\n data = json.load(data_file)\n for item in data:\n print('--item--%s' % item)\n area = item['area']\n pages = item['pages']\n if area not in PROVINCE_ABBR_LIST:\n raise Exception('抓取区域错误: %s is not in %r' % (area, PROVINCE_ABBR_LIST))\n\n patt = re.search(r'(^\\d+~\\d+$)|(^\\d+-\\d+$)|(^(\\d+,?)+$)', pages)\n if not patt:\n raise Exception('crawl_zb_conf.json 中包含不合法字符 %s' % pages)\n elif '~' in pages:\n start_page, end_page = pages.split('~')\n pages = range(int(start_page), int(end_page)+1)\n elif ',' in pages:\n pages = pages.split(',')\n elif '-' in pages:\n start_page, end_page = pages.split('-')\n pages = range(int(start_page), int(end_page)+1)\n else:\n pages = [int(pages)]\n\n for page in pages:\n redis_client.lpush(key, \"http://{}.zbsjw.cn/zbmulu-{}-------0-time.html\"\n .format(area, page))\n print ('%s, %s' % (key, \"http://{}.zbsjw.cn/zbmulu-{}-------0-time.html\"\n .format(area, page)))\n\ndef gen_lost_url(crawl_type):\n '''\n 生成有数据丢失页面的url\n '''\n if crawl_type == 'zb':\n key = 'lostzb:start_urls'\n redis_client.flushdb()\n with open(path.join(BASE_DIR, 'lostdump/zb_lost_pages.json'), 'r') as lost_file:\n lost_data = json.load(lost_file)\n page_list = {}\n for item in lost_data:\n page_list[item['page']] = item['area']\n for page, area in page_list.items():\n redis_client.lpush(key, \"http://{}.zbsjw.cn/zbmulu-{}-------0-time.html\"\n .format(area, page))\n print ('%s, %s' % (key, \"http://{}.zbsjw.cn/zbmulu-{}-------0-time.html\"\n .format(area, page)))\n\nif __name__ == '__main__':\n crawl_type = sys.argv[1]\n url_type = 'new'\n if len(sys.argv) > 2:\n url_type = sys.argv[2]\n if url_type not in ('new', 'lost'):\n print('参数2: 生成 urls 类型分为: new or lost')\n raise Exception('参数2: 生成 urls 类型分为: new or lost')\n\n if crawl_type in CRAWL_TYPE:\n if url_type == 'new':\n print('抓取类型为 %s' % crawl_type)\n gen_new_urls(crawl_type)\n elif url_type == 'lost':\n gen_lost_url(crawl_type)\n else:\n print('抓取类型错误: %s is not in %r' % (crawl_type, CRAWL_TYPE))","sub_path":"zbsjwv2/gen_start_urls.py","file_name":"gen_start_urls.py","file_ext":"py","file_size_in_byte":3313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"590632094","text":"### adapted from https://github.com/realpython/materials/tree/master/python-sockets-tutorial\n## more resources in server.py\n\nimport socket\n\nHOST = \"127.0.0.1\" # The server's hostname or IP address\nport_number = 65432 # The port used by the server\n\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as aSocket:\n aSocket.connect((HOST, port_number)) # connect the socket to a host and port\n msg = \"GET / HTTP/1.0\"\n print(\"sending to the server: \", msg)\n aSocket.sendall(msg.encode()) # send your message with utf-8 encoding\n data = aSocket.recv(1024) # wait for a response\n\nprint(\"Received from server: \", data.decode()) #print response\n","sub_path":"http-intro/web-client.py","file_name":"web-client.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"327875907","text":"from flask import Flask\nfrom flask import render_template\nfrom flask import request\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\n\n\napp = Flask(__name__)\n\n\ndef search_google(keyword, start_page, end_page=None):\n url = 'https://www.google.com/search?&q={0}+magnet%3A%3Fxt%3D&oq={0}+magnet%3A%3Fxt%3D&'.format(\n keyword)\n\n header = {\n 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36,gzip(gfe)'}\n\n r = requests.get(url, headers=header)\n bs = BeautifulSoup(r.text, 'lxml')\n links = bs.select('div.g > div > div.rc > div.r > a')\n\n results = []\n\n if end_page is None:\n counts = bs.select('div#resultStats')[0].text.replace(\n '검색결과 약', '').replace('개', '').replace(',', '').split('(')[0].strip()\n end_page = int(int(counts) / 10)\n\n if end_page > 30:\n end_page = 30\n\n number = 0\n\n for a in links:\n href = a['href']\n texta = a.select('h3')\n if len(texta) <= 0:\n continue\n\n title = texta[0].text\n\n # print(href)\n\n try:\n r = requests.get(href)\n bs = BeautifulSoup(r.text, 'lxml')\n magnets = bs.find_all('a', href=re.compile(r'magnet:\\?xt=*'))\n\n # print(title)\n # print('-'*40)\n # print(magnets)\n # print('+'*40)\n\n number += 1\n # print(start_page, '--', number)\n\n if len(magnets) > 0:\n magnet = magnets[0]['href']\n # print(magnet)\n # print('*'*50)\n # print('찾았습니다.')\n\n results.append({\n 'magnet': magnet,\n 'title': title\n })\n\n except:\n pass\n\n if start_page < end_page:\n start_page += 10\n results.extend(search_google(keyword, start_page, end_page=end_page))\n\n return results\n\n\n\n\n\n\n@app.route('/', methods=[\"GET\", \"POST\"])\ndef index():\n if 'keyword' in request.form:\n keyword = request.form['keyword']\n results = search_google(keyword, 0)\n\n\n else:\n results = []\n\n if len(results) > 0:\n return render_template('index.html', **{'magnets':results})\n else:\n return render_template('index.html')\n\n\n\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port = 9995, debug = True)\n\n","sub_path":"crawling/web_magnet.py","file_name":"web_magnet.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"551231667","text":"import datetime\nimport json\n\nfrom django.db.models import Sum\nfrom django.views.generic.base import TemplateView\nfrom django.views.generic import View\nfrom django.http import JsonResponse\nfrom django.shortcuts import render # RENDER() METHOD\nfrom chatterbot import ChatBot\nfrom chatterbot.ext.django_chatterbot import settings\nfrom chatterbot.trainers import ListTrainer\nfrom .models import Botmessage, Userinput\nfrom .budget.models import Budget\n\n\ndef index(request):\n return render(request, 'chatbot/app.html')\n\nclass ChatterBotAppView(TemplateView):\n template_name = 'chatbot/index.html'\n\n chatterbot = ChatBot(**settings.CHATTERBOT)\n\n trainer = ListTrainer(chatterbot)\n\n # Training with Personal Ques & Ans\n conversation = [\n \"Hello\", # user\n \"Hi there\", # bot\n \"How are you\", # user\n \"I am doing great\", # bot\n \"That is good to hear\", # user\n \"Thank you\", # bot\n \"You are welcome\", # user\n \"Is there anything I can help you with\", # bot\n \"Yes please\", # user\n \"Is there anything I can help you with\", # bot\n \"No thank you\", # user\n \"Goodbye then, let's chat again soon\", # bot\n ]\n trainer.train(conversation)\n\n trainer.train([\n \"I spent money\", # user\n \"Please tell me in this format: category XX details XX amount XX\", # bot\n \"category XX details XX amount XX\", # user\n \"I have recorded your spending as requested. Please proceed to /budget to view your records.\", # bot\n ])\n\n trainer.train([\n \"Destroy entry\", # user\n \"Please tell me the id of the entry you would like to delete\", # bot\n \"Destroy entry id\", # user\n \"I have destroyed your entry as requested. Please proceed to /budget to view your records.\", # bot\n ])\n\n trainer.train([\n \"Spending insights\", # user\n \"What would you like to find out about your spending?\", # bot\n \"How much did I spend in\", # user\n \"Look in your console to see the results.\", # bot\n ])\n\n trainer.train([\n \"Spending insights\", # user\n \"What would you like to find out about your spending?\", # bot\n \"How much did I spend on\", # user\n \"Look in your console to see the results.\", # bot\n ])\n\n budgetconvo = [\n \"I spent money\", # user\n \"Please tell me in this format: category XX details XX amount XX\", # bot\n \"category\" and \"details\" and \"amount\", # user\n \"I have recorded your spending as requested. Please proceed to /budget to view your records.\", # bot\n ]\n trainer.train(budgetconvo)\n\n def post(self, request, *args, **kwargs):\n thisuser = request.user\n\n # USERINPUT\n userText = request.POST.get('msg')\n print(userText)\n\n input_data = Userinput(userinput_text=userText, user=thisuser)\n input_data.save()\n\n if \"category\" and \"details\" and \"amount\" in userText:\n # save budget records\n # userinput format is \"category EXAMPLE details EXAMPLE amount EXAMPLE\"\n listofusertext = userText.split()\n category = listofusertext[1].lower()\n details = listofusertext[3].lower()\n amount = float(listofusertext[5])\n\n spendentry = Budget(category=category, details=details, amount=amount, user=thisuser)\n spendentry.save()\n\n # generate bot response and save to botmessage db\n botresp = self.chatterbot.get_response(userText)\n print(botresp)\n\n resp = Botmessage(botmessage_text=botresp, userinput_id=input_data.id, user=thisuser)\n resp.save()\n\n response_data = botresp.serialize()\n return JsonResponse(response_data, status=200)\n elif \"how much\" and \"spend\" in userText:\n listofusertext = userText.split()\n factor = listofusertext[5]\n\n # how much did I spend IN month\n if factor == 'in':\n monthstr = listofusertext[6]\n print(monthstr)\n monthint = datetime.datetime.strptime(monthstr, \"%B\").month\n print(monthint)\n\n recordstosummate = Budget.objects.all().filter(date__month=monthint).values()\n print(recordstosummate)\n\n sum = 0\n for x in recordstosummate:\n sum = sum + float(x[\"amount\"])\n print(sum)\n # how much did I spend ON category\n elif factor == 'on':\n category = listofusertext[6]\n print(category)\n\n recordstosummate = Budget.objects.all().filter(category=category).values()\n print(recordstosummate)\n\n sum = 0\n for x in recordstosummate:\n sum = sum + float(x[\"amount\"])\n print(sum)\n\n botresp = self.chatterbot.get_response(userText)\n print(botresp)\n\n resp = Botmessage(botmessage_text=botresp, userinput_id=input_data.id, user=thisuser)\n resp.save()\n\n response_data = botresp.serialize()\n return JsonResponse(response_data, status=200)\n elif \"Destroy entry id\" in userText:\n # userinput format is \"destroy entry id XXX\"\n listofusertext = userText.split()\n id = int(listofusertext[3])\n\n if id:\n recordtodestroy = Budget.objects.filter(id=id)\n recordtodestroy.delete()\n\n # BOTMESSAGE\n botresp = self.chatterbot.get_response(userText)\n print(botresp)\n\n resp = Botmessage(botmessage_text=botresp, userinput_id=input_data.id, user=thisuser)\n resp.save()\n\n response_data = botresp.serialize()\n return JsonResponse(response_data, status=200)\n else:\n botresp = self.chatterbot.get_response(userText)\n print(botresp)\n\n resp = Botmessage(botmessage_text=botresp, userinput_id=input_data.id, user=thisuser)\n resp.save()\n\n response_data = botresp.serialize()\n return JsonResponse(response_data, status=200)\n else:\n botresp = self.chatterbot.get_response(userText)\n print(botresp)\n\n resp = Botmessage(botmessage_text=botresp, userinput_id=input_data.id, user=thisuser)\n resp.save()\n\n response_data = botresp.serialize()\n return JsonResponse(response_data, status=200)\n\n def get(self, request, *args, **kwargs):\n return render(request, 'chatbot/index.html')\n\nclass ChatterBotApiView(View):\n \"\"\"\n Provide an API endpoint to interact with ChatterBot.\n \"\"\"\n\n chatterbot = ChatBot(**settings.CHATTERBOT)\n\n # Training with Personal Ques & Ans\n conversation = [\n \"Hello\",\n \"Hi there!\",\n \"How are you doing\",\n \"Im doing great\",\n \"That is good to hear\",\n \"Thank you\",\n \"You are welcome\",\n \"goodbye\",\n \"input gaby\",\n \"output gaby\"\n ]\n\n trainer = ListTrainer(chatterbot)\n trainer.train(conversation)\n\n '''\n # Training with English Corpus Data\n trainer_corpus = ChatterBotCorpusTrainer(chatterbot)\n trainer_corpus.train(\n 'chatterbot.corpus.english'\n )\n '''\n\n def post(self, request, *args, **kwargs):\n \"\"\"\n Return a response to the statement in the posted data.\n * The JSON data should contain a 'text' attribute.\n \"\"\"\n input_data = Userinput(userinput_text=json.loads(request.body.decode('utf-8')))\n input_data.save()\n\n print(input_data)\n\n '''\n if 'text' not in input_data:\n return JsonResponse({\n 'text': [\n 'The attribute \"text\" is required.'\n ]\n }, status=400)\n '''\n\n print(json.loads(request.body.decode('utf-8')))\n\n response = self.chatterbot.get_response(json.loads(request.body.decode('utf-8')))\n print(response)\n\n resp = Botmessage(botmessage_text=response, userinput_id=input_data.id)\n resp.save()\n\n response_data = response.serialize()\n return JsonResponse(response_data, status=200)\n\n\n def get(self, request, *args, **kwargs):\n \"\"\"\n Return data corresponding to the current conversation.\n \"\"\"\n return JsonResponse({\n 'name': self.chatterbot.name\n })\n","sub_path":"bobi/chatbot/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"470225916","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\n\nimport requests\n\nfrom .items import DownloadItem\n\n\nclass DownloadSpiderPipeline(object):\n def process_item(self, item, spider):\n if isinstance(item, DownloadItem):\n session = requests.session()\n captcha_content = session.get(item['url']).content\n with open(item['filename']) as fd:\n fd.write(captcha_content)\n","sub_path":"download_spider/download_spider/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"648995394","text":"# import needed modules\n\nimport pygame, time, random\n\n# initialize modules\n\npygame.mixer.pre_init()\npygame.init()\n\n# define needed variables and other pygame stuff\n\nscreenWidth = 1820\nscreenHeight = 980\ngameDisplay = pygame.display.set_mode((screenWidth, screenHeight))\nclock = pygame.time.Clock()\npygame.display.set_caption('Plane Fighting')\n\n# define functions\n\ndef frameUpdate():\n pygame.display.update()\n clock.tick(60)\n\ndef text_objects(text, font):\n textSurface = font.render(text, True, (0, 0, 0))\n return textSurface, textSurface.get_rect()\n\ndef displayMsg(msg, pos, fontSize):\n largeText = pygame.font.Font('freesansbold.ttf', fontSize)\n TextSurf, TextRect = text_objects(msg, largeText)\n TextRect.center = (pos[0], pos[1])\n gameDisplay.blit(TextSurf, TextRect)\n\ndef die():\n backGroundChannel.stop()\n gunFireChannel.stop()\n enemyGunFireChannel.stop()\n playMus(\"Python with AI - Level 2/pygame/planeGame/Explosion+3.wav\")\n exitingDeath = False\n gameDisplay.fill((255, 255, 255, 0))\n displayMsg(\"You died\", (int(screenWidth / 2), int(screenHeight / 2)), 115)\n frameUpdate()\n for x in range(0, 180):\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n exitingDeath = True\n if exitingDeath:\n break\n frameUpdate()\n\ndef playMus(musPath):\n pygame.mixer.music.load(musPath)\n pygame.mixer.music.play()\n\ndef playBackMus(backMusPath):\n pygame.mixer.music.load(backMusPath)\n pygame.mixer.music.play(-1)\n\ndef things(thingx, thingy, thingw, thingh, color):\n pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])\n\ndef button(activeColor, inactiveColor, buttonX, buttonY, buttonWidth, buttonHeight, msg, fontSize):\n things(buttonX, buttonY, buttonWidth, buttonHeight, inactiveColor)\n if pygame.mouse.get_pos()[0] > buttonX and pygame.mouse.get_pos()[0] < buttonX + buttonWidth and pygame.mouse.get_pos()[1] > buttonY and pygame.mouse.get_pos()[1] < buttonY + buttonHeight:\n things(buttonX, buttonY, buttonWidth, buttonHeight, activeColor)\n displayMsg(msg, (buttonX + int(buttonWidth/2), buttonY + int(buttonHeight/2)), fontSize)\n\ndef gameQuit():\n pygame.quit()\n quit()\n\ndef draw(pos, image):\n gameDisplay.blit(image, pos)\n\ndef blitRotate(surf, image, pos, originPos, angle):\n\n # calculate the axis aligned bounding box of the rotated image\n w, h = image.get_size()\n box = [pygame.math.Vector2(p) for p in [(0, 0), (w, 0), (w, -h), (0, -h)]]\n box_rotate = [p.rotate(angle) for p in box]\n min_box = (min(box_rotate, key=lambda p: p[0])[0], min(box_rotate, key=lambda p: p[1])[1])\n max_box = (max(box_rotate, key=lambda p: p[0])[0], max(box_rotate, key=lambda p: p[1])[1])\n\n # calculate the translation of the pivot \n pivot = pygame.math.Vector2(originPos[0], -originPos[1])\n pivot_rotate = pivot.rotate(angle)\n pivot_move = pivot_rotate - pivot\n\n # calculate the upper left origin of the rotated image\n origin = (int(pos[0] - originPos[0] + min_box[0] - pivot_move[0]), int(pos[1] - originPos[1] - max_box[1] + pivot_move[1]))\n\n # get a rotated image\n rotated_image = pygame.transform.rotate(image, angle)\n\n # rotate and blit the image\n surf.blit(rotated_image, origin)\n\n# define planes and projectiles\n\n# Credit to @_ryan_#6862 for image 4 and player image\n\nenemyPlane = pygame.image.load(\"Python with AI - Level 2/pygame/planeGame/Enemy.png\")\nenemyHeight = 82\nmissile = pygame.image.load(\"Python with AI - Level 2/pygame/planeGame/misslle.png\")\nbomb = pygame.image.load(\"Python with AI - Level 2/pygame/planeGame/B1.png\")\nplayer = pygame.image.load(\"Python with AI - Level 2/pygame/planeGame/Player.png\")\ncloudImage = pygame.image.load(\"Python with AI - Level 2/pygame/planeGame/Cloud.png\")\nexplodeImage = pygame.image.load(\"Python with AI - Level 2/pygame/planeGame/explosion.png\")\n\n# define enemy class\n\nclass Enemy:\n def __init__(self, x, y, shot, respawnWait, shootWait, x_change, y_change, xMovement, xMovementTime, xMovementTimeMax, yMovement, yMovementTime, yMovementTimeMax, speed, spawning, spawnAnimationTime, spawnSpeed, running, runSpeed, runSpeedWait):\n self.x = x\n self.y = y\n self.shot = shot\n self.respawnWait = respawnWait\n self.x_change = x_change\n self.y_change = y_change\n self.xMovement = xMovement\n self.xMovementTime = xMovementTime\n self.xMovementTimeMax = xMovementTimeMax\n self.yMovement = yMovement\n self.yMovementTime = yMovementTime\n self.yMovementTimeMax = yMovementTimeMax\n self.speed = speed\n self.shootWait = shootWait\n self.spawning = spawning\n self.spawnAnimationTime = spawnAnimationTime\n self.spawnSpeed = spawnSpeed\n self.running = running\n self.runSpeed = runSpeed\n self.runSpeedWait = runSpeedWait\n def move(self):\n self.x += self.x_change\n self.y += self.y_change\n return (int(self.x), int(self.y))\n def calculate(self):\n if self.spawning:\n self.y_change = self.spawnSpeed\n self.spawnAnimationTime += -1\n if self.spawnAnimationTime == 0:\n self.spawning = False\n if self.spawnAnimationTime % 10 == 0:\n self.spawnSpeed += -1\n self.running = False\n elif self.running:\n self.y_change = self.runSpeed\n if self.runSpeedWait == 0:\n self.runSpeed += -1\n self.runSpeedWait = 5\n else:\n self.runSpeedWait += -1\n self.x_change = 0\n else:\n if self.respawnWait == 0 and self.shot:\n self.shot = False\n self.x = random.randint(0, 1710)\n self.shootWait = 60\n self.y = -100\n self.spawning = True\n self.spawnAnimationTime = 50\n self.spawnSpeed = 5\n self.runSpeedWait = 0\n if self.shot:\n self.respawnWait += -1\n self.yMovementTime += 1\n if self.yMovementTime == self.yMovementTimeMax:\n self.yMovement = self.yMovement * -1\n self.yMovementTime = 0\n self.yMovementTimeMax = random.randint(21, 41)\n self.y_change = self.speed * self.yMovement\n self.xMovementTime += 1\n if self.xMovementTime == self.xMovementTimeMax:\n self.xMovement = self.xMovement * -1\n self.xMovementTime = 0\n self.xMovementTimeMax = random.randint(41, 61)\n self.x_change = self.speed * self.xMovement\n self.shootWait += -1\n def spawnBomb(self):\n bombs.append(Bomb(self.x - 5, self.y + enemyHeight, 5))\n def die(self):\n self.shot = True\n self.respawnWait = 30\n\n# define bomb class\n\nclass Bomb:\n def __init__(self, x, y, speed):\n self.x = x\n self.y = y\n self.speed = speed\n def move(self):\n self.y += self.speed\n return (int(self.x), int(self.y))\n\n# define missile class\n\nclass Missile:\n def __init__(self, x, y, direction, xSpeed, ySpeed, x_change, rotation):\n self.x = x\n self.y = y\n self.direction = direction\n self.xSpeed = xSpeed\n self.ySpeed = ySpeed\n self.x_change = x_change\n self.rotation = rotation\n def move(self):\n self.x_change += self.xSpeed * self.direction\n self.y += 0 - self.ySpeed\n return (int(self.x + self.x_change), int(self.y))\n\n# define cloud class\n\nclass Cloud:\n def __init__(self, x, y, x_change, y_change, xMovement, yMovement, xMovementTimeMax, yMovementTimeMax, xMovementTime, yMovementTime, speed):\n self.x = x\n self.y = y\n self.x_change = x_change\n self.y_change = y_change\n self.xMovement = xMovement\n self.yMovement = yMovement\n self.xMovementTimeMax = xMovementTimeMax\n self.yMovementTimeMax = yMovementTimeMax\n self.xMovementTime = xMovementTime\n self.yMovementTime = yMovementTime\n self.speed = speed\n def calculate(self):\n self.yMovementTime += 1\n if self.yMovementTime == self.yMovementTimeMax:\n self.yMovement = self.yMovement * -1\n self.yMovementTime = 0\n self.yMovementTimeMax = random.randint(21, 41)\n self.y_change = self.speed * self.yMovement\n self.xMovementTime += 1\n if self.xMovementTime == self.xMovementTimeMax:\n self.xMovement = self.xMovement * -1\n self.xMovementTime = 0\n self.xMovementTimeMax = random.randint(21, 41)\n self.x_change = self.speed * self.xMovement\n def move(self):\n self.x += self.x_change\n self.y += self.y_change\n return((self.x, self.y))\n def reset(self):\n self.x = random.randint(0, screenWidth - 100)\n self.y = random.randint(0, screenHeight - 100)\n self.xMovement = 1\n self.yMovement = 1\n self.xMovementTimeMax = random.randint(41, 81)\n self.yMovementTimeMax = random.randint(41, 81)\n self.xMovementTime = 0\n self.yMovementTime = 0\n\n# Explosion class\n\nclass Explosion:\n def __init__(self):\n self.x = random.randint(0, 1770)\n self.xDirection = 1\n self.x_change = 5\n self.y = random.randint(0, 930)\n self.yDirection = 1\n self.y_change = 5\n self.exploding = False\n self.explodingWait = random.randint(15, 60)\n self.explodingDuration = 60\n def move(self):\n self.x += self.x_change\n self.y += self.y_change\n return (self.x, self.y)\n def calculate(self):\n if self.exploding:\n self.explodingDuration += -1\n else:\n self.explodingWait += -1\n if self.explodingWait == 0:\n self.exploding = True\n self.explodingDuration = 60\n self.explodingWait = random.randint(15, 60)\n if self.explodingDuration == 0:\n self.exploding = False\n self.xDirection = 1\n self.yDirection = 1\n if self.x + 50 > 1820 or self.x < 0:\n self.xDirection = self.xDirection * -1\n if self.y + 50 > 980 or self.y < 0:\n self.yDirection = self.yDirection * -1\n if self.exploding:\n self.x_change = 0\n self.y_change = 0\n else:\n self.x_change = 5 * self.xDirection\n self.y_change = 5 * self.yDirection\n\n# enemyDeath class\n\nclass enemyDeath:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.exist = True\n self.timeLeft = 60\n def move(self):\n return (self.x, self.y)\n def calculate(self):\n self.timeLeft += -1\n if self.timeLeft == 0:\n self.exist = False\n\n# define other variables\n\nclouds = []\nfor x in range(0, 15):\n clouds.append(Cloud(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1))\nfor cloud in clouds:\n cloud.reset()\n \nhealthBarx = 810\nhealthBary = 920\n\nvolume = 100\n\ngunFire = pygame.mixer.Sound(\"Python with AI - Level 2/pygame/planeGame/gunfire.wav\")\nexplosion = pygame.mixer.Sound(\"Python with AI - Level 2/pygame/planeGame/Explosion+3.wav\")\nbackGround = pygame.mixer.Sound(\"Python with AI - Level 2/pygame/planeGame/background.wav\")\ngunFire.set_volume(0.5)\nbackGroundChannel = pygame.mixer.Channel(0)\ngunFireChannel = pygame.mixer.Channel(1)\nenemyGunFireChannel = pygame.mixer.Channel(2)\nexplosions = []\n\nwhile True:\n\n # reset variables\n\n playBackMusWait = 0\n graves = []\n soundPlaying = False\n menuEnd = False\n dead = False\n x_change = 0\n x = 740\n y_change = 0\n y = 720\n enemies = [Enemy(1700, -100, False, 0, 1, 0, 0, 1, 0, random.randint(21, 41), 1, 0, random.randint(21, 41), 1, True, 50, 5, False, 1, 5)]\n bombs = []\n missiles = []\n shooting = False\n shootDelay = 5\n shootingDelay = 0\n maxShoot = 5\n canShoot = True\n lives = 5\n invincibility = False\n invincibilityFrames = 0\n for cloud in clouds:\n cloud.reset()\n player = pygame.image.load(\"Python with AI - Level 2/pygame/planeGame/Player.png\")\n playerRotation = 0\n playerAngle = 0\n explosions = [Explosion(), Explosion(), Explosion(), Explosion(), Explosion(), Explosion(), Explosion(), Explosion(), Explosion()]\n\n\n # menu code\n\n while not menuEnd:\n displayMsg(\"Plane Fighting\", (int(1920 / 2), int(screenHeight / 2)), 115)\n displayMsg(\"press space to start and q to quit. or the buttons\", (int(1920/2), int(screenHeight/2) + 100), 20)\n button((255, 40, 0), (255, 0, 0), 1120, 780, 100, 100, \"Quit?\", 20)\n button((0, 255, 0), (90, 238, 90), 600, 780, 100, 100, \"START?\", 20)\n button((255, 255, 255), (100, 100, 100), 390, 780, 200, 100, \"Change Volume?\", 20)\n button((255, 255, 255), (255, 255, 255), 200, 100, 1, 1, f\"Volume: {str(volume)}%\", 20)\n for event in pygame.event.get():\n if (event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE) or (event.type == pygame.MOUSEBUTTONDOWN and event.pos[0] > 600 and event.pos[0] < 700 and event.pos[1] > 780 and event.pos[1] < screenHeight and event.button == 1):\n menuEnd = True\n if (event.type == pygame.KEYDOWN and event.key == pygame.K_q) or (event.type == pygame.MOUSEBUTTONDOWN and event.pos[0] > 1120 and event.pos[0] < 1220 and event.pos[1] > 780 and event.pos[1] < 880 and event.button == 1) or event.type == pygame.QUIT:\n gameQuit()\n if event.type == pygame.MOUSEBUTTONDOWN and event.pos[0] > 390 and event.pos[0] < 590 and event.pos[1] > 780 and event.pos[1] < 880 and event.button == 1:\n if volume == 100:\n volume = 0\n else:\n volume += 10\n frameUpdate()\n gameDisplay.fill((255, 255, 255, 0))\n backGroundChannel.set_volume(volume / 100)\n gunFireChannel.set_volume(volume / 100)\n enemyGunFireChannel.set_volume(volume / 100)\n \n # play background music\n\n backGroundChannel.play(backGround, -1)\n\n # start game loop\n\n while not dead:\n # events code\n\n if lives == 0:\n die()\n dead = True\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n gameQuit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT or event.key == pygame.K_a:\n x_change = -5\n playerRotation = 20 \n elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:\n x_change = 5\n playerRotation = -20\n elif event.key == pygame.K_UP or event.key == pygame.K_w:\n y_change = -5\n elif event.key == pygame.K_DOWN or event.key == pygame.K_s:\n y_change = 5\n elif event.key == pygame.K_SPACE and canShoot:\n shooting = True\n maxShoot = 5\n shootingDelay = 60\n canShoot = False\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT or event.key == pygame.K_a or event.key == pygame.K_RIGHT or event.key == pygame.K_d:\n x_change = 0\n playerRotation = 0\n elif event.key == pygame.K_DOWN or event.key == pygame.K_s or event.key == pygame.K_UP or event.key == pygame.K_w:\n y_change = 0\n elif event.key == pygame.K_SPACE:\n shooting = False\n soundPlaying = True\n playBackMusWait = 80\n\n # movement code\n\n x += x_change\n y += y_change\n x = int(x)\n y = int(y)\n if playerAngle > playerRotation:\n playerAngle += -1\n if playerAngle < playerRotation:\n playerAngle += 1\n\n # health bar code:\n\n things(healthBarx, healthBary, 10, 30, (255, 0, 0))\n if lives > 1:\n things(healthBarx + 20, healthBary, 10, 30, (255, 165, 0))\n if lives > 2:\n things(healthBarx + 40, healthBary, 10, 30, (255, 255, 0))\n if lives > 3:\n things(healthBarx + 60, healthBary, 10, 30, (90, 238, 90))\n if lives > 4:\n things(healthBarx + 80, healthBary, 10, 30, (0, 255, 0))\n\n # explosion management\n\n for explosion in explosions:\n explosion.calculate()\n if explosion.exploding:\n draw(explosion.move(), explodeImage)\n\n # Collision detection\n\n if y - 80 < 0 or y + 80 > screenHeight or x - 55 < 0 or x + 55 > screenWidth:\n die()\n dead = True\n\n for mine in bombs:\n if ((mine.x + 10) > x - 55 and mine.x < (x + 55)) and ((mine.y + 30) > y - 80 and mine.y < (y + 80)):\n if not(invincibility):\n lives += -1\n invincibility = True\n invincibilityFrames = 60\n bombs.remove(mine)\n\n for bullet in missiles:\n for enemy in enemies:\n if ((bullet.x + bullet.x_change + 25) > enemy.x - 55 and (bullet.x + bullet.x_change - 25) < (enemy.x + 55)) and ((bullet.y + 25) > enemy.y - int(enemyHeight / 2) and bullet.y - 25 < (enemy.y + int(enemyHeight / 2))) and not(enemy.shot) and bullet in missiles:\n enemy.die()\n graves.append(enemyDeath(enemy.x, enemy.y))\n enemy.spawnSpeed = -1\n enemies.append(Enemy(random.randint(0, 1710), -100, False, 0, 1, 0, 0, 1, 0, random.randint(21, 41), 1, 0, random.randint(21, 41), 1, True, 50, 5, False, 1, 5))\n for enemy2 in enemies:\n if enemy2.x + 110 > enemy.x - 100 and enemy2.x < enemy.x + 10 + 110 and not(enemy.spawning) and not(enemy2.shot) and not(enemy2 == enemy) and not enemy2.running and not enemy2.spawning:\n enemy2.running = True\n enemy2.runSpeed = 1\n enemy.running = False\n missiles.remove(bullet)\n soundPlaying = True\n for mine in bombs:\n if mine in bombs and bullet in missiles:\n if ((mine.x + 50) > bullet.x and mine.x < (bullet.x + 10)) and ((mine.y + 50) > bullet.y and mine.y < (bullet.y + 30)):\n bombs.remove(mine)\n missiles.remove(bullet)\n\n for enemy in enemies:\n if ((x + 55 > enemy.x - 55 and x - 55 < (enemy.x + 55)) and ((y + 80) > enemy.y - int(enemyHeight / 2) and y - 80 < (enemy.y + int(enemyHeight / 2))) and not(enemy.shot)): \n die()\n dead = True\n\n # cloud management\n\n for cloud in clouds:\n cloud.calculate()\n draw(cloud.move(), cloudImage)\n\n # missile management\n\n if shootingDelay > 0 and not(shooting):\n shootingDelay += -1\n if shootingDelay == 0:\n maxShoot = 5\n canShoot = True\n if shootDelay > 0:\n shootDelay += -1\n if shooting and shootDelay == 0 and maxShoot != 0:\n missiles.append(Missile(x - 5, y - 30, x_change / 5, 10, 10, 1, playerRotation))\n shootDelay = 10\n maxShoot += -1\n gunFireChannel.play(gunFire, 1)\n if maxShoot == 0 and shooting:\n shooting = False\n soundPlaying = True\n playBackMusWait = 80\n for bullet in missiles:\n if bullet.y > screenHeight or bullet.x > screenWidth or bullet.x < 0:\n missiles.remove(bullet)\n blitRotate(gameDisplay, missile, bullet.move(), (int(missile.get_size()[0] / 2), int(missile.get_size()[1] / 2)), bullet.rotation)\n\n # Enemy code\n\n for enemy in enemies:\n enemy.calculate()\n if not(enemy.shot):\n blitRotate(gameDisplay, enemyPlane, enemy.move(), (int(enemyPlane.get_size()[0] / 2), int(enemyPlane.get_size()[1] / 2)), 0)\n if enemy.shootWait == 0:\n enemy.spawnBomb()\n enemyGunFireChannel.play(gunFire, 1)\n enemy.shootWait = 360\n if enemy.y < 0 - enemyHeight and enemy.running:\n enemy.spawning = True\n enemy.running = False\n if not(enemy.running):\n enemy.runSpeed = 1\n if not(enemy.spawning):\n enemy.spawnSpeed = 5\n \n for mine in bombs:\n if mine.move()[1] > screenHeight:\n bombs.remove(mine)\n draw(mine.move(), bomb)\n\n # player management\n\n if invincibility:\n invincibilityFrames += -1\n if invincibilityFrames % 2 == 0 or not(invincibility):\n blitRotate(gameDisplay, player, (x, y), (int(player.get_size()[0] / 2), int(player.get_size()[1] / 2)), playerAngle)\n if invincibilityFrames == 0:\n invincibility = False\n\n # grave code\n\n for grave in graves:\n grave.calculate()\n draw(grave.move(), explodeImage)\n if not grave.exist:\n graves.remove(grave)\n \n # sound management\n\n backGroundChannel.set_volume(volume / 100)\n gunFireChannel.set_volume(volume / 100)\n enemyGunFireChannel.set_volume(volume / 100)\n \n frameUpdate()\n \n gameDisplay.fill((255, 255, 255))","sub_path":"Python with AI - Level 2/pygame/planeGame/planeGame.py","file_name":"planeGame.py","file_ext":"py","file_size_in_byte":21704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"396510423","text":"import json\nfrom pathlib import Path\nfrom collections import OrderedDict\n\ndef read_json(fname):\n fname = Path(fname)\n with fname.open('rt') as handle:\n return json.load(handle, object_hook=OrderedDict)\n\ndef json_to_config(args):\n args = args.parse_args()\n cfg_fname = Path(args.config)\n config = read_json(cfg_fname)\n return config","sub_path":"T2039/parse_config.py","file_name":"parse_config.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"187936291","text":"from ..DiffusionModel import DiffusionModel\nimport numpy as np\nimport future.utils\nimport pandas as pd\nimport ndlib.models.ModelConfig as mc\nfrom ndlib.utils import multi_runs\n\n__author__ = \"Giulio Rossetti, Florian Guggenmos, and Peter Hofmann\"\n__license__ = \"BSD-2-Clause\"\n__paper__ = \"Guggenmos, F., Hofmann, P., and Fridgen, G. (2019): \" \\\n \"How ill is your IT Portfolio? – Measuring Criticality in IT Portfolios Using Epidemiology,\" \\\n \"40th International Conference on Information Systems (ICIS), Munich, Germany\" \\\n \"https://www.researchgate.net/publication/336103578\"\n__email__ = \"giulio.rossetti@gmail.com, florian.guggenmos@fim-rc.de, peter.hofmann@fim-rc.de\"\n\n\nclass TDMethod(DiffusionModel):\n \"\"\"\n Model Parameters to be specified via ModelConfig\n \"\"\"\n\n def __init__(self, graph, seed=None):\n \"\"\"\n Model Constructor\n\n :param graph: A networkx graph object\n \"\"\"\n super(self.__class__, self).__init__(graph, seed)\n self.available_statuses = {\n \"Susceptible\": 0,\n \"Infected\": 1\n }\n\n self.parameters = {\n \"model\": {\n \"beta\": {\n \"descr\": \"Infection rate\",\n \"range\": \"[0,1]\",\n \"optional\": False}\n },\n \"nodes\": {},\n \"edges\": {},\n }\n\n self.name = \"TD\"\n\n def iteration(self, node_status=True):\n \"\"\"\n Execute a single model iteration\n\n :return: Iteration_id, Incremental node status (dictionary node->status)\n \"\"\"\n self.clean_initial_status(list(self.available_statuses.values()))\n\n actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)}\n\n if self.actual_iteration == 0:\n self.actual_iteration += 1\n delta, node_count, status_delta = self.status_delta(actual_status)\n if node_status:\n return {\"iteration\": 0, \"status\": actual_status.copy(),\n \"node_count\": node_count.copy(), \"status_delta\": status_delta.copy()}\n else:\n return {\"iteration\": 0, \"status\": {},\n \"node_count\": node_count.copy(), \"status_delta\": status_delta.copy()}\n\n for u in self.graph.nodes():\n u_status = self.status[u]\n eventp = np.random.random_sample()\n neighbors = []\n neighbors = self.graph.neighbors(u)\n if self.graph.directed:\n neighbors = self.graph.predecessors(u)\n\n if u_status == 0:\n infected_neighbors = [v for v in neighbors if self.status[v] == 1]\n for infn in infected_neighbors:\n to_node = u\n from_node = infn\n print((from_node+\" and \"+to_node))\n\n w = self.graph.get_edge_data(from_node, to_node)\n wi = float(w[0]['weight'])\n if eventp < len(infected_neighbors)*wi:\n actual_status[u] = 1\n break\n\n delta, node_count, status_delta = self.status_delta(actual_status)\n self.status = actual_status\n self.actual_iteration += 1\n\n if node_status:\n return {\"iteration\": self.actual_iteration - 1, \"status\": delta.copy(),\n \"node_count\": node_count.copy(), \"status_delta\": status_delta.copy()}\n else:\n return {\"iteration\": self.actual_iteration - 1, \"status\": {},\n \"node_count\": node_count.copy(), \"status_delta\": status_delta.copy()}\n\n @staticmethod\n def execute_model(G, number_of_iterations, number_of_executions):\n \"\"\"\n Execute the TD model\n\n :return: df including model results)\n \"\"\"\n nodes = []\n for node in G.nodes:\n nodes.append(node)\n df_mod_multi = pd.DataFrame(0, index=list(range(0, number_of_iterations)), columns=nodes)\n for infected_node in nodes:\n # print(infected_node)\n model = TDMethod(G)\n cfg_mod = mc.Configuration()\n cfg_mod.add_model_parameter('beta', 'individual betas') # infection rate\n\n infection_sets = []\n infection_sets.append(infected_node)\n\n cfg_mod.add_model_initial_configuration(\"Infected\", infection_sets)\n model.set_initial_status(cfg_mod)\n\n trends_multi = multi_runs(model, execution_number=number_of_executions,\n iteration_number=number_of_iterations, nprocesses=10)\n\n execution_list = list(range(0, number_of_executions))\n for ex_n in execution_list:\n list_of_infected_nodes = trends_multi[ex_n]['trends']['node_count'][1]\n iterator_ifn = 0\n for ifn in list_of_infected_nodes:\n df_mod_multi.at[iterator_ifn, infected_node] = df_mod_multi.at[iterator_ifn, infected_node] + ifn\n iterator_ifn = iterator_ifn + 1\n df_mod_multi = df_mod_multi / number_of_executions\n return df_mod_multi\n\n @staticmethod\n def execute_criticality_score(G, model_results, gamma):\n \"\"\"\n Applies the criticality score\n\n :return: dict including criticality scores)\n \"\"\"\n\n df_diff = model_results.diff().drop([0])\n nodes = G.nodes\n for node in nodes:\n for i in list(range(len(df_diff)))[1:]:\n df_diff[node][i] = df_diff[node][i] / (i ** gamma)\n df_sum_diff = df_diff.sum()\n df_results = df_sum_diff + 1\n crit = df_results.to_dict()\n return crit\n\n @staticmethod\n def execute_method(graph, number_of_iterations, number_of_executions, gamma):\n \"\"\"\n Executes the whole method\n\n :return: dict including criticality scores)\n \"\"\"\n\n model_results = TDMethod.execute_model(graph, number_of_iterations, number_of_executions)\n result_dict = TDMethod.execute_criticality_score(graph, model_results, gamma)\n return result_dict\n\n\n\n\n\n\n\n\n\n\n","sub_path":"ndlib/ndlib/models/epidemics/TDMethod.py","file_name":"TDMethod.py","file_ext":"py","file_size_in_byte":6147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}