diff --git "a/3133.jsonl" "b/3133.jsonl" new file mode 100644--- /dev/null +++ "b/3133.jsonl" @@ -0,0 +1,660 @@ +{"seq_id":"7466401","text":"\"\"\"\n\tMiller-Rabin primality test\n\"\"\"\nimport sys, random\nimport POWERS\n\ndef miller_rabin(n): \n\t\"\"\"Miller-Rabin test\n\tError probability is <= 1/4\"\"\"\n\tif n % 2 == 0: return n == 2\n\tif n <= 9: return n % 2 == 1 and n != 1 and n != 9\n\t\t# need n > 9 for 3/4 correctness probability\n\ta = random.randrange(2, n-1)\n\t# Represent n-1 == 2^s t\n\tt = n-1\n\ts = 0 \n\twhile (t % 2) == 0:\n\t\tt //= 2\n\t\ts += 1\n\t# Compute b = a^t mod n\n\tb = POWERS.mod_pow(a, t, n) \n\tif b == 1 or b == n-1: return True \n\tfor j in range(1,s):\n\t\tb = (b*b) % n; \n\t\tif b == n-1: return True\n\treturn False\t\n\ndef is_probable_prime(n, confidence=12): \n\t\"\"\"Repeated Miller-Rabin test\n\tError probability is <= 4^(-confidence)\"\"\"\n\tfor i in range(0,confidence):\n\t\tif not miller_rabin(n): return False\n\treturn True\n\ndef main():\n\tfor line in sys.stdin:\n\t\tn = int(line.strip())\n\t\tprint('YES' if is_probable_prime(n) else 'NO')\n\nif __name__ == '__main__': main()\n","sub_path":"PRIMALTY.py","file_name":"PRIMALTY.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"201312279","text":"import nox\n\n\n@nox.session(python=[\"3.6\", \"3.7\", \"3.8\"])\ndef test(session):\n session.run(\"make\", \"rebuild\", silent=True, external=True)\n session.install(\"universum[test]\")\n session.run(\"make\", \"test\", external=True, success_codes=[0, 2])\n session.run(\"mv\", \"junit_results.xml\", f\"junit_results_{session.python}.xml\", external=True)\n\n\n@nox.session()\ndef clean(session):\n session.run(\"docker\", \"image\", \"prune\", \"-f\", external=True)\n","sub_path":"noxfile.py","file_name":"noxfile.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"235074572","text":"# -*- coding: utf-8 -*-\n\n\nBUILD_SKELETON = \"\"\"\nxcrun xcodebuild \\\n-workspace {workspace} \\\n-scheme {scheme} \\\n-sdk {sdk} \\\n-destination {destination} \\\n-configuration {configuration} \\\nbuild\n\"\"\"\n\nIOS_BUILD = dict(workspac=None,\n scheme=None,\n sdk='iphonesimulator',\n destination='name=\"iPhone 6\"',\n configuration='Debug')\n\nIOS_APP = dict(app=None,\n platformName='iOS',\n platformVersion='10.2',\n deviceName='iPhone 6',\n automationName='XCUITest')\n\nMAIN = dict(workspace_path=None,\n git_repository=None,\n app_name=None)\n\nDR_MOBILE = dict(command_executor='http://127.0.0.1:4723/wd/hub',\n desired_capabilities=IOS_APP)\n\nDR_BROWSER = dict(timeout=5)\n","sub_path":"caesar/common/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"402842793","text":"# 264. 丑数 II\n\n\nclass Solution:\n def nthUglyNumber(self, n: int) -> int:\n arr = [1]\n idx1 = 0\n idx2 = 0\n idx3 = 0\n for i in range(n-1):\n num1 = arr[idx1]*2\n num2 = arr[idx2]*3\n num3 = arr[idx3]*5\n min_num = min(num1, num2, num3)\n arr.append(min_num)\n if num1 == min_num:\n idx1 += 1\n if num2 == min_num:\n idx2 += 1\n if num3 == min_num:\n idx3 += 1\n return arr[-1]\n\n\nif __name__ == '__main__':\n nums_map = {}\n print(nums_map.get(22))","sub_path":"answers/nthUglyNumber.py","file_name":"nthUglyNumber.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"602474576","text":"import os\nimport random\n\ndir = 'dataset/bearwithus/'\ntrain_split = 0.8\n\nfiles = [file.split('.')[0] for file in os.listdir(dir)]\n\nrandom.shuffle(files)\n\ntrain_num = int(len(files) * 0.8)\ntrain_files = files[:train_num]\nvalidation_files = files[train_num:]\n\nwith open('dataset/train_cases.txt', \"w\") as file:\n for file_name in train_files:\n file.write(file_name + \"\\n\")\n\nwith open('dataset/validation_cases.txt', \"w\") as file:\n for file_name in validation_files:\n file.write(file_name + \"\\n\")","sub_path":"create_bears_list.py","file_name":"create_bears_list.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"115751322","text":"import nltk\nfrom nltk import CFG\nfrom nltk.draw.tree import draw_trees\nimport sys\n\ngrammar = CFG.fromstring(\"\"\"\nX -> X X | 'a' | 'b' | 'c' | 'd'\n\"\"\")\n\nprint(\"Start:\", grammar.start(), file=sys.stderr)\nprint(\"Productions:\", grammar.productions(), file=sys.stderr)\nfor line in sys.stdin:\n text = line.strip().split()\n parser = nltk.ChartParser(grammar)\n for tree in parser.parse(text):\n print(tree)\n trees = parser.parse(text)\n draw_trees(*trees)\n","sub_path":"assets/demos/nltk/parsing_ambiguity.py","file_name":"parsing_ambiguity.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"47908776","text":"from urllib import request\nimport random\n\n# 构造list\nuaList = []\n# 读取配置\nwith open(\"./UAConfig.txt\") as cfg:\n data = cfg.read()\n # 分割之后拿到每一行数据\n lines = data.split(\"\\n\")\n for ua in lines:\n print(ua)\n\n# 随机\nuserAgent = random.choice(lines)\n\nprint(len(lines))\nprint(userAgent)\n\n# url = \"http://www.baidu.com/\"\n# headers = {\n# \"User-Agent\":userAgent\n# }\n# # 声明请求对象的时候 注入请求头 修改User-Agent(身份)\n# req = request.Request(url,headers=headers)\n# # 网页请求\n# html = request.urlopen(req).read()\n# print(html.decode())","sub_path":"0604/1.随机UA.py","file_name":"1.随机UA.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"355808519","text":"\"\"\"\n\n*************\nDS1820 Module\n*************\n\nThis module implements the class DS1820 to read OneWire temperature sensors DS18b20 and DS18s20 connected to a DS2482 I2C-OneWire bridge (`datasheet `_). \n\n \"\"\"\nfrom maxim.ds2482 import ds2482\n\nclass DS1820(ds2482.OneWireSensor):\n \"\"\"\n\n============\nDS1820 class\n=============\n\n.. class:: DS1820(serial,ow)\n \n Creates a DS1820 instance using the OneWire bridge *ow* with OneWire serial id *serial*.\n\n \"\"\" \n\n def read(self):\n \"\"\"\n.. method:: read()\n\n Returns the temperature readings as float applying the correct conversion for different DS1820 models.\n If the serial is wrong, raises *UnsupportedError*.\n \"\"\"\n if self.owbus.ow_match_rom(self.serial):\n self.owbus.ow_write(b'\\x44') # convert temperature command\n sleep(750) # max tconv time\n self.owbus.ow_match_rom(self.serial)\n self.owbus.ow_write(b'\\xbe') # read scratchpad command\n sp = self.owbus.ow_read(8)\n #print(\"%x %x\"%(sp[0],sp[1]))\n if sum(sp)==0xff*8:\n # sensor disconnected\n raise InvalidHardwareStatusError\n if self.typeid == 0x28: # ds18b20\n if sp[1]&0xF0: #sign is 1, convert\n t = (sp[1]<<8)+sp[0] # 16 bit 2-complement\n t = -(0xffff-t+1)\n else:\n t = sp[1] & 0x07; # read msb 3 bits\n t = (t<<8)+sp[0]; # 11 bits of data\n return t*0.0625\n elif self.typeid == 0x10: #d18s20\n sgn = 1\n if sp[1]: # sign is 1, convert\n t = (0xff-sp[0]+1)\n sgn=-1\n else:\n t = sp[0]\n return sgn*(t/2 - (0.25*(sp[7]-sp[6])/sp[7]))\n else:\n raise UnsupportedError\n return None\n\n","sub_path":"ds1820.py","file_name":"ds1820.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"297178007","text":"# Data to be rejected as dict of lists where keys are columns and values are rows\n# E.g. DROP_DATA = {'a': ['x', 'y']} rejects all rows that have values 'x' or 'y' in column 'a'\nDROP_DATA = {\n 'Saaja/Maksaja': ['x','y'],\n 'Tapahtuma': ['z']\n}\n\n# Default dir that will opened when data is loaded\n# Current script folder will be used if None\nDEFAULT_DATA_DIR = None","sub_path":"config_example.py","file_name":"config_example.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"456997972","text":"\"\"\"\r\ninput_dims is an integer containing the dimensions of the model input\r\nhidden_layers is a list containing the number of nodes for each hidden\r\nlayer in the encoder, respectively\r\nthe hidden layers should be reversed for the decoder\r\nlatent_dims is an integer containing the dimensions of the\r\nlatent space representation\r\nReturns: encoder, decoder, auto\r\nencoder is the encoder model\r\ndecoder is the decoder model\r\nauto is the full autoencoder model\r\nThe autoencoder model should be compiled using adam optimization and\r\nbinary cross-entropy loss\r\nAll layers should use a relu activation except for the last layer in\r\nthe decoder, which should use sigmoid\r\n\"\"\"\r\nimport tensorflow.keras as K\r\n\r\nfrom tensorflow.keras.layers import Input, Dense\r\nfrom tensorflow.keras.models import Model\r\n\r\n\r\ndef autoencoder(input_dims, hidden_layers, latent_dims):\r\n \"\"\"\r\n Autoencoder Vanilla\r\n \"\"\"\r\n nodes = len(hidden_layers)\r\n input_img = K.layers.Input(shape=(input_dims,))\r\n encoded = K.layers.Dense(hidden_layers[0], activation='relu')(input_img)\r\n for i in range(1, nodes):\r\n encoded = K.layers.Dense(hidden_layers[i], activation='relu')(encoded)\r\n lay_latent = K.layers.Dense(latent_dims, activation='relu')(encoded)\r\n encoder = K.models.Model(input_img, lay_latent)\r\n # \"decoded\" is the lossy reconstruction of the input\r\n input_dec = K.layers.Input(shape=(latent_dims,))\r\n decoded = K.layers.Dense(hidden_layers[i], activation='relu')(input_dec)\r\n for i in range(nodes-2, 0, -1):\r\n decoded = K.layers.Dense(hidden_layers[i], activation='relu')(decoded)\r\n decoded = K.layers.Dense(input_dims, activation='sigmoid')(decoded)\r\n # this model maps an input to its reconstruction\r\n decoder = K.models.Model(input_dec, decoded)\r\n enc_out = encoder(input_img)\r\n dec_out = decoder(enc_out)\r\n auto = K.models.Model(input_img, dec_out)\r\n auto.compile(optimizer='Adam', loss='binary_crossentropy')\r\n return(encoder, decoder, auto)\r\n","sub_path":"unsupervised_learning/0x04-autoencoders/0-vanilla.py","file_name":"0-vanilla.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"26685916","text":"from random import shuffle\n\nwith open(\"input.txt\",\"w\") as f :\n f.write(\"\" + str((255 * (256) / 2) * 10) + \"\\n\")\n a = []\n index = 0\n for i in range(0,256) :\n for j in range(0,i) :\n for k in range(0,10) :\n a.append(i) \n shuffle(a);\n for v in a :\n f.write(str(v) + \"\\n\");\n","sub_path":"pattern1/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"589112973","text":"\"\"\"Constants for the executors.\"\"\"\nfrom pathlib import Path\n\nDATA_LOCAL_VOLUME = Path(\"/data_local\")\nDATA_VOLUME = Path(\"/data\")\nDATA_ALL_VOLUME = Path(\"/data_all\")\nUPLOAD_VOLUME = Path(\"/upload\")\nSECRETS_VOLUME = Path(\"/secrets\")\nSETTINGS_VOLUME = Path(\"/settings\")\nSOCKETS_VOLUME = Path(\"/sockets\")\nINPUTS_VOLUME = Path(\"/inputs\")\n\nCONTAINER_TIMEOUT = 600\n# Where socket files are stored inside container.\nCOMMUNICATION_PROCESSING_SOCKET = \"_socket1.s\"\nSCRIPT_SOCKET = \"_socket2.s\"\n# Used to upload files from processing to communication container.\nUPLOAD_FILE_SOCKET = \"_upload_socket.s\"\n\nTMPDIR = \".tmp\"\n","sub_path":"resolwe/flow/executors/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"297261963","text":"from harmonograph import Oscillator\n\nimport rhinoscriptsyntax as rs\n\n\ndef main():\n \"\"\"\n The main function.\n \"\"\"\n\n #speed()\n #size()\n #progressive()\n \n #book()\n #koren()\n\n\ndef koren():\n # amplitude, frequency, phase\n # frequency ratios:\n # music intervals...5/4; \n # fibonacci 13/21; 21/34; 34/55\n\n frequency_ratio(21, 34)\n frequency_ratio(13, 21)\n frequency_ratio(5, 8)\n frequency_ratio(2, 3)\n frequency_ratio(1, 2)\n\n # koren presentation examples\n\n\n\ndef frequency():\n # modulation in:\n # phase\n # frequency\n # amplitude\n # page 2 koren experiments\n pass\n\n\n\n\ndef frequency_ratio(f1, f2):\n \"\"\"\n Fibonacci arrangements\n \"\"\"\n origin = rs.AddPoint([0,0,0])\n times = range(f1*f2 + 1)\n\n hx = []\n for e in range(100):\n # increasing circle distance reduces width.\n circle1 = rs.AddCircle(rs.AddPoint([0 + 5 * e,0,0]), 1)\n o1 = Oscillator(circle1, 1.0/f1)\n circle2 = rs.AddCircle(rs.AddPoint([15 + 5 * e,0,0]), 1)\n o2 = Oscillator(circle2, 1.0/f2, .01 * e)\n hx.append(harmonograph(o1, o2, times, 15))\n\n return hx\n\n\n\ndef book():\n # harmonograph book examples\n pass\n\n\ndef thesis():\n # thesis\n # Ben koren thesis copies\n pass\n\n\n\n\ndef fibonacci():\n \"\"\"\n Fibonacci arrangements\n \"\"\"\n origin = rs.AddPoint([0,0,0])\n times = range(13*21 + 1)\n\n\n hx = []\n for e in range(100):\n # increasing circle distance reduces width.\n circle1 = rs.AddCircle(rs.AddPoint([0 + 5 * e,0,0]), 1)\n o1 = Oscillator(circle1, 1.0/13)\n circle2 = rs.AddCircle(rs.AddPoint([15 + 5 * e,0,0]), 1)\n o2 = Oscillator(circle2, 1.0/21, e*.01)\n hx.append(harmonograph(o1, o2, times, 15))\n\n return hx\n\n\ndef space():\n # not working\n\n origin = rs.AddPoint([0,0,0])\n times = range(1000)\n circle1 = rs.AddCircle(origin, 1)\n o1 = Oscillator(circle1, .01)\n\n hx = []\n\n for radius in range(1, 10):\n circle2 = rs.AddCircle(rs.AddPoint([10,10,0]), radius)\n o2 = Oscillator(circle2, .1)\n hx.append(harmonograph(o1, o2, times, 12))\n\n return hx\n\n\ndef speed():\n # modulate speed on two identical circles\n\n origin = rs.AddPoint([0,0,0])\n times = range(2000)\n circle1 = rs.AddCircle(origin, 1)\n o1 = Oscillator(circle1, .01)\n\n circle2 = rs.AddCircle(rs.AddPoint([10,0,0]), 1)\n\n hx = []\n\n for speed in range(1, 20):\n o2 = Oscillator(circle2, .01 / speed)\n arm_length = 10 + 3 * speed\n hx.append(harmonograph(o1, o2, times, arm_length))\n\n\ndef size():\n # change size of one circle.\n # produces very large circl-ish shapes?\n\n origin = rs.AddPoint([0,0,0])\n times = range(2000)\n circle1 = rs.AddCircle(origin, 1)\n o1 = Oscillator(circle1, .01)\n\n hx = []\n\n for radius in range(1, 20):\n circle2 = rs.AddCircle(rs.AddPoint([10,0,0]), radius)\n o2 = Oscillator(circle2, .01)\n arm_length = 10 + 3 * radius\n hx.append(harmonograph(o1, o2, times, arm_length))\n\n\n\n","sub_path":"src/py/drawings/draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":3008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"346502159","text":"import json\nfrom typing import Dict, Optional\n\nimport pytorch_lightning as pl\nfrom omegaconf import DictConfig\nfrom torch.utils.data import DataLoader\n\nfrom datasets.dataset_collator import WSDDataset, WSDCollatorELMo\nfrom utils.text_processing_utils import ELMo_Embedder\n\n\nclass ELMoDatamoduleWSD(pl.LightningDataModule):\n\n def __init__(self, hparams: Dict[str, float], conf: DictConfig):\n super().__init__()\n\n self.conf = conf\n self.hparams = hparams\n\n self.bs = self.conf.training.batch_size\n self.num_works = self.conf.training.num_workers\n\n def prepare_data(self, *args, **kwargs):\n pass\n\n def setup(self, stage: Optional[str] = None):\n\n # Loading Train-Test-Validation Data\n with open(f'{self.conf.data.main_folder}{self.conf.data.train_data_name}', 'r', encoding='utf-8') as f:\n train_wsd_data = json.load(f)\n\n with open(f'{self.conf.data.main_folder}{self.conf.data.valid_data_name}', 'r', encoding='utf-8') as f:\n valid_wsd_data = json.load(f)\n\n with open(f'{self.conf.data.main_folder}{self.conf.data.test_data_name}', 'r', encoding='utf-8') as f:\n test_wsd_data = json.load(f)\n\n # Loading file with mapping of tags to their ids\n with open(f'{self.conf.data.main_folder}{self.conf.data.tag_to_idx_name}', 'r', encoding='utf-8') as f:\n self.tag_to_idx = json.load(f)\n\n self.word_to_idx = {}\n\n self.wsd_collator = WSDCollatorELMo(percentile=self.conf.training.collator.percent,\n pad_value=self.tag_to_idx['PAD'],\n max_possible_len=self.conf.training.collator.max_seq_length,\n pad_type=self.conf.training.collator.pad_type)\n\n self.train_dataset = WSDDataset(train_wsd_data, self.conf, self.word_to_idx, self.tag_to_idx)\n self.validation_dataset = WSDDataset(valid_wsd_data, self.conf, self.word_to_idx, self.tag_to_idx)\n self.test_dataset = WSDDataset(test_wsd_data, self.conf, self.word_to_idx, self.tag_to_idx)\n\n if self.conf.data.vectorization is True:\n self.embedder = ELMo_Embedder(embeddings_path=self.conf.data.embeddings_path)\n\n def train_dataloader(self, *args, **kwargs) -> DataLoader:\n\n train_loader = DataLoader(\n self.train_dataset,\n batch_size=self.bs,\n num_workers=self.num_works,\n collate_fn=self.wsd_collator,\n shuffle=False\n )\n return train_loader\n\n def val_dataloader(self, *args, **kwargs) -> DataLoader:\n\n valid_loader = DataLoader(\n self.validation_dataset,\n batch_size=self.bs,\n num_workers=self.num_works,\n collate_fn=self.wsd_collator,\n shuffle=False\n )\n return valid_loader\n\n def test_dataloader(self, *args, **kwargs) -> DataLoader:\n\n test_loader = DataLoader(\n self.test_dataset,\n batch_size=self.bs,\n num_workers=self.num_works,\n collate_fn=self.wsd_collator,\n shuffle=False\n )\n return test_loader\n","sub_path":"lightning_modules/wsd_elmo_datamodule.py","file_name":"wsd_elmo_datamodule.py","file_ext":"py","file_size_in_byte":3190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"104437471","text":"#!/usr/bin/python\n\n\"\"\"\nMemory map connected processes\n\"\"\"\n\nimport lib_common\nfrom sources_types import memmap\n\ndef Main():\n\tcgiEnv = lib_common.CgiEnv()\n\tmemmapName = cgiEnv.GetId()\n\n\tgrph = cgiEnv.GetGraph()\n\n\tmemmap.DisplayMappedProcesses(grph,memmapName)\n\n\tcgiEnv.OutCgiRdf()\n\nif __name__ == '__main__':\n\tMain()\n","sub_path":"survol/sources_types/memmap/memmap_processes.py","file_name":"memmap_processes.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"26562957","text":"import RPi.GPIO as IO\nimport time\n\n'''\nCobit car motor setup \n\nmotor 1 Right motor \n PWM pin = 19 (GPIO no 35) IA1 \n Direction pin = 13 (GPIO no 33) IB1\n\nmotor 2 Left motor \n PWM pin = 12 (GPIO no 32) IA2\n Dirction pin = 16 (GPIO no 36) IB2\n\n'''\n\nclass CobitCarMotorL9110():\n\n def __init__(self):\n self.motor1_r_pwmPin = 19\n self.motor1_r_dirPin = 13\n self.motor2_l_pwmPin = 12\n self.motor2_l_dirPin = 16\n IO.setwarnings(False)\n IO.setmode(IO.BCM)\n IO.setup(self.motor1_r_pwmPin, IO.OUT)\n IO.setup(self.motor1_r_dirPin, IO.OUT)\n IO.setup(self.motor2_l_pwmPin, IO.OUT)\n IO.setup(self.motor2_l_dirPin, IO.OUT)\n self.motor1_pwm = IO.PWM(self.motor1_r_pwmPin, 100)\n self.motor1_pwm.start(0)\n self.motor2_pwm = IO.PWM(self.motor2_l_pwmPin, 100)\n self.motor2_pwm.start(0)\n\n\n def motor_move_forward(self, speed):\n if speed > 100:\n speed = 100\n #self.motor1_pwm.stop()\n #self.motor2_pwm.stop()\n #self.motor1_pwm = IO.PWM(self.motor1_r_pwmPin, 100)\n #self.motor2_pwm = IO.PWM(self.motor2_l_pwmPin, 100)\n #self.motor1_pwm.start(0)\n #self.motor2_pwm.start(0)\n self.motor1_pwm.ChangeDutyCycle(int(speed))\n self.motor2_pwm.ChangeDutyCycle(int(speed))\n \n def motor_stop(self):\n self.motor1_pwm.ChangeDutyCycle(0)\n self.motor1_pwm.stop()\n IO.output(self.motor1_r_dirPin, False) \n IO.output(self.motor1_r_pwmPin, False)\n self.motor2_pwm.ChangeDutyCycle(0)\n self.motor2_pwm.stop()\n IO.output(self.motor2_l_dirPin, False) \n IO.output(self.motor2_l_pwmPin, False)\n \n def motor_move_backward(self, speed):\n if speed > 100:\n speed = 100\n self.motor1_pwm.stop()\n self.motor1_pwm = IO.PWM(self.motor1_r_dirPin, 100)\n self.motor1_pwm.start(0)\n self.motor1_pwm.ChangeDutyCycle(speed)\n self.motor2_pwm.stop()\n self.motor2_pwm = IO.PWM(self.motor2_l_dirPin, 100)\n self.motor2_pwm.start(0)\n self.motor2_pwm.ChangeDutyCycle(speed)\n \n\nif __name__ == '__main__':\n\n cobit_motor = CobitCarMotorL9110()\n while True:\n cobit_motor.motor_move_forward(30)\n time.sleep(2)\n cobit_motor.motor_stop()\n time.sleep(2)\n \n cobit_motor.motor_move_backward(30)\n time.sleep(2)\n cobit_motor.motor_stop()\n time.sleep(2)\n\n\n\n\n\n","sub_path":"cobit_car_motor_l9110.py","file_name":"cobit_car_motor_l9110.py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"538968324","text":"import os\n\nfrom libqtile.config import Key, Screen, Group, Drag, Click\nfrom libqtile.command import lazy\nfrom libqtile import layout, bar, widget, hook\n\nos.system(\"wmname compiz\")\n\nscreens = [Screen(top = bar.Bar([\n\t\twidget.GroupBox(urgent_alert_method='text', padding=1, borderwidth=1),\n\n\t\twidget.Prompt(),\n\t\twidget.Notify(),\n\n\t\twidget.WindowName(fontsize=14, padding=10, foreground='dddddd'),\n\n\t\twidget.Battery(fontsize=14, foreground='dddddd'),\n\t\twidget.Systray(),\n\t\twidget.Clock('%Y-%m-%d %a %I:%M %p', fontsize=14, foreground='dddddd'),\n\t], 20))\n]\n\ndmenu = 'dmenu_run -i -b -p \">>>\" -fn \"Ariel\" -nb \"#000\" -nf \"#fff\" -sb \"#15181a\" -sf \"#fff\"'\n\nmod = \"mod1\"\nmod1 = \"mod4\"\n\nkeys = [\n\tKey([mod], \"space\", lazy.nextlayout()),\n\tKey([mod, 'shift'], \"c\", lazy.window.kill()),\n\n\tKey([mod], \"k\", lazy.layout.down()),\n\tKey([mod], \"j\", lazy.layout.up()),\n\n\tKey([mod], \"l\", lazy.layout.previous()),\n\tKey([mod], \"h\", lazy.layout.next()),\n\n\tKey([mod, 'shift'], \"k\", lazy.layout.grow()),\n\tKey([mod, 'shift'], \"j\", lazy.layout.shrink()),\n\n\tKey([mod], \"n\", lazy.layout.normalize()),\n\tKey([mod], \"o\", lazy.layout.maximize()),\n\n\tKey([mod], \"Tab\", lazy.layout.down()),\n\n\tKey([mod], \"Return\", lazy.layout.shuffle_down()),\n\tKey([mod, \"shift\"], \"space\", lazy.layout.toggle_split()),\n\t#Key([mod, \"shift\"], \"j\", lazy.layout.shuffle_up()),\n\n Key([mod], \"w\", lazy.to_screen(0)),\n Key([mod], \"e\", lazy.to_screen(1)),\n\n\tKey([mod], \"t\", lazy.window.disable_floating()),\n\n\t# interact with prompts\n\tKey([mod], \"r\", lazy.spawncmd()),\n\tKey([mod], 'f', lazy.spawn(dmenu)),\n\n\tKey([mod], \"slash\", lazy.magicsearch()),\n\tKey([mod], \"g\", lazy.add_alias_to_group()),\n\n\t# start specific apps\n\tKey([mod, 'shift'], \"Return\", lazy.spawn(\"gnome-terminal\")),\n\n\tKey([mod, \"shift\"], \"r\", lazy.restart()),\n\n\t# Change the volume if your keyboard has special volume keys.\n\tKey(\n\t\t[], \"XF86AudioRaiseVolume\",\n\t\tlazy.spawn(\"amixer -c 0 -q set Master 2dB+\")\n\t),\n\tKey(\n\t\t[], \"XF86AudioLowerVolume\",\n\t\tlazy.spawn(\"amixer -c 0 -q set Master 2dB-\")\n\t),\n\tKey(\n\t\t[], \"XF86AudioMute\",\n\t\tlazy.spawn(\"amixer -c 0 -q set Master toggle\")\n\t),\n\n\tKey([mod, 'control'], 'l', lazy.spawn('/usr/bin/gnome-screensaver-command -l')),\n\tKey([mod, 'control'], 'q', lazy.spawn('/usr/bin/gnome-session-quit --logout --no-prompt')),\n\tKey([mod, 'shift', 'control'], 'q', lazy.spawn('/usr/bin/gnome-session-quit --power-off')),\n]\n\n# This allows you to drag windows around with the mouse if you want.\nmouse = [\n\tDrag([mod], \"Button1\", lazy.window.set_position_floating(),\n\t\tstart=lazy.window.get_position()),\n\tDrag([mod], \"Button3\", lazy.window.set_size_floating(),\n\t\tstart=lazy.window.get_size()),\n\tClick([mod], \"Button2\", lazy.window.bring_to_front())\n\t# TODO always front\n]\n\nfloating_layout = layout.Floating(\n\t\tborder_width=0\n\t\t,max_border_width=0\n\t\t,fullscreen_border_width=0\n)\n@hook.subscribe.client_new\ndef floats(window):\n\tif(window.window.get_wm_type() == \"dialog\" or window.window.get_wm_transient_for()):\n\t\twindow.floating = True\n\tif (window.name == 'Desktop'):\n\t\twindow.minimized = True\n\n# Next, we specify group names, and use the group name list to generate an appropriate\n# set of bindings for group switching.\ngroups = []\nfor kbs, name in ((\"quoteleft\", \"home\"), (\"1\", \"1\"), (\"2\", \"2\"), (\"3\", \"3\"), (\"4\", \"4\"), (\"5\", \"5\"),):\n\tgroups.append(Group(name))\n\tkeys.append(\n\t\tKey([mod], kbs, lazy.group[name].toscreen())\n\t)\n\tkeys.append(\n\t\tKey([mod, 'shift'], kbs, lazy.window.togroup(name))\n\t)\n\n# Two basic layouts.\nlayouts = [\n\tlayout.MonadTall(border_width=1, border_focus='#4444bb'),\n\tlayout.Max(),\n]\n","sub_path":"user-configs/hamaxx/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"356231810","text":"from os import listdir\n\nfrom Loader import Loader\n\nloader = Loader()\nlista_plikow = listdir('data')\n\nfor plik in lista_plikow:\n X, y = loader.load_data(plik)\n data = loader.preprocess(X, y, impute=True, normalize=False)\n\n\n\n","sub_path":"Runner.py","file_name":"Runner.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"209535202","text":"#! /usr/bin/python3\nimport sys\nimport pennylane as qml\nfrom pennylane import numpy as np\nfrom copy import deepcopy\n# DO NOT MODIFY any of these parameters\na = 0.7\nb = -0.3\ndev = qml.device(\"default.qubit\", wires=3)\n\n\ndef natural_gradient(params):\n \"\"\"Calculate the natural gradient of the qnode() cost function.\n\n The code you write for this challenge should be completely contained within this function\n between the # QHACK # comment markers.\n\n You should evaluate the metric tensor and the gradient of the QNode, and then combine these\n together using the natural gradient definition. The natural gradient should be returned as a\n NumPy array.\n\n The metric tensor should be evaluated using the equation provided in the problem text. Hint:\n you will need to define a new QNode that returns the quantum state before measurement.\n\n Args:\n params (np.ndarray): Input parameters, of dimension 6\n\n Returns:\n np.ndarray: The natural gradient evaluated at the input parameters, of dimension 6\n \"\"\"\n\n natural_grad = np.zeros(6)\n\n # QHACK #\n N = 6\n @qml.qnode(dev)\n def qcirc(params):\n \"\"\"A PennyLane QNode that pairs the variational_circuit with probabilistic measurement.\"\"\"\n variational_circuit(params)\n return qml.probs(range(0,3))\n \n # shifting amount for the gradients\n twist = np.pi/2\n gradient = np.zeros([N] , dtype = np.float64)\n \n # Fubini-Study metric\n F = np.zeros([N,N] , dtype = np.float64)\n \n initial_measurement = qcirc(params)\n initial_state = deepcopy(dev.state)\n \n \n\n \n for i in range(N):\n twisted_params = params.copy()\n twisted_params[i] += twist\n \n grad_measurement_1 = qnode(twisted_params)\n twisted_params[i] -= (2 * twist)\n \n grad_measurement_2 = qnode(twisted_params)\n gradient[i] = (grad_measurement_1 - grad_measurement_2)/(2 * np.sin(twist))\n for j in range(N):\n twisted_params = params.copy()\n \n twisted_params[i] += twist\n twisted_params[j] += twist\n qcirc(twisted_params)\n \n stat_vec_1 = deepcopy(dev.state)\n \n twisted_params = params.copy()\n twisted_params[i] -= twist\n twisted_params[j] += twist\n qcirc(twisted_params)\n \n stat_vec_2 = deepcopy(dev.state)\n \n twisted_params = params.copy()\n \n twisted_params[i] += twist\n twisted_params[j] -= twist\n qcirc(twisted_params)\n stat_vec_3 = deepcopy(dev.state)\n twisted_params = params.copy()\n \n twisted_params[i] -= twist\n twisted_params[j] -= twist \n qcirc(twisted_params)\n stat_vec_4 = deepcopy(dev.state)\n # inner product of the acftual state and the pi/2 shifted state\n metric1 = abs( np.array(np.matrix(stat_vec_1).H).T.dot(initial_state))**2\n metric2 = abs( np.array(np.matrix(stat_vec_2).H).T.dot(initial_state))**2\n metric3 = abs( np.array(np.matrix(stat_vec_3).H).T.dot(initial_state))**2\n metric4 =abs( np.array(np.matrix(stat_vec_4).H).T.dot(initial_state))**2\n \n F[i,j] = -metric1+metric2 + metric3 - metric4\n F[i,j] /= 8\n \n \n natural_grad = np.linalg.inv(F) @ gradient\n\n # compare with the pennylane implementation\n met_fn=qml.metric_tensor(qcirc)\n met_fn(params)\n # QHACK #\n\n return natural_grad\n\n\ndef non_parametrized_layer():\n \"\"\"A layer of fixed quantum gates.\n\n # DO NOT MODIFY anything in this function! It is used to judge your solution.\n \"\"\"\n qml.RX(a, wires=0)\n qml.RX(b, wires=1)\n qml.RX(a, wires=1)\n qml.CNOT(wires=[0, 1])\n qml.CNOT(wires=[1, 2])\n qml.RZ(a, wires=0)\n qml.Hadamard(wires=1)\n qml.CNOT(wires=[0, 1])\n qml.RZ(b, wires=1)\n qml.Hadamard(wires=0)\n\n\ndef variational_circuit(params):\n \"\"\"A layered variational circuit composed of two parametrized layers of single qubit rotations\n interleaved with non-parameterized layers of fixed quantum gates specified by\n ``non_parametrized_layer``.\n\n The first parametrized layer uses the first three parameters of ``params``, while the second\n layer uses the final three parameters.\n\n # DO NOT MODIFY anything in this function! It is used to judge your solution.\n \"\"\"\n non_parametrized_layer()\n qml.RX(params[0], wires=0)\n qml.RY(params[1], wires=1)\n qml.RZ(params[2], wires=2)\n non_parametrized_layer()\n qml.RX(params[3], wires=0)\n qml.RY(params[4], wires=1)\n qml.RZ(params[5], wires=2)\n\n\n@qml.qnode(dev)\ndef qnode(params):\n \"\"\"A PennyLane QNode that pairs the variational_circuit with an expectation value\n measurement.\n\n # DO NOT MODIFY anything in this function! It is used to judge your solution.\n \"\"\"\n variational_circuit(params)\n return qml.expval(qml.PauliX(1))\n\n\nif __name__ == \"__main__\":\n # DO NOT MODIFY anything in this code block\n\n # Load and process inputs\n params = sys.stdin.read()\n params = params.split(\",\")\n params = np.array(params, float)\n\n updated_params = natural_gradient(params)\n\n print(*updated_params, sep=\",\")\n","sub_path":"QML_Challenges/quantum_gradients_500_template/quantum_gradients_500_template.py","file_name":"quantum_gradients_500_template.py","file_ext":"py","file_size_in_byte":5344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"254122970","text":"word = input('enter word to palindrummer: ')\nif len(word) < 1: word = 'radar'\nword = str(word.lower())\nrvs=(word[::-1])\n\nif rvs == word: print(word, 'is a palindrom!')\nelse: print(word,'≠', rvs)\n\n\n\n\n","sub_path":"Palindrome_06.py","file_name":"Palindrome_06.py","file_ext":"py","file_size_in_byte":201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"556396907","text":"# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n # Op1 recursion\n def isSymmetric(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n return self.isMirror(root, root)\n\n def isMirror(self, root1, root2):\n if root1 is None and root2 is None:\n return True\n if root1 and root2 and root1.val == root2.val:\n return self.isMirror(root1.left, root2.right) and \\\n self.isMirror(root1.right, root2.left)\n return False\n\n # Op2 Non-recursion\n def isSymmetric2(self, root):\n if root is None: return True\n stack1, stack2 = [], []\n stack1.append(root.left)\n stack2.append(root.right)\n while stack1 and stack2:\n node1, node2 = stack1.pop(), stack2.pop()\n if node1 is None and node2 is None: continue\n if node1 is None or node2 is None: return False\n if node1.val != node2.val: return False\n stack1.append(node1.left)\n stack1.append(node1.right)\n stack2.append(node2.right)\n stack2.append(node2.left)\n return True\n \n\nmytree = TreeNode(1)\nmytree.left = TreeNode(2)\nmytree.right = TreeNode(3)\nprint(mytree.left == mytree.right)\ntest = Solution()\nprint(test.isSymmetric(mytree))\n","sub_path":"python/101 Symmetric Tree.py","file_name":"101 Symmetric Tree.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"156516010","text":"import requests\r\n\r\n#global apikey for using weather api, add your api key here\r\napikey = '' \r\n\r\ndef show_weather(current_user):\r\n \"\"\"\r\n shows the weather at the location of the given user\r\n current_user is user obj with 4 attributes\r\n .name\r\n .city\r\n .lat\r\n .lon\r\n lat and lon will be used for weather information \r\n \"\"\"\r\n lat = current_user._lat\r\n lon = current_user._lon\r\n response = requests.get('https://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&units=metric&APPID={}'.format(lat,lon, apikey))\r\n\r\n json_data = response.json()\r\n\r\n weather_desc = json_data['weather'][0]['description'].capitalize()\r\n current_temp = str(json_data['main']['temp'])\r\n degree_sign = u'\\N{DEGREE SIGN}'\r\n print('In {}, {}, here is the following weather information: '.format(current_user._city, current_user._count.upper()))\r\n dis = \"The weather condition: {}. The current temp: {} \".format(weather_desc, current_temp) + degree_sign + \"C\"\r\n print(dis)\r\n","sub_path":"ShowWeather.py","file_name":"ShowWeather.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"345250914","text":"#Python programme to run java commands for load shedding applications\n#Calvin Nyoni\n#2 March 2020\n\nimport subprocess\n\n#Output file for tests\n#file = open(\"LSBSTOutput.txt\", \"w+\")\n\n#Tests\nListOfTestArgs = [\n #Correct arguments should produces outpout\n [\"1\", \"1\", \"00\"], #correct output: 1\n [\"2\", \"17\", \"14\"], #correct output: 8, 16\n [\"5\", \"26\" , \"10\"], #correct output: 8, 16, 4, 12, 5\n #Incorrect arguments no output/no areas found\n [\"-1\", \"2\", \"3\"],\n [\"5\", \"100\", \"25\"],\n [\"2\", \"4\", \"5723\"]\n]\n\n#Compile before execution\nsubprocess.call([\"javac\", \"LSBSTApp.java\"])\n\n#commmand arguments\ncmdArgs = [\"java\", \"LSBSTApp\"]\n\n#Loop for each test\nfor test in ListOfTestArgs:\n cmdCall = cmdArgs + test\n #file.write(\"Input for test\\n\" + test[0] + \" \" + test[1] + \" \" + test[2] + \":\" + \"\\n\" + \"Output for test\\n\") \n #subprocess.call(cmdCall, stdout = file)\n subprocess.call(cmdCall)\n\n\n#file.close()\n\nprint(\"Done\")","sub_path":"src/scripts/LSBSTScript.py","file_name":"LSBSTScript.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"254906161","text":"\"\"\"Add last_polled\n\nRevision ID: 3ced59d8806b\nRevises: 6d548701edef\nCreate Date: 2022-10-14 10:14:23.979848\n\n\"\"\"\nimport sqlalchemy as sa\nfrom alembic import op\n\nimport prefect\n\n# revision identifiers, used by Alembic.\nrevision = \"3ced59d8806b\"\ndown_revision = \"6d548701edef\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n with op.batch_alter_table(\"work_queue\", schema=None) as batch_op:\n batch_op.add_column(\n sa.Column(\n \"last_polled\",\n prefect.server.utilities.database.Timestamp(timezone=True),\n nullable=True,\n )\n )\n\n\ndef downgrade():\n with op.batch_alter_table(\"work_queue\", schema=None) as batch_op:\n batch_op.drop_column(\"last_polled\")\n","sub_path":"src/prefect/server/database/migrations/versions/postgresql/2022_10_20_101423_3ced59d8806b_add_last_polled.py","file_name":"2022_10_20_101423_3ced59d8806b_add_last_polled.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"97935842","text":"import numpy as np\nimport pygraphviz as pgv\nfrom graphviz import Digraph\n\nclass LightBox:\n \n\n #constructor, create a light box with specified lights and dependecies if BOTH are given. If not, construc the default one\n def __init__(self, light_by_lvl=None, dependencies=None):\n #attributes\n self.nb_level = 0\n self.list_ligth = []\n \n if(light_by_lvl is None and dependencies is None):\n light_by_lvl = [9,6,4,1]\n dependencies = [[],[],[],[],[],[],[],[],[],[1,4,7],[2,5],[3,6],[2,3],[5,6],[7,8,9],[10,11],[11,12],[13,14],[14,15],[17,18]]\n elif(light_by_lvl is None and dependencies is None):\n print(\"You must give both light_by_lvl and dependencies argument, or no one but you can't give one. Creating default lightbox.\")\n light_by_lvl = [9,6,4,1]\n dependencies = [[],[],[],[],[],[],[],[],[],[1,4,7],[2,5],[3,6],[2,3],[5,6],[7,8],[10,11],[11,12],[13,14],[14,15],[17,18]]\n \n self.light_by_lvl = light_by_lvl\n self.nb_level = len(light_by_lvl)\n self.list_light = []\n self.dependencies = dependencies\n currentLvl = 1\n indNextLevel = light_by_lvl[0]\n for i in range(len(dependencies)):\n if(i==indNextLevel):\n indNextLevel+=light_by_lvl[currentLvl]\n currentLvl+=1\n light = dict()\n light[\"id\"]=i+1\n light[\"level\"]=currentLvl\n light[\"dependencies\"]=dependencies[i]\n light[\"state\"]=False\n self.list_light.append(light)\n \n #create set of refinement possible. (i,j) sur as i tree should be refined on j depend on j\n self.refin = set()\n for i in self.list_light:\n dep = i[\"dependencies\"]\n for j in dep:\n self.refin.add((i[\"id\"],j))\n \n def __str__(self):\n currentLvl=1\n s=\"\"\n s=s+\"-----------lvl {}----------\\n\".format(currentLvl)\n for i in range(len(self.list_light)):\n l = self.list_light[i]\n if(l[\"level\"]>currentLvl):\n currentLvl+=1\n s=s+\"-----------lvl {}----------\\n\".format(currentLvl)\n s=s+\"Light {} \\tvalue = {}\".format(l[\"id\"],l[\"state\"])\n if len(l[\"dependencies\"])>0:\n s=s+\"\\tDepend on : \"\n for k in range(len(l[\"dependencies\"])):\n s=s+\"{} \".format(l[\"dependencies\"][k])\n s=s+\"\\n\"\n return s\n \n #turn a light on\n def turn_on(self, light_id):\n #10% of fail on the action\n if np.random.random() < 0.1 :\n return\n l = self.list_light[light_id - 1]\n ##TODO remove later\n switch_off=True\n if(l[\"state\"] and switch_off):\n l[\"state\"]=False\n return\n #for each dependencies\n for dep in l[\"dependencies\"]:\n #if it's off, shutdown the whole box\n if self.list_light[dep-1][\"state\"] == False:\n self.shut_down()\n return\n l[\"state\"]=True\n \n #shutdown every lights\n def shut_down(self):\n for l in self.list_light:\n l[\"state\"] = False\n \n #return state as a list of boolean\n def get_state(self):\n state = []\n for l in self.list_light:\n state.append(l[\"state\"])\n return state\n \n #return number of lights\n def get_nb_light(self):\n return len(self.list_light)\n \n def show(self):\n graph = Digraph()\n for l in self.list_light:\n col=\"lightgrey\"\n if(l[\"state\"]):\n col=\"yellow\"\n graph.node(\"{}\".format(l[\"id\"]),style='filled', color=col)\n #graph.get_node(attr['fillcolor']=\"#CCCCFF\"\n for l in self.list_light:\n for dep in l[\"dependencies\"]:\n e=\"{}{}\".format(l[\"id\"],dep)\n graph.edge(\"{}\".format(dep), \"{}\".format(l[\"id\"]))\n return graph\n \n def count_refin(self):\n n_self_dep = self.get_nb_light()**2\n n_dep = 0\n n_co_parent = 0\n \n print(self.list_light)\n for i in self.list_light:\n print(i)\n dep = i[\"dependencies\"]\n print(dep)\n n_dep+=len(dep)\n for j in self.list_light:\n if i[\"id\"] in j[\"dependencies\"]:\n n_co_parent+=len(j[\"dependencies\"])\n \n print(\"{} refinements due to self dependencies \\n{} refinements due to dependecies\\n{} refinements due to co parenting\".format(n_self_dep, n_dep, n_co_parent))\n \n ","sub_path":"src/.ipynb_checkpoints/lightbox-checkpoint.py","file_name":"lightbox-checkpoint.py","file_ext":"py","file_size_in_byte":4638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"469762780","text":"income = int(input(\"Enter your Income here:- \"))\nsaving = int(input(\"Enter your savings here:\"))\n\ndef taxClaculation(income):\n if income <= 250000:\n return 0\n elif income >= 250001 and income <= 500000:\n return 0.1 * (income-250000)\n elif income >= 500001 and income <= 1000000: \n return 25000 + 0.2 * (income-500000)\n elif income >= 1000001:\n return 125000 + 0.3 * (income-1000000)\n\ndef rebateCalculation(income, saving):\n if income <= 500000:\n return income - (0.5 * saving)\n elif income >= 500001 and income <= 1000000: \n return income - (0.3 * saving)\n elif income >= 1000001:\n cal = (0.1 * saving)\n if cal <= 50000:\n return income-cal\n else:\n return income-50000\n\nrebate = rebateCalculation(income, saving)\ntax= taxClaculation(rebate)\n\nprint(\"Final value to be paid Rs.\" +str(tax))","sub_path":"submissions/sp_017_madhu/week_13/day_1/session_1/tax_calculator.py","file_name":"tax_calculator.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"31190541","text":"#!/usr/bin/python3\n\"\"\"Uploads old run results to Amazon S3.\"\"\"\n\nimport argparse\nimport collections\nimport configparser\nimport datetime\nimport logging\nimport os\nimport os.path\nimport time\n\nfrom typing import Deque, List, Sequence\n\nimport s3put\n\n_GRADE_ROOT = '/var/lib/omegaup/grade'\n\n\ndef _upload(run_id: int, s3client: s3put.S3, dry_run: bool = False) -> bool:\n run_path = os.path.join(\n _GRADE_ROOT,\n '%02d/%02d/%d' % (run_id % 100, (run_id // 100) % 100, run_id))\n assert os.path.isdir(run_path)\n\n if dry_run:\n return True\n\n # Files to upload.\n for filename in ('files.zip', 'details.json', 'logs.txt.gz',\n 'tracing.json.gz'):\n path = os.path.join(run_path, filename)\n if not os.path.exists(path):\n continue\n try:\n s3client.put(path=path, filename='/%d/%s' % (run_id, filename))\n os.unlink(path)\n except KeyboardInterrupt:\n raise\n except: # pylint: disable=bare-except\n logging.exception('Failed to upload %d: %s', run_id, path)\n time.sleep(2)\n return False\n\n os.rmdir(run_path)\n return True\n\n\ndef _format_delta(seconds: float) -> str:\n seconds = int(seconds)\n hours = seconds // 3600\n seconds %= 3600\n minutes = seconds // 60\n seconds %= 60\n return '%02d:%02d:%02d' % (hours, minutes, seconds)\n\n\ndef _get_runs(last_ctime: int) -> Sequence[int]:\n runs: List[int] = []\n for i in range(100):\n for j in range(100):\n parent_dir = os.path.join(_GRADE_ROOT, '%02d/%02d' % (i, j))\n for run_id in os.listdir(parent_dir):\n try:\n stinfo = os.stat(os.path.join(parent_dir, run_id))\n if stinfo.st_ctime >= last_ctime:\n continue\n runs.append(int(run_id))\n except ValueError:\n pass\n runs.sort()\n return runs\n\n\ndef _log_progress(start_time: float, times: Deque[float], runs: Sequence[int],\n uploaded: int) -> None:\n done_rate = len(times) / (times[-1] - times[0])\n remaining_time = (len(runs) - uploaded) / done_rate\n done_ratio = 1.0 * uploaded / len(runs)\n percent_done = 100 * done_ratio\n logging.info('%d/%d (%.2f %%) %.2f/sec, %s elapsed, %s remaining',\n uploaded, len(runs), percent_done, done_rate,\n _format_delta(time.time() - start_time),\n _format_delta(remaining_time))\n\n\ndef _main() -> None:\n parser = argparse.ArgumentParser()\n logging_args = parser.add_argument_group('Logging')\n logging_args.add_argument('--quiet',\n '-q',\n action='store_true',\n help='Disables logging')\n logging_args.add_argument('--verbose',\n '-v',\n action='store_true',\n help='Enables verbose logging')\n logging_args.add_argument('--logfile',\n type=str,\n default=None,\n help='Enables logging to a file')\n\n parser.add_argument('--aws-username', type=str, default='omegaup-backups')\n parser.add_argument('--aws-config',\n type=str,\n default='/etc/omegaup/grader/aws_credentials')\n parser.add_argument('--days-to-keep', type=int, default=14)\n parser.add_argument('--dry-run', action='store_true')\n args = parser.parse_args()\n\n aws_config = configparser.ConfigParser()\n aws_config.read([args.aws_config])\n\n logging.basicConfig(\n filename=args.logfile,\n format='%%(asctime)s:%s:%%(message)s' % parser.prog,\n level=(logging.DEBUG if args.verbose else\n logging.INFO if not args.quiet else logging.ERROR))\n\n last_ctime = (datetime.datetime.now() -\n datetime.timedelta(days=args.days_to_keep)).timestamp()\n runs = _get_runs(int(last_ctime))\n\n logging.info('Going to upload %d runs in the [%d, %d] range', len(runs),\n runs[0], runs[-1])\n\n start_time = time.time()\n times: Deque[float] = collections.deque([time.time()], maxlen=1000)\n errors: List[int] = []\n uploaded = 0\n\n s3client = s3put.S3(aws_access_key=aws_config.get(args.aws_username,\n 'aws_access_key_id'),\n secret_access_key=aws_config.get(\n args.aws_username, 'aws_secret_access_key'),\n bucket='omegaup-runs')\n\n for i, run_id in enumerate(runs):\n try:\n if _upload(run_id, s3client, dry_run=args.dry_run):\n uploaded += 1\n else:\n errors.append(run_id)\n except KeyboardInterrupt:\n break\n times.append(time.time())\n if i % 100 == 0:\n _log_progress(start_time, times, runs, uploaded)\n\n for retry_round in range(10):\n if not errors:\n break\n current_errors = errors\n errors.clear()\n logging.info('Retrying failed runs... round %d: %s', retry_round + 1,\n ', '.join(str(x) for x in current_errors))\n for run_id in current_errors:\n try:\n if _upload(run_id, s3client, dry_run=args.dry_run):\n uploaded += 1\n else:\n errors.append(run_id)\n except KeyboardInterrupt:\n break\n\n _log_progress(start_time, times, runs, uploaded)\n\n\nif __name__ == '__main__':\n _main()\n","sub_path":"files/aws_results_upload.py","file_name":"aws_results_upload.py","file_ext":"py","file_size_in_byte":5661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"158969055","text":"'''This module fetches and processes events from an iCal feed.'''\nimport requests, icalendar\nfrom ical2redmine.logger import LOG as log\nfrom datetime import datetime\nfrom ical2redmine import entries, destinator\nfrom dateutil.tz import tzlocal\nfrom pyactiveresource.connection import ForbiddenAccess\n\ndef localize_timezones(event):\n\t'''Makes sure all date and datetimes are in the local timezone.'''\n\tfor field_name, field_value in event.items():\n\t\tif isinstance(field_value, icalendar.prop.vDDDTypes):\n\t\t\t# Is this infact a datetime?\n\t\t\tif isinstance(field_value.dt, datetime):\n\t\t\t\tevent[field_name].dt = field_value.dt.astimezone( tzlocal() )\n\treturn event\n\ndef fetch(ical_url):\n\t'''Fetches events from an iCal feed.'''\n\tlog.debug(\"Fetching ical feeds from %s.\" % ical_url)\n\tresponse = requests.get(ical_url)\n\tcalendar = icalendar.Calendar.from_ical(response.text)\n\tname = calendar.get('X-WR-CALNAME')\n\tdescription = calendar.get('X-WR-CALDESC')\n\tif name and description:\n\t\tlog.debug(\"Fetched calendar: '%s' (%s).\", name, description)\n\telif name:\n\t\tlog.debug(\"Fetched calendar: '%s'.\", name)\n\telse:\n\t\tlog.debug(\"Fetched calendar!\")\n\tresult = dict()\n\tfor event in calendar.walk(\"VEVENT\"):\n\t\tevent = localize_timezones(event)\n\t\tresult[str(event.get('UID'))] = event\n\treturn result\n\ndef find_recurring_events(in_events):\n\t'''This function finds recurrances of events'''\n\tresult = {}\n\tfor uid, (event, issue_id) in in_events.items():\n\t\tif event.get('RRULE'): # TODO: Need to implement support for this.\n\t\t\trrule = event.get('RRULE')\n\t\t\tresult[uid] = (event, issue_id)\n\treturn result\n\ndef expand_recurrances(recurring_events, start=False, end=None ):\n\t'''This function expands recurrances of events, within a time interval'''\n\tif end == None:\n\t\t# Use now as the default value.\n\t\tend = datetime.now(tzlocal())\n\tlog.error(\"The expand rrules functionality has not yet been implemented.\")\n\tresult = {}\n\tfor (event, issue_id) in recurring_events.values():\n\t\tlog.debug(\"RRULE found!\")\n\t\trrule = event.get('RRULE')\n\t\t#for recurrance in recurrances:\n\t\t# TODO: Do something about this.\n\t\t#\tresult[uid + \"#\" + recurrance] = (event, issue_id)\n\treturn result\n\ndef process(users_events, users_entries, settings):\n\t'''Processes events from an iCal feed.'''\n\tsummary = {\n\t\tdestinator.DESTINY_SKIP: 0,\n\t\tdestinator.DESTINY_CREATE: 0,\n\t\tdestinator.DESTINY_UPDATE: 0,\n\t\tdestinator.DESTINY_DELETE: 0,\n\t\t'recurring_events': 0,\n\t\t'errors': []\n\t}\n\tmatching_events = {}\n\t# Loop through all iCal events from the ical feed.\n\tfor uid, event in users_events.items():\n\t\tevent_summary = unicode(event.get('SUMMARY'))\n\t\t# Match the pattern with the summary.\n\t\tmatch = settings[\"pattern\"].match(event_summary)\n\t\tif match:\n\t\t\tissue_id = match.group('issue_id')\n\t\t\tmatching_events[uid] = event, issue_id\n\t\t\t# We've got a relevant event\n\t\t\tlog.debug(\"An event '%s' (%s) matches issue id #%s\",\n\t\t\t\tevent_summary, uid, issue_id)\n\toriginal_matching_events_count = len(matching_events)\n\t# Check for recurring events (currently not supported).\n\trecurring_events = find_recurring_events(matching_events)\n\tsummary[\"recurring_events\"] = recurring_events\n\t# matching_events.update(expand_recurrances(recurring_events))\n\tlog.info(\"Found %u events in the iCal feed matching the pattern,\" \\\n\t\t\" which was expanded to %u when expading rrules.\",\n\t\toriginal_matching_events_count,\n\t\tlen(matching_events) )\n\n\tfor uid, (event, issue_id) in matching_events.items():\n\t\tdestiny = destinator.determine_event_destiny(\n\t\t\tevent, issue_id, users_entries, settings)\n\t\tlog.debug(\"Event (uid=%s) should be %s.\", uid, destiny)\n\t\ttry:\n\t\t\tif destiny == destinator.DESTINY_CREATE:\n\t\t\t\tentry = entries.create(event, issue_id, users_entries, settings)\n\t\t\t\tif entry == None or not entry.id:\n\t\t\t\t\tlog.error(\"Error occurred when creating entry.\")\n\t\t\telif destiny == destinator.DESTINY_UPDATE:\n\t\t\t\tlog.error(\"Event should be updated, but its not implemented!\")\n\t\t\t\tentry = entries.update(event, issue_id, users_entries, settings)\n\t\t\t\tif entry == None or not entry.id:\n\t\t\t\t\tlog.error(\"Error occurred when updating entry.\")\n\t\t\telif destiny == destinator.DESTINY_DELETE:\n\t\t\t\tentries.delete(event, users_entries)\n\t\t\telif destiny != destinator.DESTINY_SKIP:\n\t\t\t\tlog.error(\"Unsupported destiny!\")\n\t\t\tsummary[destiny] += 1\n\t\texcept Exception as exp:\n\t\t\tlog.exception(\"Error when entry was appempted %s: %s\", destiny, exp)\n\t\t\tsummary['errors'].append({\n\t\t\t\t'uid': uid,\n\t\t\t\t'event': event,\n\t\t\t\t'issue_id': issue_id,\n\t\t\t\t'destiny': destiny,\n\t\t\t\t'exp': exp\n\t\t\t})\n\treturn summary\n","sub_path":"ical2redmine/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":4493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"409954352","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n#定义圆类\r\nclass circle:\r\n #定义构造函数\r\n def __init__ (self,x=0,y=0,r=0): \r\n self.x=x\r\n self.y=y\r\n self.r=abs(r)\r\n \r\n #输出圆的半径和圆心坐标 \r\n def print_circle(self):\r\n print('radius={}, coordinate=({},{})'.format(self.r, self.x, self.y))\r\n \r\n#定义search函数,寻找list中符合条件的最大圆\r\ndef search(list):\r\n max_x=0\r\n max_y=0\r\n max_r=0\r\n \r\n state=1#初始状态设置为1\r\n #在-1到1这个范围内以0.01为步长逐点扫描作为圆心,range中必须为整数类型,所以整体扩大100倍再缩小\r\n for x in range(-100,100,1):\r\n x=x/100\r\n for y in range(-100,100,1):\r\n y=y/100\r\n for c in list:\r\n if (x-c.x)**2 + (y-c.y)**2 < c.r**2:\r\n state=0#当发生重叠时状态变为0\r\n \r\n if state==0:\r\n state=1 \r\n continue\r\n \r\n #先使半径为到边界的最短距离\r\n r=min(abs(x+1),abs(1-x),abs(y+1),abs(y-1))\r\n \r\n #找到在不重叠不越界的情况下圆的最大半径\r\n for c in list:\r\n if (x-c.x)**2+(y-c.y)**2<(c.r+r)**2:\r\n r=((x-c.x)**2+(y-c.y)**2)**0.5-c.r ##若相交,改变r为相切时的半径\r\n \r\n #存储得到的最大半径圆的信息\r\n if r>max_r:\r\n max_x=x\r\n max_y=y\r\n max_r=r\r\n \r\n new=circle(max_x,max_y,max_r)\r\n list.append(new) \r\n \r\ndef plot(list):\r\n plt.figure()\r\n plt.axes().set_aspect('equal')\r\n plt.xlim([-1,1])\r\n plt.ylim([-1,1]) \r\n theta = np.linspace(0,2*np.pi,50)\r\n for c in list: \r\n plt.plot(c.x+c.r*np.cos(theta),c.y+c.r*np.sin(theta),'b') \r\n plt.show()\r\n \r\nif __name__ == \"__main__\":\r\n m = 30\r\n c_list = [] \r\n RR = 0\r\n n=m\r\n \r\n #利用贪心算法,每次在前一次的基础上,调用search函数得到当前情况下的最优解\r\n while(n):\r\n search(c_list) \r\n n-=1\r\n \r\n for c in c_list:\r\n RR+=c.r**2\r\n c.print_circle()\r\n print('for {} circles, the maximize sum of r^2 = {}'.format(m, RR))\r\n\r\n plot(c_list) ","sub_path":"Max_Area.py","file_name":"Max_Area.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"381799684","text":"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom xyz2defect import GetDefects\nfrom xyz2cluster import Xyz2Cluster\n\nxyz2cluster = Xyz2Cluster(2.87)\nsitesFile = \"F:\\\\csaransh-master\\\\csaransh-master\\\\csaransh-pp\\\\data\\\\parcas\\\\sites\"\natomsFile = \"F:\\\\csaransh-master\\\\csaransh-master\\\\csaransh-pp\\\\data\\\\parcas\\\\atoms\"\n\ngd = GetDefects()\ndefects = gd.getDefects(sitesFile, atomsFile)\ndefects = xyz2cluster.addDefectIndex(defects) # 添加索引\nprint(defects)\ncluster_dict = xyz2cluster.getOldClusterDict(defects)\n\ncluster_sizes = xyz2cluster.clusterSize(defects, cluster_dict)\ncluster_dict = xyz2cluster.removeSmallClusters(cluster_dict, cluster_sizes)\n\na = []\nvalue = cluster_dict[8]\n\nfor i in value:\n a.append(defects[i][1:4])\n\na = np.array(a)\nx = a[:, 0]\ny = a[:, 1]\nz = a[:, 2]\n\nplt.scatter(x, y, z)\nplt.show()\n","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"464318663","text":"from palett.convert.utils.rgb import bound, hue\n\nTH = 1000\n\n'''\n!dif: dif===0\n@param {int} r - [0,255]\n@param {int} g - [0,255]\n@param {int} b - [0,255]\n@returns {[int,float,float]} [Hue([0,360]), Saturation([0,100]), Lightness([0,100])]\n'''\n\n\ndef rgb_hsl(rgb):\n r, g, b = rgb\n r /= 255\n g /= 255\n b /= 255\n ma, su, df = bound([r, g, b])\n hu = hue(r, g, b, ma, df) * 60\n sa = 0 if not df else (df / (2 - su)) if su > 1 else df / su\n li = su / 2\n return round(hu), round(sa * TH) / 10.0, round(li * TH) / 10.0\n","sub_path":"palett/convert/rgb_hsl.py","file_name":"rgb_hsl.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"645319960","text":"\n\nfrom xai.brain.wordbase.nouns._fudge import _FUDGE\n\n#calss header\nclass _FUDGES(_FUDGE, ):\n\tdef __init__(self,): \n\t\t_FUDGE.__init__(self)\n\t\tself.name = \"FUDGES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"fudge\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_fudges.py","file_name":"_fudges.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"416823772","text":"from graph import Graph\n\n\ndef earliest_ancestor(ancestors, starting_node):\n g = Graph()\n\n # Target first and second value within ancestors list\n # Add each value as a vertex on our Graph\n for (v1, v2) in ancestors:\n g.add_vertex(v1)\n g.add_vertex(v2)\n\n # Create edges for each set of values\n for (v1, v2) in ancestors:\n g.add_edge(v1, v2)\n\n # Keep track of node's greatest ancestor\n depth = 1\n target_ancestor = None\n\n for val in g.vertices:\n # Build path from val to starting_node\n # by utilizing dfs\n path = g.dfs(val, starting_node)\n\n # If path length greater than current depth\n # reassign depth value to new path length\n if path:\n if len(path) > depth:\n depth = len(path)\n target_ancestor = val\n\n # If no path to starting_node\n elif not path and depth == 1:\n target_ancestor = -1\n\n return target_ancestor\n","sub_path":"projects/ancestor/ancestor.py","file_name":"ancestor.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"354130650","text":"import useful_functions\nimport factorialPrimes\n\n#Script which is used to find the 10001st prime number. Note this uses the code from Problem 2.\n\ndef findFactors(number, allFactorsArray):\n\tfactorialPrimes.runPrimeFactors(number,allFactorsArray);\n\tallPrimesFound = sorted(useful_functions.removeDuplicatesFromList(allFactorsArray));\n\t#If nothing is found, then the number we have is a prime number!\n\tif not allPrimesFound:\n\t\tunofficalArray =[];\n\t\tunofficalArray.append(number);\n\t\treturn unofficalArray;\n\telse:\n\t\treturn allPrimesFound;\n\ndef main(initialStartingFactor,numberOfFactors):\n\tfactorsGot = 0;\n\tnumber = initialStartingFactor;\n\tfactorsGotArray =[];\n\twhile(factorsGot <= numberOfFactors):\n\t\tallFactorsArray =[];\n\t\tallPrimesFound = findFactors(number,allFactorsArray);\n\t\tif len(allPrimesFound)==1:\n\t\t\tfactorsGotArray = factorsGotArray+allPrimesFound;\n\t\telse:\n\t\t\tfactorsGotArray = factorsGotArray+allPrimesFound;\n\t\t\tfactorsGotArray = (useful_functions.removeDuplicatesFromList(factorsGotArray));\n\t\tfactorsGot = useful_functions.countAmountElementsInarray(factorsGotArray);\n\t\tnumber = number +1;\n\t#useful_functions.printList(sorted(factorsGotArray));\n\t\ttempList = list(set(sorted(factorsGotArray)));\n\t#useful_functions.printMessageWithHeaderMessage(\"The 10001st prime number is: \",tempList[10000]);\n\treturn tempList;\n\n#Use this for this problem.\n#main(2,100005);\n","sub_path":"find10001stPrime.py","file_name":"find10001stPrime.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"214798408","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: /usr/local/lib/python2.7/dist-packages/zinc/format_price.py\n# Compiled at: 2014-01-22 02:54:05\n\n\ndef format_price(price):\n price = str(price)\n is_negative = False\n if len(price) > 0 and price[0] == '-':\n is_negative = True\n price = price[1:]\n if len(price) > 2:\n result = '$' + price[:-2] + '.' + price[-2:]\n elif len(price) == 2:\n result = '$0.' + price\n else:\n result = '$0.0' + price\n if is_negative:\n return '-' + result\n else:\n return result","sub_path":"pycfiles/Zinc-0.1.17.linux-x86_64.tar/format_price.py","file_name":"format_price.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"421732060","text":"import argparse\r\nimport sys\r\n\r\nimport torch.optim as optim\r\n\r\nimport baseline\r\nimport data_generator\r\nimport proposed\r\nimport pandas as pd\r\nfrom data_generator import *\r\nfrom loss import *\r\n\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('-d', '--data', type=str)\r\nparser.add_argument('-p', '--project_name', type=str)\r\nparser.add_argument('-k', '--top_k', type=int, default=20)\r\nparser.add_argument('-e', '--epochs', type=int, default=30)\r\nparser.add_argument('-b', '--baseline', type=bool, default=False)\r\nparser.add_argument('-nw', '--n_words', type=int, default=11500)\r\nparser.add_argument('-nc', '--n_chars', type=int, default=130)\r\nparser.add_argument('-wd', '--word_dim', type=int, default=300)\r\nparser.add_argument('-cd', '--char_dim', type=int, default=50)\r\nparser.add_argument('-nf', '--n_filters', type=int, default=64)\r\nparser.add_argument('-np', '--n_prop', type=int)\r\nparser.add_argument('-bs', '--batch_size', type=int, default=8)\r\nparser.add_argument('-nn', '--n_neg', type=int, default=1)\r\nparser.add_argument('-lr', '--learning_rate', type=float, default=1e-3, metavar='LR',\r\n help='learning rate (default: 1e-3)')\r\nargs = parser.parse_args()\r\n\r\n\r\n\r\nDATA_PATH = './raw_data/' + args.project_name + '/' + args.project_name\r\n\r\ndef train(epoch, net, optimizer):\r\n print('Epoch: {}'.format(epoch))\r\n net.train()\r\n losses = []\r\n margin = MarginLoss(margin=1.0)\r\n for loop, (batch_x, batch_pos, batch_neg) in data_generator.batch_iterator(args.data, args.batch_size, args.n_neg):\r\n pred_pos = net(batch_pos)\r\n pred_neg = net(batch_neg)\r\n pred = net(batch_x)\r\n loss = margin(pred, pred_pos, pred_neg)\r\n losses.append(loss.data[0])\r\n loop.set_postfix(loss=loss.data[0])\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n return np.array(losses).mean()\r\n\r\n\r\ndef export(net, data):\r\n test_data_pairs, test_bug_ids = read_test_data(data)\r\n\r\n with open(DATA_PATH + '_candidate_ids.pkl', 'rb') as f:\r\n candidate_ids = pickle.load(f)\r\n\r\n features = {}\r\n\r\n print(\"Test pairs number:\", len(test_data_pairs))\r\n print(\"Test bug_ids number:\", len(test_bug_ids))\r\n print(\"Candidate ids number:\", len(candidate_ids))\r\n\r\n bug_ids = list(set(list(candidate_ids) + list(test_bug_ids)))\r\n print(\"Total number of bug_ids:\", len(bug_ids))\r\n\r\n batch_size = args.batch_size * args.n_neg\r\n num_batch = int(len(bug_ids) / batch_size)\r\n if len(bug_ids) % batch_size > 0:\r\n num_batch += 1\r\n loop = tqdm(range(num_batch))\r\n loop.set_description('Exporting')\r\n for i in loop:\r\n batch_ids = []\r\n for j in range(batch_size):\r\n offset = batch_size * i + j\r\n if offset >= len(bug_ids):\r\n break\r\n batch_ids.append(bug_ids[offset])\r\n batch_features = net(read_batch_bugs(batch_ids, data, test=True))\r\n for bug_id, feature in zip(batch_ids, batch_features):\r\n features[bug_id] = feature\r\n if (i % 500 == 0 or i == num_batch - 1) and i > 0:\r\n with open('./features/trained_features_' + str(i) + '.pkl', 'wb') as f:\r\n pickle.dump(features, f)\r\n print(\"saved {} features\".format(len(features)))\r\n features = {}\r\n features = {}\r\n for path in os.listdir('./features'):\r\n with open(os.path.join('./features', path), 'rb') as f:\r\n part_features = pickle.load(f)\r\n for bug_id in part_features:\r\n features[bug_id] = part_features[bug_id]\r\n print(\"Number of feature vectors:\", len(features))\r\n\r\n return features\r\n\r\n\r\ndef test(data, top_k, features=None):\r\n if not features:\r\n features = torch.load(str(args.net) + '_features.t7')\r\n cosine_batch = nn.CosineSimilarity(dim=1, eps=1e-6)\r\n corrects = 0\r\n total = 0\r\n samples_ = torch.stack(features.values())\r\n test_data_pairs, test_bug_ids = read_test_data(data)\r\n loop = tqdm(range(len(test_data_pairs)))\r\n loop.set_description('Testing')\r\n\r\n with open(DATA_PATH + '_candidates.dict', 'rb') as f:\r\n cand_dict = pickle.load(f)\r\n\r\n with open(os.path.join(args.data, 'test_bug_ids.pkl'), 'rb') as f:\r\n test_bug_ids = pickle.load(f)\r\n\r\n results = []\r\n for i in loop:\r\n idx = test_data_pairs[i]\r\n query = idx[1] # test duplicate\r\n ground_truth = idx[0] # master\r\n\r\n query_ = features[query].expand(samples_.size(0), samples_.size(1)) # matrix (24909, 100))\r\n cos_ = cosine_batch(query_, samples_) # array (24909, )\r\n #(_, indices) = torch.topk(cos_, k=top_k + 1)\r\n #candidates = [features.keys()[x.data[0]] for x in indices]\r\n\r\n # [(candidate_id, master_id, distance)]\r\n dup_dists = [(cid, cand_dict[cid], dist) for cid, dist in zip(features.keys(), cos_) if cid not in test_bug_ids]\r\n\r\n dup_dists_df = pd.DataFrame(dup_dists, columns=['candidate', 'master', 'distance'])\r\n dup_dists_grouped_df = pd.DataFrame(dup_dists_df.groupby(['master'], sort=False)['distance'].max().reset_index(), columns=['master', 'distance'])\r\n result = dup_dists_grouped_df.sort_values(by=['distance'], ascending=False)\r\n results.append((query, ground_truth, result))\r\n\r\n # p = 0\r\n # hit = 0\r\n # for j, r in result.iterrows():\r\n # if p < top_k + 1 and r['master'] != ground_truth:\r\n # p += 1\r\n # else:\r\n # hit = 1\r\n # break\r\n\r\n if i == 0:\r\n print(\"features len:\", len(features))\r\n print(\"samples shape:\", samples_.shape)\r\n print(\"features of query shape:\", features[query].shape)\r\n print(\"query type: {}, query shape: {}\".format(type(query), query_.shape))\r\n print(\"cos shape:\", cos_.shape)\r\n #print(\"candidates number:\", len(candidates))\r\n print(\"dup_dists number:\", len(dup_dists))\r\n print(\"ground truth:\", ground_truth)\r\n total += 1\r\n\r\n with open(DATA_PATH + \"_test_result.pkl\", 'wb') as f:\r\n pickle.dump(results, f)\r\n\r\n return float(corrects) / total\r\n\r\n\r\ndef main():\r\n with open(os.path.join(args.data, 'info_dict.pkl'), 'rb') as f:\r\n info_dict = pickle.load(f)\r\n\r\n dim = sum([v for v in info_dict.values()])\r\n print(\"Dimention of categories onehot space:\", dim)\r\n args.n_prop = dim\r\n\r\n if args.baseline:\r\n args.net = 'base'\r\n else:\r\n args.net = 'proposed'\r\n\r\n if os.path.exists(str(args.net) + '_features.t7'):\r\n print('Final recall@{}={:.4f}'.format(args.top_k, test(args.data, args.top_k)))\r\n sys.exit(0)\r\n\r\n if os.path.exists(str(args.net) + '_checkpoint.t7'):\r\n net = torch.load(str(args.net) + '_checkpoint.t7')\r\n features = export(net, args.data)\r\n torch.save(features, str(args.net) + '_features.t7')\r\n print('Final recall@{}={:.4f}'.format(args.top_k, test(args.data, args.top_k)))\r\n sys.exit(0)\r\n\r\n if args.net == 'base':\r\n net = baseline.BaseNet(args)\r\n else:\r\n net = proposed.Net(args)\r\n net.cuda()\r\n optimizer = optim.Adam(net.parameters(), lr=args.learning_rate *0.1 * 0.1)\r\n best_recall = 0\r\n best_epoch = 0\r\n recall = 0\r\n f = open(DATA_PATH + \"_log.txt\", 'w+')\r\n f.close()\r\n\r\n for epoch in range(1, args.epochs + 1):\r\n if epoch == 100:\r\n optimizer = optim.Adam(net.parameters(), lr=args.learning_rate * 0.1 * 0.1)\r\n loss = train(epoch, net, optimizer)\r\n if epoch == 50:\r\n features = export(net, args.data)\r\n break\r\n #recall = test(args.data, args.top_k, features)\r\n f = open(DATA_PATH + '_log.txt', 'a')\r\n f.write('Epoch={}, Loss={:.4f}, Recall@{}={:.4f}\\n'.format(epoch, loss, args.top_k, recall))\r\n f.close()\r\n print('Loss={:.4f}, Recall@{}={:.4f}'.format(loss, args.top_k, recall))\r\n # if recall > best_recssall:\r\n # best_recall = recall\r\n # best_epoch = epoch\r\n # torch.save(net, str(args.net) + '_checkpoint.t7')\r\n # torch.save(features, str(args.net) + '_features.t7')\r\n print('Best_epoch={}, Best_recall={:.4f}'.format(best_epoch, best_recall))\r\n f.close()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"ticket_classification/DuplicateBugFinder/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"409641979","text":"from logging import getLogger\n\nfrom celery import task\nfrom django.contrib.auth.models import User\nfrom django.db.models import Count\n\nfrom concordia.models import (\n Asset,\n Campaign,\n Item,\n Project,\n SiteReport,\n Tag,\n Transcription,\n UserAssetTagCollection,\n)\nfrom concordia.utils import get_anonymous_user\n\nlogger = getLogger(__name__)\n\n\n@task\ndef site_report():\n\n report = dict()\n report[\"assets_not_started\"] = 0\n report[\"assets_in_progress\"] = 0\n report[\"assets_submitted\"] = 0\n report[\"assets_completed\"] = 0\n\n asset_count_qs = Asset.objects.values_list(\"transcription_status\").annotate(\n Count(\"transcription_status\")\n )\n for status, count in asset_count_qs:\n logger.debug(\"Assets %s: %d\", status, count)\n report[f\"assets_{status}\"] = count\n\n assets_total = Asset.objects.count()\n assets_published = Asset.objects.published().count()\n assets_unpublished = Asset.objects.unpublished().count()\n\n items_published = Item.objects.published().count()\n items_unpublished = Item.objects.unpublished().count()\n\n projects_published = Project.objects.published().count()\n projects_unpublished = Project.objects.unpublished().count()\n\n campaigns_published = Campaign.objects.published().count()\n campaigns_unpublished = Campaign.objects.unpublished().count()\n\n users_registered = User.objects.all().count()\n users_activated = User.objects.filter(is_active=True).count()\n\n anonymous_transcriptions = Transcription.objects.filter(\n user=get_anonymous_user()\n ).count()\n transcriptions_saved = Transcription.objects.all().count()\n\n stats = UserAssetTagCollection.objects.aggregate(Count(\"tags\"))\n tag_count = stats[\"tags__count\"]\n\n distinct_tag_count = Tag.objects.all().count()\n\n site_report = SiteReport()\n site_report.assets_total = assets_total\n site_report.assets_published = assets_published\n site_report.assets_not_started = report[\"assets_not_started\"]\n site_report.assets_in_progress = report[\"assets_in_progress\"]\n site_report.assets_waiting_review = report[\"assets_submitted\"]\n site_report.assets_completed = report[\"assets_completed\"]\n site_report.assets_unpublished = assets_unpublished\n site_report.items_published = items_published\n site_report.items_unpublished = items_unpublished\n site_report.projects_published = projects_published\n site_report.projects_unpublished = projects_unpublished\n site_report.anonymous_transcriptions = anonymous_transcriptions\n site_report.transcriptions_saved = transcriptions_saved\n site_report.distinct_tags = distinct_tag_count\n site_report.tag_uses = tag_count\n site_report.campaigns_published = campaigns_published\n site_report.campaigns_unpublished = campaigns_unpublished\n site_report.users_registered = users_registered\n site_report.users_activated = users_activated\n site_report.save()\n\n for campaign in Campaign.objects.all():\n campaign_report(campaign)\n\n\ndef campaign_report(campaign):\n\n report = dict()\n report[\"assets_not_started\"] = 0\n report[\"assets_in_progress\"] = 0\n report[\"assets_submitted\"] = 0\n report[\"assets_completed\"] = 0\n asset_count_qs = (\n Asset.objects.filter(item__project__campaign=campaign)\n .values_list(\"transcription_status\")\n .annotate(Count(\"transcription_status\"))\n )\n for status, count in asset_count_qs:\n logger.debug(\"Campaign %s assets %s: %d\", campaign.slug, status, count)\n report[f\"assets_{status}\"] = count\n\n assets_total = Asset.objects.filter(item__project__campaign=campaign).count()\n assets_published = (\n Asset.objects.published().filter(item__project__campaign=campaign).count()\n )\n assets_unpublished = (\n Asset.objects.unpublished().filter(item__project__campaign=campaign).count()\n )\n\n items_published = (\n Item.objects.published().filter(project__campaign=campaign).count()\n )\n items_unpublished = (\n Item.objects.published().filter(project__campaign=campaign).count()\n )\n\n projects_published = Project.objects.published().filter(campaign=campaign).count()\n projects_unpublished = (\n Project.objects.unpublished().filter(campaign=campaign).count()\n )\n\n anonymous_transcriptions = Transcription.objects.filter(\n asset__item__project__campaign=campaign, user=get_anonymous_user()\n ).count()\n transcriptions_saved = Transcription.objects.filter(\n asset__item__project__campaign=campaign\n ).count()\n\n asset_tag_collections = UserAssetTagCollection.objects.filter(\n asset__item__project__campaign=campaign\n )\n\n stats = asset_tag_collections.order_by().aggregate(tag_count=Count(\"tags\"))\n tag_count = stats[\"tag_count\"]\n\n distinct_tag_list = set()\n\n for tag_collection in asset_tag_collections:\n distinct_tag_list.add(tag_collection.tags.values_list(\"pk\", flat=True))\n\n distinct_tag_count = len(distinct_tag_list)\n\n site_report = SiteReport()\n site_report.campaign = campaign\n site_report.assets_total = assets_total\n site_report.assets_published = assets_published\n site_report.assets_not_started = report[\"assets_not_started\"]\n site_report.assets_in_progress = report[\"assets_in_progress\"]\n site_report.assets_waiting_review = report[\"assets_submitted\"]\n site_report.assets_completed = report[\"assets_completed\"]\n site_report.assets_unpublished = assets_unpublished\n site_report.items_published = items_published\n site_report.items_unpublished = items_unpublished\n site_report.projects_published = projects_published\n site_report.projects_unpublished = projects_unpublished\n site_report.anonymous_transcriptions = anonymous_transcriptions\n site_report.transcriptions_saved = transcriptions_saved\n site_report.distinct_tags = distinct_tag_count\n site_report.tag_uses = tag_count\n site_report.save()\n","sub_path":"concordia/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":5937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"64994566","text":"from django.urls import path\n#\nfrom . import views\n\n#\n\n\nurlpatterns = [\n path('register/', views.RegisterView.as_view()),\n path('login/', views.login),\n path('logout/', views.logout),\n path('define-user/', views.define_user),\n path('refresh-token/', views.CustomTokenRefreshView.as_view()),\n]\n","sub_path":"account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"555210073","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom scipy.special import expit\nfrom sklearn.datasets import load_iris\n\n\ndef sample_centroids(X, k, random_state=None):\n '''Sample and return K data points from X'''\n \n if random_state:\n np.random.seed(random_state)\n\n indicees = np.random.permutation(np.arange(X.shape[0]))\n centroids = X[indicees[0:k], :]\n \n assert isinstance(centroids, np.ndarray), 'Your centroids should be in a NumPy array'\n assert centroids.shape == (k, X.shape[1]), f'Your centroids should have shape ({k}, {X.shape[1]})'\n \n return centroids\n\n\ndef euclidean(a, b):\n '''Computes the Euclidean distance between point(s) A and another point B'''\n \n distance = np.linalg.norm(a - b, axis=int(len(a.shape) > 1))\n \n assert isinstance(distance, (float, np.float64, np.ndarray)), 'Distance should be a float or a NumPy array'\n assert True if not isinstance(distance, np.ndarray) else distance.shape[0] == a.shape[0], \\\n 'Should have the same number of distances as points in A'\n \n return distance\n\n\n\ndef assign(x, centroids, distance_measure=euclidean):\n '''\n Computes the cluster assignments for X or each point\n in X given some centroids and a distance measure\n '''\n \n assignments = np.c_[[distance_measure(x, centroid) for centroid in centroids]].argmin(axis=0)\n \n assert np.all(assignments >= 0) and np.all(assignments < len(centroids)), \\\n 'Assignments should be indices of centroids'\n \n return assignments\n\n\n\ndef compute_centroids(X, assignments):\n '''Computes new centroids given points X and cluster ASSIGNMENTS'''\n \n centroids = np.array([X[assignments == cluster].mean(axis=0)\n for cluster in np.unique(assignments)])\n \n assert len(np.unique(assignments)) == len(centroids), \\\n 'You should have the same number of centroids as clusters'\n \n return centroids\n \n \n \ndef fit(X, k, max_iters=1000, tol=1e-2, initial=None, random_state=None):\n '''\n Runs k-means cycle with data X and K clusters\n '''\n \n if initial is None:\n centroids = sample_centroids(X, k, random_state=random_state)\n else:\n centroids = initial\n \n assert k == centroids.shape[0]\n\n for iteration in range(max_iters):\n assignments = assign(X, centroids)\n prev, centroids = centroids, compute_centroids(X, assignments)\n\n if np.all(np.abs(prev - centroids) < tol):\n break\n \n return centroids, assignments;\n\n\ndef plot_kmeans(X, centroids, prev_centroids=None, assignments=None):\n '''\n Creates k-means plots\n '''\n \n # BEGIN SOLUTION\n\n plt.scatter(X[:, 0], X[:, 1], c=assignments, alpha=0.9)\n plt.scatter(centroids[:, 0], centroids[:, 1], s=200, c='orange', marker='s')\n \n if prev_centroids is not None:\n plt.scatter(prev_centroids[:, 0], prev_centroids[:, 1], s=120, \n c='gray', marker='s', alpha=0.95)\n plt.legend(['data points','inital centroids', 'final centroids'])\n\n plt.title('Toy Clustering Data')\n plt.xlabel('x1')\n plt.ylabel('x2')\n \n # END SOLUTION\n ","sub_path":"hw7/utility/lab.py","file_name":"lab.py","file_ext":"py","file_size_in_byte":3176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"350504375","text":"import numpy as np\nfrom DataImport import *\n\n\nclass Perceptron:\n def __init__(self):\n self.threshold = 0\n self.weights = np.random.rand(train_data.features.shape[1], 1)\n\n def prediction(self, features_row):\n label_prediction = np.matmul(self.weights.T, features_row) + self.threshold\n label_prediction = int(label_prediction > 0)\n\n return label_prediction\n\n def train(self, train_data, max_iter=200, learning_rate=0.1, verbose=True):\n\n for i in range(max_iter):\n errors_count = 0\n for features_row, label_value in zip(train_data.features, train_data.labels):\n true_label = int(label_value[0])\n label_prediction = self.prediction(features_row)\n\n if true_label - label_prediction != 0:\n features_row = features_row.reshape(len(features_row), 1)\n # need to reshape from (8, ) to (8,1). why extracting rows from array gives something that is not a vector?\n\n self.weights = np.add(self.weights,\n (features_row * learning_rate * (true_label - label_prediction)))\n self.threshold+=learning_rate*(true_label - label_prediction)\n errors_count += 1\n\n\n if verbose:\n error_rate = abs(errors_count) / len(train_data.features)\n print('Iteration :{}, accuracy: {}, error rate: {} \\n'.format(i, 1 - error_rate, error_rate,))\n\n def test(self, test_data):\n errors_count = 0\n for features_row, label_value in zip(test_data.features, test_data.labels):\n true_label = int(label_value[0])\n label_prediction = self.prediction(features_row)\n if true_label - label_prediction != 0:\n errors_count += 1\n\n error_rate = abs(errors_count) / len(test_data.features)\n return {'error rate': error_rate,\n 'accuracy': 1 - error_rate}\n\n\nif __name__ == '__main__':\n data = DataHandlerCSV()\n data.import_data_fromcsv('sample1.csv')\n data.get_labels_and_normalize_centralize_features()\n train_data, test_data = data.train_and_test_set_split(0.8)\n mad_mind = Perceptron()\n mad_mind.train(train_data, learning_rate=0.1)\n\n print('Test results\\n', mad_mind.test(test_data))\n print('\\n\\n')\n\n data = DataHandlerCSV()\n data.import_data_fromcsv('sample2.csv')\n data.get_labels_and_normalize_centralize_features()\n train_data, test_data = data.train_and_test_set_split(0.8)\n mad_mind = Perceptron()\n mad_mind.train(train_data, learning_rate=0.01, verbose=False)\n\n print('Test results\\n', mad_mind.test(test_data))\n print('\\n\\n')\n\n data = DataHandlerCSV()\n data.import_data_fromcsv('sample3.csv')\n data.get_labels_and_normalize_centralize_features()\n train_data, test_data = data.train_and_test_set_split(0.8)\n mad_mind = Perceptron()\n mad_mind.train(train_data, learning_rate=0.01, verbose=False)\n\n print('Test results\\n', mad_mind.test(test_data))\n print('\\n\\n')\n\n","sub_path":"Perceptron.py","file_name":"Perceptron.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"422587003","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Oct 24 11:52:53 2018\r\n\r\n@author: MHAMDI\r\n\"\"\"\r\n\r\n# Importi the Keras libraries and packages\r\nfrom keras.models import Sequential\r\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D\r\nfrom keras.layers.core import Dense, Flatten\r\nfrom keras.preprocessing.image import ImageDataGenerator as IDG\r\n\r\nfrom sklearn.metrics import confusion_matrix as cm\r\n\r\n# Initialize the CNN\r\nmy_classifier = Sequential()\r\n# Step 1a: Convolution\r\nmy_classifier.add(Conv2D(32, (3, 3), input_shape=(64, 64, 3), activation='relu'))\r\n# Step 1b: Max Pooling\r\nmy_classifier.add(MaxPooling2D())\r\n# Step 2a: Convolution\r\nmy_classifier.add(Conv2D(64, (3, 3), activation='relu'))\r\n# Step 2b: Max Pooling\r\nmy_classifier.add(MaxPooling2D())\r\n# Step 3: Faltten\r\nmy_classifier.add(Flatten())\r\n# Step 4: Fully Connected Layers\r\nmy_classifier.add(Dense(128, activation = 'relu')) # First hidden layer\r\nmy_classifier.add(Dense(1, activation = 'sigmoid')) # Output: Dog or Cat \r\n# Compile the model\r\nmy_classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\r\n\r\n''' Prepocess the data '''\r\ndataset_path = '../../../Datasets/Machine Learning A-Z/Part 8 - Deep Learning/Section 40 - Convolutional Neural Networks (CNN)/dataset/'\r\ntrain_path = dataset_path +'training_set/'\r\ntest_path = dataset_path +'test_set/'\r\n\r\ndata_gen = IDG(rotation_range=0.5,\r\n width_shift_range=0.2,\r\n zoom_range=0.2,\r\n horizontal_flip=True,\r\n rescale=1./255)\r\n# Prepare the training dataset\r\ntrain_set = data_gen.flow_from_directory(train_path, target_size=(64, 64), class_mode='binary')\r\n# Prepare the test dataset\r\ntest_set = data_gen.flow_from_directory(test_path, target_size=(64, 64), class_mode='binary')\r\n# Fit the training data\r\nmy_classifier.fit_generator(train_set,\r\n epochs=25,\r\n steps_per_epoch=8000,\r\n validation_data=test_set,\r\n validation_steps=2000)\r\n# Predict the test set\r\n# y_pred = my_classifier.predict_generator(test_set, verbose=1)\r\n# Confusion matrix\r\n# tp, fp, fn, tn = cm(y_test, y_pred)\r\n# Evaluate the model\r\n# print('Accuracy is about {}%.'.format{100*((tp+tn)/(tp+tn+fp+fn))})","sub_path":"Python/machine-learning/classifier-keras.py","file_name":"classifier-keras.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"295961478","text":"import dbl\n\nfrom discord.ext import commands\n\n\nimport logging\n\n\nclass TopGG(commands.Cog):\n \"\"\"Handles interactions with the top.gg API\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n with open(\"./lib/bot/topgg.txt\", \"r\", encoding=\"utf-8\") as tf:\n self.token = tf.read() # set this to your DBL token\n self.dblpy = dbl.DBLClient(self.bot, self.token, webhook_path='/dblwebhook', webhook_auth=\"something\", webhook_port=5000)\n\n # The decorator below will work only on discord.py 1.1.0+\n # In case your discord.py version is below that, you can use self.bot.loop.create_task(self.update_stats())\n\n @commands.Cog.listener()\n async def on_dbl_vote(self, data):\n print('Received an upvote')\n print(data)\n\n @commands.Cog.listener()\n async def on_ready(self):\n if not self.bot.ready:\n self.bot.cogs_ready.ready_up(\"TopGG\")\n\n\ndef setup(bot):\n global logger\n logger = logging.getLogger('bot')\n bot.add_cog(TopGG(bot))","sub_path":"lib/NOT IN USE/TopGG.py","file_name":"TopGG.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"130285872","text":"#!/usr/bin/env python3\n\n# Solution to Project Euler problem 81\n\nimport numpy as np\n\ndef read_file(filename):\n matrix = []\n with open(filename) as file:\n for line in file:\n matrix.append([int(x) for x in line.split(',')])\n return np.asarray(matrix)\n\ndef find_min_path(matrix):\n cost_matrix = np.zeros(shape=(len(matrix), len(matrix)))\n cost_matrix[0][0] = matrix[0][0]\n \n # Start with finding cost of first row and first column\n for i in range(1,len(matrix)):\n cost_matrix[0][i] = cost_matrix[0][i-1] + matrix[0][i]\n cost_matrix[i][0] = cost_matrix[i-1][0] + matrix[i][0]\n \n # Then loop rest of the two matrixes...\n for i in range(1, len(matrix)):\n for j in range(1, len(matrix)):\n cost_matrix[i][j] = min(cost_matrix[i-1][j], cost_matrix[i][j-1]) + matrix[i][j]\n \n return cost_matrix\n\ndef solve():\n matrix = read_file('p081_matrix.txt')\n return int(find_min_path(matrix)[-1][-1])\n\nif __name__ == \"__main__\":\n print(solve())\n ","sub_path":"081-082-083/p081.py","file_name":"p081.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"42327260","text":"from django.shortcuts import render\nimport random\n\n\nclass Note:\n def __init__(self, verbose_name, image_path, audio_path):\n self.verbose_name = verbose_name\n self.image_path = image_path\n self.audio_path = audio_path\n\n\nlist_of_notes = [\n Note('До', ['img/notes/3. До.jpg', 'img/notes/10. До.jpg'], 'audio/do.mp3'),\n Note('Ре', ['img/notes/4. Ре.jpg', 'img/notes/11. Ре.jpg'], 'audio/re.mp3'),\n Note('Ми', ['img/notes/5. Ми.jpg', 'img/notes/12. Ми.jpg'], 'audio/mi.mp3'),\n Note('Фа', ['img/notes/6. Фа.jpg', 'img/notes/13. Фа.jpg'], 'audio/fa.mp3'),\n Note('Соль', ['img/notes/0. Соль.jpg', 'img/notes/7. Соль.jpg', 'img/notes/14. Соль.jpg'], 'audio/sol.mp3'),\n Note('Ля', ['img/notes/1. Ля.jpg', 'img/notes/8. Ля.jpg', 'img/notes/15. Ля.jpg'], 'audio/la.mp3'),\n Note('Си', ['img/notes/2. Си.jpg', 'img/notes/9. Си.jpg', 'img/notes/16. Си.jpg'], 'audio/si.mp3'),\n]\n\n\n# Create your views here.\ndef index(request):\n return render(request, 'dron/index.html')\n\n\ndef notes(request):\n random_notes = []\n for i in range(6):\n random_note = random.choice(list_of_notes)\n random_notes.append(random_note)\n\n context = {'notes': random_notes}\n\n return render(request, 'dron/notes.html', context)\n\n\ndef counter(request):\n return render(request, 'dron/counter.html')\n","sub_path":"dron/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"233399473","text":"import numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\nclass Planet:\n def __init__(self, x):\n self.brzina = (x[\"brzina\"])\n self.masa = (x[\"masa\"])\n self.polozaj = (x[\"polozaj\"])\n self.velicina = (x[\"velicina\"])\n self.ime = (x[\"ime\"])\n self.boja = (x[\"boja\"])\n self.pomaci = [self.polozaj]\n self.akc = np.array([0,0])\n\nclass SolarSistem:\n def __init__(self, x,y,z=0,j=0,k=0):\n lista = [x,y,z,j,k]\n self.planeti = []\n self.dt = 60*6*24\n self.G = 6.67408 * (10**(-11))\n self.t = 365*24*3600\n self.dt = 3600\n for i in range (5):\n try:\n p1 = Planet(lista[i])\n self.planeti.append(p1)\n except:\n continue\n def reset(self):\n del self.planeti\n\n def akc(self):\n for x in self.planeti:\n for y in self.planeti:\n if y != x and y !=0 and x != 0:\n akc = -self.G * (y.masa * (np.subtract(x.polozaj,y.polozaj))/ np.linalg.norm(abs(np.subtract(x.polozaj,y.polozaj)))**3)\n x.akc = np.add(akc,x.akc)\n \n def evolve(self):\n t = 0\n while t < self.t:\n self.akc()\n for i in range (len(self.planeti)):\n x = self.planeti[i]\n x.brzina1 = np.add(x.brzina,x.akc*self.dt)\n x.polozaj = np.add(x.polozaj , x.brzina1 * self.dt)\n x.pomaci.append(x.polozaj)\n t = t + self.dt\n\n def plot(self):\n self.evolve()\n fig = plt.figure()\n ax = fig.add_subplot(111)\n for x in self.planeti:\n x_list = []\n y_list = []\n for i in range (len(x.pomaci)):\n x_list.append(x.pomaci[i][0])\n y_list.append(x.pomaci[i][1])\n ax.scatter(x_list[-1], y_list[-1],s = x.velicina , c = x.boja , label = x.ime)\n ax.plot(x_list, y_list, c = x.boja)\n ax.set_xlabel('X-os')\n ax.set_ylabel('Y-os')\n ax.legend()\n ax.set_facecolor(\"black\")\n plt.show() ","sub_path":"vjezbe11/modul.py","file_name":"modul.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"88374675","text":"import os\n\nimport pytorch_lightning as pl\nimport torch\nimport torch.nn.functional as F\nimport torchmetrics\nfrom transformers import BartForConditionalGeneration\n\nfrom ..scheduler import LinearWarmupLR\n\n\nclass R3FModule(pl.LightningModule):\n \"\"\"pytorch lightning module to train BART for dialogue summarization using R3F\n https://arxiv.org/abs/2008.03156v1\n\n Attributes:\n model: BART model\n total_steps: total training steps for lr scheduling\n max_learning_rate: Max LR\n min_learning_rate: Min LR\n warmup_rate: warmup step rate\n model_save_dir: path to save model\n r3f_lambda: R3F parameter\n \"\"\"\n\n def __init__(\n self,\n model: BartForConditionalGeneration,\n total_steps: int,\n max_learning_rate: float,\n min_learning_rate: float,\n warmup_rate: float,\n model_save_dir: str,\n r3f_lambda: float = 1.0,\n ):\n super().__init__()\n\n self.save_hyperparameters(\n {\n **model.config.to_dict(),\n \"total_steps\": total_steps,\n \"max_learning_rate\": max_learning_rate,\n \"min_learning_rate\": min_learning_rate,\n \"r3f_lambda\": r3f_lambda,\n }\n )\n\n self.model = model\n self.total_steps = total_steps\n self.max_learning_rate = max_learning_rate\n self.min_learning_rate = min_learning_rate\n self.warmup_rate = warmup_rate\n self.model_save_dir = model_save_dir\n self.r3f_lambda = r3f_lambda\n\n self.noise_sampler = torch.distributions.normal.Normal(loc=0.0, scale=1e-5)\n\n def _get_symm_kl(self, noised_logits, input_logits):\n return (\n F.kl_div(\n F.log_softmax(noised_logits, dim=-1, dtype=torch.float32),\n F.softmax(input_logits, dim=-1, dtype=torch.float32),\n reduction=\"sum\",\n )\n + F.kl_div(\n F.log_softmax(input_logits, dim=-1, dtype=torch.float32),\n F.softmax(noised_logits, dim=-1, dtype=torch.float32),\n reduction=\"sum\",\n )\n ) / noised_logits.size(0)\n\n def training_step(self, batch, batch_idx):\n inputs_embeds = self.model.model.shared(batch[\"input_ids\"])\n output = self.model(\n inputs_embeds=inputs_embeds,\n attention_mask=batch[\"attention_mask\"],\n decoder_input_ids=batch[\"decoder_input_ids\"],\n decoder_attention_mask=batch[\"decoder_attention_mask\"],\n return_dict=True,\n )\n\n noise = self.noise_sampler.sample(sample_shape=inputs_embeds.shape).to(inputs_embeds)\n noise_embeds = inputs_embeds.detach().clone() + noise\n noise_output = self.model(\n inputs_embeds=noise_embeds,\n attention_mask=batch[\"attention_mask\"],\n decoder_input_ids=batch[\"decoder_input_ids\"],\n decoder_attention_mask=batch[\"decoder_attention_mask\"],\n return_dict=True,\n )\n\n labels = batch[\"decoder_input_ids\"][:, 1:].reshape(-1)\n logits = output[\"logits\"][:, :-1].reshape([labels.shape[0], -1])\n noise_logits = noise_output[\"logits\"][:, :-1].reshape([labels.shape[0], -1])\n\n symm_kl = self._get_symm_kl(noise_logits, logits)\n loss = F.cross_entropy(logits, labels, ignore_index=self.model.config.pad_token_id)\n loss += self.r3f_lambda * symm_kl\n accuracy = torchmetrics.functional.accuracy(logits, labels, ignore_index=self.model.config.pad_token_id)\n\n metrics = {\"loss\": loss, \"acc\": accuracy}\n self.log_dict(metrics, prog_bar=True, logger=True, on_step=True)\n\n return metrics\n\n def validation_step(self, batch, batch_idx):\n output = self.model(\n input_ids=batch[\"input_ids\"],\n attention_mask=batch[\"attention_mask\"],\n decoder_input_ids=batch[\"decoder_input_ids\"],\n decoder_attention_mask=batch[\"decoder_attention_mask\"],\n return_dict=True,\n )\n\n labels = batch[\"decoder_input_ids\"][:, 1:].reshape(-1)\n logits = output[\"logits\"][:, :-1].reshape([labels.shape[0], -1])\n\n loss = F.cross_entropy(logits, labels, ignore_index=self.model.config.pad_token_id)\n accuracy = torchmetrics.functional.accuracy(logits, labels, ignore_index=self.model.config.pad_token_id)\n\n metrics = {\"val_loss\": loss, \"val_acc\": accuracy}\n self.log_dict(metrics, prog_bar=True, logger=True, on_epoch=True)\n\n return metrics\n\n def test_step(self, *args, **kwargs):\n return self.validation_step(*args, **kwargs)\n\n def configure_optimizers(self):\n optimizer = torch.optim.AdamW(params=self.model.parameters(), lr=self.max_learning_rate)\n scheduler = LinearWarmupLR(\n optimizer,\n int(self.total_steps * self.warmup_rate),\n self.total_steps,\n self.min_learning_rate / self.max_learning_rate,\n )\n\n return {\n \"optimizer\": optimizer,\n \"lr_scheduler\": {\"scheduler\": scheduler, \"interval\": \"step\", \"name\": \"Learning Rate\"},\n }\n\n def validation_epoch_end(self, outputs):\n outputs = self.all_gather(outputs)\n\n if self.trainer.is_global_zero:\n val_losses = [output[\"val_loss\"].mean() for output in outputs]\n val_accs = [output[\"val_acc\"].mean() for output in outputs]\n\n val_loss_mean = sum(val_losses) / len(val_losses)\n val_acc_mean = sum(val_accs) / len(val_accs)\n\n self.model.save_pretrained(\n os.path.join(\n self.model_save_dir,\n f\"model-{self.current_epoch:02d}epoch-{self.global_step}steps-{val_loss_mean:.4f}loss-{val_acc_mean:.4f}acc\",\n ),\n )\n","sub_path":"summarizer/method/r3f.py","file_name":"r3f.py","file_ext":"py","file_size_in_byte":5828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"7915804","text":"# -*- coding:utf-8 -*-\nimport sys\nimport os\nimport cv2\nimport argparse\nimport numpy as np\n\nsys.path.append(os.path.join(os.path.dirname(__file__), '../networks'))\nfrom breathmask import BreathMask\nsys.path.append(os.path.join(os.path.dirname(__file__), '../detection'))\nfrom detect import detection_by_image\nsys.path.append(os.path.join(os.path.dirname(__file__), '../utils'))\nfrom logger import setup_logger\n\n\ndef parms():\n parser = argparse.ArgumentParser(description='CSRnet demo')\n parser.add_argument('--save_dir', type=str, default='tmp/',\n help='Directory for detect result')\n parser.add_argument('--breath_modelpath', type=str,\n default='../networks/99.55rbcar_mafa_best.pth', help='trained model')\n parser.add_argument('--threshold', default=0.65, type=float,\n help='Final confidence threshold')\n parser.add_argument('--use_cuda', default=False, type=bool,\n help='gpu run')\n parser.add_argument('--img_dir', type=str, default='tmp/',\n help='Directory for images')\n parser.add_argument('--file_in', type=str, default='tmp.txt',\n help='image namesf')\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n args = parms()\n model = BreathMask(args)\n\n log = setup_logger('../../logs/zhatuche_log.txt')\n\n # root = '/media/changshuang/My Book/ShangYu_videos/short video'\n # path = '/media/changshuang/My Book/ShangYu_Extract_Save'\n root = '/Users/yanyan/Desktop/ShangYu_videos/short video 1'\n # root = '/Users/yanyan/Desktop/ShangYu_videos/long video'\n path = '/Users/yanyan/Desktop/zhatuche_test_save'\n\n video_anno = os.path.join(os.path.dirname(__file__), '../../video/ShangYu_short_video_1_path.txt')\n with open(video_anno, 'r') as f:\n video_annos = f.readlines()\n for video_index in range(len(video_annos)):\n video_path = os.path.join(root, video_annos[video_index].strip())\n if '#' in video_path:\n print(video_path)\n continue\n log.info(video_path)\n\n cap = cv2.VideoCapture(video_path)\n if not cap.isOpened():\n log.info(\"===================don't playing================\")\n else:\n total_frame = cap.get(cv2.CAP_PROP_FRAME_COUNT)\n print('-------------------total_frame {}------------------'.format(total_frame))\n frame_index = 0\n while frame_index < total_frame:\n cap.set(cv2.CAP_PROP_POS_FRAMES, frame_index)\n ret, frame = cap.read()\n if ret:\n if frame_index % 100 == 0:\n print('##############cur frame index value ({})##############'.format(frame_index))\n if frame_index % 1 == 0:\n data_dict = detection_by_image(frame)\n datas = data_dict['data']\n if datas:\n for box_index, data in enumerate(datas):\n h = data['height']\n l = data['left']\n t = data['top']\n w = data['width']\n\n dec_img = frame[t: t + h + 1, l: l + w + 1]\n score, pre_cls = model.inference(np.array([dec_img]))\n # cv2.rectangle(frame, (l, t), (l + w, t + h), (0, 0, 255), 2)\n\n if pre_cls[0] == 1:\n save_path = os.path.join(path, 'video_pos' + str(video_index))\n else:\n save_path = os.path.join(path, 'video_neg' + str(video_index))\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n dec_img = cv2.resize(dec_img, (224, 224))\n cv2.imwrite(save_path + '/v{}_f{}_b{}.jpg'.format(video_index, frame_index, box_index), dec_img)\n log.info('************save file [v{}_f{}_b{}.jpg]************'.format(video_index, frame_index, box_index))\n # cv2.imshow('frame', frame)\n if cv2.waitKey(1) & 0xff == 27:\n break\n frame_index += 1\n else:\n log.info(\"don't playing \" + str(frame_index))\n\n cap.release()\n","sub_path":"src/extractdata/extract_pos_neg_sample.py","file_name":"extract_pos_neg_sample.py","file_ext":"py","file_size_in_byte":4708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"361703233","text":"from base_sort import BaseSort\n\nclass CountingSort(BaseSort):\n\n\tdef sort(self, arr):\n\t\t# find the min and max values to use for the counts array\n\t\tmin_val = 0\n\t\tmax_val = 0\n\t\tfor curr in arr:\n\t\t\tmin_val = min(min_val, curr)\n\t\t\tmax_val = max(max_val, curr)\n\n\t\tcounts_size = max_val - min_val +1\n\t\tcounts = [0] * counts_size\n\n\t\tfor curr in arr:\n\t\t\tcounts[curr-min_val]+=1\n\n\t\t# form prefix sum with the counts array\n\t\tfor i in range(1, counts_size):\n\t\t\tcounts[i]+=counts[i-1]\n\n\t\t# use the counts array to get the given position of any number\n\t\toutput = [None] * len(arr)\n\t\tfor i in range(len(arr)):\n\t\t\tpos = counts[arr[i]-min_val]-1\n\t\t\toutput[pos] = arr[i]\n\t\t\tcounts[arr[i]-min_val]-=1\n\n\t\tfor i in range(len(arr)):\n\t\t\tarr[i] = output[i]\n","sub_path":"SortingAlgorithms/counting_sort.py","file_name":"counting_sort.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"610129946","text":"from model.item import Item\n\n\nclass GridHelper:\n\n def __init__(self, app):\n self.app = app\n\n # navigate through grid pages\n def open_page(self, number):\n self.app.wd.find_elements_by_css_selector('ul.pagination a.ng-binding')[number].click()\n\n # sort items in grid by id, \"up\" (descending) or \"down\" (ascending)\n def order_by_id(self, order):\n while not self.is_ordered_by_id(order):\n self.app.wd.find_elements_by_css_selector('th a')[0].click() # click by \"Id\" grid header\n self.app.wait.element_present_by_css_selector('tbody') # wait for grid to be loaded\n\n # check whether the grid is already ordered by id as needed\n def is_ordered_by_id(self, order):\n # get \"class\" attribute for chevron (it's used to display what field the grid is sorted by)\n chevron_attrib = self.app.wd.find_elements_by_css_selector('th span')[0].get_attribute('class')\n # check that correct chevron is located near id field and that it's not hidden\n if 'chevron-%s' % order in chevron_attrib and 'ng-hide' not in chevron_attrib:\n return True\n return False\n\n # create list of item located on current page\n def get_current_page_items_list(self):\n wd = self.app.wd\n items = []\n for row in wd.find_elements_by_css_selector('tr.ng-scope'): # iterate through items table row by row\n id = row.find_elements_by_css_selector('.ng-binding')[0].text # first cell in a row is \"id\"\n title = row.find_elements_by_css_selector('.ng-binding')[1].text # second cell in a row is \"Title\"\n parent_id = row.find_elements_by_css_selector('.ng-binding')[2].text # third cell in a row is \"Parent id\"\n if row.find_elements_by_css_selector('.ng-binding')[3].text == 'true': # fourth cell in a row is \"Active\"\n active = True\n else:\n active = False\n items.append(Item(title=title, parent_id=parent_id, active=active, id=id))\n return list(items)\n\n # create list of all items\n def get_all_items_list(self):\n wd = self.app.wd\n if len(wd.find_elements_by_css_selector('ul.pagination')) > 0: # check whether there is more than 1 page\n items = []\n # iterate through pages to get all items from each page\n for i in range(len(wd.find_elements_by_css_selector('ul.pagination a.ng-binding'))):\n self.app.grid.open_page(i)\n items.extend(self.get_current_page_items_list()) # add items from each visited page to result list\n return list(items)\n return self.get_current_page_items_list() # if there is just one page create list of items from current page\n\n # click dropdown link by image for particular item\n def click_dropdown_menu_image(self, item_id, image):\n # locate dropdown for corresponding item by id; if not found - navigate through the pages until found\n page_num = 0\n while not self.app.wd.find_elements_by_xpath('//td[text()=\"%s\"]/..//button' % item_id):\n self.open_page(page_num)\n page_num += 1\n # expand dropdown that was found\n self.app.wd.find_elements_by_xpath('//td[text()=\"%s\"]/..//button' % item_id)[0].click()\n # click requested link in dropdown (\"show\", \"edit\" or \"delete\") located by image (\"eye\", \"pencil\" or \"trash\")\n self.app.wd.find_element_by_xpath('//td[text()=\"%s\"]/..//span[contains(@class, \"%s\")]' % (item_id, image)).click()\n if image in ('eye', 'pencil'):\n self.app.wait.element_present_by_css_selector('.panel-body') # wait for details/edit panel to be loaded\n","sub_path":"fixture/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":3680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"464121606","text":"#! python\n\n\nimport os\n\nfrom collections import OrderedDict\n\n# The project root directory and the build directory.\ntop = \".\"\nout = \"bld\"\n\n\ndef set_project_paths(ctx):\n \"\"\"Return a dictionary with project paths represented by Waf nodes.\"\"\"\n\n pp = OrderedDict()\n pp[\"PROJECT_ROOT\"] = \".\"\n pp[\"IN_DATA_CPI\"] = \"src/original_data/CPI_data\"\n pp[\"IN_DATA_CEX\"] = \"src/original_data/CEX_data\"\n pp[\"IN_DATA_GRAPH\"] = \"src/original_data/for_graph\"\n pp[\"IN_DATA_CON\"] = \"src/original_data/Concordance\"\n pp[\"IN_DATA_CEX_EXP\"] = \"src/data_management/CEX_shares\"\n pp[\"IN_DATA_CEX_PERCN\"] = \"src/data_management/CEX_percentiles\"\n pp[\"IN_DATA_MNGM_CPI\"] = \"src/data_management/CPI_management\"\n pp[\"IN_DATA_FUNCTIONS\"] = \"src/data_management/data_functions\"\n pp[\"LIBRARY\"] = \"src/library\"\n pp[\"BLD\"] = \"\"\n pp[\"OUT_DATA_CPI_CLEARED\"] = f\"{out}/out/data/CPI_prepared\"\n pp[\"OUT_DATA_WEIGHTS_AND_EXPENDITURES\"] = f\"{out}/out/data/CEX_weights_and_expenditures\"\n pp[\"OUT_DATA_CEX_CPI_MERGED\"] = f\"{out}/out/data/CEX_CPI_merged\"\n pp[\"OUT_DATA_FINAL\"] = f\"{out}/out/data/final\"\n pp[\"OUT_DATA_CPI_CON\"] = f\"{out}/out/data/CPI_and_CON\"\n pp[\"OUT_DATA_CON_PREP\"] = f\"{out}/out/data/Concordance_prepared\"\n pp[\"OUT_DATA_PERCENTILES\"] = f\"{out}/out/data/CEX_percentiles\"\n pp[\"OUT_FINAL\"] = f\"{out}/out/final\"\n pp[\"OUT_FIGURES\"] = f\"{out}/out/figures\"\n\n\n # Convert the directories into Waf nodes.\n for key, val in pp.items():\n if not key == \"ADO\":\n pp[key] = ctx.path.make_node(val)\n else:\n for adokey, adoval in val.items():\n pp[key][adokey] = ctx.path.make_node(adoval)\n return pp\n\n\ndef path_to(ctx, pp_key, *args):\n \"\"\"Return the relative path to os.path.join(*args*) in the directory\n PROJECT_PATHS[pp_key] as seen from ctx.path (i.e. the directory of the\n current wscript).\n\n Use this to get the relative path---as needed by Waf---to a file in one\n of the directory trees defined in the PROJECT_PATHS dictionary above.\n\n We always pretend everything is in the source directory tree, Waf takes\n care of the correct placing of targets and sources.\n\n \"\"\"\n\n # Implementation detail:\n # We find the path to the directory where the file lives, so that\n # we do not accidentally declare a node that does not exist.\n dir_path_in_tree = os.path.join(\".\", *args[:-1])\n # Find/declare the directory node. Use an alias to shorten the line.\n pp_key_fod = ctx.env.PROJECT_PATHS[pp_key].find_or_declare\n dir_node = pp_key_fod(dir_path_in_tree).get_src()\n # Get the relative path to the directory.\n path_to_dir = dir_node.path_from(ctx.path)\n # Return the relative path to the file.\n return os.path.join(path_to_dir, args[-1])\n\n\ndef configure(ctx):\n ctx.env.PYTHONPATH = os.getcwd()\n # Disable on a machine where security risks could arise\n ctx.env.PDFLATEXFLAGS = \"-shell-escape\"\n ctx.load(\"run_py_script\")\n ctx.load(\"sphinx_build\")\n ctx.load(\"write_project_headers\")\n # ctx.find_program(\"dot\")\n ctx.load(\"tex\")\n\n\n\ndef build(ctx):\n ctx.env.PROJECT_PATHS = set_project_paths(ctx)\n ctx.path_to = path_to\n # Generate header file(s) with project paths in \"bld\" directory\n ctx(features=\"write_project_paths\", target=\"project_paths.py\")\n ctx.add_group()\n ctx.recurse(\"src\")\n","sub_path":"wscript","file_name":"wscript","file_ext":"","file_size_in_byte":3358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"651038965","text":"\"\"\"\n Question: Determine if any 3 integers in an array sum to 0.\n Note: The following solutions assumes that repetitions\n (i.e. choosing the same array element more than once) are *allowed*,\n so the array [-5,1,10] contains a zero sum (-5-5+10) and so does [0] (0+0+0).\n [4, 2, -1, 1, -5, 6, -4] = True\n [5, 0, -5, 10, 20, 30] = True\n [1,5,9,-8,2,1,5,20] = False\n\n 3Sum where Duplicates ARE allowed\n http://blog.gainlo.co/index.php/2016/07/19/3sum/\n\"\"\"\n\ndef threeSum(arr):\n # can do the same approach as 3sum (no duplicates), where we sort first\n # can hash and look for items\n sortedArr = sorted(arr)\n for i in range(len(sortedArr)):\n if sortedArr[i] == 0:\n return True\n lowPointer, highPointer = i, len(sortedArr) - 1\n while lowPointer <= highPointer:\n if sortedArr[lowPointer] + sortedArr[highPointer] + sortedArr[i] == 0:\n return True\n elif sortedArr[lowPointer] + sortedArr[highPointer] + sortedArr[i] > 0:\n highPointer -= 1\n else:\n lowPointer += 1\n return False\n\nprint(threeSum([4, 2, -1, 1, -5, 6, -4]))\nprint(threeSum([5, 0, -5, 10, 20, 30]))\nprint(threeSum([1,5,9,-8,2,1,5,20]))\nprint(threeSum([1,5,9,-8,0,2,1,5,20]))\n","sub_path":"AnecdotalFromCompanies/ThreeSumZeroDuplicatesAllowed/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"121150586","text":"# Takes the string and places each char into a dictionary with its count. O(n)\ndef stringToDict(string):\n dict = {}\n for char in string:\n if char in dict:\n dict[char] += 1\n else:\n dict[char] = 1\n return dict\n\n# Sorts the dictionary by value in ascending order. O(n*log(n))\ndef sortDictByVals(dict):\n return {k: val for k, val in sorted(dict.items(), key=lambda item: item[1])}\n \n# Finds the unique set. O(n)\ndef findMaxSet(dict, strLength, minLength):\n dict = sortDictByVals(dict)\n finalSet = []\n for key in dict:\n if(strLength - dict[key] >= minLength):\n strLength -= dict[key]\n finalSet.append(key)\n else:\n return finalSet\n\n# Main program. Runs in O(n*log(n))\ndef main():\n string = 'If you want to jumpstart the process of talking to us about this role, here’s a little challenge: write a program that outputs the largest unique set of characters that can be removed from this paragraph without letting its length drop below 50. For example: [‘H’, ‘i’, ‘!’, ‘ ’]'\n minLength = 50\n\n charDict = stringToDict(string)\n result = findMaxSet(charDict, len(string), minLength)\n print(result)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"LargestUniqueSet.py","file_name":"LargestUniqueSet.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"367163577","text":"_base_ = './fpn_poolformer_s12_8xb4-40k_ade20k-512x512.py'\ncheckpoint_file = 'https://download.openmmlab.com/mmclassification/v0/poolformer/poolformer-s36_3rdparty_32xb128_in1k_20220414-d78ff3e8.pth' # noqa\n\n# model settings\nmodel = dict(\n backbone=dict(\n arch='s36',\n init_cfg=dict(\n type='Pretrained', checkpoint=checkpoint_file,\n prefix='backbone.')))\n","sub_path":"configs/poolformer/fpn_poolformer_s36_8x4_512x512_40k_ade20k.py","file_name":"fpn_poolformer_s36_8x4_512x512_40k_ade20k.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"269021907","text":"import os\nimport signal\nimport subprocess\nfrom subprocess import call\n\nimport psutil\n\nfrom options.constants import Constants\n\n\nclass CleanTask(Constants):\n '''Clean up old processes with standard names (e.g., pipefork) if any.'''\n\n tasks = [\n \"pipefork\", \"parsecmgmt\", \"blackscholes\", \"bodytrack\", \"canneal\", \"dedup\", \"facesim\",\n \"ferret\", \"fluidanimate\", \"raytrace\", \"streamcluster\", \"swaptions\", \"vips\", \"x264\", \"tee\",\n \"python3\", \"run.sh\", \"java\", \"httpd\", \"trigger-con0.sh\", \"trigger-con1.sh\", \"mysqld\",\n \"memcached\", \"trigger\"\n ]\n\n @staticmethod\n def __outputPrefix():\n return \"[clean] \"\n\n @staticmethod\n def __printTaskInfoStart(options):\n if options.verbose >= 1:\n print(\"\\n\" + CleanTask.__outputPrefix() + \"Executing clean task...\")\n\n @staticmethod\n def __printTaskInfoEnd(options):\n if options.verbose >= 1:\n print(CleanTask.__outputPrefix() + \"Done executing clean task...\\n\")\n\n @staticmethod\n def cleanTask(options):\n CleanTask.__printTaskInfoStart(options)\n CleanTask.__usingPsutil(options)\n CleanTask.__printTaskInfoEnd(options)\n\n @staticmethod\n def __usingPs(options):\n ret = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)\n out, _ = ret.communicate()\n for line in out.splitlines():\n for name in CleanTask.tasks:\n if name in line.decode(\"utf-8\"):\n pid = int(line.split(None, 1)[0])\n if pid != os.getpid():\n print(\"Killing task\", name, \" with pid:\", pid)\n print(call([\"ps\", str(pid)]))\n print(line)\n if not options.printOnly:\n if options.sameMachine:\n print(CleanTask.__outputPrefix() + \"Do you want to continue? [y/n]\")\n # This is an important operation, confirm with\n # the user before executing.\n ans = input()\n else: # Ignore if a remote machine\n ans = \"y\"\n if ans.lower() == \"y\" or ans.lower() == \"yes\":\n try:\n os.kill(pid, signal.SIGKILL)\n except ProcessLookupError:\n return False\n return True\n\n @staticmethod\n def __usingPsutil(options):\n cid = os.getpid()\n try:\n for proc in psutil.process_iter():\n for name in CleanTask.tasks:\n # print(\"Checking for process named \", name)\n if proc.name() == name and proc.pid != cid:\n kill = True\n # There could be other \"python3\" processes in the\n # system\n if proc.name() == \"python3\":\n li_procCmdLine = proc.cmdline()\n str_cmdLine = CleanTask.VISER_EXP + \"/src/main.py\"\n if str_cmdLine not in li_procCmdLine:\n kill = False\n elif proc.name() == \"java\":\n # Kill simulator backends\n li_procCmdLine = proc.cmdline()\n found = False\n for elem in li_procCmdLine:\n if ((CleanTask.VISERSIM_ROOT in elem) or\n (CleanTask.MESISIM_ROOT in elem) or\n (CleanTask.RCCSISIM_ROOT in elem)):\n found = True\n kill = found\n\n if kill:\n if not options.printOnly:\n # Always print before killing a process\n print(\"** Killing task\", name, \"with pid:\", proc.pid)\n call([\"ps\", str(proc.pid)])\n if options.sameMachine:\n # print(CleanTask.__outputPrefix() +\n # \"Do you want to continue? [y/n]\")\n ans = \"y\" # input()\n else:\n ans = \"y\"\n if ans.lower() == \"y\" or ans.lower() == \"yes\":\n try:\n proc.kill()\n except psutil.ZombieProcess:\n print(\"ZombieProcess\")\n except psutil.NoSuchProcess:\n print(\"NoSuchProcess\")\n except psutil.AccessDenied:\n print(\"AccessDenied\")\n except psutil.TimeoutExpired:\n print(\"TimeoutExpired\")\n else:\n print(\"# Skipping process\", name, \"with pid:\", proc.pid)\n call([\"ps\", str(proc.pid)])\n else:\n # print(\"# Skipping process\", name, \"with pid:\",\n # proc.pid)\n # call([\"ps\", str(proc.pid)])\n pass\n except psutil.NoSuchProcess:\n pass\n","sub_path":"sim-framework/src/tasks/cleantask.py","file_name":"cleantask.py","file_ext":"py","file_size_in_byte":5620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"240234696","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 ('airline', '0002_auto_20150929_1923'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Flight',\n fields=[\n ('num', models.IntegerField(serialize=False, unique=True, primary_key=True)),\n ('linking', models.CharField(max_length=128)),\n ],\n ),\n migrations.CreateModel(\n name='Staff',\n fields=[\n ('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),\n ('name', models.CharField(null=True, max_length=64)),\n ('profession', models.SmallIntegerField(null=True)),\n ],\n ),\n ]\n","sub_path":"airline/migrations/0003_flight_staff.py","file_name":"0003_flight_staff.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"577787562","text":"import sys\nimport codecs\nimport re\nimport regex\nimport subprocess\nimport numpy\nfIn = codecs.open(sys.argv[1], \"r\", \"utf-8\")\nfOut = codecs.open(sys.argv[2], \"w\", \"utf-8\")\n\n\nscores = {}\nfilename = \"\"\nfileParts = []\ncurrent = {}\nfor i in fIn:\n if(i.strip() == \"^$\"):\n continue\n if not i[0].isupper():\n filename = i.strip()\n fileParts = filename.split(\"-\")\n if(fileParts[0] not in scores):\n scores[fileParts[0]] = {}\n if(fileParts[2] not in scores[fileParts[0]]):\n scores[fileParts[0]][fileParts[2]] = {}\n if(fileParts[1] not in scores[fileParts[0]][fileParts[2]]):\n scores[fileParts[0]][fileParts[2]][fileParts[1]] = {}\n current = scores[fileParts[0]][fileParts[2]][fileParts[1]]\n current[\"ED\"] = {}\n current[\"Accuracy\"] = {}\n \n current[\"ED\"][\"L5\"] = []\n current[\"ED\"][\"L10\"] = []\n current[\"ED\"][\"G10\"] = []\n current[\"ED\"][\"ID\"] = []\n current[\"ED\"][\"All\"] = []\n\n current[\"Accuracy\"][\"L5\"] = []\n current[\"Accuracy\"][\"L10\"] = []\n current[\"Accuracy\"][\"G10\"] = []\n current[\"Accuracy\"][\"ID\"] = []\n current[\"Accuracy\"][\"All\"] = []\n\n\n else:\n scoreParts = i.strip().split(\" \")\n scoreType = \"\"\n filterType = \"\"\n\n if(\"Accuracy\" in i):\n scoreType = \"Accuracy\"\n elif(\"ED\" in i):\n scoreType = \"ED\"\n else:\n continue\n if(\"<= 5\" in i):\n filterType = \"L5\"\n elif(\"<= 10\" in i):\n filterType = \"L10\"\n elif(\"> 10\" in i):\n filterType = \"G10\"\n elif \"ID\" in i:\n filterType = \"ID\"\n else:\n filterType = \"All\"\n current[scoreType][filterType].append(float(scoreParts[-1]))\n\nAverages = {}\nVariances = {}\nfor i in sorted(scores.keys()): #languages\n fOut.write(i.upper() + \"\\t\")\n for j in scores[i]:\n if(j not in Averages): #low, med, high\n Averages[j] = {}\n Variances[j] = {}\n\n for k in scores[i][j]: #exptType\n if(k not in Averages[j]):\n Averages[j][k] = {}\n Variances[j][k] = {}\n for m in scores[i][j][k]: #Accuracy or ED\n if(m not in Averages[j][k]):\n Averages[j][k][m] = {}\n Variances[j][k][m] = {}\n\n for n in scores[i][j][k][m]: #L5, L10, G10, All\n if(n not in Averages[j][k][m]):\n Averages[j][k][m][n] = []\n Variances[j][k][m][n] = []\n if(len(scores[i][j][k][m][n]) != 0):\n currentAverage = numpy.mean(scores[i][j][k][m][n])\n currentVariance = numpy.var(scores[i][j][k][m][n])\n else:\n currentAverage = 0.0\n currentVariance = 0.0\n Averages[j][k][m][n].append(currentAverage)\n Variances[j][k][m][n].append(currentVariance)\n #fOut.write(i + \" \" + j + \" \" + k + \" \" + m + \" \" + n + \" Average: \" + str(currentAverage) + \"\\n\")\n #fOut.write(i + \" \" + j + \" \" + k + \" \" + m + \" \" + n + \" Variance: \" + str(currentVariance) + \"\\n\")\nfOut.write(\"OVERALL AVERAGE\\n\")\n#print(Averages[\"finnish\"][\"high\"][\"teacher\"])\n#for i in Averages:\nfor j in Averages:\n for k in Averages[j]:\n for m in Averages[j][k]:\n for n in Averages[j][k][m]:\n fOut.write(j + \" \" + k + \" \" + m + \" \" + n + \" AVERAGE: \")\n\n for i in sorted(scores.keys()):\n if(len(scores[i][j][k][m][n]) == 0):\n fOut.write(\"0.0\" + \"\\t\")\n else:\n fOut.write(str(numpy.mean(scores[i][j][k][m][n])) + \"\\t\")\n #fOut.write(str(numpy.var(scores[i][j][k][m][n])) + \"\\t\")\n\n #currentVariance = numpy.mean(Variances[i][j][k][m][n])\n #fOut.write(\"VARIANCE: \" + j + \" \" + k + \" \" + m + \" \" + n + \" : \" + str(currentVariance) + \"\\n\")\n currentAverage = numpy.mean(Averages[j][k][m][n])\n fOut.write(str(currentAverage) + \"\\n\")\n \n fOut.write(j + \" \" + k + \" \" + m + \" \" + n + \" VARIANCE: \")\n for i in sorted(scores.keys()):\n #fOut.write(str(numpy.mean(scores[i][j][k][m][n])) + \"\\t\")\n if(len(scores[i][j][k][m][n]) == 0):\n fOut.write(\"0.0\" + \"\\t\")\n else:\n fOut.write(str(numpy.var(scores[i][j][k][m][n])) + \"\\t\")\n\n #currentAverage = numpy.mean(Averages[i][j][k][m][n])\n #fOut.write(\"AVERAGE: \" + j + \" \" + k + \" \" + m + \" \" + n + \" : \" + str(currentAverage) + \"\\n\")\n currentVariance = numpy.mean(Variances[j][k][m][n])\n fOut.write(str(currentVariance) + \"\\n\")\n\n\nfIn.close()\nfOut.close()\n","sub_path":"re-score.py","file_name":"re-score.py","file_ext":"py","file_size_in_byte":5063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"644269764","text":"# -- coding:utf-8 --\n\ndef shellSort(lst,delta):\n for deltaK in delta:\n shellInsert(lst,deltaK)\n\n\ndef shellInsert(lst,deltaK):\n # 获取序列长度\n length = len(lst)\n # 类似插入排序,只不过这次的跳跃间隔为deltaK\n for i in range(deltaK,length,1):\n if lst[i-deltaK] > lst[i]:\n current = lst[i]\n preInd = i - deltaK\n while preInd >= 0 and lst[preInd] > current:\n lst[preInd + deltaK] = lst[preInd]\n preInd -= deltaK\n lst[preInd + deltaK] = current\n\n\nif __name__ == \"__main__\":\n alist = [9,5,6,7,3,2,5,7,0,23,42,75,97,43,23,4,5,435,765,23]\n # delta初始值设置为待排序序列长度的一半,依次递减到1为止\n delta = range(10,0,-1)\n shellSort(alist,delta)\n print(alist)","sub_path":"SortMethod/ShellSort.py","file_name":"ShellSort.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"567257634","text":"#!/usr/bin/env python3\n######################\n#\n# dumps given file (with optional offset)\n# as a FAT32 volume boot record\n#\n\nimport os\nimport sys\nfrom ctypes import *\nimport binascii\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n \"-o\",\n \"--offset\",\n type=int,\n help=\"offset into file to start FAT32 VBR\",\n default=0\n)\nparser.add_argument(\n \"file\",\n help=\"file to open\"\n)\nargs = parser.parse_args()\n\nclass Dos20BPB(Structure):\n _fields_ = [\n (\"bytes_per_sector\", c_ushort),\n (\"sectors_per_cluster\", c_ubyte),\n (\"reserved_sectors\", c_ushort),\n (\"number_of_fats\", c_ubyte),\n (\"number_of_root_dirs\", c_ushort),\n (\"total_sectors\", c_ushort),\n (\"media_descriptor\", c_ubyte),\n (\"sectors_per_fat\", c_ushort)\n ]\n _pack_ = 1\n\nclass Dos331BPB(Structure):\n _fields_ = [\n (\"dos_2_0_bpb\", Dos20BPB),\n (\"sectors_per_track\", c_ushort),\n (\"number_of_heads\", c_ushort),\n (\"hidden_sectors\", c_uint),\n (\"logical_sectors\", c_uint)\n ]\n _pack_ = 1\n\nclass Fat32BPB(Structure):\n _fields_ = [\n (\"dos_3_31_bpb\", Dos331BPB),\n (\"sectors_per_fat\", c_uint),\n (\"drive_description\", c_ushort),\n (\"version\", c_ushort),\n (\"root_cluster\", c_uint),\n (\"info_sector\", c_ushort),\n (\"boot_copy_sector\", c_ushort),\n (\"reserved\", c_ubyte * 12),\n (\"phys_drive\", c_ubyte),\n (\"unknown\", c_ubyte),\n (\"extended_boot_sig\", c_ubyte),\n (\"volume_id\", c_uint),\n (\"volume_label\", c_ubyte * 11),\n (\"filesystem_type\", c_ubyte * 8)\n ]\n _pack_ = 1\n\nclass Fat32VBR(Structure):\n _fields_ = [\n (\"jump\", c_ubyte * 3),\n (\"oem_name\", c_ubyte * 8),\n (\"fat32_bpb\", Fat32BPB)\n ]\n\n _pack_ = 1\n\nclass DirectoryEntry(Structure):\n _fields_ = [\n (\"name\", c_ubyte * 8),\n (\"ext\", c_ubyte * 3),\n (\"attributes\", c_ubyte),\n (\"ext_attrs\", c_ubyte),\n (\"time_subsecond\", c_ubyte),\n (\"create_time\", c_ushort),\n (\"create_date\", c_ushort),\n (\"access_date\", c_ushort),\n (\"high_sector\", c_ushort),\n (\"modify_time\", c_ushort),\n (\"modify_date\", c_ushort),\n (\"low_sector\", c_ushort),\n (\"size\", c_uint)\n ]\n _pack_ = 1\n\ndef getfield(attr):\n if isinstance(attr, Structure):\n return dump(attr)\n elif isinstance(attr, int):\n return \"{} (hex: 0x{:02x})\".format(attr, attr)\n else:\n raw = bytes(attr)\n asc = \"\"\n for b in raw:\n if b < 128:\n a = chr(b)\n else:\n a = '.'\n asc += a\n return \"{} bytes: '{}' {}\".format(len(attr), asc, binascii.hexlify(raw))\n\ndump_indent = 0\n\ndef dump(ctype):\n global dump_indent\n print(\"{}{} ({} bytes)\".format(\" \"*dump_indent, ctype.__class__.__name__, sizeof(ctype)))\n dump_indent += 2\n for k in ctype._fields_:\n name = k[0]\n printable = getfield(getattr(ctype, name))\n if printable:\n print(\"{}{} => {}\".format(\" \"*dump_indent, name, printable))\n dump_indent -= 2\n\ndef cstr(b):\n string = \"\"\n for i in b:\n if i == 0:\n break\n string += chr(i)\n return string\n\ndef decode_lfn(final, lfn):\n bstr = []\n for i in range(0, len(lfn)):\n raw = bytes(sizeof(lfn[i]))\n memmove(raw, addressof(lfn[i]), sizeof(lfn[i]))\n for idx in [1,3,5,7,9,14,16,18,20,22,24,28,30]:\n bstr.append(raw[idx])\n print(\"lfn: '{}'\".format(cstr(bstr)))\n dump(final)\n# all of the files from the linux Fat32 driver appear to\n# use the LFN notation, even when small.\n print(\"first cluster number:\", final.low_sector)\n print(\"calculated offset:\", FIRST_CLUSTER + (final.low_sector-2) * SECTOR_SIZE)\n print(\"FAT entry:\", FAT_BEGIN + (final.low_sector-2) * 4)\n\ndef main():\n print(\"Fat32VBR => {} bytes\".format(sizeof(Fat32VBR)))\n fd = open(args.file, \"rb\")\n fd.seek(args.offset)\n raw = fd.read(sizeof(Fat32VBR))\n print(\" | read {} bytes\".format(len(raw)))\n vbr = Fat32VBR()\n memmove(addressof(vbr), raw, sizeof(vbr))\n dump(vbr)\n\n fat32 = vbr.fat32_bpb\n dos331 = fat32.dos_3_31_bpb\n dos20 = dos331.dos_2_0_bpb\n sector_size = dos20.bytes_per_sector\n fat_begin = dos20.reserved_sectors\n cluster_begin = fat_begin + (dos20.number_of_fats * fat32.sectors_per_fat)\n\n print(\"[offset from beginning of fat...]\")\n print(\"fat_begin {:x}\".format(fat_begin * sector_size))\n print(\"cluster_begin {:x}\".format(cluster_begin * sector_size))\n\n global FIRST_CLUSTER\n global SECTOR_SIZE\n global FAT_BEGIN\n FAT_BEGIN = fat_begin * sector_size\n offset = cluster_begin * sector_size\n FIRST_CLUSTER = offset\n SECTOR_SIZE = sector_size\n\n offset += args.offset\n fd.seek(offset)\n\n lfn = []\n for i in range(0, 32):\n raw = fd.read(sizeof(DirectoryEntry))\n de = DirectoryEntry()\n memmove(addressof(de), raw, sizeof(DirectoryEntry))\n print(\"DirectoryEntry {} at {}\".format(i,\n cluster_begin + (i*sizeof(DirectoryEntry))))\n if de.name[0] == 0xe5:\n print(\" [invalid]\")\n continue\n elif de.attributes == 0xf:\n print(\" [part of an lfn entry]\")\n lfn.append(de)\n elif len(lfn) != 0:\n decode_lfn(de, lfn)\n lfn = []\n elif de.name[0] == 0x00:\n print(\"END OF DIRECTORY ENTRIES\")\n break\n else:\n print(\"regular entry:\")\n dump(de)\n\nmain()\n","sub_path":"tools/fat_vbr.py","file_name":"fat_vbr.py","file_ext":"py","file_size_in_byte":5084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"535902619","text":"import dash\r\nimport dash_core_components as dcc\r\nimport dash_html_components as html\r\nfrom dash.dependencies import Input, Output\r\nimport pandas as pd\r\nimport plotly.graph_objs as go\r\n\r\n# Load CSV file from Datasets folder\r\ndf3 = pd.read_csv('../Datasets/Olympic2016Rio.csv')\r\ndf4 = pd.read_csv('../Datasets/Weather2014-15.csv')\r\n\r\napp = dash.Dash()\r\n\r\n# Bubble chart\r\nnew_df = df4.groupby(['month']).agg({'average_min_temp': 'mean', 'average_max_temp': 'mean'}).reset_index()\r\nnew_df['MonthIndex'] = pd.to_datetime(new_df['month'], format='%B', errors='coerce').dt.month\r\nnew_df = new_df.sort_values(by=\"MonthIndex\")\r\n# Preparing data\r\ndata_bubblechart = [\r\n go.Scatter(x=new_df['month'],\r\n y=new_df['average_max_temp'],\r\n text=new_df['month'],\r\n mode='markers',\r\n marker=dict(size=new_df['average_min_temp'],color=new_df['average_max_temp'], showscale=True))]\r\n# Layout\r\napp.layout = html.Div(children=[\r\n html.H1(children='Python Dash',\r\n style={\r\n 'textAlign': 'center',\r\n 'color': '#ef3e18'\r\n }\r\n ),\r\n html.Div('Web dashboard for Data Visualization using Python', style={'textAlign': 'center'}),\r\n html.Br(),\r\n html.Br(),\r\n html.Hr(style={'color': '#7FDBFF'}),\r\n html.H3('Bubble chart', style={'color': '#df1e56'}),\r\n dcc.Graph(id='graph6',\r\n figure={\r\n 'data': data_bubblechart,\r\n 'layout': go.Layout(title='Monthly Temps',\r\n xaxis={'title': 'Month'}, yaxis={'title': 'Temp'},\r\n hovermode='closest')\r\n }\r\n ),\r\n\r\n])\r\n\r\nif __name__ == '__main__':\r\n app.run_server()","sub_path":"Dashboard-Part4.py","file_name":"Dashboard-Part4.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"5004909","text":"G = {1:{1:0, 2:1, 3:12},\n 2:{2:0, 3:9, 4:3},\n 3:{3:0, 5:5},\n 4:{3:4, 4:0, 5:13, 6:15},\n 5:{5:0, 6:4},\n 6:{6:0}}\n\ndef Dijkstra(G,v0,v_des,INF=999):\n #distance = [999]*len(G)\n #node_list = [list(G.keys()),distance]\n distances = {vertex: float('infinity') for vertex in G}\n current_pos = v0\n dist = 0\n while(current_pos!=v_des):\n distances.pop(current_pos)\n for neighbor, weight in G[current_pos].items():\n if(neighbor!=current_pos):\n distances[neighbor] = min(distances[neighbor],dist + weight)\n current_pos = min(distances,key=distances.get)\n dist = min(distances.values())\n return dist\n\nprint(Dijkstra(G,1,6))","sub_path":"Homework2/Question3.py","file_name":"Question3.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"348252159","text":"import pandas as pd\n\ndf = pd.DataFrame({\n \"id\":[1,2,3,4,5,6], \n \"raw_grade\":['a', 'b', 'b', 'a', 'a', 'e']\n})\n\n# CSV\ndf.to_csv('foo.csv') # write\npd.read_csv('foo.csv') # read\n\n# HDF5\ndf.to_hdf('foo.h5', 'df') # write\npd.read_hdf('foo.h5', 'df') # read\n\n# Excel\ndf.to_excel('foo.xlsx', sheet_name='Sheet1') # write\npd.read_excel('foo.xlsx', 'Sheet1', index_col=None, na_values=['NA']) # read","sub_path":"2편/get_in_out_data.py","file_name":"get_in_out_data.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"609561043","text":"import datetime\nimport re\n\nfrom questionary import Validator, ValidationError\n\n# Validators for questionary\n# We don't want to make these too complicated for now, but implement\n# a base validation to get content for the dataset and pipeline\n# questionary is only interested in the ValidationError, no return values needed\n\n\nclass DateValidator(Validator):\n def validate(self, document):\n try:\n datetime.datetime.strptime(document.text, \"%Y-%m-%d\")\n except ValueError:\n raise ValidationError(\n message=\"Please enter a valid date in format YYYY-MM-DD, example: 2020-05-01)\",\n cursor_position=len(document.text),\n )\n\n\nclass SimpleEmailValidator(Validator):\n def validate(self, document):\n # Just check for a \".\" after a \"@\"\n if not re.match(r\"[^@]+@[^@]+\\.[^@]+\", document.text):\n raise ValidationError(\n message=\"Please enter a valid email, example: user@example.org\",\n cursor_position=len(document.text),\n )\n\n\nclass PhoneValidator(Validator):\n def validate(self, document):\n if not re.match(r\"^[0-9]+$\", document.text):\n raise ValidationError(\n message=\"Please enter a valid phone - all numbers and no space, example: 232334455\",\n cursor_position=len(document.text),\n )\n\n\nclass EnvironmentValidator(Validator):\n def validate(self, document):\n if not re.match(r\"^[0-9]+$\", document.text) or len(document.text) != 12:\n raise ValidationError(\n message=\"Valid environment ID, as provided by Origo, 12 characters. Example: 123456789876\",\n cursor_position=len(document.text),\n )\n\n\nclass TitleValidator(Validator):\n def validate(self, document):\n if len(document.text) < 5:\n raise ValidationError(\n message=\"Title must be at least 5 characters\",\n cursor_position=len(document.text),\n )\n\n\nclass KeywordValidator(Validator):\n def validate(self, document):\n keywords = [x.strip() for x in document.text.split(\",\")]\n if len(keywords) == 0:\n return True\n have_valid_keywords = False\n for keyword in keywords:\n keyword = keyword.strip()\n if len(keyword) >= 3:\n have_valid_keywords = True\n else:\n have_valid_keywords = False\n break\n if have_valid_keywords is False:\n raise ValidationError(\n message=\"At least one keyword, each must be at least 3 characters\",\n cursor_position=len(document.text),\n )\n","sub_path":"origocli/commands/datasets/boilerplate/validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"450247384","text":"#!/usr/bin/env python\n#\n# -*- coding: utf-8 -*-\n\"\"\"\n__author__ = 'CodeFace'\n\"\"\"\nimport datetime\nimport binascii\nfrom .util import *\nfrom qtum_electrum.qtum import hash160_to_p2pkh\nfrom qtum_electrum.i18n import _\nfrom qtum_electrum.plugin import run_hook\nfrom qtum_electrum.util import block_explorer_URL, open_browser, TxMinedInfo\n\n\nclass TokenBalanceList(MyTreeWidget):\n filter_columns = [0, 1, 2]\n\n def __init__(self, parent=None):\n MyTreeWidget.__init__(self, parent, self.create_menu, [_('Name'), _('Bind Address'), _('Balance')], 1)\n self.setSelectionMode(QAbstractItemView.ExtendedSelection)\n self.setSortingEnabled(True)\n\n def on_update(self):\n item = self.currentItem()\n current_key = item.data(0, Qt.UserRole) if item else None\n self.clear()\n for key in sorted(self.parent.tokens.keys()):\n token = self.parent.tokens[key]\n balance_str = '{}'.format(token.balance / 10 ** token.decimals)\n # balance_str = format_satoshis(token.balance, is_diff=False, num_zeros=0,\n # decimal_point=token.decimals, whitespaces=True)\n item = QTreeWidgetItem([token.name, token.bind_addr, balance_str])\n item.setData(0, Qt.UserRole, token.contract_addr)\n item.setTextAlignment(0, Qt.AlignLeft | Qt.AlignVCenter)\n item.setTextAlignment(2, Qt.AlignRight | Qt.AlignVCenter)\n item.setFont(2, QFont(MONOSPACE_FONT))\n self.addTopLevelItem(item)\n if key == current_key:\n self.setCurrentItem(item)\n run_hook('update_tokens_tab', self)\n\n def on_doubleclick(self, item, column):\n bind_addr = item.text(1)\n contract_addr = item.data(0, Qt.UserRole)\n key = '{}_{}'.format(contract_addr, bind_addr)\n token = self.parent.tokens.get(key, None)\n self.parent.token_send_dialog(token)\n\n def create_menu(self, position):\n menu = QMenu()\n selected = self.selectedItems()\n multi_select = len(selected) > 1\n if not selected:\n menu.addAction(_(\"Add Token\"), lambda: self.parent.token_add_dialog())\n elif not multi_select:\n item = selected[0]\n name = item.text(0)\n bind_addr = item.text(1)\n contract_addr = item.data(0, Qt.UserRole)\n key = '{}_{}'.format(contract_addr, bind_addr)\n token = self.parent.tokens.get(key, None)\n column = self.currentColumn()\n column_title = self.headerItem().text(column)\n column_data = '\\n'.join([item.text(column) for item in selected])\n menu.addAction(_(\"Copy %s\") % column_title, lambda: self.parent.app.clipboard().setText(column_data))\n menu.addAction(_(\"View Info\"), lambda: self.parent.token_view_dialog(token))\n menu.addAction(_(\"Send\"), lambda: self.parent.token_send_dialog(token))\n menu.addAction(_(\"Delete\"), lambda: self.parent.delete_token(key))\n URL = block_explorer_URL(self.config, {'addr': bind_addr, 'token': contract_addr})\n if URL:\n menu.addAction(_(\"View on block explorer\"), lambda: open_browser(URL))\n run_hook('create_tokens_menu', menu, selected)\n menu.exec_(self.viewport().mapToGlobal(position))\n\n\nclass TokenHistoryList(MyTreeWidget):\n filter_columns = [0, 1, 2]\n\n def __init__(self, parent=None):\n MyTreeWidget.__init__(self, parent, self.create_menu, ['', _('Date'), _('Bind Address'), _('Token'), _('Amount')], 2)\n self.setSelectionMode(QAbstractItemView.ExtendedSelection)\n self.setSortingEnabled(True)\n\n def on_update(self):\n wallet = self.parent.wallet\n item = self.currentItem()\n current_key = item.data(0, Qt.UserRole) if item else None\n self.clear()\n for hist in wallet.get_token_history():\n _from, to, amount, token, txid, height, conf, timestamp, call_index, log_index = hist\n payout = False\n if _from == to:\n amount = 0\n if hash160_to_p2pkh(binascii.a2b_hex(to)) == token.bind_addr:\n balance_str = '+'\n else:\n balance_str = '-'\n payout = True\n balance_str += '{}'.format(amount / 10 ** token.decimals)\n tx_mined_info = TxMinedInfo(height, conf, timestamp, None, None)\n status, status_str = wallet.get_tx_status(txid, tx_mined_info)\n icon = read_QIcon(TX_ICONS[status])\n\n item = QTreeWidgetItem(['', status_str, token.bind_addr, token.symbol, balance_str])\n item.setIcon(0, icon)\n item.setToolTip(0, str(conf) + \" confirmation\" + (\"s\" if conf != 1 else \"\"))\n item.setData(0, Qt.UserRole, txid)\n item.setTextAlignment(0, Qt.AlignLeft | Qt.AlignVCenter)\n self.addTopLevelItem(item)\n if txid == current_key:\n self.setCurrentItem(item)\n if payout:\n item.setForeground(3, QBrush(QColor(\"#BC1E1E\")))\n item.setForeground(4, QBrush(QColor(\"#BC1E1E\")))\n run_hook('update_token_hist_tab', self)\n\n def on_doubleclick(self, item, column):\n pass\n\n def format_date(self, d):\n return str(datetime.date(d.year, d.month, d.day)) if d else _('None')\n\n def create_menu(self, position):\n menu = QMenu()\n selected = self.selectedItems()\n multi_select = len(selected) > 1\n if not selected:\n pass\n elif not multi_select:\n item = selected[0]\n txid = item.data(0, Qt.UserRole)\n column = self.currentColumn()\n column_title = self.headerItem().text(column)\n column_data = '\\n'.join([item.text(column) for item in selected])\n menu.addAction(_(\"Copy %s\") % column_title, lambda: self.parent.app.clipboard().setText(column_data))\n menu.addAction(_(\"Copy Transaction ID\"), lambda: self.parent.app.clipboard().setText(txid))\n URL = block_explorer_URL(self.config, {'tx': txid})\n if URL:\n menu.addAction(_(\"View on block explorer\"), lambda: open_browser(URL))\n run_hook('create_token_hist_menu', menu, selected)\n menu.exec_(self.viewport().mapToGlobal(position))","sub_path":"qtum_electrum/gui/qt/token_list.py","file_name":"token_list.py","file_ext":"py","file_size_in_byte":6338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"420329548","text":"import sys\n\nfrom evalLib import evaluation\n\n########################## GETTING FILE PATHS ##########################\n\ntruthFile = sys.argv[1]\npredFile = sys.argv[2]\n\n########################## EXTRACTING VALUES ##########################\n\ntruthVals = open(truthFile).readlines()\ntruthVals = [val.strip().split() for val in truthVals]\nyTrue = [int(val[0]) for val in truthVals]\n\npredVals = open(predFile).readlines()\npredVals = [val.strip().split() for val in predVals]\nyPred = [int(val[0]) for val in predVals]\n\n########################## CALCULATING AND PRINTING SCORES ##########################\n\nevl = evaluation(yTrue, yPred)\nscore = {}\n\nif '-accuracy' in sys.argv:\n\tscore['Accuracy'] = evl.accuracy_score()\n\nif '-balanced_error' in sys.argv:\n\tscore['Balanced Error'] = evl.balanced_error_score()\n\nif '-balanced_score' in sys.argv:\n\tscore['Balanced Accuracy'] = evl.balanced_accuracy_score()\n\nif len(score.keys()) != 0:\n\tfor key in score.keys():\n\t\tprint('\\n', key, ' : ', score[key])\n\nif evl.accuracy_score() != 1.0:\n\tprint('\\n Index of Wrong Predicions:')\n\tfor i, (true, pred) in enumerate(zip(yTrue, yPred)):\n\t\tif true != pred:\n\t\t\tprint(i)\n","sub_path":"Evaluation/evalScript.py","file_name":"evalScript.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"439474800","text":"import sys\nimport time\nimport tensorflow as tf\nimport numpy as np\nimport generator as gen\nimport discriminator as dis\nfrom ops import *\n\ndef estimate_time(startTime, totalCycles, finishedCycles):\n timePast = time.time() - startTime\n if timePast < 5:\n return '...calculating...'\n cps = finishedCycles/timePast\n secsLeft = (totalCycles - finishedCycles)/cps\n\n # double slash is an integer division, returns the quotient without the decimal\n hrs, secs = secsLeft//3600, secsLeft % 3600\n mins, secs = secs//60, secs % 60\n\n timeStr = '%.0fh%.0fm%.0fs remaining'%(hrs, mins, secs) + ' '*10\n return timeStr\n\n# placeholders\nreal_im_flat = tf.placeholder(tf.float32, shape=[None, 784])\ny_logit = tf.placeholder(tf.float32, shape=[None, 10])\nsample = tf.placeholder(tf.float32, shape=[None, gen.sample_dim])\n# model begins\nreal_image = tf.reshape(real_im_flat, [-1,28,28,1])\nfake_image = gen.generate(sample, y_logit)\n\njudge_fake, dis_loss, dis_accuracy = dis.params(real_image, fake_image, y_logit)\ng_loss, gen_accuracy = gen.params(judge_fake)\n\ngen_loss = tf.reduce_mean(tf.square(real_image - fake_image))+(0.2*g_loss)\n\nall_vars = tf.trainable_variables()\ndis_vars = [v for v in all_vars if 'discriminator' in v.name]\ngen_vars = [v for v in all_vars if 'generator' in v.name]\n\n# learning for the discriminator seems good in range *0.45 to *0.5\ndis_optim = tf.train.AdamOptimizer(learning_rate, beta1 = momDecay).minimize(dis_loss, var_list=dis_vars)\ngen_optim = tf.train.AdamOptimizer(learning_rate, beta1 = momDecay).minimize(gen_loss, var_list=gen_vars)\n\n# this runs a single training step for the discriminator\ndef dis_train_step(sess, dataset):\n batch = dataset.train.next_batch(batch_size)\n vals = sess.run([dis_optim, dis_accuracy, gen_accuracy], feed_dict={\n real_im_flat: batch[0],\n y_logit: batch[1],\n sample: rand_noise([batch_size, gen.sample_dim]),\n })\n\n return vals\n\n# this runs a single training step for the generator\ndef gen_train_step(sess, dataset):\n batch = dataset.train.next_batch(batch_size)\n vals = sess.run([gen_optim, dis_accuracy, gen_accuracy], feed_dict={\n y_logit: batch[1],\n sample: rand_noise([batch_size, gen.sample_dim]),\n real_im_flat: batch[0],\n })\n\n return vals\n\n# this tests the discriminator with a single test batch\ndef test_dis(sess, dataset):\n batch = dataset.test.next_batch(batch_size)\n acc = sess.run(dis_accuracy, feed_dict={\n real_im_flat: batch[0],\n y_logit: batch[1],\n sample: rand_noise([batch_size, gen.sample_dim]),\n })\n\n return acc\n\n# this method tests the generator with a single test batch\ndef test_gen(sess, dataset):\n batch = dataset.test.next_batch(batch_size)\n acc = sess.run(gen_accuracy, feed_dict={\n y_logit: batch[1],\n sample: rand_noise([batch_size, gen.sample_dim]),\n })\n\n return acc\n\n# This method saves both discriminator and generator separately\ndef saveModels(sess):\n print('\\nsaving models... please wait...')\n gen_saver = tf.train.Saver(gen_vars)\n dis_saver = tf.train.Saver(dis_vars)\n gen_saver.save(sess, gen_model_path)\n dis_saver.save(sess, dis_model_path)\n print('\\nModels saved.')\n\ndef loadModels(sess):\n print('\\nloading models... please wait...')\n gen_saver = tf.train.Saver(gen_vars)\n dis_saver = tf.train.Saver(dis_vars)\n gen_saver.restore(sess, gen_model_path)\n dis_saver.restore(sess, dis_model_path)\n print('\\nModels loaded.')\n\n# this method generates sample images for all digits and saves them\n# the save location is given as a parameter, if nothing is given it is\n# saved in current location\ndef saveImages(sess,saveFolder):\n inp = []\n for i in range(batch_size):\n num = i % 10\n l = [0]*10\n l[num] = 1\n inp.append(l)\n\n img_array = sess.run(fake_image, feed_dict={\n y_logit: inp,\n sample: rand_noise([batch_size, gen.sample_dim]),\n })\n\n for i in range(10):\n img_data = img_array[i:i+1]\n img = toImage(img_data)\n img.save(saveFolder + '%s.png'%i)\n\n# starting a session and training the gn model\n","sub_path":"GAN/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"103802296","text":"#!/usr/bin/env python\n__author__ = 'Sergei F. Kliver'\nimport argparse\nfrom RouToolPa.Routines import AnnotationsRoutines\nfrom RouToolPa.Collections.General import IdList\n\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"-i\", \"--input_gff\", action=\"store\", dest=\"input_gff\", required=True,\n help=\"Input .gff file\")\nparser.add_argument(\"-f\", \"--value_file\", action=\"store\", dest=\"value_file\", required=True,\n help=\"Value with values to seek for\")\nparser.add_argument(\"-o\", \"--output_gff\", action=\"store\", dest=\"output_gff\", required=True,\n help=\"Output .gff file\")\nparser.add_argument(\"-d\", \"--description_fields\", action=\"store\",\n dest=\"field_id_list\",\n type=lambda s: s.split(\",\"), required=True,\n help=\"Comma-separated list of fields in gff description to check\")\n\n\n\nargs = parser.parse_args()\n\nvalue_list = IdList(filename=args.value_file)\nAnnotationsRoutines.extract_gff_records_by_description_value(args.input_gff, args.output_gff, args.field_id_list, value_list,\n retain_comments=False)\n","sub_path":"scripts/annotation/gff/extract_gff_records_by_description_value.py","file_name":"extract_gff_records_by_description_value.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"577977308","text":"from Crypto.Cipher import Blowfish\nfrom Crypto import Random\n\ndef pad(s, block_size):\n # Dam bao kich thuoc cua file nhap vao la boi cua AES.block_size\n padding_size = block_size - len(s) % block_size\n return s + b'\\0' * padding_size,padding_size\n\ndef encrypt_blowfish(message,key):\n iv = Random.new().read(Blowfish.block_size)\n cipher = Blowfish.new(key,Blowfish.MODE_CFB,iv)\n\n padded_mess, padding_size = pad(message,Blowfish.block_size)\n\n return iv + cipher.encrypt(padded_mess) + bytes(padding_size)\n\ndef decrypt_blowfish(ciphertext,key):\n iv = ciphertext[:Blowfish.block_size]\n cipher = Blowfish.new(key,Blowfish.MODE_CFB,iv)\n\n message = cipher.decrypt(ciphertext[Blowfish.block_size:-1])\n # *-1 de dung cho cau lenh ke tiep\n padding_size = ciphertext[-1]*(-1)\n # Ban chat cau nay la tu dau den vi tri -padding_size, padding_size da duoc *-1 o cau lenh truoc\n if padding_size == 0:\n return message\n else:\n return message[:padding_size]","sub_path":"source code/simple-cryptographic-program/algorithms/algorithms_blowfish.py","file_name":"algorithms_blowfish.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"622670304","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport exeapp.models.idevices.fields\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('exeapp', '0008_auto_20150312_1332'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='multichoiceoptionidevice',\n name='feedback',\n field=exeapp.models.idevices.fields.RichTextField(help_text='Feedback text for the answer', verbose_name='Feedback', null=True, blank=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='freetextversion',\n name='date_created',\n field=models.DateTimeField(default=datetime.datetime(2015, 8, 7, 11, 23, 50, 8738)),\n ),\n migrations.AlterField(\n model_name='protectedfreetextversion',\n name='date_created',\n field=models.DateTimeField(default=datetime.datetime(2015, 8, 7, 11, 23, 50, 31445)),\n ),\n ]\n","sub_path":"exeapp/migrations/0009_auto_20150807_1123.py","file_name":"0009_auto_20150807_1123.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"157562969","text":"import glob\nimport pandas as pd\nimport os\nimport sys\n\n#from Tkinter import *\nimport tkinter\nfrom tkinter import *\nfrom tkinter import filedialog\n\nimport matplotlib.mlab\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport scipy.io.wavfile as wav\nfrom numpy.lib import stride_tricks\nimport soundfile as sf\n\n\ndef select_dir():\n root = tkinter.Tk()\n print(\"Select the folder containing .wav files to create spectrograms\")\n root.directory = filedialog.askdirectory()\n print (root.directory)\n wav_path = root.directory + \"/\"\n original_dir_name = root.directory.split(\"/\")[-1]\n png_path = root.directory.rsplit(\"/\",1)[0] + \"/\"+ \"spectrograms\" + \"/\" + \"spectrograms_\" + original_dir_name + \"/\"\n\n print(\"wav_path: \")\n print(wav_path)\n\n print(\"original_dir_name: \")\n print(original_dir_name)\n\n print(\"png_path: \")\n print(png_path)\n return wav_path, original_dir_name, png_path\n\ndef create_spectrograms():\n\n wav_path, original_dir_name, png_path = select_dir()\n wavfiles = glob.glob(os.path.join(wav_path+\"*.wav\"))\n count = 0\n\n for audiofile in wavfiles:\n png_name = audiofile.split(\"/\")[-1].rsplit(\".\",1)[0]\n png_final_path = png_path + png_name + \".png\"\n\n if os.path.exists(png_path):\n plotstft(audiofile,png_final_path)\n count +=1\n print(count)\n else:\n os.makedirs(png_path)\n plotstft(audiofile,png_final_path)\n count +=1\n print(count)\n return count, png_path, wav_path\n\ndef create_spectrograms_internal(wav_path,png_path):\n\n #wav_path, original_dir_name, png_path = select_dir()\n wavfiles = glob.glob(os.path.join(wav_path+\"*.wav\"))\n count = 0\n\n for audiofile in wavfiles:\n png_name = audiofile.split(\"/\")[-1].rsplit(\".\",1)[0]\n #png_path = png_path + \"/\" + \"spectrograms\" + \"/\"\n png_final_path = png_path + png_name + \".png\"\n print(png_final_path)\n\n if os.path.exists(png_path):\n plotstft(audiofile,png_final_path)\n count +=1\n print(count)\n else:\n os.makedirs(png_path)\n plotstft(audiofile,png_final_path)\n count +=1\n print(count)\n return count \n\n\n\n\"\"\" short time fourier transform of audio signal \"\"\"\ndef stft(sig, frameSize, overlapFac=0.5, window=np.hanning):\n win = window(frameSize)\n hopSize = int(frameSize - np.floor(overlapFac * frameSize))\n \n # zeros at beginning (thus center of 1st window should be for sample nr. 0)\n samples = np.append(np.zeros(int(np.floor(frameSize/2.0))), sig) \n # cols for windowing\n cols = int(np.ceil( (len(samples) - frameSize) / float(hopSize)) + 1)\n # zeros at end (thus samples can be fully covered by frames)\n samples = np.append(samples, np.zeros(frameSize))\n \n frames = stride_tricks.as_strided(samples, shape=(int(cols), frameSize), strides=(samples.strides[0]*hopSize, samples.strides[0])).copy()\n frames *= win\n \n return np.fft.rfft(frames) \n \n\"\"\" scale frequency axis logarithmically \"\"\"\ndef logscale_spec(spec, sr=44100, factor=20.):\n timebins, freqbins = np.shape(spec)\n\n scale = np.linspace(0, 1, freqbins) ** factor\n scale *= (freqbins-1)/max(scale)\n scale = np.unique(np.round(scale))\n scale = scale.astype(int)\n \n # create spectrogram with new freq bins\n newspec = np.complex128(np.zeros([timebins, len(scale)]))\n for i in range(0, len(scale)):\n if i == len(scale)-1:\n newspec[:,i] = np.sum(spec[:,scale[i]:], axis=1)\n else: \n newspec[:,i] = np.sum(spec[:,scale[i]:scale[i+1]], axis=1)\n \n # list center freq of bins\n allfreqs = np.abs(np.fft.fftfreq(freqbins*2, 1./sr)[:freqbins+1])\n freqs = []\n for i in range(0, len(scale)):\n if i == len(scale)-1:\n freqs += [np.mean(allfreqs[scale[i]:])]\n else:\n freqs += [np.mean(allfreqs[scale[i]:scale[i+1]])]\n \n return newspec, freqs\n\n\n\"\"\" plot spectrogram\"\"\"\n\ndef plotstft(audiopath, plotpath=None, colormap=\"jet\", binsize=2**10):\n samples, samplerate = sf.read(audiopath)\n s = stft(samples, binsize)\n \n sshow, freq = logscale_spec(s, factor=1.0, sr=samplerate)\n ims = 20.*np.log10(np.abs(sshow)/10e-6) # amplitude to decibel\n \n timebins, freqbins = np.shape(ims)\n \n #plt.figure(figsize=(15, 7.5))\n plt.imshow(np.transpose(ims), origin=\"lower\", aspect=\"auto\", cmap=colormap, interpolation=\"none\")\n #plt.tick_params(direction='out', length=6, width=2, colors='r',grid_color='r', grid_alpha=0.5)\n plt.tick_params(axis='both', which='both', bottom='off',top='off',left='off',right='off',labelbottom='off',labelleft='off')\n #plt.colorbar()\n #plt.axis('off')\n\n fig = plt.gcf()\n\n #plt.xlabel(\"time (s)\")\n #plt.ylabel(\"frequency (hz)\")\n #plt.xlim([0, timebins-1])\n #plt.ylim([0, freqbins])\n\n #xlocs = np.float32(np.linspace(0, timebins-1, 5))\n #plt.xticks(xlocs, [\"%.02f\" % l for l in ((xlocs*len(samples)/timebins)+(0.5*binsize))/samplerate])\n #ylocs = np.int16(np.round(np.linspace(0, freqbins-1, 10)))\n #plt.yticks(ylocs, [\"%.02f\" % freq[i] for i in ylocs])\n \n fig.savefig(plotpath, bbox_inches=\"tight\", pad_inches=0)\n #else:\n #plt.show()\n \n plt.clf()\n plt.close()\n\n\n#plotstft(\"/home/aratrika/aratrika_work/data sets/UrbanSound_ex/test_wav_png/7061-6-0-0.wav\")\n#count = create_spectrograms()\ndef iterate_folds_spec():\n wav_path_list=[]\n png_path_list=[]\n user_input = 'c'\n while user_input == 'c': \n #count = create_spectrograms()\n wav_path, original_dir_name, png_path = select_dir()\n wav_path_list.append(wav_path)\n png_path_list.append(png_path)\n print('Press c to continue selecting paths: \\n')\n user_input = raw_input()\n length = int(len(wav_path_list))\n for j in range(length):\n print(wav_path_list[j])\n print(png_path_list[j])\n \n for i in range(length):\n create_spectrograms_internal(wav_path_list[i],png_path_list[i])\n\ndef copy_spec(): #Copy spectrograms from one folder to another\n user_input = 'c'\n while(user_input == 'c'):\n root1 = tikinter.Tk()\n print(\"Select the folder containing spectrograms: \")\n root1.directory = filedialog.askdirectory()\n print (root1.directory)\n selected_path = root1.directory + \"/\"\n\n print(\"Select the folder to be copied to: \")\n root2 = tkinter.Tk()\n root2.directory = filedialog.askdirectory()\n print (root2.directory)\n final_path = root2.directory + \"/\"\n\n specfiles = glob.glob(os.path.join(selected_path+\"*.png\"))\n\n for spectrograms in specfiles:\n if os.path.exists(final_path):\n shutil.copy2(spectrograms,final_path)\n else:\n os.makedirs(final_path)\n shutil.copy2(spectrograms,final_path)\n print('Enter c to continue')\n user_input = raw_input()\n\n\n\ndef see_spec(wav_path,png_path):\n\n #wav_path, original_dir_name, png_path = select_dir()\n wavfiles = glob.glob(os.path.join(wav_path+\"*.wav\"))\n count = 0\n\n for audiofile in wavfiles:\n png_name = audiofile.split(\"/\")[-1].rsplit(\".\",1)[0]\n #png_path = png_path + \"/\" + \"spectrograms\" + \"/\"\n png_final_path = png_path + png_name + \".png\"\n print(png_final_path)\n\n if os.path.exists(png_path):\n plotstft(audiofile,png_final_path)\n count +=1\n print(count)\n else:\n os.makedirs(png_path)\n plotstft(audiofile,png_final_path)\n count +=1\n print(count)\n return count\n\n\n\n\n# create_spectrograms()","sub_path":"spec_plot.py","file_name":"spec_plot.py","file_ext":"py","file_size_in_byte":7740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"503942141","text":"\"\"\"Logging configuration.\"\"\"\n\nimport os\nimport sys\nimport logging\n\n\nDEFAULT_LOGGING_LEVEL = logging.WARNING\n\n\nasync def configure_logging():\n # Using environ variables directly because we need to configure logging\n # before doing other stuff (loading settings as well)\n\n log_level = logging.WARNING\n log_level_str = os.environ.get('LOGGING_LEVEL', 'WARNING')\n\n default_loglevel_warning = False\n if log_level_str.isnumeric():\n log_level = int(log_level_str)\n elif hasattr(logging, log_level_str):\n log_level = getattr(logging, log_level_str)\n elif log_level_str != '':\n default_loglevel_warning = True\n\n formatter = MyFormatter()\n\n handler = logging.StreamHandler(sys.stdout)\n handler.setFormatter(formatter)\n\n logger = logging.getLogger()\n logger.setLevel(log_level)\n logger.handlers = []\n logger.addHandler(handler)\n\n if default_loglevel_warning:\n logging.warning(f'No such logging level: {log_level}.')\n\n logging.warning(f'Using logging level: {log_level}')\n\n\nclass MyFormatter(logging.Formatter):\n\n def __init__(self):\n template = '[ {asctime} {levelname} - {module}:{lineno}] {message}'\n dtm_template = '%y.%m.%d %H:%M:%S'\n super().__init__(template, dtm_template, style='{')\n","sub_path":"lib/recrierbot/recrierbot/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"457824671","text":"from unittest import skip\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\nfrom .base import FunctionalTest\n\n\nclass LayoutTest(FunctionalTest):\n\n def test_layout_and_styling(self):\n # Edith goes to the home page\n self.browser.get(self.server_url)\n self.browser.set_window_size(1024,768)\n\n # She notices the input box is nicely centred\n inputbox = self.browser.find_element_by_tag_name('input')\n self.assertAlmostEqual(\n inputbox.location['x'] + inputbox.size['width']/2,\n 512,\n delta=3\n )\n\n # she starts a new list and sees the input is nicely centered there too\n inputbox.send_keys('testing\\n')\n inputbox = self.browser.find_element_by_tag_name('input')\n self.assertAlmostEqual(\n inputbox.location['x'] + inputbox.size['width']/2,\n 512,\n delta = 3\n )\n\n","sub_path":"functional_tests/test_layout_and_styling.py","file_name":"test_layout_and_styling.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"95067929","text":"__all__ = [\"filter_params\", \"unfreeze\", \"freeze\"]\n\nfrom mantisshrimp.imports import *\n\n\nBN_TYPES = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d)\n\n\ndef filter_params(\n module: nn.Module, bn: bool = True, only_trainable=False\n) -> Generator:\n \"\"\"Yields the trainable parameters of a given module.\n\n Args:\n module: A given module\n bn: If False, don't return batch norm layers\n\n Returns:\n Generator\n \"\"\"\n children = list(module.children())\n if not children:\n if not isinstance(module, BN_TYPES) or bn:\n for param in module.parameters():\n if not only_trainable or param.requires_grad:\n yield param\n else:\n for child in children:\n for param in filter_params(\n module=child, bn=bn, only_trainable=only_trainable\n ):\n yield param\n\n\ndef unfreeze(params):\n for p in params:\n p.requires_grad = True\n\n\ndef freeze(params):\n for p in params:\n p.requires_grad = False\n","sub_path":"mantisshrimp/models/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"559928083","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 16 9:30:00 2019\n\n@author: dotax\n@title: 构建多层动态双向RNN网络对MNIST数据集进行分类\n\"\"\"\n\nimport tensorflow as tf\nfrom tensorflow.contrib import rnn\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets(\"/data/\", one_hot=True)\n\n#定义参数\nlearning_rate = 0.001\ntraining_iters = 1000\nbatch_size = 128\ndisplay_step = 10\n\n#网络模型参数设置\nn_input = 28 #MNIST data输入(img shape:28*28)\nn_steps = 28 #序列个数\nn_hidden = 128 #隐藏层节点个数\nn_classes = 10 #MNIST分类数(0~9 digits)\n\ntf.reset_default_graph() #用于清除默认图形堆栈并重置全局默认图形.\n\n#定义占位符\nx = tf.placeholder(tf.float32, [None, n_steps, n_input])\ny = tf.placeholder(tf.float32, [None, n_classes])\n\nx1 = tf.unstack(x, n_steps, 1)\nlstm_fw_cell = rnn.BasicLSTMCell(n_hidden, forget_bias=1.0)\n#反向cell\nlstm_bw_cell = rnn.BasicLSTMCell(n_hidden, forget_bias=1.0)\n'''1、使用括号括起来[lstm_fw_cell], [lstm_bw_cell],这样就生成了正方向各带有一层RNN的双向RNN网络。\n 如果想再增加层,需要再中括号里接着添加即可。'''\n#outputs, _, _ = rnn.statck_bidirectional_rnn([lstm_fw_cell], [lstm_bw_cell],\n # x1, dtype=tf.float32)\n\n'''2、循环方式生成多个RNN放在list里,list多层双向RNN'''\n'''\nstacked_rnn = []\nstacked_bw_rnn = []\nfor i in range(3):\n stacked_rnn.append(tf.contrib.rnn.LSTMCell(n_hidden))\n stacked_bw_rnn.append(tf.contrib.rnn.LSTMCell(n_hidden))\noutputs, _, _ = rnn.stack_bidirectional_rnn(stacked_rnn, stacked_bw_rnn,\n x1, dtype=tf.float32)\n'''\n'''3、构建一个多层cell放到stack_bidirectional_rnn中,multi双向RNN'''\nstacked_rnn = []\nstacked_bw_rnn = []\nfor i in range(3):\n stacked_rnn.append(tf.contrib.rnn.LSTMCell(n_hidden))\n stacked_bw_rnn.append(tf.contrib.rnn.LSTMCell(n_hidden))\nmcell = tf.contrib.rnn.MultiRNNCell(stacked_rnn)\nmcell_bw = tf.contrib.rnn.MultiRNNCell(stacked_bw_rnn)\noutputs, _, _ = rnn.stack_bidirectional_dynamic_rnn([mcell], [mcell_bw],\n x, dtype=tf.float32)\n'''注意:使用MultiRNNCell时,虽然是多层,但是从外表上看仍是一个输入,stack_rnn_bidirectional_rnn只关心输入的\ncell类是不是多个,而不会取识别输入的cell里面是否还包含多个。在这种情况下,就必须将输入用中括号括起来,\n让其变成为list类型'''\n\n#outputs = tf.concat(outputs, 2) #concat函数 维度越高,括号越小\noutputs = tf.transpose(outputs, [1, 0, 2])\nprint(outputs[0].shape, outputs.shape)\n'''输出的outputs类型如下:\n (?,256) (28,?,256)前一个括号中是送往下一层的结果,仍然是256即正、反向的结果是concat,\n 后一个括号中是ouputs的形状。\n'''\n\npred = tf.contrib.layers.fully_connected(outputs[-1], n_classes,\n activation_fn=None)\nloss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))\nopt = tf.train.AdamOptimizer(learning_rate).minimize(loss)\n#计算准确率\ncorrect_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, dtype=tf.float32))\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n iter = 1\n while iter < training_iters:\n #获取下一批次的数据\n batch_x, batch_y = mnist.train.next_batch(batch_size=batch_size)\n #改变数据结构,获取到的数据格式为[number, 784]要改变才能匹配我们定义的placehodler\n batch_x = batch_x.reshape(batch_size, n_input, n_steps)\n\n sess.run(opt, feed_dict={x: batch_x, y: batch_y})\n\n if iter % 10 == 0:\n los = sess.run(loss, feed_dict={x: batch_x, y: batch_y})\n acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y})\n print(\"Iter\", iter, \",Minibatch Loss=\", los, \",Training Accuracy=\", acc)\n iter = iter + 1\n print(\"Finished!\")\n # 也可以计算测试集的准确度 参考结果 : 99.21%\n test_data = mnist.test.images.reshape((-1, n_input, n_steps))\n test_label = mnist.test.labels\n print(\"Testing Accuracy:\", sess.run(accuracy, feed_dict={x: test_data, y: test_label}))\n","sub_path":"多层动态BI-RNN_MNIST.py","file_name":"多层动态BI-RNN_MNIST.py","file_ext":"py","file_size_in_byte":4396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"434093618","text":"#!/bin/env python\n#----------------------------------------------------------------------------\n# Name: Main.py\n# Purpose: Testing lots of stuff, controls, window types, etc.\n#\n# Author: Robin Dunn\n#\n# Created: A long time ago, in a galaxy far, far away...\n# RCS-ID: $Id: Main.py 55621 2008-09-14 19:55:48Z RD $\n# Copyright: (c) 1999 by Total Control Software\n# Licence: wxWindows license\n#----------------------------------------------------------------------------\n\n# FIXME List:\n# * Problems with flickering related to ERASE_BACKGROUND\n# and the splitters. Might be a problem with this 2.5 beta...?\n# UPDATE: can't see on 2.5.2 GTK - maybe just a faster machine :)\n# * Demo Code menu?\n# * Annoying switching between tabs and resulting flicker\n# how to replace a page in the notebook without deleting/adding?\n# Where is SetPage!? tried freeze...tried reparent of dummy panel....\n# AG: It looks like this issue is fixed by Freeze()ing and Thaw()ing the\n# main frame and not the notebook\n\n# TODO List:\n# * UI design more professional (is the new version more professional?)\n# * save file positions (new field in demoModules) (@ LoadDemoSource)\n# * Update main overview\n\n# * Why don't we move _treeList into a separate module\n\nimport sys, os, time, traceback, types\n\nimport wx \nimport wx.aui\nimport wx.html\n\nimport version\n\n# We won't import the images module yet, but we'll assign it to this\n# global when we do.\n######################images = None\nimport images \n\n# For debugging\n##wx.Trap();\n##print \"wx.VERSION_STRING = %s (%s)\" % (wx.VERSION_STRING, wx.USE_UNICODE and 'unicode' or 'ansi')\n##print \"pid:\", os.getpid()\n##raw_input(\"Press Enter...\")\n\n\n#---------------------------------------------------------------------------\n\nUSE_CUSTOMTREECTRL = False\nALLOW_AUI_FLOATING = False\nDEFAULT_PERSPECTIVE = \"Default Perspective\"\n\n#---------------------------------------------------------------------------\n\n\n\nmainOverview = \"\"\"\n

wxPython

\n\n

wxPython is a GUI toolkit for the Python programming\nlanguage. It allows Python programmers to create programs with a\nrobust, highly functional graphical user interface, simply and easily.\nIt is implemented as a Python extension module (native code) that\nwraps the popular wxWindows cross platform GUI library, which is\nwritten in C++.\n\n

Like Python and wxWindows, wxPython is Open Source which\nmeans that it is free for anyone to use and the source code is\navailable for anyone to look at and modify. Or anyone can contribute\nfixes or enhancements to the project.\n\n

wxPython is a cross-platform toolkit. This means that the\nsame program will run on multiple platforms without modification.\nCurrently supported platforms are 32-bit Microsoft Windows, most Unix\nor unix-like systems, and Macintosh OS X. Since the language is\nPython, wxPython programs are simple, easy to write and easy to\nunderstand.\n\n

This demo is not only a collection of test cases for\nwxPython, but is also designed to help you learn about and how to use\nwxPython. Each sample is listed in the tree control on the left.\nWhen a sample is selected in the tree then a module is loaded and run\n(usually in a tab of this notebook,) and the source code of the module\nis loaded in another tab for you to browse and learn from.\n\n\"\"\"\n\n\n\n\"\"\"\nclass Share (object):\n def __init__(self):\n pass\n\"\"\"\n\nshare=type('Share', (), {})()\n\nshare.demoPngs = [\"overview\", \"recent\", \"frame\", \"dialog\", \"moredialog\", \"core\",\n \"book\", \"customcontrol\", \"morecontrols\", \"layout\", \"process\", \"clipboard\",\n \"images\", \"miscellaneous\"]\n\nshare.treeList = [\n # new stuff\n ('Recent Additions/Updates', [\n 'RichTextCtrl',\n 'Treebook',\n 'Toolbook',\n 'BitmapFromBuffer',\n 'RawBitmapAccess',\n 'DragScroller',\n 'DelayedResult',\n 'ExpandoTextCtrl',\n 'ButtonPanel',\n 'FlatNotebook',\n 'CustomTreeCtrl',\n 'AboutBox',\n 'AlphaDrawing',\n 'GraphicsContext',\n 'CollapsiblePane',\n 'ComboCtrl',\n 'OwnerDrawnComboBox',\n 'BitmapComboBox',\n 'I18N',\n 'Img2PyArtProvider',\n 'SearchCtrl',\n 'SizedControls',\n 'AUI_MDI',\n 'TreeMixin',\n 'AdjustChannels',\n 'RendererNative',\n 'PlateButton',\n 'ResizeWidget',\n 'Cairo',\n 'Cairo_Snippets',\n ]),\n\n # managed windows == things with a (optional) caption you can close\n ('Frames and Dialogs', [\n 'AUI_DockingWindowMgr',\n 'AUI_MDI',\n 'Dialog',\n 'Frame',\n 'MDIWindows',\n 'MiniFrame',\n 'Wizard',\n ]),\n\n # the common dialogs\n ('Common Dialogs', [\n 'AboutBox',\n 'ColourDialog',\n 'DirDialog',\n 'FileDialog',\n 'FindReplaceDialog',\n 'FontDialog',\n 'MessageDialog',\n 'MultiChoiceDialog',\n 'PageSetupDialog',\n 'PrintDialog',\n 'ProgressDialog',\n 'SingleChoiceDialog',\n 'TextEntryDialog',\n ]),\n\n # dialogs from libraries\n ('More Dialogs', [\n 'ImageBrowser',\n 'ScrolledMessageDialog',\n ]),\n\n # core controls\n ('Core Windows/Controls', [\n 'BitmapButton',\n 'Button',\n 'CheckBox',\n 'CheckListBox',\n 'Choice',\n 'ComboBox',\n 'Gauge',\n 'Grid',\n 'Grid_MegaExample',\n 'ListBox',\n 'ListCtrl',\n 'ListCtrl_virtual',\n 'ListCtrl_edit',\n 'Menu',\n 'PopupMenu',\n 'PopupWindow',\n 'RadioBox',\n 'RadioButton',\n 'SashWindow',\n 'ScrolledWindow',\n 'SearchCtrl', \n 'Slider',\n 'SpinButton',\n 'SpinCtrl',\n 'SplitterWindow',\n 'StaticBitmap',\n 'StaticBox',\n 'StaticText',\n 'StatusBar',\n 'StockButtons',\n 'TextCtrl',\n 'ToggleButton',\n 'ToolBar',\n 'TreeCtrl',\n 'Validator',\n ]),\n \n ('\"Book\" Controls', [\n 'AUI_Notebook',\n 'Choicebook',\n 'FlatNotebook',\n 'Listbook',\n 'Notebook',\n 'Toolbook',\n 'Treebook',\n ]),\n\n ('Custom Controls', [\n 'AnalogClock',\n 'ButtonPanel',\n 'ColourSelect',\n 'ComboTreeBox',\n 'CustomTreeCtrl',\n 'Editor',\n 'FlatNotebook',\n 'GenericButtons',\n 'GenericDirCtrl',\n 'LEDNumberCtrl',\n 'MultiSash',\n 'PlateButton',\n 'PopupControl',\n 'PyColourChooser',\n 'TreeListCtrl',\n ]),\n \n # controls coming from other libraries\n ('More Windows/Controls', [\n 'ActiveX_FlashWindow',\n 'ActiveX_IEHtmlWindow',\n 'ActiveX_PDFWindow',\n 'BitmapComboBox',\n 'Calendar',\n 'CalendarCtrl',\n 'CheckListCtrlMixin',\n 'CollapsiblePane',\n 'ComboCtrl',\n 'ContextHelp',\n 'DatePickerCtrl',\n 'DynamicSashWindow',\n 'EditableListBox',\n 'ExpandoTextCtrl',\n 'FancyText',\n 'FileBrowseButton',\n 'FloatBar', \n 'FloatCanvas',\n 'FoldPanelBar',\n 'HtmlWindow',\n 'HyperLinkCtrl',\n 'IntCtrl',\n 'MVCTree', \n 'MaskedEditControls',\n 'MaskedNumCtrl',\n 'MediaCtrl',\n 'MultiSplitterWindow',\n 'OwnerDrawnComboBox',\n 'Pickers',\n 'PyCrust',\n 'PyPlot',\n 'PyShell',\n 'ResizeWidget',\n 'RichTextCtrl',\n 'ScrolledPanel',\n 'SplitTree',\n 'StyledTextCtrl_1',\n 'StyledTextCtrl_2',\n 'TablePrint',\n 'Throbber',\n 'Ticker',\n 'TimeCtrl',\n 'TreeMixin',\n 'VListBox',\n ]),\n\n # How to lay out the controls in a frame/dialog\n ('Window Layout', [\n 'GridBagSizer',\n 'LayoutAnchors',\n 'LayoutConstraints',\n 'Layoutf',\n 'RowColSizer',\n 'ScrolledPanel',\n 'SizedControls',\n 'Sizers',\n 'XmlResource',\n 'XmlResourceHandler',\n 'XmlResourceSubclass',\n ]),\n\n # ditto\n ('Process and Events', [\n 'DelayedResult',\n 'EventManager',\n 'KeyEvents',\n 'Process',\n 'PythonEvents',\n 'Threads',\n 'Timer',\n ##'infoframe', # needs better explanation and some fixing\n ]),\n\n # Clipboard and DnD\n ('Clipboard and DnD', [\n 'CustomDragAndDrop',\n 'DragAndDrop',\n 'URLDragAndDrop',\n ]),\n\n # Images\n ('Using Images', [\n 'AdjustChannels',\n 'AlphaDrawing',\n 'AnimateCtrl',\n 'ArtProvider',\n 'BitmapFromBuffer',\n 'Cursor',\n 'DragImage',\n 'Image',\n 'ImageAlpha',\n 'ImageFromStream',\n 'Img2PyArtProvider',\n 'Mask',\n 'RawBitmapAccess',\n 'Throbber',\n ]),\n\n # Other stuff\n ('Miscellaneous', [\n 'AlphaDrawing',\n 'Cairo',\n 'Cairo_Snippets',\n 'ColourDB',\n ##'DialogUnits', # needs more explanations\n 'DragScroller',\n 'DrawXXXList',\n 'FileHistory',\n 'FontEnumerator',\n 'GraphicsContext',\n 'GLCanvas',\n 'I18N', \n 'Joystick',\n 'MimeTypesManager',\n 'MouseGestures',\n 'OGL',\n 'PrintFramework',\n 'PseudoDC',\n 'RendererNative',\n 'ShapedWindow',\n 'Sound',\n 'StandardPaths',\n 'Unicode',\n ]),\n\n\n ('Check out the samples dir too', [\n ]),\n\n]\n\n#---------------------------------------------------------------------------\n# Show how to derive a custom wxLog class\nfrom mylog import MyLog\n\n#PyTipProvider\nfrom mytp import MyTP\n\n#---------------------------------------------------------------------------\n# A class to be used to simply display a message in the demo pane\n# rather than running the sample itself.\nfrom messagepanel import MessagePanel\n \n\n#---------------------------------------------------------------------------\n# A class to be used to display source code in the demo. Try using the\n# wxSTC in the StyledTextCtrl_2 sample first, fall back to wxTextCtrl\n# if there is an error, such as the stc module not being present.\n#\n\nfrom democodeeditor import DemoCodeEditor\n\n#---------------------------------------------------------------------------\n# Constants for module versions\n\nfrom constants import *\n\n#---------------------------------------------------------------------------\n\n\nfrom democodepanel import DemoCodePanel\n\n#---------------------------------------------------------------------------\n\nfrom fun import *\n\n#---------------------------------------------------------------------------\n\nfrom demomodules import DemoModules\n\n#---------------------------------------------------------------------------\n\nfrom demoerror import DemoError\n\n#---------------------------------------------------------------------------\n\nfrom demoerrorpanel import DemoErrorPanel\n\n#---------------------------------------------------------------------------\n\nfrom demotaskbarticon import DemoTaskBarIcon\n\n#---------------------------------------------------------------------------\n\nfrom wxpythondemo import wxPythonDemo, wxPythonDemoTree\n\n\n#---------------------------\n\nfrom mysplashscreen import MySplashScreen\n\n#---------------------------------------------------------------------------\n\n############from wxpythondemotree import\n\n#---------------------------------------------------------------------------\n\n\n###############print dir().index('wxPythonDemoTree')\n\n\n\n#---------------------------------------------------------------------------\n\n\n\n","sub_path":"branches/copia ejemplo main/share.py","file_name":"share.py","file_ext":"py","file_size_in_byte":11757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"599375248","text":"from pytube import *\r\nfrom tkinter import *\r\nfrom tkinter.filedialog import *\r\nfrom tkinter.messagebox import *\r\nfrom threading import *\r\n\r\n# total size container:\r\nfile_size = 0\r\n\r\n\r\n# This function call the function every second\r\ndef progress(stream=None, chunk=None,bytes_remaining=None):\r\n try:\r\n filedownloded = (file_size - bytes_remaining)\r\n per = (filedownloded / file_size) * 100\r\n dBtn.config(text=\"{:00.0f}% Downloaded\".format(per))\r\n except EXCEPTION as e:\r\n print(e)\r\n print(\"cannot show %\")\r\n\r\n\r\n # gets the percentage of the file that is to be downloaded\r\n\r\n\r\ndef startDownload():\r\n global file_size\r\n # to create the object of youtube video\r\n try:\r\n url = urlfield.get()\r\n # print(url)\r\n # changing Btn text\r\n dBtn.config(text=\"Please wait....\")\r\n dBtn.config(state=DISABLED)\r\n path_to_save_video = askdirectory()\r\n # print(path_to_save-video)\r\n if path_to_save_video is None:\r\n return\r\n #, on_progress_callback=progress\r\n ob = YouTube(url, on_progress_callback=progress)\r\n stream = ob.streams.first()\r\n vTitle.config(text=stream.title)\r\n vTitle.pack(side=TOP)\r\n file_size = stream.filesize\r\n # print(file_size)\r\n stream.download(path_to_save_video)\r\n print(\"download done....\")\r\n dBtn.config(text=\"Start Download\")\r\n dBtn.config(state=NORMAL)\r\n showinfo(\"Download Finished\", \"Downloaded Video Succesfully\")\r\n urlfield.delete(0, END)\r\n vTitle.pack_forget()\r\n\r\n except EXCEPTION as e:\r\n print(e)\r\n print(\"Error Downloading video\")\r\n\r\n\r\n# Creating new Thread;\r\ndef startDownloadThread():\r\n thread = Thread(target=startDownload)\r\n thread.start()\r\n\r\n\r\n# Starting the Gui window\r\nmain = Tk()\r\n# Setting the title\r\nmain.title(\"My Youtube Downloader\")\r\n# Setting icon\r\nmain.iconbitmap('icon.ico')\r\nmain.geometry(\"500x600\")\r\n\r\n# heading icon:\r\nfile = PhotoImage(file='youtube.png')\r\nheadingIcon = Label(main, image=file)\r\nheadingIcon.pack(side=TOP)\r\n#text field for downloading\r\nEnterUrl = Label(main, text=\"Enter the Url of Video to Download\")\r\nEnterUrl.pack(side=TOP)\r\n# url txt field\r\nurlfield = Entry(main, font=(\"verdana\", 18), justify=CENTER)\r\nurlfield.pack(side=TOP, fill=X, padx=15)\r\n\r\ndBtn = Button(main, text=\"Start Download\", font=(\"verdana\", 18), relief=\"ridge\", command=startDownloadThread)\r\ndBtn.pack(side=TOP, pady=10)\r\n\r\n#video title;\r\nvTitle = Label(main,text=\"video Title\")\r\n# vTitle.pack(side=TOP)\r\n\r\nMade = Label(main, text=\"A free Software/Program to Download the YouTube Videos\\n\\n Made by Bablu\")\r\nMade.pack(side=BOTTOM)\r\nmain.mainloop()\r\n","sub_path":"Youtube-Video-Downloader/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"219736647","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, Http404, HttpResponseRedirect\nfrom django.core.paginator import Paginator, EmptyPage\nfrom django.contrib.auth import authenticate, login\n\nfrom .models import Question, Answer\nfrom .forms import *\n\ndef test(request, *args, **kwargs):\n return HttpResponse('OK')\n\ndef new(request):\n try:\n page = int(request.GET.get('page', 1))\n except:\n page = 1\n limit = 10\n\n questions = Question.objects.new()\n paginator = Paginator(questions, limit)\n\n try:\n page = paginator.page(page)\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n page = paginator.page(paginator.num_pages)\n\n return render(request, \"posts/index.html\", {\n 'page': page\n })\n\ndef popular(request):\n try:\n page = int(request.GET.get('page', 1))\n except:\n page = 1\n limit = 10\n\n questions = Question.objects.popular()\n paginator = Paginator(questions, limit)\n\n try:\n page = paginator.page(page)\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n page = paginator.page(paginator.num_pages)\n\n return render(request, \"posts/index.html\", {\n 'page': page\n })\n\ndef question(request, id):\n try:\n questionId = int(id)\n except:\n raise Http404\n\n try:\n question = Question.objects.get(pk=questionId)\n except:\n raise Http404\n\n if request.method == \"POST\":\n form = AnswerForm(request.POST)\n form._user = request.user\n if form.is_valid():\n answer = form.save()\n url = question.get_url()\n return HttpResponseRedirect(url)\n else:\n form = AnswerForm()\n\n answers = Answer.objects.filter(question=question)\n\n return render(request, \"questions/index.html\", {\n 'question': question,\n 'answers': answers,\n 'form': form\n })\n\ndef ask(request):\n if request.method == \"POST\":\n form = AskForm(request.POST)\n form._user = request.user\n if form.is_valid():\n question = form.save()\n url = question.get_url()\n return HttpResponseRedirect(url)\n else:\n form = AskForm()\n return render(request, 'questions/ask.html', {\n 'form': form\n })\n\ndef signup(request):\n if request.method == \"POST\":\n form = SignupForm(request.POST)\n if form.is_valid():\n user = form.save()\n login(request, user)\n return HttpResponseRedirect(\"/\")\n else:\n form = SignupForm()\n return render(request, 'signup.html', {\n 'form': form\n })\n\ndef login(request):\n if request.method == \"POST\":\n form = LoginForm(request.POST)\n if form.is_valid():\n user = form.save()\n login(request, user)\n return HttpResponseRedirect(\"/\")\n else:\n form = LoginForm()\n return render(request, 'login.html', {\n 'form': form\n })\n","sub_path":"ask/qa/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"10793093","text":"# -*- coding: utf-8 -*-\n\"\"\"Example for RaspaBaseWorkChain.\"\"\"\n\nimport os\nimport sys\nimport click\n\nfrom aiida.common import NotExistent\nfrom aiida.engine import run_get_node\nfrom aiida.orm import CifData, Code, Dict, SinglefileData, Int\nfrom aiida_raspa.workchains import RaspaBaseWorkChain\n\n\ndef example_base_restart_timeout(raspa_code):\n \"\"\"Run base workchain for GCMC with restart after timeout.\"\"\"\n\n # pylint: disable=no-member\n\n print(\"Testing RaspaBaseWorkChain restart after timeout...\")\n print(\"This long simulation will require ca. 3 iterations (i.e., 2 restarts).\")\n\n parameters = Dict(\n dict={\n \"GeneralSettings\": {\n \"SimulationType\": \"MonteCarlo\",\n \"NumberOfInitializationCycles\": 5000, # many, to pass timeout\n \"NumberOfCycles\": 5000, # many, to pass timeout\n \"PrintEvery\": 1000,\n \"Forcefield\": \"GenericMOFs\",\n \"RemoveAtomNumberCodeFromLabel\": True,\n \"ChargeMethod\": \"None\",\n \"CutOff\": 12.0,\n # WriteBinaryRestartFileEvery not needed: if missing RaspaBaseWorkChain will assign a default of 1000\n },\n \"System\": {\n \"irmof_1\": {\n \"type\": \"Framework\",\n \"UnitCells\": \"1 1 1\",\n \"ExternalTemperature\": 300.0,\n \"ExternalPressure\": 1e5,\n }\n },\n \"Component\": {\n \"krypton\": {\n \"MoleculeDefinition\": \"TraPPE\",\n \"TranslationProbability\": 0.5,\n \"ReinsertionProbability\": 0.5,\n \"SwapProbability\": 1.0,\n \"BlockPocketsFileName\": {\n \"irmof_1\": \"irmof_1_krypton\",\n },\n },\n },\n })\n\n # framework\n pwd = os.path.dirname(os.path.realpath(__file__))\n structure = CifData(file=os.path.join(pwd, '..', 'files', 'IRMOF-1.cif'))\n structure_label = \"irmof_1\"\n\n block_pocket_node1 = SinglefileData(file=os.path.join(pwd, '..', 'files', 'IRMOF-1_test.block')).store()\n\n # Constructing builder\n builder = RaspaBaseWorkChain.get_builder()\n\n # Specifying the code\n builder.raspa.code = raspa_code\n\n # Specifying the framework\n builder.raspa.framework = {\n structure_label: structure,\n }\n\n # Specifying the input parameters\n builder.raspa.parameters = parameters\n\n # Specifying the block pockets\n builder.raspa.block_pocket = {\n \"irmof_1_krypton\": block_pocket_node1,\n }\n\n # Specifying the scheduler options\n builder.raspa.metadata.options = {\n \"resources\": {\n \"num_machines\": 1,\n \"num_mpiprocs_per_machine\": 1,\n },\n \"max_wallclock_seconds\": 1 * 30 * 60, # 30 min\n \"withmpi\": True, # A trick to put the kill below before raspa command.\n \"mpirun_extra_params\": [\"timeout\", \"5\"], # Kill the calculation after 5 seconds, to test restart.\n }\n\n # Specify RaspaBaseWorkChain options\n builder.max_iterations = Int(8) # number of maximum iterations: prevent for infinite restart (default: 5)\n\n _, node = run_get_node(builder)\n assert node.exit_status == 0\n\n\n@click.command('cli')\n@click.argument('codelabel')\ndef cli(codelabel):\n \"\"\"Click interface\"\"\"\n try:\n code = Code.get_from_string(codelabel)\n except NotExistent:\n print(\"The code '{}' does not exist\".format(codelabel))\n sys.exit(1)\n example_base_restart_timeout(code)\n\n\nif __name__ == '__main__':\n cli() # pylint: disable=no-value-for-parameter\n\n# EOF\n","sub_path":"examples/workchains/example_base_restart_timeout.py","file_name":"example_base_restart_timeout.py","file_ext":"py","file_size_in_byte":3667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"32070500","text":"import streamlit as st\nimport numpy as np\nimport pandas as pd\nfrom pages import utils\nimport os\n\ndef app():\n\t\n\tif 'main_data.csv' not in os.listdir('data'):\n\t\tst.markdown(\"Please upload data through `Upload Data` page!\")\n\telse:\n\t\tdf = pd.read_csv('data/main_data.csv')\n\t\tst.markdown(\"### A small demo to show redundant columns of a csv\")\n\n\t\tredCols = utils.getRedundentColumns\n\t\tcorr = df.corr(method='pearson')\n\t\ty_var = st.radio(\"Select the variable to be predicted (y)\", options=corr.columns)\n\t\tth = st.slider(\"Threshold\", min_value=0.05, max_value=0.95, value=0.25, step=0.01, format='%f')#, key=None, help=None)\n\t\t# st.write(df.col)\n\t\tredundantCols = utils.getRedundentColumns(corr, y_var, th)\n\t\tnewDF = utils.newDF(df, redundantCols)\n\t\t# st.write(\"Redundant Columns:\", redundantCols)\n\t\tst.write(\"Number of Columns Dropped: \",len(redundantCols))\n\t\tst.write(\"New Data: \\n\", newDF.head())\n\n\t","sub_path":"pages/redundant.py","file_name":"redundant.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"350620856","text":"from spitfire import ChemicalMechanismSpec, Flamelet\nimport numpy as np\nfrom test.utilities import save_chemistry_gold_standard\n\nm = ChemicalMechanismSpec('hydrogen', 'burke')\n\npressure = 101325.\n\nair = m.stream(stp_air=True)\nair.TP = 1400., pressure\n\nzstoich = 0.1\n\nfuel = m.mix_fuels_for_stoich_mixture_fraction(m.stream('X', 'H2:1'), m.stream('X', 'N2:1'), zstoich, air)\nfuel.TP = 300., pressure\n\nchi_max = 1.e3\n\nnpts_interior = 32\n\nft = Flamelet(mech_spec=m,\n pressure=pressure,\n oxy_stream=air,\n fuel_stream=fuel,\n max_dissipation_rate=chi_max,\n engine='griffon',\n grid_points=npts_interior + 2,\n grid_cluster_intensity=4.,\n initial_condition='unreacted')\n\nft.insitu_process_quantity(['temperature', 'mass fractions'])\nft.integrate_to_steady(write_log=False)\n\nt = ft.solution_times\nz = ft.mixfrac_grid[1:-1]\nT = ft.trajectory_data('temperature').ravel()\nY = np.ndarray((npts_interior * t.size, m.gas.n_species))\nfor idx, s in enumerate(m.gas.species_names):\n Y[:, idx] = ft.trajectory_data('mass fraction ' + s).ravel()\n\nsave_chemistry_gold_standard('temperature', T)\nsave_chemistry_gold_standard('mass_fractions', Y)\n","sub_path":"test/chemistry/gold_standards_test_flamelet_adiabatic_unsteady_solve/reset_gold.py","file_name":"reset_gold.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"71246811","text":"import os\r\n\r\nimport pygame\r\n\r\n\r\nclass DisplayLoop():\r\n \"\"\" Class that handles display for looping a set of images. \"\"\"\r\n\r\n def __init__(self, w, h):\r\n\r\n # Required properties\r\n self.images = []\r\n self.images_index = 0\r\n self.image = None\r\n self.rect = pygame.Rect(0, 0, w, h)\r\n self.timer = 0\r\n self.delay = 10\r\n\r\n def resize(self, w, h):\r\n \"\"\" Resizes the display \"\"\"\r\n\r\n self.images = [pygame.transform.scale(x, (w, h)) for x in self.images]\r\n self.image = pygame.transform.scale(self.image, (w, h))\r\n self.rect = pygame.Rect(0, 0, w, h)\r\n\r\n def load_images(self, path, name):\r\n \"\"\" Load a set of images \"\"\"\r\n\r\n self.images.clear()\r\n for i in range(0, 20):\r\n file = f'{path}/{name}.{i}.png'\r\n if os.path.isfile(file):\r\n image = pygame.image.load(file).convert_alpha()\r\n image = pygame.transform.scale(image, self.rect.size)\r\n self.images.append(image)\r\n else:\r\n break\r\n\r\n def update(self):\r\n \"\"\" Update current image to next image \"\"\"\r\n\r\n n = len(self.images)\r\n if n > 0:\r\n\r\n # Count timer\r\n self.timer += 1\r\n if self.timer > self.delay:\r\n\r\n # Reset timer\r\n self.timer = 0\r\n\r\n # Get the next image\r\n self.images_index = (self.images_index + 1) % n\r\n self.image = self.images[self.images_index]\r\n\r\n def blit(self, surface):\r\n \"\"\" Draw current image \"\"\"\r\n\r\n if self.image:\r\n surface.blit(self.image, self.rect)\r\n else:\r\n surface.fill((255, 255, 255, 0))\r\n","sub_path":"maplepy/display/displayloop.py","file_name":"displayloop.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"535713381","text":"import cv2\r\nimport mouse\r\nimport win32api\r\nimport win32gui\r\n\r\n\r\ndef get_win_pos():\r\n try:\r\n hwnd = win32gui.GetForegroundWindow()\r\n (left, top, right, bottom) = win32gui.GetWindowRect(hwnd)\r\n return left + 8, top\r\n except:\r\n return 0, 0\r\n\r\n\r\ndef write_coord(file_name, x, y, counter):\r\n data = f\"{x},{y}\\n\"\r\n if counter == 1:\r\n with open(file_name, \"w\") as f:\r\n f.write(data)\r\n elif counter == 2:\r\n with open(file_name, \"a\") as f:\r\n f.write(data)\r\n\r\ndef main():\r\n video_name = \"videos/2.mp4\"\r\n cap = cv2.VideoCapture(video_name) # video_name is the video being called\r\n cap.set(1, 1) # Where frame_no is the frame you want\r\n font = cv2.FONT_HERSHEY_SIMPLEX\r\n win_name = \"Setup\"\r\n color = (0, 255, 0)\r\n counter = 0\r\n while True:\r\n ret, frame = cap.read() # Read the frame\r\n cv2.imshow(win_name, frame)\r\n win_x, win_y = get_win_pos()\r\n x, y = win32api.GetCursorPos()\r\n real_x, real_y = x - win_x, y - win_y\r\n\r\n if mouse.is_pressed() and counter <= 2:\r\n counter += 1\r\n mouse.on_click(lambda: write_coord(\"config.txt\", real_x, real_y, counter))\r\n mouse.release()\r\n if counter == 2:\r\n cv2.putText(frame, \"Settings successfully saved\", (200, 200), font, 2, color, 2)\r\n cv2.putText(frame, f\"x:{x} y:{y}\", (20, 50), font, 1, color, 1)\r\n cv2.putText(frame, f\"wx:{win_x} wy:{win_y}\", (20, 100), font, 1, color, 1)\r\n cv2.putText(frame, f\"rx:{real_x} ry:{real_y}\", (20, 150), font, 1, color, 1)\r\n cv2.imshow(win_name, frame) # show frame on window\r\n\r\n key = cv2.waitKey(1) & 0xFF\r\n\r\n if key == ord('q'):\r\n break\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"156936091","text":"import boto3\nimport os\nfrom app_lib import *\n\ntable_name = os.environ.get('TABLE_NAME')\ntable = get_table(table_name)\ndynamodbexceptions = boto3.client('dynamodb').exceptions\ntokens_table_name = os.environ.get('TOKENS_TABLE_NAME')\ntokens_table = get_table(tokens_table_name)\n\ndef main(event, context):\n if not checkToken(tokens_table, event['headers']):\n log_event({\"result\": \"lambda called using revoked token\"})\n return send_error(401, 'The incoming token has been revoked')\n\n log_event(event)\n\n user = get_user(event)\n if get_role(user) != 'doctor':\n return send_error(403, 'you are not authorized to view this resource')\n\n params = event['pathParameters']\n _id = params['id']\n body = get_body(event)\n\n item = {\n 'id': _id,\n 'name': body['name'],\n 'email': body['email'],\n 'phone_number': body['phone_number'],\n 'age': body['age'],\n 'is_active': body.get('is_active', True)\n }\n\n try:\n table.put_item(Item=item, ConditionExpression='attribute_exists(id)')\n except dynamodbexceptions.ConditionalCheckFailedException:\n return send_error(400, f\"doctor with id {_id} does not exist\")\n\n return send_response(200, item)","sub_path":"doqutor-core-master/infra/lambda/api/doctors_update.py","file_name":"doctors_update.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"284257390","text":"\"\"\"\nAuthor: Самаркин А.И.\nDate: 26/10/19\nPurpose: test\n\"\"\"\n\n# стандартная секция импорта, будет использоваться всегда\n# модули числовых расчетов\nimport scipy as sc\nimport numpy as np\nimport pandas as pd\n# модуль библиотеки для вывода графиков в стиле Matlab\nimport matplotlib\n\nmatplotlib.use('Qt5Agg', force=True) # библиотека для вывода графиков на базе Qt5, нужен импорт модуля PyQt5\n# модуль печати плоских графиков\nimport matplotlib.pyplot as plt\n\nplt.style.use('bmh') # можно попробовать также 'ggplot' или 'classic'\n\n# обратите внимание\n# fig - собственно окно\n# ax - в терминологии Ecell - обл��сть построения диаграммы, оси координат графика\n# именно ax задает такие свойства, как заголовок, например\n# ДВА*ДВА - сетка подграфика на одной поверхности но по горизонтали\nfig, ax = plt.subplots(2,2) # поверхность для вывода графиков (в виде всплывающего окна)\n\n# создаем массив x\nx = np.linspace(0,100,10000)\n# рассчитываем y\ny = np.sin(x)*np.exp(-0.01*x)\n\n# график в первой ячейке\nax[0, 0].plot(x, y)\n# заголовок\nax[0, 0].set_title('Axis [0,0]')\nax[0, 1].plot(x, y, 'tab:orange')\nax[0, 1].set_title('Axis [0,1]')\nax[1, 0].plot(x, -y, 'tab:green')\nax[1, 0].set_title('Axis [1,0]')\nax[1, 1].plot(x, -y, 'tab:red')\nax[1, 1].set_title('Axis [1,1]')\n\n# заголовки по осям координат\nfor axs in ax.flat:\n axs.set(xlabel='x-label', ylabel='y-label')\n# чтобы убрать промежуточные подписи по осям\nfor axs in ax.flat:\n axs.label_outer()\n\n\n# Общий (супер) заголовок - он относится ко всему окну\nfig.suptitle('Общий заголовок')\n\n\nplt.show()\n\n\n","sub_path":"lin_reg5_5.py","file_name":"lin_reg5_5.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"75355765","text":"# -*- coding: utf-8 -*-\nfrom ralph.admin.views.extra import RalphDetailView\n\n\nclass DataCenterAssetSecurityInfo(\n RalphDetailView\n):\n\n icon = 'lock'\n label = 'Security Info'\n name = 'security_info'\n url_name = 'datacenter_asset_security_info'\n\n def get_context_data(self, **kwargs):\n context = super(DataCenterAssetSecurityInfo, self).get_context_data(\n **kwargs\n )\n context['data_classification'] = [\n {'label': 'Availability', 'value': 'A3'},\n {'label': 'Confidentiality', 'value': 'C2'},\n {'label': 'Integrity', 'value': 'I4'},\n ]\n context['logs'] = [\n '/var/log',\n ]\n context['critical_pathes'] = [\n {\n 'label': 'Critical Patch Update - April 2015',\n 'value': 'Rev 3, 28 April 2015',\n },\n {\n 'label': 'Critical Patch Update - January 2015',\n 'value': 'Rev 2, 10 March 2015',\n },\n {\n 'label': 'Critical Patch Update - October 2014',\n 'value': 'Rev 5, 21 November 2014',\n },\n {\n 'label': 'Critical Patch Update - July 2014',\n 'value': 'Rev 2, 24 July 2014',\n },\n\n ]\n return context\n","sub_path":"src/ralph/data_center/views/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"300609560","text":"tags = [\n 'a',\n 'abbr',\n 'acronym',\n 'address',\n 'applet',\n 'area',\n 'article',\n 'aside',\n 'audio',\n 'b',\n 'base',\n 'basefont',\n 'bdi',\n 'bdo',\n 'big',\n 'blockquote',\n 'body',\n 'br',\n 'button',\n 'canvas',\n 'caption',\n 'center',\n 'cite',\n 'code',\n 'col',\n 'colgroup',\n 'datalist',\n 'dd',\n 'del',\n 'details',\n 'dfn',\n 'dialog',\n 'dir',\n 'div',\n 'dl',\n 'dt',\n 'em',\n 'embed',\n 'fieldset',\n 'figcaption',\n 'figure',\n 'font',\n 'footer',\n 'form',\n 'frame',\n 'frameset',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'head',\n 'header',\n 'hr',\n 'html',\n 'i',\n 'iframe',\n 'img',\n 'input',\n 'ins',\n 'kbd',\n 'keygen',\n 'label',\n 'legend',\n 'li',\n 'link',\n 'main',\n 'map',\n 'mark',\n 'menu',\n 'menuitem',\n 'meta',\n 'meter',\n 'nav',\n 'noframes',\n 'noscript',\n 'object',\n 'ol',\n 'optgroup',\n 'option',\n 'output',\n 'p',\n 'param',\n 'pre',\n 'progress',\n 'q',\n 'rp',\n 'rt',\n 'ruby',\n 's',\n 'samp',\n 'script',\n 'section',\n 'select',\n 'small',\n 'source',\n 'span',\n 'strike',\n 'strong',\n 'style',\n 'sub',\n 'summary',\n 'sup',\n 'table',\n 'tbody',\n 'td',\n 'textarea',\n 'tfoot',\n 'th',\n 'thead',\n 'time',\n 'title',\n 'tr',\n 'track',\n 'tt',\n 'u',\n 'ul',\n 'var',\n 'video',\n 'wbr',\n]\n\nempty_tags = ['br', 'hr', 'meta', 'link', 'base', 'link', 'meta', 'hr', 'br', 'img', 'embed', 'param', 'area', 'col',\n 'input']\n\nkeywords = ['object', 'var']\n\n\ndef func_name(name):\n if name in keywords:\n name += '_'\n return name\n\n\nimport string\n\nfrom attributes import parse, global_attributes, global_events\n\n\nif __name__ == '__main__':\n from jinja2 import Template\n\n element_attrs = sorted(set(global_attributes + global_events))\n elements = []\n for i in tags:\n my_attrs = parse(i)\n all_attrs = sorted(set(element_attrs + my_attrs))\n row = (\n i, i.capitalize(), all_attrs,\n sorted(j for j in my_attrs if j not in element_attrs),\n i in empty_tags, func_name(i)\n )\n elements.append(row)\n cases = [(c, i == 0 and '0' or string.ascii_lowercase[i - 1]) for i, c in enumerate(string.ascii_lowercase)]\n element_kt = Template(open('khtml/element.kt').read()).render(\n element_attrs=element_attrs, elements=elements, cases=cases\n )\n elements_kt = Template(open('khtml/elements.kt').read()).render(element_attrs=element_attrs, elements=elements)\n open('../src/main/kotlin/com/khtml/element.kt', 'w').write(element_kt)\n open('../src/main/kotlin/com/khtml/elements.kt', 'w').write(elements_kt)\n","sub_path":"generator/khtml/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"470911917","text":"# -*- coding: utf-8 -*-\n# @project : just_to_eat\n# @file : 349_两个数组的交集.py\n# @time : 2019-10-19\n\n'''\n给定两个数组,编写一个函数来计算它们的交集。\n\n示例 1:\n\n输入: nums1 = [1,2,2,1], nums2 = [2,2]\n输出: [2]\n示例 2:\n\n输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]\n输出: [9,4]\n说明:\n\n输出结果中的每个元素一定是唯一的。\n我们可以不考虑输出结果的顺序。\n\n'''\n\nclass Solution:\n '''\n 个人解决方案\n '''\n def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:\n if not nums1 or not nums2: return []\n result = []\n dict_1 = {}\n for each in nums1:\n dict_1[each] = 1\n for item in nums2:\n if item in dict_1:\n result.append(item)\n return list(set(result))\n\n\nclass Solution1:\n '''\n 方法一:两个 set\n 幼稚的方法是根据第一个数组 nums1 迭代并检查每个值是否存在在 nums2 内。如果存在将值添加到输出。\n 这样的方法会导致 O(n \\times m)O(n×m) 的时间复杂性,其中 n 和 m 是数组的长度。\n\n 为了在线性时间内解决这个问题,我们使用集合 set,在 O(1)O(1) 时间复杂度实现操作。\n\n 其思想是将两个数组转换为集合 set,然后迭代较小的集合检查是否存在在较大集合中。平均情况下,这种方法的时间复杂度为 O(n+m)O(n+m)。\n\n [复杂度分析]\n\n 时间复杂度:O(m+n)O(m+n),其中 n 和 m 是数组的长度。O(n)O(n) 的时间用于转换 nums1 在集合中,O(m)O(m) 的时间用于转换 nums2 到集合中,并且平均情况下,集合的操作为 O(1)O(1)。\n 空间复杂度:O(m+n)O(m+n),最坏的情况是数组中的所有元素都不同。\n\n '''\n def set_intersection(self, set1, set2):\n return [x for x in set1 if x in set2]\n\n def intersection(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: List[int]\n \"\"\"\n set1 = set(nums1)\n set2 = set(nums2)\n\n if len(set1) < len(set2):\n return self.set_intersection(set1, set2)\n else:\n return self.set_intersection(set2, set1)\n\n\nclass Solution2:\n '''\n 方法二:内置函数\n 内置的函数在一般情况下的时间复杂度是 O(n+m)O(n+m) 且时间复杂度最坏的情况是 O(n \\times m)O(n×m) 。\n\n 在 Python 中提供了交集的操作,在 Java 提供了 retainAll() 函数.\n\n [复杂度分析]\n\n 时间复杂度:一般情况下是 O(m+n)O(m+n),最坏情况下是 O(m \\times n)O(m×n)。\n 空间复杂度:最坏的情况是 O(m+n)O(m+n),当数组中的元素全部不一样时。\n '''\n def intersection(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: List[int]\n \"\"\"\n set1 = set(nums1)\n set2 = set(nums2)\n return list(set2 & set1)\n","sub_path":"349_两个数组的交集.py","file_name":"349_两个数组的交集.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"194476882","text":"#!/usr/bin/env python3\n# SPDX-License-Identifier: Apache-2.0\n##\n# Copyright (C) 2021 Jihoon Lee \n#\n# @file transLayer_v2.py\n# @date 19 October 2021\n# @brief Rewrite parameters in the order consistent with nntrainer for the torch model\n# @author Jihoon lee \n\nimport torch\nfrom collections.abc import Iterable\nfrom zoneout import Zoneout\n\n__all__ = [\"params_translated\"]\n\n# type to parameter mapper containing (classes, function)\nhandler_book = []\n\n##\n# Decorater to register class mapping to a function.\n# This is to imitate function overloadding\ndef register_for_(classes):\n for already_registered_classes, _ in handler_book:\n if not isinstance(classes, Iterable):\n classes = (classes, )\n\n for cls_ in classes:\n if isinstance(cls_, already_registered_classes):\n raise ValueError(\"class is already registered %s\" % cls_.__name__)\n\n def wrapper(func):\n handler_book.append((classes, func))\n return func\n\n return wrapper\n\n\ndef default_translate_(model):\n yield from model.named_parameters(recurse=False)\n\n@register_for_(torch.nn.Linear)\ndef fc_translate(model):\n params = [(name, tensor.detach()) for name, tensor in model.named_parameters()]\n def transpose_(weight):\n return (weight[0], weight[1].transpose(1, 0))\n if len(params) == 2:\n new_params = [transpose_(params[0]), params[1]]\n else:\n new_params = [transpose_(params[0])]\n yield from new_params\n\n@register_for_(torch.nn.BatchNorm1d)\ndef bn1d_translate(model):\n gamma, beta = [(name, tensor.detach()) for name, tensor in model.named_parameters()]\n mu, var, _ = [(name, tensor.detach()) for name, tensor in model.named_buffers()]\n yield from [mu, var, gamma, beta]\n\n@register_for_(torch.nn.LayerNorm)\ndef layer_normalization_translate(model):\n gamma, beta = [(name, tensor.detach()) for name, tensor in model.named_parameters()]\n yield from [gamma, beta]\n\n@register_for_((Zoneout))\ndef zoneout_translate(model):\n params = [(name, tensor.detach()) for name, tensor in model.named_parameters()]\n hidden_state = (\"hidden_state\", torch.stack(model.hidden_state_zoneout_mask, dim=0))\n cell_state = (\"cell_state\", torch.stack(model.cell_state_zoneout_mask, dim=0))\n\n # [hidden, input] -> [input, hidden]\n def transpose_(weight):\n return (weight[0], weight[1].transpose(1, 0))\n\n new_params = [transpose_(params[0]), transpose_(params[1]), params[2], params[3], hidden_state, cell_state]\n yield from new_params\n\n@register_for_((torch.nn.LSTM))\ndef lstm_translate(model):\n params = [(name, tensor.detach()) for name, tensor in model.named_parameters()]\n # [hidden, input] -> [input, hidden]\n def transpose_(weight):\n return (weight[0], weight[1].transpose(1, 0))\n\n new_params = [transpose_(params[0]), transpose_(params[1]), params[2], params[3]]\n if model.bidirectional:\n reverse_params = [transpose_(params[4]), transpose_(params[5]), params[6], params[7]]\n new_params += reverse_params\n\n yield from new_params\n\n@register_for_((torch.nn.RNNCell, torch.nn.LSTMCell))\ndef rnn_lstm_translate(model):\n params = [(name, tensor.detach()) for name, tensor in model.named_parameters()]\n # [hidden, input] -> [input, hidden]\n def transpose_(weight):\n return (weight[0], weight[1].transpose(1, 0))\n\n new_params = [transpose_(params[0]), transpose_(params[1]), params[2], params[3]]\n yield from new_params\n\n@register_for_((torch.nn.GRUCell))\ndef gru_translate(model):\n params = [(name, tensor.detach()) for name, tensor in model.named_parameters()]\n\n # [hidden, input] -> [input, hidden]\n def transpose_(weight):\n return (weight[0], weight[1].transpose(1, 0))\n\n # resetgate, inputgate, newgate -> inputgate, resetgate, newgate\n def reorder_weights(params):\n reordered_weights = []\n for (name, weight) in params: # param = (\"name\", weight)\n weight = weight.hsplit(3)\n reordered_weights.append((name, torch.hstack((weight[1], weight[0], weight[2])))) # reorder\n return reordered_weights\n\n transposed_params = [transpose_(params[0]), transpose_(params[1]), params[2], params[3]]\n new_params = reorder_weights(transposed_params)\n\n yield from new_params\n\n@register_for_((torch.nn.MultiheadAttention))\ndef multi_head_attention_translate(model):\n def transpose_(weight):\n return (weight[0], weight[1].transpose(1, 0))\n\n params = [(name, tensor.detach()) for name, tensor in model.named_parameters()]\n\n getParamByName = lambda name: list(filter(lambda param: param[0] == name, params))[0]\n\n if model._qkv_same_embed_dim:\n in_proj_weight = getParamByName('in_proj_weight')\n w_q, w_k, w_v = in_proj_weight[1].chunk(3)\n q_proj_weight = ('q_proj_weight', w_q)\n k_proj_weight = ('k_proj_weight', w_k)\n v_proj_weight = ('v_proj_weight', w_v)\n else:\n q_proj_weight = getParamByName('q_proj_weight')\n k_proj_weight = getParamByName('k_proj_weight')\n v_proj_weight = getParamByName('v_proj_weight')\n\n if model.in_proj_bias is not None:\n in_proj_bias = getParamByName('in_proj_bias')\n w_q, w_k, w_v = in_proj_bias[1].chunk(3)\n q_proj_bias = ('q_proj_bias', w_q)\n k_proj_bias = ('k_proj_bias', w_k)\n v_proj_bias = ('v_proj_bias', w_v)\n\n out_proj_weight = getParamByName('out_proj.weight')\n\n if model.in_proj_bias is not None:\n out_proj_bias = getParamByName('out_proj.bias')\n\n if model.in_proj_bias is None:\n new_params = [transpose_(q_proj_weight), transpose_(k_proj_weight), transpose_(v_proj_weight), transpose_(out_proj_weight)]\n else:\n new_params = [transpose_(q_proj_weight), q_proj_bias, transpose_(k_proj_weight), k_proj_bias, transpose_(v_proj_weight), v_proj_bias, transpose_(out_proj_weight), out_proj_bias]\n\n yield from new_params\n\n@register_for_(torch.nn.TransformerEncoderLayer)\ndef transformer_encoder_translate(model):\n self_attn, linear1, dropout1, linear2, norm1, norm2, dropout2, dropout3 = [child for name, child in model.named_children()]\n modules = [self_attn, norm1, linear1, linear2, norm2]\n ret = []\n\n for module in modules:\n for registered_classes, fn in handler_book:\n if isinstance(module, registered_classes):\n module = fn(module)\n module = list((n, t) for n, t in module)\n ret += module\n break\n yield from ret\n\n@register_for_(torch.nn.TransformerDecoderLayer)\ndef transformer_decoder_translate(model):\n self_attn, multihead_attn, linear1, dropout1, linear2, norm1, norm2, norm3, dropout2, dropout3, dropout4 = [child for name, child in model.named_children()]\n modules = [self_attn, norm1, multihead_attn, norm2, linear1, linear2, norm3]\n ret = []\n\n for module in modules:\n for registered_classes, fn in handler_book:\n if isinstance(module, registered_classes):\n module = fn(module)\n module = list((n, t) for n, t in module)\n ret += module\n break\n yield from ret\n\ndef translate(model):\n for child in model.children():\n for registered_classes, fn in handler_book:\n if isinstance(child, registered_classes):\n yield from fn(child)\n break\n else: # default case\n yield from translate(child)\n yield from default_translate_(model)\n\nparams_translated = translate\n\n","sub_path":"test/input_gen/transLayer_v2.py","file_name":"transLayer_v2.py","file_ext":"py","file_size_in_byte":7556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"446366929","text":"import os\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport cv2\n\n\nclass DataHandler(object):\n\n def _load_data(im_fnames, add_channel_dim=True):\n im0 = cv2.imread(im_fnames[0], 0)\n im_batch = np.zeros((len(im_fnames),) + im0.shape)\n im_batch[0] = im0\n for i, fname in enumerate(im_fnames[1:], 1):\n im_batch[i] = cv2.imread(fname, 0)\n\n if add_channel_dim:\n return np.expand_dims(im_batch, axis=-1)\n\n return im_batch\n\n @staticmethod\n def load_images(_file, normalize=True):\n im_fnames = list(np.loadtxt(_file, dtype='str'))\n im_batch = DataHandler._load_data(im_fnames).astype(np.float32)\n\n if normalize:\n im_batch = im_batch / 255.\n\n return im_batch, im_fnames\n\n @staticmethod\n def load_labels(_file):\n lb_fnames = list(np.loadtxt(_file, dtype='str'))\n lb_batch = DataHandler._load_data(lb_fnames).astype(np.int32)\n\n cur_labels = np.unique(lb_batch)\n new_labels = range(np.unique(lb_batch).shape[0])\n if not np.array_equal(cur_labels, new_labels):\n for cur_l, new_l in zip(cur_labels, new_labels):\n lb_batch[lb_batch == cur_l] = new_l\n\n return lb_batch, lb_fnames\n\n @staticmethod\n def train_test_split(data_dir, out_dir,\n test_size=0.2, seed=1):\n data_fnames = [\n os.path.join(data_dir, f) for f in sorted(os.listdir(data_dir))]\n\n train_fnames, test_fnames = train_test_split(\n data_fnames, test_size, True, seed)\n\n np.savetxt(os.path.join(out_dir, 'train_fnames'),\n np.array(train_fnames), fmt='%s')\n np.savetxt(os.path.join(out_dir, 'test_fnames'),\n np.array(test_fnames), fmt='%s')\n\n @staticmethod\n def train_valid_test_split(data_dir, out_dir, valid_size=0.1,\n test_size=0.2, seed=1):\n data_fnames = [\n os.path.join(data_dir, f) for f in sorted(os.listdir(data_dir))]\n\n train_fnames, test_fnames = train_test_split(\n data_fnames, test_size, True, seed)\n train_fnames, valid_fnames = train_test_split(\n train_fnames, valid_size/(1 - test_size), False, seed + 1)\n\n np.savetxt(os.path.join(out_dir, 'train_fnames'),\n np.array(train_fnames), fmt='%s')\n np.savetxt(os.path.join(out_dir, 'valid_fnames'),\n np.array(valid_fnames), fmt='%s')\n np.savetxt(os.path.join(out_dir, 'test_fnames'),\n np.array(test_fnames), fmt='%s')\n","sub_path":"acregnet/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"198266384","text":"import string\nfrom collections import Counter\nfrom typing import List\n\nfrom letter_values import letter_to_value, value_to_letter, word_to_value\nfrom anagram_searcher import AnagramSearcher\nfrom Ciphers.substitution import Action, use_caesar\nfrom word_list import WordList\n\nwoordzoeker = \"\"\"\ntrompetneushoornnlpegbwlqaez kkjvaljjcgqcjsehlkoekoppqqkj epjzuigschijfnbpcqrkctjlipka eepqwkjcljcgqblaseehjeublhcg cschoolwimpelepjwitoorkatllh ctjsoehlpqqkjwalqeeojmllrpkj cehrgoudkejjcglettervijlqmsc\njsqrktaebpejblaabcdneejouolh cgceejtrompetlwlhjlkacsnepjv epglircdrjqrebaczwaardneusdb erwkzkzpsagscjnaaenrikrggcjj letqecojtzepvebjnrtcfemeerjb kjaoranjebuikbladeaphavlcdue jaepsrnclsvteparkpakafnlpgjl lpjeahertogsepdgrlrjgakhremp khkvepejocjnaeseojneeeqftjae\nibwrattensteencdkmpkdhbkveep jaeekmeegjcujzkoolweiaaejseq schurftnbbospsevdenjsmnpkeau\nqnbzpcuhroaglnrjilahzeaqpanl steensmaskerkogelepjmonniksc jienqpgllscajrngtqoceueanpjc eoaolrssesjfvbkkdolfijnpcboe rmaopitbfpfejavljbeermpkeeuq nbbrpecauorklangpootjzwatere vepllesncoqwlrlpmpnkhkveepae\ndriebladnkortduimlpggcjjletq\n\"\"\".strip().replace(' ', '\\n').upper()\n\nword_list = {word.upper() for word in WordList()}\n\n\ndef find_words(target_value: int, nr_letters: int, values_so_far=None):\n if values_so_far is None:\n values_so_far = []\n if len(values_so_far) == nr_letters - 1:\n last_value = target_value - sum(values_so_far)\n if last_value in value_to_letter:\n letters = [value_to_letter[value] for value in values_so_far + [last_value]]\n word = ''.join(letters)\n if word in word_list:\n print(word)\n else:\n for letter in string.ascii_uppercase:\n value = letter_to_value[letter]\n if sum(values_so_far) + value > target_value:\n break\n find_words(target_value, nr_letters, values_so_far + [value])\n\n\ndef find_words_for_value(target_value: int, nr_letters: int):\n words_10 = {word.upper() for word in word_list if len(word) == nr_letters}\n words_10 = {word for word in words_10 if all(letter in string.ascii_uppercase for letter in word)}\n for word in words_10:\n value = sum(letter_to_value[letter] for letter in word)\n if value == target_value:\n print(word)\n\n\ndef read_words() -> List[str]:\n with open('woordzoeker.txt') as f:\n words = sorted(f.read().split('\\n'))\n with open('woordzoeker.txt', 'w') as f:\n # Write the sorted list, to keep it sorted and uppercased at all times\n words = [word.upper() for word in words]\n f.write('\\n'.join(words))\n return words\n\n\ndef count_lengths():\n horizontal = [16, 10, 7, 5, 8, 8, 11, 3, 5, 3, 10, 4, 12, 4, 10, 9, 6, 10, 4, 5, 9, 8, 8]\n vertical = [7, 8, 14, 6, 11, 7, 5, 12, 11, 5, 7, 13, 9, 5, 8, 12, 6, 5, 4, 7, 10]\n total = horizontal + vertical\n print(len(horizontal), len(vertical), len(total))\n c = dict(Counter(total))\n c = {key: c[key] for key in range(3, 17) if key in c}\n print(c)\n\n\nweights = {\n 16: [169],\n 14: [210],\n 13: [176],\n 12: [144, 147, 143],\n 11: [113, 97, 78],\n 10: [138, 146, 51, 108, 139],\n 9: [114, 117, 119],\n 8: [109, 82, 77, 78, 71, 62],\n 7: [67, 104, 93, 62, 90],\n 6: [40, 64, 46],\n 5: [57, 38, 57, 37, 62, 71, 54],\n 4: [31, 41, 44, 36],\n 3: [35, 45]\n}\n\nlatin_names = {\n 'TROMPETNEUSHOORN': 'Bycanistes bucinator',\n 'ORANJEBUIKBLAD': 'Chloropsis hardwickii',\n 'PAUWOOGKEIZERS': 'Pygoplites diacanthus',\n 'SPITSNEUSGRAF': 'Taphozous troughtoni',\n 'SCHOOLWIMPEL': 'Heniochus diphreutes',\n 'WRATTENSTEEN': 'Synanceia horrida',\n 'ZANDKROKODIL': 'Thysanophrys arenicola',\n 'MASKERKOGEL': 'Arothron diadematus',\n 'PALAWANBLAD': 'Chloropsis palawanensis',\n 'BORSTELTONG': 'Platalina genovensium',\n 'ZUIGSCHIJF': 'Myzopoda aurita',\n 'LETTERVIJL': 'Aluterus scriptus',\n 'ZWAARDNEUS': 'Lonchorhina aurita',\n 'RIFHAGEDIS': 'Synodus variegatus',\n 'BALLONEGEL': 'Diodon holocanthus',\n 'WITOORKAT': 'Ailuroedus buccoides',\n 'REUZENOOR': 'Megaderma spasma',\n 'SNORBAARD': 'Pteronotus personatus',\n 'DRIEBLAD': 'Triaenops persicus',\n 'LANGPOOT': 'Macrophyllum macrophyllum',\n 'KORTDUIM': 'Furipterus horrens',\n 'HALSBAND': 'Cheiromeles parvidens',\n 'LANTAARN': 'Lampanyctodes hectoris',\n 'NAPOLEON': 'Cheilinus undulatus',\n 'EEKHOORN': 'Holocentrus ruber',\n 'TROMPET': 'Aulostomus maculatus',\n 'HERTOGS': 'Holacanthus tricolor',\n 'MONNIKS': 'Chromis chromis',\n 'SCHURFT': 'Arnoglossus laterna',\n 'DOLFIJN': 'Coryphaena hippurus',\n 'BANANEN': 'Musonycteris harrisoni',\n 'PINCET': 'Chelmon Rostratus',\n 'KOEKOP': 'Naso lituratus',\n 'PRIEEL': 'Uroderma bilobatum',\n 'STEEN': 'Synanceia verrucosa',\n 'WATER': 'Myotis daubentonii',\n 'BOTER': 'Pholis gunnellus',\n 'OMBER': 'Argyrosomus regius',\n 'ZONNE': 'Zeus faber',\n 'ANSJO': 'Engraulis encrasicolus',\n 'SPOOK': 'Diclidurus albus',\n 'GOUD': 'Carassius auratus',\n 'KOOL': 'Pollachius virens',\n 'PEST': 'Bombycilla garrulus',\n 'MEER': 'Myotis dasycneme',\n 'MOPS': 'Barbastella barbastellus',\n 'BOS': 'Nyctalus leisleri',\n 'BOK': 'Boops boops',\n 'IJS': 'Alcedo atthis',\n}\n\n\ndef analyze_weights():\n sum_letters = 0\n sum_weights = 0\n for key, value in weights.items():\n nr_words = len(value)\n sum_letters += nr_words * key\n sum_weights += sum(value)\n print(sum_weights, sum_letters, sum_weights / sum_letters)\n print('----')\n\n\ndef find_anagrams():\n words = ['OEDIG', 'FEYTI', 'OEDIGFEYTI']\n a = AnagramSearcher()\n for word in words:\n anagrams = a.find_anagrams_for(word)\n print(word, anagrams)\n print('----')\n\n\ndef check_substitution():\n for dutch, latin in latin_names.items():\n encrypted = use_caesar(msg=dutch, key=latin, action=Action.ENCRYPT)\n weight = word_to_value(encrypted)\n word_length = len(dutch)\n weight_is_correct = weight in weights[word_length]\n if not weight_is_correct:\n print(dutch, encrypted, weight)\n\n\nif __name__ == '__main__':\n # find_words_for_value(51, 10)\n # find_words(45)\n # find_values()\n # analyze_weights()\n # find_anagrams()\n check_substitution()\n","sub_path":"src/AIVD2020/woordzoeker.py","file_name":"woordzoeker.py","file_ext":"py","file_size_in_byte":6262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"641961559","text":"# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"A base class for nodes that run a single subprocess.\"\"\"\n\nimport abc\nimport shlex\nimport subprocess\nimport time\n\nclass NodeBase(object):\n @abc.abstractmethod\n def __init__(self):\n self._process = None\n\n @abc.abstractmethod\n def start(self):\n \"\"\"Start the subprocess.\n\n Should be overridden by the subclass to construct a command line, call\n self._create_process, and assign the result to self._process.\n \"\"\"\n pass\n\n def _create_process(self, args):\n \"\"\"A central point to create subprocesses, so that we can debug the\n command-line arguments.\n\n Args:\n args: An array of strings, the command line of the subprocess.\n Returns:\n The Popen object of the subprocess.\n \"\"\"\n # Print arguments formatted as output from bash -x would be.\n # This makes it easy to see the arguments and easy to copy/paste them for\n # debugging in a shell.\n print('+ ' + ' '.join([shlex.quote(arg) for arg in args]))\n return subprocess.Popen(args, stdin = subprocess.DEVNULL)\n\n def is_running(self):\n \"\"\"Returns True if the subprocess is still running, and False otherwise.\"\"\"\n if not self._process:\n return False\n\n self._process.poll()\n if self._process.returncode is not None:\n return False\n\n return True\n\n def stop(self):\n \"\"\"Stop the subprocess if it's still running.\"\"\"\n if self._process:\n # Slightly more polite than kill. Try this first.\n\n self._process.terminate()\n\n if self.is_running():\n # If it's not dead yet, wait 1 second.\n time.sleep(1)\n\n if self.is_running():\n # If it's still not dead, use kill.\n self._process.kill()\n # Don't wait to see the results. If this didn't work, nothing will.\n","sub_path":"streamer/node_base.py","file_name":"node_base.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"462468804","text":"#!/usr/bin/python\n\n#******************************\n#Get stuff going.\n#******************************\n\nimport os\nfrom subprocess import *\nfrom Tkinter import *\nfrom tkMessageBox import *\nimport time\n\nmyFractal = Tk()\nmyFractal.title(\"My Turn\")\t\nmyFractal.attributes(\"-fullscreen\", True)\n\nlength = myFractal.winfo_screenwidth()\t\t\t\t\t#Dimensions of screen.\nheight = myFractal.winfo_screenheight()\ncanDelete = True\ncheckYesNo = IntVar()\n\n#Some function definitions.\n\ndef acceptInfo():\n emailInfo = open('studentemail.txt', 'w')\n emailInfo.write(\"None\\n\")\n emailInfo.write(str(sl.get()))\n emailInfo.close()\n myFractal.quit()\n \n\n#This window has a slider and presents student with options for number of steps they want each pi to take.\n\nsomeText = open('justforfun.txt', 'r')\t\t\t\t\t\t\t#Info. text\ninfo = someText.read()\nsomeText.close()\nlb = Label(myFractal, text=info, justify=CENTER, font=\"Verdana 20\")\nlb.pack(pady=((height/8), 0))\n\nsl = Scale(myFractal, from_=1, to=1500, orient=HORIZONTAL, length=(length - 10))\t#Scroll bar.\nsl.pack(padx=(50, 50), pady=((height/6), 50))\n\nbt = Button(myFractal, text=\"Make Fractal\", command=acceptInfo, font=\"Verdana 20\")\nbt.pack(side=BOTTOM, pady=(0, 50))\n\nmyFractal.mainloop()\t\t\t\t\t\t#Start the demo. :)\n\nos.system(\"python ./fractaldemo5.py\")\n","sub_path":"fractals/fractaldemo4.py","file_name":"fractaldemo4.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"109052357","text":"import wradlib as wrl\nimport matplotlib.pyplot as pl\nimport numpy as np\nimport matplotlib as mpl\nimport os\nfrom osgeo import osr\n\ndef get_radar_locations():\n\n radars = {}\n radar = {}\n radar['name'] = 'ASR Dresden'\n radar['wmo'] = 10487\n radar['lon'] = 13.76347\n radar['lat'] = 51.12404\n radar['alt'] = 261\n radars['ASD'] = radar\n\n radar = {}\n radar['name'] = 'Boostedt'\n radar['wmo'] = 10132\n radar['lon'] = 10.04687\n radar['lat'] = 54.00438\n radar['alt'] = 124.56\n radars['BOO'] = radar\n\n radar = {}\n radar['name'] = 'Dresden'\n radar['wmo'] = 10488\n radar['lon'] = 13.76865\n radar['lat'] = 51.12465\n radar['alt'] = 263.36\n radars['DRS'] = radar\n\n radar = {}\n radar['name'] = 'Eisberg'\n radar['wmo'] = 10780\n radar['lon'] = 12.40278\n radar['lat'] = 49.54066\n radar['alt'] = 798.79\n radars['EIS'] = radar\n\n radar = {}\n radar['name'] = 'Emden'\n radar['wmo'] = 10204\n radar['lon'] = 7.02377\n radar['lat'] = 53.33872\n radar['alt'] = 58\n radars['EMD'] = radar\n\n radar = {}\n radar['name'] = 'Essen'\n radar['wmo'] = 10410\n radar['lon'] = 6.96712\n radar['lat'] = 51.40563\n radar['alt'] = 185.10\n radars['ESS'] = radar\n\n radar = {}\n radar['name'] = 'Feldberg'\n radar['wmo'] = 10908\n radar['lon'] = 8.00361\n radar['lat'] = 47.87361\n radar['alt'] = 1516.10\n radars['FBG'] = radar\n\n radar = {}\n radar['name'] = 'Flechtdorf'\n radar['wmo'] = 10440\n radar['lon'] = 8.802\n radar['lat'] = 51.3112\n radar['alt'] = 627.88\n radars['FLD'] = radar\n\n radar = {}\n radar['name'] = 'Hannover'\n radar['wmo'] = 10339\n radar['lon'] = 9.69452\n radar['lat'] = 52.46008\n radar['alt'] = 97.66\n radars['HNR'] = radar\n\n radar = {}\n radar['name'] = 'Neuhaus'\n radar['wmo'] = 10557\n radar['lon'] = 11.13504\n radar['lat'] = 50.50012\n radar['alt'] = 878.04\n radars['NEU'] = radar\n\n radar = {}\n radar['name'] = 'Neuheilenbach'\n radar['wmo'] = 10605\n radar['lon'] = 6.54853\n radar['lat'] = 50.10965\n radar['alt'] = 585.84\n radars['NHB'] = radar\n\n radar = {}\n radar['name'] = 'Offenthal'\n radar['wmo'] = 10629\n radar['lon'] = 8.71293\n radar['lat'] = 49.9847\n radar['alt'] = 245.80\n radars['OFT'] = radar\n\n radar = {}\n radar['name'] = 'Proetzel'\n radar['wmo'] = 10392\n radar['lon'] = 13.85821\n radar['lat'] = 52.64867\n radar['alt'] = 193.92\n radars['PRO'] = radar\n\n radar = {}\n radar['name'] = 'Memmingen'\n radar['wmo'] = 10950\n radar['lon'] = 10.21924\n radar['lat'] = 48.04214\n radar['alt'] = 724.40\n radars['MEM'] = radar\n\n radar = {}\n radar['name'] = 'Rostock'\n radar['wmo'] = 10169\n radar['lon'] = 12.05808\n radar['lat'] = 54.17566\n radar['alt'] = 37\n radars['ROS'] = radar\n\n radar = {}\n radar['name'] = 'Isen'\n radar['wmo'] = 10873\n radar['lon'] = 12.10177\n radar['lat'] = 48.1747\n radar['alt'] = 677.77\n radars['ISN'] = radar\n\n radar = {}\n radar['name'] = 'Tuerkheim'\n radar['wmo'] = 10832\n radar['lon'] = 9.78278\n radar['lat'] = 48.58528\n radar['alt'] = 767.62\n radars['TUR'] = radar\n\n radar = {}\n radar['name'] = 'Ummendorf'\n radar['wmo'] = 10356\n radar['lon'] = 11.17609\n radar['lat'] = 52.16009\n radar['alt'] = 183\n radars['UMM'] = radar\n\n return radars\n\ndef ex_radolan_radarloc():\n\n # load radolan file\n rw_filename = '../../examples/data/radolan/raa01-rw_10000-1408102050-dwd---bin.gz'\n rwdata, rwattrs = wrl.io.read_RADOLAN_composite(rw_filename)\n\n # print the available attributes\n print(\"RW Attributes:\", rwattrs)\n\n # mask data\n sec = rwattrs['secondary']\n rwdata.flat[sec] = -9999\n rwdata = np.ma.masked_equal(rwdata, -9999)\n\n # create radolan projection object\n dwd_string = wrl.georef.create_projstr(\"dwd-radolan\")\n proj_stereo = wrl.georef.proj4_to_osr(dwd_string)\n\n # create wgs84 projection object\n proj_wgs = osr.SpatialReference()\n proj_wgs.ImportFromEPSG(4326)\n\n # get radolan grid\n radolan_grid_xy = wrl.georef.get_radolan_grid(900,900)\n x1 = radolan_grid_xy[:,:,0]\n y1 = radolan_grid_xy[:,:,1]\n\n # convert to lonlat\n radolan_grid_ll = wrl.georef.reproject(radolan_grid_xy, projection_source=proj_stereo, projection_target=proj_wgs)\n lon1 = radolan_grid_ll[:,:,0]\n lat1 = radolan_grid_ll[:,:,1]\n\n # plot two projections side by side\n fig1 = pl.figure()\n ax1 = fig1.add_subplot(111, aspect='equal')\n pm = ax1.pcolormesh(lon1, lat1, rwdata, cmap='spectral')\n cb = fig1.colorbar(pm, shrink=0.75)\n cb.set_label(\"mm/h\")\n pl.xlabel(\"Longitude \")\n pl.ylabel(\"Latitude\")\n pl.title('RADOLAN RW Product \\n' + rwattrs['datetime'].isoformat() + '\\n WGS84')\n pl.xlim((lon1[0,0],lon1[-1,-1]))\n pl.ylim((lat1[0,0],lat1[-1,-1]))\n pl.grid(color='r')\n\n fig2 = pl.figure()\n ax2 = fig2.add_subplot(111, aspect='equal')\n pm = ax2.pcolormesh(x1, y1, rwdata, cmap='spectral')\n cb = fig2.colorbar(pm, shrink=0.75)\n cb.set_label(\"mm/h\")\n pl.xlabel(\"x [km]\")\n pl.ylabel(\"y [km]\")\n pl.title('RADOLAN RW Product \\n' + rwattrs['datetime'].isoformat() + '\\n Polar Stereographic Projection')\n pl.xlim((x1[0,0],x1[-1,-1]))\n pl.ylim((y1[0,0],y1[-1,-1]))\n pl.grid(color='r')\n\n # range array 150 km\n print(\"Max Range: \", rwattrs['maxrange'])\n r = np.arange(1, 151)*1000\n # azimuth array 1 degree spacing\n az = np.linspace(0,360,361)[0:-1]\n\n # get radar dict\n radars = get_radar_locations()\n\n # iterate over all radars in rwattrs\n # plot range rings and radar location for the two projections\n for id in rwattrs['radarlocations']:\n\n # get radar coords etc from dict\n # repair Ummendorf ID\n if id == 'umd':\n id = 'umm'\n radar = radars[id.upper()]\n\n # build polygons for maxrange rangering\n polygons = wrl.georef.polar2polyvert(r, az, (radar['lon'], radar['lat']))\n polygons.shape = (len(az), len(r), 5, 2)\n polygons_ll = polygons[:,-1,:,:]\n\n # reproject to radolan polar stereographic projection\n polygons_xy = wrl.georef.reproject(polygons_ll, projection_source=proj_wgs, projection_target=proj_stereo)\n\n # create PolyCollections and add to respective axes\n polycoll = mpl.collections.PolyCollection(polygons_ll, closed=True, edgecolors='r', facecolors='r')\n ax1.add_collection(polycoll, autolim=True)\n polycoll = mpl.collections.PolyCollection(polygons_xy, closed=True, edgecolors='r', facecolors='r')\n ax2.add_collection(polycoll, autolim=True)\n\n # plot radar location and information text\n ax1.plot(radar['lon'], radar['lat'], 'r+')\n ax1.text(radar['lon'], radar['lat'], id, color='r')\n\n # reproject lonlat radar location coordinates to polar stereographic projection\n x_loc, y_loc = wrl.georef.reproject(radar['lon'], radar['lat'], projection_source=proj_wgs, projection_target=proj_stereo)\n # plot radar location and information text\n ax2.plot(x_loc, y_loc, 'r+')\n ax2.text(x_loc, y_loc, id, color='r')\n\n pl.tight_layout()\n pl.show()\n\n# =======================================================\nif __name__ == '__main__':\n ex_radolan_radarloc()","sub_path":"0.6.0/tutorial_radolan_format-2.py","file_name":"tutorial_radolan_format-2.py","file_ext":"py","file_size_in_byte":7326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"301967593","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport copy\n\n#allModels = ['alexNet', 'densenet_201', 'resnet18', 'vgg19', 'vgg19_bn']\nallModels = ['ensembleTrain','ensembleTest','ensembleTrainSET4','ensembleTestSET4']\nfor model in allModels:\n\tconfusionMatrix = np.loadtxt(model+'.confuse')\n\tcolSumsTotals = [0,0,0]\n\tHeatMatrix = copy.deepcopy(confusionMatrix)\n\tfor i in range(0,3):\n\t\tfor j in range(0,3):\n\t\t\tcolSumsTotals[j] += confusionMatrix[i,j]\n\tfor i in range(0,3):\n\t\tfor j in range(0,3):\n\t\t\tHeatMatrix[i,j] = confusionMatrix[i,j]/colSumsTotals[j] \n#\t\ta = 0\n#\t\ttmp_arr = []\n#\t\ta = sum(i, 1)\n#\t\tfor j in i:\n#\t\t\ttmp_arr.append(float(j)/float(a))\n#\t\tnorm_conf.append(tmp_arr)\n\n\tfig = plt.figure()\n\tplt.clf()\n\tax = fig.add_subplot(111)\n\tax.set_aspect(1)\n\tres = ax.imshow(HeatMatrix, cmap=plt.cm.Reds, \n\t\t\tinterpolation='nearest')\n\n\twidth, height = confusionMatrix.shape\n\n\tfor x in range(width):\n\t\tfor y in range(height):\n\t\t\tax.annotate(str(confusionMatrix[x][y]), xy=(y, x), \n\t\t\t\t horizontalalignment='center',\n\t\t\t\t verticalalignment='center')\n\n\tcb = fig.colorbar(res)\n\tplt.xlabel(\"Ground Truth\")\n\tplt.ylabel(\"Prediction\")\n\tplt.title(model+\" Confusion Matrix Validation\")\n\tplt.xticks(range(width), ['land', 'both', 'water'])\n\tplt.yticks(range(height),['land', 'both', 'water'] )\n\tplt.savefig(model+'_confusion_matrix.png', format='png')\n\tplt.show()\n","sub_path":"ConfusionMatrices/cfMat.py","file_name":"cfMat.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"441887310","text":"#类的方法\n#在类的内部,使用 def 关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self, 且为第一个参数,self 代表的是类的实例。\n#实例(Python 3.0+)\n#!/usr/bin/python3\n\n#类定义\nclass people:\n #定义基本属性\n name = ''\n age = 0\n #定义私有属性,私有属性在类外部无法直接进行访问\n __weight = 0\n #定义构造方法\n def __init__(self,name,age,weight):\n self.name = name\n self.age = age\n self.__weight = weight\n def speak(self):\n print(\"%s 说: 我 %d 岁。\" %(self.name,self.age))\n\n# 实例化类\np = people('runoob',10,30)\np.speak()\n","sub_path":"Python/程序设计基础篇/Python语言CAP/【第6周 第1部分】Python编程之计算生态/Python3 面向对象/2 类的方法 2.py","file_name":"2 类的方法 2.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"559257053","text":"from flask import Flask, request\n\n# pip install python-telegram-bot\n# pip install telegram\nimport telegram\nfrom credentials import bot_token, URL\n\nTOKEN = bot_token\nbot = telegram.Bot(token=TOKEN)\n\napp = Flask(__name__)\n\n# 텔레그램 봇과 url 연동 \n@app.route('/setwebhook', methods=['GET', 'POST'])\ndef set_webhook():\n s = bot.setWebhook(f'{URL}/{TOKEN}')\n if s:\n return \"webhook setup ok\"\n else:\n return \"webhook setup failed\"\n\n# 실제로 텔레그램에서 request를 보내는 URL\n# 텔레그램의 경우 / 으로 http request 전송\n@app.route(f'/{TOKEN}', methods=['POST'])\ndef autoResponse():\n\t# request를 json 형식으로 파싱\n resp = request.get_json(force=True)\n\n if 'message' in resp.keys():\n msgtext = resp[\"message\"][\"text\"]\n sendername = resp[\"message\"][\"from\"][\"first_name\"]\n chat_id = resp[\"message\"][\"chat\"][\"id\"]\n elif 'channel_post' in resp.keys():\n msgtext = resp[\"channel_post\"][\"text\"]\n sendername = resp[\"channel_post\"][\"chat\"][\"username\"]\n chat_id = resp[\"channel_post\"][\"chat\"][\"id\"]\n try:\n \t# 유저가 보낸 메시지에 대한 답장으로 유저 메시지 반복하기\n \tbot.sendMessage(chat_id=chat_id, text=msgtext)\n except Exception:\n \t# 에러가 발생했을 때\n \tbot.sendMessage(chat_id=chat_id, text=\"문제가 발생하였습니다 :(\")\n\n return \"ok\"\n\nif __name__ == '__main__':\n\tapp.run(debug=True)\n","sub_path":"Slack_Telegram/telegram/telegramBot.py","file_name":"telegramBot.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"382655845","text":"import os\n\nfrom jsonschema import validate\n\nfrom tinkoff_voicekit_client.TTS.configurator_codec import configuration\nfrom tinkoff_voicekit_client.TTS.helper_tts import get_utterance_generator, get_config, get_encoder, save_synthesize_wav\nfrom tinkoff_voicekit_client.speech_utils.BaseClient.base_client import BaseClient\nfrom tinkoff_voicekit_client.speech_utils.apis.tts_pb2 import SynthesizeSpeechRequest\nfrom tinkoff_voicekit_client.speech_utils.apis.tts_pb2_grpc import TextToSpeechStub\nfrom tinkoff_voicekit_client.speech_utils.config_data import client_config\nfrom tinkoff_voicekit_client.speech_utils.metadata import Metadata\n\n\nclass ClientTTS(BaseClient):\n definitions = {\n \"AudioEncoding\": {\n \"type\": \"string\",\n \"enum\": [\"LINEAR16\", \"RAW_OPUS\"]\n },\n \"SynthesisInput\": {\n \"type\": \"object\",\n \"properties\": {\n \"text\": {\"type\": \"string\"}\n }\n }\n }\n\n streaming_synthesize_config_schema = {\n \"type\": \"object\",\n \"definitions\": definitions,\n \"properties\": {\n \"audio_encoding\": {\"$ref\": \"#/definitions/AudioEncoding\"},\n \"speaking_rate\": {\"type\": \"number\"},\n \"sample_rate_hertz\": {\"type\": \"number\"}\n },\n \"required\": [\n \"sample_rate_hertz\",\n \"audio_encoding\",\n ],\n \"additionalProperties\": False\n }\n\n def __init__(\n self,\n api_key: str,\n secret_key: str,\n host: str = client_config[\"host_tts\"],\n port: int = client_config[\"port\"],\n ca_file: str = None\n ):\n \"\"\"\n Create client for speech synthesis.\n :param api_key: client public api key\n :param secret_key: client secret api key\n :param host: Tinkoff Voicekit speech synthesize host url\n :param port: Tinkoff Voicekit speech synthesize port, default value: 443\n :param ca_file: optional certificate file\n \"\"\"\n super().__init__()\n configuration()\n self._metadata = Metadata(api_key, secret_key, aud=\"TTS\")\n self._channel = self._make_channel(host, port, ca_file)\n self._stub = TextToSpeechStub(self._channel)\n\n def streaming_synthesize(\n self,\n text_source: str,\n config: dict,\n text_encoding: str = \"utf-8\",\n ssml: bool = False\n ):\n \"\"\"\n Description:\n return generator by StreamingSynthesizeSpeechResponses from each text line in file or text string.\n :param text_source: path to file with text or string with text\n :param config: dict conforming to streaming_synthesize_config_schema\n :param text_encoding: text encoding\n :param ssml: enable ssml text source\n \"\"\"\n validate(config, ClientTTS.streaming_synthesize_config_schema)\n\n generate_utterances = get_utterance_generator(text_source)\n\n request = SynthesizeSpeechRequest()\n request.audio_config.CopyFrom(get_config(config))\n\n for text in generate_utterances(text_source, text_encoding):\n if not self._metadata.is_fresh_jwt():\n self._metadata.refresh_jwt()\n\n if ssml:\n request.input.ssml = text\n else:\n request.input.text = text\n yield self._stub.StreamingSynthesize(request, metadata=self._metadata.metadata)\n\n def synthesize_to_audio_wav(\n self,\n text_source: str,\n config: dict,\n output_dir: str = os.curdir,\n text_encoding: str = \"utf-8\",\n ssml: bool = False\n ):\n \"\"\"\n Description:\n Generate audio for each text line from your text source and save it in wav format.\n :param text_source: path to file with text or string with text\n :param config: dict conforming to streaming_synthesize_config_schema\n :param output_dir: path to output directory where to store synthesized audio\n :param text_encoding: text encoding\n :param ssml: enable ssml text source\n \"\"\"\n rows_responses = self.streaming_synthesize(text_source, config, text_encoding, ssml)\n os.makedirs(output_dir, exist_ok=True)\n\n for index, row_response in enumerate(rows_responses):\n audio_chunks = []\n get_chunk = get_encoder(config[\"audio_encoding\"], config[\"sample_rate_hertz\"])\n for response in row_response:\n audio_chunks += get_chunk(response.audio_chunk)\n\n save_synthesize_wav(bytes(audio_chunks),\n os.path.join(output_dir, f\"{index}.wav\"),\n config[\"sample_rate_hertz\"])\n","sub_path":"tinkoff_voicekit_client/TTS/client_tts.py","file_name":"client_tts.py","file_ext":"py","file_size_in_byte":4790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"611551255","text":"#coding:utf-8\nfrom __future__ import absolute_import,print_function,division\n\nimport tensorflow as tf\n\ndef clip_boxes_to_img_boundaries(decode_boxes,img_shape):\n \"\"\"\n\n :param decode_boxes:\n :param img_shape:\n :return: decode boxes,and already clip to boundaries\n \"\"\"\n\n with tf.name_scope('clip_boxes_to_img_boundaries'):\n ymin,xmin,ymax,xmax = tf.unstack(decode_boxes,axis=1)\n img_h,img_w = img_shape[1],img_shape[2]\n xmin = tf.maximum(xmin,0.0)\n xmin = tf.minimum(xmin,tf.cast(img_w,tf.float32))\n\n ymin = tf.maximum(ymin,0.0)\n ymim = tf.minimum(ymin,tf.cast(img_h,tf.float32)) #avoid xmin > img_w,ymin > img_h\n\n xmax = tf.minimum(xmax,tf.cast(img_w,tf.float32))\n ymax = tf.minimum(ymax,tf.cast(img_h,tf.float32))\n\n return tf.transpose(tf.stack([ymin,xmin,ymax,xmax]))\n\n\ndef filter_outside_boxes(boxes,img_w,img_h):\n \"\"\"\n\n :param boxes: boxes with format [xmin,ymin,xmax,ymax]\n :param img_w: weight of img\n :param img_h: height of img\n :return: indices of anchors that not outside the image boundary\n \"\"\"\n\n with tf.name_scope(\"filter_outside_boxes\"):\n\n ymin,xmin,ymax,xmax = tf.unstack(boxes,axis=1)\n xmin_index = tf.greater_equal(xmin,0)\n ymin_index = tf.greater_equal(ymin,0)\n xmax_index = tf.less_equal(xmax,img_w)\n ymax_index = tf.less_equal(ymax,img_h)\n\n indices = tf.transpose(tf.stack([ymin_index,xmin_index,ymax_index,xmax_index]))\n indices = tf.cast(indices,dtype=tf.int32)\n indices = tf.reduce_sum(indices,axis=1)\n indices = tf.where(tf.equal(indices,tf.shape(boxes)[1]))\n\n return tf.reshape(indices,[-1,])\n\ndef nmx_boxes(decode_boxes,scores,iou_threshold,max_output_size,name):\n\n \"\"\"\n 1) NMS\n 2) get maximum num of proposals\n\n :param decode_boxes:\n :param scores:\n :param iou_threshold:\n :param max_output_size:\n :param name:\n :return: valid indices\n \"\"\"\n valid_indices = tf.image.non_max_suppression(boxes=decode_boxes,\n scores=scores,\n max_output_size=max_output_size,\n iou_threshold=iou_threshold,\n name=name)\n return valid_indices\n\ndef padd_boxes_with_zeros(boxes,scores,max_num_of_boxes):\n \"\"\"\n num of boxes less than max num of boxes,so it need to pad with zeros[0,0,0,0]\n :param boxes:\n :param scores: [-1]\n :param max_num_of_boxes:\n :return:\n \"\"\"\n\n\n pad_num = tf.cast(max_num_of_boxes,tf.int32) - tf.shape(boxes)[0]\n\n zero_boxes = tf.zeros(shape=[pad_num,4],dtype=boxes.dtype)\n zero_scores = tf.zeros(shape=[pad_num],dtype=scores.dtype)\n\n final_boxes = tf.concat([boxes,zero_boxes],axis=0)\n final_scores = tf.concat([scores,zero_scores],axis=0)\n\n return final_boxes,final_scores\n\n\n\n\n\n","sub_path":"libs/box_utils/boxes_utils.py","file_name":"boxes_utils.py","file_ext":"py","file_size_in_byte":2943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"278983923","text":"import tensorflow as tf\n\nwith tf.variable_scope(\"foo\"):\n a = tf.get_variable(\"bar\", [1])\n print(a.name)\n\nwith tf.variable_scope(\"bar\"):\n b = tf.get_variable(\"bar\", [1])\n print(b.name)\n\n\nwith tf.name_scope(\"aa\"):\n # tf.Variable 受tf.name_scope 影响,名称中有aa\n a = tf.Variable([1])\n print(\"\\n\"+a.name)\n\n a = tf.get_variable(\"b\", [1])\n print(a.name)\n\nwith tf.name_scope(\"bb\"):\n # ValueError: Variable b already exists, disallowed.\n # Did you mean to set reuse=True in VarScope? Originally defined at:\n # tf.get_variable 不受tf.name_scope影响,所以这里获取 \"b\"变量,已经被声明过,回报重复声明错误\n tf.get_variable(\"b\", [1])\n\n\n","sub_path":"TensorFlow/Train/tbTrain231.py","file_name":"tbTrain231.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"498859074","text":"#!/usr/bin/env python3\n\n# Keep asking for an integer until the input is an integer\ndef integer(prompt=\"integer: \"):\n userInput = input(prompt)\n try:\n return int(userInput)\n except:\n print(\"Please enter a number.\")\n return integer(prompt)\n\n# This is what happens when you run \"python get.py\"\nif __name__ == \"__main__\":\n test = [integer()]\n print(\"\\n\".join([item for item in test]))","sub_path":"get.py","file_name":"get.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"48579573","text":"from django.db import models\nfrom .models import Branches\n\nclass Permission(models.Model):\n type_permission = models.CharField(max_length=200)\n permissions = models.CharField(max_length=200, null=True, blank=True)\n is_administrator = models.BooleanField(default=False, verbose_name='مدير')\n branch = models.ForeignKey(Branches, on_delete=models.DO_NOTHING, null=True, blank=True, verbose_name=\"الفرع\")\n\n\n def __str__(self):\n return self.type_permission\n\n # def full_permissions(self):\n # import json\n # permission = {}\n # if self.permissions == '{}' or self.permissions == None:\n # permission['administrator'] = False\n # else:\n # permission = json.loads(self.permissions)\n # if not 'administrator' in permission:\n # permission['administrator'] = False\n # self.permissions = json.dumps(permission)\n # pass\n\n def save(self, *args, **kwargs):\n # self.full_permissions()\n super(Permission, self).save(*args, **kwargs)\n\n class Meta:\n verbose_name = \"الصلاحية\"\n verbose_name_plural = \"الصلاحيات\"\n\n\nclass Users(models.Model):\n user_name = models.CharField(max_length=200)\n name = models.CharField(max_length=200)\n password = models.CharField(max_length=8)\n is_show = models.BooleanField(default=True)\n user_permissions = models.ForeignKey(Permission, on_delete=models.DO_NOTHING, null=True, blank=True)\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name = \"المستخدم\"\n verbose_name_plural = \"المستخدمين\"\n","sub_path":"ramadan/models/Users.py","file_name":"Users.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"123466832","text":"import urllib.request as urllib2\nimport urllib\nimport json\nimport urllib.parse\nimport base64\n\n\n\n\n\n\ndef convert():\n\n # print('convert')\n image = open('weh.jpg', 'rb') # open binary file in read mode\n image_read = image.read()\n image_64_encode = base64.b64encode(image_read)\n strdata = str(image_64_encode).strip('b')\n trimdata = ''\n for line in strdata:\n trimdata += line.strip(\"'\")\n send(trimdata)\n print('data:image/jpeg;base64,' + trimdata)\n\n\ndef send(dataa):\n url = 'http://smartsys.ml/upload.php'\n\n\n #prepare raw json data\n raw = {'deviceID':'frompyth','image_data':dataa}\n\n #encode raw data with json encoding\n data = json.dumps(raw).encode('utf8')\n\n #init post request\n req = urllib2.Request(url, data, {'Content-Type': 'application/json','User-Agent': 'Mozilla/5.0'})\n f = urllib2.urlopen(req)\n\n #read response from api \n response = f.read()\n f.close()\n\n\n#print (response)\n\n\n\nconvert()\n","sub_path":"hardware/testing/syafiq.py","file_name":"syafiq.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"139498211","text":"#!python\n#%matplotlib inline\nfrom __future__ import print_function\nimport time\n\nimport numpy as np\nfrom numpy import convolve as np_convolve\nfrom scipy.signal import fftconvolve, lfilter, firwin\nfrom scipy.signal import convolve as sig_convolve\nfrom scipy.ndimage import convolve1d\n#import matplotlib.pyplot as plt\n\n# Create the m by n data to be filtered.\nm = 1\nn = 2 ** 18\nx = np.random.random(size=(m, n))\n\nconv_time = []\nnpconv_time = []\nfftconv_time = []\nconv1d_time = []\nlfilt_time = []\n\ndiff_list = []\ndiff2_list = []\ndiff3_list = []\n\nntaps_list = 2 ** np.arange(2, 14)\n\nfor ntaps in ntaps_list:\n print (\"Create a FIR filter.\")\n b = firwin(ntaps, [0.05, 0.95], width=0.05, pass_zero=False)\n\n print (\" --- signal.convolve ---\")\n tstart = time.time()\n conv_result = sig_convolve(x, b[np.newaxis, :], mode='valid')\n conv_time.append(time.time() - tstart)\n\n print (\"--- numpy.convolve ---\")\n tstart = time.time()\n npconv_result = np.array([np_convolve(xi, b, mode='valid') for xi in x])\n npconv_time.append(time.time() - tstart)\n\n print (\"--- signal.fftconvolve ---\")\n tstart = time.time()\n fftconv_result = fftconvolve(x, b[np.newaxis, :], mode='valid')\n fftconv_time.append(time.time() - tstart)\n\n print (\"--- convolve1d ---\")\n tstart = time.time()\n # convolve1d doesn't have a 'valid' mode, so we expliclity slice out\n # the valid part of the result.\n conv1d_result = convolve1d(x, b)[:, (len(b)-1)//2 : -(len(b)//2)]\n conv1d_time.append(time.time() - tstart)\n\n print( \"--- lfilter ---\")\n tstart = time.time()\n lfilt_result = lfilter(b, [1.0], x)[:, len(b) - 1:]\n lfilt_time.append(time.time() - tstart)\n\n diff = np.abs(fftconv_result - lfilt_result).max()\n diff_list.append(diff)\n\n diff2 = np.abs(conv1d_result - lfilt_result).max()\n diff2_list.append(diff2)\n\n diff3 = np.abs(npconv_result - lfilt_result).max()\n diff3_list.append(diff3)\n\n# Verify that np.convolve and lfilter gave the same results.\nprint(\"Did np.convolve and lfilter produce the same results?\",)\ncheck = all(diff < 1e-13 for diff in diff3_list)\nif check:\n print( \"Yes.\")\nelse:\n print( \"No! Something went wrong.\")\n\n# Verify that fftconvolve and lfilter gave the same results.\nprint( \"Did fftconvolve and lfilter produce the same results?\")\ncheck = all(diff < 1e-13 for diff in diff_list)\nif check:\n print( \"Yes.\")\nelse:\n print( \"No! Something went wrong.\")\n\n# Verify that convolve1d and lfilter gave the same results.\nprint( \"Did convolve1d and lfilter produce the same results?\",)\ncheck = all(diff2 < 1e-13 for diff2 in diff2_list)\nif check:\n print( \"Yes.\")\nelse:\n print( \"No! Something went wrong.\")\n\n\nprint (conv_time )\nprint( npconv_time )\nprint (fftconv_time )\nprint (conv1d_time )\nprint (lfilt_time )\n","sub_path":"scipy_test.py","file_name":"scipy_test.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"382163660","text":"from py2neo import Graph,Node,Relationship\nimport random\nimport numpy\n\ngraph = Graph(\"bolt://localhost:7687\", username=\"neo4j\", password=\"1234\")\n\nnum_intentos=3\ndef genera_pregunta2(num_intentos):\n\n cursorniveles = graph.run(\"Match(n) Return n.name, n.pr ORDER BY n.pr\")\n cursorniveles.forward()\n\n lista = []\n lista1 = []\n lista2 = []\n lista3 = []\n\n for field in cursorniveles:\n lista.append(field[\"n.pr\"])\n\n l = lista\n\n maximo=max(l)\n minimo=min(l)\n\n rango = maximo - minimo\n intervalo = rango/3\n\n rango1 = minimo + intervalo\n rango2 = rango1 + intervalo \n rango3 = rango2 + intervalo \n\n for i in l:\n if i >= minimo and i <=rango1:\n lista1.append(i)\n\n if i >= rango1 and i <=rango2:\n lista2.append(i)\n\n if i >= rango2 and i <=rango3:\n lista3.append(i)\n\n lfacil = lista1\n lmedia = lista2\n ldificil = lista3\n\n #print (lfacil)\n node = random.choice(ldificil)\n node = str(node)\n print (node)\n \n\n cursor = graph.run(\"Match (a)-[r]->(m) Where a.pr = \"+ node +\" Return a.name,labels(a),TYPE(r),m.title,labels(m), rand() as l ORDER BY l LIMIT 1\")\n\n\n cursor.forward()\n p=\"¿What\" + \" \" + cursor.current[\"labels(a)\"][0] + \" \" + cursor.current[\"TYPE(r)\"] + \" \" + \"the\" + \" \" + cursor.current[\"labels(m)\"][0] + \" \" + cursor.current[\"m.title\"] + \"?\"\n p=p.replace(\"_\",\" \")\n\n #p =(\"¿Qué\", cursor.current[\"labels(a)\"], cursor.current[\"TYPE(r)\"], \"el/la\", cursor.current[\"labels(m)\"],cursor.current[\"m.title\"], \"?\")\n v1=(cursor.current[\"a.name\"])\n tipo_pregunta= cursor.current[\"labels(a)\"][0]\n tipo_destino = cursor.current[\"labels(m)\"][0]\n names = [v1]\n\n s = cursor.current[\"TYPE(r)\"]\n #\n c = cursor.current[\"m.title\"]\n #\n # print(s,c)\n # print(\"Match (\"+tipo_pregunta+\")-[:\" + s + \"]->(m) where not (\"+tipo_pregunta+\")-[:\"+ s +\"]->(:\"+tipo_destino+\"{title:'\" + c + \"' }) return (\"+tipo_pregunta+\").name, rand() as l ORDER BY l LIMIT 3\")\n cursor2 = graph.run(\"Match (\"+tipo_pregunta+\")-[:\" + s + \"]->(m) where not (\"+tipo_pregunta+\")-[:\"+ s +\"]->(:\"+tipo_destino+\"{title:'\" + c + \"' }) return (\"+tipo_pregunta+\").name, rand() as l ORDER BY l LIMIT 3\")\n\n # cursor2.forward()\n # print(cursor2.current[\"b.name\"])\n\n\n\n names2 = []\n for field in cursor2:\n names2.append(field[\"(\"+tipo_pregunta+\").name\"])\n\n # print(names2)\n names +=names2\n\n\n random.shuffle(names)\n l=(names)\n\n inames=len(names)\n # print(inames)\n\n i=names.index(cursor.current[\"a.name\"])\n\n if inames == 4:\n return p,l,i\n else:\n if num_intentos>0:\n return genera_pregunta2(num_intentos-1)\n else:\n return \"No se pudo generar la pregunta\", [], -1\n\nprint (genera_pregunta2(num_intentos))\n","sub_path":"motor.py","file_name":"motor.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"255989407","text":"from time import time as curr_time\r\nfrom itertools import zip_longest\r\nfrom select import select\r\nfrom struct import unpack\r\nfrom struct import pack\r\nimport threading\r\nimport socket\r\nfrom Config import *\r\n\r\n\r\nlock = threading.Lock()\r\nwrite_lock = threading.Lock()\r\n\r\n\r\nclass ICMP(threading.Thread):\r\n def __init__(self, destination, com, broadcast, count):\r\n super(ICMP, self).__init__()\r\n self.destination = destination\r\n self.broadcast = broadcast\r\n self.count = count\r\n self.timeout = TIMEOUT\r\n self.com = com\r\n self.id = threading.get_ident()\r\n self.s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)\r\n\r\n def run(self):\r\n super(ICMP, self).run()\r\n self.id = threading.get_ident()\r\n if self.com == PING_CMD:\r\n self.ping()\r\n elif self.com == TRACE_CMD:\r\n self.traceroute()\r\n elif self.com == SMURF_CMD:\r\n self.s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) # ip header include\r\n # self.s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\r\n self.smurf()\r\n self.s.close()\r\n\r\n @staticmethod\r\n def write_log_thread_safe(text):\r\n with write_lock:\r\n print('{:10s} {}'.format(threading.current_thread().getName(), text))\r\n\r\n @staticmethod\r\n def calculate_checksum(data):\r\n _res = 0\r\n _i = 0\r\n while _i < len(data):\r\n if _i == len(data) - 1:\r\n calc = data[_i]\r\n elif _i > len(data) - 1:\r\n calc = 0\r\n else: # count < len(data)\r\n calc = data[_i + 1] * 256 + data[_i]\r\n _res = (_res + calc) & 0xffffffff\r\n _i += 2\r\n _res = (_res >> 16) + (_res & 0xffff)\r\n _res += (_res >> 16)\r\n _res = ~_res & 0xffff\r\n return _res >> 8 | (_res << 8 & 0xff00)\r\n\r\n def create_icmp_packet(self):\r\n \"\"\" Header: type(8), code(8), checksum(16), id(16), sequence(16) \"\"\"\r\n payload = b'_' + bytes(str(curr_time()), 'UTF-8') + b'_'\r\n checksum = self.calculate_checksum(pack('bbHHh', 8, 0, 0, self.id, 1) + payload)\r\n return pack('bbHHh', 8, 0, socket.htons(checksum), self.id, 1) + payload\r\n\r\n @staticmethod\r\n def create_ip_header(src, dst):\r\n packet = b''\r\n packet += b'\\x45' # Version (IPv4) + Internet Protocol header length\r\n packet += b'\\x00' # No quality of service\r\n packet += b'\\x00\\x54' # Total frame length\r\n packet += b'\\x23\\x2c' # Id of this packet\r\n packet += b'\\x40' # Flags (Don't Fragment)\r\n packet += b'\\x00' # Fragment offset: 0\r\n packet += b'\\x40' # Time to live: 64\r\n packet += b'\\x01' # Protocol: ICMP (1)\r\n packet += b'\\x0a\\x0a' # Checksum (python does the work for us)\r\n packet += socket.inet_aton(src) # Source IP\r\n packet += socket.inet_aton(dst) # Destination IP\r\n return packet\r\n\r\n def send_single_req(self, ttl=128):\r\n self.s.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)\r\n packet = self.create_icmp_packet()\r\n while packet:\r\n sent = self.s.sendto(packet, (self.destination, 1))\r\n packet = packet[sent:]\r\n\r\n def recv_res(self, t):\r\n time_left = self.timeout\r\n while time_left > 0:\r\n r_w_e = select([self.s], [], [], time_left)\r\n time_left = self.timeout - (curr_time() - t)\r\n if not r_w_e[0]:\r\n continue\r\n data, addr = self.s.recvfrom(1024, socket.MSG_PEEK)\r\n time_received = curr_time()\r\n index2 = data.rfind(b'_')\r\n index1 = data[:index2].rfind(b'_')\r\n time_sent = float(data[index1 + 1:index2].decode('UTF-8')) if index1 != -1 and index2 != -1 else t\r\n if self.com == TRACE_CMD:\r\n self.s.recvfrom(1024)\r\n return addr, time_received - time_sent\r\n header = data[20:28]\r\n type, code, checksum, p_id, sequence = unpack('bbHHh', header)\r\n if p_id == self.id:\r\n self.s.recvfrom(1024)\r\n return addr, time_received - time_sent\r\n self.s.recvfrom(1024) # WUUUUUUUT\r\n return None, None\r\n\r\n def ping(self):\r\n total_time = 0\r\n success_count = 0\r\n for i in range(self.count):\r\n self.write_log_thread_safe('Pinging {}.........'.format(self.destination))\r\n try:\r\n with lock:\r\n self.send_single_req()\r\n addr, delay = self.recv_res(curr_time())\r\n except (socket.gaierror, OSError):\r\n self.write_log_thread_safe('Wrong address')\r\n return\r\n if delay is None:\r\n self.write_log_thread_safe('Timeout Exceed')\r\n else:\r\n delay = round(delay * 1000.0, 4)\r\n total_time += delay\r\n success_count += 1\r\n self.write_log_thread_safe('Got ping response for {} in {} milliseconds.'.format(addr[0], delay))\r\n if success_count:\r\n avg_time = round(total_time / success_count, 2)\r\n self.write_log_thread_safe('Success count: {}/{} Avg time: {}'.format(success_count, self.count, avg_time))\r\n\r\n def traceroute(self):\r\n for x in range(1, self.count):\r\n try:\r\n with lock:\r\n self.send_single_req(x)\r\n t1 = self.recv_res(curr_time())\r\n with lock:\r\n self.send_single_req(x)\r\n t2 = self.recv_res(curr_time())\r\n with lock:\r\n self.send_single_req(x)\r\n t3 = self.recv_res(curr_time())\r\n except (socket.gaierror, OSError):\r\n self.write_log_thread_safe('Wrong address')\r\n return\r\n t1str = '*' if t1 == (None, None) else '{:15s} : {:5.2f} ms'.format(t1[0][0], t1[1] * 1000)\r\n t2str = '*' if t2 == (None, None) else '{:15s} : {:5.2f} ms'.format(t2[0][0], t2[1] * 1000)\r\n t3str = '*' if t3 == (None, None) else '{:15s} : {:5.2f} ms'.format(t3[0][0], t3[1] * 1000)\r\n self.write_log_thread_safe('{:2s} -- {} {} {}'.format(str(x), t1str, t2str, t3str))\r\n\r\n if t1 != (None, None) and t1[0][0] == socket.gethostbyname(self.destination): # destination reached\r\n break\r\n\r\n def smurf(self):\r\n try:\r\n packet = self.create_ip_header(src=self.destination, dst=self.broadcast) + self.create_icmp_packet()\r\n except (OSError, TypeError):\r\n self.write_log_thread_safe('Illegal or missed address detected.')\r\n return\r\n for _ in range(self.count):\r\n _packet = packet\r\n while _packet:\r\n sent = self.s.sendto(_packet, (self.destination, 0))\r\n _packet = _packet[sent:]\r\n self.write_log_thread_safe('Sent smurfik to {} from {}'.format(self.destination, self.broadcast))\r\n\r\n\r\ndef main(hosts, broadcasts, com, n):\r\n threads = []\r\n for h, b in zip_longest(hosts, broadcasts, fillvalue=None):\r\n threads.append(ICMP(h, com, b, n))\r\n threads[-1].start()\r\n [thread.join() for thread in threads]\r\n","sub_path":"4/СПОЛКС/Lab5/ICMP.py","file_name":"ICMP.py","file_ext":"py","file_size_in_byte":7319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"631662505","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\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/order/signal_handlers.py\n# Compiled at: 2011-09-15 05:06:32\nfrom order.utils import create_order_objects, is_orderable, resolve_labels, resolve_order_item_related_set_name, sanitize_order\n\ndef post_save(sender, instance, created, **kwargs):\n \"\"\"\n After save create order instance for sending instance for orderable models.\n \"\"\"\n model_label = ('.').join([sender._meta.app_label, sender._meta.object_name])\n labels = resolve_labels(model_label)\n order_field_names = is_orderable(model_label)\n if order_field_names:\n orderitem_set = getattr(instance, resolve_order_item_related_set_name(labels))\n if not orderitem_set.all():\n fields = {}\n for order_field_name in order_field_names:\n fields[order_field_name] = 1\n\n orderitem_set.model.objects.create(item=instance, **fields)\n sanitize_order(orderitem_set.model)\n\n\ndef post_syncdb(sender, created_models, **kwargs):\n for model in created_models:\n label = ('.').join([model._meta.app_label, model._meta.object_name])\n order_fields = is_orderable(label)\n if order_fields:\n create_order_objects(model, order_fields)","sub_path":"pycfiles/django_order-0.0.7-py2.6/signal_handlers.py","file_name":"signal_handlers.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"520918216","text":"# A class for building graphs of interconnected nodes\n# Nodes of graph-type maps have neighbors only, with no heirarchy\n# Andrew Vikartofsky, March 2019\n\n\nclass Node:\n def __init__(self, myValue, myNeighbors=[]):\n for n in myNeighbors:\n if type(n) is not Node:\n print('Node init error - declared neighbor is not a Node!')\n return\n self.neighbors = myNeighbors\n self.value = myValue\n for n in myNeighbors:\n n.addNeighbor(self)\n\n def addNeighbor(self, newNeighbor):\n if type(newNeighbor) is not Node:\n print('Node modification error - declared new neighbor is not a Node!')\n return\n if newNeighbor not in self.neighbors:\n self.neighbors.append(newNeighbor)\n\n def removeNeighbor(self, oldNeighbor):\n if oldNeighbor not in self.neighbors:\n print('Node modification error - requested neighbor does not exist!')\n return\n self.neighbors.remove(oldNeighbor)\n\n def getNeighbors(self):\n for n in self.neighbors:\n print(n.value)\n\n def __populate(self, myUnvisited):\n if self not in myUnvisited:\n myUnvisited.append(self)\n for n in self.neighbors:\n myUnvisited = n.__populate(myUnvisited)\n return myUnvisited\n\n def distance(self, otherNode):\n if otherNode.value == self.value:\n print(\"Well, that's easy. The distance is zero!\")\n else: # calculate distance via Dijkstra's algorithm\n unvisited = [] # list of connected nodes in the graph, to be searched in the distance-finding algorithm.\n unvisited = self.__populate(unvisited) # populating this list recursively\n\n print('The graph has these nodes:')\n for n in unvisited: # searching the graph...\n print(n.value)\n print('The distance between node',self.value,'and node',otherNode.value,'is','undefined','.')\n\n\n#\n# %%\n# building the simple test graph:\n# 0 -- 1\n# | / | \\\n# | / | 2\n# |/ | /\n# 4 - 3\n\nnode0 = Node(0)\nnode1 = Node(1, [node0])\nnode2 = Node(2, [node1])\nnode3 = Node(3, [node1, node2])\nnode4 = Node(4, [node0, node1, node3])\n\nnode0.getNeighbors()\n\n# %%\nnode2.distance(node4)\n","sub_path":"mapClass.py","file_name":"mapClass.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"167711316","text":"# -*- coding: utf-8 -*-\n\nfrom .errors import ProcessIDNotExistsError, ProcessNotFoundError, WindowNotFoundError\nfrom .util import get_process_id_by_process_name, get_process_id_by_window_title, pid_exists\n\n\nclass Process(object):\n \"\"\"\n Class representing a process.\n \"\"\"\n\n __pid = 0\n __process_name = \"\"\n __window_title = \"\"\n\n @property\n def pid(self) -> int:\n return self.__pid\n\n @pid.setter\n def pid(self, pid: int) -> None:\n\n # Check if the value is an integer.\n if not isinstance(pid, int):\n raise ValueError(\"The process ID must be an integer.\")\n\n # Check if the PID exists and instantiate it.\n if pid_exists(pid): self.__pid = pid\n else: raise ProcessIDNotExistsError(pid)\n\n @property\n def process_name(self) -> str:\n return self.__process_name\n\n @process_name.setter\n def process_name(self, process_name: str) -> None:\n\n # Get the process ID.\n pid = get_process_id_by_process_name(process_name)\n if not pid: raise ProcessNotFoundError(process_name)\n\n # Set the PID and process name.\n self.__pid = pid\n self.__process_name = process_name\n\n @property\n def window_title(self) -> str:\n return self.__window_title\n\n @window_title.setter\n def window_title(self, window_title: str) -> None:\n\n # Get the process ID.\n pid = get_process_id_by_window_title(window_title)\n if not pid: raise WindowNotFoundError(window_title)\n\n # Set the PID and the window title.\n self.__pid = pid\n self.__window_title = window_title\n","sub_path":"PyMemoryEditor/process/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"388554313","text":"class animal():\n name = 'not named' #static\n\n def __init__(self):\n print('animal constructed')\n\n\nclass reptile(animal):\n hasScales = True #static\n\n def __init__(self):\n super(reptile,self).__init__() #must init the suoer\n print('reptile constructed')\n\nclass mammal(animal):\n hasHair = True #static\n\n def __init__(self):\n super(mammal,self).__init__() #must init the suoer\n self.hasBackBone = True\n print('mammal constructed')\n\nclass dragon(reptile,mammal):\n hasWings = True #static variable\n\n def __init__(self,age = 0):\n super(dragon,self).__init__() #must init the suoer\n self.age = age\n print('dragon constructed and is %d years old' % self.age)\n\n def __del__(self):\n print(self.__class__.__name__+'destroyed')\n\nprint('start')\n\nmydragon1 = dragon(100)\nmydragon1.name = 'San'\nmydragon2 = dragon()\n\nmydragon2.name = 'Sam'\n# dragon.name = 'beka'\n\n\n# print(mydragon1.name)\n\n# print(mydragon2.name)\n\n\nprint('Hair = %s' % mydragon1.hasHair)\nprint('BackBone = %s' % mydragon1.hasBackBone)\nprint('%s is %d years old' % (mydragon1.name, mydragon1.age))\n\nprint('finished')\n\n","sub_path":"Practiceself/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"401528686","text":"class EarlyStopping():\n \"\"\"\n Early stopping to stop the training when the loss does not improve after\n certain steps.\n \"\"\"\n\n def __init__(self, patience=5, min_delta=0):\n \"\"\"\n :param patience: how many steps to wait before stopping when loss is\n not improving\n :param min_delta: minimum difference between new loss and old loss for\n new loss to be considered as an improvement\n \"\"\"\n\n self.patience = patience\n self.min_delta = min_delta\n self.counter = 0\n self.best_loss = None\n self.early_stop = False\n\n def __call__(self, val_loss):\n if self.best_loss == None:\n self.best_loss = val_loss\n elif self.best_loss - val_loss > self.min_delta:\n self.best_loss = val_loss\n elif self.best_loss - val_loss < self.min_delta:\n self.counter += 1\n print(f\"INFO: Early stopping counter {self.counter} of {self.patience}\")\n if self.counter >= self.patience:\n print('INFO: Early stopping')\n self.early_stop = True","sub_path":"autoencoder_program_synthesis/model_utils/earlystopping.py","file_name":"earlystopping.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"44051814","text":"import os\nfrom tkinter import messagebox\nimport glob\n\nfrom pydub import AudioSegment\nfrom pydub.silence import split_on_silence\n\nfrom logger import Logger\nfrom constants import AUDIO_SAMPLE_DIR, FFPMPEG_EXE_PATH\n\nclass AudioSampling:\n def __init__(self):\n self.sample_dir = os.path.join(os.getcwd(), AUDIO_SAMPLE_DIR) # Append current dir + audio sample dir\n self.ffmpeg_path = os.path.join(os.getcwd(), FFPMPEG_EXE_PATH) # Append current dir + ffmpeg exe path\n self.logger = Logger.get_instance()\n\n self.__remove_all_samples(self.sample_dir)\n self.__create_dir()\n\n def __create_dir(self):\n if not os.path.isdir(self.sample_dir): # If no dir is found, create it\n os.mkdir(self.sample_dir)\n\n def sample(self, audio_path, min_silence_len, max_silence_dB):\n try:\n AudioSegment.converter = self.ffmpeg_path\n audio = AudioSegment.from_wav(audio_path)\n samples = split_on_silence(audio,\n min_silence_len = min_silence_len, # (in ms) minimum length of a silence\n silence_thresh = max_silence_dB, # (in dBFS) anything quieter than this will be silent\n keep_silence=True # If True is specified, all the silence is kept\n )\n\n if len(samples) == 0:\n self.logger.error('No sample created because either Min Silence Length ({} ms) is too long, or Max Silence dB ({} dB) is too high.'.format(min_silence_len, max_silence_dB))\n messagebox.showerror('Error', 'No sample created because either Min Silence Length ({} ms) is too long, or Max Silence dB ({} dB) is too high.\\nPlease adjust them and retry!'.format(min_silence_len, max_silence_dB))\n return []\n\n # Have to go to the sample directory to save the sample files\n before_dir = os.getcwd()\n os.chdir(self.sample_dir)\n\n result_dict = {'path': None, 'length_s': 0.0}\n result_dicts = []\n i = 1\n for sample in samples:\n name = \"sample_{}.wav\".format(i)\n sample.set_channels(1)\n sample.export(name, format='wav', bitrate ='256k')\n print(\"Created sample_{0}.wav\".format(i))\n i += 1\n\n result_dict['path'] = self.sample_dir + name\n result_dict['length_s'] = AudioSegment.from_file(result_dict['path']).duration_seconds\n result_dicts.append(result_dict.copy())\n\n # Once done, go back to the before directory\n os.chdir(before_dir)\n return result_dicts\n\n except Exception as e:\n self.logger.error('Failed to sample audio file. Error: {}'.format(e))\n messagebox.showerror('Error', 'Failed to sample audio file.\\nError: {}'.format(e))\n\n def __remove_all_samples(self, path):\n try:\n if os.path.isdir(self.sample_dir):\n files = glob.glob(path + '*')\n for f in files:\n os.remove(f)\n except Exception as e:\n self.logger.error('Failed to remove old audio samples. Error: {}'.format(e))\n messagebox.showerror('Error', 'Failed to remove old audio samples.\\nError: {}'.format(e))","sub_path":"TranscriptAutoMaker/TranscriptAutoMaker/src/audio_sampling.py","file_name":"audio_sampling.py","file_ext":"py","file_size_in_byte":3314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"54101783","text":"import tensorflow as tf\nfrom .dense import Dense\nfrom .utils import _activation_to_string\n\nclass GLUv2(object):\n\tdef __init__(self,initializer=tf.contrib.layers.xavier_initializer()):\n\t\tself.initializer = initializer\n\tdef __call__(self,input,scope=\"GLU\"):\n\t\twith tf.variable_scope(scope,reuse=tf.AUTO_REUSE):\n\t\t\tfeature_size = input.get_shape().as_list()[-1]\n\t\t\tself._inner_dense = Dense(feature_size,tf.nn.sigmoid,initializer=self.initializer)\n\t\t\treturn input * self._inner_dense(input)\n\tdef to_json(self,sess):\n\t\tcurr_layer = self._inner_dense.to_json(sess)\n\t\tcurr_layer['type'] = \"GLUv2\"\n\t\treturn curr_layer\n\n\nclass GLU(object):\n\tdef __init__(self,activation=tf.identity):\n\t\tself.activation = activation\n\tdef __call__(self,input,scope=\"GLU\"):\n\t\twith tf.variable_scope(scope,reuse=tf.AUTO_REUSE):\n\t\t\tself._in_feature_size = input.get_shape().as_list()[-1]\n\t\t\tassert self._in_feature_size % 2 == 0, \"input last dimention should be divisible by two\" \n\t\t\tself._out_feature_size = self._in_feature_size // 2\n\t\t\treturn self.activation(input[:,:self._out_feature_size]) * tf.nn.sigmoid(input[:,self._out_feature_size:])\n\tdef to_json(self,sess):\n\t\tcurr_layer={}\n\t\tcurr_layer['in_dim'] = self._in_feature_size\n\t\tcurr_layer['out_dim'] = self._out_feature_size\n\t\tcurr_layer['activation'] = _activation_to_string(self.activation)\n\t\tcurr_layer['type'] = \"GLU\"\n\t\treturn curr_layer","sub_path":"training_scripts/layers/glu.py","file_name":"glu.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"540152958","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport kinpy as kp\n\nimport gym\nfrom gym import error, spaces, utils\nfrom gym.utils import seeding\n\nimport tensorflow as tf\n\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, Activation, Flatten, Input, Concatenate\nfrom keras.optimizers import Adam\n\nfrom rl.agents.dqn import DQNAgent\nfrom rl.policy import BoltzmannQPolicy\nfrom rl.memory import SequentialMemory\n\n\nfrom rl.agents import DDPGAgent\nfrom rl.memory import SequentialMemory\nfrom rl.random import OrnsteinUhlenbeckProcess\n\nclass RobotKinematics:\n\n def __init__(self):\n self.chain = kp.build_chain_from_urdf(open(\"modello.urdf\").read())\n self.njoints = len( self.chain.get_joint_parameter_names() )\n self.end_link = \"link{}\".format(self.njoints)\n print(\"End link is: \", self.end_link)\n\n def calculate_direct_kinematic(self, joint_angles):\n\n assert len(joint_angles) == self.njoints\n\n joint_state = {}\n for i in range(0, len(joint_angles)):\n joint_state[\"joint{}\".format(i)] = joint_angles[i]\n\n all_link_positions = self.chain.forward_kinematics(joint_state)\n return all_link_positions[self.end_link].pos\n\n def get_joints_number(self):\n return self.njoints\n\nclass SnakeGymContinuous(gym.Env):\n\n class NoInfo:\n def items(self):\n return []\n\n # Spaces: https://ai-mrkogao.github.io/reinforcement%20learning/openaigymtutorial/\n # Own enironment: https://mc.ai/creating-a-custom-openai-gym-environment-for-stock-trading/\n\n metadata = {'render.modes': ['human']}\n\n JOINT_LIMIT = np.pi/4\n\n def __init__(self, kinematics, MOVE_DELTA=1e-2):\n self.N_JOINTS = kinematics.get_joints_number()\n self.MOVE_DELTA = MOVE_DELTA\n self.joint_limits = np.array(self.N_JOINTS * [np.pi/4], dtype=np.float32)\n self.action_space = spaces.Box(low=-self.joint_limits, high=self.joint_limits, dtype=np.float32)\n self.observation_space = spaces.Box(low=-self.joint_limits, high=self.joint_limits, dtype=np.float32)\n self.kinematics = kinematics\n self.reset()\n\n def __parse_action(self, action):\n joint = int(action // 2)\n direction = int(action % 2)\n if joint >= self.N_JOINTS: raise ValueError(\"Invalid action: {} | NJOINTS: {}, joint: {}\".format(action, self.N_JOINTS, joint))\n if direction == 0: direction = -1\n return (joint, direction)\n\n def __render_state(self, state):\n position = self.kinematics.calculate_direct_kinematic(state)\n return \"DIST {0:3.3f} | XYZ {1: 1.6f} {2: 1.6f} {3: 1.6f}\".format(self.distance, position[0], position[1], position[2])\n #return \"DIST {0:3.3f} | XYZ {1: 1.6f} {2: 1.6f} {3: 1.6f} | state {4}\".format(self.distance, position[0], position[1], position[2], state)\n\n def reset(self):\n self.current_state = np.array(self.N_JOINTS * [0]).astype(float)\n self.goal_state = np.random.uniform(-1 * self.JOINT_LIMIT, self.JOINT_LIMIT, self.N_JOINTS).astype(float)\n self.goal = self.kinematics.calculate_direct_kinematic(self.goal_state)\n self.distance = np.linalg.norm(self.goal - self.kinematics.calculate_direct_kinematic(self.current_state))\n\n self.best_distance = self.distance\n self.best_state = self.current_state\n\n print(\"Setting GOAL to \", self.__render_state(self.goal_state))\n return self.current_state\n\n def render(self, mode='human', close=False):\n print(self.__render_state(self.current_state))\n\n def step(self, action):\n\n next_state = np.clip(action, -1 * self.joint_limits, self.joint_limits)\n\n next_position = self.kinematics.calculate_direct_kinematic(next_state)\n\n old_distance = self.distance\n self.distance = np.linalg.norm(self.goal - next_position)\n reward = 0 if old_distance > self.distance else -1 \n # -1 * self.distance \n # 1.0/self.distance if self.distance < old_distance else -1 * self.distance\n\n if self.distance < self.best_distance:\n self.best_distance = self.distance\n self.best_state = next_state\n\n self.current_state = next_state\n self.done = False\n self.info = SnakeGymContinuous.NoInfo()\n\n return self.current_state, reward, self.done, self.info\n\n\nif __name__ == '__main__':\n\n kin = RobotKinematics()\n\n tf.compat.v1.disable_eager_execution()\n\n # Get the environment and extract the number of actions.\n env = SnakeGymContinuous(kin)\n np.random.seed(123)\n env.seed(123)\n print(env.action_space)\n print(env.action_space.shape)\n nb_actions = env.action_space.shape[0]\n\n # Next, we build a very simple model.\n actor = Sequential()\n actor.add(Flatten(input_shape=(1,) + env.observation_space.shape))\n actor.add(Dense(16))\n actor.add(Activation('relu'))\n actor.add(Dense(16))\n actor.add(Activation('relu'))\n actor.add(Dense(16))\n actor.add(Activation('relu'))\n actor.add(Dense(nb_actions))\n actor.add(Activation('linear'))\n print(actor.summary())\n\n action_input = Input(shape=(nb_actions,), name='action_input')\n observation_input = Input(shape=(1,) + env.observation_space.shape, name='observation_input')\n flattened_observation = Flatten()(observation_input)\n x = Concatenate()([action_input, flattened_observation])\n x = Dense(32)(x)\n x = Activation('relu')(x)\n x = Dense(32)(x)\n x = Activation('relu')(x)\n x = Dense(32)(x)\n x = Activation('relu')(x)\n x = Dense(1)(x)\n x = Activation('linear')(x)\n critic = Model(inputs=[action_input, observation_input], outputs=x)\n print(critic.summary())\n\n # Finally, we configure and compile our agent. You can use every built-in Keras optimizer and\n # even the metrics!\n memory = SequentialMemory(limit=100000, window_length=1)\n random_process = OrnsteinUhlenbeckProcess(size=nb_actions, theta=.15, mu=0., sigma=.3)\n agent = DDPGAgent(nb_actions=nb_actions, actor=actor, critic=critic, critic_action_input=action_input,\n memory=memory, nb_steps_warmup_critic=100, nb_steps_warmup_actor=100,\n random_process=random_process, gamma=.99, target_model_update=1e-3)\n #agent.compile(Adam(lr=.001, clipnorm=1.), metrics=['mae'])\n agent.compile('adam', metrics=['mae'])\n\n # Okay, now it's time to learn something! We visualize the training here for show, but this\n # slows down training quite a lot. You can always safely abort the training prematurely using\n # Ctrl + C.\n agent.fit(env, nb_steps=50000, visualize=True, verbose=2, nb_max_episode_steps=400)\n\n print(\"Best distance found: \", env.best_distance)\n print(\"Best state found: \", env.best_state)\n\n # Finally, evaluate our algorithm for 5 episodes.\n # agent.test(env, nb_episodes=5, visualize=True, nb_max_episode_steps=200)\n\n","sub_path":"snake-openai/old/snake-gym-continuous.py","file_name":"snake-gym-continuous.py","file_ext":"py","file_size_in_byte":6872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"170632463","text":"from setuptools import setup, find_packages\nfrom distutils.core import Extension\n\nDISTNAME = 'mhkit_python_utils'\nVERSION = '0.2.0'\nPACKAGES = ['mhkit_python_utils']\nEXTENSIONS = []\nDESCRIPTION = ''\nLONG_DESCRIPTION = open('README.md').read()\nAUTHOR = 'mhkit developers'\nMAINTAINER_EMAIL = ''\nLICENSE = 'Revised BSD'\nURL = ''\nCLASSIFIERS=['Development Status :: 3 - Alpha',\n 'Programming Language :: Python :: 3',\n 'Topic :: Scientific/Engineering',\n 'Intended Audience :: Science/Research',\n 'Operating System :: OS Independent',\n ]\nDEPENDENCIES = ['pandas']\n\n\nsetup(name=DISTNAME,\n version=VERSION,\n packages=PACKAGES,\n ext_modules=EXTENSIONS,\n description=DESCRIPTION,\n long_description=LONG_DESCRIPTION,\n author=AUTHOR,\n maintainer_email=MAINTAINER_EMAIL,\n license=LICENSE,\n url=URL,\n classifiers=CLASSIFIERS,\n zip_safe=False,\n install_requires=DEPENDENCIES,\n scripts=[],\n include_package_data=True\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"230218861","text":"# Copyright 2020 University of New South Wales\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\nclass Node:\n def __init__(\n self,\n name: str,\n time: str = None,\n cpu_seconds: str = None,\n cpu_ratio: str = None,\n ):\n self.name = name\n self.time = time\n self.cpu_seconds = cpu_seconds\n self.cpu_ratio = cpu_ratio\n self.children = []\n\n def append(self, node):\n self.children.append(node)\n\n return node\n\n def to_json(self):\n obj = {\"name\": self.name, \"value\": self.time}\n if self.cpu_ratio:\n obj[\"name\"] = f\"{self.name}, {self.cpu_ratio} CPU ratio\"\n if self.children:\n obj[\"children\"] = list(x.to_json() for x in self.children)\n\n return obj\n\n def replace_with(self, other, include_children: bool = False):\n self.name = other.name\n self.time = other.time\n self.cpu_seconds = other.cpu_seconds\n self.cpu_ratio = other.cpu_ratio\n if include_children:\n self.children = other.children\n","sub_path":"aggreg_stats/analyse_times/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"430558760","text":"import numpy as np\r\nimport re\r\nfrom textdistance import smith_waterman, needleman_wunsch, jaro_winkler, jaccard, levenshtein\r\nfrom fuzzywuzzy import fuzz\r\nfrom collections import defaultdict\r\n\r\n\r\n# from bs4 import BeautifulSoup\r\n\r\n\r\ndef extract_cnr(text):\r\n try:\r\n cnr_num = re.search(\"\"\"\\s[a-zA-Z]{4}[0-9]{12}\\s\"\"\", text, flags=re.IGNORECASE)\r\n if cnr_num:\r\n return cnr_num.group()\r\n else:\r\n return np.nan\r\n except AttributeError:\r\n return np.nan\r\n\r\n\r\ndef extract_case_num(text):\r\n # 'Case no.' not always written. Different courts have different formats\r\n try:\r\n case_num_0 = re.search(\"\"\".+case no\\..+\"\"\", text, flags=re.IGNORECASE) # [12][90][0-9]{2}$\r\n case_num_1 = re.search(\"\"\".+[\\d]{1,6} \"\"\", text, flags=re.IGNORECASE)\r\n case_num = re.search(\"\"\"case no\\..+:(?P.+\\s*.*)\\s*1:\"\"\", text)\r\n if case_num_0:\r\n return case_num_0.group().strip()\r\n else:\r\n return np.nan\r\n except AttributeError:\r\n return np.nan\r\n\r\n\r\n# print(filename, ae)\r\n\r\ndef extract_petitioner(text):\r\n try:\r\n if 'versus' in text:\r\n start = text.find('1:')\r\n end = text.find('versus')\r\n return text[start:end]\r\n # petitioner = re.search(\"\"\"(1:.+?)versus\"\"\", text, flags=re.DOTALL)\r\n # if petitioner:\r\n # print(petitioner.group())\r\n # print(f\"-\"*40)\r\n # return petitioner.group()\r\n else:\r\n return np.nan\r\n except AttributeError:\r\n return np.nan\r\n\r\n\r\ndef extract_respondent(text):\r\n try:\r\n if 'versus' in text:\r\n start = text.find('versus') + 6\r\n end = start + text[start:].find('advo')\r\n return text[start:end]\r\n # print(start, end, '*'*40)\r\n # if text[end:end+8]!='advocate':\r\n # print(text[end:end+8], text)\r\n else:\r\n return np.nan\r\n except AttributeError:\r\n return np.nan\r\n\r\n\r\ndef extract_petitioner_advocate(text):\r\n advocates = [np.nan, np.nan]\r\n try:\r\n if 'advocate for the petitioner' in text:\r\n start = text.find('advocate for the petitioner')\r\n mid = start + 27 + text[start + 27:].find('advocate')\r\n advocates[0] = text[start + 32:mid]\r\n if 'advocate for the respondent' in text:\r\n respondent_adv = re.match(\"\"\"advocate for the r.*?:(?P.+?)(before|linked)\"\"\", text[mid:],\r\n flags=re.DOTALL)\r\n end = mid + text[mid:].find('before')\r\n if respondent_adv:\r\n advocates[1] = respondent_adv['name']\r\n # print(text[start+28:mid], text[mid+27:end])\r\n # print('-' * 40)\r\n # return (text[start+27:mid], text[mid+27:end])\r\n # print(advocates[1])\r\n return advocates\r\n except AttributeError:\r\n return advocates\r\n\r\n\r\ndef extract_judges(text, html_soup):\r\n try:\r\n if \"hon'ble\" in text or \"honourable\" in text:\r\n judges = re.findall(\"\"\"hon.*ble(.*\\s.*(?:justice|j\\.).*)\"\"\", text)\r\n if judges:\r\n return set(judge.replace(')', '')\r\n .replace('\\n', '')\r\n .replace('\\t', '')\r\n .strip() for judge in judges)\r\n bench = html_soup.find(\"div\", \"doc_bench\")\r\n if bench:\r\n return {bench.text.replace('Bench:', '').strip()}\r\n if 'judge' in text:\r\n judges = re.findall(\"\"\"\\((.*)\\).*\\s.*judge\"\"\", text)\r\n if judges:\r\n return set(judge.replace(')', '')\r\n .replace('\\n', '')\r\n .replace('\\t', '')\r\n .strip() for judge in judges)\r\n if 'j.' in text:\r\n judges = re.findall(\"\"\"\\((.*?j\\.)\"\"\", text) # [a-zA-Z ,]\r\n if judges:\r\n return set(judge.replace(')', '')\r\n .replace('\\n', '')\r\n .replace('\\t', '')\r\n .strip() for judge in judges)\r\n author = html_soup.find(\"div\", \"doc_author\")\r\n if author:\r\n return {author.text\r\n .replace(')', '')\r\n .replace('\\n', '')\r\n .replace('\\t', '')\r\n .strip()}\r\n return np.nan\r\n except AttributeError:\r\n return np.nan\r\n\r\n\r\ndef extract_banks(text, bank_names):\r\n banks_set = defaultdict(int)\r\n try:\r\n if \" bank\" in text:\r\n # return True\r\n for bank_name in bank_names:\r\n if bank_name in text:\r\n banks_set[bank_name] += 1\r\n return banks_set if banks_set else np.nan\r\n return np.nan\r\n except AttributeError:\r\n return np.nan\r\n\r\n\r\ndef extract_state(text):\r\n keywords = ['state', 'government', 'commissioner', 'national', 'india', 'indian', 'public', 'magistrate']\r\n try:\r\n return any(keyword in text for keyword in keywords)\r\n except AttributeError:\r\n return np.nan\r\n\r\n\r\ndef extract_citations(filename, text):\r\n try:\r\n citation_set = set(re.findall(\"\"\"/doc/(\\d*)\"\"\", text, flags=re.IGNORECASE))\r\n acts_set = set(re.findall(\"\"\"/doc/(\\d*).*(?:section|constitution|penal|act|code).*<\"\"\", text, flags=re.IGNORECASE))\r\n # print(citations)\r\n citation_set.discard('')\r\n # Every case cites itself for newer cases due to website structure. Comment below line if you do want that.\r\n citation_set.discard(filename[filename.rfind('/')+1:-4])\r\n citation_set = citation_set - acts_set\r\n # if not citations:\r\n # citations = np.nan\r\n # if not acts:\r\n # acts = np.nan\r\n return citation_set, acts_set\r\n except AttributeError:\r\n return np.nan\r\n\r\n\r\ndef match_business(text, list_of_company_names):\r\n \"\"\"one wall of petitioner name text to be compared to a large list of company names to find best match\"\"\"\r\n # max_score, max_company_name = 0, np.nan\r\n max_score_jw, max_company_name_jw = 0, np.nan\r\n for company in list_of_company_names:\r\n if company in text:\r\n return 1, company\r\n score = fuzz.token_set_ratio(text, company)\r\n # print(text, company, score, max_score)\r\n if score > 0.75:\r\n score_jw = jaro_winkler.normalized_similarity(text, company)\r\n if score_jw > max_score_jw:\r\n max_score_jw, max_company_name_jw = score_jw, company\r\n print('1 done', max_score_jw, max_company_name_jw)\r\n return max_score_jw, max_company_name_jw\r\n\r\n\r\ndef match_business_tf(text, list_of_company_names, tf):\r\n \"\"\"one wall of petitioner name text to be compared to a large list of company names to find best match\"\"\"\r\n max_overall_score, max_overall_company_name = -1, np.nan\r\n for company in list_of_company_names:\r\n max_company_score, max_company_name = -1, np.nan\r\n if company in text:\r\n return 1, company\r\n for company_word in company.split():\r\n max_word_similarity_score, max_word_similarity = -1, np.nan\r\n # if company_word in text:\r\n # max_word_similarity_score, max_word_similarity = 1, word\r\n for word in text.split():\r\n word_similarity_score = levenshtein.normalized_similarity(word, company_word)\r\n # print(word_similarity_score, word, company_word, '--', max_word_similarity_score, max_word_similarity, max_company_score, max_company_name, max_overall_score, max_overall_company_name)\r\n if word_similarity_score > max_word_similarity_score:\r\n max_word_similarity_score = word_similarity_score\r\n max_word_similarity = word\r\n # if max_word_similarity_score > 0.8:\r\n # print(\"------\", max_word_similarity, '--', tf[max_word_similarity], company_word, '--', max_word_similarity_score, max_word_similarity, max_company_score, max_company_name, max_overall_score, max_overall_company_name)\r\n max_company_score += (1 / tf[max_word_similarity]) * max_word_similarity_score\r\n max_company_name = company\r\n if max_company_score > max_overall_score:\r\n max_overall_score = max_company_score\r\n max_overall_company_name = max_company_name\r\n return max_overall_score, max_overall_company_name\r\n\r\n\r\ndef preprocess_company_names(list_of_companies, bank=False):\r\n list_of_companies = [\r\n company.lower().replace('private', '').replace('limited', '').replace('pvt', '').replace('ltd', '')\r\n if str(company) != 'nan' else np.nan for company in list_of_companies]\r\n # if bank:\r\n # list_of_companies = [company.replace('bank', ' ') for company in list_of_companies]\r\n list_of_companies = [company.replace(',', ' ').replace('.', ' ').replace('-', ' ').replace(\r\n '&', ' ').replace(':', ' ').replace('(', ' ').replace(')', ' ')\r\n if str(company) != 'nan' else np.nan for company in list_of_companies]\r\n list_of_companies = [company.strip() if str(company) != 'nan' else np.nan for company in list_of_companies]\r\n return list_of_companies\r\n\r\n\r\ndef tf_idf():\r\n pass\r\n","sub_path":"kanoon/ik_parsing.py","file_name":"ik_parsing.py","file_ext":"py","file_size_in_byte":9426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"115736261","text":"import cv2\nimport os\nimport numpy as np\nimport shutil\nimport sys\n#\n# heigth = 300\n# width = 600\n\n\ndef get_plates(root,STATE,imgEnd,DATE):\n\tlabelEnd = 'json'\n\twidth=600\n\theight=300\n\n\tori_label_path = root + \"/Labels/\" + STATE\n\timage_path = root + \"/usefulImgs/\" + STATE\n\tres_image_path = root + \"/plates/\" + STATE\n\n\tfor label_file in os.listdir(ori_label_path):\n\t\tif not label_file.endswith(labelEnd):\n\t\t\tcontinue\n\t\timage_file = label_file.replace(labelEnd, imgEnd)\n\t\tif not os.path.exists(os.path.join(image_path, image_file)):\n\t\t\tcontinue\n\t\timage = cv2.imread(os.path.join(image_path, image_file))\n\t\tprint(os.path.join(ori_label_path, label_file))\n\t\twith open(os.path.join(ori_label_path, label_file)) as f:\n\t\t\tregions = eval(f.read())['region']\n\t\t# print(regions)\n\t\tpst1 = []\n\n\t\tfor point in regions:\n\t\t\tx = point['x']\n\t\t\ty = point['y']\n\t\t\tpst1.append([x, y])\n\n\t\tpst1 = np.float32(pst1)\n\t\tpst2 = np.float32([[0, 0], [width, 0], [width, height], [0, height]])\n\t\tM = cv2.getPerspectiveTransform(pst1, pst2)\n\t\tdst = cv2.warpPerspective(image, M, (width, height))\n\t\tif not os.path.exists(res_image_path):\n\t\t\tos.makedirs(res_image_path)\n\t\tsave_path=os.path.join(res_image_path, STATE+\"@\"+DATE+\"@\" + image_file)\n\t\t#print(save_path)\n\t\tcv2.imwrite(save_path, dst)\n\n\t\t# cv2.imshow('image', image)\n\t\t# cv2.imshow('dst', dst)\n\t\t# cv2.waitKey(0)\n\n\n\n\n\n\n\n\n\n\n","sub_path":"LabelTool_plate/labelCheckTool_v1/get_plate_command.py","file_name":"get_plate_command.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"190511820","text":"from functools import reduce\nfrom sortedcontainers import SortedSet\nfrom .node import Node\n\n\nclass Knapsack:\n def __init__(self, items, capacity):\n self.items = sorted(items, key=lambda item: float(item.value) / item.cost, reverse=True)\n self.capacity = capacity\n self.candidates = SortedSet(key=lambda node: -(node.upper_bound * 2 ** 16 + node.item_index))\n\n def pack(self):\n self.make_initial_node()\n\n while True:\n node = self.select_node_to_grow()\n if node:\n self.grow(node, node.item_index + 1)\n else:\n return self.node_with_highest_value().items()\n\n def grow(self, node, next_index):\n next_item = self.items[next_index] if next_index < len(self.items) else None\n\n if node.positive_child_growable():\n if next_item and node.cost() + next_item.cost <= self.capacity:\n upper_bound = node.value() + next_item.value + self.upper_bound_beyond(next_index,\n capacity=self.capacity - node.cost() - next_item.cost)\n node.positive_child = Node(next_index, next_item, upper_bound, node)\n self.candidates.add(node.positive_child)\n else:\n node.cap_positive_child()\n elif node.negative_child_growable():\n if next_item:\n upper_bound = node.value() + self.upper_bound_beyond(next_index, capacity=self.capacity - node.cost())\n node.negative_child = Node(next_index, None, upper_bound, node)\n self.candidates.add(node.negative_child)\n self.candidates.remove(node)\n else:\n node.cap_negative_child()\n\n def upper_bound_beyond(self, prev_index, capacity=0):\n index = prev_index + 1\n\n if index >= len(self.items):\n return 0\n item = self.items[index]\n\n if item.cost > capacity:\n return float(item.value) * capacity / item.cost\n else:\n return item.value + self.upper_bound_beyond(index, capacity=capacity - item.cost)\n\n def make_initial_node(self):\n self.candidates.add(Node(-1, None, self.upper_bound_beyond(-1, capacity=self.capacity), None))\n\n def select_node_to_grow(self):\n hopeful_node = self.candidates[0]\n\n if not hopeful_node.leaf():\n return hopeful_node\n\n def node_with_highest_value(self):\n return reduce(\n lambda provisional, candidate: provisional if provisional.value() >= candidate.value() else candidate,\n self.candidates)\n","sub_path":"DiscreteOptmization/week2/knapsack/knapsack.py","file_name":"knapsack.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"452640414","text":"import data.tmdbsimple as tmdb\nimport locale, random, requests, json\n\n_apikey = 'fd7c9991afdb0eae88ab6617508de077'\n_config = \"https://api.themoviedb.org/3/configuration?api_key=\"+_apikey\ntmdb.API_KEY = _apikey\n_response = requests.request(\"GET\", _config, data={}, headers={'content-type': 'application/json'})\n_configJSon = json.loads(_response.text)\n\ndef getRecommendationsByID(id):\n\tmovie = tmdb.Movies(id)\n\tmovie.similar_movies(language=locale.getdefaultlocale()[0][0:2])\n\tif hasattr(movie, 'results'):\n\t\t_listlen = len(movie.results)\n\t\tif (_listlen == 0):\n\t\t\treturn {}\n\t\t# print(\"# de recomendaciones : \",_listlen)\n\t\treturn movie.results[random.randrange(0,_listlen)] # elijo una recomendacion al azar\n\telse:\n\t\treturn {}\n\ndef _getIdByTitle(title):\n\tsearch = tmdb.Search()\n\tsearch.movie(query=title)\n\tif hasattr(search, 'results') and len(search.results)>0:\n\t\treturn search.results[0]['id'] # devuelvo el primero\n\telse:\n\t\treturn -1\n\ndef _getTitleById(id):\n\tmovie = tmdb.Movies(id)\n\tmovie.results[0].title\n\ndef getRecommendationsByTitle(title):\n\tid_pelicula = _getIdByTitle(title)\n\tif(id_pelicula>0):\n\t\treturn {'recommended':getRecommendationsByID(id_pelicula), 'path': _configJSon['images']['secure_base_url']+_configJSon['images']['poster_sizes'][4]}\n","sub_path":"data/Tmdb.py","file_name":"Tmdb.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"2815304","text":"#!/usr/bin/env python3\n\ndef f(l):\n l.sort()\n return l[0]+l[1]+1\n\nt = int(input())\nfor i in range(t):\n _ = input()\n l = list(map(int,input().split()))\n print('Case #%d: %s'%((i+1), f(l)))\n\n","sub_path":"contests/ccpc20my/d_WA.py","file_name":"d_WA.py","file_ext":"py","file_size_in_byte":207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"532106245","text":"from django.shortcuts import render\nfrom random import randint\nfrom sql import sql_classes_and_functions as cf\n\ndef list_callable_functions():\n entireModuleList = []\n for key, value in globals().items():\n if callable(value) and value.__module__ == __name__:\n entireModuleList.append(key)\n return entireModuleList\n\ndef modulesList():#this list is used by views to automatically generate views!\n return cf.moduleListGen(list_callable_functions(), 'a', 0, 1)\n\ndef previousNext(qtype = None, low = 0, high = None, name='', module_path=''):#uses list of all functions to return previous and next modules in list\n modList = cf.moduleListGen(list_callable_functions(), qtype, low, high)\n modDict = {}\n count = -1\n for thing in modList:\n count+=1\n modDict.update({str(thing):count})\n print(modDict)\n place = modDict[name]\n current = modList[place]\n try:\n next_q = modList[place+1]\n except IndexError:\n next_q = modList[0]\n try:\n previous_q = modList[place-1]\n except IndexError:\n previous_q = modList[-1]\n return f\"/sql/basics/{previous_q}\", f\"/sql/basics/{next_q}\"\n\ndef module_path():\n return \"/sql/basics/\"\n'''\ndef e4_at_the_fairground_random():\n modList = moduleListGen(\"e4q\", 0, 3)\n return eval(f\"{modList[randint(0,len(modList)-1)]}()\")\n'''\n\n# Just me making sure everything works...\ndef test():\n test_inst = question()\n return test_inst.returnAll()\n\ndef a1qa_what_is_sql():\n true = [\n 'SQL stands for structured query language',\n 'SQL is used to manage data in relational database management systems',\n 'SQL is a domain specific programming language',\n 'SQL is not a general purpose programming language'\n 'RDBMS stands for relational database management system',\n 'SQL arguably consists of a data query language (DQL), a data definition language (DDL), a data control language (DCL) and a data manipulation language (DML)',\n 'SQL is a declarative language with proceedural elements',\n 'SQL includes a data query language (DQL)',\n 'SQL includes a data definition language (DDL)',\n 'SQL includes a data control language (DCL)',\n 'SQL includes a data manipulation language (DML)',\n ]\n false = [\n 'SQL stands for standard query language',\n 'SQL stands for structured query literal',\n 'SQL stands for structured question language',\n 'SQL is a general purpose programming language', \n 'SQL is an functional language',\n 'SQL is an object oriented language',\n 'SQL does not include a data query language',\n 'SQL does not include a data definition language (DDL)',\n 'SQL does not include a data control language (DCL)',\n 'SQL does not include a data manipulation language (DML)',\n ]\n a1qa = cf.trueFalse(true, false)\n a1qa.previousQ, a1qa.nextQ = previousNext(\"a1q\", 0, 3, cf.currentFuncName(), module_path())\n a1qa.questionBase = f'Which of the following statements about SQL is {a1qa.tf}:'\n a1qa.weblink = 'https://en.wikipedia.org/wiki/SQL'\n a1qa.workOn = 'What Structured Query Language is'\n return a1qa.returnAll()\n\ndef a1qb_what_sql_does():\n true = [\n 'SQL can execute queries against a database',\n 'SQL can retrieve data from a database',\n 'SQL can insert records in a database',\n 'SQL can update records in a database',\n 'SQL can delete records from a database',\n 'SQL can create new databases',\n 'SQL can create new tables in a database',\n 'SQL can create stored procedures in a database',\n 'SQL can create views in a database',\n 'SQL can set permissions on tables, procedures, and views',\n ]\n false = [\n 'SQL can be used to propogate database information to a web page',\n 'SQL can take data from a list in another language and insert it into a database',\n 'SQL cannot execute queries against a database',\n 'SQL cannot retrieve data from a database',\n 'SQL cannot insert records in a database',\n 'SQL cannot update records in a database',\n 'SQL cannot delete records from a database',\n 'SQL cannot create new databases',\n 'SQL cannot create new tables in a database',\n 'SQL cannot create stored procedures in a database',\n 'SQL cannot create views in a database',\n 'SQL cannot set permissions on tables, procedures, and views', ]\n q = cf.trueFalse(true, false)\n q.previousQ, q.nextQ = previousNext(\"a1q\", 0, 3, cf.currentFuncName(), module_path())\n q.getAnswersAndIndicators()\n q.questionBase = f'Which of the following statements about SQL is {q.tf}:'\n q.weblink = 'https://www.w3schools.com/sql/sql_intro.asp'\n q.workOn = \"What SQL can do\"\n return q.returnAll()\n\ndef a1qc_database_brands():\n true = [\n 'MySQL',\n 'Microsoft / Sybase',\n 'MonetDB',\n 'Oracle',\n 'PostgreSQL',\n 'SAP HANA',\n 'MongoDB',\n 'IBM DB2'\n ]\n false = [\n 'PythonDB',\n 'JavaDB',\n 'JavaScriptDB',\n 'CythonDB',\n 'PythonDB',\n 'GoDB',\n 'FortranDB'\n ]\n q = cf.trueFalse(true, false)\n q.previousQ, q.nextQ = previousNext(\"a1q\", 0, 3, cf.currentFuncName())\n q.getAnswersAndIndicators()\n areNot = \"is\" if q.tf == \"true\" else \"is not\"\n q.questionBase = f'Which of the following {areNot} a relational database which uses SQL:'\n q.weblink = 'https://www.trustradius.com/relational-databases'\n q.workOn = \"Popular relational databases\"\n return q.returnAll()\n\ndef a1qd_database_entities():\n true = [\n 'a database can contain one or many tables',\n 'a table can contain one or more records or rows',\n 'a table can contain one or more fields or columns',\n 'a record is a horizontal entity',\n 'a field is a vertical entitiy',\n 'each field in a table is represented by a column',\n 'each record in a table is represented by a row', \n 'each field in a table has a name',\n 'each table in a database has a name',\n 'a record is a group of related fields',\n 'fields contain defined types of data '\n ]\n false = [\n 'a table can contain one or more databases',\n 'a row can contain one or more tables',\n 'a field can contain one or more tables',\n 'a field can contain one or more records',\n 'a record is a vertical entity',\n 'a field is a horizontal entitiy',\n 'each field in a table is represented by a row',\n 'each record in a table is represented by a column', \n 'each record in a table has a name',\n 'tables in a database are never named',\n 'a field is a group of related tables',\n 'field data type is never specified'\n ]\n q = cf.trueFalse(true, false)\n q.previousQ, q.nextQ = previousNext(\"a1q\", 0, 3, cf.currentFuncName())\n q.getAnswersAndIndicators()\n q.questionBase = f'Which of the following statements are {q.tf}:'\n q.weblink = 'https://www.cengage.com/school/corpview/RegularFeatures/DatabaseTutorial/db_elements/db_elements2.htm'\n q.workOn = \"Database entities\"\n return q.returnAll()\n\ndef a2qa_statements():\n true = [\n 'not all database systems require a semicolon at the end of each SQL statement',\n 'semicolons are commonly used to show the end of an SQL statement',\n 'SQL keywords are not case sensitive',\n 'SQL keywords are commonly written in upper-case',\n 'SQL is not a case sensitive language',\n 'table and field names are commonly written in lower-case',\n 'two or more SQL statements can be executed in the same call to the server if seperated by semicolons in systems that allow it',\n 'most actions performed on databases are done with SQL statements',\n 'SQL is case insensitive, but case is used to make it more readable',\n ]\n false = [\n 'all database systems require a semicolon at the end of each SQL statement',\n 'SQL keywords are case sensitive',\n 'SQL keywords are never written in upper-case',\n 'SQL keywords are written in lower-case',\n 'SQL is a case sensitive language',\n 'table and field names are commonly written in upper-case',\n 'table and field names are never written in lower-case',\n 'two or more SQL statements can be never be executed in the same call to the server',\n 'full stops are commonly used to show the end of an SQL statement',\n 'parenthesis are commonly used to show the end of an SQL statement',\n 'commas are commonly used to show the end of an SQL statement',\n 'dollar signs are commonly used to show the end of an SQL statement'\n 'most actions performed on databases are done using python',\n ]\n q = cf.trueFalse(true, false)\n q.previousQ, q.nextQ = previousNext(\"a2q\", 0, 3, cf.currentFuncName())\n q.getAnswersAndIndicators()\n q.questionBase = f'Which of the following statements are {q.tf}:'\n q.weblink = 'https://www.w3schools.com/sql/sql_syntax.asp'\n q.workOn = \"General rules for SQL statements\"\n return q.returnAll()\n\ndef a2qb_commands_starting_statements():\n true = ['SELECT','UPDATE','DELETE','INSERT','CREATE','ALTER ','DROP',]\n false = ['WHERE','BETWEEN','AND','ALL','BETWEEN','CHECK','CONSTRAINT','DISTINCT','EXISTS','FROM','LIKE','NOT','OR','TABLE','VALUES','WHERE']\n q = cf.trueFalseCode(true, false)\n q.previousQ, q.nextQ = previousNext(\"a2q\", 0, 3, cf.currentFuncName())\n q.getAnswersAndIndicators()\n areNot = \"can\" if q.tf == \"true\" else \"can't\"\n q.questionBase = f'Which of the following commands {areNot} be used at the start of an SQL statement:'\n q.weblink = 'https://www.w3schools.com/SQl/sql_ref_keywords.asp'\n q.workOn = \"Commands which start SQL statements\"\n return q.returnAll()\n\n'''\ndef a2qb_commands_starting_statements():\n previousQ, nextQ = previousNext(\"a2q\", 0, 3, currentFuncName())\n diagram, piclink = None, None\n true = ['SELECT','UPDATE','DELETE','INSERT','CREATE','ALTER ','DROP',]\n false = ['WHERE','BETWEEN','AND','ALL','BETWEEN','CHECK','CONSTRAINT','DISTINCT','EXISTS','FROM','LIKE','NOT','OR','TABLE','VALUES','WHERE']\n code, hint = None, None\n answercode, a1code, a2code, a3code, a4code, q, num = true_false_options_mangle(true, false)\n a1ci, a2ci, a3ci, a4ci = correct_incorrect_sequence(num)\n areNot = \"can\" if q == \"true\" else \"can't\"\n questionBase = f'Which of the following commands {areNot} be used at the start of an SQL statement:'\n answer, a1, a2, a3, a4 = None, None, None, None, None\n help, weblink, video = None, 'https://www.w3schools.com/SQl/sql_ref_keywords.asp', None\n workOn = \"Commands which start SQL statements\"\n return (previousQ, nextQ, diagram, piclink, questionBase, code, hint, weblink, video, a1, a1code, a2, a2code, a3, a3code, a4, a4code, answer, answercode, a1ci, a2ci, a3ci, a4ci, workOn)\n'''\n\ndef a2qc_create_statements():\n names = ['duck', 'stool', 'door','cup', 'tennis', 'pool','monkey','chair','orange','fruit','trampoline','beef','employees','customers','shoes','pants','troopers','rioters','clocks']\n data_types = ['INT','TEXT','DATE','TIME',f'CHAR({randint(1,20)})','REAL','DEC', 'BOOLEAN', f'BINARY({randint(1,16)})']\n entities = ['DATABASE', 'TABLE',]\n choice = randint(0, len(entities)-1)\n entity = entities[choice]\n name = names[randint(0, len(names)-1)]\n answer = f'CREATE {entity} {name}'\n data = '('\n for i in range(randint(1,4)):\n data += f\"{names[randint(0, len(names)-1)]} {data_types[randint(0, len(data_types)-1)]}, \"\n data = data[:-2] + ')'\n if choice == 0:\n a,b,c = f'CREATE {name} {entity};', f'CREATE {entity} {name} {data};', f'CREATE {entity};'\n answer += ';'\n else:\n answer += data + ';'\n a,b,c = f'CREATE {name} {entity};', f'CREATE {entity} {data} {name};', f'CREATE {entity} {data};'\n q = cf.selectCorrectCode(answer, [a,b,c])\n q.previousQ, q.nextQ = previousNext(\"a2q\", 0, 3, cf.currentFuncName())\n q.getAnswersAndIndicators()\n q.questionBase = f'Which of the following statements for creating a {entity} named {name} is valid:'\n q.weblink = 'https://www.w3schools.com/SQL/sql_ref_create.asp'\n q.workOn = \"statements using CREATE\"\n return q.returnAll()\n\n\n\n\n\"\"\"\nCommon commands\n CREATE TABLE - creates a new table \n CREATE DATABASE - creates a new database\n CREATE INDEX - creates an index (search key)\n\n SELECT - extracts data from a database\n\n UPDATE - updates data in a database\n INSERT INTO - inserts new data into a database\n ALTER DATABASE - modifies a database\n ALTER TABLE - modifies a table\n\n DELETE - deletes data from a database\n DROP TABLE - deletes a table\n DROP INDEX - deletes an index\n\nSyntax\n statements\n patterns\n examples of each keywords\n create\n read\n update\n delete\n\"\"\"","sub_path":"sql/a_basics/a_basics_logic.py","file_name":"a_basics_logic.py","file_ext":"py","file_size_in_byte":13034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"422021840","text":"# This is the client\n\nimport socket\nfrom socket import * # Import socket module\nimport random\nimport string\nimport time\nfrom flask_socketio import SocketIO, Namespace, emit, join_room, leave_room, \\\n close_room, rooms, disconnect\n\n\n# Server variables\nserverName = ''\ncombo = string.ascii_letters + string.digits\n\n\ndef printfunction(x):\n print(x)\n\ndef random_string_generator(str_size, allowed_chars):\n \"\"\"\n Generates a random number\n Input : str_size, allowed_chars\n Returns : chars of type String()\n \"\"\"\n return ''.join(random.choice(allowed_chars) for x in range(str_size))\n\n\ndef encode():\n \"\"\"\n Encodes input \n \"\"\"\n\n\ndef create_random_character_plus_input(user_input, combo_in):\n \"\"\"\n Create random character\n \"\"\"\n random_string = random_string_generator(30, combo_in)\n sentence = user_input + \"#\" + random_string\n return sentence\n\n\ndef count_time_decode(from_server):\n \"\"\"\n Decodes message\n gets time\n gets String \n\n Return Dictionary of count and time \n \"\"\"\n from_server_decoded = from_server.decode('utf-8')\n string = from_server_decoded.split(\"#\")\n count = string[0]\n time = string[1]\n count_time_dict = {'count': count, 'time': time}\n return count_time_dict\n\n\n# Port 1\n #try:\ndef connect_12003():\n serverPort = 12003\n clientSocket = socket(AF_INET, SOCK_STREAM)\n clientSocket.connect((serverName, serverPort))\n while True:\n from_server_1 = clientSocket.recv(1024)\n clientSocket.sendall(create_random_character_plus_input(\n user_input, combo).encode('utf-8'))\n dict_ct_1 = count_time_decode(from_server_1)\n print(dict_ct_1)\n \n #except ValueError:\n #print('Connection Error')\n # Port 2\n #try:\ndef connect_12004():\n serverPort2 = 12004\n clientSocket2 = socket(AF_INET, SOCK_STREAM)\n clientSocket2.connect((serverName, serverPort2))\n while True:\n from_server_1 = clientSocket2.recv(1024)\n clientSocket2.sendall(create_random_character_plus_input(\n user_input, combo).encode('utf-8'))\n dict_ct_1 = count_time_decode(from_server_1)\n print(dict_ct_1)\n # Port 3\n #except ValueError:\n #print('Connection Error')\n #try:\n #try:\ndef connect_12005():\n serverPort3 = 12005\n clientSocket3 = socket(AF_INET, SOCK_STREAM)\n clientSocket3.connect((serverName, serverPort3))\n while True:\n from_server_1 = clientSocket3.recv(1024)\n user_input=input('Input character (letter or digit): ')\n clientSocket3.sendall(create_random_character_plus_input(\n user_input, combo).encode('utf-8'))\n dict_ct_1 = count_time_decode(from_server_1)\n print(dict_ct_1)\n #except ValueError:\n #print('Connection Error')\n\n \n\n \n \n\n\ndef start():\n while True:\n print('olo')\n from_server_1 = connect_12003().recv(1024)\n from_server_2 = connect_12004().recv(1024)\n from_server_3 = connect_12005().recv(1024)\n\n connect_12003().sendall(create_random_character_plus_input(\n user_input, combo).encode('utf-8'))\n connect_12004().sendall(create_random_character_plus_input(\n user_input, combo).encode('utf-8'))\n connect_12005().sendall(create_random_character_plus_input(\n user_input, combo).encode('utf-8'))\n \n dict_ct_1 = count_time_decode(from_server_1)\n dict_ct_2 = count_time_decode(from_server_2)\n dict_ct_3 = count_time_decode(from_server_3)\n\n total_count = int(dict_ct_1['count']) + \\\n int(dict_ct_2['count']) + int(dict_ct_3['count'])\n\n dict_server_info = {'server1':dict_ct_1,'server2':dict_ct_2,'server3':dict_ct_3,'total_count':total_count}\n\n print(dict_server_info)\n \n","sub_path":"app/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"254190909","text":"from utils.database import io, config as cfg\nimport pandas as pd\nfrom sqlalchemy import create_engine\nfrom dateutil.relativedelta import relativedelta\nimport datetime as dt\nfrom utils.database.models.base_private import FundNvDataSource\n\nsources = {\n 0: \"000001\",\n 1: \"020008\",\n 2: \"020004\",\n 3: \"020001\",\n 4: \"020002\",\n 5: \"020003\",\n 6: \"04\",\n 7: \"03\",\n 8: \"05\",\n 9: \"05\",\n 10: \"05\",\n 11: None,\n 12: \"020005\",\n 13: \"020007\",\n}\n\nsources_priority = {\n \"000001\": 10,\n \"020008\": 8,\n \"020004\": 8,\n \"020001\": 8,\n \"020002\": 8,\n \"020003\": 8,\n \"04\": 8,\n \"03\": 8,\n \"05\": 8,\n \"05\": 8,\n \"05\": 8,\n \"020005\": 8,\n \"020007\": 8,\n}\n\neg = cfg.load_engine()[\"2Gb\"]\neg_cfg = create_engine(\"mysql+pymysql://root:smyt0317@182.254.128.241:4171/config_private?charset=utf8\")\neg_crawl = create_engine(\"mysql+pymysql://root:smyt0317@182.254.128.241:4171/crawl_private?charset=utf8\")\n\n\ndef check_need_mod(x):\n return int(x > 30) if x is not None else 0\n\n\ndef update_nv_data_source(fids):\n for fid in fids:\n print(fid)\n sql_nvsrc = \"SELECT data_source as source_id, statistic_date, nav, added_nav, IFNULL(swanav, swanav1) as swanav FROM fund_nv_data_source WHERE fund_id='{fid}'\".format(\n fid=fid\n )\n sql_nv = \"SELECT statistic_date, nav, added_nav, swanav FROM fund_nv_data_standard WHERE fund_id='{fid}'\".format(\n fid=fid\n )\n df_nvsrc = pd.read_sql(sql_nvsrc, eg)\n df_nv = pd.read_sql(sql_nv, eg)\n\n a = df_nv.groupby([\"statistic_date\"]).last() # 标准表净值数据\n b = df_nvsrc.groupby([\"statistic_date\", \"source_id\"]).last() # 多源表净值数据\n\n cols_cp = [\"nav\", \"added_nav\"]\n\n # 去除只存在于nv_std中, 但不存在于nv_src表中的记录\n if len(a) > 0 and len(b) != 0:\n idx_dates = list(set(a.index).intersection(b.index.levels[0]))\n a = a.loc[idx_dates]\n\n # Cond.1 一个日期下所有源 与 标准净值表 全部不相等,\n # 需要去除只存在于fund_nv_data_source表而不存在于fund_nv_data_standard表中的数据\n all_date_not_eql = (~a[cols_cp].eq(b.loc[idx_dates][cols_cp]).all(axis=1)).all(level=0)\n\n # Cond.2 一个日期下存在某个源的净值 与 标准净值表不相等\n all_date_src_eql = a[cols_cp].eq(b[cols_cp]).all(level=[0, 1]).all(axis=1)\n\n # Cond.1\n # 将符合Cond.1的标准净值表数据存入 y_fund_nv(采集库.云通源净值表)\n # pandas.Series.reset_index方法在windows和linux上可能接口不一致, 该代码在linux下运行报错;\n result_all_not_eql = a[all_date_not_eql].reset_index()\n result_all_not_eql[\"fund_id\"] = fid\n result_all_not_eql[\"source_id\"] = 0\n result_all_not_eql[\"is_used\"] = 1\n # result_all_not_eql.columns = [\"statistic_date\", \"nav\", \"added_nav\", \"swanav\", \"fund_id\", \"source_id\", \"is_used\"]\n\n result_smyt = result_all_not_eql[[\"statistic_date\", \"nav\", \"added_nav\", \"swanav\", \"fund_id\"]]\n result_smyt.columns = [\"statistic_date\", \"nav\", \"added_nav\", \"adjusted_nav\", \"fund_id\"]\n\n # Cond.2\n result_nv_src = df_nvsrc.copy()\n result_nv_src[\"is_used\"] = all_date_src_eql.apply(lambda x: int(x)).tolist()\n result_nv_src[\"fund_id\"] = fid\n\n result = result_nv_src.append(result_all_not_eql)\n result[\"source_id\"] = result[\"source_id\"].apply(lambda x: sources.get(x))\n result.dropna(subset=[\"source_id\"])\n # 标识可能需要除100的记录(以nav > 30界定)\n result[\"need_mod\"] = result[\"nav\"].apply(check_need_mod)\n result.columns = ['added_nav', 'fund_id', 'is_used', 'nav', 'source_id', 'statistic_date', 'adjusted_nav', 'need_mod']\n\n result_sync = result[[\"fund_id\", \"source_id\"]].drop_duplicates()\n result_sync.columns = [\"pk\", \"source_id\"]\n result_sync[\"target_table\"] = \"fund_nv_data_standard\"\n result_sync[\"priority\"] = result_sync[\"source_id\"].apply(lambda x: sources_priority.get(x, 0))\n\n io.to_sql(\"y_fund_nv\", eg_crawl, result_smyt)\n io.to_sql(FundNvDataSource.__tablename__, eg, result)\n io.to_sql(\"sync_source\", eg_cfg, result_sync)\n\n elif len(a) > 0 and len(b) == 0: # 处理只存在fund_nv_data_standard但不存在于fund_nv_data_source的数据\n print(\"NO SOURCE DATA FOUND: {fid}\".format(fid=fid))\n result_smyt = a.reset_index()\n result_smyt.columns = [\"statistic_date\", \"nav\", \"added_nav\", \"adjusted_nav\"]\n result_smyt[\"fund_id\"] = fid\n\n result_sync = result_smyt[[\"fund_id\"]].drop_duplicates()\n result_sync.columns = [\"pk\"]\n result_sync[\"target_table\"] = \"fund_nv_data_standard\"\n result_sync[\"source_id\"] = \"000001\"\n result_sync[\"priority\"] = 10\n result_sync[\"is_used\"] = 1\n\n result = result_smyt.copy()\n result[\"is_used\"] = 1\n result[\"need_mod\"] = result[\"nav\"].apply(check_need_mod)\n\n io.to_sql(\"y_fund_nv\", eg_crawl, result_smyt)\n io.to_sql(FundNvDataSource.__tablename__, eg, result)\n io.to_sql(\"sync_source\", eg_cfg, result_sync)\n\n\ndef main():\n now = dt.datetime.now()\n t1 = now.strftime(\"%Y%m%d%H%M%S\")\n t0 = (now - relativedelta(hours=1, minutes=10)).strftime(\"%Y%m%d%H%M%S\")\n fids = eg.execute(\"SELECT DISTINCT fund_id FROM fund_nv_data_standard WHERE update_time BETWEEN '{t0}' AND '{t1}'\".format(t0=t0, t1=t1)).fetchall()\n fids = [x[0] for x in fids]\n update_nv_data_source(fids)\n\n\ndef test():\n import sys\n start, end = sys.argv[1], sys.argv[2]\n fids = eg.execute(\"SELECT DISTINCT fund_id FROM fund_nv_data_standard\").fetchall()\n fids = [x[0] for x in fids]\n tmp = fids[int(start):int(end)]\n update_nv_data_source(tmp)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"SCRIPT/OTHER/configinit/compare_nv.py","file_name":"compare_nv.py","file_ext":"py","file_size_in_byte":6042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"474697477","text":"import time\r\n\r\nwith open('Basic/Files/Poem.txt', mode = 'r', encoding='utf-8') as f:\r\n try:\r\n for line in f:\r\n print(line, end=' ')\r\n time.sleep(0.5)\r\n finally:\r\n if f:\r\n f.close()\r\n print()","sub_path":"Basic/Files/FileRead.py","file_name":"FileRead.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"608502503","text":"# Task 3 GeekBrains Python Fast Start\n\nimport os\nimport sys\nimport psutil\n\n\ndef get_info_about_system():\n # get info about system\n cwd = os.getcwd()\n os_name = os.uname()\n code_file_system = sys.getfilesystemencoding()\n login_of_user = os.getlogin()\n count_of_cpu = psutil.cpu_count()\n\n print('Имя текущей директории - {}'.format(cwd))\n print('Платформа (ОС) - {}'.format(os_name))\n print('Кодировка файловой системы - {}'.format(code_file_system))\n print('Логин пользователя - {}'.format(login_of_user))\n print('Количество CPU - {}'.format(count_of_cpu))\n\n\ndef dupl_cwd_files():\n # duplicate files in cwd\n cwd_files = os.listdir()\n\n for cwd_file in cwd_files:\n print(cwd_file)\n\n\ndef choose_work_task():\n # Choose work task\n choosed_task = 1\n\n print('Выберите задачу:')\n print('Вывести список файлов в текущей папке (1)')\n print('Вывести информацию о системе (2)')\n print('Вывести список текущих запущенных процессов (3)')\n print('Дублировать файлы в текущей директории (4)')\n print('Выйти из программы (0)')\n\n while choosed_task != 0:\n choosed_task = int(input('?'))\n\n if choosed_task == 1:\n print(os.listdir())\n elif choosed_task == 2:\n get_info_about_system()\n elif choosed_task == 3:\n print(psutil.pids())\n elif choosed_task == 4:\n dupl_cwd_files()\n else:\n pass\n\n\ndef task_four():\n # Task 4\n choose_work_task()\n\n\ndef main():\n # Initial function\n task_four()\n\n\nmain()\n","sub_path":"GeepyFastStart_3.py","file_name":"GeepyFastStart_3.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"79016004","text":"import pytest\n\nfrom time import sleep\nfrom threading import BrokenBarrierError\nfrom contextlib import contextmanager\n\nfrom easypy.concurrency import MultiObject, MultiException\nfrom easypy.concurrency import SynchronizationCoordinator, SYNC\n\n\ndef verify_concurrent_order(executed, *expected):\n look_at_index = 0\n for expected_group in expected:\n executed_group = set(executed[look_at_index:look_at_index + len(expected_group)])\n assert executed_group == expected_group, 'wrong execution order'\n look_at_index += len(executed_group)\n assert look_at_index == len(executed), 'executed list is shorted than expected'\n\n\ndef test_synchronization_coordinator_wait_for_everyone():\n mo = MultiObject(range(3))\n\n sync = SynchronizationCoordinator(len(mo))\n executed = []\n\n def foo(i):\n def execute(caption):\n executed.append((i, caption))\n\n sleep(i / 10)\n execute('after sleep')\n sync.wait_for_everyone()\n execute('after wait')\n sync.wait_for_everyone()\n\n sleep(i / 10)\n execute('after sleep 2')\n sync.wait_for_everyone()\n execute('after wait 2')\n\n mo.call(foo)\n verify_concurrent_order(\n executed,\n {(i, 'after sleep') for i in range(3)},\n {(i, 'after wait') for i in range(3)},\n {(i, 'after sleep 2') for i in range(3)},\n {(i, 'after wait 2') for i in range(3)})\n\n\ndef test_synchronization_coordinator_collect_and_call_once():\n mo = MultiObject(range(3))\n\n sync = SynchronizationCoordinator(len(mo))\n executed = []\n\n def foo(i):\n def execute(caption):\n executed.append((i, caption))\n\n sleep(i / 10)\n\n def func_to_call_once(param):\n executed.append('params = %s' % sorted(param))\n return sum(param)\n result = sync.collect_and_call_once(i + 1, func_to_call_once)\n execute('result is %s' % result)\n\n assert sync.collect_and_call_once(i, len) == 3, 'parameters remain from previous call'\n\n mo.call(foo)\n verify_concurrent_order(\n executed,\n {'params = [1, 2, 3]'},\n {(i, 'result is 6') for i in range(3)})\n\n\ndef test_synchronization_coordinator_abandon():\n mo = MultiObject(range(3))\n\n sync = SynchronizationCoordinator(len(mo))\n executed = []\n\n def foo(i):\n def execute(caption):\n executed.append((i, caption))\n\n sync.wait_for_everyone()\n execute('after wait 1')\n\n if i == 2:\n sync.abandon()\n return\n # Only two waiters should reach here\n sync.wait_for_everyone()\n execute('after wait 2')\n\n # Even without explicit call to abandon, sync should only wait for two waiters\n sync.wait_for_everyone()\n execute('after wait 3')\n\n mo.call(foo)\n verify_concurrent_order(\n executed,\n {(i, 'after wait 1') for i in range(3)},\n {(i, 'after wait 2') for i in range(2)},\n {(i, 'after wait 3') for i in range(2)})\n\n\ndef test_synchronization_coordinator_exception_in_collect_and_call_once():\n mo = MultiObject(range(3))\n\n sync = SynchronizationCoordinator(len(mo))\n times_called = 0\n\n class MyException(Exception):\n pass\n\n def foo(i):\n def func_to_call_once(_):\n nonlocal times_called\n times_called += 1\n raise MyException\n\n with pytest.raises(MyException):\n sync.collect_and_call_once(i, func_to_call_once)\n\n assert sync.collect_and_call_once(i + 1, sum) == 6\n\n mo.call(foo)\n assert times_called == 1, 'collect_and_call_once with exception called the function more than once'\n\n\ndef test_synchronization_coordinator_with_multiobject():\n mo = MultiObject(range(3))\n\n executed = []\n\n def foo(i, _sync=SYNC):\n def execute(caption):\n executed.append((i, caption))\n\n sleep(i / 10)\n _sync.wait_for_everyone()\n execute('after wait')\n\n def func_to_call_once(param):\n executed.append('params = %s' % sorted(param))\n return sum(param)\n result = _sync.collect_and_call_once(i + 1, func_to_call_once)\n execute('result is %s' % result)\n\n foo(10)\n assert executed == [\n (10, 'after wait'),\n 'params = [11]',\n (10, 'result is 11')]\n executed.clear()\n\n mo.call(foo)\n verify_concurrent_order(\n executed,\n {(i, 'after wait') for i in range(3)},\n {'params = [1, 2, 3]'},\n {(i, 'result is 6') for i in range(3)})\n\n\ndef test_synchronization_coordinator_with_multiobject_exception():\n mo = MultiObject(range(3))\n\n executed = []\n\n class MyException(Exception):\n pass\n\n def foo(i, _sync=SYNC):\n def execute(caption):\n executed.append((i, caption))\n\n _sync.wait_for_everyone()\n execute('after wait')\n\n if i == 2:\n raise MyException\n\n _sync.wait_for_everyone()\n execute('after wait/abandon')\n\n with pytest.raises(MultiException) as exc:\n mo.call(foo)\n assert exc.value.count == 1\n assert exc.value.common_type is MyException\n\n verify_concurrent_order(\n executed,\n {(i, 'after wait') for i in range(3)},\n {(i, 'after wait/abandon') for i in range(2)})\n\n\ndef test_synchronization_coordinator_with_multiobject_early_return():\n mo = MultiObject(range(3))\n\n executed = []\n\n def foo(i, _sync=SYNC):\n def execute(caption):\n executed.append((i, caption))\n\n _sync.wait_for_everyone()\n execute('after wait')\n\n if i == 2:\n return\n\n _sync.wait_for_everyone()\n execute('after wait/abandon')\n\n mo.call(foo)\n\n verify_concurrent_order(\n executed,\n {(i, 'after wait') for i in range(3)},\n {(i, 'after wait/abandon') for i in range(2)})\n\n\ndef test_synchronization_coordinator_with_multiobject_method():\n class Foo:\n def __init__(self, i):\n self.i = i\n\n def foo(self, _sync=SYNC):\n return (self.i, _sync.collect_and_call_once(self.i, lambda i_values: sorted(i_values)))\n\n mo = MultiObject(Foo(i) for i in range(3))\n\n assert mo.foo().L == [\n (0, [0, 1, 2]),\n (1, [0, 1, 2]),\n (2, [0, 1, 2])]\n\n\ndef test_synchronization_coordinator_timeout():\n mo = MultiObject(range(3))\n\n def foo(i, _sync=SYNC):\n sleep(i / 10)\n _sync.wait_for_everyone(timeout=0.1)\n\n with pytest.raises(MultiException) as exc:\n mo.call(foo)\n assert exc.value.count == len(mo)\n assert exc.value.common_type is BrokenBarrierError\n\n\ndef test_synchronization_coordinator_with_context_manager():\n mo = MultiObject(range(3))\n\n executed = []\n\n @contextmanager\n def foo(i, _sync=SYNC):\n def execute(caption):\n executed.append((i, caption))\n\n sleep(i / 10)\n execute('after sleep')\n _sync.wait_for_everyone()\n execute('before yield')\n yield\n _sync.wait_for_everyone()\n execute('after yield')\n\n with mo.call(foo):\n executed.append('with body')\n\n verify_concurrent_order(\n executed,\n {(i, 'after sleep') for i in range(3)},\n {(i, 'before yield') for i in range(3)},\n {'with body'},\n {(i, 'after yield') for i in range(3)})\n","sub_path":"tests/test_synchronization_coordinator.py","file_name":"test_synchronization_coordinator.py","file_ext":"py","file_size_in_byte":7332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"612182298","text":"import re\n\nfrom django.conf import settings\nfrom django.http import HttpRequest\n\nfrom django_www import cache_manager, db_manager\nfrom utils import exceptions, messages, misc\n\n\ndef create_url(origin_url: str, scheme: str) -> str:\n match = re.search(f'^http(s)?:\\/\\/(www.)?[a-zA-Z0-9.\\/%-@_&=#]*', origin_url)\n\n if not match or len(origin_url) > 255:\n raise exceptions.ParseShortenUrlException(messages.ERROR__INVALID_PARAMS)\n\n while True:\n code = misc.random_string(5)\n url = cache_manager.get_original_url(code)\n if not url:\n break\n\n new_url = db_manager.create({'origin_url': origin_url, 'shorten_url': f'{scheme}://{settings.DOMAIN}/{code}', 'code': f'{code}'})\n cache_manager.get_original_url.update(code, result=new_url)\n return new_url.shorten_url\n\n\ndef get_original_url(shorten_url: str) -> str:\n base_validator(shorten_url)\n s = shorten_url.split(f'{settings.DOMAIN}/')\n code = s[1]\n\n if len(code) > 5 and code[-1] == '/':\n code = code[:6]\n\n url = cache_manager.get_original_url(code)\n\n if not url:\n cache_manager.get_original_url.clear(code)\n return ''\n\n return url.get('origin_url')\n\n\ndef base_validator(url: str) -> None:\n domain = ''\n\n for ch in settings.DOMAIN:\n if ch == '.':\n domain += '\\\\'\n domain += ch\n\n pattern = '^http(s)?:\\/\\/%s\\/[a-zA-Z0-9]{5}\\/?$' % domain\n match = re.search(pattern, url)\n\n if not match:\n raise exceptions.ParseShortenUrlException(messages.ERROR__INVALID_CODE)\n","sub_path":"django_www/django_www/services/shorten_url_service.py","file_name":"shorten_url_service.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"598541683","text":"\"\"\" Procedure to take an mod 2D plot of IV's for a SQUID. By default, assumes SQUID -40 uA to 40 uA sweep (0.5 uA step) and mod -100 uA to 100 uA sweep (4 uA step), both over a 2kOhm bias resistor. Can change these values when prompted. \"\"\"\n\nfrom IPython import display\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time, os\nfrom . import squidIV\nfrom ..Utilities import plotting\nfrom .save import Measurement\n\n\nclass Mod2D(Measurement):\n def __init__(self, instruments=None, squidout=None, squidin=None, modout=None, rate=900):\n '''\n Example: Mod2D({'daq': daq, 'preamp': preamp}, 'ao0','ai0','ao1', rate=900).\n To make an empty object, then just call Mod2D(). You can do this if you want to plot previously collected data.\n '''\n\n self.filename = ''\n self.notes = ''\n\n self.IV = squidIV.SquidIV(instruments, squidout, squidin, modout, rate=rate)\n\n self.IV.Rbias = 2e3 # Ohm # 1k cold bias resistors on the SQUID testing PCB\n self.IV.Rbias_mod = 2e3 # Ohm # 1k cold bias resistors on the SQUID testing PCB\n self.IV.Irampspan = 120e-6 # A # Will sweep from -Irampspan/2 to +Irampspan/2\n self.IV.Irampstep = 0.5e-6 # A # Step size\n\n self.Imodspan = 200e-6\n self.Imodstep = 4e-6\n\n self.IV.calc_ramp()\n self.calc_ramp()\n\n display.clear_output()\n\n def __getstate__(self):\n self.save_dict = {\"timestamp\": self.timestamp,\n \"IV\": self.IV,\n \"Imodspan\": self.Imodspan,\n \"Imodstep\": self.Imodstep,\n \"V\": self.V,\n \"notes\": self.notes,\n \"time\": self.time,\n \"Imod\": self.Imod}\n return self.save_dict\n\n def calc_ramp(self):\n self.numpts = int(self.Imodspan/self.Imodstep)\n self.Imod = np.linspace(-self.Imodspan/2, self.Imodspan/2, self.numpts) # Squid current\n self.V = np.full((self.numpts, self.IVnumpts), np.nan)\n\n def do(self):\n self.filename = time.strftime('%Y%m%d_%H%M%S') + '_mod2D'\n self.timestamp = time.strftime(\"%Y-%m-%d @ %I:%M%:%S%p\")\n\n\n self.calc_ramp() #easy way to clear self.V\n self.IV.V = self.IV.V*0\n\n self.param_prompt() # Check parameters\n self.setup_plot()\n\n for i in range(len(self.Imod)):\n self.IV.Imod = self.Imod[i]\n self.IV.do_IV()\n self.axIV.clear()\n self.IV.plot(self.axIV)\n self.V[:][i] = self.IV.V\n self.plot()\n self.fig.canvas.draw() #draws the plot; needed for %matplotlib notebook\n self.IV.daq.zero() # zero everything\n\n self.notes = input('Notes for this mod2D (q to quit without saving): ')\n if inp != 'q':\n self.save()\n\n def param_prompt(self):\n \"\"\" Check and confirm values of parameters \"\"\"\n correct = False\n while not correct:\n for param in ['rate', 'Rbias', 'Rbias_mod', 'Irampspan', 'Irampstep']:\n print('IV', param, ':', getattr(self.IV, param))\n for parammod in ['Imodspan','Imodstep']:\n print(parammod, ':', getattr(self, parammod))\n for paramamp in ['gain','filter']:\n print('IV preamp', paramamp, ':', getattr(self.IV.preamp, paramamp))\n\n if self.IV.rate > self.IV.preamp.filter[1]:\n print(\"You're filtering out your signal... fix the preamp cutoff\\n\")\n if self.IV.Irampspan > 200e-6:\n print(\"You want the SQUID biased above 100 uA?... don't kill the SQUID!\\n\")\n if self.Imodspan > 300e-6:\n print(\"You want the SQUID mod biased above 150 uA?... don't kill the SQUID!\\n\")\n\n try:\n inp = input('Are these parameters correct? Enter a command to change parameters, or press enter to continue (e.g. IV.preamp.gain = 100): ')\n if inp == '':\n correct = True\n else:\n exec('self.'+inp)\n self.IV.calc_ramp()\n self.calc_ramp() # recalculate daq output\n display.clear_output()\n except:\n display.clear_output()\n print('Invalid command\\n')\n\n def plot(self):\n '''\n Plot the 2D mod image\n '''\n plotting.update2D(self.im, self.V)\n\n\n def save(self):\n home = os.path.expanduser(\"~\")\n data_folder = os.path.join(home, 'Dropbox (Nowack lab)', 'TeamData', 'Montana', 'squid_testing', 'mod2D')\n\n filename = os.path.join(data_folder, self.filename)\n with open(filename+'.csv', 'w') as f:\n f.write(self.notes+'\\n')\n f.write('Montana info: \\n'+self.IV.montana.log()+'\\n')\n for param in ['rate', 'Rbias', 'Rbias_mod', 'Irampspan', 'Irampstep']:\n f.write('IV' + param + ': ' + str(getattr(self.IV, param)) + '\\n')\n for parammod in ['Imodspan','Imodstep']:\n f.write(parammod + ': ' + str(getattr(self, parammod)) + '\\n')\n for paramamp in ['gain','filter']:\n f.write('IV preamp ' + paramamp + ': ' + str(getattr(self.IV.preamp, paramamp)) + '\\n')\n\n f.write('Isquid (V),Imod (V),Vsquid (V)\\n')\n for i in range(self.numpts):\n for j in range(self.IV.numpts):\n if self.V[i][j] != None:\n f.write('%f' %self.IV.I[j] + ',' + '%f' %self.Imod[i] + ',' + '%f' %self.V[i][j] + '\\n')\n\n self.fig.savefig(filename+'.pdf')\n\n def setup_plot(self):\n '''\n Set up the figure. 2D mod image and last IV trace.\n '''\n self.fig, (self.axIV, self.ax2D) = plt.subplots(2,1,figsize=(7,7),gridspec_kw = {'height_ratios':[1, 3]})\n self.fig.suptitle(self.filename+'\\n'+self.notes)\n\n ## Set up 2D plot\n self.im = plotting.plot2D(self.ax2D,\n self.IV.I*1e6,\n self.Imod*1e6,\n self.V,\n xlabel=r'$I_{\\rm{bias}} = V_{\\rm{bias}}/R_{\\rm{bias}}$ ($\\mu \\rm A$)',\n ylabel = r'$I_{\\rm{mod}} = V_{\\rm{mod}}/R_{\\rm{mod}}$ ($\\mu \\rm A$)',\n clabel = r'$V_{\\rm{squid}}$ $(\\rm V)$',\n fontsize=20\n )\n","sub_path":"Procedures/mod2D.py","file_name":"mod2D.py","file_ext":"py","file_size_in_byte":6473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"638906016","text":"from src import common\nfrom src.jinja import JINJA_ENVIRONMENT\nfrom src.handlers.scheduling.scheduling_base import SchedulingBaseHandler\nfrom src.scheduling.competition_details import CompetitionDetails\n\n\nclass Schedule2018Handler(SchedulingBaseHandler):\n def get(self):\n if not self.SetCompetition('CubingUSANationals2018',\n login_required=False, edit_access_needed=False):\n return\n\n template = JINJA_ENVIRONMENT.get_template('nationals/2018/schedule.html')\n competition_details = CompetitionDetails(self.user, self.competition)\n\n self.response.write(template.render({\n 'c': common.Common(self),\n 'competition': self.competition,\n 'competition_details': competition_details,\n }))\n","sub_path":"src/handlers/nationals/eighteen/schedule.py","file_name":"schedule.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"562365170","text":"# -*- coding:utf-8 -*-\nfrom django import forms\nfrom django.conf import settings\nfrom attendance_schedule.staff.models import OtherSchedule, Schedule, Staff\nfrom django_mail_template import send_mail\nfrom django.contrib.auth.tokens import PasswordResetTokenGenerator\nfrom django.utils.http import urlsafe_base64_encode\nfrom django.utils.encoding import force_bytes\n\n\nclass OtherScheduleRegisterForm(forms.ModelForm):\n class Meta:\n model = OtherSchedule\n fields = (\n 'title',\n 'date',\n 'start',\n 'end',\n 'is_allday',\n )\n\n def __init__(self, *args, **kwargs):\n super(OtherScheduleRegisterForm, self).__init__(*args, **kwargs)\n for field in self.fields:\n self.fields[field].widget.attrs.update({'class': \"form-control\"})\n self.fields[\"is_allday\"].widget.attrs.update({'class': \"checkbox\"})\n\n\nclass OtherScheduleEditForm(forms.ModelForm):\n class Meta:\n model = OtherSchedule\n fields = (\n 'title',\n 'date',\n 'start',\n 'end',\n 'is_allday',\n 'enabled',\n )\n\n def __init__(self, *args, **kwargs):\n super(OtherScheduleEditForm, self).__init__(*args, **kwargs)\n for field in self.fields:\n self.fields[field].widget.attrs.update({'class': \"form-control\"})\n for field in (\"is_allday\", \"enabled\"):\n self.fields[field].widget.attrs.update({'class': \"checkbox\"})\n\n\nclass AdminScheduleEditForm(forms.ModelForm):\n class Meta:\n model = Schedule\n fields = (\n 'date',\n 'start',\n 'end',\n 'enabled',\n )\n\n def __init__(self, *args, **kwargs):\n super(AdminScheduleEditForm, self).__init__(*args, **kwargs)\n for field in self.fields:\n self.fields[field].widget.attrs.update({'class': \"form-control\"})\n self.fields[\"enabled\"].widget.attrs.update({'class': \"checkbox\"})\n\n\n\nclass AdminStaffRegisterForm(forms.ModelForm):\n first_name = forms.CharField(label=u\"名\", required=False)\n last_name = forms.CharField(label=u\"姓\", required=True)\n email = forms.EmailField(label=u\"メールアドレス\", required=True)\n username = forms.RegexField(\n label=u\"ユーザー名\",\n max_length=15,\n regex=r'^[a-zA-Z0-9]+$',\n error_messages={'invalid': u\"半角英数15字以内で入力してください。\"})\n\n class Meta:\n model = Staff\n fields = (\n \"username\",\n \"first_name\",\n \"last_name\",\n \"email\",\n \"affiliation\",\n )\n\n def __init__(self, *args, **kwargs):\n super(AdminStaffRegisterForm, self).__init__(*args, **kwargs)\n for field in self.fields:\n self.fields[field].widget.attrs.update({'class': \"form-control\"})\n\n def save(self, commit=True):\n user = super(AdminStaffRegisterForm, self).save(commit=False)\n user.set_unusable_password()\n if commit:\n user.save()\n token_generator = PasswordResetTokenGenerator()\n token = token_generator.make_token(user)\n mail_context = {\n \"user\": user,\n \"token\": token,\n \"uidb64\": urlsafe_base64_encode(force_bytes(user.id)),\n \"site_host\": settings.SITE_HOST,\n }\n send_mail(\n \"email/admin_staff_register.eml\",\n mail_context,\n from_email=settings.DEFAULT_FROM_EMAIL,\n to=[user.email],\n )\n return user\n","sub_path":"src/attendance_schedule/admin/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"161592050","text":"from keras.utils import to_categorical\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt \n\n\ndef remove_9(x, y):\n mask = y != 9\n return x[mask], y[mask]\n\ndef replicate(X, left=13, right=13, up=21, down=21):\n \"\"\"\n Given a batch of images (of shape (num samples, image height, image width, num channels)),\n replicates all the images' border on the 4 sides.\n \"\"\"\n # left\n X = np.concatenate((np.tile(X[:, :, :1], (1, 1, left, 1)), X), axis=2)\n\n # right\n X = np.concatenate((X, np.tile(X[:, :, -1:], (1, 1, right, 1))), axis=2)\n\n # up\n X = np.concatenate((np.tile(X[:, :1, :], (1, up, 1, 1)), X), axis=1)\n\n # down\n X = np.concatenate((X, np.tile(X[:, -1:, :], (1, down, 1, 1))), axis=1)\n\n return X\n\n\ndef preprocessing_mnist_data(train_digits, train_labels, test_digits, test_labels, num_classes=9):\n image_height = train_digits.shape[1] \n image_width = train_digits.shape[2]\n num_channels = 1 # we have grayscale images\n\n # re-shape the images data\n train_data = np.reshape(train_digits, (train_digits.shape[0], image_height, image_width, num_channels))\n test_data = np.reshape(test_digits, (test_digits.shape[0],image_height, image_width, num_channels))\n \n # threshold\n train_data[train_data > 0] = 255\n\n # add padding to have image similar to our images\n train_data = normalize(train_data, batch=True)\n test_data = normalize(test_data, batch=True)\n \n\n # one-hot encode the labels - we have 9 output classes (esclude 9!)\n # so 3 -> [0 0 0 1 0 0 0 0 0 0], 5 -> [0 0 0 0 0 1 0 0 0 0] & so on\n train_labels_cat = to_categorical(train_labels, num_classes)\n test_labels_cat = to_categorical(test_labels, num_classes)\n return train_data, train_labels_cat, test_data, test_labels_cat\n\ndef preprocessing_our_data(objects, to_exclude=False):\n toRecognize = []\n \n # esclude images with index: 2, 3, 6, 9\n idx = 0\n\n for im in objects:\n im = im * 255.\n digit = im.copy()\n im[im > 0] = 255\n if(not to_exclude):\n toRecognize.append(normalize(digit))\n elif(to_exclude and ((idx in [2, 3, 6, 9]) == False)):\n toRecognize.append(normalize(digit))\n idx = idx + 1\n\n toRecognize = np.stack(toRecognize)\n return toRecognize\n\ndef normalize(x, batch=False):\n if batch:\n return (x - x.mean(axis=(1, 2)).reshape(x.shape[0], 1, 1, 1)) / x.std(axis=(1, 2)).reshape(x.shape[0], 1, 1, 1)\n return np.array((x - x.mean()) / x.std())","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"501199422","text":"# code by btilly in answer to\n# https://stackoverflow.com/questions/72945293/generating-a-random-string-with-matched-brackets\nimport random\n\n\nclass DPPath:\n def __init__(self):\n self.count = 0\n self.next = None\n\n def add_option(self, transition, tail):\n if self.next is None:\n self.next = {}\n self.next[transition] = tail\n self.count += tail.count\n\n def random(self):\n if 0 == self.count:\n return None\n else:\n return self.find(int(random.random() * self.count))\n\n def find(self, pos):\n result = self._find(pos)\n return \"\".join(reversed(result))\n\n def _find(self, pos):\n if self.next is None:\n return []\n\n for transition, tail in self.next.items():\n if pos < tail.count:\n result = tail._find(pos)\n result.append(transition)\n return result\n else:\n pos -= tail.count\n\n raise IndexException(\"find out of range\")\n\n\ndef balanced_dp(n, alphabet):\n # Record that there is 1 empty string with balanced parens.\n base_dp = DPPath()\n base_dp.count = 1\n\n dps = [base_dp]\n\n for _ in range(n):\n # We are working backwards towards the start.\n prev_dps = [DPPath()]\n\n for i in range(len(dps)):\n # prev_dps needs to be bigger in case of closed paren.\n prev_dps.append(DPPath())\n # If there are closed parens, we can open one.\n if 0 < i:\n prev_dps[i - 1].add_option(\"(\", dps[i])\n\n # alphabet chars don't change paren balance.\n for char in alphabet:\n prev_dps[i].add_option(char, dps[i])\n\n # Add a closed paren.\n prev_dps[i + 1].add_option(\")\", dps[i])\n\n # And we are done with this string position.\n dps = prev_dps\n\n # Return the one that wound up balanced.\n return dps[0]\n\n\n# And a quick demo of several random strings.\nfor _ in range(10):\n print(balanced_dp(10, \"abc\").random())\n","sub_path":"balanced_dp.py","file_name":"balanced_dp.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"435286618","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import RepeatedStratifiedKFold, cross_validate\nfrom sklearn.metrics import accuracy_score, classification_report, plot_confusion_matrix\nimport warnings\nwarnings.filterwarnings('ignore')\nwarnings.simplefilter('ignore') \n\ndef train_evaluate_classifier(clf, x, y, x_train, y_train, x_test, y_test, skip_fit = False):\n np.random.seed(73246)\n cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=10)\n if not skip_fit:\n clf.fit(x_train, y_train)\n results = cross_validate(clf, x, y, cv=cv, scoring='f1', return_train_score=True, n_jobs=-1)\n y_predict = clf.predict(x_test)\n auc_medio = np.mean(results['test_score'])\n print(f'F1: {auc_medio}')\n print(format_classification_report(y_test, y_predict))\n plot_confusion_matrix(clf, x_test, y_test)\n return clf\n\ndef format_classification_report(test, predict):\n df_cr = pd.DataFrame(classification_report(test, predict, output_dict=True)).T\n df_cr['precision']['accuracy'] = ''\n df_cr['recall']['accuracy'] = ''\n df_cr['support']['accuracy'] = df_cr['support']['macro avg']\n df_cr['support'] = df_cr['support'].astype('int32')\n return df_cr","sub_path":"scripts/evaluate_model.py","file_name":"evaluate_model.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"21172098","text":"#!/usr/bin/env python3\nimport os\nimport json\n\norder_list = ['Gymnophiona', 'Caudata', 'Anura']\n\ndirname_species = '../species/'\ndirname_data = '../docs/_data/'\n\nfor tmp_order in order_list:\n filename_json = os.path.join(dirname_species, \n 'Order_%s.json' % tmp_order)\n\n f_json = open(filename_json, 'r')\n order_json = json.loads(f_json.read())\n f_json.close()\n\n f_out = open(os.path.join(dirname_data, '%s.yml' % tmp_order), 'w')\n f_out.write('species:\\n')\n for tmp_family in sorted(order_json.keys()):\n for tmp_species in sorted(order_json[tmp_family].keys()):\n f_out.write('- species_name: %s\\n' % tmp_species)\n f_out.write(' order: %s\\n' % tmp_order)\n f_out.write(' family: %s\\n' % tmp_family)\n f_out.write(' species_code: %s\\n' % order_json[tmp_family][tmp_species])\n f_out.close()\n","sub_path":"utils/jekyll-species_json-to-doc_yaml.py","file_name":"jekyll-species_json-to-doc_yaml.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"643021429","text":"from model.preprocess import Preprocessor\r\n\r\n## test code\r\npreprocessor = Preprocessor(vocab_size=100, seq_len=10)\r\ninputs = [[\"जैसा \"], [\"i am fine, what about you. i mean ? \"]]\r\nvocab = preprocessor.build_vocab(inputs)\r\nprint(vocab)\r\noutputs = preprocessor(inputs)\r\nprint(outputs)\r\nprint(preprocessor.get_text(outputs.numpy()))","sub_path":"model/tests/test_preprocess.py","file_name":"test_preprocess.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"171235500","text":"import os\nfrom tkinter import *\n\nroot = Tk()\nroot.title(\"SONG Memo\")\nroot.geometry(\"640x480\")\n\nfilename = \"python_basic_gui\\mynote.txt\"\n\n# 열기\ndef func_open():\n if os.path.isfile(filename):\n # with open(filename, \"r\", encoding=\"utf8\") as file:\n # txt.delete(\"1.0\", END)\n # txt.insert(END, file.read())\n file = open(filename, \"r\", encoding=\"utf8\")\n txt.delete(\"1.0\", END)\n txt.insert(END, file.read())\n file.close()\n\n# 저장\ndef func_save():\n file = open(filename, \"w\", encoding=\"utf8\")\n file.write(txt.get(\"1.0\", END))\n file.close()\n\n# 메뉴\nmenu = Menu(root)\n\n# File 메뉴\nmenu_file = Menu(menu, tearoff=0)\nmenu_file.add_command(label=\"열기\", command = func_open)\nmenu_file.add_command(label=\"저장\", command = func_save)\nmenu_file.add_separator()\nmenu_file.add_command(label=\"Exit\", command=root.quit)\nmenu.add_cascade(label=\"File\", menu=menu_file)\n\n# 편집, 서식, 보기, 도움말 메뉴\nmenu_edit = Menu(menu, tearoff=0)\nmenu_doc = Menu(menu, tearoff=0)\nmenu_w = Menu(menu, tearoff=0)\nmenu_help = Menu(menu, tearoff=0)\nmenu.add_cascade(label=\"편집\", menu=menu_edit)\nmenu.add_cascade(label=\"서식\", menu=menu_doc)\nmenu.add_cascade(label=\"보기\", menu=menu_w)\nmenu.add_cascade(label=\"도움말\", menu=menu_help)\n\n# 스크롤 바\nscrollbar = Scrollbar(root)\nscrollbar.pack(side=\"right\", fill=\"y\")\n\n# 본문 영역\ntxt = Text(root, yscrollcommand=scrollbar.set) # 여러 줄 가능\ntxt.pack(side=\"left\", fill=\"both\", expand=True)\nscrollbar.config(command=txt.yview)\n\nroot.config(menu=menu)\nroot.mainloop()","sub_path":"python_basic_gui/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"165533239","text":"# Density_Function_Theory - KIT v1.0.0 \n# August 2014\n# Class for the object atom to construct the lattice and basis atoms\n\nimport os\nimport shutil\nimport pickle\nimport string\nimport numpy as np\nimport sys\nimport string\nimport xml.etree.ElementTree as ET\nimport os.path\n\nfrom DFT_KIT.core import general_tool\nfrom DFT_KIT.core import env_parm\nfrom DFT_KIT.core import calculator\nfrom DFT_KIT.core import physics\n\nQES_control_flags='calculation title verbosity restart_mode wf_collect nstep iprint tstress tprnfor dt wfcdir lkpoint_dir max_seconds etot_conv_thr forc_conv_thr disk_io tefield dipfield lelfield nberrycyc lorbm lberry gdir nppstr'.split()\nQES_system_flags='ibrav celldm A B C cosAB cosAC cosBC nbnd tot_charge tot_magnetization starting_magnetization ecutwfc ecutrho ecutfock nr1 nr2 nr3 nr1s nr2s nr3s nosym nosym_evc noinv no_t_rev force_symmorphic use_all_frac occupations one_atom_occupations starting_spin_angle degauss smearing nspin noncolin ecfixed qcutz q2sigma input_dft exx_fraction screening_parameter exxdiv_treatment x_gamma_extrapolation ecutvcut nqx1 nqx2 nqx3 lda_plus_u lda_plus_u_kind Hubbard_U Hubbard_J0 Hubbard_alpha Hubbard_beta Hubbard_J(i,ityp) starting_ns_eigenvalue(m,ispin,I) U_projection_type edir emaxpos eopreg eamp angle1 angle2 constrained_magnetization fixed_magnetization lambda report lspinorb assume_isolated esm_bc esm_w esm_efield esm_nfit vdw_corr london london_s6 london_rcut xdm xdm_a1 xdm_a2'.split()\nQES_electrons_flags='electron_maxstep scf_must_converge conv_thr adaptive_thr conv_thr_init conv_thr_multi mixing_mode mixing_beta mixing_ndim mixing_fixed_ns diagonalization ortho_para diago_thr_init diago_cg_maxiter diago_david_ndim diago_full_acc efield efield_cart startingpot startingwfc tqr'.split()\nQES_ions_flags='ion_dynamics ion_positions phase_space pot_extrapolation wfc_extrapolation remove_rigid_rot ion_temperature tempw tolp delta_t nraise refold_pos upscale bfgs_ndim trust_radius_max trust_radius_min trust_radius_ini w_1 w_2'.split()\nQES_cell_flags='cell_dynamics press wmass cell_factor press_conv_thr cell_dofree'.split()\n\n#for .pw2wan file\nQES_PW2WAN_flags=['write_amn','write_spn','write_mmn','write_unk']\nQES_PW2BGW_flags='real_or_complex symm_type wfng_flag wfng_file wfng_kgrid wfng_nk1 wfng_nk2 wfng_nk3 wfng_dk1 wfng_dk2 wfng_dk3 wfng_occupation wfng_nvmin wfng_nvmax rhog_flag rhog_file vxcg_flag vxcg_file vxc0_flag vxc0_file vxc_flag vxc_file vxc_integral vxc_diag_nmin vxc_diag_nmax vxc_offdiag_nmin vxc_offdiag_nmax vxc_zero_rho_core vscg_flag vscg_file vkbg_flag vkbg_file'.split()\n\n\nclass calculator_QESPRESSO(calculator.calculator):\n def __init__(self,postprocess,dft_job,crystal,kgrid,scheme=0,**parms):\n calculator.calculator.__init__(self,postprocess,dft_job,crystal,kgrid,**parms)\n self.apply_scheme(scheme)\n self.wannier90_analysis=False\n self.write_occupations=False\n self.write_constraints=False\n self.write_atomic_forces=False\n self.atomic_positions_ang=True\n self.parms['claculation']=''\n self.qes_vars={}\n \n def apply_scheme(self,scheme):\n self.set_parm('ibrav','0')\n self.set_parm('conv_thr', '1E-8')\n self.set_parm('mixing_beta','0.3')\n self.set_parm('diagonalization',\"'cg'\")\n self.set_parm('diago_full_acc','.true.')\n \n \n if scheme==0:\n # general scf (for insulator)\n self.set_parm('calculation', \"'scf'\")\n\n \n elif scheme == 1:\n # general scf for metal\n self.set_parm('calculation', \"'scf'\")\n self.set_parm('occupations',\"'smearing'\")\n self.set_parm('smearing',\"'gaussian'\")\n self.set_parm('degauss','0.005')\n \n elif scheme == 2:\n # band structure calculation\n self.set_parm('calculation', \"'nscf'\")\n\n elif scheme==3:\n #relaxation\n #ENCUT increase!\n self.set_parm('calculation', \"'relax'\")\n\n elif scheme==4:\n #variable cell relaxation\n #ENCUT increase!\n self.set_parm('calculation', \"'vc-relax'\")\n self.set_parm('cell_dynamics', \"'bfgs'\")\n \n \n elif scheme==5:\n #for spin orbit interaction (NON SC)\n self.set_parm('noncolin', '.true.')\n self.set_parm('lspinorb', '.true.')\n \n def qes_save_output(self,parms_list):\n # parm_list in the form: ['aa':'new name',bb:...,cc:...]\n for parm in parms_list:\n if parm in self.qes_vars:\n self.save_output_data[parms_list[parm]]=self.qes_vars[parm]\n \n \n def run_main(self):\n env_parm.run_qes_pwx(self.dft_job.job_mamanger_mode,self.dft_job.sys_info['qes_fname'])\n \n def run_pw2wan(self):\n self.qes_generate_pw2wan()\n env_parm.run_qes_pw2wan(self.dft_job.job_mamanger_mode, self.dft_job.sys_info['qes_fname'])\n \n def run_ppx(self):\n pass\n \n def qes_generate_ppx(self):\n f_=open('qes.ppx.in','w')\n \n \n f_.close()\n \n \n def qes_generate_pw2wan(self):\n f_=open(self.dft_job.sys_info['qes_fname']+'.pw2wan.in','w')\n f_.write(' &inputpp\\n')\n f_.write(\" prefix = '\" + self.dft_job.sys_info['qes_prefix'] + \"'\\n\")\n f_.write(\" outdir = '\" + self.dft_job.get_maindir() +\"'\\n\")\n f_.write(\" seedname = '\" +self.dft_job.sys_info['wan90_seedname'] +\"'\\n\")\n for ind_key in self.parms:\n if ind_key in QES_PW2WAN_flags:\n f_.write(' '+ind_key+' = ' + self.parms[ind_key]+' \\n')\n f_.write(' /')\n f_.write('\\n')\n f_.close()\n \n def generate_files(self):\n #control section\n f_=open(self.dft_job.sys_info['qes_fname']+'.pwx.in','w')\n if 'calculation' not in self.parms or self.parms['calculation']=='':\n self.dft_job.show_error('CALC', 'calculation mode not set')\n return\n \n f_.write(' &control\\n')\n f_.write(\" prefix = '\" + self.dft_job.sys_info['qes_prefix'] + \"',\\n\")\n f_.write(\" outdir = '\" + self.dft_job.get_maindir() +\"',\\n\")\n f_.write(\" pseudo_dir = '\" + env_parm.qespresso_pseudo_dir +\"',\\n\")\n for ind_key in self.parms:\n if ind_key in QES_control_flags:\n f_.write(' '+ind_key+' = ' + self.parms[ind_key]+' ,\\n')\n f_.write(' /')\n f_.write('\\n')\n \n #system section\n f_.write(' &system\\n')\n f_.write(' nat = ' + str(self.crystal.get_totnum_atoms()) + ',\\n')\n f_.write(' ntyp = ' + str(len(self.crystal.basis_atom_groups)) + ',\\n')\n for ind_key in self.parms:\n if ind_key in QES_system_flags:\n f_.write(' '+ind_key+' = ' + self.parms[ind_key]+' ,\\n')\n f_.write(' /')\n f_.write('\\n')\n \n #electrons section\n f_.write(' &electrons\\n')\n for ind_key in self.parms:\n if ind_key in QES_electrons_flags:\n f_.write(' '+ind_key+' = ' + self.parms[ind_key]+' ,\\n')\n f_.write(' /')\n f_.write('\\n')\n \n #ions section\n f_.write(' &ions\\n')\n for ind_key in self.parms:\n if ind_key in QES_ions_flags:\n f_.write(' '+ind_key+' = ' + self.parms[ind_key]+' ,\\n')\n f_.write(' /')\n f_.write('\\n')\n \n #cell section\n f_.write(' &cell\\n')\n for ind_key in self.parms:\n if ind_key in QES_cell_flags:\n f_.write(' '+ind_key+' = ' + self.parms[ind_key]+' ,\\n')\n f_.write(' /')\n f_.write('\\n')\n \n f_.write('ATOMIC_SPECIES\\n')\n #name, mass, pseudopotential\n for group in self.crystal.basis_atom_groups.keys():\n element=self.crystal.basis_element[group]\n f_.write(' '+group + ' '+str(element.mass) + ' ' + element.info['qes_pot'] +'\\n') \n f_.write('\\n')\n \n if self.atomic_positions_ang:\n f_.write('ATOMIC_POSITIONS angstrom\\n')\n else:\n f_.write('ATOMIC_POSITIONS crystal\\n')\n #species, coordinate x and y\n for ind, group in enumerate(self.crystal.basis_atom_groups.keys()):\n for atom in self.crystal.basis_atom_groups[group]:\n if self.parms['calculation']==\"'vc-relax'\" or self.parms['calculation']==\"'relax'\" or self.parms['calculation']==\"'md'\" or self.parms['calculation']==\"'vc-md'\":\n f_.write(' '+ group + ' ' +general_tool.vec_to_str(atom.get_position())+' ' +str(general_tool.bool_to_10(atom.relax[0]))+ ' '+str(general_tool.bool_to_10(atom.relax[1])) + ' '+str(general_tool.bool_to_10(atom.relax[2]))+ '\\n')\n else:\n f_.write(' '+ group + ' ' +general_tool.vec_to_str(atom.get_position()) + '\\n')\n f_.write('\\n')\n \n \n if self.kgrid.kmode ==0:\n f_.write('K_POINTS automatic\\n')\n f_.write(' ' + general_tool.vec_to_str(self.kgrid.kgrid)+ ' '+ general_tool.vec_to_str(self.kgrid.kgrid_shift)+ '\\n')\n \n elif self.kgrid.kmode ==1:\n f_.write('K_POINTS crystal_b\\n')\n f_.write(' '+str(len(self.kgrid.kscan))+'\\n')\n for ind in range(len(self.kgrid.kscan)):\n if ind%2 ==1:\n f_.write(general_tool.vec_to_str(self.kgrid.kscan[ind])+' 1 \\n')\n else:\n f_.write(general_tool.vec_to_str(self.kgrid.kscan[ind])+ ' '+ str(self.kgrid.num_kscan) +'\\n')\n \n elif self.kgrid.kmode ==2:\n f_.write('K_POINTS crystal\\n')\n f_.write(' '+str(len(self.kgrid.klist))+'\\n')\n for ind in range(len(self.kgrid.klist)):\n tmp=self.kgrid.klist[ind]\n f_.write(' '+general_tool.vec_to_str(tmp)+'\\n')\n\n \n f_.write('\\n') \n \n #other parts in qespresso\n f_.write('CELL_PARAMETERS angstrom\\n')\n f_.write(' '+general_tool.vec_to_str(self.crystal.get_prim_vec(0)) +'\\n')\n f_.write(' '+general_tool.vec_to_str(self.crystal.get_prim_vec(1)) +'\\n')\n f_.write(' '+general_tool.vec_to_str(self.crystal.get_prim_vec(2)) +'\\n')\n f_.write('\\n') \n\n # optional part\n if self.write_constraints:\n f_.write('CONSTRAINTS\\n')\n f_.write('\\n')\n \n if self.write_occupations:\n f_.write('OCCUPATIONS\\n')\n f_.write('\\n')\n \n if self.write_atomic_forces:\n f_.write('ATOMIC_FORCES\\n')\n f_.write('\\n')\n \n f_.close()\n \n \n \n def post_process(self):\n self.qes_vars={}\n self.qes_vars['sc_tot_energy']=[]\n self.qes_vars['sc_harrisf_energy']=[]\n self.qes_vars['sc_energy_accu']=[]\n \n self.qes_vars['tot_energy']=0.0\n self.qes_vars['harrisf_energy']=0.0\n self.qes_vars['energy_accu']=0.0\n self.qes_vars['onee_energy']=0.0\n self.qes_vars['hartree_energy']=0.0\n self.qes_vars['xc_energy']=0.0\n self.qes_vars['ewald_energy']=0.0\n \n self.qespresso_post_process_xml(self.dft_job.sys_info['qes_prefix']+'.save/' ,'data-file.xml')\n if os.path.isfile(self.dft_job.sys_info['qes_fname']+'.pwx.out'):\n self.qespresso_post_process_outfile(self.dft_job.sys_info['qes_fname']+'.pwx.out')\n else:\n self.dft_job.show_error('QESPRESSO', 'pp-no out file')\n \n #fill in basic information\n #crystal\n self.output['num_atoms']=self.qes_vars['num_atoms']\n self.output['num_types']=self.qes_vars['num_types']\n self.output['final_prim_vectors']=np.array([self.qes_vars['prim_a1'],self.qes_vars['prim_a2'],self.qes_vars['prim_a3']])\n self.output['final_positions']=np.array(self.qes_vars['atom_pos'])\n\n #Energy:\n self.output['total_energy']=self.qes_vars['tot_energy']*physics.rydberg\n self.output['fermi_energy']=self.qes_vars['fermi_energy']*physics.hartree\n \n \n #eigenvalues/bands\n \n def qespresso_post_process_outfile(self,fname):\n f_=open(fname,'r')\n\n iteration=0\n \n end_scf=False\n calc_scf=False\n calc_band=False\n \n \n while True:\n tmpstr=f_.readline()\n tmpstrs=tmpstr.split()\n if tmpstr=='':\n break\n \n if tmpstr.find('Self-consistent Calculation')>=0:\n calc_scf=True\n \n if tmpstr.find('Band Structure Calculation')>=0:\n calc_band=True\n \n if tmpstr.find('iteration #')>=0:\n iteration = int(tmpstrs[2])\n \n if tmpstr.find('End of self-consistent calculation')>=0:\n end_scf=True\n \n #cpu/mem\n if tmpstr.find('PWSCF')>=0 and tmpstr.find('CPU')>=0:\n self.qes_vars['cpu_time']=tmpstrs[2]\n self.qes_vars['wall_time']=tmpstrs[4]\n \n if tmpstr.find('total energy')>=0 and tmpstr.find('=')>=0:\n if tmpstr.find('!')>=0:\n self.qes_vars['tot_energy']=float(tmpstrs[4])\n else:\n self.qes_vars['sc_tot_energy'].append(float(tmpstrs[3]))\n\n if tmpstr.find('Harris-Foulkes estimate')>=0:\n if tmpstr.find('!')>=0:\n self.qes_vars['harrisf_energy']=float(tmpstrs[3])\n else:\n self.qes_vars['sc_harrisf_energy'].append(float(tmpstrs[3]))\n \n if tmpstr.find('estimated scf accuracy')>=0:\n if tmpstr.find('!')>=0:\n self.qes_vars['energy_accu']=float(tmpstrs[4])\n else:\n self.qes_vars['sc_energy_accu'].append(float(tmpstrs[4]))\n \n if tmpstr.find('one-electron contribution')>=0:\n self.qes_vars['onee_energy']=float(tmpstrs[3])\n if tmpstr.find('hartree contribution')>=0:\n self.qes_vars['hartree_energy']=float(tmpstrs[3])\n if tmpstr.find('xc contribution')>=0:\n self.qes_vars['xc_energy']=float(tmpstrs[3])\n if tmpstr.find('ewald contribution')>=0:\n self.qes_vars['ewald_energy']=float(tmpstrs[3])\n #error message handling\n \n \n \n \n def qespresso_post_process_xml(self,xmldir,xmlfile='data-file.xml'):\n tree = ET.parse(xmldir+xmlfile)\n root = tree.getroot()\n \n root_header=root.find('HEADER')\n root_control=root.find('CONTROL')\n \n root_cell=root.find('CELL')\n prim_vec_a1=root_cell.find('DIRECT_LATTICE_VECTORS/a1')\n self.qes_vars['prim_a1']=physics.bohr*general_tool.str_to_vec(prim_vec_a1.text.split())\n prim_vec_a2=root_cell.find('DIRECT_LATTICE_VECTORS/a2')\n self.qes_vars['prim_a2']=physics.bohr*general_tool.str_to_vec(prim_vec_a2.text.split())\n prim_vec_a3=root_cell.find('DIRECT_LATTICE_VECTORS/a3')\n self.qes_vars['prim_a3']=physics.bohr*general_tool.str_to_vec(prim_vec_a3.text.split())\n rec_vec_b1=root_cell.find('RECIPROCAL_LATTICE_VECTORS/b1')\n self.qes_vars['rec_b1']=(1.0/physics.bohr)*general_tool.str_to_vec(rec_vec_b1.text.split())\n rec_vec_b2=root_cell.find('RECIPROCAL_LATTICE_VECTORS/b2')\n self.qes_vars['rec_b2']=(1.0/physics.bohr)*general_tool.str_to_vec(rec_vec_b2.text.split())\n rec_vec_b3=root_cell.find('RECIPROCAL_LATTICE_VECTORS/b3')\n self.qes_vars['rec_b3']=(1.0/physics.bohr)*general_tool.str_to_vec(rec_vec_b3.text.split())\n \n root_ions=root.find('IONS')\n tmp=root_ions.find('NUMBER_OF_ATOMS')\n self.qes_vars['num_atoms']=int(tmp.text)\n tmp=root_ions.find('NUMBER_OF_SPECIES')\n self.qes_vars['num_types']=int(tmp.text)\n \n self.qes_vars['atom_pos']=[]\n for ind in range(1,self.qes_vars['num_atoms']+1):\n tmp=root_ions.find('ATOM.'+str(ind))\n self.qes_vars['atom_pos'].append(physics.bohr*general_tool.str_to_vec(tmp.attrib['tau'].split()))\n \n root_symmetries=root.find('SYMMETRIES')\n root_electric_field=root.find('ELECTRIC_FIELD')\n root_pw=root.find('PLANE_WAVES')\n tmp=root_pw.find('WFC_CUTOFF')\n \n root_spin=root.find('SPIN')\n root_mag=root.find('MAGNETIZATION_INIT')\n root_xc=root.find('EXCHANGE_CORRELATION')\n tmp=root_xc.find('DFT')\n self.qes_vars['xc']=tmp.text\n \n root_occ=root.find('OCCUPATIONS')\n root_bz=root.find('BRILLOUIN_ZONE')\n tmp=root_bz.find('NUMBER_OF_K-POINTS')\n self.qes_vars['num_kpts']=int(tmp.text)\n self.qes_vars['kpts']=[]\n self.qes_vars['kpts_weight']=[]\n for ind in range(1,self.qes_vars['num_kpts']+1):\n tmp=root_bz.find('K-POINT.'+str(ind))\n self.qes_vars['kpts'].append(tmp.attrib['XYZ'].split())\n self.qes_vars['kpts_weight'].append(tmp.attrib['WEIGHT'])\n \n root_par=root.find('PARALLELISM')\n tmp=root_par.find('NUMBER_OF_PROCESSORS')\n \n root_charge_den=root.find('CHARGE-DENSITY')\n \n \n root_band=root.find('BAND_STRUCTURE_INFO')\n tmp=root_band.find('UNITS_FOR_ENERGIES')\n self.qes_vars['unit_energy']=tmp.text\n tmp=root_band.find('FERMI_ENERGY')\n self.qes_vars['fermi_energy']=float(tmp.text)\n tmp=root_band.find('NUMBER_OF_BANDS')\n self.qes_vars['num_bands']=int(tmp.text)\n tmp=root_band.find('NUMBER_OF_ELECTRONS')\n self.qes_vars['num_electrons']=float(tmp.text)\n \n \n root_eigval=root.find('EIGENVALUES')\n self.qes_vars['eigenvalues']=np.zeros((self.qes_vars['num_bands'],self.qes_vars['num_kpts']))\n self.qes_vars['occupations']=np.zeros((self.qes_vars['num_bands'],self.qes_vars['num_kpts']))\n \n for indk in range(1,self.qes_vars['num_kpts']+1):\n tmp=root_eigval.find('K-POINT.'+str(indk))\n subtmp=tmp.find('DATAFILE')\n eigxml=subtmp.attrib['iotk_link']\n \n #analyze the xml for the k point\n eigtree = ET.parse(xmldir+eigxml)\n eigroot = eigtree.getroot()\n \n eigroot_val=eigroot.find('EIGENVALUES')\n tmp_vals=eigroot_val.text.split()\n for ind2 in range(0,self.qes_vars['num_bands']):\n self.qes_vars['eigenvalues'][ind2,indk-1]=(float(tmp_vals[ind2]))\n\n eigroot_occ=eigroot.find('OCCUPATIONS')\n tmp_occs=eigroot_occ.text.split()\n for ind2 in range(0,self.qes_vars['num_bands']):\n self.qes_vars['occupations'][ind2,indk-1]=(float(tmp_occs[ind2]))\n\n \n \n root_eigvec=root.find('EIGENVECTORS')\n \n\n","sub_path":"calculator/QESPRESSO.py","file_name":"QESPRESSO.py","file_ext":"py","file_size_in_byte":19386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"61812236","text":"import csv\r\nimport os\r\nfrom shutil import copyfile\r\nimport scripts.settings\r\n\r\nSOURCE_DIR = scripts.settings.PLATTE_BASEPATH\r\nSOURCE_PREFIX = \"1A_\"\r\nSOURCE_SUFFIX = \".bmp\"\r\nSOURCE_NUMBER_FORMAT = '%06d'\r\n\r\nTARGET_DIR = scripts.settings.PLATTE_BASEPATH + \"small/\"\r\nTARGET_PREFIX = \"1A_\"\r\nTARGET_SUFFIX = \".bmp\"\r\nTARGET_NUMBER_FORMAT = '%06d'\r\n\r\nANNOTATIONS_FILE = \"../annotations/bb_1-4A.txt\"\r\n\r\nif not os.path.exists(TARGET_DIR):\r\n os.makedirs(TARGET_DIR)\r\n\r\nwith open(ANNOTATIONS_FILE) as file:\r\n reader = csv.reader(file, delimiter=',')\r\n for row in reader:\r\n try:\r\n path = row[0]\r\n except ValueError:\r\n print(\"invalid line\", row)\r\n continue\r\n except IndexError:\r\n print(\"invalid line\", row)\r\n continue\r\n source_file = SOURCE_DIR + path #SOURCE_PREFIX + SOURCE_NUMBER_FORMAT % frame + SOURCE_SUFFIX\r\n target_file = TARGET_DIR + path # TARGET_PREFIX + TARGET_NUMBER_FORMAT % frame + TARGET_SUFFIX\r\n\r\n if not os.path.exists(target_file[:target_file.rfind(\"/\")]):\r\n print(\"created folder for\", target_file)\r\n os.makedirs(target_file[:target_file.rfind(\"/\")])\r\n\r\n if os.path.isfile(target_file):\r\n print (\"file\", target_file, \"exists, skip it.\")\r\n continue\r\n\r\n print(\"copy\", source_file, \"->\", target_file)\r\n copyfile(source_file, target_file)\r\n","sub_path":"scripts/copyImages.py","file_name":"copyImages.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"100589053","text":"#!/usr/bin/env python\n#\n# Copyright (C) 2017 Sean D'Epagnier\n#\n# This Program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public\n# License as published by the Free Software Foundation; either\n# version 3 of the License, or (at your option) any later version. \n\nimport sys\ntry:\n from setuptools import setup, Extension\n \nexcept ImportError:\n from distutils.core import setup, Extension\n\nlinebuffer_module = Extension('_linebuffer',\n sources=['signalk/linebuffer/linebuffer.cpp', 'signalk/linebuffer/linebuffer.i'],\n extra_compile_args=['-Wno-unused-result'],\n swig_opts=['-c++']\n)\n\narduino_servo_module = Extension('_arduino_servo',\n sources=['pypilot/arduino_servo/arduino_servo.cpp', 'pypilot/arduino_servo/arduino_servo_eeprom.cpp', 'pypilot/arduino_servo/arduino_servo.i'],\n extra_compile_args=['-Wno-unused-result'],\n swig_opts=['-c++']\n)\n\nugfx_defs = ['-DWIRINGPI']\ntry:\n import RPi.GPIO\n ugfx_libraries=['wiringPi']\nexcept:\n try:\n import OPi.GPIO\n ugfx_libraries=['wiringPi']\n except:\n print('no wiring library for ugfx')\n ugfx_libraries=[]\n ugfx_defs = []\n\nugfx_module = Extension('_ugfx',\n sources=['lcd/ugfx/ugfx.cpp',\n 'lcd/ugfx/ugfx.i'],\n extra_compile_args=['-Wno-unused-result'] + ugfx_defs,\n libraries=ugfx_libraries,\n swig_opts=['-c++'] + ugfx_defs\n)\n\nimport os, os.path\nlocale_files = []\nfor walk in os.walk('lcd/locale'):\n path, dirs, files = walk\n path = path[len('lcd/'):]\n for file in files:\n if file[len(file)-3:] == '.mo':\n locale_files.append(os.path.join(path, file))\n\nfrom pypilot import version\n\nfind_packages = False\ntry:\n from setuptools import find_packages\nexcept:\n pass\n\nsetup (name = 'pypilot',\n version = version.strversion,\n description = 'pypilot sailboat autopilot',\n license = 'GPLv3',\n author=\"Sean D'Epagnier\",\n url='http://pypilot.org/',\n packages=find_packages() if find_packages else ['pypilot', 'pypilot/pilots', 'pypilot/arduino_servo', 'ui', 'lcd', 'webapp', 'signalk', 'signalk/linebuffer', 'lcd/ugfx'],\n ext_modules = [arduino_servo_module, linebuffer_module, ugfx_module],\n# py_modules = ['pypilot/arduino_servo', 'signalk/linebuffer/linebuffer'],\n package_data={'lcd': ['font.ttf'] + locale_files,\n 'ui': ['*.png', '*.mtl', '*.obj'],\n 'webapp': ['static/*', 'templates/*']},\n# requires=['flask', 'gevent'], # webapp\n # dependency_links\t= ['https://github.com/adafruit/Adafruit_Nokia_LCD/tarball/master#egg=Adafruit-Nokia-LCD-0.1.0'],\n# install_requires\t= ['Adafruit-Nokia-LCD>=0.1.0'],\n entry_points={\n 'console_scripts': [\n 'pypilot=pypilot.autopilot:main',\n 'pypilot_boatimu=pypilot.boatimu:main',\n 'pypilot_servo=pypilot.servo:main',\n 'pypilot_webapp=webapp.webapp:main',\n 'pypilot_lcd=lcd.lcd:main',\n 'pypilot_rf=rf.rf:main',\n 'pypilot_control=ui.autopilot_control:main',\n 'pypilot_calibration=ui.autopilot_calibration:main',\n 'signalk_client=signalk.client:main',\n 'signalk_scope=signalk.scope:main',\n 'signalk_client_wx=signalk.client_wx:main',\n 'signalk_scope_wx=signalk.scope_wx:main',\n ]\n }\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"146423044","text":"import torch.nn as nn\r\nimport torch\r\n\r\nclass MyNet(nn.Module):\r\n\r\n def __init__(self):\r\n super().__init__()\r\n self.cnn_layer = nn.Sequential(\r\n # 224 x 224\r\n nn.Conv2d(3,16,3,1),\r\n nn.ReLU(inplace=True),\r\n nn.Conv2d(16,32,3,1),\r\n nn.ReLU(True),\r\n nn.MaxPool2d(2,2),#110\r\n nn.Conv2d(32,64,3,1),#108\r\n nn.ReLU(True),\r\n nn.MaxPool2d(2,2),#54\r\n nn.Conv2d(64,128,3,1),#52\r\n nn.ReLU(True),\r\n nn.MaxPool2d(2,2),#26\r\n nn.Conv2d(128,256,3,1),#24\r\n nn.ReLU(True),\r\n nn.AvgPool2d(2,2), #12\r\n nn.Conv2d(256,64,3,1),#10\r\n nn.ReLU(True)\r\n )\r\n\r\n self.cnn_layer2 = nn.Sequential(\r\n nn.Conv2d(64,128,10,1),\r\n nn.ReLU(True),\r\n nn.Conv2d(128,5,1,1)\r\n )\r\n # self.mlp_layer = nn.Sequential(\r\n # nn.Linear(10*10*64, 128),\r\n # nn.ReLU(),\r\n # nn.Linear(128,5)\r\n # )\r\n\r\n\r\n def forward(self, x):\r\n x = self.cnn_layer(x)\r\n # x = x.reshape(-1, 10*10*64)\r\n # x = self.mlp_layer(x)\r\n x = self.cnn_layer2(x)\r\n # 106 5 1 1\r\n # 106 5\r\n x = x.squeeze()\r\n category = torch.sigmoid(x[:,0])\r\n axes = torch.relu(x[:, 1:])# 底层都是调的torch.rule\r\n\r\n return category, axes\r\n\r\n\r\n","sub_path":"Mynet.py","file_name":"Mynet.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"28433149","text":"import itertools, re\nimport virgenereCipher, freqAnalysis, detectEnglish, fileOperation, utils\n\nLETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nSILENT_MODE = False\n# ?\nNUM_MOST_FREQ_LETTERS = 4\nMAX_KEY_LENGTH = 16\nNONLETTERS_PATTERN = re.compile('[^A-Z]')\n\ndef main():\n ciphertext = fileOperation.inputStringFromFile()\n hackedMessage = hackVigenere(ciphertext)\n\n if hackedMessage != None:\n print (hackedMessage[:100])\n fileOperation.outputStringToFile(hackedMessage)\n\n else:\n print ('Failed to hack encryption')\n\ndef findRepeatSequencesSpacints(message):\n message = NONLETTERS_PATTERN.sub('', message.upper())\n print (message[:100])\n\n seqSpacings = {}\n for seqLen in range(3,6):\n for seqStart in range(len(message) - seqLen):\n seq = message[seqStart:seqStart+seqLen]\n\n # look for the same content\n for i in range(seqStart,len(message) - seqLen):\n if message[i:i+seqLen] == seq:\n if seq not in seqSpacings:\n seqSpacings[seq] = []\n seqSpacings[seq].append(i - seqStart)\n\n return seqSpacings\n\ndef getUsefulFactors(num):\n # return factors lesss than MAX_KEY_LENGTH + 1\n # e.g. 144 -> [2,72,3,48,4,36,6,24,8,18,9,16,12]\n\n if num < 2:\n return []\n factors = []\n for i in range(2,MAX_KEY_LENGTH+1):\n if num % i == 0:\n factors.append(i)\n factors.append(num/i)\n\n if 1 in factors:\n factors.remove(1)\n\n return list(set(factors))\n\ndef getItemAtIndexOne(x):\n return x[1]\n\ndef getMostCommonFactors(seqFactors):\n factorCounts = {}\n\n for seq in seqFactors:\n factorList = seqFactors[seq]\n for factor in factorList:\n if factor not in factorCounts:\n factorCounts[factor] = 0\n factorCounts[factor] += 1\n\n factorsByCount = []\n for factor in factorCounts:\n if factor <= MAX_KEY_LENGTH:\n factorsByCount.append((factor,factorCounts[factor]))\n\n factorsByCount.sort(key = getItemAtIndexOne, reverse = True)\n\n return factorsByCount\n\ndef kasiskiExamination(ciphertext):\n # find out the sequences of 3 to 5 letters that occur multiple times\n\n repeatedSeqSpacings = findRepeatSequencesSpacints(ciphertext)\n\n seqFactors = {}\n for seq in repeatedSeqSpacings:\n seqFactors[seq] = []\n for spacing in repeatedSeqSpacings[seq]:\n seqFactors[seq].extend(getUsefulFactors(spacing))\n\n factorsByCount = getMostCommonFactors(seqFactors)\n\n # extract the factor counts from factorsByCount and put them in allLikelyKeyLength for using later\n\n allLikelyKeyLength = []\n for twoIntTuple in factorsByCount:\n allLikelyKeyLength.append(twoIntTuple[0])\n\n return allLikelyKeyLength\n\ndef getNthSubkeysLetters(n, keyLength, message):\n # get the substring with the spacing of keyLength\n message = NONLETTERS_PATTERN.sub('',message)\n\n i = n-1\n letters = []\n while i < len(message):\n letters.append(message[i])\n i += keyLength\n\n return ''.join(letters)\n\ndef attemptHackWithKeyLength(ciphertext, mostLikelyKeyLength):\n ciphertextUp = ciphertext.upper()\n allFreqScores = []\n for nth in range(1,mostLikelyKeyLength+1):\n nthLetters = getNthSubkeysLetters(nth, mostLikelyKeyLength, ciphertextUp)\n\n freqScores = []\n for possibleKey in LETTERS:\n # print (type(nthLetters))\n # print (nthLetters)\n decryptedText = virgenereCipher.decryptMessage(possibleKey,nthLetters)\n keyAndFreqMatchTuple = (possibleKey, freqAnalysis.englishFreqMatchScore(decryptedText))\n freqScores.append(keyAndFreqMatchTuple)\n\n freqScores.sort(key = getItemAtIndexOne, reverse = True)\n allFreqScores.append(freqScores[:NUM_MOST_FREQ_LETTERS])\n\n if not SILENT_MODE:\n for i in range(len(allFreqScores)):\n print('Possible letters for letter %s of the key: ' % (i+1), end = '')\n\n for freqScore in allFreqScores[i]:\n print('%s ' % freqScore[0], end = '')\n print()\n\n for indexes in itertools.product(range(NUM_MOST_FREQ_LETTERS),repeat = mostLikelyKeyLength):\n possibleKey = ''\n print (allFreqScores)\n for i in range(mostLikelyKeyLength):\n possibleKey += allFreqScores[i][indexes[i]][0]\n\n if not SILENT_MODE:\n print('Attempting with key: %s' % (possibleKey))\n\n decryptedText = virgenereCipher.decryptMessage(possibleKey, ciphertextUp)\n if detectEnglish.isEnglish(decryptedText):\n origCase = []\n for i in range(len(ciphertext)):\n if ciphertext[i].isupper():\n origCase.append(decryptedText[i].upper())\n else:\n origCase.append(decryptedText[i].lower())\n\n decryptedText = ''.join(origCase)\n\n print('Possible encryption hack with key %s:' % (possibleKey))\n print(decryptedText[:200])\n print()\n if utils.isDone():\n return decryptedText\n return None\n\ndef hackVigenere(ciphertext):\n allLikelyKeyLength = kasiskiExamination(ciphertext)\n if not SILENT_MODE:\n keyLengthStr = ''\n for keyLength in allLikelyKeyLength:\n keyLengthStr += str(keyLength) +' '\n\n print('Kasiski Exanmination results say the most likely key length are:' + keyLengthStr + '\\n')\n\n for keyLength in allLikelyKeyLength:\n if not SILENT_MODE:\n print('Attempting hack with key length %s (%s possible keys)...' % (keyLength, NUM_MOST_FREQ_LETTERS**keyLength))\n\n hackedMessage = attemptHackWithKeyLength(ciphertext, keyLength)\n if hackedMessage != None:\n break\n\n if hackedMessage == None:\n if not SILENT_MODE:\n print('Unable to hack message with likely key length(s). Bruteforcing key length...')\n for keyLength in range (1, MAX_KEY_LENGTH+1):\n if keyLength not in allLikelyKeyLength:\n print('Attemoting hack with key length %s(%s possible keys)...' % (keyLength, NUM_MOST_FREQ_LETTERS**keyLength))\n hackedMessage = attemptHackWithKeyLength(ciphertext, keyLength)\n\n if hackedMessage != None:\n break\n\n return hackedMessage\n\nif __name__ == '__main__':\n main()\n","sub_path":"cryptography/jiaocheng/virgenereHacker.py","file_name":"virgenereHacker.py","file_ext":"py","file_size_in_byte":6390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"226854364","text":"from oslo_log import log as logging\n\nfrom tempest import config\nfrom tempest import reporting\nfrom tempest import test\nfrom tempest import tvaultconf\nfrom tempest.api.workloadmgr import base\nfrom tempest.lib import decorators\n\nLOG = logging.getLogger(__name__)\nCONF = config.CONF\n\n\nclass WorkloadTest(base.BaseWorkloadmgrTest):\n\n credentials = ['primary']\n\n @classmethod\n def setup_clients(cls):\n super(WorkloadTest, cls).setup_clients()\n reporting.add_test_script(str(__name__))\n\n @test.pre_req({'type': 'basic_workload'})\n @decorators.attr(type='smoke')\n @decorators.idempotent_id('9fe07175-912e-49a5-a629-5f52eeada4c9')\n @decorators.attr(type='workloadmgr_api')\n def test_chargeback_api(self):\n try:\n if self.exception != \"\":\n LOG.debug(\"pre req failed\")\n reporting.add_test_step(str(self.exception), tvaultconf.FAIL)\n raise Exception(str(self.exception))\n LOG.debug(\"pre req completed\")\n\n # Run getVMProtected API :\n vm_protected = self.getVMProtected()\n if not vm_protected:\n reporting.add_test_step(\n \"Verified getVMProtected API\", tvaultconf.FAIL)\n LOG.debug(\"getVMProtected API failed\")\n raise Exception(\"getVMProtected API Failed\")\n else:\n reporting.add_test_step(\n \"Verified getVMProtected API\", tvaultconf.PASS)\n\n # Verify Instance ID :\n vm_id = self.vm_id\n counter = 0\n vm_protected_list = vm_protected['protected_vms']\n for vm in vm_protected_list:\n openstack_vm_id = vm_protected_list[counter]['id']\n LOG.debug(\" Openstack VM ID : \" + openstack_vm_id)\n if(vm_id == openstack_vm_id):\n LOG.debug(\" VM ID : \" + vm_id)\n instance_found = True\n break\n else:\n instance_found = False\n counter = counter + 1\n\n if(instance_found):\n reporting.add_test_step(\n \" Verified Instance ID \", tvaultconf.PASS)\n else:\n reporting.add_test_step(\n \" Verified Instance ID \", tvaultconf.FAIL)\n raise Exception(\" Verification for instance id failed \")\n reporting.test_case_to_write()\n\n except Exception as e:\n LOG.error(\"Exception: \" + str(e))\n reporting.set_test_script_status(tvaultconf.FAIL)\n reporting.test_case_to_write()\n","sub_path":"tempest/api/workloadmgr/chargeback/test_vms_protected.py","file_name":"test_vms_protected.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"415324128","text":"from flask import abort, Blueprint, request, jsonify\nfrom flask_jwt_extended import *\nfrom flasgger import swag_from\nfrom app.doc.user import PROFILE_SHOW_SPEC, PROFILE_UPDATE_SPEC\nfrom app.model import User\n\napi = Blueprint(__name__, 'user_api')\n\n\ndef _get_user_dict(user):\n return {\n 'id': user.id,\n 'name': user.name,\n 'descritpion': user.description,\n 'phone': user.phone,\n 'email': user.email,\n 'keywords': user.keywords,\n }\n\n\n@api.route('/user/profile/show', methods=['GET'])\n@swag_from(PROFILE_SHOW_SPEC)\n@jwt_required\ndef profile_show():\n user_id = get_jwt_identity()\n user = User.find_by_id(user_id)\n\n if not user:\n return (\n jsonify(reason='사용자를 조회할 수 없음. 액세스 토큰을 재발급 받아야 함'),\n 400,\n )\n\n return jsonify(\n profile=_get_user_dict(user),\n )\n\n\n@api.route('/user/profile/update', methods=['PUT'])\n@swag_from(PROFILE_UPDATE_SPEC)\n@jwt_required\ndef profile_update():\n form = request.form\n\n user_id = get_jwt_identity()\n user = User.find_by_id(user_id)\n\n if not user:\n return (\n jsonify(reason='사용자를 조회할 수 없음. 액세스 토큰을 재발급 받아야 함'),\n 400,\n )\n\n name = form.get('form')\n description = form.get('description')\n phone = form.get('phone')\n email = form.get('email')\n keywords = form.get('keywords')\n\n user.update(\n name=name or user.name,\n description=description or user.description,\n phone=phone or user.phone,\n email=email or user.email,\n keywords=keywords or user.keywords,\n )\n\n return jsonify(\n updated=_get_user_dict(user)\n )\n","sub_path":"app/view/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"36760979","text":"\"\"\"\n This spider is a JazzCoXML spider created on top of the XMLSpider\n scrapy crawl jazz_co_xml -a extract=1 -a url=\"http://app.jazz.co/feeds/linkedin\"\n\n sample url:\n http://app.jazz.co/feeds/linkedin\n\"\"\"\n\nfrom brightcorp.base.xmlspider import XMLSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom scrapy.selector import Selector\nfrom brightcorp.processors import Prefix, RemoveBadElements\n\n\nclass JazzCoXML(XMLSpider):\n\n follow_job_url = False\n name = 'jazz_co_xml'\n tag = 'job'\n\n field_xpaths = {\n 'title': '//title/text()',\n 'company': '//company/text()',\n 'location': '//location/text()',\n 'url': '//applyUrl/text()',\n }\n\n def parse_job(self, response):\n selector = Selector(response=response)\n loader = BrightcorpItemLoader(selector=selector)\n # Load field values into the job item (first the ones that need no modification)\n for field, xpath in self.field_xpaths.iteritems():\n loader.add_xpath(field, xpath)\n\n # Adding description different to removed anchor tags in it\n loader.add_xpath(\n 'description', '//description', RemoveBadElements(['a'])\n )\n\n # Add the reference number\n loader.add_value(\n 'referencenumber',\n selector.xpath('//partnerJobId/text()').extract(),\n Prefix(\"%s-\" % self.name)\n )\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/jazz_co_xml.py","file_name":"jazz_co_xml.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"222968389","text":"import pygame\nfrom pygame.locals import KEYDOWN, K_DOWN, K_LEFT, K_UP, K_RIGHT\nfrom os import path\nROOT_PATH = path.dirname(__file__)\n\n\nclass Drawable(pygame.sprite.Sprite):\n IMAGE = None\n\n def __init__(self, x, y):\n \"\"\"Our class's constructor.\"\"\"\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(path.join(ROOT_PATH, self.IMAGE))\n self.rect = self.image.get_rect()\n self.x = x\n self.y = y\n self.rect.x = x * 30\n self.rect.y = y * 30\n\n\nclass MacGyver(Drawable):\n IMAGE = \"m.png\"\n\n def __init__(self, x, y, item_list):\n \"\"\"This constructor uses the constructor of our Drawable class with the addition of the item_list.\"\"\"\n super().__init__(x, y)\n self.item_list = item_list\n\n @staticmethod\n def find_in_maze(maze):\n \"\"\"Reads our list of lists and returns the index of our Player.\"\"\"\n for row_index, x in enumerate(maze):\n for col_index, tile in enumerate(x):\n if tile == \"m\":\n return col_index, row_index\n return None\n\n def update(self, event, maze):\n \"\"\"Makes our instances of Macgyver move.\"\"\"\n shift_x = 0\n shift_y = 0\n if event.type == KEYDOWN and event.key == K_LEFT:\n shift_x = -1\n if event.type == KEYDOWN and event.key == K_RIGHT:\n shift_x = 1\n if event.type == KEYDOWN and event.key == K_UP:\n shift_y = -1\n if event.type == KEYDOWN and event.key == K_DOWN:\n shift_y = 1\n if (shift_x == -1 and self.x == 0) or \\\n (shift_x == 1 and self.x == 14) or \\\n (shift_y == 1 and self.y == 14) or \\\n (shift_y == -1 and self.y == 0):\n return\n next_tile = maze[self.y + shift_y][self.x + shift_x]\n if next_tile == \"w\":\n return\n maze[self.y][self.x] = \" \"\n self.x += shift_x\n self.y += shift_y\n maze[self.y][self.x] = \"m\"\n self.rect.x = self.x * 30\n self.rect.y = self.y * 30\n\n if next_tile in (\"Syringe\", \"Needle\", \"Ether\"):\n self.collect_item(next_tile)\n return\n\n def collect_item(self, next_tile):\n \"\"\"We use this to collect items in the maze.\"\"\"\n self.item_list.append(next_tile)\n\n\nclass Wall(Drawable):\n IMAGE = \"w.png\"\n\n\nclass Syringe(Drawable):\n IMAGE = \"syringe.png\"\n\n\nclass Needle(Drawable):\n IMAGE = \"needle.png\"\n\n\nclass Ether(Drawable):\n IMAGE = \"ether.png\"\n\n\nclass Guardian(Drawable):\n IMAGE = \"g.png\"\n","sub_path":"sprites.py","file_name":"sprites.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"117129871","text":"#!/usr/bin/python \n# -*-encoding=utf8 -*- \n# @Author : imooc\n# @Email : imooc@foxmail.com\n# @Created at : 2018/11/21\n# @Filename : juhe.py\n# @Desc :\n\n\nimport json\nimport requests\n\n\ndef weather(cityname):\n \"\"\"\n :param cityname: 城市名字\n :return: 返回实况天气\n \"\"\"\n # cityname = '北京'\n key = '20d68abaec5f1fd17391a8f3ef734379'\n api = 'http://apis.juhe.cn/simpleWeather/query'\n params = 'city=%s&key=%s' % (cityname, key)\n url = api + '?' + params\n # print(url)\n response = requests.get(url=url)\n json_data = json.loads(response.text)\n # print('jsondata:')\n # print(json_data)\n result = json_data.get('result')\n\n\n realtime = result.get('realtime')\n response = dict()\n response['temperature'] = realtime.get('temperature')\n response['humidity'] = realtime.get('humidity')\n response['info'] = realtime.get('info')\n response['direct'] = realtime.get('direct') # 湿度\n response['power'] = realtime.get('power')\n # print(response)\n return response\n\n\nif __name__ == '__main__':\n data = weather('北京')\n","sub_path":"thirdparty/juhe.py","file_name":"juhe.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"566255935","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom datetime import datetime\n\nfrom statsmodels.tsa.holtwinters import ExponentialSmoothing\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nfrom pandas.plotting import register_matplotlib_converters\nfrom statsmodels.tsa.seasonal import STL\nfrom scipy.stats import boxcox\nfrom scipy.special import inv_boxcox\n\nfrom db_connect import dbConnect\nfrom data_preprocess import DataCleaning, DataQualityCheck\n\n## define sale_type\nsale_type = 'retail'\n## Read data\ndb_c = dbConnect()\nraw_data = db_c.read_stakeholder_db()\n\n## Clean data\ndc = DataCleaning()\ndf = raw_data.copy()\ndf = dc.read_data(df)\ndf = dc.remove_zeros(df)\ndf = dc.convert_dtypes(df)\n\n## load qc table to find candidate time series\ntablename = 'qc_'+sale_type\nqc = db_c.read_analytical_db(tablename)\ncandidate = qc[qc['DQI_cat']=='great'].iloc[1,:]\n# Specify condition for selection of subset\n# Note: cutoff-date to avoid large data gap, this can be automated later\ncutoff_date = '2011-09-20'\n\n# selected time series\nMARKET = candidate['market']\nPRODUCT = candidate['product']\nSOURCE = candidate['source']\nprint(f'Market: {MARKET}, Product:{PRODUCT}, Source: {SOURCE}')\n\n# apply filters\ncond1 = (df['product']==PRODUCT)\ncond2 = (df['source']==SOURCE)\ncond3 = (df['market'] == MARKET)\n# subset is the selected dataframe with both wholesale and retail and other infos \nsubset = df[cond1 & cond2 & cond3].sort_values(by='date', ascending=True).set_index('date')\n\n# get speficied sale type data\nsale_cols = ['retail', 'wholesale']\nsale_cols.remove(sale_type)\nsale_df = subset.drop(columns=sale_cols)\n\n# remove outliers before remove duplicates\ny = sale_df[sale_type]\nlower_bound, upper_bound = y.quantile(.05), y.quantile(.90)\nidx = y.between(lower_bound, upper_bound)\nsale_df = sale_df[idx]\n\n# remove duplicates\nidx = ~sale_df.index.duplicated(keep='first')\nsale_df = sale_df[idx]\n\n# construct data sample with complete time frame\ndqc = DataQualityCheck()\nyt = dqc.day_by_day(sale_df[sale_type]) \n\n# interpolate for missing values\nyi = yt.interpolate(method='nearest')\nplt.plot(yi)\n\n\n# Check data stationarity\n# plot autocorrelation function to decide lagging\n# fig = plt.figure(figsize=(11, 10))\n# ax = fig.add_subplot(211)\n# plot_acf(yi, lags=50, ax=ax)\n# ax2 = fig.add_subplot(212)\n# plot_pacf(yi, lags=50, method='ols',ax=ax2)\n# plt.show()\n\n## transform data: boxcox, deseasonalize, detrend\n# boxcox to achieve stationarity in variance\ny_trans, lam = boxcox(yi.values.flatten())\n\ny_trans = pd.Series(y_trans, index=yi.index)\n\nresults = STL(y_trans).fit()\nresults.plot()\nplt.show()\n# deseasonal, detrend:\ny_dd = results.resid\n\n###Predict using Holt Winter’s Exponential Smoothing (HWES), time series with trend and seasonal component\n# a manual split\n\nn_test = int(0.2 * len(y_trans))\n\ntrain, test=y_trans[:-n_test], y_dd[-n_test:]\n\nmodel = ExponentialSmoothing(train, \n trend='add', \n seasonal='add', \n seasonal_periods=30, \n damped=True)\n\nhw_model = model.fit(optimized=True, use_boxcox=False, remove_bias=False)\n# optimized include smoothing level, slope, seasonal, and damping slope\n\npred = hw_model.predict(start=test.index[0], end=test.index[-1])\n\n# inverse of boxcox: inv_boxcox(y_trans, lam)\npred = inv_boxcox(pred, lam)\n\nfig = plt.figure(figsize=(20,6))\nplt.plot(train.index, train, label='Train')\nplt.plot(test.index, test, label='Test')\nplt.plot(pred.index, pred, label='Holt-Winters')\nplt.legend(loc='best')\nplt.show()\n","sub_path":"hw-forecast/app/test/test_holtwinter_old.py","file_name":"test_holtwinter_old.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"125911435","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nfrom env.env.envs import factory\nfrom swellex.audio.config import get_proj_zr, get_proj_zs\n\n\"\"\"\nDescription:\nLook at dk/dz for swellex\n\nDate:\n01/19/2020\n\nAuthor: Hunter Akins\n\nInstitution: Scripps Institution of Oceanography, UC San Diego\n\"\"\"\n\nif __name__ == '__main__':\n proj_str = 's5_deep' \n depth_vals = np.linspace(180, 260, 30)\n source_freq = 50\n \n env_builder = factory.create('swellex')\n env = env_builder()\n zr= get_proj_zr(proj_str)\n zs = get_proj_zs(proj_str)\n dz,dr,zmax, rmax = 0.5, 10, 216.5, 10*1e3\n folder, fname= 'at_files/', 'swell'\n env.add_source_params(source_freq, zs, zr)\n env.add_field_params(dz, zmax, dr, rmax)\n r_r = np.array([1e3, 2*1e3])\n \n for depth in depth_vals:\n env.change_depth(depth)\n p, pos = env.run_model('kraken_custom_r', folder, fname, zr_flag=True,custom_r=r_r)\n num_modes = env.modes.M\n print('num modes', num_modes)\n print(env.modes.k)\n plt.scatter([depth]*num_modes, env.modes.k.real)\n plt.xlabel('Environment depth (m)')\n plt.ylabel('Modal wavenumbers (1/m)')\n plt.suptitle('k(bottom depth)')\n plt.show()\n","sub_path":"audio/dkdz.py","file_name":"dkdz.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"193000929","text":"# This file is placed in the Public Domain.\n\n\n\"thread\"\n\n\nimport queue\nimport threading\n\n\nfrom ..utility import name\n\n\nfrom .event import Event\n\n\ndef __dir__():\n return (\n 'Thread',\n 'launch'\n )\n\n\n__all__ = __dir__()\n\n\nclass Thread(threading.Thread):\n\n def __init__(self, func, thrname, *args, daemon=True):\n super().__init__(None, self.run, name, (), {}, daemon=daemon)\n self._result = None\n self.name = thrname or name(func)\n self.queue = queue.Queue()\n self.queue.put_nowait((func, args))\n self.sleep = None\n\n def __iter__(self):\n return self\n\n def __next__(self):\n for k in dir(self):\n yield k\n\n def join(self, timeout=None):\n super().join(timeout)\n return self._result\n\n def run(self) -> None:\n func, args = self.queue.get()\n self._result = func(*args)\n\n\ndef launch(func, *args, **kwargs):\n thrname = kwargs.get(\"name\", None)\n if not thrname and args and isinstance(args[0], Event):\n thrname = args[0].txt\n else:\n thrname = name(func)\n thr = Thread(func, thrname, *args)\n thr.start()\n return thr\n","sub_path":"rssbot/runtime/thread.py","file_name":"thread.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"636965879","text":"import pymysql\nimport re\n\ndb = pymysql.connect(host=\"localhost\",\n port=3306,\n user=\"root\",\n password=\"123456\",\n database=\"dict\",\n charset=\"utf8\")\n# 获取游标 (操作数据库,执行sql语句)\ncur = db.cursor()\n\ndict_txt = open(\"dict.txt\")\nid = 0\n\nfor line in dict_txt:\n c01 = re.search(r\".*? \", line)\n # print(c01.group())\n word_name = c01.group()\n c02 = re.search(r\" .*\", line)\n # print(c02.group().strip())\n meaning = c02.group().strip()\n id += 1\n\n try:\n\n sql = \"insert into words (id,word_name,meaning) values (%s,%s,%s)\"\n\n # 可以使用列表直接给sql语句的values传值\n cur.execute(sql, [id, word_name, meaning]) # 执行sql语句\n\n db.commit() # 将写操作提交,可以多次写操作一同提交\n\n except Exception as e:\n db.rollback() # 退回到commit执行之前的数据库状态\n print(e)\n\n# 关闭数据库\ncur.close() # 游标失效\ndb.close() # 数据库中断\n","sub_path":"part_02_system_programming/python_project_month02/search_dictionary_offline/test_module/store_word_in_database.py","file_name":"store_word_in_database.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"79011616","text":"# Copyright 2021 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\n\nimport mindspore.context as context\nimport mindspore.nn as nn\nfrom mindspore import Tensor\nfrom mindspore.ops.operations.array_ops import TensorScatterElements\n\ncontext.set_context(mode=context.GRAPH_MODE, device_target=\"Ascend\")\n\n\nclass Net(nn.Cell):\n def __init__(self):\n super(Net, self).__init__()\n self.scatter_elements = TensorScatterElements(0)\n\n def construct(self, data, indices, updates):\n return self.scatter_elements(data, indices, updates)\n\n\ndef test_net():\n data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]).astype(np.float32)\n indices = np.array([[1, 0, 2], [0, 2, 1]]).astype(np.int32)\n updates = np.array([[0, 0, 0], [0, 0, 0]]).astype(np.float32)\n net = Net()\n tdata = Tensor(data)\n tindices = Tensor(indices)\n tupdates = Tensor(updates)\n output = net(tdata, tindices, tupdates)\n print(output.asnumpy())\n assert np.all([[0.0, 0.0, 3.0], [0.0, 5.0, 0.0], [7.0, 0.0, 0.0]] == output.asnumpy())\n","sub_path":"tests/st/ops/ascend/test_aicpu_ops/test_tensor_scatter_elements.py","file_name":"test_tensor_scatter_elements.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"199996748","text":"\nimport os\nimport time\n\nDESK = 'd:\\\\'\n\nSAVE_FILE = 'd:\\\\info.txt'\n\nFILE_EXT = ['bmp','jpeg','gif','psd','png','jpg']\n\nmy_dirs = []\nmy_files = []\n\nFILES_NUMBER = 0\n\nRIGHT_FILES_NUMBER = 0\n\nNOT_RIGHT_FILES_NUMBER = 0\n\nDIR_NUMBER = 0\n\ndef listdir(dir_path):\n if os.path.exists(dir_path):\n return os.listdir(dir_path)\n else:\n return 'Folder'+ dir_path + 'Not Exist'\n\ndef search_files(path,name):\n if not os.path.isdir(path) and not os.path.isfile(path):\n return False\n path = os.path.join(path,name)\n if os.path.isfile(path):\n global FILES_NUMBER\n FILES_NUMBER = FILES_NUMBER + 1\n lists = path.split('.')\n #print('============================================',lists)\n file_ext = lists[-1]\n if file_ext in FILE_EXT:\n global RIGHT_FILES_NUMBER\n RIGHT_FILES_NUMBER = RIGHT_FILES_NUMBER + 1\n global my_files\n now = str(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))\n size = str(get_file_size(path))\n my_files.append(now+' '+path+' '+size+'\\n')\n print('File ',path)\n else:\n global NOT_RIGHT_FILES_NUMBER\n NOT_RIGHT_FILES_NUMBER = NOT_RIGHT_FILES_NUMBER + 1\n elif os.path.isdir(path):\n global DIR_NUMBER\n DIR_NUMBER = DIR_NUMBER + 1\n for name in listdir(path):\n #print(os.path.join(path,name))\n search_files(path,name)\n\ndef get_file_size(path):\n if os.path.exists(path):\n return os.path.getsize(path)\n\ndef write_info(content):\n if os.path.exists(path):\n with open(SAVE_FILE,'w+') as fp:\n fp.write(content)\n fp.flush()\n fp.close()\n else:\n print('File {}Not Exist '.format(SAVE_FILE))\n\ndef read_info():\n if os.path.exists(path):\n with open(SAVE_FILE,'r+') as fp:\n for line in fp:\n print(line)\n else:\n print('File {}Not Exist '.format(SAVE_FILE))\nif __name__ == '__main__':\n # for d in listdir(DESK):\n # my_dirs.append(os.path.join(DESK,d))\n # print(my_dirs)\n\n my_dir = ['d:\\\\fc']\n for path in my_dir:\n search_files(path,'')\n print('#' * 50)\n print(my_files)\n print('#' * 50)\n print('Start Writing...')\n content = ''.join(my_files)\n write_info(content)\n print('#' * 50)\n print('Starting Reading ...')\n read_info()\n print('#' * 50)\n print('Folder count {0} file count {1}'.format(DIR_NUMBER,FILES_NUMBER))\n print('require file count {0},not require file count {1}'.format(RIGHT_FILES_NUMBER,NOT_RIGHT_FILES_NUMBER))\n","sub_path":"corp_sr/oss/test_find_data.py","file_name":"test_find_data.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"617228482","text":"'''\nCreated on 23 juil. 2014\n\n@author: http://ubuntuforums.org/showthread.php?t=1215042\n'''\n\n\ndef get_ip_address():\n \"\"\"\n @author: http://ubuntuforums.org/showthread.php?t=1215042\n \"\"\"\n import socket\n#=========================================================================\n# 1: Use the gethostname method\n#\n# ipaddr = socket.gethostbyname(socket.gethostname())\n# if not(ipaddr.startswith('127')):\n# print('Can use Method 1: ' + ipaddr)\n# return ipaddr\n#\n# 2: Use outside connection\n# '''\n# Source:\n# http://commandline.org.uk/python/how-to-find-out-ip-address-in-python/\n# '''\n#\n# ipaddr = ''\n# s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n# try:\n# s.connect(('google.com', 0))\n# ipaddr = s.getsockname()[0]\n# print('Can used Method 2: ' + ipaddr)\n# return ipaddr\n# except:\n# pass\n#=========================================================================\n\n # 3: Use OS specific command\n import subprocess\n import platform\n ipaddr = ''\n os_str = platform.system().upper()\n try:\n if os_str == 'LINUX':\n\n # Linux:\n arg = 'ip route list'\n p = subprocess.Popen(arg, shell=True, stdout=subprocess.PIPE)\n data = p.communicate()\n sdata = data[0].split()\n ipaddr = sdata[sdata.index('src') + 1]\n #netdev = sdata[ sdata.index('dev')+1 ]\n #print('Can used Method 3: ' + ipaddr)\n return ipaddr\n\n elif os_str == 'WINDOWS':\n\n # Windows:\n arg = 'route print 0.0.0.0'\n p = subprocess.Popen(arg, shell=True, stdout=subprocess.PIPE)\n data = p.communicate()\n strdata = data[0].decode()\n sdata = strdata.split()\n\n while len(sdata) > 0:\n if sdata.pop(0) == 'Netmask':\n if sdata[0] == 'Gateway' and sdata[1] == 'Interface':\n ipaddr = sdata[6]\n break\n #print('Can used Method 4: ' + ipaddr)\n return ipaddr\n except:\n return \"Adresse IP inconnue\"\n","sub_path":"utils_sig40/GetIP.py","file_name":"GetIP.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"236228909","text":"from math import sqrt\nfrom BlackHoleFiles.game_circle import game_circle\nimport pygame\nimport time\n\nfrom boardentry import BoardEntry\n\ndef get_square_grid(screen):\n '''\n Returns a list of points in a square grid to place circles.\n If N rows of circles are to be placed, the grid has dimension\n N * (2N -1). This is to achieve the pyramid pattern.\n '''\n pattern = [i+1 for i in range(6)]\n points = []\n side = 2 * len(pattern) - 1\n screen_size = screen.get_size()\n width = int(0.5 * screen_size[0]) # Use 50% of the width\n height = int(0.8 * screen_size[1]) # Use 80% of the height\n delta_w = int(screen_size[0] * 0.25) # Middle 50% of the width\n delta_h = int(screen_size[1] * 0.2) # Lower 80% of the height\n for i in range(len(pattern)):\n row = []\n for j in range(side):\n # row contains tuples of the form (x,y)\n row.append((delta_w + j * (width // side), delta_h + i * (height // len(pattern))))\n points.append(row)\n return points\n\ndef get_centres(screen):\n '''\n Extrapolates the centres of the circles from the square grid.\n '''\n pattern = [i+1 for i in range(6)]\n centres = []\n points = get_square_grid(screen)\n for i in range(len(pattern)):\n start_x = (len(points[i])//2)-i #starting index of a circle in the ith row\n for j in range(pattern[i]):\n centres.append(points[i][start_x + 2*j]) #centre of the jth circle in the row\n return centres\n\ndef get_radius(centres):\n '''\n Extrapolates ideal radius for the screen size and number of\n circles.\n '''\n p1,p2 = centres[0], centres[1]\n #Use distance formula\n return int(sqrt((p1[0]-p2[0])**2 + (p1[1] - p2[1])**2))//2\n\n\ndef correct_colour(player):\n if player:\n return 0, 0, 255\n return 255, 0, 0\n\n\ndef draw_static(board_dict, time_limit = 5):\n pygame.init() # Initialize pygame\n pygame.font.init() # Initialize fonts\n screen_size = (1024, 576) # Initialize screen_size\n screen = pygame.display.set_mode(screen_size)\n pygame.display.set_caption(\"Black Hole Static\")\n screen.fill((0, 213, 242))\n circles = []\n centres = get_centres(screen)\n radius = get_radius(centres)\n for centre in centres:\n ob = game_circle(centre=centre, radius=radius)\n circles.append(ob)\n for key in board_dict:\n index = key-1\n if board_dict[key]:\n col = correct_colour(board_dict[key][1])\n val = board_dict[key][0]\n circles[index].update_circle(col, val)\n\n for circle in circles:\n circle.draw_circle(screen)\n\n done = False\n st = time.time()\n while not done:\n events = pygame.event.get()\n for event in events:\n if event.type == pygame.QUIT:\n done = True\n continue\n if time.time() - st > time_limit:\n done = True\n continue\n pygame.display.flip()\n\n pygame.quit()\n # quit()\n\n\nclass BHBoard(object):\n\n P1_COL = (255, 0, 0)\n P2_COL = (0, 0, 255)\n\n def __init__(self, screen):\n self.state = [None for index in range(21)]\n self.centres = get_centres(screen)\n self.radius = get_radius(self.centres)\n self.circles = []\n for centre in self.centres:\n ob = game_circle(centre=centre, radius=self.radius)\n self.circles.append(ob)\n\n def draw(self, screen):\n for circle in self.circles:\n circle.draw_circle(screen)\n\n def update_circles(self):\n for index in range(len(self.state)):\n if self.state[index]:\n circle_index = index\n colour = correct_colour(self.state[index].player)\n value = self.state[index].value\n self.circles[circle_index].update_circle(colour, value)\n\n def update_to_state(self, t_state):\n self.state = t_state\n self.update_circles()\n\n\n def update_from_input(self, mpos):\n move_count = sum([1 for key in range(len(self.state)) if self.state[key]])\n player = move_count % 2\n value = move_count//2 + 1\n move_tuple = BoardEntry(value, player)\n for circle_index, circle in enumerate(self.circles):\n if circle.is_clicked(mpos) and circle.colour == (0, 0, 0):\n index = circle_index\n self.state[index] = move_tuple\n self.update_circles()\n\n\n\nif __name__ == \"__main__\":\n S_State = {\n 1: (1, 1),\n 2: (2, 0),\n 3: (9, 1),\n 4: (4, 0),\n 5: (1, 0),\n 6: (3, 1),\n 7: (4, 1),\n 8: (5, 0),\n 9: (3, 0),\n 10: (5, 1),\n 11: (6, 0),\n 12: (6, 1),\n 13: (9, 0),\n 14: (2, 1),\n 15: None,\n 16: (7, 0),\n 17: (7, 1),\n 18: (8, 0),\n 19: None,\n 20: None,\n 21: (8, 1)\n }\n # draw_static(S_State)\n state = dict(zip([i + 1 for i in range(21)], [None for i in range(21)]))\n print (state)\n","sub_path":"BlackHoleAI-master/BlackHoleFiles/drawblackhole.py","file_name":"drawblackhole.py","file_ext":"py","file_size_in_byte":5011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"91194306","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 8 15:43:10 2017\n\n@author: changlongjiang\n\"\"\"\n\n\nimport numpy as np\nfrom matplotlib import pyplot\nimport pandas as pd\nimport os\nfrom pandas import read_csv\nfrom pandas import DataFrame\nfrom pandas import concat\nfrom sklearn.preprocessing import MinMaxScaler\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nimport keras.backend as K\n\ndef matthews_correlation(y_true, y_pred):\n \"\"\"Matthews correlation metric.\n +# Aliases\n \n It is only computed as a batch-wise average, not globally.\n\n Computes the Matthews correlation coefficient measure for quality\n of binary classification problems.\n \"\"\"\n y_pred_pos = K.round(K.clip(y_pred, 0, 1))\n y_pred_neg = 1 - y_pred_pos\n\n y_pos = K.round(K.clip(y_true, 0, 1))\n y_neg = 1 - y_pos\n\n tp = K.sum(y_pos * y_pred_pos)\n tn = K.sum(y_neg * y_pred_neg)\n\n fp = K.sum(y_neg * y_pred_pos)\n fn = K.sum(y_pos * y_pred_neg)\n\n numerator = (tp * tn - fp * fn)\n denominator = K.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))\n\n return numerator / (denominator + K.epsilon())\n\n\ndef precision(y_true, y_pred):\n \"\"\"Precision metric.\n\n Only computes a batch-wise average of precision.\n\n Computes the precision, a metric for multi-label classification of\n how many selected items are relevant.\n \"\"\"\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision\n\n\ndef recall(y_true, y_pred):\n \"\"\"Recall metric.\n\n Only computes a batch-wise average of recall.\n\n Computes the recall, a metric for multi-label classification of\n how many relevant items are selected.\n \"\"\"\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n recall = true_positives / (possible_positives + K.epsilon())\n return recall\n\n\ndef fbeta_score(y_true, y_pred, beta=1):\n \"\"\"Computes the F score.\n\n The F score is the weighted harmonic mean of precision and recall.\n Here it is only computed as a batch-wise average, not globally.\n\n This is useful for multi-label classification, where input samples can be\n classified as sets of labels. By only using accuracy (precision) a model\n would achieve a perfect score by simply assigning every class to every\n input. In order to avoid this, a metric should penalize incorrect class\n assignments as well (recall). The F-beta score (ranged from 0.0 to 1.0)\n computes this, as a weighted mean of the proportion of correct class\n assignments vs. the proportion of incorrect class assignments.\n\n With beta = 1, this is equivalent to a F-measure. With beta < 1, assigning\n correct classes becomes more important, and with beta > 1 the metric is\n instead weighted towards penalizing incorrect class assignments.\n \"\"\"\n if beta < 0:\n raise ValueError('The lowest choosable beta is zero (only precision).')\n\n # If there are no true positives, fix the F score at 0 like sklearn.\n if K.sum(K.round(K.clip(y_true, 0, 1))) == 0:\n return 0\n\n p = precision(y_true, y_pred)\n r = recall(y_true, y_pred)\n bb = beta ** 2\n fbeta_score = (1 + bb) * (p * r) / (bb * p + r + K.epsilon())\n return fbeta_score\n\n\ndef fmeasure(y_true, y_pred):\n \"\"\"Computes the f-measure, the harmonic mean of precision and recall.\n\n Here it is only computed as a batch-wise average, not globally.\n \"\"\"\n return fbeta_score(y_true, y_pred, beta=1)\n\ndef series_to_supervised(data, n_in=1, n_out=1, dropnan=True):\n\tn_vars = 1 if type(data) is list else data.shape[1]\n\tdf = DataFrame(data)\n\tcols, names = list(), list()\n\t# input sequence (t-n, ... t-1)\n\tfor i in range(n_in, 0, -1):\n\t\tcols.append(df.shift(i))\n\t\tnames += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]\n\t# forecast sequence (t, t+1, ... t+n)\n\tfor i in range(0, n_out):\n\t\tcols.append(df.shift(-i))\n\t\tif i == 0:\n\t\t\tnames += [('var%d(t)' % (j+1)) for j in range(n_vars)]\n\t\telse:\n\t\t\tnames += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]\n\t# put it all together\n\tagg = concat(cols, axis=1)\n\tagg.columns = names\n\t# drop rows with NaN values\n\tif dropnan:\n\t\tagg.dropna(inplace=True)\n\treturn agg\n\npath = \"/Users/xogoss/Documents/boston/CS542/project/Sick_Team_3-master/proagain\" #文件夹目录 \nfiles= os.listdir(path)\nfiles = files[1:]\ns=[]\nfor i in files:\n k = read_csv('proagain/'+i, header=0, index_col=0)\n k = k.drop(k.index[0])\n s.append(k)\ndataset = pd.concat(s)\n\n\n#dataset = read_csv('7_4.csv', header=0, index_col=0)\n\nvalues = dataset.values\ndataset.head()\n\nprint(dataset.head(2))\nprint(\"==========================\")\n\n\nvalues = values.astype('float32')\n\n\n#Normalize the data\nscaler = MinMaxScaler(feature_range=(0, 1))\nscaled = scaler.fit_transform(values)\n# frame as supervised learning\nreframed = series_to_supervised(scaled, 1, 1)\n\nreframed.head()\nprint(reframed.head(0))\nprint(\"=============================\")\nreframed.drop(reframed.columns[[35, 36]], axis=1, inplace=True) #drop some column I don't want to include\nprint(reframed.head(2))\n\n\n#split train and test\nvalues = reframed.values\n#X = np.concatenate((values[:,:29],values[:,30:]),axis=1)\n#y = values[:,29]\n#train_X, test_X, train_y, test_y = train_test_split(X, y, test_size=0.05)\nn_train_hours = -50000\ntrain = values[:n_train_hours, :]\ntest = values[n_train_hours:, :]\n# split into input and outputs\nX = np.concatenate((train[:,:29], train[:,30:]), axis=1)\ntrain_X = np.concatenate((train[:,:29], train[:,30:]), axis=1)\ntrain_y = train[:, 29]\ntest_X = np.concatenate((test[:,:29], test[:,30:]), axis=1)\ntest_y = test[:, 29]\n\n# reshape input to be 3D [samples, timesteps, features]\ntrain_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1]))\ntest_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1]))\nprint(train_X.shape, train_y.shape, test_X.shape, test_y.shape)\n \n# design network\nmodel = Sequential()\nmodel.add(LSTM(50, input_shape=(train_X.shape[1], train_X.shape[2])))\nmodel.add(Dense(1))\nmodel.compile(loss='binary_crossentropy', optimizer='adam',metrics=[precision, recall, fmeasure])\n# fit network\nhistory = model.fit(train_X, train_y, epochs=50, batch_size=72, validation_data=(test_X, test_y), verbose=2, shuffle=False)\n# plot history\npyplot.plot(history.history['loss'], label='train_loss')\npyplot.plot(history.history['val_loss'], label='test_loss')\npyplot.plot(history.history['fmeasure'], label='train_f1')\npyplot.plot(history.history['val_fmeasure'], label='test_f1')\npyplot.plot(history.history['precision'], label='train_p')\npyplot.plot(history.history['val_precision'], label='test_p')\npyplot.plot(history.history['recall'], label='train_r')\npyplot.plot(history.history['val_recall'], label='test_r')\npyplot.legend()\npyplot.show()\n''' \n# make a prediction\nyhat = model.predict(test_X)\ntest_X = test_X.reshape((test_X.shape[0], test_X.shape[2]))\n# invert scaling for forecast\ninv_yhat = concatenate((yhat, test_X[:, 1:]), axis=1)\nprint('inv_hat shape', inv_yhat.shape)\ninv_yhat = scaler.inverse_transform(inv_yhat)\ninv_yhat = inv_yhat[:,0]\n# invert scaling for actual\ntest_y = test_y.reshape((len(test_y), 1))\ninv_y = concatenate((test_y, test_X[:, 1:]), axis=1)\ninv_y = scaler.inverse_transform(inv_y)\ninv_y = inv_y[:,0]\n# calculate RMSE\nrmse = sqrt(mean_squared_error(inv_y, inv_yhat))\nprint('Test RMSE: %.3f' % rmse)\n'''\n\n\n","sub_path":"Sequencial_data_preprocessing_withTimeInterval.py","file_name":"Sequencial_data_preprocessing_withTimeInterval.py","file_ext":"py","file_size_in_byte":7530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"283387744","text":"\"\"\"\nDRS Registration Document Model package.\nCopyright (c) 2018 Qualcomm Technologies, Inc.\n All rights reserved.\n Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the\n limitations in the disclaimer below) provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided with the distribution.\n * Neither the name of Qualcomm Technologies, Inc. nor the names of its contributors may be used to endorse or promote\n products derived from this software without specific prior written permission.\n NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY\n THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\nfrom app import db\nfrom app.api.v1.helpers.utilities import Utilities\nfrom app.api.v1.models.documents import Documents\n\n\nclass RegDocuments(db.Model):\n \"\"\"Database model for regdocuments table.\"\"\"\n __tablename__ = 'regdocuments'\n\n id = db.Column(db.Integer, primary_key=True)\n filename = db.Column(db.String(100))\n\n reg_details_id = db.Column(db.Integer, db.ForeignKey('regdetails.id', ondelete='CASCADE'))\n document_id = db.Column(db.Integer, db.ForeignKey('documents.id', ondelete='CASCADE'))\n\n def __init__(self, filename):\n \"\"\"Constructor.\"\"\"\n self.filename = filename\n\n @staticmethod\n def get_document(reg_details_id, filename):\n \"\"\"Return documents of the current request.\"\"\"\n return RegDocuments.query.filter_by(reg_details_id=reg_details_id, filename=filename).first()\n\n @classmethod\n def bulk_create(cls, documents, reg_details, time):\n \"\"\"Create documents for a request in bulk.\"\"\"\n try:\n created_documents = []\n for name in documents:\n document = Documents.get_document_by_name(name, 1)\n reg_document = cls(filename='{0}_{1}'.format(time, documents[name].filename))\n reg_document.reg_details_id = reg_details.id\n reg_document.document_id = document.id\n reg_document.save()\n created_documents.append(reg_document)\n return created_documents\n except Exception:\n raise Exception\n\n @classmethod\n def bulk_update(cls, documents, reg_details, time):\n \"\"\"Update documents of a request in bulk.\"\"\"\n try:\n updated_documents = []\n for name in documents:\n document = Documents.get_document_by_name(name, 1)\n cls.trash_document(document.id, reg_details)\n reg_document = cls(filename='{0}_{1}'.format(time, documents[name].filename))\n reg_document.reg_details_id = reg_details.id\n reg_document.document_id = document.id\n reg_document.save()\n updated_documents.append(reg_document)\n return updated_documents\n except Exception:\n raise Exception\n\n @classmethod\n def trash_document(cls, type_id, reg_details):\n \"\"\"Purge documents of a request.\"\"\"\n try:\n document = cls.query.filter_by(document_id=type_id, reg_details_id=reg_details.id).one()\n cls.delete(document.id)\n Utilities.remove_file(document.filename, reg_details.tracking_id)\n except Exception:\n raise Exception\n\n @classmethod\n def delete(cls, document_id):\n \"\"\"Delete a document.\"\"\"\n try:\n cls.query.filter_by(id=document_id).delete()\n except Exception:\n raise Exception\n\n @classmethod\n def get_by_reg_id(cls, reg_id):\n \"\"\"Return a document by request id.\"\"\"\n documents = cls.query.filter_by(reg_details_id=reg_id).all()\n return documents\n\n @classmethod\n def get_by_id(cls, doc_id):\n \"\"\"Return a document by id.\"\"\"\n documents = cls.query.filter_by(id=doc_id).one()\n return documents\n\n def save(self):\n \"\"\"Save the current state of the model.\"\"\"\n try:\n db.session.add(self)\n db.session.flush()\n except Exception:\n db.session.rollback()\n raise Exception\n","sub_path":"app/api/v1/models/regdocuments.py","file_name":"regdocuments.py","file_ext":"py","file_size_in_byte":5144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"134923344","text":"import xlrd\nimport xlwt\n\n#initiallazing\n\n\nwb = xlrd.open_workbook(\"STDPY.xlsx\")\nws = wb.sheet_by_name(\"BOLTS\")\nwRows = ws.nrows\nwCol = ws.ncols\n\nwbOut = xlwt.Workbook(encoding=\"utf-8\")\nwsOut = wbOut.add_sheet(\"Sheet 1\")\n\n\n#Filling the lists\nboltNA = list()\nboltLen = list()\nboltTH = list()\nboltSL = list()\nboltSD = list()\nboltM = list()\nboltCo = list()\n\nfor i in range(1, wRows):\n boltNA.append(ws.cell(i, 0).value)\n boltLen.append(ws.cell(i, 9).value)\n boltTH.append(ws.cell(i, 10).value)\n boltSL.append(ws.cell(i, 15).value)\n boltSD.append(ws.cell(i, 16).value)\n boltM.append(ws.cell(i, 17).value)\n boltCo.append(ws.cell(i, 22).value)\n\nprint(\"Numero de parte {}\".format(boltNA))\nprint(\"Las longitudes por bolt son {}\".format(boltLen))\nprint(\"Las longitudes de TH {}\".format(boltTH))\nprint(\"Las longitudes de SL {}\".format(boltSL))\nprint(\"Las longitudes de SD {}\".format(boltSD))\nprint(\"Material del bolt {}\".format(boltM))\nprint(\"Precio por bolt: {}\".format(boltCo))\n\n#Bolt tuples\n\nboltsT = [() for i in range(1, wRows)]\n\nfor i in range(wRows-1):\n boltsT[i] = boltNA[i], boltLen[i], boltTH[i], boltSL[i], boltSD[i], boltM[i], boltCo[i]\n\n\nj = 0\ni = 0\nfor i in range(len(boltsT)):\n n = boltsT[i][0]\n si = boltsT[i][1]\n t = float(boltsT[i][2])\n sl = float(boltsT[i][3])\n sd = float(boltsT[i][4])\n m = boltsT[i][5]\n c = boltsT[i][6]\n\n for item in boltsT:\n n2 = str(item[0])\n si2 = item[1]\n t2 = item[2]\n sl2 = item[3]\n sd2 = item[4]\n m2 = item[5]\n c2 = item[6]\n # print(si)\n # print(si2)\n if si != 0 and n != n2:\n if (si -.05 <= si2 <= si+.05 and t-.05 <= t2 <= t+.05 and sl-.05 <= sl2 <= sl+.05 and sd <= sd2 <= sd and m == boltsT[j][5]):\n boltsT[i] = (boltsT[i] + ((\"Similar to: \" + n2),))\n\nfor item in boltsT:\n print(item)\n\n# for i in range(len(boltsT)):\n# if boltsT[i][7] is None:\n# boltsT[i][7] = ''\n# if boltsT[i][8] is None:\n# boltsT[i][8] = ''\n# if boltsT[i][9] is None:\n# boltsT[i][9] = ''\n# if boltsT[i][10] is None:\n# boltsT[i][10] = ''\n\n#\n# for i in range(len(boltsT)):\n# wsOut.write(i, 0, boltsT[i][0])\n# wsOut.write(i, 1, boltsT[i][1])\n# wsOut.write(i, 2, boltsT[i][2])\n# wsOut.write(i, 3, boltsT[i][3])\n# wsOut.write(i, 4, boltsT[i][4])\n# wsOut.write(i, 5, boltsT[i][5])\n# wsOut.write(i, 6, boltsT[i][6])\n\n\ncounter = 0\nfor item in boltsT:\n h = 0\n for huevos in item:\n # print(counter, h, huevos)\n wsOut.write(counter, h, huevos)\n h += 1\n counter += 1\n\n\nwbOut.save(\"Recommendations.xls\")\n","sub_path":"GE/ExcelPy.py","file_name":"ExcelPy.py","file_ext":"py","file_size_in_byte":2653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"564906246","text":"from .env_wrapper import EnvWrapper\nimport numpy as np\n\n\nclass BlueWrapper(EnvWrapper):\n def __init__(self, config):\n\n pos_control = config[\"pos_control\"]\n actuator = 'motor'\n if pos_control: actuator='position'\n env_kwargs = dict(port = 1050,\n visionnet_input = False,\n unity = False,\n world_path = '/u/home/urakamiy/doorgym/world_generator/world/pull_blue_right_v2_gripper_{}_lefthinge_single/'.format(actuator),\n pos_control = pos_control,\n ik_control = False)\n\n EnvWrapper.__init__(self, config['env'], env_kwargs)\n self.config = config\n\n print(self._true_action_space.high, self._true_action_space.low)\n print(self._norm_action_space.high, self._norm_action_space.low)\n\n def _convert_action(self, action):\n action = action.astype(np.float64)\n true_delta = self._true_action_space.high - self._true_action_space.low\n norm_delta = self._norm_action_space.high - self._norm_action_space.low\n action = (action - self._norm_action_space.low) / norm_delta\n action = action * true_delta + self._true_action_space.low\n action = action.astype(np.float32)\n return action\n\n def get_current_pos(self):\n return self.env.get_robot_joints()[:self.config[\"action_dim\"]]\n\n def step(self, action):\n # print(\"norm action: \",action)\n assert self._norm_action_space.contains(action)\n action = self._convert_action(action)\n # print(\"converted action: \", action)\n\n if self.env.pos_control:\n # print(\"current joints: \", self.get_current_pos())\n action += self.get_current_pos()\n # print(\"combined joints: \", action)\n\n # action = action.clip(self._true_action_space.low, self._true_action_space.high)\n # assert self._true_action_space.contains(action)\n # print(\"clipped action: \", action)\n\n # import sys\n # sys.exit(1)\n\n next_state, reward, terminal, _ = self.env.step(action.ravel())\n return next_state, reward, terminal\n\n def normalise_state(self, state):\n return state\n\n def normalise_reward(self, reward):\n return reward","sub_path":"env/blue.py","file_name":"blue.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"412900392","text":"# -*- coding: utf-8 -*-\nimport re\nfrom pytagcloud.lang.stopwords import get_stop_words\nfrom operator import itemgetter\n\n\ndef get_tag_counts(text):\n \"\"\"\n Search tags in a given text.\n \"\"\"\n words = map(lambda x: x.lower(), re.findall(r'[\\w-]+', text, re.UNICODE))\n stop_words = get_stop_words()\n counted = {}\n for word in words:\n if len(word) > 1 and word not in stop_words:\n if word in counted:\n counted[word] += 1\n else:\n counted[word] = 1\n return sorted(counted.iteritems(), key=itemgetter(1), reverse=True)\n","sub_path":"src/pytagcloud/lang/counter.py","file_name":"counter.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"551913034","text":"# -*- Mode:python; c-file-style:\"gnu\"; indent-tabs-mode:nil -*- */\n#\n# Copyright (C) 2014 Regents of the University of California.\n# Author: Jeff Thompson \n# See COPYING for copyright and distribution information.\n#\n\n\"\"\"\nThis module defines the ForwardingFlags class which holds the flags which\nspecify how the forwarding daemon should forward an interest for a registered\nprefix. We use a separate ForwardingFlags object to retain future compatibility\nif the daemon forwarding bits are changed, amended or deprecated.\n\"\"\"\n\nclass ForwardingFlags(object):\n \"\"\"\n Create a new ForwardingFlags object, possibly copying values from another\n object.\n\n :param ForwardingFlags value: (optional) If value is a ForwardingFlags, copy\n its values. If value is omitted, the type is the default with \"active\"\n and \"childInherit\" True and other flags False.\n \"\"\"\n def __init__(self, value = None):\n if value == None:\n self._active = True\n self._childInherit = True\n self._advertise = False\n self._last = False\n self._capture = False\n self._local = False\n self._tap = False\n self._captureOk = False\n elif type(value) is ForwardingFlags:\n # Copy its values.\n self._active = value._active\n self._childInherit = value._childInherit\n self._advertise = value._advertise\n self._last = value._last\n self._capture = value._capture\n self._local = value._local\n self._tap = value._tap\n self._captureOk = value._captureOk\n else:\n raise RuntimeError(\n \"Unrecognized type for ForwardingFlags constructor: \" +\n repr(type(value)))\n\n ACTIVE = 1\n CHILD_INHERIT = 2\n ADVERTISE = 4\n LAST = 8\n CAPTURE = 16\n LOCAL = 32\n TAP = 64\n CAPTURE_OK = 128\n\n def getForwardingEntryFlags(self):\n \"\"\"\n Get an integer with the bits set according to the flags as used by the\n ForwardingEntry message.\n\n :return: An integer with the bits set.\n :rtype: int\n \"\"\"\n result = 0\n\n if self._active :\n result |= ForwardingFlags.ACTIVE\n if self._childInherit:\n result |= ForwardingFlags.CHILD_INHERIT\n if self._advertise:\n result |= ForwardingFlags.ADVERTISE\n if self._last:\n result |= ForwardingFlags.LAST\n if self._capture:\n result |= ForwardingFlags.CAPTURE\n if self._local:\n result |= ForwardingFlags.LOCAL\n if self._tap:\n result |= ForwardingFlags.TAP\n if self._captureOk:\n result |= ForwardingFlags.CAPTURE_OK\n\n return result\n\n def setForwardingEntryFlags(self, forwardingEntryFlags):\n \"\"\"\n Set the flags according to the bits in forwardingEntryFlags as used by\n the ForwardingEntry message.\n\n :param int forwardingEntryFlags: An integer with the bits set.\n \"\"\"\n self._active = True if (forwardingEntryFlags &\n ForwardingFlags.ACTIVE) else False\n self._childInherit = True if (forwardingEntryFlags &\n ForwardingFlags.CHILD_INHERIT) else False\n self._advertise = True if (forwardingEntryFlags &\n ForwardingFlags.ADVERTISE) else False\n self._last = True if (forwardingEntryFlags &\n ForwardingFlags.LAST) else False\n self._capture = True if (forwardingEntryFlags &\n ForwardingFlags.CAPTURE) else False\n self._local = True if (forwardingEntryFlags &\n ForwardingFlags.LOCAL) else False\n self._tap = True if (forwardingEntryFlags &\n ForwardingFlags.TAP) else False\n self._captureOk = True if (forwardingEntryFlags &\n ForwardingFlags.CAPTURE_OK) else False\n\n def getActive(self):\n return self._active\n\n def getChildInherit(self):\n return self._childInherit\n\n def getAdvertise(self):\n return self._advertise\n\n def getLast(self):\n return self._last\n\n def getCapture(self):\n return self._capture\n\n def getLocal(self):\n return self._local\n\n def getTap(self):\n return self._tap\n\n def getCaptureOk(self):\n return self._captureOk\n","sub_path":"python/pyndn/forwarding_flags.py","file_name":"forwarding_flags.py","file_ext":"py","file_size_in_byte":4566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"629769337","text":"# 68996560 Zhengyi Xu 19758650 Lukun Han\nimport connectfour\nimport GameLogic\n\ngame=connectfour.new_game()\n\ndef ShowChessTable()->None:\n '''\n print chess table\n '''\n global game\n title=''\n for column_num in range(connectfour.BOARD_COLUMNS):\n title+='{} '.format(column_num+1)\n print(title)\n for i in range(connectfour.BOARD_ROWS):\n row = ''\n for column in game.board:\n if column[i] == 0:\n row += '. '\n if column[i] == 1:\n row += 'R '\n if column[i] == 2:\n row += 'Y '\n print(row)\n\ndef ResponseACT()->'game table':\n '''\n map move(including METHOD and COLUMN) on the table \n '''\n global game\n try:\n game_copy=game\n if GameLogic.METHOD=='POP':\n game=connectfour.pop(game_copy,GameLogic.COLUMN)\n elif GameLogic.METHOD=='DROP':\n game=connectfour.drop(game_copy,GameLogic.COLUMN)\n except connectfour.InvalidMoveError:\n print('Your move is invalid')\n except:\n raise\n\ndef ShowWinner()->'integer 10 or None':\n '''\n judge who is winner\n print winner\n '''\n global game # for use global variable\n if connectfour.winner(game)==connectfour.RED: # judge who is winner\n print('RED WIN') # print correct winner\n elif connectfour.winner(game)==connectfour.YELLOW:\n print('YELLOW WIN')\n else:\n return 10 # set up a default value for more convenient control in Online Version game\n\ndef connectfour_console():\n '''\n whole structure of console version connectfour\n '''\n global game # for use global variable\n while connectfour.winner(game)==connectfour.NONE: # if winner still not emerge: keep loop\n try:\n GameLogic.select_method() # request METHOD to user\n GameLogic.select_column() # request COLUMN to user\n ResponseACT() # map previous action in chess table\n ShowChessTable() # print chess table, a simple interface\n except connectfour.GameOverError: # when winner emerge: break loop for printing winner\n break\n except connectfour.InvalidMoveError: # alert user their move is invalid and keep game procedure again\n print('Your move is invalid')\n except:\n raise\n ShowWinner() # printing winner\n\nif __name__ == '__main__':\n connectfour_console() \n","sub_path":"python中级/四子棋/ConnectFour_Console.py","file_name":"ConnectFour_Console.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"590262959","text":"def spacer() -> str:\n return '\\n'\n\n\ndef imports() -> str:\n return '\\n'.join([\n 'from itertools import *',\n 'from functools import reduce',\n 'from pprint import PrettyPrinter',\n 'from typing import List, Tuple, Union, Optional',\n 'from helper import *',\n ])\n\n\ndef function_stubs() -> str:\n return '\\n'.join([\n 'def part1_solution(inputs):',\n ' pass',\n '',\n '',\n 'def part2_solution(inputs):',\n ' pass',\n ])\n\n\ndef main_func() -> str:\n return '\\n'.join([\n 'if __name__ == \"__main__\":',\n ' p = PrettyPrinter()',\n ' challenge = \"\"',\n '',\n ' print(\"----- Part 1 -----\")',\n ' part1 = part1_solution(challenge)',\n ' p.pprint(part1)',\n '',\n ' print(\"----- Part 2 -----\")',\n ' part2 = part2_solution(challenge)',\n ' p.pprint(part2)',\n ])\n\n\ndef generate_file_template(day: int) -> None:\n day = str(day).zfill(2)\n with open(f'./day{day}.py', 'w') as pyfile:\n pyfile.writelines([\n imports(),\n spacer(),\n spacer(),\n spacer(),\n function_stubs(),\n spacer(),\n spacer(),\n spacer(),\n main_func()\n ])\n\n\nif __name__ == \"__main__\":\n day = int(input('Day number: '))\n generate_file_template(day)\n","sub_path":"python/2015/template_2015.py","file_name":"template_2015.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"469190526","text":"import pandas as pd\nimport json\n\nfilename=\"../input/atomic/v4_atomic_all_agg.csv\"\n\nedges_file='../output_v004/atomic/edges_v004.csv'\nnodes_file='../output_v004/atomic/nodes_v004.csv'\n\ndf = pd.read_csv(filename,index_col=0)\ndf.iloc[:,:9] = df.iloc[:,:9].apply(lambda col: col.apply(json.loads))\n\ndf.drop(df.columns[len(df.columns)-1], axis=1, inplace=True)\ndf.drop(df.columns[len(df.columns)-1], axis=1, inplace=True)\n\nprint(df.columns)\n\nprint(len(df))\n\ndatasource='atomic'\nweight=1.0\nother={}\n\nedges_cols=['subject', 'predicate', 'object', 'datasource', 'weight', 'other']\nnodes_cols=['id', 'label', 'aliases', 'pos', 'datasource', 'other']\n\ndef make_node(x):\n und_x=x.replace(' ', '_')\n pref_und_x='at:%s' % und_x\n return pref_und_x\n\ncolumns=df.columns\n\nmy_rows=[]\nnode_rows=[]\nall_nodes=set()\n\ncounter=0\nfor event, row in df.iterrows():\n\te=event.replace('PersonX', '').strip()\n\te=e.replace('PersonY', '').strip()\n\te=e.replace('the ___', '')\n\te=e.replace('___', '')\n\te=e.replace(\"'s\", '')\n\twhile ' ' in e:\n\t\te=e.replace(' ', ' ')\n\te=e.strip()\n\tfor c in columns:\n\t\tfor v in row[c]:\n\t\t\tif v=='none': continue\n\t\t\tv=v.rstrip('.').replace('to Y', '').lower()\n\t\t\tv=v.replace('personx', '').replace('persony', '').replace('person x', '').replace('person y', '').replace(\"'s\", '').replace(' ', ' ').strip()\n\t\t\twhile ' ' in v:\n\t\t\t\tv=v.replace(' ', ' ')\n\t\t\tv=v.strip()\n\t\t\tn1=make_node(e)\n\t\t\tn2=make_node(v)\n\t\t\tthis_row=[n1, make_node(c), n2, datasource, weight, other]\n\t\t\tmy_rows.append(this_row)\n\n\t\t\tif n1 not in all_nodes:\n\t\t\t\trow1=[n1, e, '', '', datasource, other]\n\t\t\t\tnode_rows.append(row1)\n\t\t\t\tall_nodes.add(n1)\n\t\t\tif n2 not in all_nodes:\n\t\t\t\trow2=[n2, v, '', '', datasource, other]\n\t\t\t\tnode_rows.append(row2)\n\t\t\t\tall_nodes.add(n2)\n\n\t\t\t#print(e, 'at:%s' % c, v)\n\t\t\tcounter+=1\nprint(counter)\n\nnodes_df=pd.DataFrame(node_rows, columns=nodes_cols)\nnodes_df.sort_values('id').to_csv(nodes_file, index=False, sep='\\t')\n\nedges_df=pd.DataFrame(my_rows, columns=edges_cols)\nedges_df.drop_duplicates(subset=['subject', 'predicate','object'], inplace=True)\nedges_df.sort_values(by=['subject', 'predicate','object']).to_csv(edges_file, index=False, sep='\\t')\n","sub_path":"attic/extraction/atomic.py","file_name":"atomic.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"16164160","text":"# Future\nfrom __future__ import annotations\n\n# Standard Library\nfrom typing import Any, Optional, TypedDict\n\n\n# COMMON\n\nclass BaseObjectData(TypedDict):\n href: str\n id: str\n name: str\n type: str\n uri: str\n\n\nclass PagingObjectData(TypedDict):\n href: str\n items: list[Any] # type: ignore\n limit: int\n next: Optional[str | None]\n offset: int\n previous: Optional[str | None]\n total: int\n\n\nclass ImageData(TypedDict):\n url: str\n width: int\n height: int\n\n\nclass FollowersData(TypedDict):\n href: Optional[str]\n total: int\n\n\nclass CopyrightData(TypedDict):\n text: str\n type: str\n\n\nExternalUrlsData = dict[str, Any]\nExternalIdsData = dict[str, Any]\n\n\n# ALBUMS API\n\nclass AlbumRestrictionData(TypedDict):\n reason: str\n\n\nclass SimpleAlbumData(BaseObjectData):\n album_type: str\n artists: list[SimpleArtistData]\n available_markets: list[str]\n external_urls: ExternalUrlsData\n images: list[ImageData]\n release_date: str\n release_date_precision: str\n restrictions: AlbumRestrictionData\n total_tracks: int\n\n\nclass AlbumData(BaseObjectData):\n album_type: str\n artists: list[SimpleArtistData]\n available_markets: list[str]\n copyrights: list[CopyrightData]\n external_ids: ExternalIdsData\n external_urls: ExternalUrlsData\n genres: list[str]\n images: list[ImageData]\n label: str\n popularity: int\n release_date: str\n release_date_precision: str\n restrictions: AlbumRestrictionData\n total_tracks: int\n tracks: PagingObjectData\n\n\n# ARTISTS API\n\nclass SimpleArtistData(BaseObjectData):\n external_urls: ExternalUrlsData\n\n\nclass ArtistData(SimpleArtistData):\n followers: FollowersData\n genres: list[str]\n images: list[ImageData]\n popularity: int\n\n\n# BROWSE API\n\nclass CategoryData(TypedDict):\n href: str\n icons: list[ImageData]\n id: str\n name: str\n\n\nclass RecommendationSeedData(TypedDict):\n initialPoolSize: int\n afterFilteringSize: int\n afterRelinkingSize: int\n id: str\n type: str\n href: str\n\n\nclass RecommendationData(TypedDict):\n tracks: list[TrackData]\n seeds: list[RecommendationSeedData]\n\n\n# EPISODE API\n\nclass EpisodeRestrictionData(TypedDict):\n reason: str\n\n\nclass EpisodeResumePointData(TypedDict):\n fully_played: bool\n resume_position_ms: int\n\n\nclass SimpleEpisodeData(BaseObjectData):\n audio_preview_url: Optional[str]\n description: str\n duration_ms: int\n explicit: bool\n external_urls: ExternalUrlsData\n html_description: str\n images: list[ImageData]\n is_externally_hosted: bool\n is_playable: bool\n languages: list[str]\n release_date: str\n release_date_precision: str\n restrictions: EpisodeRestrictionData\n resume_point: EpisodeResumePointData\n\n\nclass EpisodeData(BaseObjectData):\n audio_preview_url: Optional[str]\n description: str\n duration_ms: int\n explicit: bool\n external_urls: ExternalUrlsData\n html_description: str\n images: list[ImageData]\n is_externally_hosted: bool\n is_playable: bool\n languages: list[str]\n release_date: str\n release_date_precision: str\n restrictions: EpisodeRestrictionData\n resume_point: EpisodeResumePointData\n show: ShowData\n\n\n# FOLLOW API\n\n...\n\n\n# LIBRARY API\n\n...\n\n\n# MARKETS API\n\n...\n\n\n# PERSONALIZATION API\n\n...\n\n\n# PLAYER API\n\nclass DeviceData(TypedDict):\n id: str\n is_active: bool\n is_private_session: bool\n is_restricted: bool\n name: str\n type: str\n volume_percent: int\n\n\nclass DisallowsData(TypedDict):\n interrupting_playback: bool\n pausing: bool\n resuming: bool\n seeking: bool\n skipping_next: bool\n skipping_prev: bool\n toggling_repeat_context: bool\n toggling_repeat_track: bool\n toggling_shuffle: bool\n transferring_playback: bool\n\n\nclass ContextData(TypedDict):\n external_urls: ExternalUrlsData\n href: str\n type: str\n uri: str\n\n\nclass CurrentlyPlayingContextData(TypedDict):\n actions: DisallowsData\n context: ContextData\n currently_playing_type: str\n device: DeviceData\n is_playing: bool\n item: Optional[TrackData]\n progress_ms: int\n repeat_state: str\n shuffle_state: str\n timestamp: int\n\n\nclass CurrentlyPlayingData(TypedDict):\n context: ContextData\n currently_playing_type: str\n is_playing: bool\n item: Optional[TrackData]\n progress_ms: int\n timestamp: int\n\n\n# PLAYLISTS API\n\n\nclass PlaylistTrackData(BaseObjectData):\n added_at: str\n added_by: UserData\n is_local: bool\n primary_color: Any\n video_thumbnail: Any\n track: TrackData\n\n\nclass PlaylistTrackRefData(TypedDict):\n href: str\n total: int\n\n\nclass SimplePlaylistData(BaseObjectData):\n collaborative: bool\n description: Optional[str]\n external_urls: ExternalUrlsData\n images: list[ImageData]\n owner: UserData\n primary_color: Optional[str]\n public: Optional[bool]\n snapshot_id: str\n tracks: PlaylistTrackRefData\n\n\nclass PlaylistData(BaseObjectData):\n collaborative: bool\n description: Optional[str]\n external_urls: ExternalUrlsData\n followers: FollowersData\n images: list[ImageData]\n owner: UserData\n primary_color: Optional[str]\n public: Optional[bool]\n snapshot_id: str\n tracks: PagingObjectData\n\n\n# SEARCH API\n\n...\n\n\n# SHOWS API\n\nclass ShowData(BaseObjectData):\n available_markets: list[str]\n copyrights: list[CopyrightData]\n description: str\n explicit: bool\n external_urls: ExternalUrlsData\n html_description: str\n images: list[ImageData]\n is_externally_hosted: bool\n languages: list[str]\n media_type: str\n publisher: str\n total_episodes: int\n\n\n# TRACKS API\n\n\nclass TrackRestrictionData(TypedDict):\n reason: str\n\n\nclass SimpleTrackData(BaseObjectData):\n artists: list[SimpleArtistData]\n available_markets: list[str]\n disc_number: int\n duration_ms: int\n explicit: bool\n external_urls: ExternalUrlsData\n is_local: bool\n is_playable: bool\n # linked_from: LinkedTrackData\n preview_url: str\n restrictions: TrackRestrictionData\n track_number: int\n\n\nclass TrackData(BaseObjectData):\n album: SimpleAlbumData\n artists: list[SimpleArtistData]\n available_markets: list[str]\n disc_number: int\n duration_ms: int\n explicit: bool\n external_ids: ExternalIdsData\n external_urls: ExternalUrlsData\n is_local: bool\n is_playable: bool\n # linked_from: LinkedTrackData\n popularity: int\n preview_url: str\n restrictions: TrackRestrictionData\n track_number: int\n\n\nclass AudioFeaturesData(TypedDict):\n acousticness: float\n analysis_url: str\n danceability: float\n duration_ms: int\n energy: float\n id: str\n instrumentalness: float\n key: int\n liveness: float\n loudness: float\n mode: int\n speechiness: float\n tempo: float\n time_signature: int\n track_href: str\n type: str\n uri: str\n valence: float\n\n\n# USERS API\n\nclass ExplicitContentSettingsData(TypedDict):\n filter_enabled: bool\n filter_locked: bool\n\n\nclass UserData(BaseObjectData):\n country: str\n display_name: str\n email: str\n explicit_content: ExplicitContentSettingsData\n external_urls: ExternalUrlsData\n followers: FollowersData\n images: list[ImageData]\n product: str\n\n\n# TOKENS\n\nclass ClientCredentialsData(TypedDict):\n access_token: str\n token_type: str\n expires_in: int\n\n\nclass UserCredentialsData(TypedDict):\n access_token: str\n token_type: str\n expires_in: int\n scope: str\n refresh_token: str\n","sub_path":"aiospotify/typings/objects.py","file_name":"objects.py","file_ext":"py","file_size_in_byte":7512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"333933006","text":"from datetime import datetime\nimport itertools\nimport json\nimport os\nimport re\nimport subprocess\nimport urllib.parse as parse\n\n\nclass Handler:\n def __init__(\n self, phone_home, log, tinkerbell, host_state_dir, statedir=\"/statedir/\"\n ):\n self.phone_home = phone_home\n self.log = log\n self.tinkerbell = tinkerbell\n self.host_state_dir = host_state_dir\n self.statedir = os.path.normpath(statedir) + \"/\"\n\n @staticmethod\n def run_osie(\n hardware_id, instance_id, tinkerbell, statedir, command, args=(), env={}\n ):\n cmd = (\"docker\", \"run\", \"--rm\", \"--privileged\", \"-ti\", \"-h\", hardware_id)\n\n rloghost = os.getenv(\"RLOGHOST\", tinkerbell.hostname)\n\n envs = (f\"container_uuid={instance_id}\", f\"RLOGHOST={rloghost}\")\n envs += tuple(itertools.starmap(\"=\".join, zip(env.items())))\n # prepends a '-e' before each env\n cmd += tuple(itertools.chain(*zip((\"-e\",) * len(envs), envs)))\n\n volumes = (\n \"/dev:/dev\",\n \"/dev/console:/dev/console\",\n \"/lib/firmware:/lib/firmware:ro\",\n f\"{statedir}:/statedir\",\n )\n # prepends a '-v' before each volume\n cmd += tuple(itertools.chain(*zip((\"-v\",) * len(volumes), volumes)))\n cmd += (\"--net\", \"host\", \"osie:x86_64\", f\"/home/packet/{command}\")\n cmd += args\n\n return subprocess.run(cmd)\n\n def wipe(self, j):\n log = self.log\n statedir = self.host_state_dir\n tinkerbell = self.tinkerbell\n\n hardware_id = j[\"id\"]\n log.info(\"wiping disks\")\n ret = self.run_osie(hardware_id, hardware_id, tinkerbell, statedir, \"wipe.sh\")\n ret.check_returncode()\n\n def handle_preinstalling(self, j):\n log = self.log\n phone_home = self.phone_home\n statedir = self.host_state_dir\n tinkerbell = self.tinkerbell\n\n hardware_id = j[\"id\"]\n\n if j.get(\"instance\"):\n log.error(\"handling preinstall, but an instance exists\")\n return\n\n args = (\"-M\", \"/statedir/metadata\")\n metadata = cacher_to_metadata(j, tinkerbell)\n write_statefile(self.statedir + \"metadata\", json.dumps(metadata))\n\n instance_id = metadata[\"id\"]\n log = log.bind(hardware_id=hardware_id, instance_id=instance_id)\n start = datetime.now()\n\n env = {\"PACKET_BOOTDEV_MAC\": os.getenv(\"PACKET_BOOTDEV_MAC\", \"\")}\n log.info(\"running docker\")\n self.run_osie(\n hardware_id,\n instance_id,\n tinkerbell,\n statedir,\n \"flavor-runner.sh\",\n args,\n env,\n )\n log.info(\"finished\", elapsed=str(datetime.now() - start))\n\n if j[\"state\"] == \"preinstalling\":\n phone_home({\"instance_id\": hardware_id})\n\n def setup_reboot(self):\n self.log.info(\"setting up cleanup.sh with reboot\")\n write_statefile(\n self.statedir + \"cleanup.sh\", \"#!/usr/bin/env sh\\n\" + \"reboot\\n\", 0o700\n )\n\n def wants_custom_osie(self, instance):\n services = instance.get(\"services\")\n if services:\n return \"osie\" in services\n\n userdata = instance.get(\"userdata\", \"\")\n if not userdata:\n return False\n\n for l in userdata.splitlines():\n match = re.search(r\"\"\"^\\s*#\\s*services=({.*\"osie\"\\s*:\\s*\".*})$\"\"\", l)\n if not match:\n continue\n\n return \"osie\" in json.loads(match.group(1))\n\n return False\n\n def handle_provisioning(self, j):\n log = self.log\n statedir = self.host_state_dir\n tinkerbell = self.tinkerbell\n\n hardware_id = j[\"id\"]\n instance = j.get(\"instance\")\n if not instance:\n return\n\n network_ready = instance.get(\"network_ready\")\n if not network_ready:\n log.info(\"network is not ready yet\", network_ready=network_ready)\n return\n\n if self.wants_custom_osie(instance):\n log.info(\"custom osie detected\")\n self.wipe(j)\n self.setup_reboot()\n return True\n\n args = ()\n\n metadata = cacher_to_metadata(j, tinkerbell)\n pre = j[\"preinstalled_operating_system_version\"]\n\n mismatch = any(\n checker(log, pre, instance)\n for checker in (tag_differs, storage_differs, wants_custom_image)\n )\n if mismatch:\n log.info(\"temporarily overriding state to osie.internal.check-env\")\n old_state = metadata[\"state\"]\n metadata[\"state\"] = \"osie.internal.check-env\"\n\n log.info(\"writing metadata\")\n write_statefile(self.statedir + \"metadata\", json.dumps(metadata))\n args += (\"-M\", \"/statedir/metadata\")\n\n userdata = instance.get(\"userdata\", \"\")\n if userdata:\n log.info(\"writing userdata\")\n write_statefile(self.statedir + \"userdata\", userdata)\n args += (\"-u\", \"/statedir/userdata\")\n\n env = {\"PACKET_BOOTDEV_MAC\": os.getenv(\"PACKET_BOOTDEV_MAC\", \"\")}\n instance_id = metadata[\"id\"]\n log = log.bind(hardware_id=hardware_id, instance_id=instance_id)\n start = datetime.now()\n\n if mismatch:\n self.wipe(j)\n ret = self.run_osie(\n hardware_id,\n instance_id,\n tinkerbell,\n statedir,\n \"flavor-runner.sh\",\n args,\n env,\n )\n\n if ret.returncode != 0:\n self.setup_reboot()\n return True\n\n log.info(\"reverting metadata to correct state\")\n metadata[\"state\"] = old_state\n log.info(\"writing metadata\")\n write_statefile(self.statedir + \"metadata\", json.dumps(metadata))\n if os.path.exists(self.statedir + \"disks-partioned-image-extracted\"):\n log.info(\"deleting disks-partitioned-image-extracted file\")\n remove_statefile(self.statedir + \"disks-partioned-image-extracted\")\n\n if os.access(self.statedir + \"loop.sh\", os.X_OK):\n log.info(\"exiting because osie needs something from the host\")\n return True\n\n log.info(\"running install from scratch\")\n else:\n log.info(\"ready to finish provision\")\n\n log.info(\"sending provisioning.104.01 event\")\n self.phone_home(\n {\"type\": \"provisioning.104.01\", \"body\": \"Device connected to DHCP system\"}\n )\n log.info(\"running docker\")\n ret = self.run_osie(\n hardware_id,\n instance_id,\n tinkerbell,\n statedir,\n \"flavor-runner.sh\",\n args,\n env,\n )\n log.info(\"finished\", elapsed=str(datetime.now() - start))\n ret.check_returncode()\n\n if os.access(self.statedir + \"cleanup.sh\", os.X_OK):\n log.info(\"exiting because osie is done\")\n return True\n\n def handler(self, state):\n try:\n return getattr(self, \"handle_\" + state)\n except Exception:\n pass\n\n def handle(self, state, j):\n return getattr(self, \"handle_\" + state)(j)\n\n\ndef cacher_to_metadata(j, tinkerbell):\n instance = j.get(\"instance\", None)\n if not instance:\n os = j[\"preinstalled_operating_system_version\"]\n storage = os.pop(\"storage\")\n instance = {\n \"crypted_root_password\": \"preinstall\",\n \"hostname\": \"preinstall\",\n \"id\": \"preinstall\",\n \"ip_addresses\": [],\n \"operating_system_version\": os,\n \"storage\": storage,\n \"userdata\": None,\n }\n\n os = instance[\"operating_system_version\"]\n os[\"slug\"] = os[\"os_slug\"]\n return {\n \"class\": j[\"plan_slug\"],\n \"facility\": j[\"facility_code\"],\n \"hostname\": instance[\"hostname\"],\n \"id\": instance[\"id\"],\n \"network\": {\n \"addresses\": instance.get(\"ip_addresses\", []),\n \"bonding\": {\"mode\": j[\"bonding_mode\"]},\n \"interfaces\": [\n {\"bond\": p[\"data\"][\"bond\"], \"mac\": p[\"data\"][\"mac\"], \"name\": p[\"name\"]}\n for p in j[\"network_ports\"]\n if p[\"type\"] == \"data\"\n ],\n },\n \"operating_system\": os,\n \"password_hash\": instance.get(\"crypted_root_password\"),\n \"phone_home_url\": parse.urljoin(tinkerbell.geturl(), \"phone-home\"),\n \"plan\": j[\"plan_slug\"],\n \"services\": instance.get(\"services\"),\n \"state\": j[\"state\"],\n \"storage\": instance.get(\"storage\", \"\"),\n } # noqa: E122\n\n\ndef write_statefile(name, content, mode=0o644):\n with open(name, \"w\") as f:\n f.write(content)\n f.flush()\n os.fchmod(f.fileno(), mode)\n\n\ndef remove_statefile(name):\n os.remove(name)\n\n\ndef get_slug_tag(os):\n tag = os.get(\"image_tag\")\n if not tag:\n tag = \"\"\n try:\n os_slug = os[\"os_slug\"]\n except KeyError as ke:\n raise AttributeError(\n \"required key missing from cacher data, key=%s\" % (ke.args[0])\n )\n return os_slug + \":\" + tag\n\n\ndef get_custom_image_from_userdata(userdata):\n # needs to stay in sync with osie's code\n repo = re.search(r\".*\\bimage_repo=(\\S+).*\", userdata)\n tag = re.search(r\".*\\bimage_tag=(\\S+).*\", userdata)\n if repo and tag:\n return repo.group(1) + \"#\" + tag.group(1)\n\n\ndef tag_differs(log, pre, instance):\n pretag = get_slug_tag(pre)\n instag = get_slug_tag(instance[\"operating_system_version\"])\n if pretag != instag:\n log.info(\n \"preinstalled does not match instance selection\",\n preinstalled=pretag,\n instance=instag,\n )\n return True\n\n\ndef storage_differs(log, pre, instance):\n precpr = pre[\"storage\"]\n inscpr = instance[\"storage\"]\n if precpr != inscpr:\n log.info(\n \"preinstalled cpr does not match instance cpr\",\n preinstalled=precpr,\n instance=inscpr,\n )\n return True\n\n\ndef wants_custom_image(log, pre, instance):\n userdata = instance.get(\"userdata\", \"\")\n if not userdata:\n return False\n\n custom_repo_tag = get_custom_image_from_userdata(userdata)\n pre_repo_tag = \"https://github.com/packethost/packet-images#\" + pre.get(\n \"image_tag\", \"\"\n )\n if custom_repo_tag and custom_repo_tag != pre_repo_tag:\n log.info(\n \"using custom image\",\n custom_repo_tag=custom_repo_tag,\n preinstalled_repo_tag=pre_repo_tag,\n )\n return True\n\n return False\n","sub_path":"osie-runner/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":10622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"469995841","text":"#!/usr/bin/env python\nimport rospy\nimport sys\nimport copy\nimport moveit_commander\nimport moveit_msgs.msg\nfrom std_msgs.msg import UInt8, Float32MultiArray\n#from PySide import QtCore, QtGui, QtOpenGL\nfrom tf import TransformListener\nfrom tf.transformations import quaternion_from_euler\nimport actionlib\nimport math\nfrom object_msgs.msg import ObjectPose\nimport geometry_msgs.msg\n\nclass Ur5Moveit:\n\n # Constructor\n def __init__(self):\n\n self._planning_group = \"arm_group\"\n self._commander = moveit_commander.roscpp_initialize(sys.argv)\n self._robot = moveit_commander.RobotCommander()\n self._scene = moveit_commander.PlanningSceneInterface()\n self._group = moveit_commander.MoveGroupCommander(self._planning_group)\n self._display_trajectory_publisher = rospy.Publisher(\n '/move_group/display_planned_path', moveit_msgs.msg.DisplayTrajectory, queue_size=1)\n\n self._exectute_trajectory_client = actionlib.SimpleActionClient(\n 'execute_trajectory', moveit_msgs.msg.ExecuteTrajectoryAction)\n self._exectute_trajectory_client.wait_for_server()\n\n self._planning_frame = self._group.get_planning_frame()\n self._eef_link = self._group.get_end_effector_link()\n self._group_names = self._robot.get_group_names()\n self._box_name = ''\n\n # Current State of the Robot is needed to add box to planning scene\n self._curr_state = self._robot.get_current_state()\n\n rospy.loginfo(\n '\\033[94m' + \"Planning Group: {}\".format(self._planning_frame) + '\\033[0m') \n rospy.loginfo(\n '\\033[94m' + \"End Effector Link: {}\".format(self._eef_link) + '\\033[0m')\n rospy.loginfo(\n '\\033[94m' + \"Group Names: {}\".format(self._group_names) + '\\033[0m')\n\n rospy.loginfo('\\033[94m' + \" >>> Ur5Moveit init done.\" + '\\033[0m')\n\n def go_to_pose(self, arg_pose):\n self._planning_group = \"arm_group\"\n self._group = moveit_commander.MoveGroupCommander(self._planning_group)\n pose_values = self._group.get_current_pose().pose\n # rospy.loginfo('\\033[94m' + \">>> Current Pose:\" + '\\033[0m')\n # rospy.loginfo(pose_values)\n\n self._group.set_pose_target(arg_pose)\n flag_plan = self._group.go(wait=True) # wait=False for Async Move\n\n list_joint_values = self._group.get_current_joint_values()\n # rospy.loginfo('\\033[94m' + \">>> Current Joint Values:\" + '\\033[0m')\n # rospy.loginfo(list_joint_values)\n\n if (flag_plan == True):\n rospy.loginfo(\n '\\033[94m' + \">>> go_to_pose() Success\" + '\\033[0m')\n else:\n rospy.logerr(\n '\\033[94m' + \">>> go_to_pose() Failed. Solution for Pose not Found.\" + '\\033[0m')\n\n return flag_plan\n \n def go_to_defined_pose(self, Plan_group, arg_pose_name):\n '''prefined pose combined with plan_group to minimise error '''\n self._planning_group = Plan_group\n self._group = moveit_commander.MoveGroupCommander(self._planning_group)\n self._group.set_named_target(arg_pose_name)\n rospy.sleep(1)\n # plan_success, plan, planning_time, error_code = self._group.plan() \n plan = self._group.plan()\n goal = moveit_msgs.msg.ExecuteTrajectoryGoal()\n goal.trajectory = plan\n self._exectute_trajectory_client.send_goal(goal)\n rospy.sleep(1)\n self._exectute_trajectory_client.wait_for_result()\n\n # Destructor\n def __del__(self):\n moveit_commander.roscpp_shutdown()\n rospy.loginfo(\n '\\033[94m' + \"Object of class Ur5Moveit Deleted.\" + '\\033[0m')\n\n\ndef main(translation_list):\n ur5 = Ur5Moveit()\n # best roll pitch yaw values for arm manipulation \n roll= -3.12\n pitch = 0.5 \n yaw = 1.59\n for j in range(0,len(translation_list),2):\n\n rospy.sleep(0.5)\n ur5_pose_1 = geometry_msgs.msg.Pose() \n ur5_pose_1.position.x = translation_list[j+1][0] \n ur5_pose_1.position.y = translation_list[j+1][1] -0.22 # to get better approach in Y \n ur5_pose_1.position.z = translation_list[j+1][2] +0.035 # to get better path planning in Z\n\n quaternion = quaternion_from_euler(roll, pitch, yaw)\n ur5_pose_1.orientation.x = quaternion[0]\n ur5_pose_1.orientation.y = quaternion[1]\n ur5_pose_1.orientation.z = quaternion[2]\n ur5_pose_1.orientation.w = quaternion[3]\n rospy.sleep(0.5)\n \n # rospy.loginfo(\"Attemp in Y\")\n ur5.go_to_pose(ur5_pose_1) # Attemp to goal in y direction\n ur5_pose_1.position.y += 0.13 #only move in y axis \n # rospy.loginfo(\"Attemp in dot\")\n ur5.go_to_pose(ur5_pose_1) # to exact location with small tolerance\n ur5.go_to_defined_pose(\"end_group\",\"grip_close_3\") # Activating gripper pose\n # rospy.sleep(1)\n ur5_pose_1.position.z += 0.19 #going away from object in Z\n # rospy.loginfo(\"Attemp in Z\")\n ur5.go_to_pose(ur5_pose_1) #going away from object in Z\n \n ur5.go_to_defined_pose(\"arm_group\",\"drop_box_1\") # go to Predefined pose # to dropbox\n ur5.go_to_defined_pose(\"end_group\",\"open_grip\") # go to Predefined pose # drop object\n ur5.go_to_defined_pose(\"arm_group\",\"up_view\") #again to initial position\n\n del ur5\n","sub_path":"project_tsukinome/scripts/obj_pick_place.py","file_name":"obj_pick_place.py","file_ext":"py","file_size_in_byte":5337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"449873112","text":"class Room(object):\n\n def __init__(self, name, description):\n self.name = name\n self.description = description\n self.paths = {}\n\n def go(self, direction):\n return self.paths.get(direction, None)\n\n def add_paths(self, paths):\n self.paths.update(paths)\n\n\ncentral_corridor = Room(\"Central Corridor\",\n\"\"\"\nCentral Corridor. Get the bomb, put it in the bridge, blow the ship up after\ngetting into an escape pod.\n\nA Gothon is blocking your way.\n\"\"\")\n\nlaser_weapon_armory = Room(\"Laser Weapon Armory\",\n\"\"\"\nYou tell the Gothon a joke and it is laughing and can't move.\nYou enter Weapon Armory.\n\nThe bomb is locked with a keypad. If you get the code wrong 10 times you\ncan't get the bomb. The code is 3 digits.\n\"\"\")\n\nthe_bridge = Room(\"The Bridge\",\n\"\"\"\nYou take the bomb and run to the bridge.\n\nThere's 5 Gothons here.\n\"\"\")\n\nescape_pod = Room(\"Escape_Pod\",\n\"\"\"\nYou place the bomb on the floor, get out of the bridge and lock the Gothons in.\n\nYou run to the chamber with the escape pods. Some of them could be damaged.\nWhich one do you take?\n\"\"\")\n\nthe_end_winner = Room(\"The End\",\n\"\"\"\nYou jump into pod 2 and fly away. The ship explodes. You win!\n\"\"\")\n\nthe_end_loser = Room(\"The End\",\n\"\"\"\nYou jump into a random pod and eject, then it implodes.\n\"\"\")\n\n\nescape_pod.add_paths({\n '2': the_end_winner,\n '*': the_end_loser\n})\n\ngeneric_death = Room(\"death\", \"You died.\")\n\nthe_bridge.add_paths({\n 'throw the bomb': generic_death,\n 'slowly place the bomb': escape_pod\n})\n\nlaser_weapon_armory.add_paths({\n '0132': the_bridge,\n '*': generic_death\n})\n\ncentral_corridor.add_paths({\n 'shoot!': generic_death,\n 'dodge!': generic_death,\n 'tell a joke': laser_weapon_armory\n})\n\nSTART = central_corridor\n","sub_path":"projects/ex52/gothonweb/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"116392805","text":"# libs\nimport requests\nimport time\nimport csv\n\n# my files\nimport addresses\nrequests.adapters.DEFAULT_RETRIES = 5\n\ndef job(uuid):\n first_job_result = first_job(uuid)\n result = first_job_result.text\n with open('logs/'+str(uuid) +'.csv', 'a') as writeFile: \n writer = csv.writer(writeFile)\n percentage_done = \"0\"\n print(first_job_result)\n while percentage_done != \"100.0\":\n try:\n start_time = time.time()\n second_job_result = second_job(result)\n percentage_done = second_job_result.text\n end_time = time.time()\n writer.writerow([uuid,start_time,end_time,'success']) \n except requests.exceptions.ConnectionError:\n end_time = time.time()\n writer.writerow([uuid,start_time,end_time,'error'])\n writeFile.close()\n\ndef first_job(argument):\n response = requests.get(addresses.synchronous(argument))\n return response\n\ndef second_job(argument):\n response = requests.get(addresses.asynchronous(argument))\n return response","sub_path":"SimpleClient/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"586609825","text":"#número é par quando é divisível por 2 e o resto da divisão por 2 é 0\n# n%2==0\n\n#exibir os números pares entre 0 e um número digitado\n#contadores-> são variáveis que são atualizadas com um valor constante\n# por exemplo qpares=qpares+1, n=n+1,k=k+2\nfim=int(input(\"Digite o último número: \"))\nn=0 # inicializar a variável\nqpares=0\nwhile n<=fim:\n if n%2==0:\n print(n)\n qpares=qpares+1\n n=n+1\nprint(\"Quantidade de pares\", qpares)\n\n#exercício com ímpares n%2==1 ou n%2=!0\n","sub_path":"Aula_3/3.2.py","file_name":"3.2.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"149872699","text":"class Pessoa:\n def __init__(self, nome, idade, documentos):\n self.nome = nome\n self.idade = idade\n self.documentos = documentos\n\ndados = print('nome: João', 'idade: 78', 'documentos: RG e CPF')\n\nclass Medico(Pessoa):\n def __init__(self, crm, nome, idade, documentos):\n super().__init__(nome, idade, documentos)\n self.crm = crm\n\ndados = print(nome,)\ncrm = print('CRM 44056')\n\n\nclass Paciente(Pessoa):\n def __init__(self, doença, sintomas):\n self.doença = doença\n self.sintomas = sintomas\n\nsintoma = print('Dor de cabeça, tontura, virose')","sub_path":"objetos.py","file_name":"objetos.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"371817780","text":"# This example demonstrates a peripheral implementing the Nordic UART Service (NUS).\r\n\r\nimport time, json\r\nimport bluetooth\r\nfrom ble_advertising import advertising_payload\r\n\r\nfrom micropython import const\r\n\r\n_IRQ_CENTRAL_CONNECT = const(1)\r\n_IRQ_CENTRAL_DISCONNECT = const(2)\r\n_IRQ_GATTS_WRITE = const(3)\r\n\r\n_UART_UUID = bluetooth.UUID(\"6E400001-B5A3-F393-E0A9-E50E24DCCA9E\")\r\n_UART_TX = (\r\n bluetooth.UUID(\"6E400003-B5A3-F393-E0A9-E50E24DCCA9E\"),\r\n bluetooth.FLAG_NOTIFY,\r\n)\r\n_UART_RX = (\r\n bluetooth.UUID(\"6E400002-B5A3-F393-E0A9-E50E24DCCA9E\"),\r\n bluetooth.FLAG_WRITE,\r\n)\r\n_UART_SERVICE = (\r\n _UART_UUID,\r\n (_UART_TX, _UART_RX),\r\n)\r\n\r\n# org.bluetooth.characteristic.gap.appearance.xml\r\n_ADV_APPEARANCE_GENERIC_COMPUTER = const(128)\r\n\r\n\r\nclass BLEUART:\r\n def __init__(self, ble, name=\"oh-yolobit\", rxbuf=100):\r\n self._ble = ble\r\n self._ble.active(True)\r\n self._ble.irq(self._irq)\r\n ((self._tx_handle, self._rx_handle),\r\n ) = self._ble.gatts_register_services((_UART_SERVICE,))\r\n # Increase the size of the rx buffer and enable append mode.\r\n self._ble.gatts_set_buffer(self._rx_handle, rxbuf, True)\r\n self._connections = set()\r\n self._rx_buffer = bytearray()\r\n self._handler_int = None #internal msg handler\r\n self._handler_user = None # msg handler by user\r\n # Optionally add services=[_UART_UUID], but this is likely to make the payload too large.\r\n self._payload = advertising_payload(\r\n name=name, appearance=_ADV_APPEARANCE_GENERIC_COMPUTER)\r\n self._advertise()\r\n \r\n def _on_rx(self):\r\n m = self.read()\r\n try:\r\n msg = m.decode('utf8')\r\n except UnicodeError:\r\n msg = ''.join([chr(c) for c in m])\r\n \r\n if self._handler_user:\r\n self._handler_user(msg)\r\n \r\n def irq(self, handler):\r\n self._handler_int = handler\r\n \r\n def irq_user(self, handler):\r\n self._handler_user = handler\r\n\r\n def _irq(self, event, data):\r\n # Track connections so we can send notifications.\r\n if event == _IRQ_CENTRAL_CONNECT:\r\n conn_handle, _, _ = data\r\n self._connections.add(conn_handle)\r\n elif event == _IRQ_CENTRAL_DISCONNECT:\r\n conn_handle, _, _ = data\r\n if conn_handle in self._connections:\r\n self._connections.remove(conn_handle)\r\n # Start advertising again to allow a new connection.\r\n self._advertise()\r\n elif event == _IRQ_GATTS_WRITE:\r\n conn_handle, value_handle = data\r\n if conn_handle in self._connections and value_handle == self._rx_handle:\r\n self._rx_buffer += self._ble.gatts_read(self._rx_handle)\r\n if self._handler_int:\r\n self._handler_int()\r\n\r\n def any(self):\r\n return len(self._rx_buffer)\r\n\r\n def read(self, sz=None):\r\n if not sz:\r\n sz = len(self._rx_buffer)\r\n result = self._rx_buffer[0:sz]\r\n self._rx_buffer = self._rx_buffer[sz:]\r\n return result\r\n\r\n def write(self, data):\r\n for conn_handle in self._connections:\r\n self._ble.gatts_notify(conn_handle, self._tx_handle, data)\r\n\r\n def close(self):\r\n for conn_handle in self._connections:\r\n self._ble.gap_disconnect(conn_handle)\r\n self._connections.clear()\r\n\r\n def _advertise(self, interval_us=500000):\r\n self._ble.gap_advertise(interval_us, adv_data=self._payload)\r\n\r\nbt = None\r\n\r\ndef ble_on_rx(handler):\r\n global bt\r\n bt.irq_user(handler=handler)\r\n\r\ndef ble_start(name='yolobit'):\r\n global bt\r\n bt = BLEUART(bluetooth.BLE(), name)\r\n bt.irq(bt._on_rx)\r\n\r\ndef ble_send(name, value=None):\r\n global bt\r\n if bt:\r\n if value is None:\r\n bt.write(str(name))\r\n else:\r\n bt.write(json.dumps((name, value)))\r\n\r\ndef ble_disconnect():\r\n global bt\r\n if bt:\r\n bt.close()\r\n\r\nif __name__ == \"__main__\":\r\n ble_start()\r\n\r\n\r\n","sub_path":"ble_uart_peripheral.py","file_name":"ble_uart_peripheral.py","file_ext":"py","file_size_in_byte":4039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"163604281","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nimport sys\nimport codecs\n\n\ndef main():\n args = []\n fin = codecs.open(\"./data1.txt\",\"r\",\"utf-8\")\n try:\n for l in fin:\n l = l.strip()\n args.append(l)\n finally:\n fin.close()\n\n syain = int(args[0])\n args.pop(0)\n bite = int(len(args)) - syain\n list2 = []\n i = 0\n while i < syain:\n list2 += args[i].split(\"-\")\n i += 1\n list3 = []\n i = 0\n args.reverse()\n while i < bite:\n list3 += args[i].split(\"-\")\n i += 1\n \n okDay = []\n for item in list3:\n if item not in list2:\n list3.remove(item)\n \n okDay = list2 + list3\n from collections import Counter\n counted_dict = Counter(okDay)\n okMax = max(counted_dict.values())\n okDay=[]\n for k,v in counted_dict.items():\n if v == okMax:\n okDay.append(k) \n okDay.sort()\n print(\"開催日:\",okDay[0])\n print(\"参加人数\",okMax)\nif __name__ == \"__main__\":\n main()\n","sub_path":"kondo/kadai6/kadai6_2.py","file_name":"kadai6_2.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"527836535","text":"#!/usr/bin/env python\n\nimport datetime as dt\nimport os\nimport shutil\n\nfrom contextlib import contextmanager\nfrom dataclasses import dataclass\nfrom operator import attrgetter\nfrom typing import List, Optional\n\nimport frontmatter\nimport mistletoe\nimport sass\nimport yattag\n\nfrom dotenv import load_dotenv\nfrom slugify import slugify\n\nload_dotenv()\n\nBLOG_TITLE = \"the blog\"\nMY_NAME = os.environ[\"NAME\"]\nEMAIL = os.environ[\"EMAIL\"]\nHEADER_LINKS = [\n (\"github\", \"https://github.com/p7g\"),\n (\"linkedin\", \"https://linkedin.com/pat775\"),\n]\n\n\ndef header(doc, tag, text, line):\n with tag(\"header\", klass=\"header\"):\n with tag(\"a\", href=\"/\", title=\"home\"):\n line(\"h1\", BLOG_TITLE, klass=\"header__title\")\n line(\"p\", MY_NAME, klass=\"header__name\")\n\n with tag(\"section\", klass=\"header__links\"):\n for link_text, address in HEADER_LINKS:\n line(\"a\", link_text, href=address, klass=\"header__links__link\")\n text(\" \")\n\n doc.stag(\"hr\")\n\n return doc\n\n\n@contextmanager\ndef base_page(doc, tag, text, line):\n doc.asis(\"\")\n\n with tag(\"html\"):\n with tag(\"head\"):\n doc.stag(\n \"meta\", name=\"viewport\", content=\"width=device-width, initial-scale=1\"\n )\n doc.stag(\n \"link\",\n rel=\"stylesheet\",\n href=\"https://fonts.googleapis.com/css?family=\"\n \"IBM+Plex+Serif:400,400i,700,700i\"\n \"|Faustina:400,400i,700,700i\"\n \"|Inconsolata\"\n \"&display=block\",\n )\n doc.stag(\"link\", rel=\"stylesheet\", href=\"/css/styles.css\")\n with tag(\"body\"):\n yield\n\n\ndef home_page(posts: List[\"Post\"]):\n doc, tag, text, line = ttl = yattag.Doc().ttl()\n\n with base_page(*ttl):\n header(*ttl)\n\n with tag(\"main\", klass=\"main\"):\n with tag(\"section\", klass=\"main__post_list\"):\n line(\"h2\", \"posts\", klass=\"main__post_list__heading\")\n for post in posts:\n with tag(\"article\", klass=\"main__post\"):\n with tag(\"a\", href=post.url):\n line(\"h3\", post.title, klass=\"main__post__title\")\n with tag(\"small\", klass=\"main__post__date\"):\n line(\n \"time\",\n post.date.strftime(\"%B %d, %Y\"),\n datetime=post.date.isoformat(),\n )\n if post.description is not None:\n line(\n \"p\", post.description, klass=\"main__post__description\",\n )\n\n return doc.getvalue()\n\n\ndef post_page(post: \"Post\"):\n doc, tag, text, line = ttl = yattag.Doc().ttl()\n\n with base_page(*ttl):\n header(*ttl)\n\n with tag(\"main\", klass=\"main\"):\n with tag(\"article\", klass=\"post\"):\n with tag(\"header\", klass=\"post__header\"):\n line(\"h2\", post.title, klass=\"post__heading\")\n line(\n \"time\",\n post.date.strftime(\"%B %d, %Y\"),\n time=post.date.isoformat(),\n klass=\"post__heading__time\",\n )\n with tag(\"main\", klass=\"post__main\"):\n doc.asis(post.html)\n with tag(\"footer\", klass=\"post__footer\"):\n doc.stag(\"hr\")\n text(\"Feedback? \")\n line(\"a\", \"Email me\", href=f\"mailto:{EMAIL}\", klass=\"post__footer__email\")\n\n return doc.getvalue()\n\n\n@dataclass\nclass Post:\n title: str\n description: Optional[str]\n date: dt.date\n html: str\n\n @property\n def slug(self):\n return slugify(self.title)\n\n @property\n def url(self):\n return f\"/posts/{self.slug}\"\n\n\nposts = []\n\nwith os.scandir(\"posts\") as it:\n for post_file in it:\n if not post_file.is_file() or post_file.name.startswith(\".\"):\n continue\n\n with open(post_file.path, \"r\") as f:\n text = f.read()\n\n post_raw = frontmatter.loads(text)\n\n date = post_raw[\"date\"]\n if isinstance(date, str):\n date = dt.date.fromisoformat(date)\n\n posts.append(\n Post(\n title=post_raw[\"title\"],\n description=post_raw.get(\"description\"),\n date=date,\n html=mistletoe.markdown(post_raw.content),\n )\n )\n\n\nposts = list(sorted(posts, key=attrgetter(\"date\")))\n\nshutil.rmtree(\"build\")\nos.makedirs(os.path.join(\"build\", \"posts\"), exist_ok=True)\n\n# generate main page\nwith open(os.path.join(\"build\", \"index.html\"), \"w\") as f:\n f.write(home_page(posts))\n\nsass.compile(dirname=(\"css\", os.path.join(\"build\", \"css\")), output_style=\"compressed\")\n\nfor post in posts:\n post_dir = os.path.join(\"build\", \"posts\", post.slug)\n os.makedirs(post_dir, exist_ok=False)\n\n with open(os.path.join(post_dir, \"index.html\"), \"w\") as f:\n f.write(post_page(post))\n","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":5125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"503248536","text":"import torch\nimport torch.nn.functional as F\nfrom torch import nn\n\n\nclass OutliyerInsensitivityLoss(nn.Module):\n \"\"\"Loss that has less penalty than Cross Entripy for hard samples\"\"\"\n def __init__(self, gamma=0.1, weight=None, first_epoch=2):\n super(OutliyerInsensitivityLoss, self).__init__()\n self.gamma = gamma\n self.weight = weight\n self.first_epoch = first_epoch\n\n def forward(self, input, target, epoch):\n if epoch < self.first_epoch:\n return F.cross_entropy(input, target, self.weight)\n \n logpt = F.log_softmax(input, dim=1)\n pt = torch.exp(logpt).detach()\n logpt = pt**self.gamma * logpt\n loss = F.nll_loss(logpt, target, self.weight)\n return loss","sub_path":"loss/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"572285497","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 6 16:13:28 2016\n\n@author: PM5\n\nPlots mooring records for analytical runs like aestus1.\n\"\"\"\n\n# setup\nimport netCDF4 as nc\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.dates as mdates\n\nimport os\nimport sys\nalp = os.path.abspath('../alpha')\nif alp not in sys.path:\n sys.path.append(alp)\nimport Lfun\n\nLdir = Lfun.Lstart()\nindir = Ldir['LOo'] + 'moor/'\n\n# choose the type of plot to make\nprint('\\n%s\\n' % '** Choose mooring file to plot **')\nm_list_raw = os.listdir(indir)\nm_list = []\nfor m in m_list_raw:\n if '.nc' in m:\n m_list.append(m)\nNpt = len(m_list)\nm_dict = dict(zip(range(Npt), m_list))\nfor npt in range(Npt):\n print(str(npt) + ': ' + m_list[npt])\nif True:\n my_npt = int(input('-- Input number -- '))\nelse:\n my_npt = 0 # for testing\nmoor_file = m_dict[my_npt]\nfn = indir + moor_file\n\n#%% load and organize data\n\nv2_list = []\nv3_list_rho = []\nv3_list_w = []\nds = nc.Dataset(fn)\nfor vv in ds.variables:\n vdim = ds.variables[vv].dimensions\n if ( ('ocean_time' in vdim)\n and ('s_rho' not in vdim)\n and ('s_w' not in vdim)\n and (vv != 'ocean_time') ):\n v2_list.append(vv)\n elif ( ('ocean_time' in vdim) and ('s_rho' in vdim) ):\n v3_list_rho.append(vv)\n elif ( ('ocean_time' in vdim) and ('s_w' in vdim) ):\n v3_list_w.append(vv)\n\n# load everything into a dict\nV = dict()\n\nlist_to_plot = v3_list_rho + v3_list_w + v2_list\nlist_to_plot.remove('temp')\nlist_to_plot.remove('shflux')\nlist_to_plot.remove('sustr')\nlist_to_plot.remove('svstr')\nlist_to_plot.remove('hh')\n\nfor vv in list_to_plot:\n V[vv] = ds[vv][:]\n\nV['ocean_time'] = ds['ocean_time'][:]\n\nds.close()\n\n#%% plotting\n\nNP = len(list_to_plot)\n\nNR = np.maximum(1, np.ceil(np.sqrt(NP)).astype(int))\nNC = np.ceil(np.sqrt(NP)).astype(int)\n\nif NR*NC - NP >= NR:\n NC = NC-1\n\nfig, axes = plt.subplots(nrows=NR, ncols=NC, figsize=(17,9), squeeze=False)\n\ndays = (V['ocean_time'] - V['ocean_time'][0])/86400.\n\nmdays = Lfun.modtime_to_mdate_vec(V['ocean_time'])\nmdt = mdates.num2date(mdays) # list of datetimes of data\n\ncc = 0\nnmid = 20\nfor vn in list_to_plot:\n ir = int(np.floor(cc/NC))\n ic = int(cc - NC*ir)\n ax = axes[ir, ic]\n if V[vn].ndim == 2:\n ax.plot(days, V[vn][-1,:], '-r')\n ax.plot(days, V[vn][nmid,:],'-g')\n ax.plot(days, V[vn][0,:], '-b')\n elif V[vn].ndim == 1:\n ax.plot(days, V[vn])\n\n # general case\n ax.set_xlim(days[0], days[-1])\n if ir == NR-1:\n ax.set_xlabel('Days')\n aa = ax.get_ylim()\n ax.set_ylim(aa)\n \n ax.ticklabel_format(useOffset=False, axis='y')\n ax.text(.05, .85, vn,\n horizontalalignment='left',\n transform=ax.transAxes, fontweight='bold', fontsize=24)\n cc += 1\n\nplt.show()\n","sub_path":"moor/plotA.py","file_name":"plotA.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"410384183","text":"\"\"\"\nReverse a linked list from position m to n. Do it in-place and in one-pass.\n\nFor example:\nGiven 1->2->3->4->5->NULL, m = 2 and n = 4,\n\nreturn 1->4->3->2->5->NULL.\n\nNote:\nGiven m, n satisfy the following condition:\n1 <= m <= n <= length of list.\n\"\"\"\nfrom . import ListNode\n\ndef reverseBetween(head, m, n):\n \"\"\"\n :type head: ListNode\n :type m: int\n :type n: int\n :rtype: ListNode\n \"\"\"\n temp = ListNode(0)\n node = temp\n end = node\n index = 0\n while head:\n index += 1\n a = head\n head = head.next\n a.next = None\n if index >= m and index <=n:\n a.next = node.next\n node.next = a\n while end.next:\n end = end.next\n else:\n end.next = a\n end = end.next\n node = end\n return temp.next","sub_path":"leetcode/reverse_linked_list_ii.py","file_name":"reverse_linked_list_ii.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"374330611","text":"import logging\nimport os\nimport pickle\nimport random\nimport select\nimport socket\nimport sys\n\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import serialization\nfrom cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey\nfrom pgp import PGP, PGPPacket, AESEncryptedData\nfrom secret_message import *\n\nlogging.basicConfig(\n level=logging.DEBUG,\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n datefmt='%m/%d/%Y %I:%M:%S %p',\n stream=sys.stdout\n)\nlogger = logging.getLogger(__name__)\n\n\nclass User(PGP):\n def __init__(self):\n PGP.__init__(self)\n self.user_id = random.randrange(42)\n\n def receive_secret_key(self, encrypted_key, sender_public_key) -> None:\n self._secret_key = self.receive_pgp_key(encrypted_key, sender_public_key)\n\n def join_room(self):\n pass\n\n def send_msg(self):\n pass\n\n def prompt(self):\n sys.stdout.write('\\nYou: ')\n sys.stdout.flush()\n\n\nif __name__ == '__main__':\n host = \"localhost\"\n port = 15555\n user = User()\n try:\n # Create socket\n user_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n user_socket.settimeout(2)\n user_socket.connect((host, port))\n logger.info(f'User #{user.user_id} is connected to {host}:{port}')\n\n # Get secret key\n logger.info('Exchanging keys')\n pem = user.public_key.public_bytes(\n encoding=serialization.Encoding.PEM,\n format=serialization.PublicFormat.SubjectPublicKeyInfo\n )\n\n logger.info('Sending our public key')\n msg = SecretMessage(op_code=OP_CODE_KEY, data=pem, user_id=user.user_id)\n msg = pickle.dumps(msg)\n user_socket.send(msg)\n server_public_key = user_socket.recv(4096)\n\n logger.info(\"Loading server's public key\")\n server_pem: RSAPublicKey = serialization.load_pem_public_key(\n server_public_key,\n backend=default_backend())\n\n pgp_packet = user_socket.recv(4096)\n logger.info('Decrypting secret key using PGP')\n\n packet: PGPPacket = pickle.loads(pgp_packet)\n logger.debug(packet)\n\n user.receive_secret_key(packet, server_pem)\n\n logger.info('Secret key exchanged!')\n\n while True:\n socket_list = [sys.stdin, user_socket]\n # Get the list sockets which are readable\n read_sockets, write_sockets, error_sockets = select.select(socket_list, [], [])\n for s in read_sockets:\n # incoming message from remote server\n if s is user_socket:\n data = user_socket.recv(4096)\n if not data:\n logger.info('Disconnected from chat server')\n sys.exit()\n else:\n # print data\n response: SecretMessage = pickle.loads(data)\n data: AESEncryptedData = response['data']\n msg = user.decrypt(data['data'], data['iv'])\n sys.stdout.write(f\"User{response['user_id']}: {msg.decode('utf-8')}\\n\")\n user.prompt()\n # user entered a message\n else:\n msg = sys.stdin.readline()\n\n logger.debug(f'Encrypting message: {msg}')\n iv = os.urandom(16)\n cipher_text = user.encrypt(msg.encode('utf-8'), iv)\n msg = AESEncryptedData(data=cipher_text, iv=iv)\n msg = SecretMessage(op_code=OP_CODE_MSG, data=msg, user_id=user.user_id)\n msg = pickle.dumps(msg)\n user_socket.send(msg)\n user.prompt()\n except KeyboardInterrupt or EOFError:\n print('Exiting chat room!')\n user_socket.close()\n finally:\n pass\n","sub_path":"src/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":3942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"405846728","text":"from profile import man, woman\n# il faut que le fichier \"profile.py\" soit placé dans le même dossier que \"database.py\"\nimport random\nimport json\n\nmale_names = ['adam', 'bob', 'steve','andréas', 'clément', 'léo', 'adrien', 'pierre', 'remi']\nfemale_names = ['eve', 'mona', 'lisa', 'claire', 'solène', 'julie', 'marion', 'dina', 'gaelle']\n\nsubjects_guy = ['french', 'english', 'maths', 'physiques', 'biology', 'spanish', 'phylosophy', 'economy', 'sport']\nsubjects_girl = ['international', 'price', 'prestige', 'doubledegree', 'accessibility', 'campus']\n\nclass data:\n\tdef __init__(self):\n\t\tself.guys = []\n\t\tself.girls = []\n\t\tself.guyprefers = {}\n\t\tself.galprefers = {}\n\t\tself.capacity = {}\n\n\t\t# on lance la génération de profiles\n\t\tself.rundata()\n\n\tdef rundata(self):\n\t\tself.set_profiles()\n\t\tself.set_preferences()\n\n\tdef set_profiles(self):\n\t\tfor name in male_names:\n\t\t\tguy = man(name)\n\t\t\tguy.set_results(subjects_guy)\n\t\t\tguy.set_standards(subjects_girl)\n\t\t\tself.guys.append(guy)\n\t\tfor name in female_names:\n\t\t\tgirl = woman(name)\n\t\t\tgirl.set_results(subjects_girl)\n\t\t\tgirl.set_standards(subjects_guy)\n\t\t\tself.girls.append(girl)\n\t\t\tself.capacity[girl.name] = girl.capacity\n\n\tdef set_preferences(self):\n\t\tfor guy in self.guys:\n\t\t\tguy.grade(self.girls)\n\t\t\tguy.classify()\n\t\t\tself.guyprefers[guy.name] = guy.preferences\n\t\tfor girl in self.girls:\n\t\t\tgirl.grade(self.guys)\n\t\t\tgirl.classify()\n\t\t\tself.galprefers[girl.name] = girl.preferences\n\ndata = data()\na,b = data.guyprefers, data.galprefers\nprint(a)\nprint(b)\n\n","sub_path":"Espace de Travail/Algo/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"142894482","text":"#!/usr/bin/env python2\n# license removed for brevity\nimport rospy\nfrom std_msgs.msg import String\nfrom geometry_msgs.msg import Point\n\n\ndef talker():\n a = Point()\n b = Point()\n a.x = 1\n b.x = 4\n a.y = 2\n b.y = 5\n a.z = 3\n b.z = 6\n pub = rospy.Publisher('chatter', Point, queue_size=20)\n rospy.init_node('talker', anonymous=True)\n rate = rospy.Rate(10) # 10hz\n while not rospy.is_shutdown(): \n rospy.loginfo(a)\n pub.publish(a)\n rate.sleep()\n rospy.loginfo(b)\n pub.publish(b)\n rate.sleep\n\nif __name__ == '__main__':\n try:\n talker()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"build/projetIntegration/catkin_generated/installspace/talker.py","file_name":"talker.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"199900132","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue May 28 13:25:34 2019\r\n\r\n@author: chuze\r\n\"\"\"\r\n\r\n\r\nimport requests\r\n\r\nfrom bs4 import BeautifulSoup \r\nimport json\r\nimport re\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom time import sleep\r\n\r\nfrom os import listdir\r\nimport os, sys\r\n\r\nimport nltk\r\nfrom newspaper import Article\r\nfrom geograpy.utils import remove_non_ascii\r\n\r\naddress = 'C:/Users/chuze/Desktop/weicheche/2019IJCAI_DTTF/'\r\n\r\n\r\n\r\n\r\ne = pd.read_csv('%sUserSide.csv'%address,encoding = \"utf-8\") \r\n\r\nl = e['11']\r\n\r\n\r\ncityl= []\r\nfor i in range(len(l)):\r\n \r\n text = l[i]\r\n try:\r\n text = text.replace(',',' ')\r\n text = text.replace('/',' ')\r\n text = text.replace('-',' ')\r\n text = nltk.word_tokenize(remove_non_ascii(text))\r\n cityl = cityl + (text)\r\n except:\r\n 1\r\n \r\n\r\ncitySet = list(set(cityl))\r\n \r\ncount = np.zeros(len(citySet))\r\n\r\nfor i in range(len(l)):\r\n \r\n text = l[i]\r\n try:\r\n text = text.replace(',',' ')\r\n text = text.replace('/',' ')\r\n text = text.replace('-',' ')\r\n text = nltk.word_tokenize(remove_non_ascii(text))\r\n for j in text:\r\n count[citySet.index(j)] +=1\r\n \r\n except:\r\n 1\r\n #try:\r\n\r\ncityE = []\r\n\r\nfor i in range(len(l)):\r\n text = l[i]\r\n try:\r\n text = text.replace(',',' ')\r\n text = text.replace('/',' ')\r\n text = text.replace('-',' ')\r\n\r\n text = nltk.word_tokenize(remove_non_ascii(text))\r\n if len(text) ==1:\r\n \r\n \r\n cityE.append(citySet.index(text[0]))\r\n else:\r\n maxNum = 0\r\n maxC = 0\r\n for j in text:\r\n if count[citySet.index(j)] > maxNum:\r\n maxNum = count[citySet.index(j)]\r\n maxC = citySet.index(j)\r\n cityE.append(maxC)\r\n except:\r\n cityE.append(-1)\r\n\r\n\r\ntempset = list(set(cityE))\r\ntempset.remove(-1)\r\ncityC = []\r\n\r\n\r\nfor i in range(len(cityE)):\r\n if cityE[i] == -1:\r\n cityC.append(-1)\r\n else:\r\n cityC.append(tempset.index(cityE[i])) \r\n\r\nsideM = pd.DataFrame(cityC) \r\nsideM.to_csv('%sStyleUserSide.csv'%address,index = False,encoding = \"utf-8\")\r\ne = pd.read_csv('%sStyleUserSide.csv'%address,encoding = \"utf-8\") \r\n \r\n\r\n\r\n\r\n\r\n ","sub_path":"feature_dispersed.py","file_name":"feature_dispersed.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"536789942","text":"import shutil\nimport os\nimport json\nfrom zipfile import ZipFile\n\nif not os.path.exists('user'):\n os.makedirs('user')\n\nwith open('user/.user-rev', 'w+') as fp:\n fp.write('CUSTOM @ fffffff')\n\nwith open('files.json', 'r') as myfile:\n data = myfile.read()\nobj = json.loads(data)\ndestination = ''\nif '__destination__' in list(obj.keys()):\n destination = obj['__destination__'] + '/'\n del obj['__destination__']\n\nfor src in list(obj.keys()):\n dest = obj[src]\n if '/' in dest:\n if not os.path.exists('user/{}'.format(\n dest[:dest.rfind('/')])):\n os.makedirs('user/{}'.format(dest[:dest.rfind('/')]))\n for folder in range(len(dest.split('/'))-1):\n with open('user/{}/.directory'.format('/'.join(\n dest.split('/')[:folder+1])), 'w+') as fp:\n pass\n shutil.copyfile('../{}'.format(src), 'user/{}'.format(dest))\n\nwith ZipFile(destination+'robot.zip', 'w') as zp:\n zp.write('info.yaml')\n zp.write('overlay.sr2020.2.squash')\n zp.write('wifi.yaml')\n for folderName, subfolders, filenames in os.walk('user'):\n for filename in filenames:\n filePath = os.path.join(folderName, filename)\n zp.write(filePath)\n","sub_path":"compiler/compiler.py","file_name":"compiler.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"351575063","text":"import hashlib\n\n\nclass MaintenanceRecord:\n aircraft_reg_number = None\n date_of_record = None\n filename = None\n file_hash = None\n file_path = None\n\n def __init__(self, aircraft_reg_number, date_of_record, filename, file_path):\n self.aircraft_reg_number = aircraft_reg_number\n self.date_of_record = date_of_record\n self.filename = filename\n self.file_path = file_path\n self.file_hash = self.get_file_hash()\n\n def get_file_hash(self):\n \"\"\"\n Generates a fingerprint of a maintenance record document\n \"\"\"\n sha256 = hashlib.sha256()\n\n with open(self.file_path, 'rb') as f:\n while True:\n data = f.read(65536)\n if not data:\n break\n sha256.update(data)\n\n return sha256.hexdigest()\n","sub_path":"blockchain/maintenance_record.py","file_name":"maintenance_record.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"563303062","text":"import random\nimport Point\nimport math\nclass Envronment():\n def __init__(self,Point_List,dimension_x,dimmension_y=0):\n\n self.PointList=Point_List\n self.grid = Point.Grid(self.PointList,dimension_x, dimmension_y)\n self.grid.set_grid(self.PointList)\n self.dis_dict = {}\n # self.cal_dis_dict(dis_function=self.dis_func1)\n # to store the distance all poins\n # the key is (id1,id2), and id1<=id2\n #deep copy\n def copy_environment(self,Envir):\n self.grid=Envir.grid\n self.PointList=Envir.PointList\n self.dis_dict=Envir.dis_dict\n # self.cal_dis_dict(dis_function=self.dis_func1)\n\n\n def add_Point(self,pointList):\n if(pointList):\n self.PointList.extend(pointList)\n self.grid.set_grid(self.PointList)\n\n # add a function to cal the dis matrix\n def cal_dis_dict(self,dis_function):\n for point in self.PointList:\n for point2 in self.PointList:\n if(point.ID!=point2.ID):\n temp_dis=dis_function(point,point2)\n self.dis_dict[(point.ID,point2.ID)]=temp_dis\n def find_distance(self,id1,id2):\n if((id1,id2) in self.dis_dict.keys()):\n return self.dis_dict[(id1,id2)]\n else:\n return pow(10,10)\n def dis_func1(self,Point1, Point2):\n r2 = (Point1.x - Point2.x) * (Point1.x - Point2.x) + (Point1.y - Point2.y) * (Point1.y - Point2.y)\n return math.sqrt(r2)\n\n","sub_path":"model_statics/Environment.py","file_name":"Environment.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"70971369","text":"#coding=utf-8\n'''\n球用ViscElCapMat材料,面用FrictMat材料,固定间距0.1m下落\n'''\nfrom yade import plot, qt\nfrom numpy import *\n\n# 材料参数\nfr = radians(80)\nrho = 2000\ntc = 0.001\nen = 0.1\net = 0.1\nGamma = 20.6 * 1e-2\nTheta = 0\nVB = 74.2 * 1e-12\n# 面的材料\n# facetMat = O.materials.append(FrictMat(young=1000, poisson=0.2, frictionAngle=frictionAngle))\n# # 颗粒的材料\n# dfltSpheresMat = O.materials.append(\n# FrictMat(density=density, young=1000, poisson=0.2, frictionAngle=frictionAngle))\nshotsId, steelId = O.materials.append([\n ViscElCapMat(dcap=0.5,\n frictionAngle=fr,\n density=rho,\n Vb=VB,\n gamma=Gamma,\n theta=Theta,\n Capillar=True,\n CapillarType=\"Rabinovich\",\n tc=tc,\n en=en,\n et=et,\n label='spheres'),\n FrictMat(young=2e9,\n density=7800,\n poisson=.3,\n frictionAngle=radians(80),\n label='steel'),\n])\n\n# 设置顶盖和容器\ncenter = (0, 0, 0)\ndBunker = 0.2\ndOutput = 0.1\nhBunker = 0.2\nhOutput = 0.2\nhPipe = 0\nBunker = geom.facetBunker(center,\n dBunker,\n dOutput,\n hBunker,\n hOutput,\n material='steel')\ndBunkerWallID = O.bodies.append(\n geom.facetBox((0, 0, .4), (.1, .1, 0), wallMask=32, material='steel'))\nBunkerID = O.bodies.append(Bunker)\nBunkerID = BunkerID + dBunkerWallID\n\n# 设置底部平台\nzl = -.1\nx0l = -.5\nx1l = .5\ny0l = -1\ny1l = 2\ntable = pack.sweptPolylines2gtsSurface([[\n Vector3(x0l, y0l, zl),\n Vector3(x0l, y1l, zl),\n Vector3(x1l, y1l, zl),\n Vector3(x1l, y0l, zl)\n]],\n capStart=True,\n capEnd=True)\ntblIds = O.bodies.append(\n pack.gtsSurface2Facets(table, material='steel', color=(0, 1, 0)))\n\n# 添加颗粒\npred = pack.inCylinder((0, 0, .3), (0, 0, .4), radius=0.07)\nspheres = pack.regularHexa(pred, radius=0.003, gap=0.001, material='spheres')\nO.bodies.append(spheres)\n\nO.engines = [\n ForceResetter(),\n InsertionSortCollider([Bo1_Sphere_Aabb(),\n Bo1_Facet_Aabb()]),\n InteractionLoop([Ig2_Sphere_Sphere_ScGeom6D(),\n Ig2_Facet_Sphere_ScGeom()], [\n Ip2_FrictMat_FrictMat_FrictPhys(),\n Ip2_ViscElCapMat_ViscElCapMat_ViscElCapPhys()\n ], [\n Law2_ScGeom_FrictPhys_CundallStrack(),\n Law2_ScGeom_ViscElCapPhys_Basic()\n ]),\n NewtonIntegrator(gravity=(0, 0, -9.81)),\n]\nO.dt = 0.002 * tc\n\n# Enable 3D view.\nV = qt.View()\nO.saveTmp()\n","sub_path":"4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":2820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"589129581","text":"import logging\nimport logging.config\n\nLOGGING = {\n 'version': 1,\n 'formatters': {\n 'brief': {\n 'format': '{message!s}',\n 'style': '{'\n },\n 'default': {\n 'format': '{asctime!s} {levelname!s:8} {name!s:15} {message!s}',\n 'datefmt': '%Y/%m/%d %H:%M:%S'\n },\n # 'custom': {\n # 'class': 'CustomAdapter',\n # 'moduleName': __name__,\n # 'yaa': 'test'\n # }\n },\n # 'filters': {\n # 'special': {\n # 'class': 'SpecialFilter',\n # }\n # },\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n 'level': 'DEBUG',\n 'formatter': 'brief'\n }\n },\n 'loggers': {\n 'root.this': {\n 'handlers': ['console'],\n 'level': 'INFO',\n # 'filters': ['special'],\n }\n }}\n\n\nclass CustomAdapter(logging.LoggerAdapter):\n def process(self, msg, kwargs):\n return f'[{self.extra[\"moduleName\"]}][{self.extra[\"yaa\"]}] {msg}', kwargs\n\n\nif __name__ == '__main__':\n # logger = logging.getLogger()\n # logging.basicConfig(level=logging.DEBUG)\n # adapter = CustomAdapter(logger, {'moduleName': __name__, 'yaa': 'test'})\n\n # adapter.info('this')\n logging.config.dictConfig(LOGGING)\n logger = CustomAdapter(logging.getLogger('root.this'), {\n 'moduleName': 'test', 'yaa': 'test'})\n logger.info('test')\n","sub_path":"Python/Lib/logger_learn/Logger.py","file_name":"Logger.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"332581981","text":"import maya.cmds as cmds\n\n\nclass WinA_Global:\n \n winName = 'sgui_selectByName'\n title = 'Select By Name'\n width = 450\n height = 50\n\n fld_searchString = ''\n\n\n\nclass WinA_Field:\n \n def __init__(self, label, w, h, al ):\n \n self.label = label\n self.width = w\n self.height = h\n self.aline = al\n\n\n def create(self):\n \n form = cmds.formLayout()\n text = cmds.text( l=self.label, w=self.width, h=self.height, al= self.aline )\n txf = cmds.textField( h = self.height )\n cmds.setParent( '..' )\n \n cmds.formLayout( form, e=1, \n af = [( text, 'top', 0 ), ( text, 'left', 0 ),\n ( txf, 'top', 0 ), ( txf, 'right', 0 )],\n ac = [( txf, 'left', 0, text )] )\n \n self.txf = txf\n self.form = form\n \n return form\n \n\n\n\nclass WinA_Cmd:\n\n @staticmethod\n def cmdSelectByName( *args ):\n \n searchString = cmds.textField( WinA_Global.fld_searchString, q=1, tx=1 )\n \n targets = cmds.ls( tr=1 )\n \n selTargets = []\n for target in targets:\n targetName = target.split( '|' )[-1]\n if targetName.lower().find( searchString.lower() ) != -1:\n selTargets.append( target )\n\n cmds.select( selTargets )\n \n\n\n\n\n\nclass WinA:\n\n \n def __init__(self):\n \n self.winName = WinA_Global.winName\n self.title = WinA_Global.title\n self.width = WinA_Global.width\n self.height = WinA_Global.height\n \n self.uiField = WinA_Field( 'Search String : ', 100, 23, 'right' )\n\n\n def create(self):\n \n if cmds.window( self.winName, ex=1 ):\n cmds.deleteUI( self.winName, wnd=1 )\n cmds.window( self.winName, title=self.title )\n \n form = cmds.formLayout()\n form_field = self.uiField.create()\n bt_select = cmds.button( l='S E L E C T', c= WinA_Cmd.cmdSelectByName )\n cmds.setParent( '..' )\n \n cmds.formLayout( form, e=1, \n af=[( form_field, 'top', 5 ), ( form_field, 'left', 5 ), ( form_field, 'right', 5 ),\n ( bt_select, 'left', 0 ), ( bt_select, 'right', 0 )],\n ac=[( bt_select, 'top', 5, form_field )] )\n \n cmds.window( self.winName, e=1, wh=[ self.width, self.height ], rtf=1 )\n cmds.showWindow( self.winName )\n \n WinA_Global.fld_searchString = self.uiField.txf\n\n\ndef show():\n \n WinA().create()\n\n\nif __name__ == '__main__':\n show()","sub_path":"scripts/sgMaya/sgWidget/selectByName.py","file_name":"selectByName.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"82903433","text":"# Welcome to the simple Yaniv cool Python encryption library\n# stringEncryption is the function of text encoding within this directory\n# stringDecryption is the function of text decoding within this directory\n\nimport error\n\ndef stringEncryption(string, key):\n if string == '':\n error.error('A key cannot be empty')\n elif key == '':\n error.error('A key cannot be empty')\n s = ''\n z = 0\n for i in string:\n e = 0\n q = 0\n for a in key:\n q = q + ord(a)\n e = e + ord(i) * q * len(string) * (z + 1)\n s = s + str(chr(e))\n if z < len(string) - 1:\n s = s + ';'\n z = z + 1\n return s\n\ndef stringDecryption(string, key):\n try:\n if string == '':\n error.error('A key cannot be empty')\n elif key == '':\n error.error('A key cannot be empty')\n e = ''\n s = str(string).split(';')\n d = 0\n for i in s:\n w = int(ord(i))\n g = []\n for a in key:\n g.insert(0, a)\n q = 0\n for p in g:\n q = q + ord(p)\n w = w / len(s) / q / (d + 1)\n e = e + chr(int(w))\n d = d + 1\n return e\n except Exception:\n error.error('Incorrect key or string')\n","sub_path":"encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"380689951","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2021 Intel Corporation\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 copy\nimport numpy as np\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import tensor_util\nfrom neural_compressor.utils.utility import dump_elapsed_time\nfrom neural_compressor.adaptor.tf_utils.graph_rewriter.graph_util import GraphAnalyzer\nfrom ..graph_base import GraphRewriterBase\nfrom ..graph_util import GraphRewriterHelper as Helper\n\n\nclass GenerateITEXModel(GraphRewriterBase):\n \"\"\" Insert Q/DQ pairs before quantizable ops.\n\n Args: model: input model.\n data: sampling data.\n\n Return: converted model\n \"\"\"\n\n def __init__(self, model, calibration_data):\n super().__init__(model)\n self.data = calibration_data\n\n @dump_elapsed_time(\"Pass GenerateITEXGraph\")\n def do_transformation(self):\n itex_min_max_values = {}\n for i in self.data:\n if i.find('_requant') == -1:\n key, value = i.rsplit(':')[0], i.rsplit(':')[1]\n key = key.split('_eightbit_')[0][1:] + key[-5:]\n if key not in itex_min_max_values:\n itex_min_max_values[key] = [float(value[1:-1])]\n else:\n itex_min_max_values[key].append(float(value[1:-1]))\n quantizable_op_names = []\n for i in itex_min_max_values:\n if i.split('__')[0] not in quantizable_op_names:\n quantizable_op_names.append(i.split('__')[0])\n\n g = GraphAnalyzer()\n g.graph = copy.deepcopy(self.model.graph_def)\n graph_info = g.parse_graph()\n for op_name in quantizable_op_names:\n min_node = Helper.create_constant_node(\n op_name + '_min', np.min(itex_min_max_values[op_name+'__min']), dtypes.float32)\n max_node = Helper.create_constant_node(\n op_name + '_max', np.max(itex_min_max_values[op_name+'__max']), dtypes.float32)\n quantizable_node_input = graph_info[op_name].node.input[0]\n quant_v2_node = Helper.create_node(\n \"QuantizeV2\", op_name + '_quantize',\n [quantizable_node_input, min_node.name, max_node.name])\n is_asymmetric = bool(graph_info[op_name].node.op == 'MatMul')\n quant_deq_dt = dtypes.quint8 if is_asymmetric else dtypes.qint8\n Helper.set_attr_dtype(quant_v2_node, \"T\", quant_deq_dt)\n if not is_asymmetric:\n Helper.set_attr_string(quant_v2_node, \"round_mode\", b\"HALF_TO_EVEN\")\n Helper.set_attr_bool(quant_v2_node, \"narrow_range\", False if is_asymmetric else True)\n\n Helper.set_attr_string(\n quant_v2_node, \"mode\", b\"MIN_FIRST\" if is_asymmetric else b\"SCALED\")\n\n dequantize_node = Helper.create_node(\"Dequantize\", op_name + '_dequantize',\n [quant_v2_node.name,\n quant_v2_node.name + ':1',\n quant_v2_node.name + ':2'])\n Helper.set_attr_dtype(dequantize_node, \"T\", quant_deq_dt)\n Helper.set_attr_string(\n dequantize_node, \"mode\", b\"MIN_FIRST\" if is_asymmetric else b\"SCALED\")\n g.add_node(quant_v2_node,\n graph_info[op_name].node.input[0],\n [dequantize_node.name])\n g.add_node(dequantize_node, quant_v2_node.name, [op_name])\n g.add_node(min_node, None, [quant_v2_node.name])\n g.add_node(max_node, None, [quant_v2_node.name])\n graph_info[op_name].node.input[0] = dequantize_node.name\n\n g_weight = GraphAnalyzer()\n g_weight.graph = g.dump_graph()\n graph_info = g_weight.parse_graph()\n target_nodes = g_weight.query_fusion_pattern_nodes(\n [[\"Conv2D\", \"MatMul\"], [\"BiasAdd\"], ('Relu',)])\n for i in target_nodes:\n computational_node_name = i[0]\n computational_node = graph_info[computational_node_name].node\n weight_name = computational_node.input[1]\n weight_node = graph_info[weight_name].node\n weight_tensor = tensor_util.MakeNdarray(weight_node.attr['value'].tensor)\n min_value = np.min(weight_tensor)\n max_value = np.max(weight_tensor)\n min_const_node = Helper.create_constant_node(\n weight_name + '_min', min_value, dtypes.float32)\n max_const_node = Helper.create_constant_node(\n weight_name + '_max', max_value, dtypes.float32)\n quant_node = Helper.create_node(\n \"QuantizeV2\", weight_name + '_quant',\n [weight_name, weight_name + '_min', weight_name + '_max'])\n dequant_node=Helper.create_node(\n \"Dequantize\", weight_name + '_dequant',\n [quant_node.name, quant_node.name + ':1', quant_node.name + ':2'])\n Helper.set_attr_dtype(quant_node, \"T\", dtypes.qint8)\n Helper.set_attr_string(quant_node, \"mode\", b\"SCALED\")\n Helper.set_attr_string(quant_node, \"round_mode\", b\"HALF_TO_EVEN\")\n\n Helper.set_attr_dtype(dequant_node, \"T\", dtypes.qint8)\n Helper.set_attr_string(dequant_node, \"mode\", b\"SCALED\")\n\n g_weight.add_node(quant_node, weight_name, [])\n g_weight.add_node(min_const_node, None, [quant_node.name])\n g_weight.add_node(max_const_node, None, [quant_node.name])\n g_weight.add_node(dequant_node, quant_node.name, [computational_node_name])\n computational_node.input[1] = dequant_node.name\n\n return g_weight.dump_graph()\n","sub_path":"neural_compressor/adaptor/tf_utils/graph_rewriter/itex/itex_convert.py","file_name":"itex_convert.py","file_ext":"py","file_size_in_byte":6230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"120234158","text":"\nimport sys\nimport time\nimport subprocess\nimport os\nfrom termcolor import colored, cprint\n\nSCORE = int(sys.argv[2])\nTOTAL_TIME = time.time()\nLEVEL = int(sys.argv[1])\n\npgl = []\ny = []\n\ndef welcome():\n cprint(\"\\n\\n\\tWelcome in a final battle!\", \"green\", attrs=[\"bold\"])\n cprint(\"\\n\\tTo defeat the evil King of Monkeys you need to guess how many bananas he ate today\", \"green\", attrs=[\"bold\"])\n cprint(\"\\n\\tHere are some clues:\\n\", attrs=[\"bold\"])\n cprint(\"\\tHe eats a lot so it's 3 digit number.\", \"green\", attrs=[\"bold\"])\n cprint(\"\\tWhen he say: That means:\", \"green\", attrs=[\"bold\"])\n cprint(\"\\tCOLD! No digit is correct.\", \"green\", attrs=[\"bold\"])\n cprint(\"\\tWarm One digit is correct but in the wrong position.\", \"green\", attrs=[\"bold\"])\n cprint(\"\\tHot One digit is correct and in the right position.\", \"green\", attrs=[\"bold\"])\n cprint(\"\\n\\tKing of Monkeys ate a many bananas today. You have 10 guesses!.\", \"green\", attrs=[\"bold\"])\n\n\ndef random_number():\n import random\n random_number = random.sample(range(1, 10), 3)\n print(random_number, \";)\")\n global y\n y = list(random_number)\n #print(y)\n\n\ndef player_guess():\n chance = 0\n global SCORE\n while True:\n chance += 1\n if chance == 11:\n cprint(\"\\tThe very bad King of Monkeys won...\", attrs=[\"bold\"])\n cprint(\"\\tThis mean that you LOSE and have to go back to the jungle!\", \"green\", attrs=[\"bold\"])\n cprint(\"\\t _,,,_ _,,,_ _,,,_ \", \"yellow\", attrs=[\"bold\"])\n cprint(\"\\t (d. .b) (dx xb) (d> eps:\n ceil = math.pow(10.0, 20)\n va_qs = np.where(va, qs, np.full_like(qs, -ceil))\n action = np.argmax(va_qs)\n else:\n va_qs = np.where(qs * va)[0]\n action = va_qs[random.randint(0, len(va_qs) - 1)]\n else:\n action = np.argmax(qs)\n return action\n\n def ppo_sample(self, va, logits):\n ceil = math.pow(10.0, 20)\n logits = np.where(va, logits, np.full_like(logits, -ceil))\n logits_max = np.amax(logits)\n logits = va * (np.exp(logits - logits_max) + 1e-6)\n sum_logits = np.sum(logits)\n if sum_logits == 0:\n return np.full_like(logits, 1) / len(logits)\n pi = logits / sum_logits\n return np.argmax(pi)\n\n def loss(self, input_dict):\n r\"\"\"Returns loss.\n\n Args:\n input_dict (dict): A dict of inputs.\n\n Returns:\n Output from :func:`~plf.policy.algorithm.algorithm.Algorithm.loss`\\.\n \"\"\"\n self.loss_counter += 1\n if self.loss_counter % self.update_target_net_gap == 0:\n input_dict[\"update_target_net\"] = np.array(1)\n input_dict[\"train\"] = np.array(1)\n\n out = self.model.forward(input_dict)\n out = self.alg.loss(out)\n\n return out\n\n @expose_to_interface\n def set_greedy(self, greedy):\n r\"\"\"\n set_greedy(greedy)\n Sets attr :attr:`~greedy`\\.\n\n Args:\n greedy (bool): Selects actions with maximum probability.\n \"\"\"\n self.greedy = greedy\n","sub_path":"work/policy/greedy_policy_impl.py","file_name":"greedy_policy_impl.py","file_ext":"py","file_size_in_byte":3911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"290732858","text":"import numpy as np\nimport glob\nfrom utils.utils import bbox_iou \nimport torch\nimport random\n\ndef k_means(dataset, k):\n '''\n Function which takes dataset and number of clusters as\n arguments and returns centroids for different clusters and cluster\n assignment for all the samples of dataset\n Arguments:\n dataset: input dataset\n k: number of clusters\n Returns:\n cluster_centroid: centroid of different clusters\n custer_assignment: cluster assignment for each sample in the dataset\n '''\n n_samples = dataset.shape[0]\n d = dataset.shape[1]\n l = random.choices(list(range(dataset.shape[0])), k=k)\n cluster_centroid = dataset[l,:] \n cluster_centroid = torch.FloatTensor(np.concatenate((np.zeros((len(cluster_centroid), 2)), np.array(cluster_centroid)), 1)) \n \n # Creating array of shape n_sample*1 to store cluster assignment for each samples\n cluster_assignment = np.zeros((n_samples, 1))\n epochs = 1000\n\n for e in range(epochs):\n # Assigning cluster to each sample of dataset\n for i in range(n_samples):\n \n gw = dataset[i,:][0]\n gh = dataset[i,:][1]\n point = torch.FloatTensor(np.array([0, 0, gw, gh])).unsqueeze(0)\n iou = bbox_iou(point, cluster_centroid)\n cluster_assignment[i] = 1 - torch.argmin(iou)# Updating cluster centroids\n\n for j in range(k):\n points = dataset[list((cluster_assignment==j).squeeze(1)),:]\n cluster_cen = np.mean(points, axis = 0).reshape(1,-1)\n cluster_cen = torch.FloatTensor(np.concatenate((np.zeros((len(cluster_cen), 2)), np.array(cluster_cen)), 1)) \n cluster_centroid[[j],:] = cluster_cen\n return(cluster_centroid, cluster_assignment)\n\nlabel_files = glob.glob('./data/labels_for_clustering/*.txt')\nX = None\nfor file in label_files:\n with open(file, 'r') as f:\n l = f.readline().strip().split(' ')\n h = float(l[3])\n w = float(l[4])\n \n if X is None:\n X = np.array([[h,w]])\n else:\n X = np.vstack((X, np.array([h,w])))\n\n\nX_416 = X*416\nc, d = k_means(X_416, 9)","sub_path":"YOLO/KMeans.py","file_name":"KMeans.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"414632476","text":"#!/usr/bin/env python\r\n# encoding=UTF-8\r\n\r\n#文件名:xd547/Views/MessageManage.py\r\n#描 述:留言管理的View定义\r\n#创建日期:2009-04-05\r\n#修改日期:2009-04-28\r\n\r\nimport os\r\nimport cgi\r\n\r\nfrom google.appengine.ext.webapp import template\r\nfrom google.appengine.ext import webapp\r\nfrom google.appengine.api import datastore\r\nfrom google.appengine.api import users\r\nfrom google.appengine.api import memcache\r\n\r\nfrom xd547.Views import Javascript\r\nfrom xd547.Views import Css\r\n\r\nfrom xd547.Controllers.Message import MessageController\r\nfrom xd547.Controllers.Settings import SettingsController\r\nfrom xd547.Functions.Functions import dateFormat\r\nfrom xd547.Functions import Functions\r\nfrom xd547.Error import Error as xd547Error\r\n\r\nclass ListMessage(webapp.RequestHandler):\r\n def get(self):\r\n settings = SettingsController()\r\n settings.Get()\r\n limit = settings.GetDefaultMsgEntriesCount()\r\n start = cgi.escape(self.request.get('page'))\r\n \r\n start = Functions.PaginationGetStart(limit, start)\r\n \r\n messages = MessageController().GetAll(limit, start * limit)\r\n \r\n totalLength = MessageController().GetCount(0)\r\n pageLength = len(messages)\r\n path = self.request.path\r\n \r\n pager = Functions.PaginationGetPager(start, limit, totalLength, pageLength, path)\r\n \r\n \r\n css_flag = False\r\n \r\n for message in messages:\r\n message.css = (\"tr0\",\"tr1\")[css_flag]\r\n css_flag = not css_flag\r\n \r\n webapp.template.register_template_library('xd547.Functions.Functions')\r\n m_template_values = {\r\n 'messages' : messages,\r\n 'pager' : pager\r\n }\r\n \r\n m_path = os.path.join(os.path.dirname(__file__),'..','..','htmlfiles', 'messagemanage.html')\r\n \r\n info = template.render(m_path, m_template_values)\r\n script = Javascript.Loder(['http://www.google.com/jsapi'],1)\r\n script += Javascript.Loder(['xd547.js',\r\n 'messagemanage.js']);\r\n css = Css.Loder([\"datalist.css\"])\r\n title = \"留言管理\"\r\n template_values = {\r\n 'title' : title,\r\n 'css' : css,\r\n 'script' : script,\r\n 'maintitle' : title,\r\n 'info' : info\r\n }\r\n path = os.path.join(os.path.dirname(__file__),'..','..','htmlfiles', 'admin_main.html')\r\n self.response.out.write(template.render(path, template_values))\r\n \r\nclass EditMessage(webapp.RequestHandler):\r\n def get(self):\r\n key = cgi.escape(self.request.get(\"key\"))\r\n \r\n message = MessageController().Get(key)\r\n m_template_values = {\r\n 'key' : message[\"key\"],\r\n 'author' :(message[\"author\"], \"匿名用户\")[ message[\"author\"] is None],\r\n 'date' : dateFormat(message[\"date\"]),\r\n 'ip' : message[\"ip\"],\r\n 'content' : message[\"content\"],\r\n 'isPrivateTrue': (\"\", 'selected=\"true\"')[message[\"isPrivate\"] == True],\r\n 'isPrivateFalse': ('selected=\"true\"', \"\")[message[\"isPrivate\"] == True]\r\n }\r\n \r\n m_path = os.path.join(os.path.dirname(__file__),'..','..','htmlfiles', 'editmessage.html')\r\n \r\n info = template.render(m_path, m_template_values)\r\n script = Javascript.Loder(['http://www.google.com/jsapi'],1)\r\n script += Javascript.Loder(['xd547.js',\r\n 'editmessage.js']);\r\n title = \"留言修改\"\r\n template_values = {\r\n 'title' : title,\r\n 'script' : script,\r\n 'maintitle' : title,\r\n 'info' : info\r\n }\r\n path = os.path.join(os.path.dirname(__file__),'..','..','htmlfiles', 'admin_main.html')\r\n self.response.out.write(template.render(path, template_values))\r\n \r\n def post(self):\r\n key = cgi.escape(self.request.get(\"key\"))\r\n content = cgi.escape(self.request.get(\"content\"))\r\n isPrivate =(True,False)[cgi.escape(self.request.get(\"isPrivate\")) == u\"false\"]\r\n \r\n result = ''\r\n try:\r\n message = MessageController().Get(key)\r\n MessageController().Update(key, message[\"author\"], content, message[\"ip\"], isPrivate)\r\n result = '''{\"info\" : \"updatesuccess\"}'''\r\n except:\r\n result = '''{\"info\" : \"updateerror\"}'''\r\n self.response.headers[\"Content-Type\"] = \"text/plain\"\r\n self.response.out.write(result)\r\n\r\nclass DelMessage(webapp.RequestHandler):\r\n def post(self):\r\n key = cgi.escape(self.request.get(\"key\"))\r\n try:\r\n MessageController().Del(key)\r\n memcache.flush_all();\r\n except:\r\n pass","sub_path":"xd547/site/xd547/Views/MessageManage.py","file_name":"MessageManage.py","file_ext":"py","file_size_in_byte":4788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"101866518","text":"#!/usr/bin/python\n\n# Copyright 2020 Hewlett Packard Enterprise Development LP\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this\n# file except in compliance with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software distributed\n# under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS\n# OF ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# author Alok Ranjan (alok.ranjan2@hpe.com)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\nDOCUMENTATION = r'''\n---\nauthor:\n - HPE Nimble Storage Ansible Team (@ar-india) \ndescription: Manage the snapshots on an HPE Nimble Storage group.\nmodule: hpe_nimble_snapshot\noptions:\n agent_type:\n required: False\n choices:\n - none\n - smis\n - vvol\n - openstack\n - openstackv2\n type: str\n description:\n - External management agent type.\n app_uuid:\n required: False\n type: str\n description:\n - Application identifier of snapshot.\n change_name:\n required: False\n type: str\n description:\n - Change name of the existing snapshot.\n description:\n required: False\n type: str\n description:\n - Text description of snapshot.\n expiry_after:\n required: False\n type: int\n description:\n - Number of seconds after which this snapshot is considered expired by snapshot TTL. A value of 0 indicates that snapshot never expires.\n force:\n required: False\n type: bool\n default: False\n description:\n - Forcibly delete the specified snapshot even if it is the last replicated collection. Doing so could lead to full re-seeding at the next replication.\n metadata:\n required: False\n type: dict\n description:\n - Key-value pairs that augment a snapshot's attributes. List of key-value pairs. Keys must be unique and non-empty.\n name:\n required: True\n type: str\n description:\n - Name of the snapshot.\n online:\n required: False\n type: bool\n default: False\n description:\n - Online state for a snapshot means it could be mounted for data restore.\n state:\n required: True\n choices:\n - present\n - absent\n - create\n type: str\n description:\n - The snapshot state.\n volume:\n required: True\n type: str\n description:\n - Parent volume name.\n writable:\n required: False\n type: bool\n default: False\n description:\n - Allow snapshot to be writable. Mandatory and must be set to 'true' for VSS application synchronized snapshots.\nextends_documentation_fragment: hpe.nimble.hpe_nimble\nshort_description: Manage the HPE Nimble Storage snapshots.\nversion_added: \"2.9.0\"\n'''\n\nEXAMPLES = r'''\n\n# if state is create , then create a snapshot if not present. Fails if already present.\n# if state is present, then create a snapshot if not present. Succeeds if it already exists.\n- name: Create snapshot if not present\n hpe_nimble_snapshot:\n host: \"{{ host }}\"\n username: \"{{ username }}\"\n password: \"{{ password }}\"\n state: \"{{ state | default('present') }}\"\n volume: \"{{ volume }}\"\n name: \"{{ name }}\"\n online: \"{{ online | default(true) }}\"\n writable: \"{{ writable | default(false) }}\"\n\n- name: Delete snapshot (must be offline)\n hpe_nimble_snapshot:\n host: \"{{ host }}\"\n username: \"{{ username }}\"\n password: \"{{ password }}\"\n volume: \"{{ volume }}\"\n name: \"{{ name }}\"\n state: absent\n\n'''\nRETURN = r'''\n'''\n\nfrom ansible.module_utils.basic import AnsibleModule\ntry:\n from nimbleclient.v1 import client\nexcept ImportError:\n client = None\nimport ansible_collections.hpe.nimble.plugins.module_utils.hpe_nimble as utils\n\n\ndef create_snapshot(\n client_obj,\n vol_name,\n snapshot_name,\n **kwargs):\n\n if utils.is_null_or_empty(snapshot_name):\n return (False, False, \"Create snapshot failed as snapshot is not present.\", {}, {})\n if utils.is_null_or_empty(vol_name):\n return (False, False, \"Create snapshot failed as volume is not present.\", {}, {})\n\n try:\n vol_resp = client_obj.volumes.get(id=None, name=vol_name)\n if utils.is_null_or_empty(vol_resp):\n return (False, False, f\"Volume '{vol_name}' not present on array for taking snapshot.\", {}, {})\n snap_resp = client_obj.snapshots.get(id=None, vol_name=vol_name, name=snapshot_name)\n if utils.is_null_or_empty(snap_resp):\n params = utils.remove_null_args(**kwargs)\n snap_resp = client_obj.snapshots.create(name=snapshot_name,\n vol_id=vol_resp.attrs.get(\"id\"),\n **params)\n if snap_resp is not None:\n return (True, True, f\"Snapshot '{snapshot_name}' created successfully.\", {}, snap_resp.attrs)\n else:\n return (False, False, f\"Snapshot '{snapshot_name}' cannot be created as it is already present in given state.\", {}, {})\n except Exception as ex:\n return (False, False, f\"Snapshot creation failed | {ex}\", {}, {})\n\n\ndef update_snapshot(\n client_obj,\n snap_resp,\n **kwargs):\n\n if utils.is_null_or_empty(snap_resp):\n return (False, False, \"Update snapshot failed as snapshot is not present.\", {}, {})\n\n try:\n snapshot_name = snap_resp.attrs.get(\"name\")\n changed_attrs_dict, params = utils.remove_unchanged_or_null_args(snap_resp, **kwargs)\n if changed_attrs_dict.__len__() > 0:\n snap_resp = client_obj.snapshots.update(id=snap_resp.attrs.get(\"id\"), **params)\n return (True, True, f\"Snapshot '{snapshot_name}' already present. Modified the following attributes '{changed_attrs_dict}'\",\n changed_attrs_dict, snap_resp.attrs)\n else:\n return (True, False, f\"Snapshot '{snapshot_name}' already present in given state.\", {}, snap_resp.attrs)\n\n except Exception as ex:\n return (False, False, f\"Snapshot update failed | {ex}\", {}, {})\n\n\ndef delete_snapshot(\n client_obj,\n vol_name,\n snapshot_name):\n\n if utils.is_null_or_empty(snapshot_name):\n return (False, False, \"Delete snapshot failed as snapshot is not present.\", {})\n if utils.is_null_or_empty(vol_name):\n return (False, False, \"Delete snapshot failed. Volume is not present.\", {})\n\n try:\n vol_resp = client_obj.volumes.get(id=None, name=vol_name)\n if utils.is_null_or_empty(vol_resp):\n return (False, False, f\"Volume '{vol_name}' is not present on Array for deleting snapshot.\", {})\n snap_resp = client_obj.snapshots.get(id=None, vol_name=vol_name, name=snapshot_name)\n if utils.is_null_or_empty(snap_resp):\n return (False, False, f\"Snapshot '{snapshot_name}' cannot be deleted as it is not present in given volume '{vol_name}'.\", {})\n else:\n client_obj.snapshots.delete(id=snap_resp.attrs.get(\"id\"))\n return (True, True, f\"Deleted snapshot '{snapshot_name}' successfully.\", {})\n except Exception as ex:\n return (False, False, f\"Snapshot deletion failed | {ex}\", {})\n\n\ndef main():\n\n fields = {\n \"state\": {\n \"required\": True,\n \"choices\": ['present',\n 'absent',\n 'create'\n ],\n \"type\": \"str\"\n },\n \"change_name\": {\n \"required\": False,\n \"type\": \"str\",\n \"no_log\": False\n },\n \"name\": {\n \"required\": True,\n \"type\": \"str\",\n \"no_log\": False\n },\n \"description\": {\n \"required\": False,\n \"type\": \"str\",\n \"no_log\": False\n },\n \"volume\": {\n \"required\": True,\n \"type\": \"str\"\n },\n \"online\": {\n \"required\": False,\n \"type\": \"bool\",\n \"no_log\": False\n },\n \"writable\": {\n \"required\": False,\n \"type\": \"bool\",\n \"no_log\": False\n },\n \"app_uuid\": {\n \"required\": False,\n \"type\": \"str\",\n \"no_log\": False\n },\n \"metadata\": {\n \"required\": False,\n \"type\": \"dict\"\n },\n \"agent_type\": {\n \"required\": False,\n \"choices\": ['none', 'smis', 'vvol', 'openstack', 'openstackv2'],\n \"type\": \"str\"\n },\n \"expiry_after\": {\n \"required\": False,\n \"type\": \"int\",\n \"no_log\": False\n },\n \"force\": {\n \"required\": False,\n \"type\": \"bool\",\n \"default\": False,\n \"no_log\": False\n }\n }\n default_fields = utils.basic_auth_arg_fields()\n fields.update(default_fields)\n required_if = [('state', 'create', ['volume'])]\n\n module = AnsibleModule(argument_spec=fields, required_if=required_if)\n if client is None:\n module.fail_json(msg='Python nimble-sdk could not be found.')\n\n hostname = module.params[\"host\"]\n username = module.params[\"username\"]\n password = module.params[\"password\"]\n state = module.params[\"state\"]\n snapshot_name = module.params[\"name\"]\n change_name = module.params[\"change_name\"]\n description = module.params[\"description\"]\n vol_name = module.params[\"volume\"]\n online = module.params[\"online\"]\n writable = module.params[\"writable\"]\n app_uuid = module.params[\"app_uuid\"]\n metadata = module.params[\"metadata\"]\n agent_type = module.params[\"agent_type\"]\n expiry_after = module.params[\"expiry_after\"]\n force = module.params[\"force\"]\n\n if (username is None or password is None or hostname is None or snapshot_name is None):\n module.fail_json(\n msg=\"Storage system IP or username or password is null or snapshot name is null.\")\n\n # defaults\n return_status = changed = False\n msg = \"No task to run.\"\n resp = None\n try:\n client_obj = client.NimOSClient(\n hostname,\n username,\n password\n )\n\n # States\n if state == \"create\" or state == \"present\":\n snap_resp = client_obj.snapshots.get(id=None, vol_name=vol_name, name=snapshot_name)\n if utils.is_null_or_empty(snap_resp) or state == \"create\":\n return_status, changed, msg, changed_attrs_dict, resp = create_snapshot(\n client_obj,\n vol_name,\n snapshot_name,\n description=description,\n online=online,\n writable=writable,\n app_uuid=app_uuid,\n metadata=metadata,\n agent_type=agent_type)\n else:\n # update op\n return_status, changed, msg, changed_attrs_dict, resp = update_snapshot(\n client_obj,\n snap_resp,\n name=change_name,\n description=description,\n online=online,\n expiry_after=expiry_after,\n app_uuid=app_uuid,\n metadata=metadata,\n force=force)\n\n elif state == \"absent\":\n return_status, changed, msg, changed_attrs_dict = delete_snapshot(\n client_obj,\n vol_name,\n snapshot_name)\n\n except Exception as ex:\n # failed for some reason.\n msg = str(ex)\n\n if return_status:\n if utils.is_null_or_empty(resp):\n module.exit_json(return_status=return_status, changed=changed, msg=msg)\n else:\n module.exit_json(return_status=return_status, changed=changed, msg=msg, attrs=resp)\n else:\n module.fail_json(return_status=return_status, changed=changed, msg=msg)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ansible_collection/hpe/nimble/plugins/modules/hpe_nimble_snapshot.py","file_name":"hpe_nimble_snapshot.py","file_ext":"py","file_size_in_byte":12262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"32391520","text":"\n\nfrom orms.models import UserModel\n\n\ndef my_user(request):\n username = request.session.get('user', '未登录')\n user = UserModel.objects.filter(username=username).first()\n if user:\n return {'my_user': username}\n else:\n return {}","sub_path":"orms/Middleware/myuser.py","file_name":"myuser.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"195495435","text":"''' importing the necessary libraries'''\n\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem.wordnet import WordNetLemmatizer\nlmtzr = WordNetLemmatizer()\nfrom string import digits\neng_words = set(nltk.corpus.words.words())\nimport re\nfrom nltk.corpus import wordnet as wn\n\nclass text_cleaning():\n ''' This class includes methods which are generally \n common to any text preprocessing before vectorizing it'''\n \n def remove_digits_from_text(self,text):\n ''' Method to remove the digits from the text'''\n \n remove_digits = str.maketrans('', '', digits)\n res = text.translate(remove_digits)\n \n return res\n \n def common_text_preperation(self,text):\n ''' Method to prepare text in proper format \n such as removing stopwords ,removing symbols etc.'''\n \n replace_by_space_re = re.compile('[/(){}\\[\\]\\|@,;]')\n good_symbols_re = re.compile('[^0-9a-z]')\n stopwords_set = set(stopwords.words('english'))\n text = text.lower()\n text = replace_by_space_re.sub(' ', text)\n text = good_symbols_re.sub(' ', text)\n text = text.strip()\n temp = text.split()\n final_text = ' '.join([x for x in sorted(set(temp),key=temp.index) if x and x not in stopwords_set]) \n \n return(final_text) \n \n def text_lemmatizer(self,text):\n ''' Method to Lemmatize text'''\n \n processed_text=[]\n words = word_tokenize(text)\n for w in words:\n x=lmtzr.lemmatize(w,'v')\n x=lmtzr.lemmatize(x,'n')\n processed_text.append(x)\n \n return ' '.join(processed_text)\n \n def remove_non_dictionary_words(self,text):\n ''' Method to remove the non dictionary(english) words from the text'''\n \n text = word_tokenize(text)\n l=[]\n for word in text:\n try:\n if len(wn._morphy(word,wn.NOUN))==2:\n l.append(wn._morphy(word,wn.NOUN)[1])\n else:\n l.append(wn._morphy(word,wn.NOUN)[0]) \n except IndexError:\n if len(wn.synsets(word))==0:\n None\n else:\n l.append(word)\n text=' '.join(l)\n return text\n \n def remove_single_character_words(self,text):\n ''' Method to remove the single character words'''\n \n processed_text = ' '.join( [w for w in text.split() if len(w)>1] )\n \n return processed_text\n \n def data_cleaning(self,text):\n '''' Method to apply all cleaning steps on the input text'''\n \n text=self.remove_digits_from_text(text)\n text=self.common_text_preperation(text)\n text=self.text_lemmatizer(text) \n text=self.remove_non_dictionary_words(text)\n text=self.remove_single_character_words(text)\n \n return text\n ","sub_path":"Preprocessing/text_cleaning.py","file_name":"text_cleaning.py","file_ext":"py","file_size_in_byte":3030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"631055536","text":"\"\"\"The SConscript file\"\"\"\n\nimport os\n\nImport('env')\n\nenv = env.Clone()\n\n# Here are the libraries, in order of compilation\nlibraries = [\n 'libiconvplus',\n 'libkfather',\n 'libasiotap',\n 'libcryptoplus',\n 'libfscp',\n 'libfreelan',\n 'freelan',\n]\n\ntargets_names = [\n 'build',\n 'install',\n 'documentation',\n 'indent',\n 'samples',\n]\n\ntargets = {}\n\nfor library in libraries:\n targets[library] = SConscript(os.path.join(library, 'SConscript'), variant_dir=env.get_variant_dir(Dir(library)), exports='env')\n\n # Special alias to build the libraries\n env.Alias(library, targets[library]['build'])\n\n for target_name in targets_names:\n if target_name in targets[library]:\n env.Alias(library + '_' + target_name, targets[library][target_name])\n env.Alias(target_name, targets[library][target_name])\n\nReturn('targets')\n","sub_path":"SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"164784416","text":"'''Mail Parser.\n'''\n#\n# Copyright (c) 2007 shinGETsu Project.\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\n# are met:\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND\n# 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 AUTHORS OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n# SUCH DAMAGE.\n#\n# $Id$\n#\nimport os\nimport re\nimport sys\nimport base64\nimport email.Parser\nfrom time import time\n\nimport config\nimport gateway\nimport spam\nfrom cache import *\nfrom node import *\nfrom tmpaddr import TmpAddress\nfrom updatequeue import UpdateQueue\n\n__version__ = '$Revision$'\n\n\nclass CGI(gateway.CGI):\n '''Mail Parser.\n '''\n\n def run(self):\n self.stdout.write('Content-Type: text/plain\\r\\n')\n if (not re.search(config.admin, self.environ[\"REMOTE_ADDR\"])) and \\\n (not self.environ[\"REMOTE_ADDR\"].startswith('127')):\n self.stdout.write(\"You are not the administrator.\\n\")\n self.stdout.close()\n return\n elif self.environ.get('REQUEST_METHOD', '') != 'POST':\n return\n self.read_mail()\n\n def read_mail(self):\n '''Read mail style post from stdin.\n '''\n try:\n length = int(self.environ['CONTENT_LENGTH'])\n except (ValueError, KeyError):\n return\n msg = email.Parser.Parser().parsestr(self.stdin.read(length))\n body = ''\n attach = ''\n suffix = 'txt'\n addr = msg.get('to', '')\n tmpaddr = TmpAddress()\n if not tmpaddr.check(addr):\n return\n for part in msg.walk():\n if part.get_content_maintype() == 'multipart':\n continue\n filename = part.get_filename()\n charset = part.get_content_charset()\n if not charset:\n charset = 'utf-8'\n if filename and (not attach):\n found = re.search(r'\\.([^./]+)$', filename)\n if found:\n suffix = found.group(1)\n if part.get('Content-Transfer-Encoding', '') == 'base64':\n attach = part.get_payload(decode=False)\n else:\n attach = part.get_payload(decode=True)\n attach = base64.encodestring(attach)\n attach = attach.replace('\\n', '')\n elif (not filename) and (not body):\n body = part.get_payload(decode=True).decode(charset, 'replace')\n datfile, dummy, body = re.split(r'[\\r\\n]+', body, 2)\n if re.search(r'thread_[0-9A-F]+', datfile) and \\\n (body or attach):\n self.do_post_from_mail(datfile,\n body.encode('utf-8', 'replace'),\n attach,\n suffix)\n \n def do_post_from_mail(self, datfile, bodystr, attach, suffix):\n \"\"\"Post article.\"\"\"\n suffix = re.sub(r\"[^0-9A-Za-z]\", \"\", suffix)\n stamp = int(time())\n\n body = {'body': self.escape(bodystr)}\n if attach:\n body['attach'] = attach\n body['suffix'] = suffix\n if not body:\n return None\n\n cache = Cache(datfile)\n rec = Record(datfile=cache.datfile)\n id = rec.build(stamp, body)\n\n if len(rec.recstr) > config.record_limit*1024:\n return None\n elif spam.check(rec.recstr):\n return None\n\n if cache.exists():\n cache.add_data(rec)\n cache.sync_status()\n else:\n return None\n\n queue = UpdateQueue()\n queue.append(cache.datfile, stamp, id, None)\n queue.start()\n\n return True\n\n# End of CGI\n","sub_path":"shingetsu/mailapi_cgi.py","file_name":"mailapi_cgi.py","file_ext":"py","file_size_in_byte":4705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"161014395","text":"#!/usr/bin/env python3\r\n\r\n# client.py \r\nimport socket\r\n\r\n# create a socket object\r\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM) \r\n\r\n\r\n# get local machine name\r\n# local host IP '127.0.0.1' \r\n##host = socket.gethostname()\r\nhost = \"127.0.0.1\"\r\n# Define the port on which you want to connect \r\nport = 9999\r\n\r\n\r\n# connection to hostname on the port.\r\ns.connect((host, port)) \r\n\r\nwhile True:\r\n \r\n# message you send to server \r\n message = input(\"Enter message or 'quit' -> \")\r\n\r\n\r\n while message != 'quit':\r\n # message sent to server \r\n s.send(message.encode('ascii'))\r\n\r\n # Receive no more than 1024 bytes\r\n data = s.recv(1024) \r\n \r\n # print the received message \r\n print(\"The time got from the server is %s\" % data.decode('ascii'))\r\n \r\n break\r\n \r\n# ask the client whether he wants to continue \r\n ans = input('\\nDo you want to continue(y/n) :') \r\n if ans == 'y': \r\n continue\r\n else: \r\n break\r\n \r\n \r\n# close the connection when loop will end\r\ns.close()","sub_path":"onemoreclient.py","file_name":"onemoreclient.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"445298225","text":"# -*- coding: utf-8 -*-\nfrom pytest import raises\nfrom watson.http.messages import create_request_from_environ\nfrom watson.framework.routing import Route, Router\nfrom tests.watson.framework.support import sample_environ\n\n\nclass TestRoute(object):\n\n def test_create_route(self):\n route = Route(name='home', path='/')\n assert route.path == '/'\n assert route.name == 'home'\n assert repr(\n route) == ''\n\n def test_create_route_regex(self):\n route = Route(name='home', path='/', regex='.*')\n assert route.regex\n\n def test_static_match(self):\n route = Route(name='home', path='/')\n invalid_request = create_request_from_environ(\n sample_environ(PATH_INFO='/test'))\n valid_request = create_request_from_environ(\n sample_environ(PATH_INFO='/'))\n assert not route.match(invalid_request)\n assert route.match(valid_request)\n\n def test_optional_segment_match(self):\n route = Route(name=\"search\", path='/search[/:keyword]')\n invalid_request = create_request_from_environ(\n sample_environ(PATH_INFO='/searching'))\n valid_request = create_request_from_environ(\n sample_environ(PATH_INFO='/search'))\n valid_request_with_param = create_request_from_environ(\n sample_environ(PATH_INFO='/search/test'))\n assert not route.match(invalid_request)\n assert route.match(valid_request)\n assert route.match(valid_request_with_param)\n\n def test_optional_segment_with_defaults(self):\n route = Route(\n name=\"search\",\n path='/search[/:keyword]',\n defaults={'keyword': 'blah'})\n invalid_request = create_request_from_environ(\n sample_environ(PATH_INFO='/searching'))\n valid_request = create_request_from_environ(\n sample_environ(PATH_INFO='/search'))\n valid_request_with_param = create_request_from_environ(\n sample_environ(PATH_INFO='/search/test'))\n valid_request_with_default = route.match(valid_request)\n assert not route.match(invalid_request)\n assert valid_request_with_default\n assert valid_request_with_default.params == {'keyword': 'blah'}\n assert route.match(valid_request_with_param)\n\n def test_optional_segment_with_required(self):\n route = Route(\n name=\"search\",\n path='/search[/:keyword]',\n requires={'keyword': 'blah'})\n valid_request = create_request_from_environ(\n sample_environ(PATH_INFO='/search/blah'))\n invalid_request = create_request_from_environ(\n sample_environ(PATH_INFO='/search/test'))\n assert not route.match(invalid_request)\n assert route.match(valid_request)\n\n def test_mandatory_segment_match(self):\n route = Route(\"search\", path='/search/:keyword')\n invalid_request = create_request_from_environ(\n sample_environ(PATH_INFO='/searching'))\n valid_request_no_param = create_request_from_environ(\n sample_environ(PATH_INFO='/search'))\n valid_request_with_param = create_request_from_environ(\n sample_environ(PATH_INFO='/search/test'))\n assert not route.match(invalid_request)\n assert not route.match(valid_request_no_param)\n assert route.match(valid_request_with_param)\n\n def test_segment_bracket_mismatch(self):\n with raises(ValueError):\n Route(name='mismatch', path='/search:keyword]')\n\n def test_format_match(self):\n valid_request = create_request_from_environ(\n sample_environ(PATH_INFO='/dump',\n HTTP_ACCEPT='application/json'))\n invalid_request = create_request_from_environ(\n sample_environ(PATH_INFO='/dump', HTTP_ACCEPT='application/xml'))\n valid_request_segment = create_request_from_environ(\n sample_environ(PATH_INFO='/dump.json'))\n route = Route(name='json', path='/dump', requires={'format': 'json'})\n route_format = Route(\n name='json',\n path='/dump.:format',\n requires={'format': 'json'})\n assert route.match(valid_request)\n assert not route.match(invalid_request)\n assert route_format.match(valid_request_segment)\n\n def test_accept_method_match(self):\n valid_request = create_request_from_environ(\n sample_environ(PATH_INFO='/test', REQUEST_METHOD='POST'))\n invalid_request = create_request_from_environ(\n sample_environ(PATH_INFO='/test', REQUEST_METHOD='GET'))\n route = Route(name='test', path='/test', accepts=('POST',))\n assert route.match(valid_request)\n assert not route.match(invalid_request)\n\n def test_subdomain_match(self):\n valid_request = create_request_from_environ(\n sample_environ(PATH_INFO='/test',\n SERVER_NAME='clients.test.com',\n HTTP_HOST='clients.test.com'))\n invalid_request = create_request_from_environ(\n sample_environ(PATH_INFO='/test', SERVER_NAME='clients2.test.com',\n HTTP_HOST='clients2.test.com'))\n route = Route(name='test', path='/test', subdomain='clients')\n assert route.match(valid_request)\n assert not route.match(invalid_request)\n route_multiple_subdomains = Route(name='test', path='/test', subdomain=('clients', 'test'))\n assert route_multiple_subdomains.match(valid_request)\n assert not route_multiple_subdomains.match(invalid_request)\n\n def test_assemble_static_route(self):\n route = Route(name='test', path='/testing')\n assert route.assemble() == '/testing'\n\n def test_assemble_segment_route(self):\n route = Route(name='test', path='/search[/:keyword]')\n assert route.assemble(keyword='test') == '/search/test'\n\n def test_assemble_segment_not_required(self):\n route = Route(name='test', path='/search[/:keyword]')\n assert route.assemble() == '/search'\n route2 = Route(name='test', path='/search[/:keyword]')\n assert route2.assemble(keyword='test') == '/search/test'\n\n def test_assemble_segment_route_missing_param(self):\n with raises(KeyError):\n route = Route(\n name='test',\n path='/search/:keyword',\n requires={'keyword': '.*'})\n route.assemble()\n\n def test_requires_get_variables(self):\n route = Route(name='test', path='/', requires={'test': '.*'})\n request = create_request_from_environ(sample_environ(\n PATH_INFO='/',\n QUERY_STRING='test=blah&something=test'))\n match = route.match(request)\n assert match\n\n request = create_request_from_environ(sample_environ(\n PATH_INFO='/',\n QUERY_STRING='tesst=blah'))\n match = route.match(request)\n assert not match\n\n\nclass TestRouter(object):\n\n def test_create_from_dict(self):\n router = Router({\n 'home': {\n 'path': '/'\n }\n })\n assert len(router) == 1\n router_objects = Router({\n 'home': Route(name='home', path='/')\n })\n assert len(router_objects) == 1\n for route in router:\n assert True\n assert router.assemble('home') == '/'\n assert repr(router) == ''\n\n def test_create_from_list(self):\n router = Router([\n {\n 'name': 'home',\n 'path': '/'\n }\n ])\n assert len(router) == 1\n router_objects = Router([\n Route(name='home', path='/')\n ])\n assert len(router_objects) == 1\n\n def test_assemble_invalid_route(self):\n with raises(KeyError):\n router = Router()\n router.assemble('test')\n\n def test_sort_routes(self):\n router = Router({\n 'home': {\n 'path': '/'\n },\n 'test': {\n 'path': '/'\n },\n 'highest': {\n 'path': '/',\n 'priority': 1000\n },\n 'lowest': {\n 'path': '/',\n 'priority': -1\n }\n })\n request = create_request_from_environ(sample_environ(PATH_INFO='/'))\n matches = router.matches(request)\n assert matches[0].route.name == 'highest'\n assert matches[3].route.name == 'lowest'\n\n def test_child_route_creation(self):\n router = Router({\n 'home': {\n 'path': '/'\n },\n 'parent': {\n 'path': '/parent',\n 'children': {\n 'child_one': {\n 'path': '/child_one',\n 'children': {\n 'sub_child': {\n 'path': '/test'\n }\n }\n },\n 'child_two': {\n 'path': '/child_two'\n }\n }\n }\n })\n assert len(router) == 5\n\n request = create_request_from_environ(sample_environ(PATH_INFO='/child_one'))\n matches = router.matches(request)\n assert len(matches) == 0\n\n request = create_request_from_environ(sample_environ(PATH_INFO='/parent/child_one'))\n matches = router.matches(request)\n assert len(matches) == 1\n\n assert router.assemble('parent/child_one/sub_child') == '/parent/child_one/test'\n","sub_path":"tests/watson/framework/test_routing.py","file_name":"test_routing.py","file_ext":"py","file_size_in_byte":9716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"139248629","text":"'''\nCreated on March 3, 2017\n\nThis file is subject to the terms and conditions defined in the\nfile 'LICENSE.txt', which is part of this source code package.\n\n@author: David Moss\n'''\n\nfrom devices.siren.siren import SirenDevice\n\n\n# For the LinkHigh siren, send all 3 parameters simultaneously:\n# ppc.alarmWarn = sound id to play\n# ppc.alarmDuration = 1 is play once, 2+ is play for that many seconds\n# ppc.alarmStrobe = 0 or 1 to turn the strobe light off or on.\n\n\nclass LinkhighSirenDevice(SirenDevice):\n \"\"\"Siren\"\"\"\n\n # List of Device Types this class is compatible with\n DEVICE_TYPES = [9009]\n\n # Sound library\n SOUNDS = {\n \"silence\": 0,\n \"alarm\": 1,\n \"dog\": 2,\n \"warning\": 3,\n \"bling\": 4,\n \"bird\": 5,\n \"droid\": 6,\n \"lock\": 7,\n \"phaser\": 8,\n \"doorbell\": 9,\n \"guncock\": 10,\n \"gunshot\": 11,\n \"switch\": 12,\n \"trumpet\": 13,\n \"whistle\": 14\n }\n\n def __init__(self, botengine, device_id, device_type, device_description, precache_measurements=True):\n \"\"\"\n Constructor\n :param botengine:\n :param device_id:\n :param device_type:\n :param device_description:\n :param precache_measurements:\n \"\"\"\n SirenDevice.__init__(self, botengine, device_id, device_type, device_description, precache_measurements=precache_measurements)\n\n # Last sound played\n self.last_sound = None\n\n # Microservice this siren is locked to\n self.locked_microservice = None\n\n def initialize(self, botengine):\n \"\"\"\n Initialize\n :param botengine:\n :return:\n \"\"\"\n # Added June 18, 2019\n if not hasattr(self, 'locked_microservice'):\n self.locked_microservice = None\n\n def get_device_type_name(self):\n \"\"\"\n :return: the name of this device type in the given language, for example, \"Entry Sensor\"\n \"\"\"\n # NOTE: Device type name\n return _(\"Siren\")\n\n def get_image_name(self):\n \"\"\"\n :return: the font icon name of this device type\n \"\"\"\n return \"siren\"\n\n #===========================================================================\n # Commands\n #===========================================================================\n def squawk(self, botengine, warning=False, microservice_identifier=\"\"):\n \"\"\"\n Squawk\n :param warning: True for a little warning squawk, False for a more alarming squawk\n \"\"\"\n if self.locked_microservice is not None:\n if self.locked_microservice != microservice_identifier:\n botengine.get_logger().info(\"Siren: Currently locked by {}, cannot play sound from microservice {}\".format(self.locked_microservice, microservice_identifier))\n return\n\n style = self.SOUNDS['warning']\n self.play_sound(botengine, style, False, 1, microservice_identifier=microservice_identifier)\n\n def alarm(self, botengine, on, microservice_identifier=\"\"):\n \"\"\"\n Sound the alarm\n :param on: True for on, False for off\n \"\"\"\n if self.locked_microservice is not None:\n if self.locked_microservice != microservice_identifier:\n botengine.get_logger().info(\"Siren: Currently locked by {}, cannot play sound from microservice {}\".format(self.locked_microservice, microservice_identifier))\n return\n\n if on:\n self.last_sound = self.SOUNDS['alarm']\n self.play_sound(botengine, self.SOUNDS['alarm'], True, 900, microservice_identifier=microservice_identifier)\n\n else:\n self.play_sound(botengine, self.SOUNDS['alarm'], False, 0, microservice_identifier=microservice_identifier)\n\n def play_sound(self, botengine, sound_id, strobe, duration_sec, microservice_identifier=\"\"):\n \"\"\"\n Squawk the given sound ID\n :param botengine: BotEngine\n :param sound_id: Sound ID to play\n :param strobe: True to activate the strobe light\n :param duration_sec: 1 = play once; 2+ = play this many seconds.\n \"\"\"\n if self.locked_microservice is not None:\n if self.locked_microservice != microservice_identifier:\n botengine.get_logger().info(\"Siren: Currently locked by {}, cannot play sound from microservice {}\".format(self.locked_microservice, microservice_identifier))\n return\n\n param_sound = {\n \"name\": \"ppc.alarmWarn\",\n \"value\": int(sound_id)\n }\n\n param_strobe = {\n \"name\": \"ppc.alarmStrobe\",\n \"value\": int(strobe)\n }\n\n param_duration = {\n \"name\": \"ppc.alarmDuration\",\n \"value\": int(duration_sec)\n }\n\n botengine.send_commands(self.device_id, [param_sound, param_strobe, param_duration], command_timeout_ms=5000)\n\n def doorbell(self, botengine):\n \"\"\"\n Make a doorbell sound.\n :param botengine:\n :return:\n \"\"\"\n if self.locked_microservice is None:\n self.play_sound(botengine, self.SOUNDS['doorbell'], True, 1)\n\n def lock(self, botengine, microservice_identifier):\n \"\"\"\n Lock the siren to some microservice - for example to use the siren exclusively for security purposes.\n :param botengine:\n :param microservice_identifier:\n :return:\n \"\"\"\n if self.locked_microservice is None:\n botengine.get_logger().info(\"Siren: LOCKING SIREN TO MICROSERVICE {}\".format(microservice_identifier))\n self.locked_microservice = microservice_identifier\n else:\n botengine.get_logger().info(\"Siren: Cannot lock siren again - siren is currently locked by {}\".format(self.locked_microservice))\n\n def unlock(self, botengine):\n \"\"\"\n Unlock the siren\n :param botengine:\n :param microservice_identifier:\n :return:\n \"\"\"\n self.locked_microservice = None\n","sub_path":"com.ppc.Bot/devices/siren/siren_linkhigh.py","file_name":"siren_linkhigh.py","file_ext":"py","file_size_in_byte":6097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"339041785","text":"\n# the purpose of this program is to confirm that two\n# mass spec .csv files contain the same number of points\n\nimport csv\nimport sys\n\n# opens first file and counts points\nwith open(sys.argv[1]) as file_1:\n reader = csv.reader(file_1)\n\n # offset for header\n file_1_points = -1\n for x in reader:\n file_1_points += 1\n\n# opens second file and counts points\nwith open(sys.argv[2]) as file_2:\n reader = csv.reader(file_2)\n\n # off set by one for header\n file_2_points = -1\n for x in reader:\n file_2_points += 1\n\n# checks number of points in both file matches\nif file_1_points == file_2_points:\n print(\"Success! Both files have the same number of points\")\nelse:\n print(\"Bummer bro....\\nThe files contain a different number of points\")\n","sub_path":"Python/80-20_reduction/point_counter.py","file_name":"point_counter.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"417390977","text":"from pathlib import Path\nimport os\nimport urllib.request\nfrom bottle import route, run\n\n\nUPSTREAM_URL = os.environ.get('UPSTREAM_URL', 'http://127.0.0.1:8080/metrics')\nPORT = int(os.environ.get('METRICS_PORT', \"8082\"))\nMETRICS_DIR = os.environ.get('METRICS_DIR', \"/extra_metrics\")\n\n\n@route('/metrics')\ndef metrics():\n with urllib.request.urlopen(UPSTREAM_URL) as req:\n contents = req.read().decode('utf-8')\n\n for file in Path(METRICS_DIR).glob('*.prom'):\n if not contents.endswith('\\n'):\n contents += '\\n'\n contents += file.read_text()\n\n return contents\n\n\nif __name__ == \"__main__\":\n run(host='0.0.0.0', port=PORT)","sub_path":"metrics/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"375623253","text":"import json\n\nfrom fastapi import APIRouter, Depends, HTTPException\nfrom starlette.responses import Response\n\nfrom ...algorithm import DbDtAlgorithm\nfrom ...residual import (\n calculate,\n Reading,\n)\nfrom .DataApiQuery import DataApiQuery\nfrom .data import format_timeseries, get_data_factory, get_data_query, get_timeseries\n\n\nrouter = APIRouter()\n\n\n@router.get(\n \"/algorithms/dbdt/\",\n description=\"First order derivative at requested interval\",\n name=\"Dbdt Algorithm\",\n)\ndef get_dbdt(\n query: DataApiQuery = Depends(get_data_query),\n) -> Response:\n dbdt = DbDtAlgorithm(period=query.sampling_period)\n data_factory = get_data_factory(query=query)\n # read data\n raw = get_timeseries(data_factory, query)\n # run dbdt\n timeseries = dbdt.process(raw)\n elements = [f\"{element}_DT\" for element in query.elements]\n # output response\n return format_timeseries(\n timeseries=timeseries, format=query.format, elements=elements\n )\n\n\n@router.post(\n \"/algorithms/residual\",\n description=\"Caclulates new absolutes and baselines from reading\\n\\n\"\n + \"Returns posted reading object with updated values\",\n response_model=Reading,\n)\ndef calculate_residual(reading: Reading, adjust_reference: bool = True):\n try:\n calculated = calculate(\n reading=reading, adjust_reference=adjust_reference\n ).json()\n return json.loads(calculated.replace(\"NaN\", \"null\"))\n except ValueError as e:\n raise HTTPException(status_code=400, detail=str(e))\n","sub_path":"geomagio/api/ws/algorithms.py","file_name":"algorithms.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"222134171","text":"# Potential improvements: stack rank relationships, take best one found (gf over so for example)\n# spell check/simplifier (huband -> husband for example, daughter's -> daughter)\n# delete \"mid\" from within captured parens\n# compound words get dashed. \"sister in law\" -> \"sister-in-law\"\n\nimport re\nfrom test_set import test_set\nfrom training_set import training_set\nfrom relationship_words import self_words, relation_words, male_relation_words, female_relation_words\n\ndef get_diff(correct, generated):\n if (correct[\"poster\"] == generated[\"poster\"] \n and correct[\"counterpart\"] == generated[\"counterpart\"]):\n return 1\n else:\n print (\"--------------------\")\n print (correct[\"title\"])\n if (correct[\"poster\"][\"gender\"] != generated[\"poster\"][\"gender\"]):\n print (\"Poster gender mismatch. \" + correct[\"poster\"][\"gender\"] + \"|\" + generated[\"poster\"][\"gender\"])\n if (correct[\"poster\"][\"age\"] != generated[\"poster\"][\"age\"]):\n print (\"Poster age mismatch. \" + correct[\"poster\"][\"age\"] + \"|\" + generated[\"poster\"][\"age\"])\n if (correct[\"counterpart\"][\"gender\"] != generated[\"counterpart\"][\"gender\"]):\n print (\"Counterpart gender mismatch. \" + correct[\"counterpart\"][\"gender\"] + \"|\" + generated[\"counterpart\"][\"gender\"])\n if (correct[\"counterpart\"][\"age\"] != generated[\"counterpart\"][\"age\"]):\n print (\"Counterpart age mismatch. \" + correct[\"counterpart\"][\"age\"] + \"|\" + generated[\"counterpart\"][\"age\"])\n if (correct[\"counterpart\"][\"relationship\"] != generated[\"counterpart\"][\"relationship\"]):\n print (\"Counterpart relationship mismatch. \" + correct[\"counterpart\"][\"relationship\"] + \"|\" + generated[\"counterpart\"][\"relationship\"])\n return 0\n\ndef create_poster_object(data):\n poster = {\"age\":\"\", \"gender\":\"\"}\n\n age = re.findall(r'\\d+', data[1])\n if (age and len(age) > 0):\n poster[\"age\"] = age[0]\n\n gender = re.findall('M|F', data[1].upper())\n if (gender):\n poster[\"gender\"] = gender[0]\n\n return poster\n\ndef create_counterpart_object(person, title):\n counterpart = {\"age\":\"\", \"gender\":\"\", \"relationship\":\"\"}\n if (person[0].lower() in relation_words):\n counterpart[\"relationship\"] = person[0].lower()\n\n age = re.findall(r'\\d+', person[1])\n if (age and len(age) > 0):\n counterpart[\"age\"] = age[0]\n\n gender = re.findall('M|F', person[1].upper())\n if (gender):\n counterpart[\"gender\"] = gender[0]\n\n if not counterpart[\"relationship\"]:\n for word in title.split(\" \"):\n if word in relation_words:\n counterpart[\"relationship\"] = word\n break\n\n if counterpart[\"relationship\"] in female_relation_words:\n counterpart[\"gender\"] = \"F\"\n if counterpart[\"relationship\"] in male_relation_words:\n counterpart[\"gender\"] = \"M\"\n\n return counterpart \n\ndef extract_relations(people, title):\n if (people[0][0].lower() in relation_words or people[1][0].lower() in self_words):\n poster = create_poster_object(people[1])\n counterpart = create_counterpart_object(people[0], title)\n else:\n poster = create_poster_object(people[0])\n counterpart = create_counterpart_object(people[1], title)\n \n return {\"poster\": poster, \"counterpart\": counterpart}\n \ndef extract(title):\n people = re.findall(\"(\\w+)\\s?(\\[|\\()(.*?)(\\]|\\))\", title)\n if (len(people) == 2):\n for counter, match in enumerate(people):\n people[counter] = match[0:4:2]\n relationships = extract_relations(people, title)\n relationships[\"title\"] = title\n return relationships\n return \"\"\n\n\ndef extract_list(list):\n total = 0\n total_correct = 0\n for tagged_obj in list:\n relationships = extract(tagged_obj[\"title\"])\n if (relationships != \"\"):\n total += 1\n total_correct += get_diff(tagged_obj, relationships)\n\n print (str(total_correct) + \" out of a possible \" + str(total))\n\n#single = [{\"title\":\"I [18 M] have been dating my gf [18 F] for a month, and I want to build our personal relationship more, rather than our physical relationship\", \"poster\":{\"age\":\"18\", \"gender\":\"M\"}, \"counterpart\":{\"age\":\"18\", \"gender\":\"F\", \"relationship\":\"gf\"}}]\n \n#extract_list(test_set)\n","sub_path":"title_extraction.py","file_name":"title_extraction.py","file_ext":"py","file_size_in_byte":4080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"605056523","text":"import urllib.request\nimport json\nimport sys\nimport dateutil.parser\n\n# The URL for the MUX camera\nbaseURL = 'https://cbers-stac-0-6.s3.amazonaws.com/CBERS4/MUX/'\n# The path to save photos to\nimg_path = \"input/images/\"\n# The path to save metadata to\nmetadata_path = \"input/metadata/\"\n\n# A search bounding box for testing purposes\nbbox = [\n\t53,\n\t4,\n\t54,\n\t5\n]\n\n# A bounding time interval for testing purposes\n# initially blank; is filled in the starter code\nbtime = [\n dateutil.parser.parse(\"2017-02-20T00:00:00Z\"),\n\tdateutil.parser.parse(\"2017-12-30T00:00:00Z\")\n]\n\n# Downloads a jpg and stores it in the desired folder\ndef download_jpg(url, file_path, file_name):\n\tfull_path = file_path + file_name + '.jpg'\n\turllib.request.urlretrieve(url, full_path)\n\n# Trawl that catalog!\ndef main():\n\n\t# Counter and limiter used to only grab that many Items\n\ttest_limiter = 3\n\tgrab_count = 0\n\n\t# Get the MUX catalog object as a Python dictionary\n\tmux_json_obj = json.loads(urllib.request.urlopen(baseURL + 'catalog.json').read())\n\n\tfor path_link in mux_json_obj[\"links\"]:\n\t\tif path_link['rel'] == 'child':\n\n\t\t\t# Get each path's catalog object as a Python dictionary\n\t\t\tpath_json_obj = json.loads(urllib.request.urlopen(baseURL + path_link['href']).read())\n\n\t\t\tfor row_link in path_json_obj[\"links\"]:\n\t\t\t\tif row_link['rel'] == 'child':\n\n\t\t\t\t\t# Get each row's catalog object as a Python dictionary\n\t\t\t\t\t# note that the URL has the path's three digits and '/' added in\n\t\t\t\t\trow_json_obj = json.loads(urllib.request.urlopen(baseURL + path_link['href'][:4] + row_link['href']).read())\n\n\t\t\t\t\t# Finally, we loop through the actual items\n\t\t\t\t\tfor item_link in row_json_obj[\"links\"]:\n\t\t\t\t\t\tif item_link['rel'] == 'item':\n\n\t\t\t\t\t\t\t# Get each item as a Python dictionary\n\t\t\t\t\t\t\titem_obj = json.loads(urllib.request.urlopen(baseURL + path_link['href'][:4] + row_link['href'][:4] + item_link['href']).read())\n\n\t\t\t\t\t\t\t# Save the Item's timestamp for later. If it's out of the search range,\n\t\t\t\t\t\t\t# move on to the next Item\n\t\t\t\t\t\t\t# If no time zone information is included, don't take it\n\t\t\t\t\t\t\t# This is necessary in order to avoid causing errors\n\t\t\t\t\t\t\t# which would occur when you compare datetimes and only one of\n\t\t\t\t\t\t\t# the datetimes has a time zone\n\t\t\t\t\t\t\titem_time = dateutil.parser.parse(item_obj[\"properties\"][\"datetime\"])\n\t\t\t\t\t\t\tif not item_time.tzinfo:\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\tif not (item_time > btime[0] and item_time < btime[1]):\n\t\t\t\t\t\t\t\tcontinue\n\n\t\t\t\t\t\t\t# Weird for conditions because the actual coordinates are buried a few layers deep.\n\t\t\t\t\t\t\t# coordinates and layer1 each had only a single thing inside (on the ones I looked at):\n\t\t\t\t\t\t\t# the next-level-down list (layer1 and layer2, respectively)\n\t\t\t\t\t\t\tfor layer1 in item_obj['geometry']['coordinates']:\n\t\t\t\t\t\t\t\tfor layer2 in layer1:\n\t\t\t\t\t\t\t\t\t# if any corner of the Item's polygon is inside our search bbox\n\t\t\t\t\t\t\t\t\t# AND the Item is within the desired timeframe, we want it!\n\t\t\t\t\t\t\t\t\tfor coordinate in layer2:\n\t\t\t\t\t\t\t\t\t\tif (coordinate[0] > bbox[0] and coordinate[0] < bbox[2] and coordinate[1] > bbox[1] and coordinate[1] < bbox[3]):\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t# download the Item's thumbnail\n\t\t\t\t\t\t\t\t\t\t\tdownload_jpg(item_obj['assets']['thumbnail']['href'], img_path, item_obj['id'])\n\n\t\t\t\t\t\t\t\t\t\t\t# save its metadata in a JSON file\n\t\t\t\t\t\t\t\t\t\t\t# make the json thing as a dict\n\t\t\t\t\t\t\t\t\t\t\t# the image shares its name with the JSON file\n\t\t\t\t\t\t\t\t\t\t\t# so there is no need for an image link/name entry here\n\t\t\t\t\t\t\t\t\t\t\tmetadata_dict = {\n\t\t\t\t\t\t\t\t\t\t\t\t\"coordinates\": item_obj['geometry']['coordinates'],\n\t\t\t\t\t\t\t\t\t\t\t\t\"timestamp\": str(item_time)\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\twith open(metadata_path + item_obj['id'] + '.json', 'w') as outfile:\n\t\t\t\t\t\t\t\t\t\t\t\tjson.dump(metadata_dict, outfile)\n\n\t\t\t\t\t\t\t\t\t\t\tgrab_count = grab_count + 1\n\n\t\t\t\t\t\t\t\t\t\t\t# stop if you've grabbed enough things\n\t\t\t\t\t\t\t\t\t\t\tif (grab_count == test_limiter):\n\t\t\t\t\t\t\t\t\t\t\t\tprint(\"Done: downloaded \" + str(grab_count) + \" Items\")\n\t\t\t\t\t\t\t\t\t\t\t\tsys.exit()\n\t\t\t\t\t\t\t\t\t\t\t\t# once you've done that based on the one coordinate being in the bbox, you've grabbed the Item and don't want to grab it again, so break\n\t\t\t\t\t\t\t\t\t\t\tbreak\n\nif __name__ == \"__main__\":\n\n\tmain()\n","sub_path":"stac_demo.py","file_name":"stac_demo.py","file_ext":"py","file_size_in_byte":4146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"206091380","text":"from flask import render_template, Flask, request\nfrom flask import send_from_directory,url_for\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport io\nimport base64\nimport json\nimport pickle\napp = Flask(__name__) \n\ndef build_graph(x_coordinates, y_coordinates):\n \n img = io.BytesIO()\n plt.plot(x_coordinates, y_coordinates)\n plt.savefig(img, format='png')\n img.seek(0)\n graph_url = base64.b64encode(img.getvalue()).decode()\n plt.close()\n return 'data:image/png;base64,{}'.format(graph_url)\n\ndef make_dict(filename):\n \n path = \"Session2/dialog/transcriptions/%s.txt\"%filename[0:14]\n d = open(path)\n text = d.readlines()\n li_ = []\n for i in text:\n li_.append((i.split(\" \")[0], i[41:]))\n path_ = \"Session2/dialog/EmoEvaluation/Categorical/%s_e2_cat.txt\"%filename[0:14]\n d_ = open(path_)\n text_ = d_.readlines()\n dic = {}\n for i in text_:\n dic[i.split(\":\")[0].strip()] = i.split(\":\")[1].split(\";\")[0]\n return (dic,li_)\n\ndef create_li(dic, li_):\n \n g = \" \"\n y_f = []\n y_m = []\n sess = []\n speaker_li = []\n emo_li = []\n text_li = []\n first = True\n for i in li_ :\n while first == True:\n first = False\n break\n sub_d = {}\n try:\n if i[0][15] == \"F\":\n g = \"Female\"\n y_f.append(dic[i[0]])\n elif i[0][15] == \"M\":\n g = \"Male\"\n y_m.append(dic[i[0]])\n sub_d[\"Speaker\"] = g\n speaker_li.append(g)\n sub_d[\"Emo\"] = dic[i[0]]\n emo_li.append(dic[i[0]])\n sub_d[\"Text\"] = i[1]\n text_li.append(i[1])\n sess.append(sub_d)\n \n del(sub_d)\n except Exception as e:\n print(e)\n pass\n np.save(\"f_1.npy\",y_f)\n np.save(\"m_1.npy\",y_m)\n return(speaker_li,emo_li,text_li)\n \ndef load_obj(name ):\n \n with open('obj/' + name + '.pkl', 'rb') as f:\n return pickle.load(f)\ndef save_obj(obj, name ):\n \n with open('obj/'+ name + '.pkl', 'wb') as f:\n pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)\n \n@app.route('/') \ndef upload(): \n \n return render_template(\"file.html\") \n \n@app.route('/success', methods = ['POST']) \ndef success(): \n \n if request.method == 'POST': \n f = request.files['file']\n f.save(\"C:\\\\Users\\\\AkhileshPatil\\\\Desktop\\\\AudioEmo\\\\Flask_V1\\\\static\\\\mp3\\\\\"+f.filename)\n sess_dic = make_dict(f.filename)\n li = create_li(sess_dic[0], sess_dic[1])\n return render_template(\"success.html\", name = f.filename, emo = li[1], speaker = li[0], text = li[2]) \n \n@app.route('/foo', methods=['GET', 'POST'])\ndef foo(x=None, y=None):\n \n y1 = np.load(\"m_1.npy\")\n y2 = np.load(\"f_1.npy\")\n x1 = []\n x2 = []\n for i in range(len(y1)):\n x1.append(i)\n for j in range(len(y2)):\n x2.append(j)\n graph1_url = build_graph(x1,y1);\n graph2_url = build_graph(x2,y2);\n return render_template(\"stop.html\",graph1=graph1_url,graph2=graph2_url)\n\nif __name__ == \"__main__\":\n app.run(debug=True,use_reloader = False)","sub_path":"flaskapp.py","file_name":"flaskapp.py","file_ext":"py","file_size_in_byte":3168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"270506349","text":"# -*- coding: utf-8 -*-\nfrom base_task import Task\nfrom datetime import date\nfrom dateutil.relativedelta import relativedelta\nimport json\nfrom lib.ah_requests import AhRequest\nimport helper_functions as helper\nfrom lib.mongodb import Mongo\nfrom logger import Logger\nimport helper_functions as helpers\n\nLOG = Logger()\n\n\n\"\"\"Task...\"\"\"\nclass InterestRate(Task):\n def __init__(self, remote_url=None, **args):\n Task.__init__(self,name=self.__class__.__name__, remote_url=remote_url, args=args)\n self.loading_msg = 'Fetching country interest rates' \n self._requires = ['ProjectData']\n self.conn = Mongo()\n self.mdb = self.conn.db\n\n \n \n def run(self):\n self.start()\n try:\n obj = []\n project_data = self.input['ProjectData']\n transactions = project_data['transactions']\n for t in transactions:\n country_from = self.mdb.countries.find_one({'country_code':t['country_from']}, {'_id': False})\n country_to = self.mdb.countries.find_one({'country_code':t['country_to']}, {'_id': False})\n source_country = country_from['country']\n target_country = country_to['country']\n req = AhRequest()\n url = self.remote_url+'interest'\n\n data = self.mdb.interest.find_one( {'date':{'$gt':helpers.today(-7)}, 'country_code':country_from['country_code'] },{'_id': False})\n if data:\n LOG.console(\"We found data in db that is not older than a week (-7)\")\n LOG.console('Using interest data from DB:{}'.format(str(data)))\n interest_source = data\n else:\n data = json.dumps( dict(country=source_country) )\n interest_source = req.post(url,data={'payload':data}, timeout=15)\n interest_source.update(country_code=country_from['country_code']) \n\n data = self.mdb.interest.find_one( {'date':{'$gt':helpers.today(-7)}, 'country_code':country_to['country_code'] },{'_id': False}) \n if data:\n LOG.console(\"We found data in db that is not older than a week (-7)\")\n LOG.console('Using interest data from DB:{}'.format(str(data)))\n interest_target = data\n else:\n data = json.dumps( dict(country=target_country) )\n interest_target = req.post(url,data={'payload':data}, timeout=15)\n interest_target.update(country_code=country_to['country_code']) \n\n pct_diff = max(interest_source['rate'],interest_target['rate']) - min(interest_source['rate'],interest_target['rate'])\n abs_diff = pct_diff/100 * transactions[0]['total_budget']\n \n obj.append(dict(source=interest_source, target=interest_target, pct_diff=pct_diff, abs_diff=abs_diff))\n\n self.output = obj\n except Exception as e:\n self.status = 'Failed'\n self.exception = e\n pass\n self.stop()\n \n def __repr__(self):\n return str(self.name)\n","sub_path":"workers/tasks/task__interest_rates.py","file_name":"task__interest_rates.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"564118304","text":"# Napisz grę kamień-papier-nożyce tak, aby korzystać z funkcji.\n\nfrom random import randint\n\nelements = ['p', 'k', 'n', 'l', 's', 'q']\nnames = ['paper', 'stone', 'scissors', 'lizard', 'spock']\n\n\ndef gamer_turn(gamer):\n print('you:', gamer)\n\n\ndef comp_turn(comp):\n if comp == 1:\n comp = 'p'\n elif comp == 2:\n comp = 'k'\n elif comp == 3:\n comp = 'n'\n elif comp == 4:\n comp = 'l'\n else:\n comp = 's'\n print('vs:', comp)\n return comp\n\n\ndef results(gamer, comp, result):\n # gamer_wins =\n if (gamer == 'k' and comp == 'n') or (gamer == 'p' and comp == 'k') or (gamer == 'n' and comp == 'p') \\\n or (gamer == 'k' and comp == 's') or (gamer == 'p' and comp == 'l') or (gamer == 'n' and comp == 's')\\\n or (gamer == 's' and comp == 'l') or (gamer == 's' and comp == 'p') or (gamer == 'l' and comp == 'n')\\\n or (gamer == 'l' and comp == 'k'):\n result = 3\n # comp_wins =\n elif (gamer == 'n' and comp == 'k') or (gamer == 'k' and comp == 'p') or (gamer == 'p' and comp == 'n') \\\n or (gamer == 's' and comp == 'k') or (gamer == 'l' and comp == 'p') or (gamer == 's' and comp == 'n')\\\n or (gamer == 'l' and comp == 's') or (gamer == 'p' and comp == 's') or (gamer == 'n' and comp == 'l')\\\n or (gamer == 'k' and comp == 'l'):\n result = 2\n # draw =\n elif gamer == comp:\n result = 1\n # error =\n elif gamer != elements:\n result = 0\n return result\n\n\ndef round1(result, summary):\n if result == 3: # gamer_wins:\n summary += 1\n print('You win the round!')\n elif result == 2: # comp_wins:\n summary -= 1\n print('Computer wins the round!')\n elif result == 1: # draw:\n print('Draw')\n elif result == 0: # error:\n print(\"Something went wrong..\")\n return summary\n\n\ndef summary_result(summary):\n print('----------------------------------------------------')\n if summary > 0:\n print(f'Game result: {summary} - You win !')\n elif summary < 0:\n print(f'Game result: {summary} - Computer wins !')\n else:\n print(f'Game result: {summary} - Draw ')\n print('++++++++++++++++++++++++++++++++++++++++++++++++++++\\n')\n\n\ndef game(level, try_no):\n summary = 0\n for i in range(try_no):\n text = ''\n for j in range(level):\n text += names[j] + ' (' + elements[j] + ') '\n gamer = input(text)\n gamer = gamer.lower()\n\n if gamer == 'q':\n break\n gamer_turn(gamer)\n comp = comp_turn(randint(1, level))\n\n result = 0\n result = results(gamer, comp, result)\n summary = round1(result, summary)\n summary_result(summary)\n\n\ndef main():\n try_no = int(input(\"Give the number of rounds in the game: \"))\n print('S - Start')\n print('P - Difficulty level')\n print('Q - Quit')\n level = input('high (h), low (l) : ').lower()\n while level != 'l' and level != 'h':\n level = input('high (h), low (l) : ').lower()\n if level == 'l':\n game(3, try_no)\n elif level == 'h':\n game(5, try_no)\n\n# rozpocznij program\n\n\nmain()\n","sub_path":"05_methods_exercises/new_ro_sham_bo.py","file_name":"new_ro_sham_bo.py","file_ext":"py","file_size_in_byte":3178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"296317430","text":"from sqlalchemy import create_engine\r\nfrom sqlalchemy import Table, Column, Integer, String, MetaData\r\nfrom sqlalchemy.orm import sessionmaker\r\nfrom sqlalchemy.sql import select, update, delete\r\nimport collections\r\n\r\n__VERSION__ = 0.6\r\n\r\n\r\nclass Phial:\r\n database_name = ''\r\n base = {}\r\n tables = {}\r\n\r\n def __init__(self, database_name, set_of_tables):\r\n self.database_name = database_name\r\n self.metadata = MetaData()\r\n\r\n for table in set_of_tables:\r\n self.tables[table.table_name] = Table(table.table_name,\r\n self.metadata,\r\n Column('id', Integer, primary_key=True))\r\n for column in table.columns:\r\n self.tables[table.table_name].append_column(Column(\r\n column.column_name,\r\n column.type,\r\n **column.options))\r\n\r\n self.engine = create_engine('sqlite:///%s' % (self.database_name), echo=False)\r\n self.metadata.create_all(self.engine)\r\n session = sessionmaker(bind=self.engine)\r\n self.session = session()\r\n self.session.commit()\r\n self.connection = self.engine.connect()\r\n\r\n def write(self, table_name, dic={}):\r\n \"\"\"\r\n Method adds a new row with values from :param dic. If dictionary is empty, method adds a new empty row\r\n with next ID.\r\n :param table_name: str\r\n :param dic: {column_name: value}\r\n :return:\r\n \"\"\"\r\n self.session.execute(self.tables[table_name].insert(dic))\r\n self.session.commit()\r\n\r\n def update(self, table_name, dic):\r\n \"\"\"\r\n Метод обновляет запись в базе, внося в соответствующие поля значения из словаря dic. При этом словарь в любом\r\n случае должен содержать ключ id с валидным значением. Возможно, есть смысл добавить проверку валидности\r\n значения ключа, передаваемого в словаре.\r\n :param table_name: str\r\n :param dic: {column_name: value}\r\n :return:\r\n \"\"\"\r\n u = update(self.tables[table_name]).where(self.tables[table_name].c.id == dic['id'])\r\n u = u.values(dic)\r\n self.connection.execute(u)\r\n\r\n def read(self, table_name, id, column=0):\r\n \"\"\"\r\n Метод возвращает словарь или строку в зависимости от входящих параметров. Если параметр column не задан,\r\n ввозвращается словарь, содержащий всю строку, соответствующую парметру id.\r\n :param table_name:\r\n :param id:\r\n :param column:\r\n :return:\r\n \"\"\"\r\n selection = select([self.tables[table_name]]).where(self.tables[table_name].c.id == id)\r\n result_proxy = self.connection.execute(selection)\r\n record = result_proxy.first()\r\n if column:\r\n return record[column]\r\n else:\r\n return {a[0]: a[1] for a in record.items()}\r\n\r\n def delete(self, table_name, id):\r\n \"\"\"\r\n Метод удаляет запись с id, равным заданному параметру. Вообще, есть мнение, что физическое удаление записи есть\r\n не слишком хорошая практика. Было бы недурно ввести дополнительную колонку в базу для фильтрации валидных и\r\n \"удаленных\" записей.\r\n :param id:\r\n :return:\r\n \"\"\"\r\n request = delete(self.tables[table_name]).where(self.tables[table_name].c.id == id)\r\n self.connection.execute(request)\r\n\r\n def count(self, table_name):\r\n \"\"\"\r\n Метод возвращает количество записей в БД.\r\n :return: integer\r\n \"\"\"\r\n return self.session.query(self.tables[table_name]).count()\r\n\r\n def annotation(self, table_name, schema):\r\n \"\"\"\r\n\r\n :param schema:\r\n :return:\r\n \"\"\"\r\n selection = select([self.tables[table_name]])\r\n result_proxy = self.connection.execute(selection)\r\n\r\n for row in result_proxy:\r\n dic = {a[0]: a[1] for a in row.items()}\r\n anno = schema\r\n for unit in dic:\r\n anno = anno.replace(unit, str(dic[unit]))\r\n yield anno\r\n\r\ncolumn = collections.namedtuple('column', ['column_name', 'type', 'options'])\r\ntable = collections.namedtuple('table', ['table_name', 'columns'])\r\n\r\ndef columns(names_list):\r\n final_list = []\r\n for col in names_list:\r\n final_list.append(column(col, String, {}))\r\n return final_list\r\n","sub_path":"phial.py","file_name":"phial.py","file_ext":"py","file_size_in_byte":4980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"237557673","text":"from django.contrib.auth.models import AnonymousUser\nfrom django.utils.crypto import get_random_string\n\nimport pytest\nfrom cms import api\nfrom cms.page_rendering import render_page\nfrom form_designer.contrib.cms_plugins.form_designer_form.cms_plugins import FormDesignerPlugin\nfrom form_designer.models import FormDefinition, FormDefinitionField\n\n\n@pytest.mark.django_db\ndef test_cms_plugin_renders_in_cms_page(rf):\n fd = FormDefinition.objects.create(\n mail_to='test@example.com',\n mail_subject='Someone sent you a greeting: {{ test }}'\n )\n field = FormDefinitionField.objects.create(\n form_definition=fd,\n name='test',\n label=get_random_string(),\n field_class='django.forms.CharField',\n )\n page = api.create_page(\"test\", \"page.html\", \"en\")\n ph = page.get_placeholders()[0]\n api.add_plugin(ph, FormDesignerPlugin, \"en\", form_definition=fd)\n request = rf.get(\"/\")\n request.user = AnonymousUser()\n request.current_page = page\n response = render_page(request, page, \"fi\", \"test\")\n response.render()\n content = response.content.decode(\"utf8\")\n assert field.label in content\n assert \" 0\n assert nt_chunk > 0\n assert var_weight > 0\n assert var_clamp_add >= 0\n assert var_clamp_mult >= 0\n assert w_clamp > 0\n assert w_cutoff > 0\n assert nt_chunk % v1_chunk == 0\n\n\n def set_stream(self, s):\n # As explained in the rf_pipelines.py_wi_transform docstring, this function is\n # called once per pipeline run, when the stream (the 's' argument) has been specified.\n self.nfreq = s.nfreq\n\n\n def start_substream(self, isubstream, t0):\n # Called once per substream (a stream can be split into multiple substreams).\n self.running_var = np.zeros((self.nfreq)) # holds the current variance estimate for each frequency\n self.v1_tmp = np.zeros((self.nfreq)) # holds the temporary v1 estimates while they are being updated\n self.running_weights = np.zeros((self.nfreq))\n\n def process_chunk(self, t0, t1, intensity, weights, pp_intensity, pp_weights):\n # Loop over intensity/weights in chunks of size v1_chunk\n for ichunk in xrange(0, self.nt_chunk, self.v1_chunk):\n for frequency in xrange(self.nfreq):\n # Calculate the v1 for each frequency\n self.v1_tmp[frequency] = self._v1(intensity[frequency, ichunk:ichunk+self.v1_chunk], weights[frequency, ichunk:ichunk+self.v1_chunk])\n\n # Once v1s have been calculated for each frequency, update the weights and running variance\n non_zero_v1 = self.v1_tmp != 0\n zero_v1 = np.logical_not(non_zero_v1)\n\n # For nonzero (successful) v1s, increase the weights (if possible) and update the running variance\n self.running_weights[non_zero_v1] = np.minimum(2.0, self.running_weights[non_zero_v1] + self.w_clamp)\n self.v1_tmp[non_zero_v1] = np.minimum((1-self.var_weight) * self.running_var[non_zero_v1] + self.var_weight * self.v1_tmp[non_zero_v1], \n self.running_var[non_zero_v1] + self.var_clamp_add + self.running_var[non_zero_v1] * self.var_clamp_mult)\n self.v1_tmp[non_zero_v1] = np.maximum(self.v1_tmp[non_zero_v1], self.running_var[non_zero_v1] - self.var_clamp_add - self.running_var[non_zero_v1] * self.var_clamp_mult)\n self.running_var[non_zero_v1] = self.v1_tmp[non_zero_v1]\n\n # For unsuccessful v1s, decrease the weights (if possible) and do not modify the running variance \n self.running_weights[zero_v1] = np.maximum(0, self.running_weights[zero_v1] - self.w_clamp)\n \n # Mask fill!\n intensity_valid = (weights[:, ichunk:ichunk+self.v1_chunk] > self.w_cutoff)\n rand_intensity = np.random.standard_normal(size=intensity[:, ichunk:ichunk+self.v1_chunk].shape)\n for (ifreq,v) in enumerate(self.running_var):\n if v > 0.0:\n rand_intensity[ifreq, :] *= v**0.5\n intensity[:, ichunk:ichunk+self.v1_chunk] = np.where(intensity_valid, intensity[:, ichunk:ichunk+self.v1_chunk], rand_intensity)\n weights[:, ichunk:ichunk+self.v1_chunk] = np.repeat(self.running_weights, self.v1_chunk).reshape(self.nfreq, self.v1_chunk)\n\n\n def end_substream(self):\n pass\n\n\n def _v1(self, i, w):\n \"\"\"Calculate weighted variance\"\"\"\n if np.count_nonzero(w) < self.v1_chunk * 0.25:\n return 0\n return np.average(i**2, weights=w) \n\n\n####################################################################################################\n\n\n# The externally-visible online_mask_filler() is now a function which can return\n# either a C++ transform object or a python transform object, depending on the\n# value of its 'cpp' argument.\n\ndef online_mask_filler(v1_chunk=32, var_weight=2e-3, var_clamp_add=3.3e-3, var_clamp_mult=3.3e-3, w_clamp=3.3e-3, w_cutoff=0.5, \n nt_chunk=1024, overwrite_on_wt0=True, modify_weights=True, cpp=True):\n \"\"\"\n Variance estimates are calculated independently for each frequency. A variance value is computed for each v1_chunk \n samples. Then, an \"exponential average\" variance is computed, in which the new variance estimate for a frequency is \n given a weight of var_weight and the previous variance estimate is given a weight of 1-var_weight. These are summed \n to arrive at the updated variance estimate. Note that the variance estimate for a particular frequency cannot vary \n by more than var_clamp in a particular chunk to account for outliers. \n \n If a new variance estimate is successful, the corresponding weight will be increased (if possible) by w_clamp. If too\n much of the channel is masked to produce a variance estimate, the corresponding weight will be decreased (if possible)\n by w_clamp (stored in a temporary weights array).\n\n Finally, the intensity values are modified. If the corresponding weight is below w_cutoff, the intensity value will\n be filled with gaussian random noise with a variance given by the calculated variance estimate. \n\n tldr: Estimates the variance of each frequency independently on ~10s timescales and uses it to uniform the \n weights/intensity arrays by filling in gaussian random noise with the calculated variance for low weight values. \n\n Constructor arguments\n ---------------------\n v1_chunk - Number of samples used to generate a variance estimate (the variance is computed across the sample)\n var_weight - The weighting given to each new variance estimate in the exponential average\n var_clamp_add - The amount the variance can vary by in each v1_chunk per frequency\n var_clamp_mult - The multiplicative amoun the variance can vary by in each v1_chunk per frequency\n w_clamp - The amount the weight can vary by in each v1_chunk per frequency\n w_cutoff - Weight threshold below which the corresponding intensity will be replaced with gaussian random noise\n cpp - If True, then the fast \"production\" C++ implementation of the transform will be used.\n If False, then the python reference implementation will be used.\n \"\"\"\n\n if cpp:\n # Return C++ transform.\n return rf_pipelines.rf_pipelines_c.make_online_mask_filler(v1_chunk, var_weight, var_clamp_add, var_clamp_mult,\n w_clamp, w_cutoff, nt_chunk, overwrite_on_wt0, modify_weights)\n\n # Return instance of the py_online_mask_filler class above.\n cout << \"online_mask_filler warning: are you sure you want to be using the old python implementation?\" << endl;\n return py_online_mask_filler(v1_chunk, var_weight, var_clamp_add, var_clamp_mult, w_clamp, w_cutoff, nt_chunk)\n","sub_path":"to_resurrect/online_mask_filler.py","file_name":"online_mask_filler.py","file_ext":"py","file_size_in_byte":7733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"300462720","text":"from random import randint, sample, uniform\r\nfrom acme import Product\r\n\r\nADJECTIVES = ['Awesome', 'Shiny', 'Impressive', \r\n\t\t\t\t'Portable', 'Improved']\r\n\r\nNOUNS = ['Anvil', 'Catapult', 'Disguise', \r\n\t\t\t\t'Mousetrap', '???']\r\n\r\n\r\ndef generate_products(num_products=30):\r\n\t\"\"\"\r\n\tGenerates a list with a passed number of products (default = 30)\r\n\t\"\"\"\r\n\tproducts = []\r\n\r\n\tfor _ in range(num_products):\r\n\t\tadj_rand = ADJECTIVES[randint(0, len(ADJECTIVES)-1)]\r\n\t\tnoun_rand = NOUNS[randint(0, len(NOUNS)-1)]\r\n\r\n\t\tname = adj_rand+\" \"+noun_rand\r\n\t\tweight = randint(5, 100)\r\n\t\tprice = randint(5, 100)\r\n\t\tflammability = uniform(0,2.5)\r\n\r\n\t\tproducts.append(Product(name = name, weight = weight, price = price, \r\n\t\t\t\t\t\t\t\tflammability = flammability))\r\n\t\t\t\r\n\treturn products\r\n\r\n\r\ndef inventory_report(products):\r\n\t\"\"\" Prints an inventory report using random values for prices,\r\n\tweights and flammability. \r\n\t\"\"\"\r\n\tprint('ACME CORPORATION OFFICIAL INVENTORY REPORT\\n')\r\n\r\n\tprint(f'Unique product names: {len(set(products))}')\r\n\r\n\tprices = []\r\n\tweights = []\r\n\tflammabilities = []\r\n\r\n\tfor i in range(len(products)):\r\n\t\tprices += [products[i].price]\r\n\t\tweights += [products[i].weight]\r\n\t\tflammabilities += [products[i].flammability]\r\n\r\n\tavg_price = sum(prices)/len(prices)\r\n\tavg_weight = sum(weights)/len(weights)\r\n\tavg_flamm = sum(flammabilities)/len(flammabilities)\r\n\r\n\tprint(f'Average price: {avg_price}')\r\n\tprint(f'Average weight: {avg_weight}')\r\n\tprint(f'Average flammability: {avg_flamm}')\r\n\r\n\r\nif __name__ == '__main__':\r\n\tinventory_report(generate_products())\r\n","sub_path":"challenge/acme_report.py","file_name":"acme_report.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"499785886","text":"ANSWER = 4782\nLIMIT = 1000\n\n\ndef main():\n a, b, i = 1, 1, 2\n while b < 10 ** (LIMIT - 1):\n a, b, i = b, a + b, i + 1\n return i\n\n\nif __name__ == '__main__':\n print(main())\n","sub_path":"python/problem25.py","file_name":"problem25.py","file_ext":"py","file_size_in_byte":190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"63745342","text":"import numpy as np\nimport pandas as pd\n\nfrom s3filter.op.aggregate import Aggregate\nfrom s3filter.op.aggregate_expression import AggregateExpression\nfrom s3filter.op.collate import Collate\nfrom s3filter.op.hash_join_build import HashJoinBuild\nfrom s3filter.op.hash_join_probe import HashJoinProbe\nfrom s3filter.op.join_expression import JoinExpression\nfrom s3filter.op.map import Map\nfrom s3filter.op.operator_connector import connect_many_to_many, connect_all_to_all, connect_many_to_one, \\\n connect_one_to_one\nfrom s3filter.op.project import ProjectExpression, Project\nfrom s3filter.op.sql_table_scan import SQLTableScan\nfrom s3filter.plan.query_plan import QueryPlan\nfrom s3filter.query.join.synthetic_join_settings import SyntheticFilteredJoinSettings\nfrom s3filter.query.tpch import get_file_key\nfrom s3filter.query.tpch_q19 import get_sql_suffix\n\n\ndef query_plan(settings):\n # type: (SyntheticFilteredJoinSettings) -> QueryPlan\n \"\"\"\n\n :return: None\n \"\"\"\n\n query_plan = QueryPlan(is_async=settings.parallel, buffer_size=settings.buffer_size)\n\n def scan_A_fn(df):\n df.columns = settings.table_A_field_names\n return df\n\n # Define the operators\n scan_A = \\\n map(lambda p:\n query_plan.add_operator(\n SQLTableScan(get_file_key(settings.table_A_key, settings.table_A_sharded, p),\n \"select \"\n \" {} \"\n \"from \"\n \" S3Object \"\n \"where \"\n \" {} \"\n \" {} \"\n .format(','.join(settings.table_A_field_names),\n settings.table_A_filter_sql,\n get_sql_suffix(settings.table_A_key, settings.table_A_parts, p,\n settings.table_A_sharded)), settings.format_,\n settings.use_pandas,\n settings.secure,\n settings.use_native,\n 'scan_A_{}'.format(p),\n query_plan,\n False, \n fn=scan_A_fn)),\n range(0, settings.table_A_parts))\n \n \"\"\"\n field_names_map_A = OrderedDict(\n zip(['_{}'.format(i) for i, name in enumerate(settings.table_A_field_names)], settings.table_A_field_names))\n\n def project_fn_A(df):\n df = df.rename(columns=field_names_map_A, copy=False)\n return df\n\n project_A = map(lambda p:\n query_plan.add_operator(Project(\n [ProjectExpression(k, v) for k, v in field_names_map_A.iteritems()],\n 'project_A_{}'.format(p),\n query_plan,\n True,\n project_fn_A)),\n range(0, settings.table_A_parts))\n \"\"\"\n def scan_B_fn(df):\n df.columns = settings.table_B_field_names\n return df\n\n scan_B = \\\n map(lambda p:\n query_plan.add_operator(\n SQLTableScan(get_file_key(settings.table_B_key, settings.table_B_sharded, p),\n \"select \"\n \" {} \"\n \"from \"\n \" S3Object \"\n \"where \"\n \" {} \"\n \" {} \"\n .format(','.join(settings.table_B_field_names),\n settings.table_B_filter_sql,\n get_sql_suffix(settings.table_B_key, settings.table_B_parts, p,\n settings.table_B_sharded, add_where=False)), settings.format_,\n settings.use_pandas,\n settings.secure,\n settings.use_native,\n 'scan_B_{}'.format(p),\n query_plan,\n False,\n fn=scan_B_fn)),\n range(0, settings.table_B_parts))\n \n \"\"\"\n field_names_map_B = OrderedDict(\n zip(['_{}'.format(i) for i, name in enumerate(settings.table_B_field_names)], settings.table_B_field_names))\n\n def project_fn_B(df):\n df.rename(columns=field_names_map_B, inplace=True)\n return df\n\n project_B = map(lambda p:\n query_plan.add_operator(Project(\n [ProjectExpression(k, v) for k, v in field_names_map_B.iteritems()],\n 'project_B_{}'.format(p),\n query_plan,\n True,\n project_fn_B)),\n range(0, settings.table_B_parts))\n \"\"\"\n def scan_C_fn(df):\n df.columns = settings.table_C_field_names\n return df\n\n scan_C = \\\n map(lambda p:\n query_plan.add_operator(\n SQLTableScan(get_file_key(settings.table_C_key, settings.table_C_sharded, p),\n \"select \"\n \" {} \"\n \"from \"\n \" S3Object \"\n \"where \"\n \" {} \"\n \" {} \"\n .format(','.join(settings.table_C_field_names),\n settings.table_C_filter_sql,\n get_sql_suffix(settings.table_C_key, settings.table_C_parts, p,\n settings.table_C_sharded, add_where=False)), settings.format_,\n settings.use_pandas,\n settings.secure,\n settings.use_native,\n 'scan_C_{}'.format(p),\n query_plan,\n False,\n fn=scan_C_fn)),\n range(0, settings.table_C_parts))\n \n \"\"\"\n field_names_map_C = OrderedDict(\n zip(['_{}'.format(i) for i, name in enumerate(settings.table_C_field_names)], settings.table_C_field_names))\n\n def project_fn_C(df):\n df = df.rename(columns=field_names_map_C, copy=False)\n return df\n\n project_C = map(lambda p:\n query_plan.add_operator(Project(\n [ProjectExpression(k, v) for k, v in field_names_map_C.iteritems()],\n 'project_C_{}'.format(p),\n query_plan,\n True,\n project_fn_C)),\n range(0, settings.table_C_parts))\n \"\"\"\n\n map_A_to_B = map(lambda p:\n query_plan.add_operator(\n Map(settings.table_A_AB_join_key, 'map_A_to_B_{}'.format(p), query_plan, False)),\n range(0, settings.table_A_parts))\n\n map_B_to_B = map(lambda p:\n query_plan.add_operator(\n Map(settings.table_B_AB_join_key, 'map_B_to_B_{}'.format(p), query_plan, False)),\n range(0, settings.table_B_parts))\n\n map_B_to_C = map(lambda p:\n query_plan.add_operator(\n Map(settings.table_B_BC_join_key, 'map_B_to_C_{}'.format(p), query_plan, False)),\n range(0, settings.table_B_parts))\n\n map_C_to_C = map(lambda p:\n query_plan.add_operator(\n Map(settings.table_C_BC_join_key, 'map_C_to_C_{}'.format(p), query_plan, False)),\n range(0, settings.table_C_parts))\n\n join_build_A_B = map(lambda p:\n query_plan.add_operator(\n HashJoinBuild(settings.table_A_AB_join_key, 'join_build_A_B_{}'.format(p), query_plan,\n False)),\n range(0, settings.table_B_parts))\n\n join_probe_A_B = map(lambda p:\n query_plan.add_operator(\n HashJoinProbe(JoinExpression(settings.table_A_AB_join_key, settings.table_B_AB_join_key),\n 'join_probe_A_B_{}'.format(p),\n query_plan, True)),\n range(0, settings.table_B_parts))\n\n join_build_AB_C = map(lambda p:\n query_plan.add_operator(\n HashJoinBuild(settings.table_B_BC_join_key, 'join_build_AB_C_{}'.format(p), query_plan,\n False)),\n range(0, settings.table_C_parts))\n\n join_probe_AB_C = map(lambda p:\n query_plan.add_operator(\n HashJoinProbe(JoinExpression(settings.table_B_BC_join_key, settings.table_C_BC_join_key),\n 'join_probe_AB_C_{}'.format(p),\n query_plan, True)),\n range(0, settings.table_C_parts))\n\n def part_aggregate_fn(df):\n sum_ = df[settings.table_C_detail_field_name].astype(np.float).sum()\n return pd.DataFrame({'_0': [sum_]})\n\n part_aggregate = map(lambda p:\n query_plan.add_operator(Aggregate(\n [\n AggregateExpression(AggregateExpression.SUM,\n lambda t: float(t[settings.table_C_detail_field_name]))\n ],\n settings.use_pandas,\n 'part_aggregate_{}'.format(p), query_plan, False, part_aggregate_fn)),\n range(0, settings.table_C_parts))\n\n def aggregate_reduce_fn(df):\n sum_ = df['_0'].astype(np.float).sum()\n return pd.DataFrame({'_0': [sum_]})\n\n aggregate_reduce = query_plan.add_operator(Aggregate(\n [\n AggregateExpression(AggregateExpression.SUM, lambda t: float(t['_0']))\n ],\n settings.use_pandas,\n 'aggregate_reduce', query_plan, False, aggregate_reduce_fn))\n\n aggregate_project = query_plan.add_operator(Project(\n [\n ProjectExpression(lambda t: t['_0'], 'total_balance')\n ],\n 'aggregate_project', query_plan,\n False))\n\n collate = query_plan.add_operator(Collate('collate', query_plan, False))\n\n # Connect the operators\n connect_many_to_many(scan_A, map_A_to_B)\n #connect_many_to_many(project_A, map_A_to_B)\n connect_all_to_all(map_A_to_B, join_build_A_B)\n connect_many_to_many(join_build_A_B, join_probe_A_B)\n\n connect_many_to_many(scan_B, map_B_to_B)\n #connect_many_to_many(scan_B, project_B)\n #connect_many_to_many(project_B, map_B_to_B)\n connect_all_to_all(map_B_to_B, join_probe_A_B)\n connect_many_to_many(join_build_AB_C, join_probe_AB_C)\n\n connect_many_to_many(join_probe_A_B, map_B_to_C)\n connect_all_to_all(map_B_to_C, join_build_AB_C)\n\n connect_many_to_many(scan_C, map_C_to_C)\n #connect_many_to_many(scan_C, project_C)\n #connect_many_to_many(project_C, map_C_to_C)\n connect_all_to_all(map_C_to_C, join_probe_AB_C)\n\n connect_many_to_many(join_probe_AB_C, part_aggregate)\n\n connect_many_to_one(part_aggregate, aggregate_reduce)\n connect_one_to_one(aggregate_reduce, aggregate_project)\n connect_one_to_one(aggregate_project, collate)\n\n return query_plan\n","sub_path":"s3filter/query_layer/join/synthetic_join_filtered_opt.py","file_name":"synthetic_join_filtered_opt.py","file_ext":"py","file_size_in_byte":11646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"636223098","text":"from rest_framework import serializers\n\nfrom board.models import Board, Task\n\nclass BoardSerializer(serializers.ModelSerializer):\n\n\ttasks = serializers.HyperlinkedRelatedField(\n many=True,\n read_only=True,\n view_name='board-api:task_detail'\n )\n\n\tclass Meta:\n\t\tmodel = Board\n\t\tfields = [\n\t\t\t'id',\n\t\t\t'users',\n\t\t\t'title',\n\t\t\t'tasks',\n\t\t]\n\t\tread_only_fields = ['users', 'tasks']\n\n\n\nclass TaskSerializer(serializers.ModelSerializer):\n\n\tclass Meta:\n\t\tmodel = Task\n\t\tfields = [\n\t\t\t'id',\n\t\t\t'board',\n\t\t\t'title',\n\t\t\t'text',\n\t\t\t'status',\n\t\t]\n","sub_path":"lime/board/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"489228476","text":"# matplotlib x pands : Correlation Analysis, =상관분석(산점도, 공분산, 상관계수, 검정)\n# 둘 이상의 사건이 서로 연관성을 가질 때, 그 관계를 상관분석과 회귀분석 둘중 하나로 분석할 수 있다.\n# 상관분석(Correlation Analysis)의 예 : GDP와 기대수명간의 관계, 키와 몸무게 간의 관계, 당뇨와 그에 영향을 미치는 변수간의 상관을 분석\n# 이번에는 당뇨와 그에 영향을 미치는 변수간의 관계를 분석해보자.\n# 데이터는 sklearn에서 제공하는 datasets을 불러왔다.\n\n# 1. import\nimport pandas as pd\nimport numpy as np\nfrom sklearn import datasets # pip install sklearn # 혹시 안될 경우 260자 제한 풀기 (링크: https://www.howtogeek.com/266621/how-to-make-windows-10-accept-file-paths-over-260-characters/)\n\n# 1. data의 준비\ndata = datasets.load_diabetes()\nprint(data.keys()) # dict 형태이므로 어떤 key를 가지는 지 먼저 확인해본다.\n# dict_keys(['data', 'target', 'frame', 'DESCR', 'feature_names', 'data_filename', 'target_filename']) # 여기서 data, target, feature_name 3가지 key만 쓰겠다. 당연히 데이터 형태의 길이가 같은지부터 확인해봐야한다.\ndata['data'].shape\ndata['target'].shape\nlen(data['feature_names'])\ndf = pd.DataFrame(data['data'], index=data['target'], columns=data['feature_names'])\nprint(df)\n# 여기서 target이 당뇨병의 수치이고 나머지 feature names에 속하는 age, sex, bmi 등등은 변수라고 보면 된다. 즉, 442명의 사람들을 상대로 10가지의 특성을 나열한 것.\n\n# 1. 산점도(Scatter Plot) : bmi(체질량지수)와 target(당뇨병의 수치)이 어떤 관계를 가지는 지 살펴본다.\nX = df.bmi.values # 체질량지수 값\nY = df.index.values # 당뇨병치수 값\nimport matplotlib.pyplot as plt\nplt.scatter(X, Y, alpha=0.5)\nplt.title('TARGET - BMI')\nplt.xlabel('BMI')\nplt.ylabel('TARGET')\nplt.show()\n# 대략 봤을 때 변수는 서로 양의 관계를 이루고 있는 것 같다.\n\n# 1. 공분산(Covariance) 및 상관계수(Correlation Coefficient)\n# 산점도를 이용하면 두 변수간 직선관계를 대략 파악은 가능하지만, \n# 두 변수 사이의 관계를 어떠한 수치로 표현하진 않는다.\n# 이를 수치로 표현하기 위해 공분산 및 상관계수를 이용한다.\n\n# 공분산 : 2개의 확률변수의 상관정도를 나타내는 값. \n# 만약 2개 변수중 하나의 값이 상승하는 경향을 보일 때, 다른 값도 상승하면 양수가 되고, \n# 하강할 때 하강하는 경향을 보이면 음수가 된다.\n# 공분산의 식은 다음과 같다.\ncov_value = (np.sum(X*Y) - len(X)*np.mean(X)*np.mean(Y))/len(X)\nprint(cov_value) # 2.148043.... # 양수가 나왔다. 값이 상승하면 상승한다(서로 양의 관계다)라는 결론이 나온다.\n# 더 편하게는 numpy의 cov()를 이용하면 된다.\ncov_value = np.cov(X, Y)[0, 1]\nprint(cov_value)\n# 둘다 비슷한 값이 나왔고 양의 값이 나왔다.\n# 그러나 공분산은 상관관계의 상승 혹은 하강하는 경향을 이해는 할 수 있으나,\n# 2개 변수의 측정 단위 크기에 따라 값이 달라지므로,\n# 절대적 정도를 파악하기에는 한계가 있다.\n# 즉 2.15가 어느 정도 양의 상관관계인지를 가늠하기가 쉽지 않다.\n# 그래서 공분산을 표준화시킨 상관계수를 보다 많이 이용한다.\n# 상관계수는 각 변수의 표준편차를 분모로 나눠주면 된다.\n\n# 1. 상관계수 구하기\n# 상관계수 공식대로 코딩해서 얻는 방법이다.\ncorr_value=cov_value/(np.std(X)*np.std(Y))\nprint(corr_value)\n# 당연히 numpy는 없는 게 없다. corrcoef() 함수를 이용해도 구할 수 있다.\ncorr_value=np.corrcoef(X, Y)[0, 1]\nprint(corr_value)\n# 상관계수는 -1에서 1 사이의 값을 가지기에 0일 경우에는 두 변수간 선형관계가 전혀 없다는 뜻이고,\n# 0.3과 0.7 사이이면, 뚜렷한 양적 선형관계로 0.7과 1.0 사이는 강한 양적 선형관계로 간주한다.\n# 그러나 데이터 특성과 샘플의 대표성 등 상황에 따라 상관계수 값 자체를 해석하는 데 있어 정확한 기준은 없다.\n# 위에 나온 0.58은 BMI(체질량지수)와 Target(당뇨병수치)는 뚜렷한 양적 선형관계를 이루고 있다고 볼 수 있다.\n\n# 1. 상관관계를 해석함에 있어서 주의할 점\n# 상관관계는 두 변수간 관련성을 의미할 뿐, 원인과 결과의 방향을 알려주지 않는다.\n# 상관계수 분석 자체가 특이값에 민감하게 반응하기 때문에, 데이터 검정(pre-processing)에 항상 주의를 기울여야 한다.\n\n# 1. 상관계수의 검정\n# 상관계수의 값 자체가 유의미한가를 검정\n# p-value를 많이 이용하는데, scipy 패키지의 stats.pearsonr()을 이용하면 상관계수와 p-value를 동시에 얻을 수 있음\nimport scipy.stats as stats # pip install scipy\ncorr_test=stats.pearsonr(X, Y)\nprint(corr_test)\n# 0.586... , 3.466...e-42 : 뒤 결과 값이 p-value인데, 귀무가설 \"상관관계가 없다\"에 대한 검정 결과,\n# p-value가 3.46e-42라는 0에 아주 매우 가까운 값이 나왔으므로, 귀무가설을 기각할 수 있음을 알 수 있음.\n\n# 1. 나머지 변수들도 상관계수를 확인해보기\nfor item in ['age', 'sex', 'bmi', 'bp']:\n print(item)\n X = df[item].values\n print('Covariance: {:.2f}'.format(np.cov(X, Y)[0, 1]))\n print('Correlation: {:.2f}'.format(stats.pearsonr(X, Y)[0]))\n print('P-Value: {:.4f}'.format(stats.pearsonr(X, Y)[1]))\n print('\\n')\n# 결과의 해석\n# P-Value가 0.0001, 0.3664인 age와 sex는 큰 관련이 없다.\n# 당뇨병수치와 가장 상관관계가 높은 것은 bmi이다.\n\n# 숙제1 : 두 데이터를 토대로 상관관계를 분석하는 앱(각종 수치를 내고 산점도도 보여주기)을 만들어보자.\n# 숙제2 : 엑셀데이터로부터 판다스를 통해 파이썬 클래스로 정보를 받아온 뒤 맷플롯립과 연동하여 그래프를 보여주는 앱을 만들어보자.","sub_path":"back_python_3_dataprocess1/2_python_pandas_x_matplotlib1/9.py","file_name":"9.py","file_ext":"py","file_size_in_byte":6118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"229268101","text":"from __future__ import division, print_function\nfrom sklearn import preprocessing\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cbook as cbook\nimport matplotlib.cm as cm\nfrom matplotlib.collections import LineCollection\nfrom matplotlib.ticker import MultipleLocator\nfrom sklearn.metrics import confusion_matrix\nimport itertools\ndef read_emg(filename):\n df= pd.read_csv(filename,names=['Batt','Time','C',\n 'Raw-Ch1','Raw-Ch2','Raw-Ch3','Raw-Ch4','Raw-Ch5','Raw-Ch6','Raw-Ch7','Raw-Ch8','L',\n 'Rect-Ch0','Rect-Ch1','Rect-Ch2','Rect-Ch3','Rect-Ch4','Rect-Ch5','Rect-Ch6','Rect-Ch7','U',\n 'Smooth-Ch0','Smooth-Ch1','Smooth-Ch2','Smooth-Ch3','Smooth-Ch4','Smooth-Ch5','Smooth-Ch6','Smooth-Ch7','AD',\n 'q1','q2','q3','q4','AI',\n 'ax','ay','az','AM',\n 'gx','gy','gz','AQ',\n 'mx','my','mz',\"AU\"])\n d=df.loc[:,['Time','Raw-Ch1','Raw-Ch2','Raw-Ch3','Raw-Ch4','Raw-Ch5','Raw-Ch6','Raw-Ch7','Raw-Ch8','Rect-Ch0','Rect-Ch1','Rect-Ch2','Rect-Ch3','Rect-Ch4',\n 'Rect-Ch5','Rect-Ch6','Rect-Ch7','Smooth-Ch0','Smooth-Ch1','Smooth-Ch2','Smooth-Ch3','Smooth-Ch4','Smooth-Ch5','Smooth-Ch6','Smooth-Ch7',\n 'q1','q2','q3','q4','ax','ay','az','gx','gy','gz']]\n return d\n \ndef plot_EMG(time,emgs,gesture_name,normalize=False):\n if normalize:\n emgs = normalize_EEG(emgs)\n fig = plt.figure(\"EMG\")\n ticklocs = []\n numRows=8\n ax = fig.add_subplot(1, 1, 1)\n ax.set_xticks(np.arange(10))\n dmin = emgs.min().min()\n dmax = emgs.max().max()\n dr = (dmax - dmin) * 1 # Crowd them a bit.\n y0 = 1\n y1 = (numRows - 1) * dr + dmax\n plt.ylim(y0, y1)\n \n segs = []\n for i,ch in enumerate(emgs[:8]):\n segs.append(np.hstack((time[:, np.newaxis], emgs[ch][:, np.newaxis])))\n ticklocs.append((i+0.25) * dr)\n\n offsets = np.zeros((numRows, 2), dtype=float)\n offsets[:, 1] = ticklocs\n\n lines = LineCollection(segs, offsets=offsets, transOffset=None)\n ax.add_collection(lines)\n\n # Set the yticks to use axes coordinates on the y axis\n ax.set_yticks(ticklocs)\n ax.set_yticklabels( [ 'Raw-Ch1','Raw-Ch2','Raw-Ch3','Raw-Ch4','Raw-Ch5','Raw-Ch6','Raw-Ch7','Raw-Ch8'])\n ax.set_title(gesture_name)\n ax.set_xlabel('Time (s)')\n \n return ax,emgs\n\ndef normalize_EEG(df):\n x = df.values #returns a numpy array\n min_max_scaler = preprocessing.MinMaxScaler()\n x_scaled = min_max_scaler.fit_transform(x)\n df = pd.DataFrame(x_scaled)\n return df\n\ndef thresholding_algo(y, lag, threshold, influence):\n signals = np.zeros(len(y))\n filteredY = np.array(y)\n avgFilter = [0]*len(y)\n stdFilter = [0]*len(y)\n avgFilter[lag - 1] = np.mean(y[0:lag])\n stdFilter[lag - 1] = np.std(y[0:lag])\n for i in range(lag, len(y)):\n if abs(y[i] - avgFilter[i-1]) > threshold * stdFilter [i-1]:\n if y[i] > avgFilter[i-1]:\n signals[i] = 1\n else:\n signals[i] = -1\n\n filteredY[i] = influence * y[i] + (1 - influence) * filteredY[i-1]\n avgFilter[i] = np.mean(filteredY[(i-lag):i])\n stdFilter[i] = np.std(filteredY[(i-lag):i])\n else:\n signals[i] = 0\n filteredY[i] = y[i]\n avgFilter[i] = np.mean(filteredY[(i-lag):i])\n stdFilter[i] = np.std(filteredY[(i-lag):i])\n\n return dict(signals = np.asarray(signals),\n avgFilter = np.asarray(avgFilter),\n stdFilter = np.asarray(stdFilter))\n\ndef find_active_time(time,emg):\n T1 = []\n T2 = []\n for i in emg:\n x = time\n y = emg[i]\n\n lag=int(len(y)*1/5)\n threshold=3.6\n influence=0.6\n result = thresholding_algo(y, lag=lag, threshold=threshold, influence=influence)\n v=np.abs(result[\"signals\"])\n if(len(np.where(v==1)[0])>2):\n t1=x[np.where(v==1)[0][0]]\n t2=x[np.where(v==1)[0][-1]]\n T1.append(t1)\n T2.append(t2)\n t1 = np.mean(T1)\n t2 = np.mean(T2)\n return [t1,t2]\n\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\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 plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\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, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n 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\ndef confuse_matrix_plot(Y,Pred,list_class,title=\"confusion matrix\"):\n \n # Compute confusion matrix\n cnf_matrix = confusion_matrix(Y, Pred)\n np.set_printoptions(precision=2)\n\n # Plot normalized confusion matrix\n plt.figure()\n plot_confusion_matrix(cnf_matrix, classes=list_class, normalize=False,\n title=title)\n plt.show()\n # Plot normalized confusion matrix\n plt.figure()\n plot_confusion_matrix(cnf_matrix, classes=list_class, normalize=True,\n title=title +'(Normalized)')\n plt.show()\n\n\n","sub_path":"Week1/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":5887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"303968037","text":"import numpy as np\nfrom scipy import special\nfrom scipy.special import ellipk, ellipe\n\n\ndef coil_field(x, y, z, R):\n \"\"\"\n Best version of the coil magnetic field so far, it uses cartesian coordinates instead of the classic cylindrical.\n Adapted from:\n \"Simple Analytic Expressions for the Magnetic Field of a Circular Current Loop\" Simpson, J et al, 2001, NASA.\n \"\"\"\n rho = np.sqrt(z * z + y * y)\n r_sq = x * x + y * y + z * z\n alpha = np.sqrt(R * R + r_sq - 2. * R * rho)\n beta = np.sqrt(R * R + r_sq + 2. * R * rho)\n k = 1. - (alpha * alpha / (beta * beta))\n K = ellipk(k) # Elliptic integral, first kind, as a function of k\n E = ellipe(k)\n C = 1.\n\n B_x = C / (2. * alpha * alpha * beta) * ((R * R - r_sq) * R + alpha * alpha * K)\n B_y = (C * y * x / (2. * alpha * alpha * beta * rho * rho)) * ((R * R + r_sq) * E - alpha * alpha * K)\n\n if B_x.ndim == 0:\n if y != 0:\n B_z = (z / y) * B_y\n elif z == 0:\n B_z = 0\n else:\n B_z = 0\n B_x = 0\n\n else:\n B_z = np.ones_like(B_y)\n B_z[y != 0] = (z / y) * B_y\n B_z[y == 0] = 0\n\n B_x[np.where((y == 0) & (z == 0))] = 0\n\n # B_x[rho > R] = 0\n # B_y[rho > R] = 0\n # B_z[rho > R] = 0\n\n return np.c_[B_x, B_y, B_z]\n\n\ndef coil_field_cylindrical(x, y, z, theta, R):\n \"\"\"\n Magnetic field in a coil, cylindrical coordinate system. Adapted from different sources (list later);\n Formulas are correct, but the translation from cylindrical to cartesian has a mistake, so this field is currently\n not accurate. It may be worth debugging it, if comparing its results to the other field function is informative.\n \"\"\"\n\n rho = np.sqrt(y * y + z * z)\n\n Bo = 1. / (2. * R) # Central field = f(current, loop radius, perm. constant)\n alpha = rho / R # Alpha = f(radius of measurement point, radius of loop)\n beta = x / R # Beta = f(axial distance to meas. point, radius of loop)\n gamma = x / rho # Gamma = f(axial distance, radius to meas. point)\n Q = (1 + alpha) ** 2 + beta ** 2 # Q = f(radius, distance to meas. point, loop radius)\n k = np.sqrt(4 * alpha / Q) # k = f(radius, distance to meas. point, loop radius)\n K = ellipk(k * k) # Elliptic integral, first kind, as a function of k\n E = ellipe(k * k)\n Bx = (Bo / (np.pi * np.sqrt(Q))) * (E * ((1.0 - alpha ** 2 - beta ** 2) / (Q - 4 * alpha)) + K)\n B_rho = (Bo * gamma / (np.pi * np.sqrt(Q))) * ((E * (1.0 + alpha ** 2 + beta ** 2) / (Q - 4 * alpha)) - K)\n\n if B_rho.ndim == 0:\n if np.isnan(B_rho):\n B_rho = 0\n if np.isinf(B_rho):\n B_rho = 0\n if np.isnan(Bx):\n Bx = 0\n if np.isinf(Bx):\n Bx = 0\n else:\n B_rho[np.isnan(B_rho)] = 0\n B_rho[np.isinf(B_rho)] = 0\n Bx[np.isnan(Bx)] = 0\n Bx[np.isinf(Bx)] = 0\n\n B = np.c_[Bx, np.sin(theta) * B_rho, np.cos(theta) * B_rho]\n\n return B\n\n\nif __name__ == \"__main__\":\n cylindrical = coil_field_cylindrical(5, 5, 5, np.arctan(1), 10)\n cartesian = coil_field(5, 5, 5, 10)\n print(cylindrical)\n print(cartesian)\n","sub_path":"magnetic_fields.py","file_name":"magnetic_fields.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"414162264","text":"from kivy.app import App\nfrom kivy.uix.widget import Widget\nfrom kivy.graphics import Color, Rectangle\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.label import Label\nfrom kivy.uix.button import Button\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.togglebutton import ToggleButton\nfrom kivy.uix.progressbar import ProgressBar\nfrom kivy.config import Config\n# No resizable window\nConfig.set('graphics', 'resizable', 0)\nfrom kivy.core.window import Window\nfrom kivy.uix.image import Image\nfrom kivy.uix.slider import Slider\n\nimport gc\n\n# Brain-CEMISID kernel imports\nfrom kernel_braincemisid import KernelBrainCemisid\nfrom sensory_neural_block import RbfKnowledge\n\n\n\nclass MyPaintElement(Widget):\n def __init__(self, **kwargs):\n super(MyPaintElement, self).__init__(**kwargs)\n self.active = False\n\n def on_touch_down(self, touch):\n # Check if touch event is inside widget\n if self.collide_point(touch.x, touch.y):\n self._draw_rectange()\n\n def on_touch_move(self, touch):\n # Check if touch event is inside widget\n if self.collide_point(touch.x, touch.y):\n # If so, draw rectangle\n self._draw_rectange()\n\n def _draw_rectange(self):\n self.canvas.clear()\n with self.canvas:\n # lets draw a semi-transparent red square\n Color(1, 1, 1, 1, mode='rgba')\n Rectangle(pos=self.pos, size=(self.width*0.9, self.height*0.9))\n self.active = True\n\n def clear(self, color):\n self.canvas.clear()\n with self.canvas:\n if color == \"black\":\n # lets draw a semi-transparent red square\n Color(0, 0.65, 0.65, 1, mode='rgba')\n else:\n Color(0, 0.2, 0.2, 1, mode='rgba')\n Rectangle(pos=self.pos, size=(self.width*0.9, self.height*0.9))\n self.active = False\n\n def mark(self):\n self._draw_rectange()\n\n\nclass MyPaintWidget(GridLayout):\n\n CODING_SIZE = 4\n\n def __init__(self, size, **kwargs):\n super(MyPaintWidget, self).__init__(**kwargs)\n self.cols = size\n for index in range(self.cols * self.cols):\n self.add_widget(MyPaintElement())\n\n def clear(self):\n index = 0\n #with self.canvas.before:\n # Color(0, .1, .3, 1) # green; colors range from 0-1 instead of 0-255\n # self.rect = Rectangle(size=self.size,\n # pos=self.pos)\n\n for child in self.children:\n if index % 2:\n child.clear(\"dark-turquoise\")\n else:\n child.clear(\"black\")\n index += 1\n\n def get_pattern(self):\n # Initial pattern is an empty list of integers\n pattern = []\n # Integer representation or first row of pattern (bottom)\n val = 0\n # Counter to obtain integer value from binary row\n count = 1\n # For each MyPaintElement instance, verify if active and\n # add integer value to val depending on its position (count)\n for child in self.children:\n if child.active:\n val += count\n count *= 2\n # If row over, append to pattern array and\n # start encoding new one\n if count == pow(2, MyPaintWidget.CODING_SIZE):\n pattern.append(val)\n val = 0\n count = 1\n return pattern\n\n def draw_pattern(self, pattern):\n \"\"\" Draw given pattern in painter\"\"\"\n for index in range(len(pattern)):\n # Get children in groups of four (As codification was made by groups of four)\n child_offset = index*MyPaintWidget.CODING_SIZE\n child_set = self.children[child_offset:child_offset+MyPaintWidget.CODING_SIZE]\n # Convert current number of pattern into binary\n format_str = \"{0:0\"+str(MyPaintWidget.CODING_SIZE)+\"b}\"\n bin_pattern_element = format_str.format(pattern[index])\n # Traverse binary, mark or clear corresponding child\n for j in range(len(bin_pattern_element)):\n if bin_pattern_element[MyPaintWidget.CODING_SIZE-1-j] == \"1\":\n child_set[j].mark()\n else:\n if j % 2:\n child_set[j].clear(\"dark-turquoise\")\n else:\n child_set[j].clear(\"black\")\n\nclass RbfCardWidget(GridLayout):\n\n def __init__(self, width, **kwargs):\n super(RbfCardWidget, self).__init__(**kwargs )\n self.rows = 2\n self.spacing = 10\n self.painter = MyPaintWidget(16, size_hint = (1,0.9))\n self.text_label = Label( text = \"\", size_hint = (1,0.1))\n self.add_widget(self.painter)\n self.add_widget(self.text_label)\n self.size_hint = (None, None)\n self.size = (width, width)\n\n def show_knowledge(self, knowledge):\n self.painter.draw_pattern(knowledge.get_pattern())\n self.text_label.text = knowledge.get_class()\n\n def clear(self):\n self.painter.clear()\n self.text_label.text = \"\"\n\nclass MyGroupPaintWidget(GridLayout):\n\n def __init__(self, **kwargs):\n super(MyGroupPaintWidget, self).__init__(**kwargs)\n self.rows = 1\n self.cards = [RbfCardWidget(100) for count in range(3)]\n for card in self.cards:\n self.add_widget(card)\n\n def show_rbf_knowledge(self, knowledge_or_vector):\n for card in self.cards:\n card.clear()\n try:\n length = len(knowledge_or_vector)\n except:\n self.cards[0].show_knowledge(knowledge_or_vector)\n return\n\n if length > 3:\n return\n for index in range(len(knowledge_or_vector)):\n self.cards[index].show_knowledge(knowledge_or_vector[index])\n\n def clear(self):\n for card in self.cards:\n card.clear()\n\nclass SetInternalVariableWidget(GridLayout):\n\n def __init__(self, img_file, **kwargs):\n super(SetInternalVariableWidget, self).__init__(**kwargs)\n self.rows = 1\n self.img = Image(source=img_file)\n # Improve rendering via OpenGl\n self.img.mipmap = True\n self.img.size_hint_x = None\n self.img.width = 30\n self.slider = Slider(min=0, max=1, value=0.25, size_hint_x=None, width=235)\n self.label = Label(text = str(self.slider.value),font_size='17sp', size_hint_x=None, width=50)\n self.slider.bind(value=self.on_slider_value_change)\n self.add_widget(self.img)\n self.add_widget(self.slider)\n self.add_widget(self.label)\n\n\n def on_slider_value_change(self, obj, val):\n self.label.text = str(\"{0:.2f}\".format(val))\n\n def value(self):\n return self.slider.value\n\nclass ShowInternalVariableWidget(GridLayout):\n\n def __init__(self, img_file = None, **kwargs):\n super(ShowInternalVariableWidget, self).__init__(**kwargs)\n self.spacing = 5\n self.rows = 1\n if not img_file is None:\n self.img = Image(source=img_file)\n # Improve rendering via OpenGl\n self.img.mipmap = True\n self.img.size_hint_x = None\n self.img.width = 30\n self.add_widget(self.img)\n\n self.progress_bar = ProgressBar(max=1.0, value=0.5, size_hint_x = None, width=235)\n self.label = Label(text = str(self.progress_bar.value),font_size='17sp', size_hint_x=None, width=50)\n self.add_widget(self.progress_bar)\n self.add_widget(self.label)\n\n def change_value(self, val):\n self.label.text = str(\"{0:.2f}\".format(val))\n self.progress_bar.value = val\n\nclass IntentionsInterface(GridLayout):\n def __init__(self, **kwargs):\n super(IntentionsInterface, self).__init__(**kwargs)\n grid_size = 16\n self.kernel = KernelBrainCemisid()\n self.biology_input = SetInternalVariableWidget('icons/biology.png', size_hint_y = 0.33)\n self.culture_input = SetInternalVariableWidget('icons/culture.png', size_hint_y = 0.33)\n self.feelings_input = SetInternalVariableWidget('icons/feelings.png', size_hint_y = 0.33)\n self.internal_state_biology = ShowInternalVariableWidget(size_hint_y = 0.33)\n self.internal_state_culture = ShowInternalVariableWidget(size_hint_y = 0.33)\n self.internal_state_feelings = ShowInternalVariableWidget(size_hint_y = 0.33)\n self.desired_biology_input = SetInternalVariableWidget('icons/biology.png', size_hint_y = 0.33)\n self.desired_culture_input = SetInternalVariableWidget('icons/culture.png', size_hint_y = 0.33)\n self.desired_feelings_input = SetInternalVariableWidget('icons/feelings.png', size_hint_y = 0.33)\n # Main layout number of columns\n self.rows = 2\n self.load_icons()\n self.declare_thinking_panel()\n self.declare_painters(grid_size)\n self.declare_inputs()\n self.declare_buttons()\n self.add_widgets_layouts()\n # Set windows size\n Window.size = (1127, 700)\n # Clear painters when window draw\n self.win_show_uid = Window.fbind('on_draw',self.clear)\n self.win_format_back_uid = Window.fbind('on_draw', self.format_backgrounds)\n\n def load_icons(self):\n self.img_eye = Image(source='icons/eye.png')\n # Improve rendering via OpenGl\n self.img_eye.mipmap = True\n self.img_ear = Image(source='icons/ear.png')\n # Improve rendering via OpenGl\n self.img_ear.mipmap = True\n self.img_eye.size_hint = (None,None)\n self.img_ear.size_hint = (None,None)\n self.img_eye.width = 60\n self.img_ear.width = 60\n\n def declare_painters(self, grid_size):\n self.sight_painter = MyPaintWidget(grid_size)\n self.sight_painter.size_hint = (None, None)\n self.sight_painter.size = (200,200)\n self.hearing_painter = MyPaintWidget(grid_size)\n self.hearing_painter.size_hint = (None, None)\n self.hearing_painter.size = (200,200)\n\n def declare_thinking_panel(self):\n self.thinking_panel = GridLayout(cols=1, size_hint_x=0.6)\n self.thinking_sight = MyGroupPaintWidget(padding=2*self.height/3)\n self.thinking_hearing = MyGroupPaintWidget(padding=2*self.height/3)\n self.thinking_panel.add_widget(self.thinking_sight)\n self.thinking_panel.add_widget(self.thinking_hearing)\n\n def declare_inputs(self):\n self.hearing_class_input = TextInput(text=\"Class?\")\n self.hearing_class_input.size_hint = (None,None)\n self.hearing_class_input.width = 100\n self.hearing_class_input.height = 35\n self.hearing_class_input.font_size = 18\n\n def declare_buttons(self):\n # sight clear\n self.sight_clear_btn = Button(text=\"Clear S\", font_size='15sp')\n self.sight_clear_btn.bind(on_press=self.sight_clear)\n\n # Hearing clear\n self.hearing_clear_btn = Button(text=\"Clear H\", font_size='15sp')\n self.hearing_clear_btn.bind(on_press=self.hearing_clear)\n\n # Bum btn\n self.bum_btn = Button(text=\"Bum\", font_size='15sp')\n self.bum_btn.bind(on_release=self.bum)\n\n # Bip btn\n self.bip_btn = Button(text=\"Bip\", font_size='15sp')\n self.bip_btn.bind(on_release=self.bip)\n\n # Check btn\n self.check_btn = Button(text=\"Check\", font_size='15sp')\n self.check_btn.bind(on_release=self.check)\n\n # Clack btn\n self.clack_btn = Button(text=\"Clack\", font_size='15sp')\n self.clack_btn.bind(on_release=self.clack)\n\n\t # Set-zero button\n self.zero_btn = Button(text=\"0 sign\", font_size='15sp')\n self.zero_btn.bind(on_release=self.set_zero)\n\n # Set-equal-sign button\n self.equal_btn = Button(text=\"= sign\", font_size='15sp' )\n self.equal_btn.bind(on_release=self.set_equal_sign)\n\n # Set-add-operator button\n self.add_operator_btn = Button(text=\"+ sign\", font_size='15sp' )\n self.add_operator_btn.bind(on_release=self.set_add_operator)\n\n # Toggle button (Words, Numbers, Episodes, Intentions)\n self.words_tgl_btn = ToggleButton(text=\"Reading\", group=\"bbcc_protocol\", allow_no_selection=False)\n self.addition_tgl_btn = ToggleButton(text=\"Addition\", group=\"bbcc_protocol\", allow_no_selection=False)\n self.counting_tgl_btn = ToggleButton(text=\"Counting\", group=\"bbcc_protocol\", allow_no_selection=False)\n self.episodes_tgl_btn = ToggleButton(text=\"Episodes\", group=\"bbcc_protocol\", state=\"down\", allow_no_selection=False)\n self.intentions_tgl_btn = ToggleButton(text=\"Intentions\", group=\"bbcc_protocol\",\n allow_no_selection=False)\n\n def add_widgets_layouts(self):\n # Sight panel\n self.sight_panel = GridLayout(rows=1, padding=10, spacing=10, size_hint_y=0.375)\n self.sight_panel.add_widget(self.img_eye)\n self.sight_panel.add_widget(self.sight_painter)\n # Hearing panel\n self.hearing_painter_text = GridLayout(cols=1)\n self.hearing_painter_text.add_widget(self.hearing_painter)\n self.hearing_painter_text.add_widget(self.hearing_class_input)\n self.hearing_panel = GridLayout(rows=1, padding=10, spacing=10, size_hint_y=0.375)\n self.hearing_panel.add_widget(self.img_ear)\n self.hearing_panel.add_widget(self.hearing_painter_text)\n\n self.main_panel = GridLayout(cols=2, size_hint=(1,0.9))\n self.senses_bcf_panel = GridLayout(cols=1, padding=25, size_hint_y=0.25)\n self.senses_bcf_panel.add_widget(self.biology_input)\n self.senses_bcf_panel.add_widget(self.culture_input)\n self.senses_bcf_panel.add_widget(self.feelings_input)\n self.senses_panel = GridLayout(cols=1, padding=10, size_hint_x=0.3)\n self.senses_panel.add_widget(self.sight_panel)\n self.senses_panel.add_widget(self.hearing_panel)\n self.senses_panel.add_widget(self.senses_bcf_panel)\n\n\n self.main_panel.add_widget(self.senses_panel)\n\n\n self.internal_state_panel = GridLayout(cols=1, size_hint_y = 1, size_hint_x = 0.5)\n self.internal_state_label = Label(text=\"Internal State\",font_size='25sp', size_hint_x = None, size_hint_y = 0.3)\n self.internal_state_panel.add_widget(self.internal_state_label)\n self.internal_state_panel.add_widget(self.internal_state_biology)\n self.internal_state_panel.add_widget(self.internal_state_culture)\n self.internal_state_panel.add_widget(self.internal_state_feelings)\n\n self.desired_state_panel = GridLayout(cols=1, padding_x = 10, size_hint_y = 1,size_hint_x=0.5)\n self.desired_state_label = Label(text=\"Desired State\",font_size='25sp', size_hint_y = 0.3)\n self.desired_state_panel.add_widget(self.desired_state_label)\n self.desired_state_panel.add_widget(self.desired_biology_input)\n self.desired_state_panel.add_widget(self.desired_culture_input)\n self.desired_state_panel.add_widget(self.desired_feelings_input)\n\n self.desired_internal_states_panel = GridLayout(rows=1, padding=25, size_hint_x=1)\n self.desired_internal_states_panel.add_widget(self.desired_state_panel)\n self.desired_internal_states_panel.add_widget(self.internal_state_panel)\n\n self.thinking_panel.add_widget(self.desired_internal_states_panel)\n self.main_panel.add_widget(self.thinking_panel)\n\n # Add widgets to bottom layout\n self.buttons_panel = GridLayout(rows=1, size_hint=(1,0.1))\n self.buttons_panel.add_widget(self.bum_btn)\n self.buttons_panel.add_widget(self.bip_btn)\n self.buttons_panel.add_widget(self.check_btn)\n self.buttons_panel.add_widget(self.clack_btn)\n self.buttons_panel.add_widget(self.zero_btn)\n self.buttons_panel.add_widget(self.equal_btn)\n self.buttons_panel.add_widget(self.add_operator_btn)\n self.buttons_panel.add_widget(self.episodes_tgl_btn)\n self.buttons_panel.add_widget(self.intentions_tgl_btn)\n self.buttons_panel.add_widget(self.words_tgl_btn)\n self.buttons_panel.add_widget(self.addition_tgl_btn)\n self.buttons_panel.add_widget(self.counting_tgl_btn)\n self.buttons_panel.add_widget(self.sight_clear_btn)\n self.buttons_panel.add_widget(self.hearing_clear_btn)\n self.add_widget(self.main_panel)\n self.add_widget(self.buttons_panel)\n\n def learn(self,obj):\n return\n\n def hearing_clear(self, obj):\n self.hearing_painter.clear()\n self.hearing_class_input.text = \"Class?\"\n self.thinking_hearing.clear()\n return\n\n def sight_clear(self, obj):\n self.sight_painter.clear()\n self.thinking_sight.clear()\n return\n\n def bum(self,obj):\n self.pass_kernel_inputs()\n self.kernel.bum()\n return\n\n def bip(self,obj):\n self.pass_kernel_inputs()\n self.kernel.bip()\n self.show_kernel_outputs()\n return\n\n def check(self,obj):\n self.pass_kernel_inputs()\n self.kernel.check()\n self.show_kernel_outputs()\n return\n\n\n def clack(self,obj):\n self.pass_kernel_inputs()\n self.kernel.clack()\n self.show_kernel_outputs()\n return\n\n def pass_kernel_inputs(self):\n # Set working domain\n if self.episodes_tgl_btn.state == \"down\":\n self.kernel.set_working_domain(\"EPISODES\")\n else:\n self.kernel.set_working_domain(\"INTENTIONS\")\n # Get patterns\n hearing_pattern = self.hearing_painter.get_pattern()\n sight_pattern = self.sight_painter.get_pattern()\n hearing_class = self.hearing_class_input.text\n hearing_knowledge = RbfKnowledge(hearing_pattern, hearing_class)\n sight_knowledge = RbfKnowledge(sight_pattern, \"NoClass\")\n self.kernel.set_hearing_knowledge_in(hearing_knowledge)\n self.kernel.set_sight_knowledge_in(sight_knowledge)\n biology_in = self.biology_input.value()\n culture_in = self.culture_input.value()\n feelings_in=self.feelings_input.value()\n self.kernel.set_internal_state_in([biology_in, culture_in, feelings_in])\n desired_biology_in = self.desired_biology_input.value()\n desired_culture_in = self.desired_culture_input.value()\n desired_feelings_in = self.desired_feelings_input.value()\n self.kernel.set_desired_state([biology_in, culture_in, feelings_in])\n\n def show_kernel_outputs(self):\n self.thinking_clear()\n self.hearing_class_input.text = self.kernel.state\n kernel_internal_state = self.kernel.get_internal_state().get_state()\n self.internal_state_biology.change_value(kernel_internal_state[0])\n self.internal_state_culture.change_value(kernel_internal_state[1])\n self.internal_state_feelings.change_value(kernel_internal_state[2])\n if self.kernel.state == \"HIT\":\n h_knowledge = self.kernel.get_hearing_knowledge_out()\n s_knowledge = self.kernel.get_sight_knowledge_out()\n if h_knowledge is not None:\n self.thinking_hearing.show_rbf_knowledge(h_knowledge)\n if s_knowledge is not None:\n self.thinking_sight.show_rbf_knowledge(s_knowledge)\n\n def thinking_clear(self):\n self.thinking_sight.clear()\n self.thinking_hearing.clear()\n\n def clear(self, obj):\n self.sight_clear(None)\n self.hearing_clear(None)\n self.thinking_clear()\n Window.unbind_uid('on_draw', self.win_show_uid)\n\n def set_zero(self, obj):\n self.pass_kernel_inputs()\n self.kernel.set_zero()\n return\n\n def set_add_operator(self, obj):\n self.pass_kernel_inputs()\n self.kernel.set_add_operator()\n return\n\n def set_equal_sign(self, obj):\n self.pass_kernel_inputs()\n self.kernel.set_equal_sign()\n return\n\n def format_backgrounds(self, obj):\n with self.senses_panel.canvas.before:\n Color(0.11, 0.10, 0.1, 1, mode='rgba')\n Rectangle(pos=self.senses_panel.pos, size=(self.senses_panel.width, self.senses_panel.height))\n with self.desired_internal_states_panel.canvas.before:\n Color(0.07, 0.07, 0.07, 1, mode='rgba')\n Rectangle(pos=self.desired_internal_states_panel.pos, size=(self.desired_internal_states_panel.width, self.desired_internal_states_panel.height))\n Window.unbind_uid('on_draw', self.win_format_back_uid)\n\nclass MyPaintApp(App):\n def build(self):\n intentions_ui = IntentionsInterface()\n return intentions_ui\n\nif __name__ == '__main__':\n MyPaintApp().run()\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":20656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"338397561","text":"from __future__ import unicode_literals\n\nimport abc\nimport logging\n\nfrom jsonpointer import resolve_pointer, JsonPointerException\n\nlogger = logging.getLogger(__name__)\n\n\nclass BaseTransformer(object):\n\n __metaclass__ = abc.ABCMeta\n\n @abc.abstractmethod\n def _transform_string(self, string, doc):\n raise NotImplementedError\n\n @abc.abstractproperty\n def schema(self):\n raise NotImplementedError\n\n def transform(self, doc):\n return self._transform(self.schema, doc)\n\n def _transform(self, schema, doc):\n transformed = {}\n for key, value in schema.items():\n if isinstance(value, dict):\n transformed[key] = self._transform(value, doc)\n elif isinstance(value, list) or isinstance(value, tuple):\n transformed[key] = self._transform_iterable(value, doc)\n elif isinstance(value, basestring):\n transformed[key] = self._transform_string(value, doc)\n elif callable(value):\n transformed[key] = value(doc)\n return transformed\n\n def _transform_iterable(self, l, doc):\n\n if isinstance(l[0], tuple) and len(l) == 2:\n return self._transform_args_kwargs(l, doc)\n\n fn, values = l[-1], l[:-1]\n args = []\n\n for value in values:\n if isinstance(value, basestring):\n args.append(self._transform_string(value, doc))\n elif callable(value):\n args.append(value(doc))\n return fn(*args)\n\n def _transform_args_kwargs(self, l, doc):\n fn = l[1]\n return fn(\n *self._transform_args(l[0], doc),\n **self._transform_kwargs(l[0], doc)\n )\n\n def _transform_args(self, t, doc):\n return [self._transform_string(arg, doc) for arg in t[0]]\n\n def _transform_kwargs(self, t, doc):\n return {\n k: self._transform_string(v, doc) for k, v in t[1].items()\n } if len(t) == 2 else {}\n\n\nclass XMLTransformer(BaseTransformer):\n\n __metaclass__ = abc.ABCMeta\n\n def _transform_string(self, string, doc):\n val = doc.xpath(string, namespaces=self.namespaces)\n return unicode(val[0]) if len(val) == 1 else [unicode(v) for v in val] or ''\n\n @abc.abstractproperty\n def namespaces(self):\n raise NotImplementedError\n\n\nclass JSONTransformer(BaseTransformer):\n\n __metaclass__ = abc.ABCMeta\n\n def _transform_string(self, val, doc):\n try:\n return resolve_pointer(doc, val)\n except JsonPointerException:\n return ''\n","sub_path":"scrapi/base/transformer.py","file_name":"transformer.py","file_ext":"py","file_size_in_byte":2570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"412728119","text":"from bs4 import BeautifulSoup\nimport urllib2\nimport re\nfrom os.path import expanduser\nimport csv as csv\nimport httplib\nhttplib.HTTPConnection._http_vsn = 10\nhttplib.HTTPConnection._http_vsn_str = 'HTTP/1.0'\n\nhome = expanduser(\"~\")\n\nf = open(\"AllGameDataEver.csv\", 'w')\n\n# Make headers\nHeaders = []\nHeaders.append(\"Year\")\nHeaders.append(\"Q1\")\nHeaders.append(\"Q2\")\nHeaders.append(\"Q3\")\nHeaders.append(\"Q4\")\nHeaders.append(\"Final\")\nHeaders.append(\"OT\")\nHeaders.append(\"2OT\")\nHeaders.append(\"3OT\")\nHeaders.append(\"Year\")\nHeaders.append(\"Q1\")\nHeaders.append(\"Q2\")\nHeaders.append(\"Q3\")\nHeaders.append(\"Q4\")\nHeaders.append(\"Final\")\nHeaders.append(\"OT\")\nHeaders.append(\"2OT\")\nHeaders.append(\"3OT\")\n\nstring = ''\nfor i in range(len(Headers)):\n tempString = Headers[i]\n string += tempString\n string += ','\n \nstring += '\\n'\nf.write(string)\n\ngames = 0\n\nfor j in range(15):\n readurls = csv.reader(open(\"GameResults\" + str(j) + \".csv\"))\n \n file = []\n for row in readurls:\n file.append(row)\n \n file.pop(0)\n urls = []\n \n for i in range(len(file)):\n urls.append(file[i][0])\n\n for i in range(len(urls)):\n # URL of the individual Game\n BASE_URL = urls[i]\n\n # Open Page\n page = urllib2.urlopen(BASE_URL)\n\n soup = BeautifulSoup(page)\n all_tables = soup.find_all('table')\n\n right_table = soup.find('table', class_ = 'nav_table stats_table')\n\n # Get lines of HTML\n A = []\n for row in right_table.findAll(\"tr\"):\n cells = row.findAll('td')\n A.append(str(cells))\n \n # Put relevant data into list\n data = []\t \n for i in range(len(A)):\n if(i > 1): # ignore the first and second table(they're headers and such)\n data.append(re.findall(r'\\d+', A[i])) # Get relevant Data\n \n # In case they didnt have OT\n if(len(data[0]) + len(data[1]) == 12):\n data[0].insert(6, '0')\n data[0].insert(7, '0')\n data[0].insert(8, '0')\n data[1].insert(6, '0')\n data[1].insert(7, '0')\n data[1].insert(8, '0')\n if(len(data[0]) + len(data[1]) == 14):\n data[0].insert(7, '0')\n data[0].insert(8, '0')\n data[1].insert(7, '0')\n data[1].insert(8, '0')\n if(len(data[0]) + len(data[1]) == 16):\n data[0].insert(8, '0')\n data[1].insert(8, '0')\n \n \n # Make strings out of everything\n string = ''\n for i in range(len(data)):\n tempString = ','.join(data[i])\n string += tempString\n string += ','\n games += .5\n \n string += str(j) + ','\n string += '\\n'\n f.write(string)\n \n # Loading progress\n if (games % 10 == 0):\n print(str((games/(1315 * 14)) * 100) + \"%\")\n\n\n \n# CLOSE THE FILE BAAAAABY\nf.close()\n","sub_path":"PHY390/Basketball/getAllData.py","file_name":"getAllData.py","file_ext":"py","file_size_in_byte":2953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"244034504","text":"\"\"\"\nContent Provider: Flickr\n\nETL Process: Use the API to identify all CC licensed images.\n\nOutput: TSV file containing the images and the respective meta-data.\n\nNotes: https://www.flickr.com/help/terms/api\n Rate limit: 3600 queries per hour.\n\"\"\"\n\nfrom modules.etlMods import *\nimport calendar\nfrom dateutil import rrule\n\nlogging.getLogger(__name__)\nTs_RANGE = int(5) #process job using 5 minute intervals\nDELAY = 1.0 #time delay (in seconds)\nFILE = 'flickr_{}.tsv'.format(int(time.time()))\nSIZE = 500\nAPI_KEY = os.environ['FLICKR_API_KEY']\n\n\nURL = None\n#QUERY = 'https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key={0}&min_upload_date={1}&max_upload_date={2}&license=1&media=photos&content_type=1&extras=description,license,date_upload,date_taken,owner_name,tags,o_dims,url_t,url_s,url_m,url_l&per_page={3}&format=json&nojsoncallback=1'.format(API, MIN_DATE, MAX_DATE, SIZE)\n\nlogging.basicConfig(format='%(asctime)s: [%(levelname)s - Flickr API] =======> %(message)s', level=logging.INFO)\n#logging.info('processing date range: {} - {}'.format(MIN_DATE, MAX_DATE))\n\ndef getLicense(_index):\n version = 2.0\n ccLicense = {\n 1: 'by-nc-sa',\n 2: 'by-nc',\n 3: 'by-nc-nd',\n 4: 'by',\n 5: 'by-sa',\n 6: 'by-nd',\n 9: 'CC0',\n 10: 'PDM'\n }\n\n\n if _index == 'all':\n return ccLicense.keys()\n else:\n _index = int(_index)\n\n\n if (_index <= 0) or (_index in [7, 8]) or (_index > 10):\n logging.warning('Invalid license')\n return None, None\n\n\n license = ccLicense[_index]\n\n if _index in [9, 10]:\n version = 1.0\n\n return license, version\n\n\ndef extractData(_data):\n creator = ''\n creatorURL = ''\n title = ''\n foreignURL = ''\n foreignID = ''\n thumbnail = ''\n imageURL = ''\n width = ''\n height = ''\n license = ''\n version = ''\n tags = ''\n metaData = {}\n tagData = ''\n\n\n title = sanitizeString(_data.get('title', '\\\\N'))\n creator = sanitizeString(_data.get('ownername', '\\\\N'))\n\n if 'owner' in _data:\n creatorURL = 'www.flickr.com/photos/{}'.format(_data['owner'])\n creatorURL = creatorURL.strip()\n\n foreignID = sanitizeString(_data.get('id', '\\\\N'))\n\n if foreignID not in ['', '\\\\N'] and creatorURL != '':\n foreignURL = '{}/{}'.format(creatorURL, foreignID)\n\n if foreignURL is None:\n logging.warning('Landing page not detected!')\n return None\n\n\n #get the image URL\n imageURL = sanitizeString(_data.get('url_l', ''))\n height = sanitizeString(_data.get('height_l', ''))\n width = sanitizeString(_data.get('width_l', ''))\n thumbnail = sanitizeString(_data.get('url_s', ''))\n\n\n if imageURL == '':\n if 'url_m' in _data:\n imageURL = sanitizeString(_data.get('url_m', ''))\n height = sanitizeString(_data.get('height_m', ''))\n width = sanitizeString(_data.get('width_m', ''))\n\n elif 'url_s' in _data:\n imageURL = sanitizeString(_data.get('url_s', ''))\n height = sanitizeString(_data.get('height_s', ''))\n width = sanitizeString(_data.get('width_s', ''))\n\n else:\n logging.warning('Image not detected!')\n return None\n\n\n license, version = getLicense(_data.get('license'))\n\n if license is None:\n logging.warning('License not detected!')\n return None\n\n if 'dateupload' in _data:\n metaData['pub_date'] = sanitizeString(_data.get('dateupload'))\n\n if 'datetaken' in _data:\n metaData['date_taken'] = sanitizeString(_data.get('datetaken'))\n\n if 'description' in _data:\n desc = _data.get('description', '')\n content = None\n\n if '_content' in desc and desc['_content'] is not None:\n content = sanitizeString(desc.get('_content', ''))\n\n if content:\n metaData['description'] = content\n\n\n if 'tags' in _data and _data['tags'] is not None:\n tags = _data.get('tags', '').strip()\n\n if tags:\n maxTags = 20\n tagData = {}\n tagData = [{'name': tag.strip(), 'provider': 'flickr'} for tag in list(set(tags.split(' ')))[:maxTags]]\n\n\n return [\n imageURL if not foreignID else foreignID,\n foreignURL,\n imageURL,\n thumbnail if thumbnail else '\\\\N',\n str(int(float(width))) if width else '\\\\N',\n str(int(float(height))) if height else '\\\\N',\n '\\\\N',\n license,\n str(version) if version else '\\\\N',\n creator if creator else '\\\\N',\n creatorURL if creatorURL else '\\\\N',\n title if title else '\\\\N',\n json.dumps(metaData, ensure_ascii=False) if metaData else '\\\\N',\n json.dumps(tagData, ensure_ascii=False) if tagData else '\\\\N',\n 'f',\n 'flickr',\n 'flickr'\n ]\n\n\ndef getMetaData(_startTs, _endTs, _license, _switchDate=False):\n procTime = time.time()\n pages = 1\n curPage = 1\n numImages = 0\n endpoint = 'https://api.flickr.com/services/rest/?method=flickr.photos.search'\n\n\n while curPage <= pages:\n #loop through each page of data\n logging.info('Processing page: {}'.format(curPage))\n\n queryStr = '{0}&api_key={1}&min_upload_date={2}&max_upload_date={3}&license={5}&media=photos&content_type=1&extras=description,license,date_upload,date_taken,owner_name,tags,o_dims,url_t,url_s,url_m,url_l&per_page={4}&format=json&nojsoncallback=1&page={6}'.format(endpoint, API_KEY, _startTs, _endTs, SIZE, _license, curPage)\n\n if _switchDate:\n queryStr = queryStr.replace('upload_date', 'taken_date')\n\n imgData = requestContent(queryStr)\n if imgData:\n status = imgData['stat']\n if status == 'ok':\n result = imgData['photos']\n total = result['total'] #total results\n pages = result['pages'] #number of pages\n curPage = result['page'] #current page\n photos = result['photo'] #image meta data for the current page\n\n if photos:\n extracted = list(map(lambda photo: extractData(photo), photos))\n extracted = list(filter(None, extracted))\n numImages += len(extracted)\n writeToFile(extracted, FILE)\n\n curPage += 1\n delayProcessing(procTime, DELAY) #throttle requests\n procTime = time.time()\n\n logging.info('Total pages processed: {}'.format(pages))\n\n return numImages\n\n\ndef execJob(_license, _startDate, _duration=1, _mode=None):\n totalImages = 0\n srtTime = datetime.strptime(_startDate, '%Y-%m-%d %H:%M')\n endTime = datetime.strptime(_startDate, '%Y-%m-%d %H:%M') + timedelta(hours=_duration)\n\n for dt in rrule.rrule(rrule.MINUTELY, dtstart=srtTime, until=endTime):\n elapsed = int((dt - srtTime).seconds/60)\n\n if elapsed % Ts_RANGE == 0:\n curTime = dt\n nxtTime = curTime + timedelta(minutes=Ts_RANGE)\n logging.info('Processing dates: {} to {}, license: {}'.format(curTime, nxtTime, getLicense(_license)[0]))\n\n #get the meta data within the time interval\n totalImages += getMetaData(curTime, nxtTime, _license) #check upload_date\n totalImages += getMetaData(curTime, nxtTime, _license, True) #check taken_date\n\n logging.info('Total {} images: {}'.format(getLicense(_license)[0], totalImages))\n\n\ndef main():\n logging.info('Begin: Flickr API requests')\n param = None\n duration = 1 #in hours\n\n parser = argparse.ArgumentParser(description='Flickr API Job', add_help=True)\n parser.add_argument('--mode', choices=['default'],\n help='Identify all images that were uploaded in the previous hour [default] \\nIdentify all images that were uploaded on a given date [date] or month [month].')\n parser.add_argument('--date', type=lambda dt: datetime.strptime(dt, '%Y-%m-%d'),\n help='Identify images uploaded on a given date (format: YYYY-MM-DD).')\n parser.add_argument('--month', type=lambda dt: datetime.strptime(dt, '%Y-%m'),\n help='Identify images uploaded in a given year and month (format: YYYY-MM).')\n\n\n args = parser.parse_args()\n if args.date:\n param = args.date.strftime('%Y-%m-%d %H:%M')\n duration = 24\n\n elif args.month:\n param = args.month.strftime('%Y-%m-01 %H:%M')\n days = calendar.monthrange(args.month.year, args.month.month)[1]\n duration = 24 * int(days)\n\n elif args.mode:\n\n if str(args.mode) == 'default': #the start of the previous hour\n param = datetime.strftime(datetime.now() - timedelta(hours=1), '%Y-%m-%d %H:00')\n else:\n logging.warning('Invalid option')\n logging.info('Terminating!')\n\n #run the job and identify images for each CC license\n if param:\n list(map(lambda license: execJob(license, param, duration), list(getLicense('all'))))\n\n logging.info('Terminated!')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/providers/api/Flickr.py","file_name":"Flickr.py","file_ext":"py","file_size_in_byte":9396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"551698860","text":"'''\n序列求和\n\n资源限制\n时间限制:1.0s 内存限制:256.0MB\n\n问题描述\n求1+2+3+...+n的值。\n\n输入格式\n输入包括一个整数n。\n\n输出格式\n输出一行,包括一个整数,表示1+2+3+...+n的值。\n\n样例输入\n4\n\n样例输出\n10\n\n样例输入\n100\n\n样例输出\n5050\n\n数据规模与约定\n1 <= n <= 1,000,000,000。\n'''\n\n#这里用了递归的算法,但是输入1000会导致最大递归深度在比较中超过\n'''\ndef cumulative(n):\n if 0 == n:\n return 0\n elif n >1000000000:\n print(\"Date overflow\")\n else:\n return n + cumulative( n - 1 )\n\nwhile True:\n n = input()\n if n.isdigit():\n n = eval(n)\n print(cumulative(int(n)))\n else:\n break\n\n'''\n\n\n'''\n这里在值为100000000的测试时,超时,运算时间过长\nsum = 0\nn = eval(input())\n\nif n <= 1 :\n print(n)\nelif n > 1000000000:\n pass\nelse:\n for n in range(n,0,-1):\n sum += n\n print(sum)\n\n'''\n\n\n#这里直接用了高斯算法\nn = eval(input())\nsum_n = ( n + 1) * n / 2\nprint(int(sum_n))\n\n \n","sub_path":"蓝桥杯测试题/入门级/BEGIN-2.py","file_name":"BEGIN-2.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"551315483","text":"# MFNN 4 LAYERED\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport xlrd\nfrom pandas import DataFrame\nfrom numpy.linalg import inv\nimport math\nfrom sklearn.cross_validation import train_test_split\ndef find_max(x):\n index = 0\n maxi = x[index]\n for i in range(len(x)):\n if x[i]>maxi:\n maxi = x[i]\n index = i\n return index\n\ndef sigmoid(x):\n temp = 1.0 + np.exp(-x)\n return (1.0/temp)\n\ndef main():\n data = pd.read_excel('dataset.xlsx')\n var1 = data['row1']\n var2 = data['row2']\n var3 = data['row3']\n var4 = data['row4']\n var5 = data['row5']\n var6 = data['row6']\n var7 = data['row7']\n y = data['row8']\n x = []\n for i in data.index:\n temp = []\n # temp.append(1)\n temp.append(var1[i])\n temp.append(var2[i])\n temp.append(var3[i])\n temp.append(var4[i])\n temp.append(var5[i])\n temp.append(var6[i])\n temp.append(var7[i])\n x.append(temp)\n\n x = np.array(x)\n y = np.array(y)\n # x = sigmoid(x)\n # normalizing the data\n mean = np.sum(x,axis = 0)/len(x)\n variance = (np.sum((x - mean)**2,axis = 0))/len(x)\n x = (x - mean)/variance\n xtra, xte, ytr, yte = train_test_split(x, y, train_size=0.7)\n # print(sigmoid(xtra))\n nhid1 = 8\n nhid2 = 6\n nout = 3\n # print(len(xtra[0]))\n yt = []\n for i in range(len(ytr)):\n if ytr[i] == 1: yt.append([1, 0, 0])\n elif ytr[i] == 2: yt.append([0, 1, 0])\n else: yt.append([0, 0, 1])\n\n wl1 = np.zeros((nhid1, len(xtra[0])))\n wl2 = np.zeros((nhid2, nhid1))\n wl3 = np.zeros((nout, nhid2))\n b1 = np.zeros(nhid1)\n b2 = np.zeros(nhid2)\n b3 = np.zeros(nout)\n yt = np.array(yt)\n eta = 0.1\n iteration = 1000\n cost = np.zeros(iteration)\n cost_test = np.zeros(iteration)\n for ite in range(iteration):\n for m in range(len(xtra)):\n out0 = xtra[m]\n out1 = sigmoid(np.matmul(out0, wl1.T)+b1)\n out2 = sigmoid(np.matmul(out1, wl2.T)+b2)\n out3 = sigmoid(np.matmul(out2, wl3.T)+b3)\n\n delta3 = (yt[m]-out3)*out3*(1-out3)\n delta2 = np.matmul(delta3, wl3)*out2*(1-out2)\n delta1 = np.matmul(delta2, wl2)*out1*(1-out1)\n\n wl3 = wl3 + eta*np.outer(delta3, out2)\n b3 = b3 + eta*delta3\n wl2 = wl2 + eta*np.outer(delta2, out1)\n b2 = b2 + eta*delta2\n wl1 = wl1 + eta*np.outer(delta1, out0)\n b1 = b1 + eta*delta1\n cost[ite] += np.sum((yt[m]-out3)**2)\n\n # print(wl1)\n # print(wl2)\n # testing the data\n # accuracy is the objective function\n cnt = 0\n tot = 0\n for m in range(len(xte)):\n out0 = xte[m]\n out1 = sigmoid(np.matmul(out0, wl1.T)+b1)\n out2 = sigmoid(np.matmul(out1, wl2.T)+b2)\n out3 = sigmoid(np.matmul(out2, wl3.T)+b3)\n cost_test[ite] += np.sum((yte[m]-out3)**2)\n ind = find_max(out3)+1\n if ind==yte[m] : cnt+=1\n tot+=1\n\n cost /= len(xtra)\n cost_test /= len(xte)\n plt.plot(range(iteration), cost)\n # plt.plot(range(iteration), cost_test)\n plt.show()\n\n print('Accuracy : ')\n print(cnt/tot)\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"assignment2/q3.py","file_name":"q3.py","file_ext":"py","file_size_in_byte":3314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"615335088","text":"import inspect\nimport json\nimport os\n\nimport fastjsonschema\n\nfrom simpleruleengine.utils.type_util import is_dict\n\n\nclass SchemaReader:\n def __init__(self, *, schema_file_name: str):\n self.schema_file_name = schema_file_name\n self._schema = {}\n self.__read_schema_file()\n\n def __read_schema_file(self):\n cwd = os.path.dirname(os.path.abspath(inspect.stack()[0][1]))\n path = cwd + \"/repo/\" + self.schema_file_name + \".json\"\n with open(path) as f:\n self._schema = json.load(f)\n\n def schema(self):\n return self._schema\n\n def validate_json_data(self, json_data: dict):\n if not is_dict(json_data):\n raise ValueError(\"Only Dict allowed\")\n return fastjsonschema.compile(self._schema)(json_data)\n","sub_path":"simpleruleengine/schema/SchemaReader.py","file_name":"SchemaReader.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"265709906","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 21 14:25:38 2019\n\n@author: DVyshenska\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\nimport pandas as pd\n#import numpy as np\nfrom os import chdir, getcwd, listdir\n#import math\nwd=getcwd()\nchdir(wd)\n\n#%% FUNCTIONS\n\ndef files_list_f(pat_match, folder_path):\n return [f for f in listdir(folder_path) if pat_match in f]\n\ndef file_id_f(f_name, pat_name, pat_ext):\n return f_name.replace(pat_name, \"\").replace(pat_ext, \"\")\n#%% VARIABLES\n\nspikin_path = \"./spikin_stats_files/\"\nsumm_file_path = \"./summary_files/Summary.Lib.Info_updated.csv\"\nmap_path = \"./map_stats_files/\"\n\n#%%\n\nlib_info = pd.read_csv(summ_file_path)\nlib_info['RQC_Seq_Unit_Name'].replace(regex=True,inplace=True,\n to_replace=r'.fastq.gz', value=r'')\n\n\nspkn_col_names=[\"total_all_reads\",\n\"total_spkn_reads\",\n\"Batch146B_p061_GC-50.8_13Clabel-57.2\",\n\"Batch146B_p060_GC-50.5_13Clabel-42.9\",\n\"Batch146B_p059_GC-48.9_13Clabel-14.3\",\n\"Batch146B_p063_GC-51.1_13Clabel-71.5\",\n\"Batch146B_p058_GC-49.7_13Clabel-28.6\",\n\"Batch146B_p056_GC-52.3_13Clabel-100\",\n\"Batch146B_p057_GC-47.7_13Clabel-0\",\n\"Batch146B_p064_GC-51.8_13Clabel-85.8\",\n\"pSET152_GC-63_13Clabel-100\",\n\"pW5Y-AprR_GC-37_13Clabel-0\",\n\"pputida_assigned_reads\",\n\"ecoli_assigned_reads\"]\n\n\nlib_info_updated = lib_info.reindex(columns = lib_info.columns.tolist() + \\\n spkn_col_names)\nlib_info_updated.set_index('RQC_Seq_Unit_Name', inplace=True)\n\nfor file_name in files_list_f(\"stats_\", spikin_path):\n file_id = file_id_f(file_name, \"stats_\", \".txt\")\n \n fileH = open(spikin_path + file_name, \"r\")\n for l in fileH:\n if \"Total\" in l:\n lib_info_updated.loc[file_id,\"total_all_reads\"]=int(l.split('\\t')[1])\n elif \"Matched\" in l:\n lib_info_updated.loc[file_id,\"total_spkn_reads\"]=int(l.split('\\t')[1])\n for s in spkn_col_names[2:]:\n if s in l:\n lib_info_updated.loc[file_id,s]=int(l.split('\\t')[1])\n fileH.close()\n\n#lib_info_updated.to_csv(\"summary_out_SP.csv\")\n\nlib_info_updated.fillna(0,inplace=True)\nfor file_name_m in files_list_f(\"mapstats_\", map_path):\n file_id_m = file_id_f(file_name_m, \"mapstats_\", \".txt\")\n temp_t = pd.read_csv(map_path + file_name_m, sep=\"\\t\")\n temp_t.set_index('#name', inplace=True)\n lib_info_updated.loc[file_id_m,\"pputida_assigned_reads\"] = int(temp_t.loc['pputida', 'assignedReads'])\n lib_info_updated.loc[file_id_m,\"ecoli_assigned_reads\"] = int(temp_t.loc['ecoli', 'assignedReads'])\n\nlib_info_updated.to_csv(\"summary_out_wd.csv\")\nprint(\"DONE!\\n\")\n","sub_path":"spikein_sammary.py","file_name":"spikein_sammary.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"375659984","text":"from gba.tests.functional_tests.base import FunctionalTest\n\n\nclass HomePageTest(FunctionalTest):\n\n def test_home_page(self):\n # A user goes to the site and is greeted with the home page\n self.browser.get(self.live_server_url)\n\n self.assertIn('Gasser Bush Associates', self.browser.title)\n self.find_el_by_id('gba-logo')\n self.find_el_by_id('main-navigation')\n\n self.fail('finish the test!')\n\n\n","sub_path":"gba/tests/functional_tests/test_home_page.py","file_name":"test_home_page.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"312076397","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 23 13:37:10 2020\n\n@author: pi\n\"\"\"\n\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 16 17:00:06 2020\n\n@author: pi\n\"\"\"\n\n\"\"\"\nimport os\n\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\nserver = app.server\n\napp.layout = html.Div([\n html.H2('Hello World'),\n dcc.Dropdown(\n id='dropdown',\n options=[{'label': i, 'value': i} for i in ['LA', 'NYC', 'MTL']],\n value='LA'\n ),\n html.Div(id='display-value')\n])\n\n@app.callback(dash.dependencies.Output('display-value', 'children'),\n [dash.dependencies.Input('dropdown', 'value')])\ndef display_value(value):\n return 'You have selected \"{}\"'.format(value)\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n #app.server.run(port=8000, host='127.0.0.1')\n\n# -*- coding: utf-8 -*-\n \"\"\"\n\"\"\"\nCreated on Sun Jul 12 12:27:33 2020\n\n@author: e142133\n\"\"\"\n#!pip install chart_studio\n\nimport spotipy\nfrom spotipy.oauth2 import SpotifyClientCredentials\nimport pandas as pd\nfrom pandas import DataFrame, read_excel\nfrom pandas import ExcelWriter\nimport requests\nimport time\nfrom bs4 import BeautifulSoup\nimport base64\nimport json\n#from secrets import *\n#import json\nimport ast\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport plotly.io as pio\nfrom plotly.subplots import make_subplots\npio.renderers.default='browser'\nimport datetime\nimport re\nimport os\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport chart_studio\nimport chart_studio.plotly as py\nimport numpy as np\n\n\"\"\"\nADD TIMESTAMP TO GEOGRAPHIC LISTENERS AND APPEND ALL\nadd change over time sliders\nset to run at a certain time\nset map bubbles to a certain color depending on amount of listeners increase in period\n\"\"\"\n\ntimestamp = datetime.datetime.now()\nweekday = (datetime.datetime.today().weekday()) #4 = Friday\nprint(timestamp)\n\nfrom datetime import datetime\n\n#-------FILES FILES FILES -----------------------------------------------------\n#os.path.join(base_dir, filename)\n\nbase_dir = '/home/pi/Desktop/Python Scripts/Spotify'\nall_geo_file = os.path.join(base_dir, 'All Geographic Listeners.xlsx')\nall_stats_file = os.path.join(base_dir, 'All General Stats.xlsx')\nall_youtube_file = os.path.join(base_dir, 'All Youtube.xlsx')\ncurrent_youtube_file = os.path.join(base_dir,'Current Youtube.xlsx')\nworld_cities_file = os.path.join(base_dir,'worldcities.xlsx')\n\n#--------SPOTIFY API FOR TRACK FEATURES THROUGH SPOTIPY (\"SP\")---------------------------------\ncid = '38a89765637f43dbb7c6cce35637daff'\nsecret = '9b263812668740268d60c728a3727347'\nclient_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret)\nsp = spotipy.Spotify(client_credentials_manager\n=\nclient_credentials_manager)\n\njohnny = '00OF0nwYaoBSO3AnPVq3vE'\njohnny_uri = 'spotify:artist:00OF0nwYaoBSO3AnPVq3vE'\nprint(\"Accessing Spotify...\")\n\n#-------Get Track List from Complete Playlist\n\ndef getPlaylistTrackIDs(user, playlist_id):\n ids = []\n playlist = sp.user_playlist(user, playlist_id)\n for item in playlist['tracks']['items']:\n track = item['track']\n ids.append(track['id'])\n return ids\n\nids = getPlaylistTrackIDs('johnny stimson', '1Teioad4fKoVjuSwGQW3P9?si=2zvXvzURTeKRHjAw4t2_zg') # Johnny Complete\nct_songs = len(ids)\n\n#------Get Track Features\n#https://unboxed-analytics.com/data-technology/analyzing-drakes-catalog-using-spotifys-api/\nprint(\"Getting track features...\")\n\ndef getTrackFeatures(id):\n meta = sp.track(id)\n features = sp.audio_features(id)\n \n # Meta\n name = meta['name']\n album = meta['album']['name']\n artist = meta['album']['artists'][0]['name']\n release_date = meta['album']['release_date']\n length = meta['duration_ms']\n popularity = meta['popularity']\n\n # Features\n acousticness = features[0]['acousticness']\n danceability = features[0]['danceability']\n energy = features[0]['energy']\n instrumentalness = features[0]['instrumentalness']\n liveness = features[0]['liveness']\n loudness = features[0]['loudness']\n speechiness = features[0]['speechiness']\n tempo = features[0]['tempo']\n time_signature = features[0]['time_signature']\n\n track = [name, album, artist, release_date, length, popularity, acousticness, danceability, energy, instrumentalness, liveness, loudness, speechiness, tempo, time_signature]\n return track\n \ntracks = []\nfor i in range(0, ct_songs):\n time.sleep(.5)\n track = getTrackFeatures(ids[i])\n tracks.append(track)\n \njohnny_songs = pd.DataFrame(data=tracks,\n index=None,\n columns=['name', 'album', 'artist', 'release_date', 'length', 'popularity', 'acousticness', 'danceability', 'energy', 'instrumentalness', 'liveness', 'loudness', 'speechiness', 'tempo','time_signature'],\n dtype=None,\n copy=False)\n\nprint(\"Visualizing track features...\")\n\njohnny_songs_radar = johnny_songs.drop(columns=['name','album','artist','release_date','tempo','time_signature','instrumentalness'])\n\njohnny_songs_radar['length'] = johnny_songs['length']/max(johnny_songs['length'])\njohnny_songs_radar['loudness'] = johnny_songs['loudness']/min(johnny_songs['loudness'])\njohnny_songs_radar['popularity'] = johnny_songs['popularity']/max(johnny_songs['popularity'])\n#johnny_songs = johnny_songs.set_index(['name','album','artist','release_date'])\n #(columns=['tempo','time_signature','instrumentalness'])\n\njohnny_songs_radar.head(5)\n\ncategories = ['length', 'popularity', 'acousticness', 'danceability', 'energy', 'liveness', 'loudness', 'speechiness']\n\n\nradar = go.Figure()\n\nfor i in range(ct_songs):\n radar.add_trace(\n go.Scatterpolar( \n r=johnny_songs_radar.loc[i].values,\n #theta=johnny_songs.columns,\n theta=categories,\n fill='toself',\n name=johnny_songs['name'].loc[i],\n #name=\"Johnny-%s\"%wine.target_names[i],\n showlegend=True\n )\n )\n\nradar.update_layout(\n polar=dict(\n radialaxis=dict(\n visible=True,\n range=[0, 1]\n )\n ),\n title=\"Tracks by Features\",\n margin=dict(l=20, r=20, t=40, b=20)\n)\n\n#radar.show()\n\n##ADD FILTER AND/OR SLIDER\n \n#----------GET ARTIST USING SPOTIFY API-----------------------------------------------\n#--Spotify SDK Access Token Using My Client/Secret IDs\n\nprint(\"Getting Spotify artist...\")\n# Step 1 - Authorization\nurl = \"https://accounts.spotify.com/api/token\"\nheaders = {}\ndata = {}\n\n# Encode as Base64\nmessage = f\"38a89765637f43dbb7c6cce35637daff:9b263812668740268d60c728a3727347\"\nmessageBytes = message.encode('ascii')\nbase64Bytes = base64.b64encode(messageBytes)\nbase64Message = base64Bytes.decode('ascii')\n\n\nheaders['Authorization'] = f\"Basic {base64Message}\"\ndata['grant_type'] = \"client_credentials\"\n\nr = requests.post(url, headers=headers, data=data)\n\ntoken = r.json()['access_token']\n\n# Step 2 - Use Access Token to call ARTIST endpoint\n\nartistUrl = f\"https://api.spotify.com/v1/artists/00OF0nwYaoBSO3AnPVq3vE\"\nheaders = {\n \"Authorization\": \"Bearer \" + token\n}\n\nres = requests.get(url=artistUrl, headers=headers)\n\nartist = json.dumps(res.json(), indent=2) #json\nartist = json.loads(artist) #parse\njohnny_popularity = (artist['popularity'])\njohnny_followers = (artist['followers'])\njohnny_followers = johnny_followers['total']\n\n\n#----------SCRAPE MONTHLY SPOTIFY LISTENERS-----------------------------------------------\nprint(\"Scraping monthly listeners...\")\nuser_agent_desktop = 'Chrome/80.0.3987.149 '\nheaders = { 'User-Agent': user_agent_desktop}\npage = requests.get(\"https://open.spotify.com/artist/00OF0nwYaoBSO3AnPVq3vE\", headers=headers)\nsoup = BeautifulSoup(page.content, 'html.parser')\n\n#print(soup.prettify())\ntext2 = soup.get_text()\nsearch_key = \"u00B7\"\nlength = len(search_key)\nposition_of_first_letter_key = text2.find(search_key) #29125\nposition_of_last_letter_key = position_of_first_letter_key + length\nnext_comma = position_of_last_letter_key + text2[position_of_last_letter_key:position_of_last_letter_key+50].find(\"K\")\nmonthly_listeners = text2[position_of_last_letter_key:next_comma] \nmonthly_listeners = int(float(monthly_listeners) * 1000)\n\n\nprint(\"Scraping geographic listeners\") #Using a weirdly different process from monthly listeners, bc they're somehow different\npage = requests.get(\"https://open.spotify.com/artist/00OF0nwYaoBSO3AnPVq3vE\")\nsoup = BeautifulSoup(page.content, 'html.parser')\n\n\n#print(soup.prettify())\ntext1 = soup.get_text()\n\"\"\"\nsearch_key = \"monthly_listeners\"\nlength = len(search_key)\nposition_of_first_letter_key = text1.find(search_key) #29125\nposition_of_last_letter_key = position_of_first_letter_key + length\nnext_comma = position_of_last_letter_key + text1[position_of_last_letter_key:position_of_last_letter_key+50].find(\",\")\nmonthly_listeners = text1[position_of_last_letter_key + 2:next_comma] #+2 for \": in \"monthy_listeners\": 792854...\n\"\"\"\n\n#Geographic Spotify listeners\nsearch_key = \"cities\"\nlast_separator = \"};\"\nlength = len(search_key)\nposition_of_first_letter_key = text1.find(search_key)\nposition_of_last_letter_key = position_of_first_letter_key + length\nposition_of_last_separator = position_of_last_letter_key + text1[position_of_last_letter_key:position_of_last_letter_key+5000].find(last_separator)\ngeographic_listeners = text1[position_of_last_letter_key + 2:position_of_last_separator-1] #+2 for \": in \"monthy_listeners\": 792854...\n#geographic_listeners = ast.literal_eval(geographic_listeners)\ngeographic_listeners = json.loads(geographic_listeners)\n#geographic_listeners = eval(geographic_listeners)\ngeographic_listeners = pd.DataFrame(geographic_listeners)\ngeographic_listeners['country_code'] = geographic_listeners['country']\ngeographic_listeners['timestamp'] = timestamp\n\n#import WorldCities and merge with geographic listeners\nworldCities = pd.read_excel(world_cities_file)\nworldCities['country_code'] = worldCities['iso2']\nworldCities.head(10)\n\nkeys = [\n \"country_code\",\n \"city\"]\ngeographic_listeners_lat_long = geographic_listeners.merge(worldCities, on= keys, how='left')\ngeographic_listeners_lat_long['text'] = geographic_listeners_lat_long['listeners'].astype(str) + (\" listeners \\n\") + geographic_listeners_lat_long['city'] + \", \" + geographic_listeners_lat_long['country_code']\n\n#Combine with historic geographic listeners info\nall_geographic_listeners_lat_long = pd.read_excel(all_geo_file) \nall_geographic_listeners_lat_long = all_geographic_listeners_lat_long.append(geographic_listeners_lat_long)\n\n#Drop unnamed columns\ndrop_cols = [col for col in all_geographic_listeners_lat_long.columns if 'Unnamed' in col]\nall_geographic_listeners_lat_long.drop(columns=drop_cols, inplace=True) \nall_geographic_listeners_lat_long.to_excel(all_geo_file)\n\n#starter groupby for later, so you can show emerging change/time bubbles\n#pivot2 = all_geographic_listeners_lat_long.groupby(by=[\"city\",\"timestamp\"], dropna=False).sum()\n \n\n#Build Geogarphic map\nprint(\"Visualizing geographic audience...\")\n\ngeographic_map = go.Figure(data=go.Scattergeo(\n lon = geographic_listeners_lat_long['lng'],\n lat = geographic_listeners_lat_long['lat'],\n text = geographic_listeners_lat_long['text'],\n mode = 'markers',\n marker=dict(\n color = 'LightSkyBlue',\n size = geographic_listeners_lat_long['listeners']/500)\n #opacity=0.5)\n #marker_color = df['cnt'],\n ))\n#geographic_map.show()\n \ngeographic_map.update_layout(title=\"Global Spotify Listeners\", margin=dict(l=20, r=20, t=40, b=20))\n \n#----------INSTAGRAM-----------------------------------------------------------\n#ADD \"liked\" etc. which is all searchable in the text\nprint(\"Scraping Instagram followers...\")\npage = requests.get(\"https://www.instagram.com/johnnystimson/\")\nsoup = BeautifulSoup(page.content, 'html.parser')\n#print(soup)\ntext = soup.get_text()\nlength = len(text)\n\n#get followers\nfoll = \"edge_followed_by\"\nfollowers_index = int(text.find(foll)) \nfollowers = text[followers_index:followers_index + 100]\nfollowers = followers.split(\"count\\\":\")\nfollowers = followers[1]\nfollowers = followers.split(\"}\")\nfollowers = followers[0]\n\n#----------YOUTUBE-------------------------------------------------------------\nprint(\"Scraping YouTube...\")\npage = requests.get(\"https://www.youtube.com/c/johnnystimson/videos\")\nsoup = BeautifulSoup(page.content, 'html.parser')\n#print(soup)\ntext = soup.get_text()\ntext = text.replace(u'—\\xa0', u'- ')\nlength = len(text)\n\n#get subscribers\nsubsc = \"subscribers\"\nsubscribers_index = int(text.find(subsc)) \nsubscribers = text[subscribers_index - 100:subscribers_index]\nsubscribers = subscribers.split(\"\\\"\")\nsubscribers = subscribers[len(subscribers) - 1]\nsubscribers = subscribers[:-2]\nsubscribers = int(float(subscribers)*1000)\n\n#GET VIDEO FEATURES\nstart_search = \"Johnny Stimson -\"\nend_search = \"views\"\n \n# using re.finditer()\n# All occurrences of first substring in string - Johnny\nstart_key = [i.start() for i in re.finditer(start_search, text)] \nstart_key = [int(i) for i in start_key]\n\n#Find ALL occurences of second substring in string (VIEWS)\nend_key = [i.start() for i in re.finditer(end_search, text)]\nend_key = [int(i) for i in end_key]\n\n#Find NEXT occurence of second substring in string\nnext_key = []\ndrop_starts = [] #iterations of \"Johnny\" for which no \"views\" follows\nfor i,val in enumerate(start_key):\n filtered_numbers = [x for x in end_key if x > val]\n while True:\n try:\n next = min(filtered_numbers)\n next_key.append(next)\n break\n except ValueError:\n next_key.append(length)\n break\n \n \n#DataFrame that ish\nyoutube = pd.DataFrame({'Start':start_key,'Next':next_key})\nyoutube['Start'] = pd.to_numeric(youtube['Start'])\nyoutube['Next'] = pd.to_numeric(youtube['Next'])\nyoutube['String'] = \"\"\n\nstring = []\nfor index, row in youtube.iterrows():\n s = row['Start']\n e = row['Next']\n ranger = slice(s,e)\n string.append(text[ranger])\n\nyoutube['String'] = string\n\nyoutube = youtube[~youtube.String.str.contains(\"}]\")]\n\nyoutube['String'] = youtube['String'].str.split(\" \")\nyoutube['String'].replace('—\\xa0Pink','- Pink')\nyoutube['Song'] = \"\"\nyoutube['Days Ago'] = \"\"\nyoutube['Weeks Ago'] = \"\"\nyoutube['Months Ago'] = \"\"\nyoutube['Years Ago'] = \"\"\nyears = []\nmonths = []\nweeks = []\ndays = []\nsongs = []\nviews = []\n\nfor index, row in youtube.iterrows():\n string = row['String']\n string = string[3:]\n #print(string)\n by = string.index('by')\n lenStr = len(string)\n song = ' '.join(string[:by])\n view = string[lenStr - 2]\n try:\n year_past = string[string.index('year') - 1]\n except ValueError:\n try:\n year_past = string[string.index('years') - 1]\n except ValueError:\n year_past = 0\n try:\n month_past = string[string.index('month') - 1]\n except ValueError:\n try:\n month_past = string[string.index('months') - 1]\n except ValueError:\n month_past = 0\n try:\n week_past = string[string.index('week') - 1]\n except ValueError:\n try:\n week_past = string[string.index('weeks') - 1]\n except ValueError:\n week_past = 0\n try:\n day_past = string[string.index('day') - 1]\n except ValueError:\n try:\n day_past = string[string.index('day') - 1]\n except ValueError:\n day_past = 0\n views.append(view)\n years.append(year_past)\n months.append(month_past)\n weeks.append(week_past)\n days.append(day_past)\n songs.append(song)\n \n\nyoutube['Years Ago'] = years\nyoutube['Months Ago'] = months\nyoutube['Weeks Ago'] = weeks\nyoutube['Days Ago'] = days\nyoutube['Song'] = songs\nyoutube['Views'] = views\nyoutube['timestamp'] = timestamp\n\n#SAVE to Excel and Import Youtube History\nprint(\"Saving YouTube details to Excel...\")\nAllYoutube = pd.read_excel(all_youtube_file)\nAllYoutube = AllYoutube.append(youtube)\n#Drop unnamed columns\ndrop_cols = [col for col in AllYoutube.columns if 'Unnamed' in col]\nAllYoutube.drop(columns=drop_cols, inplace=True) \n#to_excel\nAllYoutube.to_excel(all_youtube_file)\n\n#------------------------------------------------------------------------------\n#-----------CURRENT STATS DATAFRAME-----------------------------------------------------------------\nprint(\"Storing statistics...\")\njohnny_current_stats = pd.DataFrame()\njohnny_current_stats['timestamp'] = [timestamp]\njohnny_current_stats['spotify popularity'] = [johnny_popularity]\njohnny_current_stats['spotify followers'] = [johnny_followers]\njohnny_current_stats['spotify monthly_listeners'] = [monthly_listeners]\njohnny_current_stats['youtube subscribers'] = [subscribers]\njohnny_current_stats['instagram followers'] = [followers]\n\njohnny_all_stats = pd.read_excel(all_stats_file)\njohnny_all_stats = johnny_all_stats.append(johnny_current_stats)\n#Drop unnamed columns\ndrop_cols = [col for col in johnny_all_stats.columns if 'Unnamed' in col]\njohnny_all_stats.drop(columns=drop_cols, inplace=True) \njohnny_all_stats2 = johnny_all_stats.set_index('timestamp')\njohnny_all_stats2.index = pd.to_datetime(johnny_all_stats2.index)\njohnny_all_stats2 = johnny_all_stats2.dropna().astype(int)\n#to_excel\njohnny_all_stats.to_excel(all_stats_file)\n\n#-----------ALL STATS GRAPH---------------------------------------------------------\nprint(\"Visualizing general stats...\")\n\n\n#--Prepping Line of Best Fit Data\ngoal = 1000000\ngoal_formatted = \"{:,}\".format(goal)\n\njohnny_all_stats2['numeric_date'] = johnny_all_stats2.index.to_julian_date()\n\nX = johnny_all_stats2['numeric_date']\nY = johnny_all_stats2['spotify monthly_listeners']\nm, b = np.polyfit(X,Y,1)\njohnny_all_stats2['monthly_listeners_best_fit'] = johnny_all_stats2['numeric_date']*m + b\n\ngoal_x = ((goal - b ) / m)\ngoal_date = pd.to_datetime(goal_x, unit='D', origin = 'julian')\ngoal_date = goal_date.strftime(\"%b %-d, %Y at %-I:%M %p\")\nyay = \"Johnny is set to reach %s monthly listeners on %s!!\" % (goal_formatted, goal_date)\nprint(yay)\n\n#Visualizing Line Charts\n\nline = make_subplots(rows = 2, cols=1, shared_xaxes=True,vertical_spacing=0.02)\n\nline.add_trace(\n go.Scatter(x=johnny_all_stats2.index, y=johnny_all_stats2['spotify monthly_listeners'], mode=\"lines+markers\", name=\"Spotify Monthly Listeners\"),\n row=1,col=1)\n\nline.add_trace(\n go.Scatter(x=johnny_all_stats2.index, y=johnny_all_stats2['monthly_listeners_best_fit'], mode='lines',name=\"Prediction of Spotify Monthly Listeners\", \n line=dict(color='silver', width=2,\n dash='dash')),\n row=1,col=1)\n\nline.add_trace(\n go.Scatter(x=johnny_all_stats2.index, y=johnny_all_stats2['spotify followers'], mode=\"lines+markers\", name=\"Spotify Followers\"),\n row=2,col=1)\n\nline.add_trace(\n go.Scatter(x=johnny_all_stats2.index, y=johnny_all_stats2['youtube subscribers'], mode=\"lines+markers\", name=\"YouTube Subscribers\"),\n row=2,col=1)\n\nline.add_trace(\n go.Scatter(x=johnny_all_stats2.index, y=johnny_all_stats2['instagram followers'], mode=\"lines+markers\", name=\"Instagram Followers\"),\n row=2,col=1)\n\n\n# Set x-axis title\nline.update_layout(title_text=\"Social Media Hype\", margin=dict(l=20, r=20, t=40, b=20))\n\nline.show()\n\n\n\n\n##-----------PLOTLY CHART STUDIO----------------------------------------------------------------\n\"\"\"\nusername = 'marystimson' # your username\napi_key = 'NA0Aj5kRqGk4SHLraxp9' # your api key - go to profile > settings > regenerate key\nchart_studio.tools.set_credentials_file(username=username, api_key=api_key)\n\npy.plot(geographic_map, filename = 'geographic_map', auto_open=True)\npy.plot(radar, filename = 'radar', auto_open=True)\n\"\"\"\n#------------DASH---------------------------------------------------------------\\\n\n\napp = dash.Dash()\n\napp.layout = html.Div([\n html.Div([\n html.H3(\"The Official Johnny Stimson Fan Club Mega Tracking Dashboard 1.0\"),\n html.P(yay),\n dcc.Graph(id='line', figure=line, config={'displayModeBar': False}),\n ], className=\"six columns\"),\n \n html.Div(children=[\n dcc.Graph(id=\"graph1\", figure=geographic_map, config={'displayModeBar': False}, style={'display': 'inline-block'}),\n dcc.Graph(id=\"graph2\", figure=radar, config={'displayModeBar': False}, style={'display': 'inline-block'})\n ])\n])\n \n \nif __name__ == '__main__':\n app.run_server(debug=False) #debug=False makes it run a lot smoother but may throw a file descriptor error!\n#Look into hot reloading.\n \nprint(\"Success!\")\n\n#####TEST TEST TEST\n\n\n\n\"\"\"\ncolors = {\n 'background': '#111111',\n 'text': '#7FDBFF'\n}\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\napp.layout = html.Div(\n html.Div(dcc.Graph(\n id='map',\n figure=geographic_map\n ),\n html.Div(dcc.Graph(\n id='radar',\n figure=radar\n ))) \n#])\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n#------------------------------------------------------------------------------------\n\n\nstyle={'backgroundColor': colors['background']}, children=[\n html.H1(\n children='Hello Dash',\n style={\n 'textAlign': 'center',\n 'color': colors['text']\n }\n ),\n\n html.Div(children='Dash: A web application framework for Python.', style={\n 'textAlign': 'center',\n 'color': colors['text']\n }),\n\n#Geographic listeners over time slider\n#Youtube\n#size of stadium of listeners on spotify\n#Google trends see pytrends\n#Scrape number of listens per song on Spotify\n#append/track number of listeners on Spotify\n#Add/append number of Instagram likes per pic, etc.\n#The first option for calculating your Instagram engagement rate is to divide your total number of likes and comments by your follower count, and then multiply by 100 to give you a percentage.\n#Add/append Youtube views and #/subscribers /comments per pink lemonade\n\n#------------------------------------------------------------------------------\n\n#------------------------------------------------------------------------------\n#------------------------------------------------------------------------------\n#------TONS OF ARTISTS\n\nartist_name = []\ntrack_name = []\npopularity = []\ntrack_id = []\nfor i in range(0,10000,50):\n track_results = sp.search(q='year:2020', type='track', limit=50,offset=i)\n for i, t in enumerate(track_results['tracks']['items']):\n artist_name.append(t['artists'][0]['name'])\n track_name.append(t['name'])\n track_id.append(t['id'])\n popularity.append(t['popularity'])\n \nimport pandas as pd\ntrack_dataframe = pd.DataFrame({'artist_name' : artist_name, 'track_name' : track_name, 'track_id' : track_id, 'popularity' : popularity})\nprint(track_dataframe.shape)\ntrack_dataframe.head()\n\"\"\"\n#########\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":23382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"7963020","text":"# Run with Python 3\nimport json\nimport requests\n\n### DATA ENDS\n# Enter parameters below:\n# 1. Get your keys at https://stepik.org/oauth2/applications/ (client type = confidential,\n# authorization grant type = client credentials)\nclient_id = '...'\nclient_secret = '...'\napi_host = 'https://stepik.org'\n\n# 2. Get a token\nauth = requests.auth.HTTPBasicAuth(client_id, client_secret)\nresp = requests.post('https://stepik.org/oauth2/token/',\n data={'grant_type': 'client_credentials'},\n auth=auth\n )\ntoken = resp.json().get('access_token')\nif not token:\n raise RuntimeWarning('Client id/secret is probably incorrect')\n\n\n# 3. Call API (https://stepik.org/api/docs/) using this token.\ndef fetch_object(obj_class, obj_id):\n api_url = '{}/api/{}s/{}'.format(api_host, obj_class, obj_id)\n response = requests.get(api_url,\n headers={'Authorization': 'Bearer ' + token}).json()\n return response['{}s'.format(obj_class)][0]\n\n\ndef fetch_objects(obj_class, obj_ids):\n objs = []\n # Fetch objects by 30 items,\n # so we won't bump into HTTP request length limits\n step_size = 30\n for i in range(0, len(obj_ids), step_size):\n obj_ids_slice = obj_ids[i:i + step_size]\n api_url = '{}/api/{}s?{}'.format(api_host, obj_class,\n '&'.join('ids[]={}'.format(obj_id)\n for obj_id in obj_ids_slice))\n response = requests.get(api_url,\n headers={'Authorization': 'Bearer ' + token}\n ).json()\n objs += response['{}s'.format(obj_class)]\n return objs\n\n# SOMETHING MEANINGFUL:\n\ncourses = fetch_objects('course', list(range(2000)))\n\ntotal_courses = 0\ntotal_enrollments = 0\ntotal_lessons = 0\n\nfor course in courses:\n course_id = course['id']\n learners_group_id = course['learners_group']\n learners_group = fetch_object('group', learners_group_id)\n learners_count = len(learners_group['users'])\n sections = fetch_objects('section', course['sections'])\n units_count = sum(len(section['units']) for section in sections)\n lessons_count = units_count\n print(course_id, learners_count, lessons_count)\n if learners_count >= 10:\n total_courses += 1\n total_enrollments += learners_count\n total_lessons += lessons_count\n\nprint('Number of courses with >= 10 learners:', total_courses)\nprint('Total number of enrollments in such courses:', total_enrollments)\nprint('Total number of lessons in such courses:', total_lessons)","sub_path":"examples/popular_courses.py","file_name":"popular_courses.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"595589215","text":"# Copyright 2009 Fred Sauer\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy of\n# 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 under\n# the License.\n# package com.allen_sauer.gwt.dnd.client.util\n\nimport java\nfrom java import *\nfrom pyjamas.ui.RootPanel import RootPanel\nfrom pyjamas.ui.Widget import Widget\n\nfrom dnd.util.AbstractLocation import AbstractLocation\n\n\nclass WidgetLocation(AbstractLocation):\n\n \"\"\"\n Class representing the location of one widget relative to another.\n \"\"\"\n\n def __init__(self, widget, reference):\n\n \"\"\"\n Determine location of widget relative to reference,\n such that referencePanel.add(widget, location.getLeft(), location.getTop())\n leaves the widget in the exact same location on the screen. Note that\n reference need not be the parent node, or even an ancestor of\n widget. Therefore coordinates returned may be negative or may\n exceed the dimensions of reference.\n\n @param widget the widget whose coordinates we seek\n @param reference the widget relative to which we seek our coordinates\n \"\"\"\n\n self.left = 0\n self.referenceAdjustLeft = 0\n self.referenceAdjustTop = 0\n self.top = 0\n self.widgetLeft = 0\n self.widgetTop = 0\n\n AbstractLocation.__init__(self)\n\n self.internalSetWidget(widget)\n self.internalSetReference(reference)\n self.recalculate()\n\n #@java.typed(int, int, int, int)\n def constrain(self, minLeft, minTop, maxLeft, maxTop):\n \"\"\"\n Constrain the widget location to the provided minimum and maximum values.\n\n @param minLeft the minimum left value\n @param minTop the minimum top value\n @param maxLeft the maximum left value\n @param maxTop the maximum top value\n \"\"\"\n self.left = Math.max(minLeft, Math.min(self.left, maxLeft))\n self.top = Math.max(minTop, Math.min(self.top, maxTop))\n\n def getLeft(self):\n return self.left\n\n def getTop(self):\n \"\"\"\n public Widget getReference() {\n \"\"\"\n return self.top\n\n def __str__(self):\n \"\"\"\n public Widget getWidget() {\n \"\"\"\n return \"(\" + java.str(self.left) + \", \" + java.str(self.top) + \")\"\n\n #@java.typed(Widget)\n def internalSetReference(self, reference):\n # this.reference = reference;\n if reference == None or reference == RootPanel.get():\n self.referenceAdjustLeft = 0\n self.referenceAdjustTop = 0\n else:\n self.referenceAdjustLeft = \\\n reference.getAbsoluteLeft() + DOMUtil.getBorderLeft(reference.getElement())\n self.referenceAdjustTop = \\\n reference.getAbsoluteTop() + DOMUtil.getBorderTop(reference.getElement())\n\n #@java.typed(Widget)\n def internalSetWidget(self, widget):\n # this.widget = widget;\n if widget == None or widget == RootPanel.get():\n self.widgetLeft = 0\n self.widgetTop = 0\n else:\n self.widgetLeft = widget.getAbsoluteLeft() - widget.getElement().getScrollLeft()\n self.widgetTop = widget.getAbsoluteTop() - widget.getElement().getScrollTop()\n\n def recalculate(self):\n self.left = self.widgetLeft - self.referenceAdjustLeft\n self.top = self.widgetTop - self.referenceAdjustTop","sub_path":"dnd/util/WidgetLocation.py","file_name":"WidgetLocation.py","file_ext":"py","file_size_in_byte":3860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"616760246","text":"from selenium import webdriver \nfrom optparse import OptionParser\nfrom selenium.webdriver.chrome.options import Options\nimport urllib\nimport requests\nimport os, sys\n\nURL_LOCATE_PREX = \"https://www.aitaotu.com/guonei/\"\nDEST_ROOT = \"/Users/ddk/Downloads/img/\"\n\ndef download(serial):\n chrome_options = Options()\n chrome_options.add_argument(\"--headless\")\n chrome_options.add_argument(\"--window-size=1920,1080\")\n driver = webdriver.Chrome(executable_path=\"/usr/local/chromedriver\", chrome_options=chrome_options)\n\n dest_path = DEST_ROOT + serial\n if not os.path.exists(dest_path): \n os.mkdir(dest_path)\n \n url_local = URL_LOCATE_PREX + serial + \".html\"\n driver.get(url_local)\n print(\"get path: \" + url_local)\n\n total = int(driver.find_element_by_class_name(\"totalpage\").text)\n\n section = driver.find_elements_by_xpath(\"//div[@id='big-pic']/p/a/img\")\n section_size = len(section)\n \n url_img = driver.find_element_by_xpath(\"//div[@id='big-pic']/p/a/img\").get_attribute(\"src\")\n url_img_prex = url_img[0:url_img.rfind(\"/\")+1]\n\n print( \"total: \" + str(total) )\n print( \"section: \" + str(section_size) )\n print( \"img_prex: \" + url_img_prex )\n\n img_index = 1\n for i in range(1, total + 1):\n if i != 1:\n url_local = URL_LOCATE_PREX + serial + \"_\" + str(i) + \".html\"\n driver.get(url_local)\n for j in range(0, section_size): \n url_img = url_img_prex + \"{:0>2d}\".format(img_index) + \".jpg\"\n driver.get(url_img)\n img_file = dest_path + \"/\" + str(img_index) + \".png\"\n driver.save_screenshot(img_file)\n print(\"save img as \" + img_file)\n img_index = img_index + 1\n driver.close()\n\nSIZE = len(sys.argv)\nfor index in range(1, SIZE):\n download(sys.argv[index])\n","sub_path":"down.py","file_name":"down.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"247996977","text":"\"\"\"\ntype创建带有继承关系的类\n\"\"\"\n\n\nclass Demo06(object):\n def __init__(self):\n self.j = \"jjj\"\n self.k = \"kkk\"\n\n def demo06(self):\n print(\"demo06\")\n\n\nclass Demo08(object):\n def __init__(self):\n self.n = \"nnn\"\n self.o = \"ooo\"\n\n def show08(self):\n print(\"demo08\")\n\n\nDemo07 = type(\"Demo07\", (Demo06,), {\"m\": \"mmm\"})\n\ndemo07 = Demo07()\nprint(demo07.j)\nprint(demo07.k)\nprint(demo07.m)\n\n\nprint(\"*\" * 20)\n\nDemo09 = type(\"Demo09\", (Demo06, Demo08), {\"m\": \"mmm\", })\n\ndemo09 = Demo09()\nprint(demo09.j)\nprint(demo09.k)\nprint(demo09.m)\n\n# print(demo09.n)\n# print(demo09.o)\n","sub_path":"千峰的每天/第十二天12.26/代码/Day12/04.type创建带有继承关系的类.py","file_name":"04.type创建带有继承关系的类.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"204112660","text":"def is_palindrome(string):\n backwards = string[::-1].casefold()\n return backwards == string.casefold()\n\n\ndef palindrome_sentence(sentence):\n string = \"\"\n for char in sentence:\n if char.isalnum():\n string += char\n print(string)\n #return string [::-1].casefold() == string.casefold()\n return is_palindrome(string)\n\n\nsentence = input(\"Please enter a sentence to check: \")\nif palindrome_sentence(sentence):\n print(\"'{}' is a palindrome\".format(sentence))\nelse:\n print(\"'{}' is not a palindrome\".format(sentence))\n\n","sub_path":"palindrome_sentence_challenge.py","file_name":"palindrome_sentence_challenge.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"91700741","text":"import json\nimport logging\nfrom time import sleep\nfrom typing import Dict, List\n\nfrom shared.utils import send_message, WorkError\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n\nWORKER = 'worker3'\n\n\ndef perform_work(bucket: str, key: str, args: List):\n sleep(2)\n raise WorkError(\"Simulate a failure in this lambda!\")\n\n\ndef lambda_handler(event: Dict, context: Dict):\n records = event.get('Records')\n if not records:\n logger.error(\"Invalid message!\")\n return\n\n for record in records:\n sns = record.get('Sns')\n\n if sns is not None:\n message = sns.get('Message')\n try:\n msg = json.loads(message)\n except (TypeError, ValueError) as e:\n logger.error(\"Invalid message, must be JSON!\")\n return\n\n msg_type = msg.get('type')\n from_ = msg.get('from')\n\n logger.info(f\"Handling message from {from_}: {msg}\")\n\n if msg_type == 'StartJob' and from_ == 'controller':\n bucket = msg.get('bucket')\n key = msg.get('key')\n args = msg.get('args')\n\n try:\n perform_work(bucket, key, args)\n result = 'Passed'\n except WorkError as e:\n logger.error(str(e))\n result = 'Failed'\n\n send_message(WORKER, 'controller', 'JobCompleted',\n {'bucket': bucket,\n 'key': key,\n 'result': result})\n","sub_path":"worker3/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"429909503","text":"import tensorflow as tf\nimport get_img_from_TFRecords\nimg, label = get_img_from_TFRecords.read_and_decode(\"train.tfrecords5\")\n\n#使用shuffle_batch可以随机打乱输入\nimg_batch, label_batch = tf.train.shuffle_batch([img, label],\n batch_size=30, capacity=200,\n min_after_dequeue=100,num_threads=3)\ninit = tf.initialize_all_variables()\n\nwith tf.Session() as sess:\n sess.run(init)\n threads = tf.train.start_queue_runners(sess=sess)\n for i in range(3):\n print(i)\n val, l= sess.run([img_batch, label_batch])\n #我们也可以根据需要对val, l进行处理\n #l = to_categorical(l, 12)\n print(val.shape, l)\n","sub_path":"tes_tfRecords.py","file_name":"tes_tfRecords.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"540975497","text":"#!/usr/bin/env python3\n\nimport sys\nfrom aiida import load_profile\nfrom aiida.plugins import DataFactory\nfrom aiida.orm import Code\nfrom aiida.engine import submit\nfrom mpds_aiida.workflows.crystal import MPDSCrystalWorkchain\nfrom mpds_aiida.common import get_template\n\nload_profile()\ncalc_setup = get_template('production.yml')\nphase = sys.argv[1].split(\"/\")\n\nif len(phase) == 3:\n formula, sgs, pearson = phase\nelse:\n formula, sgs, pearson = phase[0], phase[1], None\n\nsgs = int(sgs)\ncalc_setup['parameters']['crystal']['title'] = \"/\".join(phase)\n\ninputs = MPDSCrystalWorkchain.get_builder()\ninputs.crystal_code = Code.get_from_string('{}@{}'.format(calc_setup['codes'][0], calc_setup['cluster']))\ninputs.crystal_parameters = DataFactory('dict')(dict=calc_setup['parameters']['crystal'])\ninputs.basis_family, _ = DataFactory('crystal_dft.basis_family').get_or_create(calc_setup['basis_family'])\ninputs.options = DataFactory('dict')(dict=calc_setup['options'])\n\ninputs.metadata = dict(label=\"/\".join(phase))\ninputs.mpds_query = DataFactory('dict')(dict={'formulae': formula, 'sgs': sgs})\nwc = submit(MPDSCrystalWorkchain, **inputs)\nprint(\"Submitted WorkChain %s\" % wc.pk)","sub_path":"scripts/aiida_submit_phase.py","file_name":"aiida_submit_phase.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"396908995","text":"__author__ = 'Bohdan Mushkevych'\n\nfrom logging import ERROR, INFO\n\nfrom scheduler.scheduler_constants import PIPELINE_SIMPLIFIED_DISCRETE\nfrom system import time_helper\nfrom system.process_context import ProcessContext\nfrom db.error import DuplicateKeyError\nfrom db.model import job, unit_of_work\nfrom scheduler.dicrete_pipeline import DiscretePipeline\n\n\nclass SimplifiedDiscretePipeline(DiscretePipeline):\n \"\"\" Pipeline to handle discrete timeperiod boundaries for jobs\n in comparison to DiscretePipeline this one does not transfer to STATE_FINAL_RUN\"\"\"\n\n def __init__(self, logger, timetable):\n super(SimplifiedDiscretePipeline, self).__init__(logger, timetable, name=PIPELINE_SIMPLIFIED_DISCRETE)\n\n def __del__(self):\n super(SimplifiedDiscretePipeline, self).__del__()\n\n def _process_state_in_progress(self, process_name, job_record, start_timeperiod):\n \"\"\" method that takes care of processing job records in STATE_IN_PROGRESS state\"\"\"\n time_qualifier = ProcessContext.get_time_qualifier(process_name)\n end_timeperiod = time_helper.increment_timeperiod(time_qualifier, start_timeperiod)\n actual_timeperiod = time_helper.actual_timeperiod(time_qualifier)\n can_finalize_job_record = self.timetable.can_finalize_job_record(process_name, job_record)\n uow = self.uow_dao.get_one(job_record.related_unit_of_work)\n iteration = int(uow.end_id)\n\n try:\n if start_timeperiod == actual_timeperiod or can_finalize_job_record is False:\n if uow.state in [unit_of_work.STATE_REQUESTED,\n unit_of_work.STATE_IN_PROGRESS,\n unit_of_work.STATE_INVALID]:\n # Large Job processing takes more than 1 tick of Scheduler\n # Let the Large Job processing complete - do no updates to Scheduler records\n pass\n elif uow.state in [unit_of_work.STATE_PROCESSED,\n unit_of_work.STATE_CANCELED]:\n # create new uow to cover new inserts\n uow = self.insert_uow(process_name, start_timeperiod, end_timeperiod, iteration + 1, job_record)\n self.timetable.update_job_record(process_name, job_record, uow, job.STATE_IN_PROGRESS)\n\n elif start_timeperiod < actual_timeperiod and can_finalize_job_record is True:\n if uow.state in [unit_of_work.STATE_REQUESTED,\n unit_of_work.STATE_IN_PROGRESS,\n unit_of_work.STATE_INVALID]:\n # Job processing has not started yet\n # Let the processing complete - do no updates to Scheduler records\n msg = 'Suppressed creating uow for %s in timeperiod %s; job record is in %s; uow is in %s' \\\n % (process_name, job_record.timeperiod, job_record.state, uow.state)\n elif uow.state == unit_of_work.STATE_PROCESSED:\n self.timetable.update_job_record(process_name, job_record, uow, job.STATE_PROCESSED)\n timetable_tree = self.timetable.get_tree(process_name)\n timetable_tree.build_tree()\n msg = 'Transferred job record %s in timeperiod %s to STATE_PROCESSED for %s' \\\n % (job_record.document['_id'], job_record.timeperiod, process_name)\n elif uow.state == unit_of_work.STATE_CANCELED:\n self.timetable.update_job_record(process_name, job_record, uow, job.STATE_SKIPPED)\n msg = 'Transferred job record %s in timeperiod %s to STATE_SKIPPED for %s' \\\n % (job_record.document['_id'], job_record.timeperiod, process_name)\n else:\n msg = 'Unknown state %s for job record %s in timeperiod %s for %s' \\\n % (uow.state, job_record.document['_id'], job_record.timeperiod, process_name)\n\n self._log_message(INFO, process_name, job_record, msg)\n else:\n msg = 'Job record %s has timeperiod from future %s vs current time %s' \\\n % (job_record.document['_id'], start_timeperiod, actual_timeperiod)\n self._log_message(ERROR, process_name, job_record, msg)\n\n except DuplicateKeyError as e:\n uow = self.recover_from_duplicatekeyerror(e)\n if uow is not None:\n self.timetable.update_job_record(process_name, job_record, uow, job_record.state)\n else:\n msg = 'MANUAL INTERVENTION REQUIRED! Unable to identify unit_of_work for %s in %s' \\\n % (process_name, job_record.timeperiod)\n self._log_message(ERROR, process_name, job_record, msg)\n\n def _process_state_final_run(self, process_name, job_record):\n \"\"\"method takes care of processing job records in STATE_FINAL_RUN state\"\"\"\n raise NotImplementedError('Method _process_state_final_run is not supported by SimplifiedDiscretePipeline')\n","sub_path":"scheduler/simplified_dicrete_pipeline.py","file_name":"simplified_dicrete_pipeline.py","file_ext":"py","file_size_in_byte":5104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"151494547","text":"\n\nfrom xai.brain.wordbase.nouns._dishcloth import _DISHCLOTH\n\n#calss header\nclass _DISHCLOTHS(_DISHCLOTH, ):\n\tdef __init__(self,): \n\t\t_DISHCLOTH.__init__(self)\n\t\tself.name = \"DISHCLOTHS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"dishcloth\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_dishcloths.py","file_name":"_dishcloths.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"387601233","text":"import numpy as np\nfrom script.utils import Node, Utils, FloydWarshall, LpMtsp\nfrom script.world import WorldMap\nimport pickle\nimport matplotlib.pyplot as plt\nfrom operator import add\nimport ast\nimport itertools\nfrom time import time, sleep\n\nfrom random import randint\nimport heapq\n\nimport csv\nfrom alive_progress import alive_bar\nimport sys\n\nclass Mwrp:\n\n def __init__(self, world: WorldMap, start_pos: tuple, huristic_index: int, max_pivot: int, map_name: str, minimize: int) -> None:\n \"\"\"\n :param world: An WorldMap object from script.world that contains the parameters of the world\n :param start_pos: The starting position of the agents as tupel . For example for two agents : ((1,1),(4,6))\n :param huristic_index: heuristic activated in this session ( {0: 'singlton', 1: 'max', 2: 'mtsp',3 : 'laze max',4:'BFS'})\n :param max_pivot: The maximum number of pivots for calculating heuristics . From experience 5 and 6 were the best\n :param map_name: The name of the map. For example : maze_11_11\n :param minimize: What we want to minimize (soc, mksp)\n \"\"\"\n self.huristic_index = huristic_index\n self.minimize = minimize\n self.start_time = 0\n self.number_of_agent = start_pos.__len__()\n self.world = world\n\n # we do not want to limit the number of pivot now we well limit it later in the code\n self.max_pivot = max_pivot * 10\n\n # Need it only for the experiments\n self.node_expend_index = 1\n self.genrate_node = 0\n self.expend_node = 0\n self.H_genrate = 0\n self.H_expend = 0\n self.open_is_beter = 0\n self.new_is_beter = 0\n self.real_dis_dic, self.centrality_dict = FloydWarshall(self.world.grid_map).run()\n\n # Checks whether we have previously calculated the distance between all the cell on the map and the centrality\n try:\n self.real_dis_dic = pickle.load(open(f\"config/real_dis_dic_{map_name}.p\", \"rb\"))\n self.centrality_dict = pickle.load(open(f\"config/centrality_dict_{map_name}.p\", \"rb\"))\n except:\n # calculated the distance between all the cell on the map and the centrality and save to file\n print('start FloydWarshall')\n self.real_dis_dic, self.centrality_dict = FloydWarshall(self.world.grid_map).run()\n pickle.dump(self.real_dis_dic, open(f\"config/real_dis_dic_{map_name}.p\", \"wb\"))\n pickle.dump(self.centrality_dict, open(f\"config/centrality_dict_{map_name}.p\", \"wb\"))\n print('end FloydWarshall')\n\n\n # set which contains all the free cell on the map\n unseen_all = set(map(tuple, np.transpose(np.where(self.world.grid_map == 0))))\n\n self.centrality_dict = self.centrality_list_watchers(unseen_all)\n\n pivot = self.get_pivot(unseen_all)\n #start_pos=tuple(list(pivot.keys())[:self.number_of_agent])\n\n # Filters all the cells that can be seen from the starting position\n unseen_start = unseen_all - self.world.get_all_seen(start_pos)\n\n # Produces the initial NODE\n start_node = Node(Node(None, start_pos, [0] * self.number_of_agent, 0, [0] * start_pos.__len__(),{0:0},self.minimize), start_pos,\n unseen_start, [], [0] * start_pos.__len__(),{i:i for i in range(start_pos.__len__())},self.minimize)\n\n # open sort from top to bottom (best down)\n self.open_list = [start_node]\n heapq.heapify(self.open_list)\n\n # open and close list\n self.visit_list_dic = {tuple(sorted(start_pos)): [start_node]}\n\n\n\n # Arranges the centrality_dict according to a given function and filters what you see from the starting point\n self.centrality_dict = self.centrality_list_watchers(unseen_start)\n #Utils.print_serch_status(self.world,start_node,self.start_time,0,0,False)\n # Pre-calculate suspicious points that will be PIVOT to save time during the run\n self.pivot = self.get_pivot(unseen_start)\n\n\n self.old_pivot = {tuple(sorted((i, j))): self.get_closest_watchers(i, j) for i in self.pivot.keys()\n for j in self.pivot.keys() if i != j}\n\n # limit the number of pivot\n self.max_pivot = max_pivot\n\n # Calculate all the distances between the PIVOT to calculate heuristics The goal is to try to understand if\n # there are PIVOT points that lower the value of the heuristics and filter them\n # TODO not the best method requires improvement\n distance_pivot_pivot = {(i, j): self.get_closest_watchers(i, j) for j in self.pivot.keys()\n for i in self.pivot.keys() if i != j}\n distance_in_pivot = {(i, 0): 0 for i in list(self.pivot.keys()) + list(range(1, self.number_of_agent + 1))}\n distance_agent_pivot = {(i, j): 0 for j in self.pivot for i in range(1, self.number_of_agent + 1)}\n all_dist = {**distance_in_pivot, **distance_agent_pivot,\n **{(0, i): 0 for i in range(1, self.number_of_agent + 1)},\n **distance_pivot_pivot}\n\n # Initializes the CPLEX object\n self.lp_model = LpMtsp(self.number_of_agent, self.pivot, all_dist)\n\n # List of pivot that lower the heuristic\n self.pivot_black_list = self.get_pivot_black_list(start_node)\n\n # Need it only for the experiments\n if self.huristic_index == 3:\n self.H_start = 0\n else:\n self.H_start = self.get_heuristic(start_node)\n\n self.mtsp_heuristic(start_node)\n\n\n def goal_test(self, unseen: set) -> bool:\n \"\"\"\n Checking for a solution to a problem (unseen is empty)\n :param unseen: the node unseen list (set)\n :return: True if unseen is empty (bool)\n \"\"\"\n if not unseen.__len__():\n return True\n return False\n\n def get_pivot_black_list(self, start_node: tuple) -> set:\n \"\"\"\n Checking List of pivot that lower the heuristic\n :param start_node: the start node (Node)\n :return: List of pivot that lower the heuristic (set)\n \"\"\"\n old_u = 0\n pivot_black_list = []\n\n # get all unseen cell sort by the centrality . lower is in the center\n tmp_pivot_key_sorted = sorted([(self.centrality_dict[key], key) for key in self.pivot.keys()])\n tmp_pivot_key = [val[1] for val in tmp_pivot_key_sorted]\n\n # Runs on all PIVOT points and saves the points that cause the heuristics to go down until he\n # finds no more such points\n for i in range(self.pivot.__len__()):\n # calculate the heuristics and each time remove different PIVOT\n tmp_u = [self.mtsp_heuristic(start_node,\n {k: self.pivot[k] for k in tmp_pivot_key if k != cell}) for cell in tmp_pivot_key]\n\n # Finds the index with the highest heuristics because it means we downloaded this\n # PIVOT went up the heuristics\n index_min = np.argmax(tmp_u)\n u_max = max(tmp_u)\n\n # If the heuristic has dropped from a previous calculation then there are no additional\n # PIVOT points that can be removd without affect the heuristic\n if (old_u >= u_max):\n break\n else:\n # Save the problematic PIVOT and remove it from the list\n old_u = u_max\n bad_index = tmp_pivot_key[index_min]\n pivot_black_list.append(bad_index)\n del tmp_pivot_key[index_min]\n\n return set(pivot_black_list)\n\n def centrality_list_watchers(self, unseen: set) -> dict:\n \"\"\"\n sort the unseen based on the each cell centrality watchers , number of watchers and cell centrality higher it is the better\n :param unseen: the unseen set of a node\n :return: Dictionary of each cell centrality\n \"\"\"\n centrality_dict=dict()\n #list_sort_by_centrality = []\n # Goes through every cell in unseen and And calculates its centrality\n for index, cell in enumerate(unseen):\n\n # sum all the cell watchers centrality\n centrality_value=sum(self.centrality_dict[cell_whacers] for cell_whacers in self.world.dict_watchers[cell])\n\n # calculate all cells centrality\n centrality_dict[cell] = centrality_value / (self.world.dict_watchers[cell].__len__() ** 2) * self.centrality_dict[cell]\n\n return centrality_dict\n\n def get_centrality_list_watchers(self, unseen: set) -> list:\n \"\"\"\n returt sorted list by centrality sort from the bottom up\n :param unseen: the unseen set of a node\n :return: sorted list of each cell centrality\n \"\"\"\n\n # create sorted list of each cell centrality based on unseen\n list_sort_by_centrality = sorted([(self.centrality_dict[cell], cell) for cell in unseen])\n\n return list_sort_by_centrality\n\n def get_min_list_watchers(self, unseen: set) -> list:\n \"\"\"\n returt sorted list by centrality sort from the bottom up\n :param unseen: the unseen set of a node\n :return: sorted list of each cell number watchers\n \"\"\"\n\n # create sorted list of each cell number watchers based on unseen\n list_sort_by_centrality = sorted([(len(self.world.dict_watchers[cell]), cell) for cell in unseen],reverse=True)\n return list_sort_by_centrality\n\n def get_pivot(self, unseen: set) -> dict:\n \"\"\"\n calculate the pivot location for the mtsp huristic\n :param unseen: the unseen set of a node\n :return: Dictionary of selected pivot\n \"\"\"\n\n pivot = dict()\n remove_from_unseen_set = set()\n\n # get unseen list arranged according to the centrality of the watchers (from experiments works better)\n sort_unseen = self.get_centrality_list_watchers(unseen)\n\n # get unseen list arranged according to the smallest number of watchers\n # sort_unseen = self.get_min_list_watchers(unseen)\n\n # Finds the pivot points and keeps their watchers disjoint for the gdls graph\n while sort_unseen.__len__():\n\n cell = sort_unseen.pop()\n\n # Checks if the cell is ok and is not disjoint with pivot watchers that already selected\n if not self.world.dict_watchers[cell[1]].intersection(remove_from_unseen_set):\n pivot[cell[1]] = self.world.dict_watchers[cell[1]]\n\n # set() which contains all the pivot watchers that already selected (used to test the disjoint)\n remove_from_unseen_set = remove_from_unseen_set | self.world.dict_watchers[cell[1]] | {cell[1]}\n\n if pivot.__len__() == self.max_pivot:\n return pivot\n\n return pivot\n\n def insert_to_open_and_cunt(self, new_node: Node) -> None:\n \"\"\"\n insert the new node to open lest\n :param new_node: node that need to insert to open lest\n \"\"\"\n # Need it only for the experiments\n self.genrate_node += 1\n self.H_genrate += new_node.f\n heapq.heappush(self.open_list,new_node)\n\n def insert_to_open_list_lazy_max(self, new_node: Node) -> None:\n \"\"\"\n insert new node to the open list for lazy_max huristics\n :param new_node: node that need to insert to open lest\n \"\"\"\n\n # Constructs the state so that the agents maintain anonymity\n state = tuple((tuple(sorted(new_node.location)), tuple(new_node.dead_agent)))\n\n # find if the new node is already in open list or close lest (visit_list_dic)\n if new_node.first_genarate or not self.in_open_or_close(state):\n\n # if new_node is insert to open list second time no need to update visit_list_dic and calclate heuristic\n if not new_node.first_genarate:\n new_node.f = self.singelton_heuristic(new_node)\n self.visit_list_dic[state] = [new_node]\n self.insert_to_open_and_cunt(new_node)\n\n # find if is an already node in open list or close lest (visit_list_dic) and if the new node is beter\n elif self.need_to_fix_parent(new_node, state):\n\n # if new_node is insert to open list second time no need to update visit_list_dic and calclate heuristic\n if not new_node.first_genarate:\n new_node.f = self.singelton_heuristic(new_node)\n self.visit_list_dic[state].append(new_node)\n self.insert_to_open_and_cunt(new_node)\n\n def insert_to_open_list(self,new_node: Node) -> None:\n \"\"\"\n insert new node to the open list\n :param new_node: node that need to insert to open lest\n \"\"\"\n\n # Constructs the state so that the agents maintain anonymity\n state = tuple((tuple(sorted(new_node.location)), tuple(new_node.dead_agent)))\n\n # find if the new node is already in open list or close lest (visit_list_dic)\n if not self.in_open_or_close(state):\n new_node.f = self.get_heuristic(new_node)\n self.insert_to_open_and_cunt(new_node)\n self.visit_list_dic[state] = [new_node]\n\n # find if is an already node in open list or close lest (visit_list_dic) and if the new node is beter\n elif self.need_to_fix_parent(new_node, state):\n new_node.f = self.get_heuristic(new_node)\n self.insert_to_open_and_cunt(new_node)\n self.visit_list_dic[state].append(new_node)\n\n def pop_open_list(self) -> None:\n \"\"\"\n get the best valid node in the open list\n :return:\n \"\"\"\n if len(self.open_list):\n #pop_open_list = self.open_list.pop()\n\n pop_open_list = heapq.heappop(self.open_list)\n # Throws zombie node to the bin (zombie node -> dead_agent = True)\n while pop_open_list.f < 0:\n\n #pop_open_list = self.open_list.pop()\n pop_open_list = heapq.heappop(self.open_list)\n else:\n pop_open_list = 0\n\n return pop_open_list\n\n def get_real_dis(self, cell_a: tuple, cell_b: tuple) -> int:\n \"\"\"\n Pulls out the real distance between two cell on the map The calculation is offleen and based on the FloydWarshall algorithm\n :param cell_a: cell a = (x1,y1)\n :param cell_b: cell b = (x2,y2)\n :return: real distance between two cell\n \"\"\"\n key = tuple(sorted((cell_a, cell_b)))\n return self.real_dis_dic[key]\n\n def get_closest_watchers(self, cell_a: tuple, cell_b: tuple) -> int:\n \"\"\"\n get the closest watchers between 2 cells\n :param cell_a: cell a = (x1,y1)\n :param cell_b: cell b = (x2,y2)\n :return: real distance between the two cell closest watchers\n \"\"\"\n min_dis = 100000\n # iterat on all pairs of watchers that both cells have\n for t, k in itertools.product(*(self.world.watchers_frontier[cell_b], self.world.watchers_frontier[cell_a])):\n sort_k_t = tuple(sorted((k, t)))\n if self.real_dis_dic[sort_k_t] < min_dis:\n min_dis = self.real_dis_dic[sort_k_t]\n return min_dis\n\n def singelton_heuristic(self, new_node: Node) -> int:\n \"\"\"\n Calculates the heuristics for Singleton\n :param new_node: node that need to calclate the hes heuristic\n :return: the h value for no eb and f value for eb\n \"\"\"\n\n # Holds the best pivot and heuristic value at any given time\n max_pivot_dist = 0\n max_h_dis = 0\n\n all_cost = sum(new_node.cost)\n for cell in new_node.unseen:\n # Initialize a big number so that the heuristic is sure to be smaller than it\n min_dis = 1000000\n\n # Go through each of the cells watchers and look for the one that closest to one of the agents\n for whach in self.world.watchers_frontier[cell]:\n\n if min_dis < max_pivot_dist:\n break\n\n for index, agent in enumerate(new_node.location):\n if index in new_node.dead_agent:\n continue\n\n if self.minimize == 0:\n cost = new_node.cost[index]\n else:\n cost = all_cost\n\n h = self.get_real_dis(agent, whach)\n\n real_dis = cost + h\n\n # Holds the value of the nearest watchers to one of the agent\n if min_dis >= real_dis:\n tmp_max_h_dis = h\n min_dis = real_dis\n\n # Holds the value of the farthest cell With the nearest watchers to one of the agent\n if max_pivot_dist <= min_dis:\n max_h_dis = tmp_max_h_dis\n max_pivot_dist = min_dis\n\n if new_node.unseen.__len__() == 0:\n max_h_dis = 0\n\n if self.minimize == 0:\n max_pivot_dist = max(max_pivot_dist, max(new_node.cost))\n else:\n max_pivot_dist = max_h_dis + sum(new_node.cost)\n return max_pivot_dist\n\n def mtsp_heuristic(self, new_node: Node, pivot: dict = False) -> int:\n \"\"\"\n Calculates the heuristics for mtsp\n :param new_node: node that need to calclate the hes heuristic\n :return: the h value for no eb and f value for eb\n \"\"\"\n\n if not pivot :\n tmp_pivot = self.get_pivot(new_node.unseen)\n\n #remove the pivot that lower the heuristic ( in pivot_black_list)\n pivot = {pivot: tmp_pivot[pivot] for pivot in tmp_pivot if pivot not in self.pivot_black_list}\n\n # if there is no pivot on the map\n if pivot.__len__() == 0:\n if self.minimize == 0:\n return max(new_node.cost)\n else:\n return sum(new_node.cost)\n\n # for one pivot singelton >= mtsp\n elif pivot.__len__() == 1:\n # return -1 mean that we going to calculate the singelton ensted\n return -1\n\n\n citys = range(self.number_of_agent + pivot.__len__() + 1)\n all_pos = list(new_node.location) + list(pivot.keys())\n\n # bild the dict of the agent pivot distance\n distance_agent_pivot = {}\n for i, j in itertools.product(*(citys[1: self.number_of_agent + 1], citys[self.number_of_agent + 1:])):\n if i - 1 not in new_node.dead_agent:\n distance_agent_pivot[(i, all_pos[j - 1])] = min(\n [self.real_dis_dic[tuple(sorted((all_pos[i - 1], k)))]\n for k in self.world.dict_watchers[all_pos[j - 1]]])\n\n # bild the dict of the pivot pivot distance\n distance_pivot_pivot = dict()\n for i, j in itertools.product(*(citys[self.number_of_agent + 1:], citys[self.number_of_agent + 1:])):\n if i != j:\n sort_pivot = tuple(sorted((all_pos[i - 1], all_pos[j - 1])))\n\n if sort_pivot in self.old_pivot:\n distance_pivot_pivot[(all_pos[i - 1], all_pos[j - 1])] = self.old_pivot[sort_pivot]\n else:\n distance_pivot_pivot[(all_pos[i - 1], all_pos[j - 1])] = self.get_closest_watchers(\n all_pos[i - 1], all_pos[j - 1])\n self.old_pivot[sort_pivot] = distance_pivot_pivot[(all_pos[i - 1], all_pos[j - 1])]\n\n # bild the dict of the pivot virtual distance\n distance_in_pivot = {(i, 0): 0 for i in list(pivot.keys()) + list(range(1, self.number_of_agent + 1))}\n\n # bild the dict of the virtual pivot distance\n distance_out_start = {(0, i): new_node.cost[i - 1] for i in range(1, self.number_of_agent + 1)}\n\n # join all dictionaries\n all_distance_dict = {**distance_out_start, **distance_in_pivot, **distance_agent_pivot, **distance_pivot_pivot}\n\n if self.minimize == 0:\n mtsp_cost = self.lp_model.get_mksp(all_distance_dict,pivot,new_node,all_pos,self.world)\n elif self.minimize == 1:\n mtsp_cost = self.lp_model.get_soc(all_distance_dict,pivot,new_node,all_pos,self.world)\n else:\n print('no minimais')\n #Utils.print_serch_status(self.world,new_node,self.start_time,0,0,False)\n\n return mtsp_cost\n\n def get_heuristic(self, new_node: Node) -> int:\n \"\"\"\n get the heuristic base on the heuristic_index value\n :param new_node: node that need to calclate the hes heuristic\n :return: the h value for no eb and f value for eb\n \"\"\"\n # singelton\n if self.huristic_index == 0:\n closest_pivot_dist = self.singelton_heuristic(new_node)\n\n # max\n elif self.huristic_index == 1:\n mtsp = self.mtsp_heuristic(new_node)\n singelton = self.singelton_heuristic(new_node)\n closest_pivot_dist = max(singelton, mtsp)\n\n # mtsp\n elif self.huristic_index == 2:\n closest_pivot_dist = self.mtsp_heuristic(new_node)\n if closest_pivot_dist == -1:\n closest_pivot_dist = self.singelton_heuristic(new_node)\n\n return closest_pivot_dist\n\n def get_cost(self, new_state: Node, old_state: Node, sort_indexing: dict) -> list:\n \"\"\"\n get the cost for the new node sorted by hes new indexing\n :param new_state: node that need to get hes new cost\n :param old_state: new_state ferent\n :param sort_indexing: list of the sort index (the cost inside list cant change do to the EF jumps)\n :return: cost for the new node\n \"\"\"\n\n # Returns the perent cost according to the index of the new node\n old_cost = [old_state.cost[i] for i in sort_indexing]\n\n # Returns the new cost according to the index of the new node\n cost_from_acthon_not_sort = [self.get_real_dis(data, old_state.location[i]) for i, data in enumerate(new_state)]\n cost_from_acthon = [cost_from_acthon_not_sort[i] for i in sort_indexing]\n\n cost = list(map(add, cost_from_acthon, old_cost))\n return cost\n\n def in_open_or_close(self, state: tuple) -> bool:\n \"\"\"\n find if the state are opend already (open or close)\n :param state: the new state\n :return: True if we already open same state state\n \"\"\"\n if not state in self.visit_list_dic:\n return False\n return True\n\n def get_all_frontire(self, old_state: Node) -> list:\n \"\"\"\n return all frontire (see new cells) for the EF metod\n :param old_state: need to expend the Node\n :return: list of all frontire\n \"\"\"\n\n all_frontire = []\n for index, agent_location in enumerate(old_state.location):\n\n # get frontire for spsific agent (find whit BFS)\n if index not in old_state.dead_agent:\n all_frontire.append(self.world.BFS.get_frontier(agent_location, old_state.unseen))\n else:\n all_frontire.append([agent_location])\n\n return all_frontire\n\n def get_dead_list(self, old_state: Node, new_state: Node, sort_indexing: list) -> list:\n \"\"\"\n retarn the new dead list for the new node\n :param old_state: parent node\n :param new_state: new node\n :param sort_indexing: sort indexing bitwin new node and parent node\n :return: list of dead agent\n \"\"\"\n\n dead_list = old_state.dead_agent[:]\n for i in range(new_state.__len__()):\n if new_state[i] == old_state.location[i] and i not in dead_list:\n dead_list.append(i)\n\n dead_list = [sort_indexing[i] for i in dead_list]\n\n return dead_list\n\n def expend(self):\n # Returns the best valued node currently in the open list\n old_state = self.pop_open_list()\n if self.huristic_index == 3:\n if old_state.first_genarate == False:\n mtsp = self.mtsp_heuristic(old_state)\n old_state.first_genarate = True\n if mtsp >= old_state.f:\n old_state.f = mtsp\n self.insert_to_open_list_lazy_max(old_state)\n return False\n\n # Checks if there are no more cell left to see (len(unseen)==0)\n if self.goal_test(old_state.unseen):\n return old_state\n self.expend_node += 1\n self.H_expend += old_state.f\n\n # Going through all the options to jump for each one of the agents to produce all the valid situations\n for new_state in itertools.product(*self.get_all_frontire(old_state)):\n\n # There is no need to generate a situation similar to the father\n if new_state != old_state.location:\n\n # Rearranges agents and price (from largest to smallest) to maintain anonymity\n sorted_new_state, sorted_indexing = Utils.sort_list(new_state)\n\n # Gets the list that holds the dead agents\n dead_list = self.get_dead_list(old_state, new_state, sorted_indexing)\n\n # Calculates the unseen list for the new node\n seen_state = old_state.unseen - self.world.get_all_seen(sorted_new_state)\n\n new_node = Node(old_state, sorted_new_state, seen_state, dead_list,\n self.get_cost(new_state, old_state, sorted_indexing),sorted_indexing,self.minimize)\n\n if self.huristic_index == 3:\n self.insert_to_open_list_lazy_max(new_node)\n\n else:\n # Inserts the new node to the open list\n self.insert_to_open_list(new_node)\n\n return False\n\n def need_to_fix_parent(self, new_node: Node, state: tuple) -> bool:\n \"\"\"\n Checks whether there is a state similar to the new state and whether there is one better than the other\n\n :param new_node: the new node\n :param state: the new state (pos , dead)\n :return: bool if need to insert to open\n \"\"\"\n\n all_index = set()\n\n # Runs on all existing similar posters\n for index, old_node in enumerate(self.visit_list_dic[state]):\n cost_win = 0\n\n if self.minimize == 0:\n # Checks the cost of each cell individually and only if the cost of each cell in the same trend\n # (all high or all low) then it determines who is better in terms of cost\n for index, new_cell in enumerate(new_node.cost_map.keys()):\n if cost_win == -5:\n break\n\n # A loop that passes through all the agents stnding in a particular cell (can be more than 1 such)\n for i in range(new_node.cost_map[new_cell].__len__()):\n if new_node.cost_map[new_cell][i] >= old_node.cost_map[new_cell][i] and cost_win >= 0:\n # new_node is beter\n cost_win = 1\n elif new_node.cost_map[new_cell][i] <= old_node.cost_map[new_cell][i] and cost_win <= 0:\n # old_node is beter\n cost_win = -1\n else:\n cost_win = -5\n\n # In soc the comparison can be made by only the sum of the cost\n elif self.minimize == 1:\n cost_win = 1 if sum(new_node.cost) >= sum(old_node.cost) else -1\n\n if cost_win == 1 and old_node.unseen.issubset(new_node.unseen):\n self.open_is_beter += 1\n return False\n\n elif cost_win == -1 and new_node.unseen.issubset(old_node.unseen):\n self.new_is_beter += 1\n\n # self.replace_in_heap()\n #old_node.cost = [-max(old_node.cost)] * self.number_of_agent\n old_node.f = -old_node.f\n\n #old_node.dead_agent=True\n #old_node.valid_node=False\n all_index.add(index)\n\n if all_index.__len__() > 0:\n self.visit_list_dic[state] = [data for i, data in enumerate(self.visit_list_dic[state])\n if i not in all_index]\n\n return True\n\n def run(self, writer: csv , map_config: str, start_pos: tuple, obs_remove: int) -> None:\n \"\"\"\n run the algorithm and return if finds solution or 5 minutes limit\n :param writer: the csv file holder\n :param map_config: name of the experiment\n :param start_pos: start location\n :param obs_remove: number of obstacle remove (for the experiment)\n :return:\n \"\"\"\n # Writes to the file the type of heuristic that is activated\n h_type = {0: 'singlton', 1: 'max', 2: 'mtsp', 3: 'laze max', 4: 'BFS'}\n self.start_time = time()\n goal_node = False\n\n while not goal_node:\n # expend new node if goal_node is not folse the algoritem find solution\n goal_node = self.expend()\n # Checks if we have exceeded the time limit\n if time() - self.start_time > 300:\n print('open_list size = ',self.open_list.__len__())\n # Writes to the file all the parameters of the experiment when the cost is 0 and the time is -1\n writer.writerow([map_config, start_pos, -1, h_type[self.huristic_index], self.H_start,\n self.H_genrate / self.genrate_node,\n self.H_expend / self.expend_node, self.max_pivot, 0, self.genrate_node,\n self.expend_node, self.open_is_beter, self.new_is_beter, obs_remove,\n [0] * self.number_of_agent])\n return\n\n all_path = self.get_path(goal_node, print_path=False,need_path=False)\n\n if self.genrate_node > 0:\n h_gen = self.H_genrate / self.genrate_node\n h_exp = self.H_expend / self.expend_node\n else:\n h_gen = self.H_genrate\n h_exp = self.H_expend\n\n # Writes to the file all the parameters of the experiment\n writer.writerow([map_config, start_pos, time() - self.start_time, h_type[self.huristic_index], self.H_start,\n h_gen, h_exp, self.max_pivot, 0, self.genrate_node, self.expend_node,\n self.open_is_beter, self.new_is_beter, obs_remove, goal_node.cost])\n\n def get_path(self, gole_node: Node, need_path: bool = True, print_path: bool = False) -> dict:\n \"\"\"\n #fix sorted unsycronic location and get all node on the optimal path between jump points\n\n :param gole_node: the goal node\n :param need_path: flag if need the path if true calculate pate\n :param print_path: flag if nead to print the path\n :return: dict that hold all path one for each agent (not the same length)\n \"\"\"\n\n if need_path:\n all_jump_points = []\n node = gole_node\n\n # geting all jump points\n while node.parent is not None:\n if print_path:\n print(node)\n # fix usicronic sort (the agent jumps between paths)\n all_jump_points.append(node.get_sorted_location(node.location))\n node = node.parent\n\n # reverse point because need path from start to goal\n all_jump_points=all_jump_points[::-1]\n dict_all_path={i : [all_jump_points[0][i]] for i in range(self.number_of_agent)}\n\n # get all point on path by using BFS method\n for index in range(1,all_jump_points.__len__()):\n for i in range(self.number_of_agent):\n dict_all_path[i].extend(self.world.BFS.get_path(all_jump_points[index-1][i],all_jump_points[index][i]))\n return dict_all_path\n return {}\n\n\n\nif __name__ == '__main__':\n map_type = 'maze_11_11'\n name = 'test'\n\n # run from consul\n # if sys.argv:\n # # huristics_exp = [int(sys.argv[1])]\n # loop_number_of_agent = [int(sys.argv[1])]\n\n experement_name = f'{map_type}_{name}'\n map_config = f'./config/{map_type}_config.csv'\n\n row_map = Utils.convert_map(map_config)\n\n all_free = np.transpose(np.where(np.array(row_map) == 0))\n\n pivot = [5]\n exp_number = 10\n\n loop_number_of_agent = [2,3,4]\n minimize = {'mksp': 0, 'soc': 1}\n huristics_exp = [3]\n\n start_in = 0\n exp_index = 0\n\n # remove_obs_number = 1\n # maps = pickle.load(open(\"all_maps_for_remove.p\", \"rb\"))[:-1]\n # remove_obs_number=maps.__len__()\n\n data_file = open(f'{experement_name}_{loop_number_of_agent[0]}_agent_{huristics_exp[0]}_huristic.csv', 'w',newline='\\n')\n writer = csv.writer(data_file, delimiter=',')\n writer.writerow(\n ['map_name', 'start_state', 'time', 'h type', 'h_start', 'h_genarate', 'h_expend', 'number of max pivot',\n 'use black list', 'genarate', 'expend', 'open is beter', 'new is beter', 'obs remove', 'cost'])\n\n row_map = Utils.convert_map(map_config)\n remove_obs_number=1\n with alive_bar(loop_number_of_agent.__len__() * exp_number * len(huristics_exp) * len(pivot) * remove_obs_number) as bar:\n for max_pivot in pivot:\n for number_of_agent in loop_number_of_agent:\n for remove_obs in range(remove_obs_number):\n start_config_as_string = np.loadtxt(f'./config/{map_type}_{number_of_agent}_agent_domain.csv',\n dtype=tuple, delimiter='\\n')\n all_start_config_as_tupel = [ast.literal_eval(i) for i in start_config_as_string]\n all_start_config_as_tupel = all_start_config_as_tupel[:exp_number]\n\n #all_start_config_as_tupel=list(map(tuple,all_free))\n #all_start_config_as_tupel=[[0]*number_of_agent]\n\n for start_pos in all_start_config_as_tupel:\n for huristic in huristics_exp:\n if exp_index >= start_in:\n world = WorldMap(np.array(row_map))\n mwrp = Mwrp(world, start_pos, huristic, max_pivot, map_type, minimize['soc'])\n mwrp.run(writer, map_config, start_pos, remove_obs)\n bar()\n","sub_path":"mwrp.py","file_name":"mwrp.py","file_ext":"py","file_size_in_byte":34472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"475229383","text":"from django.core.exceptions import ValidationError\nfrom django.db import models\n\nfrom . import forms\nfrom .validators import default_error_messages, has_allowed_extension, \\\n has_correct_content_type\n\n\nclass SafeFileField(models.FileField):\n default_error_messages = default_error_messages\n\n def __init__(self, **kwargs):\n self.allowed_extensions = kwargs.pop('allowed_extensions', None)\n self.strict_content_type = kwargs.pop('strict_content_type', True)\n\n super().__init__(**kwargs)\n\n def formfield(self, **kwargs):\n return super().formfield(\n form_class=forms.SafeFileField,\n\n allowed_extensions=self.allowed_extensions,\n strict_content_type=self.strict_content_type\n )\n\n def validate(self, value, model_instance):\n super().validate(value, model_instance)\n\n if not value:\n return\n\n if self.allowed_extensions \\\n and not has_allowed_extension(value, self.allowed_extensions):\n _msg = self.error_messages['file_type'] % {\n 'types': ', '.join(self.allowed_extensions)\n }\n raise ValidationError(_msg, code='file_type')\n\n if not has_correct_content_type(value, self.strict_content_type):\n raise ValidationError(\n self.error_messages['file_content_type'],\n code='file_content_type'\n )\n","sub_path":"safe_filefield/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"11700193","text":"from flask import Flask\nfrom flask import Flask, render_template, request\nimport requests\nfrom hatesonar import Sonar\nimport json\napp = Flask(__name__)\n\n@app.route('/pass_val',methods=['GET', 'POST'])\ndef pass_val():\n name=request.args.get('value')\n sonar = Sonar()\n f = open('popup.html', 'w')\n resultHate = float(sonar.ping(text=str(name))['classes'][0]['confidence'])\n resultOff = float(sonar.ping(text=str(name))['classes'][1]['confidence'])\n print(resultHate, resultOff)\n if resultHate >= 0.40:\n result = 'could be categorized as hate speech.'\n elif resultOff >= 0.40:\n result = ' could be categorized as offensive language.'\n else:\n result = ' was not flagged as either hate speech or offensive language.'\n default = ''' \n\n

\n\n '''\n\n f.write(default + '

' + '\"' + name + '\"' + '

' + '

' + result + '

')\n f.close()\n f = open('data.json', 'w')\n f.write(json.dumps({\"message\": \"'\" + name + \"'\" + result}))\n f.close()\n return 'success'\n@app.route('/get_data', methods=['POST'])\ndef home():\n f = open('popup.html', 'r')\n x = f.read()\n f.close()\n return x\n\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"239663215","text":"def intersect(A, B):\n aSize = len(A)\n bSize = len(B)\n\n a =0\n b= 0\n common = list()\n while adate(x[0][1],x[0][2],x[0][3]))))\n\n# Function for filter the data and remove data at the hours that are posterior to the reference hour\ndef filterHour(time, data):\n return(data.filter(lambda x: (time>x[1])))\n\n# Calculating kernel for difference in days\ndef gaussianDay(dateYear, dateMonth, dateDay, year, month, day, h):\n delta = (datetime(dateYear,dateMonth,dateDay)-datetime(year,month,day)).days % 365\n if(delta>=183):\n delta = 365 - delta\n u=delta/h\n return (exp(-u**2))\n\n# Calculating kernel for difference in distance\ndef gaussianDist(placeA, placeB, data, h):\n lat=data[5]\n long=data[6]\n u=haversine(placeA, placeB, lat, long)/h\n return (exp(-u**2))\n\n# Calculating kernel for difference in time\ndef gaussianTime(timeVal, timedata, h):\n delta = abs(timeVal-timedata)\n if(delta>=13):\n delta= 24 - delta\n u=delta/h\n return (exp(-u**2))\n\n# Filter and remove the data points posterior to the reference day before the time loop to optimize performance\ntemps = filterDate(ourYear,ourMonth,ourDay,temps)\n# Calculating kernels that do not depend of the hour of the day before the time loop to optimize performance\nkernel = temps.map(lambda x: (x[1],x[0][4],\n (gaussianDist(a, b, x[0], h_distance)+gaussianDay(ourYear,ourMonth,ourDay, x[0][1],x[0][2],x[0][3], h_date)),\n ((gaussianDist(a, b, x[0], h_distance)+gaussianDay(ourYear,ourMonth,ourDay, x[0][1],x[0][2],x[0][3], h_date))*x[1]),\n (gaussianDist(a, b, x[0], h_distance)*gaussianDay(ourYear,ourMonth,ourDay, x[0][1],x[0][2],x[0][3], h_date)),\n (gaussianDist(a, b, x[0], h_distance)*gaussianDay(ourYear,ourMonth,ourDay, x[0][1],x[0][2],x[0][3], h_date)*x[1])))\n# Saving this RDD to memory so it can be used in later stage\nkernel.persist()\n\nfirstTime=True\n# Looping through the different time points and storing the calculated predicted temperature through the specified kernel formulas\nfor time in [\"24:00:00\", \"22:00:00\", \"20:00:00\", \"18:00:00\", \"16:00:00\", \"14:00:00\",\n\"12:00:00\", \"10:00:00\", \"08:00:00\", \"06:00:00\", \"04:00:00\"]:\n intTime = int(time[0:2])\n kernelTemp = filterHour(intTime,kernel)\n kernelTemp = kernelTemp.map(lambda x: (1,((x[2]+gaussianTime(intTime, x[1], h_time)),\n (x[3]+(gaussianTime(intTime, x[1], h_time)*x[0])),\n (x[4]*gaussianTime(intTime, x[1], h_time)),\n (x[5]*(gaussianTime(intTime, x[1], h_time))))))\n kernelTemp = kernelTemp.reduceByKey(lambda a,b: (a[0]+b[0],a[1]+b[1],a[2]+b[2],a[3]+b[3]))\n kernelTemp = kernelTemp.mapValues(lambda a: (a[1]/a[0], a[3]/a[2]))\n if firstTime:\n kernelsum = kernelTemp.map(lambda x: (time, x[1][0]))\n kernelmult = kernelTemp.map(lambda x: (time, x[1][1]))\n firstTime = False\n else:\n kernelsum = kernelsum.union(kernelTemp.map(lambda x: (time, x[1][0])))\n kernelmult = kernelmult.union(kernelTemp.map(lambda x: (time, x[1][1])))\n\n# Shrinking the output to only one file and saving it to output folder\nkernelsum.coalesce(1).saveAsTextFile(\"BDA/output/sum\")\nkernelmult.coalesce(1).saveAsTextFile(\"BDA/output/mult\")\n# plt.figure(3)\n# plt.plot(time_vector, kernel_sum)\n# plt.xlabel('Time of day')\n# plt.ylabel('Temperature')\n# plt.suptitle('Temperature estimate through sum of factors')\n# plt.savefig(\"BDA/output/sum.png\")\n# plt.figure(4)\n# plt.plot(time_vector, kernel_mult)\n# plt.xlabel('Time of day')\n# plt.ylabel('Temperature')\n# plt.suptitle('Temperature estimate through product of factors')\n# plt.savefig(\"BDA/output/mult.png\")\n","sub_path":"lab3-ml/exercise.py","file_name":"exercise.py","file_ext":"py","file_size_in_byte":6736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"33190599","text":"import pygame\n\n#framework from http://blog.lukasperaza.com\n\nclass PygameGame(object):\n\n def isKeyPressed(self, key):\n #return whether a specific key is being held\n return self._keys.get(key, False)\n\n def __init__(self, width=600, height=600, fps=50, title=\"Super Mazeo\"):\n self.width = width\n self.height = height\n self.fps = fps\n self.title = title\n pygame.init()\n\n\n def run(self):\n clock = pygame.time.Clock()\n screen = pygame.display.set_mode((self.width, self.height))\n pygame.display.set_caption(self.title)\n\n # stores all the keys currently being held down\n self._keys = dict()\n\n # call game-specific initialization\n self.init()\n playing = True\n while playing:\n time = clock.tick(self.fps)\n self.timerFired(time)\n for event in pygame.event.get():\n if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n self.mousePressed(*(event.pos))\n\n elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:\n self.mouseReleased(*(event.pos))\n\n elif (event.type == pygame.MOUSEMOTION and\n event.buttons[0] == 1):\n self.mouseDrag(*(event.pos))\n\n elif event.type == pygame.KEYDOWN:\n self._keys[event.key] = True\n self.keyPressed(event.key, event.mod)\n \n elif event.type == pygame.QUIT:\n playing = False\n\n pygame.mixer.fadeout(1000)\n screen.fill((255, 255, 255))\n self.redrawAll(screen)\n pygame.display.flip()\n\n pygame.quit()","sub_path":"pygameGame.py","file_name":"pygameGame.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"3910183","text":"from tareas.excepciones.conexion_error import ConexionError\nfrom tareas.excepciones.valor_invalido_error import ValorInvalidoError\nfrom tareas.configuracion import ERROR_TITULOS_RECONOCIMIENTO\n\n\nclass ValidadorTitReconocimiento(object):\n def __init__(self, institucion_estudio_previo, retry):\n self.institucion_estudio_previo = institucion_estudio_previo\n self.retry = retry\n self.estado = {'existe': False, 'retry': False}\n\n def validar(self):\n self.__validar_titulo_reconocimiento()\n return self.__manejar_resultado_para_titulo_reconocimiento()\n\n def __manejar_resultado_para_titulo_reconocimiento(self):\n if self.estado['existe'] == False:\n if self.estado['retry']:\n self.retry(exc=self.estado['excepcion'])\n else:\n raise ValorInvalidoError(ERROR_TITULOS_RECONOCIMIENTO)\n else:\n return self.estado['existe']\n\n def __validar_titulo_reconocimiento(self):\n self.__verificar_existe()\n return self.estado\n\n def __verificar_existe(self):\n try:\n if self.institucion_estudio_previo == 3333:\n existe = True\n else:\n existe = False\n self.estado['existe'] = self.estado['existe'] or existe\n except ConexionError as excepcion:\n self.estado['retry'] = True\n self.estado['excepcion'] = excepcion\n","sub_path":"tareas/validadores/titulo_reconocimiento.py","file_name":"titulo_reconocimiento.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"642551329","text":"from sklearn.model_selection import train_test_split\nimport xgboost as xgb\nimport numpy as np\nimport pandas as pd\nimport featuretools as ft\nfrom sklearn.preprocessing import Imputer\nfrom featuretools.primitives import (Day, Hour, Minute, Month, Weekday, Week, Weekend, Mean, Max, Min, Std, Skew)\n\n\ndef read_data(TRAIN_DIR, TEST_DIR, nrows=None):\n data_train = pd.read_csv(TRAIN_DIR,\n parse_dates=[\"pickup_datetime\",\n \"dropoff_datetime\"],\n nrows=nrows)\n data_test = pd.read_csv(TEST_DIR,\n parse_dates=[\"pickup_datetime\"],\n nrows=nrows)\n data_train = data_train.drop(['dropoff_datetime'], axis=1)\n data_train.loc[:, 'store_and_fwd_flag'] = data_train['store_and_fwd_flag'].map({'Y': True,\n 'N': False})\n data_test.loc[:, 'store_and_fwd_flag'] = data_test['store_and_fwd_flag'].map({'Y': True,\n 'N': False})\n data_train = data_train[data_train.trip_duration < data_train.trip_duration.quantile(0.99)]\n\n xlim = [-74.03, -73.77]\n ylim = [40.63, 40.85]\n data_train = data_train[(data_train.pickup_longitude> xlim[0]) & (data_train.pickup_longitude < xlim[1])]\n data_train = data_train[(data_train.dropoff_longitude> xlim[0]) & (data_train.dropoff_longitude < xlim[1])]\n data_train = data_train[(data_train.pickup_latitude> ylim[0]) & (data_train.pickup_latitude < ylim[1])]\n data_train = data_train[(data_train.dropoff_latitude> ylim[0]) & (data_train.dropoff_latitude < ylim[1])]\n\n return (data_train, data_test)\n\ndef preview(df, n=5):\n \"\"\"return n rows that have fewest number of nulls\"\"\"\n order = df.isnull().sum(axis=1).sort_values().head(n).index\n return df.iloc[order]\n\ndef train_xgb(X_train, labels):\n Xtr, Xv, ytr, yv = train_test_split(X_train.values,\n labels,\n test_size=0.2,\n random_state=0)\n\n dtrain = xgb.DMatrix(Xtr, label=ytr)\n dvalid = xgb.DMatrix(Xv, label=yv)\n\n evals = [(dtrain, 'train'), (dvalid, 'valid')]\n\n params = {\n 'min_child_weight': 1, 'eta': 0.166,\n 'colsample_bytree': 0.4, 'max_depth': 9,\n 'subsample': 1.0, 'lambda': 57.93,\n 'booster': 'gbtree', 'gamma': 0.5,\n 'silent': 1, 'eval_metric': 'rmse',\n 'objective': 'reg:linear',\n }\n\n model = xgb.train(params=params, dtrain=dtrain, num_boost_round=227,\n evals=evals, early_stopping_rounds=50, maximize=False,\n verbose_eval=10)\n\n print('Modeling RMSE %.5f' % model.best_score)\n return model\n\n\ndef predict_xgb(model, X_test):\n dtest = xgb.DMatrix(X_test.values)\n ytest = model.predict(dtest)\n X_test['trip_duration'] = np.exp(ytest)-1\n return X_test[['trip_duration']]\n\n\ndef feature_importances(model, feature_names):\n feature_importance_dict = model.get_fscore()\n fs = ['f%i' % i for i in range(len(feature_names))]\n f1 = pd.DataFrame({'f': list(feature_importance_dict.keys()),\n 'importance': list(feature_importance_dict.values())})\n f2 = pd.DataFrame({'f': fs, 'feature_name': feature_names})\n feature_importance = pd.merge(f1, f2, how='right', on='f')\n feature_importance = feature_importance.fillna(0)\n return feature_importance[['feature_name', 'importance']].sort_values(by='importance',\n ascending=False)\n\n\ndef get_train_test_fm(feature_matrix,percentage):\n nrows = feature_matrix.shape[0]\n head = int(nrows * percentage)\n tail = nrows-head\n X_train = feature_matrix.head(head)\n y_train = X_train['trip_duration']\n X_train = X_train.drop(['trip_duration'], axis=1)\n imp = Imputer()\n X_train = imp.fit_transform(X_train)\n X_test = feature_matrix.tail(tail)\n y_test= X_test['trip_duration']\n X_test = X_test.drop(['trip_duration'], axis=1)\n imp = Imputer()\n X_test = imp.fit_transform(X_test)\n\n return (X_train, y_train, X_test,y_test)\n\n\ndef duplicate_columns(frame):\n groups = frame.columns.to_series().groupby(frame.dtypes).groups\n dups = []\n for t, v in groups.items():\n dcols = frame[v].to_dict(orient=\"list\")\n\n vs = dcols.values()\n ks = dcols.keys()\n lvs = len(vs)\n\n for i in range(lvs):\n for j in range(i+1,lvs):\n if vs[i] == vs[j]:\n dups.append(ks[i])\n break\n return dups\n\ndef find_training_examples(item_purchases, invoices, prediction_window, training_window, lead,threshold):\n niter = 2 #hard coded number of cutoffs we will search starting with \n cutoff_time = pd.Timestamp(\"2011-05-01\") # hard coded start date \n label_times=pd.DataFrame()\n for k in range(1,niter):\n cutoff_time = cutoff_time + pd.Timedelta(\"45d\")\n lt = make_label_times(item_purchases, invoices, cutoff_time, prediction_window, \n training_window, lead,threshold)\n label_times=label_times.append(lt)\n\n label_times=label_times.sort_values('cutoff_time')\n return label_times\n\ndef make_label_times(item_purchases, invoices, cutoff_time, prediction_window, training_window, lead,threshold):\n data = item_purchases.merge(invoices)[[\"CustomerID\", \"InvoiceDate\", \"Quantity\", \"UnitPrice\"]]\n data[\"amount\"] = data[\"Quantity\"] * data[\"UnitPrice\"]\n\n prediction_window_start = cutoff_time\n prediction_window_end = cutoff_time + prediction_window\n cutoff_time = cutoff_time - lead\n t_start = cutoff_time - training_window\n\n training_data = data[(data[\"InvoiceDate\"] <= cutoff_time) & (data[\"InvoiceDate\"] > t_start)]\n prediction_data = data[(data[\"InvoiceDate\"] > prediction_window_start) & (data[\"InvoiceDate\"] < prediction_window_end)]\n\n\n # get customers in training data\n label_times = pd.DataFrame()\n label_times[\"CustomerID\"] = training_data[\"CustomerID\"].dropna().unique()\n label_times[\"t_start\"] = t_start\n label_times[\"cutoff_time\"] = cutoff_time\n \n\n\n\n\n labels = prediction_data.groupby(\"CustomerID\")[[\"amount\"]].count()\n\n\n label_times = label_times.merge(labels, how=\"left\", left_on=\"CustomerID\", right_index=True)\n\n # if the amount is nan that means the customer made no purchases in prediction window\n label_times[\"amount\"] = label_times[\"amount\"].fillna(0) \n label_times.rename(columns={\"amount\": \"purchases>threshold\"}, inplace=True)\n label_times['purchases>threshold']=label_times['purchases>threshold']>threshold\n\n \n return label_times \n\ndef load_nyc_taxi_data():\n trips = pd.read_csv('nyc-taxi-data/trips.csv', \n parse_dates=[\"pickup_datetime\",\"dropoff_datetime\"],\n dtype={'vendor_id':\"category\",'passenger_count':'int64'},\n encoding='utf-8')\n trips = trips.dropna(axis=0,how='any',subset=['trip_duration'])\n passenger_cnt = pd.read_csv('nyc-taxi-data/passenger_cnt.csv',\n parse_dates=[\"first_trips_time\"],\n dtype={'passenger_count':'int64'},\n encoding='utf-8')\n vendors = pd.read_csv('nyc-taxi-data/vendors.csv', \n parse_dates=[\"first_trips_time\"],\n dtype={'vendor_id':\"category\"},\n encoding='utf-8')\n return trips, passenger_cnt, vendors \n\ndef load_uk_retail_data():\n item_purchases = pd.read_csv('uk-retail-data/item_purchases.csv')\n invoices = pd.read_csv('uk-retail-data/invoices.csv')\n items = pd.read_csv('uk-retail-data/items.csv')\n customers = pd.read_csv('uk-retail-data/customers.csv')\n invoices['first_item_purchases_time'] = pd.to_datetime(invoices['first_item_purchases_time'] , format=\"%m/%d/%y %H:%M\")\n item_purchases['InvoiceDate'] = pd.to_datetime(item_purchases['InvoiceDate'] , format=\"%m/%d/%y %H:%M\")\n customers['first_invoices_time'] = pd.to_datetime(customers['first_invoices_time'] , format=\"%m/%d/%y %H:%M\")\n items['first_item_purchases_time'] = pd.to_datetime(items['first_item_purchases_time'], format=\"%m/%d/%y %H:%M\")\n return item_purchases, invoices, items,customers \n\ndef compute_features(features,cutoff_time):\n feature_matrix = ft.calculate_feature_matrix(features,\n cutoff_time=cutoff_time,\n approximate='36d')\n return feature_matrix\n\ndef engineer_features_uk_retail(entities,relationships,label_times,training_window):\n trans_primitives = [Minute, Hour, Day, Week, Month, Weekday, Weekend]\n\n feature_matrix,features = ft.dfs(entities=entities,\n relationships=relationships,\n target_entity=\"customers\",\n trans_primitives=trans_primitives,\n agg_primitives=[Mean,Max,Std],\n cutoff_time=label_times,\n training_window=training_window)\n feature_matrix.drop(\"Country\", axis=1, inplace=True)\n feature_matrix=feature_matrix.sort_index()\n return feature_matrix ","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"197212358","text":"################## METADATA ##################\n# NAME: Mert Saraç\n# USERNAME: a18mersa\n# COURSE: Scriptprogramming IT384G - Spring 2019\n# ASSIGNMENT: Assignment 1 - Python\n# DATE OF LAST CHANGE: 20190514\n##############################################\n\n\nimport csv\n\n#csv file\nsource = \"users.csv\"\n\n#open source file as readeble\nwith open(source, \"r\") as csvfile:\n #separate the CSV file by its commas.\n csvreader = csv.reader(csvfile, delimiter=',')\n usernames = next(csvreader)\n\n#create new file\nwith open(\"users.txt\", \"w\") as orderedfile:\n #write each element into the file\n for username in sorted(usernames):\n orderedfile.write(username + \"\\n\")\n","sub_path":"script/partA/scriptD.py","file_name":"scriptD.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"192832268","text":"import pygame\nfrom gameengine.util.Vector2 import Vector2\n\nfrom gameengine.components.CustomDraw import CustomDraw\nfrom gameengine.components.Input import Input\nfrom gameengine.components.Script import Script\nfrom gameengine.core.GameObject import GameObject\nfrom gameengine.core.Scene import Scene\nfrom gameengine.core.World import World\nfrom gameengine.managers.SceneManager import SceneManager\nfrom gameengine.util.Timer import Timer\n\npygame.init()\nclock = pygame.time.Clock()\n\nWorld.display = pygame.display.set_mode((800, 464), 0, 32)\n\n\nclass Square(GameObject, Script):\n def __init__(self):\n super().__init__()\n self.addComponent(CustomDraw)\n self.addComponent(Input)\n\n self.addScript(self)\n\n self.transform.size = Vector2(50, 50)\n\n def onMouseDrag(self, pos, rel, buttons):\n self.transform.position += rel\n\n def onDraw(self):\n surface = pygame.Surface((50, 50))\n surface.fill((0, 255, 0))\n return surface\n\n def onKeyDown(self, key):\n if key == pygame.K_RIGHT:\n self.transform.position += Vector2(10, 0)\n\n\nclass Square2(Square):\n def __init__(self):\n super().__init__()\n self.transform.size = Vector2(100, 100)\n\n def onDraw(self):\n surface = pygame.Surface((100, 100))\n surface.fill((255, 0, 0))\n return surface\n\n def onKeyDown(self, key):\n pass\n\n\nclass Level1(Scene):\n def onLoad(self):\n Square().transform.position = Vector2(200, 200)\n\n\n # destroy(self.mainCamera)\n # destroy(self.mainCamera)\n Timer(1000, lambda: SceneManager().loadScene(Level2), cycles=1).start()\n\n\nclass Level2(Scene):\n def onLoad(self):\n self.mainCamera.transform.size = Vector2(400, 232)\n self.mainCamera.transform.position = Vector2(400, 232)\n\n Square2().transform.position = Vector2(50, 50)\n\n Timer(1000, lambda: SceneManager().loadScene(Level1), cycles=1).start()\n\n\nSceneManager().loadScene(Level1)\n# SceneManager().loadScene(Level2)\n\n# Timer(2000, lambda: SceneManager().loadScene(Level1), startNow=True).start()\n# Timer(2000, lambda: SceneManager().loadScene(Level2)).start()\n\nwhile True:\n World.update()\n World.draw()\n clock.tick(60)","sub_path":"gameengine/tests/testScenes.py","file_name":"testScenes.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"630353769","text":"#!/usr/bin/python3\n# --*-- coding:utf-8 --*--\n# @Author : YuAn\n# @Site : \n# @File : lily.py\n# @Time : 2018/5/30 15:56\n# @software : PyCharm\n\nfor num in range(100, 1000):\n low = num % 10\n mid = num // 10 % 10\n high = num // 100\n if num == low ** 3 + mid ** 3 + high ** 3:\n print(num)\n","sub_path":"Day05/lily.py","file_name":"lily.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"417017558","text":"# This script is used to find the interface residues from protein complex with protein 3D structures\nimport os\nfrom Bio.PDB import *\nfrom Bio.PDB import PDBParser\nfrom Bio.PDB import PDBIO\nimport Bio.PDB\nfrom optparse import OptionParser\nimport random\nimport sys\nsys.path.append(r\"/Users/luho/PycharmProjects/3D_model/Data_collection_of_PDB/code\")\nos.chdir('/Users/luho/PycharmProjects/3D_model/Data_collection_of_PDB/code')\n\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n\n\ndef get_atom_list(structure, chains):\n output = dict()\n for chain in structure:\n if chain.id in chains:\n for residue in chain.get_residues():\n hetflag, resseq, icode = residue.get_id()\n the_id = (chain.id + \"_\" + str(resseq) + \"_\" + icode).strip()\n for atom in residue.get_unpacked_list():\n if hetflag == ' ':\n if the_id in output:\n output[the_id].append(atom)\n else:\n output[the_id] = [atom]\n return output\n\n\ndef is_contact(res_1, other_atoms, cutoff):\n for atom in res_1:\n ns = NeighborSearch(other_atoms)\n center = atom.get_coord()\n neighbors = ns.search(center, cutoff) # 5.0 for distance in angstrom\n residue_list = Selection.unfold_entities(neighbors, 'R') # R for residues\n if len(residue_list) > 0:\n return True\n return False\n\n\ndef get_contacts(struc, all_atoms, verbose, cutoff):\n progress = 0\n contacts = []\n for residue in struc:\n progress += 1\n if len(verbose) > 0:\n print\n verbose, progress, \"out of\", len(struc)\n atom_list = struc[residue]\n outcome = is_contact(atom_list, all_atoms, cutoff)\n if outcome:\n contacts.append(residue)\n return contacts\n\n\n# Filter out all the atoms from the chain,residue map given by residue_map\ndef get_all_atoms(residue_map):\n all_atoms_out = []\n for residue in residue_map:\n for atom in residue_map[residue]:\n all_atoms_out.append(atom)\n # Set the b-factor to zero for coloring by contacts\n atom.set_bfactor(0.0)\n return all_atoms_out\n\n\n# Save the structures with B-factor field replaced with contact (100) and interface neighborhood (50)\ndef save_contacts(structure, chains, out_file):\n # Save only those chains that we are supposed to\n Select = Bio.PDB.Select\n\n class ConstrSelect(Select):\n def accept_chain(self, chain):\n # print dir(residue)\n\n if chain.id in chains:\n return 1\n else:\n return 0\n\n w = PDBIO()\n w.set_structure(structure)\n randint = random.randint(0, 9999999)\n w.save(\"TMP\" + str(randint) + \".pdb\", ConstrSelect())\n # Remove the HETATM and TER lines\n f_tmp = open(\"TMP\" + str(randint) + \".pdb\", 'r')\n f_out = open(out_file, 'w')\n for line in f_tmp.readlines():\n if line[0:3] != \"TER\" and line[0:6] != \"HETATM\":\n f_out.write(line)\n f_tmp.close()\n f_out.close()\n os.remove(\"TMP\" + str(randint) + \".pdb\")\n\n\n# Save the residues which are contacts or neighborhood interface in a space-delimited file\ndef save_residues(filename, interface, contacts):\n f = open(filename, 'w')\n for elem in interface:\n splitted = elem.split(\"_\")\n resname = str((splitted[1] + splitted[2]).strip())\n chain = splitted[0]\n # contact or neighbor of interface?\n coninf = \"I\" # Interface neighbor\n if elem in contacts:\n coninf = \"C\" # Contact\n f.write(chain + \" \" + resname + \" \" + coninf + \"\\n\")\n f.close()\n\n\n# only save the residues of the file that are in thelist\ndef save_constrained(filename_in, filename_out, thelist):\n f = open(filename_in, 'r')\n f_out = open(filename_out, 'w')\n for line in f.readlines():\n if \"ATOM\" in line:\n line = line.strip()\n resname = line[23:28].strip()\n icode = \"\"\n if (not is_number(resname[len(resname) - 1])):\n icode = resname[len(resname) - 1]\n resname = resname[0:(len(resname) - 1)]\n\n resname = line[21] + \"_\" + resname + \"_\" + icode\n if resname in thelist:\n f_out.write(line + \"\\n\")\n\n\ndef getInterface(pbddir, pdbid):\n '''\n This function is used to obtain the interface of two chains\n :param pbddir: The dir of a pdb file, like '../data/5hoi.pdb'\n :return:\n '''\n str_1 = PDBParser().get_structure('first_one', pbddir) # load your molecule\n str_2 = PDBParser().get_structure('second_one', pbddir) # load your molecule\n # first obtain the chainID for the model\n model = str_1[0]\n chainID0 = []\n for chain in model:\n chainID0.append(chain.get_id())\n # obtain the combination of two chains in a pdb file\n from itertools import combinations\n chain_mix = list(combinations(chainID0, 2))\n dict0 = dict()\n for i in range(len(chain_mix)):\n ss = chain_mix[i]\n chains_1 = ss[0]\n chains_2 = ss[1]\n\n # Load the structures - they can be the same!\n atoms_1 = Selection.unfold_entities(str_1, 'C') # C for chains\n atoms_2 = Selection.unfold_entities(str_2, 'C') # C for chains\n\n # get the mapping from chain,residue id to the atom lists\n input_1 = get_atom_list(atoms_1, chains_1)\n input_2 = get_atom_list(atoms_2, chains_2)\n # get the full atom lists for neighbor search\n all_atoms_1 = get_all_atoms(input_1)\n all_atoms_2 = get_all_atoms(input_2)\n\n cutoff = 4.5\n i_cutoff = 0 #10.0 \"\"\"For most applications when you want to get the interface CONTACTS without the neighborhood just run the program with the option –i 0 – this will not add any intramolecular neighborhood to your results.\"\"\"\n # run neighbor search on both instances - not optimal but good enough for most imaginable applications.\n contacts_1 = get_contacts(input_1, all_atoms_2, \"First molecule, residue \", cutoff)\n contacts_2 = get_contacts(input_2, all_atoms_1, \"Second molecule, residue \", cutoff)\n\n # color the structures according to their new BFactors\n contact_map_1 = []\n # Color molecule 1\n for residue in contacts_1:\n for atom in input_1[residue]:\n atom.set_bfactor(100.0)\n contact_map_1.append(atom)\n\n # Color molecule 2\n contact_map_2 = []\n for residue in contacts_2:\n for atom in input_2[residue]:\n atom.set_bfactor(100.0)\n contact_map_2.append(atom)\n\n # Get interface's residues\n # run neighbor search on both instances - not optimal but good enough for most imaginable applications.\n interface_1 = contacts_1\n interface_2 = contacts_2\n\n if (i_cutoff > 0):\n interface_1 = get_contacts(input_1, contact_map_1, \"First molecule, interfacial residue \", i_cutoff)\n interface_2 = get_contacts(input_2, contact_map_2, \"Second molecule, interfacial residue \", i_cutoff)\n # some combinations may have no contact\n if interface_1:\n dict1 = {pdbid + '.' + chains_1 + '@' + chains_1 + 'and' + chains_2: interface_1}\n dict2 = {pdbid + '.' + chains_2 + '@' + chains_1 + 'and' + chains_2: interface_2}\n dict0.update(dict1)\n dict0.update(dict2)\n print(dict1, dict2, sep='\\n')\n return dict0\n\n'''\n# This is the original code used to find the interface residues\n\n#str_1 = PDBParser().get_structure('first_one', '1A2Y.pdb') # load your molecule\n#str_2 = PDBParser().get_structure('second_one', '1A2Y.pdb') # load your molecule\n# one example\nstr_1 = PDBParser().get_structure('first_one', '../data/5hoi.pdb') # load your molecule\nstr_2 = PDBParser().get_structure('second_one', '../data/5hoi.pdb') # load your molecule\nchains_1 = 'A'\nchains_2 = 'B'\n\n# Load the structures - they can be the same!\natoms_1 = Selection.unfold_entities(str_1, 'C') # C for chains\natoms_2 = Selection.unfold_entities(str_2, 'C') # C for chains\n\n# get the mapping from chain,residue id to the atom lists\ninput_1 = get_atom_list(atoms_1, chains_1)\ninput_2 = get_atom_list(atoms_2, chains_2)\n\n\n# get the full atom lists for neighbor search\nall_atoms_1 = get_all_atoms(input_1)\nall_atoms_2 = get_all_atoms(input_2)\n\ncutoff = 4.5\ni_cutoff = 0 #10.0 \"\"\"For most applications when you want to get the interface CONTACTS without the neighborhood just run the program with the option –i 0 – this will not add any intramolecular neighborhood to your results.\"\"\"\n\n# run neighbor search on both instances - not optimal but good enough for most imaginable applications.\ncontacts_1 = get_contacts(input_1, all_atoms_2, \"First molecule, residue \", cutoff)\ncontacts_2 = get_contacts(input_2, all_atoms_1, \"Second molecule, residue \", cutoff)\n\n# color the structures according to their new BFactors\ncontact_map_1 = []\n# Color molecule 1\nfor residue in contacts_1:\n for atom in input_1[residue]:\n atom.set_bfactor(100.0)\n contact_map_1.append(atom)\n\n# Color molecule 2\ncontact_map_2 = []\nfor residue in contacts_2:\n for atom in input_2[residue]:\n atom.set_bfactor(100.0)\n contact_map_2.append(atom)\n\n# Get interfacial residues\n# run neighbor search on both instances - not optimal but good enough for most imaginable applications.\ninterface_1 = contacts_1\ninterface_2 = contacts_2\n\nif (i_cutoff > 0):\n interface_1 = get_contacts(input_1, contact_map_1, \"First molecule, interfacial residue \", i_cutoff)\n interface_2 = get_contacts(input_2, contact_map_2, \"Second molecule, interfacial residue \", i_cutoff)\n'''\n\n# for simple test\ninfile = '../data/5hoi.pdb'\ngetInterface(pbddir = infile, pdbid='5hoi')\n\n\n# for a loop test\ninfile = ['../data/1A2Y.pdb','../data/5hoi.pdb']\npdbID = ['1A2Y', '5hoi']\nall_interface = dict()\nfor i in range(len(infile)):\n all_interface.update(getInterface(pbddir = infile[i], pdbid = pdbID[i]))\n\n\n# for all sce experiment files\n# Note these experiment files were downloaded on 2018-5-31\npdbfile = '/Users/luho/Documents/pdb file/PDB experimental pdb files/' # all experimental pdb files were stored in this directory\nexp_pdb_all = os.listdir(pdbfile)\n# remove the non pdb files\nexp_pdb_all0 = [x for x in exp_pdb_all if x.endswith('pdb')]\nall_interface = dict()\nfor i,x in enumerate(exp_pdb_all0):\n print(x)\n pdbID0 = x.split('.pdb')[0]\n infile0 = pdbfile + x\n all_interface.update(getInterface(pbddir=infile0, pdbid=pdbID0))\n\n\n\"\"\" \n# These script not used\n# Color molecule 1\nfor residue in interface_1:\n if residue in contacts_1:\n continue\n\n for atom in input_1[residue]:\n atom.set_bfactor(50.0)\n\n# Color interface residues on molecule 2\nfor residue in interface_2:\n if residue in contacts_2:\n continue\n for atom in input_2[residue]:\n atom.set_bfactor(50.0)\n\n#save result\ncwd = \"../result\"\nout_folder = ''\n\n# Save the contact-colored structures\nsave_contacts(str_1, chains_1, cwd + \"/\" + out_folder + \"/molecule_1.pdb\")\nsave_contacts(str_2, chains_2, cwd + \"/\" + out_folder + \"/molecule_2.pdb\")\n\n# save the interface residues\nsave_residues(cwd + \"/\" + out_folder + \"/molecule_1.txt\", interface_1, contacts_1)\nsave_residues(cwd + \"/\" + out_folder + \"/molecule_2.txt\", interface_2, contacts_2)\n\nf = open(cwd + \"/\" + out_folder + \"/parameters.txt\", 'w')\nf.write(\"The results in this folder were obtained using the following parameters:\\n\")\nf.write(\"Contact distance: \" + str(cutoff) + \"A\\n\")\nf.write(\"Interface distance: \" + str(i_cutoff) + \"A\\n\")\nf.close()\n\n\n# Constrain the pdb files to the interface residues only\n save_constrained(cwd + \"/\" + out_folder + \"/molecule_1.pdb\", cwd + \"/\" + out_folder + \"/molecule_1_constrained.pdb\",\n interface_1)\n save_constrained(cwd + \"/\" + out_folder + \"/molecule_2.pdb\", cwd + \"/\" + out_folder + \"/molecule_2_constrained.pdb\", interface_2)\n \"\"\"","sub_path":"Data_collection_of_PDB/code/interface_calculation_sce.py","file_name":"interface_calculation_sce.py","file_ext":"py","file_size_in_byte":12086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"264729476","text":"import json\nimport pandas as pd\nimport math\n\nfiles_num = 5\nstatistic_num = 6\nrepresentation_num = 5\nfoldername = \"../chart_data/bomb/\"\nisMultibrain = False;\n\njson_datas = []\njson_mean_data = []\n\ndef convertIntToStatistic(value):\n if value == 1: return \"cumulative_reward\"\n elif value == 2: return \"entropy\"\n elif value == 3: return \"episode_length\"\n elif value == 4: return \"policy_loss\"\n elif value == 5: return \"value_estimate\"\n elif value == 6: return \"value_loss\"\n else: return \"null\"\n\ndef convertIntToRepresentation(value):\n if value == 1: return \"binary_flag\"\n elif value == 2: return \"binary_normalized\"\n elif value == 3: return \"hybrid\"\n elif value == 4: return \"icaart\"\n elif value == 5: return \"zero_or_one\"\n else: return \"null\"\n\ndef convertIntToMultiBrainNameRepresentation(value):\n if value == 1: return \"BinaryMultibrain\"\n elif value == 2: return \"BinaryNormalizedMultibrain\"\n elif value == 3: return \"HybridMultibrain\"\n elif value == 4: return \"ICAARTMultibrain\"\n elif value == 5: return \"ZeroOrOneMultibrain\"\n else: return \"null\"\n\ndef getFinalFilename(statisticName, representationState, representationMultibrain, sufix_num):\n if (isMultibrain):\n return foldername + representationState + \"/\" + statisticName + \"/run_bomberman_agents_all_\" + str(sufix_num) + \"-0_Aprendiz\" + representationMultibrain + \"-tag-Info_\" + statisticName + \".json\"\n else:\n return foldername + representationState + \"/\" + statisticName + \"/run_bomberman_agents_\" + representationState + \"_\" + str(sufix_num) + \"-0-tag-Info_\" + statisticName + \".json\"\n\n\nfor representation_index in range(1, representation_num + 1):\n REPRESENTATION_STATE = convertIntToRepresentation(representation_index)\n REPRESENTATION_MULTIBRAIN = convertIntToMultiBrainNameRepresentation(representation_index)\n\n for statistic_index in range(1, statistic_num + 1):\n STATISTIC_NAME = convertIntToStatistic(statistic_index)\n\n for sufix_num in range(1, files_num + 1):\n with open(getFinalFilename(STATISTIC_NAME, REPRESENTATION_STATE, REPRESENTATION_MULTIBRAIN, sufix_num)) as datafile:\n data = json.load(datafile)\n json_datas.append(data)\n\n # dataframe = pd.DataFrame(data)\n # print(dataframe[2].mean())\n # print(len(json_datas[0]))\n # print(json_datas[0])\n # print(len(json_datas[1]))\n # print(json_datas[1])\n # print(json_datas[1][0][2])\n\n maxIteration = 0\n maxIndex = 0\n for m in range(0, files_num):\n if (len(json_datas[m]) > maxIteration):\n maxIteration = len(json_datas[m])\n maxIndex = m\n\n # calculando a média\n for i in range(0, len(json_datas[m])):\n mean_value = 0\n for j in range(0, files_num):\n if (i < len(json_datas[j])):\n mean_value = mean_value + json_datas[j][i][2]\n else:\n mean_value = mean_value + json_datas[j][len(json_datas[j]) - 1][2]\n\n mean_value = mean_value / files_num\n\n line = [0, json_datas[m][i][1], mean_value]\n json_mean_data.append(line)\n\n print(json_mean_data)\n\n # calculando o desvio padrão\n for i in range(0, len(json_datas[m])):\n mean_value = json_mean_data[i][2];\n variance = 0\n\n for j in range(0, files_num):\n if (i < len(json_datas[j])):\n variance = variance + ((json_datas[j][i][2] - mean_value) ** 2)\n else:\n variance = variance + ((json_datas[j][len(json_datas[j]) - 1][2] - mean_value) ** 2)\n\n variance = variance / (files_num-1)\n std_deviation = math.sqrt(variance)\n\n json_mean_data[i][0] = std_deviation\n\n print(json_mean_data)\n\n with open(foldername + REPRESENTATION_STATE + \"/\" + STATISTIC_NAME + \"/mean.json\", \"w\") as outfile:\n json.dump(json_mean_data, outfile)\n\n # limpando lista\n json_datas.clear()\n json_mean_data.clear()","sub_path":"chart_code/generate_mean_chart_data.py","file_name":"generate_mean_chart_data.py","file_ext":"py","file_size_in_byte":4121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"512871810","text":"from pathlib import Path\nfrom csv import DictReader\nimport ast\nimport time\nimport pickle\n\nFIRST_TWEETS_FILE = '_first/first_27k_potencial_cb.txt'\nSECOND_TWEETS_DIR = '_second/'\n\np = Path(SECOND_TWEETS_DIR)\nfiles = list(p.glob('*potencial*'))\n\nout_tweets = []\nheader = True\n\ntweet_repeated = []\nusers_repeated = []\n\n''' first get all the users and tweets already taken from first execution '''\nwith open(FIRST_TWEETS_FILE, 'r') as f:\n reader = DictReader(f, delimiter='\\t', fieldnames=['id', 'created_at', 'sender_id', 'sender_name', 'mentioned',\n 'text', 'hashtags'])\n for row in reader:\n if header:\n header = False\n else:\n if row['id'] not in tweet_repeated:\n tweet_repeated.append(row['id'])\n if row['sender_id'] not in users_repeated:\n users_repeated.append(row['sender_id'])\n\n\n''' for all the other tweets that weren't extracted from first execution, obtain them and sort by user and date '''\nheader = True\nerrors = 0\nfor filename in files:\n with open(str(filename), 'r') as f:\n reader = DictReader(f, delimiter='\\t', fieldnames=['id', 'created_at', 'sender_id', 'sender_name', 'mentioned',\n 'text', 'hashtags'])\n for row in reader:\n try:\n if header:\n header = False\n # elif row['id'] not in out_tweets and row['id'] not in tweet_repeated and row['sender_id'] not in users_repeated:\n elif row['id'] not in tweet_repeated and row['sender_id'] not in users_repeated:\n out_tweets.append({'id': row['id'],\n 'created_at': time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(row['created_at'], '%a %b %d %H:%M:%S +0000 %Y')),\n 'sender_id': row['sender_id'],\n 'sender_name': row['sender_name'], 'text': row['text'],\n 'mentioned': ast.literal_eval(row['mentioned']),\n 'hashtags': ast.literal_eval(row['hashtags'])})\n tweet_repeated.append(row['id'])\n except ValueError:\n errors += 1\n continue\n\nprint(errors)\nprint(len(out_tweets))\npickle.dump(out_tweets, open(\"tweets_unrepeated.pkl\", \"wb\"))\n","sub_path":"datasets/pt_cyber/pt_pt_tweetsUpdate.py","file_name":"pt_pt_tweetsUpdate.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"115376127","text":"\"\"\"List virtual servers.\"\"\"\n# :license: MIT, see LICENSE for more details.\n\nimport SoftLayer\nfrom SoftLayer.CLI import columns as column_helper\nfrom SoftLayer.CLI import environment\nfrom SoftLayer.CLI import formatting\nfrom SoftLayer.CLI import helpers\n\nimport click\n\n# pylint: disable=unnecessary-lambda\n\nCOLUMN_MAP = {\n 'guid': ('globalIdentifier',),\n 'primary_ip': ('primaryIpAddress',),\n 'backend_ip': ('primaryBackendIpAddress',),\n 'datacenter': ('datacenter', 'name'),\n 'action': lambda guest: formatting.active_txn(guest),\n 'power_state': ('powerState', 'name'),\n}\n\n\n@click.command()\n@click.option('--sortby', help='Column to sort by', default='hostname')\n@click.option('--cpu', '-c', help='Number of CPU cores', type=click.INT)\n@click.option('--domain', '-D', help='Domain portion of the FQDN')\n@click.option('--datacenter', '-d', help='Datacenter shortname')\n@click.option('--hostname', '-H', help='Host portion of the FQDN')\n@click.option('--memory', '-m', help='Memory in mebibytes', type=click.INT)\n@click.option('--network', '-n', help='Network port speed in Mbps')\n@click.option('--hourly', is_flag=True, help='Show only hourly instances')\n@click.option('--monthly', is_flag=True, help='Show only monthly instances')\n@helpers.multi_option('--tag', help='Filter by tags')\n@click.option('--columns',\n callback=column_helper.get_formatter(COLUMN_MAP),\n help='Columns to display. default is id, hostname, primary_ip, '\n 'backend_ip, datacenter, action',\n default=\"id,hostname,primary_ip,backend_ip,datacenter,action\")\n@environment.pass_env\ndef cli(env, sortby, cpu, domain, datacenter, hostname, memory, network,\n hourly, monthly, tag, columns):\n \"\"\"List virtual servers.\"\"\"\n\n vsi = SoftLayer.VSManager(env.client)\n guests = vsi.list_instances(hourly=hourly,\n monthly=monthly,\n hostname=hostname,\n domain=domain,\n cpus=cpu,\n memory=memory,\n datacenter=datacenter,\n nic_speed=network,\n tags=tag)\n\n table = formatting.Table(columns.columns)\n table.sortby = sortby\n\n for guest in guests:\n table.add_row([value or formatting.blank()\n for value in columns.row(guest)])\n\n env.fout(table)\n","sub_path":"SoftLayer/CLI/virt/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"448944441","text":"from django.shortcuts import render, redirect\nfrom .luhn import find_check_digit, verify_number\nfrom .forms import FindCheckDigitForm, VerifyNumberForm\n\n# Create your views here.\ndef index(request):\n context = {}\n if request.method == 'POST' and 'btn_check_digit' in request.POST:\n digit_form = FindCheckDigitForm(request.POST)\n cardno_form = VerifyNumberForm()\n if digit_form.is_valid():\n string_number = digit_form.cleaned_data['number']\n check_digit = find_check_digit(string_number)\n context.update({'check_digit': check_digit, 'string_number': string_number})\n elif request.method == 'POST' and 'btn_verify' in request.POST:\n digit_form = FindCheckDigitForm()\n cardno_form = VerifyNumberForm(request.POST)\n if cardno_form.is_valid():\n string_number = cardno_form.cleaned_data['card_number']\n validity = verify_number(string_number)\n context.update({'validity': validity, 'string_number': string_number})\n else:\n digit_form = FindCheckDigitForm()\n cardno_form = VerifyNumberForm()\n context['digit_form'],context['cardno_form'] = digit_form, cardno_form\n return render(request, 'index.html', context)\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"605969262","text":"#! /usr/bin/env python\nfrom __future__ import print_function, division\n\ntry:\n import matplotlib as mpl\n mpl.use('Agg')\n import matplotlib.pyplot as plt\n can_plot = True\nexcept ImportError:\n can_plot = False\n\nfrom distutils.dir_util import mkpath\nfrom distutils.errors import DistutilsFileError\nimport logging\nimport numpy as np\nimport sys\nfrom emcee.utils import MPIPool\nsys.path.insert(0, '..')\nimport chronostar.expectmax as em\nimport chronostar.retired2.datatool as dt\n\ntry:\n run_name = sys.argv[1]\nexcept:\n run_name = 'dummy'\n\ntry:\n rdir = \"/data/mash/tcrun/em_fit/{}/\".format(run_name)\n path_msg = \"Storing data on mash data server\"\n mkpath(rdir)\nexcept (IOError, DistutilsFileError):\n path_msg = (\"I'm guessing you're not Tim Crundall...\"\n \"or not on an RSAA server\")\n rdir = \"../results/em_fit/{}/\".format(run_name)\n mkpath(rdir)\n\nlogging.basicConfig(\n level=logging.INFO,\n filename=rdir + 'em.log',\n filemode='a'\n)\n\n# Initialize the MPI-based pool used for parallisation.\nusing_mpi = True\ntry:\n pool = MPIPool()\n logging.info(\"Successfully initialised mpi pool\")\nexcept:\n #print(\"MPI doesn't seem to be installed... maybe install it?\")\n logging.info(\"MPI doesn't seem to be installed... maybe install it?\")\n using_mpi = False\n pool=None\nif using_mpi:\n if not pool.is_master():\n print(\"One thread is going to sleep\")\n # Wait for instructions from the master process.\n pool.wait()\n sys.exit(0)\nprint(\"Only one thread is master\")\n\nlogging.info(path_msg)\nprint(\"Master should be working in the directory:\\n{}\".format(rdir))\n\n# # Setting up standard filenames\n# # Partial data generation saved in results/em_fit/[run_name]/synth_data/\n# sd_dir = rdir + 'synth_data/'\n# mkpath(sd_dir)\n# xyzuvw_perf_file = sd_dir + 'perf_xyzuvw.npy'\n# groups_savefile = sd_dir + 'origins.npy'\n# xyzuvw_init_savefile = sd_dir + 'xyzuvw_init.npy'\n# astro_savefile = sd_dir + 'astro_table.txt'\n\n# Final XYZUVW data file stored in chronostar/data/ to replicate\n# treatment of real data\nxyzuvw_conv_savefile = '../data/{}_xyzuvw.fits'.format(run_name)\n\n# Calculate the initial parameters for each component that correspond\n# to the current day mean of mean_now\n# logging.info(\"---------- Generating synthetic data...\")\n# ERROR = 1.0\n# BG_DENS = 0 # 1.0e-7 # background density for synth bg stars\n# logging.info(\" with error fraction {}\".format(ERROR))\n# logging.info(\" and background density {}\".format(BG_DENS))\n# # Set a current-day location around which synth stars will end up\n# mean_now = np.array([50., -100., -0., -10., -20., -5.])\n# extra_pars = np.array([\n# #dX, dV, age, nstars\n# [10., 5., 7., 100.],\n# [ 2., 5., 10., 20.],\n# # [ 5., 0.7, 10., 50.],\n# # [100., 50., 1e-5, 1000.],\n# ])\n# logging.info(\"Mean (now):\\n{}\".format(mean_now))\n# logging.info(\"Extra pars:\\n{}\".format(extra_pars))\n# ngroups = extra_pars.shape[0]\n#\n# try:\n# all_xyzuvw_now_perf = np.load(xyzuvw_perf_file)\n# origins = dt.loadGroups(groups_savefile)\n# star_pars = dt.loadXYZUVW(xyzuvw_conv_savefile)\n# logging.info(\"Loaded synth data from previous run\")\n# except IOError:\n# all_xyzuvw_init = np.zeros((0,6))\n# all_xyzuvw_now_perf = np.zeros((0,6))\n# origins = []\n# for i in range(ngroups):\n# logging.info(\" generating from group {}\".format(i))\n# # MANUALLY SEPARATE CURRENT DAY DISTROS IN DIMENSION X\n# mean_now_w_offset = mean_now.copy()\n# mean_now_w_offset[0] += i * 50\n#\n# mean_then = torb.traceOrbitXYZUVW(mean_now_w_offset, -extra_pars[i,-2],\n# single_age=True)\n# group_pars = np.hstack((mean_then, extra_pars[i]))\n# xyzuvw_init, origin = syn.synthesiseXYZUVW(group_pars, sphere=True,\n# return_group=True,\n# internal=False)\n# origins.append(origin)\n# all_xyzuvw_init = np.vstack((all_xyzuvw_init, xyzuvw_init))\n# xyzuvw_now_perf = torb.traceManyOrbitXYZUVW(xyzuvw_init,\n# times=origin.age,\n# single_age=True)\n# all_xyzuvw_now_perf = np.vstack((all_xyzuvw_now_perf, xyzuvw_now_perf))\n#\n# # insert 'background stars' with density 1.2e-7\n# ubound = np.max(all_xyzuvw_now_perf, axis=0)\n# lbound = np.min(all_xyzuvw_now_perf, axis=0)\n# margin = 0.5 * (ubound - lbound)\n# ubound += margin\n# lbound -= margin\n# nbg_stars = int(BG_DENS * np.prod(ubound - lbound))\n#\n# # centre bg stars on mean of assoc stars\n# centre = np.mean(all_xyzuvw_now_perf, axis=0)\n# spread = ubound - lbound\n# bg_stars_xyzuvw_perf =\\\n# np.random.uniform(-1,1,size=(nbg_stars, 6)) * spread + centre\n# logging.info(\"Using background density of {}\".format(BG_DENS))\n# logging.info(\"Generated {} background stars\".format(nbg_stars))\n# logging.info(\"Spread from {}\".format(ubound))\n# logging.info(\" to {}\".format(lbound))\n#\n# all_xyzuvw_now_perf = np.vstack((all_xyzuvw_now_perf, bg_stars_xyzuvw_perf))\n#\n# np.save(groups_savefile, origins)\n# np.save(xyzuvw_perf_file, all_xyzuvw_now_perf)\n# astro_table = ms.measureXYZUVW(all_xyzuvw_now_perf, error_frac=ERROR,\n# savefile=astro_savefile)\n# star_pars = cv.convertMeasurementsToCartesian(\n# astro_table, savefile=xyzuvw_conv_savefile,\n# )\n# logging.info(\"Synthesis complete\")\n#\n#\n#\n# # make sure stars are initialised as expected\n# if can_plot:\n# for dim1, dim2 in ('xy', 'xu', 'yv', 'zw', 'uv'):\n# plt.clf()\n# true_memb = dt.getZfromOrigins(origins, star_pars)\n# fp.plotPaneWithHists(dim1,dim2,groups=origins,\n# weights=[origin.nstars for origin in origins],\n# star_pars=star_pars,\n# group_now=True,\n# membership=true_memb,\n# true_memb=true_memb)\n# plt.savefig(rdir + 'pre_plot_{}{}.pdf'.format(dim1, dim2))\n\nstar_pars = dt.loadXYZUVW(xyzuvw_conv_savefile)\n\nMAX_COMP = 6\nncomps = 1\n\n# Set up initial values of results\nprev_groups = None\nprev_meds = None\nprev_lnpost = -np.inf\nprev_BIC = np.inf\nprev_lnlike = -np.inf\nprev_z = None\n#\n# # Initialise z\n# nstars = star_pars['xyzuvw'].shape[0]\n# nassoc_stars = np.sum([o.nstars for o in origins])\n# nbg_stars = int(nstars - nassoc_stars)\n# init_z = np.zeros((nstars, 2))\n\n# basing initial z on having 80% identified association members and 3\n# interlopers\n# assoc_ix = np.arange(nassoc_stars)\n# bg_ix = np.arange(nassoc_stars, nbg_stars + nassoc_stars)\n# frac_assoc_identified = 0.8\n# ninterlopers = 3\n# random.shuffle(assoc_ix)\n# random.shuffle(bg_ix)\n# assoc_identified_ix = int(frac_assoc_identified * nassoc_stars)\n# init_z[assoc_ix[:assoc_identified_ix],0] = 1.0\n# init_z[bg_ix[:ninterlopers],0] = 1.0\n# init_z[assoc_ix[assoc_identified_ix:],1] = 1.0\n# init_z[bg_ix[ninterlopers:],1] = 1.0\n#\n# logging.info(\"Init Z:\\n{}\".format(init_z))\n\n# Manually set background log overlaps to be equal to that of bg density\nBG_DENS = np.load(rdir + 'synth_data/bg_density.npy').item()\nnstars = len(star_pars['xyzuvw'])\nif BG_DENS != 0.:\n bg_ln_ols = np.log(np.zeros(nstars) + BG_DENS)\nelse:\n bg_ln_ols = None\n\nwhile ncomps < MAX_COMP:\n # handle special case of one component\n if ncomps == 1:\n logging.info(\"******************************************\")\n logging.info(\"********* FITTING 1 COMPONENT **********\")\n logging.info(\"******************************************\")\n run_dir = rdir + '{}/'.format(ncomps)\n mkpath(run_dir)\n\n try:\n new_groups = dt.loadGroups(run_dir + 'final/final_groups.npy')\n new_meds = np.load(run_dir + 'final/final_med_errs.npy')\n new_z = np.load(run_dir + 'final/final_membership.npy')\n logging.info(\"Loaded from previous run\")\n except IOError:\n new_groups, new_meds, new_z =\\\n em.fit_many_comps(star_pars, ncomps, rdir=run_dir, pool=pool,\n bg_dens=BG_DENS,\n )\n new_groups = np.array(new_groups)\n\n new_lnlike = em.get_overall_lnlikelihood(star_pars, new_groups,\n bg_ln_ols=bg_ln_ols)\n new_lnpost = em.get_overall_lnlikelihood(star_pars, new_groups,\n bg_ln_ols=bg_ln_ols,\n inc_posterior=True)\n new_BIC = em.calc_bic(star_pars, ncomps, new_lnlike)\n # handle multiple components\n else:\n logging.info(\"******************************************\")\n logging.info(\"********* FITTING {} COMPONENTS *********\".\\\n format(ncomps))\n logging.info(\"******************************************\")\n best_fits = []\n lnlikes = []\n lnposts = []\n BICs = []\n all_meds = []\n all_zs = []\n\n # iteratively try subdividing each previous group\n for i, split_group in enumerate(prev_groups):\n logging.info(\"-------- decomposing {}th component ---------\".\\\n format(i))\n run_dir = rdir + '{}/{}/'.format(ncomps, chr(ord('A') + i))\n mkpath(run_dir)\n\n # Decompose and replace the ith group with two new groups\n # by using the 16th and 84th percentile ages from chain\n _, split_groups = em.decomposeGroup(split_group,\n young_age = prev_meds[i,-1,1],\n old_age = prev_meds[i,-1,2])\n init_groups = list(prev_groups)\n init_groups.pop(i)\n init_groups.insert(i, split_groups[1])\n init_groups.insert(i, split_groups[0])\n\n # run em fit\n try:\n groups = dt.loadGroups(run_dir + 'final/final_groups.npy')\n meds = np.load(run_dir + 'final/final_med_errs.npy')\n z = np.load(run_dir + 'final/final_membership.npy')\n logging.info(\"Fit loaded from previous run\")\n except IOError:\n groups, meds, z = \\\n em.fit_many_comps(star_pars, ncomps, rdir=run_dir, pool=pool,\n init_comps=init_groups,\n bg_dens=BG_DENS,\n correction_factor=1.0)\n best_fits.append(groups)\n all_meds.append(meds)\n all_zs.append(z)\n\n lnlike = em.get_overall_lnlikelihood(star_pars, groups,\n bg_ln_ols=bg_ln_ols)\n lnlikes.append(lnlike)\n lnposts.append(em.get_overall_lnlikelihood(star_pars, groups,\n bg_ln_ols=bg_ln_ols,\n inc_posterior=True))\n BICs.append(em.calc_bic(star_pars, ncomps, lnlike))\n logging.info(\"Decomp finished with\\nBIC: {}\\nLnlike: {}\\nLnpost\".format(\n BICs[-1], lnlikes[-1], lnposts[-1],\n ))\n\n # identify the best performing decomposition\n #best_split_ix = np.argmax(lnposts)\n best_split_ix = np.argmin(BICs)\n new_groups, new_meds, new_z, new_lnlike, new_lnpost, new_BIC = \\\n zip(best_fits, all_meds, all_zs,\n lnlikes, lnposts, BICs)[best_split_ix]\n logging.info(\"Selected {} as best decomposition\".format(best_split_ix))\n logging.info(\"Turned\\n{}\".format(\n prev_groups[best_split_ix].getInternalSphericalPars()))\n logging.info(\"into\\n{}\\n&\\n{}\".format(\n new_groups[best_split_ix].getInternalSphericalPars(),\n new_groups[best_split_ix+1].getInternalSphericalPars(),\n ))\n\n # Check if the fit has improved\n if new_BIC < prev_BIC:\n logging.info(\"Extra component has improved BIC...\")\n logging.info(\"New BIC: {} < Old BIC: {}\".format(new_BIC, prev_BIC))\n logging.info(\"lnlike: {} | {}\".format(new_lnlike, prev_lnlike))\n logging.info(\"lnpost: {} | {}\".format(new_lnpost, prev_lnpost))\n prev_groups, prev_meds, prev_z, prev_lnlike, prev_lnpost, \\\n prev_BIC = \\\n (new_groups, new_meds, new_z, new_lnlike, new_lnpost, new_BIC)\n ncomps += 1\n else:\n logging.info(\"Extra component has worsened BIC...\")\n logging.info(\"New BIC: {} > Old BIC: {}\".format(new_BIC, prev_BIC))\n logging.info(\"lnlike: {} | {}\".format(new_lnlike, prev_lnlike))\n logging.info(\"lnpost: {} | {}\".format(new_lnpost, prev_lnpost))\n logging.info(\"... saving previous fit as best fit to data\")\n np.save(rdir+'final_best_groups.npy', prev_groups)\n np.save(rdir+'final_med_errs.npy', prev_meds)\n np.save(rdir+'final_membership.npy', prev_z)\n np.save(rdir+'final_likelihood_post_and_bic', [prev_lnlike, prev_lnpost,\n prev_BIC])\n logging.info('Final best fits:')\n [logging.info(g.getSphericalPars()) for g in prev_groups]\n logging.info('Final age med and span:')\n [logging.info(row[-1]) for row in prev_meds]\n logging.info('Membership distribution: {}'.format(prev_z.sum(axis=0)))\n logging.info('Final membership:')\n logging.info('\\n',np.round(prev_z*100))\n logging.info('Final lnlikelihood: {}'.format(prev_lnlike))\n logging.info('Final lnposterior: {}'.format(prev_lnpost))\n logging.info('Final BIC: {}'.format(prev_BIC))\n break\n\n logging.info(\"Best fit:\\n{}\".format(\n [group.getInternalSphericalPars() for group in prev_groups]))\n\nif using_mpi:\n pool.close()\n","sub_path":"scripts/retired/perform_incremental_em_synth_fit.py","file_name":"perform_incremental_em_synth_fit.py","file_ext":"py","file_size_in_byte":14054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"46620360","text":"def fibonacci(n):\n if n == 0 or n == 1:\n return n\n else:\n return fibonacci(n - 1) + fibonacci(n - 2)\n\n\nprint(fibonacci(10))\n\ndef fibonacci_v2(n):\n a = 0\n b = 1\n \n if n < 0:\n print(\"Incorrect input\")\n elif n == 0:\n return 0\n elif n == 1:\n return b\n else:\n for i in range(1, n):\n c = a + b\n a = b\n b = c\n return b\n\nprint(fibonacci_v2(10))\n","sub_path":"exe_43_func_fibonacci.py","file_name":"exe_43_func_fibonacci.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"248169307","text":"\"\"\"\nAuthor: Isabella Liu 4/28/21\nFeature: Hourglass and PSMNet (stacked hourglass) module\n\"\"\"\n\nimport math\n\nfrom nets.psmnet_submodule import *\n\n\nclass hourglass(nn.Module):\n def __init__(self, inplanes):\n super(hourglass, self).__init__()\n\n self.conv1 = nn.Sequential(\n convbn_3d(inplanes, inplanes * 2, kernel_size=3, stride=2, pad=1),\n nn.ReLU(inplace=True)\n )\n\n self.conv2 = convbn_3d(inplanes * 2, inplanes * 2, kernel_size=3, stride=1, pad=1)\n\n self.conv3 = nn.Sequential(\n convbn_3d(inplanes * 2, inplanes * 2, kernel_size=3, stride=2, pad=1),\n nn.ReLU(inplace=True)\n )\n\n self.conv4 = nn.Sequential(\n convbn_3d(inplanes * 2, inplanes * 2, kernel_size=3, stride=1, pad=1),\n nn.ReLU(inplace=True)\n )\n\n self.conv5 = nn.Sequential(\n nn.ConvTranspose3d(inplanes * 2, inplanes * 2, kernel_size=3, padding=1, output_padding=1, stride=2,\n bias=False),\n nn.BatchNorm3d(inplanes * 2)\n )\n\n self.conv6 = nn.Sequential(\n nn.ConvTranspose3d(inplanes * 2, inplanes, kernel_size=3, padding=1, output_padding=1, stride=2,\n bias=False),\n nn.BatchNorm3d(inplanes)\n )\n\n def forward(self, x, presqu, postqu):\n out = self.conv1(x)\n pre = self.conv2(out)\n if postqu is not None:\n pre = F.relu(pre + postqu, inplace=True)\n else:\n pre = F.relu(pre, inplace=True)\n\n out = self.conv3(pre)\n out = self.conv4(out)\n\n if presqu is not None:\n post = F.relu(self.conv5(out) + presqu, inplace=True)\n else:\n post = F.relu(self.conv5(out) + pre, inplace=True)\n\n out = self.conv6(post)\n return out, pre, post\n\n\nclass PSMNet(nn.Module):\n def __init__(self, maxdisp):\n super(PSMNet, self).__init__()\n self.maxdisp = maxdisp\n\n self.feature_extraction = FeatureExtraction(False)\n \n self.dres0 = nn.Sequential(\n convbn_3d(64, 32, 3, 1, 1),\n nn.ReLU(inplace=True),\n convbn_3d(32, 32, 3, 1, 1),\n nn.ReLU(inplace=True)\n )\n self.dres1 = nn.Sequential(\n convbn_3d(32, 32, 3, 1, 1),\n nn.ReLU(inplace=True),\n convbn_3d(32, 32, 3, 1, 1)\n )\n\n self.dres2 = hourglass(32)\n self.dres3 = hourglass(32)\n self.dres4 = hourglass(32)\n\n self.classif1 = nn.Sequential(\n convbn_3d(32, 32, 3, 1, 1),\n nn.ReLU(inplace=True),\n nn.Conv3d(32, 1, kernel_size=3, padding=1, stride=1, bias=False)\n )\n self.classif2 = nn.Sequential(\n convbn_3d(32, 32, 3, 1, 1),\n nn.ReLU(inplace=True),\n nn.Conv3d(32, 1, kernel_size=3, padding=1, stride=1, bias=False)\n )\n self.classif3 = nn.Sequential(\n convbn_3d(32, 32, 3, 1, 1),\n nn.ReLU(inplace=True),\n nn.Conv3d(32, 1, kernel_size=3, padding=1, stride=1, bias=False)\n )\n\n # for m in self.modules():\n # if type(m) == (nn.Conv2d or nn.Conv3d or nn.Linear) :\n # torch.nn.init.xavier_uniform_(m.weight)\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.Conv3d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.kernel_size[2] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm3d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n m.bias.data.zero_()\n\n\n def forward(self, img_L, img_R):\n refimg_feature = self.feature_extraction(img_L) # [bs, 32, H/4, W/4]\n targetimg_feature = self.feature_extraction(img_R)\n\n # Cost Volume\n [bs, feature_size, H, W] = refimg_feature.size()\n cost = torch.FloatTensor(bs, feature_size * 2, self.maxdisp // 4, H, W).zero_().cuda()\n\n for i in range(self.maxdisp // 4):\n if i > 0:\n cost[:, :feature_size, i, :, i:] = refimg_feature[:, :, :, i:]\n cost[:, feature_size:, i, :, i:] = targetimg_feature[:, :, :, :-i]\n else:\n cost[:, :feature_size, i, :, :] = refimg_feature\n cost[:, feature_size:, i, :, :] = targetimg_feature\n cost = cost.contiguous() # [bs, fs*2, max_disp/4, H/4, W/4]\n\n cost0 = self.dres0(cost)\n cost0 = self.dres1(cost0) + cost0\n\n out1, pre1, post1 = self.dres2(cost0, None, None)\n out1 = out1 + cost0\n\n out2, pre2, post2 = self.dres3(out1, pre1, post1)\n out2 = out2 + cost0\n\n out3, pre3, post3 = self.dres4(out2, pre1, post2)\n out3 = out3 + cost0\n\n cost1 = self.classif1(out1)\n cost2 = self.classif2(out2) + cost1\n cost3 = self.classif3(out3) + cost2\n\n if self.training:\n # cost1 = F.upsample(cost1, [self.maxdisp,img_L.size()[2],img_L.size()[3]], mode='trilinear')\n # cost2 = F.upsample(cost2, [self.maxdisp,img_L.size()[2],img_L.size()[3]], mode='trilinear')\n cost1 = F.interpolate(cost1, (self.maxdisp, 4 * H, 4 * W), mode='trilinear', align_corners=False)\n cost2 = F.interpolate(cost2, (self.maxdisp, 4 * H, 4 * W), mode='trilinear', align_corners=False)\n\n cost1 = torch.squeeze(cost1, 1)\n pred1 = F.softmax(cost1, dim=1)\n pred1 = DisparityRegression(self.maxdisp)(pred1)\n\n cost2 = torch.squeeze(cost2, 1)\n pred2 = F.softmax(cost2, dim=1)\n pred2 = DisparityRegression(self.maxdisp)(pred2)\n\n # cost3 = F.upsample(cost3, [self.maxdisp,img_L.size()[2],img_L.size()[3]], mode='trilinear')\n cost3 = F.interpolate(cost3, (self.maxdisp, 4 * H, 4 * W), mode='trilinear', align_corners=False)\n cost3 = torch.squeeze(cost3, 1)\n pred3 = F.softmax(cost3, dim=1)\n\n # For your information: This formulation 'softmax(c)' learned \"similarity\"\n # while 'softmax(-c)' learned 'matching cost' as mentioned in the paper.\n # However, 'c' or '-c' do not affect the performance because feature-based cost volume provided flexibility.\n pred3 = DisparityRegression(self.maxdisp)(pred3)\n\n if self.training:\n return pred1, pred2, pred3\n else:\n return pred3\n\n\nif __name__ == '__main__':\n # Test PSMNet\n model = PSMNet(maxdisp=192).cuda()\n model.eval()\n img_L = torch.rand(1, 3, 256, 512).cuda()\n img_R = torch.rand(1, 3, 256, 512).cuda()\n pred = model(img_L, img_R)\n print(f'pred shape {pred.shape}') # pred shape torch.Size([1, 1, 256, 512])","sub_path":"nets/psmnet.py","file_name":"psmnet.py","file_ext":"py","file_size_in_byte":7066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"133241643","text":"import numpy as np\nimport time\n\nfrom math import log\n\nimport sys\nsys.path.append('..')\n\nfrom datasets.get_data import get_dataset\nfrom utils import discretize\n\ndef cal_shanno_ent(train_y):\n num_entries = len(train_y)\n label_count = dict()\n\n for idx in range(len(train_y)):\n if train_y[idx] not in label_count:\n label_count[train_y[idx]] = 0\n label_count[train_y[idx]] += 1\n\n entropy = 0\n\n for key in label_count:\n prob = float(label_count[key] / num_entries)\n entropy -= prob * log(prob, 2)\n \n return entropy\n\n\n# H: entropy; D: training set; A: feature A\ndef cal_H_D_A(D_x_A, D_y):\n '''\n calculate empirical entropy\n :param D_x_A: train set X with only feature A (discrete)\n :param D_y: train set Y\n :return empirical entropy of A\n '''\n H_D_A = 0\n train_X_set = set([label for label in D_x_A])\n train_Y_set = set([label for label in D_y])\n\n D = len(D_x_A)\n for i in train_X_set:\n Di = 0\n for label in D_x_A:\n if label == i:\n Di += 1\n ratio = Di / D\n for k in train_Y_set:\n Dik = 0\n for idx in range(D):\n if D_x_A[idx] == i and D_y[idx] == k:\n Dik += 1\n prob = Dik / Di\n if Dik != 0:\n H_D_A -= ratio * prob * log(prob, 2)\n return H_D_A\n\n\ndef cal_H_A_D(A, D_x):\n '''\n get H_A(D)\n :param A: the index of the feature A\n :param D_x: training set X \n '''\n\n result = 0\n\n total_entries = len(D_x) + 1\n\n feature_value_dict = dict()\n\n for instance in D_x:\n if instance[A] in feature_value_dict:\n feature_value_dict[instance[A]] += 1\n else:\n feature_value_dict[instance[A]] = 1\n for value in feature_value_dict.values():\n prob = value / total_entries\n result -= prob * log(prob, 2)\n return result\n\ndef get_best_feature(D_x, D_y):\n '''\n get the feature with higest information gain\n :param D_x: training X set\n :param D_y: training Y set\n return feature idx\n '''\n\n # discrete_x = discretize(D_x, 10)\n D_x = np.array(D_x)\n D_y = np.array(D_y).T\n\n discrete_x = D_x\n\n feature_num = D_x.shape[1]\n\n max_G_R_D_A = -1\n max_feature = -1\n\n H_D = cal_shanno_ent(D_y)\n # print(H_D)\n for feature in range(feature_num):\n\n temp = np.array(discrete_x[:, feature].flat)\n G_D_A = H_D - cal_H_D_A(temp, D_y)\n G_R_D_A = G_D_A / cal_H_A_D(feature, D_x)\n # G_R_D_A = G_D_A\n # print(G_D_A, feature)\n if G_R_D_A > max_G_R_D_A:\n max_G_R_D_A = G_R_D_A\n max_feature = feature\n return max_feature, max_G_R_D_A\n\n\ndef majorClass(label_arr):\n '''\n get the major label in the given label set\n :param label_arr: label set\n :return: the major label\n '''\n class_dict = {}\n for i in range(len(label_arr)):\n if label_arr[i] in class_dict.keys():\n class_dict[label_arr[i]] += 1\n else:\n class_dict[label_arr[i]] = 1\n class_sort = sorted(class_dict.items(), key=lambda x: x[1], reverse=True)\n \n return class_sort[0][0]\n\n\ndef get_subdata_array(train_x, train_y, A, a):\n '''\n update dataset\n :param train_x, train_y: dataset\n :param A: the index of the eliminting feature\n :param a: if data[A] == a, then keep the line\n :return: new dataset\n '''\n retDataArr = []\n retLabelArr = []\n\n for i in range(len(train_x)):\n if train_x[i][A] == a:\n retDataArr.append(np.concatenate([train_x[i][0:A],train_x[i][A+1:]]))\n retLabelArr.append(train_y[i])\n\n return retDataArr, retLabelArr\n\n\ndef create_tree(*dataSet):\n '''\n recursively create decision tree\n :param dataSet: (train_x, train_y)\n :return: ??\n '''\n\n Epsilon = 0.01\n\n train_x = dataSet[0][0]\n train_y = dataSet[0][1]\n\n if len(train_x) == 0:\n return 0\n print('start a node: ', len(train_x[0]), len(train_y))\n\n classDict = {i for i in train_y}\n\n if len(classDict) == 0:\n return majorClass(train_y)\n elif len(classDict) == 1:\n return train_y[0]\n else:\n Ag, EpsilonGet = get_best_feature(train_x, train_y)\n if EpsilonGet < Epsilon:\n return majorClass(train_y)\n\n treeDict = {Ag:{}}\n\n treeDict[Ag][0] = create_tree(get_subdata_array(train_x, train_y, Ag, 0))\n treeDict[Ag][1] = create_tree(get_subdata_array(train_x, train_y, Ag, 1))\n treeDict[Ag][2] = create_tree(get_subdata_array(train_x, train_y, Ag, 2))\n treeDict[Ag][3] = create_tree(get_subdata_array(train_x, train_y, Ag, 3))\n treeDict[Ag][4] = create_tree(get_subdata_array(train_x, train_y, Ag, 4))\n\n\n return treeDict\n\n\ndef predict(test_x, tree):\n # test_x = test_x.tolist()\n while True:\n (key, value), = tree.items()\n\n if type(tree[key]).__name__ == 'dict':\n dataVal = test_x[key]\n\n test_x = np.concatenate([test_x[0:key],test_x[key+1:]])\n\n tree = value[dataVal]\n # print(tree)\n\n if type(tree).__name__ != 'dict':\n return tree\n else:\n return value\n\ndef test(test_x, test_y, tree):\n \n error_cnt = 0\n for i in range(len(test_x)):\n\n if test_y[i] != predict(test_x[i], tree):\n error_cnt += 1\n\n return 1 - error_cnt / len(test_x)\n\n\nif __name__ == '__main__':\n start = time.time()\n\n cancer_set_info = get_dataset('breast_cancer')\n train_x, test_x, train_y, test_y = cancer_set_info.split()\n\n train_x = discretize(train_x, 5)\n tree = create_tree((train_x, train_y))\n\n print('tree:{}'.format(tree))\n test_x = discretize(test_x, 5)\n acc = test(test_x, test_y, tree)\n # acc = test(train_x, train_y, tree)\n print('accuracy is {}'.format(acc))\n\n end = time.time()\n print('time spent:{}'.format(end-start))\n\n\n","sub_path":"5.decision_tree/C45.py","file_name":"C45.py","file_ext":"py","file_size_in_byte":5925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"645641556","text":"import json\nfrom bs4 import BeautifulSoup\nfrom tqdm import tqdm\nfrom common import cache_request\n\n\ndef get_locality_ids():\n page = cache_request('https://vote.elections.virginia.gov/VoterInformation/PublicContactLookup')\n soup = BeautifulSoup(page, 'lxml')\n return [option['value'] for option in soup.select('select>option') if option['value']]\n\n\ndef get_locality_datum(id_):\n page = cache_request(\n 'https://vote.elections.virginia.gov/VoterInformation/PublicContactLookup',\n method='POST',\n data={'LocalityUid': id_},\n wait=2,\n )\n soup = BeautifulSoup(page, 'lxml')\n keys = soup.select('.resultsWrapper')[0].select('h5.display-lable')\n vals = soup.select('.resultsWrapper')[0].select('p.display-field')\n results = {key.text.strip(): val.text.strip() for key, val in zip(keys, vals)}\n locale = soup.select('select > option[selected=\"selected\"]')[0].text.title()\n final = {\n 'locale': locale,\n 'county': locale if locale.endswith('County') else None,\n 'city': locale if not locale.endswith('County') else None,\n 'official': results['Registrar'],\n 'emails': [results['Email']],\n 'faxes': [results['Fax']],\n 'url': results.get('URL'),\n 'address': results.get('Mailing Address') or results.get('Address'),\n 'physicalAddress': results.get('Physical Address'),\n }\n return {k: v for k, v in final.items() if v}\n\n\nif __name__ == '__main__':\n ids = get_locality_ids()\n\n locality_data = [get_locality_datum(id_) for id_ in tqdm(ids)]\n with open('public/virginia.json', 'w') as fh:\n json.dump(locality_data, fh)\n","sub_path":"states/virginia/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"255762798","text":"#encoding: UTF-8\n#Autor: Manuel Alejandro Bracho Mendoza\n#Matricula del autor: A01378897\n#Ejercicio n°1 de la tarea 4\n\ndef conversorDeNumeroARomano(numeroParaFuncion):\n if numeroParaFuncion < 4:\n numeroRomano = ( numeroParaFuncion * \"I\" )\n elif numeroParaFuncion == 4:\n numeroRomano = ( \"IV\")\n elif numeroParaFuncion == 5:\n numeroRomano = (\"V\")\n elif numeroParaFuncion > 5 and numeroParaFuncion < 9:\n numeroRomano = (\"V\" + (numeroParaFuncion - 5) * \"I\")\n elif numeroParaFuncion == 9:\n numeroRomano = \"IX\"\n else:\n numeroRomano = \"X\"\n return numeroRomano\n \n \n\ndef main():\n numeroSinConvertir = int(input(\"Teclee un numero, este será convertido a Romano\"))\n \n if numeroSinConvertir >= 1 and numeroSinConvertir <= 10:\n print (conversorDeNumeroARomano(numeroSinConvertir))\n else:\n print (\"Este programa soporta solo números del uno al diez positivos\") \n \n \n \nmain()","sub_path":"números romanos.py","file_name":"números romanos.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"125016664","text":"# 类得常用魔术方法\n\nclass A():\n def __init__(self,name = 0):\n print(\"哈哈,我被调用了\")\n def __str__(self):\n return \"返回字符串\"\n\na = A()\nprint(a)\n\nprint(\"*\"*20)\n\n# 描述符相关\n# __set__\n# __get__\n# __delete__\n# 属性操作相关\n# __getattr__ 访问一个不存在得属性触发\nclass B():\n name = \"NoName\"\n age = 18\n def __getattr__(self, item):\n print(item)\n return \"没找到属性\"\n\nb = B()\nprint(b.name)\nprint(b.addr)\n\n# __setattr__ 队成员属性进行设置得时候触发\nclass Person():\n def __init__(self):\n pass\n def __setattr__(self, key, value):\n print(\"设置属性:{0}\".format(key))\n print(value)\n # 下面豫剧会导致问题 死循环\n # self.age = value\n # 此种情况,为了避免死循环,规定统一调用父类魔法函数\n super(Person, self).__setattr__(key,value)\np = Person()\nprint(p.__dict__)\np.age = 18\n\nprint(\"*\"*20)\n# 运算分类相关魔术方法\n# __gt__ 大于\nclass Student():\n def __init__(self,name,age):\n self._name = name\n self._age = age\n def __gt__(self, obj):\n print(\"哈哈,{0}会比{1}大吗?\".format(self,obj))\n return self._name > obj._name\n\nstu1 = Student(\"One\",13)\nstu2 = Student(\"One\",12)\n\nprint(stu1 > stu2)","sub_path":"OOP/05.py","file_name":"05.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"577171134","text":"import re\n\n\"\"\"\nFormats move flavor text from Veekun\ninto a csv file named 'moves_flavor_format.csv'\nUse this in case of faulty line breaks in the original file\n\"\"\"\n\nlines = open('moves_flavor.csv','r').read().split(\"\\n\")\n\niter_range = range(len(lines))\niter_range.reverse()\nmatch = re.compile(r'^\\d+,\\d+,\\d+')\nfor index in iter_range:\n\tline = lines[index]\n\t#len([quote for quote in line if quote=='\"'])!=2 and not(any(i.isdigit() for i in line))\n\tif(not match.match(line)):\n\t\tlines[index-1] += ' ' + lines[index]\n\t\tlines.pop(index)\noutput = header\nfor line in lines:\n\toutput += line + \"\\n\"\nout = open('moves_flavor_format.csv','w')\nout.write(output)\nout.close()","sub_path":"data_processing/format_move_flavor.py","file_name":"format_move_flavor.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"475410120","text":"#!/usr/bin/env python\n\n\"\"\" 02 Play file\n----------------------------------------------------------------------\ncommand line equivlent\n$ gst-launch-0.10 filesrc location=song.ogg ! decodebin ! audioconvert ! alsasink\n\"\"\"\n\nfrom gi.repository import Gst, GObject\nimport sys\n\nGObject.threads_init() # Initializing threads used by the Gst various elements\n\nGst.init(None)\n\npipeline = Gst.Pipeline()\n\nsource = Gst.ElementFactory.make('filesrc', None)\nsource.set_property(\"location\", sys.argv[1])\npipeline.add(source)\n\n\ndef onPadAdded(element, pad):\n pad.link(sink.get_static_pad('sink'))\n\ndecoder = Gst.ElementFactory.make(\"decodebin\", \"decoder\")\ndecoder.connect('pad-added', onPadAdded)\npipeline.add(decoder)\n\nsink = Gst.ElementFactory.make(\"autoaudiosink\", \"sink\")\npipeline.add(sink)\n\nsource.link(decoder)\n\npipeline.set_state(Gst.State.PLAYING)\nGObject.MainLoop().run()\n","sub_path":"_201_playfile.py","file_name":"_201_playfile.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"568173714","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.examples.tutorials.mnist import input_data\n# 최신 Windows Laptop에서만 사용할것.CPU Version이 높을때 사용.\n# AVX를 지원하는 CPU는 Giuthub: How to compile tensorflow using SSE4.1, SSE4.2, and AVX. \n# Ubuntu와 MacOS는 지원하지만 Windows는 없었음. 2018-09-29\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n# Compuntational Graph Initialization\nfrom tensorflow.python.framework import ops\nops.reset_default_graph()\n\nDATA_DIR = \"/tmp/ML/MNIST_data\"\nmnist = input_data.read_data_sets(DATA_DIR, one_hot=True)\n\nSAVE_DIR = \"/tmp/ML/14_Recurrent_Neural_Networks\"\n\n# Define Hyper Parameters\nlearning_rate = 0.001\nN_EPISODES = 10\nbatch_size = 100\n\n\"\"\"\n To classify images using a recurrent neural network, we consider every image\n row as a sequence of pixels. Because MNIST image shape is 28*28px, we will then\n handle 28 sequences of 28 steps for every sample.\n RNN 은 순서가 있는 자료를 다루므로,\n 한 번에 입력받는 갯수와, 총 몇 단계로 이루어져있는 데이터를 받을지를 설정해야합니다.\n 이를 위해 가로 픽셀수를 INPUT_SIZE 으로, 세로 픽셀수를 입력 단계인 TIME_STEP 으로 설정하였습니다.\n\"\"\"\nINPUT_SIZE = 28\nTIME_STEP = 28\nH_SIZE_01 = 128\nn_class = 10\n\n# Define Placeholder\nX = tf.placeholder(tf.float32, [None, TIME_STEP, INPUT_SIZE])\nY = tf.placeholder(tf.float32, [None, n_class])\n\nW01_m = tf.Variable(tf.random_normal([H_SIZE_01, n_class]))\nB01_m = tf.Variable(tf.random_normal([n_class]))\n\n# RNN 에 학습에 사용할 셀을 생성합니다\n# 다음 함수들을 사용하면 다른 구조의 셀로 간단하게 변경할 수 있습니다\n# BasicRNNCell,BasicLSTMCell,GRUCell\ncell = tf.nn.rnn_cell.BasicRNNCell(H_SIZE_01)\n\n# RNN 신경망을 생성합니다\n# 원래는 다음과 같은 과정을 거쳐야 하지만\n# states = tf.zeros(batch_size)\n# for i in range(TIME_STEP):\n# outputs, states = cell(X[[:, i]], states)\n# ...\n# 다음처럼 tf.nn.dynamic_rnn 함수를 사용하면\n# CNN 의 tf.nn.conv2d 함수처럼 간단하게 RNN 신경망을 만들어줍니다.\n# 겁나 매직!!\noutputs, states = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)\n\n# 결과를 Y의 다음 형식과 바꿔야 하기 때문에\n# Y : [batch_size, n_class]\n# outputs 의 형태를 이에 맞춰 변경해야합니다.\n# outputs : [batch_size, TIME_STEP, H_SIZE_01]\n# -> [TIME_STEP, batch_size, H_SIZE_01]\n# -> [batch_size, H_SIZE_01]\noutputs = tf.transpose(outputs, [1, 0, 2])\noutputs = outputs[-1]\nPred_m = tf.matmul(outputs, W01_m) + B01_m\n\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=Pred_m, labels=Y))\noptimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)\n\n#########\n# 신경망 모델 학습\n######\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\ntotal_batch = int(mnist.train.num_examples/batch_size)\n\nfor episode in range(N_EPISODES):\n total_cost = 0\n\n for i in range(total_batch):\n batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n # X 데이터를 RNN 입력 데이터에 맞게 [batch_size, TIME_STEP, INPUT_SIZE] 형태로 변환합니다.\n batch_xs = batch_xs.reshape((batch_size, TIME_STEP, INPUT_SIZE))\n\n _, cost_val = sess.run([optimizer, cost],\n feed_dict={X: batch_xs, Y: batch_ys})\n total_cost += cost_val\n\n print('episode:', '%04d' % (episode + 1),\n 'Avg. cost =', '{:.3f}'.format(total_cost / total_batch))\n\nprint('Optimization Completed!')\n\n#########\n# 결과 확인\n######\nis_correct = tf.equal(tf.argmax(Pred_m, 1), tf.argmax(Y, 1))\naccuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))\n\ntest_batch_size = len(mnist.test.images)\ntest_xs = mnist.test.images.reshape(test_batch_size, TIME_STEP, INPUT_SIZE)\ntest_ys = mnist.test.labels\n\nprint('Accuracy:', sess.run(accuracy,\n feed_dict={X: test_xs, Y: test_ys}))\n\n\n#########\n# 결과 확인 (matplot)\n######\nlabels = sess.run(Pred_m,\n feed_dict={X: mnist.test.images.reshape(-1, 28, 28),\n Y: mnist.test.labels})\n\nfig = plt.figure()\nfor i in range(60):\n subplot = fig.add_subplot(4, 15, i + 1)\n subplot.set_xticks([])\n subplot.set_yticks([])\n subplot.set_title('%d' % np.argmax(labels[i]))\n subplot.imshow(mnist.test.images[i].reshape((28, 28)),\n cmap=plt.cm.gray_r)\n\nplt.show()\n\n\n# 세션을 닫습니다.\nsess.close()\n\n\n# Step 10. Tune hyperparameters:\n# Step 11. Deploy/predict new outcomes:\n\n","sub_path":"ML_19_Recurrent_Neural_Networks/ML_19_01_MNIST_RNN.py","file_name":"ML_19_01_MNIST_RNN.py","file_ext":"py","file_size_in_byte":4622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"500984611","text":"\"\"\"\nhttps://github.github.com/gfm/#paragraphs\n\"\"\"\nimport pytest\n\nfrom pymarkdown.tokenized_markdown import TokenizedMarkdown\nfrom pymarkdown.transform_to_gfm import TransformToGfm\n\nfrom .utils import (\n assert_if_lists_different,\n assert_if_strings_different,\n assert_token_consistency,\n)\n\n\n@pytest.mark.gfm\ndef test_blank_lines_197():\n \"\"\"\n Test case 197: Blank lines at the beginning and end of the document are also ignored.\n \"\"\"\n\n # Arrange\n tokenizer = TokenizedMarkdown()\n transformer = TransformToGfm()\n source_markdown = \"\"\"\\a\\a\n\naaa\n\\a\\a\n\n# aaa\n\n \"\"\".replace(\n \"\\a\", \" \"\n )\n expected_tokens = [\n \"[BLANK(1,1): ]\",\n \"[BLANK(2,1):]\",\n \"[para(3,1):]\",\n \"[text:aaa:]\",\n \"[end-para]\",\n \"[BLANK(4,1): ]\",\n \"[BLANK(5,1):]\",\n \"[atx(6,1):1:0:]\",\n \"[text:aaa: ]\",\n \"[end-atx::]\",\n \"[BLANK(7,1):]\",\n \"[BLANK(8,1): ]\",\n ]\n expected_gfm = \"\"\"

aaa

\n

aaa

\"\"\"\n\n # Act\n actual_tokens = tokenizer.transform(source_markdown)\n actual_gfm = transformer.transform(actual_tokens)\n\n # Assert\n assert_if_lists_different(expected_tokens, actual_tokens)\n assert_if_strings_different(expected_gfm, actual_gfm)\n assert_token_consistency(source_markdown, actual_tokens)\n\n\n@pytest.mark.gfm\ndef test_blank_lines_197a():\n \"\"\"\n Test case 197a: Extra blanks to test\n \"\"\"\n\n # Arrange\n tokenizer = TokenizedMarkdown()\n transformer = TransformToGfm()\n source_markdown = \"\"\"\\a\\a\n\\a\naaa\n\"\"\".replace(\n \"\\a\", \" \"\n )\n expected_tokens = [\n \"[BLANK(1,1): ]\",\n \"[BLANK(2,1): ]\",\n \"[para(3,1):]\",\n \"[text:aaa:]\",\n \"[end-para]\",\n \"[BLANK(4,1):]\",\n ]\n expected_gfm = \"\"\"

aaa

\"\"\"\n\n # Act\n actual_tokens = tokenizer.transform(source_markdown)\n actual_gfm = transformer.transform(actual_tokens)\n\n # Assert\n assert_if_lists_different(expected_tokens, actual_tokens)\n assert_if_strings_different(expected_gfm, actual_gfm)\n assert_token_consistency(source_markdown, actual_tokens)\n","sub_path":"test/test_markdown_blank_lines.py","file_name":"test_markdown_blank_lines.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"456924120","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\nimport sys\nis_python_3 = sys.version_info.major >= 3\n\nfrom collections import OrderedDict\nfrom abc import abstractmethod\nimport re\nimport time\nimport json\nimport binascii\nimport os\nimport os.path\nimport io\n\nimport cgi\n\n\nif is_python_3 :\n import http.client as http_base\n from http.cookies import SimpleCookie as DefaultCookiesContainer\n from http.cookies import Morsel as DefaultCookiesElement\nelse:\n import httplib as http_base\n from Cookie import SimpleCookie as DefaultCookiesContainer\n from Cookie import Morsel as DefaultCookiesElement\n\n\n# is this present on al os ?\nimport mimetypes\n\n__author__ = 'KeiDii'\n__version__ = '0.41'\n__license__ = 'MIT'\n\nDEFAULT_LISTEN_HOST = '0.0.0.0'\nDEFAULT_LISTEN_PORT = 8008\n\nMAX_CONTENT_SIZE = 1 * 1024 * 1024 # 1 MB\n\nINVALID_CONTENT_LEN = -1\n\n# ~~ const strings ~~\n\nSERVER_NAME = \"SaucePan\"\n\n# common header names :\nHEADER_LOCATION = \"Location\"\nHEADER_CONTENT_LENGTH = 'Content-Length'\nHEADER_CONTENT_TYPE = 'Content-type'\nHEADER_CONTENT_ENCODING = 'Content-encoding'\nHEADER_CONTENT_DISPOSITION = 'Content-disposition'\nHEADER_CONTENT_RANGE = 'Content-Range'\nHEADER_LAST_MODIFIED = 'Last-modified'\nHEADER_SERVER = 'Server'\nHEADER_RANGE = 'Range'\nHEADER_SET_COOKIE = 'Set-Cookie'\n\n# common headers values\nSAVE_AS_TPL = 'attachment; filename=\"{0:s}\"'\n\nQUERY_STRING_SEP = '&'\nQUERY_STRING_EQ = '='\n\nCONTENT_JSON = 'application/json'\nCONTENT_HTML = 'text/html'\nCONTENT_PLAIN = 'text/plain'\n\nHTTP_CODES = http_base.responses.copy()\nHTTP_CODES[418] = \"I'm a teapot\" # RFC 2324\nHTTP_CODES[428] = \"Precondition Required\"\nHTTP_CODES[429] = \"Too Many Requests\"\nHTTP_CODES[431] = \"Request Header Fields Too Large\"\n\nHTTP_CODE_RANGES = {1: 'Continue', 2: 'Success', 3: 'Redirect', 4: 'Request Error', 5: 'Server Error'}\n\n# why -> cause logging is sloooow !\nLOG_DEBUG = 4\nLOG_INFO = 3\nLOG_WARN = 2\nLOG_ERROR = 1\n\n\nclass TinyLogger(object):\n level = LOG_DEBUG\n\n def debug(self, a):\n if self.level >= LOG_DEBUG:\n print(\"DEBUG: {0}\".format(a))\n\n def info(self, a):\n if self.level >= LOG_INFO:\n print(\"INFO: {0}\".format(a))\n\n def warn(self, a):\n if self.level >= LOG_WARN:\n print(\"WARN: {0}\".format(a))\n\n def error(self, a):\n if self.level >= LOG_ERROR:\n print(\"ERROR: {0}\".format(a))\n\n\nthe_logger = TinyLogger()\n\n# , one can replace the_logger w/ logging ... will work ...\n\n## If outside functions to speed things (one \"if\" less per call ;-)\nif is_python_3:\n def __get_func_varnames(func):\n return func.__code__.co_varnames\n \n def _is_string(param):\n return isinstance(param, str)\n\nelse:\n def __get_func_varnames(func):\n return func.func_code.co_varnames\n\n def _is_string(param):\n return isinstance(param, basestring)\n\n\nclass HttpProtocolError(Exception): # raise on http-spec violation\n pass\n\n\n_ALLOW_LAZY_PROPERTY_SET = False\n\n\nclass LazyProperty(property):\n def __init__(self, func, doc=None):\n super(LazyProperty, self).__init__(func)\n self._func = func\n self.__doc__ = doc or func.__doc__\n self._name = func.__name__ # no extra 'name' as arg yet, useless\n self._flag = \"_got_{0}\".format(self._name)\n\n def __set__(self, instance, val):\n if _ALLOW_LAZY_PROPERTY_SET:\n instance.__dict__[self._name] = val\n if not hasattr(instance, self._flag):\n setattr(instance, self._flag, 1)\n else:\n raise AttributeError(\"Can't set value to lazy attribute !\")\n\n def __get__(self, instance, class_type=None):\n if instance is None:\n return False # or raise error ?\n if hasattr(instance, self._flag):\n return instance.__dict__[self._name]\n value = self._func(instance) # replace !\n instance.__dict__[self._name] = value\n setattr(instance, self._flag, 1)\n return value\n\ndef get_random_string(size, encode='hex', factor=2):\n if encode:\n return binascii.hexlify(os.urandom(int(1 + size / factor)))[:size]\n else:\n return os.urandom(size)\n\n\ndef get_default_http_message(code):\n c = int(code) / 100\n return HTTP_CODE_RANGES.get(c, None)\n\n\ndef http_status(code, message=None):\n code = int(code)\n if message is None:\n message = HTTP_CODES.get(code, None)\n if message is None:\n message = get_default_http_message(code)\n if message is None:\n message = 'http' # any better ideas ?\n return \"{0} {1}\".format(code, message)\n\n\ndef _keyname_to_httpkeyame(name, extra_keys=None):\n name = str(name).upper()\n if name.startswith(\"HTTP_\") or (extra_keys and name in extra_keys):\n return name\n return \"HTTP_\" + name\n\n\n# decorator\ndef fix_kwarg(kwarg_name, func, *func_a, **func_kw): # <- so awesome !\n def _wrap1(f):\n func_varnames = __get_func_varnames(f)\n def _wrap2(*a, **kw):\n if kwarg_name in kw:\n kw[kwarg_name] = func(kw[kwarg_name], *func_a, **func_kw)\n else:\n idx = func_varnames.index(kwarg_name)\n a = list(a)\n a[idx] = func(a[idx], *func_a, **func_kw)\n return f(*a, **kw)\n\n if kwarg_name not in func_varnames:\n raise Exception(\"{0} not in arg names of {1}\".format(kwarg_name, str(f)))\n return _wrap2\n\n return _wrap1\n\n\nclass CaseInsensitiveEnv(object):\n \"\"\"\n Object that allow to access to env storage (http headers + other metadata)\n in case-insensitive way\n \"\"\"\n _extra_keys = ('CONTENT_TYPE', 'CONTENT_LENGTH')\n _env = None\n\n def __init__(self, env):\n self._env = env\n\n def __getitem__(self, item):\n return self.get(item, None)\n\n @fix_kwarg('key', _keyname_to_httpkeyame, _extra_keys)\n def get(self, key, default=None, require=False):\n val = self._env.get(key, None)\n if val is None:\n if require:\n raise KeyError(key)\n return default\n return val\n\n @fix_kwarg('key', _keyname_to_httpkeyame, _extra_keys)\n def has(self, key):\n return self._env.get(key) is not None\n\n @fix_kwarg('key', _keyname_to_httpkeyame, _extra_keys)\n def check(self, key, val):\n cur_val = self.get(key, default=None)\n if cur_val is None:\n return False\n if isinstance(val, list):\n if cur_val in val:\n return True\n return cur_val == val\n\n def __str__(self): # debug me :-)\n c = []\n for k in self._env:\n if k.startswith('HTTP_'):\n c.append((k[5:], self._env[k]))\n return json.dumps(c)\n\n\nMULTIDICT_GET_ONE = 1\nMULTIDICT_GET_ALL = 2\n\n\nclass MultiValDict(object): # response headers container\n _storage_ = None\n _key_mod = None\n\n def __init__(self, *a, **kw):\n self._storage_ = dict()\n if len(a) > 0:\n if isinstance(a[0], dict):\n for k, v in a[0].items():\n self[k] = v\n else:\n for k, v in kw.items():\n self[k] = v\n\n def get(self, key, default=None, mode=MULTIDICT_GET_ONE):\n if self._key_mod:\n key = self._key_mod(key)\n if len(self._storage_[key]) > 0:\n if mode == MULTIDICT_GET_ONE:\n return self._storage_[key][0]\n elif mode == MULTIDICT_GET_ALL:\n return self._storage_[key]\n return default\n\n def __setitem__(self, key, value):\n if self._key_mod:\n key = self._key_mod(key)\n if key not in self._storage_:\n self._storage_[key] = list()\n self._storage_[key].append(value)\n\n def __getitem__(self, key):\n if self._key_mod:\n key = self._key_mod(key)\n if len(self._storage_[key]) > 0:\n return self._storage_[key][0]\n return None\n\n def items(self):\n for k, l in self._storage_.items():\n for v in l:\n yield k, v\n\n\nclass CaseInsensitiveMultiDict(MultiValDict): # response headers container\n\n def _key_mod(self, k):\n return str(k).upper()\n\n\ndef _parse_multipart(fd, boundary=None):\n def boo(s=''):\n the_logger.debug(\"Multipart-FAIL ! {0}\".format(s))\n raise Http4xx(http_base.BAD_REQUEST, \"Invalid Multipart/\" + s)\n\n if boundary is None:\n raise Exception(\"Need to guess boundary marker ... not yet implemented !\")\n if 1 > len(boundary) > 69: # rfc1341\n boo(\"Invalid boundary marker size \")\n delimiter = \"--{0}\".format(boundary)\n close_delimiter_marker = '--'\n\n ln = fd.readline().strip()\n if ln != delimiter:\n boo('invalid data - not delimiter')\n\n while True:\n\n meta = CaseInsensitiveMultiDict()\n\n while True:\n ln = fd.readline().strip()\n # print \" -> Line : \", ln\n if ln == '':\n # print \" -> EMPTY ! <- \"\n break\n name, data = ln.split(\": \", 1)\n val, opts = cgi.parse_header(data)\n # print \"--> HEADERS :\", name,' : ', val,' ; ', opts\n meta[name] = {'value': val, 'opts': opts}\n # entry_meta.append({'name':name, 'value':val, 'opts':opts})\n offset = fd.tell()\n # print \"DATA AT OFFSET : \", offset\n\n if meta.get('Content-Disposition', None) is None:\n boo('No Content-Disposition!')\n\n r = ''\n while True:\n chunk = fd.readline()\n if chunk == '':\n # print \"WTF\"\n return\n # rint \"CHUNK = \",`chunk`\n if chunk.startswith(delimiter):\n # r = 'some data'\n yield r.strip(), meta\n if chunk.strip().endswith(close_delimiter_marker):\n # print \"END END\"\n return\n else:\n break\n else:\n r += chunk\n\n yield \"YO LO\"\n print(\"PARSING STUFF\")\n\n\ndef _read_iter_blocks(read_fn, size, block_size=2048):\n while True:\n if block_size > size:\n block_size = size\n block = read_fn(block_size)\n if not block or len(block) == 0:\n return\n yield block\n size -= len(block)\n if size <= 0:\n return\n\n\ndef _read_iter_chunks(read_fn, max_size):\n def _read_till(fn, stop_at='\\n', max_bytes=10):\n buff = ''\n n = 0\n if max_bytes == -1:\n while True:\n chunk = fn(1)\n n += 1\n if chunk == stop_at:\n return buff, n\n buff += chunk\n else:\n while max_bytes > 0:\n chunk = fn(1)\n n += 1\n if chunk == stop_at:\n return buff, n\n buff += chunk\n max_bytes -= 1\n\n def _read_next_chunk_start(fn, sep=';'):\n buf, num_read = _read_till(fn, \"\\n\")\n if sep in buf:\n size, extension = buf.strip().split(sep, 1)\n size = int(size, 16)\n # TODO: handle params\n else:\n size = int(buf.strip(), 16)\n return size, num_read\n\n while max_size > 0:\n block_size, read_bytes = _read_next_chunk_start(read_fn)\n max_size -= read_bytes\n # TODO: check if max_size > block_size !\n if block_size > max_size:\n raise Http4xx(http_base.REQUEST_ENTITY_TOO_LARGE, \"Max body size exceed !\")\n if block_size == 0:\n return # TODO : read trailer\n else:\n chunk = ''\n while block_size > 0:\n part = read_fn(block_size)\n block_size -= len(part)\n max_size -= len(part)\n chunk += part\n yield chunk\n _read_till(read_fn, '\\n') # should read 2 chars !\n\n\ndef _regex_get_args_kwargs(exp, mo):\n idx = exp.groupindex.values()\n groups = mo.groups()\n kwargs = mo.groupdict()\n args = []\n for i in range(len(groups)):\n if (i + 1) not in idx: # not a groupdict\n args.append(groups[i])\n return args, kwargs\n\ndef _guess_str_is_querystring(s, qs_sep=QUERY_STRING_SEP, qs_eq=QUERY_STRING_EQ):\n return qs_sep in s or qs_eq in s\n\ndef _tokenize_query_str(s, qs_sep=QUERY_STRING_SEP, qs_eq=QUERY_STRING_EQ):\n for chunk in s.split(qs_sep):\n if len(chunk) == 0:\n pass\n elif qs_eq in chunk:\n yield chunk.split(qs_eq, 1)\n elif chunk and len(chunk) > 0:\n yield [chunk, None]\n else:\n pass\n\n# -------------- generic server snap-in -----\n#\n\nclass GenericServer(object):\n \"\"\" Generic, bottle-compatible build-in server \"\"\"\n\n def __init__(self, **options):\n self.server = None\n self.options = options\n\n def run(self, wsgi_app):\n \"\"\"\n Should Run forever\n :param wsgi_app: wsgi application\n :return:\n \"\"\"\n pass\n\n\nclass WSGIRefServer(GenericServer):\n \"\"\" WSGIRef-based server\n \"\"\"\n\n def run(self, wsgi_app):\n\n host = self.options.get('host', DEFAULT_LISTEN_HOST)\n port = int(self.options.get('port', DEFAULT_LISTEN_PORT))\n\n import wsgiref.simple_server as ref_srv\n\n class FixedHandler(ref_srv.WSGIRequestHandler):\n\n def address_string(self): # Prevent reverse DNS lookups please.\n return self.client_address[0]\n\n def log_request(*args, **kw):\n pass\n\n srv_class = ref_srv.WSGIServer\n hnd_class = FixedHandler\n the_logger.debug(\"Starting WSGIRef simple server on {0}:{1}\".format(host, port))\n self.server = ref_srv.make_server(host, port, wsgi_app, srv_class, hnd_class)\n try:\n self.server.serve_forever()\n except KeyboardInterrupt:\n self.server.server_close()\n\n\n#\n# -------------- HTTP STUFF -----\n#\n\n# this implements \"response\" headers container.\n# TODO: We should re-write this to support multi-values per key (list)\nclass LastUpdatedOrderedDict(OrderedDict):\n def __setitem__(self, key, value, dict_setitem=dict.__setitem__):\n if key in self:\n del self[key]\n OrderedDict.__setitem__(self, key, value, dict_setitem=dict_setitem)\n\n\nclass DictAsObject(dict): # prototype for settings ?\n def __getattr__(self, item):\n return self.__getitem__(item)\n\n def __setattr__(self, key, value):\n return self.__setitem__(key, value)\n\n\nclass FileLike(object):\n def __init__(self):\n pass\n\n\nclass HttpMessage(object): # bare meta-object\n headers = {}\n body = None\n env = None\n\n def __init__(self, env):\n self.env = env\n self.on_init()\n self.body = ''\n\n def on_init(self): # called automatically by init, just to skip __init__ overriding\n pass\n\n def prepare(self): # called manually by owner\n pass\n\n\nclass HttpRequest(HttpMessage):\n files = None\n post = None\n get = None\n cookies = None\n body = None\n headers = None\n verb = method = None\n protocol = None\n path = None\n host = None\n content_type = None\n content_length = 0\n query_string = None\n is_chunked = False\n wsgi_input = None\n\n def on_init(self):\n self.headers = CaseInsensitiveEnv(self.env)\n self.verb = self.env.get('REQUEST_METHOD','')\n self.method = self.verb # You call it verb, I call it method\n self.protocol = self.env.get('SERVER_PROTOCOL','')\n self.path = self.env.get('PATH_INFO','')\n self.host = self.env.get('HTTP_HOST','')\n self.query_string = self.env.get('QUERY_STRING','')\n self.content_type = self.env.get('CONTENT_TYPE','')\n self.wsgi_input = self.env.get('wsgi.input')\n self.is_chunked = False\n enc = self.headers.get('TRANSFER_ENCODING', '').lower()\n if 'chunk' in enc: # well, it is so pro ;-)\n self.is_chunked = True\n the_logger.debug(\"It is chunked !!!\")\n cl = self.env.get('CONTENT_LENGTH', None)\n if cl is None or cl == '':\n self.content_length = 0 # no header or empty header == 0\n else:\n try:\n int_cl = int(cl)\n if int_cl <= 0:\n int_cl = INVALID_CONTENT_LEN\n self.content_length = int_cl \n except Exception as err:\n the_logger.debug(\"Fail to parse content-length: {0}\".format(err))\n self.content_length = INVALID_CONTENT_LEN\n self.body = io.BytesIO()\n\n def prepare(self):\n \"\"\"\n parse body, POST params, GET params, files and cookies.\n IDEA/NOTE to myself: implement variables initialization as lazy properties so they will\n be evaluated on first usage, not always !\n This should speed-up a little ...\n \"\"\"\n self.cookies = {}\n self.post = {}\n self.get = {}\n self.files = {}\n # ~~~ BODY ~~~\n\n max_body_size = 0 # don't try to read in case of doubts\n if self.content_length != INVALID_CONTENT_LEN:\n if self.content_length > MAX_CONTENT_SIZE: # declared size too large ...\n raise Http4xx(http_base.REQUEST_ENTITY_TOO_LARGE)\n max_body_size = self.content_length\n try: # re-parse body, fill BytesIO ;-)\n fn = _read_iter_chunks if self.is_chunked else _read_iter_blocks\n for block in fn(self.wsgi_input.read, max_body_size):\n self.body.write(block)\n self.body.seek(0)\n except Exception as ex:\n the_logger.debug(\"Problem @ read body ... {0} | {1}\".format(str(ex), \" silently pass ;-)\"))\n #TODO : should we crash ? or keep silent ?\n # TODO: MOVE THIS TO LAZY METHODS\n cookie_str = self.env.get('HTTP_COOKIE', None)\n if cookie_str:\n tmp = SETTINGS.cookies_container_class(cookie_str)\n for c in tmp.values():\n self.cookies[c.key] = c.value\n # GET\n self._parse_query_string()\n # POST / FILES\n self._parse_body()\n\n def _parse_query_string(self):\n for k, v in _tokenize_query_str(self.query_string):\n self.get[k] = v\n\n def get_body(self):\n if self.content_length == INVALID_CONTENT_LEN:\n # self.content_length = MAX_CONTENT_SIZE\n # ^-- this cused attempt to read from empty fd .. don't !\n # try to rescue the situation :\n return ''\n if self.content_length == 0:\n return ''\n self.body.seek(0)\n content = self.body.read(self.content_length)\n self.body.seek(0)\n return content\n\n def _parse_body(self):\n # override FILES and POST properties ...\n self.post = {}\n self.files = {}\n # or check for application/x-www-form-urlencoded ?\n if 'multipart/' in self.content_type:\n ## print(\"Multipart : {0}\".format(self.get_body()))\n value, options = cgi.parse_header(self.content_type)\n for field in _parse_multipart(self.body, **options):\n data, opts = field\n # print \"FIELD :\", field, opts\n try:\n cd = opts.get('Content-Disposition') # should be present, was checked in _parse_multipart\n name = cd['opts']['name']\n is_file = 'filename' in cd['opts']\n except Exception as err:\n raise Http4xx(400, \"Fail to process body of http request: \" + str(err))\n if is_file:\n self.files[name] = data\n else:\n self.post[name] = data\n # notes to myself :\n # - try to keep all data in body (especially large blobs)\n # ~~~ POST/body (multipart) ~~~\n # by storing offset to variables in FILES array (access wrappers ?)\n else: # not a multi-part -> form !\n # split data from body into POST vars. TODO: handle this on first access to POST\n str_body = self.get_body()\n if _guess_str_is_querystring(str_body[:100]): \n for k, v in _tokenize_query_str(self.get_body()):\n self.post[k] = v\n\n # @LazyPropertyWrapper(store=file_vars\n def xfiles(self):\n self._parse_body()\n return self.files\n\n # @LazyPropertyWrapper\n def xpost(self):\n self._parse_body()\n return self.post\n\n # @LazyPropertyWrapper\n def xcookies(self):\n cookie_str = self.env.get('HTTP_COOKIE', None)\n if cookie_str:\n self.cookies = SETTINGS.cookies_container_class(cookie_str)\n else:\n self.cookies = None\n return self.cookies\n\n def arg(self, key, default=None, required=False):\n if key in self.get:\n return self.get[key]\n if key in self.post:\n return self.post[key]\n if key in self.cookies:\n return self.cookies[key]\n if required:\n raise KeyError(\"Parameter [{0:s}] not found !\".format(key))\n else:\n return default\n\n def uri(self, host=False):\n if host:\n return self.host + self.path\n else:\n return self.path\n\n\nclass HttpResponse(HttpMessage):\n status_code = 200\n status_message = None\n cookies = None\n headers = None\n body = ''\n fix_content_length = True\n\n # http_version = '' <- will not be used ?\n\n def prepare(self):\n self.headers = CaseInsensitiveMultiDict()\n self.cookies = SETTINGS.cookies_container_class()\n for k, v in SETTINGS.default_headers:\n self.headers[k] = v\n\n def set_status(self, code, message=None):\n self.status_code = code\n self.status_message = message\n\n def get_status(self):\n return http_status(self.status_code, self.status_message)\n\n def get_headers(self):\n r = []\n for k, v in self.headers.items():\n r.append((k.title(), str(v)))\n return r\n\n def old_get_headers(self): # return Camel-Case headers + values as list[]\n resp = []\n for k, v in self.headers.items():\n if isinstance(v, list):\n for vv in v:\n resp.append((k.title(), str(vv)))\n else:\n resp.append((k.title(), str(v)))\n return resp\n\n def header(self, key, value):\n self.headers[key] = value\n\n def set_cookie(self, name, value=None, **kw):\n if len(value) > 4096:\n raise Exception('Cookie value to long')\n # c = self.settings.cookies_element_class()\n self.cookies[name] = value\n for k, v in kw.items():\n self.cookies[name][k] = v\n # return c\n\n def finish(self):\n # store cookie\n if len(self.cookies) > 0:\n cookie_list = []\n for v in self.cookies.values():\n cookie_list.append(v.OutputString())\n # self.header(HEADER_SET_COOKIE, v.OutputString())\n self.headers[HEADER_SET_COOKIE] = v.OutputString()\n\n # self.headers[HEADER_SET_COOKIE] = cookie_list\n # calculate content-length header if not set\n if self.fix_content_length:\n s = len(self.body)\n self.headers[HEADER_CONTENT_LENGTH] = str(s)\n\n def get_body(self):\n retval = self.body\n if not _is_string(retval):\n retval = str(retval)\n if is_python_3:\n return retval.encode()\n else:\n return retval\n\n\nclass TheContext(object):\n def __init__(self, env):\n self.env = env\n self.request = HttpRequest(env)\n self.response = HttpResponse(env) # version=self.request.version)\n \n def prepare(self):\n self.request.prepare()\n self.response.prepare()\n\n # I know this looks weird, but it is rly handy ;-)\n def cookie(self, name, *a, **kw): # magic cookie set/get wrapper\n if len(kw) == 0 and len(a) == 0:\n return self.request.cookies.get(name, None)\n else:\n self.response.set_cookie(name, *a, **kw)\n # ^- pass value as 1st arg\n\n# -------------- ROUTER -----\n#\n\nclass AbstractRouter(object):\n _routes = []\n default = None\n\n def __init__(self):\n self.setup()\n\n @abstractmethod\n def setup(self):\n pass\n\n def _pre_process(self, testable, kw):\n return kw\n\n def _default_route(self, ctx, **kw):\n if callable(self.default):\n self.default(ctx, **kw)\n\n def add_entry(self, testable, **kw):\n the_logger.debug(\"Adding new route [testable={0:s}]\".format(str(testable)))\n self._routes.append(self._pre_process(testable, kw))\n pass\n\n @abstractmethod\n def try_route(self, ctx, **route_args):\n pass\n\n def select_route(self, ctx):\n for rt in self._routes:\n if self.try_route(ctx, **rt):\n return ctx\n the_logger.warn(\"No valid route found ! Try default ...\")\n self._default_route(ctx)\n return ctx\n\n\n#\n# -------------- 'Base' Routable class (can be passed to router) -----\n#\n\nclass RoutableClass(object):\n prefix = \"do_\"\n method_variable = \"method\"\n default = None\n\n def __init__(self):\n pass\n\n def always(self, ctx):\n pass\n\n def __call__(self, ctx, method=None, *a, **kw):\n method = kw.get(self.method_variable, None)\n if method is None:\n raise Exception(\"Method argument [{0}] is missing\".format(self.method_variable))\n func_name = self.prefix + method\n func_ptr = getattr(self, func_name, self.default)\n if func_ptr and callable(func_ptr):\n self.always(ctx, *a, **kw)\n return func_ptr(ctx, *a, **kw)\n raise Exception(\"Fail to call method :\" + str(method))\n\n\n# should we move this inside DefaultRouter class ??\n\nROUTE_CHECK_UNDEF = None\nROUTE_CHECK_ALWAYS = 0xff\nROUTE_CHECK_STR = 1\nROUTE_CHECK_SIMPLE = 2\nROUTE_CHECK_REGEX = 3\nROUTE_CHECK_CALL = 4\nROUTE_GENERATOR = 5\nROUTE_CLASS = 6\nDEFAULT_ROUTE_TYPE = ROUTE_CHECK_SIMPLE\nROUTE_ALWAYS = None # <- special 'testable' value\n\nMETHOD_GET = ['GET']\nMETHOD_POST = ['POST']\n\n\ndef _default_router_do_call(ctx, fn, a, kw):\n the_logger.debug(\"Default router call ... \")\n data = fn(ctx, *a, **kw)\n if data:\n if ctx.response.body:\n ctx.response.body += data\n # ^- append, NOT replace !\n # this would raise exception, if resp.body is already set,\n # and called function return incompatible type (ex. str + dict )\n else:\n ctx.response.body = data # <- this should work if we return dict,\n\n\n# one can implement other router-type class, this provide\n# basic, but complex functionality\n\nclass DefaultRouter(AbstractRouter):\n _SIMPLE_CHAR_SET = 'a-zA-Z0-9'\n _SIMPLE_RE_FIND = r'<([^>]+)>'\n _SIMPLE_RE_REPLACE = r'(?P<\\1>[' + _SIMPLE_CHAR_SET + ']+)'\n _type_mapping = {}\n\n def setup(self):\n # TODO : rewrite dict routes to classes ? (need to benchmark !)\n self._type_mapping = {\n ROUTE_CHECK_ALWAYS: self._test_always,\n ROUTE_CHECK_STR: self._test_str,\n ROUTE_CHECK_SIMPLE: self._test_re,\n ROUTE_CHECK_REGEX: self._test_re,\n ROUTE_CHECK_CALL: self._test_call,\n ROUTE_GENERATOR: self._test_generator,\n }\n\n @staticmethod\n def _test_always(ctx, testable=None, target=None, **kw):\n _default_router_do_call(ctx, target, [], kw)\n return True\n\n @staticmethod\n def _test_str(ctx, testable='', target=None, **ex):\n uri = ctx.request.uri()\n if uri == testable:\n _default_router_do_call(ctx, target, [], ex)\n return True\n return False\n\n @staticmethod\n def _test_re(ctx, testable=None, target=None, _re=None, **ex):\n uri = ctx.request.uri()\n mo = _re.match(uri)\n if not mo:\n return False\n args, kwargs = _regex_get_args_kwargs(_re, mo)\n ex.update(kwargs)\n _default_router_do_call(ctx, target, args, ex)\n return True\n\n @staticmethod\n def _test_call(ctx, testable=None, target=None, **ex):\n ret_val = testable(ctx, **ex)\n args = []\n if isinstance(ret_val, tuple) or isinstance(ret_val, list):\n bool_val = ret_val[0]\n args = ret_val[1:]\n else:\n bool_val = ret_val\n if bool_val:\n _default_router_do_call(ctx, target, args, route)\n return True\n return False\n\n @staticmethod\n def _test_generator(ctx, testable=None, target=None, **ex):\n ret_val = testable(ctx, **ex)\n if ret_val is None:\n return False\n args = []\n if isinstance(ret_val, tuple) or isinstance(ret_val, list):\n func = ret_val[0]\n args = ret_val[1:]\n else:\n func = ret_val\n _default_router_do_call(ctx, func, args, route)\n return True\n\n def add_entry(self, testable=ROUTE_ALWAYS, **kw): # add default testable value\n AbstractRouter.add_entry(self, testable, **kw)\n\n def _pre_process(self, testable, kw):\n # TODO : this could return object with proper methods/values/etc\n\n kw['testable'] = testable\n target = kw.get('target', None)\n route_type = kw.get('route_type', ROUTE_CHECK_UNDEF)\n if 'headers' not in kw:\n kw['headers'] = []\n else:\n if not isinstance(kw['headers'], list):\n kw['headers'] = []\n\n # convert al check_%s key into required header names\n for key in kw.keys():\n if key.startswith(\"check_\"):\n item = key.split(\"_\", 1)[1]\n kw['headers'].append((item, kw[key]))\n del kw[key]\n\n if isinstance(target, type):\n the_logger.debug(\"Creating instance of class ... \")\n # kw['_class'] = target\n kw['target'] = target()\n # if route_type != ROUTE_CLASS\n\n if route_type == ROUTE_CHECK_UNDEF:\n the_logger.debug(\"Route type is not set. Guessing ...\")\n if testable is ROUTE_ALWAYS:\n route_type = ROUTE_CHECK_ALWAYS\n elif _is_string(testable):\n if \"<\" in testable:\n route_type = ROUTE_CHECK_SIMPLE\n else:\n route_type = ROUTE_CHECK_STR\n if callable(testable): # callable can be check or generator\n if target is None:\n route_type = ROUTE_GENERATOR\n else:\n route_type = ROUTE_CHECK_CALL\n kw['route_type'] = route_type\n the_logger.debug(\"Route type after guess: {0:d}\".format(route_type))\n else:\n # \"* Route type already set to :\", route_type\n pass\n\n # setup proxy function to perform test.\n # Setting this here allow to skip another switch-case construct in try_route\n kw['_callable'] = self._type_mapping.get(route_type, None)\n if route_type == ROUTE_CHECK_REGEX:\n kw['_re'] = re.compile(testable)\n if route_type == ROUTE_CHECK_SIMPLE:\n _tmp = re.sub(self._SIMPLE_RE_FIND, self._SIMPLE_RE_REPLACE, testable)\n kw['_re'] = re.compile(_tmp)\n return kw\n\n def try_route(self, ctx, _callable=None, headers=None, route_type=None, method=None, **args):\n if method:\n if ctx.request.method not in method:\n return False\n if headers and len(headers) > 0:\n for key, val in headers:\n if not ctx.request.headers.check(key, val):\n return False\n if _callable and callable(_callable):\n the_logger.debug(\"ROUTER: calling {0:s}\".format(str(_callable)))\n return _callable(ctx, **args)\n else:\n the_logger.error(\"Ouch! problem with _callable !\")\n\n\n# 3xx and 4xx \"exceptions\",\n# use them to stop function execution and return proper http answer\n\n# this would allow user to raise HttpEndNow(200) to stop processing in middle of nowhere\n# not only 3xx and 4xx\n\nclass HttpEndNow(Exception):\n code = http_base.OK\n message = 'OK'\n\n def __init__(self, code=None, message=None, **kw):\n Exception.__init__(self, \"HTTP End Processing\")\n if code is not None:\n self.code = code\n if message is not None:\n self.message = message\n self.kw = kw\n\n def do_handle(self, ctx):\n ctx.response.status_code = self.code\n ctx.response.status_message = self.message\n return self.gracefully_handle(ctx, **self.kw)\n\n def gracefully_handle(self, ctx, **_):\n pass\n\n\nclass Http3xx(HttpEndNow):\n def gracefully_handle(self, ctx, target='/'):\n ctx.response.headers[HEADER_LOCATION] = target\n ctx.response.body = 'Moved to {0:s} '.format(target)\n\n\nclass Http4xx(HttpEndNow):\n def gracefully_handle(self, ctx, **_):\n ctx.response.body = 'Error {0:d}'.format(self.code)\n\n\n# Exception handlers :\ndef _silent_error_handler(ctx, _):\n ctx.response.headers[HEADER_CONTENT_TYPE] = CONTENT_HTML\n return \"500: server fail !\"\n\n\ndef _verbose_error_handler(ctx, _):\n import traceback\n import sys\n\n info = sys.exc_info()\n traceback.print_exception(*info)\n body = \"SERVER FAIL:
\\n\"\n  body += '\\n'.join(traceback.format_exception(*info))\n  body += \"\\n\\n
\"\n ctx.response.headers[HEADER_CONTENT_TYPE] = CONTENT_HTML\n return body\n\n\ndef _default_request_handler(ctx):\n ctx.response.status_code = 404\n return \"Not found!\"\n\n\nHOOK_BEFORE = 'pre'\nHOOK_AFTER = 'post'\nAVAILABLE_HOOKS = [HOOK_BEFORE, HOOK_AFTER]\n\nSETTINGS = DictAsObject(\n cookies_container_class=DefaultCookiesContainer,\n cookies_element_class=DefaultCookiesElement,\n be_verbose=True,\n default_headers=[\n [HEADER_CONTENT_TYPE, CONTENT_HTML],\n [HEADER_SERVER, '{0:s} (ver {1:s})'.format(SERVER_NAME, __version__)],\n ],\n)\n\n\nclass TheMainClass(object):\n \"\"\"\n >>main<< class, glues everything ...\n \"\"\"\n _write_using_writer = False\n router = DefaultRouter()\n _exception_handlers = []\n pre_hooks = []\n post_hooks = []\n extra_args = {}\n\n def __init__(self, router_class=None):\n the_logger.debug(\"Main object init\")\n if router_class:\n self.router = router_class()\n self.router.default = _default_request_handler\n\n def add_param(self, **kv):\n self.extra_args.update(**kv)\n\n def hook(self, h_type, *a, **kw):\n if h_type not in AVAILABLE_HOOKS:\n raise Exception(\"Invalid hook type! {0:s} not in {1:s}\".format(h_type, str(AVAILABLE_HOOKS)))\n\n def _wrapper(f):\n entry = dict(func=f, args=a, kwargs=kw)\n if h_type == HOOK_BEFORE:\n self.pre_hooks.append(entry)\n elif h_type == HOOK_AFTER:\n self.post_hooks.append(entry)\n\n return _wrapper\n\n def handle_exception(self, ex_type, **kw):\n def _wrapper(f):\n self.add_exception_handler(ex_type, f, **kw)\n\n return _wrapper\n\n def add_exception_handler(self, ex_type, fn, **kw):\n self._exception_handlers.append(\n dict(ex_type=ex_type, handler=fn, kwargs=kw)\n )\n\n def route(self, testable, **kw):\n def _wrapper(f):\n self.router.add_entry(testable, target=f, **kw)\n return _wrapper\n\n def add_route(self, testable, target=None, **kw):\n self.router.add_entry(testable, target=target, **kw)\n\n def _handle_error(self, ctx, error):\n ctx.response.set_status(http_base.INTERNAL_SERVER_ERROR) # 500\n for entry in self._exception_handlers:\n if isinstance(error, entry['ex_type']):\n return entry['handler'](ctx, error, **entry['kwargs'])\n if SETTINGS.be_verbose:\n return _verbose_error_handler(ctx, error)\n else:\n return _silent_error_handler(ctx, error)\n\n def wsgi_handler(self, environ, start_response):\n the_logger.debug('WSGI handler called ...')\n exc_info = None\n ctx = TheContext(environ)\n for k,v in self.extra_args.items():\n print(\"SetAttr\",k,v)\n setattr(ctx, k, v);\n try:\n # one will say that is insane, but it handle the situation that\n # exception handler will fail somehow ....\n try:\n ctx.prepare()\n for _h in self.pre_hooks:\n if callable(_h['func']):\n the_logger.debug(\"Calling PRE hook : {0:s}\".format(str(_h)))\n _h['func'](ctx, *_h['args'], **_h['kwargs'])\n self.router.select_route(ctx)\n for _h in self.post_hooks:\n if callable(_h['func']):\n the_logger.debug(\"Calling POST hook : {0:s}\".format(str(_h)))\n _h['func'](ctx, *_h['args'], **_h['kwargs'])\n except HttpEndNow as ex:\n ex.do_handle(ctx)\n except Exception as ex:\n ctx.response.body = self._handle_error(ctx, ex)\n except Exception as epic_fail:\n the_logger.error(\"EPIC FAIL : \" + str(epic_fail))\n ctx.response.body = \"CRITICAL ERROR\"\n ctx.response.set_status(http_base.INTERNAL_SERVER_ERROR) # 500\n ctx.response.finish()\n headers = ctx.response.get_headers()\n status = ctx.response.get_status()\n body_writer = start_response(status, headers, exc_info)\n if self._write_using_writer and callable(body_writer):\n body_writer(ctx.response.get_body())\n return ['']\n else:\n return [ctx.response.get_body()]\n\n\nmain_scope = TheMainClass()\n\n# expose in globals, so we can use @decorator\nroute = main_scope.route\nhook = main_scope.hook\nadd_param = main_scope.add_param\nadd_route = main_scope.add_route\nhandle_exception = main_scope.handle_exception\n\n\n# utils:\n\n\nclass MultipartElement(object):\n def __init__(self, content, fields=None):\n self.content = content\n self.fields = fields if fields else {}\n\n\ndef make_multipart(ctx, parts, mp_type='form-data', marker=None, fields=None):\n if marker is None:\n marker = 'MARK' + get_random_string(20)\n if fields is None:\n fields = {}\n body = ''\n for element in parts:\n if not isinstance(element, MultipartElement):\n continue\n body += '--' + marker + '\\n'\n merged = fields.copy()\n merged.update(element.fields)\n for k, v in merged.items():\n body += '{0:s}: {1:s}'.format(k, v)\n body += '\\n'\n body += element.content + '\\n'\n body += '--' + marker + '--\\n'\n ctx.response.headers[HEADER_CONTENT_TYPE] = 'multipart/{0:s}; boundary={1:s}'.format(mp_type, marker)\n ctx.response.body = body\n\n\ndef static_handler(ctx, filename=None, static_dir='./', mime=None, encoding=None, save_as=None, last=True):\n real_static = os.path.abspath(static_dir)\n real_path = os.path.abspath(os.path.join(static_dir, filename))\n the_logger.debug(\"Try static file access : {0:s} \".format(real_path))\n if not real_path.startswith(real_static):\n raise Http4xx(http_base.FORBIDDEN) # 403\n if not os.path.exists(real_path):\n raise Http4xx(http_base.NOT_FOUND) # 404\n if not os.path.isfile(real_path):\n raise Http4xx(http_base.NOT_FOUND) # 404\n if not os.access(real_path, os.R_OK):\n raise Http4xx(http_base.FORBIDDEN) # 403\n if hasattr(ctx, 'do_auto_json'):\n ctx.do_auto_json = False # <- skip processing\n if mime is None:\n mime, enc = mimetypes.guess_type(real_path)\n if encoding is None and enc is not None:\n encoding = enc\n if encoding:\n ctx.response.headers[HEADER_CONTENT_ENCODING] = encoding\n if save_as is not None:\n ctx.response.headers[HEADER_CONTENT_DISPOSITION] = SAVE_AS_TPL.format(save_as)\n if last:\n # http://tools.ietf.org/html/rfc2616#section-14.29\n # http://tools.ietf.org/html/rfc2616#section-3.3\n f_stat = os.stat(real_path)\n lm_str = time.strftime(\"%a, %d %b %Y %H:%M:%S GMT\", time.gmtime(f_stat.st_mtime))\n ctx.response.headers[HEADER_LAST_MODIFIED] = lm_str\n\n # TODO :\n # range ?\n # content-range ?\n # content-length ?\n return open(real_path, 'r').read()\n\n\ndef register_static_file_handler(url_prefix='/static/', static_dir='./static/'):\n add_route(url_prefix + \"(.*)\", target=static_handler, static_dir=static_dir, route_type=ROUTE_CHECK_REGEX)\n\n\n# expose WSGI handler\napplication = main_scope.wsgi_handler\n\n\ndef run(server_class=None, **opts):\n the_logger.debug(\"Preparing WSGI server ... \")\n if server_class is None:\n server_class = WSGIRefServer\n handle = server_class(**opts)\n the_logger.debug(\"Running server ... \")\n handle.run(application)\n\n\nif __name__ == '__main__':\n the_logger.warn(\"Running standalone ?\")\n run()\n\n","sub_path":"saucepan.py","file_name":"saucepan.py","file_ext":"py","file_size_in_byte":37172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"342895906","text":"#coding=utf-8\nimport pymongo\nclass Dbmanager():\n host = ''\n port = 0\n\n def __init__(self):\n self.host = 'localhost'\n self.port = 27017\n\n\n\n def get_db(self):\n client = pymongo.MongoClient(host=self.host, port=self.port)\n db = client['douban_db']\n return db\n\n def insert_data(self ,db ,dbname ,json):\n collection = db[dbname]\n if collection.find().count() > 1000:\n collection.remvoeall\n collection.save(json)\n else:\n collection.save(json)\n\n def get_dbItemsNum(self,dbname):\n db = self.get_db()\n collection = db[dbname]\n num = collection.find().count()\n return num\n\n def has_data(self ,key, name, db, dbname):\n collection = db.get_collection(dbname)\n if collection:\n has = collection.find({key:name}).count() > 0\n return has\n else:\n return False","sub_path":"Project/Be/dbmanager/dbmanager.py","file_name":"dbmanager.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"560393322","text":"a,b=input().split()\nl=len(a)\nd={}\nc=0\nfor i in range(l):\n if a[i] not in d.keys():\n d[a[i]]=b[i]\n else:\n if d[a[i]]==b[i]:\n continue\n else:\n c=1\n break\nif c==1:\n print(\"no\")\nelse:\n print(\"yes\")\n","sub_path":"isomorphic.py","file_name":"isomorphic.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"376185785","text":"\"\"\"\nrow !: \nheader !header:\nfooter !footer:\n\nempty _\n\ncol_sum !!sum\ncol_mean !!mean\ncol_diff !!delta\ncol_fn !!fn\n\"\"\"\nimport signal\nimport self_dataIO as io\nimport self_html as html\nimport self_statistics as stat\nfrom os import remove\n\n_IN = \"src\"\n_OUT = \"\"\n\nusr = \"$> \"\n\ndef write_html_table(rem=True):\n def del_file():\n print(\"> The file \" + _OUT + \" has been destroyed\")\n remove(html.filename)\n if _IN == \"\": print(\"Error, empty input\")\n else:\n global _OUT\n _OUT = _IN + \"-out.html\"\n html.filename = _OUT\n html.write_page()\n if rem:\n print(\"> Security Enabled:\")\n print(\"> The html table will be destroyed on input or exit\")\n try: input(usr)\n except (EOFError, KeyboardInterrupt, SystemExit):\n print(\">\")\n del_file()\n\ndef set_input(IN):\n global _IN\n _IN = IN + \".data\"\n io.source = IN + \".data\"\n io.data = stat.inspect(io.get_data())\n html.data = io.data\n stat.data = io.data\n\ndef create_data_file():\n print(\"> Creating a new datafile, insert a valid name:\")\n filename = input(usr)\n ret = \"!title: \" + filename + \"\\n\"\n d = {\"h\":\"!header:\",\"f\":\"!footer:\"}\n while True:\n inpt = input(usr)\n if inpt == \"\\\\e\": break\n else:\n first = inpt.split()[0]\n if first in d:\n ret+= d[first] + inpt.replace(first,\" \")\n else: ret+= \"!: \" + inpt\n ret+= \"\\n\"\n print(ret)\n open(filename+\".data\",\"w\").write(ret)\n set_input(filename)\n print(\"> \"+filename+\".data created successfully\")\n print(\"> Automatically set to _IN\")\n\nset_input(\"R004a\")\nwrite_html_table()\n\n","sub_path":"p3/self/self_control.py","file_name":"self_control.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"284695920","text":"from knock72 import *\nfrom sklearn.linear_model import LogisticRegression\nimport pickle\nimport sys\n\n\n\ndef int2label(int_):\n return '+1' if int_ == 1 else '-1'\n\n\nif __name__ == '__main__':\n # load ids_dict\n with open('result/ids.dump', 'rb') as data_ids_in:\n ids = pickle.load(data_ids_in)\n\n # load model\n with open('result/logistic.dump', 'rb') as logistic_in:\n logistic_model = pickle.load(logistic_in)\n\n # test\n with open('result/sample.txt', 'r') as txt_file_in:\n inputs = make_data(txt_file_in, 'test')\n features = create_features(inputs, ids)\n\n for predict, prob in zip(logistic_model.predict(features), logistic_model.predict_proba(features)):\n print('predict: {}\\nproba: {}\\n'.format(int2label(predict), max(prob)))\n","sub_path":"Shi-ma/chapter08/knock74.py","file_name":"knock74.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"522591371","text":"import os, sys, pathlib, setuptools, sysconfig, platform\nfrom setuptools.command.build_ext import build_ext\n\nassert platform.architecture()[0] == \"64bit\", \"ERROR: Python must be 64 Bit!. OS must be 64 Bit!.\"\n\nif sys.platform.startswith(\"lin\"):\n folder = \"lin\" # OS is Linux\nelif sys.platform.startswith(\"win\"):\n folder = \"win\" # OS is Windows\nelse:\n folder = \"mac\" # OS is Mac\n\nsources = []\nfor c_source_file in os.listdir(folder): # Walk the folder with C files.\n if c_source_file.endswith(\".c\"): # Collect all C files.\n sources.append(str(pathlib.Path(folder) / c_source_file))\n\nclass NoSuffixBuilder(build_ext):\n def get_ext_filename(self, ext_name): # NO Suffix\n filename = super().get_ext_filename(ext_name)\n return filename.replace(sysconfig.get_config_var('EXT_SUFFIX'), \"\") + pathlib.Path(filename).suffix\n\nsetuptools.setup(\n cmdclass = {\"build_ext\": NoSuffixBuilder},\n ext_modules = [\n setuptools.Extension(\n name = \"plz\",\n sources = sources,\n include_dirs = [folder],\n extra_link_args = [\"-s\"],\n extra_compile_args = [\"-flto\", \"-ffast-math\", \"-march=native\", \"-mtune=native\", \"-O3\", \"-fsingle-precision-constant\"],\n )\n ]\n)\n","sub_path":"dist/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"605423888","text":"import re\nimport sys\nfrom ..specfile.helpers import detect_specfile, get_source_urls, detect_github_tag_prefix, get_current_version, get_url\nfrom urllib.parse import urlparse\nfrom typing import Optional\n\nimport requests\n\n\nRE_GITHUB_PATH_REPO = re.compile('^/([^/]+/[^/]+)/?')\nRE_GIT_COMMIT = re.compile('^[a-f0-9]{40}$')\n\n\ndef detect_previous_version(changes):\n for line in changes:\n previous_version_match = re.match('^- +(?:version )?update(?: to)?(?: version)? ([0-9.]+)', line, re.IGNORECASE)\n if previous_version_match:\n previous_version = previous_version_match[1]\n break\n else:\n sys.exit(\"Could not determine the last mentioned version from the changes file.\")\n return previous_version\n\n\ndef get_changelog_from_github(previous_version: str, current_version: Optional[str] = None) -> dict:\n \"\"\"\n First, get the GitHub URL by interpreting the Source tags and the URL tag.\n Then, detect the tag-prefix.\n At the end, download the diff.\n \"\"\"\n specfilename = detect_specfile()\n if not current_version:\n current_version = get_current_version(specfilename=specfilename)\n\n urls = get_source_urls(specfilename=specfilename)\n for url in urls:\n parsed = urlparse(url)\n if parsed.hostname == 'github.com' and 'archive' in parsed.path:\n repo_path = RE_GITHUB_PATH_REPO.match(parsed.path).group(1)\n tag_prefix = detect_github_tag_prefix(specfilename=specfilename)\n break\n else:\n url = get_url(specfilename=specfilename)\n parsed = urlparse(url)\n if parsed.hostname == 'github.com':\n repo_path = RE_GITHUB_PATH_REPO.match(parsed.path).group(1)\n tags = requests.get(f'https://api.github.com/repos/{repo_path}/tags')\n tags.raise_for_status()\n if tags.json()[0]['name'].startswith('v'):\n tag_prefix = 'v'\n else:\n tag_prefix = ''\n else:\n sys.exit('Also found not Source URL or URL for GitHub.')\n\n if not RE_GIT_COMMIT.match(current_version):\n current_version = tag_prefix + current_version\n\n url = f'https://api.github.com/repos/{repo_path}/compare/{tag_prefix}{previous_version}...{current_version}'\n print(f'Downloading from: {url}', file=sys.stderr)\n compare = requests.get(url)\n compare.raise_for_status()\n return compare.json()\n\n\ndef get_changelog_from_github_releases(previous_version: str, current_version: Optional[str] = None) -> dict:\n \"\"\"\n First, get the GitHub URL by interpreting the Source tags and the URL tag.\n Then, detect the tag-prefix.\n At the end, download the diff.\n \"\"\"\n specfilename = detect_specfile()\n if not current_version:\n current_version = get_current_version(specfilename=specfilename)\n\n urls = get_source_urls(specfilename=specfilename)\n for url in urls:\n parsed = urlparse(url)\n if parsed.hostname == 'github.com' and 'archive' in parsed.path:\n repo_path = RE_GITHUB_PATH_REPO.match(parsed.path).group(1)\n tag_prefix = detect_github_tag_prefix(specfilename=specfilename)\n break\n else:\n url = get_url(specfilename=specfilename)\n parsed = urlparse(url)\n if parsed.hostname == 'github.com':\n repo_path = RE_GITHUB_PATH_REPO.match(parsed.path).group(1)\n releases = requests.get(f'https://api.github.com/repos/{repo_path}/releases')\n releases.raise_for_status()\n if releases.json()[0]['name'].startswith('v'):\n tag_prefix = 'v'\n else:\n tag_prefix = ''\n else:\n sys.exit('Also found no Source URL or URL for GitHub.')\n\n return {release['tag']: release['body'] for release in releases.json()}\n","sub_path":"packaging_utils/changelog_extractor/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":3801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"32543300","text":"\"\"\"\r\nDefines value objects (Value) and value sets (ValSet) for accessing variables between gui components.\r\n\"\"\"\r\nimport re\r\n\r\n\r\nclass Value(object):\r\n \"\"\"\r\n Base value class for value objects.\r\n\r\n :var value: the value it holds\r\n \"\"\"\r\n def __init__(self, value):\r\n \"\"\"\r\n Value constructor.\r\n\r\n :param value: the initial value\r\n \"\"\"\r\n if not self.is_valid(value):\r\n raise ValueError('Initial value is not valid!')\r\n self.value = value\r\n\r\n def __str__(self):\r\n return str(self.value)\r\n\r\n def set_val(self, new_value):\r\n \"\"\"\r\n Tests the new value is valid and sets the value if it is.\r\n\r\n :param new_value: a new value\r\n \"\"\"\r\n new_value = self.cast(new_value)\r\n if new_value is not None and self.is_valid(new_value):\r\n if self.value != new_value:\r\n self.value = new_value\r\n return 1\r\n else:\r\n self.value = new_value\r\n return 0\r\n\r\n def cast(self, cast_value):\r\n return cast_value\r\n\r\n def is_valid(self, new_value):\r\n \"\"\"\r\n Returns if a new value is valid.\r\n Should be overridden.\r\n\r\n :param new_value: a new value\r\n :rtype: bool\r\n \"\"\"\r\n return True\r\n\r\n def status(self, inputstr):\r\n inputcast = self.cast(inputstr)\r\n if inputcast is not None:\r\n if self.is_valid(inputcast):\r\n return True, True\r\n else:\r\n return True, False\r\n else:\r\n return False, False\r\n\r\n\r\nclass NumberValue(Value):\r\n \"\"\"\r\n A number value object.\r\n\r\n :var value: the value it holds\r\n \"\"\"\r\n\r\n def __init__(self, value, limit='', inclusive='ul', low=0, high=1):\r\n \"\"\"\r\n Number value constructor.\r\n Limit and inclusive should contain a 'u' for upper and 'l' for lower limit/inclusive comparison.\r\n\r\n :param value: the initial value\r\n :type limit: str\r\n :param limit: upper and lower limits\r\n :type inclusive: str\r\n :param inclusive: inclusive/non-inclusive comparison\r\n :type low: float\r\n :param low: lower limit\r\n :type low: float\r\n :param high: upper limit\r\n \"\"\"\r\n self.limit = limit\r\n self.inclusive = inclusive\r\n self.low = low\r\n self.high = high\r\n super().__init__(value)\r\n\r\n def incr(self):\r\n \"\"\"\r\n Increments the value by 1 if valid.\r\n \"\"\"\r\n self.set_val(self.value + 1)\r\n\r\n def decr(self):\r\n \"\"\"\r\n Decrements the value by 1 if valid.\r\n \"\"\"\r\n self.set_val(self.value - 1)\r\n\r\n def is_valid(self, new_value):\r\n \"\"\"\r\n Returns if a new value is valid.\r\n\r\n :param new_value: the new value\r\n :rtype: bool\r\n \"\"\"\r\n if 'l' in self.limit:\r\n if 'l' in self.inclusive:\r\n if new_value < self.low:\r\n return False\r\n else:\r\n if new_value <= self.low:\r\n return False\r\n if 'u' in self.limit:\r\n if 'u' in self.inclusive:\r\n if new_value > self.high:\r\n return False\r\n else:\r\n if new_value >= self.high:\r\n return False\r\n return True\r\n\r\n\r\nclass IntValue(NumberValue):\r\n \"\"\"\r\n An int value object.\r\n\r\n :var value: the value it holds\r\n \"\"\"\r\n\r\n def __str__(self):\r\n return '%i' % self.value\r\n\r\n def cast(self, cast_value):\r\n if isinstance(cast_value, int):\r\n return cast_value\r\n else:\r\n try:\r\n return int(cast_value)\r\n except ValueError:\r\n if isinstance(cast_value, str) and '^' in cast_value:\r\n try:\r\n a, b = map(int, cast_value.replace(' ', '').split('^'))\r\n return a ** b\r\n except ValueError:\r\n return None\r\n else:\r\n return None\r\n\r\n\r\nclass FloatValue(NumberValue):\r\n \"\"\"\r\n A float value object.\r\n\r\n :var value: the value it holds\r\n \"\"\"\r\n\r\n def __str__(self):\r\n return str(round(self.value, 5))\r\n\r\n def cast(self, cast_value):\r\n if isinstance(cast_value, float):\r\n return cast_value\r\n else:\r\n try:\r\n return float(cast_value)\r\n except ValueError:\r\n return None\r\n\r\n\r\nclass ComplexValue(NumberValue):\r\n \"\"\"\r\n A complex value object. Uses magnitude for comparisons.\r\n\r\n :var value: the value it holds\r\n \"\"\"\r\n\r\n def __str__(self):\r\n return '%s + %sj' % (str(round(self.value.real, 3)), str(round(self.value.imag, 3)))\r\n\r\n def cast(self, cast_value):\r\n if isinstance(cast_value, complex):\r\n return cast_value\r\n else:\r\n try:\r\n return complex(cast_value)\r\n except ValueError:\r\n return None\r\n\r\n def is_valid(self, new_value):\r\n if 'l' in self.limit:\r\n if 'l' in self.inclusive:\r\n if abs(new_value) < self.low:\r\n return False\r\n else:\r\n if abs(new_value) <= self.low:\r\n return False\r\n if 'u' in self.limit:\r\n if 'u' in self.inclusive:\r\n if abs(new_value) > self.high:\r\n return False\r\n else:\r\n if abs(new_value) >= self.high:\r\n return False\r\n return True\r\n\r\n\r\nclass BoolValue(Value):\r\n \"\"\"\r\n A bool value object.\r\n\r\n :var value: the value it holds\r\n \"\"\"\r\n\r\n def toggle(self):\r\n \"\"\"\r\n Inverts self.value.\r\n \"\"\"\r\n self.value = not self.value\r\n\r\n def cast(self, cast_value):\r\n if isinstance(cast_value, bool):\r\n return cast_value\r\n else:\r\n try:\r\n return bool(cast_value)\r\n except ValueError:\r\n return None\r\n\r\n\r\nclass ColorValue(Value):\r\n def __init__(self, value):\r\n if isinstance(value, (list, tuple)) and self.is_valid(value):\r\n self.value = self.cast(value)\r\n elif isinstance(value, str) and self.is_valid(self.cast(value)):\r\n self.value = self.cast(value)\r\n else:\r\n raise ValueError('Initial value is not valid!')\r\n\r\n def cast(self, cast_value):\r\n if isinstance(cast_value, (list, tuple)):\r\n return list(cast_value)\r\n elif isinstance(cast_value, str):\r\n if re.match(r'#[0-9,A-F,a-f]{6}', cast_value):\r\n return list(map(lambda x: int(x, 16), [cast_value[i:i+2] for i in range(1, 7, 2)]))\r\n else:\r\n return None\r\n\r\n def is_valid(self, new_value):\r\n if len(new_value) == 3:\r\n for c in new_value:\r\n if not isinstance(c, int) or c < 0 or c > 255:\r\n return False\r\n return True\r\n else:\r\n return False\r\n\r\n\r\nclass StringValue(Value):\r\n def cast(self, cast_value):\r\n if isinstance(cast_value, str):\r\n return cast_value\r\n else:\r\n try:\r\n return str(cast_value)\r\n except ValueError:\r\n return None\r\n\r\n\r\nclass ValSet:\r\n \"\"\"\r\n A collection of values.\r\n \"\"\"\r\n\r\n def __init__(self):\r\n self.vals = {}\r\n\r\n def add_value(self, name, value):\r\n self.vals[name] = Value(value)\r\n\r\n def add_generic_valobj(self, name, valobj):\r\n self.vals[name] = valobj\r\n\r\n def add_int_value(self, name, value, limit='', inclusive='ul', low=0, high=1):\r\n \"\"\"\r\n Adds an int value to the value set.\r\n Limit and inclusive should contain a 'u' for upper and 'l' for lower limit/inclusive comparison.\r\n\r\n :type name: str\r\n :param name: the value's name\r\n :type value: int\r\n :param value: the initial value\r\n :type limit: str\r\n :param limit: upper and lower limits\r\n :type inclusive: str\r\n :param inclusive: inclusive/non-inclusive comparison\r\n :type low: float\r\n :param low: lower limit\r\n :type low: float\r\n :param high: upper limit\r\n \"\"\"\r\n self.vals[name] = IntValue(value, limit, inclusive, low, high)\r\n\r\n def add_float_value(self, name, value, limit='', inclusive='ul', low=0, high=1):\r\n \"\"\"\r\n Adds a float value to the value set.\r\n Limit and inclusive should contain a 'u' for upper and 'l' for lower limit/inclusive comparison.\r\n\r\n :type name: str\r\n :param name: the value's name\r\n :type value: float\r\n :param value: the initial value\r\n :type limit: str\r\n :param limit: upper and lower limits\r\n :type inclusive: str\r\n :param inclusive: inclusive/non-inclusive comparison\r\n :type low: float\r\n :param low: lower limit\r\n :type low: float\r\n :param high: upper limit\r\n \"\"\"\r\n self.vals[name] = FloatValue(value, limit, inclusive, low, high)\r\n\r\n def add_complex_value(self, name, value, limit='', inclusive='ul', low=0, high=1):\r\n \"\"\"\r\n Adds a complex value to the value set.\r\n Limit and inclusive should contain a 'u' for upper and 'l' for lower limit/inclusive comparison.\r\n Uses magnitude for comparisons.\r\n\r\n :type name: str\r\n :param name: the value's name\r\n :type value: complex\r\n :param value: the initial value\r\n :type limit: str\r\n :param limit: upper and lower limits\r\n :type inclusive: str\r\n :param inclusive: inclusive/non-inclusive comparison\r\n :type low: float\r\n :param low: lower limit\r\n :type low: float\r\n :param high: upper limit\r\n \"\"\"\r\n self.vals[name] = ComplexValue(value, limit, inclusive, low, high)\r\n\r\n def add_bool_value(self, name, value):\r\n \"\"\"\r\n Adds a bool value to the value set.\r\n\r\n :type name: str\r\n :param name: the value's name\r\n :type value: bool\r\n :param value: the initial value\r\n \"\"\"\r\n self.vals[name] = BoolValue(value)\r\n\r\n def add_string_value(self, name, value):\r\n self.vals[name] = StringValue(value)\r\n\r\n def add_color_value(self, name, value):\r\n self.vals[name] = ColorValue(value)\r\n\r\n def get_val(self, name):\r\n \"\"\"\r\n Returns a value from the value set.\r\n\r\n :type name: str\r\n :param name: the value's name\r\n :return: the value\r\n \"\"\"\r\n return self.vals[name].value\r\n\r\n def set_val(self, name, value):\r\n \"\"\"\r\n Sets a value to a new value.\r\n\r\n :type name: str\r\n :param name: the value's name\r\n :param new_value: a new value\r\n \"\"\"\r\n self.vals[name].set_val(value)\r\n\r\n def get_valobj(self, name):\r\n \"\"\"\r\n Returns a value object from the value set.\r\n\r\n :type name: str\r\n :param name: the value's name\r\n :rtype: Value\r\n :return: the corresponding value object\r\n \"\"\"\r\n return self.vals[name]\r\n","sub_path":"pyg/valset.py","file_name":"valset.py","file_ext":"py","file_size_in_byte":11234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"186451020","text":"# -*- coding: utf-8 -*-\n\nimport time\nimport jwt\nfrom flask import g, request, current_app\nfrom flask_restplus import Namespace, Resource, abort, marshal\nfrom ..serializers.auth import access_token, token_model\nfrom ..parsers import auth_parser\nfrom .. import auth\nfrom app.models.personne.admin import get_admin_from_email\n\n\nns = Namespace('auth', description='Auth related operations.')\n\n\n# ================================================================================================\n# ENDPOINTS\n# ================================================================================================\n#\n# API Auth endpoints\n#\n# ================================================================================================\n\n\ndef is_authorized_client(email, secret):\n \"\"\"\n Verify if is authorized client\n :param email:\n :param secret:\n :return:\n \"\"\"\n u = get_admin_from_email(email)\n\n if u is None:\n return False\n\n if u[4] == secret:\n g.client = {\n 'id': u[0],\n 'nom': u[1],\n 'prenom': u[2],\n 'email': u[5]\n }\n\n return True\n\n return False\n\n\n@ns.route('/token')\nclass TokenGenerator(Resource):\n\n @ns.marshal_with(access_token)\n @ns.expect(auth_parser)\n def post(self):\n \"\"\"\n Get token\n \"\"\"\n data = request.form\n\n audience = ''\n\n if not is_authorized_client(data['email'], data['password']):\n abort(401, error='Unauthorized')\n\n now = int(time.time())\n\n token = {\n 'iss': 'https://localhost/admin/auth',\n 'aud': audience,\n 'iat': now,\n 'exp': now + 3600 * 24,\n 'user': g.client\n }\n\n token = jwt.encode(token, current_app.config['PRIVATE_KEY'], algorithm='RS512')\n\n return {'access_token': token.decode('utf-8')}\n\n\n@ns.route('/verify_token')\nclass TokenVerifier(Resource):\n decorators = [auth.login_required]\n\n @ns.marshal_with(token_model)\n @ns.expect(access_token)\n def post(self):\n \"\"\"\n Verify token\n \"\"\"\n data = request.json\n\n try:\n return jwt.decode(\n data['access_token'],\n current_app.config['PUBLIC_KEY'],\n audience=''\n )\n except Exception as ex:\n print(ex)\n abort(400, 'Invalid token')\n","sub_path":"app/admin/endpoints/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"151753936","text":"import argparse\nimport random\nimport sys\n\nfrom train_and_run_stability_test_bc import get_parser\n\nsys.path.append('/data/rishabh/')\nsys.path.append('/Users/apple/MEngProject/')\nsys.path.append('/home/ubuntu/')\n\nif __name__ == \"__main__\":\n\n parser = get_parser()\n parser.add_argument(\"--grad\", type=int, default=0)\n\n args, extras = get_parser().parse_known_args()\n args.extras = extras\n\n from Transparency.Trainers.DatasetBC import *\n from Transparency.ExperimentsBC import *\n from common_code.common import pickle_to_file\n from torch.backends import cudnn\n\n dataset = datasets[args.dataset](args)\n\n if args.output_dir is not None:\n dataset.output_dir = args.output_dir\n\n encoders = ['cnn', 'lstm', 'average'] if args.encoder == 'all' else [\n args.encoder]\n\n seeds = eval(args.seeds)\n\n all_grad_outputs = []\n for pseudo_random_seed in seeds:\n os.environ['PYTHONHASHSEED'] = str(pseudo_random_seed)\n np.random.seed(pseudo_random_seed)\n random.seed(pseudo_random_seed)\n torch.manual_seed(pseudo_random_seed)\n cudnn.deterministic = True\n cudnn.benchmark = False\n atns, preds, grads = [], [], []\n if args.loss:\n train_losses = []\n\n if args.attention in ['tanh', 'all']:\n preds, atns, grads = train_dataset_and_get_gradient(\n dataset, encoders, args.iters)\n\n if args.attention in ['dot', 'all']:\n encoders_temp = [e + '_dot' for e in encoders]\n preds, atns, grads = train_dataset_and_get_gradient(\n dataset, encoders_temp, args.iters)\n\n all_grad_outputs.append((preds, grads, atns))\n\n run_settings_str = args.name + args.swa + args.seeds + str(\n args.attention) + str(args.dataset) + str(args.encoder) + str(args.temp)\n file_name = \"gradient-outputs-\" + run_settings_str + \".pkl\"\n pickle_to_file(all_grad_outputs, file_name)","sub_path":"train_and_run_gradient_exp.py","file_name":"train_and_run_gradient_exp.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"190050098","text":"# -*- coding: utf-8 -*-\n\n# Autor: Mauricio de Oliveira (mauricioliveira_@hotmail.com)\n# Universidade Federal de Minas Gerais\n# Departamento de Ciência da Computação\n\nimport sys\nimport networkx as nx\nfrom myfunctions import read_file\nimport matplotlib.pyplot as plt\n\nFILE_END = '0,0'\nDELIMITER_1 = \",\"\nDELIMITER_2 = \" \" \n\nif __name__ == \"__main__\":\n\n delimiter = DELIMITER_1 if sys.argv[2] == \"1\" else DELIMITER_2\n input_graph = read_file(sys.argv[1], delimiter)\n\n g = nx.Graph()\n g.add_edges_from(input_graph)\n nx.draw_networkx(g)\n plt.savefig(sys.argv[1] + \"1.png\")\n","sub_path":"final/final/arq/draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"309445182","text":"import numpy as np\n\nimport pydicom\nfrom skimage.color import rgb2gray\n\nimport os\nimport pyvista as pv\n\nfrom glob import glob\n\nimport skimage.segmentation as seg\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom skimage.morphology import watershed\nfrom skimage.feature import peak_local_max\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\nimport scipy.ndimage\nfrom skimage import morphology\nfrom skimage import measure\nfrom sklearn.cluster import KMeans\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\nfrom plotly import figure_factory as FF\nfrom skimage.measure import label, regionprops, regionprops_table\nfrom scipy import ndimage, misc\n\n\n\n\n\ndef standardise_labels_timeline(images_list, start_at_end = True, count_offset = 1000):\n \"\"\"\n Replace labels on similar images to allow tracking over time\n\n :param images_list: a list of segmented and lablled images as numpy arrays\n :param start_at_end: relabels the images beginning at the end of the list\n :param count_offset: an int greater than the total number of expected labels in a single image\n :returns: a list of relablled images as numpy arrays\n \"\"\"\n\n images = list(images_list)\n if start_at_end:\n images.reverse()\n\n # Relabel all images to ensure there are no duplicates\n for image in images:\n for label in np.unique(image):\n if label > 0:\n count_offset += 1\n image[image == label] = count_offset\n\n # Ensure labels are propagated through image timeline\n for i, image in enumerate(images):\n labels = get_labelled_centers(image)\n\n # Apply labels to all subsequent images\n for j in range(i, len(images)):\n images[j] = replace_image_point_labels(images[j], labels)\n\n if start_at_end:\n images.reverse()\n\n return images\n\n\ndef get_labelled_centers(image):\n \"\"\"\n Builds a list of labels and their centers\n\n :param image: a segmented and labelled image as a numpy array\n :returns: a list of label, co-ordinate tuples\n \"\"\"\n\n # Find all labelled areas, disable caching so properties are only calculated if required\n rps = measure.regionprops(image, cache = False)\n\n return [(r.label, r.centroid) for r in rps]\n\n\ndef replace_image_point_labels(image, labels):\n \"\"\"\n Replace the labelled at a list of points with new labels\n\n :param image: a segmented and lablled image as a numpy array\n :param labels: a list of label, co-ordinate tuples\n :returns: a relabelled image as a numpy array\n \"\"\"\n img = image.copy()\n for label, point in labels:\n row, col = point\n # Find the existing label at the point\n index = img[int(row), int(col)]\n # Replace the existing label with new, excluding background\n if index > 0:\n img[img == index] = label\n\n return img\n\n\n\n\n\n\n\n\ndef make_mesh(image, threshold, step_size):\n\n print\n \"Transposing surface\"\n p = image.transpose(2, 1, 0)\n\n print\n \"Calculating surface\"\n verts, faces, norm, val = measure.marching_cubes_lewiner(p, threshold, step_size=step_size, allow_degenerate=True)\n return verts, faces\n\n\n\n\ndef plotly_3d(verts, faces):\n x, y, z = zip(*verts)\n\n print\n \"Drawing\"\n\n # Make the colormap single color since the axes are positional not intensity.\n # colormap=['rgb(255,105,180)','rgb(255,255,51)','rgb(0,191,255)']\n colormap = ['rgb(236, 236, 212)', 'rgb(236, 236, 212)']\n\n fig = FF.create_trisurf(x=x,\n y=y,\n z=z,\n plot_edges=False,\n colormap=\"Viridis\",\n simplices=faces,\n backgroundcolor='rgb(64, 64, 64)',\n title=\"Interactive Visualization\")\n iplot(fig)\n\n\n\n\n\ndef plt_3d(verts, faces):\n print\n \"Drawing\"\n x, y, z = zip(*verts)\n fig = plt.figure(figsize=(10, 10))\n ax = fig.add_subplot(111, projection='3d')\n\n # Fancy indexing: `verts[faces]` to generate a collection of triangles\n mesh = Poly3DCollection(verts[faces], linewidths=0.05, alpha=1)\n face_color = [1, 1, 0.9]\n mesh.set_facecolor(face_color)\n ax.add_collection3d(mesh)\n\n ax.set_xlim(0, max(x))\n ax.set_ylim(0, max(y))\n ax.set_zlim(0, max(z))\n ax.set_facecolor((0.7, 0.7, 0.7))\n plt.show()\n\n\n\n\n\n\n\n\ndef load_scan(path):\n slices = [pydicom.read_file(path + '/' + s) for s in os.listdir(path)]\n slices.sort(key=lambda x: int(x.InstanceNumber))\n try:\n slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2])\n except:\n slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation)\n\n for s in slices:\n s.SliceThickness = slice_thickness\n\n return slices\n\n\n\n\n\ndef get_pixels_hu(scans):\n image = np.stack([s.pixel_array for s in scans])\n # Convert to int16 (from sometimes int16),\n # should be possible as values should always be low enough (<32k)\n image = image.astype(np.int16)\n\n # Set outside-of-scan pixels to 1\n # The intercept is usually -1024, so air is approximately 0\n image[image == -2000] = 0\n\n # Convert to Hounsfield units (HU)\n intercept = scans[0].RescaleIntercept\n slope = scans[0].RescaleSlope\n\n if slope != 1:\n image = slope * image.astype(np.float64)\n image = image.astype(np.int16)\n\n image += np.int16(intercept)\n\n return np.array(image, dtype=np.int16)\n\n\n\n\ndef sample_stack(stack, show_every):\n rows = 6\n cols = 6\n start_with = 95\n\n fig,ax = plt.subplots(rows,cols,figsize=[10,12])\n for i in range(rows*cols):\n ind = start_with + i*show_every\n ax[int(i/rows),int(i % rows)].set_title('slice %d' % ind)\n ax[int(i/rows),int(i % rows)].imshow(stack[ind], cmap='nipy_spectral')\n # ax[int(i/rows),int(i % rows)].imshow(stack[ind],cmap='gray')\n ax[int(i/rows),int(i % rows)].axis('off')\n fig.tight_layout()\n plt.show()\n\n\n\n\n\n\ndef resample(image, scan, new_spacing=[1, 1, 1]):\n # Determine current pixel spacing\n spacing = map(float, ([scan[0].SliceThickness] + list(scan[0].PixelSpacing)))\n spacing = np.array(list(spacing))\n\n resize_factor = spacing / new_spacing\n new_real_shape = image.shape * resize_factor\n new_shape = np.round(new_real_shape)\n real_resize_factor = new_shape / image.shape\n new_spacing = spacing / real_resize_factor\n\n image = scipy.ndimage.interpolation.zoom(image, real_resize_factor)\n\n return image, new_spacing\n\n\n\n\n\n\n\n\ndef segmentation2d(image, display=False):\n\n threshold = np.mean(image)\n thresh_img = np.where(image < threshold, 0.0, 1.0) # threshold the image\n\n eroded = morphology.erosion(thresh_img, np.ones([4, 4]))\n dilation = morphology.dilation(eroded, np.ones([4, 4]))\n\n distance = ndimage.distance_transform_edt(dilation)\n\n\n segment = seg.felzenszwalb(thresh_img, scale=5.0, sigma=0.5, min_size=20)\n labels = measure.label(segment, background=0)\n wShed = watershed(-distance, labels, mask=thresh_img)\n\n\n\n eroded2 = morphology.erosion(dilation, np.ones([2, 2]))\n finalCleaned = morphology.dilation(eroded2, np.ones([2, 2]))\n\n # regions = measure.regionprops(labels)\n\n\n\n # for region in regions:\n # print('Label: {} >> Object size: {}'.format(region.label, region.area))\n #\n # props = regionprops_table(labels, properties=('centroid',\n # 'orientation',\n # 'major_axis_length',\n # 'minor_axis_length',\n # 'area'))\n #\n # print(pd.DataFrame(props))\n\n\n\n if (display):\n\n fig, ax = plt.subplots(3, 3, figsize=[10, 8])\n ax[0, 0].set_title(\"Original\")\n ax[0, 0].imshow(image)\n ax[0, 0].axis('off')\n\n ax[0, 1].set_title(\"Threshold\")\n ax[0, 1].imshow(thresh_img)\n ax[0, 1].axis('off')\n\n ax[0, 2].set_title(\"Erosion/Dilation\")\n ax[0, 2].imshow(dilation)\n ax[0, 2].axis('off')\n\n ax[1, 0].set_title(\"Distance Map\")\n ax[1, 0].imshow(distance)\n ax[1, 0].axis('off')\n\n ax[1, 1].set_title(\"Intial Segment\")\n ax[1, 1].imshow(segment)\n ax[1, 1].axis('off')\n\n ax[1, 2].set_title(\"Labels\")\n ax[1, 2].imshow(labels)\n ax[1, 2].axis('off')\n\n ax[2, 0].set_title(\"Watershed\")\n ax[2, 0].imshow(wShed, cmap='nipy_spectral')\n ax[2, 0].axis('off')\n\n ax[2, 1].set_title(\"Final Cleaned\")\n ax[2, 1].imshow(finalCleaned)\n ax[2, 1].axis('off')\n\n ax[2, 2].set_title(\"Final Cleaned * Watershed\")\n ax[2, 2].imshow(finalCleaned * wShed, cmap='nipy_spectral')\n ax[2, 2].axis('off')\n\n fig.tight_layout()\n plt.show()\n\n\n return finalCleaned * wShed, labels\n\n\n\n\ndef plotFourImgs(one, two, three, four):\n fig, ax = plt.subplots(2, 2, figsize=[10, 8])\n ax[0, 0].set_title(\"1\")\n ax[0, 0].imshow(one)\n ax[0, 0].axis('off')\n\n\n ax[0, 1].set_title(\"2\")\n ax[0, 1].imshow(two)\n ax[0, 1].axis('off')\n\n ax[1, 0].set_title(\"3\")\n ax[1, 0].imshow(three)\n ax[1, 0].axis('off')\n\n\n ax[1, 1].set_title(\"4\")\n ax[1, 1].imshow(four)\n ax[1, 1].axis('off')\n\n fig.tight_layout()\n plt.show()\n\n\n\n\n\n\n\n\ndef renderSTL(path):\n p = pv.Plotter()\n\n mesh = pv.PolyData(path)\n\n p.add_mesh(mesh)\n p.show()\n\n # mesh.plot()\n\n\n\n\n\n\n\n\n\n\ndef start():\n\n data_path = \"path to dicom folder/\"\n\n output_path = working_path = \"some output path/\"\n g = glob(data_path + '/*.dcm')\n\n\n id = 0 #change\n patient = load_scan(data_path)\n imgs = get_pixels_hu(patient)\n\n np.save(output_path + \"fullimages_%d.npy\" % (id), imgs)\n\n file_used = output_path + \"fullimages_%d.npy\" % id\n imgs_to_process = np.load(file_used).astype(np.float64)\n\n # imgs_to_process = np.load(output_path + '1fullimages_{}.npy'.format(id))\n\n sample_stack(imgs_to_process, 10)\n\n\n plt.hist(imgs_to_process.flatten(), bins=50, color='c')\n plt.xlabel(\"Hounsfield Units (HU)\")\n plt.ylabel(\"Frequency\")\n plt.show()\n\n print(\"Slice Thickness: %f\" % patient[0].SliceThickness)\n print(\"Pixel Spacing (row, col): (%f, %f) \" % (patient[0].PixelSpacing[0], patient[0].PixelSpacing[1]))\n print(\"Shape before resampling\\t\", imgs_to_process.shape)\n\n imgs_after_resamp, spacing = resample(imgs_to_process, patient, [1, 1, 1])\n\n print(\"Shape after resampling\\t\", imgs_after_resamp.shape)\n\n\n sample_stack(imgs_after_resamp, 10)\n\n\n\n # print(\"Max: \", ndimage.maximum(seg))\n # print(\"Min: \", ndimage.minimum(seg))\n # print(\"Mean: \", ndimage.mean(seg))\n # print(\"StDev: \", ndimage.standard_deviation(seg))\n # print(\"Extreme: \", ndimage.extrema(seg))\n\n\n\n\n\n\n segment_all = []\n label_all = []\n\n\n for img in imgs_after_resamp:\n img = np.clip(img, -50, std)\n\n mask, regions = segmentation2d(img, True)\n segment_all.append(mask)\n label_all.append(regions)\n\n sample_stack(segment_all, 10)\n\n\n tracked_centriods = standardise_labels_timeline(label_all)\n\n\n np.save(output_path + \"segment_all.npy\", segment_all)\n np.save(output_path + \"tracked_centriods.npy\", tracked_centriods)\n\n\n\n\n v, f = make_mesh(seg, 40, 2)\n ptly_3d(v, f)\n\n\n\n\n\nif __name__ == '__main__':\n start()\n\n\n\n\n\n\n\n\n\n# def segmentation3d(image, display=False):\n#\n# threshold = np.mean(image)\n# thresh_img = np.where(image < threshold, 0.0, 1.0) # threshold the image\n#\n# erodedt = morphology.erosion(image, np.ones([10, 10, 10]))\n#\n# eroded = morphology.erosion(thresh_img, np.ones([10, 10, 10]))\n# # dilation = morphology.dilation(eroded, np.ones([4, 4, 4]))\n#\n# distance = ndimage.distance_transform_edt(eroded)\n#\n# localMax = peak_local_max(distance, indices=False, min_distance=30,threshold_abs=9,exclude_border=1)\n#\n#\n# # segment = seg.felzenszwalb(thresh_img, scale=5.0, sigma=0.5, min_size=20)\n# labels = measure.label(localMax, background=0)\n# wShed = watershed(-distance, labels, mask=thresh_img)\n#\n#\n# regions = measure.regionprops(wShed)\n#\n# eroded2 = morphology.erosion(eroded, np.ones([2, 2, 2]))\n# finalCleaned = morphology.dilation(eroded2, np.ones([2, 2, 2]))\n#\n# # for region in regions:\n# # print('Region: {} >> Region size: {}'.format(region.label, region.area))\n#\n# # for label in labels:\n# # print('Label: {}'.format(label.label))\n#\n# print(\"here\")\n#\n# plotter = pv.Plotter(shape='1|1',window_size=(1000, 1200))\n# p = pv.wrap(erodedt)\n# plotter.subplot(0)\n# plotter.add_text(\" 1 \")\n# plotter.add_volume(p, shade=True)\n#\n# plotter.subplot(1)\n# p2 = pv.wrap(eroded)\n# plotter.add_text(\" 2 \")\n# plotter.add_volume(p2, shade=True)\n#\n# plotter.show()\n#\n#\n#\n# return finalCleaned * wShed\n","sub_path":"segmentation.py","file_name":"segmentation.py","file_ext":"py","file_size_in_byte":12984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"561822813","text":"# This problem was asked by Uber.\n# Given an array of integers, return a new array such that each element at index i of the new array \n# is the product of all the numbers in the original array except the one at i.\n# For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. \n# If our input was [3, 2, 1], the expected output would be [2, 3, 6].\n# Follow-up: what if you can't use division?\n\n# I think thats the defaut way of solving without division\n# input_array = [1, 2, 3, 4, 5]\n# output_array = []\n# for index_output in range(len(input_array)):\n# product = 1\n# for index in range(len(input_array)):\n# if(index != index_output):\n# product *= input_array[index]\n# output_array.append(product)\n# print(output_array)\n\n# This is a more elegant way of doing, at least in my opinion\ninput_array = [1, 2, 3, 4, 5]\noutput_array = []\nfor index_output in range(len(input_array)):\n product = 1\n for index in range(1, len(input_array)):\n product *= input_array[index]\n output_array.append(product)\n \n aux = input_array.pop(0)\n input_array.append(aux)\nprint(output_array)","sub_path":"Done/dailyCoding_#2.py","file_name":"dailyCoding_#2.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"516099941","text":"import matplotlib.patches as mpatches\nimport mpl_scatter_density\nfrom mpl_scatter_density import ScatterDensityArtist\nimport numpy as np\nimport tqdm\nimport os\nimport glob\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom argparse import ArgumentParser\nimport seaborn as sns\nfrom path import Path\nsns.set(style='white')\n\ndef parse_args():\n argparser = ArgumentParser()\n argparser.add_argument('in_path')\n argparser.add_argument('out_path')\n argparser.add_argument('--x_low', type=float)\n argparser.add_argument('--x_high', type=float)\n argparser.add_argument('--y_low', type=float)\n argparser.add_argument('--y_high', type=float)\n return argparser.parse_args()\n\nif __name__ == \"__main__\":\n args = parse_args()\n in_path, out_path = Path(args.in_path), Path(args.out_path)\n\n df = pd.DataFrame()\n for file in tqdm.tqdm(glob.glob(in_path / \"**/*.csv\", recursive=True)):\n print(file)\n data = pd.read_csv(file)\n if \"-test\" in file:\n name = os.path.basename(file)[5:-4].split(\"-\")[:-1]\n round, location, board = int(name[0]), name[1], int(name[2])\n data[\"train_round\"] = round\n data[\"train_location\"] = location\n else:\n data[\"train_round\"] = data[\"round\"]\n data[\"train_location\"] = data[\"location\"]\n for gas in [\"NO2\", \"O3\"]:\n data[\"%s MAE\" % gas] = np.abs(data[\"epa-%s\" % gas.lower()] - data[\"preds-%s\" % gas.lower()])\n df = pd.concat([df, data[[\"epa-no2\", \"epa-o3\", \"train_round\", \"train_location\", \"board\", \"round\", \"location\", \"temperature\", \"absolute-humidity\", \"pressure\", \"NO2 MAE\", \"O3 MAE\"]]])\n\n LOCATIONS = {\"elcajon\",\"shafter\", \"donovan\"}\n MAP = {\n \"elcajon\": \"El Cajon\",\n \"shafter\": \"Shafter\",\n \"donovan\": \"Donovan\"\n }\n colors = {\n 'donovan': 'red',\n 'elcajon': 'green',\n 'shafter': 'blue'\n }\n dwf = 75\n for metric in [\"epa-no2\", \"epa-o3\", \"temperature\", \"pressure\", \"absolute-humidity\"]:\n for train_location in LOCATIONS:\n for gas in tqdm.tqdm([\"NO2\", \"O3\"]):\n fig, ax = plt.subplots(subplot_kw=dict(projection='scatter_density'))\n # ax[0].scatter(filtered[metric], filtered[\"%s MAE\" % gas], label=MAP[train_location], alpha=0.1)\n axes = []\n for i, test_location in enumerate(LOCATIONS - {train_location}):\n filtered = df[(df['train_location'] == train_location) & (df['location'] == test_location)]\n error = \"%s MAE\" % gas\n # filtered = filtered[np.abs(filtered[metric]-filtered[metric].mean()) <= (2*filtered[metric].std())]\n # filtered = filtered[np.abs(filtered[error]-filtered[error].mean()) <= (3*filtered[error].std())]\n axes.append(mpatches.Patch(color=colors[test_location], label=MAP[test_location]))\n ax.scatter_density(filtered[metric], filtered[error], color=colors[test_location], label=MAP[test_location], dpi=dwf)\n # sns.kdeplot(filtered[metric], filtered[\"%s MAE\" % gas], ax=ax[i + 1])\n filtered = df[(df['train_location'] == train_location) & (df['location'] == train_location)]\n error = \"%s MAE\" % gas\n # filtered = filtered[np.abs(filtered[error]-filtered[error].mean()) <= (3*filtered[error].std())]\n ax.scatter_density(filtered[metric], filtered[error], color=colors[train_location], label=MAP[train_location], dpi=dwf)\n axes.append(mpatches.Patch(color=colors[train_location], label=MAP[train_location]))\n ax.legend(handles=axes)\n if gas == \"O3\" and metric == \"absolute-humidity\":\n # ax.set_xlim(args.x_low, args.x_high)\n ax.set_ylim(args.y_low, args.y_high)\n ax.set_ylabel(\"%s (ppb)\" % error)\n # ax[1].legend(loc='best')\n # ax[2].legend(loc='best')\n fig.savefig(out_path / (\"error_density_%s_%s_%s.png\" % (metric, train_location, gas)), dpi=200, bbox_inches='tight')\n plt.close(fig)\n","sub_path":"MetaSenseTransfer/scripts/generate_error_plots.py","file_name":"generate_error_plots.py","file_ext":"py","file_size_in_byte":4166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"362148484","text":"\"\"\"First, welcome module asking about player name\"\"\"\nimport pygame\nfrom Front import TextBox\n\n\nclass HelloMenu:\n \"\"\"Class responsible for getting PLAYER NAME and create a new one\"\"\"\n\n def __init__(self):\n self.screen = pygame.display.set_mode((800, 600))\n menu_background = pygame.image.load('Images\\\\menu_background.png')\n self.screen = pygame.display.get_surface()\n self.screen.blit(menu_background, (0, 0))\n self.ok_button = pygame.Rect(350, 440, 105, 78)\n self.game_state = True\n self.input_entered = ''\n self.box = TextBox.TextBox(pygame.Rect(240, 360, 320, 50), 1)\n\n self.clear()\n self.show_text('Podaj nick:')\n\n pygame.display.flip()\n\n def clear(self):\n \"\"\"\n Clear the screen, it is needed to show properly entered data\n \"\"\"\n tittle = pygame.image.load('Images\\\\tittle.png')\n tittle = pygame.transform.scale(tittle, (634, 148))\n self.screen.blit(tittle, (90, 30))\n\n textbox = pygame.image.load('Images\\\\input.png')\n self.screen.blit(textbox, (217, 340))\n\n ok_button = pygame.image.load('Images\\\\buttons\\\\ok.png')\n ok_button = pygame.transform.scale(ok_button, (105, 78))\n self.screen.blit(ok_button, (350, 440))\n\n def show_text(self, text):\n \"\"\"\n :param text: text to show on a screen\n :return: text on screen\n \"\"\"\n pygame.font.init()\n myfont = pygame.font.SysFont(\"Gabriola\", 40)\n\n textsurface = myfont.render(text, False, (255, 255, 255))\n self.screen.blit(textsurface, (235, 300))\n\n def update(self):\n \"\"\"\n Update and clear textbox\n \"\"\"\n self.clear()\n self.box.update(self.screen)\n pygame.display.flip()\n\n def start(self):\n \"\"\"\n Main loop of HelloMenu\n \"\"\"\n\n while self.game_state:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.game_state = False\n\n elif event.type == pygame.KEYDOWN:\n self.input_entered = self.box.char_add(event)\n\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n if self.ok_button.collidepoint(pygame.mouse.get_pos()):\n ok_button_click = pygame.image.load('Images\\\\buttons\\\\ok_click.png')\n ok_button_click = pygame.transform.scale(ok_button_click, (105, 78))\n self.screen.blit(ok_button_click, (350, 440))\n\n pygame.display.flip()\n\n if self.input_entered != '' and self.input_entered != 'Computer':\n self.game_state = False\n return self.input_entered\n else:\n self.box.str_list = []\n\n self.update()\n","sub_path":"Front/HelloMenu.py","file_name":"HelloMenu.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"157499351","text":"# Adapted from:\n# https://github.com/akanazawa/cmr/blob/c24cab6aececa1cb8416ccb2d3ee470915726937/data/cub.py\n\n\"\"\"\nCUB has 11788 images total, for 200 subcategories.\n5994 train, 5794 test images.\n\nAfter removing images that are truncated:\nmin kp threshold 6: 5964 train, 5771 test.\nmin_kp threshold 7: 5937 train, 5747 test.\n\n\"\"\"\n\nimport os.path as osp\nimport numpy as np\n\nimport scipy.io as sio\n\nimport torch\nfrom torch.utils.data import Dataset\n\nfrom . import base as base_data\n\n# -------------- Dataset ------------- #\n# ------------------------------------ #\nclass CUBDataset(base_data.BaseDataset):\n '''\n CUB Data loader\n '''\n\n def __init__(self, split, is_train, img_size):\n super().__init__(is_train, img_size)\n \n curr_path = osp.dirname(osp.abspath(__file__))\n cache_path = osp.join(curr_path, '..', 'datasets', 'cub')\n self.data_cache_dir = cache_path\n self.data_dir = osp.join(cache_path, 'CUB_200_2011')\n\n self.img_dir = osp.join(self.data_dir, 'images')\n self.anno_path = osp.join(self.data_cache_dir, 'data', '%s_cub_cleaned.mat' % split)\n self.anno_sfm_path = osp.join(self.data_cache_dir, 'sfm', 'anno_%s.mat' % split)\n\n if not osp.exists(self.anno_path):\n raise ValueError('%s doesnt exist!' % self.anno_path)\n\n # Load the annotation file.\n print('loading %s' % self.anno_path)\n self.anno = sio.loadmat(\n self.anno_path, struct_as_record=False, squeeze_me=True)['images']\n self.anno_sfm = sio.loadmat(\n self.anno_sfm_path, struct_as_record=False, squeeze_me=True)['sfm_anno']\n\n self.num_imgs = len(self.anno)\n print('%d images' % self.num_imgs)\n self.kp_perm = np.array([1, 2, 3, 4, 5, 6, 11, 12, 13, 10, 7, 8, 9, 14, 15]) - 1\n","sub_path":"code/datasets_preprocessing/cub.py","file_name":"cub.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"93180379","text":"class HTML:\r\n\tdef __init__(self, html_tag, output=\"screen\"):\r\n\t\tself.html_tag = html_tag\r\n\t\tself.children = []\r\n\t\t\r\n\t\tself.output = output\r\n\t\tself.file = None\r\n\r\n\tdef __enter__(self):\r\n\t\tif self.output != \"screen\":\r\n\t\t\tself.file = open(self.output, \"w\")\r\n\t\treturn self\r\n\r\n\tdef __exit__(self, type, value, traceback):\r\n\t\tif self.file:\r\n\t\t\tself.file.write(str(self))\r\n\t\t\tself.file.close()\r\n\r\n\tdef __iadd__(self, other):\r\n\t\tself.children.append(other)\r\n\t\treturn self\r\n\r\n\tdef __str__(self):\r\n\t\topening = \"<%s>\\n\" % self.html_tag\r\n\t\tinternal = \"\"\r\n\t\tclosing = \"\" % self.html_tag\r\n\r\n\t\tif self.children:\r\n\t\t\tfor child in self.children:\r\n\t\t\t\tinternal += str(child)\r\n\r\n\t\thtml_element = opening + internal + closing\r\n\r\n\t\treturn html_element\r\n\r\n\r\nclass TopLevelTag:\r\n\tdef __init__(self, top_level_tag):\r\n\t\tself.top_level_tag = top_level_tag\r\n\t\tself.children = []\r\n\r\n\tdef __enter__(self):\r\n\t\treturn self\r\n\r\n\tdef __exit__(self, type, value, traceback): pass\r\n\r\n\tdef __iadd__(self, other):\r\n\t\tself.children.append(other)\r\n\t\treturn self\r\n\r\n\tdef __str__(self):\r\n\t\topening = \"<%s>\\n\" % self.top_level_tag\r\n\t\tinternal = \"\"\r\n\t\tclosing = \"\\n\" % self.top_level_tag\r\n\r\n\t\tif self.children:\r\n\t\t\tfor child in self.children:\r\n\t\t\t\tinternal += str(child)\r\n\r\n\t\ttop_level_element = opening + internal + closing\r\n\r\n\t\treturn top_level_element\r\n\r\n\r\nclass LevelTag:\r\n\tdef __init__(self, level_tag, **kwargs):\r\n\t\tself.level_tag = level_tag\r\n\t\tself.children = []\r\n\t\tself.attributes = {}\r\n\r\n\t\tfor attr, value in kwargs.items():\r\n\t\t\tif attr == \"class_\":\r\n\t\t\t\tattr = \"class\"\r\n\t\t\t\tvalue = \" \".join(value)\r\n\t\t\tself.attributes[attr] = value\r\n\r\n\tdef __enter__(self):\r\n\t\treturn self\r\n\r\n\tdef __exit__(self, type, value, traceback): pass\r\n\r\n\tdef __iadd__(self, other):\r\n\t\tself.children.append(other)\r\n\t\treturn self\r\n\r\n\tdef __str__(self):\r\n\t\topening = \" <%s\" % self.level_tag\r\n\r\n\t\tif self.attributes:\r\n\t\t\tfor attr, value in self.attributes.items():\r\n\t\t\t\topening += ' %s=\"%s\"' % (attr, value)\r\n\t\topening += '>\\n'\r\n\t\t\r\n\t\tinternal = \"\"\r\n\t\tclosing = \" \\n\" % self.level_tag\r\n\r\n\t\tif self.children:\r\n\t\t\tfor child in self.children:\r\n\t\t\t\tinternal += str(child)\r\n\r\n\t\tlevel_element = opening + internal + closing\r\n\r\n\t\treturn level_element\r\n\r\n\r\nclass Tag:\r\n\tdef __init__(self, tag, is_single=False, **kwargs):\r\n\t\tself.tag = tag\r\n\t\tself.is_single = is_single\r\n\t\tself.children = []\r\n\t\tself.text = \"\"\r\n\t\tself.attributes = {}\r\n\r\n\t\tfor attr, value in kwargs.items():\r\n\t\t\tif \"_\" in attr:\r\n\t\t\t\tattr = attr.replace(\"_\",\"-\")\r\n\t\t\tif attr == \"klass\":\r\n\t\t\t\tattr = \"class\"\r\n\t\t\t\tvalue = \" \".join(value)\r\n\t\t\tself.attributes[attr] = value\r\n\r\n\tdef __enter__(self):\r\n\t\treturn self\r\n\r\n\tdef __exit__(self, type, value, traceback): pass\r\n\r\n\tdef __iadd__(self, other):\r\n\t\tself.children.append(other)\r\n\t\treturn self\r\n\r\n\tdef __str__(self):\r\n\t\topening = \" <%s\" % self.tag\r\n\t\tif self.attributes:\r\n\t\t\tfor attr, value in self.attributes.items():\r\n\t\t\t\topening += ' %s=\"%s\"' % (attr, value)\r\n\t\topening += '>'\r\n\t\t\r\n\t\tinternal = self.text\r\n\r\n\t\tclosing = \"\\n\" % self.tag\r\n\r\n\t\tif self.is_single: return opening + \"\\n\"\r\n\r\n\t\tif self.children:\r\n\t\t\tfor child in self.children:\r\n\t\t\t\tinternal += str(child)\r\n\r\n\t\t_element = opening + internal + closing\r\n\r\n\t\treturn _element","sub_path":"classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"17321696","text":"\"\"\"\r\nCreate an empty set. WAP that adds five new names to this set, modifies one existing name and deletes two existing names in it.\r\n\"\"\"\r\n\r\nS = set() # empty set. S = () does not work\r\nprint(S)\r\n\r\nS.add('Karthi')\r\nS.add('Vikram')\r\nS.add('Vijay Sethupathi')\r\nS.add('Simbu')\r\nS.add('Ajith')\r\nprint(S)\r\n\r\n# modify one name\r\nS.remove('Ajith')\r\nS.add('Thala')\r\nprint(S)\r\n\r\n# delete two existing names\r\nS.remove('Simbu')\r\nS.discard('Vikram')\r\nprint(S)","sub_path":"Chapter-7-Tuples/Exercise/A/b-set-operations.py","file_name":"b-set-operations.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"335128174","text":"import json\nfrom urllib import urlencode\n\nfrom twisted.internet.defer import inlineCallbacks\nfrom twisted.web import http\n\nfrom vumi.transports.tests.utils import TransportTestCase\nfrom vumi.transports.airtel import AirtelUSSDTransport\nfrom vumi.message import TransportUserMessage\nfrom vumi.utils import http_request_full\n\n\nclass TestAirtelUSSDTransportTestCase(TransportTestCase):\n\n transport_class = AirtelUSSDTransport\n airtel_username = None\n airtel_password = None\n session_id = 'session-id'\n\n @inlineCallbacks\n def setUp(self):\n yield super(TestAirtelUSSDTransportTestCase, self).setUp()\n self.config = {\n 'web_port': 0,\n 'web_path': '/api/v1/airtel/ussd/',\n 'airtel_username': self.airtel_username,\n 'airtel_password': self.airtel_password,\n 'validation_mode': 'permissive',\n }\n self.transport = yield self.get_transport(self.config)\n self.session_manager = self.transport.session_manager\n self.transport_url = self.transport.get_transport_url(\n self.config['web_path'])\n yield self.session_manager.redis._purge_all() # just in case\n\n @inlineCallbacks\n def tearDown(self):\n yield super(TestAirtelUSSDTransportTestCase, self).tearDown()\n yield self.session_manager.stop()\n\n def mk_full_request(self, **params):\n return http_request_full('%s?%s' % (self.transport_url,\n urlencode(params)), data='', method='GET')\n\n def mk_request(self, **params):\n defaults = {\n 'MSISDN': '27761234567',\n }\n if all([self.airtel_username, self.airtel_password]):\n defaults.update({\n 'userid': self.airtel_username,\n 'password': self.airtel_password,\n })\n\n defaults.update(params)\n return self.mk_full_request(**defaults)\n\n def mk_ussd_request(self, content, **kwargs):\n defaults = {\n 'MSC': 'msc',\n 'input': content,\n 'SessionID': self.session_id,\n }\n defaults.update(kwargs)\n return self.mk_request(**defaults)\n\n def mk_cleanup_request(self, **kwargs):\n defaults = {\n 'clean': 'clean-session',\n 'error': 522,\n 'SessionID': self.session_id,\n }\n defaults.update(kwargs)\n return self.mk_request(**defaults)\n\n @inlineCallbacks\n def test_inbound_begin(self):\n # Second connect is the actual start of the session\n deferred = self.mk_ussd_request('121')\n [msg] = yield self.wait_for_dispatched_messages(1)\n self.assertEqual(msg['content'], '')\n self.assertEqual(msg['to_addr'], '*121#')\n self.assertEqual(msg['from_addr'], '27761234567'),\n self.assertEqual(msg['session_event'],\n TransportUserMessage.SESSION_NEW)\n self.assertEqual(msg['transport_metadata'], {\n 'airtel': {\n 'MSC': 'msc',\n },\n })\n\n reply = TransportUserMessage(**msg.payload).reply(\"ussd message\")\n self.dispatch(reply)\n response = yield deferred\n self.assertEqual(response.delivered_body, 'ussd message')\n self.assertEqual(response.headers.getRawHeaders('Freeflow'), ['FC'])\n self.assertEqual(response.headers.getRawHeaders('charge'), ['N'])\n self.assertEqual(response.headers.getRawHeaders('amount'), ['0'])\n\n @inlineCallbacks\n def test_inbound_resume_and_reply_with_end(self):\n # first pre-populate the redis datastore to simulate prior BEG message\n yield self.session_manager.create_session(self.session_id,\n to_addr='*167*7#', from_addr='27761234567',\n session_event=TransportUserMessage.SESSION_RESUME)\n\n # Safaricom gives us the history of the full session in the USSD_PARAMS\n # The last submitted bit of content is the last value delimited by '*'\n deferred = self.mk_ussd_request('c')\n\n [msg] = yield self.wait_for_dispatched_messages(1)\n self.assertEqual(msg['content'], 'c')\n self.assertEqual(msg['to_addr'], '*167*7#')\n self.assertEqual(msg['from_addr'], '27761234567')\n self.assertEqual(msg['session_event'],\n TransportUserMessage.SESSION_RESUME)\n\n reply = TransportUserMessage(**msg.payload).reply(\"hello world\",\n continue_session=False)\n self.dispatch(reply)\n response = yield deferred\n self.assertEqual(response.delivered_body, 'hello world')\n self.assertEqual(response.headers.getRawHeaders('Freeflow'), ['FB'])\n\n @inlineCallbacks\n def test_inbound_resume_with_failed_to_addr_lookup(self):\n deferred = self.mk_request(MSISDN='123456',\n input='7*a', SessionID='foo')\n response = yield deferred\n self.assertEqual(json.loads(response.delivered_body), {\n 'missing_parameter': ['MSC'],\n })\n\n @inlineCallbacks\n def test_to_addr_handling(self):\n d1 = self.mk_ussd_request('167*7*1')\n [msg1] = yield self.wait_for_dispatched_messages(1)\n self.assertEqual(msg1['to_addr'], '*167*7*1#')\n self.assertEqual(msg1['content'], '')\n self.assertEqual(msg1['session_event'],\n TransportUserMessage.SESSION_NEW)\n reply = TransportUserMessage(**msg1.payload).reply(\"hello world\",\n continue_session=True)\n yield self.dispatch(reply)\n yield d1\n\n # follow up with the user submitting 'a'\n d2 = self.mk_ussd_request('a')\n [msg1, msg2] = yield self.wait_for_dispatched_messages(2)\n self.assertEqual(msg2['to_addr'], '*167*7*1#')\n self.assertEqual(msg2['content'], 'a')\n self.assertEqual(msg2['session_event'],\n TransportUserMessage.SESSION_RESUME)\n reply = TransportUserMessage(**msg2.payload).reply(\"hello world\",\n continue_session=False)\n self.dispatch(reply)\n yield d2\n\n @inlineCallbacks\n def test_hitting_url_twice_without_content(self):\n d1 = self.mk_ussd_request('167*7*3')\n [msg1] = yield self.wait_for_dispatched_messages(1)\n self.assertEqual(msg1['to_addr'], '*167*7*3#')\n self.assertEqual(msg1['content'], '')\n self.assertEqual(msg1['session_event'],\n TransportUserMessage.SESSION_NEW)\n reply = TransportUserMessage(**msg1.payload).reply('Hello',\n continue_session=True)\n self.dispatch(reply)\n yield d1\n\n # make the exact same request again\n d2 = self.mk_ussd_request('')\n [msg1, msg2] = yield self.wait_for_dispatched_messages(2)\n self.assertEqual(msg2['to_addr'], '*167*7*3#')\n self.assertEqual(msg2['content'], '')\n self.assertEqual(msg2['session_event'],\n TransportUserMessage.SESSION_RESUME)\n reply = TransportUserMessage(**msg2.payload).reply('Hello',\n continue_session=True)\n self.dispatch(reply)\n yield d2\n\n @inlineCallbacks\n def test_submitting_asterisks_as_values(self):\n yield self.session_manager.create_session(self.session_id,\n to_addr='*167*7#', from_addr='27761234567')\n # we're submitting a bunch of *s\n deferred = self.mk_ussd_request('****')\n\n [msg] = yield self.wait_for_dispatched_messages(1)\n self.assertEqual(msg['content'], '****')\n\n reply = TransportUserMessage(**msg.payload).reply('Hello',\n continue_session=True)\n self.dispatch(reply)\n yield deferred\n\n @inlineCallbacks\n def test_submitting_asterisks_as_values_after_asterisks(self):\n yield self.session_manager.create_session(self.session_id,\n to_addr='*167*7#', from_addr='27761234567')\n # we're submitting a bunch of *s\n deferred = self.mk_ussd_request('**')\n\n [msg] = yield self.wait_for_dispatched_messages(1)\n self.assertEqual(msg['content'], '**')\n\n reply = TransportUserMessage(**msg.payload).reply('Hello',\n continue_session=True)\n self.dispatch(reply)\n yield deferred\n\n @inlineCallbacks\n def test_submitting_with_base_code_empty_ussd_params(self):\n d1 = self.mk_ussd_request('167')\n [msg1] = yield self.wait_for_dispatched_messages(1)\n self.assertEqual(msg1['to_addr'], '*167#')\n self.assertEqual(msg1['content'], '')\n self.assertEqual(msg1['session_event'],\n TransportUserMessage.SESSION_NEW)\n reply = TransportUserMessage(**msg1.payload).reply('Hello',\n continue_session=True)\n self.dispatch(reply)\n yield d1\n\n # ask for first menu\n d2 = self.mk_ussd_request('1')\n [msg1, msg2] = yield self.wait_for_dispatched_messages(2)\n self.assertEqual(msg2['to_addr'], '*167#')\n self.assertEqual(msg2['content'], '1')\n self.assertEqual(msg2['session_event'],\n TransportUserMessage.SESSION_RESUME)\n reply = TransportUserMessage(**msg2.payload).reply('Hello',\n continue_session=True)\n self.dispatch(reply)\n yield d2\n\n # ask for second menu\n d3 = self.mk_ussd_request('1')\n [msg1, msg2, msg3] = yield self.wait_for_dispatched_messages(3)\n self.assertEqual(msg3['to_addr'], '*167#')\n self.assertEqual(msg3['content'], '1')\n self.assertEqual(msg3['session_event'],\n TransportUserMessage.SESSION_RESUME)\n reply = TransportUserMessage(**msg3.payload).reply('Hello',\n continue_session=True)\n self.dispatch(reply)\n yield d3\n\n @inlineCallbacks\n def test_cleanup_unknown_session(self):\n response = yield self.mk_cleanup_request(msisdn='foo')\n self.assertEqual(response.code, http.OK)\n self.assertEqual(response.delivered_body, 'Unknown Session')\n\n @inlineCallbacks\n def test_cleanup_session(self):\n yield self.session_manager.create_session(self.session_id,\n to_addr='*167*7#', from_addr='27761234567')\n response = yield self.mk_cleanup_request(msisdn='27761234567')\n self.assertEqual(response.code, http.OK)\n self.assertEqual(response.delivered_body, '')\n [msg] = yield self.wait_for_dispatched_messages(1)\n self.assertEqual(msg['session_event'],\n TransportUserMessage.SESSION_CLOSE)\n self.assertEqual(msg['to_addr'], '*167*7#')\n self.assertEqual(msg['from_addr'], '27761234567')\n self.assertEqual(msg['transport_metadata'], {\n 'airtel': {\n 'error': '522',\n 'clean': 'clean-session',\n }\n })\n\n @inlineCallbacks\n def test_cleanup_session_missing_params(self):\n response = yield self.mk_request(clean='clean-session')\n self.assertEqual(response.code, http.BAD_REQUEST)\n json_response = json.loads(response.delivered_body)\n self.assertEqual(set(json_response['missing_parameter']),\n set(['msisdn', 'SessionID', 'error']))\n\n @inlineCallbacks\n def test_cleanup_as_seen_in_production(self):\n \"\"\"what's a technical spec between friends?\"\"\"\n yield self.session_manager.create_session('13697502734175597',\n to_addr='*167*7#', from_addr='254XXXXXXXXX')\n query_string = (\"msisdn=254XXXXXXXXX&clean=cleann&error=523\"\n \"&SessionID=13697502734175597&MSC=254XXXXXXXXX\"\n \"&=&=en&=9031510005344&=&=&=postpaid\"\n \"&=20130528171235405&=200220130528171113956582\")\n response = yield http_request_full(\n '%s?%s' % (self.transport_url, query_string),\n data='', method='GET')\n self.assertEqual(response.code, http.OK)\n self.assertEqual(response.delivered_body, '')\n [msg] = yield self.wait_for_dispatched_messages(1)\n self.assertEqual(msg['session_event'],\n TransportUserMessage.SESSION_CLOSE)\n self.assertEqual(msg['to_addr'], '*167*7#')\n self.assertEqual(msg['from_addr'], '254XXXXXXXXX')\n self.assertEqual(msg['transport_metadata'], {\n 'airtel': {\n 'clean': 'cleann',\n 'error': '523',\n }\n })\n\n\nclass TestAirtelUSSDTransportTestCaseWithAuth(TestAirtelUSSDTransportTestCase):\n\n transport_class = AirtelUSSDTransport\n airtel_username = 'userid'\n airtel_password = 'password'\n\n @inlineCallbacks\n def test_cleanup_session_invalid_auth(self):\n response = yield self.mk_cleanup_request(userid='foo', password='bar')\n self.assertEqual(response.code, http.FORBIDDEN)\n self.assertEqual(response.delivered_body, 'Forbidden')\n\n @inlineCallbacks\n def test_cleanup_as_seen_in_production(self):\n \"\"\"what's a technical spec between friends?\"\"\"\n yield self.session_manager.create_session('13697502734175597',\n to_addr='*167*7#', from_addr='254XXXXXXXXX')\n query_string = (\"msisdn=254XXXXXXXXX&clean=cleann&error=523\"\n \"&SessionID=13697502734175597&MSC=254XXXXXXXXX\"\n \"&=&=en&=9031510005344&=&=&=postpaid\"\n \"&=20130528171235405&=200220130528171113956582\"\n \"&userid=%s&password=%s\" % (self.airtel_username,\n self.airtel_password))\n response = yield http_request_full(\n '%s?%s' % (self.transport_url, query_string),\n data='', method='GET')\n self.assertEqual(response.code, http.OK)\n self.assertEqual(response.delivered_body, '')\n [msg] = yield self.wait_for_dispatched_messages(1)\n self.assertEqual(msg['session_event'],\n TransportUserMessage.SESSION_CLOSE)\n self.assertEqual(msg['to_addr'], '*167*7#')\n self.assertEqual(msg['from_addr'], '254XXXXXXXXX')\n self.assertEqual(msg['transport_metadata'], {\n 'airtel': {\n 'clean': 'cleann',\n 'error': '523',\n }\n })\n","sub_path":"vumi/transports/airtel/tests/test_airtel.py","file_name":"test_airtel.py","file_ext":"py","file_size_in_byte":14125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"438741024","text":"import json\nimport os\nfrom typing import Dict\n\nimport torch\nimport torch.nn as nn\nimport yaml\n\nfrom pytorch_ner.onnx import onnx_export_and_check\nfrom pytorch_ner.utils import mkdir, rmdir\n\n\ndef save_model(\n path_to_folder: str,\n model: nn.Module,\n token2idx: Dict[str, int],\n label2idx: Dict[str, int],\n config: Dict,\n export_onnx: bool = False,\n):\n # make empty dir\n rmdir(path_to_folder)\n mkdir(path_to_folder)\n\n model.cpu()\n model.eval()\n\n # save torch model\n torch.save(model.state_dict(), os.path.join(path_to_folder, \"model.pth\"))\n\n # save token2idx\n with open(file=os.path.join(path_to_folder, \"token2idx.json\"), mode=\"w\") as fp:\n json.dump(token2idx, fp)\n\n # save label2idx\n with open(file=os.path.join(path_to_folder, \"label2idx.json\"), mode=\"w\") as fp:\n json.dump(label2idx, fp)\n\n # save config\n with open(file=os.path.join(path_to_folder, \"config.yaml\"), mode=\"w\") as fp:\n yaml.dump(config, fp)\n\n # save onnx model\n if export_onnx:\n onnx_export_and_check(\n model=model, path_to_save=os.path.join(path_to_folder, \"model.onnx\")\n )\n","sub_path":"pytorch_ner/save.py","file_name":"save.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"299823570","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 24 23:54:13 2018\n\n@author: impawan\n\n\n\"\"\"\n\nimport cv2\nimport numpy as np\n\nimg = cv2.imread('bookpage.jpg')\n#normal threshold also called fixed threshold that is applied on BGR image\nretval,thershold = cv2.threshold(img,12,255,cv2.THRESH_BINARY)\n\n#threshold of image after changibg it to greyscale\ngeryscaled = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\nretval2,thershold2 = cv2.threshold(geryscaled,12,255,cv2.THRESH_BINARY)\n\n\n#using adapative threshold\ngaus = cv2.adaptiveThreshold(geryscaled,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,115,1)\ncv2.imshow('orignal',img)\n\ncv2.imshow('thres',thershold) \n \ncv2.imshow('thres2',thershold2)\ncv2.imshow('gaus',gaus)\n\n\n\n\ncv2.waitKey(0)\n\ncv2.destroyAllWindows()","sub_path":"Computer Vision/ImageAndVideoAnalysis.py","file_name":"ImageAndVideoAnalysis.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"338866059","text":"# -*- coding:utf-8 -*-\n\nfrom twisted.internet.defer import inlineCallbacks, returnValue\nfrom autobahn.twisted.util import sleep\nfrom wamputils.logger import getLog\nlog = getLog(__name__)\n\nfrom pysnmp.hlapi.twisted import getCmd, SnmpEngine, CommunityData, UdpTransportTarget, ContextData, ObjectType, ObjectIdentity\nfrom pysnmp.proto import rfc1902\nfrom pyasn1.type import univ\n\ntagMap = {\n rfc1902.Counter32.tagSet: int,\n rfc1902.Counter64.tagSet: int,\n rfc1902.Gauge32.tagSet: int,\n rfc1902.Integer32.tagSet: int,\n rfc1902.IpAddress.tagSet: str,\n univ.Null.tagSet: str,\n univ.ObjectIdentifier.tagSet: str,\n rfc1902.OctetString.tagSet: str,\n rfc1902.TimeTicks.tagSet: int,\n }\n\n\nsnmpEngine = SnmpEngine()\n\nclass MIB(dict):\n def __init__(self, device, config):\n self.device = device\n self.id = config.get('id')\n self.value = None\n self.update(config)\n self.class_ = config.get('class','generic')\n self.aggregation = config.get('aggregation','')\n self.community = config.get('community','public')\n\n def __repr__(self):\n return \"\"\"\"\"\".format(self['mib'], self.value)\n\n def updateCarbon(self):\n if self.value:\n self.device.updateCarbon(self.id + ('.'+self.aggregation if self.aggregation else ''), self.value)\n\n @inlineCallbacks\n def poll(self):\n if '.' in self['mib']:\n objtype = ObjectType(ObjectIdentity(self['mib']))\n else:\n objtype = ObjectType(ObjectIdentity('SNMPv2-MIB', self['mib'], 0))\n\n\n a,b,varbinds = yield getCmd(snmpEngine,\n CommunityData(self.community, mpModel=1),\n UdpTransportTarget((self.device.ip, 161), timeout=3, retries=0),\n ContextData(),\n objtype,\n lookupMib=False,\n #ObjectType(ObjectIdentity('.1.3.6.1.2.1.2.2.1.2.1'))\n #\n )\n\n #yield sleep(3)\n if varbinds:\n # varbinds = [(oid_result, val), (oid_result, val), ...]\n self.value = [tagMap[varbind[1].tagSet](varbind[1]) for varbind in varbinds]\n if self.value and len(self.value)==1:\n self.value = self.value[0]\n\n log.info(\" \"*4 + str(self))\n if self.class_ != 'string':\n self.updateCarbon() # questo è già asincrono\n else:\n self.value = None\n returnValue(self.value)\n\n\n@inlineCallbacks\ndef poll(device):\n for mib in device.mibs:\n try:\n yield mib.poll()\n except Exception as e:\n log.error(\"mib failed: %s\" % str(mib))\n returnValue(device)\n","sub_path":"anms/snmp.py","file_name":"snmp.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"110949723","text":"import numpy as np\nimport random\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport scipy.misc\nimport os\nimport csv\nimport itertools\nimport tensorflow.contrib.slim as slim\nfrom PIL import Image\nfrom PIL import ImageDraw \nfrom PIL import ImageFont\n\n\n# Copies one set of variables to another.\n# Used to set worker network parameters to those of global network.\ndef update_target_graph(from_scope,to_scope):\n from_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, from_scope)\n to_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, to_scope)\n\n op_holder = []\n for from_var,to_var in zip(from_vars,to_vars):\n op_holder.append(to_var.assign(from_var))\n return op_holder\n\n# Discounting function used to calculate discounted returns.\ndef discount(x, gamma):\n return scipy.signal.lfilter([1], [1, -gamma], x[::-1], axis=0)[::-1]\n\n#Used to initialize weights for policy and value output layers\ndef normalized_columns_initializer(std=1.0):\n def _initializer(shape, dtype=None, partition_info=None):\n out = np.random.randn(*shape).astype(np.float32)\n out *= std / np.sqrt(np.square(out).sum(axis=0, keepdims=True))\n return tf.constant(out)\n return _initializer\n\n\n#This code allows gifs to be saved of the training episode for use in the Control Center.\ndef make_gif(images, fname, duration=2, true_image=False):\n import moviepy.editor as mpy\n \n def make_frame(t):\n try:\n x = images[int(len(images)/duration*t)]\n except:\n x = images[-1]\n\n if true_image:\n return x.astype(np.uint8)\n else:\n return ((x+1)/2*255).astype(np.uint8)\n \n clip = mpy.VideoClip(make_frame, duration=duration)\n clip.write_gif(fname, fps = len(images) / duration,verbose=False)\n\ndef set_image_daw(values,probs,state,trial,state_cnt,reward_dist):\n daw_image = Image.open('./resources/daw.png').convert('RGB')\n draw = ImageDraw.Draw(daw_image)\n font = ImageFont.truetype(\"./resources/FreeSans.ttf\", 24)\n\n draw.text((0, 0),'Trial: ' + str(trial),(0,0,0),font=font) \n total_reward = sum(values)\n draw.text((0,30),'Total Reward: ' + str(total_reward), (0,0,255), font=font)\n\n #plot state transition probability\n draw.text((114, 250),'Prob: ',(255,0,0),font=font)\n draw.text((340, 250),str(float(\"{0:.2f}\".format(probs[0][0]))),(255,0,0),font=font)\n draw.text((500, 250),str(float(\"{0:.2f}\".format(probs[0][1]))),(255,0,0),font=font)\n draw.text((660, 250),str(float(\"{0:.2f}\".format(probs[1][0]))),(255,0,0),font=font)\n draw.text((820, 250),str(float(\"{0:.2f}\".format(probs[1][1]))),(255,0,0),font=font)\n\n #plot reward distribution\n draw.text((114, 350),'Reward: ',(0,0,0),font=font)\n draw.text((340, 350),str(\"%d\" % reward_dist[0][0]),(0,0,0),font=font) \n draw.text((500, 350),str(\"%d\" % reward_dist[0][1]),(0,0,0),font=font) \n draw.text((660, 350),str(\"%d\" % reward_dist[1][0]),(0,0,0),font=font) \n draw.text((820, 350),str(\"%d\" % reward_dist[1][1]),(0,0,0),font=font)\n\n #plot # of state arrive\n draw.text((114, 450), 'num(#): ', (0,0,0), font=font)\n draw.text((340, 450),str(\"%d\" % state_cnt[0]),(0,0,0),font=font) \n draw.text((500, 450),str(\"%d\" % state_cnt[1]),(0,0,0),font=font) \n draw.text((660, 450),str(\"%d\" % state_cnt[2]),(0,0,0),font=font) \n draw.text((820, 450),str(\"%d\" % state_cnt[3]),(0,0,0),font=font)\n\n #plot bar graph - total rewards in episode\n sign_list = []\n sign_list += (np.sign(reward_dist[0])).tolist()\n sign_list += (np.sign(reward_dist[1])).tolist()\n color_list = []\n for i in range(len(sign_list)):\n if(sign_list[i] == 1):\n color_list.append([0,255.0,0])\n elif(sign_list[i] == -1):\n color_list.append([255.0,0,0])\n else:\n color_list.append([0,0,0])\n\n daw_image = np.array(daw_image)\n daw_image[500:500+int(np.floor(abs(values[0]))),310:370,:] = color_list[0]\n daw_image[500:500+int(np.floor(abs(values[1]))),470:530,:] = color_list[1]\n daw_image[500:500+int(np.floor(abs(values[2]))),630:690,:] = color_list[2]\n daw_image[500:500+int(np.floor(abs(values[3]))),790:850,:] = color_list[3]\n daw_image[480:490,310+(state*160):310+(state*160)+60,:] = [80.0,80.0,225.0]\n\n return daw_image\n","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":4251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"496989843","text":"from bs4 import BeautifulSoup\r\nimport csv\r\ndef parse2(name3):\r\n name = name3.lower()\r\n data = open(\"profiles\\\\\" + name + \".htm\").read()\r\n # data = open('profiles\\ihsmarkit.htm').read()\r\n soup = BeautifulSoup(data,'html.parser')\r\n\r\n comp = soup.find('p',attrs={'id':'bDesc'})\r\n detail =soup.find('div',attrs={'class':'newsItem'})\r\n s = soup.find('div',attrs={'class':'floatL subColumn'})\r\n\r\n l = {}\r\n l['Company Info'] = comp.text\r\n # l['Detail'] = detail.text\r\n l['Sub'] = s.text\r\n str = comp.text\r\n str1 = str[:300]\r\n l['Overview'] = str1\r\n # print(comp.text)\r\n # print detail.text.strip()\r\n # print(s.text)\r\n # saveFile = open('file2.csv','w')\r\n # csv_writer = csv.writer(saveFile)\r\n # csv_writer.writerow(l)\r\n return l","sub_path":"company.py","file_name":"company.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"219084770","text":"import tensorflow as tf\nfrom .ops import *\n\nclass DuelingQ(tf.keras.Model):\n \"\"\" DuelingQ Agent\n\n input observations from environment --> learn a function that outputs\n a decision --> updates from reward signal\n\n DuelingQ splits action and value branches at the end. (?? ref ??)\n\n \"\"\"\n def __init__(self, action_dim, name='DuelingQ'):\n super(DuelingQ, self).__init__()\n\n nonlin = tf.nn.relu\n kernels = [32, 64, 128]\n adv_hidden = 256\n val_hidden = 256\n self.action_dim = action_dim\n self.gamma = 0.8\n\n conv_args = {\n 'kernel_size': 2,\n 'strides': 1, \n 'activation': nonlin,\n 'padding': 'valid',\n }\n self.conv0 = tf.layers.Conv2D(kernels[0], **conv_args)\n self.conv1 = tf.layers.Conv2D(kernels[1], **conv_args)\n self.conv2 = tf.layers.Conv2D(kernels[2], **conv_args)\n\n self.adv_value = tf.layers.Dense(adv_hidden+val_hidden,\n activation=nonlin)\n\n self.adv_arm_0 = tf.layers.Dense(adv_hidden, activation=nonlin)\n self.adv_arm_1 = tf.layers.Dense(adv_hidden, activation=nonlin)\n self.adv_pred = tf.layers.Dense(action_dim, activation=nonlin)\n\n self.val_arm_0 = tf.layers.Dense(val_hidden, activation=nonlin)\n self.val_arm_1 = tf.layers.Dense(val_hidden, activation=nonlin)\n self.val_pred = tf.layers.Dense(action_dim, activation=nonlin)\n\n self.optimizer = tf.train.RMSPropOptimizer(learning_rate=1e-5)\n\n def predictQ(self, state):\n state = tf.constant(state)\n net = self.conv0(state)\n net = self.conv1(net)\n net = self.conv2(net)\n net = tf.layers.flatten(net)\n net = self.adv_value(net)\n\n adv, value = tf.split(net, 2, 1)\n adv = self.adv_arm_0(adv)\n adv = self.adv_arm_1(adv)\n adv = self.adv_pred(adv)\n\n value = self.val_arm_0(value)\n value = self.val_arm_1(value)\n value = self.val_pred(value)\n\n adv_mean = tf.reduce_mean(adv, 1, keep_dims=True)\n predQ = value + (adv - adv_mean)\n return predQ\n\n def call(self, state):\n predQ = self.predictQ(state)\n action = tf.argmax(predQ, axis=1)\n return action, predQ\n\n # Q-Learning update function (Minh, et al. )\n def q_train(self, s_j, a_j, r_j, s_j1, is_end):\n with tf.GradientTape() as tape:\n q_j = self.predictQ(s_j)\n q_prime = tf.cast(self.predictQ(s_j1), tf.float32)\n\n # Augment target according to the reward singal\n nextQ = q_j.numpy()\n for idx, (a_jx, r_jx, is_end_j) in enumerate(zip(a_j, r_j, is_end)):\n if is_end_j:\n nextQ[idx, a_jx] = r_jx\n else:\n nextQ[idx, a_jx] = r_jx + self.gamma * np.max(q_prime[idx,:])\n \n # nextQ = tf.constant(nextQ, dtype=tf.float32)\n loss = self.loss_fn(nextQ, q_prime, a_j)\n grad = tape.gradient(loss, self.variables)\n\n # print('q_train gradients')\n # for gr, v in zip(grad, self.variables):\n # print(v.name, gr.shape)\n\n self.optimizer.apply_gradients(zip(grad, self.variables))\n return loss\n \n def loss_fn(self, nextQ, predQ, actions):\n action_onehot = tf.one_hot(actions, self.action_dim,\n dtype=tf.float32)\n Q = tf.reduce_sum(predQ * action_onehot, 1)\n nextQ = tf.reduce_sum(nextQ * action_onehot, 1)\n # print('loss', nextQ.shape, Q.shape)\n # print(nextQ)\n # print(Q)\n loss = tf.losses.mean_squared_error(labels=nextQ, \n predictions=Q)\n return loss\n\n \"\"\"\n with tf.variable_scope(name) as scope:\n ## input is number of orb types + 1 for selected\n self.state = tf.placeholder('float', [None, board_row, board_col, 7], name='state')\n print('state: ', self.state.get_shape())\n self.keep_prob = tf.placeholder_with_default(0.75, None, name='keep_prob')\n print('keep_prob: ', self.keep_prob.get_shape())\n\n ## Net definition\n net = nonlin(conv(self.state, kernels[0], ksize=3, stride=2, var_scope='h1'))\n print('h1: ', net.get_shape())\n net = nonlin(conv(net, kernels[1], ksize=2, stride=1, var_scope='h2'))\n print('h2: ', net.get_shape())\n net = nonlin(conv(net, kernels[2], ksize=2, stride=1, var_scope='h3'))\n print('h3: ', net.get_shape())\n net = nonlin(conv(net, kernels[3], ksize=2, stride=1, var_scope='h4'))\n print('h4: ', net.get_shape())\n\n net = tf.layers.flatten(net, name='flatten')\n print('flatten: ', net.get_shape())\n # net = tf.nn.dropout(net, self.keep_prob)\n\n ## Split advantage and value functions:\n net = nonlin(linear(net, 2048, var_scope='fork'))\n adv_split, val_split = tf.split(net, 2, 1)\n # adv_split = tf.identity(net)\n # val_split = tf.identity(net)\n\n print('adv_split flat: ', adv_split.get_shape())\n print('val_split flat: ', val_split.get_shape())\n\n adv_split = nonlin(linear(adv_split, adv_hidden, var_scope='adv'))\n adv_split = nonlin(linear(adv_split, action_dim, var_scope='adv_action'))\n print('adv: ', adv_split.get_shape())\n\n val_split = nonlin(linear(val_split, val_hidden, var_scope='val'))\n val_split = nonlin(linear(val_split, action_dim, var_scope='val_action'))\n print('value: ', val_split.get_shape())\n\n adv_mean = tf.reduce_mean(adv_split, 1, keep_dims=True)\n print('adv_mean: ', adv_mean.get_shape())\n\n ## Double stream -- put them back together\n self.Qpred = val_split + (adv_split - adv_mean)\n print('net output: ', self.Qpred.get_shape())\n\n ## For predicting\n self.actions = tf.placeholder(shape=[None],dtype=tf.int32, name='actions')\n print('actions: ', self.actions.get_shape())\n self.actions_onehot = tf.one_hot(self.actions, action_dim, \n dtype=tf.float32)\n\n ## Predicted Q, with r_t added\n # self.nextQ = tf.placeholder('float', [None,action_dim], name='nextQ')\n self.nextQ = tf.placeholder('float', [None, 5], name='nextQ')\n print('nextQ: ', self.nextQ.get_shape())\n\n ## Zero the others\n self.Q = tf.reduce_sum(self.Qpred * self.actions_onehot, 1)\n print('Q: ', self.Q.get_shape())\n self.delta = tf.square(self.nextQ - self.Q)\n print('delta: ', self.delta.get_shape())\n\n ## endpoint operations\n self.action_op = tf.argmax(self.Qpred, axis=1)\n print('action: ', self.action_op.get_shape())\n self.loss_op = tf.reduce_sum(clipped_error(self.delta))\n print('loss: ', self.loss_op.get_shape())\n\n self.optimize_op = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(self.loss_op)\n self.init_op = tf.global_variables_initializer()\n \"\"\"","sub_path":"agent/models/duelingq.py","file_name":"duelingq.py","file_ext":"py","file_size_in_byte":7185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"467161976","text":"\nfrom __future__ import division, print_function\nimport sys\nimport os\nfrom collections import OrderedDict\nimport logging\nimport shutil\n\nimport numpy as np\nimport tensorflow as tf\n# import minitest\n\nsys.path.append(\"..\")\n# from tf_unet import util\n\n# tf.nn.conv3d [batch, in_depth, in_height, in_width, in_channels]\n# https://www.tensorflow.org/api_docs/python/tf/nn/conv3d\n# 2d w [filter_height, filter_width, in_channels, out_channels]\n# 3d w [filter_depth, filter_height, filter_width, in_channels, out_channels]\n\n# lasagne.layers.dnn.Conv3DDNNLayer \n# (batch_size, num_input_channels, input_depth, input_rows, input_columns)\n# http://lasagne.readthedocs.io/en/latest/modules/layers/dnn.html\n# 2d w (num_filters, num_input_channels, filter_rows, filter_columns)\n# 3d w (num_filters, num_input_channels, filter_depth, filter_rows, filter_columns)\n\ndef crop_and_concat3d(x1,x2):\n x1_shape = tf.shape(x1)\n x2_shape = tf.shape(x2)\n # offsets for the top left corner of the crop\n offsets = [0, (x1_shape[1] - x2_shape[1]) // 2, \n (x1_shape[2] - x2_shape[2]) // 2, \n (x1_shape[3] - x2_shape[3]) // 2, 0]\n size = [-1, x2_shape[1], x2_shape[2], x2_shape[3], -1]\n x1_crop = tf.slice(x1, offsets, size)\n # change for tf 1.0\n # return tf.concat(3, [x1_crop, x2])\n return tf.concat([x1_crop, x2], 4)\n\ndef create_3d_unet(channels, n_class, **kwargs):\n features_root = kwargs.get(\"features_root\", 32)\n layers = kwargs.get(\"layers\", 4)\n filter_size = kwargs.get(\"filter_size\", 3)\n pool_size = kwargs.get(\"pool_size\", 2)\n summaries = kwargs.get(\"summaries\", True)\n\n # Remove nodes from graph or reset entire default graph\n tf.reset_default_graph()\n\n x = tf.placeholder(tf.float32, name=\"x-input\",\n shape=[None, None, None, None, channels])\n y = tf.placeholder(tf.float32, name=\"y-input\",\n shape=[None, None, None, None, n_class])\n\n keep_prob = tf.placeholder(tf.float32)\n\n\n in_node = tf.reshape(x, tf.stack(\n [-1,tf.shape(x)[1],tf.shape(x)[2],tf.shape(x)[3],channels]))\n batch_size = tf.shape(in_node)[0]\n \n weights = []\n biases = []\n # convs = []\n # pools = OrderedDict()\n # deconv = OrderedDict()\n dw_h_convs = OrderedDict()\n up_h_convs = OrderedDict()\n\n features = features_root\n # down layers\n for layer in range(0, layers):\n stddev = np.sqrt(2 / (filter_size**2 * features))\n layer.p()\n \n if layer == 0:\n w1 = tf.Variable(tf.truncated_normal([filter_size, filter_size, \n filter_size, channels, features], stddev))\n else:\n w1 = tf.Variable(tf.truncated_normal([filter_size, filter_size, \n filter_size, features, features], stddev))\n b1 = tf.Variable(tf.constant(0.1, shape=[features]))\n\n conv1 = tf.nn.conv3d(in_node, w1, strides=[1, 1, 1, 1, 1], padding='VALID')\n # in the paper, it didn't mention the dropout\n conv1_dropout = tf.nn.dropout(conv1, keep_prob)\n tmp_h_conv = tf.nn.relu(conv1_dropout + b1)\n\n features = features*2\n w2 = tf.Variable(tf.truncated_normal([filter_size, filter_size, \n filter_size, features//2, features], stddev))\n b2 = tf.Variable(tf.constant(0.1, shape=[features]))\n \n conv2 = tf.nn.conv3d(tmp_h_conv, w2, strides=[1, 1, 1, 1, 1], padding='VALID')\n conv2_dropout = tf.nn.dropout(conv2, keep_prob)\n dw_h_convs[layer] = tf.nn.relu(conv2_dropout + b2)\n \n weights.append((w1, w2))\n biases.append((b1, b2))\n # convs.append((conv1_dropout, conv2_dropout))\n \n if layer < layers-1:\n # print(\"some:\",layer)P\n in_node = tf.nn.max_pool3d(dw_h_convs[layer], \n ksize=[1, pool_size, pool_size, pool_size, 1], \n strides=[1, pool_size, pool_size, pool_size, 1], \n padding='VALID')\n \n in_node = dw_h_convs[layers-1]\n\n # up layers\n for layer in range(layers-2, -1, -1):\n layer.p()\n # features = 2**(layer+1)*features_root\n stddev = np.sqrt(2 / (filter_size**2 * features))\n \n wd = tf.Variable(tf.truncated_normal([pool_size, pool_size, pool_size, features, features], stddev))\n bd = tf.Variable(tf.constant(0.1, shape=[features]))\n\n\n x_shape = tf.shape(in_node)\n output_shape = tf.stack([x_shape[0], x_shape[1]*2, x_shape[2]*2, x_shape[3]*2, x_shape[4]])\n h_deconv = tf.nn.conv3d_transpose(in_node, wd, output_shape, \n strides=[1, pool_size, pool_size, pool_size, 1], padding='VALID')\n h_deconv_relu = tf.nn.relu(h_deconv + bd)\n h_deconv_concat = crop_and_concat3d(dw_h_convs[layer], h_deconv_relu)\n # deconv[layer] = h_deconv_concat\n \n features = features//2\n w1 = tf.Variable(tf.truncated_normal([filter_size, filter_size, \n filter_size, features*3, features], stddev))\n w2 = tf.Variable(tf.truncated_normal([filter_size, filter_size, \n filter_size, features, features], stddev))\n b1 = tf.Variable(tf.constant(0.1, shape=[features]))\n b2 = tf.Variable(tf.constant(0.1, shape=[features]))\n \n conv1 = tf.nn.conv3d(h_deconv_concat, w1, strides=[1, 1, 1, 1, 1], padding='VALID')\n conv1_dropout = tf.nn.dropout(conv1, keep_prob)\n h_conv = tf.nn.relu(conv1_dropout + b1)\n\n conv2 = tf.nn.conv3d(h_conv, w2, strides=[1, 1, 1, 1, 1], padding='VALID')\n conv2_dropout = tf.nn.dropout(conv2, keep_prob)\n in_node = tf.nn.relu(conv2_dropout + b2)\n up_h_convs[layer] = in_node\n \n weights.append((w1, w2))\n biases.append((b1, b2))\n\n # Output Map\n weight = tf.Variable(tf.truncated_normal([1, 1, 1, features, n_class], stddev))\n bias = tf.Variable(tf.constant(0.1, shape=[n_class]))\n conv = tf.nn.conv3d(in_node, weight, strides=[1, 1, 1, 1, 1], padding='VALID')\n conv_dropout = tf.nn.dropout(conv, tf.constant(1.0))\n output_map = tf.nn.relu(conv_dropout + bias)\n\n variables = []\n for w1,w2 in weights:\n variables.append(w1)\n variables.append(w2)\n \n for b1,b2 in biases:\n variables.append(b1)\n variables.append(b2)\n\n # import ipdb; ipdb.set_trace()\n return {\"logits\":output_map,\"weights_biases\":variables,\n \"x\":x, \"y\":y, \"keep_prob\":keep_prob}\n\nif __name__ == '__main__':\n from minitest import *\n\n with test(create_3d_unet):\n channels = 1\n n_class = 10\n create_3d_unet(channels, n_class)\n pass","sub_path":"python/deep_learning/colin_unet/3d_unet/unet_3d_back.py","file_name":"unet_3d_back.py","file_ext":"py","file_size_in_byte":6620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"85734941","text":"import appdirs\nfrom avalon import style\nfrom Qt import QtWidgets\nimport os\nimport json\nfrom .widget_login import MusterLogin\nfrom avalon.vendor import requests\n\n\nclass MusterModule:\n \"\"\"\n Module handling Muster Render credentials. This will display dialog\n asking for user credentials for Muster if not already specified.\n \"\"\"\n cred_folder_path = os.path.normpath(\n appdirs.user_data_dir('pype-app', 'pype')\n )\n cred_filename = 'muster_cred.json'\n\n def __init__(self, main_parent=None, parent=None):\n self.cred_path = os.path.join(\n self.cred_folder_path, self.cred_filename\n )\n self.main_parent = main_parent\n self.parent = parent\n self.widget_login = MusterLogin(main_parent, self)\n\n def tray_start(self):\n \"\"\"\n Show login dialog if credentials not found.\n \"\"\"\n # This should be start of module in tray\n cred = self.load_credentials()\n if not cred:\n self.show_login()\n else:\n # nothing to do\n pass\n\n def process_modules(self, modules):\n\n def api_callback():\n self.aShowLogin.trigger()\n\n if \"RestApiServer\" in modules:\n def api_show_login():\n self.aShowLogin.trigger()\n modules[\"RestApiServer\"].register_callback(\n \"/show_login\", api_show_login, \"muster\", \"post\"\n )\n\n # Definition of Tray menu\n def tray_menu(self, parent):\n \"\"\"\n Add **change credentials** option to tray menu.\n \"\"\"\n # Menu for Tray App\n self.menu = QtWidgets.QMenu('Muster', parent)\n self.menu.setProperty('submenu', 'on')\n self.menu.setStyleSheet(style.load_stylesheet())\n\n # Actions\n self.aShowLogin = QtWidgets.QAction(\n \"Change login\", self.menu\n )\n\n self.menu.addAction(self.aShowLogin)\n self.aShowLogin.triggered.connect(self.show_login)\n\n parent.addMenu(self.menu)\n\n def load_credentials(self):\n \"\"\"\n Get credentials from JSON file\n \"\"\"\n credentials = {}\n try:\n file = open(self.cred_path, 'r')\n credentials = json.load(file)\n except Exception:\n file = open(self.cred_path, 'w+')\n file.close()\n\n return credentials\n\n def get_auth_token(self, username, password):\n \"\"\"\n Authenticate user with Muster and get authToken from server.\n \"\"\"\n MUSTER_REST_URL = os.environ.get(\"MUSTER_REST_URL\")\n if not MUSTER_REST_URL:\n raise AttributeError(\"Muster REST API url not set\")\n params = {\n 'username': username,\n 'password': password\n }\n api_entry = '/api/login'\n response = self._requests_post(\n MUSTER_REST_URL + api_entry, params=params)\n if response.status_code != 200:\n self.log.error(\n 'Cannot log into Muster: {}'.format(response.status_code))\n raise Exception('Cannot login into Muster.')\n\n try:\n token = response.json()['ResponseData']['authToken']\n except ValueError as e:\n self.log.error('Invalid response from Muster server {}'.format(e))\n raise Exception('Invalid response from Muster while logging in.')\n\n self.save_credentials(token)\n\n def save_credentials(self, token):\n \"\"\"\n Save credentials to JSON file\n \"\"\"\n data = {\n 'token': token\n }\n\n file = open(self.cred_path, 'w')\n file.write(json.dumps(data))\n file.close()\n\n def show_login(self):\n \"\"\"\n Show dialog to enter credentials\n \"\"\"\n self.widget_login.show()\n\n def _requests_post(self, *args, **kwargs):\n \"\"\" Wrapper for requests, disabling SSL certificate validation if\n DONT_VERIFY_SSL environment variable is found. This is useful when\n Deadline or Muster server are running with self-signed certificates\n and their certificate is not added to trusted certificates on\n client machines.\n\n WARNING: disabling SSL certificate validation is defeating one line\n of defense SSL is providing and it is not recommended.\n \"\"\"\n if 'verify' not in kwargs:\n kwargs['verify'] = False if os.getenv(\"PYPE_DONT_VERIFY_SSL\", True) else True # noqa\n return requests.post(*args, **kwargs)\n","sub_path":"pype/modules/muster/muster.py","file_name":"muster.py","file_ext":"py","file_size_in_byte":4502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"423622082","text":"''' example for add rpc method which need multi processing '''\n\nfrom ajson_rpc2.server import JsonRPC2\n\nrpc_server = JsonRPC2()\n\n\ndef subtract(minuend, subtrahend):\n b = 0\n for i in range(100000000):\n b += i\n return b + minuend - subtrahend\n\n\nrpc_server.add_method(subtract, need_multiprocessing=True)\nrpc_server.start()\n","sub_path":"examples/multi_processing_example.py","file_name":"multi_processing_example.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"422408380","text":"from rest_framework import serializers\nfrom core.models import (\n House,\n Class,\n Grade,\n Programme,\n Room,\n Period\n)\n\n\nclass ProgrammeSerializer(serializers.ModelSerializer):\n \"\"\"Programmes levels serializer\"\"\"\n\n class Meta:\n model = Programme\n fields = ('id', 'name', 'code')\n read_only_fields = ('id', )\n\n\nclass GradeSerializer(serializers.ModelSerializer):\n \"\"\"Grade levels serializer\"\"\"\n\n class Meta:\n model = Grade\n fields = ('id', 'name', 'year')\n read_only_fields = ('id', )\n\n\nclass HouseSerializer(serializers.ModelSerializer):\n \"\"\"House serializer model\"\"\"\n\n class Meta:\n model = House\n fields = ('id', 'name')\n read_only_fields = ('id',)\n\n\nclass ClassSerializer(serializers.ModelSerializer):\n \"\"\"Student class serializer\"\"\"\n\n class Meta:\n model = Class\n fields = ('id', 'name', 'grade', 'programme')\n read_only_fields = ('id', )\n\n\nclass RoomSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Room\n fields = ('id', 'name', 'capacity', 'description')\n read_only_fields = ('id',)\n\n\nclass PeriodSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Period\n fields = ('id', 'name', 'start_time', 'end_time', 'length')\n read_only_fields = ('id', 'length')\n","sub_path":"api/core/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"74622652","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: Matteo Guerra\r\nmatricola: 924497\r\n\"\"\"\r\n\r\nimport socket as sk\r\nimport time as t\r\n\r\n#apro il file dove ho scritto le misure in modalità lettura\r\nFILE = 'misure_dev2.txt'\r\nf = open(FILE, \"r\")\r\n\r\n#imposto l'ip arbitrariamente perchè mi servirà quando andrò a stampare le misure\r\nmy_ip='192.168.1.2'\r\n#leggo i dati dal file\r\ndati = f.read()\r\n\r\n# Creo il socket UDP\r\nsock = sk.socket(sk.AF_INET, sk.SOCK_DGRAM)\r\n\r\n#associo l'indirizzo locale al server\r\nserver_address = ('localhost', 10000)\r\n\r\ntry:\r\n\r\n # invio i dati raccolti al Gateway\r\n print ('sending data \\n\"%s\"' % dati)\r\n t.sleep(1) #1 secondo prima di inviargli i dati\r\n start = t.time() #parte il timer per capire quanto ci impiega ad arrivare un pacchetto UDP\r\n sent = sock.sendto(dati.encode(),server_address)\r\n \r\n # Ricevo la risposta dal Gateway \r\n print('waiting to receive response from')\r\n data, server = sock.recvfrom(1024)\r\n end = t.time()\r\n \r\n t.sleep(1) #aspetto un secondo e stampo la risposta ricevuta dal Gateway\r\n print('received message \"%s\"' % data.decode('utf8'))\r\n #stampo il tempo impiegato dal pacchetto UDP\r\n print(\"tempo per inviare il pacchetto UDP: {} sec\".format(end-start)) #stampo il tempo che ci ha impiegato un pacchetto UDP\r\n \r\nexcept Exception as info:\r\n print(info)\r\nfinally:\r\n print ('closing socket')\r\n #chiudo il socket e il file\r\n sock.close()\r\n f.close()","sub_path":"device2.py","file_name":"device2.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"563675485","text":"# -*- 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: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\n\nclass CrawljindongPipeline(object):\n def process_item(self, item, spider):\n return item\n\nimport MySQLdb\nimport MySQLdb.cursors\nfrom urllib import request\nimport requests\nimport re\nimport redis\n\nclass Writedb():\n def __init__(self):\n # 连接数据库\n self.conn = MySQLdb.connect('localhost', 'root', '12345', 'python77', charset='utf8', use_unicode=True)\n self.mycursor = self.conn.cursor()\n\n def process_item(self, item, spider):\n sql=\"insert into jd_scrapy(pname,price,commit_t,shop) VALUES ('\"+item['pname']+\"','\"+item['price']+\"','\"+item['commit']+\"','\"+item['shop']+\"')\"\n self.mycursor.execute(sql)\n self.conn.commit()\n\n\nclass Getpname():\n def __init__(self):\n # 连接数据库\n self.conn = MySQLdb.connect('localhost', 'root', '12345', 'python77', charset='utf8', use_unicode=True)\n self.mycursor = self.conn.cursor()\n con_pool = redis.ConnectionPool(host='127.0.0.1', port=6379,password='12345')\n self.r = redis.Redis(connection_pool=con_pool)\n\n def getname(self):\n sql = \"SELECT pname FROM jd_scrapy\"\n self.mycursor.execute(sql)\n # self.conn.commit()\n random=self.mycursor.fetchall()\n for i in random:\n if '华为'in i[0]:\n self.r.hincrby('phone','huawei',1)\n elif '荣耀' in i[0]:\n self.r.hincrby('phone', 'huawei', 1)\n elif '小米' in i[0]:\n self.r.hincrby('phone','xiaomi', 1)\n elif 'iPhone'in i[0]:\n self.r.hincrby('phone','iphone',1)\n elif 'Apple'in i[0]:\n self.r.hincrby('phone','iphone',1)\n elif'vivo'in i[0]:\n self.r.hincrby('phone','vivo',1)\n elif'OPPO'in i[0]:\n self.r.hincrby('phone','oppo',1)\n elif'魅族'in i[0]:\n self.r.hincrby('phone','meizu', 1)\n else:\n self.r.hincrby('phone','qita', 1)\n # print(random)\n\n def show(self):\n return self.r.hgetall('phone')\n\nif __name__ == '__main__':\n a=Getpname()\n a.getname()\n print(a.show())\n","sub_path":"crawljindong/crawljindong/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"145022987","text":"#linked-list\n#https://leetcode.com/problems/reverse-linked-list-ii/\nclass Solution:\n def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:\n if not head:\n return None\n if (m==n):\n return head\n\n current = head\n prev = None\n loop = 1\n while(loop < m):\n prev = current\n current = current.next\n loop += 1\n \n con = prev\n tail = current\n while(loop <= n):\n temp = current.next\n current.next = prev\n prev = current\n current = temp\n loop +=1\n\n if con: con.next = prev\n else: head = prev\n tail.next = current\n return head\n \n ","sub_path":"l92.py","file_name":"l92.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"261883570","text":"\r\nfrom django.conf.urls import url\r\nfrom . import views\r\napp_name=\"portal\"\r\nurlpatterns = [\r\nurl(r'^$', views.index, name='index'),\r\nurl(r'auth', views.auth, name='auth'),\r\nurl(r'forgotpasswd', views.forgotpasswd, name='forgotpasswd'),\r\nurl(r'login', views.login, name='login'),\r\nurl(r'logout', views.logout, name='logout'),\r\nurl(r'payment/completed', views.paymentcompleted, name='paymentcompleted'),\r\nurl(r'payment/list', views.listpayments, name='listpayments'),\r\nurl(r'^payment', views.payment, name='payment'),\r\nurl(r'verifycode', views.verifycode, name='verifycode'),\r\nurl(r'verify', views.verify, name='verify'),\r\nurl(r'^lawdetail/(?P\\d+)$', views.getlaw, name='getlaw'),\r\nurl(r'^lawsection/(?P\\d+)$', views.getlawdetail, name='getlawdetail'),\r\nurl(r'^section/(?P\\d+)$', views.listsections, name='listsections'),\r\nurl(r'^section', views.getsection, name='getsection'),\r\nurl(r'profile/update', views.updateprofile, name='updateprofile'),\r\nurl(r'profile', views.profile, name='profile'),\r\nurl(r'activity', views.activity, name='profile'),\r\nurl(r'billing', views.billing, name='billing'),\r\n\r\nurl(r'^notes/list', views.listnotes, name='profile'),\r\nurl(r'^notes/add', views.addnote, name='addnote'),\r\nurl(r'^notes/delete/(?P\\d+)', views.deletenote, name='profile'),\r\nurl(r'^annotations/list', views.listannotation, name='profile'),\r\nurl(r'^annotations/add', views.addannotation, name='addannotation'),\r\nurl(r'^annotations/delete/(?P\\d+)', views.deleteannotation, name='profile'),\r\nurl(r'registeruser', views.registeruser, name='registeruser'),\r\nurl(r'search', views.search, name='search'),\r\nurl(r'signup', views.signup, name='signup'),\r\nurl(r'view', views.noteview, name='noteview'),\r\n\r\n]\r\n","sub_path":"portal/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"485376862","text":"import cv2\nimport numpy as np\nimport json\nimport os\nimport math\n\nfrom .utils import INPUT_DIR\nfrom .utils import OBJECT_MODEL_DIR, OBJECT_OUTPUT_DIR, OBJECT_LOG_DIR\n\ndef objectDetector() :\n\n model_path = OBJECT_MODEL_DIR\n input_file_path = INPUT_DIR\n output_file_path = OBJECT_OUTPUT_DIR\n log_file_path = OBJECT_LOG_DIR\n\n weight_path = os.path.join(model_path + 'weights/yolov3_05-24.weights')\n cfg_path = os.path.join(model_path + 'configs/yolov3_05-24.cfg')\n names_path = os.path.join(model_path + 'names/obj_05-24.names')\n\n net = cv2.dnn.readNet(weight_path, cfg_path)\n with open(names_path, 'r') as f:\n classes = [line.strip() for line in f.readlines()]\n\n layer_names = net.getLayerNames()\n output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]\n colors = np.random.uniform(0, 255, size=(len(classes), 3))\n\n file_list = os.listdir(input_file_path)\n\n for file_ in file_list:\n\n file_name = os.path.splitext(file_)[0]\n\n # Loading Video\n cap = cv2.VideoCapture(input_file_path + file_)\n\n\n tablet_logs = dict()\n phone_logs = dict()\n watch_logs = dict()\n\n\n FPS = cap.get(cv2.CAP_PROP_FPS)\n delay = round(1000 / FPS)\n frame_second = 0\n\n makedir_path = os.path.join(output_file_path + file_name)\n os.makedirs(makedir_path, exist_ok=True)\n output_file_dir = os.path.join(file_name + '/')\n output_file_name = os.path.join('output_' + file_name + '.avi')\n\n os.makedirs(log_file_path + file_name, exist_ok=True)\n log_file_dir = file_name + '/'\n phone_log_name = file_name + '-phone_detect_log.json'\n watch_log_name = file_name + '-watch_detect_log.json'\n tablet_log_name = file_name + '-tablet_detect_log.json'\n\n # 코덱 지정, *는 문자를 풀어쓰는 방식 *'DIVX' == 'D', 'I', 'V', 'X'\n fourcc = cv2.VideoWriter_fourcc(*'DIVX')\n width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n writer = cv2.VideoWriter(output_file_path + output_file_dir + output_file_name, fourcc, FPS, (width, height), True)\n\n while True:\n ret, frame = cap.read()\n\n frame_second += (1 / FPS)\n\n if not ret:\n break\n\n # 이 구문 없으면 output.avi 재생 가능!\n # frame = cv2.resize(frame, None, fx=0.4, fy=0.4)\n\n height, width, channels = frame.shape\n\n # Detecting objects\n blob = cv2.dnn.blobFromImage(frame, 1 / 255, (416, 416), (0, 0, 0), swapRB=True, crop=False)\n\n net.setInput(blob)\n\n outs = net.forward(output_layers)\n\n boxes = []\n confidences = []\n class_ids = []\n\n for out in outs:\n for detection in out:\n scores = detection[5:]\n class_id = np.nanargmax(scores)\n confidence = scores[class_id]\n\n if confidence > 0.5:\n # Object detected\n center_x = int(detection[0] * width)\n center_y = int(detection[1] * height)\n w = int(detection[2] * width)\n h = int(detection[3] * height)\n\n # 좌표\n x = int(center_x - w / 2)\n y = int(center_y - h / 2)\n boxes.append([x, y, w, h])\n confidences.append((float(confidence)))\n class_ids.append(class_id)\n\n indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)\n\n font = cv2.FONT_HERSHEY_PLAIN\n for i in range(len(boxes)):\n if i in indexes:\n x, y, w, h = boxes[i]\n label = str(classes[class_ids[i]])\n color = colors[0]\n cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)\n cv2.putText(frame, label, (x, y + 30), font, 3, color, 3)\n\n if label == \"smartphone\":\n phone_logs[frame_second] = (label, confidences[i])\n elif label == \"smartwatch\":\n watch_logs[frame_second] = (label, confidences[i])\n elif label == \"tablet\":\n tablet_logs[frame_second] = (label, confidences[i])\n\n cv2.imshow('frame', frame)\n writer.write(frame)\n\n if cv2.waitKey(delay) & 0xFF == ord('q'): break\n \n cur_sec = 0\n max_conf = 0\n\n sec_wise_phone = dict()\n sec_wise_watch = dict()\n sec_wise_tablet = dict()\n\n for sec, values in phone_logs.items():\n if cur_sec < math.floor(sec): \n cur_sec = math.floor(sec)\n max_conf = 0\n \n if max_conf <= values[1]:\n max_conf = values[1]\n sec_wise_phone[cur_sec] = values\n \n cur_sec = 0\n max_conf = 0\n \n for sec, values in watch_logs.items():\n if cur_sec < math.floor(sec): \n cur_sec = math.floor(sec)\n max_conf = 0\n \n if max_conf <= values[1]:\n max_conf = values[1]\n sec_wise_watch[cur_sec] = values\n \n cur_sec = 0\n max_conf = 0\n \n for sec, values in tablet_logs.items():\n if cur_sec < math.floor(sec): \n cur_sec = math.floor(sec)\n max_conf = 0\n \n if max_conf <= values[1]:\n max_conf = values[1]\n sec_wise_tablet[cur_sec] = values\n\n with open(log_file_path + log_file_dir + phone_log_name, 'w') as outfile:\n json.dump(sec_wise_phone, outfile)\n \n with open(log_file_path + log_file_dir + watch_log_name, 'w') as outfile:\n json.dump(sec_wise_watch, outfile)\n \n with open(log_file_path + log_file_dir + tablet_log_name, 'w') as outfile:\n json.dump(sec_wise_tablet, outfile)\n\n cap.release()\n writer.release()\n cv2.destroyAllWindows()\n\nif __name__ == \"__main__\":\n objectDetector()","sub_path":"models/object_detection.py","file_name":"object_detection.py","file_ext":"py","file_size_in_byte":6293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"109863990","text":"\"\"\"Helper methods for PPA mapping symbolic computations\"\"\"\n\nimport sympy as sp\nfrom sympy.polys.polytools import terms_gcd\n# from sympy import *\nimport time\nfrom IPython.display import display, Math\nimport numpy as np\n\n\ndef distribute(e, x):\n \"\"\"Helper method to apply distributive multiplication.\n This helps by allowing the use of 'subs' instead of 'limit'\n in special circumstances\n \"\"\"\n\n # traverse the operations graph\n if e.is_Add:\n return sp.Add(*[distribute(a, x) for a in e.args])\n elif e.is_Mul:\n o = sp.Integer(1)\n done = False\n for a in e.args:\n if x in a.atoms() and not done:\n # prefer multiply where x is found\n # seek for simplification\n o = sp.Mul(o, distribute(a, x))\n done = True\n else:\n o = sp.Mul(o, a)\n return o if done else sp.Mul(o, x)\n else:\n return sp.Mul(e, x)\n\n\ndef show_expr(expr, plain_latex=False):\n \"\"\"Helper function to display Math expressions\"\"\"\n if plain_latex:\n print(sp.printing.latex(expr))\n return None#sp.printing.latex(expr)\n return display(Math(sp.printing.latex(expr)))\n\n\ndef compositions(n, k):\n \"\"\"\n Returns all compositions of size 'k' for number 'n'.\n We use it to discover all possible states in a given\n reduced model with k states, and n mRNAs in it. \n Very useful for bursty mRNA arrivals.\n \"\"\"\n\n if n < 0 or k < 0:\n return\n elif k == 0:\n # the empty sum, by convention, is zero, so only return something if\n # n is zero\n if n == 0:\n yield []\n return\n elif k == 1:\n yield [n]\n return\n else:\n for i in range(0,n+1):\n for comp in compositions(n-i,k-1):\n yield [i] + comp\n\n\ndef clean_from_N(M):\n \"\"\"\n Simplifies sympy matrices or vectors by taking\n limit N->inf when possible, without losing first order\n \"\"\"\n\n N = sp.symbols('N')\n M = M.as_mutable()\n for i, elem in enumerate(M):\n if N in M[i].atoms():\n # first try taking limit directly\n tmp = (M[i]).subs(N, sp.S.Infinity)\n if tmp != 0:\n M[i] = tmp\n continue\n\n # now try multiplying by N before taking the limit\n nmi = distribute(M[i], N)\n\n tmp = (nmi).subs(nmi, sp.S.Infinity)/N\n if not (-sp.S.Infinity in tmp.atoms() or sp.S.Infinity in tmp.atoms()):\n M[i] = tmp\n return M\n\n\ndef compute_steady_state_moments(model_transition_rates, model_protein_production_rates, model_protein_degradation_rate):\n\n g = model_protein_degradation_rate\n N = sp.symbols('N')\n\n model_transition_rates_by_deltas = {}\n tran_rates = {}\n\n Nmrna_stat_red = len(model_protein_production_rates)\n\n protein_mean = {}\n protein_fano = {}\n\n for burst_size in [1, 2]:\n print(\"\\n\")\n # The size of the mRNA burst\n bs = burst_size\n print(f\"\\nWorking on Burst Size = {bs}\\n\")\n\n tran_rates[bs] = {}\n\n # These are all of the possible states of the reduced model\n states = np.array(list(compositions(burst_size, Nmrna_stat_red)))\n\n # Build a dictionary of transitions\n for i in range(len(states)):\n si = tuple(states[i])\n for j in range(len(states)):\n delta = states[j] - states[i]\n sj = tuple(states[j])\n sd = tuple(delta)\n\n # the index for the source state for this transition\n src_idx = np.argmin(delta)\n\n try:\n if bs == 1:\n rate = model_transition_rates[(si, sj)]\n model_transition_rates_by_deltas[sd] = rate\n else:\n if delta[0] == - burst_size:\n sd = tuple((delta/burst_size).astype(int))\n rate = model_transition_rates_by_deltas[sd]\n else:\n # total rate is proportional to the number of mRNAs in source state\n rate = model_transition_rates_by_deltas[sd] * states[i, src_idx]\n except KeyError:\n continue\n\n msg = f\"{states[i]} --> {states[j]}\\tdelta = {delta}\\t{rate}\"\n if max(abs(delta)) == 1 and delta[0] >= 0:\n print(msg)\n elif delta[0] == - burst_size:\n print(msg + \"\\t(arrival)\")\n else:\n continue\n\n tran_rates[bs][(si, sj)] = rate\n\n # will contain the actual protein production rates for all posible\n # states of the system\n prod_rates = {}\n\n # the set of posible states of the system\n states = set([node for edge in tran_rates[bs].keys() for node in edge])\n\n # protein production rates at each state\n for state in states:\n # initialize\n prod_rates[state] = 0\n for i, n in enumerate(state):\n # add up all protein production rate contributions\n # n is the number of mRNAs in i-th mRNA state\n prod_rates[state] += n * model_protein_production_rates[i]\n\n # Node count, sorted list of nodes\n n_cnt = len(states)\n n_lst = reversed(sorted(list(states)))\n n_idx = range(n_cnt)\n\n # dict map from node name to node index in sorted list\n n_dct = dict(zip(n_lst, n_idx))\n\n # Build the \"transition\" matrix\n K = sp.zeros(n_cnt, n_cnt)\n for t, rt in tran_rates[bs].items():\n K[n_dct[t[1]], n_dct[t[0]]] += rt\n K[n_dct[t[0]], n_dct[t[0]]] -= rt\n\n print(f\"\\n\\n\\nThe transition Matrix K\\n\")\n show_expr(K)\n\n R = sp.zeros(n_cnt, n_cnt)\n for s, rt in prod_rates.items():\n R[n_dct[s], n_dct[s]] += rt\n\n X = K.copy()\n X.row_del(0)\n X = X.row_insert(0, sp.ones(1, K.shape[0]))\n G = sp.eye(K.shape[0])*g\n kr = R*sp.ones(K.shape[0], 1)\n b = sp.zeros(K.shape[0], 1)\n b[0] = 1\n\n print(f\"\\n\\n\\nThe protein production rates\\n\")\n show_expr(kr.T)\n\n L, U, P = X.LUdecomposition()\n L = clean_from_N(L)\n U = clean_from_N(U)\n b = L.inv()*b\n m0 = U.LUsolve(b)\n m0 = clean_from_N(m0)\n\n L, U, P = (K-G).LUdecomposition()\n L = clean_from_N(L)\n U = clean_from_N(U)\n b = L.inv()*R*m0\n b = clean_from_N(b)\n m1 = -U.LUsolve(b)\n m1 = clean_from_N(m1)\n\n\n # 1st moment at reduced model\n mean_rm = ((kr.T * m0/g)[0])\n\n # 1st moment: E[p], the mean\n # for protein number at original model\n\n mean = sp.factor((distribute(mean_rm, N)).subs(N, sp.S.Infinity))\n\n print(f\"\\n\\n\\nThe protein mean\\n\")\n show_expr(mean)\n\n # 2nd moment at reduced model\n secm_rm = ((kr.T * m1/g)[0])\n # secm_rm = sp.factor((kr.T * m1/g)[0])\n # show_expr(secm_rm)\n\n # 2nd moment: E[p*(p-1)]\n # for protein number at original model\n secm = ((distribute(secm_rm, N)).subs(N, sp.S.Infinity)) + mean**2\n # show_expr(secm)\n\n # compute the variance\n # for protein number at original model\n variance = (sp.factor(secm/mean - mean) + 1) * mean\n # show_expr(variance)\n\n # Standard deviation\n stdv = sp.sqrt(variance)\n # show_expr(stdv)\n\n # compute the fano factor\n # for protein number at original model\n fano = sp.factor(variance/mean -1) +1 # tweak factorization\n\n print(f\"\\n\\n\\nThe protein fano factor\\n\")\n show_expr(fano)\n\n protein_mean[bs] = mean\n protein_fano[bs] = fano\n\n FF2, FF1, FF, Gb2, Gb1, ue, up, kp = sp.symbols(\"FF_2 FF_1 FF G''_b G'_b mu_e mu_p k_p\")\n\n print(f\"\\n\\n\\nThe protein fano factor for burst size 1\\n\")\n show_expr(sp.Eq(FF1, protein_fano[1]))\n\n print(f\"\\n\\n\\nThe protein fano factor for burst size 2\\n\")\n show_expr(sp.Eq(FF2, sp.factor(protein_fano[2] - protein_fano[1]) + protein_fano[1]))\n\n print(f\"\\n\\n\\nThe protein fano factor for bursty mRNA arrivals\")\n print(f\"with Gb the generating function for the burst distribution\\n\")\n show_expr(sp.Eq(FF, (1 + (protein_fano[1]-1)*(1 + sp.factor(protein_fano[2]-protein_fano[1])/(protein_fano[1]-1)*(Gb2/Gb1)))))\n\n return protein_mean, protein_fano\n\n\ndef compute_matrices(model_transition_rates, model_protein_production_rates, model_protein_degradation_rate, max_burst_size=1):\n\n g = model_protein_degradation_rate\n N = sp.symbols('N')\n\n model_transition_rates_by_deltas = {}\n tran_rates = {}\n\n Nmrna_stat_red = len(model_protein_production_rates)\n\n for burst_size in range(1, max_burst_size + 1):\n\n # The size of the mRNA burst\n bs = burst_size\n print(f\"\\nWorking on Burst Size = {bs}\\n\")\n\n tran_rates[bs] = {}\n\n # These are all of the possible states of the reduced model\n states = np.array(list(compositions(burst_size, Nmrna_stat_red)))\n\n # Build a dictionary of transitions\n for i in range(len(states)):\n si = tuple(states[i])\n for j in range(len(states)):\n delta = states[j] - states[i]\n sj = tuple(states[j])\n sd = tuple(delta)\n\n # the index for the source state for this transition\n src_idx = np.argmin(delta)\n # the index for the target state for this transition\n trg_idx = np.argmax(delta)\n\n try:\n if bs == 1:\n rate = model_transition_rates[(si, sj)]\n model_transition_rates_by_deltas[sd] = rate\n else:\n if delta[0] == - burst_size:\n sd = tuple((delta/burst_size).astype(int))\n rate = model_transition_rates_by_deltas[sd]\n else:\n # total rate is proportional to the number of mRNAs in source state\n rate = model_transition_rates_by_deltas[sd] * states[i, src_idx]\n except KeyError:\n continue\n\n msg = f\"{states[i]} --> {states[j]}\\tdelta = {delta}\\t{rate}\"\n if max(abs(delta)) == 1 and delta[0] >= 0:\n print(msg)\n elif delta[0] == - burst_size:\n arrival_state = sj\n print(msg + \"\\t(arrival)\")\n else:\n continue\n\n tran_rates[bs][(si, sj)] = rate\n\n # will contain the actual protein production rates for all posible\n # states of the system\n prod_rates = {}\n\n # the set of posible states of the system\n states = set([node for edge in tran_rates[bs].keys() for node in edge])\n\n # protein production rates at each state\n for state in states:\n # initialize\n prod_rates[state] = 0\n for i, n in enumerate(state):\n # add up all protein production rate contributions\n # n is the number of mRNAs in i-th mRNA state\n prod_rates[state] += n * model_protein_production_rates[i]\n\n # Node count, sorted list of nodes\n n_cnt = len(states)\n n_lst = reversed(sorted(list(states)))\n n_idx = range(n_cnt)\n\n # dict map from node name to node index in sorted list\n n_dct = dict(zip(n_lst, n_idx))\n\n # Build the \"transition\" matrix\n K = sp.zeros(n_cnt, n_cnt)\n for t, rt in tran_rates[bs].items():\n K[n_dct[t[1]], n_dct[t[0]]] += rt\n K[n_dct[t[0]], n_dct[t[0]]] -= rt\n\n print(f\"\\n\\n\\nThe transition Matrix K\\n\")\n show_expr(K)\n\n R = sp.zeros(n_cnt, n_cnt)\n for s, rt in prod_rates.items():\n R[n_dct[s], n_dct[s]] += rt\n\n G = sp.eye(K.shape[0])*g\n kr = R*sp.ones(K.shape[0], 1)\n\n return K, G, R, kr, n_dct[arrival_state]-1\n","sub_path":"examples/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":12099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"532478841","text":"import pprint\n\nfrom app.models.item_stack import ItemStack # noqa: F401,E501\nfrom app.models.location import Location # noqa: F401,E501\n\n\nclass ItemPickup(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'item_stack': 'ItemStack',\n 'location': 'Location'\n }\n\n attribute_map = {\n 'item_stack': 'itemStack',\n 'location': 'location'\n }\n\n def __init__(self, item_stack=None, location=None): # noqa: E501\n \"\"\"ItemPickup - a model defined in Swagger\"\"\" # noqa: E501\n\n self._item_stack = None\n self._location = None\n self.discriminator = None\n\n if item_stack is not None:\n self.item_stack = item_stack\n if location is not None:\n self.location = location\n\n @property\n def item_stack(self):\n \"\"\"Gets the item_stack of this ItemPickup. # noqa: E501\n\n\n :return: The item_stack of this ItemPickup. # noqa: E501\n :rtype: ItemStack\n \"\"\"\n return self._item_stack\n\n @item_stack.setter\n def item_stack(self, item_stack):\n \"\"\"Sets the item_stack of this ItemPickup.\n\n\n :param item_stack: The item_stack of this ItemPickup. # noqa: E501\n :type: ItemStack\n \"\"\"\n\n self._item_stack = item_stack\n\n @property\n def location(self):\n \"\"\"Gets the location of this ItemPickup. # noqa: E501\n\n\n :return: The location of this ItemPickup. # noqa: E501\n :rtype: Location\n \"\"\"\n return self._location\n\n @location.setter\n def location(self, location):\n \"\"\"Sets the location of this ItemPickup.\n\n\n :param location: The location of this ItemPickup. # noqa: E501\n :type: Location\n \"\"\"\n\n self._location = location\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in self.swagger_types.items():\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n if issubclass(ItemPickup, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, ItemPickup):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"services/app/app/models/item_pickup.py","file_name":"item_pickup.py","file_ext":"py","file_size_in_byte":3616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"45087235","text":"# -*- coding: utf-8 -*-\nimport unittest2 as unittest\nimport pdb\n\nfrom Products.CMFCore.utils import getToolByName\n\nfrom uwosh.snippets.testing import BaseTest\n\nfrom uwosh.snippets.testing import \\\n\tUWOSH_SNIPPETS_INTEGRATION_TESTING\n\nfrom plone.app.testing import setRoles, login, TEST_USER_NAME\n\nfrom uwosh.snippets.parser import SnippetParser\n\n\nclass TestSnippetParser(BaseTest):\n\n\tlayer = UWOSH_SNIPPETS_INTEGRATION_TESTING\n\n\t#This is just a test to assure that the parser doesn't murder a helpless, unadourned string, just minding it's own business.\n\tdef test_normal(self):\n\t\tsp = SnippetParser()\n\t\ttext = sp.parsePage(self.normalString)\n\n\t\tcorrect = \"This is a test! Or is it?\"\n\n\t\tself.assertTrue( text != '' )\n\t\tself.assertEqual(text, correct)\n\n\t#This is a normal test to see if the parser works under normal circumstanes\n\tdef test_single(self):\n\t\tsp = SnippetParser()\n\t\ttext = sp.parsePage(self.testSingle)\n\n\t\tcorrect = \"This is a meaningless test! Or is it?\"\n\n\t\tself.assertTrue( text != '' )\n\t\tself.assertEqual(text, correct)\n\n\t#In this test, we're checking that the parser won't leave a snippet with a bad ID in the output.\n\tdef test_bad_ids(self):\n\t\tsp = SnippetParser()\n\t\ttext = sp.parsePage(self.testJunk)\n\n\t\tcorrect = \"This is a test! Or is it ?\"\n\n\t\tself.assertTrue( text != '' )\n\t\tself.assertEqual(text, correct)\n\n\t#In this test, we check if the parser will catch the rare event where the JS fails to properly handle snippets on save.\n\t#Essentially, we're catching what is displayed to the user on the Edit page. The snippet plugs should never be in this form \n\t#anywhere but the edit page.\n\tdef test_dead_ids(self):\n\t\tsp = SnippetParser()\n\t\ttext = sp.parsePage(self.testDeadSnippet)\n\n\t\tcorrect = \"This is a test! Or is it?\"\n\n\t\tself.assertTrue( text != '' )\n\t\tself.assertEqual(text, correct)\n\n\t#This test assures that the parser will catch multiple instances of the same snippet\n\tdef test_multiple_ids(self):\n\t\tsp = SnippetParser()\n\t\ttext = sp.parsePage(self.testMultiple)\n\n\t\tcorrect = \"This is a meaningless test! Or is it meaningless?\"\n\n\t\tself.assertTrue( text != '' )\n\t\tself.assertEqual(text, correct)\n\n\t#This test assures that the parser doesn't grab a string with just an ordinary span in it\n\tdef test_benign_span(self):\n\t\tsp = SnippetParser()\n\t\ttext = sp.parsePage(self.benignSpan)\n\n\t\tcorrect = \"This is a meaningless test! Or is it?\"\n\n\t\tself.assertTrue( text != '' )\n\t\tself.assertEqual(text, correct)\n\n\t#This test assures that the parser will properly replace the snippet span with a normal span.\n\t#\n\t#....there's doesn't rely on the regex at all, so I don't see why it would possibly fail, but...eh\n\tdef test_inner_span(self):\n\t\tsp = SnippetParser()\n\t\ttext = sp.parsePage(self.innerSpan)\n\n\t\tcorrect = \"This is a stupid test! Or is it?\"\n\n\t\tself.assertTrue( text != '' )\n\t\tself.assertEqual(text, correct)\n\n\t#This test assures that the parser will properly handle multiple, DIFFERENT snippets in the same string\n\tdef test_multiple_different(self):\n\t\tsp = SnippetParser()\n\t\ttext = sp.parsePage(self.differentPlugs)\n\n\t\tcorrect = \"This is a stupid test! Or is it meaningless?\"\n\n\t\tself.assertTrue( text != '' )\n\t\tself.assertEqual(text, correct)\n","sub_path":"src/uwosh/snippets/tests/test_parser.py","file_name":"test_parser.py","file_ext":"py","file_size_in_byte":3303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"622889070","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/octoprint_grbl_plugin/plugin.py\n# Compiled at: 2018-04-19 09:46:10\nimport re, logging\nlog = logging.getLogger(__name__)\n\ndef unsupported_commands(comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs):\n \"\"\"\n Suppress certain commands, because Grbl cant handle them.\n \"\"\"\n if cmd.startswith('M110 '):\n return (None, )\n else:\n if cmd == 'M105':\n return '?$G'\n if cmd == 'M400':\n return 'G4 P0'\n if cmd == 'M114':\n return '?'\n return\n\n\ndef translate_ok(comm_instance, line, *args, **kwargs):\n \"\"\"\n This plugin moves Grbl's ok from the end to the start.\n OctoPrint needs the 'ok' to be at the start of the line.\n \"\"\"\n if 'MPos' in line:\n match = re.search('MPos:(-?[\\\\d\\\\.]+),(-?[\\\\d\\\\.]+),(-?[\\\\d\\\\.]+)', line)\n if match is None:\n log.warning('Bad data %s', line.rstrip())\n return line\n return ('ok X:{0} Y:{1} Z:{2} E:0 {original}').format(original=line, *match.groups())\n else:\n if line.startswith('Grbl'):\n return 'ok ' + line\n else:\n if not line.rstrip().endswith('ok'):\n return line\n if line.startswith('{'):\n return 'ok'\n if '{' in line:\n before, _, _ = line.partition('{')\n return 'ok ' + before\n return 'ok'\n\n return","sub_path":"pycfiles/octoprint_grbl_plugin-1.0.2-py2.7/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"563287007","text":"'''A 2d world that supports agents with steering behaviour\n\nCreated for COS30002 AI for Games by Clinton Woodward cwoodward@swin.edu.au\n\n'''\n\nfrom vector2d import Vector2D\nfrom matrix33 import Matrix33\nfrom graphics import egi\nfrom projectile import Projectile\n\nclass World(object):\n def __init__(self, cx, cy):\n self.cx = cx\n self.cy = cy\n self.target = Vector2D(cx / 2, cy / 2)\n self.shooter = None\n self.target = None\n self.paused = True\n self.show_info = True\n\n self.projectiles = []\n self.last_shot = 'none'\n\n def update(self, delta):\n if not self.paused:\n self.shooter.update(delta)\n self.target.update(delta)\n\n for projectile in self.projectiles:\n projectile.update(delta)\n\n for projectile in self.projectiles:\n if self.target.radius + projectile.radius > self.target.pos.distance(projectile.pos):\n self.projectiles.remove(projectile)\n self.target.hits += 1\n\n\n def render(self):\n self.shooter.render()\n self.target.render()\n\n if self.projectiles:\n for projectile in self.projectiles:\n projectile.render()\n\n egi.text_color(name='ORANGE')\n egi.text_at_pos(0, 36, '1. Rifle (R)')\n egi.text_color(name='PURPLE')\n egi.text_at_pos(0, 24, '2. Rocket (B)')\n egi.text_color(name='AQUA')\n egi.text_at_pos(0, 12, '3. Handgun (H)')\n egi.text_color(name='GREEN')\n egi.text_at_pos(0, 0, '4. Grenade (G)')\n\n def wrap_around(self, pos):\n ''' Treat world as a toroidal space. Updates parameter object pos '''\n max_x, max_y = self.cx, self.cy\n if pos.x > max_x:\n pos.x = pos.x - max_x\n elif pos.x < 0:\n pos.x = max_x - pos.x\n if pos.y > max_y:\n pos.y = pos.y - max_y\n elif pos.y < 0:\n pos.y = max_y - pos.y\n\n def transform_points(self, points, pos, forward, side, scale):\n ''' Transform the given list of points, using the provided position,\n direction and scale, to object world space. '''\n # make a copy of original points (so we don't trash them)\n wld_pts = [pt.copy() for pt in points]\n # create a transformation matrix to perform the operations\n mat = Matrix33()\n # scale,\n mat.scale_update(scale.x, scale.y)\n # rotate\n mat.rotate_by_vectors_update(forward, side)\n # and translate\n mat.translate_update(pos.x, pos.y)\n # now transform all the points (vertices)\n mat.transform_vector2d_list(wld_pts)\n # done\n return wld_pts\n\n def transform_point(self, point, pos, forward, side):\n ''' Transform the given single point, using the provided position,\n and direction (forward and side unit vectors), to object world space. '''\n # make a copy of the original point (so we don't trash it)\n wld_pt = point.copy()\n # create a transformation matrix to perform the operations\n mat = Matrix33()\n # rotate\n mat.rotate_by_vectors_update(forward, side)\n # and translate\n mat.translate_update(pos.x, pos.y)\n # now transform the point (in place)\n mat.transform_vector2d(wld_pt)\n # done\n return wld_pt\n","sub_path":"spike09/world.py","file_name":"world.py","file_ext":"py","file_size_in_byte":3372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"213047036","text":"import datetime\r\nimport threading \r\n\r\n##----------------------OverridingTheThreadClass-------------------------\r\nclass mythread (threading.Thread):\r\n startValue = 0\r\n endValue = 0\r\n def __init__(self, val1, val2, name):\r\n threading.Thread.__init__(self)\r\n self.name = name\r\n self.startValue = val1\r\n self.endValue = val2\r\n def run(self):\r\n print (\"Starting \" + self.name)\r\n calcprime(self.startValue, self.endValue)\r\n print (\"Exiting \" + self.name)\r\n\r\n##--------------------MainCalculationFunction--------------------------\r\ndef calcprime(y,x):\r\n for n in range(y,x+1):\r\n count = 0\r\n if n==2:\r\n print(n)\r\n elif n%2==0:\r\n continue\r\n else:\r\n for j in range (1,n+1):\r\n if n%j==0:\r\n count+=1\r\n if count==2:\r\n print(n)\r\n \r\n##--------------------CreateindAndRunningThreads-----------------------------------\r\n##stime= datetime.datetime.now()\r\nx= int(input())\r\na=int(x/3)\r\nb=int((2*x)/3)\r\n\r\nthread1= mythread(1,a,\"firstthread\")\r\nthread2= mythread((a+1),b,\"secondthread\")\r\nthread3= mythread((b+1),(x+1),\"thirdthread\")\r\n\r\nthread1.start()\r\nthread2.start()\r\nthread3.start()\r\n\r\n##etime= datetime.datetime.now()\r\n##elapsedtime= etime-stime\r\n##print(elapsedtime)\r\n\r\n\r\n##**--------------NonThreadingVersion--------------**\r\n##stime= datetime.datetime.now()\r\n##for n in range(1,x+1):\r\n## count = 0\r\n## if n==2:\r\n## print(n)\r\n## elif n%2==0:\r\n## continue\r\n## else:\r\n## for j in range (1,n+1):\r\n## if n%j==0:\r\n## count+=1\r\n## if count==2:\r\n## print(n)\r\n##etime= datetime.datetime.now()\r\n##elapsedtime= etime-stime\r\n##print(elapsedtime)\r\n","sub_path":"Ass2_Threads/Ass2_PrimeNumbers.py","file_name":"Ass2_PrimeNumbers.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"50929657","text":"import json\nimport pandas as pd\nimport numpy as np\n\nfrom sys import argv\nfrom numpy import genfromtxt\nfrom keras import models\nfrom keras import layers\nfrom keras import optimizers\n\nclass MultiLayerPerceptron:\n def __init__(self, config_file):\n with open(config_file) as f:\n self.config = json.load(f)\n\n self.optimizer = self.config[\"optimizer\"]\n self.epochs = self.config[\"epochs\"]\n self.barch_size = self.config[\"batch_size\"]\n self.input_size = self.config[\"input_size\"]\n\n self.mlp = models.Sequential()\n\n for i, l_config in enumerate(self.config[\"layers\"]):\n if i == 0:\n self.mlp.add(\n layers.Dense(\n self.config[\"layers\"][i][\"size\"],\n activation=self.config[\"layers\"][i][\"activation\"],\n #input_shape=(self.input_size,)\n input_dim=self.input_size\n )\n )\n else:\n self.mlp.add(\n layers.Dense(\n self.config[\"layers\"][i][\"size\"],\n activation=self.config[\"layers\"][i][\"activation\"]\n )\n )\n \n def compile(self, metrics=['accuracy']):\n if self.config[\"optimizer\"][\"name\"] == \"sgd\":\n self.mlp.compile(\n optimizer=optimizers.SGD(\n lr=self.config[\"optimizer\"][\"learning_rate\"], \n momentum=self.config[\"optimizer\"][\"momentum\"]\n ),\n loss=self.config[\"loss\"],\n metrics=metrics\n )\n elif self.config[\"optimizer\"][\"name\"] == \"adam\":\n self.mlp.compile(\n optimizer=optimizers.Adam(\n lr=self.config[\"optimizer\"][\"learning_rate\"]\n ),\n loss=self.config[\"loss\"],\n metrics=metrics\n )\n else:\n self.mlp.compile(\n optimizer=optimizers.Adam(\n lr=self.config[\"optimizer\"][\"learning_rate\"]\n ),\n loss=self.config[\"loss\"],\n metrics=metrics\n )\n\n def train(self, data, labels):\n self.mlp.fit(\n data, \n labels, \n epochs=self.config[\"epochs\"], \n batch_size=self.config[\"batch_size\"]\n )\n\n def summary(self):\n self.mlp.summary()\n \n def model(self):\n return self.mlp\n\n def predict(self, data):\n return self.mlp.predict(data)\n\n def save(self, model_file):\n self.mlp.save(model_file)\n\n def load(self, model_file):\n self.mlp.load_model(model_file)\n","sub_path":"classes/mlp.py","file_name":"mlp.py","file_ext":"py","file_size_in_byte":2751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"257707682","text":"from tkinter import *\nimport tkinter.messagebox as tm\nimport tkinter.ttk as ttk\nimport hex\n\ndef blankFunc():\n print(\"Test print\")\n\nif __name__ == \"__main__\":\n root = Tk()\n root.configure(bg=hex.darkGrey)\n\n canvas = Canvas(root, width=200, heigh=100)\n canvas.pack()\n\n # first two perameters are your xy coordinates\n # second two perameters is you ending point\n # really, it's just the starting point and the ending point\n darkGreyLine = canvas.create_line(0, 0, 200, 50)\n readLine = canvas.create_line(0, 100, 20, 50, fill=hex.darkGrey)\n #above code: eveything in tkinter has a fill\n lightGreyBox = canvas.create_rectangle(25, 25, 130, 60, fill=hex.lightGrey)\n\n # Delete an object from the canvas. Currently has no functionality\n canvas.delete(darkGreyLine)\n\n # root.minsize(650, 400)\n root.mainloop()\n","sub_path":"gui9.py","file_name":"gui9.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"412318581","text":"\nlucky_numbers = [4, 8, 15 , 16, 24, 42]\nfriends = [\"Kevin\", \"Karen\", \"Jim\", \"Oscar\", \"Toby\"]\nfriends.append(\"Creed\")\nprint(friends)\n\n\n\n\n#.insert() þá getum við fært í listanum t.d inster(1,jim)\n#.append þá bætist við fyrir aftan listann\n#.extend þá bætist við listanneins og friends.extend(lucky_numbers) nöfn og tölur\n#.remove - hverfur boom!\n#.clear() - hverfur listinn BOOM!\n#.pop() - tekur síðasta af listanum\n#.index - tjékka hvort og hvar einhver sé á listanum\n#.count - telur hversu mikið er af hverju setur í swigann\n#.sort - setur í stafrófsröð","sub_path":"Learn Python/1Python/Lists.py","file_name":"Lists.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"204172622","text":"\n# exec(open(\"/home/yli11/HemTools/bin/motif_pair_direction.py\").read())\nimport pandas as pd\nimport os\n\nmotif_bed = \"/home/yli11/Data/Human/hg19/motif_mapping/JASPA_MA0139.1_CTCF.hg19.fimo.bed\"\n\noutput = \"20copy_hg19.CTCF_pairs.tsv\"\n\nanchor_motif_direction = \"/home/yli11/dirs/20copy_project/captureC/new_data/captureC_analysis/CTCF_direction/anchor.bed\"\nanchor = pd.read_csv(anchor_motif_direction,sep=\"\\t\",header=None)\nanchor.index = anchor[0]+\"_\"+anchor[1].astype(str)+\"_\"+anchor[2].astype(str)\nflip = True\nprint (anchor)\nif flip:\n\tanchor[4] = anchor[4].map({\"-\":\"+\",\"+\":\"-\",\"o\":\"o\"})\nprint (anchor)\npeak_file = \"/research/rgs01/project_space/chenggrp/blood_regulome/chenggrp/Projects/hgcOPT_insulator/Data/ChIP/chenggrp_201110/chip_seq_pair_qqi_2020-10-01_hg19/peak_files/2036257_Jurkat_20copy_ChIP_CTCF_300_700bp_2_S7.vs.2036259_Jurkat_20copy_input_300_700bp_S9.rmdup.uq.rmchrM_summits.bed\"\n\n# chr1\t235493349\t235493353\tGGPS1\t-\n# chr2\t61687564\t61687568\tUSP34\t+\n# chr3\t15118929\t15118933\tRBSN\t-\n# chr4\t32635317\t32635318\tPCDH7\to\n# chr4\t133875585\t133875589\tPCDH10\t+\n# type o is specific for 20copy data\n\ninteraction_ibed = \"/home/yli11/dirs/20copy_project/captureC/new_data/captureC_analysis/20copy_hg19.called_interactions.tsv\"\ndf = pd.read_csv(interaction_ibed,sep=\"\\t\")\n\n\n\n# for the 20copy project, CTCF is on the reverse strand to the inserted gene\n\n\n# 1. other end bed\ntmp = df[['chr_OE','start_OE','end_OE','OE_name']].sort_values(['chr_OE','start_OE'])\ntmp = tmp.drop_duplicates(\"OE_name\")\ntmp.to_csv(\"other_end.bed\",sep=\"\\t\",header=False,index=False)\n\n# overlap peak\n# assign best motif\n# best motif is determined as the one closest to peak center\n\nos.system(\"module load bedtools/2.29.2;bedtools closest -a %s -b %s -t first > peak_motif_assignment.bed\"%(peak_file,motif_bed))\n# chr1 10124 10125 2036257_Jurkat_20copy_ChIP_CTCF_300_700bp_2_S7.vs.2036259_Jurkat_20copy_input_300_700bp_S9.rmdup.uq.rmchrM_peak_1 24.82383 chr1 10470 10489 JASPA_MA0139.1_CTCF_chr1_10471 9.90164 -\n\n# get nearest peak\nos.system(\"module load bedtools/2.29.2;bedtools closest -a other_end.bed -b peak_motif_assignment.bed -t first -d > other_end_peak_motif_assignment.bed\")\n\nannot = pd.read_csv(\"other_end_peak_motif_assignment.bed\",sep=\"\\t\",header=None)\nannot.index = annot[3].tolist()\n\n# annotate interaction with peak and motif\ndf['OE_nearest_peak_distance'] = df['OE_name'].map(annot[annot.columns[-1]].to_dict())\ndf['OE_nearest_peak_name'] = df['OE_name'].map(annot[7].to_dict())\ndf['OE_motif_direction_in_peak'] = df['OE_name'].map(annot[annot.columns[-2]].to_dict())\n\n\n# get Bait_motif_direction\ndf['Bait_motif_direction'] = df['Bait_name'].map(anchor[4].to_dict())\n\n# define motif pair\n\ndef row_apply(r):\n\t# OE position\n\tOE_bait_distance = r['start_OE'] - r['start_Bait']\n\tif OE_bait_distance>0:\n\t\t# downstream\n\t\tif r['Bait_motif_direction'] == \"o\":\n\t\t\tif r['OE_motif_direction_in_peak'] == \"-\":\n\t\t\t\treturn \"convergent or tandem\"\n\t\t\telse:\n\t\t\t\treturn \"tandem or divergent\"\n\t\tif r['Bait_motif_direction'] == \"-\":\n\t\t\tif r['OE_motif_direction_in_peak'] == \"-\":\n\t\t\t\treturn \"tandem\"\n\t\t\telse:\n\t\t\t\treturn \"divergent\"\n\t\tif r['Bait_motif_direction'] == \"+\":\n\t\t\tif r['OE_motif_direction_in_peak'] == \"-\":\n\t\t\t\treturn \"convergent\"\n\t\t\telse:\n\t\t\t\treturn \"tandem\"\n\t\t\n\t\n\telif OE_bait_distance<0:\n\t\t# upstream\n\t\tif r['Bait_motif_direction'] == \"o\":\n\t\t\tif r['OE_motif_direction_in_peak'] == \"+\":\n\t\t\t\treturn \"convergent or tandem\"\n\t\t\telse:\n\t\t\t\treturn \"tandem or divergent\"\n\t\tif r['Bait_motif_direction'] == \"-\":\n\t\t\tif r['OE_motif_direction_in_peak'] == \"-\":\n\t\t\t\treturn \"tandem\"\n\t\t\telse:\n\t\t\t\treturn \"convergent\"\n\t\tif r['Bait_motif_direction'] == \"+\":\n\t\t\tif r['OE_motif_direction_in_peak'] == \"-\":\n\t\t\t\treturn \"divergent\"\n\t\t\telse:\n\t\t\t\treturn \"tandem\"\n\t\t\n\telse:\n\t\tprint (\"soimething is wrong\")\n\t\treturn \"Wrong\"\n\ndf['CTCF_pair'] = df.apply(row_apply,axis=1)\ndf.to_csv(output,sep=\"\\t\",index=False)\n\n\n","sub_path":"bin/motif_pair_direction.py","file_name":"motif_pair_direction.py","file_ext":"py","file_size_in_byte":3895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"404814267","text":"import os\nfrom django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '0xd@ioxu5e4e=z+%ovyz$qyu&d0qy0ai5)-k%@)r7%qztgybbe'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nTEMPLATE_DEBUG = DEBUG\n\nSITE_URL = \"*\"\n\nADMINS = (\n ('JP', 'jphalisnj@gmail.com'),\n)\n\n# ========================== EMAIL SETTINGS =======================\nDEFAULT_FROM_EMAIL = \"G Fitness \"\n\nEMAIL_HOST = 'smtp.mail.yahoo.com'\nEMAIL_HOST_USER = 'bryongarcia73@yahoo.com'\nEMAIL_HOST_PASSWORD = 'Katiehotass69'\nEMAIL_PORT = 587\nEMAIL_USE_TLS = True\n\n# ========================== APPLICATIONS ==========================\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.sites',\n 'allauth',\n 'allauth.account',\n # 'carts',\n 'contact',\n 'crispy_forms',\n 'localflavor',\n 'marketing',\n # 'orders',\n # 'products',\n 'profiles',\n 'schedule',\n)\n\nSITE_ID = 1\n\nCRISPY_TEMPLATE_PACK = 'bootstrap3'\n\n# ========================== USER AUTHENTICATION SETTINGS ==========================\n\nLOGIN_URL = '/accounts/login/'\nLOGIN_REDIRECT_URL = '/'\n\nACCOUNT_AUTHENTICATION_METHOD = \"username_email\" # (=\"username\" | \"email\" | \"username_email\")\nACCOUNT_CONFIRM_EMAIL_ON_GET = True\nACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = LOGIN_URL\nACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = LOGIN_REDIRECT_URL\nACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 3\nACCOUNT_EMAIL_REQUIRED = True\nACCOUNT_EMAIL_VERIFICATION = None # choices are: \"mandatory\", \"optional\", or None\nACCOUNT_EMAIL_SUBJECT_PREFIX = \"Subject: \"\nACCOUNT_DEFAULT_HTTP_PROTOCOL = \"http\" # if secure use https\nACCOUNT_LOGOUT_ON_GET = True # log user out right away.\nACCOUNT_LOGOUT_REDIRECT_URL = LOGIN_URL\nACCOUNT_SIGNUP_FORM_CLASS = None # add a custom sign up form\nACCOUNT_SIGNUP_PASSWORD_VERIFICATION = True # use False if you don't want double password fields\nACCOUNT_UNIQUE_EMAIL = True # enforces emails are unique to all accounts\nACCOUNT_USER_MODEL_USERNAME_FIELD = \"username\" # If you're using a Custom Model, maybe it's \"email\"\nACCOUNT_USER_MODEL_EMAIL_FIELD = \"email\"\n# ACCOUNT_USER_DISPLAY (=a callable returning user.username)\nACCOUNT_USERNAME_MIN_LENGTH = 3\nACCOUNT_USERNAME_BLACKLIST = ['some_username_youdon\\'t_want']\nACCOUNT_USERNAME_REQUIRED = True\nACCOUNT_PASSWORD_INPUT_RENDER_VALUE = False # don't show the password\nACCOUNT_PASSWORD_MIN_LENGTH = 4 # min length of password\nACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True # login the user after confirming email, if required.\n\n# ========================== STRIPE SETTINGS ==========================\n\n# Test Keys\nSTRIPE_SECRET_KEY = 'sk_test_pDgXLZstTUGg8jRBCQQuZYCZ'\nSTRIPE_PUBLISHABLE_KEY = 'pk_test_dFaYmsKlzHHtUdQjgDVLoCJ9'\n\n# Live Keys\n# STRIPE_SECRET_KEY = 'sk_live_N1xdi3O50CczQoFlg2tmiuLB'\n# STRIPE_PUBLISHABLE_KEY = 'pk_live_pblLnXiDokzeWT96XOesf2AS'\n\nDEFAULT_TAX_RATE = 0.08 # 8%\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.middleware.doc.XViewMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'marketing.middleware.DisplayMarketing',\n)\n\nROOT_URLCONF = 'gfitness.urls'\n\nWSGI_APPLICATION = 'gfitness.wsgi.application'\n\n\n# ========================== DATABASE SETTINGS ==========================\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\nLANGUAGE_CODE = 'en'\n\nLANGUAGES = [\n ('en', 'English'),\n]\n\nTIME_ZONE = 'US/Eastern'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\nMARKETING_HOURS_OFFSET = 3\nMARKETING_SECONDS_OFFSET = 0\n\nTEMPLATE_CONTEXT_PROCESSORS = TCP + (\n \"django.contrib.auth.context_processors.auth\",\n \"django.contrib.messages.context_processors.messages\",\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.request\",\n \"django.core.context_processors.media\",\n \"django.core.context_processors.static\",\n \"django.core.context_processors.tz\",\n \"django.core.context_processors.csrf\",\n \"allauth.account.context_processors.account\",\n \"allauth.socialaccount.context_processors.socialaccount\",\n)\n\nAUTHENTICATION_BACKENDS = (\n \"django.contrib.auth.backends.ModelBackend\",\n \"allauth.account.auth_backends.AuthenticationBackend\",\n)\n\n# ========================== FILE SETTINGS ==========================\n\n# MEDIA_URL = '/media/'\n\n# STATIC_URL = '/static/'\n\n# MEDIA_ROOT = os.path.join(os.path.dirname(settings.BASE_DIR), \"src\", \"static\", \"media\")\n\n# STATIC_ROOT = os.path.join(os.path.dirname(settings.BASE_DIR), \"src\", \"static\", \"root\")\n\n# STATICFILES_DIRS = (\n# os.path.join(os.path.dirname(settings.BASE_DIR), \"src\", \"static\", \"static\"),\n# )\n\nTEMPLATE_DIRS = (\n os.path.join(BASE_DIR, 'templates'),\n)\n\nSTATIC_ROOT = 'staticfiles'\nSTATIC_URL = '/static/'\nMEDIA_URL = '/media/'\n\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'static'),\n)\n\nMEDIAFILES_DIRS = (\n os.path.join(BASE_DIR, 'static', 'media')\n)\n\n# MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media')\n","sub_path":"gfitness/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"216045256","text":"\"\"\"\nAuthor: Zitong Wu\nDate: Oct 26, 2020\n\nDescription:\n Writes a general-purpose solver with GSAT and WALKSAT algorithms\n for propositional logic satisfiability problems. To test the solver, \n sudoku logic puzzles are turned into conjunctive normal forms (CNF)\n and are thus modeled as satisfiability problems. Note that sudoku\n puzzles are used as an example here. GSAT and WALKSAT algorithms \n can be applied to other satisfiability problems as well. \n \nThis script: Implements a utility that lets you do the sud to cnf\nconversion from the command-line (provided code)\n\n\"\"\"\n\nfrom Sudoku import Sudoku\nimport sys\n\nif __name__ == \"__main__\":\n test_sudoku = Sudoku()\n\n test_sudoku.load(sys.argv[1])\n print(test_sudoku)\n\n puzzle_name = sys.argv[1][:-4]\n cnf_filename = puzzle_name + \".cnf\"\n\n test_sudoku.generate_cnf(cnf_filename)\n print(\"Output file: \" + cnf_filename)\n\n","sub_path":"sudoku2cnf.py","file_name":"sudoku2cnf.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"433845486","text":"import pandas as pd\nimport numpy as np\n\nfrom const import *\nfrom datetime import time\n\n\ndef get_data_frame(employees, min_number_of_active_months):\n df = pd.read_csv('datasets/communication.csv', sep=';')\n\n df[EVENT_DATE] = pd.to_datetime(df[EVENT_DATE])\n\n df = delete_not_employee_accounts(df, employees)\n df = delete_messages_sent_to_yourself(df)\n df = delete_employees_under_threshold_activity(df, min_number_of_active_months)\n df = aggregate_messages_to_recipient(df)\n df = calculate_weights(df)\n df = calculate_overtime(df)\n df = calculate_work_at_weekend(df)\n return df\n\n\ndef delete_not_employee_accounts(df, employees):\n indexes_to_drop = []\n for index, row in df.iterrows():\n if row[SENDER] not in employees or row[RECIPIENT] not in employees:\n indexes_to_drop.append(index)\n df = df.drop(indexes_to_drop)\n return df\n\n\ndef delete_messages_sent_to_yourself(df):\n indexes_to_drop = []\n for index, row in df.iterrows():\n if row[SENDER] == row[RECIPIENT]:\n indexes_to_drop.append(index)\n\n df = df.drop(indexes_to_drop)\n return df\n\n\ndef delete_employees_under_threshold_activity(df, min_number_of_active_months):\n employees_activity = {}\n\n for _, row in df.iterrows():\n if row.Sender not in employees_activity:\n employees_activity[row.Sender] = set()\n employees_activity[row.Sender].add(row.EventDate.month)\n\n indexes_to_drop = []\n\n for index, row in df.iterrows():\n if len(employees_activity[row.Sender]) < min_number_of_active_months:\n indexes_to_drop.append(index)\n\n df = df.drop(indexes_to_drop)\n return df\n\n\ndef aggregate_messages_to_recipient(df):\n grouped_data = df.groupby([SENDER, RECIPIENT])\n\n senders = []\n recipients = []\n all_events = []\n\n for name, group in grouped_data:\n sender = name[0]\n recipient = name[1]\n employee_events = group[EVENT_DATE].tolist()\n\n senders.append(sender)\n recipients.append(recipient)\n all_events.append(employee_events)\n\n return pd.DataFrame({SENDER: senders, RECIPIENT: recipients, EVENT_DATE: all_events})\n\n\ndef calculate_weights(df):\n weights = []\n for index, row in df.iterrows():\n all_send_messages = len(df[df[SENDER] == row[SENDER]])\n messages_send_to_recipient = len(row[EVENT_DATE])\n weights.append(messages_send_to_recipient / all_send_messages)\n\n df[WEIGHT] = np.asarray(weights)\n\n return df\n\n\ndef calculate_overtime(df):\n overtimes = []\n for index, row in df.iterrows():\n overtime_counter = 0\n for email_date in row[EVENT_DATE]:\n if time(17,0) <= email_date.time() <= time(23,59) or time(0,0) <= email_date.time() <= time(5,0):\n overtime_counter += 1\n overtimes.append(overtime_counter)\n\n df[OVERTIME] = overtimes\n\n return df\n\n\ndef calculate_work_at_weekend(df):\n weekends = []\n for index, row in df.iterrows():\n weekend_counter = 0\n for email_date in row[EVENT_DATE]:\n if email_date.weekday() == 5 or email_date.weekday() == 6:\n weekend_counter += 1\n weekends.append(weekend_counter)\n\n df[WORK_AT_WEEKEND] = weekends\n\n return df\n\n\n","sub_path":"create_data_frame.py","file_name":"create_data_frame.py","file_ext":"py","file_size_in_byte":3251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"19615801","text":"from os import environ\nfrom datetime import timedelta\n\ntoken = environ['BOT_TOKEN']\nmy_id = int(environ['MY_ID'])\nwolfram_appid = environ['WOLFRAM_APPID']\nwolfram_url = 'https://api.wolframalpha.com/v1/simple?appid=' + wolfram_appid\nwolfram_max_ratio = 2.5\nbl_text_file = 'data/bl_data/bl_text_messages'\nbl_images_locations = 'data/bl_data/images/'\nmatan_image = 'data/matan.jpg'\nnew_member_sticker = 'CAADAgADrQEAAm29TQUoveU--qPBlAI'\ncho_pacani_sticker = 'CAADAgADJwADtIuIDaIy4m-uZXREAg'\nchto_pacani_pattern = r'(?iu).*чт?[оеё],? п[ао][цс][ао]ны'\ndeer_dembel_date = {'year': 2018, 'month': 12, 'day': 13}\ntechnoconfa_chatname = 'Техноконфа_2020'\nbot_username = '@technopsynabot'\nlogs_channel = '@technocofachbot_logs'\nupdate_delete_user_time = timedelta(seconds=3600)\nuser_delete_time = timedelta(days=1)\ndembel_message = '13 декабря 2018 года рядовой Олень с почётом закончил проходить военную службу ' \\\n 'в рядах доблестной Росгвардии!'\n\ntext_commands = {\n 'about': 'data/about_command_text',\n 'start': 'data/about_command_text',\n 'help': 'data/help_command_text',\n 'wiki': 'data/wiki_command_text',\n 'passing_scores': 'data/passing_scores',\n 'olymp_privileges': 'data/olymp_privileges',\n 'helpline': 'data/helpline'\n}\n\nege_countdown_commands = {\n 'math': ('2020-06-01', 'математике'),\n 'rus': ('2020-05-28', 'русскому языку'),\n 'inf': ('2020-05-25', 'информатике'),\n 'phys': ('2020-06-16', 'физике')\n}\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"265213473","text":"CALLBACK_DATA = {'Старт': 'start',\n 'Главное меню': 'main_menu',\n 'Внести трудозатраты': 'input_work_time',\n 'Статистика за неделю': 'stats',\n 'Текущий проект': 'current_project',\n 'Выбрать день календаря': 'calendar_day',\n 'Выбрать вид деятельности': 'koa',\n 'Выбрать АС': 'as',\n 'Выбрать тип задачи': 'tt',\n 'Введен релиз': 'input_rel',\n 'Введены трудозатраты': 'input_time',\n 'Введены артефакты': 'input_art',\n 'Введено описание': 'input_desc',\n 'Конец': 'finish'\n }\n","sub_path":"callback_data.py","file_name":"callback_data.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"7607633","text":"# -*- coding: utf-8 -*-\n\"\"\"\nHolds all the information relevant to the client (addresses for instance)\n\"\"\"\nfrom django.contrib.auth import get_user_model\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom django.conf import settings\n\nBASE_ADDRESS_TEMPLATE = \\\n_(\"\"\"\nName: %(name)s,\nAddress: %(address)s,\nZip-Code: %(zipcode)s,\nCity: %(city)s,\nState: %(state)s,\nCountry: %(country)s\n\"\"\")\n\nADDRESS_TEMPLATE = getattr(settings, 'SHOP_ADDRESS_TEMPLATE',\n BASE_ADDRESS_TEMPLATE)\n\n\n# class Country(models.Model):\n# name = models.CharField(max_length=255)\n\n# def __unicode__(self):\n# return u'%s' % self.name\n\n# class Meta(object):\n# verbose_name = _('Country')\n# verbose_name_plural = _('Countries')\n\n\nclass City(models.Model):\n name = models.CharField(max_length=128)\n weight = models.IntegerField(default=0)\n\n class Meta:\n ordering = ['weight']\n\n def __unicode__(self):\n return self.name\n\n\nclass Township(models.Model):\n city = models.ForeignKey(City, verbose_name=u\"İl\")\n name = models.CharField(max_length=128)\n weight = models.IntegerField(default=0)\n\n class Meta:\n ordering = ['weight']\n\n def __unicode__(self):\n return self.name\n\n\nclass BaseAddress(models.Model):\n first_name = models.CharField(max_length=50,\n verbose_name=u\"Ad\")\n last_name = models.CharField(max_length=50,\n verbose_name=u\"Soyad\")\n address = models.TextField(verbose_name=u\"Adres\")\n city = models.ForeignKey(City,\n verbose_name=u\"İl\")\n town = models.ForeignKey(Township,\n verbose_name=u\"İlçe\")\n postal_code = models.CharField(max_length=5,\n verbose_name=u\"Posta Kodu\",\n blank=True,\n null=True)\n phone = models.CharField(max_length=13,\n verbose_name=u\"Telefon\",\n null=True)\n id_number = models.CharField(max_length=11,\n verbose_name=u\"TC Kimlik No\",\n blank=True,\n null=True)\n tax_office = models.CharField(max_length=64,\n verbose_name=u\"Vergi Dairesi\",\n blank=True,\n null=True)\n tax_id_number = models.CharField(max_length=20,\n verbose_name=u\"Vergi Numarası\",\n blank=True,\n null=True)\n\n class Meta:\n abstract = True\n\n def as_text(self):\n return \"\"\"\n %s\n %s %s\n %s / %s\n %s\n \"\"\" % (self.get_full_name(),\n self.address, self.postal_code,\n self.town, self.city,\n self.phone)\n\n def clone(self):\n new_kwargs = dict([(fld.name, getattr(self, fld.name)) for fld in self._meta.fields if fld.name != 'id'])\n return self.__class__.objects.create(**new_kwargs)\n\n def __unicode__(self):\n return u\"%s - %s\" % (self.get_full_name(), self.city.name)\n\n def get_full_name(self):\n return u\"%s %s\" % (self.first_name.strip(), self.last_name.strip())\n\n\nclass Address(BaseAddress):\n user_shipping = models.OneToOneField(get_user_model(), related_name='shipping_address',\n blank=True, null=True)\n\n user_billing = models.OneToOneField(get_user_model(), related_name='billing_address',\n blank=True, null=True)\n\n\n\n# class Address(models.Model):\n# user_shipping = models.OneToOneField(get_user_model(), related_name='shipping_address',\n# blank=True, null=True)\n# user_billing = models.OneToOneField(get_user_model(), related_name='billing_address',\n# blank=True, null=True)\n\n# name = models.CharField(_('Name'), max_length=255)\n# address = models.CharField(_('Address'), max_length=255)\n# address2 = models.CharField(_('Address2'), max_length=255, blank=True)\n# zip_code = models.CharField(_('Zip Code'), max_length=20)\n# city = models.CharField(_('City'), max_length=20)\n# state = models.CharField(_('State'), max_length=255)\n# country = models.ForeignKey(Country, verbose_name=_('Country'), blank=True,\n# null=True)\n\n# class Meta(object):\n# verbose_name = _('Address')\n# verbose_name_plural = _(\"Addresses\")\n\n# def __unicode__(self):\n# return '%s (%s, %s)' % (self.name, self.zip_code, self.city)\n\n# def clone(self):\n# new_kwargs = dict([(fld.name, getattr(self, fld.name))\n# for fld in self._meta.fields if fld.name != 'id'])\n# return self.__class__.objects.create(**new_kwargs)\n\n# def as_text(self):\n# return ADDRESS_TEMPLATE % {\n# 'name': self.name,\n# 'address': '%s\\n%s' % (self.address, self.address2),\n# 'zipcode': self.zip_code,\n# 'city': self.city,\n# 'state': self.state,\n# 'country': self.country,\n# }","sub_path":"shop/addressmodel/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"204181293","text":"import argparse\r\nfrom AdbHandler import ADB\r\nimport os\r\nimport subprocess\r\nimport time\r\nfrom RemoteRaspberry import RemoteRaspberry\r\n\r\nROOT_FOLDER = os.path.split(os.getcwd())[0]\r\nTEST_APK_FOLDER = os.path.join(ROOT_FOLDER, \"SI\", \"app\", \"build\", \"outputs\", \"apk\", \"debug\")\r\nTEST_APK_DEBUG_FOLDER = os.path.join(ROOT_FOLDER, \"SI\", \"app\", \"build\", \"outputs\", \"apk\", \"androidTest\", \"debug\")\r\nAPP_APK_FOLDER = os.path.join(ROOT_FOLDER, \"artifacts\", \"APK\")\r\nTEST_DATA_FOLDER = os.path.join(ROOT_FOLDER, \"SI\", \"artifacts\", \"binaries\", \"fingerprints\")\r\n\r\n\r\ndef clean_up_phone(remote_adb):\r\n print(\"Cleaning up old files and folders\")\r\n remote_adb.run_adb_command(\"shell rm -rf /data/system/users/0/fpdata\")\r\n remote_adb.run_adb_command(\"shell rm -f /data/system/users/0/settings_fingerprint.xml\")\r\n remote_adb.run_adb_command(\"shell rm -rf /storage/emulated/0/logs\")\r\n remote_adb.run_adb_command(\"shell rm -rf /storage/emulated/0/injection\")\r\n\r\n remote_adb.run_adb_command(\"shell rm -rf /data/anr\")\r\n remote_adb.run_adb_command(\"shell rm -rf /data/tombstones\")\r\n remote_adb.run_adb_command(\"shell rm -rf /data/diag_logs\")\r\n remote_adb.run_adb_command(\"shell rm -rf /data/fpc/diag_logs\")\r\n\r\n\r\ndef compile_tests():\r\n print(\"Compiling tests\")\r\n subprocess.check_call(\"gradle assembleDebug assembleDebugAndroidTest\", shell=True,\r\n cwd=os.path.join(ROOT_FOLDER, \"SI\"))\r\n\r\n\r\ndef install_tests_and_apps(spi, install_apps, software, sensortest, remote_adb):\r\n print(\"Installing tests and apps\")\r\n remote_adb.wait_for_system()\r\n remote_adb.install_app(os.path.join(ROOT_FOLDER, TEST_APK_FOLDER, \"app-debug.apk\"))\r\n\r\n remote_adb.wait_for_system()\r\n remote_adb.install_app(os.path.join(ROOT_FOLDER, TEST_APK_DEBUG_FOLDER, \"app-debug-androidTest.apk\"))\r\n\r\n if install_apps:\r\n if software == \"SW22\":\r\n install_test_app(\"ImageInterception\", os.path.join(APP_APK_FOLDER, \"ImageInterception\"), remote_adb)\r\n else:\r\n install_test_app(\"ImageInjection\", os.path.join(APP_APK_FOLDER, \"ImageInjection\"), remote_adb)\r\n\r\n if sensortest:\r\n install_test_app(\"ImageTool\", os.path.join(APP_APK_FOLDER, \"ImageTool\"), remote_adb)\r\n\r\n install_test_app(\"SensorTestTool\", os.path.join(APP_APK_FOLDER, \"SensorTestTool\"), remote_adb)\r\n install_test_app(\"ImageCollection\", os.path.join(APP_APK_FOLDER, \"ImageCollection\"), remote_adb)\r\n install_test_app(\"ImageSubscription\", os.path.join(APP_APK_FOLDER, \"ImageSubscription\"), remote_adb)\r\n\r\n\r\ndef install_test_app(name, folder, remote_adb):\r\n print(\"Installing %s\" % name)\r\n for file in os.listdir(folder):\r\n # Can be serveral files and we just take one of them.\r\n remote_adb.run_adb_command(\"shell rm -rf /system/priv-app/%s\" % name)\r\n remote_adb.adb_push(os.path.join(folder, file), \"/system/priv-app/%s/%s.apk\" % (name, name))\r\n #adb.run_adb_push(os.path.join(folder, file), \"/system/priv-app/%s/\" % name)\r\n #adb.run_adb_shell(\"mv /system/priv-app/{0}/*.apk /system/priv-app/{0}/{0}.apk\".format(name))\r\n break\r\n else:\r\n print(\"[WARNING] Failed to find %s app\" % name)\r\n\r\n\r\ndef set_permissions(spi, software, sensortest, remote_adb):\r\n print(\"Setting permissions for apps\")\r\n remote_adb.wait_for_system()\r\n try:\r\n remote_adb.run_adb_command(\"shell pm grant com.fingerprints.si android.permission.READ_LOGS\")\r\n remote_adb.run_adb_command(\"shell pm grant com.fingerprints.si android.permission.READ_EXTERNAL_STORAGE\")\r\n remote_adb.run_adb_command(\"shell pm grant com.fingerprints.si android.permission.WRITE_EXTERNAL_STORAGE\")\r\n except:\r\n print('[WARNING] Could not set permissions for com.fingerprints.si')\r\n\r\n try:\r\n if software == \"SW22\":\r\n remote_adb.run_adb_command(\"shell pm grant com.fingerprints.imageinterception android.permission.READ_EXTERNAL_STORAGE\")\r\n remote_adb.run_adb_command(\"shell pm grant com.fingerprints.imageinterception android.permission.WRITE_EXTERNAL_STORAGE\")\r\n else:\r\n remote_adb.run_adb_command(\"shell pm grant com.fingerprints.imageinjection android.permission.READ_EXTERNAL_STORAGE\")\r\n remote_adb.run_adb_command(\"shell pm grant com.fingerprints.imageinjection android.permission.WRITE_EXTERNAL_STORAGE\")\r\n except:\r\n print('[WARNING] Could not set permissions Image Interception/Injection')\r\n\r\n try:\r\n if sensortest:\r\n remote_adb.run_adb_command(\"shell pm grant com.fingerprints.sensortesttool android.permission.READ_EXTERNAL_STORAGE\")\r\n remote_adb.run_adb_command(\"shell pm grant com.fingerprints.sensortesttool android.permission.WRITE_EXTERNAL_STORAGE\")\r\n except:\r\n print('[WARNING] Could not set permissions for Sensor Test Tool')\r\n\r\n try:\r\n remote_adb.run_adb_command(\"shell pm grant com.fingerprints.imagecollection android.permission.READ_EXTERNAL_STORAGE\")\r\n remote_adb.run_adb_command(\"shell pm grant com.fingerprints.imagecollection android.permission.WRITE_EXTERNAL_STORAGE\")\r\n except:\r\n print('[WARNING] Could not set permissions for Image Collection')\r\n\r\n try:\r\n remote_adb.run_adb_command(\"shell pm grant com.fingerprints.imagetool android.permission.READ_EXTERNAL_STORAGE\")\r\n remote_adb.run_adb_command(\"shell pm grant com.fingerprints.imagetool android.permission.WRITE_EXTERNAL_STORAGE\")\r\n except:\r\n print('[WARNING] Could not set permissions for Image Tool')\r\n\r\n try:\r\n remote_adb.run_adb_command(\"shell pm grant com.fingerprints.imagesubscription android.permission.READ_EXTERNAL_STORAGE\")\r\n remote_adb.run_adb_command(\"shell pm grant com.fingerprints.imagesubscription android.permission.WRITE_EXTERNAL_STORAGE\")\r\n except:\r\n print('[WARNING] Could not set permissions for Image Subscription')\r\n\r\n\r\ndef push_test_data(software, sensor, remote_adb):\r\n print(\"Pushing test data\")\r\n pushed = False\r\n attempt = 0\r\n while not pushed:\r\n try:\r\n remote_adb.adb_push(os.path.join(TEST_DATA_FOLDER, software, sensor) + \"/\", \"/storage/emulated/0/injection\")\r\n pushed = True\r\n except Exception as e:\r\n print(\"Failed to push data, retry\")\r\n time.sleep(5)\r\n attempt += 1\r\n if attempt > 3:\r\n print(\"Failed to push data 3 times: \" + e)\r\n raise e\r\n\r\n\r\ndef get_software(branch):\r\n software = \"DEV\"\r\n install_apps = False\r\n if \"sw22\" in branch.lower():\r\n software = \"SW22\"\r\n install_apps = True\r\n if \"sw23\" in branch.lower():\r\n software = \"SW23\"\r\n install_apps = True\r\n if \"sw24\" in branch.lower():\r\n software = \"SW24\"\r\n install_apps = True\r\n if \"sw25\" in branch.lower():\r\n software = \"SW25\"\r\n install_apps = True\r\n if \"sw26\" in branch.lower():\r\n software = \"SW26\"\r\n if \"sw27\" in branch.lower():\r\n software = \"SW27\"\r\n if \"sw28\" in branch.lower():\r\n software = \"SW28\"\r\n if \"sw29\" in branch.lower():\r\n software = \"SW29\"\r\n\r\n return software, install_apps\r\n\r\n\r\ndef start(sensor, model, branch, sensortest, spi, rpi):\r\n remote_adb = ADB(rpi)\r\n remote_adb.root_device()\r\n clean_up_phone(remote_adb)\r\n compile_tests()\r\n remote_adb.root_device()\r\n software, install_apps = get_software(branch)\r\n install_tests_and_apps(spi, install_apps, software, sensortest, remote_adb)\r\n remote_adb.reboot_device()\r\n remote_adb.root_device()\r\n set_permissions(spi, software, sensortest, remote_adb)\r\n push_test_data(software, sensor, remote_adb)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--sensor', '-s', required=True, help='FPC Sensor on phone')\r\n parser.add_argument('--model', '-m', required=True, help='Target model')\r\n parser.add_argument('--manifest', '-mv', required=True, help='Manifest version')\r\n parser.add_argument('--sensortest', '-st', required=True, help='_SENSORTEST_')\r\n parser.add_argument('--spi', '-spi', required=True, help='_SPI_INTERCEPTION_')\r\n parser.add_argument('--ip', '-ip', required=True, help='IP to the Raspberry Pi')\r\n\r\n args = parser.parse_args()\r\n args.model = args.model.lower()\r\n args.sensor = args.sensor.lower()\r\n args.manifest = args.manifest.lower()\r\n rpi = RemoteRaspberry(args.ip)\r\n\r\n start(args.sensor, args.model, args.manifest, args.sensortest, args.spi, rpi)\r\n rpi.close()\r\n","sub_path":"SI/python/install_apps_and_test_data.py","file_name":"install_apps_and_test_data.py","file_ext":"py","file_size_in_byte":8548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"374816941","text":"import unittest\nimport os\nimport time\n\nimport brawlstats\nfrom brawlstats.models import BattleLog, Club, Constants, Members, Ranking\nfrom dotenv import load_dotenv, find_dotenv\n\nload_dotenv(find_dotenv('.env'))\n\nTOKEN = os.getenv('token')\nURL = os.getenv('base_url')\n\n\nclass TestBlockingClient(unittest.TestCase):\n \"\"\"Tests all methods in the blocking client that\n uses the `requests` module in `brawlstats`\n \"\"\"\n def setUp(self):\n self.player_tag = '#GGJVJLU2'\n self.club_tag = '#QCGV8PG'\n self.client = brawlstats.Client(\n TOKEN,\n is_async=False,\n base_url=URL,\n timeout=30\n )\n\n def tearDown(self):\n time.sleep(1)\n self.client.close()\n\n def test_get_player(self):\n player = self.client.get_player(self.player_tag)\n self.assertEqual(player.tag, self.player_tag)\n\n club = player.get_club()\n self.assertIsInstance(club, Club)\n\n def test_get_club(self):\n club = self.client.get_club(self.club_tag)\n self.assertEqual(club.tag, self.club_tag)\n\n members = club.get_members()\n self.assertIsInstance(members, Members)\n\n def test_get_club_members(self):\n members = self.client.get_club_members(self.club_tag)\n self.assertIsInstance(members, Members)\n\n def test_get_rankings_player(self):\n rankings = self.client.get_rankings(ranking='players')\n self.assertIsInstance(rankings, Ranking)\n region = self.client.get_rankings(ranking='players', region='us')\n self.assertIsInstance(region, Ranking)\n\n def test_get_rankings_club(self):\n rankings = self.client.get_rankings(ranking='clubs')\n self.assertIsInstance(rankings, Ranking)\n limit = self.client.get_rankings(ranking='clubs', limit=100)\n self.assertTrue(len(limit) == 100)\n\n def test_get_rankings_brawler(self):\n rankings = self.client.get_rankings(ranking='brawlers', brawler='shelly')\n self.assertIsInstance(rankings, Ranking)\n rankings = self.client.get_rankings(ranking='brawlers', brawler=16000000)\n self.assertIsInstance(rankings, Ranking)\n\n def test_get_constants(self):\n default = self.client.get_constants()\n self.assertIsInstance(default, Constants)\n maps = self.client.get_constants('maps')\n self.assertIsInstance(maps, Constants)\n get_constants = self.client.get_constants\n invalid_key = 'invalid'\n self.assertRaises(KeyError, get_constants, invalid_key)\n\n def test_battle_logs(self):\n logs = self.client.get_battle_logs(self.player_tag)\n self.assertIsInstance(logs, BattleLog)\n\n def test_invalid_tag(self):\n get_player = self.client.get_player\n invalid_tag = 'P'\n self.assertRaises(brawlstats.NotFoundError, get_player, invalid_tag)\n invalid_tag = 'AAA'\n self.assertRaises(brawlstats.NotFoundError, get_player, invalid_tag)\n invalid_tag = '2PPPPPPP'\n self.assertRaises(brawlstats.NotFoundError, get_player, invalid_tag)\n\n def test_invalid_rankings(self):\n get_rankings = self.client.get_rankings\n invalid_ranking = 'test'\n invalid_limit = 200\n self.assertRaises(ValueError, get_rankings, ranking=invalid_ranking, limit=invalid_limit)\n invalid_ranking = 'players'\n invalid_limit = 201\n self.assertRaises(ValueError, get_rankings, ranking=invalid_ranking, limit=invalid_limit)\n invalid_ranking = 'players'\n invalid_limit = -5\n self.assertRaises(ValueError, get_rankings, ranking=invalid_ranking, limit=invalid_limit)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_blocking.py","file_name":"test_blocking.py","file_ext":"py","file_size_in_byte":3685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"236999776","text":"'''\nThis is the slight modification of the SPLOM dataset generation process used by\nimMens paper. Although this is a modification, it basically uses the same\nparameters to sample from Gaussian distributions; thus, there should not be any\nqualitative difference.\n'''\nimport numpy as np\nimport math\n\n\n\ndef generate_tuple():\n a_tuple = np.zeros(5, dtype=float)\n a_tuple[0] = np.random.normal(10, 10)\n a_tuple[1] = np.random.normal(10, 10)\n a_tuple[2] = np.random.normal(a_tuple[0], 10)\n a_tuple[3] = math.log(math.fabs(a_tuple[0])+1) + np.random.uniform(0,1)\n a_tuple[4] = np.random.normal(10, 10)\n return a_tuple\n\n\ndef generate_short_tuple():\n a_tuple = np.zeros(3, dtype=float)\n a_tuple[0] = np.random.normal(10, 10)\n a_tuple[1] = np.random.normal(10, 10)\n a_tuple[2] = np.random.normal(a_tuple[0], 10)\n return a_tuple\n\n\ndef generate_dataset(fout_name, size = 1000):\n fout = open(fout_name, 'w')\n\n for i in range(size):\n a_tuple = generate_short_tuple()\n a_tuple_str = ','.join(map(str, a_tuple))\n fout.write(a_tuple_str)\n fout.write('\\n')\n\n fout.close()\n\n\nif __name__ == \"__main__\":\n filename = '/z/pyongjoo_data/diverse/originals/splom_1B.csv'\n generate_dataset(filename, size = int(1e9))\n","sub_path":"dataset/splom/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"494690255","text":"from django.core.mail.backends.smtp import EmailBackend\nfrom django.conf import settings\nimport dkim\nfrom django_tools.middlewares import ThreadLocal\n\n\n\nclass DKIMBackend(EmailBackend):\n def _send(self, email_message):\n \"\"\"A helper method that does the actual sending + DKIM signing.\"\"\"\n if not email_message.recipients():\n return False\n try:\n message_string = email_message.message().as_string()\n signature = dkim.sign(message_string,\n settings.DKIM_SELECTOR,\n settings.DKIM_DOMAIN,\n settings.DKIM_PRIVATE_KEY)\n self.connection.sendmail(email_message.from_email, email_message.recipients(), signature+message_string)\n except:\n if not self.fail_silently:\n raise\n return False\n return True\n\n\nclass TestMailBackend(EmailBackend):\n def _send(self, email_message):\n \"\"\" Force recipient to the current user.\"\"\"\n request = ThreadLocal.get_current_request()\n\n try:\n request.user.is_authenticated()\n recipient = request.user.email\n except:\n recipient = str(email_message.recipients()[0])\n if '+test' not in recipient:\n return False\n\n try:\n email_message.subject += ' || To: ' + str(email_message.recipients()[0])\n message_string = email_message.message().as_string()\n\n self.connection.sendmail(email_message.from_email, recipient, message_string)\n except:\n if not self.fail_silently:\n raise\n return False\n return True\n","sub_path":"bluebottle/utils/email_backend.py","file_name":"email_backend.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"190392996","text":"import uuid\n\nfrom django.conf import settings\nfrom django.db import models\nfrom django.utils import timezone\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass UserstampModel(models.Model):\n '''\n A model that records which user created it and which\n user last updated it.\n '''\n created_by = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n blank=True,\n null=True,\n related_name='%(app_label)s_%(class)s_created_objects',\n on_delete=models.SET_NULL\n )\n last_updated_by = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n blank=True,\n null=True,\n related_name='%(app_label)s_%(class)s_last_updated_objects',\n on_delete=models.SET_NULL\n )\n\n class Meta:\n abstract = True\n\n\nclass SerializeModel(models.Model):\n\n serializer = None\n\n class Meta:\n abstract = True\n\n def get_serializer(self):\n if self.serializer is not None:\n return self.serializer(self)\n else:\n return self.serializer\n\n def serialize(self):\n if self.serializer is not None:\n return self.get_serializer().data\n\n\nclass TimestampModel(models.Model):\n date_created = models.DateTimeField(\n verbose_name=_('label_date_created'),\n default=timezone.now,\n editable=False\n )\n date_updated = models.DateTimeField(\n verbose_name=_('label_date_updated'),\n auto_now=True,\n editable=False\n )\n\n class Meta:\n abstract = True\n\n\nclass UUIDModel(models.Model):\n '''\n A model whose id is a generated uuid.\n '''\n id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n\n class Meta:\n abstract = True\n","sub_path":"prototype/core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"263852155","text":"def cal_value(s1, s2):\n n1 = len(s1)\n n2 = len(s2)\n if s1 == s2: return 0\n if n1 == 0: return sum(ord(c) for c in s2)\n j = 0\n results = \"\"\n for i in range(n1):\n j = i + len(results)\n if j >= n2:\n return -1\n while s1[i] != s2[j]:\n results += s2[j]\n j += 1\n if j >= n2: \n return -1\n # i.p()\n if j < n2-1:\n results += s2[j+1:]\n if len(results) > 0:\n return sum(ord(c) for c in results)\n else:\n return 0\n\nclass Solution(object):\n def minimumDeleteSum(self, s1, s2):\n \"\"\"\n :type s1: str\n :type s2: str\n :rtype: int\n \"\"\"\n level = False\n results = []\n queue = [s1]\n visited = {s1:True}\n\n while queue:\n cur = queue.pop(0)\n cur_v = cal_value(cur, s2)\n # (cur, cur_v).p()\n if cur_v >= 0:\n results += cur_v + cal_value(cur, s1),\n # results.p()\n level = True\n if level: \n continue\n for i in range(len(cur)):\n new_s = cur[:i] + cur[i+1:]\n if new_s not in visited:\n queue.append(new_s) \n visited[new_s] = True\n if results:\n return min(results)\n else: return None\n\n def minimumDeleteSum(self, s1, s2):\n \"\"\"\n :type s1: str\n :type s2: str\n :rtype: int\n \"\"\"\n def cal_s(s):\n return sum(ord(c) for c in s) \n n1 = len(s1)\n n2 = len(s2)\n if s1 == s2: return 0\n if n1 == 0: return sum(ord(c) for c in s2)\n if n2 == 0: return sum(ord(c) for c in s1)\n dp = [ [0] * n2 for _ in range(n1)]\n j = 0\n for i in range(n1):\n if s2[j] == s1[i]:\n dp[i][j] = cal_s(s1[:i+1]) - ord(s2[j])\n else:\n dp[i][j] = cal_s(s1[:i+1]) + ord(s2[j])\n i = 0\n for j in range(n2):\n if s1[i] in s2[:j+1]:\n dp[i][j] = cal_s(s2[:j+1]) - ord(s1[i])\n else:\n dp[i][j] = cal_s(s2[:j+1]) + ord(s1[i])\n\n for i in range(1,n1):\n for j in range(1,n2):\n if s1[i] == s2[j]:\n dp[i][j] = dp[i-1][j-1]\n else:\n dp[i][j] = min(dp[i-1][j]+ord(s1[i]), dp[i][j-1]+ord(s2[j]))\n # dp.p()\n return dp[-1][-1]\n \n \n def minimumDeleteSum(self, s1, s2):\n \"\"\"\n :type s1: str\n :type s2: str\n :rtype: int\n \"\"\"\n def cal_s(s):\n return sum(ord(c) for c in s) \n n1 = len(s1)\n n2 = len(s2)\n if s1 == s2: return 0\n if n1 == 0: return sum(ord(c) for c in s2)\n if n2 == 0: return sum(ord(c) for c in s1)\n dp = [ [0] * n2 for _ in range(n1)]\n e1, e2 = False, False\n if s1[0] == s2[0]:\n e1, e2 = True, True\n else:\n dp[0][0] = ord(s1[0]) + ord(s2[0])\n j = 0\n for i in range(1,n1):\n if not e1 and s1[i] == s2[j]:\n dp[i][j] = dp[i-1][j] - ord(s1[i])\n e1 = True\n else:\n dp[i][j] = dp[i-1][j] + ord(s1[i])\n i = 0\n for j in range(1,n2):\n if not e2 and s1[i] == s2[j]:\n dp[i][j] = dp[i][j-1] - ord(s2[j])\n e2 = True\n else:\n dp[i][j] = dp[i][j-1] + ord(s2[j])\n\n for i in range(1,n1):\n for j in range(1,n2):\n if s1[i] == s2[j]:\n dp[i][j] = dp[i-1][j-1]\n else:\n dp[i][j] = min(dp[i-1][j]+ord(s1[i]), dp[i][j-1]+ord(s2[j]))\n # dp.p()\n return dp[-1][-1]\n def minimumDeleteSum(self, s1, s2):\n \"\"\"\n :type s1: str\n :type s2: str\n :rtype: int\n \"\"\"\n dp = [ [0] * (len(s2)+1) for _ in range(len(s1)+1)]\n j = 0\n for i in range(1,len(dp)):\n dp[i][j] = dp[i-1][j] + ord(s1[i-1])\n i = 0\n for j in range(1,len(dp[0])):\n dp[i][j] = dp[i][j-1] + ord(s2[j-1])\n for i in range(1,len(dp)):\n for j in range(1,len(dp[0])):\n if s1[i-1] == s2[j-1]:\n dp[i][j] = dp[i-1][j-1]\n else:\n dp[i][j] = min(dp[i-1][j]+ord(s1[i-1]), dp[i][j-1]+ord(s2[j-1]))\n return dp[-1][-1]\n\n\n\nif __name__ == '__main__':\n from minitest import *\n # with test(cal_value):\n # cal_value(\"let\",\"leet\").p()\n # cal_value(\"lete\",\"leet\").p()\n # cal_value(\"let\",\"delete\").p()\n # cal_value(\"ea\",\"sea\").p()\n # cal_value(\"k\",\"yaybzvxitky\").p()\n # cal_value(\"k\",\"rpnuskcphiw\").p()\n # cal_value(\"i\",\"yaybzvxitky\").p()\n # cal_value(\"i\",\"rpnuskcphiw\").p()\n # cal_value(\"\",\"rpnuskcphiw\").p()\n\n with test(Solution):\n Solution().minimumDeleteSum(\"sea\",\"eat\").must_equal(231)\n Solution().minimumDeleteSum(\"delete\",\"leet\").must_equal(403)\n Solution().minimumDeleteSum(\"yaybzvxitky\",\"rpnuskcphiw\").must_equal(2246)\n\n\n\n\n \n ","sub_path":"python/leetcode/dynamic_programming/712_Minimum_ASCII_Delete_Sum_for_Two_Strings.py","file_name":"712_Minimum_ASCII_Delete_Sum_for_Two_Strings.py","file_ext":"py","file_size_in_byte":5230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"363742560","text":"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass MaxMinPair:\n def __init__(self, min=0, max=0) -> None:\n self.min = min\n self.max = max\n\n\nclass Solution:\n def __init__(self) -> None:\n self.treeNodeMap = {}\n self.valid = True\n\n def isValidBST(self, root: TreeNode) -> bool:\n self.getMaxMinValue(root)\n return self.valid\n\n def isLeaf(self, root: TreeNode) -> bool:\n return root is not None and root.left is None and root.right is None\n\n def getMaxMinValue(self, root: TreeNode) -> MaxMinPair:\n # if not self.valid:\n # return None\n if self.isLeaf(root):\n return MaxMinPair(root.val, root.val)\n elif root.left is None:\n rightPair = self.getMaxMinValue(root.right)\n if not self.valid:\n return None\n if root.val < rightPair.min:\n rightPair.min = root.val\n return rightPair\n else:\n self.valid = False\n return None\n elif root.right is None:\n leftPair = self.getMaxMinValue(root.left)\n if not self.valid:\n return None\n if root.val > leftPair.max:\n leftPair.max = root.val\n return leftPair\n else:\n self.valid = False\n return None\n else:\n leftPair = self.getMaxMinValue(root.left)\n rightPair = self.getMaxMinValue(root.right)\n if not self.valid:\n return None\n if root.val > leftPair.max and root.val < rightPair.min:\n return MaxMinPair(leftPair.min, rightPair.max)\n else:\n self.valid = False\n return None\n","sub_path":"Validate-Binary-Search-Tree/validate_binary_search_tree.py","file_name":"validate_binary_search_tree.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"270497527","text":"# uncompyle6 version 3.2.3\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 2.7.5 (default, Jul 13 2018, 13:06:57) \n# [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]\n# Embedded file name: ./sqlaudit/migrations/0046_auto_20180326_2128.py\n# Compiled at: 2018-08-23 19:33:14\n# Size of source mod 2**32: 415 bytes\nfrom django.db import migrations, models\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('sqlaudit', '0045_auto_20180326_2126')]\n operations = [\n migrations.AlterField(model_name='audit_job',\n name='schema',\n field=models.CharField(blank=True, max_length=5000, null=True))]\n# okay decompiling ./restful/hawkeye/sqlaudit/migrations/0046_auto_20180326_2128.pyc\n","sub_path":"restful/hawkeye/sqlaudit/migrations/0046_auto_20180326_2128.py","file_name":"0046_auto_20180326_2128.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"68859562","text":"graph = {}\ngraph[\"yp\"] = {}\ngraph[\"yp\"][\"hjcp\"] = 5\ngraph[\"yp\"][\"hb\"] = 0\ngraph[\"cp\"] = {}\ngraph[\"cp\"][\"jt\"] = 15\ngraph[\"cp\"][\"jzg\"] = 20\ngraph[\"hb\"] = {}\ngraph[\"hb\"][\"jt\"] = 30\ngraph[\"hb\"][\"jzg\"] = 35\ngraph[\"jzg\"] = {}\ngraph[\"jzg\"][\"gq\"] = 10\ngraph[\"jt\"] = {}\ngraph[\"jt\"][\"gq\"] = 20\ngraph[\"gq\"] = {}\n\ninfinity = float(\"inf\")#散列表是开销\ncosts = {}\ncosts[\"cp\"] = 5\ncosts[\"hb\"] = 0\ncosts[\"jt\"] = infinity\ncosts[\"jzg\"] = infinity\ncosts[\"gq\"] = infinity\n\nparents = {} #散列表是父子节点\nparents[\"cp\"] = \"yp\"\nparents[\"hb\"] = \"yp\"\nparents[\"jzg\"] = None\nparents[\"jt\"] = None\nparents[\"gq\"] = None\n\nprocessed = []\n\ndef find_lowest_cost_node(costs):\n lowest_cost = float(\"inf\")\n lowest_cost_node = None\n for node in costs:\n cost = costs[node]\n if cost < lowest_cost and node not in processed:\n lowest_cost = cost\n lowest_cost_node = node\n return lowest_cost_node\n\ndef find_shortest_path():\n node='gq'\n shortest_path=[\"gq\"]\n while node!=\"yp\":\n node=parents[node]\n shortest_path.append(node)\n shortest_path.reverse()\n print('\\n最终路径:')\n print(shortest_path)\n \nif __name__ == '__main__':\n node=find_lowest_cost_node(costs) \n while node is not None:\n cost=costs[node]\n neighbors=graph[node]\n for n in neighbors.keys():\n new_cost=cost+neighbors[n]\n if costs[n]>new_cost:\n costs[n]=new_cost\n parents[n]=node\n processed.append(node) \n node=find_lowest_cost_node(costs)\n shortest_path=find_shortest_path()\n print(shortest_path)\nprint('\\n节点:开销')\nprint(costs)\nprint('\\n节点:父节点')\nprint(parents)\n\n\n\n \n","sub_path":"168206230/06.py","file_name":"06.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"482940005","text":"from datetime import datetime\nimport time\nimport calendar\nfrom uuid import uuid4\n\nfrom contest.models.contest import Contest\nfrom contest.pages.lib.htmllib import UIElement, div, h1, a, h2, h, head, body\n\nfrom opencontest.settings import OC_STATIC_CACHE_SECS\n\ndef cachecontrol():\n secs_since_epoch = int(calendar.timegm(time.gmtime()))\n if OC_STATIC_CACHE_SECS:\n return str(int(secs_since_epoch / OC_STATIC_CACHE_SECS))\n else:\n # Prevent caching by generating a unique uuid\n return str(uuid4())\n\n\nclass Header(UIElement):\n def __init__(self, title, endtimestamp=None):\n timeRemaining = \"\"\n if endtimestamp:\n timeRemaining = str(int(((endtimestamp / 1000) - time.time())))\n self.html = div(cls=\"top\", contents=[\n div(cls=\"header\", contents=[\n h1(title),\n div(cls=\"spacer\"),\n div(cls=\"header-right\", contents=[\n h.span(cls=\"time-remaining\", data_timeremaining=timeRemaining),\n h.br(),\n h.span(cls=\"login-user\")\n ])\n ])\n ])\n\n\nclass MenuItem(UIElement):\n def __init__(self, url, title, role=\"any\"):\n self.html = div(role=role, cls=\"menu-item\", contents=[\n a(href=url, contents=[\n title\n ])\n ])\n\n\nclass Menu(UIElement):\n def __init__(self):\n self.html = div(cls=\"menu\", contents=[\n div(cls=\"menu-items\", contents=[\n MenuItem(\"/problems\", \"Problems\"),\n MenuItem(\"/leaderboard\", \"Leaderboard\"),\n MenuItem(\"/submissions\", \"My Submissions\", role=\"participant\"),\n MenuItem(\"/messages/inbox\", \"Messages\"),\n MenuItem(\"/judge\", \"Judge\", role=\"admin\"),\n MenuItem(\"/setup\", \"Setup\", role=\"admin\"),\n MenuItem(\"/logout\", \"Logout\")\n ])\n ])\n\n\nclass Footer(UIElement):\n def __init__(self):\n self.html = div(cls=\"footer\", contents=[\n h2('Copyright © {} by Nathan Collins and BJU'.format(datetime.now().year)),\n div(cls=\"footer-links\", contents=[\n h.span(h.a(\"System Status\", href=\"/status\")),\n h.span(h.a(\"Privacy Policy\", href=\"/privacy\", target=\"_blank\")),\n h.span(h.a(\"About\", href=\"/about\", target=\"_blank\")),\n h.span(h.a(\"FAQs\", href=\"/faqs\", target=\"_blank\"))\n ])\n ])\n\n\nclass Page(UIElement):\n def __init__(self, *bodyData, cls='main-content'):\n cont = Contest.getCurrent()\n title = cont.name if cont else \"OpenContest\"\n self.html = h.html(\n head(\n h.title(title),\n h.link(rel=\"stylesheet\", href=\"/static/lib/fontawesome/css/all.css\", type=\"text/css\"),\n h.link(rel=\"stylesheet\", href=\"/static/lib/bootstrap/css/bootstrap.min.css\", type=\"text/css\"),\n h.link(rel=\"stylesheet\", href=\"/static/lib/jqueryui/jquery-ui.min.css\", type=\"text/css\"),\n h.link(rel=\"stylesheet\", href=\"/static/lib/simplemde/simplemde.min.css\", type=\"text/css\"),\n h.link(rel=\"stylesheet\", href=\"/static/styles/style.css?\" + cachecontrol(), type=\"text/css\"),\n h.link(rel=\"shortcut icon\", href=\"/static/favicon.ico\"),\n h.script(src=\"/static/lib/jquery/jquery.min.js\"),\n h.script(src=\"/static/lib/bootstrap/js/bootstrap.min.js\"),\n h.script(src=\"/static/lib/jqueryui/jquery-ui.min.js\"),\n h.script(src=\"/static/lib/ace/ace.js\"),\n h.script(src=\"/static/lib/simplemde/simplemde.min.js\"),\n h.script(src=\"/static/scripts/script.js?\" + cachecontrol()),\n h.script(src=\"/static/lib/tablefilter/tablefilter.js\"),\n h.script(src=\"/static/lib/FileSaver.min.js\"),\n ),\n body(\n Header(title, cont.end if cont else None),\n Menu(),\n div(cls=\"message-alerts\"),\n div(*bodyData, cls=cls),\n Footer()\n )\n )\n\n\nclass Card(UIElement):\n def __init__(self, title, contents, link=None, cls=None, delete=None, reply=None, rejudge=None, edit=None):\n if cls == None:\n cls = \"card\"\n else:\n cls += \" card\"\n deleteLink = \"\"\n if delete:\n deleteLink = div(h.i(\"clear\", cls=\"material-icons\"), cls=\"delete-link\", onclick=delete)\n elif reply:\n deleteLink = div(h.button(\"Reply\", cls=\"btn btn-primary\", onclick=reply), cls=\"delete-link\")\n if rejudge:\n deleteLink = div(h.button(\"Rejudge All\", cls=\"btn btn-primary\", onclick=rejudge), cls=\"delete-link\")\n\n # Add a pencil to the card if one is desired\n editLink = \"\"\n if edit:\n editLink = div(h.i(\"edit\", cls=\"material-icons\", onclick=edit), cls=\"delete-link\")\n \n self.html = h.div(cls=cls, contents=[\n div(cls=\"card-header\", contents=[\n h2(contents=[title], cls=\"card-title\"),\n deleteLink,\n editLink\n ]),\n div(cls=\"card-contents\", contents=contents)\n ])\n if link != None:\n self.html = div(a(href=link, cls=\"card-link\"), self.html, cls=\"card-link-box\")\n\n\nclass Modal(UIElement):\n def __init__(self, title, body, footer, modalID=\"\"):\n '''\n modalID - used to uniquely identify different modals. Only necessary when\n two or more modals are present on page\n '''\n # taken from https://getbootstrap.com/docs/4.1/components/modal/\n self.html = div(cls=f\"modal {modalID}\", role=\"dialog\", contents=[\n div(cls=\"modal-dialog\", role=\"document\", contents=[\n div(cls=\"modal-content\", contents=[\n div(cls=\"modal-header\", contents=[\n h.h5(title, cls=\"modal-title\"),\n h.button(**{\"type\": \"button\", \"class\": \"close\", \"data-dismiss\": \"modal\", \"arial-label\": \"close\"}, contents=[\n h.span(\"×\", **{\"aria-hidden\": \"true\"})\n ])\n ]),\n div(body, cls=\"modal-body\"),\n div(footer, cls=\"modal-footer\")\n ])\n ])\n ])\n","sub_path":"opencontest/contest/pages/lib/page.py","file_name":"page.py","file_ext":"py","file_size_in_byte":6450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"62169394","text":"\n\nfrom xai.brain.wordbase.nouns._cervix import _CERVIX\n\n#calss header\nclass _CERVICES(_CERVIX, ):\n\tdef __init__(self,): \n\t\t_CERVIX.__init__(self)\n\t\tself.name = \"CERVICES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"cervix\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_cervices.py","file_name":"_cervices.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"216239946","text":"import tensorflow as tf\nimport matplotlib.pyplot as plt\n\nfrom src.simple_bitcoin_predictor import SimpleBitcoinPredictor, run_epoch, test_model\nfrom src.util.util import get_reduced_data\n\nsample_size = 24 * 30\nbatch_size = 2000\nnum_classes = 3\nnum_features = 3\n\nx, y, data = get_reduced_data(num_classes, 60)\ncutoff = round(len(x) * 0.8) # 80% training and 20% test data\nx_train = x[:cutoff]\ny_train = y[:cutoff]\nx_test = x[cutoff:]\ny_test = y[cutoff:]\n\nmodel = SimpleBitcoinPredictor(num_features, num_classes)\n\n# Training: adjust the model so that its loss is minimized\nminimize_operation = tf.train.RMSPropOptimizer(0.01).minimize(model.loss)\n\nsaver = tf.train.Saver()\n\nacc = []\n# Create session for running TensorFlow operations\nwith tf.Session() as session:\n # Initialize tf.Variable objects\n session.run(tf.global_variables_initializer())\n\n for epoch in range(100):\n run_epoch(session, model, minimize_operation, batch_size, sample_size, x_train, y_train, epoch)\n save_path = saver.save(session, \"../resources/tmp/lstm-model-reduced-1hour.ckpt\")\n acc.append(test_model(saver, session, model, sample_size, x_test, y_test, save_path, 1)[0])\n\n session.close()\n\nplt.plot(acc)\nplt.title(\"LSTM accuracy (1 hour reduced dataset)\")\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Accuracy\")\nplt.show()\n","sub_path":"src/test_model_reduced.py","file_name":"test_model_reduced.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"330324821","text":"from django.shortcuts import render, redirect\nfrom django.db.models import Q\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse, FileResponse\nfrom django.urls import reverse_lazy\nfrom django.views.generic import CreateView, UpdateView, ListView, DeleteView, DetailView\nimport json as simplejson\nfrom PyPDF2 import PdfFileWriter, PdfFileReader\nimport io, urllib.request\nfrom datetime import datetime, date, timedelta\nfrom reportlab.pdfgen import canvas\nfrom reportlab.lib.pagesizes import letter\nfrom django.views.generic.edit import FormMixin\nfrom django.core import serializers\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom django.forms.models import model_to_dict\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.contrib.auth.mixins import PermissionRequiredMixin, LoginRequiredMixin\nfrom apps.solicitud.forms import SolicitudForm, SolicitudEvaluarForm, SolicitudForm2, PracticaForm\nfrom apps.solicitud.models import Solicitud, Status, Practica\nfrom apps.inventario.models import Categoria, Equipo\nfrom apps.inventario.forms import EquipoForm\nfrom apps.incidencia.models import Incidencia\nfrom apps.incidencia.forms import IncidenciaForm\nfrom apps.usuario.models import Profile\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import permission_required, login_required\nfrom django import forms\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.utils.translation import activate\n# Create your views here.\n\n#Regresa el objeto/tupla de tipo usuario con ese codigo, guardado previamente en una sesion al loggearse\ndef getUsuario(request):\n current_user = request.user\n return current_user\n\ndef ligarEquipo(ids,s):\n equipo = Equipo.objects.filter(codigo__in=ids)\n for e in equipo:\n s.equipo.add(e)\n s.save()\n\ndef desligarEquipo(s):\n s.equipo.clear()\n s.save()\n\ndef ver_solicitudes(request):\n fecha = request.GET.get('fecha', None)\n try:\n solicitudes = Solicitud.objects.filter((Q(estatus=2)) & Q(fecha_requerida=fecha))\n except:\n solicitudes = None\n html = serializers.serialize(\"json\",solicitudes)\n return HttpResponse(html)\n\ndef equipo_disponible(request):\n categoria = request.GET.get('categoria',None)\n fecha = request.GET.get('fecha',None)\n hora_inicio = int(request.GET.get('hora_inicio',None).split(':')[0])\n hora_fin = int(request.GET.get('hora_fin',None).split(':')[0])\n equipo_d = list() # equipo disponible a prestamo, es decir todo aquel en estado de activo\n equipo_p = list() # equipo prestado, ya en solicitudes\n horas1 = list(range(hora_inicio, hora_fin + 1))\n try:\n sol = Solicitud.objects.filter((Q(estatus=1) | Q(estatus=2)) & Q(fecha_requerida=fecha)) #para validar si existen solicitudes con esa fecha\n\n except:\n sol = None\n if sol: #Si ya hay solicitudes con esa fecha\n for s in sol:\n cont=0\n i = str(s.hora_inicio) #Horas de inicio y fin de cada solicitud ya existente, se hace una lista con ese rango\n f = str(s.hora_fin)\n i = int(i.split(':')[0])\n f = int(f.split(':')[0])\n horas2 = list(range(i,f+1)) #lista de horas\n for h in horas1:\n cont += horas2.count(h) #Checa si hay mas 2 de horas en el rango de la solicitud previa\n if cont>1:\n equipo_p.extend(s.equipo.all()) #Mete el equipo de esa solicitud a equipo prestado\n #Aqui termina la comprobacion de equipo prestado\n # y solo prestara en caso de que haya disponible del restante\n c = Categoria.objects.get(id=categoria)\n nombre = c.nombre #Nombre de la categoria\n equipo_cat = c.equipo_set.filter(estatus=True) #Saca todo el equipo de esa categoria que este disponible\n #guarda el equipo real, osea, el equipo total menos el equipo ya prestado\n #este metodo se llama list comprehension\n equipo_d = [e for e in equipo_cat if e not in equipo_p]\n\n else: #Si no hay solicitudes en esa fecha, presta de manera normal con todo el inventario posible\n c = Categoria.objects.get(id=categoria)\n nombre = c.nombre #Nombre de la categoria\n equipo_d = c.equipo_set.filter(estatus=True) #Saca todo el equipo de esa categoria que este disponible\n\n #html = [model_to_dict(x) for x in equipo_d]\n #return HttpResponse(simplejson.dumps(equipo_d, cls=DjangoJSONEncoder))\n for v in equipo_d:\n if v.imagen:\n v.imagen = v.imagen.url\n html = serializers.serialize(\"json\",equipo_d)\n return HttpResponse(html)\n\n#Metodo para crear una solicitud, aqui en vez de usar una vista basada en clase (CreateView) use una funcion\n#debido a que se requeria personalizar bastante lo que iba a hacer\n@login_required(login_url='/usuario/login/')\ndef SolicitudCrear(request):\n if request.user.has_perm('Solicitud.reservar_clase'):\n form = SolicitudForm() #Se guarda el formulario\n else:\n form = SolicitudForm2() #Se guarda el formulario\n\n cat = Categoria.objects.all() #Se guardan todos los objetos de la tabla Categoria\n npracticas = Practica.objects.all()\n contexto = {'form':form,'cat':cat, 'npracticas':npracticas} #Ambos forman el contexto, lo que se enviara al html para su posterior uso\n if request.method == 'POST': #si es post (se pico submit)\n ids = request.POST.getlist('lstBox2')\n ids = list(map(int,ids))\n form = SolicitudForm(request.POST) # Se rellena la form con los datos de ese post\n\n if form.is_valid():\n datos = form.cleaned_data # Se limpian los datos del form, para que queden listos a guardarse\n try:\n form.clean_date()\n form.clean_time()\n except forms.ValidationError as VE:\n messages.error(request, str(VE))\n return render(request,'solicitud/solicitud_form.html',{'c':contexto})\n #si se pide con menos de dos horas de anticipacion\n dos_horas_mas = datetime.now() + timedelta(hours=2)\n if datos.get('fecha_requerida') == date.today() and datos.get('hora_inicio') <= dos_horas_mas.time():\n messages.warning(request, 'Advertencia: procure realizar sus solicitudes con 2 o más horas de anticipación.')\n\n usuario = getUsuario(request) # se obtiene el usuario\n s = Solicitud() # Se crea un modelo de Solicitud\n s.create(datos, usuario) # sobreescritura del metood crear del modelo\n s.save() # Se guarda el modelo\n ligarEquipo(ids,s) # Una vez guardado, como ya se tiene el id, se ligan en la tabla de union la solicitud\n # con el equipo (solicitud_equipo)\n\n msg2 = '''

¡Hola '''+ \\\n str(request.user.first_name) +' '+ str(request.user.last_name)+ \\\n '''!


Haz generado una nueva solicitud de reservacion para el laboratorio de equipos electro-ópticos.\n


Los datos de tu solicitud son los siguientes:

Fecha de la reservación: '''\\\n +str(datos.get('fecha_requerida'))+'

hora de inicio: '+ str(datos.get('hora_inicio'))+\\\n '

hora de fin: '+str(datos.get('hora_fin'))+'''

\n Este mensaje es una notificación y no requiere de respuesta.

'''\n msg = 'Se generó una nueva solicitud con fecha: ' + str(datos.get('fecha_requerida')) +\\\n ' en el horario:' + str(datos.get('hora_inicio')) + ' - ' + str(datos.get('hora_fin'))\n asunto = 'SGL-CUCEI Nueva solicitud'\n\n email = EmailMultiAlternatives(\n asunto,\n msg,\n settings.EMAIL_HOST_USER,\n [request.user.email]\n )\n email.attach_alternative(msg2, \"text/html\")\n print(\"ENVIANDO CORREO\")\n #email.send()\n print(\"se envio correo\")\n return redirect('solicitud:solicitud_milista')\n else:\n return HttpResponse(\"Error\")\n\n\n return render(request,'solicitud/solicitud_form.html',{'c':contexto})\n\nclass SolicitudListar(PermissionRequiredMixin, ListView): #Muestra todas las solicitudes\n permission_required = 'solicitud.evaluar_solicitud'\n model = Solicitud\n template_name = 'solicitud/solicitud_listar.html'\n def get_queryset(self):\n search = self.request.GET.get('search','0')\n if search == '':\n search = '2'\n if search == '0':\n queryset = Solicitud.objects.all()\n else:\n queryset = Solicitud.objects.filter(estatus = search)\n return queryset\n\n def get_context_data(self, *, object_list=None, **kwargs):\n context = super(SolicitudListar, self).get_context_data(**kwargs)\n context['search'] = self.request.GET.get('filter','')\n return context\n\nclass SolicitudMiLista(LoginRequiredMixin, ListView): #Muestra todas las solicitudes\n login_url = '/usuario/login/'\n redirect_field_name = 'redirect_to'#????\n model = Solicitud\n template_name = 'solicitud/solicitud_milista.html'\n\n def get_context_data(self, *, object_list=None, **kwargs):\n context = super(SolicitudMiLista, self).get_context_data(**kwargs)\n context['search'] = self.request.GET.get('filter','')\n return context\n\n def get_queryset(self):\n search = self.request.GET.get('search','0')\n if search == '':\n search = '2'\n edit_status = Status.objects.get(id=4)\n pend_status = Status.objects.get(id=1)\n sol_editar = Solicitud.objects.filter(usuario_id = self.request.user.id, estatus=edit_status)\n queryset = Solicitud.objects.filter(usuario_id = self.request.user.id)\n if search != '0':\n queryset = queryset.filter(estatus = search)\n\n for item in sol_editar:\n item.estatus = pend_status\n item.save()\n return queryset\n\n#COMPROBAR QUE SOLO PUEDA ELIMINAR SUS PROPIAS SOLICITUDES\nclass SolicitudEliminar(LoginRequiredMixin, DeleteView):\n login_url = '/usuario/login/'\n redirect_field_name = 'redirect_to'#????\n model = Solicitud\n template_name = 'solicitud/solicitud_eliminar.html'\n success_url = reverse_lazy('solicitud:solicitud_milista')\n\nclass SolicitudDetalle(LoginRequiredMixin, DetailView):\n login_url = '/usuario/login/'\n redirect_field_name = 'redirect_to'#????\n model = Solicitud\n template_name = 'solicitud/misolicitud_detalle.html'\n\nclass SolicitudEvaluar(LoginRequiredMixin, FormMixin , DetailView):\n login_url = '/usuario/login/'\n redirect_field_name = 'redirect_to'#????\n model = Solicitud\n template_name = 'solicitud/solicitud_detalle_evalua.html'\n form_class = SolicitudEvaluarForm\n def get_success_url(self):\n return reverse_lazy('solicitud:solicitud_listar')\n\n def get_context_data(self, **kwargs):\n context = super(SolicitudEvaluar, self).get_context_data(**kwargs)\n context['form'] = SolicitudEvaluarForm(initial={'post': self.object, 'observaciones':self.object.observaciones})\n return context\n\nclass PracticaCrear(PermissionRequiredMixin, CreateView):\n permission_required = 'solicitud.evaluar_solicitud'\n model = Practica\n template_name = 'solicitud/registro_practica.html'\n form_class = PracticaForm\n success_url = reverse_lazy('solicitud:practica_listar')\n\nclass PracticaListar(PermissionRequiredMixin, ListView):\n permission_required = 'solicitud.evaluar_solicitud'\n model = Practica\n template_name = 'solicitud/listar_practica.html'\n\nclass PracticaEditar(PermissionRequiredMixin, UpdateView):\n permission_required = 'solicitud.evaluar_solicitud'\n model = Practica\n template_name = 'solicitud/registro_practica.html'\n form_class = PracticaForm\n success_url = reverse_lazy('solicitud:practica_listar')\n\nclass PracticaEliminar(PermissionRequiredMixin, DeleteView): #borra el registro al dar el sumbit\n permission_required = 'solicitud.evaluar_solicitud'\n model = Practica\n template_name = 'solicitud/practica_eliminar.html'\n success_url = reverse_lazy('solicitud:practica_listar')\n\ndef SolicitudDecidir(request, id_solicitud, id_estatus):\n solicitud = Solicitud.objects.get(id=id_solicitud)\n form = SolicitudEvaluarForm(request.POST, instance=solicitud)\n if form.is_valid():\n solicitud=form.save(commit=False)\n solicitud.estatus_id = id_estatus\n solicitud.save()\n return redirect('solicitud:solicitud_listar')\n\ndef traducirMes(request,mes):\n if (mes==\"January\"):\n return \"Enero\"\n if(mes==\"February\"):\n return \"Febrero\"\n if (mes==\"March\"):\n return \"Marzo\"\n if(mes==\"April\"):\n return \"Abril\"\n if (mes==\"May\"):\n return \"Mayo\"\n if(mes==\"June\"):\n return \"Junio\"\n if (mes==\"July\"):\n return \"Julio\"\n if(mes==\"August\"):\n return \"Agosto\"\n if (mes==\"September\"):\n return \"Septiembre\"\n if(mes==\"October\"):\n return \"Octubre\"\n if (mes==\"November\"):\n return \"Noviembre\"\n else:\n return \"Diciembre\"\n\ndef generarPdf(request, id_solicitud):\n activate(\"es\")\n packet = io.BytesIO()\n solicitud = Solicitud.objects.get(id=id_solicitud)\n user = Profile.objects.get(user_id=solicitud.usuario.id)\n fecha = datetime.now()\n print(fecha)\n #Crear nuevo pdf con ReportLab\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=\"Solicitud.pdf\"'\n url = 'https://res.cloudinary.com/aldocloudimage/image/upload/v1536350562/pdfs/Formato_Prestamo.pdf'\n #url = settings.URL_PDF_SOLICITUD\n can = canvas.Canvas(packet,pagesize=letter)\n count = 1\n for e in solicitud.equipo.all():\n can.drawString(60,505-(count*10),str(e.codigo))\n can.drawString(160,505-(count*10),e.descripcion)\n count+=1\n can.drawString(105,628,solicitud.usuario.first_name +\" \" +solicitud.usuario.last_name)\n can.drawString(105,607,str(user.codigo))\n can.drawString(157,585,str(solicitud.hora_inicio))\n can.drawString(297,585,str(solicitud.hora_fin))\n can.drawString(377,585,solicitud.uso)\n can.drawString(60,285,solicitud.observaciones)\n can.drawString(250,65,str(fecha.day))\n mes = str(fecha.strftime(\"%B\"))\n mes = traducirMes(request,mes)\n can.drawString(290, 65, mes)\n can.drawString(445,65,str(fecha.year))\n can.save()\n #moverse al inicio del buffer de entrada-salida\n packet.seek(0)\n nuevo_pdf = PdfFileReader(packet)\n #leer el pdf ya existente (template)\n #template = PdfFileReader(open(\"Formato_Prestamo.pdf\",\"rb\"))\n templateUrl = urllib.request.urlopen(url).read()\n packetUrl = io.BytesIO(templateUrl)\n template = PdfFileReader(packetUrl)\n salida = PdfFileWriter()\n #Añadir la marca de agua (que es el pdf nuevo) al template\n page = template.getPage(0)\n page.mergePage(nuevo_pdf.getPage(0))\n salida.addPage(page)\n #finalmente escribimos la \"salida\" a un archivo real\n #archivo = open(\"Prototipo.pdf\",\"wb\")\n #salida.write(archivo)\n #archivo.close()\n salida.write(response)\n #response.write(salida)\n return response\n #return redirect('solicitud:solicitud_milista')\n\ndef SolicitudEditar(request,id_solicitud):\n solicitud = Solicitud.objects.get(id=id_solicitud)\n solicitud.estatus = Status.objects.get(id=4)\n solicitud.save()\n cat = Categoria.objects.all()\n contexto = dict\n solicitud.fecha_requerida = str(solicitud.fecha_requerida)\n if request.method == 'GET':\n form = SolicitudForm(instance=solicitud)\n contexto = {'form': form, 'cat': cat, 'sol':solicitud}\n else:\n ids = request.POST.getlist('lstBox2')\n ids = list(map(int, ids))\n form = SolicitudForm(request.POST)\n if form.is_valid():\n datos = form.cleaned_data\n solicitud.fecha_requerida = datos.get('fecha_requerida')\n solicitud.hora_inicio = datos.get('hora_inicio')\n solicitud.hora_fin = datos.get('hora_fin')\n desligarEquipo(solicitud)\n ligarEquipo(ids,solicitud)\n solicitud.estatus = Status.objects.get(id=1)\n solicitud.save()\n return redirect('solicitud:solicitud_milista')\n else:\n return HttpResponse(\"Error\")\n return render(request,'solicitud/solicitud_editar.html',{'c':contexto})\n\n@permission_required('solicitud.evaluar_solicitud')\ndef SolicitudIncidencia(request,pk,cod):\n form = IncidenciaForm()\n form2 = EquipoForm()\n solicitud = Solicitud.objects.get(id=pk)\n equipo = Equipo.objects.get(codigo=cod)\n contexto = {'solicitud':solicitud,'equipo':equipo}\n if request.method == 'POST':\n form = IncidenciaForm(request.POST)\n form2 = EquipoForm(request.POST)\n if form.is_valid():\n datos = form.cleaned_data\n equipo.estatus = form2['estatus'].value()\n i = Incidencia()\n i.create(datos,solicitud,equipo)\n i.save()\n return redirect('solicitud:solicitud_detalle', pk=pk)\n return render(request,'incidencia/incidencia_form.html',{'form':form,'form2':form2,'c':contexto})\n","sub_path":"apps/solicitud/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":17502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"568195727","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\ncopy from vnpy:2 which build ctp only\n\"\"\"\n\nimport ast\nimport platform\nimport re\nimport sys\n\nfrom setuptools import Extension, find_packages, setup\n\nwith open(\"ctp/__init__.py\", \"rb\") as f:\n version_line = re.search(\n r\"__version__\\s+=\\s+(.*)\", f.read().decode(\"utf-8\")\n ).group(1)\n version = str(ast.literal_eval(version_line))\n\nif platform.uname().system == \"Windows\":\n compiler_flags = [\n \"/MP\", \"/std:c++17\", # standard\n \"/O2\", \"/Ob2\", \"/Oi\", \"/Ot\", \"/Oy\", \"/GL\", # Optimization\n \"/wd4819\" # 936 code page\n ]\n extra_link_args = []\nelse:\n compiler_flags = [\n \"-std=c++17\", # standard\n \"-O3\", # Optimization\n \"-Wno-delete-incomplete\", \"-Wno-sign-compare\",\n ]\n extra_link_args = [\"-lstdc++\"]\n\nvnctpmd = Extension(\n \"ctp.vnctpmd\",\n [\n \"ctp/vnctp/vnctpmd/vnctpmd.cpp\",\n ],\n include_dirs=[\"ctp/include\",\n \"ctp/vnctp\", ],\n define_macros=[],\n undef_macros=[],\n library_dirs=[\"ctp/libs\", \"ctp\"],\n libraries=[\"thostmduserapi_se\", \"thosttraderapi_se\", ],\n extra_compile_args=compiler_flags,\n extra_link_args=extra_link_args,\n depends=[],\n runtime_library_dirs=[\"$ORIGIN\"],\n language=\"cpp\",\n)\nvnctptd = Extension(\n \"ctp.vnctptd\",\n [\n \"ctp/vnctp/vnctptd/vnctptd.cpp\",\n ],\n include_dirs=[\"ctp/include\",\n \"ctp/vnctp\", ],\n define_macros=[],\n undef_macros=[],\n library_dirs=[\"ctp/libs\", \"ctp\"],\n libraries=[\"thostmduserapi_se\", \"thosttraderapi_se\", ],\n extra_compile_args=compiler_flags,\n extra_link_args=extra_link_args,\n runtime_library_dirs=[\"$ORIGIN\"],\n depends=[],\n language=\"cpp\",\n)\n\nif platform.system() == \"Windows\":\n # use pre-built pyd for windows ( support python 3.7 only )\n ext_modules = []\nelif platform.system() == \"Darwin\":\n ext_modules = []\nelse:\n ext_modules = [vnctptd, vnctpmd]\n\npkgs = find_packages()\n\ninstall_requires = [\n]\n\nsetup(\n name=\"vnctp\",\n version=version,\n author=\"vn.py team\",\n author_email=\"vn.py@foxmail.com\",\n license=\"MIT\",\n url=\"https://www.vnpy.com\",\n description=\"A framework for developing quant trading systems.\",\n long_description=__doc__,\n keywords='quant quantitative investment trading algotrading',\n include_package_data=True,\n packages=pkgs,\n package_data={\"\": [\n \"*.ico\",\n \"*.ini\",\n \"*.dll\",\n \"*.so\",\n \"*.pyd\",\n ]},\n install_requires=install_requires,\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Operating System :: Microsoft :: Windows :: Windows 7\",\n \"Operating System :: Microsoft :: Windows :: Windows 8\",\n \"Operating System :: Microsoft :: Windows :: Windows 10\",\n \"Operating System :: Microsoft :: Windows :: Windows Server 2008\",\n \"Operating System :: Microsoft :: Windows :: Windows Server 2012\",\n \"Operating System :: Microsoft :: Windows :: Windows Server 2012\",\n \"Operating System :: POSIX :: Linux\"\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.6\",\n \"Topic :: Office/Business :: Financial :: Investment\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n \"License :: OSI Approved :: MIT License\",\n \"Natural Language :: Chinese (Simplified)\",\n \"Natural Language :: Chinese (Simplified)\"\n ],\n ext_modules=ext_modules\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"420126864","text":"import csv\ndef Sku_Clean(arquivo):\n # Abrir arquivo base para calcular as medianas\n f = open(arquivo, encoding='UTF-8')\n\n # Criar lists a partir do arquivo aberto.\n Sku = []\n\n reader = csv.reader(f, delimiter=',')\n for row in reader:\n Sku.append(row[0])\n f.close()\n del Sku[0]\n SkuClean = list(set(Sku))\n return SkuClean","sub_path":"untitled/venv/LendoCSV/Sku_Clean.py","file_name":"Sku_Clean.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"594808236","text":"# -*- coding:utf-8 -*-\nfrom mininet.cli import CLI\nfrom mininet.net import Mininet\nfrom mininet.node import RemoteController\nfrom mininet.link import TCLink\n\nif '__main__' == __name__:\n\t# 宣告 Mininet 使用的 Controller 種類\n net = Mininet(controller=RemoteController)\n\t\n\t# 指定 Controller 的 IP 及 Port,進行初始化\n c0 = net.addController('c0',ip='127.0.0.1', port=6633)\n\t\n\t# 加入 Switch\n s1 = net.addSwitch('s1')\n s2 = net.addSwitch('s2')\n s3 = net.addSwitch('s3')\n s4 = net.addSwitch('s4')\n s5 = net.addSwitch('s5')\n\t\n\t# 加入主機,並指定 MAC,ip\n h1 = net.addHost('h1', mac='00:00:00:00:00:01', ip='10.0.0.1')\n h2 = net.addHost('h2', mac='00:00:00:00:00:02', ip='10.0.0.2')\n\t\n\t# 建立連線\n net.addLink(s1, h1)\n net.addLink(s5, h2)\n\n # 建立連線並設定延遲\n net.addLink(s1, s2,cls=TCLink, delay=\"10ms\")\n net.addLink(s1, s3,cls=TCLink, delay=\"50ms\")\n net.addLink(s2, s4,cls=TCLink, delay=\"20ms\")\n net.addLink(s3, s5,cls=TCLink, delay=\"40ms\")\n net.addLink(s4, s5,cls=TCLink, delay=\"30ms\")\n\n\n # 建立 Mininet\n net.build()\n\t\n # 啟動 Controller\n c0.start()\n\t\n # 啟動 Switch,並指定連結的 Controller 為 c0\n s1.start([c0])\n s2.start([c0])\n s3.start([c0])\n s4.start([c0])\n s5.start([c0])\n\n\n\n # 執行互動介面(mininet>...)\n CLI(net)\n\t# 互動介面停止後,則結束 Mininet\n net.stop()","sub_path":"7.ryu_shortestPath/topoShortestPath.py","file_name":"topoShortestPath.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"611637121","text":"from MDP import MDP\nimport pdb\n\n\n# Problem Paramters\nN = 5 # Number of parcking spots\np = 0.05 # Probability of transitioning to a free parking spot\nCg = 4 # Cost of parking to the garage\n\n# Initialize mdp object\nprintLevel = 2\nmdp = MDP(N, p, Cg, printLevel)\n\n# Build transition probability\nmdp.buildTransitionMatrices()\n\n# # Compute the matrices for the closed-loop system given the threshold of the optimal policy = N\nPpi, Cpi = mdp.computePolicy(iThreshold = 3)\n\n# # Evaluate the policy for Ppi and Cpi\nmdp.policyEvaluation(Ppi, Cpi)\n\n# # Perform value iteration to compute the optimal value function\nmdp.valueIteration()\n\n# # # Perform policy iteration to compute the optimal value function\nmdp.policyIteration()\n","sub_path":"HW1/hw_1/problem_1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"348482432","text":"\nimport sys\n\nimport tensorflow as tf\n\nimport utility\n\nsys.path.append(\"src\")\nimport model\n\ndef model_or_sample(batch_size):\n\n return sample_sequence(hparams=utility.get_hparams(),\n length=utility.SAMPLE_LENGTH,\n start_token=utility.get_start_token()[0],\n batch_size=batch_size)\n\ndef sample_sequence(*, hparams, length, start_token=None, batch_size=None, context=None, temperature=1, top_k=0):\n\n context = utility.check_start_context(start_token, context, batch_size)\n\n with tf.name_scope('sample_sequence'):\n\n pastshape = model.past_shape(hparams=hparams, batch_size=batch_size)\n\n def body(past, output, tknprbs, loggies):\n\n # I still don't understand why this line is necessary\n xtok = output[:, -1]\n\n presents, logits = model.upmodel(hparams=hparams, X=xtok[:, tf.newaxis], past=past, reuse=tf.AUTO_REUSE)\n presents.set_shape(pastshape)\n\n logits = logits[:, -1, :hparams.n_vocab] / tf.to_float(temperature)\n logits = utility.top_k_logits(logits, k=top_k)\n samples = tf.multinomial(logits, num_samples=1, output_dtype=tf.int32, seed=1000)\n\n # This is the full prob distribution\n probs = tf.reshape(logits, (batch_size, hparams.n_vocab))\n probs = tf.nn.softmax(probs, axis=1)\n justidx = tf.reshape(samples, shape=(batch_size, )) \n tknprb = tf.gather(probs, justidx, axis=1)\n tknprb = tf.reshape(tf.linalg.diag_part(tknprb), (batch_size, 1))\n\n return [\n tf.concat([past, presents], axis=-2),\n tf.concat([output, samples], axis=1),\n tf.concat([tknprbs, tknprb], axis=1),\n tf.concat([loggies, tf.reshape(logits, shape=(batch_size, hparams.n_vocab, 1))], axis=2) \n ]\n\n def cond(*args):\n return True\n\n history, _ = model.upmodel(hparams=hparams, X=context[:, :-1], past=None, reuse=tf.AUTO_REUSE)\n history.set_shape(pastshape)\n\n loggies = tf.fill([batch_size, hparams.n_vocab, 1], -1.5655)\n tknprbs = tf.fill([batch_size, 1], -1.513)\n\n result = tf.while_loop(\n cond=cond, body=body,\n maximum_iterations=length,\n loop_vars=[\n history,\n context,\n tknprbs,\n loggies\n ],\n shape_invariants=[\n tf.TensorShape(pastshape),\n tf.TensorShape([batch_size, None]),\n tf.TensorShape([batch_size, None]), \n tf.TensorShape([batch_size, hparams.n_vocab, None])\n ],\n back_prop=False\n )\n\n return result\n","sub_path":"newsrc/augmented.py","file_name":"augmented.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"383093035","text":"def chain_operator(current):\n if current % 2 == 0:\n return current / 2\n else:\n return current * 3 + 1\n\n\ndef chain_gen(start):\n current = start\n while current != 1:\n yield current\n current = chain_operator(current)\n yield 1\n\nanswer = 0\nlongest_length = 0\n\nfor x in range(1, 1000000):\n length = len(list(chain_gen(x)))\n print(x, length)\n if length > longest_length:\n longest_length = length\n answer = x\n\nprint(answer)\n","sub_path":"Problems 001 - 050/Problem 014.py","file_name":"Problem 014.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"571156243","text":"# SPDX-License-Identifier: MIT\n# Copyright (c) 2019 Intel Corporation\n\"\"\"\nCommand line interface evaluates packages given their source URLs\n\"\"\"\nimport os\nimport sys\nimport pdb\nimport json\nimport pathlib\nimport asyncio\nimport logging\nimport inspect\nimport argparse\nimport contextlib\nimport pkg_resources\nfrom typing import List\n\nfrom ..version import VERSION\nfrom ..base import BaseConfig\nfrom ..repo import Repo\nfrom ..port import Port\nfrom ..feature import Feature, Features, Data\nfrom ..source.source import BaseSource, Sources, SubsetSources\nfrom ..model import Model\nfrom ..config.config import BaseConfigLoader\nfrom ..config.json import JSONConfigLoader\nfrom ..df.types import Input, Operation, DataFlow\nfrom ..df.base import StringInputSetContext\nfrom ..df.memory import MemoryInputSet, MemoryInputSetConfig\nfrom ..util.entrypoint import load\nfrom ..util.data import merge\nfrom ..util.cli.arg import Arg\nfrom ..util.cli.cmd import CMD\nfrom ..util.cli.cmds import (\n SourcesCMD,\n FeaturesCMD,\n ModelCMD,\n PortCMD,\n KeysCMD,\n ListEntrypoint,\n)\n\nfrom .dataflow import Dataflow\nfrom .config import Config\n\n\nclass Version(CMD):\n \"\"\"\n Print version and installed dffml packages\n \"\"\"\n\n async def run(self):\n self.logger.debug(\"Reporting version\")\n devmode = False\n for syspath in map(pathlib.Path, sys.path):\n if (syspath / \"dffml.egg-link\").is_file():\n devmode = True\n print(f\"dffml version {VERSION} (devmode: {str(devmode).lower()})\")\n\n\nclass Edit(SourcesCMD, KeysCMD):\n \"\"\"\n Edit each specified repo\n \"\"\"\n\n async def run(self):\n async with self.sources as sources:\n async with sources() as sctx:\n for key in self.keys:\n repo = await sctx.repo(key)\n pdb.set_trace()\n await sctx.update(repo)\n\n\nclass ListRepos(SourcesCMD):\n \"\"\"\n List repos stored in sources\n \"\"\"\n\n async def run(self):\n async with self.sources as sources:\n async with sources() as sctx:\n async for repo in sctx.repos():\n print(repo)\n\n\nclass ListFeatures(ListEntrypoint):\n \"\"\"\n List installed features\n \"\"\"\n\n ENTRYPOINT = Feature\n\n def display(self, cls):\n if not cls.__doc__ is None:\n print(\"%s(%s):\" % (cls.NAME, cls.__qualname__))\n print(cls.__doc__.rstrip())\n else:\n print(\"%s(%s)\" % (cls.NAME, cls.__qualname__))\n print()\n\n\nclass ListServices(ListEntrypoint):\n \"\"\"\n List installed services\n \"\"\"\n\n async def run(self):\n for i in pkg_resources.iter_entry_points(\"dffml.service.cli\"):\n loaded = i.load()\n if issubclass(loaded, CMD):\n self.display(loaded)\n\n\nclass ListSources(ListEntrypoint):\n \"\"\"\n List installed sources\n \"\"\"\n\n ENTRYPOINT = BaseSource\n\n\nclass ListModels(ListEntrypoint):\n \"\"\"\n List installed models\n \"\"\"\n\n ENTRYPOINT = Model\n\n\nclass ListPorts(ListEntrypoint):\n \"\"\"\n List installed ports\n \"\"\"\n\n ENTRYPOINT = Port\n\n\nclass List(CMD):\n \"\"\"\n List repos and installed interfaces\n \"\"\"\n\n repos = ListRepos\n features = ListFeatures\n sources = ListSources\n models = ListModels\n services = ListServices\n ports = ListPorts\n\n\nclass Applicable(FeaturesCMD):\n\n arg_key = Arg(\n \"-key\",\n help=\"Check if features is applicable for this key\",\n required=True,\n )\n\n async def run(self):\n async with self.features as features:\n return await features.applicable(Data(self.key))\n\n\nclass Merge(CMD):\n \"\"\"\n Merge repo data between sources\n \"\"\"\n\n arg_dest = Arg(\n \"dest\", help=\"Sources merge repos into\", type=BaseSource.load_labeled\n )\n arg_src = Arg(\n \"src\", help=\"Sources to pull repos from\", type=BaseSource.load_labeled\n )\n\n async def run(self):\n async with self.src.withconfig(\n self.extra_config\n ) as src, self.dest.withconfig(self.extra_config) as dest:\n async with src() as sctx, dest() as dctx:\n async for src in sctx.repos():\n repo = Repo(src.src_url)\n repo.merge(src)\n repo.merge(await dctx.repo(repo.src_url))\n await dctx.update(repo)\n\n\nclass EvaluateCMD(FeaturesCMD, SourcesCMD):\n\n arg_sources = SourcesCMD.arg_sources.modify(required=False)\n arg_caching = Arg(\n \"-caching\",\n help=\"Re-evaluate or use last\",\n required=False,\n default=False,\n action=\"store_true\",\n )\n arg_parallel = Arg(\n \"-parallel\",\n help=\"Evaluate in parallel\",\n required=False,\n default=1,\n type=int,\n )\n arg_cacheless = Arg(\n \"-cacheless\",\n help=\"Do not re-evaluate if these features are missing\",\n required=False,\n default=[],\n nargs=\"+\",\n )\n\n\nclass EvaluateAll(EvaluateCMD):\n \"\"\"Evaluate all repos in sources\"\"\"\n\n arg_update = Arg(\n \"-update\",\n help=\"Update repo with sources\",\n required=False,\n default=False,\n action=\"store_true\",\n )\n\n async def evaluate(self, sources, features):\n async with sources() as sctx:\n async for repo in features.evaluate_repos(\n sctx.repos(),\n features=[\n name\n for name in features.names()\n if not name in self.cacheless\n ],\n num_workers=self.parallel,\n caching=self.caching,\n ):\n yield repo\n if self.update:\n await sctx.update(repo)\n\n async def run(self):\n async with self.sources as sources, self.features as features:\n async for repo in self.evaluate(sources, features):\n yield repo\n\n\nclass EvaluateRepo(EvaluateAll, KeysCMD):\n \"\"\"Evaluate features on individual repos\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.sources = SubsetSources(*self.sources, keys=self.keys)\n\n\nclass Evaluate(CMD):\n \"\"\"Evaluate features against repos\"\"\"\n\n repo = EvaluateRepo\n _all = EvaluateAll\n\n\nclass MLCMD(ModelCMD, FeaturesCMD, SourcesCMD):\n \"\"\"\n Commands which use models share many similar arguments.\n \"\"\"\n\n\nclass Train(MLCMD):\n \"\"\"Train a model on data from given sources\"\"\"\n\n async def run(self):\n async with self.sources as sources, self.features as features, self.model as model:\n async with sources() as sctx, model(features) as mctx:\n return await mctx.train(sctx)\n\n\nclass Accuracy(MLCMD):\n \"\"\"Assess model accuracy on data from given sources\"\"\"\n\n async def run(self):\n async with self.sources as sources, self.features as features, self.model as model:\n async with sources() as sctx, model(features) as mctx:\n return float(await mctx.accuracy(sctx))\n\n\nclass PredictAll(EvaluateAll, MLCMD):\n \"\"\"Predicts for all sources\"\"\"\n\n async def predict(self, mctx, sctx, repos):\n async for repo in mctx.predict(repos):\n yield repo\n if self.update:\n await sctx.update(repo)\n\n async def run(self):\n async with self.sources as sources, self.features as features, self.model as model:\n async with sources() as sctx, model(features) as mctx:\n async for repo in self.predict(mctx, sctx, sctx.repos()):\n yield repo\n\n\nclass PredictRepo(PredictAll, EvaluateRepo):\n \"\"\"Predictions for individual repos\"\"\"\n\n\nclass Predict(CMD):\n \"\"\"Evaluate features against repos and produce a prediction\"\"\"\n\n repo = PredictRepo\n _all = PredictAll\n\n\nclass ImportExportCMD(PortCMD, SourcesCMD):\n \"\"\"Shared import export arguments\"\"\"\n\n arg_filename = Arg(\"filename\", type=str)\n\n\nclass Import(ImportExportCMD):\n \"\"\"Imports repos\"\"\"\n\n async def run(self):\n async with self.sources as sources:\n async with sources() as sctx:\n return await self.port.import_from_file(sctx, self.filename)\n\n\nclass Export(ImportExportCMD):\n \"\"\"Exports repos\"\"\"\n\n async def run(self):\n async with self.sources as sources:\n async with sources() as sctx:\n return await self.port.export_to_file(sctx, self.filename)\n\n\ndef services():\n \"\"\"\n Loads dffml.services.cli entrypoint and creates a CMD class incorporating\n all of the loaded CLI versions of services as subcommands.\n \"\"\"\n\n class Service(CMD):\n \"\"\"\n Expose various functionalities of dffml\n \"\"\"\n\n pass\n\n for i in pkg_resources.iter_entry_points(\"dffml.service.cli\"):\n loaded = i.load()\n if issubclass(loaded, CMD):\n setattr(Service, i.name, loaded)\n return Service\n\n\nclass CLI(CMD):\n \"\"\"\n CLI interface for dffml\n \"\"\"\n\n version = Version\n _list = List\n edit = Edit\n merge = Merge\n _import = Import\n export = Export\n train = Train\n accuracy = Accuracy\n predict = Predict\n evaluate = Evaluate\n service = services()\n applicable = Applicable\n dataflow = Dataflow\n config = Config\n","sub_path":"dffml/cli/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":9288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"237757899","text":"from flask import (render_template, url_for, flash,\n redirect, request, abort, Blueprint)\nfrom flask_login import current_user, login_required\nfrom journalshare import db\nfrom journalshare.models import Journal\nfrom journalshare.journals.forms import JournalForm\n\njournals = Blueprint('journals', __name__)\n\n@journals.route(\"/journal/new\", methods=['GET', 'POST'])\n@login_required\ndef new_journal():\n\tform = JournalForm()\n\tif form.validate_on_submit():\n\t\tif 'privacy_setting' in request.form:\n\t\t\tjournal = Journal(title=form.title.data, content=form.content.data, private=False if request.form['privacy_setting']=='public' else True, author=current_user)\n\t\t\tdb.session.add(journal)\n\t\t\tdb.session.commit()\n\t\t\tflash('Your journal entry has been created!', 'success')\n\t\t\treturn redirect(url_for('main.home'))\n\t\telse:\n\t\t\tflash('You must select a privacy setting for your journal entry!', 'danger')\n\t\t\treturn render_template('create_journal.html', title='New Journal Entry', form=form, legend='New Journal Entry')\n\treturn render_template('create_journal.html', title='New Journal Entry', form=form, legend='New Journal Entry')\n\n@journals.route(\"/journal/\")\ndef journal(journal_id):\n\tjournal = Journal.query.get_or_404(journal_id)\n\treturn render_template('journal.html', title=journal.title, journal=journal)\n\n@journals.route(\"/journal//update\", methods=['GET', 'POST'])\n@login_required\ndef update_journal(journal_id):\n\tjournal = Journal.query.get_or_404(journal_id)\n\tif journal.author != current_user:\n\t\tabort(403)\n\tform = JournalForm()\n\tif form.validate_on_submit():\n\t\tjournal.title = form.title.data\n\t\tjournal.content = form.content.data\n\t\tdb.session.commit()\n\t\tflash('Your journal entry has been updated!', 'success')\n\t\treturn redirect(url_for('journals.journal', journal_id=journal.id))\n\telif request.method == 'GET':\n\t\tform.title.data = journal.title\n\t\tform.content.data = journal.content\n\treturn render_template('create_journal.html', title='Update Journal Entry', form=form, legend='Update Journal Entry')\n\n@journals.route(\"/journal//delete\", methods=['POST'])\n@login_required\ndef delete_journal(journal_id):\n\tjournal = Journal.query.get_or_404(journal_id)\n\tif journal.author != current_user:\n\t\tabort(403)\n\tdb.session.delete(journal)\n\tdb.session.commit()\n\tflash('Your journal entry has been deleted!', 'success')\n\treturn redirect(url_for('main.home'))","sub_path":"journalshare/journals/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"151641573","text":"import cv2\nimport csv\nimport argparse\nimport numpy as np\nfrom ColorDescriptor import ColorDescriptor\nimport glob\n\nclass searcher:\n\tdef __init__(self, indexPath):\n\t\tself.indexPath = indexPath\n\n\tdef search(self, queryFeatures, limit = 10):\n\t\tresults = {}\n\t\twith open(self.indexPath) as f:\n\t\t\treader = csv.reader(f)\n\t\t\tfor row in reader:\n\t\t\t\tfeatures = [float(x) for x in row[1:]]\n\t\t\t\td = self.chi1_distance(features, queryFeatures)\n\t\t\t\tresults[row[0]] = d\n\t\t\tf.close()\n\t\tresults = sorted([(v, k) for (k, v) in results.items()])\n\t\treturn results[:limit]\n\tdef chi1_distance(self, histA, histB, eps = 1e-10):\n\t\td = 0.5 * np.sum([((a - b) ** 2) / (a + b + eps)\n\t\t\tfor (a, b) in zip(histA, histB)])\n\t\treturn d\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--index\", required = True, help = \"Path to the csv of the features\")\nap.add_argument(\"-q\", \"--query\", required = True, help = \"Path to the query\")\nap.add_argument(\"-r\", \"--result-path\", required = True, help = \"Path to the result\")\narge = vars(ap.parse_args())\n\ncd = ColorDescriptor((8,12,3))\nimagePath = arge[\"query\"]\nimage = cv2.imread(imagePath)\nfeatures = cd.describe(image)\n\nSearch = searcher(arge[\"index\"])\nresults = Search.search(features)\n\ncv2.imshow(\"Query\", image)\ncv2.waitKey(0)\n\nprint(arge[\"query\"])\n\nfor (score, resultID) in results:\n\tresult = cv2.imread(resultID)\n\t#print(result)\n\t#cv2.namedWindow(\"Result\", cv2.WINDOW_AUTOSIZE)\n\tcv2.imshow(\"Result\", result)\n\tcv2.waitKey(0)\n","sub_path":"Report-1/ImageSearch/searcher.py","file_name":"searcher.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"537030853","text":"#!/usr/bin/env python3\n\n\"\"\"Retrieve and print words from a URL\n\nUsage:\n\n\tpython3 soutce_1.py \n\"\"\"\n\nimport sys\nfrom urllib.request import urlopen\n\n# http://sixty-north.com/c/t.txt\n\ndef fetch_words(url):\n\t\"\"\" Fetch a list of words from a URL \n\n\tArgs:\n\t\turl: The URL of a UTF-8 text document\n\n\tReturns:\n\t\tA list of string containing the words from\n\t\tthe document.\n\t\"\"\"\n\twith urlopen(url) as story:\n\t\tstory_words = []\n\t\tfor line in story:\n\t\t\tline_words = line.decode('utf-8').split()\n\t\t\tfor word in line_words:\n\t\t\t\t\tstory_words.append(word)\n\treturn story_words\n\n\ndef print_items(items):\n\t\"\"\"Print items one per line\n\n\tArgs:\n\t\tAn iterable series of printable items\n\t\"\"\"\n\tfor item in items:\n\t\tprint(item)\n\ndef main(url):\n\t\"\"\"Print each word from a text document from a URL.\n\n\tArgs:\n\t\turl: the URL of a UTF-8 text document\n\t\"\"\"\n\twords = fetch_words(url)\n\tprint_items(words);\n\n\nif __name__ == '__main__':\n\turl = sys.argv[1] # taking the argument #1 because it is our url\n\tmain(url)","sub_path":"source_1.py","file_name":"source_1.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"650301171","text":"#!/usr/bin/env python3\n\nimport numpy as np\n\n\nfrom world_state import WorldState\n\n\n# Door sensor - needs to now the world state to answer questions\nclass RobotState:\n def __init__(self):\n # Default probabilities - will be set later by gui\n self.set_move_left_probabilities(0.8, 0.1)\n self.set_move_right_probabilities(0.8, 0.1)\n\n self.prob_move_left_if_left = 0.8\n self.prob_move_right_if_left = 0.05\n self.prob_no_move_if_left = 0.15\n\n self.prob_move_left_if_right = 0.8\n self.prob_move_right_if_right = 0.05\n self.prob_no_move_if_right = 0.15\n\n self.robot_move_standard_deviation_err = 0.1\n\n # Gaussian probabilities\n self.set_move_gauss_probabilities(0.05)\n\n # Where the robot actually is\n self.robot_loc = 0.5\n\n # Make sure probabilities add up to one\n def set_move_left_probabilities(self, move_left_if_left=0.8, move_right_if_left=0.05):\n self.prob_move_left_if_left = move_left_if_left\n self.prob_move_right_if_left = move_right_if_left\n\n # begin homework 2 : problem 2\n # check probabilities are correct)\n if (self.prob_move_left_if_left + self.prob_move_right_if_left) <= 1:\n return True\n return False\n # end homework 2 : problem 2\n\n # Make sure probabilities add up to one\n def set_move_right_probabilities(self, move_right_if_right=0.8, move_left_if_right=0.05):\n self.prob_move_right_if_right = move_right_if_right\n self.prob_move_left_if_right = move_left_if_right\n\n # begin homework 2 : problem 2\n # check probabilities are correct\n if (self.prob_move_left_if_right + self.prob_move_right_if_right) <= 1:\n return True\n return False\n # end homework 2 : problem 2\n\n # Just a helper function to place robot + sign in middle of bin\n def adjust_location(self, n_divs):\n div = 1.0 / n_divs\n bin_id = min(n_divs-1, max(0, np.round(self.robot_loc / div)))\n self.robot_loc = (bin_id + 0.5) * div\n\n # For Kalman filtering - error in movement\n def set_move_gauss_probabilities(self, standard_deviation):\n self.robot_move_standard_deviation_err = standard_deviation\n\n # Actually move - don't move off of end of hallway\n def _move_(self, amount):\n \"\"\" Move the amount given - but clamp value\n :param amount - requested amount to move\n :return amount - amount actually moved\"\"\"\n if 0 <= self.robot_loc + amount <= 1:\n self.robot_loc += amount\n\n return amount\n\n # Roll the dice and move\n def move_left(self, step_size):\n \"\"\" Move to the left by step_size (probably)\n :param step_size - the bin size\n :returns The amount actually moved \"\"\"\n # begin homework 2 : problem 2\n # begin homework 2 : problem 2\n # Flip the coin...\n rand = np.random.uniform(0.0, 1.0) # Get random float between 0-1\n \n # Determine whether to move left, right, or stay put\n if rand < self.prob_move_right_if_left:\n# print('Move right')\n step_size = step_size\n elif rand < (self.prob_move_left_if_left+self.prob_move_right_if_left): # Check if should really move left\n# print('Move left')\n step_size = -step_size\n else:\n# print('Stay put')\n step_size = 0\n\n # end homework 2 : problem 2\n return self._move_(step_size)\n\n # Roll the dice and move\n def move_right(self, step_size):\n \"\"\" Move to the right by step_size (probably)\n :param step_size - the bin size\n :returns The amount actually moved \"\"\"\n # begin homework 2 : problem 2\n # Flip the coin...\n rand = np.random.uniform(0.0, 1.0) # Get random float between 0-1\n # Determine whether to move left, right, or stay put\n if rand < self.prob_move_right_if_right:\n# print('Move right')\n step_size = step_size\n elif rand < (self.prob_move_left_if_right+self.prob_move_right_if_right): # Check if should really move left\n# print('Move left')\n step_size = -step_size\n else:\n# print('Stay put')\n step_size = 0\n # end homework 2 : problem 2\n return self._move_(step_size)\n\n def move_gauss(self, amount):\n \"\"\" Move by the amount given (may be positive or negative) with noise added\n :param amount - amount to move (negative is left, positive right)\n :returns The amount actually moved \"\"\"\n # begin homework 3 : problem 2\n # Sample the noise distribution - note zero mean\n # Move amount plus noise sampled from noise distribution\n # end homework 3 : problem 2\n\n # Actually move (don't run off of end)\n return self._move_(amount)\n\n\nif __name__ == '__main__':\n ws = WorldState()\n\n rs = RobotState()\n\n # Move far enough to the left and you should stop moving\n print(\"Checking _Move_ function\")\n check_step_size = 0.1\n for i in range(0, 20):\n rs.move_left(check_step_size)\n if rs.robot_loc < 0 or rs.robot_loc > 1:\n raise ValueError(\"Robot went off end of left wall\")\n\n # Repeat for right\n for i in range(0, 20):\n rs.move_right(check_step_size)\n if rs.robot_loc < 0 or rs.robot_loc > 1:\n raise ValueError(\"Robot went off end of right wall\")\n\n # Check that we get our probabilites back (mostly)\n print(\"Checking move left probabilities\")\n count_moved_left = 0\n count_moved_right = 0\n for i in range(0, 1000):\n rs.robot_loc = 0.5\n rs.move_left(check_step_size)\n if rs.robot_loc == 0.5 - check_step_size:\n count_moved_left += 1\n elif rs.robot_loc == 0.5 + check_step_size:\n count_moved_right += 1\n\n# print('Moved left:', count_moved_left, 'times')\n# print('Moved right:', count_moved_right, 'times')\n# print('No move:', 1000-count_moved_left-count_moved_right, 'times')\n\n prob_count_left = count_moved_left/1000\n prob_count_right = count_moved_right/1000\n if abs(prob_count_left - rs.prob_move_left_if_left) > 0.1:\n raise ValueError(\"Probability should be close to {}, is {}\".format(rs.prob_move_left_if_left, prob_count_left))\n# else:\n# print(\"Probability should be close to {}, is {}\".format(rs.prob_move_left_if_left, prob_count_left))\n if abs(prob_count_right - rs.prob_move_right_if_left) > 0.1:\n raise ValueError(\"Probability should be close to {}, is {}\".format(rs.prob_move_right_if_left, prob_count_right))\n# else:\n# print(\"Probability should be close to {}, is {}\".format(rs.prob_move_right_if_left, prob_count_right))\n\n print(\"Checking move right probabilities\")\n count_moved_left = 0\n count_moved_right = 0\n for i in range(0, 1000):\n rs.robot_loc = 0.5\n rs.move_right(check_step_size)\n if rs.robot_loc == 0.5 - check_step_size:\n count_moved_left += 1\n elif rs.robot_loc == 0.5 + check_step_size:\n count_moved_right += 1\n\n# print('Moved left:', count_moved_left, 'times')\n# print('Moved right:', count_moved_right, 'times')\n# print('No move:', 1000-count_moved_left-count_moved_right, 'times')\n\n prob_count_left = count_moved_left / 1000\n prob_count_right = count_moved_right / 1000\n if abs(prob_count_left - rs.prob_move_left_if_right) > 0.1:\n raise ValueError(\"Probability should be close to {}, is {}\".format(rs.prob_move_left_if_right, prob_count_left))\n# else:\n# print(\"Probability should be close to {}, is {}\".format(rs.prob_move_left_if_right, prob_count_left))\n if abs(prob_count_right - rs.prob_move_right_if_right) > 0.1:\n raise ValueError(\"Probability should be close to {}, is {}\".format(rs.prob_move_right_if_right, prob_count_right))\n# else:\n# print(\"Probability should be close to {}, is {}\".format(rs.prob_move_right_if_right, prob_count_right))\n\n print(\"Checking move with normal distribution probabilities\")\n dist_moved = []\n rs.set_move_gauss_probabilities(0.1)\n for i in range(0, 1000):\n rs.robot_loc = 0.5\n\n dist_moved.append(rs.move_gauss(0))\n\n # This one will only pass when we do homework 3\n mu_moved = np.mean(dist_moved)\n standard_deviation_moved = np.std(dist_moved)\n if abs(mu_moved) > 0.01:\n raise ValueError(\"Mean should be close to 0, is {}\".format(mu_moved))\n if abs(standard_deviation_moved - rs.robot_move_standard_deviation_err) > 0.01:\n raise ValueError(\"Standard deviation should be close to {}, is {}\".format(rs.robot_move_standard_deviation_err, standard_deviation_moved))\n\n print(\"Passed tests\")\n","sub_path":"SimpleSLAM/robot_state.py","file_name":"robot_state.py","file_ext":"py","file_size_in_byte":8739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"18976711","text":"from pprint import pprint\nfrom time import time\nimport logging\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.decomposition import TruncatedSVD, PCA\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.metrics import f1_score\nfrom gensim.models import FastText\n\nimport warnings\nwarnings.simplefilter('ignore')\n\ndef my_split_train_test(X, y):\n return train_test_split(X,y,test_size=0.33, random_state=42)\n\n\ndf = pd.read_csv('data/df_news.csv', index_col=0)\ndf.drop('Unnamed: 0.1', axis=1, inplace=True)\n\ndata = df['text'].values\ny = df['fake'].values\n\nfrom sklearn.base import BaseEstimator\nclass tensorflow_tub_transformer(BaseEstimator):\n def __init__(self):\n self.data=1\n\n def transform(self, X):\n return np.array(X)\n\n def fit(self, X, y):\n return self\n\na = np.loadtxt('data/Tfidf_w2v_ft_transformed.txt')\nprint(a.shape)\nb = np.load('data/embedding_npy/universal_large_text.npy')\nXX = np.c_[a,b]\nprint(XX.shape)\nX_train, X_test, y_train, y_test = my_split_train_test(XX, y)\nprint(X_train.shape)\n\nga = []\nfor i in range(1,200):\n ga.append(i/100)\n\ngam = [0.05, 0.1, 0.3, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n\nfrom scipy.stats import randint as sp_randint\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV\n\npipeline = Pipeline([\n ('ft', tensorflow_tub_transformer()),\n ('svd', PCA(n_components=900)),\n ('clf', SVC(kernel=\"rbf\",gamma=0.7,C=8)),\n])\n\n\n\n# uncommenting more parameters will give better exploring power but will\n# increase processing time in a combinatorial way\nparameters = {\n #'tfidf__use_idf': (True, False),\n 'svd__n_components': (300, 400, 500, 600, 700, 800, 900, 1000, 1100),\n# 'clf__batch_size' : sp_randint(50, 300),\n# 'clf__C' : (1, 3, 5, 7, 9, 11),\n# 'clf__gamma' : gam,\n# 'clf__sec_layer_nodes' : sp_randint(4, 900),\n# 'clf__third_layer_nodes' : sp_randint(4, 900),\n# 'clf__opt_lr_rate' : (0.0001, 0.0002, 0.0003, 0.0005, 0.0007, 0.0009, 0.001),\n# 0.03, 0.035, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.10,\n# 0.11, 0.13, 0.15, 0.17, 0.19, 0.21, 0.23, 0.25),\n\n}\n\n\nif __name__ == \"__main__\":\n # multiprocessing requires the fork to happen in a __main__ protected\n # block\n\n # find the best parameters for both the feature extraction and the\n # classifier\n grid_search = GridSearchCV(pipeline, parameters, n_jobs=-1, verbose=1, refit='f1_score')\n\n print(\"Performing grid search...\")\n print(\"pipeline:\", [name for name, _ in pipeline.steps])\n print(\"parameters:\")\n pprint(parameters)\n t0 = time()\n grid_search.fit(X_train, y_train)\n print(\"done in %0.3fs\" % (time() - t0))\n print()\n\n print(\"Best score: %0.3f\" % grid_search.best_score_)\n print(\"Best parameters set:\")\n best_parameters = grid_search.best_estimator_.get_params()\n for param_name in sorted(parameters.keys()):\n print(\"\\t%s: %r\" % (param_name, best_parameters[param_name]))\n\n print(grid_search.predict(X_test))\n","sub_path":"codes/Stella/tune.py","file_name":"tune.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"11960446","text":"import sqlite3\r\nimport numpy as np\r\nimport itertools\r\nimport random\r\nimport math\r\nprojects = ['Matrix','sample','demo','empty','FBVE']\r\nmode = [6,2,2,0,2]\r\ntSwitch = [10,10,90,90,10]\r\ntExp = [90,90,5,90,90]\r\nnSwitch = [9,9,1,1,9]\r\nnExp = [1,3,1,1,3]\r\n\r\ndBowl = 0.360\r\nhWater = 0.08\r\n\r\n\r\ndef oneModeMatrixNet(mode):\r\n A=mode+np.zeros((5,5))\r\n A[:,0]=-1\r\n A[0,:]=-1\r\n np.fill_diagonal(A,-1)\r\n return A\r\n\r\ndef oneModeMatrix(mode):\r\n A=mode+np.zeros((5,5))\r\n return A\r\n\r\ndef oneModeMatrixSingle(mode):\r\n A=np.zeros((5,5))-1\r\n np.fill_diagonal(A,mode)\r\n\r\n return A\r\n\r\n\r\ndef associativeMatrix(mode,n):\r\n A=[]\r\n A=oneModeMatrix(0)\r\n fishVR = [1,2,3,4]\r\n combinationList = [] \r\n for comb in itertools.combinations([1,2,3,4],n):\r\n combinationList.append(comb)\r\n print(combinationList)\r\n if n==2:\r\n A[combinationList[0][0],combinationList[0][1]]=mode\r\n A[combinationList[0][1],combinationList[0][0]]=mode\r\n A[combinationList[-1][0],combinationList[-1][1]]=mode\r\n A[combinationList[-1][1],combinationList[-1][0]]=mode\r\n elif n==3:\r\n \r\n A2=oneModeMatrix(0)\r\n for perm in itertools.permutations(combinationList[0],2):\r\n A2[perm[0],perm[1]]=mode\r\n \r\n return A\r\n\r\ndef dataCreation(mode,var='z',nSwitch=9):\r\n dataTemplate = {'speed':0.05,'z':-0.03,'r':0.07,'clockwise':1}\r\n data=[]\r\n if mode==2:\r\n if var == 'z2':\r\n z=np.arange(-0.07, -0.01, .01)\r\n r=np.arange(.02, .14, .02)\r\n print(z)\r\n for k in range(0,nSwitch):\r\n data.append([])\r\n for j in range(0,5):\r\n data[k].append([])\r\n for l in range(0,5):\r\n data2 = dataTemplate.copy()\r\n\r\n rmax=0\r\n r0=100\r\n\r\n while r0>rmax:\r\n z0=random.choice(z)\r\n r0=random.choice(r)\r\n\r\n z2 = dBowl-(hWater+z0)\r\n rmax=math.sqrt(math.pow(dBowl,2)-math.pow(z2,2))\r\n\r\n data2['z']=z0\r\n data2['r']=r0\r\n\r\n\r\n data[k][j].append(data2.copy())\r\n if var == 'r':\r\n \r\n r=np.arange(0.0175, .15, .0175)\r\n print(r)\r\n random.shuffle(r)\r\n r=np.insert(r,0,[100])\r\n print(r)\r\n for k in range(0,nSwitch):\r\n data.append([])\r\n for j in range(0,5):\r\n data[k].append([])\r\n for l in range(0,5):\r\n data2 = dataTemplate.copy()\r\n\r\n\r\n data2['r']=r[k]\r\n if bool(random.getrandbits(1)):\r\n data2['clockwise']=1\r\n else:\r\n data2['clockwise']=-1\r\n\r\n data[k][j].append(data2.copy())\r\n if var == 'z':\r\n \r\n z=np.arange(.01,.07,.06/8)\r\n print(z)\r\n random.shuffle(z)\r\n z=np.insert(z,0,[100])\r\n for k in range(0,nSwitch):\r\n data.append([])\r\n for j in range(0,5):\r\n data[k].append([])\r\n for l in range(0,5):\r\n data2 = dataTemplate.copy()\r\n\r\n data2['z']=z[k]\r\n if bool(random.getrandbits(1)):\r\n data2['clockwise']=1\r\n else:\r\n data2['clockwise']=-1\r\n\r\n\r\n data[k][j].append(data2.copy())\r\n\r\n if var == 'speed':\r\n \r\n speed=np.arange(.01,0.1,0.1/8)\r\n print(speed)\r\n random.shuffle(speed)\r\n speed=np.insert(speed,0,[0])\r\n for k in range(0,nSwitch):\r\n data.append([])\r\n for j in range(0,5):\r\n data[k].append([])\r\n for l in range(0,5):\r\n data2 = dataTemplate.copy()\r\n \r\n if k==0:\r\n data2['z']=100\r\n data2['speed']=speed[k]\r\n if bool(random.getrandbits(1)):\r\n data2['clockwise']=1\r\n else:\r\n data2['clockwise']=-1\r\n print(data2)\r\n\r\n\r\n data[k][j].append(data2.copy())\r\n if var == 'background':\r\n \r\n background=np.arange(0,8,1)\r\n print(background)\r\n random.shuffle(background)\r\n background=np.insert(background,0,[0])\r\n for k in range(0,nSwitch):\r\n data.append([])\r\n for j in range(0,5):\r\n data[k].append([])\r\n for l in range(0,5):\r\n data2 = dataTemplate.copy()\r\n data2['background']=background[k]\r\n if k==0:\r\n data2['z']=100\r\n if bool(random.getrandbits(1)):\r\n data2['clockwise']=1\r\n else:\r\n data2['clockwise']=-1\r\n print(data2)\r\n\r\n\r\n data[k][j].append(data2.copy())\r\n #print(data)\r\n return data\r\n\r\n\r\ndef symMatrix(mode):\r\n A=[]\r\n A.append(oneModeMatrix(0))\r\n fishVR = [1,2,3,4]\r\n combinationList = []\r\n for comb in itertools.combinations([1,2,3,4],2):\r\n combinationList.append(comb)\r\n print(combinationList)\r\n for n in range(0,3):\r\n A2=oneModeMatrix(0)\r\n A2[combinationList[n][0],combinationList[n][1]]=mode\r\n A2[combinationList[n][1],combinationList[n][0]]=mode\r\n A2[combinationList[-1-n][0],combinationList[-1-n][1]]=mode\r\n A2[combinationList[-1-n][1],combinationList[-1-n][0]]=mode\r\n A.append(A2)\r\n for comb in itertools.combinations([1,2,3,4],3):\r\n A2=oneModeMatrix(0)\r\n for perm in itertools.permutations(comb,2):\r\n A2[perm[0],perm[1]]=mode\r\n A.append(A2)\r\n A.append(oneModeMatrix(6))\r\n\r\n return A\r\n\r\n\r\n\r\n\r\n\r\ndef FirstGenExpBase(c):\r\n c.execute('''CREATE TABLE experiments (project text, exp integer,\r\n replicate integer,\r\n date text, tStart text, tEnd text, \r\n nameExperimenter text,expId text,\r\n fishVR integer, \r\n fishVRId text,\r\n species text,\r\n fishSize REAL,fishAge integer)''')\r\n\r\n\r\ndef FirstGen(c):\r\n c.execute('''CREATE TABLE projects (project text, exp integer,\r\n replicate integer,\r\n tExp int,tSwitch integer, \r\n nSwitch integer,\r\n nStimuli integer, \r\n fishVR integer,\r\n fishVR1 integer,param1 text, \r\n fishVR2 integer,param2 text, \r\n fishVR3 integer,param3 text, \r\n fishVR4 integer,param4 text, \r\n fishVR5 integer,param5 text)''')\r\n\r\n\r\ndef defineStimuli(c):\r\n for k in range(0,len(projects)):\r\n if k==0:\r\n exp = 0\r\n modeMat = symMatrix(mode[k])\r\n replicate = 0\r\n for n in range(0,nSwitch[k]):\r\n for l in range(0,5):\r\n values = [projects[k],exp,replicate,tExp[k],tSwitch[k],nSwitch[k],n,l,modeMat[n][l,0],'',modeMat[n][l,1],'',modeMat[n][l,2],'',modeMat[n][l,3],'',modeMat[n][l,4],'']\r\n c.execute(\"INSERT INTO projects VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\",values)\r\n if k==3:\r\n exp = 0\r\n modeMat = oneModeMatrixNet(mode[k])\r\n replicate = 0\r\n for n in range(0,nSwitch[k]):\r\n for l in range(0,5):\r\n for j in range(0,5):\r\n values = [projects[k],exp,replicate,tExp[k],tSwitch[k],nSwitch[k],n,l,modeMat[l,0],'',modeMat[l,1],'',modeMat[l,2],'',modeMat[l,3],'',modeMat[l,4],'']\r\n c.execute(\"INSERT INTO projects VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\",values)\r\n if k==2:\r\n data=dataCreation(mode[k],nSwitch=nSwitch[k])\r\n exp = 0\r\n modeMat = oneModeMatrixNet(mode[k])\r\n replicate = 0\r\n for n in range(0,nSwitch[k]):\r\n for l in range(0,5):\r\n for j in range(0,5):\r\n values = [projects[k],exp,replicate,tExp[k],tSwitch[k],nSwitch[k],n,l,modeMat[l,0],str(data[n][l][0]),modeMat[l,1],str(data[n][l][1]),modeMat[l,2],str(data[n][l][2]),modeMat[l,3],str(data[n][l][3]),modeMat[l,4],str(data[n][l][4])]\r\n c.execute(\"INSERT INTO projects VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\",values)\r\n if k==1:\r\n data=dataCreation(mode[k],var='z2',nSwitch=nSwitch[k])\r\n replicate = 0\r\n modeMat = oneModeMatrix(2)\r\n for exp in range(0,nExp[k]):\r\n for n in range(0,nSwitch[k]):\r\n for l in range(0,5):\r\n values = [projects[k],exp,replicate,tExp[k],tSwitch[k],nSwitch[k],n,l,modeMat[l,0],str(data[n][l][0]),modeMat[l,1],str(data[n][l][1]),modeMat[l,2],str(data[n][l][2]),modeMat[l,3],str(data[n][l][3]),modeMat[l,4],str(data[n][l][4])]\r\n c.execute(\"INSERT INTO projects VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\",values)\r\n if k==4:\r\n exp = 0\r\n modeMat = oneModeMatrixSingle(2)\r\n for replicate in range(0,8):\r\n data=dataCreation(mode[k],var='r',nSwitch=nSwitch[k])\r\n for n in range(0,nSwitch[k]):\r\n for l in range(0,5):\r\n values = [projects[k],exp,replicate,tExp[k],tSwitch[k],nSwitch[k],n,l,modeMat[l,0],str(data[n][l][0]),modeMat[l,1],str(data[n][l][1]),modeMat[l,2],str(data[n][l][2]),modeMat[l,3],str(data[n][l][3]),modeMat[l,4],str(data[n][l][4])]\r\n c.execute(\"INSERT INTO projects VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\",values)\r\n exp = 1\r\n modeMat = oneModeMatrixSingle(2)\r\n for replicate in range(0,8):\r\n data=dataCreation(mode[k],var='z',nSwitch=nSwitch[k])\r\n for n in range(0,nSwitch[k]):\r\n for l in range(0,5):\r\n values = [projects[k],exp,replicate,tExp[k],tSwitch[k],nSwitch[k],n,l,modeMat[l,0],str(data[n][l][0]),modeMat[l,1],str(data[n][l][1]),modeMat[l,2],str(data[n][l][2]),modeMat[l,3],str(data[n][l][3]),modeMat[l,4],str(data[n][l][4])]\r\n c.execute(\"INSERT INTO projects VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\",values)\r\n exp = 2\r\n modeMat = oneModeMatrixSingle(2)\r\n for replicate in range(0,8):\r\n data=dataCreation(mode[k],var='speed',nSwitch=nSwitch[k])\r\n for n in range(0,nSwitch[k]):\r\n for l in range(0,5):\r\n values = [projects[k],exp,replicate,tExp[k],tSwitch[k],nSwitch[k],n,l,modeMat[l,0],str(data[n][l][0]),modeMat[l,1],str(data[n][l][1]),modeMat[l,2],str(data[n][l][2]),modeMat[l,3],str(data[n][l][3]),modeMat[l,4],str(data[n][l][4])]\r\n c.execute(\"INSERT INTO projects VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\",values)\r\n exp = 3\r\n modeMat = oneModeMatrixSingle(2)\r\n for replicate in range(0,8):\r\n data=dataCreation(mode[k],var='background',nSwitch=nSwitch[k])\r\n for n in range(0,nSwitch[k]):\r\n for l in range(0,5):\r\n values = [projects[k],exp,replicate,tExp[k],tSwitch[k],nSwitch[k],n,l,modeMat[l,0],str(data[n][l][0]),modeMat[l,1],str(data[n][l][1]),modeMat[l,2],str(data[n][l][2]),modeMat[l,3],str(data[n][l][3]),modeMat[l,4],str(data[n][l][4])]\r\n c.execute(\"INSERT INTO projects VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\",values)\r\n\r\n \r\n\r\n \r\n\r\n\r\ndef main():\r\n conn = sqlite3.connect('matrixProjects.db')\r\n c = conn.cursor()\r\n FirstGen(c)\r\n defineStimuli(c)\r\n conn.commit()\r\n conn.close()\r\n conn2 = sqlite3.connect('matrixExperiments.db')\r\n c2 = conn2.cursor()\r\n FirstGenExpBase(c2)\r\n conn2.commit()\r\n conn2.close()\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"online/db/generateDB - Copy.py","file_name":"generateDB - Copy.py","file_ext":"py","file_size_in_byte":12986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"470966067","text":"from flask import Flask, jsonify, render_template\nfrom flask_cors import CORS\nfrom redis import Redis\n\n\nclass Dashboard:\n def __init__(self, redis_server):\n self.app = Flask(__name__)\n self.redis = redis_server\n CORS(self.app, resources={r'/data': {'origins': '*'}})\n\n\ndef get_jobs_stats(database):\n jobs_waiting = int(database.hlen('jobs_waiting'))\n jobs_in_progress = int(database.hlen('jobs_in_progress'))\n jobs_done = int(database.hlen('jobs_done'))\n jobs_total = jobs_waiting + jobs_in_progress + jobs_done\n client_ids = database.get('total_num_client_ids')\n clients_total = int(client_ids) if client_ids is not None else 0\n return {\n 'num_jobs_waiting': jobs_waiting,\n 'num_jobs_in_progress': jobs_in_progress,\n 'num_jobs_done': jobs_done,\n 'jobs_total': jobs_total,\n 'clients_total': clients_total\n }\n\n\ndef create_server(database):\n dashboard = Dashboard(database)\n\n @dashboard.app.route('/dashboard', methods=['GET'])\n def _index():\n job_information = get_jobs_stats(dashboard.redis)\n return render_template(\n 'index.html',\n jobs_waiting=job_information['num_jobs_waiting'],\n jobs_in_progress=job_information['num_jobs_in_progress'],\n jobs_done=job_information['num_jobs_done'],\n jobs_total=job_information['jobs_total'],\n clients_total=job_information['clients_total']\n )\n\n @dashboard.app.route('/data', methods=['GET'])\n def _get_dashboard_data():\n job_information = get_jobs_stats(dashboard.redis)\n return jsonify(job_information), 200\n\n return dashboard\n\n\nif __name__ == '__main__':\n server = create_server(Redis())\n server.app.run(port=5000)\n","sub_path":"src/c21server/dashboard/dashboard_server.py","file_name":"dashboard_server.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"3840198","text":"class Solution:\n \"\"\"\n @param: heights: a list of integers\n @return: a integer\n \"\"\"\n\n def trapRainWater(self, heights):\n # write your code here\n h = heights\n l, r, water, min_h = 0, len(h) - 1, 0, 0\n while l < r:\n while l < r and h[l] <= min_h:\n water += min_h - h[l]\n l += 1\n while l < r and h[r] <= min_h:\n water += min_h - h[r]\n r -= 1\n min_h = min(h[l], h[r])\n return water\n","sub_path":"lintcode/363-trapping-rain-water.py","file_name":"363-trapping-rain-water.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"109828317","text":"class Solution:\n \"\"\"\n @param A: a string\n @param B: a string\n @return: return the sum of two strings\n \"\"\"\n def SumofTwoStrings(self, A, B):\n # write your code here\n len_A, len_B, res = len(A), len(B), ''\n \n if len_A < len_B:\n A = '0' * (len_B - len_A) + A\n else:\n B = '0' * (len_A - len_B) + B\n \n for a, b in zip(A, B):\n res += str(int(a) + int(b))\n \n return res","sub_path":"LintCode/ladder 02 two pointers/旧/1343. Sum of Two Strings/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"245188310","text":"def is_network_connected(person_to_friends: Dict[str, List[str]]) -> bool:\r\n '''\r\n Return whether the social network based on the given\r\n person_to_friends dictionary is connected. A network\r\n is connected if and only if every key in the dictionary\r\n is linked, through a sequence of friends, to every\r\n other person in the dictionary.\r\n\r\n >>> param = {}\r\n >>> is_network_connected(param)\r\n True\r\n >>> param ={'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', \\\r\n 'Manny Delgado'], 'Claire Dunphy': ['Jay Pritchett', \\\r\n 'Mitchell Pritchett', 'Phil Dunphy'], 'Manny Delgado':\\\r\n ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy'],\\\r\n 'Mitchell Pritchett': ['Cameron Tucker', 'Claire Dunphy',\\\r\n 'Luke Dunphy'], 'Alex Dunphy': ['Luke Dunphy'], \\\r\n 'Cameron Tucker': ['Gloria Pritchett', 'Mitchell Pritchett'],\\\r\n 'Haley Gwendolyn Dunphy': ['Dylan D-Money', 'Gilbert D-Cat'],\\\r\n 'Phil Dunphy': ['Claire Dunphy', 'Luke Dunphy'], \\\r\n 'Dylan D-Money': ['Chairman D-Cat', 'Haley Gwendolyn Dunphy'],\\\r\n 'Gloria Pritchett': ['Cameron Tucker', 'Jay Pritchett', \\\r\n 'Manny Delgado'], 'Luke Dunphy': ['Alex Dunphy', \\\r\n 'Manny Delgado', 'Mitchell Pritchett', 'Phil Dunphy']}\r\n >>> is_network_connected(param)\r\n False\r\n >>> param = {'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', \\\r\n 'Manny Delgado'], 'Claire Dunphy': ['Claire Dunphy', \\\r\n 'Jay Pritchett', 'Mitchell Pritchett', 'Phil Dunphy', \\\r\n 'moe ah'],'Manny Delgado': ['Gloria Pritchett', \\\r\n 'Jay Pritchett', 'Luke Dunphy', 'moe ah'], 'Gloria Pritchett': \\\r\n ['Cameron Tucker', 'Jay Pritchett', 'Manny Delgado', 'moe ah']}\r\n >>> is_network_connected(param)\r\n True\r\n >>> param = {'moe ahmed': ['Karim Benzema']}\r\n >>> is_network_connected(param)\r\n True\r\n >>> param = {'Lionel Messi': ['Cristiano Ronaldo'], 'Robert Luis': \\\r\n ['Cristiano Ronaldo']}\r\n >>> is_network_connected(param)\r\n False\r\n '''\r\n keys_lst = []\r\n connected_ppl_lst = []\r\n connected = True\r\n for key in person_to_friends:\r\n if not (person_to_friends in keys_lst):\r\n keys_lst.append(key)\r\n\r\n # If the key has on;y one key then the network is connected\r\n # return True\r\n if len(keys_lst) == 1:\r\n return True\r\n\r\n for key_name in keys_lst:\r\n for key in person_to_friends:\r\n if key_name == key:\r\n for value in person_to_friends[key]:\r\n if value in keys_lst and not (value in connected_ppl_lst):\r\n connected_ppl_lst.append(value)\r\n\r\n for name in connected_ppl_lst:\r\n for key1 in person_to_friends:\r\n if key1 == name:\r\n friends_of_friends_lst = get_friends_of_friends\\\r\n (person_to_friends, name)\r\n for index in friends_of_friends_lst:\r\n if index in keys_lst and not (index in \\\r\n connected_ppl_lst):\r\n connected_ppl_lst.append(index)\r\n\r\n for value1 in person_to_friends[key1]:\r\n friends_of_friends_lst = get_friends_of_friends\\\r\n (person_to_friends, value1)\r\n for index2 in friends_of_friends_lst:\r\n if index2 in keys_lst and not (index2 in \\\r\n connected_ppl_lst):\r\n connected_ppl_lst.append(index2)\r\n\r\n for name2 in connected_ppl_lst:\r\n friends_of_friends_lst = get_friends_of_friends \\\r\n (person_to_friends, name2)\r\n for index2 in friends_of_friends_lst:\r\n if name2 in keys_lst and not (name2 in \\\r\n connected_ppl_lst):\r\n connected_ppl_lst.append(name2)\r\n\r\n if len(connected_ppl_lst) != len(keys_lst):\r\n connected = False\r\n else:\r\n del connected_ppl_lst[:]\r\n\r\n return (connected)\r\n\r\ndef time_listfunc(is_network_connected: Callable[[List[int]], List[int]]) -> float:\r\n '''Return how many seconds it takes to run function f on a shuffled\r\n list with n items, on average over m times.\r\n '''\r\n\r\n import time\r\n total = 0\r\n #for i in range(m):\r\n p2f = make_dict()\r\n t1 = time.time()\r\n f(p2f)\r\n t2 = time.time()\r\n total += t2 - t1\r\n return total\r\nprint(time_listfunc(is_network_connected))\r\n","sub_path":"timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":4998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"272650677","text":"\"\"\"\n编写一个函数,调用函数返回四位不含0的随机数.\n\"\"\"\n\nimport random\ndef random_number(figure):\n num = 0\n for i in range(1,figure+1):\n num = num*10 + random.randint(1,9)\n return num\nif __name__ == '__main__':\n print(random_number(4))\n","sub_path":"本科科研/7-13/问题1.py","file_name":"问题1.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"578080989","text":"from sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder, MinMaxScaler\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndf = pd.read_csv('Social_Network_Ads.csv')\ndf = df.drop(['User ID'] , axis=1)\n# print(df)\nX = df.iloc[:, :-1].values\nY = df.iloc[:, -1].values\n\nlabel = LabelEncoder()\nX[:, 0] = label.fit_transform(X[:, 0])\nhotEncoder = OneHotEncoder(categorical_features=[0])\nX = hotEncoder.fit_transform(X).toarray()\n\nsc_x = MinMaxScaler()\nX = sc_x.fit_transform(X)\n\n\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.15, random_state=99)\n\n\nclassifier = GaussianNB()\nclassifier.fit(X_train, Y_train)\n\ny_pred = classifier.predict(X_test)\n\nprint(y_pred)\n\n\nmatrix = confusion_matrix(Y_test, y_pred)\nprint(matrix)\nprint(56/60)\n\n\n\n\n\n\n","sub_path":"Naive Bayes/NaiveBayesClassifier.py","file_name":"NaiveBayesClassifier.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"508275058","text":"from sympy.core.function import AppliedUndef\nfrom sympy.sets.fancysets import ImageSet\nfrom sympy.sets.sets import FiniteSet\nfrom sympy.tensor.indexed import Indexed\n\n\ndef _get_free_symbols(exprs):\n \"\"\"Returns the free symbols of a symbolic expression.\n\n If the expression contains any of these elements, assume that they are\n the \"free symbols\" of the expression:\n\n * indexed objects\n * applied undefined function (useful for sympy.physics.mechanics module)\n \"\"\"\n if not isinstance(exprs, (list, tuple, set)):\n exprs = [exprs]\n if all(callable(e) for e in exprs):\n return set()\n\n free = set().union(*[e.atoms(Indexed) for e in exprs])\n free = free.union(*[e.atoms(AppliedUndef) for e in exprs])\n return free or set().union(*[e.free_symbols for e in exprs])\n\n\ndef extract_solution(set_sol, n=10):\n \"\"\"Extract numerical solutions from a set solution (computed by solveset,\n linsolve, nonlinsolve). Often, it is not trivial do get something useful\n out of them.\n\n Parameters\n ==========\n\n n : int, optional\n In order to replace ImageSet with FiniteSet, an iterator is created\n for each ImageSet contained in `set_sol`, starting from 0 up to `n`.\n Default value: 10.\n \"\"\"\n images = set_sol.find(ImageSet)\n for im in images:\n it = iter(im)\n s = FiniteSet(*[next(it) for n in range(0, n)])\n set_sol = set_sol.subs(im, s)\n return set_sol\n","sub_path":"sympy/plotting/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"456267892","text":"\"\"\"conftest.py :: Setup fixtures for pytest.\"\"\"\n\nimport time\nfrom multiprocessing import Process\nfrom types import TracebackType\nfrom typing import Callable, Optional, Type\n\nimport pytest\nfrom fauxmo import fauxmo\nfrom fauxmo.utils import get_local_ip\n\n\nclass TestFauxmoServer:\n \"\"\"Runs Fauxmo in a separate thread.\"\"\"\n\n def __init__(self, config_path_str: str) -> None:\n \"\"\"Initialize test Fauxmo server with path to config.\"\"\"\n self.config_path_str = config_path_str\n\n def __enter__(self) -> str:\n \"\"\"Start a TextFauxmoServer, returns the ip address it's running on.\"\"\"\n self.server = Process(\n target=fauxmo.main,\n kwargs={\"config_path_str\": self.config_path_str},\n daemon=True,\n )\n self.server.start()\n time.sleep(1)\n return get_local_ip()\n\n def __exit__(\n self,\n exc_type: Optional[Type[BaseException]],\n exc_value: Optional[Exception],\n traceback: Optional[TracebackType],\n ) -> None:\n \"\"\"Terminate the server and join the thread on exit.\"\"\"\n self.server.terminate()\n self.server.join()\n\n\n@pytest.fixture(scope=\"module\")\ndef fauxmo_server() -> Callable[[str], TestFauxmoServer]:\n \"\"\"Use a pytest fixture to provide the TestFauxmoServer context manager.\"\"\"\n return TestFauxmoServer\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"188937226","text":"# -*- coding: utf-8 -*-\n\nimport logging\nfrom contextlib import contextmanager\n\nimport babel\nimport pkg_resources\nfrom babel.support import Translations\nfrom jinja2 import Environment, FileSystemLoader, select_autoescape\n\n__author__ = 'lundberg'\n\nlogger = logging.getLogger(__name__)\n\n\nclass Jinja2Env:\n \"\"\"\n Initiates Jinja2 environment with Babel translations\n \"\"\"\n\n def __init__(self):\n templates_dir = pkg_resources.resource_filename('eduid_queue', 'templates')\n translations_dir = pkg_resources.resource_filename('eduid_queue', 'translations')\n # Templates\n template_loader = FileSystemLoader(searchpath=templates_dir)\n logger.info(f'Loaded templates from {templates_dir}: {template_loader.list_templates()}')\n self.env = Environment(\n loader=template_loader,\n extensions=['jinja2.ext.i18n', 'jinja2.ext.autoescape'],\n autoescape=select_autoescape(),\n )\n # Translations\n self.translations = {\n 'en': Translations.load(translations_dir, ['en']),\n 'sv': Translations.load(translations_dir, ['sv']),\n }\n logger.info(f'Loaded translations from {translations_dir}: {self.translations}')\n logger.info('Jinja2 environment loaded')\n\n @contextmanager\n def select_language(self, lang: str):\n \"\"\"\n Usage:\n with Jinja2Env().select_language(lang) as env:\n txt = env.get_template('template.jinja2').render(*args, **kwargs)\n \"\"\"\n neg_lang = babel.negotiate_locale(preferred=[lang], available=self.translations.keys())\n translation = self.translations.get(neg_lang, self.translations['en'])\n # install_gettext_translations is available when instantiating env with extension jinja2.ext.i18n\n self.env.install_gettext_translations(translation, newstyle=True)\n yield self.env\n","sub_path":"src/eduid_queue/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"369827684","text":"# explore the effect of the variance thresholds on the number of selected features\nfrom numpy import arange\nfrom pandas import read_csv\nfrom sklearn.feature_selection import VarianceThreshold\nfrom matplotlib import pyplot\n# load the dataset\ndf = read_csv('oil-spill.csv', header=None)\n# split data into inputs and outputs\ndata = df.values\nX = data[:, :-1]\ny = data[:, -1]\nprint(X.shape, y.shape)\n# define thresholds to check\nthresholds = arange(0.0, 0.55, 0.05)\n# apply transform with each threshold\nresults = list()\nfor t in thresholds:\n\t# define the transform\n\ttransform = VarianceThreshold(threshold=t)\n\t# transform the input data\n\tX_sel = transform.fit_transform(X)\n\t# determine the number of input features\n\tn_features = X_sel.shape[1]\n\tprint('>Threshold=%.2f, Features=%d' % (t, n_features))\n\t# store the result\n\tresults.append(n_features)\n# plot the threshold vs the number of selected features\npyplot.plot(thresholds, results)\npyplot.show()","sub_path":"dataPreparation/dataCleaning/basicDataCleaning/08_compare_variance_thresholds.py","file_name":"08_compare_variance_thresholds.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"603979417","text":"import app\nimport unittest\n\nfrom faros.client import FarosClient\nfrom faros.utils import DATE_FORMAT\nfrom datetime import datetime, timedelta\nfrom unittest.mock import patch\n\n\n@patch.object(FarosClient, \"graphql_execute\")\nclass EC2OldInstances(unittest.TestCase):\n def setUp(self):\n self.event = {\n \"farosToken\": \"farosToken\",\n \"params\": {\"num_days\": 2}\n }\n self.now = datetime.utcnow()\n\n def test_get_old_instances(self, mocked_execute):\n new_instance = (self.now - timedelta(hours=5)).strftime(DATE_FORMAT)\n old_instance = (self.now - timedelta(days=3)).strftime(DATE_FORMAT)\n old_instance2 = (self.now - timedelta(days=10)).strftime(DATE_FORMAT)\n data = {\"aws\": {\"ec2\": {\"instance\": {\"data\": [\n {\n \"farosAccountId\": \"accountId\",\n \"farosRegionId\": \"farosId\",\n \"instanceId\": \"instanceId4\",\n \"launchTime\": old_instance,\n \"state\": {\"name\": \"running\"}\n },\n {\n \"farosAccountId\": \"accountId\",\n \"farosRegionId\": \"farosId\",\n \"instanceId\": \"instanceId2\",\n \"launchTime\": old_instance2,\n \"state\": {\"name\": \"running\"}\n },\n {\n \"farosAccountId\": \"accountId\",\n \"farosRegionId\": \"farosId\",\n \"instanceId\": \"instanceId3\",\n \"launchTime\": new_instance,\n \"state\": {\"name\": \"running\"}\n }\n ]}}}\n }\n\n mocked_execute.return_value = data\n result = app.lambda_handler(self.event, None)\n mocked_execute.assert_called_once()\n self.assertEqual(len(result), 2)\n old = {i[\"instanceId\"] for i in result}\n self.assertSetEqual(old, {\"instanceId2\", \"instanceId4\"})\n\n def test_missing_cutoff(self, mocked_execute):\n mocked_execute.return_value = None\n with self.assertRaises(KeyError):\n app.lambda_handler({\"farosToken\": \"token\"}, None)\n self.assertFalse(mocked_execute.called)\n\n def test_invalid_cutoff_value(self, mocked_execute):\n event = {\n \"farosToken\": \"token\",\n \"params\": {\"num_days\": \"day\"}\n }\n mocked_execute.return_value = None\n with self.assertRaises(ValueError):\n app.lambda_handler(event, None)\n self.assertFalse(mocked_execute.called)\n\n event = {\n \"farosToken\": \"token\",\n \"params\": {\"num_days\": \"-2\"}\n }\n with self.assertRaises(ValueError):\n app.lambda_handler(event, None)\n self.assertFalse(mocked_execute.called)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"apps/ec2-old-instances/test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":2738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"518899695","text":"import pandas as pd\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nimport os\r\nimport scipy\r\nimport numpy as np\r\nimport re\r\nimport nltk\r\nimport datetime\r\nnltk.download('stopwords')\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.stem.porter import PorterStemmer\r\nimport random\r\nimport spacy\r\nimport gensim \r\nfrom datetime import datetime,date,time\r\nfrom gensim.models import Word2Vec \r\nfrom nltk.tokenize import sent_tokenize, word_tokenize \r\nimport matplotlib.pyplot as plt\r\npd.set_option(\"display.max_columns\",50)\r\npd.set_option(\"display.max_rows\",300)\r\nfrom nltk import FreqDist\r\nimport seaborn as sns\r\nimport plotly.graph_objects as go #pip install plotly==4.1.0\r\nimport plotly\r\nfrom plotly.offline import init_notebook_mode;import plotly.graph_objs as go;plotly.offline.init_notebook_mode(connected=True)# offline ploting of box plots\r\nimport pyod\r\nfrom datetime import date, time\r\nos.chdir('F:\\\\LocalDriveD\\\\Use case 4')\r\n\r\ndata = pd.read_csv('DataCommunicationTime.csv', delimiter=',', decimal=',')\r\ndata.head()\r\ndata.info()\r\ndata.describe(include='all')\r\ndata.columns\r\n# Variable Understanding\r\n\r\ndata.Communication_Type.value_counts()\r\nsns.set(style=\"darkgrid\")\r\nax = sns.countplot(x=\"Communication_Type\", data=data)\r\n\r\ndata.Communication_Day.value_counts()\r\nsns.set(style=\"darkgrid\")\r\nax = sns.countplot(x=\"Communication_Day\", data=data)\r\n\r\ndata.City.value_counts()\r\nsns.set(style=\"darkgrid\")\r\nax = sns.countplot(x=\"Communication_Type\", data=data)\r\n\r\ndata.Qualification.value_counts()\r\nsns.set(style=\"darkgrid\")\r\nax = sns.countplot(x=\"Qualification\", data=data)\r\n\r\ndata.Gender.value_counts()\r\nsns.set(style=\"darkgrid\")\r\nax = sns.countplot(x=\"Gender\", data=data)\r\n\r\ndata.Marital_Status.value_counts()\r\ndata.Marital_Status = data.Marital_Status.str.lower() \r\ndata['Marital_Status'] = np.where(data['Marital_Status']=='u','unmarried',data['Marital_Status'])\r\ndata['Marital_Status'] = np.where(data['Marital_Status']=='m','married',data['Marital_Status'])\r\ndata['Marital_Status'] = np.where(data['Marital_Status']=='w','widow',data['Marital_Status'])\r\ndata['Marital_Status'] = np.where(data['Marital_Status']=='d','divorcee',data['Marital_Status'])\r\nsns.set(style=\"darkgrid\")\r\nax = sns.countplot(x=\"Marital_Status\", data=data)\r\n\r\ndata.Occupation_Code.value_counts()\r\nsns.set(style=\"darkgrid\")\r\nax = sns.countplot(x=\"Occupation_Code\", data=data)\r\n\r\ndata.TwitterPresence.value_counts()\r\n\r\ndata.LinkedinPresence.value_counts()\r\n\r\ndata.PreviousAttemptOfCommunication.describe()\r\n\r\ndata.SuccessfullCommunication.describe()\r\n\r\ndata.Communication_Success.value_counts()\r\n\r\ndata.MonthPeriod.value_counts()\r\n\r\ndata.Industry.value_counts()\r\n\r\ndata.Type_Accomodation.value_counts()\r\n\r\ndata['DateOfBirth'].head()\r\ndata['DateOfBirth'] = pd.to_datetime(data['DateOfBirth'])\r\ndata['Today'] = pd.to_datetime(date.today())\r\ndata['age'] = data['Today']-data['DateOfBirth']\r\ndata['age'] = np.round(data['age'].dt.days/365)\r\ndata['age'] = data['age'].astype(int)\r\ndata['age'].head()\r\ndel data['DateOfBirth']\r\ndel data['Today']\r\ndata['age'].hist()\r\n\r\n# Data Cleaning\r\ndata.isnull().sum()/data.shape[0]\r\nlimitper = len(data)*0.9\r\ndata = data.dropna(thresh = limitper,axis=1)\r\n\r\ndata_copy = data.copy()\r\ndata_cat = data[['Communication_Day', 'MonthPeriod', 'Communication_Type',\r\n 'City', 'Industry', 'Qualification', 'Gender', 'Type_Accomodation',\r\n 'Marital_Status', 'Occupation_Code', 'FacebookPresence',\r\n 'TwitterPresence', 'LinkedinPresence', 'PreviousAttemptOfCommunication']]\r\ndata_num = data[['Customer_ID','SuccessfullCommunication' , 'age']]\r\n\r\n\r\ndata_cat= data_cat.fillna(data_cat.mode().iloc[0])\r\ndata_num= data_num.fillna(data_num.mean().iloc[0])\r\ndata_Cat_dummy = pd.get_dummies(data_cat)\r\ndata = pd.concat([data_num,data_Cat_dummy],axis=1)\r\ndata['Communication_Success'] = data_copy['Communication_Success']\r\ndata.isnull().sum()/data.shape[0]\r\n\r\n## Since no variable has a significant large values we can omit outlier test\r\n\r\ndata['Communication_Success'].value_counts()\r\nX = data[['SuccessfullCommunication', 'age', 'FacebookPresence',\r\n 'TwitterPresence', 'LinkedinPresence', 'PreviousAttemptOfCommunication',\r\n 'Communication_Day_weekday', 'Communication_Day_weekend',\r\n 'MonthPeriod_10To20Days', 'MonthPeriod_First10Days',\r\n 'MonthPeriod_Last10Days', 'Communication_Type_promotional',\r\n 'Communication_Type_service', 'City_Tier1', 'City_Tier2', 'City_Tier3',\r\n 'Industry_Banking/Finance', 'Industry_IT', 'Industry_Others',\r\n 'Industry_Retail', 'Industry_Telecom', 'Industry_manufacturing',\r\n 'Qualification_Diploma', 'Qualification_Graduate',\r\n 'Qualification_Others', 'Qualification_PHD',\r\n 'Qualification_Post Graduate', 'Gender_female', 'Gender_male',\r\n 'Gender_other', 'Type_Accomodation_rented',\r\n 'Type_Accomodation_self_home', 'Marital_Status_divorcee',\r\n 'Marital_Status_married', 'Marital_Status_other',\r\n 'Marital_Status_unmarried', 'Marital_Status_widow',\r\n 'Occupation_Code_farmer', 'Occupation_Code_house wife',\r\n 'Occupation_Code_other', 'Occupation_Code_pensioner',\r\n 'Occupation_Code_salaried',\r\n 'Occupation_Code_self employeed -nonprofessional',\r\n 'Occupation_Code_self employeed -professional',\r\n 'Occupation_Code_student', 'Occupation_Code_trader']]\r\ny = data[ 'Communication_Success']\r\n\r\n######## Model Development ##############\r\nfrom sklearn.preprocessing import StandardScaler\r\nScale = StandardScaler()\r\nScaledObject = Scale.fit(X)\r\nX_scaled = ScaledObject.transform(X)\r\nX_scaled = pd.DataFrame(X_scaled,columns = X.columns)\r\n######### Train/Test Split\r\na = random.sample(range(0, X.shape[0]), int(X.shape[0]*0.75))\r\nX_train = X.iloc[a,] \r\nX_test = X.drop(X.index[a])\r\ny_train = y.iloc[a,] \r\ny_test = y.drop(y.index[a])\r\n\r\nfrom sklearn.metrics import classification_report,accuracy_score\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.model_selection import cross_validate\r\n# Let's first try a simple model to make a benchmark for our model performance\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nscoring = ['precision_macro','recall_macro','accuracy']\r\nclf = DecisionTreeClassifier(max_depth = 50,random_state=0)\r\nscores = cross_validate(estimator = clf,X=X_train, y=y_train,cv=3,scoring=scoring)\r\nscores\r\n\r\n################## Precision,Accuracy,Recall through cross validation###\r\nfrom xgboost import XGBClassifier\r\nPerformance = pd.DataFrame(columns = ['test_accuracy','test_precision_macro','test_recall_macro',\r\n 'Max_depth','n_estimators','learning_rate'])\r\nmax_depth = [10,50]\r\nfor k in range(1,2):\r\n for j in range(1,2):\r\n for i in max_depth:\r\n clf = XGBClassifier(learning_rate =k/10, max_depth = i,n_estimators = j*100,random_state=0)\r\n scores = cross_validate(estimator = clf,X=X_train, y=y_train,cv=2,scoring=scoring)\r\n a = pd.DataFrame(scores)\r\n a = a[['test_accuracy','test_precision_macro','test_recall_macro']]\r\n a['Max_depth']=i\r\n a['n_estimators']=j*100\r\n a['learning_rate']=k/10\r\n Performance = pd.concat([a,Performance],axis=0)\r\nPerformance[['Max_depth','n_estimators','learning_rate','test_accuracy']][Performance['test_accuracy'] ==Performance['test_accuracy'].max()] #50\r\nprint(Performance)\r\n\r\n####### Validation of model results from best obtained model ( frm c.v.) on test data\r\nfrom sklearn import metrics\r\nfrom sklearn.metrics import classification_report\r\nfrom sklearn.metrics import accuracy_score,roc_curve,auc\r\nfrom sklearn.preprocessing import label_binarize\r\nfrom scipy import interp\r\nfrom itertools import cycle\r\nimport matplotlib.pyplot as plt\r\nxgb = XGBClassifier(max_depth = 10,n_estimators =100,learning_rate = 0.1,random_state=0)\r\nxgb.fit(X_train,y_train)\r\ny_pred = xgb.predict(X_test)\r\nprint(accuracy_score(y_test,y_pred))\r\nprint(classification_report(y_test,y_pred))\r\n\r\n### Prediction on new data\r\nOutput = X_test.copy()\r\nOutput = Output.reset_index() \r\nprediction_prob = pd.DataFrame(xgb.predict_proba(X_test))\r\nprediction_prob.columns = ['12PM_6PM','6AM_12PM','6PM_12PM']\r\nprediction = pd.Series(xgb.predict(X_test))\r\nOutput = pd.concat([Output,prediction_prob],axis=1)\r\nOutput['Prediction'] = prediction\r\nOutput.to_csv('final_output.csv')\r\n\r\n\r\n########## ROC Curve on best model\r\n# Compute ROC curve and ROC area for each class\r\ny_score = xgb.predict_proba(X_test)\r\nfrom sklearn.preprocessing import LabelBinarizer\r\ny_test_binary = label_binarize(y_test, classes=[0, 1, 2])\r\nn_classes = 3\r\nfpr = dict()\r\ntpr = dict()\r\nroc_auc = dict()\r\nfor i in range(n_classes):\r\n fpr[i], tpr[i], _ = roc_curve(y_test_binary[:, i], y_score[:, i])\r\n roc_auc[i] = auc(fpr[i], tpr[i])\r\n# Compute micro-average ROC curve and ROC area\r\nfpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(y_test_binary.ravel(), y_score.ravel())\r\nroc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\r\n# Compute macro-average ROC curve and ROC area\r\n# First aggregate all false positive rates\r\nall_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))\r\n# Then interpolate all ROC curves at this points\r\nmean_tpr = np.zeros_like(all_fpr)\r\nfor i in range(n_classes):\r\n mean_tpr += interp(all_fpr, fpr[i], tpr[i])\r\n\r\n# Finally average it and compute AUC\r\nmean_tpr /= n_classes\r\n\r\nfpr[\"macro\"] = all_fpr\r\ntpr[\"macro\"] = mean_tpr\r\nroc_auc[\"macro\"] = auc(fpr[\"macro\"], tpr[\"macro\"])\r\n\r\n# Plot all ROC curves\r\nplt.figure()\r\nlw=2\r\nplt.plot(fpr[\"micro\"], tpr[\"micro\"],\r\n label='micro-average ROC curve (area = {0:0.2f})'\r\n ''.format(roc_auc[\"micro\"]),\r\n color='deeppink', linestyle=':', linewidth=4)\r\n\r\nplt.plot(fpr[\"macro\"], tpr[\"macro\"],\r\n label='macro-average ROC curve (area = {0:0.2f})'\r\n ''.format(roc_auc[\"macro\"]),\r\n color='navy', linestyle=':', linewidth=4)\r\n\r\ncolors = cycle(['aqua', 'darkorange', 'cornflowerblue'])\r\nfor i, color in zip(range(n_classes), colors):\r\n plt.plot(fpr[i], tpr[i], color=color, lw=lw,\r\n label='ROC curve of class {0} (area = {1:0.2f})'\r\n ''.format(i, roc_auc[i]))\r\n\r\nplt.plot([0, 1], [0, 1], 'k--', lw=lw)\r\nplt.xlim([0.0, 1.0])\r\nplt.ylim([0.0, 1.05])\r\nplt.xlabel('False Positive Rate')\r\nplt.ylabel('True Positive Rate')\r\nplt.title('Some extension of Receiver operating characteristic to multi-class')\r\nplt.legend(loc=\"lower right\")\r\nplt.show()\r\n","sub_path":"UseCase4_Communication_Time.py","file_name":"UseCase4_Communication_Time.py","file_ext":"py","file_size_in_byte":10414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"458415567","text":"from flask import Flask, render_template, flash, redirect, url_for\nfrom flask.ext.wtf import Form\nfrom wtforms import StringField, SubmitField\nfrom wtforms.validators import Email, Length\n\nimport db\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'Super Secret Unguessable Key'\n\n\n@app.before_request\ndef before():\n db.open_db_connection()\n\n\n@app.teardown_request\ndef after(exception):\n db.close_db_connection(exception)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"HW5 - SQL Updates/hw5.py","file_name":"hw5.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"364310559","text":"# Best Case O(n+k)\nfrom collections import Counter\nn = int(input())\nl=[0]*100\nstring1=''\nfor x in range(n):\n string1 += \" \" + input()\nls=[int(s) for s in string1.split() if s.isdigit()]\na = dict(Counter(ls))\nl[0]=a[0]\nfor i in range(1,100):\n if i not in a.keys():\n l[i]=l[i-1]\n else:\n l[i]=a[i]+l[i-1]\nprint (' '.join(map(str, l)))","sub_path":"problems/sort/Counting Sort 2.py","file_name":"Counting Sort 2.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"386454016","text":"#!/usr/bin/env python3\n\nimport configparser\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport urllib.request\nfrom distutils.errors import DistutilsPlatformError\nfrom distutils.log import INFO\n\nimport setuptools\nimport setuptools_rust as rust\nfrom setuptools.command.sdist import sdist as _sdist\nfrom setuptools_rust.build import build_rust as _build_rust\nfrom setuptools_rust.utils import get_rust_version\n\n\nclass sdist(_sdist):\n\n def run(self):\n # build `pyproject.toml` from `setup.cfg`\n c = configparser.ConfigParser()\n c.add_section(\"build-system\")\n c.set(\"build-system\", \"requires\", str(self.distribution.setup_requires))\n c.set(\"build-system\", 'build-backend', '\"setuptools.build_meta\"')\n with open(\"pyproject.toml\", \"w\") as pyproject:\n c.write(pyproject)\n\n # run the rest of the packaging\n _sdist.run(self)\n\n\nclass build_rust(_build_rust):\n\n def run(self):\n\n try:\n rustc = get_rust_version()\n nightly = rustc.prerelease is not None and \"nightly\" in rustc.prerelease\n except DistutilsPlatformError:\n if sys.platform in (\"linux\", \"darwin\"):\n self.setup_temp_rustc_unix(toolchain=\"nightly\", profile=\"minimal\")\n nightly = True\n else:\n nightly = False\n\n if self.inplace:\n self.extensions[0].strip = rust.Strip.No\n if nightly:\n self.extensions[0].features.append(\"nightly\")\n\n _build_rust.run(self)\n\n\n def setup_temp_rustc_unix(self, toolchain, profile):\n\n rustup_sh = os.path.join(self.build_temp, \"rustup.sh\")\n os.environ[\"CARGO_HOME\"] = os.path.join(self.build_temp, \"cargo\")\n os.environ[\"RUSTUP_HOME\"] = os.path.join(self.build_temp, \"rustup\")\n\n self.mkpath(os.environ[\"CARGO_HOME\"])\n self.mkpath(os.environ[\"RUSTUP_HOME\"])\n\n self.announce(\"downloading rustup.sh install script\", level=INFO)\n with urllib.request.urlopen(\"https://sh.rustup.rs\") as res:\n with open(rustup_sh, \"wb\") as dst:\n shutil.copyfileobj(res, dst)\n\n self.announce(\"installing Rust compiler to {}\".format(self.build_temp), level=INFO)\n subprocess.call([\n \"sh\",\n rustup_sh,\n \"-y\",\n \"--default-toolchain\",\n toolchain,\n \"--profile\",\n profile,\n \"--no-modify-path\"\n ])\n\n self.announce(\"updating $PATH variable to use local Rust compiler\", level=INFO)\n os.environ[\"PATH\"] = \":\".join([\n os.path.abspath(os.path.join(os.environ[\"CARGO_HOME\"], \"bin\")),\n os.environ[\"PATH\"]\n ])\n\n\n\n\nsetuptools.setup(\n setup_requires=[\"setuptools\", \"setuptools_rust\"],\n cmdclass=dict(sdist=sdist, build_rust=build_rust),\n rust_extensions=[rust.RustExtension(\n \"fastobo\",\n path=\"Cargo.toml\",\n binding=rust.Binding.PyO3,\n strip=rust.Strip.Debug,\n features=[\"extension-module\"],\n )],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"562030846","text":"import pdfkit\nimport requests\nfrom lxml import etree\nimport re\n \nconfg = pdfkit.configuration(wkhtmltopdf=r'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\wkhtmltox\\bin\\wkhtmltopdf.exe')\n \n \n#获取链接\ndef get_listurl():\n url=\"https://www.dusaiphoto.com/article/detail/2/\"\n list_url = [url,]\n html=requests.get(url).content.decode('utf-8')\n con=re.findall(r'
(.+?)
',html,re.S)[0]\n listurls=re.findall(r'

.+?(.+?)

',html,re.S)[0]\n return content\n \n#保存html为pdf文档\ndef dypdf(contents):\n contents=etree.HTML(contents)\n s = etree.tostring(contents).decode()\n print(\"开始打印内容!\")\n pdfkit.from_string(s, r'out.pdf',configuration=confg)\n print(\"打印保存成功!\")\n \n \nif __name__ == '__main__':\n contents=''\n urls=get_listurl()\n for url in urls:\n print(url)\n content=get_content(url)\n contents='%s%s%s'%(contents,content,'


')\n \n dypdf(contents)","sub_path":"爬虫/其他爬虫/djangodocument.py","file_name":"djangodocument.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"338036332","text":"import datetime\r\nfrom PIL import Image\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\r\n\r\n\r\nclass Ryanair:\r\n\r\n def __init__(self, reservation_number, mail, origin, destination):\r\n driver = self.create_driver()\r\n driver = self.select_paid_seat(driver, reservation_number, mail, origin, destination)\r\n self.get_captcha_square(driver)\r\n driver.quit()\r\n\r\n def create_driver(self):\r\n # spoof the useragent\r\n dcap = dict(DesiredCapabilities.PHANTOMJS)\r\n dcap[\"phantomjs.page.settings.userAgent\"] = (\"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/46.0\")\r\n # set options from browser\r\n service_args = ['--load-images=true', '--proxy-type=None', '--ignore-ssl-errors=true', '--webdriver-loglevel=OFF', '--ssl-protocol=tlsv1', '--debug=false']\r\n driver = webdriver.PhantomJS(desired_capabilities=dcap, service_args=service_args)\r\n # Set window size\r\n driver.set_window_size(2400, 2400)\r\n return driver\r\n\r\n def select_paid_seat(self, driver, reservation_number, mail, origin, destination):\r\n driver.get('https://www.bookryanair.com/SkySales/Booking.aspx?culture=es-ES&lc=es-ES#Security')\r\n driver.find_element_by_xpath(\"//input[@id='BookingRetrieveSecurity_CONFIRMATIONNUMBER1']\").send_keys(reservation_number)\r\n driver.find_element_by_xpath(\"//input[@id='BookingRetrieveSecurity_CONTACTEMAIL1']\").send_keys(mail)\r\n WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, \"//select[@id='BookingRetrieveSecurity_ORIGINCITY1']//option[@value='\" + origin + \"']\"))).click()\r\n WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, \"//select[@id='BookingRetrieveSecurity_DESTINATIONCITY1']//option[@value='\" + destination + \"']\"))).click()\r\n WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, \"//div[@id='BookingRetrieveSecurity_Buttons_Container']/button[@type='submit']\"))).click()\r\n WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, \"//button[@id='submitbutton']\"))).click()\r\n # select paid seat, from 30 days before fly\r\n WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, \"//input[@id='seatOpt1']\"))).click()\r\n return driver\r\n\r\n def get_captcha_square(self, driver):\r\n element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, \"//div[@class='cabin fll']\")))\r\n location = element.location\r\n size = element.size\r\n # get the size and position of element\r\n left = location['x']\r\n top = location['y']\r\n right = location['x'] + size['width']\r\n bottom = location['y'] + size['height']\r\n # save image only from seats\r\n driver.save_screenshot('seats_page.png')\r\n im = Image.open('seats_page.png')\r\n im = im.crop((left, top, right, bottom))\r\n im.save('seats_' + datetime.datetime.now().strftime(\"%H-%M-%S-%M%p_%B-%d-%Y\") + '.png')","sub_path":"check_seats.py","file_name":"check_seats.py","file_ext":"py","file_size_in_byte":3240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"401622669","text":"\"\"\"\nUnit Testing Links Module\n\"\"\"\n\n\nimport unittest\nimport numpy as np\nfrom robot.link import Link\n\nclass TestLink(unittest.TestCase):\n\n def test_transform_theta(self):\n link = Link(name = 'Body1', alpha = np.pi / 3, a = 0.1, d = 0.1)\n\n transformation = link.transform(np.pi/2)\n actual_transformation = np.array([[0.0000, -1.0000, 0, 0.1000],\n [0.5000, 0.0000, -0.8660, -0.0866],\n [0.8660, 0.0000, 0.5000, 0.0500],\n [0, 0, 0, 1.0000]])\n\n np.testing.assert_almost_equal(actual_transformation, transformation, decimal = 4)\n\n def test_transform_a(self):\n link = Link(name = 'Body1', alpha = np.pi / 3, theta = np.pi / 2, \n d = 0.1, joint_type = 'prismatic')\n\n transformation = link.transform(0.1)\n actual_transformation = np.array([[0.0000, -1.0000, 0, 0],\n [0.5000, 0.0000, -0.8660, -0.0866],\n [0.8660, 0.0000, 0.5000, 0.0500],\n [0, 0, 0, 1.0000]])\n\n np.testing.assert_almost_equal(actual_transformation, transformation, decimal = 4)","sub_path":"Part-9-NewtonMethod/tests/test_links.py","file_name":"test_links.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"122954939","text":"\"\"\"\n python QuestionDetector_Test.py\n\"\"\"\nimport unittest\nimport json\nimport os\nimport TargetClassifier\n\nos.environ[\n 'KATECHEO_NER'] = 'health=https://storage.googleapis.com/pachyderm-neuralbot/ner_models/health.zip,faith=https://storage.googleapis.com/pachyderm-neuralbot/ner_models/faith.zip'\n\n\nclass TargetClassifier_Test(unittest.TestCase):\n def setUp(self):\n self.classifier = TargetClassifier.TargetClassifier()\n\n def test_get_topic(self):\n params = [\"Does some food increase pollen allergy symptoms?\"]\n response = self.classifier.predict(params, \"features\",\n {'tags': {\n 'proceed': True\n }})\n self.assertIsNotNone(response)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"target-classifier/TargetClassifier_Test.py","file_name":"TargetClassifier_Test.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"295138809","text":"#!/usr/bin/env python3\n\n\"\"\" ICSC python\n tested with Arduino Nano 328\n\"\"\" \n\nfrom serial import Serial\nfrom array import array\n\nclass ICSC(object):\n _debug = False\n _max_message = 255\n _soh_start_count = 1 # to 5\n _soh = 1\n _stx = 2\n _etx = 3\n _eot = 4\n _sys_ping = 5\n _sys_pong = 6\n _sys_qstat = 7\n _sys_rstat = 8\n _sys_relay = 9\n _catch_all = 255\n _broadcast = 0\n _functions = {}\n\n def __init__(self, port, baud, station, debug=False):\n self._debug = debug\n self._port = Serial(port = port, baudrate = baud, timeout = 0.1)\n self._station = station\n \n self._functions[self._sys_ping] = self._pong\n self._functions[self._sys_pong] = self._pongRecived\n \n if self._port.closed:\n raise IOError(\"[Error] Serial on % is closed.\"%port)\n\n \"\"\" send command\n \"\"\"\n def send(self, txDestination, txCommand, txData):\n \n sendPacket = array('B')\n \n for n in range(self._soh_start_count):\n sendPacket.append(self._soh)\n \n sendPacket.extend(\n [txDestination,\n self._station,\n txCommand,\n len(txData),\n self._stx]\n )\n\n checkSum = txDestination\n checkSum += self._station\n checkSum += txCommand\n checkSum += len(txData)\n\n for data in txData:\n sendPacket.append(data)\n checkSum += data\n\n sendPacket.append(self._etx)\n sendPacket.append(checkSum % 256)\n sendPacket.append(self._eot)\n \n if(len(sendPacket) > self._max_message-self._soh_start_count):\n print('[Warning] Packet size exceeds message maximum')\n return\n \n if(self._debug):\n print('[Info] Sending: ', sendPacket )\n \n self._port.write(sendPacket.tostring())\n \n \"\"\" read and process commands\n \"\"\"\n def process(self):\n _rxbuffer = array('B')\n try:\n # try to read 10k or as many as in the buffer\n _rxbuffer.extend(self._port.read(self._max_message))\n except:\n return\n \n if(\n (len(_rxbuffer)) and\n (_rxbuffer[0] == self._soh) and\n (_rxbuffer[5] == self._stx) and\n (_rxbuffer[1] != _rxbuffer[2])\n ):\n checkSum = 0\n \n rxDestination = _rxbuffer[1]\n rxSource = _rxbuffer[2]\n rxCommand = _rxbuffer[3]\n rxLenght = _rxbuffer[4]\n \n checkSum += rxDestination + rxSource + rxCommand + rxLenght\n \n if(\n (rxSource == self._station) or\n (\n (rxDestination != self._station) and\n (rxDestination != self._broadcast) and\n (rxDestination != self._sys_relay)\n )\n ):\n if(self._debug):\n print('[Info] Packet rejected')\n return\n \n rxData = array('B')\n \n for buffIndex in range(rxLenght):\n rxData.append(_rxbuffer[6+buffIndex])\n checkSum += _rxbuffer[6+buffIndex]\n \n if(\n (_rxbuffer[6+rxLenght]==self._etx) and\n (_rxbuffer[7+rxLenght]==checkSum%256) and\n (_rxbuffer[8+rxLenght]==self._eot)\n ):\n try:\n self._functions[rxCommand](rxSource, rxCommand, rxData)\n except Exception as e:\n print('[Warning] No function assinged with command ', str(e) )\n pass\n else:\n if(self._debug):\n print('[Info] Packet rejected')\n return\n \n \"\"\" Add callback function to command\n \"\"\"\n def addCommandCallback(self, command, function):\n if(command > 9):\n if command not in self._functions:\n self._functions[command] = function\n elif(self._debug):\n print('[Warning] Command %s added already' % command)\n elif(self._debug):\n print('[Error] Reserved for sysytem command (%s)' % command)\n \n \"\"\" Remove callback function\n \"\"\"\n def removeCommandCallback(self, command):\n if command in self._functions:\n del(self._functions[command])\n \n \"\"\" send ping\n \"\"\"\n def ping(self, destination, data=array('B')):\n if(self._debug):\n print( '[Info] Sending PING to %s (data: %s)' % (destination, data) )\n self.send(destination, self._sys_ping, data)\n \n \"\"\" * system callbacks * \"\"\"\n \"\"\" Response to ping\n \"\"\"\n def _pong( self, source, command, data ):\n if(self._debug):\n print( '[Info] Sending PONG to %s (cmd: %s, data: %s)' % (source, command, data) )\n self.send(source, self._sys_pong, data)\n \n \"\"\" Response to pong\n \"\"\"\n def _pongRecived(self, source, command, data):\n if(self._debug):\n print( '[Info] Received PONG from %s (cmd: %s, data: %s)' % (source, command, data) )\n\n\nif __name__ == '__main__':\n from time import sleep\n \n foo = ICSC(\"/dev/ttyUSB0\", 115200, 2, True)\n \n ''' arduino reset is called when opening serial port\n need to wait for first command\n ''' \n \n print('Waiting for arduino to boot')\n sleep(1)\n \n #foo.ping(2, [1,2,3])\n \n while(True):\n foo.process()\n","sub_path":"other/python/ICSC.py","file_name":"ICSC.py","file_ext":"py","file_size_in_byte":5476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"249956855","text":"__author__ = 'jaume'\n\nimport numpy as np\nfrom collections import Counter\nimport time\nimport multiprocessing as mp\n\nclass Qnn:\n\n def __init__(self, q=3):\n self.data = []\n self.labels = []\n self.q = q\n\n def train(self, data, labels):\n self.data = data\n self.labels = labels\n\n def to_string(self):\n return str(self.q)\n\n def classify(self, individual):\n\n min_distances = [np.inf for _i in range(self.q)]\n nearest_neightbours = [[] for _i in range(self.q)]\n max_min_distances = np.inf\n\n for datum, datum_label in zip(self.data, self.labels):\n dist = distancia_euclidea(individual, datum)\n if dist < max_min_distances:\n i_to_neightbour_to_update = min_distances.index(max_min_distances)\n min_distances[i_to_neightbour_to_update] = dist\n nearest_neightbours[i_to_neightbour_to_update] = datum_label\n max_min_distances = max(min_distances)\n\n return Counter(nearest_neightbours).most_common(1)[0][0]\n\ndef distancia_euclidea(a, b):\n\n if np.all(np.asarray(a) == np.asarray(b)):\n return 0\n\n xnp_ynp = np.array(a)-np.array(b)\n transpose__dot = xnp_ynp.transpose().dot(xnp_ynp)\n distancia = np.sqrt(transpose__dot)\n #print distancia\n return distancia\n\ndef distancia_mahalanobis(a, b):\n\n if np.all(np.asarray(a) == np.asarray(b)):\n return 0\n\n xnp_ynp = np.array(a)-np.array(b)\n distancia = np.sum(xnp_ynp)\n #print distancia\n return distancia\n\n\"\"\"\ninicio = time.time()\n\ndataset = np.load(\"datos_procesados.npy\")[0:11].tolist()\n_q = 3\n\nunlabeled_data = np.delete(dataset, np.s_[9:], axis=1).tolist()\ndata_labels = np.delete(dataset, np.s_[0:9], axis=1).flatten().tolist()\nunique_data_labels = np.unique(data_labels).tolist()\n\n_c_matrix = np.zeros([len(unique_data_labels), len(unique_data_labels)], dtype=int)\nqnn = Qnn(q=_q)\nqnn.train(unlabeled_data[:10], data_labels[:10])\nfor individuo_a_clasificar, e in zip(unlabeled_data[10:], data_labels[10:]):\n clasificado = qnn.classify(individuo_a_clasificar)\n _c_matrix[unique_data_labels.index(e), unique_data_labels.index(clasificado)] += 1\n\nprint \"Matriz de confusion q\" + str(_q) + \":\\n\" + str(np.array(_c_matrix))\n\nfin_ejecucion = time.time() - inicio\nprint \"Tiempo transcurrido: \" + str(fin_ejecucion)\n\"\"\"\n","sub_path":"src/qnn.py","file_name":"qnn.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"355607334","text":"import pytest\nimport time\n\nfrom .jtrace import *\nfrom .tds2024c import *\n\n\ndef get_x_scale(frequency):\n return 1.0 / frequency / 5.0\n\n\n@pytest.mark.parametrize('test_point, f_min, f_max', [\n pytest.param(6, 99e6, 101e6, id='PLL 1 @ 100[MHz]+-1[%]'),\n pytest.param(7, 9.9e6, 10.1e6, id='PLL 2 @ 10[MHz]+-1[%]'),\n pytest.param(8, 15.84e6, 16.16e6, id='oscillator @ 16[MHz]+-1[%]'),\n pytest.param(9, 36.0e3, 180.0e3, id='low frequency LPO in [36[KHz]..180[KHz]]'),\n pytest.param(10, 5.5e6, 19.5e6, id='high frequency LPO in [5.5[MHz]..19.5[MHz]]'),\n pytest.param(18, 99e6, 101e6, id='GCLK @ 100[MHz]+-1[%]'),\n pytest.param(19, 99e6, 101e6, id='HCLK @ 100[MHz]+-1[%]'),\n pytest.param(20, 49.5e6, 50.5e6, id='VCLK1 @ 50[MHz]+-1[%]'),\n pytest.param(21, 49.5e6, 50.5e6, id='VCLK2 @ 50[MHz]+-1[%]'),\n pytest.param(22, 9.9e6, 10.1e6, id='VCLK3 @ 10[MHz]+-1[%]'),\n pytest.param(23, 49.5e6, 50.5e6, id='VCLKA1 @ VCLK1'),\n pytest.param(24, 49.5e6, 50.5e6, id='VCLKA2 @ VCLK1'),\n # not implemented pytest.param(25, 49.9e6, 50.1e6, id='VCLKA4 @ VCLK1'),\n pytest.param(26, 49.5e6, 50.5e6, id='VCLKA4_DIV @ VCLK1'),\n pytest.param(27, 9.9e6, 10.1e6, id='RTICLK1 @ 10[MHz]+-1[%]')])\ndef test_clock_sources_and_domains_are_running_at_expected_frequency(probe, boot_elf, osc, test_point, f_min, f_max):\n \"\"\"\n check if clock sources and clock domains are running within expected frequency range\n \"\"\"\n\n probe_setup_breakpoints(probe, addresses=(boot_elf.get_symbol('test_point_startup_{}'.format(test_point)).address,))\n probe.reset(halt=False)\n probe_wait_halt(probe)\n set_measurement_1_source(osc, MeasurementSource.CHANNEL_1)\n set_measurement_1_type(osc, MeasurementType.FREQUENCY)\n set_acquisition_mode(osc, AcquisitionModeType.AVERAGE)\n set_acquisition_average_number(osc, AcquisitionAverageType.AVERAGE_64)\n set_vertical_scale(osc, 1, 2.0)\n set_horizontal_scale(osc, get_x_scale(f_min))\n set_trigger_level(osc, 3.3 / 2)\n time.sleep(5) # wait for correct average.\n measured = get_measurement_1_value(osc)\n assert f_min < measured < f_max\n","sub_path":"source/boot/test/test_clock.py","file_name":"test_clock.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"434883978","text":"from django import forms\n\nfrom masterApp.models import Shift\nimport time\nfrom datetime import datetime\n\nstrg = \"2017-07-20-10-30\"\n\ndt = datetime.strptime(strg, '%Y-%m-%d-%H-%M')\ntme = dt.time()\n # 10:30:00\nclass CreateShiftForm(forms.Form):\n\ttitle = forms.CharField(\n\t\tlabel='', \n\t\twidget=forms.TextInput(\n\t\t\tattrs={\n\t\t\t\"class\":\"form-control\", \n\t\t\t\"placeholder\":\"Shift title\", \n\t\t\t\n\t\t\t}\n\t\t)\n\t)\n\n\tstart_time = forms.TimeField(\n\t\t\twidget=forms.TimeInput(\n\t\t\t\tformat=('%H:%M:%S'),\n\t\t\t\t# input_formats=('%H:%M:%S'),\n\t\t\t\tattrs={\n\t\t\t\t\"class\":\"form-control\",\n\t\t\t\t\"placeholder\":\"Start time\",\n\t\t\t\t\"type\":\"time\",\n\t\t\t\t\"value\":tme\n\n\t\t\t\t}\t\n\t\t\t)\n\n\t)\n\n\t# date = forms.DateField(\n\t# \twidget=forms.widgets.DateInput(\n\t# \t\tformat='%Y-%m-%d', \n\t\t\t\n\t# \t\tattrs={\n\t# \t\t\t\"class\":\"form-control\",\n\t# \t\t\t\"placeholder\":\"Date\",\n\t# \t\t\t\"type\":\"date\",\n\t# \t\t\t\"value\":date.today()\n\t# \t\t\t}\n\t# \t\t),\n\t\t\t\n\t# \t)\n\t# start_time = forms.TimeField(input_formats=['%I:%M %p'])\n\t\n\n\t# start_time = datetime.datetime.strptime('12:12:12', '%H:%M:%S').time()\n\t# start_time = forms.DateTimeField(\n\t# \twidget=forms.widgets.DateInput(\n\t# \t\tformat=\"%m/%d/%y\", \n\t\t\t# attrs={\n\t\t\t# \t\"class\":\"form-control\",\n\t\t\t# \t\"placeholder\":\"Start time\"\n\t\t\t# \t}\n\t\t\t# )\n\t# \t)\n\n\tend_time = forms.CharField(widget=forms.widgets.TextInput(attrs={\n\t\t\t\t\"class\":\"form-control\",\n\t\t\t\t\"placeholder\":\"End time\",\n\t\t\t\t\"type\":\"time\",\n\t\t\t\t\"value\":tme\n\t\t\t\t}\n\t\t\t)\n\t)\n\n\t# end_time = forms.DateTimeField(\n\t# \twidget=forms.widgets.DateInput(\n\t# \t\tformat=\"%m/%d/%y\", \n\t# \t\tattrs={\n\t# \t\t\t\"class\":\"form-control\",\n\t# \t\t\t\"placeholder\":\"End time\"\n\t# \t\t\t}\n\t# \t\t)\n\t# \t)\n\t","sub_path":"shift/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"570360916","text":"#\n# pygaR\n#\n# Author: Brad Cable\n# Email: brad@bcable.net\n# License: BSD\n#\n\nfrom json import JSONEncoder\n\nfrom pygar.query_output import query_output\n\n\nclass query_json(query_output):\n\t_filetype = 'json'\n\n\tdef out_data(self, out, filename=None):\n\t\tif self.mode == 'data':\n\t\t\tself._output_cache = out\n\n\t\telse:\n\t\t\tencoder = JSONEncoder()\n\t\t\tself._out_fd.write(encoder.encode(out))\n\t\t\tself._out_fd.write('\\n')\n","sub_path":"python/pygar/query_json.py","file_name":"query_json.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"193358906","text":"import vdf, os, glob\nfrom gui import startCurses\nfrom launcher import launch\n\npath = os.path.expanduser('~/.steam/steam/steamapps')\nos.chdir(path)\ngames = []\nfor filename in glob.glob('appmanifest_*.acf'):\n f = vdf.parse(open(filename))['AppState']\n if f['BytesDownloaded'] == f['BytesToDownload']:\n games.append({'appid': f['appid'], 'name': f['name']})\n\nstartCurses(games, launch)\n","sub_path":"steam_cli/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"167720123","text":"from django import template\nfrom django.utils import timezone\n\n__author__ = 'lee.gent'\n\nregister = template.Library()\n\ndef decimalise_time(timedelta):\n hours = timedelta.hours\n minutes = timedelta.minutes\n hour_frac = minutes / 60.0\n return hours + hour_frac\n\n@register.filter\ndef humanise(decimal_hours):\n hours = int(decimal_hours)\n parts_of_hour = decimal_hours - hours\n minutes = 60 * parts_of_hour\n return timezone.timedelta(hours=hours, minutes=minutes)\n\n\n@register.filter\ndef humanise_longhours(decimal_hours):\n neg = decimal_hours < 0\n decimal_hours = abs(decimal_hours)\n hours = int(decimal_hours)\n\n parts_of_hour = decimal_hours - hours\n minutes = 60 * parts_of_hour\n minutes = int(round(minutes, 2))\n if minutes == 60:\n hours = hours + 1\n minutes = 0\n\n return \"{0}{1}:{2:02}\".format(\"-\" if neg else \"\", hours, minutes)\n","sub_path":"aeroplanes/templatetags/decimaltime.py","file_name":"decimaltime.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"78042427","text":"#!/usr/bin/python3\nimport json\nimport atexit\nimport urllib3\nfrom config import *\nfrom telegram import Update\nfrom datetime import datetime\nfrom dbhandler import DBHandler\nfrom urllib3.util import Timeout\nfrom persiantools.jdatetime import JalaliDate\nfrom telegram.ext import (Updater, CommandHandler, \n\tCallbackContext, MessageHandler, Filters)\n\n\ndef start(update: Update, context: CallbackContext) -> None:\n\tchat_id = update.effective_chat.id\n\tif chat_id:\n\t\tadded, rejoin, existed = dbhandler.add_chat(chat_id)\n\t\tif existed:\n\t\t\tupdate.message.reply_text(EXISTING_MESSAGE)\n\t\telif rejoin:\n\t\t\tupdate.message.reply_text(REJOIN_MESSAGE)\n\t\telif added:\n\t\t\tupdate.message.reply_text(GREETING_MESSAGE)\n\t\telse:\n\t\t\tupdate.message.reply_text(\"Oops, Please try again later...\")\n\n\ndef notify_all(context: CallbackContext) -> None:\n\tdata_to_send = get_data()\n\tchat_list = dbhandler.get_chats()\n\tfor chat_id in chat_list:\n\t\tcontext.bot.send_message(chat_id=chat_id, text=data_to_send, parse_mode='markdown')\n\n\ndef stop(update: Update, context: CallbackContext) -> None:\n\tupdate.message.reply_text(GOODBYE_MESSAGE)\n\tdbhandler.remove_chat_id(update.effective_chat.id)\n\n\ndef exit_bot() -> None:\n\tprint(\"---> stopping jobs\")\n\tjob_queue.stop()\n\tprint(\"---> stopping updater\")\n\tupdater.stop()\n\tprint(\"---> closing database connection\")\n\tdbhandler.close()\n\n\ndef get_channel_id(update: Update, context: CallbackContext) -> None:\n\tif (update.channel_post.chat_id):\n\t\tdbhandler.add_chat(update.channel_post.chat_id)\n\n\ndef get_data() -> str:\n\tresponse = request_manager.request(\"GET\", IREX_URL)\n\tif response.status == 200:\n\t\tresponse_data = json.loads(response.data)\n\t\tfetch_time = response_data[\"check_time\"]\n\t\tlist_of_coins = response_data[\"coins\"].keys()\n\t\t\n\t\tformatted_message = \"\"\n\t\tpersian_fetch_date = JalaliDate.fromtimestamp(fetch_time).strftime(\"%Y/%m/%d \") + datetime.fromtimestamp(fetch_time).strftime(\"%H:%M:%S\")\n\n\t\tfor coin in list_of_coins:\n\t\t\tif coin in ALLOWED_COINS_LIST.keys():\n\t\t\t\tcoin_exchanges_data = response_data[\"coins\"][coin]\n\t\t\t\t\n\t\t\t\tformatted_message += \"\\n{0}\".format(\n\t\t\t\t\tMESSAGE_HEADER.format(\n\t\t\t\t\t\tALLOWED_COINS_LIST[coin],\n\t\t\t\t\t\tpersian_fetch_date)\n\t\t\t\t\t)\n\n\t\t\t\t# for exchange in coin_exchanges_data.keys():\n\t\t\t\t# \ttry:\n\t\t\t\t# \t\t_data = coin_exchanges_data[exchange]\n\t\t\t\t# \t\tformatted_message += ROW_TEMPLATE.format(\n\t\t\t\t# \t\t\t_data[\"exchange_lable\"], EXCHANGES_LINK[exchange],\n\t\t\t\t# \t\t\t_data[\"buy\"][\"price\"], _data[\"buy\"][\"vol\"],\n\t\t\t\t# \t\t\t_data[\"sell\"][\"price\"], _data[\"sell\"][\"vol\"]\n\t\t\t\t# \t\t)\n\t\t\t\t# \texcept Exception as e:\n\t\t\t\t# \t\tpass\n\t\t\t\tfor exchange in EXCHANGES_ORDER:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tif exchange in coin_exchanges_data.keys():\n\t\t\t\t\t\t\t_data = coin_exchanges_data[exchange]\n\t\t\t\t\t\t\tformatted_message += ROW_TEMPLATE.format(\n\t\t\t\t\t\t\t\t_data[\"exchange_lable\"], EXCHANGES_LINK[exchange],\n\t\t\t\t\t\t\t\t_data[\"buy\"][\"price\"], _data[\"buy\"][\"vol\"],\n\t\t\t\t\t\t\t\t_data[\"sell\"][\"price\"], _data[\"sell\"][\"vol\"]\n\t\t\t\t\t\t\t)\n\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\tpass\n\n\t\treturn formatted_message\n\n\n\nif __name__ == \"__main__\":\n\ttry:\n\t\tprint(\"\"\"\n\n██ ██████  ███████ ██  ██ ██ \t ██ ███████ ████████ \n██ ██   ██ ██       ██ ██  ██ \t ██ ██         ██    \n██ ██████  █████   ███   ██ \t ██ ███████  ██  \n██ ██   ██ ██     ██ ██  ██ \t ██      ██  ██  \n██ ██  ██ ███████ ██   ██ █████ ██ ███████  ██  \n                                                 \n\t\t\"\"\")\n\t\tprint(\"press ctrl+c to stop this bot\")\n\t\tprint(\"=============================\")\n\t\tdbhandler = DBHandler()\n\t\tupdater = Updater(TOKEN, use_context=True)\n\n\t\tjob_queue = updater.job_queue\n\t\tjob_send_prices = job_queue.run_repeating(notify_all, interval=EVERY_X_MIN * 60, first=0)\n\n\t\trequest_manager = urllib3.PoolManager(timeout=Timeout(connect=1.0, read=1.0))\n\n\t\tupdater.dispatcher.add_handler(CommandHandler('start', start))\n\t\tupdater.dispatcher.add_handler(CommandHandler('stop', stop))\n\t\tupdater.dispatcher.add_handler(MessageHandler(Filters.update.channel_post, get_channel_id))\n\n\t\tupdater.start_polling()\n\t\tupdater.idle()\n\texcept KeyboardInterrupt as e:\n\t\texit_bot()\n\texcept Exception as e:\n\t\tprint(f\"# Error: {e}\")\n\tfinally:\n\t\tprint(\"\\nGood Bye...\")\n","sub_path":"irex.py","file_name":"irex.py","file_ext":"py","file_size_in_byte":4639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"486900151","text":"#Author: Sharanjeet Singh Mago & Yasir Aslam Shah\n#Project 2\n#EID Ecen 5013\n#Fall 2018\n#\nimport sys\nimport Adafruit_DHT\nimport datetime\nimport calendar\n#import matplotlib\nimport MySQLdb\n#matplotlib.use(\"Qt5Agg\")\nfrom PyQt5.QtCore import pyqtSlot\nfrom PyQt5.QtWidgets import QApplication\nfrom PyQt5.QtWidgets import QDialog\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtWidgets import QVBoxLayout\nfrom PyQt5.QtWidgets import QSizePolicy\nfrom PyQt5.uic import loadUi\nfrom PySide.QtCore import *\nfrom PyQt5 import QtCore\nfrom PyQt5 import QtWidgets\n#from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\n#from matplotlib.figure import Figure\na=5\nu=str(a)\n#connecting to pythonspot\ndb=MySQLdb.connect(host=\"localhost\",user=\"root\",passwd=\"root\",db=\"pythonspot\")\ncur=db.cursor()\n#global variables \nflag=[]\nlistA=[]\nlistB=[]\ncount1=[]\ncount2=[]\narray_average1=[0,0,0,0]\narray_average2=[0,0,0,0]\naverage1=0\naverage2=0\ntimer_temp1='0'\ntimer_temp2='0'\nmintemp=100\nmaxtemp=0\nminhum=100\nmaxhum=0\nstr_average1=0.0\nstr_average2=0.0\nkel=0\nfar=0\ncel=1\n\n#function to call calender \ncal1=calendar.month(2018,10)\ntoday=datetime.date.today()\ndate=format(today)\n#connection.close()\n#to initailise graph2 to display the average of humidity values \nclass project(QDialog):\n def __init__(self):\n super(project,self).__init__()\n loadUi ('projectl.ui',self)\n self.setWindowTitle('ProjectOne')\n self.pushButton1.clicked.connect(self.on_pushButton1_clicked)\n self.pushButton2.clicked.connect(self.on_pushButton2_clicked)\n self.pushButton3.clicked.connect(self.on_pushButton3_clicked)\n humidity,temperature = Adafruit_DHT.read(22,4)\n if humidity == None:#if the sensor is not connected the console prints an error message\n self.labelHUM.setText(\"Not Connected\")\n self.labelTEMP.setText(\"Not Connected\") \n d=99\n self.average_hum()\n self.average_temp()\n self.lineEdit.setText(\"0\")\n self.lineEdit1.setText(\"0\")\n @pyqtSlot()\n #date1=format(today)\n #self.label_Time.setText(str(date))\n #function to derive the average of humidity and display the average after every two seconds.\n #the values are automatically displayed on the graphic userinterface\n #the average values is stored in a global varaible and is also dislayed on graph\n def average_hum(self): \n try:\n self.label_Time.setText(str(date))\n self.label_2.setText(cal1)\n #print(cal1)\n global average1\n global timer_temp2\n global minhum\n global maxhum\n global str_average1\n global kel\n global far\n global cel\n\n #global array_average1[]\n humidity,temperature = Adafruit_DHT.read(22,4)\n if humidity == None:#if the sensor is not connected the console prints an error message\n #self.label_Hum1.setText(\"\n cur_hum=\"NC\" \n self.labelHUM.setText(\"Not Connected\") \n cur.execute(\"SELECT * FROM hum2 ORDER by id DESC LIMIT 1\")\n for row in cur.fetchall():\n minhum=float(row[4])\n maxhum=float(row[5])\n str_average1=float(row[2])\n \n #hum=round(humidity,3)\n else: \n self.labelHUM.setText(\"Connected\") \n #print('Humidity ={0:0.1f}%'.format(humidity))\n hum=round(humidity,3)\n cur_hum=str(hum)\n listA.append(hum) \n sum1=sum(listA)\n #print(sum1)\n #print('Timestamp : {:%H:%M:%S}'.format(datetime.datetime.now()))\n #print('Date :{:%Y-%m-%d}'.format(datetime.datetime.now()))\n length1=len(listA)\n average1=sum1/length1\n aver=round(average1,3)\n str_average1=str(aver)\n array_average1.append(average1)\n #print('Hum_average is')\n #print(array_average1)\n self.label_AveA1.setText(str(str_average1))\n a=1\n count1.append(a)\n counter1=sum(count1)\n if counter1 == 10:\n listA.clear()\n #print('yaha')\n count1.clear()\n if minhum > hum:\n minhum=hum\n if maxhum < hum:\n maxhum=hum\n\n timer_hum =(datetime.datetime.now().strftime('%H:%M:%S'))\n self.label_Time1.setText(str(timer_hum))\n timer_temp2=str(timer_hum)\n self.label_curr_hum.setText(str(cur_hum))\n self.label_min_hum.setText(str(minhum))\n self.label_max_hum.setText(str(maxhum))\n timer_temp=(datetime.datetime.now().strftime('%H:%M:%S'))\n self.label_Time2.setText(str(timer_temp))\n #inserting into table HUM@\n cur.execute(\"\"\"INSERT INTO hum2 (col1,col2,col3,col4,col5) VALUES (%s,%s,%s,%s,%s)\"\"\",(cur_hum,str_average1,timer_temp2,minhum,maxhum,))\n db.commit();\n #printing values off table HUM2\n #cur.execute(\"SELECT *FROM hum2\")\n cur.execute(\"SELECT * FROM hum2 ORDER by id DESC LIMIT 1\")\n for row in cur.fetchall():\n print(row[0 ],\"\",row[1 ],\" \",row[2 ],\" \",row[3 ],\" \",row[4 ],\" \",row[5 ])\n \n finally:\n QtCore.QTimer.singleShot(5000,self.average_hum)#the average function for humidity is called after every 2 sec \n #function to calculate the average temperture values automatically after every 2.5 seconds\n #the avergae function is used also to feed the graph to display the values every 10 seconds\n def average_temp(self):\n try:\n global average2\n global timer_temp1\n global mintemp\n global maxtemp\n global str_average2\n global kel\n global far\n global cel\n humidity,temperature = Adafruit_DHT.read(22,4)\n #print('yasir')\n if temperature == None:#if the sensor is not connected, an error message is displayed on UI\n #self.label_Temp1.setText(\"Not Connected\")\n cur_temp=\"NC\"\n #temp=0\n far_temp=0\n self.labelTEMP.setText(\"Not Connected\") \n self.label_curr_temp.setText(str(cur_temp))\n\n kel_temp=0\n cur.execute(\"SELECT * FROM temp2 ORDER by id DESC LIMIT 1\")\n for row in cur.fetchall():\n mintemp=float(row[4])\n maxtemp=float(row[5])\n str_average2=float(row[2])\n else:\n #print('Temperature ={0:0.f}*'.format(temperature))\n self.labelTEMP.setText(\"Connected\")\n temp=round(temperature,3)\n cur_temp =str(temp)\n #cur.execute(\"\"\"INSERT INTO temperature1 (col1) VALUES (%s)\"\"\",(cur_temp,)) \n #db.commit();\n listB.append(temp)\n sum2=sum(listB)\n #print(sum2)\n length2=len(listB)\n average2=(sum2/length2)\n averB=round(average2,3)\n str_average2=str(averB)\n if mintemp > temp:\n mintemp=temp\n if maxtemp < temp:\n maxtemp=temp\n far_temp=((((temp)*9)/5)+32)\n kel_temp=(273.0+(temp))\n #print(kel)\n #print(far)\n #print(cel)\n\n array_average2.append(average2) \n if ((kel==1)&(far==0)&(cel==0)):\n #print(\"k mai gusa\")\n mintempK=(float(mintemp)+273.0)\n maxtempK=(float(maxtemp)+273.0)\n str_average2K=(float(str_average2)+273.0)\n cur_tempK=(float(cur_temp)+273.0)\n average2K=(float(average2)+273.0)\n self.label_curr_temp.setText(str(cur_tempK))\n self.label_min_temp.setText(str(mintempK))\n self.label_max_temp.setText(str(maxtempK))\n self.label_AveB1.setText(str(average2K))\n\n if ((kel==0)&(far==1)&(cel==0)):\n #print(\"f mai gusa\")\n mintempF=((float(mintemp)/9)*5 + 32)\n maxtempF=((float(maxtemp)/9)*5 + 32)\n str_average2F=((float(str_average2)/9)*5 + 32)\n cur_tempF=((float(cur_temp)/9)*5 + 32)\n average2F=((float(average2)/9)*5 + 32)\n self.label_curr_temp.setText(str(cur_tempF))\n self.label_min_temp.setText(str(mintempF))\n self.label_max_temp.setText(str(maxtempF))\n self.label_AveB1.setText(str(average2F))\n\n\n if ((kel==0)&(far==0)&(cel==1)):\n self.labelscale.setText(\"Celsius\")\n #print(\"c mai gusa\")\n self.label_curr_temp.setText(str(cur_temp))\n self.label_min_temp.setText(str(mintemp))\n self.label_max_temp.setText(str(maxtemp))\n self.label_AveB1.setText(str(average2))\n\n\n timer_temp=(datetime.datetime.now().strftime('%H:%M:%S'))\n timer_temp1=str(timer_temp)\n self.label_Time2.setText(str(timer_temp1))\n cur.execute(\"\"\"INSERT INTO temp2 (col1,col2,col3,col4,col5,col6,col7) VALUES (%s,%s,%s,%s,%s,%s,%s)\"\"\",(cur_temp,str_average2,timer_temp1,mintemp,maxtemp,far_temp,kel_temp,))\n db.commit();\n #for row in cur.fetchall():\n #print(row[0],\"\",row[1],\"\",row[2],\"\",row[3],\"\",row[4],\"\",row[5])\n cur.execute(\"SELECT * FROM temp2 ORDER by id DESC LIMIT 1\")\n #cur.execute(\"SELECT *FROM temp2\")\n for row in cur.fetchall():\n print( row[ 0] ,\" \",row[ 1] ,\" \",row[ 2 ],\" \",row[ 3] ,\" \",row[ 4],\" \",row[ 5],\" \",row[6],\" \",row[7])\n #print('Temp_average')\n #print(average2)\n b=1\n count2.append(b)\n counter2=sum(count2)\n #print(counter2)\n #after ten entries the array is cleared\n if counter2 == 10:\n listB.clear()\n #print('waha')\n count2.clear()\n finally:\n #this function is called to display average temperature every 2.5 seconds\n QtCore.QTimer.singleShot(5000,self.average_temp)\n #function defined at clicking pushbutton1(Refresh) to display current temperature\n #in celsuis, farenheut and kelvin.The curent temp is displayed with a timestamp\n def on_pushButton1_clicked(self):\n #timer_temp=(datetime.datetime.now().strftime('%H:%M:%S'))\n #self.label_Time2.setText(str(timer_temp))\n #cur.execute(\"\"\"INSERT INTO temperature1 (col5) VALUES (%s)\"\"\",(timer_temp,))\n #db.commit();\n humidity,temperature = Adafruit_DHT.read(22,4)\n #farenhiet=((temperature *9)/5 + 32) #for temperature conversion to farenhiet\n if temperature == None:#if sensor is not connected, an error message is displayed\n #self.label_Temp1.setText(\"Not Connected\")\n self.labelTEMP.setText(\"Not Connected\") \n self.label_curr_temp.setText(\"NC\")\n\n else:\n self.labelTEMP.setText(\"Connected\") \n #self.label_curr_temp.setText(str(cur_temp))\n\n #print('Temp ={0:0.1f}*'.format(temperature))\n #self.label_Temp1.setText(str(temperature))\n comp2=self.lineEdit1.text()\n if comp2 == None:\n self.label_AlertA.setText('Set Threshold')\n else: \n compare2=int(comp2)\n if compare2 > temperature:\n self.label_AlertB.setText('Cold!')\n\n else:\n self.label_AlertB.setText('Hot!')\n #cur.execute(\"SELECT *FROM temp1\")\n #for row in cur.fetchall():\n #print(row[0],\"\",row[1],\"\",row[2],\"\",row[3],\"\",row[4],\"\",row[5])\n\n temp=temperature\n listB.append(temp)\n #function defined at pushbutton clicked(Refresh) to display the current humidity.The humidity \n #is displayed with current timestamp\n def on_pushButton2_clicked(self):\n #displaying time stamp\n #timer_hum =(datetime.datetime.now().strftime('%H:%M:%S'))\n #self.label_Time1.setText(str(timer_hum))\n humidity,temperature = Adafruit_DHT.read(22,4)\n if humidity == None:\n #if the humidty sensor is not connected an error is displayed as not connected\n #self.label_Hum1.setText(\"Not Connected\")\n d=8\n else: \n #self.label_Hum1.setText(str(humidity))\n #print('Humidity ={0:0.1f}%'.format(humidity))\n hum=humidity\n listA.append(hum)\n comp1=self.lineEdit.text()\n #print(comp1)\n #compare1 = int(comp1)\n if comp1 == None:\n self.label_AlertA.setText('Set Threshold')\n else:\n compare1=int(comp1)\n if compare1 > humidity:\n self.label_AlertA.setText('Dry!')\n else:\n self.label_AlertA.setText('Humid!')\n #cur.execute(\"SELECT *FROM hum1\")\n #for row in cur.fetchall():\n #print(row[0],\"\",row[1],\"\",row[2],\"\",row[3],\"\",row[4],\"\",row[5])\n \n #pushbutton 3 is used to display the current temperature in farenheit \n def on_pushButton3_clicked(self):#kelvin selection\n global kel\n global far\n global cel\n humidity,temperature = Adafruit_DHT.read(22,4)\n #print(\"Klevin selected\\n\")\n self.labelscale.setText(\"Kelvin\")\n if temperature == None:\n #self.label_Temp1.setText(\"Not Connected\")\n kel=1\n far=0\n cel=0\n else:\n kel=1\n far=0\n cel=0\n # print(kel)\n #print(far)\n #print(cel)\n \n #pushbutton 4 is used to display the current temperature in kelvin \n def on_pushButton4_clicked(self):#farenheit is selcted\n global kel\n global far\n global cel\n humidity,temperature = Adafruit_DHT.read(22,4)\n self.labelscale.setText(\"Farenheit\")\n print(\"farenheight\\n\")\n if temperature == None:\n #self.label_Temp1.setText(\"Not Connected\")\n kel=0\n far=1\n cel=0\n else: \n kel=0\n far=1\n cel=0\n #print(kel)\n #print(far)\n #print(cel)\n \n #pushbutton 5 is clicked to display temperature in celsius \n def on_pushButton5_clicked(self):#celsius is selected\n global kel\n global far\n global cel\n #print(\"celsius\\n\")\n self.labelscale.setText(\"Celsius\")\n humidity,temperature = Adafruit_DHT.read(22,4)\n if temperature == None:\n #self.label_Temp1.setText(\"Not Connected\")\n kel=0\n far=0\n cel=1\n else:\n #self.label_Temp1.setText(str(temperature)) \n kel=0\n far=0\n cel=1\n #print(kel)\n #print(far)\n #print(cel)\n\napp=QApplication(sys.argv)\nwidget=project()\nwidget.show()\nsys.exit(app.exec_())\n\n\n\n","sub_path":"Project_2/pro.py","file_name":"pro.py","file_ext":"py","file_size_in_byte":15702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"367336069","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom conexion import *\n\nclass base_fields(object):\n \"\"\"docstring for base_fields.\"\"\"\n def _check_field(self, _field):\n print (_field)\n\n def create_database(self, _table):\n conn \t= Connection()\n cr \t\t= conn.cr()\n _sql = \"CREATE TABLE {}.{} ( `id` INT NOT NULL AUTO_INCREMENT , `create_date` DATETIME NOT NULL , `create_uid` INT NOT NULL , `write_uid` INT NOT NULL , `write_date` DATETIME NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;\".format(conn.database(), _table)\n cr.execute(_sql)\n conn.close()\n cr.close()\n\n def create_field(self, _field, _table):\n conn \t= Connection()\n cr \t\t= conn.cr()\n _vals = {\n 'default' : \"0\",\n 'size' : 20,\n 'null' : \"NOT NULL\",\n 'desc' : '',\n 'AI' : '',\n }\n\n _sql = \"SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{}' AND COLUMN_NAME = '{}'\".format(_table, _field['name'])\n cr.execute(_sql)\n if cr.fetchall() != []:\n return False\n for _f in _field:\n if _f in ['default','size','desc']:\n _vals[_f] = _field[_f]\n elif _f == 'null' and _field[_f]:\n _vals[_f] = 'NULL'\n elif _f == 'AI' and _field[_f]:\n _vals[_f] = 'AUTO_INCREMENT'\n _sql = \"ALTER TABLE {table} ADD {name} {type}({size}) {null} DEFAULT '{default}' {ai} COMMENT '{desc}';\".format(\n table=_table, name=_field['name'], type=_field['type'].upper(), null=_vals['null'], ai=_vals['AI'] ,size=_vals['size'], default=_vals['default'], desc=_vals['desc'])\n cr.execute(_sql)\n conn.commit()\n conn.close()\n cr.close()\n","sub_path":"base_fields.py","file_name":"base_fields.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"174534009","text":"# -*- coding: utf-8 -*-\n# @Time : 19-2-23 下午9:21\n# @Author : langzi\n# @Software: PyCharm\n# @Blog :anonymous\n\n\n\nfrom django.urls import path\nfrom . import views\n\napp_name = \"blog\"\n\nurlpatterns = [\n path(\"\", views.blog_title, name='blog_title'),\n #path('/', views.blog_article),\n path('/', views.blog_article, name='blog_article'),\n]","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"95087427","text":"import http.client\nimport json\nimport time\nimport sys\nimport collections\n\n\n# Request to the server\ndef send_get_request(connection, url):\n\n global start_time\n global request_count\n\n # make a maximum of 40 requests in 10 seconds\n curr_time = time.time()\n diff = curr_time - start_time\n # print(request_count, '- diff :', diff)\n\n if (diff < 10) and (request_count >= 40):\n\n # reset the counters\n t = 10 # (11 - diff)\n print('sleeping for ', t, 'secs')\n time.sleep(t)\n print('fetching again ...')\n request_count = 0\n start_time = time.time()\n\n # perform GET request and read data\n payload = \"{}\"\n connection.request(\"GET\", url, payload)\n response = connection.getresponse()\n data = response.read()\n # print(data.decode(\"utf-8\"))\n\n request_count += 1\n\n return data\n\n\n# Fetch the top 350 movies\ndef get_top_movies(connection):\n\n f = open(MOVIE_FILE_NAME, \"w\")\n\n movie_count = 0\n page_num = 1\n\n while movie_count < MAX_MOVIES:\n\n url = '/3/discover/movie?api_key='\n url += API_KEY\n url += '&sort_by=popularity.desc&page='\n url += str(page_num)\n url += '&primary_release_date.gte=2004-01-01&with_genres=18'\n\n data = send_get_request(connection, url)\n\n # parse json and write to file\n json_string = json.loads(data)\n for movie in json_string['results']:\n\n movie_count += 1\n if movie_count > MAX_MOVIES:\n break\n\n new_line = str(movie['id']) + \",\" + movie['title'] + \"\\n\"\n f.write(new_line)\n movie_ids.append(movie['id'])\n\n page_num += 1\n if movie_count > MAX_MOVIES:\n break\n\n f.close()\n\n\n# Add similar movies to dictionary if they don't exist\ndef add_values_to_dict(movie_id, sim_movie_id):\n\n global sim_movies_dict\n\n # see if the combination \"sim_movie_id - movie_id\" exists\n if (sim_movie_id in sim_movies_dict.keys()) and (movie_id in sim_movies_dict[sim_movie_id]):\n\n # do nothing\n pass\n\n # if reverse combination doesn't exist, add this combination to the dictionary\n else:\n if movie_id in sim_movies_dict.keys():\n sim_movies_dict[movie_id].append(sim_movie_id)\n else:\n sim_movies_dict[movie_id] = list([sim_movie_id])\n\n\n# Fetch 5 similar movies for each movie\ndef get_similar_movies(connection):\n\n for orig_movie_id in movie_ids:\n url = '/3/movie/'\n url += str(orig_movie_id)\n url += '/similar?api_key='\n url += API_KEY\n\n data = send_get_request(connection, url)\n\n # parse json and write to file\n json_string = json.loads(data)\n\n if 'results' not in json_string:\n continue\n\n # if len(json_string['results']) < 5:\n # print(str(orig_movie_id) + ' has ' + str(len(json_string['results'])) + ' similar movies')\n\n movie_count = 0\n for sim_movie in json_string['results']:\n\n movie_count += 1\n if movie_count > 5:\n break\n\n add_values_to_dict(orig_movie_id, sim_movie['id'])\n\n f = open(MOVIE_SIMILAR_FILE_NAME, \"w\")\n\n global sim_movies_dict\n for key in sim_movies_dict:\n for item in sim_movies_dict[key]:\n new_line = str(key) + \",\" + str(item) + \"\\n\"\n f.write(new_line)\n\n f.close()\n\n\n# print('Number of arguments:', len(sys.argv), 'arguments.')\n# print('Argument List:', str(sys.argv))\n\nAPI_KEY = sys.argv[1]\n# API_KEY = '0eb47c135d0f38dfad89642579afec61'\n\n# Global constants\nMOVIE_FILE_NAME = 'movie_ID_name.csv'\nMOVIE_SIMILAR_FILE_NAME = 'movie_ID_sim_movie_ID.csv'\nMAX_MOVIES = 350\n\n# Global Variables\nrequest_count = 0\nstart_time = time.time()\nmovie_ids = []\nconn = http.client.HTTPSConnection(\"api.themoviedb.org\")\nsim_movies_dict = {}\n\nprint('starting to get top ' + str(MAX_MOVIES) + ' movies...')\nget_top_movies(conn)\n\nprint('starting to get similar movies...')\nget_similar_movies(conn)\nprint('fetched all movies')\n","sub_path":"HW1/Q1/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":4034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"165809792","text":"import os\nimport sys\nfrom subprocess import Popen, PIPE\nfrom queue import Queue, Empty # python 3.x\nfrom threading import Thread\nfrom time import sleep\nimport numpy as np\nimport pandas as pd\nimport networkx as nx\nfrom functools import reduce\nfrom . import nodes as node_types\n\n# Non blocking IO solution from http://stackoverflow.com/a/4896288\nON_POSIX = 'posix' in sys.builtin_module_names\nTAG_PROCESS='_process'\nTAG_MODEL='_model'\nTAG_RUN_INDEX='_run_idx'\nTAG_GENERATION='_generation'\nMETA_TAGS=[TAG_PROCESS,TAG_MODEL,TAG_RUN_INDEX,TAG_GENERATION]\nDEFAULT_TIMESTEPS=365\nLINK_TABLE_COLUMNS = ['%s_%s'%(n,c) for n in ['src','dest'] for c in ['generation','model','node','gen_node','var']]\n\ndef connections_match(o,i):\n o_node,_,o_alias,o_tags = o\n i_node,_,i_alias,i_tags = i\n\n if o_alias != i_alias:\n# print('aliases do not match')\n return False\n o_tags = o_tags.copy()\n o_tags.update(o_node.tags)\n i_tags = i_tags.copy()\n i_tags.update(i_node.tags)\n common_keys = list(set(o_tags.keys()).intersection(i_tags.keys()))\n for ck in common_keys:\n if ck in ['_process','_model']: continue\n if o_tags[ck] != i_tags[ck]:\n# print('common key (%s) does not match (%s vs %s)'%(ck,o_node.tags[ck],i_node.tags[ck]))\n return False\n\n return True\n\nclass OWTemplate(object):\n def __init__(self,lbl=''):\n self.label=lbl\n self.nodes = []\n self.links = []\n self.nested = []\n self.inputs = []\n self.outputs = []\n\n def define_input(self,node,name=None,alias=None,**kwargs):\n if name is None:\n # Would be nice to have a short hand to define every input of this\n # node as an input to the graph (and similarly every output of a node\n # as an output of the graph\n # But the node currently stores the model name)\n pass\n\n if alias is None:\n alias = name\n self.inputs.append((node,name,alias,kwargs))\n\n def define_output(self,node,name=None,alias=None,**kwargs):\n if alias is None:\n alias = name\n self.outputs.append((node,name,alias,kwargs))\n\n def add_node(self,model_type=None,name=None,process=None,**tags):\n # if hasattr(node_or_name,'model_type'):\n # self.nodes.append(node_or_name)\n # else:\n if process and not TAG_PROCESS in tags:\n tags[TAG_PROCESS]=process\n\n new_node = OWNode(model_type,name,**tags)\n self.nodes.append(new_node)\n return new_node\n\n def add_link(self,link):\n self.links.append(link)\n\n def flatten(self):\n '''\n Generate a single, flat template containing all nested\n templates, instantiating links between nested templates based\n on input and output descriptions.\n\n When instantiating links, the order of the nested templates matters,\n with links only instantiated from outputs of earlier nested templates to\n inputs of later nested templates.\n '''\n result = OWTemplate(self.label)\n result.nodes += self.nodes\n result.links += self.links\n\n result.inputs += self.inputs\n result.outputs += self.outputs\n\n flattened = [t.flatten() for t in self.nested]\n available_outputs = []\n used_outputs = []\n for child in flattened:\n result.nodes += child.nodes\n result.links += child.links\n\n for child_input in child.inputs:\n input_linked = False\n for previous_output in available_outputs:\n if connections_match(previous_output,child_input):\n# print('linking',previous_output,child_input)\n result.add_link(OWLink(previous_output[0],previous_output[1],child_input[0],child_input[1]))\n used_outputs.append(previous_output)\n input_linked = True\n if not input_linked:\n result.inputs.append(child_input)\n\n available_outputs += child.outputs\n #unused_outputs = set(available_outputs).difference(set(used_outputs))\n unused_outputs = [o for o in available_outputs if not o in used_outputs]\n result.outputs+= list(unused_outputs)\n return result\n\n def nest(self,other):\n '''\n Add all nodes and links from other to this template,\n connecting all outputs from this template to inputs in other AND\n\n '''\n self.nested.append(other)\n\n def instantiate(self,**instance_tags):\n res = OWTemplate()\n node_map = {}\n for n in self.nodes:\n new_node = res.add_node(n.model_type,**n.tags,**instance_tags)\n node_map[n.name] = new_node\n\n for l in self.links:\n new_from = node_map[l.from_node.name]\n new_to = node_map[l.to_node.name]\n new_link = res.add_link(OWLink(new_from,l.from_output,new_to,l.to_input))\n\n return res\n\nclass OWNode(object):\n def __init__(self,model_type,name=None,**tags):\n self.model_type = model_type\n if hasattr(model_type,'name'):\n self.model_name = model_type.name\n self.model_type = model_type\n else:\n self.model_name = model_type\n import openwater.nodes as node_types\n from openwater.discovery import discover\n discover()\n self.model_type = getattr(node_types,self.model_name)\n\n self.tags = tags\n self.tags[TAG_MODEL] = self.model_name\n\n if name:\n self.name = name\n else:\n self.name = self.make_name()\n\n def make_name(self):\n std_names = ['catchment','model',TAG_PROCESS,'constituent','hru','lu']\n for k in sorted(self.tags.keys()):\n if k.startswith('_'):continue\n\n if not k in std_names:\n std_names.append(k)\n return '-'.join([str(self.tags.get(k,None)) for k in std_names if k in self.tags])\n\n def __str__(self):\n return '%s (%s)'%(self.name,self.model_name)\n\nclass OWLink(object):\n def __init__(self,from_node,from_output,to_node,to_input):\n self.from_node = from_node\n self.from_output = from_output\n self.to_node = to_node\n self.to_input = to_input\n\n# class OWSystem(object):\n# def __init__(self):\n# self.nodes = []\n# self.links = []\n\n# def add_node(self,name,)\n\ndef template_to_graph(g,tpl,**tags):\n if not g:\n g = nx.DiGraph()\n nodes = {}\n nw = tpl.instantiate(**tags)\n for n in nw.nodes:\n g.add_node(str(n),**n.tags)\n nodes[str(n)] = n\n \n for l in nw.links:\n key = (str(nodes[str(l.from_node)]),str(nodes[str(l.to_node)]))\n if key in g.edges:\n existing = g.edges[key]\n existing['src'].append(l.from_output)\n existing['dest'].append(l.to_input)\n continue\n\n g.add_edge(key[0],key[1],\n src=[l.from_output],dest=[l.to_input])\n\n return g\n\ndef node_matches(n,**kwargs):\n for k,v in kwargs.items():\n if not k in n:\n return False\n if n[k]!=v:\n return False\n return True\n\ndef match_nodes(g,**kwargs):\n return [name for name,node in g.nodes.items() if node_matches(node,**kwargs)]\n\ndef model_type(n):\n return str(n).split('(')[1][:-1]\n\ndef group_run_order(g):\n ancestors_by_node = {}\n by_node_type_gen = {}\n node_gen = {}\n for n in list(g.nodes):\n ancestors = nx.ancestors(g,n)\n ancestors_by_node[n] = ancestors\n\n mt = model_type(n)\n \n if not mt in by_node_type_gen:\n by_node_type_gen[mt] = {}\n \n n_ancestors = len(ancestors)\n if not n_ancestors in by_node_type_gen[mt]:\n by_node_type_gen[mt][n_ancestors] = []\n by_node_type_gen[mt][n_ancestors].append(n)\n node_gen[n]=n_ancestors\n return ancestors_by_node,by_node_type_gen,node_gen\n\ndef assign_stages(order,node_gen,by_node_type_gen):\n done = {}\n stages = []\n i = 0\n for n in order:\n if n in done: continue\n\n gen = node_gen[n]\n mt = model_type(n)\n others = by_node_type_gen[mt][gen]\n while len(stages) <= gen:\n stages.append([])\n\n stages[gen] += others\n for o in others: done[o]=i\n i += 1\n return stages\n\ndef map_stages(stages):\n result = {}\n for i,s in enumerate(stages):\n for n in s:\n result[n] = i\n return result\n\nTHRESHOLD_N_JOBS=500\ndef find_first_small_stage(stages):\n for i,s in enumerate(stages):\n if len(s)1)}\n dimension_values = {d:vals for d,vals in dim_values.items() if (len(vals)>1) or (len(node_set)==1)}\n dimensions = [d for d in dimensions if not d in attributes]\n\n if not len(dimensions):\n print(attributes)\n print(len(node_set))\n raise 'No dimensions'\n\n if len([d for d in dimensions if len(dimension_values[d])==0]):\n print('Dimension(s) with 0 length:',dimension_values)\n raise Exception('Dimension(s) with 0 length')\n # dims = tags_by_process[p]\n # dimensions = [distinct_values[d] for d in dims]\n shape = tuple([len(self.distinct_values[d]) for d in dimensions])\n\n model_instances = np.ones(shape=shape,dtype=np.uint32) * -1\n for node_name in node_set:\n node = nodes[node_name]\n\n loc = tuple([self.distinct_values[d].index(node[d]) for d in dimensions])\n if len(loc) < len(shape):\n print(loc,node)\n model_instances[loc] = node[TAG_RUN_INDEX]\n\n return dimension_values, attributes,model_instances\n\n def _write_model_groups(self,f,n_timesteps):\n models_grp = f.create_group('MODELS')\n nodes = self._graph.nodes\n\n models = {nodes[n][TAG_MODEL] for n in nodes}\n self.model_batches = {}\n for m in models:\n model_grp = models_grp.create_group(m)\n\n model_nodes = [n for n in nodes if nodes[n][TAG_MODEL]==m]\n processes_for_model = {nodes[n][TAG_PROCESS] for n in model_nodes}\n assert(len(processes_for_model)==1) # not necessary?\n\n dims,attributes,instances = self._map_process(model_nodes)\n ds = model_grp.create_dataset('map',dtype=instances.dtype,data=instances,fillvalue=-1)\n\n # write out model index\n ds.attrs['PROCESSES']=[np.string_(s) for s in list(processes_for_model)]\n ds.attrs['DIMS']=[np.string_(d) for d in dims]\n for attr,val in attributes.items():\n ds.attrs[attr]=val\n\n self.model_batches[m] = np.cumsum([len([n for n in gen if nodes[n][TAG_MODEL]==m]) for gen in self.order])\n\n model_meta = getattr(node_types,m)\n if hasattr(model_meta,'description'):\n desc = model_meta.description\n n_states = len(desc['States']) # Compute, based on parameters...\n n_params = len(desc['Parameters'])\n n_inputs = len(desc['Inputs'])\n else:\n print('No description for %s'%m)\n desc = None\n n_states = 3\n n_params = 4\n n_inputs = 2\n\n# batch_counts = [len(mc.get(m,[])) for mc in model_counts_by_generation]\n\n model_grp.create_dataset('batches',shape=(len(self.order),),dtype=np.uint32,data=self.model_batches[m],fillvalue=-1)\n\n n_cells = instances.size\n # Init states....\n model_grp.create_dataset('states',shape=(n_cells,n_states),dtype=np.float64,fillvalue=0)\n\n model_grp.create_dataset('parameters',shape=(n_params,n_cells),dtype=np.float64,fillvalue=0)\n\n model_grp.create_dataset('inputs',shape=(n_cells,n_inputs,n_timesteps),dtype=np.float64,fillvalue=0)\n\n if (self._parameteriser is not None) and (desc is not None):\n node_dict = {n:nodes[n] for n in model_nodes}\n self._parameteriser.parameterise(model_meta,model_grp,instances,dims,node_dict)\n\n def gen_index(self,node):\n global_idx = node['_run_idx']\n model_name = node['_model']\n gen = node['_generation']\n if gen:\n start_of_gen = self.model_batches[model_name][gen-1]\n else:\n start_of_gen = 0\n return global_idx - start_of_gen\n\n def link_table(self):\n model_lookup = dict([(m,i) for i,m in enumerate(self.model_names)])\n link_table = []\n\n for l_from,l_to in self._graph.edges:\n link_data = self._graph.edges[(l_from,l_to)]\n for src_var,dest_var in zip(link_data['src'],link_data['dest']):\n link = {}\n f_node = self._graph.nodes[l_from]\n t_node = self._graph.nodes[l_to]\n\n link['src_generation'] = f_node['_generation']\n link['src_model'] = model_lookup[f_node['_model']]\n link['src_node'] = f_node['_run_idx']\n link['src_gen_node'] = self.gen_index(f_node)\n link['src_var'] = self._flux_number(l_from,'output',src_var)\n\n link['dest_generation'] = t_node['_generation']\n link['dest_model'] = model_lookup[t_node['_model']]\n link['dest_node'] = t_node['_run_idx']\n link['dest_gen_node'] = self.gen_index(t_node)\n link['dest_var'] = self._flux_number(l_to,'input',dest_var)\n link_table.append(link)\n link_table = pd.DataFrame(link_table)\n col_order = LINK_TABLE_COLUMNS\n link_table = link_table[col_order]\n sort_order = ['src_generation','src_model','src_gen_node','dest_generation','dest_model','dest_gen_node']\n return link_table.sort_values(sort_order)\n\n def _write_links(self,f):\n table = np.array(self.link_table())\n f.create_dataset('LINKS',dtype=np.uint32,data=table)\n\ndef dim_val(v):\n if hasattr(v,'decode'):\n return v.decode()\n return v\n\nclass ModelFile(object):\n def __init__(self,fn):\n self.filename = fn\n import h5py\n self._h5f = h5py.File(self.filename,'r')\n self._dimensions = {k:[dim_val(d) for d in self._h5f['DIMENSIONS'][k][...]] for k in self._h5f['DIMENSIONS']}\n # print(self._dimensions)\n self._links = pd.DataFrame(self._h5f['LINKS'][...],columns=LINK_TABLE_COLUMNS)\n self._models = self._h5f['META']['models'][...]\n self._parameteriser = None\n\n def _matches(self,model,**tags):\n model_dims = [d.decode() for d in self._h5f['MODELS'][model]['map'].attrs['DIMS']]\n # print(model_dims)\n lookup = {}\n for tag,value in tags.items():\n if not tag in model_dims:\n return False\n if not value in self._dimensions[tag]:\n return False\n lookup[tag] = self._dimensions[tag].index(value)\n idx = [lookup.get(d,slice(None,None)) for d in model_dims]\n # print(model,list(zip(model_dims,idx)))\n return np.any(self._h5f['MODELS'][model]['map'][tuple(idx)] > 0)\n\n def models_matching(self,**tags):\n result = []\n for k in self._h5f['MODELS']:\n # print(k)\n if self._matches(k,**tags):\n result.append(k)\n return result\n\n def _map_model_dims(self,model):\n model_map = self._h5f['MODELS'][model]['map'][...]\n m_dims = [dim_val(d) for d in self._h5f['MODELS'][model]['map'].attrs['DIMS']]\n dims = {d:self._h5f['DIMENSIONS'][d][...] for d in m_dims}\n dim_indices = list(zip(*np.where(model_map>=0)))#np.logical_not(np.isnan(model_map)))))\n def translate_dims(tpl):\n return [dim_val(dims[d][ix]) for d,ix in zip(m_dims,tpl)]\n\n dim_columns = [translate_dims(di)+[model_map[di]] for ix,di in enumerate(dim_indices) if model_map[di]>=0]\n\n return {d:[di[i] for di in dim_columns] for i,d in enumerate(m_dims+['_run_idx'])}\n\n def parameters(self,model,**tags):\n vals = self._h5f['MODELS'][model]['parameters'][...]\n desc = getattr(node_types,model)\n names = [p['Name'] for p in desc.description['Parameters']]\n\n result = pd.DataFrame(self._map_model_dims(model))\n print(vals.shape)\n order = list(result['_run_idx'])\n for ix,name in enumerate(names):\n result[name] = vals[ix,:][order]\n\n # result = pd.DataFrame(vals.transpose(),columns=names)\n # for k,vals in dims.items():\n # result = result[:len(vals)]\n # result[k] = vals\n\n for k,v in tags.items():\n result = result[result[k]==v]\n\n return result\n\n def write(self):\n try:\n self._h5f.close()\n import h5py\n self._h5f = h5py.File(self.filename,'r+')\n if self._parameteriser is None:\n print('Nothing to do')\n return\n\n models_grp = self._h5f['MODELS']\n models = list(models_grp.keys())\n for m in models:\n print('Parameterising %s'%str(m))\n model_grp = models_grp[m]\n\n instances = model_grp['map'][...]\n dims = [dim_val(d) for d in model_grp['map'].attrs['DIMS']]\n\n dim_map = self._map_model_dims(m)\n\n nodes = ['%s-%d'%(m,ix) for ix in range(len(dim_map[dims[0]]))]\n\n # dims,attributes,instances = self._map_process(model_nodes)\n\n model_meta = getattr(node_types,m)\n\n node_dict = {n:{d:vals[ix] for d,vals in dim_map.items()} for ix,n in enumerate(nodes)}\n\n self._parameteriser.parameterise(model_meta,model_grp,instances,dims,node_dict)\n finally:\n self._h5f.close()\n self._h5f = h5py.File(self.filename,'r')\n\n def run(self,time_period,results_fn=None,**kwargs):\n '''\n\n kwargs: Arguments and fflags to pass directly to ow-sim, including:\n\n * overwrite (boolean): Overwrite existing output file if it exists\n * verbose (boolean): Show verbose logging during simulation\n '''\n return _run(time_period,self.filename,results_fn,**kwargs)\n\ndef _run(time_period,model_fn=None,results_fn=None,**kwargs):\n '''\n\n kwargs: Arguments and fflags to pass directly to ow-sim, including:\n\n * overwrite (boolean): Overwrite existing output file if it exists\n * verbose (boolean): Show verbose logging during simulation\n '''\n from openwater.discovery import _exe_path\n from openwater.results import OpenwaterResults\n\n if not results_fn:\n base,ext = os.path.splitext(model_fn)\n results_fn = '%s_outputs%s'%(base,ext)\n print('INFO: No output filename provided. Writing to %s'%results_fn)\n\n # flags = ' '.join([ow_sim_flag_text(k,v) \n cmd_line = [_exe_path('sim')]\n for k,v in kwargs.items():\n cmd_line.append(ow_sim_flag_text(k,v))\n cmd_line.append(model_fn),\n cmd_line.append(results_fn)\n # \"%s %s %s %s\"%(_exe_path('sim'),flags,model_fn,results_fn)\n\n proc = Popen(cmd_line,stdout=PIPE,stderr=PIPE,bufsize=1, close_fds=ON_POSIX)\n std_out_queue,std_out_thread = configure_non_blocking_io(proc,'stdout')\n std_err_queue,std_err_thread = configure_non_blocking_io(proc,'stderr')\n\n err = []\n out = []\n finished = False\n while not finished:\n if proc.poll() is not None:\n finished = True\n\n end_stream=False\n while not end_stream:\n try:\n line = std_err_queue.get_nowait().decode('utf-8')\n err.append(line)\n print('ERROR %s'%(line,))\n sys.stdout.flush()\n except Empty:\n end_stream = True\n\n end_stream = False\n while not end_stream:\n try:\n line = std_out_queue.get_nowait().decode('utf-8')\n out.append(line)\n print(line)\n sys.stdout.flush()\n except Empty:\n end_stream = True\n sleep(0.05)\n\n return OpenwaterResults(model_fn,results_fn,time_period)\n\ndef run_simulation(model,output='model_outputs.h5',overwrite=False):\n import openwater.discovery\n cmd = '%s/ow-sim'%openwater.discovery.OW_BIN\n if overwrite:\n cmd += ' -overwrite'\n cmd = '%s %s %s'%(cmd,model,output)\n res = os.system(cmd)\n return res\n\ndef _enqueue_output(out, queue):\n for line in iter(out.readline, b''):\n queue.put(line)\n out.close()\n\ndef configure_non_blocking_io(proc,stream):\n queue = Queue()\n thread = Thread(target=_enqueue_output,args=(getattr(proc,stream),queue))\n thread.daemon = True\n thread.start()\n return queue,thread\n\ndef ow_sim_flag_text(k,v):\n if v == False:\n return ''\n if v == True:\n return '-%s'%k\n return '-%s %s'%(k,str(v))\n\n","sub_path":"openwater/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":31148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"249323356","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nfrom datetime import date\nfrom dateutil.relativedelta import relativedelta\nimport shutil\n\ntry:\n from .database import read_dfs\n from .common import dump_iter_to_csv\nexcept SystemError:\n from database import read_dfs \n from common import dump_iter_to_csv\n\n\nXLFILE = \"kep.xls\"\n\ndef get_end_of_monthdate(y,m):\n return date(year=y, month=m, day=1) + relativedelta(months=+1) + relativedelta(days = -1)\n\ndef get_end_of_quarterdate(y,q):\n return date(y,1,1) + relativedelta (months = q*3) + relativedelta (days = -1)\n \ndef duplicate_labels(df):\n r = df[df.duplicated(['label','year']) == True]\n return r['label'].unique()\n\ndef check_for_dups(df): \n dups = duplicate_labels(df)\n if len(dups) > 0:\n raise Exception(\"Duplicate labels: \" + \" \".join(dups))\n\ndef reshape_all(dfa, dfq, dfm):\n return reshape_a(dfa), reshape_q(dfq), reshape_m(dfm)\n \ndef reshape_a(dfa):\n return dfa.pivot(columns='label', values = 'val', index = 'year')\n \ndef reshape_q(dfq):\n dt = [get_end_of_quarterdate(y,q) for y, q in zip(dfq[\"year\"], dfq[\"qtr\"])]\n dfq[\"time_index\"] = pd.DatetimeIndex(dt, freq = \"Q\")\n dfq = dfq.pivot(columns='label', values = 'val', index = 'time_index')\n dfq.insert(0, \"year\", dfq.index.year)\n dfq.insert(1, \"qtr\", dfq.index.quarter)\n return dfq\n\ndef reshape_m(dfm):\n dt = [get_end_of_monthdate(y,m) for y, m in zip(dfm[\"year\"], dfm[\"month\"])]\n dfm[\"time_index\"] = pd.DatetimeIndex(dt, freq = \"M\")\n dfm = dfm.pivot(columns='label', values = 'val', index = 'time_index')\n print(\"\\nMonthly vars:\")\n print(dfm.columns.values)\n dfm.insert(0, \"year\", dfm.index.year)\n dfm.insert(1, \"month\", dfm.index.month)\n return dfm\n\ndef write_to_xl(dfa, dfq, dfm):\n with pd.ExcelWriter(XLFILE) as writer:\n dfa.to_excel(writer, sheet_name='year')\n dfq.to_excel(writer, sheet_name='quarter')\n dfm.to_excel(writer, sheet_name='month') \n shutil.copy(XLFILE, \"..\")\n\n\ndef get_additional_header(df):\n # TODO 1: make a query on spec dictionary\n return [\"date\"] + df.columns.values.tolist()\n \ndef get_csvrows(df):\n strings = df.to_csv(sep = \"\\t\", decimal = \",\")\n # note: below will not be needed in pandas 0.16\n # undesired - will change . for , in headers too\n # TODO 2: get headers and datablock separately \n strings = strings.replace(\".\", \",\")\n return [x.split(\"\\t\") for x in strings.split(\"\\n\")]\n\ndef df_csv_iter(df):\n # TODO 3 restore original order of items as in spec dictionary + rebase df\n # TODO 4 this has to be stored in database, something with autoincrement\n yield get_additional_header(df) \n for row in get_csvrows(df):\n yield row\n \ndef to_csv(df, filename):\n dump_iter_to_csv(df_csv_iter(df), filename)\n\ndef write_to_csv(dfa, dfq, dfm):\n to_csv(dfa, \"annual.txt\")\n to_csv(dfq, \"qtr.txt\")\n to_csv(dfm, \"month.txt\") \n # TODO 5 - Also write this to Excel xls/xlsx too as sheets\n # TODO 6 - Write a sheet with varnames\n # TODO 7 - Check its complete\n \ndef db2xl():\n dfa, dfq, dfm = read_dfs()\n check_for_dups(dfa)\n dfa = reshape_a(dfa)\n dfq = reshape_q(dfq)\n dfm = reshape_m(dfm)\n write_to_xl(dfa, dfq, dfm)\n write_to_csv(dfa, dfq, dfm)\n\nif __name__ == \"__main__\":\n dfa, dfq, dfm = read_dfs()\n check_for_dups(dfa)\n dfa, dfq, dfm = reshape_all(dfa, dfq, dfm)\n write_to_xl(dfa, dfq, dfm)\n for y in df_csv_iter(dfa):\n print(y)\n \n# note- order on columns i lost, a-betic\n\n \n#TODO:\n# may change formatting of the columns http://xlsxwriter.readthedocs.org/en/latest/example_pandas_column_formats.html#ex-pandas-column-formats\n# http://stackoverflow.com/questions/17069694/writing-xlwt-dates-with-excel-date-format\n# http://stackoverflow.com/questions/9920935/easily-write-formatted-excel-from-python-start-with-excel-formatted-use-it-in\n# do not write second row - inherited from pivot. \n ","sub_path":"src/doc2db/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":3966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"218602811","text":"def search(x):\n global visited,n\n for i in range(0,n):\n if edge[x][i]:\n if visited[i]==-1:\n visited[i]=x\n search(i)\n elif visited[i]!=x:\n return False\n return True\n \nee=eval(input())\nn=len(ee)\nedge=[[False for i in range(0,n)]for i in range(0,n)]\nrepeated=False\nfor i in range(0,n):\n if edge[ee[i][0]-1][ee[i][1]-1]==True:\n repeated=True\n print(ee[i])\n break\n else:\n edge[ee[i][0]-1][ee[i][1]-1]=True\n edge[ee[i][1]-1][ee[i][0]-1]=True\nif not repeated:\n for i in range(n-1,-1,-1):\n visited=[-1 for i in range(0,n)]\n edge[ee[i][0]-1][ee[i][1]-1]=False\n edge[ee[i][1]-1][ee[i][0]-1]=False\n repeated=search(0)\n edge[ee[i][0]-1][ee[i][1]-1]=True\n edge[ee[i][1]-1][ee[i][0]-1]=True\n if repeated:\n print(ee[i])\n break","sub_path":"Code/CodeRecords/2704/60670/307258.py","file_name":"307258.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"480244589","text":"import os\r\nimport sqlite3\r\n\r\nimport discord\r\nfrom discord.ext import commands\r\n\r\nfrom dotenv import load_dotenv\r\n\r\nfrom database import inserts\r\nfrom database import selects\r\nfrom database import deletes\r\nfrom database import updates\r\nfrom database import util as db_util\r\n\r\nfrom bot import error_messages\r\nfrom bot import util\r\n\r\nload_dotenv()\r\nTOKEN = os.getenv(\"DISCORD_TOKEN\")\r\n\r\nbot = commands.Bot(command_prefix=\"!\")\r\n\r\n# Messages that appear when the user hits !help\r\nhelp_messages = {\r\n \"new\": \"Insert !new followed by the type of item, then add in the entries.\"\r\n \"For example: !new region Drydock \\\"the main city\\\"\",\r\n \"list-all\": \"Insert !list-all followed by the type of item. For example: !list-all region\",\r\n \"select\": \"Insert !select followed by the type of item and the descriptors for that item. \"\r\n \"Note that a space should not exist between descriptor category and value. \"\r\n \"For example: !select region name=Drydock\",\r\n \"delete-all\": \"Insert !delete-all followed by the category name to clear everything from that category. \"\r\n \"For example: !delete-all region\",\r\n \"delete\": \"Insert !delete followed by the type of item and the descriptors for that item. \"\r\n \"Note that a space should not exist between descriptor category and value. \"\r\n \"For example: !delete region name=Drydock\",\r\n \"edit\": \"Insert !select followed by the type of item and the descriptors for that item. \"\r\n \"Note that a space should not exist between descriptor category and value. \"\r\n \"Insert a : between the old descriptors and the desired changes\"\r\n \"For example: !edit region name=Drydock : name=Dockdry\",\r\n \"sqlite\": \"Directly run an SQLite query. Type !sqlite then follow it with the query. \"\r\n \"For example: !sqlite SELECT * FROM regions\",\r\n \"drydock-characters\": \"List all the player and npc characters in Drydock.\",\r\n \"list-dead\": \"List all the dead characters\",\r\n \"list-living\": \"List all the living characters\",\r\n \"items-owned\": \"List all the items owned by a particular character\",\r\n \"class-chars\": \"List all the characters in a particular class\",\r\n \"org-chars\": \"List all the characters in a particular organization\",\r\n \"total-items\": \"List the total amount of items owned by a particular character\"\r\n}\r\n\r\n\r\n@bot.event\r\nasync def on_ready():\r\n print(f'{bot.user} has connected to Discord!')\r\n\r\n\r\n# Used to add a new entry to a table\r\n@bot.command(name=\"new\", help=help_messages[\"new\"])\r\nasync def new(ctx, table, *args):\r\n try:\r\n table = table.lower().strip()\r\n if table == \"region\":\r\n inserts.insert_region(name=args[0], description=args[1])\r\n elif table == \"location\":\r\n inserts.insert_location(name=args[0], description=args[1], region=args[2])\r\n elif table == \"organization\":\r\n inserts.insert_organization(name=args[0], description=args[1], region=args[2])\r\n elif table == \"class\":\r\n inserts.insert_class(name=args[0], description=args[1], source=args[2])\r\n elif table == \"player-characters\":\r\n inserts.insert_pcs(player=args[0], name=args[1], description=args[2], alive=args[3], dnd_class=args[4],\r\n origin=args[5], area=args[6])\r\n elif table == \"npcs\":\r\n inserts.insert_npcs(name=args[0], description=args[1], region=args[2])\r\n elif table == \"items\":\r\n inserts.insert_item(name=args[0], description=args[1])\r\n else:\r\n await ctx.send(error_messages.INVALID_CATEGORY)\r\n except IndexError:\r\n await ctx.send(error_messages.ENTRY_LENGTH)\r\n\r\n\r\n# List every entry in a table\r\n@bot.command(name=\"list-all\", help=help_messages[\"list-all\"])\r\nasync def list_all(ctx, table):\r\n try:\r\n results = selects.select_all(table)\r\n\r\n titles = results[\"titles\"]\r\n title_string = \" | \"\r\n for title in titles:\r\n title_string += title + \" | \"\r\n await ctx.send(title_string)\r\n\r\n data = results[\"data\"]\r\n for entry in data:\r\n entry_string = \" | \"\r\n for point in entry:\r\n entry_string += str(point) + \" | \"\r\n await ctx.send(entry_string)\r\n\r\n except sqlite3.OperationalError:\r\n await ctx.send(error_messages.INVALID_CATEGORY)\r\n except discord.ext.commands.errors.MissingRequiredArgument:\r\n await ctx.send(error_messages.INVALID_CATEGORY)\r\n\r\n\r\n# Select an entry from a table\r\n@bot.command(name=\"select\", help=help_messages[\"select\"])\r\nasync def select(ctx, table, *args):\r\n try:\r\n conditions = util.trim_args(args)\r\n output = selects.select(table, conditions)\r\n await ctx.send(output)\r\n except IndexError:\r\n await ctx.send(error_messages.CONDITION_SYNTAX)\r\n except sqlite3.OperationalError:\r\n await ctx.send(error_messages.INVALID_CATEGORY)\r\n except discord.ext.commands.errors.MissingRequiredArgument:\r\n await ctx.send(error_messages.INVALID_CATEGORY)\r\n\r\n\r\n# Delete every entry in a table\r\n@bot.command(name=\"delete-all\", help=help_messages[\"delete-all\"])\r\nasync def delete_all(ctx, table):\r\n try:\r\n deletes.delete_all(table)\r\n await ctx.send(\"Successfully deleted all from: \" + table)\r\n except sqlite3.OperationalError:\r\n await ctx.send(error_messages.INVALID_CATEGORY)\r\n except discord.ext.commands.errors.MissingRequiredArgument:\r\n await ctx.send(error_messages.INVALID_CATEGORY)\r\n\r\n\r\n# Delete a particular entry in a table\r\n@bot.command(name=\"delete\", help=help_messages[\"delete\"])\r\nasync def delete(ctx, table, *args):\r\n try:\r\n conditions = util.trim_args(args)\r\n deletes.delete(table, conditions)\r\n await ctx.send(\"Deleted Successfully!\")\r\n except IndexError:\r\n await ctx.send(error_messages.CONDITION_SYNTAX)\r\n except sqlite3.OperationalError:\r\n await ctx.send(error_messages.INVALID_CATEGORY)\r\n except discord.ext.commands.errors.MissingRequiredArgument:\r\n await ctx.send(error_messages.INVALID_CATEGORY)\r\n\r\n\r\n# Edit an entry in a table\r\n@bot.command(name=\"edit\", help=help_messages[\"edit\"])\r\nasync def edit(ctx, table, *args):\r\n try:\r\n entries = util.split_tuple(args, \":\")\r\n conditions = util.trim_args(entries[0])\r\n changes = util.trim_args(entries[1])\r\n updates.update(table, changes=changes, conditions=conditions)\r\n await ctx.send(\"Changed data successfully!\")\r\n except IndexError:\r\n await ctx.send(error_messages.CONDITION_SYNTAX)\r\n except sqlite3.OperationalError:\r\n await ctx.send(error_messages.INVALID_CATEGORY)\r\n except discord.ext.commands.errors.MissingRequiredArgument:\r\n await ctx.send(error_messages.INVALID_CATEGORY)\r\n\r\n\r\n# Run an SQLite query from Discord\r\n@bot.command(name=\"sqlite\", help=help_messages[\"sqlite\"])\r\nasync def sqlite(ctx, *args):\r\n query = \"\"\r\n for arg in args:\r\n query += arg\r\n query += \" \"\r\n try:\r\n db_util.commit_query(query)\r\n await ctx.send(\"Query operated successfully\")\r\n except sqlite3.OperationalError:\r\n await ctx.send(error_messages.QUERY_SYNTAX)\r\n except discord.ext.commands.errors.MissingRequiredArgument:\r\n await ctx.send(error_messages.INVALID_CATEGORY)\r\n\r\n\r\n@bot.command(name=\"drydock-characters\", help=help_messages[\"drydock-characters\"])\r\nasync def drydock_chars(ctx):\r\n await ctx.send(selects.drydock_chars())\r\n\r\n\r\n@bot.command(name=\"list-dead\", help=help_messages[\"list-dead\"])\r\nasync def list_dead(ctx):\r\n await ctx.send(selects.list_dead())\r\n\r\n\r\n@bot.command(name=\"list-living\", help=help_messages[\"list-living\"])\r\nasync def list_living(ctx):\r\n await ctx.send(selects.list_living())\r\n\r\n\r\n@bot.command(name=\"items-owned\", help=help_messages[\"items-owned\"])\r\nasync def items_owned(ctx, player):\r\n try:\r\n if player.isnumeric():\r\n await ctx.send(selects.items_owned(owner_id=player))\r\n else:\r\n await ctx.send(selects.items_owned(owner_name=player))\r\n except sqlite3.OperationalError:\r\n await ctx.send(error_messages.QUERY_SYNTAX)\r\n\r\n\r\n@bot.command(name=\"class-chars\", help=help_messages[\"class-chars\"])\r\nasync def class_chars(ctx, dnd_class):\r\n try:\r\n if dnd_class.isnumeric():\r\n await ctx.send(selects.class_chars(class_id=dnd_class))\r\n else:\r\n await ctx.send(selects.class_chars(class_name=dnd_class))\r\n except sqlite3.OperationalError:\r\n await ctx.send(error_messages.QUERY_SYNTAX)\r\n\r\n\r\n@bot.command(name=\"org-chars\", help=help_messages[\"org-chars\"])\r\nasync def org_chars(ctx, org):\r\n try:\r\n if org.isnumeric():\r\n await ctx.send(selects.org_chars(org_id=org))\r\n else:\r\n await ctx.send(selects.org_chars(org_name=org))\r\n except sqlite3.OperationalError:\r\n await ctx.send(error_messages.QUERY_SYNTAX)\r\n\r\n\r\n@bot.command(name=\"total-items\", help=help_messages[\"total-items\"])\r\nasync def total_items(ctx, character):\r\n try:\r\n if character.isnumeric():\r\n await ctx.send(selects.total_owned(char_id=character))\r\n else:\r\n await ctx.send(selects.total_owned(char_name=character))\r\n except sqlite3.OperationalError:\r\n await ctx.send(error_messages.QUERY_SYNTAX)\r\n\r\n\r\nbot.run(TOKEN)\r\n","sub_path":"bot/bot_maker.py","file_name":"bot_maker.py","file_ext":"py","file_size_in_byte":9389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"243753477","text":"import inflection\n\n\nclass NamedElement(object):\n def __init__(self, **kwargs):\n self.name = kwargs.pop('name', \"unnamed\")\n self.description = kwargs.pop('description', \"\")\n super(NamedElement, self).__init__(**kwargs)\n\n def __getattr__(self, name):\n l = {'CamelCase': lambda: inflection.camelize(self.name),\n 'camelCase': lambda: inflection.camelize(self.name, False),\n 'snake_case': lambda: inflection.underscore(self.name)}\\\n .get(name)\n\n if l:\n return l()\n try:\n return super(NamedElement, self).__getattr__(name)\n except:\n raise AttributeError(\"Attribute '%s' not found in %s.NamedElement\"\n % (name, self.__module__))\n","sub_path":"tools/sdbusplus/namedelement.py","file_name":"namedelement.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"368618188","text":"from suggestion_list import SuggestionList\n\nclass List(object):\n\t\"\"\"creates and returns a JSON response for List\"\"\"\n\tdef __init__(self, simpleResponse):\n\t\tsuper(List, self).__init__()\n\t\tprint(\"Inside custom list\")\n\t\tself.simpleResponse = simpleResponse\n\t\tself.listTitle = None\n\t\tself.expectedUserResponse = True\n\t\tself.sugTitles = None\n\t\tself.keyArr = []\n\t\tself.titleArr = []\n\t\tself.synArr = []\n\t\tself.descriptionArr = []\n\t\tself.imgURLArr = []\n\t\tself.imgAccTextArr = []\n\n\n\n\tdef removeExpectedUserResponse(self):\n\t\tself.expectedUserResponse = False\n\n\tdef addExpectedUserResponse(self):\n\t\tself.expectedUserResponse = True\n\n\tdef addSugTitles(self, sugTitles):\n\t\tself.sugTitles = sugTitles\n\n\tdef addListTitle(self, listTitle):\n\t\tself.listTitle = listTitle\n\n\tdef addListItem(self, key, title, syn, description, imgURL, imgAccText):\n\t\tself.keyArr.append(key)\n\t\tself.titleArr.append(title)\n\t\tself.synArr.append(syn)\n\t\tself.descriptionArr.append(description)\n\t\tself.imgURLArr.append(imgURL)\n\t\tself.imgAccTextArr.append(imgAccText)\n\n\tdef addCompleteListItem(self, keyArr, titleArr, synArr, descriptionArr, imgURLArr, imgAccTextArr):\n\t\tself.keyArr = keyArr\n\t\tself.titleArr = titleArr\n\t\tself.synArr = synArr\n\t\tself.descriptionArr = descriptionArr\n\t\tself.imgURLArr = imgURLArr\n\t\tself.imgAccTextArr = imgAccTextArr\n\n\tdef getListItemResponse(self, key, title, syn, description, imgURL, imgAccText):\n\t\tlistItemDict = {}\n\t\tlistItemDict[\"optionInfo\"] = {}\n\n\t\toptionInfoDict = listItemDict[\"optionInfo\"]\n\t\toptionInfoDict[\"key\"] = key\n\t\toptionInfoDict[\"synonyms\"] = []\n\n\t\tsynList = optionInfoDict[\"synonyms\"]\n\t\tsynList.append(syn)\n\n\t\tlistItemDict[\"title\"] = title\n\t\tlistItemDict[\"description\"] = description\n\n\t\tlistItemDict[\"image\"] = {}\n\n\t\timageDict = listItemDict[\"image\"]\n\t\timageDict[\"url\"] = imgURL\n\t\timageDict[\"accessibilityText\"] = imgAccText\n\n\t\treturn listItemDict\n\n\tdef getInteriorListResponse(self):\n\t\tsystemIntentDict = {}\n\t\tsystemIntentDict[\"intent\"] = \"actions.intent.OPTION\"\n\t\tsystemIntentDict[\"data\"] = {}\n\n\t\tdataDict = systemIntentDict[\"data\"]\n\t\tdataDict[\"@type\"] = \"type.googleapis.com/google.actions.v2.OptionValueSpec\"\n\t\tdataDict[\"listSelect\"] = {}\n\n\t\tlistSelectDict = dataDict[\"listSelect\"]\n\n\t\tif self.listTitle != \"\" and self.listTitle != None:\n\t\t\tlistSelectDict[\"title\"] = self.listTitle\n\n\t\tlistSelectDict[\"items\"] = []\n\n\t\titemList = listSelectDict[\"items\"]\n\n\t\tfor index in range(0, len(self.titleArr)):\n\t\t\titemList.append(self.getListItemResponse(self.keyArr[index], self.titleArr[index], \n\t\t\t\tself.synArr[index], self.descriptionArr[index], self.imgURLArr[index], self.imgAccTextArr[index]))\n\n\n\t\treturn systemIntentDict\n\n\n\tdef getListResponse(self):\n\t\tlistResponse = {}\n\t\titemsDict = {}\n\t\titemsDict[\"simpleResponse\"] = {}\n\t\tsimpleResponseDict = itemsDict[\"simpleResponse\"]\n\t\tsimpleResponseDict[\"textToSpeech\"] = self.simpleResponse[0]\n\n\t\t#Code to add multiple simple responses (Seems unwieldy & needs to be better done for a loop)\n\t\tif len(self.simpleResponse) > 1:\n\t\t\titemsDict1 = {}\n\t\t\titemsDict1[\"simpleResponse\"] = {}\n\t\t\tsimpleResponseDict1 = itemsDict1[\"simpleResponse\"]\n\t\t\tsimpleResponseDict1[\"textToSpeech\"] = self.simpleResponse[1]\n\n\t\t\n\t\tlistResponse[\"data\"] = {}\n\t\tlistResponse[\"source\"] = \"phillips-bot\"\n\t\tdataDict = listResponse[\"data\"]\n\n\t\tdataDict[\"google\"] = {}\n\t\tgoogleDict = dataDict[\"google\"]\n\n\t\tgoogleDict[\"expect_user_response\"] = self.expectedUserResponse\n\t\tgoogleDict[\"rich_response\"] = {}\n\n\n\t\trichResponseDict = googleDict[\"rich_response\"]\n\t\trichResponseDict[\"items\"] = []\n\n\n\t\titemList = richResponseDict[\"items\"]\n\t\titemList.append(itemsDict)\n\n\t\tif len(self.simpleResponse) > 1:\n\t\t itemList.append(itemsDict1)\n\n\n\n\t\tif self.sugTitles != \"\" and self.sugTitles != None:\n\t\t\tmySuggestionList = SuggestionList(self.sugTitles)\n\t\t\trichResponseDict[\"suggestions\"] = mySuggestionList.getSuggestionListResponse()\n\n\t\tgoogleDict[\"systemIntent\"] = self.getInteriorListResponse()\n\n\t\treturn listResponse","sub_path":"custom_list.py","file_name":"custom_list.py","file_ext":"py","file_size_in_byte":3915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"232025373","text":"import discord\n\nfrom discord.ext import commands\n\n\ndef to_keycap(c):\n return '\\N{KEYCAP TEN}' if c == 10 else str(c) + '\\u20e3'\n\n\nclass Polls:\n \"\"\"Poll voting system.\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(no_pm=True)\n async def quickpoll(self, ctx, *questions_and_choices: str):\n\n if len(questions_and_choices) < 3:\n return await ctx.send('Need at least 1 question with 2 choices.')\n elif len(questions_and_choices) > 11:\n return await ctx.send('You can only have up to 10 choices.')\n\n perms = ctx.channel.permissions_for(ctx.guild.me)\n if not (perms.read_message_history or perms.add_reactions):\n return await ctx.send('Need Read Message History and Add Reactions permissions.')\n\n question = questions_and_choices[0]\n choices = [(to_keycap(e), v)\n for e, v in enumerate(questions_and_choices[1:], 1)]\n\n try:\n await ctx.message.delete()\n except:\n pass\n\n fmt = '{0} asks: {1}\\n\\n{2}'\n answer = '\\n'.join('%s: %s' % t for t in choices)\n poll = await ctx.send(fmt.format(ctx.message.author, question.replace(\"@\", \"@\\u200b\"), answer))\n for emoji, _ in choices:\n await poll.add_reaction(emoji)\n\n @commands.command(pass_context=True, no_pm=True)\n async def poll(self, ctx, *questions_and_choices: str):\n msg = await ctx.send(\"**{}#{}** asks: {}\".format(ctx.message.author.name, ctx.message.author.discriminator, ctx.message.clean_content[5:]))\n await ctx.message.delete()\n if ctx.guild.id == 207943928018632705:\n # Essential :sexthumb:\n yes_thumb = discord.utils.get(\n ctx.guild.emojis, id=287711899943043072)\n no_thumb = discord.utils.get(\n ctx.guild.emojis, id=291798048009486336)\n else:\n yes_thumb = \"👍\"\n no_thumb = \"👎\"\n await msg.add_reaction(yes_thumb)\n await msg.add_reaction(no_thumb)\n\n\ndef setup(bot):\n bot.add_cog(Polls(bot))\n","sub_path":"cogs/poll.py","file_name":"poll.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"507734121","text":"def find_rigid_transform(a, b, visualize=False):\n \"\"\"\n Args:\n a: a 3xN array of vertex locations\n b: a 3xN array of vertex locations\n\n Returns: (R,T) such that R.dot(a)+T ~= b\n Based on Arun et al, \"Least-squares fitting of two 3-D point sets,\" 1987.\n See also Eggert et al, \"Estimating 3-D rigid body transformations: a\n comparison of four major algorithms,\" 1997.\n \"\"\"\n import numpy as np\n import scipy.linalg\n\n if a.shape[0] != 3:\n if a.shape[1] == 3:\n a = a.T\n if b.shape[0] != 3:\n if b.shape[1] == 3:\n b = b.T\n assert a.shape[0] == 3\n assert b.shape[0] == 3\n\n a_mean = np.mean(a, axis=1)\n b_mean = np.mean(b, axis=1)\n a_centered = a - a_mean.reshape(-1, 1)\n b_centered = b - b_mean.reshape(-1, 1)\n\n c = a_centered.dot(b_centered.T)\n u, s, v = np.linalg.svd(c, full_matrices=False)\n v = v.T\n R = v.dot(u.T)\n\n if scipy.linalg.det(R) < 0:\n if np.any(s == 0): # This is only valid in the noiseless case; see the paper\n v[:, 2] = -v[:, 2]\n R = v.dot(u.T)\n else:\n raise ValueError(\n \"find_rigid_transform found a reflection that it cannot recover from. Try RANSAC or something...\"\n )\n\n T = (b_mean - R.dot(a_mean)).reshape(-1, 1)\n\n if visualize != False:\n from lace.mesh import Mesh\n from lace.meshviewer import MeshViewer\n\n mv = MeshViewer() if visualize is True else visualize\n a_T = R.dot(a) + T\n mv.set_dynamic_meshes(\n [\n Mesh(v=a.T, f=[]).set_vertex_colors(\"red\"),\n Mesh(v=b.T, f=[]).set_vertex_colors(\"green\"),\n Mesh(v=a_T.T, f=[]).set_vertex_colors(\"orange\"),\n ]\n )\n\n return R, T\n","sub_path":"polliwog/transform/rigid_transform.py","file_name":"rigid_transform.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"556664609","text":"import math\n\na = int(input(\"请输入一个整数: \"))\nb = []\nc = int(math.sqrt(a) + 1)\ni = 2\nif a!=1:\n while i <= int(math.sqrt(a) + 1):\n while a % i == 0:\n b.append(i)\n a //= i\n i += 1\n if a > 1:\n b.append(a)\nelse:\n b.append(1)\nd = str()\nfor i in range(0, len(b)):\n if i != len(b) - 1:\n d = d + str(b[i]) + \"*\"\n else:\n d = d + str(b[i])\nprint(d)\n","sub_path":"homework/work2/factor.py","file_name":"factor.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"328680753","text":"n=int(input(\"n-ésima aproximação:\"))\ni=1\na=1\np=0\ns=1\nwhile(a<=n):\n\tp+=(4/i)*s\n\ti+=2\n\ta+=1\n\ts*= -1\nprint(round(p,8))\n","sub_path":"exs-s/1142/1355-1142.py","file_name":"1355-1142.py","file_ext":"py","file_size_in_byte":119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"234211449","text":"from datetime import date, datetime, time, timedelta\n\nimport matplotlib.animation as animation\nimport matplotlib.pyplot as plt\nimport mplfinance as mpf\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport yfinance as yf\nfrom market_profile import MarketProfile\n\n## Class to simulate getting more data from API:\n\nclass RealTimeAPI():\n def __init__(self, df):\n self.data_pointer = 0\n self.data_frame = df\n #self.data_frame = self.data_frame.iloc[0:120,:]\n self.df_len = len(self.data_frame)\n\n def fetch_next(self, interval=1):\n r1 = self.data_pointer\n self.data_pointer += interval\n if self.data_pointer >= self.df_len:\n return None\n return self.data_frame.iloc[r1:self.data_pointer,:]\n\n def initial_fetch(self):\n if self.data_pointer > 0:\n return\n r1 = self.data_pointer\n self.data_pointer += int(0.2*self.df_len)\n return self.data_frame.iloc[r1:self.data_pointer,:]\n\n\n########## DOWNLOAD YAHOO DATA #############\nsymbol = 'AAPL'\nsd = datetime(2020, 1, 1)\ned = datetime(2021, 2, 28)\ndfdata = yf.download(tickers=symbol, start=sd, end=ed, interval=\"60m\")\n\ndf = dfdata.copy()\n\n########### PREPROCESSINNG DF ###############\ndf['PriceUp'] = df['Close'].gt(df['Open'])\ndf['VolumeR'] = np.where(df['PriceUp']==True, df['Volume'], -1*df['Volume'])\n\n\n# pd.show_versions()\n\nrtapi = RealTimeAPI(df) # pass a dataframe with OHLCV data in Yahoo format \n\nresample_map ={'Open' :'first',\n 'High' :'max' ,\n 'Low' :'min' ,\n 'Close':'last' }\nresample_period = '15T'\n\ndf = rtapi.initial_fetch()\n# rs = df.resample(resample_period).agg(resample_map).dropna()\nrs = df.copy()\n\n# fig, axes = mpf.plot(rs,returnfig=True,figsize=(11,8),type='candle',title='\\n\\nGrowing Candle')\n# ax = axes[0]\n\nfig = plt.figure(figsize=(10,6))\n# ax = sns.distplot(d.Volume, x=d.Close,hist_kws={'weights':d.Volume}, bins = 100)\n# ax = plt.gca() # get currwent axis\nax0 = fig.add_axes ([0, 0, 0.8, 1])\nax = fig.add_axes ( [0.8, 0, 0.2, 1], sharey = ax0) \n\n# Create an array with the colors you want to use\ncolors = [\"#ff3061\", \"#00b061\",\"blue\", \"orange\"]# Set your custom color palette\ncustomPalette = sns.set_palette(sns.color_palette(colors))\n\"Kernel Density Estimator\"\nkde_factor = 0.05\nnum_samples = 500\n\ndef animate(ival):\n global df\n global rs\n global ax\n nxt = rtapi.fetch_next(interval=2)\n if nxt is None:\n print('no more data to plot')\n ani.event_source.interval *= 3\n if ani.event_source.interval > 12000:\n exit()\n return\n df = df.append(nxt)\n df = df.iloc[1:]\n # rs = df.resample(resample_period).agg(resample_map).dropna()\n ax0.clear()\n ax.clear()\n \n # mpf.plot(rs[:150],ax=ax0,type='candle', style='yahoo')\n mpf.plot(df[-200:],ax=ax0,type='candle', style='yahoo')\n # ax = sns.distplot(df.Volume, x=df.Close,hist_kws={'weights':df.VolumeR}, bins = 100)\n # ax = sns.histplot(data=df, x='Close', hue=\"PriceUp\", weights=df.Volume, bins = 100)\n # ax = sns.histplot(data=df, x='Close', weights=df.Volume, bins = 100)\n\n # ax = sns.histplot(data=df, x='Close', weights=df.Volume, bins = 50)\n # ax = sns.histplot(data=df, x='Close', weights=df.Volume, bins = 50, stat=\"density\")\n\n # ax = sns.histplot(data=df, x='Close', hue=\"PriceUp\", weights=df.Volume, bins=50, palette=customPalette, alpha=1)\n # ax = sns.histplot(data=df, x='Close', hue=\"PriceUp\", weights=df.Volume.astype(np.float64), bins=100, stat=\"density\", palette=customPalette, alpha=1) # normalize Y \n # ax = sns.histplot(data=df, x='Close', hue=\"PriceUp\", weights=df.Volume.astype(np.float64), bins=100, stat=\"density\", palette=customPalette, alpha=1, kde=True) # normalize Y \n\n # histogram with KDE \n # ax = sns.histplot(data=df, y='Close', hue=\"PriceUp\", weights=df.Volume.astype(np.float64), bins=100, stat=\"density\", palette=customPalette, alpha=1, kde=True, kde_kws={'bw_method': kde_factor}) # normalize Y \n \n # KDE only \n # ax = sns.kdeplot(data=df, y='Close', hue=\"PriceUp\", weights=df.Volume.astype(np.float64), palette=customPalette, alpha=0.2, bw_method=kde_factor, fill=True) # normalize Y \n\n\n # ##### [TESTING PARAMS] KDE only with last 150 \n ax = sns.kdeplot(data=df[-200:], y='Close', hue=\"PriceUp\", weights=df[-200:].Volume.astype(np.float64), palette=customPalette, alpha=0.2, bw_method=kde_factor, fill=True) # normalize Y \n\n \n \n \n \n close = float(df[-1:].Close)\n # print (\"Close\", close)\n # draw price line \n ax.axhline(close, ls='--', color='b')\n ax0.axhline(close, ls='--', color='b')\n ax0.text(y=close, x=ax0.get_xlim()[1]*0.70, s=\"{:.2f}\".format(close), alpha=0.7, color='b')\n\n # ax = sns.displot(df.Volume, x=df.Close, weights=df.Volume, bins = 50, hue=df.PriceUp) # weight Volume \n\n# ani = animation.FuncAnimation(fig, animate, interval=5)\nani = animation.FuncAnimation(fig, animate, interval=250)\n\nplt.show()\n\n# from IPython.display import HTML\n# HTML(ani.to_jshtml())\n\n\n# \n# from IPython.display import HTML\n# # HTML(ani.to_html5_video())\n# ani._repr_html_() is None\n# plt.rc('animation', html='html5')\n\n######### SAVE AS GIF with imagemagik \n# anim.save('../../files/animation.gif', writer='imagemagick', fps=60)\n# Image(url='../../../animation.gif')","sub_path":"rough/BasicAnimation3_VolumePrice.py","file_name":"BasicAnimation3_VolumePrice.py","file_ext":"py","file_size_in_byte":5355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"444507403","text":"# Euler problem 10\n\n# naive sieve algoritm\ndef sieve(max_n):\n x = [n for n in range(2,max_n+1)]\n i = 0\n while i < len(x):\n j = i + 1\n while j < len(x):\n if x[j] % x[i] == 0:\n del x[j]\n else:\n j += 1\n i += 1\n return x\n\n# optimized sieve algorithm\ndef sieve2(max_n):\n x = [n for n in range(2,max_n+1)]\n i = 0\n while i < len(x):\n if x[i] == 0:\n i += 1\n continue\n j = i + x[i]\n while j < len(x):\n x[j] = 0\n j += x[i]\n i += 1\n return x\n\ndef euler10():\n return sum(sieve2(2000000))\n","sub_path":"python/010.py","file_name":"010.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"122021275","text":"\nimport data_profiler as profiler\nimport gym\n\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\n\nfrom de_runner import run_de\nfrom de_runner import get_network\nfrom ea_wrapper import EAWrapper\nfrom preprocess_wrapper import PreprocessWrapper\nfrom util import *\n\ndef get_uber_network(env):\n\tnetwork = Sequential()\n\tnetwork.add(Conv2D(16, (8, 8), strides=(4, 4), input_shape=env.reset().shape, activation=\"relu\"))\n\tnetwork.add(Conv2D(32, (4, 4), strides=(2, 2), activation=\"relu\"))\n\tnetwork.add(Flatten())\n\tnetwork.add(Dense(256, activation=\"relu\"))\n\tnetwork.add(Dense(env.action_space.n, activation=\"linear\"))\n\treturn network\n\n\ndef profile_full_run(env_name=\"Asteroids-v0\", pop_size=1):\n\tp = profiler.Profile(signatures=False)\n\tp.enable()\n\n\tenv = gym.make(env_name)\n\tenv.seed(0)\n\tenv = PreprocessWrapper(env)\n\tnetwork = get_uber_network(env)\n\n\tinitial_pop = []\n\tsize_of_weights = 0\n\tfor weight_layer in network.get_weights():\n\t\tsize_of_weights += weight_layer.size\n\tfor indv in range(pop_size):\n\t\tinitial_pop.append(np.random.uniform(low=-1.0, high=1.0, size=size_of_weights))\n\n\trun_de(preprocess=False)\n\n\tp.disable()\n\tp.print_stats(2)\n\ndef profile(env_name=\"Asteroids-v0\"):\n\tp = profiler.Profile(signatures=False)\n\tp.enable()\n\n\tenv = gym.make(env_name)\n\tenv.seed(0)\n\tenv = PreprocessWrapper(env)\n\tnetwork = get_network(env)\n\n\tde = EAWrapper(env, network)\n\tde.run_env(view=True)\n\n\tp.disable()\n\tp.print_stats(2)\n\nif __name__ == \"__main__\":\n\tprofile()\n","sub_path":"profile_de.py","file_name":"profile_de.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"599009764","text":"# coding: utf-8\r\n\r\n# Заклинания (способности).\r\n# (c) alexbft 2011\r\n\r\nimport utils\r\nfrom chat import Chat\r\nimport effect\r\nimport inspect\r\nimport random\r\nimport constants\r\nfrom constants import COMMON, UNCOMMON, RARE, UNIQUE, price_factor\r\n\r\nspell_module = None\r\n\r\nclass Spell:\r\n # Название заклинания.\r\n name = u\"Неизвестно\"\r\n # Набор допустимых целей (allies, enemies, self, not_self, dead, alive_or_dead) через пробел.\r\n target = \"\"\r\n # Приоритет заклинания.\r\n priority = 0\r\n rarity = COMMON\r\n price = None\r\n level = 1\r\n shop = True\r\n drop = True\r\n image = \"default\"\r\n color = None\r\n mana = 1\r\n text = \"\"\r\n \r\n def __init__(self):\r\n if self.price == None or isinstance(self.price, float):\r\n self.calculate_price()\r\n self.shop = self.shop and self.drop\r\n if self.image == \"default\":\r\n self.image = 'spells/' + self.__class__.__name__.lower() + '.png'\r\n \r\n def calculate_price(self):\r\n q = self.price if self.price != None else 1\r\n self.price = int(price_factor[self.rarity] * utils.gold_factor(self.level) * q)\r\n \r\n def js_targets(self, fighter):\r\n ' Возвращает информацию о допустимых целях для заклинания. '\r\n return {\"allow\": [f.id for f in self.targets(fighter)]}\r\n \r\n def _targets(self, fighter):\r\n ''' Возвращает список допустимых целей для заклинания.\r\n Fighter f - кастер заклинания.\r\n ''' \r\n fight = fighter.fight\r\n types = self.target.split()\r\n if \"enemies\" in types:\r\n res = list(fight.p[1 - fighter.team_id])\r\n elif \"allies\" in types:\r\n res = list(fight.p[fighter.team_id])\r\n elif \"self\" in types:\r\n res = [fighter]\r\n else:\r\n res = list(fight.fighters())\r\n if \"not_self\" in types:\r\n res.remove(fighter)\r\n if not \"alive_or_dead\" in types:\r\n if \"dead\" in types:\r\n res = [f for f in res if not f.alive]\r\n else:\r\n res = [f for f in res if f.alive]\r\n return res\r\n \r\n def targets(self, fighter):\r\n if (fighter._type == \"user\" and fighter.level < self.level) or fighter.mana < (-self.mana):\r\n return []\r\n else:\r\n return self._targets(fighter)\r\n \r\n def msg(self, message, params = None):\r\n ''' Пишет сообщение в чат.\r\n str message - сообщение (или шаблон).\r\n params - параметры.\r\n К параметрам автоматом добавляются: src:f - кастер заклинания, dest:f - цель заклинания, spell:s - заклинание.\r\n '''\r\n if params == None:\r\n params = {}\r\n params.update({\"src\": self.src.js_link(), \"dest\": self.dest.js_link(), \"spell\": self.js_link()})\r\n self.src.fight.log(message, params)\r\n self.need_msg = False\r\n \r\n def cast_message(self):\r\n ' Стандартное сообщение о применении заклинания. '\r\n if self.target == \"self\":\r\n self.msg(u\"{src:f} применяет {spell:s}.\")\r\n else:\r\n self.msg(u\"{src:f} применяет {spell:s} на %s.\" % (u\"cебя\" if self.target_self() else \"{dest:f}\"))\r\n \r\n def _cast(self, caster, target):\r\n ''' Каст заклинания.\r\n Fighter caster - кастер.\r\n Fighter target - цель.\r\n '''\r\n self.src = caster\r\n self.dest = target\r\n self.need_msg = True\r\n self.cast()\r\n self.src.fight.anim.append({\"type\": \"cast\", \"fighter_id\": self.dest.id, \"image\": self.image})\r\n if self.need_msg:\r\n self.cast_message()\r\n \r\n def cast(self):\r\n ''' Действия при касте заклинания.\r\n '''\r\n utils.log_debug(self.id + \" has no effect!\")\r\n \r\n def target_self(self):\r\n ' Возвращает, является ли целью заклинания сам кастер. '\r\n return self.src == self.dest\r\n \r\n def js(self):\r\n return {\"spell\": self.id, \"name\": self.name, \"level\": self.level, \"mana\": self.mana,\r\n \"rarity\": self.rarity, \"rarity_text\": constants.rarities[self.rarity],\r\n \"color\": self.color, \"color_text\": constants.colors[self.color], \"image\": self.image,\r\n \"price\": self.price, \"text\": self.get_text()}\r\n \r\n def js_link(self):\r\n ' Для ссылки '\r\n return {\"name\": self.name, \"level\": self.level, \"text\": self.get_text(), \"image\": self.image, \"color_text\": constants.colors[self.color], \"rarity_text\": constants.rarities[self.rarity]}\r\n \r\n def js_save(self):\r\n return self.id\r\n\r\n @staticmethod\r\n def js_load(obj):\r\n global spell_module\r\n if spell_module == None:\r\n import spell as spell_module\r\n return spell_module.get(obj)\r\n \r\n def add_effect(self, effect, turns, target = None):\r\n ''' Добавляет эффект, в качестве источника будет указан кастер заклинания.\r\n Параметры аналогичны Fighter.add_effect.\r\n '''\r\n if target == None:\r\n target = self.dest\r\n target.add_effect(effect, turns=turns, source=self.src)\r\n \r\n def skill(self, min_value, max_value, level_span = 10, skill_name = None, base_skill_level = None):\r\n ''' Возвращает множитель/бонус от скилла (по сути - от уровня игрока, потому как качать скиллы можно все (но за бобло)\r\n skill_name - какой скилл считать, если не задано, то берется по цвету заклинания.\r\n '''\r\n if skill_name is None:\r\n skill_name = self.color\r\n factor = float(max_value - min_value) / level_span\r\n if base_skill_level == None:\r\n base_skill_level = self.level - 1\r\n skill = max(0, self.src.get_skill(skill_name) - base_skill_level)\r\n res = min_value + skill * factor\r\n if max_value != None and (factor >= 0 and res > max_value or factor < 0 and res < max_value):\r\n res = max_value\r\n return res\r\n \r\n def get_text(self):\r\n return self.text\r\n \r\n @property\r\n def cur(self):\r\n return self.dest.stats.cur \r\n","sub_path":"tornado/spells/spell_base.py","file_name":"spell_base.py","file_ext":"py","file_size_in_byte":6790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"531375725","text":"import datetime\n\nfrom django.conf import settings\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.db.models import Q\n\nfrom extras.models import Webhook\nfrom extras.constants import OBJECTCHANGE_ACTION_CREATE, OBJECTCHANGE_ACTION_DELETE, OBJECTCHANGE_ACTION_UPDATE\nfrom utilities.api import get_serializer_for_model\nfrom .constants import WEBHOOK_MODELS\n\n\ndef enqueue_webhooks(instance, action):\n \"\"\"\n Find Webhook(s) assigned to this instance + action and enqueue them\n to be processed\n \"\"\"\n if not settings.WEBHOOKS_ENABLED or instance._meta.model_name not in WEBHOOK_MODELS:\n return\n\n type_create = action == OBJECTCHANGE_ACTION_CREATE\n type_update = action == OBJECTCHANGE_ACTION_UPDATE\n type_delete = action == OBJECTCHANGE_ACTION_DELETE\n\n # Find assigned webhooks\n obj_type = ContentType.objects.get_for_model(instance.__class__)\n webhooks = Webhook.objects.filter(\n Q(enabled=True) &\n (\n Q(type_create=type_create) |\n Q(type_update=type_update) |\n Q(type_delete=type_delete)\n ) &\n Q(obj_type=obj_type)\n )\n\n if webhooks:\n # Get the Model's API serializer class and serialize the object\n serializer_class = get_serializer_for_model(instance.__class__)\n serializer_context = {\n 'request': None,\n }\n serializer = serializer_class(instance, context=serializer_context)\n\n # We must only import django_rq if the Webhooks feature is enabled.\n # Only if we have gotten to ths point, is the feature enabled\n from django_rq import get_queue\n webhook_queue = get_queue('default')\n\n # enqueue the webhooks:\n for webhook in webhooks:\n webhook_queue.enqueue(\n \"extras.webhooks_worker.process_webhook\",\n webhook,\n serializer.data,\n instance.__class__,\n action,\n str(datetime.datetime.now())\n )\n","sub_path":"netbox/extras/webhooks.py","file_name":"webhooks.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"184551429","text":"import unittest\nfrom simulator import TestSimulator\nfrom fileio import TestImportExport\nfrom graph import TestGraph\nfrom analysis import TestAnalysis, TestStateTransition\nfrom sbml import TestSBML\n\n\nclass Main():\n allTests = []\n \n def loadCase(self, prefix, testCase):\n loader = unittest.TestLoader()\n loader.testMethodPrefix = prefix\n tests = loader.loadTestsFromTestCase(testCase)\n self.allTests.append(tests)\n\n def main(self):\n self.loadCase('testUI', TestSimulator)\n self.loadCase('testIO', TestImportExport)\n self.loadCase('testGraph', TestGraph)\n self.loadCase('testAnalysis', TestAnalysis)\n self.loadCase('testGraph', TestStateTransition)\n self.loadCase('testSBML', TestSBML)\n \n suite = unittest.TestSuite(self.allTests)\n unittest.TextTestRunner(verbosity = 2).run(suite)\n\nif __name__ == \"__main__\":\n Main().main()\n","sub_path":"tests/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"84417370","text":"\"\"\"\nPerforms local population-based training on MNIST ConvNets.\n\nIf this file is run directly, the training will be executed and its results\nreported at the end.\n\"\"\"\n\nimport math\nimport datetime\nfrom tensorflow.models.official.mnist.dataset import train, test\nfrom pbt import LocalCluster\nfrom mnist import set_mnist_data\nfrom mnist_pbt import ConvNet, plot_hyperparams\n\n\nclass Cluster(LocalCluster[ConvNet]):\n \"\"\"\n A LocalCluster that trains ConvNets.\n \"\"\"\n\n def __init__(self, pop_size: int) -> None:\n \"\"\"\n Creates a new Cluster with ConvNets.\n \"\"\"\n super().__init__(pop_size, lambda num, sess: ConvNet(num, sess))\n\n def exploit_and_or_explore(self) -> None:\n accuracies = {}\n for graph in self.population:\n accuracy = graph.get_accuracy()\n print('Graph', graph.num, 'accuracy:', accuracy)\n accuracies[graph] = accuracy\n if len(self.population) > 1:\n # Rank population by accuracy\n ranked_pop = sorted(self.population, key=lambda graph: accuracies[graph])\n # Bottom 20% copies top 20%\n worst_graphs = ranked_pop[:math.ceil(0.2 * len(ranked_pop))]\n best_graphs = ranked_pop[math.floor(0.8 * len(ranked_pop)):]\n for i in range(len(worst_graphs)):\n bad_graph = worst_graphs[i]\n good_graph = best_graphs[i]\n print('Graph', bad_graph.num, 'copying graph', good_graph.num)\n bad_graph.set_value(good_graph.get_value())\n bad_graph.explore()\n\n def plot_hyperparams(self, directory: str) -> None:\n \"\"\"\n Creates step plots of the hyperparameter update histories of this\n Cluster's population and saves them as images in .\n\n will be created if it does not already exist.\n \"\"\"\n plot_hyperparams([(graph.step_num, graph.get_update_history(), graph.accuracy)\n for graph in self.population], directory)\n\n\nif __name__ == '__main__':\n set_mnist_data(train('MNIST_data/'), test('MNIST_data/'))\n cluster = Cluster(50)\n cluster.initialize_variables()\n training_start = datetime.datetime.now()\n cluster.train(20000)\n print('Training time:', datetime.datetime.now() - training_start)\n ranked_pop = sorted(cluster.get_population(), key=lambda graph: -graph.get_accuracy())\n print()\n for graph in ranked_pop:\n print('Graph', graph.num)\n print('Accuracy:', graph.get_accuracy())\n print('Hyperparameter update history:')\n print()\n print(''.join(str(update) for update in graph.get_update_history()))\n cluster.plot_hyperparams('plots/')\n","sub_path":"mnist_pbt_local.py","file_name":"mnist_pbt_local.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"394588724","text":"import numpy as np\n\nfrom board_util import (\n GoBoardUtil,\n BLACK,\n WHITE,\n EMPTY,\n BORDER,\n PASS,\n is_black_white,\n is_black_white_empty,\n coord_to_point,\n where1d,\n MAXSIZE,\n GO_POINT\n)\n\n\"\"\"\nThe GoBoard class implements a board and basic functions to play\nmoves, check the end of the game, and count the acore at the end.\nThe class also contains basic utility functions for writing a Go player.\nFor many more utility functions, see the GoBoardUtil class in board_util.py.\n\nThe board is stored as a one-dimensional array of GO_POINT in self.board.\nSee GoBoardUtil.coord_to_point for explanations of the array encoding.\n\"\"\"\nclass GoBoard(object):\n def __init__(self, size):\n \"\"\"\n Creates a Go board of given size\n \"\"\"\n assert 5 <= size <= MAXSIZE\n self.reset(size)\n\n def calculate_rows_cols_diags(self):\n if (self.size < 5):\n return\n # all win scenarios for 5's\n self.rows = []\n self.cols = []\n\n def calculate_rows_cols_diags(self):\n if (self.size < 5):\n return\n \n # all win scenarios for 5's\n self.rows = []\n self.cols = []\n for i in range(1, self.size + 1):\n current_row = []\n start = self.row_start(i)\n for pt in range(start, start + self.size):\n current_row.append(pt)\n self.rows.append(current_row)\n\n start = self.row_start(1) + i - 1\n current_col = []\n for pt in range(start, self.row_start(self.size) + i, self.NS):\n current_col.append(pt)\n self.cols.append(current_col)\n\n self.diags = []\n # SE diagonal\n start = self.row_start(1)\n for i in range(start, start + self.size):\n diag_SE = []\n pt = i\n while self.get_color(pt) == EMPTY:\n diag_SE.append(pt)\n pt += self.NS + 1\n if len(diag_SE) >= 5:\n self.diags.append(diag_SE)\n # SE/NE diagonal\n for i in range(start + self.NS, self.row_start(self.size) + 1, self.NS):\n diag_SE = []\n diag_NE = []\n pt = i\n while self.get_color(pt) == EMPTY:\n diag_SE.append(pt)\n pt += self.NS + 1\n pt = i\n while self.get_color(pt) == EMPTY:\n diag_NE.append(pt)\n pt += -1 * self.NS + 1\n if len(diag_SE) >= 5:\n self.diags.append(diag_SE)\n if len(diag_NE) >= 5:\n self.diags.append(diag_NE)\n # NE diagonal\n start = self.row_start(self.size) + 1\n for i in range(start, start + self.size):\n diag_NE = []\n pt = i\n while self.get_color(pt) == EMPTY:\n diag_NE.append(pt)\n pt += -1 * self.NS + 1\n if len(diag_NE) >=5:\n self.diags.append(diag_NE)\n assert len(self.rows) == self.size\n assert len(self.cols) == self.size\n assert len(self.diags) == (2 * (self.size - 5) + 1) * 2\n\n def reset(self, size):\n \"\"\"\n Creates a start state, an empty board with given size.\n \"\"\"\n self.size = size\n self.NS = size + 1\n self.WE = 1\n self.ko_recapture = None\n self.last_move = None\n self.last2_move = None\n self.current_player = BLACK\n self.maxpoint = size * size + 3 * (size + 1)\n self.board = np.full(self.maxpoint, BORDER, dtype=GO_POINT)\n self._initialize_empty_points(self.board)\n self.calculate_rows_cols_diags()\n self.boardLines5 = self.generate_lines(5)\n self.boardLines6 = self.generate_lines(6)\n\n\n def copy(self):\n b = GoBoard(self.size)\n assert b.NS == self.NS\n assert b.WE == self.WE\n b.ko_recapture = self.ko_recapture\n b.last_move = self.last_move\n b.last2_move = self.last2_move\n b.current_player = self.current_player\n b.boardLines5 = self.boardLines5\n b.boardLines6 = self.boardLines6\n assert b.maxpoint == self.maxpoint\n b.board = np.copy(self.board)\n return b\n\n def get_color(self, point):\n return self.board[point]\n\n def pt(self, row, col):\n return coord_to_point(row, col, self.size)\n\n def is_legal(self, point, color):\n \"\"\"\n Check whether it is legal for color to play on point\n This method tries to play the move on a temporary copy of the board.\n This prevents the board from being modified by the move\n \"\"\"\n board_copy = self.copy()\n can_play_move = board_copy.play_move(point, color)\n return can_play_move\n\n def get_empty_points(self):\n \"\"\"\n Return:\n The empty points on the board\n \"\"\"\n return where1d(self.board == EMPTY)\n\n def get_color_points(self, color):\n \"\"\"\n Return:\n All points of color on the board\n \"\"\"\n return where1d(self.board == color)\n\n def row_start(self, row):\n assert row >= 1\n assert row <= self.size\n return row * self.NS + 1\n\n def _initialize_empty_points(self, board):\n \"\"\"\n Fills points on the board with EMPTY\n Argument\n ---------\n board: numpy array, filled with BORDER\n \"\"\"\n for row in range(1, self.size + 1):\n start = self.row_start(row)\n board[start : start + self.size] = EMPTY\n\n def play_move(self, point, color):\n \"\"\"\n Play a move of color on point\n Returns boolean: whether move was legal\n \"\"\"\n assert is_black_white(color)\n # Special cases\n if point == PASS:\n self.ko_recapture = None\n self.current_player = GoBoardUtil.opponent(color)\n self.last2_move = self.last_move\n self.last_move = point\n return True\n elif self.board[point] != EMPTY:\n return False\n self.board[point] = color\n self.current_player = GoBoardUtil.opponent(color)\n self.last2_move = self.last_move\n self.last_move = point\n return True\n\n def undo_move(self, move):\n self.board[move] = EMPTY\n self.current_player = GoBoardUtil.opponent(self.current_player)\n\n def last_board_moves(self):\n \"\"\"\n Get the list of last_move and second last move.\n Only include moves on the board (not None, not PASS).\n \"\"\"\n board_moves = []\n if self.last_move != None and self.last_move != PASS:\n board_moves.append(self.last_move)\n if self.last2_move != None and self.last2_move != PASS:\n board_moves.append(self.last2_move)\n return\n\n def detect_five_in_a_row(self):\n \"\"\"\n Returns BLACK or WHITE if any five in a row is detected for the color\n EMPTY otherwise.\n \"\"\"\n for r in self.rows:\n result = self.has_five_in_list(r)\n if result != EMPTY:\n return result\n for c in self.cols:\n result = self.has_five_in_list(c)\n if result != EMPTY:\n return result\n for d in self.diags:\n result = self.has_five_in_list(d)\n if result != EMPTY:\n return result\n return EMPTY\n\n def has_five_in_list(self, list):\n \"\"\"\n Returns BLACK or WHITE if any five in a rows exist in the list.\n EMPTY otherwise.\n \"\"\"\n prev = BORDER\n counter = 1\n for stone in list:\n if self.get_color(stone) == prev:\n counter += 1\n else:\n counter = 1\n prev = self.get_color(stone)\n if counter == 5 and prev != EMPTY:\n return prev\n return EMPTY\n\n # compute upon new board size\n def generate_lines(self, length): \n boardLines = []\n size = self.size\n for p in range(size * size):\n pointLines = \\\n self.horizontal_lines(p, length) + \\\n self.vertical_lines(p, length) + \\\n self.diag_lines(p, size + 1, length) + \\\n self.diag_lines(p, size - 1, length)\n boardLines.append(pointLines)\n return boardLines\n\n def horizontal_lines(self, pt, length):\n lines = []\n size = self.size\n beg = max(pt - (length - 1), pt - (pt % size))\n end = min(pt + (length - 1), size * (pt // size + 1) - 1)\n\n for i in range(end - beg - (length - 2)):\n lines.append(list(map(self.padded_point, range(beg + i, beg + i + length))))\n\n return lines\n\n def vertical_lines(self, pt, length):\n lines = []\n size = self.size \n beg = max(pt - ((length - 1) * size), pt % size)\n end = min(pt + ((length - 1) * size), (size - 1) * size + (pt % size))\n\n for i in range(beg, end - ((length - 1) * size) + 1, size):\n lines.append(list(map(self.padded_point, range(i, i + ((length - 1) * size) + 1, size))))\n\n return lines\n\n def diag_lines(self, pt, dir, length):\n lines = []\n size = self.size\n row = pt // size\n col = pt % size\n\n if (dir == size - 1):\n maxBackwardDist = min(row, size - col - 1, length - 1)\n maxForwardDist = min(size - row - 1, col, length - 1)\n else:\n maxBackwardDist = min(row, col, length - 1)\n maxForwardDist = min(size - row - 1, size - col - 1, length - 1)\n\n start = pt - maxBackwardDist * dir\n end = pt + maxForwardDist * dir\n\n for i in range(start, end - ((length - 1) * dir) + 1, dir):\n lines.append(list(map(self.padded_point, range(i, i + ((length - 1) * dir) + 1, dir))))\n\n return lines\n\n def padded_point(self, pt):\n # convert point in board to padded board point\n size = self.size\n row = (pt // size) + 1\n col = (pt % size) + 1\n return row * (size + 1) + col\n\n def unpadded_point(self, pt):\n size = self.size\n row = pt // (size + 1) - 1\n col = pt % (size + 1) - 1\n return row * size + col\n\n def check_win(self, move):\n newPoint = self.unpadded_point(move)\n lines = self.boardLines5[newPoint]\n for line in lines:\n b_count, w_count, e_count = self.get_counts(line)\n if (b_count == 5):\n return BLACK\n elif (w_count == 5):\n return WHITE\n\n return EMPTY\n\n def get_counts(self, line):\n b_count = w_count = e_count = 0\n for p in line:\n stone = self.board[p]\n if (stone == BLACK):\n b_count = b_count + 1\n elif (stone == WHITE):\n w_count = w_count + 1\n else:\n e_count = e_count + 1\n\n return b_count, w_count, e_count\n\n def __str__(self):\n twod = GoBoardUtil.get_twoD_board(self)\n twod_str = ['[' + ' '.join(row) + ']' for row in twod]\n return '\\n'.join(twod_str)\n","sub_path":"assignment4/QuentinQuarantino/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":11141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"650781917","text":"__author__ = \"Alberto Garcia-Garcia and Brayan Zapata-Impata\"\n__copyright__ = \"Copyright 2018, 3D Perception Lab\"\n__credits__ = [\"Alberto Garcia-Garcia\",\n \"Brayan Zapata-Impata\"]\n\n__license__ = \"MIT\"\n__version__ = \"1.0\"\n__maintainer__ = \"Alberto Garcia-Garcia\"\n__email__ = \"agarcia@dtic.ua.es\"\n__status__ = \"Development\"\n\nimport argparse\nimport datetime\nimport logging\nimport sys\nimport time\nfrom timeit import default_timer as timer\n\nimport numpy as np\n\nimport torch\nimport torch.nn.functional as F\nimport torch.utils.data.dataloader\nfrom torch.utils.data.sampler import SubsetRandomSampler\nfrom torch_geometric.data import Data\nfrom torch_geometric.data import DataLoader\n\nimport loader.biotacsp_loader\nimport dataset.biotacsp\nimport network.utils\nimport transforms.tograph\nimport utils.plotaccuracies\nimport utils.plotcontour\nimport utils.plotgraph\nimport utils.plotlosses\n\nlog = logging.getLogger(__name__)\n\ndef visualize_batch(batch):\n\n log.info(batch)\n log.info(\"Batch size {}\".format(batch.num_graphs))\n\n npg_ = int(batch.num_nodes / batch.num_graphs)\n epg_ = int(batch.num_edges / batch.num_graphs)\n\n log.info(npg_)\n log.info(epg_)\n\n for i in range(batch.num_graphs):\n pos_ = batch['pos'][i*npg_:i*npg_ + npg_, :]\n x_ = batch['x'][i*npg_:i*npg_ + npg_, :]\n y_ = batch['y'][i:i]\n edge_index_ = batch['edge_index'][:, epg_*i:epg_*i + epg_] - i*npg_\n\n utils.plotgraph.plot_graph_3d(pos_, x_, y_, edge_index_)\n utils.plotgraph.plot_contourgraph_batch(pos_, x_, y_, edge_index_)\n\ndef traintest(args, experimentStr, datasetTrain, datasetTest):\n\n log.info(\"Training and testing...\")\n\n train_loader_ = DataLoader(datasetTrain, batch_size=args.batch_size, shuffle=True, num_workers=1)\n test_loader_ = DataLoader(datasetTest, batch_size=args.batch_size, shuffle=False, num_workers=1)\n\n ## Select CUDA device\n device_ = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n log.info(device_)\n log.info(torch.cuda.get_device_name(0))\n\n ## Build model\n model_ = network.utils.get_network(args.network, datasetTrain.data.num_features, datasetTrain.data.num_classes).to(device_)\n #model_ = torch.nn.DataParallel(model_, device_ids=range(torch.cuda.device_count()))\n log.info(model_)\n\n ## Optimizer\n optimizer_ = torch.optim.Adam(model_.parameters(), lr=args.lr, weight_decay=5e-4)\n log.info(optimizer_)\n\n ## Log accuracies, learning rate, and loss\n epochs_ = []\n best_test_acc_ = 0.0\n train_accuracies_ = []\n test_accuracies_ = []\n train_losses_ = []\n\n time_start_ = timer()\n \n for epoch in range(args.epochs):\n\n log.info(\"Training epoch {0} out of {1}\".format(epoch, args.epochs))\n\n model_.train()\n loss_all = 0\n\n i = 1\n for batch in train_loader_:\n\n # Batch Visualization\n if (args.visualize_batch):\n log.info(\"Training batch {0} of {1}\".format(i, len(dataset)/args.batch_size))\n visualize_batch(batch)\n\n batch = batch.to(device_)\n optimizer_.zero_grad()\n output_ = model_(batch)\n loss_ = F.nll_loss(output_, batch.y)\n loss_.backward()\n loss_all += batch.y.size(0) * loss_.item()\n optimizer_.step()\n\n i+=1\n\n # Log train loss\n train_losses_.append(loss_all)\n log.info(\"Training loss {0}\".format(loss_all))\n\n # Get train accuracy\n model_.eval()\n correct_ = 0\n\n for batch in train_loader_:\n\n batch = batch.to(device_)\n pred_ = model_(batch).max(1)[1]\n correct_ += pred_.eq(batch.y).sum().item()\n\n correct_ /= len(datasetTrain)\n\n # Log train accuracy\n train_accuracies_.append(correct_)\n log.info(\"Training accuracy {0}\".format(correct_))\n\n # Get test accuracy\n model_.eval()\n correct_ = 0\n\n for batch in test_loader_:\n\n batch = batch.to(device_)\n pred_ = model_(batch).max(1)[1]\n correct_ += pred_.eq(batch.y).sum().item()\n\n correct_ /= len(datasetTest)\n\n # Log test accuracy\n test_accuracies_.append(correct_)\n log.info(\"Test accuracy {0}\".format(correct_))\n\n # Checkpoint model\n if correct_ > best_test_acc_ and args.save_ckpt:\n\n log.info(\"BEST ACCURACY SO FAR, checkpoint model...\")\n\n best_test_acc_ = correct_\n\n state_ = {'epoch': epoch+1,\n 'model_state': model_.state_dict(),\n 'optimizer_state': optimizer_.state_dict(),}\n torch.save(state_, (args.ckpt_path + \"/\" + experimentStr + \"_{0}.pkl\").format(epoch))\n\n epochs_.append(epoch)\n\n time_end_ = timer()\n log.info(\"Training took {0} seconds\".format(time_end_ - time_start_))\n\n utils.plotaccuracies.plot_accuracies(epochs_, [train_accuracies_, test_accuracies_], [\"Train Accuracy\", \"Test Accuracy\"])\n utils.plotlosses.plot_losses(epochs_, [train_losses_], [\"Train Loss\"])\n\ndef train(args, experimentStr):\n\n biotacsp_dataset_train_ = dataset.biotacsp.BioTacSp(root='data/biotacsp', k=args.graph_k, split=None, csvs=args.train_csvs, normalize=args.normalize)\n biotacsp_dataset_test_ = dataset.biotacsp.BioTacSp(root='data/biotacsp', k=args.graph_k, split=None, csvs=args.test_csvs, normalize=args.normalize)\n\n log.info(biotacsp_dataset_train_)\n log.info(biotacsp_dataset_test_)\n traintest(args, experimentStr, biotacsp_dataset_train_, biotacsp_dataset_test_)\n\nif __name__ == \"__main__\":\n\n parser_ = argparse.ArgumentParser(description=\"Parameters\")\n parser_.add_argument(\"--train_csvs\", nargs=\"+\", help=\" Train CSV list\", required=True)\n parser_.add_argument(\"--test_csvs\", nargs=\"+\", help=\" Test CSV list\", required=True)\n parser_.add_argument(\"--log_path\", nargs=\"?\", default=\"logs\", help=\"Logging path\")\n parser_.add_argument(\"--ckpt_path\", nargs=\"?\", default=\"ckpts\", help=\"Path to save checkpoints\")\n parser_.add_argument(\"--save_ckpt\", nargs=\"?\", type=bool, default=True, help=\"Wether or not to store the best weights\")\n parser_.add_argument(\"--normalize\", nargs=\"?\", type=bool, default=False, help=\"Normalize dataset using feature scaling\")\n parser_.add_argument(\"--graph_k\", nargs=\"?\", type=int, default=0, help=\"K-Neighbours for graph connections, use 0 for manual connections\")\n parser_.add_argument(\"--batch_size\", nargs=\"?\", type=int, default=1, help=\"Batch Size\")\n parser_.add_argument(\"--network\", nargs=\"?\", default=\"GCN_test\", help=\"The network model to train\")\n parser_.add_argument(\"--lr\", nargs=\"?\", type=float, default=0.0001, help=\"Learning Rate\")\n parser_.add_argument(\"--epochs\", nargs=\"?\", type=int, default=32, help=\"Training Epochs\")\n parser_.add_argument(\"--visualize_batch\", nargs=\"?\", type=bool, default=False, help=\"Wether or not to display batch contour plots\")\n\n args_ = parser_.parse_args()\n\n logging.basicConfig(stream=sys.stdout, level=logging.INFO)\n\n # Experiment name (and log filename) follows the format network-normalization-graph_k-datetime\n experiment_str_ = \"traintest-{0}-{1}-{2}-{3}-{4}-{5}\".format(\n ''.join(args_.train_csvs),\n ''.join(args_.test_csvs),\n args_.network,\n args_.normalize,\n args_.graph_k,\n datetime.datetime.now().strftime('%b%d_%H-%M-%S'))\n\n # Add file handler to logging system to simultaneously log information to console and file\n log_formatter_ = logging.Formatter(\"%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s\")\n file_handler_ = logging.FileHandler(\"{0}/{1}.log\".format(args_.log_path, experiment_str_))\n file_handler_.setFormatter(log_formatter_)\n log.addHandler(file_handler_)\n\n train(args_, experiment_str_)\n","sub_path":"train_csv.py","file_name":"train_csv.py","file_ext":"py","file_size_in_byte":7968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"534661527","text":"def format_arg(a, kw):\n str_list = []\n for v in a: str_list.append(str(v))\n if kw: str_list.append(f\"**{kw}\")\n return \", \".join(str_list)\n\n\ndef logcall(fun):\n \"\"\"Log calls to the decorated function each time one begins\"\"\"\n def wrap(*a, **kw):\n print(f\"{fun.__name__}({format_arg(a, kw)})\")\n result = fun(*a, **kw)\n return result\n return wrap\n\n\ndef logboth(fun):\n \"\"\"Log beginning and end of calls to the decorated function\"\"\"\n def wrap(*a, **kw):\n print(f\"{fun.__name__}({format_arg(a, kw)}) begin\")\n result = fun(*a, **kw)\n print(f\"{fun.__name__} end\")\n return result\n return wrap\n\n\ndef repeat(fun, sleep, duration, ending_message):\n \"\"\"\n Refactored code which runs the `fun` function a number of times proportional to duration\n (10 times duration to be precise)\n - sleep is the function to use to perform sleep. It is passed `.1` each time\n - ending_message is printed at the end\n \"\"\"\n for k in range(int(duration)):\n print(k, end=\" \")\n for m in [0] * 10:\n fun()\n sleep(.1)\n print(int(duration), end=\" \")\n for m in [0] * (int(10 * duration) % 10):\n fun()\n sleep(.1)\n print(ending_message)\n\n\ndef remove_common_prefix(*list_list):\n \"\"\"\n Given any number of lists, identify what part is common to all of them at the begnning, and return\n a list of lists (in the same order) where this common part has been removed.\n \"\"\"\n common = 0\n for k, elemList in enumerate(zip(*list_list)):\n elem, *rest = elemList\n if any(elem != e for e in rest):\n break\n common = k + 1\n result_list = [li[common:] for li in list_list]\n return result_list\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"615897152","text":"from keras import utils\r\nimport json\r\nimport run\r\nfrom flask import abort\r\nfrom logging.config import dictConfig\r\nimport pandas as pd\r\nfrom keras.preprocessing.text import Tokenizer\r\nfrom keras.preprocessing.sequence import pad_sequences\r\nimport numpy as np\r\n#utility\r\nimport re\r\nfrom keras.models import load_model\r\nimport tensorflow as tf\r\ndf = pd.read_csv(\"sentiment_data.csv\")\r\ntokenizer = Tokenizer(num_words=50000, filters='!\"#$%&()*+,-./:;<=>?@[\\]^_`{|}~', lower=True)\r\ntokenizer.fit_on_texts(df['tweet_content'].values)\r\ndef run_model(img):\r\n\ttry :\r\n\t model = tf.keras.models.load_model('model.h5')\r\n \r\n\texcept FileNotFoundError as e : \r\n\t return abort('Unable to find the file: %s.' % str(e), 503)\r\n\tpred = model.predict(img)\r\n\tprediction = pred[0][0]\r\n\tif(prediction>=0.38):\r\n\t\tstatus=1\r\n\telse:\r\n\t\tstatus=0\r\n\treturn status\r\ndef load_image(filename):\r\n\t\r\n\tx = tokenizer.texts_to_sequences(filename)\r\n\tx = pad_sequences(x, maxlen=20, padding='post')\r\n\treturn x\r\ndef classify(data):\r\n\tupload = data\r\n\timage = load_image(upload)\r\n\t#load_image() is to process image :\r\n\tprint('image ready')\r\n\ttry:\r\n\t\tprediction = run_model(image)\r\n\t\treturn (json.dumps({\"prediction\": str(prediction)}))\r\n\texcept FileNotFoundError as e:\r\n\t\treturn abort('Unable to locate image: %s.' % str(e), 503)\r\n\texcept Exception as e:\r\n\t\treturn abort('Unable to process image: %s.' % str(e), 500)\r\n\r\n\r\n\r\n\r\n","sub_path":"methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"566157193","text":"#!/user/bin/python3\n# -*- coding: utf-8 -*-\n# compatible with Python 3.4.3\n\n__author__=\"Bo Zhou\"\n__copyright__ = \"Copyright 2015, The NRA project \"\n__credits__ = [\"Bo Zhou\"]\n__license__ = \"MIT\"\n__version__ = \"1.0.0\"\n__maintainer__ = \"Bo Zhou\"\n__email__ = \"bzhou2@ualberta.ca\"\n__status__ = \"Testing\"\n\nimport time\nimport bs4\nimport xlsxwriter\nimport geopy\nfrom contextlib import closing\nfrom selenium import webdriver\nfrom selenium.webdriver import Firefox\nfrom selenium.webdriver.support.ui import Select\n\n# global variable\nbft_number = 1 # for bft\npts_number = 1 # for pts\nrow = 0\nrowCount = 0\n# http://www.zipcodestogo.com/Pennsylvania/\nf = open(\"pazip\",'r')\nzipList = f.read().split() \nf.close()\n\n# swithch key\nDUPFILTER = 0 # avoid duplicated information, change it to 1, or leave it 0 if you need original information\nPROVINCE = \"\" # if you want to get all, change it to ''\n\n\ndef open_url_by_se(driver):\n # main page\n chooseList = [\"0\", \"2\", \"8\"]\n checkboxId = \"ContentPlaceHolderDefault_DivMainCPH_ctl01_NRANearYouControl_2_chkGrids_\"\n formId = \"ContentPlaceHolderDefault_DivMainCPH_ctl01_NRANearYouControl_2_LocationTextBox\"\n rangId = \"ContentPlaceHolderDefault_DivMainCPH_ctl01_NRANearYouControl_2_ddlMiles\" \n srchBtId = \"ContentPlaceHolderDefault_DivMainCPH_ctl01_NRANearYouControl_2_imgbtn_Locate\"\n # Basic Firearms Training\n bftPageCtrlId = \"ContentPlaceHolderDefault_DivMainCPH_ctl01_NRANearYouControl_2_BasicFirearmPagerPanel\"\n bftNtPageId = \"ContentPlaceHolderDefault_DivMainCPH_ctl01_NRANearYouControl_2_dg2NextPage\" \n bftTableId = \"ContentPlaceHolderDefault_DivMainCPH_ctl01_NRANearYouControl_2_dg2\"\n bftDataTag = \"ET\"\n # Places to Shoot\n ptsPageCtrlId = \"ContentPlaceHolderDefault_DivMainCPH_ctl01_NRANearYouControl_2_NationalRegistryShootPagerPanel\"\n ptsNtPageId = \"ContentPlaceHolderDefault_DivMainCPH_ctl01_NRANearYouControl_2_dg1NextPage\"\n ptsTableId = \"ContentPlaceHolderDefault_DivMainCPH_ctl01_NRANearYouControl_2_dg1\"\n ptsDataTag = \"RANGE\"\n # Clubs and Associations\n try:\n for i in chooseList:\n driver.find_element_by_id(checkboxId+i).click()\n except Exception as e:\n print(e)\n elem = driver.find_element_by_id(formId)\n # http://www.netstate.com/states/geography/pa_geography.htm\n elem.send_keys(\"16823\") # The geographic center of Pennsylvania\n select = Select(driver.find_element_by_id(rangId))\n select.select_by_visible_text(\"200\")\n button = driver.find_element_by_id(srchBtId)\n button.click()\n workbook = xlsxwriter.Workbook(\"all_data_All.xlsx\")\n worksheet = workbook.add_worksheet('NRA Address') \n worksheet.set_column(\"A:A\",40)\n worksheet.set_column(\"B:C\",60)\n # handle bft\n bftRslt = crawl_one_category(driver, bftPageCtrlId, bftNtPageId, bftTableId, bftDataTag, 2)\n write_to_excel(bftRslt, worksheet, 'Basic Firearms Training')\n # handle pts\n ptsRslt = crawl_one_category(driver, ptsPageCtrlId, ptsNtPageId, ptsTableId, ptsDataTag, 0)\n write_to_excel(ptsRslt, worksheet, 'Place to Shoot')\n # handle cad\n cadRslt = crawl_cad()\n write_to_excel(cadRslt, worksheet, 'Club and Associations Directory')\n workbook.close()\n return\n\n\ndef write_to_excel(content,worksheet,category):\n #content [(name, adrs, PA, Postcode, geo),...]\n global row\n for unit in content:\n worksheet.write(row, 0, category)\n column = 1\n for k in range(4):\n worksheet.write(row, column, unit[k])\n column += 1\n for item in unit[4]:\n worksheet.write(row, column, item)\n column += 1\n row += 1\n return\n\n\ndef search_page(soup, tableId, dataTag, omitNumber):\n global pts_number\n global bft_number\n cad_number = 1\n if dataTag == \"ET\":\n choose = bft_number\n elif dataTag == \"RANGE\":\n choose = pts_number\n elif dataTag == \"CLUBDIRECTORY\":\n choose = cad_number\n \n #cases = {\"ET\":bft_number,\"RANGE\":pts_number}\n table = soup.find(id = tableId)\n allItem = table.find_all(class_= \"tableItem\")\n resultList = []\n for el in allItem:\n item = []\n courseNameList = el.find(class_=\"findCourse\").get_text().split()\n courseName = \" \".join(courseNameList)\n #print(courseName)\n info = el.find(id = dataTag + str(choose))\n if info != None:\n adrsList = info_catch(info.get_text(), omitNumber)\n if adrsList != None:\n adrsList [0] = courseName\n resultList.append(adrsList)\n choose += 1\n if dataTag == \"ET\":\n bft_number = choose\n elif dataTag == \"RANGE\":\n pts_number = choose \n return resultList\n\n\n# Based on Google Map Geolocation API\ndef geocoding(onePgAdrsList): #[(name, address, province, zip,(100,100)),(),()]\n global rowCount\n googlev3 = geopy.GoogleV3()\n geoAdrsList = []\n for el in onePgAdrsList:\n adrsCnt = ''\n newItem = []\n gps = tuple()\n for i in range(1,4):\n adrsCnt += (el[i]+' ')\n rowCount += 1\n try:\n place,gps = googlev3.geocode(adrsCnt)\n except Exception as err:\n print (\"on row: \"+str(rowCount)+\". Cannot find Geolation for: \"+adrsCnt+\" ziplist[0] is: \"+str(zipList[0]))\n for item in el:\n newItem.append(item)\n newItem.append(gps)\n geoAdrsList.append(newItem)\n return geoAdrsList\n\n\ndef crawl_one_category(driver, pageCtrlId, ntPageId, tableId, dataTag, omitNumber):\n currentPage = -2\n totalPage = -1\n rsltList = []\n geoChcekList = []\n while currentPage < totalPage:\n content = driver.page_source\n soup = bs4.BeautifulSoup(content) \n pageCtrl = soup.find(id=pageCtrlId)\n if pageCtrl == None:\n time.sleep(10)\n print(\"try to reload \"+str(currentPage+1))\n continue\n try:\n pageContent = pageCtrl.get_text()\n except Exception as err:\n print(\"problem on page \"+str(currentPage+1))\n continue\n pageList = pageContent.split()\n currentPage = int(pageList[1].replace('of', ''))\n totalPage = int(pageList[2])\n onePgList = search_page(soup, tableId, dataTag, omitNumber)\n geoedList = geocoding(onePgList) \n if DUPFILTER == 1:\n for finalItem in geoedList:\n if (finalItem[4] in geoChcekList) and finalItem[4] != ():\n continue\n else:\n geoChcekList.append(finalItem[4])\n rsltList.append(finalItem)\n else:\n for finalItem in geoedList:\n rsltList.append(finalItem) \n if currentPage == totalPage:\n break \n try:\n npBt = driver.find_element_by_id(ntPageId)\n except Exception as e:\n print (e)\n print ('stuck in page: '+str(currentPage))\n time.sleep(5) \n npBt = driver.find_element_by_id(ntPageId) \n npBt.click()\n return rsltList\n \n \ndef info_catch(item, omitNumber):\n global PROVINCE\n itemList = item.split()\n for i in range(omitNumber):\n itemList.pop(0)\n etAdrs = ''\n etPost = []\n j = 0\n length = len(itemList)\n while j < length:\n if itemList[j] != ',':\n etAdrs += (' '+itemList[j])\n else:\n for k in range (1,3):\n etPost.append(itemList[j+k])\n break\n j += 1\n if PROVINCE == '' or PROVINCE == etPost[0]:\n return [None, etAdrs, etPost[0], etPost[1]]\n else:\n return None\n \n\ndef crawl_cad():\n global zipList\n rsltList = []\n resultSet = []\n while zipList != []:\n onePgSet = []\n zipCode = zipList.pop(0)\n driver = webdriver.Firefox()\n driver.maximize_window()\n driver.get('http://findnra.nra.org/') \n driver = do_cad_search(driver, zipCode)\n content = driver.page_source\n soup = bs4.BeautifulSoup(content)\n tableId = \"ContentPlaceHolderDefault_DivMainCPH_ctl01_NRANearYouControl_2_dg11\"\n dataTag = \"CLUBDIRECTORY\"\n onePgList = search_page(soup, tableId, dataTag, 1)\n for item in onePgList:\n if item not in resultSet: \n onePgSet.append(item)\n resultSet.append(item)\n geoedList = geocoding(onePgSet) \n for el in geoedList:\n rsltList.append(el)\n driver.close()\n return rsltList\n \n \n\ndef do_cad_search(driver, zipCode):\n failCount = 0\n failSwitch = True\n checkId = \"ContentPlaceHolderDefault_DivMainCPH_ctl01_NRANearYouControl_2_chkGrids_2\"\n while failSwitch:\n try: \n driver.find_element_by_id(checkId).click()\n failSwitch = False\n except Exception as e:\n failCount += 1\n print(\"Fail to load main search Page. Failed: \"+str(failCount)+\" time(s)\")\n time.sleep(5)\n if failCount == 10: \n raise\n continue\n elem = driver.find_element_by_id(\"ContentPlaceHolderDefault_DivMainCPH_ctl01_NRANearYouControl_2_LocationTextBox\")\n # http://www.netstate.com/states/geography/pa_geography.htm\n elem.send_keys(zipCode) # The geographic center of Pennsylvania\n select = Select(driver.find_element_by_id(\"ContentPlaceHolderDefault_DivMainCPH_ctl01_NRANearYouControl_2_ddlMiles\"))\n select.select_by_visible_text(\"25\")\n button = driver.find_element_by_id(\"ContentPlaceHolderDefault_DivMainCPH_ctl01_NRANearYouControl_2_imgbtn_Locate\")\n button.click()\n return driver\n\n\ndef show_time(time):\n hours = time//3600\n minutes = (time//60)%60\n seconds = time%60\n print (\"program runs for \"+str(int(hours))+\" hours, \"+str(int(minutes))+\" minutes, \"+str(seconds)+\" seconds.\")\n\n \nif __name__ == '__main__':\n saveFileName = \"nra\"\n crawlUrl = 'http://findnra.nra.org/'\n startTime = time.time()\n driver = webdriver.Firefox()\n driver.maximize_window()\n driver.get(crawlUrl)\n open_url_by_se(driver)\n driver.close()\n elapsedTime = time.time() - startTime\n show_time(elapsedTime) \n print('all finish! ')","sub_path":"scratch.py","file_name":"scratch.py","file_ext":"py","file_size_in_byte":10200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"160113894","text":"import os\n\nfiles = os.listdir('.')\nfor each_file in files:\n altered_content = []\n if each_file != 's-helper.py':\n with open(each_file,'r') as f:\n contents = f.readlines()\n for line in contents:\n if line.strip() != '':\n if not line.startswith('\"'):\n altered_content.append('\"'+line[:line.rfind(',')]+'\"'+line[line.rfind(','):])\n else:\n altered_content.append(line)\n with open(each_file,'w') as f:\n for line in altered_content:\n f.write(line+\"\\n\") ","sub_path":"grub-hunter-data-populator/data/s-helper.py","file_name":"s-helper.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"147779825","text":"import tensorflow as tf\nimport builder\nimport typing\nimport data.coding as coding\n\n\nclass RCNNBuilder(builder.base.GraphBuilder):\n def __init__(self, dtype=tf.float32):\n builder.base.GraphBuilder.__init__(self, dtype)\n\n def rpn_bboxes(self,\n objectness_nodes: tf.Tensor,\n regression_nodes: tf.Tensor,\n anchors: typing.List[typing.List[float]],\n input_shape: typing.List[int],\n iou_threshold: int=0.7,\n max_bboxes: int=100) \\\n -> typing.Tuple[tf.Tensor, tf.Tensor]:\n \"\"\"\n\n :param objectness_nodes:\n :param regression_nodes:\n :param anchors: list of lists containing (height, width)\n :param input_shape: list containing (height, width)\n :param iou_threshold:\n :param max_bboxes:\n :return: tuple containing (image indices, bounding boxes)\n \"\"\"\n n_anchors = len(anchors)\n\n output_shape = objectness_nodes[0].shape[1:3]\n image_indices = tf.zeros([1], dtype=tf.int32)\n selected_boxes = tf.zeros([0, 4], dtype=self.dtype)\n for i_anchor in range(n_anchors):\n assert(objectness_nodes.shape[0] == regression_nodes.shape[0])\n\n coded_anchor_bboxes = coding.encode_anchor_bboxes(input_shape, output_shape, anchors[i_anchor])\n anchor_node = tf.constant(coded_anchor_bboxes.reshape(-1, 4), tf.float32)\n\n i_sample = tf.constant(0, tf.int32)\n\n def max_samples(i_sample: tf.Tensor, image_indices, selected_boxes):\n return tf.less(i_sample, tf.shape(objectness_nodes)[0])\n\n def sample_subgraph(i_sample: tf.Tensor, image_indices, selected_boxes):\n objectness_node = tf.reshape(objectness_nodes[i_anchor][i_sample, :, :, :], [-1, 2])\n objectness_scores = tf.nn.softmax(objectness_node, dim=1)[:, 0]\n \n true_indices = tf.where(tf.greater_equal(objectness_scores, [.5]))\n \n objectness_scores = objectness_scores[true_indices]\n \n valid_anchor_node = anchor_node[true_indices, :]\n\n regression_node = tf.reshape(regression_nodes[i_anchor][i_sample, :, :, :], [-1, 4])\n regression_node = regression_node[true_indices, :]\n\n regression_corners = tf.add(tf.multiply(regression_node[:, 0:2], valid_anchor_node[:, 2:4]),\n valid_anchor_node[:, 0:2])\n regression_sizes = tf.multiply(tf.exp(tf.subtract(regression_node[:, 2:4], regression_node[:, 0:2])),\n valid_anchor_node[:, 2:4])\n regression_boxes = tf.concat([regression_corners, tf.add(regression_corners, regression_sizes)], axis=1)\n selected_indices = tf.image.non_max_suppression(regression_boxes,\n objectness_scores,\n max_bboxes,\n iou_threshold)\n\n selected_boxes = tf.concat([selected_boxes, regression_boxes[selected_indices, :]], 0)\n image_indices = tf.concat([image_indices, tf.ones_like(selected_indices, dtype=tf.int32)], 0)\n\n return [tf.add(i_sample, 1), image_indices, selected_boxes]\n\n _, image_indices, selected_boxes = tf.while_loop(max_samples,\n sample_subgraph,\n loop_vars=[i_sample, image_indices, selected_boxes],\n shape_invariants=[i_sample.shape,\n tf.TensorShape([None]),\n tf.TensorShape([None, 4])])\n\n return image_indices, selected_boxes\n\n def roi_pooling(self,\n input: tf.Tensor,\n bboxes: tf.Tensor,\n crop_size: tf.Tensor,\n box_indices: tf.Tensor,\n n_outputs: int=256):\n return tf.image.crop_and_resize(image=input,\n boxes=bboxes,\n box_ind=box_indices,\n crop_size=crop_size)\n\n def simple_rpn_loss(self,\n regression_predictions: typing.List[tf.Tensor],\n regression_ground_truths: typing.List[tf.Tensor],\n objectness_predictions: typing.List[tf.Tensor],\n objectness_ground_truths: typing.List[tf.Tensor],\n loss_masks: typing.List[tf.Tensor],\n regression_loss_weight: int=10):\n assert(len(regression_predictions) ==\n len(regression_ground_truths) ==\n len(objectness_predictions) ==\n len(objectness_ground_truths) ==\n len(loss_masks))\n regression_loss_weight = tf.constant(regression_loss_weight, self.dtype)\n n_anchors = len(regression_predictions)\n n_samples = regression_predictions[0].shape[0]\n\n regression_loss = None\n objectness_loss = None\n for i_anchor in range(n_anchors):\n # regression loss\n regression_prediction = regression_predictions[i_anchor]\n regression_ground_truth = regression_ground_truths[i_anchor]\n loss_mask = loss_masks[i_anchor]\n n_anchor_locations = regression_prediction.shape[1] * regression_prediction.shape[2]\n\n diff = tf.subtract(regression_prediction, regression_ground_truth)\n abs_diff = tf.abs(diff)\n abs_diff_lt_1 = tf.less(abs_diff, 1)\n anchorwise_smooth_l1norm = tf.where(abs_diff_lt_1,\n 0.5 * tf.square(abs_diff),\n abs_diff - 0.5) * loss_mask\n if regression_loss is None:\n regression_loss = anchorwise_smooth_l1norm * regression_loss_weight / n_anchor_locations\n else:\n regression_loss = tf.add(regression_loss, anchorwise_smooth_l1norm * regression_loss_weight / n_anchor_locations)\n\n # objectness_loss\n objectness_prediction = objectness_predictions[i_anchor]\n objectness_ground_truth = objectness_ground_truths[i_anchor]\n\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=objectness_ground_truth,\n logits=objectness_prediction,\n dim=3) * loss_mask\n if objectness_loss is None:\n objectness_loss = cross_entropy / n_samples\n else:\n objectness_loss = tf.add(objectness_loss, cross_entropy / n_samples)\n\n regression_loss = tf.reduce_sum(regression_loss)\n objectness_loss = tf.reduce_sum(objectness_loss)\n rpn_loss = objectness_loss + regression_loss\n\n return rpn_loss\n\n def simple_rpn_detector(self,\n tail,\n n_anchors,\n n_channels=256,\n batch_norm=False,\n is_training=None,\n conv_keepprob=None,\n fc_keepprob=None\n ):\n regression_nodes = list()\n objectness_nodes = list()\n\n if conv_keepprob is not None:\n tail = self.add_dropout_layer(tail, conv_keepprob)\n tail = self.add_conv_layer(tail,\n n_channels,\n kernel_size=1,\n batch_norm=batch_norm,\n is_training=is_training,\n bias=False)\n\n for i_anchor in range(n_anchors):\n with tf.name_scope(\"rpn_anchor{}\".format(i_anchor)):\n objectness_node = tail\n with tf.name_scope(\"objectness\".format(i_anchor)):\n if fc_keepprob is not None:\n objectness_node = self.add_dropout_layer(objectness_node, fc_keepprob)\n objectness_node = self.add_conv_layer(objectness_node,\n 2,\n kernel_size=3,\n batch_norm=batch_norm,\n is_training=is_training,\n bias=False)\n objectness_nodes.append(objectness_node)\n \n regression_node = tail\n with tf.name_scope(\"regression\".format(i_anchor)):\n if fc_keepprob is not None:\n regression_node = self.add_dropout_layer(regression_node, fc_keepprob)\n regression_node = self.add_conv_layer(regression_node,\n 4,\n kernel_size=3,\n batch_norm=batch_norm,\n is_training=is_training,\n bias=False)\n regression_nodes.append(regression_node)\n\n return objectness_nodes, regression_nodes","sub_path":"code/builder/rcnn.py","file_name":"rcnn.py","file_ext":"py","file_size_in_byte":9851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"5079410","text":"import json\n\nimport pyodbc\nfrom sqlalchemy import create_engine, event\nimport urllib\n\nfrom urllib import parse\n\ncredentials = json.load(open('credentials.json'))\n\nserver = credentials['server']\ndatabase = credentials['database']\nusername = credentials['sql_username']\npassword = credentials['sql_password']\ndriver = '{ODBC Driver 17 for SQL Server}'\n# def get_connection_for_sql_server(server, database, username, password):\n# connection = pyodbc.connect(\n# 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=' + server + ';PORT=1433;DATABASE=' + database\n# + ';UID=' + username + ';PWD=' + password)\n# return connection\n\n\ndef get_engine_for_sql_server():\n params = parse.quote_plus(\n 'Driver=%s;' % driver +\n 'Server=tcp:%s,1433;' % server +\n 'Database=%s;' % database +\n 'Uid=%s;' % username +\n 'Pwd={%s};' % password +\n 'Encrypt=yes;' +\n 'TrustServerCertificate=no;' +\n 'Connection Timeout=30;')\n conn_str = 'mssql+pyodbc:///?odbc_connect=' + params\n engine = create_engine(conn_str)\n return engine\nengine = get_engine_for_sql_server()\n\n\ndef get_connection_for_sql_server():\n connection = pyodbc.connect(\n 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=' + server + ';PORT=1433;DATABASE=' + database\n + ';UID=' + username + ';PWD=' + password)\n return connection\n\n\ndef get_df_from_sql_server(connection, sql_statement):\n cursor = connection.cursor()\n cursor.execute(sql_statement)\n return cursor\n\n\ndef add_table_to_sql_server(connection, sql_statement):\n success_flg = False\n try:\n cursor = connection.cursor()\n cursor.execute(sql_statement)\n connection.commit()\n success_flg = True\n except Exception as e:\n print(e)\n finally:\n connection.close()\n return success_flg\n\n\ndef insert_df_to_table(df, table_name, append_replace):\n success_flg = False\n try:\n engine = get_engine_for_sql_server()\n insert_statement = get_insert_statement(df)\n # df.convert_dtypes()\n df.to_sql(table_name, engine, if_exists=append_replace, index=False)\n #cursor = connection.cursor()\n # Insert Dataframe into SQL Server:\n #for index, row in df.iterrows():\n # cursor.execute(\"INSERT INTO \" + table_name + \" (\" + column_list + \") values(?,?,?)\",\n # row.DepartmentID, row.Name, row.GroupName)\n #connection.commit()\n success_flg = True\n except Exception as e:\n print(e)\n return success_flg\n\n\n@event.listens_for(engine, \"before_cursor_execute\")\ndef receive_before_cursor_execute(conn, cursor, statement, params, context, executemany):\n if executemany:\n cursor.fast_executemany = True\n\n\ndef fast_load(df, table_name, append_replace):\n df.to_sql(table_name, engine, index=False, if_exists=append_replace, schema=\"dbo\")\n\n\ndef bulk_insert_df_to_table(df, table_name, append_replace):\n success_flg = False\n connection = get_connection_for_sql_server()\n try:\n engine = get_engine_for_sql_server()\n insert_statement = get_insert_statement(df, table_name)\n cursor = connection.cursor()\n cursor.fast_executemany = True\n for row_count in range(0, df.shape[0]):\n chunk = df.iloc[row_count:row_count + 1, :].values.tolist()\n tuple_of_tuples = tuple(tuple(x) for x in chunk)\n cursor.executemany(\n insert_statement,\n # \"insert into test\" + \" ([col_name1], col_name2],[col_name3],[col_name4],[col_name5],[col_name6],[col_name7],[col_name8],[col_name9],[col_name10]) values (?,?,?,?,?,?,?,?,?,?)\",\n tuple_of_tuples)\n cursor.commit()\n # df.convert_dtypes()\n # df.to_sql(table_name, engine, if_exists=append_replace, index=False)\n #\n # Insert Dataframe into SQL Server:\n #for index, row in df.iterrows():\n # cursor.execute(\"INSERT INTO \" + table_name + \" (\" + column_list + \") values(?,?,?)\",\n # row.DepartmentID, row.Name, row.GroupName)\n #connection.commit()\n success_flg = True\n except Exception as e:\n print(e)\n finally:\n connection.close()\n return success_flg\n\n\ndef get_insert_statement(df, table_nm):\n column_list = df.columns.values.tolist()\n comma_sep_list = \",\".join(column_list)\n value_list = \"\"\n for x in column_list:\n value_list += \"?,\"\n value_list = value_list[:-1]\n insert_statement = 'INSERT INTO ' + table_nm + ' (' + comma_sep_list + ') VALUES (' + value_list + \")\"\n return insert_statement","sub_path":"sql_server_connector.py","file_name":"sql_server_connector.py","file_ext":"py","file_size_in_byte":4634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"468571802","text":"import os\nfrom shutil import copyfile\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"input_dir\")\nparser.add_argument(\"output_dir\")\nparser.add_argument(\"train_size\")\nparser.add_argument(\"val_size\")\nargs=parser.parse_args()\n\ndef gen_sample_data(input_dir,output_dir, train_sample_size, val_sample_size):\n \n #storing names of directories-these are class names\n dirs = [d for d in os.listdir(input_dir) if os.path.isdir(os.path.join(input_dir, d))]\n \n data_dir = ['train','validation'] #array storing train, validation names\n \n #create folders with similar class names for both train and validation in output dir\n for data_name in data_dir:\n for dir_name in dirs:\n output_path = os.path.join(output_dir,data_name,dir_name)\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n \n #copying images from each class dir to train and validation class dir with sample size\n for dir_name in dirs:\n file_names=[]\n for f in os.listdir(os.path.join(input_dir,dir_name)):\n file_names.append(os.path.join(input_dir,dir_name,f))\n for i in range(0,train_sample_size):\n copyfile(file_names[i], os.path.join(output_dir,\"train\",dir_name,os.path.basename(file_names[i])))\n print(os.path.join(output_dir,\"train\",dir_name+os.path.basename(file_names[i])))\n for j in range(train_sample_size,(train_sample_size+val_sample_size)):\n copyfile(file_names[j], os.path.join(output_dir,\"validation\",dir_name,os.path.basename(file_names[j])))\n print(os.path.join(output_dir,\"validation\",dir_name+os.path.basename(file_names[j])))\n \ngen_sample_data(args.input_dir,args.output_dir,int(args.train_size),int(args.val_size))\n","sub_path":"gen_sample.py","file_name":"gen_sample.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"481526772","text":"from django.core.management.base import BaseCommand\nfrom django.db import transaction\nfrom django.db.utils import IntegrityError\nfrom main_platform.models import rome_code, trade_to_rome_code\nimport csv\nimport os\n\nclass Command(BaseCommand):\n help = \"\"\"fulfill database fields with rome codes and their different names\n using csv file\"\"\"\n\n def handle(self, *args, **options):\n path = os.getcwd()\n i = 0\n with open(path + '/csv/rome_codes_names.csv', newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n with transaction.atomic():\n code_exist = rome_code.objects.filter(code__icontains=row['ROME_PROFESSION_CARD_CODE']).exists()\n if code_exist:\n pass\n else:\n rome_code.objects.create(code=row['ROME_PROFESSION_CARD_CODE'])\n with open(path + '/csv/rome_codes_names.csv', newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n with transaction.atomic():\n rc = rome_code.objects.filter(code__icontains=row['ROME_PROFESSION_CARD_CODE'])[0]\n trc = trade_to_rome_code.objects.create(job_name=row['ROME_PROFESSION_NAME'], job_code=rc)\n","sub_path":"job_search_platform/main_platform/management/commands/rome_codes_to_db.py","file_name":"rome_codes_to_db.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"165228991","text":"import shapefile\nimport random\nimport numpy as np\nimport pandas as pd\nimport os\n\ntodo = [\"ct\", \"il\", \"nj\", \"ny\", \"pa\", \"wa\"]\nattrs = [\"CE01\", \"CE02\"]\n\ndef genPath(state, year):\n return \"LEHD Data/\" + state.upper() + \"/\" + state + \"_rac_S000_JT00_\" + str(year) + \".csv\"\n\ndef csvReader(state, begin_year, end_year):\n year_dic = {}\n for year in range(begin_year, end_year + 1):\n print(year)\n dic = {}\n df = pd.read_csv(genPath(state, year), dtype = {'h_geocode': str, 'CE01': np.int64, 'CE02': np.int64, 'CE03': np.int64})\n for index, row in df.iterrows():\n dic[row[\"h_geocode\"]] = [int(row[i]) for i in attrs]\n year_dic[year] = dic\n return year_dic\n\ndef newShapeFile(input, state , dic, output, begin_year, end_year):\n \n r = shapefile.Reader(input)\n w = shapefile.Writer()\n #shapes = sf.shapes()\n mis = 0\n hit = 0\n w.fields = list(r.fields)\n for year in range(begin_year, end_year + 1):\n for attr in attrs:\n w.field(attr +\"_\" + str(year), \"N\", 10)\n for rec in r.records():\n blkid = str(rec[4])\n for year in range(begin_year, end_year + 1):\n try:\n values = dic[year][blkid]\n for value in values:\n rec.append(value)\n except:\n for at in attrs:\n rec.append(-1)\n w.records.append(rec)\n \n w._shapes.extend(r.shapes())\n if not os.path.exists(output):\n os.mkdir(output)\n w.save(output + \"/block\")\n print(hit, \" blocks have LEHD data\")\n print(mis, \" blocks dont have LEHD data\")\n\nif __name__ == \"__main__\":\n for state in todo:\n newShapeFile(\"raw/\" + state, state, csvReader(state, 2002, 2014), \"merged/\" + state, 2002, 2014)\n\n","sub_path":"data_cleaning/CocoCui/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"25812482","text":"#Example 1:\r\nclass Computer:\r\n def __init__(self, ram, rom):\r\n self.ram = ram\r\n self. rom = rom\r\n\r\n\r\nc1 = Computer(4,16)\r\nprint(c1.ram)\r\nc1.ram = 45 # Attributes of the class support muttability\r\nprint(c1.ram)\r\n\r\n#You can create new attributes also like this\r\nc1.ask = \"aakash\"\r\nprint(c1.ask)\r\n\r\n\r\nprint(\"\")\r\n# Example 2:\r\nclass Computer:\r\n def __init__(self, ram, rom):\r\n self.ram = ram\r\n self. rom = rom\r\n def add(self,a,b):\r\n print(self. ram +a+b)\r\n #In this class you can use self.ram, self.rom variable anywhere in any function but you cannot use this a,b function in other function, for example:\r\n def sub(self):\r\n '''\r\n print(a-b)# It is not recognising the variables of the add function outside the add function.\r\n print(self.a,self.b) # it will give an error that computer object has not attribute a and b.\r\n '''\r\n\r\nc1= Computer(3,16)\r\nc1.add(3,4)\r\nc1.sub()\r\nprint(\"\")","sub_path":"46_operations and example of class and object.py","file_name":"46_operations and example of class and object.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"620116010","text":"#! /usr/bin/env python3\n\n\nf=open('impl_reports/matmul_utilization_routed0000.rpt','r')\na=f.readlines()\nt=(a[76].split('|'))\nif t[1].strip(' ')=='CLB':\n print(t[2].strip(' '))\nf.close()\n\nf=open('syn_reports/cycle0007.rpt','r')\nb=f.readlines()\nk=(b[25].split())\nprint(k)\nk=k.remove(\"' '\")\nli=[]\nprint(k)\nf.close()\n\n","sub_path":"matrix_multiplication/catapult/script/source_util.py","file_name":"source_util.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"484731026","text":"#!/usr/bin/env python3\nimport Map as mp\nimport Player as p\nimport Story as s\nimport numpy as np\nimport Monster as mo\nfrom sys import exit, platform\nfrom os import system\nimport Artwork as a\nfrom colorama import Fore, Style\nimport json\n\n\ndef main():\n clear_screen()\n art = a.Artwork()\n print(art.get_main_logo())\n\n current_level = player.get_position()['z']\n print(messages.storyline(current_level))\n\n while True:\n action = input(get_story_ps1()).lower()\n\n # Update map for each round\n player.set_map()\n\n available_actions = get_commands()\n\n if action in ['help', '?', 'commands']:\n for act in available_actions:\n print(act)\n\n if action in ['q', 'quit']:\n player.set_hp(-player.get_hp())\n if player.is_dead():\n exit(messages.death())\n\n if action in ['e', 'east', 'go east']:\n if 'Go [E]ast' in available_actions:\n player.set_position(x=player.get_position()['x'] + 1)\n enter_room(messages.go_east())\n else:\n print(messages.hit_wall())\n\n if action in ['w', 'west', 'go west']:\n if 'Go [W]est' in available_actions:\n player.set_position(x=player.get_position()['x'] - 1)\n enter_room(messages.go_west())\n else:\n print(messages.hit_wall())\n\n if action in ['n', 'north', 'go north']:\n if 'Go [N]orth' in available_actions:\n player.set_position(y=player.get_position()['y'] - 1)\n enter_room(messages.go_north())\n else:\n print(messages.hit_wall())\n\n if action in ['s', 'south', 'go south']:\n if 'Go [S]outh' in available_actions:\n player.set_position(y=player.get_position()['y'] + 1)\n enter_room(messages.go_south())\n else:\n print(messages.hit_wall())\n\n if action in ['l', 'look', 'look around']:\n check_room()\n\n if action in ['m', 'map', 'check map']:\n check_map()\n\n if action in ['st', 'stat', 'status', 'show status']:\n print(player.get_player_status())\n\n\ndef get_commands(monster=False):\n if monster:\n commands = [\n '[A]ttack'\n ]\n else:\n commands = [\n '[L]ook around'\n ]\n\n commands.append('[M]ap')\n commands.append('[St]atus\\n')\n\n current_pos = player.get_position()\n\n if not monster:\n if current_pos['x'] - 1 >= 0:\n if world.current_map[current_pos['y']][current_pos['x'] - 1] != ' ':\n commands.append('Go [W]est')\n\n if current_pos['x'] + 1 <= len(world.current_map[current_pos['y']]) - 1:\n if world.current_map[current_pos['y']][current_pos['x'] + 1] != ' ':\n commands.append('Go [E]ast')\n\n if current_pos['y'] - 1 >= 0:\n if world.current_map[current_pos['y'] - 1][current_pos['x']] != ' ':\n commands.append('Go [N]orth')\n\n if current_pos['y'] + 1 <= len(world.current_map[current_pos['y']]) - 1:\n if world.current_map[current_pos['y'] + 1][current_pos['x']] != ' ':\n commands.append('Go [S]outh')\n\n return commands\n\n\ndef look_for_end():\n current_position = player.get_position()\n\n if world.current_map[current_position['y']][current_position['x']] == 'E':\n world.set_map(current_position['z'] + 1)\n new_pos = world.init_player()\n player.reset_map()\n player.set_position(x=new_pos[0], y=new_pos[1], z=new_pos[2])\n\n clear_screen()\n print(messages.find_stairs())\n print(messages.storyline(new_pos[2]))\n\n\ndef enter_room(message):\n print(message)\n look_for_end()\n\n if np.random.randint(100) > 98:\n if player.get_hp() < player.max_hp:\n player.set_hp(player.max_hp)\n print(messages.power_up())\n\n else:\n # Check if monster spawns, bosses will always spawn!\n if np.random.randint(100) < 80 or world.current_map[player.get_position()['y']][player.get_position()['x']] == 'X':\n kinds = mo.Monster.get_all_kinds()\n\n if world.current_map[player.get_position()['y']][player.get_position()['x']] == 'X':\n boss = mo.Monster.get_all_bosses()[player.get_position()['z']]\n monster = mo.Monster(boss=True, kind=boss['name'])\n else:\n monster = mo.Monster(kind=kinds[np.random.randint(len(kinds))]['name'])\n\n print(messages.monster_spawn(monster.get_kind(), monster.get_sound()))\n\n while not monster.is_dead():\n action = input(get_action_ps1()).lower()\n\n available_actions = get_commands(True)\n\n # Check HP affecting conditions\n if player.get_condition('poison') or player.get_condition('burn') or player.get_condition('frozen'):\n cond_dmg = int(player.get_level() * monster.get_dmg() / 2)\n\n if player.get_condition('poison'):\n print('{}The poison burns in your veins, you take {} dmg{}'.format(\n Fore.LIGHTCYAN_EX,\n cond_dmg,\n Style.RESET_ALL))\n elif player.get_condition('frozen'):\n print('{}The frost burn is taking a toll on you, you take {} dmg{}'.format(\n Fore.LIGHTCYAN_EX,\n cond_dmg,\n Style.RESET_ALL))\n else:\n print('{}The burn wounds are taking a toll on you, you take {} dmg{}'.format(\n Fore.LIGHTCYAN_EX,\n cond_dmg,\n Style.RESET_ALL))\n\n player.set_hp(-cond_dmg)\n\n if player.is_dead():\n print(Fore.RED + messages.death() + Style.RESET_ALL)\n exit(0)\n\n if action in ['help', '?', 'commands']:\n for act in available_actions:\n print(act)\n\n if action == 'q':\n player.set_hp(-player.get_hp())\n if player.is_dead():\n exit(messages.death())\n\n elif action in ['a', 'attack']:\n dmg = np.random.randint(player.get_dmg())\n\n if player.get_condition('stun'):\n print('You are stunned, and unable to move')\n player.set_condition(name='stun', value=False)\n\n elif player.get_condition('sleep'):\n print('You are fast asleep')\n player.set_condition(name='sleep', value=False)\n\n elif dmg > 0:\n print(Fore.YELLOW + messages.attack(dmg) + Style.RESET_ALL)\n monster.set_hp(-dmg)\n\n if monster.is_dead():\n print(Fore.GREEN + messages.monster_dead(monster) + Style.RESET_ALL)\n\n else:\n print(messages.miss())\n\n if not monster.is_dead():\n\n monster_dmg = np.random.randint(monster.get_dmg()) - player.get_shield()\n\n if monster_dmg > 0:\n if monster.has_ability():\n if np.random.randint(100) > (100 - monster.get_ability_chance()) and \\\n not player.get_condition(monster.get_ability_type()):\n print('As the {}, attacks you are infected by: {}'.format(\n monster.get_kind(),\n monster.get_ability_type()))\n player.set_condition(name=monster.get_ability_type(), value=True)\n\n player.set_hp(-monster_dmg)\n print(Fore.MAGENTA + messages.monster_attack(monster, monster_dmg) + Style.RESET_ALL)\n\n else:\n print(messages.monster_miss(monster))\n\n else:\n if monster.has_ability():\n player.set_condition(name=monster.get_ability_type(), value=False)\n player.set_xp(monster.get_xp())\n\n if action in ['st', 'stat', 'status', 'show status']:\n print(player.get_player_status())\n\n if player.is_dead():\n print(Fore.RED + messages.death() + Style.RESET_ALL)\n exit(0)\n\n return\n\n\ndef check_room():\n room = '{0:0>3}{1:0>3}{2:0>3}'.format(player.get_position()['x'],\n player.get_position()['y'],\n player.get_position()['z'])\n\n if room in world.secrets:\n chance = world.secrets[room]\n else:\n chance = np.random.randint(100)\n # Make sure a repeat visit does not activate multiple secrets.\n world.secrets[room] = 0\n\n current_pos = player.get_position()\n\n if world.current_map[current_pos['y']][current_pos['x']] == 'S':\n if chance > 60:\n # todo; add weapon power-ups\n # Create a list with random power-ups\n player.hp = player.max_hp\n print(messages.power_up())\n\n elif chance in range(50, 60):\n player.set_hp(-10)\n print(messages.trap(10))\n\n elif chance in [5, 11, 20, 44, 49]:\n weapons = list(player.player_weapons.keys())\n weapon = weapons[player.get_position()['z']]\n\n print('You found a {}'.format(weapon))\n decided = False\n\n while not decided:\n ans = input('{0}Do you wish to pick up the {2} (dmg: {3})? '\n '{1}(yes|no): '.format(Fore.CYAN,\n Style.RESET_ALL,\n weapon,\n player.player_weapons[weapon])).lower()\n if ans in ['y', 'yes']:\n player.set_dmg(player.player_weapons[weapon])\n decided = True\n elif ans in ['n', 'no']:\n decided = True\n\n else:\n print('You found nothing of interest')\n else:\n print('You found nothing of interest')\n\n\ndef check_map():\n clear_screen()\n for i in player.get_map():\n line = ''\n for j in i:\n line += j\n print(line)\n\n\ndef get_action_ps1():\n return '{}o{}={}[{}====>{} : '.format(Fore.RED, Fore.YELLOW, Fore.LIGHTYELLOW_EX, Fore.WHITE, Style.RESET_ALL)\n\n\ndef get_story_ps1():\n return '{0}~\\'({1}@{0}),~{2} : '.format(Fore.GREEN, Fore.RED, Style.RESET_ALL)\n\n\ndef clear_screen():\n unix = ['linux1', 'linux2', 'darwin']\n windows = ['win32']\n\n if platform in unix:\n system('clear')\n elif platform in windows:\n system('cls')\n\n\nif __name__ == '__main__':\n world = mp.Map()\n player = p.Player()\n messages = s.Story()\n # Initiate the player into the start position of the map\n x, y, z = world.init_player()\n player.set_position(x=x, y=y, z=z)\n\n main()\n","sub_path":"crawl.py","file_name":"crawl.py","file_ext":"py","file_size_in_byte":11435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"509276999","text":"# -*- coding: utf-8 -*-\n\"\"\"\nA library created by PhishMe Intelligence to support developing integregations with client security architecture.\n\nFor more information on gaining access to PhishMe Intelligence data at\nhttps://phishme.com/product-services/phishing-intelligence\n\nIf you are already a customer, detailed documentation on the Intelligence API can be found at\nhttps://www.threathq.com/documentation/display/MAD\n\nThe download and/or use of this PhishMe application is subject to the terms and conditions set forth at https://phishme.com/legal/integration-applications/.\n\nCopyright 2013-2017 PhishMe, Inc. All rights reserved.\n\nThis software is provided by PhishMe, Inc. (\"PhishMe\") on an \"as is\" basis and any express or implied warranties,\nincluding but not limited to the implied warranties of merchantability and fitness for a particular purpose, are\ndisclaimed in all aspects. In no event will PhishMe be liable for any direct, indirect, special, incidental or\nconsequential damages relating to the use of this software, even if advised of the possibility of such damage. Use of\nthis software is pursuant to, and permitted only in accordance with, the agreement between you and PhishMe.\n\nAuthor: PhishMe Intelligence Solutions Engineering\nSupport: support@phishme.com\n\"\"\"\n\nfrom os import path\nfrom setuptools import setup, find_packages\n\nfrom phishme_intelligence import __version__\n\npackage_path = path.abspath(path.dirname(__file__))\n\nsetup(\n name='phishme_intelligence',\n version=__version__,\n url='https://www.threathq.com/documentation/display/MAD',\n license='Proprietary',\n description='PhishMe Intelligence Integration Library',\n long_description=__doc__,\n author='PhishMe Intelligence Solutions Engineering',\n author_email='support@phishme.com',\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Information Technology',\n 'License :: Free To Use But Restricted',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Topic :: Security',\n ],\n keywords='phishing threat intelligence',\n install_requires=['requests>=2.3', 'defusedxml>=0.5.0', 'six>=1.11.0'],\n packages=find_packages(),\n include_package_data=True\n)\n","sub_path":"pypi_install_script/phishme_intelligence-4.8.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"35552985","text":"import os\nimport torch\nimport numpy as np\n\nimport cv2\nfrom maskrcnn_benchmark.utils.visualization import cv2_util\nfrom tqdm import tqdm\n\nfrom maskrcnn_benchmark.modeling.roi_heads.mask_head.inference import Masker\nfrom maskrcnn_benchmark.data.evaluation.coco import PanopticMetrics\nfrom maskrcnn_benchmark.data.evaluation.coco import do_coco_evaluation\nfrom maskrcnn_benchmark.data.evaluation.coco import do_coco_semantic_evaluation\n\n\ndef do_coco_panoptic_evaluation(\n dataset,\n predictions_detection,\n predictions_detection_retinamask,\n predictions_semantic,\n box_only,\n output_folder,\n iou_types,\n expected_results,\n expected_results_sigma_tol,\n):\n coco_detection_results = do_coco_evaluation(\n dataset.detection_dataset,\n predictions_detection,\n box_only,\n output_folder,\n iou_types,\n expected_results,\n expected_results_sigma_tol,\n )\n\n coco_detection_retinamask_results = do_coco_evaluation(\n dataset.detection_dataset,\n predictions_detection_retinamask,\n box_only,\n output_folder,\n iou_types,\n expected_results,\n expected_results_sigma_tol,\n )\n\n coco_semantic_results = do_coco_semantic_evaluation(\n dataset.semantic_dataset,\n predictions_semantic,\n output_folder,\n )\n\n pano_cls_inds = []\n panos = []\n ssegs = []\n\n semantic_scores = []\n for pred in predictions_semantic:\n semantic_scores.append(pred[2])\n\n coco = dataset.semantic_dataset.coco\n\n # Generate mask logits\n masker = Masker(threshold=0.5, padding=1)\n for image_id, prediction in tqdm(enumerate(predictions_detection)):\n img_info = dataset.get_img_info(image_id)\n image_width = img_info[\"width\"]\n image_height = img_info[\"height\"]\n prediction = prediction.resize((image_width, image_height))\n masks = prediction.get_field(\"mask\")\n if list(masks.shape[-2:]) != [image_height, image_width]:\n masks = masker(masks.expand(1, -1, -1, -1, -1), prediction)\n masks = masks[0]\n prediction.add_field('mask', masks)\n\n # Display masks\n img_id = dataset.semantic_dataset.ids[image_id]\n path = coco.loadImgs(img_id)[0]['file_name']\n img = cv2.imread(os.path.join(dataset.semantic_dataset.root, path), cv2.IMREAD_COLOR)\n top_predictions = select_top_predictions(prediction)\n # result = img.copy()\n # result = overlay_boxes(result, top_predictions)\n # result = overlay_mask(result, top_predictions)\n # cv2. imwrite(os.path.join(output_folder, path), result)\n # cv2.imshow(\"COCO detections\", result)\n # cv2.waitKey()\n # cv2.destroyAllWindows()\n\n boxes = top_predictions._split_into_xyxy()\n labels = top_predictions.get_field('labels')\n labels = [lab - 53 for lab in labels]\n masks = top_predictions.get_field('mask')\n boxes_sorted = [[] for i in range(4)]\n labels_sorted = []\n masks_sorted = []\n # Remove stuff predictions\n for i in range(len(labels)):\n if (labels[i] >= 0):\n for j in range(len(boxes)):\n boxes_sorted[j].append(boxes[j][i])\n labels_sorted.append(labels[i])\n masks_sorted.append(masks[i])\n\n img_shape = (1, image_height, image_width)\n mask_logits = np.full(img_shape, 0, dtype=np.uint8)\n\n minimum_pixels = 50\n idx_removed = 0\n new_labels = []\n\n zeros = np.zeros(img_shape, dtype=np.uint8)\n seg_logits = np.where((coco_semantic_results[image_id] > 52), zeros, coco_semantic_results[image_id])\n seg_inst_logits = np.where((coco_semantic_results[image_id] <= 52), zeros, coco_semantic_results[image_id] - 52)\n\n label = 53\n for idx, mask in enumerate(masks_sorted):\n label = 53 + idx - idx_removed\n calc = np.full(img_shape, label, dtype=np.uint8)\n xmin = int(boxes_sorted[0][idx])\n ymin = int(boxes_sorted[1][idx])\n xmax = int(boxes_sorted[2][idx].round() + 1)\n ymax = int(boxes_sorted[3][idx].round() + 1)\n\n # Select pixels of seg_inst inside te bbox and add those with the good label\n # TODO manage the inst pixels not in the instance branch\n mask_seg_inst = np.zeros(img_shape)\n mask_seg_inst[0, ymin: ymax, xmin: xmax] = seg_inst_logits[0, ymin: ymax, xmin: xmax]\n cond = (mask_seg_inst == labels_sorted[idx].item()) * (mask.numpy() == 0)\n mask = np.where(cond, mask_seg_inst, mask)\n mask = np.where((mask != 0), calc, mask)\n\n new_mask = np.where((mask_logits != 0), mask_logits, mask)\n cond = (mask != 0) * (mask - mask_logits == label)\n remaining_pixels = cond.sum().item()\n if remaining_pixels >= minimum_pixels:\n mask_logits = new_mask\n new_labels.append(labels_sorted[idx].item())\n else:\n idx_removed += 1\n\n labels_seg_inst = np.delete(np.unique(seg_inst_logits), 0)\n for lab in labels_seg_inst:\n if lab.item() not in new_labels:\n calc = np.full(img_shape, label, dtype=np.uint8)\n cond = (seg_inst_logits == lab.item()) * semantic_scores[image_id] >= 10\n mask_logits = np.where(cond, calc, mask_logits)\n new_labels.append(lab.item())\n label += 1\n\n # Display mask logits\n # print(\"MASK\", np.unique(mask_logits), idx_removed)\n # cv2.imshow(\"Mask logits\", mask_logits[0].astype(np.uint8))\n # cv2.waitKey()\n # cv2.destroyAllWindows()\n\n # Create panoptic logits\n empty = torch.full(img_shape, 255, dtype=torch.uint8)\n pan = np.where((mask_logits == 0), empty, mask_logits)\n pan = np.where((pan == 255), seg_logits, pan)\n\n pano_cls_inds.append(new_labels)\n panos.append(np.squeeze(pan.astype(np.uint8)))\n ssegs.append(np.squeeze(coco_semantic_results[image_id]))\n\n print(\"Start panoptic evaluation\")\n panoptic_metrics = PanopticMetrics()\n coco_panoptic_results = panoptic_metrics.evaluate_panoptic(\n panoptic_metrics.get_unified_pan_result(ssegs, panos, pano_cls_inds), output_folder,\n dataset.semantic_dataset.root)\n\n return coco_detection_results, coco_detection_retinamask_results, coco_semantic_results, coco_panoptic_results\n\n\ndef select_top_predictions(predictions):\n \"\"\"\n Select only predictions which have a `score` > self.confidence_threshold,\n and returns the predictions in descending order of score\n\n Arguments:\n predictions (BoxList): the result of the computation by the model.\n It should contain the field `scores`.\n\n Returns:\n prediction (BoxList): the detected objects. Additional information\n of the detection properties can be found in the fields of\n the BoxList via `prediction.fields()`\n \"\"\"\n confidence_threshold = 0.7\n scores = predictions.get_field(\"scores\")\n keep = torch.nonzero(scores > confidence_threshold).squeeze(1)\n predictions = predictions[keep]\n scores = predictions.get_field(\"scores\")\n _, idx = scores.sort(0, descending=True)\n return predictions[idx]\n\n\ndef compute_colors_for_labels(labels):\n \"\"\"\n Simple function that adds fixed colors depending on the class\n \"\"\"\n palette = torch.tensor([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1], dtype=torch.float32)\n colors = labels[:, None].to(dtype=torch.float32) * palette\n colors = (colors % 255).numpy().astype(\"uint8\")\n return colors\n\n\ndef overlay_boxes(image, predictions):\n \"\"\"\n Adds the predicted boxes on top of the image\n\n Arguments:\n image (np.ndarray): an image as returned by OpenCV\n predictions (BoxList): the result of the computation by the model.\n It should contain the field `labels`.\n \"\"\"\n labels = predictions.get_field(\"labels\")\n boxes = predictions.bbox\n\n colors = compute_colors_for_labels(labels).tolist()\n\n for box, color in zip(boxes, colors):\n box = box.to(torch.int64)\n top_left, bottom_right = box[:2].tolist(), box[2:].tolist()\n image = cv2.rectangle(\n image, tuple(top_left), tuple(bottom_right), tuple(color), 1\n )\n\n return image\n\n\ndef overlay_mask(image, predictions):\n \"\"\"\n Adds the instances contours for each predicted object.\n Each label has a different color.\n\n Arguments:\n image (np.ndarray): an image as returned by OpenCV\n predictions (BoxList): the result of the computation by the model.\n It should contain the field `mask` and `labels`.\n \"\"\"\n masks = predictions.get_field(\"mask\").numpy()\n labels = predictions.get_field(\"labels\")\n colors = compute_colors_for_labels(labels).tolist()\n\n for mask, color in zip(masks, colors):\n thresh = mask[0, :, :, None]\n contours, hierarchy = cv2_util.findContours(\n thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE\n )\n image = cv2.drawContours(image, contours, -1, color, 3)\n\n composite = image\n\n return composite","sub_path":"maskrcnn_benchmark/data/evaluation/coco_panoptic/coco_panoptic_eval.py","file_name":"coco_panoptic_eval.py","file_ext":"py","file_size_in_byte":9278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"65908144","text":"import argparse\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description='Crawling@Home Worker Script'\n )\n\n parser.add_argument('--name', '-n', type=str,\n default='ARKseal', help='Your name')\n parser.add_argument('--url', '-u', type=str,\n default='http://cah.io.community/', help='The Crawling Server')\n parser.add_argument('--debug', '-d', action='store_true',\n help='Add additional prints to debug code')\n parser.add_argument('--notebook', '-b', action='store_true',\n help='Use tqdm.notebook module for notebooks')\n parser.add_argument('--docker', '-k', action='store_true',\n help='Check docker version for latest image')\n\n group = parser.add_mutually_exclusive_group()\n group.add_argument('--hybrid', '-y', action='store_true',\n help='Run the hybrid worker (default)')\n group.add_argument('--cpu', '-c', action='store_true',\n help='Run the cpu worker')\n group.add_argument('--gpu', '-g', action='store_true',\n help='Run the gpu worker')\n\n args = parser.parse_args()\n\n if args.cpu:\n import cpu\n cpu.main(args.name, args.url, args.debug, args.notebook, args.docker)\n elif args.gpu:\n import gpu\n gpu.main(args.name, args.url, args.debug, args.notebook, args.docker)\n else:\n import hybrid\n hybrid.main(args.name, args.url, args.debug,\n args.notebook, args.docker)\n","sub_path":"crawlingathome.py","file_name":"crawlingathome.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"68313368","text":"# -- coding: utf-8 --\r\n\r\n\r\nclass AreaInfo: \r\n '''\r\n 行政区划信息 递归结构 id/name/所属id/下辖行政区划字典(id+行政区划对象)\r\n ''' \r\n \r\n def __init__(self, areaID, areaName, level, dircID): \r\n self.__areaID = areaID\r\n self.__areaName = areaName\r\n self.__level = level\r\n self.__dircID = dircID\r\n self.__areaMap = {} \r\n \r\n \r\n def addArea(self, areaInfo):\r\n '''\r\n 添加行政区划 id已存在或所属id不匹配不添加\r\n ''' \r\n if areaInfo == None:\r\n return\r\n areaID = areaInfo.getAreaID()\r\n dircID = areaInfo.getDircID()\r\n if dircID != self.__areaID:\r\n return\r\n if areaID in self.__areaMap.keys(): \r\n return\r\n self.__areaMap[areaID] = areaInfo\r\n \r\n \r\n def getAreaID(self): \r\n return self.__areaID \r\n \r\n def getAreaName(self): \r\n return self.__areaName \r\n \r\n def getLevel(self): \r\n return self.__level \r\n \r\n def getDircID(self): \r\n return self.__dircID \r\n \r\n def getAreaMap(self): \r\n return self.__areaMap\r\n \r\n \r\n def isContainsID(self, areaID):\r\n '''\r\n 是否包含直辖的指定id行政区划信息\r\n '''\r\n if areaID in self.__areaMap.keys(): \r\n return True\r\n return False\r\n \r\n \r\n def isSubChildID(self, childID, childLevel):\r\n '''\r\n 指定ID号是否隶属于当前行政区划或当前行政区划\r\n '''\r\n flagChild = False\r\n \r\n if self.__level == childLevel:\r\n if childID == self.__areaID:\r\n flagChild = True\r\n else: \r\n if self.__level == 0: \r\n flagChild = True\r\n elif self.__level == 1: # 当前行政区划为省\r\n if childLevel == 2 and self.isContainsID(childID):\r\n flagChild = True\r\n elif childLevel == 3:\r\n areaCounty = self.getAreaByID(childID)\r\n if areaCounty != None: \r\n areaCity = self.getAreaByID(areaCounty.getDircID())\r\n if areaCity != None and self.isContainsID(areaCity.getAreaID()): \r\n flagChild = True\r\n elif self.__level == 2: # 当前行政区划为市\r\n if childLevel == 3:\r\n if self.isContainsID(childID):\r\n flagChild = True\r\n \r\n return flagChild\r\n \r\n \r\n def getAreaIDList(self):\r\n '''\r\n 获取直辖的行政区划id列表\r\n ''' \r\n ary = []\r\n for key in self.__areaMap.keys(): \r\n ary.append(key)\r\n if len(ary) == 0:\r\n return None\r\n else:\r\n return ary\r\n \r\n \r\n def getAreaByID(self, areaID): \r\n '''\r\n 递归查询指定id行政区划对象\r\n ''' \r\n return self.__getArea(areaID, self) \r\n \r\n \r\n def __getArea(self, areaID, areaInfo):\r\n areaMap = areaInfo.__areaMap\r\n if len(areaMap) == 0:\r\n return None\r\n if areaID in areaMap.keys(): \r\n return areaMap[areaID]\r\n areaInfoCur = None\r\n for key in areaMap.keys(): \r\n areaInfoCur = self.__getArea(areaID, areaMap[key])\r\n if areaInfoCur != None:\r\n break\r\n return areaInfoCur\r\n \r\n \r\n","sub_path":"src/common/entity/AreaInfo.py","file_name":"AreaInfo.py","file_ext":"py","file_size_in_byte":3524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"158309967","text":"from .utils import TestCase\nimport os\nimport sys\nfrom tempfile import mktemp\nimport shakedown\nimport shakedown.site\nfrom shakedown.frontend import shake_run\nimport requests\nimport pkg_resources\nfrom six.moves import cStringIO as StringIO\n\nsite_customized = False\n\nclass ShakeRunSiteCustomizationTest(TestCase):\n \"Make sure ``shake run`` calls site.load()\"\n def setUp(self):\n super(ShakeRunSiteCustomizationTest, self).setUp()\n self.forge.replace(shakedown.site, \"load\")\n self.forge.replace_with(sys, \"stderr\", StringIO())\n def test_shake_run_calls_site_load(self):\n shakedown.site.load()\n self.forge.replay()\n with self.assertRaises(SystemExit):\n shake_run.shake_run([])\n\nclass CustomizationTest(TestCase):\n def get_customization_source(self):\n return \"import {0}; {0}.site_customized=True\".format(__name__)\n def get_customization_function(self):\n def _customize():\n global site_customized\n site_customized = True\n return _customize\n def test_customize_via_shakerc(self):\n shakedownrc_path = mktemp()\n self.forge.replace(os.path, \"expanduser\")\n os.path.expanduser(\"~/.shakedown/shakerc\").whenever().and_return(shakedownrc_path)\n with open(shakedownrc_path, \"w\") as f:\n f.write(self.get_customization_source())\n self.forge.replay()\n self.assert_customization_loaded()\n def test_customize_via_env_var(self):\n os.environ[\"SHAKEDOWN_SETTINGS\"] = custom_filename = mktemp()\n self.addCleanup(os.environ.pop, \"SHAKEDOWN_SETTINGS\")\n with open(custom_filename, \"w\") as f:\n f.write(self.get_customization_source())\n self.assert_customization_loaded()\n def test_customize_via_url(self):\n url = \"http://nonexistent.com/some/path/to/custom/file.py\"\n self.forge.replace(requests, \"get\")\n fake_response = self.forge.create_mock(requests.Response)\n fake_response.raise_for_status().whenever()\n fake_response.content = self.get_customization_source()\n requests.get(url).and_return(fake_response)\n os.environ[\"SHAKEDOWN_SETTINGS\"] = url\n self.addCleanup(os.environ.pop, \"SHAKEDOWN_SETTINGS\")\n self.forge.replay()\n self.assert_customization_loaded()\n def test_customize_via_pkgutil_entry_point(self):\n self.forge.replace(pkg_resources, \"iter_entry_points\")\n entry_point = self.forge.create_wildcard_mock()\n pkg_resources.iter_entry_points(\"shakedown.site.customize\").and_return(iter([entry_point]))\n entry_point.load().and_return(self.get_customization_function())\n self.forge.replay()\n self.assert_customization_loaded()\n def assert_customization_loaded(self):\n global site_customized\n site_customized = False\n shakedown.site.load()\n self.assertTrue(site_customized, \"Customization not loaded!\")\n","sub_path":"tests/test_site_customization.py","file_name":"test_site_customization.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"401473705","text":"# NOTE: to install nltk\n# command line: pip3 install nltk\n# in idle shell: import nltk, press enter\n# in idle shell: nltk.download(), press enter\n# a graphical interface will show, click all and click download\n\nfrom nltk.corpus import stopwords #common words\nfrom nltk.cluster.util import cosine_distance # return cosine between vectors\nimport numpy as np # scientific computing\nimport networkx as nx # study of complex networks\nimport re # regular expression\nimport io\n\n# pip3 install dash==0.42.0\n# pip3 install dash-daq==0.1.0\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\nimport plotly.graph_objs as go\n\nimport genius_api_class\n\n# global variables for lyrics, songs names, and artist names\n# two of the same for comparing \ngenius = genius_api_class.GeniusAPI()\nsong_titles = []\nsong_artist = []\nsong_choice = 10\nwordX = []\ncountY = []\nsongNameArtist = \"\"\n \ngenius2 = genius_api_class.GeniusAPI()\nsong_titles2 = []\nsong_artist2 = []\nsong_choice2 = 10\nwordX2 = []\ncountY2 = []\nsongNameArtist2= \"\"\n\n# NOTE: Need to use command line, not idle\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\ndef main():\n dash_plot()\n app.run_server()\n# end def main\n \ndef dash_plot():\n # text that is going to overwritten\n markdown_text = '''\n # MADE MAIN FUNCTION\n ### Dash and Markdown\n \n Dash apps can be written in Markdown.\n Dash uses the [CommonMark](http://commonmark.org/)\n specification of Markdown.\n Check out their [60 Second Markdown Tutorial](http://commonmark.org/help/)\n if this is your first introduction to Markdown!\n '''\n\n app.layout = html.Div([\n # first song\n # make input\n dcc.Input(id='input-1-submit', type='text', value='', placeholder=\"Enter Song or Artist\"),\n\n # make drpdown\n dcc.Dropdown(\n id=\"dropdown1\",\n options=[\n {'label': 'Doomsday', 'value': 0},\n {'label': 'Beef Rap', 'value': 1}\n ],\n placeholder=\"Select a Song\"\n ),\n html.P(\" \"),\n\n # secong song\n dcc.Input(id='input-2-submit', type='text', value='', placeholder=\"Enter Song or Artist\"),\n # make drpdown\n dcc.Dropdown(\n id=\"dropdown2\",\n options=[\n {'label': 'Doomsday', 'value': 0},\n {'label': 'Beef Rap', 'value': 1}\n ],\n placeholder=\"Select a Song\"\n ),\n\n html.P(\"\"),\n # make graph\n dcc.Graph(id='example-graph'),\n\n # make h2 text\n html.H2(children='Summarization'),\n\n # make markdown\n dcc.Markdown(id='markdown1', children=markdown_text),\n\n # make space at the bottom of the screen\n html.P(\" \"),\n html.P(\" \"),\n\n dcc.Markdown(id='markdown2', children=markdown_text)\n ])\n\n # First callback for input to update dropdown\n @app.callback(Output('dropdown1', 'options'),\n [Input('input-1-submit', 'n_submit'), Input('input-1-submit', 'n_blur')],\n [State('input-1-submit', 'value')])\n \n # update dropdown with new labels and values\n def update_dropdown(ns1, nb1, input1):\n \n # empty array\n songs = []\n song_titles = []\n song_artist = []\n\n # find songs\n genius.find_song(input1)\n \n # get top songs and artist\n song_titles, song_artist = genius.top_results()\n # loop through all songs titles and artist and combine them\n for i in range(len(song_titles)):\n songs.append((song_titles[i] + ' by ' + song_artist[i]))\n\n # return results \n return [{'label': songs[i], 'value': i} for i in range(len(songs))]\n # end def update_dropdown\n\n # second song\n # First callback for input to update dropdown\n @app.callback(Output('dropdown2', 'options'),\n [Input('input-2-submit', 'n_submit'), Input('input-2-submit', 'n_blur')],\n [State('input-2-submit', 'value')])\n \n # update dropdown with new labels and values\n def update_dropdown2(ns1, nb1, input1):\n \n # empty array\n songs = []\n song_titles2 = []\n song_artist2 = []\n\n # find songs\n genius2.find_song(input1)\n \n # get top songs and artist\n song_titles2, song_artist2 = genius2.top_results()\n\n # loop through all songs titles and artist and combine them\n for i in range(len(song_titles2)):\n songs.append((song_titles2[i] + ' by ' + song_artist2[i]))\n\n #print(songs)\n # return results \n return [{'label': songs[i], 'value': i} for i in range(len(songs))]\n #end def update_dropdown2\n\n # second callback for dropdown to update chart\n @app.callback(\n Output('example-graph', 'figure'),\n [dash.dependencies.Input('dropdown1', 'value'),\n Input('dropdown2', 'value')]\n )\n\n # update graph with words and word count from dropdown\n def update_figure(input1, input2):\n # NOTE: returns index 0-9\n # clear variables\n countY = []\n wordX = []\n songNameArtist = \"\"\n countY2 = []\n wordX2 = []\n songNameArtist2 = \"\"\n \n # input is not empty\n if input1 is not None:\n # get most common words from song\n countY, wordX = mostCommonWords(genius.song_lyrics(input1))\n # get song name and artist\n songNameArtist = genius.song_name_artist(input1)\n # input is not empty\n if input2 is not None:\n # get most common words from song\n countY2, wordX2 = mostCommonWords(genius2.song_lyrics(input2))\n wordX2 = wordX\n countY2 = matchLists(wordX, wordX2, countY2)\n # get song name and artist\n songNameArtist2 = genius2.song_name_artist(input2)\n # plot words, word count, and legend to a graph\n return {\n 'data': [go.Scatter(\n {'marker': {'size': 300}},\n x = wordX,\n y = countY,\n name = songNameArtist\n \n ),go.Scatter(\n {'marker': {'size': 300}},\n x = wordX2,\n y = countY2,\n name = songNameArtist2\n )],\n 'layout': go.Layout(\n xaxis={\n 'title': \"Words\"\n },\n yaxis={\n 'title': \"Word Count\"\n },\n title = \"Compare Songs\", \n hovermode = 'closest'\n )\n }\n # end def update_figure\n\n # third callback for dropdown to update text\n @app.callback(\n Output('markdown1', 'children'),\n [dash.dependencies.Input('dropdown1', 'value')]\n )\n\n # update text with text summarization for first song\n def update_text(input1):\n #print(input1)\n summary = \"\"\n if input1 is not None:\n summary = generate_summary( genius.song_lyrics(input1), 10)\n return u' '.join(summary)\n #end def update_text\n\n # Second Song\n # third callback for dropdown to update text\n @app.callback(\n Output('markdown2', 'children'),\n [dash.dependencies.Input('dropdown2', 'value')]\n )\n\n # update text with text summarization for second song\n def update_text(input1):\n #print(input1)\n summary = \"\"\n if input1 is not None:\n summary = generate_summary( genius2.song_lyrics(input1), 10)\n return u' '.join(summary)\n #end def update_text\n# end dash_plot\n\ndef matchLists(list1word, list2word, list2count):\n newlist2 = []\n newtemp = []\n \n # loop 35 times\n for i in range(35):\n temp = 0\n try:\n # get index of word\n temp = list2word.index(list1word[i])\n except ValueError:\n # if no word\n temp = -1\n\n # if word exists\n if temp is not -1:\n # append word count\n newlist2.append(list2count[temp])\n newtemp.append(list2word[temp])\n else:\n # if word doesn't exists append 0\n newlist2.append(0)\n newtemp.append(list1word[i])\n\n # return new list\n return newlist2\n# end def matchLists\n\ndef selectionSortInternally(word_count, word):\n for i in range(len(word_count)): #i goes from = to lenth of array\n smallest=findSmallestFrom(word_count,i) #find smallest item in array from current i\n holdSmallest=word_count[smallest] #hold current smallest value found\n holdWord=word[smallest]\n word_count[smallest]=word_count[i] #move the value in the current lower index to whatever smallest was\n word[smallest]=word[i]\n word_count[i]=holdSmallest #put smallest's value in its propar place\n word[i]=holdWord\n return word_count, word #return array of sorted. Only one array every existed\n# end def selectionSortInternally\n\ndef findSmallestFrom(word_count, index):\n smallest = word_count[index] #hold start item for comparision\n smallest_index = index #hold start location given\n for i in range(index+1, len(word_count)): #go from star+1 to end of array\n if word_count[i] 0:\n self._is_on = True\n else:\n self._is_on = False\n\n self.async_write_ha_state()\n\n @callback\n def availability_message_received(msg):\n \"\"\"Handle a new received MQTT availability message.\"\"\"\n payload = msg.payload\n\n if payload == \"online\":\n self._available = True\n elif payload == \"offline\":\n self._available = False\n else:\n _LOGGER.info(f\"Invalid payload received for {self.name}\")\n return\n\n self._sub_state = await async_subscribe_topics(\n self.hass,\n self._sub_state,\n {\n \"state_topic\": {\n \"topic\": self._topic,\n \"msg_callback\": state_message_received,\n \"qos\": 0,\n },\n \"availability_topic\": {\n \"topic\": self._availability_topic,\n \"msg_callback\": availability_message_received,\n \"qos\": 0,\n }\n },\n )\n\n @property\n def unique_id(self):\n \"\"\"Return a unique ID to use for this entity.\"\"\"\n return f\"{DOMAIN}_{self._cam_name}_{self._obj_name}_binary_sensor\"\n\n @property\n def device_info(self):\n return {\n \"identifiers\": {(DOMAIN, self._entry.entry_id)},\n \"name\": NAME,\n \"model\": VERSION,\n \"manufacturer\": NAME,\n }\n\n @property\n def name(self):\n \"\"\"Return the name of the sensor.\"\"\"\n friendly_camera_name = self._cam_name.replace('_', ' ')\n return f\"{friendly_camera_name} {self._obj_name} Motion\".title()\n\n @property\n def is_on(self):\n \"\"\"Return true if the binary sensor is on.\"\"\"\n return self._is_on\n\n @property\n def device_class(self):\n return DEVICE_CLASS_MOTION\n\n @property\n def available(self) -> bool:\n return self._available\n","sub_path":"custom_components/frigate/binary_sensor.py","file_name":"binary_sensor.py","file_ext":"py","file_size_in_byte":4186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"454548590","text":"from pyaccum import accumulate\n\n# ORIGINAL CODE\n\nclass Conjunction:\n def min_gen(self, inst):\n return [self._min_gen(inst)]\n \n def _min_gen(self, inst):\n features = []\n for i in range(len(self)):\n if self[i] is None:\n features.append(inst[i])\n elif is_wildcard(self[i]) or self[i] == inst[i]:\n features.append(self[i])\n else:\n features.append(Wildcard)\n return Conjunction(tuple(features))\n\n# NEW CODE\n\nclass Conjunction:\n @accumulate(lambda x: [Conjunction(tuple(x))])\n def min_gen(self, inst):\n for i in range(len(self)):\n if self[i] is None:\n yield inst[i]\n elif is_wildcard(self[i]) or self[i] == inst[i]:\n yield self[i]\n else:\n yield Wildcard","sub_path":"test_2.py","file_name":"test_2.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"419064212","text":"import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nfrom collections import Counter\n\ndata = np.load('data2D.npy')\n\n\ndef getdist(X,Y):\n\t\n\tXX = tf.reshape(tf.reduce_sum(tf.multiply(X,X),1),[-1,1])\n\tYY = tf.reshape(tf.reduce_sum(tf.multiply(tf.transpose(Y),tf.transpose(Y)),0),[1,-1])\n\tXY = tf.scalar_mul(2.0,tf.matmul(X,tf.transpose(Y)))\n\n\treturn XX - XY + YY\n\n\ndef k_means(K,data,LEARNINGRATE,epochs,valid_start):\n\n\ttrain_data = data[:valid_start]\n\tvalid_data = data[valid_start:]\n\n\tN = train_data.shape[0]\n\tD = train_data.shape[1]\n\n\tx = tf.placeholder(\"float32\", [None,D])\n\n\tmu = tf.Variable(tf.truncated_normal([K,D],stddev=0.25))\n\n\tdist = getdist(x,mu)\n\n\tmin_d = tf.reduce_min(dist,1)\n\n\tloss = tf.reduce_sum(min_d,0)\n\n\tadamop = tf.train.AdamOptimizer(LEARNINGRATE, beta1=0.9, beta2=0.99, epsilon=1e-5).minimize(loss)\n\n\tassign = tf.argmin(dist,1)\n\n\tinit = tf.initialize_all_variables()\n\n\ttrain_loss = np.zeros(epochs)\n\n\n\twith tf.Session() as sess:\n\n\t\tsess.run(init)\n\n\t\tfor epoch in range(epochs):\n\t\t\tL, _ = sess.run([loss, adamop], feed_dict={x:train_data})\n\t\t\ttrain_loss[epoch] = L \n\n\t\tcluster_assign = sess.run(assign, feed_dict={x:train_data})\n\n\t\tvalid_loss = sess.run(loss, feed_dict={x:valid_data})\n\n\treturn train_loss, cluster_assign, valid_loss\n\n\nepochs = 600\nK = 3\n\n\n### PART 2 ### \n\n# valid_loss1 = []\n# valid_loss2 = []\n# valid_loss3 = []\n\n\n# for eta in [0.1, 0.01, 0.001]:\n\n# \tvalidError, cluster_assign, _ = k_means(K, data, eta, epochs, len(data))\n\t\n# \tif eta == 0.1:\n# \t\tvalid_loss1 = validError\n# \tif eta == 0.01:\n# \t\tvalid_loss2 = validError\n# \tif eta == 0.001:\n# \t\tvalid_loss3 = validError\n\n# \tprint eta\n\n# plt.figure()\n# plt.plot(range(epochs),valid_loss1[:],label=\"0.1\",linewidth=0.75)\n# plt.plot(range(epochs),valid_loss2[:],label=\"0.01\",linewidth=0.75)\n# plt.plot(range(epochs),valid_loss3[:],label=\"0.001\",linewidth=0.75)\n# plt.legend(loc='best')\n# plt.title('Loss vs. Number of Epochs')\n# plt.xlabel('Number of Epochs')\n# plt.ylabel('Loss')\n# plt.show()\n\n\n\nLEARNINGRATE = 0.01\n\n# train_loss, cluster_assign, _ = k_means(K, data, LEARNINGRATE, epochs, len(data))\n# print 'Minimum Training Loss: ', train_loss.min()\n# print 'Minimum Validation Loss: ', valid_loss.min()\n\n# plt.figure()\n# plt.plot(range(epochs),train_loss)\n# plt.title('Loss vs. Number of Epochs')\n# plt.xlabel('Number of Epochs')\n# plt.ylabel('Loss')\n# plt.show()\n\n\n\n### PART 3 ###\n\n\n# for k in range(1,6):\n# \tprint k \n\n# \ttrain_loss, cluster_assign, _ = k_means(k, data, LEARNINGRATE, epochs, len(data))\n# \tprint 'Minimum Training Loss: ', train_loss.min()\n\n# \tsamples = dict(Counter(cluster_assign))\n# \tsamples.update((x,y*100.0/data.shape[0]) for x,y in samples.items())\n# \tprint '% of points in each cluster: ', samples \n\n# \t# plot\n# \tcolors = ['c','r','g','m','y']\n# \tfor i in range(k):\n# \t\tcluster_data = data[:len(cluster_assign)][cluster_assign==i].T\n# \t\tif i == 0:\n# \t\t\tplt.scatter(cluster_data[0],cluster_data[1],color=colors[i],label=\"K = 1\")\n# \t\tif i == 1:\n# \t\t\tplt.scatter(cluster_data[0],cluster_data[1],color=colors[i],label=\"K = 2\")\n# \t\tif i == 2:\n# \t\t\tplt.scatter(cluster_data[0],cluster_data[1],color=colors[i],label=\"K = 3\")\n# \t\tif i == 3:\n# \t\t\tplt.scatter(cluster_data[0],cluster_data[1],color=colors[i],label=\"K = 4\")\n# \t\tif i == 4:\n# \t\t\tplt.scatter(cluster_data[0],cluster_data[1],color=colors[i],label=\"K = 5\")\n# \t\tplt.legend(loc='best')\n# \tplt.show()\n\n\n\n### PART 4 ###\n\n# for k in range(1,6):\n# \tprint k\n\n# \ttrain_loss, cluster_assign, valid_loss = k_means(k, data, LEARNINGRATE, epochs, 2*len(data)/3)\n# \tprint 'Minimum Training Loss: ', train_loss.min()\n# \tprint 'Minimum Validation Loss: ', valid_loss.min()\n","sub_path":"lab3/k_means.py","file_name":"k_means.py","file_ext":"py","file_size_in_byte":3648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"143234067","text":"# -*- coding: utf-8 -*-\nfrom admintool.nc.lib.Wrapper import wrapper\nfrom admintool.nc.lib import nc_id\nfrom admintool.nc.models import AOT\nfrom django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned\n\ndef index(request):\n \"\"\"\n обработка входных параметров\n \"\"\"\n return wrapper(request=request,\n req_params=['attr_schema','object_types', 'attr'],\n worker=worker, context='aot')\n\n\ndef worker(req):\n \"\"\"\n функция отвязки атрибута\n \"\"\"\n error = False\n \n schema = req.params()['attr_schema']\n object_types = req.params()['object_types']\n attr = req.params()['attr']\n \n for object_type in object_types:\n if not error:\n #Проверяем - нет ли уже привязки данного атрибута к объектному типу\n try:\n aot = AOT.objects.get(schema=schema, object_type=object_type, attr=attr)\n except ObjectDoesNotExist:\n #привязки нет => создём привязку\n AOT.create(schema=schema, object_type=object_type, attr=attr, options=0)\n except MultipleObjectsReturned:\n error = True\n reason = u\"Атрибут привязан к данному OT больше чем 1 раз[ID атрибута: %s, ID OT: %s(ошибка в БД)]\" % (attr.attr, object_type.object_type,)\n else:\n if aot.options not in (0,2,):\n #атрибут уже привязан на данном ОТ - выкинем предупреждение и ничего не будем делать\n error = True\n reason = u\"Неизвестный тип options = %s(ошибка БД)\" % aot.options\n else: \n if aot.options == 0:\n #атрибут уже привязан на данном ОТ - пропускаем его\n pass\n \n #привязка найдена - проверяем её на ORIGIN\n if aot.options == 2:\n #атрибут был отвязан - привяжем его снова\n AOT.bind(schema=schema, object_type=object_type, attr=attr)\n \n if error:\n return {\"success\": False, \"errors\": reason}\n else:\n return {\"success\": True, \"message\": \"атрибут %s успешно привязан\" % str(attr.id)}\n ","sub_path":"nc/aot/bind/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"511080877","text":"import json\nimport xml.etree.ElementTree as ET\nfrom LTRLibrary import LTRLibrary\nimport misc\n\nclass LibraryFormatter(LTRLibrary):\n\n def reProcessQueryDocFeatureVector(self, min_max, trainingFile):\n fout = open(trainingFile + \".tmp\", \"w\")\n\n with open(trainingFile, \"r\") as fin:\n for f in fin:\n fields = f.strip().split(\" \")\n rel = float(fields[0])\n query = int(fields[1].split(\":\")[1])\n fv = {}\n for i in range(2, len(fields)):\n feat = fields[i]\n fid, fvalue = feat.split(\":\")\n min_ = min_max[self.featureIdToName[int(fid)]][\"min\"]\n max_ = min_max[self.featureIdToName[int(fid)]][\"max\"]\n delta = max_ - min_\n\n if abs(delta) <= 0.00000001:\n new_value = 0.0\n else:\n new_value = (float(fvalue) - min_) / delta\n fv[int(fid)] = new_value\n\n misc.writeRankLibLine(rel, query, fv, fout)\n misc.rename(trainingFile + \".tmp\", trainingFile)\n\n\n def processQueryDocFeatureVector(self,docClickInfo,trainingFile, min_max):\n with open(trainingFile,\"w\") as output:\n self.featureNameToId = {}\n self.featureIdToName = {}\n self.curFeatIndex = 1\n self.curQuery = 0\n curListOfFv = []\n curQueryAndSource = \"\"\n for query,docId,relevance,source,featureVector in docClickInfo:\n if curQueryAndSource != query + source:\n #Time to flush out all the pairs\n misc.writeRankLib(curListOfFv,output,self.curQuery);\n misc.save_mm(curListOfFv, self.featureIdToName, min_max)\n curListOfFv = []\n curQueryAndSource = query + source\n self.curQuery += 1\n\n curListOfFv.append((relevance,self._makeFeaturesMap(featureVector)))\n misc.writeRankLib(curListOfFv,output,self.curQuery) #This catches the last list of comparisons\n\n def convertLibraryModelToLtrModel(self, libraryModelLocation, outputFile, modelName, featureStoreName, useMinMax, min_max):\n content = {}\n\n content[\"class\"] = \"org.apache.solr.ltr.model.MultipleAdditiveTreesModel\"\n content[\"store\"] = str(featureStoreName)\n content[\"name\"] = str(modelName)\n content[\"features\"] = []\n\n for featKey in self.featureNameToId.keys():\n if useMinMax:\n min_, max_ = min_max[featKey][\"min\"], min_max[featKey][\"max\"]\n\n if abs(max_ - min_) < 0.000000001:\n max_ += 0.01\n\n norm = {\"class\": \"org.apache.solr.ltr.norm.MinMaxNormalizer\", \"params\":{ \"min\": str(min_), \"max\": str(max_) } }\n content[\"features\"].append({\"name\" : featKey, \"norm\": norm})\n else:\n content[\"features\"].append({\"name\" : featKey})\n\n with open(libraryModelLocation, 'r') as inFile:\n model = inFile.readlines()\n\n i = 0\n while model[i].startswith(\"##\"):\n i += 1\n\n model = model[i+1:]\n model = [l.strip() for l in model]\n root = ET.fromstring(' '.join(model))\n\n forest = []\n for child in root:\n tree = {}\n tree[\"weight\"] = child.attrib[\"weight\"]\n first_split = child.find(\"split\")\n\n tree_dict = self.get_tree(first_split)\n tree[\"root\"] = tree_dict\n\n forest.append(tree)\n\n content[\"params\"] = {\"trees\": forest}\n\n with open(outputFile,'w') as convertedOutFile:\n json.dump(content, convertedOutFile, sort_keys=False, indent=4)\n\n def get_tree(self, tree):\n\n tree_dict = {}\n\n if tree.find(\"output\") is not None:\n tree_dict[\"value\"] = tree.find(\"output\").text.strip()\n return tree_dict\n\n tree_dict[\"feature\"] = self.featureIdToName[ int(tree.find(\"feature\").text) ]\n tree_dict[\"threshold\"] = tree.find(\"threshold\").text.strip()\n\n left_tree, right_tree = None, None\n for s in tree.findall(\"split\"):\n if s.attrib[\"pos\"] == \"left\":\n left_tree = s\n if s.attrib[\"pos\"] == \"right\":\n right_tree = s\n\n if left_tree is not None:\n left = self.get_tree(left_tree)\n tree_dict[\"left\"] = left\n\n if right_tree is not None:\n right = self.get_tree(right_tree)\n tree_dict[\"right\"] = right\n\n return tree_dict\n\n\n","sub_path":"tree_formatter.py","file_name":"tree_formatter.py","file_ext":"py","file_size_in_byte":4633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"220166073","text":"def is_valid_index_x(x, m):\n if x < 0 or x >= m:\n return False\n return True\n\n\ndef is_valid_index_y(y, n):\n if y < 0 or y >= n:\n return False\n return True\n\n\nif __name__ == '__main__':\n # 세로, 가로 길이\n n, m = map(int, input().split())\n\n # 각 노드가 연결된 정보가 담긴 그래프\n graph = []\n visited = [[] for _ in range(m)]\n\n for _ in range(n):\n graph.append(list(map(int, input())))\n\n from collections import deque\n queue = deque()\n queue.append((0, 0))\n\n while queue:\n y, x = queue.popleft()\n\n # 이미 방문한 곳을 가지 않도록 체크 해줘야 무한 반복을 하지 않는다.\n # right\n if is_valid_index_x(x + 1, m) and graph[y][x + 1] == 1:\n queue.append((y, x + 1))\n graph[y][x + 1] = graph[y][x] + 1 # 따로 visited 2차원 배열을 만들지 않고 graph에 값을 더하므로써 이미 방문한 노드를 안가는 것, 값 누적이 포인트\n\n # left\n if is_valid_index_x(x - 1, m) and graph[y][x - 1] == 1:\n queue.append((y, x - 1))\n graph[y][x - 1] = graph[y][x] + 1\n\n # top\n if is_valid_index_y(y - 1, n) and graph[y - 1][x] == 1:\n queue.append((y - 1, x))\n graph[y - 1][x] = graph[y][x] + 1\n\n # bottom\n if is_valid_index_y(y + 1, n) and graph[y + 1][x] == 1:\n queue.append((y + 1, x))\n graph[y + 1][x] = graph[y][x] + 1\n\n print(graph[n-1][m-1])\n","sub_path":"백준/bfsdfs/2178/2178.py","file_name":"2178.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"498481874","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.preprocessing import StandardScaler\n\n\n# Evaluate trading system defined in current file.\nif __name__ == '__main__':\n import quantiacsToolbox\n\n result = quantiacsToolbox.runts(__file__)\n # values_test = result['settings']['y_test'].values\n # values_pred = result['settings']['y_pred'].values\n\n print('stats:', result['stats'])\n print('evalDate', result['evalDate'])\n print('runtime', result['runtime'])\n print('errorLog', result['errorLog'])\n # print(result['settings']['y_test'].shape)\n # print(result['settings']['y_pred'].shape)\n # print('Accuracy Score is {:f}'.format(accuracy_score(values_test, values_pred)))\n # print('Classification report is {:s}\\n'.format(classification_report(values_test, values_pred)))\n\ndef mySettings():\n \"\"\" Define your trading system settings here \"\"\"\n\n settings = {}\n\n print('your call')\n # Futures Contracts\n settings['markets'] = ['CASH', 'F_W', 'F_SM', 'F_SB', 'F_S', 'F_OJ','F_O','F_LB','F_GC','F_SS','F_JY']\n\n # settings['markets'] = ['F_GC']\n # settings['markets'] = ['CASH', 'VLO', 'ZTS', 'GOOG', 'AMZN', 'AAPL', 'BA', 'FB', 'NFLX', 'THC']\n # best one for this 0.61 with 2520 lookback\n settings['beginInSample'] = '19900102'\n settings['endInSample'] = '20180610'\n settings['lookback'] = 87\n settings['budget'] = 10 ** 6\n settings['slippage'] = 0.05\n # settings['X_train'] = pd.DataFrame(columns=['close', 'open', 'low', 'high'])\n # settings['X_test'] = pd.DataFrame(columns=['close', 'open', 'low', 'high'])\n # settings['y_train'] = pd.Series()\n # settings['y_test'] = pd.Series()\n # settings['y_pred'] = pd.Series()\n\n settings['market'] = ''\n settings['iterations'] = 0\n\n return settings\n\n\ndef myTradingSystem(DATE, OPEN, HIGH, LOW, CLOSE, VOL, OI, P, R, RINFO, exposure, equity, settings):\n nMarkets = len(settings['markets'])\n pos = np.zeros((1, nMarkets), dtype='float')\n actual_market = settings['markets'][0]\n for i in range(nMarkets):\n try:\n pos[0, i] = predict(OPEN[:, i], HIGH[:, i], LOW[:, i], CLOSE[:, i], settings,i)\n # for NaN data set position to 0\n except ValueError:\n pos[0, i] = 0.\n return pos, settings\n\n\n################################# MY FUNCTIONS #################################\n\ndef predict(OPEN, HIGH, LOW, CLOSE, settings,i):\n # settings['market'] = settings['markets'][i]\n\n data_temp = pd.DataFrame()\n data_temp['close'] = CLOSE\n data_temp['open'] = OPEN\n data_temp['low'] = LOW\n data_temp['high'] = HIGH\n close_open_diff = data_temp['close'] - data_temp['open']\n fee = (close_open_diff) * settings['slippage']\n data_temp['sign_close_diff'] = np.where(abs(close_open_diff) > fee, 1.0, 0.0)\n\n # drop nan values\n data_temp.dropna(axis=0, inplace=True)\n split_rate = 0.8\n split = int(split_rate * len(data_temp))\n y = data_temp.loc[:, 'sign_close_diff']\n X = data_temp.drop(['sign_close_diff'], axis=1)\n # y[y == -1] = 0\n\n\n X_train = X[:split]\n X_test = X[split:]\n y_train = y[:split]\n y_test = y[split:]\n\n lr = LogisticRegression()\n\n pipeline = make_pipeline(\n StandardScaler(),\n lr,\n )\n\n pipeline.fit(X_train, y_train)\n y_pred = pipeline.predict(X_test)\n y_pred_series = pd.Series(y_pred)\n\n # settings['X_train'] = pd.concat([X_train, settings['X_train']], ignore_index=True)\n # settings['X_test'] = pd.concat([X_test, settings['X_test']], ignore_index=True)\n # settings['y_train'] = pd.concat([y_train, settings['y_train']], ignore_index=True,sort=True)\n # settings['y_test'] = pd.concat([y_test, settings['y_test']], ignore_index=True,sort=True)\n # settings['y_pred'] = pd.concat([y_pred_series, settings['y_pred']], ignore_index=True, sort=True)\n\n # import pdb;\n # pdb.set_trace()\n\n unique, counts = np.unique(y_pred, return_counts=True)\n y_dict = dict(zip(unique, counts))\n if (not (1.0 in y_dict)):\n y_dict[1.0] = 0\n if (not (-1.0 in y_dict)):\n y_dict[-1.0] = 0\n\n # print(y_dict)\n y_pred = np.where(y_dict[1.0] > y_dict[-1.0], 1.0, -1.0)\n # save old data\n\n return y_pred.item(0)","sub_path":"check/lr_price_indicators.py","file_name":"lr_price_indicators.py","file_ext":"py","file_size_in_byte":4308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"576605641","text":"\"\"\" View for managing streams. \"\"\"\n\n__author__ = \"William Tucker\"\n__date__ = \"2018-03-13\"\n__copyright__ = \"Copyright 2019 United Kingdom Research and Innovation\"\n__license__ = \"BSD - see LICENSE file in top-level package directory\"\n\n\nimport os\nimport re\nimport unidecode\nimport shutil\n\nfrom zipfile import ZipFile\n\nfrom django.shortcuts import render, redirect\nfrom uploader.utils.streams import get_stream\nfrom uploader.decorators import data_directory_required\n\n\ngood_path_regex = re.compile('^[\\w\\./-]*$')\n\n\n@data_directory_required\ndef mkdir(request,*args,**kwargs):\n \"\"\"Make a directory\"\"\"\n arrivals_dir = request.user.uploaderprofile.data_directory\n\n # if this is a POST request we need to process the form data\n if request.method == 'POST':\n # create a form instance and populate it with data from the request:\n stream = request.POST[\"stream\"]\n rel_dir = request.POST[\"dir\"]\n new_dir = request.POST[\"new_dir\"]\n path = os.path.join(arrivals_dir, stream, rel_dir, new_dir)\n path = os.path.normpath(path)\n\n # check stream defined\n if not get_stream(request.user, stream):\n return render(request, \"uploader/error.html\", context={\"error_message\": \"Need an upload route to make a directory\"})\n\n # check for badness\n if not path.startswith(arrivals_dir):\n return render(request, \"uploader/error.html\", context={\"error_message\": \"Could not make sense of directory name\"})\n\n if not os.path.exists(path):\n os.mkdir(path)\n\n url_params = { 'stream': stream }\n url_params.update(kwargs) # combine url_params with the request kwargs\n if rel_dir:\n url_params['rel_dir'] = rel_dir\n return redirect(\"browse\", **url_params)\n\n elif request.method == \"GET\":\n stream = request.GET.get(\"stream\")\n rel_dir = request.GET.get(\"dir\")\n if stream:\n return render(request, \"uploader/mkdir.html\", context={\"stream\": stream, \"rel_dir\": rel_dir})\n else:\n return redirect('browse')\n\n\n@data_directory_required\ndef rename(request,*args,**kwargs):\n \"\"\"rename a file or directory\"\"\"\n arrivals_dir = request.user.uploaderprofile.data_directory\n\n # if this is a POST request we need to process the form data\n if request.method == 'POST':\n # create a form instance and populate it with data from the request:\n stream = request.POST[\"stream\"]\n rel_dir = request.POST[\"dir\"]\n old_filename = request.POST[\"filename\"]\n new_filename = request.POST[\"new_name\"]\n old_path = os.path.join(arrivals_dir, stream, rel_dir, old_filename)\n new_path = os.path.join(arrivals_dir, stream, rel_dir, new_filename)\n new_path = os.path.normpath(new_path)\n\n # check for badness\n assert new_path.startswith(arrivals_dir)\n\n os.rename(old_path, new_path)\n\n url_params = { 'stream': stream }\n url_params.update(kwargs) # combine url_params with the request kwargs\n if rel_dir:\n url_params['rel_dir'] = rel_dir\n return redirect(\"browse\", **url_params)\n\n elif request.method == \"GET\":\n stream = request.GET[\"stream\"]\n rel_dir = request.GET[\"dir\"]\n filename = request.GET[\"filename\"]\n return render(request, \"uploader/rename.html\", context={\"stream\": stream, \"rel_dir\": rel_dir, \"filename\": filename})\n\n\n@data_directory_required\ndef delete_file(request,*args,**kwargs):\n \"\"\"Delete a file or empty directory\"\"\"\n arrivals_dir = request.user.uploaderprofile.data_directory\n\n # if this is a POST request we need to process the form data\n if request.method == 'POST':\n # create a form instance and populate it with data from the request:\n stream = request.POST[\"stream\"]\n rel_dir = request.POST[\"dir\"]\n filename = request.POST[\"filename\"]\n path = os.path.join(arrivals_dir, stream, rel_dir, filename)\n path = os.path.normpath(path)\n\n # check for badness\n assert path.startswith(arrivals_dir)\n\n if os.path.islink(path):\n os.unlink(path)\n elif not os.path.exists(path):\n pass\n elif os.path.isfile(path):\n os.unlink(path)\n elif os.path.isdir(path) and len(os.listdir(path)) == 0:\n os.rmdir(path)\n else:\n pass\n\n url_params = { 'stream': stream }\n url_params.update(kwargs) # combine url_params with the request kwargs\n if rel_dir:\n url_params['rel_dir'] = rel_dir\n return redirect(\"browse\", **url_params)\n\n elif request.method == \"GET\":\n stream = request.GET[\"stream\"]\n rel_dir = request.GET[\"dir\"]\n filename = request.GET[\"filename\"]\n return render(request, \"uploader/delete_confirm.html\", context={\"stream\": stream, \"rel_dir\": rel_dir,\n \"filename\": filename})\n\n\n@data_directory_required\ndef fix(request, fix_type, fix_info, fix_function,*args,**kwargs):\n \"\"\"Apply a fix a direcory\"\"\"\n arrivals_dir = request.user.uploaderprofile.data_directory\n\n if request.method == 'GET':\n # create a form instance and populate it with data from the request:\n stream = request.GET[\"stream\"]\n rel_dir = request.GET[\"dir\"]\n path = os.path.join(arrivals_dir, stream, rel_dir)\n path = os.path.normpath(path)\n\n if \"confirmed\" not in request.GET:\n return render(request, 'uploader/confirm_fix.html',\n {\"fix_type\": fix_type, 'fix_info': fix_info, \"rel_dir\": rel_dir, \"stream\":stream})\n else:\n fix_function(path)\n\n url_params = { 'stream': stream }\n url_params.update(kwargs) # combine url_params with the request kwargs\n if rel_dir:\n url_params['rel_dir'] = rel_dir\n return redirect(\"browse\", **url_params)\n\n\ndef fix_chars(request,*args,**kwargs):\n \"\"\"Apply a fix to bad characters in file names\"\"\"\n\n # make fix function\n def fix_filenames(start_dir):\n for directory, dirs, files in os.walk(start_dir, topdown=False):\n for f in files + dirs:\n path = os.path.join(directory, f)\n if not good_path_regex.match(f):\n new_name = unidecode.unidecode(f)\n new_name = re.sub('%20', '_', new_name).strip()\n new_name = re.sub('[+&]', '_and_', new_name).strip()\n new_name = re.sub('[@]', '_at_', new_name).strip()\n new_name = re.sub('[^\\w\\s\\.-]', '', new_name).strip()\n new_name = re.sub('\\s+', '_', new_name)\n print(new_name)\n\n new_path = os.path.join(directory, new_name)\n os.rename(path, new_path)\n\n return fix(request, \"fix_chars\", \"\"\"Change filenames so that & and + become _and_, @ becomes _at_, spaces\n become underscores and other charaters are mapped to plain ASCII or removed.\"\"\", fix_filenames, **kwargs)\n\n\ndef fix_unzip(request,*args,**kwargs):\n \"\"\"Apply a fix to unzip any .zip files\"\"\"\n\n # make fix function\n def _fix_unzip(start_dir):\n for directory, _, files in os.walk(start_dir):\n for f in files:\n _, ext = os.path.splitext(f)\n if ext == \".zip\":\n path = os.path.join(directory, f)\n with ZipFile(path) as z:\n z.extractall(directory)\n os.unlink(path)\n\n return fix(request, \"fix_unzip\", \"\"\"Expand compressed or aggregated files like .zip, .tar, .gz.\"\"\", _fix_unzip,**kwargs)\n\n\ndef fix_zero(request,*args,**kwargs):\n \"\"\"Apply a fix to remove zero length files\"\"\"\n\n # make fix function\n def _fix_zero(start_dir):\n for directory, _, files in os.walk(start_dir):\n for f in files:\n path = os.path.join(directory, f)\n size = os.path.getsize(path)\n if size == 0:\n os.unlink(path)\n print(\"REMOVE zero length file %s \" % path)\n\n return fix(request, \"fix_zero_length\", \"\"\"Remove any files with no content.\"\"\", _fix_zero,**kwargs)\n\n\ndef fix_empty(request,*args,**kwargs):\n \"\"\"Apply a fix to remove empty directories\"\"\"\n\n # make fix function\n def _fix_empty(start_dir):\n for directory, dirs, files in os.walk(start_dir):\n if len(dirs) == 0 and len(files) == 0:\n print(\"Removing Empty directory\")\n os.rmdir(directory)\n\n return fix(request, \"fix_empty_dir\", \"\"\"Remove any empty directories.\"\"\", _fix_empty,**kwargs)\n\n\ndef fix_delete_dir(request,*args,**kwargs):\n \"\"\"Apply a fix to remove empty directories\"\"\"\n\n # make fix function\n def _fix_delete_dir(start_dir):\n for f in os.listdir(start_dir):\n path = os.path.join(start_dir, f)\n if os.path.islink(path):\n os.unlink(path)\n elif os.path.isfile(path):\n os.unlink(path)\n elif os.path.isdir(path):\n shutil.rmtree(path)\n\n return fix(request, \"fix_delete_dir\", \"\"\"Recursively delete this directory.\"\"\", _fix_delete_dir,**kwargs)\n\n\ndef fix_links(request,*args,**kwargs):\n \"\"\"Apply a fix to remove symlinks\"\"\"\n\n def _fix_links(start_dir):\n for directory, dirs, files in os.walk(start_dir):\n for f in files + dirs:\n path = os.path.join(directory, f)\n if os.path.islink(path):\n os.unlink(path)\n print(\"REMOVE - %s \" % path)\n\n return fix(request, \"fix_remove_links\", \"\"\"Remove any symbolic links.\"\"\", _fix_links,**kwargs)\n","sub_path":"uploader/views/tool_views.py","file_name":"tool_views.py","file_ext":"py","file_size_in_byte":9697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"50676701","text":"from js9 import j\nfrom .NetworkScanner import NetworkScanner\nimport multiprocessing\nimport time\nimport logging\nfrom queue import Empty\n\nJSBASE = j.application.jsbase_get_class()\nNUM_WORKERS = 4\n\n\nclass BaseDumper(JSBASE):\n\n def __init__(self, cidr, ports=[6379], scaninterval=300):\n logging.root.setLevel(logging.INFO)\n\n self._cidr = cidr\n self._scaninterval = scaninterval\n self._scanner = NetworkScanner(cidr, ports)\n self._circulation = set()\n\n def update_queue(self, queue):\n candidates = self._scanner.scan()\n for ip, ports in candidates.items():\n for port in ports:\n item = (ip, port)\n if item not in self._circulation:\n self._circulation.add(item)\n queue.put_nowait((ip, port))\n\n def start(self, workers=NUM_WORKERS):\n manager = multiprocessing.Manager()\n queue = manager.Queue()\n errorqueue = manager.Queue()\n self.update_queue(queue)\n\n pool = multiprocessing.Pool(workers)\n scantime = time.time()\n\n while True:\n if scantime + self._scaninterval < time.time():\n self.update_queue(queue)\n scantime = time.time()\n while not errorqueue.empty():\n erroritem = errorqueue.get()\n if erroritem in self._circulation:\n self._circulation.remove(erroritem)\n try:\n ip, port = queue.get(timeout=5)\n pool.apply_async(self._process, (ip, port, queue, errorqueue))\n except Empty:\n # queue is empty carry on\n pass\n\n @property\n def cidr(self):\n return self._cidr\n\n def _process(self, ip, port, queue, errorqueue):\n try:\n redis = j.clients.redis.get(ip, port)\n now = int(time.time())\n logging.info(\"Processing redis %s:%s\" % (ip, port))\n self.dump(redis)\n queue.put_nowait((ip, port))\n except Exception:\n logging.exception(\"Failed to process redis '%s:%s'\" % (ip, port))\n errorqueue.put_nowait((ip, port))\n finally:\n # workers must have some rest (1 sec) before moving to next\n # ip to process\n if int(time.time()) - now < 1:\n # process took very short time. Give worker time to rest\n time.sleep(1)\n\n def dump(self, redis):\n \"\"\"\n Dump, gets a redis connection. It must process the queues of redis until there is no more items to\n process and then immediately return.\n\n :param redis: redis connection\n :return:\n \"\"\"\n \"\"\"\n :param redis:\n :return:\n \"\"\"\n raise NotImplementedError\n","sub_path":"JumpScale9Lib/tools/aggregator/Dumper.py","file_name":"Dumper.py","file_ext":"py","file_size_in_byte":2791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"374804385","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom functools import partial\nfrom sklearn.datasets import make_blobs as sk_make_blobs\nfrom sklearn.datasets import make_moons as sk_make_moons\n\n\nmake_blobs = partial(sk_make_blobs, n_samples=500, centers=5, cluster_std=1.95)\nmake_moons = partial(sk_make_moons, n_samples=500, noise=0.15)\n\n\ndef draw_clusters(X, y=None, centers=None, cluster_size=10000):\n _, ax = plt.subplots(figsize=(10, 10))\n \n if y is not None:\n cm = {c: f\"C{c}\" for c in np.unique(y)}\n colors = [cm[i] for i in y]\n else:\n cm = None\n colors = \"b\"\n \n ax.scatter(X[:,0], X[:,1], color=colors)\n\n if centers is not None:\n colors = [cm[i] for i in range(len(centers))] if cm else \"b\"\n ax.scatter(\n centers[:,0], centers[:,1], marker=\"o\", \n c=colors, alpha=0.25, s=cluster_size\n )\n \n ax.set_xlabel(\"$X_0$\")\n ax.set_xticks([])\n ax.set_ylabel(\"$X_1$\")\n ax.set_yticks([])\n \n return ax\n\n\n\n","sub_path":"notebooks/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"423300416","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.linux-i686/egg/firebug/widgets.py\n# Compiled at: 2006-12-20 07:34:41\n__all__ = [\n 'firebug_css', 'firebug_js', 'firebugx_js']\nimport pkg_resources\nfrom turbogears.widgets import CSSLink, JSLink, Widget, WidgetDescription, register_static_directory\nstatic_dir = pkg_resources.resource_filename('firebug', 'static')\nregister_static_directory('firebug', static_dir)\nfirebug_css = CSSLink('firebug', 'css/firebug.css')\nfirebug_js = JSLink('firebug', 'javascript/firebug.js')\nfirebugx_js = JSLink('firebug', 'javascript/firebugx.js')","sub_path":"pycfiles/TGFirebugLite-1.0b-py2.4/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"164571815","text":"from nltk.tokenize import RegexpTokenizer\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.stem import SnowballStemmer\r\nimport os.path\r\nfrom os import path\r\nimport numpy as np\r\nimport random\r\nimport json\r\n\r\nstop_words = set(stopwords.words('spanish'))\r\nstemmer = SnowballStemmer(\"spanish\")\r\n\r\nproperties_tags = []\r\n\r\nSITE_ROOT = os.path.realpath(os.path.dirname(__file__))\r\njson_url = os.path.join(SITE_ROOT, 'intents.json')\r\n#open files\r\nfile_data=open(json_url)\r\nfile_property=open(os.path.join(SITE_ROOT, 'properties_intents.json'))\r\n\r\n#load json\r\ndata = json.load(file_data)\r\nproperty_data = json.load(file_property)\r\n\r\n\r\nfor property_intent in property_data['intents']:\r\n data['intents'].append(property_intent)\r\n properties_tags.append(property_intent['tag'])\r\n\r\ntokenizer = RegexpTokenizer(r'\\w+')\r\ntokenizer = RegexpTokenizer(r'[a-zA-Z0-9]+|[$]?[0-9]+[.]?[0-9]*')\r\n\r\n\r\ndef procesar():\r\n file_data=open(json_url)\r\n file_property=open(os.path.join(SITE_ROOT, 'properties_intents.json'))\r\n data = json.load(file_data)\r\n property_data = json.load(file_property)\r\n\r\n properties_tags.clear()\r\n for property_intent in property_data['intents']:\r\n data['intents'].append(property_intent)\r\n properties_tags.append(property_intent['tag'])\r\n\r\n words = []\r\n labels = []\r\n documents = []\r\n\r\n for intent in data[\"intents\"]:\r\n for pattern in intent[\"patterns\"]:\r\n wrds = tokenizer.tokenize(pattern.lower())\r\n words.extend(wrds)\r\n documents.append((wrds, intent[\"tag\"]))\r\n #print(wrds)\r\n if intent[\"tag\"] not in labels:\r\n labels.append(intent[\"tag\"])\r\n\r\n words = [stemmer.stem(w.lower())\r\n for w in words if w not in list(stop_words)]\r\n words = sorted(list(set(words)))\r\n\r\n #print(\"vocabulario: \", len(words), words)\r\n\r\n labels = sorted(labels)\r\n\r\n #print(\"etiquetas:\", len(labels), labels)\r\n\r\n file_data.close()\r\n file_property.close()\r\n training = []\r\n output_empty = [0] * len(labels)\r\n\r\n\r\n for doc in documents:\r\n bag = []\r\n pattern_words = doc[0]\r\n pattern_words = [stemmer.stem(word.lower()) for word in pattern_words]\r\n\r\n for w in words:\r\n bag.append(1) if w in pattern_words else bag.append(0)\r\n\r\n output_row = list(output_empty)\r\n output_row[labels.index(doc[1])] = 1\r\n\r\n training.append([bag, output_row])\r\n\r\n random.shuffle(training)\r\n training = np.array(training)\r\n\r\n train_x = list(training[:, 0])\r\n train_y = list(training[:, 1])\r\n\r\n return [(train_x, train_y), (labels, words)]\r\n","sub_path":"app/chatbot/preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"39022516","text":"# -*- coding: utf-8 -*-\n\nfrom thompsonlib import thompsonlib as TL\nfrom thompsonlib.common.colors import plot_color_gradients\n\n# Get help for one fit function\nprint(TL.FitExp)\n\n# Get help for all fit functions\nprint(TL.AllFits)\n\n# Print all color maps\nplot_color_gradients()\n\n# Quickly preview a wave.\nwave1 = TL.Wave([1, 2, .3, .66, 2.4, 1.5], name=\"Test Wave\")\nwave1.plot()","sub_path":"demos/how_to_get_help.py","file_name":"how_to_get_help.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"365331674","text":"import robel\nimport gym\nimport torch\nimport torch.nn as nn\nimport gym\nimport numpy as np\nimport os\nimport sys\nimport datetime\nimport argparse\nimport random\n\n\nfrom modules import *\nimport utils\n\nif __name__ == \"__main__\":\n env = gym.make('DClawTurnFixed-v0')\n # env = gym.make('DClawTurnFixed-v0', device_path='/dev/tty.usbserial-FT3WI485')\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--start-timesteps\", type=int, default=1e4)\n parser.add_argument(\"--max-timesteps\", type=int, default=3e6)\n parser.add_argument(\"--eval-freq\", type = int, default = 2000)\n parser.add_argument(\"--broken-info\", action='store_true', default=False,\n help=\"whether use broken joints indice as a part of state\")\n parser.add_argument(\"--broken-info-recap\", action='store_true', default=False,\n help='whether to use broken info again in actor module to reinforce the learning')\n parser.add_argument(\"--save-freq\", type=int, default=5000)\n\n parser.add_argument(\"--seed\", type=int, default=0)\n parser.add_argument(\"--buffer-max-size\", type=int, default=int(1e6))\n parser.add_argument(\"--agent-training-episodes\", type=int, default=int(2))\n parser.add_argument(\"--adversary-training-episodes\", type=int,default=int(1))\n parser.add_argument(\"--restore-step\", type=int, default=0)\n parser.add_argument(\"--broken-timesteps\", type=int, default=1)\n parser.add_argument(\"--hidden-size\", type=int, default=512)\n parser.add_argument(\"--broken-angle\", type=float, default=-0.6)\n parser.add_argument(\"--std\", type=float, default=0.1)\n parser.add_argument('--gamma', type=float, default=0.99, metavar='G',\n help='discount factor for reward (default: 0.99)')\n parser.add_argument('--tau', type=float, default=0.005, metavar='G',\n help='target smoothing coefficient(τ) (default: 0.005)')\n parser.add_argument('--env-name', default='DClawTurnFixed-v0',\n help='Mujoco Gym environment (default: HalfCheetah-v2)')\n parser.add_argument('--policy', default=\"Gaussian\",\n help='Policy Type: Gaussian | Deterministic (default: Gaussian)')\n parser.add_argument('--eval', type=bool, default=True,\n help='Evaluates a policy a policy every 10 episode (default: True)')\n parser.add_argument('--alpha', type=float, default=0.2, metavar='G',\n help='Temperature parameter α determines the relative importance of the entropy\\\n term against the reward (default: 0.2)')\n parser.add_argument('--automatic_entropy_tuning', type=bool, default=False, metavar='G',\n help='Automaically adjust α (default: False)')\n parser.add_argument('--target_update_interval', type=int, default=1, metavar='N',\n help='Value target update per no. of updates per step (default: 1)')\n parser.add_argument('--lr', type=float, default=0.0003, metavar='G',\n help='learning rate (default: 0.0003)')\n parser.add_argument('--batch_size', type=int, default=256, metavar='N',\n help='batch size (default: 256)')\n parser.add_argument('--trim-state', action=\"store_true\", default=True)\n args = parser.parse_args()\n if args.broken_info_recap:\n assert args.broken_info\n # device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n device = torch.device('cpu')\n state_dim = env.reset().shape[0]\n if args.trim_state:\n state_dim -= 9\n original_state_dim = state_dim\n if args.broken_info:\n state_dim += 9\n action_dim = env.action_space.sample().shape[0]\n max_action = env.action_space.high[0]\n\n agent = SAC(num_inputs=state_dim,\n action_space=env.action_space,\n args=args,\n writer=None,\n outdir=None,\n device=device)\n agent.restore_model_for_test(85000) \n # agent.restore_model_for_test(1100000) \n #1100000 works good\n # 660000 works good\n #trivial 225000 works perfect!!\n current_state = env.reset()\n env.render()\n\n if args.trim_state:\n current_state = utils.trim_state(current_state)\n\n broken_joints = [4,8] # 5 doesn't work\n\n if args.broken_info:\n current_state = np.concatenate((current_state, np.ones(9)))\n for broken_one in broken_joints:\n current_state[original_state_dim + broken_one] = 0\n previous_joint = np.zeros(9)\n sum_reward = 0\n index = 0\n episode = 0\n env._max_episode_steps = 50\n broken_angle_1 = random.uniform(-0.8, 0.8)\n broken_angle_2 = random.uniform(-0.5, -1)\n valve_angles = [0]\n with torch.no_grad():\n while True:\n if args.broken_info:\n valve_angles.append(current_state[-10])\n else:\n valve_angles.append(current_state[-1])\n \"self diagnosed module\"\n # current_joint = current_state[:9]\n # diff = current_joint - previous_joint\n # diff = np.abs(diff)\n # broken_loc = np.where(diff < 0.03)\n # print(adversary_action)\n for broken_one in broken_joints:\n current_state[broken_one] = 0\n action = agent.select_action(current_state, 'test')\n index += 1\n for broken_one in broken_joints:\n if broken_one == 0 or broken_one == 3 or broken_one == 6:\n action[broken_one] = broken_angle_1\n # action[broken_one] = random.uniform(-1,1)\n else:\n action[broken_one] = broken_angle_2\n # action[broken_one] = random.uniform(-0.5, -1)\n # action[adversary_action[0]] = -0.6\n # action[random.randint(0,8)] = 0\n # joint = current_state[:9]\n # cossin = current_state[9:11]\n # command = current_state[11:20]\n # other = current_state[20]\n next_state, reward, done, info = env.step(action)\n if args.trim_state:\n next_state = utils.trim_state(next_state)\n if args.broken_info:\n next_state = np.concatenate((next_state, np.ones(9)))\n for broken_one in broken_joints:\n current_state[original_state_dim + broken_one] = 0\n next_state[original_state_dim + broken_one] = 0\n sum_reward += reward \n # print(sum_reward)\n suc = info['score/success']\n # previous_joint = current_joint\n current_state = next_state\n if done:\n episode += 1\n valve_angles = np.array(valve_angles)\n # np.save('./valve_angles_pure_5.npy', valve_angles)\n current_state = env.reset()\n previous_joint = np.zeros(9)\n if args.trim_state:\n current_state = utils.trim_state(current_state)\n if args.broken_info:\n current_state = np.concatenate((current_state, np.ones(9)))\n \n for broken_one in broken_joints:\n current_state[original_state_dim + broken_one] = 0\n print(sum_reward)\n sum_reward = 0\n \n break\n\n ","sub_path":"train/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":7411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"529356761","text":"#!/usr/bin/env python3\nfrom __future__ import annotations\n\nfrom typing import Optional, List\n\nfrom lxml import etree\n\nfrom capybara_tw.model.capy_context import CapyContext\nfrom capybara_tw.util.xliff_util import Xliff12Tag\n\n\nclass CapyContextGroup(object):\n contexts: List[CapyContext]\n\n def __init__(self):\n self.contexts = []\n\n @classmethod\n def from_element(cls, elem) -> Optional[CapyContextGroup]:\n if elem is None:\n return None\n obj = cls()\n obj.contexts = [CapyContext.from_element(e) for e in elem.iterchildren(Xliff12Tag.context)]\n return obj\n\n def to_element(self):\n root = etree.Element(Xliff12Tag.context_group)\n for context in self.contexts:\n root.append(context.to_element())\n return root\n","sub_path":"capybara_tw/model/capy_context_group.py","file_name":"capy_context_group.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"613912797","text":"'''\nGiven n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.\n\n\nThe above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!\n\nExample:\n\nInput: [0,1,0,2,1,0,1,3,2,1,2,1]\nOutput: 6\n'''\n# 总面积然后减去所有柱子的面积的方法。这种方法感觉算不上是双指针,但也是把图从最高点分成两块从两头计算。\nclass Solution:\n def trap(self, height: List[int]) -> int:\n m,minx = 0, 0\n sumh = 0\n for idx,num in enumerate(height):\n sumh += height[idx]\n if num > m:\n m = num\n minx = idx\n cnt = 0\n maxi, maxj = 0, 0\n for i in range(minx): # 左边总面积\n maxi = max(maxi,height[i])\n cnt += maxi\n for j in reversed(range(minx,len(height))): # 右边总面积\n maxj = max(maxj,height[j])\n cnt += maxj\n return cnt-sumh\n\n# 只需要一次循环,用左右两个指针,左指针记录左边遇到的最大值,右指针记录右边遇到的最大值\n# 每轮循环将两个最大值加起来,并且减去当前柱子的高度。\n# 最���减去总体面积即可\nclass Solution:\n def trap(self, height: List[int]) -> int:\n ans, lmax, rmax = 0, 0, 0\n for i in range(len(height)):\n lmax = max(lmax, height[i])\n rmax = max(rmax, height[-1-i])\n ans += lmax + rmax - height[i]\n return ans-lmax*len(height)\n \n","sub_path":"python/0042.Trapping Rain Water.py","file_name":"0042.Trapping Rain Water.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"190467822","text":"import boto3\r\nimport time\r\nimport csv\r\nimport json\r\n\r\n# Document\r\ns3BucketName = \"textract-console-us-east-2-2987cd7c-e629-4de2-ab04-11e0e6bbf3fe\"\r\ndocumentName = \"_1438556735_coi.pdf\"\r\n\r\n# Amazon Textract client\r\ntextract = boto3.client('textract')\r\n\r\n# Call Amazon Textract\r\ndata = textract.start_document_analysis(\r\n DocumentLocation={\r\n 'S3Object': {\r\n 'Bucket': s3BucketName,\r\n 'Name': documentName\r\n }\r\n },\r\n FeatureTypes=[\r\n 'TABLES','FORMS',\r\n ],\r\n NotificationChannel={\r\n 'SNSTopicArn': 'arn:aws:sns:us-east-2:929835491811:AmazonTextract',\r\n 'RoleArn': 'arn:aws:iam::929835491811:role/TextractRole'\r\n }\r\n)\r\n\r\n# Needs to be replaced with https://docs.aws.amazon.com/textract/latest/dg/api-async.html SQS Queue Monitoring\r\ntime.sleep(60)\r\n\r\nresponse = textract.get_document_analysis(\r\n JobId=data['JobId'],\r\n MaxResults=200\r\n)\r\n\r\n \r\nwith open('data.txt', 'w') as outfile:\r\n json.dump(response, outfile)\r\n\r\n# # Print detected text\r\n# for item in response[\"Blocks\"]:\r\n# if item[\"BlockType\"] == 'KEY_VALUE_SET':\r\n# print ('\\033[94m' + item + '\\033[0m')","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"293380730","text":"import torch\nimport torch.utils.data as Data\nimport torchvision\nfrom lib.network import Network\nfrom torch import nn\nimport time\n\n\n# def calc_acc(x, y):\n# x = torch.max(x, dim=-1)[1]\n# accuracy = sum(x == y) / x.size(0)\n# return accuracy\n\n\ntrain_data = torchvision.datasets.MNIST(root='./mnist', train=True,\n transform=torchvision.transforms.ToTensor(),\n download=True)\ntest_data = torchvision.datasets.MNIST(root='./mnist/',\n transform=torchvision.transforms.ToTensor(),\n train=False)\n\ntrain_loader = Data.DataLoader(dataset=train_data, batch_size=128, shuffle=True)\ntest_loader = Data.DataLoader(dataset=test_data, batch_size=128, shuffle=False)\n\ntrain_batch_num = len(train_loader)\ntest_batch_num = len(test_loader)\n\nnet = Network()\nif torch.cuda.is_available():\n net = nn.DataParallel(net)\n net.cuda()\n\nopt = torch.optim.Adam(net.parameters(), lr=0.001)\nloss_func = nn.CrossEntropyLoss()\n\nfor epoch_index in range(20):\n st = time.time()\n\n torch.set_grad_enabled(True)\n net.train()\n for train_batch_index, (img_batch, label_batch) in enumerate(train_loader):\n if torch.cuda.is_available():\n img_batch = img_batch.cuda()\n label_batch = label_batch.cuda()\n\n predict = net(img_batch)\n # acc = calc_acc(predict.cpu().data, label_batch.cpu().data)\n loss = loss_func(predict, label_batch)\n\n net.zero_grad()\n loss.backward()\n opt.step()\n\n print('(LR:%f) Time of a epoch:%.4fs' % (opt.param_groups[0]['lr'], time.time()-st))\n\n torch.set_grad_enabled(False)\n net.eval()\n total_loss = []\n total_acc = 0\n total_sample = 0\n\n for test_batch_index, (img_batch, label_batch) in enumerate(test_loader):\n if torch.cuda.is_available():\n img_batch = img_batch.cuda()\n label_batch = label_batch.cuda()\n\n predict = net(img_batch)\n loss = loss_func(predict, label_batch)\n\n predict = predict.argmax(dim=1)\n acc = (predict == label_batch).sum()\n\n total_loss.append(loss)\n total_acc += acc\n total_sample += img_batch.size(0)\n\n net.train()\n\n mean_acc = total_acc.item() * 1.0 / total_sample\n mean_loss = sum(total_loss) / total_loss.__len__()\n\n print('[Test] epoch[%d/%d] acc:%.4f%% loss:%.4f\\n'\n % (epoch_index, 100, mean_acc * 100, mean_loss.item()))\n","sub_path":"Non-Local_pytorch_0.4.1_to_1.1.0/demo_MNIST.py","file_name":"demo_MNIST.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"627940883","text":"\"\"\"This class ingests all NBA, ABA, and BAA seasons.\nIt uses the fantalytix_python_crawler package to parse and \nSQLAlchemy package to preserve the data. The fantalytix_sqlalchemy package\ncontains the models.\n\"\"\"\nfrom datetime import date, datetime, timezone\n\nfrom fantalytix_python_crawler.crawler.sports_reference.basketball\\\n .leagues_page_parser import LeaguesPageParser\n\nfrom fantalytix_sqlalchemy.orm.common.league import League\nfrom fantalytix_sqlalchemy.orm.common.season import Season\n\nclass NBASeasonsIngestor:\n\n def __init__(self):\n self.signature = self.__repr__()\n self.league_cache = dict()\n\n def get_league_by_abbreviation(self, abbreviation, session):\n \"\"\"Gets the league object from the cache if available. If the \n league has not yet been retrieved, or if the league is no longer \n associated with the session, refresh with a new query.\n \"\"\"\n league = self.league_cache.get(abbreviation)\n if league is None or league not in session:\n league = session.query(League)\\\n .filter_by(abbreviation=abbreviation)\\\n .one()\n self.league_cache[abbreviation] = league\n return league\n\n def map_to_season(self, season_row, session):\n league = self.get_league_by_abbreviation(season_row['league'], session)\n return Season(\n league_id=league.id,\n start_date=None,\n end_date=None,\n start_year=season_row['start_year'],\n end_year=season_row['end_year'],\n created_by=self.signature,\n creation_date=datetime.now(tz=timezone.utc),\n last_updated_by=None,\n last_updated_date=None\n )\n\n def update_season(self, season_row, session, season):\n \"\"\"Updates the season object if its information is different from the \n season row. This is done by iterating through each key in season_row, \n determining if the season object has an attribute with the same name, \n and updating if they aren't the same. e.g.\n >>> if season.start_year != season_row['start_year']:\n ... season.start_year = season_row['start_year']\n ... updated = True\n \"\"\"\n updated = False\n league = self.get_league_by_abbreviation(season_row['league'], session)\n for key in season_row.keys():\n if key in season.__dict__ and season.__dict__[key] != season_row[key]:\n season.__dict__[key] = season_row[key]\n updated = True\n if updated:\n season.last_updated_by = self.signature\n season.last_updated_date = datetime.now(tz=timezone.utc)\n return season\n\n def get_season_query(self, season_row, session):\n league = self.get_league_by_abbreviation(season_row['league'], session)\n return session.query(Season).filter_by(\n league_id=league.id,\n start_year=season_row['start_year'])\n\n def season_exists(self, season_row, session):\n return session.query(self.get_season_query(season_row, session)\\\n .exists()).scalar()\n\n def get_season(self, season_row, session):\n return self.get_season_query(season_row, session).one()\n\n def get_season_or_none(self, season_row, session):\n return self.get_season_query(season_row, session).one_or_none()\n\n def ingest_all(self, html, session):\n \"\"\"This method iterates through each season row starting from the top \n of the page, adds new seasons and updates existing seasons.\n \"\"\"\n parser = LeaguesPageParser(html)\n for season_row in parser.get_data():\n season = self.get_season_or_none(season_row, session)\n if season is None:\n session.add(self.map_to_season(season_row, session))\n else:\n self.update_season(season_row, session, season)\n\n def ingest_one(self, html, session):\n \"\"\"This method iterates through each season row starting from the top \n of the page until it finds one that does not exist in the database, \n then adds it.\n \"\"\"\n parser = LeaguesPageParser(html)\n for season_row in parser.get_data():\n if not self.season_exists(season_row, session):\n session.add(self.map_to_season(season_row, session))\n break\n\n def ingest_recent(self, html, session):\n \"\"\"This method adds each new season row starting from the top of the \n page until it finds an existing season. It stops ingesting at that \n point.\n \"\"\"\n parser = LeaguesPageParser(html)\n for season_row in parser.get_data():\n if not self.season_exists(season_row, session):\n session.add(self.map_to_season(season_row, session))\n else:\n break\n\n def __repr__(self):\n return \"\"\n","sub_path":"src/fantalytix_python_ingestion/ingestion/sports_reference/basketball/nba_seasons_ingestor.py","file_name":"nba_seasons_ingestor.py","file_ext":"py","file_size_in_byte":4926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"622930083","text":"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.\n# Copyright (c) 2018, NVIDIA CORPORATION. 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\nimport argparse\nimport glob\nimport logging\nimport os\nimport random\nimport timeit\nimport sys\nimport numpy as np\nfrom tqdm import tqdm, trange\nimport math\n\nimport torch\nfrom torch.utils.data import DataLoader, RandomSampler, SequentialSampler\nfrom torch.utils.data.distributed import DistributedSampler\nfrom torch.distributed import all_gather\nfrom torch.utils.tensorboard import SummaryWriter\nimport torch.nn as nn\nfrom transformers import (\n MODEL_FOR_QUESTION_ANSWERING_MAPPING,\n WEIGHTS_NAME,\n AdamW,\n get_linear_schedule_with_warmup,\n get_cosine_schedule_with_warmup,\n)\n\nfrom model.model_utils import configure_tokenizer_model\nfrom kgs_retrieve.kg_utils import initialize_kg_retriever\nfrom utils.args import ArgumentGroup\nfrom text_processor.multirc import MultircResult, MultircProcessor, create_input, DefinitionInfo\nfrom dgl import save_graphs, load_graphs\nimport pandas as pd\nfrom sklearn.metrics import f1_score\n\nimport resource\n\nrlimit = resource.getrlimit(resource.RLIMIT_NOFILE)\nresource.setrlimit(resource.RLIMIT_NOFILE, (2048, rlimit[1]))\n\nsys.path.append('..')\nsys.path.append('.')\n# os.environ['CUDA_VISIBLE_DEVICES']='5, 6'\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\nMODEL_CONFIG_CLASSES = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())\nMODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)\n\nlogger.info(\"running on GPU: {}\".format(torch.cuda.current_device()))\n\n\ndef set_seed(args):\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if args.n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed)\n\n\ndef to_list(tensor):\n return tensor.detach().cpu().tolist()\n\n\ndef train(args, train_dataset, model, processor, tokenizer, retrievers, wn_synset_graphs, wn_synset_graphs_label_dict,\n input_dir):\n \"\"\" Train the model \"\"\"\n logger.info(\"Training the model {}\".format(args.model_type))\n if args.local_rank in [-1, 0] and args.mark != \"test\":\n tb_writer = SummaryWriter(log_dir=os.path.join(args.tensorboard_dir, args.mark), filename_suffix=args.mark)\n\n args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)\n train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset)\n train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size)\n\n if args.max_steps > 0:\n t_total = args.max_steps\n args.num_train_epochs = args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1\n else:\n t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs\n\n # Prepare optimizer and schedule (linear warmup and decay)\n no_decay = [\"bias\", \"LayerNorm.weight\"]\n named_parameters = list(model.named_parameters())\n\n optimizer_grouped_parameters = [\n {\n \"params\": [p for n, p in named_parameters if not any(nd in n for nd in no_decay)],\n \"weight_decay\": args.weight_decay,\n },\n {\n \"params\": [p for n, p in named_parameters if any(nd in n for nd in no_decay)],\n \"weight_decay\": 0.0},\n ]\n optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)\n if args.schedule_strategy == \"linear\":\n scheduler = get_linear_schedule_with_warmup(\n optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total\n )\n elif args.schedule_strategy == \"cosine\":\n scheduler = get_cosine_schedule_with_warmup(\n optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total\n )\n else:\n logger.error(\"unknown schedule, program exits\")\n exit()\n # Check if saved optimizer or scheduler states exist\n if os.path.isfile(os.path.join(args.output_dir, \"optimizer.pt\")) and os.path.isfile(\n os.path.join(args.output_dir, \"scheduler.pt\")\n ):\n # Load in optimizer and scheduler states\n map_location = {'cuda:%d' % 0: 'cuda:%d' % torch.distributed.get_rank()}\n logger.info(\"map_location when loading optimizer and scheduler: {}\".format(map_location))\n optimizer.load_state_dict(torch.load(os.path.join(args.output_dir, \"optimizer.pt\"), map_location=map_location))\n scheduler.load_state_dict(torch.load(os.path.join(args.output_dir, \"scheduler.pt\"), map_location=map_location))\n\n if args.use_fp16:\n try:\n from apex import amp\n except ImportError:\n raise ImportError(\"Please install apex from https://www.github.com/nvidia/apex to use fp16 training.\")\n\n model, optimizer = amp.initialize(model, optimizer, opt_level=args.use_fp16_opt_level)\n\n # multi-gpu training (should be after apex fp16 initialization)\n if args.n_gpu > 1:\n model = torch.nn.DataParallel(model)\n\n # Distributed training (should be after apex fp16 initialization)\n if args.local_rank != -1:\n model = torch.nn.parallel.DistributedDataParallel(\n model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True\n )\n\n # Train!\n logger.info(\"***** Running training *****\")\n logger.info(\" Dataset size = %d\", len(train_dataset))\n logger.info(\" Num Epochs = %d\", args.num_train_epochs)\n logger.info(\" Instantaneous batch size per GPU = %d\", args.per_gpu_train_batch_size)\n logger.info(\n \" Total train batch size (w. parallel, distributed & accumulation) = %d\",\n args.train_batch_size\n * args.gradient_accumulation_steps\n * (torch.distributed.get_world_size() if args.local_rank != -1 else 1),\n )\n logger.info(\" Gradient Accumulation steps = %d\", args.gradient_accumulation_steps)\n logger.info(\" Total optimization steps = %d\", t_total)\n\n global_step = 1\n epochs_trained = 0\n steps_trained_in_current_epoch = 0\n # Check if continuing training from a checkpoint\n if os.path.exists(args.output_dir):\n try:\n # set global_step to gobal_step of last saved checkpoint from model path\n checkpoint_suffix = args.output_dir.split(\"-\")[-1].split(\"/\")[0]\n global_step = int(checkpoint_suffix)\n epochs_trained = global_step // (len(train_dataloader) // args.gradient_accumulation_steps)\n steps_trained_in_current_epoch = global_step % (len(train_dataloader) // args.gradient_accumulation_steps)\n\n logger.info(\" Continuing training from checkpoint, will skip to saved global_step\")\n logger.info(\" Continuing training from epoch %d\", epochs_trained)\n logger.info(\" Continuing training from global step %d\", global_step)\n logger.info(\" Will skip the first %d steps in the first epoch\", steps_trained_in_current_epoch)\n except ValueError:\n logger.info(\" Starting fine-tuning.\")\n\n tr_loss, logging_loss = 0.0, 0.0\n tr_loss_dic, logging_loss_dic = {}, {}\n\n model.zero_grad()\n train_iterator = trange(\n epochs_trained, int(args.num_train_epochs), desc=\"Epoch\", disable=args.local_rank not in [-1, 0]\n )\n set_seed(args)\n best_evals = dict()\n all_train_size = args.per_gpu_train_batch_size * torch.distributed.get_world_size() * args.gradient_accumulation_steps\n\n if args.evaluate_epoch:\n num_train_iteration = math.floor(len(train_dataloader) / (10 ** (len(str(len(train_dataloader))) - 1))) * (\n 10 ** (len(str(len(train_dataloader))) - 1))\n train_loss_record_steps = int(num_train_iteration / 8)\n first_record_point = int(num_train_iteration / 8)\n args.evaluate_steps = int(num_train_iteration * args.evaluate_epoch)\n else:\n train_loss_record_steps = int(500 * (24 / all_train_size))\n first_record_point = int(500 * (24 / all_train_size))\n args.evaluate_steps = int(args.evaluate_steps * (24 / all_train_size))\n\n for _ in train_iterator:\n\n if epochs_trained >= 1:\n if args.evaluate_epoch:\n args.evaluate_steps = int(num_train_iteration * (args.evaluate_epoch / 2))\n else:\n args.evaluate_steps = int(1000 * (24 / all_train_size))\n\n # shuffle dataset per epoch\n if args.local_rank != -1:\n train_sampler.set_epoch(epochs_trained)\n\n logger.info(\"args.evaluate_steps: {}\".format(args.evaluate_steps))\n logger.info(\"epochs_trained: {}\".format(epochs_trained))\n\n epoch_iterator = tqdm(train_dataloader, desc=\"Iteration\", disable=args.local_rank not in [-1, 0])\n for step, batch in enumerate(epoch_iterator):\n # Skip past any already trained steps if resuming training\n if steps_trained_in_current_epoch > 0:\n steps_trained_in_current_epoch -= 1\n continue\n\n def training_step(batch):\n model.train()\n\n batch = tuple(t.to(args.device) for t in batch)\n batch_synset_graphs = batch[3]\n\n inputs = create_input(args, batch, global_step, batch_synset_graphs=batch_synset_graphs,\n wn_synset_graphs=wn_synset_graphs)\n\n outputs = model(**inputs)\n # model outputs are always tuple in transformers (see doc)\n loss = outputs[0]\n\n if args.n_gpu > 1:\n loss = loss.mean() # mean() to average on multi-gpu parallel (not distributed) training\n if args.gradient_accumulation_steps > 1:\n loss = loss / args.gradient_accumulation_steps\n\n if args.use_fp16:\n with amp.scale_loss(loss, optimizer) as scaled_loss:\n scaled_loss.backward()\n else:\n loss.backward()\n\n return loss.detach()\n\n if (step + 1) % args.gradient_accumulation_steps != 0:\n with model.no_sync():\n loss = training_step(batch)\n else:\n loss = training_step(batch)\n\n tr_loss += loss.item()\n if args.local_rank in [-1, 0] and (step + 1) % args.gradient_accumulation_steps == 0:\n logger.info('total loss during training {} at {}'.format(loss.item(), global_step))\n\n if (step + 1) % args.gradient_accumulation_steps == 0:\n if args.local_rank in [-1, 0] and global_step == 1:\n tb_writer.add_scalar(\"loss\", tr_loss, int(global_step * all_train_size / 24))\n\n if args.use_fp16:\n torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm)\n else:\n torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)\n\n optimizer.step()\n scheduler.step() # Update learning rate schedule\n model.zero_grad()\n global_step += 1\n\n # Evaluate metrics\n if args.evaluate_steps > 0 and (global_step % args.evaluate_steps == 0 or (\n global_step == first_record_point and epochs_trained == 0)) \\\n and args.evaluate_during_training:\n logger.info(\"Evaluation during training:\")\n logger.info(\"Loss during training is {}\".format(loss.item()))\n\n results = evaluate(args, model, processor, tokenizer, global_step, input_dir)\n\n if args.local_rank in [-1, 0]:\n total_score = 0\n is_saved = True\n for key, value in results.items():\n total_score += value\n logger.info(\"eval_{}. Value: {}. In Step: {}\".format(key, value, global_step))\n if args.mark != \"test\":\n tb_writer.add_scalar(\"eval_{}\".format(key), value,\n int(global_step * all_train_size / 24))\n if key not in best_evals:\n best_evals[key] = (value, global_step)\n elif value > best_evals[key][0]:\n if global_step - best_evals[key][1] > args.min_diff_steps and args.save_model:\n logger.info(\n \"notice the model since {} is improved from {} to {} at step {}\".format(key,\n best_evals[\n key][\n 0],\n value,\n global_step))\n # Save model checkpoint\n try:\n if is_saved:\n output_dir = os.path.join(args.output_dir,\n \"checkpoint-{}\".format(global_step))\n if not os.path.exists(output_dir):\n os.mkdir(output_dir)\n logger.info(\"saving model ...\")\n # Take care of distributed/parallel training\n model_to_save = model.module if hasattr(model, \"module\") else model\n model_to_save.save_pretrained(output_dir)\n\n torch.save(args, os.path.join(output_dir, \"training_args.bin\"))\n torch.save(optimizer.state_dict(), os.path.join(output_dir, \"optimizer.pt\"))\n torch.save(scheduler.state_dict(), os.path.join(output_dir, \"scheduler.pt\"))\n logger.info(\"Saving arguments, optimizer and scheduler states to %s\",\n output_dir)\n is_saved = False\n except:\n logger.warning(\"Cannot save the checkpoints.\")\n best_evals[key] = (value, global_step)\n if \"total_score\" not in best_evals:\n best_evals[\"total_score\"] = (total_score, global_step)\n elif total_score > best_evals[\"total_score\"][0]:\n best_evals[\"total_score\"] = (total_score, global_step)\n logger.info(\"best em+f1 score: {} at step {}\".format(total_score, global_step))\n if is_saved:\n try:\n output_dir = os.path.join(args.output_dir,\n \"checkpoint-{}\".format(global_step))\n if not os.path.exists(output_dir):\n os.mkdir(output_dir)\n logger.info(\"saving model ...\")\n # Take care of distributed/parallel training\n model_to_save = model.module if hasattr(model, \"module\") else model\n model_to_save.save_pretrained(output_dir)\n\n torch.save(args, os.path.join(output_dir, \"training_args.bin\"))\n torch.save(optimizer.state_dict(), os.path.join(output_dir, \"optimizer.pt\"))\n torch.save(scheduler.state_dict(), os.path.join(output_dir, \"scheduler.pt\"))\n logger.info(\"Saving arguments, optimizer and scheduler states to %s\",\n output_dir)\n except:\n logger.warning(\"Cannot save the checkpoints.\")\n\n logger.info(\"em+f1 score: {}\".format(total_score))\n # # except:\n # logger.info(\"To be processed Error for evaluate within train.\")\n\n if global_step % train_loss_record_steps == 0:\n if args.mark != \"test\" and args.local_rank in [-1, 0]:\n tb_writer.add_scalar(\"lr\", scheduler.get_lr()[0], int(global_step * all_train_size / 24))\n tb_writer.add_scalar(\"loss\", (tr_loss - logging_loss) / train_loss_record_steps,\n int(global_step * all_train_size / 24))\n\n logging_loss = tr_loss\n\n # if args.memory_bank_update and args.use_context_graph and global_step % args.memory_bank_update_steps == 0:\n # model.eval()\n # with torch.no_grad():\n # start_time = timeit.default_timer()\n # logger.info(\"cuda: {} updating entity description text embedding by the latest encoder\".format(args.local_rank))\n # t_list = torch.load(os.path.join(input_dir, args.cache_file_suffix) + \"_\" + \"definition_info\")[\"t_list\"]\n #\n # encoder = model.module.text_embed_model\n # t_list_input_ids = t_list[\"input_ids\"].to(encoder.device)\n # if args.text_embed_model == \"bert\":\n # t_list_token_type_ids = t_list[\"token_type_ids\"].to(encoder.device)\n # t_list_attention_mask = t_list[\"attention_mask\"].to(encoder.device)\n #\n # defid2defembed = torch.Tensor().to(encoder.device)\n # c_size = 1024\n # start_point = 0\n # end_point = start_point + c_size\n # total_size = len(t_list_input_ids)\n # while True:\n # if start_point > total_size:\n # break\n # if end_point > total_size:\n # end_point = total_size\n #\n # if args.text_embed_model == \"bert\":\n # tmp = encoder(input_ids=t_list_input_ids[start_point:end_point, :],\n # token_type_ids=t_list_token_type_ids[start_point:end_point, :],\n # attention_mask=t_list_attention_mask[start_point:end_point, :])[1]\n # elif args.text_embed_model == \"roberta\" or args.text_embed_model == \"roberta_base\":\n # tmp = encoder(input_ids=t_list_input_ids[start_point:end_point, :],\n # attention_mask=t_list_attention_mask[start_point:end_point, :])[1]\n # else:\n # logger.warning(\"not available LM, exit program\")\n # exit()\n # defid2defembed = torch.cat([defid2defembed, tmp], dim=0)\n #\n # start_point += c_size\n # end_point += c_size\n #\n # model.module.update_defid2defembed(defid2defembed, args.memory_bank_keep_coef)\n # logger.info(\"cuda: {} time for updating is {}\".format(args.local_rank, timeit.default_timer() - start_time))\n # logger.info(\"cuda: {} update is done\".format(args.local_rank))\n\n # if args.memory_bank_update and global_step % args.memory_bank_update_steps == 0:\n # with torch.no_grad():\n # start_time = timeit.default_timer()\n # logger.info(\"cuda: {} updating entity description text embedding by the latest encoder\".format(\n # args.local_rank))\n # t_list = torch.load(os.path.join(input_dir, args.cache_file_suffix) + \"_\" + \"definition_info\")[\n # \"t_list\"]\n # logger.info(\"t_list size: {}\".format(t_list[\"input_ids\"].shape))\n #\n # encoder = model.module.text_embed_model.cpu()\n # t_list_input_ids = t_list[\"input_ids\"]\n # if args.text_embed_model == \"bert\":\n # t_list_token_type_ids = t_list[\"token_type_ids\"]\n # t_list_attention_mask = t_list[\"attention_mask\"]\n #\n # defid2defembed = torch.Tensor()\n # c_size = 10000\n # start_point = 0\n # end_point = start_point + c_size\n # total_size = len(t_list_input_ids)\n # while True:\n # if start_point > total_size:\n # break\n # if end_point > total_size:\n # end_point = total_size\n #\n # if args.text_embed_model == \"bert\":\n # tmp = encoder(input_ids=t_list_input_ids[start_point:end_point, :],\n # token_type_ids=t_list_token_type_ids[start_point:end_point, :],\n # attention_mask=t_list_attention_mask[start_point:end_point, :])[1]\n # elif args.text_embed_model == \"roberta\" or args.text_embed_model == \"roberta_base\":\n # tmp = encoder(input_ids=t_list_input_ids[start_point:end_point, :],\n # attention_mask=t_list_attention_mask[start_point:end_point, :])[1]\n # else:\n # logger.warning(\"not available LM, exit program\")\n # exit()\n # defid2defembed = torch.cat([defid2defembed, tmp], dim=0)\n #\n # start_point += c_size\n # end_point += c_size\n #\n # model.module.update_defid2defembed(defid2defembed.to(model.module.text_embed_model.device))\n # logger.info(\"cuda: {} time for updating is {}\".format(args.local_rank,\n # timeit.default_timer() - start_time))\n # logger.info(\"cuda: {} update is done\".format(args.local_rank))\n\n if args.max_steps > 0 and global_step > args.max_steps:\n logger.info(\"to max steps and stop iterator\")\n epoch_iterator.close()\n break\n\n epochs_trained += 1\n if args.local_rank in [-1, 0] and args.mark != \"test\":\n tb_writer.close()\n\n return global_step, tr_loss / global_step\n\n\ndef evaluate(args, model, processor, tokenizer, global_step, input_dir, prefix=\"\"):\n retrievers = dict()\n for kg in args.use_kgs:\n logger.info(\"Initialize kg:{}\".format(kg))\n kg_path = os.path.join(input_dir, args.kg_paths[kg])\n data_path = os.path.join(args.data_dir, args.kg_paths[kg])\n\n if not os.path.exists(kg_path):\n logger.warning(\"need prepare training dataset firstly, program exit\")\n exit()\n\n retrievers[kg] = initialize_kg_retriever(kg, kg_path, data_path, args.cache_file_suffix)\n\n dataset, examples_tokenized, features, wn_synset_graphs, wn_synset_graphs_label_dict = \\\n load_and_cache_examples(args,\n processor,\n retrievers,\n relation_list=args.relation_list,\n input_dir=input_dir,\n evaluate=True,\n output_examples=True)\n\n if not os.path.exists(args.output_dir) and args.local_rank in [-1, 0]:\n os.mkdir(args.output_dir)\n\n args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)\n\n # Note that DistributedSampler samples randomly\n eval_sampler = SequentialSampler(dataset) if args.local_rank == -1 else DistributedSampler(dataset)\n eval_dataloader = DataLoader(dataset, sampler=eval_sampler, batch_size=args.eval_batch_size)\n\n # synset_graphs_batch = []\n # for batch_index in eval_dataloader.batch_sampler:\n # synset_graphs_batch.append([i for i in batch_index])\n\n # multi-gpu evaluate\n if args.n_gpu > 1 and not isinstance(model, torch.nn.DataParallel):\n model = torch.nn.DataParallel(model)\n\n if args.local_rank != -1 and not isinstance(model, torch.nn.parallel.DistributedDataParallel):\n model = torch.nn.parallel.DistributedDataParallel(\n model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True\n )\n\n # Eval!\n logger.info(\"***** Running evaluation {} *****\".format(prefix))\n logger.info(\" Dataset size = %d\", len(dataset))\n logger.info(\" Batch size = %d\", args.eval_batch_size)\n\n if args.local_rank == -1:\n logger.warning(\"program exits and please use pytorch DDP framework\")\n exit()\n else:\n # all_results = []\n # all_start_logits = torch.tensor([], dtype=torch.float32, device=args.device)\n # all_end_logits = torch.tensor([], dtype=torch.float32, device=args.device)\n # all_unique_ids = []\n all_pred = torch.tensor([], dtype=torch.long, device=args.device)\n all_label_ids = torch.tensor([], dtype=torch.long, device=args.device)\n all_question_ids = torch.tensor([], dtype=torch.long, device=args.device)\n all_logits = torch.tensor([], dtype=torch.float, device=args.device)\n # start_time = timeit.default_timer()\n epoch_iterator = tqdm(eval_dataloader, desc=\"Evaluating Iteration\", disable=args.local_rank not in [-1, 0])\n for step, batch in enumerate(epoch_iterator):\n model.eval()\n batch = tuple(t.to(args.device) for t in batch)\n batch_synset_graphs = batch[3]\n with torch.no_grad():\n inputs = create_input(args, batch, global_step, batch_synset_graphs=batch_synset_graphs,\n wn_synset_graphs=wn_synset_graphs, evaluate=True)\n feature_indices = batch[3]\n\n outputs = model(**inputs)\n\n logits, label_ids, qas_ids = outputs[1], outputs[2], outputs[3]\n all_pred = torch.cat((all_pred, torch.argmax(logits, axis=-1)), dim=0)\n all_label_ids = torch.cat((all_label_ids, label_ids), dim=0)\n all_question_ids = torch.cat((all_question_ids, qas_ids), dim=0)\n all_logits = torch.cat((all_logits, logits), dim=0)\n\n start_time = timeit.default_timer()\n\n all_pred_list = [torch.zeros_like(all_pred, device=args.device) for _ in\n range(torch.distributed.get_world_size())]\n all_label_ids_list = [torch.zeros_like(all_label_ids, device=args.device) for _ in\n range(torch.distributed.get_world_size())]\n all_question_ids_list = [torch.zeros_like(all_question_ids, device=args.device) for _ in\n range(torch.distributed.get_world_size())]\n all_logits_list = [torch.zeros_like(all_logits, device=args.device) for _ in\n range(torch.distributed.get_world_size())]\n\n all_gather(all_pred_list, all_pred)\n all_gather(all_label_ids_list, all_label_ids)\n all_gather(all_question_ids_list, all_question_ids)\n all_gather(all_logits_list, all_logits)\n\n logger.info(\n \"time for gather communication:{} in rank {}\".format(timeit.default_timer() - start_time, args.local_rank))\n\n if args.local_rank == 0:\n start_time = timeit.default_timer()\n all_results = []\n all_pred_list = all_pred_list\n all_label_ids_list = all_label_ids_list\n all_question_ids_list = all_question_ids_list\n all_logits_list = all_logits_list\n\n logger.info(\"all_logits_list\\n{}\".format(all_logits_list))\n logger.info(\"all_question_ids_list\\n{}\".format(all_question_ids_list))\n logger.info(\"all_label_ids_list\\n{}\".format(all_label_ids_list))\n logger.info(\"all_pred_list\\n{}\".format(all_pred_list))\n\n\n preds = np.asarray([], dtype=int)\n label_values = np.asarray([], dtype=int)\n question_ids = np.asarray([], dtype=int)\n for batch_idx, batch_preds in enumerate(all_pred_list):\n preds = np.concatenate((preds, batch_preds.cpu().detach().numpy()), axis=0)\n label_values = np.concatenate((label_values, all_label_ids_list[batch_idx].cpu().detach().numpy()), axis=0)\n question_ids = np.concatenate((question_ids, all_question_ids_list[batch_idx].cpu().detach().numpy()), axis=0)\n\n df = pd.DataFrame({'label_values': label_values, 'question_ids': question_ids})\n assert \"label_values\" in df.columns\n assert \"question_ids\" in df.columns\n df[\"preds\"] = preds\n # noinspection PyUnresolvedReferences\n exact_match = (\n df.groupby(\"question_ids\")\n .apply(lambda _: (_[\"preds\"] == _[\"label_values\"]).all())\n .mean()\n )\n exact_match = float(exact_match)\n f1 = f1_score(y_true=df[\"label_values\"], y_pred=df[\"preds\"])\n\n results = {'exact_match': exact_match, 'f1': f1}\n return results\n else:\n return None\n\n\ndef load_and_cache_examples(args, processor, retrievers, relation_list, input_dir, evaluate=False,\n output_examples=False):\n \"\"\"\n :param args: arguments. Here use \"local_rank\", \"cache_dir\", \"model_type\", \"max_seq_length\", \"data_dir\",\n \"train_file\", \"tokenization_train_filepath\", \"predict_file\", \"tokenization_dev_filepath\", \"retrieved_nell_concept_filepath\",\n :param tokenizer: the predefined tokenzier, correpsonding to the type of model. Each model has its own tokenizer.\n :param evaluate: bool. An indicator for loading train file or dev file.\n :param output_examples: bool. To decide whether to output examples.\n :return:\n \"\"\"\n\n if args.local_rank not in [-1, 0]:\n # Make sure only the first process in distributed training process the dataset, and the others will use the cache\n torch.distributed.barrier()\n\n # Load data features from cache or dataset file\n cached_features_file = os.path.join(\n input_dir,\n \"cached_{}_{}_{}\".format(\n \"dev\" if evaluate else \"train\",\n args.model_type,\n str(args.cache_file_suffix),\n ),\n )\n\n # Init features and dataset from cache if it exists\n if os.path.exists(cached_features_file) and not args.overwrite_cache:\n logger.info(\"Loading features from cached file %s\", cached_features_file)\n features_and_dataset = torch.load(cached_features_file)\n features, dataset, examples_tokenized = (\n features_and_dataset[\"features\"],\n features_and_dataset[\"dataset\"],\n features_and_dataset[\"examples\"],\n )\n if args.model_type == \"kelm\":\n all_kgs_graphs, all_kgs_graphs_label_dict = load_graphs(cached_features_file + \"_all_kgs_graphs.bin\")\n else:\n all_kgs_graphs, all_kgs_graphs_label_dict = [], []\n else:\n logger.error(\"dataset not exist and program exits\")\n exit()\n if args.local_rank == 0:\n # Make sure only the first process in distributed training process the dataset, and the others will use the cache\n torch.distributed.barrier()\n\n logger.info(\"{} load data is done\".format(args.local_rank))\n\n if output_examples:\n return dataset, examples_tokenized, features, all_kgs_graphs, all_kgs_graphs_label_dict\n\n # exit()\n return dataset, all_kgs_graphs, all_kgs_graphs_label_dict\n\n\ndef create_dataset(args, processor, retrievers, relation_list, evaluate, input_dir):\n if args.local_rank not in [-1, 0]:\n # Make sure only the first process in distributed training process the dataset, and the others will use the cache\n torch.distributed.barrier()\n definition_info = DefinitionInfo()\n tokenizer, encoder = configure_tokenizer_model(args, logger, retrievers, is_preprocess=True)\n logger.info(\"tokenizer: {}\".format(tokenizer))\n logger.info(\"encoder: {}\".format(encoder))\n\n encoder.to(args.device)\n for param in encoder.parameters():\n param.requires_grad = False\n\n if not evaluate:\n cached_features_file = os.path.join(\n input_dir,\n \"cached_{}_{}_{}\".format(\n \"dev\" if evaluate else \"train\",\n args.model_type,\n str(args.cache_file_suffix),\n ),\n )\n\n if os.path.exists(cached_features_file):\n logger.warning(\"cache file exist and exit program\")\n exit()\n\n logger.info(\"Creating features from dataset file at %s\", input_dir)\n\n # if not os.path.exists(\"../tmp/examples_tokenized\"):\n examples = processor.get_train_examples(args.data_dir, filename=args.train_file)\n\n examples_tokenized = processor.tokenization_on_examples(examples, tokenizer, is_testing=args.test)\n\n features = processor.convert_examples_to_features(args, examples_tokenized, tokenizer, retrievers,\n not evaluate, debug=args.debug)\n\n features, dataset, all_kgs_graphs = processor.pad_and_index_features_all(\n features, retrievers, args, tokenizer, relation_list, encoder=encoder, definition_info=definition_info,\n is_training=not evaluate, debug=args.debug)\n\n if args.local_rank in [-1, 0]:\n if args.model_type == \"kelm\":\n all_kgs_graphs_label_dict = {\"glabel\": torch.tensor([i for i in range(len(all_kgs_graphs))])}\n save_graphs(cached_features_file + \"_all_kgs_graphs.bin\", all_kgs_graphs, all_kgs_graphs_label_dict)\n logger.info(\"complete data preprocessing\")\n\n logger.info(\"Saving features into cached file %s\", cached_features_file)\n\n torch.save({\"features\": None, \"dataset\": dataset, \"examples\": examples_tokenized}, cached_features_file)\n\n logger.info(\"Saving knowledge graph retrievers\")\n\n for kg, retriever in retrievers.items():\n if not os.path.exists(os.path.join(input_dir, args.kg_paths[kg])):\n os.mkdir(os.path.join(input_dir, args.kg_paths[kg]))\n torch.save(retriever, os.path.join(input_dir, args.kg_paths[kg], kg + args.cache_file_suffix))\n\n logger.info(\"saving definition information ...\")\n torch.save({\"defid2def\": definition_info.defid2def, \"conceptid2defid\": definition_info.conceptid2defid},\n os.path.join(input_dir, args.cache_file_suffix) + \"_\" + \"definition_info\")\n assert len(definition_info.defid2def) == len(definition_info.conceptid2defid)\n\n logger.info(\"training data create is done\")\n\n else:\n stored_definition_info = torch.load(os.path.join(input_dir, args.cache_file_suffix) + \"_\" + \"definition_info\")\n definition_info.defid2def, definition_info.conceptid2defid = stored_definition_info[\"defid2def\"], \\\n stored_definition_info[\"conceptid2defid\"]\n cached_features_file = os.path.join(\n input_dir,\n \"cached_{}_{}_{}\".format(\n \"dev\" if evaluate else \"train\",\n args.model_type,\n str(args.cache_file_suffix),\n ),\n )\n\n if os.path.exists(cached_features_file):\n logger.warning(\"cache file exist and exit program\")\n exit()\n\n logger.info(\"Creating features from dataset file at %s\", input_dir)\n\n if not os.path.exists(cached_features_file + \"_example\"):\n examples = processor.get_dev_examples(args.data_dir, filename=args.predict_file)\n torch.save(examples, cached_features_file + \"_example\")\n else:\n logger.info(\"Loading examples from cached files.\")\n examples = torch.load(cached_features_file + \"_example\")\n\n examples_tokenized = processor.tokenization_on_examples(examples, tokenizer, is_testing=args.test)\n\n features = processor.convert_examples_to_features(args, examples_tokenized, tokenizer, retrievers,\n not evaluate, debug=args.debug)\n\n features, dataset, all_kgs_graphs = processor.pad_and_index_features_all(\n features, retrievers, args, tokenizer, relation_list, encoder=encoder, definition_info=definition_info,\n is_training=not evaluate, debug=args.debug)\n\n if args.local_rank in [-1, 0]:\n if args.model_type == \"kelm\":\n all_kgs_graphs_label_dict = {\"glabel\": torch.tensor([i for i in range(len(all_kgs_graphs))])}\n save_graphs(cached_features_file + \"_all_kgs_graphs.bin\", all_kgs_graphs, all_kgs_graphs_label_dict)\n logger.info(\"complete data preprocessing\")\n\n logger.info(\"Saving features into cached file %s\", cached_features_file)\n\n for f in features:\n del f.kgs_conceptids2synset\n torch.save({\"features\": features, \"dataset\": dataset, \"examples\": examples_tokenized}, cached_features_file)\n\n if args.model_type == \"kelm\":\n logger.info(\"saving definition embedding\")\n\n t_list = tokenizer(definition_info.defid2def, return_tensors=\"pt\", padding=True)\n\n t_list_input_ids = t_list[\"input_ids\"].to(encoder.device)\n if args.text_embed_model == \"bert\":\n t_list_token_type_ids = t_list[\"token_type_ids\"].to(encoder.device)\n t_list_attention_mask = t_list[\"attention_mask\"].to(encoder.device)\n\n defid2defembed = torch.Tensor()\n c_size = 1024\n start_point = 0\n end_point = start_point + c_size\n total_size = len(t_list_input_ids)\n while True:\n if start_point > total_size:\n break\n if end_point > total_size:\n end_point = total_size\n\n if args.text_embed_model == \"bert\":\n tmp = encoder(input_ids=t_list_input_ids[start_point:end_point, :],\n token_type_ids=t_list_token_type_ids[start_point:end_point, :],\n attention_mask=t_list_attention_mask[start_point:end_point, :])[1].cpu()\n elif args.text_embed_model == \"roberta\" or args.text_embed_model == \"roberta_base\":\n tmp = encoder(input_ids=t_list_input_ids[start_point:end_point, :],\n attention_mask=t_list_attention_mask[start_point:end_point, :])[1].cpu()\n else:\n logger.warning(\"not available LM, exit program\")\n exit()\n defid2defembed = torch.cat([defid2defembed, tmp], dim=0)\n\n start_point += c_size\n end_point += c_size\n\n assert defid2defembed.shape[0] == total_size\n else:\n defid2defembed = []\n t_list = []\n\n\n logger.info(\"Saving knowledge graph retrievers\")\n for kg, retriever in retrievers.items():\n torch.save(retriever, os.path.join(input_dir, args.kg_paths[kg], kg + args.cache_file_suffix))\n\n logger.info(\"saving definition embedding ...\")\n torch.save({\"defid2defembed\": defid2defembed},\n os.path.join(input_dir, args.cache_file_suffix) + \"_\" + \"definition_embedding\")\n\n logger.info(\"saving definition information ...\")\n torch.save({\"defid2def\": definition_info.defid2def, \"conceptid2defid\": definition_info.conceptid2defid,\n \"t_list\": t_list},\n os.path.join(input_dir, args.cache_file_suffix) + \"_\" + \"definition_info\")\n assert len(definition_info.defid2def) == len(definition_info.conceptid2defid)\n\n logger.info(\"data create is done\")\n\n if args.local_rank == 0:\n # Make sure only the first process in distributed training process the dataset, and the others will use the cache\n torch.distributed.barrier()\n\n exit()\n\n\ndef main():\n parser = argparse.ArgumentParser()\n\n model_g = ArgumentGroup(parser, \"model\", \"model configuration and path.\")\n\n model_g.add_arg(\"dataset\", str, \"multirc\", \"used dataset\")\n model_g.add_arg(\"is_update_max_concept\", bool, False, \"weather update max concept for kg retriver\")\n model_g.add_arg(\"full_table\", bool, False, \"full_table\")\n model_g.add_arg(\"test\", bool, False, \"weather load superglue test set\")\n model_g.add_arg(\"use_wn\", bool, True, \"wn\")\n model_g.add_arg(\"use_nell\", bool, True, \"nell\")\n\n model_g.add_arg(\"sentinel_trainable\", bool, False, \"sentinel_trainable\")\n model_g.add_arg(\"memory_bank_update\", bool, False, \"memory_bank_update\")\n model_g.add_arg(\"memory_bank_update_steps\", int, 500, \"memory_bank_update_steps\")\n model_g.add_arg(\"memory_bank_keep_coef\", float, 0.0, \"what percent keep\")\n model_g.add_arg(\"use_context_graph\", bool, True, \"use_context_graph\")\n\n model_g.add_arg(\"schedule_strategy\", str, \"linear\", \"schedule_strategy\")\n model_g.add_arg(\"tokenizer_path\", str, \"../cache/bert-large-cased/\", \"tokenizer_path\")\n model_g.add_arg(\"save_model\", bool, True, \"whether save model\")\n model_g.add_arg(\"data_preprocess\", bool, False, \"data process\")\n model_g.add_arg(\"data_preprocess_evaluate\", bool, False, \"data_preprocess_evaluate\")\n\n # multi-relational part\n model_g.add_arg(\"relation_agg\", str, \"sum\", \"the method to aggeregate multi-relational neoghbor\")\n\n model_g.add_arg(\"is_lemma\", bool, False, \"whether trigger lemma\")\n model_g.add_arg(\"is_filter\", bool, True, \"weather filter node not in wn18\")\n model_g.add_arg(\"is_clean\", bool, True, \"weather filter node not in repeated_id\")\n model_g.add_arg(\"is_morphy\", bool, False, \"weather morphy\")\n model_g.add_arg(\"fewer_label\", bool, False, \"weather fewer_label\")\n model_g.add_arg(\"label_rate\", float, 0.1, \"label rate\")\n\n model_g.add_arg(\"relation_list\", list,\n [\"_hyponym\", \"_hypernym\", \"_derivationally_related_form\", \"_member_meronym\", \"_member_holonym\",\n \"_part_of\", \"_has_part\", \"_member_of_domain_topic\", \"_synset_domain_topic_of\", \"_instance_hyponym\",\n \"_instance_hypernym\", \"_also_see\", \"_verb_group\", \"_member_of_domain_region\",\n \"_synset_domain_region_of\", \"_member_of_domain_usage\", \"_synset_domain_usage_of\", \"_similar_to\"],\n \"The used relation.\")\n model_g.add_arg(\"is_all_relation\", bool, False, \"use all relations\")\n model_g.add_arg(\"selected_relation\", str, \"_hyponym,_hypernym,_derivationally_related_form\", \"relations\")\n model_g.add_arg(\"wn18_dir\", str, \"../data/kgs/wn18/text/\", \"wn18 dir\")\n\n # SSL part\n model_g.add_arg(\"use_consistent_loss_wn\", bool, False, \"add consistent loss between entity embedding from WN.\")\n model_g.add_arg(\"warm_up\", int, 10000, \"warm_up_iterations\")\n model_g.add_arg(\"consistent_loss_wn_coeff\", float, 2.0, \"Weight decay if we apply some.\")\n model_g.add_arg(\"consistent_loss_type\", str, \"kld\", \"consistent loss type\")\n model_g.add_arg(\"mark\", str, \"test1\", \"mark\")\n model_g.add_arg(\"tensorboard_dir\", str, \"./\", \"tensorboard_dir\")\n model_g.add_arg(\"debug\", bool, False, \"debug\")\n\n model_g.add_arg(\"model_name_or_path\", str, \"../cache/bert-large-cased/\",\n \"Path to pretrained model or model identifier from huggingface.co/models\")\n model_g.add_arg(\"config_name\", str, \"../cache/bert-large-cased/\", \"Pretrained config name or path if not the same as model_name\")\n model_g.add_arg(\"model_type\", str, \"kelm\", \"The classification model to be used.\")\n model_g.add_arg(\"text_embed_model\", str, \"bert\", \"The model for embedding texts in kelm model.\")\n model_g.add_arg(\"output_dir\", str, \"../outputs/test\", \"Path to save checkpoints.\")\n model_g.add_arg(\"overwrite_output_dir\", bool, True, \"Overwrite the content of the output directory.\")\n model_g.add_arg(\n \"--tokenizer_name\",\n default=\"\",\n type=str,\n help=\"Pretrained tokenizer name or path if not the same as model_name\",\n )\n model_g.add_arg(\"per_gpu_train_batch_size\", int, 6, \"Batch size per GPU/CPU for training.\")\n model_g.add_arg(\"per_gpu_eval_batch_size\", int, 4, \"Batch size per GPU/CPU for evaluation.\")\n model_g.add_arg(\"max_steps\", int, -1,\n \"If > 0: set total number of training steps to perform. Override num_train_epochs.\")\n model_g.add_arg(\"gradient_accumulation_steps\", int, 1,\n \"Number of updates steps to accumulate before performing a backward/update pass.\")\n model_g.add_arg(\"num_train_epochs\", float, 10, \"Total number of training epochs to perform.\")\n model_g.add_arg(\"weight_decay\", float, 0.01, \"Weight decay if we apply some.\")\n model_g.add_arg(\"learning_rate\", float, 3e-4, \"The initial learning rate for Adam.\")\n model_g.add_arg(\"adam_epsilon\", float, 1e-8, \"Epsilon for Adam optimizer.\")\n model_g.add_arg(\"warmup_steps\", int, 10, \"Linear warmup over warmup_steps.\")\n model_g.add_arg(\"max_grad_norm\", float, 1.0, \"Max gradient norm.\")\n model_g.add_arg(\"evaluate_steps\", int, 2, \"Evaluate every X updates steps.\")\n model_g.add_arg(\"evaluate_epoch\", float, 0.0, \"evaluate every X update epoch\")\n\n model_g.add_arg(\"save_steps\", int, 1, \"Save every X updates steps.\")\n model_g.add_arg(\"evaluate_during_training\", bool, True, \"Run evaluation during training at each logging step.\")\n model_g.add_arg(\"n_best_size\", int, 20,\n \"The total number of n-best predictions to generate in the nbest_predictions.json output file.\")\n model_g.add_arg(\"verbose_logging\", bool, False,\n \"If true, all of the warnings related to data processing will be printed. \"\n \"A number of warnings are expected for a normal multirc evaluation.\")\n model_g.add_arg(\"init_dir\", str, \"../cache/bert-large-cased/\", \"The path of loading pre-trained model.\")\n model_g.add_arg(\"initializer_range\", float, 0.02, \"The initializer range for KELM\")\n model_g.add_arg(\"cat_mul\", bool, True, \"The output part of vector in KELM\")\n model_g.add_arg(\"cat_sub\", bool, True, \"The output part of vector in KELM\")\n model_g.add_arg(\"cat_twotime\", bool, True, \"The output part of vector in KELM\")\n model_g.add_arg(\"cat_twotime_mul\", bool, True, \"The output part of vector in KELM\")\n model_g.add_arg(\"cat_twotime_sub\", bool, False, \"The output part of vector in KELM\")\n\n data_g = ArgumentGroup(parser, \"data\", \"Data paths, vocab paths and data processing options\")\n data_g.add_arg(\"train_file\", str, \"multirc/train.tagged.jsonl\", \"multirc json for training. E.g., train.json.\")\n data_g.add_arg(\"predict_file\", str, \"multirc/val.tagged.jsonl\", \"multirc json for predictions. E.g. dev.json.\")\n data_g.add_arg(\"cache_file_suffix\", str, \"test\", \"The suffix of cached file.\")\n data_g.add_arg(\"cache_dir\", str, \"../cache/\", \"The cached data path.\")\n data_g.add_arg(\"cache_store_dir\", str, \"../cache/\", \"The cached data path.\")\n data_g.add_arg(\"data_dir\", str, \"../data/\", \"The input data dir. Should contain the .json files for the task.\"\n + \"If no data dir or train/predict files are specified, will run with tensorflow_datasets.\")\n\n data_g.add_arg(\"vocab_path\", str, \"vocab.txt\", \"Vocabulary path.\")\n data_g.add_arg(\"do_lower_case\", bool, False,\n \"Whether to lower case the input text. Should be True for uncased models and False for cased models.\")\n data_g.add_arg(\"seed\", int, 42, \"Random seed.\")\n data_g.add_arg(\"kg_paths\", dict, {\"wordnet\": \"kgs/\", \"nell\": \"kgs/\"}, \"The paths of knowledge graph files.\")\n data_g.add_arg(\"wn_concept_embedding_path\", str, \"embedded/wn_concept2vec.txt\",\n \"The embeddings of concept in knowledge graph : Wordnet.\")\n data_g.add_arg(\"nell_concept_embedding_path\", str, \"embedded/nell_concept2vec.txt\",\n \"The embeddings of concept in knowledge graph : Nell.\")\n data_g.add_arg(\"use_kgs\", list, ['nell', 'wordnet'], \"The used knowledge graphs.\")\n # data_g.add_arg(\"doc_stride\", int, 128,\n # \"When splitting up a long document into chunks, how much stride to take between chunks.\")\n data_g.add_arg(\"max_seq_length\", int, 256, \"Number of words of the longest seqence.\")\n # data_g.add_arg(\"max_query_length\", int, 64, \"Max query length.\")\n # data_g.add_arg(\"max_answer_length\", int, 30, \"Max answer length.\")\n data_g.add_arg(\"no_stopwords\", bool, True, \"Whether to include stopwords.\")\n data_g.add_arg(\"ignore_length\", int, 0, \"The smallest size of token.\")\n data_g.add_arg(\"print_loss_step\", int, 100, \"The steps to print loss.\")\n\n run_type_g = ArgumentGroup(parser, \"run_type\", \"running type options.\")\n run_type_g.add_arg(\"use_fp16\", bool, False, \"Whether to use fp16 mixed precision training.\")\n run_type_g.add_arg(\"use_cuda\", bool, True, \"If set, use GPU for training.\")\n run_type_g.add_arg(\"max_n_gpu\", int, 100, \"The maximum number of GPU to use.\")\n run_type_g.add_arg(\"use_fast_executor\", bool, False, \"If set, use fast parallel executor (in experiment).\")\n run_type_g.add_arg(\"num_iteration_per_drop_scope\", int, 1,\n \"Ihe iteration intervals to clean up temporary variables.\")\n run_type_g.add_arg(\"do_train\", bool, True, \"Whether to perform training.\")\n run_type_g.add_arg(\"do_eval\", bool, False, \"Whether to perform evaluation during training.\")\n run_type_g.add_arg(\"do_predict\", bool, False, \"Whether to perform prediction.\")\n run_type_g.add_arg(\"freeze\", bool, True, \"freeze bert parameters\")\n run_type_g.add_arg(\"server_ip\", str, \"\", \"Can be used for distant debugging.\")\n run_type_g.add_arg(\"chunksize\", int, 1024, \"The chunksize for multiprocessing to convert examples to features.\")\n run_type_g.add_arg(\"server_port\", str, \"\", \"Can be used for distant debugging.\")\n run_type_g.add_arg(\"local_rank\", int, -1, \"Index for distributed training on gpus.\")\n run_type_g.add_arg(\"threads\", int, 50, \"multiple threads for converting example to features\")\n run_type_g.add_arg(\"overwrite_cache\", bool, False, \"Overwrite the cached training and evaluation sets\")\n run_type_g.add_arg(\"eval_all_checkpoints\", bool, False,\n \"Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number\")\n run_type_g.add_arg(\"min_diff_steps\", int, 50, \"The minimum saving steps before the last maximum steps.\")\n args = parser.parse_args()\n\n logging.getLogger(\"transformers.modeling_utils\").setLevel(logging.WARNING) # Reduce model loading logs\n\n if not args.is_all_relation:\n args.relation_list = args.selected_relation.split(\",\")\n logger.info(\"not use all relation, relation_list: {}\".format(args.relation_list))\n\n # if args.doc_stride >= args.max_seq_length - args.max_query_length:\n # logger.warning(\n # \"WARNING - You've set a doc stride which may be superior to the document length in some \"\n # \"examples. This could result in errors when building features from the examples. Please reduce the doc \"\n # \"stride or increase the maximum length to ensure the features are correctly built.\"\n # )\n\n if (\n os.path.exists(args.output_dir)\n and os.listdir(args.output_dir)\n and args.do_train\n and not args.overwrite_output_dir\n ):\n raise ValueError(\n \"Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.\".format(\n args.output_dir\n )\n )\n\n # Setup distant debugging if needed\n if args.server_ip and args.server_port:\n # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script\n import ptvsd\n\n print(\"Waiting for debugger attach\")\n ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True)\n ptvsd.wait_for_attach()\n\n # Setup CUDA, GPU & distributed training\n if args.local_rank == -1 or not args.use_cuda: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs\n device = torch.device(\"cuda\" if torch.cuda.is_available() and args.use_cuda else \"cpu\")\n args.n_gpu = 0 if not args.use_cuda else min(args.max_n_gpu, torch.cuda.device_count())\n else:\n torch.cuda.set_device(args.local_rank)\n device = torch.device(\"cuda\", args.local_rank)\n torch.distributed.init_process_group(backend=\"nccl\")\n args.n_gpu = 1\n\n args.device = device\n\n if args.local_rank in [-1, 0] and not os.path.exists(args.output_dir):\n os.mkdir(args.output_dir)\n\n # Setup logging\n logging.basicConfig(\n format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",\n datefmt=\"%m/%d/%Y %H:%M:%S\",\n level=logging.INFO if args.local_rank in [-1, 0] else logging.WARNING,\n )\n logger.warning(\n \"Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s\",\n args.local_rank,\n device,\n args.n_gpu,\n bool(args.local_rank != -1),\n args.use_fp16,\n )\n\n # Set seed\n set_seed(args)\n\n logger.info(\"Parameters from arguments are:\\n{}\".format(args))\n\n # Before we do anything with models, we want to ensure that we get fp16 execution of torch.einsum if args.use_fp16 is set.\n # Otherwise it'll default to \"promote\" mode, and we'll get fp32 operations. Note that running `--fp16_opt_level=\"O2\"` will\n # remove the need for this code, but it is still valid.\n if args.use_fp16:\n try:\n import apex\n apex.amp.register_half_function(torch, \"einsum\")\n except ImportError:\n raise ImportError(\"Please install apex from https://www.github.com/nvidia/apex to use fp16 training.\")\n\n processor = MultircProcessor(args)\n\n input_dir = os.path.join(args.cache_store_dir, \"cached_{}_{}\".format(\n args.model_type,\n str(args.cache_file_suffix),\n )\n )\n if not os.path.exists(input_dir):\n os.mkdir(input_dir)\n\n if args.data_preprocess:\n retrievers = dict()\n for kg in args.use_kgs:\n logger.info(\"Initialize kg:{}\".format(kg))\n kg_path = os.path.join(input_dir, args.kg_paths[kg])\n data_path = os.path.join(args.data_dir, args.kg_paths[kg])\n\n if args.data_preprocess_evaluate and \\\n (not os.path.exists(kg_path) or not os.path.join(input_dir,\n args.cache_file_suffix) + \"_\" + \"definition_info\"):\n logger.warning(\"need prepare training dataset firstly, program exit\")\n exit()\n\n retrievers[kg] = initialize_kg_retriever(kg, kg_path, data_path, args.cache_file_suffix)\n\n create_dataset(args, processor, retrievers, relation_list=args.relation_list,\n evaluate=args.data_preprocess_evaluate, input_dir=input_dir)\n\n logger.info(\"data preprocess is done. program exits\")\n exit()\n\n if not args.full_table:\n args.wn_def_embed_mat_dir = os.path.join(input_dir, args.cache_file_suffix) + \"_\" + \"definition_embedding\"\n else:\n logger.warning(\"set full_table False and program exits\")\n exit()\n logger.info(\"used definition table: {}\".format(args.wn_def_embed_mat_dir))\n\n # Training\n if args.do_train:\n retrievers = dict()\n for kg in args.use_kgs:\n logger.info(\"Initialize kg:{}\".format(kg))\n kg_path = os.path.join(input_dir, args.kg_paths[kg])\n data_path = os.path.join(args.data_dir, args.kg_paths[kg])\n\n if not os.path.exists(kg_path):\n logger.warning(\"need prepare training dataset firstly, program exit\")\n exit()\n\n retrievers[kg] = initialize_kg_retriever(kg, kg_path, data_path, args.cache_file_suffix)\n\n # Load pretrained model and tokenizer\n if args.local_rank not in [-1, 0]:\n # Make sure only the first process in distributed training will download model & vocab\n torch.distributed.barrier()\n tokenizer, model = configure_tokenizer_model(args, logger, retrievers)\n if args.local_rank == 0:\n # Make sure only the first process in distributed training will download model & vocab\n torch.distributed.barrier()\n\n if args.do_eval:\n model.to(args.device)\n results = evaluate(args, model, processor, tokenizer, 100, input_dir)\n\n if args.local_rank in [-1, 0]:\n logger.info(\"results: {}\".format(results))\n\n logger.info(\"eval is done\")\n exit()\n\n train_dataset, wn_synset_graphs, wn_synset_graphs_label_dict = load_and_cache_examples(args,\n processor,\n retrievers,\n relation_list=args.relation_list,\n input_dir=input_dir,\n evaluate=False,\n output_examples=False)\n model.to(args.device)\n global_step, tr_loss = train(args, train_dataset, model, processor, tokenizer, retrievers, wn_synset_graphs,\n wn_synset_graphs_label_dict, input_dir)\n logger.info(\" global_step = %s, average loss = %s\", global_step, tr_loss)\n\n # Save the trained model\n if args.do_train and (args.local_rank == -1 or torch.distributed.get_rank() == 0):\n logger.info(\"Saving trained model to %s\", args.output_dir)\n # Save a trained model, configuration using `save_pretrained()`.\n # They can then be reloaded using `from_pretrained()`\n # Take care of distributed/parallel training\n\n model_to_save = model.module if hasattr(model, \"module\") else model\n model_to_save.save_pretrained(args.output_dir)\n # Good practice: save your training arguments together with the trained model\n torch.save(args, os.path.join(args.output_dir, \"training_args.bin\"))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/run_multirc_qa.py","file_name":"run_multirc_qa.py","file_ext":"py","file_size_in_byte":60920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"348130112","text":"import sys\nimport os\nsys.path.insert(0, os.getcwd())\n\nimport requests\nimport calculator\nimport todo\nimport dictionary\nimport news\nimport geekjokes\nimport courses\nimport jobs\nimport leaderboard\nimport trendingproblems\nfrom bs4 import BeautifulSoup\n\nfrom typing import Dict\nfrom typing import Any\n\ndef get_codery_result(codery_keywords: str) -> str:\n help_message = \"*Help for Codery* : \\n\\n\" \\\n \"The bot responds to messages starting with @Codery.\\n\\n\" \\\n \"`@Codery contests` will return top Contests today, their dates, time left and the links to each contest.\\n\" \\\n \"`@Codery top contest` also returns the top Contest result.\\n\" \\\n \"`@Codery trending` returns the top trending ploblems across all programming platforms.\\n\" \\\n \"`@Codery dictionary ` returns the meaning of that word in an instant.\\n\" \\\n \"`@Codery jokes` keeps your morale boosted with programming jokes.\\n\" \\\n \"`@Codery jobs ` returns the top jobs for that search word.\\n\" \\\n \"`@Codery news ` returns the news for that key word.\\n\" \\\n \"`@Codery man ` returns the user manual of that function.\\n\" \\\n \"`@Codery top contests` will return n number of top contests at that time.\\n \\n\" \\\n \"Example:\\n\" \\\n \" * @Codery contests\\n\" \\\n \" * @Codery top contest\\n\" \\\n \" * @Codery jokes\\n\" \\\n \" * @Codery top 7 contests\\n\" \\\n \" * @Codery dictionary computer\\n\" \\\n \" * @Codery search code\\n\" \\\n \" * @Codery jobs pyhton\\n\" \\\n \" * @Codery jobs java\\n\" \\\n \" * @Codery trending\\n\" \\\n \" * @Codery man execvp\\n\" \\\n \" * @Codery news corona\"\n\n codery_keywords = codery_keywords.strip()\n codery_keywords_list = codery_keywords.split(\" \")\n\n if codery_keywords == 'help':\n return help_message\n\n elif codery_keywords_list[0] == \"todo\":\n return todo.get_todo_response(codery_keywords, CoderyHandler)\n\n elif codery_keywords_list[0] == \"jobs\":\n return jobs.get_jobs(codery_keywords, CoderyHandler)\n\n elif codery_keywords_list[0] == \"leaderboard\":\n return leaderboard.get_leaderboard()\n\n elif codery_keywords_list[0] == \"trending\":\n return trendingproblems.get_problems()\n\n elif codery_keywords_list[0] == \"search\" or codery_keywords_list[0] == \"dictionary\":\n return dictionary.get_dictionary_response(codery_keywords, CoderyHandler)\n\n elif codery_keywords_list[0] == \"courses\" or codery_keywords_list[0] == \"course\":\n return courses.get_courses(codery_keywords, CoderyHandler)\n\n elif codery_keywords_list[0] == \"jokes\" or codery_keywords_list[0] == \"joke\":\n return geekjokes.get_joke(codery_keywords, CoderyHandler)\n\n elif codery_keywords_list[0] == \"calculator\":\n return \"The answer is\"+calculator.get_calculator_response(codery_keywords, CoderyHandler)\n\n elif codery_keywords_list[0] == \"news\":\n return news.get_news_response(codery_keywords, CoderyHandler)\n\n elif codery_keywords == 'contests':\n\n URL = 'https://www.stopstalk.com/contests'\n content = requests.get(URL)\n soup = BeautifulSoup(content.text, 'html.parser')\n contentTable = soup.find('table', {\"class\": \"centered bordered\"}) # Use dictionary to pass key : value pair\n\n rows = contentTable.find_all('tr')\n lo = []\n i = 0\n\n for row in rows[1:]:\n lo.append(\"##\")\n columns = row.find_all('td')\n for column in columns:\n if column.get_text() != \"\":\n lo.append((column.get_text()).strip() + \"@@\")\n\n lo.append((columns[4].find('a')['href']).strip())\n i += 1\n\n l1 = \"The top contests and hackathons of today are \\n\"\n for r in lo:\n allContest = r.split(\"##\")\n for eachContest in allContest:\n attrList = eachContest.split(\"@@\")\n for attr in attrList:\n l1 += attr+\"\\n\"\n\n return l1\n\n # return a list of top contests\n elif codery_keywords == 'top contest':\n URL = 'https://www.stopstalk.com/contests'\n content = requests.get(URL)\n soup = BeautifulSoup(content.text, 'html.parser')\n contentTable = soup.find('table', {\"class\": \"centered bordered\"}) # Use dictionary to pass key : value pair\n\n rows = contentTable.find_all('tr')\n lo = []\n i = 0\n\n for row in rows[1:]:\n lo.append(\"##\")\n columns = row.find_all('td')\n for column in columns:\n if column.get_text() != \"\":\n lo.append((column.get_text()).strip() + \"@@\")\n\n lo.append((columns[4].find('a')['href']).strip())\n i += 1\n if i == 1:\n break\n l1 = \"\"\n for r in lo:\n allContest = r.split(\"##\")\n for eachContest in allContest:\n attrList = eachContest.split(\"@@\")\n for attr in attrList:\n l1 += attr+\"\\n\"\n\n return l1\n\n # to return a list of n top contests\n elif len(codery_keywords_list) == 3:\n\n if codery_keywords_list[0] == \"top\" and codery_keywords_list[2] == \"contests\":\n n = int(codery_keywords_list[1])\n else:\n help_message\n URL = 'https://www.stopstalk.com/contests'\n content = requests.get(URL)\n soup = BeautifulSoup(content.text, 'html.parser')\n contentTable = soup.find('table', {\"class\": \"centered bordered\"}) # Use dictionary to pass key : value pair\n\n rows = contentTable.find_all('tr')\n lo = []\n i = 0\n\n for row in rows[1:]:\n lo.append(\"##\")\n columns = row.find_all('td')\n for column in columns:\n if column.get_text() != \"\":\n lo.append((column.get_text()).strip() + \"@@\")\n\n lo.append((columns[4].find('a')['href']).strip())\n i += 1\n if i == n:\n break\n l1 = \"\"\n for r in lo:\n allContest = r.split(\"##\")\n for eachContest in allContest:\n attrList = eachContest.split(\"@@\")\n for attr in attrList:\n l1 += attr+\"\\n\"\n\n return l1\n\n elif codery_keywords == '' or codery_keywords is None:\n return help_message\n\nclass CoderyHandler(object):\n def handle_message(self, message: Dict[str, str], bot_handler: Any) -> None:\n original_content = message['content']\n result = get_codery_result(original_content)\n bot_handler.send_reply(message, result)\nhandler_class = CoderyHandler\n","sub_path":"zulip_bots/zulip_bots/bots/codery/codery.py","file_name":"codery.py","file_ext":"py","file_size_in_byte":6925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"3599713","text":"from aux_funcs_2020 import *\n\ndatlist=sort(glob.glob(datadir+'aux_data/Air-Sea_FW/ERA5_ilebras/hourly_downloaded_200618/*'))\n\ndat=xr.open_dataset(datlist[0])\nfor dd in datlist[1:]:\n dattmp=xr.open_dataset(dd)\n dat=xr.concat([dat,dattmp],dim='time')\n\ncut_dat=dat.sel(latitude=60).sel(longitude=slice(-43,-41)).sortby('time')\n\ncut_dat['tau']=cut_dat.metss*cos(theta)+cut_dat.mntss*sin(theta)\ncut_dat['hf']=cut_dat['msnlwrf']+cut_dat['msnswrf']+cut_dat['msshf']+cut_dat['mslhf']\n\ndef plotvar(var):\n cut_dat[var].mean(dim='longitude').resample(time='1D').mean(dim='time').plot()\n\nplotvar('hf')\nplotvar('tau')\n\ncut_dat.to_netcdf(datadir+'aux_data/Air-Sea_FW/ERA5_ilebras/hourly_downloaded_200618/ERA5_hourly_SI_ilebras.nc','w',format='netCDF4')\n","sub_path":"SI/Load_ERA5_hourly.py","file_name":"Load_ERA5_hourly.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"179012384","text":"import csv\n\ndef main():\n\tdata = [['bidid', 'bidprice']]\n\ttotalBidSum = 12\n\tcurrentBid = 0\n\twhile (currentBid < totalBidSum):\n\t\tdata.append([currentBid, '233'])\n\t\tcurrentBid = currentBid + 1\n\tTestBidLogWriter(totalBidSum, data)\n\ndef TestBidLogWriter(totalBidSum, data):\n\tbid_log_file = open('testing bidding price.csv', 'w')\n\tbid_log_writer = csv.writer(bid_log_file)\n\tbid_log_writer.writerows(data)\n\tbid_log_file.close()\n\nmain()","sub_path":"BidLogWriter.py","file_name":"BidLogWriter.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"2608590","text":"#factorial function\n#Input : n\n#Output : n!\n\ndef factorial(n):\n\n if n <=1:\n return 1\n\n else:\n result = 1\n while n >0:\n result *= n\n n -= 1\n return result\n\n#Main Program\n\nwhile True:\n\n try:\n\n n = int(input('Enter a number : '))\n if n == -1:\n break\n elif n < 0:\n print('0 또는 양의 정수를 입력해주세요.')\n else:\n print(n, \"! = \", factorial(n))\n\n except:\n\n print('0 또는 양의 정수를 입력해주세요.')\n continue\n","sub_path":"week2/김수진-assignment2.py","file_name":"김수진-assignment2.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"531063220","text":"import numpy as np\nfrom PIL import Image\n\ndef unpad(arr, dim_sizes):\n for dim, s in dim_sizes.items():\n arr = np.delete(arr, np.s_[-s:], axis=dim)\n arr = np.delete(arr, np.s_[0:s], axis=dim)\n return arr\n\ndef replicate_edges(arr, dim_sizes):\n arr = unpad(arr, dim_sizes)\n pads = []\n for i in range(arr.ndim):\n if i in dim_sizes:\n pads.append((dim_sizes[i], dim_sizes[i]))\n else:\n pads.append((0,0))\n arr = np.pad(arr, pads, mode='wrap')\n return arr\n\n\nif __name__ == '__main__':\n img_path = 'data/pol.jpg'\n out_path = 'test_wrap.png'\n arr = np.array(Image.open(img_path))\n arr = replicate_edges(arr, {0:30,1:30})\n\n img = Image.fromarray(arr)\n img.save(out_path)\n","sub_path":"unpad.py","file_name":"unpad.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"137569535","text":"# Copyright (c) 2018, MD2K Center of Excellence\n# - Nasir Ali \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, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# 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 ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport json\nimport re\nimport traceback\nimport uuid\nfrom datetime import datetime, timedelta\nfrom typing import List\n\nfrom pytz import timezone\n\n\nclass StreamHandler():\n\n ###################################################################\n ################## GET DATA METHODS ###############################\n ###################################################################\n\n def get_stream_metadata(self, stream_id: uuid) -> dict:\n \"\"\"\n Get stream metadata\n :param stream_id:\n :return: identifier, owner, name, data_descriptor,execution_context,annotations, type, start_time, end_time, tmp (tmp is just a primary key ID)\n :rtype dict\n \"\"\"\n qry = \"SELECT * from \" + self.datastreamTable + \" where identifier=%(identifier)s\"\n vals = {\"identifier\": str(stream_id)}\n rows = self.execute(qry, vals)\n return rows\n\n def get_stream_metadata_by_user(self, user_id: uuid, stream_name: str = None, start_time: datetime = None,\n end_time: datetime = None) -> dict:\n \"\"\"\n Returns stream ids and metadata of a stream name belong to a user\n :param user_id:\n :return: identifier, data_descriptor,execution_context,annotations, start_time, end_time\n :rtype: dict\n \"\"\"\n vals = []\n if not user_id:\n raise ValueError(\"User ID cannot be empty/None.\")\n\n qry = \"SELECT identifier, data_descriptor,execution_context,annotations, start_time, end_time from \" + self.datastreamTable\n where_clause = \" where owner=%s \"\n vals.append(user_id)\n if stream_name:\n where_clause += \" and name=%s \"\n vals.append(stream_name)\n if start_time:\n where_clause += \" and start_time<=%s \"\n vals.append(start_time)\n if end_time:\n where_clause += \" and end_time>=%s \"\n vals.append(end_time)\n\n qry = qry + where_clause\n vals = tuple(vals)\n rows = self.execute(qry, vals)\n return rows\n\n def user_has_stream(self, user_id: uuid, stream_name: str) -> bool:\n \"\"\"\n Returns true if a user has a stream available\n :param user_id: \n :param stream_name: \n :return: True if owner has a stream, False otherwise\n \"\"\"\n if not stream_name or not user_id:\n raise ValueError(\"Strea name and User ID are required fields.\")\n\n qry = \"select identifier from \" + self.datastreamTable + \" where owner=%s and name = %s\"\n vals = str(user_id), str(stream_name)\n\n rows = self.execute(qry, vals)\n\n if len(rows) == 0:\n return False\n else:\n return True\n\n def get_stream_duration(self, stream_id: uuid) -> dict:\n \"\"\"\n Get time duration (start time - end time) of a stream\n :param stream_id:\n :return:start_time, end_time\n :rtype dict\n \"\"\"\n if not stream_id:\n raise ValueError(\"Stream ID is a required field.\")\n\n qry = \"select start_time, end_time from \" + self.datastreamTable + \" where identifier = %(identifier)s\"\n vals = {'identifier': str(stream_id)}\n\n rows = self.execute(qry, vals)\n\n if len(rows) == 0:\n return {\"start_time\": None, \"end_time\": None}\n else:\n return {\"start_time\": rows[0][\"start_time\"], \"end_time\": rows[0][\"end_time\"]}\n\n def get_all_users(self, study_name: str) -> List[dict]:\n\n \"\"\"\n Get all users id and user name for a particular study\n :param study_name:\n :return: List of dicts (keys=identifier, username)\n :rtype List\n \"\"\"\n if not study_name:\n raise ValueError(\"Study name is a requied field.\")\n\n results = []\n qry = 'SELECT identifier, username FROM ' + self.userTable + ' where user_metadata->\"$.study_name\"=%(study_name)s'\n vals = {'study_name': str(study_name)}\n\n rows = self.execute(qry, vals)\n\n if len(rows) == 0:\n return []\n else:\n for row in rows:\n results.append(row)\n return results\n\n def get_user_streams(self, user_id: uuid) -> dict:\n\n \"\"\"\n Returns all user streams with name and metadata attached to it. Do not use \"identifier\" field as it doesn't\n represents all the stream-ids linked to a stream name. Use stream_ids field in dict to get all stream-ids of a stream name.\n :param user_id:\n :return: identifier, owner, name, data_descriptor,execution_context,annotations, type, start_time, end_time, tmp, stream_ids (this contains all the stream ids of a stream name)\n :rtype: dict\n \"\"\"\n if not user_id:\n raise ValueError(\"User ID is a required field.\")\n\n result = {}\n qry = 'SELECT * FROM ' + self.datastreamTable + ' where owner=%(owner)s'\n vals = {'owner': str(user_id)}\n\n rows = self.execute(qry, vals)\n\n if len(rows) == 0:\n return result\n else:\n for row in rows:\n stream_ids = self.get_stream_id(str(user_id), row[\"name\"])\n row[\"stream_ids\"] = [d['identifier'] for d in stream_ids]\n result[row[\"name\"]] = row\n return result\n\n def get_user_streams_metadata(self, user_id: str) -> dict:\n \"\"\"\n Get all streams metadata of a user\n :param user_id:\n :return: name, data_descriptor,execution_context,annotations, start_time, end_time\n :rtype: dict\n \"\"\"\n if not user_id:\n raise ValueError(\"User ID is a required field.\")\n\n result = {}\n qry = \"select name, data_descriptor,execution_context,annotations, start_time, end_time from \" + self.datastreamTable + \" where owner = %(owner)s\"\n vals = {'owner': str(user_id)}\n\n rows = self.execute(qry, vals)\n\n if len(rows) == 0:\n return result\n else:\n for row in rows:\n stream_ids = self.get_stream_id(str(user_id), row[\"name\"])\n row[\"stream_ids\"] = [d['identifier'] for d in stream_ids]\n result[row[\"name\"]] = row\n return result\n\n def get_user_name(self, user_id: uuid) -> str:\n \"\"\"\n Get username of a user's UUID\n :param user_id:\n :return: user id\n :rtype: str\n \"\"\"\n if not user_id:\n raise ValueError(\"User ID is a required field.\")\n\n qry = \"select username from \" + self.userTable + \" where identifier = %(identifier)s\"\n vals = {'identifier': str(user_id)}\n\n rows = self.execute(qry, vals)\n\n if len(rows) == 0:\n return \"\"\n else:\n return rows[0][\"username\"]\n\n def is_user(self, user_id: uuid = None, user_name: uuid = None) -> bool:\n \"\"\"\n Check whether a username or user ID exists in MySQL\n :param user_id:\n :param user_name\n :return: True if user exist, False otherwise\n :rtype: bool\n \"\"\"\n if user_id and user_name:\n qry = \"select username from \" + self.userTable + \" where identifier = %s and username=%s\"\n vals = str(user_id), user_name\n elif user_id and not user_name:\n qry = \"select username from \" + self.userTable + \" where identifier = %(identifier)s\"\n vals = {'identifier': str(user_id)}\n elif not user_id and user_name:\n qry = \"select username from \" + self.userTable + \" where username = %(username)s\"\n vals = {'username': str(user_name)}\n else:\n raise ValueError(\"Wrong parameters.\")\n\n rows = self.execute(qry, vals)\n\n if len(rows) == 0:\n return False\n else:\n return True\n\n def get_user_id(self, user_name: str) -> str:\n \"\"\"\n Get user's UUID\n :param user_name:\n :return: user's UUID\n :rtype: str\n \"\"\"\n if not user_name:\n raise ValueError(\"User name is a required field.\")\n\n qry = \"select identifier from \" + self.userTable + \" where username = %(username)s\"\n vals = {'username': str(user_name)}\n\n rows = self.execute(qry, vals)\n\n if len(rows) == 0:\n return \"\"\n else:\n return rows[0][\"identifier\"]\n\n def get_stream_id(self, user_id: uuid, stream_name: str) -> dict:\n \"\"\"\n Get a stream ids of stream name linked to a user\n :param user_id\n :param stream_name:\n :return: List of stream ids\n :rtype: dict\n \"\"\"\n if not stream_name or not user_id:\n raise ValueError(\"User ID and stream name are required field.\")\n\n qry = \"select identifier from \" + self.datastreamTable + \" where owner=%s and name = %s\"\n vals = str(user_id), str(stream_name)\n\n rows = self.execute(qry, vals)\n\n if len(rows) == 0:\n return {}\n else:\n return rows\n\n def get_stream_days(self, stream_id: uuid) -> List:\n \"\"\"\n Returns a list of days (string format: YearMonthDay (e.g., 20171206) for a given stream-id\n :param stream_id:\n :param dd_stream_id:\n :return: list of days (format YYYYMMDD)\n :rtype: List\n \"\"\"\n if not stream_id:\n raise ValueError(\"Stream ID is a required field.\")\n all_days = []\n stream_days = self.get_stream_duration(stream_id)\n if stream_days[\"end_time\"] is not None and stream_days[\"start_time\"] is not None:\n days = stream_days[\"end_time\"] - stream_days[\"start_time\"]\n for day in range(days.days + 1):\n all_days.append((stream_days[\"start_time\"] + timedelta(days=day)).strftime('%Y%m%d'))\n\n return all_days\n\n def get_stream_name(self, stream_id: uuid) -> str:\n \"\"\"\n Get strea name linked to a stream UUID\n :param stream_id:\n :return: stream name\n :rtype: str\n \"\"\"\n if not stream_id:\n raise ValueError(\"Stream ID is a required field.\")\n\n qry = \"select name from \" + self.datastreamTable + \" where identifier = %(identifier)s\"\n vals = {'identifier': str(stream_id)}\n\n rows = self.execute(qry, vals)\n\n if len(rows) == 0:\n return \"\"\n else:\n return rows[0][\"name\"]\n\n def is_stream(self, stream_id: uuid) -> bool:\n\n \"\"\"\n Checks whether a stream exist\n :param stream_id:\n :return: True if a stream ID exist, False otherwise\n :rtype: bool\n \"\"\"\n qry = \"SELECT * from \" + self.datastreamTable + \" where identifier = %(identifier)s\"\n vals = {'identifier': str(stream_id)}\n rows = self.execute(qry, vals)\n\n if rows:\n return True\n else:\n return False\n\n ###################################################################\n ################## STORE DATA METHODS #############################\n ###################################################################\n\n def save_stream_metadata(self, stream_id: uuid, stream_name: str, owner_id: uuid,\n data_descriptor: dict,\n execution_context: dict,\n annotations: dict, stream_type: str, start_time: datetime, end_time: datetime):\n \"\"\"\n Update a record if stream already exists, insert a new record otherwise.\n :param stream_id:\n :param stream_name:\n :param owner_id:\n :param data_descriptor:\n :param execution_context:\n :param annotations:\n :param stream_type:\n :param start_time:\n :param end_time:\n \"\"\"\n isQueryReady = 0\n\n if stream_id:\n stream_id = str(stream_id)\n\n if self.is_stream(stream_id=stream_id):\n self.update_start_time(stream_id, start_time)\n stream_end_time = self.check_end_time(stream_id, end_time)\n annotation_status = self.annotations_status(stream_id, owner_id, annotations)\n else:\n stream_end_time = None\n annotation_status = \"new\"\n\n if stream_end_time != \"unchanged\" and annotation_status == \"changed\":\n # update annotations and end-time\n qry = \"UPDATE \" + self.datastreamTable + \" set annotations=JSON_ARRAY_APPEND(annotations, '$.annotations', CAST(%s AS JSON)), end_time=%s where identifier=%s\"\n vals = json.dumps(annotations, default=str), stream_end_time, str(stream_id)\n isQueryReady = 1\n elif stream_end_time != \"unchanged\" and annotation_status == \"unchanged\":\n # update only end-time\n qry = \"UPDATE \" + self.datastreamTable + \" set end_time=%s where identifier=%s\"\n vals = end_time, str(stream_id)\n isQueryReady = 1\n elif stream_end_time == \"unchanged\" and annotation_status == \"changed\":\n # update only annotations\n qry = \"UPDATE \" + self.datastreamTable + \" set annotations=JSON_ARRAY_APPEND(annotations, '$.annotations', CAST(%s AS JSON)) where identifier=%s\"\n vals = json.dumps(annotations, default=str), str(stream_id)\n isQueryReady = 1\n\n elif (annotation_status == \"new\"):\n qry = \"INSERT INTO \" + self.datastreamTable + \" (identifier, owner, name, data_descriptor, execution_context, annotations, type, start_time, end_time) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s)\"\n vals = str(stream_id), str(owner_id), str(stream_name), json.dumps(\n data_descriptor), json.dumps(execution_context, default=str), json.dumps(\n annotations, default=str), stream_type, start_time, end_time\n isQueryReady = 1\n # if nothing is changed then isQueryReady would be 0 and no database transaction would be performed\n if isQueryReady == 1:\n try:\n self.execute(qry, vals, commit=True)\n except:\n self.logging.log(\n error_message=\"Query: \" + str(qry) + \" - cannot be processed. \" + str(traceback.format_exc()),\n error_type=self.logtypes.CRITICAL)\n\n def annotations_status(self, stream_id: uuid, owner_id: uuid, annotations: dict) -> str:\n \"\"\"\n This method will check whether the stream already exist with the same data (as provided in params) except annotations.\n :param stream_id:\n :param owner_id:\n :param annotations:\n :return:\n \"\"\"\n qry = \"select annotations from \" + self.datastreamTable + \" where identifier = %s and owner=%s\"\n vals = stream_id, owner_id\n result = self.execute(qry, vals)\n\n if result:\n if json.loads(result[0][\"annotations\"]) == annotations:\n return \"unchanged\"\n else:\n return \"changed\"\n else:\n return \"new\"\n\n def check_end_time(self, stream_id: uuid, end_time: datetime):\n \"\"\"\n Check whether end time was changed of a stream-id\n :param stream_id:\n :param end_time:\n :return: It returns a datetime object if end-time was changed. Otherwise, it returns status as unchanged\n :rtype: str OR datetime\n \"\"\"\n localtz = timezone(self.time_zone)\n\n qry = \"SELECT end_time from \" + self.datastreamTable + \" where identifier = %(identifier)s\"\n vals = {'identifier': str(stream_id)}\n rows = self.execute(qry, vals)\n\n if rows:\n old_end_time = rows[0][\"end_time\"]\n if end_time.tzinfo is None:\n end_time = localtz.localize(end_time)\n if old_end_time.tzinfo is None:\n old_end_time = localtz.localize(old_end_time)\n\n if old_end_time <= end_time:\n return end_time\n else:\n return \"unchanged\"\n else:\n self.logging.log(\n error_message=\"STREAM ID: \" + stream_id + \" - No record found. \" + str(traceback.format_exc()),\n error_type=self.logtypes.DEBUG)\n\n def update_start_time(self, stream_id: uuid, new_start_time: datetime):\n \"\"\"\n update start time only if the new-start-time is older than the existing start-time\n :param stream_id:\n :param new_start_time:\n :return:\n \"\"\"\n localtz = timezone(self.time_zone)\n\n qry = \"SELECT start_time from \" + self.datastreamTable + \" where identifier = %(identifier)s\"\n vals = {'identifier': str(stream_id)}\n rows = self.execute(qry, vals)\n\n if rows:\n old_start_time = rows[0][\"start_time\"]\n if new_start_time.tzinfo is None:\n new_start_time = localtz.localize(new_start_time)\n if old_start_time.tzinfo is None:\n old_start_time = localtz.localize(old_start_time)\n\n if old_start_time > new_start_time:\n qry = \"UPDATE \" + self.datastreamTable + \" set start_time=%s where identifier=%s\"\n vals = new_start_time, str(stream_id)\n self.execute(qry, vals, commit=True)\n else:\n self.logging.log(\n error_message=\"STREAM ID: \" + stream_id + \" - No record found. \" + str(traceback.format_exc()),\n error_type=self.logtypes.DEBUG)\n\n def mark_processed_day(self, owner_id: uuid, stream_id: uuid, day: str):\n \"\"\"\n Mark row as processed if the data has been processed/ingested. This is used for data replay.\n :param owner_id:\n :param stream_id:\n :param day:\n \"\"\"\n qry = \"UPDATE \" + self.dataReplayTable + \" set processed=1 where owner_id=%s and stream_id=%s and day=%s\"\n vals = str(owner_id), str(stream_id), str(day)\n self.execute(qry, vals, commit=True)\n\n def is_day_processed(self, owner_id: uuid, stream_id: uuid, day: str) -> bool:\n \"\"\"\n Checks whether data is processed for a given user-id and stream-id\n :param owner_id:\n :param stream_id:\n :param day:\n :return: True if day is processed, False otherwise\n :rtype: bool\n \"\"\"\n if day is not None:\n qry = \"SELECT processed from \" + self.dataReplayTable + \" where owner_id=%s and stream_id=%s and day=%s\"\n vals = str(owner_id), str(stream_id), str(day)\n rows = self.execute(qry, vals)\n if rows[0][\"processed\"] == 1:\n return True\n else:\n return False\n return False\n\n ###########################################################################################################################\n ## DATA REPLAY HELPER METHOD\n ###########################################################################################################################\n def get_all_data_days(self):\n \"\"\"\n Returns a list of days where data is available\n :return: List of days (yyyymmdd)\n :rtype: list of strings\n \"\"\"\n qry = \"SELECT day from \" + self.dataReplayTable + \" where processed=0 group by day\"\n rows = self.execute(qry)\n days = []\n if len(rows) > 0:\n for row in rows:\n days.append(row[\"day\"])\n return days\n\n def get_replay_batch(self, day, record_limit: int = 5000, nosql_blacklist:dict={\"regzex\":\"nonez\", \"txt_match\":\"nonez\"}) -> List:\n \"\"\"\n This method helps in data replay. Yield a batch of data rows that needs to be processed and ingested in CerebralCortex\n :param record_limit:\n :return: List of dicts (keys=owner_id, stream_id, stream_name, day, files_list, metadata)\n :rtype: dict\n \"\"\"\n\n regex_cols = \"\" # regex match on columns\n like_cols = \"\" # like operator on columns\n for breg in nosql_blacklist[\"regzex\"]:\n regex_cols += '%s NOT REGEXP \"%s\" and ' % (\"stream_name\", nosql_blacklist[\"regzex\"][breg])\n\n for btm in nosql_blacklist[\"txt_match\"]:\n like_cols += '%s not like \"%s\" and ' % (\"stream_name\", nosql_blacklist[\"txt_match\"][btm])\n\n # if regex_cols!=\"\" or like_cols!=\"\":\n # where_clause = \" where \"\n\n if regex_cols != \"\" and like_cols != \"\":\n qry = \"SELECT owner_id, stream_id, stream_name, day, files_list, metadata from \" + self.dataReplayTable + \" where \" + regex_cols + \" \" + like_cols + \" processed=0 and day='\"+day+\"' order by dir_size\"\n elif regex_cols != \"\" and like_cols == \"\":\n qry = \"SELECT owner_id, stream_id, stream_name, day, files_list, metadata from \" + self.dataReplayTable + \" where \" + regex_cols +\" processed=0 and day='\"+day+\"' order by dir_size\"\n elif regex_cols == \"\" and like_cols != \"\":\n qry = \"SELECT owner_id, stream_id, stream_name, day, files_list, metadata from \" + self.dataReplayTable + \" where \" + like_cols + \" processed=0 and day='\"+day+\"' order by dir_size\"\n else:\n qry = \"\"\n\n if qry != \"\":\n rows = self.execute(qry)\n msgs = []\n if len(rows) > 0:\n for row in rows:\n if len(msgs) > int(record_limit):\n yield msgs\n msgs = []\n #if row[\"owner_id\"] in good_participants:\n msgs.append(\n {\"owner_id\": row[\"owner_id\"], \"stream_id\": row[\"stream_id\"], \"stream_name\": row[\"stream_name\"],\n \"metadata\": json.loads(row[\"metadata\"]), \"day\": row[\"day\"],\n \"filename\": json.loads(row[\"files_list\"])})\n yield msgs\n else:\n yield []\n else:\n yield []\n\n def add_to_data_replay_table(self, table_name, owner_id, stream_id, stream_name, day, files_list, dir_size, metadata):\n qry = \"INSERT IGNORE INTO \"+table_name+\" (owner_id, stream_id, stream_name, day, files_list, dir_size, metadata) VALUES(%s, %s, %s, %s, %s, %s, %s)\"\n vals = str(owner_id), str(stream_id), str(stream_name), str(day), json.dumps(files_list), dir_size, json.dumps(metadata)\n self.execute(qry, vals, commit=True)\n","sub_path":"cerebralcortex/core/data_manager/sql/stream_handler.py","file_name":"stream_handler.py","file_ext":"py","file_size_in_byte":23637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"327575518","text":"# encoding=utf-8\nimport matplotlib.pyplot as plt\n'''\n将标注OURS1改成OURS2,将OURS3改成OURS1\n'''\ndef read_wrq(pro_name,E,K,D):\n #name*epsilon*k*delta\n means=[]\n for p in range(len(pro_name)):\n means.append([])\n for e in range(len(E)):\n means[p].append([])\n for k in range(len(K)):\n means[p][e].append([])\n for d in range(len(D)):\n fileName=pro_name[p]+'/'+pro_name[p]+'/output/'+'k(' + str(K[k]) + \\\n ')_e(' + str(E[e]) +')_delta('+str(D[d])+ ')wrq' + '.txt'\n f=open(fileName,'r')\n infos=f.readlines()\n f.close()\n means[p][e][k].append(float(infos[0]))\n return means\n\ndef get_info(means,p,e,K,d):\n re=[]\n for k in range(len(K)):\n re.append(means[p][e][k][d])\n return re\n\nif __name__ == '__main__':\n \n pro_name=['INFOCOM15','INFOCOM17','OURS1','OURS3']\n K = [10, 20, 30, 40, 50, 60, 70, 80]\n E = [0.1, 0.5, 1.0, 1.5, 2.0]\n D = [0.4,0.6,0.8,1.0]\n \n #means ( name*epsilon*k*delta )\n means=read_wrq(pro_name,E,K,D)\n \n \n for e in range(len(E)):\n \n #初始化画布\n p_long=9\n p_width=9\n fig=plt.figure(figsize=(p_long,p_width))\n \n #pl.xlim(-1, 11) # 限定横轴的范围\n #pl.ylim(-1, 110) # 限定纵轴的范围\n ax=[]\n for d in range(len(D)):\n #x轴\n names = K\n x = range(len(names))\n \n #2行2列第(d+1)个子图\n new=fig.add_subplot(220+d+1)\n \n infocom15_means=get_info(means,0,e,K,d)\n infocom17_means=get_info(means,1,e,K,d)\n ours1_means=get_info(means,2,e,K,d)\n ours3_means=get_info(means,3,e,K,d)\n \n new.plot(x, infocom15_means,linewidth=1.8,linestyle='-.',marker='p',label='INFOCOM15')\n new.plot(x, infocom17_means,linewidth=1.8,linestyle='-.',marker='*',label='INFOCOM17')\n new.plot(x, ours3_means,linewidth=1.8,linestyle='-.',marker='x',label='OURS1')\n new.plot(x, ours1_means,linewidth=1.8,linestyle='-.',marker='s',label='OURS2')\n \n ax.append(new)\n \n plt.plot(fontsize=15)\n plt.legend(loc='best') # 让图例生效\n #plt.legend(loc=2, bbox_to_anchor=(1.05,1.0),borderaxespad = 0)\n plt.xticks(x, names, rotation=45,fontsize=15)\n plt.yticks(fontsize=15)\n plt.margins(0)\n plt.subplots_adjust(bottom=0.15)\n plt.xlabel('(Numbers of Groups)',fontsize=15) \n plt.ylabel('wrq',fontsize=15)\n plt.title('delta='+str(D[d]))\n plt.tight_layout()\n #网格\n plt.grid(alpha=1,linestyle='-.',c='gray') \n #plt.subplots_adjust(right=0.72)\n #plt.show()\n plt.savefig('output/wrq/'+'_e('+str(E[e])+')'+'.png')\n \n \n ","sub_path":"wrq_lineChart.py","file_name":"wrq_lineChart.py","file_ext":"py","file_size_in_byte":3023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"521955425","text":"from matplotlib import pyplot as plt\r\nimport gpxpy\r\nimport os\r\nfrom tqdm import tqdm\r\nimport numpy as np\r\nimport json\r\n\r\npath = './data/'\r\n\r\nmass = 78\r\nbike_mass = 10.0\r\nt_m = mass + bike_mass\r\ng = 9.81\r\narea = 0.4\r\nearth_r = 6371000\r\nC_d = 1.0\r\nrho = 1.225\r\n\r\ndef find_optimal(fba_points):\r\n\tfba_points.sort(key = lambda x : x[0],reverse = True)\r\n\tto_return = []\r\n\tcurrent_max = -np.inf\r\n\tfor point in fba_points:\r\n\t\tif point[1] > current_max:\r\n\t\t\tcurrent_max = point[1]\r\n\t\t\tto_return.append(point)\r\n\treturn to_return\r\n\r\ndef smooth(y, box_pts):\r\n box = np.ones(box_pts)/box_pts\r\n y_smooth = np.convolve(y, box, mode='same')\r\n return y_smooth\r\n\r\ndef make_json_data(gpx_data):\r\n\tpoints = gpx_data.tracks[0].segments[0].points\r\n\tlat = np.array(list(map(lambda x : x.latitude,points)))\r\n\tlon = np.array(list(map(lambda x : x.longitude,points)))\r\n\telev = np.array(list(map(lambda x : x.elevation,points)))\r\n\tts = np.array(list(map(lambda x : x.time,points)))\r\n\td_lat = np.deg2rad(np.diff(lat))\r\n\td_lon = np.deg2rad(np.diff(lon))\r\n\td_elev = np.diff(elev)\r\n\td_ts = np.array(list(map(lambda x: x.total_seconds(),np.diff(ts))))\r\n\r\n\th_d_lat_2 = np.power(np.sin(d_lat/2),2)\r\n\tcos_cos = np.multiply(np.cos(np.deg2rad(lat[1:])),np.cos(np.deg2rad(lat[:-1])))\r\n\th_d_lon_2 = np.power(np.sin(d_lon/2),2)\r\n\tcc_h_d_lon_2 = np.multiply(cos_cos, h_d_lon_2)\r\n\r\n\tds = 2*earth_r*np.arcsin(np.sqrt(cc_h_d_lon_2+h_d_lat_2))\r\n\tvs = ds/d_ts\r\n\tif (len(vs)<10):\r\n\t\tbox_pts = len(vs)-1\r\n\telse:\r\n\t\tbox_pts = 10\r\n\tsmooth_vs = smooth(vs, box_pts)\r\n\tto_return = {'d_elev':d_elev,'d_ts':d_ts,'ds':ds,'vs':smooth_vs,'rough_vs':vs,'ts':ts}\r\n\treturn to_return\r\n\r\ndef add_power_to_json(data):\r\n\td_KE = np.diff(np.power(data['vs'],2))*t_m*0.5\r\n\td_GPE = t_m*g*data['d_elev'][:-1]/data['d_ts'][:-1]\r\n\tP_drag = 0.5*C_d*area*rho*np.power(data['vs'][:-1],3)\r\n\tP_kin = (d_KE + d_GPE)/data['d_ts'][:-1]\r\n\tpower = P_drag + P_kin\r\n\tdata['power'] = power\r\n\treturn data\r\n\r\ndef power_curve(data):\r\n\tpower = np.clip(data['power'],0.0,np.inf)/t_m\r\n\tts = data['ts']\r\n\tpowers = []\r\n\ttimes = []\r\n\tbox_pts = 4\r\n\twhile box_pts len(smoothed)-1:\r\n\t\t\tmax_arg = len(smoothed)-1\r\n\t\ttime = (ts[max_arg]-ts[min_arg]).total_seconds()\r\n\t\tif(time>1260):\r\n\t\t\tbreak\r\n\r\n\t\ttimes.append(time)\r\n\t\tpowers.append(p)\r\n\t\tbox_pts+=int(np.ceil(0.07*box_pts))\r\n\treturn powers,times\r\nif __name__ == '__main__':\r\n\tdata = []\r\n\r\n\tfor file in tqdm(sorted(os.listdir(path))[::-1]\t):\r\n\t\tgpx_file = open(path+file,'r')\r\n\t\tdata.append(make_json_data(gpxpy.parse(gpx_file)))\r\n\t\tdata[-1] = add_power_to_json(data[-1])\r\n\r\n\r\n\t# for datum in data:\r\n\t# \tpower = datum['power']\r\n\t# \tmean = np.mean(power)\r\n\t# \tprint(mean)\r\n\r\n\tall_powers = []\r\n\tall_times = []\r\n\r\n\tplt.rcParams['figure.facecolor'] = 'black'\r\n\tplt.rcParams['axes.facecolor'] = 'black'\r\n\tplt.rcParams['text.color'] = 'white'\r\n\tplt.rcParams['axes.labelcolor'] = 'white'\r\n\tplt.rcParams['axes.edgecolor'] = 'white'\r\n\tplt.rcParams['xtick.color'] = 'white'\r\n\tplt.rcParams['ytick.color'] = 'white'\r\n\tshow_recent = True\r\n\tcolor = 'limegreen'\r\n\tfor i,datum in enumerate(tqdm(data)):\r\n\t\tpowers, times = power_curve(datum)\r\n\t\tall_powers.extend(powers)\r\n\t\tall_times.extend(times)\r\n\t\tif show_recent:\r\n\t\t\tplt.semilogx(times,powers,color=color,alpha = 0.1+0.9*1.2**(len(data)-i)/1.2**len(data),markersize=3)\r\n\t\telse:\r\n\t\t\tplt.semilogx(times,powers,color=color,alpha = 0.7,markersize=3)\r\n\t\tcolor = 'deepskyblue'\r\n\tplt.xlabel('Time')\r\n\tplt.ylabel('Power / $W kg^{-1}$')\r\n\tplt.xticks([5,10,30,60,120,300,600,1200],['5s','10s','30s','1min','2min','5min','10min','20min'])\r\n\tplt.xlim([4.5,1250])\r\n\tplt.show()\r\n\tpoints = list(zip(all_times,all_powers))\r\n\tpoints = [x for x in points if x[0]<1300]\r\n\tto_save = {'power_curve':find_optimal(points)}\t\r\n\tprint(to_save)\r\n\twith open('power_curve_vp.json','w') as outfile:\r\n\t\tjson.dump(to_save,outfile)\r\n\r\n","sub_path":"power_curve_gen.py","file_name":"power_curve_gen.py","file_ext":"py","file_size_in_byte":4043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"193740596","text":"# Send notifications to registered mobile phones\n# Currently I am using pushover and the client has to install the\n# pushover app and register a user and application token.\n# The client supplies the keys on the cosmic pi client launch command line\nimport httplib\nimport urllib\n\n\nclass Notifications(object):\n def send_ntf(self, kyp, msg):\n nstr = kyp.split('-')\n\n self.conn = httplib.HTTPSConnection(\"api.pushover.net:443\")\n\n self.conn.request(\"POST\", \"/1/messages.json\",\n urllib.urlencode({\"token\": nstr[1],\n \"user\": nstr[0],\n \"sound\": \"Cosmic\",\n \"message\": msg}),\n {\"Content-type\": \"application/x-www-form-urlencoded\"})\n\n self.conn.getresponse()","sub_path":"notifications.py","file_name":"notifications.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"51445908","text":"'''\n\nimport socket\nimport ssl\n#创建一个socket\n#s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\ns = ssl.wrap_socket(socket.socket(socket.AF_INET,socket.SOCK_STREAM))\n\ns.connect(('www.sina.com.cn',443))\n\n\ns.send(b'GET / HTTP/1.1\\r\\nHost: www.sina.com.cn\\r\\nConnection: close\\r\\n\\r\\n')\n\nbuffer=[]\nwhile True:\n d=s.recv(1024)\n if d:\n buffer.append(d)\n else:\n break\n\ndata=b''.join(buffer)\n\ns.close()\n\nprint(data)\nheader,html=data.split(b'\\r\\n\\r\\n',1)\nwith open('sina.html','wb') as f:\n f.write(html)\n'''\n\nimport socket\nimport threading\nimport time\ns=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\ns.bind(('127.0.0.1',9999))\ns.listen(5)\n\ndef tcplink(sock,addr):\n print('Accept new connection from %s:%s...'%addr)\n sock.send(b'Welcome!')\n while True:\n data=sock.recv(1024)\n time.sleep(1)\n if not data or data.decode('utf-8')=='exit':\n break\n sock.send(('Hello,%s!'% data.decode('utf-8')).encode('utf-8'))\n print('Connection from %s:%s closed.'% addr)\n\nwhile True:\n sock,addr=s.accept()\n t=threading.Thread(target=tcplink,args=(sock,addr))\n t.start()\n\n","sub_path":"socket_tcp_server.py","file_name":"socket_tcp_server.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"143285367","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Aug 11 15:49:25 2019\r\n\r\n@author: libozhang\r\n\"\"\"\r\n\r\nimport sys,pygame\r\nfrom pygame.locals import *\r\nfrom random import randrange\r\n\r\nclass Weight(pygame.sprite.Sprite):\r\n def __init__(self,speed):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.speed=speed\r\n self.image=snake_image#使用到的图像\r\n self.rect=self.image.get_rect()\r\n self.reset()\r\n \r\n def reset(self):\r\n \"\"\"\r\n 将铅锤移到屏幕顶端的随机位置\r\n \"\"\"\r\n self.rect.top=-self.rect.height\r\n self.rect.centerx=randrange(screen_size[0])\r\n def update(self):\r\n self.rect.top+=self.speed\r\n if self.rect.top>screen_size[1]:\r\n self.reset()\r\n#初始化\r\npygame.init()\r\nscreen_size=800,600\r\npygame.display.set_mode(screen_size,FULLSCREEN)\r\npygame.mouse.set_visible(0)\r\n\r\n#加载铅锤图像\r\nsnake_image=pygame.image.load('snake.png')\r\nsnake_image=snake_image.convert()#just match screen\r\n\r\n#set speed\r\nspeed=100\r\n\r\n#创建一个对象编组,并在其中添加一个weight实例\r\n\r\nsprites=pygame.sprite.RenderUpdates()\r\nsprites.add(Weight(speed))\r\n\r\n#获取并填充屏幕表面\r\n\r\nscreen=pygame.display.get_surface()\r\nbg=(100,255,200)#随便设置了一种颜色\r\nscreen.fill(bg)\r\npygame.display.flip()\r\n\r\n#用于清除Sprites对象\r\n\r\ndef clear_callback(surf,rect):\r\n surf.fill(bg,rect)\r\n\r\nwhile True:\r\n for event in pygame.event.get():\r\n if event.type==QUIT:\r\n sys.exit()\r\n if event.type==KEYDOWN and event.key==K_ESCAPE:\r\n sys.exit()\r\n sprites.clear(screen,clear_callback)\r\n sprites.update()\r\n updates=sprites.draw(screen)\r\n pygame.display.update(updates)\r\n \r\n \r\n \r\n","sub_path":"weights.py","file_name":"weights.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"70669194","text":"class Solution:\n def maximumGap(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums)<=1:\n return 0\n \n nums = sorted(nums)\n max_gap = float('-inf')\n for i in range(1, len(nums)):\n max_gap = max(max_gap, nums[i]-nums[i-1])\n \n return max_gap\n ","sub_path":"164.py","file_name":"164.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"412259748","text":"#!/usr/bin/env python3\nimport random\nimport sys\nimport time\n\nimport requests\nimport ipaddress\nimport re\nimport json\nimport boto3\n\n\ndef read_json_file(read_file):\n with open(read_file, 'r', newline='', encoding='utf-8', errors='ignore') as file:\n return json.load(file)\n\n\ndef write_json_file(write_file, content):\n with open(write_file, 'w+', newline='', encoding='utf-8', errors='ignore') as file:\n file.write(json.dumps(content))\n\n\ndef get_public_ip():\n urls = [\"https://ident.me\", \"https://api.ipify.org\", \"https://myip.dnsomatic.com\", \"https://ipecho.net/plain\",\n \"http://checkip.dyndns.org/\", \"http://ipinfo.io/ip\", \"http://icanhazip.com\"]\n\n random.shuffle(urls)\n\n for url in urls:\n r = requests.get(url)\n if r.status_code != 200:\n continue\n\n try:\n if ipaddress.ip_address(r.text).is_global:\n return r.text\n except ValueError:\n regex = '(?:(?:1\\d\\d|2[0-5][0-5]|2[0-4]\\d|0?[1-9]\\d|0?0?\\d)\\.){3}(?:1\\d\\d|2[0-5][0-5]|2[0-4]\\d|0?[1-9]\\d|0?0?\\d)'\n found_ips = re.findall(regex, r.text)\n if not found_ips:\n continue\n ip = found_ips[0]\n\n if ipaddress.ip_address(ip).is_global:\n return ip\n else:\n continue\n\n\ndef build_record_update(record, value, ttl=30, type=\"A\"):\n return {\n 'Changes': [\n {\n 'Action': 'UPSERT',\n 'ResourceRecordSet': {\n 'Name': str(record),\n 'Type': str(type),\n 'TTL': int(ttl),\n 'ResourceRecords': [{'Value': str(value)}]\n }\n }]}\n\n\ndef update_dns_record(config, ip):\n client = boto3.client('route53', aws_access_key_id=config['access_key'], aws_secret_access_key=config['secret_key'])\n batch = build_record_update(config['zone_record'], ip)\n client.change_resource_record_sets(HostedZoneId=config['hosted_zone'], ChangeBatch=batch)\n\n\ndef record_current_ip(current_dns_records, config):\n for record in current_dns_records:\n if record['Name'].lower() == config['zone_record'].lower():\n for resource in record['ResourceRecords']:\n for k, v in resource.items():\n if k.lower() == 'value':\n return v\n else:\n return False\n\n\ndef main():\n # Load config files from file.\n config = read_json_file(\"config_clean.json\")\n\n # Build client based on config.\n client = boto3.client('route53', aws_access_key_id=config['access_key'], aws_secret_access_key=config['secret_key'])\n\n # Get external IP address.\n current_ext_ip = get_public_ip()\n\n # Get current DNS records.\n current_dns_records = client.list_resource_record_sets(HostedZoneId=config['hosted_zone'])['ResourceRecordSets']\n\n # Get current IP address of DNS entry.\n current_dns_ip = record_current_ip(current_dns_records, config)\n\n # Compare current external IP to current DNS record IP.\n if current_dns_ip == current_ext_ip:\n print(f\"Your current IP {str(current_ext_ip)} matches the current DNS IP {str(current_dns_ip)}. Nothing to do.\")\n sys.exit(2)\n\n else:\n print(\"The IPs are different, time for some updating!\")\n\n # Verifying IP change with a couple different resources.\n counter = 1\n while counter < 3:\n time.sleep(1)\n new_ip = get_public_ip()\n if current_ext_ip == new_ip:\n counter += 1\n print(f\"New IP agreed, score: {str(counter)}/3\")\n\n else:\n counter -= 1\n print(f\"New IP NOT agreed, score: {str(counter)}/3\")\n\n update_dns_record(config, current_ext_ip)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"156687742","text":"# Your Bedroom\r\n\r\n\r\ndef run():\r\n import main\r\n import variables\r\n\r\n options = {\"look around\": 1, \"look\": 1, \"check\": 1, \"leave\": 2, \"shop\": 2}\r\n option = -1\r\n\r\n print(\"What is your name?\")\r\n variables.player.name = input()\r\n print(\"How old are you?\")\r\n variables.player.age = input()\r\n\r\n while option != 0:\r\n if option == -1:\r\n print(variables.player.name + \", you wake up in a soft bed\")\r\n elif option == 1:\r\n print(\"You look around the room and see WALLS\")\r\n elif option == 2:\r\n print(\"You leave the bedroom and continue on your way.\")\r\n return 2\r\n elif option == 99:\r\n print(\"You can't do that. Try something else.\")\r\n\r\n print(\"What do you do?\")\r\n option = input()\r\n\r\n for key in options:\r\n if option in options:\r\n option = options[option]\r\n break\r\n else:\r\n option = 99\r\n","sub_path":"The_Quest_Python/your_home/your_bedroom.py","file_name":"your_bedroom.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"391283849","text":"\"\"\"\nEvennia settings file.\n\nThe full options are found in the default settings file found here:\n\n/home/mouvar/PycharmProjects/evennia/evennia/settings_default.py\n\nNote: Don't copy more from the default file than you actually intend to\nchange; this will make sure that you don't overload upstream updates\nunnecessarily.\n\n\"\"\"\n\n# Use the defaults from Evennia unless explicitly overridden\nimport os\nfrom evennia.settings_default import *\n\n######################################################################\n# Evennia base server config\n######################################################################\n\n# This is the name of your game. Make it catchy!\nSERVERNAME = \"EveMUSH\"\n\n# Path to the game directory (use EVENNIA_DIR to refer to the\n# core evennia library)\nGAME_DIR = \"/home/mouvar/PycharmProjects/evemush\"\n\n# Place to put log files\nLOG_DIR = os.path.join(GAME_DIR, \"server\", \"logs\")\nSERVER_LOG_FILE = os.path.join(LOG_DIR, 'server.log')\nPORTAL_LOG_FILE = os.path.join(LOG_DIR, 'portal.log')\nHTTP_LOG_FILE = os.path.join(LOG_DIR, 'http_requests.log')\n\n\nTELNET_PORTS = [4000]\nWEBSERVER_PORTS = [(7999, 5001)]\nWEBSOCKET_CLIENT_URL = \"ws://fubarp.crabdance.com\"\nMULTISESSION_MODE = 3\nUSE_TZ = True\nMAX_NR_CHARACTERS = 4\nIRC_ENABLED = True\n\n#IDLE_TIMEOUT = -1\n\nTELNET_OOB_ENABLED = True\n\nCONNECTION_SCREEN_MODULE = \"server.conf.connection_screens\"\nDEFAULT_HOME = \"#2\"\nSTART_LOCATION = \"#2\"\n\n# Determines whether non-admin can create characters at all.\nPLAYER_CREATE = True\n\nINSTALLED_APPS = INSTALLED_APPS + ('commands.eveadmin',\n 'commands.evegroups',\n 'commands.evebbs',\n 'commands.evedesc',\n 'commands.evepennimport',\n 'commands.eveinfo',\n 'commands.evechannels',\n 'commands.everadio',)\n\nLOCK_FUNC_MODULES = LOCK_FUNC_MODULES + (\"commands.evegroups.lockfuncs\",\n \"commands.evechannels.lockfuncs\",)\n\nCHANNEL_PUBLIC = (\"Public\", '', 'Public discussion',\n \"control:perm(Wizards);listen:all();send:all()\")\nCHANNEL_MUDINFO = (\"***Reports\", '', 'Informative messages',\n \"control:perm(Immortals);listen:perm(Wizards);send:false()\")\nCHANNEL_CONNECTINFO = (\"***Connections\", '', 'Connection log',\n \"control:perm(Immortals);listen:perm(Wizards);send:false()\")\n\nEVEMUSH_PLAYER_TYPECLASS = 'typeclasses.players.Player'\nEVEMUSH_CHARACTER_TYPECLASS = 'typeclasses.characters.Character'\n\nBASE_PLAYER_TYPECLASS = \"typeclasses.players.Player\"\nBASE_OBJECT_TYPECLASS = \"typeclasses.objects.Object\"\nBASE_CHARACTER_TYPECLASS = \"typeclasses.characters.Character\"\nBASE_ROOM_TYPECLASS = \"typeclasses.rooms.Room\"\nBASE_EXIT_TYPECLASS = \"typeclasses.exits.Exit\"\nBASE_CHANNEL_TYPECLASS = \"typeclasses.channels.Channel\"\nBASE_SCRIPT_TYPECLASS = \"typeclasses.scripts.Script\"\n\n\nCHAN_GUEST = 'Guest'\nCHAN_PUBLIC = 'Public'\nCHAN_STAFFREP = '***Reports'\nCHAN_CONNECT = '***Connections'\n\n######################################################################\n# Evennia Database config\n######################################################################\n\n# Database config syntax:\n# ENGINE - path to the the database backend. Possible choices are:\n# 'django.db.backends.sqlite3', (default)\n# 'django.db.backends.mysql',\n# 'django.db.backends.'postgresql_psycopg2' (see Issue 241),\n# 'django.db.backends.oracle' (untested).\n# NAME - database name, or path to the db file for sqlite3\n# USER - db admin (unused in sqlite3)\n# PASSWORD - db admin password (unused in sqlite3)\n# HOST - empty string is localhost (unused in sqlite3)\n# PORT - empty string defaults to localhost (unused in sqlite3)\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(GAME_DIR, \"server\", \"evennia.db3\"),\n 'USER': '',\n 'PASSWORD': '',\n 'HOST': '',\n 'PORT': ''\n }}\n\n######################################################################\n# Django web features\n######################################################################\n\n# Absolute path to the directory that holds file uploads from web apps.\n# Example: \"/home/media/media.lawrence.com\"\nMEDIA_ROOT = os.path.join(GAME_DIR, \"gamesrc\", \"web\", \"media\")\n\n# The master urlconf file that contains all of the sub-branches to the\n# applications. Change this to add your own URLs to the website.\nROOT_URLCONF = 'web.urls'\n\n# URL prefix for admin media -- CSS, JavaScript and images. Make sure\n# to use a trailing slash. Django1.4+ will look for admin files under\n# STATIC_URL/admin.\nSTATIC_URL = '/static/'\nSTATIC_ROOT = os.path.join(GAME_DIR, \"web\", \"static\")\n\n# Directories from which static files will be gathered from.\nSTATICFILES_DIRS = (\n os.path.join(GAME_DIR, \"web\", \"static_overrides\"),\n os.path.join(EVENNIA_DIR, \"web\", \"static\"),)\n\n# We setup the location of the website template as well as the admin site.\nTEMPLATE_DIRS = (\n os.path.join(GAME_DIR, \"web\", \"template_overrides\"),\n os.path.join(EVENNIA_DIR, \"web\", \"templates\", ACTIVE_TEMPLATE),\n os.path.join(EVENNIA_DIR, \"web\", \"templates\"),)\n\n# The secret key is randomly seeded upon creation. It is used to\n# salt cryptographic keys. Don't change this once you have created users\n# and don't share it with anyone.\nSECRET_KEY = 'Gul^{DgX%Zmw.)L1(N!S|6#&\",pK0x~stHf2Aa$c'\n","sub_path":"server/conf/evemush_settings.py","file_name":"evemush_settings.py","file_ext":"py","file_size_in_byte":5515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"623947264","text":"size(780,780)\nbackground(None)\nimport math\nimport pprint\n\nnofill()\nstroke(0)\nspeed(36)\n\n\ndef drawArcedCircle(x,y,r,n,s,sw,t,o):\n strokewidth(sw)\n stroke(s)\n if t < 1:\n stroke(s, t)\n nofill()\n if n == 0:\n arcsize = 360\n stepsize = 360\n else:\n stepsize = 360.0 / n\n if fractional:\n arcsize = stepsize * float(n-1) / n\n else:\n arcsize = stepsize * 3 / 4.0\n\n for i in range(n):\n start = i * stepsize + o\n end = start + arcsize\n arc(x, y, r, start, end)\n\nx, y = WIDTH / 2.0, HEIGHT / 2.0\n\n\n# fractional arc length\nfractional = False\n\n# how many rings\nringnumber = 7\n\n# a ring is divided into this many segments\nsegments = 8\n\n# width of a segment\nsegwidth = 80\n\n# gap between rings\nseggap = -32\n\nsegtotal = segwidth + seggap\nphi = 0\nphiincrement = 1 / (2**(ringnumber-1) * 0.1)\n\n# use 0.9..0.1 for color\nlightgap = 0.8 / (ringnumber-1)\n\n\na = 0.5\ndef handleAlpha(i):\n global a\n a = i\n\nvar(\"alpha\", NUMBER, 0.5, 0.01, 1.0, handler=handleAlpha)\n\n\n\nrings = [\n # (radius, speed, color)\n [ (i+1)*segtotal, 2**(ringnumber-i-1), 0.90-(i*lightgap)] for i in range(ringnumber)]\n\n\ndef draw():\n global phi\n\n background(None)\n phi = phi % 360.0\n for i,ring in enumerate(rings):\n r, spd, c = ring\n o = phi * spd\n if i % 2 == 0:\n o = -o\n drawArcedCircle(x,y,r,segments, c, segwidth, a, o)\n phi += phiincrement\n\n","sub_path":"examples/New Functions/Example arc 4.py","file_name":"Example arc 4.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"383076702","text":"# CONCATENACIÓN\n\n#MANIPULACION DE TEXTOS\n#manipulacion de texto nro 1\nnombre=\"jose\"\nescuela=\"ingeniería electrónica\"\ncurso=\"programacion\"\nfacultad=\"ciencias fisicas y matematicas\"\n#agrupacion de cadenas\nprint(nombre+\" estudia \" + curso + \" en la \" + escuela + \" en la facultad \"+facultad)\n\n#manipulacion de texto nro 2\nnombre=\"juan jose\"\napellidos=\"lozano Gomez\"\nnacimiento=25\nnombre_completo=(nombre+\" se apellidad \"+apellidos+\" nacion el \"+str(nacimiento)+\" de mayo\")\n\nprint(nombre_completo)\n\n#manipulacion de texto nro 3\nsuma=5+16\nresultado=(\"el resultado de 5+11 es :\" +str(suma))\nprint(resultado)\n\n#manipulacion de texto nro 4\nnombre=\"elmer miguel\"\nestudia=\"ingenieria electronica\"\nnota1,nota2,nota3=14,12,13\npromedio=(nota1+nota2+nota3)/3\n\nmensaje=nombre+\" estudia \"+estudia+\"y tiene un promedio de \"+str(promedio)\nprint(mensaje)\n#si el promedio es mayor que diez mostrar esta aprobado\nif (promedio>10):\n mensaje=nombre + \" ha aprobado el curso \"\nprint(mensaje)\n\n\n#manipulacion de texto nro 5\ncadena=\"jose\"\ncadena_nueva=\".\"\nwhile (cadena_nueva!=cadena):\n cadena_nueva=input(\"por favor ingrese una apellido\")\n cadena_p=cadena +\" \" + cadena_nueva\n print(cadena_p)\n\n\n#manipulacion de texto nro 6\nsuma=\"suma\"\nresta=\"resta\"\ndivision=\"division\"\nmultiplicacion=\"multiplicacion\"\nresultado=(\"son operaciones arimeticas \"+suma+\",\"+resta+\",\"+division+\",\"+multiplicacion)\nprint(resultado)\n\n#manipulacion de texto nro 7\nnombre=\"miguel\"\nescuela=\"estadistica\"\ncurso=\"poblacion y muestra\"\nfacultad=\"ciencias fisicas y matematicas\"\n#agrupacion de cadenas\nprint(nombre+\" estudia \" + curso + \" en la \" + escuela + \" en la facultad \"+facultad)\n\n#manipulacion de texto numero nro8\nnombre=\"elmer miguel\"\nestudia=\"ingenieria electronica\"\nnota1,nota2=14,12\npromedio=(nota1+nota2)/2\nmensaje=nombre+\" estudia \"+estudia+\"y tiene un promedio de \"+str(promedio)\nprint(mensaje)\n#si el promedio es menor que diez mostrar esta desaprobado\nif (promedio<10):\n mensaje=nombre + \" ha desaprobado el curso \"\nprint(mensaje)\n\n#manipulacion de texto numero nro9\n\npalabras_1=\"hola como estas?\"\npalabras_2=\"sabes te extrañado mucho.\"\npalabras_3=\"espero que te encuentres bien, muy bien. \"\n\nprint(palabras_1+\" \"+palabras_2+\" \"+palabras_3)\n\n\n#manipulacion de texto numero nro10\npromedio=(5+16+17+10)/4\nprint(\"el promedio final de un alumno es de \"+str(promedio))\n\n#manipulacion de texto numero nro11\nalumno=\"\\\"Juan Carlos\\\"\"\ncurso='\\'Base de datos\\''\nnota=18\ncondicion= \"\\\"Aprobado\\\"\"\n\n\nprint(\"El alumno\" + alumno + \" llevo el curso de \" + curso + \"\\n\" + \"y su nota es\" + str(nota) +\" , su condicion es \" + condicion)\n\n#manipulacion de texto numero nro12\n#CUIDAR EL MUNDO ES NUETRA OBLIGACION\n#concatenar la siguiente frase\n#CUIDAR EL MUNDO\n\n# 012345678901234567890123456789012345\ntexto=\"CUIDAR EL MUNDO ES NUETRA OBLIGACION\"\nmsg=texto[0:6] +\" \" +texto[7:9] +\" \" +texto[10:15]\nprint(msg)\n\n#manipulacion de texto numero nro13\n#CUIDAR EL MUNDO ES NUETRA OBLIGACION\n#concatenar la siguiente frase:\n#RADIUC LE ODNUM\n# 012345678901234567890123456789012345\ntexto=\"CUIDAR EL MUNDO ES NUETRA OBLIGACION\"\nmsg=texto[0:6:-1] +\" \" +texto[7:9:-1] +\" \" +texto[10:15:-1]\nprint(msg)\n\n#manipulacion de texto numero nro14\n#QUIEN QUIERE VIAJAR CONMIGO\n#concatenar la siguiente frase\n#QUIEN\n#QUIERE\n#VIAJAR\n# 012345678901234567890123456\ntexto=\"QUIEN QUIERE VIAJAR CONMIGO\"\nmsg=texto[0:5] +\"\\n\" +texto[6:12] +\"\\n\" +texto[13:19]\nprint(msg)\n\n#manipulacion de texto numero nro15\ncad1=\"hola\"\ncad2=\"mundo\"\nprint(cad1+\" \"+cad2)\n\n\n\n\n\n\n\n\n\n\n","sub_path":"manipuladores_de_textos/concatenacion.py","file_name":"concatenacion.py","file_ext":"py","file_size_in_byte":3511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"210156752","text":"def repeat_rows(filename=\"test.xls\", columnText=\"姓名\"):\n \"\"\"\n # 请先安装xlrd模块\n # 读取一个excel文件,找到其中某列的值重复的行\n # 比如excel文件中有一列叫做“ID”,那么这一列的值要求不重复,如果有重复的,把他们找出来\n \"\"\"\n import xlrd\n data = xlrd.open_workbook(filename)\n table = data.sheet_by_index(0)\n header = table.row_values(0) # 获取表头\n if columnText in header: index = header.index(columnText)\n else: return []\n map = {}\n for rowIndex in range(1, table.nrows):\n value = table.row_values(rowIndex)\n key = value[index]\n if not key in map: map[key] = []\n map[key].append(value)\n return [value for key, value in map.items() if len(value) > 1]\n\nif __name__ == \"__main__\":\n print(u\"重复的记录: \")\n for line in repeat_rows():\n print(line)","sub_path":"tool/excel/Util.py","file_name":"Util.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"218077685","text":"import sys\nimport numpy as np\nimport argparse\n\nfrom scipy.interpolate import griddata\nfrom core.plot import plt_saver\nfrom core.loader import DataLoader\n\nfrom hyperdash import Experiment\n\nif __name__ == \"__main__\":\n sys.path.append(\"./\")\n from models.burgers import BurgersHPM\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--niter\", default=10000, type=int)\n parser.add_argument(\"--scipyopt\", default=False)\n parser.add_argument(\"--name\", default=\"default\")\n parser.add_argument(\"--traindata\", nargs=\"+\")\n parser.add_argument(\n \"--testdata\", default=\"../MyData/burgers_polynominal.mat\")\n args = parser.parse_args()\n logname = f\"log/burgers_{args.name}.log\"\n figurename = f\"Burgers_{args.name}\"\n # filen = \"../MyData/burgers_cos.mat\"\n\n exp = Experiment(args.name)\n exp.param(\"niter\", args.niter)\n exp.param(\"scipyopt\", args.scipyopt)\n exp.param(\"testdata\", args.testdata)\n for i, n in enumerate(args.traindata):\n exp.param(f\"traindata{i}\", n)\n\n dataloader = DataLoader(args.traindata, args.testdata, 10.0, 8.0)\n sol_data = dataloader.get_solver_data(20000)\n idn_data = dataloader.get_train_batch()\n\n u_layers = [[2, 50, 50, 50, 50, 1] for _ in range(len(args.traindata))]\n pde_layers = [3, 100, 100, 1]\n layers = [2, 50, 50, 50, 50, 1]\n\n idn_lbs = idn_data[\"idn_lbs\"]\n idn_ubs = idn_data[\"idn_ubs\"]\n train_ts = idn_data[\"train_ts\"]\n train_xs = idn_data[\"train_xs\"]\n train_us = idn_data[\"train_us\"]\n\n train_x0 = sol_data[\"train_x0\"]\n train_u0 = sol_data[\"train_u0\"]\n sol_lb = sol_data[\"sol_lb\"]\n sol_ub = sol_data[\"sol_ub\"]\n train_tb = sol_data[\"train_tb\"]\n train_X_f = sol_data[\"train_X_f\"]\n\n model = BurgersHPM(idn_lbs, idn_ubs, sol_lb, sol_ub, train_ts, train_xs,\n train_us, train_tb, train_x0, train_u0, train_X_f,\n layers, u_layers, pde_layers, logname)\n model.train_idn(args.niter, \"model/saved.model\", args.scipyopt)\n\n # idn_t_stars = idn_data[\"idn_t_stars\"]\n # idn_x_stars = idn_data[\"idn_x_stars\"]\n # idn_u_stars = idn_data[\"idn_u_stars\"]\n\n # idn_u_preds, idn_f_preds = model.idn_predict(idn_t_stars, idn_x_stars)\n # idn_error_us = [\n # np.linalg.norm(star - pred, 2) / np.linalg.norm(star, 2)\n # for star, pred in zip(idn_u_stars, idn_u_preds)\n # ]\n # for i, e in enumerate(idn_error_us):\n # model.logger.info(f\"Data{i} Error u: {e:.3e}\")\n\n sol_t_star = sol_data[\"sol_t_star\"]\n sol_x_star = sol_data[\"sol_x_star\"]\n sol_u_star = sol_data[\"sol_u_star\"]\n\n model.train_solver(args.niter * 2, args.scipyopt)\n u_pred, f_pred = model.solver_predict(sol_t_star, sol_x_star)\n error_u = np.linalg.norm(sol_u_star - u_pred, 2) / np.linalg.norm(\n sol_u_star, 2)\n model.logger.info(f\"Error u: {error_u:.3e}\")\n exp.metric(\"Error u\", error_u)\n\n sol_X_star = sol_data[\"sol_X_star\"]\n sol_T = sol_data[\"sol_T\"]\n sol_X = sol_data[\"sol_X\"]\n sol_exact = sol_data[\"sol_exact\"]\n U_pred = griddata(\n sol_X_star, u_pred.flatten(), (sol_T, sol_X), method=\"cubic\")\n plt_saver(U_pred, sol_exact, sol_lb, sol_ub, figurename)\n exp.end()\n","sub_path":"Mine/multiple_burgers.py","file_name":"multiple_burgers.py","file_ext":"py","file_size_in_byte":3195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"106729645","text":"import os\nimport sys\n\nfrom flask import Flask, jsonify, make_response, redirect, request\nfrom flask_cors import CORS\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\napplication = Flask(__name__)\nCORS(application)\n\napplication.debug = True\n\nif os.environ.get('ENV') is None:\n application.debug = True\nelif os.environ.get('ENV') == 'prod':\n application.debug = False\n\n\n@application.route('/test')\ndef health():\n return \"Success\"\n\nif __name__ == '__main__':\n application.run(host=\"0.0.0.0\", port=5000)\n","sub_path":"ml-api/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"204752216","text":"import util\nfrom googLeNet import googLeNet_official\nimport torch\nfrom PIL import Image\nimport torch.nn as nn\nfrom torch.optim import lr_scheduler\nfrom torchvision import datasets, models, transforms\nimport time\nimport os\nimport copy\nimport constant\nimport resnet\nimport matplotlib.pyplot as plt\nfrom torch.autograd import Variable\nimport numpy as np\nimport dataAnalyze\nimport cv2\n\n\ndef resNet_valuate(data_loader, dataset, use_gpu, is_image_gray=True, model_name=\"resNet\"):\n model = generate_resnet_model(is_image_gray, use_gpu)\n\n map_location = torch.device('cpu')\n if use_gpu:\n map_location = None\n model.load_state_dict(\n torch.load(constant.cache_dir + 'trained_{}.pkl'.format(model_name), map_location=map_location))\n model.eval()\n\n valuate_model(data_loader, dataset, model, use_gpu)\n\n\ndef valuate_model(data_loader, dataset, model, use_gpu):\n since = time.time()\n # 数据类别\n class_names = dataset.classes\n softmax = nn.Softmax(dim=1)\n results = []\n signs = []\n aux_weight1 = 0.2\n aux_weight2 = 0.2\n\n for i, data in enumerate(data_loader):\n if i % 10 == 0:\n print(\"loop {} in {}\".format(i, int(len(dataset) / data_loader.batch_size)))\n # 获取输入\n inputs, labels = data\n if use_gpu:\n inputs = inputs.cuda()\n labels = labels.cuda()\n with torch.no_grad():\n if model.use_aux_classify:\n outputs, aux_output1 ,aux_output2= model(inputs)\n # aux_output1, aux_output2 = aux_outputs\n # print(\"valuate outputs = {}\\naux_outputs = {}\".format(outputs, aux_outputs))\n results = np.concatenate((results, (1 - aux_weight1 - aux_weight2) *\n softmax(outputs).cpu().data.T[1].numpy() +\n aux_weight1 * softmax(aux_output1).cpu().data.T[1].numpy() +\n aux_weight2 * softmax(aux_output2).cpu().data.T[1].numpy()))\n else:\n outputs = model(inputs)\n results = np.concatenate((results, softmax(outputs).cpu().data.T[1].numpy()))\n signs = np.concatenate((signs, labels.cpu().data.numpy()))\n precision, recall, threshold = dataAnalyze.compute_precision_recall_curve(signs.flatten(),\n results.flatten())\n # print(\"precision:\", precision, \"\\nrecall:\", recall, \"\\nthreshold:\", threshold)\n # util.save_pr_csv_data(signs, results, precision, recall, threshold, \"test\")\n # print(\"results: {}\\nsigns: {}\".format(results, signs))\n average_precision = dataAnalyze.compute_average_precision(signs.flatten(),\n results.flatten())\n print(\"average_precision: {}\".format(average_precision))\n time_elapsed = time.time() - since\n print('avgtime',time_elapsed/500)\n dataAnalyze.show_precision_recall_curve_image(precision, recall, average_precision, \"Test PR Curve\")\n\n\n# 训练与验证网络(所有层都参加训练)\ndef train_model(model, data_loaders, dataset_sizes, use_gpu, criterion, optimizer, scheduler, num_epochs=25):\n since = time.time()\n # 保存网络训练最好的权重\n best_model_wts = copy.deepcopy(model.state_dict())\n best_acc = 0.0\n loss_history = {x: [] for x in ['train', 'val']}\n counter = {x: [] for x in ['train', 'val']}\n iteration_number = {x: 0 for x in ['train', 'val']}\n\n aux_weight1 = 0.2\n aux_weight2 = 0.2\n aux_outputs = None\n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch, num_epochs - 1))\n print('-' * 10)\n # 每训练一个epoch,测试一下网络模型的准确率\n for phase in ['train', 'val']:\n if phase == 'train':\n # 梯度清零\n optimizer.zero_grad()\n # 学习率更新方式\n if epoch > 0:\n scheduler.step()\n # 调用模型训练\n model.train(True)\n else:\n # 调用模型测试\n model.train(False)\n model.eval()\n\n running_loss = 0.0\n running_corrects = 0\n\n softmax = nn.Softmax(dim=1)\n results = []\n signs = []\n\n # 依次获取所有图像,参与模型训练或测试\n for i, data in enumerate(data_loaders[phase]):\n # 获取输入\n inputs, labels = data\n # 判断是否使用gpu\n if use_gpu:\n inputs = inputs.cuda()\n labels = labels.cuda()\n\n # 梯度清零\n optimizer.zero_grad()\n\n # 网络前向运行\n if model.use_aux_classify:\n outputs, aux_output1, aux_output2= model(inputs)\n # aux_output1, aux_output2 = aux_outputs\n # 计算Loss值\n loss = criterion(outputs, labels)\n aux_loss1 = criterion(aux_output1, labels)\n aux_loss2 = criterion(aux_output2, labels)\n loss = (1 - aux_weight1 - aux_weight2) * loss + aux_weight1 * aux_loss1 + aux_weight2 * aux_loss2\n else:\n outputs = model(inputs)\n # 计算Loss值\n loss = criterion(outputs, labels)\n\n _, preds = torch.max(outputs.data, 1)\n\n # 反传梯度,更新权重\n if phase == 'train':\n # 反传梯度\n loss.backward()\n # 更新权重\n optimizer.step()\n\n # 计算一个epoch的loss值和准确率\n running_loss += loss.item() * inputs.size(0)\n running_corrects += torch.sum(preds == labels.data)\n if i % 10 == 0:\n iteration_number[phase] += 10\n counter[phase].append(iteration_number[phase])\n loss_history[phase].append(loss.item())\n # if epoch == num_epochs - 1:\n result_np = softmax(outputs).cpu().data.T[1].numpy()\n if model.use_aux_classify:\n # aux_output1, aux_output2 = aux_outputs\n results = np.concatenate((results, (1 - aux_weight1 - aux_weight2) * result_np +\n aux_weight1 * softmax(aux_output1).cpu().data.T[1].numpy() +\n aux_weight2 * softmax(aux_output2).cpu().data.T[1].numpy()))\n else:\n results = np.concatenate((results, result_np))\n signs = np.concatenate((signs, labels.cpu().data.numpy()))\n\n precision, recall, threshold = dataAnalyze.compute_precision_recall_curve(signs.flatten(),\n results.flatten())\n if epoch == num_epochs - 1:\n util.save_pr_csv_data(signs, results, precision, recall, threshold, phase)\n # print(\"precision:\", precision, \"\\nrecall:\", recall, \"\\nthreshold:\", threshold)\n # print(\"{} results: {}\\nsigns: {}\".format(phase, results, signs))\n average_precision = dataAnalyze.compute_average_precision(signs.flatten(),\n results.flatten())\n print(\"{} average_precision: {}\".format(phase, average_precision))\n dataAnalyze.save_precision_recall_curve_image(precision, recall, average_precision,\n phase + \" PR Curve_\" + str(epoch))\n\n # 计算Loss和准确率的均值\n epoch_loss = running_loss / dataset_sizes[phase]\n epoch_acc = float(running_corrects) / dataset_sizes[phase]\n\n print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc))\n\n # 保存测试阶段,准确率最高的模型\n if phase == 'val' and epoch_acc > best_acc:\n best_acc = epoch_acc\n best_model_wts = copy.deepcopy(model.state_dict())\n dataAnalyze.save_loss_plot(counter[phase], loss_history[phase], \"loss_\" + phase + \"_\" + str(epoch))\n\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(\n time_elapsed // 60, time_elapsed % 60))\n print('Best val Acc: {:4f}'.format(best_acc))\n # 网络导入最好的网络权重\n # model.load_state_dict(best_model_wts)\n return model\n\n\ndef alexNet_train(use_gpu):\n # 导入Pytorch封装的AlexNet网络模型\n model = models.alexnet(pretrained=True)\n # 获取最后一个全连接层的输入通道数\n num_input = model.classifier[6].in_features\n # 获取全连接层的网络结构\n feature_model = list(model.classifier.children())\n feature_model.pop()\n # 添加上适用于自己数据集的全连接层\n feature_model.append(nn.Linear(num_input, 2))\n # 仿照这里的方法,可以修改网络的结构,不仅可以修改最后一个全连接层\n # 还可以为网络添加新的层\n # 重新生成网络的后半部分\n model.classifier = nn.Sequential(*feature_model)\n if use_gpu:\n model = model.cuda()\n # 定义损失函数\n criterion = nn.CrossEntropyLoss()\n # 为不同层设定不同的学习率\n fc_params = list(map(id, model.classifier[6].parameters()))\n base_params = filter(lambda p: id(p) not in fc_params, model.parameters())\n params = [{\"params\": base_params, \"lr\": 0.0001},\n {\"params\": model.classifier[6].parameters(), \"lr\": 0.001}, ]\n optimizer_ft = torch.optim.SGD(params, lr=1e-4)\n # 定义学习率的更新方式,每5个epoch修改一次学习率\n exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=5, gamma=0.1)\n model = train_model(model, criterion, optimizer_ft, exp_lr_scheduler, num_epochs=10)\n torch.save(model.state_dict(), constant.cache_dir + \"model_AlexNet.pkl\")\n # visualize_model(model)\n\n\ndef googLeNet_train(use_gpu):\n model = googLeNet_official.googlenet(pretrained=False, init_weights=True, num_classes=17)\n\n if use_gpu:\n model = model.cuda()\n # 定义损失函数\n criterion = nn.CrossEntropyLoss()\n\n # # 为不同层设定不同的学习率\n # fc_params = list(map(id, model.classifier[6].parameters()))\n # base_params = filter(lambda p: id(p) not in fc_params, model.parameters())\n # params = [{\"params\": base_params, \"lr\": 0.0001},\n # {\"params\": model.classifier[6].parameters(), \"lr\": 0.001}, ]\n params = model.parameters()\n optimizer_ft = torch.optim.SGD(params, lr=1e-4)\n\n # 定义学习率的更新方式,每5个epoch修改一次学习率\n exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=5, gamma=0.1)\n model = train_model(model, criterion, optimizer_ft, exp_lr_scheduler, num_epochs=10)\n torch.save(model.state_dict(), constant.cache_dir + \"model_googLeNet.pkl\")\n\n\ndef resNet_train(data_loaders, dataset_sizes, gray_image, use_gpu, num_epochs=50, model_name=\"resNet\"):\n model = generate_resnet_model(gray_image, use_gpu)\n\n criterion = nn.CrossEntropyLoss()\n\n # Observe that all parameters are being optimized\n optimizer_ft = torch.optim.SGD(model.parameters(), lr=0.001, momentum=0.9)\n exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=5, gamma=0.1)\n model = train_model(model, data_loaders, dataset_sizes, use_gpu, criterion, optimizer_ft, exp_lr_scheduler,\n num_epochs)\n torch.save(model.state_dict(), constant.cache_dir + \"trained_{}.pkl\".format(model_name))\n # visualize_model(model)\n\n\ndef generate_resnet_model(gray_image, use_gpu):\n model = models.resnet18(pretrained=True)\n # model = AuxResnet.resnet18(pretrained=True)\n # model = resnet.resnet18(pretrained=False)\n \"\"\"\n # 获取最后一个全连接层的输入通道数\n num_input = model.classifier[6].in_features\n # 获取全连接层的网络结构\n feature_model = list(model.classifier.children())\n # 去掉原来的最后一层\n feature_model.pop()\n # 添加上适用于自己数据集的全连接层\n feature_model.append(nn.Linear(num_input, 2))\n # 仿照这里的方法,可以修改网���的结构,不仅可以修改最后一个全连接层,还可以为网络添加新的层,重新生成网络的后半部分\n model.classifier = nn.Sequential(*feature_model)\n \"\"\"\n num_ftrs = model.fc.in_features\n model.fc = nn.Linear(num_ftrs, 17)\n if gray_image:\n model.conv1 = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=False)\n edit_resnet(gray_image, model)\n # print(\"model: \", model)\n if use_gpu:\n model = model.cuda()\n return model\n\n\ndef edit_resnet(gray_image, model):\n if gray_image:\n model.conv1 = nn.Conv2d(1, 64, kernel_size=3, stride=1, padding=1, bias=False)\n else:\n model.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)\n # del model.maxpool\n # num_in = model.maxpool.in_features\n # print(\"num_in = \", num_in)\n # model.maxpool = nn.Conv2d(64, 64, kernel_size=1, bias=False)\n\n\ndef prepare_train_data(gray_image, data_dir):\n data_transforms = get_data_transforms(gray_image)\n # 这种数据读取方法,需要有train和val两个文件夹,每个文件夹下一类图像存在一个文件夹下\n image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x]) for x in ['train', 'val']}\n data_loaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=15, shuffle=True, num_workers=4) for x\n in\n ['train', 'val']}\n # 读取数据集大小\n dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}\n # 数据类别\n class_names = image_datasets['train'].classes\n return data_loaders, dataset_sizes\n\n\ndef prepare_valuate_data(gray_image, data_dir):\n data_transforms = get_data_transforms(gray_image)\n image_dataset = datasets.ImageFolder(data_dir, data_transforms[\"val\"])\n data_loader = torch.utils.data.DataLoader(image_dataset, batch_size=15, shuffle=True, num_workers=4)\n return data_loader, image_dataset\n\n\ndef get_data_transforms(gray_image):\n resize_value = 128\n # 数据预处理\n data_transforms = {\n 'train': transforms.Compose([\n transforms.Resize(resize_value),\n # transforms.Resize((32,32)),\n # 随机在图像上裁剪出224*224大小的图像\n # transforms.RandomResizedCrop(224),\n transforms.RandomCrop(resize_value),\n transforms.Grayscale(1) if gray_image else transforms.Grayscale(3),\n # 将图像随机翻转\n # transforms.RandomHorizontalFlip(),\n # 将图像数据,转换为网络训练所需的tensor向量\n transforms.ToTensor(),\n # 图像归一化处理\n # 个人理解,前面是3个通道的均值,后面是3个通道的方差\n # transforms.Normalize([0.485, ], [0.229, ]) if gray_image else transforms.Normalize([0.485, 0.456, 0.406],\n # [0.229, 0.224, 0.225])\n ]),\n 'val': transforms.Compose([\n transforms.Resize(resize_value),\n # transforms.CenterCrop(224),\n transforms.RandomCrop(resize_value),\n transforms.Grayscale(1) if gray_image else transforms.Grayscale(3),\n transforms.ToTensor(),\n # transforms.Normalize([0.485, ], [0.229, ]) if gray_image else transforms.Normalize([0.485, 0.456, 0.406],\n # [0.229, 0.224, 0.225])\n ]),\n }\n return data_transforms\n\n\ndef train(data_dir, num_epochs):\n # 是否使用gpu运算\n use_gpu = torch.cuda.is_available()\n # 是否灰度图\n gray_image = True\n data_loaders, dataset_sizes = prepare_train_data(gray_image, data_dir)\n resNet_train(data_loaders, dataset_sizes, gray_image, use_gpu, num_epochs, \"flowers17\")\n\n\ndef valuate(data_dir, is_image_gray):\n # 是否使用gpu运算\n use_gpu = torch.cuda.is_available()\n data_loader, image_dataset = prepare_valuate_data(is_image_gray, data_dir)\n resNet_valuate(data_loader, image_dataset, use_gpu, is_image_gray, \"flowers17\")\n\n\nif __name__ == '__main__':\n\n train(r\"E:\\img_data\\Resnxt\\cnn_flowers17\", 15)\n # valuate(r\"D:\\img_data\\CNN2\\test\",True)\n\n","sub_path":"CNNProcess.py","file_name":"CNNProcess.py","file_ext":"py","file_size_in_byte":16787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"145697935","text":"'''\nGiven a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.\n\nNote that it is the kth smallest element in the sorted order, not the kth distinct element.\n\nExample:\n\nmatrix = [\n [ 1, 5, 9],\n [10, 11, 13],\n [12, 13, 15]\n],\nk = 8,\n\nreturn 13.\nNote: \nYou may assume k is always valid, 1 ≤ k ≤ n2.\n'''\nclass Solution(object):\n def kthSmallest(self, matrix, k):\n \"\"\"\n :type matrix: List[List[int]]\n :type k: int\n :rtype: int\n \"\"\"\n import heapq\n if not matrix:\n return 0\n heap = []\n row = len(matrix)\n col = len(matrix[0])\n for i in range(col):\n heapq.heappush(heap, (matrix[0][i], 0, i))\n for j in range(k-1):\n curt = heapq.heappop(heap)\n x = curt[1]\n y = curt[2]\n if x+1 < row:\n heapq.heappush(heap, (matrix[x+1][y], x+1, y))\n return heap[0][0]","sub_path":"378 Kth Smallest Element in a Sorted Matrix.py","file_name":"378 Kth Smallest Element in a Sorted Matrix.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"392406245","text":"# -*- coding: utf-8 -*-\n\nimport pymongo\n\nfrom collections import MutableMapping\n\nclass db_base(pymongo.collection.Collection):\n COLLECTION_NAME = '_id'\n SEQUENCE = '_seq'\n NOT_EXIST_SEQ_ID = -1\n\n def __init__(self, mongo_client_uri, db_name, collection_name, has_seq, index_col_list=None, codec_options=None, read_preference=None, write_concern=None, read_concern=None, **kwargs):\n self._has_seq = has_seq\n self._collection_name = collection_name\n\n mongo_client = pymongo.MongoClient(mongo_client_uri)\n\n self._db = mongo_client.get_database(db_name)\n super(db_base, self).__init__(self._db, collection_name, False, codec_options, read_preference, write_concern, read_concern, **kwargs)\n\n if index_col_list is None:\n index_col_list = []\n else:\n index_col_list = list(index_col_list)\n\n if not isinstance(index_col_list, (list, tuple)):\n raise ValueError('Column to make index must be list or tuple.')\n \n if collection_name not in self._db.collection_names() and has_seq:\n self._db.counter.insert({ db_base.COLLECTION_NAME: collection_name, db_base.SEQUENCE: 0 })\n\n if has_seq:\n index_col_list.append(db_base.SEQUENCE)\n \n self.create_index([(column, pymongo.DESCENDING) for column in index_col_list], unique=True)\n\n def insert_one(self, document, bypass_document_validation=False):\n inserted_seq_id = db_base.NOT_EXIST_SEQ_ID\n\n if self._has_seq:\n if db_base.SEQUENCE in document:\n raise ValueError('Remove _seq field to add sequence id.')\n\n document[db_base.SEQUENCE] = self._next_seq(self.name)\n inserted_seq_id = document[db_base.SEQUENCE]\n\n result = super(db_base, self).insert_one(document, bypass_document_validation)\n \n return ExtendedInsertOneResult(result.inserted_id, result.acknowledged, inserted_seq_id)\n\n def insert_many(self, documents, ordered=True, bypass_document_validation=False):\n inserted_seq_ids = []\n\n for document in documents:\n if self._has_seq:\n if db_base.SEQUENCE in document:\n raise ValueError('Remove _seq field to add sequence id.')\n\n document[db_base.SEQUENCE] = self._next_seq(self.name)\n inserted_seq_ids.append(document[db_base.SEQUENCE])\n else:\n inserted_seq_ids.append(db_base.NOT_EXIST_SEQ_ID)\n\n result = super(db_base, self).insert_many(documents, ordered, bypass_document_validation)\n \n return ExtendedInsertManyResult(result.inserted_ids, result.acknowledged, inserted_seq_ids)\n\n def drop(self):\n self._db.counter.delete_many({ '_id': self._collection_name })\n return super(db_base, self).drop()\n\n def cursor_limit(self, cursor, limit=None, limit_default=None):\n if (isinstance(limit, (int, long)) ^ (limit is None)) and (isinstance(limit_default, (int, long)) ^ (limit_default is None)):\n if limit is not None:\n return cursor.limit(limit)\n elif limit_default is not None:\n return cursor.limit(limit_default)\n else:\n return cursor\n else:\n raise ValueError('Either limit default and limit must be integer or None to present \"not set\".')\n\n\n def _next_seq(self, collection_name):\n ret = self._db.counter.find_one_and_update({ db_base.COLLECTION_NAME: collection_name }, { '$inc': { db_base.SEQUENCE: 1 }}, None, None, True, pymongo.ReturnDocument.AFTER)\n return ret[db_base.SEQUENCE]\n\nclass dict_like_mapping(MutableMapping):\n def __init__(self, org_dict):\n if org_dict is None:\n self._dict = {}\n else:\n self._dict = dict(org_dict)\n\n def __getitem__(self, key):\n return self._dict[key]\n\n def __setitem__(self, key, value):\n self._dict[key] = value\n\n def __delitem__(self, key):\n del self._dict[key]\n\n def __iter__(self):\n return iter(self._dict)\n\n def __len__(self):\n return len(self._dict)\n\n def __repr__(self):\n return str(self._dict)\n\nclass ExtendedInsertOneResult(pymongo.results.InsertOneResult):\n def __init__(self, inserted_id, acknowledged, seq_id=None):\n if seq_id is None:\n self._seq_id = db_base.NOT_EXIST_SEQ_ID\n else:\n self._seq_id = seq_id\n\n super(ExtendedInsertOneResult, self).__init__(inserted_id, acknowledged)\n\n @property\n def inserted_seq_id(self):\n return self._seq_id\n\nclass ExtendedInsertManyResult(pymongo.results.InsertManyResult):\n def __init__(self, inserted_ids, acknowledged, inserted_seq_ids=None):\n if inserted_seq_ids is None:\n self._seq_ids = [db_base.NOT_EXIST_SEQ_ID for i in range(len(inserted_ids))]\n else:\n self._seq_ids = inserted_seq_ids\n \n return super(ExtendedInsertManyResult, self).__init__(inserted_ids, acknowledged)\n\n @property\n def inserted_seq_ids(self):\n return self._seq_ids\n","sub_path":"db/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"332780433","text":"import json\nimport asyncio\nimport pathlib\nfrom os import path\nfrom typing import List\nfrom collections import defaultdict\n\nimport aiohttp\nimport aioredis\nfrom pydantic import ValidationError\nfrom sqlalchemy.dialects.mysql import insert\n\nfrom app.core import config\nfrom app.db.mysql import database\nfrom app.db.utils import preserve_fields\nfrom app.db_models import sa\nfrom app.video_website_spider import SupportWebsite\nfrom data_manager.models.bangumi_data import Item\n\nbase_dir = pathlib.Path(path.dirname(__file__))\n\n\nasync def save_bangumi_data_to_db(redis):\n container = defaultdict(list)\n data: List[Item] = []\n async with aiohttp.ClientSession() as session:\n async with session.get(\n \"https://cdn.jsdelivr.net/npm/bangumi-data@0.3.x/dist/data.json\"\n ) as response:\n server_data = await response.json()\n\n for item in server_data[\"items\"]:\n try:\n data.append(Item.parse_obj(item))\n except ValidationError as e:\n print(item)\n print(e)\n\n for item in data:\n site_bangumi = [site for site in item.sites if site.site == \"bangumi\"]\n\n if site_bangumi:\n site_bangumi = site_bangumi[0]\n else:\n continue\n\n subject_id = int(site_bangumi.id)\n\n for site in item.sites:\n if not site.id:\n continue\n if site.site == SupportWebsite.bilibili:\n try:\n container[SupportWebsite.bilibili].append(\n {\n \"subject_id\": subject_id,\n \"media_id\": int(site.id),\n \"season_id\": await get_season_id(\n redis, session, site.id\n ),\n \"title\": item.name_cn,\n }\n )\n except KeyError:\n pass\n elif site.site == SupportWebsite.iqiyi:\n container[SupportWebsite.iqiyi].append(\n {\n \"subject_id\": subject_id,\n \"bangumi_id\": site.id,\n \"title\": item.name_cn,\n }\n )\n\n for key, value in container.items():\n print(key, len(value))\n\n # print(len(container[SupportWebsite.bilibili]))\n await insert_bilibili_bangumi(database, container[SupportWebsite.bilibili])\n await insert_iqiyi_bangumi(database, container[SupportWebsite.iqiyi])\n\n\nasync def save_patch_to_db():\n with open(base_dir / \"patch.json\", encoding=\"utf-8\") as f:\n d = json.load(f)\n\n await insert_bilibili_bangumi(\n database,\n [\n {\n \"subject_id\": int(x[\"subject_id\"]),\n \"media_id\": x[\"season_id\"],\n \"season_id\": x[\"season_id\"],\n \"title\": x.get(\"title\", \"\"),\n }\n for x in d[SupportWebsite.bilibili]\n ],\n )\n\n await insert_iqiyi_bangumi(\n database,\n [\n {\n \"subject_id\": int(x[\"subject_id\"]),\n \"bangumi_id\": x[\"bangumi_id\"],\n \"title\": x.get(\"title\", \"\"),\n }\n for x in d[SupportWebsite.iqiyi]\n ],\n )\n\n\nasync def insert_bilibili_bangumi(db, values):\n insert_stmt = insert(sa.BangumiBilibili)\n query = insert_stmt.on_duplicate_key_update(\n **preserve_fields(insert_stmt, \"title\", \"season_id\", \"media_id\"),\n )\n await db.execute_many(query, values)\n\n\nasync def insert_iqiyi_bangumi(db, values):\n insert_stmt = insert(sa.BangumiIqiyi)\n query = insert_stmt.on_duplicate_key_update(\n **preserve_fields(insert_stmt, \"title\", \"bangumi_id\"),\n )\n await db.execute_many(query, values)\n\n\nasync def get_season_id(\n redis_client: aioredis.Redis, session: aiohttp.ClientSession, media_id,\n):\n r = await redis_client.get(f\"bilibili:initial_state:media_id:{media_id}\")\n if r:\n return int(r)\n async with session.get(\n f\"https://bangumi.bilibili.com/view/web_api/media?media_id={media_id}\"\n ) as r:\n season_id = (await r.json())[\"result\"][\"param\"][\"season_id\"]\n await redis_client.set(\n f\"bilibili:initial_state:media_id:{media_id}\", str(season_id)\n )\n return season_id\n\n\nasync def main():\n redis_client = await aioredis.create_redis_pool(\n address=config.REDIS_URI, password=config.REDIS_PASSWORD,\n )\n await database.connect()\n await asyncio.gather(save_bangumi_data_to_db(redis_client), save_patch_to_db())\n await database.disconnect()\n\n\nif __name__ == \"__main__\": # pragma: no cover\n loop = asyncio.get_event_loop()\n loop.run_until_complete(main())\n print(\"exit\")\n","sub_path":"data_manager/save_patch_and_bangumi_data_to_db.py","file_name":"save_patch_and_bangumi_data_to_db.py","file_ext":"py","file_size_in_byte":4921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"576081339","text":"import conditions\nfrom conditions import Action\nfrom random import randint\nfrom random import random\nfrom constants import *\n\nclass Strategy:\n\n # self.conds is the list of this strategy's condition rules.\n\n def __init__(self, n=3, parent1 = None, parent2 = None):\n\n self.conds = []\n\n # If no parents, then create a random strategy.\n if parent1 == None or parent2 == None:\n num_conds = randint(1,n)\n for i in range(0,num_conds):\n self.conds.append(conditions.gen_random_condition())\n \n # Else do recombination\n else:\n if len(parent1.conds) <= 0:\n num_from_p1 = 0\n else:\n num_from_p1 = randint(0, len(parent1.conds))\n if len(parent2.conds) <= 0:\n num_from_p2 = 0\n else:\n num_from_p2 = randint(0, len(parent2.conds))\n\n p1_rules = parent1.conds[:num_from_p1]\n p2_rules = parent2.conds[:num_from_p2]\n\n longer = max(p1_rules, p2_rules, key=len)\n shorter = min(p2_rules, p1_rules, key=len)\n\n for i in range(0, len(shorter)):\n if not (shorter[i] in longer):\n longer.insert(2*i+1, shorter[i])\n\n self.conds = longer[:RULE_CAP]\n\n if random() < MUTATE_CHANCE:\n self.mutate()\n\n def __call__(self, own_moves, opp_moves):\n\n for rule in self.conds:\n move = rule(own_moves, opp_moves)\n if move != None:\n return move\n else:\n pass\n return Action(Action.C)\n\n def next_move(self, own_moves, opp_moves):\n return self(own_moves, opp_moves)\n\n def __repr__(self):\n cond_strings = map(lambda x: repr(x), self.conds)\n return \"\\n\".join(cond_strings)\n\n def mutate(self):\n # adding a rule\n if len(self.conds) <= 1:\n i = 0\n else:\n i = randint(0, len(self.conds)-1)\n def add_r():\n rule = conditions.gen_random_condition()\n self.conds.insert(i, rule)\n # deleting a rule\n def del_r():\n if self.conds != []:\n del self.conds[i]\n # swapping two rules in order\n def swap_r():\n if len(self.conds) <= 1:\n return\n else:\n i2 = randint(0, len(self.conds)-1)\n tmp = self.conds[i]\n self.conds[i] = self.conds[i2]\n self.conds[i2] = tmp\n roll = random()\n if roll < MUTATE_ADD_CHANCE:\n add_r()\n elif roll < MUTATE_ADD_CHANCE + MUTATE_DEL_CHANCE:\n del_r()\n else:\n swap_r()\n\n def delete(self, n=0):\n return self.conds.pop(n)\n\n def add(self, rule, n=0):\n self.conds.insert(n, rule)\n","sub_path":"strategies.py","file_name":"strategies.py","file_ext":"py","file_size_in_byte":2860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"606262946","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'rentals.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n \n #url(r'^list/$', 'renters.views.list', name='list'),\n #url(r'^$', include('renters.urls')),\n #url(r'^renter/$', 'renters.views.renter'),\n url(r'^admin/', include(admin.site.urls)),\n url(r'', include('renters.urls')),\n)\n","sub_path":"rentals/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"491768757","text":"#! /usr/bin/env python\nimport sys\ndef fib(n:int) -> int:\n if n==0: return 0\n if n==1: return 1\n else :\n return fib(n-1)+fib(n-2)\n\nn = int(sys.argv[1])\nprint(fib(n))\n","sub_path":"fibo.py","file_name":"fibo.py","file_ext":"py","file_size_in_byte":185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"252817247","text":"import pytest\nfrom geminidr.core.primitives_calibdb import _update_datalab\n\n\n@pytest.fixture()\ndef ad(astrofaker):\n return astrofaker.create('NIRI', 'IMAGE')\n\n\ndef test_update_datalab(ad):\n kw_lut = {'DATALAB': 'comment'}\n kw_datalab = ad._keyword_for('data_label')\n orig_datalab = 'GN-2001A-Q-9-52-001'\n ad.phu[kw_datalab] = orig_datalab\n _update_datalab(ad, '_flat', kw_lut)\n assert ad.phu[kw_datalab] == orig_datalab + '_flat'\n _update_datalab(ad, '_flat', kw_lut)\n assert ad.phu[kw_datalab] == orig_datalab + '_flat'\n _update_datalab(ad, '_bias', kw_lut)\n assert ad.phu[kw_datalab] == orig_datalab + '_bias'\n","sub_path":"geminidr/core/tests/test_calibdb.py","file_name":"test_calibdb.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"581980260","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('post_item', '0002_auto_20150105_0210'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='bid',\n name='id',\n ),\n migrations.AddField(\n model_name='bid',\n name='bid_no',\n field=models.AutoField(default=-1, serialize=False, primary_key=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='bid',\n name='post_date',\n field=models.DateTimeField(default=datetime.datetime(2015, 1, 8, 2, 44, 22, 417887, tzinfo=utc), auto_now_add=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='item',\n name='post_date',\n field=models.DateTimeField(default=datetime.datetime(2015, 1, 8, 2, 44, 22, 417278, tzinfo=utc), verbose_name=b'Date Posted ', auto_now_add=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"post_item/migrations/0003_auto_20150108_0244.py","file_name":"0003_auto_20150108_0244.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"315749124","text":"# coding: utf-8\n\nimport sys\n#sys.path.append('/Users/PP/Documents/eclipse/giant')\nsys.path.append('/home/vinzor/giant')\nfrom giant.user import RUser_info, SUser_info\nfrom giant.ceph import Ceph_User_Info, Ceph_Pool_Info\n#from libs.message.message import LocalMessage\nimport libs.message.local_message\n\n\n\n\nclass Manage_api(object):\n \n def __init__(self):\n self.mes = libs.message.local_message.LocalMessage()\n\n \n \n \n def Create_Ceph_User(self, user_id=None, display_name=None, email=None, suspended=None, max_buckets=None, auid=None,\n subusers=None, keys=None, swift_keys=None, caps=None, op_mask=None, system=None,\n default_placement=None, placement_tags=None, bucket_quota=None, user_quota=None, temp_url_keys=None,\n manager=None, **kwargs):\n '''\n 1\n '''\n response = self.mes.send(api='Create_Ceph_User', \n user_id=user_id, \n display_name=display_name,\n email=email)\n return response\n '''\n if response['Cep_User_Info'] is not None:\n ceph_user_info = Ceph_User_Info.load(k)\n return ceph_user_info\n if response['Error'] is not None:\n return response['Error']\n '''\n \n \n def Create_Pool(self, Ceph_Pool_Info, Auth_Info):\n '''\n 2\n '''\n response = self.mes.send(api='Create_Pool', \n Ceph_User_Info=Ceph_User_Info, \n Auth_Info=Auth_Info)\n if response['Ceph_Pool_Info'] is not None: \n pool_info = Ceph_Pool_Info(k)\n return pool_info\n if response['Error'] is not None:\n return response['Error']\n \n \n def Set_Pool_Model(self, Pool_ID, Pool_Model, Auth_Info):\n '''\n 3\n '''\n response = self.mes.send(api='Set_Pool_Model', \n Pool_ID=Pool_ID, \n Pool_Model = Pool_Model,\n Auth_Info=Auth_Info)\n return response['Opt_Number']\n\n \n \n def Set_Pool_Quota(self, Pool_ID, Quota, Auth_Info):\n '''\n 4\n '''\n response = self.mes.send(api='Set_Pool_Quota', \n Pool_ID=Pool_ID, \n Quota=Quota,\n Auth_Info=Auth_Info)\n return response['Opt_Number']\n \n \n def Remove_Pool(self, Pool_ID, Auth_Info):\n '''\n 5\n '''\n response = self.mes.send(api='Remove_Pool', \n Ceph_User_Info=Ceph_User_Info, \n Auth_Info=Auth_Info)\n return response['Opt_Number']\n \n \n \n def Get_Ceph_User_Info(self, Ceph_User_ID, Access_Key, Secret_Key, Auth_Info=None):\n '''\n 6\n '''\n response = self.mes.send(api='Get_Ceph_User_Info', \n ceph_user_id=Ceph_User_ID,\n auth_info=Auth_Info,\n access_key=Access_Key,\n secret_key=Secret_Key)\n return response\n \n \n \n def Get_Ceph_User_Key(self, Ceph_User_ID, Auth_Info=None):\n '''\n 7\n '''\n response = self.mes.send(api='Get_Ceph_User_Key', \n ceph_user_id=Ceph_User_ID, \n Auth_Info=Auth_Info)\n return response\n \n \n def Set_Pool_Policy(self, Pool_ID, Pool_Policy, Auth_Info=None):\n '''\n 8\n '''\n response = self.mes.send(api='Set_Pool_Policy', \n Pool_ID=Pool_ID, \n Pool_Policy=Pool_Policy,\n Auth_Info=Auth_Info)\n if response['Opt_Number'] is not None:\n return response['Opt_Number']\n \n \n def Get_Object_List(self, Ceph_User_ID, Pool_ID):\n '''\n 9 *\n '''\n response = self.mes.send(api='Get_Object_List', \n Ceph_User_ID=Ceph_User_ID, \n Pool_ID=Pool_ID)\n return response\n \n \n def Get_Object(self, Ceph_User_ID, Ceph_Pool_ID, Object_Key, Auth_Info=None):\n '''\n 10 *\n '''\n response = self.mes.send(api='Get_Object', \n CCeph_User_ID=Ceph_User_ID, \n Ceph_Pool_ID=Ceph_Pool_ID,\n Object_Key=Object_Key,\n Auth_Info=Auth_Info)\n return response\n \n \n def Put_Object(self, Ceph_User_ID, Ceph_Pool_ID, Object_Key, Object_ct, Auth_Info=None):\n '''\n 11 *\n '''\n response = self.mes.send(api='Put_Object', \n Ceph_User_ID=Ceph_User_ID, \n Ceph_Pool_ID=Ceph_Pool_ID,\n Object_Key=Object_Key,\n Object_ct=Object_ct,\n Auth_Info=Auth_Info)\n return response\n \n \n def Updata_Object(self, Ceph_User_ID, Ceph_Pool_ID, Object_Key, Object_ct, Updata_Style, Auth_Info=None):\n '''\n 12 *\n '''\n response = self.mes.send(api='Updata_Object', \n Ceph_User_ID=Ceph_User_ID, \n Ceph_Pool_ID=Ceph_Pool_ID,\n Object_Key=Object_Key,\n Object_ct=Object_ct,\n Updata_Style=Updata_Style,\n Auth_Info=Auth_Info)\n return response\n \n \n def Delete_Object(self, Ceph_User_ID, Ceph_Pool_ID, Object_Key, Auth_Info=None):\n '''\n 13 *\n '''\n response = self.mes.send(api='Delete_Object', \n Ceph_User_ID=Ceph_User_ID, \n Ceph_Pool_ID=Ceph_Pool_ID,\n Object_Key=Object_Key,\n Auth_Info=Auth_Info)\n return response\n \n \n def Set_User_Quota(self, Ceph_User_ID, Max_Size_Kb, Enabled=True, Max_Objects=None,):\n response = self.mes.send(api='Set_User_Quota',\n ceph_user_id=Ceph_User_ID,\n max_size_kb=Max_Size_Kb,\n max_objects=Max_Objects,\n enabled=Enabled)\n return response\n \n \n def Get_User_Quota(self, Ceph_User_ID, Quota_Type='user'):\n response = self.mes.send(api='Get_User_Quota',\n ceph_user_id=Ceph_User_ID,\n quota_type=Quota_Type)\n return response\n \n \n \n def Add_User_Key(self, Ceph_User_ID, New_Access_Key, New_Secret_Key):\n response = self.mes.send(api='Add_User_Key',\n ceph_user_id=Ceph_User_ID,\n new_access_key=New_Access_Key,\n new_secret_key=New_Secret_Key)\n return response\n \n \n def Remove_User_Key(self, Ceph_User_ID, Old_Secret_Key):\n response = self.mes.send(api='Remove_User_Key',\n Ceph_User_ID=Ceph_User_ID,\n Old_Secret_Key=Old_Secret_Key)\n return response\n \n \n \n \n ","sub_path":"giant/manage/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":7101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"328750776","text":"#Monte Roybal\n#Dr. Richard Medina\n#Software Engineering\n#Student Analytics Class\n\nimport json\n\nclass Student_Analytics():\n\t\n\tdef __init__(self,data=[]):\n\t\t\"\"\"Constructor Method\"\"\"\n\t\tself.data = data\n\t\tself.load_data(\"/home/monte/Desktop/CS_551/cs451-551-analytics-engine/data/grade-data.json\")\n\n\tdef __str__(self):\n\t\t\"\"\"Print Method\"\"\"\n\t\treturn (\"Average final grade over the entire database is {} \\nAverage change in grade from midterm to final is {}, {} to {} \\nA count of each final grade (E.g., #A's, #B's, etc.) {},{},{},{},{} \\nTotal number of female students is {} \\nTotal number of male students is {}\".format(s.classify_grade(s.avg_grade(3)),s.grade_change(),s.classify_grade(s.avg_grade(2)),s.classify_grade(s.avg_grade(3)),s.element_count(3,\"A\"),s.element_count(3,\"B\"),s.element_count(3,\"C\"),s.element_count(3,\"D\"),s.element_count(3,\"F\"),s.element_count(1,\"F\"),s.element_count(1,\"M\")))\n\n\tdef load_data(self,fname):\n\t\t\"\"\"Load the json file\"\"\"\n\t\tfile_obj = open(fname)\n\t\tself.data = json.loads(file_obj.read())\n\t\tfile_obj.close()\n\n\tdef classify_grade(self,grade_val):\n\t\t\"\"\"Return a grade classification from a given grade value\"\"\"\n\t\tif grade_val >= 5.00:\n\t\t\treturn \"A+\"\n\t\telif grade_val > 4.7:\n\t\t\treturn \"A-\"\n\t\telif grade_val > 4.3:\n\t\t\treturn \"B+\"\n\t\telif grade_val >= 4.0:\n\t\t\treturn \"B\"\n\t\telif grade_val > 3.7:\n\t\t\treturn \"B-\"\n\t\telif grade_val > 3.3:\n\t\t\treturn \"C+\"\n\t\telif grade_val >= 3.0:\n\t\t\treturn \"C\"\n\t\telif grade_val > 2.7:\n\t\t\treturn \"C-\"\n\t\telif grade_val >1.7:\n\t\t\treturn \"D\"\n\t\telse:\n\t\t\treturn \"F\"\n\n\tdef element_count(self,pos,query):\n\t\t\"\"\"Return a total number of elements from a given query and data position\"\"\"\n\t\ttotal_count = 0\n\t\tfor i in self.data:\n\t\t\tif i[pos] == query:\n\t\t\t\ttotal_count+=1\n\t\treturn total_count\n\n\tdef avg_grade(self,pos):\n\t\t\"\"\"Return the average grade value from a given data position\"\"\"\n\t\ttotal_count = len(self.data) \n\t\ttotal_val = 0\n\t\ttotal_val = (self.element_count(pos,\"A\")*5+self.element_count(pos,\"B\")*4+self.element_count(pos,\"C\")*3+self.element_count(pos,\"D\")*2+self.element_count(pos,\"F\")) \n\t\treturn (total_val/total_count)\n\n\tdef grade_change(self):\n\t\t\"\"\"Return the average change in grade value from midterm to final grades\"\"\"\n\t\tfinal_val = self.avg_grade(3)\n\t\tmid_val = self.avg_grade(2)\n\t\treturn (final_val-mid_val)\n\n\nif __name__ == '__main__':\n s = Student_Analytics()\n print (s)","sub_path":"src/roybal_student_analytics.py","file_name":"roybal_student_analytics.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"296314648","text":"\nimport calendar\nimport csv\nimport os\nimport re\nimport sys\nfrom decimal import Decimal\nfrom datetime import date\nfrom datetime import timedelta\n\nfrom charge import Charge\nfrom charge import account_code\nfrom ledger import Ledger\nfrom date_range import DateRange\nfrom date_range import MonthRange\nfrom repeater import Repeater\nfrom data_file import load_ledger_dir\nfrom data_file import load_budget_csv\n\nDATE_RANGE = DateRange(date(2017,2,1), date(2017,4,30))\n\n# MONTH = MonthRange(date(2017,3,1))\n\nconfig_file_path = os.path.join(os.environ['HOME'],'.monkey')\nwith open(config_file_path, 'r') as config_file:\n dirpath = config_file.readline().strip()\n\nbudget = load_budget_csv(os.path.join(dirpath, 'budget.csv'))\nraw_ledger = load_ledger_dir(os.path.join(dirpath, 'transactions'))\naccount_codes = [account_code(a) for a in raw_ledger.accounts()]\nprint(account_codes)\n\nmonth_names = [n.lower() for n in calendar.month_name]\nmonth_abbrs = [a.lower() for a in calendar.month_abbr]\n\nif __name__ == \"__main__\":\n sys.argv.pop(0)\n commands = sys.argv\n month = date.today().month\n year = date.today().year\n account = None\n while commands:\n command = commands.pop(0).lower()\n print(command)\n if command in month_names:\n month = month_names.index(command)\n elif command in month_abbrs:\n month = month_abbrs.index(command)\n elif command.isdigit():\n year = int(command)\n if year < 100:\n year = 2000 + year\n elif account_code(command) in account_codes:\n account = account_code(command)\n elif command == 'dates':\n monthrange = MonthRange(date(year, month, 1))\n if account:\n print('by account')\n new_ledger = raw_ledger.by_account(account)\n else:\n new_ledger = raw_ledger\n calc_ledger = new_ledger.by_month_calculated(monthrange, budget)\n for account in calc_ledger.accounts():\n print()\n print(account)\n account_charges = calc_ledger.by_account(account)\n balance = Decimal(0)\n for day in monthrange.range():\n day_amount = account_charges.by_date(day).total_amount()\n balance += day_amount\n # if day >= date.today() - timedelta(7) and day <= date.today() + timedelta(7):\n print(\" {day:%Y-%m-%d} {amount: >9.2f} {balance: >9.2f}\".format(day=day, amount=day_amount, balance=balance))\n # print(charge.amount())\n\n# for account in balances:\n# # print(\"{account: <12.12} {balance: >9.2f}\".format(account=account, balance=balances[account]))\n# print\n# print(account)\n","sub_path":"monkey.py","file_name":"monkey.py","file_ext":"py","file_size_in_byte":2775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"398837746","text":"# Alunas: Izabela A. Andrade (20192004795), Marcela P. Silvério (20192020028) e Tássyla L. Lima (20192001990)\n# Turma: INF3A\n\n# **********************************************************************************************************\n# O código em questão visa determinar a quantidade máxima de casamentos possíveis de acordo com as condições\n# do enunciado. Para tal, primeiramente a função dfs é definida. Em seguida temos a inicialização dos\n# dicionários que armazenarão as relações a serem definidas na entrada e um dicionário que indicará quais \n# pessoas dessa relação já foram analisadas, respectivamente. Logo depois, temos um loop que lê a entrada \n# até o fim de arquivo e armazena tal entrada no dicionário de relações, no qual a chave indica uma pessoa \n# e o valor indica a pessoa que ela gosta. Simultaneamente, a lista de visitados é inicializada com False. \n# Após isso, temos um for que percorre cada relação na lista de relações, armazenando em uma varíavel o \n# retorno da função dfs que faz a busca de casamentos na relação inicializada.\n\n# A função dfs funciona recebendo o grafo no qual será realizada a busca (relações), o vétice inicial \n# (relação) e a lista de visitados. A função funciona iterativamente para evitar problemas com empilhamento \n# máximo de função recursiva. No início, definimos uma lista que armazenará os visitados especificamente \n# naquela seção. Inicializamos uma lista de vértices a visitar com o própria relação que foi passada \n# inicialmente para a função. O loop funciona enquanto houverem vértices a serem visitados. Definimos o \n# vértice atual na varíavel vertice e verificamos se esse vértice já foi visitado. Em caso positivo, a \n# execução da função para, retornando 0, o que significa que não foi possível formar um casamento na seção \n# em questão. Em caso negativo, ele define o vértice como visitado, o adiciona na lista de visitados na \n# seção, e continua a execução da função, passando para o próximo bloco condicional. Nesse bloco verificamos\n# se a pessoa gostada pela pessoa atual já foi visitada e, em caso negativo, ela é adicionada na lista de \n# vértices a visitar. Em caso positivo, ou seja, a pessoa gostada já foi visitada, fazemos outra condição \n# que verifica se a pessoa gostada está na relação atual e se essa relação tem 2 ou mais pessoas. Em caso \n# posivo, encontramos um cilco, o que representa um casamento possível, dessa forma a função retorna 1. Por \n# fim, temos um retorno após o while do valor 0, para que, quando os vértices a visitar acabarem sem que um\n# casamento seja encontrado, tal seja retornado para a soma de casamentos. No final, a variável casamentos \n# é impressa, informando a quantidade de casamentos que é possível formar.\n# **********************************************************************************************************\n\ndef dfs(grafo, vertice, visitados):\n \n visitados_na_secao = []\n\n vertices_visitar = [vertice]\n\n while vertices_visitar:\n\n vertice = vertices_visitar.pop()\n\n if not visitados[vertice]:\n\n visitados[vertice] = True\n visitados_na_secao.append(vertice)\n\n if not visitados[grafo[vertice]]:\n vertices_visitar.append(grafo[vertice])\n elif grafo[vertice] in visitados_na_secao and len(visitados_na_secao) >= 2: return 1\n\n else: return 0\n return 0\n\nrelacoes, visitados = {}, {}\n\nwhile True:\n try:\n e = input().split()\n relacoes[e[0]] = e[1]\n visitados[e[0]] = False\n\n except:\n break\n\ncasamentos = 0\n\nfor relacao in relacoes:\n casamentos += dfs(relacoes, relacao, visitados)\n\nprint(casamentos)\n","sub_path":"Lista 4 - Grafos/07_1902.py","file_name":"07_1902.py","file_ext":"py","file_size_in_byte":3761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"294434982","text":"from pprint import pformat\n\nimport requests\n\n\nclass HitbtcClientRest:\n def __init__(self, key: str, secret: str, url: str = 'https://api.hitbtc.com/api/2'):\n try:\n self.session = requests.session()\n self.session.auth = (key, secret)\n except Exception as e:\n raise\n \n self.url = {}\n try:\n self.url['base'] = url\n except Exception as e:\n raise\n\n # Public API Methods\n def get_symbols(self) -> dict:\n return self.get_symbol()\n\n def get_symbol(self, symbol: str = None) -> dict:\n path = '/public/symbol/'\n if symbol is None:\n endpoint = ''\n else:\n endpoint = symbol\n\n return self.get(locals())\n\n def get_currencies(self) -> dict:\n return self.get_currency()\n\n def get_currency(self, currency: str = None) -> dict:\n path = '/public/currency'\n if currency is None:\n endpoint = ''\n else:\n endpoint = currency\n\n return self.get(locals())\n\n def get_ticker(self) -> dict:\n return self.get_symbol_ticker()\n\n def get_symbol_ticker(self, symbol: str = None) -> dict:\n path = '/public/ticker/'\n if symbol is None:\n endpoint = ''\n else:\n endpoint = symbol\n\n return self.get(locals())\n\n def get_trades_for_symbol(self, symbol: str, sort: str = None, by: str = None, from_type: str = None, till: str = None, limit: str = None) -> dict:\n path = '/public/trades/'\n if symbol is None:\n raise Exception('Argument symbol must be specified')\n else:\n endpoint = symbol\n\n return self.get(locals())\n\n def get_order_book_for_symbol(self, symbol: str, limit: int = None) -> dict:\n path = '/public/orderbook/'\n if symbol is None:\n raise Exception('Argument symbol must be specified')\n else:\n endpoint = symbol\n\n return self.get(locals())\n\n def get_candles_for_symbol(self, symbol: str, limit: int = None, period: str = None) -> dict:\n path = '/public/candles/'\n if symbol is None:\n raise Exception('Argument symbol must be specified')\n else:\n endpoint = symbol\n\n return self.get(locals())\n\n # Trading API Methods\n\n def get_all_orders(self) -> dict:\n return self.get_order_book_for_symbol()\n\n def get_all_orders_for_symbol(self, symbol: str = None) -> dict:\n path = '/order'\n return self.get(locals())\n\n def post_order_for_symbol(self, symbol: str, side: str, quantity: str, clientOrderId: str = None, type: str = None, timeInForce: str = None, price: str = None,\n stopPrice: str = None, expireTime: str = None, strictValidate: bool = True) -> dict:\n path = '/order'\n if None in [symbol, side, quantity]:\n raise Exception('Arguments symbol, side, quantity must be specified')\n\n return self.post(locals())\n\n def delete_all_orders_for_symbol(self, symbol: str) -> dict:\n path = '/order'\n if symbol is None:\n raise Exception('Argument symbol must be specified')\n\n return self.delete(locals())\n\n def get_order_by_id(self, clientOrderId: str, wait: str = None) -> dict:\n path = '/order/'\n if clientOrderId is None:\n raise Exception('Argument clientOrderId must be specified')\n else:\n endpoint = clientOrderId\n\n return self.get(locals())\n\n def put_order_for_symbol(self, symbol: str, side: str, clientOrderId: str, timeInForce: str, quantity: str, type: str = None, price: str = None,\n stopPrice: str = None, expireTime: str = None, strictValidate: bool = True) -> dict:\n path = '/order/'\n if None in [clientOrderId, symbol, side, quantity, timeInForce]:\n raise Exception('Arguments clientOrderId, symbol, side, quantity, timeInForce must be specified')\n else:\n endpoint = clientOrderId\n\n return self.put(locals())\n\n def delete_order_by_id(self, clientOrderId: str) -> dict:\n path = '/order/'\n if clientOrderId is None:\n raise Exception('Argument clientOrderId must be specified')\n else:\n endpoint = clientOrderId\n\n return self.delete(locals())\n\n def patch_order_by_id(self, clientOrderId: str) -> dict:\n path = '/order/'\n if clientOrderId is None:\n raise Exception('Argument clientOrderId must be specified')\n else:\n endpoint = clientOrderId\n\n return self.patch(locals())\n\n def get_trading_balance(self) -> list:\n path = '/trading/balance'\n return self.get(locals())\n\n def get_trading_fee(self, symbol) -> dict:\n path = '/trading/fee/'\n if symbol is None:\n raise Exception('Argument symbol must be specified')\n else:\n endpoint = symbol\n return self.get(locals())\n\n # Trading History API Methods\n\n # Account API Methods\n def get_account_balance(self):\n path = '/account/balance'\n return self.get(locals())\n\n def get_account_transactions(self, transaction_id: str = None) -> dict:\n path = '/account/transactions'\n if transaction_id is not None:\n path += '/%s' % transaction_id\n return self.get(locals())\n\n def get_account_transaction_by_id(self, transaction_id) -> dict:\n return self.get_account_transactions(transaction_id)\n\n\n # API Helper Methods\n def get(self, params: dict) -> dict:\n return self.__call('get', params)\n\n def patch(self, params: dict) -> dict:\n return self.__call('patch', params)\n\n def put(self, params: dict) -> dict:\n return self.__call('put', params)\n\n def post(self, params: dict) -> dict:\n return self.__call('post', params)\n\n def delete(self, params: dict) -> dict:\n return self.__call('delete', params)\n\n def __call(self, method: str, params: dict) -> dict:\n if 'endpoint' not in params:\n params['endpoint'] = ''\n if 'from_type' in params:\n params['from'] = params['from_type']\n del params['from_type']\n\n data = {}\n\n for key in params.keys():\n if params[key] is not None and key not in ['path', 'endpoint', 'self']:\n data[key] = params[key]\n\n if hasattr(self.session, method):\n try:\n #print(\"%s%s%s\" % (self.url['base'], params['path'], params['endpoint']))\n #print('data=%s' % pformat(data))\n try:\n r = getattr(self.session, method)(url=\"%s%s%s\" % (self.url['base'], params['path'], params['endpoint']), params=data).json()\n except Exception as e:\n raise\n if 'error' in r:\n raise Exception('API Error: %s' % r)\n return r\n except Exception as e:\n raise\n return {} # For Code Annotations\n","sub_path":"brickmover/market/hitbtc/rest/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":7077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"247987250","text":"\"\"\"\nState to handle the taking of calibration frames (evening and morning).\n\"\"\"\nfrom functools import partial\n\n\ndef wait_for_twilight(pocs):\n \"\"\"\n Wait for twilight. Temporary solution until something better is found.\n\n Twilight when Sun between flat and focus horizons.\n \"\"\"\n pocs.logger.debug('Waiting for twilight...')\n while pocs.is_safe(horizon='flat'):\n if pocs.is_dark(horizon='focus'):\n pocs.sleep(delay=pocs._safe_delay)\n else:\n return True\n return False\n\n\ndef safety_func(pocs):\n \"\"\" Return True only if safe for flats to continue. \"\"\"\n return pocs.is_safe(horizon='flat') and not pocs.is_dark(horizon='focus')\n\n\ndef on_enter(event_data):\n \"\"\"\n Calibrating state. If safe to do so, take flats and darks. Should be\n called once at the beginning and end of the night.\n\n If evening, the next state will be coarse_focusing, else, parking.\n \"\"\"\n pocs = event_data.model\n pocs.next_state = 'parking'\n\n # Make sure it's safe, dark and light enough for flats\n if not wait_for_twilight(pocs):\n return\n\n if pocs.observatory.flat_fields_required:\n sf = partial(safety_func, pocs=pocs)\n pocs.observatory.take_flat_fields(safety_func=sf)\n else:\n pocs.logger.debug('Skipping twilight flat fields.')\n\n # Specify the next state\n if pocs.observatory.past_midnight:\n pocs.next_state = 'parking'\n else:\n pocs.next_state = 'coarse_focusing'\n","sub_path":"src/huntsman/pocs/states/huntsman/twilight_flat_fielding.py","file_name":"twilight_flat_fielding.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"9270836","text":"# -*- coding: utf-8 -*-\n\n__author__ = \"Kjersti Rustad Kvisberg\"\n__email__ = \"kjkv@nmbu.no\"\n\n\nclass LCGRand:\n \"\"\"Implementation of a linear congruential generator\n that returns random numbers.\n\n Attributes\n ----------\n a : int\n Constant given in ex. text, necessary for generation.\n m : int\n Constant given in ex. text, necessary for generation.\n \"\"\"\n def __init__(self, seed):\n \"\"\"Initialises the class with given constants a and m.\n\n Parameters\n ----------\n seed : int\n The seed that the generating is based on.\n \"\"\"\n self.seed = seed\n self.a = 7**5\n self.m = 2**31 - 1\n\n def rand(self):\n \"\"\"Generates a random number based on a seed given by the user.\n\n Returns\n -------\n random_number : int\n The generated number.\n \"\"\"\n random_number = self.a * self.seed % self.m\n self.seed = random_number\n return random_number\n\n\nclass ListRand:\n \"\"\"Generates random numbers from a list of numbers.\n\n Attributes\n ----------\n counter : int\n Number of numbers that have been returned from the list.\n \"\"\"\n def __init__(self, list_of_numbers: list):\n \"\"\"\n Initialises the class with list given by user and a counter.\n\n Parameters\n ----------\n list_of_numbers : list\n List of numbers that will be returned, one by one.\n \"\"\"\n self.numbers_list = list_of_numbers\n self.counter = 0\n\n def rand(self):\n \"\"\"\n Returns a number from the list.\n\n Raises\n ------\n RuntimeError :\n All numbers have been returned.\n\n Returns\n -------\n random_number : int\n Random number drawn from the input list.\n \"\"\"\n if self.counter == len(self.numbers_list):\n raise RuntimeError('Empty list, all numbers have been returned.')\n else:\n random_number = self.numbers_list[self.counter]\n self.counter += 1\n return random_number\n\n\nif __name__ == '__main__':\n LCG_generator = LCGRand(1)\n print(LCG_generator.rand())\n print(LCG_generator.rand())\n\n numbers_list = [1, 12, 5, 19, 2, 7, 16]\n list_generator = ListRand(numbers_list)\n print(list_generator.rand())\n print(list_generator.rand())\n","sub_path":"src/kjersti_rustad_kvisberg_ex/ex04/myrand.py","file_name":"myrand.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"353628814","text":"####################################################################################################\n\nimport matplotlib.pyplot as plt\n\n####################################################################################################\n\nimport PySpice.Logging.Logging as Logging\nlogger = Logging.setup_logging()\n\n####################################################################################################\n\nfrom PySpice.Doc.ExampleTools import find_libraries\nfrom PySpice.Probe.Plot import plot\nfrom PySpice.Spice.Library import SpiceLibrary\nfrom PySpice.Spice.Netlist import Circuit\nfrom PySpice.Unit import *\n\n####################################################################################################\n# Stuff for model\nfrom PySpice.Spice.NgSpice.Shared import NgSpiceShared\n\n####################################################################################################\n\nlibraries_path = find_libraries()\nspice_library = SpiceLibrary(libraries_path)\n\n####################################################################################################\nimport datetime\nsim_start_time = datetime.datetime.now()\nprint()\nprint('Simulation Start Time =', sim_start_time)\nprint()\n####################################################################################################\n\n##########\n# Python code block\n##########\nclass MyNgSpiceShared(NgSpiceShared):\n\n\n def __init__(self, amplitude, **kwargs):\n super().__init__(**kwargs)\n self._amplitude = amplitude\n # Section below needed only to prevent harmless \"AttributeError: 'MyNgSpiceShared' object has no attribute 'clk_out'\"\n #messages at beginning of run\n self.clk_out = 0\n self.gate_drive1 = 0\n #####\n # Section below actually needed for initialization.\n #####\n #clock inits\n self.clk_out_old = 0\n self.ana_time_old = 0.0\n self.time_filt = 0.0\n #filter inits\n self.h = 0.0\n self.inz2 = 0.0 \n self.inz1 = 0.0\n self.midz2 = 0.0\n self.midz1 = 0.0\n self.outz2 = 0.0\n self.outz1 = 0.0\n self.out_filt = 0.0\n #PWM inits\n self.clk_cycls = 0.0\n self.dc_pct = 0.0\n self.i = 0.0\n self.duty = 0.0\n \n \n #########\n # the def get_vsrc_data function provides digital signals from the python block to the ngspice block\n #########\n def get_vsrc_data(self, voltage, time, node, ngspice_id):\n self._logger.debug('ngspice_id-{} get_vsrc_data @{} node {}'.format(ngspice_id, time, node))\n \n #####\n # Debugging aid shows timestep deltas (not just time stamps) when non-zero, and in RED when negative\n #####\n timestep = time - self.ana_time_old\n '''\n if timestep > 0:\n print('Timestep = ', time - self.ana_time_old)\n if timestep < 0:\n print('\\033[1;31mTimestep = ', time - self.ana_time_old, '\\033[1;31m ************************************************************************************************************************') \n '''\n self.ana_time_old = time # END debugging aid\n \n \n # the calculations following this conditional are only executed once per dig_timestep.\n # This runs on every positive and negative clock edge\n \n # print()\n # print('clk_out= '+str(round(self.clk_out))+', clk_out_old= '+str(round(self.clk_out_old))+', time= '+str(round(time,7))+', time_filt= '+str(round(self.time_filt,7)))\n if (round(self.clk_out) != round(self.clk_out_old)) and (time != self.time_filt):\n self.time_filt = time #Need time stamp to avoid executing this code redundantly\n self.clk_out_old = self.clk_out #Need state of clk to know when it next changes\n \n # duty_raw = g_angle*(pot_bip-trgt_bip) #Raw duty cycle is simply gain times actual minus target angle.\n # duty = min(abs(duty_raw),1) #Clip raw duty to get duty\n \n self.clk_cycls+=1\n # print()\n # print('clk_cycls= '+str(self.clk_cycls))\n \n \n # PWM output stage\n # duty cycle = 0.2\n # buck fsw=200k, period=5us\n # switch period is 5us\n # sw_period = 0.000005\n # This if statement runs on every positive and negative edge.\n # clock period: 1000ns\n # new clock edge every: 500ns\n # clock edge speed: 2MHz\n # number of clock edges per switching period: 100\n # self.dc_pct = 17 # 20% duty cycle\n self.i += 1\n # if self.i < self.dc_pct:\n # print('duty high')\n if self.i >= self.dc_pct:\n self.duty = 0\n # print('duty low')\n if self.i >= 100:\n self.i=0\n self.duty = 1\n # print('duty high')\n \n \n # print()\n # print('clk_cycls= '+str(self.clk_cycls))\n # print('New switch period, duty cycle = '+str(self.dc_pct))\n # self.dc_pct = 17 # 20% duty cycle\n \n \n\n ################################################################\n # 2p2z filter\n \"\"\" \n Filter b = [0.0976, 0.1952, 0.0976] a = [1, -0.9429, -0.3334]\n b3 = [1, 0.5018, 0.49818]\n a3 = [0.6, 0.06324,-0.33201 ]\n \"\"\"\n \n self.h += 1\n # The error sampling rate is 66kHz\n # the input is the error, so subtract ideal reference\n if self.h >= 30:\n #Sample the vinput, divide by 10\n v_sns_adc=self.v_sns/10\n self.err_in=0.42-v_sns_adc\n # print()\n # print('clk_cycls= '+str(self.clk_cycls))\n # print('v_sense is: '+str(round(self.v_sns,3))+', error is: '+str(round(self.err_in,4)))\n \n b0 = 1\n b1 = 0.5018\n b2 = 0.4981\n a0 = 0.6\n a1 = 0.0632\n a2 = -0.3320\n \n # note all addition, negative signs included in coefficients\n mid_filt = self.err_in*b0 + self.inz1*b1 + self.inz2*b2\n self.out_filt = mid_filt*a0 + self.outz1*a1 + self.outz2*a2\n \n # print('filter output before bounds is: '+str(round(self.out_filt,4)))\n # print('filter midpoint before bounds is: '+str(round(mid_filt,4)))\n \n # bound filter output\n if self.out_filt > 1:\n self.out_filt = 1\n elif self.out_filt < 0:\n self.out_filt = 0\n \n # print('filter output after bounds is: '+str(round(self.out_filt,4)))\n # inz2 is the z-2 delayed input to the filter\n self.inz2 = self.inz1\n # inz1 is the z-1 delayed input to the filter\n self.inz1 = self.err_in\n \n # outz2 is the z-2 delayed output to the filter\n self.outz2 = self.outz1\n # outz1 is the z-1 delayed output to the filter\n self.outz1 = self.out_filt\n \n # reset sampling counter\n self.h = 0\n \n # Set the duty cycle based on the filter results\n # each integer value of 1 represents 1%\n # Only change the duty cycle once every fsamp\n '''\n if self.out_filt >=0:\n self.dc_pct -= 1\n else:\n self.dc_pct += 1\n '''\n self.dc_pct=self.out_filt*100\n # print('duty cycle after error amp = '+str(self.dc_pct))\n \n # bound the duty cycle to 95% or 5%\n if self.dc_pct > 95:\n self.dc_pct = 95\n elif self.dc_pct < 5:\n self.dc_pct = 5\n \n ########################### END of 2p2z filter##############\n \n ################################################################\n # PID filter\n \"\"\" \n Filter b = [0.0976, 0.1952, 0.0976] a = [1, -0.9429, -0.3334]\n \"\"\"\n '''\n # the input is the error, so subtract ideal reference\n self.err_in=self.v_sns-2.5\n print('v_sense is: '+str(round(self.v_sns,3))+', error is: '+str(round(self.err_in,4)))\n \n b0 = 0.0975\n b1 = 0.1952\n b2 = 0.0976\n a0 = 1.\n a1 = -0.9429\n a2 = 0.3334\n \n # note all addition, negative signs included in coefficients\n mid_filt = self.err_in*b0 + self.inz1*b1 + self.inz2*b2\n out_filt = mid_filt*a0 + self.outz1*a1 + self.outz2*a2\n \n print('filter output is: '+str(round(out_filt,4)))\n # inz2 is the z-2 delayed input to the filter\n self.inz2 = self.inz1\n # inz1 is the z-1 delayed input to the filter\n self.inz1 = self.err_in\n \n # outz2 is the z-2 delayed output to the filter\n self.outz2 = self.outz1\n # outz1 is the z-1 delayed output to the filter\n self.outz1 = out_filt\n '''\n ########################### END of PID filter##############\n \n \n \n # duty = min(self.outz1, duty) # cannot use out_filt here (it's not remembered)\n # if self.i_pol == -1:\n # d_scaled = self.outz1 # no feed forward needed for reverse current regulation; better to use full bus voltage (not 22V max). Also need to override positional loop (use self.outz1 instead of duty here); active high instead of just open-drain output for outz1 when regulating reverse current.\n # else:\n # d_scaled = min(max(0, duty*22/self.p_28v_out), 1) # feed-forward of Vbus\n \n # scale the duty cycle to the drive voltage\n self.gate_drive1=self._amplitude*self.duty\n # print(duty, gate_drive1)\n \n ################### Outputs below go from Python to NGspice#################################################### \n if node == 'vgate_drive1':\n voltage[0]=self.gate_drive1\n # elif node == 'vb':\n # voltage[0]=self.vb_val \n # elif node == 'vc':\n # voltage[0]=self.vc_val\n \n # Dummy outputs below are just for probing. They are no-connects in NGspice \n elif node == 'vdc_pct_out': # this can be used to probe various \"nets\" inside the Python (not NGspice)\n voltage[0]=self.dc_pct #output of elliptic filter\n \n # send the data\n # self.send_data(self, number_of_vectors=2,ngspice_id=ngspice_id)\n return 0\n \n \n ############################################## \n # NGspice data sent to Python\n\n # def send_data(self):\n def send_data(self, actual_vector_values, number_of_vectors, ngspice_id):\n self.clk_out = actual_vector_values['clk'].real\n self.v_sns = actual_vector_values['v_sns'].real\n # self.gate_drive1_out = actual_vector_values['gate_drive1'].real\n #~ self.idt_in_1 = actual_vector_values['x1.xx1.xx5.xx2.xx7.idt_in'].real # example of probing a net in the hierarchy\n return 0\n\n\n\n##########\n# NGspice block\n##########\ncircuit = Circuit('Buck Converter')\n\ncircuit.include(spice_library['1N5822']) # Schottky diode\n# nch mosfet for pulling pch gate to ground\ncircuit.include(spice_library['irf150'])\n# pch mosfet for driving buck output\ncircuit.include(spice_library['DMG4435SSS'])\n\n\n\n# analog stimulus that goes nowhere below; just used to probe Python \"net\" inside digital controller\n\n# Real analog stimuli below:\ncircuit.V('gate_drive1', 'gate_drive1_net', circuit.gnd, 'dc 0 external')\ncircuit.V('dc_pct_out', 'dc_pct_out', circuit.gnd, 'dc 0 external')\n\n# Other NGspice circuit parameters for buck stage\nVin = 28@u_V\nVout = 5@u_V\nRload = 3@u_Ohm\n\n\nL = 150@u_uH\nRL = 100@u_mOhm\n\nCout = 22@u_uF\nESR = 20@u_mOhm\nESL = 0\n\nESR_in = 120@u_mOhm\nCin = 10@u_uF\n\n\n\n# parameters on input to buck\ncircuit.V('input', 'input', circuit.gnd, Vin)\ncircuit.C('input', 'input', circuit.gnd, Cin)\n\n\n# Buck switch\n# p-channel buck switch\ncircuit.X('Q', 'DMG4435SSS', 'pch_drain', 'p_gate_drive', 'input')\n# circuit.R('gate', 'gate', 'gate_drive1_net', 1@u_Ohm)\n# circuit.PulseVoltageSource('pulse', 'gate_drive', circuit.gnd, 0@u_V, 10@u_V, duty_cycle, period)\n\n# resistor from p-channel gate to Vin to bring pchan gate back to Vin when off\ncircuit.R('pgate', 'input', 'p_gate_drive', 1@u_Ohm)\n# nchannel mosfet to pull pchannel gate to ground to turn it on\ncircuit.X('Q3', 'irf150', 'p_gate_drive', 'nchan_sw_drive', circuit.gnd)\n# resistor to drive nch fet, drive comes from controller\ncircuit.R('pgate_nch', 'nchan_sw_drive', 'gate_drive1_net', 1@u_Ohm)\n\n\n\n# Buck LC output and diode\ncircuit.X('D', '1N5822', circuit.gnd, 'pch_drain')\ncircuit.L(1, 'pch_drain', 1, L)\ncircuit.R('L', 1, 'out', RL)\ncircuit.C(1, 'out', circuit.gnd, Cout) # , initial_condition=0@u_V\ncircuit.R('load', 'out', circuit.gnd, Rload)\n\n\n# Voltage Feedback for controller\ncircuit.R(2, 'out', 'v_sns', 10@u_kOhm)\ncircuit.R(3, 'v_sns', circuit.gnd, 10@u_kOhm)\n\n# This clock is used for NGspice mixed signal simulation.\n# The python code runs every clock edge, both positive and negative\n# clock speed: 20MHz\n# clock cycle length: 50ns\ncircuit.PulseVoltageSource('clk', 'clk', circuit.gnd, 0@u_V, 1@u_V, 0.05@u_us, 0.1@u_us)\n# circuit.R(4, 'gate_drive1', circuit.gnd, 10@u_kOhm)\n\n\n#####\n# Add a step load\n#####\n# ~ circuit.PulseVoltageSource('name', n1, n2, v_low, v_high, t_high, t_period, t_delay,t_rise,t_fall)\ncircuit.PulseVoltageSource('load_sw', 'gate_drive2', circuit.gnd, 0@u_V, 10@u_V, 1@u_s,1@u_s,0.8@u_ms,10@u_ns)\n\n# load switch\ncircuit.X('Q2', 'irf150', 'out', 'gate2', 'source2')\ncircuit.R('gate2', 'gate2', 'gate_drive2', 1@u_Ohm)\ncircuit.R('load_on','source2', circuit.gnd,Rload)\n\n#####\n# Simulation parameters\n#####\n# Python block input constants\namplitude = 10@u_V\n\n# Call the MyNgSpiceShared\nngspice_shared = MyNgSpiceShared(amplitude=amplitude, send_data=True)\n\nsimulator = circuit.simulator(temperature=25, nominal_temperature=25,simulator='ngspice-shared',ngspice_shared=ngspice_shared)\n\nsimulator.initial_condition(clk=0)\n# step time is 0.1us, 100 datapoints per clock switch period, and 25 datapoints per buck switch period\n# Total of 150 clock cycles measured and 1200 buck switch cycles\nanalysis = simulator.transient(step_time=.05E-6, end_time=75*20E-6)\n\n\n# Print the time to run simulation\nsim_end_time = datetime.datetime.now()\nprint()\nprint('Simulation End Time =', sim_end_time)\nelapsed = sim_end_time - sim_start_time\nprint('Total Simulation Time =', elapsed)\nprint()\n\n#####\n# Plotting\n#####\n\n#plots of circuit components\nfigure = plt.figure(1, (10, 5))\nplot2 = plt.subplot(211)\n\n# plot(analysis.out, axis=axe)\n# plot(analysis['source'], axis=axe)\n# plot(analysis.gate_drive1_net, axis=axe)\nplot(analysis.dc_pct_out)\n# plot(analysis.sw_drive, axis=axe)\n# plot(analysis.r_top/circuit['R1'].resistance,axis=axe)\n# plot(analysis['source'] - analysis['out'], axis=axe)\n# plot(analysis['gate'], axis=axe)\n# plt.axhline(y=float(Vout), color='red')\n# plt.legend(('Vout [V]', 'Vsource [V]'), loc=(.8,.8))\nplt.grid()\nplt.xlabel('t [s]')\nplt.ylabel('[V]')\nplt.legend(('duty cycle %',''), loc=(.05,.1))\n\n\nplot2 = plt.subplot(212)\nplot(analysis.out)\n# plot(analysis.input)\nplt.grid()\nplt.xlabel('t [s]')\nplt.ylabel('[V]')\nplt.legend(('Vout',''), loc=(.05,.1))\n\n\n\n\nplt.tight_layout()\nplt.show()\n\n# plots of mcu internal signals\n'''\nfigure = plt.figure(2, (10, 5))\naxe = plt.subplot(111)\n\nplot(analysis.clk, axis=axe)\n# plot(analysis.sw_drive, axis=axe)\n# plot(analysis.out, axis=axe)\nplot(analysis.gate_drive1_net, axis=axe)\n# plot(analysis.r_top, axis=axe)\n# plot(analysis['source'], axis=axe)\n\nplt.grid()\nplt.xlabel('t [s]')\nplt.ylabel('[V]')\n\nplt.tight_layout()\nplt.show()\n'''","sub_path":"Pyspice/pcu_sim/pyspice_examples/mq_buck_2019_08_16.py","file_name":"mq_buck_2019_08_16.py","file_ext":"py","file_size_in_byte":16351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"579312273","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jan 16 20:22:07 2020\r\n\r\n@author: Hugo\r\n\"\"\"\r\nimport numpy as np\r\nimport utils \r\nimport datasets as data\r\nimport autoencod as ae\r\nfrom torch import load\r\n\r\ndef NnQuery(y,S):\r\n \"\"\"\r\n Finds the nearest neighbour of y in the space S according to the cosine distance\r\n y = Numpy vector \r\n S = Numpy Array\r\n \"\"\"\r\n \r\n iMax = np.shape(S)[1]\r\n \r\n d = np.zeros((2,iMax))\r\n for i in range(iMax):\r\n d[0][i] = i\r\n d[1][i] = 1.0 - utils.s(y,S[:][i])\r\n \r\n dSorted = np.sort(d)\r\n NNindex = np.int32(dSorted[0][0])\r\n \r\n return NNindex\r\n\r\ndef AudioRetrieval(x,model_dir = \"models/multimodal_small.pth\", data_dir = \"db/splitMIDI\"):\r\n Encoder = ae.multimodal()\r\n Encoder.load_state_dict(load(model_dir))\r\n # Put the spectrogram x in the latent space\r\n _,y = Encoder.forward(x) \r\n # Sets the MIDI points in the latent space\r\n dataset,labels = data.Snippets(data_dir)\r\n Slist = []\r\n for snip in dataset : \r\n L,_ = Encoder.forward(snip)\r\n Slist.append(L)\r\n S = tuple(Slist)\r\n #Find the nearest MIDI files to y in the latent space\r\n NNindex = NnQuery(y,S)\r\n RetrievedMIDI = dataset[NNindex,:,:,:]\r\n print(labels[NNindex])\r\n return RetrievedMIDI\r\n\r\ndef MIDIRetrieval(x,model_dir = \"models/multimodal_small.pth\",data_dir = \"db/SplitAudio\"):\r\n Encoder = ae.multimodal()\r\n Encoder.load_state_dict(load(model_dir))\r\n #Put the MIDI snippet x in the latent space\r\n y,_ = Encoder.forward(x)\r\n # Sets the Audio points in the latent space\r\n dataset,labels = data.Snippets(data_dir)\r\n Slist = []\r\n for snip in dataset : \r\n _,L = Encoder.forward(snip)\r\n Slist.append(L)\r\n S = tuple(Slist)\r\n #Finds the nearest MIDI files to y in the latent space\r\n NNindex = NnQuery(y,S)\r\n RetrievedAudio = dataset[NNindex,:,:,:]\r\n print(labels[NNindex])\r\n return RetrievedAudio\r\n \r\n \r\n \r\n \r\n ","sub_path":"retrevial.py","file_name":"retrevial.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"87634489","text":"\"\"\"\nAuthor: Francisco Javier Guzman-Vega\n\nWrapper for PULCHRA - command line tool for all-atom reconstruction and\nrefinement of reduced protein models. PULCHRA can correct alpha carbon\npositions, add backbone and side chain atoms, improve hydrogen bond patterns\nand check proper protein chirality\n\nhttp://www.pirx.com/pulchra/index.shtml\n\n\"\"\"\n\nimport biskit as B\nfrom biskit.exe.executor import Executor\nimport os\nfrom errors import *\n\nclass Pulchra(Executor):\n \"\"\"\n A Pulchra wrapper to add side chains to the linkers generated by Ranch\n\n Usage\n ====\n\n >>> call = Pulchra(f_in)\n\n >>> rebuild = call.run()\n\n The rebuilt model is created in the same directory as the input pdb\n\n \"\"\"\n\n def __init__(self, f_in, **kw):\n \n \"\"\"\n Create the variables that Pulchra needs to run\n\n :param f_in: path for the input pdb file to be rebuilt\n :type f_in: str\n\n :param kw: additional key=value parameters are passed on to\n 'Executor.__init__'. For example:\n ::\n debug - 0|1, keep all temporary files (default: 0)\n verbose - 0|1, print progress messages to log\n (log != STDOUT)\n nice - int, nice level (default: 0)\n log - biskit.LogFile, program log (None->STOUT)\n (default:None)\n \"\"\"\n self.f_in = f_in\n\n if not os.path.exists(self.f_in):\n raise InputError('Invalid PDB file path.')\n\n # The executable needs to be accessed\n self.pulchra = os.path.join(os.path.abspath(\n os.path.dirname(__file__)), 'pulchra/pulchra')\n\n super().__init__(self.pulchra, strict=False, args=self.f_in, **kw)\n\n\n\n#############\n## TESTING \n#############\nimport testing\n\nclass TestPulchra(testing.AutoTest):\n \"\"\"\n Test class\n \"\"\"\n\n TAGS = [testing.EXE]\n\n testpdb = None\n\n def setUp(self):\n self.testpdb = self.testpdb or \\\n os.path.join(os.path.abspath(os.path.dirname(__file__)), \n 'testdata/2z6o_mod.pdb')\n\n def test_rebuiltFile(self):\n \"\"\"\n Test to confirm that .rebuilt.pdb file was created after running pulchra\n \"\"\"\n\n call = Pulchra(self.testpdb)\n rebuilt = call.run()\n \n f_out = self.testpdb[:-3]+'rebuilt.pdb'\n self.assertTrue(os.path.exists(f_out), '.rebuilt.pdb file not created')\n os.remove(f_out)\n\n\nif __name__ == '__main__':\n\n testing.localTest(debug=False)\n","sub_path":"multiprot/pulchra.py","file_name":"pulchra.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"499594411","text":"'''\nBloom Filter\n False positive matches are possible, but false negatives are not - in other words, a query returns either \"possibly in set\" or \"definitely not in set\".\n\nFalse Positive \n An error in data reporting in which a test result improperly indicates presence of a condition, such as a disease (the result is positive), when in reality it is not present.\n\nFalse Negative \n An error in which a test result improperly indicates no presence of a condition (the result is negative), when in reality it is present.\n'''\nimport matplotlib.pyplot as plt\nimport random\nimport string\nimport sys\nimport time\nimport os\nimport psutil\nimport argparse\n\n\n'''\nadd_and_check\n'''\n\ndef add_and_check(myset, key2add, key2check, verbose):\n hit = False\n if verbose:\n print('Adding :'+key2add)\n\n myset.add(key2add)\n\n if(key2check is None):\n key2check = key2add\n\n hit = key2check in myset\n\n if verbose:\n if hit:\n print(\"Found :\"+key2check)\n else:\n print(\"Not Found :\"+key2check)\n\n return hit\n\n'''\ntest\n We keep the unit testing under this method.\n'''\ndef test():\n # instantiate BloomFilter with custom settings,\n # max_elements is how many elements you expect the filter to hold.\n # error_rate defines accuracy; You can use defaults with\n # `BloomFilter()` without any arguments. Following example\n # is same as defaults:\n prev_key = None\n myset = set([])\n\n for i in range(0, 10):\n key = str(i)\n if add_and_check(myset, key, prev_key, True):\n print ('Success')\n prev_key = key\n\n'''\nanalyse\n We keep the analysis under this method.\n'''\ndef analyse(max_elements, error_rate, iteration_count, population_count): \n process = psutil.Process(os.getpid())\n m0 = process.memory_info().rss\n print('Initial Memory : '+str(m0))\n myset = set([])\n m0 = process.memory_info().rss\n print('Memory after Bloom Filter: '+str(m0))\n\n count_false_positive = 0\n count_false_negative = 0\n\n #-\n # Iterate and monitor the parameters in each iteration.\n # Measure the parameters at the begining and end of each iteration\n #-\n '''\n Iteration, Count, F +ve, F -ve, Time, Memory\n 1, 10000, 0.0000, 0.0000, 0.86896200, 360448\n 1, 20000, 0.0000, 0.0000, 0.87001700, 0\n 1, 30000, 0.0000, 0.0000, 0.87261100, 12288\n 1, 40000, 0.0000, 0.0000, 0.87400500, 0\n 1, 50000, 0.0020, 0.0000, 0.87497200, 0\n 1, 60000, 0.0100, 0.0000, 0.87615900, 0\n 1, 70000, 0.0270, 0.0000, 0.87717300, 0\n 1, 80000, 0.0580, 0.0000, 0.88109100, 0\n\n '''\n print('Iteration, Count, F +ve, F -ve, Time, Memory')\n iter = []\n false_positive = []\n false_negative = []\n time_measured = []\n memory_measured = []\n\n\n for i in range(0, iteration_count):\n #record the time stamp\n m0 = process.memory_info().rss\n t0 = time.clock()\n\n #add entries\n prev_key = None\n for j in range (0, population_count):\n #generate a random number and add it to the bloom filter\n key = str( random.randint(0, sys.maxint) )\n if prev_key is None:\n prev_key = key\n\n myset.add(key)\n\n #lets check whatever we just added is present or not\n if prev_key not in myset:\n count_false_negative += 1\n\n # We never generated any with 'x'. So shouldn't be there.\n if (key+'x') in myset:\n count_false_positive += 1\n\n\n #lets analyze the current hits and analyse the error, time and memory\n t_delta = time.clock() - t0\n #calculate the error\n actual_count = (i+1) * population_count\n err_false_positive = (count_false_positive)*100.0/(actual_count*1.0)\n err_false_negative = (count_false_negative)*100.0/(actual_count*1.0)\n #calculate memory growth\n m_delta = process.memory_info().rss - m0\n\n\n print('{:8d}'.format(i)+', '+ \n '{:8d}'.format(actual_count)+', '+\n '{:8.4f}'.format(round(err_false_positive,3))+', '+\n '{:8.4f}'.format(round(err_false_negative,3))+', '+\n '{:10.8f}'.format(t_delta)+', '+\n '{:8d}'.format(m_delta))\n sys.stdout.flush()\n\n iter.append(i)\n false_positive.append(err_false_positive)\n false_negative.append(err_false_negative)\n time_measured.append(t_delta)\n memory_measured.append(m_delta)\n\n fig, ax = plt.subplots()\n ax.margins(0.02, 0.02)\n\n ax.set_xlabel('Population Count ( x'+'{:,}'.format(population_count)+' )')\n #ax.plot(iter, false_positive, label='False +ve(%)')\n #ax.plot(iter, false_negative, label='False -ve(%)')\n #ax.plot(iter, memory_measured, label='Memory')\n total_memory = 0;\n mem_accumulated = []\n for x in memory_measured:\n total_memory += x;\n mem_accumulated.append(total_memory/1024/1024)\n ax.plot(iter, mem_accumulated, label='Memory (MB)')\n #ax.plot(iter, [x/1024/1024 for x in memory_measured], label='Memory (MB)')\n #ax.plot(iter, time_measured, label='Time(Sec)')\n\n ax.grid(True, which='both')\n ax.set_title(\"Set\")\n ax.legend(loc='best')\n plt.show()\n\n\ndef main():\n ap = argparse.ArgumentParser()\n\n ap.add_argument(\"--test\", \n help=\"Test Run\",\n action=\"store_true\")\n\n ap.add_argument(\"-i\", \"--iterations\", \n help=\"Number of Iterations\",\n type=int,\n default=10)\n\n ap.add_argument(\"-p\", \"--population\", \n help=\"Population Count per Iteration\",\n type=int,\n default=1000000)\n\n ap.add_argument(\"-m\", \"--max\", \n help=\"Max Number\",\n type=int,\n default=100000)\n\n\n ap.add_argument(\"-e\", \"--error\", \n help=\"Error Tolerance\",\n type=float,\n default=0.01)\n\n\n args = ap.parse_args()\n if(args.test):\n test()\n else:\n print('Capacity :'+str(args.max))\n print('Err Tolerance :'+str(args.error))\n print('#Iterations :'+str(args.iterations))\n print('Population per Iteration :'+str(args.population))\n analyse(args.max, args.error, args.iterations, args.population)\n \n \nif __name__ == \"__main__\":\n main()\n","sub_path":"src/set.py","file_name":"set.py","file_ext":"py","file_size_in_byte":6579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"140175486","text":"import os\nimport fileinput\nimport sys\nimport random\nimport shutil\nimport stat\nfrom PIL import Image\n\nclasses = []\n\ndef move_files(output_path):\n\n if os.path.isdir(os.path.join(output_path, \"train\")):\n shutil.rmtree(os.path.join(output_path, \"train\"))\n\n if os.path.isdir(os.path.join(output_path, \"valid\")):\n shutil.rmtree(os.path.join(output_path, \"valid\"))\n\n if os.path.isdir(os.path.join(output_path, \"test\")):\n shutil.rmtree(os.path.join(output_path, \"test\"))\n\n os.mkdir(os.path.join(output_path, \"train\"))\n os.mkdir(os.path.join(output_path, \"valid\"))\n os.mkdir(os.path.join(output_path, \"test\"))\n\n with open(os.path.join(output_path, \"train.txt\")) as train_file:\n for line in train_file:\n image_source = line.replace(\"\\n\", \"\")\n image_dest = os.path.join(output_path, \"train\", os.path.basename(image_source))\n shutil.copyfile(image_source, image_dest)\n\n label_file = os.path.basename(line).replace(\".jpg\\n\", \".txt\")\n label_source = os.path.join(output_path, \"label\", label_file)\n label_dest = os.path.join(output_path, \"train\", os.path.basename(label_source))\n shutil.copyfile(label_source, label_dest)\n\n with open(os.path.join(output_path, \"valid.txt\")) as valid_file:\n for line in valid_file:\n image_source = line.replace(\"\\n\", \"\")\n image_dest = os.path.join(output_path, \"valid\", os.path.basename(image_source))\n shutil.copyfile(image_source, image_dest)\n\n label_file = os.path.basename(line).replace(\".jpg\\n\", \".txt\")\n label_source = os.path.join(output_path, \"label\", label_file)\n label_dest = os.path.join(output_path, \"valid\", os.path.basename(label_source))\n shutil.copyfile(label_source, label_dest)\n\n with open(os.path.join(output_path, \"test.txt\")) as test_file:\n for line in test_file:\n image_source = line.replace(\"\\n\", \"\")\n image_dest = os.path.join(output_path, \"test\", os.path.basename(image_source))\n shutil.copyfile(image_source, image_dest)\n\n label_file = os.path.basename(line).replace(\".jpg\\n\", \".txt\")\n label_source = os.path.join(output_path, \"label\", label_file)\n label_dest = os.path.join(output_path, \"test\", os.path.basename(label_source))\n shutil.copyfile(label_source, label_dest)\n\ndef file_len(fname):\n with open(fname) as f:\n count = sum(1 for _ in f)\n\n return count\n\ndef split_test_data(file, output_path, test_split):\n num_data = sum(1 for line in open(file))\n all_data = []\n all_data_no_augment = []\n train_data = []\n test_data = []\n\n with open(file, 'r', encoding=\"utf-8\") as fp:\n for line in fp:\n all_data.append(line.replace(\"\\n\", \"\"))\n\n all_data_orig = len(all_data)\n\n all_data_no_augment = [data for data in all_data if \"-f0.\" not in data and \"-f1.\" not in data\n and \"_rotate_\" not in data and \"_gaussian_blur\" not in data]\n\n while len(test_data) <= int(test_split * num_data):\n filename = all_data_no_augment[random.randrange(len(all_data_no_augment))]\n filename_no_ext = filename[:-4]\n filename_vflip = filename_no_ext + \"-f0.jpg\"\n filename_hflip = filename_no_ext + \"-f1.jpg\"\n\n if filename_vflip in all_data and filename_hflip in all_data:\n test_data.append(filename)\n test_data.append(filename_vflip)\n test_data.append(filename_hflip)\n all_data.remove(filename)\n all_data.remove(filename_vflip)\n all_data.remove(filename_hflip)\n num_data -= 3\n\n if os.path.isfile(os.path.join(output_path, \"train_valid.txt\")):\n os.remove(os.path.join(output_path, \"train_valid.txt\"))\n\n if os.path.isfile(os.path.join(output_path, \"test.txt\")):\n os.remove(os.path.join(output_path, \"test.txt\"))\n\n with open(os.path.join(output_path, \"train_valid.txt\"), 'a') as train_file:\n for line in all_data:\n train_file.write(line + \"\\n\")\n\n with open(os.path.join(output_path, \"test.txt\"), 'a') as test_file:\n for line in test_data:\n test_file.write(line + \"\\n\")\n\n train_valid_len = file_len(os.path.join(output_path, \"train_valid.txt\"))\n\n return [all_data_orig , train_valid_len]\n\ndef split_file(file, out1, out2, file_count, train_split, seed=123):\n \"\"\"Splits a file in 2 given the `percentage` to go in the large file.\"\"\"\n random.seed(seed)\n all_count = file_count[0]\n train_valid_count = file_count[1]\n\n try:\n percentage = (all_count * train_split) / train_valid_count\n print(\"Train Percentage: \" + str(percentage))\n\n except ZeroDivisionError:\n print(\"Divide by 0 error.\")\n sys.exit()\n\n train_valid_data = []\n with open(file, 'r', encoding=\"utf-8\") as fin:\n for line in fin:\n train_valid_data.append(line.replace('\\n', \"\"))\n\n random.shuffle(train_valid_data)\n split_index = int(percentage * len(train_valid_data))\n\n train_data = train_valid_data[:split_index]\n valid_data = train_valid_data[split_index:]\n\n with open(out1, 'w') as foutTrain:\n for data in train_data:\n foutTrain.write(data + '\\n')\n\n with open(out2, 'w') as foutValid:\n for data in valid_data:\n foutValid.write(data + '\\n')\n\n\ndef darknet_convert(bbox_file, output_path, classes_file, train_split=0.7, valid_split=0.2, test_split=0.1):\n\n filename_file = os.path.join(output_path, \"filename.txt\")\n seen_lines = [] # stored seen lines here so that no lines written are duplicated\n\n if train_split > 1.0 or test_split > 1.0 or valid_split > 1.0:\n print(\"One of the data split is greater than 1. Please enter correct data split again.\")\n sys.exit()\n\n if train_split < 0 or test_split < 0 or valid_split < 0:\n print(\"One of the data split is less than 0. Please enter correct data split again.\")\n sys.exit()\n\n if os.path.isfile(filename_file):\n os.remove(filename_file)\n\n with open(classes_file) as class_fp:\n for line in class_fp:\n classes.append(line.replace(\"\\n\", \"\"))\n\n if os.path.isdir(output_path):\n shutil.rmtree(output_path)\n\n os.mkdir(output_path)\n\n if os.path.isdir(os.path.join(output_path, \"label\")):\n shutil.rmtree(os.path.join(output_path, \"label\"))\n\n os.mkdir(os.path.join(output_path, \"label\"))\n\n with open(bbox_file, 'r') as fp:\n for line in fp:\n filename_no_ext = line.split(' ')[0][:-4]\n image_filename = line.split(\" \")[0]\n\n values = line.split(' ')[1].split(',')\n values[-1] = values[-1].replace('\\n', '')\n label_file = os.path.join(output_path, \"label\", os.path.basename(filename_no_ext) + '.txt')\n image_file = line.split(' ')[0]\n\n try:\n im = Image.open(image_filename)\n WIDTH, HEIGHT = im.size\n except:\n print(\"Could not find \" + image_filename + \". Please check that image exists.\")\n\n print(\"Image: \" + image_filename)\n\n print(values)\n x_center = (int(values[2]) + int(values[0])) / (2 * WIDTH)\n y_center = (int(values[3]) + int(values[1])) / (2 * HEIGHT)\n box_width = (int(values[2]) - int(values[0])) / WIDTH\n box_height = (int(values[3]) - int(values[1])) / HEIGHT\n class_index = int(classes.index(values[4]))\n\n print(\"Class index: \" + str(class_index))\n print(\"X_center: \" + str(x_center))\n print(\"Y_center: \" + str(y_center))\n print(\"Box_width: \" + str(box_width))\n print(\"Box_height: \" + str(box_height))\n print('\\n')\n\n anno = str(class_index) + \" \" + str(x_center) + \" \" + str(y_center) + \" \" + str(box_width) + \" \" + str(box_height) + '\\n'\n\n with open(filename_file, 'a') as train_fp:\n os.chmod(filename_file, stat.S_IWUSR)\n if image_file not in seen_lines:\n train_fp.write(image_file)\n train_fp.write('\\n')\n seen_lines.append(image_file)\n\n with open(label_file, 'a') as out_fp:\n out_fp.write(anno)\n\n [all_count, train_valid_count] = split_test_data(os.path.join(output_path, filename_file), output_path, test_split)\n\n print(\"All count: \" + str(all_count))\n print(\"train valid count: \" + str(train_valid_count))\n\n if all_count != 0 and split_file != 0:\n split_file(os.path.join(output_path, \"train_valid.txt\"),\n os.path.join(output_path, \"train.txt\"),\n os.path.join(output_path, \"valid.txt\"),\n [all_count, train_valid_count],\n train_split\n )\n\n move_files(output_path)\n\n if os.path.isfile(os.path.join(output_path, \"train_valid.txt\")):\n os.remove(os.path.join(output_path, \"train_valid.txt\"))\n\n os.remove(filename_file)\n","sub_path":"scripts/change_to_darknet_v2.py","file_name":"change_to_darknet_v2.py","file_ext":"py","file_size_in_byte":9065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"648576126","text":"# -*- coding: utf-8 -*-\n\nimport scrapy\nimport base64\nfrom fontTools.ttLib import TTFont\nimport io\nimport re\nfrom scrapy.selector import Selector\nfrom crawler_58city.items import HouseInfo\n\n\nclass MainSpider(scrapy.Spider):\n name = '58'\n\n def start_requests(self):\n \"\"\"\n 访问城市切换页面\n :yield: 城市切换页面\n \"\"\"\n # yield scrapy.Request(url='https://www.58.com/changecity.html', callback=self.parse_city_href)\n yield scrapy.Request(url='https://httpbin.org/get', callback=self.parse_city_href)\n\n def parse_city_href(self, response):\n \"\"\"\n 在城市切换页面中,解析并合成各城市租房页面的地址\n :yield: 各城市的租房页面\n \"\"\"\n # from scrapy.shell import inspect_response\n # inspect_response(response, self)\n s = Selector(text=response.text)\n origin = s.re(r'\"origin\": \"(.*)\"')\n self.logger.error(\"origin\", origin)\n\n # city_list = response.xpath(\"//script[position()=3]/text()\").re(r':\"(.*?)\\|.*?\"')\n # url_template = 'https://{}.58.com/chuzu/'\n # url_list = [url_template.format(city) for city in city_list]\n # for url in url_list[0:1]: # 先爬一个城市作为测试\n # yield scrapy.Request(url=url, callback=self.parse_house_list)\n\n def parse_house_list(self, response):\n \"\"\"\n 在租房页面,解析广告标题和租房价格\n \"\"\"\n # from scrapy.shell import inspect_response\n # inspect_response(response, self)\n new_response = self.cracking_font_encryption(response)\n li_list = new_response.xpath('//li[@class=\"house-cell\"]')\n # titles, prices = [], []\n for li in li_list:\n # titles.append(li.xpath('.//a[@class=\"strongbox\"]/text()').re(r'\\s*(.*?)\\s{3,}'))\n # prices.append(li.xpath('.//b[@class=\"strongbox\"]/text()').get() + \"元/月\")\n title = li.xpath('.//a[@class=\"strongbox\"]/text()').re(r'\\s*(.*?)\\s{3,}')[0]\n price = li.xpath('.//b[@class=\"strongbox\"]/text()').get() + \"元/月\"\n item = HouseInfo(title=title, price=price)\n yield item\n \"\"\"\n 翻页,直到没有“下一页”的链接\n \"\"\"\n\n def cracking_font_encryption(self, response):\n \"\"\"\n 应对字体反爬\n :param response: scrapy返回的response\n :return: 破解字体反爬后的response\n \"\"\"\n # 抓取加密字符串\n base64_str = response.xpath('//head/script[position()=2]/text()').re(r\"base64,(.*?)'\\) format\")[0]\n b = base64.b64decode(base64_str)\n font = TTFont(io.BytesIO(b))\n bestcmap = font['cmap'].getBestCmap()\n newmap = dict() # 计算正常字体的映射字典\n for key in bestcmap.keys():\n value = int(re.search(r'(\\d+)', bestcmap[key]).group(1)) - 1\n key = hex(key)\n newmap[key] = value\n response_ = response.text # 根据映射字典替换反爬字符\n for key, value in newmap.items():\n key_ = key.replace('0x', '&#x') + ';'\n if key_ in response_:\n response_ = response_.replace(key_, str(value))\n return Selector(text=response_) # 得到破解后的新response\n\n\n\n","sub_path":"crawler_58city/crawler_58city/spiders/main_spider.py","file_name":"main_spider.py","file_ext":"py","file_size_in_byte":3287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"184377516","text":"\"\"\"\r\nCount majority element in an array\r\nCount(element) >= floor(len(array) // 2)\r\n\"\"\"\r\nfrom collections import Counter\r\n\r\n\"\"\"\r\nTime Complexity O(n)\r\nSpace Complexity O(n)\r\n\r\nNote: we can only return 1 element if it exists!!!\r\nThere cannot be 2 majority elements!!!!\r\n\"\"\"\r\ndef find_majority(array):\r\n if not array:\r\n return None\r\n \r\n counter = Counter(array)\r\n majority_element = None\r\n\r\n for element in counter:\r\n if counter[element] > int(len(array) // 2):\r\n majority_element = element\r\n \r\n return majority_element\r\n\r\nprint(find_majority([2, 1, 2]))\r\n\r\n\"\"\"\r\nCan we do better???\r\nTime Complexity: O(n) : 1 time pass???\r\nSpace Complexity O(1)\r\n\r\n=> Boyer-Moore Voting Algorithm to find the majority -> distributed system\r\n\r\nIf the problem doesnt guarantee that the majority element exists\r\nThen, we have to run another the pass to confirm the majority element\r\n\"\"\"\r\ndef find_majority_2(array):\r\n if not array:\r\n return None\r\n\r\n majority_index = 0\r\n counter = 0\r\n\r\n for i in range(len(array)):\r\n if counter == 0:\r\n majority_index = i\r\n counter = 1\r\n elif array[majority_index] == array[i]:\r\n counter += 1\r\n else:\r\n counter -= 1\r\n \r\n return array[majority_index] if majority_index >= 0 else None\r\n\r\nprint(find_majority_2([2, 1, 2]))","sub_path":"LeetCode/Microsoft/majority_element.py","file_name":"majority_element.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"524896033","text":"#!/usr/bin/env python3\n\n#******************************************************************************\n# treeopener.py, provides a class to open and import tree data\n#\n# TreeLine, an information storage program\n# Copyright (C) 2015, Douglas W. Bell\n#\n# This is free software; you can redistribute it and/or modify it under the\n# terms of the GNU General Public License, either Version 2 or any later\n# version. This program is distributed in the hope that it will be useful,\n# but WITTHOUT ANY WARRANTY. See the included LICENSE file for details.\n#******************************************************************************\n\nfrom xml.etree import ElementTree\nimport xml.sax.saxutils\nimport os\nimport sys\nimport treemodel\nimport treenode\nimport nodeformat\nimport urltools\n\n\nclass TreeOpener:\n \"\"\"Class to open or import tree data files\n \n Creates a new model and provides methods for file open/import.\n \"\"\"\n def __init__(self):\n \"\"\"Initialize a TreeOpenFile object.\n \"\"\"\n self.model = treemodel.TreeModel()\n self.rootAttr = {}\n self.duplicateIdList = []\n\n def readFile(self, filePath):\n \"\"\"Open the given TreeLine file and return the resulting model.\n \n Arguments:\n filePath -- file path or file object to open\n \"\"\"\n tree = ElementTree.ElementTree()\n try:\n tree.parse(filePath)\n except ElementTree.ParseError:\n raise ParseError(_('Invalid XML file'))\n if not tree.getroot().get('item') == 'y':\n raise ParseError(_('Bad elememnt - not a valid TreeLine file'))\n version = tree.getroot().get('tlversion', '').split('.')\n try:\n version = [int(i) for i in version]\n except ValueError:\n version = []\n self.rootAttr = tree.getroot().attrib\n self.model.formats.loadAttr(self.rootAttr)\n self.loadNode(tree.getroot(), None)\n self.model.formats.updateLineParsing()\n if version < [1, 9]:\n self.convertOldFormats()\n self.convertOldNodes()\n if nodeformat.FileInfoFormat.typeName in self.model.formats:\n altFormat = self.model.formats[nodeformat.FileInfoFormat.typeName]\n self.model.formats.fileInfoFormat.duplicateFieldFormats(altFormat)\n del self.model.formats[nodeformat.FileInfoFormat.typeName]\n self.model.formats.updateDerivedRefs()\n self.model.formats.updateMathFieldRefs()\n return self.model\n\n def loadNode(self, element, parent=None):\n \"\"\"Recursively load an ElementTree node and its children.\n \n Arguments:\n element -- an ElementTree node\n parent -- the parent TreeNode (None for the root node only)\n \"\"\"\n try:\n typeFormat = self.model.formats[element.tag]\n except KeyError:\n typeFormat = nodeformat.NodeFormat(element.tag, self.model.formats,\n element.attrib)\n self.model.formats[element.tag] = typeFormat\n if element.get('item') == 'y':\n node = treenode.TreeNode(parent, element.tag, self.model,\n element.attrib)\n if parent:\n parent.childList.append(node)\n else:\n self.model.root = node\n else: # bare format (no nodes)\n node = None\n for child in element:\n if child.get('item') and node:\n self.loadNode(child, node)\n else:\n if node and child.text:\n node.data[child.tag] = child.text\n if child.get('linkcount'):\n self.model.linkRefCollect.searchForLinks(node,\n child.tag)\n typeFormat.addFieldIfNew(child.tag, child.attrib)\n if node and typeFormat.fieldDict:\n try:\n node.setUniqueId()\n except ValueError:\n oldId = node.uniqueId\n node.setUniqueId(True)\n self.duplicateIdList.append('{0} -> {1}'.format(oldId,\n node.uniqueId))\n\n def convertOldFormats(self):\n \"\"\"Convert node and field formats from old TreeLine versions.\n\n Set node parameters from old file formats, change date & time formats,\n set ID ref field.\n \"\"\"\n oldSpaceBetween = not self.rootAttr.get('nospace', '').startswith('y')\n oldFormatHtml = not self.rootAttr.get('nohtml', '').startswith('y')\n for nodeFormat in self.model.formats.values():\n nodeFormat.spaceBetween = oldSpaceBetween\n nodeFormat.formatHtml = oldFormatHtml\n for field in nodeFormat.fields():\n if field.oldRef:\n nodeFormat.idField = field\n if field.typeName == 'Date':\n field.format = field.format.replace('w', 'd')\n field.format = field.format.replace('m', 'M')\n elif field.typeName == 'Time':\n field.format = field.format.replace('M', 'm')\n field.format = field.format.replace('s', 'z')\n field.format = field.format.replace('S', 's')\n field.format = field.format.replace('AA', 'AP')\n field.format = field.format.replace('aa', 'ap')\n elif field.oldTypeName and field.oldTypeName in ('URL', 'Path',\n 'ExecuteLink',\n 'Email'):\n field.changeType('ExternalLink')\n\n def convertOldNodes(self):\n \"\"\"Convert node data from old TreeLine versions to match new formats.\n\n Fix escaping of special characters.\n \"\"\"\n for node in self.model.root.descendantGen():\n for field in node.nodeFormat().fields():\n text = node.data.get(field.name, '')\n if text:\n if field.typeName == 'Text' and not field.oldHasHtml:\n text = text.strip()\n text = xml.sax.saxutils.escape(text)\n text = text.replace('\\n', '
\\n')\n node.data[field.name] = text\n elif (field.typeName == 'ExternalLink' and\n field.oldTypeName):\n dispName = node.data.get(field.oldLinkAltField, '')\n if not dispName:\n dispName = text\n if field.oldTypeName == 'URL':\n if not urltools.extractScheme(text):\n text = urltools.replaceScheme('http', text)\n elif field.oldTypeName == 'Path':\n text = urltools.replaceScheme('file', text)\n elif field.oldTypeName == 'ExecuteLink':\n if urltools.isRelative(text):\n fullPath = which(text)\n if fullPath:\n text = fullPath\n text = urltools.replaceScheme('file', text)\n elif field.oldTypeName == 'Email':\n text = urltools.replaceScheme('mailto', text)\n node.data[field.name] = ('
{1}'.\n format(text, dispName))\n elif field.typeName == 'InternalLink':\n uniqueId = treenode.adjustId(text)\n dispName = node.data.get(field.oldLinkAltField, '')\n if not dispName:\n dispName = uniqueId\n node.data[field.name] = ('{1}'.\n format(uniqueId, dispName))\n elif field.typeName == 'Picture':\n node.data[field.name] = (''.\n format(text))\n if node.nodeFormat().fields(): # skip for dummy root\n node.updateUniqueId()\n\n\nclass ParseError(Exception):\n \"\"\"Exception raised when the file is not a valid format.\n \"\"\"\n pass\n\n\ndef which(fileName):\n \"\"\"Return the full path if the fileName is found somewhere in the PATH.\n\n If not found, return an empty string.\n Similar to the Linux which command.\n Arguments:\n fileName -- the name to search for\n \"\"\"\n extList = ['']\n if sys.platform.startswith('win'):\n extList.extend(os.getenv('PATHEXT', '').split(os.pathsep))\n for path in os.get_exec_path():\n for ext in extList:\n fullPath = os.path.join(path, fileName + ext)\n if os.access(fullPath, os.X_OK):\n return fullPath\n return ''\n","sub_path":"TreeLine/source/treeopener.py","file_name":"treeopener.py","file_ext":"py","file_size_in_byte":9062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"4352018","text":"import re\n\nimport bs4\nimport mwparserfromhell\nfrom fuzzywuzzy.fuzz import token_set_ratio\n\nfrom wikipediabase.article import get_article\nfrom wikipediabase.classifiers import SectionsClassifier\nfrom wikipediabase.exceptions import IllegalRequest, AttributeNotFound\nfrom wikipediabase.provider import provide\nfrom wikipediabase.resolvers.base import BaseResolver, check_resolver\nfrom wikipediabase.renderer import get_renderer\nfrom wikipediabase.util import remove_text_formatting_from_markup\n\n\nclass SectionResolver(BaseResolver):\n\n \"\"\"\n A resolver that gets sections from articles\n \"\"\"\n priority = 8\n\n UNWANTED_SECTIONS = SectionsClassifier.UNWANTED_SECTIONS\n\n def _should_resolve(self, cls):\n return cls == 'wikibase-sections'\n\n def heading_names_from_markup(self, symbol):\n \"\"\"\n Get heading names from markup as text. Possibly stale.\n \"\"\"\n markup = get_article(symbol).markup_source()\n headings = mwparserfromhell.parse(markup).filter_headings()\n ret = [remove_text_formatting_from_markup(h.strip(\"=\").strip())\n for h in headings]\n # remove certain unwanted sections\n unwanted_idx = map(ret.index, filter(ret.__contains__,\n self.UNWANTED_SECTIONS))\n if len(unwanted_idx) > 0:\n ret = ret[:min(unwanted_idx)]\n ret = [re.sub(\"\\{\\{anchor\\|.*?\\}\\}\", \"\", s).strip() for s in ret]\n return ret\n\n def heading_names_from_html(self, symbol):\n \"\"\"\n Get heading names from HTML as text. Always up-to-date but slower.\n \"\"\"\n ret = get_article(symbol).headings()\n # remove unwanted sections\n unwanted_idx = map(ret.index, filter(ret.__contains__,\n self.UNWANTED_SECTIONS))\n if len(unwanted_idx) > 0:\n ret = ret[:min(unwanted_idx)]\n return ret\n\n def markup_headings_to_html_headings(self, markup_headings, html_headings):\n \"\"\"\n Find a mapping from markup headings to HTML headings. Assumes that\n the section ordering is unchanged, but HTML can contain sections not\n in markup and vice versa.\n \"\"\"\n # checks whether two headings are similar enough to regard as the same\n\n def _probably_same_heading(m_heading, h_heading):\n return token_set_ratio(m_heading, h_heading) > 70\n\n # Treat the problem as a LCS (longest common subsequence) problem:\n # two headings are the \"same\" (in the LCS sense) if they are similar\n # enough. See the Wikipedia page on LCS for more details of the\n # algorithm.\n\n # If the number of sections are the same and the sections pair up\n # perfectly, then this algorithm runs in O(n) time instead of O(mn)\n # as in the general case.\n _lcs_cache = {}\n\n def _lcs(idx_m, idx_h):\n # LCS of first idx_m of markup headings and first idx_h of HTML's\n if (idx_m, idx_h) not in _lcs_cache:\n if idx_m == 0 or idx_h == 0:\n ans = []\n else:\n m_title = markup_headings[idx_m - 1]\n h_title = html_headings[idx_h - 1]\n if _probably_same_heading(m_title, h_title):\n ans = _lcs(idx_m - 1, idx_h - 1) + [(m_title, h_title)]\n else:\n ans1 = _lcs(idx_m - 1, idx_h)\n ans2 = _lcs(idx_m, idx_h - 1)\n ans = max([ans1, ans2], key=len)\n _lcs_cache[(idx_m, idx_h)] = ans\n return _lcs_cache[(idx_m, idx_h)]\n\n # convert \"subsequence\" into mapping\n pairings = _lcs(len(markup_headings), len(html_headings))\n mapping = {m: h for (m, h) in pairings}\n return mapping\n\n def _clean_html(self, symbol, raw):\n \"\"\"\n Clean the HTML text from BS4 parse tree.\n Parameters\n raw: raw input from BS4 parse tree\n Returns\n cleaned HTML text as unicode string\n \"\"\"\n if isinstance(raw, bs4.element.Comment):\n return u\"\"\n elif isinstance(raw, bs4.element.NavigableString):\n return unicode(raw).replace(\"\\n\", \"\")\n # includes bs4.BeautifulSoup\n elif isinstance(raw, bs4.element.Tag):\n # remove edit button\n edit_btn = raw.find(class_=\"mw-editsection\")\n if edit_btn:\n edit_btn.extract()\n # remove references\n for ref in raw.find_all(\"sup\", class_=\"reference\"):\n ref.extract()\n # make URLs absolute\n base_url = \"https://en.wikipedia.org\"\n article_url = \"%s/%s\" % (base_url, symbol)\n for link in raw.find_all(\"a\"):\n url = link[\"href\"]\n if url.startswith(\"/wiki/\"):\n link[\"href\"] = \"%s%s\" % (base_url, url)\n elif url.startswith(\"#\"):\n link[\"href\"] = \"%s%s\" % (article_url, url)\n # convert to unicode and remove line breaks between tags\n txt = unicode(raw)\n txt = txt.replace(\">\\n<\", \"><\")\n return txt\n else:\n # should never happen if the right version of bs4 is used\n self.log().error(\"Cannot parse HTML for section resolver due to \"\n \"unknown bs4 type. Check bs4's documentation and \"\n \"update the method.\")\n return unicode(raw)\n\n def get_section_from_markup(self, symbol, heading_idx):\n \"\"\"\n Extract section from markup. Returns markup.\n \"\"\"\n markup = mwparserfromhell.parse(get_article(symbol).markup_source())\n sections = markup.get_sections()\n return sections[heading_idx + 1]\n\n def get_section_from_html(self, symbol, heading_idx, html=None):\n \"\"\"\n Extract section from HTML.\n Parameters\n symbol: article title\n heading_idx: index of the heading in the HTML\n Optional Parameters\n html: You can choose to specify the base HTML. However, this HTML\n must only contain article content and nothing else\n Returns\n [{\"html\": (section HTML)}].\n \"\"\"\n if html is None:\n html = get_article(symbol).html_source()\n soup = bs4.BeautifulSoup(html, \"lxml\")\n soup = soup.find(id=\"mw-content-text\")\n else:\n soup = bs4.BeautifulSoup(html, \"lxml\")\n headings = soup.find_all(re.compile(\"h[2-6]\"))\n # remove the table of contents\n if headings[0].string == \"Contents\":\n headings = headings[1:]\n # get the section and its subsections\n start_elt = headings[heading_idx]\n heading_lvl = int(start_elt.name[-1])\n stop_tags = [(\"h%01d\" % d) for d in xrange(2, heading_lvl + 1)]\n ret = self._clean_html(symbol, start_elt)\n for elt in start_elt.next_siblings:\n if elt.name in stop_tags:\n break\n txt = self._clean_html(symbol, elt)\n ret += txt\n # standardize heading so top-level is always

\n if heading_lvl > 2:\n diff = heading_lvl - 2\n for d in xrange(heading_lvl, 7):\n ret = ret.replace(\"\" % d, \"\" % (d - diff))\n ret = ret.replace(\"\" % d, \"\" % (d - diff))\n # done\n return [{\"html\": ret}]\n\n @provide(name=\"sections\")\n def resolve_section(self, cls, symbol, attrs, **options):\n # parse attr\n attr = attrs.get(\"code\", attrs.get(\"rendered\"))\n if attr is None:\n raise IllegalRequest('Cannot resolve \"{}\": must include code or '\n 'rendered as attribute'.format(symbol))\n # check if the heading is found in markup\n markup_headings = self.heading_names_from_markup(symbol)\n try:\n markup_heading_idx = map(unicode.lower,\n markup_headings).index(attr.lower())\n except ValueError:\n raise AttributeNotFound('Cannot find attribute \"{}\"'.format(attr))\n # check if we can find the section in HTML\n html_headings = self.heading_names_from_html(symbol)\n markup_html_mapping = self.markup_headings_to_html_headings(\n markup_headings, html_headings)\n # get section directly from HTML\n if attr in markup_html_mapping:\n html_heading = markup_html_mapping[attr]\n heading_idx = html_headings.index(html_heading)\n return self.get_section_from_html(symbol, heading_idx)\n # can't find section in HTML -> render from markup\n else:\n markup = self.get_section_from_markup(symbol, markup_heading_idx)\n html = get_renderer().render(unicode(markup))\n return self.get_section_from_html(symbol, 0, html=html)\n\n @check_resolver\n def attributes(self, cls, symbol):\n headings = self.heading_names_from_markup(symbol)\n ret = [{\"code\": name} for name in headings]\n return ret\n","sub_path":"wikipediabase/resolvers/section.py","file_name":"section.py","file_ext":"py","file_size_in_byte":9186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"124369237","text":"import sys\nimport os, glob\nimport pdb\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy\nfrom scipy.optimize import minimize\nimport math\n\ndef gaussian(x, mean, sigma):\n return np.exp(-(x-mean)**2/(2*sigma**2))\n\ndef Tones3dgrid(latentTones, sigma): \n \n input_array_0 = np.expand_dims(gaussian(log_freq_percept, latentTones[0], sigma), axis = 1)\n input_array_1 = np.expand_dims(gaussian(log_freq_percept, latentTones[1], sigma), axis = 1)\n input_array_2 = np.expand_dims(gaussian(log_freq_percept, latentTones[2], sigma), axis = 1)\n s0 = 1/np.sum(input_array_0); s1 = 1/np.sum(input_array_1); s2 = 1/np.sum(input_array_2)\n input_array_0 *= s0; input_array_1 *= s1; input_array_2 *= s2; \n \n input_array_mat = np.expand_dims(input_array_0@input_array_1.T,axis=2)@(input_array_2.T) #p(T1,T2..|H) \n \n return input_array_mat\n\ndef posterior_array(freq_input, n_tones, p_back, log_prior):\n \"\"\"\n Arguments: \n freq_input - range of all possible frequencies (percepts?)\n p_back - prob of background\n p_low - prob of low condition\n log_prior - list of prior parameters\n \"\"\"\n \n log_prior_low_mean = log_prior[0]; log_prior_low_sigma = log_prior[2];\n log_prior_high_mean = log_prior[1]; log_prior_high_sigma = log_prior[2];\n likelihood_onetone_low = gaussian(x=freq_input, mean=log_prior_low_mean, sigma=log_prior_low_sigma)\n likelihood_onetone_high = gaussian(x=freq_input, mean=log_prior_high_mean, sigma=log_prior_high_sigma)\n likelihood_onetone_mixed_high = p_back*(1/len(freq_input)) + (1-p_back)*likelihood_onetone_high \n #mixture model with p(T|B) = 1/no. of possible freqs\n likelihood_onetone_mixed_high /= likelihood_onetone_mixed_high.sum() #normalizing\n likelihood_onetone_mixed_high = np.expand_dims(likelihood_onetone_mixed_high, axis = 1)\n likelihood_onetone_mixed_low = p_back*(1/len(freq_input)) + (1-p_back)*likelihood_onetone_low \n #mixture model with p(T|B) = 1/no. of possible freqs\n likelihood_onetone_mixed_low /= likelihood_onetone_mixed_low.sum() #normalizing\n likelihood_onetone_mixed_low = np.expand_dims(likelihood_onetone_mixed_low, axis = 1)\n \n if n_tones == 3:\n likelihood_alltones_low = (np.expand_dims(likelihood_onetone_mixed_low@np.transpose\n (likelihood_onetone_mixed_low),axis=2)\n @np.transpose(likelihood_onetone_mixed_low))\n #p(T1,T2..|L) \n likelihood_alltones_high = (np.expand_dims(likelihood_onetone_mixed_high@np.transpose\n (likelihood_onetone_mixed_high),axis=2)\n @np.transpose(likelihood_onetone_mixed_high))\n #p(T1,T2..|H) \n elif n_tones == 1:\n likelihood_alltones_low = likelihood_onetone_mixed_low\n likelihood_alltones_high = likelihood_onetone_mixed_high\n\n return [likelihood_onetone_mixed_high, likelihood_onetone_mixed_low, \n likelihood_alltones_high, likelihood_alltones_low]\n\n# define mle function\ndef MLE(params):\n [sigma_sensory, \n prob_back, \n Wconstant, W1, tau] = params # inputs are guesses for parameter values\n \n [_,_,LikelihoodLatentTonegivenHigh,LikelihoodLatentTonegivenLow] = posterior_array(log_freq_seq_array, len(trial_tones[0]), p_back=prob_back, log_prior=[2.55,2.85,0.1])\n\n LikelihoodPerceptgivenHigh = np.zeros((len(log_freq_percept),len(log_freq_percept),len(log_freq_percept)))\n LikelihoodPerceptgivenLow = np.zeros((len(log_freq_percept),len(log_freq_percept),len(log_freq_percept)))\n \n for itrue1 in range(len(log_freq_seq_array)):\n for itrue2 in range(len(log_freq_seq_array)):\n for itrue3 in range(len(log_freq_seq_array)):\n probPerceptgivenLatentTones = Tones3dgrid([log_freq_seq_array[itrue1],\n log_freq_seq_array[itrue2],\n log_freq_seq_array[itrue3]],sigma=sigma_sensory)\n LikelihoodPerceptgivenHigh += probPerceptgivenLatentTones * LikelihoodLatentTonegivenHigh[itrue1,itrue2,itrue3]\n LikelihoodPerceptgivenLow += probPerceptgivenLatentTones * LikelihoodLatentTonegivenLow[itrue1,itrue2,itrue3]\n \n neg_ll = 0; \n probability_high = np.zeros((len(trial_tones),1))\n for i_trial in range(1,len(trial_tones)):\n arePrevTrialsLow = 1-2*trial_corrans[:i_trial]\n prob_low = np.clip(Wconstant + W1*np.sum(np.flip(arePrevTrialsLow)*np.exp(-(np.arange(i_trial)+1)/tau)),\n a_min=0,a_max=1)\n probHighgivenPercept = LikelihoodPerceptgivenHigh*(1-prob_low)/\\\n (LikelihoodPerceptgivenHigh*(1-prob_low) + LikelihoodPerceptgivenLow*prob_low)\n input_array_mat = Tones3dgrid(np.array([np.log10(trial_tones[i_trial][0]),np.log10(trial_tones[i_trial][1]),\n np.log10(trial_tones[i_trial][2])]),sigma=sigma_sensory)\n probability_high[i_trial] = np.sum(np.multiply(probHighgivenPercept>0.5,input_array_mat)) \n \n if trial_behaviour[i_trial]:\n if np.isnan(np.log(probability_high[i_trial] + 0.0000001)) \\\n or np.isinf(np.log(probability_high[i_trial] + 0.0000001)) \\\n or np.isnan(np.log(1-probability_high[i_trial] + 0.0000001)) \\\n or np.isinf(np.log(1-probability_high[i_trial] + 0.0000001)):\n pdb.set_trace()\n neg_ll += -np.log(probability_high[i_trial] + 0.0000001) # if high dist is chosen by observer\n else:\n neg_ll += -np.log(1 - probability_high[i_trial] + 0.0000001) # if low dist is chosen by observer\n return(neg_ll, probability_high)\n\ndef write_into_file(params, fresult):\n \"\"\"\n New optimization algorithm: uses scipy.optimize.fmin. \n Crude grid initially and then find minimum using the function.\n \"\"\"\n\n lowMean,highMean,stdGauss = [2.55,2.85,0.1]\n stdSensory,pBack = params\n print(lowMean,highMean,stdGauss,stdSensory,pBack)\n guess_sensory_sigma = np.array([float(stdSensory)]);\n guess_p_back = np.array([float(pBack)]); \n guess_WConstant = np.arange(0.46,0.56,0.03);\n #guess_WConstant = np.arange(0.52,0.8,0.03); \n guess_W1 = np.arange(0,1.1,0.1); \n guess_tau = 10**(np.arange(-1,0.7,0.15))\n\n neg_ll_array = np.zeros((len(guess_sensory_sigma), len(guess_p_back), len(guess_WConstant), len(guess_W1), len(guess_tau)))\n for ss in range(len(guess_sensory_sigma)):\n for pb in range(len(guess_p_back)):\n for WC in range(len(guess_WConstant)):\n for W1 in range(len(guess_W1)):\n for tau in range(len(guess_tau)):\n params = [guess_sensory_sigma[ss], guess_p_back[pb], guess_WConstant[WC], guess_W1[W1], guess_tau[tau]]\n neg_ll_array[ss,pb,WC,W1,tau],_ = MLE(params) \n fresult.write(\"%s\\n\" % neg_ll_array[ss,pb,WC,W1,tau])\n fresult.flush()\n \nif __name__ == '__main__':\n \n \"\"\" \n Obtaining data from a given expt\n \"\"\"\n csv_test = pd.read_csv('/home/janakis/data/allTrials_longcontext_plow0pt70.csv')\n csv_data = pd.read_csv(sys.argv[1])\n \n \"\"\"\n Get tones and values of keys pressed\n \"\"\" \n\n test_columns = list(csv_test.columns)\n test_tones_name = test_columns.index('Name')\n test_tones_col_idx = test_columns.index('Tones')\n df_names = (csv_test.iloc[0:800,test_tones_name]).values\n df_tones = (csv_test.iloc[0:800,test_tones_col_idx]).values\n\n n_tones = 3\n n_trials = csv_data.shape[0]-47\n \n tones_array_orig = np.zeros((n_trials,n_tones))\n tones_array_idxs_keep = []\n\n for i_wav in range(804):\n if isinstance(csv_data['Name'][i_wav+46],str):\n tones_array_orig[i_wav,:] = np.array(df_tones[np.where(csv_data['Name'][i_wav+46]\\\n ==df_names)[0]][0][1:-1].split(',')).astype(float) \n tones_array_idxs_keep += [i_wav]\n\n\n df_tones = np.copy(tones_array_orig[tones_array_idxs_keep,:])\n df_corrans = np.copy(csv_data['corrAns'][46:csv_data.shape[0]])[tones_array_idxs_keep]\n df_keys = np.copy(csv_data['test_resp.keys'][46:csv_data.shape[0]])[tones_array_idxs_keep]\n \n \"\"\"\n Find no response cases in the expt\n \"\"\"\n no_response = np.intersect1d(np.where(df_keys!='h')[0],np.where(df_keys!='l')[0])\n print(\"Did not respond to: \",no_response)\n\n \"\"\"\n Convert keys ['l','h'] to [0,1] and plot p(H|T)\n \"\"\"\n corrans_num_orig = np.zeros_like(df_corrans)\n corrans_num_orig[df_corrans == 'h'] = 1\n\n keys_num_orig = np.zeros_like(df_keys)\n keys_num_orig[df_keys == 'h'] = 1\n\n corrans_num = corrans_num_orig[:800]\n keys_num = keys_num_orig[:800]\n tones_array = df_tones[:800,:]\n print(corrans_num.shape, keys_num.shape, tones_array.shape)\n print(\"Got correct: \", np.sum(keys_num==corrans_num)/len(tones_array))\n \n \"\"\"\n Latent variables\n \"\"\"\n expt_tones = np.arange(90,3000,1) #array of possible true tones\n log_freq_seq_array = np.arange(0.6,4.7,0.1)\n log_freq_percept = np.arange(0.6,4.7,0.1) # array of possible perceptual tones\n\n \"\"\"\n Experimental data variables: tones and behaviour\n \"\"\"\n idxs_with_response = np.delete(np.arange(len(tones_array)),no_response)\n trialTones = tones_array[idxs_with_response,:]\n trialBehaviour = keys_num[idxs_with_response]\n corrAns = corrans_num[idxs_with_response]\n\n print(log_freq_percept, log_freq_seq_array.shape)\n \n os.chdir(\"/home/janakis/results/longContextLowFromProlific/shortTermContext/\")\n \n \"\"\"\n Subsampling trials and behaviour\n \"\"\" \n for iteration in np.arange(0,300,30):\n if len(trialBehaviour)>iteration+500:\n trial_tones = trialTones[iteration:iteration+500,:]\n trial_behaviour = trialBehaviour[iteration:iteration+500]\n trial_corrans = corrAns[iteration:iteration+500]\n filename = sys.argv[2] + str(iteration) + \"extra.txt\"\n new_file = open(filename,\"a+\") \n write_into_file(params=[sys.argv[3],sys.argv[4]],fresult = new_file) \n \n new_file.close()\n","sub_path":"filesForTheCluster/signalModel/Analyzing_online_data_script_ShortContext_biasLow.py","file_name":"Analyzing_online_data_script_ShortContext_biasLow.py","file_ext":"py","file_size_in_byte":10323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"396114161","text":"import paho.mqtt.client as mqtt\nfrom gpiozero import Motor\nimport ultrasonic as us\n\nmotl = Motor(2, 3)\nmotr= Motor(14, 15)\n\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \"+str(rc))\n\n client.subscribe('joystick/left_right')\n client.subscribe('joystick/forward_reverse')\n client.subscribe('joystick/stop')\n\ndef on_message(client, userdata, msg):\n \n if msg.topic=='joystick/left_right':\n lr_val=float(msg.payload.decode())\n if lr_val>0.15:\n print('Go right : ',lr_val)\n motl.forward(speed=lr_val)\n motr.backward(speed=lr_val)\n elif lr_val< -0.15:\n print('Go left : ',-lr_val)\n motl.backward(speed=-lr_val)\n motr.forward(speed=-lr_val)\n \n if msg.topic=='joystick/forward_reverse':\n fwrev_val=float(msg.payload.decode())\n if fwrev_val>0.15:\n if us.get_distance()<50:\n print('[STOP] Obstacle detected')\n motl.stop()\n motr.stop()\n return \n else: \n print('Go back : ',fwrev_val)\n motl.backward(speed=fwrev_val)\n motr.backward(speed=fwrev_val)\n \n elif fwrev_val<-0.15:\n print('Go forward : ',-fwrev_val)\n motl.forward(speed=-fwrev_val)\n motr.forward(speed=-fwrev_val)\n \n if msg.topic=='joystick/stop':\n print('Motor Stop')\n motl.stop()\n motr.stop()\n\n\n\nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\nclient.connect('192.168.100.214', 1883, 60)\nclient.loop_forever()\n","sub_path":"misc/zmisc/test/robot/integr/robotctl.py","file_name":"robotctl.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"428413410","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.contrib.auth.views import login,logout\n#from django.conf import settings\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\n\nurlpatterns = patterns('',\n\turl(r'^$', 'schooladdr.indexview.index',name = 'index'),\n url(r'^index.html/$','schooladdr.indexview.index',name = 'index'),\n url(r'^MyData.html/$','schooladdr.indexview.getmydataview',name = 'MyData'),\n url(r'^MyAddrLists.html/$','schooladdr.addressview.myAddressListView',name = 'MyAddrLists'),\n #url(r'^Updatedata/$','schooladdr.indexview.postmydataview',name = 'MyData'),\n \turl(r'^AllNamecard.html/$','schooladdr.cardview.allNameCardsView',name = 'AllNamecard'),\n \turl(r'^Namecard.html/$','schooladdr.cardview.nameCardView',name='NameCard'),\n\turl(r'^AllActivities.html/$','schooladdr.indexview.allactivitiesview',name = 'AllActivities'),\n \turl(r'^Settings.html/$','schooladdr.indexview.settingsview',name = 'Settings'),\n \turl(r'^ListDetail.html/$','schooladdr.indexview.listdetailview',name = 'ListDetail'),\n url(r'^login/$','schooladdr.logview.login',name = 'login'),\n url(r'^register/$','schooladdr.logview.register',name = 'register_'),\n url(r'^accounts/login/$',login),\n url(r'^accounts/logout/$',logout),\n\n url(r'^admin/', include(admin.site.urls)),\n # Examples:\n # url(r'^$', 'schooladdr.views.home', name='home'),\n # url(r'^schooladdr/', include('schooladdr.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n # url(r'^admin/', include(admin.site.urls)),\n)\n\n#if settings.DEBUG:\n# urlpatterns += patterns('',\n# url(r'^static/(?P.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_PATH, 'show_indexes':True}),\n# )","sub_path":"schooladdr/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"402991639","text":"import json\nfrom nameko.rpc import rpc, RpcProxy\nfrom nameko.events import EventDispatcher, event_handler\nfrom nameko.web.handlers import http\n\nimport dependenciesCirculation\n\nclass CirculationService:\n name=\"circulation_service\"\n\n database = dependenciesCirculation.Database()\n\n \n\n #Publish Subscribe\n dispatch = EventDispatcher()\n\n #Handle Event (Orchestration)\n @event_handler(\"orchestration_service\", \"circulation_event\")\n def handle_event_method(self, payload):\n print(payload)\n\n\n @http('GET','/room_item_by_id//')\n def get_room_item_by_id(self, request, id_room, id_item):\n room_item = self.get_room_item_by_id(id_room, id_item)\n return json.dumps({'result': room_item})\n\n @http('POST', '/room_item')\n def add_room_item(self, request):\n data = json.loads(request.get_data(as_text=True))\n new_room_item = self.add_room_item(data['id_room'], data['id_item'])\n return new_room_item\n\n @http('POST', '/circulation')\n def add_circulation(self, request):\n data = json.loads(request.get_data(as_text=True))\n new_circulaton = self.add_circulation(data['id_room'], data['id_item'], data['id_employee'], data['id_purchase'], data['qty'], data['date'], data['status'])\n return new_circulaton\n\n @rpc\n def get_room_item_by_id(self, id_room, id_item):\n room_item = self.database.get_room_item_by_id(id_room, id_item)\n return room_item\n\n @rpc\n def add_room_item(self, id_room, id_item, qty):\n new_room_item = self.database.add_room_item(id_room, id_item, qty)\n return new_room_item\n\n @rpc\n def add_circulation(self, id_room, id_item, id_employee, id_purchase, qty, status):\n new_circulation = self.database.add_circulation(id_room, id_item, id_employee, id_purchase, qty, status)\n return new_circulation\n\n ","sub_path":"Proyek Circulation/circulation_service.py","file_name":"circulation_service.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"205568334","text":"#! /usr/bin/env python3\nimport sys\n\ndef update_status(text):\n print(\"\"\"\"\"\")\n# print(\"New status:\", text, file=sys.stderr)\n sys.stdout.flush()\n","sub_path":"cgi-bin/lib/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"134731158","text":"#!/usr/bin/python3\nimport threading, time\n\n\ndef func(string, k):\n print(string, k)\n\n time.sleep(1)\n\n\ndef main():\n thr_arr = []\n\n for i in range(5):\n th = threading.Thread(name=\"print_me\", target=func, args=(\"josue\", i))\n thr_arr.append(th)\n thr_arr[i].start()\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"worker_th.py","file_name":"worker_th.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"504067276","text":"import csv, editdistance, time\nmax_word_change = 2 # gætum svo prófað max_word_change = 3\n\n# byrjum á að hafa cmbil og rbil tiltölulega stór til að þetta taki ekki langan tíma\ncmbil = 0.01\ncmbil = 0.0009\n# eyði síðan út \n\n# fáum Ncom*Nr langan lista, fjölda tilrauna út frá því\n# höfum Ncom = 40, Nr = 20\ncmstart = 0.0005\ncmend = 0.0200\ncmbil = 0.0005\nNcom = (cmend-cmstart)/cmbil\nrstart = 0.00001\nrend = 0.001\nrbil = 0.00004\nNr = (rend-rstart)/rbil\n\n\n\ndef sum_read_in_test_data(word_count, word_frequency, following_word, common_words, rare_words):\n def exists(word):\n return following_word.get(word)\n\n\n# Assuming word exists\n def common(word):\n return word_frequency > treshold_common/word_count\n\n # Assuming word exists\n def rare(word):\n return word_frequency < treshold_rare/word_count\n\n def count_seen_wordpair(previous_word, current_word):\n # print previous_word, current_word, \"(\" + str(following_word[previous_word].get(current_word)) + \")\", \"times\"\n return following_word[previous_word].get(current_word) or 0\n\n # Assuming previous_word exists\n def best_guess(previous_word, current_word):\n least_distance = max_word_change\n guess = \"\"\n if not exists(previous_word):\n possibilities = word_frequency\n else:\n possibilities = following_word[previous_word]\n for possibility, freq in possibilities.items():\n edit_distance = editdistance.eval(possibility, current_word)\n if edit_distance < least_distance:\n least_distance = edit_distance\n guess = possibility\n return guess or current_word\n\n with open('althingi_errors/079.csv', newline='', encoding='utf-8') as csvfile:\n reader = csv.DictReader(csvfile)\n\n prev_word = \"\"\n prev_guess = \"\"\n unnoticed_errors = 0\n wrong_guesses = 0\n false_errors = 0\n total_words = 0\n for row in reader:\n before = time.process_time()\n word = row['Word']\n if word == \",\":\n continue\n if exists(word) and exists(prev_word) and (common(word) or common(prev_word)) and (rare(word) or rare(prev_word)):\n guess = word\n elif exists(prev_word) and (count_seen_wordpair(prev_word, word) > 0):\n guess = word\n elif prev_guess != prev_word and count_seen_wordpair(prev_guess, word) > 0:\n guess = word\n else:\n # We don't know if prev_word existed.\n\t\t\t\t# So let's use prev_guess to be safe.\n guess = best_guess(prev_guess, word)\n if not prev_word:\n # The first word in a sentence.\n guess.capitalize()\n #print(\"Best guess: \", guess )\n #print(\"Correct word: \", correct_word)\n #elif word != correct_word:\n #print(\"Not a real word error: \", word )\n #print(\"Correct word: \", correct_word )\n correct_word = row['CorrectWord']\n if guess != correct_word:\n if word == guess:\n unnoticed_errors += 1\n else:\n if word == correct_word:\n false_errors += 1\n else:\n wrong_guesses += 1\n total_words += 1\n prev_guess = guess\n prev_word = word\n wrong_guesses_percent = wrong_guesses/total_words*100\n false_errors_percent = false_errors/total_words*100\n unnoticed_errors_percent = unnoticed_errors/total_words*100\n print(\"Wrong guesses:\", wrong_guesses_percent)\n print(\"False errors:\", false_errors_percent)\n print(\"Unnoticed errors:\", unnoticed_errors_percent)\n print()\n print(\"Duration:\", time.process_time() - before)\n return wrong_guesses_percent + false_errors_percent + unnoticed_errors_percent\n\nthresholds_errors = []\n# verður listi af [treshold_common, treshold_rare, errorsum]\nfor treshold_common in range(cmstart, cmend, cmbil):\n for treshold_rare in range(rstart, rend, rbil):\n errorsum = sum_read_in_test_data(word_count, word_frequency, following_word, common_words, rare_words) # breytt til að gefa summu\n thresholds_errors.append([treshold_common, treshold_rare, errorsum])\n\nminerror = thresholds_errors[0][2]\nfor j in range(0,len(thresholds_errors)):\n if(thresholds_errors[j][2] < minerror):\n minerror = thresholds_errors[j][2]\n mintresholds = [thresholds_errors[j][0], thresholds_errors[j][1]]\n\nprint(\"common: \" + str(mintresholds[0]) + \"rare: \" + str(mintresholds[1]))\n\n\n","sub_path":"treshold_test.py","file_name":"treshold_test.py","file_ext":"py","file_size_in_byte":4737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"46834611","text":"# Python\ndef balance(t):\n # Initial balance is 25\n if ( t == 0):\n return 25\n else:\n return balance(t-1)+10\n\ndef factorial(num):\n if ( num == 1):\n return 1;\n else:\n return factorial(num-1)*num\n\ndef quadratic(num, factor):\n if (factor == 1):\n return num\n else:\n return quadratic(num, factor-1)*num\n\ndef main():\n print(balance(3))\n print(factorial(9))\n print(quadratic(4,5))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"randomStuff/recursive.py","file_name":"recursive.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"325404625","text":"#!/usr/bin/python3\n\nimport time\nimport board\nimport neopixel\nimport copy\nfrom random import random\nimport math\nfrom pprint import pprint\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-b', '--brightness', default=0.3, type=float, help='how bright you is?')\nparser.add_argument('-n', '--num_pixels', default=100, type=int, help='how many led you got?')\nparser.add_argument('-s', '--speed', default=0.001, type=float, help='how fast it go?')\nparser.add_argument('-o', '--offset', default=0, type=int, help='how fast it go?')\nargs = parser.parse_args()\n\n# Choose an open pin connected to the Data In of the NeoPixel strip, i.e. board.D18\n# NeoPixels must be connected to D10, D12, D18 or D21 to work.\npixel_pin = board.D21\n\n# The number of NeoPixels\nnum_pixels = args.num_pixels\n\n# The order of the pixel colors - RGB or GRB. Some NeoPixels have red and green reversed!\n# For RGBW NeoPixels, simply change the ORDER to RGBW or GRBW.\nORDER = neopixel.GRB\n\ndef wheel(pos):\n # Input a value 0 to 255 to get a color value.\n # The colours are a transition r - g - b - back to r.\n if pos < 0 or pos > 255:\n r = g = b = 0\n elif pos < 85:\n r = int(pos * 3)\n g = int(255 - pos * 3)\n b = 0\n elif pos < 170:\n pos -= 85\n r = int(255 - pos * 3)\n g = 0\n b = int(pos * 3)\n else:\n pos -= 170\n r = 0\n g = int(pos * 3)\n b = int(255 - pos * 3)\n return (r, g, b) if ORDER in (neopixel.RGB, neopixel.GRB) else (r, g, b, 0)\n\ndef shift_array(array, count):\n temp = array[count::] + array[0:count]\n shifted = copy.deepcopy(array)\n for i, val in enumerate(temp[0:len(array)-1]):\n shifted[i] = val\n return shifted\n\n\ndef mirror_array(pivot, array):\n bottom = array[0:pivot]\n top = array[pivot::-1]\n full = bottom + top\n mirrored = copy.deepcopy(array)\n for i, val in enumerate(full[0:len(array)-1]):\n mirrored[i] = val\n return mirrored\n\ndef rainbow_cycle(wait):\n pivot = math.floor( len(pixels)/2 )\n while True:\n for j in range(255):\n for i in range(num_pixels):\n pixel_index = (i * 256 // num_pixels) + j\n pixels[i] = wheel(pixel_index & 255)\n mirror_pixels = mirror_array(pivot, pixels)\n if abs(args.offset) > 0:\n shift_pixels = shift_array(mirror_pixels, args.offset)\n shift_pixels.show()\n else:\n mirror_pixels.show()\n time.sleep(wait)\n\nif __name__ == \"__main__\":\n # use with so ctrl-c kills the lights when done.\n with neopixel.NeoPixel(pixel_pin, num_pixels, brightness=args.brightness, auto_write=False, pixel_order=ORDER) as pixels:\n rainbow_cycle(args.speed)\n","sub_path":"mirror_rainbow_third_up.py","file_name":"mirror_rainbow_third_up.py","file_ext":"py","file_size_in_byte":2788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"197815813","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 1 19:07:52 2016\n\n@author: sam\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.backends.backend_pdf as backend_pdf\nimport json, skrf, CP\nfrom numpy.polynomial import Polynomial\n\nN = 9\ntopology = np.eye(N + 2, dtype=int)\ntopology[0, 0] = 0\ntopology[-1, -1] = 0\nfor i in np.arange(N + 1):\n topology[i, i + 1] = 1\n topology[i + 1, i] = 1\n#topology[1, 3] = 1\n#topology[3, 1] = 1\n#topology[1, 4] = 1\n#topology[4, 1] = 1\n#topology[4, 6] = 1\n#topology[6, 4] = 1\n\nsparaFolder = \"C:\\\\Users\\sam\\Documents\\\\User\\Embeded\\ServerApp\\Heroku\\S_file_for_capture\"\nwith open(\"%s\\\\\\\\%s\" % (sparaFolder, \"_s_parameter.txt\"), 'r') as json_file:\n testCases = np.array(json.load(json_file))\n \nplt.close(\"all\")\nselectCases = np.array([12])\n#selectCases = np.arange(1, 24)\nwith backend_pdf.PdfPages(\"%s\\\\\\\\%s\" % (sparaFolder, \"summary.pdf\")) as pdf:\n for testCase in testCases[selectCases - 1]:\n ntwk = skrf.Network(\"%s\\\\\\\\%s\" % (sparaFolder, testCase[\"fileName\"]))\n freq = ntwk.frequency.f\n S11 = ntwk.s[:, 0, 0]\n S21 = ntwk.s[:, 1, 0]\n \n numDecimals = 6\n S11_db = np.around(20 * np.log10(np.abs(S11)), numDecimals)\n S21_db = np.around(20 * np.log10(np.abs(S21)), numDecimals)\n S11_angRad = np.around(np.angle(S11), numDecimals)\n S21_angRad = np.around(np.angle(S21), numDecimals)\n \n S11_amp = 10 ** (S11_db / 20)\n S11 = S11_amp * (np.cos(S11_angRad) + 1j * np.sin(S11_angRad))\n S21_amp = 10 ** (S21_db / 20)\n S21 = S21_amp * (np.cos(S21_angRad) + 1j * np.sin(S21_angRad))\n \n f0 = testCase[\"f0\"]\n bw = testCase[\"BW\"]\n w1 = testCase[\"f0\"] - testCase[\"BW\"] / 2\n w2 = testCase[\"f0\"] + testCase[\"BW\"] / 2\n normalizedFreq = np.real(CP.NormalizeFreq(freq, w1, w2))\n N = testCase['N']\n numZeros = testCase['Nz']\n filterOrder = np.hstack((np.zeros((N, )), 2 * np.ones((numZeros, ))))\n \n extractMethod = 6\n isSymmetric = (testCase['isSymmetric'] == 1)\n captureStartFreq = testCase['captureStartFreq']\n captureStopFreq = testCase['captureStopFreq']\n fc = f0 / 2\n epsilon, epsilonE, Qu, coefF, coefP, rootE, port1, port2 = CP.S2FP(freq, S21, S11, filterOrder, w1, w2, fc=fc, method=extractMethod, startFreq=captureStartFreq, stopFreq=captureStopFreq, isSymmetric=isSymmetric)\n \n polyF = Polynomial(coefF)\n polyP = Polynomial(coefP)\n polyE = Polynomial.fromroots(rootE)\n \n rootF = polyF.roots()\n rootP = polyP.roots()\n \n matrixMethod = 5\n transversalMatrix = CP.FPE2M(epsilon, epsilonE, coefF, coefP, rootE, method=matrixMethod)\n# print(np.round(transversalMatrix, 3))\n \n# extractedMatrix, msg = CP.FPE2MComprehensive(epsilon, epsilonE, rootF, rootP, rootE, topology, method = matrixMethod)\n# arrowM = CP.RotateM2Arrow(transversalMatrix, isComplex = True)\n# ctcqM, ctcqPoint = CP.RotateArrow2CTCQ(arrowM, topology, rootP)\n# print(np.round(np.real(transversalMatrix), 3))\n# print(np.round(np.imag(transversalMatrix), 4))\n# print(np.round(np.real(arrowM), 2))\n# print(np.round(np.imag(arrowM), 4))\n# print(np.round(np.real(ctcqM), 2))\n# print(np.round(np.imag(ctcqM), 4))\n \n port1[\"L\"] *= 1.2\n port1[\"phi\"] += 0.6\n S11_new, S21_new = CP.FPE2S(epsilon, epsilonE, coefF, coefP, rootE, normalizedFreq - 1j * f0 / (bw * Qu))\n S21_new, S11_new = CP.CM2S(transversalMatrix, normalizedFreq - 1j * f0 / (bw * Qu))\n S11_new, S21_new = CP.embedS(freq, S11_new, S21_new, fc, port1, port2)\n \n fig = plt.figure(testCase[\"No\"])\n plt.subplot(2, 2, 1)\n plt.plot(normalizedFreq, 20*np.log10(np.abs(S11)), 'o');\n plt.plot(normalizedFreq, 20*np.log10(np.abs(S11_new)), '*');\n plt.title('S11(dB)')\n plt.subplot(2, 2, 3)\n plt.plot(normalizedFreq, np.angle(S11, deg=True), 'o');\n plt.plot(normalizedFreq, np.angle(S11_new, deg=True), '*');\n plt.title('S11(degree)')\n plt.subplot(2, 2, 2)\n plt.plot(normalizedFreq, 20*np.log10(np.abs(S21)), 'o');\n plt.plot(normalizedFreq, 20*np.log10(np.abs(S21_new)), '*');\n plt.title('S21(dB)')\n plt.subplot(2, 2, 4)\n plt.plot(normalizedFreq, np.angle(S21, deg=True), 'o');\n plt.plot(normalizedFreq, np.angle(S21_new, deg=True), '*');\n plt.title('S21(degree)')\n \n# pdf.savefig(fig)","sub_path":"public/DemoFilterStudy/python/test_c.py","file_name":"test_c.py","file_ext":"py","file_size_in_byte":4589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"301860064","text":"from pprint import pprint\n\nH, W = map(int, input().split())\n\nS = []\nS.append(list('#'*(W+2)))\nfor h in range(H):\n tmp = input()\n tmp = '#'+tmp+'#'\n S.append(list(tmp))\nS.append(list('#'*(W+2)))\n\nans = 0\nfor h in range(1, H+1):\n for w in range(1, W+1):\n if S[h][w] == '#':\n continue\n\n if S[h][w+1] == '.':\n ans += 1\n if S[h][w-1] == '.':\n ans += 1\n if S[h+1][w] == '.':\n ans += 1\n if S[h-1][w] == '.':\n ans += 1\nprint(ans//2)\n","sub_path":"other/hhkb2020_b.py","file_name":"hhkb2020_b.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"345564053","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n# https://github.com/fmyblack/naoc_tab_web.git\r\n\r\nfrom flask import Flask, request, render_template\r\nimport randpic\r\nimport record\r\n\r\napp = Flask(__name__)\r\n\r\n## login\r\n@app.route('/login', methods=['GET'])\r\ndef login_form():\r\n return render_template('login.html')\r\n\r\n@app.route('/signin', methods=['GET','POST'])\r\ndef loginned():\r\n username = request.form['username'] if 'username' in request.form else ''\r\n gender = request.form['gender'] if 'gender' in request.form else ''\r\n age = request.form['age'] if 'age' in request.form else ''\r\n info={'username':username,'gender':gender,'age':age}\r\n record.recorduser(info)\r\n return render_template('table.html', pic=randpic.randfile())\r\n\r\n@app.route('/recordCompareResult', methods=['GET','POST'])\r\ndef recordResult():\r\n unnatural = '0' if 'unnatural' in request.form else '1'\r\n not_callout = '0' if 'not_callout' in request.form else '1'\r\n callout = request.form['callout'] if 'callout' in request.form else ''\r\n picinfo = request.form['pic']\r\n info = (unnatural, not_callout, picinfo, callout)\r\n record.recordpicinfo(info)\r\n return render_template('table.html', pic=randpic.randfile())\r\n\r\nif __name__ == '__main__':\r\n app.run(host=\"0.0.0.0\")\r\n","sub_path":"table/src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"216616408","text":"import sys\r\n\r\nfrom . import (abandon, bed, brain, # noqa: F401\r\n byemom, disability, facts, gay, hitler, invert, jail,\r\n quote, shit, sickfilth, slap, spank, trash, trigger, tweet, ugly,\r\n warp, whodidthis, magik, deepfry, brazzers, cancer, cry, dab,\r\n delete, door, egg, failure, fakenews, fedora, floor, laid, note,\r\n ohno, plan, rip, satan, savehumanity, thesearch, dank, salty, screams,\r\n changemymind, balloon, knowyourlocation, madethis, humansgood, roblox,\r\n wanted, boo, armor, slapsroof, youtube, bongocat, unpopular, vr, affect, surprised, equalizer)\r\n\r\nendpoints = {}\r\n\r\n\r\nfor e in filter(lambda module: str(module).startswith('endpoints.'), sys.modules):\r\n endpoint = sys.modules[e].setup()\r\n endpoints.update({endpoint.name: endpoint})\r\n","sub_path":"endpoints/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"282380428","text":"import glob\nimport os\nimport PyPDF2\nimport md2pdf.core as md2pdf\n\n\ndef convert_md_to_pdf(dirname):\n original_dir = os.getcwd()\n\n os.chdir(dirname)\n for file in glob.glob('*.md'):\n pdf_list = glob.glob('*.pdf')\n new_filename = file.replace('.md', '.pdf')\n if new_filename not in pdf_list and new_filename.lower().replace(' ', '-') not in pdf_list:\n md2pdf.md2pdf(new_filename, md_file_path=file)\n\n os.chdir(original_dir)\n\n\ndef merge_pdfs(dirname, output):\n original_dir = os.getcwd()\n files = []\n pdf_writer = PyPDF2.PdfFileWriter()\n\n os.chdir(dirname)\n for file in glob.glob('*.pdf'):\n if file != output:\n files.append(file)\n\n files.sort(key=lambda x: str(x.lower()).replace(' ', '-'))\n for file in files:\n pdf_reader = PyPDF2.PdfFileReader(file)\n\n for page in range(pdf_reader.getNumPages()):\n # Add each page to the writer object\n pdf_writer.addPage(pdf_reader.getPage(page))\n\n # Write out the merged PDF\n with open(output, 'wb') as out:\n pdf_writer.write(out)\n\n os.chdir(original_dir)\n\n\nif __name__ == '__main__':\n directory = os.environ.get('MERGE_PDFS_DIRECTORY')\n filename = os.environ.get('MERGE_PDFS_FILENAME')\n convert_md_to_pdf(directory)\n merge_pdfs(directory, filename)\n","sub_path":"merge_pdfs.py","file_name":"merge_pdfs.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"49344137","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom .seq2seq import Seq2Seq\nfrom .recurrent import RecurrentAttentionDecoder, RecurrentEncoder\nfrom torchvision.models import resnet\n\n\n# models = dict(**resnet.__dict__, **vgg.__dict__)\n\n\nclass ResNetCaptionGenerator(Seq2Seq):\n\n def __init__(self, vocab_size, hidden_size=256, model_name='resnet50',\n num_layers=2, bias=True, train_cnn=False, dropout=0, tie_embedding=False):\n super(ResNetCaptionGenerator, self).__init__()\n self.train_cnn = train_cnn\n self.encoder = resnet.__dict__[model_name](pretrained=True)\n self.decoder = RecurrentAttentionDecoder(vocab_size, hidden_size=hidden_size,\n tie_embedding=tie_embedding, context_size=2048,\n num_layers=num_layers, bias=bias, dropout=dropout)\n\n def parameters(self):\n if self.train_cnn:\n return super(ResNetCaptionGenerator, self).parameters()\n else:\n return self.decoder.parameters()\n\n def named_parameters(self):\n if self.train_cnn:\n return super(ResNetCaptionGenerator, self).named_parameters()\n else:\n return self.decoder.named_parameters()\n\n def encode(self, x, hidden=None, devices=None):\n if not self.train_cnn:\n self.encoder.eval()\n for p in self.encoder.parameters():\n p.requires_grad = False\n x = x.squeeze(0)\n x = self.encoder.conv1(x)\n x = self.encoder.bn1(x)\n x = self.encoder.relu(x)\n x = self.encoder.maxpool(x)\n\n x = self.encoder.layer1(x)\n x = self.encoder.layer2(x)\n x = self.encoder.layer3(x)\n x = self.encoder.layer4(x)\n return x, None\n\n def bridge(self, context):\n context, hidden = context\n B, C, H, W = list(context.size())\n context = context.view(B, C, H * W) \\\n .transpose(0, 1) \\\n .transpose(0, 2) # H*W x B x C\n return (context, hidden)\n\n def generate(self, inputs, context, get_attention=False):\n return self.decoder(inputs, context, get_attention=get_attention)\n","sub_path":"seq2seq/models/caption_generator.py","file_name":"caption_generator.py","file_ext":"py","file_size_in_byte":2215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"63204741","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 28 11:49:03 2018\n\n@author: praveen\n\"\"\"\nWELCOME_SUGGESTIONS=[\n u\"do your homework\",\n u\"go to class\",\n u\"take a quiz\",\n u\"list my classes\",\n u\"read announcements\"\n]\n\nWELCOME_TEXT=[\n u'Do your homework, or review a lesson,\\\n ah maybe a quick quiz',\n u'Do your homework, or read a lesson,\\\n ah maybe a quick quiz',\n u'Do your homework, or read a lesson,\\\n ah maybe a quick quiz',\n u'Do your homework, or read a lesson,\\\n ah maybe a quick quiz',\n u'Do your homework, or read a lesson,\\\n ah maybe a quick quiz',\n u'Do your homework, or read a lesson,\\\n ah maybe a quick quiz'\n]\n\n# 0:user \nWELCOME_BASIC=[\n u'Hello {0}, every day is a learning day \\\n ',\n u'Padawan {0}, so eager to learn you are let the learning begin',\n u'{0}, kindle your curiosity',\n u'{0}, I can help you with ',\n u'{0}, let us begin with '\n]\n\nWELCOME_SECOND_LOGON=[\n u\"Welcome back {0}, how can I help you?\", \n u\"Welcome back, start from where you left off?\"\n]\n\n# 0:user, 1:# of announcements\nUNREAD_ANNOUNCEMENTS=[\n u'Hey {0}, you have {1} new announcements',\n u'{0}, {1} new announcements'\n]\n\n# 0:user, 1:announcement\nUNREAD_ANNOUNCEMENT=[\n u'Hey {0}, an announcement for you',\n u'{0}, you have one announcement'\n]\n\nNO_UNREAD_ANNOUNCEMENTS=[\n u'No new announcements for you'\n]\n\nNO_HOMEWORK=[\n u'{0}, you have no homework today',\n u'{0}, no homework today'\n]\n\n# 0:user, 1:#of assignments\nPENDING_HOMEWORKS=[\n u'{0}, you have {1} assignments pending, choose to get started',\n u'{0}, {1} assignments due'\n]\n\n# 0:user, 1:assignment-title\nPENDING_HOMEWORK=[\n u'{0}, assignment {1} pending, begin now?',\n u'{0}, do you want to start your assignment {1} now ?'\n]\n\nCOURSE_SELECT=[\n u'which class would you want to begin with ?',\n u'select a class to start ',\n u'you\\'re enrolled for the following, select one'\n]\n\nLESSON_SELECT=[\n u'which lesson do you want to study?',\n u'Here are your lessons, select one'\n]\n\nQUIZ_SELECT=[\n u'which quiz do you want to take?',\n u'Here are your quizzes, select one'\n]\n\nLESSON_ACTIVITY_SELECT=[\n u'Lesson has these study materials, choose one',\n u'Here are your study materials, select one'\n]\n\nLESSON_ACTIVITY_DO=[\n u'Do this activity now'\n]\n\nINCORRECT_ANSWER=[\n u'INCORRECT\\nCorrect answer for question - {0} is {1}'\n]\n\nCORRECT_ANSWER=[\n u'CORRECT\\nCorrect answer for - {0} is indeed {1}',\n u'RIGHT\\nanswer for - {0} is {1}'\n]\n\nQUIZ_REPORT=[\n u'You got {0} out of {1} right'\n]\n\nCONCEPT_DEFINITION_UNKNOWN=[\n u'I am afraid, I don\\'t know what {0} means, do check with your teacher or elders.',\n u'Sorry, don\\'t know what {0} is'\n]\n\nGENERAL_FALLBACKS=[\n u'I didn\\'t get that. Can you say it again?',\n u'Ohh! I missed what you said. Say it again?',\n u'Sorry, could you say that again?',\n u'Sorry, can you say that again?',\n u'Can you say that again?',\n u'Sorry, I didn\\'t get that.',\n u'Sorry, what was that?',\n u'One more time?',\n u'Say that again?',\n u'I didn\\'t get that.',\n u'I missed that.',\n u'Couldn\\'t understand, try again?'\n]\n","sub_path":"response_generators/messages_hogwarts.py","file_name":"messages_hogwarts.py","file_ext":"py","file_size_in_byte":4520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"247743987","text":"from django.urls import path\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n path(\"home/\", views.home, name='home'),\r\n path(\"about/\", views.about, name='about'),\r\n path(\"compile/\", views.comp, name='compile'),\r\n path(\"del/\",views.delet,name='delet'),\r\n path(\"cross/\",views.cross,name='cross'),\r\n]\r\n","sub_path":"to_do_list/todolist/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"572926063","text":"import tensorflow as tf\nimport Losses\n\nclass Learner(object):\n \"\"\"\n A base learner for tensorflow.\n Stores all the cruft general to all models.\n - saving\n - optimiser\n - learning rate\n - batch size\n - ...\n - manage the session??\n \"\"\"\n def __init__(self,shape = None, \n act_fn = None, loss_fn = None,\n batch_size = 50, dropout = False, keep_prob = 1.0,\n learning_rate = 0.0005, decay = 1.0, momentum = 0.0, opt = tf.train.MomentumOptimizer,\n summaries = False, log_dir = 'tmp/Net'):\n \n #architecture params\n self.shape = shape #first tuple is the shape of the input\n self.act_fn = act_fn\n \n #more params\n self.loss_fn = loss_fn\n self.batch_size = batch_size\n self.dropout = dropout\n self.keep_prob = keep_prob\n \n #training params\n self.learning_rate = learning_rate\n self.decay = decay\n self.momentum = momentum\n self.opt = opt(learning_rate,momentum=momentum)\n self.global_step = tf.Variable(0, trainable=False)\n \n #tensorboard params\n self.summaries = summaries\n self.log_dir = log_dir\n \n def save(self):\n #sort out existing saved data/models\n if tf.gfile.Exists(self.log_dir):\n tf.gfile.DeleteRecursively(self.log_dir)\n tf.gfile.MakeDirs(self.log_dir)\n \n def summarise_grads(self,cost):\n #Get the gradients wrt to cost\n #(before they are applied) \n #and add them to a summary\n with tf.name_scope('gradients'):\n grads_and_vars = opt.compute_gradients(cost,tf.trainable_variables())\n for grad,var in range(grads_and_vars):\n tf.histogram_summary('Grad'+var.name,grad)\n #update = opt.apply_gradients(grads_and_vars,global_step=global_step)\n \n def train(self):\n with tf.Session() as sess:\n pass\n \nclass Aversarial(Learner):\n \"\"\"\n A generative adversarial network has;\n - a generative net\n - a discriminative net\n - a loss that is ???\n \"\"\"\n def __init__(self,encoder,decoder,\n shape = [784,10], act_fn = tf.nn.relu,\n batch_size = 50, dropout = False,\n learning_rate = 0.0005, decay = 1.0, momentum = 0.0, opt = tf.train.MomentumOptimizer,\n summaries = False, log_dir = 'tmp/AE'):\n \n Net.__init__(self, shape, act_fn, batch_size, dropout, learning_rate, decay, momentum, opt, summaries, log_dir)\n \n #Define all the variables and placeholders\n self.inputs = tf.placeholder(tf.float32,shape=self.shape)\n self.Gen = Generative()\n self.Dis = Discriminative()\n \n #Build the computational graph\n with tf.name_scope('Aversarial'):\n self.bottle = self.encoder(self.inputs)\n self.out = self.decoder(self.bottle)\n self.error = SquaredError(data,self.out)\n self.train_step = self.opt.minimise(self.error)","sub_path":"LearnerClass.py","file_name":"LearnerClass.py","file_ext":"py","file_size_in_byte":3104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"75231277","text":"# -*- coding: utf-8 -*-\n\nfrom datetime import datetime\nfrom bson import ObjectId\n\nfrom corelib.store import get_cursor\nfrom model.photo import Photo\nfrom model.user import User\n\n\nclass Comment(object):\n\n table = 'comment'\n\n def __init__(self, id, photo_id, author_id, text, create_time):\n self.id = id\n self.photo_id = photo_id\n self.author_id = author_id\n self.text = text\n self.create_time = create_time\n\n @property\n def author(self):\n return self.author_id and User.get(self.author_id)\n\n @property\n def photo(self):\n return self.photo_id and Photo.get(self.photo_id)\n\n @classmethod\n def initialize(cls, item):\n if not item:\n return None\n id = str(item.get('_id'))\n photo_id = item.get('photo_id')\n author_id = item.get('author_id')\n text = item.get('text')\n create_time = item.get('create_time')\n return cls(id, photo_id, author_id, text, create_time)\n\n @classmethod\n def get(cls, id):\n query = {'_id': ObjectId(id)}\n item = get_cursor(cls.table).find_one(query)\n return cls.initialize(item)\n\n @classmethod\n def gets_by_photo(cls, photo_id, start=0, limit=10):\n query = {'photo_id': photo_id}\n rs = get_cursor(cls.table).find(query).sort('create_time', -1)\\\n .skip(start).limit(limit)\n return filter(None, [cls.initialize(r) for r in rs])\n\n @classmethod\n def get_count_by_photo(cls, photo_id):\n query = {'photo_id': photo_id}\n return get_cursor(cls.table).find(query).count()\n\n @classmethod\n def new(cls, photo_id, author_id, text):\n item = {\n 'photo_id': photo_id,\n 'author_id': author_id,\n 'text': text,\n 'create_time': datetime.now()\n }\n id = get_cursor(cls.table).insert(item, safe=True)\n if id:\n return cls.get(id)\n return None\n\n @classmethod\n def delete(cls, id):\n query = {'_id': ObjectId(id)}\n get_cursor(cls.table).remove(query, safe=True)\n\n @classmethod\n def gets(cls, ids):\n query = {'_id': {'$in': [ObjectId(id) for id in ids]}}\n rs = get_cursor(cls.table).find(query)\n return filter(None, [cls.initialize(r) for r in rs])\n\n","sub_path":"model/comment.py","file_name":"comment.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"571159017","text":"# -*- coding: utf-8 -*-\nimport scrapy\n# import csv\nimport re\n\nfrom CVE_DETAILS import settings\nfrom CVE_DETAILS.items import CveDetailsItem\n# from scrapy import signals\n# from scrapy.xlib.pydispatch import dispatcher\n\n\nclass CveSpider(scrapy.Spider):\n\tname = \"cve\"\n\tallowed_domains = 'https://www.cvedetails.com'\n\tstart_urls = [\n\t\t\"https://www.cvedetails.com/vulnerability-list.php?vendor_id=1802&product_id=3085&version_id=&page=%s&hasexp=0&opdos=0&opec=0&opov=0&opcsrf=0&opgpriv=0&opsqli=0&opxss=0&opdirt=0&opmemc=0&ophttprs=0&opbyp=0&opfileinc=0&opginf=0&cvssscoremin=0&cvssscoremax=0&year=0&month=0&cweid=0&order=1&trc=77&sha=49c347e6d8a9f01c0e18c15a95582d3519d0e88f\" % page for page in range(1,3)\n\t]\n\n\t# CSV_TITLE = [\n\t\t\t# \"CVE ID\", \"CWE ID\", \"No of Exploits\", \"Vulnerability Types\", \"Publish Date\", \"Update Date\", \"Score\", \n\t\t\t# \"Gained Access Level\", \"Access\", \"Complexity\", \"Authentication\", \"Conf\", \"Integ\", \"Avail\", \"Summary\"\n\t# ]\n\t\t\t\n\t# def __init__(self):\n\t\t# dispatcher.connect(self.spider_closed, signals.spider_closed)\n\t\t# self.csv_file = open(\"Results.csv\", \"wb\")\n\t\t# self.csv_wr = csv.writer(self.csv_file, quoting=csv.QUOTE_ALL)\n\t\t# self.csv_wr.writerow(self.CSV_TITLE)\n\t\t\n\t# def spider_closed(self, spider):\n\t\t# self.csv_file.close()\n\n\tdef parse(self, response):\n\t\t# item = []\n\t\titems = CveDetailsItem()\n\t\tfor sel in response.xpath('//table[@class=\"searchresults sortable\"]//tr'):\n\t\t\tfor CVE_ID in sel.xpath('./td[2]/a/text()').extract():\n\t\t\t\titems['CVE_ID'] = CVE_ID\n\t\t\tfor CWE_ID in sel.xpath('./td[3]/a/text()').extract():\n\t\t\t\titems['CWE_ID'] = CWE_ID\n\t\t\tfor No_of_Exploits in sel.xpath('./td[4]/text()').extract():\n\t\t\t\titems['No_of_Exploits'] = No_of_Exploits\n\t\t\tfor Vulnerability_Types in sel.xpath('./td[5]/text()').extract():\n\t\t\t\tVulnerability_Types = re.sub(r'^\\s+','',Vulnerability_Types)\n\t\t\t\titems['Vulnerability_Types'] = Vulnerability_Types\n\t\t\tfor Publish_Date in sel.xpath('./td[6]/text()').extract():\n\t\t\t\titems['Publish_Date'] = Publish_Date\n\t\t\tfor Update_Date in sel.xpath('./td[7]/text()').extract():\n\t\t\t\titems['Update_Date'] = Update_Date\n\t\t\tfor Score in sel.xpath('./td[8]/div/text()').extract():\n\t\t\t\titems['Score'] = Score\n\t\t\tfor Gained_Access_Level in sel.xpath('./td[9]/text()').extract():\n\t\t\t\titems['Gained_Access_Level'] = Gained_Access_Level\n\t\t\tfor Access in sel.xpath('./td[10]/text()').extract():\n\t\t\t\titems['Access'] = Access\n\t\t\tfor Complexity in sel.xpath('./td[11]/text()').extract():\n\t\t\t\titems['Complexity'] = Complexity\n\t\t\tfor Authentication in sel.xpath('./td[12]/text()').extract():\n\t\t\t\titems['Authentication'] = Authentication\n\t\t\tfor Conf in sel.xpath('./td[13]/text()').extract():\n\t\t\t\titems['Conf'] = Conf\n\t\t\tfor Integ in sel.xpath('./td[14]/text()').extract():\n\t\t\t\titems['Integ'] = Integ\n\t\t\tfor Avail in sel.xpath('./td[15]/text()').extract():\n\t\t\t\titems['Avail'] = Avail\n\t\t\tfor Summary in sel.xpath('./td[@class=\"cvesummarylong\"]/text()[normalize-space()]').extract():\n\t\t\t\tSummary = re.sub(r'^\\s+','',Summary)\n\t\t\t\titems['Summary'] = Summary\n\t\t\t\t\n\t\t\t\t# item.append(items)\n\t\t\t\t# self.csv_wr.writerow([CVE_ID, CWE_ID, No_of_Exploits, Vulnerability_Types, Publish_Date, Update_Date, Score, Gained_Access_Level, Access, Complexity, Authentication, Conf, Integ, Avail, Summary])\n\t\t\t\tyield items","sub_path":"CVE+Websites/CVE_DETAILS_Original/CVE_DETAILS/CVE_DETAILS/spiders/cve.py","file_name":"cve.py","file_ext":"py","file_size_in_byte":3242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"193028952","text":"\"\"\" SimpleVia_Boundaries.py ----------------------------------------------------\nDescription:\n This script adds the necessary boundaries in the SimpleVia project\n-----------------------------------------------------------------------------\"\"\"\n\n# The project and model should be already selected -----------------------------\noDesktop.RestoreWindow()\noProject = oDesktop.GetActiveProject()\noDesign = oProject.GetActiveDesign()\noEditor = oDesign.SetActiveEditor(\"3D Modeler\")\n\n# To change arrays to be used in the boundary condition selection\nfrom System import Array\n\n\n# Select the outer faces for D00 -----------------------------------------------\n\n# Select all the D00 elements\naD00 = oEditor.GetMatchedObjectName(\"D00*\")\nsD00 = \",\".join(aD00)\n\n# Gets a list of strings\naD00_Faces = oEditor.GetFaceIDs(sD00)\n\n# Remove the inner face\ndel aD00_Faces[4]\n\n# Changes from list to array of strings\naD00_Faces = Array[str](aD00_Faces)\n\n# Changes from array of string to array of integers\naD00_Faces = map(int, aD00_Faces)\n\n# Select the outer faces for D01 -----------------------------------------------\n\n# Select all the D00 elements\naD01 = oEditor.GetMatchedObjectName(\"D01*\")\nsD01 = \",\".join(aD01)\n\n# Gets a list of strings\naD01_Faces = oEditor.GetFaceIDs(sD01)\n\n# Remove the inner face\ndel aD01_Faces[5]\n\n# Changes from list to array of strings\naD01_Faces = Array[str](aD01_Faces)\n\n# Changes from array of string to array of integers\naD01_Faces = map(int, aD01_Faces)\n\n# Assign the outer faces a radiation boundary in D01 --------------------------\naOuterBoundaryFaces = aD00_Faces + aD01_Faces\noModule = oDesign.GetModule(\"BoundarySetup\")\noModule.AssignRadiation(\n [\n \"NAME:OuterRadiation\",\n \"Faces:=\", aOuterBoundaryFaces,\n \"IsIncidentField:=\", False,\n \"IsEnforcedHField:=\", False,\n \"IsEnforcedEField:=\", False,\n \"IsFssReference:=\", False,\n \"IsForPML:=\", False,\n \"UseAdaptiveIE:=\", False,\n \"IncludeInPostproc:=\", True\n ])\n\n# Save the changes\noProject.Save()\n\n# EOF\n","sub_path":"python/ansoft/FG_CB_CPW/Boundaries_FG_CB_CPW.py","file_name":"Boundaries_FG_CB_CPW.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"107047984","text":"ciagi = []\nwith open('ciagi.txt','r') as file:\n\tk = 1\n\tfor line in file:\n\t\tif k % 2 == 0:\n\t\t\tciagi.append(line.strip())\n\t\tk += 1\nbledne = []\nwith open('bledne.txt','r') as file:\n\tk = 1\n\tfor line in file:\n\t\tif k % 2 == 0:\n\t\t\tbledne.append(line.strip())\n\t\tk += 1\n\n#1\nzad1 = 0\nzad1_naj = 0\n\n#2\nszesciany = [x**3 for x in range(101)]\n\ndef szescian(list):\n\tx = 0\n\tfor l in list:\n\t\tif l in szesciany:\n\t\t\tif l > x:\n\t\t\t\tx = l\n\tif x != 0:\n\t\treturn x\n\nzad2 = []\n\n\nfor c in ciagi:\n\taryt = True\n\tciag = c.split(\" \")\n\tciag = [int(x) for x in ciag]\n\ts = szescian(ciag)\n\tif s != None:\n\t\tzad2.append(s)\n\t\n\tr = ciag[1] - ciag[0]\n\tfor i in range(0,len(ciag) - 1):\n\t\tif ciag[i] + r != ciag[i + 1]:\n\t\t\taryt = False\n\tif aryt:\n\t\tzad1 += 1\n\t\tif r > zad1_naj:\n\t\t\tzad1_naj = r\t\n\n#3\ndef bledny_wyraz(ciag):\n\tr = 0\n\n\tl = len(ciag)\n\tif ciag[1] - ciag[0] == ciag[2] - ciag[1]:\n\t\tr = ciag[1] - ciag[0]\n\tif r == 0:\n\t\tr = ciag[l-1] - ciag[l-2]\n\n\tfor i in range(1,l - 2):\n\t\tif (ciag[i] - r != ciag[i-1]) and (ciag[i] + r != ciag[i+1]):\n\t\t\treturn ciag[i]\n\n\tif ciag[0] + r != ciag[1]:\n\t\treturn ciag[0]\n\tif ciag[l-1] - r != ciag[l-2]:\n\t\treturn ciag[l-1]\n\nzad3 = []\nfor c in bledne:\n\tciag = c.split(\" \")\n\tciag = [int(x) for x in ciag]\n\tzad3.append(bledny_wyraz(ciag))\n\nwith open('wynik1.txt','w') as w:\n\tw.write(str(zad1)+ '\\n' + str(zad1_naj))\nwith open('wynik2.txt','w') as w:\n\tfor x in zad2:\n\t\tw.write(str(x) + '\\n')\nwith open('wynik3.txt','w') as w:\n\tfor x in zad3:\n\t\tw.write(str(x) + '\\n')\n\n\t","sub_path":"zbior zadan cke/61 - python/zadanie61.py","file_name":"zadanie61.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"435071543","text":"import re\n\nfrom . import config as cf\nfrom .shelves import Shelf\nfrom .structure import st\nfrom .structure import FullProcessingCode as fpc\n\n\n\n\n\nregular = {}\nregular['attrs_one'] = re.compile(r\"(?P([\\w\\-]+)\\s*?=\\s*?'(?P[\\s\\S]+?)')\")\nregular['attrs_two'] = re.compile(r'(?P([\\w\\-]+)\\s*?=\\s*?\"(?P[\\s\\S]+?)\")')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nsetting_tag = {\n 'move': ['static', 'dinamic'],\n 'quantity': ['one', 'many'],\n}\n\nclass Info(object):\n\n full = tip = tag = name = attrs_t = cont = str\n def __init__(self, reobj):\n data = reobj.groupdict()\n\n self.tip = data['tip']\n self.name = data['name']\n self.tag = data['tag']\n \n self.full = data['full']\n self.cont = data['cont']\n \n self.__attrs(data['attrs'])\n\n setting = {\n 'move': 'static'\n }\n attrs = {}\n attrs_ress = []\n def __attrs(self, title):\n if title != None:\n\n attrs = {}\n for i in ['one', 'two']:\n at = regular['attrs_' + i].findall(title)\n for varsa in at:\n attrs[varsa[1]] = varsa[2]\n title = regular['attrs_' + i].sub('', title)\n\n for i in attrs:\n attrs[i] = attrs[i].split()\n self.attrs = attrs\n\n attrs_ress = title.split()\n for i in setting_tag:\n val = setting_tag[i]\n for ii in val:\n if ii in attrs_ress:\n self.setting[i] = ii\n attrs_ress.remove(ii)\n self.attrs_ress = attrs_ress\n\n\n\nzero_tag = zero_tag = Info(cf.sint(r'').tag('t'))\n\n\n\n\n\n\n\nno_repeat = ['class']\nonly_one = ['href']\n\nclass Merge(object):\n\n\n name = str\n def __init__(self, MOD, ORIG):\n self.name = MOD.name\n self.__attrs(MOD, ORIG)\n self.__content(MOD, ORIG)\n \n\n tag = str\n attrs = {}\n attrs_ress = []\n def __attrs(self, MOD, ORIG):\n \n tag = MOD.tag\n if tag == None: tag = ORIG.tag\n if tag == None: tag = False\n self.tag = tag\n\n\n attrs = {}\n attrs_help = {\n 'orig': ORIG.attrs,\n 'mod': MOD.attrs,\n }\n for i in attrs_help:\n for ii in attrs_help[i]:\n if ii in attrs: attrs[ii] = attrs[ii] + attrs_help[i][ii]\n else: attrs[ii] = attrs_help[i][ii]\n \n for i in attrs:\n if i in no_repeat:\n attrs[i] = cf.helper().clear_list(attrs[i])\n if i in only_one:\n attrs[i] = attrs[i].pop()\n\n self.attrs = attrs\n\n\n attrs_ress = cf.helper().clear_list(ORIG.attrs_ress + MOD.attrs_ress)\n self.attrs_ress = attrs_ress\n\n\n old = {}\n cont = {}\n def __content(self, MOD, ORIG):\n self.old = {\n 'orig': ORIG.full,\n 'mod': MOD.full,\n }\n self.cont = {\n 'orig': ORIG.cont,\n 'mod': MOD.cont,\n }\n\n\n\n\n\n\n\n \nclass Render(Merge):\n\n name = str\n tag = str\n\n def __init__(self, MOD, ORIG):\n Merge.__init__(self, MOD, ORIG)\n\n self.__title()\n self.__content()\n\n\n title = bottom = str\n def __title(self):\n\n if not self.tag:\n self.title = self.bottom = ''\n else:\n tag = self.tag\n attrs = self.attrs\n attrs_ress = self.attrs_ress\n\n for i in attrs:\n st_help = ''\n for ii in attrs[i]:\n st_help = st_help + ii + ' '\n straka = i + '=\"' + st_help.strip() + '\"'\n attrs_ress.append(straka)\n \n straka = ''\n for i in attrs_ress:\n straka = straka + i + ' '\n \n straka = straka.strip()\n if straka != '': straka = ' ' + straka\n\n self.title = '<' + tag + straka + '>'\n self.bottom = ''\n\n\n def __content(self):\n mod_cont = self.cont['mod']\n orig_cont = self.cont['orig']\n \n if st(self.title, 'html').vs().find('content'):\n self.title = st(self.title, 'html').vs().insert('content', mod_cont)\n self.cont = ''\n elif st(orig_cont, 'html').vs().find('content'):\n orig_cont = st(orig_cont, 'html').vs().insert('content', mod_cont)\n self.cont = orig_cont\n else:\n self.cont = mod_cont\n\n\n def render(self):\n self.new = self.title + self.cont + self.bottom\n \n def insert(self, varss):\n self.new = st(self.new, 'html').allvs().insert(varss)\n\n def prll(self, prll):\n for i in prll:\n if prll[i]:\n for ii in prll[i]:\n self.new = self.new + '\\n' + ii\n\n def replace(self, html, tip, use_new):\n if use_new: use_new = self.new\n else: use_new = \"\"\n \n html = html.replace(self.old[tip], use_new)\n return html\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\nclass MAINTAG(object):\n\n\n page = str\n MOD = ORIG = Info\n def __init__(self, html):\n \n self.page = html\n if self.__FIND_tag():\n self.name = self.shelf.name\n\n self.cont = {\n 'orig': self.ORIG.cont,\n 'mod': self.MOD.cont,\n }\n self.__clear_1_tag()\n\n fpc_orig = fpc(self.cont['orig'], 'html').act_varss().act_prll(self.shelf)\n \n fpc_mod = fpc(self.cont['mod'], 'html').act_varss()\n fpc_mod.varss = cf.helper().merge_dict(fpc_mod.varss, fpc_orig.varss)\n fpc_mod.act_prll(self.shelf, fpc_orig.prll)\n \n self.cont['orig'] = fpc_orig.code\n self.cont['mod'] = fpc_mod.code\n \n self.__FIND_t()\n self.__clear_2_tag()\n\n self.ORIG.cont = self.cont['orig']\n self.MOD.cont = self.cont['mod']\n\n new_tag = Render(self.MOD, self.ORIG)\n new_tag.render()\n\n fpc_mod.code = new_tag.new\n fpc_mod.insert()\n\n new_tag.new = fpc_mod.code\n self.prll = fpc_mod.prll\n \n new_tag.prll(self.prll)\n\n\n self.page = new_tag.replace(self.page, 'mod', True)\n\n\n \n\n\n\n\n\n\n\n \n\n shelf = Shelf\n name = str\n def __FIND_tag(self):\n ret = False\n MOD = ORIG = zero_tag\n\n mod_reobj = cf.sint(self.page).tag('tag', True)\n if mod_reobj:\n MOD = Info(mod_reobj)\n shelf = Shelf('tag', MOD.name).get()\n if shelf.search:\n self.shelf = shelf\n orig_reobj = cf.sint(shelf.html).tag('tag', False)\n if orig_reobj:\n ORIG = Info(orig_reobj)\n else:\n print('Элемент Tag с именем '+ MOD.name +' не подходит форматом')\n else:\n print('Не найден элемент Tag с именем '+ MOD.name)\n ret = True\n\n if MOD: self.MOD = MOD\n if ORIG: self.ORIG = ORIG\n return ret\n \n \n\n def __FIND_t(self):\n cont = self.cont\n while cf.sint(cont['orig']).tag( 't', True):\n orig_reobj = cf.sint(cont['orig']).tag( 't', True)\n ORIG = Info(orig_reobj)\n\n mod_reobj = cf.sint(cont['mod']).tag( ['t', ORIG.name], True)\n if mod_reobj: MOD = Info(mod_reobj)\n else: MOD = zero_tag\n\n new_tag = Render(MOD, ORIG)\n new_tag.render()\n \n if ORIG.setting['move'] == 'static':\n h = [True, False]\n elif ORIG.setting['move'] == 'dinamic':\n h = [False, True]\n \n cont['orig'] = new_tag.replace(cont['orig'],'orig', h[0])\n cont['mod'] = new_tag.replace(cont['mod'], 'mod', h[1])\n self.cont = cont\n\n\n\n\n \n def __clear_1_tag(self):\n self.clear_list = {'mod': {},'orig': {},}\n for i in self.cont:\n [self.cont, self.clear_list[i]] = delite_tag(self.cont[i])\n\n def __clear_2_tag(self):\n for i in self.cont:\n for ii in self.clear_list[i]:\n self.cont[i] = self.cont[i].replace(ii, self.clear_list[i][ii])\n\n \n\n\n\n def __varss(self):\n varss = {}\n cont = self.cont\n for i in cont:\n s = st(cont[i], 'html').vs()\n varss.update(s.get())\n cont[i] = s.code\n self.cont = cont\n return varss\n\n\n\n\n\ndef delite_tag(code):\n clear_list = {}\n while cf.sint(code).tag('tag', True):\n full = cf.sint(code).tag('tag', True).group('full')\n h = cf.replace_id(['html', 'replace', 'tag'], full)\n \n clear_list.update(h)\n for ii in h:\n code = code.replace(h[ii], ii)\n return code, clear_list\n \n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"core/htmltag.py","file_name":"htmltag.py","file_ext":"py","file_size_in_byte":8980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"116283348","text":"import re\r\n\r\ndef run(inpt):\r\n Xs, Ys, Hs, Vs = [], [], [], []\r\n for line in inpt:\r\n splt = re.split('[<,>]', line)\r\n Xs += [int(splt[1])]\r\n Ys += [int(splt[2])]\r\n Hs += [int(splt[4])]\r\n Vs += [int(splt[5])]\r\n\r\n Bx, By = [x for x in Xs], [y for y in Ys]\r\n sprd = max(Xs) - min(Xs) + max(Ys) - min(Ys)\r\n while True:\r\n Xs = [Xs[i] + Hs[i] for i in range(len(Xs))]\r\n Ys = [Ys[i] + Vs[i] for i in range(len(Ys))]\r\n s = max(Xs) - min(Xs) + max(Ys) - min(Ys)\r\n if s < sprd:\r\n Bx, By = [x for x in Xs], [y for y in Ys]\r\n sprd = s\r\n else: break\r\n\r\n L, R = min(Bx), max(Bx)\r\n U, D = min(By), max(By)\r\n pos = [(Bx[i], By[i]) for i in range(len(Bx))]\r\n for y in range(U, D+1):\r\n for x in range(L, R+1):\r\n if (x, y) in pos: print('#', end='')\r\n else: print(' ', end='')\r\n print()\r\n\r\nif __name__ == '__main__':\r\n with open('AoC18_10.txt') as file:\r\n inpt = [line.rstrip('\\n') for line in file]\r\n print('Input Loaded\\n')\r\n run(inpt)\r\n print('\\n')\r\n","sub_path":"2018/10/AoC18_10_1.py","file_name":"AoC18_10_1.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"126579378","text":"from BaseClass.EntityHandler import EntityHandler\nfrom BaseClass.APIRequest import APIRequest\n\nfrom Entity.Bug.Bug import Bug\n\nclass BugsHandler(EntityHandler):\n\n\tdef find(self, id_):\n\t\tsuper().find(id_)\n\n\t\treq = APIRequest(\n\t\t\tself._origin,\n\t\t\t'/v1/bugs/' + str(id_),\n\t\t\t'GET',\n\t\t\t{\n\t\t\t\t'params': {\n\t\t\t\t\t'include': 'steps,platform,attachments,comments,tags'\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\t\treturn Bug(self._origin, req.exec_())\n\n\tdef delete(self, id_):\n\t\tsuper().delete(id_)\n\n\t\treq = APIRequest(self._origin, '/v1/bugs/' + str(id_), 'DELETE')\n\t\treturn req.exec_()\n\n\tdef update(self, id_, fields):\n\t\tsuper().update(id_, fields)\n\n\t\tsupports = {\n\t\t\t'title' : False,\n\t\t\t'status_id' : False,\n\t\t\t'severity_id' : False,\n\t\t\t'priority_id' : False,\n\t\t\t'project_version_id' : False,\n\t\t\t'project_section_id' : False,\n\t\t\t'type_id' : False,\n\t\t\t'assigned_user_id' : False,\n\t\t\t'description' : False,\n\t\t\t'expected_results' : False,\n\t\t\t'steps' : False,\n\t\t\t'platform' : False\n\t\t\t# 'device_model' : False,\n\t\t\t# 'device_model_id' : False,\n\t\t\t# 'os' : False,\n\t\t\t# 'os_version' : False,\n\t\t\t# 'os_version_id' : False,\n\t\t\t# 'browser_version_id' : False\n\t\t}\n\n\t\tif self.enforce(fields, supports):\n\t\t\tinitFields = {'include': 'steps,platform'}\n\t\t\tinitFields.update(fields)\n\t\t\tfields = initFields\n\n\t\t\treq = APIRequest(self._origin, '/v1/bugs/' + str(id_), 'PUT', {'params': fields})\n\t\t\treturn Bug(self._origin, req.exec_())\n","sub_path":"leantesting/Handler/Bug/BugsHandler.py","file_name":"BugsHandler.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"138519133","text":"# coding: utf-8\r\nfrom license_image_extraction import extraction\r\nfrom recognize_license_id import text\r\n\r\n#export GOOGLE_APPLICATION_CREDENTIALS=\"/Users/zhizhouqiu/Desktop/web1127/parking_management_system/EC601MiniProject1.json\"\r\ncar_path = \"car10.jpg\"\r\nlicense_plate_path = 'license.jpg'\r\njson_path = \"EC601MiniProject1.json\"\r\n\r\n\r\ndef extract_license_plate(car_pic_path, license_plate_path, json_path):\r\n upd_time = extraction.time_extraction(car_path)\r\n extraction.store_license_plate(car_path, license_plate_path)\r\n license_id = str(text.recognize(license_plate_path, json_path))\r\n license_id = license_id.replace(\"\\n\",\"\")\r\n license_id = license_id.replace(\" \",\"\")\r\n license_id = license_id.replace(\"·\",\"\")\r\n #license_id = 'LEM446AA'\r\n return license_id\r\n\r\n\r\n","sub_path":"parking_management_system/t.py","file_name":"t.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"296922988","text":"# exercise 11.2.3\nfrom pylab import *\nfrom sklearn.neighbors import NearestNeighbors\nfrom import_data import *\nfrom sklearn import cross_validation\n\n#------------------------\n\ndata = Data()\n\ndata.normalize_data()\nX = np.matrix(data.X)\nN, M = data.N, data.M\n\nCV = cross_validation.LeaveOneOut(data.N)\n#------------------------\n\n\n\nfor train_index, test_index in CV:\n print('Crossvalidation fold: {0}/{1}'.format(i + 1, data.N))\n\n # extract training and test set for current CV fold\n X_train = data.X[train_index, :]\n X_test = data.X[test_index, :]\n # Number of neighbors\n K = 137\n\n # Find the k nearest neighbors\n knn = NearestNeighbors(n_neighbors=K).fit(X)\n D, i = knn.kneighbors(X)\n\n # Compute the density\n #D, i = knclassifier.kneighbors(np.matrix(xe).T)\n knn_density = 1./(D.sum(axis=1)/K)\n\n # Compute the average relative density\n DX, iX = knn.kneighbors(X)\n knn_densityX = 1./(DX[:,1:].sum(axis=1)/K)\n knn_avg_rel_density = knn_density/(knn_densityX[i[:,1:]].sum(axis=1)/K)\n\n\n# Plot KNN density\nfigure()\nsubplot(2,1,1)\nhist(X,X)\ntitle('Data histogram')\nsubplot(2,1,2)\nplot(X, knn_density)\ntitle('KNN density')\n# Plot KNN average relative density\nfigure()\nsubplot(2,1,1)\nhist(X,x)\ntitle('Data histogram')\nsubplot(2,1,2)\nplot(xe, knn_avg_rel_density)\ntitle('KNN average relative density')\n\nshow()\n","sub_path":"assignment_3/src/Ourlier.py","file_name":"Ourlier.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"438138716","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n__author__ = 'MFC'\n__time__ = '2020-01-14 15:51'\n\n\"\"\"\n4-1 Python内置数据结构算法常考\n\n什么是LRUCache?\n\nLeast-Recently-Used 替换掉最近最少使用的对象\n\n1.缓存剔除策略,当缓存空间不够用的时候需要一种方式剔除key\n\n2.常见的有:LRU(Least-Recently-Used,替换掉最近最少使用的对象),LFU(Least-Frequently-Used,根据数据的历史访问频率来淘汰数据) \n\n3.LRU通过使用一个循环双端队列不断把最新访问的key放到表头、把最远的访问放到最后、把最远访问的key剔除即可。\n\n重点:如何实现LRUCache?\n\n字典用来缓存,循环双端链表用来记录访问顺序\n\n1)利用Python内置的dict+collections.OrderedDict实现\n2)dict用来当作k/v键值对的缓存\n3)OrderedDict用来实现更新最近访问的key\n\n要求:\n自己实现LRUCache,并编写单元测试\n\"\"\"\n\nfrom collections import OrderedDict\n\nclass LRUCache:\n\n def __init__(self, capacity=128):\n # capacity表示最多有多少个key\n self.od = OrderedDict()\n self.capacity = capacity\n\n def get(self, key:str):\n if key in self.od:\n val = self.od[key]\n self.od.move_to_end(key) # 每次访问更新最新使用的key,把最近访问的放到最右边,表示最新 左旧右新\n return val\n else:\n return -1\n\n def put(self, key, value)->None:\n \"\"\"更新key/value值\n 分2种情况:\n 1.如果key在od里,需要把它删除,然后重新赋值\n 2.判断当前容量capacity是否已经满了,��果满了,则把最早的一个key给删除\n \"\"\"\n if key in self.od:\n del self.od[key]\n self.od[key] = value # 更新key到表头,最右边\n else: # insert\n self.od[key] = value\n # 判断当前容量capacity是否已经满了\n if len(self.od) > self.capacity:\n self.od.popitem(last=False) # 把最早的一个key给删除\n\n# 自己实现LRUCache,并编写单元测试\n\nif __name__ == \"__main__\":\n keys = ['python', 'go', 'java', 'php', 'c', 'javascript']\n cache = LRUCache(capacity=4)\n print(cache.od)\n\n for key in keys:\n if cache.get(key) == -1:\n cache.put(key,key)\n\n print(cache.od)\n\n import unittest\n class LRUCache(unittest.TestCase):\n def setUp(self) -> None:\n self.keys = ['python', 'go', 'java', 'php', 'c', 'javascript']\n self.cache = LRUCache(capacity=4)\n\n def testType(self):\n self.assertIsInstance(self.cache, OrderedDict)\n\n\n\n","sub_path":"pw_python/imooc/ch4/03_lru_cache.py","file_name":"03_lru_cache.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"76963550","text":"\"\"\"\nDisagreement measures and disagreement based query strategies for the Committee model.\n\"\"\"\nfrom collections import Counter\nfrom typing import Tuple\nimport numpy as np\nfrom scipy.stats import entropy\nfrom sklearn.exceptions import NotFittedError\nfrom sklearn.base import BaseEstimator\nfrom keras.models import Sequential\n\nfrom modAL_multicol.utils.data import modALinput\nfrom modAL_multicol.utils.selection import multi_argmax, shuffled_argmax\nfrom modAL_multicol.models.base import BaseCommittee\n\n\ndef vote_entropy(\n committee: BaseCommittee, X: modALinput, **predict_proba_kwargs\n) -> np.ndarray:\n \"\"\"\n #edited\n\n Calculates the vote entropy for the Committee.\n First it computes the predictions of X for each learner in the Committee (i.e., committee.vote(X) ), then\n calculates the probability distribution of the votes.\n The entropy of this distribution is the vote entropy of the Committee, which is returned.\n\n Args:\n committee: The :class:`modAL.models.BaseCommittee` instance for which the vote entropy is to be calculated.\n X: The data for which the vote entropy is to be calculated.\n **predict_proba_kwargs: Keyword arguments for the :meth:`predict_proba` of the Committee.\n\n Returns:\n Vote entropy of the Committee for the samples in X.\n \"\"\"\n n_learners = len(committee)\n try:\n votes = committee.vote(X, **predict_proba_kwargs) # the prediction votes\n except NotFittedError:\n print(\"Not Fitted Error at vote_entropy\")\n return np.zeros(shape=(X.shape[0],))\n\n entr = np.zeros(shape=(X.shape[0],))\n n_output_cols = int(votes.shape[1] / n_learners) # 4 output columns\n p_vote = np.zeros(\n shape=(X.shape[0], len(committee.classes_) * n_output_cols)\n ) # 200000, 5*8/2 -> 200000, 20 (5 classes * 4 output columns)\n for vote_idx, vote in enumerate(votes):\n split_vote = np.split(vote, n_learners)\n multi_vote_counter = list(\n map(lambda c: Counter(list(map(lambda x: x[c], split_vote))), [0, 1, 2, 3])\n ) # for each column, return the counter of votes\n # put the average vote count in the p_vote, in which has [vote_idx, multi_class_idx]\n # multi_class_idx: size of 20 => 5*4 => [0,1,2,3,4 | 5,6,7,8,9 | 10,11,12,13,14 | 15,16,17,18,19]\n for c in range(n_output_cols):\n mvc_c = multi_vote_counter[c]\n for key in mvc_c:\n key = int(key)\n if mvc_c[key] > 0:\n multi_class_idx = c * 5 + key if c > 0 else key\n p_vote[vote_idx, multi_class_idx] = mvc_c[key] / n_learners\n entr[vote_idx] = entropy(\n p_vote[vote_idx]\n ) # entropy is calculated for each data_point (index) of X\n\n # print(split_vote, p_vote[vote_idx], entr[vote_idx])\n return entr\n\n\ndef vote_entropy_sampling(\n committee: BaseCommittee,\n X: modALinput,\n n_instances: int = 1,\n random_tie_break=True,\n **disagreement_measure_kwargs\n) -> Tuple[np.ndarray, modALinput]:\n \"\"\"\n Vote entropy sampling strategy.\n\n Args:\n committee: The committee for which the labels are to be queried.\n X: The pool of samples to query from.\n n_instances: Number of samples to be queried.\n random_tie_break: If True, shuffles utility scores to randomize the order. This\n can be used to break the tie when the highest utility score is not unique.\n **disagreement_measure_kwargs: Keyword arguments to be passed for the disagreement\n measure function.\n\n Returns:\n The indices of the instances from X chosen to be labelled;\n the instances from X chosen to be labelled.\n \"\"\"\n disagreement = vote_entropy(committee, X, **disagreement_measure_kwargs)\n\n if not random_tie_break:\n query_idx = multi_argmax(disagreement, n_instances=n_instances)\n else:\n query_idx = shuffled_argmax(disagreement, n_instances=n_instances)\n\n return query_idx, X[query_idx]\n","sub_path":"modAL_multicol/disagreement.py","file_name":"disagreement.py","file_ext":"py","file_size_in_byte":4003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"424377718","text":"# coding:utf8\n\"\"\"\n 4. 寻找两个正序数组的中位数\n 给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。\n\n 示例 1:\n 输入:nums1 = [1,3], nums2 = [2]\n 输出:2.00000\n 解释:合并数组 = [1,2,3] ,中位数 2\n 链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays\n\"\"\"\n\nfrom typing import List\n\nclass Solution:\n def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n return self.findMedianSortedArrays_v1(nums1, nums2)\n def findMedianSortedArrays_v1(self, nums1: List[int], nums2: List[int]) -> float:\n \"\"\"\n 思路\n 遍历找中位数\n \"\"\"\n size1, size2 = len(nums1), len(nums2)\n size = size1 + size2\n pos1, pos2 = 0, 0\n preVal, curVal = None, None\n\n for _ in range(size // 2 + 1):\n preVal = curVal\n if (pos1 < size1 and (pos2 >= size2 or nums1[pos1] < nums2[pos2])):\n curVal = nums1[pos1]\n pos1 += 1\n else:\n curVal = nums2[pos2]\n pos2 += 1\n\n\n\n if size % 2 == 0:\n return (preVal + curVal) / 2\n else:\n return curVal\n\n def findMedianSortedArrays_v2(self, nums1: List[int], nums2: List[int]) -> float:\n pass\n\n\nif __name__ == '__main__':\n nums1, nums2 = [1, 3], [2]\n obj = Solution()\n print(obj.findMedianSortedArrays(nums1, nums2))\n","sub_path":"suqing/fuckal/python/array/median-of-two-sorted-arrays.py","file_name":"median-of-two-sorted-arrays.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"405119602","text":"\"\"\"empty message\n\nRevision ID: 53b4356f52d6\nRevises: 9363f75a0d12\nCreate Date: 2020-09-17 21:08:26.444331\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '53b4356f52d6'\ndown_revision = '9363f75a0d12'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('Artist', sa.Column('datecreate', sa.DateTime(), nullable=True))\n op.add_column('Venue', sa.Column('datecreate', sa.DateTime(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('Venue', 'datecreate')\n op.drop_column('Artist', 'datecreate')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/53b4356f52d6_.py","file_name":"53b4356f52d6_.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"441544641","text":"import unittest\nfrom modulo import promedio\n\nclass TestFuncionesEstadisticas(unittest.TestCase):\n def test_promedio(self):\n self.assertEqual(promedio([20, 30, 70]), 40.0)\n self.assertEqual(round(promedio([1, 5, 7]), 1), 4.3)\n with self.assertRaises(ZeroDivisionError):\n promedio([])\n with self.assertRaises(TypeError):\n promedio(20, 30, 70)\n\nunittest.main()\n# ejecutar las pruebas:\n# python test.py\n","sub_path":"learn/varios/test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"29595672","text":"# -*- coding: utf-8 -*-\nimport logging\nimport os\nfrom pathlib import Path\n\nimport click\nimport progressbar\nimport pymongo\nfrom dotenv import find_dotenv, load_dotenv\nfrom pymongo.errors import DuplicateKeyError\nfrom sqlitedict import SqliteDict\n\n\n@click.command()\n@click.argument('topic')\ndef main(topic):\n \"\"\" Export a topic's data from sqlite to mongodb\n \"\"\"\n logger = logging.getLogger(__name__)\n\n # root directories\n root_dir = Path(__file__).resolve().parents[2]\n datastore_root_dir = os.path.join(root_dir, 'data', 'raw')\n dataset_dir = os.path.join(datastore_root_dir, topic)\n\n try:\n if not os.path.exists(dataset_dir):\n raise FileNotFoundError(f'{dataset_dir} does not exist.')\n myclient = pymongo.MongoClient(\"localhost\", 27017)\n except (ValueError, FileNotFoundError, FileExistsError, KeyError) as error:\n logger.error(error)\n else:\n network_filepath = Path(dataset_dir)\n if not network_filepath.is_absolute():\n raise ValueError('Expected an absolute path.')\n if not network_filepath.is_dir():\n raise ValueError('network_filepath path is not a directory.')\n\n database_filepath = list(network_filepath.glob('*.sqlite'))[0]\n\n mydb = myclient[\"info-diffusion\"]\n mycol = mydb[topic]\n\n # get tweet ids that fulfil the date range of interest\n logger.info(\"Export tweets from sqlite to mongodb\")\n with SqliteDict(filename=database_filepath.as_posix(),\n tablename='tweet-objects') as tweets:\n # iterate over the tweets dataset to fetch desired result for nodes\n bar = progressbar.ProgressBar(maxval=len(tweets),\n prefix='Exporting Tweets: ')\n for tweet_id in bar(tweets):\n # export to mongodb\n tweet_ = tweets[tweet_id]._json\n id_ = {\"_id\": tweet_id}\n new_document = {**id_, **tweet_}\n\n try:\n _ = mycol.insert_one(new_document)\n except DuplicateKeyError:\n logging.info(f\"found duplicate key: {tweet_id}\")\n continue\n\n\nif __name__ == '__main__':\n log_fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n logging.basicConfig(level=logging.INFO, format=log_fmt)\n\n # find .env automagically by walking up directories until it's found, then\n # load up the .env entries as environment variables\n load_dotenv(find_dotenv())\n\n main()\n","sub_path":"indiff/data/export_db.py","file_name":"export_db.py","file_ext":"py","file_size_in_byte":2545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"605738070","text":"import json\n# import xmltodict\nimport os\nimport cv2\nimport numpy as np\nimport torch\nimport matplotlib.pyplot as plt\n\n\n# def xmltojson(name, file):\n# dirc = \"../SUNDATABASE/Annotations/l/living_room\"\n# outputdirc = \"../SUNDATABASE/Annotations/l/json\"\n# xmlstr = file.read()\n# xmlparse = xmltodict.parse(xmlstr)\n# jsonstr = json.dumps(xmlparse,indent=1)\n# print(jsonstr, file=open(outputdirc+\"/\"+name+\".json\", \"w\"))\n\n\n# def tojson(dirc):\n# files = os.listdir(dirc)\n# for file in files:\n# name = file.split('.')[0]\n# print(name)\n# f = open(dirc+\"/\"+file, \"r\")\n# xmltojson(name, f)\n\n\ndef read_json():\n with open(\"./data/class.json\", 'r') as load_f:\n load_dict = json.load(load_f)\n keys = [tmp[0] for tmp in load_dict]\n for k in keys:\n print(k)\n\n\ndef deal_data(only_level=False):\n img_root = \"../data/bedroom\"\n level_root = \"../data/levels\"\n seg_root = \"../data/seg_mat\"\n deep_root = \"../data/depth_new\"\n\n wanted_size = (300, 200)\n files = os.listdir(img_root)\n images = None\n segmentation = None\n depth__ = None\n level__ = None\n\n for i in range(0, 2118):\n f_name = files[i].split('.')[0]\n img = cv2.imread(img_root + \"/\" + f_name + \".jpg\")\n img = cv2.resize(img, dsize=wanted_size, interpolation=cv2.INTER_NEAREST)\n seg = np.load(seg_root+\"/\"+f_name+\".npy\")\n depth = np.load(deep_root+\"/\"+f_name+\".npy\")\n level = np.load(level_root+\"/\"+f_name+\".npy\")\n if i%16==0:\n if i!=0:\n print(i)\n X = images\n Y = torch.cat((segmentation, depth__, level__), dim=3)\n Y = Y.transpose(2, 3)\n Y = Y.transpose(1, 2)\n X = X.transpose(2, 3)\n X = X.transpose(1, 2)\n print(Y.shape)\n torch.save(X, \"../data/data_batch/bx_{0}.th\".format(int(i/16)))\n torch.save(Y, \"../data/data_batch/by_{0}.th\".format(int(i/16)))\n\n images = torch.reshape(torch.Tensor(img), (1, wanted_size[1], wanted_size[0], 3))\n segmentation = torch.reshape(torch.Tensor(seg), (1, wanted_size[1], wanted_size[0], 1))\n depth__ = torch.reshape(torch.Tensor(depth), (1, wanted_size[1], wanted_size[0], 1))\n level__ = torch.reshape(torch.Tensor(level), (1, wanted_size[1], wanted_size[0], 1))\n else:\n images = torch.cat((images, torch.reshape(torch.Tensor(img), (1, wanted_size[1], wanted_size[0], 3))))\n segmentation = torch.cat((segmentation, torch.reshape(torch.Tensor(seg), (1, wanted_size[1], wanted_size[0], 1))))\n depth__ = torch.cat((depth__, torch.reshape(torch.Tensor(depth), (1, wanted_size[1], wanted_size[0], 1))))\n level__ = torch.cat((level__, torch.reshape(torch.Tensor(level), (1, wanted_size[1], wanted_size[0], 1))))\n\n\ndef get_better_size():\n dirt = \"../data/bedroom\"\n images = os.listdir(dirt)\n l = []\n w = []\n for f in images:\n img = cv2.imread(dirt+\"/\"+f)\n l.append(img.shape[0])\n w.append(img.shape[1])\n l.sort()\n w.sort()\n for i in range(0, 21):\n print(l[i*100], end=' ')\n print(\"\")\n for i in range(0, 21):\n print(w[i * 100], end=' ')\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"pre_process.py","file_name":"pre_process.py","file_ext":"py","file_size_in_byte":3325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"625953","text":"import time\n\nfrom pytest_bdd import scenario, given, when, then\n\nfrom features.Pages.ConfirmationPage import ConfirmationPage\nfrom features.steps.Common.CommunSteps import chose_pick_up_location, car_reservation_page, click_on_car_details_button, \\\n cars_result_page, click_on_cars_search_button, chose_date, enter_pick_up_and_drop_off_time, click_on_book_now\n\n\n@scenario('../exercice3.feature',\n 'As an anonymous user, when I reach the booking confirmation page of my car reservation, when I go back two steps before, and I come back to the confirmation page, the booking information should be maintained')\ndef test_exercice3_part2():\n pass\n\n\n@then(\"I go back to results page using the browser back button\")\ndef go_back_to_results_page(browser):\n browser.back()\n time.sleep(2)\n browser.back()\n time.sleep(2)\n\n\n@then(\"I come back to the confirmation page using the browser forward button\")\ndef comeback_to_confirmation_page(browser):\n browser.forward()\n time.sleep(2)\n browser.forward()\n\n\n@then(\n \"the booking information summary that contains location and should be maintained\")\ndef booking_information_maintained(browser, pick_up, pick_up_date, drop_off_date):\n confirmation = ConfirmationPage(browser)\n confirmation.booking_summary_maintained(pick_up, pick_up_date, drop_off_date)\n","sub_path":"features/steps/test_exercice3_part2.py","file_name":"test_exercice3_part2.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"96284754","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 8 09:34:13 2018\n\n@author: Administrator\n\"\"\"\nimport pandas as pd \nimport os\nfrom datetime import datetime \ncurrent_date = str(datetime.now()).split('.')[0].split(' ')[0]\n\ndata_path = r'D:\\test' + '\\\\'\n\nfile_name = '修改切换模式_2018-11-08.xlsx'\ndf_file = pd.read_excel(data_path + file_name ,encoding='utf-8') \n\n# =============================================================================\n# 生成ommb1修改指令\n# =============================================================================\ndf_ommb1 = df_file[df_file['OMMB'] == 'OMMB1']\ndf_ommb1 = df_ommb1.reset_index()\n\n\nwith open(data_path + current_date + '_' + 'apply_right_OMMB1.txt','a') as f:\n for i in range(0,len(df_ommb1),1):\n line = r'APPLY MUTEXRIGHT:SUBNET=\"{0}\",NE=\"{1}\";'\\\n .format(df_ommb1.loc[i,'SubNetwork'],\n df_ommb1.loc[i,'MEID'],\n)\n f.write(line+'\\n') \n\n\nwith open(data_path + current_date + '_' + 'OMMB1_command_flagSwiMode.txt','a') as f:\n for i in range(0,len(df_ommb1),1):\n line = r'UPDATE:MOC=\"EUtranCellFDD\",MOI=\"{0}\",ATTRIBUTES=\"flagSwiMode=6\",EXTENDS=\"\";'\\\n .format(df_ommb1.loc[i,'MOI'])\n f.write(line+'\\n') \n\n# =============================================================================\n# 生成ommb1修改指令\n# =============================================================================\ndf_ommb2 = df_file[df_file['OMMB'] == 'OMMB2']\ndf_ommb2 = df_ommb2.reset_index()\n\n\nwith open(data_path + current_date + '_' + 'apply_right_OMMB2.txt','a') as f:\n for i in range(0,len(df_ommb2),1):\n line = r'APPLY MUTEXRIGHT:SUBNET=\"{0}\",NE=\"{1}\";'\\\n .format(df_ommb2.loc[i,'SubNetwork'],\n df_ommb2.loc[i,'MEID'],\n)\n f.write(line+'\\n') \n\n\nwith open(data_path + current_date + '_' + 'OMMB2_command_flagSwiMode.txt','a') as f:\n for i in range(0,len(df_ommb2),1):\n line = r'UPDATE:MOC=\"EUtranCellFDD\",MOI=\"{0}\",ATTRIBUTES=\"flagSwiMode=6\",EXTENDS=\"\";'\\\n .format(df_ommb2.loc[i,'MOI'])\n f.write(line+'\\n') \n","sub_path":"中兴网管参数修改_flagSwiMode.py","file_name":"中兴网管参数修改_flagSwiMode.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"422617421","text":"#!/usr/bin/python3\n\n\nimport sys\nfrom PyQt5.QtWidgets import QApplication,QWidget\n\nclass myform(QWidget):\n def __init__(self):\n super().__init__() #调用父类QWidget的构造函数,这句很重要\n self.setWindowTitle('hello qt')\n self.resize(400,300)\n\nif __name__=='__main__':\n app = QApplication(sys.argv)\n w = myform() \n w.show()\n\napp.exec_()\n\n\n","sub_path":"python/project_py/pyqt5/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"127337805","text":"import json\nimport re\nimport pandas as pd \nimport numpy as np \nfrom csv import DictWriter, writer\nfrom datetime import date, time, datetime\n\nwith open(\"YOURFILENAME.json\", \"r\") as data_read:\n json_data = json.load(data_read)\n\ntweet_properties = {}\n\nwith open('YOURNEWFILENAME.csv', 'w') as f:\n csv_writer = DictWriter(f, fieldnames=[\n 'tanggal', 'username', 'followers', 'tweet', 'likes', 'retweet', 'komentar', 'location'])\n csv_writer.writeheader()\n for data in json_data:\n if \"RT @\" not in data['text']: #cleaning\n if 'extended_tweet' in data:\n tweet_properties['tweet'] = re.sub(\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t])|(\\w+:\\/\\/\\S+)\", \" \", data['extended_tweet']['full_text'].lower())\n else:\n tweet_properties['tweet'] = re.sub(\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t])|(\\w+:\\/\\/\\S+)\", \" \", data['text'].lower())\n \n tweet_properties['location'] = re.sub(\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t])|(\\w+:\\/\\/\\S+)\",\n \" \", str(data['user']['location']).lower())\n \n csv_writer.writerow({\n 'tanggal': datetime.strptime(\n data['created_at'], \"%a %b %d %X %z %Y\").strftime(\"%d-%m-%Y %X\"),\n 'username': data['user']['screen_name'],\n 'followers': data['user']['followers_count'],\n 'tweet': tweet_properties['tweet'],\n 'likes': data['favorite_count'],\n 'retweet': data['retweet_count'],\n 'komentar': data['reply_count'],\n 'location': tweet_properties['location']\n })\n\nprint(\"DONE!\")\n","sub_path":"prepeksploratif.py","file_name":"prepeksploratif.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"228537547","text":"# -*- encoding: utf-8 -*-\r\n#import sys\r\n#sys.path.append('./modulos')\r\n#from modulos.Ifta_Wyrowski import IftaWyrowski\r\n\r\nfrom modulos.principal import funcionprincipal\r\n\r\n#x = iftaWyrowski()\r\n#x.iniciaralgooritmo()\r\nALLOWED_EXTENSIONS = set(['pgm', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])\r\n\r\ndef allowed_file(filename):\r\n return '.' in filename and \\\r\n filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS\r\n\r\n\r\nobj = {}\r\nobj['ruta'] = \"C:\\\\Users\\\\Lenovo\\\\Documents\\\\Tesis\\\\www\\\\Software\\\\holoeasy\\\\images\\\\3.jpg\"\r\nobj['tailleimg'] = 322\r\nobj['pixelmargin'] = 4\r\nobj['tipoimg']='file'\r\nobj['phase'] = 'phaheur'\r\nobj['phaseinitial'] = 'bandelimitee'\r\nobj['iterODD'] = 200\r\nobj['code'] = 'codedur'\r\nobj['MASIRdes'] = 0.8\r\nobj['control_banda'] = 0.01\r\nobj['controlbande'] = 0.01\r\nobj['diffphase'] = 1.335\r\nobj['tipoilum'] = 'carre'\r\nobj['nivel'] = 4\r\nobj['PRs'] = 1\r\nobj['PRb'] = 0\r\nobj['DPRA'] = 1\r\nobj['DPLRA'] = 0\r\nobj['DPE'] = 0\r\nobj['iteraccion'] = 20\r\nobj['tailleobject'] = 322\r\nobj['taillesignal'] = 644\r\nobj['tailleholo'] = 322\r\nobj['cuantificar'] = 'SI'\r\n\r\nfuncionprincipal(obj)\r\n","sub_path":"prueba_322x294.py","file_name":"prueba_322x294.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"195857754","text":"#\n# @lc app=leetcode.cn id=543 lang=python3\n#\n# [543] 二叉树的直径\n#\n\n# @lc code=start\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def diameterOfBinaryTree(self, root: TreeNode) -> int:\n maxh = 0 \n \n def get_height(node):\n nonlocal maxh\n if not node:\n return 0\n \n lh = get_height(node.left)\n rh = get_height(node.right)\n maxh = max(maxh, lh+rh+1)\n\n return max(lh, rh) + 1\n \n get_height(root)\n return maxh - 1\n# @lc code=end","sub_path":"LeetCode/0543/递归.py","file_name":"递归.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"646710001","text":"N = int(input()) #Number of elements on the following arrays\nX = [float(x) for x in input().split(' ')] #elements\nW = [float(x) for x in input().split(' ')] #elements' weights\n\nsoma = 0\nsoma_pesos = 0\ni=0\nwhile i < N:\n\tsoma += X[i]*W[i]\n\tsoma_pesos += W[i]\n\ti+=1\n\nweighted_mean = round((soma/soma_pesos), 1)\nprint(weighted_mean)\n","sub_path":"weightedmean.py","file_name":"weightedmean.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"36817050","text":"# -*- coding: utf-8 -*-\n\n# Scrapy settings for tutorial project\n#\n# For simplicity, this file contains only settings considered important or\n# commonly used. You can find more settings consulting the documentation:\n#\n# http://doc.scrapy.org/en/latest/topics/settings.html\n# http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html\n# http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html\n\n\n#################basic-setting################################################\nBOT_NAME = 'tutorial'\nLOG_LEVEL = 'INFO' \nLOG_FILE = \"logs/sys.log\"\nDOWNLOAD_DELAY = 3\nRANDOMIZE_DOWNLOAD_DELAY = True\n\nSPIDER_MODULES = ['tutorial.spiders']\nNEWSPIDER_MODULE = 'tutorial.spiders'\n\n# 相关链接的爬取深度\nMAXLAYER = 5\n# Crawl responsibly by identifying yourself (and your website) on the user-agent\nUSER_AGENT = 'Mozilla/5.0 (Linux; Android 4.2.2; GT-I9505 Build/JDQ39) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.59 Mobile Safari/537.36'\n# Disable cookies (enabled by default)\nCOOKIES_ENABLED=False\n\nITEM_PIPELINES = {\n 'tutorial.pipelines.MongoDBPipeline':100,\n #'scrapy_redis.pipelines.RedisPipeline': 300\n}\n\nDOWNLOADER_MIDDLEWARES = {\n 'scrapy.contrib.downloadermiddleware.useragent.UserAgentMiddleware' : None,\n #'tutorial.contrib.downloadermiddleware.middlewares.ProxyMiddleware':300,\n 'tutorial.contrib.downloadermiddleware.middlewares.RotateUserAgentMiddleware':400,\n }\n\n##########################################################################\n\n\n################scrapy-redis#############################################\n# 修改scrapy默认的调度器为scrapy重写的调度器 启动从reids缓存读取队列调度爬虫\nSCHEDULER = \"scrapy_redis.scheduler.Scheduler\"\n# 调度状态持久化,不清理redis缓存,允许暂停/启动爬虫\nSCHEDULER_PERSIST = True\n# 请求调度使用优先队列(默认)\nSCHEDULER_QUEUE_CLASS = 'scrapy_redis.queue.SpiderPriorityQueue'\n# 请求调度使用FIFO队列\n#SCHEDULER_QUEUE_CLASS = 'scrapy_redis.queue.SpiderQueue'\n# 请求调度使用LIFO队列\n#SCHEDULER_QUEUE_CLASS = 'scrapy_redis.queue.SpiderStack'\n# 最大的空闲时间,避免分布式爬取得情况下爬虫被关闭\n# 此设置只适用于SpiderQueue和SpiderStack\n# 也是爬虫第一次启动时的等待时间(应为队列是空的)\nSCHEDULER_IDLE_BEFORE_CLOSE = 10\n###########################################################################\n\n\n#######################redis-setting#######################################\n# 指定redis的地址和端口(可选,程序将使用默认的地址localhost:6379)\nREDIS_HOST = '115.159.194.211'\nREDIS_PORT = 6379\n\n\n# 声明redis的url地址(可选)\n# 如果设置了这一项,则程序会有限采用此项设置,忽略REDIS_HOST 和 REDIS_PORT的设置\n#REDIS_URL = 'redis://user:pass@hostname:9001'\n\n###########################################################################\n# 爬虫状态信息\nSTATS_CLASS = 'tutorial.scrapy_graphite.graphite.RedisGraphiteStatsCollector'\n\n# graphite 设置\nGRAPHITE_HOST = '115.159.194.211'\nGRAPHITE_PORT = 2003\nGRAPHITE_IGNOREKEYS = []\n\n\n###############################proxy-ip####################################\n\nPROXIES = [\n #{'ip_port': '111.11.228.75:80', 'user_pass': ''},\n #{'ip_port': '120.198.243.22:80', 'user_pass': ''},\n #{'ip_port': '111.8.60.9:8123', 'user_pass': ''},\n #{'ip_port': '101.71.27.120:80', 'user_pass': ''},\n #{'ip_port': '122.96.59.104:80', 'user_pass': ''},\n #{'ip_port': '122.224.249.122:8088', 'user_pass': ''},\n]\n\n###########################################################################\n\n#CONCURRENT_REQUESTS_PER_DOMAIN = 10\n\n# Configure maximum concurrent requests performed by Scrapy (default: 16)\n#CONCURRENT_REQUESTS=32\n\n# Configure a delay for requests for the same website (default: 0)\n# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay\n# See also autothrottle settings and docs\n#DOWNLOAD_DELAY=3\n# The download delay setting will honor only one of:\n#CONCURRENT_REQUESTS_PER_DOMAIN=16\n#CONCURRENT_REQUESTS_PER_IP=16\n\n# Disable cookies (enabled by default)\n#COOKIES_ENABLED=False\n\n# Disable Telnet Console (enabled by default)\n#TELNETCONSOLE_ENABLED=False\n\n# Override the default request headers:\n#DEFAULT_REQUEST_HEADERS = {\n# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n# 'Accept-Language': 'en',\n#}\n\n# Enable or disable spider middlewares\n# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html\n#SPIDER_MIDDLEWARES = {\n# 'tutorial.middlewares.MyCustomSpiderMiddleware': 543,\n#}\n\n# Enable or disable downloader middlewares\n# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html\n#DOWNLOADER_MIDDLEWARES = {\n# 'tutorial.middlewares.MyCustomDownloaderMiddleware': 543,\n#}\n\n# Enable or disable extensions\n# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html\n#EXTENSIONS = {\n# 'scrapy.telnet.TelnetConsole': None,\n#}\n\n# Configure item pipelines\n# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html\n\n\n# Enable and configure the AutoThrottle extension (disabled by default)\n# See http://doc.scrapy.org/en/latest/topics/autothrottle.html\n# NOTE: AutoThrottle will honour the standard settings for concurrency and delay\n#AUTOTHROTTLE_ENABLED=True\n# The initial download delay\n#AUTOTHROTTLE_START_DELAY=5\n# The maximum download delay to be set in case of high latencies\n#AUTOTHROTTLE_MAX_DELAY=60\n# Enable showing throttling stats for every response received:\n#AUTOTHROTTLE_DEBUG=False\n\n# Enable and configure HTTP caching (disabled by default)\n# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings\n#HTTPCACHE_ENABLED=True\n#HTTPCACHE_EXPIRATION_SECS=0\n#HTTPCACHE_DIR='httpcache'\n#HTTPCACHE_IGNORE_HTTP_CODES=[]\n#HTTPCACHE_STORAGE='scrapy.extensions.httpcache.FilesystemCacheStorage'\n","sub_path":"slave/tutorial/tutorial/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"248743519","text":"import sys\nimport numpy as np\nimport os\nfrom OnClass.utils import *\nfrom OnClass.OnClassPred import OnClassPred\nfrom OnClass.other_datasets_utils import my_assemble, data_names_all, load_names \n\nDATA_DIR = '../../../OnClass_data/'\nOUTPUT_DIR = DATA_DIR + '/marker_genes/'\nif not os.path.exists(OUTPUT_DIR):\n\tos.makedirs(OUTPUT_DIR)\n\t\n## read data\ndata_file = DATA_DIR + '/raw_data/tabula-muris-senis-facs'\n\nif not os.path.isfile(OUTPUT_DIR + 'FACS-predicted_score_matrix.npy'):\n\ttrain_X, train_Y_str, genes_list = read_data(filename=data_file, DATA_DIR=DATA_DIR, return_genes=True)\n\ttms_genes_list = [x.upper() for x in list(genes_list.values())[0]]\n\tntrain,ngene = np.shape(train_X)\n\t## embedd the cell ontology\n\tunseen_l, l2i, i2l, onto_net, Y_emb, cls2cls = ParseCLOnto(train_Y_str, co_dim = 200, co_mi = 0, DATA_DIR=DATA_DIR)\n\ttrain_Y = MapLabel2CL(train_Y_str, l2i)\n\n\t## train and predict\n\tOnClass_obj = OnClassPred()\n\tOnClass_obj.train(train_X, train_Y, Y_emb, max_iter=20, nhidden=[100])\n\ttest_Y_pred = OnClass_obj.predict(train_X)\n\n\tnp.save(OUTPUT_DIR + 'FACS-predicted_score_matrix.npy', test_Y_pred)\n\nfig_dir = '../../OnClass_data/figures/marker_gene/'\nif not os.path.exists(fig_dir):\n\tos.makedirs(fig_dir)\n\t\n## read data\ntrain_X, train_Y_str, genes_list = read_data(filename=data_file, DATA_DIR=DATA_DIR, return_genes=True)\ntrain_X = np.log1p(train_X.todense()+1)\ntms_genes_list = [x.upper() for x in list(genes_list.values())[0]]\nunseen_l, l2i, i2l, onto_net, Y_emb, cls2cls = ParseCLOnto(train_Y_str, DATA_DIR=DATA_DIR)\ntrain_Y = MapLabel2CL(train_Y_str, l2i)\ngenes = genes_list[datanames[0]]\ng2i = {}\ni2g = {}\nfor i,g in enumerate(genes):\n\tg2i[g.lower()] = i\n\ti2g[i] = g\nngene = len(genes)\ntest_Y_pred = np.load(OUTPUT_DIR + 'FACS-predicted_score_matrix.npy')\n\n## Differential expression analysis\nncell = np.shape(test_Y_pred)[0]\nco2name, name2co = get_ontology_name(DATA_DIR=DATA_DIR)\ntp2genes = read_type2genes(g2i, DATA_DIR=DATA_DIR)\nthres = np.array(range(1,1000))\ntopk = 50\nin_tms_ranks = []\nnot_tms_ranks = []\nn_in_tms =0\nfor tp in tp2genes:\n\tci = l2i[tp]\n\tk_bot_cells = np.argsort(test_Y_pred[:,ci])[:topk]\n\tk_top_cells = np.argsort(test_Y_pred[:,ci])[ncell-topk:]\n\tpv = scipy.stats.ttest_ind(train_X[k_top_cells,:], train_X[k_bot_cells,:], axis=0)[1]\n\ttop_mean = np.mean(train_X[k_top_cells,:],axis=0)\n\tbot_mean = np.mean(train_X[k_bot_cells,:],axis=0)\n\tfor g in range(ngene):\n\t\tif top_mean[0,g] < bot_mean[0,g]:\n\t\t\tpv[g] = 1.\n\tpv_sort = list(np.argsort(pv))\n\tmin_rank = 1000000\n\tfor g in tp2genes[tp]:\n\t\tgid = g2i[g.lower()]\n\t\trank = pv_sort.index(gid)\n\t\tmin_rank = min(rank, min_rank)\n\tif ci in np.unique(train_Y):\n\t\tin_tms_ranks.append(min_rank)\n\telse:\n\t\tnot_tms_ranks.append(min_rank)\n\nnot_tms_ranks = np.array(not_tms_ranks)\nin_tms_ranks = np.array(in_tms_ranks)\n\n\nin_tms_y = []\nnot_tms_y = []\nfor t in thres:\n\tin_tms_y.append( len(np.where(in_tms_ranks <= t)[0]) / len(in_tms_ranks))\n\tnot_tms_y.append( len(np.where(not_tms_ranks <= t)[0]) / len(not_tms_ranks))\n\n\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\nplt.plot(thres, in_tms_y, 'g', label='Seen cell types (n=%d)'%len(in_tms_ranks), linewidth=2)\nplt.plot(thres, not_tms_y, 'y', label='Unseen cell types (n=%d)'%len(not_tms_ranks), linewidth=2)\nplt.legend(loc=\"lower right\",frameon=False)\n\nplt.ylabel('Percentage of cell types')\nplt.xlabel('Rank of marker genes')\n#ax.yaxis.set_major_formatter(FuncFormatter('{0:.0%}'.format))\nvals = ax.get_yticks()\nax.set_yticklabels(['{:,.0%}'.format(x) for x in vals])\nplt.tight_layout()\nplt.savefig(fig_dir+'mark_genes.pdf')\n\n## Write marker genes to file\nfmarker_genes = open(OUTPUT_DIR+'marker_genes.txt','w')\nfor ci in range(nlabel):\n\ttp = i2l[ci]\n\tk_bot_cells = np.argsort(test_Y_pred[:,ci])[:topk]\n\tk_top_cells = np.argsort(test_Y_pred[:,ci])[ncell-topk:]\n\tpv = scipy.stats.ttest_ind(train_X[k_top_cells,:], train_X[k_bot_cells,:], axis=0)[1]\n\ttop_mean = np.mean(train_X[k_top_cells,:],axis=0)\n\tbot_mean = np.mean(train_X[k_bot_cells,:],axis=0)\n\tfor g in range(ngene):\n\t\tif top_mean[0,g] < bot_mean[0,g]:\n\t\t\tpv[g] = 1.\n\tpv_sort = list(np.argsort(pv))\n\tmin_rank = 1000000\n\tfmarker_genes.write(tp+'\\t')\n\tfor i in range(100):\n\t\tfmarker_genes.write(i2g[pv_sort[i]]+'\\t')\n\tfmarker_genes.write('\\n')\nfmarker_genes.close()","sub_path":"scripts/MarkerGenesIdentification/FindMarkerGenes.py","file_name":"FindMarkerGenes.py","file_ext":"py","file_size_in_byte":4244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"389490473","text":"import numpy\nimport pytest\n\nfrom helpers import *\nfrom reikna.linalg import EntrywiseNorm\n\n\n@pytest.mark.parametrize('dtype', [numpy.float32, numpy.complex64], ids=['float32', 'complex64'])\n@pytest.mark.parametrize('order', [0.5, 1, 2])\ndef test_entrywise_norm(thr, dtype, order):\n\n a = get_test_array(1000, dtype)\n a_dev = thr.to_device(a)\n\n norm = EntrywiseNorm(a_dev, order=order)\n\n b_dev = thr.empty_like(norm.parameter.output)\n b_ref = numpy.linalg.norm(a, ord=order).astype(norm.parameter.output.dtype)\n\n normc = norm.compile(thr)\n normc(b_dev, a_dev)\n\n assert diff_is_negligible(b_dev.get(), b_ref)\n","sub_path":"test/test_linalg/test_norm.py","file_name":"test_norm.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"262024948","text":"# (C) Datadog, Inc. 2010-present\n# All rights reserved\n# Licensed under Simplified BSD License (see LICENSE)\nfrom six import iteritems\n\n\ndef freeze(o):\n \"\"\"\n Freezes any mutable object including dictionaries and lists for hashing.\n Accepts nested dictionaries.\n \"\"\"\n\n # NOTE: we sort items in containers so that the resulting frozen structure (and its hash) don't depend\n # on the order of those items. In other words: `hash_mutable([1, 2]) == hash_mutable([2, 1])`.\n # So, the sort `key` can be any function that uniquely maps a value to another.\n # We used to use the identify function, i.e. no `key` (or `key=lambda x: x`), but this prevented freezing\n # containers that contain `None` values, since on Python 3 those can't be compared with anything else.\n # The `hash` built-in is a function that uniquely maps values, while being also applicable to all immutable objects.\n # See: https://github.com/DataDog/integrations-core/pull/7763\n key = hash\n\n if isinstance(o, (tuple, list)):\n return tuple(sorted((freeze(e) for e in o), key=key))\n\n if isinstance(o, dict):\n return tuple(sorted(((k, freeze(v)) for k, v in iteritems(o)), key=key))\n\n if isinstance(o, (set, frozenset)):\n return tuple(sorted((freeze(e) for e in o), key=key))\n\n return o\n\n\ndef hash_mutable(m):\n return hash(freeze(m))\n\n\ndef iter_unique(*iterables):\n seen = set()\n\n for iterable in iterables:\n for item in iterable:\n item_id = hash_mutable(item)\n\n if item_id in seen:\n continue\n\n seen.add(item_id)\n yield item\n","sub_path":"datadog_checks_base/datadog_checks/base/utils/containers.py","file_name":"containers.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"271731480","text":"from uuid import uuid4\n\nfrom fastapi import FastAPI, HTTPException\nfrom orm import NoMatch\nfrom pydantic import BaseModel, Field\nfrom starlette.requests import Request\n\nfrom game import (\n GameList,\n GameSchema,\n CreateGame,\n State,\n JoinGame,\n InvalidState\n)\n\nfrom handlers import (\n create_game,\n list_games,\n find_game,\n update_game,\n join_game\n)\n\napp = FastAPI(\n docs_url=\"/api/schema\",\n redoc_url=\"/api/redoc\"\n)\n\n\n@app.get(\"/api/games\")\nasync def games() -> GameList:\n return await list_games()\n\n\n@app.post(\"/api/games\", response_model=GameSchema)\nasync def create(request: Request, game_data: CreateGame):\n return await create_game(request, game_data)\n\n\n@app.get(\"/api/games/{game_id}\", response_model=GameSchema)\nasync def get_game(game_id: int):\n try:\n return await find_game(game_id)\n except NoMatch:\n raise HTTPException(status_code=404)\n\n\nclass StateUpdate(BaseModel):\n state: State = Field(None, title=\"New state to set\")\n\n\n@app.post(\"/api/games/{game_id}\", response_model=GameSchema)\nasync def update(game_id: int, state_update: StateUpdate):\n try:\n return await update_game(game_id, state_update.state)\n except InvalidState:\n raise HTTPException(status_code=400)\n except NoMatch:\n raise HTTPException(status_code=404)\n\n\n@app.post(\"/api/games/{game_id}/join\", response_model=GameSchema)\nasync def join(request: Request, game_id: int, join_data: JoinGame):\n try:\n return await join_game(request, game_id, join_data)\n except NoMatch:\n raise HTTPException(status_code=404)\n\n\n@app.middleware(\"http\")\nasync def player_session(request: Request, call_next):\n response = await call_next(request)\n if not request.cookies.get(\"player_id\"):\n response.set_cookie(\"player_id\", id(uuid4()))\n\n return response\n","sub_path":"app/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"333191761","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 21 18:55:50 2017\n\n@author: RyanMunguia\n\"\"\"\n\n#Given an array with multiple values, write a function that returns a new array\n#that only contains the maximum, minimum, and average values of the original array. \n#(e.g. [1,5,10,-2] will return [10,-2,3.5])\n\ndef maxMinAvg(arr):\n sum = 0\n max = arr[0]\n min = arr[0]\n for i in arr:\n if i > max:\n max = i\n elif i < min:\n min = i\n sum += i\n av = sum/len(arr)\n newArr = [max,min,av]\n return newArr\n \n\nprint(maxMinAvg([1,5,10,-2]))\n \n \n\n","sub_path":"algos/maxMinAvg.py","file_name":"maxMinAvg.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"544684515","text":"\nlearning_rate = 0.1 # 实现设定好的初始学习率\ndecay_rate = 0.99 #衰减系数\ndecay_steps = 5.0 #衰减速度,若参数staircase=True,则反应为每decay_steps次迭代之后更新一次learning_rate\nglobal_step = 5 #当前迭代次数\n\n\n\n\n\nfor global_step in range(1000):\n decayed_learning_rate = learning_rate * decay_rate ** int((global_step / decay_steps))\n print(decayed_learning_rate)\n\n#\n# import tensorflow as tf\n#\n# global_step = tf.Variable(0)\n#\n# learning_rate = tf.train.exponential_decay(\n# 0.1,global_step,100,0.96,staircase=True\n# )\n# learning_step = tf.train.GradientDescentOptimizer(learning_rate).\n\n\n\n","sub_path":"part4_Deep_Network/指数衰减学习率/decayed_learning_rate.py","file_name":"decayed_learning_rate.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"606939534","text":"import requests, json, cv2\nfrom PIL import Image\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n#URL = 'http://127.0.0.1:5000/v1/models/addtest:predict'\nURL = 'http://143.248.96.81:35005/api/predict'\n\n\nimg_path = './data/ki_corridor/2.png'\nim1 = cv2.imread(img_path)\n\nif im1.shape != [480,640]:\n im1 = cv2.resize(im1, (640, 480))\n\nim1=cv2.cvtColor(im1, cv2.COLOR_RGB2BGR)\nprint(im1.shape)\nrNum = 480\ncNum = 640\n\nstrImgTest = '['\nfor r in range(rNum):\n strImgTest+='['\n for c in range(cNum):\n strTmp = '['+str((im1[r][c][0]))+','+str((im1[r][c][1]))+','+str((im1[r][c][2]))+']'\n strImgTest+=strTmp\n\n if c !=cNum-1 :\n strImgTest+=','\n strImgTest+=']'\n if r != rNum-1:\n strImgTest += ','\nstrImgTest+=']'\n\n#plt.figure(figsize=(20, 15))\n#plt.imshow(img)\n#plt.show()\n\nres = requests.post(url=URL, data={'image':strImgTest})\nprint(res.text)","sub_path":"DeepLabAPI/JK/FlaskClient.py","file_name":"FlaskClient.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"133427842","text":"\"\"\"\nBuild_Geomorph_Raster.py\n\nThis script builds a raster of the geomorphic and site potential codes\ndescribed in the Willamette Basin TMDL.\n\nThe site potential vegetation scenario and related vegetation classes\nwere developed using the same methods described in the 2006 TMDL.\n\nPython scripts were developed to process the geomorphic raster\nand translate geomorphic codes into site potential vegetation codes \n\nThe original geomorphic feature class used in the 2006 TMDL had two \nlimitations that needed to be addressed for modeling in the southern Willamette.\n\nThe limitations concern two land cover classes for water: open water\nand general water. \n\n General water (code 3011) are areas which include natural river\nchannels, lakes, ponds, or wetland areas. Under the site potential\nvegetation scenario these features continued to stay as water. The 2006 effort\n mapped these areas using aerial photos and digitized them into a landcover\nfeature class only at locations that were modeled. For this\nproject water features that would have code 3011 needed to be\nmapped across the entire study area. The National Wetland Inventory\n(USFWS 2004) and the National Hydrography Dataset high resolution\nv2.2 databases contain extensive inventories of water features and\nwere incorporated into geomorphic raster. \n\nNWI's classification system (Cowardin et al 2013) allowed the removal of\nmost anthropogenic related water areas such as impounded reservoirs\nand gravel mining ponds. Water's classified as Lacustrine (L),\nPalustrine (P), Marine (M), or Estuarine (E) that are NOT forested (FO),\nscrub/shrub (SS), diked/impounded (h), a spoil (s), or excavated (x) were\ncoded as general water. Forested and scrub/shrub classes were removed\nbecause they have emergent or overhanging vegetation. The NHD high\nchannel areas were used to map the riverine reaches because in some areas\nit was a little more accurate than NWI where the channel has migrated\nin recent years, mostly in portions of the Willamette River.\n\nOpen water (code 2000) are areas representing the ACOE reservoirs\nwithin the boundaries of the original geomorphic feature class and other\nanthropogenic related water areas that did not meet the criteria for\ngeneral water. Under the classification rules for site potential\nvegetation these areas were treated as prairie or savanna vegetation\ntypes. In the upland forest zone impounded reservoirs were not mapped.\nThey were classified as upland forest (code 1900). The intent was that\nthese site potential vegetation types would be present along the\nnatural unimpouned channel (rather than actually present in the\nriver channel). The reservoirs were not modeled so no effort was made\nto map the location of the natural (unimpounded) water channel.\n\n\"\"\"\nfrom __future__ import print_function\n\nfrom operator import itemgetter\nimport csv\nimport random\nimport numpy\n\nimport arcpy\nfrom arcpy import env\n\nfrom arcpy.sa import *\n#from arcpy.sa import Con\n#from arcpy.sa import Nibble\n#from arcpy.sa import SetNull\narcpy.CheckOutExtension(\"Spatial\")\n\nworking_dir = r\"F:\\WorkSpace\\Quantifying_Conservation_2014\\SouthernWillamette\\Site_Potential_Geomorph.gdb\"\nenv.workspace = working_dir\n\n# This csv file contains the probability of occurrence for each vegetation \n# type within each geomorphic unit. \n# This comes from Table 1 on page C-18 in the TMDL Appendix C\ninput_geomorph = r\"C:\\WorkSpace\\Quantifying_Conservation_2014\\SouthernWillamette\\Site_Potential\\geomorph_probability_table.csv\"\n\n# This is the geomorph fc from the Willamette TMDL project files \n# clipped to the S. Willamette and reprojected into lambert (ogic)\ngeomorph_fc1 = r\"geomorph_fc_s01_from_TMDL\"\narcpy.env.extent = geomorph_fc1\n\n# This is nhd high areas v 2.20 cliped to the S. Willamette and \n# reprojected into lambert (ogic). They are being used to identify\n# riverine channel areas because they correspond to \n# the flowlines used to generate the stream nodes.\n# These areas will be coded as water (3011)\nnhd_fc = r\"NHDH_Area_v220_s01\"\n\n# This is nwi v 20141006 cliped to the S. Willamette and \n# reprojected into lambert (ogic). It is being used to identify the \n# impounded open water (OW) areas, such as ACOE reserovirs and also \n# wetlands, lakes, or ponds which will be coded as general water (3011).\nnwi_fc1 = r\"NWI_v20141006_s01\"\n\n# outputs\nnhd_fc2 = r\"NHDH_Area_v220_s02\"\nnwi_fc2 = r\"NWI_v20141006_s02\"\nnwi_fc3 = r\"NWI_v20141006_s03\"\n\ngeomorph_fc2 = r\"geomorph_fc_s02\"\ngeomorph_fc3 = r\"geomorph_fc_s03_final\"\n\nwater_fc1 = r\"water_features_s01\"\n\nout_raster1 = r\"geomorph_codes_s01\"\nout_raster2 = r\"geomorph_codes_s02\"\nout_raster3 = r\"geomorph_codes_s03_final\"\nout_raster4 = r\"site_pot_codes_s04_final\"\n\ndef read_csv_dict(csvfile, key_col, val_col, skipheader=True):\n \"\"\"Reads an input csv file and returns a dictionary with\n one of the columns as the dictionary keys and another as the values\"\"\"\n with open(csvfile, \"rb\") as f:\n reader = csv.reader(f)\n if skipheader == True: reader.next()\n csvdict = dict((row[key_col], row[val_col[0]:val_col[1]]) for row in reader)\n return csvdict\n\n# This is the rex SQL query to select NWI attribute codes that will be coded as \n# water - 3011. It corresponds to Lacustrine (L), Palustrine (P), Marine (M),\n# or Estuarine (E) waters that are not forested (FO), scrub/shrub (SS),\n# diked/impounded (h), spoil (s), or excavated (x).\n# Note Riverine (R) waters are excluded because those are covered \n# by the NHD.\n# Refer to NWI documentation for meaning of the codes\n# http://www.fws.gov/wetlands/Documents/NWI_Wetlands_and_Deepwater_Map_Code_Diagram.pdf\nnwi_to_water = ('''(ATTRIBUTE LIKE ('%L%') OR \n ATTRIBUTE LIKE ('%P%') OR\n ATTRIBUTE LIKE ('%E%') OR\n ATTRIBUTE LIKE ('%M%')) AND\n (ATTRIBUTE NOT LIKE ('%FO%') AND\n ATTRIBUTE NOT LIKE ('%SS%') AND\n ATTRIBUTE NOT LIKE ('%h%') AND\n ATTRIBUTE NOT LIKE ('%x%') AND\n ATTRIBUTE NOT LIKE ('%s%'))''')\n\n# This is the rex SQL query to select NWI attribute codes that \n# correspond to Lacustrine (L) limnetic or littoral systems \n# that are diked/impounded (h). \n# These codes will be reclassed as open water (OW), which is \n# geomorph code 2000.\nnwi_to_ow = '''ATTRIBUTE LIKE ('%L%h%')'''\n\n# Make a new copy of the NWI\nif not arcpy.Exists(nwi_fc2):\n arcpy.FeatureClassToFeatureClass_conversion(nwi_fc1, out_path=working_dir, \n out_name=nwi_fc2)\n\n # outdent <----\n\n # Add a new fields into the NWI and NHD for the reclass code\n arcpy.AddField_management(nwi_fc2, \"TYPE\", \"TEXT\", \"\", \"\", \"\",\n \"\", \"NULLABLE\", \"NON_REQUIRED\")\n arcpy.AddField_management(nhd_fc, \"TYPE\", \"TEXT\", \"\", \"\", \"\",\n \"\", \"NULLABLE\", \"NON_REQUIRED\")\n \n arcpy.AddField_management(nwi_fc2, \"GEOMORPH\", \"DOUBLE\", \"\", \"\", \"\",\n \"\", \"NULLABLE\", \"NON_REQUIRED\")\n arcpy.AddField_management(nhd_fc, \"GEOMORPH\", \"DOUBLE\", \"\", \"\", \"\",\n \"\", \"NULLABLE\", \"NON_REQUIRED\")\n \n # select NHD features, code as 3011\n update_fields = [\"TYPE\", \"GEOMORPH\"]\n with arcpy.da.UpdateCursor(nhd_fc, update_fields) as cursor: \n for row in cursor:\n row[0] = \"Wa\"\n row[1] = 3011\n cursor.updateRow(row)\n \n # select NWI water features, code as 3011\n query_field = [\"ATTRIBUTE\"]\n with arcpy.da.UpdateCursor(nwi_fc2, query_field + update_fields, \n nwi_to_water) as cursor: \n for row in cursor:\n row[1] = \"Wa\"\n row[2] = 3011\n cursor.updateRow(row)\n \n # select NWI open water features, code as 2000\n with arcpy.da.UpdateCursor(nwi_fc2, query_field + update_fields, \n nwi_to_ow) as cursor: \n for row in cursor:\n row[1] = \"OW\"\n row[2] = 2000\n cursor.updateRow(row)\n \n# Copy only the NWI features that were just changed\nif not arcpy.Exists(nwi_fc3):\n nwi2_sql_query = \"\"\"GEOMORPH IN (2000, 3011)\"\"\"\n arcpy.FeatureClassToFeatureClass_conversion(nwi_fc2, working_dir,\n nwi_fc3, nwi2_sql_query)\n\n# Erase overlapping NWI features in the NHD \nif not arcpy.Exists(nhd_fc2):\n arcpy.Erase_analysis(nhd_fc, nwi_fc3, nhd_fc2)\n\n# merge the nwi and nhd\nif not arcpy.Exists(water_fc1):\n arcpy.Merge_management([nwi_fc3, nhd_fc2], water_fc1)\n\n\nif not arcpy.Exists(geomorph_fc2):\n arcpy.Erase_analysis(geomorph_fc1, water_fc1, geomorph_fc2)\n\n# merge the water fc and geomorph\nif not arcpy.Exists(geomorph_fc3):\n arcpy.Merge_management([geomorph_fc2, water_fc1], geomorph_fc3)\n\n# convert to raster\nif not arcpy.Exists(out_raster1):\n arcpy.PolygonToRaster_conversion(geomorph_fc3, \"GEOMORPH\", out_raster1, \"CELL_CENTER\", \"NONE\" , 9)\nelse:\n raster1 = arcpy.Raster(out_raster1)\n\n# make a null mask for the areas to use in the nibble\nif not arcpy.Exists(out_raster2):\n print(\"set null\")\n raster2 = arcpy.sa.SetNull(out_raster1,out_raster1,\"VALUE IN (900, 2000, 3011)\")\n raster2.save(out_raster2)\nelse:\n raster2 = arcpy.Raster(out_raster2)\n \n# implement nearest neighbor on Qg2 (900) but keep water (2000, 3011) the same\nif not arcpy.Exists(out_raster3):\n print(\"nearest neighbor nibble\")\n raster3 = arcpy.sa.Con(out_raster1, out_raster1,\n Nibble(out_raster1,\n out_raster2,\n \"DATA_ONLY\"),\n \"VALUE IN (2000, 3011)\")\n raster3.save(out_raster3)\nelse:\n raster3 = arcpy.Raster(out_raster3)\n \n# Now implement the the site potential rules\nif not arcpy.Exists(out_raster4):\n print(\"Apply site potential rules\")\n \n arcpy.env.extent = raster3\n arcpy.env.snapRaster = raster3\n \n # get the coordinate system\n coord_sys = arcpy.Describe(raster3).spatialReference\n arcpy.env.outputCoordinateSystem = coord_sys\n \n # read in the geomorhic codes and vegetation probabilities\n geodict = read_csv_dict(input_geomorph, key_col=1, val_col=[2, 8], skipheader=True) \n \n # may need blocking here\n \n lowerLeft = arcpy.Point(raster3.extent.XMin, raster3.extent.YMin)\n cell_size = raster3.meanCellWidth \n \n # in feet\n block_size = 45000\n \n block_cells = int(block_size / cell_size)\n \n # cols/rows\n x_width = raster3.width\n y_width = raster3.height\n \n x_min = raster3.extent.XMin\n y_min = raster3.extent.YMin\n \n x_max = raster3.extent.XMax\n y_max = raster3.extent.YMax\n \n na_value = raster3.noDataValue\n \n if na_value is None:\n na_value = 0\n \n raster4_names = []\n \n x_n = len(range(0, x_width, block_cells))\n y_n = len(range(0, y_width, block_cells))\n n_total = x_n * y_n\n block_n = 0\n \n # Build data blocks\n for x in range(0, x_width, block_cells):\n for y in range(0, y_width, block_cells):\n \n print(\"Processing block {0} of {1}\".format(block_n+1, n_total))\n \n # Name the temp raster\n raster4_name = r\"temp_block_{0}\".format(block_n)\n \n # Lower left coordinate of block (in map units)\n block0_x_min = x_min + (x * cell_size)\n block0_y_min = y_min + (y * cell_size)\n # Upper right coordinate of block (in map units)\n block0_x_max = min([block0_x_min + block_size, x_max])\n block0_y_max = min([block0_y_min + block_size, y_max])\n \n block_array = arcpy.RasterToNumPyArray(raster3,\n lower_left_corner=arcpy.Point(block0_x_min, block0_y_min),\n ncols=block_cells , nrows=block_cells)\n \n # Continue to next block if there are no values\n if block_array.max() <= 0:\n del block_array\n block_n += 1\n continue\n \n # Continue to next block if it already exists \n # but add to names list\n if arcpy.Exists(raster4_name):\n del block_array\n raster4_names.append(raster4_name)\n block_n += 1\n continue \n \n # Get the count of unique values\n block_unique = numpy.unique(block_array, return_counts=False)\n \n for geocode in block_unique:\n \n if geocode in [na_value, 3011]: continue\n \n geocode_index = numpy.where(numpy.in1d(block_array.ravel(), [geocode]).reshape(block_array.shape))\n \n # Count the number of array elements equal to the geocode\n geocode_len = len(geocode_index[0])\n \n # Generate an equal number of site potential codes \n # where the count of each site potential code is equal \n # to the distribution established in the TMDL \n param = geodict[str(geocode)]\n forest = [int(param[3])] * int(round(float(param[0]) * geocode_len))\n savanna = [int(param[4])] * int(round(float(param[1]) * geocode_len))\n prairie = [int(param[5])] * int(round(float(param[2]) * geocode_len))\n \n spc = forest + savanna + prairie\n \n m = geocode_len - len(spc)\n \n if m > 0:\n # need to add some values\n random.seed(33)\n spc = spc + [int(param[random.randint(3, 5)]) for i in range(m)]\n \n \n # set the random seed so this is repeatable\n random.seed(42)\n # shuffle the order\n random.shuffle(spc)\n \n # replace array values with the site potential codes\n for i in range(0, geocode_len):\n \n r = geocode_index[0][i]\n c = geocode_index[1][i]\n block_array[r, c] = spc[i]\n \n \n del geocode_index\n \n # Convert data block back to raster\n arcpy.env.extent = arcpy.Extent(block0_x_min, block0_y_min, block0_x_max, block0_y_max)\n raster4_block = arcpy.NumPyArrayToRaster(block_array,\n arcpy.Point(block0_x_min, block0_y_min),\n cell_size,\n cell_size, na_value)\n # output the temp raster\n raster4_block.save(raster4_name)\n \n raster4_names.append(raster4_name)\n block_n += 1\n \n del block_array\n del raster4_block\n \n arcpy.MosaicToNewRaster_management(input_rasters=raster4_names,\n output_location=working_dir,\n raster_dataset_name_with_extension=out_raster4,\n pixel_type='16_BIT_UNSIGNED',\n number_of_bands=1)\n \n # Rebuild the attribute table because it does not seem to \n # get compleated in the process above\n arcpy.BuildRasterAttributeTable_management(in_raster=out_raster4, overwrite=\"Overwrite\")\n \n # Remove temporary files\n if arcpy.Exists(out_raster4):\n for raster4_name in raster4_names:\n if arcpy.Exists(raster4_name):\n arcpy.Delete_management(raster4_name)\n\nprint(\"done\")","sub_path":"QC_S_Willamette/Build_SitePotential_raster.py","file_name":"Build_SitePotential_raster.py","file_ext":"py","file_size_in_byte":15921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"436715876","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\n\n \n# read in files\ndf = pd.read_excel('MergedProj1.xlsx')\n\n\n# drop unncessary colums \nX = df.drop(columns=['name','category','main_category','currency','deadline','state','country','launched'])\n\nprint(X.head())\n\n\n# add in categorical data \n\n# main_Category\n\ndf['main_category'] = pd.Categorical(df['main_category'])\n\ndfDummies = pd.get_dummies(df['main_category'], prefix = 'category')\n\n\nX = pd.concat([X, dfDummies], axis=1)\n\n#Category\n\ndf['category'] = pd.Categorical(df['category'])\n\ndfDummies = pd.get_dummies(df['category'], prefix = 'category')\n\n\nX = pd.concat([X, dfDummies], axis=1)\n\n\n#Country\n\ndf['country'] = pd.Categorical(df['country'])\n\ndfDummies = pd.get_dummies(df['country'], prefix = 'category')\n\n\nX = pd.concat([X, dfDummies], axis=1)\n\n\n\n# column to predict \ny = df['state'].values \n\n# split training data \nprint(\"Split data\\n\")\n\nX_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.2, random_state=1, stratify=y)\n\nprint(\"train data\\n\")\nprint(\"k = 10\\n\")\nknn = KNeighborsClassifier(n_neighbors = 10)\n\n# accuracy of whole dataset\n\nknn.fit(X_train,y_train)\n\nprint(\"predict data\\n\")\nprint(knn.predict(X_test)[0:])\n\nprint(\"Accuracy\\n\")\nprint(knn.score(X_test, y_test))\n\n## write something to find the difference between start and deadline.","sub_path":"CA4010-Data Warehousing and Data Mining/oneEncoderBoi.py","file_name":"oneEncoderBoi.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"289947288","text":"# coding=utf8\nfrom appium import webdriver\nimport time\nimport traceback\n\n\ndesired_caps = {}\ndesired_caps['platformName'] = 'Android' #测试平台\ndesired_caps['platformVersion'] = '9' #平台版本,不能写错\ndesired_caps['deviceName'] = 'test' #设备名称,多设备时需区分\n#desired_caps['app'] = r'd:\\apk\\HiSpace.apk' #app 文件 名,指定了要安装的app 在电脑上的路径\ndesired_caps['appPackage'] = 'com.huawei.appmarket' #app package名,指定了要运行的app\ndesired_caps['appActivity'] = '.MainActivity' #app默认Activity\n# desired_caps['unicodeKeyboard'] = True # 一定要有该参数,否则unicode 输入的中文无效\n# desired_caps['automationName'] = 'uiautomator2'\ndesired_caps['noReset'] = True\ndesired_caps['newCommandTimeout'] = 6000\n\ndriver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) #启动Remote RPC\ndriver.implicitly_wait(10)\n\n\n'''\nwindow_size=driver.get_window_size()\nheight=window_size['height']\nwidth=window_size['width']\nstart_x=width*0.5\nend_y=height*0.1\nstart_y=height*0.9\n\ntry:\n for i in range(3):\n driver.swipe(start_x,start_y,start_x,end_y,2000)\n time.sleep(2)\nexcept:\n print(traceback.format_exc())\n\ninput('**** Press to quit..')\ndriver.quit()\n'''\n\n\nwindow_size=driver.get_window_size()\nheight=window_size['height']\nwidth=window_size['width']\nstart_x=width*0.5\nend_y=height*0.1\nstart_y=height*0.9\n\nbanner=driver.find_element_by_id('com.huawei.appmarket:id/backPicture')\nleftop=banner.location\n\nele_size=banner.size\n\ncenter_x=leftop['x']+ele_size['width']*0.5\ncenter_y=leftop['y']+ele_size['height']*0.5\n\nprint(center_x,center_y)\n\nstart_x=leftop['x']+ele_size['width']*0.2\nend_x=leftop['x']+ele_size['width']*0.8\n\n\ntry:\n for i in range(10):\n driver.swipe(start_x,center_y,end_x,center_y,200)\n time.sleep(0.2)\nexcept:\n print(traceback.format_exc())\n\ninput('**** Press to quit..')\ndriver.quit()","sub_path":"vova_project/vova_resful/sept/appium-1/华为商城.py","file_name":"华为商城.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"482150100","text":"import numpy as np\nimport sys\n\n# no dependence - vectorizable\n# jump in data access\ndef s1111(a, b, c, d):\n for i in range(a.shape[0]//2):\n a[2*i] = c[i] * b[i] + d[i] * b[i] + c[i] * c[i] + d[i] * b[i] + d[i] * c[i]\n\nif __name__ == '__main__':\n size = int(sys.argv[1])\n a = np.arange(size)\n b = np.arange(size)\n c = np.arange(size)\n d = np.arange(size)\n\n s1111(a, b, c, d)\n\n","sub_path":"perf_test/s1111.py","file_name":"s1111.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"549279160","text":"class Solution:\n def permuteUnique(self, nums: List[int]) -> List[List[int]]:\n if len(nums) < 2: return [nums]\n sorted(nums)\n res = []\n def __impl(nums, s, e):\n if s == e: res.append(nums[:])\n else:\n for i in range(len(nums) - 1):\n while nums[i + 1] == nums[i]: i += 1\n nums[s], nums[i] = nums[i], nums[s]\n __impl(nums, s + 1, e)\n nums[s], nums[i] = nums[i], nums[s]\n return res\n","sub_path":"leetcode-en/47.py","file_name":"47.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"210679489","text":"# -*- coding: utf-8 -*-\n\nimport logging\n\nfrom openerp.osv import osv, fields\nimport time\nimport hashlib\nimport sys\nimport json\nimport urllib2\nfrom openerp.tools.translate import _\nfrom openerp.addons.payment.models.payment_acquirer import ValidationError\nfrom openerp.osv import osv, fields\nfrom openerp.tools.float_utils import float_compare\nfrom openerp import SUPERUSER_ID\nimport datetime\n\n\nreload(sys)\nsys.setdefaultencoding('utf8')\n_logger = logging.getLogger(__name__)\n\n\nclass AcquireAlipay(osv.Model):\n\n _inherit = 'payment.acquirer'\n _description = 'alipay'\n _columns = {\n 'alipay_service': fields.char(u'接口名称', help=u'接口名称,create_direct_pay_by_user'),\n 'alipay_partner': fields.char(u'合作者身份ID', help=u'签约的支付宝账号对应的支付宝唯一用户号,以 2088 开头的 16 位纯数字组成'),\n 'alipay_input_charset': fields.char(u'参数编码字符集', help=u'商户网站使用的编码格式,如utf-8、gbk、gb2312 等'),\n 'alipay_sign_type': fields.char(u'签名方式', help=u'DSA、RSA、MD5 三个值可选,必须大写,这里请默认填写utf-8'),\n 'alipay_seller_email': fields.char(u'用户名', help=u'卖家支付宝帐户'),\n 'alipay_out_trade_no': fields.char(u'商品唯一订单号', help=u'商户网站订单系统中唯一订单号,必填'),\n 'alipay_key': fields.char(u'安全检验码', help=u'以数字和字母组成的32位字符'),\n\n 'alipay_subject': fields.char(u'商品名', help=u'商品的名称'),\n 'alipay_payment_type': fields.char(u'支付类型', size=128, help=u'商品的标题/交易标题/订单标题/订单关键字等。'),\n 'alipay_total_fee': fields.char(u'交易金额',\n help=u'该笔订单的资金总额,单位为RMB-Yuan。取值范围为[0.01,100000000.00],精确到小数点后两位。'),\n 'alipay_url': fields.char(u'alipay网址'),\n 'alipay_return_url': fields.char(u'alipay支付结果通知页面', help=u'本地地址'),\n 'alipay_refund_notify_url': fields.char(u'支付宝退款通知页面', help=u'本地地址处理退款'),\n }\n\n _defaults = {\n 'alipay_service': 'create_direct_pay_by_user',\n 'alipay_input_charset': 'utf-8',\n 'alipay_sign_type': 'MD5',\n 'alipay_payment_type': '1',\n 'alipay_url': 'https://mapi.alipay.com/gateway.do?',\n 'alipay_return_url': 'http://.../c/8/alipay/return',\n 'alipay_refund_notify_url': 'http://.../c/8/alipay/refund'\n\n\n }\n\n\n def _migrate_alipay_account(self, cr, uid, context=None):\n return True\n\n def _get_providers(self, cr, uid, context=None):\n providers = super(AcquireAlipay, self)._get_providers(cr, uid, context=context)\n providers.append(['alipay', 'Alipay'])\n return providers\n\n def _get_alipay_urls(self, cr, uid, environment, context=None):\n \"\"\" Alipay URLS \"\"\"\n return {\n 'alipay_url': 'https://mapi.alipay.com/gateway.do?', # alipay接收数据url\n }\n\n def alipay_get_form_action_url(self, cr, uid, id, context=None):\n acquirer = self.browse(cr, uid, id, context=context)\n return self._get_alipay_urls(cr, uid, acquirer.environment, context=context)['alipay_url']\n\n # def alipay_compute_fees(self, cr, uid, id, amount, currency_id, country_id, context=None):\n # return 1\n\n def test(self, cr, uid, id, context):\n '''\n 测试参数是否配置正确,这里会跳转到支付页面\n '''\n acquirer = self.browse(cr, uid, id, context=context)\n para = {}\n para['service'] = acquirer['alipay_service']\n para['partner'] = acquirer['alipay_partner']\n para['seller_email'] = acquirer['alipay_seller_email']\n para['_input_charset'] = acquirer['alipay_input_charset']\n para['payment_type'] = acquirer['alipay_payment_type']\n para['out_trade_no'] = time.time()\n para['total_fee'] = '0.1'\n para['subject'] = '测试商品'\n para['return_url'] = context['return_url']\n keylist = list(para.keys())\n keylist.sort()\n print(keylist)\n s = ''\n for i in range(len(keylist)):\n s += str(keylist[i]) + '=' + str(para[keylist[i]])\n if i != len(keylist) - 1:\n s += '&'\n sign = str(hashlib.md5(s + context['key']).hexdigest())\n s += '&sign=' + sign + '&sign_type=MD5'\n s = context['url'] + s\n print(s)\n return {\n 'type': 'ir.actions.act_url',\n 'url': s,\n 'nodestroy': True,\n 'target': 'new',\n }\n\n def alipay_form_generate_values(self, cr, uid, ids, partner_values, tx_values, context=None):\n '''\n 生成支付支付参数\n '''\n acquirer = self.browse(cr, uid, ids, context=context)\n tx_values['_input_charset'] = acquirer['alipay_input_charset']\n tx_values['out_trade_no'] = tx_values['reference'] + str(time.time())\n tx_values['partner'] = acquirer['alipay_partner']\n tx_values['payment_type'] = acquirer['alipay_payment_type']\n tx_values['seller_email'] = acquirer['alipay_seller_email']\n tx_values['total_fee'] = tx_values['amount']\n tx_values['subject'] = tx_values['reference']\n tx_values['sign_type'] = acquirer['alipay_sign_type']\n tx_values['service'] = acquirer['alipay_service']\n tx_values['return_url'] = acquirer['alipay_return_url']\n # 生成签名----------------\n para = {}\n para['service'] = acquirer['alipay_service']\n para['partner'] = acquirer['alipay_partner']\n para['seller_email'] = acquirer['alipay_seller_email']\n para['_input_charset'] = acquirer['alipay_input_charset']\n para['payment_type'] = acquirer['alipay_payment_type']\n para['out_trade_no'] = tx_values['out_trade_no']\n para['total_fee'] = tx_values['total_fee']\n para['subject'] = tx_values['subject']\n para['return_url'] = tx_values['return_url']\n\n keylist = list(para.keys())\n keylist.sort()\n s = ''\n for i in range(len(keylist)):\n s += str(keylist[i]) + '=' + str(para[keylist[i]])\n if i != len(keylist) - 1:\n s += '&'\n sign = str(hashlib.md5(s + acquirer['alipay_key']).hexdigest())\n # 生成签名+++++++++++++++++++\n tx_values['sign'] = sign\n tx_values['sortkeylist'] = keylist\n return partner_values, tx_values\n\n\nclass TxAliPay(osv.Model):\n _inherit = 'payment.transaction'\n\n _columns = {\n 'refunds': fields.text(u'Reason for refund'),\n 'date_order_refunds': fields.datetime(u'申请退款日期'),\n 'date_confirm': fields.datetime(u'退款日期', copy=False),\n 'user_id': fields.many2one('res.users', u'退款人'),\n 'alipay_txn_id': fields.char('alipay Transaction ID'),\n 'alipay_txn_type': fields.char('alipay Transaction type'),\n 'payment_state': fields.selection(\n [('normal', u'正常'), ('refunds', u'申请退款'), ('pay_done', u'已支付'), ('pay_processing', u'等待支付'),\n ('refund_processing', u'等待退款'), ('refund_done', u'退款完成')], u'支付状态'),\n }\n\n def alipay_refund(self, cr, uid, ids, context):\n '''\n 支付宝退款\n '''\n try:\n if context is None:\n context = {}\n refund = self.browse(cr, 1, ids, context)\n if refund['payment_state'] == 'refund_done':\n raise osv.except_osv(_('重复退款'), _('退款已完成,请审核!'))\n elif refund['payment_state'] == 'pay_processing':\n raise osv.except_osv(_('退款失败'), _('支付未完成,请审核!'))\n else:\n self.write(cr, 1, ids, {'payment_state': 'refund_processing', 'user_id': uid}, context)\n\n #支付宝退款参数\n value = {}\n refund = self.browse(cr, 1, ids, context=context)\n value['_input_charset'] = refund['acquirer_id']['alipay_input_charset']\n value['notify_url'] = refund['acquirer_id']['alipay_refund_notify_url']\n value['service'] = 'refund_fastpay_by_platform_pwd'\n value['partner'] = refund['acquirer_id']['alipay_partner']\n value['seller_email'] = refund['acquirer_id']['alipay_seller_email']\n value['seller_user_id'] = refund['acquirer_id']['alipay_partner']\n value['refund_date'] = time.strftime('%Y-%m-%d %H:%M:%S')#固定格式\n value['batch_num'] = 1#一次退款一个订单\n value['batch_no'] = time.strftime('%Y%m%d') + '00' + str(refund['id'])#按照固定格式\n trade_no = str(refund['alipay_txn_id'])\n amont_total = str(refund['amount'])\n value['detail_data'] = u'%s^%s^%s' % (trade_no, amont_total, refund['refunds'])\n\n #对参数进行MD5加密获得sign\n keylist = list(value.keys())\n keylist.sort()\n s = ''\n for i in range(len(keylist)):\n s += str(keylist[i]) + '=' + str(value[keylist[i]])\n if i != len(keylist) - 1:\n s += '&'\n sign = str(hashlib.md5(s + refund['acquirer_id']['alipay_key']).hexdigest())\n\n s += '&sign=' + sign + '&sign_type=MD5'\n #跳转至支付宝退款页面\n return {\n 'type': 'ir.actions.act_url',\n 'url': refund['acquirer_id']['alipay_url'] + s,\n 'nodestroy': True,\n 'target': 'new',\n }\n except Exception:\n raise osv.except_osv(_('警告'), _('退款失败,请稍候再试!'))\n\n def refund(self, cr, uid, ids, context):\n rd = self.browse(cr, 1, ids, context)\n acquirer = (rd['acquirer_id']['name']).lower() + '_refund'\n if hasattr(self, acquirer):\n tx = getattr(self, acquirer)(cr, uid, ids, context=context)\n else:\n tx = ''\n return tx\n\n\nclass payment_sale_order(osv.Model):\n _inherit = 'sale.order'\n\n _columns = {\n 'is_pay_success': fields.one2many('payment.transaction', 'sale_order_id', u'支付明细', readonly=True, copy=True),\n }\n\n","sub_path":"cm_payment_alipay/models/alipay.py","file_name":"alipay.py","file_ext":"py","file_size_in_byte":10346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"35568919","text":"import os\nimport random\nfrom PIL import Image, ImageDraw, ImageFont\nimport numpy as np\nimport cv2\n\nimage_path_train = \"data/image/train/\"\nif not os.path.exists(image_path_train):\n os.makedirs(image_path_train)\nimage_path_test = \"data/image/test/\"\nif not os.path.exists(image_path_test):\n os.makedirs(image_path_test)\nDEFAULT_FONTS = \"data/DroidSansMono.ttf\"\nWIDHT = 28\nHEIGHT = 28\n\n\ndef get_content_from_file(label_name):\n content = open(\"data/\" + label_name, \"r\")\n code_text = content.read()\n #return code_text.split(\"#\")\n return code_text.split(\",\")\n\ndef convert2gray(img):\n if len(img.shape) > 2:\n gray = np.mean(img, -1)\n return gray\n else:\n return img\n\n\ndef generate_image(i, c, dir_path):\n path = dir_path + str(i) + \".jpg\"\n print(path)\n #color = (0, 0, 0)\n color = (255,255,255)\n #background = (255, 255, 255)\n background = (0,0,0)\n print(str(i) + \"-->\" + c)\n image = create_image_one_char(c, color, background)\n image = convert2gray(np.array(image))\n cv2.imwrite(path, image)\n\n\ndef create_image_one_char(c, color, background):\n font = ImageFont.truetype(DEFAULT_FONTS, 30)\n im = Image.new('RGBA', (WIDHT, HEIGHT), background)\n drawAvatar = ImageDraw.Draw(im)\n w, h = im.size\n drawAvatar.text((4, -3), c, fill=color, font=font)\n del drawAvatar\n # rotate\n im = im.crop(im.getbbox())\n im = im.rotate(random.uniform(-30, 30), Image.BILINEAR, expand=1)\n\n # warp\n dx = w * random.uniform(0.1, 0.4)\n dy = h * random.uniform(0.2, 0.5)\n x1 = int(random.uniform(-dx, dx))\n y1 = int(random.uniform(-dy, dy))\n x2 = int(random.uniform(-dx, dx))\n y2 = int(random.uniform(-dy, dy))\n w2 = w + abs(x1) + abs(x2)\n h2 = h + abs(y1) + abs(y2)\n data = (\n x1, y1,\n -x1, h2 - y2,\n w2 + x2, h2 + y2,\n w2 - x2, -y1,\n )\n im = im.resize((w2, h2))\n im = im.transform((WIDHT, HEIGHT), Image.QUAD, data)\n image = Image.new('RGB', (WIDHT, HEIGHT), background)\n image.paste(im, (0, 0), im)\n return image\n\n\ntrain_label_name = \"code_train_text.txt\"\ntest_label_name = \"code_test_text.txt\"\n\n\ndef write_image(label_name, dir_path):\n code_list = get_content_from_file(label_name)\n for each in range(len(code_list)):\n generate_image(each, code_list[each], dir_path)\n\n\ndef main():\n write_image(train_label_name, image_path_train)\n write_image(test_label_name, image_path_test)\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"mnist/generate_images.py","file_name":"generate_images.py","file_ext":"py","file_size_in_byte":2483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"235055180","text":"'''\n单链表的实现,其思想就是递归实现\nNode:每个节点的实现,包val 和一个指向下一个节点的引用\n'''\n\n\nclass Node:\n '''节点类'''\n\n def __init__(self):\n self.val = None\n self.next = None\n\n\nclass List:\n '''链表的实现'''\n\n def __init__(self):\n self.__first = Node # 头节点\n self.__len = 0 # 链表长度\n\n def add(self, val):\n oldfirst = self.__first\n self.__first = Node()\n self.__first.val = val\n self.__first.next = oldfirst\n self.__len += 1\n\n def size(self):\n return self.__len\n\n def __next__(self):\n val = self.__first.val\n if self.__first.next:\n self.__first = self.__first.next\n return val\n\n def __iter__(self):\n return self\n\nif __name__ == \"__main__\":\n l = List()\n print(l.size())\n l.add(5)\n print(l.size())\n l.add(6)\n l.add(3)\n l.add(8)\n print(l.size())\n for x in l:\n print(x)\n","sub_path":"algorithm/adt/List.py","file_name":"List.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"638463142","text":"\"\"\" User Interface (UI) module \"\"\"\nfrom PyQt5 import QtWidgets, uic\nfrom PyQt5.QtWidgets import QTableWidgetItem, QLabel, QLineEdit, QPushButton\nimport common\n# Get Window\n\napp = QtWidgets.QApplication([])\nui = uic.loadUi(\"erp2.ui\") # loads the ui file we created\n\n# Draw Window\n\n\ndef start_ui():\n # Set Welcome page\n ui.stackedWidget.setCurrentIndex(0)\n # After menu selected go to details page\n ui.ERPMenu.triggered.connect(lambda: ui.stackedWidget.setCurrentIndex(2))\n # Add functions to buttons\n ui.saveChanges.clicked.connect(lambda: common.save_gui_table()) # Save changes made in table\n ui.deleteItem.clicked.connect(lambda: common.delete_gui_item())\n ui.addNew.clicked.connect(lambda: common.add_gui_item())\n\n # Start GUI\n ui.show()\n app.exec()\n\n\ndef change_page(module):\n ui.stackedWidget.setCurrentIndex(2)\n # show_form(header)\n # table = data_manager.get_table_from_file(filename)\n # gui.show_table(table, get_header())\n\n\ndef show_table(data, header=False):\n table = ui.storeTable\n table.setRowCount(len(data))\n table.setColumnCount(len(data[0]))\n if header is not False:\n table.setHorizontalHeaderLabels(header)\n for rowIndex, rowData in enumerate(data):\n for columnIndex, columnData in enumerate(rowData):\n table.setItem(rowIndex, columnIndex, QTableWidgetItem(columnData))\n # Do the resize of the columns by content\n table.resizeColumnsToContents()\n\n\ndef show_result(result, label):\n if type(result) is str or type(result) is int or type(result) is float:\n answer = ui.findChild(QLabel, \"answer\")\n answer.setText('Answer: ' + result)\n elif type(result) is list:\n if type(result[0]) is list:\n for idx, row in enumerate(result):\n result[idx] = list(map(lambda x: str(x), row))\n else:\n result = list(map(lambda x: str(x), result))\n show_table(result, label)\n else:\n resultList = []\n for key, item in result.items():\n resultList.append([key, str(item)])\n show_table(resultList, label)\n\n\ndef show_form(header):\n for idx, val in enumerate(header):\n fieldname = 'fieldName' + str(idx + 1)\n label = ui.findChild(QLabel, fieldname)\n if idx > 0:\n input_field = ui.findChild(QLineEdit, 'input' + str(idx + 1))\n input_field.setText('')\n label.setText(val)\n id_ = common.generate_random([])\n label = ui.findChild(QLabel, \"input1\")\n label.setText(id_)\n length = len(header)\n i = 7\n while i > len(header):\n fieldname = 'fieldName' + str(i)\n label = ui.findChild(QLabel, fieldname)\n label.hide()\n input_field = ui.findChild(QLineEdit, 'input' + str(i))\n input_field.hide()\n i -= 1\n\n\ndef show_io_zone():\n for i in range(3, 8):\n fieldname = 'fieldName' + str(i)\n label = ui.findChild(QLabel, fieldname)\n label.hide()\n fieldname = 'input' + str(i)\n input_field = ui.findChild(QLineEdit, fieldname)\n input_field.hide()\n for i in range(1, 3):\n fieldname = 'fieldName' + str(i)\n label = ui.findChild(QLabel, fieldname)\n if i == 1:\n label.setText(\"Output\")\n else:\n label.setText(\"Input\")\n label = ui.findChild(QLabel, \"input1\")\n label.setText(\"\")\n button = ui.findChild(QPushButton, \"addNew\")\n button.setText(\"Give the input\")\n","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"166728776","text":"import os.path\r\nimport glob\r\n\r\nprint(os.path.isfile(\"Genre/Acid_House/Adamski/Killer.txt\"))\r\n\r\nf = glob.glob('Genre/A*')\r\ngenre_list = list(map(lambda x:(x.split('/')[1]),f))\r\n\r\nfor genre in genre_list:\r\n\tartists = glob.glob('Genre/'+genre+'/*')\r\n\tfor artist in artists:\r\n\t\t#print(\"------\")\t\t\r\n\t\tfor dirpath, dirnames, files in os.walk(artist):\r\n\t\t\tif files:\r\n\t\t\t\tprint(dirpath, 'has files')\r\n\t\t\t#if not files:\r\n\t\t\t\t#print(dirpath, 'is empty')\r\n","sub_path":"Scraping/file_exist.py","file_name":"file_exist.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"216223856","text":"#!/usr/bin/env python\n\"\"\"\n# Author: palayutm\n# Created Time : Sat 09 Apr 2016 03:43:45 PM CST\n\n# File Name: c.py\n# Description:\n\n\"\"\"\nprint ('Case #1:')\nx = (1<<15) + 1\nn = 50\nwhile True:\n a = []\n flag = True\n for base in range (2, 11):\n if not flag:\n break\n num = int(bin(x)[2:], base=base)\n t = 2\n while True:\n if num % t == 0:\n a.append (t)\n break\n if t*t >= num:\n flag = False\n break\n t += 1\n if flag:\n st = bin(x)[2:]\n #xx = [int(st, i) for i in range (2, 11)]\n for i in a:\n st += ' ' + str(i)\n print (st)\n #print (xx)\n n -= 1\n if n == 0:\n break\n x += 2\n\n","sub_path":"codes/CodeJamCrawler/16_0_3/newSolar/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"395323933","text":"import tempfile\nfrom bibliopixel.project import project\nfrom bibliopixel.util import json\nfrom .. mark_tests import SKIP_LONG_TESTS\n\n\ndef make_project(data):\n if isinstance(data, dict):\n desc = data\n name = None\n\n elif not isinstance(data, str):\n raise ValueError('Cannot understand data %s' % data)\n\n else:\n if '{' in data:\n fp = tempfile.NamedTemporaryFile(mode='w')\n fp.write(data)\n fp.seek(0)\n name = fp.name\n else:\n name = data\n\n desc = json.load(name)\n\n return project.project(desc, root_file=name)\n\n\ndef make(data, run_start=not SKIP_LONG_TESTS):\n project = make_project(data)\n\n if run_start:\n project.animation.start()\n\n return project.animation\n","sub_path":"test/bibliopixel/project/make.py","file_name":"make.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"544524677","text":"from django.conf.urls import url\nfrom .views import index, profile, \\\n add_session_item, del_session_item, clear_session_item, \\\n cookie_login, cookie_auth_login, cookie_profile, cookie_clear\n\nurlpatterns = [\n url(r'^$', index, name='index'),\n url(r'^profile/$', profile, name='profile'),\n\n # custom auth moved to praktikum/urls.py for challenge\n\n #general function : solution to challenge\n url(r'^add_session_item/(?P\\w+)/(?P\\d+)/$', add_session_item, name='add_session_item'),\n url(r'^del_session_item/(?P\\w+)/(?P\\d+)/$', del_session_item, name='del_session_item'),\n url(r'^clear_session_item/(?P\\w+)/$', clear_session_item, name='clear_session_item'),\n\n # cookie\n url(r'^cookie/login/$', cookie_login, name='cookie_login'),\n url(r'^cookie/auth_login/$', cookie_auth_login, name='cookie_auth_login'),\n url(r'^cookie/profile/$', cookie_profile, name='cookie_profile'),\n url(r'^cookie/clear/$', cookie_clear, name='cookie_clear'), #sekaligus logout dari cookie\n]","sub_path":"lab_9/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"98545834","text":"import unittest\nfrom collections import Counter\n\n# Check Permutation\n\n\ndef permutation(string1, string2):\n if len(string1) != len(string2):\n return False\n\n c1 = Counter(string1)\n c2 = Counter(string2)\n\n for char in c1.keys():\n if c1[char] != c2[char]:\n return False\n\n return True\n\n\nclass Test(unittest.TestCase):\n data_T = [('abcd', 'bacd'), ('', ''), ('collect', 'letcolc')]\n data_F = [('a', 'b'), ('a', 'aa'), ('taxi', 'tax')]\n\n def test_permutation(self):\n # true check\n for test_string in self.data_T:\n actual = permutation(*test_string)\n self.assertTrue(actual)\n # false check\n for test_string in self.data_F:\n actual = permutation(*test_string)\n self.assertFalse(actual)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"ctci/01/0102.py","file_name":"0102.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"146165909","text":"\"\"\"Unit test cases for the :class:`p2per.DBSession` class.\n\n\"\"\"\nimport unittest\nimport os\nimport tempfile\n\nimport p2per\n\n\nclass TestDBSession(unittest.TestCase):\n\n def test_init(self):\n \"\"\"Initialise an p2per.DBSession object\n \"\"\"\n dbsession = p2per.DBSession()\n msg = 'Object is not a p2per.DBSession'\n self.assertIsInstance(dbsession, p2per.DBSession, msg)\n\n def test_connect(self):\n \"\"\"Connect to DB.\n \"\"\"\n # Given a shelve DB connection.\n shelve_dir = tempfile.mkdtemp()\n\n # when I attempt to connect to the DB.\n kwargs = {\n 'shelve': shelve_dir,\n }\n dbsession = p2per.DBSession(**kwargs)\n received = dbsession.connect()\n\n # then I should receive success status.\n msg = 'Shelve DB connection should return True'\n self.assertTrue(received, msg)\n\n # Clean up.\n del dbsession\n os.remove(os.path.join(shelve_dir, 'p2per.db'))\n os.removedirs(shelve_dir)\n","sub_path":"p2per/tests/test_dbsession.py","file_name":"test_dbsession.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"153403363","text":"\n'''\n1.1 Is Unique: Implement an algorithm to determine if a string has all unique characters. \n What if you cannot use additional data structures\n'''\n\n'''\nAsk the interviewer if the string is ASCII(128 characters) or unicode or extended ASCII(256 characters).\n'''\n\n\ndef is_unique(string):\n \"\"\"Using hast table to check if all characters have a count of one\"\"\"\n # if string is ASCII\n if len(st) > 128:\n return False\n dict_chars = {}\n for char in string:\n if char in dict_chars:\n return False\n else:\n dict_chars[char] = 1\n return True\n# Time Complexity: O(n); Space Complexity: O(1)\n\n# without using additional data structures\n\n\ndef is_unique_1(string):\n \"\"\"Sorting the string and checking if neighboring elements have repeated characters\"\"\"\n # if string is ASCII\n if len(string) > 128:\n return False\n string = ''.join(sorted(string))\n for i in range(len(string)-1):\n if string[i] == string[i+1]:\n return False\n return True\n# Time Complexity: O(nlogn);\n\n\nif __name__ == \"__main__\":\n st = input(\"enter a string:\")\n print(is_unique(st))\n","sub_path":"Arrays and Strings/1.1isUnique.py","file_name":"1.1isUnique.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"391612257","text":"from hub1d import hubbard1d\nimport matplotlib.pyplot as plt\ndef test():\n N=256\n U=4.25\n t=1.0\n Ntot=128\n Nups=range(0,Ntot+2,2)\n ms=[]\n es=[]\n for Nup in Nups:\n e=hubbard1d(N,t,U,Ntot,Nup)\n ms.append((1.0*(Nup-(Ntot-Nup))/Ntot))\n es.append(e)\n\n return ms,es\n\nif __name__ == '__main__':\n Nups,es=test()\n plt.plot(Nups,es)\n plt.show()\n","sub_path":"test/test1d.py","file_name":"test1d.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"521998527","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author: Gillett Hernandez\n# @Date: 2016-06-24 18:59:07\n# @Last Modified by: Gillett Hernandez\n# @Last Modified time: 2016-08-02 13:50:53\ndef square_digit_chain(n):\n #make more efficient using caching.\n if n==0:\n raise Exception(\"out of range n: n cannot be less than one.\")\n if n==89 or n==1:\n return n\n while n!=89 and n!=1:\n n=sum(int(c)**2 for c in str(n))\n return n\n\n\ndef problem_92():\n s=0\n\n for n in xrange(1,10000000):\n if square_digit_chain(n)==89:\n s+=1\n\n return s\n\nif __name__ == '__main__':\n res=problem_92()\n print(res)\n","sub_path":"Python/problem_92.py","file_name":"problem_92.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"131441788","text":"'''\nName: Kyaw Za Zaw\nCourse: COMP123-04\nProfessor: Lauren Milne\nExercise: In Class Activity 09\n'''\n\nimport turtle\nimport time\n\n# --------------------------------------------------------------------------\n# The main functions demonstrate how to use this code for three different fractals\n\n\ndef main():\n # first defines a few L-systems for fractals\n kochAxiom = \"F\"\n kochRules = [['F', 'F+F--F+F']]\n kochAngle = 60\n\n hilbertAxiom = \"L\"\n hilbertRules = [['L', '+RF-LFL-FR+'], ['R', '-LF+RFR+FL-']]\n hilbertAngle = 90\n\n islandLakeAxiom = \"F+F+F+F\"\n islandLakeRules = [['F', 'F+f-FF+F+FF+Ff+FF-f+FF-F-FF-Ff-FFF'], ['f', 'ffffff']]\n islandLakeAngle = 90\n\n # my L-system\n # Peano curve\n peanoAxiom = \"F\"\n peanoRules = [['F', 'F+F-F-F-F+F+F+F-F']]\n peanoAngle = 90\n\n win = turtle.Screen()\n fracTurtle = turtle.Turtle()\n fracTurtle.speed(0)\n\n\n # moveTurtle(fracTurtle, -400, -50)\n # generateFractal(fracTurtle, 0, kochAxiom, kochRules, kochAngle, 20)\n #\n # time.sleep(3.0)\n # win.reset()\n # fracTurtle.speed(0)\n\n # moveTurtle(fracTurtle, -300, -300)\n # generateFractal(fracTurtle, 5, hilbertAxiom, hilbertRules, hilbertAngle)\n #\n # time.sleep(3.0)\n # win.reset()\n # fracTurtle.speed(0)\n\n moveTurtle(fracTurtle, -250, -200)\n # generateFractal(fracTurtle, 3, islandLakeAxiom, islandLakeRules, islandLakeAngle)\n # step 2 of question - drawing hilbert\n # generateFractal(fracTurtle, 4, hilbertAxiom, hilbertRules, hilbertAngle)\n\n # step 3 of question - drawing peano curve\n generateFractal(fracTurtle, 2, peanoAxiom, peanoRules, peanoAngle)\n fracTurtle.hideturtle()\n win.exitonclick()\n\n\ndef moveTurtle(t, x, y):\n \"\"\"Given a turtle object, and x and y coordinates, moves the turtle to that location\n without leaving a line behind.\"\"\"\n t.up()\n t.goto(x, y)\n t.down()\n\n\n\ndef generateFractal(fTurt, recReps, axiom, rules, angle, dist=10):\n \"\"\"Given a turtle, the number of recursive repetitions to do, and a specification\n of an L-system: axiom, rules, and angle, it generates the string that directs the turtle\n to move, and then draws the fractal.\"\"\"\n\n # Build instructions with L-system\n instructions = createLSystem(recReps, axiom, rules)\n # print(instructs)\n\n # draw the picture\n drawLsystem(fTurt, instructions, angle, dist)\n\n\n\n# --------------------------------------------------------------------------\n# These functions take a string-based L-System and create a string by applying\n# the rewriting rules\n\n\ndef createLSystem(numIters, axiom, rules):\n \"\"\"Takes in the number of iterations of the rewriting process, the starting\n axiom, and a list of rules. Each rule is a sublist with the symbol on the lefthand side\n first, followed by a string for the righthand side. Returns the final string.\"\"\"\n currString = axiom\n nextString = axiom\n for i in range(numIters):\n nextString = processString(currString, rules)\n currString = nextString\n return nextString\n\n\n\ndef processString(oldStr, rules):\n \"\"\"Processes the current string by going through character by character and\n replacing each character by the application of a rule, if any. Returns the\n new string. This performs one step of the rewriting process.\"\"\"\n newstr = \"\"\n for ch in oldStr:\n newstr = newstr + applyRules(ch, rules)\n return newstr\n\n\n\ndef applyRules(ch, rules):\n \"\"\"Takes in a character and the list of rules, and finds the first rule that applies\n to the character and returns the righthand side. If no rules apply the character is\n returned unchanged.\"\"\"\n newstr = \"\"\n for rule in rules:\n lhs = rule[0]\n rhs = rule[1]\n if ch == lhs:\n return rhs\n return ch\n\n\n# --------------------------------------------------------------------------\n# These functions take a string giving instructions for an L-system, and a list\n# that decodes the characters in the string to tell what to do with them, and\n# it has a turtle trace the shape given by the instructions\n\ndef drawLsystem(aTurtle, instructions, angle, distance):\n \"\"\"Takes in a turtle, a string of instructions, plus the\n angle to turn when told to turn, and the distance forward to go.\n It loops over the instructions, and does the correct action for\n each. F means go forward distance while drawing, f means go forward\n distance without drawing, + means turn left by angle, - means turn right\n by angle, and | means turn 180 degrees.\"\"\"\n for cmd in instructions:\n if cmd == 'F':\n aTurtle.forward(distance)\n elif cmd == 'f':\n aTurtle.up()\n aTurtle.forward(distance)\n aTurtle.down()\n elif cmd == '-':\n aTurtle.right(angle)\n elif cmd == '+':\n aTurtle.left(angle)\n elif cmd == '|':\n aTurtle.left(180)\n else:\n # ignore any other characters in the instructions\n pass\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"activity09/LSystemsImproved.py","file_name":"LSystemsImproved.py","file_ext":"py","file_size_in_byte":5037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"410617299","text":"\"\"\"\nHere are your instructions:\n\n\nWrite a GUI-based program that provides two Entry fields, a button and a label. When the button is clicked, the value of each Entry should (if possible) be converted into a float. If both conversions succeed, the label should change to the sum of the two numbers. Otherwise it should read \"***ERROR***.\"\n\"\"\"\n\nfrom tkinter import *\nfrom is_float import isfloat\n\nclass Application(Frame):\n def __init__(self, master=None):\n Frame.__init__(self, master)\n self.pack()\n self.createWidgets()\n \n def createWidgets(self):\n top_frame = Frame(self)\n self.text_in1 = Entry(top_frame)\n self.text_in1.pack()\n self.text_in2 = Entry(top_frame)\n self.text_in2.pack()\n self.label = Label(top_frame, text = \"Output label\")\n self.label.pack()\n top_frame.pack()\n \n bottom_frame = Frame(self)\n self.convertb = Button(bottom_frame, text = \"convert\", command = self.convert)\n self.convertb.pack()\n bottom_frame.pack()\n \n def convert(self):\n text1 = self.text_in1.get()\n text2 = self.text_in2.get()\n \n if isfloat(text1) and isfloat(text2):\n output = float(text1) + float(text2)\n else:\n output = \"***ERROR***\"\n self.label.config(text = output)\n \nroot = Tk()\napp = Application(master=root)\napp.mainloop()","sub_path":"Python 2/Python2_6(Introduction to GUI)/IntroGUI.py","file_name":"IntroGUI.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"600412080","text":"from rest_framework.serializers import ModelSerializer\n\nfrom ads.models import Boost\n\nfrom case.serializers import CaseSerializer\n\nfrom profiles.serializers import ProfileSerializer\n\n\nclass BoostSerializer(ModelSerializer):\n\n profile = ProfileSerializer()\n case = CaseSerializer()\n\n class Meta:\n model = Boost\n fields = (\n 'profile',\n 'case',\n 'amount',\n 'per_day_allotment',\n 'start_date',\n 'end_date'\n )\n","sub_path":"ads/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"60101934","text":"#dictionary\ndict= {1: \"hello\", 2: \"World\",3: \"Apple\", 4: \"ball\"}\n\n#square dict\nsquare_dict = {num: num*num for num in range(1, 20)}\nprint(square_dict)\n\n# Creating a Dictionary \n# with Integer Keys\nDict = {1: 'Hey', 2: 'Hello', 3: 'Hi'}\nprint(\"\\nDictionary with the use of Integer Keys: \")\nprint(Dict)\n \n# Creating a Dictionary \n# with Mixed keys\nDict = {'Name': 'OK', 1: [1, 2, 3, 4]}\nprint(\"\\nDictionary with the use of Mixed Keys: \")\nprint(Dict)\n\n# Adding elements one at a time\nDict[0] = 'Hey'\nDict[2] = 'Hello'\nDict[3] = 1\nprint(\"\\nDictionary after adding 3 elements: \")\nprint(Dict)\n\n#\nD = {'spam': 2, 'ham': 1, 'eggs': 3}\nD['spam']\nlen (D)\n#D['ham'] = ['grill', 'bake', 'fry']\n(D.keys())\n#del D['eggs']\n#list(D.values())\n#list(D.items())\nD.pop('ham')\nD","sub_path":"dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"589899811","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport os\nimport pickle\nimport random\nimport glob \n\nimport enum\nimport numpy as np\nimport six\nimport tensorflow as tf\n\n\nNDIM = 640\n\nProblemInstance = collections.namedtuple(\n \"ProblemInstance\",\n [\"tr_input\", \"tr_output\", \"tr_info\", \"val_input\", \"val_output\", \"val_info\"])\n\n\nclass StrEnum(enum.Enum):\n \"\"\"An Enum represented by a string.\"\"\"\n\n def __str__(self):\n return self.value\n\n def __repr__(self):\n return self.__str__()\n\n\nclass EmbeddingCrop(StrEnum):\n \"\"\"Embedding types supported by the DataProvider class.\"\"\"\n CENTER = \"center\"\n MULTIVIEW = \"multiview\"\n\n\nclass MetaSplit(StrEnum):\n \"\"\"Meta-datasets split supported by the DataProvider class.\"\"\"\n TRAIN = \"train\"\n VALID = \"val\"\n TEST = \"test\"\n\n\nclass DataProvider(object):\n\n def __init__(self, dataset_split, config, verbose=False):\n\n self._dataset_split = MetaSplit(dataset_split)\n self._config = config\n self._verbose = verbose\n self._base_path = os.path.join(self._config['data_path'], self._config['dataset_name'])\n self._splitfilename = os.path.join(self._config['data_path'], 'reddit_splits/{}_{}.txt'.format(self._config['splitname'], self._dataset_split))\n self._class_dict = [c.strip().split(',') for c in open(self._splitfilename).readlines()]\n self._class_dict = {c[0]: c[1:] for c in self._class_dict}\n self.classes = list(self._class_dict.keys())\n self._ndim = self._config['ndim']\n self.multi_topic = self._config['multi_topic']\n\n\n def sample_emb(self, author_names, labels, nb_samples):\n\n samples = []\n\n for i, author_name in zip(labels, author_names):\n\n if self.multi_topic:\n topic = random.choice(self._class_dict[author_name])\n else:\n topic = self._class_dict[author_name][0]\n\n emb = np.load(os.path.join(self._base_path, topic, '{}.npy'.format(author_name)))\n idx = np.random.choice(emb.shape[0], nb_samples, replace = False)\n samples += [(i, e) for e in emb[idx]]\n\n if shuffle:\n random.shuffle(samples)\n\n return samples\n \n def get_instance(self, num_classes, tr_size, val_size):\n \"\"\"Samples a random N-way K-shot classification problem instance.\n\n Args:\n num_classes: N in N-way classification.\n tr_size: K in K-shot; number of training examples per class.\n val_size: number of validation examples per class.\n\n Returns:\n A tuple with 6 Tensors with the following shapes:\n - tr_input: (num_classes, tr_size, NDIM): training image embeddings.\n - tr_output: (num_classes, tr_size, 1): training image labels.\n - tr_info: (num_classes, tr_size): training image file names.\n - val_input: (num_classes, val_size, NDIM): validation image embeddings.\n - val_output: (num_classes, val_size, 1): validation image labels.\n - val_input: (num_classes, val_size): validation image file names.\n \"\"\"\n def _build_one_instance_py():\n \n paths = random.sample(self.classes, num_classes)\n idx = np.random.permutation(num_classes)\n labels = np.array(list(range(num_classes)))\n labels = labels[idx]\n emb_labels = self.sample_emb(paths, labels, tr_size + val_size)\n \n labels, emb = list(zip(*emb_labels))\n labels, emb= np.array(list(labels)), np.array(list(emb))\n labels = labels.reshape((num_classes, tr_size + val_size, 1))\n emb = emb.reshape((num_classes, tr_size + val_size, self._config['ndim']))\n\n return emb, labels, paths\n\n output_list = tf.py_func(_build_one_instance_py, [],\n [tf.float32, tf.int32, tf.string])\n\n instance_input, instance_output, instance_info = output_list\n instance_input = tf.nn.l2_normalize(instance_input, axis=-1)\n\n split_sizes = [tr_size, val_size]\n tr_input, val_input = tf.split(instance_input, split_sizes, axis=1)\n tr_output, val_output = tf.split(instance_output, split_sizes, axis=1)\n \n with tf.control_dependencies(\n self._check_labels(num_classes, tr_size, val_size,\n tr_output, val_output)):\n tr_output = tf.identity(tr_output)\n val_output = tf.identity(val_output)\n \n tr_info = instance_info\n val_info = instance_info\n\n\n return tr_input, tr_output, tr_info, val_input, val_output, val_info\n \n \n def _check_labels(self, num_classes, tr_size, val_size,\n tr_output, val_output):\n correct_label_sum = (num_classes*(num_classes-1))//2\n tr_label_sum = tf.reduce_sum(tr_output)/tr_size\n val_label_sum = tf.reduce_sum(val_output)/val_size\n all_label_asserts = [\n tf.assert_equal(tf.to_int32(tr_label_sum), correct_label_sum),\n tf.assert_equal(tf.to_int32(val_label_sum), correct_label_sum),\n ]\n return all_label_asserts\n\n\n def get_batch(self, batch_size, num_classes, tr_size, val_size,\n num_threads=10):\n \"\"\"Returns a batch of random N-way K-shot classification problem instances.\n\n Args:\n batch_size: number of problem instances in the batch.\n num_classes: N in N-way classification.\n tr_size: K in K-shot; number of training examples per class.\n val_size: number of validation examples per class.\n num_threads: number of threads used to sample problem instances in\n parallel.\n\n Returns:\n A ProblemInstance of Tensors with the following shapes:\n - tr_input: (batch_size, num_classes, tr_size, NDIM): training image\n embeddings.\n - tr_output: (batch_size, num_classes, tr_size, 1): training image\n labels.\n - tr_info: (batch_size, num_classes, tr_size): training image file\n names.\n - val_input: (batch_size, num_classes, val_size, NDIM): validation\n image embeddings.\n - val_output: (batch_size, num_classes, val_size, 1): validation\n image labels.\n - val_info: (batch_size, num_classes, val_size): validation image\n file names.\n \"\"\"\n if self._verbose:\n num_threads = 1\n one_instance = self.get_instance(num_classes, tr_size, val_size)\n\n tr_data_size = (num_classes, tr_size)\n val_data_size = (num_classes, val_size)\n task_batch = tf.train.shuffle_batch(one_instance, batch_size=batch_size,\n capacity=1000, min_after_dequeue=0,\n enqueue_many=False,\n shapes=[tr_data_size + (self._ndim,),\n tr_data_size + (1,),\n (num_classes,),\n val_data_size + (self._ndim,),\n val_data_size + (1,),\n (num_classes,)],\n num_threads=num_threads)\n\n\n\n return ProblemInstance(*task_batch)\n\n","sub_path":"data_text.py","file_name":"data_text.py","file_ext":"py","file_size_in_byte":6964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"387374085","text":"#!/usr/bin/env python\nimport logging\nimport selectors\nimport socket\nfrom functools import partial\nimport rx\nfrom rx import Observable\nfrom rx.concurrency import AsyncIOScheduler\nasyncio = rx.config['asyncio']\n\n\ndef main():\n \"\"\"Merge, don't cross the streams.\"\"\"\n\n logging.basicConfig(level=logging.DEBUG)\n\n # Parts taken from https://docs.python.org/3/library/selectors.html\n sel = selectors.DefaultSelector()\n loop = asyncio.get_event_loop()\n loop.run_until_complete(run(sel, loop))\n try:\n while True:\n events = sel.select()\n for key, mask in events:\n callback = key.data\n callback(key.fileobj, mask)\n except KeyboardInterrupt:\n pass\n loop.close()\n\n logging.info('closed event loop')\n\n\nasync def run(sel, loop):\n def create_socket_observable(port, observer):\n sock = socket.socket()\n sock.bind(('localhost', port))\n sock.listen(100)\n sock.setblocking(False)\n sel.register(\n sock,\n selectors.EVENT_READ,\n partial(accept, observer, sel)\n )\n\n socket_1234 = Observable.create(\n partial(create_socket_observable, 1234)\n )\n socket_1235 = Observable.create(\n partial(create_socket_observable, 1235)\n )\n\n source = socket_1234.merge(socket_1235).share()\n\n source.subscribe(\n logging.info\n )\n\n source.where(\n lambda msg: \"error\" in msg\n ).subscribe(\n logging.error\n )\n\n\ndef accept(observer, sel, sock, mask):\n conn, addr = sock.accept() # Should be ready\n observer.on_next('accepted {} from {}'.format(conn, addr))\n conn.setblocking(False)\n sel.register(conn, selectors.EVENT_READ, partial(read, observer, sel))\n\n\ndef read(observer, sel, conn, mask):\n data = conn.recv(1000) # Should be ready\n if data:\n observer.on_next('echoing {} to {}'.format(repr(data), conn))\n conn.send(data) # Hope it won't block\n else:\n observer.on_next('closing {}'.format(conn))\n sel.unregister(conn)\n conn.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"five.py","file_name":"five.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"413332741","text":"\"\"\"\nFrom a Photo to a 3D Model with Python and Blender Python API\nhttps://www.youtube.com/watch?v=Q41QxPK5xzM\nhttps://github.com/armindocachada/create-3d-model-using-python/tree/master \n 55:06\n \n \"\"\" \nimport bpy \nimport numpy as np\nfrom math import sin\n\n\nvertices= []\nedges = []\nfaces = [] \n\n(X,W) = (300 , 300)\nDX=1\nDY=1\n\nfor X in range(0,W,DX):\n vertices.append((X,sin(X),0))\n \n#Create a new mash\nnew_mesh=bpy.data.meshes.new(\"new_mesh\")\nnew_mesh.from_pydata(vertices,edges,faces)\nnew_mesh.update()\n# make objec from the mesh\nnew_object = bpy.data.objects.new(\"new_object\",new_mesh)\n\n# Add the new object to view layer\nview_layer=bpy.context.view_layer\nview_layer.active_layer_collection.collection.objects.link(new_object)\n\n\n\n\n\n\"\"\"\nvertices=[(1,1,0),(1,-1,0),(-1,1,0),(-1,-1,0), (1,1,1),(1,-1,1),(-1,1,1),(-1,-1,1)]\n# list of vertixs 0 to 7 (eight vertixs)\n \nedges=[(0,4)]# Each number is a number of a vertix\nfaces=[(3,1,0,2),(7,5,4,6),(3,1,5,7)]\n\n\n\"\"\"","sub_path":"blender/sinobject.py","file_name":"sinobject.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"477466018","text":"# -*- coding=utf-8 -*-\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom layers import GraphAttentionLayer, GraphConvolution\n\n\nclass NMA(nn.Module):\n def __init__(self, n_feat, n_hid, n_nums, dropout, alpha, n_heads, n_gcn):\n \"\"\"Dense version of GAT.\"\"\"\n super(NMA, self).__init__()\n self.L = 2*n_heads*n_hid\n self.D = n_feat\n self.K = 1\n self.n_nums = n_nums\n self.n_heads = n_heads\n self.dropout = dropout\n self.GCN = GraphConvolution(n_feat, n_feat, n_gcn)\n\n self.attentions = [GraphAttentionLayer(n_feat, n_hid, dropout=dropout, alpha=alpha, concat=True)\n for _ in range(n_heads)]\n for i, attention in enumerate(self.attentions):\n self.add_module('attention_{}'.format(i), attention)\n\n self.attention_degs = nn.Sequential(\n nn.Linear(self.n_nums, self.n_nums),\n nn.ReLU()\n )\n\n self.attention_distance = nn.Sequential(\n nn.Linear(self.n_nums, self.n_nums),\n nn.ReLU()\n )\n\n self.attention_interlayer = nn.Sequential(\n nn.Linear(self.L, self.D),\n nn.Tanh(),\n nn.Linear(self.D, self.K)\n )\n\n self.classifier = nn.Sequential(\n nn.Linear(self.L, self.L),\n nn.ReLU(),\n nn.Linear(self.L, 2),\n )\n\n def forward(self, x, adj, degs_weights, distance_weights):\n # x = F.dropout(x, self.dropout, training=self.training)\n x = self.GCN(x, adj)\n\n degs_weights = self.attention_degs(degs_weights)\n distance_weights = self.attention_distance(distance_weights)\n nodes_weights = torch.mul(degs_weights, distance_weights)\n nodes_weights = torch.transpose(nodes_weights, 3, 2)\n nodes_weights = nodes_weights.expand_as(x)\n x = torch.mul(x, nodes_weights)\n\n x = torch.cat([att(x, adj) for att in self.attentions], dim=3)\n x = x[:, :, 0:2, :]\n x = x.view(x.shape[0], x.shape[1], 1, -1).squeeze(2)\n x = F.dropout(x, self.dropout, training=self.training)\n A = self.attention_interlayer(x)\n A = torch.transpose(A, 2, 1)\n A = F.softmax(A, dim=2)\n x = torch.matmul(A, x)\n logits = self.classifier(x.squeeze(1))\n return logits\n\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"569104691","text":"import matplotlib.pyplot as plt\n\nchrom = []\nlength = []\n\ntimes_mult1 = []\ntimes_mult2 = []\ntimes_mult3 = []\n\ntimes_simp = []\ntimes_simp1 = []\ntimes_simp2 = []\ntimes_simp3 = []\n\ntimes_cpu2_1 = []\ntimes_cpu2_2 = []\ntimes_cpu2_3 = []\n\ntimes_cpu6_1 = []\ntimes_cpu6_2 = []\ntimes_cpu6_3 = []\n\n\nwith open(\"comparaison_spacer_k1-9.txt\",\"r\") as data:\n for line in data:\n values = line.split()\n chrom.append(int(values[0]))\n length.append(int(values[1]))\n times_mult1.append(90.34/float(values[2]))\n times_mult2.append(90.34/float(values[3]))\n times_mult3.append(248.96/float(values[4]))\n times_simp1.append(248.96/float(values[5]))\n '''\n \n times_simp2.append(int(values[6]))\n times_simp3.append(int(values[7]))\n times_cpu2_1.append(int(values[8]))\n times_cpu2_2.append(int(values[9]))\n times_cpu2_3.append(int(values[10]))\n times_cpu6_1.append(int(values[11]))\n times_cpu6_2.append(int(values[12]))\n times_cpu6_3.append(int(values[13]))\n\n\ndata = [times_mult1, times_mult2, times_mult3]\ntimes_mult = [round(sum(e)/len(e)) for e in zip(*data)]\n\ndata = [times_simp1, times_simp2, times_simp3]\ntimes_simp = [round(sum(e)/len(e)) for e in zip(*data)]\n\ndata = [times_cpu2_1, times_cpu2_2, times_cpu2_3]\ntimes_cpu2 = [round(sum(e)/len(e)) for e in zip(*data)]\n\ndata = [times_cpu6_1, times_cpu6_2, times_cpu6_3]\ntimes_cpu6 = [round(sum(e)/len(e)) for e in zip(*data)]\n'''\n \n\n#plt.plot(true_length, true_times_simp, label = '6CPUs - cut 5 Mb')\nplt.plot(chrom, times_mult1, label = 'Ch16 - v5 - sans spacer')\nplt.plot(chrom, times_mult2, label = 'Ch16 - v4 - avec spacer')\nplt.plot(chrom, times_mult3, label = 'Ch1 - v5 - sans spacer')\nplt.plot(chrom, times_simp1, label = 'Ch1 - v4 - avec spacer')\n\n#plt.plot(true_length, true_times_cpu6, label = '6CPUs - cut 100 Mb')\n\n\nplt.grid()\nplt.xlabel(\"k value\")\nplt.ylabel(\"Mb/sec\")\nplt.title(\"Execution time for Human Chromosome depending on k value\")\nplt.legend()\nplt.savefig(\"comparaison_human_k1-10.png\")\n","sub_path":"results/Spacer_vs_nospacer/data_analyses.py","file_name":"data_analyses.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"189452139","text":"import json\r\nimport os\r\nimport uuid\r\n\r\nfrom bottle import error, request, response, route, static_file, template, \\\r\n SimpleTemplate\r\n\r\nimport config\r\nimport constants\r\nimport headers_util\r\nimport log\r\nimport resources as res\r\nfrom models import fingerprint_manager\r\n\r\nlogger = log.get_logger(__name__)\r\nSimpleTemplate.defaults['url'] = lambda: str(request.url).split('/')[-1]\r\n\r\n\r\n@route('/')\r\ndef index():\r\n fp_manager = fingerprint_manager.FingerprintManager(config)\r\n return template('index', fp_count=fp_manager.get_count())\r\n\r\n\r\n@route('/fp')\r\ndef fp():\r\n set_cookie()\r\n headers = headers_util.http_headers(request.headers)\r\n return template('fp',\r\n referenced_scripts=res.referenced_scripts,\r\n registered_methods=res.registered_methods,\r\n headers='headers: {0}'.format(json.dumps(headers)))\r\n\r\n\r\n@route('/fpnojs')\r\ndef fpnojs():\r\n set_cookie()\r\n\r\n fingerprint = process_result(request)\r\n if not fingerprint:\r\n return ''\r\n\r\n return template('result_table', fp=fingerprint, no_js=True)\r\n\r\n\r\n@route('/fp', method='POST')\r\ndef post_fp():\r\n fingerprint = process_result(request)\r\n if not fingerprint:\r\n return ''\r\n\r\n return template('result_table', fp=fingerprint)\r\n\r\n\r\ndef process_result(request_obj):\r\n try:\r\n fp_manager = fingerprint_manager.FingerprintManager(config)\r\n return fp_manager.add_fingerprint(request_obj)\r\n except fingerprint_manager.FingerprintException:\r\n import pprint\r\n logger.error(pprint.pformat({\r\n 'Cookies': request.cookies.get(constants.FP_ID),\r\n 'JSON': request.json,\r\n 'HTTP Headers': dict(\r\n (k, v) for k, v in request.headers.environ.items() if\r\n 'HTTP' in k or 'X-' in k)\r\n }, indent=2)\r\n )\r\n\r\n return None\r\n\r\n\r\n@route('/about')\r\ndef about():\r\n return template('about')\r\n\r\n\r\n@route('/contact')\r\ndef about():\r\n return template('contact')\r\n\r\n\r\n@route('/privacy')\r\ndef privacy():\r\n return template('privacy')\r\n\r\n\r\n@route('/static//')\r\ndef static_files(subdir, filename):\r\n \"\"\" Serve static files in\r\n '/static/css/*', '/static/fonts/*' and '/static/js/*'.\r\n \"\"\"\r\n if subdir in ['css', 'fonts', 'img', 'js']:\r\n return static_file(filename, res.project_subdir('static/' + subdir))\r\n\r\n\r\n@route('///')\r\ndef fpmethod_static(fp_subdir, method, filename):\r\n \"\"\"Serve fingerprint methods' specific static files.\r\n \"\"\"\r\n if fp_subdir != config.FP_SUBDIR:\r\n pass\r\n\r\n # e.g. filename: 'js/navigator.js'\r\n parts = [fp_subdir, method] + list(os.path.split(filename))\r\n if '/'.join(parts) in res.referenced_scripts+res.referenced_static_files:\r\n return static_file(\r\n parts[-1],\r\n res.project_subdir(os.path.join(*parts[:-1])))\r\n\r\n\r\n@error(404)\r\ndef error404(e):\r\n \"\"\"Error handling.\r\n\r\n :return blank page\r\n \"\"\"\r\n return str(e)\r\n\r\n\r\ndef set_cookie():\r\n \"\"\"Set cookie for 90 days.\r\n \"\"\"\r\n if not request.cookies.get(constants.FP_ID):\r\n response.set_cookie(\r\n name=constants.FP_ID,\r\n value=uuid.uuid4().hex,\r\n max_age=constants.COOKIE_AGE\r\n )\r\n\r\n\r\n# reference to app.py -- DO NOT REMOVE!\r\nrefd = False\r\n","sub_path":"routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"491410910","text":"#!/usr/bin/env/ python\r\n# coding: utf-8\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt \r\n\r\nfrom .. import (powerSpectrumSmoothWrapper, \r\nsmoothWrapper, a_correlate, \r\nstandardBackgroundModel, \r\nLSSampler, ESSampler, echelle)\r\n\r\nfrom wotan import flatten\r\nimport peakutils\r\nfrom scipy.signal import detrend \r\n\r\n__all__ = ['solarlikeGlobalSeismo']\r\n\r\nclass solarlikeGlobalSeismo:\r\n '''\r\n Under development:\r\n # 1: p-mode asymptotic fitting\r\n # 2: light curve processing\r\n # 3: g-mode asymptotic fitting\r\n '''\r\n def __init__(self, freq, power, fnyq, starID='', filepath=''):\r\n idx = (freq>15.)\r\n self.freq, self.power = freq[idx], power[idx]\r\n self.fnyq = fnyq\r\n self.powerGlobalSmoothed = powerSpectrumSmoothWrapper(self.freq, self.power, windowSize=0.5)\r\n\r\n self.starID = starID if starID != '' else 'star'\r\n self.filepath = filepath if filepath != '' else './'\r\n return\r\n\r\n def run(self, verbose=True):\r\n if verbose: print('>>> Processing star {:s}.'.format(self.starID))\r\n\r\n if verbose: print('> Using 2d-acf to determine nu_max.')\r\n numax_diagnostics = self.get_numax()\r\n if verbose: print(' 2d-acf numax: {:0.3f}'.format(numax_diagnostics['cacf_numax']))\r\n\r\n if verbose: print(\"> Using acf to determine Delta_nu.\")\r\n dnu_diagnostics = self.get_dnu(numax_diagnostics['cacf_numax'])\r\n if verbose: print(' ACF dnu: {:0.3f}'.format(dnu_diagnostics['acf_dnu']))\r\n\r\n if verbose: print(\"> Fitting background to accurately determine nu_max.\")\r\n bg_diagnostics = self.get_background(numax_diagnostics['cacf_numax'], verbose=verbose)\r\n if verbose: print(' NHarvey: {:0.0f}'.format(bg_diagnostics['NHarvey']))\r\n if verbose: print(' Fitted numax: {:0.3f}'.format(bg_diagnostics['paramsMax'][2]))\r\n\r\n # save\r\n if verbose: print('> Plotting.')\r\n self.to_plot(numax_diagnostics, dnu_diagnostics, bg_diagnostics, 1)\r\n\r\n if verbose: print('> Saving.')\r\n self.to_data(cacf_numax=numax_diagnostics, acf_dnu=dnu_diagnostics,\r\n psfit_bg=bg_diagnostics)\r\n return\r\n\r\n # def run2(self, numax_diagnostics, dnu_diagnostics, bg_diagnostics, verbose=True):\r\n # if verbose: print('>>> Processing star {:s}.'.format(self.starID))\r\n\r\n # if verbose: print('> Fitting p-mode asymptotics.')\r\n # pmode_diagnostics = self.get_pmode_asymp(numax_diagnostics['cacf_numax'])\r\n\r\n # if verbose: print('> Plotting.')\r\n # self.to_plot(numax_diagnostics, dnu_diagnostics, bg_diagnostics, pmode_diagnostics)\r\n\r\n # # if verbose: print('> Saving.')\r\n # # self.to_data(cacf_numax=numax_diagnostics, acf_dnu=dnu_diagnostics,\r\n # # psfit_bg=bg_diagnostics, pmode_asymp=pmode_diagnostics)\r\n # return\r\n\r\n def get_numax(self):\r\n # use 2d ACF to get a rough estimation on numax\r\n freqRanges = np.logspace(min(np.log10(15.),np.log10(np.min(self.freq))), \r\n np.log10(np.max(self.freq)), \r\n 250)\r\n # freqRanges = np.linspace(15., np.max(freq), 200.)\r\n freqCenters = (freqRanges[1:]+freqRanges[:-1])/2.\r\n spacings = np.diff(freqRanges)\r\n widths = 0.263*freqCenters**0.772 * 4.\r\n\r\n # # crude background estimation\r\n \r\n cacf = np.zeros(len(spacings))\r\n acf2d = np.zeros([140,len(spacings)])\r\n for isp, width in enumerate(widths):\r\n idx = (self.freq >= freqRanges[isp]) & (self.freq <= freqRanges[isp]+width)\r\n \r\n if np.sum(idx)>100:\r\n # powerbg = percentile_filter(self.power[idx], 15, size=int(width/np.median(np.diff(self.freq[idx]))))\r\n # powerbg = np.percentile(self.power[idx], 20)\r\n lag, rho = a_correlate(self.freq[idx], self.power[idx]) # return the acf at this freqRange\r\n acf = np.interp(np.arange(30,170)/200*np.max(lag), lag, rho) # switch to the scale of width\r\n acf2d[:, isp] = np.abs(detrend(acf)) # store the 2D acf\r\n cacf[isp] = np.sum(np.abs(detrend(acf))) # store the max acf power (collapsed acf)\r\n else:\r\n acf2d[:, isp] = 0.\r\n cacf[isp] = np.nan\r\n\r\n # detrend the data to find the peak\r\n idx = np.isfinite(cacf)\r\n cacfDetrend = np.zeros(len(cacf))\r\n cacfDetrend[idx] = flatten(np.arange(np.sum(idx)), cacf[idx], \r\n method='biweight', window_length=50, edge_cutoff=10)\r\n\r\n # The highest value of the cacf (smoothed) corresponds to numax\r\n cacf_numax = freqCenters[np.nanargmax(cacfDetrend)]\r\n\r\n # create and return the object containing the result\r\n self.numax_diagnostics = {'cacf':cacf, 'acf2d':acf2d, 'freqCenters':freqCenters,\r\n 'spacings':spacings, 'widths':widths, 'freqRanges':freqRanges,\r\n 'cacfDetrend': cacfDetrend,\r\n 'cacf_numax':cacf_numax}\r\n return self.numax_diagnostics\r\n\r\n\r\n def _guessBackgroundParams(self, freq, powerSmoothed, numax):\r\n zeta = 2*2**0.5/np.pi\r\n flatNoiseLevel = np.median(powerSmoothed[int(len(self.freq)*0.9):]) \r\n heightOsc = powerSmoothed[np.argmin(np.abs(freq-numax))] \r\n widthOsc = 3.0 * (0.263*numax**0.772) \r\n\r\n freqHarvey_solar = np.array([2440.5672465, 735.4653975, 24.298031575000003])\r\n numax_solar = 3050\r\n \r\n freqHarvey = numax/numax_solar*freqHarvey_solar\r\n powerHarvey = np.ones(3)*4.\r\n ampHarvey = np.zeros(3)\r\n for iHarvey in range(3):\r\n ampHarvey[iHarvey] = (powerSmoothed[np.argmin(np.abs(freq-freqHarvey[iHarvey]))]*2/zeta*freqHarvey[iHarvey])**0.5\r\n\r\n paramsInit = [flatNoiseLevel, heightOsc, numax, widthOsc,\r\n ampHarvey[0], freqHarvey[0], powerHarvey[0],\r\n ampHarvey[1], freqHarvey[1], powerHarvey[1],\r\n ampHarvey[2], freqHarvey[2], powerHarvey[2]]\r\n paramsBounds = [[flatNoiseLevel*0.1, flatNoiseLevel*1.1], \r\n [heightOsc*0.2, heightOsc*5.0],\r\n [numax*0.8, numax*1.2],\r\n [widthOsc*0.5, widthOsc*4.0],\r\n [ampHarvey[0]*0.3, ampHarvey[0]*3.0],\r\n [freqHarvey[0]*0.2, freqHarvey[0]*5.0],\r\n [2.0, 8.0],\r\n [ampHarvey[1]*0.3, ampHarvey[1]*3.0],\r\n [freqHarvey[1]*0.2, freqHarvey[1]*5.0],\r\n [2.0, 8.0],\r\n [ampHarvey[2]*0.3, ampHarvey[2]*3.0],\r\n [freqHarvey[2]*0.2, freqHarvey[2]*5.0],\r\n [2.0, 8.0]]\r\n paramsNames = [\"flatNoiseLevel\", \"heightOsc\", \"numax\", \"widthOsc\", \r\n 'ampHarvey1', 'freqHarvey1', 'powerHarvey1',\r\n 'ampHarvey2', 'freqHarvey2', 'powerHarvey2',\r\n 'ampHarvey3', 'freqHarvey3', 'powerHarvey3']\r\n return paramsInit, paramsBounds, paramsNames\r\n\r\n\r\n def get_background(self, numax, verbose=True):\r\n # use background fit to get a precise estimation on numax\r\n # guess params\r\n paramsInit, paramsBounds, paramsNames = self._guessBackgroundParams(self.freq, self.powerGlobalSmoothed, numax)\r\n\r\n fitterOutput, fitterResidual = [[0,0,0] for i in range(2)]\r\n for NHarvey in range(1,4):\r\n def chi2(params):\r\n residual = np.sum((self.power-standardBackgroundModel(self.freq, \r\n params[:4+NHarvey*3], self.fnyq, NHarvey=NHarvey))**2.)\r\n return residual\r\n fitter = LSSampler(chi2, paramsInit[:4+NHarvey*3], paramsBounds[:4+NHarvey*3],\r\n paramsNames=paramsNames[:4+NHarvey*3])\r\n fitterOutput[NHarvey-1] = fitter.run(wrapper='minimize')\r\n fitterResidual[NHarvey-1] = chi2(fitterOutput[NHarvey-1]['paramsMax'])\r\n if verbose: print(' No. of Harvey = {:0.0f}, chi2: {:0.5f}'.format(NHarvey, fitterResidual[NHarvey-1]))\r\n fitterDiagnostic = fitterOutput[np.nanargmin(fitterResidual)]\r\n\r\n NHarvey = int((len(fitterDiagnostic['paramsMax'])-4)/3)\r\n powerBackground = standardBackgroundModel(self.freq, fitterDiagnostic['paramsMax'], \r\n self.fnyq, NHarvey=NHarvey, ifReturnOscillation=False)\r\n powerFit = standardBackgroundModel(self.freq, fitterDiagnostic['paramsMax'], \r\n self.fnyq, NHarvey=NHarvey, ifReturnOscillation=True)\r\n powerSNR = self.power/powerBackground\r\n self.bg_diagnostics = {**fitterDiagnostic, \r\n 'NHarvey':NHarvey, \r\n 'powerBackground':powerBackground, \r\n 'powerFit':powerFit, 'powerSNR':powerSNR}\r\n return self.bg_diagnostics\r\n\r\n\r\n def get_dnu(self, numax):\r\n # Determine dnu by acf\r\n dnu_guess = 0.263*numax**0.772\r\n idx = (self.freq>(numax-7*dnu_guess)) & (self.freq<(numax+7*dnu_guess))\r\n freq, power = self.freq[idx], self.power[idx]\r\n\r\n powers = smoothWrapper(freq, power, 0.1*dnu_guess, \"bartlett\")\r\n\r\n lag, acf = a_correlate(freq, powers) # acf\r\n acfs = smoothWrapper(lag, acf, 0.1*dnu_guess, \"bartlett\") # smooth acf\r\n\r\n # Use peak-finding algorithm to extract dnu in ACF\r\n idx = (lag>0.66*dnu_guess) & (lag<1.33*dnu_guess)\r\n index = peakutils.peak.indexes(acfs[idx], min_dist=int(dnu_guess/np.median(np.diff(freq))))\r\n\r\n if len(index) != 0:\r\n peaks_lags, peaks_amps = lag[idx][index], acfs[idx][index]\r\n acf_dnu = peaks_lags[np.nanargmax(peaks_amps)]\r\n acf_dnu_amp = peaks_amps[np.nanargmax(peaks_amps)]\r\n else:\r\n acf_dnu, acf_dnu_amp = np.nan, np.nan\r\n\r\n # create and return the object containing the result\r\n self.dnu_diagnostics = {'lag':lag, 'acf':acf, 'acfs':acfs,\r\n 'acf_dnu':acf_dnu,'acf_dnu_amp':acf_dnu_amp,\r\n 'dnu_guess':dnu_guess}\r\n\r\n return self.dnu_diagnostics\r\n\r\n\r\n def get_pmode_asymp(self, numax):\r\n \r\n dnu_guess = 0.263*numax**0.772\r\n idx = (self.freq>=numax-8*dnu_guess)&(self.freq<=numax+8*dnu_guess)\r\n x, y = self.freq[idx], self.power[idx]\r\n fs = np.median(np.diff(x))\r\n numax_j = np.nanargmin(np.abs(x-numax))\r\n\r\n def normal(theta, mu, sigma):\r\n return np.log(1.0/(np.sqrt(2*np.pi)*sigma))-0.5*(theta-mu)**2/sigma**2\r\n\r\n def model(theta):\r\n delta_nu, dnu_01, dnu_02, A0, A1, A2, fwhm0, fwhm1, fwhm2, C, offset = theta\r\n Nbin = np.int(delta_nu/fs)\r\n yFoldObs = (y[numax_j-3*Nbin:numax_j-2*Nbin] + y[numax_j-2*Nbin:numax_j-Nbin] + \r\n y[numax_j-Nbin:numax_j] + y[numax_j:numax_j+Nbin] +\r\n y[numax_j+Nbin:numax_j+Nbin*2] + y[numax_j+Nbin*2:numax_j+Nbin*3])\r\n yFoldObs /= np.max(yFoldObs)\r\n nu0 = offset*delta_nu \r\n nu1 = nu0 - 0.5*delta_nu + dnu_01 \r\n nu2 = nu0 - dnu_02\r\n tx = np.linspace(0,1,Nbin)*delta_nu-delta_nu/2.\r\n y0 = A0/(1+(tx)**2./(fwhm0**2./4.))\r\n y0 = y0[np.argsort((tx+nu0)%delta_nu)]\r\n y1 = A1/(1+(tx)**2./(fwhm1**2./4.))\r\n y1 = y1[np.argsort((tx+nu1)%delta_nu)]\r\n y2 = A2/(1+(tx)**2./(fwhm2**2./4.))\r\n y2 = y2[np.argsort((tx+nu2)%delta_nu)]\r\n yFoldMod = y0+y1+y2+C \r\n return yFoldObs, yFoldMod\r\n\r\n def posterior(theta):\r\n delta_nu, dnu_01, dnu_02, A0, A1, A2, fwhm0, fwhm1, fwhm2, C, offset = theta\r\n\r\n # priors for unkown model parameters\r\n boo = (0.7*dnu_guess0) & (A1>0) & (A2>0)\r\n if boo:\r\n lnprior = 0.\r\n else:\r\n return -np.inf\r\n lnprior += normal(delta_nu, dnu_guess, 0.15*dnu_guess)\r\n lnprior += normal(dnu_01, -0.025*dnu_guess, 0.1*dnu_guess)\r\n lnprior += normal(dnu_02, 0.121*dnu_guess+0.047, 0.1*dnu_guess)\r\n lnprior += normal(A0, 1.0, 0.3)\r\n lnprior += normal(A1, 1.0, 0.3)\r\n lnprior += normal(A2, 0.8, 0.15)\r\n\r\n # expected value of outcome\r\n yFoldObs, yFoldMod = model(theta)\r\n\r\n # likelihood (sampling distribution) of observations\r\n lnlike = -np.sum(yFoldObs/yFoldMod+np.log(yFoldMod))*6.\r\n return lnprior + lnlike\r\n\r\n paramsInit = [dnu_guess, -0.025*dnu_guess, 0.121*dnu_guess+0.047,\r\n 1.0, 1.0, 0.8, 0.25*dnu_guess, 0.25*dnu_guess, 0.25*dnu_guess, \r\n 0.05, 0.5]\r\n sampler = ESSampler(paramsInit, posterior, Nsteps=1000, Nburn=3000)\r\n diagnostics = sampler.run(verbose=True)\r\n yFoldObs, yFoldMod = model(diagnostics['paramsMax'])\r\n epsp = (numax/diagnostics['paramsMax'][0]+diagnostics['paramsMax'][-1]) % 1.\r\n\r\n self.pmode_diagnostics = {**diagnostics, 'model':model, \r\n 'yFoldObs':yFoldObs, 'yFoldMod':yFoldMod, 'epsp':epsp}\r\n return self.pmode_diagnostics\r\n\r\n\r\n def to_plot(self, numax_diagnostics, dnu_diagnostics, bg_diagnostics, pmode_diagnostics):\r\n _, axes = plt.subplots(figsize=(16,16), nrows=3, ncols=3, squeeze=False)\r\n\r\n # plot A, original flux\r\n # axes[0,0]\r\n\r\n # plot B, corrected flux\r\n # axes[1,0]\r\n\r\n # plot C, smoothed power spectra\r\n axes[2,0].plot(self.freq, self.power, color='gray')\r\n axes[2,0].plot(self.freq, self.powerGlobalSmoothed, color='red')\r\n axes[2,0].set_xlabel('$\\\\nu$ ($\\\\mu$Hz)')\r\n axes[2,0].set_ylabel('Power')\r\n axes[2,0].set_xlim(np.min(self.freq), np.max(self.freq))\r\n axes[2,0].set_xscale('log')\r\n axes[2,0].set_yscale('log')\r\n\r\n # plot D, 2d-acf\r\n axes[0,1].contourf(numax_diagnostics['freqCenters'], \r\n np.arange(0,numax_diagnostics['acf2d'].shape[0]), \r\n numax_diagnostics['acf2d'], cmap='gray_r')\r\n axes[0,1].set_xlabel('$\\\\nu$ ($\\\\mu$Hz)')\r\n axes[0,1].set_ylabel('Normalized lag')\r\n axes[0,1].set_xscale('log')\r\n\r\n # plot E, cacf\r\n # axes[1,1].plot(numax_diagnostics['freqCenters'], numax_diagnostics['cacf'], 'b-')\r\n axes[1,1].plot(numax_diagnostics['freqCenters'], numax_diagnostics['cacf'], color='C0')\r\n axes[1,1].plot(numax_diagnostics['freqCenters'], numax_diagnostics['cacfDetrend'], color='gray')\r\n axes[1,1].axvline(numax_diagnostics['cacf_numax'], color='r',linestyle='--')\r\n axes[1,1].set_xlabel('$\\\\nu$ ($\\\\mu$Hz)')\r\n axes[1,1].set_ylabel('Collapsed 2d-ACF')\r\n axes[1,1].set_xscale('log')\r\n axes[1,1].text(0.95,0.95,'2d-acf numax: {:0.3f}'.format(numax_diagnostics['cacf_numax']), \r\n transform=axes[1,1].transAxes, va='top', ha='right')\r\n\r\n\r\n # plot F, fitted power spectra\r\n powerBackground = standardBackgroundModel(self.freq, bg_diagnostics['paramsMax'], \r\n self.fnyq, NHarvey=bg_diagnostics['NHarvey'], ifReturnOscillation=False)\r\n powerFit = standardBackgroundModel(self.freq, bg_diagnostics['paramsMax'], \r\n self.fnyq, NHarvey=bg_diagnostics['NHarvey'], ifReturnOscillation=True)\r\n axes[2,1].plot(self.freq, self.power, color='gray')\r\n axes[2,1].plot(self.freq, self.powerGlobalSmoothed, color='black')\r\n axes[2,1].plot(self.freq, powerBackground, color='green')\r\n axes[2,1].plot(self.freq, powerFit, color='green', linestyle='--')\r\n axes[2,1].axhline(bg_diagnostics['paramsMax'][0], color='black', linestyle='--')\r\n axes[2,1].axvline(bg_diagnostics['paramsMax'][2], color='red', linestyle='--')\r\n axes[2,1].set_xlabel('$\\\\nu$ ($\\\\mu$Hz)')\r\n axes[2,1].set_ylabel('Power')\r\n axes[2,1].set_xlim(np.min(self.freq), np.max(self.freq))\r\n axes[2,1].set_xscale('log')\r\n axes[2,1].set_yscale('log')\r\n axes[2,1].text(0.05,0.05,'NHarvey: {:0.0f}'.format(bg_diagnostics['NHarvey']),\r\n transform=axes[2,1].transAxes, va='bottom', ha='left')\r\n axes[2,1].text(0.05,0.10,'Fitted numax: {:0.3f}'.format(bg_diagnostics['paramsMax'][2]),\r\n transform=axes[2,1].transAxes, va='bottom', ha='left')\r\n\r\n # plot G, acf\r\n axes[0,2].plot(dnu_diagnostics['lag'], dnu_diagnostics['acf'])\r\n axes[0,2].axvline(dnu_diagnostics['dnu_guess']*0.66, color='gray',linestyle='--')\r\n axes[0,2].axvline(dnu_diagnostics['dnu_guess']*1.33, color='gray',linestyle='--')\r\n axes[0,2].plot([dnu_diagnostics['acf_dnu']], [dnu_diagnostics['acf_dnu_amp']], 'rx')\r\n axes[0,2].set_xlabel('$\\\\nu$ ($\\\\mu$Hz)')\r\n axes[0,2].set_ylabel('ACF')\r\n axes[0,2].text(0.95,0.95,'ACF dnu: {:0.3f}'.format(dnu_diagnostics['acf_dnu']), \r\n transform=axes[0,2].transAxes, va='top', ha='right')\r\n\r\n # # plot H, asymptotic p fitting\r\n # x = np.linspace(0,1,len(pmode_diagnostics['yFoldObs']))*pmode_diagnostics['paramsMax'][0]\r\n # axes[1,2].plot(x, pmode_diagnostics['yFoldObs'], color='C0')\r\n # axes[1,2].plot(x, pmode_diagnostics['yFoldMod'], color='black')\r\n # axes[1,2].axvline(pmode_diagnostics['paramsMax'][0]*pmode_diagnostics['paramsMax'][-1], color='red', linestyle='--')\r\n # axes[1,2].text(0.95,0.95,'aysmp dnu: {:0.3f}'.format(pmode_diagnostics['paramsMax'][0]), \r\n # transform=axes[1,2].transAxes, va='top', ha='right')\r\n # axes[1,2].text(0.95,0.90,'aysmp eps: {:0.3f}'.format(pmode_diagnostics['epsp']), \r\n # transform=axes[1,2].transAxes, va='top', ha='right')\r\n\r\n\r\n # plot I, echelle\r\n # axes[2,2]\r\n numax = numax_diagnostics['cacf_numax']\r\n dnu = 0.263*numax**0.772\r\n powerSmoothed = smoothWrapper(self.freq, self.power, dnu*0.03, 'flat')\r\n echx, echy, echz = echelle(self.freq, powerSmoothed, \r\n dnu, numax-dnu*8, numax+dnu*8, echelletype=\"replicated\")\r\n levels = np.linspace(np.min(echz), np.max(echz), 500)\r\n axes[2,2].contourf(echx, echy, echz, cmap=\"jet\", levels=levels)\r\n axes[2,2].axis([np.min(echx), np.max(echx), np.min(echy), np.max(echy)])\r\n axes[2,2].set_xlabel(\"$\\\\nu$ mod {:0.2f} ($\\\\mu$Hz)\".format(dnu))\r\n axes[2,2].set_ylabel('$\\\\nu$ ($\\\\mu$Hz)')\r\n # axes[2,2].axvline(dnu, color='black', linestyle='--')\r\n # axes[2,2].axhline(bg_diagnostics['paramsMax'][2], color='black', linestyle='--')\r\n\r\n # save\r\n plt.savefig(self.filepath+self.starID+'.png')\r\n plt.close() \r\n return\r\n\r\n def to_data(self, **kwargs):\r\n data = kwargs\r\n np.save(self.filepath+self.starID+'', data)\r\n return","sub_path":"solarlike/seisGlobe.py","file_name":"seisGlobe.py","file_ext":"py","file_size_in_byte":19211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"290017702","text":"import tensorflow as tf\nimport tensorflow.keras as ks\n\nimport importlib\nimport collections\nfrom typing import *\n\nimport yolo.modeling.building_blocks as nn_blocks\nfrom yolo.modeling.backbones.get_config import build_block_specs\nfrom . import configs\n\n\n@ks.utils.register_keras_serializable(package='yolo')\nclass Backbone_Builder(ks.Model):\n def __init__(self,\n name,\n input_shape=(None, None, None, 3),\n config=None,\n weight_decay = 5e-4, \n **kwargs):\n self._layer_dict = {\n \"DarkRes\": nn_blocks.DarkResidual,\n \"DarkUpsampleRoute\": nn_blocks.DarkUpsampleRoute,\n \"DarkBlock\": None\n }\n\n self._input_shape = input_shape\n self._model_name = \"custom_csp_backbone\"\n layer_specs = config\n\n if not isinstance(config, Dict):\n self._model_name = name\n layer_specs = self.get_model_config(name)\n\n self._weight_decay = weight_decay\n inputs = ks.layers.Input(shape=self._input_shape[1:])\n output = self._build_struct(layer_specs, inputs)\n super().__init__(inputs=inputs, outputs=output, name=self._model_name)\n return\n\n @staticmethod\n def get_model_config(name):\n if name == \"darknet53\":\n name = \"darknet_53\"\n\n try:\n backbone = importlib.import_module(\n '.' + name, package=configs.__package__).backbone\n except ModuleNotFoundError as e:\n if e.name == configs.__package__ + '.' + name:\n raise ValueError(f\"Invlid backbone '{name}'\") from e\n else:\n raise\n\n return build_block_specs(backbone)\n\n def _build_struct(self, net, inputs):\n endpoints = collections.OrderedDict() #dict()\n x = inputs\n for i, config in enumerate(net):\n x = self._build_block(config, x, f\"{config.name}_{i}\")\n if config.output:\n endpoints[config.output_name] = x\n\n return endpoints\n\n def _build_block(self, config, inputs, name):\n x = inputs\n i = 0\n while i < config.repititions:\n if config.name == \"DarkConv\":\n x = nn_blocks.DarkConv(filters=config.filters,\n kernel_size=config.kernel_size,\n strides=config.strides,\n padding=config.padding,\n l2_regularization=self._weight_decay,\n name=f\"{name}_{i}\")(x)\n elif config.name == \"darkyolotiny\":\n x = nn_blocks.DarkTiny(filters=config.filters,\n strides=config.strides,\n name=f\"{name}_{i}\")(x)\n elif config.name == \"MaxPool\":\n x = ks.layers.MaxPool2D(pool_size=config.kernel_size,\n strides=config.strides,\n padding=config.padding,\n name=f\"{name}_{i}\")(x)\n else:\n layer = self._layer_dict[config.name]\n x = layer(filters=config.filters,\n downsample=config.downsample,\n l2_regularization=self._weight_decay,\n name=f\"{name}_{i}\")(x)\n i += 1\n return x\n","sub_path":"yolo/modeling/backbones/backbone_builder.py","file_name":"backbone_builder.py","file_ext":"py","file_size_in_byte":3477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"287429117","text":"# !/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author:pylarva\n# bolg:www.lichengbing.com\n\n# 条件满足会放行一个\n\nimport threading\n\n\ndef condition():\n\n r = input('>>>')\n\n if r == 'true':\n ret = True\n else:\n ret = False\n return ret\n\n\ndef func(i, con):\n print(i)\n con.acquire()\n con.wait_for(condition)\n print(i+100)\n con.release()\n\nc = threading.Condition()\n\nfor i in range(10):\n t = threading.Thread(target=func, args=(i, c, ))\n t.start()\n","sub_path":"day11/s7.py","file_name":"s7.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"493605611","text":"import numpy as np\nimport random\n\n\nDimentions_rows = int(input('how many rows/matrix do you want: '))\nDimentions_columns = int(input('how many columns/matrix do you want: '))\nrandom_scale = int(input('how large the random numbers: '))\nnumbers_matrix = int(input('how many matrix do you want: '))\n\n\nclass MakeRandomList:\n def __init__(self):\n self.Dimentions_rows = Dimentions_rows\n self.Dimentions_columns = Dimentions_columns\n self.random_scale = random_scale\n\n def creating(self, Dimentions_rows, Dimentions_columns, random_scale):\n Origin_List = []\n for i in range(1, Dimentions_rows + 1):\n Origin_List.append([random.randint(0, random_scale)\n for i in range(1, Dimentions_columns + 1)])\n return Origin_List\n # 这个地方用了表达式,因为一开始使用的嵌套的 for 循环让我迷失了。\n\n # for i in range(1, 5):\n # a.append(random.randint(0, 10))\n # b.append(a)\n # 其实不用两层循环,一层就可以了。因为 append 函数返回的还是一个列表,包含了原来的列表。\n\n\n# print(Origin_List)\ncreat_list = MakeRandomList()\n\nfor s in range(numbers_matrix):\n i = creat_list.creating(Dimentions_rows, Dimentions_columns, random_scale)\n print('No.', s+1, 'Matrix is:\\n', np.array(i))\n print('*******')\n print(np.array(i))\n","sub_path":".history/生成随机n维数组_20200320203146.py","file_name":"生成随机n维数组_20200320203146.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"429514755","text":"# Feedback system for the tour guide program:\n# Northwestern Univeristy Office of Undergraduate Admissions\n# Segal Visitor's Center\n# 1841 Hinman Ave, Evanston, IL, 60201\n# Author: Andrew Bowen\n# License: MIT License\n\n'''\nScript to test out nltk python package\nWant to incorporate sentiment analysis\ntutorial here:\nhttps://www.digitalocean.com/community/tutorials/how-to-perform-sentiment-analysis-in-python-3-using-the-natural-language-toolkit-nltk\nRewriting this code as a class\n'''\n\nimport re\nimport string\nimport random\nimport pandas as pd\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom nltk.corpus import twitter_samples\nfrom nltk.corpus import stopwords\nfrom nltk.tag import pos_tag\nfrom nltk.tokenize import word_tokenize\nfrom nltk import FreqDist\nfrom nltk import classify\nfrom nltk import NaiveBayesClassifier\n\nclass commentAnalyzer(object):\n '''\n Object to incorporate NLP into tour comment analysis\n Want to only call classifier once for training\n Then use the model for guide comments\n Currently using .JSON files\n Will want to rewrite guide comments to this format\n '''\n\n def __init__(self, guideName):\n self.guideName = guideName\n # self.comment = comment\n self.model = None\n\n def remove_noise(self, tweet_tokens, stop_words=()):\n '''\n Method to remove noise\n Removes words/characters that don\\'t contribute to overall meaning'\n '''\n self.cleaned_tokens = []\n\n for token, tag in pos_tag(tweet_tokens):\n token = re.sub('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+#]|[!*\\(\\),]|'\n '(?:%[0-9a-fA-F][0-9a-fA-F]))+', '', token)\n token = re.sub(\"(@[A-Za-z0-9_]+)\", \"\", token)\n\n if tag.startswith(\"NN\"):\n pos = 'n'\n elif tag.startswith('VB'):\n pos = 'v'\n else:\n pos = 'a'\n\n lemmatizer = WordNetLemmatizer()\n token = lemmatizer.lemmatize(token, pos)\n\n if (len(token) > 0) and (token not in string.punctuation) and (token.lower() not in stop_words):\n self.cleaned_tokens.append(token.lower())\n return self.cleaned_tokens\n\n def get_all_words(self, cleaned_tokens_list):\n '''\n Method that gets words from cleaned tokens\n '''\n\n self.cleaned_tokens_list = cleaned_tokens_list\n for tokens in self.cleaned_tokens_list:\n for token in tokens:\n yield token\n\n def get_tweets_for_model(self, cleaned_tokens_list):\n '''Method to pull cleaned (noise removed tweets to apply to Model'''\n for tweet_tokens in cleaned_tokens_list:\n yield dict([token, True] for token in tweet_tokens)\n\n def trainClassifier(self):\n '''\n Method to train model on classifying positive and negative comment\n Would like to use actualy comments for the training data\n Need to convert those to a .JSON file structure\n '''\n print('Training model...')\n # Positive and negative tweet lists\n positive_tweets = twitter_samples.strings('positive_tweets.json')\n negative_tweets = twitter_samples.strings('negative_tweets.json')\n text = twitter_samples.strings('tweets.20150430-223406.json')\n tweet_tokens = twitter_samples.tokenized('positive_tweets.json')\n\n stop_words = stopwords.words('english')\n\n positive_tweet_tokens = twitter_samples.tokenized('positive_tweets.json')\n negative_tweet_tokens = twitter_samples.tokenized('negative_tweets.json')\n\n self.positive_cleaned_tokens_list = []\n self.negative_cleaned_tokens_list = []\n\n # Creating positive and negative tokens for tweets with noise removed\n for tokens in positive_tweet_tokens:\n self.positive_cleaned_tokens_list.append(self.remove_noise(tokens, stop_words))\n\n for tokens in negative_tweet_tokens:\n self.negative_cleaned_tokens_list.append(self.remove_noise(tokens, stop_words))\n\n # part of speech words\n self.all_pos_words = self.get_all_words(self.positive_cleaned_tokens_list)\n\n freq_dist_pos = FreqDist(self.all_pos_words)\n # print(freq_dist_pos.most_common(10))\n\n positive_tokens_for_model = self.get_tweets_for_model(self.positive_cleaned_tokens_list)\n negative_tokens_for_model = self.get_tweets_for_model(self.negative_cleaned_tokens_list)\n\n # Establishing positive and negative datasets from tokens\n positive_dataset = [(tweet_dict, \"Positive\")\n for tweet_dict in positive_tokens_for_model]\n\n negative_dataset = [(tweet_dict, \"Negative\")\n for tweet_dict in negative_tokens_for_model]\n\n # Creating randomized dataset\n self.dataset = positive_dataset + negative_dataset\n random.shuffle(self.dataset)\n\n # Establishing training and testing datasets\n train_data = self.dataset[:7000]\n test_data = self.dataset[7000:]\n # print(train_data[0:10], type(test_data))\n\n self.classifier = NaiveBayesClassifier.train(train_data)\n\n accuracy = classify.accuracy(self.classifier, test_data)\n print(\"Accuracy is:\", accuracy * 100, '%')\n\n print(self.classifier.show_most_informative_features(10))\n\n return self.classifier\n\n # def establishModel(self):\n # print('Training model to identify constructive feedback...')\n # # Calling trained model once - returns nltk Bayes classifier object\n # self.model = self.trainClassifier()\n # # return self.model\n\n\n def classifyComment(self, comment, classifier):\n '''\n Method to use trained classifier above\n Will apply to comments pulled from guide data\n '''\n\n self.comment = comment\n custom_comment_tokens = self.remove_noise(word_tokenize(self.comment)) # Tour sample comment\n\n # Might not want to train for every comment\n self.model = self.trainClassifier()\n\n print('Creating comment classification...')\n self.classification = self.model.classify(dict([token, True]\n for token in custom_comment_tokens))\n\n # Returngin either positive of negative classification\n return self.classification\n\n def displayComments(self, guideName):\n\n # Reading in visitor feedback files (responses for every guide/tour)\n allpath = '/Users/andrewbowen/tgCoordinator/data/allFiles/'\n self.feedback = pd.read_csv(allpath + 'Feedback_Form_Beta.csv', sep=',', header=0)\n\n # Renaming the columns for easier readability\n self.feedback.columns = ['Timestamp', 'Visitor Name', 'Visitor Email',\n 'Visitor Type', 'Visit Date', 'Guide Name',\n 'Exp Score', 'Route Score', 'Guide Score', 'Comments']\n\n self.names = self.feedback['Guide Name']\n\n numComments = 3 # # of comments to display\n # Pulling guide name data\n self.guideData = self.feedback.loc[self.names == self.guideName]\n good_comments = []\n\n # ca = commentAnalyzer(guideName)\n\n for comment in self.guideData['Comments']:\n comment_type = self.classifyComment(comment, self.model)\n print(comment, '--Result--> ', comment_type)\n\n # Grouping together positive comments\n if comment_type == 'Positive':\n good_comments.append(comment)\n\n print('')\n print('####################################')\n print('')\n\n # Displaying a few good comments\n if numComments > len(self.guideData['Comments']):\n numComments = len(self.guideData['Comments'])\n print('There are fewer comments than you requested.')\n print('Guide Feedback: ', good_comments[0: numComments])\n\n\n# ## TODO: testing and integration of this object into our django app\n\n# Test calling object above\n#ca = commentAnalyzer('Andrew Bowen')\n#ca.displayComments('Andrew Bowen')\n","sub_path":"testing/comments/commentAnalyzer.py","file_name":"commentAnalyzer.py","file_ext":"py","file_size_in_byte":8067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"531199595","text":"# coding: utf-8\n\nimport chainer\nimport chainer.functions as F\n\n\nclass ROIPool2D(chainer.Chain):\n def __init__(self, fn, outsize, spatial_scale):\n super(ROIPool2D, self).__init__()\n self.fn = fn\n self.outsize = outsize\n self.spatial_scale = spatial_scale\n\n def forward(self, x, rois, roi_indices):\n return self.fn(x, rois, roi_indices, 7, 1.2)\n\n\nclass ROIAlign2D(chainer.Chain):\n def __init__(self, fn, outsize, spatial_scale, sampling_ratio):\n super(ROIAlign2D, self).__init__()\n self.fn = fn\n self.outsize = outsize\n self.spatial_scale = spatial_scale\n self.sampling_ratio = sampling_ratio\n\n def forward(self, x, rois, roi_indices):\n return self.fn(x, rois, roi_indices, 7, 1.2, 2)\n\n\n# ======================================\n\nimport ch2o\n\nif __name__ == '__main__':\n import numpy as np\n\n x = np.arange(2 * 3 * 5 * 5).reshape((2, 3, 5, 5)).astype(np.float32)\n rois = np.array([[0, 1, 3, 4], [1, 0.3, 4, 2.6]]).astype(np.float32)\n roi_indices = np.array([0, 1]).astype(np.int32)\n\n ch2o.generate_testcase(ROIPool2D(F.roi_max_pooling_2d, 7, 1.2),\n [x, rois, roi_indices],\n subname='max_pool')\n ch2o.generate_testcase(ROIPool2D(F.roi_average_pooling_2d, 7, 1.2),\n [x, rois, roi_indices],\n subname='avg_pool')\n ch2o.generate_testcase(ROIAlign2D(F.roi_max_align_2d, 7, 1.2, 2),\n [x, rois, roi_indices],\n subname='max_align')\n ch2o.generate_testcase(ROIAlign2D(F.roi_average_align_2d, 7, 1.2, 3),\n [x, rois, roi_indices],\n subname='avg_align')\n","sub_path":"ch2o/tests/node/Roi.py","file_name":"Roi.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"566602395","text":"import html\nimport json\nimport requests\nfrom django.apps import apps\nfrom django.contrib.gis.geos import GEOSGeometry, MultiPolygon, Polygon\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\nfrom councils.models import Council\n\n\nclass Command(BaseCommand):\n \"\"\"\n Turn off auto system check for all apps\n We will maunally run system checks only for the\n 'councils' and 'pollingstations' apps\n \"\"\"\n requires_system_checks = False\n\n\n def add_arguments(self, parser):\n parser.add_argument(\n '-t',\n '--teardown',\n default=False,\n action='store_true',\n required=False,\n help=\"Clear Councils table before importing\"\n )\n\n def feature_to_multipolygon(self, feature):\n geometry = GEOSGeometry(json.dumps(feature['geometry']), srid=4326)\n if isinstance(geometry, Polygon):\n return MultiPolygon(geometry)\n return geometry\n\n def get_json(self, url):\n r = requests.get(url)\n r.raise_for_status()\n return r.json()\n\n def get_councils(self, url, id_field, name_field):\n # call url and return a list of Council objects\n # with the code and boundary fields populated\n # (ready to atttach contact details to)\n councils = []\n feature_collection = self.get_json(url)\n for feature in feature_collection['features']:\n council_id = feature['properties'][id_field]\n self.stdout.write(\"Found boundary for %s: %s\" % (council_id, feature['properties'][name_field]))\n poly = self.feature_to_multipolygon(feature)\n councils.append(Council(council_id=council_id, area=poly))\n return councils\n\n def _save_council(self, council):\n # write council object to ALL databases\n for db in settings.DATABASES.keys():\n council.save(using=db)\n\n def clean_url(self, url):\n if not url.startswith(('http://', 'https://')):\n # Assume http everywhere will redirect to https if it is there.\n url = \"http://{}\".format(url)\n return url\n\n def get_contact_info_from_yvm(self, council_id):\n url = \"{}{}\".format(settings.YVM_LA_URL, council_id)\n\n req = requests.get(url)\n content = req.text\n\n council_data = json.loads(str(content))['registrationOffice']\n info = {}\n info['name'] = html.unescape(council_data.get('office'))\n info['website'] = self.clean_url(council_data.get('website'))\n info['email'] = council_data.get('email')\n info['phone'] = council_data.get('telephone', '').replace('', '')\\\n .split('>')[-1]\n\n address_fields = [council_data.get(f, '') for f in [\n 'address1',\n 'address2',\n 'address3',\n 'city',\n 'address4',\n\n ]]\n info['address'] = \"\\n\".join([f for f in address_fields if f])\n info['postcode'] = \" \".join(\n council_data.get('postalcode', '').split(' ')[-2:])\n\n return info\n\n def handle(self, **options):\n \"\"\"\n Manually run system checks for the\n 'councils' and 'pollingstations' apps\n Management commands can ignore checks that only apply to\n the apps supporting the website part of the project\n \"\"\"\n self.check([\n apps.get_app_config('councils'),\n apps.get_app_config('pollingstations')\n ])\n\n if options['teardown']:\n self.stdout.write('Clearing councils table..')\n Council.objects.all().delete()\n\n councils = []\n self.stdout.write(\"Downloading GB boundaries from ONS...\")\n councils = councils + self.get_councils(\n settings.GB_BOUNDARIES_URL, id_field='lad16cd', name_field='lad16nm')\n self.stdout.write(\"Downloading NI boundaries from ONS...\")\n councils = councils + self.get_councils(\n settings.NI_BOUNDARIES_URL, id_field='LGDCode', name_field='LGDNAME')\n\n for council in councils:\n self.stdout.write(\"Getting contact info for %s from YourVoteMatters\" %\\\n (council.council_id))\n info = self.get_contact_info_from_yvm(council.council_id)\n council.name = info['name']\n council.website = info['website']\n council.email = info['email']\n council.phone = info['phone']\n council.address = info['address']\n council.postcode = info['postcode']\n self._save_council(council)\n\n self.stdout.write('..done')\n","sub_path":"polling_stations/apps/councils/management/commands/import_councils.py","file_name":"import_councils.py","file_ext":"py","file_size_in_byte":4596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"519581655","text":"from __future__ import unicode_literals, absolute_import\n\nfrom django.db import models\nfrom django.utils.translation import gettext as _\nfrom django.utils.translation import gettext_lazy\n\nfrom filer.fields.image import FilerImageField\nfrom cms.models.pluginmodel import CMSPlugin\nfrom cms.models import Page\nfrom cms.models.fields import PageField\nfrom ckeditor.fields import RichTextField\n#from cmsplugin_filer_image import ThumbnailOption\n\nfrom . import fields\nfrom djangocms_attributes_field.fields import AttributesField\n\nclass Classes(models.TextField):\n default_field_class = fields.Classes\n\n def __init__(self, *args, **kwargs):\n if 'verbose_name' not in kwargs:\n kwargs['verbose_name'] = 'Classes'\n if 'blank' not in kwargs:\n kwargs['blank'] = True\n if 'default' not in kwargs:\n kwargs['default'] = ''\n if 'help_text' not in kwargs:\n kwargs['help_text'] = 'Space separated classes that are added to ' + \\\n \t'the class. See Bootstrap 3 documentation.'\n super(Classes, self).__init__(*args, **kwargs)\n\n def formfield(self, **kwargs):\n defaults = {\n 'form_class': self.default_field_class,\n }\n defaults.update(kwargs)\n return super(Classes, self).formfield(**defaults)\n\nSIZE_CHOICES = (\n ('100% auto', 'fit width: 100% auto'),\n ('auto 100%', 'fit height: auto 100%'),\n ('cover', 'fill: cover '),\n ('auto', 'default: auto'),\n)\n\nREPEAT_CHOICES = (\n ('no-repeat', 'no-repeat'),\n ('repeat', 'repeat'),\n ('repeat-x', 'repeat-x'),\n ('repeat-y', 'repeat-y'),\n)\n\nATTACHMENT_CHOICES = (\n ('scroll', 'scroll'),\n ('fixed', 'fixed'),\n)\n\n# Should pull these from django settings.py\nCONTAINER_CHOICES = (\n ('', 'No container (full-width)'),\n ('container', '.container (smaller content width based on device size)'),\n ('container-fluid', '.container-fluid (full-width with slight padding on sides)'),\n)\n\nclass Section(CMSPlugin):\n name = models.CharField('Section Name', max_length=25, default='', help_text='Descriptive name [not rendered on page]', blank=True, null=True)\n min_height = models.CharField('Minimum Section Height', max_length=25, default='0px', help_text='0 is default. Set it larger to expand height of section.')\n bg_image = FilerImageField(\n verbose_name=_('Background Image'),\n blank=True,\n null=True,\n on_delete=models.SET_NULL,\n related_name='+',\n )\n bg_external_image = models.URLField(\n verbose_name=_('External URL Background Image'),\n blank=True,\n max_length=255,\n help_text=_('If provided, overrides the embedded image.')\n )\n bg_color = models.CharField('CSS Background Color', max_length=25, default='transparent', help_text='(e.g., #RRGGBB, rgba(120,120,120,0.3))')\n bg_size = models.CharField('Background Size', max_length=25, choices=SIZE_CHOICES, default='cover')\n bg_position = models.CharField('Background Position', max_length=25, default='center', blank=True)\n bg_repeat = models.CharField('Background Repeat', max_length=25, choices=REPEAT_CHOICES, default='no-repeat', blank=True)\n bg_attachment = models.CharField('Background Attachment', max_length=25, choices=ATTACHMENT_CHOICES, default='scroll', blank=True)\n container = models.CharField(\n verbose_name='Add nested .container or .container-fluid child element',\n max_length=25,\n choices=CONTAINER_CHOICES,\n blank=True,\n default='container',\n help_text=_('Adds a \".container\" or \".container-fluid\" element inside the section. '\n 'Use it to have a full-page-width styled
with an inner container with '\n 'a constrained width. All child plugins render inside the container.'),\n )\n\n classes = Classes()\n\n attributes = AttributesField(\n verbose_name='Attributes',\n blank=True,\n excluded_keys=['class'],\n )\n\n def __str__(self):\n return self.name + ' ' + self.container\n\n @property\n def bg_image_url(self):\n if self.bg_image:\n return self.bg_image.url\n else:\n return self.bg_external_image\n\n def clean(self):\n # you shall only set one image kind\n if self.bg_image and self.bg_external_image:\n raise ValidationError(\n _('You need to add either an image or a URL '\n 'linking to an external image, not both.')\n )\n","sub_path":"djangocms_layouttools/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"532390951","text":"grocery_item = {} \ngrocery_history = [] \n\nstop = False \n\nwhile not stop:\n item_name = input(\"Item name:\\n\") \n quantity = input(\"Quantity purchased:\\n\") \n cost = input(\"Price per item:\\n\")\n grocery_item = {'name':item_name, 'number': int(quantity), 'price': float(cost)}\n grocery_history.append(grocery_item)\n user_input = input(\"Enter another item?\\nType 'c' for continue or 'q' to quit:\\n\")\n if user_input == 'q':\n stop = True\n\ngrand_total = 0 \n\nfor index, item in enumerate(grocery_history):\n item_total = item['number'] * item['price']\n grand_total = grand_total + item_total\n print('%d %s @ $%.2f ea $%.2f' % (item['number'], item['name'], item['price'], item_total))\n item_total = 0\n\nprint('Grand total: $%.2f' % grand_total)\n","sub_path":"Day 3/Learn How to Reduce Food Waste.py","file_name":"Learn How to Reduce Food Waste.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"253286659","text":"import redis\nimport json\nimport random\nimport time\nimport string\nfrom datetime import datetime\nfrom statistics import mean\n\nfrom conf import redis_host, redis_port, redis_password\ntimes = []\n\nemit_lua=\"\"\"if redis.call('exists', KEYS[1]) == 0 then if ARGV[1] == '1' then redis.call('set', KEYS[1], 'basic') end if ARGV[1] == '3' then redis.call('set', KEYS[1], 'none') end if ARGV[1] == '2' then redis.call('set', KEYS[1], 'better') end return redis.call('get', KEYS[2]) end return -1\"\"\"\n\n\n\nif __name__ == '__main__':\n \n try:\n r = redis.StrictRedis(host=redis_host, port=redis_port, password=redis_password, decode_responses=True)\n p_bas = r.pubsub()\n p_bas.psubscribe('basic')\n p_bet = r.pubsub()\n p_bet.psubscribe('better')\n\n emit = r.register_script(emit_lua)\n\n max = 0.0\n\n for message in p_bas.listen():\n if message[\"type\"] == 'psubscribe':\n continue\n \n decision = random.uniform(0.0, 1.0)\n id = message[\"data\"]\n\n if id == '-1':\n break\n\n if decision < 0.4:\n if decision > 0.1:\n for mes in p_bet.listen():\n if mes[\"data\"] == id and mes[\"type\"] == 'pmessage':\n break\n\n if r.exists(id+'_END'):\n continue\n\n if decision > 0.1:\n r.set(id+'_END', 'better')\n else:\n r.set(id + '_END', 'basic')\n else :\n if r.exists(id+'_END'):\n continue\n r.set(id + '_END', 'none')\n\n start = float(r.get(id +'_T'))\n end = time.time() * 1000.0\n delta = end - start\n times.append(delta)\n if delta > max:\n max = delta\n except Exception as e:\n print(e)\n\n print(\"emiter finito\")\n if len(times) > 0:\n print(\"max-->\",max)\n print(\"mean-->\", mean(times))\n ","sub_path":"redis_slow/emiter.py","file_name":"emiter.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"18132591","text":"\n# In[]:\n# Controls for webapp\nimport numpy as np\n\n## since fitbounds='location not working\n# from https://stackoverflow.com/questions/63787612/plotly-automatic-zooming-for-mapbox-maps\n## NOT WORKING ! zoom and center defined in if clause\n\ndef zoom_center(lons: tuple=None, lats: tuple=None, lonlats: tuple=None,\n format: str='lonlat', projection: str='mercator',\n width_to_height: float=2.0) -> (float, dict):\n \"\"\"Finds optimal zoom and centering for a plotly mapbox.\n Must be passed (lons & lats) or lonlats.\n Temporary solution awaiting official implementation, see:\n https://github.com/plotly/plotly.js/issues/3434\n \n Parameters\n --------\n lons: tuple, optional, longitude component of each location\n lats: tuple, optional, latitude component of each location\n lonlats: tuple, optional, gps locations\n format: str, specifying the order of longitud and latitude dimensions,\n expected values: 'lonlat' or 'latlon', only used if passed lonlats\n projection: str, only accepting 'mercator' at the moment,\n raises `NotImplementedError` if other is passed\n width_to_height: float, expected ratio of final graph's with to height,\n used to select the constrained axis.\n \n Returns\n --------\n zoom: float, from 1 to 20\n center: dict, gps position with 'lon' and 'lat' keys\n\n >>> print(zoom_center((-109.031387, -103.385460),\n ... (25.587101, 31.784620)))\n (5.75, {'lon': -106.208423, 'lat': 28.685861})\n \"\"\"\n if lons is None and lats is None:\n if isinstance(lonlats, tuple):\n lons, lats = zip(*lonlats)\n else:\n raise ValueError(\n 'Must pass lons & lats or lonlats'\n )\n \n maxlon, minlon = max(lons), min(lons)\n maxlat, minlat = max(lats), min(lats)\n center = {\n 'lon': round((maxlon + minlon) / 2, 6),\n 'lat': round((maxlat + minlat) / 2, 6)\n }\n \n # longitudinal range by zoom level (20 to 1)\n # in degrees, if centered at equator\n lon_zoom_range = np.array([\n 0.0007, 0.0014, 0.003, 0.006, 0.012, 0.024, 0.048, 0.096,\n 0.192, 0.3712, 0.768, 1.536, 3.072, 6.144, 11.8784, 23.7568,\n 47.5136, 98.304, 190.0544, 360.0\n ])\n \n if projection == 'mercator':\n margin = 1.2\n height = (maxlat - minlat) * margin * width_to_height\n width = (maxlon - minlon) * margin\n lon_zoom = np.interp(width , lon_zoom_range, range(20, 0, -1))\n lat_zoom = np.interp(height, lon_zoom_range, range(20, 0, -1))\n zoom = round(min(lon_zoom, lat_zoom), 2)\n else:\n raise NotImplementedError(\n f'{projection} projection is not implemented'\n )\n \n return zoom, center\n \nREGENCIES = dict(\n JEM = 'Jembrana',\n BAD = 'Badung',\n DEN = 'Denpasar',\n BUL = 'Buleleng',\n KLU = 'Klungkung',\n TAB = 'Tabanan',\n GIA = 'Gianyar',\n KAR = 'Karangasem',\n BAN = 'Bangli',\n )","sub_path":"controls.py","file_name":"controls.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"168481773","text":"from Map.FieldTypes import FieldTypes\n\n\nclass MapUtils:\n @staticmethod\n def findPlayer(map):\n for arrayIndex, array in enumerate(map.getMap()):\n for elementIndex, element in enumerate(array):\n if element == FieldTypes.PLAYER.value:\n return [arrayIndex, elementIndex]\n\n @staticmethod\n def findBoxPositions(map):\n l = []\n for arrayIndex, array in enumerate(map.getMap()):\n for elementIndex, element in enumerate(array):\n if element == FieldTypes.BOX.value:\n l.append([arrayIndex, elementIndex])\n return l\n\n\n @staticmethod\n def findGoalPositions(map):\n l = []\n for arrayIndex, array in enumerate(map.getInitialMap()):\n for elementIndex, element in enumerate(array):\n if element == FieldTypes.OUTPUT.value:\n l.append([arrayIndex, elementIndex])\n return l\n\n @staticmethod\n def getEnumValues(enum):\n # What the fuck, Python?\n # I spent a huge amount of time searching for way to somehow map values to names in an enum;\n # The obvious way would be to get a ValueSet from an EntrySet from a map from an enum...\n # But apparently Python maps do not support this???\n\n # The line below is a really shitty code violating principles of OOP,\n # But since Python allows access to protected methods (What the fuck?), a hacky way is a way nonetheless..\n\n return list(enum._value2member_map_)\n","sub_path":"Map/MapUtils.py","file_name":"MapUtils.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"233724561","text":"\"\"\"\n\"\"\"\n\nimport numpy as np\n\nfrom PyQt5 import QtWidgets\n\nfrom meggie.ui.source_analysis.linearSourceEstimateDialogUi import Ui_linearSourceEstimateDialog # noqa\n\nfrom meggie.code_meggie.general.source_analysis import create_linear_source_estimate # noqa\n\nfrom meggie.code_meggie.utils.validators import validate_name\n\nfrom meggie.ui.utils.messaging import exc_messagebox\nfrom meggie.ui.utils.messaging import messagebox\nfrom meggie.ui.utils.decorators import threaded\n\nimport meggie.code_meggie.general.mne_wrapper as mne\n\n\nclass LinearSourceEstimateDialog(QtWidgets.QDialog):\n \"\"\"\n \"\"\"\n\n def __init__(self, parent, fwd_name, inst_type,\n inst_name, experiment=None, on_close=None):\n QtWidgets.QDialog.__init__(self)\n self.parent = parent\n self.ui = Ui_linearSourceEstimateDialog()\n self.ui.setupUi(self)\n self.on_close = on_close\n self.experiment = experiment\n self.fwd_name = fwd_name\n self.inst_type = inst_type\n self.inst_name = inst_name\n\n if inst_type == 'raw':\n self.ui.groupBoxTimeParameters.setEnabled(True)\n self.ui.doubleSpinBoxStart.setEnabled(True)\n self.ui.doubleSpinBoxEnd.setEnabled(True)\n raw = self.experiment.active_subject.get_working_file(\n preload=False)\n self.ui.doubleSpinBoxStart.setValue(raw.times[0])\n self.ui.doubleSpinBoxEnd.setValue(raw.times[-1])\n\n self.ui.lineEditBasedOn.setText(fwd_name)\n self.ui.lineEditData.setText(inst_name)\n\n # temporarily remove labels\n # try:\n # self.populate_labels()\n # except Exception as exc:\n # messagebox(self, \"Could not populate labels.\",\n # exec_=True)\n\n self.populate_covariances()\n\n def read_labels(self):\n active_subject = self.experiment.active_subject\n subject = active_subject.mri_subject_name\n subjects_dir = active_subject.source_analysis_directory\n\n labels = mne.read_labels_from_annot(subject=subject, parc='aparc',\n subjects_dir=subjects_dir)\n\n return labels\n\n def populate_labels(self):\n labels = self.read_labels()\n\n self.ui.comboBoxLabel.clear()\n self.ui.comboBoxLabel.addItem('None')\n for label in labels:\n self.ui.comboBoxLabel.addItem(label.name)\n\n self.ui.comboBoxLabel.setCurrentIndex(0)\n\n def populate_covariances(self):\n active_subject = self.experiment.active_subject\n\n covariances = active_subject.get_covfiles()\n self.ui.comboBoxCovariance.clear()\n for covariance in covariances:\n self.ui.comboBoxCovariance.addItem(covariance)\n self.ui.comboBoxCovariance.setCurrentIndex(0)\n\n def accept(self):\n \"\"\"\n \"\"\"\n\n # collect parameters\n try:\n stc_name = validate_name(\n str(self.ui.lineEditSourceEstimateName.text()))\n except Exception as exc:\n exc_messagebox(self, exc, exec_=True)\n return\n\n if not stc_name:\n messagebox(self, \"Please give a name for the source estimate\",\n exec_=True)\n return\n\n if stc_name in self.experiment.active_subject.stcs:\n messagebox(self, \"Source estimate with this name already exists\",\n exec_=True)\n return\n\n fwd_name = self.fwd_name\n inst_name = self.inst_name\n inst_type = self.inst_type\n\n loose = float(self.ui.doubleSpinBoxLoose.value())\n depth = float(self.ui.doubleSpinBoxDepth.value())\n lambda2 = float(self.ui.doubleSpinBoxLambda.value())\n method = str(self.ui.comboBoxMethod.currentText())\n covfile = str(self.ui.comboBoxCovariance.currentText())\n\n if np.isclose(depth, 0):\n depth = None\n\n if not covfile:\n messagebox(self, \"No covariance matrix selected\", exec_=True)\n return\n\n start = float(self.ui.doubleSpinBoxStart.value())\n end = float(self.ui.doubleSpinBoxEnd.value())\n\n if inst_type == 'raw':\n start, end = None, None\n\n # label = str(self.ui.comboBoxLabel.currentText())\n # if label == 'None' or label == '':\n # label = None\n # else:\n # labels = self.read_labels()\n # label = [lbl for lbl in labels if lbl.name == label][0]\n label = None\n\n subject = self.experiment.active_subject\n\n @threaded\n def linear_stc(*args, **kwargs):\n create_linear_source_estimate(*args, **kwargs)\n\n try:\n update_ui = self.parent.parent.update_ui\n linear_stc(self.experiment, stc_name, inst_name, inst_type,\n covfile, fwd_name, loose, depth, label, lambda2,\n method, start, end, do_meanwhile=update_ui)\n except Exception as exc:\n exc_messagebox(self.parent, exc, exec_=True)\n\n # call close handler\n if self.on_close:\n self.on_close()\n\n self.close()\n","sub_path":"old_stc/source_analysis/dialogs/linearSourceEstimateDialogMain.py","file_name":"linearSourceEstimateDialogMain.py","file_ext":"py","file_size_in_byte":5138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"166236500","text":"'''\npython 3.4\n1. 下载安装pytesseract\n2.配置环境变量 C:\\Program Files (x86)\\Tesseract-OCR 至 Path中\n添加系统环境变量 TESSDATA_PREFIX C:\\Program Files (x86)\\Tesseract-OCR\\tessdata\n\n3.将 test.traineddata 文件拷贝到 C:\\Program Files (x86)\\Tesseract-OCR\\tessdata 中\n\n4.pip install -r requirements.pip\n\n5.安装雷神模拟器\n\n6. python main.py\n\n7.使用微信进入挑战智力按照提示进行标点\n\n8.不要拖动雷神模拟器等待刷分\n\n'''\n\nimport win32api\nimport win32con\nfrom ctypes import *\nimport time\nimport random\nimport pytesseract\n\nfrom PIL import ImageGrab\n\n\n\nclass POINT(Structure):\n _fields_ = [(\"x\", c_ulong), (\"y\", c_ulong)]\n\ndef get_mouse_point():\n \"\"\"\n 获取鼠标位置\n :return: dict,鼠标横纵坐标\n \"\"\"\n po = POINT()\n windll.user32.GetCursorPos(byref(po))\n return int(po.x), int(po.y)\n\ndef mouse_move(x, y):\n \"\"\"\n 移动鼠标位置\n :param x: int, 目的横坐标\n :param y: int, 目的纵坐标\n :return: None\n \"\"\"\n windll.user32.SetCursorPos(x, y)\n\ndef mouse_pclick(x=None, y=None, press_time=0.0):\n \"\"\"\n 模拟式长按鼠标\n :param x: int, 鼠标点击位置横坐标\n :param y: int, 鼠标点击位置纵坐标\n :param press_time: float, 点击时间,单位秒\n :return: None\n \"\"\"\n if not x is None and not y is None:\n mouse_move(x, y)\n time.sleep(0.05)\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)\n time.sleep(press_time)\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)\n\ndef click_xy(coordinate=None, press_time=0.0):\n \"\"\"\n 模拟式长按鼠标\n :param coordinate: tuple, 鼠标点击位置横坐标\n :param press_time: float, 点击时间,单位秒\n :return: None\n \"\"\"\n if not coordinate is None:\n mouse_move(int(coordinate[0]), int(coordinate[1]))\n time.sleep(0.05)\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)\n time.sleep(press_time)\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)\n\ndef get_static_mouse_point():\n \"\"\"\n 获取鼠标稳定的位置\n :return: dict,鼠标横纵坐标\n \"\"\"\n last = get_mouse_point()\n while True:\n time.sleep(0.5)\n current = get_mouse_point()\n if last == current:\n return current\n last = current\n\ndef grap_img(area):\n '''\n 根据区域进行截图\n :param area:\n :return:\n '''\n return ImageGrab.grab((int(area[0][0]),int(area[0][1]),int(area[1][0]),int(area[1][1])))\n\ndef get_str_by_img(img):\n '''\n 根据图片进行文字识别\n :param img:\n :return:\n '''\n return pytesseract.image_to_string(img, lang=\"test\",config=\"-psm 8 -c tessedit_char_whitelist=1234567890\")\n\ndef grap_by_center(center):\n '''\n 以一个坐标点为中心截一个100*100像素的图片并显示出来\n :param center:\n :return:\n '''\n grap_area = ((center[0]-50,center[1]-50),(center[0]+50,center[1]+50))\n img = grap_img(grap_area)\n img.show()\n img.close()\n\ndef get_num_coordinate(numUpleft,numDownright):\n '''\n 根据选取的数字区域,来解析该区域中每个格子(将区域划分为12个格子)的数字\n :param numUpleft:\n :param numDownright:\n :return dict: 返回一个字典 能够获取到每个数字对应的中心点坐标用于点击\n '''\n offsetX = (numDownright[0] - numUpleft[0] ) / 3 #X轴分为三块每块的偏移量\n offsetY = (numDownright[1] - numUpleft[1] ) / 4 #Y轴分为三块每块的偏移量\n num1Center = (numUpleft[0]+offsetX/2,numUpleft[1]+offsetY/2) #第一块中心点坐标\n num2Center = (numUpleft[0]+offsetX+offsetX/2,numUpleft[1]+offsetY/2) #第二块中点坐标\n num3Center = (numUpleft[0]+offsetX*2+offsetX/2,numUpleft[1]+offsetY/2) #第三块中点坐标\n num4Center = (numUpleft[0]+offsetX/2,numUpleft[1]+offsetY+offsetY/2) #第四块中点坐标\n num5Center = (numUpleft[0]+offsetX+offsetX/2,numUpleft[1]+offsetY+offsetY/2) #第五块中点坐标\n num6Center = (numUpleft[0]+offsetX*2+offsetX/2,numUpleft[1]+offsetY+offsetY/2) #第六块中点坐标\n num7Center = (numUpleft[0]+offsetX/2,numUpleft[1]+offsetY*2+offsetY/2) #第七块中点坐标\n num8Center = (numUpleft[0]+offsetX+offsetX/2,numUpleft[1]+offsetY*2+offsetY/2) #第八块中点坐标\n num9Center = (numUpleft[0]+offsetX*2+offsetX/2,numUpleft[1]+offsetY*2+offsetY/2) #第九块中点坐标\n #num10Center = (numUpleft[0]+offsetX/2,numUpleft[1]+offsetY*3+offsetY/2) #第七块中点坐标\n num11Center = (numUpleft[0]+offsetX+offsetX/2,numUpleft[1]+offsetY*3+offsetY/2) #第八块中点坐标\n #num12Center = (numUpleft[0]+offsetX*2+offsetX/2,numUpleft[1]+offsetY*3+offsetY/2) #第九块中点坐标\n\n\n num1Area = ((numUpleft[0],numUpleft[1]),(numUpleft[0]+offsetX,numUpleft[1]+offsetY))#第一块数字范围坐标\n num2Area = ((numUpleft[0]+offsetX,numUpleft[1]),(numUpleft[0]+offsetX*2,numUpleft[1]+offsetY))#第二块数字范围坐标\n num3Area = ((numUpleft[0]+offsetX*2,numUpleft[1]),(numUpleft[0]+offsetX*3,numUpleft[1]+offsetY))#第三块数字范围坐标\n num4Area = ((numUpleft[0],numUpleft[1]+offsetY),(numUpleft[0]+offsetX,numUpleft[1]+offsetY*2))#第四块数字范围坐标\n num5Area = ((numUpleft[0]+offsetX,numUpleft[1]+offsetY),(numUpleft[0]+offsetX*2,numUpleft[1]+offsetY*2))#第五块数字范围坐标\n num6Area = ((numUpleft[0]+offsetX*2,numUpleft[1]+offsetY),(numUpleft[0]+offsetX*3,numUpleft[1]+offsetY*2))#第六块数字范围坐标\n num7Area = ((numUpleft[0],numUpleft[1]+offsetY*2),(numUpleft[0]+offsetX,numUpleft[1]+offsetY*3))#第七块数字范围坐标\n num8Area = ((numUpleft[0]+offsetX,numUpleft[1]+offsetY*2),(numUpleft[0]+offsetX*2,numUpleft[1]+offsetY*3))#第八块数字范围坐标\n num9Area = ((numUpleft[0]+offsetX*2,numUpleft[1]+offsetY*2),(numUpleft[0]+offsetX*3,numUpleft[1]+offsetY*3))#第九块数字范围坐标\n #num10Area = ((numUpleft[0],numUpleft[1]+offsetY*3),(numUpleft[0]+offsetX,numUpleft[1]+offsetY*4))#第七块数字范围坐标\n num11Area = ((numUpleft[0]+offsetX,numUpleft[1]+offsetY*3),(numUpleft[0]+offsetX*2,numUpleft[1]+offsetY*4))#第八块数字范围坐标\n #num12Area = ((numUpleft[0]+offsetX*2,numUpleft[1]+offsetY*3),(numUpleft[0]+offsetX*3,numUpleft[1]+offsetY*4))#第九块数字范围坐标\n\n num_list = [\n {\"numCenter\":num1Center,\n \"numArea\":num1Area},\n {\"numCenter\":num2Center,\n \"numArea\":num2Area},\n {\"numCenter\":num3Center,\n \"numArea\":num3Area},\n {\"numCenter\":num4Center,\n \"numArea\":num4Area},\n {\"numCenter\":num5Center,\n \"numArea\":num5Area},\n {\"numCenter\":num6Center,\n \"numArea\":num6Area},\n {\"numCenter\":num7Center,\n \"numArea\":num7Area},\n {\"numCenter\":num8Center,\n \"numArea\":num8Area},\n {\"numCenter\":num9Center,\n \"numArea\":num9Area},\n {\"numCenter\":num11Center,\n \"numArea\":num11Area}\n ]\n resultDict = {}\n pageId = 1;\n for num_dict in num_list :\n img1 = grap_img(num_dict[\"numArea\"])\n img1.save(\"./graps/grap{}.jpg\".format(pageId))\n str1 = get_str_by_img(img1)\n print(\"当前格子解析的数字是{}\".format(str1))\n img1.close()\n resultDict[int(str1)]=num_dict[\"numCenter\"]\n pageId = pageId+1\n return resultDict\n\ndef click_current_num(i,numDict):\n '''\n 点击数字对应的中心点坐标\n :param i: 当前的数字\n :param numDict: 数字字段 key:数字 value: 数字对应的中心点坐标\n :return:\n '''\n if i < 10:\n # 1位数\n oneNum = i\n # print(\"{}的坐标点位{}\".format(oneNum, numDict.get(oneNum)))\n # grap_by_center(numDict.get(oneNum)) #用于数字识别错误时DEBUG使用\n\n click_xy(numDict.get(oneNum), round(random.uniform(0.1, 0.4), 2))\n\n elif i < 100:\n # 2位数\n oneNum = int(i % 10)\n twoNum = int(i / 10)\n # grap_by_center(numDict.get(twoNum)) #用于数字识别错误时DEBUG使用\n # time.sleep(2)\n # grap_by_center(numDict.get(oneNum))#用于数字识别错误时DEBUG使用\n click_xy(numDict.get(twoNum), round(random.uniform(0.1, 0.4), 2))\n click_xy(numDict.get(oneNum), round(random.uniform(0.1, 0.4), 2))\n else:\n # 3位数\n oneNum = int(i % 10)\n twoNum = int(i / 10 % 10)\n threeNum = int(i / 100)\n # grap_by_center(numDict.get(threeNum))#用于数字识别错误时DEBUG使用\n # grap_by_center(numDict.get(twoNum))#用于数字识别错误时DEBUG使用\n # grap_by_center(numDict.get(oneNum))#用于数字识别错误时DEBUG使用\n click_xy(numDict.get(threeNum), round(random.uniform(0.1, 0.4), 2))\n click_xy(numDict.get(twoNum), round(random.uniform(0.1, 0.4), 2))\n click_xy(numDict.get(oneNum), round(random.uniform(0.1, 0.4), 2))\n return\n\nif __name__ == '__main__':\n\n print(\"鼠标移动到剩余秒数左上角\")\n time.sleep(1)\n remainUpleft = get_static_mouse_point() #剩余秒数左上角坐标\n print(\"获取到剩余秒数左上坐标为{}\".format(remainUpleft))\n time.sleep(0.5)\n print(\"鼠标移动到剩余秒数右下角\")\n time.sleep(1)\n remainDownright = get_static_mouse_point() #剩余秒数右下角坐标\n print(\"获取到剩余秒数右下坐标为{}\".format(remainDownright))\n print(\"鼠标移动到数字区域左上角\")\n time.sleep(1)\n numUpleft = get_static_mouse_point() #数字区域左上角坐标\n print(\"获取到数字区域左上坐标为{}\".format(numUpleft))\n time.sleep(0.5)\n print(\"鼠标移动到数字区域右下角\")\n time.sleep(1)\n numDownright = get_static_mouse_point() #数字区域右下角坐标\n print(\"获取到数字区域右下坐标为{}\".format(numDownright))\n\n remainArea = (remainUpleft, remainDownright) # 剩余秒数区域\n\n for i in range(501): #进行循环\n im1 = grap_img(remainArea) #获取目前剩余秒数的图片\n remainstr = get_str_by_img(im1) #获取目前剩余秒数的数值\n im1.close()\n # im2 = grap_img((numUpleft,numDownright)) #用于数字识别错误时DEBUG使用\n # im2.save(\"./graps/umarea.jpg\")\n #确保当前剩余3秒以上。需要除以10是因为后缀s被识别为5需要去掉\n while int(int(remainstr)/10) < 3:\n print(\"剩余秒数小于3秒,等待{}秒....\".format(int(remainstr)/10))\n time.sleep(int(remainstr)/10)\n im1 = grap_img(remainArea)\n remainstr = get_str_by_img(im1)\n #获取当前数字区域的数字字典\n numDict = get_num_coordinate(numUpleft, numDownright)\n i=i+1\n print(\"目前需要输入的数字为{}\".format(i))\n click_current_num(i,numDict) #输入当前数字\n print(\"点击完成\")\n time.sleep(20)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"91438559","text":"from google.appengine.ext import db\nfrom db_model import User,Set,Card\nimport json\nimport logging\n\nclass BaseController:\n def __init__(self, request):\n self.request = request\n\nclass SetsController(BaseController):\n def index(self):\n user_query = User.gql(\"WHERE iwiw_id = :1\", self.request.get('opensocial_owner_id'))\n user = user_query.get()\n if user == None:\n user = User()\n user.iwiw_id = self.request.get('opensocial_owner_id')\n user.put()\n\n sets = []\n for set in user.sets:\n sets.append({'key': str(set.key()),\n 'title': set.title, \n 'description': set.description})\n return json.write(sets)\n\n def show(self, key):\n set = db.get(db.Key(key))\n item = {'key': str(set.key()),\n 'description': set.description,\n 'cards': []}\n for card in set.cards:\n item['cards'].append({'front': card.front,\n 'flip': card.flip,\n 'key': str(card.key())})\n return json.write(item)\n\n def create(self):\n user_query = User.gql(\"WHERE iwiw_id = :1\", self.request.get('opensocial_owner_id'))\n user = user_query.get()\n\n set = Set()\n set.description = self.request.get('description')\n set.title = self.request.get('title')\n set.owner = user\n return json.write({'key': str(set.put())})\n\nclass CardsController(BaseController):\n def create(self):\n card = Card()\n card.front = self.request.get('front')\n card.flip = self.request.get('flip')\n card.set = db.Key(self.request.get('set_key'))\n return json.write({'key': str(card.put())}) \n\n def update(self, key):\n card = db.get(db.Key(key))\n card.front = self.request.get('front')\n card.flip = self.request.get('flip')\n card.put()\n\n def delete(self, key):\n card = db.get(db.Key(key))\n card.delete()\n","sub_path":"controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"237569018","text":"import csv\n\nwith open('prediction_6.csv', newline='') as csvfile:\n spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')\n headings = next(spamreader)\n print(headings)\n headings = [\"id\", \"class\"]\n print(headings)\n rows = []\n for row in spamreader:\n row = list(map(float, row))\n new_row = [None, None]\n new_row[0] = int(row[0]) + 1\n new_row[1] = row.index(max(row[1:]))\n rows.append(new_row)\n row = new_row\n \nwith open(\"prediction_new.csv\", 'w', newline='') as f:\n f_csv = csv.writer(f)\n f_csv.writerow(headings)\n f_csv.writerows(rows)\n\n","sub_path":"CNN-Image/convert_csv.py","file_name":"convert_csv.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"642862294","text":"#Peptide Encoding Problem: Find substrings of a genome encoding a given amino acid sequence.\n# Input: A DNA string Text, an amino acid string Peptide, and the array GeneticCode.\n# Output: All substrings of Text encoding Peptide (if any such substrings exist).\ndef reverse_string(seq):\n return seq[::-1]\n\ndef complement(seq):\n#return the complementary sequence string.\n seq=seq.upper()\n basecomplement={\"A\":\"T\",\"C\":\"G\",\"G\":\"C\",\"T\":\"A\",\"N\":\"N\"}\n letters=list(seq)\n letters=[basecomplement[base] for base in letters]\n return ''.join(letters)\n\n\ndef reversecomplement(seq):\n #return the reverse complement of the dna string.\n seq=reverse_string(seq)\n seq=complement(seq)\n return seq\n\ndef DNA_To_AA(seq):\n RNA_AA_dict = {'TCC': 'S', 'TAC': 'Y', 'AGT': 'S', 'ACG': 'T', 'TAA': '*', 'TTA': 'L', 'GTC': 'V', 'CAC': 'H',\n 'CGT': 'R', 'CGG': 'R', 'CTC': 'L', 'AGG': 'R', 'ACA': 'T', 'TCA': 'S', 'CCT': 'P', 'CAG': 'Q',\n 'ACC': 'T', 'TTC': 'F', 'ATC': 'I', 'AAT': 'N', 'ATA': 'I', 'CAT': 'H', 'GGC': 'G', 'GGG': 'G',\n 'GCT': 'A', 'GAT': 'D', 'GCA': 'A', 'GCG': 'A', 'GTA': 'V', 'GAC': 'D', 'CTT': 'L', 'CAA': 'Q',\n 'CCG': 'P', 'AAG': 'K', 'GTT': 'V', 'GGT': 'G', 'TAT': 'Y', 'TGG': 'W', 'AGA': 'R', 'TTT': 'F',\n 'TAG': '*', 'TGC': 'C', 'GGA': 'G', 'CCA': 'P', 'GCC': 'A', 'CGA': 'R', 'AAA': 'K', 'GTG': 'V',\n 'CGC': 'R', 'CTG': 'L', 'TCG': 'S', 'TTG': 'L', 'GAA': 'E', 'GAG': 'E', 'TCT': 'S', 'ATT': 'I',\n 'AAC': 'N', 'ACT': 'T', 'TGT': 'C', 'CTA': 'L', 'ATG': 'M', 'CCC': 'P', 'AGC': 'S', 'TGA': '*'}\n F_position = 0\n R_position = 0\n Aa=\"\"\n for i in range(int(len(seq) / 3)):\n F_position = i*3\n R_position = F_position+3\n RNA_one=seq[F_position:R_position]\n #if RNA_one == \"TAA\" or RNA_one == \"TAG\" or RNA_one == \"TGA\":\n # break\n Aa += RNA_AA_dict[RNA_one]\n\n return Aa\n\ndef Peptide_Encoding(DNA,AA_input):\n AA= DNA_To_AA(DNA)\n print(AA)\n l=len(AA_input)\n return_DNA=[]\n find_position=0\n #print(DNA,AA,l,return_DNA,find_position)\n\n\n while AA_input in AA[find_position:]:\n #print(AA[find_position:])\n AA_position = find_position + AA[find_position:].find(AA_input)\n DNA_position = 3 * AA_position\n #print(AA_position, DNA_position)\n return_DNA.append(DNA[DNA_position:DNA_position + 3 * l])\n find_position = AA_position + 1\n #print(find_position)\n return return_DNA\n\n\n\nDNA=\"\"\nfilename = input(\"Enter file name: \")\nfileread = open(filename, \"r\")\nfor i in fileread:\n read = i.strip()\n DNA+=read.upper()\nprint(DNA[:200])\n\nF_position=0\nR_position=0\n\nAa_input=input(\"what is the aa?\")\n\n\n\nDNA_F_1=DNA\nprint1=Peptide_Encoding(DNA_F_1,Aa_input)\nif print1!=[]:\n for i in print1:\n print(\"1\",i)\n\n\nDNA_F_2=DNA[1:]\nprint2=Peptide_Encoding(DNA_F_2,Aa_input)\nif print2!=[]:\n for i in print2:\n print(\"2\",i)\n\nDNA_F_3=DNA[2:]\nprint3=Peptide_Encoding(DNA_F_3,Aa_input)\nif print3!=[]:\n for i in print3:\n print(\"3\",i)\n\nRC_DNA=reversecomplement(DNA)\n\nDNA_R_1=RC_DNA\nprint4=Peptide_Encoding(DNA_R_1,Aa_input)\nif print4!=[]:\n for i in print4:\n print(\"4\",reversecomplement(i))\n\nDNA_R_2=RC_DNA[1:]\nprint5=Peptide_Encoding(DNA_R_2,Aa_input)\nif print5!=[]:\n for i in print5:\n print(\"5\",reversecomplement(i))\n\nDNA_R_3=RC_DNA[2:]\nprint6=Peptide_Encoding(DNA_R_3,Aa_input)\nif print6!=[]:\n for i in print6:\n print(\"6\",reversecomplement(i))\n\n#print(DNA_F_1,DNA_F_2,DNA_F_3,DNA_R_1,DNA_R_2,DNA_R_3)\n#print(Aa_F_1,Aa_F_2,Aa_F_3,Aa_R_1,Aa_R_2,Aa_R_3)\n\n#根据AA序列在基因组中寻找相关序列\n\n\n\n\n#Bacillus brevis.txt\n#VKLFPWFNQY","sub_path":"genome sequence/Peptide Encoding Problem for Bacillus brevis.py","file_name":"Peptide Encoding Problem for Bacillus brevis.py","file_ext":"py","file_size_in_byte":3749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"598424822","text":"# A simple program that encrypts your text using Digrapgh Cipher method #\r\n\r\n# You can find the table that I used to encrypt the text using below given link. Save it as 'dgcph.jpg' #\r\n# https://www.google.com/url?sa=i&url=https%3A%2F%2Fcrypto.interactive-maths.com%2Fdigraph-substitution-ciphers.html&psig=AOvVaw27PUfxyisv5U6olwTKQKLU&ust=1604991496396000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCNiitrPx9OwCFQAAAAAdAAAAABAJ#\r\n\r\nimport cv2\r\n\r\ndef diciph(word):\r\n\r\n word=word.upper()\r\n\r\n if word.isalpha():\r\n s=(list(word))\r\n l=len(s)\r\n if (l%2)!=0:\r\n s.append(\"X\")\r\n l=len(s)\r\n c=[]\r\n for i in range(l):\r\n\r\n if(i%2 is 0):\r\n asc=ord(s[i])+9\r\n if asc>90:\r\n asc=64+asc-90\r\n char=chr(asc)\r\n c.append(char)\r\n\r\n\r\n if(i%2!=0):\r\n asc=ord(s[i])+17\r\n if asc>90:\r\n asc=64+asc-90\r\n char=chr(asc)\r\n c.append(char)\r\n\r\n\r\n for i in range(len(c)):\r\n print(c[i],end=' ')\r\n\r\n s=input(\"\\n\\nDo you want to verify you answer? [Yes/No]: \")\r\n if (str(s)==\"yes\" or str(s)==\"Yes\" or str(s)==\"Y\" or str(s)==\"y\"):\r\n print(\"Check out the popped up image on your Taskbar!:)\")\r\n c=cv2.imread('dgcph.jpg')\r\n cv2.imshow('a',c)\r\n cv2.waitKey(0)\r\n\r\n \r\n\r\n \r\n else:\r\n print(\"enter valid word with letters only\")\r\n \r\n\r\n## DRIVER FUNCTION ##\r\n\r\nif __name__ == \"__main__\":\r\n a=str(input(\"Enter the word to be encrypted: \"))\r\n diciph(a)\r\n\r\n\r\n","sub_path":"Digraph Cipher.py","file_name":"Digraph Cipher.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"55606943","text":"from selenium import webdriver\nimport time\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.action_chains import ActionChains\ndriver=webdriver.PhantomJS()\n\ndriver.implicitly_wait(30)\ndriver.get(\"https://login.taobao.com/member/login.jhtml\")\ntime.sleep(2)\ndriver.maximize_window() #将浏览器最大化显示\ntime.sleep(2)\nelement = WebDriverWait(driver, 100).until(lambda driver:driver.find_element_by_xpath(\"//*[@id='J_Quick2Static']\"))\nelement.click()\ndriver.implicitly_wait(30)\nusername = driver.find_element_by_name(\"TPL_username\")\nif not username.is_displayed:\n driver.implicitly_wait(20)\n driver.find_element_by_xpath(\"//*[@id='J_Quick2Static']\").click()\ndriver.implicitly_wait(20)\nusername.send_keys(\"13229481609\")\ndriver.find_element_by_name(\"TPL_password\").send_keys(\"lian446878\")\ndriver.implicitly_wait(20)\ndriver.find_element_by_xpath(\"//*[@id='J_SubmitStatic']\").click()\ntime.sleep(4)\n\n\ndriver.get_screenshot_as_file('show.png')\nmoney=driver.find_element_by_xpath(\"//*[@id='J_Col_Main']/div/div[3]/div[1]/div[2]/div[3]/ul/li[2]/div/ul/li/a\")\n\ntime.sleep(3)\nif not money.is_displayed:\n\tprint(\"not displayed\")\nelse:\n\tprint(\"displayed,but is can't be clicked\")\n\tmoney.click()\ntime.sleep(4)\nwh = driver.window_handles\nch = driver.current_window_handle\nfor i in wh:\n\tif i != ch:\n\t\tdriver.switch_to_window(i)\n\t\tbreak\ndriver.get_screenshot_as_file('show1.png')\ntime.sleep(2)\ntaojinb=driver.find_element_by_xpath(\"//*[@id='content']/div[1]/div[2]/div[2]/div/div[1]/div[1]/div[3]/a[1]\")\ntime.sleep(2)\ntaojinb.click()\ntime.sleep(2)\ndriver.get_screenshot_as_file('show1.png')\nprint(driver.page_source)\n","sub_path":"selenium/taobao.py","file_name":"taobao.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"162138057","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[28]:\n\n\nimport os\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"1\"\nimport warnings # 消除警告\nwarnings.filterwarnings(\"ignore\")\n\n\n# In[29]:\n\n\nimport tensorflow as tf\n\n\n# In[30]:\n\n\nimport numpy as np\nimport pandas as pd\nimport pickle\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\nfrom IPython.display import Audio\nfrom matplotlib.pyplot import imshow\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.utils.class_weight import compute_class_weight\n\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import models\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras import callbacks\nfrom tensorflow.keras import regularizers\nfrom tensorflow.keras import models\n\n\n# In[31]:\n\n\nIMG_DIR = 'D:/mgc/spectrogram_images/'\nIMG_HEIGHT = 216\nIMG_WIDTH = 216\nNUM_CLASSES = 7\nNUM_EPOCHS = 10\nBATCH_SIZE = 32\nL2_LAMBDA = 0.001\n\n\n# In[32]:\n\n\nlabel_dict = {'Hip':0,\n 'Pop':1,\n 'Vocal':2,\n 'Rhythm':3,\n 'Reggae':4,\n 'Rock':5,\n 'Techno':6,\n }\n\n\n# In[33]:\n\n\none_hot = OneHotEncoder(n_values=NUM_CLASSES)\n\n\n# In[35]:\n\n\nall_files = os.listdir(IMG_DIR)\n\n\n# In[247]:\n\n\nlabel_array = []\nfor file_ in all_files:\n vals = file_[:-4].split('_')\n label_array.append(label_dict[vals[1]])\n\n\n# In[248]:\n\n\ntrain_files, test_files, train_labels, test_labels = train_test_split(all_files, \n label_array,\n random_state = 8, \n test_size = 0.2\n )\n\n\n# In[249]:\n\n\ntest_files,val_files, test_labels, val_labels = train_test_split(test_files, test_labels,\n random_state = 6, \n test_size = 0.5\n )\n\n\n# In[250]:\n\n\nconv_base = tf.keras.applications.VGG16(include_top = False, \n weights = 'imagenet', \n input_shape = (216, 216, 3) # 3 channels - RGB\n ) \n# The weights are for the CONV filters - hence you can pass any pre-set image size to this VGG network\n# Need not be 224 x 224 x 3 (Although does it work better for 224 size? Need to check)\n\n\n# In[251]:\n\n\nconv_base\n\n\n# In[252]:\n\n\nconv_base.summary()\n\n\n# In[253]:\n\n\nmodel = models.Sequential()\nmodel.add(conv_base)\nmodel.add(layers.Flatten()) # Flatten output and send it to MLP\n\n# 1-layer MLP with Dropout, BN \nmodel.add(layers.Dense(512, name='dense_1', kernel_regularizer=regularizers.l2(L2_LAMBDA)))\nmodel.add(layers.Dropout(rate=0.3, name='dropout_1')) # Can try varying dropout rates\nmodel.add(layers.Activation(activation='relu', name='activation_1'))\n\nmodel.add(layers.Dense(NUM_CLASSES, activation='softmax', name='dense_output'))\nmodel.summary()\n\n\n# In[254]:\n\n\n# Set the convolution base to be not trainable\nconv_base.trainable = False\nmodel.summary()\n\n\n# In[255]:\n\n\ndef load_batch(file_list):\n img_array = []\n idx_array = []\n label_array = []\n\n for file_ in file_list:\n im = Image.open(IMG_DIR + file_)\n im = im.resize((216, 216), Image.ANTIALIAS)\n img_array.append(np.array(im))\n\n vals = file_[:-4].split('_')\n idx_array.append(vals[0])\n label_array.append([label_dict[vals[1]]])\n\n label_array = one_hot.fit_transform(label_array).toarray()\n img_array = np.array(img_array)/255.0 # Normalize RGB\n \n return img_array, np.array(label_array), np.array(idx_array)\n\n\n# In[256]:\n\n\ndef batch_generator(files, BATCH_SIZE):\n L = len(files)\n\n #this line is just to make the generator infinite, keras needs that \n while True:\n\n batch_start = 0\n batch_end = BATCH_SIZE\n\n while batch_start < L:\n \n limit = min(batch_end, L)\n file_list = files[batch_start: limit]\n batch_img_array, batch_label_array, batch_idx_array = load_batch(file_list)\n\n yield (batch_img_array, batch_label_array) # a tuple with two numpy arrays with batch_size samples \n\n batch_start += BATCH_SIZE \n batch_end += BATCH_SIZE\n\n\n# In[257]:\n\n\noptimizer = optimizers.Adam(lr=1e-5)\n\nloss = 'categorical_crossentropy'\n\nmetrics = ['categorical_accuracy']\n\nmodel.compile(optimizer=optimizer, loss=loss, metrics=metrics)\n\n\n# In[258]:\n\n\nSTEPS_PER_EPOCH = len(train_files)//BATCH_SIZE\n\n\n# 所以,如果列表元素可以按照某種演算法推算出來,那我們是否可以在迴圈的過程中不斷推算出後續的元素呢?這樣就不必建立完整的list,從而節省大量的空間。在Python中,這種一邊迴圈一邊計算的機制,稱為生成器:generator。\n\n# In[259]:\n\n\nhistory = model.fit_generator(generator = batch_generator(train_files, BATCH_SIZE),\n epochs = 10,\n steps_per_epoch = STEPS_PER_EPOCH,\n validation_data = batch_generator(val_files, BATCH_SIZE), \n validation_steps = 1)\n\n\n# In[261]:\n\n\nhistory.history.keys()\ntest1 = pd.DataFrame(history.history, index=range(1,11))\n\n\n# In[262]:\n\n\n#test1.to_csv('D:/VGG16.CSV')\n\n\n# In[263]:\n\n\ntest1 = pd.read_csv('D:/VGG16.CSV')\ntest1\n\n\n# In[264]:\n\n\nplt.xticks(range(1,11))\nplt.plot(test1['loss'], marker='o', label='training_loss')\nplt.plot(test1['val_loss'], marker='d', label='validation_loss')\nplt.ylabel('Loss', fontsize=12)\nplt.xlabel('Training Epochs', fontsize=12)\nplt.grid()\nplt.legend()\n\n\n# In[265]:\n\n\nplt.xticks(range(1,11))\nplt.plot(test1['categorical_accuracy'], marker='o', label='training_accuracy')\nplt.plot(test1['val_categorical_accuracy'], marker='d', label='validation_accuracy')\nplt.ylabel('Accuracy', fontsize=12)\nplt.xlabel('Training Epochs', fontsize=12)\nplt.grid()\nplt.legend()\n\n\n# In[274]:\n\n\nhistory = model.fit_generator(generator = batch_generator(train_files, BATCH_SIZE),\n epochs = 4,\n steps_per_epoch = STEPS_PER_EPOCH,\n validation_data = batch_generator(val_files, BATCH_SIZE), \n validation_steps = 1)\n\n\n# In[290]:\n\n\nhistory.history.keys()\ntest1 = pd.DataFrame(history.history)\ntest1\n\n\n# In[283]:\n\n\n#TEST_STEPS = len(test_files)//BATCH_SIZE\n\npred_probs = model.predict_generator(generator = batch_generator(test_files, BATCH_SIZE), steps=2)\npred = np.argmax(pred_probs, axis=-1)\n\n\n# In[284]:\n\n\nmi = dict(zip(label_dict.values(), label_dict.keys()))\n\n\n# In[285]:\n\n\ntest_labels_name = []\nfor i in range(0,len(test_labels),1):\n test_labels_name.append(mi[test_labels[i]])\n\n\n# In[286]:\n\n\npred_name = []\nfor i in range(0,len(pred),1):\n pred_name.append(mi[pred[i]])\n\n\n# In[287]:\n\n\nfrom sklearn.metrics import confusion_matrix, f1_score, accuracy_score, roc_auc_score, roc_curve, auc\nfrom scipy import interp\nimport itertools\nfrom itertools import cycle \ndef one_hot_encoder(true_labels, num_records, num_classes):\n temp = np.array(true_labels[:num_records])\n true_labels = np.zeros((num_records, num_classes))\n true_labels[np.arange(num_records), temp] = 1\n return true_labels\n\n\n# In[288]:\n\n\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(test_labels_name, pred_name,labels=['Hip', 'Pop', 'Vocal', 'Rhythm', 'Reggae', 'Rock', 'Techno'])\ncm\nimport seaborn as sns\nimport matplotlib.pyplot as plt \nplt.figure(figsize = (10,8))\nax= plt.subplot()\nsns.heatmap(cm, annot=True, ax = ax); #annot=True to annotate cells\n\n# labels, title and ticks\nax.set_xlabel('Predicted labels');ax.set_ylabel('True labels'); \nax.set_title('Confusion Matrix'); \nax.xaxis.set_ticklabels(['Hip', 'Pop', 'Vocal', 'Rhythm', 'Reggae', 'Rock', 'Techno']); ax.yaxis.set_ticklabels(['Hip', 'Pop', 'Vocal', 'Rhythm', 'Reggae', 'Rock', 'Techno'])\n\n\n# In[289]:\n\n\nprint('Test Set Accuracy = {0:.2f}'.format(accuracy_score(y_true=test_labels[:len(pred)], y_pred=pred)))\nprint('Test Set F-score = {0:.2f}'.format(f1_score(y_true=test_labels[:len(pred)], y_pred=pred, average='macro')))\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Final _report/09_8108050001/cnn_vgg16_Paper/transfer.py","file_name":"transfer.py","file_ext":"py","file_size_in_byte":8514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"71386649","text":"from threadqueue import ThreadQueue\nfrom unittest import TestCase\n\n\nclass TestThreadqueue(TestCase):\n\n def test_threadqueue(self):\n args = range(0, 10)\n\n self.assertEquals(\n ThreadQueue(lambda _, i: i * 10, *args),\n [i * 10 for i in args]\n )\n","sub_path":"tests/test_threadqueue.py","file_name":"test_threadqueue.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"50394212","text":"from django.shortcuts import render,redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse,Http404,HttpResponseRedirect\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.http import JsonResponse\nimport datetime as dt\nfrom .models import Post,Comment,Profile\nfrom .forms import CommentForm,PostForm,ProfileForm\nfrom django.contrib.auth.models import User\n#from decouple import config,Csv\n\n\ndef home(request):\n posts = Post.objects.all()\n current_user = request.user\n profiles = Profile.objects.all()\n form = CommentForm()\n comments = Comment.objects.all()\n\n return render (request, 'home.html', { \"posts\": posts ,\"form\":form, \"comments\":comments,\"profiles\":profiles})\n\n\n@login_required(login_url='/accounts/login/')\ndef user_profile(request,profile_id):\n current_user = request.user\n comments = Comment.objects.all()\n form = CommentForm()\n\n try:\n # all_posts = Post.objects.all()\n profile = Profile.objects.get(id=profile_id)\n prof_username = profile.username\n posts = Post.objects.filter(username = prof_username)\n\n except:\n raise ObjectDoesNotExist()\n\n return render(request, 'userprofile.html', { \"posts\": posts ,\"form\":form, \"comments\":comments, \"profile\":profile })\n\n\n\n@login_required(login_url='/accounts/login/')\ndef new_post(request):\n current_user = request.user\n profile = Profile.objects.filter(user=current_user)\n\n\n if request.method == 'POST':\n form = PostForm(request.POST, request.FILES)\n if form.is_valid():\n post = form.save(commit=False)\n post.username = current_user\n # post.p_pic = profile.p_pic\n\n post.likes = 0\n post.save()\n\n return redirect('home')\n\n else:\n form = PostForm()\n\n return render(request, 'new_post.html',{\"form\":form, \"profile\":profile})\n\n\n\n@login_required(login_url='/accounts/login/')\ndef profile(request):\n current_user = request.user\n current_user_id=request.user.id\n form = CommentForm()\n comments=Comment.objects.all()\n # comment_number=len(comments)\n\n try:\n profile = Profile.objects.get(user=current_user)\n posts = Post.objects.filter(username=current_user_id)\n title = profile.user\n username = profile.user\n post_number = len(posts)\n\n except ObjectDoesNotExist:\n return redirect('home')\n\n return render(request, 'profile.html',{\"profile\":profile,\"posts\":posts,\"form\":form,\"post_number\":post_number,\"title\":title,\"username\":username,\"comments\":comments})\n\n\n\n\ndef search_results(request):\n current_user = request.user\n current_user_id=request.user.id\n posts = Post.objects.filter(username=current_user_id)\n if 'searchname' in request.GET and request.GET['searchname']:\n search_term = request.GET.get(\"searchname\")\n searched_names = Profile.search_profile(search_term)\n message = f\"{search_term}\"\n\n return render(request,'search.html', {\"message\":message, \"usernames\":searched_names,\"posts\":posts})\n\n else:\n message = \"You haven't searched for any username\"\n return render(request,'search.html',{\"message\":message})\n\n\n\n\n\n@login_required(login_url='/accounts/login')\ndef Comment_Image(request,pk):\n # user_comment = request.GET.get('comment')\n current_user = request.user\n current_image = Post.objects.get(id=pk)\n if request.method == 'POST':\n form = CommentForm(request.POST)\n if form.is_valid():\n comment=form.save(commit=False)\n comment.username = current_user\n comment.post = current_image\n comment.save()\n # comment.comment = user_comment\n return redirect('home')\n\n else:\n return redirect('home')\n\n\n@login_required(login_url='/accounts/login')\ndef edit_profile(request):\n\n form=ProfileForm(instance=request.user.profile)\n\n if request.method == 'POST':\n form = ProfileForm(request.POST, request.FILES,instance=request.user.profile)\n if form.is_valid():\n profile = form.save(commit=False)\n profile.user = request.user\n profile.save()\n\n else:\n form=ProfileForm()\n\n return render(request,'edit_profile.html', {\"form\":form})\n","sub_path":"images/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"294872383","text":"\"\"\"\nIf p is the perimeter of a right angle triangle with integral length sides, \n{a,b,c}, there are exactly three solutions for p = 120.\n\n{20,48,52}, {24,45,51}, {30,40,50}\n\nFor which value of p ≤ 1000, is the number of solutions maximised?\n\n20^2 + 48^2 = 52^2\n\n\"\"\"\n\n\ndef triangle_count(p):\n t_count = 0\n for i in range(int(p/3), int(p/2)+1):\n cat = p - i\n for j in range(int(cat/2), i):\n p_catetos = j**2 + (cat-j)**2\n if i**2 == p_catetos:\n #print(f'P: {p} - [{i},{j},{cat-j}]')\n t_count += 1\n return t_count\n\n\nmax_tr = 0\nfor i in range(10,1001):\n n = triangle_count(i)\n if n > max_tr:\n max_tr = n\n print(f'P: {i}, {n} triangulos')\n\n","sub_path":"Problem_039/problem_39.py","file_name":"problem_39.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"354147454","text":"# Class to construct a minimum heap\n# Heaps are good to keep track of min or max value\n# To access children nodes: let i be index of current node\n# First child node: 2i + 1\n# Second child node: 2i + 2\n# To access parent nodes:\n# Parent Node = floor((i- 1) / 2)\nclass minHeap:\n # init class sets the heap equal to buildHeap() of thay array passed in\n def __init__(self, array):\n self.heap = self.buildHeap(array)\n\n # runs in O(n) time | O(1) space\n # method that turns array into an array that satisfies heap properties\n def buildHeap(self, array):\n # Grab first parent node of the heap, basically parent node ofthe final node we pass in\n firstParentIdx = (len(array) - 2) // 2\n # Now go from the first parent idx and go backwards, starting and parent and building to the top\n for currentIdx in reversed(range(firstParentIdx + 1)):\n # Now call sift down, build all the nodes or children that parent has, and keep going until you reach the start of the array\n self.siftDown(currentIdx, len(array) -1, array)\n return array\n # Function that sifts down heap applying heap property \n def siftDown(self, currentIdx, endIdx, heap):\n childOneIdx = currentIdx * 2 + 1\n while childOneIdx <= endIdx: # run while loop while there still are children nodes\n childTwoIdx = currentIdx * 2 + 2 if currentIdx * 2 + 2 <= endIdx else -1\n # if there is a child 2 and child 2 is smaller than child one\n if childTwoIdx != -1 and heap[childTwoIdx] < heap[childOneIdx]: # For max heap replace this with > sign\n # Now we know our second child is smallest so swap that\n idxToSwp = childTwoIdx\n # Else just swap child one\n else:\n idxToSwap = childOneIdx\n # if our heap of our index to swap is less than the current index we are on,\n # Thid means the child is less than the parent, this is NOT okay\n if heap[idxToSwap] < heap[currentIdx]: # For max heap replace this with > sign\n # Here we swap our indexes\n self.swap(currentIdx, idxToSwap, heap)\n # Now sift and move that node down\n currentIdx = idxToSwap\n # Now recalculate child one idx\n childOneIdx = currentIdx * 2 + 1\n else:\n break # break when in correct position\n\n def siftUp(self, currentIdx, heap):\n # Formula that calculates our parent node\n parentIdx = (currentIdx - 1) // 2\n # While we are not at root and the property of a min heap is not satisfied\n while currentIdx > 0 and heap[currentIdx] < heap[parentIdx]:\n self.swap(currentIdx, parentIdx, heap)\n currentIdx = parentIdx # now sets current index to parent index and goes up\n parentIdx = (currentIdx - 1) // 2 # Finds new parent index\n \n # Returns root node of the heap\n def peak(self):\n return self.heap[0]\n # Functionality for removing the ROOT node of the heap, good for keeping track of greatst or smallest value\n def remove(self):\n # Swap first index to last index\n swap(0, len(self.heap)-1, self.heap)\n # Now pop the last value, which is our root and remove it\n valueToRemove = self.heap.pop()\n # Sifting value that we swapped down to correct position\n self.siftDown(0, len(self.heap)-1, self.heap)\n return valueToRemove\n # Functionality for inserting a node in the heap\n # WHat we do is add that value to last index of heap\n # Now since that value isn't neccessarily in place, we need to make heap satisfy heap property\n # So we need to sift it up to the correct position\n # This method swaps the node with its parent until satisfies property\n def insert(self, value):\n # so append value to end of heap\n self.heap.append(value)\n # Now sift that value up\n self.siftUp(len(self.heap) - 1, self.heap)\n\n # function to swap indeces\n def swap(self, i,j, heap):\n heap[i], heap[j] = heap[j], heap[i]\n","sub_path":"Python/BreadAndButter/minMaxHeap.py","file_name":"minMaxHeap.py","file_ext":"py","file_size_in_byte":4133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"350934662","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\n\nclass Visualizer:\n\n def __init__(self, prob_num, arr, local_max_seg, kadane_arr):\n self.prob_num = prob_num\n self.ans = None\n self.max = None\n self.N = len(arr)\n self.arr = arr\n self.arr_inv = [ -n for n in arr ]\n self.local_max_seg = local_max_seg\n self.local_wrap_seg = []\n self.kadane_arr = kadane_arr\n self.kadane_wrap_arr = [''] * self.N\n self.fontsize = 14\n self.plot_offset = 0.027\n\n def draw(self):\n self.set_plot()\n self.set_ax1()\n self.set_ax2()\n self.set_ax3()\n plt.show()\n\n def set_plot(self):\n fig = plt.figure(figsize=(14, 10))\n gs = mpl.gridspec.GridSpec(2, 2, height_ratios=[3,1])\n ax1 = fig.add_subplot(gs[0])\n ax2 = fig.add_subplot(gs[1])\n ax3 = fig.add_subplot(gs[2:])\n fig.suptitle(f'918. Maximum Sum Circular Subarray - Problem {self.prob_num}',\n size=self.fontsize + 2)\n fig.subplots_adjust(left=0.2)\n self.fig, self.ax1, self.ax2, self.ax3 = fig, ax1, ax2, ax3\n\n def set_ax1(self):\n ax = self.ax1\n self.format_axes(ax)\n ax.plot(range(self.N), self.arr, 'o-', color='magenta')\n\n for x, y in self.local_max_seg:\n x = np.array(x) + self.plot_offset\n y = np.array(y) + self.plot_offset\n ax.plot(x, y, 'go-', )\n\n ax.legend(['Array', 'Local Sum'])\n ax.axhline(color='black', linewidth=0.5)\n table = ax.table(\n cellText=[ ['Ans', self.ans], ['Max', self.max] ],\n bbox=[-0.4, 0.85, 0.25, 0.15]\n )\n table.set_fontsize(self.fontsize)\n for cc in table.get_children():\n cc.set(edgecolor='lightgray')\n\n def set_ax2(self):\n ax = self.ax2\n self.format_axes(ax)\n ax.plot(range(self.N), self.arr_inv, 'o-', color='blue')\n ax.plot(range(self.N), self.arr, 'o--', color='silver')\n\n for x, y in self.local_wrap_seg:\n x = np.array(x) + self.plot_offset\n y = np.array(y) + self.plot_offset\n ax.plot(x, y, 'o-', color='red')\n\n ax.legend(['Array Inverse', 'Array', 'Wrapped Local Sum'])\n ax.axhline(color='black', linewidth=0.5)\n\n def set_ax3(self):\n N = self.N\n w = 'white'\n s = 'palegoldenrod'\n ax = self.ax3\n ax.set_axis_off()\n table = ax.table(\n cellText=[\n self.arr,\n self.arr_inv,\n self.kadane_arr,\n self.kadane_wrap_arr,\n ],\n rowLabels=['Array', 'Array Inverse', 'Kadane', 'Kadane Wrap'],\n colLabels=range(self.N),\n bbox=[0, 0, 1, 1],\n rowColours=[ w, w, s, s ],\n cellColours=[ [w]*N, [w]*N, [s]*N, [s]*N ],\n )\n\n table.set_fontsize(self.fontsize)\n\n for cc in table.get_children():\n cc.set(edgecolor='gray')\n\n def format_axes(self, ax):\n pad = 0.5\n ax.set(xlim=[-pad, self.N - pad], yticks=range(-100, 100, 1), xticks=range(-1, self.N+1))\n ax.grid(linestyle='dotted')\n","sub_path":"Leetcode/max_sum_circular_array/visualizer.py","file_name":"visualizer.py","file_ext":"py","file_size_in_byte":3220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"269758923","text":"# A function must have two blank lines before it\nimport numpy as np\n\n\ndef count_number_of_digits(num):\n '''\n\n :param num: An integer\n :return: The number of digits in the integer\n '''\n\n if (isinstance(num, int)) | (isinstance(num, float)):\n num = abs(int(num))\n\n # if the given number is zero itself, then it has 1 digit\n if num == 0:\n return 1\n\n count = 0\n\n while num > 0:\n num = num // 10\n count += 1\n return count\n else:\n print(f'the given input {num} must be a number')\n\n\ndef is_even(num):\n '''\n\n :param num: A number\n :return: The number is even or not\n '''\n if (isinstance(num, int)) | (isinstance(num, float)):\n if num % 2 == 0:\n return True\n else:\n return False\n else:\n print(f'the given input {num} must be a number')\n\n# x = int(input('please enter a number(integer)'))\n# y = int(input('please enter another number(integer)'))\n\n\ndef gen_int_array(lower_bound, upper_bound, size):\n '''\n\n :param lower_bound: lowest number allowed in the array\n :param upper_bound: biggest number allowed in the array + 1\n :param size: number of elements in the array\n :return: an integer array\n '''\n return list(np.random.randint(low=lower_bound, high=upper_bound, size=size))\n\n\n","sub_path":"standford/basic_finctions.py","file_name":"basic_finctions.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"446985348","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters\nimport logging\nfrom local_settings import BOT_TOKEN\nfrom core.ed_bot import *\n\n# Enable logging\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\nlogger = logging.getLogger(__name__)\n\nCOMMANDS = {\n \"start\": command_start,\n \"contests\": command_contests\n}\n\n\ndef main():\n logger.info('starting telegram updater...')\n updater = Updater(BOT_TOKEN)\n dp = updater.dispatcher\n\n logger.info('add handlers')\n for key, value in COMMANDS.iteritems():\n dp.add_handler(CommandHandler(key, value))\n\n # dp.add_handler(MessageHandler([Filters.text], echo))\n\n dp.add_error_handler(command_error)\n\n updater.start_polling()\n updater.idle()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ed_main.py","file_name":"ed_main.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"361730232","text":"import paho.mqtt.client as mqtt\nfrom hardware import hardware\nfrom datetime import timedelta\nimport time\nimport threading\n\nimport logout\nimport atexit\nimport signal\nimport sys\nfrom scheduler import Schedule\n\nclass hardwareCommunication():\n\n def __init__(self):\n self.msg=''\n self.interval = 0.0\n self.receivedHWCommand = False\n\n # create hardwareInstance\n self.hardware = hardware()\n\n # create and start Threads\n self.runThread = Schedule(interval=timedelta(seconds=self.interval), execute=self.hardwareThread)\n #self.runThread.start()\n\n # mqtt Client\n self.client = mqtt.Client()\n self.client.on_connect = self.on_connect\n self.client.on_message = self.on_message \n\n try:\n self.client.connect(\"localhost\", 1883, 60)\n except Exception as e:\n print(\"connection failed!\")\n exit(1)\n\n self.client.loop_forever()\n\n\n def __del__(self):\n print('ending')\n self.client.disconnect()\n del self.hardware\n\n\n def on_connect(self, client, userdata, flags, rc):\n print(\"Connected with result code \" + str(rc))\n client.subscribe(\"HW/Commands\")\n\n def on_message(self, client, userdata, msg):\n data = msg.payload\n decodedData = data.decode('utf-8')\n\n if decodedData == \"start\":\n print('received Msg: start')\n self.runThread.start()\n self.runThread.do_run = True\n\n elif decodedData == \"stop\":\n print('received Msg: stop')\n self.runThread.do_run = False\n self.runThread.stop()\n\n elif decodedData == \"exit\":\n print('received Msg: exit')\n del self.hardware\n \n elif decodedData == '':\n print('msg empty')\n \n else: \n print('received Msg: A..:..:..')\n self.receivedHWCommand = True\n self.msg = decodedData.replace('A', '').split(':')\n print('')\n\n\n def hardwareThread(self):\n cc = 0\n while getattr(self.runThread, \"do_run\", True):\n cc += 1\n if cc % 100 == 0:\n print('Publishing registers')\n regs = self.hardware.readAddresses(0, 10)\n self.client.publish('HW/Publish', str(regs))\n time.sleep(0.001)\n\n if self.receivedHWCommand == True:\n print('writing bits to hardware')\n ret = self.hardware.writeBits(self.msg)\n print(ret)\n self.receivedHWCommand = False\n \n time.sleep(0.001)\n\nif __name__ == \"__main__\":\n hwComThread = hardwareCommunication()\n\n # except(ProgramKilled):\n # hwComThread.runThread.stop()\n # #hwComThread.messageThread.stop()\n # del hwComThread.hardware\n # print('program exited')\n\n\n# class ProgramKilled(Exception):\n# pass\n\n# def sendMsg():\n# # create client\n# client = mqtt.Client()\n# try:\n# client.connect(\"localhost\", 1883, 60)\n# except Exception as e:\n# print(\"connection failed!\")\n# exit(1)\n# cc = 0\n# timeout = time.time() + 5\n# whiletrue = True \n# while whiletrue:\n# if time.time() < timeout:\n# client.publish('HW/Commands', 'A0:8:' + str(cc), qos=2)\n# client.loop(2, 10)\n# time.sleep(0.002)\n# cc+=1\n# if cc > 127:\n# cc = 0\n\n# else:\n# client.publish('HW/Commands', 'stop')\n# whiletrue = False\n\n# except ProgramKilled:\n# print('runThread stopped')\n# #self.runThread.stop()\n# #cleanup\n# break","sub_path":"hardwareCommunication.py","file_name":"hardwareCommunication.py","file_ext":"py","file_size_in_byte":3258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"518906017","text":"Ekran = \"GELİŞMİŞ HESAP MAKİNESİ\"\r\nprint(\"*\"*len(Ekran), Ekran, \"*\"*len(Ekran), sep=\"\\n\")\r\n\r\nimport math\r\nfrom math import *\r\nimport time\r\nprint(\"\\n\"\"\"\"İŞLEMLER\\n********\r\n1-Toplama (topla)\r\n2-Çıkarma (çıkar)\r\n3-Çarpma (çarp)\r\n4-Bölme (böl)\r\n5-Faktöriyel Bulma (faktöriyel)\r\n6-Karekökünü Bulma (karekök)\r\n7-İki Sayının Logaritmasını Bulma örnek:(25,5) (log) \r\n8-Hipotenüsünü Bulma (pisagor)\r\n\r\nÇıkış (q)\r\n\"\"\")\r\nwhile True:\r\n işlem = input(\"Lütfen İşlemin Kısaltımını Giriniz:\")\r\n if işlem == (\"topla\"):\r\n print(\"Toplama İşlemi Seçildi..\")\r\n time.sleep(1)\r\n toplama1=int(input(\"İlk Sayıyı Giriniz:\"))\r\n toplama2=int(input(\"İlk Sayıyı Giriniz:\"))\r\n print(\"{} sayısı ile {} sayısının toplamı {} dır.\".format(toplama1,toplama2,toplama1+toplama2))\r\n elif işlem == (\"çıkar\"):\r\n print(\"Çıkarma İşlemi Seçildi..\")\r\n time.sleep(1)\r\n çıkarma1=int(input(\"İlk Sayıyı Giriniz:\"))\r\n çıkarma2=int(input(\"İlk Sayıyı Giriniz:\"))\r\n print(\"{} sayısı ile {} sayısının farkı {} dır.\".format(çıkarma1,çıkarma2,çıkarma1-çıkarma2))\r\n elif işlem == (\"çarp\"):\r\n print(\"Çarpma İşlemi Seçildi..\")\r\n time.sleep(1)\r\n çarpma1=int(input(\"İlk Sayıyı Giriniz:\"))\r\n çarpma2=int(input(\"İlk Sayıyı Giriniz:\"))\r\n print(\"{} sayısı ile {} sayısının çarpımı {} dır.\".format(çarpma1,çarpma2,çarpma1*çarpma2))\r\n elif işlem == (\"böl\"):\r\n print(\"Bölme İşlemi Seçildi..\")\r\n time.sleep(1)\r\n bölme1=int(input(\"İlk Sayıyı Giriniz:\"))\r\n bölme2=int(input(\"İlk Sayıyı Giriniz:\"))\r\n print(\"{} sayısının {} sayısına bölümü {} dır.\".format(bölme1,bölme2,bölme1/bölme2))\r\n elif işlem ==(\"faktöriyel\"):\r\n print(\"Faktöriyel Bulma İşlemi Seçildi..\")\r\n time.sleep(1)\r\n faktöriyel=int(input(\"Faktöriyelini Alacağınız Sayıyı Giriniz:\"))\r\n factorial(faktöriyel)\r\n print(\"{} sayısının faktöriyeli {} sayısıdır.\".format(faktöriyel,factorial(faktöriyel)))\r\n elif işlem == (\"karekök\"):\r\n print(\"Karekökünü Bulma İşlemi Seçildi..\")\r\n time.sleep(1)\r\n karekök=int(input(\"Karekökünü Alacağınız Sayıyı Giriniz:\"))\r\n sqrt(karekök)\r\n print(\"{} sayısının karekökü {} sayısıdır.\".format(karekök,sqrt(karekök)))\r\n elif işlem == (\"log\"):\r\n print(\"İki Sayının Logaritmasını Bulma İşlemi Seçildi..\")\r\n time.sleep(1)\r\n logaritma1=int(input(\"Birinci Değeri Giriniz:\"))\r\n logaritma2=int(input(\"İkinci Değeri Giriniz:\"))\r\n log(logaritma1,logaritma2)\r\n print(\"Birinci değerin ikinci değere göre logaritması ({},{}) = {} dır.\".format(logaritma1,logaritma2,log(logaritma1,logaritma2)))\r\n elif işlem == (\"pisagor\"):\r\n print(\"Hipotenüsünü Bulma İşlemi Seçildi..\")\r\n time.sleep(1)\r\n pisagor1=int(input(\"İlk Değeri Giriniz:\"))\r\n pisagor2=int(input(\"İkinci Değeri Giriniz:\"))\r\n hypot(pisagor1,pisagor2)\r\n print(\"İlk değeri {} ,İkinci değeri {} olan iki sayının Hipotenüsü {} dir\".format(pisagor1,pisagor2,hypot(pisagor1,pisagor2)))\r\n else:\r\n işlem == \"q\"\r\n print(\"Programdan Sonlandırılıyor...\")\r\n time.sleep(2)\r\n print(\"Programdan Sonlandırıldı...\")\r\n break\r\n","sub_path":"Gelişmiş Hesap Makinesi.py","file_name":"Gelişmiş Hesap Makinesi.py","file_ext":"py","file_size_in_byte":3787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"44238977","text":"from django.shortcuts import render, redirect\n\n# Create your views here.\nfrom django.urls import reverse\nfrom django.views import View\nfrom .models import Info\n\n\nclass IndexView(View):\n def get(self, request):\n print('### IndexView_get #######################')\n return render(request, 'collect_info.html')\n\n def post(self, request):\n print('### IndexView_post #######################')\n name = request.POST.get('name')\n age = request.POST.get('age')\n gender = request.POST.get('gender')\n student = Info()\n print('### name :', name)\n print('### gender :', gender)\n print('### age :', age)\n student.name = name\n student.age = age\n student.gender = gender\n student.save()\n return redirect(reverse('show'))\n\n\nclass ShowInfo(View):\n def get(self, request):\n print('### ShowInfo_get #######################')\n infos = Info.objects.all()\n print('### infos:', infos)\n return render(request, 'show_info.html', {'infos': infos})\n\n def post(self, request):\n pass\n","sub_path":"django_test/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"440016343","text":"#-------------------------------------------------------------------------------\r\n# Name: umgdy-ab-batch-profiling, part 2: 2-txtToPlots\r\n# Author: Alicja Byzdra\r\n# Created: 13-02-2017\r\n# Copyright: (c) Alicja Byzdra 2017\r\n# Institution: UMGDY, University of Gdansk\r\n#-------------------------------------------------------------------------------\r\n\r\n#-*- coding: utf-8 -*-\r\n\r\n\r\nimport arcpy\r\nimport numpy as np\r\nfrom matplotlib.backends.backend_pdf import PdfPages\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib\r\nfrom matplotlib.path import Path\r\nimport matplotlib.patches as patches\r\nfrom datetime import datetime\r\nimport os\r\n\r\n################## PARAMETERS ####################################################################\r\ndir = arcpy.GetParameterAsText(0)\r\nName_PDF = arcpy.GetParameterAsText(1)\r\n\r\nOutput_folder = arcpy.GetParameterAsText(2)\r\nif Output_folder is None:\r\n Output_folder = dir\r\n\r\ntry:\r\n userMinX=int(arcpy.GetParameterAsText(3))\r\nexcept:\r\n userMinX=\"#\"\r\n\r\ntry:\r\n userMaxX=int(arcpy.GetParameterAsText(4))\r\nexcept:\r\n userMaxX=\"#\"\r\n\r\ntry:\r\n userMinY=int(arcpy.GetParameterAsText(5))\r\nexcept:\r\n userMinY=\"#\"\r\n\r\ntry:\r\n userMaxY=int(arcpy.GetParameterAsText(6))\r\nexcept:\r\n userMaxY=\"#\"\r\n\r\npdfTitle=arcpy.GetParameterAsText(7)\r\n\r\nuserColormap=arcpy.GetParameterAsText(8)\r\n\r\nlineWidth=1.5\r\npatchColor=\"#C2DFFF\" #blue patch\r\nuserXLabel=\"miara biezaca [m]\"\r\nuserYLabel=\"h [m]\"\r\n\r\n#COLORMAPS NAMES ARE DESCRIBED ON THE FOLLOWING WEBSITE:\r\n#https://matplotlib.org/examples/color/colormaps_reference.html\r\n\r\n\r\n################## CURRENT DATE ##################################################################\r\ncurrentDate = str(datetime.now())\r\ncurrentDate = currentDate[:10]\r\n\r\n\r\n################## CREATE MULTIPAGE PDF ##########################################################\r\npdf = PdfPages(Output_folder + \"\\\\\" + Name_PDF + \".pdf\")\r\n\r\n\r\n################## COLLECT PTXT FILES PATHS ######################################################\r\ndirs = [x[0] for x in os.walk(dir)]\r\nfilesPtxt = [x[2] for x in os.walk(dir)]\r\nfilesPaths = []\r\nfor d in range(len(dirs)):\r\n if filesPtxt[d]:\r\n for fil in filesPtxt[d]:\r\n filesPaths.append(dirs[d] + \"\\\\\" + fil)\r\n\r\n\r\n################## COLLECT LINE_IDs, ALLHEIGHTS, ALLDISTANCES ####################################\r\nallHeights=[]\r\nallDistances=[]\r\nallLineIds=[]\r\n\r\nfor f in filesPaths:\r\n with open(f) as txtFile:\r\n for line in txtFile:\r\n if line[0]==\"#\":\r\n line=line.split(\":\")\r\n if line[0]==\"#Line_id\":\r\n line=line[1]\r\n if line[0]==\" \":\r\n line=line[1:-1]\r\n allLineIds.append(line)\r\n else:\r\n line=line.split()\r\n allHeights.append(float(line[1]))\r\n allDistances.append(float(line[2]))\r\n txtFile.close()\r\nallLineIds=sorted(list(set(allLineIds)))\r\n\r\n\r\n################## COLLECT LINE_IDs, ALLHEIGHTS, ALLDISTANCES ####################################\r\nfor ID in allLineIds:\r\n fig=plt.figure(figsize=(15,10))\r\n fig.suptitle(pdfTitle, fontsize=14, verticalalignment=\"top\", fontweight='bold')\r\n\r\n plt.figtext(0.855, 0.04, 'Data wydruku: '+currentDate, fontsize=10, color=\"grey\")\r\n plt.figtext(0.610, 0.025, u'Wydruk z programu umgdy-ab-batch-profiling, bedacego praca dyplomowa Alicji Byzdra', fontsize=9, color=\"grey\")\r\n plt.figtext(0.558, 0.01, u'Studia podyplomowe \"GIS - System Informacji Geograficznej\" (edycja 2016/17), Uniwersytet Gdanski', fontsize=9, color=\"grey\")\r\n\r\n plt.title(ID)\r\n ax = fig.add_subplot(111)\r\n cmap = matplotlib.cm.get_cmap(userColormap)\r\n\r\n heightsPlot=[]\r\n distancesPlot=[]\r\n datesPlot=[]\r\n\r\n for f in filesPaths:\r\n with open(f) as txtFile:\r\n distHeight={}\r\n for line in txtFile:\r\n if line[0]==\"#\":\r\n line=line.split(\":\")\r\n if line[0]==\"#Date\":\r\n line=line[1]\r\n if line[0]==\" \":\r\n lDate=line[1:-1]\r\n else:\r\n lDate=line[:-1]\r\n if line[0]==\"#Line_id\":\r\n line=line[1]\r\n if line[0]==\" \":\r\n lID=line[1:-1]\r\n else:\r\n lID=line[:-1]\r\n else:\r\n if lID==ID:\r\n line=line.split()\r\n distHeight[float(line[2])]=float(line[1])\r\n txtFile.close()\r\n if lID==ID:\r\n distances=sorted(distHeight.keys())\r\n heights=[distHeight[d] for d in distances]\r\n heightsPlot.append(heights)\r\n distancesPlot.append(distances)\r\n datesPlot.append(lDate)\r\n num=len(datesPlot)\r\n for nr in range(num):\r\n heights=heightsPlot[nr]\r\n distances=distancesPlot[nr]\r\n date=datesPlot[nr]\r\n\r\n if num==1:\r\n c = cmap(float(nr)/(num))\r\n else:\r\n c = cmap(float(nr)/(num-1))\r\n line, = plt.plot(distances,heights,label=date,linewidth=lineWidth,color=c)\r\n line.set_label(date)\r\n\r\n belowZeroHeights=[]\r\n belowZeroDist = []\r\n for h in range(len(heights)):\r\n if heights[h]<=0:\r\n belowZeroHeights.append(heights[h])\r\n belowZeroDist.append(distances[h])\r\n if belowZeroHeights:\r\n verts=[]\r\n codes=[Path.MOVETO]\r\n verts.append((belowZeroDist[0],0))\r\n codes.append(Path.LINETO)\r\n for v in range(len(belowZeroHeights)):\r\n verts.append((belowZeroDist[v],belowZeroHeights[v]))\r\n codes.append(Path.LINETO)\r\n if userMaxX!=\"#\" and userMinX!=\"#\" and userMaxY!=\"#\" and userMinY!=\"#\":\r\n verts.append((userMaxX+3,belowZeroHeights[-1]))\r\n codes.append(Path.LINETO)\r\n verts.append((userMaxX+3,0))\r\n verts.append((belowZeroDist[0],0))\r\n codes.append(Path.CLOSEPOLY)\r\n path = Path(verts, codes)\r\n else:\r\n maxDist=int(max(allDistances))+2\r\n verts.append((maxDist+3,belowZeroHeights[-1]))\r\n codes.append(Path.LINETO)\r\n verts.append((maxDist+3,0))\r\n verts.append((belowZeroDist[0],0))\r\n codes.append(Path.CLOSEPOLY)\r\n path = Path(verts, codes)\r\n patch = patches.PathPatch(path, facecolor=patchColor, lw=0)\r\n ax.add_patch(patch)\r\n\r\n plt.legend(loc=1, frameon=True, fontsize=11)\r\n if userMaxX!=\"#\" and userMinX!=\"#\" and userMaxY!=\"#\" and userMinY!=\"#\":\r\n maxDist = userMaxX\r\n minDist = userMinX\r\n maxHeight = userMaxY\r\n minHeight = userMinY\r\n\r\n ############### AUTOMATIC STEP - GRID #######################################\r\n okY=0\r\n divY=20.0\r\n while okY!=1:\r\n if (int(maxHeight)-int(minHeight))%divY==0:\r\n okY=1\r\n else:\r\n divY+=1\r\n stepY=int((int(maxHeight)-int(minHeight))/divY)\r\n\r\n\r\n okX=0\r\n divX=25.0\r\n while okX!=1:\r\n if (int(maxDist)-int(minDist))%divX==0:\r\n okX=1\r\n else:\r\n divX+=1\r\n stepX=int((int(maxDist)-int(minDist))/divX)\r\n\r\n plt.xlim(minDist, maxDist)\r\n plt.ylim(minHeight, maxHeight)\r\n\r\n plt.xticks(range(minDist,maxDist,stepX))\r\n\r\n plt.yticks(range(minHeight,maxHeight,stepY))\r\n ax=plt.gca()\r\n ax.grid(which='major', axis='x', linewidth=0.75, linestyle='-', color='0.75')\r\n ax.grid(which='minor', axis='x', linewidth=0.25, linestyle='-', color='0.75')\r\n ax.grid(which='major', axis='y', linewidth=0.75, linestyle='-', color='0.75')\r\n ax.grid(which='minor', axis='y', linewidth=0.25, linestyle='-', color='0.75')\r\n plt.axhline(0, color='0.4', linewidth=1, zorder=20)\r\n plt.axvline(0, color='0.4', linewidth=1, zorder=20)\r\n plt.xlabel(userXLabel) #\"miara biezaca [m]\"\r\n plt.ylabel(userYLabel) #\"h [m]\"\r\n plt.tight_layout()\r\n plt.subplots_adjust(top=0.93, bottom=0.096)\r\n\r\n\r\n else:\r\n maxDist=int(max(allDistances))\r\n minDist=int(min(allDistances))\r\n while (maxDist-minDist)%4.0!=0:\r\n maxDist+=1\r\n minHeight=int(min(allHeights))\r\n maxHeight=int(max(allHeights))\r\n if (maxHeight-minHeight)%2.0==0:\r\n maxHeight+=1\r\n\r\n ############### AUTOMATIC STEP - GRID #######################################\r\n okY=0\r\n divY=10.0\r\n while okY!=1:\r\n if (float(int(maxHeight)-int(minHeight)))%divY==0:\r\n okY=1\r\n else:\r\n divY+=1\r\n stepY=int(float((int(maxHeight)-int(minHeight)))/divY)\r\n\r\n\r\n okX=0\r\n divX=15.0\r\n while okX!=1:\r\n if (float(int(maxDist)-int(minDist)))%divX==0:\r\n okX=1\r\n else:\r\n divX+=1\r\n stepX=int(float((int(maxDist)-int(minDist)))/divX)\r\n\r\n\r\n plt.xlim(minDist-1, maxDist+2)\r\n plt.ylim(minHeight-1, maxHeight+2)\r\n plt.xticks(range(minDist,maxDist+2,stepX))\r\n\r\n plt.yticks(range(minHeight-1,maxHeight+2,stepY))\r\n ax=plt.gca()\r\n ax.grid(which='major', axis='x', linewidth=0.75, linestyle='-', color='0.75')\r\n ax.grid(which='minor', axis='x', linewidth=0.25, linestyle='-', color='0.75')\r\n ax.grid(which='major', axis='y', linewidth=0.75, linestyle='-', color='0.75')\r\n ax.grid(which='minor', axis='y', linewidth=0.25, linestyle='-', color='0.75')\r\n plt.axhline(0, color='0.4', linewidth=1, zorder=20)\r\n plt.axvline(0, color='0.4', linewidth=1, zorder=20)\r\n plt.xlabel(userXLabel)\r\n plt.ylabel(userYLabel)\r\n plt.tight_layout()\r\n plt.subplots_adjust(top=0.93, bottom=0.096)\r\n\r\n pdf.savefig(fig)\r\npdf.close()\r\nplt.close('all')\r\n\r\n","sub_path":"umgdy-ab-batch-profiling/scripts/2-txtToPlots-ARCGIS.py","file_name":"2-txtToPlots-ARCGIS.py","file_ext":"py","file_size_in_byte":10148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"417004198","text":"#!/usr/local/anaconda/bin/python\n\nimport sys, math\nfrom pathlib import Path\n\nimport pandas as pd\n\nsys.path.insert(0, '/home/paperspace/train_data_v94/python/pysimple')\nfrom pysimple.io import from_tsv, to_tsv\n\n\nDATA_DIR = Path('/home/paperspace/train_data_v94/__SPLIT__/mx')\nDATA_PATH = DATA_DIR / 'data.tsv'\nSPLIT = 0.6\n\ndata = from_tsv(filepath=DATA_PATH, report=print)\ndata = data.astype({'label': int})\n\ntrain_data = []\nvalid_data = []\n\nfor query, query_data in data.groupby('query'):\n query_data_0 = query_data[query_data['label'].eq(0)]\n query_data_1 = query_data[query_data['label'].eq(1)]\n \n s = math.ceil(query_data_0.shape[0] * SPLIT)\n train_data.append(query_data_0.iloc[:s])\n valid_data.append(query_data_0.iloc[s:])\n \n s = math.ceil(query_data_1.shape[0] * SPLIT)\n train_data.append(query_data_1.iloc[:s])\n valid_data.append(query_data_1.iloc[s:])\n\ntrain_data = pd.concat(train_data)\nvalid_data = pd.concat(valid_data)\n\nto_tsv(filepath=DATA_DIR / 'train.tsv', data=train_data, report=print)\nto_tsv(filepath=DATA_DIR / 'valid.tsv', data=valid_data, report=print)\n","sub_path":"pyaltum/lstm2/train_valid_split.py","file_name":"train_valid_split.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"635635845","text":"import json\nimport gspread\n#from oauth2client.client import SignedJwtAssertionCredentials # deprecated\n#from oauth2client.service_account import ServiceAccountCredentials\nfrom google.oauth2 import service_account\nfrom google.auth.transport.requests import AuthorizedSession\n\n\n# JSON credential files downloaded from google service (user responsible for store it securely)\n#json_key = json.load(open('bionic-trilogy-248914-95046f556068.json'))\n#scope = ['https://spreadsheets.google.com/feeds'] \nscope = ['https://www.googleapis.com/auth/spreadsheets.readonly',\\\n 'https://www.googleapis.com/auth/drive']\n#credentials = SignedJwtAssertionCredentials(\\\n# json_key['client_email'], json_key['private_key'], scope)\n#credentials = ServiceAccountCredentials.from_json_keyfile_name(\\\n# 'dataviz-248918-a811120998f8.json', scope)\ncredentials = service_account.Credentials.from_service_account_file('dataviz-248918-a811120998f8.json')\nscoped_credentials = credentials.with_scopes(scope)\n\n#gc = gspread.authorize(credentials) # NOT SUPPORT google-auth\ngc = gspread.Client(auth=scoped_credentials)\ngc.session = AuthorizedSession(scoped_credentials)\nprint(\"authorized\")\nss = gc.open('bank_info') # open spreadsheet by name share with client-email before open\nworksheet_list = ss.worksheets()\nfor worksheet in worksheet_list:\n print(worksheet)\nws = ss.worksheet('广东发展银行')\nfor location in ws.col_values(2):\n print(location)\n\n\n\n","sub_path":"GettingDataOfftheWeb/google_spreadsheet_api.py","file_name":"google_spreadsheet_api.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"36434802","text":"# Volume and surface area of a box\nstop = False\nwhile(not stop):\n print(\"You will be asked for the dimensions of your box.\")\n print(\"If you would like to stop this process, input 0 for any\" \\\n + \" of the dimensions.\")\n length = float(input(\"Please input the length of the box: \"))\n width = float(input(\"Please input the width of the box: \"))\n height = float(input(\"Please input the height of the box: \"))\n if length == 0 or width == 0 or height == 0:\n print(\"Thanks for using this calculator!\")\n stop = True;\n else:\n volume = length * width * height\n surface_area = (((length + width) * height) + (length * width)) * 2\n print(\"Volume is\", volume)\n print(\"Surface area is\", surface_area, \"\\n\\n\")\n","sub_path":"Loop Box Condition.py","file_name":"Loop Box Condition.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"270114432","text":"'''\n7/27/2018\ncreate fore leg set up\n\n'''\nfrom maya import cmds\n\nimport joint_utility as ju\nreload(ju)\nimport control_utility as cu\nreload(cu)\nimport math_utility as mu\nreload(mu)\n\nfrom shape_data import ctrlColor\n\nfrom leg_rig import legRig\nfrom hindLeg_rig import hindLegRig\n\n\nclass foreLegRig(hindLegRig):\n def __init__(self, side=\"LF\", index=1, alias=\"ForeLeg\", aliasList=[\"Hip\", \"Knee\", \"Ankle\", \"Foot\", \"Knuckle\", \"Toe\"], par=\"MD_Torso_01_Chest_Ctrl\", parJnt=\"MD_Torso_01_Chest_Ctrl_Out_Jnt\", \n ik=True, fk=True, stretch=True, squeeze=True, localScale=False, elbowLock=True, softIK=True, autoSmooth=True, bendy=(5, 5, 0),\n ikSpace=[\"World\", \"Master_Sub_Ctrl\", \"COG_Sub_Ctrl\"], pvSpace=[\"World\", \"Master_Sub_Ctrl\", \"COG_Sub_Ctrl\"], shortFoot=False):\n \n super(foreLegRig, self).__init__(side=side, index=index, alias=alias, aliasList=aliasList, par=par, parJnt=parJnt, ik=ik, fk=fk, stretch=stretch, squeeze=squeeze, localScale=localScale,\n elbowLock=elbowLock, softIK=softIK, autoSmooth=autoSmooth, bendy=bendy, ikSpace=ikSpace, pvSpace=pvSpace, shortFoot=shortFoot)\n\n #the initial ik fk status\n self.ikFk = 1 #as ik\n self.ikMatchCoordinate = True #whether to have the ik ctrl match the world coordinate\n\n self.proxyJnts.extend([\"{0}_Scapula_Proxy_Jnt\".format(self.longAlias), \"{0}_Scapula_Top_Proxy_Jnt\".format(self.longAlias), \"{0}_Scapula_Pivot_Proxy_Jnt\".format(self.longAlias)])\n self.proxyCtrls.update({\"Scapula\": \"{0}_Scapula_Proxy_Ctrl\".format(self.longAlias)})\n self.ctrlShape.update({\"Scapula\": {\"shape\": \"cube\", \"ax\": (0, 1, 0), \"p\": (0, 0, 0), \"s\": (0.8, 0.8, 0.8)}})\n\n\n def createProxy(self):\n self.proxyJnts = self.proxyJnts[:-3]\n super(foreLegRig, self).createProxy(repositionIK=False)\n self.proxyJnts.extend([\"{0}_Scapula_Proxy_Jnt\".format(self.longAlias), \"{0}_Scapula_Top_Proxy_Jnt\".format(self.longAlias), \"{0}_Scapula_Pivot_Proxy_Jnt\".format(self.longAlias)])\n \n #reset initial pose\n cmds.move(self.negDic[self.side]*2.5, 11, 5.5, self.proxyJnts[0], a=True)\n cmds.move(self.negDic[self.side]*5, 0, 0, self.proxyJnts[1], a=True, ls=True)\n cmds.move(self.negDic[self.side]*5, 0, 0, self.proxyJnts[2], a=True, ls=True)\n cmds.move(self.negDic[self.side]*2, 0, 0.6, self.proxyJnts[3], a=True, ls=True)\n cmds.move(self.negDic[self.side]*2, 0, -0.3, self.proxyJnts[4], a=True, os=True)\n\n cmds.rotate(0, 30*self.negDic[self.side], -90*self.negDic[self.side], self.proxyJnts[0], a=True, os=True)\n cmds.rotate(0, -60*self.negDic[self.side], 0, self.proxyJnts[1], a=True, os=True)\n cmds.rotate(0, 30*self.negDic[self.side], 0, self.proxyJnts[2], a=True, os=True)\n cmds.rotate(0, -90*self.negDic[self.side], 0, self.proxyJnts[3], a=True, os=True)\n\n cmds.xform(self.proxyCtrls[\"IKTilt\"], t=(self.negDic[self.side]*2.34, 0, 4.3), ro=(0, 0, 0), a=True, os=True)\n cmds.xform(self.proxyCtrls[\"IKTilt2\"], t=(self.negDic[self.side]*2.34, 0, 0.15), ro=(0, 0, 0), a=True, os=True)\n\n cmds.setAttr(\"{0}.ty\".format(self.proxyCtrls[\"PV\"]), 6)\n cmds.setAttr(\"{0}.tz\".format(self.proxyCtrls[\"FootIK\"]), -1.5)\n cmds.setAttr(\"{0}.tz\".format(self.proxyCtrls[\"ToeIK\"]), 1.5)\n\n #add scapula joint\n cmds.select(self.proxyJnts[0], r=True)\n scapulaJnt = self.proxyJnts[-3]\n cmds.joint(n=scapulaJnt, p=(0, 0, 0), rad=0.5, r=True)\n cu.lockAttr(scapulaJnt, [\"t\", \"s\", \"v\"])\n cmds.setAttr(\"{0}.r\".format(scapulaJnt), -45, 0, 90*self.negDic[self.side], type=\"double3\")\n\n endJnt = self.proxyJnts[-2]\n cmds.joint(n=endJnt, p=(0, 3, 0), rad=0.5, r=True)\n cu.lockAttr(endJnt, [\"tx\", \"tz\", \"r\", \"s\", \"v\"])\n\n pivotJntGrp = cmds.group(n=\"{0}_Grp\".format(self.proxyJnts[-1]), em=True, p=self.proxyGrp)\n pivotJnt = cmds.joint(n=self.proxyJnts[-1], rad=0.5, p=(-4.5*self.negDic[self.side], 1.2, 0), r=True)\n cu.lockAttr(pivotJnt, [\"r\", \"s\", \"v\"])\n cmds.pointConstraint(scapulaJnt, endJnt, pivotJntGrp, mo=False)\n cmds.orientConstraint(scapulaJnt, pivotJntGrp, mo=False)\n\n ploy = cu.createPloy(n=\"{0}_Scapula_Proxy_Poly\".format(self.longAlias), posList=[scapulaJnt, endJnt, pivotJnt], attach=True)\n cu.setCtrlColor(ploy, 30)\n cmds.setAttr(\"{0}.inheritsTransform\".format(ploy), 0)\n cmds.parent(ploy, self.proxyGrp)\n\n #create Scapula proxy ctrl\n cu.createCtrl(n=self.proxyCtrls[\"Scapula\"], colorNo=self.colorDic[self.side], ctrlShape=self.ctrlShape[\"Scapula\"], depth=1, lockAttrs=[\"t\", \"r\", \"s\", \"v\"])\n cmds.parent(\"{0}_Grp\".format(self.proxyCtrls[\"Scapula\"]), self.proxyGrp)\n cmds.parentConstraint(endJnt, \"{0}_Grp\".format(self.proxyCtrls[\"Scapula\"]), mo=False)\n\n return True\n\n def copyCleanJointsChain(self, alias=\"Jnt\"):\n '''\n ducplicate the proxy chain, auto orient it and freeze the tranfrom\n overwrite this part from limbRig object\n input:\n alias(string): the new name alisa for the duplicated joint chain\n '''\n #create a bind joint chain\n jnts = ju.copyJointChain(self.proxyJnts[:-3], oldAlias=\"Proxy_Jnt\", newAlias=alias, freeze=False)\n\n aimAxisDic = {self.left : \"x\", self.right: \"-x\"}\n sideAxisDic = {self.left : \"y\", self.right: \"-y\"}\n ju.orientJointChain(jnts, aimAxis=aimAxisDic[self.side], sideAxis=sideAxisDic[self.side])\n\n #set prefered angle\n cmds.setAttr(\"{0}.preferredAngleY\".format(jnts[1]), self.negDic[self.side]*-10)\n\n [cmds.setAttr(\"{0}.segmentScaleCompensate\".format(jnt), 0) for jnt in jnts]\n return jnts\n\n def createRig(self):\n if not super(foreLegRig, self).createRig():\n return False\n #add shoulder set up\n scapulaJnts = ju.copyJointChain(reversed(self.proxyJnts[-3:]), oldAlias=\"Proxy_Jnt\", newAlias=\"Jnt\", freeze=False)\n\n aimAxisDic = {self.left : \"x\", self.right: \"-x\"}\n sideAxisDic = {self.left : \"y\", self.right: \"-y\"}\n ju.orientJointChain(scapulaJnts, aimAxis=aimAxisDic[self.side], upAxis=sideAxisDic[self.side])\n\n #set prefered angle\n cmds.setAttr(\"{0}.preferredAngleY\".format(scapulaJnts[1]), -10)\n [cmds.setAttr(\"{0}.segmentScaleCompensate\".format(jnt), 0) for jnt in scapulaJnts]\n\n scapulaJntGrp = cu.addGroup(scapulaJnts[0], depth=1)\n cmds.parent(scapulaJntGrp, self.main)\n cmds.setAttr(\"{0}.v\".format(scapulaJntGrp), 0)\n\n self.bindJnts.insert(0, scapulaJnts[2])\n self.bindJnts.insert(0, scapulaJnts[1])\n [ju.labelJoint(jnt, displayAxis=True) for jnt in scapulaJnts[1:]]\n [ju.setJoint(jnt) for jnt in scapulaJnts[1:]]\n\n #create IK handle for scapula joint chain\n self.scapulaIkHandle = cmds.ikHandle(n=\"{0}_Scapula_IK_IKHandle\".format(self.longAlias), startJoint=scapulaJnts[0], endEffector=scapulaJnts[2], solver=\"ikRPsolver\")[0]\n cmds.parent(self.scapulaIkHandle, self.ctrls[\"Master\"])\n cmds.setAttr(\"{0}.v\".format(self.scapulaIkHandle), 0)\n\n self.ctrls[\"Scapula\"] = \"{0}_Scapula_Ctrl\".format(self.longAlias)\n cu.createCtrlFromProxy(n=self.ctrls[\"Scapula\"], depth=2, lockAttrs=[\"s\", \"v\"], colorNo=self.colorDic[self.side], pSet=\"default\", posObj=self.proxyJnts[-2])\n cmds.connectAttr(\"{0}.ty\".format(self.ctrls[\"Master\"]), \"{0}_02_Grp.ty\".format(self.ctrls[\"Scapula\"]))\n cmds.poleVectorConstraint(self.ctrls[\"Scapula\"], self.scapulaIkHandle)\n cmds.parent(\"{0}_Grp\".format(self.ctrls[\"Scapula\"]), self.main)\n\n #set for the right local scale for scapula joint\n scle02Null = cmds.group(em=True, n=\"{0}_Scale_02_Null\".format(self.longAlias), p=self.deformerGrp)\n cmds.scaleConstraint(self.topGrp, scle02Null, mo=False)\n \n #add scapular stretch feature\n cmds.addAttr(self.ctrls[\"Scapula\"], ln=\"stretch\", at=\"double\", dv=0, min=0, max=1, k=True)\n scapula01DB = cmds.createNode(\"distanceBetween\", n=\"{0}_Scapula_01_DB\".format(self.longAlias))\n scapula02DB = cmds.createNode(\"distanceBetween\", n=\"{0}_Scapula_02_DB\".format(self.longAlias))\n\n cmds.connectAttr(\"{0}.worldMatrix[0]\".format(scapulaJntGrp), \"{0}.inMatrix1\".format(scapula01DB))\n cmds.connectAttr(\"{0}.worldMatrix[0]\".format(self.ctrls[\"Scapula\"]), \"{0}.inMatrix2\".format(scapula01DB))\n cmds.connectAttr(\"{0}.worldMatrix[0]\".format(self.ctrls[\"Scapula\"]), \"{0}.inMatrix1\".format(scapula02DB))\n cmds.connectAttr(\"{0}.worldMatrix[0]\".format(self.mainGrp), \"{0}.inMatrix2\".format(scapula02DB))\n\n scaleMD = cmds.createNode(\"multiplyDivide\", n=\"{0}_Scapula_Scale_01_MD\".format(self.longAlias))\n cmds.connectAttr(\"{0}.distance\".format(scapula01DB), \"{0}.input1X\".format(scaleMD))\n cmds.connectAttr(\"{0}.distance\".format(scapula02DB), \"{0}.input1Y\".format(scaleMD))\n\n cmds.setAttr(\"{0}.operation\".format(scaleMD), 2)\n cmds.connectAttr(\"{0}.sx\".format(scle02Null), \"{0}.input2X\".format(scaleMD))\n cmds.connectAttr(\"{0}.sx\".format(scle02Null), \"{0}.input2Y\".format(scaleMD))\n\n upLength = cmds.getAttr(\"{0}.tx\".format(scapulaJnts[1]))\n lowLength = cmds.getAttr(\"{0}.tx\".format(scapulaJnts[2]))\n bc = cmds.createNode(\"blendColors\", n=\"{0}_Scapula_BC\".format(self.longAlias))\n cmds.connectAttr(\"{0}.stretch\".format(self.ctrls[\"Scapula\"]), \"{0}.blender\".format(bc))\n\n if self.side == self.right:\n inverseMD = cmds.createNode(\"multiplyDivide\", n=\"{0}_Scapula_Inverse_02_MD\".format(self.longAlias))\n cmds.connectAttr(\"{0}.outputX\".format(scaleMD), \"{0}.input1X\".format(inverseMD))\n cmds.connectAttr(\"{0}.outputY\".format(scaleMD), \"{0}.input1Y\".format(inverseMD))\n cmds.setAttr(\"{0}.input2X\".format(inverseMD), -1)\n cmds.setAttr(\"{0}.input2Y\".format(inverseMD), -1)\n cmds.connectAttr(\"{0}.outputX\".format(inverseMD), \"{0}.color1R\".format(bc))\n cmds.connectAttr(\"{0}.outputY\".format(inverseMD), \"{0}.color1G\".format(bc))\n else:\n cmds.connectAttr(\"{0}.outputX\".format(scaleMD), \"{0}.color1R\".format(bc))\n cmds.connectAttr(\"{0}.outputY\".format(scaleMD), \"{0}.color1G\".format(bc))\n\n cmds.setAttr(\"{0}.color2R\".format(bc), upLength)\n cmds.setAttr(\"{0}.color2G\".format(bc), lowLength)\n cmds.connectAttr(\"{0}.outputR\".format(bc), \"{0}.tx\".format(scapulaJnts[1]))\n cmds.connectAttr(\"{0}.outputG\".format(bc), \"{0}.tx\".format(scapulaJnts[2]))\n\n #aim constraint the upper arm\n '''\n main02Grp = cmds.group(self.mainGrp, n=self.mainGrp.replace(\"_Grp\", \"_02_Grp\"))\n cmds.xform(main02Grp, rp=(0, 0, 0), sp=(0, 0, 0), a=True, os=True)\n aimVectorDic = {self.left: (-1, 0, 0), self.right: (1, 0, 0)}\n cmds.aimConstraint(scapulaJnts[0], main02Grp, aim=aimVectorDic[self.side], u=(0, 1, 0), wut=\"object\", wuo=self.ctrls[\"Scapula\"], mo=True)\n\n #--\n roPma = cmds.createNode(\"plusMinusAverage\", n=\"{0}_Main_Ro_PMA\".format(self.longAlias))\n cmds.connectAttr(\"{0}.r\".format(self.ctrls[\"Master\"]), \"{0}.input3D[0]\".format(roPma))\n cmds.connectAttr(\"{0}.r\".format(self.ctrls[\"Master2\"]), \"{0}.input3D[1]\".format(roPma))\n cmds.connectAttr(\"{0}.output3D\".format(roPma), \"{0}.r\".format(self.mainGrp))\n\n cmds.orientConstraint(self.mainGrp, scapulaJnts[2], mo=True)\n '''\n return True\n \n def createIK(self):\n # inheret from leg rig and mute from leg rig\n super(foreLegRig, self).createIK(repositionIK=False)\n\n return True \n\n\n\n\n\n\n\n\n","sub_path":"Rig_Module/foreLeg_rig.py","file_name":"foreLeg_rig.py","file_ext":"py","file_size_in_byte":11679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"550918890","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 13 11:56:58 2017\n\n@author: jc3e13\n\"\"\"\n\nimport numpy as np\nimport load_data\nimport gsw\nimport matplotlib.pyplot as plt\n\nmoorings, vmoorings, extras = load_data.load_data(ret_extras=True)\ncc, nw, ne, se, sw = moorings\nnn, ee, ss, ww = vmoorings\nN_levels = extras['N_levels']\n\ndef unit_vector(vector):\n \"\"\" Returns the unit vector of the vector. \"\"\"\n return vector/np.linalg.norm(vector)\n\ndef angle_between(v1, v2):\n \"\"\" Returns the angle in radians between vectors 'v1' and 'v2'::\n\n >>> angle_between((1, 0, 0), (0, 1, 0))\n 1.5707963267948966\n >>> angle_between((1, 0, 0), (1, 0, 0))\n 0.0\n >>> angle_between((1, 0, 0), (-1, 0, 0))\n 3.141592653589793\n \"\"\"\n v1_u = unit_vector(v1)\n v2_u = unit_vector(v2)\n return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))\n\n# %% Create stacked arrays and convert coordinates\nmll = np.stack(([m['lon'] for m in moorings], [m['lat'] for m in moorings]), axis=1)\nvmll = np.stack(([m['lon'] for m in vmoorings], [m['lat'] for m in vmoorings]), axis=1)\nll = np.vstack((mll, vmll))\n\nlllon = ll[:, 0].min()\nlllat = ll[:, 1].min()\nurlon = ll[:, 0].max()\nurlat = ll[:, 1].max()\n\ndlon = urlon - lllon\ndlat = urlat - lllat\ndx_ = np.squeeze(gsw.distance([lllon, urlon], [lllat, lllat])) # dx of box\ndy_ = np.squeeze(gsw.distance([lllon, lllon], [lllat, urlat])) # dy of box\n\nxy = np.zeros_like(ll)\nxy[:, 0] = dx_*(ll[:, 0] - lllon)/dlon\nxy[:, 1] = dy_*(ll[:, 1] - lllat)/dlat\nmxy = xy[:5, :]\nvmxy = xy[5:, :]\n\n# %% Average of four triangles\ndudx1 = np.ma.dstack((nn['dudx_e'], ee['dudx_e'], ss['dudx_e'], ww['dudx_e'])).mean(axis=-1)\ndudy1 = np.ma.dstack((nn['dudy_e'], ee['dudy_e'], ss['dudy_e'], ww['dudy_e'])).mean(axis=-1)\ndvdx1 = np.ma.dstack((nn['dvdx_e'], ee['dvdx_e'], ss['dvdx_e'], ww['dvdx_e'])).mean(axis=-1)\ndvdy1 = np.ma.dstack((nn['dvdy_e'], ee['dvdy_e'], ss['dvdy_e'], ww['dvdy_e'])).mean(axis=-1)\n\n# %% Full cross with averaged velocities.\n# Distances between the east and west (dx) and north and south moorings (dy)\ndew = np.sqrt(np.sum((vmxy[1, :] - vmxy[3, :])**2))\ndns = np.sqrt(np.sum((vmxy[0, :] - vmxy[2, :])**2))\n\ndudx2 = (ee['u_e'] - ww['u_e'])/dew\ndvdx2 = (ee['v_e'] - ww['v_e'])/dew\ndudy2 = (nn['u_e'] - ss['u_e'])/dns\ndvdy2 = (nn['v_e'] - ss['v_e'])/dns\n\n# %% Full cross rotated.\n# Distances between the NE, SW and SE, NW moorings\nrnesw = mxy[2, :] - mxy[4, :]\nrnwse = mxy[1, :] - mxy[3, :]\nthetax = angle_between(rnesw, np.array([1., 0.]))\nthetay = angle_between(rnwse, np.array([0., 1.]))\n# The minus is necessary to make the sense of rotation the right way around\ntheta = -.5*(thetax + thetay)\ndnesw = np.sqrt(np.sum(rnesw**2))\ndnwse = np.sqrt(np.sum(rnwse**2))\n\ndudxp = (ne['u_e'] - sw['u_e'])/dnesw\ndvdxp = (ne['v_e'] - sw['v_e'])/dnesw\ndudyp = (nw['u_e'] - se['u_e'])/dnwse\ndvdyp = (nw['v_e'] - se['v_e'])/dnwse\n\ndudx3 = dudxp*np.cos(theta) + dudyp*np.sin(theta)\ndvdx3 = dvdxp*np.cos(theta) + dvdyp*np.sin(theta)\ndudy3 = -dudxp*np.sin(theta) + dudyp*np.cos(theta)\ndvdy3 = -dvdxp*np.sin(theta) + dvdyp*np.cos(theta)\n\n# %% Plot the comparison\n\nt = cc['tdt64'][:, 0]\n\nfig, axs = plt.subplots(N_levels, 1, sharex=True, sharey=True, figsize=(3, 6))\n\nfor i in range(N_levels):\n axs[i].plot(t, dudy1[:, i])\n axs[i].plot(t, dudy2[:, i])\n axs[i].plot(t, dudy3[:, i])\n\n","sub_path":"scripts/central_derivative_estimates.py","file_name":"central_derivative_estimates.py","file_ext":"py","file_size_in_byte":3386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"367060676","text":"#Chris Conklin 2018-08-30\n#This is a Monte Carlo simulation of the Hardy golf problem\n#with extensions for smart play and a tournament\nimport matplotlib.pyplot as plt\nimport numpy \nimport random\n\n\ndef hole_result(prob):\n score = 0\n remaining = 4\n while remaining > 0:\n score += 1\n p = random.random()\n #Bad shot, continue\n if p < prob:\n continue\n #normal shot, 1 less remaining\n remaining -= 1\n #Excellent shot, 1 more less remaining\n if p > 1-prob:\n remaining -=1\n return score\n\n#returns 1 if p1 beats p2, 0 if tie, and -1 if p2 beats p1\ndef hole_compare(p1,p2):\n r1 = hole_result(p1)\n r2 = hole_result(p2)\n if r1 < r2:\n return 1\n elif r1 == r2:\n return 0\n return -1\n\n# returns tuple with fraction of wins and fraction of losses for p1\ndef compare_average(p1,p2,trials):\n total_wins = 0\n total_losses = 0\n for i in range(trials):\n res = hole_compare(p1,p2)\n if res == 1:\n total_wins += 1\n if res == -1:\n total_losses += 1\n return (total_wins/trials, total_losses/trials)\n\n#now p1 is a tuple\ndef smart_hole_result(p1):\n if type(p1) is not tuple and type(p1) is not list:\n return hole_result(p1)\n score = 0\n remaining = 4\n while remaining > 0:\n score += 1\n p = random.random()\n #Check remaining, if it is just 1, switch to second entry\n if remaining == 1:\n prob = p1[1]\n else:\n prob = p1[0]\n #Bad shot, continue\n if p < prob:\n continue\n #normal shot, 1 less remaining\n remaining -= 1\n #Excellent shot, 1 more less remaining\n if p > 1-prob:\n remaining -=1\n return score\n\n# returns tuple with fraction of wins and fraction of losses for p1\n# now p1 and p2 are tuples with the normal and cautious probabilities\ndef smart_compare(p1,p2):\n r1 = smart_hole_result(p1)\n r2 = smart_hole_result(p2)\n if r1 < r2:\n return 1\n elif r1 == r2:\n return 0\n return -1\n\n#again tuples are needed for smart performance\ndef smart_compare_average(p1,p2,trials):\n total_wins = 0\n total_losses = 0\n for i in range(trials):\n res = smart_compare(p1,p2)\n if res == 1:\n total_wins += 1\n if res == -1:\n total_losses += 1\n return (total_wins/trials, total_losses/trials)\n\n#scoring average, can be smart or dumb dependign on whether prob is a tuple or not\ndef scoring_average(prob, trials):\n total = 0\n for i in range(trials):\n total += smart_hole_result(prob)\n return total/trials\n\ndef smart_rounds(prob,trials):\n rounds = []\n for i in range(trials):\n total = 0\n for j in range(18):\n total += smart_hole_result(prob)\n rounds += [total]\n return rounds\n\n#players is a list of elements of the form (score, (p1,p2)) corresponding to the score and\n#characteristics of each player\ndef tournament_round(players):\n results = []\n for p in players:\n total = p[0]\n for i in range(18):\n total += smart_hole_result(p[1])\n results += [(total,p[1])]\n return results\n\ndef print_results(players):\n players = sorted(players)\n for p in players:\n i = players.index(p)\n if p[0] != players[i-1][0]:\n place = str(i+1)\n print(f'{place}\\t {p}')\n\ndef payments(players, cut_but_paid):\n players = sorted(players)\n payout_fraction = (0.18, 0.108, 0.068,\n 0.048,0.04,0.036,0.0335,0.031,0.029,0.027,\n 0.025,0.023,0.021,0.019,0.018,0.017,0.016,\n 0.015,0.014,0.013,0.012,0.0112,0.0104,0.0096,\n 0.0088,0.008,0.0077,0.0074,0.0071,0.0068,0.0065,\n 0.0062,0.0059,0.00565,0.0054,0.00515,0.0049,\n 0.0047,0.0045,0.0043,0.0041,0.0039,0.0037,\n 0.0035,0.0033,0.0031,0.0029,0.00274,0.0026,\n 0.00252,0.00246,0.0024,0.00236,0.00232,0.0023,\n 0.00228,0.00226,0.00224,0.00222,0.0022,0.00218,\n 0.00216,0.00214,0.00212,0.0021,0.00208,0.00206,\n 0.00204,0.00202,0.002)\n # We determine the places\n payouts = {}\n results = []\n place = 0\n number = 0\n fraction = 0\n j = 0\n for p in players:\n #j = players.index(p) #The issue here is with identical players the index isn't right (grabs the first one)k\n if p[0] != players[j-1][0] and j>0:\n payouts[place]= fraction/number\n place = j\n number = 0\n fraction = 0\n number += 1\n if j<70:\n fraction += payout_fraction[j]\n else:\n fraction += payout_fraction[69]\n if j == len(players)-1:\n payouts[place] = fraction/number\n\n results += [{'player':p, 'place':place}]\n j+=1\n #Next is the cut but paid category, which will get 0.002 each\n if cut_but_paid != []:\n payouts['cut'] = 0.002\n for p in cut_but_paid:\n results += [{'player':p, 'place':'cut'}]\n #Now we must consider if there needs to be a playoff\n if payouts[0] != 0.18:\n p = 1\n while results[p]['place']==0:\n p+=1\n playoff = results[:p]\n #print(f'playoff between {playoff}')\n #Now we have the players, we take them to sudden death\n playoff = [(0,c) for c in playoff]\n while len(playoff)>1:\n for c in playoff:\n playoff = [(smart_hole_result(c[1]['player'][1]),c[1]) for c in playoff]\n #print(playoff)\n for c in playoff:\n if c[0] > min(playoff, key=lambda x: x[0])[0]:\n playoff.remove(c) \n #print(f'Winner is {playoff[0][1]}')\n payouts[1] = (payouts[0]*p-0.18)/(p-1)\n payouts[0] = 0.18\n identified_winner = False\n for itr in range(p):\n if results[itr] != playoff[0][1] or identified_winner:\n results[itr]['place'] = 1\n if results[itr]['place'] == 0:\n identified_winner = True\n #print(payouts)\n for r in results:\n r['payout'] = payouts[r['place']]\n #print(str(r['place'])+'\\t'+str(r['player'])+'\\t'+str(r['payout']))\n #Change player to just have p value\n r['player'] = r['player'][1]\n return results\n\n \n\n\n#Will perform 2 rounds, take the low 70 and ties (unless there are more than 78 who make the cut,\n#in which case there is a complicated tiebreaker) and then do 2 more rounds\n#The tournament will return a list of dicts with the names 'player', 'place', 'payout'\ndef tournament(players):\n #first two rounds\n for i in range(2):\n players = tournament_round(players)\n # print(f'ROUND {i+1}')\n #print_results(players)\n #making the cut\n players = sorted(players)\n cut = 69\n while players[cut+1][0] == players[cut][0]:\n cut += 1\n #must go one more so that the cut represents the actual person cut\n cut += 1\n #this is the weird rule that says that more than 78 players requires a tiebreaker, \n #but the 70 and ties still get paid\n cut_but_paid = []\n cut_not_paid = []\n if cut > 78:\n next_best = 69\n while players[next_best-1][0]==players[next_best][0]:\n next_best -= 1\n cut_not_paid = players[cut:]\n if abs(next_best-69) < abs(cut-69):\n cut_but_paid = players[next_best:cut]\n cut = next_best\n \n else:\n cut_not_paid = players[cut:]\n #print(f'Cut at {players[cut][0]} with player number {cut+1}')\n #print(f'{len(cut_but_paid)} players cut but paid')\n players = players[:cut]\n for i in range(2):\n players = tournament_round(players)\n #print(f'ROUND {i+3}')\n #print_results(players)\n return payments(players,cut_but_paid)+[{'player':p[1],'place':'cut','payout':0} for p in cut_not_paid]\n #print(len(cut_not_paid))\n\n#Class for player prob and result for compiling tournament results\nclass competitor:\n def __init__(self, pval1,pval2=0, e=0, m=0,c=0,w=0):\n self.p1 = pval1\n self.p2 = pval2\n self.events = e\n self.money = m\n self.cuts_made = c\n self.wins = w\n def entered(self):\n self.events+=1\n def made_cut(self):\n self.cuts_made += 1\n def won(self):\n self.wins += 1\n def add(self, newp):\n self.events += newp.events\n self.money += newp.money\n self.cuts_made += newp.cuts_made\n self.wins += newp.wins\n def print(self):\n print(f'{self.p1}\\t{self.p2}\\t{self.events}\\t{self.money}\\t{self.cuts_made}\\t{self.wins}')\n \n\n#Class for list of players\nclass all_players:\n players = []\n def add_player(self,new_p):\n #we either add the data from this player to a previous one or we just add the new player\n for p in self.players:\n if p.p1 == new_p.p1 and p.p2 == new_p.p2:\n p.add(new_p)\n return\n #getting through this means this p value is not in the list\n self.players += [new_p]\n #event_list is a list of tuples of the form ((p1,p2) to go into the tournament\n def tourney(self,event_list):\n results = tournament([(0,p) for p in event_list])\n for r in results:\n p = competitor(r['player'][0],r['player'][1],1,r['payout'])\n if r['place']!='cut':\n p.made_cut()\n if r['place'] == 0:\n p.won()\n self.add_player(p)\n def print(self):\n #print('p1\\tp2\\tevents\\tmoney\\tcuts\\twins')\n for p in self.players:\n p.print()\n def plot_wins(self, show=True):\n res = sorted([(p.p1,p.wins/p.events) for p in self.players])\n plt.plot(*zip(*res),'r-.',label='Wins')\n if show:\n plt.title('Fraction of wins')\n plt.show()\n def plot_cuts(self,show=True):\n res = sorted([(p.p1,p.cuts_made/p.events) for p in self.players])\n plt.plot(*zip(*res),'k-',label='Cuts Made')\n if show:\n plt.title('Fraction of cuts made')\n plt.show()\n def plot_money(self,show=True,purse=1):\n res = sorted([(p.p1,p.money/p.events*purse) for p in self.players])\n plt.plot(*zip(*res),'g--',label='Earnings')\n if show:\n plt.title(f'Season earnings (millions of dollars), ${purse}M total purse' )\n plt.show()\n def plot_all(self):\n self.plot_wins(False)\n self.plot_cuts(False)\n self.plot_money(False)\n plt.legend(loc='best')\n plt.show()\n\n\nplayer_totals = all_players()\nfor i in range(1000000):\n player_totals.tourney([(random.choice(numpy.arange(0,0.10001,0.001)),0) for x in range(156)])\nplayer_totals.print()\nplayer_totals.plot_cuts()\nplayer_totals.plot_wins()\nplayer_totals.plot_money(purse=342)\n\n\n'''\n#Scoring average for smart player with various p values\nmed = []\ntop25 = []\nbot25 = []\nprob_vals = numpy.arange(0.0,0.5,0.01)\nnum_trials = 1000000\nfor p in prob_vals:\n rounds = smart_rounds((p,0),num_trials)\n med += [numpy.median(rounds)]\n top25 += [numpy.percentile(rounds,25)]\n bot25 += [numpy.percentile(rounds,75)]\n\nplt.plot(prob_vals, med, 'k-.', label='Median')\nplt.plot(prob_vals, top25, 'g-', label='25th Percentile')\nplt.plot(prob_vals, bot25, 'r--', label='75th Percentile')\nplt.xlabel('Probability $p$ of hitting an excellent or bad shot')\nplt.ylabel('Round Score')\nplt.title('Scoring vs Consistency')\nplt.legend(loc='best')\nplt.savefig('HardyScoring.jpg')\nplt.show()\n\n'''\n","sub_path":"HardyTour.py","file_name":"HardyTour.py","file_ext":"py","file_size_in_byte":11561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"556834753","text":"import sys\nimport os\nimport java.awt.Toolkit # only once per script\n\nsys.path.append(os.getcwd() + '\\\\sikulixapi.jar\\\\Lib')\nimport datetime\nfrom sikuli import *\n\nimport signal\nimport time\nimport operator\nimport random\nrandom = random.SystemRandom()\nimport math\n\nimport threading\n\nLAST_INV_BBOX = Region(867, 948, 30, 30)\nFIRST_INV_BBOX = Region(714, 678, 30, 30)\nINV_ICON_BBOX = Region(793, 626, 25, 34)\nBANK_FIRST_ITEM_BBOX = Region(92, 139, 27, 22)\nBANK_TITLE_BBOX = Region(142, 36, 310, 35)\n\ndef _press_key(key):\n '''\n Press a key\n https://stackoverflow.com/questions/22505698/what-is-a-typical-keypress-duration\n Says that standard keypress is 50 ms to 300 ms\n :param key:\n :return:\n '''\n keyDown(key)\n _wait(0.05, 0.3)\n keyUp(key)\n _wait(0.8, 2)\n\ndef _assert_standing_at_bank():\n '''\n Assert the player (you) is standing in a marked tile.\n Assumes that the camera is verticle and zoomed in\n Checks the 4 corners for the yellow tile highlight right angle\n :return:\n '''\n #TODO corners change depending on how you got to that tile\n corners = {\n 'NW': Region(383, 395, 43, 41),\n 'NE': Region(572, 387, 54, 62),\n 'SE': Region(565, 586, 63, 57),\n 'SW': Region(387, 580, 36, 53),\n }\n\n matches = 0\n for corner, region in corners.items():\n pattern = Pattern(os.getcwd() + r'\\images\\%s_corner_marker.png' % corner)\n pattern.similar(0.95)\n\n if region.exists(pattern, 0):\n matches += 1\n\n assert matches >= 3, '%d corners were not found!' % (4 - matches)\n\n\ndef _assert_player_in_tile():\n '''\n Assert the player (you) is standing in a marked tile.\n Assumes that the camera is verticle and zoomed in\n Checks the 4 corners for the yellow tile highlight right angle\n :return:\n '''\n #TODO currently setup for mining south orientation!!\n corners = {\n 'NW' : Region(383, 441, 44, 43),\n 'NE' : Region(571, 438, 54, 51),\n 'SE' : Region(568, 619, 56, 62),\n 'SW' : Region(379, 632, 48, 48),\n }\n \n matches = 0\n for corner, region in corners.items():\n pattern = Pattern(os.getcwd() + r'\\images\\%s_corner_marker.png' % corner)\n pattern.similar(0.95)\n\n if region.exists(pattern, 0):\n matches += 1\n\n assert matches >=3 , '%d corners were not found!' % (4-matches)\n \n \ndef _ge_click_banker(bank_title):\n '''\n \n :param bank_title: Title of the bank inventory screen\n :return:\n '''\n bank_bbox = Region(695, 481, 45, 51)\n blank_bank_bbox = Region(158, 284, 344, 354)\n \n for bankAttempt in range(3):\n _assert_standing_at_bank()\n randomCoords(bank_bbox).click()\n _wait(1, 1.5)\n randomCoords(blank_bank_bbox).hover()\n _wait(1, 1.5)\n if BANK_TITLE_BBOX.exists(os.getcwd() + r'\\images\\bank_title_%s.png' % bank_title, 0.1):\n break\n _wait(2,5)\n else:\n raise RuntimeError(\"Couldn't open the bank!!!\")\n _wait(1,2)\n \n\ndef _bank_transaction(withdraw_num=1, dep_all=False, deposit=True):\n '''\n Once in the bank screen\n :param withdraw_num: Number of uniqe items to withdraw\n :param dep_all: click deposit all button or just deposit all items of first inv slot\n :return:\n '''\n assert withdraw_num in (1,2)\n\n bank_first_item_bbox = BANK_FIRST_ITEM_BBOX\n bank_second_item_bbox = Region(155, 138, 23, 27)\n bank_deposit_all_bbox = Region(536, 786, 31, 26)\n\n first_inv_bbox = FIRST_INV_BBOX\n\n # Deposit\n _wait(0.8, 1.3)\n if deposit:\n if dep_all:\n randomCoords(bank_deposit_all_bbox).click()\n _wait(0.8, 1.3)\n else:\n keyDown(Key.SHIFT)\n _wait(0.3, 0.8)\n randomCoords(first_inv_bbox).click()\n _wait(0.5,1)\n \n \n # Withdraw\n if (deposit and dep_all) or not deposit:\n keyDown(Key.SHIFT)\n _wait(0.3, 0.8)\n \n randomCoords(bank_first_item_bbox).click()\n _wait(1, 2)\n\n if withdraw_num == 2:\n randomCoords(bank_second_item_bbox).click()\n _wait(1, 2)\n\n\n keyUp(Key.SHIFT)\n _wait(0.3, 0.8)\n\n # Close bank\n keyDown(Key.ESC)\n _wait(0.2, 0.4)\n keyUp(Key.ESC)\n _wait(0.7, 1.3)\n\ndef _assert_spellbook_selected():\n spellbook_selected_img = os.getcwd() + r'\\images\\spellbook_selected.png'\n spellbook_selected_red_img = os.getcwd() + r'\\images\\spellbook_selected_red.png'\n spellbook_selected_bbox = Region(893, 601, 73, 71)\n\n spellbook_selected_red_pattern = Pattern(spellbook_selected_img)\n spellbook_selected_red_pattern.similar(0.95)\n \n assert (spellbook_selected_bbox.exists(spellbook_selected_red_img, 0.01) or spellbook_selected_bbox.exists(spellbook_selected_red_pattern, 0.01)), 'Spellbook not selected!'\n\ndef _alert_low_health_inventory():\n 'Read the bars on the inventory screen for health'\n inv_bar_region = Region(664, 901, 22, 18)\n pattern = Pattern(os.getcwd() + r'\\images\\low_health_inventory.PNG')\n pattern.similar(0.98)\n if not inv_bar_region.exists(pattern, 0.01):\n raise RuntimeError('Low Health!!')\n \n\ndef _get_health():\n for _ in range(5):\n t = Region(698, 92, 33, 32).text()\n if t.isnumeric():\n return int(t)\n else:\n raise RuntimeError(\"Couldn't read health!\")\n \ndef _alert_health(level=20):\n health = _get_health()\n if health <= level:\n for _ in range(5):\n beep(200)\n raise ValueError('Low health!')\n\ndef _hide_cursor():\n if not os.path.exists(r'C:\\Users\\Richard\\.runelite\\_cursor.png'):\n if not os.path.exists(r'C:\\Users\\Richard\\.runelite\\cursor.png'):\n raise AssertionError('Neither form of the cursor image exists!')\n else:\n print('Cursor is already hidden!')\n else:\n os.rename(r'C:\\Users\\Richard\\.runelite\\_cursor.png', r'C:\\Users\\Richard\\.runelite\\cursor.png')\n \ndef _show_cursor():\n if not os.path.exists(r'C:\\Users\\Richard\\.runelite\\cursor.png'):\n if not os.path.exists(r'C:\\Users\\Richard\\.runelite\\_cursor.png'):\n raise AssertionError('Neither form of the cursor image exists!')\n else:\n print('Cursor is already shown!')\n os.rename(r'C:\\Users\\Richard\\.runelite\\cursor.png', r'C:\\Users\\Richard\\.runelite\\_cursor.png')\n\ndef _resetZoom(look_direction=None):\n compass_bbox = Region(744, 45, 30, 25)\n look_direction_dict = {\n 'west': Region(628, 36, 316, 253)\n }\n assert look_direction in look_direction_dict or look_direction is None\n \n # Reset zoom and look in a specific cardinal direction\n if look_direction:\n look_bbox = look_direction_dict[look_direction]\n look_Pattern = Pattern(os.getcwd() + r'\\images\\look_%s.png' % look_direction)\n look_Pattern.similar(0.85)\n for _ in range(3):\n try:\n randomCoords(compass_bbox).rightClick()\n _wait(1,2)\n look_bbox = Region(*fromRaw(look_bbox.find(look_Pattern)))\n break\n except:\n INV_ICON_BBOX.hover()\n _wait(1,2)\n else:\n raise RuntimeError(\"Couldn't find look direction on compass!!!\")\n print('Found direction')\n _wait(0.6, 1)\n randomCoords(look_bbox).click()\n else: # Just reset zoom\n randomCoords(compass_bbox).click()\n \n _wait(0.6, 1)\n keyDown(Key.UP)\n _wait(3,4)\n keyUp(Key.UP)\n _wait(0.6, 1)\n \n keyDown(Key.CTRL)\n _wait(0.6,1)\n keyUp(Key.CTRL)\n _wait(1, 2)\n\ndef _zoom(wheel_direction):\n assert wheel_direction in (Button.WHEEL_DOWN, Button.WHEEL_UP)\n mouse_scroll_bbox = Region(61, 157, 456, 389)\n region = randomCoords(mouse_scroll_bbox)\n region.hover()\n for _ in range(random.randint(6, 7)):\n region.wheel(wheel_direction, random.randint(5, 9))\n _wait(0.3, 0.7)\n\nclass __KillableThread(threading.Thread):\n def __init__(self, key):\n super(__KillableThread, self).__init__()\n self._kill = threading.Event()\n self.key = key\n \n def run(self):\n while True:\n keyDown(self.key)\n keyUp(self.key)\n # If no kill signal is set, sleep for the interval,\n # If kill signal comes in while sleeping, immediately\n # wake up and handle\n is_killed = self._kill.wait(0.0)\n if is_killed:\n break\n \n print(\"Killing Thread\")\n \n def kill(self):\n self._kill.set()\n\n\nclass press_and_hold_key(object):\n def __init__(self, key):\n self.key = key\n self.thread = __KillableThread(self.key)\n \n def __enter__(self):\n self.thread.start()\n \n def __exit__(self, exc_type, exc_val, exc_tb):\n self.thread.kill()\n self.thread.join(0.0)\n \nclass MaxTimeError(Exception):\n def __init__(self):\n super(Exception, self).__init__('Past max time')\n \nclass LevelUpError(Exception):\n def __init__(self):\n super(Exception, self).__init__('level up message')\n\ndef fromRaw(rawRegion):\n return [rawRegion.getX(), rawRegion.getY(), rawRegion.getW(), rawRegion.getH()]\n\ndef _wait(a, b):\n sleepTime = random.uniform(float(a), float(b))\n time.sleep(sleepTime)\n return sleepTime\n \ndef randomCoords(coords):\n if isinstance(coords, Region):\n coords = fromRaw(coords)\n newX = coords[0] + random.randrange(0, coords[2])\n newY = coords[1] + random.randrange(0, coords[3])\n return Region(newX, newY, 0, 0)\n\ndef beep(wait):\n '''\n :param wait(ms):\n :return:\n '''\n java.awt.Toolkit.getDefaultToolkit().beep()\n time.sleep(wait / float(1000))\n \ndef _checkLevelUp():\n levelupRegion = Region(504, 837, 141, 60)\n levelupImage = Pattern(os.getcwd() + r'\\images\\levelup.png')\n levelupImage.similar(0.95)\n if levelupRegion.exists(levelupImage, 0.01):\n randomCoords(levelupRegion).click()\n _wait(0.2,0.5)\n for _ in range(5):\n _wait(0.5, 0.7)\n keyDown(Key.SPACE)\n _wait(0.1, 0.3)\n keyUp(Key.SPACE)\n if not levelupRegion.exists(levelupImage):\n break\n raise LevelUpError()\n\ndef waitFor(region, image, numTries=None, maxTime=None, inverse=False):\n '''\n Waits for an image\n :param region:\n :param image:\n :param numTries: int, max number of attempts. Raises StopIteration\n :param maxTime: datetime.datetime or datetime.timedelta. Raises\n :return:\n '''\n image = os.getcwd() + (r'\\images\\%s' % image ) + '.png' if not image.endswith('.png') else ''\n assert os.path.exists(image)\n \n iter=0\n if numTries:\n assert isinstance(numTries, int)\n if maxTime:\n assert isinstance(maxTime, (datetime.datetime, datetime.timedelta))\n if isinstance(maxTime, datetime.timedelta):\n maxTime = datetime.datetime.now() + maxTime\n opr = operator.truth if not inverse else operator.not_\n while not opr(region.exists(image, 0.2)):\n if numTries:\n iter += 1\n if iter == numTries:\n raise StopIteration('hit max attempts')\n if maxTime:\n if datetime.datetime.now() >= maxTime:\n raise MaxTimeError()\n _checkLevelUp()\n\n\nOBSERVED_EVENT = False\ndef waitForChange(region, maxTime):\n \"\"\"\n Wait until ANY changes are observed in a region.\n Raises RuntimeError if none are observed\n :param region:\n :param maxTime:\n :return:\n \"\"\"\n global OBSERVED_EVENT\n OBSERVED_EVENT = False\n \n region = Region(*fromRaw(region))\n\n def changeHandler(event):\n global OBSERVED_EVENT\n OBSERVED_EVENT = True\n event.region.stopObserver()\n\n \n region.onChange(50, changeHandler)\n region.observe(maxTime, background=False)\n region.stopObserver()\n if not OBSERVED_EVENT:\n raise RuntimeError(\"Didn't observe any changes in given region.\")\n \n\ndef mining():\n '''\n Set to half window (left), center viewing angle, zoom all the way in, minimize chat.\n Allow custom cursors\n Orient such that ore is left\n '''\n \n print('Go to the Mining Guild!!!!!')\n \n ore_bbox_W = Region(206, 508, 101, 87)\n ore_bbox_E = Region(600, 496, 113, 102)\n ore_bbox_S = Region(410, 702, 107, 106)\n \n inventory_slot_bbox = FIRST_INV_BBOX\n\n randomCoords(INV_ICON_BBOX).click()\n \n #TODO\n _hide_cursor()\n \n _wait(0.4, 0.7)\n keyDown(Key.SHIFT)\n _wait(0.4, 0.7)\n\n try:\n # Time to mine ore\n while True:\n # Timeout\n #if datetime.datetime.now() > datetime.datetime(2020,11,20,4):\n # return\n for ore_bbox in [ore_bbox_W, ore_bbox_S, ore_bbox_E]:\n _assert_player_in_tile()\n \n randomCoords(ore_bbox).click()\n _wait(0.1, 0.3)\n \n inv_bbox = randomCoords(inventory_slot_bbox)\n\n inv_bbox.hover()\n \n try:\n waitFor(inventory_slot_bbox, 'empty_inventory', maxTime=datetime.timedelta(seconds=3), inverse=True)\n except MaxTimeError:\n continue\n except LevelUpError:\n continue\n \n _wait(0.1, 0.2)\n inv_bbox.click()\n _wait(0.1, 0.3)\n \n \n \n #if ore_bbox.exists(os.getcwd() + r'\\images\\iron_rock_color.png' , 0.2):\n # continue\n #else:\n # _wait(0.5, 0.7)\n finally:\n keyUp(Key.SHIFT)\n\n\ndef _agility(info):\n print('Make sure the side panels are minimized in options!')\n # info = (\n # Outer region of the click box,\n # Inner region of the click box (What to click on),\n # Bbox of the roof(where to search for marks of grace)\n # Time to wait for animation to complete,\n # )\n raw_input('Press enter when ready...')\n \n maxTime = 5 + max([x[-1] for x in info])\n graceIndex = None\n \n center_bbox = Region(463, 509, 45, 45)\n \n entire_screen_bbox = Region(9, 237, 940, 700)\n \n def checkRedAgility(reg):\n if reg.exists(os.getcwd() + r'\\images\\agility_red.png', 0.01):\n for _ in range(5):\n beep(500)\n raise RuntimeError('Mark of grace!')\n \n while True:\n for index, (outerRegion, clickRegion, roofRegion, sleeptime) in enumerate(info):\n if center_bbox.exists(os.getcwd() + r'\\images\\agility_player_fell_down.png', 0.01):\n _zoom(Button.WHEEL_UP)\n try:\n _assert_player_in_tile()\n except AssertionError:\n print('What?')\n _zoom(Button.WHEEL_DOWN)\n raise RuntimeError('Player fell down!')\n \n if graceIndex == index:\n raise RuntimeError('Mark of grace was found, but was not picked up!')\n \n if outerRegion.exists(os.getcwd() + r'\\images\\agility_red.png', 0.01):\n graceIndex = index\n \n \n if roofRegion and roofRegion.exists(os.getcwd() + r'\\images\\mark_of_grace.png', 0.01):\n for _ in range(5):\n beep(500)\n raw_input('Collect mark and goto the next one, then press enter')\n graceIndex = None\n continue\n \n img = 'agility_red' if isinstance(graceIndex, int) else 'agility_green'\n waitFor(outerRegion, img, maxTime=datetime.timedelta(seconds=maxTime))\n \n _wait(0.8, 1.5)\n\n randomCoords(clickRegion).click()\n\n slept_time = _wait(sleeptime, sleeptime+0.5)\n _wait(0.8, 1.5)\n print('Waited for %f for %d' % (slept_time, index,))\n \n\ndef agility_canifis():\n 'Start after the first one'\n info = [\n (Region(425, 318, 92, 110), Region(448, 354, 44, 39), Region(404, 352, 235, 229), 5),\n (Region(311, 495, 54, 78), Region(322, 508, 28, 52), Region(303, 427, 255, 159), 4.6),\n (Region(286, 626, 46, 78), Region(297, 638, 22, 54), Region(280, 478, 248, 226), 4.9),\n (Region(431, 690, 41, 78), Region(441, 701, 20, 54), Region(325, 480, 200, 274), 5),\n (Region(498, 574, 68, 75), Region(520, 600, 20, 22), Region(428, 480, 222, 206), 7),\n #Region(851, 518, 28, 41) Region(887, 518, 28, 41)\n (Region(828, 497, 67, 79), Region(856, 518, 18, 41), Region(433, 434, 461, 342), 6.5),\n (Region(458, 314, 43, 66), Region(470, 330, 19, 37), Region(395, 322, 263, 293), 5),\n (Region(271, 380, 196, 76), Region(319, 394, 63, 16), None, 7.5), # Marks of grace should never appear here.\n ]\n _agility(info)\n\ndef dartSmithing():\n \n 'start next to southern most bank, full inventory, bank tab preset'\n \n \n bank_bbox = Region(420, 210, 18, 19)\n \n anvil_bbox = Region(559, 834, 7, 10)\n dart_bbox = Region(431, 276, 37, 39)\n bank_title_bbox = BANK_TITLE_BBOX\n \n bars = int(raw_input('Number of iron bars: '))\n numRuns = int(math.ceil(bars / 27.0))\n print('numRuns = %d' % numRuns)\n for _ in range(numRuns):\n randomCoords(anvil_bbox).click()\n _wait(6.8, 7.5)\n \n randomCoords(dart_bbox).click()\n _wait(80,90)\n \n \n randomCoords(bank_bbox).click()\n try:\n waitFor(bank_title_bbox, 'bank_title_darts', maxTime=datetime.timedelta(seconds=10))\n except:\n java.awt.Toolkit.getDefaultToolkit().beep()\n raise\n \n _wait(1,3)\n _bank_transaction(deposit=False)\n\n\ndef camelotTele():\n numTele = int(raw_input('Number of teleports: '))\n \n tele_bbox = Region(859, 757, 25, 22)\n \n clickRegion = randomCoords(tele_bbox)\n \n for i in range(numTele):\n print(numTele-i-1)\n _assert_spellbook_selected()\n if not random.randint(0, 20):\n clickRegion = randomCoords(tele_bbox)\n clickRegion.click()\n _wait(3.3, 3.8)\n\ndef highAlch():\n numAlch = int(raw_input('Number of items: '))\n \n alch_bbox = Region(895, 789, 9, 9)\n \n clickRegion = randomCoords(alch_bbox)\n \n for i in range(numAlch):\n print(numAlch - i - 1)\n _assert_spellbook_selected()\n if not random.randint(0, 50):\n clickRegion = randomCoords(alch_bbox)\n clickRegion.click()\n _wait(0.3, 0.7)\n clickRegion.click()\n _wait(2.3, 3.0)\n\ndef firemaking():\n '''\n Inventory layout:\n Tinderbox: top left\n Junk: rest of top row\n Junk: 2nd from the bottom row, left most column.\n Junk: bottom most row, all but left most column.\n Noted logs: bottom right\n Start with only these two items.\n Start at the grand exchange, with player models off, directly west of the top left banker, zoomed all the way IN.\n '''\n numLogs = int(raw_input('Number of logs: '))\n \n logs_per_run = 19\n numRuns = int(math.ceil(numLogs / float(logs_per_run)))\n \n noted_logs_bbox = LAST_INV_BBOX\n tinderbox_bbox = Region(714, 678, 30, 30)\n bank_outer_bbox = Region(576, 467, 170, 143)\n bank_bbox = Region(666, 516, 80, 70)\n step_left_bbox = Region(246, 507, 134, 90)\n\n step_down_left_bbox = Region(231, 628, 139, 128)\n \n banker_foot = Pattern(os.getcwd() + r'\\images\\banker_foot.png')\n banker_foot.similar(0.80)\n \n initial_item_bbox = [711, 723, 34, 31]\n item_bbox_X_translate = 53\n item_bbox_Y_translate = 46\n \n # Arbitrary region on the screen, used to monitor for movement that occurs when a fire is\n # successfully started, signalling that a new fire can be attempted.\n started_fire_observer_bboxs = (Region(51, 178, 212, 173), Region(46, 691, 184, 176))\n\n bank_return_pos_bbox = Region(930, 530, 16, 16)\n bankstand_marker_bboxs = ( Region(18, 53, 717, 921), Region(683, 249, 268, 362))\n\n ground_marker = Pattern(os.getcwd() + r'\\images\\firemaking_bank_ground_marker.png')\n ground_marker.similar(0.80)\n centered_bankstand_bbox = Region(379, 439, 95, 111)\n \n allowed_misobservations = 1\n\n #TODO fill the unused inventory slots with misc garbage to prvent miscounting.\n for numRun in range(numRuns):\n misobservations = 0\n start_time = time.time()\n # Make sure the banker is where it should be\n assert bank_outer_bbox.exists(banker_foot)\n \n # Un-note the logs and step left to a vaild firemaking spot.\n randomCoords(noted_logs_bbox).click()\n _wait(0.2, 0.5)\n randomCoords(bank_bbox).click()\n _wait(1, 2)\n keyDown('1')\n _wait(0.1, 0.3)\n keyUp('1')\n _wait(1,2)\n if numRun % 2:\n randomCoords(step_down_left_bbox).click()\n else:\n randomCoords(step_left_bbox).click()\n _wait(1.5,2.5)\n\n \n # Start burning the logs\n for rowNum in range(5):\n for colNum in range(4):\n if rowNum == 4 and colNum == 3:\n #Last row only has 3 items.\n break\n randomCoords(tinderbox_bbox).click()\n _wait(0.3, 0.5)\n \n item_bbox = Region(\n initial_item_bbox[0] + (item_bbox_X_translate * colNum),\n initial_item_bbox[1] + (item_bbox_Y_translate * rowNum),\n 27,\n 24\n )\n \n randomCoords(item_bbox).click()\n try:\n waitForChange(started_fire_observer_bboxs[numRun % 2], 7)\n except RuntimeError:\n if misobservations > allowed_misobservations:\n raise\n misobservations += 1\n continue\n _wait(0.3, 0.5)\n _wait(0.3,0.5)\n \n # Run back to the banker to repeat the process\n _zoom(Button.WHEEL_DOWN)\n randomCoords(bank_return_pos_bbox).click()\n _wait(9, 11)\n _zoom(Button.WHEEL_UP)\n _wait(1,3)\n \n for marker_bbox in bankstand_marker_bboxs:\n if marker_bbox.exists(ground_marker, 0.01):\n bankstand = marker_bbox.find(ground_marker)\n bankstand = fromRaw(bankstand)\n bankstand[0] += 10\n randomCoords(bankstand).click()\n _wait(3, 5)\n bank_bbox.hover()\n break\n else:\n raise RuntimeError(\"Couldn't find bankstand marker! Did you remember to mark it?\")\n assert bank_outer_bbox.exists(banker_foot) or Region(379, 439, 95, 111).exists(ground_marker, 1)\n\n\n _wait(0.9, 1.2)\n \n #timeToWait = abs(120 - int(time.time() - start_time) + 1)\n #print('Completed a set, waiting %d seconds for fires to die before starting the next one.' % timeToWait)\n #_wait(timeToWait, timeToWait+10)\n beep(500)\n \ndef glassBlowing():\n bank_bbox = Region(633, 478, 73, 65)\n numGlass = int(raw_input('Number of molten glass: '))\n\n glass_per_run = 26\n numRuns = int(math.ceil(numGlass / float(glass_per_run)))\n\n noted_glass_bbox = LAST_INV_BBOX\n pipe_bbox = Region(714, 678, 30, 30)\n first_glass_bbox = Region(767, 686, 23, 21)\n \n for _ in range(numRuns):\n # Un-note the glass\n randomCoords(noted_glass_bbox).click()\n _wait(0.2, 0.5)\n randomCoords(bank_bbox).click()\n _wait(1, 2)\n keyDown('1')\n _wait(0.1, 0.3)\n keyUp('1')\n _wait(1, 2)\n \n # Start the process\n randomCoords(pipe_bbox).click()\n _wait(0.2,0.7)\n randomCoords(first_glass_bbox).click()\n _wait(1, 2)\n\n keyDown('6')\n _wait(0.1, 0.3)\n keyUp('6')\n _wait(1, 2)\n \n waitTime = 1.8*glass_per_run\n \n _wait(waitTime+ 3, waitTime + 7)\n\n randomCoords(bank_bbox).click()\n _wait(0.7, 1.3)\n keyDown(Key.SHIFT)\n _wait(0.1, 0.3)\n randomCoords(first_glass_bbox).click()\n _wait(0.1, 0.2)\n keyUp(Key.SHIFT)\n _wait(0.7, 1.3)\n\n keyDown(Key.ESC)\n _wait(0.1, 0.3)\n keyUp(Key.ESC)\n _wait(0.7, 1.3)\n \ndef _dump_inventory(exclude_slots=[]):\n '''\n Will dump the entire inventory on the ground except for the bottom row.\n :param exclude_slots: list of 2 tuple of inventory slot coordinates to exclude from dumping.\n Ex) To prevent top right, use (3, 0).\n Ex) To prevent bottom left (remember the last row is always excluded), use (5, 0).\n :return: Number of items dumped.\n '''\n print('Dumping Inventory')\n \n for excluded_slot in exclude_slots:\n assert isinstance(excluded_slot, tuple) and len(excluded_slot) == 2\n assert 0 < excluded_slot[0] <= 3\n assert 0 < excluded_slot[1] <= 5 #skip the last row\n \n inventory_icon_bbox = INV_ICON_BBOX\n mouse_move_region = Region(101, 156, 359, 205)\n first_inv_bbox = [714, 678, 30, 30]\n item_bbox_X_translate = 53\n item_bbox_Y_translate = 46\n randomCoords(mouse_move_region).hover()\n \n # Find items to dump\n inv_slots_to_dump = []\n for rowNum in range(6): # Keep contents bottom row\n colIter = range(4) if not rowNum % 2 else reversed(range(4)) # Make it an S pattern\n for colNum in colIter:\n if (colNum, rowNum) in exclude_slots:\n continue\n inventory_slot_bbox = Region(\n first_inv_bbox[0] + (item_bbox_X_translate * colNum),\n first_inv_bbox[1] + (item_bbox_Y_translate * rowNum),\n 30, # 27\n 30 # 24\n )\n if not inventory_slot_bbox.exists(os.getcwd() + r'\\images\\woodcutting_empty_inventory_slot.png', 0):\n inv_slots_to_dump.append(inventory_slot_bbox)\n _wait(1, 2)\n \n \n # Dump items\n keyDown(Key.SHIFT)\n _wait(0.8, 1.2)\n for region in inv_slots_to_dump:\n randomCoords(region).click()\n _wait(0.3, 0.6)\n\n keyUp(Key.SHIFT)\n _wait(1, 2)\n return len(inv_slots_to_dump)\n \ndef woodcutting():\n '''\n Camera up, zoomed all the way in, tree on the right.\n :return:\n '''\n tree_bbox = Region(665, 487, 120, 99)\n inventory_icon_bbox = INV_ICON_BBOX\n mouse_move_region = Region(101, 156, 359, 205)\n while True:\n randomCoords(tree_bbox).click()\n _wait(1,2)\n randomCoords(mouse_move_region).hover()\n waitFor(tree_bbox, 'woodcutting_yellow_timer', maxTime=datetime.timedelta(seconds=200))\n _wait(1, 5)\n _dump_inventory()\n \n waitFor(tree_bbox, 'woodcutting_yellow_timer',maxTime=datetime.timedelta(seconds=10), inverse=True)\n print('Tree is back')\n _wait(1,5)\n \n\ndef humidifyClay():\n\n numClay = int(raw_input('Clay: '))\n numRuns = int(math.floor(numClay / 27.0))\n print('Will need %d Astral Runes.' % numRuns)\n \n humidify_bbox = Region(796, 700, 24, 20)\n \n for i in range(numRuns):\n print(numRuns - i - 1)\n _assert_spellbook_selected()\n _assert_standing_at_bank()\n randomCoords(humidify_bbox).click()\n _wait(2.5,4)\n \n _ge_click_banker('clay')\n _bank_transaction()\n\ndef tanLeather():\n numHides = int(raw_input('Hides: '))\n numRuns = int(math.floor(numHides / 25.0))\n print('Will need %d Astral Runes.' % (numRuns*2*5))\n print('Will need %d Nature Runes.' % (numRuns*5))\n tan_bbox = Region(751, 805, 14, 18)\n \n for i in range(numRuns):\n print(numRuns - i - 1)\n _assert_spellbook_selected()\n _assert_standing_at_bank()\n for _ in range(5):\n randomCoords(tan_bbox).click()\n _wait(2, 2.5)\n \n _ge_click_banker('tan')\n _bank_transaction()\n _wait(1,2)\n\n\ndef _fishing(fish):\n '''\n Zoomed in\n Vertical camera\n Hide all entities EXCEPT NPCs\n Have fishing spots oriented to be above you (relative North).\n Can do exact movements by right clicking on compass.\n Hide minimap\n :return:\n '''\n print('Make sure to hide all entities EXCEPT for NPCs')\n\n player_region = Region(-1528, 441, 148, 138)\n \n total_fish_area_bbox = Region(-1910, 247, 925, 127)\n \n last_inv_slot = LAST_INV_BBOX\n \n mouse_move_region = Region(-1784, 671, 324, 256)\n \n # Constant. Will always be the north tile\n current_fish_region = Region(-1518, 259, 199, 106)\n\n empty_inv_slot_img = os.getcwd() + r'\\images\\woodcutting_empty_inventory_slot.png'\n fish_img = os.getcwd() + r'\\images\\fishing\\%s.png' % fish\n \n MAX_FISH_FIND_ATTEMPTS = 3\n \n fish_areas = []\n fish_bbox = None\n \n def find_closest_spot(fish_areas):\n player_center = player_region.center\n player_coords = (player_center.getX(), player_center.getY())\n closest_distance = 100000\n closest = None\n for area in fish_areas:\n center = area.center\n coords = (center.getX(), center.getY())\n distance = math.sqrt( math.pow((player_coords[0] - coords[0]), 2) + math.pow((player_coords[1] - coords[1]), 2) )\n if distance < closest_distance:\n closest = area\n return closest\n \n \n \n while True:\n if not fish_bbox or not fish_bbox.exists(fish_img, 0.01):\n for _ in range(MAX_FISH_FIND_ATTEMPTS):\n try:\n print('Attempting to find fishing spot.')\n fish_areas = total_fish_area_bbox.findAll(fish_img)\n break\n except FindFailed:\n _wait(15, 30)\n else:\n raise RuntimeError(\"Couldn't find a fishing spot!\")\n \n print('Found fishing spots')\n \n fish_bbox = fromRaw(find_closest_spot(fish_areas))\n fish_bbox = Region(\n fish_bbox[0] - 15,\n fish_bbox[1] - 15,\n fish_bbox[2] + 15,\n fish_bbox[3] + 15\n )\n print('Found closest fishing spot')\n else:\n print('Using old fishing spot')\n \n _wait(1,3)\n randomCoords(fish_bbox).click()\n _wait(1,3)\n randomCoords(mouse_move_region).hover()\n _wait(3,6)\n\n \n\n maxTime = time.time() + 200\n try:\n while True:\n # If last inventory slot is full\n if not last_inv_slot.exists(empty_inv_slot_img, 0.2):\n break\n if not current_fish_region.exists(fish_img, 0.2):\n time.sleep(1)\n if not current_fish_region.exists(fish_img, 0.2):\n raise ValueError('Fishing spot depleted')\n if time.time() >= maxTime:\n raise MaxTimeError()\n _checkLevelUp()\n except Exception as e:\n print(e)\n \n _wait(2,4)\n _dump_inventory()\n _wait(1,3)\n \n \n \n \ndef salmon():\n _fishing('salmon')\n \n \ndef cooking():\n '''\n Cooking karambwan at Hosidious\n Zoom all the way in\n Vertical camera\n Looking south\n :return:\n '''\n numFish = int(raw_input('Number of Karambwan: '))\n numRuns = int(math.floor(numFish / 28.0))\n \n \n inventory_icon_bbox = INV_ICON_BBOX\n oven_outer_bbox = Region(-1595, 650, 266, 234)\n oven_bbox = Region(-1507, 723, 96, 95)\n\n last_inv_slot = Region(-1050, 948, 30, 30)\n bank_bbox = Region(-1399, 371, 16, 15)\n bank_title_bbox = BANK_TITLE_BBOX\n oven_stand_bbox = Region(-1495, 652, 14, 16)\n \n \n \n \n randomCoords(inventory_icon_bbox).click()\n _wait(0.5, 1)\n for numIter in range(numRuns):\n assert oven_outer_bbox.exists(os.getcwd() + r'\\images\\cooking_oven.png', 0.01)\n \n with press_and_hold_key('2'):\n _wait(0.4, 0.6)\n random_last_inv_slot_bbox = randomCoords(last_inv_slot)\n for _ in range(28):\n if not last_inv_slot.exists(os.getcwd() + r'\\images\\raw_karambwan.png', 0.01):\n break\n random_last_inv_slot_bbox.click()\n _wait(0.0, 0.15)\n randomCoords(oven_bbox).click()\n t1 = time.time()\n _wait(0.2, 0.4)\n random_last_inv_slot_bbox = randomCoords(last_inv_slot)\n random_last_inv_slot_bbox.hover()\n waitTime = max(0.4 - (time.time()-t1), 0)\n _wait(waitTime, waitTime+0.2)\n\n print('Cooked all')\n \n _wait(0.3, 0.9)\n _zoom(Button.WHEEL_DOWN)\n _wait(0.3, 0.9)\n randomCoords(bank_bbox).click()\n waitFor(bank_title_bbox, 'cooking', maxTime=datetime.timedelta(seconds=15))\n _wait(1, 1.5)\n \n _bank_transaction(dep_all=True)\n \n randomCoords(oven_stand_bbox).click()\n _wait(3.2, 3.7)\n _zoom(Button.WHEEL_UP)\n _wait(0.5, 1)\n \n \ndef barbarian_fishing():\n '''\n Zoomed in\n Vertical camera\n Hide all entities EXCEPT NPCs\n Have fishing spots oriented to be above you (relative North).\n Can do exact movements by right clicking on compass.\n Hide minimap\n Turn off Ground Items\n :return:\n '''\n print('Make sure to hide all entities EXCEPT for NPCs')\n \n player_region = Region(-1528, 441, 148, 138)\n zoomed_player_region = Region(-1443, 521, 15, 15)\n \n total_fish_area_bbox = Region(-1910, 247, 925, 127)\n \n zoomed_total_fish_area_bbox = Region(-1694, 466, 683, 58)\n \n first_inv_slot = Region(-1206, 678, 30, 30)\n \n mouse_move_region = Region(-1209, 444, 214, 151)\n \n # Constant. Will always be the north tile\n current_fish_region = Region(-1518, 259, 199, 106)\n \n empty_inv_slot_img = os.getcwd() + r'\\images\\woodcutting_empty_inventory_slot.png'\n fish_img = os.getcwd() + r'\\images\\fishing\\barbarian.png'\n \n MAX_FISH_FIND_ATTEMPTS = 3\n \n fish_areas = []\n fish_bbox = None\n \n \n def find_closest_spot(player_loc, fish_areas):\n player_center = player_loc.center\n player_coords = (player_center.getX(), player_center.getY())\n closest_distance = 100000\n closest = None\n for area in fish_areas:\n center = area.center\n coords = (center.getX(), center.getY())\n distance = math.sqrt(\n math.pow((player_coords[0] - coords[0]), 2) + math.pow((player_coords[1] - coords[1]), 2))\n if distance < closest_distance:\n closest = area\n return closest\n \n def findFish():\n for _ in range(MAX_FISH_FIND_ATTEMPTS):\n try:\n print('Attempting to find fishing spot.')\n fish_areas = total_fish_area_bbox.findAll(fish_img)\n break\n except FindFailed:\n _wait(15, 30)\n else:\n raise RuntimeError(\"Couldn't find a fishing spot!\")\n print('Found fishing spots')\n\n fish_bbox = fromRaw(find_closest_spot(player_region, fish_areas))\n fish_bbox = Region(\n fish_bbox[0] - 15,\n fish_bbox[1] - 15,\n fish_bbox[2] + 15,\n fish_bbox[3] + 15\n )\n print('Found closest fishing spot')\n return fish_bbox\n \n while True:\n if not fish_bbox or not fish_bbox.exists(fish_img, 0.01):\n if total_fish_area_bbox.exists(fish_img, 0.01):\n fish_bbox = findFish()\n else:\n raise RuntimeError\n _zoom(Button.WHEEL_DOWN)\n if not zoomed_total_fish_area_bbox.exists(os.getcwd() + r'\\images\\fishing\\barbarian_zoom_edge.png', 0.01):\n raise RuntimeError(\"Couldn't find regardless of zoom level\")\n else:\n fish_zoom_areas = zoomed_total_fish_area_bbox.findAll(os.getcwd() + r'\\images\\fishing\\barbarian_zoom_edge.png')\n closest_zoom = fromRaw(find_closest_spot(zoomed_player_region, fish_zoom_areas))\n closest_zoom = Region(\n closest_zoom[0] - 15,\n closest_zoom[1] - 15,\n closest_zoom[2] + 15,\n closest_zoom[3] + 15\n )\n randomCoords(closest_zoom).click()\n _wait(3,5)\n _zoom(Button.WHEEL_UP)\n fish_bbox = findFish()\n \n \n \n else:\n print('Using old fishing spot')\n \n randomCoords(fish_bbox).click()\n _wait(0.5, 1)\n randomCoords(mouse_move_region).hover()\n _wait(0.5, 1)\n \n \n \n maxTime = time.time() + 20\n try:\n while True:\n # If last inventory slot is full\n if not first_inv_slot.exists(empty_inv_slot_img, 0.01):\n break\n if not fish_bbox.exists(fish_img, 0.01):\n time.sleep(1)\n if not fish_bbox.exists(fish_img, 0.2):\n raise ValueError('Fishing spot depleted')\n if time.time() >= maxTime:\n raise MaxTimeError()\n _checkLevelUp()\n except Exception as e:\n print(e)\n\n _wait(0.1, 0.3)\n keyDown(Key.SHIFT)\n _wait(0.1, 0.3)\n \n randomCoords(first_inv_slot).click()\n _wait(0.1, 0.3)\n\n keyUp(Key.SHIFT)\n _wait(0.1, 0.3)\n \ndef _mixPotions(use):\n numPots = int(raw_input('Number of potions: '))\n numRuns = int(math.floor(numPots / 14.0))\n \n inv_mix_slot_1 = Region(771, 817, 20, 21)\n inv_mix_slot_2 = Region(822, 820, 21, 26)\n \n last_inv_bbox = LAST_INV_BBOX\n \n for i in range(numRuns):\n print(numRuns - i - 1)\n\n _assert_standing_at_bank()\n\n randomCoords(inv_mix_slot_1).click()\n _wait(0.1,0.3)\n randomCoords(inv_mix_slot_2).click()\n \n _wait(1, 1.5)\n keyDown(Key.SPACE)\n _wait(0.3, 0.6)\n keyUp(Key.SPACE)\n _wait(2, 3)\n try:\n waitFor(last_inv_bbox, 'woodcutting_empty_inventory_slot', maxTime=datetime.timedelta(seconds=1.2*16))\n except LevelUpError:\n pass\n _wait(0.6, 1)\n\n _ge_click_banker(use)\n\n _bank_transaction(withdraw_num=2, dep_all=True)\n \ndef herblore():\n _mixPotions('herblore')\n\ndef fruitStall():\n inventory_icon_bbox = INV_ICON_BBOX\n stall_bbox = Region(634, 501, 141, 108)\n first_inv_bbox = FIRST_INV_BBOX\n \n #with press_and_hold_key()\n randomCoords(inventory_icon_bbox).click()\n keyDown(Key.SHIFT)\n _wait(0.3, 0.5)\n try:\n while True:\n randomCoords(stall_bbox).click()\n try:\n waitFor(first_inv_bbox, 'woodcutting_empty_inventory_slot', maxTime=datetime.timedelta(seconds=3), inverse=True)\n except Exception:\n continue\n _wait(0.2, 0.5)\n randomCoords(first_inv_bbox).click()\n _wait(0.9, 1.2)\n finally:\n keyUp(Key.SHIFT)\n\n\ndef ensouledHeads():\n '''\n Camera verticle.\n Hide everything in entity hider\n Zoomed out\n :return:\n '''\n headType = raw_input('Head type: ').lower()\n spellbook_locations = {\n 'dag': Region(708, 874, 18, 18),\n 'kal': Region(826, 837, 22, 26),\n }\n\n spellbook_bbox = spellbook_locations[headType]\n\n look_bbox = Region(3, 210, 752, 486)\n \n item_bbox_X_translate = 53\n item_bbox_Y_translate = 46\n initial_item_bbox = fromRaw(FIRST_INV_BBOX)\n initial_item_bbox[1] += item_bbox_Y_translate\n \n for row in range(6):\n for col in range(4):\n try:\n #try:\n # _alert_health()\n #except RuntimeError:\n # pass\n\n _assert_spellbook_selected()\n randomCoords(spellbook_bbox).click()\n _wait(0.3, 0.8)\n\n item_bbox = Region(\n initial_item_bbox[0] + (item_bbox_X_translate * col),\n initial_item_bbox[1] + (item_bbox_Y_translate * row),\n 27,\n 24\n )\n\n randomCoords(item_bbox).click()\n\n # Wait for it to appear\n waitFor(look_bbox, 'ensouled_head', maxTime=datetime.timedelta(seconds=15))\n print('head appeared')\n # Wait for it to die\n waitFor(look_bbox, 'ensouled_head', inverse=True)\n\n _wait(1, 2)\n except LevelUpError:\n pass\n \n\ndef fletching():\n numLogs = int(raw_input('Num logs: '))\n pressDown = str(int(raw_input('Key to press down in option menu: ')))\n \n numRuns = int(math.ceil(numLogs / 27.0))\n\n first_inv_bbox = FIRST_INV_BBOX\n\n for i in range(numRuns):\n print(numRuns - i - 1)\n _ge_click_banker('fletching')\n _bank_transaction()\n \n # Knife to logs\n randomCoords(LAST_INV_BBOX).click()\n _wait(0.6, 1)\n randomCoords(first_inv_bbox).click()\n _wait(0.6, 1)\n\n # Make selection\n _wait(1, 2)\n keyDown(pressDown)\n _wait(0.1, 0.3)\n keyUp(pressDown)\n _wait(1,2)\n \n _wait(50,55)\n \ndef knight_pickpocket():\n '''\n Put coins in last inventory slot\n Mouse tooltips off\n World 378 or 302\n :return:\n '''\n \n print('Try world 378 or 302')\n \n raw_input('Is NPC attack options off? ')\n \n entire_screen_bbox = Region(2, 33, 939, 956)\n\n knight_click_tile = None\n NW, SW = None, None\n\n NW_pattern = Pattern(os.getcwd() + r'\\images\\pickpocket_NW_corner.png')\n NW_pattern.similar(0.95)\n SE_pattern = Pattern(os.getcwd() + r'\\images\\pickpocket_SE_corner.png')\n SE_pattern.similar(0.95)\n\n bank_pattern = Pattern(os.getcwd() + r'\\images\\knight_pickpocket_bank_booth.png')\n bank_pattern.similar(0.5)\n\n bank_title_bbox = BANK_TITLE_BBOX\n blank_bank_bbox = Region(158, 284, 344, 354)\n \n # For healing\n def get_heal_bboxes():\n item_bbox_X_translate = 53\n item_bbox_Y_translate = 46\n inv_bboxes = []\n for row in range(6):\n row += 1\n colIter = range(4) if not row % 2 else reversed(range(4))\n for col in colIter:\n tmp_bbox = fromRaw(FIRST_INV_BBOX)\n tmp_bbox[0] += item_bbox_X_translate*col\n tmp_bbox[1] += item_bbox_Y_translate*row\n inv_bboxes.append(Region(*tmp_bbox))\n return inv_bboxes\n inv_bboxes = get_heal_bboxes()\n\n _resetZoom('west')\n\n while True:\n for _ in range(28):\n try:\n _alert_low_health_inventory()\n except RuntimeError:\n # Heal\n _wait(0.6, 1)\n if len(inv_bboxes) == 0:\n _zoom(Button.WHEEL_DOWN)\n _wait(1,2)\n bank_bbox = fromRaw(entire_screen_bbox.find(bank_pattern))\n randomCoords(bank_bbox).click()\n waitFor(bank_title_bbox, 'bank_title_pickpocket', maxTime=datetime.timedelta(seconds=15))\n _wait(1,2)\n \n keyDown(Key.SHIFT)\n _wait(0.5,1)\n randomCoords(LAST_INV_BBOX).click()\n _wait(1,1.5)\n\n randomCoords(BANK_FIRST_ITEM_BBOX).click()\n _wait(0.5, 1)\n \n keyUp(Key.SHIFT)\n _wait(0.3, 0.7)\n\n randomCoords(FIRST_INV_BBOX).click()\n _wait(1,2)\n\n keyDown(Key.ESC)\n _wait(0.1, 0.3)\n keyUp(Key.ESC)\n _wait(0.7, 1.3)\n\n _resetZoom('west')\n \n inv_bboxes = get_heal_bboxes()\n \n for _ in range(4):\n inv_food_bbox = inv_bboxes.pop()\n randomCoords(inv_food_bbox).click()\n _wait(1.8, 2.3)\n #beep(100)\n #raw_input('Heal and press enter to continue: ')\n \n knight_moved_wait = False\n \n # If knight moved\n if NW and (not Region(*fromRaw(NW)).exists(NW_pattern, 0.01) or not Region(*fromRaw(SE)).exists(SE_pattern, 0.01)):\n knight_click_tile = None\n\n # Get where to click\n if knight_click_tile is None:\n\n NW = entire_screen_bbox.find(NW_pattern)\n SE = entire_screen_bbox.find(SE_pattern)\n \n NWc = NW.center\n SEc = SE.center\n \n x_offset = 25\n y_offset = 32\n \n knight_region = Region(NWc.getX() + x_offset, NWc.getY() + y_offset, SEc.getX() - NWc.getX() - (2*x_offset), SEc.getY() - NWc.getY() - (2*y_offset))\n\n knight_click_tile = randomCoords(knight_region)\n\n knight_moved_wait = True\n\n knight_click_tile.click()\n \n _wait(0.8, 1.3)\n \n if knight_moved_wait:\n _wait(1,2)\n \n \n \n _wait(1,2)\n randomCoords(FIRST_INV_BBOX).click()\n knight_click_tile = None\n _wait(1,2)\n\n\ndef crafting():\n numLeather = int(raw_input('Num items: '))\n pressDown = str(int(raw_input('Key to press down in option menu: ')))\n \n numRuns = int(math.floor(numLeather / 24.0))\n \n needle_bbox = LAST_INV_BBOX\n \n leather_bbox = fromRaw(LAST_INV_BBOX)\n leather_bbox[1] -= 46\n leather_bbox = Region(*leather_bbox)\n \n for i in range(numRuns):\n print(numRuns - i - 1)\n _ge_click_banker('crafting')\n _bank_transaction()\n \n # Knife to logs\n randomCoords(needle_bbox).click()\n _wait(1, 2)\n randomCoords(leather_bbox).click()\n _wait(1, 2)\n \n # Make selection\n _wait(1, 2)\n _press_key(pressDown)\n \n _wait(17,19)\n \n \ndef test():\n entire_screen_bbox = Region(9, 237, 940, 700)\n \n xmin, xmax, ymin, ymax = 9000, 0, 9000, 0\n if entire_screen_bbox.exists(os.getcwd() + r'\\images\\agility_green.png'):\n pattern = Pattern(os.getcwd() + r'\\images\\agility_green.png')\n pattern.similar(0.95)\n matches = entire_screen_bbox.findAll(pattern)\n idx = 0\n while True:\n if not matches.hasNext():\n break\n m = matches.next()\n \n print(m)\n m = m.center\n \n if m.getX() < xmin:\n xmin = m.getX()\n elif m.getX() > xmax:\n xmax = m.getX()\n if m.getY() < ymin:\n ymin = m.getY()\n elif m.getY() > ymax:\n ymax = m.getY()\n \n \n \n newRegion = Region(xmin, ymin, xmax-xmin, ymax-ymin)\n newRegion.highlight()\n raw_input('Ready')\n\n\n\ndef _prep_cleanup():\n mySignal = signal.SIGINT\n currSignalFunc = signal.getsignal(mySignal)\n def mySignalFunc(*args, **kwargs):\n print('In my signal func')\n _cleanup()\n currSignalFunc(*args, **kwargs)\n signal.signal(mySignal, mySignalFunc)\n\ndef _cleanup():\n print('In cleanup')\n keyUp()\n try:\n _show_cursor()\n except:\n pass\n\nif __name__ == \"__main__\":\n '''\n To enable stop signals to be caught:\n In PyCharm hit Ctrl + Shift + A to bring up the \"Find Actions...\" menu\n Search for \"Registry\" and hit enter\n Find the key kill.windows.processes.softly and enable it (you can start typing \"kill\" and it will search for the key)\n Restart PyCharm\n \n Stop signals will now be sent as SIGINT\n '''\n print('Make sure verticle camera is set')\n if sys.argv[1] in locals():\n Settings.ActionLogs = False\n try:\n _show_cursor()\n except:\n pass\n _prep_cleanup()\n try:\n eval(sys.argv[1])()\n beep(500)\n except:\n _cleanup()\n for _ in range(3):\n beep(200)\n raise","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":48876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"31999794","text":"from Task1 import scrap_movie_list\nimport os \nimport requests\nimport time\nimport random\n\nmovies=scrap_movie_list()\nmovie=movies[:100]\ndef text_file():\n for i in movie:\n # print(i)\n time_1=random.randint(1,3)\n path=(\"/home/admin123/Desktop/web scraping/eight_task\"+i[\"Moviename\"]+\".text\")\n if os.path.exists(path):\n pass\n else:\n creating=open(\"/home/admin123/Desktop/web scraping/task9.text\"+i[\"Moviename\"]+\".text\",\"w+\")\n url=requests.get(i[\"url\"])\n a=creating.write(url.text)\n time.sleep(time_1)\n creating.close()\n\ntext_file()\n\n\n\n\n\n","sub_path":"Task9+.py","file_name":"Task9+.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"53731637","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport mock\n\nfrom tuskarclient.common import base\nfrom tuskarclient.tests import utils as tutils\n\n\nclass ManagerTest(tutils.TestCase):\n\n def setUp(self):\n super(ManagerTest, self).setUp()\n self.api = mock.Mock()\n self.m = base.Manager(self.api)\n\n def test_get(self):\n self.m._list = mock.Mock(return_value=['fake_resource'])\n got = self.m._get('url', response_key='response_key',\n obj_class='obj_class', body='body')\n\n self.assertEqual('fake_resource', got)\n self.m._list.assert_called_with('url', response_key='response_key',\n obj_class='obj_class',\n body='body', expect_single=True)\n\n def test_get_nonexistent(self):\n self.m._list = mock.Mock(return_value=[])\n got = self.m._get('url', response_key='response_key',\n obj_class='obj_class', body='body')\n\n self.assertEqual(None, got)\n self.m._list.assert_called_with('url', response_key='response_key',\n obj_class='obj_class',\n body='body', expect_single=True)\n\n def test_path(self):\n self.assertRaises(NotImplementedError, self.m._path)\n\n def test_single_path(self):\n self.m._path = mock.Mock(return_value='/v1/somethings/42')\n self.m._single_path(42)\n self.m._path.assert_called_with(42)\n\n def test_single_path_without_id(self):\n self.assertRaises(ValueError, self.m._single_path, None)\n","sub_path":"tuskarclient/tests/common/test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"189282515","text":"import os, json, redis, logging\nfrom flask import Flask, Response, request\nfrom logging.handlers import RotatingFileHandler\n\nlog_handler = RotatingFileHandler('/var/log/api.log', maxBytes=100000, backupCount=10)\nlog_handler = logging.StreamHandler()\nlog_handler.setFormatter(logging.Formatter(\"%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s\"))\n\napp = Flask(__name__)\napp.logger.setLevel(logging.DEBUG)\napp.logger.addHandler(log_handler)\n\n@app.route(\"/\")\ndef index():\n return \"OK\"\n\n@app.route(\"/keys/\", methods=['GET'])\ndef get_key(user_id):\n r = redis.Redis(host='cache', port=6379, db=0)\n data={\n 'endpoint':'get-key',\n 'result':'success',\n 'user_id': user_id\n }\n if r.hexists('wp_authorized_keys', user_id):\n data['authorized_key'] = r.hget('wp_authorized_keys', user_id)\n return Response(json.dumps(data))\n # not found\n data['result'] = 'failed'\n data['error_title'] = 'Not Found'\n data['error_description'] = 'The %s\\'s public key is not found.'%(user_id)\n return Response(json.dumps(data), 404)\n\n@app.route(\"/keys/\", methods=['POST'])\ndef post_key(user_id):\n # auth_key = request.form['authorized_key']\n # r = redis.Redis(host='cache', port=6379, db=0)\n # r.hset('wp_authorized_keys', user_id, auth_key)\n # update_authorized_keys(r.hgetall('wp_authorized_keys'))\n data={\n 'endpoint':'set-key',\n 'result':'success',\n 'user_id': user_id,\n 'test': r.hgetall('wp_authorized_keys')\n }\n return Response(json.dumps(data))\n\ndef update_authorized_keys(r):\n r.hgetall('wp_authorized_keys')\n pass\n\nif __name__ == \"__main__\":\n # r = redis.Redis(host='cache', port=6379, db=0)\n # update_authorized_keys(r.hgetall('wp_authorized_keys'))\n app.run(host='0.0.0.0', port=80)","sub_path":"20151201/files/api-server.py","file_name":"api-server.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"645377460","text":"'''\nGiven n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.\n\nNote: You may not slant the container and n is at least 2.\nExample:\n\nInput: [1,8,6,2,5,4,8,3,7]\nOutput: 49\n'''\nclass Solution:\n def maxArea(self, height: List[int]) -> int:\n l ,r = 0,len(height)-1\n lb ,ub = 0,len(height)-1\n maxcap = min(height[0],height[-1])*(len(height)-1)\n while l < r:\n if height[l]maxcap:\n maxcap = curcap\n return maxcap","sub_path":"11. Container With Most Water.py","file_name":"11. Container With Most Water.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"175098377","text":"from setuptools import setup, find_packages\nimport os.path\n\nname = \"zc.recipe.zope3checkout\"\n\ndef read(*rnames):\n return open(os.path.join(os.path.dirname(__file__), *rnames)).read()\n\nsetup(\n name = name,\n version = \"1.2\",\n author = \"Jim Fulton\",\n author_email = \"jim@zope.com\",\n description = \"ZC Buildout recipe for installing a Zope 3 checkout\",\n long_description=(\n read('README.txt')\n + '\\n' +\n read('CHANGES.txt')\n + '\\n' +\n 'Download\\n'\n '**********************\\n'\n ),\n license = \"ZPL 2.1\",\n keywords = \"zope3 buildout\",\n url='http://svn.zope.org/'+name,\n classifiers = [\n 'License :: OSI Approved :: Zope Public License',\n ],\n\n packages = find_packages('src'),\n include_package_data = True,\n package_dir = {'':'src'},\n namespace_packages = ['zc', 'zc.recipe'],\n install_requires = ['setuptools'],\n dependency_links = ['http://download.zope.org/distribution/'],\n entry_points = {'zc.buildout': ['default = %s:Recipe' % name]},\n )\n","sub_path":"zc.recipe.zope3checkout/trunk/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"62157109","text":"\"\"\"\n\"\"\"\n\nimport sys\nimport base\n\n# Global vars\nCITY = None\nOUTPUT = None\n\n\ndef order_waiting_rides(waiting_rides):\n \"\"\" Sorts waiting rides, in-place, by their earliest start time.\n \"\"\"\n waiting_rides.sort(key=lambda r: r.earliest_start)\n\n\ndef assign_vehicle_to_ride(ride, free_vehicles):\n \"\"\" Returns Vehicle object which should be assigned to the ride.\n \"\"\"\n free_vehicles.sort(key=lambda v: base.get_distance_between_points(\n v.current_position, ride.start_intersection))\n return free_vehicles[0]\n\n\ndef assign_rides(free_vehicles, waiting_rides):\n \"\"\" Returns a list of tuples; where the first item is a Vehicle and the\n second item is a Ride.\n \"\"\"\n assignments = []\n order_waiting_rides(waiting_rides)\n for ride in waiting_rides:\n if (len(free_vehicles) == 0):\n break\n v = assign_vehicle_to_ride(ride, free_vehicles)\n assignments.append((v, ride))\n free_vehicles.remove(v)\n v.step_busy_until += base.get_distance_between_points(\n v.current_position, ride.start_intersection) + ride.distance\n print('Vehicle', v.id, 'is now busy until step', v.step_busy_until)\n ride.is_taken = True\n OUTPUT[v.id].append(ride.id)\n return assignments\n\n\ndef output_file(file):\n filename = file[6:-3]\n contents = ''\n for item in OUTPUT:\n line = str(len(item))\n for a in item:\n line += ' ' + str(a)\n contents += line + '\\n'\n with open('output/' + filename + '.out', 'w') as f:\n f.write(contents)\n\n\ndef main(file):\n global CITY\n global OUTPUT\n CITY = base.City(file)\n OUTPUT = [[] for v in CITY.vehicles]\n print('THIS CITY IS:')\n print('---')\n print(CITY)\n print('---')\n for step in range(0, CITY.step_num):\n print('\\nSTEP', step, 'BEGIN')\n free_vehicles = CITY.get_free_vehicles(step)\n waiting_rides = CITY.get_waiting_rides()\n if (len(free_vehicles) > 0 and len(waiting_rides) > 0):\n assignments_to_make = assign_rides(free_vehicles, waiting_rides)\n print('Assignments made this step:')\n for a in assignments_to_make:\n print('(' + str(a[0].id) + ', ' + str(a[1].id) + ')')\n output_file(file)\n\n\nif (__name__ == '__main__'):\n if (len(sys.argv) == 2):\n main(sys.argv[1])\n else:\n print('Invalid arguments.')\n","sub_path":"src/naive.py","file_name":"naive.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"592402762","text":"#coding=utf-8\nimport unittest\nimport HTMLTestRunner\n\nclass TestMethod(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.comn = 1001\n print(\"所有case运行之前只运行一次...\\n\")\n\n # @classmethod\n # def tearDownClass(cls):\n # print(\"类执行之后的方法\")\n\n # def setUp(self):\n # print(\"setUp是在测试函数调用前执行\")\n\n # def tearDown(self):\n # print(\"tearDown是在之后执行\")\n\n def test01(self):\n print(\"这是第一个测试方法。。。\")\n s = self.comn\n print(s)\n\n def test02(self):\n print(\"这是第二个测试方法。。。\")\n s = self.comn\n print(s)\n\n\nif __name__ == '__main__':\n print(\"开始main\")\n filepath = \"../report/htmltestrunner.html\"\n fp = open(filepath,'wb')\n suite = unittest.TestSuite()\n suite.addTest(TestMethod('test01'))\n suite.addTest(TestMethod('test02'))\n html = HTMLTestRunner.HTMLTestRunner(stream=fp,title=\"接口测试报告\")\n html.run(suite)\n print(html)\n","sub_path":"base_test/UnittestOne.py","file_name":"UnittestOne.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"326021848","text":"\"\"\"\nGiven an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.\n\nYou may return any answer array that satisfies this condition.\n\nInput: [3,1,2,4]\nOutput: [2,4,3,1]\nThe outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.\n\"\"\"\n\nclass Solution:\n def sortArrayByParity(self, A: List[int]) -> List[int]:\n n = len(A)\n res = [0 for i in range(n)]\n left,right = 0, n-1\n for i,v in enumerate(A):\n if A[i] % 2 == 0:\n res[left] = A[i]\n left += 1\n else:\n res[right] = A[i]\n right -= 1\n return res\n\n# Time Complexity = O(n)\n# Space Complexity = O(n)\n","sub_path":"sortArrayByParity.py","file_name":"sortArrayByParity.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"579196024","text":"\n\n#calss header\nclass _FIRST():\n\tdef __init__(self,): \n\t\tself.name = \"FIRST\"\n\t\tself.definitions = [u'before all others in order, time, amount, quality, or importance: ', u'for the first time: ', u'used at the beginning of a list of things you want to say or write: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adverbs'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adverbs/_first.py","file_name":"_first.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"197402890","text":"# What does this piece of code do?\n# Answer: find the primer factor of a number between 1 and 100\n\n# Import libraries\n# randint allows drawing a random number, \n# e.g. randint(1,5) draws a number between 1 and 5\nfrom random import randint\n\n# ceil takes the ceiling of a number, i.e. the next higher integer.\n# e.g. ceil(4.2)=5\nfrom math import ceil\n\np=False #set p is False to get into the loop\nwhile p==False:\n p=True\n n = randint(1,100) #get a number that is between 1 and 100\n u = ceil(n**(0.5)) #take the ceiling of the square root of n\n for i in range(2,u+1): #find the primer factor of n\n if n%i == 0: # if there is still a primer factor, change p to False so that n can get into the loop again\n p=False\n\n\n \nprint(n)\n","sub_path":"Practical5/mystery_code.py","file_name":"mystery_code.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"432916879","text":"from itertools import groupby\n\nfrom corehq.apps.tzmigration.timezonemigration import is_datetime_string, FormJsonDiff\n\nPARTIAL_DIFFS = {\n 'XFormInstance*': [\n {'path': ('_rev',)},\n {'path': ('migrating_blobs_from_couch',)},\n {'path': ('#export_tag',)},\n {'path': ('computed_',)},\n {'path': ('state',)},\n {'path': ('computed_modified_on_',)},\n {'path': ('deprecated_form_id',)},\n {'path': ('path',)},\n {'path': ('user_id',)},\n {'path': ('external_blobs',)},\n {'diff_type': 'type', 'path': ('openrosa_headers', 'HTTP_X_OPENROSA_VERSION')},\n ],\n 'XFormInstance': [\n {'path': ('problem',)},\n {'path': ('orig_id',)},\n {'path': ('edited_on',)},\n ],\n 'XFormInstance-Deleted': [\n {'path': ('problem',)},\n {'path': ('orig_id',)},\n {'path': ('edited_on',)},\n ],\n 'HQSubmission': [\n {'path': ('problem',)},\n {'path': ('orig_id',)},\n {'path': ('edited_on',)},\n ],\n 'XFormArchived': [\n {'path': ('edited_on',)},\n ],\n 'XFormError': [\n {'path': ('edited_on',)},\n ],\n 'XFormDuplicate': [\n {'path': ('edited_on',)},\n ],\n 'XFormDeprecated': [],\n 'CommCareCase': [\n {'path': ('_rev',)},\n {'path': ('initial_processing_complete',)},\n {'path': ('actions', '[*]')},\n {'path': ('id',)},\n {'path': ('@xmlns',)},\n {'path': ('_attachments',)},\n {'path': ('#export_tag',)},\n {'path': ('computed_',)},\n {'path': ('version',)},\n {'path': ('case_attachments',)},\n {'path': ('deleted',)},\n {'path': ('export_tag',)},\n {'path': ('computed_modified_on_',)},\n {'path': ('case_id',)},\n {'path': ('@case_id',)},\n {'path': ('case_json',)},\n {'path': ('modified_by',)},\n {'path': ('indices', '[*]', 'case_id')},\n {'diff_type': 'diff', 'path': ('owner_id',), 'old_value': ''},\n {'diff_type': 'type', 'path': ('owner_id',), 'old_value': None},\n ],\n 'LedgerValue': [\n {'path': ('_id',)},\n ],\n 'case_attachment': [\n {'path': ('doc_type',)},\n {'path': ('attachment_properties',)},\n {'path': ('attachment_from',)},\n {'path': ('attachment_src',)},\n {'path': ('content_type',)},\n {'path': ('server_mime',)},\n {'path': ('attachment_name',)},\n {'path': ('server_md5',)},\n ]\n}\n\n\nFORM_IGNORED_DIFFS = (\n FormJsonDiff(\n diff_type=u'missing', path=(u'history', u'[*]', u'doc_type'),\n old_value=u'XFormOperation', new_value=Ellipsis\n ),\n FormJsonDiff(\n diff_type=u'diff', path=(u'doc_type',),\n old_value=u'HQSubmission', new_value=u'XFormInstance'\n ),\n FormJsonDiff(diff_type=u'missing', path=(u'deleted_on',), old_value=Ellipsis, new_value=None),\n FormJsonDiff(diff_type=u'missing', path=(u'location_',), old_value=[], new_value=Ellipsis),\n FormJsonDiff(diff_type=u'missing', path=(u'form', u'case', u'#text'), old_value=u'', new_value=Ellipsis),\n FormJsonDiff(diff_type=u'type', path=(u'xmlns',), old_value=None, new_value=u''),\n FormJsonDiff(diff_type=u'type', path=(u'initial_processing_complete',), old_value=None, new_value=True),\n FormJsonDiff(diff_type=u'missing', path=(u'backend_id',), old_value=Ellipsis, new_value=u'sql'),\n)\n\nCASE_IGNORED_DIFFS = (\n FormJsonDiff(diff_type=u'type', path=(u'name',), old_value=u'', new_value=None),\n FormJsonDiff(diff_type=u'type', path=(u'closed_by',), old_value=u'', new_value=None),\n FormJsonDiff(diff_type=u'missing', path=(u'location_id',), old_value=Ellipsis, new_value=None),\n FormJsonDiff(\n diff_type=u'missing', path=(u'indices', u'[*]', u'doc_type'),\n old_value=u'CommCareCaseIndex', new_value=Ellipsis),\n FormJsonDiff(diff_type=u'missing', path=(u'referrals',), old_value=[], new_value=Ellipsis),\n FormJsonDiff(diff_type=u'missing', path=(u'location_',), old_value=[], new_value=Ellipsis),\n FormJsonDiff(diff_type=u'type', path=(u'type',), old_value=None, new_value=u''),\n # this happens for cases where the creation form has been archived but the case still has other forms\n FormJsonDiff(diff_type=u'type', path=(u'owner_id',), old_value=None, new_value=u''),\n FormJsonDiff(diff_type=u'missing', path=(u'closed_by',), old_value=Ellipsis, new_value=None),\n FormJsonDiff(diff_type=u'type', path=(u'external_id',), old_value=u'', new_value=None),\n FormJsonDiff(diff_type=u'missing', path=(u'deleted_on',), old_value=Ellipsis, new_value=None),\n FormJsonDiff(\n diff_type=u'missing', path=(u'indices', u'[*]', u'relationship'),\n old_value=Ellipsis, new_value=u'child'\n ),\n FormJsonDiff(diff_type=u'missing', path=(u'backend_id',), old_value=Ellipsis, new_value=u'sql'),\n)\n\nRENAMED_FIELDS = {\n 'XFormDeprecated': [('deprecated_date', 'edited_on')],\n 'XFormInstance-Deleted': [('-deletion_id', 'deletion_id'), ('-deletion_date', 'deleted_on')],\n 'CommCareCase': [('@user_id', 'user_id'), ('@date_modified', 'modified_on')],\n 'CommCareCase-Deleted': [('-deletion_id', 'deletion_id'), ('-deletion_date', 'deleted_on')],\n 'case_attachment': [('attachment_size', 'content_length'), ('identifier', 'name')],\n}\n\n\ndef filter_form_diffs(doc_type, diffs):\n filtered = _filter_exact_matches(diffs, FORM_IGNORED_DIFFS)\n partial_diffs = PARTIAL_DIFFS[doc_type] + PARTIAL_DIFFS['XFormInstance*']\n filtered = _filter_partial_matches(filtered, partial_diffs)\n filtered = _filter_renamed_fields(filtered, doc_type)\n filtered = _filter_date_diffs(filtered)\n return filtered\n\n\ndef filter_case_diffs(couch_case, sql_case, diffs):\n doc_type = couch_case['doc_type']\n filtered_diffs = _filter_exact_matches(diffs, CASE_IGNORED_DIFFS)\n filtered_diffs = _filter_partial_matches(filtered_diffs, PARTIAL_DIFFS['CommCareCase'])\n filtered_diffs = _filter_renamed_fields(filtered_diffs, doc_type)\n filtered_diffs = _filter_date_diffs(filtered_diffs)\n filtered_diffs = _filter_user_case_diffs(couch_case, filtered_diffs)\n filtered_diffs = _filter_xform_id_diffs(couch_case, sql_case, filtered_diffs)\n filtered_diffs = _filter_case_attachment_diffs(filtered_diffs)\n return filtered_diffs\n\n\ndef filter_ledger_diffs(diffs):\n return _filter_partial_matches(diffs, PARTIAL_DIFFS['LedgerValue'])\n\n\ndef _filter_exact_matches(diffs, diffs_to_ignore):\n return [\n diff for diff in diffs\n if diff not in diffs_to_ignore\n ]\n\n\ndef _filter_partial_matches(diffs, partial_diffs_to_exclude):\n \"\"\"Filter out diffs that match a subset of attributes\n :type partial_diffs_to_exclude: dict([(attr, value)...])\n \"\"\"\n def _partial_match(diff):\n for partial in partial_diffs_to_exclude:\n if all(getattr(diff, attr) == val for attr, val in partial.items()):\n return True\n return False\n\n return [\n diff for diff in diffs\n if not _partial_match(diff)\n ]\n\n\ndef _filter_renamed_fields(diffs, doc_type):\n if doc_type in RENAMED_FIELDS:\n renames = RENAMED_FIELDS[doc_type]\n for rename in renames:\n _check_renamed_fields(diffs, *rename)\n\n return diffs\n\n\ndef _check_renamed_fields(filtered_diffs, couch_field_name, sql_field_name):\n from corehq.apps.tzmigration.timezonemigration import FormJsonDiff\n sql_fields = [diff for diff in filtered_diffs if diff.path[0] == sql_field_name]\n couch_fields = [diff for diff in filtered_diffs if diff.path[0] == couch_field_name]\n if sql_fields and couch_fields:\n sql_field = sql_fields[0]\n couch_field = couch_fields[0]\n filtered_diffs.remove(sql_field)\n filtered_diffs.remove(couch_field)\n if couch_field.old_value != sql_field.new_value:\n filtered_diffs.append(FormJsonDiff(\n diff_type='complex', path=(couch_field_name, sql_field_name),\n old_value=couch_field.old_value, new_value=sql_field.new_value\n ))\n\n\ndef _filter_date_diffs(diffs):\n def _both_dates(old, new):\n return is_datetime_string(old) and is_datetime_string(new)\n\n return [\n diff for diff in diffs\n if diff.diff_type not in ('diff', 'complex') or not _both_dates(diff.old_value, diff.new_value)\n ]\n\n\ndef _filter_user_case_diffs(couch_case, diffs):\n \"\"\"SQL cases store the hq_user_id property in ``external_id`` for easier querying\"\"\"\n if 'hq_user_id' not in couch_case:\n return diffs\n\n hq_user_id = couch_case['hq_user_id']\n external_id_diffs = [diff for diff in diffs if diff.diff_type == 'diff' and diff.path == (u'external_id',)]\n for diff in external_id_diffs:\n if diff.old_value in ('', Ellipsis, None) and diff.new_value == hq_user_id:\n diffs.remove(diff)\n\n return diffs\n\n\ndef _filter_xform_id_diffs(couch_case, sql_case, diffs):\n \"\"\"Some couch docs have the xform ID's out of order so assume that\n if both docs contain the same set of xform IDs then they are the same\"\"\"\n xform_id_diffs = {\n diff for diff in diffs if diff.path == ('xform_ids', '[*]')\n }\n if not xform_id_diffs:\n return diffs\n\n ids_in_couch = set(couch_case['xform_ids'])\n ids_in_sql = set(sql_case['xform_ids'])\n if ids_in_couch ^ ids_in_sql:\n couch_only = ','.join(list(ids_in_couch - ids_in_sql))\n sql_only = ','.join(list(ids_in_sql - ids_in_couch))\n diffs.append(\n FormJsonDiff(diff_type='set_mismatch', path=('xform_ids', '[*]'), old_value=couch_only, new_value=sql_only)\n )\n else:\n diffs.append(\n FormJsonDiff(diff_type='list_order', path=('xform_ids', '[*]'), old_value=None, new_value=None)\n )\n\n return [diff for diff in diffs if diff not in xform_id_diffs]\n\n\ndef _filter_case_attachment_diffs(diffs):\n attachment_diffs = [diff for diff in diffs if diff.path[0] == 'case_attachments']\n if not attachment_diffs:\n return diffs\n\n diffs = [diff for diff in diffs if diff not in attachment_diffs]\n\n grouped_diffs = groupby(attachment_diffs, lambda diff: diff.path[1])\n for name, group in grouped_diffs:\n group = list(group)\n normalized_diffs = [\n FormJsonDiff(diff_type=diff.diff_type, path=(diff.path[-1],), old_value=diff.old_value, new_value=diff.new_value)\n for diff in group\n ]\n filtered = _filter_partial_matches(normalized_diffs, PARTIAL_DIFFS['case_attachment'])\n filtered = _filter_renamed_fields(filtered, 'case_attachment')\n if filtered:\n diffs.extend([\n FormJsonDiff(\n diff_type=diff.diff_type, path=(u'case_attachments', name, diff.path[-1]),\n old_value=diff.old_value, new_value=diff.new_value\n ) for diff in filtered\n ])\n\n return diffs\n\n","sub_path":"corehq/apps/couch_sql_migration/diff.py","file_name":"diff.py","file_ext":"py","file_size_in_byte":10871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"256550856","text":"import email\nimport email.header\nimport imaplib\nimport sys\nfrom BeautifulSoup import BeautifulSoup\nimport mechanize\n\n\n\ndef verify_email(M):\n print('Checking the mailbox.')\n br = mechanize.Browser()\n br.addheaders = [('User-agent', 'Firefox')]\n\n # Sort through the emails for any from noreply@pokemon.com\n # Todo: Maybe make it a variable, so the script can be used for other stuff...?\n # ^ Probably not, the account creation is specific to the forms\n M.select('inbox')\n rv, data = M.search(None, '(FROM \"noreply@pokemon.com\")')\n if rv != 'OK' or data[0] == '' :\n print('No messages found!')\n return False\n\n # The main loop that gets the emails and activates them\n\n for num in data[0].split():\n\n # Attempts the fetch, and attempts again if an error is thrown\n # This previously would cause an error that stopped the script,\n # lets see if it can do it's bullshit this time when I a fuck\n # it with a while loop\n\n\n try:\n rv, data = M.fetch(num, 'RFC822')\n except:\n print('Fetch command failed, restarting the function')\n verify_email(M)\n break\n\n if rv != 'OK':\n print('Error getting message')\n return\n\n msg = email.message_from_string(data[0][1])\n decode = email.header.decode_header(msg['Subject'])[0]\n subject = unicode(decode[0], 'utf-8')\n body = email.message_from_string(data[0][1])\n\n\n # IMAP doesn't give the entire email body in one go\n # So, we have to loop through the body if it is larger\n # than one part. Otherwise, it's one part and done\n\n if body.is_multipart():\n for payload in body.get_payload():\n\n # Beautiful soup filters out all the href links\n # inside the email bodies, and then I check if\n # the link contains the word \"activated\", which\n # is in all pokemon go activation links. Then I\n # delete the email.\n\n soup = BeautifulSoup(payload.get_payload())\n for link in soup.findAll('a'):\n link = link.get('href')\n if \"activated\" in link:\n\n # Pretty sure this activates the link, could be fucked later on though\n tried = 0\n while tried < 5:\n try:\n print('Attempting to activate: %s' % tried)\n br.open(link)\n break\n except:\n tried += 1\n print(\"%s\", link)\n M.store(num, '+FLAGS', '\\\\Deleted')\n M.store(num, '+X-GM-LABELS', '\\\\Trash')\n M.expunge()\n\n else:\n\n # Beautiful soup filters out all the href links\n # inside the email bodies, and then I check if\n # the link contains the word \"activated\", which\n # is in all pokemon go activation links. Then I\n # delete the email.\n\n soup = BeautifulSoup(body.get_payload())\n for link in soup.findAll('a'):\n link = link.get('href')\n if \"activated\" in link:\n\n # Pretty sure this activates the link, could be fucked later on though\n br.open(link)\n tried = 0\n while tried < 5:\n try:\n print('Attempting to activate: %s' % tried)\n br.open(link)\n break\n except:\n tried += 1\n print(\"%s\", link)\n M.store(num, '+FLAGS', '\\\\Deleted')\n M.expunge()\n return True\n print('Done checking emails')\n\n\ndef email_login(M, email, password):\n # Attempts a login with the data supplied in the header\n try:\n rv, data = M.login(email, password)\n except imaplib.IMAP4.error:\n print('Login failed!')\n sys.exit(1)\n\n # Selects the folder specified in the header\n rv, data = M.select('inbox')\n if rv == 'OK':\n print('Successful login')\n return True\n else:\n print(\"ERROR: Unable to open mailbox \", rv)\n return False\n\nif __name__ == \"__main__\":\n M = imaplib.IMAP4_SSL(\"imap.gmail.com\")\n email_login(M,'user','pwd')\n verify_email(M)","sub_path":"ptcaccount2/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":4552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"222153717","text":"from captureAgents import CaptureAgent\nimport random, time, util\nimport copy\nfrom game import Directions\nfrom util import nearestPoint\nfrom collections import defaultdict\nimport game\nimport copy\n\n\n# python capture.py -b astar_new -r MCTS_new -l RANDOM9968 pacman loops\n# python capture.py -r baselineTeam -b astar_new -l RANDOM3971 debug time and illegal\n# python capture.py -r baselineTeam -b astar_new -l RANDOM38 check normal back home\n\n\n# python capture.py -b astar_new -r MCTS_new -l RANDOM996\n# debug attackloop\n\n# python capture.py -r astar_new -b AAA -l RANDOM5267\n# avoid powerful pacman\n\n\n#################\n# Team creation #\n#################\n\ndef createTeam(firstIndex, secondIndex, isRed,\n first='OffensiveAgent', second='DefensiveAgent'):\n # The following line is an example only; feel free to change it.\n return [eval(first)(firstIndex), eval(second)(secondIndex)]\n\n\n##########\n# Agents #\n##########\n\nclass DefensiveAgent(CaptureAgent):\n \"\"\"\n defensive agent, use simple heuristic search\n \"\"\"\n\n # register the initial state\n def registerInitialState(self, gameState):\n CaptureAgent.registerInitialState(self, gameState)\n\n self.boundary = []\n\n if self.red:\n mid_line = (gameState.data.layout.width - 2) // 2\n else:\n mid_line = (gameState.data.layout.width - 2) // 2 + 1\n\n for i in range(5, gameState.data.layout.height - 5):\n if not gameState.hasWall(mid_line, i):\n self.boundary.append((mid_line, i))\n\n self.defendFoods = self.getDefendFoods(gameState)\n self.target = None\n self.previousFoodList = self.getFoodYouAreDefending(gameState).asList()\n\n def getDefendFoods(self, gameState):\n food_list = self.getFoodYouAreDefending(gameState).asList()\n defend = []\n\n for boundary in self.boundary:\n min_dis = 10000\n target = None\n for food in food_list:\n if self.getMazeDistance(food, boundary) < min_dis:\n min_dis = self.getMazeDistance(food, boundary)\n target = food\n if target is not None:\n defend.append(target)\n\n return defend\n\n def getTarget(self, gameState):\n pos = gameState.getAgentState(self.index).getPosition()\n cur_food = self.getFoodYouAreDefending(gameState).asList()\n\n if pos == self.target:\n goal = None\n else:\n goal = self.target\n\n enemies = []\n for index in self.getOpponents(gameState):\n enemy = gameState.getAgentState(index)\n if enemy.getPosition() is not None:\n if enemy.isPacman:\n enemies.append(enemy)\n\n # defender should always be ghost\n if not gameState.getAgentState(self.index).isPacman:\n if len(enemies) > 0:\n min_dis = 10000\n target_pos = None\n for enemy in enemies:\n if self.getMazeDistance(pos, enemy.getPosition()) < min_dis:\n min_dis = self.getMazeDistance(pos, enemy.getPosition())\n target_pos = enemy.getPosition()\n if gameState.getAgentState(self.index).scaredTimer > 0 and self.getMazeDistance(pos, target_pos) == 2:\n actions = gameState.getLegalActions(self.index)\n actions.remove('Stop')\n valid_move = []\n for action in actions:\n next_pos = gameState.generateSuccessor(self.index, action).getAgentState(\n self.index).getPosition()\n if not self.getMazeDistance(target_pos, next_pos) <= 1:\n valid_move.append(next_pos)\n if not len(valid_move) == 0:\n goal = random.choice(valid_move)\n else:\n goal = target_pos\n else:\n if len(list(set(self.previousFoodList))) > len(list(set(cur_food))):\n foodEaten = []\n for food in set(self.previousFoodList):\n if food not in set(cur_food):\n foodEaten.append(food)\n goal = random.choice(foodEaten)\n self.previousFoodList = cur_food\n\n if goal is None:\n if 4 >= len(cur_food) > 0:\n goal = random.choice(cur_food)\n else:\n self.defendFoods = self.getDefendFoods(gameState)\n defendArea = self.defendFoods\n defendArea.extend(self.boundary)\n goal = random.choice(defendArea)\n\n return goal\n\n def search(self, goal, gameState):\n actions = gameState.getLegalActions(self.index)\n actions.remove('Stop')\n min_dis = 10000\n chosen_action = random.choice(actions)\n\n for action in actions:\n successor = gameState.generateSuccessor(self.index, action)\n next_pos = successor.getAgentState(self.index).getPosition()\n if not successor.getAgentState(self.index).isPacman:\n distance = self.getMazeDistance(next_pos, self.target)\n else:\n enemies = []\n for index in self.getOpponents(gameState):\n enemy = gameState.getAgentState(index)\n if enemy.getPosition() is not None:\n if not enemy.isPacman and not enemy.scaredTimer > 0:\n enemies.append(enemy)\n if len(enemies) > 0:\n min_distance = 10000\n for enemy in enemies:\n if self.getMazeDistance(enemy.getPosition(), next_pos) < min_distance:\n min_distance = self.getMazeDistance(enemy.getPosition(), next_pos)\n if min_distance <= 2:\n continue\n else:\n distance = self.getMazeDistance(next_pos, self.target)\n else:\n distance = self.getMazeDistance(next_pos, self.target)\n\n if distance < min_dis:\n min_dis = distance\n chosen_action = action\n\n if chosen_action is None:\n return 'Stop'\n return chosen_action\n\n def chooseAction(self, gameState):\n self.target = self.getTarget(gameState)\n return self.search(self.target, gameState)\n\n\nclass OffensiveAgent(CaptureAgent):\n\n def registerInitialState(self, gameState):\n\n CaptureAgent.registerInitialState(self, gameState)\n\n '''\n Your initialization code goes here, if you need any.\n '''\n self.boundary = []\n if self.red:\n mid_line = (gameState.data.layout.width - 2) // 2\n enemy_line = mid_line + 1\n else:\n mid_line = (gameState.data.layout.width - 2) // 2 + 1\n enemy_line = mid_line - 1\n # consider opponent's wall at the same time\n for i in range(1, gameState.data.layout.height - 1):\n if not gameState.hasWall(mid_line, i) and not gameState.hasWall(enemy_line, i):\n self.boundary.append((mid_line, i))\n\n # maximum 300\n self.step = 0\n # avoid loop\n self.iterate = 0\n # safe distance with enemy\n self.safe_dis = 5 + 3\n # avoid loop, record the steps of each pos\n self.step_pos = defaultdict(int)\n self.goal = None\n\n # same function as in baselineTeam\n def getSuccessor(self, gameState, action):\n successor = gameState.generateSuccessor(self.index, action)\n pos = successor.getAgentState(self.index).getPosition()\n if pos != nearestPoint(pos):\n return successor.generateSuccessor(self.index, action)\n else:\n return successor\n\n def initialAction(self, gameState):\n pos = gameState.getAgentState(self.index).getPosition()\n capsule_list = self.getCapsules(gameState)\n self.step += 1\n # store all enemies, no matter ghost or pacman\n enemies = []\n for index in self.getOpponents(gameState):\n enemy = gameState.getAgentState(index)\n if enemy.getPosition() is not None:\n enemies.append(enemy)\n return pos, capsule_list, enemies\n\n def enterBoundary(self, gameState, actions):\n pos, capsule_list, enemies = self.initialAction(gameState)\n self.cur_foods = self.getFood(gameState).asList()\n if self.goal is None or not self.goal in self.boundary:\n self.goal = random.choice(self.boundary)\n if pos in self.boundary and self.step - self.step_pos[pos] <= 10:\n self.goal = random.choice(self.boundary)\n if pos in self.boundary and self.step - self.step_pos[pos] > 10:\n self.step_pos[pos] = self.step\n min_dis = 10000\n for enemy in enemies:\n if self.getMazeDistance(pos, enemy.getPosition()) < min_dis:\n min_dis = self.getMazeDistance(pos, enemy.getPosition())\n # if not dangerous, enter directly\n if min_dis >= 5:\n if self.red:\n return 'East'\n return 'West'\n else:\n # see if distance too close\n if self.red:\n successor = self.getSuccessor(gameState, 'East')\n else:\n successor = self.getSuccessor(gameState, 'West')\n next_pos = successor.getAgentState(self.index).getPosition()\n for enemy in enemies:\n if self.getMazeDistance(next_pos, enemy.getPosition()) <= 2 or \\\n self.getMazeDistance(next_pos, enemy.getPosition()) > 10:\n boundary = copy.deepcopy(self.boundary)\n boundary.remove(pos)\n # if has no choice now, back 1 step\n if len(boundary) == 0:\n for a in actions:\n successor = self.getSuccessor(gameState, a)\n next_pos = successor.getAgentState(self.index).getPosition()\n if self.getMazeDistance(next_pos, enemy.getPosition()) > 0:\n return a\n return 'Stop'\n self.goal = random.choice(boundary)\n return self.search(gameState, self.goal, actions)\n if self.red:\n return 'East'\n return 'West'\n else:\n # if has powerful pacman use avoid search\n if gameState.getAgentState(self.index).scaredTimer > 0:\n return self.avoid_search(gameState, self.goal, actions)\n else:\n action = self.search(gameState, self.goal, actions)\n return action\n\n # helper function for avoid_search\n def getClosestInvader(self, gameState, pos):\n invaders = []\n closest_invader = None\n for index in self.getOpponents(gameState):\n enemy = gameState.getAgentState(index)\n if enemy.getPosition() is not None and enemy.isPacman:\n invaders.append(enemy)\n dis_toInvader = 10000\n for invader in invaders:\n if self.getMazeDistance(pos, invader.getPosition()) < dis_toInvader:\n dis_toInvader = self.getMazeDistance(pos, invader.getPosition())\n closest_invader = invader.getPosition()\n return closest_invader\n\n def avoid_search(self, gameState, goal, actions, attack=True):\n pos = gameState.getAgentState(self.index).getPosition()\n avoid_pos = self.getClosestInvader(gameState, pos)\n min_dis = 10000\n chosen_action = None\n for action in actions:\n successor = self.getSuccessor(gameState, action)\n next_pos = successor.getAgentState(self.index).getPosition()\n if attack and successor.getAgentState(self.index).isPacman:\n continue\n if avoid_pos is not None and self.getMazeDistance(next_pos, avoid_pos) <= 1:\n continue\n if self.getMazeDistance(next_pos, goal) < min_dis:\n min_dis = self.getMazeDistance(next_pos, goal)\n chosen_action = action\n if chosen_action is None:\n return 'Stop'\n else:\n return chosen_action\n\n def attackMode(self, gameState, actions):\n pos, capsule_list, enemies = self.initialAction(gameState)\n # how many foods was eaten since last enter\n self.foodEaten = len(self.cur_foods) - len(self.getFood(gameState).asList())\n\n # find closest enemy, only ghost enemy\n closest_enemy = None\n ghosts = []\n for enemy in enemies:\n if not enemy.isPacman:\n ghosts.append(enemy)\n dis_toEnemy = 10000\n for ghost in ghosts:\n if self.getMazeDistance(pos, ghost.getPosition()) < dis_toEnemy:\n dis_toEnemy = self.getMazeDistance(pos, ghost.getPosition())\n closest_enemy = ghost\n\n # find closest home\n closest_home = None\n dis_toHome = 10000\n for boundary in self.boundary:\n if self.getMazeDistance(pos, boundary) < dis_toHome:\n dis_toHome = self.getMazeDistance(pos, boundary)\n closest_home = boundary\n\n # if has only 2 foods left or the dis to closest home equals to the left time, go back home\n # use BFS, not closest home, can easily stop\n if len(self.getFood(gameState).asList()) == 2 or dis_toHome >= 299 - self.step:\n return self.BFS(gameState, self.boundary, pos)\n\n # if not dangerous, eat foods\n if len(ghosts) == 0 or dis_toEnemy > self.safe_dis:\n score = self.getScore(gameState)\n if score >= 1:\n action, des, cost = self.astar(gameState, 1)\n else:\n action, des, cost = self.astar(gameState, 2)\n return action\n\n scared = False\n if closest_enemy.scaredTimer > 0:\n scared = True\n # if enemy scared, eat foods\n if scared:\n action, des, cost = self.astar(gameState, 2)\n live = self.boundary + capsule_list\n dis_toHome = 10000\n for boundary in self.boundary:\n if self.getMazeDistance(des, boundary) < dis_toHome:\n dis_toHome = self.getMazeDistance(des, boundary)\n closest_home = boundary\n\n closest_life = None\n dis_toLife = 10000\n for item in live:\n if self.getMazeDistance(des, item) < dis_toLife:\n dis_toLife = self.getMazeDistance(des, item)\n closest_life = item\n\n # if cost to food plus time back home equals to left time, go back home\n if cost + dis_toHome >= 300 - self.step:\n self.goal = closest_home\n return self.search(gameState, self.goal, actions, False)\n # if cost to food plus dis to safe place, go to food\n if cost + dis_toLife < closest_enemy.scaredTimer:\n return action\n else:\n self.goal = closest_life\n return self.search(gameState, self.goal, actions, False)\n else:\n # when not scared, use BFS\n # if has eaten less than 2 foods, go to capsule\n live = self.boundary + capsule_list\n if self.foodEaten >= 2:\n goals = live\n else:\n if len(capsule_list) > 0:\n goals = capsule_list\n action = self.BFS(gameState, goals, pos)\n if action == 'Stop':\n if self.safe_dis - 1 / 4 <= 2:\n self.safe_dis = 2\n else:\n self.safe_dis -= 1 / 4\n goals = self.boundary\n else:\n if self.safe_dis - 1 / 4 <= 2:\n self.safe_dis = 2\n else:\n self.safe_dis -= 1 / 4\n goals = self.boundary\n action = self.BFS(gameState, goals, pos)\n action = self.attackLoop(gameState, action, pos)\n return action\n\n # pacman can easily loop when meet not scared pacman\n # if has no wall, go back for 1 step\n def attackLoop(self, gameState, action, pos):\n # remain stop here\n if self.getPreviousObservation() is not None:\n previous_direction = self.getPreviousObservation().getAgentState(self.index).configuration.direction\n else:\n previous_direction = None\n\n reverse = Directions.REVERSE[gameState.getAgentState(self.index).configuration.direction]\n if reverse == previous_direction:\n self.iterate += 1\n else:\n self.iterate = 0\n\n # see if ghost is at east or west\n enemy_pos = self.findClosestEnemy(gameState, pos)\n # if at east, back west\n if enemy_pos[0] - pos[0] > 0:\n back = 'West'\n elif enemy_pos[0] - pos[0] < 0:\n back = 'East'\n else:\n back = action\n\n if self.iterate >= 5:\n # when back and has no wall\n if back in gameState.getLegalActions(self.index):\n action = back\n else:\n action = random.choice(gameState.getLegalActions(self.index))\n\n return action\n\n # avoid loop within 5 steps\n def removeLoop(self, gameState, actions):\n actions.remove('Stop')\n if self.getPreviousObservation() is not None:\n previous_direction = self.getPreviousObservation().getAgentState(self.index).configuration.direction\n else:\n previous_direction = None\n\n reverse = Directions.REVERSE[gameState.getAgentState(self.index).configuration.direction]\n if reverse == previous_direction:\n self.iterate += 1\n else:\n self.iterate = 0\n\n if self.iterate >= 5:\n actions.remove(reverse)\n\n return actions\n\n def search(self, gameState, goal, actions, attack=True):\n min_dis = 10000\n chosen_action = None\n for action in actions:\n successor = self.getSuccessor(gameState, action)\n next_pos = successor.getAgentState(self.index).getPosition()\n if attack and successor.getAgentState(self.index).isPacman:\n continue\n if self.getMazeDistance(next_pos, goal) < min_dis:\n min_dis = self.getMazeDistance(next_pos, goal)\n chosen_action = action\n if chosen_action is None:\n return 'Stop'\n else:\n return chosen_action\n\n # use heuristic search to eat foods,when safe, return an action,destination and cost\n def astar(self, gameState, goals):\n open_list = util.PriorityQueue()\n closed = []\n best_g = {}\n actions = []\n cur_goals = goals\n initial_foods = self.getFood(gameState).asList()\n if len(initial_foods) < 2:\n cur_goals = 1\n # if has eaten food, eat one\n if self.foodEaten >= 1:\n cur_goals = 1\n pos = gameState.getAgentState(self.index).getPosition()\n best_g[pos] = 0\n open_list.push((gameState, actions, 0), 0 + self.h(gameState, cur_goals, initial_foods))\n\n while not open_list.isEmpty():\n cur_state, actions, cost = open_list.pop()\n cur_pos = cur_state.getAgentState(self.index).getPosition()\n if cur_pos not in closed or cost < best_g[cur_pos]:\n closed.append(cur_pos)\n best_g[cur_pos] = cost\n # see how many foods has eaten in this astar, if reached goals, return\n cur_foods = self.getFood(cur_state).asList()\n if len(initial_foods) - len(cur_foods) >= cur_goals:\n if len(actions) == 0:\n return 'Stop', cur_pos, cost\n return actions[0], cur_pos, cost\n for a in cur_state.getLegalActions(self.index):\n successor = self.getSuccessor(cur_state, a)\n if successor.getAgentState(self.index).isPacman:\n if successor.getAgentState(self.index).getPosition() not in closed:\n eaten = len(initial_foods) - len(cur_foods)\n open_list.push((successor, actions + [a], cost + 1), cost + 1 + self.h(\n successor, cur_goals - eaten, cur_foods))\n\n if goals > 0:\n goals -= 1\n return self.astar(gameState, goals)\n else:\n a = random.choice(gameState.getLegalActions(self.index))\n if a is None:\n return 'Stop', pos, 0\n return a, pos, 0\n\n # heuristic function, find closest food\n def h(self, gameState, goals, foods):\n pos = gameState.getAgentState(self.index).getPosition()\n # if eat one, choose the closest food, if two, use combined dis\n if goals == 1:\n min_dis = 10000\n for food in foods:\n if self.getMazeDistance(pos, food) < min_dis:\n min_dis = self.getMazeDistance(pos, food)\n return min_dis\n else:\n min_dis1 = min_dis2 = 10000\n for food in foods:\n if self.getMazeDistance(pos, food) < min_dis1:\n min_dis2 = min_dis1\n min_dis1 = self.getMazeDistance(pos, food)\n elif self.getMazeDistance(pos, food) < min_dis2:\n min_dis2 = self.getMazeDistance(pos, food)\n return min_dis2 + min_dis1\n\n # helper function for BFS, only avoid enemies that are not scared\n def findClosestEnemy(self, gameState, pos):\n enemies = []\n target = None\n for index in self.getOpponents(gameState):\n enemy = gameState.getAgentState(index)\n if enemy.getPosition() is not None and not enemy.scaredTimer > 0:\n if not enemy.isPacman:\n enemies.append(enemy)\n if len(enemies) > 0:\n min_dis = 1000\n for enemy in enemies:\n dis = self.getMazeDistance(enemy.getPosition(), pos)\n if dis < min_dis:\n min_dis = dis\n target = enemy.getPosition()\n return target\n\n def BFS(self, gameState, goals, pos):\n avoid_pos = self.findClosestEnemy(gameState, pos)\n open = util.Queue()\n closed = []\n actions = []\n open.push((gameState, actions))\n while not open.isEmpty():\n cur_state, actions = open.pop()\n cur_pos = cur_state.getAgentState(self.index).getPosition()\n if cur_pos not in closed:\n closed.append(cur_pos)\n if cur_pos in goals:\n if len(actions) == 0:\n return 'Stop'\n else:\n return actions[0]\n for a in cur_state.getLegalActions(self.index):\n successor = self.getSuccessor(cur_state, a)\n next_pos = successor.getAgentState(self.index).getPosition()\n if next_pos not in closed:\n if avoid_pos is not None and self.getMazeDistance(avoid_pos, next_pos) <= 1:\n continue\n open.push((successor, actions + [a]))\n\n return 'Stop'\n\n def chooseAction(self, gameState):\n \"\"\"\n Picks among actions for defending.\n \"\"\"\n actions = gameState.getLegalActions(self.index)\n\n '''\n You should change this in your own agent.\n '''\n\n new_actions = self.removeLoop(gameState, actions)\n\n if not gameState.getAgentState(self.index).isPacman:\n action = self.enterBoundary(gameState, new_actions)\n return action\n else:\n action = self.attackMode(gameState, new_actions)\n return action\n","sub_path":"myTeam.py","file_name":"myTeam.py","file_ext":"py","file_size_in_byte":24407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"306044263","text":"from opengever.core.upgrade import SQLUpgradeStep\nfrom plone import api\nfrom sqlalchemy.sql.expression import column\nfrom sqlalchemy.sql.expression import select\nfrom sqlalchemy.sql.expression import table\nfrom zope.app.intid.interfaces import IIntIds\nfrom zope.component import getUtility\nimport logging\n\n\nLOG = logging.getLogger('ftw.upgrade')\n\nfavorites_table = table(\n 'favorites',\n column('id'),\n column('plone_uid'),\n column('admin_unit_id'),\n column('int_id'),\n)\n\n\nclass CleanUpFavoritesForTrashedAndDeletedObjects(SQLUpgradeStep):\n \"\"\"Clean up favorites for trashed and deleted objects.\n \"\"\"\n\n deferrable = True\n\n def migrate(self):\n\n # We delete all favorites for trashed objects\n current_admin_unit_id = api.portal.get_registry_record(\n 'opengever.ogds.base.interfaces.IAdminUnitConfiguration.current_unit_id'\n )\n rows = self.execute(\n select([favorites_table.c.plone_uid])\n .where(favorites_table.c.admin_unit_id == current_admin_unit_id)\n .distinct()\n ).fetchall()\n favorite_uids = [row[0] for row in rows]\n\n query = {\"trashed\": True,\n \"UID\": favorite_uids}\n trashed_uids = [brain.UID for brain in\n self.catalog_unrestricted_search(query=query)]\n self.execute(\n favorites_table.delete()\n .where(favorites_table.c.plone_uid.in_(trashed_uids))\n .where(favorites_table.c.admin_unit_id == current_admin_unit_id))\n\n # Now we delete all favorites for objects that have been deleted, i.e.\n # that are not in the catalog\n intids = getUtility(IIntIds)\n\n rows = self.execute(\n select([favorites_table.c.int_id])\n .where(favorites_table.c.admin_unit_id == current_admin_unit_id)\n .distinct()\n ).fetchall()\n\n favorites_to_delete = [row[0] for row in rows if row[0] not in intids]\n self.execute(\n favorites_table.delete()\n .where(favorites_table.c.int_id.in_(favorites_to_delete))\n .where(favorites_table.c.admin_unit_id == current_admin_unit_id))\n","sub_path":"opengever/core/upgrades/20201207113732_clean_up_favorites_for_trashed_and_deleted_objects/upgrade.py","file_name":"upgrade.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"585354520","text":"# Car_gamming......\ncommand = \"\"\nwhile True: # command != \"quite\" :\n command = input(\"> \").lower()\n if command == \"start\" :\n print(\"Car started.......\")\n elif command == \"stop\" :\n print(\"Car stop..........\")\n elif command == \"help\" :\n print(\"\"\"\n Start - to start the car\n Stop - to stop the car\n Quite - to quite\n \"\"\")\n elif command == \"quite\" :\n break\n else:\n print('Sorry, i dont understand that...')","sub_path":"practice_mode/car_gamming.py","file_name":"car_gamming.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"610073516","text":"# Copyright 2014 - Rackspace\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport unittest\n\nfrom solumdashboard.common import workflow_parsers\n\n\nMISTRAL_DSL = {\n \"Namespaces\": {\n \"Nova\": {\n \"actions\": \"random data\"\n }\n },\n \"Workflow\": {\n \"tasks\": {\n \"createVM\": {\n \"action\": \"Nova.createVM\",\n \"parameters\": {\n \"nova_url\": \"$.nova_url\",\n \"auth_token\": \"$.auth_token\"\n },\n \"publish\": {\n \"vm_id\": \"vm_id\"\n },\n \"on-success\": \"waitForIP\"\n },\n \"waitForIP\": {\n \"action\": \"Nova.getIP\",\n \"publish\": {\n \"vm_ip\": \"vm_ip\"\n },\n \"parameters\": {\n \"nova_url\": \"$.nova_url\",\n \"project_id\": \"$.project_id\",\n \"auth_token\": \"$.auth_token\"\n },\n \"on-error\": \"errorTask\"\n }\n }\n }\n}\n\nHEAT_TEMPLATE = {\n \"heat_template_version\": \"2013-05-23\",\n \"description\": \"Basic app deploy.\",\n \"parameters\": {\n \"app_name\": {\n \"type\": \"string\",\n \"default\": \"solum-app\",\n \"description\": \"app name desc\"\n },\n \"key_name\": {\n \"type\": \"string\",\n \"default\": \"mykey\"\n }\n },\n \"randomstuff\": \"blah blah blah\"\n}\n\n\nclass TestWorkflowParsers(unittest.TestCase):\n \"\"\"Test routines for workflow parsing code.\"\"\"\n def test_get_mistral_tasks(self):\n \"\"\"Test get Mistral Tasks functionality.\"\"\"\n # Correct operation test case\n task_list = workflow_parsers.get_mistral_tasks(MISTRAL_DSL)\n self.assertEqual(task_list,\n [[\"createVM\", \"waitForIP\", None],\n [\"waitForIP\", None, \"errorTask\"]])\n # Missing \"tasks\" section from Workflow\n dsl_copy = MISTRAL_DSL.copy()\n dsl_copy[\"Workflow\"] = {\"garbage\": \"here\", \"nothing\": \"useful\"}\n self.assertRaises(KeyError, workflow_parsers.get_mistral_tasks,\n dsl_copy)\n # All tasks have an on-success condition (invalid DSL)\n dsl_copy = MISTRAL_DSL.copy()\n dsl_copy[\"Workflow\"][\"tasks\"][\"waitForIP\"][\"on-success\"] = \"noTask\"\n self.assertRaises(IndexError, workflow_parsers.get_mistral_tasks,\n dsl_copy)\n # None data test case\n self.assertRaises(TypeError, workflow_parsers.get_mistral_tasks, None)\n\n def test_get_mistral_required_input(self):\n \"\"\"Test get Mistral required user input functionality.\"\"\"\n # Handle None data\n self.assertRaises(TypeError, workflow_parsers.get_mistral_tasks, None)\n # Correct operation test case\n input_dict = workflow_parsers.get_mistral_required_input(MISTRAL_DSL)\n self.assertEqual(input_dict,\n {\"nova_url\": [\"createVM\", \"waitForIP\"],\n \"auth_token\": [\"createVM\", \"waitForIP\"],\n \"project_id\": [\"waitForIP\"]})\n # Remove the \"tasks\" section from Workflow\n dsl_copy = MISTRAL_DSL.copy()\n dsl_copy[\"Workflow\"] = {\"garbage\": \"here\", \"nothing\": \"useful\"}\n self.assertRaises(KeyError,\n workflow_parsers.get_mistral_required_input,\n dsl_copy)\n # Verify that a publish removes the input from the next task\n dsl_copy = MISTRAL_DSL.copy()\n dsl_copy[\"Workflow\"][\"tasks\"][\"createVM\"][\"publish\"] = (\n {\"project_id\": \"test project\"})\n input_dict = workflow_parsers.get_mistral_required_input(dsl_copy)\n self.assertEqual(input_dict,\n {\"nova_url\": [\"createVM\", \"waitForIP\"],\n \"auth_token\": [\"createVM\", \"waitForIP\"]})\n # Test ignoring of odd tags like \"arguments\"\n dsl_copy[\"Workflow\"][\"tasks\"][\"createVM\"][\"parameters\"] = (\n {\"key\": \"value\", \"arguments\": {\"random arguments\"}})\n input_dict = workflow_parsers.get_mistral_required_input(dsl_copy)\n self.assertEqual(input_dict,\n {\"key\": [\"createVM\"], \"nova_url\": [\"waitForIP\"],\n \"auth_token\": [\"waitForIP\"]})\n\n def test_get_heat_required_input(self):\n \"\"\"Test get Heat required user input functionality.\"\"\"\n # Handle None data\n self.assertRaises(TypeError, workflow_parsers.get_heat_required_input,\n None)\n # Remove the \"parameters\" section from the HoT\n hot_copy = {\"nothing_here\": \"error time\"}\n self.assertRaises(KeyError,\n workflow_parsers.get_heat_required_input,\n hot_copy)\n # Correct operation test case\n heat_list = workflow_parsers.get_heat_required_input(HEAT_TEMPLATE)\n self.assertEqual(heat_list,\n [[\"app_name\", \"string\", \"solum-app\", \"app name desc\"],\n [\"key_name\", \"string\", \"mykey\", None]])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"solumdashboard/tests/common/test_workflow_parsers.py","file_name":"test_workflow_parsers.py","file_ext":"py","file_size_in_byte":5669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"550726591","text":"# coding:utf-8\nfrom __future__ import print_function\n\nimport json\nimport random\nimport time\n\nimport requests\n\nfrom config import LOG_DIR\n\nurl = \"http://127.0.0.1:8000/trade.do\"\ntype_list = [\"buy\", \"sell\", \"buy_market\", \"sell_market\"]\nprice_list = (90, 110)\namount_list = (1, 100)\nclient_log = LOG_DIR + \"/client.log\"\n\n\ndef post_data():\n data = {\n \"type\": random.choice(type_list),\n \"amount\": random.randint(1, 100),\n \"price\": random.randint(90, 110)\n }\n r = requests.post(url, data=json.dumps(data))\n res = json.loads(r.content)\n if data[\"type\"] in [\"buy\", \"sell\"]:\n c_log = open(client_log, 'a')\n c_log.writelines(\"order_id:%s \\n\" % str(res[\"order_id\"]))\n c_log.close()\n print(res)\n\n\nwhile True:\n post_data()\n time.sleep(0.25)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"491249510","text":"#This script uses wget -i to use FTP to pull \n#each file specified by the text files within a folder \n#Katie Brennan 2016-09-19\n\nimport os\nimport sys\nimport glob\n#import wget\nimport urllib2\n\ninitial_dir = os.getcwd()\nftp_dir = initial_dir + '/he_cdif_ftp_directions'\ncdif_dir = initial_dir + '/he_genome_download'\nos.mkdir(cdif_dir)\n\nos.chdir(ftp_dir)\nfor file in glob.glob(\"*.txt\"): \n genome = os.path.basename(file)\n genome_id = genome[:-17]\n genome_dir = cdif_dir + '/'+genome_id\n os.mkdir(genome_dir)\n os.chdir(genome_dir)\n file_path = ftp_dir + '/'+file\n with open(file_path,'r') as genome_file:\n for line in genome_file:\n #wget.download(line) \n #urllib2.urlopen(line) \n os.system(\"wget\" + \" \"+ line)\n","sub_path":"2016-cdiff/2016-09-19-He-genomes-download/wget_i.py","file_name":"wget_i.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"303598680","text":"import random\ndef guessNumber(reference_num):\n\tcount = 0\n\twhile True:\n\t\tsystem_num = random.randint(1, 50)\n\t\t# print(\"---\"+str(system_num))\n\t\t# inn = input(\"Enter the number: \")\n\t\treceived_num = int(reference_num)\n\t\tcount += 1\n\n\t\tif received_num > system_num :\n\t\t\treturn \"Input is greater than guess number\"\n\t\telif received_num < system_num :\n\t\t\treturn \"Input is less than guess number\"\n\t\telse:\n\t\t\treturn \"Correct, Number of guesses : \" +str(count)\n\t\t\tbreak","sub_path":"Assignments/Module-9/guessNumber.py","file_name":"guessNumber.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"274159938","text":"import os\nimport sqlite3\nfrom contextlib import closing\nimport discord\n\n\nclient = discord.Client()\ndbname = os.path.join(os.path.dirname(__file__), 'prihel.db')\n\nwith open(\"./token.txt\") as f:\n token = f.read()\n\n# 文言\nhelptext = '''プリコネお助けBOTを使ってくれてありがとうございます!\nこのBOTは「!pb」から始まるコマンドで操作ができます。\n「!pb」のあとに半角スペースを入れてからコマンドを入力してください。\n\n● !pb [キャラクター名 or スキル名]\n→該当のキャラ(スキルを持つキャラ)の基本情報を表示します(あいまい検索)\n\n● !pb detail [キャラクター名 or スキル名]\n→該当のキャラ(スキルを持つキャラ)の詳細情報を表示します\n\n● !pb action [キャラクター名 or スキル名]\n→該当のキャラ(スキルを持つキャラ)の行動パターンを表示します\n'''\n\ndef searchid(rcvstr, amb): # ID検索\n ids = []\n\n with closing(sqlite3.connect(dbname)) as conn:\n conn.row_factory = sqlite3.Row\n c = conn.cursor()\n\n if amb == 0:\n chara = (rcvstr, rcvstr, rcvstr, rcvstr, rcvstr)\n sql = 'SELECT * FROM chara WHERE name=? OR ub=? OR s1=? OR s2=? OR ex=?'\n else:\n chara = (rcvstr, rcvstr, rcvstr, rcvstr, rcvstr, '%' + rcvstr + '%')\n sql = 'SELECT * FROM chara WHERE name=? OR ub=? OR s1=? OR s2=? OR ex=? OR name_amb LIKE ?'\n\n for cdata in c.execute(sql, chara):\n ids.append(cdata['id'])\n\n return ids\n\n\ndef basic(id): # 標準のデータ\n ans = [\"\", \"\"]\n\n with closing(sqlite3.connect(dbname)) as conn:\n conn.row_factory = sqlite3.Row\n c = conn.cursor()\n\n chara = (id,)\n sql = 'SELECT * FROM chara WHERE id=?'\n for cdata in c.execute(sql, chara):\n ans[0] = cdata['IMG']\n ans[1] += '☆' + cdata['name'] + \\\n '☆ [' + cdata['GUILD'] + '/' + cdata['POS'] + ']' + '\\n\\n'\n ans[1] += 'UB:' + cdata['UB'] + '\\n・' + \\\n cdata['UB_TEXT'] + '\\n\\n'\n ans[1] += 'S1:' + cdata['S1'] + '\\n・' + \\\n cdata['S1_TEXT'] + '\\n\\n'\n ans[1] += 'S2:' + cdata['S2'] + '\\n・' + \\\n cdata['S2_TEXT'] + '\\n\\n'\n ans[1] += 'EX:' + cdata['EX'] + '\\n・' + \\\n cdata['EX_TEXT'] + '\\n\\n'\n ans[1] += '◎ 「!pb detail ' + cdata['name'] + '」で詳細情報を表示' + '\\n'\n ans[1] += '◎ 「!pb action ' + cdata['name'] + '」で行動パターンを表示' + '\\n\\n'\n return ans\n\n\ndef detail(id): # 詳細データ\n ans = [\"\", \"\"]\n\n with closing(sqlite3.connect(dbname)) as conn:\n conn.row_factory = sqlite3.Row\n c = conn.cursor()\n\n chara = (id,)\n sql = 'SELECT * FROM chara WHERE id=?'\n for cdata in c.execute(sql, chara):\n ans[0] = cdata['IMG']\n ans[1] += '☆' + cdata['name'] + \\\n '☆ [' + cdata['GUILD'] + '/' + cdata['POS'] + ']' + '\\n\\n'\n ans[1] += 'UB:' + cdata['UB'] + '\\n・' + \\\n cdata['UB_TEXT'] + '\\n' + cdata['UB_COEF'] + '\\n\\n'\n ans[1] += 'S1:' + cdata['S1'] + '\\n・' + \\\n cdata['S1_TEXT'] + '\\n' + cdata['S1_COEF'] + '\\n\\n'\n ans[1] += 'S2:' + cdata['S2'] + '\\n・' + \\\n cdata['S2_TEXT'] + '\\n' + cdata['S2_COEF'] + '\\n\\n'\n ans[1] += 'EX:' + cdata['EX'] + '\\n・' + \\\n cdata['EX_TEXT'] + '\\n' + cdata['EX_COEF'] + '\\n\\n'\n ans[1] += '◎ 「!pb action ' + cdata['name'] + '」で行動パターンを表示' + '\\n\\n'\n return ans\n\n\ndef action(id): # 行動パターン\n ans = \"\"\n\n with closing(sqlite3.connect(dbname)) as conn:\n conn.row_factory = sqlite3.Row\n c = conn.cursor()\n\n chara = (id,)\n sql = 'SELECT * FROM chara WHERE id=?'\n for cdata in c.execute(sql, chara):\n ans += '☆' + cdata['name'] + '☆ [' + \\\n cdata['GUILD'] + '/' + cdata['POS'] + ']' + '\\n\\n'\n ans += '攻撃パターン:\\n' + cdata['ACTION'] + '\\n\\n'\n return ans\n\n@client.event\nasync def on_ready():\n print('We have logged in as {0.user}'.format(client))\n\n@client.event\nasync def on_message(message):\n if message.author == client.user:\n return\n\n if message.content.startswith('!pb '):\n if message.content.startswith('!pb help'):\n await message.channel.send(helptext)\n elif message.content.startswith('!pb action '):\n ids = searchid(message.content.lstrip('!pb action '), 0)\n if ids == []:\n await message.channel.send('「' + message.content.lstrip('!pb action ') + '」は見つかりませんでした。')\n else:\n for id in ids:\n reply = action(id)\n await message.channel.send(reply)\n elif message.content.startswith('!pb detail '):\n ids = searchid(message.content.lstrip('!pb detail '), 0)\n if ids == []:\n await message.channel.send('「' + message.content.lstrip('!pb detail ') + '」は見つかりませんでした。')\n else:\n for id in ids:\n reply = detail(id)\n await message.channel.send(reply[0])\n await message.channel.send(reply[1])\n else:\n ids = searchid(message.content.lstrip('!pb '), 1)\n if ids == []:\n await message.channel.send('「' + message.content.lstrip('!pb ') + '」は見つかりませんでした。')\n else:\n for id in ids:\n reply = basic(id)\n await message.channel.send(reply[0])\n await message.channel.send(reply[1])\n elif message.content.startswith('!pb'):\n await message.channel.send(helptext)\n\nclient.run(token)","sub_path":"prihel.py","file_name":"prihel.py","file_ext":"py","file_size_in_byte":5990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"132493017","text":"import json\nfrom harvester.logs import logger\nimport os\nimport requests\nfrom harvester.data_gov_api import CKANPortalAPI\nfrom harvester.data_json import DataJSON\nfrom datapackage import Package, Resource\nfrom slugify import slugify\nfrom harvester import config\nimport base64\nfrom dateutil.parser import parse\nimport glob\nfrom functions import encode_identifier\nimport pytz\n\n\ndef get_current_ckan_resources_from_api(harvest_source_id):\n results_json_path = config.get_ckan_results_cache_path()\n logger.info(f'Extracting from harvest source id: {harvest_source_id}')\n cpa = CKANPortalAPI(base_url=config.CKAN_CATALOG_URL)\n resources = 0\n\n page = 0\n for datasets in cpa.search_harvest_packages(harvest_source_id=harvest_source_id):\n # getting resources in pages of packages\n page += 1\n logger.info('PAGE {} from harvest source id: {}'.format(page, harvest_source_id))\n for dataset in datasets:\n pkg_resources = len(dataset['resources'])\n resources += pkg_resources\n yield(dataset)\n\n # we don't need to save this\n # save_dict_as_data_packages(data=package, path=config.get_data_packages_folder_path(),\n # prefix='ckan-result',\n # identifier_field='id')\n\n logger.info('{} total resources in harvest source id: {}'.format(resources, harvest_source_id))\n cpa.save_packages_list(path=results_json_path)\n\n\ndef compare_resources(rows):\n \"\"\" read the previous resource (CKAN API results)\n Yield any comparison result\n \"\"\"\n\n res_name = rows.res.name if hasattr(rows, 'res') else 'Fake res testing'\n logger.info(f'Rows from resource {res_name}')\n\n data_packages_path = config.get_data_packages_folder_path()\n default_tzinfo_for_naives_dates = pytz.UTC\n\n # Calculate minimum statistics\n total = 0\n\n no_extras = 0\n no_identifier_key_found = 0\n deleted = 0\n found_update = 0\n found_not_update = 0\n\n sample_row = None\n for row in rows:\n total += 1\n # logger.info(f'Row: {total}')\n # check for identifier\n ckan_id = row['id']\n extras = row.get('extras', False)\n if not extras:\n # TODO learn why.\n logger.error(f'No extras! dataset: {ckan_id}')\n result = {'action': 'error',\n 'ckan_id': ckan_id,\n 'new_data': None,\n 'reason': 'The CKAN dataset does not '\n 'have the \"extras\" property'}\n row.update({'comparison_results': result})\n yield row\n no_extras += 1\n continue\n\n identifier = None\n for extra in extras:\n if extra['key'] == 'identifier':\n identifier = extra['value']\n\n if identifier is None:\n logger.error('No identifier '\n '(extras[].key.identifier not exists). '\n 'Dataset.id: {}'.format(ckan_id))\n\n no_identifier_key_found += 1\n result = {'action': 'error',\n 'ckan_id': ckan_id,\n 'new_data': None,\n 'reason': 'The CKAN dataset does not have an \"identifier\"'}\n row.update({'comparison_results': result})\n yield row\n continue\n\n # was parent in the previous harvest\n # if extras.get('collection_metadata', None) is not None:\n\n encoded_identifier = encode_identifier(identifier)\n expected_filename = f'data-json-{encoded_identifier}.json'\n expected_path = os.path.join(data_packages_path, expected_filename)\n\n if not os.path.isfile(expected_path):\n logger.info((f'Dataset: {ckan_id} not in DATA.JSON.'\n f'It was deleted?: {expected_path}'))\n deleted += 1\n result = {'action': 'delete',\n 'ckan_id': ckan_id,\n 'new_data': None,\n 'reason': 'It no longer exists in the data.json source'}\n row.update({'comparison_results': result})\n yield row\n continue\n\n datajson_package = Package(expected_path)\n # logger.info(f'Dataset: {ckan_id}\n # found as data package at {expected_path}')\n\n # TODO analyze this: https://github.com/ckan/ckanext-harvest/blob/master/ckanext/harvest/harvesters/base.py#L229\n\n # compare dates\n # at data.json: \"modified\": \"2019-06-27 12:41:27\",\n # at ckan results: \"metadata_modified\": \"2019-07-02T17:20:58.334748\",\n\n data_json = datajson_package.get_resource('inline')\n data_json_data = data_json.source\n data_json_modified = parse(data_json_data['modified']) # It's a naive date\n\n ckan_json = row\n ckan_json_modified = parse(ckan_json['metadata_modified'])\n\n # un-naive datetimes\n if data_json_modified.tzinfo is None:\n data_json_modified = data_json_modified.replace(tzinfo=default_tzinfo_for_naives_dates)\n # logger.warning('Modified date in data.json is naive: {}'.format(data_json_data['modified']))\n if ckan_json_modified.tzinfo is None:\n ckan_json_modified = ckan_json_modified.replace(tzinfo=default_tzinfo_for_naives_dates)\n # logger.warning('Modified date in CKAN results is naive: {}'.format(ckan_json['metadata_modified']))\n\n diff_times = data_json_modified - ckan_json_modified\n\n seconds = diff_times.total_seconds()\n # logger.info(f'Seconds: {seconds} data.json:{data_json_modified} ckan:{ckan_json_modified})')\n\n # TODO analyze this since we have a Naive date we are not sure\n if abs(seconds) > 86400: # more than a day\n warning = '' if seconds > 0 else 'Data.json is older than CKAN'\n result = {'action': 'update',\n 'ckan_id': ckan_id,\n 'new_data': data_json_data,\n 'reason': f'Changed: ~{seconds} seconds difference. {warning}'\n }\n found_update += 1\n else:\n result = {'action': 'ignore',\n 'ckan_id': ckan_id,\n 'new_data': None, # do not need this data_json_data\n 'reason': 'Changed: ~{seconds} seconds difference'}\n found_not_update += 1\n row.update({'comparison_results': result})\n yield row\n\n # if sample_row is None:\n # sample_row = row\n\n # Delete the data.json file\n os.remove(expected_path)\n\n news = 0\n for name in glob.glob(f'{data_packages_path}/data-json-*.json'):\n news += 1\n package = Package(name)\n data_json = package.get_resource('inline')\n data_json_data = data_json.source\n\n result = {'action': 'create',\n 'ckan_id': None,\n 'new_data': data_json_data,\n 'reason': 'Not found in the CKAN results'}\n\n # there is no real row here\n\n # row = sample_row.update({'comparison_results': result})\n row = {'comparison_results': result}\n yield row\n\n # Delete the data.json file\n os.remove(name)\n\n found = found_not_update + found_update\n\n stats = f\"\"\"Total processed: {total}.\n {no_extras} fail extras.\n {no_identifier_key_found} fail identifier key.\n {deleted} deleted.\n {found} datasets found ({found_update} needs update, {found_not_update} are the same),\n {news} new datasets.\"\"\"\n\n logger.info(stats)\n","sub_path":"harvest/datajson/functions2.py","file_name":"functions2.py","file_ext":"py","file_size_in_byte":7651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"242347861","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 12 16:38:10 2020\n\n@author: aktasos\n\"\"\"\nimport torch\n\ndef correct(preds, labels):\n c=torch.eq(preds.argmax(dim=1),labels,out=torch.tensor([]))\n return c.sum().item()\n\ndef get_all_preds(model, loader):\n all_preds = torch.tensor([])\n for batch in loader:\n images, labels = batch\n preds = model(images.float())\n all_preds = torch.cat((all_preds, preds),dim=0)\n return all_preds\n \ndef confusion_matrix():\n with torch.no_grad(): \n prediction_loader = DataLoader(dataset=dataset,batch_size=len(dataset),shuffle=False)\n train_preds = get_all_preds(network, prediction_loader)\n \n preds_labels = torch.stack((dataset.y, train_preds.argmax(dim=1)),dim=1)\n \n \n conf_matrix = torch.zeros(10,10,dtype=torch.int32)\n for i in preds_labels:\n l, p = i.tolist()\n conf_matrix[l,p] = conf_matrix[l,p] + 1","sub_path":"analytics.py","file_name":"analytics.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"28003693","text":"from typing import List\n\n\nclass Solution:\n def findSubsequences(self, nums: List[int]) -> List[List[int]]:\n self.nums = nums\n self.result = []\n self.process(0, [])\n\n print(self.result)\n return self.result\n\n def process(self, index, tmp):\n if len(tmp) > 1 and tmp not in self.result:\n self.result.append(tmp[:])\n for i in range(index, len(self.nums)):\n # 剪枝\n if tmp and tmp[-1] > self.nums[i]:\n continue\n tmp.append(self.nums[i])\n self.process(i + 1, tmp)\n tmp.pop()\n\n\nif __name__ == '__main__':\n s = Solution()\n data = [10, 9, 2, 5, 3, 7, 101, 18]\n s.findSubsequences(data)\n","sub_path":"leetcode/回溯/491. 递增子序列.py","file_name":"491. 递增子序列.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"384587183","text":"from time import time\n\ndef exponentiate(x, n):\n if n < 0: return exponentiate(1 / x, -n)\n elif n == 0: return 1\n elif n == 1: return x\n elif not n % 2: return exponentiate(x * x, n / 2)\n elif n % 2: return x * exponentiate(x * x, (n - 1) / 2)\n\nstart = time()\nexponentiate(123456789, 5000000)\nprint(time() - start)\n\nstart = time()\n123456789 ** 5000000\nprint(time() - start)\n","sub_path":"s01_numbers/fast_exp.py","file_name":"fast_exp.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"25284904","text":"# Copyright 2017 TensorHub, 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\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport os\n\nimport guild.cmd_support\nimport guild.package\n\ndef create_package(args, ctx):\n project_dir = args.project_location or \".\"\n package_file = os.path.join(project_dir, \"PACKAGE\")\n if not os.path.exists(package_file):\n guild.cli.error(\n \"a PACKAGE file does not exist in %s\\n%s\"\n % (guild.cmd_support.project_location_desc(project_dir),\n guild.cmd_support.try_project_location_help(project_dir, ctx)))\n guild.package.create_package(\n package_file,\n dist_dir=args.dist_dir,\n upload=args.upload,\n sign=args.sign,\n identity=args.identity,\n user=args.user,\n password=args.password,\n comment=args.comment)\n","sub_path":"guild/commands/package_impl.py","file_name":"package_impl.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"435114171","text":"# Source: https://oj.leetcode.com/problems/permutations/\n# Author: renzongxian\n# Date: 2016-07-06\n\n\"\"\"\n\nGiven a collection of distinct numbers, return all possible permutations.\n\nFor example,\n[1,2,3] have the following permutations:\n[\n [1,2,3],\n [1,3,2],\n [2,1,3],\n [2,3,1],\n [3,1,2],\n [3,2,1]\n]\n\n\"\"\"\n\nclass Solution(object):\n def permute(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n def recur(sublist, result_list, remain):\n if len(remain) == 0 and sublist not in result_list:\n result_list.append(sublist)\n return\n for item in remain:\n recur(sublist + [item], result_list, [i for i in remain if i!=item])\n result = []\n recur([], result, nums)\n return result\n \n","sub_path":"src/permutations.py","file_name":"permutations.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"612391203","text":"# 请实现一个函数,把字符串 s 中的每个空格替换成\"%20\"。\n\nclass Solution:\n def replaceSpace(self, s: str) -> str:\n res = []\n for c in s:\n if c == ' ': res.append(\"%20\")\n else: res.append(c)\n return \"\".join(res)\n\n \n","sub_path":"lcof/面试题05. 替换空格.py","file_name":"面试题05. 替换空格.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"259149384","text":"import xidx\n\nfrom xidx import *\n\nn_ts = 10\nfilepath = \"test.xidx\"\n\n# create metadata file\nmeta = MetadataFile(filepath)\n\n# create time group\ntime_group = Group(\"TimeSeries\", Group.TEMPORAL_GROUP_TYPE)\n\n# set data source to the dataset file\nsource = DataSource(\"data\", \"file_path\")\ntime_group.addDataSource(source)\n\n# create a list domain for the temporal group\ntime_dom = ListDomainDouble(\"Time\")\n\n# add attributes for the domain\ntime_dom.addAttribute(\"units\", \"days since 1980\")\ntime_dom.addAttribute(\"calendar\", \"gregorian\")\n\n# add time values\nfor i in range(0,n_ts):\n ret = time_dom.addDomainItem(float(i)*0.25)\n # you can also use a tuple (e.g., bounds for netcdf)\n #time_dom.addDomainItems(IndexSpace([float(i)*0.25,float(i)*0.50]))\n\n# set group time domain\ntime_group.setDomain(time_dom)\n\n# create grid domain \ngeo_dom = MultiAxisDomain(\"Geospatial\")\n\n# create axis\nlatitude_axis = Variable(\"latitude\");\nlongitude_axis = Variable(\"longitude\");\n\n# Populate the axis with explicit values (will be written in the XML)\nfor i in range(0,10):\n latitude_axis.addValue(float(i)*0.5)\n longitude_axis.addValue(float(i)*2*0.6)\n # you can also use a tuple (e.g., bounds for netcdf)\n #longitude_axis.addValues(IndexSpace([float(i)*2*0.6,float(i)*2*1.2]))\n\n# add attributes to axis\nlatitude_axis.addAttribute(\"units\", \"degrees_north\")\nlatitude_axis.addAttribute(\"units\", \"degrees_east\")\n\n# add axis to the domain\ngeo_dom.addAxis(latitude_axis)\ngeo_dom.addAxis(longitude_axis)\n\ngeo_vars = Group(\"geo_vars\", Group.SPATIAL_GROUP_TYPE, geo_dom);\n \n# create and add a variable to the group\ntemp = geo_vars.addVariable(\"geo_temperature\", XidxDataType.FLOAT_32());\n \n# add attribute to the variable (key-value) pairs\ntemp.addAttribute(\"unit\", \"Celsius\");\ntemp.addAttribute(\"valid_min\", \"-100.0\");\ntemp.addAttribute(\"valid_max\", \"200.0\");\n\ntime_group.addGroup(geo_vars);\n \n# set the root group of the metadata\nmeta.setRootGroup(time_group);\n# write to disk\nmeta.save();\n\nprint (\"write done\")","sub_path":"examples/python/write.py","file_name":"write.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"319582737","text":"MYPORT = 3000\nMYGROUP_6 = 'ff02::1%eth0'\n\nimport time\nimport struct\nimport socket\nimport sys\n\ndef main():\n s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)\n s.bind(('', MYPORT))\n # MAX 5800\n buffer_size = 4800\n data = bytearray([0x7A, 0xA7, 0x6, 0x28])\n data += bytearray( struct.pack(\"I\", buffer_size) )\n s.sendto(data, (MYGROUP_6, MYPORT))\n\nif __name__ == '__main__':\n main()\n","sub_path":"write_buffer_size.py","file_name":"write_buffer_size.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"515226128","text":"def checkio(marbles: str, step: int) -> float:\n \"\"\" Input: The start sequence of the pearls as a string and the move number as an integer.\n Output: The probability for a white pearl as a float. \"\"\"\n \n def branch(white, step):\n \"\"\" Recursively branch into both (if possible) cases\"\"\"\n if step == 1:\n return white/all\n \n left = 0 if white == all else branch(white+1,step-1)\n right = 0 if white == 0 else branch(white-1,step-1)\n \n return (all-white)/all * left + white/all * right\n \n white = marbles.count('w')\n all = len(marbles)\n \n return round(branch(white,step),2)\n \n#These \"asserts\" using only for self-checking and not necessary for auto-testing\nif __name__ == '__main__':\n print(\"Example:\")\n print(checkio('bbw', 3))\n\n assert checkio('bbw', 3) == 0.48, \"1st example\"\n assert checkio('wwb', 3) == 0.52, \"2nd example\"\n assert checkio('www', 3) == 0.56, \"3rd example\"\n assert checkio('bbbb', 1) == 0, \"4th example\"\n assert checkio('wwbb', 4) == 0.5, \"5th example\"\n assert checkio('bwbwbwb', 5) == 0.48, \"6th example\"\n print(\"Coding complete? Click 'Check' to earn cool rewards!\")\n","sub_path":"box-probability.py","file_name":"box-probability.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"226515029","text":"from flask import Flask, jsonify\nfrom flask.ext.cors import CORS\nimport sqlite3\n\napp = Flask(__name__)\ncors = CORS(app)\n\nempty_database_quote = {\n \"quote\": \"Well what do you know? I ran out of piggies.\",\n \"author\": \"Tweety bird\",\n \"comment\": \"THE DATABASE IS EMPTY\"\n}\n\n@app.route('/', defaults={'path': ''})\n@app.route('/')\ndef get_random_quote(path):\n with sqlite3.connect('quotes.db') as conn:\n cur = conn.cursor()\n cur.execute('SELECT quote, name FROM quote '\\\n 'INNER JOIN author ON quote.author = author.id '\\\n 'ORDER BY random() LIMIT 1;')\n rows = cur.fetchone()\n if rows:\n return jsonify(quote=rows[0], author=rows[1])\n else:\n return jsonify(**empty_database_quote)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"488634865","text":"#!/usr/bin/python\n\nimport os\nimport sys\nimport json\n\nfrom termcolor import colored\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nsys.path.append(os.path.dirname(dir_path))\nfrom core import *\nfrom core_real_dataset import *\n\nconfig = configparser.ConfigParser()\nconfig.read(os.path.join(dir_path, \"config.ini\"))\n\n__real_errors_dir = config['DEFAULT']['real_errors_dir']\n \ndef real_errors_stats():\n errors_info = load_errors_info(only_targeted=True)\n # print(errors_info)\n\n for repo, errors_info in group_by(lambda e: e['repo'], errors_info).items():\n errors = [\n error['source'].split('.')[-1][:-5]\n for info in errors_info\n if len(info['errors']) <= 10\n for error in info['errors']\n ]\n print(colored(f'{repo} : {len(errors)} errors', attrs=['bold']))\n for size, errors_info in sorted(group_by(lambda e: len(e['errors']), errors_info).items()):\n errors = [\n error['source'].split('.')[-1][:-5]\n for info in errors_info\n if len(info['errors']) <= 10\n for error in info['errors']\n ]\n if len(errors) > 0:\n print(colored(f'\\t{size} errors per file ({len(errors)/size:.0f} file(s))', attrs=['bold']))\n\n for error, count in dict_count(errors).items():\n print('\\t\\t', end='')\n if error in targeted_errors:\n if error not in corner_cases_errors:\n print(colored(f'{error:<30} : {count}', color='green'))\n else:\n print(colored(f'{error:<30} : {count}', color='yellow'))\n else:\n print(f'{error:<30} : {count}')\n \nreal_errors_stats()\n","sub_path":"python/real_error_dataset/real_errors_stats.py","file_name":"real_errors_stats.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"44955743","text":"import smtplib\nfrom email.message import EmailMessage\n\nfrom config import config\n\nsmtp_class = smtplib.SMTP_SSL if config.SMTP_PORT == 465 else smtplib.SMTP\n\n\ndef send_mail(to, subject, content):\n try:\n with smtp_class(config.SMTP_HOST, config.SMTP_PORT) as server:\n server.login(config.SMTP_USER, config.SMTP_PASSWORD)\n\n message = EmailMessage()\n message[\n \"From\"\n ] = (\n config.SMTP_USER\n ) # Вне зависимости от того, что вы укажете в этом поле, Gmail подставит ваши данные\n message[\"To\"] = \",\".join([to]) # Попробуйте отправить письмо самому себе\n message[\"Subject\"] = subject\n\n # Для отправки HTML-письма нужно вместо метода `set_content` использовать `add_alternative` с subtype \"html\",\n # Иначе пользователю придёт набор тегов вместо красивого письма\n message.add_alternative(content, subtype=\"html\")\n server.sendmail(config.SMTP_USER, [to], message.as_string())\n except Exception:\n return False, \"exception\"\n else:\n return True, \"ok\"\n","sub_path":"scheduler/src/email_sender.py","file_name":"email_sender.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"519206228","text":"import arrow\nfrom configparser import ConfigParser\nimport os\nimport shutil\nimport subprocess\nimport logging\nimport glob\n\n\ndef load_zapa(fn):\n\tret = {}\n\twith open(fn, 'r', encoding='utf-8') as f:\n\t\tfor line in f:\n\t\t\tline = line.strip()\n\t\t\tif not line:\n\t\t\t\tcontinue\n\t\t\tif line.startswith('#'):\n\t\t\t\tcontinue\n\t\t\tmj, loc = line.split(' ', 1)\n\t\t\tmj = mj.lower()\n\t\t\tloc = loc.split('., ', 1)[1]\n\t\t\tret[mj] = loc\n\treturn ret\n\n\ndef fn_to_since_till(fn):\n\tfn = fn.replace('signals.', '')\n\tsince, _ = fn.split('.', 1)\n\tsince = arrow.get(since, 'YYYYMMDDHHmmss').replace(tzinfo='Europe/Prague').timestamp\n\ttill = None\n\treturn (since, till)\n\n\ndef unpack(mj, since, till, path_incoming, path_to):\n\tsince = arrow.get(since).replace(tzinfo='Europe/Prague')\n\ttill = arrow.get(till).replace(tzinfo='Europe/Prague')\n\n\t#subprocess.call('rm -rf %s/%s' % (mj, path_to), shell=True)\n\tif os.path.isdir('%s/%s' % (path_to, mj)):\n\t\tshutil.rmtree('%s/%s' % (path_to, mj))\n\n\tos.mkdir('%s/%s' % (path_to, mj))\n\n\ttill_year = till.year\n\ttill_month = till.month\n\ttill_month += 1\n\tif till_month > 12:\n\t\ttill_month -= 12\n\t\ttill_year += 1\n\n\tyears_months = []\n\tyear = since.year\n\tmonth = since.month\n\twhile year < till_year or (year == till_year and month <= till_month):\n\t\tyears_months.append('%04d-%02d' % (year, month))\n\n\t\tmonth += 1\n\t\tif month > 12:\n\t\t\tmonth -= 12\n\t\t\tyear += 1\n\n\tif os.path.isdir('%s/%s/archive' % (path_incoming, mj)):\n\t\tfor fn in sorted(os.listdir('%s/%s/archive' % (path_incoming, mj))):\n\t\t\tif '_comm_' not in fn or '_log_' in fn:\n\t\t\t\tcontinue\n\n\t\t\tfor ym in years_months:\n\t\t\t\tif ym in fn:\n\t\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tcontinue\n\n\t\t\tcmd = '7z x -y %s/%s/archive/%s -o%s/%s' % (path_incoming, mj, fn, path_to, mj)\n\t\t\tlogging.debug(cmd)\n\t\t\tsubprocess.call(cmd, shell=True, stdout=subprocess.DEVNULL)\n\n\tadditional_copies = 0\n\n\t# TODO: add support for languages (sk, cs) or solve this upstream\n\tfor lang in ['cs', 'sk', ]:\n\t\tfor d in ('ctr_man', 'dis_man', 'man_ctr', 'man_dis'):\n\t\t\tif not os.path.isdir('%s/%s/atx300/comm/%s/%s/archive' % (path_incoming, mj, lang, d)):\n\t\t\t\tcontinue\n\n\t\t\tif not os.path.isdir('tmp/%s/%s' % (mj, d)):\n\t\t\t\tos.mkdir('tmp/%s/%s' % (mj, d))\n\n\t\t\tfor fn in os.listdir('%s/%s/atx300/comm/%s/%s/archive' % (path_incoming, mj, lang, d)):\n\t\t\t\t#logging.debug('additional copy of %s/%s' % (d, fn))\n\t\t\t\tshutil.copy('%s/%s/atx300/comm/%s/%s/archive/%s' % (path_incoming, mj, lang, d, fn), '%s/%s/%s/%s' % (path_to, mj, d, fn))\n\t\t\t\tadditional_copies += 1\n\n\tlogging.debug('did %d additional copies' % additional_copies)\n\n\ndef find_scale_for(name, structure):\n\tcur = name\n\twhile cur:\n\t\tif 'Scale' in structure[cur]:\n\t\t\treturn structure[cur]['Scale']\n\t\tcur = structure[cur].get('Sink')\n\treturn None\n\n\ndef is_silo_open(d, mem):\n\tif d['Signal_Is_Closed'] is not None and d['Signal_Is_Closed'] in mem:\n\t\treturn mem[d['Signal_Is_Closed']] == 0\n\tif d['Signal_Open'] is not None and d['Signal_Open'] in mem:\n\t\treturn mem[d['Signal_Open']] != 0\n\treturn None\n\n\nis_bin_open = is_silo_open\n\n\ndef is_lift_up(d, mem):\n\tif d['Signal_Is_Up'] is not None and d['Signal_Is_Up'] in mem:\n\t\treturn mem[d['Signal_Is_Up']] != 0\n\treturn None\n\n\ndef is_lift_down(d, mem):\n\tif d['Signal_Is_Down'] is not None and d['Signal_Is_Down'] in mem:\n\t\treturn mem[d['Signal_Is_Down']] != 0\n\treturn None\n\n\ndef is_mixer_open(d, mem):\n\tif d['Signal_Is_Closed'] is not None and d['Signal_Is_Closed'] in mem:\n\t\treturn mem[d['Signal_Is_Closed']] == 0\n\treturn None\n\n\n# TODO: uglyyyy - and also it should be somewhere in pylib or so...\ndef load_placement(placement_ini_fn):\n\tret = {}\n\tini = ConfigParser()\n\tini.read(placement_ini_fn)\n\tfor sec in ini.sections():\n\t\t# TODO: beware - not all sections may have been converted to new names in real world files\n\t\tif '_' in sec:\n\t\t\tcontinue\n\t\td = {\n\t\t\t'Name': ini[sec]['Name'],\n\t\t\t'LongName': ini[sec]['LongName'],\n\t\t\t'Type': ini[sec]['Type'],\n\t\t\t'Silo_Minor': ini[sec]['Silo_Minor'],\n\t\t\t'Substitution': ini[sec]['Substitution'],\n\t\t}\n\t\tret[sec] = d\n\treturn ret\n\n\ndef get_signals_files(path, since, till):\n\tsignals_fns = glob.glob('%s/atx300/signalsrecorder/signals.*.dat' % path)\n\tsignals_fns += glob.glob('%s/atx300/signalsrecorder/signals.*.msgpack' % path)\n\tsignals_fns += glob.glob('%s/atx300/signalsrecorder/signals.*.msgpack.xz' % path)\n\tsignals_fns = sorted(signals_fns)\n\n\tlogging.debug('unfiltered files: %d' % len(signals_fns))\n\n\t# TODO: hack (for speedup)\n\tfound_earlier = False\n\tfor fn in reversed(signals_fns.copy()):\n\t\tif found_earlier:\n\t\t\tsignals_fns.remove(fn)\n\t\t\tcontinue\n\t\tsince_, till_ = fn_to_since_till(os.path.basename(fn))\n\t\tif till is not None and since_ > till:\n\t\t\tsignals_fns.remove(fn)\n\t\tif since is not None and since_ < since:\n\t\t\tfound_earlier = True\n\n\tlogging.debug('filtered files: %d' % len(signals_fns))\n\treturn signals_fns\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"271302947","text":"\"\"\"\nDjango settings for lc project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'pq2xe-h4#t*mk^!pmfn)r6s#yk!wh+6a7kl0#mx)9=h71l)-&v'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nTEMPLATE_DEBUG = True\n\nALLOWED_HOSTS = []\n\nRIOT_KEY = (\n \"7d0baafa-94e9-4d0c-8939-a13dc083a7af\",\n \"e5b3c20d-8ce5-4ca6-9c48-847f81fccb64\",\n \"9cc6593f-5eb8-42e4-ab31-901cd3ee8828\",\n)\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.admindocs',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'riot_static',\n 'summoner',\n 'team',\n 'notification',\n 'event',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n)\n\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n \"django.core.context_processors.i18n\",\n \"django.contrib.auth.context_processors.auth\",\n)\n\nROOT_URLCONF = 'lc.urls'\n\nWSGI_APPLICATION = 'lc.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.6/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n#Languages\ngettext = lambda x: x\n\nLANGUAGES = (\n ('fr', gettext('French')),\n ('en', gettext('English')),\n)\nLOCALE_PATHS = (\n os.path.join(BASE_DIR, '/message/locale'),\n os.path.join(BASE_DIR, '/notification/locale'),\n os.path.join(BASE_DIR, '/summoner/locale'),\n os.path.join(BASE_DIR, '/team/locale'),\n)\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\n\nSTATIC_URL = '/static/'\n","sub_path":"lc/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"215594463","text":"from __future__ import annotations\n\nfrom typing import List, Sequence\n\nfrom django.db.models import Q\n\nfrom sentry.models import NotificationSetting, User\nfrom sentry.notifications.helpers import get_scope_type\nfrom sentry.notifications.types import (\n NotificationScopeType,\n NotificationSettingOptionValues,\n NotificationSettingTypes,\n)\nfrom sentry.services.hybrid_cloud.notifications import (\n ApiNotificationSetting,\n MayHaveActor,\n NotificationsService,\n)\nfrom sentry.services.hybrid_cloud.user import APIUser\n\n\nclass DatabaseBackedNotificationsService(NotificationsService):\n def get_settings_for_users(\n self,\n *,\n types: List[NotificationSettingTypes],\n users: List[APIUser],\n value: NotificationSettingOptionValues,\n ) -> List[ApiNotificationSetting]:\n settings = NotificationSetting.objects.filter(\n target__in=[u.actor_id for u in users],\n type__in=types,\n value=value.value,\n scope_type=NotificationScopeType.USER.value,\n )\n return [self._serialize_notification_settings(u) for u in settings]\n\n def get_settings_for_recipient_by_parent(\n self, *, type: NotificationSettingTypes, parent_id: int, recipients: Sequence[MayHaveActor]\n ) -> List[ApiNotificationSetting]:\n team_ids = [r.id for r in recipients if r.class_name() == \"Team\"]\n user_ids = [r.id for r in recipients if r.class_name() == \"User\"]\n actor_ids: List[int] = [r.actor_id for r in recipients if r.actor_id is not None]\n\n parent_specific_scope_type = get_scope_type(type)\n notification_settings = NotificationSetting.objects.filter(\n Q(\n scope_type=parent_specific_scope_type.value,\n scope_identifier=parent_id,\n )\n | Q(\n scope_type=NotificationScopeType.USER.value,\n scope_identifier__in=user_ids,\n )\n | Q(\n scope_type=NotificationScopeType.TEAM.value,\n scope_identifier__in=team_ids,\n ),\n type=type.value,\n target__in=actor_ids,\n )\n\n return [self._serialize_notification_settings(s) for s in notification_settings]\n\n def get_settings_for_user_by_projects(\n self, *, type: NotificationSettingTypes, user_id: int, parent_ids: List[int]\n ) -> List[ApiNotificationSetting]:\n try:\n user = User.objects.get(id=user_id)\n except User.DoesNotExist:\n return []\n\n scope_type = get_scope_type(type)\n return [\n self._serialize_notification_settings(s)\n for s in NotificationSetting.objects.filter(\n Q(\n scope_type=scope_type.value,\n scope_identifier__in=parent_ids,\n )\n | Q(\n scope_type=NotificationScopeType.USER.value,\n scope_identifier=user_id,\n ),\n type=type.value,\n target_id=user.actor_id,\n )\n ]\n\n def close(self) -> None:\n pass\n","sub_path":"src/sentry/services/hybrid_cloud/notifications/impl.py","file_name":"impl.py","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"154277687","text":"# Created by: Mark Brown\n# Email: mb899115@ohio.edu\n# Date: 1/2/2017 -> Last rev. 8/2/2017\n# Description: This file is designed to convert a simple C++ program into Python3 ready code\n\n# used for regular expression characters\nimport re\n# used for checking the command line arguments\nimport sys\n\n\n# This is called to clean all unnecessary characters in every line such as ';''s but also calls other funtions\n# to correct the other differences between C++ and Python\ndef clean_scum(line):\n\n\t# removes all the characters that python doesn't use\n\tline = re.sub(';', '', line)\n\tline = re.sub('\\s*{\\n$', '', line)\n\tline = re.sub('\\s*}$', '', line)\n\tline = re.sub('({|})', '', line)\n\tline = re.sub('//', '# ', line)\n\tline = re.sub('\\|\\|', 'or', line)\n\tline = re.sub('&&', 'and', line)\n\tline = re.sub('!([^=\\n])', 'not \\\\1', line)\n\tline = re.sub('false', 'False', line)\n\tline = re.sub('true', 'True', line)\n\tline = re.sub('const ', ' ', line)\n\tline = re.sub(' const$', '', line)\n\tline = re.sub('if\\s*\\((.*)\\)$', 'if \\\\1:', line)\n\tline = re.sub('^[\\w:&<>\\*]+\\s+([\\w:]+)\\(([^\\)]*\\))$', 'def \\\\1( \\\\2:', line)\n\tline = re.sub('else\\s+if', 'elif', line)\n\tline = re.sub('else\\s*$', 'else:\\n', line)\n\t\n\t# checks for while loops then places a ':' character at the end of that statement\n\tif re.search ('while', line):\n\t\tline = re.sub('\\n', ':\\n', line)\n\n\t# tracks for all letters and everything between to numbers and removes the leading and trailing \n\t# variable names\n\tif re.search('[A-Za-z]+ . \\d+', line):\n\t\ttransfer = re.search('[A-Za-z]+ . \\d+', line)\n\t\tline = transfer.group() + '\\n'\n\n\t# remove the unnecessary commands/functions not used by Python\n\tif re.search(\"#\\s*include\", line):\n\t\tline = ''\n\tif re.search(\"using \", line):\n\t\tline = ''\n\n\t# check if pattern and then remove or replace if necessary\n\tif re.search(\"int|float|double|string\", line):\n\t\tline = ''\n\n\t# corrects the cout statment to a print statement\n\tif re.search(\"cout\", line):\n\t\tline = re.sub('cout', 'print(', line)\n\t\tline = re.sub('<<', '', line)\n\t\tline = re.sub('endl', '\\n', line)\n\t\tline = re.sub('\\n$', ')\\n', line)\n\n\t# corrects the cin statement to input statement\n\tif re.search(\"cin\", line):\n\t\tline = re.sub('\\s*>>\\s*', '', line)\n\t\tline = re.sub('>>', '', line)\n\t\tline = re.sub('cin', '', line)\n\t\tline = re.sub('([A-Za-z\\d]+)', '\\\\1 = input( )\\n', line)\n\n\t# removes the return in main\n\tif re.search(\"return\\s*(EXIT_SUCCESS)|(\\d+)\", line):\n\t\tline = ''\n\n\treturn line\n\ndef main():\n\t# checks the argument amount and sends an error message if in correct amount\n\tif len(sys.argv) > 3 or len(sys.argv) == 1:\n\t\tprint (\"Incorrect amount of command line arguments\")\n\t\tprint (\"python3 assignment.py NAMEOFCPP.cc NAMEOFPYTHON.py\")\n\t\tprint (\"OR python3 assignment.py NAMEOFCPP.cc and look for CpptPython.py\")\n\t\n\t# checks the argument amount is equal to 2 and then enters the main portion of the program\n\tif len(sys.argv) == 2:\n\t\tinf = sys.argv[1]\n\t\t# opens the file name under argv[1] and standard name and passes the lines in one\n\t\t# line at a time to be checked then printed the outfile\n\t\twith open(inf, 'r') as infile, open(\"Cpp2Python.py\", 'w+') as outfile:\n\t\t\tlines = infile.readlines()\n\t\t\tfor line in lines:\n\t\t\t\toutfile.write(clean_scum(line))\n\t\t\toutfile.write(\"if __name__ == '__main__': \\n\\t main()\")\n\n\t# checks the argument amount is equal to 3 and then enters the main portion of the program\n\tif len(sys.argv) == 3:\n\t\tinf = sys.argv[1]\n\t\toutf = sys.argv[2]\n\t\t# opens the file name under argv[1] and argv[2] and passes the lines in one\n\t\t# line at a time to be checked then printed the outfile\n\t\twith open(inf, 'r') as infile, open(outf, 'w+') as outfile:\n\t\t\tlines = infile.readlines()\n\t\t\tfor line in lines:\n\t\t\t\toutfile.write(clean_scum(line))\n\t\t\toutfile.write(\"if __name__ == '__main__': \\n\\t main()\")\n\n# run def main()\nif __name__ == '__main__':\n\tmain()","sub_path":"Past Work Examples/Python examples/assignment.py","file_name":"assignment.py","file_ext":"py","file_size_in_byte":3813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"76890648","text":"#!/usr/bin/env python\n\n\n\n\n##################################################\n## DEPENDENCIES\nimport sys\nimport os\nimport os.path\ntry:\n import builtins as builtin\nexcept ImportError:\n import builtins as builtin\nfrom os.path import getmtime, exists\nimport time\nimport types\nfrom Cheetah.Version import MinCompatibleVersion as RequiredCheetahVersion\nfrom Cheetah.Version import MinCompatibleVersionTuple as RequiredCheetahVersionTuple\nfrom Cheetah.Template import Template\nfrom Cheetah.DummyTransaction import *\nfrom Cheetah.NameMapper import NotFound, valueForName, valueFromSearchList, valueFromFrameOrSearchList\nfrom Cheetah.CacheRegion import CacheRegion\nimport Cheetah.Filters as Filters\nimport Cheetah.ErrorCatchers as ErrorCatchers\nfrom xpdeint.Operators._SICDeltaAOperator import _SICDeltaAOperator\n\n##################################################\n## MODULE CONSTANTS\nVFFSL=valueFromFrameOrSearchList\nVFSL=valueFromSearchList\nVFN=valueForName\ncurrentTime=time.time\n__CHEETAH_version__ = '2.4.4'\n__CHEETAH_versionTuple__ = (2, 4, 4, 'development', 0)\n__CHEETAH_genTime__ = 1484975072.07045\n__CHEETAH_genTimestamp__ = 'Sat Jan 21 16:04:32 2017'\n__CHEETAH_src__ = '/home/mattias/xmds-2.2.3/admin/staging/xmds-2.2.3/xpdeint/Operators/SICDeltaAOperator.tmpl'\n__CHEETAH_srcLastModified__ = 'Mon Jul 23 09:42:26 2012'\n__CHEETAH_docstring__ = 'Autogenerated by Cheetah: The Python-Powered Template Engine'\n\nif __CHEETAH_versionTuple__ < RequiredCheetahVersionTuple:\n raise AssertionError(\n 'This template was compiled with Cheetah version'\n ' %s. Templates compiled before version %s must be recompiled.'%(\n __CHEETAH_version__, RequiredCheetahVersion))\n\n##################################################\n## CLASSES\n\nclass SICDeltaAOperator(_SICDeltaAOperator):\n\n ##################################################\n ## CHEETAH GENERATED METHODS\n\n\n def __init__(self, *args, **KWs):\n\n super(SICDeltaAOperator, self).__init__(*args, **KWs)\n if not self._CHEETAH__instanceInitialized:\n cheetahKWArgs = {}\n allowedKWs = 'searchList namespaces filter filtersLib errorCatcher'.split()\n for k,v in list(KWs.items()):\n if k in allowedKWs: cheetahKWArgs[k] = v\n self._initCheetahInstance(**cheetahKWArgs)\n \n\n def description(self, **KWS):\n\n\n\n ## Generated from @def description: Left/Right Delta A propagation operator for field $field.name at line 26, col 1.\n trans = KWS.get(\"trans\")\n if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):\n trans = self.transaction # is None unless self.awake() was called\n if not trans:\n trans = DummyTransaction()\n _dummyTrans = True\n else: _dummyTrans = False\n write = trans.response().write\n SL = self._CHEETAH__searchList\n _filter = self._CHEETAH__currentFilter\n \n ########################################\n ## START - generated method body\n \n write('''Left/Right Delta A propagation operator for field ''')\n _v = VFFSL(SL,\"field.name\",True) # u'$field.name' on line 26, col 69\n if _v is not None: write(_filter(_v, rawExpr='$field.name')) # from line 26, col 69.\n \n ########################################\n ## END - generated method body\n \n return _dummyTrans and trans.response().getvalue() or \"\"\n \n\n def callEvaluateLoop(self, **KWS):\n\n\n\n ## CHEETAH: generated from @def callEvaluateLoop at line 28, col 1.\n trans = KWS.get(\"trans\")\n if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):\n trans = self.transaction # is None unless self.awake() was called\n if not trans:\n trans = DummyTransaction()\n _dummyTrans = True\n else: _dummyTrans = False\n write = trans.response().write\n SL = self._CHEETAH__searchList\n _filter = self._CHEETAH__currentFilter\n \n ########################################\n ## START - generated method body\n \n # \n for crossIntegrationVector in VFFSL(SL,\"crossIntegrationVectors\",True): # generated from line 30, col 3\n for componentName in crossIntegrationVector.components: # generated from line 31, col 5\n _v = VFFSL(SL,\"crossIntegrationVector.type\",True) # u'${crossIntegrationVector.type}' on line 32, col 1\n if _v is not None: write(_filter(_v, rawExpr='${crossIntegrationVector.type}')) # from line 32, col 1.\n write(''' _old_d''')\n _v = VFFSL(SL,\"componentName\",True) # u'${componentName}' on line 32, col 38\n if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 32, col 38.\n write('''_d''')\n _v = VFFSL(SL,\"crossPropagationDimension\",True) # u'${crossPropagationDimension}' on line 32, col 56\n if _v is not None: write(_filter(_v, rawExpr='${crossPropagationDimension}')) # from line 32, col 56.\n write(''';\n''')\n # \n loopingOrder = { '+': SICDeltaAOperator.LoopingOrder.StrictlyAscendingOrder, '-': SICDeltaAOperator.LoopingOrder.StrictlyDescendingOrder }[self.crossPropagationDirection]\n _v = VFN(VFFSL(SL,\"codeBlocks\",True)['operatorDefinition'],\"loop\",False)(self.insideEvaluateOperatorLoops, loopingOrder = loopingOrder) # u\"${codeBlocks['operatorDefinition'].loop(self.insideEvaluateOperatorLoops, loopingOrder = loopingOrder)}\" on line 40, col 1\n if _v is not None: write(_filter(_v, rawExpr=\"${codeBlocks['operatorDefinition'].loop(self.insideEvaluateOperatorLoops, loopingOrder = loopingOrder)}\")) # from line 40, col 1.\n \n ########################################\n ## END - generated method body\n \n return _dummyTrans and trans.response().getvalue() or \"\"\n \n\n def insideEvaluateOperatorLoops(self, codeString, **KWS):\n\n\n\n ## CHEETAH: generated from @def insideEvaluateOperatorLoops($codeString) at line 43, col 1.\n trans = KWS.get(\"trans\")\n if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):\n trans = self.transaction # is None unless self.awake() was called\n if not trans:\n trans = DummyTransaction()\n _dummyTrans = True\n else: _dummyTrans = False\n write = trans.response().write\n SL = self._CHEETAH__searchList\n _filter = self._CHEETAH__currentFilter\n \n ########################################\n ## START - generated method body\n \n # \n _v = VFFSL(SL,\"insideEvaluateOperatorLoopsBegin\",True) # u'${insideEvaluateOperatorLoopsBegin}' on line 45, col 1\n if _v is not None: write(_filter(_v, rawExpr='${insideEvaluateOperatorLoopsBegin}')) # from line 45, col 1.\n # \n # The Operator class will have defined for us all of the dVariableName_dPropagationDimension variables.\n # Note that we assume that all of the integration vectors have an operotor component defined for them.\n write(''' \n// UNVECTORISABLE\n''')\n for crossIntegrationVector in VFFSL(SL,\"crossIntegrationVectors\",True): # generated from line 51, col 3\n for componentName in crossIntegrationVector.components: # generated from line 52, col 5\n write('''d''')\n _v = VFFSL(SL,\"componentName\",True) # u'${componentName}' on line 53, col 2\n if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 53, col 2.\n write('''_d''')\n _v = VFFSL(SL,\"crossPropagationDimension\",True) # u'${crossPropagationDimension}' on line 53, col 20\n if _v is not None: write(_filter(_v, rawExpr='${crossPropagationDimension}')) # from line 53, col 20.\n write(''' = _old_d''')\n _v = VFFSL(SL,\"componentName\",True) # u'${componentName}' on line 53, col 57\n if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 53, col 57.\n write('''_d''')\n _v = VFFSL(SL,\"crossPropagationDimension\",True) # u'${crossPropagationDimension}' on line 53, col 75\n if _v is not None: write(_filter(_v, rawExpr='${crossPropagationDimension}')) # from line 53, col 75.\n write(''';\n''')\n write('''\n''')\n crossDimRep = VFN(VFN(VFFSL(SL,\"loopingField\",True),\"dimensionWithName\",False)(VFFSL(SL,\"crossPropagationDimension\",True)),\"inBasis\",False)(VFFSL(SL,\"operatorBasis\",True))\n if VFFSL(SL,\"crossPropagationDirection\",True) == '+': # generated from line 58, col 3\n write('''if (''')\n _v = VFFSL(SL,\"crossDimRep.loopIndex\",True) # u'${crossDimRep.loopIndex}' on line 59, col 5\n if _v is not None: write(_filter(_v, rawExpr='${crossDimRep.loopIndex}')) # from line 59, col 5.\n write(''' == 0) {\n''')\n else: # generated from line 60, col 3\n write('''if (''')\n _v = VFFSL(SL,\"crossDimRep.loopIndex\",True) # u'${crossDimRep.loopIndex}' on line 61, col 5\n if _v is not None: write(_filter(_v, rawExpr='${crossDimRep.loopIndex}')) # from line 61, col 5.\n write(''' == ''')\n _v = VFFSL(SL,\"crossDimRep.globalLattice\",True) # u'${crossDimRep.globalLattice}' on line 61, col 33\n if _v is not None: write(_filter(_v, rawExpr='${crossDimRep.globalLattice}')) # from line 61, col 33.\n write(''' - 1) {\n''')\n write(''' // ********** Boundary condition code ***********\n ''')\n _v = VFN(VFFSL(SL,\"codeBlocks\",True)['boundaryCondition'],\"loopCodeString\",True) # u\"${codeBlocks['boundaryCondition'].loopCodeString, autoIndent=True}\" on line 64, col 3\n if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=\"${codeBlocks['boundaryCondition'].loopCodeString, autoIndent=True}\")) # from line 64, col 3.\n write(''' // **********************************************\n \n''')\n for crossIntegrationVector in VFFSL(SL,\"crossIntegrationVectors\",True): # generated from line 67, col 3\n write(''' for (long _cmp = 0; _cmp < _''')\n _v = VFFSL(SL,\"crossIntegrationVector.id\",True) # u'${crossIntegrationVector.id}' on line 68, col 31\n if _v is not None: write(_filter(_v, rawExpr='${crossIntegrationVector.id}')) # from line 68, col 31.\n write('''_ncomponents; _cmp++)\n _old_''')\n _v = VFFSL(SL,\"crossIntegrationVector.id\",True) # u'${crossIntegrationVector.id}' on line 69, col 10\n if _v is not None: write(_filter(_v, rawExpr='${crossIntegrationVector.id}')) # from line 69, col 10.\n write('''[_cmp] = _active_''')\n _v = VFFSL(SL,\"crossIntegrationVector.id\",True) # u'${crossIntegrationVector.id}' on line 69, col 55\n if _v is not None: write(_filter(_v, rawExpr='${crossIntegrationVector.id}')) # from line 69, col 55.\n write('''[_''')\n _v = VFFSL(SL,\"crossIntegrationVector.id\",True) # u'${crossIntegrationVector.id}' on line 69, col 85\n if _v is not None: write(_filter(_v, rawExpr='${crossIntegrationVector.id}')) # from line 69, col 85.\n write('''_index_pointer + _cmp];\n''')\n write(''' \n''')\n # This is where one (half-step) cross-IP step would go\n write('''} else {\n // Update the next guess for iteration.\n''')\n for crossIntegrationVector in VFFSL(SL,\"crossIntegrationVectors\",True): # generated from line 75, col 3\n for componentNumber, componentName, in enumerate(crossIntegrationVector.components): # generated from line 76, col 5\n write(''' ''')\n _v = VFFSL(SL,\"componentName\",True) # u'${componentName}' on line 77, col 3\n if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 77, col 3.\n write(''' = _old_''')\n _v = VFFSL(SL,\"crossIntegrationVector.id\",True) # u'${crossIntegrationVector.id}' on line 77, col 27\n if _v is not None: write(_filter(_v, rawExpr='${crossIntegrationVector.id}')) # from line 77, col 27.\n write('''[''')\n _v = VFFSL(SL,\"componentNumber\",True) # u'${componentNumber}' on line 77, col 56\n if _v is not None: write(_filter(_v, rawExpr='${componentNumber}')) # from line 77, col 56.\n write('''] + d''')\n _v = VFFSL(SL,\"componentName\",True) # u'${componentName}' on line 77, col 79\n if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 77, col 79.\n write('''_d''')\n _v = VFFSL(SL,\"crossPropagationDimension\",True) # u'${crossPropagationDimension}' on line 77, col 97\n if _v is not None: write(_filter(_v, rawExpr='${crossPropagationDimension}')) # from line 77, col 97.\n write(''' * (''')\n _v = VFFSL(SL,\"crossPropagationDirection\",True) # u'${crossPropagationDirection}' on line 77, col 129\n if _v is not None: write(_filter(_v, rawExpr='${crossPropagationDirection}')) # from line 77, col 129.\n write('''0.5*d''')\n _v = VFFSL(SL,\"crossPropagationDimension\",True) # u'${crossPropagationDimension}' on line 77, col 162\n if _v is not None: write(_filter(_v, rawExpr='${crossPropagationDimension}')) # from line 77, col 162.\n write(''');\n''')\n write('''}\n\nfor (long _iter = 0; _iter < ''')\n _v = VFFSL(SL,\"iterations\",True) # u'${iterations}' on line 82, col 30\n if _v is not None: write(_filter(_v, rawExpr='${iterations}')) # from line 82, col 30.\n write('''; _iter++) {\n \n #define d''')\n _v = VFFSL(SL,\"propagationDimension\",True) # u'${propagationDimension}' on line 84, col 12\n if _v is not None: write(_filter(_v, rawExpr='${propagationDimension}')) # from line 84, col 12.\n write(''' _step\n {\n // ************* Propagation code ***************\n ''')\n _v = VFFSL(SL,\"codeString\",True) # u'${codeString, autoIndent=True}' on line 87, col 5\n if _v is not None: write(_filter(_v, autoIndent=True, rawExpr='${codeString, autoIndent=True}')) # from line 87, col 5.\n write(''' // **********************************************\n }\n #undef d''')\n _v = VFFSL(SL,\"propagationDimension\",True) # u'${propagationDimension}' on line 90, col 11\n if _v is not None: write(_filter(_v, rawExpr='${propagationDimension}')) # from line 90, col 11.\n write('''\n \n {\n // *********** Cross-propagation code ***********\n ''')\n _v = VFN(VFFSL(SL,\"codeBlocks\",True)['crossPropagation'],\"loopCodeString\",True) # u\"${codeBlocks['crossPropagation'].loopCodeString, autoIndent=True}\" on line 94, col 5\n if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=\"${codeBlocks['crossPropagation'].loopCodeString, autoIndent=True}\")) # from line 94, col 5.\n write(''' // **********************************************\n }\n \n // Update propagation vectors (note that _step is actually half a step)\n''')\n for integrationVector in VFFSL(SL,\"integrationVectors\",True): # generated from line 99, col 3\n for componentNumber, componentName in enumerate(integrationVector.components): # generated from line 100, col 5\n write(''' ''')\n _v = VFFSL(SL,\"componentName\",True) # u'${componentName}' on line 101, col 3\n if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 101, col 3.\n write(''' = _''')\n _v = VFFSL(SL,\"integrator.name\",True) # u'${integrator.name}' on line 101, col 23\n if _v is not None: write(_filter(_v, rawExpr='${integrator.name}')) # from line 101, col 23.\n write('''_oldcopy_''')\n _v = VFFSL(SL,\"integrationVector.id\",True) # u'${integrationVector.id}' on line 101, col 50\n if _v is not None: write(_filter(_v, rawExpr='${integrationVector.id}')) # from line 101, col 50.\n write('''[_''')\n _v = VFFSL(SL,\"integrationVector.id\",True) # u'${integrationVector.id}' on line 101, col 75\n if _v is not None: write(_filter(_v, rawExpr='${integrationVector.id}')) # from line 101, col 75.\n write('''_index_pointer + ''')\n _v = VFFSL(SL,\"componentNumber\",True) # u'${componentNumber}' on line 101, col 115\n if _v is not None: write(_filter(_v, rawExpr='${componentNumber}')) # from line 101, col 115.\n write('''] + d''')\n _v = VFFSL(SL,\"componentName\",True) # u'${componentName}' on line 101, col 138\n if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 101, col 138.\n write('''_d''')\n _v = VFFSL(SL,\"propagationDimension\",True) # u'${propagationDimension}' on line 101, col 156\n if _v is not None: write(_filter(_v, rawExpr='${propagationDimension}')) # from line 101, col 156.\n write(''' * _step;\n''')\n write(''' \n // Update cross-propagation vectors\n''')\n for crossIntegrationVector in VFFSL(SL,\"crossIntegrationVectors\",True): # generated from line 106, col 3\n for componentNumber, componentName in enumerate(VFFSL(SL,\"crossIntegrationVector.components\",True)): # generated from line 107, col 5\n write(''' ''')\n _v = VFFSL(SL,\"componentName\",True) # u'${componentName}' on line 108, col 3\n if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 108, col 3.\n write(''' = _old_''')\n _v = VFFSL(SL,\"crossIntegrationVector.id\",True) # u'${crossIntegrationVector.id}' on line 108, col 27\n if _v is not None: write(_filter(_v, rawExpr='${crossIntegrationVector.id}')) # from line 108, col 27.\n write('''[''')\n _v = VFFSL(SL,\"componentNumber\",True) # u'${componentNumber}' on line 108, col 56\n if _v is not None: write(_filter(_v, rawExpr='${componentNumber}')) # from line 108, col 56.\n write('''] + d''')\n _v = VFFSL(SL,\"componentName\",True) # u'${componentName}' on line 108, col 79\n if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 108, col 79.\n write('''_d''')\n _v = VFFSL(SL,\"crossPropagationDimension\",True) # u'${crossPropagationDimension}' on line 108, col 97\n if _v is not None: write(_filter(_v, rawExpr='${crossPropagationDimension}')) # from line 108, col 97.\n write(''' * (''')\n _v = VFFSL(SL,\"crossPropagationDirection\",True) # u'${crossPropagationDirection}' on line 108, col 129\n if _v is not None: write(_filter(_v, rawExpr='${crossPropagationDirection}')) # from line 108, col 129.\n write('''0.5*d''')\n _v = VFFSL(SL,\"crossPropagationDimension\",True) # u'${crossPropagationDimension}' on line 108, col 162\n if _v is not None: write(_filter(_v, rawExpr='${crossPropagationDimension}')) # from line 108, col 162.\n write(''');\n''')\n write(\"\"\"}\n\n// Update the 'old' copy for the next half-step\n\"\"\")\n for crossIntegrationVector in VFFSL(SL,\"crossIntegrationVectors\",True): # generated from line 114, col 1\n for componentNumber, componentName in enumerate(crossIntegrationVector.components): # generated from line 115, col 3\n write('''_old_''')\n _v = VFFSL(SL,\"crossIntegrationVector.id\",True) # u'${crossIntegrationVector.id}' on line 116, col 6\n if _v is not None: write(_filter(_v, rawExpr='${crossIntegrationVector.id}')) # from line 116, col 6.\n write('''[''')\n _v = VFFSL(SL,\"componentNumber\",True) # u'${componentNumber}' on line 116, col 35\n if _v is not None: write(_filter(_v, rawExpr='${componentNumber}')) # from line 116, col 35.\n write('''] += d''')\n _v = VFFSL(SL,\"componentName\",True) # u'${componentName}' on line 116, col 59\n if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 116, col 59.\n write('''_d''')\n _v = VFFSL(SL,\"crossPropagationDimension\",True) # u'${crossPropagationDimension}' on line 116, col 77\n if _v is not None: write(_filter(_v, rawExpr='${crossPropagationDimension}')) # from line 116, col 77.\n write(''' * (''')\n _v = VFFSL(SL,\"crossPropagationDirection\",True) # u'${crossPropagationDirection}' on line 116, col 109\n if _v is not None: write(_filter(_v, rawExpr='${crossPropagationDirection}')) # from line 116, col 109.\n write('''d''')\n _v = VFFSL(SL,\"crossPropagationDimension\",True) # u'${crossPropagationDimension}' on line 116, col 138\n if _v is not None: write(_filter(_v, rawExpr='${crossPropagationDimension}')) # from line 116, col 138.\n write(''');\n''')\n write('''\n''')\n # This is where one (full step) cross-IP step would go\n write('''\n''')\n for crossIntegrationVector in VFFSL(SL,\"crossIntegrationVectors\",True): # generated from line 122, col 3\n for componentName in crossIntegrationVector.components: # generated from line 123, col 5\n write('''_old_d''')\n _v = VFFSL(SL,\"componentName\",True) # u'${componentName}' on line 124, col 7\n if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 124, col 7.\n write('''_d''')\n _v = VFFSL(SL,\"crossPropagationDimension\",True) # u'${crossPropagationDimension}' on line 124, col 25\n if _v is not None: write(_filter(_v, rawExpr='${crossPropagationDimension}')) # from line 124, col 25.\n write(''' = d''')\n _v = VFFSL(SL,\"componentName\",True) # u'${componentName}' on line 124, col 57\n if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 124, col 57.\n write('''_d''')\n _v = VFFSL(SL,\"crossPropagationDimension\",True) # u'${crossPropagationDimension}' on line 124, col 75\n if _v is not None: write(_filter(_v, rawExpr='${crossPropagationDimension}')) # from line 124, col 75.\n write(''';\n''')\n write('''\n''')\n # \n \n ########################################\n ## END - generated method body\n \n return _dummyTrans and trans.response().getvalue() or \"\"\n \n\n def evaluateOperatorFunctionContentsWithCodeBlock(self, function, **KWS):\n\n\n\n ## CHEETAH: generated from @def evaluateOperatorFunctionContentsWithCodeBlock($function) at line 131, col 1.\n trans = KWS.get(\"trans\")\n if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):\n trans = self.transaction # is None unless self.awake() was called\n if not trans:\n trans = DummyTransaction()\n _dummyTrans = True\n else: _dummyTrans = False\n write = trans.response().write\n SL = self._CHEETAH__searchList\n _filter = self._CHEETAH__currentFilter\n \n ########################################\n ## START - generated method body\n \n # \n # We shouldn't have a deltaAField. It doesn't work with cross-propagation.\n assert not VFFSL(SL,\"deltaAField\",True)\n # \n for crossIntegrationVector in VFFSL(SL,\"crossIntegrationVectors\",True): # generated from line 136, col 3\n _v = VFFSL(SL,\"crossIntegrationVector.type\",True) # u'${crossIntegrationVector.type}' on line 137, col 1\n if _v is not None: write(_filter(_v, rawExpr='${crossIntegrationVector.type}')) # from line 137, col 1.\n write(''' _old_''')\n _v = VFFSL(SL,\"crossIntegrationVector.id\",True) # u'${crossIntegrationVector.id}' on line 137, col 37\n if _v is not None: write(_filter(_v, rawExpr='${crossIntegrationVector.id}')) # from line 137, col 37.\n write('''[_''')\n _v = VFFSL(SL,\"crossIntegrationVector.id\",True) # u'${crossIntegrationVector.id}' on line 137, col 67\n if _v is not None: write(_filter(_v, rawExpr='${crossIntegrationVector.id}')) # from line 137, col 67.\n write('''_ncomponents];\n''')\n # \n _v = super(SICDeltaAOperator, self).evaluateOperatorFunctionContentsWithCodeBlock(function)\n if _v is not None: write(_filter(_v))\n # \n \n ########################################\n ## END - generated method body\n \n return _dummyTrans and trans.response().getvalue() or \"\"\n \n\n def writeBody(self, **KWS):\n\n\n\n ## CHEETAH: main method generated for this template\n trans = KWS.get(\"trans\")\n if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):\n trans = self.transaction # is None unless self.awake() was called\n if not trans:\n trans = DummyTransaction()\n _dummyTrans = True\n else: _dummyTrans = False\n write = trans.response().write\n SL = self._CHEETAH__searchList\n _filter = self._CHEETAH__currentFilter\n \n ########################################\n ## START - generated method body\n \n # \n # SICDeltaAOperator.tmpl\n # \n # delta-a operator for the left/right propagation in the SIC integrator.\n # \n # Created by Graham Dennis on 2008-08-07.\n # \n # Copyright (c) 2008-2012, Graham Dennis\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, see .\n # \n write('''\n\n\n\n''')\n \n ########################################\n ## END - generated method body\n \n return _dummyTrans and trans.response().getvalue() or \"\"\n \n ##################################################\n ## CHEETAH GENERATED ATTRIBUTES\n\n\n _CHEETAH__instanceInitialized = False\n\n _CHEETAH_version = __CHEETAH_version__\n\n _CHEETAH_versionTuple = __CHEETAH_versionTuple__\n\n _CHEETAH_genTime = __CHEETAH_genTime__\n\n _CHEETAH_genTimestamp = __CHEETAH_genTimestamp__\n\n _CHEETAH_src = __CHEETAH_src__\n\n _CHEETAH_srcLastModified = __CHEETAH_srcLastModified__\n\n _mainCheetahMethod_for_SICDeltaAOperator= 'writeBody'\n\n## END CLASS DEFINITION\n\nif not hasattr(SICDeltaAOperator, '_initCheetahAttributes'):\n templateAPIClass = getattr(SICDeltaAOperator, '_CHEETAH_templateClass', Template)\n templateAPIClass._addCheetahPlumbingCodeToClass(SICDeltaAOperator)\n\n\n# CHEETAH was developed by Tavis Rudd and Mike Orr\n# with code, advice and input from many other volunteers.\n# For more information visit http://www.CheetahTemplate.org/\n\n##################################################\n## if run from command line:\nif __name__ == '__main__':\n from Cheetah.TemplateCmdLineIface import CmdLineIface\n CmdLineIface(templateObj=SICDeltaAOperator()).run()\n\n\n","sub_path":"Src/xmds2_0/xpdeint/Operators/SICDeltaAOperator.py","file_name":"SICDeltaAOperator.py","file_ext":"py","file_size_in_byte":28146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"629750103","text":"# -*- coding: utf-8 -*-\nfrom django.db import models\nfrom djtools.dbfields import BrEstadoBrasileiroField, BrTelefoneField\n\nclass Pessoa(models.Model):\n nome = models.CharField(u'Nome', max_length=200)\n sexo = models.CharField(u'Sexo', max_length=2, null=True, blank=True)\n nome_mae = models.CharField(u'Nome da mãe', max_length=100, null=True, blank=True)\n nome_pai = models.CharField(u'Nome do pai', max_length=100, null=True, blank=True)\n data_nascimento = models.DateField(u'Data nascimento')\n nacionalidade = models.CharField(u'Nacionalidade', max_length=40, null=True, blank=True)\n naturalidade = models.CharField(u'Naturalidade', max_length=50,null=True, blank=True)\n estado_civil = models.CharField(u'Estado Civil', max_length=20, null=True, blank=True)\n cpf = models.CharField(u'CPF', max_length=20, null=True, blank=True)\n rg = models.CharField(u'Identidade', max_length=20, null=True, blank=True)\n uf = BrEstadoBrasileiroField(u'UF', max_length=2, null=True, blank=True)\n via_documento = models.CharField(u'Via Documento', max_length=2, null=True, blank=True)\n excluido = models.BooleanField(u'Excluído', default=False)\n \n class Meta:\n db_table = 'pessoa'\n verbose_name = u'Pessoa'\n verbose_name_plural = u'Pessoas'\n \n def __unicode__(self):\n return self.nome\n \n def _endereco_lograd_num(self):\n if self.endereco_set.all()[0].numero or self.endereco_set.all()[0].complemento:\n if self.endereco_set.all()[0].numero and self.endereco_set.all()[0].complemento:\n return \"%s, %s %s\" %(self.endereco_set.all()[0].logradouro, self.endereco_set.all()[0].numero, self.endereco_set.all()[0].complemento) \n elif self.endereco_set.all()[0].numero:\n return \"%s, %s\" %(self.endereco_set.all()[0].logradouro, self.endereco_set.all()[0].numero)\n elif self.endereco_set.all()[0].complemento:\n return \"%s, %s\" %(self.endereco_set.all()[0].logradouro, self.endereco_set.all()[0].complemento)\n else:\n return \"%s\" %(self.endereco_set.all()[0].logradouro)\n \n def _endereco_bairro(self):\n if self.endereco_set.all()[0].bairro is None:\n return \"\"\n else:\n return self.endereco_set.all()[0].bairro\n \n def _endereco_municipio_estado(self):\n if self.endereco_set.all()[0].municipio or self.endereco_set.all()[0].estado:\n if self.endereco_set.all()[0].municipio and self.endereco_set.all()[0].estado:\n return \", %s/%s\" %(self.endereco_set.all()[0].municipio, self.endereco_set.all()[0].estado)\n elif self.endereco_set.all()[0].municipio:\n return \", %s\" %(self.endereco_set.all()[0].municipio)\n elif self.endereco_set.all()[0].estado:\n return \", %s\" %(self.endereco_set.all()[0].estado)\n else:\n return \"\"\n \n def _endereco_cep_municipio(self):\n return \"%s %s\" %(self.endereco_set.all()[0].cep, self._endereco_municipio_estado())\n\n# def _endereco_geral(self):\n# out = ['
    ']\n# out.append('
  1. %s
  2. ' % self.nome)\n# out.append('
  3. %s
  4. ' % self.endereco._)\n# out.append('
  5. %s
  6. ' % self.nome)\n# out.append('
  7. %s
  8. ' % self.nome)\n# out.append('
')\n# return ''.join(out)\n\nclass Email(models.Model):\n email = models.CharField(u'E-Mail', max_length=100, null=True, blank=True)\n pessoa = models.ForeignKey(Pessoa, verbose_name=u'Pessoa')\n \n class Meta:\n db_table = 'email'\n verbose_name = u'Email'\n verbose_name_plural = u'Emails'\n \n def __unicode__(self):\n return '%s' % self.email\n\nclass Telefone(models.Model):\n telefone = BrTelefoneField(u'Telefone', null=True, blank=True)\n tipo = models.CharField(u'Tipo', max_length=3, null=True, blank=True)\n pessoa = models.ForeignKey(Pessoa, verbose_name=u'Pessoa')\n \n class Meta:\n db_table = 'telefone'\n verbose_name = u'Telefone'\n verbose_name_plural = u'Telefones'\n \n def __unicode__(self):\n return '%s' % self.telefone\n\nclass Endereco(models.Model):\n logradouro = models.CharField(u'Logradouro', max_length=50)\n numero = models.CharField(u'Número', max_length=10, null=True, blank=True)\n complemento = models.CharField(u'Complemento', max_length=50, null=True, blank=True)\n bairro = models.CharField(u'Bairro', max_length=30, null=True, blank=True)\n municipio = models.CharField(u'Município', max_length=30, null=True, blank=True)\n cep = models.CharField(u'CEP', max_length=9, null=True, blank=True)\n estado = BrEstadoBrasileiroField(u'Estado', max_length=2, null=True, blank=True)\n pessoa = models.ForeignKey(Pessoa, verbose_name=u'Pessoa')\n \n class Meta:\n db_table = 'endereco'\n verbose_name = u'Endereço'\n verbose_name_plural = u'Endereços'\n \n def __unicode__(self):\n return '%s, %s' % (self.logradouro.upper(), self.numero)\n# \n# def endereco_rua(self):\n# return '%s, %s' % (self.logradouro.upper(), self.numero)\n# \n# def endereco_cep(self):\n# return '%s, %s/%s' % (self.cep, self.municipio.upper(), self.uf.upper())\n \nclass Setor(models.Model):\n nome = models.CharField(u'Nome', max_length=50, unique=True)\n sigla = models.CharField(u'Sigla', max_length=15, unique=True)\n ramal = models.SmallIntegerField(u'Ramal', null=True, blank=True)\n \n class Meta:\n db_table = 'setor'\n verbose_name = u'Setor'\n verbose_name_plural = u'Setores'\n \n def __unicode__(self):\n return '%s' % self.sigla\n \nclass Orgao(models.Model):\n codigo = models.SmallIntegerField(u'Código', unique=True)\n nome = models.CharField(u'Nome', max_length=50, unique=True)\n sigla = models.CharField(u'Sigla', max_length=15, unique=True)\n \n class Meta:\n db_table = 'orgao'\n verbose_name = u'Órgão'\n verbose_name_plural = u'Orgãos'\n \n def __unicode__(self):\n return '%s' % (self.sigla)\n \nclass Estacao(models.Model):\n nome = models.CharField(u'Nome', max_length=150, unique=True)\n \n class Meta:\n db_table = 'estacao'\n verbose_name = u'Estação'\n verbose_name_plural = u'Estações'\n \n def __unicode__(self):\n return '%s' % self.nome","sub_path":"stunat/comum/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"575029818","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef vn_diagram(cl_max, stall_speed, max_speed, load_factors, mass, surface, show=False):\n fig, ax = plt.subplots()\n n_max, n_min = load_factors\n velocity = np.linspace(0, max_speed, 1000)\n\n # max cl curves\n n_cl_max = 1 / 2 * 1.225 * cl_max * velocity ** 2 * surface / (mass * 9.81)\n n_cl_max[np.where(n_cl_max > n_max)] = n_max\n n_cl_min = -1 / 2 * 1.225 * cl_max * velocity ** 2 * surface / (mass * 9.81)\n n_cl_min[np.where(n_cl_min < -1)] = -1\n plt.plot(velocity, n_cl_max, 'b', label='Flight loads')\n plt.plot(velocity, n_cl_min, 'b')\n\n # stall curve\n plt.vlines(stall_speed, 0, 1, linestyles='--', label='Stall speed')\n\n # max speed curve\n plt.vlines(max_speed, n_min, n_max, colors='b')\n plt.plot(max_speed, 0, 'go', label='Dive speed')\n\n plt.axvline()\n plt.axhline()\n plt.xlim(0, 1.1 * max_speed)\n plt.ylabel(\"Load Factor\")\n plt.xlabel('Speed [m\\s]')\n\n if show:\n plt.show()\n\n\ndef gust_load(stall_speed, speed_cruise, dive_speed, gust_speed, cl_max, mass, surface, show=True):\n cl_cruise = 2 * mass * 9.81 / (speed_cruise ** 2 * 1.225 * surface)\n cl_dive = 2 * mass * 9.81 / (dive_speed ** 2 * 1.225 * surface)\n velocity = np.linspace(0, dive_speed, 1000)\n\n cl_max_line = 1 + 1.225 * velocity * gust_speed * surface * cl_max / (2 * mass * 9.81)\n cl_max_line = cl_max_line[np.where(velocity < stall_speed)]\n cl_max_line_2 = 1 - 1.225 * velocity * gust_speed * surface * cl_max / (2 * mass * 9.81)\n cl_max_line_2 = cl_max_line_2[np.where(velocity < stall_speed)]\n\n cl_cruise_line = 1 + 1.225 * velocity * gust_speed * surface * cl_cruise / (2 * mass * 9.81)\n cl_cruise_line = cl_cruise_line[np.where(velocity < speed_cruise)]\n cl_cruise_line_2 = 1 - 1.225 * velocity * gust_speed * surface * cl_cruise / (2 * mass * 9.81)\n cl_cruise_line_2 = cl_cruise_line_2[np.where(velocity < speed_cruise)]\n\n cl_dive_line = 1 + 1.225 * velocity * gust_speed * surface * cl_dive / (2 * mass * 9.81)\n cl_dive_line = cl_dive_line[np.where(velocity < dive_speed)]\n cl_dive_line_2 = 1 - 1.225 * velocity * gust_speed * surface * cl_dive / (2 * mass * 9.81)\n cl_dive_line_2 = cl_dive_line_2[np.where(velocity < dive_speed)]\n\n # line that connects cl_masx line to cl cruise\n speed_0 = np.linspace(stall_speed, speed_cruise, 100)\n line_0 = cl_max_line[-1] + (cl_cruise_line[-1] - cl_max_line[-1]) / (\n speed_cruise - stall_speed) * (speed_0 - stall_speed)\n line_01 = cl_max_line_2[-1] + (cl_cruise_line_2[-1] - cl_max_line_2[-1]) / (\n speed_cruise - stall_speed) * (speed_0 - stall_speed)\n # line that connects cruise to dive\n speed_1 = np.linspace(speed_cruise, dive_speed, 100)\n line_1 = cl_cruise_line[-1] + (cl_dive_line[-1] - cl_cruise_line[-1]) / (\n dive_speed - speed_cruise) * (speed_1 - speed_cruise)\n line_11 = cl_cruise_line_2[-1] + (cl_dive_line_2[-1] - cl_cruise_line_2[-1]) / (\n dive_speed - speed_cruise) * (speed_1 - speed_cruise)\n plt.plot(speed_0, line_0, '-r', label='Gust loads')\n plt.plot(speed_0, line_01, '-r')\n plt.plot(speed_1, line_1, '-r')\n plt.plot(speed_1, line_11, '-r')\n\n # cruise speed\n plt.plot(speed_cruise, 0, 'ro', label='Cruise speed')\n\n\n plt.plot(velocity[np.where(velocity < stall_speed)],\n cl_max_line[np.where(velocity < stall_speed)], '--r')\n plt.plot(velocity[np.where(velocity < stall_speed)],\n cl_max_line_2[np.where(velocity < stall_speed)], '--r')\n plt.plot(velocity[np.where(velocity < speed_cruise)],\n cl_cruise_line[np.where(velocity < speed_cruise)], '--r')\n plt.plot(velocity[np.where(velocity < speed_cruise)],\n cl_cruise_line_2[np.where(velocity < speed_cruise)], '--r')\n plt.plot(velocity[np.where(velocity < dive_speed)],\n cl_dive_line[np.where(velocity < dive_speed)], '--r')\n plt.plot(velocity[np.where(velocity < dive_speed)],\n cl_dive_line_2[np.where(velocity < dive_speed)], '--r')\n plt.legend()\n if show:\n plt.show()\n\n\nif __name__ == '__main__':\n vn_diagram(1.27, 16, 30, (2.5, -1), 12.3, 0.6)\n gust_load(16, 23.8, 30, 12, 1.27, 12.3, 0.6)\n","sub_path":"src/flight_envelope.py","file_name":"flight_envelope.py","file_ext":"py","file_size_in_byte":4232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"7717831","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Aug 24 09:40:28 2018\r\n\r\n@author: Paulo Augusto\r\n\"\"\"\r\n\r\nimport numpy as np\r\n#from numpy import fft\r\nimport matplotlib.pyplot as plt\r\n#import scipy.signal as sig\r\nimport os\r\nimport random \r\nimport emgReaderClass_v2 as erc\r\nimport threading\r\nimport multiprocessing\r\nimport dataPlotter\r\n\r\n # This script is compatible with 'emgReaderClass_v2', that\r\n # reads the .csv files generated by 'movementSaver.m', from\r\n # the folder './csv/'\r\n \r\nbias=0 # If bias = 1, every cromossome will have a non frequency dependant DNA\r\nmaxGen=3000 # The max number of generations\r\nstartOver=True # If True, the code will not consider the last simulation\r\ntamPop=500 # Population number\r\n\r\nmaxFreq=200 # This is the max Frequency to consider #240\r\nfreqStep=2 # For freqStep=3 -> The code will consider [1,2,3],[3,4,5], etc# 3\r\n\r\ntaxaMut=0.01 # The mutation rate\r\ntaxaMutMin=0.01 # Minimum mutation rate\r\ntaxaMutMax=10.0 # Maximum mutation rate\r\nchanceMut=20 # The chance of mutation (only for the \"absolute\" mutation)\r\n\r\nbestTypes=[] # Logging variable\r\n\r\ncontinuous=False # If True, the code will use a continuous fitness function (not recommended)\r\nbinaryFit=False # If True, the fitness of each individual will be 1 for each right guess\r\n # If False, it will be continuous if \"continuous\" is True, or 1 point if\r\n # it guesses correctly, and 1.5 if it guesses with an confidence above \r\n # a \"multFac\" threshold\r\nmultFac=1.5 # \r\nbinaryCrossChance=0.5 # The chance of ocurring a binary cross. 1 minus this \r\n # is the chance of ans mean crossing\r\nvectorialMutationChance=0.5 # The chance of vectorial mutation. 1 minus this is \r\n # chance of an absolute mutation\r\n\r\ntaxaMutMult=4.0 # The factor by which taxaMut will be multiplied\r\n\r\nsourceType='ninapro'\r\nfs=2000\r\n##############################################################################\r\nguid=0 # Individual ID (logging variable)\r\n\r\nreal=[] # DATA\r\norigin=[] # DATA\r\nfv=[] # DATA\r\nfrv=[] # DATA\r\nnArq=0 # DATA\r\n\r\n\r\n# lastValues, botThs and topThs to be used in each archive\r\nparameters={'bicepsinteiro.txt': [400,20,10],\\\r\n 'bicepsmetade.txt': [400,20,10],\\\r\n 'emgwk.txt': [400,20,10],\\\r\n 'emgmed.txt':[400,20,10],\\\r\n# 'xoxoxo.txt':[300,40,30],\\\r\n 'emgabrindo.txt':[500,20,20],\\\r\n 'emgapertando.txt':[400,20,20]}\r\n\r\n\r\n# Method that return the number of right guesses of and individual\r\ndef countGuesses(indiv):\r\n \r\n arqVec=getArqs()\r\n score=0\r\n \r\n for arq in range(0,nArq):\r\n \r\n for i in range(0,len(real[arq])):\r\n tam=len(real[arq][i])\r\n \r\n x= getFreqVector(fv[arq][i])\r\n x=np.array(x)\r\n \r\n pont=x*indiv.cromo.freqFactor\r\n# test.append(pont)\r\n \r\n if np.argmax(pont[0]) == arq:\r\n\r\n score+=1\r\n \r\n return score\r\n\r\n# This function just multiplies the chromossome of an individual by the frequency\r\n# vector of an signal, return the result. The position that gets the higher\r\n# number represent from which archive it thinks this signal belongs\r\ndef sayWho(indiv,real,fv):\r\n tam=len(fv)\r\n x= getFreqVector(fv)\r\n x=np.array(x)\r\n pont=x*indiv.cromo.freqFactor\r\n return pont\r\n \r\n# Gets the *.txt files\r\ndef getArqs():\r\n arqVec=[]\r\n for arq in os.listdir('.'):\r\n if os.path.splitext(arq)[1]=='.txt':\r\n arqVec.append(arq)\r\n arqVec.reverse()\r\n return arqVec\r\n\r\n# Chromossome class each chromossome mainly consists of an nArqs x (maxFreq/freqStep)\r\n# matrix. Each column represent an archive, and each line represent a set of \r\n# freqStep frequencies\r\nclass cromossome:\r\n \r\n def getRandomVec(self,n):\r\n v=[]\r\n for i in range(0,n):\r\n v.append(random.random()*2-1) \r\n return v\r\n \r\n def __init__(self):\r\n self.freqFactor=[]\r\n n=nArq\r\n for i in range(0,maxFreq/freqStep+bias): \r\n self.freqFactor.append(self.getRandomVec(n))\r\n self.freqFactor=np.matrix(self.freqFactor)\r\n\r\n\r\n# Individual class\r\nclass ind:\r\n def __init__(self):\r\n global guid\r\n self.uid=guid\r\n guid+=1\r\n self.cromo = cromossome()\r\n self.fit=0\r\n self.marker='none'\r\n\r\n# This function takes the fft data od an signal, and returns a similar vector,\r\n# but instead of getting one element per frequency it take a number of freqStep\r\n# frequencies, sum it and divide by freqStep\r\ndef getFreqVector(fv):\r\n x=[]\r\n tam=float(len(fv))\r\n# for j in range(0,int(tam/2)-5):\r\n# k=int(np.floor(float(j)*fs/tam))\r\n# step=int(np.ceil(tam*freqStep/fs))\r\n# if(k % step == 0):\r\n# if len(x)==maxFreq/freqStep:\r\n# ##### BIAS ######\r\n# if bias==1:\r\n# x.append(-1)\r\n# #################\r\n# break\r\n# x.append(sum(fv[k:k+step+1])*2/tam)\r\n# return x\r\n norm=int(np.ceil(tam*1/fs))\r\n step=freqStep*norm\r\n for j in range(0,norm*maxFreq,step):\r\n x.append(sum(fv[j:j+step])*2/tam)\r\n ##### BIAS ######\r\n if bias==1 and j==step*maxFreq-1:\r\n x.append(-1)\r\n #################\r\n \r\n return x\r\n\r\n\r\n# Read the data archives. The original signal is stored in origin. Each signal\r\n# Is stored in real. real[arq][5] will contain the 5th signal of the arq'th file\r\n# (as read by getArqs). The fft data will be stored at \"fv\" (indexes works the\r\n# the same as for \"real\"). The frequency vector as got by getFrequencyVector\r\n# is stored at frv\r\ndef readArqs(source):\r\n reader=erc.emgReader()\r\n \r\n global real,fv,frv\r\n if source=='bioplux':\r\n for arq in range(0,nArq): \r\n origin.append([])\r\n real.append([])\r\n fv.append([])\r\n frv.append([])\r\n \r\n reader.lastValues=parameters[arqVec[arq]][0]\r\n reader.topThs=parameters[arqVec[arq]][1]\r\n reader.botThs=parameters[arqVec[arq]][2]\r\n \r\n origin[arq],real[arq],fv[arq] = reader.analyzeEmg(arqVec[arq],fs)\r\n \r\n elif source=='ninapro':\r\n real,fv=reader.getCsvData('bic')\r\n real=real[0:12]\r\n fv=fv[0:12]\r\n \r\n for arq in range(0,len(real)): \r\n frv.append([])\r\n for i in range(0,len(fv[arq])):\r\n frv[arq].append(getFreqVector(fv[arq][i]))\r\n\r\n# Fitness method. Each signal frequency vector is multiplied by indiv\r\n# chromossome. The numbers got are reconized as the score of each archive.\r\n# Let's say that the 0th element gets the largest number. That mean this \r\n# individual \"thinks\" that that signal belongs to archive 4 (getArqs()[0])\r\n# The fitnnes is then calculated by the number of right guesses of each\r\n# individual\r\n \r\ndef fitness(indiv):\r\n \r\n global nArq\r\n score=0\r\n for arq in range(0,nArq):\r\n \r\n for i in range(0,len(fv[arq])):\r\n tam=len(real[arq][i])\r\n \r\n pont=np.array(frv[arq][i])*indiv.cromo.freqFactor\r\n# print pont\r\n test=pont\r\n \r\n if np.argmax(pont) == arq:\r\n if not binaryFit:\r\n###############################################################################\r\n if continuous:\r\n score+=(np.max(pont[0])-np.min(pont[0]))/np.mean(pont[0]-np.min(pont[0]))\r\n###############################################################################\r\n else:\r\n if np.max(np.array(pont)) >=multFac*np.mean(np.array(pont)):\r\n score+=1.5\r\n else:\r\n score+=1\r\n ###########################################################################\r\n else:\r\n score+=1\r\n return score\r\n \r\n# Population class\r\nclass population:\r\n def __init__(self):\r\n self.population=[]\r\n\r\n def initPop(self,tamPop):\r\n for i in range(0,tamPop):\r\n self.population.append(ind())\r\n def evaluateAll(self):\r\n for ind in self.population:\r\n ind.fit=fitness(ind) \r\n def getBest(self):\r\n return self.population[np.argmax(self.population)]\r\n \r\n# Mutation method. The mutation can be vetorial or absolute.\r\ndef mutate(indiv):\r\n\r\n global taxaMut,chanceMut\r\n\r\n if random.random()=bestIndiv.fit:\r\n bestIndiv=indiv\r\n return bestIndiv\r\n \r\n# Generate a new population by performing crossovers with best and the reminder\r\n# population\r\ndef genNewPop(best,pop): \r\n newpop=population()\r\n for indiv in pop.population:\r\n if indiv == best:\r\n newpop.population.append(indiv)\r\n continue\r\n else:\r\n temp=weightedCrossover([best,indiv])\r\n newpop.population.append(temp)\r\n return newpop\r\n\r\n# Remove the n less fitted individuals, replacing them by new ones\r\ndef removeSuckers(pop,n):\r\n \r\n def getFit(indiv):\r\n return indiv.fit\r\n pop.population.sort(reverse=False,key=getFit)\r\n for i in range(0,n):\r\n pop.population[i]=ind()\r\n \r\n# Returns the mean fitness of poppulation in pop\r\ndef getPopMean(pop):\r\n temp=0.0\r\n tam=len(pop.population)\r\n for indiv in pop.population:\r\n temp+=indiv.fit\r\n return temp/tam\r\n\r\n# Not used. Divide all chromossomes of a population by the highest number \r\n# amongst them\r\ndef normalizePop(pop):\r\n for indiv in pop.population: \r\n maxF=0 \r\n for line in indiv.cromo.freqFactor:\r\n for i in range(0,len(np.array(line)[0])): \r\n if abs(line[0,i]) > maxF:\r\n maxF=abs(line[0,i])\r\n \r\n for line in indiv.cromo.freqFactor:\r\n for i in range(0,len(np.array(line)[0])): \r\n line[0,i]/=maxF\r\n \r\n# Plot a graph\r\ndef plotGens(best,mean):\r\n plt.plot(best,'go')\r\n plt.plot(mean,'b-')\r\n\r\n# Class for controlling the GA variables\r\nclass populationControl():\r\n global tamPop,\\\r\n taxaMut,\\\r\n chanceMut,\\\r\n bestAll,\\\r\n bias,\\\r\n maxGen,\\\r\n tamPop,\\\r\n taxaMut,\\\r\n taxaMutMax,\\\r\n chanceMut,\\\r\n continuous,\\\r\n binaryFit,\\\r\n multFac,\\\r\n binaryCrossChance,\\\r\n taxaMutMult,\\\r\n taxaMutMin\r\n\r\n def __init__(self):\r\n self._tamPop=tamPop\r\n self._taxaMut=taxaMut\r\n self._chanceMut=chanceMut\r\n self._bias=bias\r\n self._maxGen=maxGen\r\n self._tamPop=tamPop \r\n self._taxaMutMin=taxaMutMin\r\n self._taxaMutMax=taxaMutMax\r\n self._chanceMut=chanceMut\r\n self._continuous=continuous\r\n self._binaryFit=binaryFit\r\n self._multFac=multFac\r\n self._binaryCrossChance=binaryCrossChance\r\n self._taxaMutMult=taxaMutMult\r\n self._counter=0\r\n self._expansion=False\r\n \r\n def control(self,gen,counter,best,last):\r\n global taxaMut\r\n# taxaMut=self._taxaMutMax\r\n ascendingCounter=0\r\n if gen>25:\r\n if best.fit<=last.fit*1.001: #If the fitness doesnt grow by 0.1%\r\n self._counter+=1\r\n else:\r\n # taxaMut=self._taxaMut\r\n chanceMut=self._chanceMut\r\n self._expansion=False\r\n self._counter=0\r\n ascendingCounter=0\r\n \r\n \r\n if self._counter==8: # If the fitness doesnt grow in n generations\r\n if self._expansion: # If it the taxaMut is increasing \r\n if taxaMutself._taxaMutMin: # If it is bigger than the minimum\r\n taxaMut/=self._taxaMutMult\r\n else: # If it is less than the minimum\r\n self._expansion=True \r\n \r\n self._counter=0 \r\n \r\n\r\ndef main():\r\n \r\n global maxFreq,\\\r\n freqStep,\\\r\n tamPop,\\\r\n taxaMut,\\\r\n chanceMut,\\\r\n nArq,\\\r\n bestAll,\\\r\n startOver,\\\r\n bestTypes\r\n \r\n gen=0\r\n counter=0\r\n last=ind()\r\n bestVec=[]\r\n meanVec=[]\r\n taxaVec=[]\r\n taxaMut=taxaMutMax\r\n\r\n\r\n\r\n# plotter=dataPlotter.dataPlotter('Geracao','Melhor de Todos',bestVec)\r\n# threading.Thread(target=plotter.start).start()\r\n controller=populationControl()\r\n readArqs(sourceType)\r\n if sourceType=='bioplux':\r\n nArq=len(getArqs())\r\n elif sourceType=='ninapro':\r\n nArq=len(real)\r\n if startOver:\r\n pop = population()\r\n pop.initPop(tamPop)\r\n else:\r\n pop=bestAll\r\n while gen Config:\n \"\"\"Assemble config for given target and program directory.\n\n Mbed library and application specific config parameters are parsed from mbed_lib.json and mbed_app.json files\n located in the project source tree.\n The config files contain sets of \"labels\" which correspond to directory names in the mbed-os source tree. These\n labels are used to determine which mbed_lib.json files to include in the final configuration.\n\n The mbed_app.json config overrides must be applied after all the mbed_lib.json files have been parsed.\n Unfortunately, mbed_app.json may also contain filter labels to tell us which mbed libs we're depending on.\n This means we have to collect the filter labels from mbed_app.json before parsing any other config files.\n Then we parse all the required mbed_lib config and finally apply the app overrides.\n\n Args:\n target_attributes: Mapping of target specific config parameters.\n search_paths: Iterable of paths to search for mbed_lib.json files.\n mbed_app_file: The path to mbed_app.json. This can be None.\n \"\"\"\n mbed_lib_files = list(\n set(\n itertools.chain.from_iterable(\n find_files(\"mbed_lib.json\", path.absolute().resolve()) for path in search_paths\n )\n )\n )\n return _assemble_config_from_sources(target_attributes, mbed_lib_files, mbed_app_file)\n\n\ndef _assemble_config_from_sources(\n target_attributes: dict, mbed_lib_files: List[Path], mbed_app_file: Optional[Path] = None\n) -> Config:\n config = Config(source.prepare(target_attributes, source_name=\"target\"))\n previous_filter_data = None\n app_data = None\n if mbed_app_file:\n # We need to obtain the file filter data from mbed_app.json so we can select the correct set of mbed_lib.json\n # files to include in the config. We don't want to update the config object with all of the app settings yet\n # as we won't be able to apply overrides correctly until all relevant mbed_lib.json files have been parsed.\n app_data = source.from_file(\n mbed_app_file, default_name=\"app\", target_filters=FileFilterData.from_config(config).labels\n )\n _get_app_filter_labels(app_data, config)\n\n current_filter_data = FileFilterData.from_config(config)\n while previous_filter_data != current_filter_data:\n filtered_files = _filter_files(mbed_lib_files, current_filter_data)\n for config_file in filtered_files:\n config.update(source.from_file(config_file, target_filters=current_filter_data.labels))\n # Remove any mbed_lib files we've already visited from the list so we don't parse them multiple times.\n mbed_lib_files.remove(config_file)\n\n previous_filter_data = current_filter_data\n current_filter_data = FileFilterData.from_config(config)\n\n # Apply mbed_app.json data last so config parameters are overriden in the correct order.\n if app_data:\n config.update(app_data)\n\n return config\n\n\ndef _get_app_filter_labels(mbed_app_data: dict, config: Config) -> None:\n requires = mbed_app_data.get(\"requires\")\n if requires:\n config[\"requires\"] = requires\n\n config.update(_get_file_filter_overrides(mbed_app_data))\n\n\ndef _get_file_filter_overrides(mbed_app_data: dict) -> dict:\n return {\"overrides\": [override for override in mbed_app_data.get(\"overrides\", []) if override.modifier]}\n\n\n@dataclass(frozen=True)\nclass FileFilterData:\n \"\"\"Data used to navigate mbed-os directories for config files.\"\"\"\n\n labels: Set[str]\n features: Set[str]\n components: Set[str]\n requires: Set[str]\n\n @classmethod\n def from_config(cls, config: Config) -> \"FileFilterData\":\n \"\"\"Extract file filters from a Config object.\"\"\"\n return cls(\n labels=config.get(\"labels\", set()) | config.get(\"extra_labels\", set()),\n features=set(config.get(\"features\", set())),\n components=set(config.get(\"components\", set())),\n requires=set(config.get(\"requires\", set())),\n )\n\n\ndef _filter_files(files: Iterable[Path], filter_data: FileFilterData) -> Iterable[Path]:\n filters = (\n LabelFilter(\"TARGET\", filter_data.labels),\n LabelFilter(\"FEATURE\", filter_data.features),\n LabelFilter(\"COMPONENT\", filter_data.components),\n RequiresFilter(filter_data.requires),\n )\n return filter_files(files, filters)\n","sub_path":"src/mbed_tools/build/_internal/config/assemble_build_config.py","file_name":"assemble_build_config.py","file_ext":"py","file_size_in_byte":5037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"528738365","text":"from django.shortcuts import get_object_or_404, render, redirect,HttpResponseRedirect\nfrom django.urls import reverse\nfrom django.http import HttpResponseRedirect\nimport datetime\nfrom django.utils import timezone\n\nfrom .models import Person, Offer\nfrom .forms import ContactForm\n\n\ndef spasibo_k(request, spasibo_id=None):\n zakaz = Person.objects.last()\n first_name = zakaz.first_name\n offer_name = zakaz.offer_id\n boss = 'Владимир'\n\n box = {'first_name':first_name, 'offer_name':offer_name, 'boss': boss}\n # box = None\n return render(request, 'event/spasibo.html', box)\n\ndef get_client_ip(request):\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0]\n else:\n ip = request.META.get('REMOTE_ADDR')\n return ip\n\ndef get_name(request):\n if request.method == 'POST':\n form = ContactForm(request.POST)\n if form.is_valid():\n c = form.save()\n # now = datetime.datetime.now()\n # bb = Person(date = timezone.now())\n # bb.save()\n \n # return redirect()\n print(c.id)\n\n zakaz = Person.objects.get(id=c.id)\n first_name = zakaz.first_name\n offer_name = zakaz.offer_id\n boss = 'Владимир'\n\n box = {'first_name':first_name, 'offer_name':offer_name, 'boss': boss}\n # box = None\n return render(request, 'event/spasibo.html', box)\n\n return HttpResponseRedirect('/spasibo/')\n\n\n \n # return redirect('event:spasibo_k', spasibo_id = c.id)\n else:\n print('nerabotaet')\n else:\n form = ContactForm()\n ip = get_client_ip(request)\n return render(request, 'event/hello.html', {'form': form, 'ip':ip})\n\n\n\n# def homepage(request, first_name=''):\n# first_name = Person.objects.get(id=1)\n# b = first_name.first_name\n# offer_name = Offer.objects.get(id=1)\n# offer_name = offer_name.offer_name\n# # print(b)\n# all_events = Offer.objects.all()\n# boss = 'Владимир'\n\n# box = {'first_name':b, 'offer_name':offer_name, 'all_events':all_events, 'boss': boss}\n# return render(request, 'event/hello.html', box)\n\ndef person_id(request):\n pass\n","sub_path":"event/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"25827118","text":"from PyQt5 import QtWidgets, QtCore, QtGui\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nimport sys\n\nclass MyWindow(QWidget):\n def __init__(self):\n super().__init__()\n self.initUI()\n self.resize(500, 500)\n\n def initUI(self):\n self.v_layout=QVBoxLayout()\n self.h1_layout=QHBoxLayout()\n self.h2_layout=QHBoxLayout()\n self.h3_layout=QHBoxLayout()\n self.h4_layout=QHBoxLayout()\n self.h5_layout=QHBoxLayout()\n self.h6_layout=QHBoxLayout()\n\n self.h1_layoutUI()\n self.h2_layoutUI()\n self.h3_layoutUI()\n self.h4_layoutUI()\n self.h5_layoutUI()\n self.h6_layoutUI()\n\n self.v_layout.addItem(self.h1_layout)\n self.v_layout.addItem(self.h2_layout)\n self.v_layout.addItem(self.h3_layout)\n self.v_layout.addItem(self.h4_layout)\n self.v_layout.addItem(self.h5_layout)\n self.v_layout.addItem(self.h6_layout)\n self.setLayout(self.v_layout)\n\n def h1_layoutUI(self):\n self.label=QLabel()\n # setting geometry to the label\n # creating label multi line\n self.label.setWordWrap(True)\n # setting style sheet to the label\n self.label.setStyleSheet(\"QLabel\"\n \"{\"\n \"border : 4px solid black;\"\n \"background : white;\"\n \"}\")\n # setting alignment to the label\n self.label.setAlignment(Qt.AlignRight)\n # setting font\n self.label.setFont(QFont('Arial', 15))\n\n self.label.setFixedHeight(200)\n\n self.h1_layout.addWidget(self.label)\n\n def h2_layoutUI(self):\n self.push_clear=QPushButton(\"Clear\")\n self.push_clear.setStyleSheet(\"QPushButton::pressed\"\n \"{\"\n \"background-color: red\"\n \"}\")\n self.push_del=QPushButton(\"Del\")\n self.push_del.setStyleSheet(\"QPushButton::pressed\"\n \"{\"\n \"background-color: red\"\n \"}\")\n\n self.push_clear.clicked.connect(self.action_clear)\n self.push_del.clicked.connect(self.action_del)\n\n self.h2_layout.addWidget(self.push_clear)\n self.h2_layout.addWidget(self.push_del)\n\n\n def h3_layoutUI(self):\n self.push_1=QPushButton(\"1\")\n self.push_1.setStyleSheet(\"QPushButton::pressed\"\n \"{\"\n \"background-color: red\"\n \"}\")\n self.push_2=QPushButton(\"2\")\n self.push_2.setStyleSheet(\"QPushButton::pressed\"\n \"{\"\n \"background-color: red\"\n \"}\")\n self.push_3=QPushButton(\"3\")\n self.push_3.setStyleSheet(\"QPushButton::pressed\"\n \"{\"\n \"background-color: red\"\n \"}\")\n self.push_mul=QPushButton(\"*\")\n self.push_mul.setStyleSheet(\"QPushButton::pressed\"\n \"{\"\n \"background-color: red\"\n \"}\")\n\n self.push_1.clicked.connect(self.action1)\n self.push_2.clicked.connect(self.action2)\n self.push_3.clicked.connect(self.action3)\n self.push_mul.clicked.connect(self.action_mul)\n\n self.h3_layout.addWidget(self.push_1)\n self.h3_layout.addWidget(self.push_2)\n self.h3_layout.addWidget(self.push_3)\n self.h3_layout.addWidget(self.push_mul)\n\n def h4_layoutUI(self):\n self.push_4=QPushButton(\"4\")\n self.push_4.setStyleSheet(\"QPushButton::pressed\"\n \"{\"\n \"background-color: red\"\n \"}\")\n self.push_5=QPushButton(\"5\")\n self.push_5.setStyleSheet(\"QPushButton::pressed\"\n \"{\"\n \"background-color: red\"\n \"}\")\n self.push_6=QPushButton(\"6\")\n self.push_6.setStyleSheet(\"QPushButton::pressed\"\n \"{\"\n \"background-color: red\"\n \"}\")\n self.push_minus=QPushButton(\"-\")\n self.push_minus.setStyleSheet(\"QPushButton::pressed\"\n \"{\"\n \"background-color: red\"\n \"}\")\n\n self.push_4.clicked.connect(self.action4)\n self.push_5.clicked.connect(self.action5)\n self.push_6.clicked.connect(self.action6)\n self.push_minus.clicked.connect(self.action_minus)\n\n self.h4_layout.addWidget(self.push_4)\n self.h4_layout.addWidget(self.push_5)\n self.h4_layout.addWidget(self.push_6)\n self.h4_layout.addWidget(self.push_minus)\n\n def h5_layoutUI(self):\n self.push_7=QPushButton(\"7\")\n self.push_7.setStyleSheet(\"QPushButton::pressed\"\n \"{\"\n \"background-color: red\"\n \"}\")\n self.push_8=QPushButton(\"8\")\n self.push_8.setStyleSheet(\"QPushButton::pressed\"\n \"{\"\n \"background-color: red\"\n \"}\")\n self.push_9=QPushButton(\"9\")\n self.push_9.setStyleSheet(\"QPushButton::pressed\"\n \"{\"\n \"background-color: red\"\n \"}\")\n self.push_plus=QPushButton(\"+\")\n self.push_plus.setStyleSheet(\"QPushButton::pressed\"\n \"{\"\n \"background-color: red\"\n \"}\")\n\n self.push_7.clicked.connect(self.action7)\n self.push_8.clicked.connect(self.action8)\n self.push_9.clicked.connect(self.action9)\n self.push_plus.clicked.connect(self.action_plus)\n\n self.h5_layout.addWidget(self.push_7)\n self.h5_layout.addWidget(self.push_8)\n self.h5_layout.addWidget(self.push_9)\n self.h5_layout.addWidget(self.push_plus)\n\n def h6_layoutUI(self):\n self.push_0=QPushButton(\"0\")\n self.push_0.setStyleSheet(\"QPushButton::pressed\"\n \"{\"\n \"background-color: red\"\n \"}\")\n self.push_point=QPushButton(\".\")\n self.push_point.setStyleSheet(\"QPushButton::pressed\"\n \"{\"\n \"background-color: red\"\n \"}\")\n self.push_div=QPushButton(\"/\")\n self.push_div.setStyleSheet(\"QPushButton::pressed\"\n \"{\"\n \"background-color: red\"\n \"}\")\n self.push_equal=QPushButton(\"=\")\n self.push_equal.setStyleSheet(\"QPushButton::pressed\"\n \"{\"\n \"background-color: red\"\n \"}\")\n\n self.push_0.clicked.connect(self.action0)\n self.push_point.clicked.connect(self.action_point)\n self.push_div.clicked.connect(self.action_div)\n self.push_equal.clicked.connect(self.action_equal)\n\n self.h6_layout.addWidget(self.push_0)\n self.h6_layout.addWidget(self.push_point)\n self.h6_layout.addWidget(self.push_div)\n self.h6_layout.addWidget(self.push_equal)\n\n\n def action_equal(self):\n\n # get the label text\n equation = self.label.text()\n try:\n # getting the ans\n ans = eval(equation)\n\n # setting text to the label\n self.label.setText(str(ans))\n\n except:\n # setting text to the label\n self.label.setText(\"Wrong Input\")\n\n def action_plus(self):\n # appending label text\n text = self.label.text()\n self.label.setText(text + \" + \")\n\n def action_minus(self):\n # appending label text\n text = self.label.text()\n self.label.setText(text + \" - \")\n\n def action_div(self):\n # appending label text\n text = self.label.text()\n self.label.setText(text + \" / \")\n\n def action_mul(self):\n # appending label text\n text = self.label.text()\n self.label.setText(text + \" * \")\n\n def action_point(self):\n # appending label text\n text = self.label.text()\n self.label.setText(text + \".\")\n\n def action0(self):\n # appending label text\n text = self.label.text()\n self.label.setText(text + \"0\")\n\n def action1(self):\n # appending label text\n text = self.label.text()\n self.label.setText(text + \"1\")\n\n def action2(self):\n # appending label text\n text = self.label.text()\n self.label.setText(text + \"2\")\n\n def action3(self):\n # appending label text\n text = self.label.text()\n self.label.setText(text + \"3\")\n\n def action4(self):\n # appending label text\n text = self.label.text()\n self.label.setText(text + \"4\")\n\n def action5(self):\n # appending label text\n text = self.label.text()\n self.label.setText(text + \"5\")\n\n def action6(self):\n # appending label text\n text = self.label.text()\n self.label.setText(text + \"6\")\n\n def action7(self):\n # appending label text\n text = self.label.text()\n self.label.setText(text + \"7\")\n\n def action8(self):\n # appending label text\n text = self.label.text()\n self.label.setText(text + \"8\")\n\n def action9(self):\n # appending label text\n text = self.label.text()\n self.label.setText(text + \"9\")\n\n def action_clear(self):\n # clearing the label text\n self.label.setText(\"\")\n\n def action_del(self):\n # clearing a single digit\n text = self.label.text()\n print(text[:len(text) - 1])\n self.label.setText(text[:len(text) - 1])\n\n def call_layout(self):\n return self.g_layout\n\n\nif __name__ == '__main__':\n app = QtWidgets.QApplication(sys.argv)\n window = MyWindow() #開始創建視窗\n window.show()\n sys.exit(app.exec_())\n\n\n\n\n","sub_path":"pythonProject/Simple_PySide_Base-master/cal.py","file_name":"cal.py","file_ext":"py","file_size_in_byte":10891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"177047949","text":"from tensorflow.examples.tutorials.mnist import input_data\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, Dropout, Input, Reshape, BatchNormalization , Flatten\nfrom keras.layers import Lambda, TimeDistributed, Activation,Conv2D, MaxPooling2D #, Merge\nfrom keras import backend as K\nfrom keras.optimizers import SGD, Adadelta, Adam\nfrom keras.losses import categorical_crossentropy\nfrom keras.datasets import mnist\nfrom keras.utils import to_categorical\n\nfrom sklearn.metrics import confusion_matrix\nfrom keras import backend as K\nfrom keras.utils import np_utils\n#from keras.utils import np_utils , plot_model\n#from tensorflow.keras.callbacks import TensorBoard\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Convolution2D, MaxPooling2D\n\nimport platform as plat\nimport os, sys\nimport time\nimport matplotlib.pyplot as plt \n\nimport keras as kr\nimport numpy as np\nimport random\n\nfrom readdata import DataMnist\n\nabspath = ''\nModelName='003'\npredict_size = 10\nIMG_WIDTH = 28\nIMG_HEIGHT = 28\nIMG_LEN = IMG_WIDTH * IMG_HEIGHT\n#kernel_size = (5, 5)\nkernel_size = (3, 3)\nflagquick = True\n\nif flagquick:\n\tdefsave_step = 50\nelse:\n\tdefsave_step = 500\n\n#reference URL:https://blog.csdn.net/briblue/article/details/80398369 \n#ref 基于Keras+CNN的MNIST数据集手写数字分类 - 简书 https://www.jianshu.com/p/3a8b310227e6\nclass ModelMnist():\n\tdef __init__(self, datapath):\n\t\tMS_OUTPUT_SIZE = 10\n\t\tself.MS_OUTPUT_SIZE = MS_OUTPUT_SIZE # 神经网络最终输出的每一个字符向量维度的大小\n\t\tself.label_max_string_length = 64\n\t\tself._model = self.CreateModel() \n\t\t#self.base_model = self._model\n\t\tself.datapath = datapath\n\n\tdef loss_b(self, y_true, y_pred):\n\t\treturn categorical_crossentropy(y_true, y_pred)\n\t\n\tdef CreateModel(self):\n\t\tinput_data = Input(name='the_input', shape=(IMG_WIDTH, IMG_HEIGHT, 1))\n\t\t\n\t\tlayer_h1 = Conv2D(32, kernel_size, use_bias=False, activation='relu', padding='same', kernel_initializer='he_normal')(input_data) # 卷积层\n\t\t#layer_h1 = Dropout(0.05)(layer_h1)\n\t\tlayer_h2 = Conv2D(64, kernel_size, use_bias=True, activation='relu', padding='same', kernel_initializer='he_normal')(layer_h1) # 卷积层\n\t\tlayer_h3 = MaxPooling2D(pool_size=2, strides=None, padding=\"valid\")(layer_h2) # 池化层\n\t\t\n\t\tlayer_h4 = Flatten()(layer_h3)\n\t\t#layer_h5 = Dense(64*2, activation=\"relu\", use_bias=True, kernel_initializer='he_normal')(layer_h4) # 全连接层\n\t\t#num_output = Dense(self.MS_OUTPUT_SIZE, use_bias=True, kernel_initializer='he_normal', activation='softmax', name='num_output')(layer_h5) # 全连接层\n\t\tlayer_h5 = Dense(64*2, activation=\"relu\", use_bias=True, kernel_initializer='he_normal')(layer_h4) # 全连接层\n\t\tbigger5_output = Dense(2, use_bias=True, kernel_initializer='he_normal', activation='softmax', name='bigger5_output')(layer_h5) # 全连接层\n\n\n\t\t#layer_h5 = Dense(64*2, activation=\"relu\", use_bias=True, kernel_initializer='he_normal')(layer_h4) # 全连接层\n\t\t#odd_even_output = Dense(2, use_bias=True, kernel_initializer='he_normal', activation='softmax', name='odd_even_output')(layer_h5) # 全连接层\n\t\t\n\t\t#y_2kinds = Input(name='y_2kinds', shape=[1], dtype='int64')\n\t\t#y_odds = Input(name='y_odds', shape=[1], dtype='int64')\n\t\tmodel = Model(inputs=input_data, outputs=[bigger5_output])\n\n\t\tlosses = {'bigger5_output': self.loss_b,\n\t\t\t\t}\n\n\t\tmodel.compile(optimizer=Adam(),\n\t\t\t\t\t\tloss=losses,\n\t\t\t\t\t\tmetrics={ 'bigger5_output': 'accuracy'})\n\t\tmodel.summary()\n\t\t#plot_model(model, abspath + 'mnist_model'+os.sep + 'm' + ModelName + os.sep + './model.png',show_shapes=True)\n\t\t\n\t\treturn model\n\t\n\tdef restoreFromLastPoint(self, ModelName, save_step):\n\t\tif(not os.path.exists('step'+ModelName+'.txt')): \n\t\t\tprint(\"return 0\")\n\t\t\treturn 0\n\t\tf = open('step'+ModelName+'.txt','r')\n\t\ttxt_mode_name = f.read()\n\t\tf.close()\n\t\tif os.path.exists(txt_mode_name + '.model'):\n\t\t\tself.LoadModel(txt_mode_name + '.model')\n\t\telse:\n\t\t\tos.remove('step'+ModelName+'.txt')\n\t\t\treturn 0\n\t\tprint(txt_mode_name)\n\t\t#for example, get mnist_model/m002/speech_model002_e_0_step_28000\n\t\t#need return 28000 / save_step = 28000 / 500\n\t\ttxt_lines=txt_mode_name.split('_')\n\t\tprint('****restoreFromLastPoint**** ' , txt_lines[-1], int(txt_lines[-1])//save_step)\n\t\treturn int(txt_lines[-1])//save_step\n\t\t\t\n\tdef TrainModel(self, datapath, epoch = 8, save_step = 1000, batch_size = 100, filename = abspath + 'mnist_model/m' + ModelName + '/speech_model'+ModelName):\n\t\t'''\n\t\t训练模型\n\t\t参数:\n\t\t\tdatapath: 数据保存的路径\n\t\t\tepoch: 迭代轮数\n\t\t\tsave_step: 每多少步保存一次模型\n\t\t\tfilename: 默认保存文件名,不含文件后缀名\n\t\t'''\n\t\tn_step = self.restoreFromLastPoint(ModelName, save_step)\n\t\t#n_step = 0\n\t\tdata=DataMnist(datapath, type = 'train', addnoise = False)\n\t\t\n\t\tnum_data = data.GetDataNum() # 获取数据的数量\n\t\t\n\t\tyielddatas = data.data_genetator_only_big5(batch_size, IMG_LEN)\n\n\t\t#两步轻松实现在Keras中使用Tensorboard - 简书\n\t\t#https: // www.jianshu.com / p / b0e98ee80a49\n\t\tNAME = 'mnist-CNN-{}'.format(time.asctime( time.localtime(time.time()) ))\n\t\t#tensorboard = TensorBoard(log_dir='mnist_model'+os.sep + 'logs' + os.sep + '{}'.format(NAME))\n\t\t#tensorboard --logdir ./mnist_model/logs\n\n\t\t\n\t\tfor epoch in range(epoch): # 迭代轮数\n\t\t\tprint('[running] train epoch %d .' % epoch)\n\t\t\t#n_step = 0 # 迭代数据数\n\t\t\twhile True:\n\t\t\t\ttry:\n\t\t\t\t\tprint('[message] epoch %d . Have train datas %d+'%(epoch, n_step*save_step))\n\t\t\t\t\t# data_genetator是一个生成器函数\n\t\t\t\t\t\n\t\t\t\t\t#self._model.fit_generator(yielddatas, save_step, nb_worker=2)\n\t\t\t\t\tself._model.fit_generator(yielddatas, save_step) #, callbacks=[tensorboard])\n\t\t\t\t\tn_step += 1\n\t\t\t\texcept StopIteration:\n\t\t\t\t\tprint('[error] generator error. please check data format.')\n\t\t\t\t\tbreak\n\t\t\t\t\n\t\t\t\tself.SaveModel(comment='_e_'+str(epoch)+'_step_'+str(n_step * save_step))\n\t\t\t\tself.TestModel(self.datapath, str_dataset='train', data_count = 4)\n\t\t\t\tself.TestModel(self.datapath, str_dataset='dev', data_count = 4)\n\n\tdef TestModel(self, datapath='', str_dataset='dev', data_count = 32, out_report = False, show_ratio = True, io_step_print = 10, io_step_file = 10):\n\t\t'''\n\t\t测试检验模型效果\n\t\t\n\t\tio_step_print\n\t\t\t为了减少测试时标准输出的io开销,可以通过调整这个参数来实现\n\t\t\n\t\tio_step_file\n\t\t\t为了减少测试时文件读写的io开销,可以通过调整这个参数来实现\n\t\t\n\t\t'''\n\t\tprint(\"dataset type=\", str_dataset)\n\t\tdata=DataMnist(self.datapath, type = str_dataset, addnoise = False)\n\t\t#data.LoadDataList(str_dataset) \n\t\tnum_data = data.GetDataNum() # 获取数据的数量\n\t\tif(data_count <= 0 or data_count > num_data): # 当data_count为小于等于0或者大于测试数据量的值时,则使用全部数据来测试\n\t\t\tdata_count = num_data\n\t\t\n\t\ttry:\n\t\t\tran_num = random.randint(0,num_data - 1) # 获取一个随机数\n\t\t\t\n\t\t\twords_num = 0\n\t\t\tword_error_num = 0\n\t\t\t\n\t\t\tnowtime = time.strftime('%Y%m%d_%H%M%S',time.localtime(time.time()))\n\t\t\tif(out_report == True):\n\t\t\t\ttxt_obj = open('Test_Report_' + str_dataset + '_' + nowtime + '.txt', 'w', encoding='UTF-8') # 打开文件并读入\n\t\t\t\n\t\t\ttxt = '测试报告\\n模型编号 ' + ModelName + '\\n\\n'\n\t\t\tfor i in range(data_count):\n\t\t\t\tdata_input, data_labels, y_2kind, y_odd = data.GetData((ran_num + i) % num_data, 2) # 从随机数开始连续向后取一定数量数据\n\t\t\t\t\n\t\t\t\t# 数据格式出错处理 开始\n\t\t\t\t# 当输入的wav文件长度过长时自动跳过该文件,转而使用下一个wav文件来运行\n\t\t\t\tnum_bias = 0\n\t\t\t\twhile(data_input.shape[0] > IMG_LEN):\n\t\t\t\t\tprint('*[Error]','wave data lenghth of num',(ran_num + i) % num_data, 'is too long.','\\n A Exception raise when test Speech Model.')\n\t\t\t\t\tnum_bias += 1\n\t\t\t\t\tdata_input, data_labels, y_2kind, y_odd = data.GetData((ran_num + i + num_bias) % num_data) # 从随机数开始连续向后取一定数量数据\n\t\t\t\t# 数据格式出错处理 结束\n\t\t\t\t\n\t\t\t\taax=np.array([0,1,2,3,4,5,6,7,8,9])\n\t\t\t\tnum = np.sum(data_labels*aax)\n\t\t\t\tpre = self.Predict(num, data_input, data_input.shape[0] // 8)\n\t\t\t\t#print(\"pre=\", (pre))\n\t\t\t\twords_n = data_labels.shape[0] # 获取每个句子的字数\n\t\t\t\twords_num += words_n # 把句子的总字数加上\n\t\t\t\t#edit_distance = GetEditDistance(y_2kind, pre) # 获取编辑距离\n\t\t\t\tedit_distance = GetLoss(y_2kind, pre) # 获取编辑距离\n\t\t\t\tif(edit_distance <= words_n): # 当编辑距离小于等于句子字数时\n\t\t\t\t\tword_error_num += edit_distance # 使用编辑距离作为错误字数\n\t\t\t\telse: # 否则肯定是增加了一堆乱七八糟的奇奇怪怪的字\n\t\t\t\t\tword_error_num += words_n # 就直接加句子本来的总字数就好了\n\t\t\t\t\n\t\t\t\tif((i % io_step_print == 0 or i == data_count - 1) and show_ratio == True):\n\t\t\t\t\t#print('测试进度:',i,'/',data_count)\n\t\t\t\t\tprint('Test Count: ',i,'/',data_count)\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(out_report == True):\n\t\t\t\t\tif(i % io_step_file == 0 or i == data_count - 1):\n\t\t\t\t\t\ttxt_obj.write(txt)\n\t\t\t\t\t\ttxt = ''\n\t\t\t\t\t\n\t\t\t\t\ttxt += str(i) + '\\n'\n\t\t\t\t\ttxt += 'True:\\t' + str(data_labels) + '\\n'\n\t\t\t\t\ttxt += 'Pred:\\t' + str(pre) + '\\n'\n\t\t\t\t\ttxt += '\\n'\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t\t#print('*[测试结果] 识别 ' + str_dataset + ' 集单字错误率:', word_error_num / words_num * 100, '%')\n\t\t\tprint('*[Test Result] Speech Recognition ' + str_dataset + ' set word error ratio: ', word_error_num / words_num * 100, '%')\n\t\t\tif(out_report == True):\n\t\t\t\ttxt += '*[测试结果] 识别 ' + str_dataset + ' 集单字错误率: ' + str(word_error_num / words_num * 100) + ' %'\n\t\t\t\ttxt_obj.write(txt)\n\t\t\t\ttxt = ''\n\t\t\t\ttxt_obj.close()\n\t\t\t\n\t\texcept StopIteration:\n\t\t\tprint('[Error] Model Test Error. please check data format.')\n\t\n\tdef get2kindsstr(self, num, a1, a2):\n\t\tif a1 > a2:\n\t\t\treturn \"{} < 5\".format(num)\n\t\treturn \"{} >= 5\".format(num)\n\n\t#y_odds[0] = 1 if number is even.\n\tdef getoddstr(self, number, a1, a2):\n\t\tcolor_str_head_p = '\\033[1;40;35m'\n\t\tcolor_str_tail = '\\033[0m'\n\t\tevenflag = (number % 2) == 0\n\t\tcorrect = False\n\t\tif evenflag and a1 > a2:\n\t\t\tcorrect = True\n\t\t\tcolor_str_head_p = ''\n\t\t\tcolor_str_tail = ''\n\t\tif evenflag == False and a1 < a2:\n\t\t\tcorrect = True\n\t\t\tcolor_str_head_p = ''\n\t\t\tcolor_str_tail = ''\n\t\tif a1 > a2:\n\t\t\treturn color_str_head_p + \"{} is even number\".format(number) + color_str_tail\n\t\treturn color_str_head_p + \"{} is odd number\".format(number) + color_str_tail\n\n\tdef Predict(self, num, data_input, input_len):\n\t\t'''\n\t\t预测结果\n\t\t返回语音识别后的拼音符号列表\n\t\t'''\n\t\t\n\t\tbatch_size = 1 \n\t\tin_len = np.zeros((batch_size),dtype = np.int32)\n\t\t\n\t\tin_len[0] = input_len\n\t\t\n\t\tx_in = np.zeros((batch_size, 28, 28, 1), dtype=np.float)\n\t\t\n\t\tfor i in range(batch_size):\n\t\t\tx_in[i,0:len(data_input)] = data_input\n\t\t\n\t\t#print(f'x_in:{x_in.shape}')\n\t\tbase_pred = self.model.predict(x = x_in)\n\t\t\n\t\t#print('base_pred:\\n', base_pred)\n\t\t\n\t\t#y_p = base_pred\n\t\t#for j in range(200):\n\t\t#\tmean = np.sum(y_p[0][j]) / y_p[0][j].shape[0]\n\t\t#\tprint('max y_p:',np.max(y_p[0][j]),'min y_p:',np.min(y_p[0][j]),'mean y_p:',mean,'mid y_p:',y_p[0][j][100])\n\t\t#\tprint('argmin:',np.argmin(y_p[0][j]),'argmax:',np.argmax(y_p[0][j]))\n\t\t#\tcount=0\n\t\t#\tfor i in range(y_p[0][j].shape[0]):\n\t\t#\t\tif(y_p[0][j][i] < mean):\n\t\t#\t\t\tcount += 1\n\t\t#\tprint('count:',count)\n\t\t\n\t\t#base_pred =base_pred[:]\n\t\t#print('base_pred:',base_pred)\n\t\ty_2kinds = base_pred[0]\n\t\tprint('================================')\n\t\tprint('y_2kinds:', self.get2kindsstr(int(num), y_2kinds[0], y_2kinds[1]))\n\t\t#base_pred =base_pred[:, 2:, :]\n\t\t\n\t\t#r = K.ctc_decode(base_pred, in_len, greedy = True, beam_width=100, top_paths=1)\n\t\t\n\t\t#print('r', r)\n\t\t\n\t\t\n\t\t#r1 = K.get_value(r[0][0])\n\t\t#print('r1', r1)\n\t\t\n\t\t\n\t\t#r2 = K.get_value(r[1])\n\t\t#print(r2)\n\t\t\n\t\t#r1=r1[0]\n\t\treturn y_2kinds\n\t\tpass\n\n\tdef LoadModel(self,filename = abspath + 'mnist_model/m'+ModelName+'/speech_model'+ModelName+'.model'):\n\t\t'''\n\t\t加载模型参数\n\t\t'''\n\t\tself._model.load_weights(filename)\n\t\t#self.base_model.load_weights(filename + '.base')\n\n\tdef SaveModel(self,filename = abspath + 'mnist_model/m'+ModelName+'/speech_model'+ModelName,comment=''):\n\t\t'''\n\t\t保存模型参数\n\t\t'''\n\t\tdir1,fname = os.path.split(filename)\n\t\tos.makedirs(dir1, exist_ok=True)\n\t\tself._model.save_weights(filename + comment + '.model')\n\t\t#self.model.save_weights(filename + comment + '.model.base')\n\t\t# 需要安装 hdf5 模块\n\t\tself._model.save(filename + comment + '.h5')\n\t\t#self.base_model.save(filename + comment + '.base.h5')\n\t\tf = open('step'+ModelName+'.txt','w')\n\t\tf.write(filename+comment)\n\t\tf.close()\n\n\t \n\t@property\n\tdef model(self):\n\t\t'''\n\t\t返回 model\n\t\t'''\n\t\treturn self._model\n\ndef conv2d(size):\n\t\treturn Conv2D(size, (3,3), use_bias=True, activation='relu',\n\t\t\t\tpadding='same', kernel_initializer='he_normal')\n\n\ndef norm(x):\n\t\treturn BatchNormalization(axis=-1)(x)\n\n\ndef maxpool(x):\n\t\treturn MaxPooling2D(pool_size=(2,2), strides=None, padding=\"valid\")(x)\n\t\ndef dense(units, activation=\"relu\"):\n\t\treturn Dense(units, activation=activation, use_bias=True,\n\t\t\t\tkernel_initializer='he_normal')\n\n\n# x.shape=(none, none, none)\n# output.shape = (1/2, 1/2, 1/2)\ndef cnn_cell(size, x, pool=True):\n x = norm(conv2d(size)(x))\n x = norm(conv2d(size)(x))\n if pool:\n x = maxpool(x)\n return x\n\nimport difflib\n\ndef GetEditDistance(str1, str2):\n leven_cost = 0\n s = difflib.SequenceMatcher(None, str1, str2)\n for tag, i1, i2, j1, j2 in s.get_opcodes():\n #print('{:7} a[{}: {}] --> b[{}: {}] {} --> {}'.format(tag, i1, i2, j1, j2, str1[i1: i2], str2[j1: j2]))\n if tag == 'replace':\n leven_cost += max(i2-i1, j2-j1)\n elif tag == 'insert':\n leven_cost += (j2-j1)\n elif tag == 'delete':\n leven_cost += (i2-i1)\n if leven_cost != 0:\n \tprint(\"leven_cost=\", (leven_cost))\n return leven_cost\n\ndef GetLoss(str1, str2):\n #mse2 = tf.losses.mean_squared_error(str1, str2)\n t1, t2 = str1\n a1, a2 = str2\n return np.abs((t1 - a1) + (t2 - a2))\n\nif(__name__=='__main__'):\n\tdatapath = abspath + ''\n\tmodelpath = abspath + 'mnist_model'\n\t\n\t\n\tif(not os.path.exists(modelpath)): \n\t\tos.makedirs(modelpath) \n\t'''\n\tmnist = input_data.read_data_sets(\"MNIST_data\",one_hot=True)\n\t#validation_images = train_images[:validation_size]\n\t#validation_labels = train_labels[:validation_size]\n\t#train_images = train_images[validation_size:]\n\t#train_labels = train_labels[validation_size:]\n\tprint(mnist.train.images.shape)\n\tprint(mnist.train.labels.shape)\n\timage = mnist.train.images[11111,:]\n\timage = image.reshape(28,28)\n\t\n\tplt.figure()\n\tplt.imshow(image)\n\t#plt.show()\n\t'''\n\t\n\tsystem_type = plat.system() # 由于不同的系统的文件路径表示不一样,需要进行判断\n\tif(system_type == 'Windows'):\n\t\tdatapath = 'E:\\\\语音数据集'\n\t\tmodelpath = modelpath + '\\\\'\n\telif(system_type == 'Linux'):\n\t\tdatapath = abspath + 'dataset'\n\t\tmodelpath = modelpath + '/'+'m'+ModelName+'/'\n\t\tif(not os.path.exists(modelpath)): \n\t\t\tos.makedirs(modelpath) \n\telse:\n\t\tprint('*[Message] Unknown System\\n')\n\t\tdatapath = 'dataset'\n\t\tmodelpath = modelpath + '/'\n\t\n\t\n\tms = ModelMnist(datapath)\n\t##test code##############\n\t#ms.restoreFromLastPoint(ModelName, defsave_step)\n\t#ms.TrainModel(datapath, epoch = 8, batch_size = 100, save_step = 500) final value here\n\tif flagquick:\n\t\tms.TrainModel(datapath, epoch = 8, batch_size = 10, save_step = defsave_step)\n\telse:\n\t\tms.TrainModel(datapath, epoch = 8, batch_size = 100, save_step = defsave_step)\n\t###########################################\n\ttrain_X, train_y = mnist.load_data()[0]\n\ttrain_X = train_X.reshape(-1, 28, 28, 1)\n\ttrain_X = train_X.astype('float32')\n\ttrain_X /= 255\n\n\ttrain_y = to_categorical(train_y, 10)\n\n\t\n\tbatch_size = 100\n\tepochs = 8\n\t#p train_X.shape\n\t#(60000, 28, 28, 1)\n\tms.model.fit(train_X, train_y,\n\t batch_size=batch_size,\n\t epochs=epochs)\n\n\n\ttest_X, test_y = mnist.load_data()[1]\n\ttest_X = test_X.reshape(-1, 28, 28, 1)\n\ttest_X = test_X.astype('float32')\n\ttest_X /= 255\n\ttest_y = to_categorical(test_y, 10)\n\tloss, accuracy = ms.model.evaluate(test_X, test_y, verbose=1)\n\tprint('loss:%.4f accuracy:%.4f' %(loss, accuracy))\n","sub_path":"model_big5.py","file_name":"model_big5.py","file_ext":"py","file_size_in_byte":16179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"529557021","text":"\nimport re\n\nphone = \"2004-959-559 # 这是一个电话号码\"\n\n# 删除注释\nnum = re.sub(r'#.*$', \"\", phone)\nprint(\"电话号码 : \", num)\n\n# 移除非数字的内容\nnum = re.sub(r'\\D', \"\", phone)\nprint(\"电话号码 : \", num)\n\n\n#电话号码判断\nimport re\ndef checkMobile(strData):\n CMCCRule=r\"^(13[4-9]|15[0-2]|15[7-9]|18[2,3,7,8]|147)\\d{8}$\"\n CCrule=r\"^(13[0,1,2,6]|18[5,6]|145)\\d{8}$\"\n Cnetrule=r\"^(133|153|18[0,1,9])\\d{8}$\"\n rescmcc = re.findall(CMCCRule,strData)\n rescc=re.findall(CCrule,strData)\n rescnet=re.findall(Cnetrule,strData)\n if rescmcc:\n print('%s是中国移动号码'%strData)\n elif rescc:\n print('%s是中国联通号码'%strData)\n elif rescnet:\n print('%s是中国电信号码'%strData)\n else:\n print('这不是一个手机号码')\ncheckMobile('18114090465')\n\n\n\n#正则表达\n#match只能匹配开头\nimport re\na=re.match(r'^\\d{10}$','1203145647')\nprint(a)\n#serach只能总开头匹配,找到一个就停止\nimport re\na=re.search(r'a12','mma1203145647')\nprint(a)\n#findall找所有,将找到的内容存于列表中\nimport re\na=re.findall(r'^A\\d{10}$','a1203145647',re.I) #re.I代表忽略大小写\nprint(a)\n\n\n\nprint(re.findall(r'\\d{10}','123456789'))\nprint(re.findall(r'[2-5]{2}','123456789'))\nprint(re.findall(r'[a-zA-Z]{10}','JhHjhKJhJKJjhGhjHgghJHjklJkjhKJ'))\n","sub_path":"Python基础/基础知识点及作业/正则表达.py","file_name":"正则表达.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"418038116","text":"from django import template\nfrom django.conf import settings\nfrom itsdangerous import TimedSerializer\nfrom markupsafe import Markup\n\nserializer = TimedSerializer(secret_key=settings.SECRET_KEY, salt='crossbar')\n\nregister = template.Library()\n\n\n@register.simple_tag(takes_context=True)\ndef crossbar_head(context):\n if not context.request.user.is_authenticated():\n return \"\"\n key = serializer.dumps(context.request.user.pk)\n return Markup(\n '' % (\n context.request.user.pk, key))\n","sub_path":"crossbar_server/templatetags/crossbar.py","file_name":"crossbar.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"100339752","text":"from django.db import models\nfrom gensim.models import Doc2Vec\nfrom nltk import sent_tokenize, word_tokenize\n\n\ndef direct(complaint):\n model = Doc2Vec.load(\"/home/nusmyhero/symptom_checker_API/symptom_checker/AImodel/social_mining_doc2vec\")\n tokens = tokenize_text(complaint)\n diag_vector = model.infer_vector(tokens)\n pred_diag = model.docvecs.most_similar([diag_vector], topn=1)\n return str(pred_diag[0][0])\n\ndef diagnose(complaint):\n model = Doc2Vec.load(\"/home/nusmyhero/symptom_checker_API/symptom_checker/AImodel/social_mining_diagnosis_doc2vec\")\n tokens = tokenize_text(complaint)\n diag_vector = model.infer_vector(tokens)\n pred_diag = model.docvecs.most_similar([diag_vector], topn=3)\n return str([diag[0].split(\":\")[0] for diag in pred_diag])\n\ndef tokenize_text(text):\n tokens = []\n for sent in sent_tokenize(text):\n for word in word_tokenize(sent):\n if len(word) < 2: # eliminate trivial words with length less than 2\n continue\n tokens.append(word.lower())\n\n return tokens\n\nclass Report(models.Model):\n complaint = models.TextField()\n user = models.CharField(max_length=200)\n diagnosis = models.CharField(default=\"N/A\", max_length=200)\n direction = models.CharField(default=\"N/A\", max_length=10)\n comments = models.TextField(default=\"N/A\")\n\n def save(self, *args, **kwargs):\n if not self.pk:\n self.diagnosis = diagnose(str(self.complaint))\n self.direction = direct(str(self.complaint))\n super(Report, self).save(*args, **kwargs)\n\n def __str__(self):\n return str(self.pk) + \". \" + self.user + ' *** ' + self.complaint[0:50] \\\n + '...' + ' *** ' + self.diagnosis + ' *** ' + self.direction","sub_path":"symptom_checker/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"295420995","text":"\"\"\"illustrates one way to use a custom pickler that is session-aware.\"\"\"\n\nfrom sqlalchemy import *\nfrom sqlalchemy.orm import *\nfrom sqlalchemy.orm.session import object_session\nfrom cStringIO import StringIO\nfrom pickle import Pickler, Unpickler\nimport threading\n\nmeta = MetaData('sqlite://')\nmeta.bind.echo = True\n\nclass MyExt(MapperExtension):\n def populate_instance(self, mapper, selectcontext, row, instance, **flags):\n MyPickler.sessions.current = selectcontext.session\n return EXT_CONTINUE\n def before_insert(self, mapper, connection, instance):\n MyPickler.sessions.current = object_session(instance)\n return EXT_CONTINUE\n def before_update(self, mapper, connection, instance):\n MyPickler.sessions.current = object_session(instance)\n return EXT_CONTINUE\n \nclass MyPickler(object):\n sessions = threading.local()\n\n def persistent_id(self, obj):\n if getattr(obj, \"id\", None) is None:\n sess = MyPickler.sessions.current\n newsess = create_session(bind=sess.connection(class_mapper(Bar)))\n newsess.save(obj)\n newsess.flush()\n key = \"%s:%s\" % (type(obj).__name__, obj.id)\n return key\n\n def persistent_load(self, key):\n name, ident = key.split(\":\")\n sess = MyPickler.sessions.current\n return sess.query(Bar).get(ident)\n\n def dumps(self, graph, protocol):\n src = StringIO()\n pickler = Pickler(src)\n pickler.persistent_id = self.persistent_id\n pickler.dump(graph)\n return src.getvalue()\n\n def loads(self, data):\n dst = StringIO(data)\n unpickler = Unpickler(dst)\n unpickler.persistent_load = self.persistent_load\n return unpickler.load()\n\nfoo_table = Table('foo', meta, \n Column('id', Integer, primary_key=True),\n Column('bar', PickleType(pickler=MyPickler()), nullable=False))\n\nbar_table = Table('bar', meta,\n Column('id', Integer, primary_key=True),\n Column('data', String(40)))\n\nmeta.create_all()\n\nclass Foo(object):\n pass\n\nclass Bar(object):\n def __init__(self, value):\n self.data = value\n \nmapper(Foo, foo_table, extension=MyExt())\nmapper(Bar, bar_table)\n\nsess = create_session()\nf = Foo()\nf.bar = Bar('some bar')\nsess.save(f)\nsess.flush()\nsess.clear()\n\ndel MyPickler.sessions.current\n\nf = sess.query(Foo).get(f.id)\nassert f.bar.data == 'some bar'\n","sub_path":"sqlalchemy/examples/pickle/custom_pickler.py","file_name":"custom_pickler.py","file_ext":"py","file_size_in_byte":2395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"312551050","text":"# hash of connections from -> to,(from,to) in both directions\n# set of visited, key is original (from,to) tuple which is unique\n\nfrom collections import defaultdict\nconnect = defaultdict(list)\n\ndef dfs_p1(this, strength, visited):\n vs = [dfs_p1(to, this+to+strength, visited | set([c])) for (to,c) in connect[this] if c not in visited]\n vs.append(strength)\n return max(vs)\n\ndef dfs_p2(this, length, strength, visited):\n vs = [dfs_p2(to, length+1, this+to+strength, visited | set([c])) for (to,c) in connect[this] if c not in visited]\n vs.append((length,strength))\n return max(vs)\n\n\nwith open('day24.in') as f:\n for (id,line) in enumerate(f):\n (fro,to) = [int(x) for x in line.strip().split('/')]\n connect[fro].append((to,id))\n connect[to].append((fro,id))\n\n#print(dfs_p1(0, 0, set()))\nprint(dfs_p2(0, 0, 0, set()))\n","sub_path":"day24.py","file_name":"day24.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"528343776","text":"import numpy as np\nimport tensorflow as tf\nfrom tfoptests.persistor import TensorFlowPersistor\nfrom tfoptests.test_graph import TestGraph\n\n\nclass MathOpsTen(TestGraph):\n def __init__(self, *args, **kwargs):\n super(MathOpsTen, self).__init__(*args, **kwargs)\n self.input_1 = np.random.uniform(size=(4, 3))\n\n def list_inputs(self):\n return [\"input_1\"]\n\n def get_placeholder_input(self, name):\n if name == \"input_1\":\n return self.input_1\n\n def _get_placeholder_shape(self, name):\n if name == \"input_1\":\n return [None, 3]\n\n\ndef test_mathops_ten():\n mathops_10 = MathOpsTen(seed=19)\n in_node_1 = mathops_10.get_placeholder(\"input_1\")\n #in_node_2 = mathops_8.get_placeholder(\"input_2\")\n #n0 = tf.is_finite(in_node_1)\n #n1 = tf.reduce_all(n0)\n #n2 = tf.cast(n0, dtype=tf.float64)\n #n3 = tf.cast(n1, dtype=tf.float64)\n n4 = tf.add(in_node_1, in_node_1)\n #n5 = tf.cast(tf.truncatediv(tf.cast(n4, dtype=tf.int32), 3), dtype=tf.float64)\n n6 = tf.reciprocal(n4) # should be inf now\n #n7 = tf.cast(tf.is_inf(n6), dtype=tf.float64)\n #n8 = tf.cast(tf.is_nan(n6), dtype=tf.float64)\n n9 = tf.squared_difference(n4, n6)\n w = tf.Variable(tf.random_normal([4, 3], dtype=tf.float64), name=\"w\")\n n10 = tf.reverse(w, axis=[-1])\n n11 = tf.add(n10, n9)\n #n12 = tf.reciprocal(tf.multiply(n11, [[0, 1, 1], [1, 1, 1], [0, 1, 0], [1, 0, 0]]))\n #n13 = tf.reduce_any(tf.is_inf(n12))\n #n14 = tf.cast(n13, dtype=tf.float64)\n\n out_node = tf.identity(n11, name=\"output\")\n placeholders = [in_node_1]\n predictions = [out_node]\n # Run and persist\n tfp = TensorFlowPersistor(save_dir=\"g_11\")\n predictions_after_freeze = tfp.set_placeholders(placeholders) \\\n .set_output_tensors(predictions) \\\n .set_test_data(mathops_10.get_test_data()) \\\n .build_save_frozen_graph()\n print(predictions_after_freeze[0].shape)\n\n\nif __name__ == '__main__':\n test_mathops_ten()\n","sub_path":"import-tests/tests/OLD/mathops/test_g_11.py","file_name":"test_g_11.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"156458869","text":"## Modules\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport math\r\n\r\nfrom newton import Newton_Raphson\r\n\r\n### Computation of the Lagrangian points\r\n\r\n## Force vectors\r\n\r\n# Creates an elastic force vector\r\n#\r\n# @param X the point where the force is applied\r\n# @param G The spring's base point\r\n# @param k the spring constant\r\n# @return The force vector\r\n#\r\ndef elastic_force(X,G,k):\r\n dX = np.array([X[0] - G[0], X[1] - G[1]])\r\n return np.array([-k*i for i in dX])\r\n\r\n# Creates a centrifugal force vector\r\n#\r\n# @param X the point where the force is applied\r\n# @param G The center of the force\r\n# @param k the intensity constant\r\n# @return The force vector\r\n#\r\ndef centrifugal_force(X,G,k):\r\n return np.array([k*(X[0]-G[0]), k*(X[1]-G[1])])\r\n\r\n# Creates a gravitational force vector\r\n#\r\n# @param X the point where the force is applied\r\n# @param G The object applying gravity\r\n# @param k the intensity constant\r\n# @return The force vector\r\n#\r\ndef gravitational_force(X,G,k):\r\n d = ((X[0] - G[0])**2 + (X[1] - G[1])**2)**(3/2)\r\n return np.array([-k*(X[0]-G[0])/d, -k*(X[1]-G[1])/d])\r\n\r\n\r\n## Tests\r\n\r\n# Case : two gravitational forces with respective coefficients 1 (resp 0.01)\r\n# originating from [0,0] (resp [1,0])\r\n\r\n# Returns a system force (one huge and one tiny objects orbitating)\r\n#\r\n# @param U the position of the object\r\n# @return The force vector applied to this object\r\n#\r\ndef test__force(U):\r\n F = gravitational_force(U, np.array([0,0]), 1)\r\n F += gravitational_force(U, np.array([1,0]), 0.01)\r\n F += centrifugal_force(U, np.array([0.01, 0]), 1)\r\n return F\r\n\r\n# Returns the Jacobian matrix of the system force defined above\r\n#\r\n# @param U the position of the object\r\n# @return the Jacobian matrix applied to the vector\r\n#\r\ndef test__jacob(U):\r\n dF = np.zeros((2,2))\r\n x,y = U[0], U[1]\r\n\r\n dF[0,0] = 1 - ((x**2 + y**2)**(3/2) - 3*(x**2)*((x**2 + y**2)**(1/2))) / ((x**2 + y**2)**3)\r\n dF[0,0] -= 0.01*(((x-1)**2+y**2)**(3/2) - 3*((x-1)**2)*(((x-1)**2+y**2)**(1/2))) / (((x-1)**2 + y**2)**3)\r\n\r\n dF[0,1] = -(-3*x*y*((x**2 + y**2)**(1/2))) / ((x**2 + y**2)**3)\r\n dF[0,1] -= 0.01*(-3*(x-1)*y*(((x-1)**2+y**2)**(1/2))) / (((x-1)**2 + y**2)**3)\r\n\r\n dF[1,0] = (3*x*y*((x**2 + y**2)**(1/2))) / ((x**2 + y**2)**3)\r\n dF[1,0] += 0.01*(3*(x-1)*y*(((x-1)**2+y**2)**(1/2))) / (((x-1)**2 + y**2)**3)\r\n\r\n dF[1,1] = 1 - ((x**2 + y**2)**(3/2) - 3*(y**2)*((x**2 + y**2)**(1/2))) / ((x**2 + y**2)**3)\r\n dF[1,1] -= 0.01*(((x-1)**2+y**2)**(3/2) - 3*(y**2)*(((x-1)**2+y**2)**(1/2))) / (((x-1)**2 + y**2)**3)\r\n\r\n return dF\r\n\r\n# Tries to compute the 5 Lagrangian Points\r\n#\r\ndef test__lagrangian_points():\r\n # Trying different starting points in a grid, to reach the maximum of points\r\n Axis = [k*0.4 for k in range(-20,20)]\r\n Ulist = [np.array([i, j]) for i in Axis for j in Axis]\r\n Ufound, Points = [], []\r\n\r\n for i in range(len(Ulist)):\r\n U = Newton_Raphson(test__force, test__jacob, Ulist[i], 100000, 10**-12, True, False)\r\n Ufound.append(U)\r\n\r\n # Gathering close points together\r\n if(len(Points) == 0):\r\n Points.append(Ufound[i])\r\n new = True\r\n for k in range(len(Points)):\r\n if np.allclose(Points[k],Ufound[i], rtol=1e-2):\r\n new = False\r\n if(new and not np.allclose(Ufound[i], np.array([0,0])) and not np.allclose(Ufound[i], np.array([1,0]))):\r\n Points.append(Ufound[i])\r\n\r\n # Verifying all 5 points have been found\r\n assert(len(Points) == 5)\r\n\r\n # Verifying the points are correct\r\n assert(np.allclose(Points[0], np.array([-1,0]), rtol=1e-2))\r\n assert(np.allclose(Points[1], np.array([0.5,-math.sin(math.pi/3)]), rtol=1e-2))\r\n assert(np.allclose(Points[2], np.array([0.5,math.sin(math.pi/3)]), rtol=1e-2))\r\n assert(np.allclose(Points[3], np.array([0.86,0]), rtol=1e-2))\r\n assert(np.allclose(Points[4], np.array([1.16,0]), rtol=1e-2))\r\n\r\n # Scattering points\r\n # Black dots : lagrangian points\r\n for L in Points:\r\n plt.scatter(L[0],L[1], c = \"black\")\r\n # Orange diamond : massive celestial object\r\n plt.scatter(0, 0, c = \"orange\", marker = 'D')\r\n # Gray square : smaller celestial object\r\n plt.scatter(1, 0, c = \"gray\", marker = 's')\r\n\r\n plt.xlabel(\"x\")\r\n plt.ylabel(\"y\")\r\n plt.show()\r\n\r\n print(\"Lagrangian points found :\")\r\n return Points\r\n\r\n# Graphs where each point in a grid leads with a color\r\n#\r\ndef test__lagrangian_fields():\r\n # Trying different starting points in a grid, to reach the maximum of points\r\n Axis = [k*0.025 for k in range(-80,80)]\r\n Ulist = [np.array([i, j]) for i in Axis for j in Axis]\r\n Ufound, Points = [], []\r\n\r\n At_Fields = [[[0,0,0] for k in range(160)] for j in range(160)]\r\n\r\n for i in range(len(Ulist)):\r\n U = Newton_Raphson(test__force, test__jacob, Ulist[i], 10000, 10**-12, True, False)\r\n Ufound.append(U)\r\n\r\n # Gathering close points together\r\n if(len(Points) == 0):\r\n Points.append(Ufound[i])\r\n new = True\r\n for k in range(len(Points)):\r\n if np.allclose(Points[k],Ufound[i], rtol=1e-2):\r\n new = False\r\n if(new and not np.allclose(Ufound[i], np.array([0,0])) and not np.allclose(Ufound[i], np.array([1,0]))):\r\n Points.append(Ufound[i])\r\n\r\n # Applying a color to all starting positions relatively to their destination\r\n if(np.allclose(Ufound[i], Points[0])):\r\n c = [128,0,128]\r\n if(len(Points) > 1):\r\n if(np.allclose(Ufound[i], Points[1])):\r\n c = [0,255,128]\r\n if(len(Points) > 2):\r\n if(np.allclose(Ufound[i], Points[2])):\r\n c = [0,128,255]\r\n if(len(Points) > 3):\r\n if(np.allclose(Ufound[i], Points[3])):\r\n c = [255,128,0]\r\n if(len(Points) > 4):\r\n if(np.allclose(Ufound[i], Points[4])):\r\n c = [255,0,128]\r\n At_Fields[i%160][i//160] = c\r\n\r\n plt.imshow(At_Fields)\r\n\r\n # Verifying all 5 points have been found\r\n assert(len(Points) == 5)\r\n\r\n plt.xlabel(\"x (0,0 is at the center)\")\r\n plt.ylabel(\"y\")\r\n plt.show()\r\n\r\n return\r\n\r\n# Test function to verify if test__jacob and test__force are correct\r\n#\r\ndef test__force_n_jacob():\r\n U0 = np.array([1.5, 0])\r\n assert(np.allclose(test__force(U0), np.array([1.00565457, 0]), rtol=1e-03))\r\n assert(np.allclose(test__jacob(U0), np.array([[1.75259259, 0],[0, 0.6237037]])))\r\n return \"Force and Jacobian are correct\"\r\n\r\n\r\n## Main\r\n\r\nif __name__ == '__main__':\r\n print(test__force_n_jacob())\r\n\r\n # Use only one of the following at a time :\r\n print(test__lagrangian_points())\r\n #print(test__lagrangian_fields())","sub_path":"code/lagrangian_points.py","file_name":"lagrangian_points.py","file_ext":"py","file_size_in_byte":6747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"494363357","text":"# -*- coding: utf-8 -*-\n\nimport copy\n\nfrom bson.errors import InvalidId\nfrom django import forms\nfrom django.core.validators import EMPTY_VALUES\nfrom django.forms.fields import ChoiceField\nfrom django.forms.models import (\n ModelChoiceIterator, ModelChoiceField, ModelMultipleChoiceField)\nfrom django.utils.encoding import smart_str\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.core.exceptions import ValidationError\n\n\nclass MongoCharField(forms.CharField):\n def to_python(self, value):\n if value in EMPTY_VALUES:\n return None\n return smart_str(value)\n\n\nclass DocumentChoiceIterator(ModelChoiceIterator):\n\n def __iter__(self):\n if self.field.empty_label is not None:\n yield (\"\", self.field.empty_label)\n\n queryset = self.queryset.all()\n for obj in queryset:\n yield self.choice(obj)\n\n\nclass DocumentChoiceField(ModelChoiceField):\n def _get_choices(self):\n if hasattr(self, '_choices'):\n return self._choices\n\n return DocumentChoiceIterator(self)\n\n choices = property(_get_choices, ChoiceField._set_choices)\n\n def prepare_value(self, value):\n if hasattr(value, '_meta'):\n if self.to_field_name:\n return value.serializable_value(self.to_field_name)\n else:\n return value.id.hex\n\n return value\n\n\nclass DocumentMultipleChoiceField(\n ModelMultipleChoiceField, DocumentChoiceField):\n\n def _check_values(self, value):\n key = self.to_field_name or 'id'\n try:\n value = frozenset(value)\n except TypeError:\n # list of lists isn't hashable, for example\n raise ValidationError(\n self.error_messages['list'],\n code='list')\n\n for pk in value:\n try:\n self.queryset.filter(**{key: pk})\n except (ValueError, TypeError):\n raise ValidationError(\n self.error_messages['invalid_pk_value'],\n code='invalid_pk_value',\n params={'pk': pk})\n\n qs = self.queryset.filter(**{'%s__in' % key: value}).only(key)\n pks = {\n getattr(o, key).hex if key == \"id\" else getattr(o, key)\n for o in qs\n }\n\n for val in value:\n if val in pks:\n continue\n\n raise ValidationError(\n self.error_messages['invalid_choice'],\n code='invalid_choice',\n params={'value': val})\n\n return qs\n","sub_path":"mongodbforms/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"242906055","text":"__author__ = 'Benji'\n\n#############################################################################\n# #\n# Generic lexer that takes a set of regex and corresponding #\n# tags. #\n# #\n# If a match is found, the matching text is converted into #\n# a token, along with its tag. #\n# If the regex's tag is None (e.g. whitespace), it is discarded #\n# Otherwise, there exists no matching regex, so we report an #\n# error #\n# #\n#############################################################################\n\nfrom re import compile\n\n\ndef lex(chars, regex_tokens, logger):\n tokens = list()\n position = 0\n iter_size = len(chars)\n\n while position < iter_size:\n regex_match = None\n\n for regex_token in regex_tokens:\n regex, tag = regex_token\n\n regex_compiled = compile(regex)\n regex_match = regex_compiled.match(chars, position)\n\n if regex_match:\n partner = regex_match.group(0)\n\n if tag is not None:\n token = (partner, tag)\n tokens.append(token)\n\n break\n\n if regex_match is None:\n logger.error(\"Illegal character: {} (ASCII={})\".format(chars[position], ord(chars[position])))\n\n else:\n position = regex_match.end(0)\n\n return tokens\n","sub_path":"lexer.py","file_name":"lexer.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"302276949","text":"Player={\"Name\":\"Messi\",\"Position\":[\"SS\",\"RW\",\"CF\"],\"Jersey No\":10}\nPlayer[\"Goals\"]=48\nPlayer[\"Assists\"]=18\nGA=0\n\nfor key in Player:\n\tprint(key,\":\",Player[key])\n\tif key==\"Goals\" or key==\"Assists\":\n\t\tGA+=Player[key]\n\nprint(\"G+A:\",GA)","sub_path":"Basics/6)Dictionaries.py","file_name":"6)Dictionaries.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"612046401","text":"import numpy as np\nimport scipy.interpolate\nimport matplotlib.pyplot as plt\nfrom taco_vis import FLOW\n#Read in Cox et al. (2013) dataset\ndata_file = './cox_etal_2013.txt' #Data file\ndata = np.genfromtxt(data_file,delimiter=',')\n\n#Regrid the data down (too high resolution to be practically plotted as is)\nr , t = np.linspace(0,1,data.shape[0]), np.linspace(0,1,data.shape[1])\ntime, radius = np.linspace(0,1,2000) , np.linspace(0,1,16)\nfunc = scipy.interpolate.RectBivariateSpline(r,t,data)\nu = func(radius,time)\n\n#Initialise FLOW class\nf = FLOW(u)\n\n#Up the speed of texture advection\nf.speed = 5\n\n#Animate\nf.image_filename = 'myplot.png'\nf.plot_cylinders(animate=False, save=True, time_idx=0)\nf.plot_cylinders_3D(animate=False, save=True, time_idx=0)\n","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"76770950","text":"\nclass BinaryTree(object):\n def __init__(self, value = None):\n self.value = value\n self.left = None\n self.right = None\n\n def _is_parent(node):\n return bool(node.left or node.right)\n\n def _is_interior(self, node):\n return (not node == self.root) and self.is_parent(node)\n\n def _is_leaf(self, node):\n return (not node == self.root) and not self.is_interior(node)\n \n \n\n\n def insert_left(self, node):\n if self.left == None:\n self.left = BinaryTree(node)\n else:\n new = BinaryTree(node)\n new.left = self.left\n self.left = new\n \n def insert_right(self, node):\n if self.right == None:\n self.right = BinaryTree(node)\n else:\n new = BinaryTree(node)\n new.right = self.right\n self.right = new\n\n def depth(self, node):\n if not node:\n return 0\n return max(self.depth(node.left), self.depth(node.right)) + 1\n\n def is_balanced(self, node):\n if not node:\n return True\n \n left_height = self.depth(node.left)\n right_height = self.depth(node.right)\n \n if (abs(right_height - left_height) <= 1\n and self.is_balanced(node.left)\n and self.is_balanced(node.right)):\n return True\n return False \n \n\ntree = BinaryTree('a')\ntree.insert_left('b')\ntree.insert_left('e')\ntree.insert_left('f')\ntree.insert_left('g')\ntree.insert_right('c')\n\ndict.fromkeys\ndef preorder(tree):\n if tree:\n print(tree.key)\n preorder(tree.left)\n preorder(tree.right)\n\ndef postorder(tree):\n if tree:\n postorder(tree.left)\n postorder(tree.right)\n print(tree.key)\n\ndef num_nodes(tree):\n if tree is None:\n return 0\n if tree:\n return 1 + num_nodes(tree.left) + num_nodes(tree.right)\n\nprint(tree.is_balanced(tree))\nprint(num_nodes(tree))\n\n","sub_path":"src/graphs/trees/binary_tree.py","file_name":"binary_tree.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}